Compare commits

...

85 Commits

Author SHA1 Message Date
hole-thu bdb3bc49a6 support alumni email 10 months ago
hole-thu d3d9f30b2a basic rate limit 2 years ago
hole-thu 84943a3965 rocket 5.0 & diesel 2.1 2 years ago
hole-thu 7621f56b34 fix lock rc version 2 years ago
hole-thu 289a19d4da fix: not put new post into reply timeline cache 2 years ago
hole-thu 50df8eda36 auth backend from host and default frontend/backend 2 years ago
hole-thu 01f56ea0a6 support sort by n_attention 2 years ago
hole-thu bbed041253 add user_count in systemlog 2 years ago
hole-thu 959e6caa1d random hash username and clear users when restart 2 years ago
hole-thu 6911038f56 feat: tmp post always room 0 3 years ago
hole-thu 104ccb030d fix: not show deleted post to admin 3 years ago
hole-thu 54fa0e1cbd change username format 3 years ago
hole-thu f5005faedc support github login 3 years ago
hole-thu e531f0fed8 support sha256 token 3 years ago
hole-thu dd88bbb868 tmp use cannot reply others 3 years ago
hole-thu 0a5af9f35f stop use 114514 3 years ago
hole-thu 1a04c41846 filter private in getlist, getmulti and attention 3 years ago
hole-thu 553b46b504 allow get popular private post 3 years ago
hole-thu b70b6b2e7f Revert "update set token url" 3 years ago
hole-thu 3b8efc0c0b fix: not use title for report 3 years ago
hole-thu fcf6b33aa7 can't get one private post 3 years ago
hole-thu d98e7fb653 update set token url 3 years ago
hole-thu 04a0d1084f feat: upvote & downvote 3 years ago
hole-thu e0d6720433 use custom_title in syslog 3 years ago
hole-thu 8fabca785c allow any char in title 3 years ago
hole-thu cbf24d6eec admin based on title 3 years ago
hole-thu 503a8a3b9b use 404 for old api 3 years ago
hole-thu 7ab60c9975 keep title for 7 days and random title secret 3 years ago
hole-thu 791d1f526d rocket 0.5-rc2 & rust 1.64 3 years ago
hole-thu 2bae66099d not return blocked_count 3 years ago
hole-thu d5a3c3d7d7 disable no room warning 3 years ago
hole-thu 8639ed0c88 is_candidate and is_admin 3 years ago
hole-thu dd110be8c7 feat: filter invisible chars in title 3 years ago
hole-thu 86b736dadb feat: support announcement 3 years ago
hole-thu 18262a62e0 提醒旧版前端分区问题 3 years ago
hole-thu 0e1a088575 feat: room(分区) 3 years ago
hole-thu dbb5732938 feat: prepare for push notification II 3 years ago
hole-thu f2fa7bb6f8 feat: fix docker and docs 3 years ago
hole-thu 241034ca9b fix: cors 3 years ago
hole-thu 7016718673 stop use ipfs 3 years ago
hole-thu 999ca30448 use api v2 for add comment 3 years ago
hole-thu 273073ba11 举报时手动选择是否隐藏 3 years ago
hole-thu 58794a479d update README 3 years ago
hole-thu 4c4ddca82b 支持Docker部署 3 years ago
hole-thu 25649e6280 fix clippy & rustfmt 3 years ago
hole-thu 1aa86b0963 lock rocket version to rc.1 3 years ago
hole-thu dbea8f435f feat: 有评论后允许删除主楼内容 3 years ago
hole-thu 9a33ef5a88 禁止举报标准改为10 3 years ago
hole-thu 9937bc0dc7 fix bugs 3 years ago
hole-thu fcc8ee3b15 调整热度算法 & 举报自动发洞 3 years ago
hole-thu 9ec106872b fix: check jump_to_url 3 years ago
hole-thu 462071da54 fix: handle preflight 3 years ago
hole-thu a42ef851be feat: fixed login backend url 3 years ago
hole-thu 0fcb56c8a3 feat: cors 3 years ago
hole-thu ff4b983ac3 feat: clear outdate attention data 3 years ago
hole-thu 340d6da45c feat: clear cache of random list 3 years ago
hole-thu c8dcaab936 fix: search 3 years ago
hole-thu 47a6e51a2a feat: configurable auto block 3 years ago
hole-thu 728887e1e2 AGPL3.0 -> WTFPL2.0 3 years ago
hole-thu 4c99fe17d3 remove useless code 3 years ago
hole-thu 40f183d393 opt: don't save uploaded files 3 years ago
hole-thu 57edcb28b6 fix: upload big file 3 years ago
hole-thu 5e36f1809c fix: wrong uploaded files path 3 years ago
hole-thu 4627eda849 feat: support upload files & adjust output 3 years ago
hole-thu b3da584dab style 3 years ago
hole-thu 7c024bfd6b feat: make mastodon login a optional feature 3 years ago
hole-thu dd3c208fe1 feat: tmp user only write, no read 3 years ago
hole-thu 4ed92568d8 v1.0.0 3 years ago
hole-thu b57e1a9233 update README 3 years ago
hole-thu d6eaec9111 feat: cs login & add vote api file 3 years ago
hole-thu ffd30f3c03 feat: add to dangers users when banned 3 years ago
hole-thu 8ffbd6fa31 fix: filte reported in for search 3 years ago
hole-thu caec3e1930 fix: attention list order 3 years ago
hole-thu 79e9a492a7 feat: poll 3 years ago
hole-thu f5b0dbdbac feat: set and user custom title 3 years ago
hole-thu 5bef37cd62 feat: block and dangerous users 3 years ago
hole-thu b2cf8475c5 opt: use macro for sql updates, and merge updates 3 years ago
hole-thu cbf933e74f feat: report 3 years ago
hole-thu fb9648456a feat: ban user 3 years ago
hole-thu ce3379c5ae feat: record and show systemlog, admin delete log 3 years ago
hole-thu 59714bfbef feat: annealing for hot score & clean cache 3 years ago
hole-thu 38bacc1ee0 feat: cache for posts list 3 years ago
hole-thu 9dbb02a838 style 3 years ago
hole-thu c8b8ad0787 feat: post comments cache & use cache everywhere 3 years ago
hole-thu cc32c318a7 fix migdb.py 3 years ago
  1. 5
      .dockerignore
  2. 15
      .env.sample
  3. 6
      .gitignore
  4. 32
      Cargo.toml
  5. 20
      Dockerfile
  6. 249
      LICENSE
  7. 116
      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. 117
      src/api/attention.rs
  19. 168
      src/api/comment.rs
  20. 269
      src/api/mod.rs
  21. 228
      src/api/operation.rs
  22. 219
      src/api/post.rs
  23. 65
      src/api/reaction.rs
  24. 17
      src/api/search.rs
  25. 28
      src/api/systemlog.rs
  26. 20
      src/api/upload.rs
  27. 69
      src/api/vote.rs
  28. 300
      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. 274
      src/login.rs
  34. 106
      src/main.rs
  35. 411
      src/models.rs
  36. 14
      src/random_hasher.rs
  37. 67
      src/rate_limit.rs
  38. 3
      src/rds_conn.rs
  39. 410
      src/rds_models.rs
  40. 9
      src/schema.rs
  41. 6
      tools/migdb.py

5
.dockerignore

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

15
.env.sample

@ -0,0 +1,15 @@
MAST_BASE_URL="https://thu.closed.social/"
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"
ROCKET_DATABASES='{pg_v2={url="postgres://hole:hole_pass@localhost/hole_v2"}}'
RUST_LOG=debug

6
.gitignore vendored

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

32
Cargo.toml

@ -2,22 +2,30 @@
name = "hole-thu"
version = "0.1.0"
edition = "2021"
license = "AGPL-3.0"
license = "WTFPL-2.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-rc.1", features = ["json"] }
diesel = { version = "1.4.8", features = ["postgres", "chrono"] }
diesel_migrations = "1.4.0"
redis = { version="0.21.5", features = ["aio", "tokio-comp"] }
chrono = { version="0.*", features =["serde"] }
rand = "0.*"
dotenv = "0.*"
sha2 = "0.*"
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"] }
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"
[dependencies.rocket_sync_db_pools]
version = "0.1.0-rc.1"
features = ["diesel_postgres_pool"]
reqwest = { version = "0.11.10", features = ["json"], optional = true }

20
Dockerfile

@ -0,0 +1,20 @@
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"]

249
LICENSE

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

116
README.md

