tetratto-core 17.0.1

The core behind Tetratto
Documentation
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
use super::common::NAME_REGEX;
use oiseau::cache::Cache;
use crate::{
    auto_method, DataManager,
    model::{
        Error, Result,
        auth::User,
        communities::{
            CommunityReadAccess, CommunityWriteAccess, ForumTopic, Community, CommunityContext,
            CommunityJoinAccess, CommunityMembership,
        },
        permissions::{FinePermission, SecondaryPermission},
        communities_permissions::CommunityPermission,
    },
};
use pathbufd::PathBufD;
use std::{
    fs::{exists, remove_file},
    collections::HashMap,
};

use oiseau::{PostgresRow, execute, get, query_row, query_rows, params};

impl DataManager {
    /// Get a [`Community`] from an SQL row.
    pub(crate) fn get_community_from_row(x: &PostgresRow) -> Community {
        Community {
            id: get!(x->0(i64)) as usize,
            created: get!(x->1(i64)) as usize,
            title: get!(x->2(String)),
            context: serde_json::from_str(&get!(x->3(String))).unwrap(),
            owner: get!(x->4(i64)) as usize,
            read_access: serde_json::from_str(&get!(x->5(String))).unwrap(),
            write_access: serde_json::from_str(&get!(x->6(String))).unwrap(),
            join_access: serde_json::from_str(&get!(x->7(String))).unwrap(),
            likes: get!(x->8(i32)) as isize,
            dislikes: get!(x->9(i32)) as isize,
            member_count: get!(x->10(i32)) as usize,
            is_forge: get!(x->11(i32)) as i8 == 1,
            post_count: get!(x->12(i32)) as usize,
            is_forum: get!(x->13(i32)) as i8 == 1,
            topics: serde_json::from_str(&get!(x->14(String))).unwrap(),
        }
    }

    pub async fn get_community_by_id(&self, id: usize) -> Result<Community> {
        if id == 0 {
            return Ok(Community::void());
        }

        if let Some(cached) = self.0.1.get(format!("atto.community:{}", id)).await {
            match serde_json::from_str(&cached) {
                Ok(c) => return Ok(c),
                Err(_) => self.0.1.remove(format!("atto.community:{}", id)).await,
            };
        }

        let conn = match self.0.connect().await {
            Ok(c) => c,
            Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
        };

        let res = query_row!(
            &conn,
            "SELECT * FROM communities WHERE id = $1",
            &[&(id as i64)],
            |x| { Ok(Self::get_community_from_row(x)) }
        );

        if res.is_err() {
            return Ok(Community::void());
            // return Err(Error::GeneralNotFound("community".to_string()));
        }

        let x = res.unwrap();
        self.0
            .1
            .set(
                format!("atto.community:{}", id),
                serde_json::to_string(&x).unwrap(),
            )
            .await;

        Ok(x)
    }

    pub async fn get_community_by_title(&self, id: &str) -> Result<Community> {
        if id == "void" {
            return Ok(Community::void());
        }

        if let Some(cached) = self.0.1.get(format!("atto.community:{}", id)).await {
            match serde_json::from_str(&cached) {
                Ok(c) => return Ok(c),
                Err(_) => self.0.1.remove(format!("atto.community:{}", id)).await,
            };
        }

        let conn = match self.0.connect().await {
            Ok(c) => c,
            Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
        };

        let res = query_row!(
            &conn,
            "SELECT * FROM communities WHERE title = $1",
            params![&id],
            |x| { Ok(Self::get_community_from_row(x)) }
        );

        if res.is_err() {
            return Ok(Community::void());
            // return Err(Error::GeneralNotFound("community".to_string()));
        }

        let x = res.unwrap();
        self.0
            .1
            .set(
                format!("atto.community:{}", id),
                serde_json::to_string(&x).unwrap(),
            )
            .await;

        Ok(x)
    }

    auto_method!(get_community_by_id_no_void()@get_community_from_row -> "SELECT * FROM communities WHERE id = $1" --name="community" --returns=Community --cache-key-tmpl="atto.community:{}");
    auto_method!(get_community_by_title_no_void(&str)@get_community_from_row -> "SELECT * FROM communities WHERE title = $1" --name="community" --returns=Community --cache-key-tmpl="atto.community:{}");

    /// Get the top 12 most popular (most likes) communities.
    pub async fn get_popular_communities(&self) -> Result<Vec<Community>> {
        let conn = match self.0.connect().await {
            Ok(c) => c,
            Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
        };

        let res = query_rows!(
            &conn,
            "SELECT * FROM communities WHERE NOT context LIKE '%\"is_nsfw\":true%' ORDER BY member_count DESC LIMIT 12",
            params![],
            |x| { Self::get_community_from_row(x) }
        );

        if res.is_err() {
            return Err(Error::GeneralNotFound("communities".to_string()));
        }

        Ok(res.unwrap())
    }

