/** * Lots of routes.. would be good idea to do some separation I guess. */ module.exports = (app, redis, fetch, RedditAPI) => { const config = require('./config'); let processSubreddit = require('./inc/processJsonSubreddit.js')(); let processPost = require('./inc/processJsonPost.js')(); let processUser = require('./inc/processJsonUser.js')(); let processSearches = require('./inc/processSearchResults.js')(); let processAbout = require('./inc/processSubredditAbout.js')(); let tedditApiSubreddit = require('./inc/teddit_api/handleSubreddit.js')(); let tedditApiUser = require('./inc/teddit_api/handleUser.js')(); let processSubredditsExplore = require('./inc/processSubredditsExplore.js')(); let processMoreComments = require('./inc/processMoreComments.js')(); app.all('*', (req, res, next) => { let themeOverride = req.query.theme if(themeOverride) { // Convert Dark to dark since the stylesheet has it lower case themeOverride = themeOverride.toLowerCase() // This override here will set it for the current request req.cookies.theme = themeOverride // this will set it for future requests res.cookie('theme', themeOverride, { maxAge: 31536000, httpOnly: true }) } else if(!req.cookies.theme && req.cookies.theme !== '') { req.cookies.theme = config.theme } let flairsOverride = req.query.flairs if(flairsOverride) { req.cookies.flairs = flairsOverride res.cookie('flairs', flairsOverride, { maxAge: 31536000, httpOnly: true }) } let nsfwEnabledOverride = req.query.nsfw_enabled if(nsfwEnabledOverride) { req.cookies.nsfw_enabled = nsfwEnabledOverride res.cookie('nsfw_enabled', nsfwEnabledOverride, { maxAge: 31536000, httpOnly: true }) } let highlightControversialOverride = req.query.highlight_controversial if(highlightControversialOverride) { req.cookies.highlight_controversial = highlightControversialOverride res.cookie('highlight_controversial', highlightControversialOverride, { maxAge: 31536000, httpOnly: true }) } let postMediaMaxHeight = req.query.post_media_max_height if(postMediaMaxHeight) { if(config.post_media_max_heights.hasOwnProperty(postMediaMaxHeight) || !isNaN(postMediaMaxHeight)) { req.cookies.post_media_max_height = postMediaMaxHeight res.cookie('post_media_max_height', postMediaMaxHeight, { maxAge: 31536000, httpOnly: true }) } } let collapseChildComments = req.query.collapse_child_comments if(collapseChildComments) { req.cookies.collapse_child_comments = collapseChildComments res.cookie('collapse_child_comments', collapseChildComments, { maxAge: 31536000, httpOnly: true }) } let showUpvotedPercentage = req.query.show_upvoted_percentage if(showUpvotedPercentage) { req.cookies.show_upvoted_percentage = showUpvotedPercentage res.cookie('show_upvoted_percentage', showUpvotedPercentage, { maxAge: 31536000, httpOnly: true }) } let domainTwitter = req.query.domain_twitter if(domainTwitter) { req.cookies.domain_twitter = domainTwitter res.cookie('domain_twitter', domainTwitter, { maxAge: 31536000, httpOnly: true }) } let domainYoutube = req.query.domain_youtube if(domainYoutube) { req.cookies.domain_youtube = domainYoutube res.cookie('domain_youtube', domainYoutube, { maxAge: 31536000, httpOnly: true }) } let domainInstagram = req.query.domain_instagram if(domainInstagram) { req.cookies.domain_instagram = domainInstagram res.cookie('domain_instagram', domainInstagram, { maxAge: 31536000, httpOnly: true }) } if(!config.rate_limiting) { return next() } if(config.rate_limiting.enabled) { /** * This route enforces request limits based on an IP address if * config.rate_limiting.enabled is true. By default it's false. */ let ip = String(req.headers['x-forwarded-for'] || req.connection.remoteAddress || 'unknown') if(ip === 'unknown') { return next() } if(ratelimit_counts[ip] == undefined) { ratelimit_counts[ip] = 0 } if(ratelimit_timestamps[ip] == undefined) { ratelimit_timestamps[ip] = Date.now() } let diff = Date.now() - ratelimit_timestamps[ip] let credit = (diff / 60000) * config.rate_limiting.limit_after_limited ratelimit_counts[ip] -= credit if(ratelimit_counts[ip] < 0) { ratelimit_counts[ip] = 0 } ratelimit_counts[ip]++ ratelimit_timestamps[ip] = Date.now() if(ratelimit_counts[ip] > config.rate_limiting.initial_limit) { console.log(`RATE LIMITED IP ADDRESS: ${ip}`) return res.send(`Hold your horses! You have hit the request limit. You should be able to refresh this page in a couple of seconds. If you think you are wrongfully limited, create an issue at https://codeberg.org/teddit/teddit. Rate limiting is highly experimental feature.`) } else { return next() } } else { return next() } }) app.get('/about', (req, res, next) => { return res.render('about', { user_preferences: req.cookies }) }) app.get('/preferences', (req, res, next) => { return res.render('preferences', { user_preferences: req.cookies, instance_config: config }) }) app.get('/resetprefs', (req, res, next) => { res.clearCookie('theme') res.clearCookie('flairs') res.clearCookie('nsfw_enabled') res.clearCookie('highlight_controversial') res.clearCookie('subbed_subreddits') return res.redirect('/preferences') }) app.get('/import_prefs/:key', (req, res, next) => { let key = req.params.key if(!key) return res.redirect('/') if(key.length !== 10) return res.redirect('/') key = `prefs_key:${key}` redis.get(key, (error, json) => { if(error) { console.error(`Error getting the preferences import key ${key} from redis.`, error) return res.render('index', { json: null, user_preferences: req.cookies }) } if(json) { try { let prefs = JSON.parse(json) let subbed_subreddits_is_set = false for(var setting in prefs) { if(prefs.hasOwnProperty(setting)) { res.cookie(setting, prefs[setting], { maxAge: 365 * 24 * 60 * 60 * 1000, httpOnly: true }) if(setting === 'subbed_subreddits') subbed_subreddits_is_set = true } } if(!subbed_subreddits_is_set) res.clearCookie('subbed_subreddits') return res.redirect('/') } catch(e) { console.error(`Error setting imported preferences to the cookies. Key: ${key}.`, error) } } else { return res.redirect('/preferences') } }) }) app.get('/privacy', (req, res, next) => { return res.render('privacypolicy', { user_preferences: req.cookies }) }) app.get('/gallery/:id', (req, res, next) => { return res.redirect(`/comments/${req.params.id}`) }) app.get('/poll/:id', (req, res, next) => { return res.redirect(`/comments/${req.params.id}`) }) app.get('/saved', (req, res, next) => { let saved = req.cookies.saved if(!saved || !Array.isArray(saved)) { return res.render('saved', { json: null, user_preferences: req.cookies, }) } let key = `saved_posts:${saved.join(',')}` redis.get(key, (error, json) => { if(error) { console.error(`Error getting saved_post ${saved_post} key from redis.`, error) return res.redirect('/') } if(json) { (async () => { let processed_json = await processJsonSubreddit(json, 'redis', null, req.cookies, true) if(!processed_json.error) { return res.render('saved', { json: processed_json, user_preferences: req.cookies, }) } else { return res.render('subreddit', { json: null, error: true, data: processed_json, user_preferences: req.cookies }) } })() } }) }) app.get('/save/:id', (req, res, next) => { let post_id = req.params.id let redis_key = req.query.rk let back = req.query.b let saved = req.cookies.saved let fetched = req.query.f if(!post_id || !redis_key) return res.redirect('/saved') if(!saved || !Array.isArray(saved)) saved = [] if(saved.length > 100) return res.send('You can not save more than 100 posts.') redis.get(redis_key, (error, json) => { if(error) { console.error(`Error getting the ${redis_key} key from redis (via /save/).`, error) return res.redirect('/') } if(json) { json = JSON.parse(json) if(fetched === 'true' || redis_key.includes('/comments/')) json = json[0] let post_to_save = false for(var i = 0; i < json.data.children.length; i++) { let post = json.data.children[i] if(post.data.id === post_id) { post_to_save = post break } } if(post_to_save) { if(!saved || !Array.isArray(saved)) saved = [] for(var i = 0; i < saved.length; i++) { if(post_to_save.data.id === saved[i]) return res.redirect('/saved') } let key = `saved_posts:${saved.join(',')}` redis.get(key, (error, json) => { if(error) { console.error(`Error getting saved_posts ${key} key from redis.`, error) return res.redirect('/') } links = JSON.parse(json) if(!links) links = [] links.unshift(post_to_save) saved.unshift(post_to_save.data.id) res.cookie('saved', saved, { maxAge: 3 * 365 * 24 * 60 * 60 * 1000, httpOnly: true }) let new_key = `saved_posts:${saved.join(',')}` redis.set(new_key, JSON.stringify(links), (error) => { if(error) console.error(`Error saving ${new_key} to redis.`, error) if(!back) return res.redirect('/saved') else { back = back.replace(/§2/g, '?').replace(/§1/g, '&') return res.redirect(back) } }) }) } else { return res.redirect(`/comments/${post_id}/?save=true&b=${back}`) } } else { return res.redirect(`/comments/${post_id}/?save=true&b=${back}`) } }) }) app.get('/unsave/:id', (req, res, next) => { let post_id = req.params.id let back = req.query.b let saved = req.cookies.saved if(!post_id) return res.redirect('/saved') if(!saved || !Array.isArray(saved)) return res.redirect('/saved') let key = `saved_posts:${saved.join(',')}` redis.get(key, (error, json) => { if(error) { console.error(`Error getting the ${key} key from redis (via /save/).`, error) return res.redirect('/') } if(json) { json = JSON.parse(json) let post_found = false for(var i = 0; i < json.length; i++) { if(json[i].data.id === post_id) { post_found = true json.splice(i, 1) for(var j = 0; j < saved.length; j++) { if(saved[j] === post_id) saved.splice(j, 1) } } } if(post_found) { res.cookie('saved', saved, { maxAge: 3 * 365 * 24 * 60 * 60 * 1000, httpOnly: true }) let new_key = `saved_posts:${saved.join(',')}` redis.set(new_key, JSON.stringify(json), (error) => { if(error) console.error(`Error saving ${new_key} to redis.`, error) if(!back) return res.redirect('/saved') else { back = back.replace(/§2/g, '?').replace(/§1/g, '&') return res.redirect(back) } }) } else { return res.redirect(`/saved`) } } else { return res.redirect(`/saved`) } }) }) app.get('/subreddits/:sort?', (req, res, next) => { let q = req.query.q let nsfw = req.query.nsfw let after = req.query.after let before = req.query.before let sortby = req.params.sort let searching = false if(!after) { after = '' } if(!before) { before = '' } let d = `&after=${after}` if(before) { d = `&before=${before}` } if(nsfw !== 'on') { nsfw = 'off' } if(!sortby) { sortby = '' } let key = `subreddits:sort:${sortby}${d}` if(sortby === 'search') { if(typeof(q) == 'undefined' || q == '') return res.redirect('/subreddits') key = `subreddits:search:q:${q}:nsfw:${nsfw}${d}` searching = true } redis.get(key, (error, json) => { if(error) { console.error(`Error getting the subreddits key from redis.`, error) return res.render('index', { json: null, user_preferences: req.cookies }) } if(json) { console.log(`Got subreddits key from redis.`); (async () => { let processed_json = await processJsonSubredditsExplore(json, 'redis', null, req.cookies) if(!processed_json.error) { return res.render('subreddits_explore', { json: processed_json, sortby: sortby, after: after, before: before, q: q, nsfw: nsfw, searching: searching, subreddits_front: (!before && !after) ? true : false, user_preferences: req.cookies, instance_nsfw_enabled: config.nsfw_enabled }) } else { return res.render('subreddits_explore', { json: null, error: true, data: processed_json, user_preferences: req.cookies }) } })() } else { let url = '' if(config.use_reddit_oauth) { if(!searching) url = `https://oauth.reddit.com/subreddits/${sortby}?api_type=json&count=25&g=GLOBAL&t=${d}` else url = `https://oauth.reddit.com/subreddits/search?api_type=json&q=${q}&include_over_18=${nsfw}${d}` } else { if(!searching) url = `https://reddit.com/subreddits/${sortby}.json?api_type=json&count=25&g=GLOBAL&t=${d}` else url = `https://reddit.com/subreddits/search.json?api_type=json&q=${q}&include_over_18=${nsfw}${d}` } fetch(encodeURI(url), redditApiGETHeaders()) .then(result => { if(result.status === 200) { result.json() .then(json => { let ex = config.setexs.subreddits_explore.front if(sortby === 'new') ex = config.setexs.subreddits_explore.new_page redis.setex(key, ex, JSON.stringify(json), (error) => { if(error) { console.error(`Error setting the subreddits key to redis.`, error) return res.render('subreddits_explore', { json: null, user_preferences: req.cookies }) } else { console.log(`Fetched the JSON from reddit.com/subreddits.`); (async () => { let processed_json = await processJsonSubredditsExplore(json, 'from_online', null, req.cookies) return res.render('subreddits_explore', { json: processed_json, sortby: sortby, after: after, before: before, q: q, nsfw: nsfw, searching: searching, subreddits_front: (!before && !after) ? true : false, user_preferences: req.cookies, instance_nsfw_enabled: config.nsfw_enabled }) })() } }) }) } else { if(result.status === 404) { console.log('404 – Subreddits not found') } else { console.error(`Something went wrong while fetching data from Reddit. ${result.status} – ${result.statusText}`) console.error(config.reddit_api_error_text) } return res.render('index', { json: null, http_status_code: result.status, user_preferences: req.cookies }) } }).catch(error => { console.error(`Error fetching the JSON file from reddit.com/subreddits.`, error) }) } }) }) app.get('/subscribe/:subreddit', (req, res, next) => { let subreddit = req.params.subreddit let subbed = req.cookies.subbed_subreddits let back = req.query.b if(!subreddit) return res.redirect('/') if(!subbed || !Array.isArray(subbed)) subbed = [] if(!subbed.includes(subreddit)) subbed.push(subreddit) res.cookie('subbed_subreddits', subbed, { maxAge: 365 * 24 * 60 * 60 * 1000, httpOnly: true }) if(!back) return res.redirect('/r/' + subreddit) else { back = back.replace(/,/g, '+').replace(/§1/g, '&') return res.redirect(back) } }) app.get('/import_subscriptions/:subreddits', (req, res, next) => { let subreddits = req.params.subreddits let subbed = req.cookies.subbed_subreddits let back = req.query.b if(!subreddits) return res.redirect('/') if(!subbed || !Array.isArray(subbed)) subbed = [] subreddits = subreddits.split('+') for(var i = 0; i < subreddits.length; i++) { if(!subbed.includes(subreddits[i])) subbed.push(subreddits[i]) } res.cookie('subbed_subreddits', subbed, { maxAge: 365 * 24 * 60 * 60 * 1000, httpOnly: true }) if(!back) return res.redirect('/r/' + subreddits) else { back = back.replace(/,/g, '+').replace(/ /g, '+') return res.redirect(back) } }) app.get('/unsubscribe/:subreddit', (req, res, next) => { let subreddit = req.params.subreddit let subbed = req.cookies.subbed_subreddits let back = req.query.b if(!subreddit || !subbed || !Array.isArray(subbed)) { res.clearCookie('subbed_subreddits') return res.redirect('/') } var index = subbed.indexOf(subreddit) if(index !== -1) subbed.splice(index, 1) if(subbed.length <= 0) res.clearCookie('subbed_subreddits') else res.cookie('subbed_subreddits', subbed, { maxAge: 365 * 24 * 60 * 60 * 1000, httpOnly: true }) if(!back) return res.redirect('/r/' + subreddit) else { back = back.replace(/,/g, '+').replace(/§1/g, '&') return res.redirect(back) } }) app.get('/search', (req, res, next) => { let q = req.query.q if (typeof q === "undefined") { return res.render('search', { json: { posts: [] }, no_query: true, q: '', restrict_sr: undefined, nsfw: undefined, subreddit: 'all', sortby: undefined, past: undefined, user_preferences: req.cookies }) } let restrict_sr = req.query.restrict_sr let nsfw = req.query.nsfw let sortby = req.query.sort let past = req.query.t let after = req.query.after let before = req.query.before if(!after) { after = '' } if(!before) { before = '' } if(restrict_sr !== 'on') { restrict_sr = 'off' } if(nsfw !== 'on') { nsfw = 'off' } let d = `&after=${after}` if(before) { d = `&before=${before}` } return res.redirect(`/r/all/search?q=${q}&restrict_sr=${restrict_sr}&nsfw=${nsfw}&sort=${sortby}&t=${past}${d}`) }) app.get('/:sort?', (req, res, next) => { let past = req.query.t let before = req.query.before let after = req.query.after let sortby = req.params.sort let api_req = req.query.api let api_type = req.query.type let api_target = req.query.target let d = `&after=${after}` if(before) { d = `&before=${before}` } if(!sortby) { sortby = 'hot' } if(['apple-touch-icon.png', 'apple-touch-icon-precomposed.png', 'apple-touch-icon-120x120.png', 'apple-touch-icon-120x120-precomposed.png'].includes(sortby)) { return res.sendStatus(404) // return 404 on shitty apple favicon stuff } if(!['new', 'rising', 'controversial', 'top', 'gilded', 'hot'].includes(sortby)) { console.log(`Got invalid sort.`, req.originalUrl) return res.redirect('/') } if(past) { if(sortby === 'controversial' || sortby === 'top') { if(!['hour', 'day', 'week', 'month', 'year', 'all'].includes(past)) { console.error(`Got invalid past.`, req.originalUrl) return res.redirect(`/`) } } else { past = undefined } } else { if(sortby === 'controversial' || sortby === 'top') { past = 'day' } } if(req.query.hasOwnProperty('api')) api_req = true else api_req = false let key = `/after:${after}:before:${before}:sort:${sortby}:past:${past}` let subbed_subreddits = req.cookies.subbed_subreddits let get_subbed_subreddits = false if(subbed_subreddits && Array.isArray(subbed_subreddits)) { get_subbed_subreddits = true subbed_subreddits = subbed_subreddits.join('+') key = `${subbed_subreddits.toLowerCase()}:${after}:${before}:sort:${sortby}:past:${past}` } redis.get(key, (error, json) => { if(error) { console.error('Error getting the frontpage key from redis.', error) return res.render('index', { json: null, user_preferences: req.cookies }) } if(json) { console.log('Got frontpage key from redis.'); (async () => { if(api_req) { return handleTedditApiSubreddit(json, req, res, 'redis', api_type, api_target, '/') } else { let processed_json = await processJsonSubreddit(json, 'redis', null, req.cookies) return res.render('index', { json: processed_json, sortby: sortby, past: past, user_preferences: req.cookies, redis_key: key }) } })() } else { let url = '' if(config.use_reddit_oauth) { if(get_subbed_subreddits) url = `https://oauth.reddit.com/r/${subbed_subreddits}/${sortby}?api_type=json&count=25&g=GLOBAL&t=${past}${d}` else url = `https://oauth.reddit.com/${sortby}?api_type=json&g=GLOBAL&t=${past}${d}` } else { if(get_subbed_subreddits) url = `https://reddit.com/r/${subbed_subreddits}/${sortby}.json?api_type=json&count=25&g=GLOBAL&t=${past}${d}` else url = `https://reddit.com/${sortby}.json?g=GLOBAL&t=${past}${d}` } fetch(encodeURI(url), redditApiGETHeaders()) .then(result => { if(result.status === 200) { result.json() .then(json => { redis.setex(key, config.setexs.frontpage, JSON.stringify(json), (error) => { if(error) { console.error('Error setting the frontpage key to redis.', error) return res.render('index', { json: null, user_preferences: req.cookies }) } else { console.log('Fetched the frontpage from Reddit.'); (async () => { if(api_req) { return handleTedditApiSubreddit(json, req, res, 'from_online', api_type, api_target, '/') } else { let processed_json = await processJsonSubreddit(json, 'from_online', null, req.cookies) return res.render('index', { json: processed_json, sortby: sortby, past: past, user_preferences: req.cookies, redis_key: key }) } })() } }) }) } else { console.error(`Something went wrong while fetching data from Reddit. ${result.status} – ${result.statusText}`) console.error(config.reddit_api_error_text) return res.render('index', { json: null, http_status_code: result.status, user_preferences: req.cookies }) } }).catch(error => { console.error('Error fetching the frontpage JSON file.', error) }) } }) }) app.get('/comments/:post_id/:comment?/:comment_id?', (req, res, next) => { let post_id = req.params.post_id let comment = req.params.comment let comment_id = req.params.comment_id let back = req.query.b let save = req.query.save let post_url = false let comment_url = false if(comment) if(comment !== 'comment' || !comment_id) return res.redirect('/') if(comment) comment_url = true else post_url = true let key = `/shorturl:post:${post_id}:comment:${comment_id}` redis.get(key, (error, json) => { if(error) { console.error('Error getting the short URL for post key from redis.', error) return res.render('index', { json: null, user_preferences: req.cookies }) } if(json) { console.log('Got short URL for post key from redis.') json = JSON.parse(json) if(post_url) { if(save === 'true') return res.redirect(`/save/${post_id}/?rk=${key}&b=${back}&f=true`) return res.redirect(json[0].data.children[0].data.permalink) } else { return res.redirect(json[1].data.children[0].data.permalink) } } else { let url = '' if(config.use_reddit_oauth) { if(post_url) url = `https://oauth.reddit.com/comments/${post_id}?api_type=json` else url = `https://oauth.reddit.com/comments/${post_id}/comment/${comment_id}?api_type=json` } else { if(post_url) url = `https://reddit.com/comments/${post_id}.json?api_type=json` else url = `https://reddit.com/comments/${post_id}/comment/${comment_id}.json?api_type=json` } fetch(encodeURI(url), redditApiGETHeaders()) .then(result => { if(result.status === 200) { result.json() .then(json => { redis.setex(key, config.setexs.shorts, JSON.stringify(json), (error) => { if(error) { console.error('Error setting the short URL for post key to redis.', error) return res.render('index', { json: null, user_preferences: req.cookies }) } else { console.log('Fetched the short URL for post from Reddit.') if(post_url) { if(save === 'true') return res.redirect(`/save/${post_id}/?rk=${key}&b=${back}&f=true`) return res.redirect(json[0].data.children[0].data.permalink) } else { return res.redirect(json[1].data.children[0].data.permalink) } } }) }) } else { console.error(`Something went wrong while fetching data from Reddit. ${result.status} – ${result.statusText}`) console.error(config.reddit_api_error_text) return res.render('index', { json: null, http_status_code: result.status, user_preferences: req.cookies }) } }).catch(error => { console.error('Error fetching the short URL for post with sortby JSON file.', error) }) } }) }) app.get('/r/:subreddit/search', (req, res, next) => { let subreddit = req.params.subreddit let q = req.query.q if (typeof q === "undefined") { return res.render('search', { json: { posts: [] }, no_query: true, q: '', restrict_sr: undefined, nsfw: undefined, subreddit: subreddit, sortby: undefined, past: undefined, user_preferences: req.cookies }) } let restrict_sr = req.query.restrict_sr let nsfw = req.query.nsfw let sortby = req.query.sort let past = req.query.t let after = req.query.after let before = req.query.before if(!after) { after = '' } if(!before) { before = '' } let d = `&after=${after}` if(before) { d = `&before=${before}` } if(restrict_sr !== 'on') { restrict_sr = 'off' } if(nsfw !== 'on') { nsfw = 'off' } let key = `search:${subreddit}:${q}:${restrict_sr}:${sortby}:${past}:${after}:${before}:${nsfw}` redis.get(key, (error, json) => { if(error) { console.error('Error getting the search key from redis.', error) return res.render('index', { json: null, user_preferences: req.cookies }) } if(json) { console.log('Got search key from redis.'); (async () => { let processed_json = await processSearchResults(json, false, after, before, req.cookies) return res.render('search', { json: processed_json, no_query: false, q: q, restrict_sr: restrict_sr, nsfw: nsfw, subreddit: subreddit, sortby: sortby, past: past, user_preferences: req.cookies }) })() } else { let url = '' if(config.use_reddit_oauth) url = `https://oauth.reddit.com/r/${subreddit}/search?api_type=json&q=${q}&restrict_sr=${restrict_sr}&include_over_18=${nsfw}&sort=${sortby}&t=${past}${d}` else url = `https://reddit.com/r/${subreddit}/search.json?api_type=json&q=${q}&restrict_sr=${restrict_sr}&include_over_18=${nsfw}&sort=${sortby}&t=${past}${d}` fetch(encodeURI(url), redditApiGETHeaders()) .then(result => { if(result.status === 200) { result.json() .then(json => { (async () => { /** * Fetch suggested subreddits when the restrict_sr option is * turned off ("limit my search to") and we are on the first search * page (just like in Reddit). */ json.suggested_subreddits = {} if(restrict_sr === 'off' && before == '' && after == '') { let url = `https://reddit.com/subreddits/search.json?q=${q}&include_over_18=${nsfw}&limit=3` const response = await fetch(encodeURI(url)) const data = await response.json() json.suggested_subreddits = data } redis.setex(key, config.setexs.searches, JSON.stringify(json), (error) => { if(error) { console.error('Error setting the searches key to redis.', error) return res.render('index', { json: null, user_preferences: req.cookies }) } else { console.log('Fetched search results from Reddit.'); (async () => { let processed_json = await processSearchResults(json, true, after, before, req.cookies) return res.render('search', { no_query: false, json: processed_json, q: q, restrict_sr: restrict_sr, nsfw: nsfw, subreddit: subreddit, sortby: sortby, past: past, user_preferences: req.cookies }) })() } }) })() }) } else { console.error(`Something went wrong while fetching data from Reddit. ${result.status} – ${result.statusText}`) console.error(config.reddit_api_error_text) return res.render('index', { json: null, http_status_code: result.status, user_preferences: req.cookies }) } }).catch(error => { console.error('Error fetching the frontpage JSON file.', error) }) } }) }) app.get('/r/:subreddit/wiki/:page?', (req, res, next) => { let subreddit = req.params.subreddit let page = req.params.page if(!page) page = 'index' function formatWikipagelisting(json, subreddit) { let html = '