Compare commits

...

93 commits
master ... dev

Author SHA1 Message Date
Hollgy
27b2be3213 Boilerplate UI for removal of post, Portal implementation 2024-03-25 14:15:37 +01:00
Hollgy
3b52b1b7e8 Font change 2024-03-25 14:15:05 +01:00
Hollgy
dd1a419244 Layout change of post 2024-03-25 14:11:38 +01:00
Hollgy
9954588913 Fixed bug where invalid date renders in comments as loop, did not piss off lintbro 2024-03-25 10:58:25 +01:00
Imbus
2e600cc6d2 Set cache control to no-cache for all api endpoints, logging access keys instead of captcha keys 2024-03-25 01:54:25 +01:00
Imbus
a2292ffc68 Merge branch 'dev' of git.silversoft.se:Imbus/FrostByte into dev 2024-03-24 23:45:27 +01:00
Imbus
81303d31cd Beefing up security and cleaning up state 2024-03-24 23:45:22 +01:00
Hollgy
c3ded8a27b Removed old toPost btn 2024-03-24 23:01:51 +01:00
Imbus
630f19f82c Merge branch 'dev' of git.silversoft.se:Imbus/FrostByte into dev 2024-03-24 23:00:26 +01:00
Imbus
5ed65b3aeb Bumping versions in frontend 2024-03-24 23:00:22 +01:00
Hollgy
ac71cbd9e2 Bugfix of setEdited, bordercolor swap 2024-03-24 22:59:49 +01:00
Hollgy
78ede1785a Change of color palette 2024-03-24 22:59:14 +01:00
Hollgy
e3162a6973 Making linterbro happy 2024-03-24 22:39:25 +01:00
Hollgy
a51d397ded Refactor, added navigation to comment button 2024-03-24 22:31:28 +01:00
Imbus
b324e0f16d Fixing reactivity 2024-03-24 21:59:21 +01:00
Hollgy
6be8925970 Refactor of comments and posts 2024-03-24 21:40:57 +01:00
Imbus
2fe0090422 Merge branch 'dev' of git.silversoft.se:Imbus/FrostByte into dev 2024-03-23 00:40:09 +01:00
Hollgy
e04d588b56 Added active render of amount of comments on post 2024-03-23 00:40:02 +01:00
Imbus
3abedb256c Making linter bro happy 2024-03-23 00:38:33 +01:00
Imbus
85c2161a4d Comment count API endpoint 2024-03-23 00:23:29 +01:00
Hollgy
5eeed1e8bc Removal of posts added 2024-03-23 00:10:42 +01:00
Imbus
a1e362acee Specifying no-cache policy on all API endpoints 2024-03-22 23:59:07 +01:00
Imbus
3610a7413a Returning Promise<Response> from deletePost 2024-03-22 23:55:50 +01:00
Imbus
038b83e530 Cascading 2024-03-22 23:38:08 +01:00
Imbus
d2eac68638 Delete post fix, proper cascading on comments 2024-03-22 23:20:47 +01:00
Hollgy
61ab9e072e Replies to comments removed, out of current scope 2024-03-22 22:58:41 +01:00
Imbus
6909dbd146 TS API for deletePost 2024-03-22 22:57:05 +01:00
Imbus
70ba521aa5 Delete post route 2024-03-22 22:44:57 +01:00
Hollgy
ea25fa9489 Handlers for GET and POST engages added, renders numbers of unique engagements per post 2024-03-22 22:38:18 +01:00
Imbus
efcdaf0cd2 Get engagements path 2024-03-22 22:03:26 +01:00
Imbus
e946dc456d Ugly fix for removing bearer prefix from auth header 2024-03-22 21:48:11 +01:00
Imbus
c5a25ad714 Fix: mounting engage_post path correctly 2024-03-22 21:39:46 +01:00
Imbus
d93dc7fd89 Engage endpoint 2024-03-22 21:28:20 +01:00
Hollgy
6fcbb92691 Removal of props for build to run 2024-03-22 20:41:15 +01:00
Hollgy
146518b94a Refactoring of most components regarding props and, Lint corrections 2024-03-22 20:39:34 +01:00
Imbus
2e23c7919f Removed the concept of down & upvotes 2024-03-22 19:47:36 +01:00
Hollgy
84defa703e Removal of replies, Styling and interface update of comments and commentsection 2024-03-22 13:30:32 +01:00
Hollgy
39801dfbda Border color change 2024-03-22 13:28:52 +01:00
Hollgy
29f1ed952a Removed home icon button 2024-03-22 13:27:40 +01:00
Hollgy
b5b256f6e9 Refactor of replies,Icon Swap 2024-03-22 13:27:11 +01:00
Hollgy
999d180b24 Added dropdown for report and removal of post, added removal of post frontend 2024-03-22 11:45:52 +01:00
Hollgy
458cf196e9 Minor style changes 2024-03-20 14:59:14 +01:00
Hollgy
7b87c92139 Minor text change 2024-03-20 14:32:32 +01:00
Hollgy
0907e2b7bd Refactor of PostSegment, Buttons made into separate comps, Changed color variation of site, Added Reporticon without logic for logged in users 2024-03-19 15:23:12 +01:00
Hollgy
b7d00d4e75 Boilerplate logic for votes added in frontend, Header added for post creation 2024-03-18 18:34:11 +01:00
Hollgy
6093751799 Merge branch 'dev' of git.silversoft.se:Imbus/FrostByte into dev 2024-03-18 17:27:16 +01:00
Hollgy
a0025921b1 restyling button 2024-03-18 17:27:09 +01:00
Hollgy
88e3f03ee4 Stylechange buttons 2024-03-18 16:07:55 +01:00
Hollgy
581d6454c0 Redesign of comments, now differs more from post, space made for additions regarding replies 2024-03-18 15:59:32 +01:00
Hollgy
b1f6c21b6f logout prompt added 2024-03-18 15:42:07 +01:00
Imbus
ac527a4b71 Splitting PostSegment into its own file, minor refactoring 2024-03-12 19:51:41 +01:00
Imbus
46678dfdeb Merge branch 'dev' of git.silversoft.se:Imbus/FrostByte into dev 2024-03-12 19:40:01 +01:00
Imbus
a298f63326 Comment declutter 2024-03-12 19:39:48 +01:00
Hollgy
cedb469105 Refactor of dateOfCreation, Addition of edited check in frontend, Endpoint added for engagement on posts 2024-03-12 18:57:14 +01:00
Hollgy
f9ef90e61f Co-authored-by: Imbus <imbus64@users.noreply.github.com> 2024-03-12 18:34:00 +01:00
Hollgy
67563c5c25 Refactor of posts 2024-03-12 18:33:08 +01:00
Imbus
addbb820a3 Less goofy margins/padding for PostSegment 2024-03-12 17:59:58 +01:00
Imbus
bbae426c09 Passing in root prop for post comments 2024-03-12 17:59:28 +01:00
Imbus
2b12a83aa8 Merge branch 'dev' of git.silversoft.se:Imbus/FrostByte into dev 2024-03-12 17:27:04 +01:00
Imbus
82e3f18961 Serde renames for javascript appropriate camel case 2024-03-12 17:26:58 +01:00
Hollgy
3174f99a51 Added props && Interfaces for parentCommentId, Boilerplate idea for comment separation 2024-03-11 22:07:39 +01:00
Hollgy
3a42624042 Formatting 2024-03-11 22:05:49 +01:00
Hollgy
368d7c9c65 added type for parent-commen-id into comment 2024-03-11 15:16:55 +01:00
Hollgy
45c3b87243 style adjustments, moving to darker theme 2024-03-08 14:52:20 +01:00
Hollgy
79208cb9c2 conditional rendering of new comment added, typo corrected 2024-03-08 10:04:35 +01:00
Imbus
39df975b04 Split npm dependency fetching and building into two stages in Containerfile 2024-03-08 06:34:53 +01:00
Imbus
a83cce236f Formatting 2024-03-08 06:28:57 +01:00
Imbus
aee8a44404 CLS fix significantly better on footer with sticky 2024-03-08 06:28:46 +01:00
Imbus
6e6b9aa73c Some more aria-labels in footer 2024-03-08 06:10:10 +01:00
Imbus
238b0442e4 Sample hrefs for footer links 2024-03-08 06:06:29 +01:00
Imbus
cceba2cc42 Aria label for view post 2024-03-08 06:06:15 +01:00
Imbus
2362231767 Revert all changes related to layout fix 2024-03-08 06:02:18 +01:00
Imbus
d233fa4fd5 Attempting to mitigate CLS again 2024-03-08 05:50:59 +01:00
Imbus
21e8cab0ed CLS mitigation in Footer component 2024-03-08 05:39:41 +01:00
Imbus
8eca21336d Simple makefile for rebuilding with docker-compose 2024-03-08 05:32:48 +01:00
Imbus
6f69abe973 Allow dead code for hex_string, since its not used for now 2024-03-08 05:26:22 +01:00
Imbus
211490bd6f Simple robots.txt for SEO 2024-03-08 05:23:45 +01:00
Imbus
68fca7cbde Wrap server in header middleware with a sane CacheControl policy to satisfy lighthouse 2024-03-08 05:08:00 +01:00
Imbus
71bbd3bfbd Removed unused import 2024-03-07 09:03:44 +01:00
Imbus
40099c9b62 Allowed non-signed-in users to view comments 2024-03-07 08:57:05 +01:00
Imbus
b0113aa985 Fixing ovious error in composefile 2024-03-07 08:27:46 +01:00
Imbus
a2064b440d Justfile targets for db-backup, db-restore, pgshell and re-migrate for debugging 2024-03-06 08:22:58 +01:00
Imbus
a5dadfc1d1 Initial comment draft with working server communication 2024-03-06 08:10:42 +01:00
Imbus
3a389d854b Updated sqlx cache 2024-03-06 08:08:41 +01:00
Imbus
8875ae4a4c Added a migration script containing useful functions/procedures 2024-03-06 08:06:32 +01:00
Imbus
5a75e6f9a0 Gitignore now ignores everything containing backup 2024-03-06 08:05:54 +01:00
Imbus
d0e5b57006 Working comment route fully implemented 2024-03-06 08:05:23 +01:00
Imbus
32ff43e87c Removing everything to do with parent_comment_id in comment table for now 2024-03-06 08:04:26 +01:00
Imbus
3d40ec513e Adding a bunch of dummy comments on each post 2024-03-06 08:03:03 +01:00
Imbus
d12bd9aa99 Silencing logs a bit 2024-03-06 07:55:31 +01:00
Imbus
9e302fc54a Example jsdoc 2024-03-06 02:06:13 +01:00
Imbus
d2fd1a17ed Remove unused deps in CommentSection, build now works 2024-03-06 01:35:48 +01:00
Hollgy
edb7ef2fc4 Initial draft of comments 2024-03-06 00:48:19 +01:00
54 changed files with 3171 additions and 1820 deletions

