Merge pull request 'main' (#9) from teddit/teddit:main into changelog

Reviewed-on: https://codeberg.org/random_guy52/teddit/pulls/9
This commit is contained in:
random_guy52 2021-01-31 12:48:17 +01:00
commit c300d23fe7
18 changed files with 186 additions and 33 deletions

View File

@ -26,10 +26,10 @@ Community instances:
* [https://teddit.ggc-project.de](https://teddit.ggc-project.de) * [https://teddit.ggc-project.de](https://teddit.ggc-project.de)
* [https://teddit.kavin.rocks](https://teddit.kavin.rocks) * [https://teddit.kavin.rocks](https://teddit.kavin.rocks)
* [https://teddit.zaggy.nl](https://teddit.zaggy.nl)
## TODO ## TODO
* Import/export preferences
* User trophies * User trophies
* "other discussions" feature * "other discussions" feature
* "Open on reddit" links * "Open on reddit" links
@ -37,7 +37,6 @@ Community instances:
## Roadmap ## Roadmap
* More themes, not just white or dark
* HLS video streaming? (Would require browser JavaScript) * HLS video streaming? (Would require browser JavaScript)
* Onion site * Onion site
* User login, so people can use their Reddit account through teddit to comment and up/downvote posts etc. * User login, so people can use their Reddit account through teddit to comment and up/downvote posts etc.

1
app.js
View File

@ -11,7 +11,6 @@ const express = require('express')
const cookieParser = require('cookie-parser') const cookieParser = require('cookie-parser')
const r = require('redis') const r = require('redis')
const redis = (() => { const redis = (() => {
if (!config.redis_enabled) { if (!config.redis_enabled) {
// Stub Redis if disabled // Stub Redis if disabled

View File

@ -1,6 +1,6 @@
module.exports = function() { module.exports = function() {
const config = require('../config'); const config = require('../config');
this.processJsonUser = function(json, parsed, after, before, user_preferences) { this.processJsonUser = function(json, parsed, after, before, user_preferences, kind, post_type) {
return new Promise(resolve => { return new Promise(resolve => {
(async () => { (async () => {
if(!parsed) { if(!parsed) {
@ -40,7 +40,10 @@ module.exports = function() {
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)
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((config.nsfw_enabled === false && user_preferences.nsfw_enabled != 'true') || user_preferences.nsfw_enabled === 'false')
continue continue
@ -103,6 +106,7 @@ module.exports = function() {
comment_karma: about.comment_karma, comment_karma: about.comment_karma,
view_more_posts: view_more_posts, view_more_posts: view_more_posts,
user_front: user_front, user_front: user_front,
post_type: post_type,
before: before, before: before,
after: after, after: after,
posts: posts posts: posts

View File

@ -69,6 +69,7 @@ module.exports = function() {
<title>${link.title}</title> <title>${link.title}</title>
<author>${link.author}</author> <author>${link.author}</author>
<created>${link.created}</created> <created>${link.created}</created>
<pubDate>${new Date(link.created_utc*1000).toGMTString()}</pubDate>
<domain>${link.domain}</domain> <domain>${link.domain}</domain>
<id>${link.id}</id> <id>${link.id}</id>
<thumbnail>${thumbnail}</thumbnail> <thumbnail>${thumbnail}</thumbnail>

View File

@ -74,6 +74,7 @@ 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>
<ups>${post.ups}</ups> <ups>${post.ups}</ups>
<link>${permalink}</link> <link>${permalink}</link>
<edited>${post.edited}</edited> <edited>${post.edited}</edited>

103
routes.js
View File

@ -28,6 +28,42 @@ module.exports = (app, redis, fetch, RedditAPI) => {
res.clearCookie('subbed_subreddits') res.clearCookie('subbed_subreddits')
return res.redirect('/preferences') 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('/preferences')
} 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) => { app.get('/privacy', (req, res, next) => {
return res.render('privacypolicy', { user_preferences: req.cookies }) return res.render('privacypolicy', { user_preferences: req.cookies })
@ -1001,14 +1037,25 @@ module.exports = (app, redis, fetch, RedditAPI) => {
}) })
}) })
app.get('/user/:user', (req, res, next) => { app.get('/user/:user/:kind?', (req, res, next) => {
res.redirect(`/u/${req.params.user}`) let kind = ''
if(req.params.kind)
kind = `/${req.params.kind}`
let q = ''
if(req.query.sort)
q += `?sort=${req.query.sort}&`
if(req.query.t)
q += `t=${req.query.t}`
res.redirect(`/u/${req.params.user}${kind}${q}`)
}) })
app.get('/u/:user/:sort?', (req, res, next) => { app.get('/u/:user/:kind?', (req, res, next) => {
let user = req.params.user let user = req.params.user
let after = req.query.after let after = req.query.after
let before = req.query.before let before = req.query.before
let post_type = req.params.kind
let kind = post_type
let user_data = {} let user_data = {}
let api_req = req.query.api let api_req = req.query.api
let api_type = req.query.type let api_type = req.query.type
@ -1029,6 +1076,19 @@ module.exports = (app, redis, fetch, RedditAPI) => {
if(before) { if(before) {
d = `&before=${before}` d = `&before=${before}`
} }
post_type = `/${post_type}`
switch(post_type) {
case '/comments':
kind = 't1'
break;
case '/submitted':
kind = 't3'
break;
default:
post_type = ''
kind = ''
}
let sortby = req.query.sort let sortby = req.query.sort
let past = req.query.t let past = req.query.t
@ -1059,7 +1119,7 @@ module.exports = (app, redis, fetch, RedditAPI) => {
} }
} }
let key = `${user}:${after}:${before}:sort:${sortby}:past:${past}` let key = `${user}:${after}:${before}:sort:${sortby}:past:${past}:post_type:${post_type}`
redis.get(key, (error, json) => { redis.get(key, (error, json) => {
if(error) { if(error) {
console.error(`Error getting the user ${key} key from redis.`, error) console.error(`Error getting the user ${key} key from redis.`, error)
@ -1068,10 +1128,10 @@ module.exports = (app, redis, fetch, RedditAPI) => {
if(json) { if(json) {
console.log(`Got user ${user} key from redis.`); console.log(`Got user ${user} key from redis.`);
(async () => { (async () => {
if(api_req) { if(api_req) {
return handleTedditApiUser(json, req, res, 'redis', api_type, api_target, user, after, before) return handleTedditApiUser(json, req, res, 'redis', api_type, api_target, user, after, before)
} else { } else {
let processed_json = await processJsonUser(json, false, after, before, req.cookies) let processed_json = await processJsonUser(json, false, after, before, req.cookies, kind, post_type)
return res.render('user', { return res.render('user', {
data: processed_json, data: processed_json,
sortby: sortby, sortby: sortby,
@ -1093,10 +1153,14 @@ module.exports = (app, redis, fetch, RedditAPI) => {
.then(json => { .then(json => {
user_data.about = json user_data.about = json
let url = '' let url = ''
if(config.use_reddit_oauth) if(config.use_reddit_oauth) {
url = `https://oauth.reddit.com/user/${user}/overview?limit=26${d}&sort=${sortby}&t=${past}` let endpoint = '/overview'
else if(post_type !== '')
url = `https://reddit.com/user/${user}.json?limit=26${d}&sort=${sortby}&t=${past}` endpoint = post_type
url = `https://oauth.reddit.com/user/${user}${post_type}?limit=26${d}&sort=${sortby}&t=${past}`
} else {
url = `https://reddit.com/user/${user}${post_type}.json?limit=26${d}&sort=${sortby}&t=${past}`
}
fetch(encodeURI(url), redditApiGETHeaders()) fetch(encodeURI(url), redditApiGETHeaders())
.then(result => { .then(result => {
if(result.status === 200) { if(result.status === 200) {
@ -1109,10 +1173,10 @@ module.exports = (app, redis, fetch, RedditAPI) => {
return res.render('index', { post: null, user_preferences: req.cookies }) return res.render('index', { post: null, user_preferences: req.cookies })
} else { } else {
(async () => { (async () => {
if(api_req) { if(api_req) {
return handleTedditApiUser(user_data, req, res, 'online', api_type, api_target, user, after, before) return handleTedditApiUser(user_data, req, res, 'online', api_type, api_target, user, after, before)
} else { } else {
let processed_json = await processJsonUser(user_data, true, after, before, req.cookies) let processed_json = await processJsonUser(user_data, true, after, before, req.cookies, kind, post_type)
return res.render('user', { return res.render('user', {
data: processed_json, data: processed_json,
sortby: sortby, sortby: sortby,
@ -1144,7 +1208,7 @@ module.exports = (app, redis, fetch, RedditAPI) => {
}) })
} else { } else {
if(result.status === 404) { if(result.status === 404) {
console.log('404  User not found') console.log('404 User not found')
} else { } else {
console.error(`Something went wrong while fetching data from Reddit. ${result.status} ${result.statusText}`) console.error(`Something went wrong while fetching data from Reddit. ${result.status} ${result.statusText}`)
console.error(config.reddit_api_error_text) console.error(config.reddit_api_error_text)
@ -1196,6 +1260,19 @@ module.exports = (app, redis, fetch, RedditAPI) => {
return res.redirect('/preferences') return res.redirect('/preferences')
}) })
app.post('/export_prefs', (req, res, next) => {
let r = `${(Math.random().toString(36)+'00000000000000000').slice(2, 10+2).toUpperCase()}`
let key = `prefs_key:${r}`
redis.set(key, JSON.stringify(req.cookies), (error) => {
if(error) {
console.error(`Error saving preferences to redis.`, error)
return res.redirect('/preferences')
} else {
return res.render('preferences', { user_preferences: req.cookies, instance_config: config, preferences_key: r })
}
})
})
app.post('/r/:subreddit/comments/:id/:snippet', (req, res, next) => { app.post('/r/:subreddit/comments/:id/:snippet', (req, res, next) => {
/* morechildren route */ /* morechildren route */

View File

@ -223,4 +223,11 @@ body.sepia .comments > form button {
body.sepia #sidebar { body.sepia #sidebar {
width: 100%; width: 100%;
} }
body.sepia #links .link .entry details[open] .preview {
width: calc(100vw - 34px);
margin-left: 3px;
}
body.sepia #links .link .entry .selftext {
width: calc(100vw - 70px);
}
} }

View File

@ -150,6 +150,12 @@ form .setting {
margin: 10px 0; margin: 10px 0;
width: 100%; width: 100%;
} }
#export-form {
margin: 60px 0px 0px 0px;
}
#export-form input {
margin: 10px 0px 10px 0px;
}
.container .content small.notice { .container .content small.notice {
padding-top: 20px; padding-top: 20px;
padding-bottom: 5px; padding-bottom: 5px;
@ -183,6 +189,9 @@ header a {
header a.main { header a.main {
margin-left: 12px; margin-left: 12px;
} }
header h3.username {
margin: 0px 15px 0px 0px;
}
header .bottom { header .bottom {
float: left; float: left;
overflow: hidden; overflow: hidden;
@ -497,6 +506,9 @@ footer a {
#links .link .entry details .line:first-child { #links .link .entry details .line:first-child {
margin-top: 0; margin-top: 0;
} }
#links .link .entry details.preview-container img {
max-height: 600px !important;
}
/* COMMENTS */ /* COMMENTS */
.comment { .comment {
font-size: 0.83rem; font-size: 0.83rem;
@ -1542,4 +1554,13 @@ code {
.explore#links .link .entry { .explore#links .link .entry {
width: calc(100% - 20px); width: calc(100% - 20px);
} }
#links .link .entry details[open] .preview {
width: 100vw;
transform: translateX(-150px);
}
#links .link .entry .selftext {
width: calc(100vw - 40px);
transform: translateX(-150px);
margin-left: 10px;
}
} }

View File

@ -3,7 +3,7 @@ html
head head
title about - teddit title about - teddit
include includes/head.pug include includes/head.pug
body(class=""+ user_preferences.theme +"") body(class=""+ (user_preferences.theme === 'auto' ? 'dark' : user_preferences.theme) + "")
include includes/topbar.pug include includes/topbar.pug
.container .container
.content .content

View File

@ -1,3 +1,5 @@
if(user_preferences.theme === 'auto')
link(rel="stylesheet", type="text/css", href="/css/dark.css", media="(prefers-color-scheme: dark)")
if(user_preferences.theme === 'dark') if(user_preferences.theme === 'dark')
link(rel="stylesheet", type="text/css", href="/css/dark.css") link(rel="stylesheet", type="text/css", href="/css/dark.css")
if(user_preferences.theme === 'sepia') if(user_preferences.theme === 'sepia')

View File

@ -3,7 +3,7 @@ html
head head
title teddit title teddit
include includes/head.pug include includes/head.pug
body(class=""+ user_preferences.theme +"") body(class=""+ (user_preferences.theme === 'auto' ? 'dark' : user_preferences.theme) + "")
include includes/topbar.pug include includes/topbar.pug
if json === null if json === null
h2 error h2 error

View File

@ -3,7 +3,7 @@ html
head head
title #{cleanTitle(post.title)} : #{subreddit} title #{cleanTitle(post.title)} : #{subreddit}
include includes/head.pug include includes/head.pug
body(class=""+ user_preferences.theme +"") body(class=""+ (user_preferences.theme === 'auto' ? 'dark' : user_preferences.theme) + "")
include includes/topbar.pug include includes/topbar.pug
if post === null if post === null
h1 Error occured h1 Error occured

View File

@ -3,7 +3,7 @@ html
head head
title preferences - teddit title preferences - teddit
include includes/head.pug include includes/head.pug
body(class=""+ user_preferences.theme +"") body(class=""+ (user_preferences.theme === 'auto' ? 'dark' : user_preferences.theme) + "")
include includes/topbar.pug include includes/topbar.pug
.container .container
.content .content
@ -14,17 +14,25 @@ html
label(for="theme") Theme: label(for="theme") Theme:
select(id="theme", name="theme") select(id="theme", name="theme")
if(!user_preferences.theme || user_preferences.theme == '') if(!user_preferences.theme || user_preferences.theme == '')
option(value="auto") Auto
option(value="", selected="selected") White option(value="", selected="selected") White
option(value="dark") Dark option(value="dark") Dark
option(value="sepia") Sepia option(value="sepia") Sepia
if(user_preferences.theme === 'dark') if(user_preferences.theme === 'dark')
option(value="auto") Auto
option(value="") White option(value="") White
option(value="dark", selected="selected") Dark option(value="dark", selected="selected") Dark
option(value="sepia") Sepia option(value="sepia") Sepia
if(user_preferences.theme === 'sepia') if(user_preferences.theme === 'sepia')
option(value="auto") Auto
option(value="") White option(value="") White
option(value="dark") Dark option(value="dark") Dark
option(value="sepia", selected="selected") Sepia option(value="sepia", selected="selected") Sepia
if(user_preferences.theme === 'auto')
option(value="auto", selected="selected") Auto
option(value="") White
option(value="dark") Dark
option(value="sepia") Sepia
.setting .setting
label(for="flairs") Show flairs: label(for="flairs") Show flairs:
if(!user_preferences.flairs || user_preferences.flairs == 'true') if(!user_preferences.flairs || user_preferences.flairs == 'true')
@ -59,4 +67,27 @@ html
small(class="notice") Preferences are stored client-side using cookies without any personal information. small(class="notice") Preferences are stored client-side using cookies without any personal information.
input(type="submit", value="Save preferences") input(type="submit", value="Save preferences")
a(href="/resetprefs", class="btn") Reset preferences a(href="/resetprefs", class="btn") Reset preferences
form(action="/export_prefs", method="POST", id="export-form")
if preferences_key
details(open)
summary
span Export preferences
.setting
small By exporting your preferences you can transfer your subscribed subreddits and preferences to another device. Or you could create a bookmark if you tend to delete your cookies frequently.
br
input(type="submit", value="Export preferences")
if preferences_key
- var protocol = 'http'
if instance_config.https_enabled === true
- var protocol = 'https'
p Visit this URL to import your preferences:
a(href=`${protocol}://${instance_config.domain}/import_prefs/${preferences_key}`) #{protocol}://#{instance_config.domain}/import_prefs/#{preferences_key}
else
details
summary
span Export preferences
.setting
small By exporting your preferences you can transfer your subscribed subreddits and preferences to another device. Or you could create a bookmark if you tend to delete your cookies frequently.
br
input(type="submit", value="Export preferences")
include includes/footer.pug include includes/footer.pug

View File

@ -3,7 +3,7 @@ html
head head
title privacy policy - teddit title privacy policy - teddit
include includes/head.pug include includes/head.pug
body(class=""+ user_preferences.theme +"") body(class=""+ (user_preferences.theme === 'auto' ? 'dark' : user_preferences.theme) + "")
include includes/topbar.pug include includes/topbar.pug
.container .container
.content .content

View File

@ -6,7 +6,7 @@ html
else else
title search results for #{q} title search results for #{q}
include includes/head.pug include includes/head.pug
body(class=""+ user_preferences.theme +"") body(class=""+ (user_preferences.theme === 'auto' ? 'dark' : user_preferences.theme) + "")
include includes/topbar.pug include includes/topbar.pug
#search.sr.search-page #search.sr.search-page
form(action="/r/" + subreddit + "/search", method="GET") form(action="/r/" + subreddit + "/search", method="GET")

View File

@ -3,7 +3,7 @@ html
head head
title /r/#{subreddit} title /r/#{subreddit}
include includes/head.pug include includes/head.pug
body(class=""+ user_preferences.theme +"") body(class=""+ (user_preferences.theme === 'auto' ? 'dark' : user_preferences.theme) + "")
include includes/topbar.pug include includes/topbar.pug
- -
let show_nsfw_warning = false; let show_nsfw_warning = false;

View File

@ -3,7 +3,7 @@ html
head head
title subreddits - explore title subreddits - explore
include includes/head.pug include includes/head.pug
body(class=""+ user_preferences.theme +"") body(class=""+ (user_preferences.theme === 'auto' ? 'dark' : user_preferences.theme) + "")
include includes/topbar.pug include includes/topbar.pug
if json === null if json === null
h1 Error occured h1 Error occured

View File

@ -3,13 +3,24 @@ html
head head
title overview for #{data.username} title overview for #{data.username}
include includes/head.pug include includes/head.pug
body(class=""+ user_preferences.theme +"") body(class=""+ (user_preferences.theme === 'auto' ? 'dark' : user_preferences.theme) + "")
include includes/topbar.pug include includes/topbar.pug
if user === null if user === null
h1 Error occured h1 Error occured
p #{JSON.stringify(error_data)} p #{JSON.stringify(error_data)}
else else
#user #user
header
.bottom
a(href="/u/" + data.username + "")
h3.username user: #{data.username}
ul.tabmenu
li(class=!data.post_type || data.post_type == '' ? 'active' : '')
a(href="/u/" + data.username) overview
li(class=data.post_type === '/comments' ? 'active' : '')
a(href="/u/" + data.username + "/comments") comments
li(class=data.post_type === '/submitted' ? 'active' : '')
a(href="/u/" + data.username + "/submitted") submitted
#links #links
details details
summary summary
@ -23,13 +34,13 @@ html
span sorted by: controversial span sorted by: controversial
ul ul
li(class=!sortby || sortby == 'new' ? 'active' : '') li(class=!sortby || sortby == 'new' ? 'active' : '')
a(href="/u/" + data.username) new a(href="/u/" + data.username + data.post_type) new
li(class=sortby === 'hot' ? 'active' : '') li(class=sortby === 'hot' ? 'active' : '')
a(href="/u/" + data.username + "?sort=hot") hot a(href="/u/" + data.username + data.post_type + "?sort=hot") hot
li(class=sortby === 'top' ? 'active' : '') li(class=sortby === 'top' ? 'active' : '')
a(href="/u/" + data.username + "?sort=top&t=" + past + "") top a(href="/u/" + data.username + data.post_type + "?sort=top&t=" + past + "") top
li(class=sortby === 'controversial' ? 'active' : '') li(class=sortby === 'controversial' ? 'active' : '')
a(href="/u/" + data.username + "?sort=controversial&t=" + past + "") controversial a(href="/u/" + data.username + data.post_type + "?sort=controversial&t=" + past + "") controversial
if sortby === 'top' || sortby === 'controversial' if sortby === 'top' || sortby === 'controversial'
details details
summary summary
@ -132,7 +143,7 @@ html
if data.before || data.after if data.before || data.after
p view more: p view more:
if data.before && !data.user_front if data.before && !data.user_front
a(href="/u/" + data.username + "?before=" + data.before + "") prev a(href="/u/" + data.username + data.post_type + "?before=" + data.before + "") prev
if data.after if data.after
a(href="/u/" + data.username + "?after=" + data.after + "") next a(href="/u/" + data.username + data.post_type + "?after=" + data.after + "") next
include includes/footer.pug include includes/footer.pug