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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
use std::collections::HashMap;

use serde::{Deserialize, Serialize};
use tetratto_shared::{snow::Snowflake, unix_epoch_timestamp};
use super::communities_permissions::CommunityPermission;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Community {
    pub id: usize,
    pub created: usize,
    pub title: String,
    pub context: CommunityContext,
    /// The ID of the owner of the community.
    pub owner: usize,
    /// Who can read the community.
    pub read_access: CommunityReadAccess,
    /// Who can write to the community (create posts belonging to it).
    ///
    /// The owner of the community (and moderators) are the ***only*** people
    /// capable of removing posts.
    pub write_access: CommunityWriteAccess,
    /// Who can join the community.
    pub join_access: CommunityJoinAccess,
    pub likes: isize,
    pub dislikes: isize,
    pub member_count: usize,
    pub is_forge: bool,
    pub post_count: usize,
    pub is_forum: bool,
    /// The topics of a community if the community has `is_forum` enabled.
    ///
    /// Since topics are given a unique ID (the key of the hashmap), a removal of a topic
    /// should be done through a specific DELETE endpoint which ALSO deletes all posts
    /// within the topic.
    ///
    /// Communities should be limited to 10 topics per community.
    pub topics: HashMap<usize, ForumTopic>,
}

impl Community {
    /// Create a new [`Community`].
    pub fn new(title: String, owner: usize) -> Self {
        Self {
            id: Snowflake::new().to_string().parse::<usize>().unwrap(),
            created: unix_epoch_timestamp(),
            title: title.clone(),
            context: CommunityContext {
                display_name: title,
                ..Default::default()
            },
            owner,
            read_access: CommunityReadAccess::default(),
            write_access: CommunityWriteAccess::default(),
            join_access: CommunityJoinAccess::default(),
            likes: 0,
            dislikes: 0,
            member_count: 0,
            is_forge: false,
            post_count: 0,
            is_forum: false,
            topics: HashMap::new(),
        }
    }

    /// Create the "void" community. This is where all posts with a deleted community
    /// resolve to.
    pub fn void() -> Self {
        Self {
            id: 0,
            created: 0,
            title: "void".to_string(),
            context: CommunityContext::default(),
            owner: 0,
            read_access: CommunityReadAccess::Joined,
            write_access: CommunityWriteAccess::Owner,
            join_access: CommunityJoinAccess::Nobody,
            likes: 0,
            dislikes: 0,
            member_count: 0,
            is_forge: false,
            post_count: 0,
            is_forum: false,
            topics: HashMap::new(),
        }
    }
}

#[derive(Clone, Debug, Serialize, Deserialize, Default)]
pub struct CommunityContext {
    #[serde(default)]
    pub display_name: String,
    #[serde(default)]
    pub description: String,
    #[serde(default)]
    pub is_nsfw: bool,
    #[serde(default)]
    pub enable_questions: bool,
    /// If posts are allowed to set a `title` field.
    #[serde(default)]
    pub enable_titles: bool,
    /// If posts are required to set a `title` field.
    ///
    /// `enable_titles` is required for this setting to work.
    #[serde(default)]
    pub require_titles: bool,
}

/// Who can read a [`Community`].
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[derive(Default)]
pub enum CommunityReadAccess {
    /// Everybody can view the community.
    #[default]
    Everybody,
    /// Only people in the community can view the community.
    Joined,
}


/// Who can write to a [`Community`].
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[derive(Default)]
pub enum CommunityWriteAccess {
    /// Everybody.
    Everybody,
    /// Only people who joined the community can write to it.
    ///
    /// Memberships can be managed by the owner of the community.
    #[default]
    Joined,
    /// Only the owner of the community.
    Owner,
}


/// Who can join a [`Community`].
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[derive(Default)]
pub enum CommunityJoinAccess {
    /// Joins are closed. Nobody can join the community.
    Nobody,
    /// All authenticated users can join the community.
    #[default]
    Everybody,
    /// People must send a request to join.
    Request,
}


#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CommunityMembership {
    pub id: usize,
    pub created: usize,
    pub owner: usize,
    pub community: usize,
    pub role: CommunityPermission,
}

