feat(web/converse): Import repository

Imports the converse forum software I wrote a few years ago. I want to
clean this up a bit and try using Hotwire with it.

Note: The original repository was AGPL-3.0 licensed. I'm the copyright
holder and have relicensed it to GPL-3.0 in the commit that is being
merged.

Imported from: https://github.com/tazjin/converse

git-subtree-dir: web/converse
git-subtree-mainline: 386afdc794
git-subtree-split: 09168021e7
Change-Id: Ia8b587db5174ef5b3c52910d3d027199150c58e0
This commit is contained in:
Vincent Ambo 2021-04-05 16:55:10 +02:00
commit 8142149e28
54 changed files with 11309 additions and 0 deletions

1
web/converse/.gitattributes vendored Normal file
View file

@ -0,0 +1 @@
Cargo.nix linguist-generated=true

3
web/converse/.gitignore vendored Normal file
View file

@ -0,0 +1,3 @@
.envrc
/target/
**/*.rs.bk

2
web/converse/.travis.yml Normal file
View file

@ -0,0 +1,2 @@
language: nix
sudo: true

View file

@ -0,0 +1,29 @@
A SERMON ON ETHICS AND LOVE
===========================
One day Mal-2 asked the messenger spirit Saint Gulik to approach the
Goddess and request Her presence for some desperate advice. Shortly
afterwards the radio came on by itself, and an ethereal female Voice
said **YES?**
"O! Eris! Blessed Mother of Man! Queen of Chaos! Daughter of Discord!
Concubine of Confusion! O! Exquisite Lady, I beseech You to lift a
heavy burden from my heart!"
**WHAT BOTHERS YOU, MAL? YOU DON'T SOUND WELL.**
"I am filled with fear and tormented with terrible visions of pain.
Everywhere people are hurting one another, the planet is rampant with
injustices, whole societies plunder groups of their own people,
mothers imprison sons, children perish while brothers war. O, woe."
**WHAT IS THE MATTER WITH THAT, IF IT IS WHAT YOU WANT TO DO?**
"But nobody Wants it! Everybody hates it."
**OH. WELL, THEN *STOP*.**
At which moment She turned herself into an aspirin commercial and left
The Polyfather stranded alone with his species.
SINISTER DEXTER HAS A BROKEN SPIROMETER.

View file

@ -0,0 +1,114 @@
Contribution Guidelines
=======================
<!-- markdown-toc start - Don't edit this section. Run M-x markdown-toc-refresh-toc -->
**Table of Contents**
- [Contribution Guidelines](#contribution-guidelines)
- [Before making a change](#before-making-a-change)
- [Commit messages](#commit-messages)
- [Commit content](#commit-content)
- [Code quality](#code-quality)
- [Builds & tests](#builds--tests)
<!-- markdown-toc end -->
This is a loose set of "guidelines" for contributing to my projects.
Please note that I will not accept any pull requests that don't follow
these guidelines.
Also consider the [code of conduct](CODE_OF_CONDUCT.md). No really,
you should.
## Before making a change
Before making a change, consider your motivation for making the
change. Documentation updates, bug fixes and the like are *always*
welcome.
When adding a feature you should consider whether it is only useful
for your particular use-case or whether it is generally applicable for
other users of the project.
When in doubt - just ask me!
## Commit messages
All commit messages should follow the style-guide used by the [Angular
project][]. This means for the most part that your commit message
should be structured like this:
```
type(scope): Subject line with at most 68 a character length
Body of the commit message with an empty line between subject and
body. This text should explain what the change does and why it has
been made, *especially* if it introduces a new feature.
Relevant issues should be mentioned if they exist.
```
Where `type` can be one of:
* `feat`: A new feature has been introduced
* `fix`: An issue of some kind has been fixed
* `docs`: Documentation or comments have been updated
* `style`: Formatting changes only
* `refactor`: Hopefully self-explanatory!
* `test`: Added missing tests / fixed tests
* `chore`: Maintenance work
And `scope` should refer to some kind of logical grouping inside of
the project.
Please take a look at the existing commit log for examples.
## Commit content
Multiple changes should be divided into multiple git commits whenever
possible. Common sense applies.
The fix for a single-line whitespace issue is fine to include in a
different commit. Introducing a new feature and refactoring
(unrelated) code in the same commit is not fine.
`git commit -a` is generally **taboo**.
In my experience making "sane" commits becomes *significantly* easier
as developer tooling is improved. The interface to `git` that I
recommend is [magit][]. Even if you are not yet an Emacs user, it
makes sense to install Emacs just to be able to use magit - it is
really that good.
For staging sane chunks on the command line with only git, consider
`git add -p`.
## Code quality
This one should go without saying - but please ensure that your code
quality does not fall below the rest of the project. This is of course
very subjective, but as an example if you place code that throws away
errors into a block in which errors are handled properly your change
will be rejected.
In my experience there is a strong correlation between the visual
appearance of a code block and its quality. This is a simple way to
sanity-check your work while squinting and keeping some distance from
your screen ;-)
## Builds & tests
Most of my projects are built using [Nix][] to avoid "build pollution"
via the user's environment. If you have Nix installed and are
contributing to a project that has a `default.nix`, consider using
`nix-build` to verify that builds work correctly.
If the project has tests, check that they still work before submitting
your change.
Both of these will usually be covered by Travis CI.
[Angular project]: https://gist.github.com/stephenparish/9941e89d80e2bc58a153#format-of-the-commit-message
[magit]: https://magit.vc/
[Nix]: https://nixos.org/nix/

2407
web/converse/Cargo.lock generated Normal file

File diff suppressed because it is too large Load diff

5384
web/converse/Cargo.nix generated Normal file

File diff suppressed because it is too large Load diff

35
web/converse/Cargo.toml Normal file
View file

@ -0,0 +1,35 @@
[package]
name = "converse"
version = "0.1.0"
authors = ["Vincent Ambo <mail@tazj.in>"]
license = "AGPL-3.0-or-later"
[dependencies]
actix = "0.5"
actix-web = "0.6"
askama = "0.6"
chrono = { version = "0.4", features = ["serde"] }
comrak = "0.2"
diesel = { version = "1.2", features = ["postgres", "chrono", "r2d2"]}
env_logger = "0.5"
failure = "0.1"
futures = "0.1"
hyper = "0.11"
log = "0.4"
md5 = "0.3.7"
mime_guess = "2.0.0-alpha"
pq-sys = "=0.4.4"
r2d2 = "0.8"
rand = "0.4"
reqwest = "0.8"
serde = "1.0"
serde_derive = "1.0"
serde_json = "1.0"
tokio = "0.1"
tokio-timer = "0.2"
url = "1.7"
url_serde = "0.2"
[build-dependencies]
pulldown-cmark = "0.1"
askama = "0.6"

674
web/converse/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>.

14
web/converse/README.org Normal file
View file

@ -0,0 +1,14 @@
#+TITLE: Converse
#+AUTHOR: Vincent Ambo
Welcome to Converse, a work-in-progress forum software written in
Rust. The intention behind Converse is to provide a simple forum-like
experience.
There is not a lot of documentation about Converse yet and it has
several known issues. Also note that Converse is being developed for a
specific use-case and is not going to be a forum feature kitchen-sink
like most classical forum softwares.
Better documentation is forthcoming once the remaining basics have
been taken care of.

5
web/converse/build.rs Normal file
View file

@ -0,0 +1,5 @@
extern crate askama;
fn main() {
askama::rerun_if_templates_changed();
}

18
web/converse/default.nix Normal file
View file

@ -0,0 +1,18 @@
# This Nix derivation imports the generated Carnix sources and builds
# Converse.
#
# To work around an issue in Carnix ([1] & [2]) the attributes of the
# comrak crate have been overridden with a dummy environment variable
# to simulate a Cargo-based build. This requires a manual change to
# `Cargo.nix` when updating dependencies.
#
# [1]: https://nest.pijul.com/pmeunier/carnix/discussions/2
# [2]: https://nest.pijul.com/pmeunier/carnix/discussions/3
{ pkgs ? import <nixpkgs> {}, ... }:
let cargo = pkgs.callPackage ./Cargo.nix {};
in {
# Build is not yet fixed up for the depot.
meta.ci = false;
}

View file

@ -0,0 +1,14 @@
# This is an example configuration for running converse during
# development using direnv:
# https://github.com/direnv/direnv
#
# The OIDC actor is configured with bogus values as disabling logins
# never causes it to run anyways.
export DATABASE_URL=postgres://converse:converse@localhost/converse
export RUST_LOG=info
export OIDC_DISCOVERY_URL=https://does.not.matter.com/
export OIDC_CLIENT_ID=some-client-id
export OIDC_CLIENT_SECRET='some-client-secret'
export BASE_URL=http://localhost:4567
export REQUIRE_LOGIN=false

View file

View file

@ -0,0 +1,6 @@
-- This file was automatically created by Diesel to setup helper functions
-- and other internal bookkeeping. This file is safe to edit, any future
-- changes will be added to existing projects as new migrations.
DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass);
DROP FUNCTION IF EXISTS diesel_set_updated_at();

View file

@ -0,0 +1,36 @@
-- This file was automatically created by Diesel to setup helper functions
-- and other internal bookkeeping. This file is safe to edit, any future
-- changes will be added to existing projects as new migrations.
-- Sets up a trigger for the given table to automatically set a column called
-- `updated_at` whenever the row is modified (unless `updated_at` was included
-- in the modified columns)
--
-- # Example
--
-- ```sql
-- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW());
--
-- SELECT diesel_manage_updated_at('users');
-- ```
CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$
BEGIN
EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s
FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl);
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$
BEGIN
IF (
NEW IS DISTINCT FROM OLD AND
NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at
) THEN
NEW.updated_at := current_timestamp;
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;

View file

@ -0,0 +1,2 @@
DROP TABLE posts;
DROP TABLE threads;

View file

@ -0,0 +1,13 @@
CREATE TABLE threads (
id SERIAL PRIMARY KEY,
title VARCHAR NOT NULL,
body TEXT NOT NULL,
posted TIMESTAMPTZ NOT NULL
);
CREATE TABLE posts (
id SERIAL PRIMARY KEY,
thread SERIAL REFERENCES threads (id),
body TEXT NOT NULL,
posted TIMESTAMPTZ NOT NULL
);

View file

@ -0,0 +1 @@
ALTER TABLE posts RENAME COLUMN thread_id TO thread;

View file

@ -0,0 +1 @@
ALTER TABLE posts RENAME COLUMN thread TO thread_id;

View file

@ -0,0 +1,2 @@
ALTER TABLE threads ALTER COLUMN posted DROP DEFAULT;
ALTER TABLE posts ALTER COLUMN posted DROP DEFAULT;

View file

@ -0,0 +1,2 @@
ALTER TABLE threads ALTER COLUMN posted SET DEFAULT (NOW() AT TIME ZONE 'UTC');
ALTER TABLE posts ALTER COLUMN posted SET DEFAULT (NOW() AT TIME ZONE 'UTC');

View file

@ -0,0 +1,5 @@
ALTER TABLE threads DROP COLUMN author_name;
ALTER TABLE threads DROP COLUMN author_email;
ALTER TABLE posts DROP COLUMN author_name;
ALTER TABLE posts DROP COLUMN author_email;

View file

@ -0,0 +1,10 @@
-- This migration adds an 'author' column to the thread & post table.
-- Authors don't currently exist as independent objects in the
-- database as most user management is simply delegated to the OIDC
-- provider.
ALTER TABLE threads ADD COLUMN author_name VARCHAR NOT NULL DEFAULT 'anonymous';
ALTER TABLE threads ADD COLUMN author_email VARCHAR NOT NULL DEFAULT 'unknown@example.org';
ALTER TABLE posts ADD COLUMN author_name VARCHAR NOT NULL DEFAULT 'anonymous';
ALTER TABLE posts ADD COLUMN author_email VARCHAR NOT NULL DEFAULT 'unknown@example.org';

View file

@ -0,0 +1 @@
ALTER TABLE threads ADD COLUMN body TEXT NOT NULL DEFAULT '';

View file

@ -0,0 +1,6 @@
-- Instead of storing the thread OP in the thread table, this will
-- make it a post as well.
-- At the time at which this migration was created no important data
-- existed in any converse instances, so data is not moved.
ALTER TABLE threads DROP COLUMN body;

View file

@ -0,0 +1,2 @@
DROP VIEW thread_index;
ALTER TABLE threads DROP COLUMN sticky;

View file

@ -0,0 +1,21 @@
-- Add support for stickies in threads
ALTER TABLE threads ADD COLUMN sticky BOOLEAN NOT NULL DEFAULT FALSE;
-- CREATE a simple view that returns the list of threads ordered by
-- the last post that occured in the thread.
CREATE VIEW thread_index AS
SELECT t.id AS thread_id,
t.title AS title,
t.author_name AS thread_author,
t.posted AS created,
t.sticky AS sticky,
p.id AS post_id,
p.author_name AS post_author,
p.posted AS posted
FROM threads t
JOIN (SELECT DISTINCT ON (thread_id)
id, thread_id, author_name, posted
FROM posts
ORDER BY thread_id, id DESC) AS p
ON t.id = p.thread_id
ORDER BY t.sticky DESC, p.id DESC;

View file

@ -0,0 +1,2 @@
DROP INDEX idx_fts_search;
DROP MATERIALIZED VIEW search_index;

View file

@ -0,0 +1,21 @@
-- Prepare a materialised view containing the tsvector data for all
-- threads and posts. This view is indexed using a GIN-index to enable
-- performant full-text searches.
--
-- For now the query language is hardcoded to be English.
CREATE MATERIALIZED VIEW search_index AS
SELECT p.id AS post_id,
p.author_name AS author,
t.id AS thread_id,
t.title AS title,
p.body AS body,
setweight(to_tsvector('english', t.title), 'B') ||
setweight(to_tsvector('english', p.body), 'A') ||
setweight(to_tsvector('simple', t.author_name), 'C') ||
setweight(to_tsvector('simple', p.author_name), 'C') AS document
FROM posts p
JOIN threads t
ON t.id = p.thread_id;
CREATE INDEX idx_fts_search ON search_index USING gin(document);

View file

@ -0,0 +1,63 @@
-- First restore the old columns:
ALTER TABLE threads ADD COLUMN author_name VARCHAR;
ALTER TABLE threads ADD COLUMN author_email VARCHAR;
ALTER TABLE posts ADD COLUMN author_name VARCHAR;
ALTER TABLE posts ADD COLUMN author_email VARCHAR;
-- Then select the data back into them:
UPDATE threads SET author_name = users.name,
author_email = users.email
FROM users
WHERE threads.user_id = users.id;
UPDATE posts SET author_name = users.name,
author_email = users.email
FROM users
WHERE posts.user_id = users.id;
-- add the constraints back:
ALTER TABLE threads ALTER COLUMN author_name SET NOT NULL;
ALTER TABLE threads ALTER COLUMN author_email SET NOT NULL;
ALTER TABLE posts ALTER COLUMN author_name SET NOT NULL;
ALTER TABLE posts ALTER COLUMN author_email SET NOT NULL;
-- reset the index view:
CREATE OR REPLACE VIEW thread_index AS
SELECT t.id AS thread_id,
t.title AS title,
t.author_name AS thread_author,
t.posted AS created,
t.sticky AS sticky,
p.id AS post_id,
p.author_name AS post_author,
p.posted AS posted
FROM threads t
JOIN (SELECT DISTINCT ON (thread_id)
id, thread_id, author_name, posted
FROM posts
ORDER BY thread_id, id DESC) AS p
ON t.id = p.thread_id
ORDER BY t.sticky DESC, p.id DESC;
-- reset the search view:
DROP MATERIALIZED VIEW search_index;
CREATE MATERIALIZED VIEW search_index AS
SELECT p.id AS post_id,
p.author_name AS author,
t.id AS thread_id,
t.title AS title,
p.body AS body,
setweight(to_tsvector('english', t.title), 'B') ||
setweight(to_tsvector('english', p.body), 'A') ||
setweight(to_tsvector('simple', t.author_name), 'C') ||
setweight(to_tsvector('simple', p.author_name), 'C') AS document
FROM posts p
JOIN threads t
ON t.id = p.thread_id;
CREATE INDEX idx_fts_search ON search_index USING gin(document);
-- and drop the users table and columns:
ALTER TABLE posts DROP COLUMN user_id;
ALTER TABLE threads DROP COLUMN user_id;
DROP TABLE users;

View file

@ -0,0 +1,83 @@
-- This query creates a users table and migrates the existing user
-- information (from the posts table) into it.
CREATE TABLE users (
id SERIAL PRIMARY KEY,
email VARCHAR NOT NULL UNIQUE,
name VARCHAR NOT NULL,
admin BOOLEAN NOT NULL DEFAULT false
);
-- Insert the 'anonymous' user explicitly:
INSERT INTO users (name, email)
VALUES ('Anonymous', 'anonymous@nothing.org');
INSERT INTO users (id, email, name)
SELECT nextval('users_id_seq'),
author_email AS email,
author_name AS name
FROM posts
WHERE author_email != 'anonymous@nothing.org'
GROUP BY name, email;
-- Create the 'user_id' column in the relevant tables (initially
-- without a not-null constraint) and populate it with the data
-- selected above:
ALTER TABLE posts ADD COLUMN user_id INTEGER REFERENCES users (id);
UPDATE posts SET user_id = users.id
FROM users
WHERE users.email = posts.author_email;
ALTER TABLE threads ADD COLUMN user_id INTEGER REFERENCES users (id);
UPDATE threads SET user_id = users.id
FROM users
WHERE users.email = threads.author_email;
-- Add the constraints:
ALTER TABLE posts ALTER COLUMN user_id SET NOT NULL;
ALTER TABLE threads ALTER COLUMN user_id SET NOT NULL;
-- Update the index view:
CREATE OR REPLACE VIEW thread_index AS
SELECT t.id AS thread_id,
t.title AS title,
ta.name AS thread_author,
t.posted AS created,
t.sticky AS sticky,
p.id AS post_id,
pa.name AS post_author,
p.posted AS posted
FROM threads t
JOIN (SELECT DISTINCT ON (thread_id)
id, thread_id, user_id, posted
FROM posts
ORDER BY thread_id, id DESC) AS p
ON t.id = p.thread_id
JOIN users ta ON ta.id = t.user_id
JOIN users pa ON pa.id = p.user_id
ORDER BY t.sticky DESC, p.id DESC;
-- Update the search view:
DROP MATERIALIZED VIEW search_index;
CREATE MATERIALIZED VIEW search_index AS
SELECT p.id AS post_id,
pa.name AS author,
t.id AS thread_id,
t.title AS title,
p.body AS body,
setweight(to_tsvector('english', t.title), 'B') ||
setweight(to_tsvector('english', p.body), 'A') ||
setweight(to_tsvector('simple', ta.name), 'C') ||
setweight(to_tsvector('simple', pa.name), 'C') AS document
FROM posts p
JOIN threads t ON t.id = p.thread_id
JOIN users ta ON ta.id = t.user_id
JOIN users pa ON pa.id = p.user_id;
CREATE INDEX idx_fts_search ON search_index USING gin(document);
-- And drop the old fields:
ALTER TABLE posts DROP COLUMN author_name;
ALTER TABLE posts DROP COLUMN author_email;
ALTER TABLE threads DROP COLUMN author_name;
ALTER TABLE threads DROP COLUMN author_email;

View file

@ -0,0 +1 @@
DROP VIEW simple_posts;

View file

@ -0,0 +1,11 @@
-- Creates a view for listing posts akin to the post table before
-- splitting out users. This exists to avoid having to do joining
-- logic and such inside of the application.
CREATE VIEW simple_posts AS
SELECT p.id AS id,
thread_id, body, posted, user_id,
users.name AS author_name,
users.email AS author_email
FROM posts p
JOIN users ON users.id = p.user_id;

View file

@ -0,0 +1 @@
ALTER TABLE threads DROP COLUMN closed;

View file

@ -0,0 +1 @@
ALTER TABLE threads ADD COLUMN closed BOOLEAN NOT NULL DEFAULT false;

View file

@ -0,0 +1,30 @@
-- Update the index view:
DROP VIEW thread_index;
CREATE VIEW thread_index AS
SELECT t.id AS thread_id,
t.title AS title,
ta.name AS thread_author,
t.posted AS created,
t.sticky AS sticky,
p.id AS post_id,
pa.name AS post_author,
p.posted AS posted
FROM threads t
JOIN (SELECT DISTINCT ON (thread_id)
id, thread_id, user_id, posted
FROM posts
ORDER BY thread_id, id DESC) AS p
ON t.id = p.thread_id
JOIN users ta ON ta.id = t.user_id
JOIN users pa ON pa.id = p.user_id
ORDER BY t.sticky DESC, p.id DESC;
-- Update the post view:
DROP VIEW simple_posts;
CREATE VIEW simple_posts AS
SELECT p.id AS id,
thread_id, body, posted, user_id,
users.name AS author_name,
users.email AS author_email
FROM posts p
JOIN users ON users.id = p.user_id;

View file

@ -0,0 +1,35 @@
-- Update the index view:
DROP VIEW thread_index;
CREATE VIEW thread_index AS
SELECT t.id AS thread_id,
t.title AS title,
ta.name AS thread_author,
t.posted AS created,
t.sticky AS sticky,
t.closed AS closed,
p.id AS post_id,
pa.name AS post_author,
p.posted AS posted
FROM threads t
JOIN (SELECT DISTINCT ON (thread_id)
id, thread_id, user_id, posted
FROM posts
ORDER BY thread_id, id DESC) AS p
ON t.id = p.thread_id
JOIN users ta ON ta.id = t.user_id
JOIN users pa ON pa.id = p.user_id
ORDER BY t.sticky DESC, p.id DESC;
-- Update post view:
DROP VIEW simple_posts;
CREATE VIEW simple_posts AS
SELECT p.id AS id,
thread_id, body,
p.posted AS posted,
p.user_id AS user_id,
threads.closed AS closed,
users.name AS author_name,
users.email AS author_email
FROM posts p
JOIN users ON users.id = p.user_id
JOIN threads ON threads.id = p.thread_id;

282
web/converse/src/db.rs Normal file
View file

@ -0,0 +1,282 @@
// Copyright (C) 2018-2021 Vincent Ambo <tazjin@tvl.su>
//
// This file is part of Converse.
//
// 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/>.
//! This module implements the database connection actor.
use actix::prelude::*;
use diesel::{self, sql_query};
use diesel::sql_types::Text;
use diesel::prelude::*;
use diesel::r2d2::{Pool, ConnectionManager};
use models::*;
use errors::{ConverseError, Result};
/// The DB actor itself. Several of these will be run in parallel by
/// `SyncArbiter`.
pub struct DbExecutor(pub Pool<ConnectionManager<PgConnection>>);
impl Actor for DbExecutor {
type Context = SyncContext<Self>;
}
/// Message used to request a list of threads.
/// TODO: This should support page numbers.
pub struct ListThreads;
message!(ListThreads, Result<Vec<ThreadIndex>>);
impl Handler<ListThreads> for DbExecutor {
type Result = <ListThreads as Message>::Result;
fn handle(&mut self, _: ListThreads, _: &mut Self::Context) -> Self::Result {
use schema::thread_index::dsl::*;
let conn = self.0.get()?;
let results = thread_index
.load::<ThreadIndex>(&conn)?;
Ok(results)
}
}
/// Message used to look up a user based on their email-address. If
/// the user does not exist, it is created.
pub struct LookupOrCreateUser {
pub email: String,
pub name: String,
}
message!(LookupOrCreateUser, Result<User>);
impl Handler<LookupOrCreateUser> for DbExecutor {
type Result = <LookupOrCreateUser as Message>::Result;
fn handle(&mut self,
msg: LookupOrCreateUser,
_: &mut Self::Context) -> Self::Result {
use schema::users;
use schema::users::dsl::*;
let conn = self.0.get()?;
let opt_user = users
.filter(email.eq(&msg.email))
.first(&conn).optional()?;
if let Some(user) = opt_user {
Ok(user)
} else {
let new_user = NewUser {
email: msg.email,
name: msg.name,
};
let user: User = diesel::insert_into(users::table)
.values(&new_user)
.get_result(&conn)?;
info!("Created new user {} with ID {}", new_user.email, user.id);
Ok(user)
}
}
}
/// Message used to fetch a specific thread. Returns the thread and
/// its posts.
pub struct GetThread(pub i32);
message!(GetThread, Result<(Thread, Vec<SimplePost>)>);
impl Handler<GetThread> for DbExecutor {
type Result = <GetThread as Message>::Result;
fn handle(&mut self, msg: GetThread, _: &mut Self::Context) -> Self::Result {
use schema::threads::dsl::*;
use schema::simple_posts::dsl::id;
let conn = self.0.get()?;
let thread_result: Thread = threads
.find(msg.0).first(&conn)?;
let post_list = SimplePost::belonging_to(&thread_result)
.order_by(id.asc())
.load::<SimplePost>(&conn)?;
Ok((thread_result, post_list))
}
}
/// Message used to fetch a specific post.
#[derive(Deserialize, Debug)]
pub struct GetPost { pub id: i32 }
message!(GetPost, Result<SimplePost>);
impl Handler<GetPost> for DbExecutor {
type Result = <GetPost as Message>::Result;
fn handle(&mut self, msg: GetPost, _: &mut Self::Context) -> Self::Result {
use schema::simple_posts::dsl::*;
let conn = self.0.get()?;
Ok(simple_posts.find(msg.id).first(&conn)?)
}
}
/// Message used to update the content of a post.
#[derive(Deserialize)]
pub struct UpdatePost {
pub post_id: i32,
pub post: String,
}
message!(UpdatePost, Result<Post>);
impl Handler<UpdatePost> for DbExecutor {
type Result = Result<Post>;
fn handle(&mut self, msg: UpdatePost, _: &mut Self::Context) -> Self::Result {
use schema::posts::dsl::*;
let conn = self.0.get()?;
let updated = diesel::update(posts.find(msg.post_id))
.set(body.eq(msg.post))
.get_result(&conn)?;
Ok(updated)
}
}
/// Message used to create a new thread
pub struct CreateThread {
pub new_thread: NewThread,
pub post: String,
}
message!(CreateThread, Result<Thread>);
impl Handler<CreateThread> for DbExecutor {
type Result = <CreateThread as Message>::Result;
fn handle(&mut self, msg: CreateThread, _: &mut Self::Context) -> Self::Result {
use schema::threads;
use schema::posts;
let conn = self.0.get()?;
conn.transaction::<Thread, ConverseError, _>(|| {
// First insert the thread structure itself
let thread: Thread = diesel::insert_into(threads::table)
.values(&msg.new_thread)
.get_result(&conn)?;
// ... then create the first post in the thread.
let new_post = NewPost {
thread_id: thread.id,
body: msg.post,
user_id: msg.new_thread.user_id,
};
diesel::insert_into(posts::table)
.values(&new_post)
.execute(&conn)?;
Ok(thread)
})
}
}
/// Message used to create a new reply
pub struct CreatePost(pub NewPost);
message!(CreatePost, Result<Post>);
impl Handler<CreatePost> for DbExecutor {
type Result = <CreatePost as Message>::Result;
fn handle(&mut self, msg: CreatePost, _: &mut Self::Context) -> Self::Result {
use schema::posts;
let conn = self.0.get()?;
let closed: bool = {
use schema::threads::dsl::*;
threads.select(closed)
.find(msg.0.thread_id)
.first(&conn)?
};
if closed {
return Err(ConverseError::ThreadClosed {
id: msg.0.thread_id
})
}
Ok(diesel::insert_into(posts::table)
.values(&msg.0)
.get_result(&conn)?)
}
}
/// Message used to search for posts
#[derive(Deserialize)]
pub struct SearchPosts { pub query: String }
message!(SearchPosts, Result<Vec<SearchResult>>);
/// Raw PostgreSQL query used to perform full-text search on posts
/// with a supplied phrase. For now, the query language is hardcoded
/// to English and only "plain" queries (i.e. no searches for exact
/// matches or more advanced query syntax) are supported.
const SEARCH_QUERY: &'static str = r#"
WITH search_query (query) AS (VALUES (plainto_tsquery('english', $1)))
SELECT post_id,
thread_id,
author,
title,
ts_headline('english', body, query) AS headline
FROM search_index, search_query
WHERE document @@ query
ORDER BY ts_rank(document, query) DESC
LIMIT 50
"#;
impl Handler<SearchPosts> for DbExecutor {
type Result = <SearchPosts as Message>::Result;
fn handle(&mut self, msg: SearchPosts, _: &mut Self::Context) -> Self::Result {
let conn = self.0.get()?;
let search_results = sql_query(SEARCH_QUERY)
.bind::<Text, _>(msg.query)
.get_results::<SearchResult>(&conn)?;
Ok(search_results)
}
}
/// Message that triggers a refresh of the view used for full-text
/// searching.
pub struct RefreshSearchView;
message!(RefreshSearchView, Result<()>);
const REFRESH_QUERY: &'static str = "REFRESH MATERIALIZED VIEW search_index";
impl Handler<RefreshSearchView> for DbExecutor {
type Result = Result<()>;
fn handle(&mut self, _: RefreshSearchView, _: &mut Self::Context) -> Self::Result {
let conn = self.0.get()?;
debug!("Refreshing search_index view in DB");
sql_query(REFRESH_QUERY).execute(&conn)?;
Ok(())
}
}

133
web/converse/src/errors.rs Normal file
View file

@ -0,0 +1,133 @@
// Copyright (C) 2018-2021 Vincent Ambo <tazjin@tvl.su>
//
// This file is part of Converse.
//
// 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/>.
//! This module defines custom error types using the `failure`-crate.
//! Links to foreign error types (such as database connection errors)
//! are established in a similar way as was tradition in
//! `error_chain`, albeit manually.
use std::result;
use actix_web::{ResponseError, HttpResponse};
use actix_web::http::StatusCode;
// Modules with foreign errors:
use actix;
use actix_web;
use askama;
use diesel;
use r2d2;
use reqwest;
use tokio_timer;
pub type Result<T> = result::Result<T, ConverseError>;
#[derive(Debug, Fail)]
pub enum ConverseError {
#[fail(display = "an internal Converse error occured: {}", reason)]
InternalError { reason: String },
#[fail(display = "a database error occured: {}", error)]
Database { error: diesel::result::Error },
#[fail(display = "a database connection pool error occured: {}", error)]
ConnectionPool { error: r2d2::Error },
#[fail(display = "a template rendering error occured: {}", reason)]
Template { reason: String },
#[fail(display = "error occured during request handling: {}", error)]
ActixWeb { error: actix_web::Error },
#[fail(display = "error occured running timer: {}", error)]
Timer { error: tokio_timer::Error },
#[fail(display = "user {} does not have permission to edit post {}", user, id)]
PostEditForbidden { user: i32, id: i32 },
#[fail(display = "thread {} is closed and can not be responded to", id)]
ThreadClosed { id: i32 },
// This variant is used as a catch-all for wrapping
// actix-web-compatible response errors, such as the errors it
// throws itself.
#[fail(display = "Actix response error: {}", error)]
Actix { error: Box<ResponseError> },
}
// Establish conversion links to foreign errors:
impl From<diesel::result::Error> for ConverseError {
fn from(error: diesel::result::Error) -> ConverseError {
ConverseError::Database { error }
}
}
impl From<r2d2::Error> for ConverseError {
fn from(error: r2d2::Error) -> ConverseError {
ConverseError::ConnectionPool { error }
}
}
impl From<askama::Error> for ConverseError {
fn from(error: askama::Error) -> ConverseError {
ConverseError::Template {
reason: format!("{}", error),
}
}
}
impl From<actix::MailboxError> for ConverseError {
fn from(error: actix::MailboxError) -> ConverseError {
ConverseError::Actix { error: Box::new(error) }
}
}
impl From<actix_web::Error> for ConverseError {
fn from(error: actix_web::Error) -> ConverseError {
ConverseError::ActixWeb { error }
}
}
impl From<reqwest::Error> for ConverseError {
fn from(error: reqwest::Error) -> ConverseError {
ConverseError::InternalError {
reason: format!("Failed to make HTTP request: {}", error),
}
}
}
impl From<tokio_timer::Error> for ConverseError {
fn from(error: tokio_timer::Error) -> ConverseError {
ConverseError::Timer { error }
}
}
// Support conversion of error type into HTTP error responses:
impl ResponseError for ConverseError {
fn error_response(&self) -> HttpResponse {
// Everything is mapped to internal server errors for now.
match *self {
ConverseError::ThreadClosed { id } => HttpResponse::SeeOther()
.header("Location", format!("/thread/{}#post-reply", id))
.finish(),
_ => HttpResponse::build(StatusCode::INTERNAL_SERVER_ERROR)
.body(format!("An error occured: {}", self))
}
}
}

View file

@ -0,0 +1,345 @@
// Copyright (C) 2018-2021 Vincent Ambo <tazjin@tvl.su>
//
// This file is part of Converse.
//
// 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/>.
//! This module contains the implementation of converse's actix-web
//! HTTP handlers.
//!
//! Most handlers have an associated rendering function using one of
//! the tera templates stored in the `/templates` directory in the
//! project root.
use actix::prelude::*;
use actix_web::*;
use actix_web::http::Method;
use actix_web::middleware::identity::RequestIdentity;
use actix_web::middleware::{Started, Middleware};
use actix_web;
use db::*;
use errors::ConverseError;
use futures::Future;
use mime_guess::guess_mime_type;
use models::*;
use oidc::*;
use render::*;
type ConverseResponse = Box<Future<Item=HttpResponse, Error=ConverseError>>;
const HTML: &'static str = "text/html";
const ANONYMOUS: i32 = 1;
const NEW_THREAD_LENGTH_ERR: &'static str = "Title and body can not be empty!";
/// Represents the state carried by the web server actors.
pub struct AppState {
/// Address of the database actor
pub db: Addr<Syn, DbExecutor>,
/// Address of the OIDC actor
pub oidc: Addr<Syn, OidcExecutor>,
/// Address of the rendering actor
pub renderer: Addr<Syn, Renderer>,
}
pub fn forum_index(state: State<AppState>) -> ConverseResponse {
state.db.send(ListThreads)
.flatten()
.and_then(move |res| state.renderer.send(IndexPage {
threads: res
}).from_err())
.flatten()
.map(|res| HttpResponse::Ok().content_type(HTML).body(res))
.responder()
}
/// Returns the ID of the currently logged in user. If there is no ID
/// present, the ID of the anonymous user will be returned.
pub fn get_user_id(req: &HttpRequest<AppState>) -> i32 {
if let Some(id) = req.identity() {
// If this .expect() call is triggered, someone is likely
// attempting to mess with their cookies. These requests can
// be allowed to fail without further ado.
id.parse().expect("Session cookie contained invalid data!")
} else {
ANONYMOUS
}
}
/// This handler retrieves and displays a single forum thread.
pub fn forum_thread(state: State<AppState>,
req: HttpRequest<AppState>,
thread_id: Path<i32>) -> ConverseResponse {
let id = thread_id.into_inner();
let user = get_user_id(&req);
state.db.send(GetThread(id))
.flatten()
.and_then(move |res| state.renderer.send(ThreadPage {
current_user: user,
thread: res.0,
posts: res.1,
}).from_err())
.flatten()
.map(|res| HttpResponse::Ok().content_type(HTML).body(res))
.responder()
}
/// This handler presents the user with the "New Thread" form.
pub fn new_thread(state: State<AppState>) -> ConverseResponse {
state.renderer.send(NewThreadPage::default()).flatten()
.map(|res| HttpResponse::Ok().content_type(HTML).body(res))
.responder()
}
#[derive(Deserialize)]
pub struct NewThreadForm {
pub title: String,
pub post: String,
}
/// This handler receives a "New thread"-form and redirects the user
/// to the new thread after creation.
pub fn submit_thread(state: State<AppState>,
input: Form<NewThreadForm>,
req: HttpRequest<AppState>) -> ConverseResponse {
// Trim whitespace out of inputs:
let input = NewThreadForm {
title: input.title.trim().into(),
post: input.post.trim().into(),
};
// Perform simple validation and abort here if it fails:
if input.title.is_empty() || input.post.is_empty() {
return state.renderer
.send(NewThreadPage {
alerts: vec![NEW_THREAD_LENGTH_ERR],
title: Some(input.title),
post: Some(input.post),
})
.flatten()
.map(|res| HttpResponse::Ok().content_type(HTML).body(res))
.responder();
}
let user_id = get_user_id(&req);
let new_thread = NewThread {
user_id,
title: input.title,
};
let msg = CreateThread {
new_thread,
post: input.post,
};
state.db.send(msg)
.from_err()
.and_then(move |res| {
let thread = res?;
info!("Created new thread \"{}\" with ID {}", thread.title, thread.id);
Ok(HttpResponse::SeeOther()
.header("Location", format!("/thread/{}", thread.id))
.finish())
})
.responder()
}
#[derive(Deserialize)]
pub struct NewPostForm {
pub thread_id: i32,
pub post: String,
}
/// This handler receives a "Reply"-form and redirects the user to the
/// new post after creation.
pub fn reply_thread(state: State<AppState>,
input: Form<NewPostForm>,
req: HttpRequest<AppState>) -> ConverseResponse {
let user_id = get_user_id(&req);
let new_post = NewPost {
user_id,
thread_id: input.thread_id,
body: input.post.trim().into(),
};
state.db.send(CreatePost(new_post))
.flatten()
.from_err()
.and_then(move |post| {
info!("Posted reply {} to thread {}", post.id, post.thread_id);
Ok(HttpResponse::SeeOther()
.header("Location", format!("/thread/{}#post-{}", post.thread_id, post.id))
.finish())
})
.responder()
}
/// This handler presents the user with the form to edit a post. If
/// the user attempts to edit a post that they do not have access to,
/// they are currently ungracefully redirected back to the post
/// itself.
pub fn edit_form(state: State<AppState>,
req: HttpRequest<AppState>,
query: Path<GetPost>) -> ConverseResponse {
let user_id = get_user_id(&req);
state.db.send(query.into_inner())
.flatten()
.from_err()
.and_then(move |post| {
if user_id != 1 && post.user_id == user_id {
return Ok(post);
}
Err(ConverseError::PostEditForbidden {
user: user_id,
id: post.id,
})
})
.and_then(move |post| {
let edit_msg = EditPostPage {
id: post.id,
post: post.body,
};
state.renderer.send(edit_msg).from_err()
})
.flatten()
.map(|page| HttpResponse::Ok().content_type(HTML).body(page))
.responder()
}
/// This handler "executes" an edit to a post if the current user owns
/// the edited post.
pub fn edit_post(state: State<AppState>,
req: HttpRequest<AppState>,
update: Form<UpdatePost>) -> ConverseResponse {
let user_id = get_user_id(&req);
state.db.send(GetPost { id: update.post_id })
.flatten()
.from_err()
.and_then(move |post| {
if user_id != 1 && post.user_id == user_id {
Ok(())
} else {
Err(ConverseError::PostEditForbidden {
user: user_id,
id: post.id,
})
}
})
.and_then(move |_| state.db.send(update.0).from_err())
.flatten()
.map(|updated| HttpResponse::SeeOther()
.header("Location", format!("/thread/{}#post-{}",
updated.thread_id, updated.id))
.finish())
.responder()
}
/// This handler executes a full-text search on the forum database and
/// displays the results to the user.
pub fn search_forum(state: State<AppState>,
query: Query<SearchPosts>) -> ConverseResponse {
let query_string = query.query.clone();
state.db.send(query.into_inner())
.flatten()
.and_then(move |results| state.renderer.send(SearchResultPage {
results,
query: query_string,
}).from_err())
.flatten()
.map(|res| HttpResponse::Ok().content_type(HTML).body(res))
.responder()
}
/// This handler initiates an OIDC login.
pub fn login(state: State<AppState>) -> ConverseResponse {
state.oidc.send(GetLoginUrl)
.from_err()
.and_then(|url| Ok(HttpResponse::TemporaryRedirect()
.header("Location", url)
.finish()))
.responder()
}
/// This handler handles an OIDC callback (i.e. completed login).
///
/// Upon receiving the callback, a token is retrieved from the OIDC
/// provider and a user lookup is performed. If a user with a matching
/// email-address is found in the database, it is logged in -
/// otherwise a new user is created.
pub fn callback(state: State<AppState>,
data: Form<CodeResponse>,
mut req: HttpRequest<AppState>) -> ConverseResponse {
state.oidc.send(RetrieveToken(data.0)).flatten()
.map(|author| LookupOrCreateUser {
email: author.email,
name: author.name,
})
.and_then(move |msg| state.db.send(msg).from_err()).flatten()
.and_then(move |user| {
info!("Completed login for user {} ({})", user.email, user.id);
req.remember(user.id.to_string());
Ok(HttpResponse::SeeOther()
.header("Location", "/")
.finish())})
.responder()
}
/// This is an extension trait to enable easy serving of embedded
/// static content.
///
/// It is intended to be called with `include_bytes!()` when setting
/// up the actix-web application.
pub trait EmbeddedFile {
fn static_file(self, path: &'static str, content: &'static [u8]) -> Self;
}
impl EmbeddedFile for App<AppState> {
fn static_file(self, path: &'static str, content: &'static [u8]) -> Self {
self.route(path, Method::GET, move |_: HttpRequest<_>| {
let mime = format!("{}", guess_mime_type(path));
HttpResponse::Ok()
.content_type(mime.as_str())
.body(content)
})
}
}
/// Middleware used to enforce logins unceremoniously.
pub struct RequireLogin;
impl <S> Middleware<S> for RequireLogin {
fn start(&self, req: &mut HttpRequest<S>) -> actix_web::Result<Started> {
let logged_in = req.identity().is_some();
let is_oidc_req = req.path().starts_with("/oidc");
if !is_oidc_req && !logged_in {
Ok(Started::Response(
HttpResponse::SeeOther()
.header("Location", "/oidc/login")
.finish()
))
} else {
Ok(Started::Done)
}
}
}

223
web/converse/src/main.rs Normal file
View file

@ -0,0 +1,223 @@
// Copyright (C) 2018-2021 Vincent Ambo <tazjin@tvl.su>
//
// This file is part of Converse.
//
// 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/>.
#[macro_use]
extern crate askama;
#[macro_use]
extern crate diesel;
#[macro_use]
extern crate failure;
#[macro_use]
extern crate log;
#[macro_use]
extern crate serde_derive;
extern crate actix;
extern crate actix_web;
extern crate chrono;
extern crate comrak;
extern crate env_logger;
extern crate futures;
extern crate hyper;
extern crate md5;
extern crate mime_guess;
extern crate r2d2;
extern crate rand;
extern crate reqwest;
extern crate serde;
extern crate serde_json;
extern crate tokio;
extern crate tokio_timer;
extern crate url;
extern crate url_serde;
/// Simple macro used to reduce boilerplate when defining actor
/// message types.
macro_rules! message {
( $t:ty, $r:ty ) => {
impl Message for $t {
type Result = $r;
}
}
}
pub mod db;
pub mod errors;
pub mod handlers;
pub mod models;
pub mod oidc;
pub mod render;
pub mod schema;
use actix::prelude::*;
use actix_web::*;
use actix_web::http::Method;
use actix_web::middleware::Logger;
use actix_web::middleware::identity::{IdentityService, CookieIdentityPolicy};
use db::*;
use diesel::pg::PgConnection;
use diesel::r2d2::{ConnectionManager, Pool};
use handlers::*;
use oidc::OidcExecutor;
use rand::{OsRng, Rng};
use render::Renderer;
use std::env;
fn config(name: &str) -> String {
env::var(name).expect(&format!("{} must be set", name))
}
fn config_default(name: &str, default: &str) -> String {
env::var(name).unwrap_or(default.into())
}
fn start_db_executor() -> Addr<Syn, DbExecutor> {
info!("Initialising database connection pool ...");
let db_url = config("DATABASE_URL");
let manager = ConnectionManager::<PgConnection>::new(db_url);
let pool = Pool::builder().build(manager).expect("Failed to initialise DB pool");
SyncArbiter::start(2, move || DbExecutor(pool.clone()))
}
fn schedule_search_refresh(db: Addr<Syn, DbExecutor>) {
use tokio::prelude::*;
use tokio::timer::Interval;
use std::time::{Duration, Instant};
use std::thread;
let task = Interval::new(Instant::now(), Duration::from_secs(60))
.from_err()
.for_each(move |_| db.send(db::RefreshSearchView).flatten())
.map_err(|err| error!("Error while updating search view: {}", err));
thread::spawn(|| tokio::run(task));
}
fn start_oidc_executor(base_url: &str) -> Addr<Syn, OidcExecutor> {
info!("Initialising OIDC integration ...");
let oidc_url = config("OIDC_DISCOVERY_URL");
let oidc_config = oidc::load_oidc(&oidc_url)
.expect("Failed to retrieve OIDC discovery document");
let oidc = oidc::OidcExecutor {
oidc_config,
client_id: config("OIDC_CLIENT_ID"),
client_secret: config("OIDC_CLIENT_SECRET"),
redirect_uri: format!("{}/oidc/callback", base_url),
};
oidc.start()
}
fn start_renderer() -> Addr<Syn, Renderer> {
let comrak = comrak::ComrakOptions{
github_pre_lang: true,
ext_strikethrough: true,
ext_table: true,
ext_autolink: true,
ext_tasklist: true,
ext_footnotes: true,
ext_tagfilter: true,
..Default::default()
};
Renderer{ comrak }.start()
}
fn gen_session_key() -> [u8; 64] {
let mut key_bytes = [0; 64];
let mut rng = OsRng::new()
.expect("Failed to retrieve RNG for key generation");
rng.fill_bytes(&mut key_bytes);
key_bytes
}
fn start_http_server(base_url: String,
db_addr: Addr<Syn, DbExecutor>,
oidc_addr: Addr<Syn, OidcExecutor>,
renderer_addr: Addr<Syn, Renderer>) {
info!("Initialising HTTP server ...");
let bind_host = config_default("CONVERSE_BIND_HOST", "127.0.0.1:4567");
let key = gen_session_key();
let require_login = config_default("REQUIRE_LOGIN", "true".into()) == "true";
server::new(move || {
let state = AppState {
db: db_addr.clone(),
oidc: oidc_addr.clone(),
renderer: renderer_addr.clone(),
};
let identity = IdentityService::new(
CookieIdentityPolicy::new(&key)
.name("converse_auth")
.path("/")
.secure(base_url.starts_with("https"))
);
let app = App::with_state(state)
.middleware(Logger::default())
.middleware(identity)
.resource("/", |r| r.method(Method::GET).with(forum_index))
.resource("/thread/new", |r| r.method(Method::GET).with(new_thread))
.resource("/thread/submit", |r| r.method(Method::POST).with3(submit_thread))
.resource("/thread/reply", |r| r.method(Method::POST).with3(reply_thread))
.resource("/thread/{id}", |r| r.method(Method::GET).with3(forum_thread))
.resource("/post/{id}/edit", |r| r.method(Method::GET).with3(edit_form))
.resource("/post/edit", |r| r.method(Method::POST).with3(edit_post))
.resource("/search", |r| r.method(Method::GET).with2(search_forum))
.resource("/oidc/login", |r| r.method(Method::GET).with(login))
.resource("/oidc/callback", |r| r.method(Method::POST).with3(callback))
.static_file("/static/highlight.css", include_bytes!("../static/highlight.css"))
.static_file("/static/highlight.js", include_bytes!("../static/highlight.js"))
.static_file("/static/styles.css", include_bytes!("../static/styles.css"));
if require_login {
app.middleware(RequireLogin)
} else {
app
}})
.bind(&bind_host).expect(&format!("Could not bind on '{}'", bind_host))
.start();
}
fn main() {
env_logger::init();
info!("Welcome to Converse! Hold on tight while we're getting ready.");
let sys = actix::System::new("converse");
let base_url = config("BASE_URL");
let db_addr = start_db_executor();
let oidc_addr = start_oidc_executor(&base_url);
let renderer_addr = start_renderer();
schedule_search_refresh(db_addr.clone());
start_http_server(base_url, db_addr, oidc_addr, renderer_addr);
sys.run();
}

127
web/converse/src/models.rs Normal file
View file

@ -0,0 +1,127 @@
// Copyright (C) 2018-2021 Vincent Ambo <tazjin@tvl.su>
//
// This file is part of Converse.
//
// 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/>.
use chrono::prelude::{DateTime, Utc};
use schema::{users, threads, posts, simple_posts};
use diesel::sql_types::{Text, Integer};
/// Represents a single user in the Converse database. Converse does
/// not handle logins itself, but rather looks them up based on the
/// email address received from an OIDC provider.
#[derive(Identifiable, Queryable, Serialize)]
pub struct User {
pub id: i32,
pub name: String,
pub email: String,
pub admin: bool,
}
#[derive(Identifiable, Queryable, Serialize, Associations)]
#[belongs_to(User)]
pub struct Thread {
pub id: i32,
pub title: String,
pub posted: DateTime<Utc>,
pub sticky: bool,
pub user_id: i32,
pub closed: bool,
}
#[derive(Identifiable, Queryable, Serialize, Associations)]
#[belongs_to(Thread)]
#[belongs_to(User)]
pub struct Post {
pub id: i32,
pub thread_id: i32,
pub body: String,
pub posted: DateTime<Utc>,
pub user_id: i32,
}
/// This struct is used as the query result type for the simplified
/// post view, which already joins user information in the database.
#[derive(Identifiable, Queryable, Serialize, Associations)]
#[belongs_to(Thread)]
pub struct SimplePost {
pub id: i32,
pub thread_id: i32,
pub body: String,
pub posted: DateTime<Utc>,
pub user_id: i32,
pub closed: bool,
pub author_name: String,
pub author_email: String,
}
/// This struct is used as the query result type for the thread index
/// view, which lists the index of threads ordered by the last post in
/// each thread.
#[derive(Queryable, Serialize)]
pub struct ThreadIndex {
pub thread_id: i32,
pub title: String,
pub thread_author: String,
pub created: DateTime<Utc>,
pub sticky: bool,
pub closed: bool,
pub post_id: i32,
pub post_author: String,
pub posted: DateTime<Utc>,
}
#[derive(Deserialize, Insertable)]
#[table_name="threads"]
pub struct NewThread {
pub title: String,
pub user_id: i32,
}
#[derive(Deserialize, Insertable)]
#[table_name="users"]
pub struct NewUser {
pub email: String,
pub name: String,
}
#[derive(Deserialize, Insertable)]
#[table_name="posts"]
pub struct NewPost {
pub thread_id: i32,
pub body: String,
pub user_id: i32,
}
/// This struct models the response of a full-text search query. It
/// does not use a table/schema definition struct like the other
/// tables, as no table of this type actually exists.
#[derive(QueryableByName, Debug, Serialize)]
pub struct SearchResult {
#[sql_type = "Integer"]
pub post_id: i32,
#[sql_type = "Integer"]
pub thread_id: i32,
#[sql_type = "Text"]
pub author: String,
#[sql_type = "Text"]
pub title: String,
/// Headline represents the result of Postgres' ts_headline()
/// function, which highlights search terms in the search results.
#[sql_type = "Text"]
pub headline: String,
}

149
web/converse/src/oidc.rs Normal file
View file

@ -0,0 +1,149 @@
// Copyright (C) 2018-2021 Vincent Ambo <tazjin@tvl.su>
//
// This file is part of Converse.
//
// 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/>.
//! This module provides authentication via OIDC compliant
//! authentication sources.
//!
//! Currently Converse only supports a single OIDC provider. Note that
//! this has so far only been tested with Office365.
use actix::prelude::*;
use reqwest;
use url::Url;
use url_serde;
use errors::*;
use reqwest::header::Authorization;
use hyper::header::Bearer;
/// This structure represents the contents of an OIDC discovery
/// document.
#[derive(Deserialize, Debug, Clone)]
pub struct OidcConfig {
#[serde(with = "url_serde")]
authorization_endpoint: Url,
token_endpoint: String,
userinfo_endpoint: String,
scopes_supported: Vec<String>,
issuer: String,
}
#[derive(Clone, Debug)]
pub struct OidcExecutor {
pub client_id: String,
pub client_secret: String,
pub redirect_uri: String,
pub oidc_config: OidcConfig,
}
/// This struct represents the form response returned by an OIDC
/// provider with the `code`.
#[derive(Debug, Deserialize)]
pub struct CodeResponse {
pub code: String,
}
/// This struct represents the data extracted from the ID token and
/// stored in the user's session.
#[derive(Debug, Serialize, Deserialize)]
pub struct Author {
pub name: String,
pub email: String,
}
impl Actor for OidcExecutor {
type Context = Context<Self>;
}
/// Message used to request the login URL:
pub struct GetLoginUrl; // TODO: Add a nonce parameter stored in session.
message!(GetLoginUrl, String);
impl Handler<GetLoginUrl> for OidcExecutor {
type Result = String;
fn handle(&mut self, _: GetLoginUrl, _: &mut Self::Context) -> Self::Result {
let mut url: Url = self.oidc_config.authorization_endpoint.clone();
{
let mut params = url.query_pairs_mut();
params.append_pair("client_id", &self.client_id);
params.append_pair("response_type", "code");
params.append_pair("scope", "openid");
params.append_pair("redirect_uri", &self.redirect_uri);
params.append_pair("response_mode", "form_post");
}
return url.into_string();
}
}
/// Message used to request the token from the returned code and
/// retrieve userinfo from the appropriate endpoint.
pub struct RetrieveToken(pub CodeResponse);
message!(RetrieveToken, Result<Author>);
#[derive(Debug, Deserialize)]
struct TokenResponse {
access_token: String,
}
// TODO: This is currently hardcoded to Office365 fields.
#[derive(Debug, Deserialize)]
struct Userinfo {
name: String,
unique_name: String, // email in office365
}
impl Handler<RetrieveToken> for OidcExecutor {
type Result = Result<Author>;
fn handle(&mut self, msg: RetrieveToken, _: &mut Self::Context) -> Self::Result {
debug!("Received OAuth2 code, requesting access_token");
let client = reqwest::Client::new();
let params: [(&str, &str); 5] = [
("client_id", &self.client_id),
("client_secret", &self.client_secret),
("grant_type", "authorization_code"),
("code", &msg.0.code),
("redirect_uri", &self.redirect_uri),
];
let mut response = client.post(&self.oidc_config.token_endpoint)
.form(&params)
.send()?;
debug!("Received token response: {:?}", response);
let token: TokenResponse = response.json()?;
let user: Userinfo = client.get(&self.oidc_config.userinfo_endpoint)
.header(Authorization(Bearer { token: token.access_token }))
.send()?
.json()?;
Ok(Author {
name: user.name,
email: user.unique_name,
})
}
}
/// Convenience function to attempt loading an OIDC discovery document
/// from a specified URL:
pub fn load_oidc(url: &str) -> Result<OidcConfig> {
let config: OidcConfig = reqwest::get(url)?.json()?;
Ok(config)
}

265
web/converse/src/render.rs Normal file
View file

@ -0,0 +1,265 @@
// Copyright (C) 2018-2021 Vincent Ambo <tazjin@tvl.su>
//
// This file is part of Converse.
//
// 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/>.
//! This module defines a rendering actor used for processing Converse
//! data into whatever format is needed by the templates and rendering
//! them.
use actix::prelude::*;
use askama::Template;
use errors::*;
use std::fmt;
use md5;
use models::*;
use chrono::prelude::{DateTime, Utc};
use comrak::{ComrakOptions, markdown_to_html};
pub struct Renderer {
pub comrak: ComrakOptions,
}
impl Actor for Renderer {
type Context = actix::Context<Self>;
}
/// Represents a data formatted for human consumption
#[derive(Debug)]
struct FormattedDate(DateTime<Utc>);
impl fmt::Display for FormattedDate {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0.format("%a %d %B %Y, %R"))
}
}
/// Message used to render the index page.
pub struct IndexPage {
pub threads: Vec<ThreadIndex>,
}
message!(IndexPage, Result<String>);
#[derive(Debug)]
struct IndexThread {
id: i32,
title: String,
sticky: bool,
closed: bool,
posted: FormattedDate,
author_name: String,
post_author: String,
}
#[derive(Template)]
#[template(path = "index.html")]
struct IndexPageTemplate {
threads: Vec<IndexThread>,
}
impl Handler<IndexPage> for Renderer {
type Result = Result<String>;
fn handle(&mut self, msg: IndexPage, _: &mut Self::Context) -> Self::Result {
let threads: Vec<IndexThread> = msg.threads
.into_iter()
.map(|thread| IndexThread {
id: thread.thread_id,
title: thread.title, // escape_html(&thread.title),
sticky: thread.sticky,
closed: thread.closed,
posted: FormattedDate(thread.posted),
author_name: thread.thread_author,
post_author: thread.post_author,
})
.collect();
let tpl = IndexPageTemplate {
threads
};
tpl.render().map_err(|e| e.into())
}
}
/// Message used to render a thread.
pub struct ThreadPage {
pub current_user: i32,
pub thread: Thread,
pub posts: Vec<SimplePost>,
}
message!(ThreadPage, Result<String>);
// "Renderable" structures with data transformations applied.
#[derive(Debug)]
struct RenderablePost {
id: i32,
body: String,
posted: FormattedDate,
author_name: String,
author_gravatar: String,
editable: bool,
}
/// This structure represents the transformed thread data with
/// Markdown rendering and other changes applied.
#[derive(Template)]
#[template(path = "thread.html")]
struct RenderableThreadPage {
id: i32,
title: String,
closed: bool,
posts: Vec<RenderablePost>,
}
/// Helper function for computing Gravatar links.
fn md5_hex(input: &[u8]) -> String {
format!("{:x}", md5::compute(input))
}
fn prepare_thread(comrak: &ComrakOptions, page: ThreadPage) -> RenderableThreadPage {
let user = page.current_user;
let posts = page.posts.into_iter().map(|post| {
let editable = user != 1 && post.user_id == user;
RenderablePost {
id: post.id,
body: markdown_to_html(&post.body, comrak),
posted: FormattedDate(post.posted),
author_name: post.author_name.clone(),
author_gravatar: md5_hex(post.author_email.as_bytes()),
editable,
}
}).collect();
RenderableThreadPage {
posts,
closed: page.thread.closed,
id: page.thread.id,
title: page.thread.title,
}
}
impl Handler<ThreadPage> for Renderer {
type Result = Result<String>;
fn handle(&mut self, msg: ThreadPage, _: &mut Self::Context) -> Self::Result {
let renderable = prepare_thread(&self.comrak, msg);
renderable.render().map_err(|e| e.into())
}
}
/// The different types of editing modes supported by the editing
/// template:
#[derive(Debug, PartialEq)]
pub enum EditingMode {
NewThread,
PostReply,
EditPost,
}
impl Default for EditingMode {
fn default() -> EditingMode { EditingMode::NewThread }
}
/// This is the template used for rendering the new thread, edit post
/// and reply to thread forms.
#[derive(Template, Default)]
#[template(path = "post.html")]
pub struct FormTemplate {
/// Which editing mode is to be used by the template?
pub mode: EditingMode,
/// Potential alerts to display to the user (e.g. input validation
/// results)
pub alerts: Vec<&'static str>,
/// Either the title to be used in the subject field or the title
/// of the thread the user is responding to.
pub title: Option<String>,
/// Body of the post being edited, if present.
pub post: Option<String>,
/// ID of the thread being replied to or the post being edited.
pub id: Option<i32>,
}
/// Message used to render new thread page.
///
/// It can optionally contain a vector of warnings to display to the
/// user in alert boxes, such as input validation errors.
#[derive(Default)]
pub struct NewThreadPage {
pub alerts: Vec<&'static str>,
pub title: Option<String>,
pub post: Option<String>,
}
message!(NewThreadPage, Result<String>);
impl Handler<NewThreadPage> for Renderer {
type Result = Result<String>;
fn handle(&mut self, msg: NewThreadPage, _: &mut Self::Context) -> Self::Result {
let ctx = FormTemplate {
alerts: msg.alerts,
title: msg.title,
post: msg.post,
..Default::default()
};
ctx.render().map_err(|e| e.into())
}
}
/// Message used to render post editing page.
pub struct EditPostPage {
pub id: i32,
pub post: String,
}
message!(EditPostPage, Result<String>);
impl Handler<EditPostPage> for Renderer {
type Result = Result<String>;
fn handle(&mut self, msg: EditPostPage, _: &mut Self::Context) -> Self::Result {
let ctx = FormTemplate {
mode: EditingMode::EditPost,
id: Some(msg.id),
post: Some(msg.post),
..Default::default()
};
ctx.render().map_err(|e| e.into())
}
}
/// Message used to render search results
#[derive(Template)]
#[template(path = "search.html")]
pub struct SearchResultPage {
pub query: String,
pub results: Vec<SearchResult>,
}
message!(SearchResultPage, Result<String>);
impl Handler<SearchResultPage> for Renderer {
type Result = Result<String>;
fn handle(&mut self, msg: SearchResultPage, _: &mut Self::Context) -> Self::Result {
msg.render().map_err(|e| e.into())
}
}

View file

@ -0,0 +1,88 @@
// Copyright (C) 2018-2021 Vincent Ambo <tazjin@tvl.su>
//
// This file is part of Converse.
//
// 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/>.
table! {
posts (id) {
id -> Int4,
thread_id -> Int4,
body -> Text,
posted -> Timestamptz,
user_id -> Int4,
}
}
table! {
threads (id) {
id -> Int4,
title -> Varchar,
posted -> Timestamptz,
sticky -> Bool,
user_id -> Int4,
closed -> Bool,
}
}
table! {
users (id) {
id -> Int4,
email -> Varchar,
name -> Varchar,
admin -> Bool,
}
}
// Note: Manually inserted as print-schema does not add views.
table! {
simple_posts (id) {
id -> Int4,
thread_id -> Int4,
body -> Text,
posted -> Timestamptz,
user_id -> Int4,
closed -> Bool,
author_name -> Text,
author_email -> Text,
}
}
// Note: Manually inserted as print-schema does not add views.
table! {
thread_index (thread_id) {
thread_id -> Int4,
title -> Text,
thread_author -> Text,
created -> Timestamptz,
sticky -> Bool,
closed -> Bool,
post_id -> Int4,
post_author -> Text,
posted -> Timestamptz,
}
}
joinable!(posts -> threads (thread_id));
joinable!(posts -> users (user_id));
joinable!(threads -> users (user_id));
joinable!(simple_posts -> threads (thread_id));
allow_tables_to_appear_in_same_query!(
posts,
threads,
users,
simple_posts,
);

View file

@ -0,0 +1,99 @@
/*
github.com style (c) Vasily Polovnyov <vast@whiteants.net>
*/
.hljs {
display: block;
overflow-x: auto;
padding: 0.5em;
color: #333;
background: #f8f8f8;
}
.hljs-comment,
.hljs-quote {
color: #998;
font-style: italic;
}
.hljs-keyword,
.hljs-selector-tag,
.hljs-subst {
color: #333;
font-weight: bold;
}
.hljs-number,
.hljs-literal,
.hljs-variable,
.hljs-template-variable,
.hljs-tag .hljs-attr {
color: #008080;
}
.hljs-string,
.hljs-doctag {
color: #d14;
}
.hljs-title,
.hljs-section,
.hljs-selector-id {
color: #900;
font-weight: bold;
}
.hljs-subst {
font-weight: normal;
}
.hljs-type,
.hljs-class .hljs-title {
color: #458;
font-weight: bold;
}
.hljs-tag,
.hljs-name,
.hljs-attribute {
color: #000080;
font-weight: normal;
}
.hljs-regexp,
.hljs-link {
color: #009926;
}
.hljs-symbol,
.hljs-bullet {
color: #990073;
}
.hljs-built_in,
.hljs-builtin-name {
color: #0086b3;
}
.hljs-meta {
color: #999;
font-weight: bold;
}
.hljs-deletion {
background: #fdd;
}
.hljs-addition {
background: #dfd;
}
.hljs-emphasis {
font-style: italic;
}
.hljs-strong {
font-weight: bold;
}

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,145 @@
* :not(.material-icons) {
font-family: 'Ubuntu', sans-serif;
}
code, pre, code * {
font-family: 'Ubuntu Mono', monospace !important;
}
.cvs-title, .thread-link {
text-decoration: none;
}
.thread-list-item:hover {
background-color: #f5f5f5;
}
.thread-link {
padding: 5px;
padding-top: 10px;
}
.thread-title {
padding-right: 15vw;
}
.search-field {
margin-right: 15px;
max-width: 200px;
}
.thread-author {
font-style: italic;
font-size: 85%;
}
@media only screen and (min-width: 768px) {
.converse main {
padding-top: 10px;
padding-bottom: 10px;
}
}
.mdl-list__item-text-body {
max-height: 40px;
}
.thread-divider:after {
border-bottom: 1px solid rgba(0,0,0,.13);
content:"";
position: absolute;
width: 80%;
}
html, body {
margin: 0;
padding: 0;
}
.converse .mdl-layout__header-row {
padding-left: 40px;
}
.converse .mdl-layout.is-small-screen .mdl-layout__header-row h3 {
font-size: inherit;
}
.converse .mdl-card {
height: auto;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column;
}
.converse .mdl-card > * {
height: auto;
}
.converse .mdl-card .mdl-card__supporting-text {
margin: 40px;
-webkit-flex-grow: 1;
-ms-flex-positive: 1;
flex-grow: 1;
padding: 0;
color: inherit;
width: calc(100% - 80px);
}
.mdl-demo.converse .mdl-card__supporting-text h4 {
margin-top: 0;
margin-bottom: 20px;
}
.converse .mdl-card__actions {
margin: 0;
padding: 4px 40px;
color: inherit;
}
.converse section.section--center {
max-width: 860px;
}
.converse .mdl-card .avatar-card {
display: flex;
flex-direction: column;
text-align: center;
margin-top: 30px;
}
.desktop-avatar {
width: 80px;
margin-right: auto;
margin-left: auto;
}
.mobile-avatar {
width: 30px;
border-radius: 8px;
margin-bottom: 5px;
}
.mobile-date {
text-decoration: none;
}
.converse .mdl-card .post-box {
margin: 20px;
}
.converse .mdl-card .post-actions {
display: flex;
padding-right: 5px;
}
.post-action {
margin: 5px;
margin-bottom: 10px;
}
.converse section.post-section {
padding: 5px;
}
.post-date {
text-decoration: none;
font-size: 80%;
}
.mdl-layout__content {
flex: 1 0 auto;
}
.converse .reply-box {
padding-top: 10px;
}
.search-result {
margin: 8px;
}
.search-result .mdl-button {
margin: 3px;
}

