🔀 Merge branch 'release/v82'
[Sone.git] / src / main / kotlin / net / pterodactylus / sone / template / PostAccessor.kt
1 /*
2  * Sone - PostAccessor.kt - Copyright Â© 2010–2020 David Roden
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17
18 package net.pterodactylus.sone.template
19
20 import net.pterodactylus.sone.core.*
21 import net.pterodactylus.sone.data.*
22 import net.pterodactylus.sone.utils.*
23 import net.pterodactylus.util.template.*
24
25 /**
26  * Accessor for [Post] objects that adds additional properties:
27  *
28  * * `replies`: All replies to this post, sorted by time, oldest first
29  * * `likes`: All Sones that have liked the post
30  * * `liked`: `true` if the current Sone from the [template context][TemplateContext] has liked the post
31  * * `new`: `true` if the post is not known
32  * * `bookmarked`: `true` if the post is bookmarked
33  */
34 class PostAccessor(private val core: Core) : ReflectionAccessor() {
35
36         override fun get(templateContext: TemplateContext?, `object`: Any?, member: String): Any? =
37                         (`object` as Post).let { post ->
38                                 when (member) {
39                                         "replies" -> core.getReplies(post)
40                                         "likes" -> core.getLikes(post)
41                                         "liked" -> templateContext.currentSone?.isLikedPostId(post.id) ?: false
42                                         "new" -> !post.isKnown
43                                         "bookmarked" -> core.isBookmarked(post)
44                                         "replySone" -> core.getReplies(post).lastOrNull { it.sone.isLocal }?.sone
45                                                         ?: post.recipient.let { it.takeIf { it.isLocal } }
46                                                         ?: post.sone.takeIf { it.isLocal }
47                                                         ?: templateContext.currentSone
48                                         else -> super.get(templateContext, `object`, member)
49                                 }
50                         }
51
52 }
53
54 private fun Core.getReplies(post: Post) = getReplies(post.id).filter(noFutureReply)
55 private val TemplateContext?.currentSone: Sone? get() = this?.get("currentSone") as? Sone