const processJsonUser = require('../processJsonUser');
module.exports = function () {
const config = require('../../config');
this.handleTedditApiUser = async (
json,
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');
let _json = json; // Keep the original json
if (from === 'redis') json = JSON.parse(json);
let protocol = config.https_enabled ? 'https' : 'http';
let link = `${protocol}://${config.domain}/user/${user}`;
if (api_type === 'rss') {
let items = '';
let posts_limit = 25;
if (json.overview.data.children.length <= posts_limit) {
posts_limit = json.overview.data.children.length;
}
for (var i = 0; i < posts_limit; i++) {
let post = json.overview.data.children[i].data;
let post_id = post.permalink.split('/').slice(-2)[0] + '/';
let url = post.permalink.replace(post_id, '');
let permalink = `${protocol}://${config.domain}${post.permalink}`;
let comments_url = `${protocol}://${config.domain}${url}`;
let kind = json.overview.data.children[i].kind;
let t1_elements = '';
let t3_elements = '';
if (kind === 't1') {
let append_desc_html = `
[link] [comments]`;
t1_elements = `
${comments_url}
`;
}
if (kind === 't3') {
let s = await downloadAndSave(post.thumbnail, 'thumb_');
let thumbnail = '';
let enclosure = '';
if (s !== 'self' && s != '') {
let img = `${protocol}://${config.domain}${s}`;
thumbnail = `${img}`;
let mime = '';
let ext = s.split('.').pop();
if (ext === 'png') mime = 'image/png';
else mime = 'image/jpeg';
enclosure = ``;
}
let append_desc_html = `submitted by r/${post.subreddit}`;
append_desc_html += `
[comments]`;
t3_elements = `
${thumbnail}
${enclosure}
`;
}
let title = post.title;
if (!post.title) title = post.link_title;
items += `
-
${title}
/u/${user}
${kind}
${post.subreddit}
${post.created_utc}
${new Date(
post.created_utc * 1000
).toGMTString()}
${post.ups}
${permalink}
${post.edited}
${post.num_comments}
${post.over_18}
${t1_elements}
${t3_elements}
`;
}
let xml_output = `
overview for ${user}
${link}
${items}
`;
res.setHeader('Content-Type', 'application/rss+xml');
return res.end(xml_output);
} else {
res.setHeader('Content-Type', 'application/json');
if (api_target === 'reddit') {
return res.end(JSON.stringify(json));
} else {
let processed_json = await processJsonUser(
json,
true,
null,
null,
req.cookies
);
return res.end(JSON.stringify(processed_json));
}
}
};
};