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
use frame_support::dispatch::DispatchResult;

use pallet_utils::{SpaceId, remove_from_vec};

use super::*;

impl<T: Trait> Post<T> {

    pub fn new(
        id: PostId,
        created_by: T::AccountId,
        space_id_opt: Option<SpaceId>,
        extension: PostExtension,
        content: Content
    ) -> Self {
        Post {
            id,
            created: WhoAndWhen::<T>::new(created_by.clone()),
            updated: None,
            owner: created_by,
            extension,
            space_id: space_id_opt,
            content,
            hidden: false,
            replies_count: 0,
            hidden_replies_count: 0,
            shares_count: 0,
            upvotes_count: 0,
            downvotes_count: 0,
            score: 0
        }
    }

    pub fn ensure_owner(&self, account: &T::AccountId) -> DispatchResult {
        ensure!(self.is_owner(account), Error::<T>::NotAPostOwner);
        Ok(())
    }

    pub fn is_owner(&self, account: &T::AccountId) -> bool {
        self.owner == *account
    }

    pub fn is_root_post(&self) -> bool {
        !self.is_comment()
    }

    pub fn is_regular_post(&self) -> bool {
        matches!(self.extension, PostExtension::RegularPost)
    }

    pub fn is_comment(&self) -> bool {
        matches!(self.extension, PostExtension::Comment(_))
    }

    pub fn is_sharing_post(&self) -> bool {
        matches!(self.extension, PostExtension::SharedPost(_))
    }

    pub fn get_comment_ext(&self) -> Result<Comment, DispatchError> {
        match self.extension {
            PostExtension::Comment(comment_ext) => Ok(comment_ext),
            _ => Err(Error::<T>::NotComment.into())
        }
    }

    pub fn get_shared_post_id(&self) -> Result<PostId, DispatchError> {
        match self.extension {
            PostExtension::SharedPost(post_id) => Ok(post_id),
            _ => Err(Error::<T>::NotASharingPost.into())
        }
    }

    pub fn get_root_post(&self) -> Result<Post<T>, DispatchError> {
        match self.extension {
            PostExtension::RegularPost | PostExtension::SharedPost(_) =>
                Ok(self.clone()),
            PostExtension::Comment(comment) =>
                Module::require_post(comment.root_post_id),
        }
    }

    pub fn get_space_id(&self) -> Result<SpaceId, DispatchError> {
        Self::try_get_space_id(self).ok_or_else(|| Error::<T>::PostHasNoSpaceId.into())
    }

    pub fn try_get_space_id(&self) -> Option<SpaceId> {
        if let Ok(root_post) = self.get_root_post() {
            return root_post.space_id;
        }

        None
    }

    pub fn get_space(&self) -> Result<Space<T>, DispatchError> {
        let root_post = self.get_root_post()?;
        let space_id = root_post.space_id.ok_or(Error::<T>::PostHasNoSpaceId)?;
        Spaces::require_space(space_id)
    }

    pub fn try_get_space(&self) -> Option<Space<T>> {
        if let Ok(root_post) = self.get_root_post() {
            return root_post.space_id.and_then(|space_id| Spaces::require_space(space_id).ok());
        }

        None
    }

    // TODO use macros to generate inc/dec fns for Space, Post.

    pub fn inc_replies(&mut self) {
        self.replies_count = self.replies_count.saturating_add(1);
    }

    pub fn dec_replies(&mut self) {
        self.replies_count = self.replies_count.saturating_sub(1);
    }

    pub fn inc_hidden_replies(&mut self) {
        self.hidden_replies_count = self.hidden_replies_count.saturating_add(1);
    }

    pub fn dec_hidden_replies(&mut self) {
        self.hidden_replies_count = self.hidden_replies_count.saturating_sub(1);
    }

    pub fn inc_shares(&mut self) {
        self.shares_count = self.shares_count.saturating_add(1);
    }

    pub fn dec_shares(&mut self) {
        self.shares_count = self.shares_count.saturating_sub(1);
    }

    pub fn inc_upvotes(&mut self) {
        self.upvotes_count = self.upvotes_count.saturating_add(1);
    }

    pub fn dec_upvotes(&mut self) {
        self.upvotes_count = self.upvotes_count.saturating_sub(1);
    }

    pub fn inc_downvotes(&mut self) {
        self.downvotes_count = self.downvotes_count.saturating_add(1);
    }

