convert processJsonUser to async function

This commit is contained in:
json 2021-09-07 13:27:29 +01:00
parent d1ef359435
commit f3cc837a01
3 changed files with 200 additions and 172 deletions

View File

@ -1,59 +1,68 @@
module.exports = function() { const config = require('../config');
const config = require('../config'); const link = require('./components/link');
const link = require('./components/link')
this.processJsonUser = function(json, parsed, after, before, user_preferences, kind, post_type) { async function processJsonUser(
return new Promise(resolve => { json,
(async () => { parsed,
if(!parsed) { after,
json = JSON.parse(json) before,
user_preferences,
kind,
post_type
) {
if (!parsed) {
json = JSON.parse(json);
} }
let about = json.about.data let about = json.about.data;
let posts = [] let posts = [];
let view_more_posts = false let view_more_posts = false;
let posts_limit = 25 let posts_limit = 25;
let user_front = false let user_front = false;
if(json.overview.data.children.length > posts_limit) { if (json.overview.data.children.length > posts_limit) {
view_more_posts = true view_more_posts = true;
} else { } else {
posts_limit = json.overview.data.children.length posts_limit = json.overview.data.children.length;
} }
if(!after && !before) { if (!after && !before) {
user_front = true user_front = true;
} }
if(json.overview.data.children) { if (json.overview.data.children) {
if(json.overview.data.children[posts_limit - 1]) { if (json.overview.data.children[posts_limit - 1]) {
after = json.overview.data.children[posts_limit - 1].data.name after = json.overview.data.children[posts_limit - 1].data.name;
} }
if(json.overview.data.children[0]) { if (json.overview.data.children[0]) {
before = json.overview.data.children[0].data.name before = json.overview.data.children[0].data.name;
} }
} }
for(var i = 0; i < posts_limit; i++) { for (var i = 0; i < posts_limit; i++) {
let post = json.overview.data.children[i].data let post = json.overview.data.children[i].data;
let thumbnail = 'self' let thumbnail = 'self';
let type = json.overview.data.children[i].kind let type = json.overview.data.children[i].kind;
let obj let obj;
let post_id = post.permalink.split('/').slice(-2)[0] + '/' let post_id = post.permalink.split('/').slice(-2)[0] + '/';
let url = post.permalink.replace(post_id, '') let url = post.permalink.replace(post_id, '');
if(type !== kind && kind) if (type !== kind && kind) continue;
continue
if(post.over_18) if (post.over_18)
if((config.nsfw_enabled === false && user_preferences.nsfw_enabled != 'true') || user_preferences.nsfw_enabled === 'false') if (
continue (config.nsfw_enabled === false &&
user_preferences.nsfw_enabled != 'true') ||
user_preferences.nsfw_enabled === 'false'
)
continue;
if(type === 't3') { if (type === 't3') {
obj = await link.fromJson(post, user_preferences) obj = await link.fromJson(post, user_preferences);
obj.type = 't3' obj.type = 't3';
} }
if(type === 't1') { if (type === 't1') {
obj = { obj = {
type: type, type: type,
subreddit: post.subreddit, subreddit: post.subreddit,
@ -69,15 +78,16 @@ module.exports = function() {
permalink: post.permalink, permalink: post.permalink,
link_author: post.link_author, link_author: post.link_author,
link_title: post.link_title, link_title: post.link_title,
user_flair: (user_preferences.flairs != 'false' ? await formatUserFlair(post) : '') user_flair:
user_preferences.flairs != 'false' ? await formatUserFlair(post) : '',
};
} }
} posts.push(obj);
posts.push(obj)
} }
let obj = { let obj = {
username: about.name, username: about.name,
icon_img: await downloadAndSave(about.icon_img, "icon_"), icon_img: await downloadAndSave(about.icon_img, 'icon_'),
created: about.created_utc, created: about.created_utc,
verified: about.verified, verified: about.verified,
link_karma: about.link_karma, link_karma: about.link_karma,
@ -87,11 +97,10 @@ module.exports = function() {
post_type: post_type, post_type: post_type,
before: before, before: before,
after: after, after: after,
posts: posts posts: posts,
} };
resolve(obj) return obj;
})()
})
}
} }
module.exports = processJsonUser;

View File

@ -1,73 +1,85 @@
module.exports = function() { const processJsonUser = require('../processJsonUser');
const config = require('../../config')
this.handleTedditApiUser = async (json, req, res, from, api_type, api_target, user) => { module.exports = function () {
if(!config.api_enabled) { const config = require('../../config');
res.setHeader('Content-Type', 'application/json') this.handleTedditApiUser = async (
let msg = { info: 'This instance do not support API requests. Please see https://codeberg.org/teddit/teddit#instances for instances that support API, or setup your own instance.' } json,
return res.end(JSON.stringify(msg)) req,
res,
from,
api_type,
api_target,
user
) => {
if (!config.api_enabled) {
res.setHeader('Content-Type', 'application/json');
let msg = {
info: 'This instance do not support API requests. Please see https://codeberg.org/teddit/teddit#instances for instances that support API, or setup your own instance.',
};
return res.end(JSON.stringify(msg));
} }
console.log('Teddit API request - user') console.log('Teddit API request - user');
let _json = json // Keep the original json let _json = json; // Keep the original json
if(from === 'redis') if (from === 'redis') json = JSON.parse(json);
json = JSON.parse(json)
let protocol = (config.https_enabled ? 'https' : 'http') let protocol = config.https_enabled ? 'https' : 'http';
let link = `${protocol}://${config.domain}/user/${user}` let link = `${protocol}://${config.domain}/user/${user}`;
if(api_type === 'rss') { if (api_type === 'rss') {
let items = '' let items = '';
let posts_limit = 25 let posts_limit = 25;
if(json.overview.data.children.length <= posts_limit) { if (json.overview.data.children.length <= posts_limit) {
posts_limit = json.overview.data.children.length posts_limit = json.overview.data.children.length;
} }
for(var i = 0; i < posts_limit; i++) { for (var i = 0; i < posts_limit; i++) {
let post = json.overview.data.children[i].data let post = json.overview.data.children[i].data;
let post_id = post.permalink.split('/').slice(-2)[0] + '/' let post_id = post.permalink.split('/').slice(-2)[0] + '/';
let url = post.permalink.replace(post_id, '') let url = post.permalink.replace(post_id, '');
let permalink = `${protocol}://${config.domain}${post.permalink}` let permalink = `${protocol}://${config.domain}${post.permalink}`;
let comments_url = `${protocol}://${config.domain}${url}` let comments_url = `${protocol}://${config.domain}${url}`;
let kind = json.overview.data.children[i].kind let kind = json.overview.data.children[i].kind;
let t1_elements = '' let t1_elements = '';
let t3_elements = '' let t3_elements = '';
if(kind === 't1') { if (kind === 't1') {
let append_desc_html = `<br/><a href="${permalink}">[link]</a> <a href="${comments_url}">[comments]</a>` let append_desc_html = `<br/><a href="${permalink}">[link]</a> <a href="${comments_url}">[comments]</a>`;
t1_elements = ` t1_elements = `
<description><![CDATA[${unescape(post.body_html)}${append_desc_html}]]></description> <description><![CDATA[${unescape(
post.body_html
)}${append_desc_html}]]></description>
<url>${comments_url}</url> <url>${comments_url}</url>
` `;
} }
if(kind === 't3') { if (kind === 't3') {
let s = await downloadAndSave(post.thumbnail, 'thumb_') let s = await downloadAndSave(post.thumbnail, 'thumb_');
let thumbnail = '' let thumbnail = '';
let enclosure = '' let enclosure = '';
if(s !== 'self' && s != '') { if (s !== 'self' && s != '') {
let img = `${protocol}://${config.domain}${s}` let img = `${protocol}://${config.domain}${s}`;
thumbnail = `<thumbnail>${img}</thumbnail>` thumbnail = `<thumbnail>${img}</thumbnail>`;
let mime = '' let mime = '';
let ext = s.split('.').pop() let ext = s.split('.').pop();
if(ext === 'png') if (ext === 'png') mime = 'image/png';
mime = 'image/png' else mime = 'image/jpeg';
else enclosure = `<enclosure length="0" type="${mime}" url="${img}" />`;
mime = 'image/jpeg'
enclosure = `<enclosure length="0" type="${mime}" url="${img}" />`
} }
let append_desc_html = `submitted by <a href="${protocol}://${config.domain}/u/${user}>/u/${user}</a> to <a href="${protocol}://${config.domain}/r/${post.subreddit}/">r/${post.subreddit}</a>` let append_desc_html = `submitted by <a href="${protocol}://${config.domain}/u/${user}>/u/${user}</a> to <a href="${protocol}://${config.domain}/r/${post.subreddit}/">r/${post.subreddit}</a>`;
append_desc_html += `<br/><a href="${permalink}">[comments]</a>` append_desc_html += `<br/><a href="${permalink}">[comments]</a>`;
t3_elements = ` t3_elements = `
<description><![CDATA[${unescape(post.selftext_html)}${append_desc_html}]]></description> <description><![CDATA[${unescape(
post.selftext_html
)}${append_desc_html}]]></description>
${thumbnail} ${thumbnail}
${enclosure} ${enclosure}
` `;
} }
let title = post.title let title = post.title;
if(!post.title) if (!post.title) title = post.link_title;
title = post.link_title
items += ` items += `
<item> <item>
@ -76,7 +88,9 @@ module.exports = function() {
<kind>${kind}</kind> <kind>${kind}</kind>
<subreddit>${post.subreddit}</subreddit> <subreddit>${post.subreddit}</subreddit>
<created>${post.created_utc}</created> <created>${post.created_utc}</created>
<pubDate>${new Date(post.created_utc*1000).toGMTString()}</pubDate> <pubDate>${new Date(
post.created_utc * 1000
).toGMTString()}</pubDate>
<ups>${post.ups}</ups> <ups>${post.ups}</ups>
<link>${permalink}</link> <link>${permalink}</link>
<edited>${post.edited}</edited> <edited>${post.edited}</edited>
@ -85,11 +99,10 @@ module.exports = function() {
${t1_elements} ${t1_elements}
${t3_elements} ${t3_elements}
</item> </item>
` `;
} }
let xml_output = let xml_output = `<?xml version="1.0" encoding="UTF-8"?>
`<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0"> <rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0">
<channel> <channel>
<atom:link href="${link}/?api&amp;type=rss" rel="self" type="application/rss+xml" /> <atom:link href="${link}/?api&amp;type=rss" rel="self" type="application/rss+xml" />
@ -97,17 +110,23 @@ module.exports = function() {
<link>${link}</link> <link>${link}</link>
${items} ${items}
</channel> </channel>
</rss>` </rss>`;
res.setHeader('Content-Type', 'application/rss+xml') res.setHeader('Content-Type', 'application/rss+xml');
return res.end(xml_output) return res.end(xml_output);
} else { } else {
res.setHeader('Content-Type', 'application/json') res.setHeader('Content-Type', 'application/json');
if(api_target === 'reddit') { if (api_target === 'reddit') {
return res.end(JSON.stringify(json)) return res.end(JSON.stringify(json));
} else { } else {
let processed_json = await processJsonUser(json, true, null, null, req.cookies) let processed_json = await processJsonUser(
return res.end(JSON.stringify(processed_json)) json,
true,
null,
null,
req.cookies
);
return res.end(JSON.stringify(processed_json));
} }
} }
} };
} };

View File

@ -2,7 +2,7 @@ const config = require('../config');
const { redis, fetch } = require('../app'); const { redis, fetch } = require('../app');
const userRoutes = require('express').Router(); const userRoutes = require('express').Router();
const processUser = require('../inc/processJsonUser.js')(); const processJsonUser = require('../inc/processJsonUser.js');
const processPost = require('../inc/processJsonPost.js')(); const processPost = require('../inc/processJsonPost.js')();
const processAbout = require('../inc/processSubredditAbout.js')(); const processAbout = require('../inc/processSubredditAbout.js')();
const tedditApiUser = require('../inc/teddit_api/handleUser.js')(); const tedditApiUser = require('../inc/teddit_api/handleUser.js')();