@ -1,14 +1,95 @@
# hole-backend-rust
# hole-backend-rust v1.3.0
## 部署
### prepare database
### 使用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 (略)
安装redis (略)
#### 准备数据库
进入:
```shell
sudo -u postgres psql
```
执行 (替换`hole_pass`为实际希望使用的密码):
```postgresql
postgres=# CREATE USER hole WITH PASSWORD 'hole_pass';
CREATE ROLE
@ -20,7 +101,36 @@ 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`后
```shell
diesel migration run
cargo run --release
```
### 基于二进制文件
安装与准备数据库同
从[release](https://git.thu.monster/newthuhole/hole-backend-rust/releases)直接下载二进制文件
```shell
./hole-thu --init-database
./hole-thu
```
## 关于账号系统
+ 如果你希望使用自己的登录系统,在Nginx或Apache中将 `/_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`

2
Rocket.toml

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

32
docker-compose.yml

@ -0,0 +1,32 @@
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

@ -0,0 +1,3 @@
-- 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

@ -0,0 +1,3 @@
-- 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

@ -0,0 +1,4 @@
-- 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

@ -0,0 +1,4 @@
-- 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

@ -0,0 +1,2 @@
-- 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

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

5
psql-docker-init/add_pg_trgm.sh

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

1
rust-toolchain

@ -0,0 +1 @@
stable

117
src/api/attention.rs

@ -1,11 +1,18 @@
use crate::api::post::ps2outputs;
use crate::api::{APIError, CurrentUser, PolicyError::*, API, UGC};
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, Value};
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 {
@ -20,13 +27,15 @@ pub async fn attention_post(
user: CurrentUser,
db: Db,
rconn: RdsConn,
) -> API<Value> {
user.id.ok_or_else(|| APIError::PcError(NotAllowed))?;
let mut p = Post::get(&db, ai.pid).await?;
) -> JsonApi {
// 临时用户不允许手动关注
user.id.ok_or(YouAreTmp)?;
let mut p = Post::get(&db, &rconn, ai.pid).await?;
p.check_permission(&user, "r")?;
let mut att = Attention::init(&user.namehash, &rconn);
let switch_to = ai.switch == 1;
let mut delta: i32 = 0;
let delta: i32;
if att.has(ai.pid).await? != switch_to {
if switch_to {
att.add(ai.pid).await?;
@ -35,28 +44,100 @@ pub async fn attention_post(
att.remove(ai.pid).await?;
delta = -1;
}
p = p.change_n_attentions(&db, delta).await?;
p = p.change_hot_score(&db, delta * 2).await?;
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 }
);
if switch_to && user.is_admin {
update!(p, posts, &db, { is_reported, to false });
}
p.refresh_cache(&rconn, false).await;
}
Ok(json!({
"code": 0,
"attention": ai.switch == 1,
"n_attentions": p.n_attentions + delta,
"n_attentions": p.n_attentions,
// for old version frontend
"likenum": p.n_attentions + delta,
"likenum": p.n_attentions,
}))
}
#[get("/getattention")]
pub async fn get_attention(user: CurrentUser, db: Db, rconn: RdsConn) -> API<Value> {
let ids = Attention::init(&user.namehash, &rconn).all().await?;
let ps = Post::get_multi(&db, ids).await?;
let ps_data = ps2outputs(&ps, &user, &db, &rconn).await;
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?;
Ok(json!({
"code": 0,
"data": ps_data,
}))
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!()
}

168
src/api/comment.rs

