2022-12-14 21:45:42 +01:00
const { processJsonPost , getPostItem } = require ( '../processJsonPost' ) ;
module . exports = function ( ) {
const config = require ( '../../config' ) ;
this . handleTedditApiPost = async (
json ,
req ,
res ,
from ,
api _type ,
api _target
) => {
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 - post' ) ;
if ( from === 'redis' ) json = JSON . parse ( json ) ;
if ( api _type === 'rss' ) {
let protocol = config . https _enabled || config . api _force _https ? 'https' : 'http' ;
let items = '' ;
let post = json [ 0 ] . data . children [ 0 ] . data ;
let comments = json [ 1 ] . data . children ;
2022-12-15 20:16:13 +01:00
items += await getPostItem ( post , req , protocol ) ;
2022-12-14 21:45:42 +01:00
for ( var i = 0 ; i < comments . length ; i ++ ) {
let comment = comments [ i ] . data ;
let kind = comments [ i ] . kind ;
let title = ` /u/ ${ comment . author } on ${ post . title } ` ;
comment . permalink = ` ${ protocol } :// ${ config . domain } ${ comment . permalink } ` ;
if ( kind !== 'more' ) {
items += `
< item >
< title > $ { title } < / t i t l e >
< author > $ { comment . author } < / a u t h o r >
< created > $ { comment . created } < / c r e a t e d >
< pubDate > $ { new Date (
comment . created _utc * 1000
) . toGMTString ( ) } < / p u b D a t e >
< id > $ { comment . id } < / i d >
< link > $ { comment . permalink } < / l i n k >
< description > < ! [ CDATA [ $ { unescape (
comment . body _html
) } ] ] > < / d e s c r i p t i o n >
< ups > $ { comment . ups } < / u p s >
< / i t e m >
` ;
}
}
let xml _output = ` <?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" >
< channel >
< atom : link href = "${post.permalink}?api&type=rss" rel = "self" type = "application/rss+xml" / >
< title > $ { post . title } < / t i t l e >
< link > $ { post . url } < / l i n k >
$ { items }
< / c h a n n e l >
< / r s s > ` ;
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 processJsonPost (
json ,
true ,
req . cookies
) ;
return res . end ( JSON . stringify ( processed _json ) ) ;
}
}
} ;
} ;