tetratto-core 18.0.2

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
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
use std::collections::HashMap;
use oiseau::cache::Cache;
use tetratto_shared::unix_epoch_timestamp;
use crate::model::addr::RemoteAddr;
use crate::model::communities::Post;
use crate::model::communities_permissions::CommunityPermission;
use buckets_core::model::{MediaType, MediaUpload};
use crate::model::{
    Error, Result,
    communities::Question,
    requests::{ActionRequest, ActionType},
    auth::User,
    permissions::FinePermission,
};
use crate::{auto_method, DataManager};
use oiseau::{execute, get, query_rows, params, PostgresRow};

impl DataManager {
    /// Get a [`Question`] from an SQL row.
    pub(crate) fn get_question_from_row(x: &PostgresRow) -> Question {
        Question {
            id: get!(x->0(i64)) as usize,
            created: get!(x->1(i64)) as usize,
            owner: get!(x->2(i64)) as usize,
            receiver: get!(x->3(i64)) as usize,
            content: get!(x->4(String)),
            is_global: get!(x->5(i32)) as i8 == 1,
            answer_count: get!(x->6(i32)) as usize,
            community: get!(x->7(i64)) as usize,
            // likes
            likes: get!(x->8(i32)) as isize,
            dislikes: get!(x->9(i32)) as isize,
            // ...
            context: serde_json::from_str(&get!(x->10(String))).unwrap(),
            ip: get!(x->11(String)),
            drawings: serde_json::from_str(&get!(x->12(String))).unwrap(),
        }
    }

    auto_method!(get_question_by_id()@get_question_from_row -> "SELECT * FROM questions WHERE id = $1" --name="question" --returns=Question --cache-key-tmpl="atto.question:{}");

    /// Get the post a given question is asking about.
    pub async fn get_question_asking_about(
        &self,
        question: &Question,
    ) -> Result<Option<(User, Post)>> {
        Ok(if let Some(id) = question.context.asking_about {
            let post = match self.get_post_by_id(id).await {
                Ok(x) => x,
                Err(_) => return Ok(None),
            };

            Some((self.get_user_by_id(post.owner).await?, post))
        } else {
            None
        })
    }

    /// Fill the given vector of questions with their owner as well.
    pub async fn fill_questions(
        &self,
        questions: Vec<Question>,
        ignore_users: &[usize],
    ) -> Result<Vec<(Question, User, Option<(User, Post)>)>> {
        let mut out: Vec<(Question, User, Option<(User, Post)>)> = Vec::new();

        let mut seen_users: HashMap<usize, User> = HashMap::new();
        for question in questions {
            if ignore_users.contains(&question.owner) {
                continue;
            }

            if let Some(ua) = seen_users.get(&question.owner) {
                let asking_about = self.get_question_asking_about(&question).await?;
                out.push((question, ua.to_owned(), asking_about));
            } else {
                let user = if question.owner == 0 {
                    User::anonymous()
                } else {
                    self.get_user_by_id_with_void(question.owner).await?
                };

                seen_users.insert(question.owner, user.clone());

                let asking_about = self.get_question_asking_about(&question).await?;
                out.push((question, user, asking_about));
            }
        }

        Ok(out)
    }

    /// Filter to update questions to clean their owner for public APIs.
    pub fn questions_owner_filter(
        &self,
        questions: &[(Question, User, Option<(User, Post)>)],
    ) -> Vec<(Question, User, Option<(User, Post)>)> {
        let mut out: Vec<(Question, User, Option<(User, Post)>)> = Vec::new();

        for mut question in questions.to_owned() {
            question.1.clean();

            if question.2.is_some() {
                question.2.as_mut().unwrap().0.clean();
            }

            out.push(question);
        }

        out
    }

    /// Get all questions by `owner`.
    pub async fn get_questions_by_owner(&self, owner: usize) -> Result<Vec<Question>> {
        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 questions WHERE owner = $1 AND NOT context LIKE '%\"is_nsfw\":true%' ORDER BY created DESC",
            &[&(owner as i64)],
            |x| { Self::get_question_from_row(x) }
        );

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