View file

@ -0,0 +1,80 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
<title>Converse: Index</title>
<!-- TODO -->
<meta http-equiv="Content-Security-Policy" content="script-src https://code.getmdl.io 'self';">
<!-- <link rel="shortcut icon" href="images/favicon.png"> -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Ubuntu">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.blue_grey-orange.min.css" />
<link rel="stylesheet" href="/static/styles.css">
</head>
<body class="converse mdl-base mdl-color-text--grey-700 mdl-color--grey-100">
<div class="mdl-layout mdl-layout--fixed-header mdl-js-layout mdl-color--grey-100">
<header class="mdl-layout__header mdl-layout__header--scroll mdl-color--primary-dark">
<div class="mdl-layout__header-row">
<a href="/" class="mdl-layout-title mdl-color-text--blue-grey-50 cvs-title">Converse</a>
<div class="mdl-layout-spacer"></div>
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label mdl-color-text--blue-grey-50 search-field">
<form method="get" action="/search">
<input class="mdl-textfield__input" type="search" id="search-query" aria-label="Search" name="query">
<label class="mdl-textfield__label mdl-color-text--blue-grey-100" for="search-query">Search query...</label>
<input type="submit" hidden />
</form>
</div>
&nbsp;
<a href="/thread/new">
<button class="mdl-button mdl-js-button mdl-button--raised mdl-button--accent mdl-js-ripple-effect">
New Thread
</button>
</a>
</div>
</header>
<main class="mdl-layout__content">
<section class="section--center mdl-grid mdl-grid--no-spacing mdl-shadow--2dp">
<div class="mdl-card mdl-cell mdl-cell--12-col">
<div class="mdl-card__supporting-text mdl-grid">
<h4 class="mdl-cell mdl-cell--12-col">Latest threads:</h4>
<ul class="mdl-list">
{% for thread in threads %}
<li class="mdl-list__item thread-list-item mdl-list__item--three-line">
<a class="thread-link mdl-color-text--grey-800" href="/thread/{{ thread.id }}">
<span class="mdl-list__item-primary-content {% if loop.index < threads.len() %}thread-divider{% endif %}">
<button class="mdl-button mdl-js-button mdl-button--fab mdl-button--mini-fab mdl-button--colored mdl-list__item-icon">
<i class="material-icons">
{% if thread.sticky %}
announcement
{% else if thread.closed %}
lock
{% else %}
library_books
{% endif %}
</i>
</button>
<span class="thread-title">{{ thread.title }}<span class="thread-author"> by {{ thread.author_name }}</span></span>
<span class="mdl-list__item-text-body">
Last reply by {{ thread.post_author }} on {{ thread.posted }}.
</span>
</span>
</a>
</li>
{% endfor %}
</ul>
</div>
</div>
</section>
</main>
<footer class="mdl-mini-footer">
<div class="mdl-mini-footer--right-section">
<p>Powered by <a href="https://github.com/tazjin/converse">Converse</a></p>
</div>
</footer>
</div>
<script src="https://code.getmdl.io/1.3.0/material.min.js"></script>
</body>
</html>

