2 * Sone - PostAccessor.java - Copyright © 2010–2019 David Roden
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.
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.
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/>.
17 package net.pterodactylus.sone.template
19 import net.pterodactylus.sone.core.*
20 import net.pterodactylus.sone.data.*
21 import net.pterodactylus.sone.utils.*
22 import net.pterodactylus.util.template.*
25 * Accessor for [Post] objects that adds additional properties:
27 * * `replies`: All replies to this post, sorted by time, oldest first
28 * * `likes`: All Sones that have liked the post
29 * * `liked`: `true` if the current Sone from the [template context][TemplateContext] has liked the post
30 * * `new`: `true` if the post is not known
31 * * `bookmarked`: `true` if the post is bookmarked
33 class PostAccessor(private val core: Core) : ReflectionAccessor() {
35 override fun get(templateContext: TemplateContext?, `object`: Any?, member: String): Any? =
36 (`object` as Post).let { post ->
38 "replies" -> core.getReplies(post)
39 "likes" -> core.getLikes(post)
40 "liked" -> templateContext.currentSone?.isLikedPostId(post.id) ?: false
41 "new" -> !post.isKnown
42 "bookmarked" -> core.isBookmarked(post)
43 "replySone" -> core.getReplies(post).lastOrNull { it.sone.isLocal }?.sone
44 ?: post.recipient.let { it.takeIf { it.isLocal } }
45 ?: post.sone.takeIf { it.isLocal }
46 ?: templateContext.currentSone
47 else -> super.get(templateContext, `object`, member)
53 private fun Core.getReplies(post: Post) = getReplies(post.id).filter { Reply.FUTURE_REPLY_FILTER.apply(it) }
54 private val TemplateContext?.currentSone: Sone? get() = this?.get("currentSone") as? Sone