@ -1,21 +1,17 @@
use crate::api::{APIError, CurrentUser, PolicyError::*, API, UGC};
use crate::api::{ApiError, CurrentUser, JsonApi, PolicyError::*, Ugc};
use crate::cache::BlockDictCache;
use crate::db_conn::Db;
use crate::models::*;
use crate::rds_conn::RdsConn;
use crate::rds_models::*;
use chrono::{offset::Utc, DateTime};
use futures::{future, join};
use rocket::form::Form;
use rocket::futures::{future::TryFutureExt, try_join};
use rocket::serde::{
json::{json, Value},
Serialize,
};
use rocket::serde::{json::json, Serialize};
use std::collections::HashMap;
#[derive(FromForm)]
pub struct CommentInput {
pid: i32,
#[field(validate = len(1..4097))]
#[field(validate = len(1..12289))]
text: String,
use_title: Option<i8>,
}
@ -29,55 +25,79 @@ pub struct CommentOutput {
can_del: bool,
name_id: i32,
is_tmp: bool,
create_time: DateTime<Utc>,
create_time: i64,
is_blocked: bool,
//blocked_count: Option<i32>,
// for old version frontend
timestamp: i64,
blocked: bool,
}
pub fn c2output<'r>(
pub async fn c2output<'r>(
p: &'r Post,
cs: &Vec<Comment>,
cs: &[Comment],
user: &CurrentUser,
cached_block_dict: &HashMap<String, bool>,
//rconn: &RdsConn,
) -> Vec<CommentOutput> {
let mut hash2id = HashMap::<&String, i32>::from([(&p.author_hash, 0)]);
cs.iter()
.filter_map(|c| {
let name_id: i32 = match hash2id.get(&c.author_hash) {
Some(id) => *id,
None => {
let x = hash2id.len().try_into().unwrap();
hash2id.insert(&c.author_hash, x);
x
}
};
if c.is_deleted {
// TODO: block
None
} else {
Some(CommentOutput {
cid: c.id,
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,
is_tmp: c.is_tmp,
create_time: c.create_time,
timestamp: c.create_time.timestamp(),
})
}
})
.collect()
let name_ids_iter = cs.iter().map(|c| match hash2id.get(&c.author_hash) {
Some(id) => *id,
None => {
let x = hash2id.len().try_into().unwrap();
hash2id.insert(&c.author_hash, x);
x
}
});
future::join_all(cs.iter().zip(name_ids_iter).map(|(c, name_id)| async move {
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));
Some(CommentOutput {
cid: c.id,
text: (if can_view { &c.content } else { "" }).to_string(),
author_title: c.author_title.to_string(),
can_del: c.check_permission(user, "wd").is_ok(),
name_id,
is_tmp: c.is_tmp,
create_time: c.create_time.timestamp(),
is_blocked,
/*
blocked_count: if user.is_admin {
BlockCounter::get_count(rconn, &c.author_hash)
.await
.ok()
.flatten()
} else {
None
},
*/
timestamp: c.create_time.timestamp(),
blocked: is_blocked,
})
}
}))
.await
.into_iter()
.flatten()
.collect()
}
#[get("/getcomment?<pid>")]
pub async fn get_comment(pid: i32, user: CurrentUser, db: Db, rconn: RdsConn) -> API<Value> {
let p = Post::get(&db, pid).await?;
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::PcError(IsDeleted));
return Err(ApiError::Pc(IsDeleted));
}
let pid = p.id;
let cs = Comment::gets_by_post_id(&db, pid).await?;
let data = c2output(&p, &cs, &user);
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;
Ok(json!({
"code": 0,
@ -89,45 +109,61 @@ pub async fn get_comment(pid: i32, user: CurrentUser, db: Db, rconn: RdsConn) ->
}))
}
#[post("/docomment", data = "<ci>")]
#[post("/post/<pid>/comment", data = "<ci>")]
pub async fn add_comment(
pid: i32,
ci: Form<CommentInput>,
user: CurrentUser,
db: Db,
rconn: RdsConn,
) -> API<Value> {
let mut p = Post::get(&db, ci.pid).await?;
Comment::create(
) -> 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;
let c = Comment::create(
&db,
NewComment {
content: ci.text.to_string(),
author_hash: user.namehash.to_string(),
author_title: "".to_string(),
author_title: user
.custom_title
.and_then(|title| use_title.then_some(title))
.unwrap_or_default(),
is_tmp: user.id.is_none(),
post_id: ci.pid,
post_id: pid,
},
)
.await?;
p = p.change_n_comments(&db, 1).await?;
// auto attention after comment
let mut att = Attention::init(&user.namehash, &rconn);
let mut hs_delta = 1;
let mut att = Attention::init(&user.namehash, &rconn);
let hs_delta;
let at_delta;
if !att.has(p.id).await? {
hs_delta += 2;
try_join!(
att.add(p.id).err_into::<APIError>(),
async {
p = p.change_n_attentions(&db, 1).await?;
Ok::<(), APIError>(())
}
.err_into::<APIError>(),
)?;
hs_delta = 3;
at_delta = 1;
att.add(p.id).await?;
} else {
hs_delta = (p.n_comments < 3 * p.n_attentions) as i32;
at_delta = 0;
}
p = p.change_hot_score(&db, hs_delta).await?;
p.refresh_cache(&rconn, false).await;
update!(
p,
posts,
&db,
{ n_comments, add 1 },
{ last_comment_time, to c.create_time },
{ n_attentions, add at_delta },
{ hot_score, add hs_delta }
);
join!(
p.refresh_cache(&rconn, false),
p.clear_comments_cache(&rconn),
);
Ok(json!({
"code": 0

269
src/api/mod.rs

@ -1,23 +1,89 @@
#![allow(clippy::unnecessary_lazy_evaluations)]
use crate::db_conn::Db;
use crate::models::*;
use crate::random_hasher::RandomHasher;
use crate::rate_limit::MainLimiters;
use crate::rds_conn::RdsConn;
use rocket::http::Status;
use crate::rds_models::*;
use rocket::http::{Method, Status};
use rocket::outcome::try_outcome;
use rocket::request::{FromRequest, Outcome, Request};
use rocket::response::{self, Responder};
use rocket::serde::json::{json, Value};
macro_rules! code0 {
() => (
Ok(json!({"code": 0}))
);
($data:expr) => (
Ok(json!({
"code": 0,
"data": $data,
}))
);
}
/*
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过期"
}
#[catch(403)]
pub fn catch_403_error() -> &'static str {
"可能被封禁了,等下次重置吧"
}
#[catch(404)]
pub fn catch_404_error() -> &'static str {
"请更新前端版本"
}
pub struct CurrentUser {
id: Option<i32>, // tmp user has no id, only for block
pub id: Option<i32>, // tmp user has no id, only for block
namehash: String,
is_admin: bool,
custom_title: String,
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,
}
}
}
#[rocket::async_trait]
@ -25,35 +91,50 @@ impl<'r> FromRequest<'r> for CurrentUser {
type Error = ();
async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
let rh = request.rocket().state::<RandomHasher>().unwrap();
let mut cu: Option<CurrentUser> = None;
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() {
let namehash = rh.hash_with_salt(sp[1]);
cu = Some(CurrentUser {
id: None,
custom_title: format!("TODO: {}", &namehash),
namehash: namehash,
is_admin: false,
});
} else {
let db = try_outcome!(request.guard::<Db>().await);
let rconn = try_outcome!(request.guard::<RdsConn>().await);
if let Some(user) = User::get_by_token_with_cache(&db, &rconn, token).await {
let namehash = rh.hash_with_salt(&user.name);
cu = Some(CurrentUser {
id: Some(user.id),
custom_title: format!("TODO: {}", &namehash),
namehash: namehash,
is_admin: user.is_admin,
});
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
}
}
} else {
None
}
}
match cu {
Some(u) => Outcome::Success(u),
None => Outcome::Failure((Status::Unauthorized, ())),
} {
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)
}
} else {
Outcome::Error((Status::Unauthorized, ()))
}
}
}
@ -61,37 +142,46 @@ 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 {
DbError(diesel::result::Error),
RdsError(redis::RedisError),
PcError(PolicyError),
pub enum ApiError {
Db(diesel::result::Error),
Rds(redis::RedisError),
WebPush(web_push::WebPushError),
Pc(PolicyError),
IO(std::io::Error),
}
impl<'r> Responder<'r, 'static> for APIError {
impl<'r> Responder<'r, 'static> for ApiError {
fn respond_to(self, req: &'r Request<'_>) -> response::Result<'static> {
dbg!(&self);
match self {
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!({
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!({
"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),
@ -99,90 +189,120 @@ impl<'r> Responder<'r, 'static> for APIError {
}
}
impl From<diesel::result::Error> for APIError {
fn from(err: diesel::result::Error) -> APIError {
APIError::DbError(err)
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::Db(err)
}
}
impl From<redis::RedisError> for ApiError {
fn from(err: redis::RedisError) -> ApiError {
ApiError::Rds(err)
}
}
impl From<redis::RedisError> for APIError {
fn from(err: redis::RedisError) -> APIError {
APIError::RdsError(err)
impl From<std::io::Error> for ApiError {
fn from(err: std::io::Error) -> ApiError {
ApiError::IO(err)
}
}
pub type API<T> = Result<T, APIError>;
pub type JsonAPI = API<Value>;
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>;
#[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(&self, db: &Db) -> API<usize>;
fn check_permission(&self, user: &CurrentUser, mode: &str) -> API<()> {
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));
}
if user.is_admin {
return Ok(());
}
if mode.contains('r') && self.get_is_deleted() {
return Err(APIError::PcError(PolicyError::IsDeleted));
}
if mode.contains('o') && self.get_is_reported() {
return Err(APIError::PcError(PolicyError::IsReported));
return Err(ApiError::Pc(PolicyError::IsReported));
}
if mode.contains('o') && self.get_is_private() {
return Err(ApiError::Pc(PolicyError::IsPrivate));
}
if mode.contains('w') && self.get_author_hash() != user.namehash {
return Err(APIError::PcError(PolicyError::NotAllowed));
return Err(ApiError::Pc(PolicyError::NotAllowed));
}
if mode.contains('d') && !self.extra_delete_condition() {
return Err(APIError::PcError(PolicyError::NotAllowed));
return Err(ApiError::Pc(PolicyError::NotAllowed));
}
Ok(())
}
async fn soft_delete(&self, user: &CurrentUser, db: &Db) -> API<()> {
async fn soft_delete(&mut self, user: &CurrentUser, db: &Db) -> Api<()> {
self.check_permission(user, "rwd")?;
let _ = self.do_set_deleted(db).await?;
self.do_set_deleted(db).await?;
Ok(())
}
}
#[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.n_comments == 0
self.room_id != 42
}
async fn do_set_deleted(&self, db: &Db) -> API<usize> {
self.set_deleted(db).await.map_err(From::from)
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(&self, db: &Db) -> API<usize> {
self.set_deleted(db).await.map_err(From::from)
async fn do_set_deleted(&mut self, db: &Db) -> Api<()> {
update!(*self, comments, db, { is_deleted, to true });
Ok(())
}
}
@ -196,5 +316,8 @@ 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;

228
src/api/operation.rs

@ -1,9 +1,12 @@
use crate::api::{APIError, CurrentUser, PolicyError::*, API, UGC};
use crate::api::{ApiError, CurrentUser, JsonApi, PolicyError::*, Ugc};
use crate::cache::*;
use crate::db_conn::Db;
use crate::rds_conn::RdsConn;
use crate::models::*;
use crate::rds_conn::RdsConn;
use crate::rds_models::*;
use chrono::offset::Local;
use rocket::form::Form;
use rocket::serde::json::{json, Value};
use rocket::serde::json::json;
#[derive(FromForm)]
pub struct DeleteInput {
@ -14,24 +17,223 @@ pub struct DeleteInput {
}
#[post("/delete", data = "<di>")]
pub async fn delete(di: Form<DeleteInput>, user: CurrentUser, db: Db, rconn: RdsConn) -> API<Value> {
match di.id_type.as_str() {
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 c = Comment::get(&db, di.id).await?;
let mut c = Comment::get(&db, di.id).await?;
c.soft_delete(&user, &db).await?;
let mut p = Post::get(&db, c.post_id).await?;
p = p.change_n_comments(&db, -1).await?;
p = p.change_hot_score(&db, -2).await?;
let mut p = Post::get(&db, &rconn, c.post_id).await?;
update!(
p,
posts,
&db,
{ n_comments, add -1 },
{ hot_score, add -1 }
);
p.refresh_cache(&rconn, false).await;
p.clear_comments_cache(&rconn).await;
(c.author_hash.clone(), p)
}
"pid" => {
let p = Post::get(&db, di.id).await?;
p.soft_delete(&user, &db).await?;
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?;
}
// 如果是删除,需要也从0号缓存队列中去掉
p.refresh_cache(&rconn, true).await;
(p.author_hash.clone(), p)
}
_ => Err(NotAllowed)?,
};
if user.is_admin && !user.namehash.eq(&author_hash) {
Systemlog {
user_hash: user.custom_title.clone().unwrap_or(look!(user.namehash)),
action_type: LogType::AdminDelete,
target: format!("#{}, {}={}", p.id, di.id_type, di.id),
detail: di.note.clone(),
time: Local::now(),
}
.create(&rconn)
.await?;
if di.note.starts_with("!ban ") {
Systemlog {
user_hash: user.custom_title.unwrap_or(look!(user.namehash)),
action_type: LogType::Ban,
target: look!(author_hash),
detail: di.note.clone(),
time: Local::now(),
}
.create(&rconn)
.await?;
BannedUsers::add(&rconn, &author_hash).await?;
}
_ => return Err(APIError::PcError(NotAllowed)),
}
code0!()
}
#[derive(FromForm)]
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 {
// 临时用户不允许举报
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)?;
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;
}
Systemlog {
user_hash: look!(user.namehash),
action_type: LogType::Report,
target: format!("#{}", ri.pid),
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!()
}
#[derive(FromForm)]
pub struct BlockInput {
#[field(name = "type")]
content_type: String,
id: i32,
}
#[post("/block", data = "<bi>")]
pub async fn block(bi: Form<BlockInput>, user: CurrentUser, db: Db, rconn: RdsConn) -> JsonApi {
user.id.ok_or(NotAllowed)?;
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)),
};
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()
};
BlockDictCache::init(&user.namehash, pid, &rconn)
.clear()
.await?;
Ok(json!({
"code": 0
"code": 0,
"data": {
"curr": curr,
},
}))
}
#[derive(FromForm)]
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)?
}
/*
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!()
}

219
src/api/post.rs

@ -1,149 +1,194 @@
use crate::api::comment::{c2output, CommentOutput};
use crate::api::{APIError, CurrentUser, JsonAPI, PolicyError::*, UGC};
use crate::api::vote::get_poll_dict;
use crate::api::{Api, CurrentUser, JsonApi, PolicyError::*, Ugc};
use crate::cache::*;
use crate::db_conn::Db;
use crate::models::*;
use crate::rds_conn::RdsConn;
use crate::rds_models::*;
use chrono::{offset::Utc, DateTime};
use rocket::form::Form;
use rocket::futures::future;
use rocket::serde::{json::json, Serialize};
use rocket::futures::future::{self, OptionFuture};
use rocket::serde::{
json::{json, Value},
Serialize,
};
#[derive(FromForm)]
pub struct PostInput {
#[field(validate = len(1..4097))]
#[field(validate = len(1..12289))]
text: String,
#[field(validate = len(0..33))]
#[field(validate = len(0..97))]
cw: String,
allow_search: Option<i8>,
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: DateTime<Utc>,
last_comment_time: DateTime<Utc>,
create_time: i64,
last_comment_time: i64,
allow_search: bool,
is_reported: Option<bool>,
comments: Option<Vec<CommentOutput>>,
can_del: bool,
attention: bool,
hot_score: Option<i32>,
is_blocked: bool,
//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,
reply: i32,
blocked: bool,
}
#[derive(FromForm)]
pub struct CwInput {
pid: i32,
#[field(validate = len(0..33))]
#[field(validate = len(0..97))]
cw: String,
}
async fn p2output(
p: &Post,
user: &CurrentUser,
db: &Db,
rconn: &RdsConn,
) -> PostOutput {
PostOutput {
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 {
pid: p.id,
text: format!("{}{}", if p.is_tmp { "[tmp]\n" } else { "" }, p.content),
cw: if p.cw.len() > 0 {
Some(p.cw.to_string())
} else {
None
},
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()),
n_attentions: p.n_attentions,
n_comments: p.n_comments,
create_time: p.create_time,
last_comment_time: p.last_comment_time,
create_time: p.create_time.timestamp(),
last_comment_time: p.last_comment_time.timestamp(),
allow_search: p.allow_search,
author_title: if p.author_title.len() > 0 {
Some(p.author_title.to_string())
} else {
None
},
author_title: (!p.author_title.is_empty()).then_some(p.author_title.clone()),
is_tmp: p.is_tmp,
is_reported: if user.is_admin {
Some(p.is_reported)
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 {
None
},
comments: if p.n_comments > 50 {
None
*/
poll: if can_view {
get_poll_dict(p.id, rconn, &user.namehash).await
} else {
// 单个洞还有查询评论的接口,这里挂了不用报错
let pid = p.id;
if let Some(cs) = Comment::gets_by_post_id(db, pid).await.ok() {
Some(c2output(p, &cs, user))
} else {
None
}
None
},
can_del: p.check_permission(user, "wd").is_ok(),
attention: Attention::init(&user.namehash, &rconn)
.has(p.id)
.await
.unwrap_or_default(),
hot_score: if user.is_admin { Some(p.hot_score) } 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?,
// 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: &Vec<Post>,
ps: &[Post],
user: &CurrentUser,
db: &Db,
rconn: &RdsConn,
) -> Vec<PostOutput> {
future::join_all(
) -> Api<Vec<PostOutput>> {
future::try_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 {
// let p = Post::get(&db, pid).await?;
let p = Post::get_with_cache(&db, &rconn, pid).await?;
pub async fn get_one(pid: i32, user: CurrentUser, db: Db, rconn: RdsConn) -> JsonApi {
user.id.ok_or(YouAreTmp)?;
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>")]
#[get("/getlist?<p>&<order_mode>&<room_id>")]
pub async fn get_list(
p: Option<u32>,
order_mode: u8,
room_id: Option<i32>,
user: CurrentUser,
db: Db,
rconn: RdsConn,
) -> JsonAPI {
) -> JsonApi {
user.id.ok_or(YouAreTmp)?;
let page = p.unwrap_or(1);
let page_size = 25;
let start = (page - 1) * page_size;
let ps = Post::gets_by_page(&db, order_mode, start.into(), page_size.into()).await?;
let ps_data = ps2outputs(&ps, &user, &db, &rconn).await;
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?;
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?,
"code": 0
}))
}
@ -154,41 +199,65 @@ pub async fn publish_post(
user: CurrentUser,
db: Db,
rconn: RdsConn,
) -> JsonAPI {
) -> 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()
};
let p = Post::create(
&db,
NewPost {
content: poi.text.to_string(),
cw: poi.cw.to_string(),
author_hash: user.namehash.to_string(),
author_title: "".to_string(),
is_tmp: user.id.is_none(),
author_title: user
.custom_title
.and_then(|title| use_title.then_some(title))
.unwrap_or_default(),
is_tmp,
n_attentions: 1,
allow_search: poi.allow_search.is_some(),
room_id,
},
)
.await?;
Attention::init(&user.namehash, &rconn).add(p.id).await?;
Ok(json!({
"code": 0
}))
p.refresh_cache(&rconn, true).await;
if !poi.poll_options.is_empty() {
PollOption::init(p.id, &rconn)
.set_list(&poi.poll_options)
.await?;
}
code0!()
}
#[post("/editcw", data = "<cwi>")]
pub async fn edit_cw(cwi: Form<CwInput>, user: CurrentUser, db: Db) -> JsonAPI {
let p = Post::get(&db, cwi.pid).await?;
if !(user.is_admin || p.author_hash == user.namehash) {
return Err(APIError::PcError(NotAllowed));
}
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")?;
_ = p.update_cw(&db, cwi.cw.to_string()).await?;
Ok(json!({"code": 0}))
update!(p, posts, &db, { cw, to cwi.cw.to_string() });
p.refresh_cache(&rconn, false).await;
code0!()
}
#[get("/getmulti?<pids>")]
pub async fn get_multi(pids: Vec<i32>, user: CurrentUser, db: Db, rconn: RdsConn) -> JsonAPI {
let ps = Post::get_multi_with_cache(&db, &rconn, &pids).await?;
let ps_data = ps2outputs(&ps, &user, &db, &rconn).await;
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?;
Ok(json!({
"code": 0,

65
src/api/reaction.rs

@ -0,0 +1,65 @@
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,
},
}))
}

17
src/api/search.rs

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

28
src/api/systemlog.rs

@ -1,16 +1,36 @@
use crate::api::{CurrentUser, API};
use crate::api::{CurrentUser, JsonApi};
use crate::cache::cached_user_count;
use crate::db_conn::Db;
use crate::random_hasher::RandomHasher;
use crate::rds_conn::RdsConn;
use crate::rds_models::{get_admin_list, get_candidate_list, Systemlog};
use rocket::serde::json::{json, Value};
use rocket::State;
use crate::db_conn::Db;
#[get("/systemlog")]
pub async fn get_systemlog(user: CurrentUser, rh: &State<RandomHasher>, db: Db) -> API<Value> {
pub async fn get_systemlog(
user: CurrentUser,
rh: &State<RandomHasher>,
db: Db,
mut 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,
"data": [],
"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,
"timestamp": log.time.timestamp(),
"detail": format!("{}\n{}", &log.target, &log.detail),
})
).collect::<Vec<Value>>(),
}))
}