    pub fn dec_downvotes(&mut self) {
        self.downvotes_count = self.downvotes_count.saturating_sub(1);
    }

    #[allow(clippy::comparison_chain)]
    pub fn change_score(&mut self, diff: i16) {
        if diff > 0 {
            self.score = self.score.saturating_add(diff.abs() as i32);
        } else if diff < 0 {
            self.score = self.score.saturating_sub(diff.abs() as i32);
        }
    }

    pub fn is_public(&self) -> bool {
        !self.hidden && self.content.is_some()
    }

    pub fn is_unlisted(&self) -> bool {
        !self.is_public()
    }
}

impl Default for PostUpdate {
    fn default() -> Self {
        PostUpdate {
            space_id: None,
            content: None,
            hidden: None
        }
    }
}

impl<T: Trait> Module<T> {

    pub fn ensure_account_can_update_post(
        editor: &T::AccountId,
        post: &Post<T>,
        space: &Space<T>
    ) -> DispatchResult {
        let is_owner = post.is_owner(&editor);
        let is_comment = post.is_comment();

        let permission_to_check: SpacePermission;
        let permission_error: DispatchError;

        if is_comment {
          if is_owner {
            permission_to_check = SpacePermission::UpdateOwnComments;
            permission_error = Error::<T>::NoPermissionToUpdateOwnComments.into();
          } else {
            return Err(Error::<T>::NotACommentAuthor.into());
          }
        } else {
          // Not a comment

          if is_owner {
            permission_to_check = SpacePermission::UpdateOwnPosts;
            permission_error = Error::<T>::NoPermissionToUpdateOwnPosts.into();
          } else {
            permission_to_check = SpacePermission::UpdateAnyPost;
            permission_error = Error::<T>::NoPermissionToUpdateAnyPost.into();
          }
        }

        Spaces::ensure_account_has_space_permission(
          editor.clone(),
          space,
          permission_to_check,
          permission_error
        )
    }

    /// Check that there is a `Post` with such `post_id` in the storage
    /// or return`PostNotFound` error.
    pub fn ensure_post_exists(post_id: PostId) -> DispatchResult {
        ensure!(<PostById<T>>::contains_key(post_id), Error::<T>::PostNotFound);
        Ok(())
    }

    /// Get `Post` by id from the storage or return `PostNotFound` error.
    pub fn require_post(post_id: SpaceId) -> Result<Post<T>, DispatchError> {
        Ok(Self::post_by_id(post_id).ok_or(Error::<T>::PostNotFound)?)
    }

    fn share_post(
        account: T::AccountId,
        original_post: &mut Post<T>,
        shared_post_id: PostId
    ) -> DispatchResult {
        original_post.inc_shares();

        T::PostScores::score_post_on_new_share(account.clone(), original_post)?;

        let original_post_id = original_post.id;
        PostById::insert(original_post_id, original_post.clone());
        SharedPostIdsByOriginalPostId::mutate(original_post_id, |ids| ids.push(shared_post_id));

        Self::deposit_event(RawEvent::PostShared(account, original_post_id));

        Ok(())
    }

    pub fn is_root_post_hidden(post_id: PostId) -> Result<bool, DispatchError> {
        let post = Self::require_post(post_id)?;
        let root_post = post.get_root_post()?;
        Ok(root_post.hidden)
    }

    pub fn is_root_post_visible(post_id: PostId) -> Result<bool, DispatchError> {
        Self::is_root_post_hidden(post_id).map(|v| !v)
    }

    pub fn mutate_post_by_id<F: FnOnce(&mut Post<T>)> (
        post_id: PostId,
        f: F
    ) -> Result<Post<T>, DispatchError> {
        <PostById<T>>::mutate(post_id, |post_opt| {
            if let Some(ref mut post) = post_opt.clone() {
                f(post);
                *post_opt = Some(post.clone());

                return Ok(post.clone());
            }

            Err(Error::<T>::PostNotFound.into())
        })
    }

    // TODO refactor to a tail recursion
    /// Get all post ancestors (parent_id) including this post
    pub fn get_post_ancestors(post_id: PostId) -> Vec<Post<T>> {
        let mut ancestors: Vec<Post<T>> = Vec::new();

        if let Some(post) = Self::post_by_id(post_id) {
            ancestors.push(post.clone());
            if let Some(parent_id) = post.get_comment_ext().ok().unwrap().parent_id {
                ancestors.extend(Self::get_post_ancestors(parent_id).iter().cloned());
            }
        }

        ancestors
    }