2
.gitignore vendored
View file

@ -25,3 +25,5 @@ dist-ssr
*.env *.env
*.db* *.db*
*backup*

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,3 @@
User-agent: *
Disallow: /settings/
Disallow: /public/

View file

@ -0,0 +1,42 @@
import { useNavigate } from "@solidjs/router";
import { JSXElement, createEffect, createSignal, onMount } from "solid-js";
import { CommentsIcon } from "../../Util/Icons";
import { getCommentCount } from "../../Util/api";
export default function CommentsButton(props: { postId: string }): JSXElement {
const [commentCount, setCommentCount] = createSignal(0);
const [postId, setPostId] = createSignal<string>("");
const nav = useNavigate();
createEffect(() => {
setPostId(props.postId);
});
const handleComments = async (): Promise<void> => {
try {
const count = await getCommentCount(props.postId);
setCommentCount(count);
} catch (error) {
console.error("Error reading comments:", error);
}
};
// Fetch comment count when the component mounts
onMount(handleComments);
return (
<div class="flex p-1">
<button
onClick={(): void => nav("/post/" + postId())}
class="rounded-base btn btn-xs hover:border-primary"
>
<CommentsIcon />
</button>
<span class="text-1xl countdown px-1.5 pt-1.5 text-center">
<p style={{ "--value": commentCount() }} />
</span>
</div>
);
}

View file

@ -0,0 +1,51 @@
import { JSXElement, createSignal, onMount, useContext } from "solid-js";
import { LoginContext } from "../../Context/GlobalState";
import { EngagementIcon } from "../../Util/Icons";
import { engage, getEngagementCount } from "../../Util/api";
export default function EngagementButton(props: {
postId: string;
}): JSXElement {
const [engagementCount, setEngagementCount] = createSignal(0);
const login_ctx = useContext(LoginContext)!;
onMount((): void => {
void setUp();
});
const setUp = async (): Promise<void> => {
const r = await getEngagementCount(props.postId);
setEngagementCount(r);
};
// Function to handle engagement
const handleEngagement = async (): Promise<void> => {
try {
const response = await engage(props.postId, login_ctx.token());
if (response.ok) {
// Update engagement count if the request is successful
setEngagementCount(await response.json());
} else {
console.error("Failed to engage:", response.statusText);
}
} catch (error) {
console.error("Error engaging:", error);
}
};
return (
<div class="flex p-1">
<button
class="rounded-base btn btn-xs hover:border-primary"
aria-label="Show sign of engagement"
onClick={handleEngagement} // Call handleEngagement function on button click
>
<EngagementIcon />
</button>
<span class="text-1xl countdown px-1.5 pt-1.5 text-center">
<p style={{ "--value": engagementCount() }} />
</span>
</div>
);
}

View file

@ -0,0 +1,65 @@
import { useNavigate } from "@solidjs/router";
import { JSXElement, createEffect, createSignal, useContext } from "solid-js";
import { Portal } from "solid-js/web";
import { LoginContext } from "../../Context/GlobalState";
import { RemovePostIcon } from "../../Util/Icons";
import { deletePost } from "../../Util/api";
export default function RemovePostButton(props: {
postId: string;
}): JSXElement {
const navigate = useNavigate();
const login_ctx = useContext(LoginContext)!;
// State to track whether the post has been deleted
const [isDeleted, setIsDeleted] = createSignal(false);
// Function to handle post deletion
const handleDeletePost = async (): Promise<void> => {
try {
const response = await deletePost(props.postId, login_ctx.token());
if (response.ok) {
// If deletion is successful, set isDeleted to true
setIsDeleted(true);
console.log("Post deleted successfully");
// Optional: You can also navigate to "/" after successful deletion
navigate("/");
} else {
console.error("Failed to delete post:", response.statusText);
// You may want to show an error message or handle the failure in some other way
}
} catch (error) {
console.error("Error deleting post:", error);
// Handle any unexpected errors that occur during the deletion process
}
};
// Effect to display modal when post is deleted
createEffect(() => {
if (isDeleted()) {
// Display modal here
<Portal mount={document.body}>
<div class="w-100 h-100 -z-20">
<div class="fixed inset-0 z-20 w-1/4 items-center justify-center">
<div role="alert" class="alert alert-success">
<p>Post was successfully removed</p>
</div>
</div>
</div>
</Portal>;
}
});
return (
<div class="flex p-1">
<button
class="rounded-base btn btn-xs hover:border-primary"
aria-label="Remove post"
onClick={handleDeletePost}
>
<RemovePostIcon />
</button>
</div>
);
}

View file

@ -0,0 +1,20 @@
import { JSXElement, Show, useContext } from "solid-js";
import { LoginContext } from "../../Context/GlobalState";
import { ReplyIcon } from "../../Util/Icons";
export default function ReplyButton(): JSXElement {
const login_ctx = useContext(LoginContext)!;
return (
<Show when={login_ctx.loggedIn()}>
<div class="flex p-1">
<button
class="rounded-base btn btn-xs hover:border-primary"
aria-label="Report post or comment"
>
<ReplyIcon />
</button>
</div>
</Show>
);
}

View file

@ -0,0 +1,20 @@
import { JSXElement, Show, useContext } from "solid-js";
import { LoginContext } from "../../Context/GlobalState";
import { ReportIcon } from "../../Util/Icons";
export default function ReportButton(): JSXElement {
const login_ctx = useContext(LoginContext)!;
return (
<Show when={login_ctx.loggedIn()}>
<div class="flex p-1">
<button
class="rounded-base btn btn-xs hover:border-primary"
aria-label="Report post or comment"
>
<ReportIcon />
</button>
</div>
</Show>
);
}

View file

@ -0,0 +1,21 @@
import { useNavigate } from "@solidjs/router";
import { JSXElement } from "solid-js";
import { Arrow } from "../../Util/Icons";
import { Post } from "../../Util/api";
export default function ToPostButton(props: { post: Post }): JSXElement {
const nav = useNavigate();
return (
<div class="p-1">
<button
onClick={(): void => nav("/post/" + props.post.id)} // Accessing props.post directly
class="btn btn-xs hover:border-primary"
aria-label="View post"
>
<Arrow />
</button>
</div>
);
}

View file

@ -0,0 +1,31 @@
import { JSXElement, createEffect, createSignal } from "solid-js";
import { PublicComment } from "../Util/api";
export function Comment(props: { comment: PublicComment }): JSXElement {
const [creationDate, setCreationDate] = createSignal<string>("");
const [content, setContent] = createSignal<string>("");
createEffect(() => {
const date = new Date(props.comment.created_at);
if (!isNaN(date.getTime())) {
setCreationDate(date.toDateString());
} else {
// Set creation date to an empty string or any default value when the date is invalid
setCreationDate("");
}
setContent(props.comment.content);
});
return (
<>
{creationDate() && ( // Render creation date only if it's not an empty string
<div class="py-5">
<time class="text-xs opacity-50">{creationDate()}</time>
</div>
)}
<div class="text-base">{content()}</div>
<div class="divider" />
</>
);
}

View file

@ -0,0 +1,18 @@
import { For, JSXElement, createResource, splitProps } from "solid-js";
import { getComments } from "../Util/api";
import { Comment } from "./Comment";
export function CommentSection(postId: { postId: string }): JSXElement {
const [local] = splitProps(postId, ["postId"]);
// Not sure why this is a resource, refetch is not implemented
const [state] = createResource(() => getComments(local.postId, 10, 0));
return (
<div>
<For each={state()} fallback={<div>Loading...</div>}>
{(comment) => <Comment comment={comment} />}
</For>
</div>
);
}

View file

