Compare commits

..

No commits in common. 'master' and 'v1.0.0' have entirely different histories.

  1. 5
      .dockerignore
  2. 5
      .env.sample
  3. 6
      .gitignore
  4. 25
      Cargo.toml
  5. 20
      Dockerfile
  6. 239
      LICENSE
  7. 118
      README.md
  8. 2
      Rocket.toml
  9. 32
      docker-compose.yml
  10. 3
      migrations/postgres/2022-08-18-234900_add_room_id/down.sql
  11. 3
      migrations/postgres/2022-08-18-234900_add_room_id/up.sql
  12. 4
      migrations/postgres/2022-10-15-161115_post_reaction/down.sql
  13. 4
      migrations/postgres/2022-10-15-161115_post_reaction/up.sql
  14. 2
      migrations/postgres/2023-05-05-135236_post_add_index_for_attentions/down.sql
  15. 2
      migrations/postgres/2023-05-05-135236_post_add_index_for_attentions/up.sql
  16. 5
      psql-docker-init/add_pg_trgm.sh
  17. 1
      rust-toolchain
  18. 90
      src/api/attention.rs
  19. 79
      src/api/comment.rs
  20. 243
      src/api/mod.rs
  21. 151
      src/api/operation.rs
  22. 183
      src/api/post.rs
  23. 65
      src/api/reaction.rs
  24. 18
      src/api/search.rs
  25. 20
      src/api/systemlog.rs
  26. 20
      src/api/upload.rs
  27. 15
      src/api/vote.rs
  28. 136
      src/cache.rs
  29. 42
      src/cors.rs
  30. 8
      src/db_conn.rs
  31. 148
      src/libs/diesel_logger.rs
  32. 1
      src/libs/mod.rs
  33. 198
      src/login.rs
  34. 100
      src/main.rs
  35. 147
      src/models.rs
  36. 67
      src/rate_limit.rs
  37. 3
      src/rds_conn.rs
  38. 230
      src/rds_models.rs
  39. 9
      src/schema.rs

5
.dockerignore

@ -1,5 +0,0 @@
/target
Cargo.lock
/user_files
*.db
.env

5
.env.sample

@ -3,11 +3,6 @@ MAST_CLIENT="<your client id>"
MAST_SECRET="<your client key>"
MAST_SCOPE="read:accounts"
AUTH_BACKEND_URL="http://hole.localhost"
FRONTEND_WHITELIST="https://thuhollow.github.io"
UPLOAD_DIR="user_files"
DATABASE_URL="postgres://hole:hole_pass@localhost/hole_v2"
MIGRATION_DIRECTORY=migrations/postgres
REDIS_URL="redis://127.0.0.1:6379"

6
.gitignore vendored

@ -1,12 +1,6 @@
# private key
keys
# --> sqlite3
*.db
# user files
/user_files
# ---> Rust
# Generated by Cargo
# will have compiled files and executables

25
Cargo.toml

@ -2,30 +2,23 @@
name = "hole-thu"
version = "0.1.0"
edition = "2021"
license = "WTFPL-2.0"
license = "AGPL-3.0"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[features]
default = ["mastlogin"]
mastlogin = ["reqwest"]
[dependencies]
rocket = { version = "0.5.0", features = ["json"] }
rocket_sync_db_pools = { version = "0.1.0", features = ["diesel_postgres_pool"] }
diesel = { version = "2.1", features = ["postgres", "chrono"] }
diesel_migrations = "2.1"
redis = { version="0.24.0", features = ["aio", "tokio-comp"] }
rocket = { version = "0.5.0-rc.1", features = ["json"] }
rocket_sync_db_pools = { version = "0.1.0-cr.1", features = ["diesel_postgres_pool"] }
diesel = { version = "1.4.8", features = ["postgres", "chrono"] }
diesel_migrations = "1.4.0"
tokio = "1.17.0"
redis = { version="0.21.5", features = ["aio", "tokio-comp"] }
chrono = { version="0.4.19", features = ["serde"] }
rand = "0.8.5"
dotenv = "0.15.0"
sha2 = "0.10.2"
log = "0.4.16"
env_logger = "0.9.0"
web-push = "0.9.2"
url = "2.2.2"
futures = "0.3.24"
futures-util = "0.3.24"
lru = "0.11"
reqwest = { version = "0.11.10", features = ["json"], optional = true }
url = "2.2.2"
reqwest = { version = "0.11.10", features = ["json"] }

20
Dockerfile

@ -1,20 +0,0 @@
FROM rust:1-bullseye as builder
WORKDIR /usr/src/
RUN cargo new myapp --vcs none
WORKDIR /usr/src/myapp
COPY Cargo.toml ./
COPY rust-toolchain ./
RUN cargo build --release
# 为了充分利用docker的缓存
COPY src ./src
COPY migrations ./migrations
RUN touch src/main.rs && cargo build --release
FROM debian:bullseye-slim
RUN apt-get update && apt-get install libpq5 -y
COPY --from=builder /usr/src/myapp/target/release/hole-thu /usr/local/bin/hole-thu
COPY Rocket.toml /usr/local/bin/
CMD ["hole-thu"]

239
LICENSE

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

118
README.md