impl CommunityMembership {
    /// Create a new [`CommunityMembership`].
    pub fn new(owner: usize, community: usize, role: CommunityPermission) -> Self {
        Self {
            id: Snowflake::new().to_string().parse::<usize>().unwrap(),
            created: unix_epoch_timestamp(),
            owner,
            community,
            role,
        }
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PostContext {
    #[serde(default = "default_comments_enabled")]
    pub comments_enabled: bool,
    #[serde(default)]
    pub is_pinned: bool,
    #[serde(default)]
    pub is_profile_pinned: bool,
    #[serde(default)]
    pub edited: usize,
    #[serde(default)]
    pub is_nsfw: bool,
    #[serde(default)]
    pub repost: Option<RepostContext>,
    #[serde(default = "default_reposts_enabled")]
    pub reposts_enabled: bool,
    /// The ID of the question this post is answering.
    #[serde(default)]
    pub answering: usize,
    #[serde(default = "default_reactions_enabled")]
    pub reactions_enabled: bool,
    #[serde(default)]
    pub content_warning: String,
    #[serde(default)]
    pub tags: Vec<String>,
    #[serde(default)]
    pub full_unlist: bool,
}

fn default_comments_enabled() -> bool {
    true
}

fn default_reposts_enabled() -> bool {
    true
}

fn default_reactions_enabled() -> bool {
    true
}

impl Default for PostContext {
    fn default() -> Self {
        Self {
            comments_enabled: default_comments_enabled(),
            reposts_enabled: default_reposts_enabled(),
            is_pinned: false,
            is_profile_pinned: false,
            edited: 0,
            is_nsfw: false,
            repost: None,
            answering: 0,
            reactions_enabled: default_reactions_enabled(),
            content_warning: String::new(),
            tags: Vec::new(),
            full_unlist: false,
        }
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RepostContext {
    /// Should be `false` is `reposting` is `Some`.
    ///
    /// Declares the post to be a repost of another post.
    pub is_repost: bool,
    /// Should be `None` if `is_repost` is true.
    ///
    /// Sets the ID of the other post to load.
    pub reposting: Option<usize>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Post {
    pub id: usize,
    pub created: usize,
    pub content: String,
    /// The ID of the owner of this post.
    pub owner: usize,
    /// The ID of the [`Community`] this post belongs to.
    pub community: usize,
    /// Extra information about the post.
    pub context: PostContext,
    /// The ID of the post this post is a comment on.
    pub replying_to: Option<usize>,
    pub likes: isize,
    pub dislikes: isize,
    pub comment_count: usize,
    /// IDs of all uploads linked to this post.
    pub uploads: Vec<usize>,
    /// If the post was deleted.
    pub is_deleted: bool,
    /// The ID of the poll associated with this post. 0 means no poll is connected.
    pub poll_id: usize,
    /// The title of the post (in communities where titles are enabled).
    pub title: String,
    /// If the post is "open". Posts can act as tickets in a forge community.
    pub is_open: bool,
    /// The ID of the stack this post belongs to. 0 means no stack is connected.
    ///
    /// If stack is not 0, community should be 0 (and vice versa).
    pub stack: usize,
    /// The ID of the topic this post belongs to. 0 means no topic is connected.
    ///
    /// This can only be set if the post is created in a community with `is_forum: true`,
    /// where this is also a required field.
    pub topic: usize,
    pub views: usize,
}

impl Post {
    /// Create a new [`Post`].
    pub fn new(
        content: String,
        community: usize,
        replying_to: Option<usize>,
        owner: usize,
        poll_id: usize,
    ) -> Self {
        Self {
            id: Snowflake::new().to_string().parse::<usize>().unwrap(),
            created: unix_epoch_timestamp(),
            content,
            owner,
            community,
            context: PostContext::default(),
            replying_to,
            likes: 0,
            dislikes: 0,
            comment_count: 0,
            uploads: Vec::new(),
            is_deleted: false,
            poll_id,
            title: String::new(),
            is_open: true,
            stack: 0,
            topic: 0,
            views: 0,
        }
    }

    /// Create a new [`Post`] (as a repost of the given `post_id`).
    pub fn repost(content: String, community: usize, owner: usize, post_id: usize) -> Self {
        let mut post = Self::new(content, community, None, owner, 0);

        post.context.repost = Some(RepostContext {
            is_repost: false,
            reposting: Some(post_id),
        });

        post
    }

    /// Make the given post a reposted post.
    pub fn mark_as_repost(&mut self) {
        self.context.repost = Some(RepostContext {
            is_repost: true,
            reposting: None,
        });
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PostView {
    pub id: usize,
    pub created: usize,
    pub owner: usize,
    pub post: usize,
}

impl PostView {
    /// Create a new [`PostView`]
    pub fn new(owner: usize, post: usize) -> Self {
        Self {
            id: Snowflake::new().to_string().parse::<usize>().unwrap(),
            created: unix_epoch_timestamp(),
            owner,
            post,
        }
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Question {
    pub id: usize,
    pub created: usize,
    pub owner: usize,
    pub receiver: usize,
    pub content: String,
    /// The `is_global` flag allows any (authenticated) user to respond
    /// to the question. Normally, only the `receiver` can do so.
    ///
    /// If `is_global` is true, `receiver` should be 0 (and vice versa).
    pub is_global: bool,
    /// The number of answers the question has. Should never really be changed
    /// unless the question has `is_global` set to true.
    pub answer_count: usize,
    /// The ID of the community this question is asked to. This should only be > 0
    /// if `is_global` is set to true.
    pub community: usize,
    // likes
    #[serde(default)]
    pub likes: isize,
    #[serde(default)]
    pub dislikes: isize,
    // ...
    #[serde(default)]
    pub context: QuestionContext,
    /// The IP of the question creator for IP blocking and identifying anonymous users.
    #[serde(default)]
    pub ip: String,
    /// The IDs of all uploads which hold this question's drawings.
    #[serde(default)]
    pub drawings: Vec<usize>,
}

impl Question {
    /// Create a new [`Question`].
    pub fn new(
        owner: usize,
        receiver: usize,
        content: String,
        is_global: bool,
        ip: String,
    ) -> Self {
        Self {
            id: Snowflake::new().to_string().parse::<usize>().unwrap(),
            created: unix_epoch_timestamp(),
            owner,
            receiver,
            content,
            is_global,
            answer_count: 0,
            community: 0,
            likes: 0,
            dislikes: 0,
            context: QuestionContext::default(),
            ip,
            drawings: Vec::new(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct QuestionContext {
    #[serde(default)]
    pub is_nsfw: bool,
    /// If the owner is shown as anonymous in the UI.
    #[serde(default)]
    pub mask_owner: bool,
    /// The POST this question is asking about.
    #[serde(default)]
    pub asking_about: Option<usize>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PostDraft {
    pub id: usize,
    pub created: usize,
    pub content: String,
    pub owner: usize,
}

impl PostDraft {
    /// Create a new [`PostDraft`].
    pub fn new(content: String, owner: usize) -> Self {
        Self {
            id: Snowflake::new().to_string().parse::<usize>().unwrap(),
            created: unix_epoch_timestamp(),
            content,
            owner,
        }
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Poll {
    pub id: usize,
    pub owner: usize,
    pub created: usize,
    /// The number of milliseconds until this poll can no longer receive votes.
    pub expires: usize,
    // options
    pub option_a: String,
    pub option_b: String,
    pub option_c: String,
    pub option_d: String,
    // votes
    pub votes_a: usize,
    pub votes_b: usize,
    pub votes_c: usize,
    pub votes_d: usize,
}

impl Poll {
    /// Create a new [`Poll`].
    pub fn new(
        owner: usize,
        expires: usize,
        option_a: String,
        option_b: String,
        option_c: String,
        option_d: String,
    ) -> Self {
        Self {
            id: Snowflake::new().to_string().parse::<usize>().unwrap(),
            owner,
            created: unix_epoch_timestamp(),
            expires,
            // options
            option_a,
            option_b,
            option_c,
            option_d,
            // votes
            votes_a: 0,
            votes_b: 0,
            votes_c: 0,
            votes_d: 0,
        }
    }
}

/// Poll option (selectors) are stored in the database as numbers 0 to 3.
///
/// This enum allows us to convert from these numbers into letters.
#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub enum PollOption {
    A,
    B,
    C,
    D,
}

impl From<u8> for PollOption {
    fn from(value: u8) -> Self {
        match value {
            0 => Self::A,
            1 => Self::B,
            2 => Self::C,
            3 => Self::D,
            _ => Self::A,
        }
    }
}

impl From<PollOption> for u8 {
    fn from(val: PollOption) -> Self {
        match val {
            PollOption::A => 0,
            PollOption::B => 1,
            PollOption::C => 2,
            PollOption::D => 3,
        }
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PollVote {
    pub id: usize,
    pub owner: usize,
    pub created: usize,
    pub poll_id: usize,
    pub vote: PollOption,
}

impl PollVote {
    /// Create a new [`PollVote`].
    pub fn new(owner: usize, poll_id: usize, vote: PollOption) -> Self {
        Self {
            id: Snowflake::new().to_string().parse::<usize>().unwrap(),
            owner,
            created: unix_epoch_timestamp(),
            poll_id,
            vote,
        }
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ForumTopic {
    pub title: String,
    pub description: String,
    pub color: String,
    pub position: i32,
    #[serde(default)]
    pub write_access: CommunityWriteAccess,
}

impl ForumTopic {
    /// Create a new [`ForumTopic`].
    ///
    /// # Returns
    /// * ID for [`Community`] hashmap
    /// * [`ForumTopic`]
    pub fn new(
        title: String,
        description: String,
        color: String,
        position: i32,
        write_access: CommunityWriteAccess,
    ) -> (usize, Self) {
        (
            Snowflake::new().to_string().parse::<usize>().unwrap(),
            Self {
                title,
                description,
                color,
                position,
                write_access,
            },
        )
    }
}