ejs stuff

This commit is contained in:
2025-07-22 00:17:00 +01:00
parent 7eeafddae4
commit cc131798a3
23 changed files with 311 additions and 89 deletions

131
app.js
View File

@@ -6,8 +6,10 @@ const crypto = require('crypto'); // For encrypting passwords, I use sha512
// fromUnixTime(): Create a date from a Unix timestamp (in seconds). Decimal values will be discarded.
// format(): Return the formatted date string in the given format. The result may vary by locale.
// getUnixTime(): Get the seconds timestamp of the given date.
// find out more at https://date-fns.org/ \or docs: https://date-fns.org/docs/Getting-Startedyyyyyyyy
// find out more at https://date-fns.org/ \or docs: https://date-fns.org/docs/Getting-Started
const { fromUnixTime, format, getUnixTime } = require("date-fns") // A date utility library
const ejs = require("ejs")
const func = require("./functions.js")
// There's only one possible argument, so we can just check if the user passed that one
// TODO I plan on adding more such as --help and --post so I should make this more robust at some point
@@ -20,6 +22,7 @@ let users // contains a list of users, each user is an object containing usernam
let posts // contains a list of posts,
let comments // contains a list of comments
let config // contains a set of configuration for the site, see example-config.js for an example
let ejs_templates
try {
// We're going to try and import the modules,
@@ -27,6 +30,7 @@ try {
posts = require('./posts.json');
comments = require('./comments.json');
config = require('./config.json');
ejs_templates = require("./ejs-templates.js")
}
catch (error) {
// if they don't all import then
@@ -56,6 +60,9 @@ const app = express();
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(express.static(config.root_path));
// set the view engine to ejs
app.set('view engine', 'ejs');
// Initialise the program by creating users.js, comments.js, posts.js and config.js
// All require default content in them to start off with
// Then exit successfully
@@ -110,16 +117,6 @@ function get_userID(username) {
return -1 // If user is not present, return -1
}
// The configuration defines a date format using the date-fns (a datetime library) syntax
// eg "yyyy-MM-dd"
// this converts unix time (an integer) into a string that is formatted according to config.js
// uses date-fns's fromUnixTime() and format() functions
// returns the formatted date (string)
function unix_time_to_date_format(unix_time) {
date = fromUnixTime(unix_time)
formatted_date = format(date, config.date_format)
return formatted_date
}
// This is similar to the above function, however, instead of formatting to the users
// configuration, it formats to RFC-822 which is the date format used by RSS feeds
@@ -173,8 +170,8 @@ function replace_format_indicators(template, post_index=-1, tag_name="tag", user
.replaceAll("%A", (post_object["tags"]))
.replaceAll("%B", (hyperlink_tags(post_object["tags"])))
.replaceAll("%C", converter.makeHtml(post_object["content"]))
.replaceAll("%D", unix_time_to_date_format(post_object["pubdate"]))
.replaceAll("%E", unix_time_to_date_format(post_object["editdate"]))
//.replaceAll("%D", unix_time_to_date_format(post_object["pubdate"]))
//.replaceAll("%E", unix_time_to_date_format(post_object["editdate"]))
.replaceAll("%F", users[post_object["userID"]]['prettyname'])
.replaceAll("%G", tag_name)
.replaceAll("%I", converter.makeHtml(users[post_object['userID']]['description']))
@@ -235,13 +232,13 @@ function return_comments(post_id) {
.replaceAll(/>> ([0-9]*)/g, "<a href='#$1'>>> $1</a>")
.replaceAll(/&gt;&gt; ([0-9]*)/g, "<a href='#$1'>>> $1</a>")
.replaceAll("\n", "<br/>")
comment_content += `<div id="${comment['id']}">${comment['name']} ${unix_time_to_date_format(comment['pubdate'])} No. ${comment['id']}<br/>${comment['content']}</div><br/>`
//comment_content += `<div id="${comment['id']}">${comment['name']} ${unix_time_to_date_format(comment['pubdate'])} No. ${comment['id']}<br/>${comment['content']}</div><br/>`
}
return comment_content
}
// RSS protocol gets
app.get(config.rss_path, (req,res) => {
app.get(config.rss_url, (req,res) => {
if (config.rss == false) {
res.send("Sorry, RSS is disabled!")
}
@@ -275,6 +272,7 @@ app.get(config.rss_path, (req,res) => {
});
app.get("/", (req,res) => {
// Increment the hitcount
if (config.enable_hitcount) {
let hitcount = parseInt(fs.readFileSync('hitcount.txt'))
hitcount += 1
@@ -282,51 +280,68 @@ app.get("/", (req,res) => {
fs.writeFileSync(`${__dirname}/hitcount.txt`, `${hitcount}`, 'utf-8');
}
header_div = config.timeline_header
header_div = replace_format_indicators(header_div);
posts_div = "";
counter = posts.length - 1;
while ((counter >= 0) && (counter > (posts.length - (config.timeline_length + 1))))
{
let post = config.timeline_post_format;
posts_div += replace_format_indicators(post, counter);
counter -= 1;
}
res.send(`<html><head><meta charset="${config.charset}"><style>${config.css}</style></head><body><div id="header">${header_div}</div><div id="posts">${posts_div}</div></body><footer>${footer_div}</footer></html>`);
res.render("pages/timeline",
{
config: config,
posts: posts,
users: users,
comments: comments.comments,
hitcount: fs.readFileSync("hitcount.txt"),
fromUnixTime: fromUnixTime,
format: format,
getUnixTime: getUnixTime,
hyperlink_tags: hyperlink_tags,
})
}); // /
app.get("/user/:username", (req, res) => {
header_div = config.user_page_header
header_div = replace_format_indicators(header_div,-1,"tag",get_userID(req.params.username))
posts_div = "";
for (let post_index = posts.length-1; post_index >= 0; post_index--) {
if (users[posts[post_index]["userID"]]["username"] == req.params.username) {
let post = config.user_post_format;
posts_div += replace_format_indicators(post, post_index);
}
}
res.send(`<html><head><meta charset="${config.charset}"><style>${config.css}</style></head><body><div id="header">${header_div}</div><div id="posts">${posts_div}</div></body><footer>${footer_div}</footer></html>`);
const userID = get_userID(req.params.username)
console.log(userID)
console.log(users[userID].prettyname)
res.render("pages/user",
{
config: config,
posts: posts,
user: users[userID],
userID: userID,
comments: comments.comments,
fromUnixTime: fromUnixTime,
format: format,
getUnixTime: getUnixTime,
hyperlink_tags: hyperlink_tags,
})
}); // /user/:username
app.get("/post/:post_index", (req, res) => {
post_div = "";
let post = config.post_page_format;
post_div += replace_format_indicators(post, req.params.post_index);
res.send(`<html><head><meta charset="${config.charset}"><style>${config.css}</style></head><body><div id="posts">${post_div}</div></body><footer>${footer_div}</footer></html>`);
const postID = req.params.post_index
res.render("pages/post",
{
config,
post: posts[postID],
postID: postID,
user: users[posts[postID].userID],
comments: comments.comments[postID],
fromUnixTime,
format,
getUnixTime,
hyperlink_tags,
})
}); // /post/:post_index
app.get("/tag/:tag", (req,res) => {
const tag = req.params.tag
let header_div = config.tag_page_header
header_div = replace_format_indicators(header_div,0,tag)
let page_content = ""
for (let i = posts.length-1; i >= 0; i--) {
if (posts[i]['tags'].includes(tag)) {
let post = config.tag_post_format;
page_content += replace_format_indicators(post, i);
};
};
res.send(`<html><style>${config.css}</style><body><div id="header">${header_div}</div><div id="posts">${page_content}</div></body><footer>${footer_div}</footer></html>`);
const tag = req.params.tag
res.render("pages/tag",
{
config: config,
tag: tag,
posts: posts,
users: users,
comments: comments.comments,
fromUnixTime: fromUnixTime,
format: format,
getUnixTime: getUnixTime,
hyperlink_tags: hyperlink_tags,
})
}); // /tag/:tag
app.get("/post", (req,res) => {
app.get(config.new_post_url, (req,res) => {
res.send(`</html><head><meta charset="${config.charset}"><style>${config.css}</style></head><form action="/submit_post" method="POST">
<input placeholder="username" required name="username"><br/>
<input placeholder="password" type="password" required id="password" name="password"><br/>
@@ -337,7 +352,7 @@ app.get("/post", (req,res) => {
<small>* Markdown supported</small>
</form></html>`);
}); // /post
app.get("/signup", (req,res) => {
app.get(config.signup_url, (req,res) => {
// if the server does allow signup
if (config.allow_signup == true) {
// Send the page for signing up to the server
@@ -359,14 +374,14 @@ app.get("/signup", (req,res) => {
console.log("Error, invalid value for allow_signup (bool)")
}
}); // /signup
app.get("/delete_account", (req,res) => {
app.get(config.delete_account_url, (req,res) => {
res.send(`</html><head><meta charset="${config.charset}"><style>${config.css}</style></head><form action="/submit_delete_account" method="POST">
<input placeholder="username" required name="username"><br/>
<input placeholder="password" type="password" required id="password" name="password"><br/>
<label>${config.delete_account_confirmation}: </label><input type="checkbox" name="agreement" required><br/>
<input type="submit" value="Submit"><br/></form></html>`);
}); // /delete_account
app.get("/edit/:post_id", (req,res) => {
app.get(`${config.edit_post_base_url}/:post_id`, (req,res) => {
const post_id = req.params.post_id
const post = posts[post_id]
const user = users[post['userID']]
@@ -409,13 +424,13 @@ app.post("/submit_post", (req,res) => {
const content = escape_input(req.body.content)
const tags = escape_input(req.body.tags).split(',');
const unix_timestamp = getUnixTime(new Date())
console.log(username, "is submitting a post titled:", title);
if (get_userID(username) == -1) {
res.send("User does not exist")
res.send(`</html><head><meta charset="${config.charset}"><style>${config.css}</style></head><body>${config.user_doesnt_exit}</body></html>`)
}
else if (users[get_userID(username)]['hash'] == password) { // Password matches
console.log(username, "is submitting a post titled:", title);
posts.push({
"userID": get_userID(username),
"title": title,
@@ -430,7 +445,7 @@ app.post("/submit_post", (req,res) => {
res.redirect(302, "/");
}
else {
res.send(`Invalid Password for user`,username);
res.send(`</html><head><meta charset="${config.charset}"><style>${config.css}</style></head><body>${config.incorrect_password}</body></html>`)
}
}); // /submit_post
app.post("/submit_signup", (req,res) => {