    /// Applies function to all post ancestors (parent_id) including this post
    pub fn for_each_post_ancestor<F: FnMut(&mut Post<T>) + Copy> (
        post_id: PostId,
        f: F
    ) -> DispatchResult {
        let post = Self::mutate_post_by_id(post_id, f)?;

        if let PostExtension::Comment(comment_ext) = post.extension {
            if let Some(parent_id) = comment_ext.parent_id {
                Self::for_each_post_ancestor(parent_id, f)?;
            }
        }

        Ok(())
    }

    pub fn try_get_post_replies(post_id: PostId) -> Vec<Post<T>> {
        let mut replies: Vec<Post<T>> = Vec::new();

        if let Some(post) = Self::post_by_id(post_id) {
            replies.push(post);
            for reply_id in Self::reply_ids_by_post_id(post_id).iter() {
                replies.extend(Self::try_get_post_replies(*reply_id).iter().cloned());
            }
        }

        replies
    }

    /// Recursively et all nested post replies (reply_ids_by_post_id)
    pub fn get_post_replies(post_id: PostId) -> Result<Vec<Post<T>>, DispatchError> {
        let reply_ids = Self::reply_ids_by_post_id(post_id);
        ensure!(!reply_ids.is_empty(), Error::<T>::NoRepliesOnPost);

        let mut replies: Vec<Post<T>> = Vec::new();
        for reply_id in reply_ids.iter() {
            replies.extend(Self::try_get_post_replies(*reply_id));
        }
        Ok(replies)
    }
    // TODO: maybe add for_each_reply?

    pub(crate) fn create_comment(
        creator: &T::AccountId,
        new_post_id: PostId,
        comment_ext: Comment,
        root_post: &mut Post<T>
    ) -> DispatchResult {
        let mut commented_post_id = root_post.id;

        if let Some(parent_id) = comment_ext.parent_id {
            let parent_comment = Self::post_by_id(parent_id).ok_or(Error::<T>::UnknownParentComment)?;
            ensure!(parent_comment.is_comment(), Error::<T>::NotACommentByParentId);

            let ancestors = Self::get_post_ancestors(parent_id);
            ensure!(ancestors.len() < T::MaxCommentDepth::get() as usize, Error::<T>::MaxCommentDepthReached);

            commented_post_id = parent_id;
        }

        root_post.inc_replies();
        T::PostScores::score_root_post_on_new_comment(creator.clone(), root_post)?;

        Self::for_each_post_ancestor(commented_post_id, |post| post.inc_replies())?;
        PostById::insert(root_post.id, root_post);
        ReplyIdsByPostId::mutate(commented_post_id, |reply_ids| reply_ids.push(new_post_id));

        Ok(())
    }

    pub(crate) fn create_sharing_post(
        creator: &T::AccountId,
        new_post_id: PostId,
        original_post_id: PostId,
        space: &mut Space<T>
    ) -> DispatchResult {
        let original_post = &mut Self::post_by_id(original_post_id)
            .ok_or(Error::<T>::OriginalPostNotFound)?;

        ensure!(!original_post.is_sharing_post(), Error::<T>::CannotShareSharingPost);

        // Check if it's allowed to share a post from the space of original post.
        Spaces::ensure_account_has_space_permission(
            creator.clone(),
            &original_post.get_space()?,
            SpacePermission::Share,
            Error::<T>::NoPermissionToShare.into()
        )?;

        space.inc_posts();

        Self::share_post(creator.clone(), original_post, new_post_id)
    }

    fn mutate_posts_count_on_space<F: FnMut(&mut u32) + Copy> (
        space_id: SpaceId,
        post: &Post<T>,
        mut f: F
    ) -> DispatchResult {
        Spaces::<T>::mutate_space_by_id(space_id, |space: &mut Space<T>| {
            f(&mut space.posts_count);
            if post.hidden {
                f(&mut space.hidden_posts_count);
            }
        }).map(|_| ())
    }

