2021-09-07 15:24:10 +02:00
|
|
|
|
const config = require('../config');
|
2021-09-08 10:32:26 +02:00
|
|
|
|
const { redisAsync } = require('./redis');
|
|
|
|
|
|
|
|
|
|
function returnRelevantKeys(json) {
|
|
|
|
|
return {
|
|
|
|
|
title: json.data.title,
|
|
|
|
|
public_description_html: json.data.public_description_html,
|
|
|
|
|
active_user_count: json.data.active_user_count,
|
|
|
|
|
subscribers: json.data.subscribers,
|
|
|
|
|
created_utc: json.data.created_utc,
|
|
|
|
|
over18: json.data.over18,
|
|
|
|
|
description_html: json.data.description_html,
|
|
|
|
|
moderators: json.moderators,
|
|
|
|
|
};
|
|
|
|
|
}
|
2021-09-07 15:24:10 +02:00
|
|
|
|
|
|
|
|
|
async function processSubredditAbout(subreddit, redis, fetch, RedditAPI) {
|
|
|
|
|
if (subreddit && !subreddit.includes('+') && subreddit !== 'all') {
|
2021-09-08 10:32:26 +02:00
|
|
|
|
const key = `${subreddit}:sidebar`;
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
const cached = await redisAsync.get(key);
|
|
|
|
|
|
|
|
|
|
if (cached !== null) {
|
|
|
|
|
return returnRelevantKeys(JSON.parse(cached));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let url = `https://reddit.com/r/${subreddit}/about.json`;
|
|
|
|
|
|
|
|
|
|
if (config.use_reddit_oauth) {
|
|
|
|
|
url = `https://oauth.reddit.com/r/${subreddit}/about`;
|
|
|
|
|
}
|
2021-09-07 15:24:10 +02:00
|
|
|
|
|
2021-09-08 10:32:26 +02:00
|
|
|
|
const subredditAboutRequest = await fetch(url, redditApiGETHeaders());
|
|
|
|
|
|
|
|
|
|
if (subredditAboutRequest.ok) {
|
|
|
|
|
let response = await subredditAboutRequest.json();
|
|
|
|
|
response.moderators = [];
|
|
|
|
|
|
|
|
|
|
await redisAsync.setex(
|
|
|
|
|
key,
|
|
|
|
|
config.setexs.sidebar,
|
|
|
|
|
JSON.stringify(response)
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
console.log(`Fetched sidebar for ${subreddit} from reddit API`);
|
|
|
|
|
|
|
|
|
|
return returnRelevantKeys(response);
|
|
|
|
|
} else {
|
2021-09-07 15:24:10 +02:00
|
|
|
|
console.error(
|
2021-09-08 10:32:26 +02:00
|
|
|
|
`Something went wrong while fetching data from reddit API:
|
|
|
|
|
${subredditAboutRequest.status} – ${subredditAboutRequest.statusText}`
|
2021-09-07 15:24:10 +02:00
|
|
|
|
);
|
2021-09-08 10:32:26 +02:00
|
|
|
|
console.error(config.reddit_api_error_text);
|
2021-09-07 15:24:10 +02:00
|
|
|
|
return null;
|
|
|
|
|
}
|
2021-09-08 10:32:26 +02:00
|
|
|
|
} catch (error) {
|
|
|
|
|
console.error('Error fetching the sidebar: ', error);
|
2021-09-07 15:24:10 +02:00
|
|
|
|
|
2021-09-08 10:32:26 +02:00
|
|
|
|
return null;
|
|
|
|
|
}
|
2021-09-07 15:24:10 +02:00
|
|
|
|
} else {
|
|
|
|
|
return null;
|
2020-12-28 00:16:45 +01:00
|
|
|
|
}
|
|
|
|
|
}
|
2021-09-07 15:24:10 +02:00
|
|
|
|
|
|
|
|
|
module.exports = processSubredditAbout;
|