    /// Get all communities, filtering their title.
    /// Communities are sorted by popularity first, creation date second.
    pub async fn get_communities_searched(
        &self,
        query: &str,
        batch: usize,
        page: usize,
    ) -> Result<Vec<Community>> {
        let conn = match self.0.connect().await {
            Ok(c) => c,
            Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
        };

        let res = query_rows!(
            &conn,
            "SELECT * FROM communities WHERE title LIKE $1 ORDER BY member_count DESC, created DESC LIMIT $2 OFFSET $3",
            params![
                &format!("%{query}%"),
                &(batch as i64),
                &((page * batch) as i64)
            ],
            |x| { Self::get_community_from_row(x) }
        );

        if res.is_err() {
            return Err(Error::GeneralNotFound("communities".to_string()));
        }

        Ok(res.unwrap())
    }

    /// Get all communities by their owner.
    pub async fn get_communities_by_owner(&self, id: usize) -> Result<Vec<Community>> {
        let conn = match self.0.connect().await {
            Ok(c) => c,
            Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
        };

        let res = query_rows!(
            &conn,
            "SELECT * FROM communities WHERE owner = $1",
            params![&(id as i64)],
            |x| { Self::get_community_from_row(x) }
        );

        if res.is_err() {
            return Err(Error::GeneralNotFound("communities".to_string()));
        }

        Ok(res.unwrap())
    }

    /// Create a new community in the database.
    ///
    /// # Arguments
    /// * `data` - a mock [`Community`] to insert
    pub async fn create_community(&self, data: Community) -> Result<String> {
        // check values
        if data.title.trim().len() < 2 {
            return Err(Error::DataTooShort("title".to_string()));
        } else if data.title.len() > 32 {
            return Err(Error::DataTooLong("title".to_string()));
        }

        if self.0.0.banned_usernames.contains(&data.title) {
            return Err(Error::MiscError("This title cannot be used".to_string()));
        }

        let regex = regex::RegexBuilder::new(NAME_REGEX)
            .multi_line(true)
            .build()
            .unwrap();

        if regex.captures(&data.title).is_some() {
            return Err(Error::MiscError(
                "This title contains invalid characters".to_string(),
            ));
        }

        // check number of communities
        let owner = self.get_user_by_id(data.owner).await?;

        if !owner
            .permissions
            .check(FinePermission::INFINITE_COMMUNITIES)
        {
            let memberships = self.get_memberships_by_owner(data.owner).await?;
            let mut admin_count = 0; // you can not make anymore communities if you are already admin of at least 5

            for membership in memberships {
                if membership.role.check(CommunityPermission::ADMINISTRATOR) {
                    admin_count += 1;
                }
            }

            let maximum_count = if owner.permissions.check(FinePermission::SUPPORTER) {
                10
            } else {
                5
            };

            if admin_count >= maximum_count {
                return Err(Error::MiscError(
                    "You are already owner/co-owner of too many communities to create another"
                        .to_string(),
                ));
            }
        }

        // check is_forge
        // only supporters can CREATE forge communities... anybody can contribute to them
        if data.is_forge
            && !owner
                .secondary_permissions
                .check(SecondaryPermission::DEVELOPER_PASS)
        {
            return Err(Error::RequiresSupporter);
        }

        // make sure community doesn't already exist with title
        if self
            .get_community_by_title_no_void(&data.title.to_lowercase())
            .await
            .is_ok()
        {
            return Err(Error::MiscError("Title already in use".to_string()));
        }

        // ...
        let conn = match self.0.connect().await {
            Ok(c) => c,
            Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
        };

        let res = execute!(
            &conn,
            "INSERT INTO communities VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)",
            params![
                &(data.id as i64),
                &(data.created as i64),
                &data.title.to_lowercase(),
                &serde_json::to_string(&data.context).unwrap().as_str(),
                &(data.owner as i64),
                &serde_json::to_string(&data.read_access).unwrap().as_str(),
                &serde_json::to_string(&data.write_access).unwrap().as_str(),
                &serde_json::to_string(&data.join_access).unwrap().as_str(),
                &0_i32,
                &0_i32,
                &1_i32,
                &{ if data.is_forge { 1 } else { 0 } },
                &0_i32,
                &{ if data.is_forum { 1 } else { 0 } },
                &serde_json::to_string(&data.topics).unwrap().as_str(),
            ]
        );

        if let Err(e) = res {
            return Err(Error::DatabaseError(e.to_string()));
        }

        // add community owner as admin
        self.create_membership(
            CommunityMembership::new(data.owner, data.id, CommunityPermission::ADMINISTRATOR),
            &owner,
        )
        .await
        .unwrap();

        // return
        Ok(data.title)
    }