@ -1,23 +1,54 @@
import { JSXElement, Show, useContext } from "solid-js"; import { JSXElement, Show, createSignal, useContext } from "solid-js";
import { LoginContext, ModalContext } from "../Context/GlobalState"; import { LoginContext, ModalContext } from "../Context/GlobalState";
import { UserCircle } from "../Util/Icons";
export function LoginButton(): JSXElement { export function LoginButton(): JSXElement {
const modal_ctx = useContext(ModalContext)!; const modal_ctx = useContext(ModalContext)!;
const login_ctx = useContext(LoginContext)!; const login_ctx = useContext(LoginContext)!;
const [showLogoutModal, setShowLogoutModal] = createSignal(false);
const clickHandler = (): void => { const clickHandler = (): void => {
if (login_ctx.loggedIn()) login_ctx.logOut(); if (login_ctx.loggedIn()) {
else modal_ctx.setOpen(true); setShowLogoutModal(true);
} else {
modal_ctx.setOpen(true);
}
};
const confirmLogout = (): void => {
login_ctx.logOut();
setShowLogoutModal(false);
};
const cancelLogout = (): void => {
setShowLogoutModal(false);
}; };
return ( return (
<>
<div class="btn btn-ghost text-sm capitalize" onClick={clickHandler}> <div class="btn btn-ghost text-sm capitalize" onClick={clickHandler}>
<Show when={login_ctx.loggedIn()} fallback="Login"> <Show when={login_ctx.loggedIn()} fallback="Login">
{login_ctx.username()} {login_ctx.username()}
</Show> </Show>
<UserCircle />
</div> </div>
{showLogoutModal() && (
<div
role="alert"
class="absolute top-10 z-10 flex rounded-md border-2 border-info bg-base-200"
>
<div class="relative p-5">
<p>Do you wish to logout?</p>
<div class="w-100' flex justify-around">
<button class="btn btn-primary btn-sm" onClick={confirmLogout}>
Yes
</button>
<button class="btn btn-primary btn-sm" onClick={cancelLogout}>
No
</button>
</div>
</div>
</div>
)}
</>
); );
} }

View file