20
src/api/upload.rs

@ -0,0 +1,20 @@
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 }))
}

69
src/api/vote.rs

@ -0,0 +1,69 @@
use crate::api::{CurrentUser, JsonApi, PolicyError::*};
use crate::rds_conn::RdsConn;
use crate::rds_models::*;
use rocket::form::Form;
use rocket::futures::future;
use rocket::serde::json::{json, Value};
pub async fn get_poll_dict(pid: i32, rconn: &RdsConn, namehash: &str) -> Option<Value> {
let opts = PollOption::init(pid, rconn)
.get_list()
.await
.unwrap_or_default();
if opts.is_empty() {
None
} else {
let choice = future::join_all(opts.iter().enumerate().map(|(idx, opt)| async move {
PollVote::init(pid, idx, rconn)
.has(namehash)
.await
.unwrap_or_default()
.then_some(opt)
}))
.await
.into_iter()
.flatten()
.collect::<Vec<&String>>()
.pop();
Some(json!({
"answers": future::join_all(
opts.iter().enumerate().map(|(idx, opt)| async move {
json!({
"option": opt,
"votes": PollVote::init(pid, idx, rconn).count().await.unwrap_or_default(),
})
})
).await,
"vote": choice,
}))
}
}
#[derive(FromForm)]
pub struct VoteInput {
pid: i32,
vote: String,
}
#[post("/vote", data = "<vi>")]
pub async fn vote(vi: Form<VoteInput>, user: CurrentUser, rconn: RdsConn) -> JsonApi {
user.id.ok_or(NotAllowed)?;
let pid = vi.pid;
let opts = PollOption::init(pid, &rconn).get_list().await?;
if opts.is_empty() {
Err(NotAllowed)?;
}
for idx in 0..opts.len() {
if PollVote::init(pid, idx, &rconn).has(&user.namehash).await? {
Err(NotAllowed)?;
}
}
let idx: usize = opts.iter().position(|x| x.eq(&vi.vote)).ok_or(NotAllowed)?;
PollVote::init(pid, idx, &rconn).add(&user.namehash).await?;
code0!(get_poll_dict(vi.pid, &rconn, &user.namehash).await)
}