    pub async fn cache_clear_community(&self, community: &Community) {
        self.0
            .1
            .remove(format!("atto.community:{}", community.id))
            .await;
        self.0
            .1
            .remove(format!("atto.community:{}", community.title))
            .await;
    }

    pub async fn delete_community(&self, id: usize, user: &User) -> Result<()> {
        let y = self.get_community_by_id(id).await?;

        if user.id != y.owner {
            if !user.permissions.check(FinePermission::MANAGE_COMMUNITIES) {
                return Err(Error::NotAllowed);
            } else {
                self.create_audit_log_entry(crate::model::moderation::AuditLogEntry::new(
                    user.id,
                    format!("invoked `delete_community` with x value `{id}`"),
                ))
                .await?
            }
        }

        let conn = match self.0.connect().await {
            Ok(c) => c,
            Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
        };

        let res = execute!(
            &conn,
            "DELETE FROM communities WHERE id = $1",
            &[&(id as i64)]
        );

        if let Err(e) = res {
            return Err(Error::DatabaseError(e.to_string()));
        }

        self.cache_clear_community(&y).await;

        // remove memberships
        let res = execute!(
            &conn,
            "DELETE FROM memberships WHERE community = $1",
            &[&(id as i64)]
        );

        if let Err(e) = res {
            return Err(Error::DatabaseError(e.to_string()));
        }

        // remove images
        let avatar = PathBufD::current().extend(&[
            self.0.0.dirs.media.as_str(),
            "community_avatars",
            &format!("{}.avif", &y.id),
        ]);

        let banner = PathBufD::current().extend(&[
            self.0.0.dirs.media.as_str(),
            "community_banners",
            &format!("{}.avif", &y.id),
        ]);

        if exists(&avatar).unwrap() {
            remove_file(avatar).unwrap();
        }

        if exists(&banner).unwrap() {
            remove_file(banner).unwrap();
        }

        // ...
        Ok(())
    }

    pub async fn update_community_title(&self, id: usize, user: User, title: &str) -> Result<()> {
        // check values
        if title.len() < 2 {
            return Err(Error::DataTooShort("title".to_string()));
        } else if title.len() > 32 {
            return Err(Error::DataTooLong("title".to_string()));
        }

        if self.0.0.banned_usernames.contains(&title.to_string()) {
            return Err(Error::MiscError("This title cannot be used".to_string()));
        }

        let regex = regex::RegexBuilder::new(NAME_REGEX)
            .multi_line(true)
            .build()
            .unwrap();

        if regex.captures(title).is_some() {
            return Err(Error::MiscError(
                "This title contains invalid characters".to_string(),
            ));
        }

        // ...
        let y = self.get_community_by_id(id).await?;

        if user.id != y.owner {
            if !user.permissions.check(FinePermission::MANAGE_COMMUNITIES) {
                return Err(Error::NotAllowed);
            } else {
                self.create_audit_log_entry(crate::model::moderation::AuditLogEntry::new(
                    user.id,
                    format!("invoked `update_community_title` with x value `{id}`"),
                ))
                .await?
            }
        }

        // check for existing community
        let title = &title.to_lowercase();
        if self.get_community_by_title_no_void(title).await.is_ok() {
            return Err(Error::TitleInUse);
        }

        // ...
        let conn = match self.0.connect().await {
            Ok(c) => c,
            Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
        };

        let res = execute!(
            &conn,
            "UPDATE communities SET title = $1 WHERE id = $2",
            params![&title, &(id as i64)]
        );

        if let Err(e) = res {
            return Err(Error::DatabaseError(e.to_string()));
        }

        self.cache_clear_community(&y).await;

        Ok(())
    }

