Compare commits

...

1787 Commits

Author SHA1 Message Date
Dessalines 69bdcb3069 Version 0.19.4-rc.2 2024-05-23 12:10:33 -04:00
Dessalines 6a6108ac55
Fixing proxied images for federated posts. (#4737)
* Fixing proxied images for federated posts.

- Also added test.
- Fixes #4736

* Address PR comments.
2024-05-23 11:11:25 -04:00
Nutomic b2c1a14234
Correct url for nodeinfo version (#4734)
* Correct url for nodeinfo version

* add compat redirect

---------

Co-authored-by: SleeplessOne1917 <28871516+SleeplessOne1917@users.noreply.github.com>
2024-05-23 10:59:56 -04:00
Nutomic d8dc38eb06
Upgrade dependencies (#4740) 2024-05-23 10:55:20 -04:00
Nutomic c96017c009
Configure max comment width in clippy (#4738)
* Configure max comment width in clippy

* update default config
2024-05-23 08:46:26 -04:00
Dessalines 9aa565b559 Version 0.19.4-rc.1 2024-05-22 08:58:31 -04:00
Dessalines 7d7cd8ded4
Dont show replies / mentions from blocked users. Fixes #4227 (#4727)
* Dont show replies / mentions from blocked users. Fixes #4227

* Adding unit tests for reply and mention views.

- Also cleaned up some unwraps in the tests.

* Add allow deprecated to pass clippy for deprecated wav crate.

---------

Co-authored-by: SleeplessOne1917 <28871516+SleeplessOne1917@users.noreply.github.com>
2024-05-22 08:50:26 -04:00
Nutomic 943c31cc72
Allow passing command line params via environment (fixes #4603) (#4729)
* Allow passing command line params via environment (fixes #4603)

* add prefix

---------

Co-authored-by: SleeplessOne1917 <28871516+SleeplessOne1917@users.noreply.github.com>
2024-05-22 08:39:01 -04:00
Nutomic 973f39601c
Dont allow removing comment which was deleted (fixes #4731) (#4732) 2024-05-22 08:29:01 -04:00
Felix Ableitner a39c19c9db Version 0.19.4-beta.8 2024-05-22 10:30:38 +02:00
Dessalines 55f84dd38a
Fixing proxy images (#4722)
* Adding an image_details table to store image dimensions.

- Adds an image_details table, which stores the height,
  width, and content_type for local and remote images.
- For LocalImages, this information already comes back with
  the upload.
- For RemoteImages, it calls the pictrs details endpoint.
- Fixed some issues with proxying non-image urls.
- Fixes #3328
- Also fixes #4703

* Running sql format.

* Running fmt.

* Don't fetch metadata in background for local API requests.

* Dont export remote_image table to typescript.

* Cleaning up validate.

* Dont proxy url.

* Fixing tests, fixing issue with federated thumbnails.

* Fix tests.

* Updating corepack, fixing issue.

* Refactoring image inserts to use transactions.

* Use select exists again.

* Fixing imports.

* Fix test.

* Removing pointless backgrounded metadata generation version.

* Removing public pictrs details route.

* Fixing clippy.

* Fixing proxy image fetching. Fixes #4703

- This extracts only the proxy image fixes from #4704, leaving off
  thumbnails.

* Fix test.

* Addressing PR comments.

* Address PR comments 2.

---------

Co-authored-by: SleeplessOne1917 <28871516+SleeplessOne1917@users.noreply.github.com>
2024-05-22 10:28:47 +02:00
Nutomic 6b46a70535
Extra logging to debug duplicate activities (ref #4609) (#4726)
* Extra logging to debug duplicate activities (ref #4609)

* Fix logging for api tests

* fmt
2024-05-21 14:47:06 -04:00
Nutomic 4ffaa93431
Dont allow reusing password reset token, use normal rate limit (#4719)
* Dont allow reusing password reset token, use normal rate limit

* fix
2024-05-21 14:46:49 -04:00
flamingos-cant a0ad7806cb
Increase alt_text size to 1500 (#4724) 2024-05-17 13:03:19 -04:00
Nutomic 99aac07714
Mark database fields as sensitive so they dont show up in logs (#4720)
* Mark database fields as sensitive so they dont show up in logs

* add file

* fix test

* Update crates/apub/src/objects/person.rs

Co-authored-by: SleeplessOne1917 <28871516+SleeplessOne1917@users.noreply.github.com>

* Update crates/apub/src/objects/community.rs

Co-authored-by: SleeplessOne1917 <28871516+SleeplessOne1917@users.noreply.github.com>

* Update crates/apub/src/objects/instance.rs

Co-authored-by: SleeplessOne1917 <28871516+SleeplessOne1917@users.noreply.github.com>

---------

Co-authored-by: SleeplessOne1917 <28871516+SleeplessOne1917@users.noreply.github.com>
Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2024-05-16 20:41:57 -04:00
Dessalines 1a4aa3eaba
Stop using a diesel_cli docker image, use cargo-install in woodpecker. (#4723)
* Stop using a diesel_cli docker image, use cargo-binstall in woodpecker.

- The diesel_cli image is 500MB, and rebuilt daily. Much easier to use
  binstall to install it.

* Trying out a multiline var.

* Try sequence merges 1

* Try removing features.

* Try path fix.

* Abstracting diesel cli install.

* Try installing mysql and postgres.

* Try installing mysql and postgres 2.

* Try installing mysql and postgres 3.

* Try installing mysql and postgres 4.

* Try installing mysql and postgres 5.

* Try installing mysql and postgres 6.

* Try installing mysql and postgres 7.

* Try installing mysql and postgres 8.

* Try installing mysql and postgres 9.

* Try installing mysql and postgres 10.

* Try installing mysql and postgres 11.

* Try installing mysql and postgres 12.

* Try installing mysql and postgres 13.

* Add logging line.

* Add logging line 2.

* Add logging line 3.

* Add logging line 4.

* Removing binstall.

* Extract taplo into its own image, ignore binstall.

* Use a smaller taplo.

* taplo is the same image.
2024-05-16 16:41:36 -04:00
Nutomic 93c9a5f2b1
Dont federate post locking via Update activity (#4717)
* Dont federate post locking via Update activity

* cleanup

* add missing mod log entries

* update assets
2024-05-15 07:36:00 -04:00
Nutomic 9a9d518153
Fix import blocked objects (#4712)
* Allow importing partial backup (fixes #4672)

* Fetch blocked objects if not known locally (fixes #4669)

* extract helper fn

* add comment

* cleanup

* remove test

* fmt

* remove .ok()
2024-05-14 23:03:43 -04:00
Nutomic 7fb03c502e
Add test to ensure reports are sent to user's home instance (ref #4701) (#4711)
* Add test to ensure reports are sent to user's home instance (ref #4701)

* enable all tests

* set package-manager-strict=false
2024-05-14 22:48:24 -04:00
Nutomic 49bb17b583
Stricter rate limit for login (#4718) 2024-05-14 22:43:43 -04:00
Nutomic 723cb549d4
Allow importing partial backup (fixes #4672) (#4705)
* Allow importing partial backup (fixes #4672)

* Dont throw error on empty LocalUser::update

* fix tests
2024-05-14 22:37:30 -04:00
Nutomic 8b6a4c060e
Make nodeinfo standard compliant, upgrade to nodeinfo 2.1 (fixes #4702) (#4706)
* Always set activitypub protocol in nodeinfo response (fixes #4702)

* Add mandatory fields
2024-05-13 22:53:20 -04:00
Dessalines cb80980027 Version 0.19.4-beta.7 2024-05-11 13:51:09 -04:00
dullbananas c4fc3a8ede
Optimize stuff in attempt to fix high amount of locks, and fix comment_aggregates.child_count (#4696)
* separate triggers

* auto_explain.log_triggers=on

* Revert "auto_explain.log_triggers=on"

This reverts commit 078b2dbb9bbb878078f1089cffda06b6458d127c.

* Revert "separate triggers"

This reverts commit 95600da4afb49e1dc203c2d61da4c57858e107db.

* bring back migration

* re-order statements

* add comment about statement ordering

* no redundant updates

* optimize post_aggregates update in comment trigger

* set comment path in trigger

* update comment_aggregates.child_count using trigger

* move `LEFT JOIN post` to inner query

* clean up newest_comment_time_necro

* add down.sql
2024-05-09 08:18:55 -04:00
Nutomic b4f9ef24a5
Dont exit early when running only scheduled tasks (#4707)
* Dont exit early when running only scheduled tasks (fixes #4709)

* fix
2024-05-08 14:56:44 +02:00
Nutomic 866d752a3c
Instance.preferred_username should be optional (fixes #4701) (#4713) 2024-05-08 08:01:04 -04:00
Nutomic e0b1d0553d
Add timeout for processing incoming activities (#4708)
* Add timeout for processing incoming activities

* move to const
2024-05-08 08:00:55 -04:00
Nutomic 7c146272c3
Federate with wordpress, improvements for NodeBB, Discourse federation (#4692)
* Federate with wordpress

* upgrade apub lib with fix

* Also read post's community from `audience`

* cleanup

* cargo update

* upgrade apub lib

* add wordpress test activity
2024-05-07 16:20:43 -04:00
Nutomic cfdc732d3a
On registration set show_nsfw based on site.content_warning (#4616)
Co-authored-by: SleeplessOne1917 <28871516+SleeplessOne1917@users.noreply.github.com>
2024-05-07 16:18:58 -04:00
Tim Coombs 522f974e30
fix: use docker compose v2 (#4622)
* fix: use docker compose v2

* Using sudo tee.

* fix: correct postgres sed command

---------

Co-authored-by: Dessalines <tyhou13@gmx.com>
Co-authored-by: SleeplessOne1917 <28871516+SleeplessOne1917@users.noreply.github.com>
2024-05-07 11:41:40 +02:00
SleeplessOne1917 b152be7951
Update rustls (#4690)
* Update rustls

* Format code
2024-05-03 16:06:14 -04:00
SleeplessOne1917 485b0f1a54
Replace unmaintained encoding dep with maintained encoding_rs dep (#4694)
* Replace dependency on unmaintained encoding crate with dep on maintained encoding_rs crate

* Update lockfile

* Taplo format Cargo.toml

* Use better variable name

* Replace into_owned with into
2024-05-03 10:42:48 +00:00
Nutomic 7540b02723
Update activitypub library (#4691)
https://github.com/LemmyNet/activitypub-federation-rust/releases/tag/0.5.5
2024-05-02 12:46:34 -04:00
Nutomic 7746db4169
Testing and minor fix for federation with Discourse (#4628)
* Testing and minor fix for federation with Discourse

* prettier
2024-05-02 07:49:19 -04:00
Dessalines db2ce81fc4
Show trigger logging. #4681 (#4688) 2024-05-01 18:46:14 -04:00
renovate[bot] 4175a1af80
chore(deps): update rust crate serde_with to 3.8.1 (#4687)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2024-04-30 23:47:02 -04:00
renovate[bot] 563280456e
chore(deps): update pnpm to v9.0.6 (#4682)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2024-04-30 23:43:14 -04:00
Dessalines 2fecb7ecdf
Dont show own comments for liked and disliked_only. Fixes #4675 (#4679)
Co-authored-by: SleeplessOne1917 <28871516+SleeplessOne1917@users.noreply.github.com>
2024-04-30 23:26:55 -04:00
renovate[bot] 2c6f9c7fd5
chore(deps): update rust crate serde to 1.0.199 (#4684)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2024-04-30 23:17:23 -04:00
renovate[bot] e338e59868
fix(deps): update rust crate lettre to 0.11.7 (#4685)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2024-04-30 22:54:16 -04:00
renovate[bot] b0caa85ed4
chore(deps): update rust crate base64 to 0.22.1 (#4683)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2024-04-30 22:30:19 -04:00
Dessalines ad60d91f5c
Dont publish lemmy_db_perf to fix crates.io publish. Fixes #4678 (#4680) 2024-04-30 17:51:12 +00:00
Dessalines 6423d2dde5 Version 0.19.4-beta.6 2024-04-30 06:38:44 -04:00
Nutomic 12163701e7
Avoid crash when handling urls without domain (#4676)
* Avoid crash when handling urls without domain

* Add some extra checks
2024-04-30 06:33:37 -04:00
Dessalines 5c35e97a75
Dont show deleted / removed posts when searching. Fixes #4576 (#4671)
* Dont show deleted / removed posts when searching. Fixes #4576

* Address PR comments.

* Clean up comment removed also.

---------

Co-authored-by: SleeplessOne1917 <28871516+SleeplessOne1917@users.noreply.github.com>
2024-04-30 12:24:18 +02:00
SleeplessOne1917 b05f221565
Remove login step from publish to crates.io (#4674) 2024-04-30 00:07:03 +00:00
Nutomic beec080274
Testing for federation with NodeBB, make community.followers_url optional (#4629)
* Testing for federation with NodeBB, make community.followers_url optional

* clippy
2024-04-29 12:34:11 +02:00
Dessalines 492d8f1b01
Fix communities with broken outboxes, and use PostView. Fixes #4658 (#4668)
* Fix communities with broken outboxes, and use PostView. Fixes #4658

* Fixing tests.

* Dont pass ref and clone.
2024-04-29 12:22:00 +02:00
dullbananas d3737d4453
Optimize actor_language.rs (#4612)
* Remove useless transaction in actor_language.rs

* Update actor_language.rs

* site

* community

* Update actor_language.rs

* Update actor_language.rs

* Update actor_language.rs

* Update actor_language.rs

* Update actor_language.rs
2024-04-27 10:59:58 -04:00
Dessalines b459949f57 Version 0.19.4-beta.5 2024-04-25 19:59:24 -04:00
Dessalines 93f5df2d2a
Adding post_id desc to all post_aggregates indexes. Fixes #4618 (#4662)
* Adding post_id desc to all post_aggregates indexes. Fixes #4618

* Running pg_format

* Not rebuilding indexes which had no changes.
2024-04-25 18:19:02 -04:00
Nutomic cf426493e1
Fix community add mod check (fixes #4624) (#4667) 2024-04-25 11:47:38 -04:00
Dessalines 8e3ff0408e
Fixing extra modlog entries when post_id or comment_id is given. (#4664)
- Previously when given a post_id, it didn't filter out any other
  modlog entries, such as community removals. This fixes that problem.
- Context: https://github.com/LemmyNet/lemmy-ui/pull/2437

Co-authored-by: SleeplessOne1917 <28871516+SleeplessOne1917@users.noreply.github.com>
2024-04-25 10:26:17 +02:00
Dessalines 66e06b3952
Removing scheme from block urls. Fixes #4656 (#4659)
* Removing scheme from block urls. Fixes #4656

* Fix comment.

* Fixing domain checking.

* Removing pointless URL building in url blocklist regex.

* Remove trailing /
2024-04-23 23:15:20 -04:00
Kroese 6b9d9dfaa5
Fix broken thumbnails (#4661)
* Check is_image_post flag

* Keep cargo_fmt happy

* Filter on is_image_post

* Trigger CI

* Keep cargo_fmt happy
2024-04-23 22:52:56 -04:00
tracyspacy 0eaf8d33e7
Filter_removed_comments_from_search (#4634)
* filter_removed_comments_from_search

* Revert "filter_removed_comments_from_search"

This reverts commit c6d6490afa923a666b96c785a776711ef42baed7.

* filtering_removed_comments_search

* filter_deleted_comments

* Revert "filter_deleted_comments"

This reverts commit 7dc1d13d24f0300ae17cecdf13abbfba24ac9a06.

* Revert "filtering_removed_comments_search"

This reverts commit 6e9b1de7a21a03caed3b2832fbf5d09c204b7994.

* filtering_removed_dELeted_comments_search
2024-04-22 11:33:02 -04:00
renovate[bot] c31a29ec7f
chore(deps): update dependency @types/node to v20.12.7 (#4647)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2024-04-19 18:56:35 -04:00
renovate[bot] 80635c9e24
chore(deps): update rust crate base64 to 0.22.0 (#4651)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2024-04-19 18:40:38 -04:00
renovate[bot] 95d75e07b2
chore(deps): update pnpm to v9.0.4 (#4649)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2024-04-19 18:23:06 -04:00
renovate[bot] efbfdc9340
chore(deps): update docker/dockerfile docker tag to v1.7 (#4650)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2024-04-19 18:12:26 -04:00
renovate[bot] 1ae3aab764
chore(deps): update dependency typescript to v5.4.5 (#4648)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2024-04-19 18:11:21 -04:00
renovate[bot] f68881c552
chore: Configure Renovate (#4644)
* Add renovate.json

* Updating renovate.

---------

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: Dessalines <tyhou13@gmx.com>
Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2024-04-19 17:00:23 -04:00
Dessalines 2ba1ba88b8
Upgrading deps. (#4645) 2024-04-19 16:50:27 -04:00
Dessalines 079fa0b8f6 Version 0.19.4-beta.4 2024-04-18 21:11:15 -04:00
dependabot[bot] b0a740d5c5
Bump h2 from 0.3.25 to 0.3.26 (#4639)
Bumps [h2](https://github.com/hyperium/h2) from 0.3.25 to 0.3.26.
- [Release notes](https://github.com/hyperium/h2/releases)
- [Changelog](https://github.com/hyperium/h2/blob/v0.3.26/CHANGELOG.md)
- [Commits](https://github.com/hyperium/h2/compare/v0.3.25...v0.3.26)

---
updated-dependencies:
- dependency-name: h2
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-04-18 21:05:45 -04:00
Kroese ee46242a43
Update aarch64-lemmy-linux-gnu to v0.3.0 (#4638) 2024-04-18 20:34:55 -04:00
dullbananas 4ba6221e04
Move SQL triggers from migrations into reusable sql file (#4333)
* stuff

* stuff including batch_upsert function

* stuff

* do things

* stuff

* different timestamps

* stuff

* Revert changes to comment.rs

* Update comment.rs

* Update comment.rs

* Update post_view.rs

* Update utils.rs

* Update up.sql

* Update up.sql

* Update down.sql

* Update up.sql

* Update main.rs

* use anyhow macro

* Create down.sql

* Create up.sql

* Create replaceable_schema.sql

* Update replaceable_schema.sql

* Update replaceable_schema.sql

* Update replaceable_schema.sql

* Update utils.rs

* Update .woodpecker.yml

* Update sql_format_check.sh

* Update replaceable_schema.sql

* Update replaceable_schema.sql

* Update replaceable_schema.sql

* Update replaceable_schema.sql

* Update replaceable_schema.sql

* Update replaceable_schema.sql

* Update replaceable_schema.sql

* Create dump_schema.sh

* Update start_dev_db.sh

* Update replaceable_schema.sql

* Update replaceable_schema.sql

* Update replaceable_schema.sql

* Update replaceable_schema.sql

* Update replaceable_schema.sql

* Update replaceable_schema.sql

* Update replaceable_schema.sql

* Update replaceable_schema.sql

* Update replaceable_schema.sql

* Update replaceable_schema.sql

* Update replaceable_schema.sql

* stuff

* Update replaceable_schema.sql

* Update .pg_format

* fmt

* stuff

* stuff (#21)

* Update replaceable_schema.sql

* Update up.sql

* Update replaceable_schema.sql

* fmt

* update cargo.lock

* stuff

* Update replaceable_schema.sql

* Remove truncate trigger because truncate is already restricted by foreign keys

* Update replaceable_schema.sql

* fix some things

* Update replaceable_schema.sql

* Update replaceable_schema.sql

* Update .woodpecker.yml

* stuff

* fix TG_OP

* Psql env vars

* try to fix combine_transition_tables parse error

* Revert "try to fix combine_transition_tables parse error"

This reverts commit 75d00a46266fbb49b7fab1b149c79fa1c31ee84a.

* refactor combine_transition_tables

* try to fix create_triggers

* fix some things

* try to fix combined_transition_tables

* fix sql errors

* update comment count in post trigger

* fmt

* Revert "fmt"

This reverts commit a5bcd0834bb91a63b66bf63a848caa078f193940.

* Revert "update comment count in post trigger"

This reverts commit 0066a4b42b3472c088eed945605a2cf0bfcc1362.

* fix everything

* Update replaceable_schema.sql

* actually fix everything

* refactor create_triggers

* fix

* add semicolons

* add is_counted function and fix incorrect bool operator in update_comment_count_from_post

* refactor comment trigger

* refactor post trigger

* fix

* Delete crates/db_schema/src/utils/series.rs

* subscribers_local

* edit migrations

* move migrations

* remove utils::series module declaration

* fix everything

* stuff

* Move sql to schema_setup dir

* utils.sql

* delete .pg_format

* Update .woodpecker.yml

* Update sql_format_check.sh

* Update .woodpecker.yml

* Merge remote-tracking branch 'upstream/main' into bliss

* fmt

* Create main.rs

* Update lib.rs

* Update main.rs

* Update .woodpecker.yml

* Update main.rs

* Update Cargo.toml

* Update .woodpecker.yml

* Update .woodpecker.yml

* Update triggers.sql

* YAY

* Update mod.rs

* Update Cargo.toml

* a

* Update Cargo.toml

* Update Cargo.toml

* Delete crates/db_schema/src/main.rs

* Update Cargo.toml

* Update .woodpecker.yml

* Update .woodpecker.yml

* Update .woodpecker.yml

* Update .woodpecker.yml

* Update .woodpecker.yml

* Update .woodpecker.yml

* Update .woodpecker.yml

* Update utils.sql

* Update utils.sql

* Update .woodpecker.yml

* Update .woodpecker.yml

* Update .woodpecker.yml

* Update .woodpecker.yml

* Update .woodpecker.yml

* Update down.sql

* Update up.sql

* Update triggers.sql

* Update .woodpecker.yml

* Update .woodpecker.yml

* Update triggers.sql

* Update down.sql

* Update .woodpecker.yml

* Update Cargo.toml

* Update .woodpecker.yml

* Update Cargo.toml

* Update .woodpecker.yml

* Update .woodpecker.yml

* Update .woodpecker.yml

* Update .woodpecker.yml

* Update .woodpecker.yml

* Update .woodpecker.yml

* Update .woodpecker.yml

* Update .woodpecker.yml

* Update .woodpecker.yml

* Update .woodpecker.yml

* Update .woodpecker.yml

* Update .woodpecker.yml

* Update .woodpecker.yml

* Update .woodpecker.yml

* Update .woodpecker.yml

* Update mod.rs

* Update Cargo.toml

* Update mod.rs

* make dump_schema.sh executable

* fix dump_schema.sh

* defer

* diff dumps

* fmt

* Update utils.sql

* Update .woodpecker.yml

* use correct version for pg_dump

* Update .woodpecker.yml

* Update .woodpecker.yml

* change migration date

* atomic site_aggregates insert

* temporarily repeat tests in CI

* drop r schema in CI migration check

* show ReceivedActivity::create error

* move check_diesel_migration CI step

* Update .woodpecker.yml

* Update scheduled_tasks.rs

* Update scheduled_tasks.rs

* update cargo.lock

* move sql files

* move rank functions

* filter post_aggregates update

* fmt

* cargo fmt

* replace post_id with id

* update cargo.lock

* avoid locking rows that need no change in up.sql

* only run replaceable_schema if migrations were run

* debug ci test failure

* make replaceable_schema work in CI

* Update .woodpecker.yml

* remove println

* Use migration revert and git checkout

* Update schema_setup.rs

* Fix

* Update schema_setup.rs

* Update schema_setup.rs

* Update .woodpecker.yml

---------

Co-authored-by: Nutomic <me@nutomic.com>
Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2024-04-17 20:58:44 -04:00
Nutomic 31829b6c05
Untangle thumbnail generation logic (ref #4604) (#4615)
* Untangle thumbnail generation logic (ref #4604)

* prettier

* test cleanup

* fix tests

* also consider opengraph image for local thumbnail generation
2024-04-17 10:36:45 -04:00
TechVest b0370ae2fd
chore: fix some comments (#4637)
Signed-off-by: TechVest <techdashen@qq.com>
2024-04-17 14:35:54 +02:00
Dessalines 6efab9aab1
Creating a LocalImageView, so that front ends have the Person struct. (#4631)
* Creating a LocalImageView, so that front ends have the Person struct.

* Removing local_user from LocalImageView.

* Add uploader check.
2024-04-16 19:20:44 -04:00
Dessalines d075acce43
Make all single-fetch database calls return an Option. (#4617)
- Diesel ordinarily throws an error when no results are returned for a
  single fetch, which is a bit confusing. This PR ensures that the
  missing value cases are all caught, and wrapped with new LemmyErrors,
  rather than diesel errors.
- Fixes #4601
2024-04-16 14:48:15 +02:00
Nutomic 3a0c1dca90
Avoid overwriting local objects via federation (#4611)
* Dont allow federation to overwrite local objects

* is_local check in apub lib

* use imports

* fix check, update lib

* use verify_is_remote_object()

* submodule
2024-04-11 10:05:49 -04:00
dullbananas 0f6b13a4ec
Test coverage (#4596)
* update .gitignore

* add test-with-coverage.sh

* coverage gutters extension comment

* move lcov.info to target folder

---------

Co-authored-by: SleeplessOne1917 <28871516+SleeplessOne1917@users.noreply.github.com>
2024-04-11 10:32:07 +02:00
Dessalines 64760ec960 Version 0.19.4-beta.3 2024-04-10 11:03:11 -04:00
Dessalines 555f789269
Fixing custom_thumbnail updates. (#4593)
* Fixing custom_thumbnail updates.

* Fixing issue with image posts.

* Fixing upgrade deps script.

* Adding API tests for custom thumbnails.

* Remove pointless todo.

* Address PR comments.

---------

Co-authored-by: SleeplessOne1917 <28871516+SleeplessOne1917@users.noreply.github.com>
2024-04-10 10:59:46 -04:00
Dessalines 5dea21d531
Convert all Result<..., LemmyError> into LemmyResult<...> Fixes #4613 (#4614)
* Convert all Result<..., LemmyError> into LemmyResult<...> Fixes #4613

* Fixing clippy.
2024-04-10 10:14:11 -04:00
Kroese d5622a65f8
Fix for PictrsImageMode::None (#4604)
* Fix PictrsImageMode::None

* Update crates/api_common/src/request.rs

Co-authored-by: SleeplessOne1917 <28871516+SleeplessOne1917@users.noreply.github.com>

* Fix formatting

---------

Co-authored-by: SleeplessOne1917 <28871516+SleeplessOne1917@users.noreply.github.com>
2024-04-10 10:09:54 -04:00
Nutomic 9059de8569
Allow fetching from local url, add fetch redirect test (fixes #4526) (#4607)
* Allow fetching from local url, at fetch redirect test (fixes #4526)

* prettier

* update lib

* update apub lib
2024-04-10 10:04:57 -04:00
Nutomic 0203b62a6d
Ignore old federated post edits (ref #4529) (#4586)
* Ignore old federated post edits (ref #4529)

* use filter on insert

* coalesce(updated, published)

* avoid comment conflict clause

---------

Co-authored-by: SleeplessOne1917 <28871516+SleeplessOne1917@users.noreply.github.com>
2024-04-10 10:03:51 -04:00
Dessalines 99d585b7be
Change defaults on user vote display mode to upvotes + downvotes (#4599)
* Change defaults on user vote display mode to upvotes + downvotes

* Forgot to regenerate the rows.

* Drop and re-add columns instead.
2024-04-10 10:47:05 +02:00
Nutomic b4670988b5
Change exponential backoff algorithm for federation send (#4597)
* Limit federation send retry interval to one hour

* clippy

* avoid overflow

* change base for exp backoff

* ignore first error

* fix day duration
2024-04-09 19:33:01 -04:00
Nutomic 1d0a6ac08f
Avoid breaking api change, reduce api cache duration (#4610)
* Dont mark site.public_key as `serde(skip)` to avoid breaking change (fixes #4605)

* Reduce cache duration for api
2024-04-09 10:10:20 -04:00
Dessalines 8e54a4a6cc
Fixing bug where comment replies wouldn't be sent to blocked instances. (#4595)
* Fixing bug where comment replies wouldn't be sent to blocked instances.

- Instance blocks should only affect communities, not comments.
- Fixes #4590

* Revert "Fixing bug where comment replies wouldn't be sent to blocked instances."

This reverts commit 1349aa351a.

* Only block replies from the community's instance id.

- Also refactor send_local_notifs slightly, since it has to fetch the
  community now.
- Fixes #4590

---------

Co-authored-by: SleeplessOne1917 <28871516+SleeplessOne1917@users.noreply.github.com>
2024-04-08 16:26:24 +02:00
jim-taylor-business a14ebefd24
When env variable is set, any config file will be ignored and the default settings will be used (#4594)
* do not panic when no config file found use defaults

* formatting

* implement env variable

* ermove commented code

* remove redundant comment

* remove redundant space

* simplify check logic

* format

* returns and messages

* correct mistake
2024-04-08 12:05:54 +02:00
Dessalines 705e86eb4c
Fixing docker release (#4592)
* Re-add notif on tag failure.

* Upping rust version.

* Version 0.19.4-beta.1a

* Try again.

* Version 0.19.4-beta.1b

* Removing unstable inspect.

* Version 0.19.4-beta.1c

* Remove use release cache.

* Trying to fix cargo publish 1.

* Version 0.19.4-beta.1d

* Re-adding publish release

* Version 0.19.4-beta.2

* Fixing workspace for lemmy_federate
2024-04-04 16:14:59 +02:00
Dessalines a1d632e582
Re-add notif on tag failure. (#4591) 2024-04-04 10:21:31 +02:00
Nutomic 087684658a
Cache result of LocalSite::read to avoid unnecessary db calls (#4585)
* Cache result of LocalSite::read to avoid unnecessary db calls

* single const for cache duration

* clippy

* revert apub send changes

* clippy

* fmt
2024-04-03 17:38:31 -04:00
Dessalines aaaa362b98
Remove latest tag for pgformatter. (#4589) 2024-04-03 17:29:24 -04:00
Dessalines 5237233f97 Version 0.19.4-beta.1 2024-04-03 16:50:35 -04:00
Dessalines 94438a8516
Removing cardano, this was never used. (#4588) 2024-04-03 10:38:57 +02:00
Dessalines 4d9c16a336
Fix private message sort order. #4581 (#4587) 2024-04-02 13:25:28 -04:00
Nutomic ae9f82b452
Read crate version from cargo.toml (fixes #4583) (#4584) 2024-04-02 11:19:51 -04:00
dullbananas 007e9b7aab
Optimize Community::set_featured_posts (#4579)
* Don't lock excess rows in Community::set_featured_posts

* Update community.rs

* Update community.rs

* Update community.rs

* Update community.rs
2024-04-02 11:19:04 -04:00
tracyspacy 60f9a97dfa
Fix unnecessarily duplicated notifs (#4578)
* add check to remove duplicated notifs

* added comments
2024-03-29 17:09:19 -04:00
Dessalines 067332553d
Fixing woodpecker. (#4575) 2024-03-27 11:09:44 -04:00
Nutomic a4b79ca610
Generate post thumbnail/metadata in background (ref #4529) (#4564)
* Generate post thumbnail/metadata in background (ref #4529)

* fix api test

* Apply suggestions from code review

Co-authored-by: SleeplessOne1917 <28871516+SleeplessOne1917@users.noreply.github.com>

* fix test

---------

Co-authored-by: SleeplessOne1917 <28871516+SleeplessOne1917@users.noreply.github.com>
2024-03-27 10:54:42 -04:00
Dessalines a632a86852
Delete a person's local images on delete account. (#4506)
* Delete a person's local images on delete account.

* Rename purge function to delete.

* Use purge_user_account instead of Person::delete_account in purge person.

* Fixing clippy
2024-03-27 10:28:02 -04:00
Nutomic 85ee89f4e8
When uploading new icon/avatar/banner, delete old one (#4573) 2024-03-27 09:00:52 -04:00
Dessalines 6bfbb9332d
Adding listMedia endpoint, to view all your local image uploads. (#4509)
* Adding listMedia endpoint, to view all your local image uploads.

- Fixes #4445

* Fix ts import.

* Forgot to order by published desc

* Adding an endpoint to list all images, for admins only.

* Forgot to add file.

* Add additional test.

* Use better logic for no-limit version.

* Better call sites.

* Adding another test.

* Fix tests.

* Moving list_media to /account action.

* Addressing PR comments.

* Removing pointless comment.

---------

Co-authored-by: SleeplessOne1917 <28871516+SleeplessOne1917@users.noreply.github.com>
2024-03-26 12:06:11 -04:00
Dessalines 945064726f
Add creator_banned_from_community to vote_view. (#4568)
* Add creator_banned_from_community to vote_view.

- Fixes #4561

* Adding tests.
2024-03-26 16:22:04 +01:00
Dessalines 7929e77602
Fixing issue with comment replies wrongly marked as read. (#4567)
* Fixing issue with comment replies wrongly marked as read.

- Fixes #4566

* Elaborating on a comment.
2024-03-26 10:46:37 -04:00
Dessalines 95069d7648
Fixing some clippy and woodpecker lints. (#4565)
* Fixing some clippy and woodpecker lints.

* Try fixing woodpecker 1.

* Revert "Try fixing woodpecker 1."

This reverts commit 7c2020a08d.
2024-03-26 10:17:42 +01:00
Dessalines e4356a7701
Fixing a few broken tests from the change in LocalUser::create (#4569) 2024-03-25 19:14:35 -04:00
Nutomic 846848c4f6
On registration, automatically set content languages from `accept-language` header (#4550)
* On registration, automatically set content languages from accept header

* no need to set site language or default language for new user anymore

* fix test

* fix langs

* avoid duplicate writing of new user languages
2024-03-25 16:02:12 -04:00
Nutomic d06ef2c47e
Migrate apub block activity to standard `endTime` property and deprecate `expires` (fixes #2316) (#4541)
* Migrate apub block activity to standard `endTime` property (fixes #2316)

* add todo
2024-03-25 08:10:09 -04:00
Sander Saarend 99d01e186a
Fix rate limiter (#4560) 2024-03-25 07:56:03 -04:00
Nutomic ef4bb3cc40
Add delete user field `removeData` to apub assets (fixes #4544) (#4549) 2024-03-22 18:41:59 -04:00
Nutomic 21547dedf7
Fix handling of apub downvote (fixes #4545) (#4551)
* Fix handling of apub downvote (fixes #4545)

* fmt

---------

Co-authored-by: SleeplessOne1917 <28871516+SleeplessOne1917@users.noreply.github.com>
2024-03-22 18:41:09 -04:00
Nutomic baf5921d2c
Add comment about console feature requiring tokio_unstable (fixes #4553) (#4555) 2024-03-22 18:40:08 -04:00
SleeplessOne1917 6679b2559f
Add SleeplessOne1917 to CODEOWNERS (#4558)
Co-authored-by: SleeplessOne1917 <insomnia-void@protonmail.com>
2024-03-22 18:31:45 -04:00
SleeplessOne1917 38c22d9453
Add banned_from_community to PostView and CommentView (#4552)
* Add banned_from_community to PostView and CommentView

* Add post view test

* Add tests for CommentView

* Add tests for case where local user is not banned from community

---------

Co-authored-by: SleeplessOne1917 <insomnia-void@protonmail.com>
2024-03-22 18:31:08 -04:00
Tomas 78581bd696
Add ARG RUSTFLAGS into Dockerfile (#4556)
* Add ARG RUSTFLAGS into Dockerfile 

Allows passing RUSTFLAGS through --build-arg

* Remove invalid ARG syntax
2024-03-21 16:42:30 +01:00
Dessalines 2fd81067c7
Temporarily comment sticky test. (#4538) 2024-03-18 12:54:45 +01:00
Dessalines 0f77951e05
Upgrading deps. (#4537)
* Upgrading deps.

* Addressing PR comments
2024-03-18 10:36:49 +01:00
Nutomic 9d4299aaac
Dont require leading ! or @ for webfinger resolve (#4513)
* Dont require leading ! or @ for webfinger resolve

* fmt

* clippy
2024-03-15 08:42:09 -04:00
Nutomic 43378c5bb3
Fix video thumbnail generation (fixes #3484) (#4539)
* Fix video thumbnail generation (fixes #3484)

* fix test
2024-03-15 08:41:16 -04:00
flamingos-cant 19a1a077c5
Add a blocklist for URLs. (#4515)
* Add a blocklist for URLs.

* Fix SQL format

* Make clippy happy.

* Use regex for URL matching.

* Escape regex chars in URLs.

* Use post for modification.

* Make URL block regex static and remove API routes.

* Add date fields to table and use transaction.

* Use Cache for blocklist.

* Rename check_links + move list to parameters of process_markdown.

* SQL format.

* Format, again.

* Remove println.

* Add API test.

* Set a shorter lifetime for regex in debug mode.

* Add missing macro.

* Update lemmy-js-client

* Update api_test/pnpm-lock.yaml

* Don't break other tests

* Use different URL for test

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
Co-authored-by: Nutomic <me@nutomic.com>
2024-03-15 07:03:29 -04:00
Nutomic 0e7080337b
Dont allow admins to post in community with `posting_restricted_to_mods` (fixes #3571) (#4534)
* Dont allow admins to post in community with `posting_restricted_to_mods` (fixes #3571)

* fmt
2024-03-14 17:31:54 -04:00
Nutomic 835d329134
Fix longstanding bug that breaks initial community view (fixes #3529) (#4535) 2024-03-14 16:57:56 -04:00
Nutomic f1de7b7590
Automatically include apub hashtag with posts (fixes #3906) (#4533) 2024-03-14 12:16:45 -04:00
Dessalines 255e695633
Adding extra fields to PostReport and CommentReport views. (#4520)
- Fixes #4200
2024-03-13 12:11:24 -04:00
Dessalines 15f02f00a9
Add a vote_display_mode local_user setting. (#4450)
* Add a vote_display_mode local_user setting.

- Fixes #4449

* Changing HideDownvotes to Score.

* Adding ScoreAndDownvote display mode.

* Adding upvote and downvote mode.

* Extracting vote_display_mode to another table.

* Fixing fmt.

* Remove published and updated columns.

---------

Co-authored-by: SleeplessOne1917 <28871516+SleeplessOne1917@users.noreply.github.com>
2024-03-13 12:10:58 -04:00
Dessalines 45c56df4e8
Adding git cliff to help generate changelogs. (#4522) 2024-03-12 11:24:27 +01:00
Nutomic 5d361d63ef
Change 2FA to use hostname as issuer (fixes #4518) (#4525) 2024-03-11 16:27:05 -04:00
Dessalines 10bf7464b1
Add code of conduct rules to issue template. (#4523) 2024-03-08 11:53:57 -05:00
Nutomic 5859502a2a
Fix missing private key for signed fetch (#4516)
* Fix missing private key for signed fetch (fixes #4451)

* clippy

* instance actor name and webfinger

* better webfinger handling

* upgrade lib

* update test asset
2024-03-08 10:23:15 -05:00
Nutomic 00f7778485
Store thumbnails in db table local_image (#4512)
* Store thumbnails in db table local_image

* fmt
2024-03-08 10:17:26 -05:00
Nutomic bc2e75d5a3
Add @dullbananas to codeowners (#4521) 2024-03-08 10:16:05 -05:00
battmdpkq f228f9d7a9
fix some typos (#4519)
Signed-off-by: battmdpkq <cmaker@163.com>
2024-03-08 10:38:20 +01:00
Nutomic fed6b61eaf
Upgrade apub lib, correct webfinger content-type (#4498)
* Upgrade apub lib, correct webfinger content-type

* fmt

* fix test by avoiding network fetch
2024-03-06 11:21:46 -05:00
Raphael Lullis bdabc5e827
Add curl to base images (#4510)
Having a tool like curl or wget can help us to run healthchecks on
docker-based deployments more easily. This commit adds curl to the
list of deb packages that are installed as external dependencies
2024-03-06 11:15:13 +01:00
Nutomic 97e2dbdfd7
Update contact section in readme (#4508)
* Update contact section in readme

* Update README.md

* Update README.md
2024-03-05 13:07:52 -05:00
Nutomic 22c2e20fc5
Remove contributing.md (#4507) 2024-03-05 13:07:20 -05:00
Dessalines 6778279bb6
When purging a federated user, federate local community removals. (#4505) 2024-03-05 09:31:04 -05:00
Nutomic 1ad9a211c9
Improve contributing instructions (#4504) 2024-03-05 09:14:15 -05:00
Nutomic 157378b4c9
Clear text of deleted/removed comments (#4503) 2024-03-05 08:52:35 -05:00
Dessalines 7f9950fe85
Add alt_text for posts. Fixes #1086 (#4477)
* Add alt_text for posts. Fixes #1086

* Moving alt_text to attachment name.

* Cleaning up mod action line.

* Addressing PR comments

* Addressing PR comments.

* Fixing clones.
2024-03-05 11:34:57 +01:00
Dessalines 52155c74cb
View report history for a post or comment. Fixes #4190 (#4492) 2024-03-05 11:31:40 +01:00
SleeplessOne1917 36ad1868b3
Make SiteAggregates derive Copy and Hash (#4501)
Co-authored-by: SleeplessOne1917 <insomnia-void@protonmail.com>
2024-03-05 11:14:12 +01:00
Dessalines 65da4e7dbd
View mod history for a post or comment. Fixes #4162 (#4491) 2024-03-04 11:42:25 -05:00
Nutomic 3c358e5b0b
Mods and admins can comment in locked posts (fixes #4116) (#4488)
* Mods and admins can comment in locked posts (fixes #4116)

* fmt

* fix

* fix test
2024-03-04 09:15:21 -05:00
Dessalines eb1245bceb
When using `saved_only`, sort posts / comments by the saved publish time, not the item creation time (#4479)
* Work on saved selection.

* Using single value for join.

* Removing unecessary check.

* Remove saved_only pointless block.
2024-03-04 14:19:51 +01:00
Dessalines 7eec8714d7
When site banning a federated user, also remove their content from our local communities. (#4464)
* When banning a federated user, also remove their content from our local
communities.

- This works by:
  - Before a site ban, find all posts and comments to local communities
  - Send a federated community ban action for each local comm.
  - This also removes their content in the apub receive code.
- Adding back in federated community ban api tests.
- Adding in two more api tests for site bans.
- Fixes #4118

* Add local community ban, and nonlocal person check.

* Ignoring errors.

* Move local check into function.

* Addressing PR comments 2
2024-03-01 13:45:06 -05:00
Nutomic 08b01a377d
Support listing type for person (fixes #4146) (#4487)
* Support listing type for person (fixes #4146)

* add test
2024-03-01 11:53:20 -05:00
Nutomic c5e54a318a
Store password reset token after email successfully sent (fixes #3757) (#4489) 2024-03-01 11:32:59 -05:00
Nutomic a7fa075e8c
Make logs less verbose (fixes #3627) (#4490) 2024-03-01 11:32:13 -05:00
Nutomic c895e57086
Remove unneeded error "last successful id is higher than latest id" (fixes #4363) (#4486) 2024-03-01 11:31:37 -05:00
Dessalines e1b26897be
Add nlnet grant line in readme. (#4484) 2024-03-01 11:22:53 -05:00
Dessalines 87b577467b
Adding ability to hide posts. (#4480)
* Adding ability to hide posts.

- Adds an post/hide API route.
- Adds a `show_hidden` (default false) to `GetPosts`.
- Adds a `hidden` field to `PostView`.
- Removes the single `post_id` from MarkPostAsRead.
- Fixes #1403

* Add a check to make sure hidden field is true.

* Fixing test.

* Add back semicolon
2024-02-29 10:42:34 -05:00
Nutomic 6d815db375
Require verified email to reset password (#4482) 2024-02-29 09:12:45 -05:00
Nutomic 328a48c9f5
Remove error-type feature from lemmy-utils (#4474)
* Remove error-type feature from lemmy-utils

* fixes

---------

Co-authored-by: SleeplessOne1917 <28871516+SleeplessOne1917@users.noreply.github.com>
2024-02-27 11:13:52 -05:00
Nutomic ab4deaa49a
Add api test for synchronizing featured posts (ref #4475) (#4476)
* Correctly synchronize collection of community featured posts (fixes #3867)

* Add api test for synchronizing featured posts (ref #4475)

* prettier
2024-02-27 09:11:41 -05:00
Dessalines e01ea32928
Fix doctype check issue for metadata fetching. Fixes #4468 (#4472)
* Fix doctype check issue for metadata fetching. Fixes #4468

* Change warn to info.
2024-02-26 10:24:09 -05:00
Dessalines f3d48f2c2c
Adding some recommended fixes from nightly clippy. (#4473) 2024-02-26 09:47:10 -05:00
Nutomic 7316dd281a
Correctly synchronize collection of community featured posts (fixes #3867) (#4475) 2024-02-26 09:45:23 -05:00
Richard Schwab 80bfd23b4d
Ensure rustfmt is installed in cargo fmt CI job (#4466) 2024-02-26 11:22:22 +01:00
SleeplessOne1917 f42420809b
Expose LemmyErrorType in lemmy_api_common (#4439)
* Expose LemmyErrorType in lemmy_api_common

* Make conditional compilation gates for utils

* Make it so api_common doesn't pull in unnecessary deps

* Make error type non exhaustive

* Fix formatting

* Format toml

* Add some convenience derives to LemmyError

* Simplify features

* Fix CI compile error

---------

Co-authored-by: SleeplessOne1917 <insomnia-void@protonmail.com>
2024-02-24 19:54:27 -05:00
dullbananas f56b84615c
Move DbUrl trait impls to newtypes.rs (#4463)
* Move DbUrl trait impls to newtypes.rs

* Update utils.rs
2024-02-19 12:41:28 -05:00
dullbananas d79502dff3
Escape backslashes in fuzzy_search (#4462)
* Escape backslashes in fuzzy_search

* Update utils.rs
2024-02-18 09:12:56 -05:00
dullbananas ae62ef2b7e
Ignore expired bans in CommentReportView::read, just like in CommentReportQuery::list (#4457)
* Update comment_report_view.rs

* Update comment_report_view.rs

* Update comment_report_view.rs

* Update comment_report_view.rs
2024-02-18 09:12:12 -05:00
SleeplessOne1917 39345466da
Make it so the signed in user can see if they're banned from a community (#4458)
* Make it so the signed in user can see if they're banned from a community

* Use more appropriate field name

---------

Co-authored-by: SleeplessOne1917 <insomnia-void@protonmail.com>
2024-02-18 09:09:46 -05:00
Dessalines 5d551e6da5
Adding an instance-level default_sort_type (#4454)
* Adding an instance-level default_sort_type

- Fixes #3796

* Fixing comment.

* Put user sort before site sort.
2024-02-16 09:36:46 -05:00
Nutomic ffcf415cac
Dont log db url on connection error (fixes #4453) (#4456)
* Dont log db url on connection error (fixes #4453)

* remove format
2024-02-16 08:50:06 -05:00
Nutomic 86b44c2a4d
Add site.content_warning, local_site.default_post_listing_mode (#4393)
* Include local_site.content_warning setting for showing nsfw by default

* Add community setting `only_followers_can_vote`

* clippy

* add auto_expand_images site setting

* cleanup

* add missing api params

* postquery/communityquery changes

* clippy

* change error

* replace auto_expand_images with default_site_post_listing_mode

* change post/community query params

* get rid of only_followers_can_vote

* machete

* fix

* clippy

* revert remaining vote changes

* remove dead code

* remove unused var

* fmt
2024-02-16 07:24:35 -05:00
Dessalines a3bf2f1cf1
Auto resolve reports on removing a comment or post. Fixes #4390 (#4402)
* Automatically resolve report when post/comment is removed (#3850)

* Automatically resolve report when post/comment is removed

* also handle apub removes

* Removing auto-resolve report triggers.

* Dont allow creating reports for deleted / removed items.

* Running pgformat.

* Fixing test.

* Addressing PR comments.

* Forgot comment report.

---------

Co-authored-by: Nutomic <me@nutomic.com>
2024-02-15 08:52:04 -05:00
Dessalines 890565ca14
Deleting denied local_users older than a week. Fixes #4434 (#4448)
* Deleting denied local_users older than a week. Fixes #4434

* Addressing PR comments.

* Upping rust to 1.76

* Delete the person rows also.
2024-02-15 07:50:53 -05:00
Dessalines 3f7cc07b02
Adding ability to specify a custom post thumbnail. (#4425)
* Adding ability to specify a custom post thumbnail.

- Context: #4204

* Fixing ts-rs serialization.

* Fixing conversion, adding checks.

* Proxying custom_thumbnail. Fixed logic for update.

* Only generate metadata thumbnail is theres no custom thumbnail.
2024-02-15 10:42:23 +01:00
Dessalines 33989f5518
Blocking an instance also hides private messages from their users. (#4447)
* Blocking an instance also hides private messages from their users.

- Fixes #4444

* Separating private message tests.
2024-02-14 10:49:55 +01:00
Lcchy 8a6a86c1bb
Add support for RSS media enclosures in feeds (#4442)
* Add support for RSS media enclosures in feeds

* Use post.url_content_type
2024-02-13 10:46:46 +01:00
dullbananas 677d54ae57
Allow better query plans (#4424)
* Update utils.rs

* Create bind_if_some.rs

* limit connection age

* Delete crates/db_schema/src/utils/bind_if_some.rs

* Update utils.rs

* Update utils.rs

* Update utils.rs

* Update utils.rs

* Update utils.rs

* Update utils.rs

* Update utils.rs

* Update utils.rs

* Update utils.rs

* Update utils.rs

* Update utils.rs

* Update utils.rs

* Update utils.rs
2024-02-12 16:44:29 +01:00
SleeplessOne1917 300869d397
Make request models derive PartialEq, Eq, and Hash (#4443)
* Make request models derive PartialEq, Eq, and Hash

* Fix clippy error

---------

Co-authored-by: SleeplessOne1917 <insomnia-void@protonmail.com>
2024-02-11 00:32:14 -05:00
Dessalines 609de3e9e2
Remove front end size. Fixes #4437 (#4440) 2024-02-09 10:42:12 +01:00
Elara 3c5b1ac6dd
Use the Accept-Language header to set new users' language (#4435)
* Use the Accept-Language header to set new users' language

* Implement clippy suggestions

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2024-02-08 10:53:03 +01:00
dullbananas f631f43024
Run analyze in db_perf (#4420) 2024-02-07 22:37:44 -05:00
Dessalines 9367cbdb00
Upgrading from postgres 15 -> 16-alpine. (#4426)
- Includes an upgrade script.
- Fixes #4406
2024-02-07 11:21:02 +01:00
Dessalines 3647a46e86
Remove ansible tagging. (#4417)
- See https://github.com/LemmyNet/lemmy-ansible/issues/215
2024-01-31 10:46:13 +01:00
Elara 328d48ef7e
Remove invalid XML characters from RSS feeds (#4416)
* Remove all characters that are disallowed by XML

* Combine contiguous unicode ranges into one range
2024-01-30 15:55:45 +01:00
Nutomic a09027c4c0
Silence warnings from ts-rs (#4415)
* Silence warnings from ts-rs

https://github.com/Aleph-Alpha/ts-rs/issues/108

* fmt
2024-01-29 09:22:53 -05:00
Elara 0e9924a2b3
Add `media:content` thumbnail to RSS feed (#4413)
* Add media:content thumbnail to RSS feed

* Run formatter

* Add media namespace definition

* Add comment linking to media-rss documentation
2024-01-29 08:56:35 -05:00
Dessalines eb0dc2fda4
Moving from yarn to pnpm. (#4414)
* Moving from yarn to pnpm.

* Prettier check.
2024-01-29 11:38:39 +01:00
Dessalines 9a2fb8e7c2
Fix image_mode for docker lemmy.hjson (#4403) 2024-01-26 10:51:59 +01:00
dullbananas f481a607d0
Show server output if federation tests fail in CI (#4389)
* Show server output if federation tests fail in CI

* dummy failure

* Revert dummy failure

* Update private_message.rs

* Fix errors

* Update private_message.rs

* Update private_message.rs

* Update .woodpecker.yml

* correct exit code

* Update .woodpecker.yml

* Update .woodpecker.yml

* Update .woodpecker.yml

* Update prepare-drone-federation-test.sh

* Update .woodpecker.yml

* Update prepare-drone-federation-test.sh

* Update .woodpecker.yml

* Update prepare-drone-federation-test.sh

* Update private_message.rs

* Update lib.rs

* Update lib.rs

* Update session_middleware.rs

* Update session_middleware.rs

* Update .woodpecker.yml
2024-01-26 10:38:15 +01:00
dullbananas ade1cb1495
Remove outdated comment from .woodpecker.yml (#4404) 2024-01-26 10:33:03 +01:00
Nutomic 0f414a95d5
Local only community (#4350)
* Add support for local only community (fixes #1576)

* add filters and tests to db views

* dont federate local only community

* test get apub community http

* tests

* more checks

* wip

* api test

* fix tests

* change community.local_only column to visibility enum
(for private communities)

* sql fmt

* rename vars

* clippy

* fix tests

* update lib

* review

* fix js client version

* update client
2024-01-25 11:04:25 -05:00
Dessalines 8cde452fca
Add a comment to clarify the ban expires field. (#4400)
* Add a comment to clarify the ban expires field.

* Add comment about simpler client implementation.

* Better language.
2024-01-25 16:45:42 +01:00
Nutomic dadf8f28f9
Send purges to federated instances (fixes #4119) (#4398)
* Send purges to federated instances (fixes #4119)

* clippy

* review

* remove unused function

* clippy
2024-01-25 09:24:09 -05:00
Nutomic e8a52d3a5c
Rewrite images to use local proxy (#4035)
* Add markdown rule to add rel=nofollow for all links

* Add markdown image rule to add local image proxy (fixes #1036)

* comments

* rewrite markdown image links working

* add comment

* perform markdown image processing in api/apub receivers

* clippy

* add db table to validate proxied links

* rewrite link fields for avatar, banner etc

* sql fmt

* proxy links received over federation

* add config option

* undo post.url rewriting, move http route definition

* add tests

* proxy images through pictrs

* testing

* cleanup request.rs file

* more cleanup (fixes #2611)

* include url content type when sending post over apub (fixes #2611)

* store post url content type in db

* should be media_type

* get rid of cache_remote_thumbnails setting, instead automatically
take thumbnail from federation data if available.

* fix tests

* add setting disable_external_link_previews

* federate post url as image depending on mime type

* change setting again

* machete

* invert

* support custom emoji

* clippy

* update defaults

* add image proxy test, fix test

* fix test

* clippy

* revert accidental changes

* address review

* clippy

* Markdown link rule-dess (#4356)

* Extracting opengraph_data to its own type.

* A few additions for markdown-link-rule.

---------

Co-authored-by: Nutomic <me@nutomic.com>

* fix setting

* use enum for image proxy setting

* fix test configs

* add config backwards compat

* clippy

* machete

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2024-01-25 09:22:11 -05:00
Dessalines 1782aafd10
Upgrading deps. (#4401) 2024-01-25 10:24:07 +01:00
dullbananas d8f9e8a64c
Post view: move cursor pagination to separate library, add backward pagination to PostQuery (#4320)
* stuff

* stuff

* crates.io

* Update up.sql

* Rerun federation tests

* Update post_view.rs

* Update post_view.rs

* Update up.sql

* Update utils.rs

* Fix precision loss

* Update up.sql

* Update down.sql

* remove unwrap

* Update post_view.rs

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2024-01-24 10:50:11 -05:00
dullbananas 759f6d8a9a
Better query plan viewing experience (#4285)
* stuff

* stuff including batch_upsert function

* stuff

* do things

* stuff

* different timestamps

* stuff

* Revert changes to comment.rs

* Update comment.rs

* Update comment.rs

* Update post_view.rs

* Update utils.rs

* Update up.sql

* Update up.sql

* Update down.sql

* Update up.sql

* Update main.rs

* use anyhow macro

* replace get(0) with first()

* as_slice

* Update series.rs

* Update db_perf.sh

* Update and rename crates/db_schema/src/utils/series.rs to crates/db_perf/src/series.rs

* Update utils.rs

* Update main.rs

* Update main.rs

* Update .woodpecker.yml

* fmt main.rs

* Update .woodpecker.yml

* Instance::delete at end

* Update main.rs

* Update Cargo.toml

---------

Co-authored-by: Nutomic <me@nutomic.com>
2024-01-24 10:22:33 -05:00
İsmail Karslı 8670403a67
Add local_subscribers field to CommunityAggregates. Fixes #4144 (#4166)
* Add upload timeout to PictrsConfig

* Bad space 🤔

* Update PictrsConfig upload timeout to include units.

* Add local_subscribers field to CommunityAggregates
struct and schema

* sql format

* local_subscribers test

* fix local_subscribers test

* Revert "fix local_subscribers test"

This reverts commit 4bbac5ce4afe101b2db4b9f099ca772c5ce2932b.

* Revert "local_subscribers test"

This reverts commit 735107e1f7554dfac6e474104eb87047675f11a5.

* Create trigger for local_subscribers

* Rename variable

* re-trigger ci

* re-trigger ci

* Add local_subscribers count to follow.spec.ts

* Rename local_subscribers to subscribers_local

* Add subscribers_local to community_aggregates

* added subscribers_local to the aggregate tests

* Check if person exists on community_follower trigger

* Delete community follows before deleting person

* Update lemmy-js-client in api_tests

* Refactor local_subscriber migration

* fix format

* Move migration files date to now

* Fix test to wait for aggregates to federate

* re-trigger ci

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2024-01-24 10:22:05 -05:00
Dessalines 922ec7c2cd
Forgot to add skip_serializing_none to persondetailsres. (#4399) 2024-01-24 09:58:58 -05:00
jim-taylor-business f43d2eca70
make inner type pub so it can be read and created easily in other crates (#4397)
this is for use in SSR pagination in Lemmy-UI-Leptos
2024-01-24 09:03:31 -05:00
Dessalines 20fd4b5869
Clippy fixes for 1.77.0 nightly (#4395)
* A few 1.77.0-nightly clippy fixes.

* Dead code warnings.

* More fixes.
2024-01-24 10:34:09 +01:00
Dessalines eb56d9253c
Adding site to GetPersonDetails. Fixes #4373 (#4394)
* Adding site to GetPersonDetails. Fixes #4373

* Removing the conditioned site return.
2024-01-24 10:32:14 +01:00
SleeplessOne1917 4b4b99aa78
Allow community mods to see votes in addition to admins (#4392)
* Allow community mods to see votes in addition to admins

* Use Post instead of PostView

---------

Co-authored-by: SleeplessOne1917 <insomnia-void@protonmail.com>
2024-01-23 18:47:28 -05:00
Dessalines 2133bcea4e Version 0.19.3 2024-01-22 08:56:08 -05:00
Nutomic 0868910570
Add secondary sort by published date for post view (fixes #4383) (#4384) 2024-01-22 08:52:21 -05:00
Dessalines e78fe5a34c
Removing group from woodpecker, as its deprecated. (#4387)
* Removing group from woodpecker, as its deprecated.

* Removing meltwater drone cache.
2024-01-22 10:57:07 +01:00
Dessalines f652513030 Version 0.19.3-rc.1 2024-01-19 11:25:45 -05:00
Dessalines df11d77a0d Updating translations. 2024-01-19 11:23:47 -05:00
Nutomic 3d6f7ff911
Revert "Dont ignore errors during login (fixes #4319) (#4321)" (#4380)
This reverts commit 4163e0465e.

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2024-01-19 11:21:43 -05:00
Nutomic 516db012bf
Dont allow caching captcha response (#4381)
Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2024-01-19 10:41:05 -05:00
Nutomic b58da11fb7
Mark instance as alive after successful activity send (fixes #4039) (#4377)
* Mark instance as alive after successful activity send (fixes #4039)

* clippy

* Instance::update

* domain

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2024-01-19 09:40:12 -05:00
Nutomic 1be7dbde33
Count chars, not bytes for max title length (fixes #4366) (#4367)
* Count chars, not bytes for max title length (fixes #4366)

* fix api test
2024-01-15 09:33:39 -05:00
Nutomic 9240a653c0
Fix bug with Mastodon undo follow activities (#4364) 2024-01-11 18:56:19 -05:00
Dessalines 0d35c247f9 Version 0.19.2 2024-01-10 10:18:09 -05:00
Dessalines 143fdb62b1 Updating translations. 2024-01-10 10:16:36 -05:00
Nutomic 2d16d12cb7
Move `publish = false` to correct place in lemmy_server (fixes #4359) (#4361) 2024-01-10 09:07:09 -05:00
Dessalines 3b717cfc88
Removing serde_skip from newest_comment_time. Fixes #4351 (#4360) 2024-01-10 10:44:27 +01:00
Dessalines ea0b856f1e Version 0.19.2-rc.5 2024-01-09 12:45:54 -05:00
Nutomic 92b49dea3a
Increase CI timeout for restore cache (#4358) 2024-01-09 12:37:48 -05:00
dullbananas 1ef90773e0
Refactor post view tests (#4313)
* Refactor post view tests

* Update post_view.rs

* Update post_view.rs

* Update post_view.rs

* Update post_view.rs

* Update post_view.rs

* Update post_view.rs

* Update post_view.rs

* remove unused import
2024-01-09 12:19:25 -05:00
Dessalines 3d9dda4677
Woodpecker rust 1.75 (#4355)
* Upgrading woodpecker rust to 1.75

* Trying to get publish working, try 1.

* Version 0.19.2-rc.3.publish1

* Temporarily disable arm builds.

* Version 0.19.2-rc.3.publish2

* Comment out arm blocks.

* Version 0.19.2-rc.3.publish3

* Moving back publish block to below.

* Upgrade to rasky lemmy-arm v0.2.0

* Version 0.19.2-rc.3.publish4

* Test bump for upgraded woodpecker.

* Revert "Test bump for upgraded woodpecker."

This reverts commit e2a5a99f33b63ef2a6f731b1ba7b4f06a02ded5f.

* Adding link to raskys repo.
2024-01-09 11:48:29 -05:00
Dessalines 2f09ad8e5b Version 0.19.2-rc.4 2024-01-09 09:25:52 -05:00
Nutomic e3b715002b
Handle federated reports from Mastodon, Kbin (#4323)
* Test Kbin/Mbin federation

* Handle reports from Mastodon/Kbin (fixes #4217)

* prettier

* revert

* add mastodon activity

* ci

* revert

* ci
2024-01-05 11:03:13 -05:00
Nutomic 4ca63c5641
Move apub context to join-lemmy.org (fixes #4234) (#4302)
* Move apub context to join-lemmy.org (fixes #4234)

* Dont store federation context in sent_activity table

* include basic activitypub context

* update lib

* ci
2024-01-05 15:42:46 +01:00
Felix Ableitner 346ff11795 Version 0.19.2-rc.2 2024-01-05 12:33:20 +01:00
Nutomic 747ab89e87
Upgrade docker rust version to 1.75 (#4353) 2024-01-05 12:32:06 +01:00
Felix Ableitner d3efebfa4e Version 0.19.2-rc.1 2024-01-05 11:33:37 +01:00
Dessalines 1856e7c0ca
Increasing max items for user settings import. (#4352)
- Fixes #4307
2024-01-05 10:43:30 +01:00
phiresky 0e6669f617
no endless loop if queue too recent (#4349) 2024-01-04 13:28:26 -05:00
Dessalines 4a740ee80a Version 0.19.1 2024-01-04 12:32:26 -05:00
Nutomic 7d9b59c467
Reduce default db pool size to 30, remove db timeout (ref #4282) (#4301)
* Reduce default db pool size to 30 (ref #4282)

* remove db timeout
2024-01-04 12:16:51 -05:00
Nutomic 38e64825e6
Add macro assert_length!() for tests (#4348)
* Add macro assert_length!() for tests

* fix

* number
2024-01-04 11:51:55 -05:00
Nutomic 3cad3b2119
Dont overwrite cache-control header in session middleware (#4337) 2024-01-04 11:44:36 -05:00
Nutomic 023c9f4fcd
Fix fetching of community posts (fixes #4283) (#4293)
* Fix fetching of community posts (fixes #4283)

Also use spawn_try_task to fetch community outbox, mods etc to avoid
delay/timeout when fetching new community.

* prettier

* fix test

* fix api test

* prettier

* add delay

* Update run-federation-test.sh

* fix test
2024-01-04 11:42:18 -05:00
Nutomic 952c162dac
Fix CI cache (#4276)
* Minor CI improvements (second attempt)

* test slow check condition

* remove rebuild cache condition for testing

* trigger quick ci check

* mkdir

* ls, remove steps

* exclude cargo home from prettier

* ci

* increase timeout

* more timeout

* even higher just for testing

* disable compression

* also increase restore timeout

* cleanup

* try again

* Update .woodpecker.yml

* Update .woodpecker.yml

* cleanup

* rerun ci

* cleanup
2024-01-04 11:40:41 -05:00
ALEX11BR a5289dd4cf
Use `pretty_assertions` for assertions (#4347)
* Use `pretty_assertions` for assertions

* fixed ordering of `use`s

* ci

---------

Co-authored-by: Felix Ableitner <me@nutomic.com>
2024-01-04 04:47:18 -05:00
Dessalines 009a45dffb
Adding /post/like/list and /comment/like/list for admins. (#4332)
- Allows admins to view likes, sorted by downvotes first,
  for a given comment or post.
- Fixes #4088
2024-01-03 13:39:21 -05:00
phiresky 024ab7d530
Fix federate loop (#4330)
* make activity channel infallible

* clippy

* federate: make cancellabletask loop itself
2024-01-03 13:30:06 -05:00
Nutomic 53147596b4
Drop unique constraint for site.name (fixes #4329) (#4342)
* Drop unique constraint for site.name (fixes #4329)

* working down migration
2024-01-03 12:47:39 -05:00
Nutomic 4163e0465e
Dont ignore errors during login (fixes #4319) (#4321)
* Dont ignore errors during login (fixes #4319)

* fix test

* fmt
2024-01-03 10:34:03 -05:00
Nutomic abe8b18ea8
Also send reports to user's home instance (fixes #4286) (#4305) 2024-01-03 10:31:51 -05:00
Sander Saarend 35db0dc8e7
Reduce initial federation retry delay (#4346) 2024-01-03 10:31:23 +01:00
Dessalines 5f603985c0
Allow reports to be resolved, even if the community is deleted / removed. (#4345)
Fixes #4344
2024-01-03 10:31:03 +01:00
Ikko Eltociear Ashimine 2f3a7abe6b
Update READMEs (#4325)
* Update README.ja.md

fix image path

* Update README.es.md

* Update README.ru.md

* Update README.zh.hans.md

* Update README.zh.hant.md

* prettier

---------

Co-authored-by: Felix Ableitner <me@nutomic.com>
2023-12-26 05:23:03 -05:00
Andrew Voynov f223eb94d5
Fixed `matrix_user_id` regex (#4312)
* fix(matrix_user_id): fixed regex

* test(matrix_user_id): added test with underscore
2023-12-21 12:13:24 +01:00
SleeplessOne1917 4ef00e068f
Prevent crates that shouldn't be published from being published (#4309)
* Prevent crates that shouldn't be published from being published

* Make dependent crates publishable

* Make dependent crates publishable

* fix toml formatting

* Removing publish=true

* Removing versioned deps.

---------

Co-authored-by: SleeplessOne1917 <insomnia-void@protonmail.com>
Co-authored-by: Dessalines <tyhou13@gmx.com>
2023-12-20 09:11:58 -05:00
Nutomic 2b9d89057d
Reenable crates.io releases (fixes #4291) (#4294)
* Reenable crates.io releases (fixes #4291)

* disable docker release for now

* fixes

* fix indent

* move to top

* install libssl

* -y

* apt update

* debian version

* install cargo, git

* use cargo install

* move to orig position
2023-12-20 08:18:54 -05:00
Felix Ableitner 08b7e0f03d Version 0.19.1-rc.2 2023-12-20 10:32:51 +01:00
Dessalines 7f780376bc
Add end software patents bagde (#4296)
* Adding End software patents badge.

Context: https://github.com/LemmyNet/joinlemmy-site/issues/283

* Smaller badge.

* Smaller badge 2.

* Smaller badge 3.
2023-12-19 19:59:48 -05:00
Nutomic a507a39336
Add missing test cleanup (#4289)
* Add missing test cleanup

* cleanup
2023-12-19 05:26:00 -05:00
Dessalines 2899ba0131
Fixing broken post_read logic. Fixes #4290 (#4297) 2023-12-19 10:46:41 +01:00
Dessalines 8583a85607 Version 0.19.1-rc.1 2023-12-18 14:20:42 -05:00
phiresky 6790b54d4d
make activity channel infallible (#4295) 2023-12-18 13:17:10 -05:00
dullbananas dcb89f52d6
Don't update comment_aggregates if updating path fails (#4281) 2023-12-18 10:31:39 +01:00
Dessalines bc32b408b5
Fixing private message reports. (#4279) 2023-12-18 10:25:05 +01:00
Dessalines aab3ca4eb0 Version 0.19.0 2023-12-15 06:53:26 -05:00
dullbananas a7ba5c9dd3
Sort by post id in post view (#4270)
* Sort by post id in post view

* Remove tie_breaker

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
Co-authored-by: Nutomic <me@nutomic.com>
2023-12-15 06:42:28 -05:00
Nutomic 7a182c982b
Debug random test failure (#4275) 2023-12-15 12:28:08 +01:00
Dessalines 719b76a6e7
Create comment in transaction. Fixes #3741 (#4265)
* Create comment in transaction. Fixes #3741

* Removing if let on comment create.
2023-12-15 11:36:58 +01:00
Dessalines 246e38a45b
Making login case-insensitive. Fixes #4272 (#4273)
* Making login case-insensitive. Fixes #4272

* Removing redundant lowercase.
2023-12-15 11:34:17 +01:00
Dessalines e4b97ad8a9
Revert "Minor CI improvements (#4266)" (#4271)
This reverts commit af4d008ce4.
2023-12-14 18:36:33 -05:00
Dessalines 70530a8ad2
Optimizing sql format check. (#4268)
* Optimizing sql format check.

* Fixing format testing.

* Fixing format testing 2.
2023-12-14 11:35:52 -05:00
Nutomic af4d008ce4
Minor CI improvements (#4266)
* Speed up SQL formatting in CI with parallel processing

* mess up formatting

* check permissions

* make repo world writable

* need git

* use debian image

* apt update

* perl image for faster install

* fix format

* run restore cache in parallel to format

* add drone-cache exit code

* revert sql format changes
2023-12-14 11:18:15 -05:00
Dessalines ac209d58b4
Adding a retry on a few fetches. (#4267) 2023-12-14 16:26:42 +01:00
Dessalines 59eef85bb7 Version 0.19.0-rc.16 2023-12-14 07:59:27 -05:00
Dessalines 442ec0b9f8
Upgrading lemmy-js-client to 0.19.0 (#4260) 2023-12-14 07:26:01 -05:00
Nutomic 4a55d4f871
Quick fix for Peertube federation (fixes #4261) (#4264)
* Quick fix for Peertube federation (fixes #4261)

* prettier

* apub assets should be included in slow check paths
2023-12-14 07:25:47 -05:00
phiresky 7353be5b68
federate-less-noisy (#4263) 2023-12-14 07:25:04 -05:00
dullbananas 32afc32bc0
Correctly combine sorts in post view cursor-based pagination (#4247)
* Update post_view.rs

* Update post_view.rs

* Update Cargo.toml

* Update post_view.rs

* fix

* Update post_view.rs

---------

Co-authored-by: SleeplessOne1917 <abias1122@gmail.com>
Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-12-14 07:10:01 -05:00
Nutomic 01aa17f38e
Reenable API tests that were accidentally skipped (#4259)
* Reenable API tests that were accidentally skipped

* log get comment parent id failure
2023-12-13 09:29:10 -05:00
Dessalines 0b2df3980f Version 0.19.0-rc.15 2023-12-13 09:24:24 -05:00
Nutomic 6626d35b98
Second attempt to make command line options more consistent (#4249)
Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-12-13 09:14:59 -05:00
Nutomic 60ffa2a599
Upgrade pictrs to 0.5.0-rc.2, remove cargo unstable flags (#4258) 2023-12-13 07:05:13 -05:00
dullbananas 5e589004a5
Add test for fixed deleted post filter (#4256)
* Add test for fixed deleted post filter

* fmt

* Fmt

* Update post_view.rs
2023-12-13 11:09:10 +01:00
dullbananas a0ef56b9b7
Remove moderator_view field from PostQuery (#4255) 2023-12-13 10:52:28 +01:00
Dessalines 93d123b46e
Fixing metadata endpoint. (#4257) 2023-12-13 10:50:51 +01:00
Dessalines 5ad881f3df Version 0.19.0-rc.14 2023-12-12 14:58:17 -05:00
dullbananas 3e2393993e
Update mod.rs (#4240)
Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-12-12 13:06:17 -05:00
SleeplessOne1917 8d52c7e7c7
See if different SQL query fixes performance regression (#4246)
* See if different SQL query fixes performance regression

* Fix formatting

* Hopefully fix failing federation test

* Hopefully solve federation test problem

* Use already-existing coalesce function

* Update person_view.rs

---------

Co-authored-by: SleeplessOne1917 <insomnia-void@protonmail.com>
Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
Co-authored-by: Nutomic <me@nutomic.com>
Co-authored-by: Dessalines <tyhou13@gmx.com>
2023-12-12 12:09:52 -05:00
Nutomic 30d58865b8
Speed up GET /api/v3/site endpoint (#4245)
* Make db queries for GET /api/v3/site in parallel (ref #4244)

* Cache site response

* machete

* Use try_join_with_pool macro

* machete

* taplo

* ttl 1s
2023-12-12 11:56:39 -05:00
Nutomic e0e74e50ae
Dont use test.png image for api tests (#4254) 2023-12-12 10:58:22 -05:00
Nutomic c7ee53026f
Upgrade dependencies (#4248)
* Upgrade dependencies

* clippy
2023-12-12 08:56:33 -05:00
Nutomic b2ae69f96c
Set explicit limit for getPosts/getComments in tests (#4250)
* Set explicit limit for getPosts/getComments in tests

* pretier
2023-12-12 08:54:54 -05:00
Nutomic 95130370f0
Add CI check for ignored files (#4252)
* Add CI check for ignored files

* remove ignored files
2023-12-12 08:54:06 -05:00
Dessalines f764996745
Show federated posts on user profile. Fixes #4228 (#4229)
* Show federated posts on user profile. Fixes #4228

* Make sure posts are hidden if no listing_type is given.
2023-12-11 14:36:12 -05:00
Nutomic e317947b75
Dont allow blocking local instance (fixes #4241) (#4242)
* Dont allow blocking local instance (fixes #4241)

* use localuserview
2023-12-11 14:35:53 -05:00
Nutomic cef3f220a2
Make command line options consistent (#4243) 2023-12-11 09:39:18 -05:00
Benjamin Barbeau 60849355db
Add voters to active users (#4235)
* Add voters to active users

* Edit formatting

* Edit formatting

* Edit formatting in down.sql

* Fix person table inner joins

* Remove post read from calculations
2023-12-11 09:38:17 -05:00
Kroese 2d4037ba61
Extend sitemap span (#4231)
* Extend sitemap span

* Keep cargo_fmt happy

* Add FETCH_LIMIT_SITEMAP

* Use FETCH_LIMIT_SITEMAP

* Keep cargo_fmt happy

* Update utils.rs

* Use SITEMAP_DAYS

* Keep cargo_fmt happy

* Sitemap

* Keep cargo_fmt happy

* Sitemap

* Sitemap

* Increase to 31 days
2023-12-11 11:24:51 +01:00
Dessalines c85e680aba Version 0.19.0-rc.13 2023-12-06 18:20:52 -05:00
Kroese 203ca9d617
Print version to log (#4226)
* Print version to log

* Keep cargofmt happy

* Keep cargo_fmt happy

* Keep Clippy happy
2023-12-05 11:35:59 -05:00
Nutomic a790a24c4d
Revert debug auth (#4232)
* Revert "Some changes to help debug auth problems on lemmy.ml (#4220)"

This reverts commit 16ac893e15.

* Rename auth cookie back to jwt
2023-12-05 11:22:08 -05:00
Nutomic de85e51fac
Dont set duplicate context for activities (#4233) 2023-12-05 11:19:12 -05:00
Nutomic a5386187e3
Enable missing code for prometheus actix-web stats (#4230)
* Enable missing code for prometheus actix-web stats

* enable middleware conditionally
2023-12-04 09:53:53 -05:00
Dessalines 3f79eacb53 Version 0.19.0-rc.12 2023-12-01 09:29:44 -05:00
Nutomic 16ac893e15
Some changes to help debug auth problems on lemmy.ml (#4220)
* Some changes to help debug auth problems on lemmy.ml

* fix

* clippy
2023-12-01 09:18:29 -05:00
Nutomic d7376d9541
Fix cors_origin wildcard (fixes #4214) (#4221) 2023-12-01 09:16:55 -05:00
Nutomic 809fc05cb3
Only allow distinguishing own comments (fixes #4216) (#4222) 2023-12-01 09:16:22 -05:00
Dessalines 70003407a7 Version 0.19.0-rc.11 2023-11-30 05:02:18 -05:00
Dessalines 170b3ec45f
Removing cookie secure check. (#4213) 2023-11-30 04:44:18 -05:00
Dessalines 7ef6476520 Version 0.19.0-rc.10 2023-11-29 10:04:42 -05:00
Dessalines e84f8f55a2
Remove httpOnly requirement. (#4212) 2023-11-29 09:58:35 -05:00
Dessalines 86990d5138
Registrations and Reports should sort by New when viewing unresolved / unread. (#4207)
- Fixes #4206
2023-11-29 11:08:23 +01:00
Dessalines 23b266ec12
Upgrade deps, fix issue with wrong diesel-async in Cargo.lock (#4211)
Co-authored-by: Nutomic <me@nutomic.com>
2023-11-29 11:06:34 +01:00
Dessalines a986db1a00
Fixing rust-analyzer suggestions on rss feeds. (#4210)
* Fixing rust-analyzer suggestions on rss feeds.

* Get rid of other pointless builders.

* More cleanup.
2023-11-29 11:00:06 +01:00
Bhoomtawath Plinsut 6fa3b59d25
Fix:#4197: validate post title must be shorter than 200 letters (#4198)
* validate post title must be shorter than 200 letters

* use range contains
2023-11-27 10:46:03 +01:00
dullbananas d95df3a46f
Update diesel-async (#4203)
* Update diesel-async

* Fix
2023-11-27 10:31:19 +01:00
Dessalines 7972dd0fcf Version 0.19.0-rc.8 2023-11-26 22:26:57 -05:00
Kroese fc07ba2d3b
Fix entrypoint in Dockerfile (#4202)
* Fix entrypoint

* Delete docker/builders/lemmy-builder-arm64/docker-build.sh

* Delete docker/builders directory

* Remove exception for builder

* Remove publish_builder_arm64
2023-11-26 16:50:31 -05:00
Enzo Nocera 8a05c8f8be
fix: Cross-compilation to ARM64 (#4142)
* feat(docker/docs): explain how building lemmy works

Signed-off-by: Enzo NOCERA <enzo@nocera.eu>

* feat: add arm build

* review: rename script & fix typo

* feat(ci): allow cross platform compilation

* feat(ci): prettier

* fix(docker): fix base image name

* fix: add dockerfile in CI path

Signed-off-by: Enzo Nocera <enzo@nocera.eu>

* fix(docker): fix runner name

* fix(docker): fix builder base image

* fix(docker): fix builder base image platform

* fix(docker): avoid using the wrapper adduser/addgroup

* feat: avoid adding the whole docker directory in the build context

---------

Signed-off-by: Enzo NOCERA <enzo@nocera.eu>
Signed-off-by: Enzo Nocera <enzo@nocera.eu>
Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
Co-authored-by: Nutomic <me@nutomic.com>
2023-11-24 12:52:19 -05:00
Nutomic 934fe7d1cb
Remove pictrs config section `old_db` (#4199)
* Remove pictrs config section `old_db` (ref #4194)

* ci

* remove cargo config comment

* ci

* Revert "remove cargo config comment"

This reverts commit 9389e936490ec1a82e5a51a61f61a576201479a8.

* rename .cargo to .cargo_home
2023-11-24 11:26:21 -05:00
Nutomic 7d489f1e3f
Upgrade pictrs to 0.5.0-beta.2 (#4194)
* Upgrade pictrs to 0.5.0-beta.2

* Update src/main.rs

Co-authored-by: asonix <asonix@asonix.dog>

* add comment

---------

Co-authored-by: asonix <asonix@asonix.dog>
2023-11-24 07:44:17 -05:00
Dessalines 2b5a31b411
Upgrading deps. (#4196)
* Upgrading deps.

* Try to use native node-fetch function.

* Fixing image upload tests.
2023-11-24 10:29:41 +01:00
Dessalines d795c54a7a Version 0.19.0-rc.7 2023-11-23 21:09:56 -05:00
Dessalines 6e4278b1c9
Setting rank column defaults to a small number. Fixes #4178 (#4191)
* Setting rank column defaults to a small number. Fixes #4178

* Fixing tests.
2023-11-23 20:39:46 -05:00
Nutomic 26297b4035
Users can view their own posts after removal (fixes #4186) (#4192) 2023-11-23 09:47:49 -05:00
Nutomic cafeb14f1c
Add API tests for purge user and purge post (#4183)
* Add API tests for purge user and purge post

* prettier

* fix test

* ci

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-11-22 10:15:06 -05:00
Dessalines 58258414cc Version 0.19.0-rc.6 2023-11-22 09:59:04 -05:00
Nutomic e58a167d64
Fix remote community posts appearing in local listing (fixes #4180) (#4181)
* Fix remote community posts appearing in local listing (fixes #4180)

* fmt

* fix typo
2023-11-22 09:41:52 -05:00
Nutomic 375e232217
Prevent purged user getting refetched from home instance (fixes #3815) (#4189) 2023-11-22 09:36:20 -05:00
Dessalines 9d4d6ce881
Removing yarn-error.log (#4185) 2023-11-22 09:34:15 -05:00
Dessalines 3e1f7f2efa
Adding `creator_is_admin` to `PersonView`, `CommentView`, and `PostView`. (#4165)
* Adding creator_is_admin to PersonView, CommentView, and PostView.

* Removing left joins from comment_view.

* Removing joins from person_mention and comment_reply views.

* Removing extra left join from person_view.

* Reverting some changes in post_view.

* Fixing compile error.
2023-11-21 11:20:24 -05:00
Dessalines 28d779a960
Fixing issue with mods not being able to view reports. Fixes #4172 (#4174)
* Fixing issue with mods not being able to view reports. Fixes #4172

* Addressing PR comments.
2023-11-21 16:33:49 +01:00
Nutomic 7ba1d98915
Prevent random test failure (#4184) 2023-11-21 10:08:19 -05:00
Nutomic 49377c195e
Fix deleted posts so they can only be seen by creator (#4182) 2023-11-21 08:59:47 -05:00
dullbananas 30f7135f32
Use rust 1.74.0 in CI and move clippy lints to Cargo.toml (#4170)
* ci rust 1.74.0

* do it

* Update .woodpecker.yml

* Update Cargo.toml

* Update lint.sh

* Update lib.rs

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-11-21 08:51:22 -05:00
Nutomic 62357f4444
Fix banning of remote user (fixes #4169) (#4171) 2023-11-21 08:44:55 -05:00
Dessalines 82b30b5467
Adding Selectable and diesel postgres backend check. (#4175) 2023-11-21 08:42:28 -05:00
cetra3 1c03a86c17
Upgrade activitypub to `0.5.0-beta.5` (#4179)
* Remove anyhow test

* Update lock

* Fix lints hopefully!
2023-11-21 10:26:12 +01:00
Nutomic f786df151f
Include instance blocks in settings export (#4173) 2023-11-17 21:59:15 -05:00
Nutomic 25450ea090
Fix following local communities stuck on pending (fixes #4160) (#4161)
* Fix following local communities stuck on pending (fixes #4160)

* fmt

* remove import

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-11-17 04:55:26 -05:00
İsmail Karslı 2070381e81
Add upload_timeout to PictrsConfig (#4159)
* Add upload timeout to PictrsConfig

* Bad space 🤔

* Update PictrsConfig upload timeout to include units.
2023-11-17 04:01:32 -05:00
Nutomic 525359f7c5
Add api tests for image endpoints (#4150)
* Add api tests for image endpoints (fixes #4105)

* curl instead of wget

* add missing files

* revert cargo update

* simplify setup

* use const

* rename to image.spec.ts

* adjust to client changes

* update client lib

* remove todos, move import

* try to fix ci

---------

Co-authored-by: SleeplessOne1917 <insomnia_void@protonmail.com>
2023-11-16 23:43:40 -05:00
Dessalines 7cb20200d8 Version 0.19.0-rc.5 2023-11-16 23:30:09 -05:00
Nutomic fc56d0aa05
Use result instead of unwrap in apub tests (#4168) 2023-11-16 22:51:33 -05:00
SleeplessOne1917 e573010202
Fix report count endpoint error (#4167) 2023-11-16 08:50:15 -05:00
Nutomic a00313e680
Merge `/site_inbox` into `/inbox`, remove unique constraint for inboxes (#4138)
* Merge /site_inbox into /inbox (fixes #4137)

Get rid of different inboxes, only use /inbox

Remove shared_inbox_url db columns

add code migration

move to db migration, fixes

machete

fix sql

drop inbox url unique constraints

Dont create auth cookie in backend (#4136)

dont change individual inboxes to shared inbox

Dont send comment reply to user who has community blocked. Fixes #3684 (#4096)

* Dont send comment reply to user who has community blocked. Fixes #3684

* Adding source instance block check.

* Adding api test.

* Addressing PR comments.

* move site inbox rewrite to db

* fix test

* clippy

* clippy 2

* fix test
2023-11-16 14:22:40 +01:00
Dessalines a53892d2bb
Fixing an issue with timezone migration. (#4153) 2023-11-16 14:19:31 +01:00
Dessalines e2bf2ce530
Removing show_new_post_notifs. (#4158) 2023-11-15 10:20:01 +01:00
Nutomic 9a94a86363
Fix cors wildcard (ref #4095) (#4156)
* Fix cors wildcard (ref #4095)

* cleanup

* clippy
2023-11-14 09:39:13 -05:00
Dessalines 28c30cc502
Adding skip_serializing_none to federation state. (#4152) 2023-11-14 08:20:44 -05:00
Dessalines 907e0ce726
Removing one other cache_remote_images. (#4151) 2023-11-14 11:09:35 +01:00
Nutomic 1d23df37d8
Rename cache_remote_images setting to cache_external_link_previews (ref #4035) (#4148) 2023-11-13 09:19:09 -05:00
dullbananas 8e2cbc9a0f
Remove id column and use different primary key on some tables (#4093)
* post_saved

* fmt

* remove unique and not null

* put person_id first in primary key and remove index

* use post_saved.find

* change captcha_answer

* remove removal of not null

* comment_aggregates

* comment_like

* comment_saved

* aggregates

* remove "\"

* deduplicate site_aggregates

* person_post_aggregates

* community_moderator

* community_block

* community_person_ban

* custom_emoji_keyword

* federation allow/block list

* federation_queue_state

* instance_block

* local_site_rate_limit, local_user_language, login_token

* person_ban, person_block, person_follower, post_like, post_read, received_activity

* community_follower, community_language, site_language

* fmt

* image_upload

* remove unused newtypes

* remove more indexes

* use .find

* merge

* fix site_aggregates_site function

* fmt

* Primary keys dess (#17)

* Also order reports by oldest first (ref #4123) (#4129)

* Support signed fetch for federation (fixes #868) (#4125)

* Support signed fetch for federation (fixes #868)

* taplo

* add federation queue state to get_federated_instances api (#4104)

* add federation queue state to get_federated_instances api

* feature gate

* move retry sleep function

* move stuff around

* Add UI setting for collapsing bot comments. Fixes #3838 (#4098)

* Add UI setting for collapsing bot comments. Fixes #3838

* Fixing clippy check.

* Only keep sent and received activities for 7 days (fixes #4113, fixes #4110) (#4131)

* Only check auth secure on release mode. (#4127)

* Only check auth secure on release mode.

* Fixing wrong js-client.

* Adding is_debug_mode var.

* Fixing the desktop image on the README. (#4135)

* Delete dupes and add possibly missing unique constraint on person_aggregates.

* Fixing clippy lints.

---------

Co-authored-by: Nutomic <me@nutomic.com>
Co-authored-by: phiresky <phireskyde+git@gmail.com>

* fmt

* Update community_block.rs

* Update instance_block.rs

* Update person_block.rs

* Update person_block.rs

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
Co-authored-by: Nutomic <me@nutomic.com>
Co-authored-by: phiresky <phireskyde+git@gmail.com>
2023-11-13 08:14:07 -05:00
SleeplessOne1917 1dc6c60760
Make import and export settings endpoints reachable (#4143)
* Make import and export settings endpoints reachable

* Preserve original routes
2023-11-13 08:08:07 -05:00
Dessalines e00b0c9da2
Dont send comment reply to user who has community blocked. Fixes #3684 (#4096)
* Dont send comment reply to user who has community blocked. Fixes #3684

* Adding source instance block check.

* Adding api test.

* Addressing PR comments.
2023-11-09 12:03:25 +01:00
Nutomic aaaf17486d
Dont create auth cookie in backend (#4136) 2023-11-08 07:55:09 -05:00
Dessalines 7a30a75905
Fixing the desktop image on the README. (#4135) 2023-11-07 11:05:12 +01:00
Dessalines 98ed0e51cc
Only check auth secure on release mode. (#4127)
* Only check auth secure on release mode.

* Fixing wrong js-client.

* Adding is_debug_mode var.
2023-11-07 11:03:13 +01:00
Nutomic cb01427dcf
Only keep sent and received activities for 7 days (fixes #4113, fixes #4110) (#4131) 2023-11-06 16:17:53 -05:00
Dessalines 97a4fb9a72
Add UI setting for collapsing bot comments. Fixes #3838 (#4098)
* Add UI setting for collapsing bot comments. Fixes #3838

* Fixing clippy check.
2023-11-06 16:09:12 -05:00
phiresky b9b65c9c18
add federation queue state to get_federated_instances api (#4104)
* add federation queue state to get_federated_instances api

* feature gate

* move retry sleep function

* move stuff around
2023-11-06 16:07:04 -05:00
Nutomic 8c85f35b19
Support signed fetch for federation (fixes #868) (#4125)
* Support signed fetch for federation (fixes #868)

* taplo
2023-11-06 16:02:01 -05:00
Nutomic cf788334aa
Also order reports by oldest first (ref #4123) (#4129) 2023-11-06 05:29:30 -05:00
Dessalines adef3479c0 Version 0.19.0-rc.4 2023-11-03 10:02:30 -04:00
Dessalines eeec56c22d
Adding creator_is_moderator to CommentReplyView and PersonMentionView. (#4126) 2023-11-03 14:41:00 +01:00
Nutomic 1e59e7ab47
Show oldest registration applications first (ref #4122) (#4123)
* Show oldest registration applications first (ref #4122)

* fix tests
2023-11-02 07:38:46 -04:00
Nutomic df53d2a0e8
Change logout endpoint to return SuccessResponse (#4121) 2023-10-31 08:41:52 -04:00
Nutomic 9007d49324
Remove unused deps (#4111)
* Remove unused deps

* Adding cargo-machete to woodpecker.

---------

Co-authored-by: Dessalines <tyhou13@gmx.com>
2023-10-31 11:11:12 +01:00
Dessalines c11e9446c6
Fix hot_rank algorithm pushing downvoted content off the feed. (#4085)
* Fix hot_rank algorithm pushing downvoted content off the feed.

- Max hot_rank algorithm now uses max(2, score) rather than greatest(1, score + 3)
- Fixes #4084

* Fixing SQL format.

* Adding 2 to bias the positive scores.
2023-10-30 10:47:57 +01:00
Nutomic 08739e2925
Move usage of env::var to lemmy_utils, simplify db init (ref #4095) (#4108) 2023-10-25 11:34:38 -04:00
Dessalines b63836b31b
Add link to githubs new issue button for security advisories. Fixes #3734 (#4107) 2023-10-25 16:50:56 +02:00
Dessalines 1b751a8cac
Adding cors_origin to settings. Fixes #3665 (#4095)
* Adding cors_origin to settings. Fixes #3665

* Fix result to option.

* Forgot to update config defaults.

* Setting a cors origin doku default.

* Adding comments for CORS.
2023-10-25 16:46:34 +02:00
Dessalines 64b00ee850
Dont allow bots to vote. Fixes #3940 (#4100)
* Dont allow bots to vote. Fixes #3940

* Removing pointless function.
2023-10-25 10:14:12 -04:00
Nutomic 568233b062
Resolve federated objects from other instances via redirect (fixes #3129) (#4073)
* Resolve federated objects from other instances via redirect (fixes #3129)

* restore domain check using library change

* add test case, update apub lib

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-10-25 07:14:59 -04:00
Nutomic 45bed71c36
Include prometheus in default build, remove build feature (fixes #3558) (#4071)
Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-10-25 06:54:58 -04:00
Dessalines 766ca99fd5
Hide private messages from blocked users. (#4102)
- Also fixes the unread count calls for CommentReply and PrivateMessage.
- Fixes #3629
2023-10-25 12:01:40 +02:00
Dessalines bd9739b5b7
Upgrading deps. (#4103) 2023-10-25 05:32:21 -04:00
Dessalines 0b41ddca58
Fix issue with sending private messages to yourself. Fixes #3912 (#4099)
* Fix issue with sending private messages to yourself. Fixes #3912

* Fix clippy.
2023-10-25 05:09:10 -04:00
Dessalines c38dfdcd64
Disable ansi coloring in logs. Fixes #3975 (#4101) 2023-10-25 10:58:55 +02:00
Dessalines c0aee244e7
Hide public rss items for private instance. Fixes #3785 (#4097) 2023-10-25 10:41:52 +02:00
Dessalines 221365bc9a
Fix bug when leaving admin team, setting accepted application as true… (#4090)
* Fix bug when leaving admin team, setting accepted application as true. Fixes #3422

* Addressing PR comments.
2023-10-24 17:30:47 -04:00
Dessalines 2df21b9d83
Dont serialize karma. #3393 (#4089) 2023-10-24 17:26:09 -04:00
Nutomic d55bd2f2bc
Allow Arabic and Cyrillic usernames/community names (fixes #1764) (#4083)
* Allow Arabic and Cyrillic usernames/community names (fixes #1764)

* update comment
2023-10-24 16:25:52 -04:00
HackerNCoder 722d9efc13
Use starts_with for forbidden unicode (Fix #3888) (#4079)
* Use starts_with for forbidden unicode (Fix #3888)

* Require 3 visible chars in display name

* Run cargo fmt and scripts/lint

* Undo invisibly_starts_with_at

* Remove 3 min chars.count() check for display name
2023-10-24 16:57:40 +02:00
Dessalines 09a67472e7
Allow torrent magnet links as post urls. Fixes #3916 (#4092) 2023-10-24 16:48:00 +02:00
Dessalines 053dcf8c10
Fixing matrix id regex. Fixes #3431 (#4091) 2023-10-24 16:47:02 +02:00
Dessalines 5d48ee3dc8
Add creator_is_moderator to Comment and PostViews. Fixes #3347 (#4087)
* Add creator_is_moderator to Comment and PostViews. Fixes #3347

* Fixing community_moderator join.

* Addressing PR comments.
2023-10-24 08:37:03 -04:00
Dessalines 5540257b36
Fixing problem with SaveUserSettings, when either the Person or Local… (#4077)
* Fixing problem with SaveUserSettings, when either the Person or LocalUser update is null.

- Fixes #4076
- Also upgrading api_test deps

* Move function into test.
2023-10-24 11:20:23 +02:00
Dessalines 1596aee724
Adding /version route. Fixes #2914 (#4059)
* Adding /version route. Fixes #2914

* Using a simple version string.

* Use nginx rewriting to solve version.

* Forgot to remove version.

* Using an actix redirect.
2023-10-24 10:49:52 +02:00
Dessalines 5bfa4e9358
Make sure my_vote is consistently missing if not voted. Fixes #3197 (#4075)
* Make sure my_vote is consistently missing if not voted. Fixes #3197

* Fix clippy.

* Fix tests.
2023-10-23 12:40:29 -04:00
Nutomic 6235ff45b5
Return status 401 on logout with invalid auth (fixes #4081) (#4082)
* Return status 401 on logout with invalid auth (fixes #4081)

* format
2023-10-23 12:17:26 -04:00
Nutomic ec0a707110
Avoid using proxy for pictrs requests (fixes #3489) (#4072)
* Avoid using proxy for pictrs requests (fixes #3489)

* fmt
2023-10-20 11:09:34 -04:00
Nutomic dfc74835b1
Hide deleted user accounts, add tests for PersonView (fixes #3811) (#4070)
* Hide deleted user accounts, add tests for PersonView (fixes #3811)

* clippy
2023-10-20 10:01:29 -04:00
Dessalines 6bcb12b14f Version 0.19.0-rc.3 2023-10-19 20:34:48 -04:00
Dessalines 236c7e24fd
Making mark post read fields optional. (#4055)
* Making mark post read fields optional.

* Remove unecessary &

* Fix clippy.

* Addressing PR comments.

* serde(default)

* Revert "serde(default)"

This reverts commit d56afd3075a3baccb2b0eda1cc739406b83963aa.

---------

Co-authored-by: Felix Ableitner <me@nutomic.com>
2023-10-19 20:16:23 -04:00
Dessalines cae25486e4
Adding ts-rs directives for login_token. (#4063)
* Adding ts-rs directives for login_token.

* Fixing ts-rs derive.
2023-10-19 20:16:12 -04:00
Dessalines c1db65c6e5
Fix up convert more responses to SuccessResponse (#4066)
* Revert "Convert more responses to SuccessResponse. Fixes #2860 (#4058)"

This reverts commit 8deb4e5752.

* Removing purgeitem and deletecustomemoji response.

* Adding back in utils building.
2023-10-19 20:15:55 -04:00
Dessalines 8deb4e5752
Convert more responses to SuccessResponse. Fixes #2860 (#4058)
* Convert more responses to SuccessResponse. Fixes #2860

* Upgrading lemmy-js-client.
2023-10-19 13:21:05 -04:00
Nutomic 9ef28eb53b
Remove unused static (#4061) 2023-10-19 11:57:39 -04:00
dullbananas a14657d124
Refactor rate limiter and improve rate limit bucket cleanup (#3937)
* Update rate_limiter.rs

* Update mod.rs

* Update rate_limiter.rs

* Update rate_limiter.rs

* Update mod.rs

* Update scheduled_tasks.rs

* Shrink `RateLimitBucket`

* Update rate_limiter.rs

* Update mod.rs

* Update rate_limiter.rs

* Update rate_limiter.rs

* Update rate_limiter.rs

* Update rate_limiter.rs

* Update mod.rs

* Update rate_limiter.rs

* fmt

* Update rate_limiter.rs

* Update rate_limiter.rs

* Update rate_limiter.rs

* Update rate_limiter.rs

* Update rate_limiter.rs

* Update rate_limiter.rs

* Update rate_limiter.rs

* Update rate_limiter.rs

* Update rate_limiter.rs

* rerun ci

* Update rate_limiter.rs

* Undo changes to  fields

* Manually undo changes to RateLimitBucket fields

* fmt

* Bucket cleanup loop in rate_limit/mod.rs

* Remove rate limit bucket cleanup from scheduled_tasks.rs

* Remove ;

* Remove UNINITIALIZED_TOKEN_AMOUNT

* Update rate_limiter.rs

* fmt

* Update rate_limiter.rs

* fmt

* Update rate_limiter.rs

* fmt

* Update rate_limiter.rs

* stuff

* MapLevel trait

* fix merge

* Prevent negative numbers in buckets

* Clean up MapLevel::check

* MapLevel::remove_full_buckets

* stuff

* Use remove_full_buckets to avoid allocations

* stuff

* remove tx

* Remove RateLimitConfig

* Rename settings_updated_channel to rate_limit_cell

* Remove global rate limit cell

* impl Default for RateLimitCell

* bucket_configs doc comment to explain EnumMap

* improve test_rate_limiter

* rename default to with_test_config

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
Co-authored-by: Nutomic <me@nutomic.com>
2023-10-19 15:31:51 +02:00
Dessalines a675fecacd Version 0.19.0-rc.2 2023-10-17 14:13:44 -04:00
Nutomic 6d27bfed08
Handle invalid ban expires values (fixes #4045) (#4046)
* Handle invalid ban expires values (fixes #4045)

* Adding a few missing expire time checks. Fixing up time conversions. (#4051)

* Adding a few missing expire time checks. Fixing up time conversions.

* Increase settings export wait time.

* get rid of RemoveCommunity.expires

* fmt

* tests

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-10-17 13:25:35 -04:00
Nutomic d827af725a
List distinguished comments first (fixes #3843) (#4050)
* List distinguished comments first (fixes #3843)

* then_order_by

* Fixing assert.

* move line

* then

---------

Co-authored-by: Dessalines <tyhou13@gmx.com>
2023-10-17 13:22:50 -04:00
Nutomic 3a19af5215
Allow marking multiple posts as read in single api call (fixes #3963) (#4048)
* Allow marking multiple posts as read in single api call (fixes #3963)

* cleanup

* limit array length

* fix test

* review

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-10-17 12:35:51 -04:00
Nutomic 3f62135083
Add validate_auth api endpoint (fixes #3702) (#4049)
* Add validate_auth api endpoint (fixes #3702)

* clippy

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-10-17 11:25:48 -04:00
SleeplessOne1917 cf1c32d2ab
Enable animated avatars setting (#4040)
* feat: Add user setting for toggling avatar gif animations

* Add forgotten post listing mode option to settings form

* Fix compilation error

* Fix formatting

* Change name of column to be more general purpose

* Fix sql format.

* Fix comments

* Running format.

---------

Co-authored-by: Dessalines <tyhou13@gmx.com>
Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-10-17 10:52:34 -04:00
Nutomic 56322c75f0
Read community follower count from home instance (fixes #1440) (#4013)
* Read community follower count from home instance (fixes #1440)

* fmt

* prettier

* fix tests

* fmt

* rename fn

* fmt

* Run prettier

* increase timeout

* ci

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
Co-authored-by: Dessalines <tyhou13@gmx.com>
2023-10-17 10:34:38 -04:00
Nutomic 332e698336
Cleanup public api (#4047)
* Convert PersonSortType to purely internal

* Remove hot rank and other db optimizations from public api
2023-10-16 19:37:28 -04:00
Nutomic 6cfbb8fc3b
Remove empty API responses (#3993)
* Remove empty API responses

* also remove change password response

* fix invalidate

* Run clippy.

* Fixing api_test lints.

---------

Co-authored-by: Dessalines <tyhou13@gmx.com>
Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-10-16 12:36:53 -04:00
Nutomic 256ee61908
Ignore activities in remote communities without local followers (#4006)
* Ignore activities in remote communities without local followers (fixes #3568)

* x

* comments

* prettier

* fix api test

* fix test

* cleanup

* fix remaining test

* clippy

* decrease delay
2023-10-16 06:03:49 -04:00
Dessalines 3be56ef2e0
Trying to fix export ci, try 1. (#4038) 2023-10-16 12:01:59 +02:00
Nutomic 9e099726e6
Cleanup checks for community actions (fixes #2858, fixes #2868) (#4028)
* Cleanup checks for community actions (fixes #2858, fixes #2868)

* allow restoring deleted community

* review changes

* remove unneeded sql

* remove joins

* change mod log check
2023-10-13 09:48:18 -04:00
Nutomic 608bb6b1b4
Convert titles for posts from Mastodon to plaintext (fixes #3828) (#4033)
* Convert titles for posts from Mastodon to plaintext (fixes #3828)

* Fix prettier.

* Trigger build

* Convert titles for posts from Mastodon to plaintext (fixes #3828)

* Fix prettier.

* Fix sanizize.

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
Co-authored-by: Dessalines <tyhou13@gmx.com>
2023-10-12 20:36:02 -04:00
Dessalines 645bf21d54
Moving to debian-based docker image. Fixes #3972 (#4004)
* Moving to debian-based docker image. Fixes #3972

* Fix cargo.toml format.

* Try nightly rust for cargo_fmt.

* Trying to fix cargo build.

* Trying to fix cargo build 2.

* Trying to fix federation tests.

* Trying to fix federation tests 2.

* Trying to fix federation tests 3.

* Try to fix aarch 1.

* Try to fix aarch 2.

* Try to fix aarch 3.

* Removing aarch

* Adding tests back in.

* Adding ca-certs, and debian non-root user

* Commenting arm image building.

* Fix platform on runner.

* Version 0.19.0-beta.6
2023-10-11 11:57:05 -04:00
Maxime Poulin 3a1be8c041
Fix legacy pagination for Subscribed feed (#4030)
This is the fix suggested in #4019

I've manually tested both legacy pagination (`page=2&limit=20`) as well as the new pagination (`cursor_next=XXXXXXX&limit=20`) using the same endpoint as #4019, and both methods appear to work as expected.
2023-10-11 16:53:18 +02:00
Nutomic 291ff19718
Only sanitize strings when generating RSS feeds and emails (fixes #4003) (#4024)
* Only sanitize strings when generating RSS feeds and emails (fixes #4003)

* clippy

* fix test
2023-10-11 16:48:19 +02:00
Nutomic 6d7b38f4de
Implement user data import/export (#3976)
* Implement endpoints for user data import/export

* add test

* exclude avatar/banner

* increase import url count, add rate limit

* also export/import saved posts

* rate limit

* rename

* saved posts also exist

* rename routes

* fix test

* error handling

* clippy

* limit parallelism

* clippy

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-10-11 16:47:22 +02:00
Nutomic 6d1a7c8ae0
Wipe bio when user is banned with remove content (fixes #4012) (#4032) 2023-10-10 11:11:11 -04:00
Hamzah Mansour 6470ea81a7
add keyboard navigation setting (#3569)
Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
Co-authored-by: Dessalines <tyhou13@gmx.com>
2023-10-10 12:17:27 +02:00
Nutomic dc327652a5
Add db table for login tokens which allows for invalidation (#3818)
* wip

* stuff

* fmt

* fmt 2

* fmt 3

* fix default feature

* use Authorization header

* store ip and user agent for each login

* add list_logins endpoint

* serde(skip) for token

* fix api tests

* A few suggestions for login_token (#3991)

* A few suggestions.

* Fixing SQL format.

* review

* review

* rename cookie

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-10-09 12:46:12 +02:00
Nutomic b7d570cf35
Make input length checks consistent with HTML maxlength attribute (#4009)
* Make input length checks consistent with HTML maxlength attr (fixes #3688)

* ci

* Extricating min and max length checks (#4018)

* revert string change

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-10-05 16:39:07 -04:00
Dessalines a5b8583aab Version 0.19.0-beta.7 2023-10-05 16:01:12 -04:00
Nutomic 4bf9947153
Add comment to explain startup server (ref #4005) (#4022)
* Add comment to explain startup server (ref #4005)

* ci
2023-10-05 07:41:05 -04:00
Nutomic 0115613f90
Specify password length limits in error (fixes #3284) (#4007)
* Specify password length limits in error (fixes #3284)

* convert to comment
2023-10-05 07:40:22 -04:00
Nutomic 5ef4807d09
Dont create :latest docker tag (fixes #3996) (#4016)
* Dont create :latest docker tag (fixes #3996)

* ci

* Update .woodpecker.yml

Co-authored-by: Richard Schwab <mail@w.tf-w.tf>

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
Co-authored-by: Richard Schwab <mail@w.tf-w.tf>
2023-10-04 18:34:56 -04:00
Nutomic 6950dd90e5
Return HTTP status 503 to all requests during startup (fixes #3780) (#4005)
* Return HTTP status 503 to all requests during startup (fixes #3780)

* add message

* fmt

* remove err

* dont run startup server if http disabled

* ci
2023-10-04 18:19:58 -04:00
Nutomic 626c7ebc85
Handle empty reason for registration application denial (fixes #3485) (#4008)
* Handle empty reason for registration application denial (fixes #3485)

* clippy

* clippy
2023-10-04 15:20:22 +02:00
Nutomic 50b7322ff3
Mention max length for site name in config (fixes #3006) (#4010)
* Mention max length for site name in config (fixes #3006)

* ci
2023-10-04 15:09:25 +02:00
Dessalines 2dad29106a
Change RELEASES.md to link to join-lemmy.org news (#3997)
* Adding 0.18.5 Release notes.

* Linking to join-lemmy RELEASES dir instead.
2023-10-02 10:55:23 +02:00
Nutomic d45a2a6441
Increase timeout for image upload to 30s (fixes #3920) (#3998) 2023-09-29 11:20:14 -04:00
Nutomic 210c470ebd
Notify admin about registration application after email verification (fixes #3024) (#3995) 2023-09-28 10:06:45 -04:00
Nutomic 9bb99bec5e
Increase default database connections (fixes #3394) (#3994) 2023-09-28 09:56:39 -04:00
Dessalines 9275041f42 Version 0.19.0-rc.1 2023-09-26 23:01:19 -04:00
Nutomic 50589115e0
Fix federation of admin actions (fixes #3980) (#3988)
* Fix federation of admin actions (fixes #3980)

* clippy

---------

Co-authored-by: Dessalines <tyhou13@gmx.com>
2023-09-25 21:39:18 -04:00
SleeplessOne1917 9a9ece8fa4
Merge pull request #3982 from SleeplessOne1917/bearer-token
feat: Replace ad hoc auth header with internet standard bearer token auth header
2023-09-26 00:59:55 +00:00
SleeplessOne1917 1032cce065 Fix api test typo 2023-09-25 07:18:06 -04:00
SleeplessOne1917 bee6b7a1bb Update translations 2023-09-25 06:38:23 -04:00
SleeplessOne1917 13b20b0502 Address PR feedback 2023-09-25 06:37:45 -04:00
SleeplessOne1917 ed8dae99f1 Merge branch 'main' into bearer-token 2023-09-24 17:47:17 -04:00
SleeplessOne1917 e181f4f41d
Merge pull request #3965 from SleeplessOne1917/comment-fix
Display deleted or removed comments when they have children
2023-09-24 18:29:40 +00:00
SleeplessOne1917 6387ac07b3 Merge branch 'bearer-token' of https://github.com/SleeplessOne1917/lemmy into bearer-token 2023-09-22 21:48:47 -04:00
SleeplessOne1917 3a76a10931 chore: Run rust format 2023-09-22 21:48:27 -04:00
SleeplessOne1917 37655f0f18 chore: Run rust format 2023-09-22 21:39:03 -04:00
SleeplessOne1917 519e800b33 feat: Replace ad hoc auth header with internet standard bearer token
auth header
2023-09-22 21:26:27 -04:00
Dessalines b16661a17d
Merge branch 'main' into comment-fix 2023-09-21 11:20:49 -04:00
phiresky 24c98a726a
Merge pull request #3960 from LemmyNet/add_federation_worker_index
Fixing high CPU usage on federation worker recheck + fix federation tests. Fixes #3958
2023-09-21 16:40:04 +02:00
phiresky 9bcadadede fix after merge 2023-09-21 12:52:10 +00:00
phiresky fe40adfc39 fix after merge 2023-09-21 12:32:41 +00:00
phiresky 31f3677270 fix after merge 2023-09-21 12:01:22 +00:00
phiresky 5941dc2924 Merge remote-tracking branch 'origin/main' into add_federation_worker_index 2023-09-21 11:57:13 +00:00
phiresky 07ffdc3d53 Revert "Revert "re-remove lemmy logs""
This reverts commit 459d5a3726.
2023-09-21 11:45:43 +00:00
phiresky 2c283d90ca Revert "Revert "re-remove debug comments""
This reverts commit 6d519ef376.
2023-09-21 11:45:33 +00:00
phiresky dec25f9ee8 ensure overlap 2023-09-21 11:11:54 +00:00
phiresky 6d519ef376 Revert "re-remove debug comments"
This reverts commit ae37ca0137.
2023-09-21 11:07:36 +00:00
phiresky 459d5a3726 Revert "re-remove lemmy logs"
This reverts commit ac0c0c8856.
2023-09-21 11:07:20 +00:00
Nutomic f858d8cbce
Remove explicit auth params (#3946)
* Remove explicit auth params (ref #3725)

Only take auth via header or cookie. This requires a new version
of lemmy-js-client for api tests to pass.

* rework api_crud

* remove remaining auth params, move logic to session middleware

* fmt, fix test

* update js client

* remove auth param from api tests

* Pass auth as header

* add !

* url vars, setHeader

* cleanup

* fmt

* update

* Updating for new lemmy-js-client.

---------

Co-authored-by: Dessalines <tyhou13@gmx.com>
Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-09-21 06:42:28 -04:00
phiresky 7e8b973128 empty 2023-09-20 21:21:23 +00:00
phiresky f16aa9228d community fix 2023-09-20 21:00:30 +00:00
phiresky 1b7ab96887 wait until ban post removed 2023-09-20 20:26:00 +00:00
SleeplessOne1917 bb552d7659
Merge branch 'main' into comment-fix 2023-09-20 17:38:47 +00:00
phiresky ac0c0c8856 re-remove lemmy logs 2023-09-20 16:07:01 +00:00
phiresky 2dbaf67b7c
Merge branch 'main' into add_federation_worker_index 2023-09-20 18:06:44 +02:00
phiresky ae37ca0137 re-remove debug comments 2023-09-20 15:33:09 +00:00
phiresky a808d3208a use max(id) instead of seq max value to prevent uncommitted transactions from causing skipped activities 2023-09-20 14:57:18 +00:00
Nutomic 22608ae983
Rework the way 2FA is enabled/disabled (fixes #3309) (#3959)
* Rework the way 2FA is enabled/disabled (fixes #3309)

* postgres format

* change algo to sha1 for better compat

* review comments

* review

* clippy

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-09-20 10:49:54 -04:00
phiresky 3d649e1d3e remove synchronous federation flag 2023-09-20 14:22:17 +00:00
phiresky 1a0c866b51 logging temporary 2023-09-20 13:37:18 +00:00
Dessalines 77b2d236b9
Forgot to add ts export to pagination cursor. (#3971) 2023-09-20 15:28:56 +02:00
SleeplessOne1917 a866b3424d
Make local federated instances use comnpose file for build (#3968)
* Make local federated instances use comnpose file for build

* Remove commented out part of script
2023-09-20 09:14:51 -04:00
phiresky a61d564732 fix delete test 2023-09-20 13:07:36 +00:00
phiresky a59a94492d more debug log 2023-09-20 12:30:38 +00:00
phiresky 78a8a7b8b7 clippy 2023-09-20 11:41:34 +00:00
phiresky c792f46c59 more wait for 2023-09-20 11:38:12 +00:00
phiresky ae3b8f4f76 fix 2023-09-20 11:23:02 +00:00
phiresky 2e7d2d1956 wait for post api test function, better announce activity id 2023-09-20 11:23:02 +00:00
Nutomic 50f81cf157
User can block instances (fixes #2397) (#3869)
* User can block instances (fixes #2397)

* update comments

* review comments

* use route

* update

* add api test

* update tests

* fix

* fix test

* ci

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-09-20 11:56:13 +02:00
Dessalines 89b7c981f5
Fixing GetPostsResponse serialization. (#3967) 2023-09-20 11:49:26 +02:00
SleeplessOne1917 a57b116431 Merge branch 'comment-fix' of https://github.com/SleeplessOne1917/lemmy into comment-fix 2023-09-18 22:10:07 -04:00
SleeplessOne1917 553c5bda88 Update versions to correct version 2023-09-18 22:07:31 -04:00
Dessalines 3812c8bf81 Force update 2 2023-09-18 21:20:06 -04:00
Dessalines dc6dee61b9 Force update 2023-09-18 21:19:08 -04:00
SleeplessOne1917 671676d7e4 Remove unused import 2023-09-18 19:40:01 -04:00
SleeplessOne1917 c471692949
Merge branch 'main' into comment-fix 2023-09-18 19:31:46 -04:00
SleeplessOne1917 be961075c7 Do not filter removed and deleted comments on the backend 2023-09-18 19:31:12 -04:00
Dessalines c25734e4ca
Merge branch 'main' into add_federation_worker_index 2023-09-18 19:19:24 -04:00
Dessalines 8c419103b2 Fixing formatting. 2023-09-18 19:19:13 -04:00
Dessalines 4f85adc393
Merge branch 'main' into add_federation_worker_index 2023-09-18 19:16:49 -04:00
SleeplessOne1917 f93d08a147 Make moderators be able to see removed comments in communities they moderate 2023-09-18 19:09:17 -04:00
phiresky 990445bf84 tmp tail lemmy log 2023-09-18 21:08:17 +00:00
phiresky a19b1d2606 ci 2023-09-18 21:02:52 +00:00
phiresky afde8e7576 tweak more tests 2023-09-18 20:31:12 +00:00
phiresky dff54d5e39 tweak tests more 2023-09-18 19:58:20 +00:00
Apple Sheeple c05458adcd Sanitize registration application answer
Signed-off-by: Apple Sheeple <AppleSheeple@github>
2023-09-18 22:39:29 +03:00
Apple Sheeple 5fff7504e5 Reject registration application if sanitizing the username modifies it
This removes the possibility of using a mix of sanitized and
 non-sanitized values for `username` in code.

Signed-off-by: Apple Sheeple <AppleSheeple@github>
2023-09-18 22:39:20 +03:00
phiresky 7dd857e00b log result 2023-09-18 19:19:40 +00:00
phiresky 2f0ad53b60 wait longer for fed init 2023-09-18 18:39:09 +00:00
phiresky 9868065089 minor test improvement 2023-09-18 18:23:55 +00:00
phiresky d58e2e9db7 minor test improvement 2023-09-18 18:09:18 +00:00
phiresky 007f4f5319 wait on score 2023-09-18 17:30:02 +00:00
phiresky 954b3f443d fix wait 2023-09-18 17:28:23 +00:00
phiresky 9e886fba4a delay shorter 2023-09-18 16:49:55 +00:00
phiresky 88931227b0 Merge remote-tracking branch 'origin/main' into add_federation_worker_index 2023-09-18 16:45:23 +00:00
phiresky 943b960c32 fix waits after all follow actions 2023-09-18 16:29:08 +00:00
phiresky 48496599b2 ci 2023-09-18 15:45:39 +00:00
phiresky 27141553b6 fix after revert 2023-09-18 14:28:49 +00:00
phiresky 08401fc85f Revert "remove synchronous federation"
This reverts commit 2767ab4a6fed9aa8d197eda0c6a25a1d617d192d.
2023-09-18 14:25:35 +00:00
Apple Sheeple b431c9bdf9 Sanitize apub post body
Signed-off-by: Apple Sheeple <AppleSheeple@github>
2023-09-18 16:00:29 +02:00
phiresky 544d30f0d4
Fix Posts List Performance + cursor-based pagination (#3872)
* add token-based pagination + fast subscribed post view

* add migrations

* fix failing heuristic

* revert

* output pagination token as next_page, fix off-by-one, restructure

* more cleanup

* clean

* format sql

* fix comment

* fix tests

* e

* empty

* move last page thing

* restructure a bit for readability

* rename page_cursor

* update for scaled sort

* fix

* sql format

* fix

* get rid of macros

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-09-18 15:44:48 +02:00
SleeplessOne1917 7118200cab Use up to date default UI container for dev 2023-09-18 07:55:38 -04:00
SleeplessOne1917 6d02a9914c Update translation 2023-09-18 07:38:00 -04:00
SleeplessOne1917 05b1ebdc7c Fix comments created by ser not showing up 2023-09-18 02:59:59 -04:00
SleeplessOne1917 eab1862e9a Make deleted and removed comments show when they have childern 2023-09-17 23:38:07 -04:00
phiresky fc1f9c1ec3 ci 2023-09-15 22:06:55 +00:00
phiresky c86173577d fix export location 2023-09-15 15:51:31 +00:00
phiresky 7ee707e78b ci 2023-09-13 11:59:09 +00:00
phiresky b09ffa7197 instead of changing fed delays in debug mode, change them via env variable 2023-09-13 11:23:13 +00:00
phiresky dca43dcfd9 fix a bug where after an hour community follows would be overwritten completely by an incremental upgrade 2023-09-13 10:54:10 +00:00
Dessalines 4f1240487e Fixing high CPU usage on federation worker recheck. Fixes #3958 2023-09-12 15:54:49 -04:00
Alex Roman 6735a98d35
Async scheduler (#3949)
* fix: switch to async scheduler

* fix: pass context to scheduled tasks

* Merge remote-tracking branch 'upstream/main' into async-scheduler

* retrigger ci

* retrigger ci
2023-09-11 11:12:16 +02:00
phiresky 375d9a2a3c
Persistent, performant, reliable federation queue (#3605)
* persistent activity queue

* fixes

* fixes

* make federation workers function callable from outside

* log federation instances

* dead instance detection not needed here

* taplo fmt

* split federate bin/lib

* minor fix

* better logging

* log

* create struct to hold cancellable task for readability

* use boxfuture for readability

* reset submodule

* fix

* fix lint

* swap

* remove json column, use separate array columns instead

* some review comments

* make worker a struct for readability

* minor readability

* add local filter to community follower view

* remove separate lemmy_federate entry point

* fix remaining duration

* address review comments mostly

* fix lint

* upgrade actitypub-fed to simpler interface

* fix sql format

* increase delays a bit

* fixes after merge

* remove selectable

* fix instance selectable

* add comment

* start federation based on latest id at the time

* rename federate process args

* dead instances in one query

* filter follow+report activities by local

* remove synchronous federation

remove activity sender queue

* lint

* fix federation tests by waiting for results to change

* fix fed test

* fix comment report

* wait some more

* Apply suggestions from code review

Co-authored-by: SorteKanin <sortekanin@gmail.com>

* fix most remaining tests

* wait until private messages

* fix community tests

* fix community tests

* move arg parse

* use instance_id instead of domain in federation_queue_state table

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
Co-authored-by: SorteKanin <sortekanin@gmail.com>
2023-09-09 12:25:03 -04:00
Nutomic 3b67642ec2
Add ts(skip) attributes to fix js client code generation (#3952)
* Add ts(skip) attributes to fix js client code generation

* use feature flag
2023-09-08 08:35:58 -04:00
Dessalines 9785b20843
Adding a scaled sort, to boost smaller communities. (#3907)
* Adding a scaled sort, to boost smaller communities.

- Previously referred to as *best* .
- Fixes #3622

* Fixing scheduled task update.

* Converting hot_rank integers to floats.

* Altering hot_rank psql function to default to zero after a week.

* Setting scaled_rank to zero, where hot_rank is zero.

* Adding image_upload table.
2023-09-06 13:43:27 -04:00
SorteKanin 4121fc4d56
Include domain in errors (#3944) 2023-09-06 13:29:15 -04:00
SorteKanin 722027ce2e
Bump ts_rs version (#3947)
Co-authored-by: Nutomic <me@nutomic.com>
2023-09-06 13:04:24 -04:00
Nutomic 71d61138bc
Replace ammonia lib with manual html escaping (fixes #3774) (#3938)
* Replace ammonia lib with manual html escaping (fixes #3774)

* prettier

* clippy

* remove sanitize unit test

* fix tests

* fix schema
2023-09-06 10:56:26 -04:00
Anon fe3ebea95a
Add logging for pictrs uploads (#3927)
* Add logging for pictrs uploads

* cleanup
2023-09-06 09:13:30 -04:00
Dessalines 797d26fdf4
Change AddAdmin to use person_id instead of local_user_id (#3941)
- Front ends don't have easy access to local_user_id on moddable
  items like comments and posts.
2023-09-06 11:37:03 +02:00
Nutomic a0ea8dbc00
Auto resolve reports trigger (#3871)
* Revert "Automatically resolve report when post/comment is removed (#3850)"

This reverts commit f7f6766650.

* Automatically resolve reports using db trigger

* lint

* use mod log tables

* fix migration

* fix ci

* fix clippy
2023-09-05 05:35:10 -04:00
Nutomic 366d9d1e2e
Get rid of remaining Perform/SendActivity traits (fixes #3670) (#3926)
* Get rid of remaining Perform/SendActivity traits (fixes #3670)

* fix api tests

* ci
2023-09-05 05:33:46 -04:00
dullbananas a1a9c3e4c0
Make use of variables less redundant and inconsistent in distinguish.rs (#3932)
* Make use of variables less redundant and inconsistent in distinguish.rs

* fmt
2023-09-04 11:06:54 +02:00
dullbananas 5b5ac0f37d
Remove left joins and use only one call to select method in post_view.rs (#3865)
* Use same joins for read and list in post_view.rs

* fmt

* rerun ci

* rerun ci

* Update post_view.rs

* rerun ci

* rerun ci

* Update post_view.rs

* Use `exists`

* Update post_view.rs

* Update post_view.rs

* Update post_view.rs

* rerun ci

* Update post_view.rs

* person_id_join parameter

* rerun ci

* fmt

* Update post_view.rs

* rerun ci

* Update post_view.rs

* rerun ci

* fmt

* Update post_view.rs

* fmt

* Use into_sql

* Update post_view.rs

* Use inferred query source for BoxableExpression

* Update post_view.rs

* Update post_view.rs

* Update community.rs

* Update community.rs

* Update post_view.rs

* fmt

* Update community.rs

* Update community.rs

* Update community.rs

* Update community.rs

* Update community.rs

* Update post_view.rs

* Update community.rs

* fmt

* Update post_view.rs

* Update post_view.rs

* Update post_view.rs

* Update post_view.rs

* Update post_view.rs

* Update post_view.rs

* Update post_view.rs

* fmt

* Update post_view.rs

* Update post_view.rs

* fix

* trigger ci

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
Co-authored-by: phiresky <phireskyde+git@gmail.com>
2023-09-04 11:05:00 +02:00
Nick Webster a57658d99c
Adding a new config flag to disable pictrs caching for thumbnails (#3897)
* add logic to prevent downloading remote pictrs images

* apply formatting

* Do not attempt a pictrs fetch if the remote image is also on a pictrs instance

* Do not attempt a pictrs fetch if the remote image is also on a pictrs instance and cache_federated_images is false

* Generalising the no caching option to handle all remote images

* rustfmt

* Return None if the URL is not an image

* Updating defaults.hjson

* fixing typo

* Fixing typo

* Skip cloning the Url unless we need to

* using a HEAD request for checking the content type, saving bandwidth/improving perf

* Removing early returns

* Switching back to GET requests for Content-Type because pictrs does not handle HEAD requests

* Simplifying logic and using metadata_image instead of url if we do not get a pictrs thumbnail

* Removing unused import

* Return None as a thumbnail if caching is disabled

* formatting

---------

Co-authored-by: Djones4822 <david.jones4822@gmail.com>
2023-08-31 10:36:39 -04:00
dullbananas 15930cbf4d
Use Queryable instead of JoinView (#3917)
* Update utils.rs

* Update traits.rs

* Update comment_report_view.rs

* Update comment_view.rs

* Update local_user_view.rs

* Update post_report_view.rs

* Update post_view.rs

* Update private_message_report_view.rs

* Update private_message_view.rs

* Update registration_application_view.rs

* Update site_view.rs

* Update structs.rs

* Update comment_reply_view.rs

* Update community_block_view.rs

* Update community_follower_view.rs

* Update community_moderator_view.rs

* Update community_person_ban_view.rs

* Update community_person_ban_view.rs

* Update community_view.rs

* Update person_block_view.rs

* Update person_mention_view.rs

* Update person_view.rs

* Update structs.rs

* Update admin_purge_comment_view.rs

* Update admin_purge_community_view.rs

* Update admin_purge_person_view.rs

* Update admin_purge_post_view.rs

* Update mod_add_community_view.rs

* Update mod_add_view.rs

* Update mod_ban_from_community_view.rs

* Update mod_ban_view.rs

* Update mod_feature_post_view.rs

* Update mod_hide_community_view.rs

* Update mod_lock_post_view.rs

* Update mod_remove_comment_view.rs

* Update mod_remove_community_view.rs

* Update mod_remove_post_view.rs

* Update mod_transfer_community_view.rs

* Update structs.rs

* Update utils.rs

* Update private_message_view.rs

* Update comment_report_view.rs

* Update registration_application_view.rs

* Update utils.rs

* fix

* fix db_views

* fix

* Update comment_view.rs
2023-08-31 15:26:10 +02:00
Ellie bd3f39973f
Add ARM64 Docker image support (#3810)
* Add ARM64 Docker image support

* Fix

* Fix Docker build

* Fix typo

* Use OpenSSL 3 and PostgreSQL Lib v15 in Docker builder

* Use simple comments in Dockerfile

* Add comment explaining Docker image cross build

* Move docker step above tests for testing

* Move docker build step back to normal position

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-08-31 09:02:59 -04:00
Dessalines 56e26fc3d4
Adding a post_view mode. Fixes #3730 (#3731)
* Adding a post_view mode. Fixes #3730

* Fix test.

* Addressing PR comments.

* Adding a post_view mode. Fixes #3730

* Fix test.

* Addressing PR comments.

* Fixing column order.

* Fix default Ok returns.

* Removing return Err(... where feasible.
2023-08-31 09:01:08 -04:00
Nutomic fed6542055
Implement remote follow (#3738)
* Add remote follow url to webfinger response

* update apub lib
2023-08-31 09:00:41 -04:00
biosfood 384e55f0e4
update moderator view (#3820)
* update api tests for new moderator view

* chage moderator view to be a listing type in get posts

Note: Internally, the listing type is called ListingType.ModeratorView,
but it's called "Moderator View" in the api endpoint

* fix formatting

* add support for moderator view to list comments

* add api test for moderator view when listing comments

* fix api test formatting

* retry tests

* don't filter out blocked users and communities when using moderator view

* fix cargo tests failing

* fix formatting

* fix previous merge

* Adding ModeratorView to listing_type_enums

* Fixing fmt.

* Adding a default to ListingType.

* Upgrading to use new lemmy-js-client.

---------

Co-authored-by: Nutomic <me@nutomic.com>
Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
Co-authored-by: Dessalines <tyhou13@gmx.com>
2023-08-31 13:07:45 +02:00
Lukas Trombach c93bde9799
replace `expect` with `ErrorUnauthorized` (#3915)
Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-08-29 19:08:44 -04:00
Nutomic b2aee565f3
Allow passing auth via header or cookie (#3725)
* Allow passing auth via header or cookie

* revert submodule

* taplo

* fix build

* working

* convert apub api methods

* also set cache-control header

* opt

* clippy

* deduplicate code, ignore invalid auth

* clippy

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-08-29 10:47:57 -04:00
Nutomic 7fd14b3d2a
Make remove content optional during account deletion (fixes #1617) (#3817)
* Make remove content optional during account deletion (fixes #1617)

* simplify purge params by passing context

* update js client

* add delete content

* update woodpecker config

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-08-28 12:23:45 +02:00
Lukas Trombach 26d125cc63
Sitemap - use UTC time (#3914)
* change local filter to use `eq` function

* use Utc time for sitemap
2023-08-28 11:09:20 +02:00
phiresky 514f2222e0
Fix time zone handling (#3496)
* convert naive time to utc time

* compounding fixes

* cargo fmt

* fix the rest

* fix down migration

* fix migrations

* fix after merge

* clippy fix

* ap-fed 0.5.0

---------

Co-authored-by: Nutomic <me@nutomic.com>
2023-08-24 11:27:00 -04:00
Nutomic 6047257bfc
Move admin flag from person to local_user (fixes #3060) (#3403)
* Move admin flag from person to local_user (fixes #3060)

The person table is for federated data, but admin flag can only
apply to local users. Thats why it really belongs in the local_user
table. This will also prevent the federation code from accidentally
overwriting the admin flag

* fmt

* try to fix api tests

* lint

* fix person view

* ci

* ci

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-08-24 05:40:08 -04:00
Freakazoid182 51ccf318e8
Lowercase domain on db query filters (#3849) (#3873)
* Lowercase domain on db query filters (#3849)

* Add test to get a community on different cased domain (#3849)

* Lowercase the identity for webfinger (#3849)

* Lowercase both sides of the domain comparison (#3849)

* Format api_tests (#3849)

* Lowercase domain lookup on Instance and Person (#3849)

---------

Co-authored-by: Freek van Zee <freek.van.zee@mediamonks.com>
Co-authored-by: Freakazoid182 <>
2023-08-22 11:10:21 -04:00
Lukas Trombach 28324ad2c8
Sitemap (#3808)
* generate sitemap.xml file

* set up endpoint for sitemap

* Update sitemap generation

- remove sitemap generation from scheduled tasks
- add posts query for sitemap
- create sitemap module in API crate

* remove priority and change freq from sitemap

* add configuration option for number of posts for sitemap

* fix default config

* rate limit sitemap endpoint

* update sitemap query

* update sitemap generation

- remove config value for query limit
- adjust sitemap generation to query changes
- tidy up error handling

* refactor sitemap generation loop

* remove `limit` argument

* refactor `generate_urlset` and add unit test

* change query to only fetch local posts of past 24h

* fix outdated comment and log

* cargo fmt
2023-08-22 10:30:15 -04:00
Alex Roman ab828b81e4
fix: add client connect timeout to scheduled task (#3883) 2023-08-21 10:53:35 +02:00
Freakazoid182 ee7b35a04a
Add person name to PersonIsBannedFromSite error (#3786) (#3855)
* Add person name to PersonIsBannedFromSite error (#3786)

* Log PersonId instead of Person name (#3850)

* Log actor_id for PersonIsBannedFromSite (#3850)

---------

Co-authored-by: Freek van Zee <freek.van.zee@mediamonks.com>
2023-08-16 11:36:58 +02:00
Freakazoid182 c8063f3267
Replace Option<bool> with bool for PostQuery and CommentQuery (#3819) (#3857)
* Replace Option<bool> with bool for PostQuery and CommentQuery (#3819)

* Replace Option<bool> from all list queries (#3819)

---------

Co-authored-by: Freek van Zee <freek.van.zee@mediamonks.com>
2023-08-11 11:13:14 +02:00
Maarten Vercruysse 9b710a2ed3
Update .woodpecker.yml use steps instead (#3858) 2023-08-10 08:15:30 -04:00
Dessalines 654bc513ea
Fixing woodpecker env var. (#3854) 2023-08-09 11:14:09 +02:00
Dessalines 29869b132c
Adding 0.18.4 Release notes. (#3853) 2023-08-09 11:08:32 +02:00
Nutomic f7f6766650
Automatically resolve report when post/comment is removed (#3850)
* Automatically resolve report when post/comment is removed

* also handle apub removes
2023-08-08 11:19:55 -04:00
Nutomic ae438e148e
Speedup CI (#3852)
* Speedup CI

* run tests in parallel

* restore cp

* main push

* no self update

* parallel format
2023-08-08 10:35:03 -04:00
Nutomic 33b2d67be6
Reorder woodpecker config to avoid ci failures (#3851) 2023-08-08 13:09:27 +02:00
dullbananas 969f8b2ce9
Replace TypedBuilder with Default in update forms (#3814)
* Update comment.rs

* Update community.rs

* Update local_site.rs

* Update local_site_rate_limit.rs

* Update local_user.rs

* Update person.rs

* Update comment.rs

* Update community.rs

* Update local_site.rs

* Update local_site_rate_limit.rs

* Update local_user.rs

* Update post.rs

* Update private_message.rs

* Update site.rs

* Update post.rs

* Update person.rs

* Update private_message.rs

* Update comment.rs

* Update create.rs

* Update leave_admin.rs

* Update update.rs

* Update remove.rs

* Update add_admin.rs

* Update verify_email.rs

* Update mod.rs

* Update mod.rs

* Update undo_delete.rs

* Update undo_delete.rs

* Update utils.rs

* Update feature.rs

* Update delete.rs

* Update lock.rs

* Update create.rs

* Update approve.rs

* Update update.rs

* Update lock_page.rs

* Update block_user.rs

* Update delete.rs

* Update undo_block_user.rs

* Update collection_remove.rs

* Update post.rs

* Update hide.rs

* Update person.rs

* Update remove.rs

* Update post_view.rs

* Update create.rs

* Update remove.rs

* Update collection_add.rs

* Update community.rs

* Update update.rs

* Update post_aggregates.rs

* Update update.rs

* Update comment.rs

* Update code_migrations.rs

* Update registration_application_view.rs

* Update update.rs

* Update ban_person.rs

* Update community.rs

* Update delete.rs

* Update delete.rs

* Update delete.rs

* Update person_aggregates.rs

* Update save_settings.rs

* Update distinguish.rs

* Update mark_read.rs

* Update site_aggregates.rs

* Update create.rs

* Fix

* rerun ci

* Update comment.rs

* rerun ci

* Update create.rs

* Update create.rs

* Update post_view.rs

* rerun ci

* Update undo_delete.rs

* rerun ci
2023-08-08 11:41:41 +02:00
dullbananas a47b12bbde
Reduce amount of columns selected (#3755)
* PostAggregatesNotInPost

* CommentAggregatesNotInComment

* CommunityPersonBanAdditionalInfo (partial)

* Revert "CommunityPersonBanAdditionalInfo (partial)"

This reverts commit 158f7f0cd9a07392fb1f457ac43c8d7c57e4190d.

* Replace some nullable parts of selection with id::nullable().is_not_null()

* CommunityFollower::select_subscribed_type

* WithoutId

* Add WithoutId derives

* Update Cargo.toml

* rerun ci

* Fix syntatx errors

* rerun ci

* Add missing "|" in private_message_report_view.rs

* rerun ci

* cargo fmt

* rerun ci

* Only derive WithoutId for Community with "full" feature

* rerun ci

* Fix attribute filtering in WithoutId macro

* rerun ci

* Update without_id.rs

* rerun ci

* Update without_id.rs

* rerun ci

* Fix errors

* rerun ci

* cargo fmt

* Fix errors

* rerun ci

* Move WithoutId to lib.rs

* rerun ci

* Remove macro_use for paste

* rerun ci

* Update comment_reply_view.rs

* rerun ci

* Update registration_application_view.rs

* rerun ci

* Revert "Update registration_application_view.rs"

This reverts commit 2e98e4bb8385b4630ed2d1dfdd8da9a35c0126b2.

* Revert "Update comment_reply_view.rs"

This reverts commit 857bf9f5a2413ff0e6e6c95e1157e8ce6bf9c0c3.

* Revert "Remove macro_use for paste"

This reverts commit 13247279ed9090f2d3c5c6525b9611529217d605.

* Revert "Move WithoutId to lib.rs"

This reverts commit 0c23e5213be1366bb64029e2007e97194e126676.

* Revert "Fix errors"

This reverts commit a283d155e5622bba0b6df8b07649fc246df8bb77.

* Revert "cargo fmt"

This reverts commit 36a5210352809b3ca417ec3b869ae4baaca17e16.

* Revert "Fix errors"

This reverts commit c9102c14f466a5d6175732625e74183579ee2be5.

* Revert "Update without_id.rs"

This reverts commit 19adb2fcc805f92f6720a439f3b2c80a2b866938.

* Revert "Update without_id.rs"

This reverts commit e26107a2fe30cc2ec81797830e3a34a1676619e4.

* Revert "Fix attribute filtering in WithoutId macro"

This reverts commit acaa4902b0e7e33205c5d287cd22b83732a1a401.

* Revert "Only derive WithoutId for Community with "full" feature"

This reverts commit de0e9c6fdc3c9344998d9d72e5e361a7f009c829.

* Revert "cargo fmt"

This reverts commit 5e1bd1ce58e997e9431f212fd2ee0283faaf6da3.

* Revert "Add missing "|" in private_message_report_view.rs"

This reverts commit c7ae9f1cd50dfead0fbc363d93692f82274ff870.

* Revert "Fix syntatx errors"

This reverts commit d942f099de8128b5a02fe74f5af43a4453a06350.

* Revert "Update Cargo.toml"

This reverts commit 23cdb6f6d3df6d2db06173f066c117a0c96dd8e1.

* Revert "Add WithoutId derives"

This reverts commit 06006d6ad338e946410962f4276f67fe5096ad5a.

* Revert "WithoutId"

This reverts commit 5e86922b0fd5bf08d114a8eee5d1e10b2ea534ee.

* Revert "CommentAggregatesNotInComment"

This reverts commit 603aede7cecacd246664f7f3f0047202f80d9938.

* Revert "PostAggregatesNotInPost"

This reverts commit 1ee3fcaeab8705e4e0e849ae6b93b45716aa9cc0.

* Restore original position of options.saved_only filter

* rerun ci

* Update post_view.rs

* rerun ci
2023-08-08 11:41:10 +02:00
Piotr Juszczyk 2ad3450004
Allow filtering posts and comments by whether they were liked/disliked - fixes #3401 (#3523)
* Allow filtering posts and comments by whether they were liked/disliked

* Switch to 2 args - liked_only, disliked_only - taking bools

* Make liked_only and disliked_only Option<bool>

* Fix unrelated is_profile_view compilation error
2023-08-08 11:40:28 +02:00
Alex Lavallee f9c2ba1cfa
Allow filtering PMs by sender (#3770)
* Allow filtering PMs by sender

* Fix retreiving own messages when filtering pm creator id

* Add tests

* Undo rename

* Fix PM tests

* Fix formatting for PMs

* Fix PM test formatting

* Rename PM creator_id field

* Fix PM formatting
2023-08-08 11:07:41 +02:00
Felix Ableitner 91c024fd98 Revert "Version 0.18.4-rc.2"
This reverts commit 48466b6826.
2023-08-07 17:12:09 +02:00
Felix Ableitner 48466b6826 Version 0.18.4-rc.2 2023-08-07 17:09:10 +02:00
maxime.io d81fb987aa
Fix sanitize_html whitespaces (#3829) 2023-08-07 14:22:52 +02:00
Felix Ableitner bed9474cf0 Revert "Attempt to fix CI building wrong commits (#3830)"
This reverts commit 5e9930bdcc.
2023-08-07 13:19:07 +02:00
dullbananas 5e9930bdcc
Attempt to fix CI building wrong commits (#3830)
* Attempt to fix CI building wrong commits

* Update .woodpecker.yml

* Update .woodpecker.yml
2023-08-07 06:40:50 -04:00
Dessalines 57cb5637fc
Fix ordering when doing a comment_parent type `list_comments` (#3823)
* Fix ordering when doing a comment_parent type GetPost.

* Fix missing options.
2023-08-07 11:11:07 +02:00
Nutomic 66ac8100d9
Remove unused db view options (#3787)
* Remove unused db view options

* fix tests

* ci
2023-08-04 11:36:36 -04:00
Nutomic 2bb24c2859
Remove form_id params (#3812) 2023-08-04 09:22:43 -04:00
Maarten Vercruysse da031a4ce2
Update QUESTION.yml, remove UI (#3807) 2023-08-03 05:12:21 -04:00
Dessalines 70fae9d68d
Fixing broken SQL migration formatting. (#3800)
* Fixing SQL format.

* Fixing clippy lints.

* Fixing clippy lint 2.
2023-08-03 11:07:35 +02:00
Nutomic 2d0f77af59
Dont use sha hash for password reset token (fixes #3491) (#3795) 2023-08-02 13:02:53 -04:00
Nutomic 27be1efb74
Rewrite remaining federation actions, get rid of PerformCrud trait (#3794)
* Rewrite ban actions

* Rewrite delete/remove actions

* Rewrite remove/delete community

* Rewrite report actions

* Rewrite feature/lock post

* Rewrite update community actions

* Rewrite remaining federation actions

* Get rid of PerformCrud trait

* clippy
2023-08-02 12:52:41 -04:00
Dessalines be1389420b
Adding SQL format checking via `pg_format` / pgFormatter (#3740)
* SQL format checking, 1.

* SQL format checking, 2.

* SQL format checking, 3.

* SQL format checking, 4.

* SQL format checking, 5.

* Running pg_format

* Getting rid of comment.

* Upping pg_format version.

* Using git ls-files for sql format check.

* Fixing sql lints.

* Addressing PR comments.
2023-08-02 12:44:51 -04:00
RocketDerp b4380cb548
Do not hide read posts when it is a user profile view (#3791) 2023-08-02 12:31:28 -04:00
Nutomic 58388f2ce8
Only run slow CI checks for actual code changes (attempt 2) (#3759)
* Only run slow CI checks for actual code changes (attempt 2)

* use when path include

* change rust

* update

* x

* y

* zsad

* remove println

* fmt

* readme

* Revert "readme"

This reverts commit d58b6ad9731d8c6009d8680d0126d9e9f0af3103.

* ci

* gitmodules
2023-08-02 12:29:21 -04:00
Louis GERARD 7bc64ab91a
Remove follow community traits (#3737)
* chore(FollowCommunity): remove Perform and Send Activity traits

* chore(FollowCommunity): avoid fetching community and person from db
2023-08-02 11:32:16 +02:00
dullbananas 91834d0d21
Default imprementations for read and delete in Crud trait (#3707)
* h

* Start doing stuff

* Default impl for Crud::read

* Simplify Crud::read lifetimes

* fmt

* Stuff

* Stuff

* Successfully make default read implementation work

* Restore Person::read

* Clean up default Crud::read and rename 'query2

* Replace filter with find

* Attempt default Crud::create

* Change Crud to Crud<'a> (won't compile)

* Revert "Change Crud to Crud<'a> (won't compile)"

This reverts commit 7ed20f5f713600bd48c85aad0848d8dbaae56503.

* Default Crud::delete

* Remove Crud::delete definitions that match default

* Remove commented Site::read

* Insert trait

* Revert "Insert trait"

This reverts commit 9d780c24035d3a9fb12968d3009a28724046dc3a.

* Use non-borrowed forms

* Revert "Use non-borrowed forms"

This reverts commit d2dd4425634b54ef105aab44f1c37cc10a32491e.

* Revert "Revert "Change Crud to Crud<'a> (won't compile)""

This reverts commit 25a27165a8ef56495e9f605ac15c9924b101d1bf.

* Fix lifetime for everything except Crud::delete

* Fix Crud::delete

* Add comment about futures

* Attempt Crud::create

* Attempt separate CrudBounds

* Revert "Attempt separate CrudBounds"

This reverts commit 1b4ca321c3d2a1d045e2f4c542c593582e9c6d80.

* Try to fix Crud::create

* Move lifetime parameters to associated types

* Revert "Move lifetime parameters to associated types"

This reverts commit af1bc858ce5e1dacddc4bbded2da7e4b7237e237.

* Revert "Try to fix Crud::create"

This reverts commit eec238496c38127cbf3d542b7cfd57ec55622d1f.

* Revert "Revert "Attempt separate CrudBounds""

This reverts commit 1ec33ce5022c58a5ad079ed7f5c220fafe5f0a5f.

* Revert "Attempt separate CrudBounds"

This reverts commit 1b4ca321c3d2a1d045e2f4c542c593582e9c6d80.

* Revert "Attempt Crud::create"

This reverts commit 47e8071b6826f27e2a562680b4948c37dffa68cb.

* Revert "Add comment about futures"

This reverts commit b266b1465393995b3be51d5ba207d5249560884f.

* Revert "Fix Crud::delete"

This reverts commit 3abcce2eec55208993dd9c7c3e51cff83412d15a.

* Revert "Fix lifetime for everything except Crud::delete"

This reverts commit c1ad7a161bbc8495dbfb8b52073f35ae88519da6.

* Revert "Revert "Revert "Change Crud to Crud<'a> (won't compile)"""

This reverts commit 3129cd0fc302f34bc0aad59987b9d0eb1139076c.

* Clean up

* Update site.rs
2023-08-01 10:34:10 -04:00
Nutomic d82194cfe9
Rewrite some federation actions to remove Perform/SendActivity (ref #3670) (#3758) 2023-08-01 15:53:36 +02:00
RocketDerp 05a7fced65
Enhanced testing of comments. Validate reply notifications, mentions (#3686)
* shared.ts first test of getReplies

* comment testing now validates reply notifications and mentions, some code comment cleanup in other functions

* comments revised

* first use of getUnreadCount in testing

* test notification of new comment replies, clarify usage of getReplies

* killall moved earlier in bash script

* api-test jest run does not need directory prefix, make consistent with other jest runs

* do not put my testing system password into script

* fix, killall exits script when no process found

* killall now moved to parent script to release locks before database create

* need to run killall a second time, before database drop

* first use of getReplies getPosts saveUserSettings

* accidental duplication of functions, removed

* try to sync shared library with main

* Nutomic feedback: Better to rename the var instead of putting a comment which can easily get outdated.

* Correct logic to meet join-lemmy requirement, don't have closed signups. Allows Open and Applications. (#3761)

Co-authored-by: Josh Bernardini <josh.bernardini@cologix.com>

* Fix fetch instance software version from nodeinfo (#3772)

Fixes #3771

* remove unused code, revert killall change

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
Co-authored-by: figure-0e <133478007+figure-0e@users.noreply.github.com>
Co-authored-by: Josh Bernardini <josh.bernardini@cologix.com>
Co-authored-by: Denis Dzyubenko <denis@ddenis.info>
Co-authored-by: Felix Ableitner <me@nutomic.com>
2023-08-01 09:14:40 -04:00
Denis Dzyubenko 55e383ae38
Fix fetch instance software version from nodeinfo (#3772)
Fixes #3771
2023-08-01 10:55:28 +02:00
figure-0e 6ed2ddf76d
Correct logic to meet join-lemmy requirement, don't have closed signups. Allows Open and Applications. (#3761)
Co-authored-by: Josh Bernardini <josh.bernardini@cologix.com>
2023-08-01 10:40:42 +02:00
Felix Ableitner 963d04b352 Revert "Only run slow CI checks for actual code changes (#3750)"
This reverts commit a34e0d477e.
2023-07-28 22:44:45 +02:00
Nutomic 543bd99900
Update CODEOWNERS (#3748) 2023-07-28 11:16:18 -04:00
Nutomic 39752fa096
Delete migrations_testing folder (#3751)
Its completely unused as far as I can see
2023-07-28 11:14:26 -04:00
Nutomic e365d48769
Move entry from .rgignore to .gitignore (#3752)
rg command respects gitignore, and sql dumps should be ignored by
git as well. So theres no reason to have a separate file.
2023-07-28 11:11:18 -04:00
Nutomic 37998b3398
Rewrite some API handlers to remove Perform trait (#3735)
* Rewrite some API handlers to remove Perform trait

* Convert CreateComment

* ci
2023-07-28 10:39:38 -04:00
Dessalines db76c5b7ff
Adding 0.18.3 Release notes. (#3753) 2023-07-28 16:33:45 +02:00
Nutomic a34e0d477e
Only run slow CI checks for actual code changes (#3750)
* Only run slow CI checks for actual code changes

Its a waste of time to compile Rust and run tests when only
something like the readme was changed.

* also make cache restore/rebuild conditional

* remove unused condition
2023-07-28 09:33:23 -04:00
Nutomic 0e6fb08284
Restore markdown quotes after sanitize (#3708) (#3749) 2023-07-28 08:23:46 -04:00
dullbananas 9a5a13c734
Use same table join code for both read and list functions (#3663)
* Try stuff

* Revert "Try stuff"

This reverts commit 3da5f83a8b4928368bf58e0061091c270259a226.

* Revert "Revert "Try stuff""

This reverts commit 178bd43cac8c7674d30d2c285ed47ca0493ad659.

* Revert "Revert "Revert "Try stuff"""

This reverts commit b9f9a2316e7cd37082319608c606a1c7db057206.

* Revert "Revert "Revert "Revert "Try stuff""""

This reverts commit ccd498dd7228050ae05d2022e9106034fd4132f8.

* Try more stuff

* Add queries function

* Simplify queries function

* Move aliases to db_schema

* Revert "Move aliases to db_schema"

This reverts commit 69afed05c1807c3fef8d5b5872546fa22e60b4d0.

* Add ReadFuture and ListFuture

* Refactor queries function and add Queries struct

* Box futures in Queries::new

* Use from_tuple

* Add comment_view::queries and improve comment_report_view::queries

* Add local_user_view::queries

* Add post_report_view::queries

* Ad post_view::queries

* Add private_message_report_view::queries

* private_message_view, registration_application_view

* Use 'a in BoxedQuery

* comment_reply_view, community_view

* Change aliases to inline module

* person_mention_view

* person_view

* Use separate community_person_ban joins instead of including boolean literal in join-on clause

* Fix comment_view

* rerun ci
2023-07-28 10:36:50 +02:00
phiresky e315092ee3
remove n^2 part of person triggers, improve community aggregate trigger (#3739)
* remove n^2 part of person triggers, improve community aggregate trigger

* comment out comment_score tests since previously they only accidentally succeeded

* empty
2023-07-27 23:36:51 +02:00
phiresky 1253a2a0d5
remove performance-problematic and buggy duplicate site aggregates (#3732) 2023-07-27 23:35:53 +02:00
Nutomic d909f3455d
Change readme installation link (#3736)
Replaces https://github.com/LemmyNet/lemmy/pull/3551
2023-07-27 09:42:52 -04:00
RocketDerp 21a87ebaf2
Federation tests replication round1 - demonstrate absent replication of comment deletes (#3657)
* more robust test of unlike a comment, confirm replication to instance downstream from community home

* more robust 'delete a comment' test, confirm replication

* Far more robust "Report a comment" test. Many comments about situation, this is currently failing because gamma does not get the report

* typo and actually have Gamma comment check use gamma, not alpha

* prepare-drone-federation-test.sh has some more echo output and note about the LEMMY_DATABASE_URL format (#3651)

* Add http cache for webfingers (#3317)

* Add http cache for webfingers

* Remove the outgoing cache middleware & adjust the cache headers directive

* Use 1h & 3day cache header

* Update routes and adjust the cache headers location

* revert apub caching

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
Co-authored-by: Felix Ableitner <me@nutomic.com>

* Rewrite activity lists to fix delete federation (fixes #3625)

* Revert "typo and actually have Gamma comment check use gamma, not alpha"

This reverts commit 7dfb6ee0f4885da3a2d10316422f5b510772806c.

* Revert "Far more robust "Report a comment" test. Many comments about situation, this is currently failing because gamma does not get the report"

This reverts commit 7bd3b20ae08a64324029491ddb3ce4295ba16787.

* prettier TypeScript

* revised comments, as ResolveObject isn't using routine replication

* fmt

* fix api tests

* remove comment

---------

Co-authored-by: cetra3 <cetra3@hotmail.com>
Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
Co-authored-by: Felix Ableitner <me@nutomic.com>
2023-07-27 06:17:40 -04:00
Bao 2d7b416652
Omit local instance from federated instances list (#3712)
Co-authored-by: Nutomic <me@nutomic.com>
2023-07-27 12:12:18 +02:00
phiresky 9bfa86d162
add trigram index to search (#3719)
* add trigram index to search

* add community index
2023-07-27 12:11:00 +02:00
Nutomic 3471f3533c
Sanitize html (#3708)
* HTML sanitization in apub code

* Sanitize API inputs

* fmt

* Dont allow html a, img tags

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-07-26 14:01:15 -04:00
biosfood 2de994797e
Add moderator view parameter to list posts (#3176)
* add option to only show posts from moderated communities

* rename moderated_only to moderator_view and show blocked users in moderator view

* add test for moderator view

* bump lemmy-js-client version for moderation view tests

* fix yarn lockfile

* retry build

* Delete logfile

* retry checks

* remove unused select statement from list posts

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-07-26 13:51:11 -04:00
Pavlos Smith c890797b37
Add controversial ranking (#3205)
* Added controversy rank property to posts and comments, and ability to sort by it

* Triggers instead of schedules tasks, integer -> double, TODO: comments don't seem to get updated with floats, divide SortTypes

* Created PersonSortType

* PersonSortType::MostComments case

* Removed unused PartialOrd trait

* Added new person sort type mappings

* SortType -> PersonSortType

* fixes

* cargo fmt

* fixes after merge with main

* Fixed bug in controversy rank trigger, removed TopX sorts from PersonSortType and added CommentScore instead

* Uncovered enum case

* clippy

* reset translation changes

* translations

* translations

* Added additional hot ordering on controversial posts and comments

* featured local and featured community added to controversy rank index, additional order_by removed (?), added post_score and post_count to PersonSortType

* Woodpecker rerun

* cargo fmt

* woodpecker rerun

* fixed controversy_rank order

* fix

* Readded migration as latest, removed second update statement for setting controversy rank
2023-07-26 13:07:05 -04:00
marsara9 dc4572460e
Make resolve_object not require auth #3685 (#3716)
* Resolves issue #3685

If user isn't authenticated with resolve_object, only allow a local search instead of possibly making an http request.

* Making sure to validate auth before doing a potential remote lookup.
2023-07-26 12:17:42 -04:00
Nutomic afac3ee7ff
Skip fragile API tests (#3723)
* Skip fragile API tests

These tests fail very often for no reason, eg in #3712 and #3696.
Better to disable them until they can be fixed.

* killall -s1
2023-07-26 12:15:18 -04:00
Domenic Horner f9351b6512
UI Settings - Blur NSFW & Auto Expand (#3377)
* add new flag to api

* add new ui settings for local user

* remove extraneous def

* add props to application reg.

* fix clippy updated these

* re-order db schema entries

* remove dupe

* update lemmy sdk

* update lemmy js client

---------

Co-authored-by: Nutomic <me@nutomic.com>
2023-07-26 07:53:45 -04:00
dullbananas 9b123f45ec
Enable gzip for reqwest (#3696)
This will reduce bandwidth used by federation

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-07-26 12:22:14 +02:00
Into the V0id cf2229d665
Dont authenticate user after successful password reset #3714 (#3715)
Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-07-25 13:33:02 -04:00
Freakazoid182 9a1f9aad45
detailed error message for blocked domains (#3698) (#3701)
* detailed error message for blocked domains (#3698)

* Pass the domain as an error param

Not formatting the error message to support i18n

---------

Co-authored-by: Freek van Zee <freek.van.zee@mediamonks.com>
2023-07-25 13:26:54 -04:00
Ben Wyatt 95e758e707
Bump version of dependency "webmention" (#3711)
Webmention .4->.5 bumps a few internal dependencies that needed to be upgraded
2023-07-25 13:01:13 -04:00
phiresky 3b09d8c882
prevent ordering by comment path without post filter (#3717) 2023-07-25 12:46:00 -04:00
asimons04 13a866aeb0
Update Dockerfile to run process as non-privileged user. (#3709) 2023-07-24 09:51:51 -04:00
Nutomic 102124b6d2
Change logic for determining comment default language (fixes #3451) (#3672) 2023-07-21 09:08:25 -04:00
Joel Beckmeyer ea7f83c4dc
disable rustfmt feature on rosetta-build (#3679) 2023-07-21 11:50:47 +02:00
Dessalines e17f0097ff
Fix federation test errors with new lemmy-js-client (#3678) 2023-07-21 11:47:56 +02:00
Dessalines 417c4d2311
Adding diesel migration check. Fixes #3676 (#3677)
* Adding diesel migration check. Fixes #3676

* Fixing prettier.
2023-07-21 11:46:10 +02:00
Dessalines 623d81139e
Make sure comments are sorted by hot_rank, then score. (#3667) 2023-07-21 11:44:47 +02:00
Nutomic ccc122100e
Fix process shutdown (#3673)
I noticed that stopping the Lemmy process with ctrl+c wasnt working
because the activity channel isnt properly closed. This is now fixed.

Later we should also move the channel from static into LemmyContext,
Im not doing that now to avoid conflicts with #3670.
2023-07-20 11:36:48 -04:00
Nutomic 1a164a649e
Ignore errors when fetching community mods (fixes #3460) (#3674) 2023-07-20 11:34:07 -04:00
Nutomic 3753a3bf54
Upgrade activitypub library to 0.4.6 (fixes #3222) (#3675) 2023-07-20 11:33:19 -04:00
Sander Saarend b511c2e6cb
Denormalize community_id into post_aggregates for a 1000x speed-up when loading posts (#3653)
* Denormalize community_id into post_aggregates for a 1000x speed-up when loading posts

* Remove unused index

* Add creator_id to post_aggregates

* Use post_aggregates as main table for PostQuery

* Make post_aggregates the main table for PostView

* Reformat SQL
2023-07-20 11:13:21 -04:00
Dessalines ced3aa5bd8
Fixing hot_ranks and scores to append a published sort. (#3618)
- #3428
2023-07-20 16:44:23 +02:00
Nutomic 047db9ac85
Handle displaying of deleted and removed posts/comments (fixes #2624) (#3286)
* Handle displaying of deleted and removed posts/comments (fixes #2624)

* remove duplicate test

* fix tests

* no show_removed/show_deleted

* merge

* partially fix tests

* fix tests

* clippy

* fix tests

* get rid of build_post_response_deleted_allowed
2023-07-20 16:36:16 +02:00
Sander Saarend d7051c40f8
Use local_site.default_post_listing_type as the initial default listing type for new users (#3666) 2023-07-19 11:04:43 -04:00
Nutomic 5cd4c6c586
Dont publish releases to crates.io (fixes #3272) (#3664)
This is not needed anymore as from scratch installation now uses
`git clone` instead of `cargo install`.

https://github.com/LemmyNet/lemmy-docs/pull/241/files
2023-07-19 10:25:46 -04:00
Nutomic 5d23ef960e
Remove SendActivity and Perform traits, rely on channel (#3596)
* Remove SendActivity and Perform traits, rely on channel

These traits arent necessary anymore now that websocket is removed.
Removing them allows us to use normal actix http handler methods
which are much more flexible, and allow using different middlewares
as well as setting response attributes.

* compiling and create post federating

* clippy

* rename methods, join outgoing activities task

* fix api tests

* no unwrap

* conditional compile

* add back getrandom

* make crates optional

* fmt
2023-07-19 09:49:41 -04:00
Sander Saarend 77a8e3b897
Don't panic when scheduled tasks can't connect to database (#3634)
* Don't panic when scheduled tasks can't connect to database

* Use map & map_err instead of match

* Empty commit for Woodpecker re-run
2023-07-19 15:00:44 +02:00
cetra3 1f21bdb2f9
Add http cache for webfingers (#3317)
* Add http cache for webfingers

* Remove the outgoing cache middleware & adjust the cache headers directive

* Use 1h & 3day cache header

* Update routes and adjust the cache headers location

* revert apub caching

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
Co-authored-by: Felix Ableitner <me@nutomic.com>
2023-07-19 06:09:04 -04:00
RocketDerp 2adf7d5008
prepare-drone-federation-test.sh has some more echo output and note about the LEMMY_DATABASE_URL format (#3651) 2023-07-19 10:28:10 +02:00
RocketDerp 38c6210912
Post remove delete federation outbound fix0 (#3613)
* add new function build_post_response_deleted_allowed

* PostDelete uses new function build_post_response_deleted_allowed

* RemovePost uses new build_post_response_deleted_allowed function

* code comments about mod or admin flag having other use

* reformat "cargo +nightly fmt --all"
2023-07-17 11:07:45 -04:00
Ikko Eltociear Ashimine 0ada7dc889
Add Japanese README (#3620)
* Add Japanese README

* add translate

* fix link

* Update README.ja.md
2023-07-17 11:05:14 -04:00
cetra3 9256895635
Cache & Optimize Woodpecker CI (#3450)
* Try using drone cache plugin

* Try another path

* Include volume

* Fix formatting

* Include fmt

* Exclude cargo dir from prettier

* Don't override cargo

* Just do check

* Add cache key

* Use different cache plugin

* Add clippy

* Try minio

* Add quotes

* Try adding secrets

* Try again

* Again

* Use correct secret formation

* Add back clippy

* Use secret for the root bucket name

* Try drone cache instead

* Add region

* Add path-style option

* Include cargo clippy

* Include everything again

* Fix formatting

* Don't run clippy twice

* Add `allow` statements for tests to pass

* Adjust endpoint to be a secret

* Fix prettier

* Merge & fix tests

* Try to restart the woodpecker test

* Change the ENV var name

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-07-17 11:04:14 -04:00
dullbananas 88215bfbc9
Remove TypedBuilder from db_views and db_views_actor (#3637)
* change pool fields to parameters for list

* remove my_person_id and admin fields

* Change recipient id to list param

* Remove TypedBuilder from db_views and db_views_actor
2023-07-17 12:20:25 +02:00
Sander Saarend 6688a8a5d4
Optimize hot rank updates (#3617) 2023-07-17 11:05:55 +02:00
Nutomic e9e76549a8
Split activity table into sent and received parts (fixes #3103) (#3583)
* Split activity table into sent and received parts (fixes #3103)

The received activities are only stored in order to avoid processing
the same incoming activity multiple times. For this purpose it is
completely unnecessary to store the data. So we can split the
table into sent_activity and received_activity parts, where
only sent_activity table needs to store activity data. This should
reduce storage use significantly.

Also reduces activity storage duration to three months, we can reduce
this further if necessary.

Additionally the id columns of activity tables are removed because
they are completely unused and risk overflowing (fixes #3560).

* address review

* move insert_received_activity() methods to verify handlers

* remove unnecessary conflict line

* clippy

* use on conflict, add tests
2023-07-14 11:17:06 -04:00
phiresky 2938b50908
work around race condition on community fetch (#3414) 2023-07-14 14:57:36 +02:00
Dessalines 164f4b93d9
Make `lemmy_api_common` wasm-compatible (#3587)
* Fixing lemmy_api_common optionals

* Adding taplo for .toml files.

* Versioning taplo in woodpecker.

* Addressing PR comments.
2023-07-14 10:45:18 +02:00
Nutomic 39f28c1a40
Add dev profile to strip symbols and disable debug info (ref #3610) (#3611)
* Add dev profile to strip symbols and disable debug info (ref #3610)

This significantly speeds up builds:
- with strip symbols and debug 0: 43s
- without: 169s

* add comment, no strip symbols
2023-07-13 14:50:17 -04:00
Nutomic 7d8cb93b53
Check for dead federated instances (fixes #2221) (#3427)
* Check for dead federated instances (fixes #2221)

* move to apub crate, use timestamp

* make it compile

* clippy

* use moka to cache blocklists, dead instances, restore orig scheduled tasks

* remove leftover last_alive var

* error handling

* wip

* fix alive check for instances without nodeinfo, add coalesce

* clippy

* move federation blocklist cache to #3486

* unused deps
2023-07-13 16:12:01 +02:00
Manuel Bleichner c0b7865896
Fix wrong SMTP port when TLS is being used (fixes #3574) (#3607)
Co-authored-by: Manuel Bleichner <manuel.bleichner@bvu.de>
2023-07-13 13:10:14 +02:00
Nina Blanson 40ff77eee2
Add workaround for #3102 until cross-compile work complete (#3472)
* Add workaround for #3102 until cross-compile work complete

* Minor cleanup

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-07-13 13:02:08 +02:00
Jason Grim 8992965c0c
Updated Lemmy Matrix Support link (#3599) 2023-07-13 12:31:35 +02:00
nixoye 6310f55984
Update RELEASES.md (#3593)
replaced the confusing api_key line that's commented out with the line that is now used in the new config.hjson in /lemmy-ansible/examples

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-07-12 10:48:49 -04:00
Simon Bordeyne 9b5e765364
Add infinite scroll user option (#3572) 2023-07-12 09:12:01 -04:00
Nutomic c060546ffa
Use specific Rust nightly version for CI cargo fmt (fixes #3467) (#3577)
* Use specific Rust nightly version for CI cargo fmt (fixes #3467)

* fix

* fix
2023-07-12 11:15:28 +02:00
dullbananas 1d38aad9d3
Make functions work with both connection and pool (#3420)
* a lot

* merge

* Fix stuff broken by merge

* Get rid of repetitive `&mut *context.conn().await?`

* Add blank lines under each line with `conn =`

* Fix style mistakes (partial)

* Revert "Fix style mistakes (partial)"

This reverts commit 48a033b87f4fdc1ce14ff86cc019e1c703cd2741.

* Revert "Add blank lines under each line with `conn =`"

This reverts commit 773a6d3beba2cf89eac75913078b40c4f5190dd4.

* Revert "Get rid of repetitive `&mut *context.conn().await?`"

This reverts commit d2c6263ea13710177d49b2791278db5ad115fca5.

* Use DbConn for CaptchaAnswer methods

* DbConn trait

* Remove more `&mut *`

* Fix stuff

* Re-run CI

* try to make ci start

* fix

* fix

* Fix api_common::utils

* Fix apub::activities::block

* Fix apub::api::resolve_object

* Fix some things

* Revert "Fix some things"

This reverts commit 2bf8574bc8333d8d34ca542d61a0a5b50039c24d.

* Revert "Fix apub::api::resolve_object"

This reverts commit 3e4059aabbe485b2ff060bdeced8ef958ff62832.

* Revert "Fix apub::activities::block"

This reverts commit 3b02389abd780a7b1b8a2c89e26febdaa6a12159.

* Revert "Fix api_common::utils"

This reverts commit 7dc73de613a5618fa57eb06450f3699bbcb41254.

* Revert "Revert "Fix api_common::utils""

This reverts commit f740f115e5457e83e53cc223e48196a2c47a9975.

* Revert "Revert "Fix apub::activities::block""

This reverts commit 2ee206af7c885c10092cf209bf4a5b1d60327866.

* Revert "Revert "Fix apub::api::resolve_object""

This reverts commit 96ed8bf2e9dcadae760743929498312334e23d2e.

* Fix fetch_local_site_data

* Fix get_comment_parent_creator

* Remove unused perma deleted text

* Fix routes::feeds

* Fix lib.rs

* Update lib.rs

* rerun ci

* Attempt to create custom GetConn and RunQueryDsl traits

* Start over

* Add GetConn trait

* aaaa

* Revert "aaaa"

This reverts commit acc9ca1aed10c39efdd91cefece066e035a1fe80.

* Revert "Revert "aaaa""

This reverts commit 443a2a00a56d152bb7eb429efd0d29a78e21b163.

* still aaaaaaaaaaaaa

* Return to earlier thing

Revert "Add GetConn trait"

This reverts commit ab4e94aea5bd9d34cbcddf017339131047e75344.

* Try to use DbPool enum

* Revert "Try to use DbPool enum"

This reverts commit e4d1712646a52006b865a1fbe0dcf79976fdb027.

* DbConn and DbPool enums (db_schema only fails to compile for tests)

* fmt

* Make functions take `&mut DbPool<'_>` and make db_schema tests compile

* Add try_join_with_pool macro and run fix-clippy on more crates

* Fix some errors

* I did it

* Remove function variants that take connection

* rerun ci

* rerun ci

* rerun ci
2023-07-11 09:09:59 -04:00
dullbananas 73492af4b0
Shrink capacity in `RateLimitStorage::remove_older_than` (#3536)
* Shrink capacity in `RateLimitStorage::remove_older_than`

* Update rate_limiter.rs

* rerun ci

* rerun ci

* rerun ci

* Update rate_limiter.rs
2023-07-10 22:52:37 +02:00
Pawan Hegde ef9dc5d0b6
Fix #3366: Wrap plain-text error responses from the API in JSON (#3559)
* Fix #3366: API does return plain HTML errors

* Fix Clippy errors

* Improve api response times by doing send_activity asynchronously (#3493)

* do send_activity after http response

* move to util function

* format

* fix prometheus

* make synchronous federation configurable

* cargo fmt

* empty

* empty

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>

* Updating `login.rs` with generic `incorrect_login` response. (#3549)

* Adding v0.18.1 and v0.18.0 release notes. (#3530)

* Update RELEASES.md (#3556)

added instruction to find the location of your docker directory (especially useful for those who used ansible since they never had to setup docker manually)

* Use async email sender (#3554)

* Upgrade all dependencies (#3526)

* Upgrade all dependencies

* as base64

* Adding phiresky to codeowners. (#3576)

* Error enum fixed (#3487)

* Create error type enum

* Replace magic string slices with LemmyErrorTypes

* Remove unused enum

* Add rename snake case to error enum

* Rename functions

* clippy

* Fix merge errors

* Serialize in PascalCase instead of snake_case

* Revert src/lib

* Add serialization tests

* Update translations

* Fix compilation error in test

* Fix another compilation error

* Add code for generating typescript types

* Various fixes to avoid breaking api

* impl From<LemmyErrorType> for LemmyError

* with_lemmy_type

* trigger ci

---------

Co-authored-by: SleeplessOne1917 <abias1122@gmail.com>

* Only update site_aggregates for local site (#3516)

* Fix #3501 - Fix aggregation counts for elements removed and deleted (#3543)

Two bugs were found and fixed:
- previously elements removal and deletion were counted as two separate disappearances
- removing comments did not affect post aggregations

* Use LemmyErrorType also make error_type compulsory

* Add missing import for jsonify_plain_text_errors

* Fix formatting

* Trying to make woodpecker run again

---------

Co-authored-by: phiresky <phireskyde+git@gmail.com>
Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
Co-authored-by: rosenjcb <rosenjcb@gmail.com>
Co-authored-by: nixoye <12674582+nixoye@users.noreply.github.com>
Co-authored-by: dullbananas <dull.bananas0@gmail.com>
Co-authored-by: Nutomic <me@nutomic.com>
Co-authored-by: SleeplessOne1917 <abias1122@gmail.com>
Co-authored-by: Sander Saarend <sander@saarend.com>
Co-authored-by: Piotr Juszczyk <74842304+pijuszczyk@users.noreply.github.com>
2023-07-10 22:44:14 +02:00
Piotr Juszczyk 9c2490d4f2
Fix #3501 - Fix aggregation counts for elements removed and deleted (#3543)
Two bugs were found and fixed:
- previously elements removal and deletion were counted as two separate disappearances
- removing comments did not affect post aggregations
2023-07-10 11:30:30 -04:00
Sander Saarend 651f2747ee
Only update site_aggregates for local site (#3516) 2023-07-10 11:20:39 -04:00
Nutomic 93225e5ddf
Error enum fixed (#3487)
* Create error type enum

* Replace magic string slices with LemmyErrorTypes

* Remove unused enum

* Add rename snake case to error enum

* Rename functions

* clippy

* Fix merge errors

* Serialize in PascalCase instead of snake_case

* Revert src/lib

* Add serialization tests

* Update translations

* Fix compilation error in test

* Fix another compilation error

* Add code for generating typescript types

* Various fixes to avoid breaking api

* impl From<LemmyErrorType> for LemmyError

* with_lemmy_type

* trigger ci

---------

Co-authored-by: SleeplessOne1917 <abias1122@gmail.com>
2023-07-10 16:50:07 +02:00
Dessalines b50634e2cf
Adding phiresky to codeowners. (#3576) 2023-07-10 16:20:40 +02:00
Nutomic ff26bc21af
Upgrade all dependencies (#3526)
* Upgrade all dependencies

* as base64
2023-07-10 15:00:55 +02:00
dullbananas 934f72511e
Use async email sender (#3554) 2023-07-10 14:04:39 +02:00
nixoye 3dd2fd0f7f
Update RELEASES.md (#3556)
added instruction to find the location of your docker directory (especially useful for those who used ansible since they never had to setup docker manually)
2023-07-10 14:00:00 +02:00
Dessalines 9d52d8bd0b
Adding v0.18.1 and v0.18.0 release notes. (#3530) 2023-07-10 13:51:24 +02:00
rosenjcb e7e60e0514
Updating `login.rs` with generic `incorrect_login` response. (#3549) 2023-07-10 07:27:38 -04:00
phiresky b35757b429
Improve api response times by doing send_activity asynchronously (#3493)
* do send_activity after http response

* move to util function

* format

* fix prometheus

* make synchronous federation configurable

* cargo fmt

* empty

* empty

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-07-10 12:27:49 +02:00
Dessalines 0c82f4e660 Version 0.18.1 2023-07-07 09:24:49 -04:00
Dessalines c208faf276
Revert "Make sure hot rank sorts for post and community filter by positive hot ranks. (#3497)" (#3521)
This reverts commit 6840fd64f9.
2023-07-07 11:29:07 +02:00
phiresky aa70325c11
Make hot rank not crash on future (#3517)
* make hot rank zero for future

* parallel safe
2023-07-07 11:27:47 +02:00
Nutomic b3dfc3721f
Upgrade crossbeam-channel (#3512) 2023-07-06 14:21:11 -04:00
Dessalines 2a088cf023
Update prettier to 3.0.0 (#3509)
* Update prettier to 3.0.0

* Updating prettier dep.

* Explicity 3.0.0 version.
2023-07-06 15:10:38 +02:00
Felix Ableitner 22cdcc6b60 Version 0.18.1-rc.10 2023-07-06 14:46:46 +02:00
phiresky 922ee6a230
improve admin and mod check to not do seq scans and return unnecessary data (#3483)
* improve admin and mod check

* fix clippy

* move admin index to existing code

* Revert "move admin index to existing code"

This reverts commit d0c58d5f4021e1775d0c1d30d8df6c7df87557c4.

* third attempt at the migration

* fix formatting

* rebuild

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-07-06 14:44:26 +02:00
Nutomic 00f9f79a44
Only allow http(s) scheme for urls (ref #3505) (#3508)
With this change only http(s) schemes are allowed for post.url
field. This is checked for incoming api and federation requests.
Existing posts in database which are sent to clients are not
checked. Neither does it check urls in markdown.
2023-07-06 08:29:51 -04:00
Nutomic c12fedaf1b
Change security contact mail (#3506)
Old one isnt working apparently
2023-07-06 07:27:47 -04:00
Diamond 084f603745
Allow cross-origin requests (#3421)
Co-authored-by: pfg <pfg@pfg.pw>
2023-07-06 07:25:19 -04:00
Dessalines 6840fd64f9
Make sure hot rank sorts for post and community filter by positive hot ranks. (#3497)
* Make sure hot rank sorts for post and community filter by positive hot ranks.

- Context #2994

* Adding a comment.
2023-07-06 13:22:48 +02:00
Dessalines ef11a6ca37
Fixes wrong community moderator ordering. (#3495) 2023-07-06 12:27:25 +02:00
Nutomic ce1ffebeb0
Use fixed prettier version for CI (#3507)
3.0.0 was pushed to docker hub 2 hours ago, thats probably why
builds are breaking now.
2023-07-06 12:23:51 +02:00
phiresky 2158621bda
upgrade markdown-it to fix panic (#3490)
Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-07-05 13:08:53 -04:00
phiresky 45b1a0d4fb
improve performance of community followers inbox query (#3482)
* improve performance of community followers inbox query

* nightly format

* force woodpecker to retry

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-07-05 11:50:26 -04:00
Nutomic ebaf69bd70
Cache federation blocklist (#3486)
* Cache federation blocklist

* revert submodule change
2023-07-05 11:08:02 -04:00
Andrew Fields 1e99e8b9dc
Add Prometheus endpoint (#3456)
Add a server for serving Prometheus metrics. Include a configuration
block in the config file. Provide HTTP metrics on the API, along with
process-level metrics and DB pool metrics.
2023-07-05 13:25:19 +02:00
Dessalines 657c2e37c0
Adding a person.admin index, and featured_local/community indexes. (#3479) 2023-07-05 13:00:41 +02:00
Lemmus.org ff47d97bd3
Add feature for enabling json logging (#3462) 2023-07-04 07:11:47 -04:00
Louis GERARD 85dab149a9
fix(posts/comments/search): return error on invalid community name (#3418) 2023-07-04 13:04:38 +02:00
Josephos cdc5b47886
Improved validation of display names (Fixes #3436) (#3437)
* Fixed validation of display names

Fixed validation of display names: reject names beginning with invisible unicode characters.

* Formatting

Formatting fix.

* Expanded list of forbidden Unicode characters. Validation now checks for disallowed characters anywhere in the name.

* Formatting

* Added a comment detailing source of the list of invisible chars.
2023-07-04 12:41:58 +02:00
Dessalines 8bcf2ea7c9
Fixing clippy. (#3471) 2023-07-04 12:15:27 +02:00
Piotr Juszczyk bf62fbe644
Remove not needed anymore http-signature-normalization-actix dependency (#3458) 2023-07-04 12:14:37 +02:00
Dessalines f0e487f18a
300 comment limit. (#3306)
* 300 comment limit.

* Another fix.
2023-07-03 18:02:57 -04:00
Dessalines 7a04971ecd Version 0.18.1-rc.9 2023-07-03 17:16:48 -04:00
JP Moresmau bbca6ef6dc
Do not decrement comment score twice when removing then deleting. (#3196)
Fixes #3004

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-07-03 14:13:53 -04:00
perillamint 696cca4ce4
Remove excessive content_type header configuration (#3470) 2023-07-03 13:43:45 -04:00
Dessalines 935b0bf048
Adding rest of community sorts. Fixes #3374 (#3376)
* Adding rest of community sorts. Fixes #3374

* Addressing PR comments.
2023-07-03 13:09:15 -04:00
Nutomic e1494d4683
Dont compare db string errors (fixes #1393) (#3424)
* Dont compare db string errors (fixes #1393)

* cargo fmt

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-07-03 11:59:49 -04:00
Simon Bordeyne b8ee9315bc
Add Open links in new tab setting (#3318)
* Add Open links in new tab setting

* reorder because it fixes tests ?
2023-07-03 11:10:25 -04:00
David BELEY efe98158c0
Fix awesome-lemmy owner (#3469) 2023-07-03 16:44:55 +02:00
David BELEY 050216eed9
Add awesome-lemmy to LemmyNet? (#3413)
* Add LemmyNet/awesome-lemmy

* Delete other apps/projects from README.md
2023-07-03 15:15:45 +02:00
Nutomic cb91eedd24
Use serde(skip) instead of skip_serializing, add placeholder values (#3362)
* Use serde(skip) instead of skip_serializing

The latter breaks lemmy_crawler as the field is not included in
the Lemmy API, but is required when attempting to parse API responses.
Should only use serde(skip) to avoid this problem

* use option

* add placeholders

* no unwrap
2023-07-03 15:14:01 +02:00
Nutomic 6405761891
Mark follow as pending when subscribing to remote community (fixes #3384) (#3406) 2023-07-03 12:03:20 +02:00
Felix Ableitner fc60b82f82 Fix formatting for latest nightly (#ref 3467) 2023-07-03 11:45:53 +02:00
Nutomic 3578dab67f
Remove PerformApub trait (#3423)
* Remove PerformApub trait

This is completely useless now that websocket is gone. In the future
I also plan to remove Perform and PerformCrud traits, but it will be
difficult to do that while still compiling crates in parallel.

* params need to use query
2023-07-03 11:01:41 +02:00
drumlinish 682ca55e0c
Fix quoting of max-file in docker-compose.yml (#3442) 2023-07-03 10:59:07 +02:00
phiresky cb28af508d
don't strip, log trace if requested (#3425) 2023-06-30 09:32:43 -04:00
Lemmus.org 810762762f
Update federated posts to not cache sensitive images if not allow by local site (#3253)
* Update federated posts to not cache sensitive images if not allow by local site

* Refactor thumbnail match to simplify logic
2023-06-30 12:42:42 +02:00
Dominic Mazzoni fcc010b5dc
Fix concatenation of audio captcha wav files (#3350)
* Fix concatenation of audio captcha wav files

* Log errors rather than crashing

* Return Result from captcha_as_wav_base64

* Change to return LemmyError

* Check for wav write error, format

* Remove unused import

* Rewrite to avoid clippy warnings
2023-06-30 12:36:38 +02:00
dullbananas 7d3894d5dd
Automatically manage database when running scripts/test.sh (#3389)
* Update .gitignore

* Create start-dev-db.sh

* Rename start-dev-db.sh to start_dev_db.sh

* Update .gitignore

* Update start_dev_db.sh

* Update start_dev_db.sh

* Update start_dev_db.sh

* Update start_dev_db.sh

* h

* Update test.sh

* Update start_dev_db.sh

* made it work

* Make test.sh work when run from scripts dir
2023-06-30 09:50:30 +02:00
Dessalines 3159eedd99 Version 0.18.1-rc.4 2023-06-29 10:45:59 -04:00
Dessalines 6c64cb5233
Fixing release script. (#3398)
* Fixing release script.

* Version 0.18.1-rc.2

* Removing cargo update from release script.

* Fixing topdir location.
2023-06-29 16:17:59 +02:00
Nick Shockey 0464c46d26
Added gitattributes to normalize all files to lf (#3386)
This makes it less annoying to build on windows/mac

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-06-29 10:16:11 +02:00
Nutomic c216153dfb
Update activitypub-federation crate to 0.4.5 (#3379)
https://github.com/LemmyNet/activitypub-federation-rust/releases/tag/0.4.5
2023-06-28 12:58:23 -04:00
Sander Saarend ec18fd9869
Fix cargo warnings (#3397) 2023-06-28 12:57:49 -04:00
c-andy-candies ffc049078e
Fix missing sorting types (#3370)
* Fix missing sorting types

* Reordered sort_type_enum
2023-06-28 12:44:16 -04:00
Jan Klass 0f91759e4d
docs(api): Add api-common info on generating TypeScript bindings (#3330) 2023-06-28 11:25:46 +02:00
dullbananas bef76630c5
Remove redundant calls to `Iterator::collect` (#3365)
* Remove redundant calls to `Iterator::collect`

* Update mentions.rs

* Add clippy lints and run fmt

* CI ran on the wrong commit again 
2023-06-28 11:19:26 +02:00
Nutomic e4b739320c
Run cargo update as part of release script (#3369)
To get newest dependency patches and get rid of yanked deps

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-06-27 08:59:58 -04:00
Dessalines ad6f244b61 Version 0.18.1-rc.1 2023-06-27 08:14:46 -04:00
Nina Blanson e63aa80c3a
Fixes #2900 - Checks slur regex to see if it is too permissive (#3146)
* Fixes #2900 - Checks slur regex to see if it is too permissive along with small validation organization

* Clean up variable names, add handler for valid empty string usecase

* Update tests

* Create validation function and add tests

* Test clean up

* Use payload value vs local site value to prevent stunlocking

* Remove println added while testing

* Fall back to local site regex if not provided from request

* Attempt clean up of flaky comment_view tests

* Pull in latest submodule

* Move application, post check into functions, add more tests and improve test readability

---------

Co-authored-by: Nutomic <me@nutomic.com>
2023-06-27 07:03:30 -04:00
Domenic Horner d1d90af0eb
add new flag to api (#3363) 2023-06-27 06:45:26 -04:00
TKilFree 2aef6a5a33
feat: re-added captcha checks (#3289) 2023-06-27 06:38:53 -04:00
Sander Saarend 76a4513774
Limit password resets (#3344) 2023-06-27 11:20:53 +02:00
Dessalines 98482b1564
Fixing the release script. (#3295)
* Fixing the release script.

* Updating the submodules.
2023-06-27 10:28:56 +02:00
Sander Saarend 211e76dc27
Batch hot rank updates (#3175) 2023-06-27 10:13:51 +02:00
c-andy-candies f5209fffc1
Feature add three six and nine months options backend (#3226)
Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-06-26 15:03:35 -04:00
Nutomic 50efb1d519
Fetch community outbox and moderators in parallel (#3360)
This will speedup first time fetching of a remote community
2023-06-26 12:14:50 -04:00
Nutomic 8fbc630ce1
Remove networks from docker-compose.yml (#3356) 2023-06-26 12:10:38 -04:00
Simon Lundström c9e9ff46fa
Item URL should point to post URL (#3345)
If the post is an URL post the item link should point to the URL of the
link that is being posted.
2023-06-26 15:11:16 +02:00
Otto Rottier 62c8ac1db5
Site Metadata: resolve relative URLs for embedded images/videos (#3338)
* Site Metadata: resolve relative URLs for embedded images/videos

* api_common: relax version requirement of `webpage` dependency

With this change we opt into next (non breaking) versions of webpage-rs

* cargo +nightly fmt

* Add tests for resolving absolute urls in SiteMetadata
2023-06-26 15:07:57 +02:00
dullbananas b2a9d4a335
Use compression middleware (#3343) 2023-06-26 12:54:41 +02:00
Felix Ableitner 73d2faa9f5 Remove another unused dev dependency 2023-06-26 12:46:44 +02:00
cetra3 9406c3ad2b
Adjust the config check to be a separate faster to compile binary (#3313) 2023-06-26 06:23:21 -04:00
Felix Ableitner a39e948b52 Remove unused actix_rt dependency 2023-06-26 12:14:47 +02:00
wiki-me 83ff9adee5
Add Liftoff to README.md (#3357) 2023-06-26 12:12:38 +02:00
perillamint 3d7d6b2530
Respond with `Content-Type: application/activity+json` (#3353)
As per ActivityPub specification, the return type should be
`application/activity+json`, not `application/json`.
2023-06-26 12:10:04 +02:00
anonion 01dc1efe77
Fix lemmy UI environment variable (#3299) 2023-06-26 06:07:22 -04:00
Peter Dave Hello 2f3d60a63b
Leave no apk cache in Docker image (#3327) 2023-06-26 11:59:02 +02:00
Nutomic ddfa112e0b
Allow wildcard imports in schema.rs (#3293)
Dont mess with auto-generated code, this avoids problems with
clippy after running diesel commands
2023-06-26 11:18:29 +02:00
Scott c5886404ef
Update DB local_user.theme type to text (#3266)
* Update local_user.theme type to text

* fix default value

* Undo auto generate changes
2023-06-26 10:53:04 +02:00
TKilFree 21d5349785
feat: allow all admins to purge content (#3271) 2023-06-26 10:47:39 +02:00
Neshura 203e35899e
Add separate Post check for is_valid_body_field (#3263)
* Add separate Post check for is_valid_body_field

* Modify is_valid_body_check for posts only

* Fix check var reinit in validation.rs

* Extra empty line to rerun woodpecker with changes

* Change Option to bool, add false to non-post calls

* Woodpecker trick.. again

* Probable rust_fmt fail fixed

* cargo_clippy changes

* Missing space between = and if

* Remove ; after body length checks
2023-06-26 10:47:01 +02:00
Felix Ableitner 206789af67 Merge branch 'vijaykramesh_clear_deleted_posts_comments' 2023-06-26 10:45:49 +02:00
Felix Ableitner ce0cf0e41b Remove DELETED_REPLACEMENT_URL 2023-06-26 10:45:37 +02:00
Sander Saarend 6b28f8c616 Add support for sslmode=require for diesel-async DB connections (#3189) 2023-06-26 10:45:22 +02:00
cetra3 d6b580a530 Remove `actix_rt` & use standard tokio spawn (#3158)
* Remove `actix_rt` & use standard tokio spawn

* Adjust rust log back down

* Format correctly

* Update cargo lock

* Add DB settings

* Change name and update to latest rev

* Clean up formatting changes

* Move `worker_count` and `worker_retry_count` to settings

* Update defaults

* Use `0.4.4` instead of git branch
2023-06-26 10:45:22 +02:00
Dessalines e4d78b0974 Version 0.18.0 2023-06-26 10:45:22 +02:00
Dessalines 3f6e9a7f23 Version 0.18.0-rc.8 2023-06-26 10:45:22 +02:00
Dessalines 37a47de3a8 Revert "feat: re-added captcha checks (#3249)" (#3288)
This reverts commit 8a086c8240.
2023-06-26 10:45:22 +02:00
Dessalines b6cd1bde8e Fixing removed posts showing. Fixes #2875 (#3279)
* Fixing removed posts showing. Fixes #2875

* Fixing clippy.
2023-06-26 10:45:22 +02:00
Kresten Laust aea5f6a38b Reversed requirement question logic (#3283)
* Reversed requirement question logic

* Changed required state to 'true'
2023-06-26 10:45:22 +02:00
TKilFree 9537878519 feat: re-added captcha checks (#3249) 2023-06-26 10:45:22 +02:00
Sander Saarend 6d67f88603
Add support for sslmode=require for diesel-async DB connections (#3189) 2023-06-26 10:25:38 +02:00
cetra3 d7da911a48
Remove `actix_rt` & use standard tokio spawn (#3158)
* Remove `actix_rt` & use standard tokio spawn

* Adjust rust log back down

* Format correctly

* Update cargo lock

* Add DB settings

* Change name and update to latest rev

* Clean up formatting changes

* Move `worker_count` and `worker_retry_count` to settings

* Update defaults

* Use `0.4.4` instead of git branch
2023-06-26 10:24:11 +02:00
Dessalines 63d3759c48 Version 0.18.0 2023-06-23 08:41:20 -04:00
Dessalines cb3b9b1a66 Version 0.18.0-rc.8 2023-06-23 07:07:51 -04:00
Dessalines 1f1c0ad17a
Revert "feat: re-added captcha checks (#3249)" (#3288)
This reverts commit 8a086c8240.
2023-06-23 07:02:05 -04:00
Dessalines dce79b83bf
Fixing removed posts showing. Fixes #2875 (#3279)
* Fixing removed posts showing. Fixes #2875

* Fixing clippy.
2023-06-23 12:53:46 +02:00
Kresten Laust 39572e1c3e
Reversed requirement question logic (#3283)
* Reversed requirement question logic

* Changed required state to 'true'
2023-06-23 11:50:35 +02:00
TKilFree 8a086c8240
feat: re-added captcha checks (#3249) 2023-06-23 11:47:12 +02:00
Vijay Ramesh 418bca78e1
Merge branch 'main' into clear_deleted_posts_comments 2023-06-22 09:59:43 -07:00
Dessalines 60baebcb14 Version 0.18.0-rc.6 2023-06-22 08:55:08 -04:00
Nutomic ffce66abb8
Update apub library to 0.4.4 (#3258)
Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-06-22 08:35:12 -04:00
kartikynwa 4f2fb68d6b
Add migration to mark local communities as such (#3257) 2023-06-22 07:52:31 -04:00
Nutomic 08e25d0e63
Remove translation part from docs links (#3260)
Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-06-22 07:46:37 -04:00
Nutomic 434beadb58
Use Rust 1.70 for Docker and CI (#3265) 2023-06-22 07:46:07 -04:00
ShittyKopper 862ceefc56
docker-compose: Add init to UI (#3248)
* docker-compose: Add init to UI

Prevents waiting 10 seconds to shutdown

* docker-compose: Update to version 3.7
2023-06-22 10:22:15 +02:00
Óliver García Albertos 985359918f
logger: Use forwarded instead of peer IP address (#3223) 2023-06-22 09:34:51 +02:00
Vijay Ramesh 0d576a8f23
Merge branch 'main' into clear_deleted_posts_comments 2023-06-21 13:35:37 -07:00
kartikynwa ef3544bac4
Put /admin/purge routes before /admin routes (#3244) 2023-06-21 22:32:06 +02:00
Bnyro c9d1fec117
docs: Add Lemoa to lemmy projects section (#3247) 2023-06-21 22:15:10 +02:00
Scott da3e3b6d8a
Ensure site can only either be a private instance or federated when creating or editing site (#3237)
* Add site visibility validation

* Fix formatting

* linter changes

* Update error message to match existing check

* Remove existing check

---------

Co-authored-by: Scott Merchant <97430840+scottmerchant@users.noreply.github.com>
2023-06-21 22:14:12 +02:00
Dessalines 289052f261 Version 0.18.0-rc.5 2023-06-21 16:02:42 -04:00
Vijay Ramesh 4db65c191c after 30 days post deletion, replace comment.content and post.body with 'Permanently Deleted' 2023-06-21 12:46:56 -07:00
Dessalines d4f52b78b3
Trying to fix version again. (#3246) 2023-06-21 21:46:32 +02:00
Michał 4cdb9583e9
feat: allow overriding smtp_password with the LEMMY_SMTP_PASSWORD env var (#3154)
Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-06-21 13:36:42 -04:00
Dessalines 3775418952 Version 0.18.0-rc.4 2023-06-21 08:05:15 -04:00
Nutomic 8fb4760e02
Dont publish to crates.io (#3239) 2023-06-21 07:57:01 -04:00
Nutomic e3eda68147
Correct error messages if user registers with taken user/email (#3093)
* Correct error messages if user registers with taken user/email (fixes #2955)

* exists
2023-06-21 05:26:07 -04:00
Dessalines 1ef095dd96
Fixing cross_post duplicates. Fixes #3233 (#3234) 2023-06-21 10:56:44 +02:00
JP Moresmau a1beccf353
Add test to check reading and listing posts return my_vote (#3215) 2023-06-21 10:48:39 +02:00
dullbananas 45818fb4c5
Reduce memory usage of rate limiting (#3111)
* Reduce Vec allocations

* Optimize stuff

* Move embedded migrations to separate crate

* Revert "Move embedded migrations to separate crate"

This reverts commit 44b104997016ee2a1f2c0bb735b75e654666860d.

* clippy, fmt

* Shrink rate limit allowance to f32

* Initialize rate limit allowance directly

* Add removal of old rate limit buckets

* Improve readability

* Remove usage of is_okay_and for Rust 1.67 compatibility

* Add dhat-heap feature

* Fix api_benchmark.sh and add run_and_benchmark.sh

* Revert "Fix api_benchmark.sh and add run_and_benchmark.sh"

This reverts commit b4528e5b85dd3f13cea43d72ada9382200c8fc77.

* Revert "Add dhat-heap feature"

This reverts commit 08e835d487b983c44ce2570d8c396d570d426916.

* Manually revert remaining stuff

* Use Ipv6Addr in RateLimitStorage

* Shrink last_checked in RateLimitBucket to 32 bits

* Fix rate_limit::get_ip

* Stuff (#1)

* Update rate_limiter.rs

* Update mod.rs

* Update scheduled_tasks.rs

* Fix rate_limiter.rs

* Dullbananas patch 1 (#2)

* Update rate_limiter.rs

* Update mod.rs

* Update scheduled_tasks.rs

* Fix rate_limiter.rs

* Rate limit IPv6 addresses in groups

* Fmt lib.rs

* woodpicker trigger

* Refactor and comment `check_rate_limit_full`

* Add `test_split_ipv6`

* Replace -2.0 with UNINITIALIZED_TOKEN_AMOUNT

* Add `test_rate_limiter`

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-06-21 10:28:20 +02:00
Dessalines b214d3dc00
Adding current domain from settings to CORs. (#3231) 2023-06-20 20:29:48 -04:00
Joel Beckmeyer 8179b0daf2
remove debugging println (#3227) 2023-06-20 14:20:20 -04:00
Dessalines 5ff221a2e4
Fixing comment_view unit tests. (#3224) 2023-06-20 14:14:08 -04:00
Sander Saarend 8ed3f3530e
Fix parameter ordering for new_report_subject string (#3210) 2023-06-20 11:24:04 -04:00
Nutomic b37c30ffae
Move cors default to source code (#3219) 2023-06-20 11:19:03 -04:00
Dessalines 154a85cc36
Fixing tag deploys. (#3216)
* Fixing tag deploys.

* Fixing tag deploys 2.

* Try to comment build_args.

* Fixing tag deploys 3.

* Fixing build args again.

* Last fix.
2023-06-20 16:29:24 +02:00
Ivo Barros 4d160461ce
Feature add hours as sorting options backend (#3161)
* add hours as sorting options

* ran cargo +nightly fmt

* woodpicker trigger
2023-06-20 16:05:43 +02:00
kartikynwa dc36d9ed89
Don't check verified email when an admin logs in (#3209)
Workaround for instance admins getting locked out when they turn on
the email verification requirement without having verified their
own email.

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-06-20 08:52:21 -04:00
Andrew DeLisa bfc0c0e7d3
fix: add CORS origin environment variable (#3191)
* fix: add CORS origin environment variable

* chore: formatting

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-06-20 08:29:38 -04:00
Joel Beckmeyer 06a3f9c5aa
make embedded pict-rs port configurable (#3201) 2023-06-20 13:07:18 +02:00
Dessalines 981c111567
Move connection creation into scheduler. (#3120)
* Move connection creation into scheduler.

- #3076

* Fix clippy.
2023-06-20 11:33:03 +02:00
Felix Ableitner 56de68c77a Update translations 2023-06-20 10:59:27 +02:00
Sander Saarend e23621c2cd
Calculate initial hot_rank and hot_rank_active for posts and comments from other instances (#3131)
* Calculate initial hot_rank when receiving posts and comments from other instances

* Move hot rank update logic into db_schema
2023-06-20 10:52:51 +02:00
ludrol d97ff65fe1
Changed github issue template to align logically with the question asked (#3135) 2023-06-16 11:56:21 -04:00
Chethan bb27339e68
Update README.md (#3137)
The Ace of Spades video linked in the README was private, have replaced it with a public video.
2023-06-16 11:54:12 -04:00
Sander Saarend 007c7d5812
Remove e-mail verification success e-mails (#3124) 2023-06-16 11:53:33 -04:00
Alex Maras becf75d1f9
Fix Hidden communities showing in community list (#3094)
* Only show hidden communities when explicitly searching for them rather then in "all"

* dont set hidden to false when creating and updating - let DB set default

* lint

---------

Co-authored-by: Alex Maras <alexmaras@gmail.com>
2023-06-15 13:39:58 +02:00
Nutomic b5dba17426
Update all dependencies (#3091) 2023-06-15 11:37:05 +02:00
Wyatt Smith 744153eee6
Prevent making an instance private if federation is enabled. (#3074)
* Prevent making an instance private if federation is enabled.

* Added case where federation is enabled, check if the alternative setting is changed

* Merged the error messages for private instance/federation.

---------

Co-authored-by: Wyatt Smith <wys@dropbox.com>
2023-06-15 11:35:09 +02:00
Sander Saarend 68d814b9b1
Handle scheduled task errors (#3090)
* Add --disable-scheduled-tasks CLI flag

* Add error handling for scheduled tasks
2023-06-15 11:29:12 +02:00
Dessalines 5af831c6fa
Fix unapproved users being able to log in after registration mode set to closed. (#3096)
- Fixes #3095
2023-06-14 19:02:17 -04:00
Nutomic ebd8c86f0e
Link tafkars in readme (#3087) 2023-06-14 23:41:20 +02:00
Divided by Zer0 14b990e006
doc: Added pythorhead library in readme (#3114) 2023-06-14 23:40:49 +02:00
adisbladis e0af3a292e
Only create ltree postgres extension in migration if doesn't already exist (#3092) 2023-06-14 17:03:10 -04:00
Raymond Berger 53fe93db47
add issue template yml from lemmy-ui (#3086)
* add issue template yml from lemmy-ui

* prettier

* Empty-Commit for CI

* improve Qs

* add instance question

* delete hexbear

* backend version
2023-06-14 22:21:03 +02:00
Neshura 558035b128
Fix Issue #3075 by using None for local fields instead of Some(false) (#3088)
* Set insert and update form "local" to None

* Extra space to retrigger woodpecker

* Resolve code review request

https://github.com/LemmyNet/lemmy/pull/3088#discussion_r1229336958

* Remove extra space after None,
2023-06-14 08:34:45 -04:00
Charles Hall f43bb454c3
stop requiring superuser to run migrations (#3002)
Fixes <https://github.com/LemmyNet/lemmy/issues/2863>.
2023-06-14 07:54:12 -04:00
Nina Blanson 1c7bfd6be8
Fixes #1884 - Support Spoiler Tags (#3018)
* Fixes #1884 - Switches markdown libraries and creates a custom rule to manage spoiler blocks

* Add tests to cover invalid spoiler input

* Consolidate tests, add comments

* Make immutable, static instance of markdown parser

---------

Co-authored-by: Nutomic <me@nutomic.com>
2023-06-14 13:15:59 +02:00
Felix Ableitner f3f95e5d2f Fix compilation 2023-06-14 11:34:29 +02:00
Patrick Roe 87aa0acaf1
Align default DB password with documentation (#3068) 2023-06-13 22:23:07 +02:00
JetpackJackson 91271a7ce4
Update RSS url (#3053)
* Update RSS url

* Fixed next line

* making sure this thing uploads

* Update feeds.rs

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-06-13 16:17:02 -04:00
Edgar Alvarado c32585b034
Docker yaml anchors and docker logs (#3027)
* Use anchor for duplicated compose properties

* Include docker log max

* Run prettier
2023-06-13 08:37:06 -04:00
Edgar Alvarado 932e65c16d
Fix ports used by docker (#3012)
Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-06-12 18:38:27 -04:00
Jared Schneiderman 5f92125e44
Add limit and pagination to feeds (#2980)
* adds limit and pagination to all rss feeds

* consistent ordering

* refactor page and limit and add after

* revert back to using page

* remove offset change

* refactor to impl adding helper methods

* clippy
2023-06-12 17:48:02 -04:00
Nutomic 25275b79ee
Upgrade activitypub-federation to 0.4.1 (#3039)
This improves logging so that its not necessary to enable debug
logs to find out that activity worker count needs to be increased.
2023-06-12 14:12:15 -04:00
Charlie Fish 87634ca206
Adding Lemmy-Swift-Client to README.md (#3026) 2023-06-12 15:31:27 +02:00
Andy Brandt b47ce4c2e6
use usize::MAX for line wrap length, since lettre does it for us (#3034)
fixes #2921
2023-06-12 15:29:15 +02:00
Charles Hall f50325e78a
update doku (#3003)
Fixes malformed documentation generated by previous version.
2023-06-12 05:55:47 -04:00
Nathan Schulzke 3a6f8877c9
Fix contributing link (#3015) 2023-06-12 11:04:47 +02:00
Dessalines ecc9469a02
Better issue templates. (#2991)
* Better issue templates.

* Fixing bug report.
2023-06-09 23:08:27 +02:00
Charles Hall 14c18dbdae
allow specifying db uri in config file (#2956)
* allow specifying db uri in config file

* succumb to a bug in doku

See <https://github.com/anixe/doku/issues/33>.
2023-06-09 08:18:22 -04:00
Dessalines 8cb5939f50
Adding hot_rank columns in place of function sorting. (#2952)
* Adding hot_rank columns in place of function sorting.

- Creates hot_rank columns for post, comment, and community.
- Fixes #2932

* Updating all hot ranks on startup.

* Fixing post.url migration.

* Removing update_instance_software from startup.

* Adding post_rank query
2023-06-08 16:15:15 -04:00
Charles Hall 4e5798852f
make shebangs posix compliant (#2974)
Previously, these scripts wouldn't work on exotic systems such as NixOS.

```
fd '\.sh$' -t f --exec sed -i 's@#!/bin/bash@#!/usr/bin/env bash@'
```
2023-06-08 15:38:26 -04:00
Andy Brandt f98476c5c0
Fix private message e-mail notification subject and body (#2963)
It used to say:

Subject: Private message from [your username]
Body: [your username] - [private message]

It now display the correct username that it's from.
2023-06-08 13:42:32 -04:00
Anon 15c84e2f7b
Add comment depth check (#2940)
* Add comment depth check

* Move comment depth code

* linter fix
2023-06-08 10:31:26 -04:00
Jason Watkins 491e197529
Add `lemmyexternalproxy` to `lemmy` so that it can talk to the internet (#2960)
Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-06-08 08:30:16 -04:00
Nutomic 980df7545d
Fix translation build error (fixes #2967) (#2968) 2023-06-08 07:12:40 -04:00
Nutomic 2423b89ced
Activitypub breaking changes for Lemmy 0.18 (#2705)
* Remove deprecated field `group.moderators`

* Drop column local_site.federation_debug

* Remove backwards compatibility code for feature/lock post

https://github.com/LemmyNet/lemmy/pull/2716

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-06-07 15:18:17 -04:00
Nutomic 1c9f0c2bed
Add db index for post.url column (#2929)
* Add db index for post.url column

As mentioned in https://github.com/LemmyNet/lemmy/issues/2877#issuecomment-1576439829

Not sure if its preferable to do this, or make a combined index
which includes post.nsfw, post.removed, post.deleted

* remove unique
2023-06-07 11:31:24 -04:00
derivator 9419dd7c05
Fall back to String for Comment::path when not using the full feature (#2941) 2023-06-07 09:38:46 -04:00
Carlrs 24323e17b2
update diesel to 2.1.0 and diesel-async to 0.3.0 (issue #2882) (#2895)
* update diesel to 2.1.0 and diesel-async to 0.3.0 (issue #2882)

* get rid of deprecated RawValue type alias usage, explicitly import diesel types instead of using wildcard import

* Update diesel-derive-enum and diesel-derive-newtype libraries

* Revert manual changes to schema.rs

* Update to newer diesel-cli image in CI, run fix-clippy before schema comparison, update schema to one generated with diesel-cli 2.1.0 and clippyfixed

* Remove wildcard import lint, fix diesel schema pipeline

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-06-07 12:54:40 +02:00
Dessalines af03dcfeac
Fix dev setups. (#2944) 2023-06-06 22:22:21 -04:00
Nutomic e97c30b930
Set version name for crates.io release (#2928)
* Set version name for crates.io release

ref https://github.com/LemmyNet/lemmy-ui/issues/1052

* fix yml

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-06-06 20:24:06 -04:00
vpzomtrrfrt 09099e7b90
Fix handling of follows addressed to single value (#2920)
* Fix handling of follows addressed to single value

* Switch to deserialize_skip_error for Follow to

* Also use deserialize_skip_error for AcceptFollow and UndoFollow

* actually import deserialize_skip_error
2023-06-06 18:33:38 -04:00
Nutomic 3565ad984a
Remove chatserver (#2919)
* Remove chatserver

* fix clippy

* Remove captchas (fixes #2922)

* fix prettier

* fix api_common build

* cargo fmt
2023-06-06 12:27:22 -04:00
Dessalines ef1aa18fd2
Adding taglines to SiteResponse. Fixes #2925 (#2926)
* Adding taglines to SiteResponse. Fixes #2925

* Fixing CI line.
2023-06-06 08:59:34 -04:00
Dessalines bb625c3671
Fix *All* reports not showing. Fixes #2902 (#2903)
* Fix *All* reports not showing. Fixes #2902

* Fix *All* reports not showing. Fixes #2902

* Fixing tests.
2023-06-06 11:01:48 +02:00
Matt Pusch ae88f618fd
README updates (#2913)
* Updated readme to remove unsecure sunchid lemming article - replaced with wikipedia article.

Commented out sponsor list as page DNE.

Commented out Contributing section as all sites DNE. Added simple instructions for git contribution. Cleaned up formatting for Contributing section.

TODO: update join-lemmy.org/docs, uncomment removed lines

* Implemented suggested changes
2023-06-05 11:34:15 -04:00
Nutomic 7248c4a6f4
Filter empty username strings from Mastodon (fixes #2886) (#2887)
* Filter empty username strings from Mastodon (fixes #2886)

* add issue link
2023-06-05 13:56:53 +02:00
Udo dc9ca5768b
Update humane tech badge to point to new repo (#2898) 2023-06-05 12:49:32 +02:00
Justin Gauthier d439bdf8b4
Update to fix nginx proxy config for Docker Installs (#2908)
* Update to fix nginx proxy config

* Update docker-compose.yml - fix type

---------

Co-authored-by: Jax Gauthier <jax@gauthier.id>
2023-06-05 12:43:31 +02:00
Nutomic 1b4f995706
Remove jaeger, opentelemetry from docker-compose (#2894) 2023-06-04 22:16:49 +02:00
Dessalines e363c25521
Replace remmel with Mlem. (#2890) 2023-06-01 22:40:47 +02:00
Dessalines af3eb6e27b
Add CORS support for debug mode. (#2884) 2023-05-29 17:14:00 -04:00
phankydn d30839bea1
Don't filter comments of posts from blocked community when viewing post detail (#2880) 2023-05-29 11:41:47 -04:00
Nutomic 4240af86ca
Remove websocket code (#2878)
Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-05-29 10:44:20 -04:00
Nutomic a5707328cf
Dont return error in case optional auth is invalid (#2879)
* Dont return error in case optional auth is invalid

* fixes
2023-05-25 10:50:07 -04:00
phankydn 4a70502007
Remove unnecessary clone (#2874)
Co-authored-by: KyP <phanky.vn@proton.me>
2023-05-23 19:00:19 -04:00
Nutomic 82d93da26b
Remove GetCommunityResponse.default_post_language (#2867)
This field is unnecessary because we already set a default language
with the same logic if none is passed in CreatePost. So if the user
doesnt set a post language, it should simply be passed as None. This
also has the advantage that it works with clients that dont support
language tags.

Technically not a breaking change because its optional, but better
be safe.
2023-05-21 11:55:32 -04:00
Nutomic a9d708f494
Merge pull request #2866 from LemmyNet/remove-reqwest-retry
Optimize fetching of post url metadata
2023-05-18 17:19:54 +02:00
Felix Ableitner 436a293f38 Dont refetch post url metadata when post is received again 2023-05-18 16:34:52 +02:00
Felix Ableitner df57795595 Dont retry outgoing HTTP requests (ref #2865) 2023-05-18 16:34:52 +02:00
Nutomic 8410a9696e
Force enable undetermined language (#2851)
* Force enable undetermined language

* update

* fix tests
2023-05-18 16:34:21 +02:00
SleeplessOne1917 e856eda74d
Fix typo that caused error (#2861) 2023-05-14 14:02:05 -04:00
Dessalines 69f179bd33
Prettier check (#2855)
* Adding prettier check to CI.

* Running prettier on codebase.
2023-05-13 16:50:58 -04:00
Nutomic ce5161d997
Downgrade postgres for CI to 15.2 (fixes #2857) (#2859) 2023-05-12 19:08:32 -04:00
SleeplessOne1917 0379c9e4c1
Make volumes used in docker compose work when running on machines with SELinux enabled (#2853)
* Make volumes used in docker compose work when running on machines with SELinux enabled

* Switch lemmy-ui comments

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-05-11 20:15:12 -04:00
Nutomic af5175a282
Set attribute `deny_unknown_fields` for Lemmy config (#2852)
With this attribute, Lemmy will throw an error and exit if any
invalid entry is found in the config file. I think can be useful
to notice typos or keys that were removed or renamed in an upgrade.
Currently you wouldnt notice these at all unless you manually
compare the config file with settings that are listed in documentation.

This should be considered a breaking change.

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-05-11 20:12:12 -04:00
Dessalines 32a5567cbf
Fixing empty req issue. (#2849)
* Fixing empty req issue.

* Forgot skip serializing none.
2023-05-11 21:20:45 +02:00
Dessalines d63b1ba935
Upgrade api_test deps (#2850)
* Upgrade api_test deps

* Fix cargo fmt.

* Try to trigger a new format
2023-05-10 16:31:37 -04:00
Dessalines 014c0ad87f
Adding comments to all API related types. Fixes #2846 (#2848) 2023-05-10 21:20:39 +02:00
Dessalines 88a0d2feec
Adding typescript generation for API. Fixes #2824 (#2827)
* Adding typescript generation for API. Fixes #2824

* Try to fix Ltree issue 1.

* Forgot a few types.

* Fixing api tests.

* Removing url_serde line.

* Manually deriving TS for some types.
2023-04-26 00:26:10 -04:00
Dessalines 1b5437cbe3
Addressing slow profile queries. #2777 (#2830)
* Addressing slow profile queries. #2777

* Addressing PR comments.
2023-04-25 19:28:06 -04:00
Dessalines 17527d0e7e
Reverting to older non-multi-arch dockerfile. Fixes #2832 (#2833) 2023-04-25 22:40:58 +02:00
Nutomic a25faf3e97
Add `to` field in follow activities for better compatibility (#2829)
* Add `to` field in follow activities for better compatibility (fixes #2744)

* fix tests
2023-04-24 17:19:08 -04:00
Dessalines a2fb4b8cd0
Use older git clone for woodpecker. (#2831) 2023-04-24 21:40:36 +02:00
Dessalines eb40aeb89b
Remove last Option<Vec.. from API. Fixes #2820 (#2822)
* Remove last Option<Vec.. from API. Fixes #2820

* Add empty allowed_instances check.

* Adding comment for allowed_instances.
2023-04-21 23:41:03 +02:00
Dessalines 1e26709cb4
Adding cross_post fetching to GetPost. Fixes #2127 (#2821) 2023-04-19 22:16:19 +02:00
6543 85ef507ac7
Use Dockerfile.multiarch as Dockerfile (#2818)
* use Dockerfile.multiarch and delete old Dockerfile

* Dockerfile.multiarch -> Dockerfile

* nit
2023-04-18 22:21:31 +02:00
Dessalines d8722b6e91
Adding diesel enums for SortType and ListingType (#2808)
* Adding diesel enums for SortType and ListingType

- Uses diesel-derive-enum.
- Adds diesel.toml , so we can again use the auto-generated schema.rs
- Fixes a lot of DB null issues and column ordering issues.
- Fixes #1136
- Also replaces RegistrationMode boilerplate.

* Fixing unit tests 1.

* Remove comment line.

* Before patch.

* Before again.

* Using patch file to fix diesel_ltree issue with diesel.toml

* Adding some yalc ignores

* Fixing RegistrationMode enums

* Adding woodpecker diesel schema check.

* Try adding openssl 1.

* Try using diesel-cli image 1

* Try using diesel-cli image 2

* Try using diesel-cli image 3

* Try using diesel-cli image 4

* Try using diesel-cli image 5

* Try using diesel-cli image 6

* Try using diesel-cli image 7

* Try using diesel-cli image 8

* Try using diesel-cli image 9

* Try using diesel-cli image 10

* Try using diesel-cli image 11

* Try using diesel-cli image 12

* Try using diesel-cli image 13
2023-04-17 15:19:51 -04:00
SleeplessOne1917 f5511cfd25
Make path to local lemmy-ui use correct relative path (#2817) 2023-04-17 13:38:59 -04:00
SleeplessOne1917 922b50fc7c
Add lemmy-bot to README libraries list (#2816) 2023-04-17 13:21:37 -04:00
Dessalines 33ba1fc623
Separate federated_instances into its own endpoint. Fixes #1931 (#2813) 2023-04-16 17:00:31 -04:00
6543 90c6dc2732
Use official rust image and clean up Dockerfiles (#2804)
* Add docker/Dockerfile.multiarch

* Update normal Dockerfile to be similar to multiarch one

* docker build run on x86 and arm64 now
manifest not needed, its handled by buildx plugin

* Rename Dockerfile.arm To Dockerfile.debian

* Emulate builder on arm target too

* fix misspell

* Improve Dockerfiles

* naming

* undo multiarchbuild settings as its blocked by a dependeny, see #2806

* Delete Dockerfile.debian
2023-04-16 12:56:12 -04:00
Dessalines 3fa713f414
Temporary fix for hiding deleted posts. #2624 (#2811) 2023-04-15 20:23:36 -04:00
Dessalines 148f33def5
Leave modded communities on account deletion. Fixes #2560 (#2810) 2023-04-15 19:41:05 -04:00
Dessalines 38d4429ae7
Adding check to description and body length fields. (#2805)
* Adding check to description and body length fields.

- Also making the checks return `LemmyError`
- Fixes #1747

* Address PR comments.

* PR comments 2
2023-04-15 10:45:11 -04:00
6543 e7a2080f3f
Fix & Optimize CI config (#2802)
* let the clone plugin handle submodules too

* start using yml aliase

* fix publish_to_crates_io

* CI.restart()
2023-04-13 22:33:00 +02:00
Dessalines 63f54a3103
Making the chat server an actor. (#2793)
* Making the chat server an actor.

- Fixes #2778
- #2787

* Forgot to add handlers folder.

* Some cleanup.

* Forgot to remove a comment.

* Address PR comments.

* Using ToString for enum operations.
2023-04-13 06:53:55 -04:00
Nutomic 844cde9db3
Use pretty print for federation json responses (#2801) 2023-04-12 20:17:23 -04:00
Nutomic 9d26ac2c6f
Fix listing type default value (#2796)
* Fix listing type default value

The listing type parameter is only meant for the frontpage, but is
also applied inside of communities. The result is that this call
returns nothing, because it defaults to ListingType::Local:
https://fedibb.ml/api/v3/post/list?community_id=3

It needs to be called like this to get any posts:
https://fedibb.ml/api/v3/post/list?community_id=3&type_=All

This is clearly not expected behaviour, when a community is
specified, the listing type should default to All.

* fix clippy
2023-04-12 10:40:59 -04:00
Dessalines d18bc95b7b
Add woodpecker ci (#2789)
* Adding woodpecker. Try 1

* Adding woodpecker. Try 2

* Adding woodpecker. Try 3

* Adding woodpecker. Try 4

* Adding woodpecker. Try 5

* Adding woodpecker. Try 6

* Adding woodpecker. Try 7

* Adding woodpecker. Try 8

* Adding woodpecker. Try 9

* Adding woodpecker. Try 10

* Adding woodpecker. Try 11

* Adding woodpecker. Try 12

* Adding woodpecker. Try 13

* Adding woodpecker. Try 14

* Adding woodpecker. Try 15

* Adding woodpecker. Try 16

* Adding platform when conditionals.

* Adding platform when conditionals 2.

* Adding woodpecker docker buildx.
2023-04-05 16:29:35 -04:00
Nutomic 3a526b0b7d
Remove unused dependencies (#2795) 2023-04-05 16:29:08 -04:00
Nutomic 165b19e75c
Optimize federated language updates to avoid unnecessary db writes (#2786)
* Optimize federated language updates to avoid unnecessary db writes (fixes #2772)

* fix tests

* fix test, rename functions

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-03-30 11:03:13 -04:00
Helge fdaa2bcf09
Added identifier to context (#2791) 2023-03-26 22:19:10 +02:00
Nutomic 6f513793cb
Activitypub crate rewrite (#2782)
* update activitypub-federation crate to 0.4.0

* fixes

* apub compiles!

* everything compiling!

* almost done, federated follow failing

* some test fixes

* use release

* add code back in
2023-03-21 16:03:05 +01:00
Anon 6bc49bdd70
Add Custom Emojis Support (#2616)
* Add Custom Emojis

* Modify index
2023-03-20 17:32:31 -04:00
Dessalines 66b0ddbbc5
Adding deadpool timeouts. (#2775) 2023-03-03 10:30:03 +01:00
Dessalines 1dba94c9cb
Adding TOTP / 2FA to lemmy (#2741)
* Combine prod and dev docker setups using build-arg

- Fixes #2603

* Dont use cache for release build.

* Adding 2FA / TOTP support.

- Fixes #2363

* Changed name to totp_2fa for clarity.

* Switch to sha256 for totp.
2023-03-02 21:37:41 +01:00
Dessalines 985fe24669
Get rid of Safe Views, use serde_skip (#2767)
* Get rid of Safe Views, use serde_skip

- Also change the ViewToVec, to work with non-vector cases. Might be
  necessary in preparation for #2763
- Fixes #2712

* Forgot one safe

---------

Co-authored-by: Nutomic <me@nutomic.com>
2023-03-01 18:19:46 +01:00
Dessalines 48f187188b
Show deleted and removed posts for profile views. Fixes #2624 (#2729)
* Show deleted and removed posts for profile views. Fixes #2624

* Only showing non-deleted/removed posts for creator.

* Add a admin or mod check to views, to show deleted and removed posts.

- Also removed the pointless "blanking" functions

* Fix clippy

* Make hidden posts comment clearer.

* Fixing federation tests.

* Fixing fmt.
2023-02-28 22:46:15 -05:00
Nutomic d9e7f0100a
Dont upsert Instance row every apub fetch (#2771)
This is not necessary because the domain cant change, so we only
need to insert if no row exists for this domain.

Also fetch instance actor when parsing person, not only community

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-02-28 21:36:57 -05:00
Dessalines 3844ac76c3
Fixing broken websockets. (#2770)
* Fixing broken websockets.

* Use cloned() for serde::Value
2023-02-28 21:27:33 -05:00
Nutomic f0e1627824
Ignore undetermined language when calculating post default language (#2769)
This will make it much more likely to successfully get a default,
as most users and communities have undetermined selected.
2023-03-01 01:49:31 +01:00
Dessalines 209c8a9185
Switch from bb8 to deadpool. Fixes #2765 (#2768)
* Switch from bb8 to deadpool. Fixes #2765

* Remove unecessary deadpool dependency.

* Ignoring nodeinfo test.
2023-02-28 22:45:37 +01:00
Dessalines 8c0c1628e0
Adding a vector indexing check to prevent panics. Fixes #2753 (#2754)
* Adding a vector indexing check to prevent panics. Fixes #2753

* Fixing for new clippy lint.

* Externalizing get_top_mod check. Adding get_first clippy lint

* Removing unit tests get(0)s

* Fixing some firsts manually
2023-02-28 12:34:50 +01:00
Dessalines 4c77c84b60
Cleaning up person_view sorts (#2760) 2023-02-24 13:33:54 +09:00
Nutomic 80571567e1
Add default attribute for webfinger properties (fixes #2756) (#2759) 2023-02-23 09:51:33 -05:00
Dessalines 155af88582 Adding 0.17.2 Release notes. 2023-02-22 10:08:41 -05:00
Nutomic 675353d4e9
Include type information with webfinger responses (fixes #2037) (#2746)
So that it is easier to parse for other software
2023-02-22 11:25:26 +09:00
Dessalines cd5c79527a
Fixing issue with saving site language. Fixes #2748 (#2749)
* Fixing issue with saving site language. Fixes #2748

* Add a warning to Site::read
2023-02-22 02:22:54 +01:00
Nutomic a42f7271e6
Proper permission check for federated comment distinguish (#2697)
Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-02-19 03:57:45 +09:00
Nutomic 62663a9f2e
Implement separate mod activities for feature, lock post (#2716)
* Implement separate mod activities for feature, lock post

Also includes collection for featured posts. Later we also need
to do the same for Comment.distinguished

* some changes

---------

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-02-18 09:50:28 -05:00
Nutomic 8409e50f8c
Fix case in activitypub context (ref #2734) (#2743)
Should be camelCase.

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-02-18 09:48:50 -05:00
Dessalines 1917e3d495
Separate comment distinguish (#2740)
* Combine prod and dev docker setups using build-arg

- Fixes #2603

* Dont use cache for release build.

* Separate comment distinguish into its own action.

- Fixes #2708

---------

Co-authored-by: Nutomic <me@nutomic.com>
2023-02-18 09:46:34 -05:00
Dessalines 3735c6fabf
Adding instance software and version. Fixes #2222 (#2733)
* Adding instance software and version. Fixes #2222

* Fix clippy.

* Fix clippy 2

* Fixing some more issues.
2023-02-18 09:36:12 -05:00
Dessalines 47f4aa3550
Fixing slow joins to post_read, post_saved, and comment_saved . (#2738)
- Fixes #2445
2023-02-18 09:35:35 -05:00
Dessalines 9b0428bc50
Remove lemmur since its deprecated. (#2742) 2023-02-18 14:23:28 +01:00
Dessalines 993489a80f
Combine prod and dev docker setups using build-arg (#2739)
* Combine prod and dev docker setups using build-arg

- Fixes #2603

* Dont use cache for release build.
2023-02-17 15:29:45 +09:00
Dessalines 36aaa50644
Organize utils into separate files. Fixes #2295 (#2736)
* Organize utils into separate files. Fixes #2295

* Moving tests.

* Fix test.

* Fix test 2
2023-02-16 05:05:14 +01:00
Dessalines 8a27978ee1
Removing checking permissions when editing posts and comments. (#2727)
* Removing checking permissions when editing posts and comments. Fixes #2714

* Running cargo fmt again.

* Adding back in community ban checks.
2023-02-15 11:04:23 +09:00
Dessalines 956d0aa52f
Fixing updated form fields. Fixes #2724 (#2725)
* Fixing updated form fields. Fixes #2724

* Fix import.
2023-02-14 16:41:22 -05:00
Dessalines 9d7009c772
Only let top admin purge. Fixes #2731 (#2732) 2023-02-14 14:31:04 -05:00
Nutomic 25e98064b6
Fix writing of `removeData` in apub context (fixes #2734) (#2735) 2023-02-14 13:40:39 -05:00
Dessalines ddb6268164
Adding a site option to email admins for new reports. (#2730)
- Fixes #2551
2023-02-15 00:57:08 +09:00
Dessalines 166854b37e
Sort community search by active_monthly by default. (#2728)
- Fixes #2678
2023-02-14 15:19:37 +01:00
Nutomic 3bb98fcc64
Fix post titles being cut off (fixes #2718) (#2720)
I didnt notice that this limit would also apply to Lemmy and other
software which has the title field. So gonna change it to be
identical to db limit
2023-02-10 13:35:23 -05:00
Nutomic 3bfa8ab4ff
Improved error message when attempting to fetch non-local object (fixes #2715) (#2717) 2023-02-08 14:45:29 -05:00
Kradyz ab9b60e86d
Convert HTML from titles into markdown (#2709)
Co-authored-by: Kradyz <k@radiz.nl>
2023-02-07 03:27:17 +01:00
Nutomic 7c1a37d584
In apub post receive, check posting restricted to mods (ref #2702) (#2704)
Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-02-05 12:31:09 -05:00
Nutomic 2891856b48
Fix docker federation setup (#2706) 2023-02-05 12:30:10 -05:00
Nutomic eb78af9b02
Fix data fetching from Peertube (fixes #2689) (#2703)
- Other platforms can support additional language tags. Treat those
as None instead of throwing error
- deserialize_skip_error was implemented incorrectly and failed on
array values (6d9682f4e6)

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-02-05 00:38:08 -05:00
Dessalines bc8845391f
Add a ntfy notif on a tag deploy success. (#2701) 2023-02-05 02:51:48 +09:00
Dessalines 0c8fd240a6 Adding 0.17.1 Release notes. 2023-02-03 14:30:26 -05:00
Nutomic 4dddc3f717
Disable pictrs feature in CI to make it faster (#2698) 2023-02-04 03:32:44 +09:00
Dessalines 5ae409d4e4 Version 0.17.1 2023-02-03 09:36:18 -05:00
Dessalines ed95c61bca
Fixing admin application email subject. Fixes #2688 (#2695) 2023-02-03 09:24:19 -05:00
Dessalines b1e121b5ba
Fixing person block views. Fixes #2693 (#2694) 2023-02-03 14:45:32 +01:00
Dessalines d0c94a4f49
Fixing GetPosts active sort index. Fixes #2683 (#2684)
* Fixing GetPosts active sort index. Fixes #2683

* Fixing other sort.
2023-02-02 14:09:32 -05:00
Dessalines 93f2eb4df0 More explicit upgrade instructions. 2023-02-01 09:35:24 -05:00
Dessalines 4dfe4c5579 Fix yerbate.ml -> join-lemmy.org links 2023-02-01 09:34:59 -05:00
Dessalines 41010328c1 Merge branch 'main' of https://github.com/LemmyNet/lemmy 2023-01-31 12:21:34 -05:00
Dessalines 2754bc1d10 Fixing instructions. 2023-01-31 12:21:28 -05:00
Nutomic 36ac1b54c1
Publish without verify (#2681)
Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-01-31 10:41:48 -05:00
Nutomic 43b94e5f16
Fix paths in release script, update crate versions (#2680) 2023-02-01 00:26:51 +09:00
Dessalines d5368cbba9 Adding 0.17.0 Release notes. 2023-01-31 08:38:41 -05:00
Dessalines 53bc0311b1 Version 0.17.0 2023-01-31 08:30:54 -05:00
Dessalines a9905bf999 Updating translations. 2023-01-31 08:29:31 -05:00
Dessalines a610211557
Fixing `.drone.yml` (#2677)
* Try to fix docker/drone plugin

* Trying to use one rust image.

* Fixing drone 1.

* Fixing drone 2.

* Add drone notify.

* Fixing drone 3.

* Fixing drone 4.

* Fix clippy.

* Remove uninlined format lint.

* Combine all cargo tasks

* Fixing drone 5.

* Fixing drone 6.

* Fixing drone 7.

* Fixing drone 8.

* Fixing drone 9.

* Fixing drone 10.

* Fixing drone 12.

* Fixing drone 13.

* Fixing drone 14.

* Fixing drone 15.

* Fixing drone 16.

* Fixing drone 17.

* Fixing drone 18.

* Fixing drone 19.

* Fixing drone 20.

* Fixing drone 21.

* Fixing drone 22.

* Fixing drone 23.

* Fixing drone 24.

* Fixing drone 25.

* Fixing drone 26.

* Fixing drone 27.

* Fixing drone 28.

* Fixing drone 29.

* Fixing drone 30.

* Fixing drone 31.

* Fixing drone 32.

* Fixing drone 33.

* Fixing drone 34.

* Fixing drone 35.

* Fixing drone 36.

* Fixing drone 37.

* Fixing drone 38.

* Fixing drone 39.

* Fixing drone 40.

* Fixing drone 41.

* Fixing drone 43.

* Fixing drone 44.

* Fixing drone 45.

* Last cleanup.

* Fixing drone 46.

* Separate ci steps (#2679)

* separate ci steps

* fix 1

* add comments

* dont add rustfmt explicitly

* Revert "dont add rustfmt explicitly"

This reverts commit 358ce3302a134b7ac88d90a854079356995e9725.

* dont use all features for tests

---------

Co-authored-by: Nutomic <me@nutomic.com>
2023-01-30 14:17:24 -05:00
Dessalines a8232fe3d6
Use join_all instead of try_join_all. Fixes #2673 (#2674)
* Use join_all instead of try_join_all. Fixes #2673

* Add note about closed connections.
2023-01-30 11:11:11 -05:00
Kradyz c416e4ce14
Update message_id to comply with RFC 2822 (#2668)
The RFC 2822 format standard requires the message ID to be enclosed within angle brackets. If the standard is not followed, SpamAssassin deducts points from the e-mail.

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-01-30 11:10:51 -05:00
Dessalines 70c549dad8
Speeding up comment-ltree migration, fixing index creation. Fixes #2664 (#2670)
* Speeding up comment-ltree migration, fixing index creation. Fixes #2664

* Adding some logging lines, fixing for missing posts.

* Adding more postgres config
2023-01-23 09:59:25 -05:00
Nutomic 1eaf2c8a03
Add feature to embed pictrs in lemmy binary (fixes #2627) (#2633)
* Add feature to embed pictrs in lemmy binary (fixes #2627)

* Add pictrs config

* add protobuf

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-01-20 12:46:49 -05:00
Dessalines 6eb5ed343c
Update post_aggregates indexes to account for featured_local and featured_community columns. (#2661)
- Fixes #2660
2023-01-20 12:44:03 -05:00
Nutomic 7e3d3839b6
Post creation from Mastodon (fixes #2590) (#2651)
* Post creation from Mastodon (fixes #2590)

* better logic for page title

* add deserialize helper

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2023-01-20 12:43:23 -05:00
Dessalines ac56504291
Upgrade to postgres 15. (#2659) 2023-01-20 18:15:07 +01:00
Dessalines b5d45fa826
Add reddit -> lemmy importer to readme. (#2662) 2023-01-20 03:41:37 +01:00
Nutomic 2ec8bb877c
Some script improvements (#2654)
- Allow specifying which packages should be tested
- Hardcode `lemmy` as db password because thats used in many different places
2023-01-13 00:23:58 +01:00
Nutomic ceff2ec686
Use enum for registration mode setting (#2604)
* Use enum for registration mode setting

* fix tests
2023-01-05 01:42:30 +00:00
Dessalines 0630d214e3
Removing sniptt/monads for lemmy-js-client. (#2644)
* Removing sniptt/monads for lemmy-js-client.

* Fix tests.
2023-01-04 10:59:26 -05:00
Dessalines b7d5b37ac9
Fix historical post fetching. Fixes #2640 (#2643) 2023-01-04 14:58:11 +00:00
Dessalines e567151ec3
Adding the go client. (#2629)
* Adding the go client.

* Adding lemmyBB, and a stub for lemmy-rust-client

* Updating to use api_common readme.
2023-01-03 21:04:22 +00:00
Nutomic dab532f743
Point to !lemmy_support for support questions (#2638) 2023-01-03 03:28:21 -05:00
Nutomic 270f3b781a
Add documentation for using Lemmy API from Rust (#2639) 2023-01-03 03:23:41 -05:00
Nutomic 0d4cdb579c
Improve application question check (#2628)
The check was failing if only require_application was passed
and not application_question, despite application_question
being set in database.
2022-12-23 01:31:39 +00:00
Nutomic 9f52d4ae53
Fix user following (#2623)
Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2022-12-19 10:55:26 -05:00
Nutomic c3fbb7702f
Allow embedding Lemmy, fix setup error (#2618)
* Fix error during site creation due to empty LocalSiteRateLimit update

* Move main function into lib.rs, to allow calling from other crates

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2022-12-19 10:54:42 -05:00
Dessalines 76e0ab934f
Fixing missing forms, incorrect user discussion_languages (#2580)
* Fixing missing forms, incorrect user discussion_languages

* Add discussion_language to CommunityResponse

* Adding discussion_languages to CommunityResponse

* Adding discussion_language logic to community.create
2022-12-19 11:40:22 +00:00
Anon 9dfd819691
Add support for Featured Posts (#2585)
* Add support for Featured Posts

* Fix rebase

* More fixes
2022-12-12 11:17:10 +00:00
Nutomic 0ecf256ce3
Remove federation backwards compatibility with 0.16.x (#2183)
* Breaking: remove compatiblity with page.url field (ref #2182)

* Breaking: change type of Instance to `Application` (ref #2200)

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2022-12-09 11:21:17 -05:00
Nutomic 2732a5bf07
Rework websocket (#2598)
* Merge websocket crate into api_common

* Add SendActivity trait so that api crates compile in parallel with lemmy_apub

* Rework websocket code

* fix websocket heartbeat
2022-12-09 10:31:47 -05:00
Nutomic f02892b23b
Merge pull request #2593 from LemmyNet/refactor-notifications
Refactor crates for parallel build
2022-12-02 11:17:10 +00:00
Felix Ableitner c6c52ab9cc Add SendActivity trait so that api crates compile in parallel with lemmy_apub 2022-12-02 10:46:49 +01:00
Felix Ableitner 201fa97769 Move code to generate apub urls into lemmy_api_common 2022-12-02 10:46:49 +01:00
Felix Ableitner 904d7bec2f Builds lemmy_routes in parallel with lemmy_apub 2022-12-02 10:46:49 +01:00
Felix Ableitner 030afbc2e7 Merge websocket crate into api_common 2022-12-02 10:46:49 +01:00
Nutomic 70e3feb174
Check user accepted before sending jwt in password reset (fixes #2591) (#2597)
Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2022-12-01 16:36:03 -05:00
Nutomic ccb6435c1d
Relax honeypot check (fixes #2595) (#2596)
Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2022-12-01 16:33:59 -05:00
Nutomic bcf5c91f81
Use audience field to federate items in groups (fixes #2464) (#2584) 2022-12-01 15:52:49 -05:00
Nutomic 41d4852efc
Federate group moderators using attributedTo field (#2588)
* Federate group moderators using attributedTo field

* fix tests

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2022-11-25 09:01:58 -05:00
Nutomic 96a2bec691
Set cargo home in ci to avoid redownloading deps between steps (#2587)
* Set cargo home in ci to avoid redownloading deps between steps

* remove protobuf

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2022-11-24 23:43:31 -05:00
Nutomic d39bc14c43
Add some more clippy lints (#2586)
* Add some more clippy lints

* restore config

* no allow dirty

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2022-11-24 16:38:00 +00:00
Nutomic c3c4508a72
Use release docker image for nightly build (#2583)
Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2022-11-24 08:33:58 -05:00
Nutomic d20d2b9218
Implement federated user following (fixes #752) (#2577)
* Implement federated user following (fixes #752)

* rewrite send_activity_in_community and add docs, remove default for column pending

* improve migration

* replace null values in db migration
2022-11-23 18:40:47 -05:00
Felix Ableitner 4ddca46228 Revert "Test drone (#2582)"
This reverts commit 87c7ee5490.
2022-11-23 21:25:24 +01:00
Nutomic 87c7ee5490
Test drone (#2582) 2022-11-23 15:23:23 -05:00
Nutomic bb1e3bc891
Upgrade activitypub_federation to 0.3.4 (#2581) 2022-11-23 09:06:25 -05:00
Nutomic bc19d94e3c
Upgrade activitypub_federation crate to 0.3.3 (ref #2511) (#2578) 2022-11-22 07:20:31 -05:00
Nutomic 872c60a013
Remove federation settings, rely on sensible defaults instead (#2574)
This affects federation_strict_allowlist and federation_http_fetch_retry_limit
2022-11-21 11:44:34 -05:00
Dessalines 65041a20bb
Fix clippy lints. (#2572)
* Fix clippy lints.

* Fix fmt.

* Dont use cargo-workspaces for fix-clippy script.
2022-11-21 10:21:09 +00:00
Anon c27d2a5687
Add support for Taglines (#2548)
* Add support for Taglines

* recreate migration

* Update content column -> Text

* Optimize replace function

* Change taglines to Option

* Move Ok() call

* Move taglines to GetSiteResponse

* Fix logic

Co-authored-by: layla <layla@chapo.dev>
Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2022-11-19 09:48:29 -05:00
Nutomic 6f3bf4634b
Various pedantic clippy fixes (#2568)
* Various pedantic clippy fixes

* more clippy pedantic fixes

* try to fix ci

* add fix clippy script, use rust 1.65

* fix clippy
2022-11-19 04:33:54 +00:00
Nutomic a39cf31466
Sort vecs before assert to avoid random test failures (#2569)
* Sort language read queries to avoid random test failures

* change sort columns
2022-11-18 20:30:59 -05:00
Nutomic 23d0f3ed3c
Display build status badge from drone.join-lemmy.org (#2564)
Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2022-11-17 18:51:17 +00:00
Nutomic df7809fbbb
Specify dependencies and metadata for entire workspace (#2565)
* Specify dependencies and metadata for entire workspace (fixes #2474)

* building api_common shouldnt depend on diesel

* remove drone task

* try with quotes

* fix clippy

* more clippy
2022-11-17 15:23:01 +00:00
Nutomic 63c237d6df
Use enum_delegate crate (#2554) 2022-11-16 22:51:05 +00:00
Nutomic 24756af84b
Live reload settings (fixes #2508) (#2543)
* Live reload rate limit settings (fixes #2508)

* fix tests
2022-11-16 14:06:22 -05:00
Nutomic b16df59373
Fix activity list test (#2562) 2022-11-15 22:38:26 +00:00
Felix Ableitner 0b86ffbdbd Remove unwrap 2022-11-14 15:30:44 +01:00
Nutomic a0fed24cee
When announcing incoming activities, keep extra fields (#2550) 2022-11-12 08:52:57 -05:00
Nutomic e3bb43542c
Mobilizon federation (#2544)
* Mobilizon federation

* Also accept document attachments from mobilizon
2022-11-12 08:51:08 -05:00
Nutomic 83d2959b4b
Update doku dependency for easier formatting of defaults.hjson (#2553) 2022-11-11 16:01:29 -05:00
ᡥᠠᡳᡤᡳᠶᠠ ᡥᠠᠯᠠ·ᠨᡝᡴᠣ 猫 42674b7abd
Translated README.md to Chinese (#2549)
* Add Mandarin locales

`README.zh.hans.md` for Simplified Chinese, `README.zh.hant.md` for Traditional Chinese

* Fix relative links to README
2022-11-11 10:10:13 +00:00
Dessalines 5d837780f5
Add diesel_async, get rid of blocking function (#2510)
* Moving settings to Database.

- Moves many settings into the database. Fixes #2285
- Adds a local_site and instance table. Fixes #2365 . Fixes #2368
- Separates SQL update an insert forms, to avoid runtime errors.
- Adds TypedBuilder to all the SQL forms, instead of default.

* Fix weird clippy issue.

* Removing extra lines.

* Some fixes from suggestions.

* Fixing apub tests.

* Using instance creation helper function.

* Move forms to their own line.

* Trying to fix local_site_data, still broken.

* Testing out async

* Testing out async 2

* Fixing federation tests.

* Trying to fix check features 1.

* Starting on adding diesel async. 1/4th done.

* Added async to views and schema.

* Adding some more async

* Compiling now.

* Added diesel async. Fixes #2465

* Running clippy --fix

* Trying to fix cargo test on drone.

* Trying new muslrust.

* Trying a custom dns

* Trying a custom dns 2

* Trying a custom dns 3

* Trying a custom dns 4

* Trying a custom dns 5

* Trying a custom dns 6

* Trying a custom dns 7

* Addressing PR comments.

* Adding check_apub to all verify functions.

* Reverting back drone.

* Fixing merge

* Fix docker images.

* Adding missing discussion_languages.

* Trying to fix federation tests.

* Fix site setup user creation.

* Fix clippy

* Fix clippy 2

* Test api faster

* Try to fix 1

* Try to fix 2

* What are these lines about

* Trying to fix 3

* Moving federation test back to top.

* Remove logging cat.
2022-11-09 10:05:00 +00:00
Nutomic ceae0f5993
Use urlencoding for db url params (fixes #2532) (#2537) 2022-11-07 21:29:32 -05:00
Nutomic a0a84d91ce
Dont serve apub json for removed objects (ref #2522) (#2538) 2022-11-04 20:57:28 -04:00
Nutomic 50a2233b52
Fix password length check (#2536) 2022-11-04 20:56:38 -04:00
Nutomic 2207fed0f5
Remove explicit panic from db connection code (fixes #2533) (#2535) 2022-11-04 20:53:46 -04:00
Nutomic 9393195827
Send error message when rate limit is reached (#2527)
* Send error message when rate limit is reached

* l18n key
2022-11-03 18:13:40 +00:00
Nutomic 5e871ca7ba
Mark own private messages as read in api (fixes #2484) (#2531) 2022-11-03 13:41:44 -04:00
Nutomic b5cd732372
Mark objects as not deleted when received via apub (fixes #2507) (#2528) 2022-11-03 09:39:30 -04:00
Dessalines cb753b045f
Group imports dess (#2526)
* Group imports with rustfmt

* Running cargo fmt again.

Co-authored-by: Felix Ableitner <me@nutomic.com>
2022-11-02 15:18:22 -04:00
Nutomic 28eade6168
Fix invalid config in docker/prod (fixes #2520) (#2524) 2022-11-02 18:50:09 +00:00
Dessalines ed9e91345a
Fix local site images. (#2519)
* Fix local site images.

* It should be set up.
2022-11-02 12:10:40 +00:00
sam365724 7aa6d6b3e1
Fix 2455: Check auth for pictrs when instance is private. (#2477)
* Fix 2455: Check auth for pictrs when instance is private.

* Update, no utils function, use of existing get_local_user_view_from_jwt

* rustup toolchain install nightly (ftw)
2022-10-28 10:43:33 -04:00
Nutomic 6aa9bdebae
Fix limit_languages to operate on correct instance (fixes #2496) (#2518)
* Fix limit_languages to operate on correct instance (fixes #2496)

* cargo fmt
2022-10-28 10:42:05 -04:00
Nutomic 3b0be52e67
Image improvements (#2513)
* Image improvements

* remove rate limits
2022-10-28 14:34:40 +00:00
Nutomic b0c3185663
Make verify apub url function async (#2514)
* Make verify apub url function async

* cleanup

* use dep from crates.io

* dont use unwrap
2022-10-28 09:38:22 -04:00
Dessalines 235cc8b228
Moving settings to Database. (#2492)
* Moving settings to Database.

- Moves many settings into the database. Fixes #2285
- Adds a local_site and instance table. Fixes #2365 . Fixes #2368
- Separates SQL update an insert forms, to avoid runtime errors.
- Adds TypedBuilder to all the SQL forms, instead of default.

* Fix weird clippy issue.

* Removing extra lines.

* Some fixes from suggestions.

* Fixing apub tests.

* Using instance creation helper function.

* Move forms to their own line.

* Trying to fix local_site_data, still broken.

* Fixing federation tests.

* Trying to fix check features 1.

* Addressing PR comments.

* Adding check_apub to all verify functions.
2022-10-27 09:24:07 +00:00
Nutomic 276a8c2bd3
Enable lto, strip symbols via cargo.toml (#2512) 2022-10-25 15:10:07 +00:00
Dessalines 9ac13a0891
Fix docker dev build (#2509)
* Fixing docker dev build.

* Remove volume mount files.

* Fixing pictrs.

* Addressing PR comments.
2022-10-21 15:13:24 +00:00
Nutomic aaaea2006c
Federate votes as private (#2501) 2022-10-18 03:13:18 +00:00
Nutomic 74bc1198ce
Dont try to send activities if federation is disabled (fixes #2499) (#2500) 2022-10-17 14:29:18 -04:00
Nutomic 0a60bcb8ee
Return empty vec when reading all languages (fixes #2495) (#2497) 2022-10-17 09:37:22 +00:00
Nutomic 04f0f3af0b
Update clippy to use Rust 1.64 (#2498) 2022-10-14 16:09:37 +00:00
Nutomic 6c3e984ad1
Only allow authenticated users to fetch remote objects (#2493)
* Only allow authenticated users to fetch remote objects

* try to fix api tests
2022-10-13 16:30:31 +00:00
sam365724 cb559178bd
More real-world prod config, separate lemmy config (#2487) 2022-10-10 16:06:52 +00:00
Nutomic ec5e63b5a9
Fix check for federated mod actions (#2489) 2022-10-10 11:20:36 -04:00
sam365724 d2608bb279
Make docker-compose more clear and explicit (#2469)
* Make docker-compose more clear, starting with dev

Explicit networks, not opining ports when not necessary: Confusing for users. All requests go through nginx, so there is no need to open ports directly on pictrs and other services for example. I wasn't sure about jaeger and otel, maybe that can be changed somewhat too. 

Also adding comments and things that are relevant for a prod setup too.

* Update with comments

* Providing dedicated nginx and lemmy conf

* Fix config key for pictrs.

* Fix config key for pictrs.

* updates on naming

* Adding docker compose build info

* Revert to more complete lemmy config

* Test and fix build paths

* Fix otel config

* Delete dev file

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2022-10-06 19:01:19 +00:00
Nutomic 2ef0f8f5f8
implement language tags for site/community in db and api (#2434)
* implement language tags for site/community in db and api

* add api checks for valid languages

* during db migration, update existing users, sites, communities to have all languages enabled

* init new users/communities with site languages (not all languages)

* federate site/community languages

* fix tests

* when updating site languages, limit community languages to this subset

also, when making a new post and subset of user lang, community lang
contains only one item, use that as post lang

* add tests for actor_language db functions

* include language list in siteview/communityview

* Fix some of the review comments

* Some more review changes

* Add todo about boxed query

* Add default_post_language to GetCommunityResponse
2022-10-06 14:27:58 -04:00
Nutomic 7bb941e546
Change description in readme (#2481)
* Change description in readme

* Replace Mastodon contact link with Lemmy support forum

* update text

* remove part about unstable api
2022-10-05 12:25:17 -04:00
Nutomic 290acf6acc
Use compat mode when signing outgoing activities (fixes #1984) (#2473) 2022-10-03 13:46:42 -04:00
Dessalines 3f8c28b26f
Check to make sure comment isnt deleted / removed for unread count. (#2472)
- Fixes #2471
2022-09-29 20:52:14 +00:00
Dessalines ee41654394
Dont show deleted users or communities on profile page. (#2450)
* Dont show deleted users or communities on profile page.

- Fixes #2448

* Fix missing communities

* Add include_deleted to resolve_actor_identifier.
2022-09-28 20:54:32 +00:00
Dessalines ae95f5928e
Adding email admins for new applications. Fixes #2271 (#2390)
* Adding email admins for new applications. Fixes #2271

* Fix error.

Co-authored-by: Nutomic <me@nutomic.com>
2022-09-27 12:48:44 -04:00
Dessalines 0aeb78b8f3
Showing # of unread comments for posts. Fixes #2134 (#2393)
* Showing # of unread comments for posts. Fixes #2134

* Fix lint.

* Forgot to remove comment list update.

* Fix clippy
2022-09-27 16:45:46 +00:00
Nutomic f2537ba7db
Convert emails to lowercase (fixes #2462) (#2463) 2022-09-27 12:02:04 -04:00
Dessalines 3c5368d8b1
Remove unnecessary show_deleted_and_removed comments for a profile. (#2458) 2022-09-26 20:02:06 +00:00
Dessalines 2dca80d678
Remove pointless language joins. (#2451)
* Remove pointless language joins.

* Fix test
2022-09-26 15:25:18 +00:00
Dessalines 3adb293541
Fix rate limit error messages. Fixes #2428 (#2449)
* Fix rate limit error messages. Fixes #2428

* Simplify
2022-09-26 10:40:42 -04:00
Dessalines 9ce15ed071
Fix missing local user from post queries. (#2447) 2022-09-26 10:39:22 -04:00
Dessalines c9f1407429
Diesel 2.0.0 upgrade (#2452)
* Initial commit to bump diesel to 2.0.0-rc.0 and see what happens

* Add chrono feature from diesel

* db_schema crate is close to building?

* Upgrade diesel-derive-newtype

* Mostly modifying references to connections to be mutable ones; also used
new way to do migrations as suggested by the migration guide; a lot more
compiles now, though I can't figure out this tricky ToSql issue at the
moment

* Running clippy --fix

* Trying to fix drone clippy 1

* Fix clippy

* Upgrade clux-musl

* Trying to fix drone clippy 2

* Trying to fix drone clippy 3

* Trying to fix drone clippy 5

* Adding diesel table aliases, removing sql view hack. Fixes #2101

Co-authored-by: Steven Chu <stevenc1@gmail.com>
Co-authored-by: Nutomic <me@nutomic.com>
2022-09-26 14:09:32 +00:00
kartikynwa 4e6409f325
Allow filtering out of deleted and removed comments when getting person details (#2446)
undefined
2022-09-20 21:33:33 -04:00
Nutomic 004efd5d94
Implement reports for private messages (#2433)
* Implement reports for private messages

* finish private message report view + test

* implement api for pm reports

* merge list report api calls into one, move report count to site

* fix compile error

* Revert "merge list report api calls into one, move report count to site"

This reverts commit 3bf3b06a705c6bcf2bf20d07e2819b81298790f3.

* add websocket messages for pm report created/resolved

* remove private_message_report_view

* add joinable private_message_report -> person_alias_1

* Address review comments
2022-09-19 22:58:42 +00:00
Dessalines 09246a20fb
Check for slurs in account creation. (#2443) 2022-09-19 19:42:42 +00:00
Dessalines 71aed94a00 Merge branch 'main' of https://github.com/LemmyNet/lemmy 2022-09-14 11:30:44 -04:00
Dessalines 553654b8e8 Add 0.16.7 release notes. 2022-09-14 11:30:40 -04:00
Dessalines a93095ed3f
The language id is crucial for front ends. (#2437) 2022-09-13 21:02:37 +00:00
Dessalines 2f0560ca3f
Update docker version to 0.16.6. Fixes #2435 (#2438) 2022-09-12 09:33:49 +00:00
Dessalines eacd4e44cd
Adding job to drop phantom ccnew indexes. Fixes #2431 (#2432) 2022-09-07 12:12:51 +00:00
Dessalines 3f2a689edf
Don't search for community descriptions, search for user display_name. (#2430)
- https://github.com/LemmyNet/lemmy-ui/issues/756
2022-09-07 08:58:41 +00:00
Dessalines 265dc54627
Increase default search rate limit. (#2424) 2022-09-03 11:37:27 +02:00
Felix Ableitner 0a14b17747 fix clippy 2022-09-02 10:49:54 -04:00
Felix Ableitner 3295784ebb dont set default user languages in api code (already done in db) 2022-09-02 10:49:54 -04:00
Felix Ableitner 095591ef69 dont test with all features 2022-09-02 10:49:54 -04:00
Felix Ableitner 5e8a37ac86 clippy fixes 2022-09-02 10:49:54 -04:00
Felix Ableitner d058e2217a api changes for comment language tagging 2022-09-02 10:49:54 -04:00
Felix Ableitner bc7450ae3e add test for comment view languages 2022-09-02 10:49:54 -04:00
Felix Ableitner f5b1ee6c34 fix tests 2022-09-02 10:49:54 -04:00
Felix Ableitner 3d0d8796ad Add language tags for comments 2022-09-02 10:49:54 -04:00
Nutomic a6dc6804aa
Pass LocalUser to PostQuery etc, instead of separate params (#2413) 2022-08-19 10:27:39 -04:00
Nutomic e4a49b6eab
Tag posts and comments with language (fixes #440) (#2269)
* Tag posts and comments with language (fixes #440)

* Untangle PostView tests

* Implement test for PostView language query

* Store languages directly in database

* finish moving languages into db, it compiles

* update post_view

* serde skip Language.id field

* add local_user_language table, other changes suggested in review

* add code for local_user_discussion_language_view

* Remove unnecessary clones in db view converteres

* Fixing up some table and join issues.

* Clearing the current languages.

* Fix formatting.

* update user languages in single transaction

* proper test for user language queries

* Some fixes for all / missing user languages. (#2404)

* Some fixes for all / missing user languages.

* Adding back in transaction.

* fix test

Co-authored-by: Dessalines <tyhou13@gmx.com>
Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2022-08-18 15:11:19 -04:00
Nutomic c89006c94a
Rejected federated pm from blocked users (fixes #2398) (#2408) 2022-08-17 16:53:19 -04:00
Dessalines 870abf8442
Adding distinguish comment. Fixes #2002 (#2391)
* Adding distinguish comment. Fixes #2002

* Adding lemmy:distinguished
2022-08-17 11:38:52 +00:00
Nutomic 583ceb2506
Fix pictrs routing (#2407)
* SUGGESTED FIX TO PICTRS ROUTING 404 ERROR #2359

Removed slashes at "/image" routes.

* cargo fmt

Co-authored-by: Majid  <72635080+umamawme@users.noreply.github.com>
2022-08-16 11:20:41 -04:00
Dessalines f878151648
Add postgres auto-explain for dev testing. (#2399)
* Add postgres auto-explain for dev testing.

* add newline

* fix indent

Co-authored-by: Nutomic <me@nutomic.com>
2022-08-16 12:22:29 +00:00
Anon 21455d6b73
Add Modlog Filters (#2313)
* Fix crash running locally on windows.

* Add support for filtering mod logs

* Refactor cleanup

* Clippy fix

* Condense match statements

* Clippy fix 2
2022-08-16 11:52:04 +00:00
vpzomtrrfrt 08a797c986
Accept Image objects in attachments (#2394) 2022-08-16 10:12:43 +00:00
Dessalines 2f9d8776ac
Tweaking postgres upgrade script (#2389)
* Tweaking postgres upgrade script

* Removing pointless comments.
2022-08-04 22:03:14 +02:00
Nutomic 8a4d9cc1ba
Use typed-builder crate for queries (#2379)
* Use typed-builder crate for PrivateMessageQuery

* derive builder for all queries

* remove unnecessary clones

* fix tests
2022-08-04 15:30:17 -04:00
Nutomic 7094a0c0a4
Use doku release version (ref #2343) (#2386) 2022-08-02 15:38:19 +02:00
Dessalines 9c3efe32e7
First pass at adding comment trees. (#2362)
* First pass at adding comment trees.

- Extracted comment replies into its own table.
- Added ltree column to comment
- Added parent_id param to GetComments to fetch a tree branch
- No paging / limiting yet

* Adding child_count to comment_aggregates.

* Adding parent comment update counts

* Fix unit tests.

* Comment tree paging mostly done.

* Fix clippy

* Fix drone tests wrong postgres version.

* Fix unit tests.

* Add back in delete in unit test.

* Add postgres upgrade script.

* Fixing some PR comments.

* Move update ltree into Comment::create

* Updating based on comments.

* Fix send soft fail.
2022-07-30 05:55:59 +02:00
Nutomic becb8b4f66
Update apub examples to remove `to` field (ref #2380) (#2382) 2022-07-29 13:30:38 -04:00
Nutomic a85334c675
Handle Like, Undo/Like activities from Mastodon, add tests (fixes #2378) (#2380) 2022-07-29 15:32:12 +02:00
Dessalines 8bfeb4b627
Fix a few form options for diesel. Fixes #2287 (#2376)
* Fix a few form options for diesel. Fixes #2287

* Adding TODO comment.
2022-07-29 15:04:21 +02:00
Nutomic 42eac1560f
Remove docker/pleroma/ folder (#2381) 2022-07-29 08:37:23 -04:00
Dessalines 3b86e15399
Remove listing type community. Fixes #2361 (#2377)
* Remove listing type community. Fixes #2361

* Have ListingType::All be the default
2022-07-29 10:57:39 +00:00
Nutomic b78826c2c8
Dont allow login if account is banned or deleted (fixes #2372) (#2374) 2022-07-28 23:14:07 +02:00
Dessalines c62671116c
Send websocket message on accepted follow. Fixes #2369 (#2375) 2022-07-28 15:49:26 +00:00
Nutomic b9f1fc0518
Fix panics in search_by_apub_id() (fixes #2371) (#2373) 2022-07-27 17:03:44 -04:00
Nutomic eee8f467b5
Fix follow being stuck as pending after accept (#2366)
* Fix follow being stuck as pending after accept

* fix api test
2022-07-20 14:10:29 +00:00
Dessalines 767f1aa0de Adding 0.16.6 release 2022-07-19 15:01:15 -04:00
Nutomic 16fe149a6d
Change config pictrs key name (#2360) 2022-07-14 14:25:10 -04:00
Nutomic d0a3d99636
Config changes, remove unused image purge function (#2343)
* Throw error if old pictrs config item is used, make api key optional

* use doku url feature

* fix doku version

* fix clippy

* remove unused image purge function, remove config migration
2022-07-11 16:38:37 -04:00
Nutomic 63fff96275
Fix problem where actors can have empty public key (fixes #2347) (#2348) 2022-07-11 18:25:33 +00:00
Luna e33736ae47
remove parking_lot (#2350) 2022-07-11 17:12:12 +00:00
Dessalines 67a34adf4b
Revert "Use correct url for activitystreams protocol context (#2326)" (#2351)
This reverts commit dc35ab9c2b.
2022-07-08 10:47:40 +00:00
Dessalines ff026dc3ff
Adding check for requests with no id or name, adding max limit. (#2265)
* Adding check for requests with no id or name, adding max limit.

* Consolidating a few functions.

* Fix page min

* Adding more websocket rate limits.

* Add check to GetCommunity

* Use a default message rate limit check.

* Adding a page and limit checker

* Fix clippy

* Fix clippy again

* Adding check for requests with no id or name, adding max limit.

* Consolidating a few functions.

* Fix page min

* Adding more websocket rate limits.

* Add check to GetCommunity

* Use a default message rate limit check.

* Adding a page and limit checker

* Fix clippy

* Fix clippy again

* Fix limit request.

* Move checks to inside limit_and_offset

* Fixing API tests.

* Change NotFound diesel errors to QueryBuilderError
2022-07-08 10:21:33 +00:00
Nutomic 3ef812660c
Dont allow blocking admin (#2340) 2022-07-05 23:02:54 +00:00
Nutomic ddc9763050
Fix wrong clippy warning in ci (#2339) 2022-07-05 17:41:22 -04:00
Nutomic b7a2677b4d
Be more explicit about returning deleted actors or not (#2335)
* Be more explicit about returning deleted actors or not

* simplify db queries
2022-07-05 17:40:44 -04:00
Nutomic 587a0de8f7
Specify minimum Rust version 1.57 (fixes #2333) (#2334)
* Specify minimum Rust version 1.57 (fixes #2333)

* use latest rust for clippy

* use rust 1.60 for clippy

* no add component

* use official rust docker

* comments
2022-06-28 17:44:55 -04:00
Dessalines a745fa6f43
Remove update and read site config. Fixes #2306 (#2329)
* Remove update and read site config. Fixes #2306

* Removing lazy_static, removing Settings::get()
2022-06-22 20:24:54 +00:00
Dessalines 8af913f583
Don't create or initially follow a default community. Fixes #2317 (#2328)
* Don't create or initially follow a default community. Fixes #2317

* Fix unit tests.
2022-06-22 19:38:27 +00:00
Dessalines 40609549d8
Increase RSS fetch limit to 20. Fixes #2319 (#2327) 2022-06-22 12:30:09 +00:00
Dessalines 92d17639cd
Expose pending 2 (#2282)
* Exposing SubscribedType. Fixes #2281

* Fixing other subscribed fields.

* Fix federation tests

* Add comment about follower row.
2022-06-22 12:05:41 +00:00
Nutomic dc35ab9c2b
Use correct url for activitystreams protocol context (#2326) 2022-06-21 15:27:10 -04:00
Nutomic cd4d235171
Move setting http_fetch_retry_limit into federation block (#2314) 2022-06-14 01:20:30 -04:00
Nutomic c78de25652
Fix length of post_report.original_post_name db field (fixes #2311) (#2315) 2022-06-14 01:20:01 -04:00
Dessalines 4e12e25c59
Adding admin purging of DB items and pictures. #904 #1331 (#1809)
* First pass at adding admin purge. #904 #1331

* Breaking out purge into 4 tables for the 4 purgeable types.

* Using CommunitySafe instead in view

* Fix db_schema features flags.

* Attempting to pass API key.

* Adding pictrs image purging

- Added pictrs_config block, for API_KEY
- Clear out image columns after purging

* Remove the remove_images field from a few of the purge API calls.

* Fix some suggestions by @nutomic.

* Add separate pictrs reqwest client.

* Update defaults.hjson

Co-authored-by: Nutomic <me@nutomic.com>
2022-06-13 19:15:04 +00:00
trwnh 5b7376512f
Fix: Use correctly parseable JSON-LD context (#2299)
* Fix: Use correctly parseable JSON-LD context

* Changed: Better ordering for context document

alphabetized properties

* Changed: Use xsd types instead of schema.org types

* Changed: use simple namespacing
2022-06-13 13:26:56 +00:00
Nutomic a29cf04092
Fix lemmy version in prod docker-compose.yml (#2304) 2022-06-08 11:48:36 -04:00
Nutomic fcaf7a084c
Upgrade activitypub_federation to 0.2.0, add setting federation.debug (#2300) 2022-06-08 11:45:39 -04:00
Nutomic 7bc2f9fd6d
Remove unused setup config vars (#2302) 2022-06-08 11:44:53 -04:00
Nutomic c050945b1f
Add pub use for db crates in api_common (#2305) 2022-06-08 11:30:20 -04:00
Nutomic 23819d44f3
Add link to Matrix chat in readme (#2303) 2022-06-08 11:19:12 -04:00
Nutomic 7804a9d893
Accept private like (#1968) (#2301) 2022-06-08 11:14:38 -04:00
Dessalines 916c53ccec
Move different features drone check to below defaults.hjson check. (#2296) 2022-06-06 12:09:43 +00:00
Paolo Barbolini 0a3b69a259
Bump lettre to 0.10.0-rc.7 (#2297) 2022-06-04 22:07:38 -04:00
Nutomic 780832256c
Remove unused cargo.toml files (#2293) 2022-06-03 15:56:33 +00:00
Nutomic 5387c262c1
Forbid outgoing requests in activitypub tests (fixes #2289) (#2294) 2022-06-03 11:31:22 -04:00
Nutomic 339eab01fd
Embed Peertube videos (#2261)
* Use og:video attribute for embeds, change Post.embed_html to embed_url

* fix clippy
2022-06-02 21:44:47 +00:00
Nutomic 9a458d2e4b
Run cargo check for each crate with different features (ref #2284) (#2292) 2022-06-02 18:19:53 +00:00
Nutomic 13ca1111c4
Remove 0.15 federation compat code (#2131) 2022-06-02 13:48:53 -04:00
Nutomic a2a594b763
Extract Activitypub logic into separate library (#2288)
* Create example for apub lib

* some rewriting of apub lib

* Add LocalInstance struct for apub lib to avoid using Lemmy Settings

* Move ActorType trait to lemmy_apub, because its not needed in library

* Use reqwest_retry instead of custom impl, dont specify timeout on every send()

* Some improvements to example

* Moved inbox handling to library

* bug fixes

* Move context and serde helpers into library

* wip: example changes

* Add lemmy_utils feature to build only LemmyError

* Rename to activitypub_federation

* Remove lemmy_utils dep from activitypub_federation using generic error type

* Finish activitypub example

* Cleanup and fix tests

* Reorganize library files

* Remove ApubObject.to_tombstone()

* Extract activitypub library into separate git repository
2022-06-02 16:33:41 +02:00
Dessalines 1bd57ee5ca Version 0.16.5 2022-05-30 18:32:31 -04:00
Dessalines 9b9b7b16c8 Merge branch 'main' of https://github.com/LemmyNet/lemmy 2022-05-27 09:49:40 -04:00
Dessalines 09454f3e49 Update releases.md 2022-05-27 09:48:11 -04:00
Nutomic 205b4a22a8
Merge pull request #2284 from LemmyNet/fix_publish
Fix publish
2022-05-27 11:21:49 +00:00
Dessalines 69106589ba Fix publish 2022-05-26 16:10:36 -04:00
Dessalines eafb3869f2
Revert "Add pending, and change use specific API response for FollowCommunity…" (#2283) 2022-05-26 11:17:04 -04:00
Nutomic 3af4a27a88
Merge pull request #2248 from LemmyNet/expose_pending
Add pending, and change use specific API response for FollowCommunity…
2022-05-20 16:31:56 +00:00
Dessalines 3c111b3062 Dropping default on pending column. 2022-05-20 16:15:14 +00:00
Dessalines d4ee171b08 Making community_follower.pending column not null. 2022-05-20 16:15:14 +00:00
Dessalines 763dc9668c Fix formatting. 2022-05-20 16:15:14 +00:00
Dessalines e6fe9d0325 Fixing unfollow 2022-05-20 16:15:14 +00:00
Dessalines ed9b66541e Fixing API tests. 2022-05-20 16:15:14 +00:00
Dessalines 48f5a2ee5e Add pending, and change use specific API response for FollowCommunity. Fixes #2246 2022-05-20 16:15:14 +00:00
Nutomic 7566f325cd
Downgrade Rust Docker images to 1.59 to fix CI failures (ref #2263) (#2274) 2022-05-20 13:29:04 +00:00
Nutomic 9ef0efa420
Add legal information (fixes #721) (#2273) 2022-05-19 20:32:40 +00:00
Nutomic 60e9586530
Add drone task for nightly build (#2264) 2022-05-19 20:30:16 +00:00
Dessalines be246425f0
Merge pull request #2267 from LemmyNet/update-image
Update image crate
2022-05-17 14:03:07 -04:00
Felix Ableitner 426e1b1e51 Update image crate 2022-05-17 13:48:47 -04:00
Dessalines 144336b8b1
Merge pull request #2263 from LemmyNet/fix-ci-unsafe-repo
Fix CI failures
2022-05-17 13:44:09 -04:00
Felix Ableitner 562b88da9e Remove youtube metadata test 2022-05-17 16:26:36 +02:00
Felix Ableitner 26d5b38115 Fix CI failures 2022-05-16 13:50:41 +02:00
Nutomic 91d1d5f7ff
Merge pull request #2260 from LemmyNet/fix_email_param_order
Fixing malformed rosetta translations. Fixes #2231
2022-05-16 10:58:58 +00:00
Dessalines 5eb0dfdc73 Fixing malformed rosetta translations. Fixes #2231 2022-05-13 12:24:29 -04:00
Nutomic bd9df834f5
Merge pull request #2253 from LemmyNet/optional-opentelemetry
Make opentelemetry dependency optional
2022-05-11 12:54:21 +00:00
Felix Ableitner 80684de7da Make opentelemetry dependency optional 2022-05-11 14:29:01 +02:00
Nutomic f0ec3015cd
Remove check that avatars/banners are locally hosted (fixes #2254) (#2255) 2022-05-10 17:08:13 +00:00
Nutomic 99f3141841
Update to Rust 1.60 (#2247) 2022-05-10 17:04:40 +00:00
Paolo Barbolini ef12cd9588
Bump lettre to 0.10.0-rc.6 (#2250) 2022-05-09 23:08:13 +00:00
Paolo Barbolini 559e43075a
Simplify building plain/html emails (#2251) 2022-05-08 17:00:12 +00:00
Nutomic 7b86441bab
Federate with Peertube (#2244) 2022-05-06 23:53:33 +00:00
Nutomic 3053e14be7
Derive default for api request structs, move type enums (#2245)
* Derive default for api request structs, move type enums

* Simplify api by using enum types directly, instead of string

* Add default and clone for most api structs
2022-05-06 20:55:07 +00:00
Nutomic 3aa3d75a1e
Add cargo feature for building lemmy_api_common with mininum deps (#2243) 2022-05-03 17:44:13 +00:00
Nutomic dd5835fb6e
Add restricted community field to CreateCommunity, UpdateCommunity (ref #2235) (#2242) 2022-04-29 14:01:10 +00:00
Nutomic 7058cfa1cf
Implement restricted community (only mods can post) (fixes #187) (#2235)
* Implement restricted community (only mods can post) (fixes #187)

* review fixes

* fix tests
2022-04-28 20:32:32 +00:00
Rens Groothuijsen 9c1b9ff3cf
Update community statistics after post or comment is deleted by user (#2193)
* Update community statistics after post or comment is deleted by user

* Update triggers for site and person aggregates

* Restore comment counts when post is restored

* Simplify insertion/deletion trigger checks before updating statistics
2022-04-27 16:12:41 +00:00
Nutomic c718882479
Accept comments with hashtags from Friendica (#2236) 2022-04-27 16:12:13 +00:00
Nutomic 2e01e8e42c
Remove unused dependencies (#2239) 2022-04-27 17:56:05 +02:00
Nutomic 56b7030901
Fix link metadata unit test (#2237) 2022-04-27 15:42:10 +00:00
Nutomic 3488b9aeb5
Dont return "admin" for GET user when no id/name is provided (fixes #1546) (#2233) 2022-04-25 21:16:29 +00:00
Nutomic ae84258c41
Federation: dont overwrite local object from Announce activity (#2232)
* Federation: dont overwrite local object from Announce activity (fixes #2143)

* add missing form fields

* refactoring

* add ap_id, updated fields

* fix
2022-04-25 21:11:34 +00:00
Nutomic 7e13406979
Require registration application by default (#2229) 2022-04-19 19:13:20 +00:00
Nutomic 00b0b26dfa
Add default post listing type (fixes #2195) (#2209)
* Add default post listing type (fixes #2195)

* review fixes

* change column type
2022-04-19 19:05:08 +00:00
Dessalines 24be9f2cd5
Show deny reason to users after a failed login. Fixes #2191 (#2206)
* Show deny reason to users after a failed login. Fixes #2191

* Updating translations.

* Adding registration_denied translated string.
2022-04-19 10:48:59 +00:00
Dessalines 0a36b16e29
Fix allowlist / blocklist description location. Fixes #2214 (#2215)
* Fix allowlist / blocklist description location. Fixes #2214

* Fix allowlist check
2022-04-13 18:27:56 +00:00
Nutomic 3951a16447
Split apart api files (#2216) 2022-04-13 18:12:25 +00:00
Nutomic ce4682caa0
Merge pull request #2213 from LemmyNet/change_default_listing_type
Changing default listing type to Local from Subscribed.
2022-04-13 17:48:47 +00:00
Dessalines 0372029e8d Changing default listing type to Local from Subscribed. 2022-04-13 17:35:21 +00:00
Nutomic e0381df88a
Expose remote site info in GetCommunity API (fixes #2208) (#2210)
* Expose remote site info in GetCommunity API (fixes #2208)

* use instance_actor_id_from_url()
2022-04-13 16:37:54 +00:00
Dessalines 3d8709780a
Fixing unstable post sorts. Fixes #2188 (#2204) 2022-04-13 15:33:38 +00:00
Dessalines 0d9b756b75
Adding lemmy_ui_debug for future debug testing. (#2211)
Co-authored-by: Nutomic <me@nutomic.com>
2022-04-13 11:53:21 +00:00
Dessalines 2985e88a49
Fixing generate unique changeme (#2205)
* Fixing generate unique changeme

* Fixing generate unique changeme 2

* Changing link to .invalid domain.

Co-authored-by: Nutomic <me@nutomic.com>
2022-04-13 11:13:29 +00:00
Nutomic bbd739af9b
Change Person, Instance types (#2200) 2022-04-12 17:10:35 +00:00
Nutomic 2180bd0369
Merge pull request #2207 from LemmyNet/clippy_fix_2
Clippy fixes.
2022-04-12 10:16:10 +00:00
Nutomic b47a474863
Merge branch 'main' into clippy_fix_2 2022-04-12 10:03:40 +00:00
Nutomic fed73a72c1
Write mod log for federated sticky/lock post actions (#2203) 2022-04-11 23:03:31 +00:00
Dessalines 0bcdfa8be4 Clippy fixes. 2022-04-11 18:51:11 -04:00
Dessalines a7540bd59f Adding 0.16.3 release. 2022-04-08 13:09:17 -04:00
Dessalines c232564fda Version 0.16.3 2022-04-08 10:20:31 -04:00
Dessalines 4878848955 Version 0.16.3-rc.1 2022-04-08 09:17:00 -04:00
Dessalines 4052900d30 Updating translations 2022-04-08 09:13:46 -04:00
Nutomic 8337eaefdd
Federate user account deletion (fixes #1284) (#2199) 2022-04-07 20:52:17 +00:00
Nutomic 9ac1f46a2b
Dont federate initial upvote (#2196) 2022-04-07 20:46:10 +00:00
Nutomic f9d563d80a
Add missing mod log entries for federated actions (fixes #1489) (#2198) 2022-04-07 20:44:28 +00:00
Nutomic b41f7f3eca
Merge pull request #2192 from LemmyNet/mandatory_questionnaire
Make sure application questionaire is required. Fixes #2189
2022-04-05 10:47:59 +00:00
Nutomic 1e2d2ecbae
Merge branch 'main' into mandatory_questionnaire 2022-04-05 10:36:13 +00:00
Nutomic b5d0a9322a
Merge pull request #2194 from LemmyNet/upgrade_pictrs_8
Upgrading pictrs.
2022-04-05 10:26:00 +00:00
Dessalines ef08870ce5 Upgrading pictrs. 2022-04-04 21:31:17 -04:00
Dessalines 37c834725c Make sure application questionaire is required. Fixes #2189
Also fix local image domain check. Was failing for blank strings /
replaces.
2022-04-04 20:58:50 +00:00
Nutomic 65cac21713
Fix verify_mod_action check for remote admin actions (#2190)
* Fix verify_mod_action check for remote admin actions

* fix federation test
2022-04-04 14:46:49 +00:00
Nutomic c7f5337099
Run cargo upgrade (#2176)
* Run cargo upgrade and cargo update

* Fixing validation (#2179)

Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2022-04-01 18:37:51 +00:00
Nutomic bfae246734
Migrate towards using page.attachment field for url (ref #2144) (#2182) 2022-04-01 18:25:19 +00:00
Nutomic 56b275acd4
Exclude removed/deleted posts from community outbox (#2184) 2022-04-01 18:18:25 +00:00
Nutomic 589d952a95
Fetch community outbox in parallel (fixes #2180) (#2181) 2022-04-01 18:06:23 +00:00
Nutomic 4597ea2017
Merge pull request #2178 from LemmyNet/fix_ban_expires
Adding a ban expires update job. Fixes #2177
2022-03-31 12:05:17 +00:00
Dessalines 4cf0da7b60 Clippy fixes. 2022-03-30 10:58:03 -04:00
Dessalines 3ad172e8ed Adding a ban expires update job. Fixes #2177 2022-03-30 09:56:23 -04:00
Nutomic ad7e6d99ed
Add email translations (#2175) 2022-03-29 18:23:03 +00:00
Dessalines 2e65b31aa6
Fix arm submodule (#2174) 2022-03-29 18:05:18 +00:00
Dessalines d5a213760d Version 0.16.2 2022-03-29 12:56:21 -04:00
Dessalines 11b7525c41
Add update translations script. (#2173) 2022-03-29 16:54:16 +00:00
Dessalines f7fa1f10f9 Updating translations. 2022-03-29 12:07:39 -04:00
Dessalines 7bb8069224 Version 0.16.2-rc.3 2022-03-29 11:54:13 -04:00
Nutomic 610120067c
Add test files for Friendica federation (fixes #2144) (#2167) 2022-03-29 15:48:29 +00:00
Dessalines e16821116e
Lowering search rate limit. Fixes #2153 (#2154)
* Lowering search rate limit. Fixes #2153

* Adding a search rate limit.

* Forgot to add the websocket search rate limit

* Fix wrong op
2022-03-29 15:46:03 +00:00
Dessalines f6b543ae0f
Add tag to lemmy-ansible. (#2172) 2022-03-29 15:36:59 +00:00
Dessalines 052e509954
Fixing release script. (#2170) 2022-03-29 15:23:39 +00:00
Dessalines d49565e030
Rate limit ws joins (#2171)
* Removing async on mutex lock fn.

* Removing redundant ip

* Don't check rate limit twice.
2022-03-28 20:31:35 +00:00
Nutomic f21f2fd7b0
Delete unused diesel.toml file (#2166) 2022-03-28 18:29:11 +00:00
Dessalines a11b5b107d Version 0.16.2-rc.2 2022-03-26 21:37:12 -04:00
Dessalines f2a0841586
Rate limit websocket joins. (#2165)
* Rate limit websocket joins.

* Removing async on mutex lock fn.

* Removing redundant ip

* Return early if check fails.
2022-03-27 00:29:05 +00:00
Dessalines 483e7ab168
Doing tests in sequential order. Fixes #2158 (#2163)
* Doing tests in sequential order. Fixes #2158

* Doing tests in sequential order. Fixes #2158

* Fixing order 1
2022-03-25 19:00:33 +00:00
Nutomic a5ff629b24
Dont log errors when rate limit is hit (fixes #2157) (#2161)
* Dont log errors when rate limit is hit (fixes #2157)

* Clone service rather than http request

* some cleanup/refactoring

Co-authored-by: Aode (Lion) <asonix@asonix.dog>
2022-03-25 16:41:38 +01:00
Dessalines c681bb79b1 Version 0.16.2-rc.1 2022-03-24 18:25:21 -04:00
Nutomic e208f0cb4d
Merge pull request #2160 from LemmyNet/rate_limit_websocket_fail
Fix rate limit check for register. Fixes #2159
2022-03-24 21:43:02 +01:00
Dessalines 2da0684e95 Removing check_only 2022-03-24 16:29:08 -04:00
Dessalines ed9f70276d Fix rate limit check for register. Fixes #2159 2022-03-24 16:13:58 -04:00
Nutomic dfb0938738
GNU social compatibility (#2100)
* Use SourceCompat everywhere (better compat with other software)

* Name field should not be mandatory in Group

* also check page.cc field for community id

* add gnu social tests

* better to use option<sourcecompat>

* update gnu social tests, marked vote as "unlisted"
2022-03-24 16:33:42 +00:00
Dessalines 1e9f609cdb
Consolidate and lower reqwest timeouts. Fixes #2150 (#2151) 2022-03-24 16:33:23 +00:00
Nutomic 83e996111e
Check that config is valid before saving (#2152) 2022-03-24 16:23:12 +00:00
Nutomic b406342a14
Dont log error if duplicate activity is received (fixes #2146) (#2148) 2022-03-24 16:05:27 +00:00
Nutomic cb44b14717
WIP: Email localization (fixes #500) (#2053)
* Allow email localization (fixes #500)

* add PersonAggregates::default()

* add lemmy-translations submodule

* fix gitmodules
2022-03-24 15:25:51 +00:00
Nutomic ecd157d4a7
Update pictrs to 0.3.0-rc.7 (#2149) 2022-03-24 01:57:40 +00:00
Nutomic 01cdac012f
Merge pull request #2139 from LemmyNet/add_jerboa_link
Add jerboa link to readme. Fixes #2137
2022-03-23 21:48:25 +00:00
Nutomic 6616e89bcf
Merge branch 'main' into add_jerboa_link 2022-03-23 21:33:07 +00:00
Nutomic 8112816e99
If viewed actor isnt in db, fetch it from other instance (#2145) 2022-03-23 21:27:51 +00:00
Nutomic 0c63dbafb6
Merge pull request #2138 from LemmyNet/rate_limit_algorithm_desc
Show rate limit algorithm. Fixes #2136
2022-03-23 14:48:09 +00:00
Nutomic 0d0772a48a
Merge branch 'main' into rate_limit_algorithm_desc 2022-03-23 14:33:03 +00:00
Nutomic cda93e08d8
Merge branch 'main' into add_jerboa_link 2022-03-23 14:30:06 +00:00
Nutomic 7be5fa4a47
Merge pull request #2147 from LemmyNet/fixing_api_tests_1
Fixing api tests 1
2022-03-23 14:29:46 +00:00
Dessalines 500ca15893 Trying to fix api tests 2 2022-03-22 18:06:59 -04:00
Dessalines 5698dd7771 Trying to fix api tests 1 2022-03-22 15:50:47 -04:00
Dessalines 4e6d901649 Show rate limit algorithm. Fixes #2136 2022-03-22 18:45:14 +00:00
Nutomic a10bf7d410
Adjust retry interval for sending activities (#2141) 2022-03-22 18:40:40 +00:00
Dessalines 5a245659c8 Add jerboa link to readme. Fixes #2137 2022-03-22 18:32:50 +00:00
Dessalines 5265f6100e Restore prod docker-compose.yml 2022-03-19 12:21:07 -04:00
Nutomic bcf7ec6109
Forbid remote URLs for avatars/banners (fixes #1618) (#2132) 2022-03-18 15:46:58 +00:00
Nutomic 611d336f94
Remove docker/prod unused files (fixes #2086) (#2133) 2022-03-17 16:28:35 +00:00
Nutomic 166ec196b0
Rework error handling (fixes #1714) (#2135) 2022-03-16 20:11:49 +00:00
Dessalines d3d4e76a19 Adding release notes. 2022-03-15 17:29:05 -04:00
Dessalines 514e2301b5 Version 0.16.1 2022-03-15 17:23:16 -04:00
Dessalines 9fd6a48e3c Version 0.16.1-rc.1 2022-03-15 16:52:37 -04:00
Nutomic 7d61616dff
Revert "Add logging to debug federation issues (ref #2096) (#2099)" (#2130)
This reverts commit e094989a4c.
2022-03-14 20:18:19 +00:00
Nutomic 550a93aed9
Dont allow admin to add mod to remote community (#2129) 2022-03-14 18:35:57 +00:00
Nutomic f8fb3b41f0
Reject federated downvotes if downvotes are disabled (fixes #2124) (#2128) 2022-03-14 18:20:18 +00:00
Dessalines 71237f1b53 Add Release notes. 2022-03-08 13:54:25 -05:00
Dessalines 05f20da51f Version 0.16.0 2022-03-08 13:45:01 -05:00
Dessalines 82dec1911f Version 0.16.0-rc.4 2022-03-08 08:57:57 -05:00
Nutomic 660efd1549
Correctly read local SiteView (#2122) 2022-03-08 12:52:33 +00:00
Dessalines 15ff832c4a Version 0.16.0-rc.3 2022-03-07 18:59:29 -05:00
Nutomic 3c5275638f
Increase default worker count (#2120) 2022-03-07 22:28:50 +00:00
Dessalines ffd2ba5d90
Fix community rss. Fixes #2116 (#2119)
Co-authored-by: Nutomic <me@nutomic.com>
2022-03-07 21:49:02 +00:00
Nutomic fbadb2d7bd
Try to fix federation test on ci (#2121) 2022-03-07 21:25:34 +00:00
Dessalines aef2abb962 Version 0.16.0-rc.2 2022-03-03 14:40:09 -05:00
Nutomic df757f28b4
Make delete activities backwards compatible with 0.15 (#2114) 2022-03-03 19:37:12 +00:00
Nutomic ef1e164cc5
Make activity queue worker count configurable, log stats (#2113) 2022-03-03 18:54:33 +00:00
Nutomic fa29ffade1
Add timeout for sending activities (#2112)
* Add timeout for sending activities

* Also set request timeouts in utils/src/request.rs
2022-03-03 13:40:10 -05:00
Nutomic 46e937d6e6
Merge pull request #2115 from LemmyNet/fix_tests_1
Fixing unit tests.
2022-03-03 18:13:09 +00:00
Dessalines a5433ebf77 Fixing unit tests. 2022-03-03 12:51:55 -05:00
Nutomic 0d957a2a27
Merge pull request #2111 from robjtede/aw4
Update `actix-*` dependencies to stable v4.
2022-03-02 20:59:51 +00:00
Rob Ede e3153df74d
Remove direct `actix-http` dependency 2022-03-02 18:11:05 +00:00
Rob Ede b06f3eb32e
Update `actix-*` dependencies to stable v4. 2022-03-02 18:00:52 +00:00
Dessalines 1b5037e92d Version 0.16.0-rc.1 2022-03-02 12:41:11 -05:00
dayinjing bc3927a9bd
Show nsfw communities if you are logged in and searching communities (#2105)
* Show nsfw communities in logged in and you've enabled nsfw in your profile atleast

* Reuse existing user check

Co-authored-by: Sun Wukong <monkey@king.com>
2022-03-02 17:39:27 +00:00
Nutomic 63565712ad
Fix resending activities (fixes #1282) (#2109) 2022-03-01 13:40:05 -05:00
Nutomic fb4c47d602
Dont hardcode site id in Site::update (#2110) 2022-03-01 17:01:23 +00:00
RedLobster999 348077c3de
send plain-text in email along with html (#2107)
* send plain text in email along with html

* format the code using "cargo +nightly fmt"

Co-authored-by: kittiphat-kang <kittiphat.nu@easysunday.com>
2022-03-01 14:28:18 +00:00
Nutomic 9f5183fe98
Add site option for default theme (#2104) 2022-02-23 11:40:36 -05:00
dayinjing 7f9b55e793
Hide community v2 (#2055)
* Initial working of hiding communities and adding a db entry for mod log

* Return mod log for hidden communities

* Clean up hidding communities PR

* use lower case like other migration files

* Formatting fix

* pass in admin id to list, make match logic the same in post_view as community_view. Dont force non null for reason

* Clean PR review stuff

* Change person_id to mod_person_id on hide community table

* Make bools optional, add a space for formating

Co-authored-by: Thor Odinson <odinson@asgard.com>
Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2022-02-18 02:30:47 +00:00
Nutomic 762b85b27e
Reorganize federation tests (#2092)
* Reorganize apub protocol tests

* Reorder apub protocol struct members to clarify mandatory/optional fields
2022-02-17 22:04:01 +00:00
Nutomic e094989a4c
Add logging to debug federation issues (ref #2096) (#2099) 2022-02-17 18:48:45 +00:00
Dessalines 81aa39ba68
Adding a reqwest timeout. Fixes #2089 (#2097) 2022-02-15 12:53:57 +00:00
Nutomic 5a8c894359
Upgrade to Rust 2021 edition (#2093)
Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2022-02-14 15:34:54 +00:00
Nutomic 788924d7ff
Merge different delete activities for better compatibility (fixes #2066) (#2073) 2022-02-14 10:14:24 -05:00
Nutomic dd865c5af5
Implement instance actor (#1798)
* Implement instance actor

* wip: make site bans federate

* finish implementation and unit tests for federated bans

* start adding api tests

* fix api test

* remve site from GetCommunityResponse

* only federate site bans originating from user's home instance

* dont expose site.private_key in api
2022-02-07 19:23:12 +00:00
Nutomic f1aef63149
Use doku(skip) for opentelemetry_url config value (ref #2085) (#2091) 2022-02-07 10:39:37 -05:00
Riley 51fd3e7f77
Merge pull request #2085 from LemmyNet/asonix/document-opentelemetry-url
Add comment about opentelemetry_url
2022-02-04 21:46:38 -06:00
Riley 6b500f6cf2
Merge branch 'main' into asonix/document-opentelemetry-url 2022-02-04 21:22:27 -06:00
Riley 0f8caac689
Merge pull request #2087 from LemmyNet/asonix/console-feature
Add console feature flag, not default
2022-02-04 21:22:07 -06:00
Aode (Lion) 14b27b8377 Merge remote-tracking branch 'lemmynet/fix_sitemetadata_test' into asonix/console-feature 2022-02-04 20:37:57 -06:00
Aode (Lion) 1546e5fd0d Merge remote-tracking branch 'lemmynet/fix_sitemetadata_test' into asonix/document-opentelemetry-url 2022-02-04 20:37:38 -06:00
Dessalines 609d2b99f7 Fix site metadata test. 2022-02-04 18:22:43 -05:00
Aode (lion) 2e5746b74f Add console feature flag, not default
The most recent tracing-core changed the number of variants on metadata::Kind,
which broke console-api 0.1.1, and no fix has been applied yet. To avoid build
failures, disable console-subscriber for now
2022-02-04 11:31:38 -06:00
Aode (lion) 6058b11f6e Add comment about opentelemetry_url 2022-02-03 17:24:19 -06:00
Dessalines 6b1894faf0
Alpha-ordering community follows. Fixes #2062 (#2079) 2022-02-01 20:00:54 +00:00
Dessalines 2ac6e1a463
Adding a test comment. (#2081) 2022-02-01 18:19:07 +00:00
Dessalines d71e1c06e2
Adding codeowners. (#2080) 2022-02-01 16:37:30 +00:00
Nutomic 2fa47aaef9
Remove commit hook (#2078) 2022-01-31 19:20:31 -05:00
Nutomic 7560e0ec8e
Dont update default config in commit hook (#2075) 2022-01-29 18:50:56 -05:00
Nutomic 545fe8d0dd
Add federation tests for Friendica, improve parsing of source field (fixes #2057) (#2070) 2022-01-28 16:47:34 -05:00
Dessalines a8d17c7847
Update issue templates (#2069) 2022-01-27 16:32:12 -05:00
Dessalines 18f63f0f01 Updating releases.md 2022-01-27 14:11:38 -05:00
Nutomic 4a23ee4d8b
Dont make webfinger request when viewing community/user profile (fixes #1896) (#2049) 2022-01-27 16:39:22 +00:00
Dessalines d83a53e905
Fixing private instance check. Fixes #2064 (#2065) 2022-01-27 16:25:22 +00:00
Kradyz 1c5c02e1bf
Case-insensitive username at login (#2010)
* Case-insensitive username at login

* formatting

Co-authored-by: Kradyz <k@radiz.nl>
2022-01-26 18:05:07 +00:00
Dessalines e36ad9d984
Removing the site creator, adding leave_admin. Fixes #1808 (#2052)
* Removing the site creator, adding leave_admin. Fixes #1808

* Making sure there's at least one admin. Fixing unit tests
2022-01-26 17:57:16 +00:00
Dessalines 1372827b41
Adding starttls support. Fixes #1997 (#2051)
* Adding starttls support. Fixes #1997

* Change name to tls_type, make a string
2022-01-26 16:42:43 +00:00
Nutomic 2544341e47
Put community last in webfinger response (fixes #2037) (#2047) 2022-01-21 21:00:17 +00:00
Nutomic 16f98261f8
Dont check for ban in MarkCommentAsRead (fixes #2045) (#2054) 2022-01-21 14:46:43 -05:00
Dessalines 16271b0a4c
Empty post bodies (#2050)
* Cleaning optional post bodies. Fixes #2039

* Only trim once.

* Using .map() instead.

* Revert "Using .map() instead."

This reverts commit a2f49072095e0c0622c4a7d041dcea81e11fe1dc.
2022-01-21 13:38:01 +00:00
Nutomic f23fed70bc
Add tombstone tests, better test errors (#2046) 2022-01-20 14:13:29 +00:00
vpzomtrrfrt 272dc3e7a6
Accept single object as to for arrays too (#2048) 2022-01-20 14:12:45 +00:00
Dessalines 19ccaf767c
Cleaning optional post bodies. Fixes #2039 (#2043)
* Cleaning optional post bodies. Fixes #2039

* Only trim once.

* Using .map() instead.
2022-01-20 14:04:54 +00:00
Dessalines a212f6b780
Fixing liking comment on blocked person. Fixes #2033 (#2042) 2022-01-19 14:17:18 +00:00
Nutomic eea3308906
Add tests for lotide federation, make lotide groups fetchable (#2035)
* Add tests for lotide federation, make lotide groups fetchable

* Accept posts using Note type (and better error messages for tests)
2022-01-17 09:40:47 -05:00
Riley bc8ed1e6da
Remove unneeded dependency on activitystreams (#2034) 2022-01-13 00:17:00 +00:00
Dessalines 55bb68f6f9 Updating readme. 2022-01-12 09:52:21 -05:00
Dessalines f53902ecff Version 0.15.1 2022-01-12 09:45:29 -05:00
Dessalines 46e6affd54 Adding v0.15.0 release notes. 2022-01-12 09:22:38 -05:00
Dessalines bccb4f068d Version 0.15.0 2022-01-12 08:46:35 -05:00
Marty a860e22b85
uses compatable images - fixes GLIBC_2.29 not found issue on (at least) arm machines (#2028) 2022-01-10 10:48:55 -05:00
Dessalines a24676e629 Version 0.15.0-rc.7 2022-01-09 11:09:03 -05:00
Dessalines e65c45f152
Adding temporary bans. Fixes #1423 (#1999)
* Adding temporary bans. Fixes #1423

* Adding ban_expires to person

* Fix clippy

* Removing ban_expires from federated fields.

* Trying to add expires to blockcommunity apub.
2022-01-08 12:37:07 +00:00
Riley 41b90bb162
Add console-subscriber (#2003)
* Add console-subscriber

* Add larg event buffer capacity

* Add console port to lemmy prod container

* Expose pict-rs console port

* Update pictrs
2022-01-07 09:53:45 -05:00
Riley 3032a2745b
Opentelemetry (#1992)
* Add otlp export

* Add jaeger to dev docker

* More instrument

* Update deps

* Merge from main.

* Add comment about viewing traces

* Fixing reqwest-tracing dep.

* Update pre-commit regex

* Move imports to top

Co-authored-by: Dessalines <tyhou13@gmx.com>
Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2022-01-06 19:10:20 +00:00
Rens Groothuijsen 661f97a073
Use correct encoding when fetching non-UTF-8 site metadata (#2015)
* Use correct encoding when fetching non-UTF-8 site metadata

* Style fixes
2022-01-06 13:13:17 +00:00
Nutomic e864685759
Merge pull request #1927 from LemmyNet/add_banned_persons_endpoint
Adding a banned endpoint for admins. Removing it from GetSite. Fixes …
2022-01-05 14:04:26 +00:00
Dessalines bd31475dba Adding a banned endpoint for admins. Removing it from GetSite. Fixes #1806 2022-01-04 09:50:30 -05:00
Nutomic b733df2903
Merge pull request #2016 from robjtede/aw-b18
Updated actix-web dependency to `4.0.0-beta.18`
2022-01-04 14:40:54 +00:00
Rob Ede 1943bcd7f5
Prevent panic on InboxRequestGuard 2021-12-30 18:41:35 +00:00
Rob Ede f6c13cf313
Updated actix-web dependency to `4.0.0-beta.18` 2021-12-30 18:37:59 +00:00
Dessalines 3065154f4e
Merge pull request #2007 from LemmyNet/another_tokenizer_fix
Trying another tokenizer fix. #1964
2021-12-21 17:24:44 -05:00
Kradyz 9f64872d5a
Case-insensitive webfinger response. Fixes #1955 & #1986 (#2005)
* Make webfinger case insensitive

* Make webfinger case insensitive

* Case insensitive domain name

* Case-insensitive webfinger

* formatting

Co-authored-by: Kradyz <k@radiz.nl>
2021-12-20 17:23:06 -05:00
Dessalines ad4715c2a3 Trying another tokenizer fix. #1964 2021-12-20 16:57:36 -05:00
Dessalines c883a49a40
First pass at invite-only migration. (#1949)
* First pass at invite-only migration.

* Implement email verification (fixes #219)

* remove unwrap

* Adding views and functionality to registration application. #209

* Add private instance site column, and back end checks.

* Adding some message fields to LoginResponse

* Adding private instance to site setup.

* A few additions:

- Add a DeleteAccount response.
- RegistrationApplicationView now has the safe LocalUserSettings.
- Adding VerifyEmail to websocket API, added a proper response type.

* Adding and reorganizing some email helpers.

* A few fixes for private sites:

- Added a check_registration_application function.
- Only send a verification email if its been changed.
- VerifyEmail now returns LoginResponse.
- Deleting the old tokens after a successful email verify.
- If port is missing on email config, display a better error message.

* Version 0.15.0-rc.3

* Adding published to email_verification table.

* Adding fixes from comments.

* Version 0.15.0-rc.4

* Adding modlog private site check.

* Version 0.15.0-rc.6

Co-authored-by: Felix Ableitner <me@nutomic.com>
2021-12-15 14:49:59 -05:00
Dessalines 1410c5659c
Upgrading deps (#1995) 2021-12-14 13:30:37 +00:00
Dessalines 1880d64235
Upgrading pictrs. (#1996) 2021-12-14 13:24:33 +00:00
Dessalines 4a46dc805f
Trying out an upgraded version of html5ever. #1964 (#1991)
* Trying out an upgraded version of html5ever. #1964

* New release of webpage.
2021-12-12 23:49:25 +00:00
Dessalines 161d41999d
Adding min setup password length to the docs. Fixes #1989 (#1990) 2021-12-12 16:42:24 +00:00
Nutomic c6ac606f60
Test pleroma follow (#1988)
* Add test case for Pleroma follow activity (ref #1984)

* Use WithContext in apub tests where possible
2021-12-11 21:39:18 -05:00
Riley 0ed3856ef1
Remove awc (#1979)
* Remove unused awc dep

* Replace awc pict-rs client with reqwest

* Reinstate 30 second pict-rs timeout
2021-12-08 10:56:43 -05:00
Dessalines 7d07bc16ae
Merge pull request #1978 from LemmyNet/asonix/reqwest-middleware
Consolidate reqwest clients, use reqwest-middleware for tracing
2021-12-08 10:51:46 -05:00
Aode (lion) 5b3d707d8f Use from_message for static error string 2021-12-07 17:17:19 -06:00
Aode (lion) 2cf3278724 Update deps 2021-12-06 18:12:04 -06:00
Aode (lion) 97ebf2f6f3 Consolidate reqwest clients, use reqwest-middleware for tracing 2021-12-06 16:54:34 -06:00
Riley 35cbae61bc
Don't drop error context when adding a message to errors (#1958)
* Respond directly with LemmyError

Instrument Perform implementations for more precise traces
Use ApiError to format JSON errors when messages are present
Keep SpanTrace output in LemmyError Display impl

* Hide SpanTrace debug output from LemmyError

* Don't log when entering spans, only when leaving

* Update actix-web

* Update actix-rt

* Add newline after error info in LemmyError Display impl

* Propogate span information to blocking operations

* Instrument apub functions

* Use skip_all for more instrument attributes, don't skip 'self' in some api actions

* Make message a static string

* Send proper JSON over websocket

* Add 'message' to LemmyError display if present

* Use a quieter root span builder, don't pretty-print logs

* Keep passwords and emails out of logs

* Re-enable logging Login

* Instrument feeds

* Emit our own errors

* Move error log after status code recording

* Make Sensitive generic over the inner type

* Remove line that logged secrets
2021-12-06 09:54:47 -05:00
Marcin Wojnarowski 4a541a25ab
Change lemmur repo links (#1977) 2021-12-06 08:17:59 -05:00
Marty 8ce0c6d618
added deps - git and ca-certificates (for federation to work) and changed adduser to useradd so that user can be added non-interactively (#1976) 2021-12-06 01:35:50 +01:00
Dessalines 4e9ecb2632
Allow comment replies from blocked users. Fixes #1793 (#1969)
* Allow comment replies from blocked users. Fixes #1793

* Clearer check block.
2021-12-05 17:45:40 +00:00
Dessalines 040770d7ba
Fix retry infinite loops. Fixes #1964 (#1967)
* Fix retry infinite loops. Fixes #1964

* Moving retry_limit to settings
2021-12-05 10:03:13 -05:00
Nutomic 8bf0f31b0f
Merge pull request #1962 from vpzomtrrfrt/oneormany2
Allow single item for to, cc, and @context
2021-12-03 12:50:52 +00:00
Colin Reeder e2baed9a6d
Add lotide activities to tests 2021-12-02 22:44:52 -07:00
Colin Reeder a91c0c8feb
Allow single item for to, cc, and @context 2021-11-26 21:55:33 -07:00
Dessalines ad76c75821
Trying to add docker:latest. Fixes #1959 (#1960)
* Trying to add docker:latest. Fixes #1959

* Version 0.14.4-rc.3

* Trying to fix clippy on crate build

* Version 0.14.4-rc.4
2021-11-26 12:38:55 +00:00
Dessalines be65b6869f
Merge pull request #1937 from LemmyNet/disable-edit-email-notifications
Dont send email notifications for edited comments (fixes #1925)
2021-11-25 13:00:26 -05:00
Dessalines e765b42d46
Adding a captcha rate limit. Fixes #1755 (#1941)
* Adding a captcha rate limit. Fixes #1755

* Changing to post rate limit.
2021-11-25 13:04:19 +00:00
Felix Ableitner 27a687bcd0 Dont send email notifications for edited comments (fixes #1925) 2021-11-24 22:29:29 +01:00
Dessalines 97b8b9c255 Version 0.14.3 2021-11-23 14:39:55 -05:00
Dessalines 7363b19f01
Merge pull request #1951 from LemmyNet/fix_ap_id_dupes_query
Fix API dupes query. #1878
2021-11-23 14:37:58 -05:00
Dessalines f6b96370b8 Fix API dupes query. #1878 2021-11-23 14:30:16 -05:00
Dessalines 7f01d8cde6 Version 0.14.2 2021-11-23 11:48:49 -05:00
Dessalines b1f7bad0a3 Version 0.14.2-rc.1 2021-11-23 11:12:46 -05:00
Dessalines 46c7429429
Fixing duped report view for admins. Fixes #1933 (#1945)
* Fixing duped report view for admins. Fixes #1933

* Fixing tests.
2021-11-23 15:54:30 +00:00
Dessalines d2e28e5f38
Adding a GetComment endpoint. Fixes #1919 (#1944) 2021-11-23 15:53:48 +00:00
Dessalines 451818749b
Fix min title char count for post titles. Fixes #1854 (#1940)
* Fix min title char count for post titles. Fixes #1854

* Adding more newline checks for actors.

* Adding helper function
2021-11-23 15:52:58 +00:00
Dessalines 86b2901e8c
Adding MarkPostAsRead to API. Fixes #1784 (#1946)
* Adding MarkPostAsRead to API. Fixes #1784

* Adding error
2021-11-23 14:15:43 +00:00
Riley 1579ee566f
background-jobs 0.11 (#1943) 2021-11-23 12:20:01 +00:00
Riley 3fea5645f8
Add tracing (#1942) 2021-11-23 12:16:47 +00:00
Dessalines 88c7b95d03
Remove pointless community follower sort. (#1939) 2021-11-23 12:05:09 +00:00
Dessalines 3e062a9959
Merge pull request #1938 from LemmyNet/once_cell
Use once_cell instead of lazy_static
2021-11-22 14:27:08 -05:00
Felix Ableitner e88106cef4 Use once_cell instead of lazy_static 2021-11-22 19:58:31 +01:00
Dessalines 3d08e6c1fc
Adding unique constraint for activity ap_id. Fixes #1878 (#1935)
* Adding unique constraint for activity ap_id. Fixes #1878

* Removing is_activity_already_known
2021-11-22 18:57:03 +00:00
Nutomic 76c4378011
Merge pull request #1936 from LemmyNet/required_public_key
Making public key required. Fixes #1934
2021-11-22 15:37:05 +00:00
Dessalines 05d43150bc Making public key required. Fixes #1934 2021-11-22 10:10:18 -05:00
Dessalines 209829e1f3
Merge pull request #1926 from LemmyNet/replace-activitystreams-lib
Replace activitystreams crate with activitystreams-kinds
2021-11-22 08:47:46 -05:00
Felix Ableitner afccd5cf69 Replace activitystreams crate with activitystreams-kinds 2021-11-22 14:28:57 +01:00
Nutomic 88e81dce6b
Merge pull request #1921 from LemmyNet/fix_login
Fix login ilike bug. Fixes #1920
2021-11-22 13:05:57 +00:00
Nutomic ae153dc243
Merge pull request #1930 from Minoru/bugfix/nodeinfo-links
Change NodeInfo `links` to an array
2021-11-22 12:45:13 +00:00
Alexander Batischev d53d229c49
Change NodeInfo `links` to an array
NodeInfo spec[1] says that _.well-known/nodeinfo_ is a JSON Resource
Descriptor (JRD) document. That is specified in RFC 7033, where §4.4[2]
mandates that `links` is an array.

1. https://nodeinfo.diaspora.software/protocol.html
2. https://datatracker.ietf.org/doc/html/rfc7033#section-4.4
2021-11-21 20:10:39 +03:00
Dessalines e58c2048ed Fixing fuzzy_search to escape like chars. 2021-11-19 15:07:20 -05:00
Dessalines ffc898a7b8
Merge pull request #1924 from LemmyNet/fix-1914
Fix build error in #1914
2021-11-19 12:42:48 -05:00
Felix Ableitner 3e4fe89a45 Fix build error in #1914 2021-11-19 18:05:23 +01:00
Dessalines 6d35508f08
Merge pull request #1914 from LemmyNet/dont-announce-note
Dont announce comments, edited posts to Pleroma/Mastodon followers
2021-11-19 11:48:47 -05:00
Dessalines 4ce01f8bb4 Fix login ilike bug. Fixes #1920 2021-11-18 20:58:11 -05:00
Dessalines 712dabd16b
Merge pull request #1918 from LemmyNet/fix-smithereen-webfinger
Fix Smithereen webfinger, remove duplicate webfinger impl (fixes #1916)
2021-11-18 14:47:34 -05:00
Dessalines e756e85da7
Merge pull request #1917 from LemmyNet/outbox-announce
Community outbox should only contain activities sent by community
2021-11-18 14:31:47 -05:00
Felix Ableitner da89ea22fb Fix Smithereen webfinger, remove duplicate webfinger impl (fixes #1916) 2021-11-18 19:28:53 +01:00
Felix Ableitner aeb34199f5 Dont announce comments, edited posts to Pleroma/Mastodon followers 2021-11-18 18:41:43 +01:00
Felix Ableitner a2707e1c56 Community outbox should only contain activities sent by community (fixes #1916) 2021-11-18 18:31:50 +01:00
Dessalines 1f03a2d957
Merge pull request #1915 from LemmyNet/remove-http-sig-compat
Remove HTTP signature compatibility mode (its not necessary)
2021-11-18 11:43:32 -05:00
Dessalines a56853be05
Merge pull request #1907 from not-layla/main
Implement rate limits on comments
2021-11-18 11:22:38 -05:00
Felix Ableitner f07aaf417a Remove HTTP signature compatibility mode (its not necessary) 2021-11-18 17:06:10 +01:00
layla 7fe7062c47 Implement rate limits on comments 2021-11-18 13:40:16 +00:00
Nutomic 8fc252ec55
Merge pull request #1911 from LemmyNet/fix_arm_docker
Fixing arm dockerfile.
2021-11-18 11:55:01 +00:00
Dessalines 66ba91de8c Fixing arm dockerfile. 2021-11-17 16:46:05 -05:00
Dessalines f4616789a7 Version 0.14.1 2021-11-17 16:25:50 -05:00
Nutomic 8000ee92e1
Merge pull request #1908 from LemmyNet/upgrade_background_jobs
Upgrade background jobs
2021-11-17 20:46:19 +00:00
Dessalines 4166f30fb4 Upgrading background-jobs-core and actix. #1820 2021-11-17 14:50:25 -05:00
Dessalines 0845d61d2b Fixing release 2021-11-17 13:50:03 -05:00
Dessalines 8b45ca0da2 Fixing prod deploy not adding other docker-compose.yml files. 2021-11-17 12:05:02 -05:00
Dessalines a24683b40c 0.14.0 Release notes. 2021-11-17 12:01:07 -05:00
Dessalines c29366328e Version 0.14.0 2021-11-17 11:28:16 -05:00
Dessalines dc3858c82d Version 0.14.0-rc.2 2021-11-17 09:14:54 -05:00
Dessalines 5f6419ff76
Merge pull request #1897 from LemmyNet/mastodon-compat
Mastodon compat
2021-11-17 09:12:01 -05:00
Felix Ableitner db631005d3 Fix error due to same activity being inserted in database twice 2021-11-16 19:13:05 +01:00
Felix Ableitner 3249060f67 Remove to field from follow activities 2021-11-16 19:13:05 +01:00
Aode (lion) 20cddf5e81 Support mastodon deletes 2021-11-16 18:07:47 +01:00
Felix Ableitner 7f4a773b88 Create and Note always need to tag parent creator, for mastodon notifications 2021-11-16 18:07:47 +01:00
Felix Ableitner c1f1b8aa0f Activities in community should also be sent to actors in cc 2021-11-16 18:07:45 +01:00
Felix Ableitner dc416bf255 Make http signature compatible with mastodon 2021-11-16 18:06:01 +01:00
Nutomic 60f72b2785
Merge pull request #1905 from LemmyNet/fix_comment_report_creator
Fixing comment report creator. Fixes #1904
2021-11-16 17:03:58 +00:00
Felix Ableitner 579ca37ddf Make webfinger standard compliant 2021-11-16 18:03:09 +01:00
Nutomic 3914c6c875
Merge pull request #1903 from LemmyNet/fix_direct_string_apub_serialize_error
Use serde_json::to_value
2021-11-16 17:00:07 +00:00
Dessalines ec40b4f7fb Fixing comment report creator. Fixes #1904 2021-11-16 09:59:52 -05:00
Dessalines 23641fcd06 Use serde_json::to_value 2021-11-15 21:11:44 -05:00
Dessalines 09cd32034b
Fixing activity serialization. Fixes #1900 (#1901) 2021-11-15 20:26:48 +00:00
Dessalines 497564359b Version 0.14.0-rc.1 2021-11-11 14:57:25 -05:00
Dessalines 3bd827c73a
Temporarily disable arm tests (#1895)
* Temporarily disable arm tests

* Disable cargo build
2021-11-11 14:49:48 -05:00
Nutomic 1b9414f292
More federation compat (#1894)
* Make HTTP signatures compatible with Pleroma

* Send Announce/Page, Announce/Note for Pleroma compatibility

* remove unused code
2021-11-11 14:49:15 -05:00
Dessalines dbc92d6ee0
Merge pull request #1888 from LemmyNet/test-pleroma-federation
Add docker setup for testing Pleroma federation
2021-11-11 08:52:26 -05:00
Felix Ableitner 135fd6864b Add docker setup for testing Pleroma federation 2021-11-11 14:26:46 +01:00
Dessalines 8d4c4fdf6c
Adding clippy:unwrap to husky. Fixes #1892 (#1893) 2021-11-11 12:18:08 +00:00
Dessalines 8a108bccae
Merge pull request #1891 from LemmyNet/remove-apub-accept-guard
Remove header guard for activitypub routes
2021-11-10 09:38:50 -05:00
Felix Ableitner 9a1fe154db Remove header guard for activitypub routes 2021-11-10 15:08:33 +01:00
Nutomic 2ed58aeda6
Merge pull request #1889 from LemmyNet/update_docker_images
Updating rust musl images
2021-11-10 13:45:49 +00:00
Dessalines f035af3738 Fixing clippy 2021-11-09 17:31:28 -05:00
Dessalines 5b3be5c102 Updating rust musl images 2021-11-09 17:16:59 -05:00
Dessalines 76220a4523
Fixing clippy lints. (#1885)
* Fixing clippy lints.

* Revert object id display

* Trying to fix clippy again
2021-11-09 18:16:37 +00:00
Dessalines c03689ed4c
Merge pull request #1887 from LemmyNet/federate-smithereen
Add federation test cases for Smithereen and Mastodon
2021-11-09 12:26:41 -05:00
Felix Ableitner 5319046dc7 Add federation test cases for Smithereen and Mastodon 2021-11-09 17:16:58 +01:00
Dessalines 5d321949e6
Merge pull request #1877 from LemmyNet/refactor-apub-2
Refactor apub 2
2021-11-08 10:25:25 -05:00
Felix Ableitner c21c142a9a Include apub context from file, so that it can be embedded in docs 2021-11-08 16:04:02 +01:00
Felix Ableitner 252d87d332 Fix clippy error 2021-11-08 13:16:14 +01:00
Felix Ableitner 888e683856 For verify_is_public() we also need to check cc field 2021-11-06 18:44:34 +01:00
Felix Ableitner a5a674a270 Add method ApubObject.verify() 2021-11-06 18:35:14 +01:00
Felix Ableitner 02ce7bdc7d Remove unused ActorType methods 2021-11-06 15:01:00 +01:00
Felix Ableitner 8ea21c39b7 Reduce stack memory usage in apub code
- use our own, smaller Endpoints struct
- wrap ObjectId.url in Box
- adjust usage of Box in different places
2021-11-06 14:53:39 +01:00
Felix Ableitner c725514841 Change to_apub and from_apub to take by value and avoid cloning 2021-11-06 14:47:58 +01:00
Dessalines 44b5fe0631
Stop using lemmy-ui:dev images (#1880)
* Stop using lemmy-ui:dev images

* Dont publish dev docker images with drone.
2021-11-05 21:49:15 +00:00
Felix Ableitner 2edf8ba157 Move ObjectId to library 2021-11-05 21:37:46 +01:00
Felix Ableitner bd3352423a Remove ActivityFields trait, deserialize into another struct instead 2021-11-05 21:14:19 +01:00
Felix Ableitner 969a7f2d1b Refactoring apub code 2021-11-05 21:12:10 +01:00
Dessalines a83113935d
Check if post or comment are deleted first. Fixes #1864 (#1867)
* Check if post or comment are deleted first. Fixes #1864

* Refactoring delete apub.

* Revert "Refactoring delete apub."

This reverts commit ba2c3d06cfb870efe792f4b2541036265b425156.
2021-11-03 17:47:24 +00:00
Dessalines 1bec551945
Merge pull request #1874 from LemmyNet/protocol-testing
Protocol testing
2021-11-03 11:23:26 -04:00
Felix Ableitner 41f7bcc0d2 Correctly use and document check_is_apub_id_valid() param use_strict_allowlist 2021-11-02 21:39:06 +01:00
Felix Ableitner b396344eae Merge two functions into one 2021-11-02 21:39:06 +01:00
Felix Ableitner 1c6f74cad5 Convert note.content and chat_message.content to html (fixes #1871) 2021-11-02 21:39:02 +01:00
Dessalines d4753049d7
Upgrade background_jobs to 0.9.1 #1820 (#1875) 2021-11-02 20:27:24 +00:00
Dessalines 87bc2763ce
Fix husky fmt hook. (#1868)
* Fix husky fmt hook.

* Change to use default cargo

* Using nightly check
2021-11-02 15:15:19 +00:00
Felix Ableitner 0bde2d595e Add tests for parsing activities and collections 2021-11-02 12:44:51 +01:00
Felix Ableitner aaaf039779 Move apub test files into tree structure 2021-10-29 16:54:19 +02:00
Felix Ableitner 03d8ac75ef Move activity structs to protocol folder 2021-10-29 12:50:32 +02:00
Felix Ableitner 5ff044346f Move object and collection structs to protocol folder 2021-10-29 12:50:32 +02:00
Felix Ableitner 358ef99ea2 Rewrite community followers and user outbox to use our own structs 2021-10-29 12:50:32 +02:00
Felix Ableitner d89156810d Move @context out of object/activity definitions 2021-10-29 12:50:32 +02:00
Felix Ableitner 2d04ff93f5 Change activity.cc to Vec<Url> in public activities 2021-10-29 12:50:32 +02:00
Felix Ableitner 271785b7fb When receiving activity, dont read community from cc (for pleroma compat and better verification) 2021-10-29 12:50:30 +02:00
Felix Ableitner 74523fb534 Make Note.context optional for pleroma compat (hack) 2021-10-29 12:45:54 +02:00
Felix Ableitner 03b8ae7215 Activity.to should always be a vec (and unspecified size for public activities) 2021-10-29 12:45:54 +02:00
Felix Ableitner 614490d29b Fix problem that prevented viewing of pleroma user profiles 2021-10-29 12:45:53 +02:00
Felix Ableitner 0af047dd83 Rewrite community moderators collection 2021-10-29 12:45:53 +02:00
Felix Ableitner 6792e376b4 Rewrite community outbox to use new fetcher 2021-10-29 12:45:53 +02:00
Felix Ableitner bb085189e0 Merge traits ToApub and FromApub into ApubObject 2021-10-29 12:45:53 +02:00
Dessalines b18ea3e0cc
Renaming to slur_filter. Fixes #1773 (#1801)
* Renaming to slur_filter. Fixes #1773

* Fixing config

* Updating doku for slur filter.

* Updating doku for slur filter again.

* Remove comment.
2021-10-28 20:47:25 +00:00
Dessalines f1f7c45017
Three instance inbox bug (#1866)
* 3 instance shared inbox bug test

* Fixing shared inbox bug. Fixes #1865

* A few fixes.
2021-10-28 20:46:24 +00:00
Dessalines 90a5febd38
Remove ansible from this repo. (#1829)
* Remove ansible from this repo.

* Adding a git push.
2021-10-27 12:09:00 -04:00
Nutomic 61189efe72
Rewrite collections to use new fetcher (#1861)
* Merge traits ToApub and FromApub into ApubObject

* Rewrite community outbox to use new fetcher

* Rewrite community moderators collection

* Rewrite tombstone
2021-10-27 12:03:07 -04:00
Dessalines d9ecabee87
Dont blank out post or community info. Fixes #1813 (#1841)
* Dont blank out post or community info. Fixes #1813

* Fix federation tests

* Only blank out info for non-logged in users.

* Remove pointless trait.

* Blank the community if deleted for post

* Fix hook

* Fixing again

* Fixing again

* Fixing again
2021-10-27 13:34:18 +00:00
Dessalines f4bac6a17f Merge remote-tracking branch 'origin/main' 2021-10-22 13:32:17 -04:00
Nutomic 7bfe59a89f
Format config/defaults.hjson before committing (#1860) 2021-10-22 13:29:47 -04:00
Dessalines 40264c17a0 Version 0.13.5-rc.7 2021-10-22 13:26:00 -04:00
Nutomic 149a4e0de8
Breaking apub changes (#1859)
* Remove CommentInReplyToMigration

* Remove compat for RemovePostCommentOrCommunity

* Remove PublicUrlMigration

* Change type of pm to ChatMessage from Pleroma, make pm.to array

* Use person.summary instead of person.content for pleroma compat

* Also change group.content to summary

* Rewrite apub object test json to serve as nice examples

* Also add test case for parsing pleroma private message
2021-10-22 12:21:26 -04:00
Dessalines 23731cd49c
Trying out rust-musl-builder for cargo publish (#1856)
* Trying out rust-musl-builder for cargo publish

* Version 0.13.5-rc.1

* Try rust:nightly

* Version 0.13.5-rc.2

* Try rust slim

* Version 0.13.5-rc.3

* Try rust 1.51

* Version 0.13.5-rc.4

* Trying another nightly

* Version 0.13.5-rc.5

* Trying another fix

* Version 0.13.5-rc.6
2021-10-21 13:26:01 -04:00
Nutomic dd0ba10b44
Pleroma federation2 (#1855)
* Allow fetching person from Pleroma, including test case (ref #1461)

* Added test case for parsing community from apub json

- fixed a bug with objectid (de)serialization
- fixed a bug with outbox fetching (ref #1582)

* Added apub test for post

* Ignore errors when reading community outbox (fixes #1582)

* Dont fetch community outbox/moderators during tests

* added test for lemmy comment

* Added federation test for pleroma comment

* Added html2md crate to parse comment html from pleroma (fixes #1461)

* some fixes for update_apub_test_files.sh

* Add tests for ToApub, private message, remove update script

* Delete objects from db at the end of each test
2021-10-21 13:25:35 -04:00
Nutomic 21304e6751
Create a custom pre-commit hook, generates config/defaults.hjson (#1857)
* Create a custom pre-commit hook, generates config/defaults.hjson (fixes #1836)

* invalid defaults file

* Revert "invalid defaults file"

This reverts commit 76d2c303e293b13d581f9c5aa2944caedb2f530b.
2021-10-21 12:57:09 -04:00
Dessalines 9e0fa99c69
Merge pull request #1850 from LemmyNet/refactor-apub
Refactor apub
2021-10-20 11:01:04 -04:00
Felix Ableitner 1aa0e1997b Major refactor, adding newtypes for apub crate
- this allows moving FromApub/ToApub traits into apub lib
2021-10-20 12:28:09 +02:00
Felix Ableitner f24999027e Merge crates db_schema and db_queries 2021-10-20 12:28:08 +02:00
Felix Ableitner d206aad282 Remove DeletableApubObject trait 2021-10-20 12:20:54 +02:00
Tmpod e9d9bc82d8
Add cargo metadata to all crates (#1853) 2021-10-19 13:03:43 -04:00
Tmpod aef9786fa7
Add both (De)Serialize to all models (#1851) 2021-10-19 12:37:01 -04:00
Dessalines 97aa7268ae
Adding GetUnreadCount to the API. Fixes #1794 (#1842)
* Adding GetUnreadCount to the API. Fixes #1794

* Reordering filters to fix unread replies.
2021-10-16 10:43:41 +00:00
Nutomic 18badcfdb4
Federate reports (#1830)
* Federate reports

* add federation test cases for reports
2021-10-15 10:37:33 -04:00
Dessalines ccb8e4b414
Fix saved posts and hide read posts issue. Fixes #1839 (#1840) 2021-10-14 17:03:12 +00:00
Dessalines 2402515fcc
Dont allow posts to deleted / removed communities. Fixes #1827 (#1828)
* Dont allow posts to deleted / removed communities. Fixes #1827

* Fixing couldnt find community error.

* Adding check in createorupdate post and comment.

* make sure post wasn't deleted or removed.

* Adding a post not deleted or removed check to creatorupdatecomment.

* Using pub(crate)
2021-10-14 16:33:19 +00:00
Dessalines f052e5f1ab 0.13.3 release notes. 2021-10-13 21:28:04 -04:00
Dessalines f526bce618 Update ansible version 2021-10-13 21:18:55 -04:00
Nutomic 8067244765
Dont swallow API errors (fixes #1834) (#1837)
Dont swallow API errors (fixes #1834)
2021-10-13 15:50:21 -04:00
Nutomic d26255957b
Fix federation of initial post/comment vote (fixes #1824) (#1835) 2021-10-13 10:12:41 -04:00
Nutomic f4c783cba5
Fix clippy warnings added in nightly (#1833) 2021-10-12 12:46:26 -04:00
Dessalines 864598908d
Admins can view all reports. Fixes #1810 (#1825) 2021-10-12 12:02:16 +00:00
Dessalines 35d0aba9e6
Adding a message_id to emails. Fixes #1807 (#1826) 2021-10-12 11:38:55 +00:00
Nutomic 454d3987a5
Generate config docs from code (#1786)
* Generate config docs from code

* update library

* move settings comments from config.hjson to code

* updte doku to 0.10

* update doku
2021-10-08 11:07:24 -04:00
Dessalines 53a2b6d013
Trying a background_jobs fix. #1820 (#1822) 2021-10-08 14:36:53 +00:00
Luna e06cd9c0ac
mark parent as read on reply (#1819)
* mark parent as read on reply

* mark as read only if you are the recipient

* mark mentions as read on reply
2021-10-08 10:28:32 -04:00
Nutomic b96ce81f89
Move code to apub library (#1795)
* Remove dependency of apub_lib on LemmyContext

* Move ApubObject trait to library

* Reorganize files in apub lib

* Move ActorType, signatures, activity_queue to apub library
2021-10-06 16:20:05 -04:00
Dessalines fe7c1b300b
Adding honeypot to user and post creation. Fixes #1802 (#1803) 2021-10-01 11:37:39 +00:00
Nutomic a03727e28a
Add database host back into config file (#1805) 2021-09-30 16:45:20 -04:00
Dessalines b6b045bf76 Update releases.md 2021-09-30 09:17:29 -04:00
Dessalines a99ba2de24 Version 0.13.0 2021-09-29 16:16:46 -04:00
Dessalines 9c50cbf431
Adding a user agent. Fixes #1769 (#1800)
* Adding a user agent. Fixes #1769

* Fix client duplicate creation.
2021-09-29 16:05:38 -04:00
Dessalines 5a281445a3
Upgrade deps (#1799)
* Upgrade deps

* Fix web::scope
2021-09-29 14:50:00 -04:00
Nutomic aee48f3f5d
Ansible changes (#1781)
* Use env var for config location when saving (not default location)

* Consistent variable formatting for easy replacement with sed

* Remove unmaintained lemmy_dev and uninstall playbooks

* Simplify lemmy.hjson for ansible

* cleanup ansible playbook

* add separate playbook for updating lemmy config

* Revert "add separate playbook for updating lemmy config"

This reverts commit 0a970ae1da984791958b01b01d35e64d6f6eb98a.
2021-09-28 11:34:18 -04:00
Dessalines 37bd9e0e6c Version 0.13.0-rc.1 2021-09-28 10:59:29 -04:00
Dessalines b18c744f63
Clean up reporting (#1776)
* First untested pass at reporting.

* Adding unit tests for post and comment report views

* Fix clippy

* Adding counts, creator_banned, and unresolved_only

* Adding my_vote to report views

* Fixing unit tests.
2021-09-28 10:36:17 +00:00
Nutomic 240de006db
Implement webmention support (fixes #1395) (#1671)
* Implement webmention support (fixes #1395)

* update

* use post url instead of instance or, better error handling

* update webmention
2021-09-27 10:49:47 -04:00
Felix Ableitner 329a282aac Merge branch 'remove_settings_and_secret_singletons_squashed' 2021-09-27 12:34:41 +02:00
Dessalines 8708ad1b44 Moving settings and secrets to context. 2021-09-27 11:25:26 +02:00
Felix Ableitner cf214ff583 Move jwt secret from config to database (fixes #1728) 2021-09-27 11:25:09 +02:00
Nutomic 527eefbe92
Rewrite fetcher (#1792)
* Use new fetcher implementation for post/comment

* rewrite person fetch to use new fetcher

* rewrite community to use new fetcher

* rename new_fetcher to dereference_object_id

* make ObjectId a newtype

* handle deletion in new fetcher

* rewrite apub object search to be generic

* move upsert() method out of ApubObject trait

* simplify ObjectId::new (and fix clippy)
2021-09-25 11:44:52 -04:00
Nutomic 21346eb786
Merge pull request #1785 from LemmyNet/add_cardano_donation_link
Add cardano donation link
2021-09-20 15:47:43 +00:00
Nutomic 1e7f3a4b23
Merge pull request #1782 from LemmyNet/password_min_length
Set a 10 char minimum password length.
2021-09-20 10:02:30 +00:00
Dessalines 0fbc342fe3 Fix tests 2021-09-19 17:20:47 -04:00
Dessalines 05e91ab9a2 Add cardano donation link 2021-09-19 16:52:16 -04:00
Dessalines 721962589c Clean up. 2021-09-18 19:53:30 -04:00
Dessalines 1033995801 Set a 10 char minimum password length. 2021-09-18 19:43:08 -04:00
Nutomic e84e1193fc
Dont pass accept-encoding header to pictrs (ref #1734) (#1738)
* Allow image upload in docker/dev/ (replaces #1765)

* Dont pass accept-encoding header to pictrs (ref #1734)

* Fix clippy errors
2021-09-17 11:44:20 -04:00
Nutomic 007a43c012
Merge pull request #1775 from LemmyNet/add_pictrs_to_ansible
Add pictrs to ansible.
2021-09-13 10:02:27 +00:00
Dessalines f3af561404 Add pictrs to ansible. 2021-09-07 20:11:36 -04:00
Dessalines 2cb0b6756c Adding 0.12.2 release notes 2021-09-06 11:33:32 -04:00
Dessalines 81c21a5328 Upping ansible version 2021-09-06 11:29:04 -04:00
Nutomic 9a2dc53097
Merge pull request #1770 from LemmyNet/fix/arm_build
Fix/arm build
2021-09-06 11:30:40 +00:00
Dessalines e9891977ee Version 0.12.2-rc.1 2021-09-05 13:59:28 -04:00
Dessalines a9a65a0f4f Try fixing arm build 2021-09-05 13:56:41 -04:00
Dessalines 52e6dcc51c Upping ansible version 2021-09-04 09:50:14 -04:00
Dessalines 9376c67ade Adding v0.12.1 release notes. 2021-09-04 09:33:26 -04:00
Dessalines 0940fb5f00
Fixing some comment websocket issues. (#1768)
- Wasn't correctly getting comment parent user for mark as read. Fixes #1767
- Was using all recipients for simple comment return. Fixes #1766
2021-09-04 08:47:41 -04:00
Dessalines 8b2491ea23 Fix upgrade note. 2021-09-03 10:56:47 -04:00
Dessalines 0b236a2fc2 Adding v0.12.0 release notes. 2021-09-03 09:29:11 -04:00
Dessalines df997dff49 Version 0.12.0 2021-09-03 09:23:50 -04:00
Dessalines 83a035082a Upgrading to lemmy-js-client 0.12.0 2021-09-03 09:21:24 -04:00
Dessalines e19349343a Version 0.12.0-rc.2 2021-09-03 08:28:26 -04:00
Dessalines ed2744201b
Create SECURITY.md (#1758)
Adding a security.md file.
2021-09-02 12:09:48 +00:00
Dessalines c654aa3416
Use more generic docker deps. Fixes #1759 (#1762)
* Use more generic docker deps. Fixes #1759

* Don't use slim
2021-09-02 11:50:20 +00:00
Dessalines c28c1b4bb3
Trying to fix arm builds. (#1761)
* Trying to fix arm builds.

* Adding comment
2021-09-02 11:00:45 +00:00
Dessalines 46b223e3c5
Fixing docker-compose prod (#1741) 2021-08-31 14:01:36 +00:00
Nutomic 2822f5a126
Change public activities to field to array (#1739) 2021-08-27 21:33:38 -04:00
Dessalines 2c8003a9fa
Upgrading deps (#1735) 2021-08-26 08:37:10 -04:00
Dessalines 0a91a28b27
Reindex tables non-concurrently on startup. Fixes #1726 . #1723 (#1736) 2021-08-26 11:49:16 +00:00
Dessalines da5fdae006 Version 0.12.0-rc.1 2021-08-25 17:28:42 -04:00
Dessalines a685e33f20 Merge branch 'main' of https://github.com/lemmynet/lemmy 2021-08-25 17:26:28 -04:00
Dessalines af225a42d0
Fix prod deploy script and clippy (#1724)
* Updating lemmy-js-client.

* Fix prod deploy script and clippy

* Try using buster.

* Using more generic and updated images.

* again.

* again.

* Try alternate env

* again.

* again.

* Version 0.11.4-rc.24

* again.

* Better old_tag

* Version 0.11.4-rc.27

* Updating cargo.lock

* Trying to run a cargo check to update the lock

* Version 0.11.4-rc.28
2021-08-25 17:26:10 -04:00
Dessalines 815b271084 Updating lemmy-js-client. 2021-08-25 13:00:39 -04:00
Dessalines 73449c09a7
Fix image uploads. Fixes #1725 (#1734)
* Fix image uploads. Fixes #1725

* Adding comment on awc dep.
2021-08-25 16:33:45 +00:00
Nutomic e413350be3
Merge pull request #1666 from LemmyNet/resolve-endpoint
Move resolving of activitypub objects to separate api endpoint
2021-08-23 17:06:51 +00:00
Dessalines c23e7cc20d
Fixing ResolveObject API and unit tests (#1713) 2021-08-23 17:25:39 +02:00
Dessalines 1ee0c0c291
Adding more site setup vars. Fixes #678 (#1718) 2021-08-23 09:44:10 +00:00
Nutomic 3b37ea6c8b
Dont append ? to url when cleaning it (#1716) 2021-08-21 09:36:33 -04:00
Felix Ableitner 251e0d3b82 Move resolving of activitypub objects to separate api endpoint (fixes #1584) 2021-08-20 12:35:50 +02:00
Nutomic f6f169b4eb
Rewrite remaining activities (#1712)
* Limit type/method visibility in apub code

* Simplify db_queries traits by removing generics

* Simplify delete activity implementation

* Rewrite delete activities

* Implement helper functions for websocket message sending

* When receiving delete reason as empty string, change to none

* Rewrite remaining activities

* Simplify inbox

* Remove struct ActivityCommonFields, derive ActivityFields trait instead

* Community should announce received activities to followers
2021-08-19 17:24:33 -04:00
Dessalines 2016afc9db
User / community blocking. Fixes #426 (#1604)
* A first pass at user / community blocking. #426

* Adding unit tests for person and community block.

* Moving migration

* Fixing creator_blocked for comment queries, added tests.

* Don't let a person block themselves

* Fix post creator_blocked

* Adding creator_blocked to PersonMentionView

* Moving blocked and follows to MyUserInfo

* Rename to local_user_view

* Add moderates to MyUserInfo

* Adding BlockCommunityResponse

* Fixing name, and check_person_block

* Fixing tests.

* Using type in Blockable trait.

* Changing recipient to target, adding unfollow to block action.
2021-08-19 20:54:15 +00:00
Dessalines 6af75492a9
Swap out iframely (#1706)
* Replace Iframely. Fixes #1681

* Add post_link_tags to nginx

* Adding post_link_tags route

* Cleaning up post_link_tags

* Changing PostLink to SiteMetadata, adding it to the API.

* Fixing issue when local has no openssl certs.

* Fixing an issue with pictrs errors

* Revert "Fixing issue when local has no openssl certs."

This reverts commit dbf7d1b1ee03846e5ef7b7156e618424f1150e1d.

* Add ca-certs to dockerfile for volume mount.

* Cleaning up fetch_pictrs request

* Changing to fetch_site_data
2021-08-19 14:12:49 +00:00
Nutomic 8158966af6
Merge pull request #1710 from LemmyNet/mod_transfer_community
Adding ModTransferCommunity to modlog in API. Fixes #1437
2021-08-18 22:01:09 +00:00
Nutomic d8fafc1b03
Merge pull request #1709 from LemmyNet/upgrade_deps_6
Upgrading deps
2021-08-18 11:46:11 +00:00
Dessalines b241bb9cb7 Adding script to upgrade deps, and check for unused ones. 2021-08-17 19:16:20 -04:00
Dessalines 6910e18a83 Adding ModTransferCommunity to modlog in API. Fixes #1437 2021-08-17 17:52:28 -04:00
Dessalines 1f64db6a33 Upgrading deps 2021-08-17 16:31:16 -04:00
Nutomic 28d6370c35
Rewrite delete activities (#1699)
* Limit type/method visibility in apub code

* Simplify db_queries traits by removing generics

* Simplify delete activity implementation

* Rewrite delete activities

* Implement helper functions for websocket message sending

* When receiving delete reason as empty string, change to none
2021-08-17 14:04:58 -04:00
Dessalines 6fbf6a684c
Make sure bots aren't included in aggregate counts (#1705)
- Fixes #1648
2021-08-16 20:52:24 +00:00
Dessalines 2966203653
Don't allow deleted users to do actions. Fixes #1656 (#1704) 2021-08-16 20:51:08 +00:00
Dessalines 32874163a8
Merge pull request #1703 from shilangyu/patch-1
Update lemmy_api_client status in README
2021-08-15 18:19:23 -04:00
Marcin Wojnarowski fb66b77d67
Update lemmy_api_client status 2021-08-15 22:37:37 +02:00
Dessalines 8a1af056e2
When banning a user, remove communities they've created (#1700)
- Fixes #1659
2021-08-13 17:39:56 +00:00
Nutomic 353a1fe0a0
Rewrite activitypub following, person, community, pm (#1692)
* Rewrite following activities

* Rewrite person apub

* Rewrite community apub

* Rewrite private message activity sending
2021-08-12 08:48:09 -04:00
Dessalines 44716c2f24
Merge pull request #1674 from LemmyNet/crates-io
Distribute Lemmy via crates.io
2021-08-11 15:16:42 -04:00
Felix Ableitner a44b5c9c36 publish to crates.io with normal release script 2021-08-09 18:44:18 +02:00
Felix Ableitner af6aa3c0bf Distribute Lemmy via crates.io 2021-08-09 17:29:32 +02:00
Dessalines 9d936a3d85
Merge pull request #1690 from LemmyNet/comment-reply-migration
Migrate comment inReplyTo field to single value (ref #1454)
2021-08-05 11:19:33 -04:00
Felix Ableitner b2937223df Migrate comment inReplyTo field to single value (ref #1454) 2021-08-05 13:00:29 +02:00
Dessalines 7b8cbbba85
Simplify config using macros (#1686)
Co-authored-by: Felix Ableitner <me@nutomic.com>
2021-08-04 21:13:51 +00:00
Nutomic b8d7f00d58
Rewrite voting (#1685)
* Merge like/dislike activity handlers into vote

* Rewrite vote sending code

* Remove old send_create, send_update functions
2021-08-02 16:33:40 -04:00
Dessalines 1664cb326a
Merge pull request #1677 from LemmyNet/remove-fat-deps
Remove brotli, zstd dependencies
2021-08-02 16:21:33 -04:00
Nutomic 6c9e04583d
Merge pull request #1683 from LemmyNet/fix/comment_count_trigger_issues
Some comment count fixes.
2021-08-02 12:08:15 +00:00
Felix Ableitner abd26aeab2 Remove brotli, zstd dependencies 2021-08-02 14:05:39 +02:00
Dessalines 896ba8451c Some comment count fixes.
- Make sure an update to deleted decreases the count. Fixes #1676
- Don't allow the post creator to comment necro-bump their own post.
  Fixes #1675
2021-08-01 21:07:45 -04:00
Dessalines 224592c547
Merge pull request #1682 from LemmyNet/rewrite-comment
Rewrite comment
2021-08-01 20:02:13 -04:00
Felix Ableitner 6b57d716e1 Rewrite private message apub and merge create/update 2021-07-31 22:58:11 +02:00
Felix Ableitner dc363c8f35 Merge logic for post create and update 2021-07-31 19:26:17 +02:00
Felix Ableitner 3eb46868ff Merge logic for comment create and update 2021-07-31 17:47:08 +02:00
Felix Ableitner 43ad99bbe8 Rewrite apub comment (de)serialization using structs (ref #1657) 2021-07-31 16:57:37 +02:00
Nutomic bb7750d8ee
Merge pull request #1678 from LemmyNet/rewrite-post
Rewrite apub post (de)serialization using structs (ref #1657)
2021-07-31 07:10:56 +00:00
Dessalines 520436cd9a Fix changelog links 2021-07-30 18:59:22 -04:00
Felix Ableitner 433ab1e78b Add docs for MediaType, PublicUrl values 2021-07-30 23:16:33 +02:00
Felix Ableitner 57b6ecaf40 Simplify lemmy_context() function (dont return errors) 2021-07-30 23:16:33 +02:00
Felix Ableitner ff265c7ebc Rewrite apub post (de)serialization using structs (ref #1657) 2021-07-30 23:16:32 +02:00
Dessalines 15a11c13a2 Updating ansible version. 2021-07-30 16:55:04 -04:00
Dessalines 8d2dc76be3 Adding release notes. 2021-07-30 16:50:39 -04:00
Dessalines d85f0d087e
Blank out extra info for deleted or removed content. Fixes #1679 (#1680) 2021-07-30 18:44:15 +00:00
Dessalines 6ffa291ec9
Actor name length config dess (#1672)
* Make length of user/community name configurable (fixes #1306)

* use single config value, fix migrations, increase displayname length

* remove debug statements

* add helper method for setting actor_name_max_length

* move function

* Fixing some defaults

Co-authored-by: Felix Ableitner <me@nutomic.com>
2021-07-22 21:53:44 -04:00
Dessalines fcae2189eb
Add show_new_posts_notifs setting. Fixes #1664 (#1665) 2021-07-22 20:07:40 +00:00
Dessalines 7d3b90d711
Fix issue with protocol string in actor id generation (#1668) 2021-07-20 16:55:04 +00:00
Dessalines 5fe7de2bff
Adding shortname fetching for users and communities. Fixes #1662 (#1663) 2021-07-20 04:29:50 +00:00
Dessalines f18139d06c
Merge pull request #1660 from LemmyNet/merge-apub-crates
Merge apub, apub_receive crates
2021-07-17 13:00:06 -04:00
Felix Ableitner c1db86925f Merge apub, apub_receive crates (fixes #1621) 2021-07-17 18:20:44 +02:00
Nutomic c7de1fcf24
Apub inbox rewrite (#1652)
* start to implement apub inbox routing lib

* got something that almost works

* it compiles!

* implemented some more

* move library code to separate crate (most of it)

* convert private message handlers

* convert all comment receivers (except undo comment)

* convert post receiver

* add verify trait

* convert community receivers

* add cc field for all activities which i forgot before

* convert inbox functions, add missing checks

* convert undo like/dislike receivers

* convert undo_delete and undo_remove receivers

* move block/unblock activities

* convert remaining activity receivers

* reimplement http signature verification and other checks

* also use actor type for routing, VerifyActivity and SendActivity traits

* cleanup and restructure apub_receive code

* wip: try to fix activity routing

* implement a (very bad) derive macro for activityhandler

* working activity routing!

* rework pm verify(), fix tests and confirm manually

also remove inbox username check which was broken

* rework following verify(), fix tests and test manually

* fix post/comment create/update, rework voting

* Rewrite remove/delete post/comment, fix tests, test manually

* Rework and fix (un)block user, announce, update post

* some code cleanup

* rework delete/remove activity receivers (still quite messy)

* rewrite, test and fix add/remove mod, update community handlers

* add docs for ActivityHandler derive macro

* dont try to compile macro comments
2021-07-17 12:08:46 -04:00
Dessalines f4c7c2bf28
Merge pull request #1651 from LemmyNet/upgrade_deps_5
Upgrade api_test deps
2021-07-06 12:13:22 -04:00
Dessalines 904709e3f1 Upgrade api_test deps 2021-07-06 10:57:54 -04:00
Dessalines 9840f5c1c1
Upgrading deps, running clippy fix on nightly 1.55.0 (#1638)
* Upgrading deps, running clippy fix on nightly 1.55.0

* Running clippy --fix

* Trying to fix transform

* Trying to fix another transform

* Upgrading http-signature-normalization-actix

* Fix app_data

* Fix pictrs uploading

* Fix unwrap
2021-07-06 13:26:46 +00:00
Dessalines f54209c451
Running clippy --fix (#1647) 2021-07-05 16:07:26 +00:00
Dessalines 8c957ca939
Merge pull request #1649 from weex/case-insensitive-captcha
make captcha case-insensitive
2021-07-05 09:49:35 -04:00
David Sterry 1b1ebd2f70 make captcha case-insensitive 2021-07-04 17:51:08 -07:00
Dessalines 469a2b5c90
Merge pull request #1637 from LemmyNet/remove-url-tracking-params
Remove tracking params from post url (fixes #768)
2021-06-24 14:54:02 -04:00
Felix Ableitner f289374e70 Remove tracking params from post url (fixes #768) 2021-06-18 20:38:34 +02:00
Aaron DeVore 79ee271a5e
LemmyNet/lemmy#1635: Fix IPv6 port setup for Nginx (#1636) 2021-06-17 17:36:00 +00:00
Dessalines 3022c00a0b Version 0.11.2 2021-06-14 18:14:29 -04:00
Dessalines 1cdc5d662c
Fix --cert-name for certbot. (#1631) 2021-06-13 18:28:32 +00:00
Dessalines 12d50e42b4
Change join.lemmy.ml to join-lemmy.org (#1628) 2021-06-07 21:10:47 +00:00
Dessalines 7fb4508fa1
Upgrade pictrs. Fixes #1599 (#1600) 2021-05-28 15:51:09 +00:00
Dessalines ab2b8df1cb
Invalidate current logins on account deletion. Fixes #1602 (#1603) 2021-05-28 15:50:52 +00:00
Dessalines f196f05f20
Upgrading api test deps (#1608) 2021-05-28 15:46:23 +00:00
Dessalines b95bbe2fae
Fix nsfw posts showing for non-logged in users. Fixes #1614 (#1615) 2021-05-26 18:02:35 +00:00
Pavel Balashov 7008848f9c
Add additional slurs configuration option. Closes #1464. (#1612)
* Actualize a comment about config initialization

* Add additional slurs functionality.

It is possible to additional regex for slurs filtering.
It can be done through `additional_slurs` option in config file.
2021-05-26 13:39:38 +00:00
Dessalines 100a56e8ef Version 0.11.1 2021-05-17 19:15:51 -04:00
Dessalines f67b0e9ff8
Updating to rust 1.51.0 (#1598) 2021-05-03 14:46:12 +00:00
Dessalines 6eed6cf362 Fixing release doc. 2021-05-02 21:19:16 -04:00
Dessalines c1cbcdc253 Version 0.11.0 2021-04-27 10:35:54 -04:00
Dessalines c48c620048 Adding v0.11.0 release notes 2021-04-27 10:34:45 -04:00
Dessalines 0d9dceff88
Merge pull request #1595 from LemmyNet/Nutomic-patch-1
Better slur regex
2021-04-27 09:56:36 -04:00
Nutomic 96488684e6
Better slur regex 2021-04-27 12:32:56 +00:00
Dessalines c864dfadf6
Fixing regex. Fixes #1593 (#1594)
* Fixing regex. Fixes #1593

* Fixing test
2021-04-26 18:18:12 +00:00
Dessalines 1eb7e41674
Merge pull request #1592 from LemmyNet/feature/mark_post_as_read
Add show_read_posts filter. Fixes #1561
2021-04-26 10:57:40 -04:00
Dessalines 880c51687a Merge branch 'main' into feature/mark_post_as_read 2021-04-26 10:44:19 -04:00
Nutomic df0a38e0ba
Merge pull request #1566 from LemmyNet/additional_search_filters
Add creator id to search. Fixes #765
2021-04-26 14:17:21 +00:00
Dessalines 6d3778cafe Changing unwrap_default to unwrap_or(false) 2021-04-26 09:50:34 -04:00
Nutomic dc1a0dcd5e
Fetch git tags manually in CI (#1590)
* Fetch git tags manually in CI

* Dont need espeak in CI anymore
2021-04-26 09:30:30 -04:00
Dessalines 5b2be6f9df Add show_read_posts filter. Fixes #1561 2021-04-24 18:26:50 -04:00
Dessalines ed31deab00 Creator extra search results 2021-04-23 11:54:38 -04:00
Dessalines ef7fe7586b Some formatting 2021-04-23 02:40:10 -04:00
Dessalines 51e181c529 Don't search for communities or users when the id is included. 2021-04-23 02:30:13 -04:00
Dessalines f8cd6fd445 Making more fields optional in the API.
- Fixes #1569
2021-04-23 02:30:13 -04:00
Dessalines c86f5472fb Adding listing_type to search. 2021-04-23 02:13:32 -04:00
Dessalines a42ac3e58a Add creator id to search. Fixes #765 2021-04-23 02:12:29 -04:00
Nutomic db1abff857
Add option to limit community creation to admins only (fixes #1586) (#1587)
* Add option to limit community creation to admins only (fixes #1586)

* address review
2021-04-22 19:42:58 -04:00
Nutomic efee2062dd
Mark accounts as bot nutomic (#1565)
* Mark account as bot. Fixes #1357

* Fix clippy

* Federate bot status using actor `type` field

* fix clippy

Co-authored-by: Dessalines <tyhou13@gmx.com>
2021-04-21 17:41:14 -04:00
Dessalines 9dc5605663
Merge pull request #1588 from LemmyNet/improved-logging
Improved logging
2021-04-21 10:34:47 -04:00
Nutomic 8bb3ba4a16
Add option to disable strict allowlist (fixes #1486) (#1581)
* Add option to disable strict allowlist (fixes #1486)

* adjust docs
2021-04-21 09:36:07 -04:00
Felix Ableitner 78eee7dc9e Improved logging 2021-04-21 14:45:10 +02:00
Nutomic 65a11a7239
Use .map_err in api code (fixes #1573) (#1575)
* Use .map_err in api code (fixes #1573)

* forgot some
2021-04-16 09:10:43 -04:00
Nutomic 03c18ecfbe
Merge pull request #1571 from guland2000/patch-3
Update README.ru.md
2021-04-14 16:10:07 +00:00
Nutomic c9d461ea93
Merge pull request #1570 from guland2000/patch-2
Update README.ru.md
2021-04-14 16:09:59 +00:00
Dessalines b0cef3c76d
Merge pull request #1572 from LemmyNet/feature/federated-mod-community-updates
Remote mods can update/delete/undelete communities
2021-04-14 11:02:36 -04:00
Felix Ableitner c572dc0cc6 Remote mods can update/delete/undelete communities 2021-04-13 15:19:17 +02:00
Andrei Guliaikin 0d01461de4
Update README.ru.md
Missing one letter
2021-04-12 23:16:17 +02:00
Andrei Guliaikin d1b57501bd
Update README.ru.md
Some mistakes... logical ;-)
2021-04-12 23:02:59 +02:00
Dessalines dee02e6642
Merge pull request #1567 from LemmyNet/include-commit-in-version
For untagged commits, include hash in version name (fixes #1563)
2021-04-12 11:40:43 -04:00
Nutomic 198f3073f9
Readme russian (#1568)
* README.ru.md

Russian language is done.

* Some fixes for previous commit

Co-authored-by: Andrei Guliaikin <guland2000@users.noreply.github.com>
2021-04-12 13:08:05 +00:00
Felix Ableitner b7d1d91309 For untagged commits, include hash in version name (fixes #1563) 2021-04-12 13:47:58 +02:00
Nutomic aa79c5131f
Implement federated bans (fixes #1298) (#1553)
* Implement federated bans (fixes #1298)

* mod actions should always be federated to affected user, in addition to followers

* Make Undo/Block work for remote mods

* clippy fix

* fix federation test

* vscodium doesnt auto-save changes...
2021-04-09 11:01:26 -04:00
Nutomic 89dd0f2925
Merge pull request #1564 from LemmyNet/remove_extra_save_user_fields
Forgot to remove extra fields for changepassword.
2021-04-09 14:33:28 +00:00
Dessalines 2e16b11db8 Forgot to remove extra fields for changepassword. 2021-04-08 21:14:26 -04:00
Nutomic b8a6592369
Drone release main (ref #1556) (#1557)
* publish docker images from main

* try with separate step

* redo, lots of boilerplate

* try to fix syntax

* unique step names

* fix docker tags, remove cargo-chef

* only build dev image on main branch

* use `ref` for condition, as `branch` uses the target branch for PRs

* consistent indents

* fix tag

* use lemmy-ui:dev image for `docker/dev` and `docker/federation`
2021-04-08 10:33:58 -04:00
Dessalines c3d64f996e
Removing community.creator column. Fixes #1504 (#1541)
* Removing community.creator column. Fixes #1504

* Fixing unit tests.

* Fixing federation tests.
2021-04-08 11:29:08 +00:00
Dessalines 1a70477fc7
Better DB default fields. (#1560)
* Better DB default fields.

* Fixing clippy
2021-04-08 11:19:58 +00:00
Dessalines 3a01949f81
Fixing volume mount. (#1559)
* Fixing volume mount.

* Remove config line.
2021-04-07 18:41:12 +00:00
Dessalines 0c17668844 Updating releases.md 2021-04-07 14:26:22 -04:00
Dessalines 04a3cb1ee8 Merge branch 'release/v0.10' 2021-04-07 14:23:32 -04:00
Dessalines 831ab76152 Version 0.10.3 2021-04-07 14:23:09 -04:00
Dessalines c30d38829d Version 0.10.3 2021-04-07 13:17:38 -04:00
Dessalines 727fa610d4
Merge pull request #1552 from LemmyNet/feature/1550-optional-config-values
Make some of the database config values optional (fixes #1550)
2021-04-07 13:16:28 -04:00
Dessalines 2452bf8f01
Merge pull request #1558 from LemmyNet/feature/1550-optional-config-values
Make some of the database config values optional (fixes #1550)
2021-04-07 13:16:08 -04:00
Dessalines 7bd474a843
Adding a short site description. Fixes #1496 (#1532)
* Adding a short site description. Fixes #1496

- Renaming old description to sidebar

* Adding a back end site desc length check.
2021-04-07 11:40:35 +00:00
Dessalines 5fff927dc4
Adding matrix id validation check. Fixes #1520 (#1538) 2021-04-07 11:38:00 +00:00
Dessalines 8df102ff4b
Merge pull request #1539 from LemmyNet/change_password_api
Moving ChangePassword to its own API action. Fixes #1471
2021-04-06 12:21:41 -04:00
Dessalines d97129e7ae Merge branch 'main' into change_password_api 2021-04-06 12:09:26 -04:00
Felix Ableitner ccdf117c8f Make some of the database config values optional (fixes #1550) 2021-04-06 14:57:37 +02:00
Nutomic a4c2421e74
Merge pull request #1537 from LemmyNet/add_users_active_monthly_community_sort
Adding users active monthly for community sort. Fixes #1527
2021-04-06 12:03:11 +00:00
Nutomic bcdbced0dd
Merge pull request #1536 from LemmyNet/change_preferred_to_display_name
Changing preferred to display name. Fixes #1211
2021-04-06 12:02:50 +00:00
Nutomic 98216d8a3b
Merge pull request #1535 from LemmyNet/rust_captcha_features
Rust captcha features
2021-04-06 11:58:48 +00:00
Nutomic 7daee06383
Merge pull request #1529 from LemmyNet/show_score_setting
Adding a setting to show / hide scores. Fixes #1503
2021-04-06 11:47:31 +00:00
Dessalines df7fe705eb Updating releases.md 2021-04-05 13:26:24 -04:00
Dessalines 89b96511bf Version 0.10.2 2021-04-05 13:21:08 -04:00
Nutomic 74a63804dc
Fix test failure due to config loading error (#1547)
* Crash if config fails to load

* fix previous commit

* Fix test failure due to config loading error

* Adding test fix to drone.

* Logging line.

* Trying to fix drone 2

* Fixing deploy script.

Co-authored-by: Dessalines <tyhou13@gmx.com>
2021-04-05 13:21:56 -04:00
Dessalines 458767e3a8 Version 0.10.1 2021-04-05 10:29:14 -04:00
Nutomic f0c96c28bf
Crash if config fails to load (#1545)
* Crash if config fails to load

* fix previous commit
2021-04-05 10:23:32 -04:00
Dessalines ebb980eaaf
Fix ansible deploy template. (#1544)
* Fix ansible deploy template.

* Add ansible comment.

* Changing tls to true

* Fixing comment line.
2021-04-05 14:20:40 +00:00
Dessalines a617a6a6d6 Update releases.md 2021-04-05 08:55:38 -04:00
Dessalines ba517249e8 Version 0.10.0 2021-04-05 08:53:28 -04:00
Dessalines f33f763278 Moving ChangePassword to its own API action. Fixes #1471 2021-04-01 17:39:01 -04:00
Dessalines b893085d1f Adding users active monthly for community sort. Fixes #1527 2021-04-01 14:34:27 -04:00
Dessalines 799ab94af3 Don't allow zero-space char in display name. Fixes #1317 2021-04-01 14:09:53 -04:00
Dessalines bf7558830f Changing preferred to display name. Fixes #1211 2021-04-01 13:57:45 -04:00
Dessalines 1ba570092e Adding more rust captcha features. Fixes #1248 2021-04-01 13:30:24 -04:00
mickie fac024b90c
Translated README.md to Spanish (#1525)
* Add menu bar for language selection

* Create README.es.md

* Update README.es.md

* fix minor issues

* Update README.md

* Update and rename README.es.md to readmes/README.es.md

* Update features section.

* Update README.md

* Update README.es.md
2021-03-31 19:02:27 +00:00
Dessalines 2f63fdbde0 Adding a setting to show / hide scores. Fixes #1503 2021-03-31 06:54:46 -04:00
dessalines 1a3a215f59 Merge pull request 'Split lemmy_apub crate into two parts apub and apub_receive' (#190) from split-apub-crate into main
Reviewed-on: https://yerbamate.ml/LemmyNet/lemmy/pulls/190
2021-03-31 10:36:51 +00:00
Felix Ableitner 722cdb78ba Split lemmy_apub crate into two parts apub and apub_receive 2021-03-30 22:29:16 +02:00
Dessalines 36a79e18cd Version 0.10.0-rc.13 2021-03-29 18:10:04 -04:00
Dessalines 4da6e42fc1 Fix websocket location to /api/vX 2021-03-29 17:48:37 -04:00
Dessalines 4c8f2e976e Merge remote-tracking branch 'yerba/split-api-crate' into test_merge_api_crates_reorg 2021-03-29 16:24:50 -04:00
Felix Ableitner 01fc1228d5 Fix API and clippy warnings 2021-03-29 20:55:08 +02:00
Dessalines 2309088b03 Renaming to api/v3 2021-03-29 11:26:15 -04:00
Dessalines c2f8695c9a Version 0.10.0-rc.12 2021-03-25 15:22:07 -04:00
Felix Ableitner 249fcc5066 Split api crate into api_structs and api 2021-03-25 20:19:40 +01:00
Dessalines 6ee76e9280
Merge pull request #1516 from LemmyNet/move_matrix_and_admin_to_person
Move matrix and admin to person
2021-03-25 11:41:37 -04:00
Dessalines 0b5438d3fd
Merge pull request #1522 from LemmyNet/move_matrix_and_admin_to_person_nutomic
Federate Matrix ID (fixes #1438)
2021-03-24 15:38:57 -04:00
Felix Ableitner 34bdf4c7c5 Federate Matrix ID (fixes #1438) 2021-03-24 17:56:13 +01:00
Dessalines af2f84805a Fixing image locations. 2021-03-24 12:42:34 -04:00
Dessalines 3ca2453fc6 Merge branch 'main' into move_matrix_and_admin_to_person 2021-03-24 11:51:34 -04:00
Dessalines 8a10a9079f Merge remote-tracking branch 'yerba/federated-moderation' 2021-03-24 11:48:02 -04:00
Felix Ableitner c7524d924b Fix federation tests 2021-03-24 16:33:04 +01:00
Dessalines 7051207495 Version 0.10.0-rc.10 2021-03-23 14:46:18 -04:00
Dessalines 8543092b9f Merge branch 'remove_cargo_cache_v2' into move_matrix_and_admin_to_person 2021-03-23 14:46:00 -04:00
Dessalines 6758922a63 Version 0.10.0-rc.9 2021-03-23 14:17:44 -04:00
Dessalines baab2e88a5 Merge branch 'main' into move_matrix_and_admin_to_person 2021-03-23 14:16:54 -04:00
Dessalines 3949b35360
Merge pull request #1517 from LemmyNet/add_saved_only_1
Adding saved_only to GetComments and GetPosts. Fixes #1513
2021-03-22 13:52:04 -04:00
Dessalines b4276341af Adding saved_only to GetComments and GetPosts. Fixes #1513 2021-03-22 10:39:54 -04:00
Dessalines e4ead96d3a Merge branch 'main' into move_matrix_and_admin_to_person 2021-03-22 10:29:10 -04:00
Dessalines eb45bf2d0a Moving admin to person table. Fixes #1515 2021-03-22 10:28:00 -04:00
Felix Ableitner d6bd072ea1 Make federation compatible with Lemmy v0.9.9 2021-03-22 15:08:06 +01:00
Felix Ableitner a5a0d90349 Address review comments 2021-03-22 13:52:00 +01:00
Felix Ableitner e726d1e184 Merge branch 'grishka_fix_ld_context' 2021-03-22 13:12:05 +01:00
Felix Ableitner 459b95bc7e Make previous commit compile 2021-03-22 13:11:32 +01:00
Felix Ableitner 6b5354fb11 Merge branch 'fix_ld_context' of https://yerbamate.ml/grishka/lemmy into grishka_fix_ld_context 2021-03-22 13:08:07 +01:00
Nutomic 8b2b3eef73
Merge pull request #1509 from LemmyNet/fix_deploy_prod_script
Fixing docker deploy script. Fixes #1507
2021-03-22 12:02:41 +00:00
Grishka 115b986edc uh 2021-03-21 04:03:53 +03:00
Grishka c14a505456 Fix JSON-LD contexts 2021-03-21 04:00:32 +03:00
Dessalines c884510173 Creating default DB forms. Fixes #1511 2021-03-20 16:59:07 -04:00
Dessalines 53ea383b4e Forgot to regenerate person_alias views 2021-03-20 16:32:52 -04:00
Dessalines 1745b64ceb Moving matrix_user_id to person table. #1438 2021-03-20 15:21:51 -04:00
Dessalines 77f8dc9675 Fixing docker deploy script. Fixes #1507 2021-03-20 14:49:07 -04:00
Dessalines 4b92e35edc Reverting docker versions until deploy.sh fix. 2021-03-20 11:55:11 -04:00
Dessalines e9eca35816 Version 0.10.0-rc.8 2021-03-19 15:58:24 -04:00
Dessalines ae635c752a Try to remove cargo home changing to fix release. 2021-03-19 15:57:56 -04:00
Felix Ableitner 05b07b8cbb Fix conflicts in docker-compose.yml 2021-03-19 18:09:05 +01:00
Felix Ableitner 4f54108a9c Merge branch 'main' into federated-moderation 2021-03-19 17:11:34 +01:00
Dessalines f55ef1d7ef Version 0.10.0-rc.7 2021-03-19 11:46:46 -04:00
Nutomic 14bc9f0946
Merge pull request #1500 from LemmyNet/jwt_revocation_dess
Jwt revocation dess
2021-03-19 15:43:47 +00:00
Dessalines 493598c1ba A few suggestion fixes. 2021-03-19 10:02:58 -04:00
Nutomic 96efe302ce
Merge pull request #1499 from LemmyNet/strictly_type_db_ids
Strictly type db ids
2021-03-19 13:41:22 +00:00
Nutomic e25bcb35d7
Merge pull request #1428 from LemmyNet/split_user_table
Split user table
2021-03-19 13:20:23 +00:00
Dessalines 05b485b678 Merge branch 'Mart-Bogdan-1462-jwt-revocation-on-pwd-change' into jwt_revocation_dess 2021-03-19 00:31:49 -04:00
Dessalines 360d4ea8d1 Merge branch '1462-jwt-revocation-on-pwd-change' of https://github.com/Mart-Bogdan/lemmy into Mart-Bogdan-1462-jwt-revocation-on-pwd-change 2021-03-18 21:41:00 -04:00
Dessalines c06d612432 Merge branch 'split_user_table' into strictly_type_db_ids 2021-03-18 19:37:54 -04:00
Dessalines c88722983e Merge branch 'main' into split_user_table 2021-03-18 19:36:48 -04:00
Nutomic 33a326854a
Set CARGO_HOME for CI so deps arent redownloaded (#1497)
* Set CARGO_HOME for CI so deps arent redownloaded

* run find on x86

* fix path

* cleanup

* try again

* use mv
2021-03-18 16:35:04 -04:00
Dessalines 9930c7288a Merge branch 'split_user_table' into strictly_type_db_ids 2021-03-18 16:30:42 -04:00
Dessalines 8d9fab0389 Merge branch 'main' into split_user_table 2021-03-18 16:30:29 -04:00
Dessalines c3efb9f7cf Strictly typing DB id fields. Fixes #1498 2021-03-18 16:25:21 -04:00
Felix Ableitner 4f7dca7c2b Fix three federation test cases 2021-03-18 17:02:15 +01:00
Dessalines 5899b89ef2 Adding some comments to notifs. 2021-03-18 10:59:17 -04:00
Dessalines 99e5a4d1c3 Moving send email check inside function. 2021-03-18 10:52:25 -04:00
Felix Ableitner b3a5b4eb82 Refactor activitypub code 2021-03-17 18:12:37 +01:00
Felix Ableitner 71067a8cb5 For FromApub trait, use `is_mod_action: bool` instead 2021-03-16 18:26:19 +01:00
Felix Ableitner be00f63fb2 Allow remot moderators to do Remove/Post and Remove/Comment 2021-03-16 18:06:59 +01:00
dessalines db4fe8031c Merge pull request 'Insert announced activities into DB for fetching (fixes #1494)' (#187) from insert-local-announce into main
Reviewed-on: https://yerbamate.ml/LemmyNet/lemmy/pulls/187
2021-03-16 13:47:32 +00:00
Dessalines 270ce539bf Removing some TODOS. 2021-03-15 18:18:50 -04:00
Dessalines b9f483bc27 Version 0.10.0-rc.5 2021-03-15 14:50:50 -04:00
Dessalines 8ee624a542 Some changes
- Changing claim name to local_user_id to facilitate logout.
- Changing AddAdmin back to using person_id
2021-03-15 14:02:27 -04:00
Felix Ableitner 621355b6ef Insert announced activities into DB for fetching (fixes #1494) 2021-03-15 13:58:54 +01:00
Nutomic 72b5e0cab5
Merge pull request #1491 from LemmyNet/upgrade_pictrs_3
Upgrading pictrs.
2021-03-15 12:14:31 +00:00
Bogdan Mart 74272ed754 more correct tests 2021-03-13 22:36:40 +02:00
Bogdan Mart 4426c3176d fix timestamp condition #1462 2021-03-13 22:18:26 +02:00
Bogdan Mart 7b0a09e84e Merge remote-tracking branch 'origin/main' into 1462-jwt-revocation-on-pwd-change
* origin/main:
  revert Compose file version from 3.3 to 2.2
  Adding more mem limits
  bump memory limit of iframely
  Remove extra category_id s . Fixes #1429
  Fixing wrong user_ and community icon and banner urls.
  Remove category from activitypub context
  Adding a password length check to other API actions. (#1474)
  Update test script
  Use URL type in most outstanding struct fields (#1468)
  Forbid usage of unwrap
  Upgrade Rust version
  Rewrite settings implementation. Fixes #1270 (#1433)
  Rename `lemmy_structs` to `lemmy_api_structs`

# Conflicts:
#	crates/db_schema/src/source/user.rs
2021-03-13 20:19:55 +02:00
Bogdan Mart ab947f1f08 User token revocation upon password change
Added DB column validator_time and chedking that is is less then token's "Issuead at time"
Wip on #1462
2021-03-13 20:16:35 +02:00
Dessalines 5998c83b2a Only sending private message if its a local user. 2021-03-12 15:18:03 -05:00
Dessalines 434fb53dd1 Trying to fix API tests. 2021-03-12 14:09:03 -05:00
Dessalines 75a95acf04 Change joinuser, sendusermessage to use local_user_id 2021-03-12 10:54:47 -05:00
Felix Ableitner de14636e10 Fix code to allow sticky/lock from remote moderators 2021-03-12 16:46:36 +01:00
dessalines 931a132161 Merge pull request 'Add memory limit for pictrs' (#186) from nutomic-patch-1 into main
Reviewed-on: https://yerbamate.ml/LemmyNet/lemmy/pulls/186
2021-03-12 15:16:49 +00:00
Dessalines 0a7271a185 Upgrading pictrs. 2021-03-12 10:13:20 -05:00
Felix Ableitner de39d57592 WIP: check that modifications are made by same user, add docs 2021-03-12 14:47:55 +01:00
Dessalines 7c039340ed 2nd pass. JWT now uses local_user_id 2021-03-11 17:47:44 -05:00
Felix Ableitner b1ca85b910 Fix clippy warning 2021-03-11 18:18:01 +01:00
Felix Ableitner 50559de6d2 Add check so only mods can change stickied/locked state of posts 2021-03-11 18:11:59 +01:00
Dessalines 7d04f371a5 fixing tests 3 2021-03-11 12:08:30 -05:00
Dessalines 5d8ccbafe4 Fixing some tests 2 2021-03-11 11:54:03 -05:00
Felix Ableitner 803aad3b3e Add check so only author or mods can edit posts/comments 2021-03-11 17:50:47 +01:00
Dessalines 1a4c8c08ee Fixing some tests 2021-03-11 11:41:04 -05:00
Felix Ableitner a2698dea92 Allow for remote mods to remove posts/comments 2021-03-11 17:21:45 +01:00
Dessalines 9cb4dad4b4 A first pass. 2021-03-10 23:43:11 -05:00
Dessalines ddf4a667b1 ~80% done 2021-03-10 17:33:55 -05:00
nutomic fc74bfeb23 Add memory limit for pictrs 2021-03-10 18:38:00 +00:00
Felix Ableitner 3ffae1f5b8 Allow adding remote users as community mods (ref #1061) 2021-03-09 18:14:15 +01:00
Felix Ableitner dcf40db225 Update activitystreams to 0.7.0-alpha.11 2021-03-09 18:14:15 +01:00
Felix Ableitner 9172eff65a Implemented receiving activities to add/remove remote mods 2021-03-09 18:14:15 +01:00
Felix Ableitner 0c484e8c76 Move moderators collection to separate HTTP endpoint 2021-03-09 18:14:15 +01:00
Felix Ableitner beb8b9fe69 Use collection for moderators, instead of `attributedTo` (ref #1061) 2021-03-09 18:14:15 +01:00
Nutomic 8f6b8895f4
Merge pull request #1485 from PatMulligan/fix-docker-compose-yaml
revert Compose file version from 3.3 to 2.2
2021-03-08 15:41:17 +00:00
Patrick Mulligan a650312858 revert Compose file version from 3.3 to 2.2 2021-03-08 09:23:50 -06:00
Dessalines ff2c71a74a Adding more mem limits 2021-03-04 22:41:08 -05:00
Avery Pierce 126c6a23bb bump memory limit of iframely 2021-03-04 08:58:03 -06:00
Nutomic e0c61c1334
Merge pull request #1478 from LemmyNet/fix_wrong_urls
Fixing wrong user_ and community icon and banner urls.
2021-03-04 12:18:30 +00:00
Nutomic f7aa97d45e
Merge pull request #1479 from LemmyNet/fix_extra_categories
Remove extra category_id s . Fixes #1429
2021-03-04 12:14:25 +00:00
Dessalines a1c7584875 Remove extra category_id s . Fixes #1429 2021-03-03 23:44:07 -05:00
Dessalines 817b4ff08e Fixing wrong user_ and community icon and banner urls.
- Fixes #1477
2021-03-03 23:40:00 -05:00
Dessalines ca3c1269f5 Merge branch 'main' of https://github.com/lemmynet/lemmy 2021-03-02 11:52:46 -05:00
dessalines 0a52396706 Merge pull request 'Forbid usage of unwrap' (#179) from clippy-unwrap into main
Reviewed-on: https://yerbamate.ml/LemmyNet/lemmy/pulls/179
2021-03-02 16:49:19 +00:00
dessalines 7c4969c92b Merge pull request 'Remove category from activitypub context' (#183) from context-remove-category into main
Reviewed-on: https://yerbamate.ml/LemmyNet/lemmy/pulls/183
2021-03-02 16:48:24 +00:00
dessalines 45a94203f2 Merge pull request 'Update test script' (#182) from update-test-script into main
Reviewed-on: https://yerbamate.ml/LemmyNet/lemmy/pulls/182
2021-03-02 16:47:58 +00:00
Felix Ableitner 7189328f80 Remove category from activitypub context 2021-03-02 17:12:45 +01:00
Dessalines 134fece36d
Adding a password length check to other API actions. (#1474)
* Adding a password length check to other API actions.

- Fixes #1473

* Fixing comment.
2021-03-02 10:36:10 -05:00
Felix Ableitner 985dbcaada Update test script 2021-03-02 13:57:06 +01:00
Andrew Yoon e78ba38e94
Use URL type in most outstanding struct fields (#1468)
* Use URL type in most outstanding struct fields

This fixes all known remaining cases where url fields are stored as
plain strings, with the exception of form fields where empty strings
are used as sentinels (see `diesel_option_overwrite_to_url`).

Tested for regressions in the federated docker setup attempting to
exercise all changed fields, including through apub federation.

Fixes #1385

* Add migration to fix blank-string post.url values to be null

This also then fixes #602

* Address review feedback

- Fixed some unwraps and err message formatting
- Bumped the `url` library to 2.2.1 to fix a bug with serde error
  messages
- Add unit tests for the two diesel option override functions
- Fix migration teardown by adding a no-op

* Rename lemmy_db_queries::Url to lemmy_db_queries::DbUrl

* fix compile error

* box PostOrComment variants
2021-03-02 12:41:48 +00:00
Felix Ableitner 7f56281c26 Forbid usage of unwrap 2021-03-01 19:24:34 +01:00
dessalines 45e05dac30 Merge pull request 'Upgrade Rust version' (#181) from upgrade-rust into main
Reviewed-on: https://yerbamate.ml/LemmyNet/lemmy/pulls/181
2021-03-01 18:02:39 +00:00
Felix Ableitner 66946117e1 Upgrade Rust version 2021-03-01 18:46:56 +01:00
Dessalines 462c4a2954
Rewrite settings implementation. Fixes #1270 (#1433)
* A first attempt at using deser-hjson. Fixes #1270

* Trying to fix tests, try 1

* Trying to fix tests, try 2

* A few fixes to deser_hjson

- Removing unwrap_or_defaults, using impl functions.
- Reorganized settings

* Make clippy happy

* hjson list strings must be quoted.

* Adding support for env vars.

* Moving to structs and defaults file.

* Moving settings default and struct.
2021-03-01 17:24:11 +00:00
dessalines 5ce8adcb13 Merge pull request 'Rename `lemmy_structs` to `lemmy_api_structs`' (#180) from rename-structs into main
Reviewed-on: https://yerbamate.ml/LemmyNet/lemmy/pulls/180
2021-03-01 15:50:45 +00:00
Felix Ableitner 3bdd78f341 Rename `lemmy_structs` to `lemmy_api_structs` 2021-03-01 14:08:41 +01:00
Dessalines b5aa4cf41a
Merge pull request #1465 from arjenpdevries/patch-2
Update README.md
2021-02-27 18:08:58 -05:00
Arjen P. de Vries a5e2463097
Update README.md
Federation is probably more complete than suggested here.

In response to:
https://github.com/LemmyNet/lemmy/issues/647#issuecomment-787068478
2021-02-27 20:26:30 +01:00
Dessalines a869a2823b Still continuing on.... 2021-02-26 08:49:58 -05:00
dessalines ff3e26452a Merge pull request 'Remove federation backward compatibility code (ref #1220)' (#164) from remove-backwards-compatibility into main
Reviewed-on: https://yerbamate.ml/LemmyNet/lemmy/pulls/164
2021-02-26 13:23:46 +00:00
dessalines da5b27ecc6 Merge pull request 'Remove code for apub compatibility with Lemmy v0.8.9 and older' (#178) from remove-apub-compat-code into main
Reviewed-on: https://yerbamate.ml/LemmyNet/lemmy/pulls/178
2021-02-26 13:23:07 +00:00
Felix Ableitner c618b4efaa Remove federation backward compatibility code (ref #1220) 2021-02-26 14:06:26 +01:00
Felix Ableitner 4cc341e4aa Remove code for apub compatibility with Lemmy v0.8.9 and older 2021-02-26 14:03:49 +01:00
Nutomic 82d97cf6de
Merge pull request #1455 from ajyoon/fix-flaky-db-tests
Support plain `cargo test` and disable unused doctests for speed
2021-02-25 22:54:40 +00:00
Andrew Yoon 600ae662a5 Support plain `cargo test` and disable unused doctests for speed
Since DB tests execute diesel migrations automatically, concurrent
execution causes flaky failures from simultaneous migrations. This can
be worked around using `cargo test --workspace -- --test-threads=1`,
which is what the CI config does, but this is not intuitive for
newcomer developers and unnecessarily slows down the test suite for
the majority of tests which are safe to run concurrently. This fixes
this issue by integrating with the small test crate `serial_test` and
using it to explicitly mark DB tests to run sequentially while
allowing all other tests to run in parallel.

Additionally, this greatly improves the speed of `cargo test` by
disabling doc-tests in all crates, since these are aren't currently
used and cargo's doc-test pass, even when no doc-tests exist, has
significant overhead. On my machine, this change significantly
improves test suite times by about 85%, making it much more practical
to develop with tools like `cargo watch` auto-running tests.
2021-02-25 15:44:30 -05:00
Dessalines efc9047f87 Done with user->person migrations, now to code. 2021-02-25 14:04:12 -05:00
Dessalines aba32917bd Merge branch 'main' into split_user_table 2021-02-25 12:34:00 -05:00
Dessalines ea3c0e1772 Merge branch 'main' into remove-integration-tests 2021-02-25 11:37:54 -05:00
Dessalines 058052b46c Merge remote-tracking branch 'yerba/main' 2021-02-25 11:36:08 -05:00
dessalines 7c87da012e Merge pull request 'Remove categories (fixes #1429)' (#176) from remove-categories into main
Reviewed-on: https://yerbamate.ml/LemmyNet/lemmy/pulls/176
2021-02-25 16:35:07 +00:00
Felix Ableitner bf1e859e72 Remove broken actix_rt test 2021-02-25 17:25:31 +01:00
Felix Ableitner 289cef3101 Remove integration tests (fixes #1449) 2021-02-25 16:31:41 +01:00
Nutomic 085c307b8b
Merge pull request #1451 from LemmyNet/update_cargo_chef
Use more recent version of cargo chef.
2021-02-25 15:19:29 +00:00
Felix Ableitner 72783edb17 In remove categories down migration, add default for category 2021-02-25 16:16:02 +01:00
Felix Ableitner 3141ad31de Remove categories (fixes #1429) 2021-02-25 13:22:37 +01:00
dessalines 40ceec9737 Merge pull request 'Better type safety for activity parsing' (#175) from apub-type-safety into main
Reviewed-on: https://yerbamate.ml/LemmyNet/lemmy/pulls/175
2021-02-24 22:20:15 +00:00
Dessalines 723ec65ac6 Use more recent version of cargo chef. 2021-02-24 17:10:28 -05:00
Felix Ableitner 3ae62573b7 Better type safety for activity parsing 2021-02-24 20:37:27 +01:00
dessalines 6499709221 Merge pull request 'Dont include community in comment `to` field (fixes #1446)' (#174) from no-community-in-comment-to into main
Reviewed-on: https://yerbamate.ml/LemmyNet/lemmy/pulls/174
2021-02-24 01:03:07 +00:00
Felix Ableitner 813fcabe13 Fix lemmy_dev ansible playbook 2021-02-23 19:35:09 +01:00
Felix Ableitner 92ea9b97dd Dont include community in comment `to` field (fixes #1446) 2021-02-23 19:00:47 +01:00
dessalines 0c9b109bf7 Merge pull request 'Order outbox by published, not id' (#171) from outbox-order-published into main
Reviewed-on: https://yerbamate.ml/LemmyNet/lemmy/pulls/171
2021-02-22 20:37:06 +00:00
dessalines 2cbd158a11 Merge pull request 'Use `name` field for post titles instead of `summary` (ref #1220)' (#173) from apub-post-name into main
Reviewed-on: https://yerbamate.ml/LemmyNet/lemmy/pulls/173
2021-02-22 20:36:22 +00:00
dessalines 7dc3ff4544 Merge pull request 'Fix clippy error upper_case_acronyms' (#172) from fix-clippy into main
Reviewed-on: https://yerbamate.ml/LemmyNet/lemmy/pulls/172
2021-02-22 20:34:22 +00:00
Felix Ableitner 8d5e9f865c Use `name` field for post titles instead of `summary` (ref #1220) 2021-02-22 19:34:41 +01:00
Felix Ableitner 8096765f0e Fix clippy error upper_case_acronyms 2021-02-22 19:04:32 +01:00
Dessalines 8eb81bb153 Updating release version. 2021-02-19 13:11:16 -05:00
Dessalines c81435c994 Version 0.9.9 2021-02-19 13:10:04 -05:00
Nutomic 7548b44d1b
Merge pull request #1442 from LemmyNet/fix_deploy_version_1
Fixing deploy version.
2021-02-19 18:09:27 +00:00
Dessalines bcc8dae16b Fixing deploy version. 2021-02-19 13:05:42 -05:00
Dessalines b014ac44c8 Adding 0.9.8 release notes. 2021-02-19 12:41:51 -05:00
Dessalines a806493bc2 Version 0.9.8 2021-02-19 11:38:24 -05:00
Felix Ableitner b593047fb1 Order outbox by published, not id 2021-02-19 15:59:06 +01:00
Dessalines 9845366a36 Merge remote-tracking branch 'yerba/main' 2021-02-18 16:19:39 -05:00
dessalines 15d0f54a88 Merge pull request 'Specify order for activities query (fixes #1436)' (#169) from outbox-order into main
Reviewed-on: https://yerbamate.ml/LemmyNet/lemmy/pulls/169
2021-02-18 21:18:26 +00:00
Dessalines 8088055d38
Fix aggregates time columns 2 (#1427)
* Adding a new comment sort. Fixes #1294

* Fixing a migration comment.

* Adding a comment for newest_comment_time_necro

* Make sure federated items set correct aggregates fields in trigger.

- Fixes #1402
2021-02-18 10:53:04 -05:00
Dessalines 0c4b57a6d0
Adding a new comment sort for posts. Fixes #1294 (#1425)
* Adding a new comment sort. Fixes #1294

* Fixing a migration comment.

* Adding a comment for newest_comment_time_necro
2021-02-18 10:38:25 -05:00
Dessalines a183815870 Adding a few more tables. 2021-02-15 14:34:10 -05:00
Dessalines d0bd02eea0 Starting on user_ to person migration. 2021-02-14 13:46:16 -05:00
Dessalines 5a33fce8bd Listing columns. 2021-02-10 11:05:12 -05:00
1167 changed files with 99195 additions and 45001 deletions

View File

@ -4,5 +4,5 @@ docker
api_tests
ansible
tests
.git
*.sh
pictrs

View File

@ -1,177 +0,0 @@
---
kind: pipeline
name: amd64
platform:
os: linux
arch: amd64
steps:
- name: chown repo
image: ekidd/rust-musl-builder:1.47.0
user: root
commands:
- chown 1000:1000 . -R
- name: check formatting
image: rustdocker/rust:nightly
commands:
- /root/.cargo/bin/cargo fmt -- --check
- name: cargo clippy
image: ekidd/rust-musl-builder:1.47.0
commands:
- cargo clippy --workspace --tests --all-targets --all-features -- -D warnings -D deprecated -D clippy::perf -D clippy::complexity -D clippy::dbg_macro
- name: cargo test
image: ekidd/rust-musl-builder:1.47.0
environment:
LEMMY_DATABASE_URL: postgres://lemmy:password@database:5432/lemmy
RUST_BACKTRACE: 1
RUST_TEST_THREADS: 1
commands:
- sudo apt-get update
- sudo apt-get -y install --no-install-recommends espeak postgresql-client
- cargo test --workspace --no-fail-fast
- name: cargo build
image: ekidd/rust-musl-builder:1.47.0
commands:
- cargo build
- mv target/x86_64-unknown-linux-musl/debug/lemmy_server target/lemmy_server
- name: run federation tests
image: node:15-alpine3.12
environment:
LEMMY_DATABASE_URL: postgres://lemmy:password@database:5432
DO_WRITE_HOSTS_FILE: 1
commands:
- apk add bash curl postgresql-client
- bash api_tests/prepare-drone-federation-test.sh
- cd api_tests/
- yarn
- yarn api-test
- name: make release build and push to docker hub
image: plugins/docker
settings:
dockerfile: docker/prod/Dockerfile
username:
from_secret: docker_username
password:
from_secret: docker_password
repo: dessalines/lemmy
auto_tag: true
auto_tag_suffix: linux-amd64
when:
ref:
- refs/tags/*
- name: push to docker manifest
image: plugins/manifest
settings:
username:
from_secret: docker_username
password:
from_secret: docker_password
target: "dessalines/lemmy:${DRONE_TAG}"
template: "dessalines/lemmy:${DRONE_TAG}-OS-ARCH"
platforms:
- linux/amd64
- linux/arm64
ignore_missing: true
when:
ref:
- refs/tags/*
services:
- name: database
image: postgres:12-alpine
environment:
POSTGRES_USER: lemmy
POSTGRES_PASSWORD: password
---
kind: pipeline
name: arm64
platform:
os: linux
arch: arm64
steps:
- name: cargo test
image: rust:1.47-slim-buster
environment:
LEMMY_DATABASE_URL: postgres://lemmy:password@database:5432/lemmy
RUST_BACKTRACE: 1
RUST_TEST_THREADS: 1
commands:
- apt-get update
- apt-get -y install --no-install-recommends espeak postgresql-client libssl-dev pkg-config libpq-dev
- cargo test --workspace --no-fail-fast
- cargo build
# Using Debian here because there seems to be no official Alpine-based Rust docker image for ARM.
- name: cargo build
image: rust:1.47-slim-buster
commands:
- apt-get update
- apt-get -y install --no-install-recommends libssl-dev pkg-config libpq-dev
- cargo build
- mv target/debug/lemmy_server target/lemmy_server
- name: run federation tests
image: node:15-buster-slim
environment:
LEMMY_DATABASE_URL: postgres://lemmy:password@database:5432
DO_WRITE_HOSTS_FILE: 1
commands:
- mkdir -p /usr/share/man/man1 /usr/share/man/man7
- apt-get update
- apt-get -y install --no-install-recommends bash curl libssl-dev pkg-config libpq-dev postgresql-client libc6-dev
- bash api_tests/prepare-drone-federation-test.sh
- cd api_tests/
- yarn
- yarn api-test
- name: make release build and push to docker hub
image: plugins/docker
settings:
dockerfile: docker/prod/Dockerfile.arm
username:
from_secret: docker_username
password:
from_secret: docker_password
repo: dessalines/lemmy
auto_tag: true
auto_tag_suffix: linux-arm64
when:
ref:
- refs/tags/*
- name: push to docker manifest
image: plugins/manifest
settings:
username:
from_secret: docker_username
password:
from_secret: docker_password
target: "dessalines/lemmy:${DRONE_TAG}"
template: "dessalines/lemmy:${DRONE_TAG}-OS-ARCH"
platforms:
- linux/amd64
- linux/arm64
ignore_missing: true
when:
ref:
- refs/tags/*
services:
- name: database
image: postgres:12-alpine
environment:
POSTGRES_USER: lemmy
POSTGRES_PASSWORD: password

2
.gitattributes vendored Normal file
View File

@ -0,0 +1,2 @@
# Normalize EOL for all files that Git considers text files.
* text=auto eol=lf

3
.github/CODEOWNERS vendored Normal file
View File

@ -0,0 +1,3 @@
* @Nutomic @dessalines @phiresky @dullbananas @SleeplessOne1917
crates/apub/ @Nutomic
migrations/ @dessalines @phiresky @dullbananas

View File

@ -1,29 +0,0 @@
---
name: "\U0001F41E Bug Report"
about: Create a report to help us improve Lemmy
title: ''
labels: bug
assignees: ''
---
Found a bug? Please fill out the sections below. 👍
For front end issues, use [lemmy-ui](https://github.com/LemmyNet/lemmy-ui)
### Issue Summary
A summary of the bug.
### Steps to Reproduce
1. (for example) I clicked login, and an endless spinner show up.
2. I tried to install lemmy via this guide, and I'm getting this error.
3. ...
### Technical details
* Please post your log: `sudo docker-compose logs > lemmy_log.out`.
* What OS are you trying to install lemmy on?
* Any browser console errors?

70
.github/ISSUE_TEMPLATE/BUG_REPORT.yml vendored Normal file
View File

@ -0,0 +1,70 @@
name: "\U0001F41E Bug Report"
description: Create a report to help us improve lemmy
title: "[Bug]: "
labels: ["bug", "triage"]
body:
- type: markdown
attributes:
value: |
Found a bug? Please fill out the sections below. 👍
Thanks for taking the time to fill out this bug report!
For front end issues, use [lemmy](https://github.com/LemmyNet/lemmy-ui)
- type: checkboxes
attributes:
label: Requirements
description: Before you create a bug report please do the following.
options:
- label: Is this a bug report? For questions or discussions use https://lemmy.ml/c/lemmy_support
required: true
- label: Did you check to see if this issue already exists?
required: true
- label: Is this only a single bug? Do not put multiple bugs in one issue.
required: true
- label: Do you agree to follow the rules in our [Code of Conduct](https://join-lemmy.org/docs/code_of_conduct.html)?
required: true
- label: Is this a backend issue? Use the [lemmy-ui](https://github.com/LemmyNet/lemmy-ui) repo for UI / frontend issues.
required: true
- type: textarea
id: summary
attributes:
label: Summary
description: A summary of the bug.
validations:
required: true
- type: textarea
id: reproduce
attributes:
label: Steps to Reproduce
description: |
Describe the steps to reproduce the bug.
The better your description is _(go 'here', click 'there'...)_ the fastest you'll get an _(accurate)_ resolution.
value: |
1.
2.
3.
validations:
required: true
- type: textarea
id: technical
attributes:
label: Technical Details
description: |
- Please post your log: `sudo docker-compose logs > lemmy_log.out`.
- What OS are you trying to install lemmy on?
- Any browser console errors?
validations:
required: true
- type: input
id: lemmy-backend-version
attributes:
label: Version
description: Which Lemmy backend version do you use? Displayed in the footer.
placeholder: ex. BE 0.17.4
validations:
required: true
- type: input
id: lemmy-instance
attributes:
label: Lemmy Instance URL
description: Which Lemmy instance do you use? The address
placeholder: lemmy.ml, lemmy.world, etc

View File

@ -1,44 +0,0 @@
---
name: "\U0001F680 Feature request"
about: Suggest an idea for improving Lemmy
title: ''
labels: enhancement
assignees: ''
---
For front end issues, use [lemmy-ui](https://github.com/LemmyNet/lemmy-ui)
### Is your proposal related to a problem?
<!--
Provide a clear and concise description of what the problem is.
For example, "I'm always frustrated when..."
-->
(Write your answer here.)
### Describe the solution you'd like
<!--
Provide a clear and concise description of what you want to happen.
-->
(Describe your proposed solution here.)
### Describe alternatives you've considered
<!--
Let us know about other solutions you've tried or researched.
-->
(Write your answer here.)
### Additional context
<!--
Is there anything else you can add about the proposal?
You might want to link to related issues here, if you haven't already.
-->
(Write your answer here.)

View File

@ -0,0 +1,56 @@
name: "\U0001F680 Feature request"
description: Suggest an idea for improving Lemmy
labels: ["enhancement"]
body:
- type: markdown
attributes:
value: |
Have a suggestion about Lemmy's UI?
For backend issues, use [lemmy](https://github.com/LemmyNet/lemmy)
- type: checkboxes
attributes:
label: Requirements
description: Before you create a bug report please do the following.
options:
- label: Is this a feature request? For questions or discussions use https://lemmy.ml/c/lemmy_support
required: true
- label: Did you check to see if this issue already exists?
required: true
- label: Is this only a feature request? Do not put multiple feature requests in one issue.
required: true
- label: Is this a backend issue? Use the [lemmy-ui](https://github.com/LemmyNet/lemmy-ui) repo for UI / frontend issues.
required: true
- label: Do you agree to follow the rules in our [Code of Conduct](https://join-lemmy.org/docs/code_of_conduct.html)?
required: true
- type: textarea
id: problem
attributes:
label: Is your proposal related to a problem?
description: |
Provide a clear and concise description of what the problem is.
For example, "I'm always frustrated when..."
validations:
required: true
- type: textarea
id: solution
attributes:
label: Describe the solution you'd like.
description: |
Provide a clear and concise description of what you want to happen.
validations:
required: true
- type: textarea
id: alternatives
attributes:
label: Describe alternatives you've considered.
description: |
Let us know about other solutions you've tried or researched.
validations:
required: true
- type: textarea
id: context
attributes:
label: Additional context
description: |
Is there anything else you can add about the proposal?
You might want to link to related issues here, if you haven't already.

View File

@ -1,10 +0,0 @@
---
name: "? Question"
about: General questions about Lemmy
title: ''
labels: question
assignees: ''
---
What's the question you have about lemmy?

17
.github/ISSUE_TEMPLATE/QUESTION.yml vendored Normal file
View File

@ -0,0 +1,17 @@
name: "? Question"
description: General questions about Lemmy
title: "Question: "
labels: ["question", "triage"]
body:
- type: markdown
attributes:
value: |
Have a question about Lemmy?
Please check the docs first: https://join-lemmy.org/docs/en/index.html
- type: textarea
id: question
attributes:
label: Question
description: What's the question you have about Lemmy?
validations:
required: true

17
.gitignore vendored
View File

@ -1,6 +1,5 @@
# local ansible configuration
ansible/inventory
ansible/inventory_dev
ansible/passwords/
# docker build files
@ -19,3 +18,19 @@ query_testing/**/reports/*.json
# API tests
api_tests/node_modules
api_tests/.yalc
api_tests/yalc.lock
api_tests/pict-rs
# pictrs data
pictrs/
# The generated typescript bindings
bindings
# Database cluster and sockets for testing
dev_pgdata/
*.PGSQL.*
# database dumps
*.sqldump

4
.gitmodules vendored Normal file
View File

@ -0,0 +1,4 @@
[submodule "crates/utils/translations"]
path = crates/utils/translations
url = https://github.com/LemmyNet/lemmy-translations.git
branch = main

View File

@ -1 +0,0 @@
*.sql

View File

@ -1,5 +1,7 @@
tab_spaces = 2
edition="2018"
imports_layout="HorizontalVertical"
merge_imports=true
reorder_imports=true
edition = "2021"
imports_layout = "HorizontalVertical"
imports_granularity = "Crate"
group_imports = "One"
wrap_comments = true
comment_width = 100

312
.woodpecker.yml Normal file
View File

@ -0,0 +1,312 @@
# TODO: The when: platform conditionals aren't working currently
# See https://github.com/woodpecker-ci/woodpecker/issues/1677
variables:
- &rust_image "rust:1.77"
- &rust_nightly_image "rustlang/rust:nightly"
- &install_pnpm "corepack enable pnpm"
- &slow_check_paths
- event: pull_request
path:
include: [
# rust source code
"crates/**",
"src/**",
"**/Cargo.toml",
"Cargo.lock",
# database migrations
"migrations/**",
# typescript tests
"api_tests/**",
# config files and scripts used by ci
".woodpecker.yml",
".rustfmt.toml",
"scripts/update_config_defaults.sh",
"diesel.toml",
".gitmodules",
]
- install_binstall: &install_binstall
- wget https://github.com/cargo-bins/cargo-binstall/releases/latest/download/cargo-binstall-x86_64-unknown-linux-musl.tgz
- tar -xvf cargo-binstall-x86_64-unknown-linux-musl.tgz
- cp cargo-binstall /usr/local/cargo/bin
- install_diesel_cli: &install_diesel_cli
- apt update && apt install -y lsb-release build-essential
- sh -c 'echo "deb https://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list'
- wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | apt-key add -
- apt update && apt install -y postgresql-client-16
- cargo install diesel_cli --no-default-features --features postgres
- export PATH="$CARGO_HOME/bin:$PATH"
steps:
prepare_repo:
image: alpine:3
commands:
- apk add git
- git submodule init
- git submodule update
when:
- event: [pull_request, tag]
prettier_check:
image: tmknom/prettier:3.0.0
commands:
- prettier -c . '!**/volumes' '!**/dist' '!target' '!**/translations' '!api_tests/pnpm-lock.yaml'
when:
- event: pull_request
toml_fmt:
image: tamasfe/taplo:0.8.1
commands:
- taplo format --check
when:
- event: pull_request
sql_fmt:
image: backplane/pgformatter
commands:
- ./scripts/sql_format_check.sh
when:
- event: pull_request
cargo_fmt:
image: *rust_nightly_image
environment:
# store cargo data in repo folder so that it gets cached between steps
CARGO_HOME: .cargo_home
commands:
- rustup component add rustfmt
- cargo +nightly fmt -- --check
when:
- event: pull_request
cargo_machete:
image: *rust_nightly_image
commands:
- <<: *install_binstall
- cargo binstall -y cargo-machete
- cargo machete
when:
- event: pull_request
ignored_files:
image: alpine:3
commands:
- apk add git
- IGNORED=$(git ls-files --cached -i --exclude-standard)
- if [[ "$IGNORED" ]]; then echo "Ignored files present:\n$IGNORED\n"; exit 1; fi
when:
- event: pull_request
# make sure api builds with default features (used by other crates relying on lemmy api)
check_api_common_default_features:
image: *rust_image
environment:
CARGO_HOME: .cargo_home
commands:
- cargo check --package lemmy_api_common
when: *slow_check_paths
lemmy_api_common_doesnt_depend_on_diesel:
image: *rust_image
environment:
CARGO_HOME: .cargo_home
commands:
- "! cargo tree -p lemmy_api_common --no-default-features -i diesel"
when: *slow_check_paths
lemmy_api_common_works_with_wasm:
image: *rust_image
environment:
CARGO_HOME: .cargo_home
commands:
- "rustup target add wasm32-unknown-unknown"
- "cargo check --target wasm32-unknown-unknown -p lemmy_api_common"
when: *slow_check_paths
check_defaults_hjson_updated:
image: *rust_image
environment:
CARGO_HOME: .cargo_home
commands:
- export LEMMY_CONFIG_LOCATION=./config/config.hjson
- ./scripts/update_config_defaults.sh config/defaults_current.hjson
- diff config/defaults.hjson config/defaults_current.hjson
when: *slow_check_paths
check_diesel_schema:
image: *rust_image
environment:
CARGO_HOME: .cargo_home
DATABASE_URL: postgres://lemmy:password@database:5432/lemmy
commands:
- <<: *install_diesel_cli
- diesel migration run
- diesel print-schema --config-file=diesel.toml > tmp.schema
- diff tmp.schema crates/db_schema/src/schema.rs
when: *slow_check_paths
check_db_perf_tool:
image: *rust_image
environment:
LEMMY_DATABASE_URL: postgres://lemmy:password@database:5432/lemmy
RUST_BACKTRACE: "1"
CARGO_HOME: .cargo_home
commands:
# same as scripts/db_perf.sh but without creating a new database server
- export LEMMY_CONFIG_LOCATION=config/config.hjson
- cargo run --package lemmy_db_perf -- --posts 10 --read-post-pages 1
when: *slow_check_paths
cargo_clippy:
image: *rust_image
environment:
CARGO_HOME: .cargo_home
commands:
- rustup component add clippy
- cargo clippy --workspace --tests --all-targets --features console -- -D warnings
when: *slow_check_paths
cargo_build:
image: *rust_image
environment:
CARGO_HOME: .cargo_home
commands:
- cargo build
- mv target/debug/lemmy_server target/lemmy_server
when: *slow_check_paths
cargo_test:
image: *rust_image
environment:
LEMMY_DATABASE_URL: postgres://lemmy:password@database:5432/lemmy
RUST_BACKTRACE: "1"
CARGO_HOME: .cargo_home
commands:
- export LEMMY_CONFIG_LOCATION=../../config/config.hjson
- cargo test --workspace --no-fail-fast
when: *slow_check_paths
check_diesel_migration:
# TODO: use willsquire/diesel-cli image when shared libraries become optional in lemmy_server
image: *rust_image
environment:
LEMMY_DATABASE_URL: postgres://lemmy:password@database:5432/lemmy
RUST_BACKTRACE: "1"
CARGO_HOME: .cargo_home
DATABASE_URL: postgres://lemmy:password@database:5432/lemmy
PGUSER: lemmy
PGPASSWORD: password
PGHOST: database
PGDATABASE: lemmy
commands:
# Install diesel_cli
- <<: *install_diesel_cli
# Run all migrations
- diesel migration run
# Dump schema to before.sqldump (PostgreSQL apt repo is used to prevent pg_dump version mismatch error)
- apt update && apt install -y lsb-release
- sh -c 'echo "deb https://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list'
- wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | apt-key add -
- apt update && apt install -y postgresql-client-16
- psql -c "DROP SCHEMA IF EXISTS r CASCADE;"
- pg_dump --no-owner --no-privileges --no-table-access-method --schema-only --no-sync -f before.sqldump
# Make sure that the newest migration is revertable without the `r` schema
- diesel migration redo
# Run schema setup twice, which fails on the 2nd time if `DROP SCHEMA IF EXISTS r CASCADE` drops the wrong things
- alias lemmy_schema_setup="target/lemmy_server --disable-scheduled-tasks --disable-http-server --disable-activity-sending"
- lemmy_schema_setup
- lemmy_schema_setup
# Make sure that the newest migration is revertable with the `r` schema
- diesel migration redo
# Check for changes in the schema, which would be caused by an incorrect migration
- psql -c "DROP SCHEMA IF EXISTS r CASCADE;"
- pg_dump --no-owner --no-privileges --no-table-access-method --schema-only --no-sync -f after.sqldump
- diff before.sqldump after.sqldump
when: *slow_check_paths
run_federation_tests:
image: node:20-bookworm-slim
environment:
LEMMY_DATABASE_URL: postgres://lemmy:password@database:5432
DO_WRITE_HOSTS_FILE: "1"
commands:
- *install_pnpm
- apt update && apt install -y bash curl postgresql-client
- bash api_tests/prepare-drone-federation-test.sh
- cd api_tests/
- pnpm i
- pnpm api-test
when: *slow_check_paths
federation_tests_server_output:
image: alpine:3
commands:
# `|| true` prevents this step from appearing to fail if the server output files don't exist
- cat target/log/lemmy_*.out || true
- "# If you can't see all output, then use the download button"
when:
- event: pull_request
status: failure
publish_release_docker:
image: woodpeckerci/plugin-docker-buildx
secrets: [docker_username, docker_password]
settings:
repo: dessalines/lemmy
dockerfile: docker/Dockerfile
platforms: linux/amd64, linux/arm64
build_args:
- RUST_RELEASE_MODE=release
tag: ${CI_COMMIT_TAG}
when:
- event: tag
nightly_build:
image: woodpeckerci/plugin-docker-buildx
secrets: [docker_username, docker_password]
settings:
repo: dessalines/lemmy
dockerfile: docker/Dockerfile
platforms: linux/amd64,linux/arm64
build_args:
- RUST_RELEASE_MODE=release
tag: dev
when:
- event: cron
# using https://github.com/pksunkara/cargo-workspaces
publish_to_crates_io:
image: *rust_image
commands:
- <<: *install_binstall
# Install cargo-workspaces
- cargo binstall -y cargo-workspaces
- cp -r migrations crates/db_schema/
- cargo workspaces publish --token "$CARGO_API_TOKEN" --from-git --allow-dirty --no-verify --allow-branch "${CI_COMMIT_TAG}" --yes custom "${CI_COMMIT_TAG}"
secrets: [cargo_api_token]
when:
- event: tag
notify_on_failure:
image: alpine:3
commands:
- apk add curl
- "curl -d'Lemmy CI build failed: ${CI_PIPELINE_URL}' ntfy.sh/lemmy_drone_ci"
when:
- event: [pull_request, tag]
status: failure
notify_on_tag_deploy:
image: alpine:3
commands:
- apk add curl
- "curl -d'lemmy:${CI_COMMIT_TAG} deployed' ntfy.sh/lemmy_drone_ci"
when:
- event: tag
services:
database:
image: postgres:16-alpine
environment:
POSTGRES_USER: lemmy
POSTGRES_PASSWORD: password

View File

@ -1,4 +0,0 @@
# Contributing
See [here](https://join.lemmy.ml/docs/en/contributing/contributing.html) for contributing Instructions.

7012
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,59 +1,210 @@
[workspace.package]
version = "0.19.4-rc.2"
edition = "2021"
description = "A link aggregator for the fediverse"
license = "AGPL-3.0"
homepage = "https://join-lemmy.org/"
documentation = "https://join-lemmy.org/docs/en/index.html"
repository = "https://github.com/LemmyNet/lemmy"
[package]
name = "lemmy_server"
version = "0.0.1"
edition = "2018"
version.workspace = true
edition.workspace = true
description.workspace = true
license.workspace = true
homepage.workspace = true
documentation.workspace = true
repository.workspace = true
publish = false
[lib]
doctest = false
[lints]
workspace = true
[profile.release]
debug = 0
lto = "thin"
strip = true # Automatically strip symbols from the binary.
opt-level = "z" # Optimize for size.
# This profile significantly speeds up build time. If debug info is needed you can comment the line
# out temporarily, but make sure to leave this in the main branch.
[profile.dev]
debug = 0
[features]
embed-pictrs = ["pict-rs"]
# This feature requires building with `tokio_unstable` flag, see documentation:
# https://docs.rs/tokio/latest/tokio/#unstable-features
console = [
"console-subscriber",
"opentelemetry",
"opentelemetry-otlp",
"tracing-opentelemetry",
"reqwest-tracing/opentelemetry_0_16",
]
json-log = ["tracing-subscriber/json"]
default = []
[workspace]
members = [
"crates/api",
"crates/apub",
"crates/utils",
"crates/db_queries",
"crates/db_schema",
"crates/db_views",
"crates/db_views_actor",
"crates/db_views_actor",
"crates/structs",
"crates/websocket",
"crates/routes"
"crates/api",
"crates/api_crud",
"crates/api_common",
"crates/apub",
"crates/utils",
"crates/db_perf",
"crates/db_schema",
"crates/db_views",
"crates/db_views_actor",
"crates/db_views_actor",
"crates/routes",
"crates/federate",
]
[dependencies]
lemmy_api = { path = "./crates/api" }
lemmy_apub = { path = "./crates/apub" }
lemmy_utils = { path = "./crates/utils" }
lemmy_db_schema = { path = "./crates/db_schema" }
lemmy_db_queries = { path = "./crates/db_queries" }
lemmy_db_views = { path = "./crates/db_views" }
lemmy_db_views_moderator = { path = "./crates/db_views_moderator" }
lemmy_db_views_actor = { path = "./crates/db_views_actor" }
lemmy_structs = { path = "./crates/structs" }
lemmy_websocket = { path = "./crates/websocket" }
lemmy_routes = { path = "./crates/routes" }
diesel = "1.4.5"
diesel_migrations = "1.4.0"
chrono = { version = "0.4.19", features = ["serde"] }
serde = { version = "1.0.123", features = ["derive"] }
actix = "0.10.0"
actix-web = { version = "3.3.2", default-features = false, features = ["rustls"] }
log = "0.4.14"
env_logger = "0.8.2"
strum = "0.20.0"
url = { version = "2.2.0", features = ["serde"] }
openssl = "0.10.32"
http-signature-normalization-actix = { version = "0.4.1", default-features = false, features = ["sha-2"] }
tokio = "0.3.6"
anyhow = "1.0.38"
reqwest = { version = "0.10.10", features = ["json"] }
activitystreams = "0.7.0-alpha.10"
actix-rt = { version = "1.1.1", default-features = false }
serde_json = { version = "1.0.61", features = ["preserve_order"] }
clokwerk = "0.3.4"
[workspace.lints.clippy]
cast_lossless = "deny"
complexity = { level = "deny", priority = -1 }
correctness = { level = "deny", priority = -1 }
dbg_macro = "deny"
explicit_into_iter_loop = "deny"
explicit_iter_loop = "deny"
get_first = "deny"
implicit_clone = "deny"
indexing_slicing = "deny"
inefficient_to_string = "deny"
items-after-statements = "deny"
manual_string_new = "deny"
needless_collect = "deny"
perf = { level = "deny", priority = -1 }
redundant_closure_for_method_calls = "deny"
style = { level = "deny", priority = -1 }
suspicious = { level = "deny", priority = -1 }
uninlined_format_args = "allow"
unused_self = "deny"
unwrap_used = "deny"
[dev-dependencies.cargo-husky]
version = "1.5.0"
default-features = false # Disable features which are enabled by default
features = ["precommit-hook", "run-cargo-fmt", "run-cargo-clippy"]
[workspace.dependencies]
lemmy_api = { version = "=0.19.4-rc.2", path = "./crates/api" }
lemmy_api_crud = { version = "=0.19.4-rc.2", path = "./crates/api_crud" }
lemmy_apub = { version = "=0.19.4-rc.2", path = "./crates/apub" }
lemmy_utils = { version = "=0.19.4-rc.2", path = "./crates/utils", default-features = false }
lemmy_db_schema = { version = "=0.19.4-rc.2", path = "./crates/db_schema" }
lemmy_api_common = { version = "=0.19.4-rc.2", path = "./crates/api_common" }
lemmy_routes = { version = "=0.19.4-rc.2", path = "./crates/routes" }
lemmy_db_views = { version = "=0.19.4-rc.2", path = "./crates/db_views" }
lemmy_db_views_actor = { version = "=0.19.4-rc.2", path = "./crates/db_views_actor" }
lemmy_db_views_moderator = { version = "=0.19.4-rc.2", path = "./crates/db_views_moderator" }
lemmy_federate = { version = "=0.19.4-rc.2", path = "./crates/federate" }
activitypub_federation = { version = "0.5.6", default-features = false, features = [
"actix-web",
] }
diesel = "2.1.6"
diesel_migrations = "2.1.0"
diesel-async = "0.4.1"
serde = { version = "1.0.202", features = ["derive"] }
serde_with = "3.8.1"
actix-web = { version = "4.6.0", default-features = false, features = [
"macros",
"rustls",
"compress-brotli",
"compress-gzip",
"compress-zstd",
"cookies",
] }
tracing = "0.1.40"
tracing-actix-web = { version = "0.7.10", default-features = false }
tracing-error = "0.2.0"
tracing-log = "0.2.0"
tracing-subscriber = { version = "0.3.18", features = ["env-filter"] }
url = { version = "2.5.0", features = ["serde"] }
reqwest = { version = "0.11.27", features = ["json", "blocking", "gzip"] }
reqwest-middleware = "0.2.5"
reqwest-tracing = "0.4.8"
clokwerk = "0.4.0"
doku = { version = "0.21.1", features = ["url-2"] }
bcrypt = "0.15.1"
chrono = { version = "0.4.38", features = ["serde"], default-features = false }
serde_json = { version = "1.0.117", features = ["preserve_order"] }
base64 = "0.22.1"
uuid = { version = "1.8.0", features = ["serde", "v4"] }
async-trait = "0.1.80"
captcha = "0.0.9"
anyhow = { version = "1.0.86", features = [
"backtrace",
] } # backtrace is on by default on nightly, but not stable rust
diesel_ltree = "0.3.1"
typed-builder = "0.18.2"
serial_test = "3.1.1"
tokio = { version = "1.37.0", features = ["full"] }
regex = "1.10.4"
once_cell = "1.19.0"
diesel-derive-newtype = "2.1.2"
diesel-derive-enum = { version = "2.1.0", features = ["postgres"] }
strum = "0.26.2"
strum_macros = "0.26.2"
itertools = "0.13.0"
futures = "0.3.30"
http = "0.2.12"
rosetta-i18n = "0.1.3"
opentelemetry = { version = "0.19.0", features = ["rt-tokio"] }
tracing-opentelemetry = { version = "0.19.0" }
ts-rs = { version = "7.1.1", features = [
"serde-compat",
"chrono-impl",
"no-serde-warnings",
] }
rustls = { version = "0.23.8", features = ["ring"] }
futures-util = "0.3.30"
tokio-postgres = "0.7.10"
tokio-postgres-rustls = "0.12.0"
urlencoding = "2.1.3"
enum-map = "2.7"
moka = { version = "0.12.7", features = ["future"] }
i-love-jesus = { version = "0.1.0" }
clap = { version = "4.5.4", features = ["derive", "env"] }
pretty_assertions = "1.4.0"
[dependencies]
lemmy_api = { workspace = true }
lemmy_api_crud = { workspace = true }
lemmy_apub = { workspace = true }
lemmy_utils = { workspace = true }
lemmy_db_schema = { workspace = true }
lemmy_api_common = { workspace = true }
lemmy_routes = { workspace = true }
lemmy_federate = { workspace = true }
activitypub_federation = { workspace = true }
diesel = { workspace = true }
diesel-async = { workspace = true }
actix-web = { workspace = true }
tracing = { workspace = true }
tracing-actix-web = { workspace = true }
tracing-error = { workspace = true }
tracing-log = { workspace = true }
tracing-subscriber = { workspace = true }
url = { workspace = true }
reqwest = { workspace = true }
reqwest-middleware = { workspace = true }
reqwest-tracing = { workspace = true }
clokwerk = { workspace = true }
serde_json = { workspace = true }
tracing-opentelemetry = { workspace = true, optional = true }
opentelemetry = { workspace = true, optional = true }
console-subscriber = { version = "0.1.10", optional = true }
opentelemetry-otlp = { version = "0.12.0", optional = true }
pict-rs = { version = "0.5.14", optional = true }
tokio.workspace = true
actix-cors = "0.7.0"
futures-util = { workspace = true }
chrono = { workspace = true }
prometheus = { version = "0.13.4", features = ["process"] }
serial_test = { workspace = true }
clap = { workspace = true }
actix-web-prom = "0.8.0"
[dev-dependencies]
pretty_assertions = { workspace = true }

View File

@ -1,27 +1,39 @@
<div align="center">
![GitHub tag (latest SemVer)](https://img.shields.io/github/tag/LemmyNet/lemmy.svg)
[![Build Status](https://cloud.drone.io/api/badges/LemmyNet/lemmy/status.svg)](https://cloud.drone.io/LemmyNet/lemmy/)
[![Build Status](https://woodpecker.join-lemmy.org/api/badges/LemmyNet/lemmy/status.svg)](https://woodpecker.join-lemmy.org/LemmyNet/lemmy)
[![GitHub issues](https://img.shields.io/github/issues-raw/LemmyNet/lemmy.svg)](https://github.com/LemmyNet/lemmy/issues)
[![Docker Pulls](https://img.shields.io/docker/pulls/dessalines/lemmy.svg)](https://cloud.docker.com/repository/docker/dessalines/lemmy/)
[![Translation status](http://weblate.yerbamate.ml/widgets/lemmy/-/lemmy/svg-badge.svg)](http://weblate.yerbamate.ml/engage/lemmy/)
[![Translation status](http://weblate.join-lemmy.org/widgets/lemmy/-/lemmy/svg-badge.svg)](http://weblate.join-lemmy.org/engage/lemmy/)
[![License](https://img.shields.io/github/license/LemmyNet/lemmy.svg)](LICENSE)
![GitHub stars](https://img.shields.io/github/stars/LemmyNet/lemmy?style=social)
[![Awesome Humane Tech](https://raw.githubusercontent.com/humanetech-community/awesome-humane-tech/main/humane-tech-badge.svg?sanitize=true)](https://github.com/humanetech-community/awesome-humane-tech)
<a href="https://endsoftwarepatents.org/innovating-without-patents"><img style="height: 20px;" src="https://static.fsf.org/nosvn/esp/logos/patent-free.svg"></a>
</div>
<p align="center">
<a href="https://join.lemmy.ml/" rel="noopener">
<span>English</span> |
<a href="readmes/README.es.md">Español</a> |
<a href="readmes/README.ru.md">Русский</a> |
<a href="readmes/README.zh.hans.md">汉语</a> |
<a href="readmes/README.zh.hant.md">漢語</a> |
<a href="readmes/README.ja.md">日本語</a>
</p>
<p align="center">
<a href="https://join-lemmy.org/" rel="noopener">
<img width=200px height=200px src="https://raw.githubusercontent.com/LemmyNet/lemmy-ui/main/src/assets/icons/favicon.svg"></a>
<h3 align="center"><a href="https://join.lemmy.ml">Lemmy</a></h3>
<h3 align="center"><a href="https://join-lemmy.org">Lemmy</a></h3>
<p align="center">
A link aggregator / Reddit clone for the fediverse.
A link aggregator and forum for the fediverse.
<br />
<br />
<a href="https://join.lemmy.ml">Join Lemmy</a>
<a href="https://join-lemmy.org">Join Lemmy</a>
·
<a href="https://join.lemmy.ml/docs/en/index.html">Documentation</a>
<a href="https://join-lemmy.org/docs/index.html">Documentation</a>
·
<a href="https://matrix.to/#/#lemmy-space:matrix.org">Matrix Chat</a>
·
<a href="https://github.com/LemmyNet/lemmy/issues">Report Bug</a>
·
@ -29,29 +41,27 @@
·
<a href="https://github.com/LemmyNet/lemmy/blob/main/RELEASES.md">Releases</a>
·
<a href="https://join.lemmy.ml/docs/en/code_of_conduct.html">Code of Conduct</a>
<a href="https://join-lemmy.org/docs/code_of_conduct.html">Code of Conduct</a>
</p>
</p>
## About The Project
Desktop|Mobile
---|---
![desktop](https://raw.githubusercontent.com/LemmyNet/joinlemmy-site/main/static/images/main_img.webp)|![mobile](https://raw.githubusercontent.com/LemmyNet/joinlemmy-site/main/static/images/mobile_pic.webp)
| Desktop | Mobile |
| --------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
| ![desktop](https://raw.githubusercontent.com/LemmyNet/joinlemmy-site/main/src/assets/images/main_screen_2.webp) | ![mobile](https://raw.githubusercontent.com/LemmyNet/joinlemmy-site/main/src/assets/images/mobile_pic.webp) |
[Lemmy](https://github.com/LemmyNet/lemmy) is similar to sites like [Reddit](https://reddit.com), [Lobste.rs](https://lobste.rs), or [Hacker News](https://news.ycombinator.com/): you subscribe to forums you're interested in, post links and discussions, then vote, and comment on them. Behind the scenes, it is very different; anyone can easily run a server, and all these servers are federated (think email), and connected to the same universe, called the [Fediverse](https://en.wikipedia.org/wiki/Fediverse).
For a link aggregator, this means a user registered on one server can subscribe to forums on any other server, and can have discussions with users registered elsewhere.
The overall goal is to create an easily self-hostable, decentralized alternative to Reddit and other link aggregators, outside of their corporate control and meddling.
It is an easily self-hostable, decentralized alternative to Reddit and other link aggregators, outside of their corporate control and meddling.
Each Lemmy server can set its own moderation policy; appointing site-wide admins, and community moderators to keep out the trolls, and foster a healthy, non-toxic environment where all can feel comfortable contributing.
*Note: Federation is still in active development and the WebSocket, as well as, HTTP API are currently unstable*
### Why's it called Lemmy?
- Lead singer from [Motörhead](https://invidio.us/watch?v=pWB5JZRGl0U).
- Lead singer from [Motörhead](https://invidio.us/watch?v=3mbvWn1EY6g).
- The old school [video game](<https://en.wikipedia.org/wiki/Lemmings_(video_game)>).
- The [Koopa from Super Mario](https://www.mariowiki.com/Lemmy_Koopa).
- The [furry rodents](http://sunchild.fpwc.org/lemming-the-little-giant-of-the-north/).
@ -68,7 +78,7 @@ Each Lemmy server can set its own moderation policy; appointing site-wide admins
- Open source, [AGPL License](/LICENSE).
- Self hostable, easy to deploy.
- Comes with [Docker](https://join.lemmy.ml/docs/en/administration/install_docker.html) and [Ansible](https://join.lemmy.ml/docs/en/administration/install_ansible.html).
- Comes with [Docker](https://join-lemmy.org/docs/administration/install_docker.html) and [Ansible](https://join-lemmy.org/docs/administration/install_ansible.html).
- Clean, mobile-friendly interface.
- Only a minimum of a username and password is required to sign up!
- User avatar support.
@ -85,7 +95,7 @@ Each Lemmy server can set its own moderation policy; appointing site-wide admins
- i18n / internationalization support.
- RSS / Atom feeds for `All`, `Subscribed`, `Inbox`, `User`, and `Community`.
- Cross-posting support.
- A *similar post search* when creating new posts. Great for question / answer communities.
- A _similar post search_ when creating new posts. Great for question / answer communities.
- Moderation abilities.
- Public Moderation Logs.
- Can sticky posts to the top of communities.
@ -95,39 +105,28 @@ Each Lemmy server can set its own moderation policy; appointing site-wide admins
- Can transfer site and communities to others.
- Can fully erase your data, replacing all posts and comments.
- NSFW post / community support.
- OEmbed support via Iframely.
- High performance.
- Server is written in rust.
- Front end is `~80kB` gzipped.
- Supports arm64 / Raspberry Pi.
## Installation
- [Docker](https://join.lemmy.ml/docs/en/administration/install_docker.html)
- [Ansible](https://join.lemmy.ml/docs/en/administration/install_ansible.html)
- [Lemmy Administration Docs](https://join-lemmy.org/docs/administration/administration.html)
## Lemmy Projects
### Apps
- [lemmy-ui - The official web app for lemmy](https://github.com/LemmyNet/lemmy-ui)
- [Lemmur - A mobile client for Lemmy (Android, Linux, Windows)](https://github.com/krawieck/lemmur)
- [Remmel - A native iOS app](https://github.com/uuttff8/Lemmy-iOS)
### Libraries
- [lemmy-js-client](https://github.com/LemmyNet/lemmy-js-client)
- [Kotlin API ( under development )](https://github.com/eiknat/lemmy-client)
- [Dart API client ( under development )](https://github.com/krawieck/lemmy_api_client)
- [awesome-lemmy - A community driven list of apps and tools for lemmy](https://github.com/dbeley/awesome-lemmy)
## Support / Donate
Lemmy is free, open-source software, meaning no advertising, monetizing, or venture capital, ever. Your donations directly support full-time development of the project.
Lemmy is made possible by a generous grant from the [NLnet foundation](https://nlnet.nl/).
- [Support on Liberapay](https://liberapay.com/Lemmy).
- [Support on Patreon](https://www.patreon.com/dessalines).
- [Support on OpenCollective](https://opencollective.com/lemmy).
- [List of Sponsors](https://join.lemmy.ml/sponsors).
- [List of Sponsors](https://join-lemmy.org/donate).
### Crypto
@ -137,23 +136,28 @@ Lemmy is free, open-source software, meaning no advertising, monetizing, or vent
## Contributing
- [Contributing instructions](https://join.lemmy.ml/docs/en/contributing/contributing.html)
- [Docker Development](https://join.lemmy.ml/docs/en/contributing/docker_development.html)
- [Local Development](https://join.lemmy.ml/docs/en/contributing/local_development.html)
Read the following documentation to setup the development environment and start coding:
- [Contributing instructions](https://join-lemmy.org/docs/contributors/01-overview.html)
- [Docker Development](https://join-lemmy.org/docs/contributors/03-docker-development.html)
- [Local Development](https://join-lemmy.org/docs/contributors/02-local-development.html)
When working on an issue or pull request, you can comment with any questions you may have so that maintainers can answer them. You can also join the [Matrix Development Chat](https://matrix.to/#/#lemmydev:matrix.org) for general assistance.
### Translations
If you want to help with translating, take a look at [Weblate](https://weblate.yerbamate.ml/projects/lemmy/). You can also help by [translating the documentation](https://github.com/LemmyNet/lemmy-docs#adding-a-new-language).
- If you want to help with translating, take a look at [Weblate](https://weblate.join-lemmy.org/projects/lemmy/). You can also help by [translating the documentation](https://github.com/LemmyNet/lemmy-docs#adding-a-new-language).
## Contact
## Community
- [Mastodon](https://mastodon.social/@LemmyDev)
- [Matrix](https://matrix.to/#/#lemmy:matrix.org)
- [Matrix Space](https://matrix.to/#/#lemmy-space:matrix.org)
- [Lemmy Forum](https://lemmy.ml/c/lemmy)
- [Lemmy Support Forum](https://lemmy.ml/c/lemmy_support)
## Code Mirrors
- [GitHub](https://github.com/LemmyNet/lemmy)
- [Gitea](https://yerbamate.ml/LemmyNet/lemmy)
- [Gitea](https://git.join-lemmy.org/LemmyNet/lemmy)
- [Codeberg](https://codeberg.org/LemmyNet/lemmy)
## Credits

View File

@ -1,309 +1,3 @@
# Lemmy v0.9.7 Release (2021-02-08)
[Lemmy Releases / news](https://join-lemmy.org/news)
## Changes
- Posts and comments are no longer live-sorted (meaning most content should stay in place).
- Fixed an issue with the create post title field not expanding when copied from iframely suggestion.
- Fixed broken federated community paging / sorting.
- Added aria attributes for accessibility, thx to @Mitch Lillie.
- Updated translations and added croatian.
- No changes to lemmy back-end.
# Lemmy v0.9.6 Release (2021-02-05)
## Changes
- Fixed inbox_urls not being correctly set, which broke federation in `v0.9.5`. Added some logging to catch these.
- Fixing community search not using auth.
- Moved docs to https://join.lemmy.ml
- Fixed an issue w/ lemmy-ui with forms being cleared out.
# Lemmy v0.9.4 Pre-Release (2021-02-02)
## Changes
### Lemmy
- Fixed a critical bug with votes and comment unlike responses not being `0` for your user.
- Fixed a critical bug with comment creation not checking if its parent comment is in the post.
- Serving proper activities for community outbox.
- Added some active user counts, including `users_active_day`, `users_active_week`, `users_active_month`, `users_active_half_year` to `SiteAggregates` and `CommunityAggregates`. (Also added to lemmy-ui)
- Made sure banned users can't follow.
- Added `FederatedInstances` to `SiteResponse`, to show allowed and blocked instances. (Also added to lemmy-ui)
- Added a `MostComments` sort for posts. (Also added to lemmy-ui)
### Lemmy-UI
- Added a scroll position restore to lemmy-ui.
- Reworked the combined inbox so incoming comments don't wipe out your current form.
- Fixed an updated bug on the user page.
- Fixed cross-post titles and body getting clipped.
- Fixing the post creation title height.
- Squashed some other smaller bugs.
# Lemmy v0.9.0 Release (2021-01-25)
## Changes
Since our last release in October of last year, and we've had [~450](https://github.com/LemmyNet/lemmy/compare/v0.8.0...main) commits.
The biggest changes, as we'll outline below, are a re-work of Lemmy's database structure, a `v2` of Lemmy's API, and activitypub compliance fixes. The new re-worked DB is much faster, easier to maintain, and [now supports hierarchical rather than flat objects in the new API](https://github.com/LemmyNet/lemmy/issues/1275).
We've also seen the first release of [Lemmur](https://github.com/krawieck/lemmur/releases/tag/v0.1.1), an android / iOS (soon) / windows / linux client, as well as [Lemmer](https://github.com/uuttff8/Lemmy-iOS), a native iOS client. Much thanks to @krawieck, @shilangyu, and @uuttff8 for making these great clients. If you can, please contribute to their [patreon](https://www.patreon.com/lemmur) to help fund lemmur development.
## LemmyNet projects
### Lemmy Server
- [Moved views from SQL to Diesel](https://github.com/LemmyNet/lemmy/issues/1275). This was a spinal replacement for much of lemmy.
- Removed all the old fast_tables and triggers, and created new aggregates tables.
- Added a `v2` of the API to support the hierarchical objects created from the above changes.
- Moved continuous integration to [drone](https://cloud.drone.io/LemmyNet/lemmy/), now includes formatting, clippy, and cargo build checks, unit testing, and federation testing. [Drone also deploys both amd64 and arm64 images to dockerhub.](https://hub.docker.com/r/dessalines/lemmy)
- Split out documentation into git submodule.
- Shortened slur filter to avoid false positives.
- Added query performance testing and comparisons. Added indexes to make sure every query is `< 30 ms`.
- Added compilation time testing.
### Federation
This release includes some bug fixes for federation, and some changes to get us closer to compliance with the ActivityPub standard.
- [Community bans now federating](https://github.com/LemmyNet/lemmy/issues/1287).
- [Local posts sometimes got marked as remote](https://github.com/LemmyNet/lemmy/issues/1302).
- [Creator of post/comment was not notified about new child comments](https://github.com/LemmyNet/lemmy/issues/1325).
- [Community deletion now federated](https://github.com/LemmyNet/lemmy/issues/1256).
None of these are breaking changes, so federation between 0.9.0 and 0.8.11 will work without problems.
### Lemmy javascript / typescript client
- Updated the [lemmy-js-client](https://github.com/LemmyNet/lemmy-js-client) to use the new `v2` API. Our API docs now reference this project's files, to show what the http / websocket forms and responses should look like.
- Drone now handles publishing its [npm packages.](https://www.npmjs.com/package/lemmy-js-client)
### Lemmy-UI
- Updated it to use the `v2` API via `lemmy-js-client`, required changing nearly every component.
- Added a live comment count.
- Added drone deploying, and builds for ARM.
- Fixed community link wrapping.
- Various other bug fixes.
### Lemmy Docs
- We moved documentation into a separate git repository, and support translation for the docs now!
- Moved our code of conduct into the documentation.
## Upgrading
If you'd like to make a DB backup before upgrading, follow [this guide](https://join.lemmy.ml/docs/en/administration/backup_and_restore.html).
- [Upgrade with manual Docker installation](https://join.lemmy.ml/docs/en/administration/install_docker.html#updating)
- [Upgrade with Ansible installation](https://join.lemmy.ml/docs/en/administration/install_ansible.html)
# Lemmy v0.8.0 Release (2020-10-16)
## Changes
We've been working at warp speed since our `v0.7.0` release in June, adding over [870 commits](https://github.com/LemmyNet/lemmy/compare/v0.7.0...main) since then. :sweat:
Here are some of the bigger changes:
### LemmyNet projects
- Created [LemmyNet](https://github.com/LemmyNet), where all lemmy-related projects live.
- Split out the frontend into a separete repository, [lemmy-ui](https://github.com/LemmyNet/lemmy-ui)
- Created a [lemmy-js-client](https://github.com/LemmyNet/lemmy-js-client), for any js / typescript developers.
- Split out i18n [lemmy-translations](https://github.com/LemmyNet/lemmy-translations), that any app or site developers can import and use. Lemmy currently supports [~30 languages!](https://weblate.yerbamate.ml/projects/lemmy/lemmy/)
### Lemmy Server
#### Federation
- The first **federation public beta release**, woohoo :fireworks:
- All Lemmy functionality now works over ActivityPub (except turning remote users into mods/admins)
- Instance allowlist and blocklist
- Documentation for [admins](https://join.lemmy.ml/docs/administration_federation.html) and [devs](https://join.lemmy.ml/docs/contributing_federation_overview.html) on how federation works
- Upgraded to newest versions of @asonix activitypub libraries
- Full local federation setup for manual testing
- Automated testing for nearly every federation action
- Many additional security checks
- Lots and lots of refactoring
- Asynchronous sending of outgoing activities
### User Interface
- Separated the UI from the server code, in [lemmy-ui](https://github.com/LemmyNet/lemmy-ui).
- The UI can now read with javascript disabled!
- It's now a fully isomorphic application using [inferno-isomorphic](https://infernojs.org/docs/guides/isomorphic). This means that page loads are now much faster, as the server does the work.
- The UI now also supports open-graph and twitter cards! Linking to lemmy posts (from whatever platform you use) looks pretty now: ![](https://i.imgur.com/6TZ2v7s.png)
- Improved the search page ( more features incoming ).
- The default view is now `Local`, instead of `All`, since all would show all federated posts.
- User settings are now shared across browsers ( a page refresh will pick up changes ).
- A much leaner mobile view.
#### Backend
- Re-organized the rust codebase into separate workspaces for backend and frontend.
- Removed materialized views, making the database **a lot faster**.
- New post sorts `Active` (previously called hot), and `Hot`. Active shows posts with recent comments, hot shows highly ranked posts.
- New sort for `Local` ( meaning from local communities).
- Customizeable site, user, and community icons and banners.
- Added user preferred names / display names, bios, and cakedays.
- Visual / Audio captchas through the lemmy API.
- Lots of API field verifications.
- Upgraded to pictrs-v2 ( thanks to @asonix )
- Wayyy too many bugfixes to count.
## Contributors
We'd also like to thank both the [NLnet foundation](https://nlnet.nl/) for their support in allowing us to work full-time on Lemmy ( as well as their support for [other important open-source projects](https://nlnet.nl/project/current.html) ), [those who sponsor us](https://lemmy.ml/sponsors), and those who [help translate Lemmy](https://weblate.yerbamate.ml/projects/lemmy/). Every little bit does help. We remain committed to never allowing advertisements, monetizing, or venture-capital in Lemmy; software should be communal, and should benefit humanity, not a small group of company owners.
## Upgrading
- [with manual Docker installation](https://join.lemmy.ml/docs/administration_install_docker.html#updating)
- [with Ansible installation](https://join.lemmy.ml/docs/administration_install_ansible.html)
## Testing Federation
Federation is finally ready in Lemmy, pending possible bugs or other issues. So for now we suggest to enable federation only on test servers, or try it on our own test servers ( [enterprise](https://enterprise.lemmy.ml/), [ds9](https://ds9.lemmy.ml/), [voyager](https://voyager.lemmy.ml/) ).
If everything goes well, after a few weeks we will enable federation on lemmy.ml, at first with a limited number of trusted instances. We will also likely change the domain to https://lemmy.ml . Keep in mind that changing domains after turning on federation will break things.
To enable on your instance, edit your [lemmy.hjson](https://github.com/LemmyNet/lemmy/blob/main/config/defaults.hjson#L60) federation section to `enabled: true`, and restart.
### Connecting to another server
The server https://ds9.lemmy.ml has open federation, so after either adding it to the `allowed_instances` list in your `config.hjson`, or if you have open federation, you don't need to add it explicitly.
To federate / connect with a server, type in `!community_name@server.tld`, in your server's search box [like so](https://voyager.lemmy.ml/search/q/!main%40ds9.lemmy.ml/type/All/sort/TopAll/page/1).
To connect with the `main` community on ds9, the search is `!main@ds9.lemmy.ml`.
You can then click the community, and you will see a local version of the community, which you can subscribe to. New posts and comments from `!main@ds9.lemmy.ml` will now show up on your front page, or `/c/All`
# Lemmy v0.7.40 Pre-Release (2020-08-05)
We've [added a lot](https://github.com/LemmyNet/lemmy/compare/v0.7.40...v0.7.0) in this pre-release:
- New post sorts `Active` (previously called hot), and `Hot`. Active shows posts with recent comments, hot shows highly ranked posts.
- Customizeable site icon and banner, user icon and banner, and community icon and banner.
- Added user preferred names / display names, bios, and cakedays.
- User settings are now shared across browsers (a page refresh will pick up changes).
- Visual / Audio captchas through the lemmy API.
- Lots of UI prettiness.
- Lots of bug fixes.
- Lots of additional translations.
- Lots of federation prepping / additions / refactors.
This release removes the need for you to have a pictrs nginx route (the requests are now routed through lemmy directly). Follow the upgrade instructions below to replace your nginx with the new one.
## Upgrading
**With Ansible:**
```
# run these commands locally
git pull
cd ansible
ansible-playbook lemmy.yml
```
**With manual Docker installation:**
```
# run these commands on your server
cd /lemmy
wget https://raw.githubusercontent.com/LemmyNet/lemmy/master/ansible/templates/nginx.conf
# Replace the {{ vars }}
sudo mv nginx.conf /etc/nginx/sites-enabled/lemmy.conf
sudo nginx -s reload
wget https://raw.githubusercontent.com/LemmyNet/lemmy/master/docker/prod/docker-compose.yml
sudo docker-compose up -d
```
# Lemmy v0.7.0 Release (2020-06-23)
This release replaces [pictshare](https://github.com/HaschekSolutions/pictshare)
with [pict-rs](https://git.asonix.dog/asonix/pict-rs), which improves performance
and security.
Overall, since our last major release in January (v0.6.0), we have closed over
[100 issues!](https://github.com/LemmyNet/lemmy/milestone/16?closed=1)
- Site-wide list of recent comments
- Reconnecting websockets
- Many more themes, including a default light one.
- Expandable embeds for post links (and thumbnails), from
[iframely](https://github.com/itteco/iframely)
- Better icons
- Emoji autocomplete to post and message bodies, and an Emoji Picker
- Post body now searchable
- Community title and description is now searchable
- Simplified cross-posts
- Better documentation
- LOTS more languages
- Lots of bugs squashed
- And more ...
## Upgrading
Before starting the upgrade, make sure that you have a working backup of your
database and image files. See our
[documentation](https://join.lemmy.ml/docs/administration_backup_and_restore.html)
for backup instructions.
**With Ansible:**
```
# deploy with ansible from your local lemmy git repo
git pull
cd ansible
ansible-playbook lemmy.yml
# connect via ssh to run the migration script
ssh your-server
cd /lemmy/
wget https://raw.githubusercontent.com/LemmyNet/lemmy/master/docker/prod/migrate-pictshare-to-pictrs.bash
chmod +x migrate-pictshare-to-pictrs.bash
sudo ./migrate-pictshare-to-pictrs.bash
```
**With manual Docker installation:**
```
# run these commands on your server
cd /lemmy
wget https://raw.githubusercontent.com/LemmyNet/lemmy/master/ansible/templates/nginx.conf
# Replace the {{ vars }}
sudo mv nginx.conf /etc/nginx/sites-enabled/lemmy.conf
sudo nginx -s reload
wget https://raw.githubusercontent.com/LemmyNet/lemmy/master/docker/prod/docker-compose.yml
wget https://raw.githubusercontent.com/LemmyNet/lemmy/master/docker/prod/migrate-pictshare-to-pictrs.bash
chmod +x migrate-pictshare-to-pictrs.bash
sudo bash migrate-pictshare-to-pictrs.bash
```
**Note:** After upgrading, all users need to reload the page, then logout and
login again, so that images are loaded correctly.
# Lemmy v0.6.0 Release (2020-01-16)
`v0.6.0` is here, and we've closed [41 issues!](https://github.com/LemmyNet/lemmy/milestone/15?closed=1)
This is the biggest release by far:
- Avatars!
- Optional Email notifications for username mentions, post and comment replies.
- Ability to change your password and email address.
- Can set a custom language.
- Lemmy-wide settings to disable downvotes, and close registration.
- A better documentation system, hosted in lemmy itself.
- [Huge DB performance gains](https://github.com/LemmyNet/lemmy/issues/411) (everthing down to < `30ms`) by using materialized views.
- Fixed major issue with similar post URL and title searching.
- Upgraded to Actix `2.0`
- Faster comment / post voting.
- Better small screen support.
- Lots of bug fixes, refactoring of back end code.
Another major announcement is that Lemmy now has another lead developer besides me, [@felix@radical.town](https://radical.town/@felix). Theyve created a better documentation system, implemented RSS feeds, simplified docker and project configs, upgraded actix, working on federation, a whole lot else.
https://lemmy.ml
[Github link](https://github.com/LemmyNet/joinlemmy-site/tree/main/src/assets/news)

5
SECURITY.md Normal file
View File

@ -0,0 +1,5 @@
# Security Policy
## Reporting a Vulnerability
Use [Github's security advisory issue system](https://github.com/LemmyNet/lemmy/security/advisories/new).

View File

@ -1 +0,0 @@
0.9.7

View File

@ -1,6 +0,0 @@
[defaults]
inventory = inventory
interpreter_python = /usr/bin/python3
[ssh_connection]
pipelining = True

View File

@ -1,12 +0,0 @@
[lemmy]
# to get started, copy this file to `inventory` and adjust the values below.
# - `myuser@example.com`: replace with the destination you use to connect to your server via ssh
# - `domain=example.com`: replace `example.com` with your lemmy domain
# - `letsencrypt_contact_email=your@email.com` replace `your@email.com` with your email address,
# to get notifications if your ssl cert expires
# - `lemmy_base_dir=/srv/lemmy`: the location on the server where lemmy can be installed, can be any folder
# if you are upgrading from a previous version, set this to `/lemmy`
myuser@example.com domain=example.com letsencrypt_contact_email=your@email.com lemmy_base_dir=/srv/lemmy
[all:vars]
ansible_connection=ssh

View File

@ -1,119 +0,0 @@
---
- hosts: all
# Install python if required
# https://www.josharcher.uk/code/ansible-python-connection-failure-ubuntu-server-1604/
gather_facts: False
pre_tasks:
- name: check lemmy_base_dir
fail:
msg: "`lemmy_base_dir` is unset. if you are upgrading from an older version, add `lemmy_base_dir=/lemmy` to your inventory file."
when: lemmy_base_dir is not defined
- name: install python for Ansible
# python2-minimal instead of python-minimal for ubuntu 20.04 and up
raw: test -e /usr/bin/python || (apt -y update && apt install -y python3-minimal python3-setuptools)
args:
executable: /bin/bash
register: output
changed_when: output.stdout != ''
- setup: # gather facts
tasks:
- name: install dependencies
apt:
pkg:
- 'nginx'
- 'docker-compose'
- 'docker.io'
- 'certbot'
- name: install certbot-nginx on ubuntu < 20
apt:
pkg:
- 'python-certbot-nginx'
when: ansible_distribution == 'Ubuntu' and ansible_distribution_version is version('20.04', '<')
- name: install certbot-nginx on ubuntu > 20
apt:
pkg:
- 'python3-certbot-nginx'
when: ansible_distribution == 'Ubuntu' and ansible_distribution_version is version('20.04', '>=')
- name: request initial letsencrypt certificate
command: certbot certonly --nginx --agree-tos -d '{{ domain }}' -m '{{ letsencrypt_contact_email }}'
args:
creates: '/etc/letsencrypt/live/{{domain}}/privkey.pem'
- name: create lemmy folder
file:
path: '{{item.path}}'
owner: '{{item.owner}}'
state: directory
with_items:
- path: '{{lemmy_base_dir}}'
owner: 'root'
- path: '{{lemmy_base_dir}}/volumes/'
owner: 'root'
- path: '{{lemmy_base_dir}}/volumes/pictrs/'
owner: '991'
- block:
- name: add template files
template:
src: '{{item.src}}'
dest: '{{item.dest}}'
mode: '{{item.mode}}'
with_items:
- src: 'templates/docker-compose.yml'
dest: '{{lemmy_base_dir}}/docker-compose.yml'
mode: '0600'
- src: 'templates/nginx.conf'
dest: '/etc/nginx/sites-enabled/lemmy.conf'
mode: '0644'
- src: '../docker/iframely.config.local.js'
dest: '{{lemmy_base_dir}}/iframely.config.local.js'
mode: '0600'
vars:
lemmy_docker_image: "dessalines/lemmy:{{ lookup('file', 'VERSION') }}"
lemmy_docker_ui_image: "dessalines/lemmy-ui:{{ lookup('file', 'VERSION') }}"
lemmy_port: "8536"
lemmy_ui_port: "1235"
pictshare_port: "8537"
iframely_port: "8538"
- name: add config file (only during initial setup)
template:
src: 'templates/config.hjson'
dest: '{{lemmy_base_dir}}/lemmy.hjson'
mode: '0600'
force: false
owner: '1000'
group: '1000'
vars:
postgres_password: "{{ lookup('password', 'passwords/{{ inventory_hostname }}/postgres chars=ascii_letters,digits') }}"
jwt_password: "{{ lookup('password', 'passwords/{{ inventory_hostname }}/jwt chars=ascii_letters,digits') }}"
- name: enable and start docker service
systemd:
name: docker
enabled: yes
state: started
- name: start docker-compose
docker_compose:
project_src: '{{lemmy_base_dir}}'
state: present
pull: yes
remove_orphans: yes
- name: reload nginx with new config
shell: nginx -s reload
- name: certbot renewal cronjob
cron:
special_time: daily
name: certbot-renew-lemmy
user: root
job: "certbot certonly --nginx -d '{{ domain }}' --deploy-hook 'nginx -s reload'"

View File

@ -1,141 +0,0 @@
---
- hosts: all
vars:
lemmy_docker_image: 'lemmy:dev'
# Install python if required
# https://www.josharcher.uk/code/ansible-python-connection-failure-ubuntu-server-1604/
gather_facts: False
pre_tasks:
- name: check lemmy_base_dir
fail:
msg: "`lemmy_base_dir` is unset. if you are upgrading from an older version, add `lemmy_base_dir=/lemmy` to your inventory file."
when: lemmy_base_dir is not defined
- name: install python for Ansible
raw: test -e /usr/bin/python || (apt -y update && apt install -y python-minimal python-setuptools)
args:
executable: /bin/bash
register: output
changed_when: output.stdout != ''
- setup: # gather facts
tasks:
- name: install dependencies
apt:
pkg:
- 'nginx'
- 'docker-compose'
- 'docker.io'
- 'certbot'
- 'python-certbot-nginx'
- name: request initial letsencrypt certificate
command: certbot certonly --nginx --agree-tos -d '{{ domain }}' -m '{{ letsencrypt_contact_email }}'
args:
creates: '/etc/letsencrypt/live/{{domain}}/privkey.pem'
- name: create lemmy folder
file:
path: '{{item.path}}'
owner: '{{item.owner}}'
state: directory
with_items:
- path: '{{lemmy_base_dir}}/lemmy/'
owner: 'root'
- path: '{{lemmy_base_dir}}/volumes/'
owner: 'root'
- path: '{{lemmy_base_dir}}/volumes/pictrs/'
owner: '991'
- block:
- name: add template files
template:
src: '{{item.src}}'
dest: '{{item.dest}}'
mode: '{{item.mode}}'
with_items:
- src: 'templates/docker-compose.yml'
dest: '{{lemmy_base_dir}}/docker-compose.yml'
mode: '0600'
- src: 'templates/nginx.conf'
dest: '/etc/nginx/sites-enabled/lemmy.conf'
mode: '0644'
- src: '../docker/iframely.config.local.js'
dest: '{{lemmy_base_dir}}/iframely.config.local.js'
mode: '0600'
- name: add config file (only during initial setup)
template:
src: 'templates/config.hjson'
dest: '{{lemmy_base_dir}}/lemmy.hjson'
mode: '0600'
force: false
owner: '1000'
group: '1000'
vars:
postgres_password: "{{ lookup('password', 'passwords/{{ inventory_hostname }}/postgres chars=ascii_letters,digits') }}"
jwt_password: "{{ lookup('password', 'passwords/{{ inventory_hostname }}/jwt chars=ascii_letters,digits') }}"
- name: build the dev docker image
local_action: shell cd .. && sudo docker build . -f docker/dev/Dockerfile -t lemmy:dev
register: image_build
- name: find hash of the new docker image
set_fact:
image_hash: "{{ image_build.stdout | regex_search('(?<=Successfully built )[0-9a-f]{12}') }}"
# this does not use become so that the output file is written as non-root user and is easy to delete later
- name: save dev docker image to file
local_action: shell sudo docker save lemmy:dev > lemmy-dev.tar
- name: copy dev docker image to server
copy:
src: lemmy-dev.tar
dest: '{{lemmy_base_dir}}/lemmy-dev.tar'
- name: import docker image
docker_image:
name: lemmy
tag: dev
load_path: '{{lemmy_base_dir}}/lemmy-dev.tar'
source: load
force_source: yes
register: image_import
- name: delete remote image file
file:
path: '{{lemmy_base_dir}}/lemmy-dev.tar'
state: absent
- name: delete local image file
local_action:
module: file
path: lemmy-dev.tar
state: absent
- name: enable and start docker service
systemd:
name: docker
enabled: yes
state: started
# cant pull here because that fails due to lemmy:dev (without dessalines/) not being on docker hub, but that shouldnt
# be a problem for testing
- name: start docker-compose
docker_compose:
project_src: '{{lemmy_base_dir}}'
state: present
recreate: always
remove_orphans: yes
ignore_errors: yes
- name: reload nginx with new config
shell: nginx -s reload
- name: certbot renewal cronjob
cron:
special_time: daily
name: certbot-renew-lemmy
user: root
job: "certbot certonly --nginx -d '{{ domain }}' --deploy-hook 'nginx -s reload'"

View File

@ -1,36 +0,0 @@
{
# for more info about the config, check out the documentation
# https://join.lemmy.ml/docs/en/administration/configuration.html
# settings related to the postgresql database
database: {
# password to connect to postgres
password: "{{ postgres_password }}"
# host where postgres is running
host: "postgres"
}
# the domain name of your instance (eg "lemmy.ml")
hostname: "{{ domain }}"
# json web token for authorization between server and client
jwt_secret: "{{ jwt_password }}"
# email sending configuration
email: {
# hostname of the smtp server
smtp_server: "postfix:25"
# address to send emails from, eg "noreply@your-instance.com"
smtp_from_address: "noreply@{{ domain }}"
use_tls: false
}
# settings related to activitypub federation
federation: {
# whether to enable activitypub federation.
enabled: false
# Allows and blocks are described here:
# https://join.lemmy.ml/docs/en/federation/administration.html#instance-allowlist-and-blocklist
#
# comma separated list of instances with which federation is allowed
# allowed_instances: ""
# comma separated list of instances which are blocked from federating
# blocked_instances: ""
}
}

View File

@ -1,61 +0,0 @@
version: '3.3'
services:
lemmy:
image: {{ lemmy_docker_image }}
ports:
- "127.0.0.1:8536:8536"
restart: always
environment:
- RUST_LOG=error
volumes:
- ./lemmy.hjson:/config/config.hjson:ro
depends_on:
- postgres
- pictrs
- iframely
lemmy-ui:
image: {{ lemmy_docker_ui_image }}
ports:
- "127.0.0.1:1235:1234"
restart: always
environment:
- LEMMY_INTERNAL_HOST=lemmy:8536
- LEMMY_EXTERNAL_HOST={{ domain }}
- LEMMY_HTTPS=true
depends_on:
- lemmy
postgres:
image: postgres:12-alpine
environment:
- POSTGRES_USER=lemmy
- POSTGRES_PASSWORD={{ postgres_password }}
- POSTGRES_DB=lemmy
volumes:
- ./volumes/postgres:/var/lib/postgresql/data
restart: always
pictrs:
image: asonix/pictrs:v0.2.5-r0
user: 991:991
ports:
- "127.0.0.1:8537:8080"
volumes:
- ./volumes/pictrs:/mnt
restart: always
iframely:
image: dogbin/iframely:latest
ports:
- "127.0.0.1:8061:80"
volumes:
- ./iframely.config.local.js:/iframely/config.local.js:ro
restart: always
postfix:
image: mwader/postfix-relay
environment:
- POSTFIX_myhostname={{ domain }}
restart: "always"

View File

@ -1,121 +0,0 @@
limit_req_zone $binary_remote_addr zone=lemmy_ratelimit:10m rate=1r/s;
server {
listen 80;
server_name {{ domain }};
location /.well-known/acme-challenge/ {
root /var/www/certbot;
}
location / {
return 301 https://$host$request_uri;
}
}
server {
listen 443 ssl http2;
server_name {{ domain }};
ssl_certificate /etc/letsencrypt/live/{{domain}}/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/{{domain}}/privkey.pem;
# Various TLS hardening settings
# https://raymii.org/s/tutorials/Strong_SSL_Security_On_nginx.html
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256';
ssl_session_timeout 10m;
ssl_session_cache shared:SSL:10m;
ssl_session_tickets off;
ssl_stapling on;
ssl_stapling_verify on;
# Hide nginx version
server_tokens off;
# Enable compression for JS/CSS/HTML bundle, for improved client load times.
# It might be nice to compress JSON, but leaving that out to protect against potential
# compression+encryption information leak attacks like BREACH.
gzip on;
gzip_types text/css application/javascript image/svg+xml;
gzip_vary on;
# Only connect to this site via HTTPS for the two years
add_header Strict-Transport-Security "max-age=63072000";
# Various content security headers
add_header Referrer-Policy "same-origin";
add_header X-Content-Type-Options "nosniff";
add_header X-Frame-Options "DENY";
add_header X-XSS-Protection "1; mode=block";
# Upload limit for pictrs
client_max_body_size 20M;
# frontend
location / {
# The default ports:
# lemmy_ui_port: 1235
# lemmy_port: 8536
set $proxpass "http://0.0.0.0:{{ lemmy_ui_port }}";
if ($http_accept = "application/activity+json") {
set $proxpass "http://0.0.0.0:{{ lemmy_port }}";
}
if ($http_accept = "application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\"") {
set $proxpass "http://0.0.0.0:{{ lemmy_port }}";
}
if ($request_method = POST) {
set $proxpass "http://0.0.0.0:{{ lemmy_port }}";
}
proxy_pass $proxpass;
rewrite ^(.+)/+$ $1 permanent;
# Send actual client IP upstream
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
# backend
location ~ ^/(api|pictrs|feeds|nodeinfo|.well-known) {
proxy_pass http://0.0.0.0:{{ lemmy_port }};
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
# Rate limit
limit_req zone=lemmy_ratelimit burst=30 nodelay;
# Add IP forwarding headers
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
# Redirect pictshare images to pictrs
location ~ /pictshare/(.*)$ {
return 301 /pictrs/image/$1;
}
location /iframely/ {
proxy_pass http://0.0.0.0:8061/;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
# Anonymize IP addresses
# https://www.supertechcrew.com/anonymizing-logs-nginx-apache/
map $remote_addr $remote_addr_anon {
~(?P<ip>\d+\.\d+\.\d+)\. $ip.0;
~(?P<ip>[^:]+:[^:]+): $ip::;
127.0.0.1 $remote_addr;
::1 $remote_addr;
default 0.0.0.0;
}
log_format main '$remote_addr_anon - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" "$http_user_agent"';
access_log /var/log/nginx/access.log main;

View File

@ -1,54 +0,0 @@
---
- hosts: all
vars_prompt:
- name: confirm_uninstall
prompt: "Do you really want to uninstall Lemmy? This will delete all data and can not be reverted [yes/no]"
private: no
- name: delete_certs
prompt: "Delete certificates? Select 'no' if you want to reinstall Lemmy [yes/no]"
private: no
tasks:
- name: end play if no confirmation was given
debug:
msg: "Uninstall cancelled, doing nothing"
when: not confirm_uninstall|bool
- meta: end_play
when: not confirm_uninstall|bool
- name: stop docker-compose
docker_compose:
project_src: '{{lemmy_base_dir}}'
state: absent
- name: delete data
file:
path: '{{item.path}}'
state: absent
with_items:
- path: '{{lemmy_base_dir}}'
- path: '/etc/nginx/sites-enabled/lemmy.conf'
- name: Remove a volume
docker_volume:
name: '{{item.name}}'
state: absent
with_items:
- name: 'lemmy_lemmy_db'
- name: 'lemmy_lemmy_pictshare'
- name: delete entire ecloud folder
file:
path: '/mnt/repo-base/'
state: absent
when: delete_certs|bool
- name: remove certbot cronjob
cron:
name: certbot-renew-lemmy
state: absent

View File

@ -3,27 +3,18 @@
"env": {
"browser": true
},
"plugins": [
"jane"
],
"extends": [
"plugin:jane/recommended",
"plugin:jane/typescript"
],
"plugins": ["@typescript-eslint"],
"extends": ["eslint:recommended", "plugin:@typescript-eslint/recommended"],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"project": "./tsconfig.json",
"warnOnUnsupportedTypeScriptVersion": false
},
"rules": {
"@typescript-eslint/camelcase": 0,
"@typescript-eslint/member-delimiter-style": 0,
"@typescript-eslint/no-empty-interface": 0,
"@typescript-eslint/ban-ts-comment": 0,
"@typescript-eslint/no-explicit-any": 0,
"@typescript-eslint/no-this-alias": 0,
"@typescript-eslint/no-unused-vars": 0,
"@typescript-eslint/no-use-before-define": 0,
"@typescript-eslint/no-useless-constructor": 0,
"@typescript-eslint/explicit-module-boundary-types": 0,
"@typescript-eslint/no-var-requires": 0,
"arrow-body-style": 0,
"curly": 0,
"eol-last": 0,

1
api_tests/.npmrc Normal file
View File

@ -0,0 +1 @@
package-manager-strict=false

View File

@ -1,4 +0,0 @@
module.exports = Object.assign(require('eslint-plugin-jane/prettier-ts'), {
arrowParens: 'avoid',
semi: true,
});

View File

@ -0,0 +1,4 @@
{
"arrowParens": "avoid",
"semi": true
}

View File

@ -1,4 +1,4 @@
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
};
preset: "ts-jest",
testEnvironment: "node",
};

View File

@ -6,20 +6,31 @@
"repository": "https://github.com/LemmyNet/lemmy",
"author": "Dessalines",
"license": "AGPL-3.0",
"packageManager": "pnpm@9.1.1+sha256.9551e803dcb7a1839fdf5416153a844060c7bce013218ce823410532504ac10b",
"scripts": {
"lint": "tsc --noEmit && eslint --report-unused-disable-directives --ext .js,.ts,.tsx src",
"lint": "tsc --noEmit && eslint --report-unused-disable-directives --ext .js,.ts,.tsx src && prettier --check 'src/**/*.ts'",
"fix": "prettier --write src && eslint --fix src",
"api-test": "jest src/ -i --verbose"
"api-test": "jest -i follow.spec.ts && jest -i image.spec.ts && jest -i user.spec.ts && jest -i private_message.spec.ts && jest -i community.spec.ts && jest -i post.spec.ts && jest -i comment.spec.ts ",
"api-test-follow": "jest -i follow.spec.ts",
"api-test-comment": "jest -i comment.spec.ts",
"api-test-post": "jest -i post.spec.ts",
"api-test-user": "jest -i user.spec.ts",
"api-test-community": "jest -i community.spec.ts",
"api-test-private-message": "jest -i private_message.spec.ts",
"api-test-image": "jest -i image.spec.ts"
},
"devDependencies": {
"@types/jest": "^26.0.20",
"eslint": "^7.18.0",
"eslint-plugin-jane": "^9.0.3",
"jest": "^26.6.3",
"lemmy-js-client": "0.9.1-rc.1",
"node-fetch": "^2.6.1",
"prettier": "^2.1.2",
"ts-jest": "^26.4.4",
"typescript": "^4.1.3"
"@types/jest": "^29.5.12",
"@types/node": "^20.12.4",
"@typescript-eslint/eslint-plugin": "^7.5.0",
"@typescript-eslint/parser": "^7.5.0",
"download-file-sync": "^1.0.4",
"eslint": "^8.57.0",
"eslint-plugin-prettier": "^5.1.3",
"jest": "^29.5.0",
"lemmy-js-client": "0.19.4-alpha.18",
"prettier": "^3.2.5",
"ts-jest": "^29.1.0",
"typescript": "^5.4.4"
}
}

3449
api_tests/pnpm-lock.yaml Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,18 +1,34 @@
#!/bin/bash
#!/usr/bin/env bash
# IMPORTANT NOTE: this script does not use the normal LEMMY_DATABASE_URL format
# it is expected that this script is called by run-federation-test.sh script.
set -e
export LEMMY_JWT_SECRET=changeme
export LEMMY_FEDERATION__ENABLED=true
export LEMMY_TLS_ENABLED=false
export LEMMY_SETUP__ADMIN_PASSWORD=lemmy
export LEMMY_RATE_LIMIT__POST=99999
export LEMMY_RATE_LIMIT__REGISTER=99999
export LEMMY_CAPTCHA__ENABLED=false
export LEMMY_TEST_SEND_SYNC=1
if [ -z "$LEMMY_LOG_LEVEL" ];
then
LEMMY_LOG_LEVEL=info
fi
export RUST_BACKTRACE=1
export RUST_LOG="warn,lemmy_server=$LEMMY_LOG_LEVEL,lemmy_federate=$LEMMY_LOG_LEVEL,lemmy_api=$LEMMY_LOG_LEVEL,lemmy_api_common=$LEMMY_LOG_LEVEL,lemmy_api_crud=$LEMMY_LOG_LEVEL,lemmy_apub=$LEMMY_LOG_LEVEL,lemmy_db_schema=$LEMMY_LOG_LEVEL,lemmy_db_views=$LEMMY_LOG_LEVEL,lemmy_db_views_actor=$LEMMY_LOG_LEVEL,lemmy_db_views_moderator=$LEMMY_LOG_LEVEL,lemmy_routes=$LEMMY_LOG_LEVEL,lemmy_utils=$LEMMY_LOG_LEVEL,lemmy_websocket=$LEMMY_LOG_LEVEL"
export LEMMY_TEST_FAST_FEDERATION=1 # by default, the persistent federation queue has delays in the scale of 30s-5min
# pictrs setup
if [ ! -f "api_tests/pict-rs" ]; then
curl "https://git.asonix.dog/asonix/pict-rs/releases/download/v0.5.13/pict-rs-linux-amd64" -o api_tests/pict-rs
chmod +x api_tests/pict-rs
fi
./api_tests/pict-rs \
run -a 0.0.0.0:8080 \
--danger-dummy-mode \
--api-key "my-pictrs-key" \
filesystem -p /tmp/pictrs/files \
sled -p /tmp/pictrs/sled-repo 2>&1 &
for INSTANCE in lemmy_alpha lemmy_beta lemmy_gamma lemmy_delta lemmy_epsilon; do
echo "DB URL: ${LEMMY_DATABASE_URL} INSTANCE: $INSTANCE"
psql "${LEMMY_DATABASE_URL}/lemmy" -c "DROP DATABASE IF EXISTS $INSTANCE"
echo "create database"
psql "${LEMMY_DATABASE_URL}/lemmy" -c "CREATE DATABASE $INSTANCE"
done
@ -29,62 +45,50 @@ if [ -z "$DO_WRITE_HOSTS_FILE" ]; then
fi
else
for INSTANCE in lemmy-alpha lemmy-beta lemmy-gamma lemmy-delta lemmy-epsilon; do
echo "127.0.0.1 $INSTANCE" >> /etc/hosts
echo "127.0.0.1 $INSTANCE" >>/etc/hosts
done
fi
killall lemmy_server || true
echo "$PWD"
LOG_DIR=target/log
mkdir -p $LOG_DIR
echo "start alpha"
LEMMY_HOSTNAME=lemmy-alpha:8541 \
LEMMY_PORT=8541 \
LEMMY_CONFIG_LOCATION=./docker/federation/lemmy_alpha.hjson \
LEMMY_DATABASE_URL="${LEMMY_DATABASE_URL}/lemmy_alpha" \
LEMMY_FEDERATION__ALLOWED_INSTANCES=lemmy-beta,lemmy-gamma,lemmy-delta,lemmy-epsilon \
LEMMY_SETUP__ADMIN_USERNAME=lemmy_alpha \
LEMMY_SETUP__SITE_NAME=lemmy-alpha \
target/lemmy_server >/dev/null 2>&1 &
target/lemmy_server >$LOG_DIR/lemmy_alpha.out 2>&1 &
echo "start beta"
LEMMY_HOSTNAME=lemmy-beta:8551 \
LEMMY_PORT=8551 \
LEMMY_CONFIG_LOCATION=./docker/federation/lemmy_beta.hjson \
LEMMY_DATABASE_URL="${LEMMY_DATABASE_URL}/lemmy_beta" \
LEMMY_FEDERATION__ALLOWED_INSTANCES=lemmy-alpha,lemmy-gamma,lemmy-delta,lemmy-epsilon \
LEMMY_SETUP__ADMIN_USERNAME=lemmy_beta \
LEMMY_SETUP__SITE_NAME=lemmy-beta \
target/lemmy_server >/dev/null 2>&1 &
target/lemmy_server >$LOG_DIR/lemmy_beta.out 2>&1 &
echo "start gamma"
LEMMY_HOSTNAME=lemmy-gamma:8561 \
LEMMY_PORT=8561 \
LEMMY_CONFIG_LOCATION=./docker/federation/lemmy_gamma.hjson \
LEMMY_DATABASE_URL="${LEMMY_DATABASE_URL}/lemmy_gamma" \
LEMMY_FEDERATION__ALLOWED_INSTANCES=lemmy-alpha,lemmy-beta,lemmy-delta,lemmy-epsilon \
LEMMY_SETUP__ADMIN_USERNAME=lemmy_gamma \
LEMMY_SETUP__SITE_NAME=lemmy-gamma \
target/lemmy_server >/dev/null 2>&1 &
target/lemmy_server >$LOG_DIR/lemmy_gamma.out 2>&1 &
echo "start delta"
# An instance with only an allowlist for beta
LEMMY_HOSTNAME=lemmy-delta:8571 \
LEMMY_PORT=8571 \
LEMMY_CONFIG_LOCATION=./docker/federation/lemmy_delta.hjson \
LEMMY_DATABASE_URL="${LEMMY_DATABASE_URL}/lemmy_delta" \
LEMMY_FEDERATION__ALLOWED_INSTANCES=lemmy-beta \
LEMMY_SETUP__ADMIN_USERNAME=lemmy_delta \
LEMMY_SETUP__SITE_NAME=lemmy-delta \
target/lemmy_server >/dev/null 2>&1 &
target/lemmy_server >$LOG_DIR/lemmy_delta.out 2>&1 &
echo "start epsilon"
# An instance who has a blocklist, with lemmy-alpha blocked
LEMMY_HOSTNAME=lemmy-epsilon:8581 \
LEMMY_PORT=8581 \
LEMMY_CONFIG_LOCATION=./docker/federation/lemmy_epsilon.hjson \
LEMMY_DATABASE_URL="${LEMMY_DATABASE_URL}/lemmy_epsilon" \
LEMMY_FEDERATION__BLOCKED_INSTANCES=lemmy-alpha \
LEMMY_SETUP__ADMIN_USERNAME=lemmy_epsilon \
LEMMY_SETUP__SITE_NAME=lemmy-epsilon \
target/lemmy_server >/dev/null 2>&1 &
target/lemmy_server >$LOG_DIR/lemmy_epsilon.out 2>&1 &
echo "wait for all instances to start"
while [[ "$(curl -s -o /dev/null -w '%{http_code}' 'localhost:8541/api/v2/site')" != "200" ]]; do sleep 1; done
while [[ "$(curl -s -o /dev/null -w '%{http_code}' 'localhost:8551/api/v2/site')" != "200" ]]; do sleep 1; done
while [[ "$(curl -s -o /dev/null -w '%{http_code}' 'localhost:8561/api/v2/site')" != "200" ]]; do sleep 1; done
while [[ "$(curl -s -o /dev/null -w '%{http_code}' 'localhost:8571/api/v2/site')" != "200" ]]; do sleep 1; done
while [[ "$(curl -s -o /dev/null -w '%{http_code}' 'localhost:8581/api/v2/site')" != "200" ]]; do sleep 1; done
while [[ "$(curl -s -o /dev/null -w '%{http_code}' 'lemmy-alpha:8541/api/v3/site')" != "200" ]]; do sleep 1; done
echo "alpha started"
while [[ "$(curl -s -o /dev/null -w '%{http_code}' 'lemmy-beta:8551/api/v3/site')" != "200" ]]; do sleep 1; done
echo "beta started"
while [[ "$(curl -s -o /dev/null -w '%{http_code}' 'lemmy-gamma:8561/api/v3/site')" != "200" ]]; do sleep 1; done
echo "gamma started"
while [[ "$(curl -s -o /dev/null -w '%{http_code}' 'lemmy-delta:8571/api/v3/site')" != "200" ]]; do sleep 1; done
echo "delta started"
while [[ "$(curl -s -o /dev/null -w '%{http_code}' 'lemmy-epsilon:8581/api/v3/site')" != "200" ]]; do sleep 1; done
echo "epsilon started. All started"

View File

@ -1,20 +1,21 @@
#!/bin/bash
#!/usr/bin/env bash
set -e
export LEMMY_DATABASE_URL=postgres://lemmy:password@localhost:5432
pushd ..
cargo +1.47.0 build
cargo build
rm target/lemmy_server || true
cp target/debug/lemmy_server target/lemmy_server
killall -s1 lemmy_server || true
./api_tests/prepare-drone-federation-test.sh
popd
yarn
yarn api-test || true
killall lemmy_server
pnpm i
pnpm api-test || true
killall -s1 lemmy_server || true
killall -s1 pict-rs || true
for INSTANCE in lemmy_alpha lemmy_beta lemmy_gamma lemmy_delta lemmy_epsilon; do
psql "$LEMMY_DATABASE_URL" -c "DROP DATABASE $INSTANCE"
done
rm -r /tmp/pictrs

View File

@ -1,4 +1,6 @@
jest.setTimeout(180000);
import { PostResponse } from "lemmy-js-client/dist/types/PostResponse";
import {
alpha,
beta,
@ -6,305 +8,542 @@ import {
setupLogins,
createPost,
getPost,
searchComment,
resolveComment,
likeComment,
followBeta,
searchForBetaCommunity,
resolveBetaCommunity,
createComment,
editComment,
deleteComment,
removeComment,
getMentions,
searchPost,
resolvePost,
unfollowRemotes,
createCommunity,
registerUser,
API,
} from './shared';
import { CommentView } from 'lemmy-js-client';
reportComment,
listCommentReports,
randomString,
unfollows,
getComments,
getCommentParentId,
resolveCommunity,
getPersonDetails,
getReplies,
getUnreadCount,
waitUntil,
waitForPost,
alphaUrl,
followCommunity,
blockCommunity,
delay,
} from "./shared";
import { CommentView, CommunityView } from "lemmy-js-client";
import { PostResponse } from 'lemmy-js-client';
let postRes: PostResponse;
let betaCommunity: CommunityView | undefined;
let postOnAlphaRes: PostResponse;
beforeAll(async () => {
await setupLogins();
await followBeta(alpha);
await followBeta(gamma);
let search = await searchForBetaCommunity(alpha);
postRes = await createPost(
alpha,
search.communities.find(c => c.community.local == false).community.id
);
await Promise.all([followBeta(alpha), followBeta(gamma)]);
betaCommunity = (await resolveBetaCommunity(alpha)).community;
if (betaCommunity) {
postOnAlphaRes = await createPost(alpha, betaCommunity.community.id);
}
});
afterAll(async () => {
await unfollowRemotes(alpha);
await unfollowRemotes(gamma);
});
afterAll(unfollows);
function assertCommentFederation(
commentOne: CommentView,
commentTwo: CommentView
commentOne?: CommentView,
commentTwo?: CommentView,
) {
expect(commentOne.comment.ap_id).toBe(commentOne.comment.ap_id);
expect(commentOne.comment.content).toBe(commentTwo.comment.content);
expect(commentOne.creator.name).toBe(commentTwo.creator.name);
expect(commentOne.community.actor_id).toBe(commentTwo.community.actor_id);
expect(commentOne.comment.published).toBe(commentTwo.comment.published);
expect(commentOne.comment.updated).toBe(commentOne.comment.updated);
expect(commentOne.comment.deleted).toBe(commentOne.comment.deleted);
expect(commentOne.comment.removed).toBe(commentOne.comment.removed);
expect(commentOne?.comment.ap_id).toBe(commentTwo?.comment.ap_id);
expect(commentOne?.comment.content).toBe(commentTwo?.comment.content);
expect(commentOne?.creator.name).toBe(commentTwo?.creator.name);
expect(commentOne?.community.actor_id).toBe(commentTwo?.community.actor_id);
expect(commentOne?.comment.published).toBe(commentTwo?.comment.published);
expect(commentOne?.comment.updated).toBe(commentOne?.comment.updated);
expect(commentOne?.comment.deleted).toBe(commentOne?.comment.deleted);
expect(commentOne?.comment.removed).toBe(commentOne?.comment.removed);
}
test('Create a comment', async () => {
let commentRes = await createComment(alpha, postRes.post_view.post.id);
test("Create a comment", async () => {
let commentRes = await createComment(alpha, postOnAlphaRes.post_view.post.id);
expect(commentRes.comment_view.comment.content).toBeDefined();
expect(commentRes.comment_view.community.local).toBe(false);
expect(commentRes.comment_view.creator.local).toBe(true);
expect(commentRes.comment_view.counts.score).toBe(1);
// Make sure that comment is liked on beta
let searchBeta = await searchComment(beta, commentRes.comment_view.comment);
let betaComment = searchBeta.comments[0];
let betaComment = (
await waitUntil(
() => resolveComment(beta, commentRes.comment_view.comment),
c => c.comment?.counts.score === 1,
)
).comment;
expect(betaComment).toBeDefined();
expect(betaComment.community.local).toBe(true);
expect(betaComment.creator.local).toBe(false);
expect(betaComment.counts.score).toBe(1);
expect(betaComment?.community.local).toBe(true);
expect(betaComment?.creator.local).toBe(false);
expect(betaComment?.counts.score).toBe(1);
assertCommentFederation(betaComment, commentRes.comment_view);
});
test('Create a comment in a non-existent post', async () => {
let commentRes = await createComment(alpha, -1);
expect(commentRes).toStrictEqual({ error: 'couldnt_find_post' });
test("Create a comment in a non-existent post", async () => {
await expect(createComment(alpha, -1)).rejects.toStrictEqual(
Error("couldnt_find_post"),
);
});
test('Update a comment', async () => {
let commentRes = await createComment(alpha, postRes.post_view.post.id);
test("Update a comment", async () => {
let commentRes = await createComment(alpha, postOnAlphaRes.post_view.post.id);
// Federate the comment first
let searchBeta = await searchComment(beta, commentRes.comment_view.comment);
assertCommentFederation(searchBeta.comments[0], commentRes.comment_view);
let betaComment = (
await resolveComment(beta, commentRes.comment_view.comment)
).comment;
assertCommentFederation(betaComment, commentRes.comment_view);
let updateCommentRes = await editComment(
alpha,
commentRes.comment_view.comment.id
commentRes.comment_view.comment.id,
);
expect(updateCommentRes.comment_view.comment.content).toBe(
'A jest test federated comment update'
"A jest test federated comment update",
);
expect(updateCommentRes.comment_view.community.local).toBe(false);
expect(updateCommentRes.comment_view.creator.local).toBe(true);
// Make sure that post is updated on beta
let searchBetaUpdated = await searchComment(
beta,
commentRes.comment_view.comment
);
assertCommentFederation(
searchBetaUpdated.comments[0],
updateCommentRes.comment_view
);
let betaCommentUpdated = (
await waitUntil(
() => resolveComment(beta, commentRes.comment_view.comment),
c =>
c.comment?.comment.content === "A jest test federated comment update",
)
).comment;
assertCommentFederation(betaCommentUpdated, updateCommentRes.comment_view);
});
test('Delete a comment', async () => {
let commentRes = await createComment(alpha, postRes.post_view.post.id);
test("Delete a comment", async () => {
let post = await createPost(alpha, betaCommunity!.community.id);
// creating a comment on alpha (remote from home of community)
let commentRes = await createComment(alpha, post.post_view.post.id);
// Find the comment on beta (home of community)
let betaComment = (
await resolveComment(beta, commentRes.comment_view.comment)
).comment;
if (!betaComment) {
throw "Missing beta comment before delete";
}
// Find the comment on remote instance gamma
let gammaComment = (
await waitUntil(
() =>
resolveComment(gamma, commentRes.comment_view.comment).catch(e => e),
r => r.message !== "couldnt_find_object",
)
).comment;
if (!gammaComment) {
throw "Missing gamma comment (remote-home-remote replication) before delete";
}
let deleteCommentRes = await deleteComment(
alpha,
true,
commentRes.comment_view.comment.id
commentRes.comment_view.comment.id,
);
expect(deleteCommentRes.comment_view.comment.deleted).toBe(true);
expect(deleteCommentRes.comment_view.comment.content).toBe("");
// Make sure that comment is undefined on beta
let searchBeta = await searchComment(beta, commentRes.comment_view.comment);
let betaComment = searchBeta.comments[0];
expect(betaComment).toBeUndefined();
await waitUntil(
() => resolveComment(beta, commentRes.comment_view.comment).catch(e => e),
e => e.message == "couldnt_find_object",
);
// Make sure that comment is undefined on gamma after delete
await waitUntil(
() => resolveComment(gamma, commentRes.comment_view.comment).catch(e => e),
e => e.message === "couldnt_find_object",
);
// Test undeleting the comment
let undeleteCommentRes = await deleteComment(
alpha,
false,
commentRes.comment_view.comment.id
commentRes.comment_view.comment.id,
);
expect(undeleteCommentRes.comment_view.comment.deleted).toBe(false);
// Make sure that comment is undeleted on beta
let searchBeta2 = await searchComment(beta, commentRes.comment_view.comment);
let betaComment2 = searchBeta2.comments[0];
expect(betaComment2.comment.deleted).toBe(false);
assertCommentFederation(
searchBeta2.comments[0],
undeleteCommentRes.comment_view
);
let betaComment2 = (
await waitUntil(
() => resolveComment(beta, commentRes.comment_view.comment).catch(e => e),
e => e.message !== "couldnt_find_object",
)
).comment;
expect(betaComment2?.comment.deleted).toBe(false);
assertCommentFederation(betaComment2, undeleteCommentRes.comment_view);
});
test('Remove a comment from admin and community on the same instance', async () => {
let commentRes = await createComment(alpha, postRes.post_view.post.id);
test.skip("Remove a comment from admin and community on the same instance", async () => {
let commentRes = await createComment(alpha, postOnAlphaRes.post_view.post.id);
// Get the id for beta
let betaCommentId = (
await searchComment(beta, commentRes.comment_view.comment)
).comments[0].comment.id;
await resolveComment(beta, commentRes.comment_view.comment)
).comment?.comment.id;
if (!betaCommentId) {
throw "beta comment id is missing";
}
// The beta admin removes it (the community lives on beta)
let removeCommentRes = await removeComment(beta, true, betaCommentId);
expect(removeCommentRes.comment_view.comment.removed).toBe(true);
// Make sure that comment is removed on alpha (it gets pushed since an admin from beta removed it)
let refetchedPost = await getPost(alpha, postRes.post_view.post.id);
expect(refetchedPost.comments[0].comment.removed).toBe(true);
let refetchedPostComments = await getPersonDetails(
alpha,
commentRes.comment_view.comment.creator_id,
);
expect(refetchedPostComments.comments[0].comment.removed).toBe(true);
// beta will unremove the comment
let unremoveCommentRes = await removeComment(beta, false, betaCommentId);
expect(unremoveCommentRes.comment_view.comment.removed).toBe(false);
// Make sure that comment is unremoved on beta
let refetchedPost2 = await getPost(alpha, postRes.post_view.post.id);
expect(refetchedPost2.comments[0].comment.removed).toBe(false);
// Make sure that comment is unremoved on alpha
let refetchedPostComments2 = await getComments(
alpha,
postOnAlphaRes.post_view.post.id,
);
expect(refetchedPostComments2.comments[0].comment.removed).toBe(false);
assertCommentFederation(
refetchedPost2.comments[0],
unremoveCommentRes.comment_view
refetchedPostComments2.comments[0],
unremoveCommentRes.comment_view,
);
});
test('Remove a comment from admin and community on different instance', async () => {
let alphaUser = await registerUser(alpha);
let newAlphaApi: API = {
client: alpha.client,
auth: alphaUser.jwt,
};
test("Remove a comment from admin and community on different instance", async () => {
let newAlphaApi = await registerUser(alpha, alphaUrl);
// New alpha user creates a community, post, and comment.
let newCommunity = await createCommunity(newAlphaApi);
let newPost = await createPost(
newAlphaApi,
newCommunity.community_view.community.id
newCommunity.community_view.community.id,
);
let commentRes = await createComment(newAlphaApi, newPost.post_view.post.id);
expect(commentRes.comment_view.comment.content).toBeDefined();
// Beta searches that to cache it, then removes it
let searchBeta = await searchComment(beta, commentRes.comment_view.comment);
let betaComment = searchBeta.comments[0];
let betaComment = (
await resolveComment(beta, commentRes.comment_view.comment)
).comment;
if (!betaComment) {
throw "beta comment missing";
}
let removeCommentRes = await removeComment(
beta,
true,
betaComment.comment.id
betaComment.comment.id,
);
expect(removeCommentRes.comment_view.comment.removed).toBe(true);
expect(removeCommentRes.comment_view.comment.content).toBe("");
// Comment text is also hidden from list
let listComments = await getComments(
beta,
removeCommentRes.comment_view.post.id,
);
expect(listComments.comments.length).toBe(1);
expect(listComments.comments[0].comment.removed).toBe(true);
expect(listComments.comments[0].comment.content).toBe("");
// Make sure its not removed on alpha
let refetchedPost = await getPost(newAlphaApi, newPost.post_view.post.id);
expect(refetchedPost.comments[0].comment.removed).toBe(false);
assertCommentFederation(refetchedPost.comments[0], commentRes.comment_view);
let refetchedPostComments = await getComments(
alpha,
newPost.post_view.post.id,
);
expect(refetchedPostComments.comments[0].comment.removed).toBe(false);
assertCommentFederation(
refetchedPostComments.comments[0],
commentRes.comment_view,
);
});
test('Unlike a comment', async () => {
let commentRes = await createComment(alpha, postRes.post_view.post.id);
test("Unlike a comment", async () => {
let commentRes = await createComment(alpha, postOnAlphaRes.post_view.post.id);
// Lemmy automatically creates 1 like (vote) by author of comment.
// Make sure that comment is liked (voted up) on gamma, downstream peer
// This is testing replication from remote-home-remote (alpha-beta-gamma)
let gammaComment1 = (
await waitUntil(
() => resolveComment(gamma, commentRes.comment_view.comment),
c => c.comment?.counts.score === 1,
)
).comment;
expect(gammaComment1).toBeDefined();
expect(gammaComment1?.community.local).toBe(false);
expect(gammaComment1?.creator.local).toBe(false);
expect(gammaComment1?.counts.score).toBe(1);
let unlike = await likeComment(alpha, 0, commentRes.comment_view.comment);
expect(unlike.comment_view.counts.score).toBe(0);
// Make sure that post is unliked on beta
let searchBeta = await searchComment(beta, commentRes.comment_view.comment);
let betaComment = searchBeta.comments[0];
// Make sure that comment is unliked on beta
let betaComment = (
await waitUntil(
() => resolveComment(beta, commentRes.comment_view.comment),
c => c.comment?.counts.score === 0,
)
).comment;
expect(betaComment).toBeDefined();
expect(betaComment.community.local).toBe(true);
expect(betaComment.creator.local).toBe(false);
expect(betaComment.counts.score).toBe(0);
expect(betaComment?.community.local).toBe(true);
expect(betaComment?.creator.local).toBe(false);
expect(betaComment?.counts.score).toBe(0);
// Make sure that comment is unliked on gamma, downstream peer
// This is testing replication from remote-home-remote (alpha-beta-gamma)
let gammaComment = (
await waitUntil(
() => resolveComment(gamma, commentRes.comment_view.comment),
c => c.comment?.counts.score === 0,
)
).comment;
expect(gammaComment).toBeDefined();
expect(gammaComment?.community.local).toBe(false);
expect(gammaComment?.creator.local).toBe(false);
expect(gammaComment?.counts.score).toBe(0);
});
test('Federated comment like', async () => {
let commentRes = await createComment(alpha, postRes.post_view.post.id);
test("Federated comment like", async () => {
let commentRes = await createComment(alpha, postOnAlphaRes.post_view.post.id);
await waitUntil(
() => resolveComment(beta, commentRes.comment_view.comment),
c => c.comment?.counts.score === 1,
);
// Find the comment on beta
let searchBeta = await searchComment(beta, commentRes.comment_view.comment);
let betaComment = searchBeta.comments[0];
let betaComment = (
await resolveComment(beta, commentRes.comment_view.comment)
).comment;
if (!betaComment) {
throw "Missing beta comment";
}
let like = await likeComment(beta, 1, betaComment.comment);
expect(like.comment_view.counts.score).toBe(2);
// Get the post from alpha, check the likes
let post = await getPost(alpha, postRes.post_view.post.id);
expect(post.comments[0].counts.score).toBe(2);
let postComments = await waitUntil(
() => getComments(alpha, postOnAlphaRes.post_view.post.id),
c => c.comments[0].counts.score === 2,
);
expect(postComments.comments[0].counts.score).toBe(2);
});
test('Reply to a comment', async () => {
// Create a comment on alpha, find it on beta
let commentRes = await createComment(alpha, postRes.post_view.post.id);
let searchBeta = await searchComment(beta, commentRes.comment_view.comment);
let betaComment = searchBeta.comments[0];
test("Reply to a comment from another instance, get notification", async () => {
await alpha.markAllAsRead();
let betaCommunity = (
await waitUntil(
() => resolveBetaCommunity(alpha),
c => !!c.community?.community.instance_id,
)
).community;
if (!betaCommunity) {
throw "Missing beta community";
}
const postOnAlphaRes = await createPost(alpha, betaCommunity.community.id);
// Create a root-level trunk-branch comment on alpha
let commentRes = await createComment(alpha, postOnAlphaRes.post_view.post.id);
// find that comment id on beta
let betaComment = (
await waitUntil(
() => resolveComment(beta, commentRes.comment_view.comment),
c => c.comment?.counts.score === 1,
)
).comment;
// Reply from beta
if (!betaComment) {
throw "Missing beta comment";
}
// Reply from beta, extending the branch
let replyRes = await createComment(
beta,
betaComment.post.id,
betaComment.comment.id
betaComment.comment.id,
);
expect(replyRes.comment_view.comment.content).toBeDefined();
expect(replyRes.comment_view.community.local).toBe(true);
expect(replyRes.comment_view.creator.local).toBe(true);
expect(replyRes.comment_view.comment.parent_id).toBe(betaComment.comment.id);
expect(getCommentParentId(replyRes.comment_view.comment)).toBe(
betaComment.comment.id,
);
expect(replyRes.comment_view.counts.score).toBe(1);
// Make sure that comment is seen on alpha
// TODO not sure why, but a searchComment back to alpha, for the ap_id of betas
// comment, isn't working.
// let searchAlpha = await searchComment(alpha, replyRes.comment);
let post = await getPost(alpha, postRes.post_view.post.id);
let alphaComment = post.comments[0];
// Make sure that reply comment is seen on alpha
let commentSearch = await waitUntil(
() => resolveComment(alpha, replyRes.comment_view.comment),
c => c.comment?.counts.score === 1,
);
let alphaComment = commentSearch.comment!;
let postComments = await waitUntil(
() => getComments(alpha, postOnAlphaRes.post_view.post.id),
pc => pc.comments.length >= 2,
);
// Note: this test fails when run twice and this count will differ
expect(postComments.comments.length).toBeGreaterThanOrEqual(2);
expect(alphaComment.comment.content).toBeDefined();
expect(alphaComment.comment.parent_id).toBe(post.comments[1].comment.id);
expect(getCommentParentId(alphaComment.comment)).toBe(
postComments.comments[1].comment.id,
);
expect(alphaComment.community.local).toBe(false);
expect(alphaComment.creator.local).toBe(false);
expect(alphaComment.counts.score).toBe(1);
assertCommentFederation(alphaComment, replyRes.comment_view);
// Did alpha get notified of the reply from beta?
let alphaUnreadCountRes = await waitUntil(
() => getUnreadCount(alpha),
e => e.replies >= 1,
);
expect(alphaUnreadCountRes.replies).toBeGreaterThanOrEqual(1);
// check inbox of replies on alpha, fetching read/unread both
let alphaRepliesRes = await waitUntil(
() => getReplies(alpha),
r => r.replies.length > 0,
);
const alphaReply = alphaRepliesRes.replies.find(
r => r.comment.id === alphaComment.comment.id,
);
expect(alphaReply).toBeDefined();
if (!alphaReply) throw Error();
expect(alphaReply.comment.content).toBeDefined();
expect(alphaReply.community.local).toBe(false);
expect(alphaReply.creator.local).toBe(false);
expect(alphaReply.counts.score).toBe(1);
// ToDo: interesting alphaRepliesRes.replies[0].comment_reply.id is 1, meaning? how did that come about?
expect(alphaReply.comment.id).toBe(alphaComment.comment.id);
// this is a new notification, getReplies fetch was for read/unread both, confirm it is unread.
expect(alphaReply.comment_reply.read).toBe(false);
assertCommentFederation(alphaReply, replyRes.comment_view);
});
test('Mention beta', async () => {
// Create a mention on alpha
let mentionContent = 'A test mention of @lemmy_beta@lemmy-beta:8551';
let commentRes = await createComment(alpha, postRes.post_view.post.id);
test("Mention beta from alpha", async () => {
if (!betaCommunity) throw Error("no community");
const postOnAlphaRes = await createPost(alpha, betaCommunity.community.id);
// Create a new branch, trunk-level comment branch, from alpha instance
let commentRes = await createComment(alpha, postOnAlphaRes.post_view.post.id);
// Create a reply comment to previous comment, this has a mention in body
let mentionContent = "A test mention of @lemmy_beta@lemmy-beta:8551";
let mentionRes = await createComment(
alpha,
postRes.post_view.post.id,
postOnAlphaRes.post_view.post.id,
commentRes.comment_view.comment.id,
mentionContent
mentionContent,
);
expect(mentionRes.comment_view.comment.content).toBeDefined();
expect(mentionRes.comment_view.community.local).toBe(false);
expect(mentionRes.comment_view.creator.local).toBe(true);
expect(mentionRes.comment_view.counts.score).toBe(1);
let mentionsRes = await getMentions(beta);
// get beta's localized copy of the alpha post
let betaPost = await waitForPost(beta, postOnAlphaRes.post_view.post);
if (!betaPost) {
throw "unable to locate post on beta";
}
expect(betaPost.post.ap_id).toBe(postOnAlphaRes.post_view.post.ap_id);
expect(betaPost.post.name).toBe(postOnAlphaRes.post_view.post.name);
// Make sure that both new comments are seen on beta and have parent/child relationship
let betaPostComments = await waitUntil(
() => getComments(beta, betaPost!.post.id),
c => c.comments[1]?.counts.score === 1,
);
expect(betaPostComments.comments.length).toEqual(2);
// the trunk-branch root comment will be older than the mention reply comment, so index 1
let betaRootComment = betaPostComments.comments[1];
// the trunk-branch root comment should not have a parent
expect(getCommentParentId(betaRootComment.comment)).toBeUndefined();
expect(betaRootComment.comment.content).toBeDefined();
// the mention reply comment should have parent that points to the branch root level comment
expect(getCommentParentId(betaPostComments.comments[0].comment)).toBe(
betaPostComments.comments[1].comment.id,
);
expect(betaRootComment.community.local).toBe(true);
expect(betaRootComment.creator.local).toBe(false);
expect(betaRootComment.counts.score).toBe(1);
assertCommentFederation(betaRootComment, commentRes.comment_view);
let mentionsRes = await waitUntil(
() => getMentions(beta),
m => !!m.mentions[0],
);
expect(mentionsRes.mentions[0].comment.content).toBeDefined();
expect(mentionsRes.mentions[0].community.local).toBe(true);
expect(mentionsRes.mentions[0].creator.local).toBe(false);
expect(mentionsRes.mentions[0].counts.score).toBe(1);
// the reply comment with mention should be the most fresh, newest, index 0
expect(mentionsRes.mentions[0].person_mention.comment_id).toBe(
betaPostComments.comments[0].comment.id,
);
});
test('Comment Search', async () => {
let commentRes = await createComment(alpha, postRes.post_view.post.id);
let searchBeta = await searchComment(beta, commentRes.comment_view.comment);
assertCommentFederation(searchBeta.comments[0], commentRes.comment_view);
test("Comment Search", async () => {
let commentRes = await createComment(alpha, postOnAlphaRes.post_view.post.id);
let betaComment = (
await resolveComment(beta, commentRes.comment_view.comment)
).comment;
assertCommentFederation(betaComment, commentRes.comment_view);
});
test('A and G subscribe to B (center) A posts, G mentions B, it gets announced to A', async () => {
test("A and G subscribe to B (center) A posts, G mentions B, it gets announced to A", async () => {
// Create a local post
let alphaPost = await createPost(alpha, 2);
let alphaCommunity = (await resolveCommunity(alpha, "!main@lemmy-alpha:8541"))
.community;
if (!alphaCommunity) {
throw "Missing alpha community";
}
// follow community from beta so that it accepts the mention
let betaCommunity = await resolveCommunity(
beta,
alphaCommunity.community.actor_id,
);
await followCommunity(beta, true, betaCommunity.community!.community.id);
let alphaPost = await createPost(alpha, alphaCommunity.community.id);
expect(alphaPost.post_view.community.local).toBe(true);
// Make sure gamma sees it
let search = await searchPost(gamma, alphaPost.post_view.post);
let gammaPost = search.posts[0];
let gammaPost = (await resolvePost(gamma, alphaPost.post_view.post))!.post;
if (!gammaPost) {
throw "Missing gamma post";
}
let commentContent =
'A jest test federated comment announce, lets mention @lemmy_beta@lemmy-beta:8551';
"A jest test federated comment announce, lets mention @lemmy_beta@lemmy-beta:8551";
let commentRes = await createComment(
gamma,
gammaPost.post.id,
undefined,
commentContent
commentContent,
);
expect(commentRes.comment_view.comment.content).toBe(commentContent);
expect(commentRes.comment_view.community.local).toBe(false);
@ -312,80 +551,256 @@ test('A and G subscribe to B (center) A posts, G mentions B, it gets announced t
expect(commentRes.comment_view.counts.score).toBe(1);
// Make sure alpha sees it
let alphaPost2 = await getPost(alpha, alphaPost.post_view.post.id);
expect(alphaPost2.comments[0].comment.content).toBe(commentContent);
expect(alphaPost2.comments[0].community.local).toBe(true);
expect(alphaPost2.comments[0].creator.local).toBe(false);
expect(alphaPost2.comments[0].counts.score).toBe(1);
assertCommentFederation(alphaPost2.comments[0], commentRes.comment_view);
let alphaPostComments2 = await waitUntil(
() => getComments(alpha, alphaPost.post_view.post.id),
e => e.comments[0]?.counts.score === 1,
);
expect(alphaPostComments2.comments[0].comment.content).toBe(commentContent);
expect(alphaPostComments2.comments[0].community.local).toBe(true);
expect(alphaPostComments2.comments[0].creator.local).toBe(false);
expect(alphaPostComments2.comments[0].counts.score).toBe(1);
assertCommentFederation(
alphaPostComments2.comments[0],
commentRes.comment_view,
);
// Make sure beta has mentions
let mentionsRes = await getMentions(beta);
expect(mentionsRes.mentions[0].comment.content).toBe(commentContent);
expect(mentionsRes.mentions[0].community.local).toBe(false);
expect(mentionsRes.mentions[0].creator.local).toBe(false);
let relevantMention = await waitUntil(
() =>
getMentions(beta).then(m =>
m.mentions.find(
m => m.comment.ap_id === commentRes.comment_view.comment.ap_id,
),
),
e => !!e,
);
if (!relevantMention) throw Error("could not find mention");
expect(relevantMention.comment.content).toBe(commentContent);
expect(relevantMention.community.local).toBe(false);
expect(relevantMention.creator.local).toBe(false);
// TODO this is failing because fetchInReplyTos aren't getting score
// expect(mentionsRes.mentions[0].score).toBe(1);
});
test('Fetch in_reply_tos: A is unsubbed from B, B makes a post, and some embedded comments, A subs to B, B updates the lowest level comment, A fetches both the post and all the inreplyto comments for that post.', async () => {
test("Check that activity from another instance is sent to third instance", async () => {
// Alpha and gamma users follow beta community
let alphaFollow = await followBeta(alpha);
expect(alphaFollow.community_view.community.local).toBe(false);
expect(alphaFollow.community_view.community.name).toBe("main");
let gammaFollow = await followBeta(gamma);
expect(gammaFollow.community_view.community.local).toBe(false);
expect(gammaFollow.community_view.community.name).toBe("main");
await waitUntil(
() => resolveBetaCommunity(alpha),
c => c.community?.subscribed === "Subscribed",
);
await waitUntil(
() => resolveBetaCommunity(gamma),
c => c.community?.subscribed === "Subscribed",
);
// Create a post on beta
let betaPost = await createPost(beta, 2);
expect(betaPost.post_view.community.local).toBe(true);
// Make sure gamma and alpha see it
let gammaPost = await waitForPost(gamma, betaPost.post_view.post);
if (!gammaPost) {
throw "Missing gamma post";
}
expect(gammaPost.post).toBeDefined();
let alphaPost = await waitForPost(alpha, betaPost.post_view.post);
if (!alphaPost) {
throw "Missing alpha post";
}
expect(alphaPost.post).toBeDefined();
// The bug: gamma comments, and alpha should see it.
let commentContent = "Comment from gamma";
let commentRes = await createComment(
gamma,
gammaPost.post.id,
undefined,
commentContent,
);
expect(commentRes.comment_view.comment.content).toBe(commentContent);
expect(commentRes.comment_view.community.local).toBe(false);
expect(commentRes.comment_view.creator.local).toBe(true);
expect(commentRes.comment_view.counts.score).toBe(1);
// Make sure alpha sees it
let alphaPostComments2 = await waitUntil(
() => getComments(alpha, alphaPost!.post.id),
e => e.comments[0]?.counts.score === 1,
);
expect(alphaPostComments2.comments[0].comment.content).toBe(commentContent);
expect(alphaPostComments2.comments[0].community.local).toBe(false);
expect(alphaPostComments2.comments[0].creator.local).toBe(false);
expect(alphaPostComments2.comments[0].counts.score).toBe(1);
assertCommentFederation(
alphaPostComments2.comments[0],
commentRes.comment_view,
);
await Promise.all([unfollowRemotes(alpha), unfollowRemotes(gamma)]);
});
test("Fetch in_reply_tos: A is unsubbed from B, B makes a post, and some embedded comments, A subs to B, B updates the lowest level comment, A fetches both the post and all the inreplyto comments for that post.", async () => {
// Unfollow all remote communities
let followed = await unfollowRemotes(alpha);
let site = await unfollowRemotes(alpha);
expect(
followed.communities.filter(c => c.community.local == false).length
site.my_user?.follows.filter(c => c.community.local == false).length,
).toBe(0);
// B creates a post, and two comments, should be invisible to A
let postRes = await createPost(beta, 2);
expect(postRes.post_view.post.name).toBeDefined();
let postOnBetaRes = await createPost(beta, 2);
expect(postOnBetaRes.post_view.post.name).toBeDefined();
let parentCommentContent = 'An invisible top level comment from beta';
let parentCommentContent = "An invisible top level comment from beta";
let parentCommentRes = await createComment(
beta,
postRes.post_view.post.id,
postOnBetaRes.post_view.post.id,
undefined,
parentCommentContent
parentCommentContent,
);
expect(parentCommentRes.comment_view.comment.content).toBe(
parentCommentContent
parentCommentContent,
);
// B creates a comment, then a child one of that.
let childCommentContent = 'An invisible child comment from beta';
let childCommentContent = "An invisible child comment from beta";
let childCommentRes = await createComment(
beta,
postRes.post_view.post.id,
postOnBetaRes.post_view.post.id,
parentCommentRes.comment_view.comment.id,
childCommentContent
childCommentContent,
);
expect(childCommentRes.comment_view.comment.content).toBe(
childCommentContent
childCommentContent,
);
// Follow beta again
let follow = await followBeta(alpha);
expect(follow.community_view.community.local).toBe(false);
expect(follow.community_view.community.name).toBe('main');
expect(follow.community_view.community.name).toBe("main");
// An update to the child comment on beta, should push the post, parent, and child to alpha now
let updatedCommentContent = 'An update child comment from beta';
let updatedCommentContent = "An update child comment from beta";
let updateRes = await editComment(
beta,
childCommentRes.comment_view.comment.id,
updatedCommentContent
updatedCommentContent,
);
expect(updateRes.comment_view.comment.content).toBe(updatedCommentContent);
// Get the post from alpha
let search = await searchPost(alpha, postRes.post_view.post);
let alphaPostB = search.posts[0];
let alphaPostB = await waitForPost(alpha, postOnBetaRes.post_view.post);
if (!alphaPostB) {
throw "Missing alpha post B";
}
let alphaPost = await getPost(alpha, alphaPostB.post.id);
let alphaPostComments = await waitUntil(
() => getComments(alpha, alphaPostB!.post.id),
c =>
c.comments[1]?.comment.content ===
parentCommentRes.comment_view.comment.content &&
c.comments[0]?.comment.content === updateRes.comment_view.comment.content,
);
expect(alphaPost.post_view.post.name).toBeDefined();
assertCommentFederation(alphaPost.comments[1], parentCommentRes.comment_view);
assertCommentFederation(alphaPost.comments[0], updateRes.comment_view);
assertCommentFederation(
alphaPostComments.comments[1],
parentCommentRes.comment_view,
);
assertCommentFederation(
alphaPostComments.comments[0],
updateRes.comment_view,
);
expect(alphaPost.post_view.community.local).toBe(false);
expect(alphaPost.post_view.creator.local).toBe(false);
await unfollowRemotes(alpha);
});
test("Report a comment", async () => {
let betaCommunity = (await resolveBetaCommunity(beta)).community;
if (!betaCommunity) {
throw "Missing beta community";
}
let postOnBetaRes = (await createPost(beta, betaCommunity.community.id))
.post_view.post;
expect(postOnBetaRes).toBeDefined();
let commentRes = (await createComment(beta, postOnBetaRes.id)).comment_view
.comment;
expect(commentRes).toBeDefined();
let alphaComment = (await resolveComment(alpha, commentRes)).comment?.comment;
if (!alphaComment) {
throw "Missing alpha comment";
}
const reason = randomString(10);
let alphaReport = (await reportComment(alpha, alphaComment.id, reason))
.comment_report_view.comment_report;
let betaReport = (await waitUntil(
() =>
listCommentReports(beta).then(r =>
r.comment_reports.find(rep => rep.comment_report.reason === reason),
),
e => !!e,
))!.comment_report;
expect(betaReport).toBeDefined();
expect(betaReport.resolved).toBe(false);
expect(betaReport.original_comment_text).toBe(
alphaReport.original_comment_text,
);
expect(betaReport.reason).toBe(alphaReport.reason);
});
test("Dont send a comment reply to a blocked community", async () => {
let newCommunity = await createCommunity(beta);
let newCommunityId = newCommunity.community_view.community.id;
// Create a post on beta
let betaPost = await createPost(beta, newCommunityId);
let alphaPost = (await resolvePost(alpha, betaPost.post_view.post))!.post;
if (!alphaPost) {
throw "unable to locate post on alpha";
}
// Check beta's inbox count
let unreadCount = await getUnreadCount(beta);
expect(unreadCount.replies).toBe(1);
// Beta blocks the new beta community
let blockRes = await blockCommunity(beta, newCommunityId, true);
expect(blockRes.blocked).toBe(true);
delay();
// Alpha creates a comment
let commentRes = await createComment(alpha, alphaPost.post.id);
expect(commentRes.comment_view.comment.content).toBeDefined();
let alphaComment = await resolveComment(
beta,
commentRes.comment_view.comment,
);
if (!alphaComment) {
throw "Missing alpha comment before block";
}
// Check beta's inbox count, make sure it stays the same
unreadCount = await getUnreadCount(beta);
expect(unreadCount.replies).toBe(1);
let replies = await getReplies(beta);
expect(replies.replies.length).toBe(1);
// Unblock the community
blockRes = await blockCommunity(beta, newCommunityId, false);
expect(blockRes.blocked).toBe(false);
});

View File

@ -1,76 +1,94 @@
jest.setTimeout(120000);
import { CommunityView } from "lemmy-js-client/dist/types/CommunityView";
import {
alpha,
beta,
gamma,
setupLogins,
searchForCommunity,
resolveCommunity,
createCommunity,
deleteCommunity,
removeCommunity,
getCommunity,
followCommunity,
} from './shared';
import { CommunityView } from 'lemmy-js-client';
banPersonFromCommunity,
resolvePerson,
getSite,
createPost,
getPost,
resolvePost,
registerUser,
getPosts,
getComments,
createComment,
getCommunityByName,
blockInstance,
waitUntil,
alphaUrl,
delta,
betaAllowedInstances,
searchPostLocal,
longDelay,
editCommunity,
unfollows,
} from "./shared";
import { EditCommunity, EditSite } from "lemmy-js-client";
beforeAll(async () => {
await setupLogins();
});
beforeAll(setupLogins);
afterAll(unfollows);
function assertCommunityFederation(
communityOne: CommunityView,
communityTwo: CommunityView
communityOne?: CommunityView,
communityTwo?: CommunityView,
) {
expect(communityOne.community.actor_id).toBe(communityTwo.community.actor_id);
expect(communityOne.community.name).toBe(communityTwo.community.name);
expect(communityOne.community.title).toBe(communityTwo.community.title);
expect(communityOne.community.description).toBe(
communityTwo.community.description
expect(communityOne?.community.actor_id).toBe(
communityTwo?.community.actor_id,
);
expect(communityOne.community.icon).toBe(communityTwo.community.icon);
expect(communityOne.community.banner).toBe(communityTwo.community.banner);
expect(communityOne.community.published).toBe(
communityTwo.community.published
expect(communityOne?.community.name).toBe(communityTwo?.community.name);
expect(communityOne?.community.title).toBe(communityTwo?.community.title);
expect(communityOne?.community.description).toBe(
communityTwo?.community.description,
);
expect(communityOne.creator.actor_id).toBe(communityTwo.creator.actor_id);
expect(communityOne.community.nsfw).toBe(communityTwo.community.nsfw);
expect(communityOne.community.category_id).toBe(
communityTwo.community.category_id
expect(communityOne?.community.icon).toBe(communityTwo?.community.icon);
expect(communityOne?.community.banner).toBe(communityTwo?.community.banner);
expect(communityOne?.community.published).toBe(
communityTwo?.community.published,
);
expect(communityOne.community.removed).toBe(communityTwo.community.removed);
expect(communityOne.community.deleted).toBe(communityTwo.community.deleted);
expect(communityOne?.community.nsfw).toBe(communityTwo?.community.nsfw);
expect(communityOne?.community.removed).toBe(communityTwo?.community.removed);
expect(communityOne?.community.deleted).toBe(communityTwo?.community.deleted);
}
test('Create community', async () => {
test("Create community", async () => {
let communityRes = await createCommunity(alpha);
expect(communityRes.community_view.community.name).toBeDefined();
// A dupe check
let prevName = communityRes.community_view.community.name;
let communityRes2: any = await createCommunity(alpha, prevName);
expect(communityRes2['error']).toBe('community_already_exists');
await expect(createCommunity(alpha, prevName)).rejects.toStrictEqual(
Error("community_already_exists"),
);
// Cache the community on beta, make sure it has the other fields
let searchShort = `!${prevName}@lemmy-alpha:8541`;
let search = await searchForCommunity(beta, searchShort);
let communityOnBeta = search.communities[0];
assertCommunityFederation(communityOnBeta, communityRes.community_view);
let betaCommunity = (await resolveCommunity(beta, searchShort)).community;
assertCommunityFederation(betaCommunity, communityRes.community_view);
});
test('Delete community', async () => {
test("Delete community", async () => {
let communityRes = await createCommunity(beta);
// Cache the community on Alpha
let searchShort = `!${communityRes.community_view.community.name}@lemmy-beta:8551`;
let search = await searchForCommunity(alpha, searchShort);
let communityOnAlpha = search.communities[0];
assertCommunityFederation(communityOnAlpha, communityRes.community_view);
let alphaCommunity = (await resolveCommunity(alpha, searchShort)).community;
if (!alphaCommunity) {
throw "Missing alpha community";
}
assertCommunityFederation(alphaCommunity, communityRes.community_view);
// Follow the community from alpha
let follow = await followCommunity(
alpha,
true,
communityOnAlpha.community.id
);
let follow = await followCommunity(alpha, true, alphaCommunity.community.id);
// Make sure the follow response went through
expect(follow.community_view.community.local).toBe(false);
@ -78,14 +96,17 @@ test('Delete community', async () => {
let deleteCommunityRes = await deleteCommunity(
beta,
true,
communityRes.community_view.community.id
communityRes.community_view.community.id,
);
expect(deleteCommunityRes.community_view.community.deleted).toBe(true);
expect(deleteCommunityRes.community_view.community.title).toBe(
communityRes.community_view.community.title,
);
// Make sure it got deleted on A
let communityOnAlphaDeleted = await getCommunity(
alpha,
communityOnAlpha.community.id
let communityOnAlphaDeleted = await waitUntil(
() => getCommunity(alpha, alphaCommunity!.community.id),
g => g.community_view.community.deleted,
);
expect(communityOnAlphaDeleted.community_view.community.deleted).toBe(true);
@ -93,35 +114,33 @@ test('Delete community', async () => {
let undeleteCommunityRes = await deleteCommunity(
beta,
false,
communityRes.community_view.community.id
communityRes.community_view.community.id,
);
expect(undeleteCommunityRes.community_view.community.deleted).toBe(false);
// Make sure it got undeleted on A
let communityOnAlphaUnDeleted = await getCommunity(
alpha,
communityOnAlpha.community.id
let communityOnAlphaUnDeleted = await waitUntil(
() => getCommunity(alpha, alphaCommunity!.community.id),
g => !g.community_view.community.deleted,
);
expect(communityOnAlphaUnDeleted.community_view.community.deleted).toBe(
false
false,
);
});
test('Remove community', async () => {
test("Remove community", async () => {
let communityRes = await createCommunity(beta);
// Cache the community on Alpha
let searchShort = `!${communityRes.community_view.community.name}@lemmy-beta:8551`;
let search = await searchForCommunity(alpha, searchShort);
let communityOnAlpha = search.communities[0];
assertCommunityFederation(communityOnAlpha, communityRes.community_view);
let alphaCommunity = (await resolveCommunity(alpha, searchShort)).community;
if (!alphaCommunity) {
throw "Missing alpha community";
}
assertCommunityFederation(alphaCommunity, communityRes.community_view);
// Follow the community from alpha
let follow = await followCommunity(
alpha,
true,
communityOnAlpha.community.id
);
let follow = await followCommunity(alpha, true, alphaCommunity.community.id);
// Make sure the follow response went through
expect(follow.community_view.community.local).toBe(false);
@ -129,14 +148,17 @@ test('Remove community', async () => {
let removeCommunityRes = await removeCommunity(
beta,
true,
communityRes.community_view.community.id
communityRes.community_view.community.id,
);
expect(removeCommunityRes.community_view.community.removed).toBe(true);
expect(removeCommunityRes.community_view.community.title).toBe(
communityRes.community_view.community.title,
);
// Make sure it got Removed on A
let communityOnAlphaRemoved = await getCommunity(
alpha,
communityOnAlpha.community.id
let communityOnAlphaRemoved = await waitUntil(
() => getCommunity(alpha, alphaCommunity!.community.id),
g => g.community_view.community.removed,
);
expect(communityOnAlphaRemoved.community_view.community.removed).toBe(true);
@ -144,26 +166,370 @@ test('Remove community', async () => {
let unremoveCommunityRes = await removeCommunity(
beta,
false,
communityRes.community_view.community.id
communityRes.community_view.community.id,
);
expect(unremoveCommunityRes.community_view.community.removed).toBe(false);
// Make sure it got undeleted on A
let communityOnAlphaUnRemoved = await getCommunity(
alpha,
communityOnAlpha.community.id
let communityOnAlphaUnRemoved = await waitUntil(
() => getCommunity(alpha, alphaCommunity!.community.id),
g => !g.community_view.community.removed,
);
expect(communityOnAlphaUnRemoved.community_view.community.removed).toBe(
false
false,
);
});
test('Search for beta community', async () => {
test("Search for beta community", async () => {
let communityRes = await createCommunity(beta);
expect(communityRes.community_view.community.name).toBeDefined();
let searchShort = `!${communityRes.community_view.community.name}@lemmy-beta:8551`;
let search = await searchForCommunity(alpha, searchShort);
let communityOnAlpha = search.communities[0];
assertCommunityFederation(communityOnAlpha, communityRes.community_view);
let alphaCommunity = (await resolveCommunity(alpha, searchShort)).community;
assertCommunityFederation(alphaCommunity, communityRes.community_view);
});
test("Admin actions in remote community are not federated to origin", async () => {
// create a community on alpha
let communityRes = (await createCommunity(alpha)).community_view;
expect(communityRes.community.name).toBeDefined();
// gamma follows community and posts in it
let gammaCommunity = (
await resolveCommunity(gamma, communityRes.community.actor_id)
).community;
if (!gammaCommunity) {
throw "Missing gamma community";
}
await followCommunity(gamma, true, gammaCommunity.community.id);
gammaCommunity = (
await waitUntil(
() => resolveCommunity(gamma, communityRes.community.actor_id),
g => g.community?.subscribed === "Subscribed",
)
).community;
if (!gammaCommunity) {
throw "Missing gamma community";
}
expect(gammaCommunity.subscribed).toBe("Subscribed");
let gammaPost = (await createPost(gamma, gammaCommunity.community.id))
.post_view;
expect(gammaPost.post.id).toBeDefined();
expect(gammaPost.creator_banned_from_community).toBe(false);
// admin of beta decides to ban gamma from community
let betaCommunity = (
await resolveCommunity(beta, communityRes.community.actor_id)
).community;
if (!betaCommunity) {
throw "Missing beta community";
}
let bannedUserInfo1 = (await getSite(gamma)).my_user?.local_user_view.person;
if (!bannedUserInfo1) {
throw "Missing banned user 1";
}
let bannedUserInfo2 = (await resolvePerson(beta, bannedUserInfo1.actor_id))
.person;
if (!bannedUserInfo2) {
throw "Missing banned user 2";
}
let banRes = await banPersonFromCommunity(
beta,
bannedUserInfo2.person.id,
betaCommunity.community.id,
true,
true,
);
expect(banRes.banned).toBe(true);
// ban doesn't federate to community's origin instance alpha
let alphaPost = (await resolvePost(alpha, gammaPost.post)).post;
expect(alphaPost?.creator_banned_from_community).toBe(false);
// and neither to gamma
let gammaPost2 = await getPost(gamma, gammaPost.post.id);
expect(gammaPost2.post_view.creator_banned_from_community).toBe(false);
});
test("moderator view", async () => {
// register a new user with their own community on alpha and post to it
let otherUser = await registerUser(alpha, alphaUrl);
let otherCommunity = (await createCommunity(otherUser)).community_view;
expect(otherCommunity.community.name).toBeDefined();
let otherPost = (await createPost(otherUser, otherCommunity.community.id))
.post_view;
expect(otherPost.post.id).toBeDefined();
let otherComment = (await createComment(otherUser, otherPost.post.id))
.comment_view;
expect(otherComment.comment.id).toBeDefined();
// create a community and post on alpha
let alphaCommunity = (await createCommunity(alpha)).community_view;
expect(alphaCommunity.community.name).toBeDefined();
let alphaPost = (await createPost(alpha, alphaCommunity.community.id))
.post_view;
expect(alphaPost.post.id).toBeDefined();
let alphaComment = (await createComment(otherUser, alphaPost.post.id))
.comment_view;
expect(alphaComment.comment.id).toBeDefined();
// other user also posts on alpha's community
let otherAlphaPost = (
await createPost(otherUser, alphaCommunity.community.id)
).post_view;
expect(otherAlphaPost.post.id).toBeDefined();
let otherAlphaComment = (
await createComment(otherUser, otherAlphaPost.post.id)
).comment_view;
expect(otherAlphaComment.comment.id).toBeDefined();
// alpha lists posts and comments on home page, should contain all posts that were made
let posts = (await getPosts(alpha, "All")).posts;
expect(posts).toBeDefined();
let postIds = posts.map(post => post.post.id);
let comments = (await getComments(alpha, undefined, "All")).comments;
expect(comments).toBeDefined();
let commentIds = comments.map(comment => comment.comment.id);
expect(postIds).toContain(otherPost.post.id);
expect(commentIds).toContain(otherComment.comment.id);
expect(postIds).toContain(alphaPost.post.id);
expect(commentIds).toContain(alphaComment.comment.id);
expect(postIds).toContain(otherAlphaPost.post.id);
expect(commentIds).toContain(otherAlphaComment.comment.id);
// in moderator view, alpha should not see otherPost, wich was posted on a community alpha doesn't moderate
posts = (await getPosts(alpha, "ModeratorView")).posts;
expect(posts).toBeDefined();
postIds = posts.map(post => post.post.id);
comments = (await getComments(alpha, undefined, "ModeratorView")).comments;
expect(comments).toBeDefined();
commentIds = comments.map(comment => comment.comment.id);
expect(postIds).not.toContain(otherPost.post.id);
expect(commentIds).not.toContain(otherComment.comment.id);
expect(postIds).toContain(alphaPost.post.id);
expect(commentIds).toContain(alphaComment.comment.id);
expect(postIds).toContain(otherAlphaPost.post.id);
expect(commentIds).toContain(otherAlphaComment.comment.id);
});
test("Get community for different casing on domain", async () => {
let communityRes = await createCommunity(alpha);
expect(communityRes.community_view.community.name).toBeDefined();
// A dupe check
let prevName = communityRes.community_view.community.name;
await expect(createCommunity(alpha, prevName)).rejects.toStrictEqual(
Error("community_already_exists"),
);
// Cache the community on beta, make sure it has the other fields
let communityName = `${communityRes.community_view.community.name}@LEMMY-ALPHA:8541`;
let betaCommunity = (await getCommunityByName(beta, communityName))
.community_view;
assertCommunityFederation(betaCommunity, communityRes.community_view);
});
test("User blocks instance, communities are hidden", async () => {
// create community and post on beta
let communityRes = await createCommunity(beta);
expect(communityRes.community_view.community.name).toBeDefined();
let postRes = await createPost(
beta,
communityRes.community_view.community.id,
);
expect(postRes.post_view.post.id).toBeDefined();
// fetch post to alpha
let alphaPost = (await resolvePost(alpha, postRes.post_view.post)).post!;
expect(alphaPost.post).toBeDefined();
// post should be included in listing
let listing = await getPosts(alpha, "All");
let listing_ids = listing.posts.map(p => p.post.ap_id);
expect(listing_ids).toContain(postRes.post_view.post.ap_id);
// block the beta instance
await blockInstance(alpha, alphaPost.community.instance_id, true);
// after blocking, post should not be in listing
let listing2 = await getPosts(alpha, "All");
let listing_ids2 = listing2.posts.map(p => p.post.ap_id);
expect(listing_ids2.indexOf(postRes.post_view.post.ap_id)).toBe(-1);
// unblock instance again
await blockInstance(alpha, alphaPost.community.instance_id, false);
// post should be included in listing
let listing3 = await getPosts(alpha, "All");
let listing_ids3 = listing3.posts.map(p => p.post.ap_id);
expect(listing_ids3).toContain(postRes.post_view.post.ap_id);
});
test("Community follower count is federated", async () => {
// Follow the beta community from alpha
let community = await createCommunity(beta);
let communityActorId = community.community_view.community.actor_id;
let resolved = await resolveCommunity(alpha, communityActorId);
if (!resolved.community) {
throw "Missing beta community";
}
await followCommunity(alpha, true, resolved.community.community.id);
let followed = (
await waitUntil(
() => resolveCommunity(alpha, communityActorId),
c => c.community?.subscribed === "Subscribed",
)
).community;
// Make sure there is 1 subscriber
expect(followed?.counts.subscribers).toBe(1);
// Follow the community from gamma
resolved = await resolveCommunity(gamma, communityActorId);
if (!resolved.community) {
throw "Missing beta community";
}
await followCommunity(gamma, true, resolved.community.community.id);
followed = (
await waitUntil(
() => resolveCommunity(gamma, communityActorId),
c => c.community?.subscribed === "Subscribed",
)
).community;
// Make sure there are 2 subscribers
expect(followed?.counts?.subscribers).toBe(2);
// Follow the community from delta
resolved = await resolveCommunity(delta, communityActorId);
if (!resolved.community) {
throw "Missing beta community";
}
await followCommunity(delta, true, resolved.community.community.id);
followed = (
await waitUntil(
() => resolveCommunity(delta, communityActorId),
c => c.community?.subscribed === "Subscribed",
)
).community;
// Make sure there are 3 subscribers
expect(followed?.counts?.subscribers).toBe(3);
});
test("Dont receive community activities after unsubscribe", async () => {
let communityRes = await createCommunity(alpha);
expect(communityRes.community_view.community.name).toBeDefined();
expect(communityRes.community_view.counts.subscribers).toBe(1);
let betaCommunity = (
await resolveCommunity(beta, communityRes.community_view.community.actor_id)
).community;
assertCommunityFederation(betaCommunity, communityRes.community_view);
// follow alpha community from beta
await followCommunity(beta, true, betaCommunity!.community.id);
// ensure that follower count was updated
let communityRes1 = await getCommunity(
alpha,
communityRes.community_view.community.id,
);
expect(communityRes1.community_view.counts.subscribers).toBe(2);
// temporarily block alpha, so that it doesn't know about unfollow
let editSiteForm: EditSite = {};
editSiteForm.allowed_instances = ["lemmy-epsilon"];
await beta.editSite(editSiteForm);
await longDelay();
// unfollow
await followCommunity(beta, false, betaCommunity!.community.id);
// ensure that alpha still sees beta as follower
let communityRes2 = await getCommunity(
alpha,
communityRes.community_view.community.id,
);
expect(communityRes2.community_view.counts.subscribers).toBe(2);
// unblock alpha
editSiteForm.allowed_instances = betaAllowedInstances;
await beta.editSite(editSiteForm);
await longDelay();
// create a post, it shouldnt reach beta
let postRes = await createPost(
alpha,
communityRes.community_view.community.id,
);
expect(postRes.post_view.post.id).toBeDefined();
// await longDelay();
let postResBeta = searchPostLocal(beta, postRes.post_view.post);
expect((await postResBeta).posts.length).toBe(0);
});
test("Fetch community, includes posts", async () => {
let communityRes = await createCommunity(alpha);
expect(communityRes.community_view.community.name).toBeDefined();
expect(communityRes.community_view.counts.subscribers).toBe(1);
let postRes = await createPost(
alpha,
communityRes.community_view.community.id,
);
expect(postRes.post_view.post).toBeDefined();
let resolvedCommunity = await waitUntil(
() =>
resolveCommunity(beta, communityRes.community_view.community.actor_id),
c => c.community?.community.id != undefined,
);
let betaCommunity = resolvedCommunity.community;
expect(betaCommunity?.community.actor_id).toBe(
communityRes.community_view.community.actor_id,
);
await longDelay();
let post_listing = await getPosts(beta, "All", betaCommunity?.community.id);
expect(post_listing.posts.length).toBe(1);
expect(post_listing.posts[0].post.ap_id).toBe(postRes.post_view.post.ap_id);
});
test("Content in local-only community doesn't federate", async () => {
// create a community and set it local-only
let communityRes = (await createCommunity(alpha)).community_view.community;
let form: EditCommunity = {
community_id: communityRes.id,
visibility: "LocalOnly",
};
await editCommunity(alpha, form);
// cant resolve the community from another instance
await expect(
resolveCommunity(beta, communityRes.actor_id),
).rejects.toStrictEqual(Error("couldnt_find_object"));
// create a post, also cant resolve it
let postRes = await createPost(alpha, communityRes.id);
await expect(resolvePost(beta, postRes.post_view.post)).rejects.toStrictEqual(
Error("couldnt_find_object"),
);
});

View File

@ -1,45 +1,98 @@
jest.setTimeout(120000);
import {
alpha,
setupLogins,
searchForBetaCommunity,
resolveBetaCommunity,
followCommunity,
checkFollowedCommunities,
unfollowRemotes,
} from './shared';
getSite,
waitUntil,
beta,
betaUrl,
registerUser,
unfollows,
} from "./shared";
beforeAll(async () => {
await setupLogins();
});
beforeAll(setupLogins);
afterAll(async () => {
await unfollowRemotes(alpha);
});
afterAll(unfollows);
test('Follow federated community', async () => {
let search = await searchForBetaCommunity(alpha); // TODO sometimes this is returning null?
let follow = await followCommunity(
alpha,
true,
search.communities[0].community.id
);
test("Follow local community", async () => {
let user = await registerUser(beta, betaUrl);
let community = (await resolveBetaCommunity(user)).community!;
expect(community.counts.subscribers).toBe(1);
expect(community.counts.subscribers_local).toBe(1);
let follow = await followCommunity(user, true, community.community.id);
// Make sure the follow response went through
expect(follow.community_view.community.local).toBe(false);
expect(follow.community_view.community.name).toBe('main');
expect(follow.community_view.community.local).toBe(true);
expect(follow.community_view.subscribed).toBe("Subscribed");
expect(follow.community_view.counts.subscribers).toBe(2);
expect(follow.community_view.counts.subscribers_local).toBe(2);
// Test an unfollow
let unfollow = await followCommunity(user, false, community.community.id);
expect(unfollow.community_view.subscribed).toBe("NotSubscribed");
expect(unfollow.community_view.counts.subscribers).toBe(1);
expect(unfollow.community_view.counts.subscribers_local).toBe(1);
});
test("Follow federated community", async () => {
// It takes about 1 second for the community aggregates to federate
let betaCommunity = (
await waitUntil(
() => resolveBetaCommunity(alpha),
c =>
c.community?.counts.subscribers === 1 &&
c.community.counts.subscribers_local === 0,
)
).community;
if (!betaCommunity) {
throw "Missing beta community";
}
let follow = await followCommunity(alpha, true, betaCommunity.community.id);
expect(follow.community_view.subscribed).toBe("Pending");
betaCommunity = (
await waitUntil(
() => resolveBetaCommunity(alpha),
c => c.community?.subscribed === "Subscribed",
)
).community;
// Make sure the follow response went through
expect(betaCommunity?.community.local).toBe(false);
expect(betaCommunity?.community.name).toBe("main");
expect(betaCommunity?.subscribed).toBe("Subscribed");
expect(betaCommunity?.counts.subscribers_local).toBe(1);
// check that unfollow was federated
let communityOnBeta1 = await resolveBetaCommunity(beta);
expect(communityOnBeta1.community?.counts.subscribers).toBe(2);
expect(communityOnBeta1.community?.counts.subscribers_local).toBe(1);
// Check it from local
let followCheck = await checkFollowedCommunities(alpha);
let remoteCommunityId = followCheck.communities.find(
c => c.community.local == false
).community.id;
let site = await getSite(alpha);
let remoteCommunityId = site.my_user?.follows.find(
c => c.community.local == false,
)?.community.id;
expect(remoteCommunityId).toBeDefined();
expect(site.my_user?.follows.length).toBe(2);
if (!remoteCommunityId) {
throw "Missing remote community id";
}
// Test an unfollow
let unfollow = await followCommunity(alpha, false, remoteCommunityId);
expect(unfollow.community_view.community.local).toBe(false);
expect(unfollow.community_view.subscribed).toBe("NotSubscribed");
// Make sure you are unsubbed locally
let unfollowCheck = await checkFollowedCommunities(alpha);
expect(unfollowCheck.communities.length).toBeGreaterThanOrEqual(1);
let siteUnfollowCheck = await getSite(alpha);
expect(siteUnfollowCheck.my_user?.follows.length).toBe(1);
// check that unfollow was federated
let communityOnBeta2 = await resolveBetaCommunity(beta);
expect(communityOnBeta2.community?.counts.subscribers).toBe(1);
expect(communityOnBeta2.community?.counts.subscribers_local).toBe(1);
});

363
api_tests/src/image.spec.ts Normal file
View File

@ -0,0 +1,363 @@
jest.setTimeout(120000);
import {
UploadImage,
DeleteImage,
PurgePerson,
PurgePost,
} from "lemmy-js-client";
import {
alpha,
alphaImage,
alphaUrl,
beta,
betaUrl,
createCommunity,
createPost,
deleteAllImages,
epsilon,
followCommunity,
gamma,
getSite,
imageFetchLimit,
registerUser,
resolveBetaCommunity,
resolveCommunity,
resolvePost,
setupLogins,
waitForPost,
unfollows,
getPost,
waitUntil,
createPostWithThumbnail,
sampleImage,
sampleSite,
} from "./shared";
const downloadFileSync = require("download-file-sync");
beforeAll(setupLogins);
afterAll(async () => {
await Promise.all([unfollows(), deleteAllImages(alpha)]);
});
test("Upload image and delete it", async () => {
// Before running this test, you need to delete all previous images in the DB
await deleteAllImages(alpha);
// Upload test image. We use a simple string buffer as pictrs doesn't require an actual image
// in testing mode.
const upload_form: UploadImage = {
image: Buffer.from("test"),
};
const upload = await alphaImage.uploadImage(upload_form);
expect(upload.files![0].file).toBeDefined();
expect(upload.files![0].delete_token).toBeDefined();
expect(upload.url).toBeDefined();
expect(upload.delete_url).toBeDefined();
// ensure that image download is working. theres probably a better way to do this
const content = downloadFileSync(upload.url);
expect(content.length).toBeGreaterThan(0);
// Ensure that it comes back with the list_media endpoint
const listMediaRes = await alphaImage.listMedia();
expect(listMediaRes.images.length).toBe(1);
// Ensure that it also comes back with the admin all images
const listAllMediaRes = await alphaImage.listAllMedia({
limit: imageFetchLimit,
});
// This number comes from all the previous thumbnails fetched in other tests.
const previousThumbnails = 1;
expect(listAllMediaRes.images.length).toBe(previousThumbnails);
// The deleteUrl is a combination of the endpoint, delete token, and alias
let firstImage = listMediaRes.images[0];
let deleteUrl = `${alphaUrl}/pictrs/image/delete/${firstImage.local_image.pictrs_delete_token}/${firstImage.local_image.pictrs_alias}`;
expect(deleteUrl).toBe(upload.delete_url);
// Make sure the uploader is correct
expect(firstImage.person.actor_id).toBe(
`http://lemmy-alpha:8541/u/lemmy_alpha`,
);
// delete image
const delete_form: DeleteImage = {
token: upload.files![0].delete_token,
filename: upload.files![0].file,
};
const delete_ = await alphaImage.deleteImage(delete_form);
expect(delete_).toBe(true);
// ensure that image is deleted
const content2 = downloadFileSync(upload.url);
expect(content2).toBe("");
// Ensure that it shows the image is deleted
const deletedListMediaRes = await alphaImage.listMedia();
expect(deletedListMediaRes.images.length).toBe(0);
// Ensure that the admin shows its deleted
const deletedListAllMediaRes = await alphaImage.listAllMedia({
limit: imageFetchLimit,
});
expect(deletedListAllMediaRes.images.length).toBe(previousThumbnails - 1);
});
test("Purge user, uploaded image removed", async () => {
let user = await registerUser(alphaImage, alphaUrl);
// upload test image
const upload_form: UploadImage = {
image: Buffer.from("test"),
};
const upload = await user.uploadImage(upload_form);
expect(upload.files![0].file).toBeDefined();
expect(upload.files![0].delete_token).toBeDefined();
expect(upload.url).toBeDefined();
expect(upload.delete_url).toBeDefined();
// ensure that image download is working. theres probably a better way to do this
const content = downloadFileSync(upload.url);
expect(content.length).toBeGreaterThan(0);
// purge user
let site = await getSite(user);
const purgeForm: PurgePerson = {
person_id: site.my_user!.local_user_view.person.id,
};
const delete_ = await alphaImage.purgePerson(purgeForm);
expect(delete_.success).toBe(true);
// ensure that image is deleted
const content2 = downloadFileSync(upload.url);
expect(content2).toBe("");
});
test("Purge post, linked image removed", async () => {
let user = await registerUser(beta, betaUrl);
// upload test image
const upload_form: UploadImage = {
image: Buffer.from("test"),
};
const upload = await user.uploadImage(upload_form);
expect(upload.files![0].file).toBeDefined();
expect(upload.files![0].delete_token).toBeDefined();
expect(upload.url).toBeDefined();
expect(upload.delete_url).toBeDefined();
// ensure that image download is working. theres probably a better way to do this
const content = downloadFileSync(upload.url);
expect(content.length).toBeGreaterThan(0);
let community = await resolveBetaCommunity(user);
let post = await createPost(
user,
community.community!.community.id,
upload.url,
);
expect(post.post_view.post.url).toBe(upload.url);
// purge post
const purgeForm: PurgePost = {
post_id: post.post_view.post.id,
};
const delete_ = await beta.purgePost(purgeForm);
expect(delete_.success).toBe(true);
// ensure that image is deleted
const content2 = downloadFileSync(upload.url);
expect(content2).toBe("");
});
test("Images in remote image post are proxied if setting enabled", async () => {
let community = await createCommunity(gamma);
let postRes = await createPost(
gamma,
community.community_view.community.id,
sampleImage,
`![](${sampleImage})`,
);
const post = postRes.post_view.post;
expect(post).toBeDefined();
// remote image gets proxied after upload
expect(
post.thumbnail_url?.startsWith(
"http://lemmy-gamma:8561/api/v3/image_proxy?url",
),
).toBeTruthy();
expect(
post.body?.startsWith("![](http://lemmy-gamma:8561/api/v3/image_proxy?url"),
).toBeTruthy();
// Make sure that it ends with jpg, to be sure its an image
expect(post.thumbnail_url?.endsWith(".jpg")).toBeTruthy();
let epsilonPostRes = await resolvePost(epsilon, postRes.post_view.post);
expect(epsilonPostRes.post).toBeDefined();
// Fetch the post again, the metadata should be backgrounded now
// Wait for the metadata to get fetched, since this is backgrounded now
let epsilonPostRes2 = await waitUntil(
() => getPost(epsilon, epsilonPostRes.post!.post.id),
p => p.post_view.post.thumbnail_url != undefined,
);
const epsilonPost = epsilonPostRes2.post_view.post;
expect(
epsilonPost.thumbnail_url?.startsWith(
"http://lemmy-epsilon:8581/api/v3/image_proxy?url",
),
).toBeTruthy();
expect(
epsilonPost.body?.startsWith(
"![](http://lemmy-epsilon:8581/api/v3/image_proxy?url",
),
).toBeTruthy();
// Make sure that it ends with jpg, to be sure its an image
expect(epsilonPost.thumbnail_url?.endsWith(".jpg")).toBeTruthy();
});
test("Thumbnail of remote image link is proxied if setting enabled", async () => {
let community = await createCommunity(gamma);
let postRes = await createPost(
gamma,
community.community_view.community.id,
// The sample site metadata thumbnail ends in png
sampleSite,
);
const post = postRes.post_view.post;
expect(post).toBeDefined();
// remote image gets proxied after upload
expect(
post.thumbnail_url?.startsWith(
"http://lemmy-gamma:8561/api/v3/image_proxy?url",
),
).toBeTruthy();
// Make sure that it ends with png, to be sure its an image
expect(post.thumbnail_url?.endsWith(".png")).toBeTruthy();
let epsilonPostRes = await resolvePost(epsilon, postRes.post_view.post);
expect(epsilonPostRes.post).toBeDefined();
let epsilonPostRes2 = await waitUntil(
() => getPost(epsilon, epsilonPostRes.post!.post.id),
p => p.post_view.post.thumbnail_url != undefined,
);
const epsilonPost = epsilonPostRes2.post_view.post;
expect(
epsilonPost.thumbnail_url?.startsWith(
"http://lemmy-epsilon:8581/api/v3/image_proxy?url",
),
).toBeTruthy();
// Make sure that it ends with png, to be sure its an image
expect(epsilonPost.thumbnail_url?.endsWith(".png")).toBeTruthy();
});
test("No image proxying if setting is disabled", async () => {
let user = await registerUser(beta, betaUrl);
let community = await createCommunity(alpha);
let betaCommunity = await resolveCommunity(
beta,
community.community_view.community.actor_id,
);
await followCommunity(beta, true, betaCommunity.community!.community.id);
const upload_form: UploadImage = {
image: Buffer.from("test"),
};
const upload = await user.uploadImage(upload_form);
let post = await createPost(
alpha,
community.community_view.community.id,
upload.url,
`![](${sampleImage})`,
);
expect(post.post_view.post).toBeDefined();
// remote image doesn't get proxied after upload
expect(
post.post_view.post.url?.startsWith("http://127.0.0.1:8551/pictrs/image/"),
).toBeTruthy();
expect(post.post_view.post.body).toBe(`![](${sampleImage})`);
let betaPost = await waitForPost(
beta,
post.post_view.post,
res => res?.post.alt_text != null,
);
expect(betaPost.post).toBeDefined();
// remote image doesn't get proxied after federation
expect(
betaPost.post.url?.startsWith("http://127.0.0.1:8551/pictrs/image/"),
).toBeTruthy();
expect(betaPost.post.body).toBe(`![](${sampleImage})`);
// Make sure the alt text got federated
expect(post.post_view.post.alt_text).toBe(betaPost.post.alt_text);
});
test("Make regular post, and give it a custom thumbnail", async () => {
const uploadForm1: UploadImage = {
image: Buffer.from("testRegular1"),
};
const upload1 = await alphaImage.uploadImage(uploadForm1);
const community = await createCommunity(alphaImage);
// Use wikipedia since it has an opengraph image
const wikipediaUrl = "https://wikipedia.org/";
let post = await createPostWithThumbnail(
alphaImage,
community.community_view.community.id,
wikipediaUrl,
upload1.url!,
);
// Wait for the metadata to get fetched, since this is backgrounded now
post = await waitUntil(
() => getPost(alphaImage, post.post_view.post.id),
p => p.post_view.post.thumbnail_url != undefined,
);
expect(post.post_view.post.url).toBe(wikipediaUrl);
// Make sure it uses custom thumbnail
expect(post.post_view.post.thumbnail_url).toBe(upload1.url);
});
test("Create an image post, and make sure a custom thumbnail doesn't overwrite it", async () => {
const uploadForm1: UploadImage = {
image: Buffer.from("test1"),
};
const upload1 = await alphaImage.uploadImage(uploadForm1);
const uploadForm2: UploadImage = {
image: Buffer.from("test2"),
};
const upload2 = await alphaImage.uploadImage(uploadForm2);
const community = await createCommunity(alphaImage);
let post = await createPostWithThumbnail(
alphaImage,
community.community_view.community.id,
upload1.url!,
upload2.url!,
);
post = await waitUntil(
() => getPost(alphaImage, post.post_view.post.id),
p => p.post_view.post.thumbnail_url != undefined,
);
expect(post.post_view.post.url).toBe(upload1.url);
// Make sure the custom thumbnail is ignored
expect(post.post_view.post.thumbnail_url == upload2.url).toBe(false);
});

View File

@ -1,4 +1,6 @@
jest.setTimeout(120000);
import { CommunityView } from "lemmy-js-client/dist/types/CommunityView";
import {
alpha,
beta,
@ -8,92 +10,139 @@ import {
setupLogins,
createPost,
editPost,
stickyPost,
featurePost,
lockPost,
searchPost,
resolvePost,
likePost,
followBeta,
searchForBetaCommunity,
resolveBetaCommunity,
createComment,
deletePost,
delay,
removePost,
getPost,
unfollowRemotes,
searchForUser,
banUserFromSite,
searchPostLocal,
banUserFromCommunity,
} from './shared';
import { PostView, CommunityView } from 'lemmy-js-client';
resolvePerson,
banPersonFromSite,
followCommunity,
banPersonFromCommunity,
reportPost,
listPostReports,
randomString,
registerUser,
getSite,
unfollows,
resolveCommunity,
waitUntil,
waitForPost,
alphaUrl,
loginUser,
createCommunity,
} from "./shared";
import { PostView } from "lemmy-js-client/dist/types/PostView";
import { EditSite, ResolveObject } from "lemmy-js-client";
let betaCommunity: CommunityView;
let betaCommunity: CommunityView | undefined;
beforeAll(async () => {
await setupLogins();
let search = await searchForBetaCommunity(alpha);
betaCommunity = search.communities[0];
await unfollows();
betaCommunity = (await resolveBetaCommunity(alpha)).community;
expect(betaCommunity).toBeDefined();
});
afterAll(async () => {
await unfollows();
});
afterAll(unfollows);
async function unfollows() {
await unfollowRemotes(alpha);
await unfollowRemotes(gamma);
await unfollowRemotes(delta);
await unfollowRemotes(epsilon);
async function assertPostFederation(postOne: PostView, postTwo: PostView) {
// Link metadata is generated in background task and may not be ready yet at this time,
// so wait for it explicitly. For removed posts we cant refetch anything.
postOne = await waitForPost(beta, postOne.post, res => {
return res === null || res?.post.embed_title !== null;
});
postTwo = await waitForPost(
beta,
postTwo.post,
res => res === null || res?.post.embed_title !== null,
);
expect(postOne?.post.ap_id).toBe(postTwo?.post.ap_id);
expect(postOne?.post.name).toBe(postTwo?.post.name);
expect(postOne?.post.body).toBe(postTwo?.post.body);
// TODO url clears arent working
// expect(postOne?.post.url).toBe(postTwo?.post.url);
expect(postOne?.post.nsfw).toBe(postTwo?.post.nsfw);
expect(postOne?.post.embed_title).toBe(postTwo?.post.embed_title);
expect(postOne?.post.embed_description).toBe(postTwo?.post.embed_description);
expect(postOne?.post.embed_video_url).toBe(postTwo?.post.embed_video_url);
expect(postOne?.post.published).toBe(postTwo?.post.published);
expect(postOne?.community.actor_id).toBe(postTwo?.community.actor_id);
expect(postOne?.post.locked).toBe(postTwo?.post.locked);
expect(postOne?.post.removed).toBe(postTwo?.post.removed);
expect(postOne?.post.deleted).toBe(postTwo?.post.deleted);
}
function assertPostFederation(postOne: PostView, postTwo: PostView) {
expect(postOne.post.ap_id).toBe(postTwo.post.ap_id);
expect(postOne.post.name).toBe(postTwo.post.name);
expect(postOne.post.body).toBe(postTwo.post.body);
expect(postOne.post.url).toBe(postTwo.post.url);
expect(postOne.post.nsfw).toBe(postTwo.post.nsfw);
expect(postOne.post.embed_title).toBe(postTwo.post.embed_title);
expect(postOne.post.embed_description).toBe(postTwo.post.embed_description);
expect(postOne.post.embed_html).toBe(postTwo.post.embed_html);
expect(postOne.post.published).toBe(postTwo.post.published);
expect(postOne.community.actor_id).toBe(postTwo.community.actor_id);
expect(postOne.post.locked).toBe(postTwo.post.locked);
expect(postOne.post.removed).toBe(postTwo.post.removed);
expect(postOne.post.deleted).toBe(postTwo.post.deleted);
}
test("Create a post", async () => {
// Setup some allowlists and blocklists
const editSiteForm: EditSite = {};
test('Create a post', async () => {
let postRes = await createPost(alpha, betaCommunity.community.id);
editSiteForm.allowed_instances = [];
editSiteForm.blocked_instances = ["lemmy-alpha"];
await epsilon.editSite(editSiteForm);
if (!betaCommunity) {
throw "Missing beta community";
}
let postRes = await createPost(
alpha,
betaCommunity.community.id,
"https://example.com/",
"აშშ ითხოვს ირანს დაუყოვნებლივ გაანთავისუფლოს დაკავებული ნავთობის ტანკერი",
);
expect(postRes.post_view.post).toBeDefined();
expect(postRes.post_view.community.local).toBe(false);
expect(postRes.post_view.creator.local).toBe(true);
expect(postRes.post_view.counts.score).toBe(1);
// Make sure that post is liked on beta
let searchBeta = await searchPost(beta, postRes.post_view.post);
let betaPost = searchBeta.posts[0];
const betaPost = await waitForPost(
beta,
postRes.post_view.post,
res => res?.counts.score === 1,
);
expect(betaPost).toBeDefined();
expect(betaPost.community.local).toBe(true);
expect(betaPost.creator.local).toBe(false);
expect(betaPost.counts.score).toBe(1);
assertPostFederation(betaPost, postRes.post_view);
expect(betaPost?.community.local).toBe(true);
expect(betaPost?.creator.local).toBe(false);
expect(betaPost?.counts.score).toBe(1);
await assertPostFederation(betaPost, postRes.post_view);
// Delta only follows beta, so it should not see an alpha ap_id
let searchDelta = await searchPost(delta, postRes.post_view.post);
expect(searchDelta.posts[0]).toBeUndefined();
await expect(
resolvePost(delta, postRes.post_view.post),
).rejects.toStrictEqual(Error("couldnt_find_object"));
// Epsilon has alpha blocked, it should not see the alpha post
let searchEpsilon = await searchPost(epsilon, postRes.post_view.post);
expect(searchEpsilon.posts[0]).toBeUndefined();
await expect(
resolvePost(epsilon, postRes.post_view.post),
).rejects.toStrictEqual(Error("couldnt_find_object"));
// remove added allow/blocklists
editSiteForm.allowed_instances = [];
editSiteForm.blocked_instances = [];
await delta.editSite(editSiteForm);
await epsilon.editSite(editSiteForm);
});
test('Create a post in a non-existent community', async () => {
let postRes = await createPost(alpha, -2);
expect(postRes).toStrictEqual({ error: 'couldnt_create_post' });
test("Create a post in a non-existent community", async () => {
await expect(createPost(alpha, -2)).rejects.toStrictEqual(
Error("couldnt_find_community"),
);
});
test('Unlike a post', async () => {
test("Unlike a post", async () => {
if (!betaCommunity) {
throw "Missing beta community";
}
let postRes = await createPost(alpha, betaCommunity.community.id);
let unlike = await likePost(alpha, 0, postRes.post_view.post);
expect(unlike.post_view.counts.score).toBe(0);
@ -103,257 +152,630 @@ test('Unlike a post', async () => {
expect(unlike2.post_view.counts.score).toBe(0);
// Make sure that post is unliked on beta
let searchBeta = await searchPost(beta, postRes.post_view.post);
let betaPost = searchBeta.posts[0];
const betaPost = await waitForPost(
beta,
postRes.post_view.post,
post => post?.counts.score === 0,
);
expect(betaPost).toBeDefined();
expect(betaPost.community.local).toBe(true);
expect(betaPost.creator.local).toBe(false);
expect(betaPost.counts.score).toBe(0);
assertPostFederation(betaPost, postRes.post_view);
expect(betaPost?.community.local).toBe(true);
expect(betaPost?.creator.local).toBe(false);
expect(betaPost?.counts.score).toBe(0);
await assertPostFederation(betaPost, postRes.post_view);
});
test('Update a post', async () => {
test("Update a post", async () => {
if (!betaCommunity) {
throw "Missing beta community";
}
let postRes = await createPost(alpha, betaCommunity.community.id);
await waitForPost(beta, postRes.post_view.post);
let updatedName = 'A jest test federated post, updated';
let updatedName = "A jest test federated post, updated";
let updatedPost = await editPost(alpha, postRes.post_view.post);
expect(updatedPost.post_view.post.name).toBe(updatedName);
expect(updatedPost.post_view.community.local).toBe(false);
expect(updatedPost.post_view.creator.local).toBe(true);
// Make sure that post is updated on beta
let searchBeta = await searchPost(beta, postRes.post_view.post);
let betaPost = searchBeta.posts[0];
let betaPost = await waitForPost(beta, updatedPost.post_view.post);
expect(betaPost.community.local).toBe(true);
expect(betaPost.creator.local).toBe(false);
expect(betaPost.post.name).toBe(updatedName);
assertPostFederation(betaPost, updatedPost.post_view);
await assertPostFederation(betaPost, updatedPost.post_view);
// Make sure lemmy beta cannot update the post
let updatedPostBeta = await editPost(beta, betaPost.post);
expect(updatedPostBeta).toStrictEqual({ error: 'no_post_edit_allowed' });
await expect(editPost(beta, betaPost.post)).rejects.toStrictEqual(
Error("no_post_edit_allowed"),
);
});
test('Sticky a post', async () => {
test("Sticky a post", async () => {
if (!betaCommunity) {
throw "Missing beta community";
}
let postRes = await createPost(alpha, betaCommunity.community.id);
let stickiedPostRes = await stickyPost(alpha, true, postRes.post_view.post);
expect(stickiedPostRes.post_view.post.stickied).toBe(true);
let betaPost1 = await waitForPost(beta, postRes.post_view.post);
if (!betaPost1) {
throw "Missing beta post1";
}
let stickiedPostRes = await featurePost(beta, true, betaPost1.post);
expect(stickiedPostRes.post_view.post.featured_community).toBe(true);
// Make sure that post is stickied on beta
let searchBeta = await searchPost(beta, postRes.post_view.post);
let betaPost = searchBeta.posts[0];
expect(betaPost.community.local).toBe(true);
expect(betaPost.creator.local).toBe(false);
expect(betaPost.post.stickied).toBe(true);
let betaPost = (await resolvePost(beta, postRes.post_view.post)).post;
expect(betaPost?.community.local).toBe(true);
expect(betaPost?.creator.local).toBe(false);
expect(betaPost?.post.featured_community).toBe(true);
// Unsticky a post
let unstickiedPost = await stickyPost(alpha, false, postRes.post_view.post);
expect(unstickiedPost.post_view.post.stickied).toBe(false);
let unstickiedPost = await featurePost(beta, false, betaPost1.post);
expect(unstickiedPost.post_view.post.featured_community).toBe(false);
// Make sure that post is unstickied on beta
let searchBeta2 = await searchPost(beta, postRes.post_view.post);
let betaPost2 = searchBeta2.posts[0];
expect(betaPost2.community.local).toBe(true);
expect(betaPost2.creator.local).toBe(false);
expect(betaPost2.post.stickied).toBe(false);
let betaPost2 = (await resolvePost(beta, postRes.post_view.post)).post;
expect(betaPost2?.community.local).toBe(true);
expect(betaPost2?.creator.local).toBe(false);
expect(betaPost2?.post.featured_community).toBe(false);
// Make sure that gamma cannot sticky the post on beta
let searchGamma = await searchPost(gamma, postRes.post_view.post);
let gammaPost = searchGamma.posts[0];
let gammaTrySticky = await stickyPost(gamma, true, gammaPost.post);
let searchBeta3 = await searchPost(beta, postRes.post_view.post);
let betaPost3 = searchBeta3.posts[0];
expect(gammaTrySticky.post_view.post.stickied).toBe(true);
expect(betaPost3.post.stickied).toBe(false);
let gammaPost = (await resolvePost(gamma, postRes.post_view.post)).post;
if (!gammaPost) {
throw "Missing gamma post";
}
// This has been failing occasionally
await featurePost(gamma, true, gammaPost.post);
let betaPost3 = (await resolvePost(beta, postRes.post_view.post)).post;
// expect(gammaTrySticky.post_view.post.featured_community).toBe(true);
expect(betaPost3?.post.featured_community).toBe(false);
});
test('Lock a post', async () => {
let postRes = await createPost(alpha, betaCommunity.community.id);
test("Collection of featured posts gets federated", async () => {
// create a new community and feature a post
let community = await createCommunity(alpha);
let post = await createPost(alpha, community.community_view.community.id);
let featuredPost = await featurePost(alpha, true, post.post_view.post);
expect(featuredPost.post_view.post.featured_community).toBe(true);
// fetch the community, ensure that post is also fetched and marked as featured
let betaCommunity = await resolveCommunity(
beta,
community.community_view.community.actor_id,
);
expect(betaCommunity).toBeDefined();
const betaPost = await waitForPost(
beta,
post.post_view.post,
post => post?.post.featured_community === true,
);
expect(betaPost).toBeDefined();
});
test("Lock a post", async () => {
if (!betaCommunity) {
throw "Missing beta community";
}
await followCommunity(alpha, true, betaCommunity.community.id);
await waitUntil(
() => resolveBetaCommunity(alpha),
c => c.community?.subscribed === "Subscribed",
);
let postRes = await createPost(alpha, betaCommunity.community.id);
let betaPost1 = await waitForPost(beta, postRes.post_view.post);
// Lock the post
let lockedPostRes = await lockPost(alpha, true, postRes.post_view.post);
let lockedPostRes = await lockPost(beta, true, betaPost1.post);
expect(lockedPostRes.post_view.post.locked).toBe(true);
// Make sure that post is locked on beta
let searchBeta = await searchPostLocal(beta, postRes.post_view.post);
let betaPost1 = searchBeta.posts[0];
expect(betaPost1.post.locked).toBe(true);
// Make sure that post is locked on alpha
let alphaPost1 = await waitForPost(
alpha,
postRes.post_view.post,
post => !!post && post.post.locked,
);
// Try to make a new comment there, on alpha
let comment: any = await createComment(alpha, postRes.post_view.post.id);
expect(comment['error']).toBe('locked');
// Try to make a new comment there, on alpha. For this we need to create a normal
// user account because admins/mods can comment in locked posts.
let user = await registerUser(alpha, alphaUrl);
await expect(createComment(user, alphaPost1.post.id)).rejects.toStrictEqual(
Error("locked"),
);
// Unlock a post
let unlockedPost = await lockPost(alpha, false, postRes.post_view.post);
let unlockedPost = await lockPost(beta, false, betaPost1.post);
expect(unlockedPost.post_view.post.locked).toBe(false);
// Make sure that post is unlocked on beta
let searchBeta2 = await searchPost(beta, postRes.post_view.post);
let betaPost2 = searchBeta2.posts[0];
expect(betaPost2.community.local).toBe(true);
expect(betaPost2.creator.local).toBe(false);
expect(betaPost2.post.locked).toBe(false);
// Make sure that post is unlocked on alpha
let alphaPost2 = await waitForPost(
alpha,
postRes.post_view.post,
post => !!post && !post.post.locked,
);
expect(alphaPost2.community.local).toBe(false);
expect(alphaPost2.creator.local).toBe(true);
expect(alphaPost2.post.locked).toBe(false);
// Try to create a new comment, on beta
let commentBeta = await createComment(beta, betaPost2.post.id);
expect(commentBeta).toBeDefined();
// Try to create a new comment, on alpha
let commentAlpha = await createComment(user, alphaPost1.post.id);
expect(commentAlpha).toBeDefined();
});
test('Delete a post', async () => {
test("Delete a post", async () => {
if (!betaCommunity) {
throw "Missing beta community";
}
let postRes = await createPost(alpha, betaCommunity.community.id);
expect(postRes.post_view.post).toBeDefined();
await waitForPost(beta, postRes.post_view.post);
let deletedPost = await deletePost(alpha, true, postRes.post_view.post);
expect(deletedPost.post_view.post.deleted).toBe(true);
expect(deletedPost.post_view.post.name).toBe(postRes.post_view.post.name);
// Make sure lemmy beta sees post is deleted
let searchBeta = await searchPost(beta, postRes.post_view.post);
let betaPost = searchBeta.posts[0];
// This will be undefined because of the tombstone
expect(betaPost).toBeUndefined();
await waitForPost(beta, postRes.post_view.post, p => !p || p.post.deleted);
// Undelete
let undeletedPost = await deletePost(alpha, false, postRes.post_view.post);
expect(undeletedPost.post_view.post.deleted).toBe(false);
// Make sure lemmy beta sees post is undeleted
let searchBeta2 = await searchPost(beta, postRes.post_view.post);
let betaPost2 = searchBeta2.posts[0];
let betaPost2 = await waitForPost(
beta,
postRes.post_view.post,
p => !!p && !p.post.deleted,
);
if (!betaPost2) {
throw "Missing beta post 2";
}
expect(betaPost2.post.deleted).toBe(false);
assertPostFederation(betaPost2, undeletedPost.post_view);
await assertPostFederation(betaPost2, undeletedPost.post_view);
// Make sure lemmy beta cannot delete the post
let deletedPostBeta = await deletePost(beta, true, betaPost2.post);
expect(deletedPostBeta).toStrictEqual({ error: 'no_post_edit_allowed' });
await expect(deletePost(beta, true, betaPost2.post)).rejects.toStrictEqual(
Error("no_post_edit_allowed"),
);
});
test('Remove a post from admin and community on different instance', async () => {
let postRes = await createPost(alpha, betaCommunity.community.id);
test("Remove a post from admin and community on different instance", async () => {
if (!betaCommunity) {
throw "Missing beta community";
}
let removedPost = await removePost(alpha, true, postRes.post_view.post);
let gammaCommunity = (
await resolveCommunity(gamma, betaCommunity.community.actor_id)
).community?.community;
if (!gammaCommunity) {
throw "Missing gamma community";
}
let postRes = await createPost(gamma, gammaCommunity.id);
let alphaPost = (await resolvePost(alpha, postRes.post_view.post)).post;
if (!alphaPost) {
throw "Missing alpha post";
}
let removedPost = await removePost(alpha, true, alphaPost.post);
expect(removedPost.post_view.post.removed).toBe(true);
expect(removedPost.post_view.post.name).toBe(postRes.post_view.post.name);
// Make sure lemmy beta sees post is NOT removed
let searchBeta = await searchPost(beta, postRes.post_view.post);
let betaPost = searchBeta.posts[0];
let betaPost = (await resolvePost(beta, postRes.post_view.post)).post;
if (!betaPost) {
throw "Missing beta post";
}
expect(betaPost.post.removed).toBe(false);
// Undelete
let undeletedPost = await removePost(alpha, false, postRes.post_view.post);
let undeletedPost = await removePost(alpha, false, alphaPost.post);
expect(undeletedPost.post_view.post.removed).toBe(false);
// Make sure lemmy beta sees post is undeleted
let searchBeta2 = await searchPost(beta, postRes.post_view.post);
let betaPost2 = searchBeta2.posts[0];
expect(betaPost2.post.removed).toBe(false);
assertPostFederation(betaPost2, undeletedPost.post_view);
let betaPost2 = (await resolvePost(beta, postRes.post_view.post)).post;
expect(betaPost2?.post.removed).toBe(false);
await assertPostFederation(betaPost2!, undeletedPost.post_view);
});
test('Remove a post from admin and community on same instance', async () => {
test("Remove a post from admin and community on same instance", async () => {
if (!betaCommunity) {
throw "Missing beta community";
}
await followBeta(alpha);
let postRes = await createPost(alpha, betaCommunity.community.id);
let gammaCommunity = await resolveCommunity(
gamma,
betaCommunity.community.actor_id,
);
let postRes = await createPost(gamma, gammaCommunity.community!.community.id);
expect(postRes.post_view.post).toBeDefined();
// Get the id for beta
let searchBeta = await searchPostLocal(beta, postRes.post_view.post);
let betaPost = searchBeta.posts[0];
let betaPost = await waitForPost(beta, postRes.post_view.post);
expect(betaPost).toBeDefined();
let alphaPost0 = await waitForPost(alpha, postRes.post_view.post);
expect(alphaPost0).toBeDefined();
// The beta admin removes it (the community lives on beta)
let removePostRes = await removePost(beta, true, betaPost.post);
expect(removePostRes.post_view.post.removed).toBe(true);
// Make sure lemmy alpha sees post is removed
let alphaPost = await getPost(alpha, postRes.post_view.post.id);
// expect(alphaPost.post_view.post.removed).toBe(true); // TODO this shouldn't be commented
// assertPostFederation(alphaPost.post_view, removePostRes.post_view);
let alphaPost = await waitUntil(
() => getPost(alpha, alphaPost0.post.id),
p => p?.post_view.post.removed ?? false,
);
expect(alphaPost?.post_view.post.removed).toBe(true);
await assertPostFederation(alphaPost.post_view, removePostRes.post_view);
// Undelete
let undeletedPost = await removePost(beta, false, betaPost.post);
expect(undeletedPost.post_view.post.removed).toBe(false);
// Make sure lemmy alpha sees post is undeleted
let alphaPost2 = await getPost(alpha, postRes.post_view.post.id);
expect(alphaPost2.post_view.post.removed).toBe(false);
assertPostFederation(alphaPost2.post_view, undeletedPost.post_view);
let alphaPost2 = await waitForPost(
alpha,
postRes.post_view.post,
p => !!p && !p.post.removed,
);
expect(alphaPost2.post.removed).toBe(false);
await assertPostFederation(alphaPost2, undeletedPost.post_view);
await unfollowRemotes(alpha);
});
test('Search for a post', async () => {
test("Search for a post", async () => {
if (!betaCommunity) {
throw "Missing beta community";
}
await unfollowRemotes(alpha);
let postRes = await createPost(alpha, betaCommunity.community.id);
expect(postRes.post_view.post).toBeDefined();
let searchBeta = await searchPost(beta, postRes.post_view.post);
expect(searchBeta.posts[0].post.name).toBeDefined();
let betaPost = await waitForPost(beta, postRes.post_view.post);
expect(betaPost?.post.name).toBeDefined();
});
test('A and G subscribe to B (center) A posts, it gets announced to G', async () => {
let postRes = await createPost(alpha, betaCommunity.community.id);
expect(postRes.post_view.post).toBeDefined();
test("Enforce site ban federation for local user", async () => {
if (!betaCommunity) {
throw "Missing beta community";
}
let search2 = await searchPost(gamma, postRes.post_view.post);
expect(search2.posts[0].post.name).toBeDefined();
});
// create a test user
let alphaUserHttp = await registerUser(alpha, alphaUrl);
let alphaUserPerson = (await getSite(alphaUserHttp)).my_user?.local_user_view
.person;
let alphaUserActorId = alphaUserPerson?.actor_id;
if (!alphaUserActorId) {
throw "Missing alpha user actor id";
}
expect(alphaUserActorId).toBeDefined();
await followBeta(alphaUserHttp);
test('Enforce site ban for federated user', async () => {
let alphaShortname = `@lemmy_alpha@lemmy-alpha:8541`;
let userSearch = await searchForUser(beta, alphaShortname);
let alphaUser = userSearch.users[0];
expect(alphaUser).toBeDefined();
let alphaPerson = (await resolvePerson(alphaUserHttp, alphaUserActorId!))
.person;
if (!alphaPerson) {
throw "Missing alpha person";
}
expect(alphaPerson).toBeDefined();
// ban alpha from beta site
let banAlpha = await banUserFromSite(beta, alphaUser.user.id, true);
// alpha makes post in beta community, it federates to beta instance
let postRes1 = await createPost(alphaUserHttp, betaCommunity.community.id);
let searchBeta1 = await waitForPost(beta, postRes1.post_view.post);
// ban alpha from its own instance
let banAlpha = await banPersonFromSite(
alpha,
alphaPerson.person.id,
true,
true,
);
expect(banAlpha.banned).toBe(true);
// Alpha makes post on beta
let postRes = await createPost(alpha, betaCommunity.community.id);
expect(postRes.post_view.post).toBeDefined();
expect(postRes.post_view.community.local).toBe(false);
expect(postRes.post_view.creator.local).toBe(true);
expect(postRes.post_view.counts.score).toBe(1);
// alpha ban should be federated to beta
let alphaUserOnBeta1 = await waitUntil(
() => resolvePerson(beta, alphaUserActorId!),
res => res.person?.person.banned ?? false,
);
expect(alphaUserOnBeta1.person?.person.banned).toBe(true);
// Make sure that post doesn't make it to beta
let searchBeta = await searchPostLocal(beta, postRes.post_view.post);
let betaPost = searchBeta.posts[0];
expect(betaPost).toBeUndefined();
// existing alpha post should be removed on beta
let betaBanRes = await waitUntil(
() => getPost(beta, searchBeta1.post.id),
s => s.post_view.post.removed,
);
expect(betaBanRes.post_view.post.removed).toBe(true);
// Unban alpha
let unBanAlpha = await banUserFromSite(beta, alphaUser.user.id, false);
expect(unBanAlpha.banned).toBe(false);
});
test('Enforce community ban for federated user', async () => {
let alphaShortname = `@lemmy_alpha@lemmy-alpha:8541`;
let userSearch = await searchForUser(beta, alphaShortname);
let alphaUser = userSearch.users[0];
expect(alphaUser).toBeDefined();
// ban alpha from beta site
await banUserFromCommunity(beta, alphaUser.user.id, 2, false);
let banAlpha = await banUserFromCommunity(beta, alphaUser.user.id, 2, true);
expect(banAlpha.banned).toBe(true);
// Alpha makes post on beta
let postRes = await createPost(alpha, betaCommunity.community.id);
expect(postRes.post_view.post).toBeDefined();
expect(postRes.post_view.community.local).toBe(false);
expect(postRes.post_view.creator.local).toBe(true);
expect(postRes.post_view.counts.score).toBe(1);
// Make sure that post doesn't make it to beta community
let searchBeta = await searchPostLocal(beta, postRes.post_view.post);
let betaPost = searchBeta.posts[0];
expect(betaPost).toBeUndefined();
// Unban alpha
let unBanAlpha = await banUserFromCommunity(
beta,
alphaUser.user.id,
2,
false
let unBanAlpha = await banPersonFromSite(
alpha,
alphaPerson.person.id,
false,
false,
);
expect(unBanAlpha.banned).toBe(false);
// Login gets invalidated by ban, need to login again
if (!alphaUserPerson) {
throw "Missing alpha person";
}
let newAlphaUserJwt = await loginUser(alpha, alphaUserPerson.name);
alphaUserHttp.setHeaders({
Authorization: "Bearer " + newAlphaUserJwt.jwt ?? "",
});
// alpha makes new post in beta community, it federates
let postRes2 = await createPost(alphaUserHttp, betaCommunity!.community.id);
await waitForPost(beta, postRes2.post_view.post);
await unfollowRemotes(alpha);
});
test("Enforce site ban federation for federated user", async () => {
if (!betaCommunity) {
throw "Missing beta community";
}
// create a test user
let alphaUserHttp = await registerUser(alpha, alphaUrl);
let alphaUserPerson = (await getSite(alphaUserHttp)).my_user?.local_user_view
.person;
let alphaUserActorId = alphaUserPerson?.actor_id;
if (!alphaUserActorId) {
throw "Missing alpha user actor id";
}
expect(alphaUserActorId).toBeDefined();
await followBeta(alphaUserHttp);
let alphaUserOnBeta2 = await resolvePerson(beta, alphaUserActorId!);
expect(alphaUserOnBeta2.person?.person.banned).toBe(false);
if (!alphaUserOnBeta2.person) {
throw "Missing alpha person";
}
// alpha makes post in beta community, it federates to beta instance
let postRes1 = await createPost(alphaUserHttp, betaCommunity.community.id);
let searchBeta1 = await waitForPost(beta, postRes1.post_view.post);
expect(searchBeta1.post).toBeDefined();
// Now ban and remove their data from beta
let banAlphaOnBeta = await banPersonFromSite(
beta,
alphaUserOnBeta2.person.person.id,
true,
true,
);
expect(banAlphaOnBeta.banned).toBe(true);
// The beta site ban should NOT be federated to alpha
let alphaPerson2 = (await getSite(alphaUserHttp)).my_user!.local_user_view
.person;
expect(alphaPerson2.banned).toBe(false);
// existing alpha post should be removed on beta
let betaBanRes = await waitUntil(
() => getPost(beta, searchBeta1.post.id),
s => s.post_view.post.removed,
);
expect(betaBanRes.post_view.post.removed).toBe(true);
// existing alpha's post to the beta community should be removed on alpha
let alphaPostAfterRemoveOnBeta = await waitUntil(
() => getPost(alpha, postRes1.post_view.post.id),
s => s.post_view.post.removed,
);
expect(betaBanRes.post_view.post.removed).toBe(true);
expect(alphaPostAfterRemoveOnBeta.post_view.post.removed).toBe(true);
expect(
alphaPostAfterRemoveOnBeta.post_view.creator_banned_from_community,
).toBe(true);
await unfollowRemotes(alpha);
});
test("Enforce community ban for federated user", async () => {
if (!betaCommunity) {
throw "Missing beta community";
}
await followBeta(alpha);
let alphaShortname = `@lemmy_alpha@lemmy-alpha:8541`;
let alphaPerson = (await resolvePerson(beta, alphaShortname)).person;
if (!alphaPerson) {
throw "Missing alpha person";
}
expect(alphaPerson).toBeDefined();
// make a post in beta, it goes through
let postRes1 = await createPost(alpha, betaCommunity.community.id);
let searchBeta1 = await waitForPost(beta, postRes1.post_view.post);
expect(searchBeta1.post).toBeDefined();
// ban alpha from beta community
let banAlpha = await banPersonFromCommunity(
beta,
alphaPerson.person.id,
searchBeta1.community.id,
true,
true,
);
expect(banAlpha.banned).toBe(true);
// ensure that the post by alpha got removed
let removePostRes = await waitUntil(
() => getPost(alpha, postRes1.post_view.post.id),
s => s.post_view.post.removed,
);
expect(removePostRes.post_view.post.removed).toBe(true);
expect(removePostRes.post_view.creator_banned_from_community).toBe(true);
expect(removePostRes.community_view.banned_from_community).toBe(true);
// Alpha tries to make post on beta, but it fails because of ban
await expect(
createPost(alpha, betaCommunity.community.id),
).rejects.toStrictEqual(Error("banned_from_community"));
// Unban alpha
let unBanAlpha = await banPersonFromCommunity(
beta,
alphaPerson.person.id,
searchBeta1.community.id,
false,
false,
);
expect(unBanAlpha.banned).toBe(false);
// Need to re-follow the community
await followBeta(alpha);
let postRes3 = await createPost(alpha, betaCommunity.community.id);
expect(postRes3.post_view.post).toBeDefined();
expect(postRes3.post_view.community.local).toBe(false);
expect(postRes3.post_view.creator.local).toBe(true);
expect(postRes3.post_view.counts.score).toBe(1);
// Make sure that post makes it to beta community
let postRes4 = await waitForPost(beta, postRes3.post_view.post);
expect(postRes4.post).toBeDefined();
expect(postRes4.creator_banned_from_community).toBe(false);
await unfollowRemotes(alpha);
});
test("A and G subscribe to B (center) A posts, it gets announced to G", async () => {
if (!betaCommunity) {
throw "Missing beta community";
}
await followBeta(alpha);
let postRes = await createPost(alpha, betaCommunity.community.id);
expect(postRes.post_view.post).toBeDefined();
let betaPost = (await resolvePost(gamma, postRes.post_view.post)).post;
expect(betaPost?.post.name).toBeDefined();
await unfollowRemotes(alpha);
});
test("Report a post", async () => {
// Create post from alpha
let alphaCommunity = (await resolveBetaCommunity(alpha)).community!;
await followBeta(alpha);
let postRes = await createPost(alpha, alphaCommunity.community.id);
expect(postRes.post_view.post).toBeDefined();
let alphaPost = (await resolvePost(alpha, postRes.post_view.post)).post;
if (!alphaPost) {
throw "Missing alpha post";
}
// Send report from gamma
let gammaPost = (await resolvePost(gamma, alphaPost.post)).post!;
let gammaReport = (
await reportPost(gamma, gammaPost.post.id, randomString(10))
).post_report_view.post_report;
expect(gammaReport).toBeDefined();
// Report was federated to community instance
let betaReport = (await waitUntil(
() =>
listPostReports(beta).then(p =>
p.post_reports.find(
r =>
r.post_report.original_post_name === gammaReport.original_post_name,
),
),
res => !!res,
))!.post_report;
expect(betaReport).toBeDefined();
expect(betaReport.resolved).toBe(false);
expect(betaReport.original_post_name).toBe(gammaReport.original_post_name);
//expect(betaReport.original_post_url).toBe(gammaReport.original_post_url);
expect(betaReport.original_post_body).toBe(gammaReport.original_post_body);
expect(betaReport.reason).toBe(gammaReport.reason);
await unfollowRemotes(alpha);
// Report was federated to poster's instance
let alphaReport = (await waitUntil(
() =>
listPostReports(alpha).then(p =>
p.post_reports.find(
r =>
r.post_report.original_post_name === gammaReport.original_post_name,
),
),
res => !!res,
))!.post_report;
expect(alphaReport).toBeDefined();
expect(alphaReport.resolved).toBe(false);
expect(alphaReport.original_post_name).toBe(gammaReport.original_post_name);
//expect(alphaReport.original_post_url).toBe(gammaReport.original_post_url);
expect(alphaReport.original_post_body).toBe(gammaReport.original_post_body);
expect(alphaReport.reason).toBe(gammaReport.reason);
});
test("Fetch post via redirect", async () => {
await followBeta(alpha);
let alphaPost = await createPost(alpha, betaCommunity!.community.id);
expect(alphaPost.post_view.post).toBeDefined();
// Make sure that post is liked on beta
const betaPost = await waitForPost(
beta,
alphaPost.post_view.post,
res => res?.counts.score === 1,
);
expect(betaPost).toBeDefined();
expect(betaPost.post?.ap_id).toBe(alphaPost.post_view.post.ap_id);
// Fetch post from url on beta instance instead of ap_id
let q = `http://lemmy-beta:8551/post/${betaPost.post.id}`;
let form: ResolveObject = {
q,
};
let gammaPost = await gamma.resolveObject(form);
expect(gammaPost).toBeDefined();
expect(gammaPost.post?.post.ap_id).toBe(alphaPost.post_view.post.ap_id);
await unfollowRemotes(alpha);
});
test("Block post that contains banned URL", async () => {
let editSiteForm: EditSite = {
blocked_urls: ["https://evil.com/"],
};
await epsilon.editSite(editSiteForm);
await delay();
if (!betaCommunity) {
throw "Missing beta community";
}
expect(
createPost(epsilon, betaCommunity.community.id, "https://evil.com"),
).rejects.toStrictEqual(Error("blocked_url"));
// Later tests need this to be empty
editSiteForm.blocked_urls = [];
await epsilon.editSite(editSiteForm);
});
test("Fetch post with redirect", async () => {
let alphaPost = await createPost(alpha, betaCommunity!.community.id);
expect(alphaPost.post_view.post).toBeDefined();
// beta fetches from alpha as usual
let betaPost = await resolvePost(beta, alphaPost.post_view.post);
expect(betaPost.post).toBeDefined();
// gamma fetches from beta, and gets redirected to alpha
let gammaPost = await resolvePost(gamma, betaPost.post!.post);
expect(gammaPost.post).toBeDefined();
// fetch remote object from local url, which redirects to the original url
let form: ResolveObject = {
q: `http://lemmy-gamma:8561/post/${gammaPost.post!.post.id}`,
};
let gammaPost2 = await gamma.resolveObject(form);
expect(gammaPost2.post).toBeDefined();
});

View File

@ -8,83 +8,142 @@ import {
editPrivateMessage,
listPrivateMessages,
deletePrivateMessage,
unfollowRemotes,
} from './shared';
waitUntil,
reportPrivateMessage,
unfollows,
} from "./shared";
let recipient_id: number;
beforeAll(async () => {
await setupLogins();
let follow = await followBeta(alpha);
recipient_id = follow.community_view.creator.id;
await followBeta(alpha);
recipient_id = 3;
});
afterAll(async () => {
await unfollowRemotes(alpha);
});
afterAll(unfollows);
test('Create a private message', async () => {
test("Create a private message", async () => {
let pmRes = await createPrivateMessage(alpha, recipient_id);
expect(pmRes.private_message_view.private_message.content).toBeDefined();
expect(pmRes.private_message_view.private_message.local).toBe(true);
expect(pmRes.private_message_view.creator.local).toBe(true);
expect(pmRes.private_message_view.recipient.local).toBe(false);
let betaPms = await listPrivateMessages(beta);
let betaPms = await waitUntil(
() => listPrivateMessages(beta),
e => !!e.private_messages[0],
);
expect(betaPms.private_messages[0].private_message.content).toBeDefined();
expect(betaPms.private_messages[0].private_message.local).toBe(false);
expect(betaPms.private_messages[0].creator.local).toBe(false);
expect(betaPms.private_messages[0].recipient.local).toBe(true);
});
test('Update a private message', async () => {
let updatedContent = 'A jest test federated private message edited';
test("Update a private message", async () => {
let updatedContent = "A jest test federated private message edited";
let pmRes = await createPrivateMessage(alpha, recipient_id);
let pmUpdated = await editPrivateMessage(
alpha,
pmRes.private_message_view.private_message.id
pmRes.private_message_view.private_message.id,
);
expect(pmUpdated.private_message_view.private_message.content).toBe(
updatedContent
updatedContent,
);
let betaPms = await listPrivateMessages(beta);
let betaPms = await waitUntil(
() => listPrivateMessages(beta),
p => p.private_messages[0].private_message.content === updatedContent,
);
expect(betaPms.private_messages[0].private_message.content).toBe(
updatedContent
updatedContent,
);
});
test('Delete a private message', async () => {
test("Delete a private message", async () => {
let pmRes = await createPrivateMessage(alpha, recipient_id);
let betaPms1 = await listPrivateMessages(beta);
let betaPms1 = await waitUntil(
() => listPrivateMessages(beta),
m =>
!!m.private_messages.find(
e =>
e.private_message.ap_id ===
pmRes.private_message_view.private_message.ap_id,
),
);
let deletedPmRes = await deletePrivateMessage(
alpha,
true,
pmRes.private_message_view.private_message.id
pmRes.private_message_view.private_message.id,
);
expect(deletedPmRes.private_message_view.private_message.deleted).toBe(true);
// The GetPrivateMessages filters out deleted,
// even though they are in the actual database.
// no reason to show them
let betaPms2 = await listPrivateMessages(beta);
let betaPms2 = await waitUntil(
() => listPrivateMessages(beta),
p => p.private_messages.length === betaPms1.private_messages.length - 1,
);
expect(betaPms2.private_messages.length).toBe(
betaPms1.private_messages.length - 1
betaPms1.private_messages.length - 1,
);
// Undelete
let undeletedPmRes = await deletePrivateMessage(
alpha,
false,
pmRes.private_message_view.private_message.id
pmRes.private_message_view.private_message.id,
);
expect(undeletedPmRes.private_message_view.private_message.deleted).toBe(
false
false,
);
let betaPms3 = await listPrivateMessages(beta);
let betaPms3 = await waitUntil(
() => listPrivateMessages(beta),
p => p.private_messages.length === betaPms1.private_messages.length,
);
expect(betaPms3.private_messages.length).toBe(
betaPms1.private_messages.length
betaPms1.private_messages.length,
);
});
test("Create a private message report", async () => {
let pmRes = await createPrivateMessage(alpha, recipient_id);
let betaPms1 = await waitUntil(
() => listPrivateMessages(beta),
m =>
!!m.private_messages.find(
e =>
e.private_message.ap_id ===
pmRes.private_message_view.private_message.ap_id,
),
);
let betaPm = betaPms1.private_messages[0];
expect(betaPm).toBeDefined();
// Make sure that only the recipient can report it, so this should fail
await expect(
reportPrivateMessage(
alpha,
pmRes.private_message_view.private_message.id,
"a reason",
),
).rejects.toStrictEqual(Error("couldnt_create_report"));
// This one should pass
let reason = "another reason";
let report = await reportPrivateMessage(
beta,
betaPm.private_message.id,
reason,
);
expect(report.private_message_report_view.private_message.id).toBe(
betaPm.private_message.id,
);
expect(report.private_message_report_view.private_message_report.reason).toBe(
reason,
);
});

File diff suppressed because it is too large Load Diff

View File

@ -1,65 +1,195 @@
jest.setTimeout(120000);
import { PersonView } from "lemmy-js-client/dist/types/PersonView";
import {
alpha,
beta,
registerUser,
searchForUser,
saveUserSettings,
resolvePerson,
getSite,
} from './shared';
import {
UserViewSafe,
SaveUserSettings,
SortType,
ListingType,
} from 'lemmy-js-client';
createPost,
resolveCommunity,
createComment,
resolveBetaCommunity,
deleteUser,
saveUserSettingsFederated,
setupLogins,
alphaUrl,
saveUserSettings,
getPost,
getComments,
fetchFunction,
alphaImage,
unfollows,
} from "./shared";
import { LemmyHttp, SaveUserSettings, UploadImage } from "lemmy-js-client";
import { GetPosts } from "lemmy-js-client/dist/types/GetPosts";
beforeAll(setupLogins);
afterAll(unfollows);
let auth: string;
let apShortname: string;
function assertUserFederation(userOne: UserViewSafe, userTwo: UserViewSafe) {
expect(userOne.user.name).toBe(userTwo.user.name);
expect(userOne.user.preferred_username).toBe(userTwo.user.preferred_username);
expect(userOne.user.bio).toBe(userTwo.user.bio);
expect(userOne.user.actor_id).toBe(userTwo.user.actor_id);
expect(userOne.user.avatar).toBe(userTwo.user.avatar);
expect(userOne.user.banner).toBe(userTwo.user.banner);
expect(userOne.user.published).toBe(userTwo.user.published);
function assertUserFederation(userOne?: PersonView, userTwo?: PersonView) {
expect(userOne?.person.name).toBe(userTwo?.person.name);
expect(userOne?.person.display_name).toBe(userTwo?.person.display_name);
expect(userOne?.person.bio).toBe(userTwo?.person.bio);
expect(userOne?.person.actor_id).toBe(userTwo?.person.actor_id);
expect(userOne?.person.avatar).toBe(userTwo?.person.avatar);
expect(userOne?.person.banner).toBe(userTwo?.person.banner);
expect(userOne?.person.published).toBe(userTwo?.person.published);
}
test('Create user', async () => {
let userRes = await registerUser(alpha);
expect(userRes.jwt).toBeDefined();
auth = userRes.jwt;
test("Create user", async () => {
let user = await registerUser(alpha, alphaUrl);
let site = await getSite(alpha, auth);
let site = await getSite(user);
expect(site.my_user).toBeDefined();
apShortname = `@${site.my_user.name}@lemmy-alpha:8541`;
if (!site.my_user) {
throw "Missing site user";
}
apShortname = `${site.my_user.local_user_view.person.name}@lemmy-alpha:8541`;
});
test('Set some user settings, check that they are federated', async () => {
let avatar = 'https://image.flaticon.com/icons/png/512/35/35896.png';
let banner = 'https://image.flaticon.com/icons/png/512/36/35896.png';
let bio = 'a changed bio';
test("Set some user settings, check that they are federated", async () => {
await saveUserSettingsFederated(alpha);
let alphaPerson = (await resolvePerson(alpha, apShortname)).person;
let betaPerson = (await resolvePerson(beta, apShortname)).person;
assertUserFederation(alphaPerson, betaPerson);
// Catches a bug where when only the person or local_user changed
let form: SaveUserSettings = {
show_nsfw: false,
theme: '',
default_sort_type: Object.keys(SortType).indexOf(SortType.Hot),
default_listing_type: Object.keys(ListingType).indexOf(ListingType.All),
lang: '',
avatar,
banner,
preferred_username: 'user321',
show_avatars: false,
send_notifications_to_email: false,
bio,
auth,
theme: "test",
};
await saveUserSettings(alpha, form);
await saveUserSettings(beta, form);
let searchAlpha = await searchForUser(alpha, apShortname);
let userOnAlpha = searchAlpha.users[0];
let searchBeta = await searchForUser(beta, apShortname);
let userOnBeta = searchBeta.users[0];
assertUserFederation(userOnAlpha, userOnBeta);
let site = await getSite(beta);
expect(site.my_user?.local_user_view.local_user.theme).toBe("test");
});
test("Delete user", async () => {
let user = await registerUser(alpha, alphaUrl);
// make a local post and comment
let alphaCommunity = (await resolveCommunity(user, "main@lemmy-alpha:8541"))
.community;
if (!alphaCommunity) {
throw "Missing alpha community";
}
let localPost = (await createPost(user, alphaCommunity.community.id))
.post_view.post;
expect(localPost).toBeDefined();
let localComment = (await createComment(user, localPost.id)).comment_view
.comment;
expect(localComment).toBeDefined();
// make a remote post and comment
let betaCommunity = (await resolveBetaCommunity(user)).community;
if (!betaCommunity) {
throw "Missing beta community";
}
let remotePost = (await createPost(user, betaCommunity.community.id))
.post_view.post;
expect(remotePost).toBeDefined();
let remoteComment = (await createComment(user, remotePost.id)).comment_view
.comment;
expect(remoteComment).toBeDefined();
await deleteUser(user);
// check that posts and comments are marked as deleted on other instances.
// use get methods to avoid refetching from origin instance
expect((await getPost(alpha, localPost.id)).post_view.post.deleted).toBe(
true,
);
expect((await getPost(alpha, remotePost.id)).post_view.post.deleted).toBe(
true,
);
expect(
(await getComments(alpha, localComment.post_id)).comments[0].comment
.deleted,
).toBe(true);
expect(
(await getComments(alpha, remoteComment.post_id)).comments[0].comment
.deleted,
).toBe(true);
});
test("Requests with invalid auth should be treated as unauthenticated", async () => {
let invalid_auth = new LemmyHttp(alphaUrl, {
headers: { Authorization: "Bearer foobar" },
fetchFunction,
});
let site = await getSite(invalid_auth);
expect(site.my_user).toBeUndefined();
expect(site.site_view).toBeDefined();
let form: GetPosts = {};
let posts = invalid_auth.getPosts(form);
expect((await posts).posts).toBeDefined();
});
test("Create user with Arabic name", async () => {
let user = await registerUser(alpha, alphaUrl, "تجريب");
let site = await getSite(user);
expect(site.my_user).toBeDefined();
if (!site.my_user) {
throw "Missing site user";
}
apShortname = `${site.my_user.local_user_view.person.name}@lemmy-alpha:8541`;
let alphaPerson = (await resolvePerson(alpha, apShortname)).person;
expect(alphaPerson).toBeDefined();
});
test("Create user with accept-language", async () => {
let lemmy_http = new LemmyHttp(alphaUrl, {
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Language#syntax
headers: { "Accept-Language": "fr-CH, en;q=0.8, de;q=0.7, *;q=0.5" },
});
let user = await registerUser(lemmy_http, alphaUrl);
let site = await getSite(user);
expect(site.my_user).toBeDefined();
expect(site.my_user?.local_user_view.local_user.interface_language).toBe(
"fr",
);
let langs = site.all_languages
.filter(a => site.my_user?.discussion_languages.includes(a.id))
.map(l => l.code);
// should have languages from accept header, as well as "undetermined"
// which is automatically enabled by backend
expect(langs).toStrictEqual(["und", "de", "en", "fr"]);
});
test("Set a new avatar, old avatar is deleted", async () => {
const listMediaRes = await alphaImage.listMedia();
expect(listMediaRes.images.length).toBe(0);
const upload_form1: UploadImage = {
image: Buffer.from("test1"),
};
const upload1 = await alphaImage.uploadImage(upload_form1);
expect(upload1.url).toBeDefined();
let form1 = {
avatar: upload1.url,
};
await saveUserSettings(alpha, form1);
const listMediaRes1 = await alphaImage.listMedia();
expect(listMediaRes1.images.length).toBe(1);
const upload_form2: UploadImage = {
image: Buffer.from("test2"),
};
const upload2 = await alphaImage.uploadImage(upload_form2);
expect(upload2.url).toBeDefined();
let form2 = {
avatar: upload1.url,
};
await saveUserSettings(alpha, form2);
// make sure only the new avatar is kept
const listMediaRes2 = await alphaImage.listMedia();
expect(listMediaRes2.images.length).toBe(1);
});

View File

@ -6,11 +6,10 @@
"noImplicitAny": true,
"lib": ["es2017", "es7", "es6", "dom"],
"outDir": "./dist",
"target": "ES5",
"target": "ES2020",
"strictNullChecks": true,
"moduleResolution": "Node"
},
"include": [
"src/**/*"
],
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}

File diff suppressed because it is too large Load Diff

86
cliff.toml Normal file
View File

@ -0,0 +1,86 @@
# git-cliff ~ configuration file
# https://git-cliff.org/docs/configuration
[remote.github]
owner = "LemmyNet"
repo = "lemmy"
# token = ""
[changelog]
# template for the changelog body
# https://keats.github.io/tera/docs/#introduction
body = """
## What's Changed
{%- if version %} in {{ version }}{%- endif -%}
{% for commit in commits %}
{% if commit.github.pr_title -%}
{%- set commit_message = commit.github.pr_title -%}
{%- else -%}
{%- set commit_message = commit.message -%}
{%- endif -%}
* {{ commit_message | split(pat="\n") | first | trim }}\
{% if commit.github.username %} by @{{ commit.github.username }}{%- endif -%}
{% if commit.github.pr_number %} in \
[#{{ commit.github.pr_number }}]({{ self::remote_url() }}/pull/{{ commit.github.pr_number }}) \
{%- endif %}
{%- endfor -%}
{% if github.contributors | filter(attribute="is_first_time", value=true) | length != 0 %}
{% raw %}\n{% endraw -%}
## New Contributors
{%- endif %}\
{% for contributor in github.contributors | filter(attribute="is_first_time", value=true) %}
* @{{ contributor.username }} made their first contribution
{%- if contributor.pr_number %} in \
[#{{ contributor.pr_number }}]({{ self::remote_url() }}/pull/{{ contributor.pr_number }}) \
{%- endif %}
{%- endfor -%}
{% if version %}
{% if previous.version %}
**Full Changelog**: {{ self::remote_url() }}/compare/{{ previous.version }}...{{ version }}
{% endif %}
{% else -%}
{% raw %}\n{% endraw %}
{% endif %}
{%- macro remote_url() -%}
https://github.com/{{ remote.github.owner }}/{{ remote.github.repo }}
{%- endmacro -%}
"""
# remove the leading and trailing whitespace from the template
trim = true
# changelog footer
footer = """
<!-- generated by git-cliff -->
"""
# postprocessors
postprocessors = []
[git]
# parse the commits based on https://www.conventionalcommits.org
conventional_commits = false
# filter out the commits that are not conventional
filter_unconventional = true
# process each line of a commit as an individual commit
split_commits = false
# regex for preprocessing the commit messages
commit_preprocessors = [
# remove issue numbers from commits
{ pattern = '\((\w+\s)?#([0-9]+)\)', replace = "" },
]
# protect breaking changes from being skipped due to matching a skipping commit_parser
protect_breaking_commits = false
# filter out the commits that are not matched by commit parsers
filter_commits = false
# regex for matching git tags
tag_pattern = "[0-9].*"
# regex for skipping tags
skip_tags = "beta|alpha"
# regex for ignoring tags
ignore_tags = "rc"
# sort the tags topologically
topo_order = false
# sort the commits inside sections by oldest/newest order
sort_commits = "newest"

View File

@ -1,3 +1,5 @@
# See the documentation for available config fields and descriptions:
# https://join-lemmy.org/docs/en/administration/configuration.html
{
hostname: "localhost:8536"
hostname: lemmy-alpha
}

View File

@ -1,90 +1,122 @@
{
# # optional: parameters for automatic configuration of new instance (only used at first start)
# setup: {
# # username for the admin user
# admin_username: ""
# # password for the admin user
# admin_password: ""
# # optional: email for the admin user (can be omitted and set later through the website)
# admin_email: ""
# # name of the site (can be changed later)
# site_name: ""
# }
# settings related to the postgresql database
database: {
# username to connect to postgres
user: "lemmy"
# password to connect to postgres
password: "password"
# host where postgres is running
host: "localhost"
# port where postgres can be accessed
port: 5432
# name of the postgres database for lemmy
database: "lemmy"
# maximum number of active sql connections
pool_size: 5
# Configure the database by specifying a URI
#
# This is the preferred method to specify database connection details since
# it is the most flexible.
# Connection URI pointing to a postgres instance
#
# This example uses peer authentication to obviate the need for creating,
# configuring, and managing passwords.
#
# For an explanation of how to use connection URIs, see [here][0] in
# PostgreSQL's documentation.
#
# [0]: https://www.postgresql.org/docs/current/libpq-connect.html#id-1.7.3.8.3.6
uri: "postgresql:///lemmy?user=lemmy&host=/var/run/postgresql"
# or
# Configure the database by specifying parts of a URI
#
# Note that specifying the `uri` field should be preferred since it provides
# greater control over how the connection is made. This merely exists for
# backwards-compatibility.
# Username to connect to postgres
user: "string"
# Password to connect to postgres
password: "string"
# Host where postgres is running
host: "string"
# Port where postgres can be accessed
port: 123
# Name of the postgres database for lemmy
database: "string"
# Maximum number of active sql connections
pool_size: 30
}
# the domain name of your instance (eg "lemmy.ml")
hostname: null
# address where lemmy should listen for incoming requests
# Pictrs image server configuration.
pictrs: {
# Address where pictrs is available (for image hosting)
url: "http://localhost:8080/"
# Set a custom pictrs API key. ( Required for deleting images )
api_key: "string"
# Backwards compatibility with 0.18.1. False is equivalent to `image_mode: None`, true is
# equivalent to `image_mode: StoreLinkPreviews`.
#
# To be removed in 0.20
cache_external_link_previews: true
# Specifies how to handle remote images, so that users don't have to connect directly to remote
# servers.
image_mode:
# Leave images unchanged, don't generate any local thumbnails for post urls. Instead the
# Opengraph image is directly returned as thumbnail
"None"
# or
# Generate thumbnails for external post urls and store them persistently in pict-rs. This
# ensures that they can be reliably retrieved and can be resized using pict-rs APIs. However
# it also increases storage usage.
#
# This is the default behaviour, and also matches Lemmy 0.18.
"StoreLinkPreviews"
# or
# If enabled, all images from remote domains are rewritten to pass through
# `/api/v3/image_proxy`, including embedded images in markdown. Images are stored temporarily
# in pict-rs for caching. This improves privacy as users don't expose their IP to untrusted
# servers, and decreases load on other servers. However it increases bandwidth use for the
# local server.
#
# Requires pict-rs 0.5
"ProxyAllImages"
# Timeout for uploading images to pictrs (in seconds)
upload_timeout: 30
}
# Email sending configuration. All options except login/password are mandatory
email: {
# Hostname and port of the smtp server
smtp_server: "localhost:25"
# Login name for smtp server
smtp_login: "string"
# Password to login to the smtp server
smtp_password: "string"
# Address to send emails from, eg "noreply@your-instance.com"
smtp_from_address: "noreply@example.com"
# Whether or not smtp connections should use tls. Can be none, tls, or starttls
tls_type: "none"
}
# Parameters for automatic configuration of new instance (only used at first start)
setup: {
# Username for the admin user
admin_username: "admin"
# Password for the admin user. It must be between 10 and 60 characters.
admin_password: "tf6HHDS4RolWfFhk4Rq9"
# Name of the site, can be changed later. Maximum 20 characters.
site_name: "My Lemmy Instance"
# Email for the admin user (optional, can be omitted and set later through the website)
admin_email: "user@example.com"
}
# the domain name of your instance (mandatory)
hostname: "unset"
# Address where lemmy should listen for incoming requests
bind: "0.0.0.0"
# port where lemmy should listen for incoming requests
# Port where lemmy should listen for incoming requests
port: 8536
# whether tls is required for activitypub. only disable this for debugging, never for producion.
# Whether the site is available over TLS. Needs to be true for federation to work.
tls_enabled: true
# json web token for authorization between server and client
jwt_secret: "changeme"
# address where pictrs is available
pictrs_url: "http://pictrs:8080"
# address where iframely is available
iframely_url: "http://iframely"
# rate limits for various user actions, by user ip
rate_limit: {
# maximum number of messages created in interval
message: 180
# interval length for message limit
message_per_second: 60
# maximum number of posts created in interval
post: 6
# interval length for post limit
post_per_second: 600
# maximum number of registrations in interval
register: 3
# interval length for registration limit
register_per_second: 3600
# maximum number of image uploads in interval
image: 6
# interval length for image uploads
image_per_second: 3600
# The number of activitypub federation workers that can be in-flight concurrently
worker_count: 0
# The number of activitypub federation retry workers that can be in-flight concurrently
retry_count: 0
prometheus: {
bind: "127.0.0.1"
port: 10002
}
# settings related to activitypub federation
federation: {
# whether to enable activitypub federation.
enabled: false
# Allows and blocks are described here:
# https://join.lemmy.ml/docs/en/federation/administration.html#instance-allowlist-and-blocklist
#
# comma separated list of instances with which federation is allowed
allowed_instances: ""
# comma separated list of instances which are blocked from federating
blocked_instances: ""
}
captcha: {
enabled: true
difficulty: medium # Can be easy, medium, or hard
}
# # email sending configuration
# email: {
# # hostname and port of the smtp server
# smtp_server: ""
# # login name for smtp server
# smtp_login: ""
# # password to login to the smtp server
# smtp_password: ""
# # address to send emails from, eg "noreply@your-instance.com"
# smtp_from_address: ""
# # whether or not smtp connections should use tls
# use_tls: true
# }
# Sets a response Access-Control-Allow-Origin CORS header
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
cors_origin: "*"
}

View File

@ -1,50 +1,45 @@
[package]
name = "lemmy_api"
version = "0.1.0"
authors = ["Felix Ableitner <me@nutomic.com>"]
edition = "2018"
publish = false
version.workspace = true
edition.workspace = true
description.workspace = true
license.workspace = true
homepage.workspace = true
documentation.workspace = true
repository.workspace = true
[lib]
name = "lemmy_api"
path = "src/lib.rs"
doctest = false
[lints]
workspace = true
[dependencies]
lemmy_apub = { path = "../apub" }
lemmy_utils = { path = "../utils" }
lemmy_db_queries = { path = "../db_queries" }
lemmy_db_schema = { path = "../db_schema" }
lemmy_db_views = { path = "../db_views" }
lemmy_db_views_moderator = { path = "../db_views_moderator" }
lemmy_db_views_actor = { path = "../db_views_actor" }
lemmy_structs = { path = "../structs" }
lemmy_websocket = { path = "../websocket" }
diesel = "1.4.5"
bcrypt = "0.9.0"
chrono = { version = "0.4.19", features = ["serde"] }
serde_json = { version = "1.0.61", features = ["preserve_order"] }
serde = { version = "1.0.123", features = ["derive"] }
actix = "0.10.0"
actix-web = { version = "3.3.2", default-features = false }
actix-rt = { version = "1.1.1", default-features = false }
awc = { version = "2.0.3", default-features = false }
log = "0.4.14"
rand = "0.8.3"
strum = "0.20.0"
strum_macros = "0.20.1"
lazy_static = "1.4.0"
url = { version = "2.2.0", features = ["serde"] }
openssl = "0.10.32"
http = "0.2.3"
http-signature-normalization-actix = { version = "0.4.1", default-features = false, features = ["sha-2"] }
base64 = "0.13.0"
tokio = "0.3.6"
futures = "0.3.12"
itertools = "0.10.0"
uuid = { version = "0.8.2", features = ["serde", "v4"] }
sha2 = "0.9.3"
async-trait = "0.1.42"
captcha = "0.0.8"
anyhow = "1.0.38"
thiserror = "1.0.23"
background-jobs = "0.8.0"
reqwest = { version = "0.10.10", features = ["json"] }
lemmy_utils = { workspace = true }
lemmy_db_schema = { workspace = true, features = ["full"] }
lemmy_db_views = { workspace = true, features = ["full"] }
lemmy_db_views_moderator = { workspace = true, features = ["full"] }
lemmy_db_views_actor = { workspace = true, features = ["full"] }
lemmy_api_common = { workspace = true, features = ["full"] }
activitypub_federation = { workspace = true }
bcrypt = { workspace = true }
actix-web = { workspace = true }
base64 = { workspace = true }
captcha = { workspace = true }
anyhow = { workspace = true }
tracing = { workspace = true }
chrono = { workspace = true }
url = { workspace = true }
wav = "1.0.1"
sitemap-rs = "0.2.1"
totp-rs = { version = "5.5.1", features = ["gen_secret", "otpauth"] }
actix-web-httpauth = "0.8.1"
[dev-dependencies]
serial_test = { workspace = true }
tokio = { workspace = true }
elementtree = "1.2.3"
pretty_assertions = { workspace = true }

View File

@ -1,817 +0,0 @@
use crate::{
check_community_ban,
check_downvotes_enabled,
collect_moderated_communities,
get_post,
get_user_from_jwt,
get_user_from_jwt_opt,
is_mod_or_admin,
Perform,
};
use actix_web::web::Data;
use lemmy_apub::{generate_apub_endpoint, ApubLikeableType, ApubObjectType, EndpointType};
use lemmy_db_queries::{
source::comment::Comment_,
Crud,
Likeable,
ListingType,
Reportable,
Saveable,
SortType,
};
use lemmy_db_schema::source::{comment::*, comment_report::*, moderator::*};
use lemmy_db_views::{
comment_report_view::{CommentReportQueryBuilder, CommentReportView},
comment_view::{CommentQueryBuilder, CommentView},
};
use lemmy_structs::{blocking, comment::*, send_local_notifs};
use lemmy_utils::{
utils::{remove_slurs, scrape_text_for_mentions},
APIError,
ConnectionId,
LemmyError,
};
use lemmy_websocket::{
messages::{SendComment, SendModRoomMessage, SendUserRoomMessage},
LemmyContext,
UserOperation,
};
use std::str::FromStr;
#[async_trait::async_trait(?Send)]
impl Perform for CreateComment {
type Response = CommentResponse;
async fn perform(
&self,
context: &Data<LemmyContext>,
websocket_id: Option<ConnectionId>,
) -> Result<CommentResponse, LemmyError> {
let data: &CreateComment = &self;
let user = get_user_from_jwt(&data.auth, context.pool()).await?;
let content_slurs_removed = remove_slurs(&data.content.to_owned());
// Check for a community ban
let post_id = data.post_id;
let post = get_post(post_id, context.pool()).await?;
check_community_ban(user.id, post.community_id, context.pool()).await?;
// Check if post is locked, no new comments
if post.locked {
return Err(APIError::err("locked").into());
}
// If there's a parent_id, check to make sure that comment is in that post
if let Some(parent_id) = data.parent_id {
// Make sure the parent comment exists
let parent =
match blocking(context.pool(), move |conn| Comment::read(&conn, parent_id)).await? {
Ok(comment) => comment,
Err(_e) => return Err(APIError::err("couldnt_create_comment").into()),
};
if parent.post_id != post_id {
return Err(APIError::err("couldnt_create_comment").into());
}
}
let comment_form = CommentForm {
content: content_slurs_removed,
parent_id: data.parent_id.to_owned(),
post_id: data.post_id,
creator_id: user.id,
removed: None,
deleted: None,
read: None,
published: None,
updated: None,
ap_id: None,
local: true,
};
// Create the comment
let comment_form2 = comment_form.clone();
let inserted_comment = match blocking(context.pool(), move |conn| {
Comment::create(&conn, &comment_form2)
})
.await?
{
Ok(comment) => comment,
Err(_e) => return Err(APIError::err("couldnt_create_comment").into()),
};
// Necessary to update the ap_id
let inserted_comment_id = inserted_comment.id;
let updated_comment: Comment =
match blocking(context.pool(), move |conn| -> Result<Comment, LemmyError> {
let apub_id =
generate_apub_endpoint(EndpointType::Comment, &inserted_comment_id.to_string())?;
Ok(Comment::update_ap_id(&conn, inserted_comment_id, apub_id)?)
})
.await?
{
Ok(comment) => comment,
Err(_e) => return Err(APIError::err("couldnt_create_comment").into()),
};
updated_comment.send_create(&user, context).await?;
// Scan the comment for user mentions, add those rows
let post_id = post.id;
let mentions = scrape_text_for_mentions(&comment_form.content);
let recipient_ids = send_local_notifs(
mentions,
updated_comment.clone(),
&user,
post,
context.pool(),
true,
)
.await?;
// You like your own comment by default
let like_form = CommentLikeForm {
comment_id: inserted_comment.id,
post_id,
user_id: user.id,
score: 1,
};
let like = move |conn: &'_ _| CommentLike::like(&conn, &like_form);
if blocking(context.pool(), like).await?.is_err() {
return Err(APIError::err("couldnt_like_comment").into());
}
updated_comment.send_like(&user, context).await?;
let user_id = user.id;
let mut comment_view = blocking(context.pool(), move |conn| {
CommentView::read(&conn, inserted_comment.id, Some(user_id))
})
.await??;
// If its a comment to yourself, mark it as read
let comment_id = comment_view.comment.id;
if user.id == comment_view.get_recipient_id() {
match blocking(context.pool(), move |conn| {
Comment::update_read(conn, comment_id, true)
})
.await?
{
Ok(comment) => comment,
Err(_e) => return Err(APIError::err("couldnt_update_comment").into()),
};
comment_view.comment.read = true;
}
let mut res = CommentResponse {
comment_view,
recipient_ids,
form_id: data.form_id.to_owned(),
};
context.chat_server().do_send(SendComment {
op: UserOperation::CreateComment,
comment: res.clone(),
websocket_id,
});
res.recipient_ids = Vec::new(); // Necessary to avoid doubles
Ok(res)
}
}
#[async_trait::async_trait(?Send)]
impl Perform for EditComment {
type Response = CommentResponse;
async fn perform(
&self,
context: &Data<LemmyContext>,
websocket_id: Option<ConnectionId>,
) -> Result<CommentResponse, LemmyError> {
let data: &EditComment = &self;
let user = get_user_from_jwt(&data.auth, context.pool()).await?;
let comment_id = data.comment_id;
let orig_comment = blocking(context.pool(), move |conn| {
CommentView::read(&conn, comment_id, None)
})
.await??;
check_community_ban(user.id, orig_comment.community.id, context.pool()).await?;
// Verify that only the creator can edit
if user.id != orig_comment.creator.id {
return Err(APIError::err("no_comment_edit_allowed").into());
}
// Do the update
let content_slurs_removed = remove_slurs(&data.content.to_owned());
let comment_id = data.comment_id;
let updated_comment = match blocking(context.pool(), move |conn| {
Comment::update_content(conn, comment_id, &content_slurs_removed)
})
.await?
{
Ok(comment) => comment,
Err(_e) => return Err(APIError::err("couldnt_update_comment").into()),
};
// Send the apub update
updated_comment.send_update(&user, context).await?;
// Do the mentions / recipients
let updated_comment_content = updated_comment.content.to_owned();
let mentions = scrape_text_for_mentions(&updated_comment_content);
let recipient_ids = send_local_notifs(
mentions,
updated_comment,
&user,
orig_comment.post,
context.pool(),
false,
)
.await?;
let comment_id = data.comment_id;
let user_id = user.id;
let comment_view = blocking(context.pool(), move |conn| {
CommentView::read(conn, comment_id, Some(user_id))
})
.await??;
let res = CommentResponse {
comment_view,
recipient_ids,
form_id: data.form_id.to_owned(),
};
context.chat_server().do_send(SendComment {
op: UserOperation::EditComment,
comment: res.clone(),
websocket_id,
});
Ok(res)
}
}
#[async_trait::async_trait(?Send)]
impl Perform for DeleteComment {
type Response = CommentResponse;
async fn perform(
&self,
context: &Data<LemmyContext>,
websocket_id: Option<ConnectionId>,
) -> Result<CommentResponse, LemmyError> {
let data: &DeleteComment = &self;
let user = get_user_from_jwt(&data.auth, context.pool()).await?;
let comment_id = data.comment_id;
let orig_comment = blocking(context.pool(), move |conn| {
CommentView::read(&conn, comment_id, None)
})
.await??;
check_community_ban(user.id, orig_comment.community.id, context.pool()).await?;
// Verify that only the creator can delete
if user.id != orig_comment.creator.id {
return Err(APIError::err("no_comment_edit_allowed").into());
}
// Do the delete
let deleted = data.deleted;
let updated_comment = match blocking(context.pool(), move |conn| {
Comment::update_deleted(conn, comment_id, deleted)
})
.await?
{
Ok(comment) => comment,
Err(_e) => return Err(APIError::err("couldnt_update_comment").into()),
};
// Send the apub message
if deleted {
updated_comment.send_delete(&user, context).await?;
} else {
updated_comment.send_undo_delete(&user, context).await?;
}
// Refetch it
let comment_id = data.comment_id;
let user_id = user.id;
let comment_view = blocking(context.pool(), move |conn| {
CommentView::read(conn, comment_id, Some(user_id))
})
.await??;
// Build the recipients
let comment_view_2 = comment_view.clone();
let mentions = vec![];
let recipient_ids = send_local_notifs(
mentions,
updated_comment,
&user,
comment_view_2.post,
context.pool(),
false,
)
.await?;
let res = CommentResponse {
comment_view,
recipient_ids,
form_id: None, // TODO a comment delete might clear forms?
};
context.chat_server().do_send(SendComment {
op: UserOperation::DeleteComment,
comment: res.clone(),
websocket_id,
});
Ok(res)
}
}
#[async_trait::async_trait(?Send)]
impl Perform for RemoveComment {
type Response = CommentResponse;
async fn perform(
&self,
context: &Data<LemmyContext>,
websocket_id: Option<ConnectionId>,
) -> Result<CommentResponse, LemmyError> {
let data: &RemoveComment = &self;
let user = get_user_from_jwt(&data.auth, context.pool()).await?;
let comment_id = data.comment_id;
let orig_comment = blocking(context.pool(), move |conn| {
CommentView::read(&conn, comment_id, None)
})
.await??;
check_community_ban(user.id, orig_comment.community.id, context.pool()).await?;
// Verify that only a mod or admin can remove
is_mod_or_admin(context.pool(), user.id, orig_comment.community.id).await?;
// Do the remove
let removed = data.removed;
let updated_comment = match blocking(context.pool(), move |conn| {
Comment::update_removed(conn, comment_id, removed)
})
.await?
{
Ok(comment) => comment,
Err(_e) => return Err(APIError::err("couldnt_update_comment").into()),
};
// Mod tables
let form = ModRemoveCommentForm {
mod_user_id: user.id,
comment_id: data.comment_id,
removed: Some(removed),
reason: data.reason.to_owned(),
};
blocking(context.pool(), move |conn| {
ModRemoveComment::create(conn, &form)
})
.await??;
// Send the apub message
if removed {
updated_comment.send_remove(&user, context).await?;
} else {
updated_comment.send_undo_remove(&user, context).await?;
}
// Refetch it
let comment_id = data.comment_id;
let user_id = user.id;
let comment_view = blocking(context.pool(), move |conn| {
CommentView::read(conn, comment_id, Some(user_id))
})
.await??;
// Build the recipients
let comment_view_2 = comment_view.clone();
let mentions = vec![];
let recipient_ids = send_local_notifs(
mentions,
updated_comment,
&user,
comment_view_2.post,
context.pool(),
false,
)
.await?;
let res = CommentResponse {
comment_view,
recipient_ids,
form_id: None, // TODO maybe this might clear other forms
};
context.chat_server().do_send(SendComment {
op: UserOperation::RemoveComment,
comment: res.clone(),
websocket_id,
});
Ok(res)
}
}
#[async_trait::async_trait(?Send)]
impl Perform for MarkCommentAsRead {
type Response = CommentResponse;
async fn perform(
&self,
context: &Data<LemmyContext>,
_websocket_id: Option<ConnectionId>,
) -> Result<CommentResponse, LemmyError> {
let data: &MarkCommentAsRead = &self;
let user = get_user_from_jwt(&data.auth, context.pool()).await?;
let comment_id = data.comment_id;
let orig_comment = blocking(context.pool(), move |conn| {
CommentView::read(&conn, comment_id, None)
})
.await??;
check_community_ban(user.id, orig_comment.community.id, context.pool()).await?;
// Verify that only the recipient can mark as read
if user.id != orig_comment.get_recipient_id() {
return Err(APIError::err("no_comment_edit_allowed").into());
}
// Do the mark as read
let read = data.read;
match blocking(context.pool(), move |conn| {
Comment::update_read(conn, comment_id, read)
})
.await?
{
Ok(comment) => comment,
Err(_e) => return Err(APIError::err("couldnt_update_comment").into()),
};
// Refetch it
let comment_id = data.comment_id;
let user_id = user.id;
let comment_view = blocking(context.pool(), move |conn| {
CommentView::read(conn, comment_id, Some(user_id))
})
.await??;
let res = CommentResponse {
comment_view,
recipient_ids: Vec::new(),
form_id: None,
};
Ok(res)
}
}
#[async_trait::async_trait(?Send)]
impl Perform for SaveComment {
type Response = CommentResponse;
async fn perform(
&self,
context: &Data<LemmyContext>,
_websocket_id: Option<ConnectionId>,
) -> Result<CommentResponse, LemmyError> {
let data: &SaveComment = &self;
let user = get_user_from_jwt(&data.auth, context.pool()).await?;
let comment_saved_form = CommentSavedForm {
comment_id: data.comment_id,
user_id: user.id,
};
if data.save {
let save_comment = move |conn: &'_ _| CommentSaved::save(conn, &comment_saved_form);
if blocking(context.pool(), save_comment).await?.is_err() {
return Err(APIError::err("couldnt_save_comment").into());
}
} else {
let unsave_comment = move |conn: &'_ _| CommentSaved::unsave(conn, &comment_saved_form);
if blocking(context.pool(), unsave_comment).await?.is_err() {
return Err(APIError::err("couldnt_save_comment").into());
}
}
let comment_id = data.comment_id;
let user_id = user.id;
let comment_view = blocking(context.pool(), move |conn| {
CommentView::read(conn, comment_id, Some(user_id))
})
.await??;
Ok(CommentResponse {
comment_view,
recipient_ids: Vec::new(),
form_id: None,
})
}
}
#[async_trait::async_trait(?Send)]
impl Perform for CreateCommentLike {
type Response = CommentResponse;
async fn perform(
&self,
context: &Data<LemmyContext>,
websocket_id: Option<ConnectionId>,
) -> Result<CommentResponse, LemmyError> {
let data: &CreateCommentLike = &self;
let user = get_user_from_jwt(&data.auth, context.pool()).await?;
let mut recipient_ids = Vec::new();
// Don't do a downvote if site has downvotes disabled
check_downvotes_enabled(data.score, context.pool()).await?;
let comment_id = data.comment_id;
let orig_comment = blocking(context.pool(), move |conn| {
CommentView::read(&conn, comment_id, None)
})
.await??;
check_community_ban(user.id, orig_comment.community.id, context.pool()).await?;
// Add parent user to recipients
recipient_ids.push(orig_comment.get_recipient_id());
let like_form = CommentLikeForm {
comment_id: data.comment_id,
post_id: orig_comment.post.id,
user_id: user.id,
score: data.score,
};
// Remove any likes first
let user_id = user.id;
blocking(context.pool(), move |conn| {
CommentLike::remove(conn, user_id, comment_id)
})
.await??;
// Only add the like if the score isnt 0
let comment = orig_comment.comment;
let do_add = like_form.score != 0 && (like_form.score == 1 || like_form.score == -1);
if do_add {
let like_form2 = like_form.clone();
let like = move |conn: &'_ _| CommentLike::like(conn, &like_form2);
if blocking(context.pool(), like).await?.is_err() {
return Err(APIError::err("couldnt_like_comment").into());
}
if like_form.score == 1 {
comment.send_like(&user, context).await?;
} else if like_form.score == -1 {
comment.send_dislike(&user, context).await?;
}
} else {
comment.send_undo_like(&user, context).await?;
}
// Have to refetch the comment to get the current state
let comment_id = data.comment_id;
let user_id = user.id;
let liked_comment = blocking(context.pool(), move |conn| {
CommentView::read(conn, comment_id, Some(user_id))
})
.await??;
let res = CommentResponse {
comment_view: liked_comment,
recipient_ids,
form_id: None,
};
context.chat_server().do_send(SendComment {
op: UserOperation::CreateCommentLike,
comment: res.clone(),
websocket_id,
});
Ok(res)
}
}
#[async_trait::async_trait(?Send)]
impl Perform for GetComments {
type Response = GetCommentsResponse;
async fn perform(
&self,
context: &Data<LemmyContext>,
_websocket_id: Option<ConnectionId>,
) -> Result<GetCommentsResponse, LemmyError> {
let data: &GetComments = &self;
let user = get_user_from_jwt_opt(&data.auth, context.pool()).await?;
let user_id = user.map(|u| u.id);
let type_ = ListingType::from_str(&data.type_)?;
let sort = SortType::from_str(&data.sort)?;
let community_id = data.community_id;
let community_name = data.community_name.to_owned();
let page = data.page;
let limit = data.limit;
let comments = blocking(context.pool(), move |conn| {
CommentQueryBuilder::create(conn)
.listing_type(type_)
.sort(&sort)
.community_id(community_id)
.community_name(community_name)
.my_user_id(user_id)
.page(page)
.limit(limit)
.list()
})
.await?;
let comments = match comments {
Ok(comments) => comments,
Err(_) => return Err(APIError::err("couldnt_get_comments").into()),
};
Ok(GetCommentsResponse { comments })
}
}
/// Creates a comment report and notifies the moderators of the community
#[async_trait::async_trait(?Send)]
impl Perform for CreateCommentReport {
type Response = CreateCommentReportResponse;
async fn perform(
&self,
context: &Data<LemmyContext>,
websocket_id: Option<ConnectionId>,
) -> Result<CreateCommentReportResponse, LemmyError> {
let data: &CreateCommentReport = &self;
let user = get_user_from_jwt(&data.auth, context.pool()).await?;
// check size of report and check for whitespace
let reason = data.reason.trim();
if reason.is_empty() {
return Err(APIError::err("report_reason_required").into());
}
if reason.chars().count() > 1000 {
return Err(APIError::err("report_too_long").into());
}
let user_id = user.id;
let comment_id = data.comment_id;
let comment_view = blocking(context.pool(), move |conn| {
CommentView::read(&conn, comment_id, None)
})
.await??;
check_community_ban(user_id, comment_view.community.id, context.pool()).await?;
let report_form = CommentReportForm {
creator_id: user_id,
comment_id,
original_comment_text: comment_view.comment.content,
reason: data.reason.to_owned(),
};
let report = match blocking(context.pool(), move |conn| {
CommentReport::report(conn, &report_form)
})
.await?
{
Ok(report) => report,
Err(_e) => return Err(APIError::err("couldnt_create_report").into()),
};
let res = CreateCommentReportResponse { success: true };
context.chat_server().do_send(SendUserRoomMessage {
op: UserOperation::CreateCommentReport,
response: res.clone(),
recipient_id: user.id,
websocket_id,
});
context.chat_server().do_send(SendModRoomMessage {
op: UserOperation::CreateCommentReport,
response: report,
community_id: comment_view.community.id,
websocket_id,
});
Ok(res)
}
}
/// Resolves or unresolves a comment report and notifies the moderators of the community
#[async_trait::async_trait(?Send)]
impl Perform for ResolveCommentReport {
type Response = ResolveCommentReportResponse;
async fn perform(
&self,
context: &Data<LemmyContext>,
websocket_id: Option<ConnectionId>,
) -> Result<ResolveCommentReportResponse, LemmyError> {
let data: &ResolveCommentReport = &self;
let user = get_user_from_jwt(&data.auth, context.pool()).await?;
let report_id = data.report_id;
let report = blocking(context.pool(), move |conn| {
CommentReportView::read(&conn, report_id)
})
.await??;
let user_id = user.id;
is_mod_or_admin(context.pool(), user_id, report.community.id).await?;
let resolved = data.resolved;
let resolve_fun = move |conn: &'_ _| {
if resolved {
CommentReport::resolve(conn, report_id, user_id)
} else {
CommentReport::unresolve(conn, report_id, user_id)
}
};
if blocking(context.pool(), resolve_fun).await?.is_err() {
return Err(APIError::err("couldnt_resolve_report").into());
};
let report_id = data.report_id;
let res = ResolveCommentReportResponse {
report_id,
resolved,
};
context.chat_server().do_send(SendModRoomMessage {
op: UserOperation::ResolveCommentReport,
response: res.clone(),
community_id: report.community.id,
websocket_id,
});
Ok(res)
}
}
/// Lists comment reports for a community if an id is supplied
/// or returns all comment reports for communities a user moderates
#[async_trait::async_trait(?Send)]
impl Perform for ListCommentReports {
type Response = ListCommentReportsResponse;
async fn perform(
&self,
context: &Data<LemmyContext>,
websocket_id: Option<ConnectionId>,
) -> Result<ListCommentReportsResponse, LemmyError> {
let data: &ListCommentReports = &self;
let user = get_user_from_jwt(&data.auth, context.pool()).await?;
let user_id = user.id;
let community_id = data.community;
let community_ids =
collect_moderated_communities(user_id, community_id, context.pool()).await?;
let page = data.page;
let limit = data.limit;
let comments = blocking(context.pool(), move |conn| {
CommentReportQueryBuilder::create(conn)
.community_ids(community_ids)
.page(page)
.limit(limit)
.list()
})
.await??;
let res = ListCommentReportsResponse { comments };
context.chat_server().do_send(SendUserRoomMessage {
op: UserOperation::ListCommentReports,
response: res.clone(),
recipient_id: user.id,
websocket_id,
});
Ok(res)
}
}

View File

@ -0,0 +1,66 @@
use actix_web::web::{Data, Json};
use lemmy_api_common::{
comment::{CommentResponse, DistinguishComment},
context::LemmyContext,
utils::{check_community_mod_action, check_community_user_action},
};
use lemmy_db_schema::{
source::comment::{Comment, CommentUpdateForm},
traits::Crud,
};
use lemmy_db_views::structs::{CommentView, LocalUserView};
use lemmy_utils::error::{LemmyErrorExt, LemmyErrorType, LemmyResult};
#[tracing::instrument(skip(context))]
pub async fn distinguish_comment(
data: Json<DistinguishComment>,
context: Data<LemmyContext>,
local_user_view: LocalUserView,
) -> LemmyResult<Json<CommentResponse>> {
let orig_comment = CommentView::read(&mut context.pool(), data.comment_id, None)
.await?
.ok_or(LemmyErrorType::CouldntFindComment)?;
check_community_user_action(
&local_user_view.person,
orig_comment.community.id,
&mut context.pool(),
)
.await?;
// Verify that only the creator can distinguish
if local_user_view.person.id != orig_comment.creator.id {
Err(LemmyErrorType::NoCommentEditAllowed)?
}
// Verify that only a mod or admin can distinguish a comment
check_community_mod_action(
&local_user_view.person,
orig_comment.community.id,
false,
&mut context.pool(),
)
.await?;
// Update the Comment
let form = CommentUpdateForm {
distinguished: Some(data.distinguished),
..Default::default()
};
Comment::update(&mut context.pool(), data.comment_id, &form)
.await
.with_lemmy_type(LemmyErrorType::CouldntUpdateComment)?;
let comment_view = CommentView::read(
&mut context.pool(),
data.comment_id,
Some(local_user_view.person.id),
)
.await?
.ok_or(LemmyErrorType::CouldntFindComment)?;
Ok(Json(CommentResponse {
comment_view,
recipient_ids: Vec::new(),
}))
}

View File

@ -0,0 +1,100 @@
use activitypub_federation::config::Data;
use actix_web::web::Json;
use lemmy_api_common::{
build_response::build_comment_response,
comment::{CommentResponse, CreateCommentLike},
context::LemmyContext,
send_activity::{ActivityChannel, SendActivityData},
utils::{check_bot_account, check_community_user_action, check_downvotes_enabled},
};
use lemmy_db_schema::{
newtypes::LocalUserId,
source::{
comment::{CommentLike, CommentLikeForm},
comment_reply::CommentReply,
local_site::LocalSite,
},
traits::Likeable,
};
use lemmy_db_views::structs::{CommentView, LocalUserView};
use lemmy_utils::error::{LemmyErrorExt, LemmyErrorType, LemmyResult};
use std::ops::Deref;
#[tracing::instrument(skip(context))]
pub async fn like_comment(
data: Json<CreateCommentLike>,
context: Data<LemmyContext>,
local_user_view: LocalUserView,
) -> LemmyResult<Json<CommentResponse>> {
let local_site = LocalSite::read(&mut context.pool()).await?;
let mut recipient_ids = Vec::<LocalUserId>::new();
// Don't do a downvote if site has downvotes disabled
check_downvotes_enabled(data.score, &local_site)?;
check_bot_account(&local_user_view.person)?;
let comment_id = data.comment_id;
let orig_comment = CommentView::read(&mut context.pool(), comment_id, None)
.await?
.ok_or(LemmyErrorType::CouldntFindComment)?;
check_community_user_action(
&local_user_view.person,
orig_comment.community.id,
&mut context.pool(),
)
.await?;
// Add parent poster or commenter to recipients
let comment_reply = CommentReply::read_by_comment(&mut context.pool(), comment_id).await;
if let Ok(Some(reply)) = comment_reply {
let recipient_id = reply.recipient_id;
if let Ok(Some(local_recipient)) =
LocalUserView::read_person(&mut context.pool(), recipient_id).await
{
recipient_ids.push(local_recipient.local_user.id);
}
}
let like_form = CommentLikeForm {
comment_id: data.comment_id,
post_id: orig_comment.post.id,
person_id: local_user_view.person.id,
score: data.score,
};
// Remove any likes first
let person_id = local_user_view.person.id;
CommentLike::remove(&mut context.pool(), person_id, comment_id).await?;
// Only add the like if the score isnt 0
let do_add = like_form.score != 0 && (like_form.score == 1 || like_form.score == -1);
if do_add {
CommentLike::like(&mut context.pool(), &like_form)
.await
.with_lemmy_type(LemmyErrorType::CouldntLikeComment)?;
}
ActivityChannel::submit_activity(
SendActivityData::LikePostOrComment {
object_id: orig_comment.comment.ap_id,
actor: local_user_view.person.clone(),
community: orig_comment.community,
score: data.score,
},
&context,
)
.await?;
Ok(Json(
build_comment_response(
context.deref(),
comment_id,
Some(local_user_view),
recipient_ids,
)
.await?,
))
}

View File

@ -0,0 +1,36 @@
use actix_web::web::{Data, Json, Query};
use lemmy_api_common::{
comment::{ListCommentLikes, ListCommentLikesResponse},
context::LemmyContext,
utils::is_mod_or_admin,
};
use lemmy_db_views::structs::{CommentView, LocalUserView, VoteView};
use lemmy_utils::{error::LemmyResult, LemmyErrorType};
/// Lists likes for a comment
#[tracing::instrument(skip(context))]
pub async fn list_comment_likes(
data: Query<ListCommentLikes>,
context: Data<LemmyContext>,
local_user_view: LocalUserView,
) -> LemmyResult<Json<ListCommentLikesResponse>> {
let comment_view = CommentView::read(
&mut context.pool(),
data.comment_id,
Some(local_user_view.person.id),
)
.await?
.ok_or(LemmyErrorType::CouldntFindComment)?;
is_mod_or_admin(
&mut context.pool(),
&local_user_view.person,
comment_view.community.id,
)
.await?;
let comment_likes =
VoteView::list_for_comment(&mut context.pool(), data.comment_id, data.page, data.limit).await?;
Ok(Json(ListCommentLikesResponse { comment_likes }))
}

View File

@ -0,0 +1,4 @@
pub mod distinguish;
pub mod like;
pub mod list_comment_likes;
pub mod save;

View File

@ -0,0 +1,44 @@
use actix_web::web::{Data, Json};
use lemmy_api_common::{
comment::{CommentResponse, SaveComment},
context::LemmyContext,
};
use lemmy_db_schema::{
source::comment::{CommentSaved, CommentSavedForm},
traits::Saveable,
};
use lemmy_db_views::structs::{CommentView, LocalUserView};
use lemmy_utils::error::{LemmyErrorExt, LemmyErrorType, LemmyResult};
#[tracing::instrument(skip(context))]
pub async fn save_comment(
data: Json<SaveComment>,
context: Data<LemmyContext>,
local_user_view: LocalUserView,
) -> LemmyResult<Json<CommentResponse>> {
let comment_saved_form = CommentSavedForm {
comment_id: data.comment_id,
person_id: local_user_view.person.id,
};
if data.save {
CommentSaved::save(&mut context.pool(), &comment_saved_form)
.await
.with_lemmy_type(LemmyErrorType::CouldntSaveComment)?;
} else {
CommentSaved::unsave(&mut context.pool(), &comment_saved_form)
.await
.with_lemmy_type(LemmyErrorType::CouldntSaveComment)?;
}
let comment_id = data.comment_id;
let person_id = local_user_view.person.id;
let comment_view = CommentView::read(&mut context.pool(), comment_id, Some(person_id))
.await?
.ok_or(LemmyErrorType::CouldntFindComment)?;
Ok(Json(CommentResponse {
comment_view,
recipient_ids: Vec::new(),
}))
}

View File

@ -0,0 +1,92 @@
use crate::check_report_reason;
use activitypub_federation::config::Data;
use actix_web::web::Json;
use lemmy_api_common::{
comment::{CommentReportResponse, CreateCommentReport},
context::LemmyContext,
send_activity::{ActivityChannel, SendActivityData},
utils::{
check_comment_deleted_or_removed,
check_community_user_action,
send_new_report_email_to_admins,
},
};
use lemmy_db_schema::{
source::{
comment_report::{CommentReport, CommentReportForm},
local_site::LocalSite,
},
traits::Reportable,
};
use lemmy_db_views::structs::{CommentReportView, CommentView, LocalUserView};
use lemmy_utils::error::{LemmyErrorExt, LemmyErrorType, LemmyResult};
/// Creates a comment report and notifies the moderators of the community
#[tracing::instrument(skip(context))]
pub async fn create_comment_report(
data: Json<CreateCommentReport>,
context: Data<LemmyContext>,
local_user_view: LocalUserView,
) -> LemmyResult<Json<CommentReportResponse>> {
let local_site = LocalSite::read(&mut context.pool()).await?;
let reason = data.reason.trim().to_string();
check_report_reason(&reason, &local_site)?;
let person_id = local_user_view.person.id;
let comment_id = data.comment_id;
let comment_view = CommentView::read(&mut context.pool(), comment_id, None)
.await?
.ok_or(LemmyErrorType::CouldntFindComment)?;
check_community_user_action(
&local_user_view.person,
comment_view.community.id,
&mut context.pool(),
)
.await?;
// Don't allow creating reports for removed / deleted comments
check_comment_deleted_or_removed(&comment_view.comment)?;
let report_form = CommentReportForm {
creator_id: person_id,
comment_id,
original_comment_text: comment_view.comment.content,
reason,
};
let report = CommentReport::report(&mut context.pool(), &report_form)
.await
.with_lemmy_type(LemmyErrorType::CouldntCreateReport)?;
let comment_report_view = CommentReportView::read(&mut context.pool(), report.id, person_id)
.await?
.ok_or(LemmyErrorType::CouldntFindCommentReport)?;
// Email the admins
if local_site.reports_email_admins {
send_new_report_email_to_admins(
&comment_report_view.creator.name,
&comment_report_view.comment_creator.name,
&mut context.pool(),
context.settings(),
)
.await?;
}
ActivityChannel::submit_activity(
SendActivityData::CreateReport {
object_id: comment_view.comment.ap_id.inner().clone(),
actor: local_user_view.person,
community: comment_view.community,
reason: data.reason.clone(),
},
&context,
)
.await?;
Ok(Json(CommentReportResponse {
comment_report_view,
}))
}

View File

@ -0,0 +1,37 @@
use actix_web::web::{Data, Json, Query};
use lemmy_api_common::{
comment::{ListCommentReports, ListCommentReportsResponse},
context::LemmyContext,
utils::check_community_mod_of_any_or_admin_action,
};
use lemmy_db_views::{comment_report_view::CommentReportQuery, structs::LocalUserView};
use lemmy_utils::error::LemmyResult;
/// Lists comment reports for a community if an id is supplied
/// or returns all comment reports for communities a user moderates
#[tracing::instrument(skip(context))]
pub async fn list_comment_reports(
data: Query<ListCommentReports>,
context: Data<LemmyContext>,
local_user_view: LocalUserView,
) -> LemmyResult<Json<ListCommentReportsResponse>> {
let community_id = data.community_id;
let comment_id = data.comment_id;
let unresolved_only = data.unresolved_only.unwrap_or_default();
check_community_mod_of_any_or_admin_action(&local_user_view, &mut context.pool()).await?;
let page = data.page;
let limit = data.limit;
let comment_reports = CommentReportQuery {
community_id,
comment_id,
unresolved_only,
page,
limit,
}
.list(&mut context.pool(), &local_user_view)
.await?;
Ok(Json(ListCommentReportsResponse { comment_reports }))
}

View File

@ -0,0 +1,3 @@
pub mod create;
pub mod list;
pub mod resolve;

View File

@ -0,0 +1,51 @@
use actix_web::web::{Data, Json};
use lemmy_api_common::{
comment::{CommentReportResponse, ResolveCommentReport},
context::LemmyContext,
utils::check_community_mod_action,
};
use lemmy_db_schema::{source::comment_report::CommentReport, traits::Reportable};
use lemmy_db_views::structs::{CommentReportView, LocalUserView};
use lemmy_utils::error::{LemmyErrorExt, LemmyErrorType, LemmyResult};
/// Resolves or unresolves a comment report and notifies the moderators of the community
#[tracing::instrument(skip(context))]
pub async fn resolve_comment_report(
data: Json<ResolveCommentReport>,
context: Data<LemmyContext>,
local_user_view: LocalUserView,
) -> LemmyResult<Json<CommentReportResponse>> {
let report_id = data.report_id;
let person_id = local_user_view.person.id;
let report = CommentReportView::read(&mut context.pool(), report_id, person_id)
.await?
.ok_or(LemmyErrorType::CouldntFindCommentReport)?;
let person_id = local_user_view.person.id;
check_community_mod_action(
&local_user_view.person,
report.community.id,
true,
&mut context.pool(),
)
.await?;
if data.resolved {
CommentReport::resolve(&mut context.pool(), report_id, person_id)
.await
.with_lemmy_type(LemmyErrorType::CouldntResolveReport)?;
} else {
CommentReport::unresolve(&mut context.pool(), report_id, person_id)
.await
.with_lemmy_type(LemmyErrorType::CouldntResolveReport)?;
}
let report_id = data.report_id;
let comment_report_view = CommentReportView::read(&mut context.pool(), report_id, person_id)
.await?
.ok_or(LemmyErrorType::CouldntFindCommentReport)?;
Ok(Json(CommentReportResponse {
comment_report_view,
}))
}

View File

@ -1,901 +0,0 @@
use crate::{
check_community_ban,
check_optional_url,
get_user_from_jwt,
get_user_from_jwt_opt,
is_admin,
is_mod_or_admin,
Perform,
};
use actix_web::web::Data;
use anyhow::Context;
use lemmy_apub::{
generate_apub_endpoint,
generate_followers_url,
generate_inbox_url,
generate_shared_inbox_url,
ActorType,
EndpointType,
};
use lemmy_db_queries::{
diesel_option_overwrite,
source::{
comment::Comment_,
community::{CommunityModerator_, Community_},
post::Post_,
},
ApubObject,
Bannable,
Crud,
Followable,
Joinable,
ListingType,
SortType,
};
use lemmy_db_schema::{
naive_now,
source::{comment::Comment, community::*, moderator::*, post::Post, site::*},
};
use lemmy_db_views::comment_view::CommentQueryBuilder;
use lemmy_db_views_actor::{
community_follower_view::CommunityFollowerView,
community_moderator_view::CommunityModeratorView,
community_view::{CommunityQueryBuilder, CommunityView},
user_view::UserViewSafe,
};
use lemmy_structs::{blocking, community::*};
use lemmy_utils::{
apub::generate_actor_keypair,
location_info,
utils::{check_slurs, check_slurs_opt, is_valid_community_name, naive_from_unix},
APIError,
ConnectionId,
LemmyError,
};
use lemmy_websocket::{
messages::{GetCommunityUsersOnline, SendCommunityRoomMessage},
LemmyContext,
UserOperation,
};
use std::str::FromStr;
#[async_trait::async_trait(?Send)]
impl Perform for GetCommunity {
type Response = GetCommunityResponse;
async fn perform(
&self,
context: &Data<LemmyContext>,
_websocket_id: Option<ConnectionId>,
) -> Result<GetCommunityResponse, LemmyError> {
let data: &GetCommunity = &self;
let user = get_user_from_jwt_opt(&data.auth, context.pool()).await?;
let user_id = user.map(|u| u.id);
let community_id = match data.id {
Some(id) => id,
None => {
let name = data.name.to_owned().unwrap_or_else(|| "main".to_string());
match blocking(context.pool(), move |conn| {
Community::read_from_name(conn, &name)
})
.await?
{
Ok(community) => community,
Err(_e) => return Err(APIError::err("couldnt_find_community").into()),
}
.id
}
};
let community_view = match blocking(context.pool(), move |conn| {
CommunityView::read(conn, community_id, user_id)
})
.await?
{
Ok(community) => community,
Err(_e) => return Err(APIError::err("couldnt_find_community").into()),
};
let moderators: Vec<CommunityModeratorView> = match blocking(context.pool(), move |conn| {
CommunityModeratorView::for_community(conn, community_id)
})
.await?
{
Ok(moderators) => moderators,
Err(_e) => return Err(APIError::err("couldnt_find_community").into()),
};
let online = context
.chat_server()
.send(GetCommunityUsersOnline { community_id })
.await
.unwrap_or(1);
let res = GetCommunityResponse {
community_view,
moderators,
online,
};
// Return the jwt
Ok(res)
}
}
#[async_trait::async_trait(?Send)]
impl Perform for CreateCommunity {
type Response = CommunityResponse;
async fn perform(
&self,
context: &Data<LemmyContext>,
_websocket_id: Option<ConnectionId>,
) -> Result<CommunityResponse, LemmyError> {
let data: &CreateCommunity = &self;
let user = get_user_from_jwt(&data.auth, context.pool()).await?;
check_slurs(&data.name)?;
check_slurs(&data.title)?;
check_slurs_opt(&data.description)?;
if !is_valid_community_name(&data.name) {
return Err(APIError::err("invalid_community_name").into());
}
// Double check for duplicate community actor_ids
let community_actor_id = generate_apub_endpoint(EndpointType::Community, &data.name)?;
let actor_id_cloned = community_actor_id.to_owned();
let community_dupe = blocking(context.pool(), move |conn| {
Community::read_from_apub_id(conn, &actor_id_cloned)
})
.await?;
if community_dupe.is_ok() {
return Err(APIError::err("community_already_exists").into());
}
// Check to make sure the icon and banners are urls
let icon = diesel_option_overwrite(&data.icon);
let banner = diesel_option_overwrite(&data.banner);
check_optional_url(&icon)?;
check_optional_url(&banner)?;
// When you create a community, make sure the user becomes a moderator and a follower
let keypair = generate_actor_keypair()?;
let community_form = CommunityForm {
name: data.name.to_owned(),
title: data.title.to_owned(),
description: data.description.to_owned(),
icon,
banner,
category_id: data.category_id,
creator_id: user.id,
removed: None,
deleted: None,
nsfw: data.nsfw,
updated: None,
actor_id: Some(community_actor_id.to_owned()),
local: true,
private_key: Some(keypair.private_key),
public_key: Some(keypair.public_key),
last_refreshed_at: None,
published: None,
followers_url: Some(generate_followers_url(&community_actor_id)?),
inbox_url: Some(generate_inbox_url(&community_actor_id)?),
shared_inbox_url: Some(Some(generate_shared_inbox_url(&community_actor_id)?)),
};
let inserted_community = match blocking(context.pool(), move |conn| {
Community::create(conn, &community_form)
})
.await?
{
Ok(community) => community,
Err(_e) => return Err(APIError::err("community_already_exists").into()),
};
// The community creator becomes a moderator
let community_moderator_form = CommunityModeratorForm {
community_id: inserted_community.id,
user_id: user.id,
};
let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form);
if blocking(context.pool(), join).await?.is_err() {
return Err(APIError::err("community_moderator_already_exists").into());
}
// Follow your own community
let community_follower_form = CommunityFollowerForm {
community_id: inserted_community.id,
user_id: user.id,
pending: false,
};
let follow = move |conn: &'_ _| CommunityFollower::follow(conn, &community_follower_form);
if blocking(context.pool(), follow).await?.is_err() {
return Err(APIError::err("community_follower_already_exists").into());
}
let user_id = user.id;
let community_view = blocking(context.pool(), move |conn| {
CommunityView::read(conn, inserted_community.id, Some(user_id))
})
.await??;
Ok(CommunityResponse { community_view })
}
}
#[async_trait::async_trait(?Send)]
impl Perform for EditCommunity {
type Response = CommunityResponse;
async fn perform(
&self,
context: &Data<LemmyContext>,
websocket_id: Option<ConnectionId>,
) -> Result<CommunityResponse, LemmyError> {
let data: &EditCommunity = &self;
let user = get_user_from_jwt(&data.auth, context.pool()).await?;
check_slurs(&data.title)?;
check_slurs_opt(&data.description)?;
// Verify its a mod (only mods can edit it)
let community_id = data.community_id;
let mods: Vec<i32> = blocking(context.pool(), move |conn| {
CommunityModeratorView::for_community(conn, community_id)
.map(|v| v.into_iter().map(|m| m.moderator.id).collect())
})
.await??;
if !mods.contains(&user.id) {
return Err(APIError::err("not_a_moderator").into());
}
let community_id = data.community_id;
let read_community = blocking(context.pool(), move |conn| {
Community::read(conn, community_id)
})
.await??;
let icon = diesel_option_overwrite(&data.icon);
let banner = diesel_option_overwrite(&data.banner);
check_optional_url(&icon)?;
check_optional_url(&banner)?;
let community_form = CommunityForm {
name: read_community.name,
title: data.title.to_owned(),
description: data.description.to_owned(),
icon,
banner,
category_id: data.category_id.to_owned(),
creator_id: read_community.creator_id,
removed: Some(read_community.removed),
deleted: Some(read_community.deleted),
nsfw: data.nsfw,
updated: Some(naive_now()),
actor_id: Some(read_community.actor_id),
local: read_community.local,
private_key: read_community.private_key,
public_key: read_community.public_key,
last_refreshed_at: None,
published: None,
followers_url: None,
inbox_url: None,
shared_inbox_url: None,
};
let community_id = data.community_id;
match blocking(context.pool(), move |conn| {
Community::update(conn, community_id, &community_form)
})
.await?
{
Ok(community) => community,
Err(_e) => return Err(APIError::err("couldnt_update_community").into()),
};
// TODO there needs to be some kind of an apub update
// process for communities and users
let community_id = data.community_id;
let user_id = user.id;
let community_view = blocking(context.pool(), move |conn| {
CommunityView::read(conn, community_id, Some(user_id))
})
.await??;
let res = CommunityResponse { community_view };
send_community_websocket(&res, context, websocket_id, UserOperation::EditCommunity);
Ok(res)
}
}
#[async_trait::async_trait(?Send)]
impl Perform for DeleteCommunity {
type Response = CommunityResponse;
async fn perform(
&self,
context: &Data<LemmyContext>,
websocket_id: Option<ConnectionId>,
) -> Result<CommunityResponse, LemmyError> {
let data: &DeleteCommunity = &self;
let user = get_user_from_jwt(&data.auth, context.pool()).await?;
// Verify its the creator (only a creator can delete the community)
let community_id = data.community_id;
let read_community = blocking(context.pool(), move |conn| {
Community::read(conn, community_id)
})
.await??;
if read_community.creator_id != user.id {
return Err(APIError::err("no_community_edit_allowed").into());
}
// Do the delete
let community_id = data.community_id;
let deleted = data.deleted;
let updated_community = match blocking(context.pool(), move |conn| {
Community::update_deleted(conn, community_id, deleted)
})
.await?
{
Ok(community) => community,
Err(_e) => return Err(APIError::err("couldnt_update_community").into()),
};
// Send apub messages
if deleted {
updated_community.send_delete(context).await?;
} else {
updated_community.send_undo_delete(context).await?;
}
let community_id = data.community_id;
let user_id = user.id;
let community_view = blocking(context.pool(), move |conn| {
CommunityView::read(conn, community_id, Some(user_id))
})
.await??;
let res = CommunityResponse { community_view };
send_community_websocket(&res, context, websocket_id, UserOperation::DeleteCommunity);
Ok(res)
}
}
#[async_trait::async_trait(?Send)]
impl Perform for RemoveCommunity {
type Response = CommunityResponse;
async fn perform(
&self,
context: &Data<LemmyContext>,
websocket_id: Option<ConnectionId>,
) -> Result<CommunityResponse, LemmyError> {
let data: &RemoveCommunity = &self;
let user = get_user_from_jwt(&data.auth, context.pool()).await?;
// Verify its an admin (only an admin can remove a community)
is_admin(context.pool(), user.id).await?;
// Do the remove
let community_id = data.community_id;
let removed = data.removed;
let updated_community = match blocking(context.pool(), move |conn| {
Community::update_removed(conn, community_id, removed)
})
.await?
{
Ok(community) => community,
Err(_e) => return Err(APIError::err("couldnt_update_community").into()),
};
// Mod tables
let expires = match data.expires {
Some(time) => Some(naive_from_unix(time)),
None => None,
};
let form = ModRemoveCommunityForm {
mod_user_id: user.id,
community_id: data.community_id,
removed: Some(removed),
reason: data.reason.to_owned(),
expires,
};
blocking(context.pool(), move |conn| {
ModRemoveCommunity::create(conn, &form)
})
.await??;
// Apub messages
if removed {
updated_community.send_remove(context).await?;
} else {
updated_community.send_undo_remove(context).await?;
}
let community_id = data.community_id;
let user_id = user.id;
let community_view = blocking(context.pool(), move |conn| {
CommunityView::read(conn, community_id, Some(user_id))
})
.await??;
let res = CommunityResponse { community_view };
send_community_websocket(&res, context, websocket_id, UserOperation::RemoveCommunity);
Ok(res)
}
}
#[async_trait::async_trait(?Send)]
impl Perform for ListCommunities {
type Response = ListCommunitiesResponse;
async fn perform(
&self,
context: &Data<LemmyContext>,
_websocket_id: Option<ConnectionId>,
) -> Result<ListCommunitiesResponse, LemmyError> {
let data: &ListCommunities = &self;
let user = get_user_from_jwt_opt(&data.auth, context.pool()).await?;
let user_id = match &user {
Some(user) => Some(user.id),
None => None,
};
let show_nsfw = match &user {
Some(user) => user.show_nsfw,
None => false,
};
let type_ = ListingType::from_str(&data.type_)?;
let sort = SortType::from_str(&data.sort)?;
let page = data.page;
let limit = data.limit;
let communities = blocking(context.pool(), move |conn| {
CommunityQueryBuilder::create(conn)
.listing_type(&type_)
.sort(&sort)
.show_nsfw(show_nsfw)
.my_user_id(user_id)
.page(page)
.limit(limit)
.list()
})
.await??;
// Return the jwt
Ok(ListCommunitiesResponse { communities })
}
}
#[async_trait::async_trait(?Send)]
impl Perform for FollowCommunity {
type Response = CommunityResponse;
async fn perform(
&self,
context: &Data<LemmyContext>,
_websocket_id: Option<ConnectionId>,
) -> Result<CommunityResponse, LemmyError> {
let data: &FollowCommunity = &self;
let user = get_user_from_jwt(&data.auth, context.pool()).await?;
let community_id = data.community_id;
let community = blocking(context.pool(), move |conn| {
Community::read(conn, community_id)
})
.await??;
let community_follower_form = CommunityFollowerForm {
community_id: data.community_id,
user_id: user.id,
pending: false,
};
if community.local {
if data.follow {
check_community_ban(user.id, community_id, context.pool()).await?;
let follow = move |conn: &'_ _| CommunityFollower::follow(conn, &community_follower_form);
if blocking(context.pool(), follow).await?.is_err() {
return Err(APIError::err("community_follower_already_exists").into());
}
} else {
let unfollow =
move |conn: &'_ _| CommunityFollower::unfollow(conn, &community_follower_form);
if blocking(context.pool(), unfollow).await?.is_err() {
return Err(APIError::err("community_follower_already_exists").into());
}
}
} else if data.follow {
// Dont actually add to the community followers here, because you need
// to wait for the accept
user.send_follow(&community.actor_id(), context).await?;
} else {
user.send_unfollow(&community.actor_id(), context).await?;
let unfollow = move |conn: &'_ _| CommunityFollower::unfollow(conn, &community_follower_form);
if blocking(context.pool(), unfollow).await?.is_err() {
return Err(APIError::err("community_follower_already_exists").into());
}
}
let community_id = data.community_id;
let user_id = user.id;
let mut community_view = blocking(context.pool(), move |conn| {
CommunityView::read(conn, community_id, Some(user_id))
})
.await??;
// TODO: this needs to return a "pending" state, until Accept is received from the remote server
// For now, just assume that remote follows are accepted.
// Otherwise, the subscribed will be null
if !community.local {
community_view.subscribed = data.follow;
}
Ok(CommunityResponse { community_view })
}
}
#[async_trait::async_trait(?Send)]
impl Perform for GetFollowedCommunities {
type Response = GetFollowedCommunitiesResponse;
async fn perform(
&self,
context: &Data<LemmyContext>,
_websocket_id: Option<ConnectionId>,
) -> Result<GetFollowedCommunitiesResponse, LemmyError> {
let data: &GetFollowedCommunities = &self;
let user = get_user_from_jwt(&data.auth, context.pool()).await?;
let user_id = user.id;
let communities = match blocking(context.pool(), move |conn| {
CommunityFollowerView::for_user(conn, user_id)
})
.await?
{
Ok(communities) => communities,
_ => return Err(APIError::err("system_err_login").into()),
};
// Return the jwt
Ok(GetFollowedCommunitiesResponse { communities })
}
}
#[async_trait::async_trait(?Send)]
impl Perform for BanFromCommunity {
type Response = BanFromCommunityResponse;
async fn perform(
&self,
context: &Data<LemmyContext>,
websocket_id: Option<ConnectionId>,
) -> Result<BanFromCommunityResponse, LemmyError> {
let data: &BanFromCommunity = &self;
let user = get_user_from_jwt(&data.auth, context.pool()).await?;
let community_id = data.community_id;
let banned_user_id = data.user_id;
// Verify that only mods or admins can ban
is_mod_or_admin(context.pool(), user.id, community_id).await?;
let community_user_ban_form = CommunityUserBanForm {
community_id: data.community_id,
user_id: data.user_id,
};
if data.ban {
let ban = move |conn: &'_ _| CommunityUserBan::ban(conn, &community_user_ban_form);
if blocking(context.pool(), ban).await?.is_err() {
return Err(APIError::err("community_user_already_banned").into());
}
// Also unsubscribe them from the community, if they are subscribed
let community_follower_form = CommunityFollowerForm {
community_id: data.community_id,
user_id: banned_user_id,
pending: false,
};
blocking(context.pool(), move |conn: &'_ _| {
CommunityFollower::unfollow(conn, &community_follower_form)
})
.await?
.ok();
} else {
let unban = move |conn: &'_ _| CommunityUserBan::unban(conn, &community_user_ban_form);
if blocking(context.pool(), unban).await?.is_err() {
return Err(APIError::err("community_user_already_banned").into());
}
}
// Remove/Restore their data if that's desired
if data.remove_data {
// Posts
blocking(context.pool(), move |conn: &'_ _| {
Post::update_removed_for_creator(conn, banned_user_id, Some(community_id), true)
})
.await??;
// Comments
// TODO Diesel doesn't allow updates with joins, so this has to be a loop
let comments = blocking(context.pool(), move |conn| {
CommentQueryBuilder::create(conn)
.creator_id(banned_user_id)
.community_id(community_id)
.limit(std::i64::MAX)
.list()
})
.await??;
for comment_view in &comments {
let comment_id = comment_view.comment.id;
blocking(context.pool(), move |conn: &'_ _| {
Comment::update_removed(conn, comment_id, true)
})
.await??;
}
}
// Mod tables
// TODO eventually do correct expires
let expires = match data.expires {
Some(time) => Some(naive_from_unix(time)),
None => None,
};
let form = ModBanFromCommunityForm {
mod_user_id: user.id,
other_user_id: data.user_id,
community_id: data.community_id,
reason: data.reason.to_owned(),
banned: Some(data.ban),
expires,
};
blocking(context.pool(), move |conn| {
ModBanFromCommunity::create(conn, &form)
})
.await??;
let user_id = data.user_id;
let user_view = blocking(context.pool(), move |conn| {
UserViewSafe::read(conn, user_id)
})
.await??;
let res = BanFromCommunityResponse {
user_view,
banned: data.ban,
};
context.chat_server().do_send(SendCommunityRoomMessage {
op: UserOperation::BanFromCommunity,
response: res.clone(),
community_id,
websocket_id,
});
Ok(res)
}
}
#[async_trait::async_trait(?Send)]
impl Perform for AddModToCommunity {
type Response = AddModToCommunityResponse;
async fn perform(
&self,
context: &Data<LemmyContext>,
websocket_id: Option<ConnectionId>,
) -> Result<AddModToCommunityResponse, LemmyError> {
let data: &AddModToCommunity = &self;
let user = get_user_from_jwt(&data.auth, context.pool()).await?;
let community_moderator_form = CommunityModeratorForm {
community_id: data.community_id,
user_id: data.user_id,
};
let community_id = data.community_id;
// Verify that only mods or admins can add mod
is_mod_or_admin(context.pool(), user.id, community_id).await?;
if data.added {
let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form);
if blocking(context.pool(), join).await?.is_err() {
return Err(APIError::err("community_moderator_already_exists").into());
}
} else {
let leave = move |conn: &'_ _| CommunityModerator::leave(conn, &community_moderator_form);
if blocking(context.pool(), leave).await?.is_err() {
return Err(APIError::err("community_moderator_already_exists").into());
}
}
// Mod tables
let form = ModAddCommunityForm {
mod_user_id: user.id,
other_user_id: data.user_id,
community_id: data.community_id,
removed: Some(!data.added),
};
blocking(context.pool(), move |conn| {
ModAddCommunity::create(conn, &form)
})
.await??;
let community_id = data.community_id;
let moderators = blocking(context.pool(), move |conn| {
CommunityModeratorView::for_community(conn, community_id)
})
.await??;
let res = AddModToCommunityResponse { moderators };
context.chat_server().do_send(SendCommunityRoomMessage {
op: UserOperation::AddModToCommunity,
response: res.clone(),
community_id,
websocket_id,
});
Ok(res)
}
}
#[async_trait::async_trait(?Send)]
impl Perform for TransferCommunity {
type Response = GetCommunityResponse;
async fn perform(
&self,
context: &Data<LemmyContext>,
_websocket_id: Option<ConnectionId>,
) -> Result<GetCommunityResponse, LemmyError> {
let data: &TransferCommunity = &self;
let user = get_user_from_jwt(&data.auth, context.pool()).await?;
let community_id = data.community_id;
let read_community = blocking(context.pool(), move |conn| {
Community::read(conn, community_id)
})
.await??;
let site_creator_id = blocking(context.pool(), move |conn| {
Site::read(conn, 1).map(|s| s.creator_id)
})
.await??;
let mut admins = blocking(context.pool(), move |conn| UserViewSafe::admins(conn)).await??;
// Making sure the creator, if an admin, is at the top
let creator_index = admins
.iter()
.position(|r| r.user.id == site_creator_id)
.context(location_info!())?;
let creator_user = admins.remove(creator_index);
admins.insert(0, creator_user);
// Make sure user is the creator, or an admin
if user.id != read_community.creator_id
&& !admins.iter().map(|a| a.user.id).any(|x| x == user.id)
{
return Err(APIError::err("not_an_admin").into());
}
let community_id = data.community_id;
let new_creator = data.user_id;
let update = move |conn: &'_ _| Community::update_creator(conn, community_id, new_creator);
if blocking(context.pool(), update).await?.is_err() {
return Err(APIError::err("couldnt_update_community").into());
};
// You also have to re-do the community_moderator table, reordering it.
let community_id = data.community_id;
let mut community_mods = blocking(context.pool(), move |conn| {
CommunityModeratorView::for_community(conn, community_id)
})
.await??;
let creator_index = community_mods
.iter()
.position(|r| r.moderator.id == data.user_id)
.context(location_info!())?;
let creator_user = community_mods.remove(creator_index);
community_mods.insert(0, creator_user);
let community_id = data.community_id;
blocking(context.pool(), move |conn| {
CommunityModerator::delete_for_community(conn, community_id)
})
.await??;
// TODO: this should probably be a bulk operation
for cmod in &community_mods {
let community_moderator_form = CommunityModeratorForm {
community_id: cmod.community.id,
user_id: cmod.moderator.id,
};
let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form);
if blocking(context.pool(), join).await?.is_err() {
return Err(APIError::err("community_moderator_already_exists").into());
}
}
// Mod tables
let form = ModAddCommunityForm {
mod_user_id: user.id,
other_user_id: data.user_id,
community_id: data.community_id,
removed: Some(false),
};
blocking(context.pool(), move |conn| {
ModAddCommunity::create(conn, &form)
})
.await??;
let community_id = data.community_id;
let user_id = user.id;
let community_view = match blocking(context.pool(), move |conn| {
CommunityView::read(conn, community_id, Some(user_id))
})
.await?
{
Ok(community) => community,
Err(_e) => return Err(APIError::err("couldnt_find_community").into()),
};
let community_id = data.community_id;
let moderators = match blocking(context.pool(), move |conn| {
CommunityModeratorView::for_community(conn, community_id)
})
.await?
{
Ok(moderators) => moderators,
Err(_e) => return Err(APIError::err("couldnt_find_community").into()),
};
// Return the jwt
Ok(GetCommunityResponse {
community_view,
moderators,
online: 0,
})
}
}
fn send_community_websocket(
res: &CommunityResponse,
context: &Data<LemmyContext>,
websocket_id: Option<ConnectionId>,
op: UserOperation,
) {
// Strip out the user id and subscribed when sending to others
let mut res_sent = res.clone();
res_sent.community_view.subscribed = false;
context.chat_server().do_send(SendCommunityRoomMessage {
op,
response: res_sent,
community_id: res.community_view.community.id,
websocket_id,
});
}

View File

@ -0,0 +1,97 @@
use activitypub_federation::config::Data;
use actix_web::web::Json;
use lemmy_api_common::{
community::{AddModToCommunity, AddModToCommunityResponse},
context::LemmyContext,
send_activity::{ActivityChannel, SendActivityData},
utils::check_community_mod_action,
};
use lemmy_db_schema::{
source::{
community::{Community, CommunityModerator, CommunityModeratorForm},
moderator::{ModAddCommunity, ModAddCommunityForm},
},
traits::{Crud, Joinable},
};
use lemmy_db_views::structs::LocalUserView;
use lemmy_db_views_actor::structs::CommunityModeratorView;
use lemmy_utils::error::{LemmyErrorExt, LemmyErrorType, LemmyResult};
#[tracing::instrument(skip(context))]
pub async fn add_mod_to_community(
data: Json<AddModToCommunity>,
context: Data<LemmyContext>,
local_user_view: LocalUserView,
) -> LemmyResult<Json<AddModToCommunityResponse>> {
let community_id = data.community_id;
// Verify that only mods or admins can add mod
check_community_mod_action(
&local_user_view.person,
community_id,
false,
&mut context.pool(),
)
.await?;
let community = Community::read(&mut context.pool(), community_id)
.await?
.ok_or(LemmyErrorType::CouldntFindCommunity)?;
// If user is admin and community is remote, explicitly check that he is a
// moderator. This is necessary because otherwise the action would be rejected
// by the community's home instance.
if local_user_view.local_user.admin && !community.local {
let is_mod = CommunityModeratorView::is_community_moderator(
&mut context.pool(),
community.id,
local_user_view.person.id,
)
.await?;
if !is_mod {
Err(LemmyErrorType::NotAModerator)?
}
}
// Update in local database
let community_moderator_form = CommunityModeratorForm {
community_id: data.community_id,
person_id: data.person_id,
};
if data.added {
CommunityModerator::join(&mut context.pool(), &community_moderator_form)
.await
.with_lemmy_type(LemmyErrorType::CommunityModeratorAlreadyExists)?;
} else {
CommunityModerator::leave(&mut context.pool(), &community_moderator_form)
.await
.with_lemmy_type(LemmyErrorType::CommunityModeratorAlreadyExists)?;
}
// Mod tables
let form = ModAddCommunityForm {
mod_person_id: local_user_view.person.id,
other_person_id: data.person_id,
community_id: data.community_id,
removed: Some(!data.added),
};
ModAddCommunity::create(&mut context.pool(), &form).await?;
// Note: in case a remote mod is added, this returns the old moderators list, it will only get
// updated once we receive an activity from the community (like `Announce/Add/Moderator`)
let community_id = data.community_id;
let moderators = CommunityModeratorView::for_community(&mut context.pool(), community_id).await?;
ActivityChannel::submit_activity(
SendActivityData::AddModToCommunity {
moderator: local_user_view.person,
community_id: data.community_id,
target: data.person_id,
added: data.added,
},
&context,
)
.await?;
Ok(Json(AddModToCommunityResponse { moderators }))
}

View File

@ -0,0 +1,111 @@
use activitypub_federation::config::Data;
use actix_web::web::Json;
use lemmy_api_common::{
community::{BanFromCommunity, BanFromCommunityResponse},
context::LemmyContext,
send_activity::{ActivityChannel, SendActivityData},
utils::{check_community_mod_action, check_expire_time, remove_user_data_in_community},
};
use lemmy_db_schema::{
source::{
community::{
CommunityFollower,
CommunityFollowerForm,
CommunityPersonBan,
CommunityPersonBanForm,
},
moderator::{ModBanFromCommunity, ModBanFromCommunityForm},
},
traits::{Bannable, Crud, Followable},
};
use lemmy_db_views::structs::LocalUserView;
use lemmy_db_views_actor::structs::PersonView;
use lemmy_utils::{
error::{LemmyErrorExt, LemmyErrorType, LemmyResult},
utils::validation::is_valid_body_field,
};
#[tracing::instrument(skip(context))]
pub async fn ban_from_community(
data: Json<BanFromCommunity>,
context: Data<LemmyContext>,
local_user_view: LocalUserView,
) -> LemmyResult<Json<BanFromCommunityResponse>> {
let banned_person_id = data.person_id;
let remove_data = data.remove_data.unwrap_or(false);
let expires = check_expire_time(data.expires)?;
// Verify that only mods or admins can ban
check_community_mod_action(
&local_user_view.person,
data.community_id,
false,
&mut context.pool(),
)
.await?;
is_valid_body_field(&data.reason, false)?;
let community_user_ban_form = CommunityPersonBanForm {
community_id: data.community_id,
person_id: data.person_id,
expires: Some(expires),
};
if data.ban {
CommunityPersonBan::ban(&mut context.pool(), &community_user_ban_form)
.await
.with_lemmy_type(LemmyErrorType::CommunityUserAlreadyBanned)?;
// Also unsubscribe them from the community, if they are subscribed
let community_follower_form = CommunityFollowerForm {
community_id: data.community_id,
person_id: banned_person_id,
pending: false,
};
CommunityFollower::unfollow(&mut context.pool(), &community_follower_form)
.await
.ok();
} else {
CommunityPersonBan::unban(&mut context.pool(), &community_user_ban_form)
.await
.with_lemmy_type(LemmyErrorType::CommunityUserAlreadyBanned)?;
}
// Remove/Restore their data if that's desired
if remove_data {
remove_user_data_in_community(data.community_id, banned_person_id, &mut context.pool()).await?;
}
// Mod tables
let form = ModBanFromCommunityForm {
mod_person_id: local_user_view.person.id,
other_person_id: data.person_id,
community_id: data.community_id,
reason: data.reason.clone(),
banned: Some(data.ban),
expires,
};
ModBanFromCommunity::create(&mut context.pool(), &form).await?;
let person_view = PersonView::read(&mut context.pool(), data.person_id)
.await?
.ok_or(LemmyErrorType::CouldntFindPerson)?;
ActivityChannel::submit_activity(
SendActivityData::BanFromCommunity {
moderator: local_user_view.person,
community_id: data.community_id,
target: person_view.person.clone(),
data: data.0.clone(),
},
&context,
)
.await?;
Ok(Json(BanFromCommunityResponse {
person_view,
banned: data.ban,
}))
}

View File

@ -0,0 +1,72 @@
use activitypub_federation::config::Data;
use actix_web::web::Json;
use lemmy_api_common::{
community::{BlockCommunity, BlockCommunityResponse},
context::LemmyContext,
send_activity::{ActivityChannel, SendActivityData},
};
use lemmy_db_schema::{
source::{
community::{CommunityFollower, CommunityFollowerForm},
community_block::{CommunityBlock, CommunityBlockForm},
},
traits::{Blockable, Followable},
};
use lemmy_db_views::structs::LocalUserView;
use lemmy_db_views_actor::structs::CommunityView;
use lemmy_utils::error::{LemmyErrorExt, LemmyErrorType, LemmyResult};
#[tracing::instrument(skip(context))]
pub async fn block_community(
data: Json<BlockCommunity>,
context: Data<LemmyContext>,
local_user_view: LocalUserView,
) -> LemmyResult<Json<BlockCommunityResponse>> {
let community_id = data.community_id;
let person_id = local_user_view.person.id;
let community_block_form = CommunityBlockForm {
person_id,
community_id,
};
if data.block {
CommunityBlock::block(&mut context.pool(), &community_block_form)
.await
.with_lemmy_type(LemmyErrorType::CommunityBlockAlreadyExists)?;
// Also, unfollow the community, and send a federated unfollow
let community_follower_form = CommunityFollowerForm {
community_id: data.community_id,
person_id,
pending: false,
};
CommunityFollower::unfollow(&mut context.pool(), &community_follower_form)
.await
.ok();
} else {
CommunityBlock::unblock(&mut context.pool(), &community_block_form)
.await
.with_lemmy_type(LemmyErrorType::CommunityBlockAlreadyExists)?;
}
let community_view =
CommunityView::read(&mut context.pool(), community_id, Some(person_id), false)
.await?
.ok_or(LemmyErrorType::CouldntFindCommunity)?;
ActivityChannel::submit_activity(
SendActivityData::FollowCommunity(
community_view.community.clone(),
local_user_view.person.clone(),
false,
),
&context,
)
.await?;
Ok(Json(BlockCommunityResponse {
blocked: data.block,
community_view,
}))
}

View File

@ -0,0 +1,77 @@
use activitypub_federation::config::Data;
use actix_web::web::Json;
use lemmy_api_common::{
community::{CommunityResponse, FollowCommunity},
context::LemmyContext,
send_activity::{ActivityChannel, SendActivityData},
utils::check_community_user_action,
};
use lemmy_db_schema::{
source::{
actor_language::CommunityLanguage,
community::{Community, CommunityFollower, CommunityFollowerForm},
},
traits::{Crud, Followable},
};
use lemmy_db_views::structs::LocalUserView;
use lemmy_db_views_actor::structs::CommunityView;
use lemmy_utils::error::{LemmyErrorExt, LemmyErrorType, LemmyResult};
#[tracing::instrument(skip(context))]
pub async fn follow_community(
data: Json<FollowCommunity>,
context: Data<LemmyContext>,
local_user_view: LocalUserView,
) -> LemmyResult<Json<CommunityResponse>> {
let community = Community::read(&mut context.pool(), data.community_id)
.await?
.ok_or(LemmyErrorType::CouldntFindCommunity)?;
let mut community_follower_form = CommunityFollowerForm {
community_id: community.id,
person_id: local_user_view.person.id,
pending: false,
};
if data.follow {
if community.local {
check_community_user_action(&local_user_view.person, community.id, &mut context.pool())
.await?;
CommunityFollower::follow(&mut context.pool(), &community_follower_form)
.await
.with_lemmy_type(LemmyErrorType::CommunityFollowerAlreadyExists)?;
} else {
// Mark as pending, the actual federation activity is sent via `SendActivity` handler
community_follower_form.pending = true;
CommunityFollower::follow(&mut context.pool(), &community_follower_form)
.await
.with_lemmy_type(LemmyErrorType::CommunityFollowerAlreadyExists)?;
}
} else {
CommunityFollower::unfollow(&mut context.pool(), &community_follower_form)
.await
.with_lemmy_type(LemmyErrorType::CommunityFollowerAlreadyExists)?;
}
if !community.local {
ActivityChannel::submit_activity(
SendActivityData::FollowCommunity(community, local_user_view.person.clone(), data.follow),
&context,
)
.await?;
}
let community_id = data.community_id;
let person_id = local_user_view.person.id;
let community_view =
CommunityView::read(&mut context.pool(), community_id, Some(person_id), false)
.await?
.ok_or(LemmyErrorType::CouldntFindCommunity)?;
let discussion_languages = CommunityLanguage::read(&mut context.pool(), community_id).await?;
Ok(Json(CommunityResponse {
community_view,
discussion_languages,
}))
}

View File

@ -0,0 +1,55 @@
use activitypub_federation::config::Data;
use actix_web::web::Json;
use lemmy_api_common::{
community::HideCommunity,
context::LemmyContext,
send_activity::{ActivityChannel, SendActivityData},
utils::is_admin,
SuccessResponse,
};
use lemmy_db_schema::{
source::{
community::{Community, CommunityUpdateForm},
moderator::{ModHideCommunity, ModHideCommunityForm},
},
traits::Crud,
};
use lemmy_db_views::structs::LocalUserView;
use lemmy_utils::error::{LemmyErrorExt, LemmyErrorType, LemmyResult};
#[tracing::instrument(skip(context))]
pub async fn hide_community(
data: Json<HideCommunity>,
context: Data<LemmyContext>,
local_user_view: LocalUserView,
) -> LemmyResult<Json<SuccessResponse>> {
// Verify its a admin (only admin can hide or unhide it)
is_admin(&local_user_view)?;
let community_form = CommunityUpdateForm {
hidden: Some(data.hidden),
..Default::default()
};
let mod_hide_community_form = ModHideCommunityForm {
community_id: data.community_id,
mod_person_id: local_user_view.person.id,
reason: data.reason.clone(),
hidden: Some(data.hidden),
};
let community_id = data.community_id;
let community = Community::update(&mut context.pool(), community_id, &community_form)
.await
.with_lemmy_type(LemmyErrorType::CouldntUpdateCommunityHiddenStatus)?;
ModHideCommunity::create(&mut context.pool(), &mod_hide_community_form).await?;
ActivityChannel::submit_activity(
SendActivityData::UpdateCommunity(local_user_view.person.clone(), community),
&context,
)
.await?;
Ok(Json(SuccessResponse::default()))
}

View File

@ -0,0 +1,6 @@
pub mod add_mod;
pub mod ban;
pub mod block;
pub mod follow;
pub mod hide;
pub mod transfer;

View File

@ -0,0 +1,97 @@
use actix_web::web::{Data, Json};
use anyhow::Context;
use lemmy_api_common::{
community::{GetCommunityResponse, TransferCommunity},
context::LemmyContext,
utils::{check_community_user_action, is_admin, is_top_mod},
};
use lemmy_db_schema::{
source::{
community::{CommunityModerator, CommunityModeratorForm},
moderator::{ModTransferCommunity, ModTransferCommunityForm},
},
traits::{Crud, Joinable},
};
use lemmy_db_views::structs::LocalUserView;
use lemmy_db_views_actor::structs::{CommunityModeratorView, CommunityView};
use lemmy_utils::{
error::{LemmyErrorExt, LemmyErrorType, LemmyResult},
location_info,
};
// TODO: we dont do anything for federation here, it should be updated the next time the community
// gets fetched. i hope we can get rid of the community creator role soon.
#[tracing::instrument(skip(context))]
pub async fn transfer_community(
data: Json<TransferCommunity>,
context: Data<LemmyContext>,
local_user_view: LocalUserView,
) -> LemmyResult<Json<GetCommunityResponse>> {
let community_id = data.community_id;
let mut community_mods =
CommunityModeratorView::for_community(&mut context.pool(), community_id).await?;
check_community_user_action(&local_user_view.person, community_id, &mut context.pool()).await?;
// Make sure transferrer is either the top community mod, or an admin
if !(is_top_mod(&local_user_view, &community_mods).is_ok() || is_admin(&local_user_view).is_ok())
{
Err(LemmyErrorType::NotAnAdmin)?
}
// You have to re-do the community_moderator table, reordering it.
// Add the transferee to the top
let creator_index = community_mods
.iter()
.position(|r| r.moderator.id == data.person_id)
.context(location_info!())?;
let creator_person = community_mods.remove(creator_index);
community_mods.insert(0, creator_person);
// Delete all the mods
let community_id = data.community_id;
CommunityModerator::delete_for_community(&mut context.pool(), community_id).await?;
// TODO: this should probably be a bulk operation
// Re-add the mods, in the new order
for cmod in &community_mods {
let community_moderator_form = CommunityModeratorForm {
community_id: cmod.community.id,
person_id: cmod.moderator.id,
};
CommunityModerator::join(&mut context.pool(), &community_moderator_form)
.await
.with_lemmy_type(LemmyErrorType::CommunityModeratorAlreadyExists)?;
}
// Mod tables
let form = ModTransferCommunityForm {
mod_person_id: local_user_view.person.id,
other_person_id: data.person_id,
community_id: data.community_id,
};
ModTransferCommunity::create(&mut context.pool(), &form).await?;
let community_id = data.community_id;
let person_id = local_user_view.person.id;
let community_view =
CommunityView::read(&mut context.pool(), community_id, Some(person_id), false)
.await?
.ok_or(LemmyErrorType::CouldntFindCommunity)?;
let community_id = data.community_id;
let moderators = CommunityModeratorView::for_community(&mut context.pool(), community_id)
.await
.with_lemmy_type(LemmyErrorType::CouldntFindCommunity)?;
// Return the jwt
Ok(Json(GetCommunityResponse {
community_view,
site: None,
moderators,
discussion_languages: vec![],
}))
}

View File

@ -1,469 +1,277 @@
use actix_web::{web, web::Data};
use lemmy_db_queries::{
use activitypub_federation::config::Data;
use actix_web::{http::header::Header, HttpRequest};
use actix_web_httpauth::headers::authorization::{Authorization, Bearer};
use base64::{engine::general_purpose::STANDARD_NO_PAD as base64, Engine};
use captcha::Captcha;
use lemmy_api_common::{
claims::Claims,
community::BanFromCommunity,
context::LemmyContext,
send_activity::{ActivityChannel, SendActivityData},
utils::{check_expire_time, check_user_valid, local_site_to_slur_regex, AUTH_COOKIE_NAME},
};
use lemmy_db_schema::{
source::{
community::{CommunityModerator_, Community_},
site::Site_,
user::UserSafeSettings_,
community::{
CommunityFollower,
CommunityFollowerForm,
CommunityPersonBan,
CommunityPersonBanForm,
},
local_site::LocalSite,
moderator::{ModBanFromCommunity, ModBanFromCommunityForm},
person::Person,
},
Crud,
DbPool,
traits::{Bannable, Crud, Followable},
};
use lemmy_db_schema::source::{
community::{Community, CommunityModerator},
post::Post,
site::Site,
user::{UserSafeSettings, User_},
use lemmy_db_views::structs::LocalUserView;
use lemmy_utils::{
error::{LemmyErrorExt, LemmyErrorExt2, LemmyErrorType, LemmyResult},
utils::slurs::check_slurs,
};
use lemmy_db_views_actor::{
community_user_ban_view::CommunityUserBanView,
community_view::CommunityView,
};
use lemmy_structs::{blocking, comment::*, community::*, post::*, site::*, user::*, websocket::*};
use lemmy_utils::{claims::Claims, settings::Settings, APIError, ConnectionId, LemmyError};
use lemmy_websocket::{serialize_websocket_message, LemmyContext, UserOperation};
use serde::Deserialize;
use std::process::Command;
use url::Url;
use std::io::Cursor;
use totp_rs::{Secret, TOTP};
pub mod comment;
pub mod comment_report;
pub mod community;
pub mod local_user;
pub mod post;
pub mod routes;
pub mod post_report;
pub mod private_message;
pub mod private_message_report;
pub mod site;
pub mod user;
pub mod websocket;
pub mod sitemap;
#[async_trait::async_trait(?Send)]
pub trait Perform {
type Response: serde::ser::Serialize + Send;
/// Converts the captcha to a base64 encoded wav audio file
#[allow(deprecated)]
pub(crate) fn captcha_as_wav_base64(captcha: &Captcha) -> LemmyResult<String> {
let letters = captcha.as_wav();
async fn perform(
&self,
context: &Data<LemmyContext>,
websocket_id: Option<ConnectionId>,
) -> Result<Self::Response, LemmyError>;
}
pub(crate) async fn is_mod_or_admin(
pool: &DbPool,
user_id: i32,
community_id: i32,
) -> Result<(), LemmyError> {
let is_mod_or_admin = blocking(pool, move |conn| {
CommunityView::is_mod_or_admin(conn, user_id, community_id)
})
.await?;
if !is_mod_or_admin {
return Err(APIError::err("not_a_mod_or_admin").into());
// Decode each wav file, concatenate the samples
let mut concat_samples: Vec<i16> = Vec::new();
let mut any_header: Option<wav::Header> = None;
for letter in letters {
let mut cursor = Cursor::new(letter.unwrap_or_default());
let (header, samples) = wav::read(&mut cursor)?;
any_header = Some(header);
if let Some(samples16) = samples.as_sixteen() {
concat_samples.extend(samples16);
} else {
Err(LemmyErrorType::CouldntCreateAudioCaptcha)?
}
}
Ok(())
}
pub async fn is_admin(pool: &DbPool, user_id: i32) -> Result<(), LemmyError> {
let user = blocking(pool, move |conn| User_::read(conn, user_id)).await??;
if !user.admin {
return Err(APIError::err("not_an_admin").into());
}
Ok(())
}
pub(crate) async fn get_post(post_id: i32, pool: &DbPool) -> Result<Post, LemmyError> {
match blocking(pool, move |conn| Post::read(conn, post_id)).await? {
Ok(post) => Ok(post),
Err(_e) => Err(APIError::err("couldnt_find_post").into()),
// Encode the concatenated result as a wav file
let mut output_buffer = Cursor::new(vec![]);
if let Some(header) = any_header {
wav::write(
header,
&wav::BitDepth::Sixteen(concat_samples),
&mut output_buffer,
)
.with_lemmy_type(LemmyErrorType::CouldntCreateAudioCaptcha)?;
Ok(base64.encode(output_buffer.into_inner()))
} else {
Err(LemmyErrorType::CouldntCreateAudioCaptcha)?
}
}
pub(crate) async fn get_user_from_jwt(jwt: &str, pool: &DbPool) -> Result<User_, LemmyError> {
let claims = match Claims::decode(&jwt) {
Ok(claims) => claims.claims,
Err(_e) => return Err(APIError::err("not_logged_in").into()),
};
let user_id = claims.id;
let user = blocking(pool, move |conn| User_::read(conn, user_id)).await??;
// Check for a site ban
if user.banned {
return Err(APIError::err("site_ban").into());
}
Ok(user)
}
/// Check size of report
pub(crate) fn check_report_reason(reason: &str, local_site: &LocalSite) -> LemmyResult<()> {
let slur_regex = &local_site_to_slur_regex(local_site);
pub(crate) async fn get_user_from_jwt_opt(
jwt: &Option<String>,
pool: &DbPool,
) -> Result<Option<User_>, LemmyError> {
match jwt {
Some(jwt) => Ok(Some(get_user_from_jwt(jwt, pool).await?)),
None => Ok(None),
}
}
pub(crate) async fn get_user_safe_settings_from_jwt(
jwt: &str,
pool: &DbPool,
) -> Result<UserSafeSettings, LemmyError> {
let claims = match Claims::decode(&jwt) {
Ok(claims) => claims.claims,
Err(_e) => return Err(APIError::err("not_logged_in").into()),
};
let user_id = claims.id;
let user = blocking(pool, move |conn| UserSafeSettings::read(conn, user_id)).await??;
// Check for a site ban
if user.banned {
return Err(APIError::err("site_ban").into());
}
Ok(user)
}
pub(crate) async fn get_user_safe_settings_from_jwt_opt(
jwt: &Option<String>,
pool: &DbPool,
) -> Result<Option<UserSafeSettings>, LemmyError> {
match jwt {
Some(jwt) => Ok(Some(get_user_safe_settings_from_jwt(jwt, pool).await?)),
None => Ok(None),
}
}
pub(crate) async fn check_community_ban(
user_id: i32,
community_id: i32,
pool: &DbPool,
) -> Result<(), LemmyError> {
let is_banned = move |conn: &'_ _| CommunityUserBanView::get(conn, user_id, community_id).is_ok();
if blocking(pool, is_banned).await? {
Err(APIError::err("community_ban").into())
check_slurs(reason, slur_regex)?;
if reason.is_empty() {
Err(LemmyErrorType::ReportReasonRequired)?
} else if reason.chars().count() > 1000 {
Err(LemmyErrorType::ReportTooLong)?
} else {
Ok(())
}
}
pub(crate) async fn check_downvotes_enabled(score: i16, pool: &DbPool) -> Result<(), LemmyError> {
if score == -1 {
let site = blocking(pool, move |conn| Site::read_simple(conn)).await??;
if !site.enable_downvotes {
return Err(APIError::err("downvotes_disabled").into());
}
pub fn read_auth_token(req: &HttpRequest) -> LemmyResult<Option<String>> {
// Try reading jwt from auth header
if let Ok(header) = Authorization::<Bearer>::parse(req) {
Ok(Some(header.as_ref().token().to_string()))
}
Ok(())
}
/// Returns a list of communities that the user moderates
/// or if a community_id is supplied validates the user is a moderator
/// of that community and returns the community id in a vec
///
/// * `user_id` - the user id of the moderator
/// * `community_id` - optional community id to check for moderator privileges
/// * `pool` - the diesel db pool
pub(crate) async fn collect_moderated_communities(
user_id: i32,
community_id: Option<i32>,
pool: &DbPool,
) -> Result<Vec<i32>, LemmyError> {
if let Some(community_id) = community_id {
// if the user provides a community_id, just check for mod/admin privileges
is_mod_or_admin(pool, user_id, community_id).await?;
Ok(vec![community_id])
} else {
let ids = blocking(pool, move |conn: &'_ _| {
CommunityModerator::get_user_moderated_communities(conn, user_id)
})
.await??;
Ok(ids)
// If that fails, try to read from cookie
else if let Some(cookie) = &req.cookie(AUTH_COOKIE_NAME) {
Ok(Some(cookie.value().to_string()))
}
}
pub(crate) fn check_optional_url(item: &Option<Option<String>>) -> Result<(), LemmyError> {
if let Some(Some(item)) = &item {
if Url::parse(item).is_err() {
return Err(APIError::err("invalid_url").into());
}
}
Ok(())
}
pub(crate) async fn build_federated_instances(
pool: &DbPool,
) -> Result<Option<FederatedInstances>, LemmyError> {
if Settings::get().federation.enabled {
let distinct_communities = blocking(pool, move |conn| {
Community::distinct_federated_communities(conn)
})
.await??;
let allowed = Settings::get().get_allowed_instances();
let blocked = Settings::get().get_blocked_instances();
let mut linked = distinct_communities
.iter()
.map(|actor_id| Ok(Url::parse(actor_id)?.host_str().unwrap_or("").to_string()))
.collect::<Result<Vec<String>, LemmyError>>()?;
linked.extend_from_slice(&allowed);
linked.retain(|a| !blocked.contains(a) && !a.eq("") && !a.eq(&Settings::get().hostname));
// Sort and remove dupes
linked.sort_unstable();
linked.dedup();
Ok(Some(FederatedInstances {
linked,
allowed,
blocked,
}))
} else {
// Otherwise, there's no auth
else {
Ok(None)
}
}
pub async fn match_websocket_operation(
context: LemmyContext,
id: ConnectionId,
op: UserOperation,
data: &str,
) -> Result<String, LemmyError> {
match op {
// User ops
UserOperation::Login => do_websocket_operation::<Login>(context, id, op, data).await,
UserOperation::Register => do_websocket_operation::<Register>(context, id, op, data).await,
UserOperation::GetCaptcha => do_websocket_operation::<GetCaptcha>(context, id, op, data).await,
UserOperation::GetUserDetails => {
do_websocket_operation::<GetUserDetails>(context, id, op, data).await
}
UserOperation::GetReplies => do_websocket_operation::<GetReplies>(context, id, op, data).await,
UserOperation::AddAdmin => do_websocket_operation::<AddAdmin>(context, id, op, data).await,
UserOperation::BanUser => do_websocket_operation::<BanUser>(context, id, op, data).await,
UserOperation::GetUserMentions => {
do_websocket_operation::<GetUserMentions>(context, id, op, data).await
}
UserOperation::MarkUserMentionAsRead => {
do_websocket_operation::<MarkUserMentionAsRead>(context, id, op, data).await
}
UserOperation::MarkAllAsRead => {
do_websocket_operation::<MarkAllAsRead>(context, id, op, data).await
}
UserOperation::DeleteAccount => {
do_websocket_operation::<DeleteAccount>(context, id, op, data).await
}
UserOperation::PasswordReset => {
do_websocket_operation::<PasswordReset>(context, id, op, data).await
}
UserOperation::PasswordChange => {
do_websocket_operation::<PasswordChange>(context, id, op, data).await
}
UserOperation::UserJoin => do_websocket_operation::<UserJoin>(context, id, op, data).await,
UserOperation::PostJoin => do_websocket_operation::<PostJoin>(context, id, op, data).await,
UserOperation::CommunityJoin => {
do_websocket_operation::<CommunityJoin>(context, id, op, data).await
}
UserOperation::ModJoin => do_websocket_operation::<ModJoin>(context, id, op, data).await,
UserOperation::SaveUserSettings => {
do_websocket_operation::<SaveUserSettings>(context, id, op, data).await
}
UserOperation::GetReportCount => {
do_websocket_operation::<GetReportCount>(context, id, op, data).await
}
pub(crate) fn check_totp_2fa_valid(
local_user_view: &LocalUserView,
totp_token: &Option<String>,
site_name: &str,
) -> LemmyResult<()> {
// Throw an error if their token is missing
let token = totp_token
.as_deref()
.ok_or(LemmyErrorType::MissingTotpToken)?;
let secret = local_user_view
.local_user
.totp_2fa_secret
.as_deref()
.ok_or(LemmyErrorType::MissingTotpSecret)?;
// Private Message ops
UserOperation::CreatePrivateMessage => {
do_websocket_operation::<CreatePrivateMessage>(context, id, op, data).await
}
UserOperation::EditPrivateMessage => {
do_websocket_operation::<EditPrivateMessage>(context, id, op, data).await
}
UserOperation::DeletePrivateMessage => {
do_websocket_operation::<DeletePrivateMessage>(context, id, op, data).await
}
UserOperation::MarkPrivateMessageAsRead => {
do_websocket_operation::<MarkPrivateMessageAsRead>(context, id, op, data).await
}
UserOperation::GetPrivateMessages => {
do_websocket_operation::<GetPrivateMessages>(context, id, op, data).await
}
let totp = build_totp_2fa(site_name, &local_user_view.person.name, secret)?;
// Site ops
UserOperation::GetModlog => do_websocket_operation::<GetModlog>(context, id, op, data).await,
UserOperation::CreateSite => do_websocket_operation::<CreateSite>(context, id, op, data).await,
UserOperation::EditSite => do_websocket_operation::<EditSite>(context, id, op, data).await,
UserOperation::GetSite => do_websocket_operation::<GetSite>(context, id, op, data).await,
UserOperation::GetSiteConfig => {
do_websocket_operation::<GetSiteConfig>(context, id, op, data).await
}
UserOperation::SaveSiteConfig => {
do_websocket_operation::<SaveSiteConfig>(context, id, op, data).await
}
UserOperation::Search => do_websocket_operation::<Search>(context, id, op, data).await,
UserOperation::TransferCommunity => {
do_websocket_operation::<TransferCommunity>(context, id, op, data).await
}
UserOperation::TransferSite => {
do_websocket_operation::<TransferSite>(context, id, op, data).await
}
UserOperation::ListCategories => {
do_websocket_operation::<ListCategories>(context, id, op, data).await
}
// Community ops
UserOperation::GetCommunity => {
do_websocket_operation::<GetCommunity>(context, id, op, data).await
}
UserOperation::ListCommunities => {
do_websocket_operation::<ListCommunities>(context, id, op, data).await
}
UserOperation::CreateCommunity => {
do_websocket_operation::<CreateCommunity>(context, id, op, data).await
}
UserOperation::EditCommunity => {
do_websocket_operation::<EditCommunity>(context, id, op, data).await
}
UserOperation::DeleteCommunity => {
do_websocket_operation::<DeleteCommunity>(context, id, op, data).await
}
UserOperation::RemoveCommunity => {
do_websocket_operation::<RemoveCommunity>(context, id, op, data).await
}
UserOperation::FollowCommunity => {
do_websocket_operation::<FollowCommunity>(context, id, op, data).await
}
UserOperation::GetFollowedCommunities => {
do_websocket_operation::<GetFollowedCommunities>(context, id, op, data).await
}
UserOperation::BanFromCommunity => {
do_websocket_operation::<BanFromCommunity>(context, id, op, data).await
}
UserOperation::AddModToCommunity => {
do_websocket_operation::<AddModToCommunity>(context, id, op, data).await
}
// Post ops
UserOperation::CreatePost => do_websocket_operation::<CreatePost>(context, id, op, data).await,
UserOperation::GetPost => do_websocket_operation::<GetPost>(context, id, op, data).await,
UserOperation::GetPosts => do_websocket_operation::<GetPosts>(context, id, op, data).await,
UserOperation::EditPost => do_websocket_operation::<EditPost>(context, id, op, data).await,
UserOperation::DeletePost => do_websocket_operation::<DeletePost>(context, id, op, data).await,
UserOperation::RemovePost => do_websocket_operation::<RemovePost>(context, id, op, data).await,
UserOperation::LockPost => do_websocket_operation::<LockPost>(context, id, op, data).await,
UserOperation::StickyPost => do_websocket_operation::<StickyPost>(context, id, op, data).await,
UserOperation::CreatePostLike => {
do_websocket_operation::<CreatePostLike>(context, id, op, data).await
}
UserOperation::SavePost => do_websocket_operation::<SavePost>(context, id, op, data).await,
UserOperation::CreatePostReport => {
do_websocket_operation::<CreatePostReport>(context, id, op, data).await
}
UserOperation::ListPostReports => {
do_websocket_operation::<ListPostReports>(context, id, op, data).await
}
UserOperation::ResolvePostReport => {
do_websocket_operation::<ResolvePostReport>(context, id, op, data).await
}
// Comment ops
UserOperation::CreateComment => {
do_websocket_operation::<CreateComment>(context, id, op, data).await
}
UserOperation::EditComment => {
do_websocket_operation::<EditComment>(context, id, op, data).await
}
UserOperation::DeleteComment => {
do_websocket_operation::<DeleteComment>(context, id, op, data).await
}
UserOperation::RemoveComment => {
do_websocket_operation::<RemoveComment>(context, id, op, data).await
}
UserOperation::MarkCommentAsRead => {
do_websocket_operation::<MarkCommentAsRead>(context, id, op, data).await
}
UserOperation::SaveComment => {
do_websocket_operation::<SaveComment>(context, id, op, data).await
}
UserOperation::GetComments => {
do_websocket_operation::<GetComments>(context, id, op, data).await
}
UserOperation::CreateCommentLike => {
do_websocket_operation::<CreateCommentLike>(context, id, op, data).await
}
UserOperation::CreateCommentReport => {
do_websocket_operation::<CreateCommentReport>(context, id, op, data).await
}
UserOperation::ListCommentReports => {
do_websocket_operation::<ListCommentReports>(context, id, op, data).await
}
UserOperation::ResolveCommentReport => {
do_websocket_operation::<ResolveCommentReport>(context, id, op, data).await
}
let check_passed = totp.check_current(token)?;
if !check_passed {
return Err(LemmyErrorType::IncorrectTotpToken.into());
}
Ok(())
}
async fn do_websocket_operation<'a, 'b, Data>(
context: LemmyContext,
id: ConnectionId,
op: UserOperation,
data: &str,
) -> Result<String, LemmyError>
where
for<'de> Data: Deserialize<'de> + 'a,
Data: Perform,
{
let parsed_data: Data = serde_json::from_str(&data)?;
let res = parsed_data
.perform(&web::Data::new(context), Some(id))
.await?;
serialize_websocket_message(&op, &res)
pub(crate) fn generate_totp_2fa_secret() -> String {
Secret::generate_secret().to_string()
}
pub(crate) fn captcha_espeak_wav_base64(captcha: &str) -> Result<String, LemmyError> {
let mut built_text = String::new();
fn build_totp_2fa(hostname: &str, username: &str, secret: &str) -> LemmyResult<TOTP> {
let sec = Secret::Raw(secret.as_bytes().to_vec());
let sec_bytes = sec
.to_bytes()
.map_err(|_| LemmyErrorType::CouldntParseTotpSecret)?;
// Building proper speech text for espeak
for mut c in captcha.chars() {
let new_str = if c.is_alphabetic() {
if c.is_lowercase() {
c.make_ascii_uppercase();
format!("lower case {} ... ", c)
TOTP::new(
totp_rs::Algorithm::SHA1,
6,
1,
30,
sec_bytes,
Some(hostname.to_string()),
username.to_string(),
)
.with_lemmy_type(LemmyErrorType::CouldntGenerateTotp)
}
/// Site bans are only federated for local users.
/// This is a problem, because site-banning non-local users will still leave content
/// they've posted to our local communities, on other servers.
///
/// So when doing a site ban for a non-local user, you need to federate/send a
/// community ban for every local community they've participated in.
/// See https://github.com/LemmyNet/lemmy/issues/4118
#[tracing::instrument(skip_all)]
pub(crate) async fn ban_nonlocal_user_from_local_communities(
local_user_view: &LocalUserView,
target: &Person,
ban: bool,
reason: &Option<String>,
remove_data: &Option<bool>,
expires: &Option<i64>,
context: &Data<LemmyContext>,
) -> LemmyResult<()> {
// Only run this code for federated users
if !target.local {
let ids = Person::list_local_community_ids(&mut context.pool(), target.id).await?;
for community_id in ids {
let expires_dt = check_expire_time(*expires)?;
// Ban / unban them from our local communities
let community_user_ban_form = CommunityPersonBanForm {
community_id,
person_id: target.id,
expires: Some(expires_dt),
};
if ban {
// Ignore all errors for these
CommunityPersonBan::ban(&mut context.pool(), &community_user_ban_form)
.await
.ok();
// Also unsubscribe them from the community, if they are subscribed
let community_follower_form = CommunityFollowerForm {
community_id,
person_id: target.id,
pending: false,
};
CommunityFollower::unfollow(&mut context.pool(), &community_follower_form)
.await
.ok();
} else {
c.make_ascii_uppercase();
format!("capital {} ... ", c)
CommunityPersonBan::unban(&mut context.pool(), &community_user_ban_form)
.await
.ok();
}
} else {
format!("{} ...", c)
};
built_text.push_str(&new_str);
// Mod tables
let form = ModBanFromCommunityForm {
mod_person_id: local_user_view.person.id,
other_person_id: target.id,
community_id,
reason: reason.clone(),
banned: Some(ban),
expires: expires_dt,
};
ModBanFromCommunity::create(&mut context.pool(), &form).await?;
// Federate the ban from community
let ban_from_community = BanFromCommunity {
community_id,
person_id: target.id,
ban,
reason: reason.clone(),
remove_data: *remove_data,
expires: *expires,
};
ActivityChannel::submit_activity(
SendActivityData::BanFromCommunity {
moderator: local_user_view.person.clone(),
community_id,
target: target.clone(),
data: ban_from_community,
},
context,
)
.await?;
}
}
espeak_wav_base64(&built_text)
Ok(())
}
pub(crate) fn espeak_wav_base64(text: &str) -> Result<String, LemmyError> {
// Make a temp file path
let uuid = uuid::Uuid::new_v4().to_string();
let file_path = format!("/tmp/lemmy_espeak_{}.wav", &uuid);
#[tracing::instrument(skip_all)]
pub async fn local_user_view_from_jwt(
jwt: &str,
context: &LemmyContext,
) -> LemmyResult<LocalUserView> {
let local_user_id = Claims::validate(jwt, context)
.await
.with_lemmy_type(LemmyErrorType::NotLoggedIn)?;
let local_user_view = LocalUserView::read(&mut context.pool(), local_user_id)
.await?
.ok_or(LemmyErrorType::CouldntFindLocalUser)?;
check_user_valid(&local_user_view.person)?;
// Write the wav file
Command::new("espeak")
.arg("-w")
.arg(&file_path)
.arg(text)
.status()?;
// Read the wav file bytes
let bytes = std::fs::read(&file_path)?;
// Delete the file
std::fs::remove_file(file_path)?;
// Convert to base64
let base64 = base64::encode(bytes);
Ok(base64)
Ok(local_user_view)
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
#[allow(clippy::indexing_slicing)]
mod tests {
use crate::captcha_espeak_wav_base64;
use super::*;
#[test]
fn test_espeak() {
assert!(captcha_espeak_wav_base64("WxRt2l").is_ok())
fn test_build_totp() {
let generated_secret = generate_totp_2fa_secret();
let totp = build_totp_2fa("lemmy.ml", "my_name", &generated_secret);
assert!(totp.is_ok());
}
}

View File

@ -0,0 +1,55 @@
use actix_web::web::{Data, Json};
use lemmy_api_common::{
context::LemmyContext,
person::{AddAdmin, AddAdminResponse},
utils::is_admin,
};
use lemmy_db_schema::{
source::{
local_user::{LocalUser, LocalUserUpdateForm},
moderator::{ModAdd, ModAddForm},
},
traits::Crud,
};
use lemmy_db_views::structs::LocalUserView;
use lemmy_db_views_actor::structs::PersonView;
use lemmy_utils::error::{LemmyErrorExt, LemmyErrorType, LemmyResult};
#[tracing::instrument(skip(context))]
pub async fn add_admin(
data: Json<AddAdmin>,
context: Data<LemmyContext>,
local_user_view: LocalUserView,
) -> LemmyResult<Json<AddAdminResponse>> {
// Make sure user is an admin
is_admin(&local_user_view)?;
// Make sure that the person_id added is local
let added_local_user = LocalUserView::read_person(&mut context.pool(), data.person_id)
.await?
.ok_or(LemmyErrorType::ObjectNotLocal)?;
LocalUser::update(
&mut context.pool(),
added_local_user.local_user.id,
&LocalUserUpdateForm {
admin: Some(data.added),
..Default::default()
},
)
.await
.with_lemmy_type(LemmyErrorType::CouldntUpdateUser)?;
// Mod tables
let form = ModAddForm {
mod_person_id: local_user_view.person.id,
other_person_id: added_local_user.person.id,
removed: Some(!data.added),
};
ModAdd::create(&mut context.pool(), &form).await?;
let admins = PersonView::admins(&mut context.pool()).await?;
Ok(Json(AddAdminResponse { admins }))
}

View File

@ -0,0 +1,105 @@
use crate::ban_nonlocal_user_from_local_communities;
use activitypub_federation::config::Data;
use actix_web::web::Json;
use lemmy_api_common::{
context::LemmyContext,
person::{BanPerson, BanPersonResponse},
send_activity::{ActivityChannel, SendActivityData},
utils::{check_expire_time, is_admin, remove_user_data},
};
use lemmy_db_schema::{
source::{
login_token::LoginToken,
moderator::{ModBan, ModBanForm},
person::{Person, PersonUpdateForm},
},
traits::Crud,
};
use lemmy_db_views::structs::LocalUserView;
use lemmy_db_views_actor::structs::PersonView;
use lemmy_utils::{
error::{LemmyErrorExt, LemmyErrorType, LemmyResult},
utils::validation::is_valid_body_field,
};
#[tracing::instrument(skip(context))]
pub async fn ban_from_site(
data: Json<BanPerson>,
context: Data<LemmyContext>,
local_user_view: LocalUserView,
) -> LemmyResult<Json<BanPersonResponse>> {
// Make sure user is an admin
is_admin(&local_user_view)?;
is_valid_body_field(&data.reason, false)?;
let expires = check_expire_time(data.expires)?;
let person = Person::update(
&mut context.pool(),
data.person_id,
&PersonUpdateForm {
banned: Some(data.ban),
ban_expires: Some(expires),
..Default::default()
},
)
.await
.with_lemmy_type(LemmyErrorType::CouldntUpdateUser)?;
// if its a local user, invalidate logins
let local_user = LocalUserView::read_person(&mut context.pool(), person.id).await;
if let Ok(Some(local_user)) = local_user {
LoginToken::invalidate_all(&mut context.pool(), local_user.local_user.id).await?;
}
// Remove their data if that's desired
let remove_data = data.remove_data.unwrap_or(false);
if remove_data {
remove_user_data(person.id, &context).await?;
}
// Mod tables
let form = ModBanForm {
mod_person_id: local_user_view.person.id,
other_person_id: person.id,
reason: data.reason.clone(),
banned: Some(data.ban),
expires,
};
ModBan::create(&mut context.pool(), &form).await?;
let person_view = PersonView::read(&mut context.pool(), person.id)
.await?
.ok_or(LemmyErrorType::CouldntFindPerson)?;
ban_nonlocal_user_from_local_communities(
&local_user_view,
&person,
data.ban,
&data.reason,
&data.remove_data,
&data.expires,
&context,
)
.await?;
ActivityChannel::submit_activity(
SendActivityData::BanFromSite {
moderator: local_user_view.person,
banned_user: person_view.person.clone(),
reason: data.reason.clone(),
remove_data: data.remove_data,
ban: data.ban,
expires: data.expires,
},
&context,
)
.await?;
Ok(Json(BanPersonResponse {
person_view,
banned: data.ban,
}))
}

View File

@ -0,0 +1,59 @@
use actix_web::web::{Data, Json};
use lemmy_api_common::{
context::LemmyContext,
person::{BlockPerson, BlockPersonResponse},
};
use lemmy_db_schema::{
source::person_block::{PersonBlock, PersonBlockForm},
traits::Blockable,
};
use lemmy_db_views::structs::LocalUserView;
use lemmy_db_views_actor::structs::PersonView;
use lemmy_utils::error::{LemmyErrorExt, LemmyErrorType, LemmyResult};
#[tracing::instrument(skip(context))]
pub async fn block_person(
data: Json<BlockPerson>,
context: Data<LemmyContext>,
local_user_view: LocalUserView,
) -> LemmyResult<Json<BlockPersonResponse>> {
let target_id = data.person_id;
let person_id = local_user_view.person.id;
// Don't let a person block themselves
if target_id == person_id {
Err(LemmyErrorType::CantBlockYourself)?
}
let person_block_form = PersonBlockForm {
person_id,
target_id,
};
let target_user = LocalUserView::read_person(&mut context.pool(), target_id)
.await
.ok()
.flatten();
if target_user.is_some_and(|t| t.local_user.admin) {
Err(LemmyErrorType::CantBlockAdmin)?
}
if data.block {
PersonBlock::block(&mut context.pool(), &person_block_form)
.await
.with_lemmy_type(LemmyErrorType::PersonBlockAlreadyExists)?;
} else {
PersonBlock::unblock(&mut context.pool(), &person_block_form)
.await
.with_lemmy_type(LemmyErrorType::PersonBlockAlreadyExists)?;
}
let person_view = PersonView::read(&mut context.pool(), target_id)
.await?
.ok_or(LemmyErrorType::CouldntFindPerson)?;
Ok(Json(BlockPersonResponse {
person_view,
blocked: data.block,
}))
}

View File

@ -0,0 +1,53 @@
use actix_web::{
web::{Data, Json},
HttpRequest,
};
use bcrypt::verify;
use lemmy_api_common::{
claims::Claims,
context::LemmyContext,
person::{ChangePassword, LoginResponse},
utils::password_length_check,
};
use lemmy_db_schema::source::{local_user::LocalUser, login_token::LoginToken};
use lemmy_db_views::structs::LocalUserView;
use lemmy_utils::error::{LemmyErrorType, LemmyResult};
#[tracing::instrument(skip(context))]
pub async fn change_password(
data: Json<ChangePassword>,
req: HttpRequest,
context: Data<LemmyContext>,
local_user_view: LocalUserView,
) -> LemmyResult<Json<LoginResponse>> {
password_length_check(&data.new_password)?;
// Make sure passwords match
if data.new_password != data.new_password_verify {
Err(LemmyErrorType::PasswordsDoNotMatch)?
}
// Check the old password
let valid: bool = verify(
&data.old_password,
&local_user_view.local_user.password_encrypted,
)
.unwrap_or(false);
if !valid {
Err(LemmyErrorType::IncorrectLogin)?
}
let local_user_id = local_user_view.local_user.id;
let new_password = data.new_password.clone();
let updated_local_user =
LocalUser::update_password(&mut context.pool(), local_user_id, &new_password).await?;
LoginToken::invalidate_all(&mut context.pool(), local_user_view.local_user.id).await?;
// Return the jwt
Ok(Json(LoginResponse {
jwt: Some(Claims::generate(updated_local_user.id, req, &context).await?),
verify_email_sent: false,
registration_created: false,
}))
}

View File

@ -0,0 +1,43 @@
use actix_web::web::{Data, Json};
use lemmy_api_common::{
context::LemmyContext,
person::PasswordChangeAfterReset,
utils::password_length_check,
SuccessResponse,
};
use lemmy_db_schema::source::{
local_user::LocalUser,
login_token::LoginToken,
password_reset_request::PasswordResetRequest,
};
use lemmy_utils::error::{LemmyErrorExt, LemmyErrorType, LemmyResult};
#[tracing::instrument(skip(context))]
pub async fn change_password_after_reset(
data: Json<PasswordChangeAfterReset>,
context: Data<LemmyContext>,
) -> LemmyResult<Json<SuccessResponse>> {
// Fetch the user_id from the token
let token = data.token.clone();
let local_user_id = PasswordResetRequest::read_and_delete(&mut context.pool(), &token)
.await?
.ok_or(LemmyErrorType::TokenNotFound)?
.local_user_id;
password_length_check(&data.password)?;
// Make sure passwords match
if data.password != data.password_verify {
Err(LemmyErrorType::PasswordsDoNotMatch)?
}
// Update the user with the new password
let password = data.password.clone();
LocalUser::update_password(&mut context.pool(), local_user_id, &password)
.await
.with_lemmy_type(LemmyErrorType::CouldntUpdateUser)?;
LoginToken::invalidate_all(&mut context.pool(), local_user_id).await?;
Ok(Json(SuccessResponse::default()))
}

View File

@ -0,0 +1,42 @@
use crate::{build_totp_2fa, generate_totp_2fa_secret};
use activitypub_federation::config::Data;
use actix_web::web::Json;
use lemmy_api_common::{context::LemmyContext, person::GenerateTotpSecretResponse};
use lemmy_db_schema::source::local_user::{LocalUser, LocalUserUpdateForm};
use lemmy_db_views::structs::{LocalUserView, SiteView};
use lemmy_utils::error::{LemmyErrorType, LemmyResult};
/// Generate a new secret for two-factor-authentication. Afterwards you need to call [toggle_totp]
/// to enable it. This can only be called if 2FA is currently disabled.
#[tracing::instrument(skip(context))]
pub async fn generate_totp_secret(
local_user_view: LocalUserView,
context: Data<LemmyContext>,
) -> LemmyResult<Json<GenerateTotpSecretResponse>> {
let site_view = SiteView::read_local(&mut context.pool())
.await?
.ok_or(LemmyErrorType::LocalSiteNotSetup)?;
if local_user_view.local_user.totp_2fa_enabled {
return Err(LemmyErrorType::TotpAlreadyEnabled)?;
}
let secret = generate_totp_2fa_secret();
let secret_url =
build_totp_2fa(&site_view.site.name, &local_user_view.person.name, &secret)?.get_url();
let local_user_form = LocalUserUpdateForm {
totp_2fa_secret: Some(Some(secret)),
..Default::default()
};
LocalUser::update(
&mut context.pool(),
local_user_view.local_user.id,
&local_user_form,
)
.await?;
Ok(Json(GenerateTotpSecretResponse {
totp_secret_url: secret_url.into(),
}))
}

View File

@ -0,0 +1,56 @@
use crate::captcha_as_wav_base64;
use actix_web::{
http::{
header::{CacheControl, CacheDirective},
StatusCode,
},
web::{Data, Json},
HttpResponse,
HttpResponseBuilder,
};
use captcha::{gen, Difficulty};
use lemmy_api_common::{
context::LemmyContext,
person::{CaptchaResponse, GetCaptchaResponse},
};
use lemmy_db_schema::source::{
captcha_answer::{CaptchaAnswer, CaptchaAnswerForm},
local_site::LocalSite,
};
use lemmy_utils::error::LemmyResult;
#[tracing::instrument(skip(context))]
pub async fn get_captcha(context: Data<LemmyContext>) -> LemmyResult<HttpResponse> {
let local_site = LocalSite::read(&mut context.pool()).await?;
let mut res = HttpResponseBuilder::new(StatusCode::OK);
res.insert_header(CacheControl(vec![CacheDirective::NoStore]));
if !local_site.captcha_enabled {
return Ok(res.json(Json(GetCaptchaResponse { ok: None })));
}
let captcha = gen(match local_site.captcha_difficulty.as_str() {
"easy" => Difficulty::Easy,
"hard" => Difficulty::Hard,
_ => Difficulty::Medium,
});
let answer = captcha.chars_as_string();
let png = captcha.as_base64().expect("failed to generate captcha");
let wav = captcha_as_wav_base64(&captcha)?;
let captcha_form: CaptchaAnswerForm = CaptchaAnswerForm { answer };
// Stores the captcha item in the db
let captcha = CaptchaAnswer::insert(&mut context.pool(), &captcha_form).await?;
let json = Json(GetCaptchaResponse {
ok: Some(CaptchaResponse {
png,
wav,
uuid: captcha.uuid.to_string(),
}),
});
Ok(res.json(json))
}

View File

@ -0,0 +1,17 @@
use actix_web::web::{Data, Json};
use lemmy_api_common::{context::LemmyContext, person::BannedPersonsResponse, utils::is_admin};
use lemmy_db_views::structs::LocalUserView;
use lemmy_db_views_actor::structs::PersonView;
use lemmy_utils::error::LemmyResult;
pub async fn list_banned_users(
context: Data<LemmyContext>,
local_user_view: LocalUserView,
) -> LemmyResult<Json<BannedPersonsResponse>> {
// Make sure user is an admin
is_admin(&local_user_view)?;
let banned = PersonView::banned(&mut context.pool()).await?;
Ok(Json(BannedPersonsResponse { banned }))
}

View File

@ -0,0 +1,14 @@
use actix_web::web::{Data, Json};
use lemmy_api_common::context::LemmyContext;
use lemmy_db_schema::source::login_token::LoginToken;
use lemmy_db_views::structs::LocalUserView;
use lemmy_utils::error::LemmyResult;
pub async fn list_logins(
context: Data<LemmyContext>,
local_user_view: LocalUserView,
) -> LemmyResult<Json<Vec<LoginToken>>> {
let logins = LoginToken::list(&mut context.pool(), local_user_view.local_user.id).await?;
Ok(Json(logins))
}

View File

@ -0,0 +1,25 @@
use actix_web::web::{Data, Json, Query};
use lemmy_api_common::{
context::LemmyContext,
person::{ListMedia, ListMediaResponse},
};
use lemmy_db_views::structs::{LocalImageView, LocalUserView};
use lemmy_utils::error::LemmyResult;
#[tracing::instrument(skip(context))]
pub async fn list_media(
data: Query<ListMedia>,
context: Data<LemmyContext>,
local_user_view: LocalUserView,
) -> LemmyResult<Json<ListMediaResponse>> {
let page = data.page;
let limit = data.limit;
let images = LocalImageView::get_all_paged_by_local_user_id(
&mut context.pool(),
local_user_view.local_user.id,
page,
limit,
)
.await?;
Ok(Json(ListMediaResponse { images }))
}

View File

@ -0,0 +1,94 @@
use crate::{check_totp_2fa_valid, local_user::check_email_verified};
use actix_web::{
web::{Data, Json},
HttpRequest,
};
use bcrypt::verify;
use lemmy_api_common::{
claims::Claims,
context::LemmyContext,
person::{Login, LoginResponse},
utils::check_user_valid,
};
use lemmy_db_schema::{
source::{local_site::LocalSite, registration_application::RegistrationApplication},
utils::DbPool,
RegistrationMode,
};
use lemmy_db_views::structs::{LocalUserView, SiteView};
use lemmy_utils::error::{LemmyErrorType, LemmyResult};
#[tracing::instrument(skip(context))]
pub async fn login(
data: Json<Login>,
req: HttpRequest,
context: Data<LemmyContext>,
) -> LemmyResult<Json<LoginResponse>> {
let site_view = SiteView::read_local(&mut context.pool())
.await?
.ok_or(LemmyErrorType::LocalSiteNotSetup)?;
// Fetch that username / email
let username_or_email = data.username_or_email.clone();
let local_user_view =
LocalUserView::find_by_email_or_name(&mut context.pool(), &username_or_email)
.await?
.ok_or(LemmyErrorType::IncorrectLogin)?;
// Verify the password
let valid: bool = verify(
&data.password,
&local_user_view.local_user.password_encrypted,
)
.unwrap_or(false);
if !valid {
Err(LemmyErrorType::IncorrectLogin)?
}
check_user_valid(&local_user_view.person)?;
check_email_verified(&local_user_view, &site_view)?;
check_registration_application(&local_user_view, &site_view.local_site, &mut context.pool())
.await?;
// Check the totp if enabled
if local_user_view.local_user.totp_2fa_enabled {
check_totp_2fa_valid(
&local_user_view,
&data.totp_2fa_token,
&context.settings().hostname,
)?;
}
let jwt = Claims::generate(local_user_view.local_user.id, req, &context).await?;
Ok(Json(LoginResponse {
jwt: Some(jwt.clone()),
verify_email_sent: false,
registration_created: false,
}))
}
async fn check_registration_application(
local_user_view: &LocalUserView,
local_site: &LocalSite,
pool: &mut DbPool<'_>,
) -> LemmyResult<()> {
if (local_site.registration_mode == RegistrationMode::RequireApplication
|| local_site.registration_mode == RegistrationMode::Closed)
&& !local_user_view.local_user.accepted_application
&& !local_user_view.local_user.admin
{
// Fetch the registration application. If no admin id is present its still pending. Otherwise it
// was processed (either accepted or denied).
let local_user_id = local_user_view.local_user.id;
let registration = RegistrationApplication::find_by_local_user_id(pool, local_user_id)
.await?
.ok_or(LemmyErrorType::CouldntFindRegistrationApplication)?;
if registration.admin_id.is_some() {
Err(LemmyErrorType::RegistrationDenied(registration.deny_reason))?
} else {
Err(LemmyErrorType::RegistrationApplicationIsPending)?
}
}
Ok(())
}

View File

@ -0,0 +1,23 @@
use crate::read_auth_token;
use activitypub_federation::config::Data;
use actix_web::{cookie::Cookie, HttpRequest, HttpResponse};
use lemmy_api_common::{context::LemmyContext, utils::AUTH_COOKIE_NAME, SuccessResponse};
use lemmy_db_schema::source::login_token::LoginToken;
use lemmy_db_views::structs::LocalUserView;
use lemmy_utils::error::{LemmyErrorType, LemmyResult};
#[tracing::instrument(skip(context))]
pub async fn logout(
req: HttpRequest,
// require login
_local_user_view: LocalUserView,
context: Data<LemmyContext>,
) -> LemmyResult<HttpResponse> {
let jwt = read_auth_token(&req)?.ok_or(LemmyErrorType::NotLoggedIn)?;
LoginToken::invalidate(&mut context.pool(), &jwt).await?;
let mut res = HttpResponse::Ok().json(SuccessResponse::default());
let cookie = Cookie::new(AUTH_COOKIE_NAME, "");
res.add_removal_cookie(&cookie)?;
Ok(res)
}

View File

@ -0,0 +1,34 @@
use lemmy_db_views::structs::{LocalUserView, SiteView};
use lemmy_utils::{error::LemmyResult, LemmyErrorType};
pub mod add_admin;
pub mod ban_person;
pub mod block;
pub mod change_password;
pub mod change_password_after_reset;
pub mod generate_totp_secret;
pub mod get_captcha;
pub mod list_banned;
pub mod list_logins;
pub mod list_media;
pub mod login;
pub mod logout;
pub mod notifications;
pub mod report_count;
pub mod reset_password;
pub mod save_settings;
pub mod update_totp;
pub mod validate_auth;
pub mod verify_email;
/// Check if the user's email is verified if email verification is turned on
/// However, skip checking verification if the user is an admin
fn check_email_verified(local_user_view: &LocalUserView, site_view: &SiteView) -> LemmyResult<()> {
if !local_user_view.local_user.admin
&& site_view.local_site.require_email_verification
&& !local_user_view.local_user.email_verified
{
Err(LemmyErrorType::EmailNotVerified)?
}
Ok(())
}

View File

@ -0,0 +1,36 @@
use actix_web::web::{Data, Json, Query};
use lemmy_api_common::{
context::LemmyContext,
person::{GetPersonMentions, GetPersonMentionsResponse},
};
use lemmy_db_views::structs::LocalUserView;
use lemmy_db_views_actor::person_mention_view::PersonMentionQuery;
use lemmy_utils::error::LemmyResult;
#[tracing::instrument(skip(context))]
pub async fn list_mentions(
data: Query<GetPersonMentions>,
context: Data<LemmyContext>,
local_user_view: LocalUserView,
) -> LemmyResult<Json<GetPersonMentionsResponse>> {
let sort = data.sort;
let page = data.page;
let limit = data.limit;
let unread_only = data.unread_only.unwrap_or_default();
let person_id = Some(local_user_view.person.id);
let show_bot_accounts = local_user_view.local_user.show_bot_accounts;
let mentions = PersonMentionQuery {
recipient_id: person_id,
my_person_id: person_id,
sort,
unread_only,
show_bot_accounts,
page,
limit,
}
.list(&mut context.pool())
.await?;
Ok(Json(GetPersonMentionsResponse { mentions }))
}

View File

@ -0,0 +1,36 @@
use actix_web::web::{Data, Json, Query};
use lemmy_api_common::{
context::LemmyContext,
person::{GetReplies, GetRepliesResponse},
};
use lemmy_db_views::structs::LocalUserView;
use lemmy_db_views_actor::comment_reply_view::CommentReplyQuery;
use lemmy_utils::error::LemmyResult;
#[tracing::instrument(skip(context))]
pub async fn list_replies(
data: Query<GetReplies>,
context: Data<LemmyContext>,
local_user_view: LocalUserView,
) -> LemmyResult<Json<GetRepliesResponse>> {
let sort = data.sort;
let page = data.page;
let limit = data.limit;
let unread_only = data.unread_only.unwrap_or_default();
let person_id = Some(local_user_view.person.id);
let show_bot_accounts = local_user_view.local_user.show_bot_accounts;
let replies = CommentReplyQuery {
recipient_id: person_id,
my_person_id: person_id,
sort,
unread_only,
show_bot_accounts,
page,
limit,
}
.list(&mut context.pool())
.await?;
Ok(Json(GetRepliesResponse { replies }))
}

View File

@ -0,0 +1,34 @@
use actix_web::web::{Data, Json};
use lemmy_api_common::{context::LemmyContext, person::GetRepliesResponse};
use lemmy_db_schema::source::{
comment_reply::CommentReply,
person_mention::PersonMention,
private_message::PrivateMessage,
};
use lemmy_db_views::structs::LocalUserView;
use lemmy_utils::error::{LemmyErrorExt, LemmyErrorType, LemmyResult};
#[tracing::instrument(skip(context))]
pub async fn mark_all_notifications_read(
context: Data<LemmyContext>,
local_user_view: LocalUserView,
) -> LemmyResult<Json<GetRepliesResponse>> {
let person_id = local_user_view.person.id;
// Mark all comment_replies as read
CommentReply::mark_all_as_read(&mut context.pool(), person_id)
.await
.with_lemmy_type(LemmyErrorType::CouldntUpdateComment)?;
// Mark all user mentions as read
PersonMention::mark_all_as_read(&mut context.pool(), person_id)
.await
.with_lemmy_type(LemmyErrorType::CouldntUpdateComment)?;
// Mark all private_messages as read
PrivateMessage::mark_all_as_read(&mut context.pool(), person_id)
.await
.with_lemmy_type(LemmyErrorType::CouldntUpdatePrivateMessage)?;
Ok(Json(GetRepliesResponse { replies: vec![] }))
}

View File

@ -0,0 +1,49 @@
use actix_web::web::{Data, Json};
use lemmy_api_common::{
context::LemmyContext,
person::{MarkPersonMentionAsRead, PersonMentionResponse},
};
use lemmy_db_schema::{
source::person_mention::{PersonMention, PersonMentionUpdateForm},
traits::Crud,
};
use lemmy_db_views::structs::LocalUserView;
use lemmy_db_views_actor::structs::PersonMentionView;
use lemmy_utils::error::{LemmyErrorExt, LemmyErrorType, LemmyResult};
#[tracing::instrument(skip(context))]
pub async fn mark_person_mention_as_read(
data: Json<MarkPersonMentionAsRead>,
context: Data<LemmyContext>,
local_user_view: LocalUserView,
) -> LemmyResult<Json<PersonMentionResponse>> {
let person_mention_id = data.person_mention_id;
let read_person_mention = PersonMention::read(&mut context.pool(), person_mention_id)
.await?
.ok_or(LemmyErrorType::CouldntFindPersonMention)?;
if local_user_view.person.id != read_person_mention.recipient_id {
Err(LemmyErrorType::CouldntUpdateComment)?
}
let person_mention_id = read_person_mention.id;
let read = Some(data.read);
PersonMention::update(
&mut context.pool(),
person_mention_id,
&PersonMentionUpdateForm { read },
)
.await
.with_lemmy_type(LemmyErrorType::CouldntUpdateComment)?;
let person_mention_id = read_person_mention.id;
let person_id = local_user_view.person.id;
let person_mention_view =
PersonMentionView::read(&mut context.pool(), person_mention_id, Some(person_id))
.await?
.ok_or(LemmyErrorType::CouldntFindPersonMention)?;
Ok(Json(PersonMentionResponse {
person_mention_view,
}))
}

View File

@ -0,0 +1,48 @@
use actix_web::web::{Data, Json};
use lemmy_api_common::{
context::LemmyContext,
person::{CommentReplyResponse, MarkCommentReplyAsRead},
};
use lemmy_db_schema::{
source::comment_reply::{CommentReply, CommentReplyUpdateForm},
traits::Crud,
};
use lemmy_db_views::structs::LocalUserView;
use lemmy_db_views_actor::structs::CommentReplyView;
use lemmy_utils::error::{LemmyErrorExt, LemmyErrorType, LemmyResult};
#[tracing::instrument(skip(context))]
pub async fn mark_reply_as_read(
data: Json<MarkCommentReplyAsRead>,
context: Data<LemmyContext>,
local_user_view: LocalUserView,
) -> LemmyResult<Json<CommentReplyResponse>> {
let comment_reply_id = data.comment_reply_id;
let read_comment_reply = CommentReply::read(&mut context.pool(), comment_reply_id)
.await?
.ok_or(LemmyErrorType::CouldntFindCommentReply)?;
if local_user_view.person.id != read_comment_reply.recipient_id {
Err(LemmyErrorType::CouldntUpdateComment)?
}
let comment_reply_id = read_comment_reply.id;
let read = Some(data.read);
CommentReply::update(
&mut context.pool(),
comment_reply_id,
&CommentReplyUpdateForm { read },
)
.await
.with_lemmy_type(LemmyErrorType::CouldntUpdateComment)?;
let comment_reply_id = read_comment_reply.id;
let person_id = local_user_view.person.id;
let comment_reply_view =
CommentReplyView::read(&mut context.pool(), comment_reply_id, Some(person_id))
.await?
.ok_or(LemmyErrorType::CouldntFindCommentReply)?;
Ok(Json(CommentReplyResponse { comment_reply_view }))
}

View File

@ -0,0 +1,6 @@
pub mod list_mentions;
pub mod list_replies;
pub mod mark_all_read;
pub mod mark_mention_read;
pub mod mark_reply_read;
pub mod unread_count;

View File

@ -0,0 +1,26 @@
use actix_web::web::{Data, Json};
use lemmy_api_common::{context::LemmyContext, person::GetUnreadCountResponse};
use lemmy_db_views::structs::{LocalUserView, PrivateMessageView};
use lemmy_db_views_actor::structs::{CommentReplyView, PersonMentionView};
use lemmy_utils::error::LemmyResult;
#[tracing::instrument(skip(context))]
pub async fn unread_count(
context: Data<LemmyContext>,
local_user_view: LocalUserView,
) -> LemmyResult<Json<GetUnreadCountResponse>> {
let person_id = local_user_view.person.id;
let replies = CommentReplyView::get_unread_replies(&mut context.pool(), person_id).await?;
let mentions = PersonMentionView::get_unread_mentions(&mut context.pool(), person_id).await?;
let private_messages =
PrivateMessageView::get_unread_messages(&mut context.pool(), person_id).await?;
Ok(Json(GetUnreadCountResponse {
replies,
mentions,
private_messages,
}))
}

View File

@ -0,0 +1,46 @@
use actix_web::web::{Data, Json, Query};
use lemmy_api_common::{
context::LemmyContext,
person::{GetReportCount, GetReportCountResponse},
utils::check_community_mod_of_any_or_admin_action,
};
use lemmy_db_views::structs::{
CommentReportView,
LocalUserView,
PostReportView,
PrivateMessageReportView,
};
use lemmy_utils::error::LemmyResult;
#[tracing::instrument(skip(context))]
pub async fn report_count(
data: Query<GetReportCount>,
context: Data<LemmyContext>,
local_user_view: LocalUserView,
) -> LemmyResult<Json<GetReportCountResponse>> {
let person_id = local_user_view.person.id;
let admin = local_user_view.local_user.admin;
let community_id = data.community_id;
check_community_mod_of_any_or_admin_action(&local_user_view, &mut context.pool()).await?;
let comment_reports =
CommentReportView::get_report_count(&mut context.pool(), person_id, admin, community_id)
.await?;
let post_reports =
PostReportView::get_report_count(&mut context.pool(), person_id, admin, community_id).await?;
let private_message_reports = if admin && community_id.is_none() {
Some(PrivateMessageReportView::get_report_count(&mut context.pool()).await?)
} else {
None
};
Ok(Json(GetReportCountResponse {
community_id,
comment_reports,
post_reports,
private_message_reports,
}))
}

View File

@ -0,0 +1,31 @@
use crate::local_user::check_email_verified;
use actix_web::web::{Data, Json};
use lemmy_api_common::{
context::LemmyContext,
person::PasswordReset,
utils::send_password_reset_email,
SuccessResponse,
};
use lemmy_db_views::structs::{LocalUserView, SiteView};
use lemmy_utils::error::{LemmyErrorType, LemmyResult};
#[tracing::instrument(skip(context))]
pub async fn reset_password(
data: Json<PasswordReset>,
context: Data<LemmyContext>,
) -> LemmyResult<Json<SuccessResponse>> {
// Fetch that email
let email = data.email.to_lowercase();
let local_user_view = LocalUserView::find_by_email(&mut context.pool(), &email)
.await?
.ok_or(LemmyErrorType::IncorrectLogin)?;
let site_view = SiteView::read_local(&mut context.pool())
.await?
.ok_or(LemmyErrorType::LocalSiteNotSetup)?;
check_email_verified(&local_user_view, &site_view)?;
// Email the pure token to the user.
send_password_reset_email(&local_user_view, &mut context.pool(), context.settings()).await?;
Ok(Json(SuccessResponse::default()))
}

View File

@ -0,0 +1,159 @@
use activitypub_federation::config::Data;
use actix_web::web::Json;
use lemmy_api_common::{
context::LemmyContext,
person::SaveUserSettings,
request::replace_image,
utils::{
get_url_blocklist,
local_site_to_slur_regex,
process_markdown_opt,
proxy_image_link_opt_api,
send_verification_email,
},
SuccessResponse,
};
use lemmy_db_schema::{
source::{
actor_language::LocalUserLanguage,
local_user::{LocalUser, LocalUserUpdateForm},
local_user_vote_display_mode::{LocalUserVoteDisplayMode, LocalUserVoteDisplayModeUpdateForm},
person::{Person, PersonUpdateForm},
},
traits::Crud,
utils::diesel_option_overwrite,
};
use lemmy_db_views::structs::{LocalUserView, SiteView};
use lemmy_utils::{
error::{LemmyErrorType, LemmyResult},
utils::validation::{is_valid_bio_field, is_valid_display_name, is_valid_matrix_id},
};
use std::ops::Deref;
#[tracing::instrument(skip(context))]
pub async fn save_user_settings(
data: Json<SaveUserSettings>,
context: Data<LemmyContext>,
local_user_view: LocalUserView,
) -> LemmyResult<Json<SuccessResponse>> {
let site_view = SiteView::read_local(&mut context.pool())
.await?
.ok_or(LemmyErrorType::LocalSiteNotSetup)?;
let slur_regex = local_site_to_slur_regex(&site_view.local_site);
let url_blocklist = get_url_blocklist(&context).await?;
let bio = diesel_option_overwrite(
process_markdown_opt(&data.bio, &slur_regex, &url_blocklist, &context).await?,
);
replace_image(&data.avatar, &local_user_view.person.avatar, &context).await?;
replace_image(&data.banner, &local_user_view.person.banner, &context).await?;
let avatar = proxy_image_link_opt_api(&data.avatar, &context).await?;
let banner = proxy_image_link_opt_api(&data.banner, &context).await?;
let display_name = diesel_option_overwrite(data.display_name.clone());
let matrix_user_id = diesel_option_overwrite(data.matrix_user_id.clone());
let email_deref = data.email.as_deref().map(str::to_lowercase);
let email = diesel_option_overwrite(email_deref.clone());
if let Some(Some(email)) = &email {
let previous_email = local_user_view.local_user.email.clone().unwrap_or_default();
// if email was changed, check that it is not taken and send verification mail
if previous_email.deref() != email {
if LocalUser::is_email_taken(&mut context.pool(), email).await? {
return Err(LemmyErrorType::EmailAlreadyExists)?;
}
send_verification_email(
&local_user_view,
email,
&mut context.pool(),
context.settings(),
)
.await?;
}
}
// When the site requires email, make sure email is not Some(None). IE, an overwrite to a None
// value
if let Some(email) = &email {
if email.is_none() && site_view.local_site.require_email_verification {
Err(LemmyErrorType::EmailRequired)?
}
}
if let Some(Some(bio)) = &bio {
is_valid_bio_field(bio)?;
}
if let Some(Some(display_name)) = &display_name {
is_valid_display_name(
display_name.trim(),
site_view.local_site.actor_name_max_length as usize,
)?;
}
if let Some(Some(matrix_user_id)) = &matrix_user_id {
is_valid_matrix_id(matrix_user_id)?;
}
let local_user_id = local_user_view.local_user.id;
let person_id = local_user_view.person.id;
let default_listing_type = data.default_listing_type;
let default_sort_type = data.default_sort_type;
let person_form = PersonUpdateForm {
display_name,
bio,
matrix_user_id,
bot_account: data.bot_account,
avatar,
banner,
..Default::default()
};
// Ignore errors, because 'no fields updated' will return an error.
// https://github.com/LemmyNet/lemmy/issues/4076
Person::update(&mut context.pool(), person_id, &person_form)
.await
.ok();
if let Some(discussion_languages) = data.discussion_languages.clone() {
LocalUserLanguage::update(&mut context.pool(), discussion_languages, local_user_id).await?;
}
let local_user_form = LocalUserUpdateForm {
email,
show_avatars: data.show_avatars,
show_read_posts: data.show_read_posts,
send_notifications_to_email: data.send_notifications_to_email,
show_nsfw: data.show_nsfw,
blur_nsfw: data.blur_nsfw,
auto_expand: data.auto_expand,
show_bot_accounts: data.show_bot_accounts,
show_scores: data.show_scores,
default_sort_type,
default_listing_type,
theme: data.theme.clone(),
interface_language: data.interface_language.clone(),
open_links_in_new_tab: data.open_links_in_new_tab,
infinite_scroll_enabled: data.infinite_scroll_enabled,
post_listing_mode: data.post_listing_mode,
enable_keyboard_navigation: data.enable_keyboard_navigation,
enable_animated_images: data.enable_animated_images,
collapse_bot_comments: data.collapse_bot_comments,
..Default::default()
};
LocalUser::update(&mut context.pool(), local_user_id, &local_user_form).await?;
// Update the vote display modes
let vote_display_modes_form = LocalUserVoteDisplayModeUpdateForm {
score: data.show_scores,
upvotes: data.show_upvotes,
downvotes: data.show_downvotes,
upvote_percentage: data.show_upvote_percentage,
};
LocalUserVoteDisplayMode::update(&mut context.pool(), local_user_id, &vote_display_modes_form)
.await?;
Ok(Json(SuccessResponse::default()))
}

View File

@ -0,0 +1,49 @@
use crate::check_totp_2fa_valid;
use actix_web::web::{Data, Json};
use lemmy_api_common::{
context::LemmyContext,
person::{UpdateTotp, UpdateTotpResponse},
};
use lemmy_db_schema::source::local_user::{LocalUser, LocalUserUpdateForm};
use lemmy_db_views::structs::LocalUserView;
use lemmy_utils::error::LemmyResult;
/// Enable or disable two-factor-authentication. The current setting is determined from
/// [LocalUser.totp_2fa_enabled].
///
/// To enable, you need to first call [generate_totp_secret] and then pass a valid token to this
/// function.
///
/// Disabling is only possible if 2FA was previously enabled. Again it is necessary to pass a valid
/// token.
#[tracing::instrument(skip(context))]
pub async fn update_totp(
data: Json<UpdateTotp>,
local_user_view: LocalUserView,
context: Data<LemmyContext>,
) -> LemmyResult<Json<UpdateTotpResponse>> {
check_totp_2fa_valid(
&local_user_view,
&Some(data.totp_token.clone()),
&context.settings().hostname,
)?;
// toggle the 2fa setting
let local_user_form = LocalUserUpdateForm {
totp_2fa_enabled: Some(data.enabled),
// if totp is enabled, leave unchanged. otherwise clear secret
totp_2fa_secret: if data.enabled { None } else { Some(None) },
..Default::default()
};
LocalUser::update(
&mut context.pool(),
local_user_view.local_user.id,
&local_user_form,
)
.await?;
Ok(Json(UpdateTotpResponse {
enabled: data.enabled,
}))
}

View File

@ -0,0 +1,23 @@
use crate::{local_user_view_from_jwt, read_auth_token};
use actix_web::{
web::{Data, Json},
HttpRequest,
};
use lemmy_api_common::{context::LemmyContext, SuccessResponse};
use lemmy_utils::error::{LemmyErrorType, LemmyResult};
/// Returns an error message if the auth token is invalid for any reason. Necessary because other
/// endpoints silently treat any call with invalid auth as unauthenticated.
#[tracing::instrument(skip(context))]
pub async fn validate_auth(
req: HttpRequest,
context: Data<LemmyContext>,
) -> LemmyResult<Json<SuccessResponse>> {
let jwt = read_auth_token(&req)?;
if let Some(jwt) = jwt {
local_user_view_from_jwt(&jwt, &context).await?;
} else {
Err(LemmyErrorType::NotLoggedIn)?;
}
Ok(Json(SuccessResponse::default()))
}

View File

@ -0,0 +1,60 @@
use actix_web::web::{Data, Json};
use lemmy_api_common::{
context::LemmyContext,
person::VerifyEmail,
utils::send_new_applicant_email_to_admins,
SuccessResponse,
};
use lemmy_db_schema::{
source::{
email_verification::EmailVerification,
local_user::{LocalUser, LocalUserUpdateForm},
},
RegistrationMode,
};
use lemmy_db_views::structs::{LocalUserView, SiteView};
use lemmy_utils::error::{LemmyErrorType, LemmyResult};
pub async fn verify_email(
data: Json<VerifyEmail>,
context: Data<LemmyContext>,
) -> LemmyResult<Json<SuccessResponse>> {
let site_view = SiteView::read_local(&mut context.pool())
.await?
.ok_or(LemmyErrorType::LocalSiteNotSetup)?;
let token = data.token.clone();
let verification = EmailVerification::read_for_token(&mut context.pool(), &token)
.await?
.ok_or(LemmyErrorType::TokenNotFound)?;
let form = LocalUserUpdateForm {
// necessary in case this is a new signup
email_verified: Some(true),
// necessary in case email of an existing user was changed
email: Some(Some(verification.email)),
..Default::default()
};
let local_user_id = verification.local_user_id;
LocalUser::update(&mut context.pool(), local_user_id, &form).await?;
EmailVerification::delete_old_tokens_for_local_user(&mut context.pool(), local_user_id).await?;
// send out notification about registration application to admins if enabled
if site_view.local_site.registration_mode == RegistrationMode::RequireApplication
&& site_view.local_site.application_email_admins
{
let local_user = LocalUserView::read(&mut context.pool(), local_user_id)
.await?
.ok_or(LemmyErrorType::CouldntFindPerson)?;
send_new_applicant_email_to_admins(
&local_user.person.name,
&mut context.pool(),
context.settings(),
)
.await?;
}
Ok(Json(SuccessResponse::default()))
}

View File

@ -1,895 +0,0 @@
use crate::{
check_community_ban,
check_downvotes_enabled,
check_optional_url,
collect_moderated_communities,
get_user_from_jwt,
get_user_from_jwt_opt,
is_mod_or_admin,
Perform,
};
use actix_web::web::Data;
use lemmy_apub::{generate_apub_endpoint, ApubLikeableType, ApubObjectType, EndpointType};
use lemmy_db_queries::{
source::post::Post_,
Crud,
Likeable,
ListingType,
Reportable,
Saveable,
SortType,
};
use lemmy_db_schema::{
naive_now,
source::{
moderator::*,
post::*,
post_report::{PostReport, PostReportForm},
},
};
use lemmy_db_views::{
comment_view::CommentQueryBuilder,
post_report_view::{PostReportQueryBuilder, PostReportView},
post_view::{PostQueryBuilder, PostView},
};
use lemmy_db_views_actor::{
community_moderator_view::CommunityModeratorView,
community_view::CommunityView,
};
use lemmy_structs::{blocking, post::*};
use lemmy_utils::{
request::fetch_iframely_and_pictrs_data,
utils::{check_slurs, check_slurs_opt, is_valid_post_title},
APIError,
ConnectionId,
LemmyError,
};
use lemmy_websocket::{
messages::{GetPostUsersOnline, SendModRoomMessage, SendPost, SendUserRoomMessage},
LemmyContext,
UserOperation,
};
use std::str::FromStr;
#[async_trait::async_trait(?Send)]
impl Perform for CreatePost {
type Response = PostResponse;
async fn perform(
&self,
context: &Data<LemmyContext>,
websocket_id: Option<ConnectionId>,
) -> Result<PostResponse, LemmyError> {
let data: &CreatePost = &self;
let user = get_user_from_jwt(&data.auth, context.pool()).await?;
check_slurs(&data.name)?;
check_slurs_opt(&data.body)?;
if !is_valid_post_title(&data.name) {
return Err(APIError::err("invalid_post_title").into());
}
check_community_ban(user.id, data.community_id, context.pool()).await?;
check_optional_url(&Some(data.url.to_owned()))?;
// Fetch Iframely and pictrs cached image
let (iframely_title, iframely_description, iframely_html, pictrs_thumbnail) =
fetch_iframely_and_pictrs_data(context.client(), data.url.to_owned()).await;
let post_form = PostForm {
name: data.name.trim().to_owned(),
url: data.url.to_owned(),
body: data.body.to_owned(),
community_id: data.community_id,
creator_id: user.id,
removed: None,
deleted: None,
nsfw: data.nsfw,
locked: None,
stickied: None,
updated: None,
embed_title: iframely_title,
embed_description: iframely_description,
embed_html: iframely_html,
thumbnail_url: pictrs_thumbnail,
ap_id: None,
local: true,
published: None,
};
let inserted_post =
match blocking(context.pool(), move |conn| Post::create(conn, &post_form)).await? {
Ok(post) => post,
Err(e) => {
let err_type = if e.to_string() == "value too long for type character varying(200)" {
"post_title_too_long"
} else {
"couldnt_create_post"
};
return Err(APIError::err(err_type).into());
}
};
let inserted_post_id = inserted_post.id;
let updated_post = match blocking(context.pool(), move |conn| -> Result<Post, LemmyError> {
let apub_id = generate_apub_endpoint(EndpointType::Post, &inserted_post_id.to_string())?;
Ok(Post::update_ap_id(conn, inserted_post_id, apub_id)?)
})
.await?
{
Ok(post) => post,
Err(_e) => return Err(APIError::err("couldnt_create_post").into()),
};
updated_post.send_create(&user, context).await?;
// They like their own post by default
let like_form = PostLikeForm {
post_id: inserted_post.id,
user_id: user.id,
score: 1,
};
let like = move |conn: &'_ _| PostLike::like(conn, &like_form);
if blocking(context.pool(), like).await?.is_err() {
return Err(APIError::err("couldnt_like_post").into());
}
updated_post.send_like(&user, context).await?;
// Refetch the view
let inserted_post_id = inserted_post.id;
let post_view = match blocking(context.pool(), move |conn| {
PostView::read(conn, inserted_post_id, Some(user.id))
})
.await?
{
Ok(post) => post,
Err(_e) => return Err(APIError::err("couldnt_find_post").into()),
};
let res = PostResponse { post_view };
context.chat_server().do_send(SendPost {
op: UserOperation::CreatePost,
post: res.clone(),
websocket_id,
});
Ok(res)
}
}
#[async_trait::async_trait(?Send)]
impl Perform for GetPost {
type Response = GetPostResponse;
async fn perform(
&self,
context: &Data<LemmyContext>,
_websocket_id: Option<ConnectionId>,
) -> Result<GetPostResponse, LemmyError> {
let data: &GetPost = &self;
let user = get_user_from_jwt_opt(&data.auth, context.pool()).await?;
let user_id = user.map(|u| u.id);
let id = data.id;
let post_view = match blocking(context.pool(), move |conn| {
PostView::read(conn, id, user_id)
})
.await?
{
Ok(post) => post,
Err(_e) => return Err(APIError::err("couldnt_find_post").into()),
};
let id = data.id;
let comments = blocking(context.pool(), move |conn| {
CommentQueryBuilder::create(conn)
.my_user_id(user_id)
.post_id(id)
.limit(9999)
.list()
})
.await??;
let community_id = post_view.community.id;
let moderators = blocking(context.pool(), move |conn| {
CommunityModeratorView::for_community(conn, community_id)
})
.await??;
// Necessary for the sidebar
let community_view = match blocking(context.pool(), move |conn| {
CommunityView::read(conn, community_id, user_id)
})
.await?
{
Ok(community) => community,
Err(_e) => return Err(APIError::err("couldnt_find_community").into()),
};
let online = context
.chat_server()
.send(GetPostUsersOnline { post_id: data.id })
.await
.unwrap_or(1);
// Return the jwt
Ok(GetPostResponse {
post_view,
community_view,
comments,
moderators,
online,
})
}
}
#[async_trait::async_trait(?Send)]
impl Perform for GetPosts {
type Response = GetPostsResponse;
async fn perform(
&self,
context: &Data<LemmyContext>,
_websocket_id: Option<ConnectionId>,
) -> Result<GetPostsResponse, LemmyError> {
let data: &GetPosts = &self;
let user = get_user_from_jwt_opt(&data.auth, context.pool()).await?;
let user_id = match &user {
Some(user) => Some(user.id),
None => None,
};
let show_nsfw = match &user {
Some(user) => user.show_nsfw,
None => false,
};
let type_ = ListingType::from_str(&data.type_)?;
let sort = SortType::from_str(&data.sort)?;
let page = data.page;
let limit = data.limit;
let community_id = data.community_id;
let community_name = data.community_name.to_owned();
let posts = match blocking(context.pool(), move |conn| {
PostQueryBuilder::create(conn)
.listing_type(&type_)
.sort(&sort)
.show_nsfw(show_nsfw)
.community_id(community_id)
.community_name(community_name)
.my_user_id(user_id)
.page(page)
.limit(limit)
.list()
})
.await?
{
Ok(posts) => posts,
Err(_e) => return Err(APIError::err("couldnt_get_posts").into()),
};
Ok(GetPostsResponse { posts })
}
}
#[async_trait::async_trait(?Send)]
impl Perform for CreatePostLike {
type Response = PostResponse;
async fn perform(
&self,
context: &Data<LemmyContext>,
websocket_id: Option<ConnectionId>,
) -> Result<PostResponse, LemmyError> {
let data: &CreatePostLike = &self;
let user = get_user_from_jwt(&data.auth, context.pool()).await?;
// Don't do a downvote if site has downvotes disabled
check_downvotes_enabled(data.score, context.pool()).await?;
// Check for a community ban
let post_id = data.post_id;
let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??;
check_community_ban(user.id, post.community_id, context.pool()).await?;
let like_form = PostLikeForm {
post_id: data.post_id,
user_id: user.id,
score: data.score,
};
// Remove any likes first
let user_id = user.id;
blocking(context.pool(), move |conn| {
PostLike::remove(conn, user_id, post_id)
})
.await??;
// Only add the like if the score isnt 0
let do_add = like_form.score != 0 && (like_form.score == 1 || like_form.score == -1);
if do_add {
let like_form2 = like_form.clone();
let like = move |conn: &'_ _| PostLike::like(conn, &like_form2);
if blocking(context.pool(), like).await?.is_err() {
return Err(APIError::err("couldnt_like_post").into());
}
if like_form.score == 1 {
post.send_like(&user, context).await?;
} else if like_form.score == -1 {
post.send_dislike(&user, context).await?;
}
} else {
post.send_undo_like(&user, context).await?;
}
let post_id = data.post_id;
let user_id = user.id;
let post_view = match blocking(context.pool(), move |conn| {
PostView::read(conn, post_id, Some(user_id))
})
.await?
{
Ok(post) => post,
Err(_e) => return Err(APIError::err("couldnt_find_post").into()),
};
let res = PostResponse { post_view };
context.chat_server().do_send(SendPost {
op: UserOperation::CreatePostLike,
post: res.clone(),
websocket_id,
});
Ok(res)
}
}
#[async_trait::async_trait(?Send)]
impl Perform for EditPost {
type Response = PostResponse;
async fn perform(
&self,
context: &Data<LemmyContext>,
websocket_id: Option<ConnectionId>,
) -> Result<PostResponse, LemmyError> {
let data: &EditPost = &self;
let user = get_user_from_jwt(&data.auth, context.pool()).await?;
check_slurs(&data.name)?;
check_slurs_opt(&data.body)?;
if !is_valid_post_title(&data.name) {
return Err(APIError::err("invalid_post_title").into());
}
let post_id = data.post_id;
let orig_post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??;
check_community_ban(user.id, orig_post.community_id, context.pool()).await?;
// Verify that only the creator can edit
if !Post::is_post_creator(user.id, orig_post.creator_id) {
return Err(APIError::err("no_post_edit_allowed").into());
}
// Fetch Iframely and Pictrs cached image
let (iframely_title, iframely_description, iframely_html, pictrs_thumbnail) =
fetch_iframely_and_pictrs_data(context.client(), data.url.to_owned()).await;
let post_form = PostForm {
name: data.name.trim().to_owned(),
url: data.url.to_owned(),
body: data.body.to_owned(),
nsfw: data.nsfw,
creator_id: orig_post.creator_id.to_owned(),
community_id: orig_post.community_id,
removed: Some(orig_post.removed),
deleted: Some(orig_post.deleted),
locked: Some(orig_post.locked),
stickied: Some(orig_post.stickied),
updated: Some(naive_now()),
embed_title: iframely_title,
embed_description: iframely_description,
embed_html: iframely_html,
thumbnail_url: pictrs_thumbnail,
ap_id: Some(orig_post.ap_id),
local: orig_post.local,
published: None,
};
let post_id = data.post_id;
let res = blocking(context.pool(), move |conn| {
Post::update(conn, post_id, &post_form)
})
.await?;
let updated_post: Post = match res {
Ok(post) => post,
Err(e) => {
let err_type = if e.to_string() == "value too long for type character varying(200)" {
"post_title_too_long"
} else {
"couldnt_update_post"
};
return Err(APIError::err(err_type).into());
}
};
// Send apub update
updated_post.send_update(&user, context).await?;
let post_id = data.post_id;
let post_view = blocking(context.pool(), move |conn| {
PostView::read(conn, post_id, Some(user.id))
})
.await??;
let res = PostResponse { post_view };
context.chat_server().do_send(SendPost {
op: UserOperation::EditPost,
post: res.clone(),
websocket_id,
});
Ok(res)
}
}
#[async_trait::async_trait(?Send)]
impl Perform for DeletePost {
type Response = PostResponse;
async fn perform(
&self,
context: &Data<LemmyContext>,
websocket_id: Option<ConnectionId>,
) -> Result<PostResponse, LemmyError> {
let data: &DeletePost = &self;
let user = get_user_from_jwt(&data.auth, context.pool()).await?;
let post_id = data.post_id;
let orig_post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??;
check_community_ban(user.id, orig_post.community_id, context.pool()).await?;
// Verify that only the creator can delete
if !Post::is_post_creator(user.id, orig_post.creator_id) {
return Err(APIError::err("no_post_edit_allowed").into());
}
// Update the post
let post_id = data.post_id;
let deleted = data.deleted;
let updated_post = blocking(context.pool(), move |conn| {
Post::update_deleted(conn, post_id, deleted)
})
.await??;
// apub updates
if deleted {
updated_post.send_delete(&user, context).await?;
} else {
updated_post.send_undo_delete(&user, context).await?;
}
// Refetch the post
let post_id = data.post_id;
let post_view = blocking(context.pool(), move |conn| {
PostView::read(conn, post_id, Some(user.id))
})
.await??;
let res = PostResponse { post_view };
context.chat_server().do_send(SendPost {
op: UserOperation::DeletePost,
post: res.clone(),
websocket_id,
});
Ok(res)
}
}
#[async_trait::async_trait(?Send)]
impl Perform for RemovePost {
type Response = PostResponse;
async fn perform(
&self,
context: &Data<LemmyContext>,
websocket_id: Option<ConnectionId>,
) -> Result<PostResponse, LemmyError> {
let data: &RemovePost = &self;
let user = get_user_from_jwt(&data.auth, context.pool()).await?;
let post_id = data.post_id;
let orig_post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??;
check_community_ban(user.id, orig_post.community_id, context.pool()).await?;
// Verify that only the mods can remove
is_mod_or_admin(context.pool(), user.id, orig_post.community_id).await?;
// Update the post
let post_id = data.post_id;
let removed = data.removed;
let updated_post = blocking(context.pool(), move |conn| {
Post::update_removed(conn, post_id, removed)
})
.await??;
// Mod tables
let form = ModRemovePostForm {
mod_user_id: user.id,
post_id: data.post_id,
removed: Some(removed),
reason: data.reason.to_owned(),
};
blocking(context.pool(), move |conn| {
ModRemovePost::create(conn, &form)
})
.await??;
// apub updates
if removed {
updated_post.send_remove(&user, context).await?;
} else {
updated_post.send_undo_remove(&user, context).await?;
}
// Refetch the post
let post_id = data.post_id;
let user_id = user.id;
let post_view = blocking(context.pool(), move |conn| {
PostView::read(conn, post_id, Some(user_id))
})
.await??;
let res = PostResponse { post_view };
context.chat_server().do_send(SendPost {
op: UserOperation::RemovePost,
post: res.clone(),
websocket_id,
});
Ok(res)
}
}
#[async_trait::async_trait(?Send)]
impl Perform for LockPost {
type Response = PostResponse;
async fn perform(
&self,
context: &Data<LemmyContext>,
websocket_id: Option<ConnectionId>,
) -> Result<PostResponse, LemmyError> {
let data: &LockPost = &self;
let user = get_user_from_jwt(&data.auth, context.pool()).await?;
let post_id = data.post_id;
let orig_post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??;
check_community_ban(user.id, orig_post.community_id, context.pool()).await?;
// Verify that only the mods can lock
is_mod_or_admin(context.pool(), user.id, orig_post.community_id).await?;
// Update the post
let post_id = data.post_id;
let locked = data.locked;
let updated_post = blocking(context.pool(), move |conn| {
Post::update_locked(conn, post_id, locked)
})
.await??;
// Mod tables
let form = ModLockPostForm {
mod_user_id: user.id,
post_id: data.post_id,
locked: Some(locked),
};
blocking(context.pool(), move |conn| ModLockPost::create(conn, &form)).await??;
// apub updates
updated_post.send_update(&user, context).await?;
// Refetch the post
let post_id = data.post_id;
let post_view = blocking(context.pool(), move |conn| {
PostView::read(conn, post_id, Some(user.id))
})
.await??;
let res = PostResponse { post_view };
context.chat_server().do_send(SendPost {
op: UserOperation::LockPost,
post: res.clone(),
websocket_id,
});
Ok(res)
}
}
#[async_trait::async_trait(?Send)]
impl Perform for StickyPost {
type Response = PostResponse;
async fn perform(
&self,
context: &Data<LemmyContext>,
websocket_id: Option<ConnectionId>,
) -> Result<PostResponse, LemmyError> {
let data: &StickyPost = &self;
let user = get_user_from_jwt(&data.auth, context.pool()).await?;
let post_id = data.post_id;
let orig_post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??;
check_community_ban(user.id, orig_post.community_id, context.pool()).await?;
// Verify that only the mods can sticky
is_mod_or_admin(context.pool(), user.id, orig_post.community_id).await?;
// Update the post
let post_id = data.post_id;
let stickied = data.stickied;
let updated_post = blocking(context.pool(), move |conn| {
Post::update_stickied(conn, post_id, stickied)
})
.await??;
// Mod tables
let form = ModStickyPostForm {
mod_user_id: user.id,
post_id: data.post_id,
stickied: Some(stickied),
};
blocking(context.pool(), move |conn| {
ModStickyPost::create(conn, &form)
})
.await??;
// Apub updates
// TODO stickied should pry work like locked for ease of use
updated_post.send_update(&user, context).await?;
// Refetch the post
let post_id = data.post_id;
let post_view = blocking(context.pool(), move |conn| {
PostView::read(conn, post_id, Some(user.id))
})
.await??;
let res = PostResponse { post_view };
context.chat_server().do_send(SendPost {
op: UserOperation::StickyPost,
post: res.clone(),
websocket_id,
});
Ok(res)
}
}
#[async_trait::async_trait(?Send)]
impl Perform for SavePost {
type Response = PostResponse;
async fn perform(
&self,
context: &Data<LemmyContext>,
_websocket_id: Option<ConnectionId>,
) -> Result<PostResponse, LemmyError> {
let data: &SavePost = &self;
let user = get_user_from_jwt(&data.auth, context.pool()).await?;
let post_saved_form = PostSavedForm {
post_id: data.post_id,
user_id: user.id,
};
if data.save {
let save = move |conn: &'_ _| PostSaved::save(conn, &post_saved_form);
if blocking(context.pool(), save).await?.is_err() {
return Err(APIError::err("couldnt_save_post").into());
}
} else {
let unsave = move |conn: &'_ _| PostSaved::unsave(conn, &post_saved_form);
if blocking(context.pool(), unsave).await?.is_err() {
return Err(APIError::err("couldnt_save_post").into());
}
}
let post_id = data.post_id;
let user_id = user.id;
let post_view = blocking(context.pool(), move |conn| {
PostView::read(conn, post_id, Some(user_id))
})
.await??;
Ok(PostResponse { post_view })
}
}
/// Creates a post report and notifies the moderators of the community
#[async_trait::async_trait(?Send)]
impl Perform for CreatePostReport {
type Response = CreatePostReportResponse;
async fn perform(
&self,
context: &Data<LemmyContext>,
websocket_id: Option<ConnectionId>,
) -> Result<CreatePostReportResponse, LemmyError> {
let data: &CreatePostReport = &self;
let user = get_user_from_jwt(&data.auth, context.pool()).await?;
// check size of report and check for whitespace
let reason = data.reason.trim();
if reason.is_empty() {
return Err(APIError::err("report_reason_required").into());
}
if reason.chars().count() > 1000 {
return Err(APIError::err("report_too_long").into());
}
let user_id = user.id;
let post_id = data.post_id;
let post_view = blocking(context.pool(), move |conn| {
PostView::read(&conn, post_id, None)
})
.await??;
check_community_ban(user_id, post_view.community.id, context.pool()).await?;
let report_form = PostReportForm {
creator_id: user_id,
post_id,
original_post_name: post_view.post.name,
original_post_url: post_view.post.url,
original_post_body: post_view.post.body,
reason: data.reason.to_owned(),
};
let report = match blocking(context.pool(), move |conn| {
PostReport::report(conn, &report_form)
})
.await?
{
Ok(report) => report,
Err(_e) => return Err(APIError::err("couldnt_create_report").into()),
};
let res = CreatePostReportResponse { success: true };
context.chat_server().do_send(SendUserRoomMessage {
op: UserOperation::CreatePostReport,
response: res.clone(),
recipient_id: user.id,
websocket_id,
});
context.chat_server().do_send(SendModRoomMessage {
op: UserOperation::CreatePostReport,
response: report,
community_id: post_view.community.id,
websocket_id,
});
Ok(res)
}
}
/// Resolves or unresolves a post report and notifies the moderators of the community
#[async_trait::async_trait(?Send)]
impl Perform for ResolvePostReport {
type Response = ResolvePostReportResponse;
async fn perform(
&self,
context: &Data<LemmyContext>,
websocket_id: Option<ConnectionId>,
) -> Result<ResolvePostReportResponse, LemmyError> {
let data: &ResolvePostReport = &self;
let user = get_user_from_jwt(&data.auth, context.pool()).await?;
let report_id = data.report_id;
let report = blocking(context.pool(), move |conn| {
PostReportView::read(&conn, report_id)
})
.await??;
let user_id = user.id;
is_mod_or_admin(context.pool(), user_id, report.community.id).await?;
let resolved = data.resolved;
let resolve_fun = move |conn: &'_ _| {
if resolved {
PostReport::resolve(conn, report_id, user_id)
} else {
PostReport::unresolve(conn, report_id, user_id)
}
};
let res = ResolvePostReportResponse {
report_id,
resolved: true,
};
if blocking(context.pool(), resolve_fun).await?.is_err() {
return Err(APIError::err("couldnt_resolve_report").into());
};
context.chat_server().do_send(SendModRoomMessage {
op: UserOperation::ResolvePostReport,
response: res.clone(),
community_id: report.community.id,
websocket_id,
});
Ok(res)
}
}
/// Lists post reports for a community if an id is supplied
/// or returns all post reports for communities a user moderates
#[async_trait::async_trait(?Send)]
impl Perform for ListPostReports {
type Response = ListPostReportsResponse;
async fn perform(
&self,
context: &Data<LemmyContext>,
websocket_id: Option<ConnectionId>,
) -> Result<ListPostReportsResponse, LemmyError> {
let data: &ListPostReports = &self;
let user = get_user_from_jwt(&data.auth, context.pool()).await?;
let user_id = user.id;
let community_id = data.community;
let community_ids =
collect_moderated_communities(user_id, community_id, context.pool()).await?;
let page = data.page;
let limit = data.limit;
let posts = blocking(context.pool(), move |conn| {
PostReportQueryBuilder::create(conn)
.community_ids(community_ids)
.page(page)
.limit(limit)
.list()
})
.await??;
let res = ListPostReportsResponse { posts };
context.chat_server().do_send(SendUserRoomMessage {
op: UserOperation::ListPostReports,
response: res.clone(),
recipient_id: user.id,
websocket_id,
});
Ok(res)
}
}

View File

@ -0,0 +1,82 @@
use activitypub_federation::config::Data;
use actix_web::web::Json;
use lemmy_api_common::{
build_response::build_post_response,
context::LemmyContext,
post::{FeaturePost, PostResponse},
send_activity::{ActivityChannel, SendActivityData},
utils::{check_community_mod_action, is_admin},
};
use lemmy_db_schema::{
source::{
moderator::{ModFeaturePost, ModFeaturePostForm},
post::{Post, PostUpdateForm},
},
traits::Crud,
PostFeatureType,
};
use lemmy_db_views::structs::LocalUserView;
use lemmy_utils::{error::LemmyResult, LemmyErrorType};
#[tracing::instrument(skip(context))]
pub async fn feature_post(
data: Json<FeaturePost>,
context: Data<LemmyContext>,
local_user_view: LocalUserView,
) -> LemmyResult<Json<PostResponse>> {
let post_id = data.post_id;
let orig_post = Post::read(&mut context.pool(), post_id)
.await?
.ok_or(LemmyErrorType::CouldntFindPost)?;
check_community_mod_action(
&local_user_view.person,
orig_post.community_id,
false,
&mut context.pool(),
)
.await?;
if data.feature_type == PostFeatureType::Local {
is_admin(&local_user_view)?;
}
// Update the post
let post_id = data.post_id;
let new_post: PostUpdateForm = if data.feature_type == PostFeatureType::Community {
PostUpdateForm {
featured_community: Some(data.featured),
..Default::default()
}
} else {
PostUpdateForm {
featured_local: Some(data.featured),
..Default::default()
}
};
let post = Post::update(&mut context.pool(), post_id, &new_post).await?;
// Mod tables
let form = ModFeaturePostForm {
mod_person_id: local_user_view.person.id,
post_id: data.post_id,
featured: data.featured,
is_featured_community: data.feature_type == PostFeatureType::Community,
};
ModFeaturePost::create(&mut context.pool(), &form).await?;
ActivityChannel::submit_activity(
SendActivityData::FeaturePost(post, local_user_view.person.clone(), data.featured),
&context,
)
.await?;
build_post_response(
&context,
orig_post.community_id,
&local_user_view.person,
post_id,
)
.await
}

Some files were not shown because too many files have changed in this diff Show More