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
60 changed files with 3716 additions and 3845 deletions

2
.gitignore vendored
View file

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

View file

@ -1,662 +0,0 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.

File diff suppressed because it is too large Load diff

View file

@ -12,27 +12,28 @@
"lint": "eslint --ext .ts,.tsx src"
},
"dependencies": {
"@solidjs/router": "^0.15.2",
"solid-js": "^1.9.3"
"@solidjs/router": "^0.9.1",
"solid-js": "^1.8.7"
},
"devDependencies": {
"@trivago/prettier-plugin-sort-imports": "^5.2.0",
"@typescript-eslint/eslint-plugin": "^8.18.2",
"@typescript-eslint/parser": "^8.18.2",
"autoprefixer": "^10.4.20",
"daisyui": "^4.12.22",
"eslint": "^9.17.0",
"@trivago/prettier-plugin-sort-imports": "^4.3.0",
"@typescript-eslint/eslint-plugin": "^6.14.0",
"@typescript-eslint/parser": "^6.14.0",
"autoprefixer": "^10.4.16",
"daisyui": "^4.4.20",
"eslint": "^8.56.0",
"eslint-config-prettier": "^9.1.0",
"eslint-import-resolver-typescript": "^3.7.0",
"eslint-plugin-import": "^2.31.0",
"eslint-plugin-prettier": "^5.2.1",
"eslint-plugin-solid": "^0.14.5",
"postcss": "^8.4.49",
"prettier": "^3.4.2",
"prettier-plugin-tailwindcss": "^0.6.9",
"tailwindcss": "^3.4.17",
"typescript": "^5.7.2",
"vite": "^6.0.6",
"vite-plugin-solid": "^2.11.0"
"eslint-import-resolver-typescript": "^3.6.1",
"eslint-plugin-import": "^2.29.1",
"eslint-plugin-prettier": "^5.0.1",
"eslint-plugin-solid": "^0.13.0",
"postcss": "^8.4.32",
"prettier": "^3.1.1",
"prettier-plugin-tailwindcss": "^0.5.9",
"tailwindcss": "^3.3.6",
"typescript": "^5.3.3",
"vite": "^5.0.10",
"vite-plugin-qrcode": "^0.2.3",
"vite-plugin-solid": "^2.8.0"
}
}

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 { 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>
{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 { 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>

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 [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"

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 { 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,25 +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>
);
}

View file

@ -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>
);

View file

@ -2,14 +2,19 @@ import { JSXElement } from "solid-js";
export function Footer(): JSXElement {
return (
<footer class="footer footer-center mt-auto rounded 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"

View file

@ -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>

View file

@ -1,22 +1,18 @@
import { Route, Router } from "@solidjs/router";
import { Route, Routes } from "@solidjs/router";
import { JSXElement } from "solid-js";
import { NewPostInputArea } from "../Components/NewPost";
import { Posts } from "../Components/Posts";
import { SinglePost } from "../Components/SinglePost";
function NotFound(): JSXElement {
return <h1>404</h1>;
}
// Primary is the section of the page that holds the main content
export function Primary(): JSXElement {
return (
<Router>
<Route path="/" component={Posts} />
<Route path="/post/:postid" component={SinglePost} />
<Route path="/new" component={NewPostInputArea} />
<Route path="*" component={NotFound} />
</Router>
<Routes>
<Route path="/" element={<Posts />} />
<Route path="/post/:postid" element={<SinglePost />} />
<Route path="/new" element={<NewPostInputArea />} />
<Route path="*" element={<h1>404</h1>} />
</Routes>
);
}

View file

@ -171,3 +171,102 @@ export function CheckMark(): JSXElement {
</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 {
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}`,
},
});
}

View file

@ -6,4 +6,11 @@ import "./index.css";
const root = document.getElementById("root");
render(() => <Router root={Root} />, root!);
render(
() => (
<Router>
<Root />
</Router>
),
root!
);

View file

@ -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",
},
},
],

View file

@ -1,4 +1,5 @@
import { defineConfig } from "vite";
import { qrcode } from "vite-plugin-qrcode";
import solid from "vite-plugin-solid";
// https://vitejs.dev/config/
@ -6,7 +7,7 @@ export default defineConfig({
// build: {
// outDir: '../server/public' // Override default outDir('dist')
// },
plugins: [solid()],
plugins: [solid(), qrcode()],
server: {
port: 3000,
open: true,

View file

@ -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
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"
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

View file

@ -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
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,
"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
]
},

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",
"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"
}

View file

@ -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"
}

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"
}

1041
server/Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -6,24 +6,24 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
actix-cors = "0.7.0"
actix-files = "0.6.6"
actix-web = "4.9.0"
argon2 = { version = "0.5.3", features = ["zeroize"] }
biosvg = "0.1.7"
chrono = { version = "0.4.39", features = ["serde"] }
clap = { version = "4.5.23", features = ["derive"] }
actix-cors = "0.6.4"
actix-files = "0.6.2"
actix-web = "4.4.0"
argon2 = { version = "0.5.2", features = ["zeroize"] }
biosvg = "0.1.3"
chrono = { version = "0.4.31", features = ["serde"] }
clap = { version = "4.4.5", features = ["derive"] }
dotenvy = "0.15.7"
env_logger = "0.11.6"
jsonwebtoken = "9.3.0"
lipsum = "0.9.1"
log = "0.4.22"
env_logger = "0.10.0"
jsonwebtoken = "9.2.0"
lipsum = "0.9.0"
log = "0.4.20"
rand = "0.8.5"
serde = { version = "1.0.216", features = ["derive"] }
serde_json = "1.0.134"
serde = { version = "1.0.188", features = ["derive"] }
serde_json = "1.0.107"
sled = { version = "0.34.7" }
sqlx = { version = "0.8.2", features = ["runtime-tokio", "chrono", "uuid", "postgres", "tls-rustls"] }
uuid = { version = "1.11.0", features = ["serde", "v4"] }
sqlx = { version = "0.7.2", features = ["runtime-tokio", "chrono", "uuid", "postgres", "tls-rustls"] }
uuid = { version = "1.4.1", features = ["serde", "v4"] }
[profile.dev.package.sqlx-macros]
opt-level = 3

View file

@ -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

View file

@ -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);

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(
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)

View file

@ -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)]
{
// 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 captcha key: {}", &s);
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)

View file

@ -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));
}

View file

@ -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();

View file

@ -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(())

View file

@ -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,

View file

@ -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,
}

View file

@ -1,7 +1,7 @@
#[allow(dead_code)]
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];