    pub async fn update_community_owner(
        &self,
        id: usize,
        user: User,
        new_owner: usize,
    ) -> Result<()> {
        let y = self.get_community_by_id(id).await?;

        if user.id != y.owner {
            if !user.permissions.check(FinePermission::MANAGE_COMMUNITIES) {
                return Err(Error::NotAllowed);
            } else {
                self.create_audit_log_entry(crate::model::moderation::AuditLogEntry::new(
                    user.id,
                    format!("invoked `update_community_owner` with x value `{id}`"),
                ))
                .await?
            }
        }

        let new_owner_membership = self
            .get_membership_by_owner_community(new_owner, y.id)
            .await?;
        let current_owner_membership = self
            .get_membership_by_owner_community(y.owner, y.id)
            .await?;

        // ...
        let conn = match self.0.connect().await {
            Ok(c) => c,
            Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
        };

        let res = execute!(
            &conn,
            "UPDATE communities SET owner = $1 WHERE id = $2",
            params![&(new_owner as i64), &(id as i64)]
        );

        if let Err(e) = res {
            return Err(Error::DatabaseError(e.to_string()));
        }

        self.cache_clear_community(&y).await;

        // update memberships
        self.update_membership_role(
            new_owner_membership.id,
            CommunityPermission::DEFAULT | CommunityPermission::ADMINISTRATOR,
        )
        .await?;

        self.update_membership_role(
            current_owner_membership.id,
            CommunityPermission::DEFAULT | CommunityPermission::MEMBER,
        )
        .await?;

        // return
        Ok(())
    }

    pub async fn delete_topic_posts(&self, id: usize, topic: usize) -> Result<()> {
        let conn = match self.0.connect().await {
            Ok(c) => c,
            Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
        };

        let res = execute!(
            &conn,
            "DELETE FROM posts WHERE community = $1 AND topic = $2",
            params![&(id as i64), &(topic as i64)]
        );

        if let Err(e) = res {
            return Err(Error::DatabaseError(e.to_string()));
        }

        Ok(())
    }

    auto_method!(update_community_context(CommunityContext)@get_community_by_id_no_void:FinePermission::MANAGE_COMMUNITIES; -> "UPDATE communities SET context = $1 WHERE id = $2" --serde --cache-key-tmpl=cache_clear_community);
    auto_method!(update_community_read_access(CommunityReadAccess)@get_community_by_id_no_void:FinePermission::MANAGE_COMMUNITIES; -> "UPDATE communities SET read_access = $1 WHERE id = $2" --serde --cache-key-tmpl=cache_clear_community);
    auto_method!(update_community_write_access(CommunityWriteAccess)@get_community_by_id_no_void:FinePermission::MANAGE_COMMUNITIES; -> "UPDATE communities SET write_access = $1 WHERE id = $2" --serde --cache-key-tmpl=cache_clear_community);
    auto_method!(update_community_join_access(CommunityJoinAccess)@get_community_by_id_no_void:FinePermission::MANAGE_COMMUNITIES; -> "UPDATE communities SET join_access = $1 WHERE id = $2" --serde --cache-key-tmpl=cache_clear_community);
    auto_method!(update_community_topics(HashMap<usize, ForumTopic>)@get_community_by_id_no_void:FinePermission::MANAGE_COMMUNITIES; -> "UPDATE communities SET topics = $1 WHERE id = $2" --serde --cache-key-tmpl=cache_clear_community);
    auto_method!(update_community_is_forum(i32)@get_community_by_id_no_void:FinePermission::MANAGE_COMMUNITIES; -> "UPDATE communities SET is_forum = $1 WHERE id = $2" --cache-key-tmpl=cache_clear_community);

    auto_method!(incr_community_likes()@get_community_by_id_no_void -> "UPDATE communities SET likes = likes + 1 WHERE id = $1" --cache-key-tmpl=cache_clear_community --incr);
    auto_method!(incr_community_dislikes()@get_community_by_id_no_void -> "UPDATE communities SET dislikes = dislikes + 1 WHERE id = $1" --cache-key-tmpl=cache_clear_community --incr);
    auto_method!(decr_community_likes()@get_community_by_id_no_void -> "UPDATE communities SET likes = likes - 1 WHERE id = $1" --cache-key-tmpl=cache_clear_community --decr=likes);
    auto_method!(decr_community_dislikes()@get_community_by_id_no_void -> "UPDATE communities SET dislikes = dislikes - 1 WHERE id = $1" --cache-key-tmpl=cache_clear_community --decr=dislikes);

    auto_method!(incr_community_member_count()@get_community_by_id_no_void -> "UPDATE communities SET member_count = member_count + 1 WHERE id = $1" --cache-key-tmpl=cache_clear_community --incr);
    auto_method!(decr_community_member_count()@get_community_by_id_no_void -> "UPDATE communities SET member_count = member_count - 1 WHERE id = $1" --cache-key-tmpl=cache_clear_community --decr=member_count);

    auto_method!(incr_community_post_count()@get_community_by_id_no_void -> "UPDATE communities SET post_count = post_count + 1 WHERE id = $1" --cache-key-tmpl=cache_clear_community --incr);
    auto_method!(decr_community_post_count()@get_community_by_id_no_void -> "UPDATE communities SET post_count = post_count - 1 WHERE id = $1" --cache-key-tmpl=cache_clear_community --decr=post_count);
}