300
src/cache.rs

@ -1,13 +1,28 @@
use crate::api::{Api, CurrentUser};
use crate::db_conn::Db;
use crate::models::{Comment, Post, User};
use crate::rds_conn::RdsConn;
use redis::AsyncCommands;
use crate::rds_models::{clear_all, init, BlockedUsers};
use rand::Rng;
use redis::{AsyncCommands, RedisError, RedisResult};
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 MIN_LENGTH: isize = 200;
const MAX_LENGTH: isize = 900;
const CUT_LENGTH: isize = 100;
const INSTANCE_EXPIRE_TIME: usize = 60 * 60;
macro_rules! post_cache_key {
($id: expr) => {
format!("hole_v2:cache:post:{}", $id)
format!("hole_v2:cache:post:{}:v2", $id)
};
}
@ -16,31 +31,22 @@ pub struct PostCache {
}
impl PostCache {
pub fn init(rconn: &RdsConn) -> Self {
PostCache {
rconn: rconn.clone(),
}
}
init!();
pub async fn sets(&mut self, ps: &Vec<&Post>) {
clear_all!("hole_v2:cache::post:*:v2");
pub async fn sets(&mut self, ps: &[&Post]) {
if ps.is_empty() {
return;
}
let kvs: Vec<(String, String)> = ps
.iter()
.map(|p| (
post_cache_key!(p.id),
serde_json::to_string(p).unwrap(),
) ).collect();
dbg!(&kvs);
let ret = self.rconn
.set_multiple(&kvs)
.await
.unwrap_or_else(|e| {
warn!("set post cache failed: {}", e);
"x".to_string()
});
dbg!(ret);
.map(|p| (post_cache_key!(p.id), serde_json::to_string(p).unwrap()))
.collect();
self.rconn.mset(&kvs).await.unwrap_or_else(|e| {
warn!("set post cache failed: {}", e);
dbg!(&kvs);
});
}
pub async fn get(&mut self, pid: &i32) -> Option<Post> {
@ -50,7 +56,7 @@ impl PostCache {
.get::<String, Option<String>>(key)
.await
.unwrap_or_else(|e| {
warn!("try to get post cache, connect rds fail, {}", e);
warn!("try to get post cache, connect rds failed, {}", e);
None
});
@ -62,7 +68,7 @@ impl PostCache {
})
}
pub async fn gets(&mut self, pids: &Vec<i32>) -> Vec<Option<Post>> {
pub async fn gets(&mut self, pids: &[i32]) -> Vec<Option<Post>> {
// 长度为1时会走GET而非MGET,返回值格式不兼容。愚蠢的设计。
match pids.len() {
0 => vec![],
@ -76,7 +82,7 @@ impl PostCache {
.get::<Vec<String>, Vec<Option<String>>>(ks)
.await
.unwrap_or_else(|e| {
warn!("try to get posts cache, connect rds fail, {}", e);
warn!("try to get posts cache, connect rds failed, {}", e);
vec![None; pids.len()]
});
// dbg!(&rds_result);
@ -100,19 +106,184 @@ impl PostCache {
}
}
pub struct UserCache {
pub struct PostCommentCache {
key: String,
rconn: RdsConn,
}
impl UserCache {
pub fn init(token: &str, rconn: &RdsConn) -> Self {
UserCache {
key: format!("hole_v2:cache:user:{}", token),
impl PostCommentCache {
init!(i32, "hole_v2:cache:post_comments:{}");
pub async fn set(&mut self, cs: &[Comment]) {
self.rconn
.set_ex(
&self.key,
serde_json::to_string(cs).unwrap(),
INSTANCE_EXPIRE_TIME,
)
.await
.unwrap_or_else(|e| {
warn!("set comments cache failed: {}", e);
dbg!(cs);
})
}
pub async fn get(&mut self) -> Option<Vec<Comment>> {
let rds_result = self.rconn.get::<&String, String>(&self.key).await;
// dbg!(&rds_result);
if let Ok(s) = rds_result {
self.rconn
.expire::<&String, bool>(&self.key, INSTANCE_EXPIRE_TIME as i64)
.await
.unwrap_or_else(|e| {
warn!(
"get comments cache, set new expire failed: {}, {}, {} ",
e, &self.key, &s
);
false
});
serde_json::from_str(&s).unwrap_or_else(|e| {
warn!("get comments cache, decode failed {}, {}", e, s);
None
})
} else {
None
}
}
pub async fn clear(&mut self) {
self.rconn.del(&self.key).await.unwrap_or_else(|e| {
warn!("clear commenrs cache fail, {}", e);
});
}
}
pub struct PostListCache {
key: String,
mode: u8,
rconn: RdsConn,
length: isize,
}
impl PostListCache {
pub fn init(room_id: Option<i32>, 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,
rconn: rconn.clone(),
length: 0,
}
}
async fn set_and_check_length(&mut self) {
let mut l = self.rconn.zcard(&self.key).await.unwrap();
if l > MAX_LENGTH {
self.rconn
.zremrangebyrank::<&String, ()>(&self.key, MAX_LENGTH - CUT_LENGTH, -1)
.await
.unwrap_or_else(|e| {
warn!("cut list cache failed, {}, {}", e, &self.key);
});
l = MIN_LENGTH;
}
self.length = l;
}
pub async fn need_fill(&mut self) -> bool {
self.set_and_check_length().await;
self.length < MIN_LENGTH
}
pub fn i64_len(&self) -> i64 {
self.length.try_into().unwrap()
}
pub fn i64_minlen(&self) -> i64 {
MIN_LENGTH.try_into().unwrap()
}
fn p2pair(&self, p: &Post) -> (i64, i32) {
(
match self.mode {
0 => (-p.id).into(),
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]) {
let items: Vec<(i64, i32)> = ps.iter().map(|p| self.p2pair(p)).collect();
self.rconn
.zadd_multiple(&self.key, &items)
.await
.unwrap_or_else(|e| {
warn!("fill list cache failed, {} {}", e, &self.key);
});
self.set_and_check_length().await;
}
pub async fn put(&mut self, p: &Post) {
// 其他都是加到最前面的,但热榜不是。可能导致MIN_LENGTH到MAX_LENGTH之间的数据不可靠
// 影响不大,先不管了
if p.is_deleted || (self.mode > 0 && p.is_reported) {
self.rconn.zrem(&self.key, p.id).await.unwrap_or_else(|e| {
warn!(
"remove from list cache failed, {} {} {}",
e, &self.key, p.id
);
});
} else {
let (s, m) = self.p2pair(p);
self.rconn.zadd(&self.key, m, s).await.unwrap_or_else(|e| {
warn!(
"put into list cache failed, {} {} {} {}",
e, &self.key, m, s
);
});
}
}
pub async fn get_pids(&mut self, start: i64, limit: i64) -> Vec<i32> {
self.rconn
.zrange(
&self.key,
start.try_into().unwrap(),
(start + limit - 1).try_into().unwrap(),
)
.await
.unwrap()
}
pub async fn clear(&mut self) {
self.rconn.del(&self.key).await.unwrap_or_else(|e| {
warn!("clear post list cache failed, {}", e);
});
}
}
pub struct UserCache {
key: String,
rconn: RdsConn,
}
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(
@ -122,16 +293,16 @@ impl UserCache {
)
.await
.unwrap_or_else(|e| {
warn!("set user cache failed: {}, {}, {}", e, u.id, u.name);
warn!("set user cache failed: {}", e);
dbg!(u);
})
}
pub async fn get(&mut self) -> Option<User> {
let rds_result = self.rconn.get::<&String, String>(&self.key).await;
if let Ok(s) = rds_result {
debug!("hint user cache");
self.rconn
.expire::<&String, bool>(&self.key, INSTANCE_EXPIRE_TIME)
.expire::<&String, bool>(&self.key, INSTANCE_EXPIRE_TIME as i64)
.await
.unwrap_or_else(|e| {
warn!(
@ -149,3 +320,66 @@ 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

@ -0,0 +1,42 @@
#![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,7 +1,15 @@
use diesel::Connection;
use rocket_sync_db_pools::{database, diesel};
use std::env;
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");
Conn::establish(&database_url)
.unwrap_or_else(|_| panic!("Error connecting to {}", database_url))
}

148
src/libs/diesel_logger.rs

@ -1,148 +0,0 @@
/*
* 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

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

274
src/login.rs

@ -0,0 +1,274 @@
#![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);
#[rocket::async_trait]
impl<'r> FromRequest<'r> for FrontendAddr {
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()),
))
}
}
#[get("/?p=cs")]
pub fn cs_login(r: FrontendAddr, h: BackendAddr) -> 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();
redirect_url.set_path("/_login/cs/auth");
redirect_url = Url::parse_with_params(
redirect_url.as_str(),
&[
("redirect_url", redirect_url.as_str()),
("jump_to_url", jump_to_url.as_str()),
],
)
.unwrap();
let url = Url::parse_with_params(
&format!("{}oauth/authorize", mast_url),
&[
("redirect_uri", redirect_url.as_str()),
("client_id", &mast_cli),
("scope", &mast_scope),
("response_type", "code"),
],
)
.unwrap();
Redirect::to(url.to_string())
}
#[derive(Deserialize, Debug)]
#[serde(crate = "rocket::serde")]
struct Token {
pub access_token: String,
}
#[derive(Deserialize, Debug)]
#[serde(crate = "rocket::serde")]
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("前端地址不在白名单内");
}
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();
let mast_scope = env::var("MAST_SCOPE").unwrap();
// 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()),
],
)
.unwrap();
let client = reqwest::Client::new();
let r = client
.post(format!("{}oauth/token", &mast_url))
.form(&[
("client_id", mast_cli.as_str()),
("client_secret", mast_sec.as_str()),
("scope", mast_scope.as_str()),
("redirect_uri", redirect_url.as_str()),
("grant_type", "authorization_code"),
("code", code.as_str()),
])
.send()
.await
.unwrap();
//dbg!(&r);
let token: Token = r.json().await.unwrap();
//dbg!(&token);
let client = reqwest::Client::new();
let account = client
.get(format!("{}api/v1/accounts/verify_credentials", &mast_url))
.bearer_auth(token.access_token)
.send()
.await
.unwrap()
.json::<Account>()
.await
.unwrap();
//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>()
.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("没有找到已验证的清华邮箱/校友邮箱")
}
}

106
src/main.rs

@ -11,37 +11,68 @@ extern crate diesel_migrations;
extern crate log;
mod api;
mod cache;
mod cors;
mod db_conn;
mod libs;
#[cfg(feature = "mastlogin")]
mod login;
mod models;
mod random_hasher;
mod rate_limit;
mod rds_conn;
mod rds_models;
mod cache;
mod schema;
use db_conn::{Conn, Db};
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 random_hasher::RandomHasher;
use rds_conn::init_rds_client;
use std::env;
use rate_limit::MainLimiters;
use rds_conn::{init_rds_client, RdsConn};
use rds_models::clear_outdate_redis_data;
embed_migrations!("migrations/postgres");
pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!("migrations/postgres");
#[rocket::main]
async fn main() -> Result<(), rocket::Error> {
async fn main() {
load_env();
if env::args().any(|arg| arg.eq("--init-database")) {
init_database();
return Ok(());
return;
}
env_logger::init();
rocket::build()
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());
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;
}
});
let _ = 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,
@ -52,14 +83,59 @@ async fn main() -> Result<(), rocket::Error> {
api::attention::get_attention,
api::systemlog::get_systemlog,
api::operation::delete,
api::operation::report,
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(),
)
.register(
"/_api",
catchers![
api::catch_401_error,
api::catch_403_error,
api::catch_404_error
],
)
.register("/_api", catchers![api::catch_401_error])
.manage(MainLimiters::init())
.manage(RandomHasher::get_random_one())
.manage(init_rds_client().await)
.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() {
@ -72,6 +148,6 @@ fn load_env() {
fn init_database() {
let database_url = env::var("DATABASE_URL").unwrap();
let conn = Conn::establish(&database_url).unwrap();
embedded_migrations::run(&conn).unwrap();
let mut conn = Conn::establish(&database_url).unwrap();
conn.run_pending_migrations(MIGRATIONS).unwrap();
}

411
src/models.rs

@ -1,25 +1,28 @@
#![allow(clippy::all)]
// #![allow(clippy::all)]
use crate::cache::{PostCache, UserCache};
use crate::db_conn::Db;
use crate::libs::diesel_logger::LoggingConnection;
use crate::cache::*;
use crate::db_conn::{Conn, Db};
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,
TextExpressionMethods,
};
use rocket::futures::{future, join};
use rocket::serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::convert::identity;
no_arg_sql_function!(RANDOM, (), "Represents the sql RANDOM() function");
sql_function!(fn random());
sql_function!(fn floor(x: Float) -> Int4);
sql_function!(fn float4(x: Int4) -> Float);
macro_rules! get {
macro_rules! _get {
($table:ident) => {
pub async fn get(db: &Db, id: i32) -> QueryResult<Self> {
async fn _get(db: &Db, id: i32) -> QueryResult<Self> {
let pid = id;
db.run(move |c| $table::table.find(pid).first(with_log!((c))))
.await
@ -27,16 +30,16 @@ macro_rules! get {
};
}
macro_rules! get_multi {
macro_rules! _get_multi {
($table:ident) => {
pub async fn get_multi(db: &Db, ids: Vec<i32>) -> QueryResult<Vec<Self>> {
async fn _get_multi(db: &Db, ids: Vec<i32>) -> QueryResult<Vec<Self>> {
if ids.is_empty() {
return Ok(vec![]);
}
// 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))
})
@ -45,20 +48,33 @@ macro_rules! get_multi {
};
}
macro_rules! set_deleted {
($table:ident) => {
pub async fn set_deleted(&self, db: &Db) -> QueryResult<usize> {
let pid = self.id;
db.run(move |c| {
diesel::update($table::table.find(pid))
.set($table::is_deleted.eq(true))
.execute(with_log!(c))
})
.await
}
macro_rules! op_to_col_expr {
($col_obj:expr, to $v:expr) => {
$v
};
($col_obj:expr, add $v:expr) => {
$col_obj + $v
};
}
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| {
diesel::update(schema::$table::table.find(id))
.set((
$(schema::$table::$col.eq(op_to_col_expr!(schema::$table::$col, $op $v))), +
))
.get_result(with_log!(c))
})
.await?;
}};
}
macro_rules! base_query {
($table:ident) => {
$table::table
@ -67,13 +83,14 @@ macro_rules! base_query {
};
}
// TODO: log sql query
macro_rules! with_log {
($c: expr) => {
&LoggingConnection::new($c)
$c
};
}
#[derive(Queryable, Insertable, Serialize, Deserialize)]
#[derive(Queryable, Insertable, Serialize, Deserialize, Debug)]
#[serde(crate = "rocket::serde")]
pub struct Comment {
pub id: i32,
@ -104,9 +121,12 @@ 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)]
#[derive(Queryable, Insertable, Serialize, Deserialize, Debug)]
#[serde(crate = "rocket::serde")]
pub struct User {
pub id: i32,
@ -116,7 +136,7 @@ pub struct User {
}
#[derive(Insertable)]
#[table_name = "posts"]
#[diesel(table_name = posts)]
pub struct NewPost {
pub content: String,
pub cw: String,
@ -125,22 +145,16 @@ pub struct NewPost {
pub is_tmp: bool,
pub n_attentions: i32,
pub allow_search: bool,
// TODO: tags
pub room_id: i32,
}
impl Post {
get!(posts);
_get!(posts);
get_multi!(posts);
_get_multi!(posts);
set_deleted!(posts);
pub async fn get_multi_with_cache(
db: &Db,
rconn: &RdsConn,
ids: &Vec<i32>,
) -> QueryResult<Vec<Self>> {
let mut cacher = PostCache::init(&rconn);
pub async fn get_multi(db: &Db, rconn: &RdsConn, ids: &[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();
@ -151,19 +165,19 @@ impl Post {
.zip(cached_posts.iter_mut())
.filter_map(|(pid, p)| match p {
None => {
id2po.insert(pid.clone(), p);
id2po.insert(*pid, p);
Some(pid)
},
}
_ => None,
})
.copied()
.collect();
dbg!(&missing_ids);
let missing_ps = Self::get_multi(db, missing_ids).await?;
// dbg!(&missing_ids);
let missing_ps = Self::_get_multi(db, missing_ids).await?;
// dbg!(&missing_ps);
cacher.sets(&missing_ps.iter().map(identity).collect()).await;
cacher.sets(&missing_ps.iter().collect::<Vec<_>>()).await;
for p in missing_ps.into_iter() {
if let Some(op) = id2po.get_mut(&p.id) {
@ -171,35 +185,89 @@ impl Post {
}
}
// dbg!(&cached_posts);
Ok(
cached_posts.into_iter().filter_map(identity).collect()
)
Ok(cached_posts
.into_iter()
.filter_map(|p| p.filter(|p| !p.is_deleted))
.collect())
}
pub async fn get_with_cache(db: &Db, rconn: &RdsConn, id: i32) -> QueryResult<Self> {
Self::get_multi_with_cache(db, rconn, &vec![id])
.await?
.pop()
.ok_or(diesel::result::Error::NotFound)
pub async fn get(db: &Db, rconn: &RdsConn, id: i32) -> QueryResult<Self> {
// 注意即使is_deleted也应该缓存和返回
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;
Ok(p)
}
}
pub async fn get_comments(&self, db: &Db, rconn: &RdsConn) -> QueryResult<Vec<Comment>> {
let mut cacher = PostCommentCache::init(self.id, rconn);
if let Some(cs) = cacher.get().await {
Ok(cs)
} else {
let cs = Comment::gets_by_post_id(db, self.id).await?;
cacher.set(&cs).await;
Ok(cs)
}
}
pub async fn clear_comments_cache(&self, rconn: &RdsConn) {
PostCommentCache::init(self.id, rconn).clear().await;
}
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);
if cacher.need_fill().await {
let pids =
Self::_get_ids_by_page(db, room_id, order_mode, 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?
} else {
cacher.get_pids(start, limit).await
};
Self::get_multi(db, rconn, &pids).await
}
async fn _get_ids_by_page(
db: &Db,
room_id: Option<i32>,
order_mode: u8,
start: i64,
limit: i64,
) -> QueryResult<Vec<i32>> {
db.run(move |c| {
let mut query = base_query!(posts);
let mut query = base_query!(posts).select(posts::id);
if order_mode > 0 {
query = query.filter(posts::is_reported.eq(false))
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 = 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),
3 => query.order(random()),
4 => query.order(posts::n_attentions.desc()),
_ => panic!("Wrong order mode!"),
};
@ -210,52 +278,68 @@ 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("%", "\\%");
db.run(move |c| {
let pat;
let mut query = base_query!(posts).distinct().left_join(comments::table);
// 先用搜索+缓存,性能有问题了再真的做tag表
query = match search_mode {
0 => {
pat = format!("%#{}%", &search_text2);
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)),
)
let search_text2 = search_text.replace('%', "\\%");
let pids = db
.run(move |c| {
let pat;
let mut query = base_query!(posts)
.select(posts::id)
.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));
}
1 => {
pat = format!("%{}%", search_text2.replace(" ", "%"));
query
.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_filter(comments::author_title.eq(&search_text)),
_ => panic!("Wrong search mode!"),
};
query
.order(posts::id.desc())
.offset(start)
.limit(limit)
.load(with_log!(c))
})
.await
// 先用搜索+缓存,性能有问题了再真的做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
.like(&pat)
.and(comments::is_deleted.eq(false))),
)
}
1 => {
pat = format!("%{}%", search_text2.replace(' ', "%"));
query
.filter(
posts::content.like(&pat).or(comments::content
.like(&pat)
.and(comments::is_deleted.eq(false))),
)
.filter(posts::allow_search.eq(true))
}
2 => query.filter(
posts::author_title
.eq(&search_text)
.or(comments::author_title.eq(&search_text)),
),
_ => panic!("Wrong search mode!"),
};
query
.order(posts::id.desc())
.offset(start)
.limit(limit)
.load(with_log!(c))
})
.await?;
Self::get_multi(db, rconn, &pids).await
}
pub async fn create(db: &Db, new_post: NewPost) -> QueryResult<Self> {
// TODO: tags
db.run(move |c| {
insert_into(posts::table)
.values(&new_post)
@ -264,56 +348,41 @@ impl Post {
.await
}
pub async fn update_cw(&self, db: &Db, new_cw: String) -> QueryResult<usize> {
let pid = self.id;
db.run(move |c| {
diesel::update(posts::table.find(pid))
.set(posts::cw.eq(new_cw))
.execute(with_log!(c))
})
.await
pub async fn set_instance_cache(&self, rconn: &RdsConn) {
PostCache::init(rconn).sets(&[self]).await;
}
pub async fn change_n_comments(&self, db: &Db, delta: i32) -> QueryResult<Self> {
let pid = self.id;
db.run(move |c| {
diesel::update(posts::table.find(pid))
.set(posts::n_comments.eq(posts::n_comments + delta))
.get_result(with_log!(c))
})
.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;
}
)),
);
}
pub async fn change_n_attentions(&self, db: &Db, delta: i32) -> QueryResult<Self> {
let pid = self.id;
db.run(move |c| {
diesel::update(posts::table.find(pid))
.set(posts::n_attentions.eq(posts::n_attentions + delta))
.get_result(with_log!(c))
})
.await
}
pub async fn annealing(c: &mut Conn, rconn: &mut 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))
.unwrap();
pub async fn change_hot_score(&self, db: &Db, delta: i32) -> QueryResult<Self> {
let pid = self.id;
db.run(move |c| {
diesel::update(posts::table.find(pid))
.set(posts::hot_score.eq(posts::hot_score + delta))
.get_result(with_log!(c))
})
.await
}
pub async fn set_instance_cache(&self, rconn: &RdsConn) {
PostCache::init(rconn).sets(&vec![self]).await;
}
pub async fn refresh_cache(&self, rconn: &RdsConn, is_new: bool) {
self.set_instance_cache(rconn).await;
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;
}
}
}
impl User {
pub async fn get_by_token(db: &Db, token: &str) -> Option<Self> {
async fn _get_by_token(db: &Db, token: &str) -> Option<Self> {
let token = token.to_string();
db.run(move |c| {
users::table
@ -324,20 +393,77 @@ impl User {
.ok()
}
pub async fn get_by_token_with_cache(db: &Db, rconn: &RdsConn, token: &str) -> Option<Self> {
let mut cacher = UserCache::init(token, &rconn);
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);
if let Some(u) = cacher.get().await {
Some(u)
} else {
let u = Self::get_by_token(db, token).await?;
let u = Self::_get_by_token(db, token).await?;
cacher.set(&u).await;
Some(u)
}
}
pub async fn find_or_create_token(
db: &Db,
name: &str,
force_refresh: bool,
) -> QueryResult<String> {
let name = name.to_string();
db.run(move |c| {
if let Some(u) = {
if force_refresh {
None
} else {
users::table
.filter(users::name.eq(&name))
.first::<Self>(with_log!(c))
.ok()
}
} {
Ok(u.token)
} else {
let token = random_string(16);
diesel::insert_into(users::table)
.values((users::name.eq(&name), users::token.eq(&token)))
.on_conflict(users::name)
.do_update()
.set(users::token.eq(&token))
.execute(with_log!(c))?;
Ok(token)
}
})
.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)]
#[table_name = "comments"]
#[diesel(table_name = comments)]
pub struct NewComment {
pub content: String,
pub author_hash: String,
@ -347,9 +473,12 @@ pub struct NewComment {
}
impl Comment {
get!(comments);
_get!(comments);
set_deleted!(comments);
pub async fn get(db: &Db, id: i32) -> QueryResult<Self> {
// no cache for single comment
Self::_get(db, id).await
}
pub async fn create(db: &Db, new_comment: NewComment) -> QueryResult<Self> {
db.run(move |c| {
@ -371,3 +500,5 @@ impl Comment {
.await
}
}
pub(crate) use {op_to_col_expr, update, with_log};

14
src/random_hasher.rs

@ -2,6 +2,14 @@ use chrono::{offset::Local, DateTime};
use rand::{distributions::Alphanumeric, thread_rng, Rng};
use sha2::{Digest, Sha256};
pub fn random_string(len: usize) -> String {
thread_rng()
.sample_iter(&Alphanumeric)
.take(len)
.map(char::from)
.collect()
}
pub struct RandomHasher {
pub salt: String,
pub start_time: DateTime<Local>,
@ -10,11 +18,7 @@ pub struct RandomHasher {
impl RandomHasher {
pub fn get_random_one() -> RandomHasher {
RandomHasher {
salt: thread_rng()
.sample_iter(&Alphanumeric)
.take(16)
.map(char::from)
.collect(),
salt: random_string(16),
start_time: Local::now(),
}
}

67
src/rate_limit.rs

@ -0,0 +1,67 @@
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::ops::{Deref, DerefMut};
use std::env;
use std::ops::{Deref, DerefMut};
pub struct RdsConn(pub MultiplexedConnection);
@ -34,7 +34,6 @@ 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");

410
src/rds_models.rs

@ -1,5 +1,96 @@
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};
macro_rules! init {
() => {
pub fn init(rconn: &RdsConn) -> Self {
Self {
rconn: rconn.clone(),
}
}
};
($ktype:ty, $formatter:literal) => {
pub fn init(k: $ktype, rconn: &RdsConn) -> Self {
Self {
key: format!($formatter, k),
rconn: rconn.clone(),
}
}
};
($k1type:ty, $k2type:ty, $formatter:literal) => {
pub fn init(k1: $k1type, k2: $k2type, rconn: &RdsConn) -> Self {
Self {
key: format!($formatter, k1, k2),
rconn: rconn.clone(),
}
}
};
}
macro_rules! has {
($vtype:ty) => {
pub async fn has(&mut self, v: $vtype) -> RedisResult<bool> {
self.rconn.sismember(&self.key, v).await
}
};
}
macro_rules! add {
($vtype:ty) => {
pub async fn add(&mut self, v: $vtype) -> RedisResult<usize> {
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_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 struct Attention {
key: String,
@ -7,26 +98,321 @@ pub struct Attention {
}
impl Attention {
pub fn init(namehash: &str, rconn: &RdsConn) -> Self {
Attention {
key: format!("hole_v2:attention:{}", namehash),
rconn: rconn.clone(),
init!(&str, "hole_v2:attention:{}");
add!(i32);
has!(i32);
clear_all!("hole_v2:attention:*");
pub async fn remove(&mut self, pid: i32) -> RedisResult<()> {
self.rconn.srem(&self.key, pid).await
}
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)
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(crate = "rocket::serde")]
pub enum LogType {
AdminDelete,
Report,
Ban,
}
pub async fn add(&mut self, pid: i32) -> RedisResult<()> {
self.rconn.sadd(&self.key, pid).await
/*
impl LogType {
pub fn contains_ugc(&self) -> bool {
match self {
Self::Report => true,
_ => false,
}
}
}
*/
pub async fn remove(&mut self, pid: i32) -> RedisResult<()> {
self.rconn.srem(&self.key, pid).await
#[derive(Serialize, Deserialize, Debug)]
#[serde(crate = "rocket::serde")]
pub struct Systemlog {
pub user_hash: String,
pub action_type: LogType,
pub target: String,
pub detail: String,
pub time: DateTime<Local>,
}
impl Systemlog {
pub async fn create(&self, rconn: &RdsConn) -> RedisResult<()> {
let mut rconn = rconn.clone();
if rconn.llen::<&str, isize>(KEY_SYSTEMLOG).await? > SYSTEMLOG_MAX_LEN {
rconn.ltrim(KEY_SYSTEMLOG, 0, SYSTEMLOG_MAX_LEN - 1).await?;
}
rconn
.lpush(KEY_SYSTEMLOG, serde_json::to_string(&self).unwrap())
.await
}
pub async fn has(&mut self, pid: i32) -> RedisResult<bool> {
self.rconn.sismember(&self.key, pid).await
pub async fn get_list(rconn: &RdsConn, limit: isize) -> RedisResult<Vec<Self>> {
let rds_result = rconn
.clone()
.lrange::<&str, Vec<String>>(KEY_SYSTEMLOG, 0, limit)
.await?;
Ok(rds_result
.iter()
.map(|s| serde_json::from_str(s).unwrap())
.collect())
}
}
pub async fn all(&mut self) -> RedisResult<Vec<i32>> {
self.rconn.smembers(&self.key).await
pub struct BannedUsers;
impl BannedUsers {
pub async fn add(rconn: &RdsConn, namehash: &str) -> RedisResult<()> {
rconn
.clone()
.sadd::<&str, &str, ()>(KEY_BANNED_USERS, namehash)
.await
}
pub async fn has(rconn: &RdsConn, namehash: &str) -> RedisResult<bool> {
rconn.clone().sismember(KEY_BANNED_USERS, namehash).await
}
pub async fn clear(rconn: &mut RdsConn) -> RedisResult<()> {
rconn.del(KEY_BANNED_USERS).await
}
}
pub struct BlockedUsers {
pub key: String,
rconn: RdsConn,
}
impl BlockedUsers {
init!(i32, "hole_v2:blocked_users:{}");
add!(&str);
has!(&str);
clear_all!("hole_v2:blocked_users:*");
pub async fn check_if_block(
rconn: &RdsConn,
user: &CurrentUser,
hash: &str,
) -> RedisResult<bool> {
Ok(match user.id {
Some(id) => BlockedUsers::init(id, rconn).has(hash).await?,
None => false,
} || BlockCounter::get_count(rconn, hash).await?.unwrap_or(0)
>= i32::from(user.auto_block_rank) * 5)
}
}
pub struct BlockCounter;
impl BlockCounter {
pub async fn count_incr(rconn: &RdsConn, namehash: &str) -> RedisResult<i32> {
rconn.clone().hincr(KEY_BLOCKED_COUNTER, namehash, 1).await
}
pub async fn get_count(rconn: &RdsConn, namehash: &str) -> RedisResult<Option<i32>> {
rconn.clone().hget(KEY_BLOCKED_COUNTER, namehash).await
}
}
pub struct CustomTitle;
impl CustomTitle {
async fn gen_and_set_secret(rconn: &RdsConn, title: &str) -> RedisResult<String> {
let secret = random_string(8);
rconn
.clone()
.set_ex(KEY_TITLE_SECRET!(&title), &secret, CUSTOM_TITLE_KEEP_TIME)
.await?;
Ok(secret)
}
// return false if title exits
pub async fn set(rconn: &RdsConn, namehash: &str, title: &str, secret: &str) -> Api<String> {
let mut rconn = rconn.clone();
if rconn.hexists(KEY_CUSTOM_TITLE, title).await? {
Err(PolicyError::TitleUsed)?
} 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?)
}
}
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 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 struct PollOption {
key: String,
rconn: RdsConn,
}
impl PollOption {
init!(i32, "hole_thu:poll_opts:{}");
pub async fn set_list(&mut self, v: &Vec<String>) -> RedisResult<()> {
self.rconn.del(&self.key).await?;
self.rconn.rpush(&self.key, v).await
}
pub async fn get_list(&mut self) -> RedisResult<Vec<String>> {
self.rconn.lrange(&self.key, 0, -1).await
}
}
pub struct PollVote {
key: String,
rconn: RdsConn,
}
impl PollVote {
init!(i32, usize, "hole_thu:poll_votes:{}:{}");
add!(&str);
has!(&str);
pub async fn count(&mut self) -> RedisResult<usize> {
self.rconn.scard(&self.key).await
}
}
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,6 +28,9 @@ table! {
is_reported -> Bool,
hot_score -> Int4,
allow_search -> Bool,
room_id -> Int4,
up_votes -> Int4,
down_votes -> Int4,
}
}
@ -42,8 +45,4 @@ 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,);

6
tools/migdb.py

@ -27,8 +27,8 @@ def mig_post():
r[3] = r[3] or '' # cw
r[4] = r[4] or '' # author_title
r[8] = r[8] or r[7] # comment_timestamp
r[7] = datetime.fromtimestamp(r[7])
r[8] = datetime.fromtimestamp(r[8])
r[7] = datetime.fromtimestamp(r[7]).astimezone()
r[8] = datetime.fromtimestamp(r[8]).astimezone()
r[9] = bool(r[9])
r[10] = bool(r[10] or False) # comment
r[12] = bool(r[12])
@ -82,7 +82,7 @@ def mig_comment():
for r in rs:
r = list(r)
r[2] = r[2] or ''
r[4] = datetime.fromtimestamp(r[4])
r[4] = datetime.fromtimestamp(r[4]).astimezone()
r[5] = bool(r[5] or False)
r.insert(6, searchable[r[6]])
r.insert(3, r[3].startswith('[tmp]\n'))

Loading…
Cancel
Save