@ -2,7 +2,7 @@ import { A } from "@solidjs/router";
import { JSXElement, Show, useContext } from "solid-js"; import { JSXElement, Show, useContext } from "solid-js";
import { LoginContext } from "../Context/GlobalState"; import { LoginContext } from "../Context/GlobalState";
import { Home, Plus } from "../Util/Icons"; import { Plus } from "../Util/Icons";
// Represents a single list item in the menu bar // Represents a single list item in the menu bar
export function MenuItem(props: { export function MenuItem(props: {
@ -23,10 +23,7 @@ export function Menu(): JSXElement {
const login_ctx = useContext(LoginContext)!; const login_ctx = useContext(LoginContext)!;
return ( return (
<Show when={login_ctx.loggedIn()}> <Show when={login_ctx.loggedIn()}>
<ul class="menu space-y-2 rounded-box md:menu-horizontal md:space-x-2 md:space-y-0"> <ul class="menu menu-horizontal space-x-2 space-y-0 rounded-box md:space-x-5 md:space-y-0">
<MenuItem href="/">
<Home />
</MenuItem>
<MenuItem href="/new"> <MenuItem href="/new">
<Plus /> <Plus />
</MenuItem> </MenuItem>

View file

@ -0,0 +1,71 @@
import { useNavigate } from "@solidjs/router";
import { JSXElement, Show, createSignal, useContext } from "solid-js";
import { LoginContext } from "../Context/GlobalState";
import { NewComment, createComment } from "../Util/api";
/** NewCommentInputArea is a component that allows users to submit a comment on a **post or comment**.
* @param {Object} props The properties for the NewCommentInputArea component.
* @param {number} props.parentPostId The id of the post that the comment is a reply to.
* @returns {JSXElement} A JSXElement that contains a textarea and a submit button.
*/
interface NewCommentInputAreaProps {
parentPostId: number;
parentCommentId: number | null;
}
export function NewCommentInputArea(
props: NewCommentInputAreaProps
): JSXElement {
const [content, setContent] = createSignal("");
const [waiting, setWaiting] = createSignal(false);
const login_ctx = useContext(LoginContext)!;
const nav = useNavigate();
const sendComment = (): void => {
setWaiting(true);
const response = createComment({
content: content(),
user_token: login_ctx.token(),
parent_post_id: props.parentPostId,
parent_comment_id: props.parentCommentId,
} as NewComment);
if (response) {
response.then(() => {
setWaiting(false);
setContent("");
nav("/post/" + props.parentPostId);
});
}
};
return (
<Show
when={!waiting()}
fallback={<span class="loading loading-spinner loading-lg self-center" />}
>
<div class="flex w-full flex-col space-y-2">
<textarea
class="textarea textarea-bordered h-32"
placeholder="Reply to post..."
maxLength={500}
onInput={(input): void => {
setContent(input.target.value);
}}
/>
<button
class={
"btn btn-primary btn-sm self-end" +
(content() == "" ? " btn-disabled" : "")
}
onClick={sendComment}
>
Submit
</button>
</div>
</Show>
);
}

View file

@ -8,7 +8,7 @@ export function NewPostInputArea(): JSXElement {
const [content, setContent] = createSignal(""); const [content, setContent] = createSignal("");
const [waiting, setWaiting] = createSignal(false); const [waiting, setWaiting] = createSignal(false);
// We assumte this context is always available // We assume this context is always available
const login_ctx = useContext(LoginContext)!; const login_ctx = useContext(LoginContext)!;
const nav = useNavigate(); const nav = useNavigate();
@ -40,6 +40,7 @@ export function NewPostInputArea(): JSXElement {
when={!waiting()} when={!waiting()}
fallback={<span class="loading loading-spinner loading-lg self-center" />} fallback={<span class="loading loading-spinner loading-lg self-center" />}
> >
<span>Create a new post</span>
<div class="flex w-full flex-col space-y-2"> <div class="flex w-full flex-col space-y-2">
<textarea <textarea
class="textarea textarea-bordered h-32" class="textarea textarea-bordered h-32"

View file

@ -0,0 +1,57 @@
import {
JSXElement,
Show,
createEffect,
createSignal,
splitProps,
} from "solid-js";
import { Post } from "../Util/api";
import CommentsButton from "./Buttons/CommentsButton";
import EngagementButton from "./Buttons/Engegament";
import RemovePostButton from "./Buttons/RemovePostButton";
import ReportButton from "./Buttons/Report";
export function PostSegment(props: { post: Post }): JSXElement {
const [local] = splitProps(props, ["post"]);
const [updatedAt, setUpdatedAt] = createSignal<string>("");
const [createdAt, setCreatedAT] = createSignal<string>("");
const [edited, setEdited] = createSignal<boolean>(false);
createEffect((): void => {
setUpdatedAt(new Date(local.post.createdAt).toDateString());
setCreatedAT(new Date(local.post.updatedAt).toDateString());
setEdited(!(updatedAt() === createdAt()));
});
return (
<div class="card compact w-full flex-grow border-b-2 border-b-info bg-base-200 text-base-content transition-all hover:bg-base-300">
<div class="card-body md:mx-6">
<div class="flex flex-row justify-between">
<p class="text-xs">{createdAt()}</p>
</div>
<Show when={edited()}>
<p>This post has been edited</p>
</Show>
<p class="my-1 text-base">{local.post.content}</p>
<div class="card-actions justify-between">
<div class="flex">
<EngagementButton postId={local.post.id} />
<CommentsButton postId={local.post.id} />
</div>
<details class="dropdown">
<summary class="btn btn-sm">...</summary>
<ul class="w-26 menu dropdown-content z-[1] rounded-box bg-base-100 p-2 shadow">
<li>
<ReportButton />
</li>
<li>
<RemovePostButton postId={local.post.id} />
</li>
</ul>
</details>
</div>
</div>
</div>
);
}

View file

@ -1,9 +1,13 @@
import { useNavigate } from "@solidjs/router";
import { For, JSXElement, Show, createSignal } from "solid-js"; import { For, JSXElement, Show, createSignal } from "solid-js";
import { Arrow, loadSpinner } from "../Util/Icons"; import { loadSpinner } from "../Util/Icons";
import { Post, getPosts } from "../Util/api"; import { Post, getPosts } from "../Util/api";
import { PostSegment } from "./PostSegment";
/**
* Posts is a component that displays a collection of posts.
* @returns {JSXElement} A JSXElement that contains a collection of posts.
*/
export function Posts(): JSXElement { export function Posts(): JSXElement {
const [posts, setPosts] = createSignal([] as Post[]); const [posts, setPosts] = createSignal([] as Post[]);
const [loading, setLoading] = createSignal(true); const [loading, setLoading] = createSignal(true);
@ -21,23 +25,3 @@ export function Posts(): JSXElement {
</Show> </Show>
); );
} }
// This is the card container for a post
export function PostSegment(props: { post: Post }): JSXElement {
const nav = useNavigate();
return (
<div class="card compact w-full flex-grow border-b-2 border-b-base-300 bg-base-200 text-base-content transition-all hover:bg-base-300">
<div class="card-body">
<p class="break-words text-base-content md:px-6 md:pt-2">{props.post?.content}</p>
<div class="card-actions justify-end">
<button
onClick={(): void => nav("/post/" + props.post?.id)}
class="btn btn-xs"
>
<Arrow />
</button>
</div>
</div>
</div>
);
}

View file

@ -1,29 +1,39 @@
import { useParams } from "@solidjs/router"; import { useParams } from "@solidjs/router";
import { For, JSXElement, Show, Suspense, createResource } from "solid-js"; import {
JSXElement,
Show,
Suspense,
createResource,
useContext,
} from "solid-js";
import { LoginContext } from "../Context/GlobalState";
import { loadSpinner } from "../Util/Icons"; import { loadSpinner } from "../Util/Icons";
import { getComments, getPost } from "../Util/api"; import { getPost } from "../Util/api";
import { PostSegment } from "./Posts"; import { CommentSection } from "./CommentSection";
import { NewCommentInputArea } from "./NewComment";
import { PostSegment } from "./PostSegment";
/**
* This is the view for a single post along with its comments.
* @returns {JSXElement} A JSXElement
*/
export function SinglePost(): JSXElement { export function SinglePost(): JSXElement {
const params = useParams(); const params = useParams();
const [post] = createResource(params.postid, getPost); const [post] = createResource(params.postid, getPost);
const [comments] = createResource(params.postid, () => const login_ctx = useContext(LoginContext)!; // Assuming login context is always available
getComments(params.postid, 0, 10)
);
return ( return (
<Suspense fallback={loadSpinner()}> <Suspense fallback={loadSpinner()}>
<Show when={post()}> <Show when={post()}>
<PostSegment post={post()!} /> <PostSegment post={post()!} />
<For each={comments()!}> <Show when={login_ctx.loggedIn()}>
{(comment) => ( <NewCommentInputArea
// TODO: This should be a separate component parentCommentId={null}
<div class="comment"> parentPostId={parseInt(params.postid)}
<p>{comment.content}</p> />
</div> </Show>
)} <CommentSection postId={params.postid} />
</For>
</Show> </Show>
</Suspense> </Suspense>
); );

View file

@ -2,14 +2,19 @@ import { JSXElement } from "solid-js";
export function Footer(): JSXElement { export function Footer(): JSXElement {
return ( return (
<footer class="footer footer-center rounded mt-auto bg-base-200 p-10 text-base-content"> /* Something here is causing a Layout Shift, TODO: Fix */
<footer class="footer footer-center sticky mt-auto rounded bg-base-200 p-10 text-base-content">
<nav class="grid grid-flow-col gap-4"> <nav class="grid grid-flow-col gap-4">
<a class="link-hover link">About us</a> <a href="/about" class="link-hover link">
<a class="link-hover link">Contact</a> About us
</a>
<a href="/contact" class="link-hover link">
Contact
</a>
</nav> </nav>
<nav> <nav>
<div class="grid grid-flow-col gap-4"> <div class="grid grid-flow-col gap-4">
<a> <a aria-label="Twitter" href="/404">
<svg <svg
xmlns="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg"
width="24" width="24"
@ -20,7 +25,7 @@ export function Footer(): JSXElement {
<path d="M24 4.557c-.883.392-1.832.656-2.828.775 1.017-.609 1.798-1.574 2.165-2.724-.951.564-2.005.974-3.127 1.195-.897-.957-2.178-1.555-3.594-1.555-3.179 0-5.515 2.966-4.797 6.045-4.091-.205-7.719-2.165-10.148-5.144-1.29 2.213-.669 5.108 1.523 6.574-.806-.026-1.566-.247-2.229-.616-.054 2.281 1.581 4.415 3.949 4.89-.693.188-1.452.232-2.224.084.626 1.956 2.444 3.379 4.6 3.419-2.07 1.623-4.678 2.348-7.29 2.04 2.179 1.397 4.768 2.212 7.548 2.212 9.142 0 14.307-7.721 13.995-14.646.962-.695 1.797-1.562 2.457-2.549z" /> <path d="M24 4.557c-.883.392-1.832.656-2.828.775 1.017-.609 1.798-1.574 2.165-2.724-.951.564-2.005.974-3.127 1.195-.897-.957-2.178-1.555-3.594-1.555-3.179 0-5.515 2.966-4.797 6.045-4.091-.205-7.719-2.165-10.148-5.144-1.29 2.213-.669 5.108 1.523 6.574-.806-.026-1.566-.247-2.229-.616-.054 2.281 1.581 4.415 3.949 4.89-.693.188-1.452.232-2.224.084.626 1.956 2.444 3.379 4.6 3.419-2.07 1.623-4.678 2.348-7.29 2.04 2.179 1.397 4.768 2.212 7.548 2.212 9.142 0 14.307-7.721 13.995-14.646.962-.695 1.797-1.562 2.457-2.549z" />
</svg> </svg>
</a> </a>
<a> <a aria-label="Facebook" href="/404">
<svg <svg
xmlns="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg"
width="24" width="24"
@ -31,7 +36,7 @@ export function Footer(): JSXElement {
<path d="M19.615 3.184c-3.604-.246-11.631-.245-15.23 0-3.897.266-4.356 2.62-4.385 8.816.029 6.185.484 8.549 4.385 8.816 3.6.245 11.626.246 15.23 0 3.897-.266 4.356-2.62 4.385-8.816-.029-6.185-.484-8.549-4.385-8.816zm-10.615 12.816v-8l8 3.993-8 4.007z" /> <path d="M19.615 3.184c-3.604-.246-11.631-.245-15.23 0-3.897.266-4.356 2.62-4.385 8.816.029 6.185.484 8.549 4.385 8.816 3.6.245 11.626.246 15.23 0 3.897-.266 4.356-2.62 4.385-8.816-.029-6.185-.484-8.549-4.385-8.816zm-10.615 12.816v-8l8 3.993-8 4.007z" />
</svg> </svg>
</a> </a>
<a> <a aria-label="Instagram" href="/404">
<svg <svg
xmlns="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg"
width="24" width="24"

View file

@ -9,7 +9,7 @@ export function Navbar(): JSXElement {
return ( return (
<div class="max-w navbar max-w-3xl rounded-box text-neutral-content md:my-4"> <div class="max-w navbar max-w-3xl rounded-box text-neutral-content md:my-4">
<div class="flex-1"> <div class="flex-1">
<A href={"/"} class="btn btn-ghost text-xl normal-case"> <A href={"/"} class="btn btn-ghost text-sm normal-case sm:text-xl">
<Flake /> <Flake />
<h1>FrostByte</h1> <h1>FrostByte</h1>
</A> </A>

View file

@ -3,8 +3,6 @@ import { JSXElement } from "solid-js";
// MainContainer is the main container for the page. // MainContainer is the main container for the page.
export function PageContainer(props: { children: JSXElement }): JSXElement { export function PageContainer(props: { children: JSXElement }): JSXElement {
return ( return (
<div class="flex min-h-screen flex-col items-center"> <div class="flex min-h-screen flex-col items-center">{props.children}</div>
{props.children}
</div>
); );
} }

View file

@ -171,3 +171,102 @@ export function CheckMark(): JSXElement {
</svg> </svg>
); );
} }
export function CommentsIcon(): JSXElement {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke-width="1.5"
stroke="currentColor"
class="h-6 w-6"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M12 20.25c4.97 0 9-3.694 9-8.25s-4.03-8.25-9-8.25S3 7.444 3 12c0 2.104.859 4.023 2.273 5.48.432.447.74 1.04.586 1.641a4.483 4.483 0 0 1-.923 1.785A5.969 5.969 0 0 0 6 21c1.282 0 2.47-.402 3.445-1.087.81.22 1.668.337 2.555.337Z"
/>
</svg>
);
}
// Placeholder icon for engagement, TBD
export function EngagementIcon(): JSXElement {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke-width="1.5"
stroke="currentColor"
class="h-6 w-6"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M15.362 5.214A8.252 8.252 0 0 1 12 21 8.25 8.25 0 0 1 6.038 7.047 8.287 8.287 0 0 0 9 9.601a8.983 8.983 0 0 1 3.361-6.867 8.21 8.21 0 0 0 3 2.48Z"
/>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M12 18a3.75 3.75 0 0 0 .495-7.468 5.99 5.99 0 0 0-1.925 3.547 5.975 5.975 0 0 1-2.133-1.001A3.75 3.75 0 0 0 12 18Z"
/>
</svg>
);
}
export function ReportIcon(): JSXElement {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke-width={1.5}
stroke="currentColor"
class="h-6 w-6"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M14.857 17.082a23.848 23.848 0 0 0 5.454-1.31A8.967 8.967 0 0 1 18 9.75V9A6 6 0 0 0 6 9v.75a8.967 8.967 0 0 1-2.312 6.022c1.733.64 3.56 1.085 5.455 1.31m5.714 0a24.255 24.255 0 0 1-5.714 0m5.714 0a3 3 0 1 1-5.714 0M3.124 7.5A8.969 8.969 0 0 1 5.292 3m13.416 0a8.969 8.969 0 0 1 2.168 4.5"
/>
</svg>
);
}
export function RemovePostIcon(): JSXElement {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke-width={1.5}
stroke="currentColor"
class="h-6 w-6"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="m20.25 7.5-.625 10.632a2.25 2.25 0 0 1-2.247 2.118H6.622a2.25 2.25 0 0 1-2.247-2.118L3.75 7.5m6 4.125 2.25 2.25m0 0 2.25 2.25M12 13.875l2.25-2.25M12 13.875l-2.25 2.25M3.375 7.5h17.25c.621 0 1.125-.504 1.125-1.125v-1.5c0-.621-.504-1.125-1.125-1.125H3.375c-.621 0-1.125.504-1.125 1.125v1.5c0 .621.504 1.125 1.125 1.125Z"
/>
</svg>
);
}
export function ReplyIcon(): JSXElement {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke-width={1.5}
stroke="currentColor"
class="h-6 w-6"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M8.625 12a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0Zm0 0H8.25m4.125 0a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0Zm0 0H12m4.125 0a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0Zm0 0h-.375M21 12c0 4.556-4.03 8.25-9 8.25a9.764 9.764 0 0 1-2.555-.337A5.972 5.972 0 0 1 5.41 20.97a5.969 5.969 0 0 1-.474-.065 4.48 4.48 0 0 0 .978-2.025c.09-.457-.133-.901-.467-1.226C3.93 16.178 3 14.189 3 12c0-4.556 4.03-8.25 9-8.25s9 3.694 9 8.25Z"
/>
</svg>
);
}

View file

@ -13,9 +13,22 @@ interface Votes {
export interface Post extends NewPost { export interface Post extends NewPost {
id: string; id: string;
createdAt: string; createdAt: string;
updatedAt: string;
votes: Votes; votes: Votes;
} }
export interface NewComment {
content: string;
user_token: string;
parent_post_id: number;
parent_comment_id?: number;
}
export interface Comment extends NewComment {
content: string;
token: string;
}
// This is what the login and registration responses look like // This is what the login and registration responses look like
export interface AuthResponse { export interface AuthResponse {
username: string; username: string;
@ -27,27 +40,26 @@ export interface PublicComment {
id: number; id: number;
parent_post_id: number; parent_post_id: number;
parent_comment_id: number | null; parent_comment_id: number | null;
upvotes: number;
downvotes: number;
content: string; content: string;
created_at: string; created_at: string;
updated_at: string; updated_at: string;
} }
export async function getPosts(): Promise<Post[]> { export async function getPosts(): Promise<Post[]> {
const res = await fetch("/api/posts"); const res = await fetch("/api/posts", { cache: "no-cache" });
const data = await res.json(); const data = await res.json();
return data; return data;
} }
export async function getPost(id: string): Promise<Post> { export async function getPost(id: string): Promise<Post> {
const res = await fetch(`/api/posts/${id}`); const res = await fetch(`/api/posts/${id}`, { cache: "no-cache" });
const data = await res.json(); const data = await res.json();
return data; return data;
} }
export async function createPost(post: NewPost): Promise<void> { export async function createPost(post: NewPost): Promise<void> {
await fetch("/api/posts", { await fetch("/api/posts", {
cache: "no-cache",
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
@ -56,6 +68,17 @@ export async function createPost(post: NewPost): Promise<void> {
}); });
} }
export async function createComment(comment: NewComment): Promise<void> {
await fetch("/api/comments", {
cache: "no-cache",
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(comment),
});
}
// Gets the comments for a specific post // Gets the comments for a specific post
export async function getComments( export async function getComments(
postId: string, postId: string,
@ -63,12 +86,48 @@ export async function getComments(
offset: number offset: number
): Promise<PublicComment[]> { ): Promise<PublicComment[]> {
const res = await fetch( const res = await fetch(
`/api/comments?post_id=${postId}&limit=${limit}&offset=${offset}` `/api/comments?post_id=${postId}&limit=${limit}&offset=${offset}`,
{
cache: "no-cache",
}
); );
const data = await res.json(); const data = await res.json();
return data; return data;
} }
/**
* Gets the total amount of comments for a post
* @param postId The id of the post
* @returns {Promise<number>} A promise that contains the number of comments
*/
export async function getCommentCount(postId: string): Promise<number> {
const res = await fetch(`/api/posts/${postId}/comments/count`);
const data = await res.json();
return data;
}
/**
* Gets the Engagement counts for a post by postId
* @param postId The id of the post
* @returns {Promise<number>} A promise that contains number of post engages
*/
export async function getEngagementCount(postId: string): Promise<number> {
const res = await fetch(`/api/posts/${postId}/engage`);
const data = await res.json();
return data;
}
export async function deletePost(id: string, token: string): Promise<Response> {
return await fetch(`/api/posts/${id}`, {
cache: "no-cache",
method: "DELETE",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
});
}
// Send the registration request to the server // Send the registration request to the server
export async function submitRegistration( export async function submitRegistration(
username: string, username: string,
@ -76,6 +135,7 @@ export async function submitRegistration(
captcha: string captcha: string
): Promise<AuthResponse | undefined> { ): Promise<AuthResponse | undefined> {
const response = await fetch("/api/register", { const response = await fetch("/api/register", {
cache: "no-cache",
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username, password, captcha }), body: JSON.stringify({ username, password, captcha }),
@ -91,6 +151,7 @@ export async function submitLogin(
): Promise<AuthResponse | undefined> { ): Promise<AuthResponse | undefined> {
if (username == "" || password == "") return; if (username == "" || password == "") return;
const response = await fetch("/api/login", { const response = await fetch("/api/login", {
cache: "no-cache",
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username, password }), body: JSON.stringify({ username, password }),
@ -98,3 +159,19 @@ export async function submitLogin(
if (response.ok) return await response.json(); if (response.ok) return await response.json();
} }
/**
* Engage with a post.
* @param postId The id of the post to engage with.
* @param token The token of the user engaging with the post.
* @returns {Promise<Response>} A promise that resolves to a Response object.
*/
export async function engage(postId: string, token: string): Promise<Response> {
return await fetch(`/api/posts/${postId}/engage`, {
cache: "no-cache",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
});
}

View file

@ -5,15 +5,15 @@ export default {
themes: [ themes: [
{ {
mytheme: { mytheme: {
primary: "#64279e", primary: "#3b82f6",
secondary: "#9454af", secondary: "#38bdf8",
accent: "#6ff7c5", accent: "#6ee7b7",
neutral: "#1f2329", neutral: "#1f2329",
"base-100": "#2a3a47", "base-100": "#2a3a47",
info: "#8b9be5", info: "#a5f3fc",
success: "#79e2b4", success: "#22c55e",
warning: "#efb261", warning: "#fbbf24",
error: "#e1604c", error: "#ef4444",
}, },
}, },
], ],

View file

@ -4,8 +4,9 @@
# make it available in the public directory. # make it available in the public directory.
FROM docker.io/node:alpine as client FROM docker.io/node:alpine as client
WORKDIR /build WORKDIR /build
ADD client-solid /build ADD client-solid/package.json client-solid/package-lock.json ./
RUN npm install RUN npm install
ADD client-solid .
RUN npm run build RUN npm run build
# Builds the server in an isolated stage # Builds the server in an isolated stage

4
container/Makefile Normal file
View file

@ -0,0 +1,4 @@
deploy:
docker rm -f fb-server
docker image rm -f container-frostbyte
docker compose up -d

View file

@ -1,6 +1,3 @@
# This composefile is not yet ready for use.
# This is because the application assumes the database to be migrated, which happens manually.
version: "3.8" version: "3.8"
services: services:
@ -10,19 +7,21 @@ services:
dockerfile: ./container/Containerfile dockerfile: ./container/Containerfile
container_name: fb-server container_name: fb-server
environment: environment:
DATABASE_URL: "postgres://CHANGEME:CHANGEME@fb-database:5432/frostbyte" DATABASE_URL: "postgres://fbuser:CHANGEMETOASECUREPASSWD@fb-database:5432/frostbyte"
networks: networks:
- fb_network - fb_network
depends_on: depends_on:
- postgres - postgres
ports:
- "8080:8080"
postgres: postgres:
image: docker.io/postgres:16.1-alpine image: docker.io/postgres:16.1-alpine
container_name: fb-database container_name: fb-database
environment: environment:
POSTGRES_DB: CHANGEME POSTGRES_DB: frostbyte
POSTGRES_USER: CHANGEME POSTGRES_USER: fbuser
POSTGRES_PASSWORD: CHANGEME POSTGRES_PASSWORD: CHANGEMETOASECUREPASSWD
networks: networks:
- fb_network - fb_network

View file

@ -55,6 +55,24 @@ start-postgres-dev: create-network
podman rm -f {{pg_container}} podman rm -f {{pg_container}}
podman run --network {{network}} --name {{pg_container}} -e POSTGRES_PASSWORD={{pg_pass}} -d -p {{pg_port}}:5432 docker.io/postgres:16.1-alpine podman run --network {{network}} --name {{pg_container}} -e POSTGRES_PASSWORD={{pg_pass}} -d -p {{pg_port}}:5432 docker.io/postgres:16.1-alpine
pgshell:
podman exec -it {{pg_container}} psql -U {{pg_user}} -d {{db_name}}
re-migrate:
echo {{env_local}} > server/.env
cd server && cargo sqlx database drop -y
cd server && cargo sqlx database create
cd server && cargo sqlx migrate run
@echo "Database re-initialized and migrations re-run."
db-backup:
podman exec -t {{pg_container}} pg_dump -U {{pg_user}} -d {{db_name}} | gzip > frostbyte_backup$(date +'%Y-%m-%d_%H:%M:%S').sql.gz
# Drops the database and restores it from a backup file
db-restore backupfile: db-backup
podman exec -i {{pg_container}} psql -U {{pg_user}} -d {{db_name}} -c "DROP SCHEMA public CASCADE; CREATE SCHEMA public;"
gunzip -c {{backupfile}} | podman exec -i {{pg_container}} psql -U {{pg_user}} -d {{db_name}}
[private] [private]
create-network: create-network:
podman network create {{network}} --ignore podman network create {{network}} --ignore

6
package-lock.json generated Normal file
View file

@ -0,0 +1,6 @@
{
"name": "FrostByte",
"lockfileVersion": 3,
"requires": true,
"packages": {}
}

View file

@ -0,0 +1,15 @@
{
"db_name": "PostgreSQL",
"query": "INSERT INTO comments (author_user_id, parent_post_id, content) VALUES (1, $1, $2)",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Int8",
"Text"
]
},
"nullable": []
},
"hash": "014c78e959cdc5d0dc059f6a6b37d664ee6d4f7586627ea7189b72e2cc43b906"
}

View file

@ -0,0 +1,15 @@
{
"db_name": "PostgreSQL",
"query": "DELETE FROM posts WHERE id = $1 AND user_id = (SELECT id FROM users WHERE username = $2)",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Int8",
"Text"
]
},
"nullable": []
},
"hash": "149c876947c5df3c5397a9aab0534c55acfc9521301399c47fcf5466bc2d58bc"
}

View file

@ -0,0 +1,40 @@
{
"db_name": "PostgreSQL",
"query": "SELECT id, content, created_at, updated_at FROM posts WHERE id = $1",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Int8"
},
{
"ordinal": 1,
"name": "content",
"type_info": "Text"
},
{
"ordinal": 2,
"name": "created_at",
"type_info": "Timestamp"
},
{
"ordinal": 3,
"name": "updated_at",
"type_info": "Timestamp"
}
],
"parameters": {
"Left": [
"Int8"
]
},
"nullable": [
false,
false,
false,
false
]
},
"hash": "1bc374be695ed5237e460b08d69e476c59530888879fd84de0a6116b3aa99641"
}

View file

@ -20,21 +20,11 @@
}, },
{ {
"ordinal": 3, "ordinal": 3,
"name": "upvotes",
"type_info": "Int4"
},
{
"ordinal": 4,
"name": "downvotes",
"type_info": "Int4"
},
{
"ordinal": 5,
"name": "created_at", "name": "created_at",
"type_info": "Timestamp" "type_info": "Timestamp"
}, },
{ {
"ordinal": 6, "ordinal": 4,
"name": "updated_at", "name": "updated_at",
"type_info": "Timestamp" "type_info": "Timestamp"
} }
@ -47,8 +37,6 @@
false, false,
false, false,
false, false,
false,
false,
false false
] ]
}, },

View file

@ -0,0 +1,15 @@
{
"db_name": "PostgreSQL",
"query": "INSERT INTO engagements (post_id, user_id) VALUES ($1, (SELECT id FROM users WHERE username = $2))",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Int8",
"Text"
]
},
"nullable": []
},
"hash": "2374223a11247bf75811f4cc846e9ab89e1a31a78a5be0c6d38d91e3a197af41"
}

View file

@ -0,0 +1,16 @@
{
"db_name": "PostgreSQL",
"query": "INSERT INTO comments (parent_post_id, author_user_id, content) VALUES ($1, $2, $3)",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Int8",
"Int8",
"Text"
]
},
"nullable": []
},
"hash": "2f0b854d9111ccd0d186cbbbd9ae74bcb33fb665db0784aedf520e2dafc8d65a"
}

View file

@ -1,66 +0,0 @@
{
"db_name": "PostgreSQL",
"query": "SELECT id, parent_post_id, parent_comment_id, upvotes, downvotes, content, created_at, updated_at FROM comments WHERE parent_post_id = $1 ORDER BY created_at DESC LIMIT $2 OFFSET $3",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Int8"
},
{
"ordinal": 1,
"name": "parent_post_id",
"type_info": "Int8"
},
{
"ordinal": 2,
"name": "parent_comment_id",
"type_info": "Int8"
},
{
"ordinal": 3,
"name": "upvotes",
"type_info": "Int4"
},
{
"ordinal": 4,
"name": "downvotes",
"type_info": "Int4"
},
{
"ordinal": 5,
"name": "content",
"type_info": "Text"
},
{
"ordinal": 6,
"name": "created_at",
"type_info": "Timestamp"
},
{
"ordinal": 7,
"name": "updated_at",
"type_info": "Timestamp"
}
],
"parameters": {
"Left": [
"Int8",
"Int8",
"Int8"
]
},
"nullable": [
false,
false,
true,
false,
false,
false,
false,
false
]
},
"hash": "361a0590e46d138eba4973962c5f527ea86dc3c8640a5dc556523ff336be470e"
}

