This commit is contained in:
Dominic Grimm 2023-05-21 18:58:10 +02:00
commit e82f35da2a
Signed by: dergrimm
GPG key ID: B6FFE500AAD54A3A
78 changed files with 10821 additions and 0 deletions

16
.example.env Normal file
View file

@ -0,0 +1,16 @@
POSTGRES_USER="gitea_pages"
POSTGRES_PASSWORD="gitea_pages"
RABBITMQ_USER="gitea_pages"
RABBITMQ_PASSWORD="gitea_pages"
PAGES_USER="MY_USER"
PAGES_PASSWORD="MY_PASSWORD"
PAGES_GITEA_URL="MY_GITEA_INSTANCE.NET"
PAGES_GITEA_API_TOKEN="MY_API_TOKEN"
PAGES_GITEA_SECRET="MY_WEBHOOK_SECRET"
PAGES_GITEA_PULL_URL="https://MY_GITEA_INSTANCE.NET"
PAGES_GITEA_PULL_BRANCH="pages"
PAGES_NGINX_CONFIG_DIR="/opt/nginx-config"
PAGES_REPOS_DIR="/data/repos"
PAGES_DOMAIN="MY_GITEA_PAGES.NET"

1
.gitignore vendored Normal file
View file

@ -0,0 +1 @@
.env

674
LICENSE Normal file
View file

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 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 General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is 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. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
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.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
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 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. Use with the GNU Affero General Public License.
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 Affero 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 special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU 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 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 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 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 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 General Public License for more details.
You should have received a copy of the GNU 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 the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
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 GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

3
README.md Normal file
View file

@ -0,0 +1,3 @@
# gitea_pages
_Containerized web application for managing public pages of Git repositories within a single Gitea instance._

BIN
avatar.xcf Normal file

Binary file not shown.

View file

@ -0,0 +1,3 @@
[target.x86_64-unknown-linux-gnu]
linker = "clang"
rustflags = ["-C", "link-arg=-fuse-ld=/usr/bin/mold"]

10
backend/.dockerignore Normal file
View file

@ -0,0 +1,10 @@
/docs/
/lib/
/bin/
/.shards/
*.dwarf
*.env
/examples/
Dockerfile
.dockerignore
README.md

17
backend/.editorconfig Normal file
View file

@ -0,0 +1,17 @@
root = true
[*.rs]
charset = utf-8
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 4
trim_trailing_whitespace = true
[*.sql]
charset = utf-8
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 4
trim_trailing_whitespace = true

1
backend/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
/target

6
backend/.sqlfluff Normal file
View file

@ -0,0 +1,6 @@
[sqlfluff]
dialect = postgres
exclude_rules = LT05
[sqlfluff:indentation]
tab_space_size = 4

3877
backend/Cargo.lock generated Normal file

File diff suppressed because it is too large Load diff

54
backend/Cargo.toml Normal file
View file

@ -0,0 +1,54 @@
[package]
name = "gitea_pages"
version = "0.1.0"
edition = "2021"
[profile.release]
opt-level = 3
lto = true
codegen-units = 1
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
actix-cors = "0.6.4"
actix-web = "4.3.1"
anyhow = { version = "1.0.71", features = ["backtrace"] }
askama = "0.12.0"
async-trait = "0.1.68"
async_once = "0.2.6"
bb8 = "0.8.0"
celery = "0.5.3"
chrono = "0.4.24"
clap = { version = "4.2.7", features = ["derive"] }
dataloader = "0.16.0"
debug-ignore = "1.0.5"
diesel = { version = "2.0.4", features = [
"postgres",
"chrono",
"r2d2",
"uuid",
] }
env_logger = "0.10.0"
envconfig = "0.10.0"
git2 = "0.17.1"
gritea = "0.1.8"
hex-simd = "0.8.0"
http = "0.2.9"
http-auth-basic = "0.3.3"
juniper = { version = "0.15.11", features = ["uuid"] }
juniper_actix = "0.4.0"
lazy_static = "1.4.0"
log = "0.4.17"
ring = "0.16.20"
serde = { version = "1.0.160", features = ["derive"] }
serde_json = "1.0.96"
stdext = "0.3.1"
tokio = { version = "1.28.0", features = ["full"] }
url = "2.3.1"
urlencoding = "2.1.2"
uuid-simd = "0.8.0"
uuidv7 = { version = "1.3.2", package = "uuid", features = ["serde"] }
[target.'cfg(not(target_env = "msvc"))'.dependencies]
tikv-jemallocator = "0.5"

81
backend/Dockerfile Normal file
View file

