diff --git a/app.js b/app.js index 1c17206ae..f2fe450b8 100755 --- a/app.js +++ b/app.js @@ -18,31 +18,31 @@ var group = require('./controllers/group'); var discussion = require('./controllers/discussion'); var issue = require('./controllers/issue'); var scriptStorage = require('./controllers/scriptStorage'); -var statusCodePage = require('./libs/templateHelpers').statusCodePage; - -var modelParser = require('./libs/modelParser'); +var statusCodePage = require('./libs/templateHelpers').statusCodePage; var modifySessions = require('./libs/modifySessions'); + var settings = require('./models/settings.json'); + var connectStr = process.env.CONNECT_STRING || settings.connect; var sessionSecret = process.env.SESSION_SECRET || settings.secret; var db = mongoose.connection; -var dbOptions = { server : { socketOptions : { keepAlive: 1 } } }; +var dbOptions = { server: { socketOptions: { keepAlive: 1 } } }; app.set('port', process.env.PORT || 8080); // Connect to the database mongoose.connect(connectStr, dbOptions); db.on('error', console.error.bind(console, 'connection error:')); -db.once('open', function () { +db.once('open', function() { app.listen(app.get('port')); }); -app.configure(function(){ +app.configure(function() { var sessionStore = new MongoStore({ mongoose_connection: db }); // See https://hacks.mozilla.org/2013/01/building-a-node-js-server-that-wont-melt-a-node-js-holiday-season-part-5/ - app.use(function (req, res, next) { + app.use(function(req, res, next) { // check if we're toobusy if (toobusy()) { statusCodePage(req, res, next, { @@ -56,13 +56,12 @@ app.configure(function(){ // Force HTTPS if (app.get('port') === 443) { - app.use(function (req, res, next) { + app.use(function(req, res, next) { res.setHeader('Strict-Transport-Security', 'max-age=8640000; includeSubDomains'); if (req.headers['x-forwarded-proto'] !== 'https') { - return res.redirect(301, 'https://' + req.headers.host - + encodeURI(req.url)); + return res.redirect(301, 'https://' + req.headers.host + encodeURI(req.url)); } next(); @@ -96,7 +95,7 @@ app.configure(function(){ }); // Build the route regex for model lists -function listRegex (root, type) { +function listRegex(root, type) { var slash = '\/'; if (root === slash) { slash = ''; } return new RegExp('^' + root + @@ -115,7 +114,7 @@ function app_route(path) { r.all = function(cb) { app.all.call(app, path, cb); }; - methods.forEach(function(method){ + methods.forEach(function(method) { r[method] = function(cb) { app[method].call(app, path, cb); return r; @@ -153,7 +152,6 @@ app_route('/user/add/lib/new').get(script.lib(user.editScript)).post(script.lib( app_route('/user/add/scripts/upload').post(user.uploadScript); app_route('/user/add/lib/upload').post(script.lib(user.uploadScript)); - // Script routes app_route('/scripts/:username/:namespace?/:scriptname').get(script.view); app_route('/script/:username/:namespace?/:scriptname/edit').get(script.edit).post(script.edit); @@ -165,7 +163,7 @@ app.get('/install/:username/:namespace?/:scriptname', scriptStorage.sendScript); app.get('/meta/:username/:namespace?/:scriptname', scriptStorage.sendMeta); app.get('/vote/scripts/:username/:namespace?/:scriptname/:vote', script.vote); app.post('/github/hook', scriptStorage.webhook); -app.post('/github/service', function (req, res, next) { next(); }); +app.post('/github/service', function(req, res, next) { next(); }); // Library routes app.get(listRegex('\/toolbox', 'lib'), main.toolbox); @@ -180,7 +178,7 @@ app.get('/vote/libs/:username/:scriptname/:vote', script.lib(script.vote)); // Issues routes app_route('/:type(scripts|libs)/:username/:namespace?/:scriptname/issues/:open(closed)?').get(issue.list); -// app_route('/:type(scripts|libs)/:username/:namespace?/:scriptname/issues/:topic').get(issue.view); +//app_route('/:type(scripts|libs)/:username/:namespace?/:scriptname/issues/:topic').get(issue.view); app_route('/:type(scripts|libs)/:username/:namespace?/:scriptname/issue/new').get(issue.open).post(issue.open); app_route('/:type(scripts|libs)/:username/:namespace?/:scriptname/issues/:topic').get(issue.view); @@ -201,9 +199,8 @@ app_route('/mod/removed').get(moderation.removedItemListPage); app_route('/mod/removed/:id').get(moderation.removedItemPage); app.get('/flag/users/:username/:unflag?', user.flag); app.get('/flag/scripts/:username/:namespace?/:scriptname/:unflag?', script.flag); -app.get('/flag/libs/:username/:scriptname/:unflag?', script.lib(script.flag)); // -app.get(listRegex('\/flagged(?:\/([^\/]+?))?', 'user|script'), - moderation.flagged); // +app.get('/flag/libs/:username/:scriptname/:unflag?', script.lib(script.flag)); +app.get(listRegex('\/flagged(?:\/([^\/]+?))?', 'user|script'), moderation.flagged); app.get(listRegex('\/graveyard(?:\/([^\/]+?))?', ''), moderation.graveyard); app.get(/^\/remove\/(.+?)\/(.+)$/, remove.rm); @@ -237,10 +234,9 @@ app.get(listRegex('\/', 'script'), main.home); // Fallback routes app.use(express.static(__dirname + '/public')); -app.use(function (req, res, next) { +app.use(function(req, res, next) { statusCodePage(req, res, next, { statusCode: 404, statusMessage: 'This is not the page you\'re are looking for.', }); }); - diff --git a/controllers/_template.js b/controllers/_template.js index 42f414084..399492681 100644 --- a/controllers/_template.js +++ b/controllers/_template.js @@ -16,9 +16,8 @@ var modelQuery = require('../libs/modelQuery'); // Generate a bootstrap3 pagination widget. var getDefaultPagination = require('../libs/templateHelpers').getDefaultPagination; - //--- Views -exports.example = function (req, res, next) { +exports.example = function(req, res, next) { var authedUser = req.session.user; // @@ -38,16 +37,15 @@ exports.example = function (req, res, next) { options.pageMetaKeywords = pageMetaKeywords.join(', '); //--- Tasks - // ... //--- - function preRender(){}; - function render(){ res.render('pages/_templatePage', options); } - function asyncComplete(){ preRender(); render(); } + function preRender() { }; + function render() { res.render('pages/_templatePage', options); } + function asyncComplete() { preRender(); render(); } async.parallel(tasks, asyncComplete); }; -exports.example = function (req, res, next) { +exports.example = function(req, res, next) { var authedUser = req.session.user; // @@ -70,17 +68,16 @@ exports.example = function (req, res, next) { var scriptListQuery = Script.find(); // Scripts: Query: isLib=false - scriptListQuery.find({isLib: false}); + scriptListQuery.find({ isLib: false }); // Scripts: Query: Search if (req.query.q) modelQuery.parseScriptSearchQuery(scriptListQuery, req.query.q); // Scripts: Query: Sort - modelQuery.parseModelListSort(scriptListQuery, req.query.orderBy, req.query.orderDir, function(){ + modelQuery.parseModelListSort(scriptListQuery, req.query.orderBy, req.query.orderDir, function() { scriptListQuery.sort('-rating -installs -updated'); }); - // Pagination var pagination = getDefaultPagination(req); @@ -90,10 +87,10 @@ exports.example = function (req, res, next) { // Pagination tasks.push(pagination.getCountTask(scriptListQuery)); - + // Scripts - tasks.push(function (callback) { - scriptListQuery.exec(function(err, scriptDataList){ + tasks.push(function(callback) { + scriptListQuery.exec(function(err, scriptDataList) { if (err) { callback(); } else { @@ -104,12 +101,12 @@ exports.example = function (req, res, next) { }); //--- - function preRender(){ + function preRender() { // Pagination options.paginationRendered = pagination.renderDefault(req); }; - function render(){ res.render('pages/_templatePage', options); } - function asyncComplete(){ preRender(); render(); } + function render() { res.render('pages/_templatePage', options); } + function asyncComplete() { preRender(); render(); } async.parallel(tasks, asyncComplete); }; diff --git a/controllers/admin.js b/controllers/admin.js index c513149ac..d433c617c 100644 --- a/controllers/admin.js +++ b/controllers/admin.js @@ -34,7 +34,11 @@ function getOAuthStrategies(stored) { strategy = strategies[type]; if (strategy.oauth) { oAuthStrats.push(stored[type] || - nil({ 'strat' : type, 'id' : '', 'key' : ''})); + nil({ + 'strat': type, + 'id': '', + 'key': '' + })); } } @@ -42,28 +46,34 @@ function getOAuthStrategies(stored) { } // Allow admins to set user roles and delete users -exports.userAdmin = function (req, res, next) { +exports.userAdmin = function(req, res, next) { var options = nil(); var thisUser = req.session.user; if (!userIsAdmin(req)) { return next(); } // You can only see users with a role less than yours - User.find({ role : { $gt: thisUser.role } }, function (err, users) { + User.find({ role: { $gt: thisUser.role } }, function(err, users) { var i = 0; options.users = []; - users.forEach(function (user) { + users.forEach(function(user) { var roles = []; - userRoles.forEach(function (role, index) { - roles.push({ 'val' : index, 'display' : role, - 'selected' : index === user.role }); + userRoles.forEach(function(role, index) { + roles.push({ + 'val': index, + 'display': role, + 'selected': index === user.role + }); }); roles = roles.splice(thisUser.role + 1); roles.reverse(); - options.users.push({ 'id' : user._id, 'name' : user.name, - 'roles' : roles }); + options.users.push({ + 'id': user._id, + 'name': user.name, + 'roles': roles + }); }); res.render('userAdmin', options); @@ -72,23 +82,25 @@ exports.userAdmin = function (req, res, next) { // View everything about a particular user // This is mostly for debugging in production -exports.adminUserView = function (req, res, next) { +exports.adminUserView = function(req, res, next) { var id = req.route.params.id; var thisUser = req.session.user; if (!userIsAdmin(req)) { return next(); } // Nothing fancy, just the stringified user object - User.findOne({ '_id' : id, role : { $gt: thisUser.role } }, - function (err, user) { + User.findOne({ '_id': id, role: { $gt: thisUser.role } }, + function(err, user) { if (err || !user) { return next(); } - res.render('userAdmin', { user: { - info: JSON.stringify(user.toObject(), null, ' ') } }); - }); + res.render('userAdmin', { + user: { + info: JSON.stringify(user.toObject(), null, ' ') + } + }); + }); }; - var jsonModelMap = { 'User': User, 'Script': Script, @@ -96,11 +108,11 @@ var jsonModelMap = { 'Discussion': Discussion, 'Comment': Comment, 'Vote': Vote, - 'Flag': Flag, + 'Flag': Flag }; // View everything about a particular user // This is mostly for debugging in production -exports.adminJsonView = function (req, res, next) { +exports.adminJsonView = function(req, res, next) { var authedUser = req.session.user; var modelname = req.query.model; @@ -115,32 +127,31 @@ exports.adminJsonView = function (req, res, next) { options.isAdmin = authedUser && authedUser.isAdmin; if (!options.isAdmin) - return res.send(403, {status: 403, message: 'Not an admin.'}); - + return res.send(403, { status: 403, message: 'Not an admin.' }); var model = jsonModelMap[modelname]; if (!model) - return res.send(400, {status: 400, message: 'Invalid model.'}); + return res.send(400, { status: 400, message: 'Invalid model.' }); model.findOne({ _id: id - }, function(err, obj){ + }, function(err, obj) { if (err || !obj) - return res.send(404, {status: 404, message: 'Id doesn\'t exist.'}); + return res.send(404, { status: 404, message: 'Id doesn\'t exist.' }); res.json(obj); }); }; // Make changes to users listed -exports.adminUserUpdate = function (req, res, next) { +exports.adminUserUpdate = function(req, res, next) { var authedUser = req.session.user; var username = req.route.params.username; User.findOne({ name: username - }, function (err, userData) { + }, function(err, userData) { if (err || !userData) { return next(); } // @@ -185,7 +196,7 @@ exports.adminUserUpdate = function (req, res, next) { } // Make sure the change is reflected in the session store - updateSessions(req, userData, function (err, sess) { + updateSessions(req, userData, function(err, sess) { res.redirect(user.userPageUrl); }); }); @@ -193,7 +204,7 @@ exports.adminUserUpdate = function (req, res, next) { }; // Landing Page for admins -exports.adminPage = function (req, res, next) { +exports.adminPage = function(req, res, next) { var authedUser = req.session.user; // @@ -218,14 +229,14 @@ exports.adminPage = function (req, res, next) { options.pageMetaKeywords = null; //--- - async.parallel(tasks, function(err){ + async.parallel(tasks, function(err) { if (err) return next(); res.render('pages/adminPage', options); }); }; // This page allows admins to set oAuth keys for the available authenticators -exports.adminApiKeysPage = function (req, res, next) { +exports.adminApiKeysPage = function(req, res, next) { var authedUser = req.session.user; // @@ -252,12 +263,12 @@ exports.adminApiKeysPage = function (req, res, next) { //--- Tasks // strategyListQuery - tasks.push(function(callback){ - Strategy.find({}, function (err, strats) { + tasks.push(function(callback) { + Strategy.find({}, function(err, strats) { var stored = nil(); var strategies = null; - strats.forEach(function (strat) { + strats.forEach(function(strat) { stored[strat.name] = { strat: strat.name, id: strat.id, @@ -273,7 +284,7 @@ exports.adminApiKeysPage = function (req, res, next) { }); //--- - async.parallel(tasks, function(err){ + async.parallel(tasks, function(err) { if (err) return next(); res.render('pages/adminApiKeysPage', options); }); @@ -282,30 +293,30 @@ exports.adminApiKeysPage = function (req, res, next) { // Manage oAuth strategies without having to restart the server // When new keys are added, we load the new strategy // When keys are removed, we remove the strategy -exports.apiAdminUpdate = function (req, res, next) { +exports.apiAdminUpdate = function(req, res, next) { var postStrats = null; if (!userIsAdmin(req)) { return next(); } - postStrats = Object.keys(req.body).map(function (postStrat) { + postStrats = Object.keys(req.body).map(function(postStrat) { var values = req.body[postStrat]; return { name: postStrat, id: values[0], key: values[1] } }); - Strategy.find({}, function (err, strats) { + Strategy.find({}, function(err, strats) { var stored = nil(); strats.forEach(function(strat) { stored[strat.name] = strat; }); - async.each(postStrats, function (postStrat, cb) { + async.each(postStrats, function(postStrat, cb) { var strategy = null; var name = postStrat.name; var id = postStrat.id; var key = postStrat.key; if (stored[name] && !id && !key) { - stored[name].remove(function () { + stored[name].remove(function() { delete strategyInstances[name]; cb(); }); @@ -317,22 +328,21 @@ exports.apiAdminUpdate = function (req, res, next) { strategy.key = key; } else { strategy = new Strategy({ - 'id' : id, - 'key' : key, - 'name' : name, - 'display' : strategies[name].name + 'id': id, + 'key': key, + 'name': name, + 'display': strategies[name].name }); } - - return strategy.save(function (err, strategy) { + return strategy.save(function(err, strategy) { loadPassport(strategy); cb(); }); } cb(); - }, function (err) { + }, function(err) { res.redirect('/admin/api'); }); }); diff --git a/controllers/auth.js b/controllers/auth.js index a112e227e..3d15fe3a7 100644 --- a/controllers/auth.js +++ b/controllers/auth.js @@ -10,29 +10,29 @@ var cleanFilename = require('../libs/helpers').cleanFilename; var addSession = require('../libs/modifySessions').add; // Unused but removing it breaks passport -passport.serializeUser(function (user, done) { +passport.serializeUser(function(user, done) { done(null, user._id); }); // Setup all our auth strategies var openIdStrategies = {}; -Strategy.find({}, function (err, strategies) { +Strategy.find({}, function(err, strategies) { // Get OpenId strategies for (var name in allStrategies) { if (!allStrategies[name].oauth) { openIdStrategies[name] = true; - strategies.push({ 'name' : name, 'openid' : true }); + strategies.push({ 'name': name, 'openid': true }); } } // Load the passport module for each strategy - strategies.forEach(function (strategy) { + strategies.forEach(function(strategy) { loadPassport(strategy); }); }); -exports.auth = function (req, res, next) { +exports.auth = function(req, res, next) { var user = req.session.user; var strategy = req.body.auth || req.route.params.strategy; var username = req.body.username || req.session.username; @@ -68,8 +68,8 @@ exports.auth = function (req, res, next) { req.session.username = username; } - User.findOne({ name : { $regex : new RegExp('^' + username + '$', 'i') } }, - function (err, user) { + User.findOne({ name: { $regex: new RegExp('^' + username + '$', 'i') } }, + function(err, user) { var strategies = null; var strat = null; @@ -93,10 +93,10 @@ exports.auth = function (req, res, next) { } else { return auth(); } - }); + }); }; -exports.callback = function (req, res, next) { +exports.callback = function(req, res, next) { var strategy = req.route.params.strategy; var username = req.session.username; var newstrategy = req.session.newstrategy; @@ -109,55 +109,53 @@ exports.callback = function (req, res, next) { // Get the passport strategy instance so we can alter the _verfiy method strategyInstance = strategyInstances[strategy]; - // Hijak the private verify method so we can fuck shit up freely // We use this library for things it was never intended to do if (openIdStrategies[strategy]) { - strategyInstance._verify = function (id, done) { + strategyInstance._verify = function(id, done) { verifyPassport(id, strategy, username, req.session.user, done); } } else { strategyInstance._verify = - function (token, refreshOrSecretToken, profile, done) { + function(token, refreshOrSecretToken, profile, done) { req.session.profile = profile; verifyPassport(profile.id, strategy, username, req.session.user, done); } } // This callback will happen after the verify routine - var authenticate = passport.authenticate(strategy, - function (err, user, info) { + var authenticate = passport.authenticate(strategy, function(err, user, info) { + if (err) { return next(err); } + if (!user) { + return res.redirect(doneUrl + (doneUrl === '/' ? 'register' : '') + + '?authfail'); + } + + req.logIn(user, function(err) { if (err) { return next(err); } - if (!user) { - return res.redirect(doneUrl + (doneUrl === '/' ? 'register' : '') - + '?authfail'); - } - req.logIn(user, function(err) { - if (err) { return next(err); } + // Store the user info in the session + req.session.user = user; - // Store the user info in the session - req.session.user = user; + // Save the session id on the user model + user.sessionId = req.sessionID; - // Save the session id on the user model - user.sessionId = req.sessionID; + // Save GitHub username. + if (req.session.profile && req.session.profile.provider === 'github') { + user.ghUsername = req.session.profile.username; + } - // Save GitHub username. - if (req.session.profile && req.session.profile.provider === 'github') { - user.ghUsername = req.session.profile.username; + addSession(req, user, function() { + if (newstrategy) { + // Allow a user to link to another acount + return res.redirect('/auth/' + newstrategy); + } else { + // Delete the username that was temporarily stored + delete req.session.username; + return res.redirect(doneUrl); } - - addSession(req, user, function () { - if (newstrategy) { - // Allow a user to link to another acount - return res.redirect('/auth/' + newstrategy); - } else { - // Delete the username that was temporarily stored - delete req.session.username; - return res.redirect(doneUrl); - } - }); }); + }); }); authenticate(req, res, next); diff --git a/controllers/discussion.js b/controllers/discussion.js index 0358a13bb..6328f73a1 100644 --- a/controllers/discussion.js +++ b/controllers/discussion.js @@ -15,7 +15,7 @@ var categories = [ slug: 'announcements', name: 'Announcements', description: 'UserScripts News (OpenUserJS, GreaseMonkey, etc)', - roleReqToPostTopic: 3, // Moderator + roleReqToPostTopic: 3 // Moderator }, { slug: 'garage', @@ -35,7 +35,7 @@ var categories = [ ]; exports.categories = categories; -exports.categoryListPage = function (req, res, next) { +exports.categoryListPage = function(req, res, next) { var authedUser = req.session.user; // @@ -80,8 +80,8 @@ exports.categoryListPage = function (req, res, next) { //--- PreRender // discussionList options.discussionList = _.map(options.discussionList, modelParser.parseDiscussion); - _.map(options.discussionList, function(discussion){ - var category = _.findWhere(categories, {slug: discussion.category}); + _.map(options.discussionList, function(discussion) { + var category = _.findWhere(categories, { slug: discussion.category }); if (!category) { category = { name: discussion.category, @@ -110,12 +110,12 @@ exports.categoryListPage = function (req, res, next) { }; // List discussions for one of the three categories -exports.list = function (req, res, next) { +exports.list = function(req, res, next) { var authedUser = req.session.user; var categorySlug = req.route.params.shift(); - var category = _.findWhere(categories, {slug: categorySlug}); + var category = _.findWhere(categories, { slug: categorySlug }); if (!category) return next(); @@ -141,7 +141,7 @@ exports.list = function (req, res, next) { var discussionListQuery = Discussion.find(); // discussionListQuery: category - discussionListQuery.find({category: category.slug}); + discussionListQuery.find({ category: category.slug }); // discussionListQuery: Defaults modelQuery.applyDiscussionListQueryDefaults(discussionListQuery, options, req); @@ -174,7 +174,7 @@ exports.list = function (req, res, next) { }; // Locate a discussion and deal with topic url collisions -function findDiscussion (category, topicUrl, callback) { +function findDiscussion(category, topicUrl, callback) { // To prevent collisions we add an incrementing id to the topic url var topic = /(.+?)(?:_(\d+))?$/.exec(topicUrl); var query = { path: '/' + category + '/' + topic[1] }; @@ -184,7 +184,7 @@ function findDiscussion (category, topicUrl, callback) { query.duplicateId = Number(topic[2]); } - Discussion.findOne(query, function (err, discussion) { + Discussion.findOne(query, function(err, discussion) { if (err || !discussion) { return callback(null); } callback(discussion); }); @@ -192,17 +192,17 @@ function findDiscussion (category, topicUrl, callback) { exports.findDiscussion = findDiscussion; // List comments in a discussion -exports.show = function (req, res, next) { +exports.show = function(req, res, next) { var authedUser = req.session.user; var categorySlug = req.route.params.shift(); var topic = req.route.params.shift(); - var category = _.findWhere(categories, {slug: categorySlug}); + var category = _.findWhere(categories, { slug: categorySlug }); if (!category) return next(); - findDiscussion(category.slug, topic, function (discussionData) { + findDiscussion(category.slug, topic, function(discussionData) { if (!discussionData) { return next(); } // @@ -229,7 +229,7 @@ exports.show = function (req, res, next) { var commentListQuery = Comment.find(); // commentListQuery: discussion - commentListQuery.find({_discussionId: discussion._id}); + commentListQuery.find({ _discussionId: discussion._id }); // commentListQuery: Defaults modelQuery.applyCommentListQueryDefaults(commentListQuery, options, req); @@ -252,7 +252,7 @@ exports.show = function (req, res, next) { //--- PreRender // commentList options.commentList = _.map(options.commentList, modelParser.parseComment); - _.map(options.commentList, function(comment){ + _.map(options.commentList, function(comment) { comment.author = modelParser.parseUser(comment._authorId); }); _.map(options.commentList, modelParser.renderComment); @@ -267,7 +267,7 @@ exports.show = function (req, res, next) { }; // UI to create a new topic -exports.newTopic = function (req, res, next) { +exports.newTopic = function(req, res, next) { var authedUser = req.session.user; if (!authedUser) @@ -275,7 +275,7 @@ exports.newTopic = function (req, res, next) { var categorySlug = req.route.params.category; - var category = _.findWhere(categories, {slug: categorySlug}); + var category = _.findWhere(categories, { slug: categorySlug }); if (!category) return next(); @@ -307,7 +307,7 @@ exports.newTopic = function (req, res, next) { }; // Does all the work of submitting a new comment and updating the discussion -function postComment (user, discussion, content, creator, callback) { +function postComment(user, discussion, content, creator, callback) { var created = new Date(); var comment = new Comment({ content: content, @@ -322,7 +322,7 @@ function postComment (user, discussion, content, creator, callback) { _authorId: user._id }); - comment.save(function (err, comment) { + comment.save(function(err, comment) { ++discussion.comments; discussion.lastCommentor = user.name; discussion.updated = new Date(); @@ -333,7 +333,7 @@ exports.postComment = postComment; // Does all the work of submitting a new topic and // resolving topic url collisions -function postTopic (user, category, topic, content, issue, callback) { +function postTopic(user, category, topic, content, issue, callback) { var urlTopic = cleanFilename(topic, '').replace(/_\d+$/, ''); var path = '/' + category + '/' + urlTopic; var params = { sort: {} }; @@ -341,7 +341,7 @@ function postTopic (user, category, topic, content, issue, callback) { if (!urlTopic) { callback(null); } - Discussion.findOne({ path: path }, params, function (err, discussion) { + Discussion.findOne({ path: path }, params, function(err, discussion) { var newDiscussion = null; var props = { topic: topic, @@ -372,9 +372,9 @@ function postTopic (user, category, topic, content, issue, callback) { newDiscussion = new Discussion(props); - newDiscussion.save(function (err, discussion) { + newDiscussion.save(function(err, discussion) { // Now post the first comment - postComment(user, discussion, content, true, function (err, discussion) { + postComment(user, discussion, content, true, function(err, discussion) { callback(discussion); }); }); @@ -383,7 +383,7 @@ function postTopic (user, category, topic, content, issue, callback) { exports.postTopic = postTopic; // post route to create a new topic -exports.createTopic = function (req, res, next) { +exports.createTopic = function(req, res, next) { var authedUser = req.session.user; if (!authedUser) @@ -393,7 +393,7 @@ exports.createTopic = function (req, res, next) { var topic = req.body['discussion-topic']; var content = req.body['comment-content']; - var category = _.findWhere(categories, {slug: categorySlug}); + var category = _.findWhere(categories, { slug: categorySlug }); if (!category) return next(); @@ -412,7 +412,7 @@ exports.createTopic = function (req, res, next) { }); } - postTopic(authedUser, category.slug, topic, content, false, function (discussion) { + postTopic(authedUser, category.slug, topic, content, false, function(discussion) { if (!discussion) { return exports.newTopic(req, res, next); } res.redirect(encodeURI(discussion.path @@ -421,7 +421,7 @@ exports.createTopic = function (req, res, next) { }; // post route to create a new comment on an existing discussion -exports.createComment = function (req, res, next) { +exports.createComment = function(req, res, next) { var category = req.route.params.category; var topic = req.route.params.topic; var user = req.session.user; @@ -430,10 +430,10 @@ exports.createComment = function (req, res, next) { if (!user) { return next(); } - findDiscussion(category, topic, function (discussion) { + findDiscussion(category, topic, function(discussion) { if (!discussion) { return next(); } - postComment(user, discussion, content, false, function (err, discussion) { + postComment(user, discussion, content, false, function(err, discussion) { res.redirect(encodeURI(discussion.path + (discussion.duplicateId ? '_' + discussion.duplicateId : ''))); }); diff --git a/controllers/group.js b/controllers/group.js index 720573155..46299ff7b 100644 --- a/controllers/group.js +++ b/controllers/group.js @@ -12,13 +12,13 @@ var getRating = require('../libs/collectiveRating').getRating; var execQueryTask = require('../libs/tasks').execQueryTask; // clean the name of the group so it is url safe -function cleanGroupName (name) { +function cleanGroupName(name) { return cleanFilename(name, '').replace(/_/g, ' ') .replace(/^\s+|\s+$/g, '').replace(/,/g, ''); } // api for the client side javascript select2 library -exports.search = function (req, res) { +exports.search = function(req, res) { var queryStr = ''; var queryRegex = null; var addTerm = req.route.params.addTerm; @@ -31,15 +31,15 @@ exports.search = function (req, res) { return res.end(JSON.stringify([])); } - terms.forEach(function (term) { - queryStr += '(?=.*?' + term + ')'; + terms.forEach(function(term) { + queryStr += '(?=.*?' + term + ')'; }); queryRegex = new RegExp(queryStr, 'i'); - Group.find({ name: queryRegex }, 'name', function (err, groups) { + Group.find({ name: queryRegex }, 'name', function(err, groups) { if (err) { groups = []; } - results = groups.map(function (group) { + results = groups.map(function(group) { return group.name; }); @@ -52,12 +52,12 @@ exports.search = function (req, res) { }; // When the select2 library submits -exports.addScriptToGroups = function (script, groupNames, callback) { +exports.addScriptToGroups = function(script, groupNames, callback) { if (script.isLib || !groupNames || groupNames[0].length === 0) { return script.save(callback); } - Group.find({ name: { $in: groupNames } }, function (err, groups) { + Group.find({ name: { $in: groupNames } }, function(err, groups) { var existingNames = null; var newGroup = null; var tasks = []; @@ -67,23 +67,23 @@ exports.addScriptToGroups = function (script, groupNames, callback) { // Groups to add the script to // This could have been added to the above query but // We need to figure out which groups don't exist as well (see below) - existingGroups = groups.filter(function (group) { + existingGroups = groups.filter(function(group) { return group._scriptIds.indexOf(script._id) === -1; }); // Names of existing groups - existingNames = groups.map(function (group) { - return group.name; + existingNames = groups.map(function(group) { + return group.name; }); // Name of a group that doesn't exist - newGroup = cleanGroupName(groupNames.filter(function (name) { + newGroup = cleanGroupName(groupNames.filter(function(name) { return existingNames.indexOf(name) === -1; }).shift()); // Add script to exising groups - tasks.push(function (cb) { - async.each(existingGroups, function (group, innerCb) { + tasks.push(function(cb) { + async.each(existingGroups, function(group, innerCb) { group._scriptIds.push(script._id); group.update = new Date(); group.save(innerCb); @@ -92,7 +92,7 @@ exports.addScriptToGroups = function (script, groupNames, callback) { // Create a custom group for the script if (!script._groupId && newGroup) { - tasks.push(function (cb) { + tasks.push(function(cb) { var group = new Group({ name: newGroup, rating: 0, @@ -100,33 +100,34 @@ exports.addScriptToGroups = function (script, groupNames, callback) { _scriptIds: [script._id] }); - group.save(function (err, group) { + group.save(function(err, group) { script._groupId = group._id; cb(); }); }); } - async.parallel(tasks, function () { + async.parallel(tasks, function() { script.save(callback); // Update the group ratings in the background - groups.forEach(function (group) { + groups.forEach(function(group) { Script.find({ _id: { $in: group._scriptIds } }, - function (err, scripts) { + function(err, scripts) { if (err || scripts.length < 2) { return; } group.rating = getRating(scripts); group.updated = new Date(); - group.save(function () {}); - }); + group.save(function() { }); + } + ); }); }); }); }; // list groups -exports.list = function (req, res) { +exports.list = function(req, res) { var authedUser = req.session.user; // @@ -170,7 +171,7 @@ exports.list = function (req, res) { tasks.push(execQueryTask(popularGroupListQuery, options, 'popularGroupList')); //--- - function preRender(){ + function preRender() { // groupList options.groupList = _.map(options.groupList, modelParser.parseGroup); @@ -186,8 +187,8 @@ exports.list = function (req, res) { pageMetaKeywords.concat(_.pluck(options.groupList, 'name')); options.pageMetaKeywords = pageMetaKeywords.join(', '); }; - function render(){ res.render('pages/groupListPage', options); } - function asyncComplete(){ preRender(); render(); } + function render() { res.render('pages/groupListPage', options); } + function asyncComplete() { preRender(); render(); } async.parallel(tasks, asyncComplete); }; @@ -208,7 +209,7 @@ var setupGroupSidePanel = function(options) { }; // list the scripts in a group -exports.view = function (req, res, next) { +exports.view = function(req, res, next) { var authedUser = req.session.user; var groupNameSlug = req.route.params.groupname; @@ -216,7 +217,7 @@ exports.view = function (req, res, next) { Group.findOne({ name: groupName - }, function (err, groupData) { + }, function(err, groupData) { if (err || !groupData) { return next(); } // Don't show page if we have no scripts assigned to it yet. @@ -241,10 +242,10 @@ exports.view = function (req, res, next) { var scriptListQuery = Script.find(); // scriptListQuery: script in group - scriptListQuery.find({_id: {$in: group._scriptIds}}); + scriptListQuery.find({ _id: { $in: group._scriptIds } }); // scriptListQuery: isLib=false - scriptListQuery.find({isLib: {$ne: true}}); + scriptListQuery.find({ isLib: { $ne: true } }); // scriptListQuery: Defaults modelQuery.applyScriptListQueryDefaults(scriptListQuery, options, req); @@ -273,7 +274,7 @@ exports.view = function (req, res, next) { tasks.push(execQueryTask(popularGroupListQuery, options, 'popularGroupList')); //--- - function preRender(){ + function preRender() { // scriptList options.scriptList = _.map(options.scriptList, modelParser.parseScript); @@ -307,8 +308,8 @@ exports.view = function (req, res, next) { options.scriptListIsEmptyMessage = 'This user hasn\'t added any scripts yet.'; } }; - function render(){ res.render('pages/groupScriptListPage', options); } - function asyncComplete(){ preRender(); render(); } + function render() { res.render('pages/groupScriptListPage', options); } + function asyncComplete() { preRender(); render(); } async.parallel(tasks, asyncComplete); }); }; diff --git a/controllers/index.js b/controllers/index.js index d436a9309..501cd18b9 100644 --- a/controllers/index.js +++ b/controllers/index.js @@ -15,9 +15,8 @@ var modelQuery = require('../libs/modelQuery'); var execQueryTask = require('../libs/tasks').execQueryTask; var removeSession = require('../libs/modifySessions').remove; - // The home page has scripts and groups in a sidebar -exports.home = function (req, res) { +exports.home = function(req, res) { var authedUser = req.session.user; // @@ -88,7 +87,7 @@ exports.home = function (req, res) { tasks.push(execQueryTask(announcementsDiscussionListQuery, options, 'announcementsDiscussionList')); //--- - function preRender(){ + function preRender() { // scriptList options.scriptList = _.map(options.scriptList, modelParser.parseScript); @@ -126,13 +125,13 @@ exports.home = function (req, res) { options.pageHeading = options.isFlagged ? 'Flagged Scripts' : 'Scripts'; } }; - function render(){ res.render('pages/scriptListPage', options); } - function asyncComplete(){ preRender(); render(); } + function render() { res.render('pages/scriptListPage', options); } + function asyncComplete() { preRender(); render(); } async.parallel(tasks, asyncComplete); }; // Preform a script search -function getSearchResults (req, res, prefixSearch, fullSearch, opts, callback) { +function getSearchResults(req, res, prefixSearch, fullSearch, opts, callback) { var user = req.session.user; var search = req.route.params.shift(); var baseUrl = '/search/' + encodeURIComponent(search); @@ -146,21 +145,21 @@ function getSearchResults (req, res, prefixSearch, fullSearch, opts, callback) { .split(/\s+/); // Match all the terms but in any order - terms.forEach(function (term) { - prefixStr += '(?=.*?\\b' + term + ')'; - fullStr += '(?=.*?' + term + ')'; + terms.forEach(function(term) { + prefixStr += '(?=.*?\\b' + term + ')'; + fullStr += '(?=.*?' + term + ')'; }); prefixRegex = new RegExp(prefixStr, 'i'); fullRegex = new RegExp(fullStr, 'i'); // One of the searchable fields must match the conditions - prefixSearch.forEach(function (prop) { + prefixSearch.forEach(function(prop) { var condition = {}; condition[prop] = prefixRegex; conditions.push(condition); }); - fullSearch.forEach(function (prop) { + fullSearch.forEach(function(prop) { var condition = {}; condition[prop] = fullRegex; conditions.push(condition); @@ -168,52 +167,53 @@ function getSearchResults (req, res, prefixSearch, fullSearch, opts, callback) { opts['$or'] = conditions; modelsList.listScripts(opts, req.route.params, baseUrl, - function (scriptsList) { + function(scriptsList) { callback({ - 'title': 'Searching for "' + search +'"', + 'title': 'Searching for "' + search + '"', 'username': user ? user.name : null, 'search': search, 'scriptsList': scriptsList }); - }); + } + ); }; // Script search results -exports.search = function (req, res, next) { +exports.search = function(req, res, next) { getSearchResults(req, res, ['name', 'author', 'about', 'meta.description'], ['meta.include', 'meta.match'], {}, - function (options) { + function(options) { res.render('index', options); - }); + }); }; // Show library scripts -exports.toolbox = function (req, res) { +exports.toolbox = function(req, res) { var user = req.session.user; modelsList.listScripts({ isLib: true }, req.route.params, '/toolbox', - function (scriptsList) { + function(scriptsList) { res.render('index', { title: 'The Toolbox', toolbox: true, username: user ? user.name : null, scriptsList: scriptsList }); - }); + }); }; // Search library scripts -exports.toolSearch = function (req, res) { +exports.toolSearch = function(req, res) { getSearchResults(req, res, ['name', 'author', 'about'], [], { isLib: true }, - function (options) { + function(options) { options.toolbox = true; res.render('index', options); - }); + }); }; // UI for user registration -exports.register = function (req, res) { +exports.register = function(req, res) { var authedUser = req.session.user; // If already logged in, goto the front page. @@ -243,7 +243,7 @@ exports.register = function (req, res) { options.strategies = []; // Get OpenId strategies - _.each(strategies, function(strategy, strategyKey){ + _.each(strategies, function(strategy, strategyKey) { if (!strategy.oauth) { options.strategies.push({ 'strat': strategyKey, @@ -255,13 +255,13 @@ exports.register = function (req, res) { //--- Tasks // - tasks.push(function (callback) { - Strategy.find({}, function (err, availableStrategies) { + tasks.push(function(callback) { + Strategy.find({}, function(err, availableStrategies) { if (err) { callback(); } else { // Get the strategies we have OAuth keys for - availableStrategies.forEach(function (strategy) { + availableStrategies.forEach(function(strategy) { options.strategies.push({ 'strat': strategy.name, 'display': strategy.display @@ -273,27 +273,27 @@ exports.register = function (req, res) { }); //--- - function preRender(){ + function preRender() { // Sort the strategies - options.strategies = _.sortBy(options.strategies, function(strategy){ return strategy.display; }); + options.strategies = _.sortBy(options.strategies, function(strategy) { return strategy.display; }); // Prefer GitHub - var githubStrategy = _.findWhere(options.strategies, {strat: 'github'}); + var githubStrategy = _.findWhere(options.strategies, { strat: 'github' }); if (githubStrategy) githubStrategy.selected = true; }; - function render(){ res.render('pages/loginPage', options); } - function asyncComplete(){ preRender(); render(); } + function render() { res.render('pages/loginPage', options); } + function asyncComplete() { preRender(); render(); } async.parallel(tasks, asyncComplete); }; -exports.logout = function (req, res) { +exports.logout = function(req, res) { var authedUser = req.session.user; if (!authedUser) { return res.redirect('/'); } - User.findOne({ _id: authedUser._id }, function (err, user) { - removeSession(req, user, function () { + User.findOne({ _id: authedUser._id }, function(err, user) { + removeSession(req, user, function() { res.redirect('/'); }); }); diff --git a/controllers/issue.js b/controllers/issue.js index 6199c7bc8..a3388ea42 100644 --- a/controllers/issue.js +++ b/controllers/issue.js @@ -12,9 +12,8 @@ var discussionLib = require('./discussion'); var execQueryTask = require('../libs/tasks').execQueryTask; var countTask = require('../libs/tasks').countTask; - // List script issues -exports.list = function (req, res, next) { +exports.list = function(req, res, next) { var authedUser = req.session.user; var type = req.route.params.type; @@ -66,7 +65,7 @@ exports.list = function (req, res, next) { var discussionListQuery = Discussion.find(); // discussionListQuery: category - discussionListQuery.find({category: category.slug}); + discussionListQuery.find({ category: category.slug }); // discussionListQuery: open modelQuery.findOrDefaultIfNull(discussionListQuery, 'open', options.openIssuesOnly, true); @@ -83,7 +82,7 @@ exports.list = function (req, res, next) { //--- Tasks // Show the number of open issues - var scriptOpenIssueCountQuery = Discussion.find({ category: script.issuesCategorySlug, open: {$ne: false} }); + var scriptOpenIssueCountQuery = Discussion.find({ category: script.issuesCategorySlug, open: { $ne: false } }); tasks.push(countTask(scriptOpenIssueCountQuery, options, 'issueCount')); // Pagination @@ -93,7 +92,7 @@ exports.list = function (req, res, next) { tasks.push(execQueryTask(discussionListQuery, options, 'discussionList')); //--- - function preRender(){ + function preRender() { options.discussionList = _.map(options.discussionList, modelParser.parseDiscussion); // Script @@ -102,14 +101,14 @@ exports.list = function (req, res, next) { // Pagination options.paginationRendered = pagination.renderDefault(req); }; - function render(){ res.render('pages/scriptIssueListPage', options); } - function asyncComplete(){ preRender(); render(); } + function render() { res.render('pages/scriptIssueListPage', options); } + function asyncComplete() { preRender(); render(); } async.parallel(tasks, asyncComplete); }); }; // Show the discussion on an issue -exports.view = function (req, res, next) { +exports.view = function(req, res, next) { var authedUser = req.session.user; var type = req.route.params.type; @@ -148,7 +147,7 @@ exports.view = function (req, res, next) { category.categoryPostDiscussionPageUrl = script.scriptOpenIssuePageUrl; options.category = category; - discussionLib.findDiscussion(category.slug, topic, function (discussionData) { + discussionLib.findDiscussion(category.slug, topic, function(discussionData) { if (err || !discussionData) { return next(); } // Discussion @@ -161,7 +160,7 @@ exports.view = function (req, res, next) { var commentListQuery = Comment.find(); // commentListQuery: discussion - commentListQuery.find({_discussionId: discussion._id}); + commentListQuery.find({ _discussionId: discussion._id }); // commentListQuery: Defaults modelQuery.applyCommentListQueryDefaults(commentListQuery, options, req); @@ -172,7 +171,7 @@ exports.view = function (req, res, next) { //--- Tasks // Show the number of open issues - var scriptOpenIssueCountQuery = Discussion.find({ category: script.issuesCategorySlug, open: {$ne: false} }); + var scriptOpenIssueCountQuery = Discussion.find({ category: script.issuesCategorySlug, open: { $ne: false } }); tasks.push(countTask(scriptOpenIssueCountQuery, options, 'issueCount')); // Pagination @@ -181,7 +180,7 @@ exports.view = function (req, res, next) { // commentListQuery tasks.push(execQueryTask(commentListQuery, options, 'commentList')); - function preRender(){ + function preRender() { // Metadata options.title = discussion.topic + ' | OpenUserJS.org'; options.pageMetaDescription = discussion.topic; @@ -189,7 +188,7 @@ exports.view = function (req, res, next) { // commentList options.commentList = _.map(options.commentList, modelParser.parseComment); - _.map(options.commentList, function(comment){ + _.map(options.commentList, function(comment) { comment.author = modelParser.parseUser(comment._authorId); }); _.map(options.commentList, modelParser.renderComment); @@ -200,15 +199,15 @@ exports.view = function (req, res, next) { // Pagination options.paginationRendered = pagination.renderDefault(req); }; - function render(){ res.render('pages/scriptIssuePage', options); } - function asyncComplete(){ preRender(); render(); } + function render() { res.render('pages/scriptIssuePage', options); } + function asyncComplete() { preRender(); render(); } async.parallel(tasks, asyncComplete); }); }); }; // Open a new issue -exports.open = function (req, res, next) { +exports.open = function(req, res, next) { var authedUser = req.session.user; if (!authedUser) return res.redirect('/login'); @@ -251,7 +250,7 @@ exports.open = function (req, res, next) { if (topic && content) { // Issue Submission discussionLib.postTopic(authedUser, category.slug, topic, content, true, - function (discussion) { + function(discussion) { if (!discussion) return res.redirect('/' + encodeURI(category) + '/open'); @@ -261,26 +260,25 @@ exports.open = function (req, res, next) { } else { // New Issue Page - //--- Tasks // ... //--- - function preRender(){ + function preRender() { // Metadata options.title = 'New Issue for ' + script.name + ' | OpenUserJS.org'; options.pageMetaDescription = ''; options.pageMetaKeywords = null; // seperator = ', ' }; - function render(){ res.render('pages/scriptNewIssuePage', options); } - function asyncComplete(){ preRender(); render(); } + function render() { res.render('pages/scriptNewIssuePage', options); } + function asyncComplete() { preRender(); render(); } async.parallel(tasks, asyncComplete); } }); }; // post route to add a new comment to a discussion on an issue -exports.comment = function (req, res, next) { +exports.comment = function(req, res, next) { var type = req.route.params.type; var topic = req.route.params.topic; var installName = scriptStorage.getInstallName(req); @@ -293,22 +291,22 @@ exports.comment = function (req, res, next) { + (type === 'libs' ? '.js' : '.user.js')) }, function (err, script) { var content = req.body['comment-content']; - if (err || !script) { return next(); } + if (err || !script) { return next(); } - discussionLib.findDiscussion(category, topic, function (issue) { - if (!issue) { return next(); } + discussionLib.findDiscussion(category, topic, function(issue) { + if (!issue) { return next(); } - discussionLib.postComment(user, issue, content, false, - function (err, discussion) { - res.redirect(encodeURI(discussion.path - + (discussion.duplicateId ? '_' + discussion.duplicateId : ''))); + discussionLib.postComment(user, issue, content, false, + function(err, discussion) { + res.redirect(encodeURI(discussion.path + + (discussion.duplicateId ? '_' + discussion.duplicateId : ''))); }); - }); + }); }); }; // Open or close and issue you are allowed -exports.changeStatus = function (req, res, next) { +exports.changeStatus = function(req, res, next) { var type = req.route.params.type; var topic = req.route.params.topic; var installName = scriptStorage.getInstallName(req); @@ -323,30 +321,31 @@ exports.changeStatus = function (req, res, next) { + (type === 'libs' ? '.js' : '.user.js')) }, function (err, script) { if (err || !script) { return next(); } - - discussionLib.findDiscussion(category, topic, function (issue) { - if (!issue) { return next(); } - - // Both the script author and the issue creator can close the issue - // Only the script author can reopen a closed issue - if (action === 'close' && issue.open - && (user.name === issue.author || user.name === script.author)) { - issue.open = false; - changed = true; - } else if (action === 'reopen' && !issue.open - && user.name === script.author) { - issue.open = true; - changed = true; - } - - if (changed) { - issue.save(function (err, discussion) { - res.redirect(encodeURI(discussion.path - + (discussion.duplicateId ? '_' + discussion.duplicateId : ''))); - }); - } else { - next(); - } - }); + if (err || !script) { return next(); } + + discussionLib.findDiscussion(category, topic, function(issue) { + if (!issue) { return next(); } + + // Both the script author and the issue creator can close the issue + // Only the script author can reopen a closed issue + if (action === 'close' && issue.open + && (user.name === issue.author || user.name === script.author)) { + issue.open = false; + changed = true; + } else if (action === 'reopen' && !issue.open + && user.name === script.author) { + issue.open = true; + changed = true; + } + + if (changed) { + issue.save(function(err, discussion) { + res.redirect(encodeURI(discussion.path + + (discussion.duplicateId ? '_' + discussion.duplicateId : ''))); + }); + } else { + next(); + } + }); }); }; diff --git a/controllers/moderation.js b/controllers/moderation.js index cfda388f0..f1f2cc9d8 100644 --- a/controllers/moderation.js +++ b/controllers/moderation.js @@ -11,52 +11,54 @@ var statusCodePage = require('../libs/templateHelpers').statusCodePage; // When content reaches a its threshold of flags it gets marked as flagged // and it can now be removed by moderators -exports.flagged = function (req, res, next) { +exports.flagged = function(req, res, next) { var user = req.session.user; var type = req.route.params.shift() || 'users'; var baseUrl = '/flagged' + (type ? '/' + type : ''); - var options = { title: 'Flagged Content', moderation: true, - username: user ? user.name : '' }; + var options = { + title: 'Flagged Content', moderation: true, + username: user ? user.name : '' + }; options[type + 'Type'] = true; if (!user || user.role > 3) { return next(); } switch (type) { - case 'users': - if (!req.route.params[1]) { - req.route.params[1] = ['flags']; - } + case 'users': + if (!req.route.params[1]) { + req.route.params[1] = ['flags']; + } - modelsList.listUsers({ flagged: true }, req.route.params, baseUrl, - function (usersList) { - options.usersList = usersList; - res.render('flagged', options); - }); - break; - case 'scripts': - if (!req.route.params[1]) { - req.route.params[1] = ['flags', 'updated']; - } + modelsList.listUsers({ flagged: true }, req.route.params, baseUrl, + function(usersList) { + options.usersList = usersList; + res.render('flagged', options); + }); + break; + case 'scripts': + if (!req.route.params[1]) { + req.route.params[1] = ['flags', 'updated']; + } - modelsList.listScripts({ flagged: true, isLib: null }, - req.route.params, baseUrl, - function (scriptsList) { - options.scriptsList = scriptsList; - res.render('flagged', options); - }); - break; - default: - next(); + modelsList.listScripts({ flagged: true, isLib: null }, + req.route.params, baseUrl, + function(scriptsList) { + options.scriptsList = scriptsList; + res.render('flagged', options); + }); + break; + default: + next(); } }; // When content is remove via the community moderation system it isn't // actually deleted. Instead it is sent to the graveyard where hopefully // any mistakes can be undone. -exports.graveyard = function (req, res, next) { +exports.graveyard = function(req, res, next) { var contentTypes = { - 'users' : + 'users': { 'name': 'User', 'selected': false, @@ -79,7 +81,7 @@ exports.graveyard = function (req, res, next) { // Hopefully one day it can actually be viewed read-only by // those who have the authority modelsList.listRemoved({ model: contentType.name }, req.route.params, baseUrl, - function (removedList) { + function(removedList) { var type = null; var name = null; contentType.selected = true; @@ -99,7 +101,7 @@ exports.graveyard = function (req, res, next) { }); }; -exports.removedItemPage = function (req, res, next) { +exports.removedItemPage = function(req, res, next) { var authedUser = req.session.user; var removedItemId = req.route.params.id; @@ -126,10 +128,10 @@ exports.removedItemPage = function (req, res, next) { if (err || !removedItemData) { return next(); } res.json(removedItemData); - }) + }); }; -exports.removedItemListPage = function (req, res, next) { +exports.removedItemListPage = function(req, res, next) { var authedUser = req.session.user; // @@ -186,7 +188,7 @@ exports.removedItemListPage = function (req, res, next) { }); }; -exports.modPage = function (req, res, next) { +exports.modPage = function(req, res, next) { var authedUser = req.session.user; // diff --git a/controllers/remove.js b/controllers/remove.js index 2318c8e05..75bfa9e88 100644 --- a/controllers/remove.js +++ b/controllers/remove.js @@ -4,36 +4,36 @@ var User = require('../models/user').User; var destroySessions = require('../libs/modifySessions').destroy; // Simple controller to remove content and save it in the graveyard -exports.rm = function (req, res, next) { +exports.rm = function(req, res, next) { var type = req.route.params[0]; var path = req.route.params[1]; var thisUser = req.session.user; switch (type) { - case 'scripts': - case 'libs': - path += type === 'libs' ? '.js' : '.user.js'; - Script.findOne({ installName: path }, function (err, script) { - removeLib.remove(Script, script, thisUser, '', function (removed) { - if (!removed) { return next(); } - res.redirect('/'); - }); - }); - break; - case 'users': - User.findOne({ name : { $regex : new RegExp('^' + path + '$', "i") } }, - function (err, user) { - removeLib.remove(User, user, thisUser, '', function (removed) { + case 'scripts': + case 'libs': + path += type === 'libs' ? '.js' : '.user.js'; + Script.findOne({ installName: path }, function(err, script) { + removeLib.remove(Script, script, thisUser, '', function(removed) { if (!removed) { return next(); } + res.redirect('/'); + }); + }); + break; + case 'users': + User.findOne({ name: { $regex: new RegExp('^' + path + '$', "i") } }, + function(err, user) { + removeLib.remove(User, user, thisUser, '', function(removed) { + if (!removed) { return next(); } - // Destory all the sessions belonging to the removed user - destroySessions(req, user, function () { - res.redirect('/'); + // Destory all the sessions belonging to the removed user + destroySessions(req, user, function() { + res.redirect('/'); + }); }); }); - }); - break; - default: - next(); + break; + default: + next(); } }; diff --git a/controllers/script.js b/controllers/script.js index 45be6ef52..0cf49a258 100644 --- a/controllers/script.js +++ b/controllers/script.js @@ -18,8 +18,8 @@ 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) { +exports.lib = function(controller) { + return (function(req, res, next) { req.route.params.isLib = true; controller(req, res, next); }); @@ -32,17 +32,17 @@ exports.lib = function (controller) { var user = req.session.user; var options = { username: user ? user.name : '' }; - Script.findOne({ installName: installName + '.js' }, function (err, lib) { + Script.findOne({ installName: installName + '.js' }, function(err, lib) { if (err || !lib) { return next(); } options.title = 'Scripts that use ' + lib.name + ''; modelsList.listScripts({ uses: lib.installName }, req.route.params, '/use/lib/' + installName, - function (scriptsList) { + function(scriptsList) { options.scriptsList = scriptsList; res.render('group', options); - }); + }); }); };*/ @@ -53,7 +53,6 @@ var getScriptPageTasks = function(options) { var script = options.script; var authedUser = options.authedUser; - //--- Tasks // Show the number of open issues @@ -61,7 +60,6 @@ var getScriptPageTasks = function(options) { .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; @@ -69,7 +67,7 @@ var getScriptPageTasks = function(options) { options.script.meta.collaborators = [{ name: script.meta.collaborator }]; } else { options.script.meta.collaborators = []; - script.meta.collaborator.forEach(function (collaborator) { + script.meta.collaborator.forEach(function(collaborator) { options.script.meta.collaborators.push({ name: collaborator }); }); } @@ -81,12 +79,12 @@ var getScriptPageTasks = function(options) { options.script.meta.licenses = [{ name: script.meta.license }]; } else { options.script.meta.licenses = []; - script.meta.license.forEach(function (license) { + script.meta.license.forEach(function(license) { options.script.meta.licenses.push({ name: license }); }); } } else if (!script.isLib) { - options.script.meta.licenses = [{ name: 'MIT License (Expat)' }]; + options.script.meta.licenses = [{ name: 'MIT License (Expat)' }]; } // Show homepages of the script @@ -102,13 +100,13 @@ var getScriptPageTasks = function(options) { } // Show the groups the script belongs to - tasks.push(function (callback) { + tasks.push(function(callback) { script.hasGroups = false; script.groups = []; Group.find({ _scriptIds: script._id - }, function (err, scriptGroupList) { + }, function(err, scriptGroupList) { if (err) return callback(err); scriptGroupList = _.map(scriptGroupList, modelParser.parseGroup); @@ -124,10 +122,10 @@ var getScriptPageTasks = function(options) { if (!script.isLib && script.uses && script.uses.length > 0) { script.usesLibs = true; script.libs = []; - tasks.push(function (callback) { + tasks.push(function(callback) { Script.find({ installName: { $in: script.uses } - }, function (err, scriptLibraryList) { + }, function(err, scriptLibraryList) { if (err) return callback(err); script.libs = scriptLibraryList; @@ -138,10 +136,10 @@ var getScriptPageTasks = function(options) { } else if (script.isLib) { script.isUsed = false; script.usedBy = []; - tasks.push(function (callback) { + tasks.push(function(callback) { Script.find({ uses: script.installName - }, function (err, libraryScriptList) { + }, function(err, libraryScriptList) { if (err) return callback(err); script.isUsed = libraryScriptList.length > 0; @@ -153,7 +151,7 @@ var getScriptPageTasks = function(options) { } // Setup the voting UI - tasks.push(function (callback) { + tasks.push(function(callback) { var voteUrl = '/vote' + script.scriptPageUrl; options.voteUpUrl = voteUrl + '/up'; options.voteDownUrl = voteUrl + '/down'; @@ -172,7 +170,7 @@ var getScriptPageTasks = function(options) { Vote.findOne({ _scriptId: script._id, _userId: authedUser._id - }, function (err, voteModel) { + }, function(err, voteModel) { options.voteable = !script.isOwner; if (voteModel) { @@ -189,7 +187,7 @@ var getScriptPageTasks = function(options) { }); // Setup the flagging UI - tasks.push(function (callback) { + 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. @@ -199,7 +197,7 @@ var getScriptPageTasks = function(options) { } flagLib.flaggable(Script, script, authedUser, - function (canFlag, author, flag) { + function(canFlag, author, flag) { if (flag) { flagUrl += '/unflag'; options.flagged = true; @@ -210,11 +208,11 @@ var getScriptPageTasks = function(options) { options.flagUrl = flagUrl; callback(); - }); + }); }); // Set up the removal UI - tasks.push(function (callback) { + tasks.push(function(callback) { // Can't remove when not logged in or when user owns the script. if (!authedUser || options.isOwner) { callback(); @@ -222,7 +220,7 @@ var getScriptPageTasks = function(options) { } removeLib.removeable(Script, script, authedUser, - function (canRemove, author) { + function(canRemove, author) { options.canRemove = canRemove; options.flags = script.flags || 0; options.removeUrl = '/remove' + (script.isLib ? '/libs/' : '/scripts/') + script.installNameSlug; @@ -230,11 +228,11 @@ var getScriptPageTasks = function(options) { if (!canRemove) { return callback(); } flagLib.getThreshold(Script, script, author, - function (threshold) { + function(threshold) { options.threshold = threshold; callback(); - }); - }); + }); + }); }); return tasks; @@ -264,7 +262,7 @@ var setupScriptSidePanel = function(options) { // View a detailed description of a script // This is the most intensive page to render on the site -exports.view = function (req, res, next) { +exports.view = function(req, res, next) { var authedUser = req.session.user; var installNameSlug = scriptStorage.getInstallName(req); @@ -275,7 +273,7 @@ exports.view = function (req, res, next) { Script.findOne({ installName: scriptStorage .caseInsensitive(installNameSlug + (isLib ? '.js' : '.user.js')) - }, function (err, scriptData) { + }, function(err, scriptData) { if (err || !scriptData) { return next(); } var options = {}; @@ -308,22 +306,21 @@ exports.view = function (req, res, next) { //--- Tasks tasks = tasks.concat(getScriptPageTasks(options)); - //--- - function preRender(){ + 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(); } + 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) { +exports.edit = function(req, res, next) { var authedUser = req.session.user; if (!authedUser) { return res.redirect('/login'); } @@ -339,7 +336,7 @@ exports.edit = function (req, res, next) { Script.findOne({ installName: scriptStorage .caseInsensitive(installNameSlug + (isLib ? '.js' : '.user.js')) - }, function (err, scriptData) { + }, function(err, scriptData) { if (err || !scriptData) { return next(); } // @@ -367,7 +364,7 @@ exports.edit = function (req, res, next) { if (req.body.remove) { // POST - scriptStorage.deleteScript(scriptData.installName, function () { + scriptStorage.deleteScript(scriptData.installName, function() { res.redirect(authedUser.userScriptListPageUrl); }); } else if (typeof req.body.about !== 'undefined') { @@ -375,7 +372,7 @@ exports.edit = function (req, res, next) { scriptData.about = req.body.about; var scriptGroups = (req.body.groups || ""); scriptGroups = scriptGroups.split(/,/); - addScriptToGroups(scriptData, scriptGroups, function () { + addScriptToGroups(scriptData, scriptGroups, function() { res.redirect(script.scriptPageUrl); }); } else { @@ -385,22 +382,22 @@ exports.edit = function (req, res, next) { tasks = tasks.concat(getScriptPageTasks(options)); - tasks.push(function (callback) { + tasks.push(function(callback) { callback(); }); // Groups options.canCreateGroup = (!script._groupId).toString(); - function preRender(){ - var groupNameList = (options.script.groups || []).map(function (group) { + 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(); } + function render() { res.render('pages/scriptEditMetadataPage', options); } + function asyncComplete() { preRender(); render(); } async.parallel(tasks, asyncComplete); // Group.find({ _scriptIds: script._id }, 'name', function (err, groups) { @@ -426,7 +423,7 @@ exports.edit = function (req, res, next) { }; // Script voting -exports.vote = function (req, res, next) { +exports.vote = function(req, res, next) { var isLib = req.route.params.isLib; var installName = scriptStorage.getInstallName(req) + (isLib ? '.js' : '.user.js'); @@ -453,25 +450,25 @@ exports.vote = function (req, res, next) { } Script.findOne({ installName: scriptStorage.caseInsensitive(installName) }, - function (err, script) { + function(err, script) { if (err || !script) { return res.redirect(url); } Vote.findOne({ _scriptId: script._id, _userId: user._id }, - function (err, voteModel) { + function(err, voteModel) { var oldVote = null; var votes = script.votes || 0; var flags = 0; - function saveScript () { + function saveScript() { if (!flags) { - return script.save(function (err, script) { res.redirect(url); }); + return script.save(function(err, script) { res.redirect(url); }); } flagLib.getAuthor(script, function(author) { flagLib.saveContent(Script, script, author, flags, - function (flagged) { + function(flagged) { res.redirect(url); - }); + }); }); } @@ -491,7 +488,7 @@ exports.vote = function (req, res, next) { if (vote) { flags = -1; } } else if (unvote) { oldVote = voteModel.vote; - return voteModel.remove(function () { + return voteModel.remove(function() { script.rating += oldVote ? -1 : 1; script.votes = votes <= 0 ? 0 : votes - 1; if (oldVote) { flags = 1; } @@ -504,24 +501,27 @@ exports.vote = function (req, res, next) { } voteModel.save(saveScript); - }); - }); + } + ); + } + ); }; // Script flagging -exports.flag = function (req, res, next) { +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) { + function(err, script) { var fn = flagLib[unflag && unflag === 'unflag' ? 'unflag' : 'flag']; if (err || !script) { return next(); } - fn(Script, script, req.session.user, function (flagged) { + fn(Script, script, req.session.user, function(flagged) { res.redirect((isLib ? '/libs/' : '/scripts/') + encodeURI(installName)); }); - }); + } + ); }; diff --git a/controllers/scriptStorage.js b/controllers/scriptStorage.js index 04d0bd22e..eaf29011a 100644 --- a/controllers/scriptStorage.js +++ b/controllers/scriptStorage.js @@ -15,10 +15,14 @@ if (process.env.NODE_ENV === 'production') { // You need to install (and ruby too): https://github.com/jubos/fake-s3 // Then run the fakes3.sh script or: fakes3 -r fakeS3 -p 10001 var DEV_AWS_URL = process.env.DEV_AWS_URL || 'localhost:10001'; - AWS.config.update({ accessKeyId: 'fakeId', secretAccessKey: 'fakeKey', + AWS.config.update({ + accessKeyId: 'fakeId', + secretAccessKey: 'fakeKey', httpOptions: { - proxy: DEV_AWS_URL, agent: require('http').globalAgent - }}); + proxy: DEV_AWS_URL, + agent: require('http').globalAgent + } + }); } /*Script.find({ installName: /^[^\/]+\/[^\/]+\/[^\/]+$/ },function (err, scripts){ @@ -95,7 +99,7 @@ exports.getSource = function (req, callback) { }); }; -exports.sendScript = function (req, res, next) { +exports.sendScript = function(req, res, next) { var accept = req.headers.accept; var installName = null; @@ -103,7 +107,7 @@ exports.sendScript = function (req, res, next) { return exports.sendMeta(req, res, next); } - exports.getSource(req, function (script, stream) { + exports.getSource(req, function(script, stream) { if (!script) { return next(); } @@ -116,12 +120,12 @@ exports.sendScript = function (req, res, next) { // Update the install count ++script.installs; - script.save(function (err, script) {}); + script.save(function(err, script) { }); }); }; // Send user script metadata block -exports.sendMeta = function (req, res, next) { +exports.sendMeta = function(req, res, next) { var installName = getInstallName(req).replace(/\.meta\.js$/, '.user.js'); Script.findOne({ installName: caseInsensitive(installName) }, @@ -166,7 +170,7 @@ function parseMeta(aString) { 'author': true }; - lines = aString.split(/[\r\n]+/).filter(function (e, i, a) { + lines = aString.split(/[\r\n]+/).filter(function(e, i, a) { return (e.match(re)); }); @@ -197,7 +201,7 @@ function parseMeta(aString) { } exports.parseMeta = parseMeta; -exports.getMeta = function (chunks, callback) { +exports.getMeta = function(chunks, callback) { // We need to convert the array of buffers to a string to // parse the header. But strings are memory inefficient compared // to buffers so we only convert the least number of chunks to @@ -217,7 +221,7 @@ exports.getMeta = function (chunks, callback) { callback(null); }; -exports.storeScript = function (user, meta, buf, callback, update) { +exports.storeScript = function(user, meta, buf, callback, update) { var s3 = new AWS.S3(); var scriptName = null; var installName = user.name + '/'; @@ -260,9 +264,9 @@ exports.storeScript = function (user, meta, buf, callback, update) { requires = meta.require; } - requires.forEach(function (require) { - var match = libraryRegex.exec(require); - if (match && match[1]) { libraries.push(match[1]); } + requires.forEach(function(require) { + var match = libraryRegex.exec(require); + if (match && match[1]) { libraries.push(match[1]); } }); } } else { @@ -274,8 +278,7 @@ exports.storeScript = function (user, meta, buf, callback, update) { // Prevent a removed script from being reuploaded findDeadorAlive(Script, { installName: caseInsensitive(installName) }, true, - function (alive, script, removed) { - + function(alive, script, removed) { if (removed || (!script && (update || collaborators))) { return callback(null); } else if (!script) { @@ -308,9 +311,9 @@ exports.storeScript = function (user, meta, buf, callback, update) { script.updated = new Date(); } - script.save(function (err, script) { - s3.putObject({ Bucket : bucketName, Key : installName, Body : buf }, - function (err, data) { + script.save(function(err, script) { + s3.putObject({ Bucket: bucketName, Key: installName, Body: buf }, + function(err, data) { if (user.role === userRoles.length - 1) { var userDoc = user; if (!userDoc.save) { @@ -318,13 +321,13 @@ exports.storeScript = function (user, meta, buf, callback, update) { userDoc = new User(userDoc); } --userDoc.role; - userDoc.save(function (err, user) { callback(script); }); + userDoc.save(function(err, user) { callback(script); }); } else { callback(script); } - }); + }); }); - }); + }); }; exports.deleteScript = function (installName, callback) { @@ -344,7 +347,7 @@ exports.deleteScript = function (installName, callback) { // GitHub calls this on a push if a webhook is setup // This controller makes sure we have the latest version of a script -exports.webhook = function (req, res) { +exports.webhook = function(req, res) { var RepoManager = require('../libs/repoManager'); var payload = null; var username = null; @@ -352,7 +355,7 @@ exports.webhook = function (req, res) { var repos = {}; var repo = null; - res.end(); // close connection + res.end(); // Close connection // Test for know GH webhook ips: https://api.github.com/meta if (!req.body.payload || @@ -373,12 +376,12 @@ exports.webhook = function (req, res) { repo = repos[reponame] = {}; // Find the user that corresponds the repo owner - User.findOne({ ghUsername: username }, function (err, user) { + User.findOne({ ghUsername: username }, function(err, user) { if (!user) { return; } // Gather the modified user scripts - payload.commits.forEach(function (commit) { - commit.modified.forEach(function (filename) { + payload.commits.forEach(function(commit) { + commit.modified.forEach(function(filename) { if (filename.substr(-8) === '.user.js') { repo[filename] = '/' + encodeURI(filename); } @@ -387,6 +390,6 @@ exports.webhook = function (req, res) { // Update modified scripts var repoManager = RepoManager.getManager(null, user, repos); - repoManager.loadScripts(function (){}, true); + repoManager.loadScripts(function() { }, true); }); }; diff --git a/controllers/user.js b/controllers/user.js index 7a666b066..dc5145eaf 100644 --- a/controllers/user.js +++ b/controllers/user.js @@ -46,7 +46,7 @@ var setupUserModerationUITask = function(options) { callback(); return; } - flagLib.flaggable(User, user, authedUser, function (canFlag, author, flag) { + flagLib.flaggable(User, user, authedUser, function(canFlag, author, flag) { if (flag) { flagUrl += '/unflag'; options.flagged = true; @@ -56,13 +56,13 @@ var setupUserModerationUITask = function(options) { } options.flagUrl = flagUrl; - removeLib.removeable(User, user, authedUser, function (canRemove, author) { + removeLib.removeable(User, user, authedUser, function(canRemove, author) { options.canRemove = canRemove; options.flags = user.flags || 0; if (!canRemove) { return callback(); } - flagLib.getThreshold(User, user, author, function (threshold) { + flagLib.getThreshold(User, user, author, function(threshold) { options.threshold = threshold; callback(); }); @@ -92,11 +92,11 @@ var getUserPageTasks = function(options) { //--- Tasks // userScriptListCountQuery - var userScriptListCountQuery = Script.find({ _authorId: user._id, flagged: {$ne: true}}); + var userScriptListCountQuery = Script.find({ _authorId: user._id, flagged: { $ne: true } }); tasks.push(countTask(userScriptListCountQuery, options, 'scriptListCount')); // userCommentListCountQuery - var userCommentListCountQuery = Comment.find({ _authorId: user._id, flagged: {$ne: true}}); + var userCommentListCountQuery = Comment.find({ _authorId: user._id, flagged: { $ne: true } }); tasks.push(countTask(userCommentListCountQuery, options, 'commentListCount')); return tasks; @@ -124,7 +124,7 @@ var setupUserSidePanel = function(options) { // user.role // Allow authedUser to raise target user role to the level below him. - var roles = _.map(userRoles, function(roleName, index){ + var roles = _.map(userRoles, function(roleName, index) { return { id: index, name: roleName, @@ -144,7 +144,7 @@ var setupUserSidePanel = function(options) { } }; -exports.userListPage = function (req, res, next) { +exports.userListPage = function(req, res, next) { var authedUser = req.session.user; // @@ -179,7 +179,7 @@ exports.userListPage = function (req, res, next) { tasks.push(execQueryTask(userListQuery, options, 'userList')); //--- - function preRender(){ + function preRender() { // userList options.userList = _.map(options.userList, modelParser.parseUser); @@ -197,20 +197,20 @@ exports.userListPage = function (req, res, next) { // Heading options.pageHeading = options.isFlagged ? 'Flagged Users' : 'Users'; }; - function render(){ res.render('pages/userListPage', options); } - function asyncComplete(err){ if (err) { return next(); } else { preRender(); render(); } }; + function render() { res.render('pages/userListPage', options); } + function asyncComplete(err) { if (err) { return next(); } else { preRender(); render(); } }; async.parallel(tasks, asyncComplete); }; // View information and scripts of a user -exports.view = function (req, res, next) { +exports.view = function(req, res, next) { var authedUser = req.session.user; var username = req.route.params.username; User.findOne({ name: caseInsensitive(username) - }, function (err, userData) { + }, function(err, userData) { if (err || !userData) { return next(); } // @@ -240,7 +240,7 @@ exports.view = function (req, res, next) { var scriptListQuery = Script.find(); // scriptListQuery: author=user - scriptListQuery.find({_authorId: user._id}); + scriptListQuery.find({ _authorId: user._id }); // scriptListQuery: Defaults modelQuery.applyScriptListQueryDefaults(scriptListQuery, options, req); @@ -257,15 +257,13 @@ exports.view = function (req, res, next) { tasks = tasks.concat(getUserSidePanelTasks(options)); //--- - function preRender(){}; - function render(){ res.render('pages/userPage', options); } - function asyncComplete(){ preRender(); render(); } + function preRender() { }; + function render() { res.render('pages/userPage', options); } + function asyncComplete() { preRender(); render(); } async.parallel(tasks, asyncComplete); }); }; - - exports.userCommentListPage = function(req, res, next) { var authedUser = req.session.user; @@ -273,7 +271,7 @@ exports.userCommentListPage = function(req, res, next) { User.findOne({ name: caseInsensitive(username) - }, function (err, userData) { + }, function(err, userData) { if (err || !userData) { return next(); } // @@ -299,7 +297,7 @@ exports.userCommentListPage = function(req, res, next) { var commentListQuery = Comment.find(); // commentListQuery: author=user - commentListQuery.find({_authorId: user._id}); + commentListQuery.find({ _authorId: user._id }); // commentListQuery: Defaults modelQuery.applyCommentListQueryDefaults(commentListQuery, options, req); @@ -330,24 +328,24 @@ exports.userCommentListPage = function(req, res, next) { tasks = tasks.concat(getUserPageTasks(options)); //-- - function preRender(){ + function preRender() { // commentList options.commentList = _.map(options.commentList, modelParser.parseComment); - _.map(options.commentList, function(comment){ + _.map(options.commentList, function(comment) { comment.author = modelParser.parseUser(comment._authorId); }); _.map(options.commentList, modelParser.renderComment); // comment.discussion - _.map(options.commentList, function(comment){ + _.map(options.commentList, function(comment) { comment.discussion = modelParser.parseDiscussion(comment._discussionId); }); // Pagination options.paginationRendered = pagination.renderDefault(req); }; - function render(){ res.render('pages/userCommentListPage', options); } - function asyncComplete(){ preRender(); render(); } + function render() { res.render('pages/userCommentListPage', options); } + function asyncComplete() { preRender(); render(); } async.parallel(tasks, asyncComplete); }); }; @@ -359,7 +357,7 @@ exports.userScriptListPage = function(req, res, next) { User.findOne({ name: caseInsensitive(username) - }, function (err, userData) { + }, function(err, userData) { if (err || !userData) { return next(); } // @@ -385,7 +383,7 @@ exports.userScriptListPage = function(req, res, next) { var scriptListQuery = Script.find(); // scriptListQuery: author=user - scriptListQuery.find({_authorId: user._id}); + scriptListQuery.find({ _authorId: user._id }); // scriptListQuery: Defaults modelQuery.applyScriptListQueryDefaults(scriptListQuery, options, req); @@ -409,7 +407,7 @@ exports.userScriptListPage = function(req, res, next) { tasks = tasks.concat(getUserPageTasks(options)); //--- - function preRender(){ + function preRender() { // scriptList options.scriptList = _.map(options.scriptList, modelParser.parseScript); @@ -434,13 +432,13 @@ exports.userScriptListPage = function(req, res, next) { options.scriptListIsEmptyMessage = 'This user hasn\'t added any scripts yet.'; } }; - function render(){ res.render('pages/userScriptListPage', options); } - function asyncComplete(){ preRender(); render(); } + function render() { res.render('pages/userScriptListPage', options); } + function asyncComplete() { preRender(); render(); } async.parallel(tasks, asyncComplete); }); }; -exports.userEditProfilePage = function (req, res, next) { +exports.userEditProfilePage = function(req, res, next) { var authedUser = req.session.user; if (!authedUser) { return res.redirect('/login'); } @@ -449,7 +447,7 @@ exports.userEditProfilePage = function (req, res, next) { User.findOne({ _id: authedUser._id - }, function (err, userData) { + }, function(err, userData) { if (err || !userData) { return next(); } // @@ -477,7 +475,7 @@ exports.userEditProfilePage = function (req, res, next) { var scriptListQuery = Script.find(); // Scripts: Query: author=user - scriptListQuery.find({_authorId: user._id}); + scriptListQuery.find({ _authorId: user._id }); // Scripts: Query: flagged // Only list flagged scripts for author and user >= moderator @@ -485,7 +483,7 @@ exports.userEditProfilePage = function (req, res, next) { // Show } else { // Script.flagged is undefined by default. - scriptListQuery.find({flagged: {$ne: true}}); + scriptListQuery.find({ flagged: { $ne: true } }); } //--- Tasks @@ -497,21 +495,21 @@ exports.userEditProfilePage = function (req, res, next) { tasks = tasks.concat(getUserSidePanelTasks(options)); //--- - function preRender(){}; - function render(){ res.render('pages/userEditProfilePage', options); } - function asyncComplete(){ preRender(); render(); } + function preRender() { }; + function render() { res.render('pages/userEditProfilePage', options); } + function asyncComplete() { preRender(); render(); } async.parallel(tasks, asyncComplete); }); }; -exports.userEditPreferencesPage = function (req, res, next) { +exports.userEditPreferencesPage = function(req, res, next) { var authedUser = req.session.user; if (!authedUser) { return res.redirect('/login'); } User.findOne({ _id: authedUser._id - }, function (err, userData) { + }, function(err, userData) { if (err || !userData) { return next(); } // @@ -539,7 +537,7 @@ exports.userEditPreferencesPage = function (req, res, next) { var scriptListQuery = Script.find(); // Scripts: Query: author=user - scriptListQuery.find({_authorId: user._id}); + scriptListQuery.find({ _authorId: user._id }); // Scripts: Query: flagged // Only list flagged scripts for author and user >= moderator @@ -547,7 +545,7 @@ exports.userEditPreferencesPage = function (req, res, next) { // Show } else { // Script.flagged is undefined by default. - scriptListQuery.find({flagged: {$ne: true}}); + scriptListQuery.find({ flagged: { $ne: true } }); } //--- Tasks @@ -555,7 +553,7 @@ exports.userEditPreferencesPage = function (req, res, next) { // User edit auth strategies tasks.push(function(callback) { var userStrats = user.strategies.slice(0); - Strategy.find({}, function (err, strats) { + Strategy.find({}, function(err, strats) { var defaultStrategy = userStrats[userStrats.length - 1]; var strategy = null; var name = null; @@ -563,15 +561,19 @@ exports.userEditPreferencesPage = function (req, res, next) { options.usedStrategies = []; // Get the strategies we have OAuth keys for - strats.forEach(function (strat) { + strats.forEach(function(strat) { if (strat.name === defaultStrategy) { return; } if (userStrats.indexOf(strat.name) > -1) { - options.usedStrategies.push({ 'strat' : strat.name, - 'display' : strat.display }); + options.usedStrategies.push({ + 'strat': strat.name, + 'display': strat.display + }); } else { - options.openStrategies.push({ 'strat' : strat.name, - 'display' : strat.display }); + options.openStrategies.push({ + 'strat': strat.name, + 'display': strat.display + }); } }); @@ -582,11 +584,15 @@ exports.userEditPreferencesPage = function (req, res, next) { if (!strategy.oauth && name !== defaultStrategy) { if (userStrats.indexOf(name) > -1) { - options.usedStrategies.push({ 'strat' : name, - 'display' : strategy.name }); + options.usedStrategies.push({ + 'strat': name, + 'display': strategy.name + }); } else { - options.openStrategies.push({ 'strat' : name, - 'display' : strategy.name }); + options.openStrategies.push({ + 'strat': name, + 'display': strategy.name + }); } } } @@ -605,15 +611,15 @@ exports.userEditPreferencesPage = function (req, res, next) { // UserSidePanel tasks tasks = tasks.concat(getUserSidePanelTasks(options)); - function preRender(){}; - function render(){ res.render('pages/userEditPreferencesPage', options); } - function asyncComplete(){ preRender(); render(); } + function preRender() { }; + function render() { res.render('pages/userEditPreferencesPage', options); } + function asyncComplete() { preRender(); render(); } async.parallel(tasks, asyncComplete); }); }; // Let a user edit their account -exports.edit = function (req, res, next) { +exports.edit = function(req, res, next) { var user = req.session.user; var userStrats = null; var options = null; @@ -630,7 +636,7 @@ exports.edit = function (req, res, next) { req.route.params.push('author'); - Strategy.find({}, function (err, strats) { + Strategy.find({}, function(err, strats) { var defaultStrategy = userStrats[userStrats.length - 1]; var strategy = null; var name = null; @@ -638,15 +644,19 @@ exports.edit = function (req, res, next) { options.usedStrategies = []; // Get the strategies we have OAuth keys for - strats.forEach(function (strat) { + strats.forEach(function(strat) { if (strat.name === defaultStrategy) { return; } if (userStrats.indexOf(strat.name) > -1) { - options.usedStrategies.push({ 'strat' : strat.name, - 'display' : strat.display }); + options.usedStrategies.push({ + 'strat': strat.name, + 'display': strat.display + }); } else { - options.openStrategies.push({ 'strat' : strat.name, - 'display' : strat.display }); + options.openStrategies.push({ + 'strat': strat.name, + 'display': strat.display + }); } }); @@ -657,11 +667,15 @@ exports.edit = function (req, res, next) { if (!strategy.oauth && name !== defaultStrategy) { if (userStrats.indexOf(name) > -1) { - options.usedStrategies.push({ 'strat' : name, - 'display' : strategy.name }); + options.usedStrategies.push({ + 'strat': name, + 'display': strategy.name + }); } else { - options.openStrategies.push({ 'strat' : name, - 'display' : strategy.name }); + options.openStrategies.push({ + 'strat': name, + 'display': strategy.name + }); } } } @@ -672,15 +686,15 @@ exports.edit = function (req, res, next) { scriptsList.listScripts({ _authorId: user._id, isLib: null, flagged: null }, { size: -1 }, '/user/edit', - function (scriptsList) { + function(scriptsList) { scriptsList.edit = true; options.scriptsList = scriptsList; res.render('userEdit', options); - }); + }); }); }; -exports.newScriptPage = function (req, res, next) { +exports.newScriptPage = function(req, res, next) { var authedUser = req.session.user; if (!authedUser) return res.redirect('/login'); @@ -712,7 +726,7 @@ exports.newScriptPage = function (req, res, next) { }); }; -exports.newLibraryPage = function (req, res, next) { +exports.newLibraryPage = function(req, res, next) { var authedUser = req.session.user; if (!authedUser) return res.redirect('/login'); @@ -744,7 +758,7 @@ exports.newLibraryPage = function (req, res, next) { }); }; -exports.userGitHubRepoListPage = function (req, res, next) { +exports.userGitHubRepoListPage = function(req, res, next) { var authedUser = req.session.user; if (!authedUser) return res.redirect('/login'); @@ -770,8 +784,7 @@ exports.userGitHubRepoListPage = function (req, res, next) { pagination.itemsPerPage = 30; // GitHub Default //--- Tasks - - tasks.push(function(callback){ + tasks.push(function(callback) { async.waterfall([ // githubUser @@ -805,7 +818,7 @@ exports.userGitHubRepoListPage = function (req, res, next) { // callback(null, githubRepoList); // }, function(githubRepoList, callback) { - _.each(githubRepoList, function(githubRepo){ + _.each(githubRepoList, function(githubRepo) { var url = authedUser.userGitHubRepoPageUrl; url = helpers.updateUrlQueryString(url, { user: options.githubUser.login, @@ -836,7 +849,7 @@ exports.userGitHubRepoListPage = function (req, res, next) { }); }; -exports.userGitHubImportScriptPage = function (req, res, next) { +exports.userGitHubImportScriptPage = function(req, res, next) { var authedUser = req.session.user; if (!authedUser) return res.redirect('/login'); @@ -865,14 +878,14 @@ exports.userGitHubImportScriptPage = function (req, res, next) { async.waterfall([ // Validate blob - function(callback){ + function(callback) { github.gitdata.getJavascriptBlobs({ user: encodeURIComponent(githubUserId), repo: encodeURIComponent(githubRepoName), }, callback); }, - function(javascriptBlobs, callback){ - var javascriptBlob = _.findWhere(javascriptBlobs, {path: githubBlobPath}); + function(javascriptBlobs, callback) { + var javascriptBlob = _.findWhere(javascriptBlobs, { path: githubBlobPath }); javascriptBlob = parseJavascriptBlob(javascriptBlob); @@ -884,19 +897,19 @@ exports.userGitHubImportScriptPage = function (req, res, next) { }, // - function(callback){ + function(callback) { github.usercontent.getBlobAsUtf8({ user: encodeURIComponent(githubUserId), repo: encodeURIComponent(githubRepoName), path: encodeURIComponent(githubBlobPath), }, callback); }, - function(blobUtf8, callback){ + function(blobUtf8, callback) { // Double check file size. if (blobUtf8.length > settings.maximum_upload_script_size) return callback(util.format('File size is larger than maximum (%s bytes).', settings.maximum_upload_script_size)); - var onScriptStored = function(script){ + var onScriptStored = function(script) { if (script) { options.script = script; callback(null); @@ -938,7 +951,7 @@ exports.userGitHubImportScriptPage = function (req, res, next) { }); }; -exports.userGitHubRepoPage = function (req, res, next) { +exports.userGitHubRepoPage = function(req, res, next) { var authedUser = req.session.user; if (!authedUser) return res.redirect('/login'); @@ -978,15 +991,15 @@ exports.userGitHubRepoPage = function (req, res, next) { //--- Tasks - tasks.push(function(callback){ + tasks.push(function(callback) { async.waterfall([ - function(callback){ + function(callback) { github.repos.get({ user: encodeURIComponent(githubUserId), repo: encodeURIComponent(githubRepoName), }, callback); }, - function(repo, callback){ + function(repo, callback) { options.repo = repo; github.gitdata.getJavascriptBlobs({ @@ -994,9 +1007,9 @@ exports.userGitHubRepoPage = function (req, res, next) { repo: encodeURIComponent(repo.name), }, callback); }, - function(javascriptBlobs, callback){ + function(javascriptBlobs, callback) { options.javascriptBlobs = javascriptBlobs; - _.each(javascriptBlobs, function(javascriptBlob){ + _.each(javascriptBlobs, function(javascriptBlob) { // Urls javascriptBlob.userGitHubImportPageUrl = helpers.updateUrlQueryString(authedUser.userGitHubImportPageUrl, { user: githubUserId, @@ -1053,7 +1066,7 @@ var parseJavascriptBlob = function(javascriptBlob) { }; // Sloppy code to let a user add scripts to their acount -exports.userManageGitHubPage = function (req, res, next) { +exports.userManageGitHubPage = function(req, res, next) { var authedUser = req.session.user; if (!authedUser) return res.redirect('/login'); @@ -1074,12 +1087,12 @@ exports.userManageGitHubPage = function (req, res, next) { // var TOO_MANY_SCRIPTS = 'GitHub user has too many scripts to batch import.'; - tasks.push(function(callback){ + tasks.push(function(callback) { var githubUserName = req.query.user || authedUser.ghUsername; async.waterfall([ // authedUser.ghUsername - function(callback){ + function(callback) { if (githubUserName || authedUser.ghUsername) { callback(null); } else { @@ -1110,7 +1123,7 @@ exports.userManageGitHubPage = function (req, res, next) { } }, // Fetch repos and format for template. - function(callback){ + function(callback) { console.log(githubUserName); var repoManager = RepoManager.getManager(githubUserName, authedUser); repoManager.fetchRecentRepos(function() { @@ -1122,10 +1135,10 @@ exports.userManageGitHubPage = function (req, res, next) { }); }, // Import repos. - function(repos, callback){ + function(repos, callback) { var loadable = {}; console.log(req.body); - _.each(req.body, function(repo, reponame){ + _.each(req.body, function(repo, reponame) { // Load all scripts in the repo if (typeof repo === 'string' && reponame.substr(-4) === '_all') { reponame = repo; @@ -1151,7 +1164,7 @@ exports.userManageGitHubPage = function (req, res, next) { if (_.size(loadable) > 0) { console.log('loadScripts'); var githubUserName = authedUser.ghUsername; - RepoManager.getManager(githubUserName, authedUser, loadable).loadScripts(function () { + RepoManager.getManager(githubUserName, authedUser, loadable).loadScripts(function() { console.log('preredirect'); res.redirect(authedUser.userScriptListPageUrl); console.log('redirect'); @@ -1166,7 +1179,7 @@ exports.userManageGitHubPage = function (req, res, next) { //--- - async.parallel(tasks, function(err){ + async.parallel(tasks, function(err) { if (err) { return statusCodePage(req, res, next, { statusMessage: err, @@ -1178,7 +1191,7 @@ exports.userManageGitHubPage = function (req, res, next) { }); }; -exports.uploadScript = function (req, res, next) { +exports.uploadScript = function(req, res, next) { var user = req.session.user; var isLib = req.route.params.isLib; var userjsRegex = /\.user\.js$/; @@ -1191,7 +1204,7 @@ exports.uploadScript = function (req, res, next) { } form = new formidable.IncomingForm(); - form.parse(req, function (err, fields, files) { + form.parse(req, function(err, fields, files) { var script = files.script; var stream = null; var bufs = []; @@ -1204,37 +1217,37 @@ exports.uploadScript = function (req, res, next) { } stream = fs.createReadStream(script.path); - stream.on('data', function (d) { bufs.push(d); }); + stream.on('data', function(d) { bufs.push(d); }); - stream.on('end', function () { - User.findOne({ _id: user._id }, function (err, user) { + stream.on('end', function() { + User.findOne({ _id: user._id }, function(err, user) { var scriptName = fields.script_name; if (isLib) { scriptStorage.storeScript(user, scriptName, Buffer.concat(bufs), - function (script) { + function(script) { if (!script) { return res.redirect(failUrl); } res.redirect('/libs/' + encodeURI(script.installName .replace(jsRegex, ''))); }); - } else { - scriptStorage.getMeta(bufs, function (meta) { - scriptStorage.storeScript(user, meta, Buffer.concat(bufs), - function (script) { - if (!script) { return res.redirect(failUrl); } - - res.redirect('/scripts/' + encodeURI(script.installName - .replace(userjsRegex, ''))); - }); - }); - } + } else { + scriptStorage.getMeta(bufs, function(meta) { + scriptStorage.storeScript(user, meta, Buffer.concat(bufs), + function(script) { + if (!script) { return res.redirect(failUrl); } + + res.redirect('/scripts/' + encodeURI(script.installName + .replace(userjsRegex, ''))); + }); + }); + } }); }); }); }; // post route to update a user's account -exports.update = function (req, res, next) { +exports.update = function(req, res, next) { var user = req.session.user; var scriptUrls = req.body.urls ? Object.keys(req.body.urls) : ''; var installRegex = null; @@ -1246,28 +1259,28 @@ exports.update = function (req, res, next) { if (typeof req.body.about !== 'undefined') { // Update the about section of a user's profile User.findOneAndUpdate({ _id: user._id }, - { about: req.body.about }, - function (err, user) { + { about: req.body.about }, + function(err, user) { if (err) { res.redirect('/'); } req.session.user.about = user.about; res.redirect('/users/' + user.name); - }); + }); } else { // Remove scripts (currently no UI) installRegex = new RegExp('^\/install\/(' + username + '\/.+)$'); - scriptUrls.forEach(function (url) { + scriptUrls.forEach(function(url) { var matches = installRegex.exec(url); if (matches && matches[1]) { installNames.push(matches[1]); } }); - async.each(installNames, scriptStorage.deleteScript, function () { + async.each(installNames, scriptStorage.deleteScript, function() { res.redirect('/users/' + user.name); }); } }; // Submit a script through the web editor -exports.submitSource = function (req, res, next) { +exports.submitSource = function(req, res, next) { var user = req.session.user; var isLib = req.route.params.isLib; var source = null; @@ -1279,8 +1292,8 @@ exports.submitSource = function (req, res, next) { var userjsRegex = /\.user\.js$/; var jsRegex = /\.js$/; - User.findOne({ _id: user._id }, function (err, user) { - scriptStorage.storeScript(user, meta, source, function (script) { + User.findOne({ _id: user._id }, function(err, user) { + scriptStorage.storeScript(user, meta, source, function(script) { var redirectUrl = encodeURI(script ? (script.isLib ? '/libs/' + script.installName.replace(jsRegex, '') : '/scripts/' + script.installName.replace(userjsRegex, '')) : req.body.url); @@ -1290,20 +1303,21 @@ exports.submitSource = function (req, res, next) { } Script.findOne({ installName: req.body.original }, - function (err, origScript) { + function(err, origScript) { var fork = null; if (err || !origScript) { return res.redirect(redirectUrl); } fork = origScript.fork || []; - fork.unshift({ author: origScript.author, url: origScript - .installName.replace(origScript.isLib ? jsRegex : userjsRegex, '') + fork.unshift({ + author: origScript.author, url: origScript + .installName.replace(origScript.isLib ? jsRegex : userjsRegex, '') }); script.fork = fork; - script.save(function (err, script) { + script.save(function(err, script) { res.redirect(redirectUrl); }); - }); + }); }); }); } @@ -1314,14 +1328,14 @@ exports.submitSource = function (req, res, next) { if (isLib) { storeScript(req.body.script_name, source); } else { - scriptStorage.getMeta([source], function (meta) { + scriptStorage.getMeta([source], function(meta) { if (!meta || !meta.name) { return res.redirect(url); } storeScript(meta, source); }); } }; -function getExistingScript (req, options, authedUser, callback) { +function getExistingScript(req, options, authedUser, callback) { options.isLib = req.route.params.isLib; if (!req.route.params.scriptname) { @@ -1339,7 +1353,7 @@ function getExistingScript (req, options, authedUser, callback) { callback(options); } else { req.route.params.scriptname += options.isLib ? '.js' : '.user.js'; - scriptStorage.getSource(req, function (script, stream) { + scriptStorage.getSource(req, function(script, stream) { var bufs = []; var collaborators = []; @@ -1353,8 +1367,8 @@ function getExistingScript (req, options, authedUser, callback) { } } - stream.on('data', function (d) { bufs.push(d); }); - stream.on('end', function () { + stream.on('data', function(d) { bufs.push(d); }); + stream.on('end', function() { options.title = 'Edit ' + script.name; options.source = Buffer.concat(bufs).toString('utf8'); options.original = script.installName; @@ -1372,7 +1386,7 @@ function getExistingScript (req, options, authedUser, callback) { } } -function pageMeta (options) { +function pageMeta(options) { options.title = (options.title || '') + ' | OpenUserJS.org'; options.pageMetaDescription = 'Download Userscripts to enhance your browser.'; var pageMetaKeywords = ['userscript', 'greasemonkey']; @@ -1382,7 +1396,7 @@ function pageMeta (options) { return options; } -exports.editScript = function (req, res, next) { +exports.editScript = function(req, res, next) { var authedUser = req.session.user; // @@ -1400,15 +1414,15 @@ exports.editScript = function (req, res, next) { // Get the info and source for an existing script for the editor // Also works for writing a new script - tasks.push(function (callback) { - getExistingScript(req, options, authedUser, function (opts) { + tasks.push(function(callback) { + getExistingScript(req, options, authedUser, function(opts) { options = opts; callback(!opts); }); }); //--- - async.parallel(tasks, function(err){ + async.parallel(tasks, function(err) { if (err) return next(); res.render('pages/scriptViewSourcePage', options); @@ -1416,15 +1430,15 @@ exports.editScript = function (req, res, next) { }; // route to flag a user -exports.flag = function (req, res, next) { +exports.flag = function(req, res, next) { var username = req.route.params.username; var unflag = req.route.params.unflag; - User.findOne({ name: username }, function (err, user) { + User.findOne({ name: username }, function(err, user) { var fn = flagLib[unflag && unflag === 'unflag' ? 'unflag' : 'flag']; if (err || !user) { return next(); } - fn(User, user, req.session.user, function (flagged) { + fn(User, user, req.session.user, function(flagged) { res.redirect('/users/' + username); }); }); diff --git a/libs/collectiveRating.js b/libs/collectiveRating.js index 2cd64a3c9..38e65a38a 100644 --- a/libs/collectiveRating.js +++ b/libs/collectiveRating.js @@ -1,14 +1,14 @@ var Script = require('../models/script').Script; -function median (values) { +function median(values) { var middle = Math.floor(values.length / 2); - values.sort(function (a, b) { return a - b; }); + values.sort(function(a, b) { return a - b; }); - return values.length % 2 ? values[middle] : + return values.length % 2 ? values[middle] : (values[middle - 1] + values[middle]) / 2; } -function mean (values) { +function mean(values) { var sum = 0; var i = 0; for (; i < values.length; ++i) { @@ -21,12 +21,12 @@ function mean (values) { // Generate a collective rating by averaging the median and mean of // scripts in a group. I think this gives a more fair rating than just // using one of them alone. -function getRating (scripts) { +function getRating(scripts) { var ratings = null; if (scripts.length < 2) { return 0; } - ratings = scripts.map(function (script) { + ratings = scripts.map(function(script) { return script.rating; }); @@ -34,13 +34,13 @@ function getRating (scripts) { } exports.getRating = getRating; -// TODO: Memoize this function with an +// TODO: Memoize this function with an // expiring cache (either memory or DB based) to // speed up voting and flagging -exports.getKarma = function (user, maxKarma, callback) { +exports.getKarma = function(user, maxKarma, callback) { var ratings = []; var karma = 0; - Script.find({ _authorId: user._id }, 'rating', function (err, scripts) { + Script.find({ _authorId: user._id }, 'rating', function(err, scripts) { if (err) { return callback(karma); } karm = Math.floor(getRating(scripts) / 10); diff --git a/libs/flag.js b/libs/flag.js index 5fab470f2..ff06d957d 100644 --- a/libs/flag.js +++ b/libs/flag.js @@ -7,7 +7,7 @@ var maxKarma = 10; // Determine whether content can be flagged by a user. // This is heavily commented so that my logic and // reasoning is documented for myself and others. -function flaggable (model, content, user, callback) { +function flaggable(model, content, user, callback) { // Not logged in. if (!user) { return callback(false); } @@ -17,12 +17,12 @@ function flaggable (model, content, user, callback) { // It is not the responsibility of the community // to police the site administration if (model.modelName === 'User') { - return getFlag(model, content, user, function (flag) { + return getFlag(model, content, user, function(flag) { callback(content._id != user._id && content.role > 2, content, flag); }); } - getAuthor(content, function (author) { + getAuthor(content, function(author) { // Content without an author shouldn't exist if (!author) { return callback(false); } @@ -33,7 +33,7 @@ function flaggable (model, content, user, callback) { if (author.role < 3) { return callback(author.role > 2, author); } // You can't flag something twice - getFlag(model, content, user, function (flag) { + getFlag(model, content, user, function(flag) { return callback(!flag, author, flag); }); }); @@ -45,13 +45,13 @@ function getFlag(model, content, user, callback) { 'model': model.modelName, '_contentId': content._id, '_userId': user._id - }, function (err, flag) { + }, function(err, flag) { callback(err || !flag ? null : flag); }); } -function getAuthor (content, callback) { - User.findOne({ _id: content._authorId }, function (err, author) { +function getAuthor(content, callback) { + User.findOne({ _id: content._authorId }, function(err, author) { // Content without an author shouldn't exist if (err || !author) { return callback(null); } @@ -60,7 +60,7 @@ function getAuthor (content, callback) { } exports.getAuthor = getAuthor; -function getThreshold (model, content, author, callback) { +function getThreshold(model, content, author, callback) { // Admins can't be flagged so they have no threshold if (author.role < 3) { return callback(null); } @@ -72,35 +72,35 @@ function getThreshold (model, content, author, callback) { var threshold = thresholds[model.modelName] * (author.role < 4 ? 2 : 1); // Calculate karma and add it to the threshold - getKarma(author, maxKarma, function (karma) { + getKarma(author, maxKarma, function(karma) { return callback(threshold + karma); }); } exports.getThreshold = getThreshold; -function saveContent (model, content, author, flags, callback) { +function saveContent(model, content, author, flags, callback) { if (!content.flags) { content.flags = 0; } content.flags += flags; if (content.flags >= thresholds[model.modelName] * (author.role < 4 ? 2 : 1)) { - return getThreshold(model, content, author, function (threshold) { + return getThreshold(model, content, author, function(threshold) { content.flagged = content.flags >= threshold; - content.save(function (err, content) { callback(content.flagged); }); + content.save(function(err, content) { callback(content.flagged); }); }); } - content.save(function (err, content) { callback(content.flagged); }); + content.save(function(err, content) { callback(content.flagged); }); } exports.saveContent = saveContent; -function flag (model, content, user, author, callback) { +function flag(model, content, user, author, callback) { var flag = new Flag({ 'model': model.modelName, '_contentId': content._id, '_userId': user._id }); - flag.save(function (err, flag) { + flag.save(function(err, flag) { if (!content.flags) { content.flags = 0; } if (!content.flagged) { content.flagged = false; } @@ -108,25 +108,25 @@ function flag (model, content, user, author, callback) { }); } -exports.flag = function (model, content, user, callback) { - flaggable(model, content, user, function (canFlag, author) { +exports.flag = function(model, content, user, callback) { + flaggable(model, content, user, function(canFlag, author) { if (!canFlag) { return callback(false); } flag(model, content, user, author, callback); }); }; -exports.unflag = function (model, content, user, callback) { +exports.unflag = function(model, content, user, callback) { if (!user) { return callback(null); } - getFlag(model, content, user, function (flag) { + getFlag(model, content, user, function(flag) { if (!flag) { return callback(null); } if (!content.flags) { content.flags = 0; } if (!content.flagged) { content.flagged = false; } - function removeFlag (author) { - flag.remove(function (err) { + function removeFlag(author) { + flag.remove(function(err) { saveContent(model, content, author, user.role < 4 ? -2 : -1, callback); }); } diff --git a/libs/githubClient.js b/libs/githubClient.js index ce9988ef9..525b471f5 100644 --- a/libs/githubClient.js +++ b/libs/githubClient.js @@ -6,7 +6,7 @@ var request = require('request'); // Client var github = new GitHubApi({ - version: "3.0.0", + version: "3.0.0" }); module.exports = github; @@ -32,12 +32,12 @@ Strategy.findOne({ name: 'github' }, function(err, strat) { // Util functions for the client. github.usercontent = github.usercontent || {}; -var githubGitDataGetBlobAsUtf8 = function (msg, callback) { +var githubGitDataGetBlobAsUtf8 = function(msg, callback) { async.waterfall([ - function(callback){ + function(callback) { github.gitdata.getBlob(msg, callback); }, - function(blob, callback){ + function(blob, callback) { var content = blob.content; if (blob.encoding == 'base64') { var buf = new Buffer(content, 'base64'); @@ -49,18 +49,18 @@ var githubGitDataGetBlobAsUtf8 = function (msg, callback) { }; github.gitdata.getBlobAsUtf8 = githubGitDataGetBlobAsUtf8; -var githubUserContentBuildUrl = function (user, repo, path) { +var githubUserContentBuildUrl = function(user, repo, path) { return util.format('https://raw.githubusercontent.com/%s/%s/HEAD/%s', user, repo, path); }; github.usercontent.buildUrl = githubUserContentBuildUrl; -var githubUserContentGetBlobAsUtf8 = function (msg, callback) { +var githubUserContentGetBlobAsUtf8 = function(msg, callback) { async.waterfall([ - function(callback){ + function(callback) { var url = githubUserContentBuildUrl(msg.user, msg.repo, msg.path); request.get(url, callback); }, - function(response, body, callback){ + function(response, body, callback) { if (response.statusCode != 200) return callback(util.format('Status Code %s', response.statusCode)); @@ -76,16 +76,16 @@ var githubGitDataIsJavascriptBlob = function(blob) { }; github.gitdata.isJavascriptBlob = githubGitDataIsJavascriptBlob; -var githubGitDataGetJavascriptBlobs = function (msg, callback) { +var githubGitDataGetJavascriptBlobs = function(msg, callback) { async.waterfall([ - function(callback){ + function(callback) { msg.sha = 'HEAD'; msg.recursive = true; github.gitdata.getTree(msg, callback); }, - function(repoTree, callback){ + function(repoTree, callback) { var entries = repoTree.tree; - var blobs = _.where(entries, {type: 'blob'}); + var blobs = _.where(entries, { type: 'blob' }); var javascriptBlobs = _.filter(blobs, githubGitDataIsJavascriptBlob); callback(null, javascriptBlobs); }, diff --git a/libs/helpers.js b/libs/helpers.js index 71ee6b685..19bae079a 100644 --- a/libs/helpers.js +++ b/libs/helpers.js @@ -22,12 +22,12 @@ var day = hour * 24; var week = day * 7; // Get a formatted date that can be used everywhere a date is displayed -exports.formatDate = function (date) { +exports.formatDate = function(date) { var difference = new Date().getTime() - date.getTime(); var ret = ''; var days = 0; - function pluralize (number, unit) { + function pluralize(number, unit) { return number + ' ' + unit + (number > 1 ? 's' : '') + ' ago'; } @@ -54,12 +54,12 @@ exports.formatDate = function (date) { } // Create an object with no properties -exports.nil = function (obj) { +exports.nil = function(obj) { var nilObj = Object.create(null); if (!obj) return nilObj; - exports.forIn(obj, function (val, key) { + exports.forIn(obj, function(val, key) { nilObj[key] = val; }); @@ -67,7 +67,7 @@ exports.nil = function (obj) { }; // Safely iterate on an object not create using nil() -exports.forIn = function (obj, forProp) { +exports.forIn = function(obj, forProp) { var key = null; for (key in obj) { @@ -78,9 +78,9 @@ exports.forIn = function (obj, forProp) { // Clean filenames but leave them readable // Based on Greasemonkey modules/remoteScript.js -exports.cleanFilename = function (filename, defaultName) { +exports.cleanFilename = function(filename, defaultName) { // Blacklist problem characters (slashes, colons, etc.). - var cleanName = (filename || '').replace(/[\\\/:*?\'\"<>|#;@=&]/g, '') + var cleanName = (filename || '').replace(/[\\\/:*?\'\"<>|#;@=&]/g, ''); // Make whitespace readable. .replace(/(\s|%20)+/g, '_'); @@ -107,7 +107,7 @@ exports.setUrlQueryValue = setUrlQueryValue; exports.updateUrlQueryString = function(baseUrl, dict) { var url = baseUrl; - _.each(dict, function(value, key){ + _.each(dict, function(value, key) { url = setUrlQueryValue(url, key, value); }); return url; diff --git a/libs/markdown.js b/libs/markdown.js index 09de13f83..1051140a2 100644 --- a/libs/markdown.js +++ b/libs/markdown.js @@ -14,7 +14,7 @@ var allWhitelistAttrs = htmlWhitelistPost.allowedAttributes.all; // Whitelist a bunch of attributes for all tags // Doing this until we have an upstream fix -htmlWhitelistPost.allowedTags.forEach(function (tag) { +htmlWhitelistPost.allowedTags.forEach(function(tag) { var otherAttrs = htmlWhitelistPost.allowedAttributes[tag]; htmlWhitelistPost.allowedAttributes[tag] = allWhitelistAttrs; @@ -25,19 +25,19 @@ htmlWhitelistPost.allowedTags.forEach(function (tag) { }); delete htmlWhitelistPost.allowedAttributes.all; -function sanitize (html) { +function sanitize(html) { return sanitizeHtml(html, htmlWhitelistPost); } // Sanitize the output from the block level renderers -blockRenderers.forEach(function (type) { - renderer[type] = function () { +blockRenderers.forEach(function(type) { + renderer[type] = function() { return sanitize(marked.Renderer.prototype[type].apply(renderer, arguments)); }; }); // Automatically generate an anchor for each header -renderer.heading = function (text, level) { +renderer.heading = function(text, level) { var escapedText = text.toLowerCase().replace(/<\/?[^>]+?>/g, '') .replace(/[^\w]+/g, '-'); @@ -54,7 +54,7 @@ renderer.heading = function (text, level) { // Set the options to use for rendering markdown marked.setOptions({ - highlight: function (code, lang) { + highlight: function(code, lang) { if (lang && hljs.getLanguage(lang)) { return hljs.highlight(lang, code).value; } else { @@ -71,6 +71,6 @@ marked.setOptions({ smartypants: false }); -exports.renderMd = function (text) { +exports.renderMd = function(text) { return marked(text); }; diff --git a/libs/modelParser.js b/libs/modelParser.js index a2a0bc01c..9acab6462 100644 --- a/libs/modelParser.js +++ b/libs/modelParser.js @@ -17,19 +17,19 @@ var parseModelFnMap = {}; */ moment.lang('en', { - relativeTime : { + relativeTime: { future: "in %s", - past: "%s ago", - s: function(number, withoutSuffix, key, isFuture){ return number + "s"; }, - m: "1m", + past: "%s ago", + s: function(number, withoutSuffix, key, isFuture) { return number + "s"; }, + m: "1m", mm: "%dm", - h: "1h", + h: "1h", hh: "%dh", - d: "1D", + d: "1D", dd: "%dD", - M: "1M", + M: "1M", MM: "%dM", - y: "1Y", + y: "1Y", yy: "%dY" } }); @@ -85,7 +85,7 @@ var parseScript = function(scriptData) { // Author if (_.isString(script.author)) { - script.author = parseUser({name: script.author}); + script.author = parseUser({ name: script.author }); } // Icons @@ -214,16 +214,16 @@ var parseGroup = function(groupData) { // Wait two hours between group rating updates // This calculation runs in the background - if (new Date().getTime() > (group.updated.getTime() + 1000*60*60*2)) { + if (new Date().getTime() > (group.updated.getTime() + 1000 * 60 * 60 * 2)) { Script.find({ _id: { $in: group._scriptIds } - }, function (err, scripts) { + }, function(err, scripts) { if (!err && scripts.length > 1) { group.rating = getRating(scripts); } group.updated = new Date(); - group.save(function(err, group){ + group.save(function(err, group) { console.log(util.format('Group(%s) Rating Updated', group.name)); }); }); @@ -257,7 +257,7 @@ var parseDiscussion = function(discussionData) { recentCommentors.push(discussion.author); if (discussion.lastCommentor != discussion.author) recentCommentors.push(discussion.lastCommentor); - recentCommentors = _.map(recentCommentors, function(username){ + recentCommentors = _.map(recentCommentors, function(username) { return { name: username, }; @@ -311,7 +311,6 @@ exports.renderComment = function(comment) { comment.contentRendered = renderMd(comment.content); }; - /** * Category */ @@ -341,7 +340,7 @@ var parseCategory = function(categoryData) { category.categoryPostDiscussionPageUrl = '/post/' + category.slug; // Functions - category.canUserPostTopic = function (user) { + category.canUserPostTopic = function(user) { return canUserPostTopicToCategory(user, category); }; @@ -350,7 +349,6 @@ var parseCategory = function(categoryData) { parseModelFnMap.Category = parseCategory; exports.parseCategory = parseCategory; - /** * Remove */ @@ -359,7 +357,7 @@ var getRemovedItemDescription = function(remove) { if (!remove.content) return 'No content'; - switch(remove.model) { + switch (remove.model) { case 'User': return remove.content.name; case 'Script': @@ -382,7 +380,7 @@ var parseRemovedItem = function(removedItemData) { parseDateProperty(removedItem, 'removed'); // User - removedItem.remover = parseUser({name: removedItem.removerName}); + removedItem.remover = parseUser({ name: removedItem.removerName }); // Content var parseModelFn = parseModelFnMap[removedItem.model]; @@ -399,4 +397,3 @@ var parseRemovedItem = function(removedItemData) { }; parseModelFnMap.Remove = parseRemovedItem; exports.parseRemovedItem = parseRemovedItem; - diff --git a/libs/modelQuery.js b/libs/modelQuery.js index bab569585..225760b27 100644 --- a/libs/modelQuery.js +++ b/libs/modelQuery.js @@ -12,7 +12,7 @@ var findOrDefaultIfNull = function(query, key, value, defaultValue) { condition[key] = null; conditions.push(condition); } - query.and({$or: conditions}); + query.and({ $or: conditions }); }; exports.findOrDefaultIfNull = findOrDefaultIfNull; @@ -40,29 +40,29 @@ var parseSearchConditions = function(q, prefixSearchFields, fullSearchFields) { var fullStr = ''; var prefixRegex = null; var fullRegex = null; - var terms = q.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1').split(/\s+/).map(function (e) { return e.trim(); }); + var terms = q.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1').split(/\s+/).map(function(e) { return e.trim(); }); // Match all the terms but in any order - terms.forEach(function (term) { + terms.forEach(function(term) { var isNonASCII = /^\W/.test(term); if (isNonASCII) { - prefixStr += '(?=.*?([ \n\r\t.,\'"\+!?-]+)' + term + ')'; + prefixStr += '(?=.*?([ \n\r\t.,\'"\+!?-]+)' + term + ')'; } else { - prefixStr += '(?=.*?\\b' + term + ')'; + prefixStr += '(?=.*?\\b' + term + ')'; } - fullStr += '(?=.*?' + term + ')'; + fullStr += '(?=.*?' + term + ')'; }); prefixRegex = new RegExp(prefixStr, 'i'); fullRegex = new RegExp(fullStr, 'i'); // One of the searchable fields must match the conditions - prefixSearchFields.forEach(function (prop) { + prefixSearchFields.forEach(function(prop) { var condition = {}; condition[prop] = prefixRegex; conditions.push(condition); }); - fullSearchFields.forEach(function (prop) { + fullSearchFields.forEach(function(prop) { var condition = {}; condition[prop] = fullRegex; conditions.push(condition); @@ -126,7 +126,6 @@ var parseRemovedItemSearchQuery = function(removedItemListQuery, query) { }; exports.parseCommentSearchQuery = parseCommentSearchQuery; - var applyModelListQueryFlaggedFilter = function(modelListQuery, options, flaggedQuery) { // Only list flagged items if authedUser >= moderator or if authedUser owns the item. if (options.isYou || options.isMod) { @@ -145,7 +144,7 @@ var applyModelListQueryFlaggedFilter = function(modelListQuery, options, flagged } else { // Hide // Script.flagged is undefined by default. - modelListQuery.and({flagged: {$ne: true}}); + modelListQuery.and({ flagged: { $ne: true } }); } }; exports.applyModelListQueryFlaggedFilter = applyModelListQueryFlaggedFilter; @@ -167,9 +166,8 @@ var applyModelListQueryDefaults = function(modelListQuery, options, req, default if (defaultOptions.filterFlaggedItems) applyModelListQueryFlaggedFilter(modelListQuery, options, req.query.flagged); - // Sort - parseModelListSort(modelListQuery, req.query.orderBy, req.query.orderDir, function(){ + parseModelListSort(modelListQuery, req.query.orderBy, req.query.orderDir, function() { modelListQuery.sort(defaultOptions.defaultSort); }); @@ -184,7 +182,7 @@ exports.applyCommentListQueryDefaults = function(commentListQuery, options, req) defaultSort: 'created', parseSearchQueryFn: parseCommentSearchQuery, searchBarPlaceholder: 'Search Comments', - filterFlaggedItems: true, + filterFlaggedItems: true }); // Populate @@ -200,7 +198,7 @@ exports.applyDiscussionListQueryDefaults = function(discussionListQuery, options defaultSort: '-updated -rating', parseSearchQueryFn: parseDiscussionSearchQuery, searchBarPlaceholder: 'Search Topics', - filterFlaggedItems: true, + filterFlaggedItems: true }); }; @@ -209,7 +207,7 @@ exports.applyGroupListQueryDefaults = function(groupListQuery, options, req) { defaultSort: '-rating name', parseSearchQueryFn: parseGroupSearchQuery, searchBarPlaceholder: 'Search Groups', - filterFlaggedItems: true, + filterFlaggedItems: true }); }; @@ -218,7 +216,7 @@ var scriptListQueryDefaults = { parseSearchQueryFn: parseScriptSearchQuery, searchBarPlaceholder: 'Search Scripts', searchBarFormAction: '/', - filterFlaggedItems: true, + filterFlaggedItems: true }; exports.scriptListQueryDefaults = scriptListQueryDefaults; exports.applyScriptListQueryDefaults = function(scriptListQuery, options, req) { @@ -231,9 +229,9 @@ var libraryListQueryDefaults = { searchBarPlaceholder: 'Search Libraries', searchBarFormAction: '/', searchBarFormHiddenVariables: [ - {name: 'library', value: 'true'}, + { name: 'library', value: 'true' }, ], - filterFlaggedItems: true, + filterFlaggedItems: true }; exports.libraryListQueryDefaults = libraryListQueryDefaults; exports.applyLibraryListQueryDefaults = function(libraryListQuery, options, req) { @@ -245,7 +243,7 @@ exports.applyUserListQueryDefaults = function(userListQuery, options, req) { defaultSort: 'name', parseSearchQueryFn: parseUserSearchQuery, searchBarPlaceholder: 'Search Users', - filterFlaggedItems: true, + filterFlaggedItems: true }); }; @@ -254,6 +252,6 @@ exports.applyRemovedItemListQueryDefaults = function(removedItemListQuery, optio defaultSort: '-removed', parseSearchQueryFn: parseRemovedItemSearchQuery, searchBarPlaceholder: 'Search Removed Items', - filterFlaggedItems: false, + filterFlaggedItems: false }); }; diff --git a/libs/modelsList.js b/libs/modelsList.js index bf93a5e5c..1578872a8 100644 --- a/libs/modelsList.js +++ b/libs/modelsList.js @@ -10,9 +10,9 @@ var formatDate = require('./helpers').formatDate; var listSize = 10; // /scriptlist/size/:size/sort/:orderBy/dir/:direction/page/:page -// Get a list of scripts and build the options object +// Get a list of scripts and build the options object // for the corresponding Mustache partial template -exports.listScripts = function (query, params, baseUrl, callback) { +exports.listScripts = function(query, params, baseUrl, callback) { // Don't list flagged scripts by default if (query.flagged === null) { @@ -30,7 +30,7 @@ exports.listScripts = function (query, params, baseUrl, callback) { } listModels(Script, query, params, ['rating', 'installs', 'updated'], - function (scripts, scriptsList) { + function(scripts, scriptsList) { /*var headings = { 'name': { label: 'Name', width: 50 }, 'author': { label: 'Author', width: 15 }, @@ -41,10 +41,10 @@ exports.listScripts = function (query, params, baseUrl, callback) { var name = null; scriptsList.scripts = []; scriptsList.headings = []; - scriptsList.hasAuthor = params[4] ? + scriptsList.hasAuthor = params[4] ? params[4].indexOf('author') === -1 : true; - scripts.forEach(function (script) { + scripts.forEach(function(script) { var isLib = script.isLib || false; var scriptPath = script.installName .replace(isLib ? /\.js$/ : /\.user\.js$/, ''); @@ -52,7 +52,7 @@ exports.listScripts = function (query, params, baseUrl, callback) { editUrl.shift(); - scriptsList.scripts.push({ + scriptsList.scripts.push({ name: script.name, author: script.author, description: script.meta.description || '', @@ -72,7 +72,7 @@ exports.listScripts = function (query, params, baseUrl, callback) { heading = headings[name]; if (orderBy === name) { - heading.direction = '/dir/' + + heading.direction = '/dir/' + (direction === 'asc' ? 'desc' : 'asc'); } else { heading.direction = ''; @@ -82,22 +82,22 @@ exports.listScripts = function (query, params, baseUrl, callback) { scriptsList.headings.push(heading); }*/ - scriptsList.baseUrl = baseUrl + (query.isLib === true ? + scriptsList.baseUrl = baseUrl + (query.isLib === true ? '/liblist' : '/scriptlist'); callback(scriptsList); - }); + }); }; // /userlist/size/:size/sort/:orderBy/dir/:direction/page/:page -// Get a list of users and build the options object +// Get a list of users and build the options object // for the corresponding Mustache partial template -exports.listUsers = function (query, params, baseUrl, callback) { +exports.listUsers = function(query, params, baseUrl, callback) { listModels(User, query, params, ['name'], - function (users, usersList) { + function(users, usersList) { usersList.users = []; - users.forEach(function (user) { - usersList.users.push({ + users.forEach(function(user) { + usersList.users.push({ name: user.name, url: '/users/' + user.name, }); @@ -105,30 +105,30 @@ exports.listUsers = function (query, params, baseUrl, callback) { usersList.baseUrl = baseUrl + '/userlist'; callback(usersList); - }); + }); }; // /list/size/:size/sort/:orderBy/dir/:direction/page/:page -// Get a list of removed content and build the options object +// Get a list of removed content and build the options object // for the corresponding Mustache partial template -exports.listRemoved = function (query, params, baseUrl, callback) { +exports.listRemoved = function(query, params, baseUrl, callback) { listModels(Remove, query, params, ['removed'], - function (results, removedList) { + function(results, removedList) { removedList.removed = []; - results.forEach(function (result) { + results.forEach(function(result) { var content = result.content; var key = null; var contentArr = []; var val = null; - + for (key in content) { val = content[key]; val = val && typeof val === 'object' ? JSON.stringify(val) : val; contentArr.push({ 'key': key, 'value': val }); } - removedList.removed.push({ + removedList.removed.push({ remover: result.removerName, removed: formatDate(result.removed), reason: result.reason, @@ -138,19 +138,19 @@ exports.listRemoved = function (query, params, baseUrl, callback) { removedList.baseUrl = baseUrl + '/list'; callback(removedList); - }); + }); }; // /groups/list/size/:size/sort/:orderBy/dir/:direction/page/:page -// Get a list of groups and build the options object +// Get a list of groups and build the options object // for the corresponding Mustache partial template -exports.listGroups = function (query, params, baseUrl, callback) { +exports.listGroups = function(query, params, baseUrl, callback) { listModels(Group, query, params, ['rating'], - function (groups, groupsList) { + function(groups, groupsList) { groupsList.groups = []; - groups.forEach(function (group) { - groupsList.groups.push({ + groups.forEach(function(group) { + groupsList.groups.push({ name: group.name, url: '/group/' + group.name.replace(/\s+/g, '_'), size: group._scriptIds.length, @@ -159,34 +159,34 @@ exports.listGroups = function (query, params, baseUrl, callback) { // Wait two hours between group rating updates // This calculation runs in the background - if (new Date().getTime() > (group.updated.getTime() + 1000*60*60*2)) { + if (new Date().getTime() > (group.updated.getTime() + 1000 * 60 * 60 * 2)) { Script.find({ _id: { $in: group._scriptIds } }, - function (err, scripts) { + function(err, scripts) { if (!err && scripts.length > 1) { group.rating = getRating(scripts); } group.updated = new Date(); - group.save(function () {}); - }); + group.save(function() { }); + }); } }); groupsList.baseUrl = baseUrl + '/list'; callback(groupsList); - }); + }); }; // /list/size/:size/sort/:orderBy/dir/:direction/page/:page -// Get a list of discussions and build the options object +// Get a list of discussions and build the options object // for the corresponding Mustache partial template -exports.listDiscussions = function (query, params, baseUrl, callback) { +exports.listDiscussions = function(query, params, baseUrl, callback) { listModels(Discussion, query, params, ['updated', 'rating'], - function (discussions, discussionsList) { + function(discussions, discussionsList) { discussionsList.discussions = []; - discussions.forEach(function (discussion) { - discussionsList.discussions.push({ + discussions.forEach(function(discussion) { + discussionsList.discussions.push({ topic: discussion.topic, comments: discussion.comments, author: discussion.author, @@ -202,19 +202,19 @@ exports.listDiscussions = function (query, params, baseUrl, callback) { discussionsList.baseUrl = baseUrl + '/list'; callback(discussionsList); - }); + }); }; // /list/size/:size/sort/:orderBy/dir/:direction/page/:page -// Get a list of comments and build the options object +// Get a list of comments and build the options object // for the corresponding Mustache partial template -exports.listComments = function (query, params, baseUrl, callback) { +exports.listComments = function(query, params, baseUrl, callback) { listModels(Comment, query, params, ['created'], - function (comments, commentsList) { + function(comments, commentsList) { commentsList.comments = []; - comments.forEach(function (comment) { - commentsList.comments.push({ + comments.forEach(function(comment) { + commentsList.comments.push({ author: comment.author, content: renderMd(comment.content), created: formatDate(comment.created), @@ -225,14 +225,14 @@ exports.listComments = function (query, params, baseUrl, callback) { commentsList.baseUrl = baseUrl + '/list'; callback(commentsList); - }); + }); }; -// options = { +// options = { // size: (Number), orderBy: (String or Array or Object), // direction: (String), page: (Number), omit: (Array) // } -function listModels (model, query, options, defaultOrder, callback) { +function listModels(model, query, options, defaultOrder, callback) { var optArr = null; var fields = Object.keys(model.schema.tree); var orderBy = null; @@ -265,8 +265,8 @@ function listModels (model, query, options, defaultOrder, callback) { .instance === 'String' ? 1 : -1; params.sort[orderBy] = direction; } else if (orderBy instanceof Array) { - orderBy.forEach(function (order) { - params.sort[order] = -1 !== fields.indexOf(order) && + orderBy.forEach(function(order) { + params.sort[order] = -1 !== fields.indexOf(order) && model.schema.paths[order].instance === 'String' ? 1 : -1; }); } else if (typeof orderBy === 'object') { @@ -281,7 +281,7 @@ function listModels (model, query, options, defaultOrder, callback) { } if (options.omit instanceof Array) { - options.omit.forEach(function (field) { + options.omit.forEach(function(field) { var index = fields.indexOf(field); if (index > -1) { fields.splice(index, 1); } }); @@ -295,7 +295,7 @@ function listModels (model, query, options, defaultOrder, callback) { } model.find(query, omit, params, - function (err, models) { + function(err, models) { var list = {}; if (!models) { models = [] } if (size < 0) { size = models.length; } @@ -314,5 +314,5 @@ function listModels (model, query, options, defaultOrder, callback) { if (list.next) { models.pop(); } callback(models, list); - }); + }); }; diff --git a/libs/modifySessions.js b/libs/modifySessions.js index 7f8c3c449..521618335 100644 --- a/libs/modifySessions.js +++ b/libs/modifySessions.js @@ -1,8 +1,8 @@ // This library allows for the modifications of user sessions var async = require('async'); -exports.init = function (store) { - return function (req, res, next) { +exports.init = function(store) { + return function(req, res, next) { // http://www.senchalabs.org/connect/session.html // Keep a reference to the session store on the request // so we can access and modify its data later @@ -12,7 +12,7 @@ exports.init = function (store) { }; // Serialize a user model to something that can be stored in the session data -function serializeUser (user) { +function serializeUser(user) { var userObj = user.toObject(); // Some things don't need to be kept in the session store @@ -24,19 +24,19 @@ function serializeUser (user) { } // Add a new session id to the user model -exports.add = function (req, user, callback) { +exports.add = function(req, user, callback) { var store = req.sessionStore; - function finish (err, user) { + function finish(err, user) { req.session.user = serializeUser(user); callback(); } // Remove invalid session ids from user model if (user.sessionIds && user.sessionIds.length > 0) { - async.filter(user.sessionIds, function (id, cb) { - store.get(id, function (err, sess) { cb(!err && sess); }); - }, function (sessionIds) { + async.filter(user.sessionIds, function(id, cb) { + store.get(id, function(err, sess) { cb(!err && sess); }); + }, function(sessionIds) { // No duplicates if (sessionIds.indexOf(req.sessionID) === -1) { sessionIds.push(req.sessionID); @@ -52,8 +52,8 @@ exports.add = function (req, user, callback) { }; // Remove a session id from the user model -exports.remove = function (req, user, callback) { - var pos = user && user.sessionIds ? +exports.remove = function(req, user, callback) { + var pos = user && user.sessionIds ? user.sessionIds.indexOf(req.sessionID) : -1; delete req.session.user; @@ -67,14 +67,14 @@ exports.remove = function (req, user, callback) { }; // Update all sessions for a user -exports.update = function (req, user, callback) { +exports.update = function(req, user, callback) { var store = req.sessionStore; var userObj = user ? serializeUser(user) : null; if (!user || !user.sessionIds) { return callback('No sessions', null); } - async.each(user.sessionIds, function (id, cb) { - store.get(id, function (err, sess) { + async.each(user.sessionIds, function(id, cb) { + store.get(id, function(err, sess) { // Invalid session, will be removed on login if (err || !sess) { return cb(null); } @@ -85,20 +85,20 @@ exports.update = function (req, user, callback) { }; // Destory all sessions for a user -exports.destroy = function (req, user, callback) { +exports.destroy = function(req, user, callback) { var store = req.sessionStore; - var emptySess = { - cookie: { + var emptySess = { + cookie: { path: '/', _expires: null, originalMaxAge: null, - httpOnly: true + httpOnly: true } }; if (!user || !user.sessionIds) { return cb('No sessions', null); } - async.each(user.sessionIds, function (id, cb) { + async.each(user.sessionIds, function(id, cb) { store.set(id, emptySess, cb); }, callback); }; diff --git a/libs/muExpress.js b/libs/muExpress.js index 94621b287..ecd37dc00 100644 --- a/libs/muExpress.js +++ b/libs/muExpress.js @@ -2,7 +2,7 @@ var mu = require('mu2'); mu.root = __dirname + '/../views'; -function renderFile (res, path, options) { +function renderFile(res, path, options) { // If you need to render a file with a different content // type, do it directly on the response object if (process.env.NODE_ENV !== 'production') { mu.clearCache(); } @@ -12,18 +12,18 @@ function renderFile (res, path, options) { // Express doesn't have stream support for rendering templates // Hack express to add support for rendering a template with Mu -exports.renderFile = function (app) { +exports.renderFile = function(app) { var render = app.response.__proto__.render; - app.response.__proto__.render = function (view, options, fn) { + app.response.__proto__.render = function(view, options, fn) { var self = this; if (!fn && app.get('view engine') === 'html') { - fn = function (path, options) { renderFile(self, path, options); }; + fn = function(path, options) { renderFile(self, path, options); }; } render.call(self, view, options, fn); }; - return (function (path, options, fn) { fn(path, options); }); + return (function(path, options, fn) { fn(path, options); }); }; diff --git a/libs/passportLoader.js b/libs/passportLoader.js index c41e5e507..57684cb8e 100644 --- a/libs/passportLoader.js +++ b/libs/passportLoader.js @@ -12,7 +12,7 @@ exports.strategyInstances = nil(); // This will load a single passport // Notice it is general so it can load any passport strategy -exports.loadPassport = function (strategy) { +exports.loadPassport = function(strategy) { var requireStr = 'passport-' + strategy.name; var PassportStrategy = require(requireStr).Strategy; var instance = null; @@ -20,12 +20,12 @@ exports.loadPassport = function (strategy) { if (strategy.openid) { instance = new PassportStrategy( { - returnURL: AUTH_CALLBACK_BASE_URL + '/auth/' + strategy.name + '/callback/', - realm: AUTH_CALLBACK_BASE_URL + '/', + returnURL: AUTH_CALLBACK_BASE_URL + '/auth/' + strategy.name + '/callback/', + realm: AUTH_CALLBACK_BASE_URL + '/', profile: false, stateless: true }, - function () {} // we replace this callback later (_verify) + function() { } // we replace this callback later (_verify) ); } else { instance = new PassportStrategy( @@ -35,9 +35,9 @@ exports.loadPassport = function (strategy) { clientID: strategy.id, clientSecret: strategy.key, state: 'a bullshit string reddit requires', - callbackURL: AUTH_CALLBACK_BASE_URL + '/auth/' + strategy.name + '/callback/' + callbackURL: AUTH_CALLBACK_BASE_URL + '/auth/' + strategy.name + '/callback/' }, - function () {} // we replace this callback later (_verify) + function() { } // we replace this callback later (_verify) ); } diff --git a/libs/passportVerify.js b/libs/passportVerify.js index d93369b6f..ac0185170 100644 --- a/libs/passportVerify.js +++ b/libs/passportVerify.js @@ -5,7 +5,7 @@ var userRoles = require('../models/userRoles.json'); // This is a custom verification function used for Passports because // we needed something more powerful than what they provided -exports.verify = function (id, strategy, username, loggedIn, done) { +exports.verify = function(id, strategy, username, loggedIn, done) { var shasum = crypto.createHash('sha256'); var digest = null; @@ -19,19 +19,19 @@ exports.verify = function (id, strategy, username, loggedIn, done) { digest = shasum.digest('hex'); } - findDeadorAlive(User, { 'auths' : digest }, true, - function (alive, user, removed) { + findDeadorAlive(User, { 'auths': digest }, true, + function(alive, user, removed) { var pos = user ? user.auths.indexOf(digest) : -1; if (removed) { done(null, false, 'user was removed'); } if (!user) { - User.findOne({ 'name' : username }, function (err, user) { + User.findOne({ 'name': username }, function(err, user) { if (user && loggedIn) { // Add the new strategy to same account // This allows linking multiple external accounts to one of ours user.auths.push(digest); user.strategies.push(strategy); - user.save(function (err, user) { + user.save(function(err, user) { return done(err, user); }); } else if (user) { @@ -40,14 +40,14 @@ exports.verify = function (id, strategy, username, loggedIn, done) { } else { // Create a new user user = new User({ - 'name' : username, - 'auths' : [digest], - 'strategies' : [strategy], - 'role' : userRoles.length - 1, + 'name': username, + 'auths': [digest], + 'strategies': [strategy], + 'role': userRoles.length - 1, 'about': '', 'ghUsername': null }); - user.save(function (err, user) { + user.save(function(err, user) { return done(err, user); }); } @@ -58,12 +58,13 @@ exports.verify = function (id, strategy, username, loggedIn, done) { user.auths.splice(pos, 1); user.strategies.push(strategy); user.auths.push(digest); - user.save(function (err, user) { + user.save(function(err, user) { return done(err, user); }); } else { // The user was authenticated return done(null, user); } - }); + } + ); } diff --git a/libs/remove.js b/libs/remove.js index 2ed954fcd..ca9135601 100644 --- a/libs/remove.js +++ b/libs/remove.js @@ -6,13 +6,13 @@ var async = require('async'); var modelNames = ['Script']; var models = {}; -modelNames.forEach(function (modelName) { +modelNames.forEach(function(modelName) { models[modelName] = require('../models/' + modelName.toLowerCase())[modelName]; }); // Determine whether content can be removed by a user. -function removeable (model, content, user, callback) { +function removeable(model, content, user, callback) { // The user must be logged in // The user is a moderator then the content must be flagged // If the user is an admin or greater then the content may be removed @@ -27,7 +27,7 @@ function removeable (model, content, user, callback) { content); } - User.findOne({ _id: content._authorId }, function (err, author) { + User.findOne({ _id: content._authorId }, function(err, author) { // Content without an author shouldn't exist if (err || !author) { return callback(false); } @@ -41,7 +41,7 @@ function removeable (model, content, user, callback) { } exports.removeable = removeable; -function remove (model, content, user, reason, callback) { +function remove(model, content, user, reason, callback) { var remove = new Remove({ 'model': model.modelName, 'content': content.toObject(), @@ -52,28 +52,28 @@ function remove (model, content, user, reason, callback) { '_removerId': user._id }); - remove.save(function (err, remove) { - content.remove(function (err) { callback(remove); }); + remove.save(function(err, remove) { + content.remove(function(err) { callback(remove); }); }); } -exports.remove = function (model, content, user, reason, callback) { - removeable(model, content, user, function (canRemove, author) { +exports.remove = function(model, content, user, reason, callback) { + removeable(model, content, user, function(canRemove, author) { if (!canRemove) { return callback(false); } if (model.modelName !== 'User') { remove(model, content, user, reason, callback); } else { // Remove all the user's content - async.each(modelNames, function (modelName, cb) { + async.each(modelNames, function(modelName, cb) { var model = models[modelName]; model.find({ _authorId: content._id }, - function (err, contentArr) { - async.each(contentArr, function (content, innerCb) { + function(err, contentArr) { + async.each(contentArr, function(content, innerCb) { remove(model, content, user, null, innerCb); }, cb); }); - }, function () { + }, function() { remove(model, content, user, reason, callback); }); } @@ -96,10 +96,10 @@ exports.remove = function (model, content, user, reason, callback) { // // The removed parameter is the Remove document containing the content // and is always returned if found, regardless of permissions. -exports.findDeadorAlive = function (model, query, user, callback) { +exports.findDeadorAlive = function(model, query, user, callback) { var modelName = model.modelName; - model.findOne(query, function (err, content) { + model.findOne(query, function(err, content) { var name = null; var rmQuery = { model: modelName }; @@ -112,7 +112,7 @@ exports.findDeadorAlive = function (model, query, user, callback) { rmQuery['content.' + name] = query[name]; } - Remove.findOne(rmQuery, function (err, removed) { + Remove.findOne(rmQuery, function(err, removed) { if (err || !removed) { return callback(null, null, null); } if (!user || (user !== true && user.role > removed.removerRole)) { return callback(false, null, removed); diff --git a/libs/repoManager.js b/libs/repoManager.js index 33b892818..56f435d8b 100644 --- a/libs/repoManager.js +++ b/libs/repoManager.js @@ -18,7 +18,7 @@ Strategy.findOne({ name: 'github' }, function(err, strat) { }); // Requests a GitHub url and returns the chunks as buffers -function fetchRaw (host, path, callback) { +function fetchRaw(host, path, callback) { var options = { hostname: host, port: 443, @@ -30,22 +30,22 @@ function fetchRaw (host, path, callback) { var req = https.request(options, function(res) { var bufs = []; - if (res.statusCode != 200) { console.log(res.statusCode);return callback([new Buffer('')]); } + if (res.statusCode != 200) { console.log(res.statusCode); return callback([new Buffer('')]); } else { res.on('data', function(d) { bufs.push(d); }); res.on('end', function() { callback(bufs); }); } - }); + }); req.end(); } // Use for call the GitHub JSON api // Returns the JSON parsed object -function fetchJSON (path, callback) { +function fetchJSON(path, callback) { path += '?client_id=' + clientId + '&client_secret=' + clientKey; - fetchRaw('api.github.com', path, function (bufs) { + fetchRaw('api.github.com', path, function(bufs) { callback(JSON.parse(Buffer.concat(bufs).toString())); }); } @@ -58,7 +58,7 @@ function RepoManager(userId, user, repos) { } // Fetches the information about repos that contain user scripts -RepoManager.prototype.fetchRecentRepos = function (callback) { +RepoManager.prototype.fetchRecentRepos = function(callback) { var repoList = []; var that = this; @@ -76,11 +76,11 @@ RepoManager.prototype.fetchRecentRepos = function (callback) { // to speedup this request. // githubRepoList = _.where(githubRepoList, {fork: false}); - _.map(githubRepoList, function(githubRepo){ + _.map(githubRepoList, function(githubRepo) { repoList.push(new Repo(that, githubRepo.owner.login, githubRepo.name)); }); - async.each(repoList, function (repo, callback) { + async.each(repoList, function(repo, callback) { repo.fetchUserScripts(function() { callback(null); }); @@ -90,19 +90,19 @@ RepoManager.prototype.fetchRecentRepos = function (callback) { }; // Import scripts on GitHub -RepoManager.prototype.loadScripts = function (callback, update) { +RepoManager.prototype.loadScripts = function(callback, update) { var scriptStorage = require('../controllers/scriptStorage'); var arrayOfRepos = this.makeRepoArray(); var that = this; var scripts = []; // TODO: remove usage of makeRepoArray since it causes redundant looping - arrayOfRepos.forEach(function (repo) { - async.each(repo.scripts, function (script, cb) { - var url = '/' + encodeURI(repo.user) + '/' + encodeURI(repo.repo) + arrayOfRepos.forEach(function(repo) { + async.each(repo.scripts, function(script, cb) { + var url = '/' + encodeURI(repo.user) + '/' + encodeURI(repo.repo) + '/master' + script.path; - fetchRaw('raw.githubusercontent.com', url, function (bufs) { - scriptStorage.getMeta(bufs, function (meta) { + fetchRaw('raw.githubusercontent.com', url, function(bufs) { + scriptStorage.getMeta(bufs, function(meta) { if (meta) { scriptStorage.storeScript(that.user, meta, Buffer.concat(bufs), cb, update); @@ -114,7 +114,7 @@ RepoManager.prototype.loadScripts = function (callback, update) { } // Create the Mustache object to display repos with their user scrips -RepoManager.prototype.makeRepoArray = function () { +RepoManager.prototype.makeRepoArray = function() { var retOptions = []; var repos = this.repos; var username = this.user.ghUsername; @@ -146,22 +146,24 @@ function Repo(manager, username, reponame) { } // Use recursive requests to locate all user scripts in a repo -Repo.prototype.fetchUserScripts = function (callback) { +Repo.prototype.fetchUserScripts = function(callback) { this.getTree('HEAD', '', callback); }; // Looks for user script in the current directory // and initiates searches on subdirectories -Repo.prototype.parseTree = function (tree, path, done) { +Repo.prototype.parseTree = function(tree, path, done) { var object; var trees = []; var that = this; var repos = this.manager.repos; - tree.forEach(function (object) { + tree.forEach(function(object) { if (object.type === 'tree') { - trees.push({ sha: object.sha, path: path + '/' - + encodeURI(object.path) }); + trees.push({ + sha: object.sha, path: path + '/' + + encodeURI(object.path) + }); } else if (object.path.substr(-8) === '.user.js') { if (!repos[that.repo]) { repos[that.repo] = nil(); } repos[that.repo][object.path] = path + '/' + encodeURI(object.path); @@ -170,21 +172,22 @@ Repo.prototype.parseTree = function (tree, path, done) { async.each(trees, function(tree, cb) { that.getTree(tree.sha, tree.path, cb); - }, function () { + }, function() { done(); }); }; // Gets information about a directory -Repo.prototype.getTree = function (sha, path, cb) { +Repo.prototype.getTree = function(sha, path, cb) { var that = this; - fetchJSON('/repos/' + encodeURI(this.user) + '/' + encodeURI(this.repo) + fetchJSON('/repos/' + encodeURI(this.user) + '/' + encodeURI(this.repo) + '/git/trees/' + sha, - function (json) { + function(json) { that.parseTree(json.tree, path, cb); - }); + } + ); }; -exports.getManager = function (userId, user, repos) { +exports.getManager = function(userId, user, repos) { return new RepoManager(userId, user, repos); }; diff --git a/libs/tasks.js b/libs/tasks.js index f7dc17843..777a7936e 100644 --- a/libs/tasks.js +++ b/libs/tasks.js @@ -8,8 +8,8 @@ var onErr = function(err, onErrFn) { }; exports.countTask = function(modelListQuery, dict, key, onErrFn) { - return function (callback) { - modelListQuery.model.count(modelListQuery._conditions, function(err, modelListCount){ + return function(callback) { + modelListQuery.model.count(modelListQuery._conditions, function(err, modelListCount) { if (err) { onErr(err, onErrFn); callback(); @@ -22,8 +22,8 @@ exports.countTask = function(modelListQuery, dict, key, onErrFn) { }; exports.execQueryTask = function(query, dict, key, onErrFn) { - return function (callback) { - query.exec(function(err, result){ + return function(callback) { + query.exec(function(err, result) { if (err) { onErr(err, onErrFn); callback(); diff --git a/libs/templateHelpers.js b/libs/templateHelpers.js index 9ecba939a..7d0e76c7d 100644 --- a/libs/templateHelpers.js +++ b/libs/templateHelpers.js @@ -2,7 +2,6 @@ var countTask = require('../libs/tasks').countTask; var helpers = require('../libs/helpers'); var modelParser = require('../libs/modelParser'); - var paginateTemplate = function(opts) { // Required var currentPage = opts.currentPage; @@ -22,10 +21,9 @@ var paginateTemplate = function(opts) { if (firstVisible && linkedPages.length > 0 && linkedPages[0] != 1) linkedPages.splice(0, 0, 1); // insert the value 1 at index 0 - if (lastVisible && linkedPages.length > 0 && linkedPages[linkedPages.length-1] != lastPage) + if (lastVisible && linkedPages.length > 0 && linkedPages[linkedPages.length - 1] != lastPage) linkedPages.push(lastPage); - var html = ''; html += ' {{/groups}}
-{{> pagination.html}} + {{> pagination.html}} {{/groupsList}} diff --git a/views/header.html b/views/header.html index 4a90c89e1..934265aa6 100644 --- a/views/header.html +++ b/views/header.html @@ -1,91 +1,88 @@ - + - - - - {{title}} - - - - - - - - - - -
- -
-
- -

