✨ Recognize audio files as linked elements
[Sone.git] / src / main / kotlin / net / pterodactylus / sone / core / DefaultElementLoader.kt
1 package net.pterodactylus.sone.core
2
3 import com.google.common.base.Ticker
4 import com.google.common.cache.Cache
5 import com.google.common.cache.CacheBuilder
6 import freenet.keys.FreenetURI
7 import org.jsoup.Jsoup
8 import org.jsoup.nodes.Document
9 import org.jsoup.nodes.TextNode
10 import java.io.ByteArrayInputStream
11 import java.net.URLDecoder
12 import java.nio.charset.Charset
13 import java.text.Normalizer
14 import java.util.concurrent.TimeUnit.MINUTES
15 import javax.activation.MimeType
16 import javax.imageio.ImageIO
17 import javax.inject.Inject
18
19 /**
20  * [ElementLoader] implementation that uses a simple Guava [com.google.common.cache.Cache].
21  */
22 class DefaultElementLoader(private val freenetInterface: FreenetInterface, ticker: Ticker): ElementLoader {
23
24         @Inject constructor(freenetInterface: FreenetInterface): this(freenetInterface, Ticker.systemTicker())
25
26         private val loadingLinks: Cache<String, Boolean> = CacheBuilder.newBuilder().build()
27         private val failureCache: Cache<String, Boolean> = CacheBuilder.newBuilder().ticker(ticker).expireAfterWrite(30, MINUTES).build()
28         private val elementCache: Cache<String, LinkedElement> = CacheBuilder.newBuilder().build()
29         private val callback = object: FreenetInterface.BackgroundFetchCallback {
30                 override fun shouldCancel(uri: FreenetURI, mimeType: String, size: Long): Boolean {
31                         if (mimeType.startsWith("audio/")) {
32                                 elementCache.get(uri.toString().decode().normalize()) {
33                                         LinkedElement(uri.toString(), properties = mapOf(
34                                                         "type" to "audio", "size" to size, "sizeHuman" to size.human
35                                         ))
36                                 }
37                         }
38                         return (size > 2097152) || (!mimeType.startsWith("image/") && !mimeType.startsWith("text/html"))
39                 }
40
41                 override fun loaded(uri: FreenetURI, mimeTypeText: String, data: ByteArray) {
42                         MimeType(mimeTypeText).also { mimeType ->
43                                 when {
44                                         mimeType.primaryType == "image" -> {
45                                                 ByteArrayInputStream(data).use {
46                                                         ImageIO.read(it)
47                                                 }?.let {
48                                                         elementCache.get(uri.toString().decode().normalize()) {
49                                                                 LinkedElement(uri.toString(), properties = mapOf("type" to "image", "size" to data.size, "sizeHuman" to data.size.human))
50                                                         }
51                                                 }
52                                         }
53                                         mimeType.baseType == "text/html" -> {
54                                                 val document = Jsoup.parse(data.toString(Charset.forName(mimeType.getParameter("charset") ?: "UTF-8")))
55                                                 elementCache.get(uri.toString().decode().normalize()) {
56                                                         LinkedElement(uri.toString(), properties = mapOf(
57                                                                         "type" to "html", "size" to data.size, "sizeHuman" to data.size.human,
58                                                                         "title" to document.title().emptyToNull,
59                                                                         "description" to (document.metaDescription ?: document.firstNonHeadingParagraph)
60                                                         ))
61                                                 }
62                                         }
63                                 }
64                                 removeLoadingLink(uri)
65                         }
66                 }
67
68                 private val String?.emptyToNull get() = if (this == "") null else this
69
70                 private val Document.metaDescription: String?
71                         get() = head().getElementsByTag("meta")
72                                         .map { it.attr("name") to it.attr("content") }
73                                         .firstOrNull { it.first == "description" }
74                                         ?.second
75
76                 private val Document.firstNonHeadingParagraph: String?
77                         get() = body().children()
78                                         .filter { it.children().all { it is TextNode } }
79                                         .map { it to it.text() }
80                                         .filterNot { it.second == "" }
81                                         .firstOrNull { !it.first.tagName().startsWith("h", ignoreCase = true) }
82                                         ?.second
83
84                 private val Long.human get() = when (this) {
85                         in 0..1023 -> "$this B"
86                         in 1024..1048575 -> "${this / 1024} KiB"
87                         in 1048576..1073741823 -> "${this / 1048576} MiB"
88                         else -> "${this / 1073741824} GiB"
89                 }
90
91                 private val Int.human get() = toLong().human
92
93                 override fun failed(uri: FreenetURI) {
94                         failureCache.put(uri.toString().decode().normalize(), true)
95                         removeLoadingLink(uri)
96                 }
97
98                 private fun removeLoadingLink(uri: FreenetURI) {
99                         synchronized(loadingLinks) {
100                                 loadingLinks.invalidate(uri.toString().decode().normalize())
101                         }
102                 }
103         }
104
105         override fun loadElement(link: String): LinkedElement {
106                 val normalizedLink = link.decode().normalize()
107                 synchronized(loadingLinks) {
108                         elementCache.getIfPresent(normalizedLink)?.run {
109                                 return this
110                         }
111                         failureCache.getIfPresent(normalizedLink)?.run {
112                                 return LinkedElement(link, failed = true)
113                         }
114                         if (loadingLinks.getIfPresent(normalizedLink) == null) {
115                                 loadingLinks.put(normalizedLink, true)
116                                 freenetInterface.startFetch(FreenetURI(link), callback)
117                         }
118                 }
119                 return LinkedElement(link, loading = true)
120         }
121
122         private fun String.decode() = URLDecoder.decode(this, "UTF-8")!!
123         private fun String.normalize() = Normalizer.normalize(this, Normalizer.Form.NFC)!!
124
125 }