View file

@ -1,6 +1,6 @@
{ {
"db_name": "PostgreSQL", "db_name": "PostgreSQL",
"query": "SELECT id, content, upvotes, downvotes, created_at, updated_at FROM posts ORDER BY created_at DESC LIMIT $1 OFFSET $2", "query": "SELECT id, content, created_at, updated_at FROM posts ORDER BY created_at DESC LIMIT $1 OFFSET $2",
"describe": { "describe": {
"columns": [ "columns": [
{ {
@ -15,21 +15,11 @@
}, },
{ {
"ordinal": 2, "ordinal": 2,
"name": "upvotes",
"type_info": "Int4"
},
{
"ordinal": 3,
"name": "downvotes",
"type_info": "Int4"
},
{
"ordinal": 4,
"name": "created_at", "name": "created_at",
"type_info": "Timestamp" "type_info": "Timestamp"
}, },
{ {
"ordinal": 5, "ordinal": 3,
"name": "updated_at", "name": "updated_at",
"type_info": "Timestamp" "type_info": "Timestamp"
} }
@ -41,13 +31,11 @@
] ]
}, },
"nullable": [ "nullable": [
false,
false,
false, false,
false, false,
false, false,
false false
] ]
}, },
"hash": "2ec6780ea09d3cd14aeb87aeb97d93ff9a46e71d75f7e00d6c990fd3585ed866" "hash": "371366128df3138dce5b63ff4fb010789ca27ba7919ceba0881134ee3e40cfb7"
} }