OpenUserJS.org

- {{#username}} -
- {{username}} - - {{/username}} - {{^username}} - - - - {{/username}} -
-
-
- - -
+ + + + {{title}} + + + + + + + + + +
+
+
+

OpenUserJS.org

+ {{#username}} +
+ {{username}} + +
+ {{/username}} + {{^username}} +
+ + +
+ {{/username}} +
+
+ +
diff --git a/views/includes/announcementsPanel.html b/views/includes/announcementsPanel.html index 2ca71a012..88b331afd 100644 --- a/views/includes/announcementsPanel.html +++ b/views/includes/announcementsPanel.html @@ -1,10 +1,8 @@ - -
- - Announcements + + Announcements
diff --git a/views/includes/commentForm.html b/views/includes/commentForm.html index c310237f5..a9e663a1e 100644 --- a/views/includes/commentForm.html +++ b/views/includes/commentForm.html @@ -1,7 +1,6 @@
-
diff --git a/views/includes/discussionList.html b/views/includes/discussionList.html index 3bf9507b9..ecb3c556b 100644 --- a/views/includes/discussionList.html +++ b/views/includes/discussionList.html @@ -1,50 +1,50 @@
- - - - - {{#multipleCategories}} - - {{/multipleCategories}} - - - - - - - - - {{#discussionList}} - - - {{#multipleCategories}} - - {{/multipleCategories}} - - - - - - - {{/discussionList}} - -
TopicCategoryUsersRepliesViewsCreatedUpdated
+ + + + + {{#multipleCategories}} + + {{/multipleCategories}} + + + + + + + + + {{#discussionList}} + + + {{#multipleCategories}} + + {{/multipleCategories}} + + + + + + + {{/discussionList}} + +
TopicCategoryUsersRepliesViewsCreatedUpdated
diff --git a/views/includes/footer.html b/views/includes/footer.html index dc4f2372d..a1f68923a 100644 --- a/views/includes/footer.html +++ b/views/includes/footer.html @@ -1,24 +1,24 @@ - - - - + + + diff --git a/views/includes/groupList.html b/views/includes/groupList.html index 2147d1017..6d5feb649 100644 --- a/views/includes/groupList.html +++ b/views/includes/groupList.html @@ -1,7 +1,7 @@ - + diff --git a/views/includes/header.html b/views/includes/header.html index ca1e0b2df..486e63593 100644 --- a/views/includes/header.html +++ b/views/includes/header.html @@ -1,27 +1,31 @@ - diff --git a/views/includes/popularGroupsPanel.html b/views/includes/popularGroupsPanel.html index 1b873da87..9b89a731d 100644 --- a/views/includes/popularGroupsPanel.html +++ b/views/includes/popularGroupsPanel.html @@ -5,7 +5,7 @@
    {{#popularGroupList}} -
  • {{name}} {{size}}
  • +
  • {{name}} {{size}}
  • {{/popularGroupList}}
diff --git a/views/includes/removedItemList.html b/views/includes/removedItemList.html index 396c1d633..2b55f1011 100644 --- a/views/includes/removedItemList.html +++ b/views/includes/removedItemList.html @@ -2,8 +2,8 @@ - - + + diff --git a/views/includes/scriptAuthorToolsPanel.html b/views/includes/scriptAuthorToolsPanel.html index 8c42bb8a2..41dd52444 100644 --- a/views/includes/scriptAuthorToolsPanel.html +++ b/views/includes/scriptAuthorToolsPanel.html @@ -5,8 +5,8 @@ diff --git a/views/includes/scriptList.html b/views/includes/scriptList.html index 21b9e4ba2..de3f7e714 100644 --- a/views/includes/scriptList.html +++ b/views/includes/scriptList.html @@ -13,13 +13,17 @@
NameName Size Rating
TypeItemReasonItemReason Removed By Date
- {{name}}{{#meta.version}}
{{meta.version}}
{{/meta.version}} by {{author.name}} + {{name}} + {{#meta.version}} + {{meta.version}} + {{/meta.version}} + by {{author.name}}

{{meta.description}}

diff --git a/views/includes/scriptModToolsPanel.html b/views/includes/scriptModToolsPanel.html index ab6a2ffc5..881488740 100644 --- a/views/includes/scriptModToolsPanel.html +++ b/views/includes/scriptModToolsPanel.html @@ -1,14 +1,17 @@ {{#modTools}}
-
Mod Tools
+
+ + Mod Tools +
{{#script}} {{> includes/flagModelSnippet.html }} {{/script}}
diff --git a/views/includes/scriptPageHeader.html b/views/includes/scriptPageHeader.html index f44c1db69..592e7c951 100644 --- a/views/includes/scriptPageHeader.html +++ b/views/includes/scriptPageHeader.html @@ -1,13 +1,18 @@

- + {{#script.isLib}} - + Raw Source {{/script.isLib}} {{^script.isLib}} - + Install {{/script.isLib}} - {{#script.icon45Url}} {{/script.icon45Url}} {{script.author.name}}/{{script.name}} + {{#script.icon45Url}} + + {{/script.icon45Url}} + {{script.author.name}} + / + {{script.name}}