        Ok(res.unwrap())
    }

    /// Get all questions by `owner` (paginated).
    pub async fn get_questions_by_owner_paginated(
        &self,
        owner: usize,
        batch: usize,
        page: usize,
    ) -> Result<Vec<Question>> {
        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 questions WHERE owner = $1 AND NOT context LIKE '%\"is_nsfw\":true%' ORDER BY created DESC LIMIT $2 OFFSET $3",
            &[&(owner as i64), &(batch as i64), &((page * batch) as i64)],
            |x| { Self::get_question_from_row(x) }
        );

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

        Ok(res.unwrap())
    }

    /// Get all questions by `receiver`.
    pub async fn get_questions_by_receiver(&self, receiver: usize) -> Result<Vec<Question>> {
        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 questions WHERE receiver = $1 ORDER BY created DESC",
            &[&(receiver as i64)],
            |x| { Self::get_question_from_row(x) }
        );

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

        Ok(res.unwrap())
    }

    /// Get all global questions by `community`.
    pub async fn get_questions_by_community(
        &self,
        community: usize,
        batch: usize,
        page: usize,
    ) -> Result<Vec<Question>> {
        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 questions WHERE community = $1 AND is_global = 1 ORDER BY created DESC LIMIT $2 OFFSET $3",
            &[
                &(community as i64),
                &(batch as i64),
                &((page * batch) as i64)
            ],
            |x| { Self::get_question_from_row(x) }
        );

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

        Ok(res.unwrap())
    }

    /// Get all global questions by the given user's following.
    pub async fn get_questions_from_user_following(
        &self,
        id: usize,
        batch: usize,
        page: usize,
    ) -> Result<Vec<Question>> {
        let following = self.get_userfollows_by_initiator_all(id).await?;
        let mut following = following.iter();
        let first = match following.next() {
            Some(f) => f,
            None => return Ok(Vec::new()),
        };

        let mut query_string: String = String::new();

        for user in following {
            query_string.push_str(&format!(" OR owner = {}", user.receiver));
        }

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

        let res = query_rows!(
            &conn,
            &format!(
                "SELECT * FROM questions WHERE (owner = {} {query_string}) AND is_global = 1 ORDER BY created DESC LIMIT $1 OFFSET $2",
                first.receiver
            ),
            &[&(batch as i64), &((page * batch) as i64)],
            |x| { Self::get_question_from_row(x) }
        );

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

        Ok(res.unwrap())
    }

    /// Get all global questions posted in the given user's communities.
    pub async fn get_questions_from_user_communities(
        &self,
        id: usize,
        batch: usize,
        page: usize,
    ) -> Result<Vec<Question>> {
        let memberships = self.get_memberships_by_owner(id).await?;
        let mut memberships = memberships.iter();
        let first = match memberships.next() {
            Some(f) => f,
            None => return Ok(Vec::new()),
        };

        let mut query_string: String = String::new();

        for membership in memberships {
            query_string.push_str(&format!(" OR community = {}", membership.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,
            &format!(
                "SELECT * FROM questions WHERE (community = {} {query_string}) AND is_global = 1 AND NOT context LIKE '%\"is_nsfw\":true%' ORDER BY created DESC LIMIT $1 OFFSET $2",
                first.community
            ),
            &[&(batch as i64), &((page * batch) as i64)],
            |x| { Self::get_question_from_row(x) }
        );

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

        Ok(res.unwrap())
    }

    /// Get global questions from all communities, sorted by creation.
    ///
    /// # Arguments
    /// * `batch` - the limit of questions in each page
    /// * `page` - the page number
    pub async fn get_latest_global_questions(
        &self,
        batch: usize,
        page: usize,
    ) -> Result<Vec<Question>> {
        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 questions WHERE is_global = 1 ORDER BY created DESC LIMIT $1 OFFSET $2",
            &[&(batch as i64), &((page * batch) as i64)],
            |x| { Self::get_question_from_row(x) }
        );

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

        Ok(res.unwrap())
    }

    /// Get global questions from all communities, sorted by likes.
    ///
    /// # Arguments
    /// * `batch` - the limit of questions in each page
    /// * `page` - the page number
    /// * `cutoff` - the maximum number of milliseconds ago the question could have been created
    pub async fn get_popular_global_questions(
        &self,
        batch: usize,
        page: usize,
        cutoff: usize,
    ) -> Result<Vec<Question>> {
        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 questions WHERE is_global = 1 AND NOT context LIKE '%\"is_nsfw\":true%' AND ($1 - created) < $2 ORDER BY likes - dislikes DESC, created ASC LIMIT $3 OFFSET $4",
            &[
                &(unix_epoch_timestamp() as i64),
                &(cutoff as i64),
                &(batch as i64),
                &((page * batch) as i64)
            ],
            |x| { Self::get_question_from_row(x) }
        );

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

        Ok(res.unwrap())
    }

    const MAXIMUM_DRAWING_SIZE: usize = 32768; // 32 KiB

    /// Create a new question in the database.
    ///
    /// # Arguments
    /// * `data` - a mock [`Question`] object to insert
    pub async fn create_question(
        &self,
        mut data: Question,
        drawings: Vec<Vec<u8>>,
    ) -> Result<usize> {
        // check if we can post this
        if data.is_global {
            // global
            if data.community > 0 {
                // posting to community
                data.receiver = 0;
                let community = self.get_community_by_id(data.community).await?;

                if !community.context.enable_questions
                    | !self.check_can_post(&community, data.owner).await
                {
                    return Err(Error::QuestionsDisabled);
                }

                // inherit nsfw status
                data.context.is_nsfw = community.context.is_nsfw;
            } else {
                // this should be unreachable
                return Err(Error::Unknown);
            }
        } else {
            // single
            let receiver = self.get_user_by_id(data.receiver).await?;

            if !receiver.settings.enable_questions {
                return Err(Error::QuestionsDisabled);
            }

            if !receiver.settings.allow_anonymous_questions && data.owner == 0 {
                return Err(Error::NotAllowed);
            }

            if !receiver.settings.enable_drawings && !drawings.is_empty() {
                return Err(Error::DrawingsDisabled);
            }

            // check muted phrases
            for phrase in receiver.settings.muted {
                if phrase.is_empty() {
                    continue;
                }

                if data.content.contains(&phrase) {
                    // act like the question was created so theyre less likely to try and send it again or bypass
                    return Ok(0);
                }
            }

            // check for ip block
            if self
                .get_ipblock_by_initiator_receiver(receiver.id, &RemoteAddr::from(data.ip.as_str()))
                .await
                .is_ok()
            {
                return Err(Error::NotAllowed);
            }
        }

        // check asking_about
        if let Some(id) = data.context.asking_about {
            let post = self.get_post_by_id(id).await?;
            let owner = self.get_user_by_id(post.owner).await?;

            if post.stack != 0 {
                return Err(Error::MiscError(
                    "Cannot ask about posts in a circle".to_string(),
                ));
            } else if owner.settings.private_profile {
                return Err(Error::MiscError(
                    "Cannot ask about posts from a private user".to_string(),
                ));
            }
        }

        // create uploads
        if drawings.len() > 2 {
            return Err(Error::MiscError(
                "Too many uploads. Please use a maximum of 2".to_string(),
            ));
        }

        for drawing in &drawings {
            // this is the initial iter to check sizes, we'll do uploads after
            if drawing.len() > Self::MAXIMUM_DRAWING_SIZE {
                return Err(Error::FileTooLarge);
            } else if drawing.len() < 25 {
                // if we have less than 25 bytes in a drawing, the drawing is likely blank
                return Err(Error::FileTooSmall);
            }
        }

        for _ in 0..drawings.len() {
            data.drawings.push(
                match self
                    .2
                    .create_upload(MediaUpload::new(
                        MediaType::Carpgraph,
                        data.owner,
                        "drawings".to_string(),
                    ))
                    .await
                {
                    Ok(x) => x.id,
                    Err(_) => continue,
                },
            );
        }

        // ...
        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 questions VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)",
            params![
                &(data.id as i64),
                &(data.created as i64),
                &(data.owner as i64),
                &(data.receiver as i64),
                &data.content,
                &{ if data.is_global { 1 } else { 0 } },
                &0_i32,
                &(data.community as i64),
                &0_i32,
                &0_i32,
                &serde_json::to_string(&data.context).unwrap(),
                &data.ip,
                &serde_json::to_string(&data.drawings).unwrap(),
            ]
        );

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

        // create request
        if !data.is_global {
            self.create_request(ActionRequest::with_id(
                data.id,
                data.receiver,
                ActionType::Answer,
                data.id,
                None,
            ))
            .await?;
        }

        // write to uploads
        for (i, drawing_id) in data.drawings.iter().enumerate() {
            let drawing = match drawings.get(i) {
                Some(d) => d,
                None => {
                    if let Err(e) = self.2.delete_upload(*drawing_id).await {
                        return Err(Error::MiscError(e.to_string()));
                    }

                    continue;
                }
            };

            let upload = match self.2.get_upload_by_id(*drawing_id).await {
                Ok(x) => x,
                Err(e) => return Err(Error::MiscError(e.to_string())),
            };

            if let Err(e) = std::fs::write(upload.path(&self.2.0.0.directory).to_string(), drawing)
            {
                return Err(Error::MiscError(e.to_string()));
            }
        }

        // return
        Ok(data.id)
    }

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

        if user.id != y.owner
            && user.id != y.receiver
            && !user.permissions.check(FinePermission::MANAGE_QUESTIONS)
        {
            if y.community != 0 {
                // check for MANAGE_QUESTIONS permission
                let membership = self
                    .get_membership_by_owner_community_no_void(user.id, y.community)
                    .await?;

                if !membership.role.check(CommunityPermission::MANAGE_QUESTIONS) {
                    return Err(Error::NotAllowed);
                }
            } else {
                return Err(Error::NotAllowed);
            }
        }

        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 questions WHERE id = $1",
            &[&(id as i64)]
        );

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

        self.0.1.remove(format!("atto.question:{}", id)).await;

        // delete request (if it exists and question isn't global)
        if !y.is_global
            && self
                .get_request_by_id_linked_asset(y.id, y.id)
                .await
                .is_ok()
        {
            // requests are also deleted when a post is created answering the given question
            // (unless the question is global)
            self.delete_request(y.id, y.id, user, false).await?;
        }

        // delete all posts answering question
        let res = execute!(
            &conn,
            "DELETE FROM posts WHERE context LIKE $1",
            &[&format!("%\"answering\":{id}%")]
        );

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

        // delete uploads
        for upload in y.drawings {
            if let Err(e) = self.2.delete_upload(upload).await {
                return Err(Error::MiscError(e.to_string()));
            }
        }

        // return
        Ok(())
    }

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

        for x in y {
            if user.id != x.receiver && !user.permissions.check(FinePermission::MANAGE_QUESTIONS) {
                return Err(Error::NotAllowed);
            }

            self.delete_question(x.id, user).await?
        }

        Ok(())
    }

    auto_method!(incr_question_answer_count() -> "UPDATE questions SET answer_count = answer_count + 1 WHERE id = $1" --cache-key-tmpl="atto.question:{}" --incr);
    auto_method!(decr_question_answer_count() -> "UPDATE questions SET answer_count = answer_count - 1 WHERE id = $1" --cache-key-tmpl="atto.question:{}" --decr);

    auto_method!(incr_question_likes() -> "UPDATE questions SET likes = likes + 1 WHERE id = $1" --cache-key-tmpl="atto.question:{}" --incr);
    auto_method!(incr_question_dislikes() -> "UPDATE questions SET dislikes = dislikes + 1 WHERE id = $1" --cache-key-tmpl="atto.question:{}" --incr);
    auto_method!(decr_question_likes() -> "UPDATE questions SET likes = likes - 1 WHERE id = $1" --cache-key-tmpl="atto.question:{}" --decr);
    auto_method!(decr_question_dislikes() -> "UPDATE questions SET dislikes = dislikes - 1 WHERE id = $1" --cache-key-tmpl="atto.question:{}" --decr);
}