Compare commits
93 commits
Author | SHA1 | Date | |
---|---|---|---|
|
27b2be3213 | ||
|
3b52b1b7e8 | ||
|
dd1a419244 | ||
|
9954588913 | ||
|
2e600cc6d2 | ||
|
a2292ffc68 | ||
|
81303d31cd | ||
|
c3ded8a27b | ||
|
630f19f82c | ||
|
5ed65b3aeb | ||
|
ac71cbd9e2 | ||
|
78ede1785a | ||
|
e3162a6973 | ||
|
a51d397ded | ||
|
b324e0f16d | ||
|
6be8925970 | ||
|
2fe0090422 | ||
|
e04d588b56 | ||
|
3abedb256c | ||
|
85c2161a4d | ||
|
5eeed1e8bc | ||
|
a1e362acee | ||
|
3610a7413a | ||
|
038b83e530 | ||
|
d2eac68638 | ||
|
61ab9e072e | ||
|
6909dbd146 | ||
|
70ba521aa5 | ||
|
ea25fa9489 | ||
|
efcdaf0cd2 | ||
|
e946dc456d | ||
|
c5a25ad714 | ||
|
d93dc7fd89 | ||
|
6fcbb92691 | ||
|
146518b94a | ||
|
2e23c7919f | ||
|
84defa703e | ||
|
39801dfbda | ||
|
29f1ed952a | ||
|
b5b256f6e9 | ||
|
999d180b24 | ||
|
458cf196e9 | ||
|
7b87c92139 | ||
|
0907e2b7bd | ||
|
b7d00d4e75 | ||
|
6093751799 | ||
|
a0025921b1 | ||
|
88e3f03ee4 | ||
|
581d6454c0 | ||
|
b1f6c21b6f | ||
|
ac527a4b71 | ||
|
46678dfdeb | ||
|
a298f63326 | ||
|
cedb469105 | ||
|
f9ef90e61f | ||
|
67563c5c25 | ||
|
addbb820a3 | ||
|
bbae426c09 | ||
|
2b12a83aa8 | ||
|
82e3f18961 | ||
|
3174f99a51 | ||
|
3a42624042 | ||
|
368d7c9c65 | ||
|
45c3b87243 | ||
|
79208cb9c2 | ||
|
39df975b04 | ||
|
a83cce236f | ||
|
aee8a44404 | ||
|
6e6b9aa73c | ||
|
238b0442e4 | ||
|
cceba2cc42 | ||
|
2362231767 | ||
|
d233fa4fd5 | ||
|
21e8cab0ed | ||
|
8eca21336d | ||
|
6f69abe973 | ||
|
211490bd6f | ||
|
68fca7cbde | ||
|
71bbd3bfbd | ||
|
40099c9b62 | ||
|
b0113aa985 | ||
|
a2064b440d | ||
|
a5dadfc1d1 | ||
|
3a389d854b | ||
|
8875ae4a4c | ||
|
5a75e6f9a0 | ||
|
d0e5b57006 | ||
|
32ff43e87c | ||
|
3d40ec513e | ||
|
d12bd9aa99 | ||
|
9e302fc54a | ||
|
d2fd1a17ed | ||
|
edb7ef2fc4 |
54 changed files with 3171 additions and 1820 deletions
2
.gitignore
vendored
2
.gitignore
vendored
|
@ -25,3 +25,5 @@ dist-ssr
|
|||
|
||||
*.env
|
||||
*.db*
|
||||
|
||||
*backup*
|
||||
|
|
3531
client-solid/package-lock.json
generated
3531
client-solid/package-lock.json
generated
File diff suppressed because it is too large
Load diff
|
@ -36,4 +36,4 @@
|
|||
"vite-plugin-qrcode": "^0.2.3",
|
||||
"vite-plugin-solid": "^2.8.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
3
client-solid/public/robots.txt
Normal file
3
client-solid/public/robots.txt
Normal file
|
@ -0,0 +1,3 @@
|
|||
User-agent: *
|
||||
Disallow: /settings/
|
||||
Disallow: /public/
|
42
client-solid/src/Components/Buttons/CommentsButton.tsx
Normal file
42
client-solid/src/Components/Buttons/CommentsButton.tsx
Normal 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>
|
||||
);
|
||||
}
|
51
client-solid/src/Components/Buttons/Engegament.tsx
Normal file
51
client-solid/src/Components/Buttons/Engegament.tsx
Normal 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>
|
||||
);
|
||||
}
|
65
client-solid/src/Components/Buttons/RemovePostButton.tsx
Normal file
65
client-solid/src/Components/Buttons/RemovePostButton.tsx
Normal 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>
|
||||
);
|
||||
}
|
20
client-solid/src/Components/Buttons/Reply.tsx
Normal file
20
client-solid/src/Components/Buttons/Reply.tsx
Normal 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>
|
||||
);
|
||||
}
|
20
client-solid/src/Components/Buttons/Report.tsx
Normal file
20
client-solid/src/Components/Buttons/Report.tsx
Normal 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>
|
||||
);
|
||||
}
|
21
client-solid/src/Components/Buttons/ToPost.tsx
Normal file
21
client-solid/src/Components/Buttons/ToPost.tsx
Normal 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>
|
||||
);
|
||||
}
|
31
client-solid/src/Components/Comment.tsx
Normal file
31
client-solid/src/Components/Comment.tsx
Normal 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" />
|
||||
</>
|
||||
);
|
||||
}
|
18
client-solid/src/Components/CommentSection.tsx
Normal file
18
client-solid/src/Components/CommentSection.tsx
Normal 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>
|
||||
);
|
||||
}
|
|
@ -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 { UserCircle } from "../Util/Icons";
|
||||
|
||||
export function LoginButton(): JSXElement {
|
||||
const modal_ctx = useContext(ModalContext)!;
|
||||
const login_ctx = useContext(LoginContext)!;
|
||||
const [showLogoutModal, setShowLogoutModal] = createSignal(false);
|
||||
|
||||
const clickHandler = (): void => {
|
||||
if (login_ctx.loggedIn()) login_ctx.logOut();
|
||||
else modal_ctx.setOpen(true);
|
||||
if (login_ctx.loggedIn()) {
|
||||
setShowLogoutModal(true);
|
||||
} else {
|
||||
modal_ctx.setOpen(true);
|
||||
}
|
||||
};
|
||||
|
||||
const confirmLogout = (): void => {
|
||||
login_ctx.logOut();
|
||||
setShowLogoutModal(false);
|
||||
};
|
||||
|
||||
const cancelLogout = (): void => {
|
||||
setShowLogoutModal(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<div class="btn btn-ghost text-sm capitalize" onClick={clickHandler}>
|
||||
<Show when={login_ctx.loggedIn()} fallback="Login">
|
||||
{login_ctx.username()}
|
||||
</Show>
|
||||
<UserCircle />
|
||||
</div>
|
||||
<>
|
||||
<div class="btn btn-ghost text-sm capitalize" onClick={clickHandler}>
|
||||
<Show when={login_ctx.loggedIn()} fallback="Login">
|
||||
{login_ctx.username()}
|
||||
</Show>
|
||||
</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>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
|
|
@ -2,7 +2,7 @@ import { A } from "@solidjs/router";
|
|||
import { JSXElement, Show, useContext } from "solid-js";
|
||||
|
||||
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
|
||||
export function MenuItem(props: {
|
||||
|
@ -23,10 +23,7 @@ export function Menu(): JSXElement {
|
|||
const login_ctx = useContext(LoginContext)!;
|
||||
return (
|
||||
<Show when={login_ctx.loggedIn()}>
|
||||
<ul class="menu space-y-2 rounded-box md:menu-horizontal md:space-x-2 md:space-y-0">
|
||||
<MenuItem href="/">
|
||||
<Home />
|
||||
</MenuItem>
|
||||
<ul class="menu menu-horizontal space-x-2 space-y-0 rounded-box md:space-x-5 md:space-y-0">
|
||||
<MenuItem href="/new">
|
||||
<Plus />
|
||||
</MenuItem>
|
||||
|
|
71
client-solid/src/Components/NewComment.tsx
Normal file
71
client-solid/src/Components/NewComment.tsx
Normal 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>
|
||||
);
|
||||
}
|
|
@ -8,7 +8,7 @@ export function NewPostInputArea(): JSXElement {
|
|||
const [content, setContent] = createSignal("");
|
||||
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 nav = useNavigate();
|
||||
|
@ -40,6 +40,7 @@ export function NewPostInputArea(): JSXElement {
|
|||
when={!waiting()}
|
||||
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">
|
||||
<textarea
|
||||
class="textarea textarea-bordered h-32"
|
||||
|
|
57
client-solid/src/Components/PostSegment.tsx
Normal file
57
client-solid/src/Components/PostSegment.tsx
Normal 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>
|
||||
);
|
||||
}
|
|
@ -1,9 +1,13 @@
|
|||
import { useNavigate } from "@solidjs/router";
|
||||
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 { 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 {
|
||||
const [posts, setPosts] = createSignal([] as Post[]);
|
||||
const [loading, setLoading] = createSignal(true);
|
||||
|
@ -21,23 +25,3 @@ export function Posts(): JSXElement {
|
|||
</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>
|
||||
);
|
||||
}
|
||||
|
|
|
@ -1,29 +1,39 @@
|
|||
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 { getComments, getPost } from "../Util/api";
|
||||
import { PostSegment } from "./Posts";
|
||||
import { getPost } from "../Util/api";
|
||||
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 {
|
||||
const params = useParams();
|
||||
const [post] = createResource(params.postid, getPost);
|
||||
const [comments] = createResource(params.postid, () =>
|
||||
getComments(params.postid, 0, 10)
|
||||
);
|
||||
const login_ctx = useContext(LoginContext)!; // Assuming login context is always available
|
||||
|
||||
return (
|
||||
<Suspense fallback={loadSpinner()}>
|
||||
<Show when={post()}>
|
||||
<PostSegment post={post()!} />
|
||||
<For each={comments()!}>
|
||||
{(comment) => (
|
||||
// TODO: This should be a separate component
|
||||
<div class="comment">
|
||||
<p>{comment.content}</p>
|
||||
</div>
|
||||
)}
|
||||
</For>
|
||||
<Show when={login_ctx.loggedIn()}>
|
||||
<NewCommentInputArea
|
||||
parentCommentId={null}
|
||||
parentPostId={parseInt(params.postid)}
|
||||
/>
|
||||
</Show>
|
||||
<CommentSection postId={params.postid} />
|
||||
</Show>
|
||||
</Suspense>
|
||||
);
|
||||
|
|
|
@ -2,14 +2,19 @@ import { JSXElement } from "solid-js";
|
|||
|
||||
export function Footer(): JSXElement {
|
||||
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">
|
||||
<a class="link-hover link">About us</a>
|
||||
<a class="link-hover link">Contact</a>
|
||||
<a href="/about" class="link-hover link">
|
||||
About us
|
||||
</a>
|
||||
<a href="/contact" class="link-hover link">
|
||||
Contact
|
||||
</a>
|
||||
</nav>
|
||||
<nav>
|
||||
<div class="grid grid-flow-col gap-4">
|
||||
<a>
|
||||
<a aria-label="Twitter" href="/404">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
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" />
|
||||
</svg>
|
||||
</a>
|
||||
<a>
|
||||
<a aria-label="Facebook" href="/404">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
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" />
|
||||
</svg>
|
||||
</a>
|
||||
<a>
|
||||
<a aria-label="Instagram" href="/404">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
|
|
|
@ -9,7 +9,7 @@ export function Navbar(): JSXElement {
|
|||
return (
|
||||
<div class="max-w navbar max-w-3xl rounded-box text-neutral-content md:my-4">
|
||||
<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 />
|
||||
<h1>FrostByte</h1>
|
||||
</A>
|
||||
|
|
|
@ -3,8 +3,6 @@ import { JSXElement } from "solid-js";
|
|||
// MainContainer is the main container for the page.
|
||||
export function PageContainer(props: { children: JSXElement }): JSXElement {
|
||||
return (
|
||||
<div class="flex min-h-screen flex-col items-center">
|
||||
{props.children}
|
||||
</div>
|
||||
<div class="flex min-h-screen flex-col items-center">{props.children}</div>
|
||||
);
|
||||
}
|
||||
|
|
|
@ -155,19 +155,118 @@ export function ThumbDown(): JSXElement {
|
|||
|
||||
export function CheckMark(): 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"
|
||||
<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-linecape="round"
|
||||
stroke-linejoin="round"
|
||||
d="m4.5 12.75 6 6 9-13.5"
|
||||
<path
|
||||
stroke-linecape="round"
|
||||
stroke-linejoin="round"
|
||||
d="m4.5 12.75 6 6 9-13.5"
|
||||
/>
|
||||
</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>
|
||||
);
|
||||
}
|
||||
|
|
|
@ -13,9 +13,22 @@ interface Votes {
|
|||
export interface Post extends NewPost {
|
||||
id: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
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
|
||||
export interface AuthResponse {
|
||||
username: string;
|
||||
|
@ -27,27 +40,26 @@ export interface PublicComment {
|
|||
id: number;
|
||||
parent_post_id: number;
|
||||
parent_comment_id: number | null;
|
||||
upvotes: number;
|
||||
downvotes: number;
|
||||
content: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
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();
|
||||
return data;
|
||||
}
|
||||
|
||||
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();
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function createPost(post: NewPost): Promise<void> {
|
||||
await fetch("/api/posts", {
|
||||
cache: "no-cache",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"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
|
||||
export async function getComments(
|
||||
postId: string,
|
||||
|
@ -63,12 +86,48 @@ export async function getComments(
|
|||
offset: number
|
||||
): Promise<PublicComment[]> {
|
||||
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();
|
||||
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
|
||||
export async function submitRegistration(
|
||||
username: string,
|
||||
|
@ -76,6 +135,7 @@ export async function submitRegistration(
|
|||
captcha: string
|
||||
): Promise<AuthResponse | undefined> {
|
||||
const response = await fetch("/api/register", {
|
||||
cache: "no-cache",
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ username, password, captcha }),
|
||||
|
@ -91,6 +151,7 @@ export async function submitLogin(
|
|||
): Promise<AuthResponse | undefined> {
|
||||
if (username == "" || password == "") return;
|
||||
const response = await fetch("/api/login", {
|
||||
cache: "no-cache",
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ username, password }),
|
||||
|
@ -98,3 +159,19 @@ export async function submitLogin(
|
|||
|
||||
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}`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
|
|
@ -5,15 +5,15 @@ export default {
|
|||
themes: [
|
||||
{
|
||||
mytheme: {
|
||||
primary: "#64279e",
|
||||
secondary: "#9454af",
|
||||
accent: "#6ff7c5",
|
||||
primary: "#3b82f6",
|
||||
secondary: "#38bdf8",
|
||||
accent: "#6ee7b7",
|
||||
neutral: "#1f2329",
|
||||
"base-100": "#2a3a47",
|
||||
info: "#8b9be5",
|
||||
success: "#79e2b4",
|
||||
warning: "#efb261",
|
||||
error: "#e1604c",
|
||||
info: "#a5f3fc",
|
||||
success: "#22c55e",
|
||||
warning: "#fbbf24",
|
||||
error: "#ef4444",
|
||||
},
|
||||
},
|
||||
],
|
||||
|
|
|
@ -4,8 +4,9 @@
|
|||
# make it available in the public directory.
|
||||
FROM docker.io/node:alpine as client
|
||||
WORKDIR /build
|
||||
ADD client-solid /build
|
||||
ADD client-solid/package.json client-solid/package-lock.json ./
|
||||
RUN npm install
|
||||
ADD client-solid .
|
||||
RUN npm run build
|
||||
|
||||
# Builds the server in an isolated stage
|
||||
|
|
4
container/Makefile
Normal file
4
container/Makefile
Normal file
|
@ -0,0 +1,4 @@
|
|||
deploy:
|
||||
docker rm -f fb-server
|
||||
docker image rm -f container-frostbyte
|
||||
docker compose up -d
|
|
@ -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"
|
||||
|
||||
services:
|
||||
|
@ -10,19 +7,21 @@ services:
|
|||
dockerfile: ./container/Containerfile
|
||||
container_name: fb-server
|
||||
environment:
|
||||
DATABASE_URL: "postgres://CHANGEME:CHANGEME@fb-database:5432/frostbyte"
|
||||
DATABASE_URL: "postgres://fbuser:CHANGEMETOASECUREPASSWD@fb-database:5432/frostbyte"
|
||||
networks:
|
||||
- fb_network
|
||||
depends_on:
|
||||
- postgres
|
||||
ports:
|
||||
- "8080:8080"
|
||||
|
||||
postgres:
|
||||
image: docker.io/postgres:16.1-alpine
|
||||
container_name: fb-database
|
||||
environment:
|
||||
POSTGRES_DB: CHANGEME
|
||||
POSTGRES_USER: CHANGEME
|
||||
POSTGRES_PASSWORD: CHANGEME
|
||||
POSTGRES_DB: frostbyte
|
||||
POSTGRES_USER: fbuser
|
||||
POSTGRES_PASSWORD: CHANGEMETOASECUREPASSWD
|
||||
networks:
|
||||
- fb_network
|
||||
|
||||
|
|
18
justfile
18
justfile
|
@ -55,6 +55,24 @@ start-postgres-dev: create-network
|
|||
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
|
||||
|
||||
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]
|
||||
create-network:
|
||||
podman network create {{network}} --ignore
|
||||
|
|
6
package-lock.json
generated
Normal file
6
package-lock.json
generated
Normal file
|
@ -0,0 +1,6 @@
|
|||
{
|
||||
"name": "FrostByte",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {}
|
||||
}
|
|
@ -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"
|
||||
}
|
|
@ -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"
|
||||
}
|
|
@ -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"
|
||||
}
|
|
@ -20,21 +20,11 @@
|
|||
},
|
||||
{
|
||||
"ordinal": 3,
|
||||
"name": "upvotes",
|
||||
"type_info": "Int4"
|
||||
},
|
||||
{
|
||||
"ordinal": 4,
|
||||
"name": "downvotes",
|
||||
"type_info": "Int4"
|
||||
},
|
||||
{
|
||||
"ordinal": 5,
|
||||
"name": "created_at",
|
||||
"type_info": "Timestamp"
|
||||
},
|
||||
{
|
||||
"ordinal": 6,
|
||||
"ordinal": 4,
|
||||
"name": "updated_at",
|
||||
"type_info": "Timestamp"
|
||||
}
|
||||
|
@ -47,8 +37,6 @@
|
|||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
|
|
|
@ -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"
|
||||
}
|
|
@ -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"
|
||||
}
|
|
@ -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"
|
||||
}
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"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": {
|
||||
"columns": [
|
||||
{
|
||||
|
@ -15,21 +15,11 @@
|
|||
},
|
||||
{
|
||||
"ordinal": 2,
|
||||
"name": "upvotes",
|
||||
"type_info": "Int4"
|
||||
},
|
||||
{
|
||||
"ordinal": 3,
|
||||
"name": "downvotes",
|
||||
"type_info": "Int4"
|
||||
},
|
||||
{
|
||||
"ordinal": 4,
|
||||
"name": "created_at",
|
||||
"type_info": "Timestamp"
|
||||
},
|
||||
{
|
||||
"ordinal": 5,
|
||||
"ordinal": 3,
|
||||
"name": "updated_at",
|
||||
"type_info": "Timestamp"
|
||||
}
|
||||
|
@ -41,13 +31,11 @@
|
|||
]
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "2ec6780ea09d3cd14aeb87aeb97d93ff9a46e71d75f7e00d6c990fd3585ed866"
|
||||
"hash": "371366128df3138dce5b63ff4fb010789ca27ba7919ceba0881134ee3e40cfb7"
|
||||
}
|
|
@ -1,41 +1,38 @@
|
|||
{
|
||||
"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": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "id",
|
||||
"type_info": "Int8"
|
||||
"type_info": "Int4"
|
||||
},
|
||||
{
|
||||
"ordinal": 1,
|
||||
"name": "parent_post_id",
|
||||
"type_info": "Int8"
|
||||
},
|
||||
{
|
||||
"ordinal": 2,
|
||||
"name": "content",
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"ordinal": 2,
|
||||
"name": "upvotes",
|
||||
"type_info": "Int4"
|
||||
},
|
||||
{
|
||||
"ordinal": 3,
|
||||
"name": "downvotes",
|
||||
"type_info": "Int4"
|
||||
},
|
||||
{
|
||||
"ordinal": 4,
|
||||
"name": "created_at",
|
||||
"type_info": "Timestamp"
|
||||
},
|
||||
{
|
||||
"ordinal": 5,
|
||||
"ordinal": 4,
|
||||
"name": "updated_at",
|
||||
"type_info": "Timestamp"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Int8",
|
||||
"Int8",
|
||||
"Int8"
|
||||
]
|
||||
},
|
||||
|
@ -44,9 +41,8 @@
|
|||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "f2463f3ff911698f3e841c631e8b8609408eaa32f0dcc7fb70c029339613cd07"
|
||||
"hash": "745713958bdfdf0f5e9fd086dda582ead87ff0b1504135f64165cdc35352db5b"
|
||||
}
|
|
@ -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"
|
||||
}
|
|
@ -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"
|
||||
}
|
|
@ -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"
|
||||
}
|
|
@ -2,11 +2,9 @@ CREATE TABLE IF NOT EXISTS posts (
|
|||
id BIGSERIAL PRIMARY KEY,
|
||||
user_id BIGINT 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,
|
||||
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
|
||||
|
|
|
@ -1,16 +1,14 @@
|
|||
CREATE TABLE IF NOT EXISTS comments (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
id SERIAL PRIMARY KEY NOT NULL,
|
||||
parent_post_id BIGINT NOT NULL,
|
||||
parent_comment_id BIGINT,
|
||||
-- parent_comment_id BIGINT,
|
||||
author_user_id BIGINT 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,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (parent_post_id) REFERENCES posts (id),
|
||||
FOREIGN KEY (parent_comment_id) REFERENCES comments (id),
|
||||
FOREIGN KEY (author_user_id) REFERENCES users (id)
|
||||
FOREIGN KEY (parent_post_id) REFERENCES posts (id) ON DELETE CASCADE,
|
||||
-- FOREIGN KEY (parent_comment_id) REFERENCES comments (id),
|
||||
FOREIGN KEY (author_user_id) REFERENCES users (id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
-- 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();
|
||||
|
||||
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);
|
62
server/migrations/0004_procedures.sql
Normal file
62
server/migrations/0004_procedures.sql
Normal 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;
|
7
server/migrations/0005_engagements_table.sql
Normal file
7
server/migrations/0005_engagements_table.sql
Normal 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)
|
||||
);
|
|
@ -9,14 +9,13 @@ use sqlx::PgPool;
|
|||
pub async fn db_new_comment(
|
||||
pool: &PgPool,
|
||||
parent_post_id: i64,
|
||||
parent_comment_id: Option<i64>,
|
||||
// parent_comment_id: Option<i64>,
|
||||
user_id: i64,
|
||||
content: &str,
|
||||
) -> bool {
|
||||
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_comment_id,
|
||||
user_id,
|
||||
content
|
||||
)
|
||||
|
@ -40,7 +39,8 @@ pub async fn db_get_comments(
|
|||
) -> Vec<PublicComment> {
|
||||
sqlx::query_as!(
|
||||
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,
|
||||
limit,
|
||||
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> {
|
||||
sqlx::query_as!(
|
||||
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,
|
||||
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> {
|
||||
sqlx::query_as!(
|
||||
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
|
||||
)
|
||||
.fetch_one(pool)
|
||||
|
|
|
@ -1,9 +1,11 @@
|
|||
use actix_cors::Cors;
|
||||
use actix_files::Files;
|
||||
use actix_web::http::header::{CacheControl, CacheDirective};
|
||||
use actix_web::middleware;
|
||||
use actix_web::web::Data;
|
||||
use actix_web::{web::scope, App, HttpServer};
|
||||
use log::info;
|
||||
use rand::Rng;
|
||||
|
||||
mod db;
|
||||
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 state::CaptchaState;
|
||||
use state::ServerState;
|
||||
#[allow(unused_imports)]
|
||||
use util::hex_string;
|
||||
|
||||
use crate::routes::{delete_post, engage_post, get_comment_count, get_engagements};
|
||||
|
||||
#[actix_web::main]
|
||||
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 capt_db = CaptchaState::new();
|
||||
let auth = Authentication::new("secret".as_bytes());
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
{
|
||||
for _ in 0..10 {
|
||||
let s = hex_string(10);
|
||||
info!("Adding captcha key: {}", &s);
|
||||
capt_db.capthca_db.lock().unwrap().insert(s);
|
||||
}
|
||||
// 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 {
|
||||
let s = hex_string(10);
|
||||
info!("Adding access key: {}", &s);
|
||||
capt_db.capthca_db.lock().unwrap().insert(s);
|
||||
}
|
||||
|
||||
info!("Spinning up server on http://localhost:8080");
|
||||
HttpServer::new(move || {
|
||||
let cors = Cors::default()
|
||||
.allowed_origin("https://shitpost.se")
|
||||
.allowed_origin("http://localhost:8080")
|
||||
.allowed_methods(vec!["GET", "POST"])
|
||||
.max_age(3600);
|
||||
|
||||
|
@ -49,14 +60,26 @@ async fn main() -> std::io::Result<()> {
|
|||
App::new()
|
||||
.wrap(cors)
|
||||
.wrap(middleware::Compress::default())
|
||||
.wrap(middleware::Logger::default())
|
||||
.wrap(middleware::Logger::new("%s %r"))
|
||||
.wrap(middleware::NormalizePath::trim())
|
||||
.wrap(
|
||||
middleware::DefaultHeaders::new()
|
||||
.add(CacheControl(vec![CacheDirective::MaxAge(31536000)])),
|
||||
)
|
||||
.service(
|
||||
scope("/api")
|
||||
.wrap(
|
||||
middleware::DefaultHeaders::new()
|
||||
.add(CacheControl(vec![CacheDirective::NoCache])),
|
||||
)
|
||||
.service(get_posts)
|
||||
.service(new_post)
|
||||
.service(delete_post)
|
||||
.service(new_comment)
|
||||
.service(get_comments)
|
||||
.service(get_comment_count)
|
||||
.service(engage_post)
|
||||
.service(get_engagements)
|
||||
.service(post_by_id)
|
||||
.service(login)
|
||||
.service(register)
|
||||
|
|
|
@ -4,7 +4,7 @@ use crate::types::{CommentQueryParams, NewComment};
|
|||
use crate::ServerState;
|
||||
|
||||
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 log::info;
|
||||
|
||||
|
@ -24,6 +24,11 @@ pub async fn get_comments(
|
|||
|
||||
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))
|
||||
}
|
||||
|
||||
|
@ -60,14 +65,7 @@ pub async fn new_comment(
|
|||
|
||||
info!("Creating a new comment {:?}", &data);
|
||||
|
||||
let success = db_new_comment(
|
||||
&state.pool,
|
||||
data.parent_post_id,
|
||||
data.parent_comment_id,
|
||||
userid,
|
||||
&content,
|
||||
)
|
||||
.await;
|
||||
let success = db_new_comment(&state.pool, data.parent_post_id, userid, &content).await;
|
||||
|
||||
match success {
|
||||
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));
|
||||
}
|
||||
|
|
|
@ -4,6 +4,7 @@ use crate::types::{NewPost, PostQueryParams};
|
|||
use crate::ServerState;
|
||||
|
||||
use actix_web::web::{Data, Path, Query};
|
||||
use actix_web::{delete, HttpRequest};
|
||||
use actix_web::{get, post, web::Json, HttpResponse, Responder, Result};
|
||||
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}")]
|
||||
pub async fn post_by_id(path: Path<i64>, state: Data<ServerState>) -> Result<impl Responder> {
|
||||
let id = path.into_inner();
|
||||
|
|
|
@ -9,7 +9,6 @@ use sqlx::PgPool;
|
|||
|
||||
#[derive(Clone)]
|
||||
pub struct CaptchaState {
|
||||
// pub capthca_db: Arc<Mutex<BTreeMap<i32, String>>>,
|
||||
pub capthca_db: Arc<Mutex<BTreeSet<String>>>,
|
||||
}
|
||||
|
||||
|
@ -45,27 +44,13 @@ impl ServerState {
|
|||
|
||||
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)]
|
||||
debug_setup(&pool).await.unwrap();
|
||||
|
||||
// We want dummy posts
|
||||
#[cfg(debug_assertions)]
|
||||
lipsum_setup(&pool).await.unwrap();
|
||||
|
||||
Self { pool }
|
||||
}
|
||||
}
|
||||
|
@ -80,6 +65,7 @@ async fn debug_setup(pool: &PgPool) -> Result<(), sqlx::Error> {
|
|||
}
|
||||
|
||||
/// Inserts a bunch of dummy posts into the database
|
||||
#[allow(dead_code)]
|
||||
async fn lipsum_setup(pool: &PgPool) -> Result<(), sqlx::Error> {
|
||||
use lipsum::lipsum;
|
||||
use rand::prelude::*;
|
||||
|
@ -105,6 +91,21 @@ async fn lipsum_setup(pool: &PgPool) -> Result<(), sqlx::Error> {
|
|||
.execute(pool)
|
||||
.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(())
|
||||
|
|
|
@ -16,8 +16,6 @@ pub struct Comment {
|
|||
pub parent_post_id: i64,
|
||||
pub parent_comment_id: Option<i64>,
|
||||
pub author_user_id: i64,
|
||||
pub upvotes: i64,
|
||||
pub downvotes: i64,
|
||||
pub content: String,
|
||||
pub created_at: chrono::NaiveDateTime,
|
||||
pub updated_at: chrono::NaiveDateTime,
|
||||
|
@ -28,9 +26,6 @@ pub struct Comment {
|
|||
pub struct PublicComment {
|
||||
pub id: i64,
|
||||
pub parent_post_id: i64,
|
||||
pub parent_comment_id: Option<i64>,
|
||||
pub upvotes: i64,
|
||||
pub downvotes: i64,
|
||||
pub content: String,
|
||||
pub created_at: chrono::NaiveDateTime,
|
||||
pub updated_at: chrono::NaiveDateTime,
|
||||
|
|
|
@ -15,8 +15,6 @@ pub struct Post {
|
|||
pub id: i64,
|
||||
pub user_id: i64,
|
||||
pub content: String,
|
||||
pub upvotes: i64,
|
||||
pub downvotes: i64,
|
||||
pub created_at: chrono::NaiveDateTime,
|
||||
pub updated_at: chrono::NaiveDateTime,
|
||||
}
|
||||
|
@ -26,9 +24,9 @@ pub struct Post {
|
|||
pub struct PublicPost {
|
||||
pub id: i64,
|
||||
pub content: String,
|
||||
pub upvotes: i64,
|
||||
pub downvotes: i64,
|
||||
#[serde(rename = "createdAt")]
|
||||
pub created_at: chrono::NaiveDateTime,
|
||||
#[serde(rename = "updatedAt")]
|
||||
pub updated_at: chrono::NaiveDateTime,
|
||||
}
|
||||
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
use rand::Rng;
|
||||
|
||||
// This will do for now
|
||||
#[allow(dead_code)]
|
||||
pub fn hex_string(length: usize) -> String {
|
||||
let mut rng = rand::thread_rng();
|
||||
let mut bytes = vec![0u8; length];
|
||||
|
|
Loading…
Reference in a new issue