/
HTMLParser.scala
209 lines (187 loc) · 5.74 KB
/
HTMLParser.scala
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
package io.youi.stream
import java.io.{File, FileInputStream, InputStream}
import java.net.URL
import java.util.concurrent.ConcurrentHashMap
import io.youi.http.content._
import io.youi.stream._
import scala.annotation.tailrec
import scala.jdk.CollectionConverters._
object HTMLParser {
private val SelfClosingTagRegex = """(?s)<(\S+)(.*)/>""".r
private val OpenTagRegex = """(?s)<(\S+)(.*)>""".r
private val CloseTagRegex = """(?s)</(\S+).*>""".r
/**
* If set to true the stored tag attributes will be limited to those in validAttributes.
*
* Defaults to false.
*/
var filterAttributes: Boolean = false
/**
* The set of attributes to limit to if filterAttributes is set to true.
*
* Defaults to "id" and "class".
*/
var validAttributes: Set[String] = Set("id", "class")
private val parsers = new ConcurrentHashMap[File, StreamableHTML]().asScala
def cache(content: Content): StreamableHTML = content match {
case FileContent(file, _, _) => cache(file)
case URLContent(url, _, _) => cache(url)
case StringContent(value, _, _) => cache(value)
}
def cache(file: File): StreamableHTML = parsers.getOrElseUpdate(file, HTMLParser(file))
def cache(url: URL): StreamableHTML = {
val file = File.createTempFile("htmlparser", "cache")
file.deleteOnExit()
IO.stream(url, file)
cache(file)
}
def cache(html: String): StreamableHTML = {
val file = File.createTempFile("htmlparser", "cache")
file.deleteOnExit()
IO.stream(html, file)
cache(file)
}
def apply(file: File): StreamableHTML = {
val cacheBuilder = new CacheBuilder {
private var lastModified: Long = 0L
override def isStale: Boolean = lastModified != file.lastModified()
override def buildCache(): CachedInformation = {
val input = new FileInputStream(file)
try {
val parser = new HTMLParser(input)
val tags = parser.parse()
var byId = Map.empty[String, OpenTag]
var byClass = Map.empty[String, Set[OpenTag]]
var byTag = Map.empty[String, Set[OpenTag]]
tags.foreach { tag =>
if (tag.attributes.contains("id")) {
byId += tag.attributes("id") -> tag
}
tag.attributes.getOrElse("class", "").split(" ").foreach { className =>
val cn = className.trim
if (cn.nonEmpty) {
var classTags = byClass.getOrElse(cn, Set.empty[OpenTag])
classTags += tag
byClass += cn -> classTags
}
}
var tagsByName = byTag.getOrElse(tag.tagName, Set.empty[OpenTag])
tagsByName += tag
byTag += tag.tagName -> tagsByName
}
lastModified = file.lastModified()
CachedInformation(byId, byClass, byTag)
} catch {
case throwable: Throwable => throw new RuntimeException(s"Error parsing ${file.getAbsolutePath}", throwable)
} finally {
input.close()
}
}
}
new StreamableHTML(file, cacheBuilder)
}
}
class HTMLParser(input: InputStream) {
import HTMLParser._
private var position = 0
private val b = new StringBuilder
private var quotes = false
private var tagStart = -1
private var tagEnd = -1
private var open = List.empty[OpenTag]
private var tags = Set.empty[OpenTag]
@tailrec
final def parse(): Set[OpenTag] = input.read() match {
case -1 => tags // Finished
case i => {
val c = i.toChar
process(c)
parse()
}
}
private def process(c: Char): Unit = {
b.append(c)
if (c == '"') {
if (quotes) {
quotes = false
} else {
quotes = true
}
} else if (c == '\n' || c == '\r') {
quotes = false
} else if (c == '<' && !quotes) {
b.clear()
b.append(c)
tagStart = position
} else if (tagStart != -1 && c == '>' && !quotes) {
tagEnd = position + 1
parseTag()
b.clear()
tagStart = -1
}
position += 1
}
private def parseTag(): Unit = b.toString() match {
case s if s.startsWith("<!--") || s.endsWith("-->") => // Ignore
case CloseTagRegex(tagName) => {
val closeTag = CloseTag(tagName, tagStart, tagEnd)
val openTag = closeUntil(tagName).copy(close = Some(closeTag))
tags += openTag
}
case SelfClosingTagRegex(tagName, attributes) => {
val a = parseAttributes(attributes)
val tag = OpenTag(tagName, a, tagStart, tagEnd, close = None)
tags += tag
}
case OpenTagRegex(tagName, attributes) => {
val a = parseAttributes(attributes)
val tag = OpenTag(tagName, a, tagStart, tagEnd, close = None)
open = tag :: open
}
}
private def parseAttributes(attributes: String): Map[String, String] = {
val sb = new StringBuilder
var quoted = false
var key = ""
var map = Map.empty[String, String]
attributes.zipWithIndex.foreach {
case (c, index) => {
if (c == '"') {
if (quoted) {
map += key -> sb.toString()
quoted = false
sb.clear()
} else {
quoted = true
}
} else if ((c == '=' || c == ' ') && !quoted) {
if (sb.nonEmpty) {
key = sb.toString()
sb.clear()
}
} else {
sb.append(c)
}
}
}
if (filterAttributes) {
map.filter(t => validAttributes.contains(t._1))
} else {
map
}
}
@tailrec
private def closeUntil(tagName: String): OpenTag = {
if (open.isEmpty) {
throw new RuntimeException(s"Missing close tag for $tagName!")
}
val t = open.head
open = open.tail
if (t.tagName.equalsIgnoreCase(tagName)) {
t
} else {
tags += t
closeUntil(tagName)
}
}
}