View file

@ -1,41 +1,38 @@
{ {
"db_name": "PostgreSQL", "db_name": "PostgreSQL",
"query": "SELECT id, content, upvotes, downvotes, created_at, updated_at FROM posts WHERE id = $1", "query": "SELECT id, parent_post_id, content, created_at, updated_at\n FROM comments WHERE parent_post_id = $1 ORDER BY created_at DESC LIMIT $2 OFFSET $3",
"describe": { "describe": {
"columns": [ "columns": [
{ {
"ordinal": 0, "ordinal": 0,
"name": "id", "name": "id",
"type_info": "Int8" "type_info": "Int4"
}, },
{ {
"ordinal": 1, "ordinal": 1,
"name": "parent_post_id",
"type_info": "Int8"
},
{
"ordinal": 2,
"name": "content", "name": "content",
"type_info": "Text" "type_info": "Text"
}, },
{
"ordinal": 2,
"name": "upvotes",
"type_info": "Int4"
},
{ {
"ordinal": 3, "ordinal": 3,
"name": "downvotes",
"type_info": "Int4"
},
{
"ordinal": 4,
"name": "created_at", "name": "created_at",
"type_info": "Timestamp" "type_info": "Timestamp"
}, },
{ {
"ordinal": 5, "ordinal": 4,
"name": "updated_at", "name": "updated_at",
"type_info": "Timestamp" "type_info": "Timestamp"
} }
], ],
"parameters": { "parameters": {
"Left": [ "Left": [
"Int8",
"Int8",
"Int8" "Int8"
] ]
}, },
@ -44,9 +41,8 @@
false, false,
false, false,
false, false,
false,
false false
] ]
}, },
"hash": "f2463f3ff911698f3e841c631e8b8609408eaa32f0dcc7fb70c029339613cd07" "hash": "745713958bdfdf0f5e9fd086dda582ead87ff0b1504135f64165cdc35352db5b"
} }

View file

@ -0,0 +1,22 @@
{
"db_name": "PostgreSQL",
"query": "SELECT COUNT(*) FROM engagements WHERE post_id = $1",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "count",
"type_info": "Int8"
}
],
"parameters": {
"Left": [
"Int8"
]
},
"nullable": [
null
]
},
"hash": "7a112e169de3c28912597e6e9d9984a7fd212436b51011e20f0ba54b209251fc"
}

View file

@ -0,0 +1,22 @@
{
"db_name": "PostgreSQL",
"query": "SELECT COUNT(*) FROM comments WHERE parent_post_id = $1",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "count",
"type_info": "Int8"
}
],
"parameters": {
"Left": [
"Int8"
]
},
"nullable": [
null
]
},
"hash": "8543bcd80753991e922e6525c4d98e403c0638293c845aec61ab662d555180b2"
}

View file

@ -1,17 +0,0 @@
{
"db_name": "PostgreSQL",
"query": "INSERT INTO comments (parent_post_id, parent_comment_id, author_user_id, content) VALUES ($1, $2, $3, $4)",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Int8",
"Int8",
"Int8",
"Text"
]
},
"nullable": []
},
"hash": "fe72509852c87463cea9775d9606e89a9851b372b39d68a10c16961acd968eef"
}

View file

@ -2,11 +2,9 @@ CREATE TABLE IF NOT EXISTS posts (
id BIGSERIAL PRIMARY KEY, id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL, user_id BIGINT NOT NULL,
content TEXT NOT NULL, content TEXT NOT NULL,
upvotes INTEGER NOT NULL DEFAULT 0,
downvotes INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users (id) FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE
); );
-- Create a function to set created_at and updated_at on INSERT -- Create a function to set created_at and updated_at on INSERT

View file

@ -1,16 +1,14 @@
CREATE TABLE IF NOT EXISTS comments ( CREATE TABLE IF NOT EXISTS comments (
id BIGSERIAL PRIMARY KEY, id SERIAL PRIMARY KEY NOT NULL,
parent_post_id BIGINT NOT NULL, parent_post_id BIGINT NOT NULL,
parent_comment_id BIGINT, -- parent_comment_id BIGINT,
author_user_id BIGINT NOT NULL, author_user_id BIGINT NOT NULL,
content TEXT NOT NULL, content TEXT NOT NULL,
upvotes INTEGER NOT NULL DEFAULT 0,
downvotes INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (parent_post_id) REFERENCES posts (id), FOREIGN KEY (parent_post_id) REFERENCES posts (id) ON DELETE CASCADE,
FOREIGN KEY (parent_comment_id) REFERENCES comments (id), -- FOREIGN KEY (parent_comment_id) REFERENCES comments (id),
FOREIGN KEY (author_user_id) REFERENCES users (id) FOREIGN KEY (author_user_id) REFERENCES users (id) ON DELETE CASCADE
); );
-- Create a function to set created_at and updated_at on INSERT -- Create a function to set created_at and updated_at on INSERT
@ -43,5 +41,5 @@ FOR EACH ROW
EXECUTE FUNCTION comments_set_updated_at(); EXECUTE FUNCTION comments_set_updated_at();
CREATE INDEX comments_parent_post_id_index ON comments (parent_post_id); CREATE INDEX comments_parent_post_id_index ON comments (parent_post_id);
CREATE INDEX comments_parent_comment_id_index ON comments (parent_comment_id); -- CREATE INDEX comments_parent_comment_id_index ON comments (parent_comment_id);
CREATE INDEX comments_user_id_index ON comments (author_user_id); CREATE INDEX comments_user_id_index ON comments (author_user_id);

View file