@ -0,0 +1,81 @@
# FROM docker.io/lukemathwalker/cargo-chef:latest-rust-1.69.0 as mold
# SHELL ["/bin/bash", "-o", "pipefail", "-c"]
# WORKDIR /tmp
# ARG MOLD_VERSION="1.11.0"
# RUN wget -qO- https://github.com/rui314/mold/archive/refs/tags/v${MOLD_VERSION}.tar.gz | tar zxf -
# WORKDIR /tmp/mold-${MOLD_VERSION}/build
# RUN ../install-build-deps.sh \
# && cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_COMPILER=c++ .. \
# && cmake --build . -j "$(nproc)" \
# && cmake --install .
FROM docker.io/lukemathwalker/cargo-chef:latest-rust-1.69.0 as chef
SHELL ["/bin/bash", "-o", "pipefail", "-c"]
# hadolint ignore=DL3009
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
lsb-release=11.1.0 \
wget=1.21-1+deb11u1 \
software-properties-common=0.96.20.2-2.1 \
gnupg=2.2.27-2+deb11u2 \
clang=1:11.0-51+nmu5
WORKDIR /tmp
ARG MOLD_VERSION="1.11.0"
RUN wget -qO- https://github.com/rui314/mold/releases/download/v${MOLD_VERSION}/mold-${MOLD_VERSION}-x86_64-linux.tar.gz | tar xzf - \
&& cp -RT ./mold-${MOLD_VERSION}-x86_64-linux /usr \
&& rm -rf ./mold-${MOLD_VERSION}-x86_64-linux
WORKDIR /
FROM chef as diesel
RUN cargo install diesel_cli --version 2.0.1 --no-default-features --features postgres
FROM chef as planner
WORKDIR /usr/src/gitea_pages
RUN mkdir -p ./src/bin && touch ./src/main.rs
COPY ./Cargo.toml ./Cargo.lock ./
RUN cargo chef prepare --recipe-path recipe.json
FROM chef as builder
WORKDIR /usr/src/gitea_pages
COPY ./.cargo ./.cargo
COPY --from=planner /usr/src/gitea_pages/recipe.json .
RUN cargo chef cook --release --recipe-path recipe.json
COPY --from=planner /usr/src/gitea_pages/Cargo.toml /usr/src/gitea_pages/Cargo.lock ./
# RUN cargo build --release --frozen --offline
COPY ./assets ./assets
COPY ./templates ./templates
COPY ./src ./src
RUN cargo build --release --frozen --offline
FROM docker.io/debian:bullseye-slim as runner
LABEL maintainer="Dominic Grimm <dominic@dergrimm.net>" \
org.opencontainers.image.description="Gitea Pages" \
org.opencontainers.image.licenses="GPLv3" \
org.opencontainers.image.source="https://git.dergrimm.net/dergrimm/gitea_pages" \
org.opencontainers.image.url="https://git.dergrimm.net/dergrimm/gitea_pages"
SHELL ["/bin/bash", "-o", "pipefail", "-c"]
RUN apt-get update && \
apt-get install --no-install-recommends -y \
libpq5=13.10-0+deb11u1 \
git=1:2.30.2-1+deb11u2 \
netcat=1.10-46 \
ca-certificates=20210119 \
wget=1.21-1+deb11u1 && \
wget -qO- https://get.docker.com/ | sh && \
apt-get clean && \
apt-get autoremove -y && \
rm -rf /var/lib/apt/lists/* && \
rm -rf /var/lib/apt/ && \
rm -rf /var/lib/dpkg/ && \
rm -rf /var/lib/cache/ && \
rm -rf /var/lib/log/
WORKDIR /usr/local/bin
COPY --from=diesel /usr/local/cargo/bin/diesel .
WORKDIR /opt/gitea_pages
RUN wget -q --show-progress https://raw.githubusercontent.com/vishnubob/wait-for-it/81b1373f17855a4dc21156cfe1694c31d7d1792e/wait-for-it.sh && \
chmod +x wait-for-it.sh
COPY ./run.sh ./migrate.sh ./
RUN chmod +x ./run.sh ./migrate.sh
COPY ./migrations ./migrations
COPY --from=builder /usr/src/gitea_pages/target/release/gitea_pages ./bin/gitea_pages
EXPOSE 8080 8081

8
backend/assets/logo.txt Normal file
View file

@ -0,0 +1,8 @@
_ _
(_) |
__ _ _| |_ ___ __ _ _ __ __ _ __ _ ___ ___
/ _` | | __/ _ \/ _` | | '_ \ / _` |/ _` |/ _ \/ __|
| (_| | | || __/ (_| | | |_) | (_| | (_| | __/\__ \
\__, |_|\__\___|\__,_| | .__/ \__,_|\__, |\___||___/
__/ | | | __/ |
|___/ |_| |___/

10
backend/migrate.sh Normal file
View file

@ -0,0 +1,10 @@
#!/usr/bin/env sh
# -*- coding: utf-8 -*-
set -e
DATABASE_URL="$PAGES_DB_URL" diesel migration run \
--migration-dir ./migrations \
--locked-schema
while true; do nc -lv 8881; done

View file

@ -0,0 +1,3 @@
DROP TABLE repositories;
DROP TABLE users;

View file

@ -0,0 +1,17 @@
CREATE EXTENSION IF NOT EXISTS pgcrypto;
CREATE TABLE users (
id uuid PRIMARY KEY DEFAULT GEN_RANDOM_UUID(),
name text NOT NULL UNIQUE,
created_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at timestamptz
);
CREATE TABLE repositories (
id uuid PRIMARY KEY DEFAULT GEN_RANDOM_UUID(),
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
name text NOT NULL,
created_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at timestamptz,
UNIQUE (user_id, name)
);

8
backend/run.sh Normal file
View file

@ -0,0 +1,8 @@
#!/usr/bin/env sh
# -*- coding: utf-8 -*-
set -e
./wait-for-it.sh migration_runner:8881 --strict -- echo "Migrations were applied"
RUST_BACKTRACE=1 RUST_LOG=info ./bin/gitea_pages "$1"

View file

@ -0,0 +1,57 @@
use dataloader::non_cached::Loader;
use juniper::FieldResult;
use juniper::IntoFieldError;
use uuid_simd::UuidExt;
use uuidv7::Uuid;
use crate::{
api::{loaders, Error},
db, worker,
};
#[derive(Clone)]
pub struct Loaders {
pub user: loaders::user::UserLoader,
pub repository: loaders::repository::RepositoryLoader,
}
impl Default for Loaders {
fn default() -> Self {
Self {
user: Loader::new(loaders::user::UserBatcher)
.with_yield_count(loaders::user::YIELD_COUNT),
repository: Loader::new(loaders::repository::RepositoryBatcher)
.with_yield_count(loaders::repository::YIELD_COUNT),
}
}
}
pub struct Context {
pub db_pool: db::Pool,
pub worker_pool: worker::Pool,
pub loaders: Loaders,
pub logged_in: bool,
}
impl Context {
pub fn get_db_conn(&self) -> FieldResult<db::PoolConnection> {
self.db_pool
.get()
.map_or(Err(Error::Internal.into_field_error()), Ok)
}
pub async fn get_worker_conn(
&self,
) -> FieldResult<bb8::PooledConnection<worker::ConnectionManager>> {
self.worker_pool
.get()
.await
.map_or(Err(Error::Internal.into_field_error()), Ok)
}
pub fn parse_uuid(id: &[u8]) -> FieldResult<Uuid> {
Uuid::parse(id).map_err(|_| Error::InvalidUuid.into_field_error())
}
}
impl juniper::Context for Context {}

99
backend/src/api/error.rs Normal file
View file

@ -0,0 +1,99 @@
use juniper::{graphql_value, FieldError, FieldResult, IntoFieldError, ScalarValue};
pub enum Error {
Internal,
DoesNotExist,
InvalidUuid,
InvalidCredentials,
Unauthenticated,
RepoAlreadyExists,
ExternalRepoDoesNotExist,
RepoPullBranchDoesNotExist,
}
impl<S: ScalarValue> IntoFieldError<S> for Error {
fn into_field_error(self) -> FieldError<S> {
match self {
Self::Internal => FieldError::new(
"Internal server error",
graphql_value!({
"type": "INTERNAL"
}),
),
Self::DoesNotExist => FieldError::new(
"Record does not exist",
graphql_value!({
"type": "DOES_NOT_EXIST"
}),
),
Self::InvalidUuid => FieldError::new(
"Invalid UUID",
graphql_value!({
"type": "INVALID_UUID",
}),
),
Self::InvalidCredentials => FieldError::new(
"Invalid credentials",
graphql_value!({
"type": "INVALID_CREDENTIALS",
}),
),
Self::Unauthenticated => FieldError::new(
"Unauthenticated",
graphql_value!({
"type": "UNAUTHENTICATED",
}),
),
Self::RepoAlreadyExists => FieldError::new(
"Repository already exists",
graphql_value!({
"type": "REPO_ALREADY_EXISTS",
}),
),
Self::ExternalRepoDoesNotExist => FieldError::new(
"Repository does not exist on Git server",
graphql_value!({
"type": "EXTERNAL_REPO_DOES_NOT_EXIST",
}),
),
Self::RepoPullBranchDoesNotExist => FieldError::new(
"Repository does not have pages branch",
graphql_value!({
"type": "REPO_PULL_BRANCH_DOES_NOT_EXIST",
}),
),
}
}
}
pub trait QueryResultIntoFieldResult<T> {
fn into_field_result(self) -> FieldResult<T>;
}
impl<T> QueryResultIntoFieldResult<T> for diesel::QueryResult<T> {
fn into_field_result(self) -> FieldResult<T> {
// match self {
// Ok(x) => Ok(x),
// Err(_) => Err(Error::Internal.into_field_error()),
// }
self.map_err(|_| Error::Internal.into_field_error())
}
}
pub trait AsyncResultIntoFieldResult<T> {
fn into_field_result(self) -> FieldResult<T>;
}
impl AsyncResultIntoFieldResult<celery::task::AsyncResult>
for Result<celery::task::AsyncResult, celery::error::CeleryError>
{
fn into_field_result(self) -> FieldResult<celery::task::AsyncResult> {
// match self {
// Ok(x) => Ok(x),
// Err(_) => Err(Error::Internal.into_field_error()),
// }
self.map_err(|_| Error::Internal.into_field_error())
}
}

View file

@ -0,0 +1,77 @@
use async_trait::async_trait;
use std::clone::Clone;
use std::fmt::Debug;
use std::hash::Hash;
use std::io::{Error, ErrorKind};
pub mod repository;
pub mod user;
#[async_trait]
pub trait TryOptionLoad<K, V>: Clone
where
K: Eq + Hash + Clone + Debug + Send + Sync,
V: Clone + Debug + Send,
{
async fn try_option_load(&self, key: K) -> Result<Option<V>, Error>;
}
#[async_trait]
impl<K, V, F> TryOptionLoad<K, V> for dataloader::non_cached::Loader<K, V, F>
where
K: Eq + Hash + Clone + Debug + Send + Sync,
V: Clone + Debug + Send,
F: dataloader::BatchFn<K, V> + Send + Sync,
{
async fn try_option_load(&self, key: K) -> Result<Option<V>, Error> {
async fn internal_try_option_load<K, V, F>(
loader: &dataloader::non_cached::Loader<K, V, F>,
key: K,
) -> Result<Option<V>, Error>
where
K: Eq + Hash + Clone + Debug + Send + Sync,
V: Clone + Debug + Send,
F: dataloader::BatchFn<K, V> + Send + Sync,
{
match loader.try_load(key).await {
Ok(x) => Ok(Some(x)),
Err(e) => match e.kind() {
ErrorKind::NotFound => Ok(None),
_ => Err(e),
},
}
}
internal_try_option_load(self, key).await
}
}
#[async_trait]
impl<K, V, F> TryOptionLoad<K, V> for dataloader::cached::Loader<K, V, F>
where
K: Eq + Hash + Clone + Debug + Send + Sync,
V: Clone + Debug + Send,
F: dataloader::BatchFn<K, V> + Send + Sync,
{
async fn try_option_load(&self, key: K) -> Result<Option<V>, Error> {
async fn internal_try_option_load<K, V, F>(
loader: &dataloader::cached::Loader<K, V, F>,
key: K,
) -> Result<Option<V>, Error>
where
K: Eq + Hash + Clone + Debug + Send + Sync,
V: Clone + Debug + Send,
F: dataloader::BatchFn<K, V> + Send + Sync,
{
match loader.try_load(key).await {
Ok(x) => Ok(Some(x)),
Err(e) => match e.kind() {
ErrorKind::NotFound => Ok(None),
_ => Err(e),
},
}
}
internal_try_option_load(self, key).await
}
}

View file

@ -0,0 +1,42 @@
use async_trait::async_trait;
use dataloader::non_cached::Loader;
use dataloader::BatchFn;
use diesel::prelude::*;
use std::collections::HashMap;
use uuidv7::Uuid;
use crate::{api::models, db};
pub struct RepositoryBatcher;
#[async_trait]
impl BatchFn<Uuid, models::repository::Repository> for RepositoryBatcher {
async fn load(&mut self, keys: &[Uuid]) -> HashMap<Uuid, models::repository::Repository> {
let db_conn = &mut db::POOL.get().unwrap();
let mut map = HashMap::new();
for row in db::schema::repositories::table
.select((
db::schema::repositories::id,
db::schema::repositories::user_id,
db::schema::repositories::name,
))
.filter(db::schema::repositories::id.eq_any(keys))
.load::<(Uuid, Uuid, String)>(db_conn)
.unwrap()
{
let row: (Uuid, Uuid, String) = row;
let data = models::repository::Repository {
id: row.0,
user_id: row.1,
name: row.2,
};
map.insert(data.id, data);
}
map
}
}
pub type RepositoryLoader = Loader<Uuid, models::repository::Repository, RepositoryBatcher>;
pub const YIELD_COUNT: usize = 100;

View file

@ -0,0 +1,37 @@
use async_trait::async_trait;
use dataloader::non_cached::Loader;
use dataloader::BatchFn;
use diesel::prelude::*;
use std::collections::HashMap;
use uuidv7::Uuid;
use crate::{api::models, db};
pub struct UserBatcher;
#[async_trait]
impl BatchFn<Uuid, models::user::User> for UserBatcher {
async fn load(&mut self, keys: &[Uuid]) -> HashMap<Uuid, models::user::User> {
let db_conn = &mut db::POOL.get().unwrap();
let mut map = HashMap::new();
for row in db::schema::users::table
.select((db::schema::users::id, db::schema::users::name))
.filter(db::schema::users::id.eq_any(keys))
.load::<(Uuid, String)>(db_conn)
.unwrap()
{
let row: (Uuid, String) = row;
let data = models::user::User {
id: row.0,
name: row.1,
};
map.insert(data.id, data);
}
map
}
}
pub type UserLoader = Loader<Uuid, models::user::User, UserBatcher>;
pub const YIELD_COUNT: usize = 100;

227
backend/src/api/mod.rs Normal file
View file

@ -0,0 +1,227 @@
use diesel::prelude::*;
use gritea::client::Gritea;
use juniper::{graphql_object, EmptySubscription, FieldResult, IntoFieldError, RootNode};
use uuidv7::Uuid;
use crate::{db, gritea_ext::GriteaExt, worker, CONFIG};
pub mod context;
pub mod error;
pub mod loaders;
pub mod models;
pub mod scalars;
pub use context::Context;
pub use error::{AsyncResultIntoFieldResult, Error, QueryResultIntoFieldResult};
use loaders::TryOptionLoad;
pub struct Query;
#[graphql_object(context = Context)]
impl Query {
fn ping() -> &'static str {
"pong"
}
fn verify_login(username: String, password: String) -> bool {
username == *CONFIG.user && password == *CONFIG.password
}
async fn user(context: &Context, id: scalars::Uuid) -> FieldResult<models::user::User> {
match context.loaders.user.try_option_load(*id).await {
Ok(Some(user)) => Ok(user),
Ok(None) => Err(Error::DoesNotExist.into_field_error()),
Err(_) => Err(Error::Internal.into_field_error()),
}
}
async fn user_by_name(context: &Context, name: String) -> FieldResult<models::user::User> {
let db_conn = &mut context.get_db_conn()?;
let id = match db::schema::users::table
.select(db::schema::users::id)
.filter(db::schema::users::name.eq(name))
.first::<Uuid>(db_conn)
.optional()
.into_field_result()?
{
Some(x) => x,
None => return Err(Error::DoesNotExist.into_field_error()),
};
context
.loaders
.user
.try_load(id)
.await
.map_err(|_| Error::Internal.into_field_error())
}
async fn users(context: &Context) -> FieldResult<Vec<models::user::User>> {
let db_conn = &mut context.get_db_conn()?;
let ids = db::schema::users::table
.select(db::schema::users::id)
.load::<Uuid>(db_conn)
.into_field_result()?;
context.loaders.user.try_load_many(ids).await.map_or_else(
|_| Err(Error::Internal.into_field_error()),
|x| Ok(x.into_values().collect()),
)
}
async fn repository(
context: &Context,
id: scalars::Uuid,
) -> FieldResult<models::repository::Repository> {
match context.loaders.repository.try_option_load(*id).await {
Ok(Some(user)) => Ok(user),
Ok(None) => Err(Error::DoesNotExist.into_field_error()),
Err(_) => Err(Error::Internal.into_field_error()),
}
}
async fn repositories(context: &Context) -> FieldResult<Vec<models::repository::Repository>> {
let db_conn = &mut context.get_db_conn()?;
let ids = db::schema::repositories::table
.select(db::schema::repositories::id)
.load::<Uuid>(db_conn)
.into_field_result()?;
context
.loaders
.repository
.try_load_many(ids)
.await
.map_or_else(
|_| Err(Error::Internal.into_field_error()),
|x| Ok(x.into_values().collect()),
)
}
}
pub struct Mutation;
#[graphql_object(context = Context)]
impl Mutation {
async fn create_repository(
context: &Context,
input: models::repository::CreateRepositoryInput,
) -> FieldResult<models::repository::Repository> {
if !context.logged_in {
return Err(Error::Unauthenticated.into_field_error());
}
let db_conn = &mut context.get_db_conn()?;
let user_id = db::schema::users::table
.select(db::schema::users::id)
.filter(db::schema::users::name.eq(&input.user))
.first::<Uuid>(db_conn)
.optional()
.into_field_result()?;
if let Some(id) = user_id {
if diesel::select(diesel::dsl::exists(
db::schema::repositories::table
.filter(db::schema::repositories::user_id.eq(id))
.filter(db::schema::repositories::name.eq(&input.name)),
))
.get_result::<bool>(db_conn)
.into_field_result()?
{
return Err(Error::RepoAlreadyExists.into_field_error());
}
}
let escaped_user = urlencoding::encode(&input.user);
let escaped_name = urlencoding::encode(&input.name);
match Gritea::builder(&CONFIG.gitea_url)
.token(&*CONFIG.gitea_api_token)
.build()
{
Ok(client) => {
let repo = match client.get_repo(&escaped_user, &escaped_name).await {
Ok(x) => x,
Err(_) => return Err(Error::ExternalRepoDoesNotExist.into_field_error()),
};
if repo.private {
return Err(Error::ExternalRepoDoesNotExist.into_field_error());
}
let branches = match client.get_repo_branches(&escaped_user, &escaped_name).await {
Ok(x) => x,
Err(_) => return Err(Error::Internal.into_field_error()),
};
if !branches
.into_iter()
.any(|x| x.name == CONFIG.gitea_pull_branch)
{
return Err(Error::RepoPullBranchDoesNotExist.into_field_error());
}
}
Err(_) => return Err(Error::Internal.into_field_error()),
}
let user_id = match user_id {
Some(x) => x,
None => diesel::insert_into(db::schema::users::table)
.values(db::models::NewUser { name: &input.user })
.returning(db::schema::users::id)
.get_result::<Uuid>(db_conn)
.into_field_result()?,
};
let id = diesel::insert_into(db::schema::repositories::table)
.values(db::models::NewRepository {
user_id,
name: &input.name,
})
.returning(db::schema::repositories::id)
.get_result::<Uuid>(db_conn)
.into_field_result()?;
let worker_conn = context.get_worker_conn().await?;
worker_conn
.send_task(worker::get_repo::get_repo::new(id))
.await
.into_field_result()?;
context
.loaders
.repository
.try_load(id)
.await
.map_err(|_| Error::Internal.into_field_error())
}
async fn delete_repository(context: &Context, id: scalars::Uuid) -> FieldResult<bool> {
if !context.logged_in {
return Err(Error::Unauthenticated.into_field_error());
}
let db_conn = &mut context.get_db_conn()?;
if diesel::select(diesel::dsl::not(diesel::dsl::exists(
db::schema::repositories::table.filter(db::schema::repositories::id.eq(*id)),
)))
.get_result::<bool>(db_conn)
.into_field_result()?
{
return Err(Error::DoesNotExist.into_field_error());
}
let worker_conn = context.get_worker_conn().await?;
worker_conn
.send_task(worker::delete_repo::delete_repo::new(*id))
.await
.into_field_result()?;
Ok(true)
}
}
pub type Schema = RootNode<'static, Query, Mutation, EmptySubscription<Context>>;
pub fn schema() -> Schema {
Schema::new(Query, Mutation, EmptySubscription::new())
}

View file

@ -0,0 +1,2 @@
pub mod repository;
pub mod user;

View file

@ -0,0 +1,62 @@
use juniper::{graphql_object, FieldResult, GraphQLInputObject, IntoFieldError};
use uuidv7::Uuid;
use crate::{
api::{models, scalars, Context, Error},
CONFIG,
};
#[derive(Clone, Debug)]
pub struct Repository {
pub id: Uuid,
pub user_id: Uuid,
pub name: String,
}
#[graphql_object(context = Context)]
impl Repository {
fn id(&self) -> scalars::Uuid {
scalars::Uuid(self.id)
}
async fn user(&self, context: &Context) -> FieldResult<models::user::User> {
context
.loaders
.user
.try_load(self.user_id)
.await
.map_err(|_| Error::Internal.into_field_error())
}
fn name(&self) -> &str {
&self.name
}
async fn url(&self, context: &Context, scheme: Option<bool>) -> FieldResult<String> {
let user_name = context
.loaders
.user
.try_load(self.user_id)
.await
.map_err(|_| Error::Internal.into_field_error())?
.name;
Ok(format!(
"{}{}.{}/{}",
if scheme.unwrap_or(true) {
"https://"
} else {
""
},
user_name,
CONFIG.domain,
self.name
))
}
}
#[derive(GraphQLInputObject)]
pub struct CreateRepositoryInput {
pub user: String,
pub name: String,
}

View file

@ -0,0 +1,47 @@
use diesel::prelude::*;
use juniper::{graphql_object, FieldResult, IntoFieldError};
use uuidv7::Uuid;
use crate::{
api::{models, scalars, Context, Error, QueryResultIntoFieldResult},
db,
};
#[derive(Clone, Debug)]
pub struct User {
pub id: Uuid,
pub name: String,
}
#[graphql_object(context = Context)]
impl User {
fn id(&self) -> scalars::Uuid {
scalars::Uuid(self.id)
}
fn name(&self) -> &str {
&self.name
}
async fn repositories(
&self,
context: &Context,
) -> FieldResult<Vec<models::repository::Repository>> {
let db_conn = &mut context.get_db_conn()?;
let ids = db::schema::repositories::table
.select(db::schema::repositories::id)
.filter(db::schema::repositories::user_id.eq(self.id))
.load::<Uuid>(db_conn)
.into_field_result()?;
context
.loaders
.repository
.try_load_many(ids)
.await
.map_or_else(
|_| Err(Error::Internal.into_field_error()),
|x| Ok(x.into_values().collect()),
)
}
}

View file

@ -0,0 +1,3 @@
pub mod uuid;
pub use uuid::Uuid;

View file

@ -0,0 +1,39 @@
use std::ops::Deref;
type Value = uuidv7::Uuid;
pub struct Uuid(pub Value);
#[juniper::graphql_scalar(name = "UUID", description = "UUID encoded as a string")]
impl<S> GraphQLScalar for Uuid
where
S: juniper::ScalarValue,
{
fn resolve(&self) -> juniper::Value {
juniper::Value::scalar(self.0.to_string())
}
fn from_input_value(value: &juniper::InputValue) -> Option<Uuid> {
value
.as_string_value()
.and_then(|s| {
use uuid_simd::UuidExt;
use uuidv7::Uuid;
Uuid::parse(s.as_bytes()).ok()
})
.map(Uuid)
}
fn from_str<'a>(value: juniper::ScalarToken<'a>) -> juniper::ParseScalarResult<'a, S> {
<String as juniper::ParseScalarValue<S>>::from_str(value)
}
}
impl Deref for Uuid {
type Target = Value;
fn deref(&self) -> &Self::Target {
&self.0
}
}

69
backend/src/config.rs Normal file
View file

@ -0,0 +1,69 @@
use anyhow::{bail, Result};
use debug_ignore::DebugIgnore;
use envconfig::Envconfig;
use lazy_static::lazy_static;
use url::Url;
#[derive(Envconfig, Debug)]
pub struct Config {
#[envconfig(from = "PAGES_DB_URL")]
pub db_url: DebugIgnore<String>,
#[envconfig(from = "PAGES_AMQP_URL")]
pub amqp_url: DebugIgnore<String>,
#[envconfig(from = "PAGES_USER")]
pub user: String,
#[envconfig(from = "PAGES_PASSWORD")]
pub password: DebugIgnore<String>,
#[envconfig(from = "PAGES_GITEA_URL")]
pub gitea_url: String,
#[envconfig(from = "PAGES_GITEA_API_TOKEN")]
pub gitea_api_token: DebugIgnore<String>,
#[envconfig(from = "PAGES_GITEA_SECRET")]
pub gitea_secret: DebugIgnore<String>,
#[envconfig(from = "PAGES_GITEA_PULL_URL")]
pub gitea_pull_url: Url,
#[envconfig(from = "PAGES_GITEA_PULL_BRANCH")]
pub gitea_pull_branch: String,
#[envconfig(from = "PAGES_NGINX_CONFIG_DIR")]
pub nginx_config_dir: String,
#[envconfig(from = "PAGES_REPOS_DIR")]
pub repos_dir: String,
#[envconfig(from = "PAGES_DOMAIN")]
pub domain: String,
}
pub const PASSWORD_MIN_LEN: usize = 64;
impl Config {
pub fn validate(&self) -> Result<()> {
if self.password.len() < PASSWORD_MIN_LEN {
bail!(
"Password is too short: {} < {}",
self.password.len(),
PASSWORD_MIN_LEN
);
}
Ok(())
}
}
#[derive(Debug)]
pub struct DynConfig {
pub cloudflare_zone_name: String,
}
lazy_static! {
pub static ref CONFIG: Config = Config::init_from_env().unwrap();
}

29
backend/src/db/mod.rs Normal file
View file

@ -0,0 +1,29 @@
use anyhow::Result;
use diesel::pg::PgConnection;
use diesel::prelude::*;
use diesel::r2d2::{ConnectionManager, PooledConnection};
use lazy_static::lazy_static;
use crate::CONFIG;
pub mod models;
pub mod schema;
pub type Pool = diesel::r2d2::Pool<ConnectionManager<PgConnection>>;
pub type Connection = PgConnection;
pub type PoolConnection = PooledConnection<ConnectionManager<PgConnection>>;
pub fn establish_connection() -> ConnectionResult<PgConnection> {
use diesel::Connection;
PgConnection::establish(&CONFIG.db_url)
}
pub fn pool() -> Result<Pool> {
Ok(diesel::r2d2::Pool::builder()
.build(ConnectionManager::<PgConnection>::new(&*CONFIG.db_url))?)
}
lazy_static! {
pub static ref POOL: Pool = pool().unwrap();
}

37
backend/src/db/models.rs Normal file
View file

@ -0,0 +1,37 @@
use chrono::prelude::*;
use diesel::prelude::*;
use uuidv7::Uuid;
use crate::db::schema;
#[derive(Identifiable, Queryable, Debug)]
#[diesel(table_name = schema::users)]
pub struct User {
pub id: Uuid,
pub name: String,
pub created_at: DateTime<Utc>,
pub updated_at: Option<DateTime<Utc>>,
}
#[derive(Insertable, Debug)]
#[diesel(table_name = schema::users)]
pub struct NewUser<'a> {
pub name: &'a str,
}
#[derive(Identifiable, Queryable, Debug)]
#[diesel(table_name = schema::repositories)]
pub struct Repository {
pub id: Uuid,
pub user_id: Uuid,
pub name: String,
pub created_at: DateTime<Utc>,
pub updated_at: Option<DateTime<Utc>>,
}
#[derive(Insertable, Debug)]
#[diesel(table_name = schema::repositories)]
pub struct NewRepository<'a> {
pub user_id: Uuid,
pub name: &'a str,
}

18
backend/src/db/schema.rs Normal file
View file

@ -0,0 +1,18 @@
diesel::table! {
users {
id -> Uuid,
name -> Text,
created_at -> Timestamptz,
updated_at -> Nullable<Timestamptz>,
}
}
diesel::table! {
repositories {
id -> Uuid,
user_id -> Uuid,
name -> Text,
created_at -> Timestamptz,
updated_at -> Nullable<Timestamptz>,
}
}

68
backend/src/gritea_ext.rs Normal file
View file

@ -0,0 +1,68 @@
use async_trait::async_trait;
use chrono::prelude::*;
use gritea::{
client::{resp_json, Gritea},
Result,
};
use http::Method;
use serde::Deserialize;
#[derive(Deserialize, Debug)]
pub struct PayloadUser {
pub email: String,
pub name: String,
pub username: String,
}
#[derive(Deserialize, Debug)]
pub struct PayloadCommitVerification {
pub payload: String,
pub reason: String,
pub signature: String,
pub signer: Option<PayloadUser>,
pub verified: bool,
}
#[derive(Deserialize, Debug)]
pub struct PayloadCommit {
pub added: Option<Vec<String>>,
pub author: PayloadUser,
pub committer: PayloadUser,
pub id: String,
pub message: String,
pub modified: Option<Vec<String>>,
pub removed: Option<Vec<String>>,
pub timestamp: DateTime<Utc>,
pub url: String,
pub verfification: Option<PayloadCommitVerification>,
}
#[derive(Deserialize, Debug)]
pub struct Branch {
pub commit: PayloadCommit,
pub effective_branch_protection_name: String,
pub enable_status_check: bool,
pub name: String,
pub protected: bool,
pub required_approvals: i64,
pub status_check_contexts: Vec<String>,
pub user_can_merge: bool,
pub user_can_push: bool,
}
#[async_trait]
pub trait GriteaExt {
async fn get_repo_branches(&self, owner: &str, repo: &str) -> Result<Vec<Branch>>;
}
#[async_trait]
impl GriteaExt for Gritea {
async fn get_repo_branches(&self, owner: &str, repo: &str) -> Result<Vec<Branch>> {
let resp = self
.request(Method::GET, &format!("repos/{}/{}/branches", owner, repo))?
.send()
.await?;
resp_json(resp, "get repo branches failed").await
}
}

35
backend/src/lib.rs Normal file
View file

@ -0,0 +1,35 @@
use anyhow::Result;
use askama::Template;
use std::fs;
pub mod api;
pub mod config;
pub mod db;
pub mod gritea_ext;
pub mod templates;
pub mod worker;
pub use config::CONFIG;
pub const ASCII_LOGO: &str = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/assets/logo.txt"));
pub fn init() -> Result<()> {
println!("{}\n", ASCII_LOGO);
CONFIG.validate()?;
Ok(())
}
pub fn init_nginx() -> Result<()> {
let config = templates::NginxConfig {
domain_segments: CONFIG.domain.split('.').collect(),
}
.render()?;
log::info!("Updating Nginx config");
fs::write(
format!("{}/gitea_pages.conf", CONFIG.nginx_config_dir),
config,
)?;
Ok(())
}

221
backend/src/main.rs Normal file
View file

@ -0,0 +1,221 @@
#[cfg(not(target_env = "msvc"))]
use tikv_jemallocator::Jemalloc;
#[cfg(not(target_env = "msvc"))]
#[global_allocator]
static GLOBAL: Jemalloc = Jemalloc;
use anyhow::Result;
use clap::{Parser, Subcommand};
use diesel::prelude::*;
use uuidv7::Uuid;
use gitea_pages::{api, db, init, init_nginx, worker, CONFIG};
#[derive(Debug, Parser)]
#[clap(author, version, about, long_about = None)]
struct Cli {
#[clap(subcommand)]
commands: Commands,
}
#[derive(Debug, Subcommand)]
enum Commands {
#[clap(about = "Starts Celery worker")]
Worker,
#[clap(about = "Starts beat for Celery worker")]
Beat,
#[clap(about = "Starts API")]
Api,
}
#[tokio::main]
async fn main() -> Result<()> {
let args = Cli::parse();
env_logger::init();
init()?;
match args.commands {
Commands::Worker => {
init_nginx()?;
let worker_conn = &worker::POOL.get().await.get().await?;
worker_conn.display_pretty().await;
worker_conn.consume_from(&[worker::QUEUE_NAME]).await?;
}
Commands::Beat => {
worker::beat().await?.start().await?;
}
Commands::Api => {
use actix_cors::Cors;
use actix_web::{
http::header, middleware, web, App, HttpRequest, HttpResponse, HttpServer,
};
use anyhow::Result;
use juniper_actix::graphql_handler;
use serde::Deserialize;
use std::str::FromStr;
async fn not_found() -> &'static str {
"Not found!"
}
#[derive(Deserialize, Debug)]
struct Owner {
username: String,
}
#[derive(Deserialize, Debug)]
struct Repository {
owner: Owner,
name: String,
}
#[derive(Deserialize, Debug)]
struct Payload {
repository: Repository,
}
async fn webhook(req: HttpRequest, body: web::Bytes) -> HttpResponse {
if let Some(content_type) = req.headers().get(header::CONTENT_TYPE) {
if content_type.as_bytes() != b"application/json" {
return HttpResponse::BadRequest()
.body("Content-Type not application/json");
}
}
let key =
ring::hmac::Key::new(ring::hmac::HMAC_SHA256, CONFIG.gitea_secret.as_bytes());
let signature = match req.headers().get("X-Gitea-Signature") {
Some(x) => x,
None => return HttpResponse::BadRequest().body("X-Gitea-Signature not given"),
};
let mut tag = vec![0u8; signature.len() / 2];
if hex_simd::decode(signature.as_bytes(), hex_simd::Out::from_slice(&mut tag))
.is_err()
{
return HttpResponse::BadRequest().body("Could not decode signature");
}
if ring::hmac::verify(&key, body.as_ref(), &tag).is_err() {
return HttpResponse::BadRequest().body("Invalid signature");
}
let payload = match serde_json::from_slice::<Payload>(body.as_ref()) {
Ok(x) => x,
Err(_) => return HttpResponse::BadRequest().body("Payload has invalid JSON"),
};
let db_conn = &mut match db::POOL.get() {
Ok(x) => x,
Err(_) => return HttpResponse::InternalServerError().finish(),
};
let user_id = match db::schema::users::table
.select(db::schema::users::id)
.filter(db::schema::users::name.eq(payload.repository.owner.username))
.first::<Uuid>(db_conn)
.optional()
{
Ok(x) => match x {
Some(y) => y,
None => {
return HttpResponse::BadRequest().body("Repository is not allowed")
}
},
Err(_) => return HttpResponse::InternalServerError().finish(),
};
let repo_id = match db::schema::repositories::table
.select(db::schema::repositories::id)
.filter(db::schema::repositories::user_id.eq(user_id))
.filter(db::schema::repositories::name.eq(payload.repository.name))
.first::<Uuid>(db_conn)
.optional()
{
Ok(x) => match x {
Some(y) => y,
None => {
return HttpResponse::BadRequest().body("Repository is not allowed")
}
},
Err(_) => return HttpResponse::InternalServerError().finish(),
};
let worker_conn = match worker::POOL.get().await.get().await {
Ok(x) => x,
Err(_) => return HttpResponse::InternalServerError().finish(),
};
if worker_conn
.send_task(worker::get_repo::get_repo::new(repo_id))
.await
.is_err()
{
return HttpResponse::InternalServerError().finish();
}
HttpResponse::Ok().finish()
}
async fn graphql_route(
req: HttpRequest,
payload: web::Payload,
schema: web::Data<api::Schema>,
) -> Result<HttpResponse, actix_web::Error> {
let logged_in = match req
.headers()
.get(header::AUTHORIZATION)
.and_then(|x| x.to_str().ok())
{
Some(x) => match http_auth_basic::Credentials::from_str(x) {
Ok(cred) => {
cred.user_id == CONFIG.user && cred.password == *CONFIG.password
}
Err(_) => false,
},
None => false,
};
let context = api::Context {
db_pool: db::POOL.clone(),
worker_pool: worker::POOL.get().await.clone(),
loaders: api::context::Loaders::default(),
logged_in,
};
graphql_handler(&schema, &context, req, payload).await
}
HttpServer::new(move || {
App::new()
.app_data(web::Data::new(api::schema()))
.wrap(middleware::Logger::default())
.wrap(middleware::Compress::default())
.wrap(
Cors::default()
.allow_any_origin()
.allowed_methods(["POST", "GET"])
.allowed_headers([header::AUTHORIZATION, header::ACCEPT])
.allowed_header(header::CONTENT_TYPE)
.supports_credentials()
.max_age(3600),
)
.service(web::resource("/webhook").route(web::post().to(webhook)))
.service(
web::resource("/graphql")
.route(web::post().to(graphql_route))
.route(web::get().to(graphql_route)),
)
.default_service(web::to(not_found))
})
.bind(("0.0.0.0", 8080))?
.run()
.await?;
}
}
Ok(())
}

7
backend/src/templates.rs Normal file
View file

@ -0,0 +1,7 @@
use askama::Template;
#[derive(Template)]
#[template(path = "gitea_pages.conf", escape = "none")]
pub struct NginxConfig<'a> {
pub domain_segments: Vec<&'a str>,
}

View file

@ -0,0 +1,53 @@
use anyhow::Result;
use celery::{error::TaskError, task::TaskResult};
use diesel::prelude::*;
use std::fs;
use uuidv7::Uuid;
use crate::{db, CONFIG};
fn do_task(db_conn: &mut db::Connection, id: Uuid) -> Result<()> {
let (user_id, name) = db::schema::repositories::table
.select((
db::schema::repositories::user_id,
db::schema::repositories::name,
))
.filter(db::schema::repositories::id.eq(id))
.first::<(Uuid, String)>(db_conn)?;
let user_name = db::schema::users::table
.select(db::schema::users::name)
.filter(db::schema::users::id.eq(user_id))
.first::<String>(db_conn)?;
diesel::delete(db::schema::repositories::table.filter(db::schema::repositories::id.eq(id)))
.execute(db_conn)?;
if db::schema::repositories::table
.filter(db::schema::repositories::user_id.eq(user_id))
.count()
.get_result::<i64>(db_conn)?
== 0
{
diesel::delete(db::schema::users::table.filter(db::schema::users::id.eq(user_id)))
.execute(db_conn)?;
fs::remove_dir_all(format!("{}/{}", CONFIG.repos_dir, user_name))?;
} else {
fs::remove_dir_all(format!("{}/{}/{}", CONFIG.repos_dir, user_name, name))?;
}
Ok(())
}
#[celery::task]
pub fn delete_repo(id: Uuid) -> TaskResult<()> {
let db_conn = &mut match db::POOL.get() {
Ok(x) => x,
Err(e) => return Err(TaskError::UnexpectedError(format!("{:?}", e))),
};
if let Err(e) = do_task(db_conn, id) {
return Err(TaskError::UnexpectedError(format!("{:?}", e)));
}
Ok(())
}

View file

@ -0,0 +1,100 @@
use anyhow::{bail, Context, Result};
use celery::{error::TaskError, task::TaskResult};
use diesel::prelude::*;
use std::{fs, path::Path};
use url::Url;
use uuidv7::Uuid;
use crate::{db, CONFIG};
fn get_repo_name(db_conn: &mut db::Connection, id: Uuid) -> Result<(String, String)> {
let (user_id, name) = db::schema::repositories::table
.select((
db::schema::repositories::user_id,
db::schema::repositories::name,
))
.filter(db::schema::repositories::id.eq(id))
.first::<(Uuid, String)>(db_conn)?;
let user_name = db::schema::users::table
.select(db::schema::users::name)
.filter(db::schema::users::id.eq(user_id))
.first::<String>(db_conn)?;
Ok((user_name, name))
}
fn repo_dir(user: &str, repo: &str) -> (String, String, String) {
let parent = format!("{}/{}", CONFIG.repos_dir, user);
let dir = format!("{}/{}", parent, repo);
(parent, dir, format!("{}/{}.git", user, repo))
}
fn do_task(parent_dir: &str, repo_dir: &str, full_name_path: &str) -> Result<()> {
let path = Path::new(repo_dir);
if path.exists() && path.is_dir() {
let repo = git2::Repository::open(repo_dir)?;
repo.find_remote("origin")?
.fetch(&[&CONFIG.gitea_pull_branch], None, None)?;
let fetch_head = repo.find_reference("FETCH_HEAD")?;
let fetch_commit = repo.reference_to_annotated_commit(&fetch_head)?;
let analysis = repo.merge_analysis(&[&fetch_commit])?;
if !analysis.0.is_up_to_date() {
if analysis.0.is_fast_forward() {
let refname = format!("refs/heads/{}", CONFIG.gitea_pull_branch);
let mut reference = repo.find_reference(&refname)?;
reference.set_target(fetch_commit.id(), "Fast-Forward")?;
repo.set_head(&refname)?;
repo.checkout_head(Some(git2::build::CheckoutBuilder::default().force()))?;
} else {
bail!("Fast-forward only!");
}
}
} else {
fs::create_dir_all(parent_dir)?;
let repo = git2::Repository::clone(
Url::parse(CONFIG.gitea_pull_url.as_str())?
.join(full_name_path)?
.as_str(),
repo_dir,
)?;
let (object, reference) =
repo.revparse_ext(&format!("remotes/origin/{}", CONFIG.gitea_pull_branch))?;
repo.checkout_tree(&object, None)?;
match reference {
Some(gref) => repo.set_head(gref.name().context("Could not get ref name")?),
None => repo.set_head_detached(object.id()),
}
.context("Failed to set HEAD")?;
};
Ok(())
}
#[celery::task]
pub async fn get_repo(id: Uuid) -> TaskResult<()> {
let db_conn = &mut match db::POOL.get() {
Ok(x) => x,
Err(e) => return Err(TaskError::UnexpectedError(format!("{:?}", e))),
};
let (user_name, repo_name) = match get_repo_name(db_conn, id) {
Ok(x) => x,
Err(e) => return Err(TaskError::UnexpectedError(format!("{:?}", e))),
};
let (parent_dir, repo_dir, full_name_path) = repo_dir(&user_name, &repo_name);
if let Err(e) = do_task(&parent_dir, &repo_dir, &full_name_path) {
if let Err(err) = fs::remove_dir_all(repo_dir) {
return Err(TaskError::UnexpectedError(format!("{:?}", err)));
}
return Err(TaskError::UnexpectedError(format!("{:?}", e)));
}
Ok(())
}

89
backend/src/worker/mod.rs Normal file
View file

@ -0,0 +1,89 @@
use anyhow::Result;
use async_once::AsyncOnce;
use async_trait::async_trait;
use celery::beat::{Beat, DeltaSchedule, LocalSchedulerBackend};
use celery::prelude::*;
use celery::Celery;
use lazy_static::lazy_static;
use std::sync::Arc;
use std::time::Duration;
use stdext::duration::DurationExt;
pub mod delete_repo;
pub mod get_repo;
pub mod update_repos;
use crate::CONFIG;
pub const QUEUE_NAME: &str = "gitea_pages";
pub async fn app() -> Result<Arc<Celery>, CeleryError> {
celery::app!(
broker = AMQPBroker { &CONFIG.amqp_url },
tasks = [
get_repo::get_repo,
delete_repo::delete_repo,
update_repos::update_repos,
],
task_routes = [
"*" => QUEUE_NAME,
],
prefetch_count = 2,
heartbeat = Some(10)
)
.await
}
pub async fn beat() -> Result<Beat<LocalSchedulerBackend>, BeatError> {
celery::beat!(
broker = AMQPBroker { &CONFIG.amqp_url },
tasks = [
// "cleanup_tokens" => {
// cleanup_tokens::cleanup_tokens,
// schedule = DeltaSchedule::new(Duration::from_hours(1)),
// args = (),
// }
"update_repos" => {
update_repos::update_repos,
schedule = DeltaSchedule::new(Duration::from_days(1)),
args = (),
},
],
task_routes = [
"*" => QUEUE_NAME,
]
)
.await
}
pub type Connection = Arc<Celery>;
pub struct ConnectionManager;
#[async_trait]
impl bb8::ManageConnection for ConnectionManager {
type Connection = Connection;
type Error = CeleryError;
async fn connect(&self) -> Result<Self::Connection, Self::Error> {
app().await
}
async fn is_valid(&self, _conn: &mut Self::Connection) -> Result<(), Self::Error> {
Ok(())
}
fn has_broken(&self, _: &mut Self::Connection) -> bool {
false
}
}
pub type Pool = bb8::Pool<ConnectionManager>;
pub async fn pool() -> Result<Pool> {
Ok(bb8::Pool::builder().build(ConnectionManager).await?)
}
lazy_static! {
pub static ref POOL: AsyncOnce<Pool> = AsyncOnce::new(async { pool().await.unwrap() });
}

View file

@ -0,0 +1,31 @@
use anyhow::Result;
use celery::prelude::*;
use diesel::prelude::*;
use uuidv7::Uuid;
use crate::{db, worker};
async fn do_task() -> Result<()> {
let db_conn = &mut db::POOL.get()?;
let repo_ids = db::schema::repositories::table
.select(db::schema::repositories::id)
.load::<Uuid>(db_conn)?;
let worker_conn = worker::POOL.get().await.get().await?;
for id in repo_ids {
worker_conn
.send_task(worker::get_repo::get_repo::new(id))
.await?;
}
Ok(())
}
#[celery::task]
pub async fn update_repos() -> TaskResult<()> {
if let Err(e) = do_task().await {
return Err(TaskError::UnexpectedError(format!("{:?}", e)));
}
Ok(())
}

View file

@ -0,0 +1,28 @@
map $host $subdomain {
~^(?P<sub>.+)\.{{ domain_segments|join("\\.") }}$ $sub;
}
server {
listen 80;
server_name *.{{ domain_segments|join(".") }};
root /var/www/repos/$subdomain;
location = / {
autoindex on;
}
location / {
try_files $uri $uri/ /index.html;
index index.html index.htm;
if (!-e $request_filename) {
return 404;
}
}
location ~ /\.git {
deny all;
return 404;
}
}

84
config/nginx/nginx.conf Normal file
View file

@ -0,0 +1,84 @@
events {
worker_connections 1024;
}
http {
server_tokens off;
more_clear_headers Server;
include /etc/nginx/mime.types;
default_type application/octet-stream;
sendfile on;
tcp_nopush on;
include /opt/nginx-config/*.conf;
server {
listen 81;
location / {
proxy_pass http://frontend;
proxy_buffering off;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location = /robots.txt {
add_header Content-Type text/plain;
return 200 "User-agent: *\nDisallow: /\n";
}
location /graphql {
proxy_pass http://api:8080;
proxy_buffering off;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /webhook {
proxy_pass http://api:8080;
proxy_buffering off;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
server {
listen 8080;
location /adminer {
proxy_pass http://adminer:8080/;
proxy_buffering off;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location ~* /rabbitmq/api/(.*?)/(.*) {
proxy_pass http://rabbitmq:15672/api/$1/%2F/$2?$query_string;
proxy_buffering off;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location ~* /rabbitmq/(.*) {
rewrite ^/rabbitmq/(.*)$ /$1 break;
proxy_pass http://rabbitmq:15672;
proxy_buffering off;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
}

156
docker-compose.yml Normal file
View file

@ -0,0 +1,156 @@
version: "3"
x-backend:
&backend
image: git.dergrimm.net/dergrimm/gitea_pages_backend:latest
build:
context: ./backend
restart: always
environment:
PAGES_DB_URL: postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_USER}
PAGES_AMQP_URL: amqp://${RABBITMQ_USER}:${RABBITMQ_PASSWORD}@rabbitmq:5672
PAGES_USER: ${PAGES_USER}
PAGES_PASSWORD: ${PAGES_PASSWORD}
PAGES_GITEA_URL: ${PAGES_GITEA_URL}
PAGES_GITEA_API_TOKEN: ${PAGES_GITEA_API_TOKEN}
PAGES_GITEA_SECRET: ${PAGES_GITEA_SECRET}
PAGES_GITEA_PULL_URL: ${PAGES_GITEA_PULL_URL}
PAGES_GITEA_PULL_BRANCH: ${PAGES_GITEA_PULL_BRANCH}
PAGES_NGINX_CONFIG_DIR: ${PAGES_NGINX_CONFIG_DIR}
PAGES_REPOS_DIR: ${PAGES_REPOS_DIR}
PAGES_DOMAIN: ${PAGES_DOMAIN}
services:
nginx:
image: docker.io/byjg/nginx-extras:1.23
restart: always
volumes:
- /var/run/docker.sock:/var/run/docker.sock
- /etc/timezone:/etc/timezone:ro
- /etc/localtime:/etc/localtime:ro
- ./config/nginx/nginx.conf:/etc/nginx/nginx.conf:ro
- nginx-config:/opt/nginx-config:ro
- repos:/var/www/repos:ro
ports:
- 80:80
- 81:81
- 8080:8080
depends_on:
- api
- adminer
- rabbitmq
db:
image: docker.io/postgres:15-alpine
restart: always
environment:
TZ: Europe/Berlin
POSTGRES_USER: ${POSTGRES_USER}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
volumes:
- /etc/timezone:/etc/timezone:ro
- /etc/localtime:/etc/localtime:ro
- db:/var/lib/postgresql/data
# pgbackups:
# image: docker.io/prodrigestivill/postgres-backup-local:15-alpine
# restart: always
# user: postgres:postgres
# volumes:
# - pgbackups:/backups
# links:
# - db
# depends_on:
# - db
# environment:
# POSTGRES_HOST: db
# POSTGRES_DB: ${POSTGRES_USER}
# POSTGRES_USER: ${POSTGRES_USER}
# POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
# POSTGRES_EXTRA_OPTS: "-Z6 --schema=public --blobs"
# SCHEDULE: "@daily"
# BACKUP_KEEP_DAYS: 7
# BACKUP_KEEP_WEEKS: 4
# BACKUP_KEEP_MONTHS: 6
adminer:
image: docker.io/adminer:standalone
restart: always
volumes:
- /etc/timezone:/etc/timezone:ro
- /etc/localtime:/etc/localtime:ro
depends_on:
- db
rabbitmq:
image: docker.io/rabbitmq:3-management-alpine
restart: always
environment:
RABBITMQ_DEFAULT_USER: ${RABBITMQ_USER}
RABBITMQ_DEFAULT_PASS: ${RABBITMQ_PASSWORD}
volumes:
- /etc/timezone:/etc/timezone:ro
- /etc/localtime:/etc/localtime:ro
- rabbitmq:/var/lib/rabbitmq
migration_runner:
<<: *backend
command: ./migrate.sh
depends_on:
- db
worker:
<<: *backend
command: ./run.sh worker
volumes:
- /var/run/docker.sock:/var/run/docker.sock
- /etc/timezone:/etc/timezone:ro
- /etc/localtime:/etc/localtime:ro
- nginx-config:/opt/nginx-config
- repos:/data/repos
depends_on:
- db
- rabbitmq
- migration_runner
beat:
<<: *backend
command: ./run.sh beat
volumes:
- /etc/timezone:/etc/timezone:ro
- /etc/localtime:/etc/localtime:ro
depends_on:
- db
- rabbitmq
- worker
- migration_runner
api:
<<: *backend
command: ./run.sh api
volumes:
- /etc/timezone:/etc/timezone:ro
- /etc/localtime:/etc/localtime:ro
depends_on:
- db
- rabbitmq
- worker
- migration_runner
frontend:
image: git.dergrimm.net/dergrimm/gitea_pages_frontend:latest
build:
context: ./frontend
restart: always
volumes:
- /etc/timezone:/etc/timezone:ro
- /etc/localtime:/etc/localtime:ro
depends_on:
- api
volumes:
nginx-config:
db: # pgbackups:
rabbitmq:
repos:

3
frontend/.cargo/config Normal file
View file

@ -0,0 +1,3 @@
[build]
target = "wasm32-unknown-unknown"
rustflags = ["--cfg=web_sys_unstable_apis"]

10
frontend/.dockerignore Normal file
View file

@ -0,0 +1,10 @@
/docs/
/lib/
/bin/
/.shards/
*.dwarf
*.env
/examples/
Dockerfile
.dockerignore
README.md

1
frontend/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
/target

2212
frontend/Cargo.lock generated Normal file

File diff suppressed because it is too large Load diff

35
frontend/Cargo.toml Normal file
View file

@ -0,0 +1,35 @@
[package]
name = "frontend"
version = "0.1.0"
edition = "2021"
build = "build.rs"
[profile.release]
lto = true
codegen-units = 1
opt-level = "z"
panic = "abort"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
bounce = { version = "0.6.1", features = ["helmet"] }
cynic = { version = "2.2.8", features = ["http-reqwest"] }
gloo = "0.8.0"
implicit-clone = "0.3.5"
lazy_static = "1.4.0"
log = "0.4.17"
paste = "1.0.12"
reqwest = "0.11.18"
serde = { version = "1.0.163", features = ["derive"] }
serde_json = "1.0.96"
wasm-logger = "0.2.0"
web-sys = { version = "0.3.63", features = ["Window", "Location"] }
wee_alloc = "0.4.5"
yew = { version = "0.20.0", features = ["csr"] }
yew-router = "0.17.0"
yewdux = "0.9.2"
[build-dependencies]
cynic-querygen = "2.2.8"
cargo-emit = "0.2.1"

59
frontend/Dockerfile Normal file
View file

@ -0,0 +1,59 @@
FROM docker.io/alpine:3.18.0 as alpine
FROM docker.io/lukemathwalker/cargo-chef:latest-rust-1.69.0 as chef
FROM codycraven/sassc:3.6.1 as css
SHELL ["/bin/ash", "-eo", "pipefail", "-c"]
ENV PYTHONUNBUFFERED=1
RUN apk add --update --no-cache python3=3.7.10-r0
WORKDIR /usr/src/scss
COPY ./compile_css.py .
RUN chmod +x ./compile_css.py
COPY ./scss ./src
RUN ./compile_css.py ./src ./dist
FROM chef as planner
WORKDIR /usr/src/frontend
RUN mkdir src && touch src/main.rs
COPY ./Cargo.toml ./Cargo.lock ./
RUN cargo chef prepare --recipe-path recipe.json
FROM chef as builder
SHELL ["/bin/bash", "-o", "pipefail", "-c"]
WORKDIR /usr/local/bin
ARG TRUNK_VERSION="v0.16.0"
RUN wget -qO- https://github.com/thedodd/trunk/releases/download/${TRUNK_VERSION}/trunk-x86_64-unknown-linux-gnu.tar.gz | tar -xzf-
RUN rustup target add wasm32-unknown-unknown
WORKDIR /usr/src/frontend
COPY ./.cargo ./.cargo
COPY --from=planner /usr/src/frontend/recipe.json .
RUN cargo chef cook --release --recipe-path recipe.json
COPY ./build.rs .
COPY ./schema.graphql ./query.graphql ./
RUN cargo build --release --frozen --offline
COPY ./src ./src
RUN cargo build --release --frozen --offline
COPY --from=css /usr/src/scss/dist ./css
COPY ./index.html ./index.html
RUN trunk build --release
FROM git.dergrimm.net/dergrimm/minify:2.12.5 as public
WORKDIR /usr/src/public
COPY --from=builder /usr/src/frontend/dist .
RUN minify . -r -o .
FROM alpine as binaryen
SHELL ["/bin/ash", "-eo", "pipefail", "-c"]
WORKDIR /tmp
ARG BINARYEN_VERSION="110"
RUN wget -qO- https://github.com/WebAssembly/binaryen/releases/download/version_${BINARYEN_VERSION}/binaryen-version_${BINARYEN_VERSION}-x86_64-linux.tar.gz | tar -xzf-
RUN cp ./binaryen-version_${BINARYEN_VERSION}/bin/wasm-opt /usr/local/bin && \
rm -rf ./binaryen-version_${BINARYEN_VERSION}
WORKDIR /usr/src/public
COPY --from=public /usr/src/public .
RUN find . -name "*.wasm" -type f -print0 | xargs -0 -I % wasm-opt % -o % -O --intrinsic-lowering -Oz
FROM docker.io/openresty/openresty:1.21.4.1-0-alpine as runner
COPY ./nginx.conf /usr/local/openresty/nginx/conf/nginx.conf
COPY --from=binaryen /usr/src/public /var/www/html
EXPOSE 80

28
frontend/build.rs Normal file
View file

@ -0,0 +1,28 @@
use std::env;
use std::fs;
use std::path::Path;
fn main() {
let manifest_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
let out_dir = env::var("OUT_DIR").unwrap();
let schema = fs::read_to_string(Path::new(&manifest_dir).join("schema.graphql")).unwrap();
let query = fs::read_to_string(Path::new(&manifest_dir).join("query.graphql")).unwrap();
let code = cynic_querygen::document_to_fragment_structs(
query,
schema,
&cynic_querygen::QueryGenOptions {
schema_path: "schema.graphql".to_string(),
query_module: "schema".to_string(),
},
)
.unwrap();
let patched_code = code
.replace("mod queries", "pub mod queries")
.replace("mod schema", "pub mod schema");
fs::write(Path::new(&out_dir).join("graphql.rs"), patched_code).unwrap();
cargo_emit::rerun_if_changed!("schema.graphql", "query.graphql");
}

26
frontend/compile_css.py Normal file
View file

@ -0,0 +1,26 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import glob
import sys
from pathlib import Path
EXTENSIONS = ("*.css", "*.sass", "*.scss")
def compile(p):
print("==========")
print(f"{p}:")
dist = Path(sys.argv[2], *p.with_suffix(".css").parts[1:])
print(f"\tWriting to: {dist}")
print(f"\tCreating dir: {dist.parent}")
dist.parent.mkdir(parents=True, exist_ok=True)
prompt = f"sassc {p} > {dist}"
print(f"\tInvoking sassc: {prompt}")
os.system(prompt)
for ext in EXTENSIONS:
for p in Path(sys.argv[1]).rglob(ext):
compile(p)

37
frontend/index.html Normal file
View file

@ -0,0 +1,37 @@
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script
src="https://kit.fontawesome.com/7efbac0aa5.js"
crossorigin="anonymous"
></script>
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bulmaswatch@0.8.1/lumen/bulmaswatch.min.css"
integrity="sha256-JlUFCH1GY5bKd0cOYm53u7NEGByTk/7uoe/yWouFKTo="
crossorigin="anonymous"
/>
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bulma-switch@2.0.4/dist/css/bulma-switch.min.css"
integrity="sha256-8EYN3r3ZVCWlBZCQhQOhcPX/CLKL1TVzxxeR/HzR5vU="
crossorigin="anonymous"
/>
<link data-trunk rel="css" href="css/styles.css" />
</head>
<body>
<noscript>
<strong>
This website does not work without JavaScript and WebAssembly.
</strong>
<br />
I too don't like this technology stack
</noscript>
</body>
</html>

24
frontend/nginx.conf Normal file
View file

@ -0,0 +1,24 @@
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
tcp_nopush on;
server_tokens off;
more_clear_headers Server;
server {
listen 80;
root /var/www/html;
location / {
try_files $uri /index.html;
}
}
}

33
frontend/query.graphql Normal file
View file

@ -0,0 +1,33 @@
query Users {
users {
name
repositories {
id
name
url
}
}
}
query UserByName($name: String!) {
userByName(name: $name) {
repositories {
name
url
}
}
}
query VerifyLogin($username: String!, $password: String!) {
verifyLogin(username: $username, password: $password)
}
mutation CreateRepository($user: String!, $name: String!) {
createRepository(input: { user: $user, name: $name }) {
id
}
}
mutation DeleteRepository($id: UUID!) {
deleteRepository(id: $id)
}

37
frontend/schema.graphql Normal file
View file

@ -0,0 +1,37 @@
input CreateRepositoryInput {
user: String!
name: String!
}
type Mutation {
createRepository(input: CreateRepositoryInput!): Repository!
deleteRepository(id: UUID!): Boolean!
}
type Query {
ping: String!
verifyLogin(username: String!, password: String!): Boolean!
user(id: UUID!): User!
userByName(name: String!): User!
users: [User!]!
repository(id: UUID!): Repository!
repositories: [Repository!]!
}
type Repository {
id: UUID!
user: User!
name: String!
url(scheme: Boolean): String!
}
type User {
id: UUID!
name: String!
repositories: [Repository!]!
}
"""
UUID encoded as a string
"""
scalar UUID

58
frontend/scss/styles.scss Normal file
View file

@ -0,0 +1,58 @@
body {
display: flex;
flex-direction: column;
overflow-x: hidden;
min-height: 100vh;
}
#wrapper {
flex: 1;
}
#main {
margin: 2vh 0;
}
#notifications {
overflow: hidden;
position: fixed;
right: 0;
z-index: 100;
}
#notifications-column {
width: 100%;
margin: 5% 0 0 auto;
}
.notification-slide-from-right {
position: relative;
animation-name: slideFromRight;
animation-duration: 0.5s;
animation-timing-function: ease;
transition: all 1s ease-out;
margin-right: 5%;
}
@keyframes slideFromRight {
from {
opacity: 0;
transform: translateX(100%);
}
to {
opacity: 1;
transform: translateX(0);
}
}
// .loader {
// width: 48px;
// height: 48px;
// border: 5px solid black;
// border-bottom-color: transparent;
// border-radius: 50%;
// display: inline-block;
// box-sizing: border-box;
// animation: rotation 1s linear infinite;
// }

View file

@ -0,0 +1,51 @@
use yew::prelude::*;
pub struct Footer;
impl Component for Footer {
type Message = ();
type Properties = ();
fn create(_ctx: &Context<Self>) -> Self {
Self
}
fn view(&self, _ctx: &Context<Self>) -> Html {
html! {
<footer class={classes!("footer")}>
<div class={classes!("columns")}>
<div class={classes!("column", "is-three-quarters")}>
<h3 class={classes!("title", "is-3")}>{ "Gitea Pages" }</h3>
<p>
<a href="https://git.dergrimm.net/dergrimm/gitea_pages"><strong>{ "Gitea Pages" }</strong></a> { " by " }
<a href="https://dergrimm.net">{ "Dominic Grimm" }</a> { ". " }
{ "Source code is licensed under the " } <a href="https://www.gnu.org/licenses/gpl-3.0.en.html">{ "GNU General Public License version 3" }</a> {"."}
</p>
</div>
<div class={classes!("column")}>
<p>
<a href="https://www.rust-lang.org/" target="_blank">
<figure class={classes!("image")}>
<img src="https://forthebadge.com/images/badges/made-with-rust.svg" />
</figure>
</a>
</p>
<p>
<figure class={classes!("image")}>
<img src="https://forthebadge.com/images/badges/no-ragrets.svg" />
</figure>
</p>
</div>
</div>
<hr />
<div>
<p>
{ "©2023 Dominic Grimm" }
</p>
</div>
</footer>
}
}
}

View file

@ -0,0 +1,18 @@
use yew::prelude::*;
pub struct Loading;
impl Component for Loading {
type Message = ();
type Properties = ();
fn create(_ctx: &Context<Self>) -> Self {
Self
}
fn view(&self, _ctx: &Context<Self>) -> Html {
html! {
<p class={classes!("has-text-centered")}>{ "Loading..." }</p>
}
}
}

View file

@ -0,0 +1,13 @@
pub mod footer;
pub mod loading;
pub mod navbar;
pub mod notification;
pub mod notification_listing;
pub mod user_pane;
pub use footer::Footer;
pub use loading::Loading;
pub use navbar::Navbar;
pub use notification::Notification;
pub use notification_listing::NotificationListing;
pub use user_pane::UserPane;

View file

@ -0,0 +1,124 @@
use std::rc::Rc;
use yew::prelude::*;
use yew_router::prelude::*;
use yewdux::prelude::*;
use crate::{routes, stores};
pub enum Msg {
UpdateUser(Rc<stores::User>),
BurgerClicked,
Logout,
}
pub struct Navbar {
user: Rc<stores::User>,
user_dispatch: Dispatch<stores::User>,
burger_active: bool,
}
impl Component for Navbar {
type Message = Msg;
type Properties = ();
fn create(ctx: &Context<Self>) -> Self {
let user_dispatch = Dispatch::subscribe(ctx.link().callback(Msg::UpdateUser));
Self {
user: user_dispatch.get(),
user_dispatch,
burger_active: false,
}
}
fn update(&mut self, _ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::UpdateUser(x) => {
self.user = x;
true
}
Msg::BurgerClicked => {
self.burger_active = !self.burger_active;
true
}
Msg::Logout => {
self.user_dispatch.set(stores::User(None));
true
}
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
html! {
<header>
<nav
class={classes!("navbar", "is-primary")}
role="navigation"
aria-label="main navigation"
>
<div class={classes!("navbar-brand")}>
<Link<routes::Route> to={routes::Route::Index} classes={classes!("navbar-item")}>
<strong>{ "Gitea Pages" }</strong>
</Link<routes::Route>>
<a
role="button"
onclick={ctx.link().callback(|_| Msg::BurgerClicked)}
class={classes!("navbar-burger")}
aria-label="menu"
aria-expandable="false"
>
<span aria-hidden="true" />
<span aria-hidden="true" />
<span aria-hidden="true" />
</a>
</div>
<div
class={classes!(
"navbar-menu",
"is-white",
if self.burger_active { Some("is-active") } else { None }
)}
>
<div class={classes!("navbar-end")}>
<a
href="https://git.dergrimm.net/dergrimm/gitea_pages"
target="_blank"
class={classes!("navbar-item")}
>
{ "Info" }
</a>
<div class={classes!("navbar-item")}>
<div class={classes!("buttons")}>
if self.user.logged_in() {
<button
onclick={ctx.link().callback(|_| Msg::Logout)}
class={classes!("button")}
>
<span class={classes!("icon", "is-small")}>
<i class={classes!("fa-solid", "fa-right-from-bracket")} />
</span>
<span>{ "Logout" }</span>
</button>
} else {
<Link<routes::Route> to={routes::Route::Login} classes={classes!("button")}>
<span class={classes!("icon", "is-small")}>
<i class={classes!("fa-solid", "fa-right-to-bracket")} />
</span>
<span>{ "Login" }</span>
</Link<routes::Route>>
}
</div>
</div>
</div>
</div>
</nav>
</header>
}
}
}

View file

@ -0,0 +1,126 @@
use gloo::timers::callback::Interval;
use std::rc::Rc;
use yew::prelude::*;
use crate::{graphql, stores};
pub enum Msg {
Remove,
}
#[derive(Clone, PartialEq)]
pub enum NotificationType {
Dark,
Primary,
Link,
Info,
Success,
Warning,
Danger,
}
pub fn class_from_notification_type(x: &NotificationType) -> &'static str {
match x {
NotificationType::Dark => "is-dark",
NotificationType::Primary => "is-primary",
NotificationType::Link => "is-link",
NotificationType::Info => "is-info",
NotificationType::Success => "is-success",
NotificationType::Warning => "is-warning",
NotificationType::Danger => "is-danger",
}
}
pub fn name_from_notification_type(x: &NotificationType) -> &'static str {
match x {
NotificationType::Dark => "Info",
NotificationType::Primary => "Info",
NotificationType::Link => "Info",
NotificationType::Info => "Info",
NotificationType::Success => "Success",
NotificationType::Warning => "Warning",
NotificationType::Danger => "Error",
}
}
#[derive(Clone, PartialEq)]
pub enum NotificationMessage {
Text(Vec<String>),
GraphQLError(graphql::GraphQLError),
}
#[derive(Properties, PartialEq)]
pub struct Props {
pub notifications: Rc<stores::Notifications>,
pub index: usize,
pub remove: Rc<Callback<usize, ()>>,
}
pub struct Notification {
_interval: Interval,
}
impl Component for Notification {
type Message = Msg;
type Properties = Props;
fn create(ctx: &Context<Self>) -> Self {
Self {
_interval: {
let link = ctx.link().clone();
Interval::new(15_000, move || link.send_message(Msg::Remove))
},
}
}
fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::Remove => {
ctx.props().remove.emit(ctx.props().index);
true
}
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
let notif = &ctx.props().notifications.notifications[&ctx.props().index];
html! {
<div class={classes!("block", "notification-slide-from-right")}>
<article class={classes!("message", class_from_notification_type(&notif.notification_type))}>
<div class={classes!("message-header")}>
<p>{ name_from_notification_type(&notif.notification_type) }</p>
<button
class={classes!("delete")}
aria-label="delete"
onclick={ctx.link().callback(|_| Msg::Remove)}
/>
</div>
<div class={classes!("message-body")}>
if let Some(message) = &notif.message {
{
match message {
NotificationMessage::Text(x) => html! {
{
for x.iter().map(|s| html! {
<>
{ s }
<br />
</>
})
}
},
NotificationMessage::GraphQLError(x) => html! {
{ x }
},
}
}
}
</div>
</article>
</div>
}
}
}

View file

@ -0,0 +1,58 @@
use std::rc::Rc;
use yew::prelude::*;
use yewdux::prelude::*;
use crate::{components, stores};
pub enum Msg {
UpdateNotifications(Rc<stores::Notifications>),
Remove(usize),
}
pub struct NotificationListing {
notifications: Rc<stores::Notifications>,
notifications_dispatch: Dispatch<stores::Notifications>,
}
impl Component for NotificationListing {
type Message = Msg;
type Properties = ();
fn create(ctx: &Context<Self>) -> Self {
let notifications_dispatch =
Dispatch::subscribe(ctx.link().callback(Msg::UpdateNotifications));
Self {
notifications: notifications_dispatch.get(),
notifications_dispatch,
}
}
fn update(&mut self, _ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::UpdateNotifications(x) => {
self.notifications = x;
true
}
Msg::Remove(i) => {
self.notifications_dispatch
.reduce_mut(|notifs| notifs.notifications.remove(&i));
true
}
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
let remove = Rc::new(ctx.link().callback(Msg::Remove));
html! {
{
for self.notifications.notifications.iter().rev().map(|(i, _)| html! {
<components::Notification notifications={self.notifications.clone()} index={i} remove={remove.clone()} />
})
}
}
}
}

View file

@ -0,0 +1,76 @@
use yew::prelude::*;
#[derive(PartialEq)]
pub struct Repository {
pub name: String,
pub url: Option<String>,
}
#[derive(Properties, PartialEq)]
pub struct Props {
pub name: AttrValue,
pub repositories: Vec<Repository>,
pub on_click: Option<Callback<usize>>,
}
pub enum Msg {
Emit(usize),
}
pub struct UserPane;
impl Component for UserPane {
type Message = Msg;
type Properties = Props;
fn create(_ctx: &Context<Self>) -> Self {
Self
}
fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::Emit(i) => {
ctx.props().on_click.as_ref().unwrap().emit(i);
false
}
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
html! {
<nav class={classes!("panel")}>
<p class={classes!("panel-heading")}>
{ &ctx.props().name }
</p>
{
for ctx.props().repositories.iter().enumerate().map(|(i, repo)| html! {
if let Some(url) = &repo.url {
<a
class={classes!("panel-block", "is-active")}
href={url.to_owned()}
target="_blank"
>
<span class={classes!("panel-icon")}>
<i class={classes!("fa-solid", "fa-book")} />
</span>
{ &repo.name }
</a>
} else {
<a
class={classes!("panel-block", "is-active")}
onclick={ctx.link().callback(move |_| Msg::Emit(i))}
>
<span class={classes!("panel-icon")}>
<i class={classes!("fa-solid", "fa-book")} />
</span>
{ &repo.name }
</a>
}
})
}
</nav>
}
}
}

99
frontend/src/graphql.rs Normal file
View file

@ -0,0 +1,99 @@
use lazy_static::lazy_static;
use serde::Deserialize;
use std::future::Future;
use std::pin::Pin;
use crate::stores;
lazy_static! {
pub static ref URL: String = format!(
"{}/graphql",
web_sys::window().unwrap().location().origin().unwrap()
);
}
type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + 'a>>;
pub trait ReqwestExt {
fn run_graphql<ResponseData, Vars, Extensions>(
self,
operation: cynic::Operation<ResponseData, Vars>,
) -> BoxFuture<
'static,
Result<cynic::GraphQlResponse<ResponseData, Extensions>, cynic::http::CynicReqwestError>,
>
where
Vars: serde::Serialize,
ResponseData: serde::de::DeserializeOwned + 'static,
Extensions: serde::de::DeserializeOwned + 'static;
}
impl ReqwestExt for reqwest::RequestBuilder {
fn run_graphql<ResponseData, Vars, Extensions>(
self,
operation: cynic::Operation<ResponseData, Vars>,
) -> BoxFuture<
'static,
Result<cynic::GraphQlResponse<ResponseData, Extensions>, cynic::http::CynicReqwestError>,
>
where
Vars: serde::Serialize,
ResponseData: serde::de::DeserializeOwned + 'static,
Extensions: serde::de::DeserializeOwned + 'static,
{
let builder = self.json(&operation);
Box::pin(async move {
match builder.send().await {
Ok(response) => {
let status = response.status();
if !status.is_success() {
let body_string = response.text().await?;
match serde_json::from_str::<cynic::GraphQlResponse<ResponseData, Extensions>>(
&body_string,
) {
Ok(response) => return Ok(response),
Err(_) => {
return Err(cynic::http::CynicReqwestError::ErrorResponse(
status,
body_string,
));
}
};
}
response
.json::<cynic::GraphQlResponse<ResponseData, Extensions>>()
.await
.map_err(cynic::http::CynicReqwestError::ReqwestError)
}
Err(e) => Err(cynic::http::CynicReqwestError::ReqwestError(e)),
}
})
}
}
pub fn client(user: Option<&stores::UserData>) -> reqwest::RequestBuilder {
let client = reqwest::Client::new().post(URL.as_str());
if let Some(x) = user {
client.basic_auth(&x.username, Some(&x.password))
} else {
client
}
}
#[derive(Deserialize, Clone, PartialEq, Eq, Debug)]
pub struct ErrorExtensions {
#[serde(rename = "type")]
pub error_type: String,
}
pub type GraphQLError = cynic::GraphQlError<ErrorExtensions>;
pub type GraphQLResponse<T> = cynic::GraphQlResponse<T, ErrorExtensions>;
pub type GraphQLResult<T> = Result<GraphQLResponse<T>, cynic::http::CynicReqwestError>;
include!(concat!(env!("OUT_DIR"), "/graphql.rs"));
pub struct Uuid(pub String);
cynic::impl_scalar!(Uuid, schema::UUID);

View file

@ -0,0 +1,32 @@
use yew::prelude::*;
use crate::components;
#[derive(Properties, PartialEq)]
pub struct Props {
#[prop_or_default]
pub children: Children,
}
pub struct Base;
impl Component for Base {
type Message = ();
type Properties = Props;
fn create(_ctx: &Context<Self>) -> Self {
Self
}
fn view(&self, ctx: &Context<Self>) -> Html {
html! {
<>
<div id="wrapper">
<components::Navbar />
{ for ctx.props().children.iter() }
</div>
<components::Footer />
</>
}
}
}

View file

@ -0,0 +1,63 @@
use std::rc::Rc;
use yew::prelude::*;
use yew_router::prelude::*;
use yewdux::prelude::*;
use crate::{routes, stores};
pub enum Msg {
UpdateUser(Rc<stores::User>),
}
#[derive(Properties, PartialEq)]
pub struct Props {
#[prop_or_default]
pub children: Children,
}
pub struct LoggedIn {
user: Rc<stores::User>,
_user_dispatch: Dispatch<stores::User>,
}
impl Component for LoggedIn {
type Message = Msg;
type Properties = Props;
fn create(ctx: &Context<Self>) -> Self {
let user_dispatch = Dispatch::subscribe(ctx.link().callback(Msg::UpdateUser));
let user = user_dispatch.get();
if !user.logged_in() {
ctx.link().navigator().unwrap().push(&routes::Route::Login);
}
Self {
user,
_user_dispatch: user_dispatch,
}
}
fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::UpdateUser(x) => {
let prev = self.user.logged_in();
self.user = x;
if !self.user.logged_in() {
ctx.link().navigator().unwrap().push(&routes::Route::Login);
}
prev != self.user.logged_in()
}
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
html! {
if self.user.logged_in() {
{ for ctx.props().children.iter() }
}
}
}
}

View file

@ -0,0 +1,39 @@
use yew::prelude::*;
use crate::{components, layouts};
#[derive(Properties, PartialEq)]
pub struct Props {
#[prop_or_default]
pub children: Children,
}
pub struct Main;
impl Component for Main {
type Message = ();
type Properties = Props;
fn create(_ctx: &Context<Self>) -> Self {
Self
}
fn view(&self, ctx: &Context<Self>) -> Html {
html! {
<>
<layouts::Base>
<div class={classes!("columns", "is-centered")}>
<main id="main" class={classes!("column", "is-four-fifths")}>
{ for ctx.props().children.iter() }
</main>
</div>
</layouts::Base>
<div id="notifications" class={classes!("columns")}>
<div id="notifications-column" class={classes!("column", "is-one-third")}>
<components::NotificationListing />
</div>
</div>
</>
}
}
}

View file

@ -0,0 +1,9 @@
pub mod base;
pub mod logged_in;
pub mod main;
pub mod not_found;
pub use base::Base;
pub use logged_in::LoggedIn;
pub use main::Main;
pub use not_found::NotFound;

View file

@ -0,0 +1,49 @@
use bounce::helmet::Helmet;
use yew::prelude::*;
use yew_router::prelude::*;
use crate::routes;
#[derive(Properties, PartialEq)]
pub struct Props {
pub message: AttrValue,
#[prop_or(true)]
pub ellipsis: bool,
}
pub struct NotFound;
impl Component for NotFound {
type Message = ();
type Properties = Props;
fn create(_ctx: &Context<Self>) -> Self {
Self
}
fn view(&self, ctx: &Context<Self>) -> Html {
html! {
<>
<Helmet>
<title>{ &ctx.props().message }</title>
</Helmet>
<div class={classes!("has-text-centered")}>
<h1 class={classes!("title", "my-auto")}>
<i>
{ &ctx.props().message }
if ctx.props().ellipsis {
{ "..." }
}
</i>
</h1>
<p>
<Link<routes::Route> to={routes::Route::Index}>
{ "Back to home" }
</Link<routes::Route>>
</p>
</div>
</>
}
}
}

5
frontend/src/lib.rs Normal file
View file

@ -0,0 +1,5 @@
pub mod components;
pub mod graphql;
pub mod layouts;
pub mod routes;
pub mod stores;

46
frontend/src/main.rs Normal file
View file

@ -0,0 +1,46 @@
use bounce::{helmet::HelmetBridge, BounceRoot};
use implicit_clone::unsync::IString;
use yew::prelude::*;
use yew_router::prelude::*;
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
use frontend::{layouts, routes};
pub const DEFAULT_TITLE: &str = "Gitea Pages";
fn format_title(title: IString) -> IString {
IString::from(format!("{} | {}", title, DEFAULT_TITLE))
}
struct App;
impl Component for App {
type Message = ();
type Properties = ();
fn create(_ctx: &Context<Self>) -> Self {
Self
}
fn view(&self, _ctx: &Context<Self>) -> Html {
html! {
<BrowserRouter>
<BounceRoot>
<HelmetBridge default_title={DEFAULT_TITLE} {format_title} />
<layouts::Main>
<Switch<routes::Route> render={routes::switch} />
</layouts::Main>
</BounceRoot>
</BrowserRouter>
}
}
}
fn main() {
wasm_logger::init(wasm_logger::Config::default());
yew::Renderer::<App>::new().render();
}

View file

@ -0,0 +1,429 @@
use bounce::helmet::Helmet;
use cynic::{MutationBuilder, QueryBuilder};
use std::rc::Rc;
use web_sys::HtmlInputElement;
use yew::prelude::*;
use yewdux::prelude::*;
use crate::{
components,
graphql::{self, ReqwestExt},
stores,
};
pub enum Msg {
Void,
UpdateUser(Rc<stores::User>),
LoadUsers,
UsersDone(graphql::GraphQLResult<graphql::queries::Users>),
OpenNewModal,
CloseNewModal,
NewModalSubmit,
NewModalSubmitDone(graphql::GraphQLResult<graphql::queries::CreateRepository>),
OpenEditModal(usize, usize),
CloseEditModal,
Delete,
DeleteDone(graphql::GraphQLResult<graphql::queries::DeleteRepository>),
}
pub struct Index {
notifications_dispatch: Dispatch<stores::Notifications>,
user: Rc<stores::User>,
_user_dispatch: Dispatch<stores::User>,
loading: bool,
users: Vec<graphql::queries::User>,
new_modal: bool,
new_modal_save_loading: bool,
new_modal_user: NodeRef,
new_modal_repo: NodeRef,
delete_modal: Option<(usize, usize)>,
delete_modal_delete_loading: bool,
}
impl Component for Index {
type Message = Msg;
type Properties = ();
fn create(ctx: &Context<Self>) -> Self {
let notifications_dispatch = Dispatch::subscribe(ctx.link().callback(|_| Msg::Void));
let user_dispatch = Dispatch::subscribe(ctx.link().callback(Msg::UpdateUser));
ctx.link().send_message(Msg::LoadUsers);
Self {
notifications_dispatch,
user: user_dispatch.get(),
_user_dispatch: user_dispatch,
loading: false,
users: vec![],
new_modal: false,
new_modal_save_loading: false,
new_modal_user: NodeRef::default(),
new_modal_repo: NodeRef::default(),
delete_modal: None,
delete_modal_delete_loading: false,
}
}
fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::Void => false,
Msg::UpdateUser(x) => {
self.user = x;
true
}
Msg::LoadUsers => {
self.loading = true;
let client = graphql::client(None);
let operation = graphql::queries::Users::build(());
ctx.link().send_future(async move {
Msg::UsersDone(client.run_graphql(operation).await)
});
true
}
Msg::UsersDone(x) => {
self.loading = false;
match x {
Ok(resp) => {
if let Some(errors) = resp.errors {
self.notifications_dispatch.reduce_mut(|notifs| {
for e in errors {
notifs.push(stores::Notification::danger(Some(
components::notification::NotificationMessage::GraphQLError(
e,
),
)));
}
});
false
} else {
let data = resp.data.unwrap();
self.users = data.users;
true
}
}
Err(e) => {
self.notifications_dispatch.reduce_mut(|notifs| {
notifs.push(stores::Notification::danger(Some(
components::notification::NotificationMessage::Text(vec![
e.to_string()
]),
)));
});
false
}
}
}
Msg::OpenNewModal => {
self.new_modal = true;
true
}
Msg::CloseNewModal => {
self.new_modal = false;
self.new_modal_save_loading = false;
ctx.link().send_message(Msg::LoadUsers);
true
}
Msg::NewModalSubmit => {
let user = match self.new_modal_user.cast::<HtmlInputElement>() {
Some(x) => x.value(),
None => return false,
};
let name = match self.new_modal_repo.cast::<HtmlInputElement>() {
Some(x) => x.value(),
None => return false,
};
self.new_modal_save_loading = true;
let operation = graphql::queries::CreateRepository::build(
graphql::queries::CreateRepositoryVariables { user, name },
);
let client = graphql::client(self.user.0.as_ref());
ctx.link().send_future(async move {
Msg::NewModalSubmitDone(client.run_graphql(operation).await)
});
true
}
Msg::NewModalSubmitDone(x) => {
self.new_modal_save_loading = false;
match x {
Ok(resp) => {
if let Some(errors) = resp.errors {
self.notifications_dispatch.reduce_mut(|notifs| {
for e in errors {
notifs.push(stores::Notification {
notification_type: components::notification::NotificationType::Danger,
message: Some(components::notification::NotificationMessage::GraphQLError(e)),
});
}
});
true
} else {
ctx.link().send_message(Msg::CloseNewModal);
true
}
}
Err(e) => {
self.notifications_dispatch.reduce_mut(|notifs| {
notifs.push(stores::Notification::danger(Some(
components::notification::NotificationMessage::Text(vec![
e.to_string()
]),
)));
});
false
}
}
}
Msg::OpenEditModal(i, j) => {
self.delete_modal = Some((i, j));
true
}
Msg::CloseEditModal => {
self.delete_modal = None;
self.delete_modal_delete_loading = false;
ctx.link().send_message(Msg::LoadUsers);
true
}
Msg::Delete => {
let modal = self.delete_modal.unwrap();
self.delete_modal_delete_loading = true;
let operation = graphql::queries::DeleteRepository::build(
graphql::queries::DeleteRepositoryVariables {
id: self.users[modal.0].repositories[modal.1].id.to_owned(),
},
);
let client = graphql::client(self.user.0.as_ref());
ctx.link().send_future(async move {
Msg::DeleteDone(client.run_graphql(operation).await)
});
true
}
Msg::DeleteDone(x) => match x {
Ok(_) => {
self.delete_modal = None;
self.delete_modal_delete_loading = false;
ctx.link().send_message(Msg::LoadUsers);
true
}
Err(e) => {
self.notifications_dispatch.reduce_mut(|notifs| {
notifs.push(stores::Notification {
notification_type: components::notification::NotificationType::Danger,
message: Some(components::notification::NotificationMessage::Text(
vec![e.to_string()],
)),
});
});
false
}
},
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
html! {
<>
<Helmet>
<title>{ "Home" }</title>
</Helmet>
<div class={classes!("columns", "is-centered")}>
<div class={classes!("column", "is-half")}>
<div class={classes!("columns", "is-multiline")}>
<div class={classes!("column", "is-full")}>
<button
class={classes!("button", "is-primary", "is-fullwidth")}
onclick={ctx.link().callback(|_| Msg::OpenNewModal)}
>
<span class={classes!("icon", "is-small")}>
<i class={classes!("fa-solid", "fa-plus")} />
</span>
<span>{ "New" }</span>
</button>
</div>
if self.loading {
<div class={classes!("column", "is-full")}>
<components::Loading />
</div>
} else {
{
for self.users.iter().enumerate().map(|(i, user)| html! {
<div class={classes!("column", "is-full")}>
<components::UserPane
name={user.name.to_owned()}
repositories={user.repositories
.iter()
.map(|repo| components::user_pane::Repository {
name: repo.name.to_owned(),
url: None,
})
.collect::<Vec<_>>()
}
on_click={ctx.link().callback(move |j| Msg::OpenEditModal(i, j))}
/>
</div>
})
}
}
</div>
</div>
</div>
if self.new_modal {
<div class={classes!("modal", "is-active")}>
<div class={classes!("modal-background")} onclick={ctx.link().callback(|_| Msg::CloseNewModal)} />
<div class={classes!("modal-card")}>
<header class={classes!("modal-card-head")}>
<p class={classes!("modal-card-title")}>
{ "Edit" }
</p>
<button
class={classes!("delete")}
aria-label="close"
onclick={ctx.link().callback(|_| Msg::CloseNewModal)}
/>
</header>
<section class={classes!("modal-card-body")}>
<table class={classes!("table", "is-bordered", "is-striped", "is-hoverable", "is-fullwidth")}>
<tbody>
<tr>
<th>{ "User" }</th>
<td>
<input
class={classes!("input")}
type="text"
required=true
placeholder="User"
ref={self.new_modal_user.clone()}
/>
</td>
</tr>
<tr>
<th>{ "Repository" }</th>
<td>
<input
class={classes!("input")}
type="text"
required=true
placeholder="Repository"
ref={self.new_modal_repo.clone()}
/>
</td>
</tr>
</tbody>
</table>
</section>
<footer class={classes!("modal-card-foot")}>
<div class={classes!("field", "is-grouped")}>
<p class={classes!("control")}>
<button
class={classes!(
"button",
"is-success",
if self.new_modal_save_loading { Some("is-loading") } else { None }
)}
onclick={ctx.link().callback(|_| Msg::NewModalSubmit)}
>
<span class={classes!("icon", "is-small")}>
<i class={classes!("fa-solid", "fa-check")} />
</span>
<span>{ "Save" }</span>
</button>
</p>
<p class={classes!("control")}>
<button class={classes!("button")} onclick={ctx.link().callback(|_| Msg::CloseNewModal)}>
{ "Cancel" }
</button>
</p>
</div>
</footer>
</div>
</div>
}
if let Some(modal) = &self.delete_modal {
<div class={classes!("modal", "is-active")}>
<div class={classes!("modal-background")} onclick={ctx.link().callback(|_| Msg::CloseEditModal)} />
<div class={classes!("modal-card")}>
<header class={classes!("modal-card-head")}>
<p class={classes!("modal-card-title")}>
{ "Edit" }
</p>
<button
class={classes!("delete")}
aria-label="close"
onclick={ctx.link().callback(|_| Msg::CloseEditModal)}
/>
</header>
<section class={classes!("modal-card-body")}>
<p>
{ &self.users[modal.0].name }
{ "/" }
{ &self.users[modal.0].repositories[modal.1].name }
</p>
</section>
<footer class={classes!("modal-card-foot")}>
<div class={classes!("field", "is-grouped")}>
<p class={classes!("control")}>
<button
class={classes!(
"button",
"is-danger",
if self.delete_modal_delete_loading { Some("is-loading") } else { None }
)}
onclick={ctx.link().callback(|_| Msg::Delete)}
>
<span class={classes!("icon", "is-small")}>
<i class={classes!("fa-solid", "fa-trash")} />
</span>
<span>{ "Delete" }</span>
</button>
</p>
<p class={classes!("control")}>
<button class={classes!("button")} onclick={ctx.link().callback(|_| Msg::CloseEditModal)}>
{ "Cancel" }
</button>
</p>
</div>
</footer>
</div>
</div>
}
</>
}
}
}

View file

@ -0,0 +1,237 @@
use bounce::helmet::Helmet;
use cynic::QueryBuilder;
use std::rc::Rc;
use web_sys::HtmlInputElement;
use yew::prelude::*;
use yew_router::prelude::*;
use yewdux::prelude::*;
use crate::{
components,
graphql::{self, ReqwestExt},
routes, stores,
};
pub enum Msg {
UpdateUser(Rc<stores::User>),
UpdateNotifications(Rc<stores::Notifications>),
Login,
LoginDone {
user_data: stores::UserData,
result: graphql::GraphQLResult<graphql::queries::VerifyLogin>,
},
}
pub struct Login {
user: Rc<stores::User>,
user_dispatch: Dispatch<stores::User>,
notifications: Rc<stores::Notifications>,
notifications_dispatch: Dispatch<stores::Notifications>,
username: NodeRef,
password: NodeRef,
loading: bool,
error: Option<&'static str>,
}
impl Component for Login {
type Message = Msg;
type Properties = ();
fn create(ctx: &Context<Self>) -> Self {
let user_dispatch = Dispatch::subscribe(ctx.link().callback(Msg::UpdateUser));
let notifications_dispatch =
Dispatch::subscribe(ctx.link().callback(Msg::UpdateNotifications));
Self {
user: user_dispatch.get(),
user_dispatch,
notifications: notifications_dispatch.get(),
notifications_dispatch,
username: NodeRef::default(),
password: NodeRef::default(),
loading: false,
error: None,
}
}
fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::UpdateUser(x) => {
self.error = None;
let prev = self.user.logged_in();
self.user = x;
prev != self.user.logged_in()
}
Msg::UpdateNotifications(x) => {
self.notifications = x;
false
}
Msg::Login => {
self.error = None;
let username = match self.username.cast::<HtmlInputElement>().map(|x| x.value()) {
Some(x) => {
if x.is_empty() {
return false;
} else {
x
}
}
None => {
return false;
}
};
let password = match self.password.cast::<HtmlInputElement>().map(|x| x.value()) {
Some(x) => {
if x.is_empty() {
return false;
} else {
x
}
}
None => {
return false;
}
};
self.loading = true;
let operation =
graphql::queries::VerifyLogin::build(graphql::queries::VerifyLoginVariables {
username: username.to_owned(),
password: password.to_owned(),
});
ctx.link().send_future(async move {
Msg::LoginDone {
user_data: stores::UserData { username, password },
result: graphql::client(None).run_graphql(operation).await,
}
});
true
}
Msg::LoginDone { user_data, result } => {
self.loading = false;
match result {
Ok(resp) => {
if let Some(errors) = resp.errors {
self.notifications_dispatch.reduce_mut(|notifs| {
for e in errors {
notifs.push(stores::Notification::danger(Some(
components::notification::NotificationMessage::GraphQLError(
e,
),
)));
}
});
true
} else if resp.data.unwrap().verify_login {
self.error = None;
self.user_dispatch.set(stores::User(Some(user_data)));
false
} else {
const MESSAGE: &str = "Username or password not correct";
self.error = Some(MESSAGE);
self.notifications_dispatch.reduce_mut(|notifs| {
notifs.push(stores::Notification {
notification_type:
components::notification::NotificationType::Danger,
message: Some(
components::notification::NotificationMessage::Text(vec![
MESSAGE.to_string(),
]),
),
});
});
true
}
}
Err(e) => {
self.notifications_dispatch.reduce_mut(|notifs| {
notifs.push(stores::Notification {
notification_type:
components::notification::NotificationType::Danger,
message: Some(components::notification::NotificationMessage::Text(
vec![e.to_string()],
)),
});
});
false
}
}
}
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
if self.user.logged_in() {
ctx.link().navigator().unwrap().push(&routes::Route::Index);
}
html! {
<>
<Helmet>
<title>{ "Login" }</title>
</Helmet>
<div class={classes!("columns", "is-centered", "my-auto")}>
<div class={classes!("column", "is-half", "box")}>
<div class={classes!("p-4")}>
<form onsubmit={ctx.link().callback(|e: SubmitEvent| { e.prevent_default(); Msg::Login })}>
<div class={classes!("field")}>
<p class={classes!("control", "has-icons-left")}>
<input
class={classes!("input")}
type="text"
placeholder="Username"
ref={self.username.clone()}
/>
<span class={classes!("icon", "is-small", "is-left")}>
<i class={classes!("fa-solid", "fa-envelope")} />
</span>
</p>
</div>
<div class={classes!("field")}>
<p class={classes!("control", "has-icons-left")}>
<input
class={classes!("input")}
type="password"
placeholder="Password"
ref={self.password.clone()}
/>
<span class={classes!("icon", "is-small", "is-left")}>
<i class={classes!("fa-solid", "fa-lock")} />
</span>
</p>
</div>
<div class={classes!("field")}>
<p class={classes!("control")}>
<button
type="submit"
class={classes!("button", "is-success", "is-fullwidth", if self.loading { Some("is-loading") } else { None })}
>
{ "Login" }
</button>
</p>
</div>
if let Some(message) = self.error {
<p class={classes!("help", "is-danger")}>
{ message }
</p>
}
</form>
</div>
</div>
</div>
</>
}
}
}

View file

@ -0,0 +1,48 @@
use yew::prelude::*;
use yew_router::prelude::*;
use crate::layouts;
pub mod index;
pub mod login;
pub mod not_found;
pub mod user;
pub use index::Index;
pub use login::Login;
pub use not_found::NotFound;
pub use user::User;
#[derive(Clone, Routable, PartialEq, Eq, Debug)]
pub enum Route {
#[at("/")]
Index,
// #[at("/user/:name")]
// User { name: String },
#[at("/login")]
Login,
#[not_found]
#[at("/404")]
NotFound,
}
pub fn switch(route: Route) -> Html {
match route {
Route::Index => html! {
<layouts::LoggedIn>
<Index />
</layouts::LoggedIn>
},
// Route::User { name } => html! {
// <User {name} />
// },
Route::Login => html! {
<Login />
},
Route::NotFound => html! {
<NotFound />
},
}
}

View file

@ -0,0 +1,20 @@
use yew::prelude::*;
use crate::layouts;
pub struct NotFound;
impl Component for NotFound {
type Message = ();
type Properties = ();
fn create(_ctx: &Context<Self>) -> Self {
Self
}
fn view(&self, _ctx: &Context<Self>) -> Html {
html! {
<layouts::NotFound message="Page not found" />
}
}
}

143
frontend/src/routes/user.rs Normal file
View file

@ -0,0 +1,143 @@
use bounce::helmet::Helmet;
use cynic::QueryBuilder;
use yew::prelude::*;
use yewdux::prelude::*;
use crate::{
components,
graphql::{self, ReqwestExt},
stores,
};
#[derive(Properties, PartialEq)]
pub struct Props {
pub name: AttrValue,
}
pub enum Msg {
Void,
Done(graphql::GraphQLResult<graphql::queries::UserByName>),
}
struct Repository {
name: String,
url: String,
}
pub struct User {
notifications_dispatch: Dispatch<stores::Notifications>,
loading: bool,
repositories: Vec<Repository>,
}
impl Component for User {
type Message = Msg;
type Properties = Props;
fn create(ctx: &Context<Self>) -> Self {
let operation =
graphql::queries::UserByName::build(graphql::queries::UserByNameVariables {
name: ctx.props().name.to_string(),
});
let client = graphql::client(None);
ctx.link()
.send_future(async move { Msg::Done(client.run_graphql(operation).await) });
Self {
notifications_dispatch: Dispatch::subscribe(ctx.link().callback(|_| Msg::Void)),
loading: true,
repositories: vec![],
}
}
fn update(&mut self, _ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::Void => false,
Msg::Done(x) => {
self.loading = false;
match x {
Ok(resp) => {
if let Some(errors) = resp.errors {
self.notifications_dispatch.reduce_mut(|notifs| {
for e in errors {
notifs.push(stores::Notification::danger(Some(
components::notification::NotificationMessage::GraphQLError(
e,
),
)));
}
});
false
} else {
self.repositories = resp
.data
.unwrap()
.user_by_name
.repositories
.into_iter()
.map(|repo| Repository {
name: repo.name,
url: repo.url,
})
.collect();
true
}
}
Err(e) => {
self.notifications_dispatch.reduce_mut(|notifs| {
notifs.push(stores::Notification::danger(Some(
components::notification::NotificationMessage::Text(vec![
e.to_string()
]),
)));
});
false
}
}
}
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
let name = &ctx.props().name;
html! {
<>
<Helmet>
<title>{ name }</title>
</Helmet>
<div class={classes!("columns", "is-centered")}>
<div class={classes!("column", "is-half")}>
<div class={classes!("columns", "is-multiline")}>
if self.loading {
<div class={classes!("column", "is-full")}>
<components::Loading />
</div>
} else {
<div class={classes!("column", "is-full")}>
<components::UserPane
name={&ctx.props().name}
repositories={
self.repositories
.iter()
.map(|repo| components::user_pane::Repository {
name: repo.name.to_owned(),
url: Some(repo.url.to_owned())
})
.collect::<Vec<_>>()
}
/>
</div>
}
</div>
</div>
</div>
</>
}
}
}

67
frontend/src/stores.rs Normal file
View file

@ -0,0 +1,67 @@
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::num::Wrapping;
use yewdux::prelude::*;
use crate::components;
#[derive(PartialEq, Serialize, Deserialize, Debug)]
pub struct UserData {
pub username: String,
pub password: String,
}
#[derive(Default, PartialEq, Serialize, Deserialize, Store, Debug)]
#[store(storage = "local")]
pub struct User(pub Option<UserData>);
impl User {
pub fn logged_in(&self) -> bool {
self.0.is_some()
}
}
#[derive(Clone, PartialEq)]
pub struct Notification {
pub notification_type: components::notification::NotificationType,
pub message: Option<components::notification::NotificationMessage>,
}
macro_rules! from_notification_types {
($($type:ident),*) => {
$(
paste::item! {
pub fn [<$type:snake>](message: Option<components::notification::NotificationMessage>) -> Self {
Self {
notification_type: components::notification::NotificationType::$type,
message,
}
}
}
)*
};
}
impl Notification {
from_notification_types!(Dark, Primary, Link, Info, Success, Warning, Danger);
}
#[derive(Default, Clone, PartialEq, Store)]
pub struct Notifications {
counter: Wrapping<usize>,
pub notifications: BTreeMap<usize, Notification>,
}
impl Notifications {
fn inc(&mut self) {
self.counter += 1;
}
pub fn push(&mut self, notif: Notification) -> usize {
let id = self.counter.0;
self.notifications.insert(id, notif);
self.inc();
id
}
}