-
-
Notifications
You must be signed in to change notification settings - Fork 949
Expand file tree
/
Copy pathutils.rs
More file actions
1149 lines (1028 loc) · 33.1 KB
/
utils.rs
File metadata and controls
1149 lines (1028 loc) · 33.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::{
claims::Claims,
context::LemmyContext,
post::CreateGalleryItem,
request::{
delete_image_from_pictrs,
fetch_pictrs_proxied_image_details,
purge_image_from_pictrs_url,
},
site::{FederatedInstances, InstanceWithFederationState},
};
use actix_web::{http::header::Header, HttpRequest};
use actix_web_httpauth::headers::authorization::{Authorization, Bearer};
use chrono::{DateTime, Days, Local, TimeZone, Utc};
use enum_map::{enum_map, EnumMap};
use lemmy_db_schema::{
newtypes::{CommentId, CommunityId, DbUrl, InstanceId, PersonId, PostId, PostOrCommentId},
source::{
comment::{Comment, CommentActions},
community::{Community, CommunityActions, CommunityUpdateForm},
images::{ImageDetails, RemoteImage},
instance::{Instance, InstanceActions},
local_site::LocalSite,
local_site_rate_limit::LocalSiteRateLimit,
local_site_url_blocklist::LocalSiteUrlBlocklist,
mod_log::moderator::{
ModRemoveComment,
ModRemoveCommentForm,
ModRemovePost,
ModRemovePostForm,
},
oauth_account::OAuthAccount,
person::{Person, PersonActions, PersonUpdateForm},
post::{Post, PostActions, PostReadCommentsForm},
post_gallery::{PostGallery, PostGalleryInsertForm},
private_message::PrivateMessage,
registration_application::RegistrationApplication,
site::Site,
},
traits::{Blockable, Crud, Likeable, ReadComments},
utils::{diesel_url_create, DbPool},
};
use lemmy_db_schema_file::enums::{FederationMode, RegistrationMode};
use lemmy_db_views_community_follower::CommunityFollowerView;
use lemmy_db_views_community_moderator::CommunityModeratorView;
use lemmy_db_views_community_person_ban::CommunityPersonBanView;
use lemmy_db_views_local_image::LocalImageView;
use lemmy_db_views_local_user::LocalUserView;
use lemmy_db_views_person::PersonView;
use lemmy_db_views_site::SiteView;
use lemmy_utils::{
error::{LemmyError, LemmyErrorExt, LemmyErrorExt2, LemmyErrorType, LemmyResult},
rate_limit::{ActionType, BucketConfig},
settings::{structs::PictrsImageMode, SETTINGS},
spawn_try_task,
utils::{
markdown::{image_links::markdown_rewrite_image_links, markdown_check_for_blocked_urls},
slurs::remove_slurs,
validation::{
build_and_check_regex,
clean_urls_in_text,
is_url_blocked,
is_valid_alt_text_field,
is_valid_post_title,
is_valid_url,
},
},
CacheLock,
CACHE_DURATION_FEDERATION,
};
use moka::future::Cache;
use regex::{escape, Regex, RegexSet};
use std::sync::LazyLock;
use tracing::Instrument;
use url::{ParseError, Url};
use urlencoding::encode;
use webmention::{Webmention, WebmentionError};
pub const AUTH_COOKIE_NAME: &str = "jwt";
pub async fn check_is_mod_or_admin(
pool: &mut DbPool<'_>,
person_id: PersonId,
community_id: CommunityId,
local_instance_id: InstanceId,
) -> LemmyResult<()> {
let is_mod =
CommunityModeratorView::check_is_community_moderator(pool, community_id, person_id).await;
if is_mod.is_ok()
|| PersonView::read(pool, person_id, local_instance_id, false)
.await
.is_ok_and(|t| t.is_admin)
{
Ok(())
} else {
Err(LemmyErrorType::NotAModOrAdmin)?
}
}
/// Checks if a person is an admin, or moderator of any community.
pub(crate) async fn check_is_mod_of_any_or_admin(
pool: &mut DbPool<'_>,
person_id: PersonId,
local_instance_id: InstanceId,
) -> LemmyResult<()> {
let is_mod_of_any = CommunityModeratorView::is_community_moderator_of_any(pool, person_id).await;
if is_mod_of_any.is_ok()
|| PersonView::read(pool, person_id, local_instance_id, false)
.await
.is_ok_and(|t| t.is_admin)
{
Ok(())
} else {
Err(LemmyErrorType::NotAModOrAdmin)?
}
}
pub async fn is_mod_or_admin(
pool: &mut DbPool<'_>,
local_user_view: &LocalUserView,
community_id: CommunityId,
) -> LemmyResult<()> {
check_local_user_valid(local_user_view)?;
check_is_mod_or_admin(
pool,
local_user_view.person.id,
community_id,
local_user_view.person.instance_id,
)
.await
}
pub async fn is_mod_or_admin_opt(
pool: &mut DbPool<'_>,
local_user_view: Option<&LocalUserView>,
community_id: Option<CommunityId>,
) -> LemmyResult<()> {
if let Some(local_user_view) = local_user_view {
if let Some(community_id) = community_id {
is_mod_or_admin(pool, local_user_view, community_id).await
} else {
is_admin(local_user_view)
}
} else {
Err(LemmyErrorType::NotAModOrAdmin)?
}
}
/// Check that a person is either a mod of any community, or an admin
///
/// Should only be used for read operations
pub async fn check_community_mod_of_any_or_admin_action(
local_user_view: &LocalUserView,
pool: &mut DbPool<'_>,
) -> LemmyResult<()> {
let person = &local_user_view.person;
check_local_user_valid(local_user_view)?;
check_is_mod_of_any_or_admin(pool, person.id, person.instance_id).await
}
pub fn is_admin(local_user_view: &LocalUserView) -> LemmyResult<()> {
check_local_user_valid(local_user_view)?;
if !local_user_view.local_user.admin {
Err(LemmyErrorType::NotAnAdmin)?
} else {
Ok(())
}
}
pub fn is_top_mod(
local_user_view: &LocalUserView,
community_mods: &[CommunityModeratorView],
) -> LemmyResult<()> {
check_local_user_valid(local_user_view)?;
if local_user_view.person.id
!= community_mods
.first()
.map(|cm| cm.moderator.id)
.unwrap_or(PersonId(0))
{
Err(LemmyErrorType::NotTopMod)?
} else {
Ok(())
}
}
/// Updates the read comment count for a post. Usually done when reading or creating a new comment.
pub async fn update_read_comments(
person_id: PersonId,
post_id: PostId,
read_comments: i64,
pool: &mut DbPool<'_>,
) -> LemmyResult<()> {
let person_post_agg_form = PostReadCommentsForm::new(post_id, person_id, read_comments);
PostActions::update_read_comments(pool, &person_post_agg_form).await?;
Ok(())
}
pub fn check_local_user_valid(local_user_view: &LocalUserView) -> LemmyResult<()> {
// Check for a site ban
if local_user_view.banned() {
Err(LemmyErrorType::SiteBan)?
}
check_local_user_deleted(local_user_view)
}
/// Check for account deletion
pub fn check_local_user_deleted(local_user_view: &LocalUserView) -> LemmyResult<()> {
if local_user_view.person.deleted {
Err(LemmyErrorType::Deleted)?
} else {
Ok(())
}
}
pub fn check_person_valid(person_view: &PersonView) -> LemmyResult<()> {
// Check for a site ban
if person_view.creator_banned {
Err(LemmyErrorType::SiteBan)?
}
// check for account deletion
else if person_view.person.deleted {
Err(LemmyErrorType::Deleted)?
} else {
Ok(())
}
}
/// Check if the user's email is verified if email verification is turned on
/// However, skip checking verification if the user is an admin
pub 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(())
}
pub 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?;
if registration.admin_id.is_some() {
Err(LemmyErrorType::RegistrationDenied {
reason: registration.deny_reason,
})?
} else {
Err(LemmyErrorType::RegistrationApplicationIsPending)?
}
}
Ok(())
}
/// Checks that a normal user action (eg posting or voting) is allowed in a given community.
///
/// In particular it checks that neither the user nor community are banned or deleted, and that
/// the user isn't banned.
pub async fn check_community_user_action(
local_user_view: &LocalUserView,
community: &Community,
pool: &mut DbPool<'_>,
) -> LemmyResult<()> {
check_local_user_valid(local_user_view)?;
check_community_deleted_removed(community)?;
CommunityPersonBanView::check(pool, local_user_view.person.id, community.id).await?;
CommunityFollowerView::check_private_community_action(pool, local_user_view.person.id, community)
.await?;
InstanceActions::check_ban(pool, local_user_view.person.id, community.instance_id).await?;
Ok(())
}
pub fn check_community_deleted_removed(community: &Community) -> LemmyResult<()> {
if community.deleted || community.removed {
Err(LemmyErrorType::Deleted)?
}
Ok(())
}
/// Check that the given user can perform a mod action in the community.
///
/// In particular it checks that he is an admin or mod, wasn't banned and the community isn't
/// removed/deleted.
pub async fn check_community_mod_action(
local_user_view: &LocalUserView,
community: &Community,
allow_deleted: bool,
pool: &mut DbPool<'_>,
) -> LemmyResult<()> {
is_mod_or_admin(pool, local_user_view, community.id).await?;
CommunityPersonBanView::check(pool, local_user_view.person.id, community.id).await?;
// it must be possible to restore deleted community
if !allow_deleted {
check_community_deleted_removed(community)?;
}
Ok(())
}
/// Don't allow creating reports for removed / deleted posts
pub fn check_post_deleted_or_removed(post: &Post) -> LemmyResult<()> {
if post.deleted || post.removed {
Err(LemmyErrorType::Deleted)?
} else {
Ok(())
}
}
pub fn check_comment_deleted_or_removed(comment: &Comment) -> LemmyResult<()> {
if comment.deleted || comment.removed {
Err(LemmyErrorType::Deleted)?
} else {
Ok(())
}
}
pub async fn check_person_instance_community_block(
my_id: PersonId,
potential_blocker_id: PersonId,
community_instance_id: InstanceId,
community_id: CommunityId,
pool: &mut DbPool<'_>,
) -> LemmyResult<()> {
PersonActions::read_block(pool, potential_blocker_id, my_id).await?;
InstanceActions::read_block(pool, potential_blocker_id, community_instance_id).await?;
CommunityActions::read_block(pool, potential_blocker_id, community_id).await?;
Ok(())
}
pub async fn check_local_vote_mode(
score: i16,
post_or_comment_id: PostOrCommentId,
local_site: &LocalSite,
person_id: PersonId,
pool: &mut DbPool<'_>,
) -> LemmyResult<()> {
let (downvote_setting, upvote_setting) = match post_or_comment_id {
PostOrCommentId::Post(_) => (local_site.post_downvotes, local_site.post_upvotes),
PostOrCommentId::Comment(_) => (local_site.comment_downvotes, local_site.comment_upvotes),
};
let downvote_fail = score == -1 && downvote_setting == FederationMode::Disable;
let upvote_fail = score == 1 && upvote_setting == FederationMode::Disable;
// Undo previous vote for item if new vote fails
if downvote_fail || upvote_fail {
match post_or_comment_id {
PostOrCommentId::Post(post_id) => PostActions::remove_like(pool, person_id, post_id).await?,
PostOrCommentId::Comment(comment_id) => {
CommentActions::remove_like(pool, person_id, comment_id).await?
}
};
}
Ok(())
}
/// Dont allow bots to do certain actions, like voting
pub fn check_bot_account(person: &Person) -> LemmyResult<()> {
if person.bot_account {
Err(LemmyErrorType::InvalidBotAction)?
} else {
Ok(())
}
}
pub fn check_private_instance(
local_user_view: &Option<LocalUserView>,
local_site: &LocalSite,
) -> LemmyResult<()> {
if local_user_view.is_none() && local_site.private_instance {
Err(LemmyErrorType::InstanceIsPrivate)?
} else {
Ok(())
}
}
/// If private messages are disabled, dont allow them to be sent / received
pub fn check_private_messages_enabled(local_user_view: &LocalUserView) -> Result<(), LemmyError> {
if !local_user_view.local_user.enable_private_messages {
Err(LemmyErrorType::CouldntCreatePrivateMessage)?
} else {
Ok(())
}
}
pub async fn build_federated_instances(
local_site: &LocalSite,
pool: &mut DbPool<'_>,
) -> LemmyResult<Option<FederatedInstances>> {
if local_site.federation_enabled {
let mut linked = Vec::new();
let mut allowed = Vec::new();
let mut blocked = Vec::new();
let all = Instance::read_all_with_fed_state(pool).await?;
for (instance, federation_state, is_blocked, is_allowed) in all {
let i = InstanceWithFederationState {
instance,
federation_state: federation_state.map(std::convert::Into::into),
};
if is_blocked {
// blocked instances will only have an entry here if they had been federated with in the
// past.
blocked.push(i);
} else if is_allowed {
allowed.push(i.clone());
linked.push(i);
} else {
// not explicitly allowed but implicitly linked
linked.push(i);
}
}
Ok(Some(FederatedInstances {
linked,
allowed,
blocked,
}))
} else {
Ok(None)
}
}
/// Checks the password length
pub fn password_length_check(pass: &str) -> LemmyResult<()> {
if !(10..=60).contains(&pass.chars().count()) {
Err(LemmyErrorType::InvalidPassword)?
} else {
Ok(())
}
}
/// Checks for a honeypot. If this field is filled, fail the rest of the function
pub fn honeypot_check(honeypot: &Option<String>) -> LemmyResult<()> {
if honeypot.is_some() && honeypot != &Some(String::new()) {
Err(LemmyErrorType::HoneypotFailed)?
} else {
Ok(())
}
}
pub fn local_site_rate_limit_to_rate_limit_config(
l: &LocalSiteRateLimit,
) -> EnumMap<ActionType, BucketConfig> {
enum_map! {
ActionType::Message => (l.message, l.message_per_second),
ActionType::Post => (l.post, l.post_per_second),
ActionType::Register => (l.register, l.register_per_second),
ActionType::Image => (l.image, l.image_per_second),
ActionType::Comment => (l.comment, l.comment_per_second),
ActionType::Search => (l.search, l.search_per_second),
ActionType::ImportUserSettings => (l.import_user_settings, l.import_user_settings_per_second),
}
.map(|_key, (capacity, secs_to_refill)| BucketConfig {
capacity: u32::try_from(capacity).unwrap_or(0),
secs_to_refill: u32::try_from(secs_to_refill).unwrap_or(0),
})
}
pub async fn slur_regex(context: &LemmyContext) -> LemmyResult<Regex> {
static CACHE: CacheLock<Regex> = LazyLock::new(|| {
Cache::builder()
.max_capacity(1)
.time_to_live(CACHE_DURATION_FEDERATION)
.build()
});
Ok(
CACHE
.try_get_with((), async {
let local_site = SiteView::read_local(&mut context.pool())
.await
.ok()
.map(|s| s.local_site);
build_and_check_regex(local_site.and_then(|s| s.slur_filter_regex).as_deref())
})
.await
.map_err(|e| anyhow::anyhow!("Failed to construct regex: {e}"))?,
)
}
pub async fn get_url_blocklist(context: &LemmyContext) -> LemmyResult<RegexSet> {
static URL_BLOCKLIST: CacheLock<RegexSet> = LazyLock::new(|| {
Cache::builder()
.max_capacity(1)
.time_to_live(CACHE_DURATION_FEDERATION)
.build()
});
Ok(
URL_BLOCKLIST
.try_get_with::<_, LemmyError>((), async {
let urls = LocalSiteUrlBlocklist::get_all(&mut context.pool()).await?;
// The urls are already validated on saving, so just escape them.
// If this regex creation changes it must be synced with
// lemmy_utils::utils::markdown::create_url_blocklist_test_regex_set.
let regexes = urls.iter().map(|url| format!(r"\b{}\b", escape(&url.url)));
let set = RegexSet::new(regexes)?;
Ok(set)
})
.await
.map_err(|e| anyhow::anyhow!("Failed to build URL blocklist due to `{}`", e))?,
)
}
pub fn check_nsfw_allowed(nsfw: Option<bool>, local_site: Option<&LocalSite>) -> LemmyResult<()> {
let is_nsfw = nsfw.unwrap_or_default();
let nsfw_disallowed = local_site.is_some_and(|s| s.disallow_nsfw_content);
if nsfw_disallowed && is_nsfw {
Err(LemmyErrorType::NsfwNotAllowed)?
}
Ok(())
}
pub fn process_gallery(
gallery_items: Option<&Vec<CreateGalleryItem>>,
url_blocklist: &RegexSet,
) -> LemmyResult<Option<Vec<PostGalleryInsertForm>>> {
if let Some(gallery_items) = gallery_items {
let mut gallery_forms = vec![];
// Sort the items. Anything with a number is put at the start and ordered by
// that number. Ones without are pushed to the end, in the order they were received.
let mut gallery_items = gallery_items.clone();
gallery_items.sort_by(|left, right| {
if let (Some(left), Some(right)) = (left.page, right.page) {
left.cmp(&right)
} else {
right.page.cmp(&left.page)
}
});
for (index, item) in gallery_items.iter().enumerate() {
let url = diesel_url_create(Some(&item.url))?.ok_or(LemmyErrorType::InvalidUrl)?;
is_url_blocked(&url, url_blocklist)?;
is_valid_url(&url)?;
if let Some(alt_text) = &item.alt_text {
is_valid_alt_text_field(alt_text)?;
}
if let Some(caption) = &item.caption {
if is_valid_post_title(caption).is_err() {
Err(LemmyErrorType::InvalidGalleryCaption)?;
}
}
gallery_forms.push(PostGalleryInsertForm {
// We overwrite this later.
post_id: PostId(0),
page: index.try_into()?,
url,
url_content_type: None,
caption: item.caption.clone(),
alt_text: item.alt_text.clone(),
});
}
Ok(Some(gallery_forms))
} else {
Ok(None)
}
}
/// Read the site for an ap_id.
///
/// Used for GetCommunityResponse and GetPersonDetails
pub async fn read_site_for_actor(
ap_id: DbUrl,
context: &LemmyContext,
) -> LemmyResult<Option<Site>> {
let site_id = Site::instance_ap_id_from_url(ap_id.clone().into());
let site = Site::read_from_apub_id(&mut context.pool(), &site_id.into()).await?;
Ok(site)
}
pub async fn purge_post_images(
url: Option<DbUrl>,
thumbnail_url: Option<DbUrl>,
context: &LemmyContext,
) {
if let Some(url) = url {
purge_image_from_pictrs_url(&url, context).await.ok();
}
if let Some(thumbnail_url) = thumbnail_url {
purge_image_from_pictrs_url(&thumbnail_url, context)
.await
.ok();
}
}
/// Delete a local_user's images
async fn delete_local_user_images(person_id: PersonId, context: &LemmyContext) -> LemmyResult<()> {
if let Ok(local_user) = LocalUserView::read_person(&mut context.pool(), person_id).await {
let pictrs_uploads =
LocalImageView::get_all_by_local_user_id(&mut context.pool(), local_user.local_user.id)
.await?;
// Delete their images
for upload in pictrs_uploads {
delete_image_from_pictrs(&upload.local_image.pictrs_alias, context)
.await
.ok();
}
}
Ok(())
}
/// Removes or restores user data.
pub async fn remove_or_restore_user_data(
mod_person_id: PersonId,
banned_person_id: PersonId,
removed: bool,
reason: &Option<String>,
context: &LemmyContext,
) -> LemmyResult<()> {
let pool = &mut context.pool();
// These actions are only possible when removing, not restoring
if removed {
delete_local_user_images(banned_person_id, context).await?;
// Update the fields to None
Person::update(
pool,
banned_person_id,
&PersonUpdateForm {
avatar: Some(None),
banner: Some(None),
bio: Some(None),
..Default::default()
},
)
.await?;
// Communities
// Remove all communities where they're the top mod
// for now, remove the communities manually
let first_mod_communities = CommunityModeratorView::get_community_first_mods(pool).await?;
// Filter to only this banned users top communities
let banned_user_first_communities: Vec<CommunityModeratorView> = first_mod_communities
.into_iter()
.filter(|fmc| fmc.moderator.id == banned_person_id)
.collect();
for first_mod_community in banned_user_first_communities {
let community_id = first_mod_community.community.id;
Community::update(
pool,
community_id,
&CommunityUpdateForm {
removed: Some(removed),
..Default::default()
},
)
.await?;
// Update the fields to None
Community::update(
pool,
community_id,
&CommunityUpdateForm {
icon: Some(None),
banner: Some(None),
..Default::default()
},
)
.await?;
}
}
// Posts
let removed_or_restored_posts =
Post::update_removed_for_creator(pool, banned_person_id, None, None, removed).await?;
create_modlog_entries_for_removed_or_restored_posts(
pool,
mod_person_id,
removed_or_restored_posts.iter().map(|r| r.id).collect(),
removed,
reason,
)
.await?;
// Comments
let removed_or_restored_comments =
Comment::update_removed_for_creator(pool, banned_person_id, removed).await?;
create_modlog_entries_for_removed_or_restored_comments(
pool,
mod_person_id,
removed_or_restored_comments.iter().map(|r| r.id).collect(),
removed,
reason,
)
.await?;
// Private messages
PrivateMessage::update_removed_for_creator(pool, banned_person_id, removed).await?;
Ok(())
}
async fn create_modlog_entries_for_removed_or_restored_posts(
pool: &mut DbPool<'_>,
mod_person_id: PersonId,
post_ids: Vec<PostId>,
removed: bool,
reason: &Option<String>,
) -> LemmyResult<()> {
// Build the forms
let forms = post_ids
.iter()
.map(|&post_id| ModRemovePostForm {
mod_person_id,
post_id,
removed: Some(removed),
reason: reason.clone(),
})
.collect();
ModRemovePost::create_multiple(pool, &forms).await?;
Ok(())
}
async fn create_modlog_entries_for_removed_or_restored_comments(
pool: &mut DbPool<'_>,
mod_person_id: PersonId,
comment_ids: Vec<CommentId>,
removed: bool,
reason: &Option<String>,
) -> LemmyResult<()> {
// Build the forms
let forms = comment_ids
.iter()
.map(|&comment_id| ModRemoveCommentForm {
mod_person_id,
comment_id,
removed: Some(removed),
reason: reason.clone(),
})
.collect();
ModRemoveComment::create_multiple(pool, &forms).await?;
Ok(())
}
pub async fn remove_or_restore_user_data_in_community(
community_id: CommunityId,
mod_person_id: PersonId,
banned_person_id: PersonId,
remove: bool,
reason: &Option<String>,
pool: &mut DbPool<'_>,
) -> LemmyResult<()> {
// Posts
let posts =
Post::update_removed_for_creator(pool, banned_person_id, Some(community_id), None, remove)
.await?;
create_modlog_entries_for_removed_or_restored_posts(
pool,
mod_person_id,
posts.iter().map(|r| r.id).collect(),
remove,
reason,
)
.await?;
// Comments
let removed_comment_ids =
Comment::update_removed_for_creator_and_community(pool, banned_person_id, community_id, remove)
.await?;
create_modlog_entries_for_removed_or_restored_comments(
pool,
mod_person_id,
removed_comment_ids,
remove,
reason,
)
.await?;
Ok(())
}
pub async fn purge_user_account(
person_id: PersonId,
local_instance_id: InstanceId,
context: &LemmyContext,
) -> LemmyResult<()> {
let pool = &mut context.pool();
// Delete their local images, if they're a local user
// No need to update avatar and banner, those are handled in Person::delete_account
delete_local_user_images(person_id, context).await.ok();
// Comments
Comment::permadelete_for_creator(pool, person_id)
.await
.with_lemmy_type(LemmyErrorType::CouldntUpdateComment)?;
// Posts
Post::permadelete_for_creator(pool, person_id)
.await
.with_lemmy_type(LemmyErrorType::CouldntUpdatePost)?;
// Leave communities they mod
CommunityActions::leave_mod_team_for_all_communities(pool, person_id).await?;
// Delete the oauth accounts linked to the local user
if let Ok(local_user) = LocalUserView::read_person(pool, person_id).await {
OAuthAccount::delete_user_accounts(pool, local_user.local_user.id).await?;
}
Person::delete_account(pool, person_id, local_instance_id).await?;
Ok(())
}
pub fn generate_followers_url(ap_id: &DbUrl) -> Result<DbUrl, ParseError> {
Ok(Url::parse(&format!("{ap_id}/followers"))?.into())
}
pub fn generate_inbox_url() -> LemmyResult<DbUrl> {
let url = format!("{}/inbox", SETTINGS.get_protocol_and_hostname());
Ok(Url::parse(&url)?.into())
}
pub fn generate_outbox_url(ap_id: &DbUrl) -> Result<DbUrl, ParseError> {
Ok(Url::parse(&format!("{ap_id}/outbox"))?.into())
}
pub fn generate_featured_url(ap_id: &DbUrl) -> Result<DbUrl, ParseError> {
Ok(Url::parse(&format!("{ap_id}/featured"))?.into())
}
pub fn generate_moderators_url(community_id: &DbUrl) -> LemmyResult<DbUrl> {
Ok(Url::parse(&format!("{community_id}/moderators"))?.into())
}
/// Ensure that ban/block expiry is in valid range. If its in past, throw error. If its more
/// than 10 years in future, convert to permanent ban. Otherwise return the same value.
pub fn check_expire_time(expires_unix_opt: Option<i64>) -> LemmyResult<Option<DateTime<Utc>>> {
if let Some(expires_unix) = expires_unix_opt {
let expires = Utc
.timestamp_opt(expires_unix, 0)
.single()
.ok_or(LemmyErrorType::InvalidUnixTime)?;
limit_expire_time(expires)
} else {
Ok(None)
}
}
fn limit_expire_time(expires: DateTime<Utc>) -> LemmyResult<Option<DateTime<Utc>>> {
const MAX_BAN_TERM: Days = Days::new(10 * 365);
if expires < Local::now() {
Err(LemmyErrorType::BanExpirationInPast)?
} else if expires > Local::now() + MAX_BAN_TERM {
Ok(None)
} else {
Ok(Some(expires))
}
}
pub fn check_conflicting_like_filters(
liked_only: Option<bool>,
disliked_only: Option<bool>,
) -> LemmyResult<()> {
if liked_only.unwrap_or_default() && disliked_only.unwrap_or_default() {
Err(LemmyErrorType::ContradictingFilters)?
} else {
Ok(())
}
}
pub async fn process_markdown(
text: &str,
slur_regex: &Regex,
url_blocklist: &RegexSet,
context: &LemmyContext,
) -> LemmyResult<String> {
let text = remove_slurs(text, slur_regex);
let text = clean_urls_in_text(&text);
markdown_check_for_blocked_urls(&text, url_blocklist)?;
if context.settings().pictrs()?.image_mode == PictrsImageMode::ProxyAllImages {
let (text, links) = markdown_rewrite_image_links(text);
RemoteImage::create(&mut context.pool(), links.clone()).await?;
// Create images and image detail rows
for link in links {
// Insert image details for the remote image
let details_res = fetch_pictrs_proxied_image_details(&link, context).await;
if let Ok(details) = details_res {
let proxied = build_proxied_image_url(&link, false, context)?;
let details_form = details.build_image_details_form(&proxied);
ImageDetails::create(&mut context.pool(), &details_form).await?;
}
}
Ok(text)
} else {
Ok(text)
}
}
pub async fn process_markdown_opt(
text: &Option<String>,
slur_regex: &Regex,
url_blocklist: &RegexSet,
context: &LemmyContext,
) -> LemmyResult<Option<String>> {
match text {
Some(t) => process_markdown(t, slur_regex, url_blocklist, context)
.await
.map(Some),
None => Ok(None),
}
}
/// A wrapper for `proxy_image_link` for use in tests.
///
/// The parameter `force_image_proxy` is the config value of `pictrs.image_proxy`. Its necessary to
/// pass as separate parameter so it can be changed in tests.
async fn proxy_image_link_internal(
link: Url,
image_mode: PictrsImageMode,
is_thumbnail: bool,
context: &LemmyContext,
) -> LemmyResult<DbUrl> {
// Dont rewrite links pointing to local domain.
if link.domain() == Some(&context.settings().hostname) {
Ok(link.into())
} else if image_mode == PictrsImageMode::ProxyAllImages {
RemoteImage::create(&mut context.pool(), vec![link.clone()]).await?;
let proxied = build_proxied_image_url(&link, is_thumbnail, context)?;
// This should fail softly, since pictrs might not even be running
let details_res = fetch_pictrs_proxied_image_details(&link, context).await;
if let Ok(details) = details_res {
let details_form = details.build_image_details_form(&proxied);
ImageDetails::create(&mut context.pool(), &details_form).await?;
};
Ok(proxied.into())
} else {
Ok(link.into())
}
}
/// Rewrite a link to go through `/api/v4/image_proxy` endpoint. This is only for remote urls and
/// if image_proxy setting is enabled.
pub async fn proxy_image_link(
link: Url,
is_thumbnail: bool,
context: &LemmyContext,
) -> LemmyResult<DbUrl> {
proxy_image_link_internal(
link,
context.settings().pictrs()?.image_mode,
is_thumbnail,
context,
)
.await
}
pub async fn proxy_image_link_opt_apub(
link: Option<Url>,
context: &LemmyContext,
) -> LemmyResult<Option<DbUrl>> {
if let Some(l) = link {
proxy_image_link(l, false, context).await.map(Some)
} else {
Ok(None)
}
}