View file

@ -0,0 +1,124 @@
{#
This template is shared by the new thread, reply and post-editing pages.
The main display differences between the different editing styles are the
headline of the page ("Submit new thread", "Reply to thread", "Edit post")
and whether or not the subject line field is displayed in the input form.
Every one of these pages can have a variable length list of alerts submitted
into the template, which will be rendered as Boostrap alert boxes above the
user input form.
#}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
<title>Converse: Post</title>
<meta http-equiv="Content-Security-Policy" content="script-src https://code.getmdl.io 'self';">
<!-- <link rel="shortcut icon" href="images/favicon.png"> -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Ubuntu">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.blue_grey-orange.min.css" />
<link rel="stylesheet" href="/static/styles.css">
</head>
<body class="converse mdl-base mdl-color-text--grey-700 mdl-color--grey-100">
<div class="mdl-layout mdl-layout--fixed-header mdl-js-layout mdl-color--grey-100">
<header class="mdl-layout__header mdl-layout__header--scroll mdl-color--primary-dark">
<div class="mdl-layout__header-row">
<a href="/" class="mdl-layout-title mdl-color-text--blue-grey-50 cvs-title">
{% match mode %}
{% when EditingMode::NewThread %}
Converse: Submit new thread
{% when EditingMode::PostReply %}
Converse: Reply to thread
{% when EditingMode::EditPost %}
Converse: Edit post
{% endmatch %}
</a>
<div class="mdl-layout-spacer"></div>
<a href="/">
<button class="mdl-button mdl-js-button mdl-button--raised mdl-button--accent mdl-js-ripple-effect">
Back to index
</button>
</a>
</div>
</header>
<main class="mdl-layout__content mdl-grid">
<div class="mdl-card mdl-shadow--2dp mdl-cell--8-col">
{% match mode %}
{% when EditingMode::NewThread %}
<form action="/thread/submit" method="post">
{% when EditingMode::PostReply %}
<form action="/thread/reply" method="post">
{% when EditingMode::EditPost %}
<form action="/post/edit" method="post">
{% endmatch %}
{% match mode %}
{% when EditingMode::PostReply %}
<input type="hidden" id="thread_id" name="thread_id" value="{{ id.unwrap() }}">
{% when EditingMode::EditPost %}
<input type="hidden" id="thread_id" name="post_id" value="{{ id.unwrap() }}">
{% else %}
{# no post ID when making a new thread #}
{% endmatch %}
<div class="mdl-card__supporting-text">
{% for alert in alerts %}
<span class="mdl-chip mdl-color--red-200">
<span class="mdl-chip__text">{{ alert }}&nbsp;</span>
</span>
{% endfor %}
{% if mode == EditingMode::NewThread %}
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label mdl-cell--12-col">
<input class="mdl-textfield__input" type="text" id="title" name="title" aria-label="thread title" required {% match title %}{% when Some with (title_text) %}value="{{ title_text }}"{% else %}{# Nothing! #}{% endmatch %}>
<label class="mdl-textfield__label" for="title">Thread title</label>
</div>
{% endif %}
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label mdl-cell--12-col">
<textarea class="mdl-textfield__input" type="text" rows="25" id="post" name="post" aria-label="post content" required>
{%- match post -%}
{%- when Some with (post_text) -%}
{{- post_text -}}
{%- else -%}
{# Nothing! #}
{%- endmatch -%}
</textarea>
<label class="mdl-textfield__label" for="body">Content ...</label>
</div>
</div>
<div class="mdl-card__actions">
<input class="mdl-button mdl-button--raised mdl-button--colored mdl-js-button mdl-js-ripple-effect" type="submit" value="Submit!">
</div>
</form>
</div>
<div class="mdl-card mdl-shadow--2dp mdl-cell--4-col">
<div class="mdl-card__title mdl-card--border">
Quick Markdown primer:
</div>
<div class="mdl-card__supporting-text">
<p>
Remember that you can use <a href="https://daringfireball.net/projects/markdown/basics"><strong>Markdown</strong></a> when
writing your posts:
</p>
<p><i>*italic text*</i></p>
<p><strong>**bold text**</strong></p>
<p><s>~strikethrough text~</s></p>
<p><code>[link text](https://some.link.com/)</code></p>
<p><code>![image text](https://foo.com/thing.jpg)</code></p>
<p>Use <code>*</code> or <code>-</code> to enumerate lists.</p>
<p>See Markdown documentation for more information!</p>
</div>
</div>
</main>
<footer class="mdl-mini-footer">
<div class="mdl-mini-footer--right-section">
<p>Powered by <a href="https://github.com/tazjin/converse">Converse</a></p>
</div>
</footer>
</div>
<script src="https://code.getmdl.io/1.3.0/material.min.js"></script>
</body>
</html>

View file

@ -0,0 +1,67 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
<title>Converse: Search results</title>
<!-- TODO -->
<meta http-equiv="Content-Security-Policy" content="script-src https://code.getmdl.io 'self';">
<!-- <link rel="shortcut icon" href="images/favicon.png"> -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Ubuntu">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.blue_grey-orange.min.css" />
<link rel="stylesheet" href="/static/styles.css">
</head>
<body class="converse mdl-base mdl-color-text--grey-700 mdl-color--grey-100">
<div class="mdl-layout mdl-layout--fixed-header mdl-js-layout mdl-color--grey-100">
<header class="mdl-layout__header mdl-layout__header--scroll mdl-color--primary-dark">
<div class="mdl-layout__header-row">
<a href="/" class="mdl-layout-title mdl-color-text--blue-grey-50 cvs-title">Converse</a>
<div class="mdl-layout-spacer"></div>
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label mdl-color-text--blue-grey-50 search-field">
<form method="get" action="/search">
<input class="mdl-textfield__input" type="search" id="search-query" aria-label="Search" name="query">
<label class="mdl-textfield__label mdl-color-text--blue-grey-100" for="search-query">Search query...</label>
<input type="submit" hidden />
</form>
</div>
&nbsp;
<a href="/">
<button class="mdl-button mdl-js-button mdl-button--raised mdl-button--accent mdl-js-ripple-effect">
Back to index
</button>
</a>
</div>
</header>
<main class="mdl-layout__content">
<section class="section--center mdl-grid">
<div class="mdl-cell--12-col">
<h4>Search results for '{{ query }}':</h4>
</div>
{% for result in results %}
<div class="mdl-card mdl-cell--6-col search-result mdl-shadow--2dp">
<div class="mdl-card__supporting-text">
<p>Posted in '{{ result.title }}' by {{ result.author }}:</p>
<p>{{ result.headline|safe }}</p>
</div>
<div class="mdl-card__actions mdl-card--border post-actions">
<div class="mdl-layout-spacer"></div>
<a class="mdl-button mdl-js-button mdl-button--fab mdl-button--mini-fab mdl-button--colored" href="/thread/{{ result.thread_id }}#post-{{ result.post_id }}">
<i class="material-icons">arrow_forward</i>
</a>
</div>
</div>
{% endfor %}
</section>
</main>
<footer class="mdl-mini-footer">
<div class="mdl-mini-footer--right-section">
<p>Powered by <a href="https://github.com/tazjin/converse">Converse</a></p>
</div>
</footer>
</div>
<script src="https://code.getmdl.io/1.3.0/material.min.js"></script>
</body>
</html>

View file

@ -0,0 +1,111 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
<title>Converse: {{ title }}</title>
<!-- TODO -->
<meta http-equiv="Content-Security-Policy" content="script-src https://code.getmdl.io 'self';">
<!-- <link rel="shortcut icon" href="images/favicon.png"> -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Ubuntu">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Ubuntu+Mono">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.blue_grey-orange.min.css" />
<link rel="stylesheet" href="/static/styles.css">
<!-- Syntax highlighting for code -->
<link rel="stylesheet" href="/static/highlight.css">
<style>img { max-width:100%; height:auto; }</style>
<script src="/static/highlight.js"></script>
</head>
<body class="converse mdl-base mdl-color-text--grey-700 mdl-color--grey-100">
<div class="mdl-layout mdl-layout--fixed-header mdl-js-layout mdl-color--grey-100">
<header class="mdl-layout__header mdl-color--primary-dark">
<div class="mdl-layout__header-row">
<a href="/" class="mdl-layout-title mdl-color-text--blue-grey-50 cvs-title">Converse: {{ title }}</a>
<div class="mdl-layout-spacer"></div>
<a href="/">
<button class="mdl-button mdl-js-button mdl-button--raised mdl-button--accent mdl-js-ripple-effect">
Back to index
</button>
</a>
</div>
</header>
<main class="mdl-layout__content">
{% for post in posts -%}
<section id="post-{{ post.id }}" class="section--center mdl-grid mdl-grid--no-spacing">
<!-- card to display avatars on desktop -->
<div class="mdl-card mdl-shadow--2dp mdl-cell--2-col mdl-cell--hide-phone mdl-cell--hide-tablet avatar-box">
<div class="avatar-card">
<img class="desktop-avatar" src="https://www.gravatar.com/avatar/{{ post.author_gravatar }}?d=monsterid&s=160" />
<p class="user-name">{{ post.author_name }}</p>
</div>
</div>
<!-- card for main post content -->
<div class="mdl-card mdl-shadow--2dp post-box mdl-cell--10-col">
<!-- card section for displaying user & post information on mobile -->
<div class="mdl-card__supporting-text mdl-card--border mdl-cell--hide-desktop mdl-color-text--blue-grey-500 mobile-user">
<img class="mobile-avatar" src="https://www.gravatar.com/avatar/{{ post.author_gravatar }}?d=monsterid"/>
<span>&nbsp;{{ post.author_name }} posted on </span>
<a class="mdl-color-text--blue-grey-500 mobile-date" href="/thread/{{ id }}#post-{{ post.id }}">{{ post.posted }}</a>
</div>
<!-- card section to display post date on desktop -->
<div class="mdl-card__menu mdl-cell--hide-phone mdl-cell--hide-tablet">
<a class="post-date mdl-color-text--blue-grey-500" href="/thread/{{ id }}#post-{{ post.id }}">{{ post.posted }}</a>
</div>
<!-- card section for actual post content -->
<div class="mdl-card__supporting-text post-box">{{ post.body|safe }}</div>
<!-- card section for post actions -->
<div class="mdl-card__actions post-actions">
<div class="mdl-layout-spacer"></div>
{% if post.editable %}
<a href="/post/{{ post.id }}/edit" class="mdl-button mdl-js-button mdl-button--accent" id="edit-post-{{ post.id }}" aria-label="Edit post">
<i class="material-icons">edit</i>
<span class="mdl-tooltip mdl-tooltip--top" for="edit-post-{{ post.id }}">Edit post</span>
</a>
{% endif %}
<button class="mdl-button mdl-js-button mdl-button--accent" id="quote-post-{{ post.id }}" aria-label="Quote post" disabled>
<i class="material-icons">reply</i>
<span class="mdl-tooltip mdl-tooltip--top" for="quote-post-{{ post.id }}">Quote post</span>
</button>
</div>
</div>
</section>
{% endfor %}
<!-- section for writing a response on the same page -->
<section id="post-reply" class="section--center mdl-grid mdl-grid--no-spacing reply-box">
<div class="mdl-card mdl-shadow--2dp mdl-cell--12-col">
{% if closed %}
<div class="mdl-card__supporting-text">
This thread is <b>closed</b> and can no longer be responded to.
</div>
{% else %}
<form id="reply-form" action="/thread/reply" method="post">
<input type="hidden" id="thread_id" name="thread_id" value="{{ id }}">
<div class="mdl-card__supporting-text">
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label mdl-cell--12-col">
<textarea class="mdl-textfield__input" type="text" rows="8" id="post" name="post" aria-label="reply content"></textarea>
<label class="mdl-textfield__label" for="post">Write a reply</label>
</div>
<button class="mdl-button mdl-button--raised mdl-button--primary mdl-js-button mdl-js-ripple-effect" type="submit">
Post!
</button>
</div>
</form>
{% endif %}
</div>
</section>
</main>
<footer class="mdl-mini-footer">
<div class="mdl-mini-footer--right-section">
<p>Powered by <a href="https://github.com/tazjin/converse">Converse</a></p>
</div>
</footer>
</div>
<script src="https://code.getmdl.io/1.3.0/material.min.js"></script>
</body>
</html>

13
web/converse/todo.org Normal file
View file

@ -0,0 +1,13 @@
* DONE Pin *-versions in cargo.toml
* DONE Markdown support
* DONE Post ordering as expected
* DONE Stickies!
* DONE Search
* DONE Post editing
* TODO Configurable number of DB workers
* TODO Match certain types of Diesel errors (esp. for "not found")
* TODO Sketch out categories vs. tags system
* TODO Quote button
* TODO Multiquote buttons
* TODO Pagination
* TODO Multi-thread guest accounts