Fix indenting to 2 spaces, remove most lint errors

This commit is contained in:
Nathan Leniz
2015-03-22 20:20:08 +09:00
parent fb5e8dc387
commit 999ba14db7

View File

@ -1,444 +1,449 @@
var R = require('ramda'), var R = require('ramda'),
debug = require('debug')('freecc:cntr:story'), debug = require('debug')('freecc:cntr:story'),
Story = require('./../models/Story'), Story = require('./../models/Story'),
Comment = require('./../models/Comment'), Comment = require('./../models/Comment'),
User = require('./../models/User'), User = require('./../models/User'),
moment = require('../public/js/lib/moment/moment.js'), moment = require('../public/js/lib/moment/moment.js'),
resources = require('./resources'), resources = require('./resources'),
mongodb = require('mongodb'), mongodb = require('mongodb'),
MongoClient = mongodb.MongoClient, MongoClient = mongodb.MongoClient,
secrets = require('../config/secrets'), secrets = require('../config/secrets'),
sanitizeHtml = require('sanitize-html'); sanitizeHtml = require('sanitize-html');
function hotRank(timeValue, rank) { function hotRank(timeValue, rank) {
/* /*
* Hotness ranking algorithm: http://amix.dk/blog/post/19588 * Hotness ranking algorithm: http://amix.dk/blog/post/19588
* tMS = postedOnDate - foundationTime; * tMS = postedOnDate - foundationTime;
* Ranking... * Ranking...
* f(ts, 1, rank) = log(10)z + (ts)/45000; * f(ts, 1, rank) = log(10)z + (ts)/45000;
*/ */
var hotness; var hotness;
var z = Math.log(rank) / Math.log(10); var z = Math.log(rank) / Math.log(10);
hotness = z + (timeValue / 115200000); hotness = z + (timeValue / 115200000);
return hotness; return hotness;
} }
exports.hotJSON = function(req, res) { exports.hotJSON = function(req, res) {
var story = Story.find({}).sort({'timePosted': -1}).limit(1000); var story = Story.find({}).sort({'timePosted': -1}).limit(1000);
story.exec(function(err, stories) { story.exec(function(err, stories) {
if (err) { if (err) {
res.send(500); return res.status(500);
return next(err); }
}
var foundationDate = 1413298800000; var foundationDate = 1413298800000;
var sliceVal = stories.length >= 100 ? 100 : stories.length; var sliceVal = stories.length >= 100 ? 100 : stories.length;
return res.json(stories.map(function(elem) { return res.json(stories.map(function(elem) {
return elem; return elem;
}).sort(function(a, b) { }).sort(function(a, b) {
return hotRank(b.timePosted - foundationDate, b.rank, b.headline) return hotRank(b.timePosted - foundationDate, b.rank, b.headline)
- hotRank(a.timePosted - foundationDate, a.rank, a.headline); - hotRank(a.timePosted - foundationDate, a.rank, a.headline);
}).slice(0, sliceVal)); }).slice(0, sliceVal));
}); });
}; };
exports.recentJSON = function(req, res, next) { exports.recentJSON = function(req, res, next) {
var story = Story.find({}).sort({'timePosted': -1}).limit(100); var story = Story.find({}).sort({'timePosted': -1}).limit(100);
story.exec(function(err, stories) { story.exec(function(err, stories) {
if (err) { if (err) {
res.status(500); res.status(500);
return next(err); return next(err);
} }
res.json(stories); res.json(stories);
}); });
}; };
exports.hot = function(req, res) { exports.hot = function(req, res) {
res.render('stories/index', { res.render('stories/index', {
title: 'Hot stories currently trending on Camper News', title: 'Hot stories currently trending on Camper News',
page: 'hot' page: 'hot'
}); });
}; };
exports.submitNew = function(req, res) { exports.submitNew = function(req, res) {
res.render('stories/index', { res.render('stories/index', {
title: 'Submit a new story to Camper News', title: 'Submit a new story to Camper News',
page: 'submit' page: 'submit'
}); });
}; };
exports.search = function(req, res) { exports.search = function(req, res) {
res.render('stories/index', { res.render('stories/index', {
title: 'Search the archives of Camper News', title: 'Search the archives of Camper News',
page: 'search' page: 'search'
}); });
}; };
exports.recent = function(req, res) { exports.recent = function(req, res) {
res.render('stories/index', { res.render('stories/index', {
title: 'Recently submitted stories on Camper News', title: 'Recently submitted stories on Camper News',
page: 'recent' page: 'recent'
}); });
}; };
exports.preSubmit = function(req, res) { exports.preSubmit = function(req, res) {
var data = req.query; var data = req.query;
var cleanData = sanitizeHtml(data.url, { var cleanData = sanitizeHtml(data.url, {
allowedTags: [], allowedTags: [],
allowedAttributes: [] allowedAttributes: []
}).replace(/";/g, '"'); }).replace(/";/g, '"');
if (data.url.replace(/&/g, '&') !== cleanData) { if (data.url.replace(/&/g, '&') !== cleanData) {
req.flash('errors', { req.flash('errors', {
msg: 'The data for this post is malformed' msg: 'The data for this post is malformed'
});
return res.render('stories/index', {
page: 'stories/submit'
});
}
var title = data.title || '';
var image = data.image || '';
var description = data.description || '';
return res.render('stories/index', {
title: "Confirm your Camper News story submission",
page: 'storySubmission',
storyURL: data.url,
storyTitle: title,
storyImage: image,
storyMetaDescription: description
}); });
return res.render('stories/index', {
page: 'stories/submit'
});
}
var title = data.title || '';
var image = data.image || '';
var description = data.description || '';
return res.render('stories/index', {
title: 'Confirm your Camper News story submission',
page: 'storySubmission',
storyURL: data.url,
storyTitle: title,
storyImage: image,
storyMetaDescription: description
});
}; };
exports.returnIndividualStory = function(req, res, next) { exports.returnIndividualStory = function(req, res, next) {
var dashedName = req.params.storyName; var dashedName = req.params.storyName;
var storyName = dashedName.replace(/\-/g, ' '); var storyName = dashedName.replace(/\-/g, ' ');
Story.find({'storyLink' : new RegExp(storyName, 'i')}, function(err, story) { Story.find({'storyLink': new RegExp(storyName, 'i')}, function(err, story) {
if (err) { if (err) {
next(err); next(err);
} }
if (story.length < 1) { if (story.length < 1) {
req.flash('errors', { req.flash('errors', {
msg: "404: We couldn't find a story with that name. Please double check the name." msg: "404: We couldn't find a story with that name. Please double check the name."
}); });
return res.redirect('/stories/'); return res.redirect('/stories/');
} }
story = story.pop(); story = story.pop();
var dashedNameFull = story.storyLink.toLowerCase().replace(/\s/g, '-'); var dashedNameFull = story.storyLink.toLowerCase().replace(/\s/g, '-');
if (dashedNameFull !== dashedName) { if (dashedNameFull !== dashedName) {
return res.redirect('../stories/' + dashedNameFull); return res.redirect('../stories/' + dashedNameFull);
} }
var userVoted = false; var userVoted = false;
try { try {
var votedObj = story.upVotes.filter(function(a){ var votedObj = story.upVotes.filter(function(a) {
return a['upVotedByUsername'] === req.user['profile']['username']; return a['upVotedByUsername'] === req.user['profile']['username'];
}) });
if (votedObj.length > 0){ if (votedObj.length > 0) {
userVoted = true; userVoted = true;
} }
} catch(err){ } catch(err) {
userVoted = false; userVoted = false;
} }
res.render('stories/index', { res.render('stories/index', {
title: story.headline, title: story.headline,
link: story.link, link: story.link,
author: story.author, author: story.author,
description: story.description, description: story.description,
rank: story.upVotes.length, rank: story.upVotes.length,
upVotes: story.upVotes, upVotes: story.upVotes,
comments: story.comments, comments: story.comments,
id: story._id, id: story._id,
timeAgo: moment(story.timePosted).fromNow(), timeAgo: moment(story.timePosted).fromNow(),
image: story.image, image: story.image,
page: 'show', page: 'show',
storyMetaDescription: story.metaDescription, storyMetaDescription: story.metaDescription,
hasUserVoted: userVoted hasUserVoted: userVoted
});
}); });
});
}; };
exports.getStories = function(req, res) { exports.getStories = function(req, res) {
MongoClient.connect(secrets.db, function(err, database) { MongoClient.connect(secrets.db, function(err, database) {
database.collection('stories').find({ if (err) {
"$text": { return res.status(500);
"$search": req.body.data.searchValue }
} database.collection('stories').find({
}, { '$text': {
headline: 1, '$search': req.body.data.searchValue
timePosted: 1, }
link: 1, }, {
description: 1, headline: 1,
rank: 1, timePosted: 1,
upVotes: 1, link: 1,
author: 1, description: 1,
comments: 1, rank: 1,
image: 1, upVotes: 1,
storyLink: 1, author: 1,
metaDescription: 1, comments: 1,
textScore: { image: 1,
$meta: "textScore" storyLink: 1,
} metaDescription: 1,
}, { textScore: {
sort: { $meta: 'textScore'
textScore: { }
$meta: "textScore" }, {
} sort: {
} textScore: {
}).toArray(function(err, items) { $meta: 'textScore'
if (items !== null && items.length !== 0) { }
return res.json(items); }
} }).toArray(function(err, items) {
return res.status(404); if (err) {
}); return res.status(500);
}
if (items !== null && items.length !== 0) {
return res.json(items);
}
return res.status(404);
}); });
});
}; };
exports.upvote = function(req, res, next) { exports.upvote = function(req, res, next) {
var data = req.body.data; var data = req.body.data;
Story.find({'_id': data.id}, function(err, story) { Story.find({'_id': data.id}, function(err, story) {
if (err) { if (err) {
res.status(500); res.status(500);
return next(err); return next(err);
} }
story = story.pop(); story = story.pop();
story.rank++; story.rank++;
story.upVotes.push( story.upVotes.push(
{ {
upVotedBy: data.upVoter._id, upVotedBy: data.upVoter._id,
upVotedByUsername: data.upVoter.profile.username upVotedByUsername: data.upVoter.profile.username
} }
); );
story.markModified('rank'); story.markModified('rank');
story.save(); story.save();
User.find({'_id': story.author.userId}, function(err, user) { User.find({'_id': story.author.userId}, function(err, user) {
'use strict'; 'use strict';
if (err) { if (err) {
return next(err); return next(err);
} }
user = user.pop(); user = user.pop();
user.progressTimestamps.push(Date.now()); user.progressTimestamps.push(Date.now());
user.save(); user.save();
});
return res.send(story);
}); });
return res.send(story);
});
}; };
exports.comments = function(req, res, next) { exports.comments = function(req, res, next) {
var data = req.params.id; var data = req.params.id;
Comment.find({'_id': data}, function(err, comment) { Comment.find({'_id': data}, function(err, comment) {
if (err) { if (err) {
res.status(500); res.status(500);
return next(err); return next(err);
} }
comment = comment.pop(); comment = comment.pop();
return res.send(comment); return res.send(comment);
}); });
}; };
exports.newStory = function(req, res) { exports.newStory = function(req, res) {
if (!req.user) { if (!req.user) {
return res.status(500); return res.status(500);
} }
var url = req.body.data.url; var url = req.body.data.url;
var cleanURL = sanitizeHtml(url, { var cleanURL = sanitizeHtml(url, {
allowedTags: [], allowedTags: [],
allowedAttributes: [] allowedAttributes: []
}).replace(/&quot;/g, '"'); }).replace(/&quot;/g, '"');
if (cleanURL !== url) { if (cleanURL !== url) {
req.flash('errors', { req.flash('errors', {
msg: "The URL you submitted doesn't appear valid" msg: "The URL you submitted doesn't appear valid"
}); });
return res.json({ return res.json({
alreadyPosted: true, alreadyPosted: true,
storyURL: '/stories/submit' storyURL: '/stories/submit'
});
}
if (url.search(/^https?:\/\//g) === -1) {
url = 'http://' + url;
}
Story.find({'link': url}, function(err, story) {
if (err) {
return res.status(500);
}
if (story.length) {
req.flash('errors', {
msg: "Someone's already posted that link. Here's the discussion."
});
return res.json({
alreadyPosted: true,
storyURL: '/stories/' + story.pop().storyLink
});
}
resources.getURLTitle(url, processResponse);
}); });
function processResponse(err, story) { }
if (err) { if (url.search(/^https?:\/\//g) === -1) {
res.json({ url = 'http://' + url;
alreadyPosted: false, }
storyURL: url, Story.find({'link': url}, function(err, story) {
storyTitle: '', if (err) {
storyImage: '', return res.status(500);
storyMetaDescription: ''
});
} else {
res.json({
alreadyPosted: false,
storyURL: url,
storyTitle: story.title,
storyImage: story.image,
storyMetaDescription: story.description
});
}
} }
if (story.length) {
req.flash('errors', {
msg: "Someone's already posted that link. Here's the discussion."
});
return res.json({
alreadyPosted: true,
storyURL: '/stories/' + story.pop().storyLink
});
}
resources.getURLTitle(url, processResponse);
});
function processResponse(err, story) {
if (err) {
res.json({
alreadyPosted: false,
storyURL: url,
storyTitle: '',
storyImage: '',
storyMetaDescription: ''
});
} else {
res.json({
alreadyPosted: false,
storyURL: url,
storyTitle: story.title,
storyImage: story.image,
storyMetaDescription: story.description
});
}
}
}; };
exports.storySubmission = function(req, res) { exports.storySubmission = function(req, res) {
var data = req.body.data; var data = req.body.data;
if (req.user._id.toString() !== data.author.userId.toString()) { if (req.user._id.toString() !== data.author.userId.toString()) {
return res.status(500); return res.status(500);
} }
var storyLink = data.headline var storyLink = data.headline
.replace(/\'/g, '') .replace(/\'/g, '')
.replace(/\"/g, '') .replace(/\"/g, '')
.replace(/,/g, '') .replace(/,/g, '')
.replace(/[^a-z0-9]/gi, ' ') .replace(/[^a-z0-9]/gi, ' ')
.replace(/\s+/g, ' ') .replace(/\s+/g, ' ')
.toLowerCase(); .toLowerCase();
var link = data.link; var link = data.link;
if (link.search(/^https?:\/\//g) === -1) { if (link.search(/^https?:\/\//g) === -1) {
link = 'http://' + link; link = 'http://' + link;
} }
var story = new Story({ var story = new Story({
headline: sanitizeHtml(data.headline, { headline: sanitizeHtml(data.headline, {
allowedTags: [], allowedTags: [],
allowedAttributes: [] allowedAttributes: []
}).replace(/&quot;/g, '"'), }).replace(/&quot;/g, '"'),
timePosted: Date.now(), timePosted: Date.now(),
link: link, link: link,
description: sanitizeHtml(data.description, { description: sanitizeHtml(data.description, {
allowedTags: [], allowedTags: [],
allowedAttributes: [] allowedAttributes: []
}).replace(/&quot;/g, '"'), }).replace(/&quot;/g, '"'),
rank: 1, rank: 1,
upVotes: data.upVotes, upVotes: data.upVotes,
author: data.author, author: data.author,
comments: [], comments: [],
image: data.image, image: data.image,
storyLink: storyLink, storyLink: storyLink,
metaDescription: data.storyMetaDescription metaDescription: data.storyMetaDescription
}); });
req.user.progressTimestamps.push(Date.now()); req.user.progressTimestamps.push(Date.now());
req.user.save(); req.user.save();
story.save(function(err) { story.save(function(err) {
if (err) { if (err) {
return res.status(500); return res.status(500);
} }
res.send(JSON.stringify({ res.send(JSON.stringify({
storyLink: story.storyLink.replace(/\s/g, '-').toLowerCase() storyLink: story.storyLink.replace(/\s/g, '-').toLowerCase()
})); }));
}); });
}; };
exports.commentSubmit = function(req, res) { exports.commentSubmit = function(req, res) {
var data = req.body.data; var data = req.body.data;
if (req.user._id.toString() !== data.author.userId.toString()) { if (req.user._id.toString() !== data.author.userId.toString()) {
return res.status(500); return res.status(500);
} }
var sanitizedBody = sanitizeHtml(data.body, var sanitizedBody = sanitizeHtml(data.body,
{ {
allowedTags: [], allowedTags: [],
allowedAttributes: [] allowedAttributes: []
}).replace(/&quot;/g, '"'); }).replace(/&quot;/g, '"');
if (data.body !== sanitizedBody) { if (data.body !== sanitizedBody) {
req.flash('errors', { req.flash('errors', {
msg: 'HTML is not allowed' msg: 'HTML is not allowed'
});
return res.send(true);
}
var comment = new Comment({
associatedPost: data.associatedPost,
body: sanitizedBody,
rank: 0,
upvotes: 0,
author: data.author,
comments: [],
topLevel: true,
commentOn: Date.now()
}); });
commentSave(comment, Story, res); return res.send(true);
}
var comment = new Comment({
associatedPost: data.associatedPost,
body: sanitizedBody,
rank: 0,
upvotes: 0,
author: data.author,
comments: [],
topLevel: true,
commentOn: Date.now()
});
commentSave(comment, Story, res);
}; };
exports.commentOnCommentSubmit = function(req, res) { exports.commentOnCommentSubmit = function(req, res) {
var data = req.body.data; var data = req.body.data;
if (req.user._id.toString() !== data.author.userId.toString()) { if (req.user._id.toString() !== data.author.userId.toString()) {
return res.status(500); return res.status(500);
} }
var sanitizedBody = sanitizeHtml(data.body, var sanitizedBody = sanitizeHtml(data.body,
{ {
allowedTags: [], allowedTags: [],
allowedAttributes: [] allowedAttributes: []
}).replace(/&quot;/g, '"'); }).replace(/&quot;/g, '"');
if (data.body !== sanitizedBody) { if (data.body !== sanitizedBody) {
req.flash('errors', { req.flash('errors', {
msg: 'HTML is not allowed' msg: 'HTML is not allowed'
});
return res.send(true);
}
var comment = new Comment({
associatedPost: data.associatedPost,
body: sanitizedBody,
rank: 0,
upvotes: 0,
author: data.author,
comments: [],
topLevel: false,
commentOn: Date.now()
}); });
commentSave(comment, Comment, res); return res.send(true);
}
var comment = new Comment({
associatedPost: data.associatedPost,
body: sanitizedBody,
rank: 0,
upvotes: 0,
author: data.author,
comments: [],
topLevel: false,
commentOn: Date.now()
});
commentSave(comment, Comment, res);
}; };
function commentSave(comment, Context, res) { function commentSave(comment, Context, res) {
comment.save(function(err, data) { comment.save(function(err, data) {
if (err) {
return res.status(500);
}
try {
Context.find({'_id': comment.associatedPost}, function (err, associatedStory) {
if (err) { if (err) {
return res.status(500); return res.status(500);
} }
try { associatedStory = associatedStory.pop();
Context.find({'_id': comment.associatedPost}, function (err, associatedStory) { if (associatedStory) {
if (err) { associatedStory.comments.push(data._id);
return res.status(500); associatedStory.save(function (err) {
} if (err) {
associatedStory = associatedStory.pop(); res.status(500);
if (associatedStory) { }
associatedStory.comments.push(data._id); res.send(true);
associatedStory.save(function (err) { });
if (err) {
res.status(500);
}
res.send(true);
});
}
});
} catch (e) {
// delete comment
return res.status(500);
} }
}); });
} catch (e) {
// delete comment
return res.status(500);
}
});
} }