    pub(crate) fn move_post_to_space(
        editor: T::AccountId,
        post: &mut Post<T>,
        new_space_id: SpaceId
    ) -> DispatchResult {
        let old_space_id_opt = post.try_get_space_id();
        let new_space = Spaces::<T>::require_space(new_space_id)?;

        ensure!(
            T::IsAccountBlocked::is_allowed_account(editor.clone(), new_space_id),
            UtilsError::<T>::AccountIsBlocked
        );
        Spaces::ensure_account_has_space_permission(
            editor,
            &new_space,
            SpacePermission::CreatePosts,
            Error::<T>::NoPermissionToCreatePosts.into()
        )?;
        ensure!(
            T::IsPostBlocked::is_allowed_post(post.id, new_space_id),
            UtilsError::<T>::PostIsBlocked
        );
        ensure!(
            T::IsContentBlocked::is_allowed_content(post.content.clone(), new_space_id),
            UtilsError::<T>::ContentIsBlocked
        );

        match post.extension {
            PostExtension::RegularPost | PostExtension::SharedPost(_) => {

                if let Some(old_space_id) = old_space_id_opt {

                    // Decrease the number of posts on the old space
                    Self::mutate_posts_count_on_space(
                        old_space_id,
                        post,
                        |counter| *counter = counter.saturating_sub(1)
                    )?;

                    // Decrease a score on the old space
                    Spaces::<T>::mutate_space_by_id(
                        old_space_id,
                        |space| space.score = space.score.saturating_sub(post.score)
                    )?;

                    PostIdsBySpaceId::mutate(old_space_id, |post_ids| remove_from_vec(post_ids, post.id));
                }

                // Increase the number of posts on the new space
                Self::mutate_posts_count_on_space(
                    new_space_id,
                    post,
                    |counter| *counter = counter.saturating_add(1)
                )?;

                // Increase a score on the new space
                Spaces::<T>::mutate_space_by_id(
                    new_space_id,
                    |space| space.score = space.score.saturating_add(post.score)
                )?;

                PostIdsBySpaceId::mutate(new_space_id, |post_ids| post_ids.push(post.id));

                post.space_id = Some(new_space_id);
                PostById::<T>::insert(post.id, post);

                Ok(())
            },
            _ => fail!(Error::<T>::CannotUpdateSpaceIdOnComment),
        }
    }

    pub fn delete_post_from_space(post_id: PostId) -> DispatchResult {
        let mut post = Self::require_post(post_id)?;

        if let PostExtension::Comment(comment_ext) = post.extension {
            post.extension = PostExtension::RegularPost;

            let root_post = &mut Self::require_post(comment_ext.root_post_id)?;
            let parent_id = comment_ext.parent_id.unwrap_or(root_post.id);

            let dec_replies_count: fn(&mut Post<T>) = |p| {
                p.dec_replies();
                if p.hidden {
                    p.dec_hidden_replies();
                }
            };

            dec_replies_count(root_post);
            PostById::<T>::insert(root_post.id, root_post.clone());
            Self::for_each_post_ancestor(parent_id, dec_replies_count)?;

            // Subtract the weight of CreateComment from the root post and its space
            T::PostScores::score_root_post_on_new_comment(post.created.account.clone(), root_post)?;
            let replies = Self::get_post_replies(post_id)?;
            for reply in replies.iter() {
                T::PostScores::score_root_post_on_new_comment(reply.created.account.clone(), root_post)?;
            }
        } else {
            // If post is not a comment:

            let space_id = post.get_space_id()?;

            // Decrease the number of posts on the space
            Self::mutate_posts_count_on_space(
                space_id,
                &post,
                |counter| *counter = counter.saturating_sub(1)
            )?;

            Spaces::<T>::mutate_space_by_id(
                space_id,
                |space| space.score = space.score.saturating_sub(post.score)
            )?;

            post.space_id = None;
            PostIdsBySpaceId::mutate(space_id, |post_ids| remove_from_vec(post_ids, post_id));
        }

        PostById::<T>::insert(post.id, post);

        Ok(())
    }

    /// Rewrite ancestor counters when Post hidden status changes
    /// Warning: This will affect storage state!
    pub(crate) fn update_counters_on_comment_hidden_change(
        comment_ext: &Comment,
        becomes_hidden: bool
    ) -> DispatchResult {
        let root_post = &mut Self::require_post(comment_ext.root_post_id)?;
        let commented_post_id = comment_ext.parent_id.unwrap_or(root_post.id);

        let mut update_hidden_replies: fn(&mut Post<T>) = Post::inc_hidden_replies;
        if !becomes_hidden {
            update_hidden_replies = Post::dec_hidden_replies;
        }

        Self::for_each_post_ancestor(commented_post_id, |post| update_hidden_replies(post))?;

        update_hidden_replies(root_post);
        PostById::insert(root_post.id, root_post);

        Ok(())
    }
}