@ -0,0 +1,62 @@
-- Description: This file creates the procedures and functions for adding users, posts, and comments.
-- Functions are commonly used for SELECT queries, while procedures are used for INSERT, UPDATE, and DELETE queries.
-- None of these seem to play very nice with sqlx for now, but they will surely be useful in the future.
-- Procedure for adding a user
CREATE OR REPLACE PROCEDURE add_user(
IN username_param TEXT,
IN password_param TEXT
)
LANGUAGE plpgsql
AS $$
BEGIN
INSERT INTO users (username, password)
VALUES (username_param, password_param);
END;
$$;
-- Procedure for adding a post
CREATE OR REPLACE PROCEDURE add_post(
IN user_id_param BIGINT,
IN content_param TEXT
)
LANGUAGE plpgsql
AS $$
BEGIN
INSERT INTO posts (user_id, content)
VALUES (user_id_param, content_param);
END;
$$;
-- Procedure for adding a comment
CREATE OR REPLACE PROCEDURE add_comment(
IN parent_post_id_param BIGINT,
-- IN parent_comment_id_param BIGINT,
IN author_user_id_param BIGINT,
IN content_param TEXT
)
LANGUAGE plpgsql
AS $$
BEGIN
INSERT INTO comments (parent_post_id, author_user_id, content)
VALUES (parent_post_id_param, author_user_id_param, content_param);
END;
$$;
-- Function for getting comments
CREATE OR REPLACE FUNCTION get_comments(
IN parent_post_id_param BIGINT,
IN limit_param BIGINT,
IN offset_param BIGINT
)
RETURNS SETOF comments AS $$
BEGIN
RETURN QUERY
SELECT *
FROM comments
WHERE parent_post_id = parent_post_id_param
ORDER BY created_at DESC
LIMIT limit_param
OFFSET offset_param;
END;
$$ LANGUAGE plpgsql;

View file

@ -0,0 +1,7 @@
CREATE TABLE IF NOT EXISTS engagements (
user_id BIGINT NOT NULL,
post_id BIGINT NOT NULL,
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE,
FOREIGN KEY (post_id) REFERENCES posts (id) ON DELETE CASCADE,
PRIMARY KEY (user_id, post_id)
);

View file