@ -1,94 +1,25 @@
# hole-backend-rust v1.3.0
# hole-backend-rust v1.0.0
## 部署
### 使用docker
+ 安装最新版docker与docker-compose-plugin
以Ubuntu为例: https://docs.docker.com/engine/install/ubuntu/
检查docker版本:
```shell
$ docker --version
Docker version 20.10.17, build 100c701
```
+ 执行
```shell
mkdir hole
cd hole
# 下载docker-compose.yml
wget https://git.thu.monster/newthuhole/hole-backend-rust/raw/branch/master/docker-compose.yml
# 下载add_pg_trgm.sh
mkdir psql-docker-init
wget https://git.thu.monster/newthuhole/hole-backend-rust/raw/branch/master/psql-docker-init/add_pg_trgm.sh -O psql-docker-init/add_pg_trgm.sh
# 下载镜像
docker compose pull
# 初始化postgres
docker compose up -d postgres
# 建表
docker compose run --rm hole-thu hole-thu --init-database
# 全部跑起来
docker compose up -d
```
现在树洞后端应该已经运行在8000端口了
停止运行:
```shell
docker compose stop
```
如需创建管理员账户,执行:
```shell
docker compose exec postgres psql --username hole --dbname hole_v2
```
进入数据库,执行需要的SQL命令。
+ 修改`docker-compose.yml`的情况:
+ 编辑services.hole-thu.environmen填入你的后端地址(用于登陆时的回调跳转)和前端地址(用于允许跨域)
+ 如果希望使用其他端口而非8000,编辑services.hole-thu.ports
+ 如果需要使用闭社登陆,请在services.hole-thu.environment中添加需要用到的更多环境变量(参考`.env.sample`)
### 使用源码编译
*以下内容假设你使用 Ubuntu 20.04*
安装rust与cargo环境 (略)
clone 代码 (略)
目前只支持postgresql,对支持sqlite的追踪见 issue #1
安装postgresql (略)
安装redis (略)
#### 准备数据库
### 准备数据库
进入:
```shell
```
sudo -u postgres psql
```
执行 (替换`hole_pass`为实际希望使用的密码):
执行 (替换`'hole_pass'`为实际希望使用的密码):
```postgresql
postgres=# CREATE USER hole WITH PASSWORD 'hole_pass';
@ -101,36 +32,39 @@ hole_v2=# CREATE EXTENSION pg_trgm;
CREATE EXTENSION
hole_v2=# \q
```
#### 编译&运行
### 运行
创建 .env 文件,写入必要的环境变量。可参考 .env.sample。
```shell
cargo run --release -- --init-database
cargo run --release
```
#### 基于二进制文件
或安装`diesel_cli`后
从[release](https://git.thu.monster/newthuhole/hole-backend-rust/releases)直接下载二进制文件
```shell
diesel migration run
cargo run --release
```
./hole-thu --init-database
./hole-thu
```
### 基于二进制文件
#### 基于源码
安装与准备数据库同
安装rust与cargo环境 (略)
从[release](https://git.thu.monster/newthuhole/hole-backend-rust/releases)直接下载二进制文件
clone 代码 (略)
```shell
./hole-thu --init-database
./hole-thu
```
cargo run --release -- --init-database
cargo run --release
```
或安装`diesel_cli`后
```
diesel migration run
cargo run --release
```
## 关于账号系统
### 关于账号系统
+ 如果你希望使用自己的登录系统,在Nginx或Apache中将 `/_login/` 路径交由另外的后端处理,只需最终将用户名和token写入users表,并跳转到 `/###token=<token>`
+ 如果你希望使用自己的登录系统,将 `/_login/` 路径交由另外的后端处理,只需最终将用户名和token写入users表,并跳转到 `/?token=<token>`
+ 如果你希望也使用闭社提供的授权来维护账号系统,使用 `https://thu.closed.social/api/v1/apps` 接口创建应用,并在.env或环境变量中填入client与secret。此操作不需要闭社账号。详情见[文档](https://docs.joinmastodon.org/client/token/#app)。编译运行时,增加`--features mastlogin`: `cargo run --release --features mastlogin`
+ 如果你希望也使用闭社提供的授权来维护账号系统,使用 `https://thu.closed.social/api/v1/apps` 接口创建应用,并在.env或环境变量中填入client与secret。此操作不需要闭社账号。详情见[文档](https://docs.joinmastodon.org/client/token/#app)。

2
Rocket.toml

@ -1,2 +0,0 @@
[default]
limits = { file = "200MB" }

32
docker-compose.yml

@ -1,32 +0,0 @@
version: '1'
services:
postgres:
image: postgres:14.3
restart: unless-stopped
volumes:
- "./data/postgres:/var/lib/postgresql/data"
- "./psql-docker-init:/docker-entrypoint-initdb.d"
environment:
POSTGRES_PASSWORD: hole_pass
POSTGRES_USER: hole
POSTGRES_DB: hole_v2
redis:
image: redis:7.0.2
restart: unless-stopped
hole-thu:
image: holethu/hole-backend-rust:1.2.0
restart: unless-stopped
ports:
- "127.0.0.1:8000:8863"
volumes:
- "./data/user_files:/user_files"
environment:
DATABASE_URL: "postgres://hole:hole_pass@postgres/hole_v2"
REDIS_URL: "redis://redis:6379"
ROCKET_DATABASES: '{pg_v2={url="postgres://hole:hole_pass@postgres/hole_v2"}}'
ROCKET_ADDRESS: "0.0.0.0"
ROCKET_PORT: 8863
AUTH_BACKEND_URL: "<你的后端地址>"
FRONTEND_WHITELIST: "<你的前端地址1>,<你的前端地址2>"
UPLOAD_DIR: "/user_files"

3
migrations/postgres/2022-08-18-234900_add_room_id/down.sql

@ -1,3 +0,0 @@
-- This file should undo anything in `up.sql`
ALTER TABLE posts
DROP COLUMN room_id

3
migrations/postgres/2022-08-18-234900_add_room_id/up.sql

@ -1,3 +0,0 @@
-- Your SQL goes here
ALTER TABLE posts
ADD COLUMN room_id INTEGER NOT NULL DEFAULT 0

4
migrations/postgres/2022-10-15-161115_post_reaction/down.sql

@ -1,4 +0,0 @@
-- This file should undo anything in `up.sql`
ALTER TABLE posts
DROP COLUMN up_votes,
DROP COLUMN down_votes

4
migrations/postgres/2022-10-15-161115_post_reaction/up.sql

@ -1,4 +0,0 @@
-- Your SQL goes here
ALTER TABLE posts
ADD COLUMN up_votes INTEGER NOT NULL DEFAULT 0,
ADD COLUMN down_votes INTEGER NOT NULL DEFAULT 0

2
migrations/postgres/2023-05-05-135236_post_add_index_for_attentions/down.sql

@ -1,2 +0,0 @@
-- This file should undo anything in `up.sql`
DROP INDEX posts_attention_idx

2
migrations/postgres/2023-05-05-135236_post_add_index_for_attentions/up.sql

@ -1,2 +0,0 @@
-- Your SQL goes here
CREATE INDEX posts_attention_idx ON posts (n_attentions)

5
psql-docker-init/add_pg_trgm.sh

@ -1,5 +0,0 @@
#!/bin/bash
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL
create extension pg_trgm;
EOSQL

1
rust-toolchain

@ -1 +0,0 @@
stable

90
src/api/attention.rs

@ -1,18 +1,14 @@
use crate::api::post::ps2outputs;
use crate::api::{CurrentUser, JsonApi, PolicyError::*, Ugc};
use crate::api::{CurrentUser, JsonAPI, PolicyError::*, UGC};
use crate::db_conn::Db;
use crate::libs::diesel_logger::LoggingConnection;
use crate::models::*;
use crate::rds_conn::RdsConn;
use crate::rds_models::*;
use crate::schema;
use diesel::{ExpressionMethods, QueryDsl, RunQueryDsl};
use rocket::form::Form;
use rocket::serde::json::json;
use rocket::serde::json::serde_json;
use rocket::serde::Serialize;
use std::fs::File;
use url::Url;
use web_push::{
ContentEncoding, SubscriptionInfo, VapidSignatureBuilder, WebPushClient, WebPushMessageBuilder,
};
#[derive(FromForm)]
pub struct AttentionInput {
@ -27,9 +23,9 @@ pub async fn attention_post(
user: CurrentUser,
db: Db,
rconn: RdsConn,
) -> JsonApi {
) -> JsonAPI {
// 临时用户不允许手动关注
user.id.ok_or(YouAreTmp)?;
user.id.ok_or_else(|| NotAllowed)?;
let mut p = Post::get(&db, &rconn, ai.pid).await?;
p.check_permission(&user, "r")?;
@ -44,17 +40,12 @@ pub async fn attention_post(
att.remove(ai.pid).await?;
delta = -1;
}
let hot_delta = if p.n_attentions <= 3 * p.n_comments {
delta * 2
} else {
0
};
update!(
p,
posts,
&db,
{ n_attentions, add delta },
{ hot_score, add hot_delta }
{ hot_score, add delta * 2 }
);
if switch_to && user.is_admin {
update!(p, posts, &db, { is_reported, to false });
@ -72,72 +63,11 @@ pub async fn attention_post(
}
#[get("/getattention")]
pub async fn get_attention(user: CurrentUser, db: Db, rconn: RdsConn) -> JsonApi {
pub async fn get_attention(user: CurrentUser, db: Db, rconn: RdsConn) -> JsonAPI {
let mut ids = Attention::init(&user.namehash, &rconn).all().await?;
ids.sort_by_key(|x| -x);
let ps: Vec<Post> = Post::get_multi(&db, &rconn, &ids)
.await?
.into_iter()
.filter(|post| {
!post.get_is_private()
|| chrono::offset::Utc::now() - post.create_time < chrono::Duration::days(30)
})
.collect();
let ps_data = ps2outputs(&ps, &user, &db, &rconn).await?;
let ps = Post::get_multi(&db, &rconn, &ids).await?;
let ps_data = ps2outputs(&ps, &user, &db, &rconn).await;
code0!(ps_data)
}
#[derive(FromForm)]
pub struct NotificatinInput {
enable: bool,
endpoint: String,
auth: String,
p256dh: String,
}
#[derive(Serialize)]
#[serde(crate = "rocket::serde")]
struct PushData {
title: String,
pid: i32,
text: String,
}
#[post("/post/<pid>/notification", data = "<ni>")]
pub async fn set_notification(pid: i32, ni: Form<NotificatinInput>, _user: CurrentUser) -> JsonApi {
let url_host = Url::parse(&ni.endpoint)
.map_err(|_| UnknownPushEndpoint)?
.host()
.ok_or(UnknownPushEndpoint)?
.to_string();
(url_host.ends_with("googleapis.com") || url_host.ends_with("mozilla.com"))
.then_some(())
.ok_or(UnknownPushEndpoint)?;
if ni.enable {
let subscription_info = SubscriptionInfo::new(&ni.endpoint, &ni.p256dh, &ni.auth);
let file = File::open("keys/private.pem").unwrap();
let sig_builder = VapidSignatureBuilder::from_pem(file, &subscription_info)
.unwrap()
.build()
.unwrap();
let mut builder = WebPushMessageBuilder::new(&subscription_info).unwrap();
let data = PushData {
title: "测试".to_owned(),
pid,
text: format!("#{} 开启提醒测试成功,消息提醒功能即将正式上线", &pid),
};
let content = serde_json::to_string(&data).unwrap();
builder.set_payload(ContentEncoding::Aes128Gcm, content.as_bytes());
builder.set_vapid_signature(sig_builder);
let client = WebPushClient::new()?;
client.send(builder.build()?).await?;
}
code0!()
}

79
src/api/comment.rs

@ -1,16 +1,21 @@
use crate::api::{ApiError, CurrentUser, JsonApi, PolicyError::*, Ugc};
use crate::cache::BlockDictCache;
use crate::api::{APIError, CurrentUser, JsonAPI, PolicyError::*, UGC};
use crate::db_conn::Db;
use crate::libs::diesel_logger::LoggingConnection;
use crate::models::*;
use crate::rds_conn::RdsConn;
use crate::rds_models::*;
use futures::{future, join};
use crate::schema;
use chrono::{offset::Utc, DateTime};
use diesel::{ExpressionMethods, QueryDsl, RunQueryDsl};
use rocket::form::Form;
use rocket::futures::future;
use rocket::futures::join;
use rocket::serde::{json::json, Serialize};
use std::collections::HashMap;
#[derive(FromForm)]
pub struct CommentInput {
pid: i32,
#[field(validate = len(1..12289))]
text: String,
use_title: Option<i8>,
@ -25,9 +30,9 @@ pub struct CommentOutput {
can_del: bool,
name_id: i32,
is_tmp: bool,
create_time: i64,
create_time: DateTime<Utc>,
is_blocked: bool,
//blocked_count: Option<i32>,
blocked_count: Option<i32>,
// for old version frontend
timestamp: i64,
blocked: bool,
@ -35,10 +40,9 @@ pub struct CommentOutput {
pub async fn c2output<'r>(
p: &'r Post,
cs: &[Comment],
cs: &Vec<Comment>,
user: &CurrentUser,
cached_block_dict: &HashMap<String, bool>,
//rconn: &RdsConn,
rconn: &RdsConn,
) -> Vec<CommentOutput> {
let mut hash2id = HashMap::<&String, i32>::from([(&p.author_hash, 0)]);
let name_ids_iter = cs.iter().map(|c| match hash2id.get(&c.author_hash) {
@ -53,28 +57,24 @@ pub async fn c2output<'r>(
if c.is_deleted {
None
} else {
let is_blocked = cached_block_dict[&c.author_hash];
let can_view = user.is_admin
|| (!is_blocked && user.id.is_some() || user.namehash.eq(&c.author_hash));
let is_blocked =
BlockedUsers::check_blocked(rconn, user.id, &user.namehash, &c.author_hash)
.await
.unwrap_or_default();
Some(CommentOutput {
cid: c.id,
text: (if can_view { &c.content } else { "" }).to_string(),
text: format!("{}{}", if c.is_tmp { "[tmp]\n" } else { "" }, c.content),
author_title: c.author_title.to_string(),
can_del: c.check_permission(user, "wd").is_ok(),
name_id,
name_id: name_id,
is_tmp: c.is_tmp,
create_time: c.create_time.timestamp(),
is_blocked,
/*
create_time: c.create_time,
is_blocked: is_blocked,
blocked_count: if user.is_admin {
BlockCounter::get_count(rconn, &c.author_hash)
.await
.ok()
.flatten()
BlockCounter::get_count(rconn, &c.author_hash).await.ok()
} else {
None
},
*/
timestamp: c.create_time.timestamp(),
blocked: is_blocked,
})
@ -82,22 +82,18 @@ pub async fn c2output<'r>(
}))
.await
.into_iter()
.flatten()
.filter_map(|x| x)
.collect()
}
#[get("/getcomment?<pid>")]
pub async fn get_comment(pid: i32, user: CurrentUser, db: Db, rconn: RdsConn) -> JsonApi {
pub async fn get_comment(pid: i32, user: CurrentUser, db: Db, rconn: RdsConn) -> JsonAPI {
let p = Post::get(&db, &rconn, pid).await?;
if p.is_deleted {
return Err(ApiError::Pc(IsDeleted));
return Err(APIError::PcError(IsDeleted));
}
let cs = p.get_comments(&db, &rconn).await?;
let hash_list = cs.iter().map(|c| &c.author_hash).collect::<Vec<_>>();
let cached_block_dict = BlockDictCache::init(&user.namehash, p.id, &rconn)
.get_or_create(&user, &hash_list)
.await?;
let data = c2output(&p, &cs, &user, &cached_block_dict).await;
let data = c2output(&p, &cs, &user, &rconn).await;
Ok(json!({
"code": 0,
@ -109,30 +105,27 @@ pub async fn get_comment(pid: i32, user: CurrentUser, db: Db, rconn: RdsConn) ->
}))
}
#[post("/post/<pid>/comment", data = "<ci>")]
#[post("/docomment", data = "<ci>")]
pub async fn add_comment(
pid: i32,
ci: Form<CommentInput>,
user: CurrentUser,
db: Db,
rconn: RdsConn,
) -> JsonApi {
let mut p = Post::get(&db, &rconn, pid).await?;
if p.author_hash != user.namehash {
user.id.ok_or(YouAreTmp)?;
}
let use_title = ci.use_title.is_some() || user.is_admin || user.is_candidate;
) -> JsonAPI {
let mut p = Post::get(&db, &rconn, ci.pid).await?;
let c = Comment::create(
&db,
NewComment {
content: ci.text.to_string(),
author_hash: user.namehash.to_string(),
author_title: user
.custom_title
.and_then(|title| use_title.then_some(title))
.unwrap_or_default(),
author_title: (if ci.use_title.is_some() {
CustomTitle::get(&rconn, &user.namehash).await?
} else {
None
})
.unwrap_or_default(),
is_tmp: user.id.is_none(),
post_id: pid,
post_id: ci.pid,
},
)
.await?;
@ -146,7 +139,7 @@ pub async fn add_comment(
at_delta = 1;
att.add(p.id).await?;
} else {
hs_delta = (p.n_comments < 3 * p.n_attentions) as i32;
hs_delta = 1;
at_delta = 0;
}

243
src/api/mod.rs

@ -1,12 +1,12 @@
#![allow(clippy::unnecessary_lazy_evaluations)]
use crate::db_conn::Db;
use crate::libs::diesel_logger::LoggingConnection;
use crate::models::*;
use crate::random_hasher::RandomHasher;
use crate::rate_limit::MainLimiters;
use crate::rds_conn::RdsConn;
use crate::rds_models::*;
use rocket::http::{Method, Status};
use crate::rds_models::BannedUsers;
use crate::schema;
use diesel::{ExpressionMethods, QueryDsl, RunQueryDsl};
use rocket::http::Status;
use rocket::outcome::try_outcome;
use rocket::request::{FromRequest, Outcome, Request};
use rocket::response::{self, Responder};
@ -25,24 +25,6 @@ macro_rules! code0 {
);
}
/*
macro_rules! code1 {
($msg:expr) => (
Ok(json!({
"code": 1,
"msg": $msg,
}))
);
}
*/
macro_rules! e2s {
($e:expr) => (json!({
"code": -1,
"msg": $e.to_string()
}));
}
#[catch(401)]
pub fn catch_401_error() -> &'static str {
"未登录或token过期"
@ -53,37 +35,11 @@ pub fn catch_403_error() -> &'static str {
"可能被封禁了,等下次重置吧"
}
#[catch(404)]
pub fn catch_404_error() -> &'static str {
"请更新前端版本"
}
pub struct CurrentUser {
pub id: Option<i32>, // tmp user has no id, only for block
id: Option<i32>, // tmp user has no id, only for block
namehash: String,
is_admin: bool,
is_candidate: bool,
custom_title: Option<String>,
title_secret: Option<String>,
pub auto_block_rank: u8,
}
impl CurrentUser {
pub async fn from_hash(rconn: &RdsConn, namehash: String) -> Self {
let (custom_title, title_secret) = CustomTitle::get(rconn, &namehash)
.await
.ok()
.unwrap_or((None, None));
Self {
id: None,
is_admin: false,
is_candidate: false,
custom_title,
title_secret,
auto_block_rank: AutoBlockRank::get(rconn, &namehash).await.unwrap_or(2),
namehash,
}
}
custom_title: String,
}
#[rocket::async_trait]
@ -92,49 +48,40 @@ impl<'r> FromRequest<'r> for CurrentUser {
async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
let rh = request.rocket().state::<RandomHasher>().unwrap();
let rconn = try_outcome!(request.guard::<RdsConn>().await);
let limiters = request.rocket().state::<MainLimiters>().unwrap();
if let Some(user) = {
if let Some(token) = request.headers().get_one("User-Token") {
let sp = token.split('_').collect::<Vec<&str>>();
if sp.len() == 2 && sp[0] == rh.get_tmp_token() {
Some(CurrentUser::from_hash(&rconn, rh.hash_with_salt(sp[1])).await)
} else {
let db = try_outcome!(request.guard::<Db>().await);
if let Some(u) = User::get_by_token(&db, &rconn, token).await {
let namehash = rh.hash_with_salt(&u.name);
let user_base = CurrentUser::from_hash(&rconn, namehash).await;
Some(CurrentUser {
id: Some(u.id),
is_admin: u.is_admin
|| is_elected_admin(&rconn, &user_base.custom_title)
.await
.unwrap(),
is_candidate: is_elected_candidate(&rconn, &user_base.custom_title)
.await
.unwrap(),
..user_base
})
} else {
None
}
}
let mut id = None;
let mut namehash = None;
let mut is_admin = false;
if let Some(token) = request.headers().get_one("User-Token") {
let sp = token.split('_').collect::<Vec<&str>>();
if sp.len() == 2 && sp[0] == rh.get_tmp_token() {
namehash = Some(rh.hash_with_salt(sp[1]));
id = None;
is_admin = false;
} else {
None
let db = try_outcome!(request.guard::<Db>().await);
if let Some(u) = User::get_by_token(&db, &rconn, token).await {
id = Some(u.id);
namehash = Some(rh.hash_with_salt(&u.name));
is_admin = u.is_admin;
}
}
} {
if BannedUsers::has(&rconn, &user.namehash).await.unwrap() {
Outcome::Error((Status::Forbidden, ()))
} else if !limiters.check(
request.method() == Method::Post,
user.id.unwrap_or_default(),
) {
Outcome::Error((Status::TooManyRequests, ()))
} else {
Outcome::Success(user)
}
match namehash {
Some(nh) => {
if BannedUsers::has(&rconn, &nh).await.unwrap() {
Outcome::Failure((Status::Forbidden, ()))
} else {
Outcome::Success(CurrentUser {
id: id,
custom_title: format!("title todo: {}", &nh),
namehash: nh,
is_admin: is_admin,
})
}
}
} else {
Outcome::Error((Status::Unauthorized, ()))
None => Outcome::Failure((Status::Unauthorized, ())),
}
}
}
@ -142,46 +89,38 @@ impl<'r> FromRequest<'r> for CurrentUser {
#[derive(Debug)]
pub enum PolicyError {
IsReported,
IsPrivate,
IsDeleted,
NotAllowed,
TitleUsed,
TitleProtected,
InvalidTitle,
YouAreTmp,
NoReason,
UnknownPushEndpoint,
}
#[derive(Debug)]
pub enum ApiError {
Db(diesel::result::Error),
Rds(redis::RedisError),
WebPush(web_push::WebPushError),
Pc(PolicyError),
IO(std::io::Error),
pub enum APIError {
DbError(diesel::result::Error),
RdsError(redis::RedisError),
PcError(PolicyError),
}
impl<'r> Responder<'r, 'static> for ApiError {
impl<'r> Responder<'r, 'static> for APIError {
fn respond_to(self, req: &'r Request<'_>) -> response::Result<'static> {
match self {
ApiError::Db(e) => e2s!(e).respond_to(req),
ApiError::Rds(e) => e2s!(e).respond_to(req),
ApiError::WebPush(e) => e2s!(e).respond_to(req),
ApiError::IO(e) => e2s!(e).respond_to(req),
ApiError::Pc(e) => json!({
APIError::DbError(e) => json!({
"code": -1,
"msg": e.to_string()
})
.respond_to(req),
APIError::RdsError(e) => json!({
"code": -1,
"msg": e.to_string()
})
.respond_to(req),
APIError::PcError(e) => json!({
"code": -1,
"msg": match e {
PolicyError::IsReported => "内容被举报,处理中",
PolicyError::IsPrivate => "未被设置为公开",
PolicyError::IsDeleted => "内容被删除",
PolicyError::NotAllowed => "不允许的操作",
PolicyError::TitleUsed => "头衔已被使用",
PolicyError::TitleProtected => "头衔处于保护期",
PolicyError::InvalidTitle => "头衔包含不允许的符号",
PolicyError::YouAreTmp => "临时用户只可发布内容",
PolicyError::NoReason => "未填写理由",
PolicyError::UnknownPushEndpoint => "未知的浏览器推送地址",
}
})
.respond_to(req),
@ -189,70 +128,54 @@ impl<'r> Responder<'r, 'static> for ApiError {
}
}
impl From<web_push::WebPushError> for ApiError {
fn from(err: web_push::WebPushError) -> ApiError {
ApiError::WebPush(err)
impl From<diesel::result::Error> for APIError {
fn from(err: diesel::result::Error) -> APIError {
APIError::DbError(err)
}
}
impl From<diesel::result::Error> for ApiError {
fn from(err: diesel::result::Error) -> ApiError {
ApiError::Db(err)
impl From<redis::RedisError> for APIError {
fn from(err: redis::RedisError) -> APIError {
APIError::RdsError(err)
}
}
impl From<redis::RedisError> for ApiError {
fn from(err: redis::RedisError) -> ApiError {
ApiError::Rds(err)
impl From<PolicyError> for APIError {
fn from(err: PolicyError) -> APIError {
APIError::PcError(err)
}
}
impl From<std::io::Error> for ApiError {
fn from(err: std::io::Error) -> ApiError {
ApiError::IO(err)
}
}
impl From<PolicyError> for ApiError {
fn from(err: PolicyError) -> ApiError {
ApiError::Pc(err)
}
}
pub type Api<T> = Result<T, ApiError>;
pub type JsonApi = Api<Value>;
pub type API<T> = Result<T, APIError>;
pub type JsonAPI = API<Value>;
#[rocket::async_trait]
pub trait Ugc {
pub trait UGC {
fn get_author_hash(&self) -> &str;
fn get_is_deleted(&self) -> bool;
fn get_is_reported(&self) -> bool;
fn get_is_private(&self) -> bool;
fn extra_delete_condition(&self) -> bool;
async fn do_set_deleted(&mut self, db: &Db) -> Api<()>;
fn check_permission(&self, user: &CurrentUser, mode: &str) -> Api<()> {
if mode.contains('r') && self.get_is_deleted() {
return Err(ApiError::Pc(PolicyError::IsDeleted));
}
async fn do_set_deleted(&mut self, db: &Db) -> API<()>;
fn check_permission(&self, user: &CurrentUser, mode: &str) -> API<()> {
if user.is_admin {
return Ok(());
}
if mode.contains('o') && self.get_is_reported() {
return Err(ApiError::Pc(PolicyError::IsReported));
if mode.contains('r') && self.get_is_deleted() {
return Err(APIError::PcError(PolicyError::IsDeleted));
}
if mode.contains('o') && self.get_is_private() {
return Err(ApiError::Pc(PolicyError::IsPrivate));
if mode.contains('o') && self.get_is_reported() {
return Err(APIError::PcError(PolicyError::IsReported));
}
if mode.contains('w') && self.get_author_hash() != user.namehash {
return Err(ApiError::Pc(PolicyError::NotAllowed));
return Err(APIError::PcError(PolicyError::NotAllowed));
}
if mode.contains('d') && !self.extra_delete_condition() {
return Err(ApiError::Pc(PolicyError::NotAllowed));
return Err(APIError::PcError(PolicyError::NotAllowed));
}
Ok(())
}
async fn soft_delete(&mut self, user: &CurrentUser, db: &Db) -> Api<()> {
async fn soft_delete(&mut self, user: &CurrentUser, db: &Db) -> API<()> {
self.check_permission(user, "rwd")?;
self.do_set_deleted(db).await?;
@ -261,46 +184,40 @@ pub trait Ugc {
}
#[rocket::async_trait]
impl Ugc for Post {
impl UGC for Post {
fn get_author_hash(&self) -> &str {
&self.author_hash
}
fn get_is_reported(&self) -> bool {
self.is_reported
}
fn get_is_private(&self) -> bool {
!(self.allow_search || self.n_attentions > 20)
}
fn get_is_deleted(&self) -> bool {
self.is_deleted
}
fn extra_delete_condition(&self) -> bool {
self.room_id != 42
self.n_comments == 0
}
async fn do_set_deleted(&mut self, db: &Db) -> Api<()> {
async fn do_set_deleted(&mut self, db: &Db) -> API<()> {
update!(*self, posts, db, { is_deleted, to true });
Ok(())
}
}
#[rocket::async_trait]
impl Ugc for Comment {
impl UGC for Comment {
fn get_author_hash(&self) -> &str {
&self.author_hash
}
fn get_is_reported(&self) -> bool {
false
}
fn get_is_private(&self) -> bool {
false
}
fn get_is_deleted(&self) -> bool {
self.is_deleted
}
fn extra_delete_condition(&self) -> bool {
true
}
async fn do_set_deleted(&mut self, db: &Db) -> Api<()> {
async fn do_set_deleted(&mut self, db: &Db) -> API<()> {
update!(*self, comments, db, { is_deleted, to true });
Ok(())
}
@ -316,8 +233,6 @@ pub mod attention;
pub mod comment;
pub mod operation;
pub mod post;
pub mod reaction;
pub mod search;
pub mod systemlog;
pub mod upload;
pub mod vote;

151
src/api/operation.rs

@ -1,10 +1,12 @@
use crate::api::{ApiError, CurrentUser, JsonApi, PolicyError::*, Ugc};
use crate::cache::*;
use crate::api::{CurrentUser, JsonAPI, PolicyError::*, UGC};
use crate::db_conn::Db;
use crate::libs::diesel_logger::LoggingConnection;
use crate::models::*;
use crate::rds_conn::RdsConn;
use crate::rds_models::*;
use crate::schema;
use chrono::offset::Local;
use diesel::{ExpressionMethods, QueryDsl, RunQueryDsl};
use rocket::form::Form;
use rocket::serde::json::json;
@ -17,7 +19,7 @@ pub struct DeleteInput {
}
#[post("/delete", data = "<di>")]
pub async fn delete(di: Form<DeleteInput>, user: CurrentUser, db: Db, rconn: RdsConn) -> JsonApi {
pub async fn delete(di: Form<DeleteInput>, user: CurrentUser, db: Db, rconn: RdsConn) -> JsonAPI {
let (author_hash, p) = match di.id_type.as_str() {
"cid" => {
let mut c = Comment::get(&db, di.id).await?;
@ -38,18 +40,7 @@ pub async fn delete(di: Form<DeleteInput>, user: CurrentUser, db: Db, rconn: Rds
}
"pid" => {
let mut p = Post::get(&db, &rconn, di.id).await?;
// 有评论:清空主楼而非删除
if p.author_hash == user.namehash && p.n_comments > 0 {
update! {
p,
posts,
&db,
{ content, to "[洞主已删除]" }
}
} else {
p.soft_delete(&user, &db).await?;
}
p.soft_delete(&user, &db).await?;
// 如果是删除,需要也从0号缓存队列中去掉
p.refresh_cache(&rconn, true).await;
@ -61,7 +52,7 @@ pub async fn delete(di: Form<DeleteInput>, user: CurrentUser, db: Db, rconn: Rds
if user.is_admin && !user.namehash.eq(&author_hash) {
Systemlog {
user_hash: user.custom_title.clone().unwrap_or(look!(user.namehash)),
user_hash: user.namehash.clone(),
action_type: LogType::AdminDelete,
target: format!("#{}, {}={}", p.id, di.id_type, di.id),
detail: di.note.clone(),
@ -72,7 +63,7 @@ pub async fn delete(di: Form<DeleteInput>, user: CurrentUser, db: Db, rconn: Rds
if di.note.starts_with("!ban ") {
Systemlog {
user_hash: user.custom_title.unwrap_or(look!(user.namehash)),
user_hash: user.namehash.clone(),
action_type: LogType::Ban,
target: look!(author_hash),
detail: di.note.clone(),
@ -81,6 +72,7 @@ pub async fn delete(di: Form<DeleteInput>, user: CurrentUser, db: Db, rconn: Rds
.create(&rconn)
.await?;
BannedUsers::add(&rconn, &author_hash).await?;
DangerousUser::add(&rconn, &author_hash).await?;
}
}
@ -92,58 +84,34 @@ pub struct ReportInput {
pid: i32,
#[field(validate = len(0..1000))]
reason: String,
should_hide: Option<u8>,
}
#[post("/report", data = "<ri>")]
pub async fn report(ri: Form<ReportInput>, user: CurrentUser, db: Db, rconn: RdsConn) -> JsonApi {
pub async fn report(ri: Form<ReportInput>, user: CurrentUser, db: Db, rconn: RdsConn) -> JsonAPI {
// 临时用户不允许举报
user.id.ok_or(NotAllowed)?;
// 被拉黑10次不允许举报
(BlockCounter::get_count(&rconn, &user.namehash)
.await?
.unwrap_or(0)
< 10)
.then_some(())
.ok_or(NotAllowed)?;
(!ri.reason.is_empty()).then_some(()).ok_or(NoReason)?;
user.id.ok_or_else(|| NotAllowed)?;
let mut p = Post::get(&db, &rconn, ri.pid).await?;
if ri.should_hide.is_some() {
update!(p, posts, &db, { is_reported, to true });
p.refresh_cache(&rconn, false).await;
}
update!(p, posts, &db, { is_reported, to true });
p.refresh_cache(&rconn, false).await;
Systemlog {
user_hash: look!(user.namehash),
user_hash: user.namehash,
action_type: LogType::Report,
target: format!("#{}", ri.pid),
target: format!(
"#{} {}",
ri.pid,
if ri.reason.starts_with("评论区") {
"评论区"
} else {
""
}
),
detail: ri.reason.clone(),
time: Local::now(),
}
.create(&rconn)
.await?;
// 自动发布一条洞
let p = Post::create(
&db,
NewPost {
content: format!("[系统自动代发]\n我举报了 #{}\n理由: {}", &p.id, &ri.reason),
cw: "举报".to_string(),
author_hash: user.namehash.clone(),
author_title: String::default(),
is_tmp: false,
n_attentions: 1,
allow_search: true,
room_id: 42,
},
)
.await?;
Attention::init(&user.namehash, &rconn).add(p.id).await?;
p.refresh_cache(&rconn, true).await;
code0!()
}
@ -155,46 +123,31 @@ pub struct BlockInput {
}
#[post("/block", data = "<bi>")]
pub async fn block(bi: Form<BlockInput>, user: CurrentUser, db: Db, rconn: RdsConn) -> JsonApi {
user.id.ok_or(NotAllowed)?;
pub async fn block(bi: Form<BlockInput>, user: CurrentUser, db: Db, rconn: RdsConn) -> JsonAPI {
let mut blk = BlockedUsers::init(user.id.ok_or_else(|| NotAllowed)?, &rconn);
let mut blk = BlockedUsers::init(user.id.ok_or(NotAllowed)?, &rconn);
let pid;
let nh_to_block = match bi.content_type.as_str() {
"post" => {
let p = Post::get(&db, &rconn, bi.id).await?;
pid = p.id;
p.author_hash
}
"comment" => {
let c = Comment::get(&db, bi.id).await?;
pid = c.post_id;
c.author_hash
}
_ => return Err(ApiError::Pc(NotAllowed)),
"post" => Post::get(&db, &rconn, bi.id).await?.author_hash,
"comment" => Comment::get(&db, bi.id).await?.author_hash,
_ => Err(NotAllowed)?,
};
if nh_to_block.eq(&user.namehash) {
Err(NotAllowed)?;
}
let curr = if blk.add(&nh_to_block).await? > 0 {
BlockCounter::count_incr(&rconn, &nh_to_block).await?
} else {
BlockCounter::get_count(&rconn, &nh_to_block)
.await?
.unwrap_or_default()
};
blk.add(&nh_to_block).await?;
let curr = BlockCounter::count_incr(&rconn, &nh_to_block).await?;
BlockDictCache::init(&user.namehash, pid, &rconn)
.clear()
.await?;
if curr >= BLOCK_THRESHOLD || user.is_admin {
DangerousUser::add(&rconn, &nh_to_block).await?;
}
Ok(json!({
"code": 0,
"data": {
"curr": curr,
"threshold": BLOCK_THRESHOLD,
},
}))
}
@ -203,37 +156,13 @@ pub async fn block(bi: Form<BlockInput>, user: CurrentUser, db: Db, rconn: RdsCo
pub struct TitleInput {
#[field(validate = len(1..31))]
title: String,
secret: String,
}
#[post("/set-title", data = "<ti>")]
pub async fn set_title(ti: Form<TitleInput>, user: CurrentUser, rconn: RdsConn) -> JsonApi {
if ti.title.is_empty() {
Err(InvalidTitle)?
#[post("/title", data = "<ti>")]
pub async fn set_title(ti: Form<TitleInput>, user: CurrentUser, rconn: RdsConn) -> JsonAPI {
if CustomTitle::set(&rconn, &user.namehash, &ti.title).await? {
code0!()
} else {
Err(TitleUsed)?
}
/*
ti.title
.chars()
.map(|c| c.is_alphanumeric().then_some(()).ok_or(InvalidTitle))
.collect::<Result<Vec<()>, PolicyError>>()?;
*/
let secret = CustomTitle::set(&rconn, &user.namehash, &ti.title, &ti.secret).await?;
code0!(secret)
}
#[derive(FromForm)]
pub struct AutoBlockInput {
rank: u8,
}
#[post("/auto_block", data = "<ai>")]
pub async fn set_auto_block(
ai: Form<AutoBlockInput>,
user: CurrentUser,
rconn: RdsConn,
) -> JsonApi {
AutoBlockRank::set(&rconn, &user.namehash, ai.rank).await?;
code0!()
}

183
src/api/post.rs

@ -1,13 +1,16 @@
use crate::api::comment::{c2output, CommentOutput};
use crate::api::vote::get_poll_dict;
use crate::api::{Api, CurrentUser, JsonApi, PolicyError::*, Ugc};
use crate::cache::*;
use crate::api::{CurrentUser, JsonAPI, UGC};
use crate::db_conn::Db;
use crate::libs::diesel_logger::LoggingConnection;
use crate::models::*;
use crate::rds_conn::RdsConn;
use crate::rds_models::*;
use crate::schema;
use chrono::{offset::Utc, DateTime};
use diesel::{ExpressionMethods, QueryDsl, RunQueryDsl};
use rocket::form::Form;
use rocket::futures::future::{self, OptionFuture};
use rocket::futures::future;
use rocket::serde::{
json::{json, Value},
Serialize,
@ -23,22 +26,20 @@ pub struct PostInput {
use_title: Option<i8>,
#[field(validate = len(0..97))]
poll_options: Vec<String>,
room_id: Option<i32>,
}
#[derive(Serialize)]
#[serde(crate = "rocket::serde")]
pub struct PostOutput {
pid: i32,
room_id: i32,
text: String,
cw: Option<String>,
author_title: Option<String>,
is_tmp: bool,
n_attentions: i32,
n_comments: i32,
create_time: i64,
last_comment_time: i64,
create_time: DateTime<Utc>,
last_comment_time: DateTime<Utc>,
allow_search: bool,
is_reported: Option<bool>,
comments: Option<Vec<CommentOutput>>,
@ -46,11 +47,8 @@ pub struct PostOutput {
attention: bool,
hot_score: Option<i32>,
is_blocked: bool,
//blocked_count: Option<i32>,
blocked_count: Option<i32>,
poll: Option<Value>,
up_votes: i32,
down_votes: i32,
reaction_status: i32, // -1, 0, 1
// for old version frontend
timestamp: i64,
likenum: i32,
@ -65,130 +63,97 @@ pub struct CwInput {
cw: String,
}
async fn p2output(p: &Post, user: &CurrentUser, db: &Db, rconn: &RdsConn) -> Api<PostOutput> {
let comments: Option<Vec<Comment>> = if p.n_comments < 5 {
Some(p.get_comments(db, rconn).await?)
} else {
None
};
let hash_list = comments
.iter()
.flatten()
.map(|c| &c.author_hash)
.chain(std::iter::once(&p.author_hash))
.collect::<Vec<_>>();
//dbg!(&hash_list);
let cached_block_dict = BlockDictCache::init(&user.namehash, p.id, rconn)
.get_or_create(user, &hash_list)
.await?;
let is_blocked = cached_block_dict[&p.author_hash];
let can_view =
user.is_admin || (!is_blocked && user.id.is_some() || user.namehash.eq(&p.author_hash));
Ok(PostOutput {
async fn p2output(p: &Post, user: &CurrentUser, db: &Db, rconn: &RdsConn) -> PostOutput {
let is_blocked = BlockedUsers::check_blocked(rconn, user.id, &user.namehash, &p.author_hash)
.await
.unwrap_or_default();
PostOutput {
pid: p.id,
room_id: p.room_id,
text: can_view.then_some(p.content.clone()).unwrap_or_default(),
cw: (!p.cw.is_empty()).then_some(p.cw.clone()),
text: format!("{}{}", if p.is_tmp { "[tmp]\n" } else { "" }, p.content),
cw: (!p.cw.is_empty()).then(|| p.cw.to_string()),
n_attentions: p.n_attentions,
n_comments: p.n_comments,
create_time: p.create_time.timestamp(),
last_comment_time: p.last_comment_time.timestamp(),
create_time: p.create_time,
last_comment_time: p.last_comment_time,
allow_search: p.allow_search,
author_title: (!p.author_title.is_empty()).then_some(p.author_title.clone()),
author_title: (!p.author_title.is_empty()).then(|| p.author_title.to_string()),
is_tmp: p.is_tmp,
is_reported: user.is_admin.then_some(p.is_reported),
comments: OptionFuture::from(
comments.map(|cs| async move { c2output(p, &cs, user, &cached_block_dict).await }),
)
.await,
can_del: p.check_permission(user, "wd").is_ok(),
attention: Attention::init(&user.namehash, rconn).has(p.id).await?,
hot_score: user.is_admin.then_some(p.hot_score),
is_blocked,
/*
blocked_count: if user.is_admin {
BlockCounter::get_count(rconn, &p.author_hash).await?
} else {
is_reported: user.is_admin.then(|| p.is_reported),
comments: if p.n_comments > 50 {
None
} else {
// 单个洞还有查询评论的接口,这里挂了不用报错
Some(
c2output(
p,
&p.get_comments(db, rconn).await.unwrap_or(vec![]),
user,
rconn,
)
.await,
)
},
*/
poll: if can_view {
get_poll_dict(p.id, rconn, &user.namehash).await
can_del: p.check_permission(user, "wd").is_ok(),
attention: Attention::init(&user.namehash, &rconn)
.has(p.id)
.await
.unwrap_or_default(),
hot_score: user.is_admin.then(|| p.hot_score),
is_blocked: is_blocked,
blocked_count: if user.is_admin {
BlockCounter::get_count(rconn, &p.author_hash).await.ok()
} else {
None
},
up_votes: p.up_votes,
down_votes: p.down_votes,
reaction_status: get_user_post_reaction_status(rconn, p.id, &user.namehash).await?,
poll: get_poll_dict(p.id, rconn, &user.namehash).await,
// for old version frontend
timestamp: p.create_time.timestamp(),
likenum: p.n_attentions,
reply: p.n_comments,
blocked: is_blocked,
})
}
}
pub async fn ps2outputs(
ps: &[Post],
ps: &Vec<Post>,
user: &CurrentUser,
db: &Db,
rconn: &RdsConn,
) -> Api<Vec<PostOutput>> {
future::try_join_all(
) -> Vec<PostOutput> {
future::join_all(
ps.iter()
.map(|p| async { p2output(p, user, db, rconn).await }),
.map(|p| async { p2output(p, &user, &db, &rconn).await }),
)
.await
}
#[get("/getone?<pid>")]
pub async fn get_one(pid: i32, user: CurrentUser, db: Db, rconn: RdsConn) -> JsonApi {
user.id.ok_or(YouAreTmp)?;
pub async fn get_one(pid: i32, user: CurrentUser, db: Db, rconn: RdsConn) -> JsonAPI {
let p = Post::get(&db, &rconn, pid).await?;
p.check_permission(&user, "ro")?;
Ok(json!({
"data": p2output(&p, &user,&db, &rconn).await?,
"data": p2output(&p, &user,&db, &rconn).await,
"code": 0,
}))
}
#[get("/getlist?<p>&<order_mode>&<room_id>")]
#[get("/getlist?<p>&<order_mode>")]
pub async fn get_list(
p: Option<u32>,
order_mode: u8,
room_id: Option<i32>,
user: CurrentUser,
db: Db,
rconn: RdsConn,
) -> JsonApi {
user.id.ok_or(YouAreTmp)?;
) -> JsonAPI {
let page = p.unwrap_or(1);
let page_size = 25;
let start = (page - 1) * page_size;
let ps: Vec<Post> = Post::gets_by_page(
&db,
&rconn,
room_id,
order_mode,
start.into(),
page_size.into(),
)
.await?
.into_iter()
.filter(|post| page < 40 || !post.get_is_private())
.collect();
let ps_data = ps2outputs(&ps, &user, &db, &rconn).await?;
let ps = Post::gets_by_page(&db, &rconn, order_mode, start.into(), page_size.into()).await?;
let ps_data = ps2outputs(&ps, &user, &db, &rconn).await;
Ok(json!({
"data": ps_data,
"count": ps_data.len(),
"custom_title": user.custom_title,
"title_secret": user.title_secret,
"is_admin": user.is_admin,
"is_candidate": user.is_candidate,
"auto_block_rank": user.auto_block_rank,
"announcement": get_announcement(&rconn).await?,
"custom_title": CustomTitle::get(&rconn, &user.namehash).await?,
"code": 0
}))
}
@ -199,30 +164,22 @@ pub async fn publish_post(
user: CurrentUser,
db: Db,
rconn: RdsConn,
) -> JsonApi {
let use_title = poi.use_title.is_some() || user.is_admin || user.is_candidate;
let is_tmp = user.id.is_none();
let room_id = if is_tmp {
0
} else {
poi.room_id.unwrap_or_default()
};
) -> JsonAPI {
let p = Post::create(
&db,
NewPost {
content: poi.text.to_string(),
cw: poi.cw.to_string(),
author_hash: user.namehash.to_string(),
author_title: user
.custom_title
.and_then(|title| use_title.then_some(title))
.unwrap_or_default(),
is_tmp,
author_title: (if poi.use_title.is_some() {
CustomTitle::get(&rconn, &user.namehash).await?
} else {
None
})
.unwrap_or_default(),
is_tmp: user.id.is_none(),
n_attentions: 1,
allow_search: poi.allow_search.is_some(),
room_id,
},
)
.await?;
@ -238,7 +195,7 @@ pub async fn publish_post(
}
#[post("/editcw", data = "<cwi>")]
pub async fn edit_cw(cwi: Form<CwInput>, user: CurrentUser, db: Db, rconn: RdsConn) -> JsonApi {
pub async fn edit_cw(cwi: Form<CwInput>, user: CurrentUser, db: Db, rconn: RdsConn) -> JsonAPI {
let mut p = Post::get(&db, &rconn, cwi.pid).await?;
p.check_permission(&user, "w")?;
update!(p, posts, &db, { cw, to cwi.cw.to_string() });
@ -247,17 +204,9 @@ pub async fn edit_cw(cwi: Form<CwInput>, user: CurrentUser, db: Db, rconn: RdsCo
}
#[get("/getmulti?<pids>")]
pub async fn get_multi(pids: Vec<i32>, user: CurrentUser, db: Db, rconn: RdsConn) -> JsonApi {
user.id.ok_or(YouAreTmp)?;
let ps: Vec<Post> = Post::get_multi(&db, &rconn, &pids)
.await?
.into_iter()
.filter(|post| {
!post.get_is_private()
|| chrono::offset::Utc::now() - post.create_time < chrono::Duration::days(30)
})
.collect();
let ps_data = ps2outputs(&ps, &user, &db, &rconn).await?;
pub async fn get_multi(pids: Vec<i32>, user: CurrentUser, db: Db, rconn: RdsConn) -> JsonAPI {
let ps = Post::get_multi(&db, &rconn, &pids).await?;
let ps_data = ps2outputs(&ps, &user, &db, &rconn).await;
Ok(json!({
"code": 0,

65
src/api/reaction.rs

@ -1,65 +0,0 @@
use crate::api::{CurrentUser, JsonApi, PolicyError::*, Ugc};
use crate::db_conn::Db;
use crate::models::*;
use crate::rds_conn::RdsConn;
use crate::rds_models::*;
use rocket::form::Form;
use rocket::serde::json::json;
#[derive(FromForm)]
pub struct ReactionInput {
#[field(validate = range(-1..2))]
status: i32,
}
#[post("/post/<pid>/reaction", data = "<ri>")]
pub async fn reaction(
pid: i32,
ri: Form<ReactionInput>,
user: CurrentUser,
db: Db,
rconn: RdsConn,
) -> JsonApi {
user.id.ok_or(YouAreTmp)?;
let mut p = Post::get(&db, &rconn, pid).await?;
p.check_permission(&user, "r")?;
let mut r_up = Reaction::init(pid, 1, &rconn);
let mut r_down = Reaction::init(pid, -1, &rconn);
let (delta_up, delta_down): (i32, i32) = match ri.status {
1 => (
r_up.add(&user.namehash).await? as i32,
-(r_down.rem(&user.namehash).await? as i32),
),
-1 => (
-(r_up.rem(&user.namehash).await? as i32),
r_down.add(&user.namehash).await? as i32,
),
_ => (
-(r_up.rem(&user.namehash).await? as i32),
-(r_down.rem(&user.namehash).await? as i32),
),
};
if delta_up != 0 || delta_down != 0 {
update!(
p,
posts,
&db,
{ up_votes, add delta_up },
{ down_votes, add delta_down }
);
p.refresh_cache(&rconn, false).await;
}
Ok(json!({
"code": 0,
"data": {
"up_votes": p.up_votes,
"down_votes": p.down_votes,
"reaction_status": ri.status,
},
}))
}

18
src/api/search.rs

@ -1,32 +1,32 @@
use crate::api::post::ps2outputs;
use crate::api::{CurrentUser, JsonApi, PolicyError::*};
use crate::api::{CurrentUser, JsonAPI};
use crate::db_conn::Db;
use crate::models::*;
use crate::rds_conn::RdsConn;
use rocket::serde::json::json;
#[get("/search?<search_mode>&<page>&<keywords>&<room_id>")]
#[get("/search?<search_mode>&<page>&<keywords>")]
pub async fn search(
room_id: Option<i32>,
keywords: String,
search_mode: u8,
page: i32,
user: CurrentUser,
db: Db,
rconn: RdsConn,
) -> JsonApi {
user.id.ok_or(YouAreTmp)?;
) -> JsonAPI {
let page_size = 25;
let start = (page - 1) * page_size;
let ps = if !keywords.chars().any(|c| !c.eq(&' ')) {
let kws = keywords
.split(" ")
.filter(|x| !x.is_empty())
.collect::<Vec<&str>>();
let ps = if kws.is_empty() {
vec![]
} else {
Post::search(
&db,
&rconn,
room_id,
search_mode,
keywords.to_string(),
start.into(),
@ -34,7 +34,7 @@ pub async fn search(
)
.await?
};
let ps_data = ps2outputs(&ps, &user, &db, &rconn).await?;
let ps_data = ps2outputs(&ps, &user, &db, &rconn).await;
Ok(json!({
"data": ps_data,
"count": ps_data.len(),

20
src/api/systemlog.rs

@ -1,35 +1,25 @@
use crate::api::{CurrentUser, JsonApi};
use crate::cache::cached_user_count;
use crate::db_conn::Db;
use crate::api::{CurrentUser, JsonAPI};
use crate::random_hasher::RandomHasher;
use crate::rds_conn::RdsConn;
use crate::rds_models::{get_admin_list, get_candidate_list, Systemlog};
use crate::rds_models::{Systemlog};
use rocket::serde::json::{json, Value};
use rocket::State;
#[get("/systemlog")]
pub async fn get_systemlog(
user: CurrentUser,
rh: &State<RandomHasher>,
db: Db,
mut rconn: RdsConn,
) -> JsonApi {
pub async fn get_systemlog(user: CurrentUser, rh: &State<RandomHasher>, rconn: RdsConn) -> JsonAPI {
let logs = Systemlog::get_list(&rconn, 50).await?;
Ok(json!({
"tmp_token": rh.get_tmp_token(),
"salt": look!(rh.salt),
"start_time": rh.start_time.timestamp(),
"user_count": cached_user_count(&db, &mut rconn).await?,
"custom_title": user.custom_title,
"admin_list": get_admin_list(&rconn).await?,
"candidate_list": get_candidate_list(&rconn).await?,
"data": logs.into_iter().map(|log|
json!({
"type": log.action_type,
"user": log.user_hash,
"user": look!(log.user_hash),
"timestamp": log.time.timestamp(),
"detail": format!("{}\n{}", &log.target, &log.detail),
"detail": format!("{}\n{}", &log.target, if user.is_admin || !log.action_type.contains_ugc() { &log.detail } else { "" })
})
).collect::<Vec<Value>>(),
}))

20
src/api/upload.rs

@ -1,20 +0,0 @@
use super::{CurrentUser, JsonApi};
use rocket::fs::TempFile;
use rocket::serde::json::json;
use std::env::var;
#[post("/upload", data = "<file>")]
pub async fn local_upload(_user: CurrentUser, mut file: TempFile<'_>) -> JsonApi {
let filename: String = format!(
"file{}.{}",
file.path().unwrap().file_name().unwrap().to_str().unwrap(),
file.content_type()
.map(|ct| ct.extension().unwrap_or_else(|| ct.sub()).as_str())
.unwrap_or("unknown")
);
file.copy_to(format!("{}/{}", var("UPLOAD_DIR").unwrap(), filename))
.await?;
code0!(json!({ "path": filename }))
}

15
src/api/vote.rs

@ -1,4 +1,4 @@
use crate::api::{CurrentUser, JsonApi, PolicyError::*};
use crate::api::{CurrentUser, JsonAPI, PolicyError::*};
use crate::rds_conn::RdsConn;
use crate::rds_models::*;
use rocket::form::Form;
@ -18,11 +18,11 @@ pub async fn get_poll_dict(pid: i32, rconn: &RdsConn, namehash: &str) -> Option<
.has(namehash)
.await
.unwrap_or_default()
.then_some(opt)
.then(|| opt)
}))
.await
.into_iter()
.flatten()
.filter_map(|x| x)
.collect::<Vec<&String>>()
.pop();
Some(json!({
@ -46,9 +46,7 @@ pub struct VoteInput {
}
#[post("/vote", data = "<vi>")]
pub async fn vote(vi: Form<VoteInput>, user: CurrentUser, rconn: RdsConn) -> JsonApi {
user.id.ok_or(NotAllowed)?;
pub async fn vote(vi: Form<VoteInput>, user: CurrentUser, rconn: RdsConn) -> JsonAPI {
let pid = vi.pid;
let opts = PollOption::init(pid, &rconn).get_list().await?;
if opts.is_empty() {
@ -61,7 +59,10 @@ pub async fn vote(vi: Form<VoteInput>, user: CurrentUser, rconn: RdsConn) -> Jso
}
}
let idx: usize = opts.iter().position(|x| x.eq(&vi.vote)).ok_or(NotAllowed)?;
let idx: usize = opts
.iter()
.position(|x| x.eq(&vi.vote))
.ok_or_else(|| NotAllowed)?;
PollVote::init(pid, idx, &rconn).add(&user.namehash).await?;

136
src/cache.rs

@ -1,20 +1,12 @@
use crate::api::{Api, CurrentUser};
use crate::db_conn::Db;
use crate::models::{Comment, Post, User};
use crate::rds_conn::RdsConn;
use crate::rds_models::{clear_all, init, BlockedUsers};
use crate::rds_models::init;
use rand::Rng;
use redis::{AsyncCommands, RedisError, RedisResult};
use redis::AsyncCommands;
use rocket::serde::json::serde_json;
// can use rocket::serde::json::to_string in master version
use futures_util::stream::StreamExt;
use rocket::futures::future;
use std::collections::HashMap;
const KEY_USER_COUNT: &str = "hole_v2:cache:user_count";
const USER_COUNT_EXPIRE_TIME: u64 = 5 * 60;
const INSTANCE_EXPIRE_TIME: u64 = 60 * 60;
const INSTANCE_EXPIRE_TIME: usize = 60 * 60;
const MIN_LENGTH: isize = 200;
const MAX_LENGTH: isize = 900;
@ -22,7 +14,7 @@ const CUT_LENGTH: isize = 100;
macro_rules! post_cache_key {
($id: expr) => {
format!("hole_v2:cache:post:{}:v2", $id)
format!("hole_v2:cache:post:{}", $id)
};
}
@ -33,9 +25,7 @@ pub struct PostCache {
impl PostCache {
init!();
clear_all!("hole_v2:cache::post:*:v2");
pub async fn sets(&mut self, ps: &[&Post]) {
pub async fn sets(&mut self, ps: &Vec<&Post>) {
if ps.is_empty() {
return;
}
@ -43,7 +33,7 @@ impl PostCache {
.iter()
.map(|p| (post_cache_key!(p.id), serde_json::to_string(p).unwrap()))
.collect();
self.rconn.mset(&kvs).await.unwrap_or_else(|e| {
self.rconn.set_multiple(&kvs).await.unwrap_or_else(|e| {
warn!("set post cache failed: {}", e);
dbg!(&kvs);
});
@ -68,7 +58,7 @@ impl PostCache {
})
}
pub async fn gets(&mut self, pids: &[i32]) -> Vec<Option<Post>> {
pub async fn gets(&mut self, pids: &Vec<i32>) -> Vec<Option<Post>> {
// 长度为1时会走GET而非MGET,返回值格式不兼容。愚蠢的设计。
match pids.len() {
0 => vec![],
@ -104,6 +94,27 @@ impl PostCache {
}
}
}
pub async fn clear_all(&mut self) {
let mut keys = self
.rconn
.scan_match::<String, String>(post_cache_key!("*"))
.await
.unwrap(); //.collect::<Vec<String>>().await;
// colllect() does not work
// also see: https://github.com/mitsuhiko/redis-rs/issues/583
let mut ks_for_del = Vec::new();
while let Some(key) = keys.next_item().await {
ks_for_del.push(key);
}
if ks_for_del.is_empty() {
return;
}
self.rconn
.del(ks_for_del)
.await
.unwrap_or_else(|e| warn!("clear all post cache fail, {}", e));
}
}
pub struct PostCommentCache {
@ -114,7 +125,7 @@ pub struct PostCommentCache {
impl PostCommentCache {
init!(i32, "hole_v2:cache:post_comments:{}");
pub async fn set(&mut self, cs: &[Comment]) {
pub async fn set(&mut self, cs: &Vec<Comment>) {
self.rconn
.set_ex(
&self.key,
@ -133,7 +144,7 @@ impl PostCommentCache {
// dbg!(&rds_result);
if let Ok(s) = rds_result {
self.rconn
.expire::<&String, bool>(&self.key, INSTANCE_EXPIRE_TIME as i64)
.expire::<&String, bool>(&self.key, INSTANCE_EXPIRE_TIME)
.await
.unwrap_or_else(|e| {
warn!(
@ -158,25 +169,18 @@ impl PostCommentCache {
}
}
pub struct PostListCache {
pub struct PostListCommentCache {
key: String,
mode: u8,
rconn: RdsConn,
length: isize,
}
impl PostListCache {
pub fn init(room_id: Option<i32>, mode: u8, rconn: &RdsConn) -> Self {
impl PostListCommentCache {
pub fn init(mode: u8, rconn: &RdsConn) -> Self {
Self {
key: format!(
"hole_v2:cache:post_list:{}:{}",
match room_id {
Some(i) => i.to_string(),
None => "".to_owned(),
},
&mode
),
mode,
key: format!("hole_v2:cache:post_list:{}", &mode),
mode: mode,
rconn: rconn.clone(),
length: 0,
}
@ -216,14 +220,13 @@ impl PostListCache {
1 => -p.last_comment_time.timestamp(),
2 => (-p.hot_score).into(),
3 => rand::thread_rng().gen_range(0..i64::MAX),
4 => (-p.n_attentions).into(),
_ => panic!("wrong mode"),
},
p.id,
)
}
pub async fn fill(&mut self, ps: &[Post]) {
pub async fn fill(&mut self, ps: &Vec<Post>) {
let items: Vec<(i64, i32)> = ps.iter().map(|p| self.p2pair(p)).collect();
self.rconn
.zadd_multiple(&self.key, &items)
@ -282,8 +285,6 @@ pub struct UserCache {
impl UserCache {
init!(&str, "hole_v2:cache:user:{}");
clear_all!("hole_v2:cache:user:*");
pub async fn set(&mut self, u: &User) {
self.rconn
.set_ex(
@ -302,7 +303,7 @@ impl UserCache {
let rds_result = self.rconn.get::<&String, String>(&self.key).await;
if let Ok(s) = rds_result {
self.rconn
.expire::<&String, bool>(&self.key, INSTANCE_EXPIRE_TIME as i64)
.expire::<&String, bool>(&self.key, INSTANCE_EXPIRE_TIME)
.await
.unwrap_or_else(|e| {
warn!(
@ -320,66 +321,3 @@ impl UserCache {
}
}
}
pub struct BlockDictCache {
key: String,
rconn: RdsConn,
}
impl BlockDictCache {
// namehash, pid
init!(&str, i32, "hole_v2:cache:block_dict:{}:{}");
pub async fn get_or_create(
&mut self,
user: &CurrentUser,
hash_list: &[&String],
) -> RedisResult<HashMap<String, bool>> {
let mut block_dict = self
.rconn
.hgetall::<&String, HashMap<String, bool>>(&self.key)
.await?;
//dbg!(&self.key, &block_dict);
let missing: Vec<(String, bool)> =
future::try_join_all(hash_list.iter().filter_map(|hash| {
(!block_dict.contains_key(&hash.to_string())).then_some(async {
Ok::<(String, bool), RedisError>((
hash.to_string(),
BlockedUsers::check_if_block(&self.rconn, user, hash).await?,
))
})
}))
.await?;
if !missing.is_empty() {
self.rconn.hset_multiple(&self.key, &missing).await?;
self.rconn
.expire(&self.key, INSTANCE_EXPIRE_TIME as i64)
.await?;
block_dict.extend(missing.into_iter());
}
//dbg!(&block_dict);
Ok(block_dict)
}
pub async fn clear(&mut self) -> RedisResult<()> {
self.rconn.del(&self.key).await
}
}
pub async fn cached_user_count(db: &Db, rconn: &mut RdsConn) -> Api<i64> {
let cnt: Option<i64> = rconn.get(KEY_USER_COUNT).await?;
if let Some(x) = cnt {
Ok(x)
} else {
let x = User::get_count(db).await?;
rconn
.set_ex(KEY_USER_COUNT, x, USER_COUNT_EXPIRE_TIME)
.await?;
Ok(x)
}
}

42
src/cors.rs

@ -1,42 +0,0 @@
#![allow(clippy::let_unit_value)]
use rocket::fairing::{Fairing, Info, Kind};
use rocket::http::Header;
use rocket::{Request, Response};
use std::path::PathBuf;
pub struct Cors {
pub whitelist: Vec<String>,
}
#[rocket::async_trait]
impl Fairing for Cors {
fn info(&self) -> Info {
Info {
name: "Add CORS headers to responses",
kind: Kind::Response,
}
}
async fn on_response<'r>(&self, request: &'r Request<'_>, response: &mut Response<'r>) {
if let Some(origin) = request.headers().get_one("Origin").and_then(|origin| {
self.whitelist
.contains(&origin.to_string())
.then_some(origin)
}) {
response.set_header(Header::new("Access-Control-Allow-Origin", origin));
response.set_header(Header::new(
"Access-Control-Allow-Methods",
"POST, GET, OPTIONS",
));
response.set_header(Header::new("Access-Control-Allow-Credentials", "true"));
response.set_header(Header::new(
"Access-Control-Allow-Headers",
"User-Token, Content-Type",
));
}
}
}
#[options("/<_path..>")]
pub async fn options_handler(_path: PathBuf) {}

8
src/db_conn.rs

@ -1,5 +1,5 @@
use diesel::Connection;
use rocket_sync_db_pools::{database, diesel};
use diesel::Connection;
use std::env;
pub type Conn = diesel::pg::PgConnection;
@ -7,9 +7,11 @@ pub type Conn = diesel::pg::PgConnection;
#[database("pg_v2")]
pub struct Db(Conn);
// get sync connection, only for annealing
pub fn establish_connection() -> Conn {
let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
let database_url = env::var("DATABASE_URL")
.expect("DATABASE_URL must be set");
Conn::establish(&database_url)
.unwrap_or_else(|_| panic!("Error connecting to {}", database_url))
.expect(&format!("Error connecting to {}", database_url))
}

148
src/libs/diesel_logger.rs

@ -0,0 +1,148 @@
/*
* from https://github.com/shssoichiro/diesel-logger
* change Connection to &mut Connection
*/
use std::ops::Deref;
use std::time::{Duration, Instant};
use diesel::backend::{Backend, UsesAnsiSavepointSyntax};
use diesel::connection::{AnsiTransactionManager, SimpleConnection};
use diesel::debug_query;
use diesel::deserialize::QueryableByName;
use diesel::prelude::*;
use diesel::query_builder::{AsQuery, QueryFragment, QueryId};
use diesel::sql_types::HasSqlType;
/// Wraps a diesel `Connection` to time and log each query using
/// the configured logger for the `log` crate.
///
/// Currently, this produces a `debug` log on every query,
/// an `info` on queries that take longer than 1 second,
/// and a `warn`ing on queries that take longer than 5 seconds.
/// These thresholds will be configurable in a future version.
pub struct LoggingConnection<'r, C: Connection>(&'r mut C);
impl<'r, C: Connection> LoggingConnection<'r, C> {
pub fn new(conn: &'r mut C) -> Self {
LoggingConnection(conn)
}
}
impl<'r, C: Connection> Deref for LoggingConnection<'r, C> {
type Target = C;
fn deref(&self) -> &Self::Target {
self.0
}
}
impl<'r, C> SimpleConnection for LoggingConnection<'r, C>
where
C: Connection + Send + 'static,
{
fn batch_execute(&self, query: &str) -> QueryResult<()> {
let start_time = Instant::now();
let result = self.0.batch_execute(query);
let duration = start_time.elapsed();
log_query(query, duration);
result
}
}
impl<C: Connection> Connection for LoggingConnection<'_, C>
where
C: Connection<TransactionManager = AnsiTransactionManager> + Send + 'static,
C::Backend: UsesAnsiSavepointSyntax,
<C::Backend as Backend>::QueryBuilder: Default,
{
type Backend = C::Backend;
type TransactionManager = C::TransactionManager;
fn establish(_: &str) -> ConnectionResult<Self> {
Err(ConnectionError::__Nonexhaustive)
//Ok(LoggingConnection(C::establish(database_url)?))
}
fn execute(&self, query: &str) -> QueryResult<usize> {
let start_time = Instant::now();
let result = self.0.execute(query);
let duration = start_time.elapsed();
log_query(query, duration);
result
}
fn query_by_index<T, U>(&self, source: T) -> QueryResult<Vec<U>>
where
T: AsQuery,
T::Query: QueryFragment<Self::Backend> + QueryId,
Self::Backend: HasSqlType<T::SqlType>,
U: Queryable<T::SqlType, Self::Backend>,
{
let query = source.as_query();
let debug_query = debug_query::<Self::Backend, _>(&query).to_string();
let start_time = Instant::now();
let result = self.0.query_by_index(query);
let duration = start_time.elapsed();
log_query(&debug_query, duration);
result
}
fn query_by_name<T, U>(&self, source: &T) -> QueryResult<Vec<U>>
where
T: QueryFragment<Self::Backend> + QueryId,
U: QueryableByName<Self::Backend>,
{
let debug_query = debug_query::<Self::Backend, _>(&source).to_string();
let start_time = Instant::now();
let result = self.0.query_by_name(source);
let duration = start_time.elapsed();
log_query(&debug_query, duration);
result
}
fn execute_returning_count<T>(&self, source: &T) -> QueryResult<usize>
where
T: QueryFragment<Self::Backend> + QueryId,
{
let debug_query = debug_query::<Self::Backend, _>(&source).to_string();
let start_time = Instant::now();
let result = self.0.execute_returning_count(source);
let duration = start_time.elapsed();
log_query(&debug_query, duration);
result
}
fn transaction_manager(&self) -> &Self::TransactionManager {
self.0.transaction_manager()
}
}
fn log_query(query: &str, duration: Duration) {
if duration.as_secs() >= 5 {
warn!(
"Slow query ran in {:.2} seconds: {}",
duration_to_secs(duration),
query
);
} else if duration.as_secs() >= 1 {
info!(
"Slow query ran in {:.2} seconds: {}",
duration_to_secs(duration),
query
);
} else {
debug!("Query ran in {:.1} ms: {}", duration_to_ms(duration), query);
}
}
const NANOS_PER_MILLI: u32 = 1_000_000;
const MILLIS_PER_SEC: u32 = 1_000;
fn duration_to_secs(duration: Duration) -> f32 {
duration_to_ms(duration) / MILLIS_PER_SEC as f32
}
fn duration_to_ms(duration: Duration) -> f32 {
(duration.as_secs() as u32 * 1000) as f32
+ (duration.subsec_nanos() as f32 / NANOS_PER_MILLI as f32)
}

1
src/libs/mod.rs

@ -0,0 +1 @@
pub mod diesel_logger;

198
src/login.rs

@ -1,68 +1,39 @@
#![allow(clippy::unused_unit)]
use crate::db_conn::Db;
use crate::models::User;
use crate::random_hasher::RandomHasher;
use rocket::request::{FromRequest, Outcome, Request};
use rocket::response::Redirect;
use rocket::serde::Deserialize;
use rocket::State;
use std::env;
use url::Url;
#[derive(Debug)]
pub struct FrontendAddr(pub String);
pub struct RefHeader(pub String);
#[rocket::async_trait]
impl<'r> FromRequest<'r> for FrontendAddr {
impl<'r> FromRequest<'r> for RefHeader {
type Error = ();
async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
Outcome::Success(Self(
request
.headers()
.get_one("Referer")
.map(|s| s.to_string())
.unwrap_or_else(|| env::var("DEFAULT_FRONTEND").unwrap()),
))
}
}
#[derive(Debug)]
pub struct BackendAddr(pub String);
#[rocket::async_trait]
impl<'r> FromRequest<'r> for BackendAddr {
type Error = ();
async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
Outcome::Success(Self(
request
.headers()
.get_one("Host")
.map(|s| format!("https://{}", s))
.unwrap_or_else(|| env::var("DEFAULT_BACKEND").unwrap()),
))
match request.headers().get_one("Referer") {
Some(h) => Outcome::Success(RefHeader(h.to_string())),
None => Outcome::Forward(()),
}
}
}
#[get("/?p=cs")]
pub fn cs_login(r: FrontendAddr, h: BackendAddr) -> Redirect {
pub fn cs_login(r: RefHeader) -> Redirect {
let mast_url = env::var("MAST_BASE_URL").unwrap();
let mast_cli = env::var("MAST_CLIENT").unwrap();
let mast_scope = env::var("MAST_SCOPE").unwrap();
let jump_to_url = Url::parse(&r.0).unwrap();
let mut redirect_url = Url::parse(&h.0).unwrap();
let mut redirect_url = Url::parse(&r.0).unwrap();
redirect_url.set_path("/_login/cs/auth");
redirect_url.set_query(None);
redirect_url = Url::parse_with_params(
redirect_url.as_str(),
&[
("redirect_url", redirect_url.as_str()),
("jump_to_url", jump_to_url.as_str()),
],
&[("redirect_url", redirect_url.as_str())],
)
.unwrap();
let url = Url::parse_with_params(
&format!("{}oauth/authorize", mast_url),
&[
@ -88,22 +59,8 @@ struct Token {
struct Account {
pub id: String,
}
#[get("/cs/auth?<code>&<redirect_url>&<jump_to_url>")]
pub async fn cs_auth(
code: String,
redirect_url: String,
jump_to_url: String,
db: Db,
rh: &State<RandomHasher>,
) -> Result<Redirect, &'static str> {
if !env::var("FRONTEND_WHITELIST")
.unwrap_or_default()
.split(',')
.any(|url| jump_to_url.starts_with(url))
{
return Err("前端地址不在白名单内");
}
#[get("/cs/auth?<code>&<redirect_url>")]
pub async fn cs_auth(code: String, redirect_url: String, db: Db) -> Redirect {
let mast_url = env::var("MAST_BASE_URL").unwrap();
let mast_cli = env::var("MAST_CLIENT").unwrap();
let mast_sec = env::var("MAST_SECRET").unwrap();
@ -112,15 +69,12 @@ pub async fn cs_auth(
// to keep same
let redirect_url = Url::parse_with_params(
redirect_url.as_str(),
&[
("redirect_url", redirect_url.as_str()),
("jump_to_url", jump_to_url.as_str()),
],
&[("redirect_url", redirect_url.as_str())],
)
.unwrap();
let client = reqwest::Client::new();
let r = client
let token: Token = client
.post(format!("{}oauth/token", &mast_url))
.form(&[
("client_id", mast_cli.as_str()),
@ -132,10 +86,11 @@ pub async fn cs_auth(
])
.send()
.await
.unwrap()
.json()
.await
.unwrap();
//dbg!(&r);
let token: Token = r.json().await.unwrap();
//dbg!(&token);
let client = reqwest::Client::new();
@ -151,124 +106,9 @@ pub async fn cs_auth(
//dbg!(&account);
let tk = User::find_or_create_token(
&db,
&rh.hash_with_salt(&format!("cs_{}", &account.id)),
false,
)
.await
.unwrap();
Ok(Redirect::to(format!("{}?token={}", &jump_to_url, &tk)))
}
#[get("/gh")]
pub fn gh_login(r: FrontendAddr, h: BackendAddr) -> Redirect {
let gh_url = "https://github.com/login/oauth/authorize";
let gh_cli = env::var("GH_CLIENT").unwrap();
let gh_scope = "user:email";
let jump_to_url = Url::parse(&r.0).unwrap();
let mut redirect_url = Url::parse(&h.0).unwrap();
redirect_url.set_path("/_login/gh/auth");
redirect_url = Url::parse_with_params(
redirect_url.as_str(),
&[("jump_to_url", jump_to_url.as_str())],
)
.unwrap();
let url = Url::parse_with_params(
gh_url,
&[
("redirect_uri", redirect_url.as_str()),
("client_id", &gh_cli),
("scope", gh_scope),
],
)
.unwrap();
Redirect::to(url.to_string())
}
#[derive(Deserialize, Debug)]
#[serde(crate = "rocket::serde")]
struct GithubEmail {
pub email: String,
pub verified: bool,
}
#[get("/gh/auth?<code>&<jump_to_url>")]
pub async fn gh_auth(
code: String,
jump_to_url: String,
db: Db,
rh: &State<RandomHasher>,
) -> Result<Redirect, &'static str> {
if !env::var("FRONTEND_WHITELIST")
.unwrap_or_default()
.split(',')
.any(|url| jump_to_url.starts_with(url))
{
return Err("前端地址不在白名单内");
}
let gh_cli = env::var("GH_CLIENT").unwrap();
let gh_sec = env::var("GH_SECRET").unwrap();
let client = reqwest::Client::new();
let r = client
.post("https://github.com/login/oauth/access_token")
.header(reqwest::header::ACCEPT, "application/json")
.form(&[
("client_id", gh_cli.as_str()),
("client_secret", gh_sec.as_str()),
("code", code.as_str()),
])
.send()
.await
.unwrap();
//let token: rocket::serde::json::Value = r.json().await.unwrap();
let token: Token = r.json().await.unwrap();
dbg!(&token);
let client = reqwest::Client::new();
let r = client
.get("https://api.github.com/user/emails")
.bearer_auth(token.access_token)
.header(reqwest::header::USER_AGENT, "hole_thu LoginBot")
.send()
.await
.unwrap();
// dbg!(&r);
let emails = r
.json::<Vec<GithubEmail>>()
//.json::<rocket::serde::json::Value>()
let tk = User::find_or_create_token(&db, &format!("cs_{}", &account.id), false)
.await
.unwrap();
//dbg!(&emails);
let name = emails
.iter()
.filter(|email| email.verified)
.find_map(
|email| match email.email.split('@').collect::<Vec<&str>>()[..] {
[name, "mails.tsinghua.edu.cn"] | [name, "tsinghua.org.cn"] => Some(name),
_ => None,
},
);
if let Some(name) = name {
let tk =
User::find_or_create_token(&db, &rh.hash_with_salt(&format!("email_{}", name)), false)
.await
.unwrap();
Ok(Redirect::to(format!("{}?token={}", &jump_to_url, &tk)))
} else {
Err("没有找到已验证的清华邮箱/校友邮箱")
}
Redirect::to(format!("/?token={}", tk))
}

100
src/main.rs

@ -1,3 +1,5 @@
#![feature(concat_idents)]
#[macro_use]
extern crate rocket;
@ -12,67 +14,47 @@ extern crate log;
mod api;
mod cache;
mod cors;
mod db_conn;
#[cfg(feature = "mastlogin")]
mod libs;
mod login;
mod models;
mod random_hasher;
mod rate_limit;
mod rds_conn;
mod rds_models;
mod schema;
use std::env;
use diesel::Connection;
use diesel_migrations::{EmbeddedMigrations, MigrationHarness};
use rocket::tokio;
use rocket::tokio::time::{sleep, Duration};
use db_conn::{establish_connection, Conn, Db};
use diesel::Connection;
use random_hasher::RandomHasher;
use rate_limit::MainLimiters;
use rds_conn::{init_rds_client, RdsConn};
use rds_models::clear_outdate_redis_data;
use std::env;
use tokio::time::{sleep, Duration};
pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!("migrations/postgres");
embed_migrations!("migrations/postgres");
#[rocket::main]
async fn main() {
async fn main() -> Result<(), rocket::Error> {
load_env();
if env::args().any(|arg| arg.eq("--init-database")) {
init_database();
return;
return Ok(());
}
env_logger::init();
let rmc = init_rds_client().await;
let mut rconn = RdsConn(rmc.clone());
let mut c_start = establish_connection();
models::User::clear_non_admin_users(&mut c_start, &mut rconn).await;
clear_outdate_redis_data(&mut rconn).await;
tokio::spawn(async move {
loop {
sleep(Duration::from_secs(3 * 60 * 60)).await;
models::Post::annealing(&mut c_start, &mut rconn).await;
}
});
let rconn = RdsConn(rmc.clone());
clear_outdate_redis_data(&rconn.clone()).await;
tokio::spawn(async move {
loop {
for room_id in (0..5).map(Some).chain([None, Some(42)]) {
cache::PostListCache::init(room_id, 3, &rconn).clear().await;
}
sleep(Duration::from_secs(5 * 60)).await;
sleep(Duration::from_secs(4 * 60 * 60)).await;
models::Post::annealing(establish_connection(), &rconn).await;
}
});
let _ = rocket::build()
rocket::build()
.mount(
"/_api/v1",
routes![
api::comment::get_comment,
api::comment::add_comment,
api::post::get_list,
api::post::get_one,
api::post::publish_post,
@ -84,58 +66,21 @@ async fn main() {
api::systemlog::get_systemlog,
api::operation::delete,
api::operation::report,
api::operation::set_title,
api::operation::block,
api::operation::set_auto_block,
api::vote::vote,
cors::options_handler,
],
)
.mount(
"/_api/v2",
routes![
api::attention::set_notification,
api::reaction::reaction,
api::comment::add_comment,
api::operation::set_title,
api::upload::local_upload,
cors::options_handler,
],
)
.mount(
"/_login",
[
#[cfg(feature = "mastlogin")]
routes![
login::cs_login,
login::cs_auth,
login::gh_login,
login::gh_auth
],
routes![],
]
.concat(),
)
.mount("/_login", routes![login::cs_login, login::cs_auth])
.register(
"/_api",
catchers![
api::catch_401_error,
api::catch_403_error,
api::catch_404_error
],
catchers![api::catch_401_error, api::catch_403_error,],
)
.manage(MainLimiters::init())
.manage(RandomHasher::get_random_one())
.manage(rmc)
.attach(Db::fairing())
.attach(cors::Cors {
whitelist: env::var("FRONTEND_WHITELIST")
.unwrap_or_default()
.split(',')
.map(|s| s.to_string())
.collect::<Vec<String>>(),
})
.launch()
.await;
.await
}
fn load_env() {
@ -148,6 +93,11 @@ fn load_env() {
fn init_database() {
let database_url = env::var("DATABASE_URL").unwrap();
let mut conn = Conn::establish(&database_url).unwrap();
conn.run_pending_migrations(MIGRATIONS).unwrap();
let conn = Conn::establish(&database_url).unwrap();
embedded_migrations::run(&conn).unwrap();
}
async fn clear_outdate_redis_data(rconn: &RdsConn) {
rds_models::BannedUsers::clear(&rconn).await.unwrap();
rds_models::CustomTitle::clear(&rconn).await.unwrap();
}

147
src/models.rs

@ -1,11 +1,13 @@
// #![allow(clippy::all)]
#![allow(clippy::all)]
use crate::cache::*;
use crate::db_conn::{Conn, Db};
use crate::libs::diesel_logger::LoggingConnection;
use crate::random_hasher::random_string;
use crate::rds_conn::RdsConn;
use crate::schema::*;
use chrono::{offset::Utc, DateTime};
use diesel::dsl::any;
use diesel::sql_types::*;
use diesel::{
insert_into, BoolExpressionMethods, ExpressionMethods, QueryDsl, QueryResult, RunQueryDsl,
@ -13,10 +15,9 @@ use diesel::{
};
use rocket::futures::{future, join};
use rocket::serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::HashMap;
sql_function!(fn random());
no_arg_sql_function!(RANDOM, (), "Represents the sql RANDOM() function");
sql_function!(fn floor(x: Float) -> Int4);
sql_function!(fn float4(x: Int4) -> Float);
@ -39,7 +40,7 @@ macro_rules! _get_multi {
// eq(any()) is only for postgres
db.run(move |c| {
$table::table
.filter($table::id.eq_any(ids))
.filter($table::id.eq(any(ids)))
.filter($table::is_deleted.eq(false))
.load(with_log!(c))
})
@ -59,8 +60,6 @@ macro_rules! op_to_col_expr {
macro_rules! update {
($obj:expr, $table:ident, $db:expr, $({ $col:ident, $op:ident $v:expr }), + ) => {{
use crate::schema;
use diesel::{ExpressionMethods, QueryDsl, RunQueryDsl};
let id = $obj.id;
$obj = $db
.run(move |c| {
@ -83,10 +82,9 @@ macro_rules! base_query {
};
}
// TODO: log sql query
macro_rules! with_log {
($c: expr) => {
$c
&LoggingConnection::new($c)
};
}
@ -121,9 +119,6 @@ pub struct Post {
pub is_reported: bool,
pub hot_score: i32,
pub allow_search: bool,
pub room_id: i32,
pub up_votes: i32,
pub down_votes: i32,
}
#[derive(Queryable, Insertable, Serialize, Deserialize, Debug)]
@ -136,7 +131,7 @@ pub struct User {
}
#[derive(Insertable)]
#[diesel(table_name = posts)]
#[table_name = "posts"]
pub struct NewPost {
pub content: String,
pub cw: String,
@ -145,7 +140,6 @@ pub struct NewPost {
pub is_tmp: bool,
pub n_attentions: i32,
pub allow_search: bool,
pub room_id: i32,
}
impl Post {
@ -153,8 +147,8 @@ impl Post {
_get_multi!(posts);
pub async fn get_multi(db: &Db, rconn: &RdsConn, ids: &[i32]) -> QueryResult<Vec<Self>> {
let mut cacher = PostCache::init(rconn);
pub async fn get_multi(db: &Db, rconn: &RdsConn, ids: &Vec<i32>) -> QueryResult<Vec<Self>> {
let mut cacher = PostCache::init(&rconn);
let mut cached_posts = cacher.gets(ids).await;
let mut id2po = HashMap::<i32, &mut Option<Post>>::new();
@ -165,7 +159,7 @@ impl Post {
.zip(cached_posts.iter_mut())
.filter_map(|(pid, p)| match p {
None => {
id2po.insert(*pid, p);
id2po.insert(pid.clone(), p);
Some(pid)
}
_ => None,
@ -177,7 +171,7 @@ impl Post {
let missing_ps = Self::_get_multi(db, missing_ids).await?;
// dbg!(&missing_ps);
cacher.sets(&missing_ps.iter().collect::<Vec<_>>()).await;
cacher.sets(&missing_ps.iter().collect()).await;
for p in missing_ps.into_iter() {
if let Some(op) = id2po.get_mut(&p.id) {
@ -193,12 +187,12 @@ impl Post {
pub async fn get(db: &Db, rconn: &RdsConn, id: i32) -> QueryResult<Self> {
// 注意即使is_deleted也应该缓存和返回
let mut cacher = PostCache::init(rconn);
let mut cacher = PostCache::init(&rconn);
if let Some(p) = cacher.get(&id).await {
Ok(p)
} else {
let p = Self::_get(db, id).await?;
cacher.sets(&[&p]).await;
cacher.sets(&vec![&p]).await;
Ok(p)
}
}
@ -221,20 +215,19 @@ impl Post {
pub async fn gets_by_page(
db: &Db,
rconn: &RdsConn,
room_id: Option<i32>,
order_mode: u8,
start: i64,
limit: i64,
) -> QueryResult<Vec<Self>> {
let mut cacher = PostListCache::init(room_id, order_mode, rconn);
let mut cacher = PostListCommentCache::init(order_mode, &rconn);
if cacher.need_fill().await {
let pids =
Self::_get_ids_by_page(db, room_id, order_mode, 0, cacher.i64_minlen()).await?;
Self::_get_ids_by_page(db, order_mode.clone(), 0, cacher.i64_minlen()).await?;
let ps = Self::get_multi(db, rconn, &pids).await?;
cacher.fill(&ps).await;
}
let pids = if start + limit > cacher.i64_len() {
Self::_get_ids_by_page(db, room_id, order_mode, start, limit).await?
Self::_get_ids_by_page(db, order_mode, start, limit).await?
} else {
cacher.get_pids(start, limit).await
};
@ -243,7 +236,6 @@ impl Post {
}
async fn _get_ids_by_page(
db: &Db,
room_id: Option<i32>,
order_mode: u8,
start: i64,
limit: i64,
@ -251,23 +243,14 @@ impl Post {
db.run(move |c| {
let mut query = base_query!(posts).select(posts::id);
if order_mode > 0 {
query = query.filter(posts::is_reported.eq(false));
}
if order_mode == 1 {
query = query.filter(posts::n_comments.gt(0));
}
if let Some(ri) = room_id {
query = query.filter(posts::room_id.eq(ri));
query = query.filter(posts::is_reported.eq(false))
}
query = match order_mode {
0 => query.order(posts::id.desc()),
1 => query.order(posts::last_comment_time.desc()),
2 => query.order(posts::hot_score.desc()),
3 => query.order(random()),
4 => query.order(posts::n_attentions.desc()),
3 => query.order(RANDOM),
_ => panic!("Wrong order mode!"),
};
@ -279,13 +262,12 @@ impl Post {
pub async fn search(
db: &Db,
rconn: &RdsConn,
room_id: Option<i32>,
search_mode: u8,
search_text: String,
start: i64,
limit: i64,
) -> QueryResult<Vec<Self>> {
let search_text2 = search_text.replace('%', "\\%");
let search_text2 = search_text.replace("%", "\\%");
let pids = db
.run(move |c| {
let pat;
@ -294,38 +276,29 @@ impl Post {
.distinct()
.left_join(comments::table)
.filter(posts::is_reported.eq(false));
if let Some(ri) = room_id {
query = query.filter(posts::room_id.eq(ri));
}
// 先用搜索+缓存,性能有问题了再真的做tag表
query = match search_mode {
0 => {
pat = format!("%#{}%", &search_text2);
query.filter(
posts::cw
.eq(&search_text)
.or(posts::cw.eq(format!("#{}", &search_text)))
.or(posts::content.like(&pat))
.or(comments::content
query
.filter(posts::cw.eq(&search_text))
.or_filter(posts::cw.eq(format!("#{}", &search_text)))
.or_filter(posts::content.like(&pat))
.or_filter(
comments::content
.like(&pat)
.and(comments::is_deleted.eq(false))),
)
.and(comments::is_deleted.eq(false)),
)
}
1 => {
pat = format!("%{}%", search_text2.replace(' ', "%"));
pat = format!("%{}%", search_text2.replace(" ", "%"));
query
.filter(
posts::content.like(&pat).or(comments::content
.like(&pat)
.and(comments::is_deleted.eq(false))),
)
.filter(posts::content.like(&pat).or(comments::content.like(&pat)))
.filter(posts::allow_search.eq(true))
}
2 => query.filter(
posts::author_title
.eq(&search_text)
.or(comments::author_title.eq(&search_text)),
),
2 => query
.filter(posts::author_title.eq(&search_text))
.or_filter(comments::author_title.eq(&search_text)),
_ => panic!("Wrong search mode!"),
};
@ -349,35 +322,28 @@ impl Post {
}
pub async fn set_instance_cache(&self, rconn: &RdsConn) {
PostCache::init(rconn).sets(&[self]).await;
PostCache::init(rconn).sets(&vec![self]).await;
}
pub async fn refresh_cache(&self, rconn: &RdsConn, is_new: bool) {
join!(
self.set_instance_cache(rconn),
future::join_all((if is_new { [0, 2, 3, 4] } else { [1, 2, 3, 4] }).map(
|mode| async move {
PostListCache::init(None, mode, &rconn.clone())
.put(self)
.await;
PostListCache::init(Some(self.room_id), mode, &rconn.clone())
.put(self)
.await;
}
)),
future::join_all((if is_new { 0..4 } else { 1..4 }).map(|mode| async move {
PostListCommentCache::init(mode, &rconn.clone())
.put(self)
.await
})),
);
}
pub async fn annealing(c: &mut Conn, rconn: &mut RdsConn) {
pub async fn annealing(mut c: Conn, rconn: &RdsConn) {
info!("Time for annealing!");
diesel::update(posts::table.filter(posts::hot_score.gt(10)))
.set(posts::hot_score.eq(floor(float4(posts::hot_score) * 0.9)))
.execute(with_log!(c))
.execute(with_log!(&mut c))
.unwrap();
PostCache::clear_all(rconn).await;
for room_id in (0..5).map(Some).chain([None, Some(42)]) {
PostListCache::init(room_id, 2, rconn).clear().await;
}
PostCache::init(&rconn).clear_all().await;
PostListCommentCache::init(2, rconn).clear().await
}
}
@ -394,20 +360,7 @@ impl User {
}
pub async fn get_by_token(db: &Db, rconn: &RdsConn, token: &str) -> Option<Self> {
let real_token;
let token = match &token.split(':').collect::<Vec<&str>>()[..] {
["sha256", tk] => {
let mut h = Sha256::new();
h.update(tk);
h.update("hole");
real_token = format!("{:x}", h.finalize())[0..16].to_string();
&real_token
}
_ => token,
};
// dbg!(token);
let mut cacher = UserCache::init(token, rconn);
let mut cacher = UserCache::init(token, &rconn);
if let Some(u) = cacher.get().await {
Some(u)
} else {
@ -448,22 +401,10 @@ impl User {
})
.await
}
pub async fn clear_non_admin_users(c: &mut Conn, rconn: &mut RdsConn) {
diesel::delete(users::table.filter(users::is_admin.eq(false)))
.execute(c)
.unwrap();
UserCache::clear_all(rconn).await;
}
pub async fn get_count(db: &Db) -> QueryResult<i64> {
db.run(move |c| users::table.count().get_result(with_log!(c)))
.await
}
}
#[derive(Insertable)]
#[diesel(table_name = comments)]
#[table_name = "comments"]
pub struct NewComment {
pub content: String,
pub author_hash: String,

67
src/rate_limit.rs

@ -1,67 +0,0 @@
use std::iter;
use std::num::NonZeroUsize;
use std::sync::Mutex;
use std::time::SystemTime;
use lru::LruCache;
pub struct Limiter {
record: Mutex<LruCache<i32, Vec<u64>>>,
amount: u64,
interval: u64,
}
impl Limiter {
pub fn init(amount: u64, interval: u64) -> Self {
Self {
record: Mutex::new(LruCache::new(NonZeroUsize::new(2000).unwrap())),
amount,
interval,
}
}
pub fn check(&self, uid: i32) -> bool {
let t = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap()
.as_secs();
let mut r = self.record.lock().unwrap();
if let Some(ts) = r.pop(&uid) {
let new_ts: Vec<u64> = ts
.into_iter()
.chain(iter::once(t))
.filter(|&tt| tt + self.interval > t)
.collect();
let len = new_ts.len() as u64;
r.put(uid, new_ts);
len < self.amount
} else {
r.put(uid, vec![t]);
true
}
}
}
pub struct MainLimiters {
post_min: Limiter,
post_hour: Limiter,
get_hour: Limiter,
}
impl MainLimiters {
pub fn init() -> Self {
Self {
post_min: Limiter::init(6, 60),
post_hour: Limiter::init(50, 3600),
get_hour: Limiter::init(1000, 3600),
}
}
pub fn check(&self, is_post: bool, uid: i32) -> bool {
if is_post {
self.post_hour.check(uid) && self.post_min.check(uid)
} else {
self.get_hour.check(uid)
}
}
}

3
src/rds_conn.rs

@ -1,7 +1,7 @@
use redis::aio::MultiplexedConnection;
use rocket::request::{FromRequest, Outcome, Request};
use std::env;
use std::ops::{Deref, DerefMut};
use std::env;
pub struct RdsConn(pub MultiplexedConnection);
@ -34,6 +34,7 @@ impl DerefMut for RdsConn {
}
}
pub async fn init_rds_client() -> MultiplexedConnection {
let redis_url = env::var("REDIS_URL").expect("REDIS_URL must be set");
let client = redis::Client::open(redis_url).expect("connect to redis fail");

230
src/rds_models.rs

@ -1,8 +1,5 @@
use crate::api::{Api, CurrentUser, PolicyError};
use crate::random_hasher::random_string;
use crate::rds_conn::RdsConn;
use chrono::{offset::Local, DateTime};
use futures_util::stream::StreamExt;
use redis::{AsyncCommands, RedisResult};
use rocket::serde::json::serde_json;
use rocket::serde::{Deserialize, Serialize};
@ -15,7 +12,7 @@ macro_rules! init {
}
}
};
($ktype:ty, $formatter:literal) => {
($ktype:ty, $formatter:expr) => {
pub fn init(k: $ktype, rconn: &RdsConn) -> Self {
Self {
key: format!($formatter, k),
@ -23,7 +20,7 @@ macro_rules! init {
}
}
};
($k1type:ty, $k2type:ty, $formatter:literal) => {
($k1type:ty, $k2type:ty, $formatter:expr) => {
pub fn init(k1: $k1type, k2: $k2type, rconn: &RdsConn) -> Self {
Self {
key: format!($formatter, k1, k2),
@ -43,54 +40,20 @@ macro_rules! has {
macro_rules! add {
($vtype:ty) => {
pub async fn add(&mut self, v: $vtype) -> RedisResult<usize> {
pub async fn add(&mut self, v: $vtype) -> RedisResult<()> {
self.rconn.sadd(&self.key, v).await
}
};
}
macro_rules! rem {
($vtype:ty) => {
pub async fn rem(&mut self, v: $vtype) -> RedisResult<usize> {
self.rconn.srem(&self.key, v).await
}
};
}
macro_rules! clear_all {
($pattern:literal) => {
pub async fn clear_all(rconn: &mut RdsConn) {
let keys: Vec<String> = rconn
.scan_match::<&str, String>($pattern)
.await
.unwrap()
.collect::<Vec<String>>()
.await;
rconn
.del(keys)
.await
.unwrap_or_else(|e| warn!("clear all fail, pattern: {} , {}", $pattern, e));
}
};
}
const KEY_SYSTEMLOG: &str = "hole_v2:systemlog_list";
const KEY_BANNED_USERS: &str = "hole_v2:banned_user_hash_list";
const KEY_BLOCKED_COUNTER: &str = "hole_v2:blocked_counter";
const KEY_DANGEROUS_USERS: &str = "hole_thu:dangerous_users"; //兼容一下旧版
const KEY_CUSTOM_TITLE: &str = "hole_v2:title";
const CUSTOM_TITLE_KEEP_TIME: u64 = 7 * 24 * 60 * 60;
macro_rules! KEY_TITLE_SECRET {
($title: expr) => {
format!("hole_v2:title_secret:{}", $title)
};
}
const KEY_AUTO_BLOCK_RANK: &str = "hole_v2:auto_block_rank"; // rank * 5: 自动过滤的拉黑数阈值
const KEY_ANNOUNCEMENT: &str = "hole_v2:announcement";
const KEY_CANDIDATE: &str = "hole_v2:candidate";
const KEY_ADMIN: &str = "hole_v2:admin";
const SYSTEMLOG_MAX_LEN: isize = 1000;
pub const BLOCK_THRESHOLD: i32 = 10;
pub struct Attention {
key: String,
@ -104,8 +67,6 @@ impl Attention {
has!(i32);
clear_all!("hole_v2:attention:*");
pub async fn remove(&mut self, pid: i32) -> RedisResult<()> {
self.rconn.srem(&self.key, pid).await
}
@ -113,34 +74,8 @@ impl Attention {
pub async fn all(&mut self) -> RedisResult<Vec<i32>> {
self.rconn.smembers(&self.key).await
}
}
pub struct Reaction {
key: String,
rconn: RdsConn,
}
impl Reaction {
init!(i32, i32, "hole_v2:reaction:{}:{}");
add!(&str);
rem!(&str);
has!(&str);
}
pub async fn get_user_post_reaction_status(
rconn: &RdsConn,
pid: i32,
namehash: &str,
) -> RedisResult<i32> {
for rt in [-1, 1] {
if Reaction::init(pid, rt, rconn).has(namehash).await? {
return Ok(rt);
}
}
Ok(0)
// TODO: clear all
}
#[derive(Serialize, Deserialize, Debug)]
@ -151,7 +86,6 @@ pub enum LogType {
Ban,
}
/*
impl LogType {
pub fn contains_ugc(&self) -> bool {
match self {
@ -160,7 +94,6 @@ impl LogType {
}
}
}
*/
#[derive(Serialize, Deserialize, Debug)]
#[serde(crate = "rocket::serde")]
@ -209,8 +142,8 @@ impl BannedUsers {
rconn.clone().sismember(KEY_BANNED_USERS, namehash).await
}
pub async fn clear(rconn: &mut RdsConn) -> RedisResult<()> {
rconn.del(KEY_BANNED_USERS).await
pub async fn clear(rconn: &RdsConn) -> RedisResult<()> {
rconn.clone().del(KEY_BANNED_USERS).await
}
}
@ -226,18 +159,17 @@ impl BlockedUsers {
has!(&str);
clear_all!("hole_v2:blocked_users:*");
pub async fn check_if_block(
pub async fn check_blocked(
rconn: &RdsConn,
user: &CurrentUser,
hash: &str,
viewer_id: Option<i32>,
viewer_hash: &str,
author_hash: &str,
) -> RedisResult<bool> {
Ok(match user.id {
Some(id) => BlockedUsers::init(id, rconn).has(hash).await?,
Ok(match viewer_id {
Some(id) => Self::init(id, rconn).has(author_hash).await?,
None => false,
} || BlockCounter::get_count(rconn, hash).await?.unwrap_or(0)
>= i32::from(user.auto_block_rank) * 5)
} || (DangerousUser::has(rconn, author_hash).await?
&& !DangerousUser::has(rconn, viewer_hash).await?))
}
}
@ -248,91 +180,47 @@ impl BlockCounter {
rconn.clone().hincr(KEY_BLOCKED_COUNTER, namehash, 1).await
}
pub async fn get_count(rconn: &RdsConn, namehash: &str) -> RedisResult<Option<i32>> {
pub async fn get_count(rconn: &RdsConn, namehash: &str) -> RedisResult<i32> {
rconn.clone().hget(KEY_BLOCKED_COUNTER, namehash).await
}
}
pub struct CustomTitle;
pub struct DangerousUser;
impl CustomTitle {
async fn gen_and_set_secret(rconn: &RdsConn, title: &str) -> RedisResult<String> {
let secret = random_string(8);
impl DangerousUser {
pub async fn add(rconn: &RdsConn, namehash: &str) -> RedisResult<()> {
rconn
.clone()
.set_ex(KEY_TITLE_SECRET!(&title), &secret, CUSTOM_TITLE_KEEP_TIME)
.await?;
Ok(secret)
.sadd::<&str, &str, ()>(KEY_DANGEROUS_USERS, namehash)
.await
}
pub async fn has(rconn: &RdsConn, namehash: &str) -> RedisResult<bool> {
rconn.clone().sismember(KEY_DANGEROUS_USERS, namehash).await
}
}
pub struct CustomTitle;
impl CustomTitle {
// return false if title exits
pub async fn set(rconn: &RdsConn, namehash: &str, title: &str, secret: &str) -> Api<String> {
pub async fn set(rconn: &RdsConn, namehash: &str, title: &str) -> RedisResult<bool> {
let mut rconn = rconn.clone();
if rconn.hexists(KEY_CUSTOM_TITLE, title).await? {
Err(PolicyError::TitleUsed)?
Ok(false)
} else {
let ori_secret: Option<String> = rconn.get(KEY_TITLE_SECRET!(title)).await?;
if ori_secret.is_none() {
clear_title_from_admins(&rconn, title).await?;
}
ori_secret
.map_or(Some(()), |s| (s.eq(&secret).then_some(())))
.ok_or(PolicyError::TitleProtected)?;
let old_title: Option<String> = rconn.hget(KEY_CUSTOM_TITLE, namehash).await?;
if let Some(t) = old_title {
clear_title_from_admins(&rconn, &t).await?;
}
rconn.hset(KEY_CUSTOM_TITLE, namehash, title).await?;
rconn.hset(KEY_CUSTOM_TITLE, title, namehash).await?;
Ok(Self::gen_and_set_secret(&rconn, title).await?)
Ok(true)
}
}
pub async fn get(
rconn: &RdsConn,
namehash: &str,
) -> RedisResult<(Option<String>, Option<String>)> {
let t: Option<String> = rconn.clone().hget(KEY_CUSTOM_TITLE, namehash).await?;
Ok(if let Some(title) = t {
let s: Option<String> = rconn.clone().get(KEY_TITLE_SECRET!(title)).await?;
let secret = if let Some(ss) = s {
rconn
.clone()
.expire(KEY_TITLE_SECRET!(title), CUSTOM_TITLE_KEEP_TIME as i64)
.await?;
ss
} else {
Self::gen_and_set_secret(rconn, &title).await?
};
(Some(title), Some(secret))
} else {
(None, None)
})
pub async fn get(rconn: &RdsConn, namehash: &str) -> RedisResult<Option<String>> {
rconn.clone().hget(KEY_CUSTOM_TITLE, namehash).await
}
pub async fn clear(rconn: &mut RdsConn) -> RedisResult<()> {
rconn.del(KEY_CUSTOM_TITLE).await
}
}
pub struct AutoBlockRank;
impl AutoBlockRank {
pub async fn set(rconn: &RdsConn, namehash: &str, rank: u8) -> RedisResult<usize> {
rconn
.clone()
.hset(KEY_AUTO_BLOCK_RANK, namehash, rank)
.await
}
pub async fn get(rconn: &RdsConn, namehash: &str) -> RedisResult<u8> {
let rank: Option<u8> = rconn.clone().hget(KEY_AUTO_BLOCK_RANK, namehash).await?;
Ok(rank.unwrap_or(4))
}
pub async fn clear(rconn: &mut RdsConn) -> RedisResult<()> {
rconn.del(KEY_AUTO_BLOCK_RANK).await
pub async fn clear(rconn: &RdsConn) -> RedisResult<()> {
rconn.clone().del(KEY_CUSTOM_TITLE).await
}
}
@ -371,48 +259,4 @@ impl PollVote {
}
}
pub async fn clear_outdate_redis_data(rconn: &mut RdsConn) {
BannedUsers::clear(rconn).await.unwrap();
CustomTitle::clear(rconn).await.unwrap();
AutoBlockRank::clear(rconn).await.unwrap();
Attention::clear_all(rconn).await;
BlockedUsers::clear_all(rconn).await;
}
pub async fn get_announcement(rconn: &RdsConn) -> RedisResult<Option<String>> {
rconn.clone().get(KEY_ANNOUNCEMENT).await
}
pub async fn is_elected_candidate(rconn: &RdsConn, title: &Option<String>) -> RedisResult<bool> {
if let Some(t) = title {
rconn.clone().sismember(KEY_CANDIDATE, t).await
} else {
Ok(false)
}
}
pub async fn is_elected_admin(rconn: &RdsConn, title: &Option<String>) -> RedisResult<bool> {
if let Some(t) = title {
rconn.clone().sismember(KEY_ADMIN, t).await
} else {
Ok(false)
}
}
pub async fn get_admin_list(rconn: &RdsConn) -> RedisResult<Vec<String>> {
rconn.clone().smembers(KEY_ADMIN).await
}
pub async fn get_candidate_list(rconn: &RdsConn) -> RedisResult<Vec<String>> {
rconn.clone().smembers(KEY_CANDIDATE).await
}
pub async fn clear_title_from_admins(rconn: &RdsConn, title: &str) -> RedisResult<()> {
let mut rconn = rconn.clone();
rconn.srem(KEY_CANDIDATE, title).await?;
rconn.srem(KEY_ADMIN, title).await?;
Ok(())
}
pub(crate) use clear_all;
pub(crate) use init;

9
src/schema.rs

@ -28,9 +28,6 @@ table! {
is_reported -> Bool,
hot_score -> Int4,
allow_search -> Bool,
room_id -> Int4,
up_votes -> Int4,
down_votes -> Int4,
}
}
@ -45,4 +42,8 @@ table! {
joinable!(comments -> posts (post_id));
allow_tables_to_appear_in_same_query!(comments, posts, users,);
allow_tables_to_appear_in_same_query!(
comments,
posts,
users,
);

Loading…
Cancel
Save