@ -9,14 +9,13 @@ use sqlx::PgPool;
pub async fn db_new_comment( pub async fn db_new_comment(
pool: &PgPool, pool: &PgPool,
parent_post_id: i64, parent_post_id: i64,
parent_comment_id: Option<i64>, // parent_comment_id: Option<i64>,
user_id: i64, user_id: i64,
content: &str, content: &str,
) -> bool { ) -> bool {
let insert_query = sqlx::query!( let insert_query = sqlx::query!(
"INSERT INTO comments (parent_post_id, parent_comment_id, author_user_id, content) VALUES ($1, $2, $3, $4)", "INSERT INTO comments (parent_post_id, author_user_id, content) VALUES ($1, $2, $3)",
parent_post_id, parent_post_id,
parent_comment_id,
user_id, user_id,
content content
) )
@ -40,7 +39,8 @@ pub async fn db_get_comments(
) -> Vec<PublicComment> { ) -> Vec<PublicComment> {
sqlx::query_as!( sqlx::query_as!(
PublicComment, PublicComment,
"SELECT id, parent_post_id, parent_comment_id, upvotes, downvotes, content, created_at, updated_at FROM comments WHERE parent_post_id = $1 ORDER BY created_at DESC LIMIT $2 OFFSET $3", "SELECT id, parent_post_id, content, created_at, updated_at
FROM comments WHERE parent_post_id = $1 ORDER BY created_at DESC LIMIT $2 OFFSET $3",
parent_post_id, parent_post_id,
limit, limit,
offset offset
@ -54,7 +54,7 @@ pub async fn db_get_comments(
pub async fn db_get_latest_posts(pool: &PgPool, limit: i64, offset: i64) -> Vec<PublicPost> { pub async fn db_get_latest_posts(pool: &PgPool, limit: i64, offset: i64) -> Vec<PublicPost> {
sqlx::query_as!( sqlx::query_as!(
PublicPost, PublicPost,
"SELECT id, content, upvotes, downvotes, created_at, updated_at FROM posts ORDER BY created_at DESC LIMIT $1 OFFSET $2", "SELECT id, content, created_at, updated_at FROM posts ORDER BY created_at DESC LIMIT $1 OFFSET $2",
limit, limit,
offset offset
) )
@ -67,7 +67,7 @@ pub async fn db_get_latest_posts(pool: &PgPool, limit: i64, offset: i64) -> Vec<
pub async fn db_get_post(id: i64, pool: &PgPool) -> Option<PublicPost> { pub async fn db_get_post(id: i64, pool: &PgPool) -> Option<PublicPost> {
sqlx::query_as!( sqlx::query_as!(
PublicPost, PublicPost,
"SELECT id, content, upvotes, downvotes, created_at, updated_at FROM posts WHERE id = $1", "SELECT id, content, created_at, updated_at FROM posts WHERE id = $1",
id id
) )
.fetch_one(pool) .fetch_one(pool)

View file

@ -1,9 +1,11 @@
use actix_cors::Cors; use actix_cors::Cors;
use actix_files::Files; use actix_files::Files;
use actix_web::http::header::{CacheControl, CacheDirective};
use actix_web::middleware; use actix_web::middleware;
use actix_web::web::Data; use actix_web::web::Data;
use actix_web::{web::scope, App, HttpServer}; use actix_web::{web::scope, App, HttpServer};
use log::info; use log::info;
use rand::Rng;
mod db; mod db;
mod jwt; mod jwt;
@ -16,29 +18,38 @@ use jwt::Authentication;
use routes::{get_comments, get_posts, login, new_comment, new_post, post_by_id, register}; use routes::{get_comments, get_posts, login, new_comment, new_post, post_by_id, register};
use state::CaptchaState; use state::CaptchaState;
use state::ServerState; use state::ServerState;
#[allow(unused_imports)]
use util::hex_string; use util::hex_string;
use crate::routes::{delete_post, engage_post, get_comment_count, get_engagements};
#[actix_web::main] #[actix_web::main]
async fn main() -> std::io::Result<()> { async fn main() -> std::io::Result<()> {
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("debug")).init(); let mut builder = env_logger::Builder::new();
builder
.filter(None, log::LevelFilter::Debug)
.filter_module("sqlx", log::LevelFilter::Warn)
.init();
let data = ServerState::new().await; let data = ServerState::new().await;
let capt_db = CaptchaState::new(); let capt_db = CaptchaState::new();
let auth = Authentication::new("secret".as_bytes());
#[cfg(debug_assertions)] // 32 random bytes for the auth key should be enough
{ let mut rng = rand::thread_rng();
let random_bytes = (0..32).map(|_| rng.gen::<u8>()).collect::<Vec<u8>>();
let auth = Authentication::new(&random_bytes);
for _ in 0..10 { for _ in 0..10 {
let s = hex_string(10); let s = hex_string(10);
info!("Adding captcha key: {}", &s); info!("Adding access key: {}", &s);
capt_db.capthca_db.lock().unwrap().insert(s); capt_db.capthca_db.lock().unwrap().insert(s);
} }
}
info!("Spinning up server on http://localhost:8080"); info!("Spinning up server on http://localhost:8080");
HttpServer::new(move || { HttpServer::new(move || {
let cors = Cors::default() let cors = Cors::default()
.allowed_origin("https://shitpost.se") .allowed_origin("https://shitpost.se")
.allowed_origin("http://localhost:8080")
.allowed_methods(vec!["GET", "POST"]) .allowed_methods(vec!["GET", "POST"])
.max_age(3600); .max_age(3600);
@ -49,14 +60,26 @@ async fn main() -> std::io::Result<()> {
App::new() App::new()
.wrap(cors) .wrap(cors)
.wrap(middleware::Compress::default()) .wrap(middleware::Compress::default())
.wrap(middleware::Logger::default()) .wrap(middleware::Logger::new("%s %r"))
.wrap(middleware::NormalizePath::trim()) .wrap(middleware::NormalizePath::trim())
.wrap(
middleware::DefaultHeaders::new()
.add(CacheControl(vec![CacheDirective::MaxAge(31536000)])),
)
.service( .service(
scope("/api") scope("/api")
.wrap(
middleware::DefaultHeaders::new()
.add(CacheControl(vec![CacheDirective::NoCache])),
)
.service(get_posts) .service(get_posts)
.service(new_post) .service(new_post)
.service(delete_post)
.service(new_comment) .service(new_comment)
.service(get_comments) .service(get_comments)
.service(get_comment_count)
.service(engage_post)
.service(get_engagements)
.service(post_by_id) .service(post_by_id)
.service(login) .service(login)
.service(register) .service(register)

View file

@ -4,7 +4,7 @@ use crate::types::{CommentQueryParams, NewComment};
use crate::ServerState; use crate::ServerState;
use actix_web::get; use actix_web::get;
use actix_web::web::{Data, Query}; use actix_web::web::{Data, Path, Query};
use actix_web::{post, web::Json, HttpResponse, Responder, Result}; use actix_web::{post, web::Json, HttpResponse, Responder, Result};
use log::info; use log::info;
@ -24,6 +24,11 @@ pub async fn get_comments(
let comments = db_get_comments(&state.pool, post_id, limit, offset).await; let comments = db_get_comments(&state.pool, post_id, limit, offset).await;
if comments.is_empty() {
info!("No comments found for post {}", post_id);
return Ok(HttpResponse::NotFound().json("No comments found"));
}
Ok(HttpResponse::Ok().json(comments)) Ok(HttpResponse::Ok().json(comments))
} }
@ -60,14 +65,7 @@ pub async fn new_comment(
info!("Creating a new comment {:?}", &data); info!("Creating a new comment {:?}", &data);
let success = db_new_comment( let success = db_new_comment(&state.pool, data.parent_post_id, userid, &content).await;
&state.pool,
data.parent_post_id,
data.parent_comment_id,
userid,
&content,
)
.await;
match success { match success {
true => { true => {
@ -80,3 +78,22 @@ pub async fn new_comment(
} }
} }
} }
#[get("/posts/{id}/comments/count")]
pub async fn get_comment_count(
path: Path<i64>,
state: Data<ServerState>,
) -> Result<impl Responder> {
let post_id = path.into_inner();
let count = sqlx::query!(
"SELECT COUNT(*) FROM comments WHERE parent_post_id = $1",
post_id
)
.fetch_one(&state.pool)
.await
.unwrap()
.count;
return Ok(HttpResponse::Ok().json(count));
}

View file

@ -4,6 +4,7 @@ use crate::types::{NewPost, PostQueryParams};
use crate::ServerState; use crate::ServerState;
use actix_web::web::{Data, Path, Query}; use actix_web::web::{Data, Path, Query};
use actix_web::{delete, HttpRequest};
use actix_web::{get, post, web::Json, HttpResponse, Responder, Result}; use actix_web::{get, post, web::Json, HttpResponse, Responder, Result};
use log::info; use log::info;
@ -59,6 +60,130 @@ pub async fn new_post(
}; };
} }
#[post("/posts/{id}/engage")]
pub async fn engage_post(
path: Path<i64>,
state: Data<ServerState>,
auth: Data<Authentication>,
req: HttpRequest,
) -> Result<impl Responder> {
// Token from header
let token = req
.headers()
.get("Authorization")
.unwrap()
.to_str()
.unwrap();
// Remove the Bearer prefix
let token = token.replace("Bearer ", "");
let claims = auth.decode(&token);
if let Err(e) = claims {
info!("Error validating token: {}", e);
return Ok(HttpResponse::BadRequest().json("Error"));
}
let post_id = path.into_inner();
let username = claims.unwrap().sub;
let q = sqlx::query!(
"INSERT INTO engagements (post_id, user_id) VALUES ($1, (SELECT id FROM users WHERE username = $2))",
post_id,
username
).execute(&state.pool).await;
match q {
Ok(_) => (),
Err(e) => {
info!("Error engaging post: {}", e);
return Ok(HttpResponse::InternalServerError().json("Error"));
}
}
// Get engagement count
let q = sqlx::query!(
"SELECT COUNT(*) FROM engagements WHERE post_id = $1",
post_id
)
.fetch_one(&state.pool)
.await;
match q {
Ok(count) => Ok(HttpResponse::Ok().json(count.count)),
Err(e) => {
info!("Error getting engagements: {}", e);
Ok(HttpResponse::InternalServerError().json("Error"))
}
}
}
#[delete("/posts/{id}")]
pub async fn delete_post(
path: Path<i64>,
state: Data<ServerState>,
auth: Data<Authentication>,
req: HttpRequest,
) -> Result<impl Responder> {
let post_id = path.into_inner();
let token = req
.headers()
.get("Authorization")
.unwrap()
.to_str()
.unwrap();
// Remove the Bearer prefix
let token = token.replace("Bearer ", "");
let claims = auth.decode(&token);
if let Err(e) = claims {
info!("Error validating token: {}", e);
return Ok(HttpResponse::BadRequest().json("Error"));
}
let username = claims.unwrap().sub;
let q = sqlx::query!(
"DELETE FROM posts WHERE id = $1 AND user_id = (SELECT id FROM users WHERE username = $2)",
post_id,
username
)
.execute(&state.pool)
.await;
match q {
Ok(q) => {
// Does this include cascading deletes?
if q.rows_affected() == 1 {
Ok(HttpResponse::Ok().json("Deleted"))
} else {
Ok(HttpResponse::Forbidden().json("Forbidden"))
}
}
Err(e) => {
info!("Error deleting post: {}", e);
Ok(HttpResponse::InternalServerError().json("Error"))
}
}
}
#[get("/posts/{id}/engage")]
pub async fn get_engagements(path: Path<i64>, state: Data<ServerState>) -> Result<impl Responder> {
let id = path.into_inner();
let q = sqlx::query!("SELECT COUNT(*) FROM engagements WHERE post_id = $1", id)
.fetch_one(&state.pool)
.await;
match q {
Ok(count) => Ok(HttpResponse::Ok().json(count.count)),
Err(e) => {
info!("Error getting engagements: {}", e);
Ok(HttpResponse::InternalServerError().json("Error"))
}
}
}
#[get("posts/{id}")] #[get("posts/{id}")]
pub async fn post_by_id(path: Path<i64>, state: Data<ServerState>) -> Result<impl Responder> { pub async fn post_by_id(path: Path<i64>, state: Data<ServerState>) -> Result<impl Responder> {
let id = path.into_inner(); let id = path.into_inner();

View file

@ -9,7 +9,6 @@ use sqlx::PgPool;
#[derive(Clone)] #[derive(Clone)]
pub struct CaptchaState { pub struct CaptchaState {
// pub capthca_db: Arc<Mutex<BTreeMap<i32, String>>>,
pub capthca_db: Arc<Mutex<BTreeSet<String>>>, pub capthca_db: Arc<Mutex<BTreeSet<String>>>,
} }
@ -45,27 +44,13 @@ impl ServerState {
sqlx::migrate!("./migrations").run(&pool).await.unwrap(); sqlx::migrate!("./migrations").run(&pool).await.unwrap();
match crate::db::db_new_user("imbus".to_string(), "kartellen1234".to_string(), &pool).await
{
Some(u) => info!("Created default user {}", u.username),
None => error!("Failed to create default user..."),
}
match crate::db::db_new_user("hollgy".to_string(), "yomomonpizza".to_string(), &pool).await
{
Some(u) => info!("Created default user {}", u.username),
None => error!("Failed to create default user..."),
}
match crate::db::db_new_user("demouser".to_string(), "demopw".to_string(), &pool).await {
Some(u) => info!("Created default user {}", u.username),
None => error!("Failed to create default user..."),
}
// We want dummy posts
lipsum_setup(&pool).await.unwrap();
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
debug_setup(&pool).await.unwrap(); debug_setup(&pool).await.unwrap();
// We want dummy posts
#[cfg(debug_assertions)]
lipsum_setup(&pool).await.unwrap();
Self { pool } Self { pool }
} }
} }
@ -80,6 +65,7 @@ async fn debug_setup(pool: &PgPool) -> Result<(), sqlx::Error> {
} }
/// Inserts a bunch of dummy posts into the database /// Inserts a bunch of dummy posts into the database
#[allow(dead_code)]
async fn lipsum_setup(pool: &PgPool) -> Result<(), sqlx::Error> { async fn lipsum_setup(pool: &PgPool) -> Result<(), sqlx::Error> {
use lipsum::lipsum; use lipsum::lipsum;
use rand::prelude::*; use rand::prelude::*;
@ -105,6 +91,21 @@ async fn lipsum_setup(pool: &PgPool) -> Result<(), sqlx::Error> {
.execute(pool) .execute(pool)
.await?; .await?;
} }
// Insert a bunch of comments
for i in 1..101 {
for _ in 0..rng.gen_range(3..30) {
query!(
"INSERT INTO comments (author_user_id, parent_post_id, content) VALUES (1, $1, $2)",
i,
lipsum(rng.gen_range(10..100))
)
.execute(pool)
.await?;
}
}
} else {
error!("No users in the database, skipping lipsum setup");
} }
Ok(()) Ok(())

View file

@ -16,8 +16,6 @@ pub struct Comment {
pub parent_post_id: i64, pub parent_post_id: i64,
pub parent_comment_id: Option<i64>, pub parent_comment_id: Option<i64>,
pub author_user_id: i64, pub author_user_id: i64,
pub upvotes: i64,
pub downvotes: i64,
pub content: String, pub content: String,
pub created_at: chrono::NaiveDateTime, pub created_at: chrono::NaiveDateTime,
pub updated_at: chrono::NaiveDateTime, pub updated_at: chrono::NaiveDateTime,
@ -28,9 +26,6 @@ pub struct Comment {
pub struct PublicComment { pub struct PublicComment {
pub id: i64, pub id: i64,
pub parent_post_id: i64, pub parent_post_id: i64,
pub parent_comment_id: Option<i64>,
pub upvotes: i64,
pub downvotes: i64,
pub content: String, pub content: String,
pub created_at: chrono::NaiveDateTime, pub created_at: chrono::NaiveDateTime,
pub updated_at: chrono::NaiveDateTime, pub updated_at: chrono::NaiveDateTime,

View file

@ -15,8 +15,6 @@ pub struct Post {
pub id: i64, pub id: i64,
pub user_id: i64, pub user_id: i64,
pub content: String, pub content: String,
pub upvotes: i64,
pub downvotes: i64,
pub created_at: chrono::NaiveDateTime, pub created_at: chrono::NaiveDateTime,
pub updated_at: chrono::NaiveDateTime, pub updated_at: chrono::NaiveDateTime,
} }
@ -26,9 +24,9 @@ pub struct Post {
pub struct PublicPost { pub struct PublicPost {
pub id: i64, pub id: i64,
pub content: String, pub content: String,
pub upvotes: i64, #[serde(rename = "createdAt")]
pub downvotes: i64,
pub created_at: chrono::NaiveDateTime, pub created_at: chrono::NaiveDateTime,
#[serde(rename = "updatedAt")]
pub updated_at: chrono::NaiveDateTime, pub updated_at: chrono::NaiveDateTime,
} }

View file

@ -1,6 +1,7 @@
use rand::Rng; use rand::Rng;
// This will do for now // This will do for now
#[allow(dead_code)]
pub fn hex_string(length: usize) -> String { pub fn hex_string(length: usize) -> String {
let mut rng = rand::thread_rng(); let mut rng = rand::thread_rng();
let mut bytes = vec![0u8; length]; let mut bytes = vec![0u8; length];