/
ServerApplication.scala
367 lines (325 loc) · 14.1 KB
/
ServerApplication.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
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
package io.youi.app
import java.io.File
import akka.actor.{ActorSystem, Cancellable}
import com.outr.hookup.{Hookup, HookupServer}
import io.youi.http._
import io.youi.http.content.{Content, FileContent, FormDataContent, StringContent, URLContent}
import io.youi.net.{ContentType, URL}
import io.youi.server.Server
import io.youi.server.handler.{CachingManager, HttpHandler, HttpHandlerBuilder, SenderHandler}
import io.youi.stream.{ByTag, Delta, HTMLParser, Selector}
import io.youi.{ErrorSupport, JavaScriptError, JavaScriptLog, Priority, http}
import net.sf.uadetector.UserAgentType
import net.sf.uadetector.service.UADetectorServiceFactory
import io.youi.stream._
import profig.{JsonUtil, Profig}
import reactify.{Channel, Var}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.concurrent.duration._
trait ServerApplication extends YouIApplication with Server {
private lazy val system = ActorSystem("ServerApplication")
override def isClient: Boolean = false
override def isServer: Boolean = true
val connected: Channel[Connection] = Channel[Connection]
val disconnected: Channel[Connection] = Channel[Connection]
lazy val cacheDirectory: Var[File] = Var(new File(System.getProperty("user.home"), ".cache"))
private var configuredEndPoints = Set.empty[ApplicationConnectivity]
private lazy val userAgentParser = UADetectorServiceFactory.getResourceModuleParser
protected def applicationBasePath: String = "app/application"
private val fullOpt = s"$applicationBasePath.js.youi"
private val fastOpt = s"$applicationBasePath-fastopt.js.youi"
private val fullOptMap = s"$fullOpt.map"
private val fastOptMap = s"$fastOpt.map"
private val jsDeps = s"$applicationBasePath-jsdeps.js.youi"
protected def applicationJSBasePath: String = "/app/application"
def applicationJSPath: String = s"$applicationJSBasePath.js"
def applicationJSMapPath: String = s"$applicationJSPath.map"
def applicationJSDepsPath: String = s"$applicationJSBasePath-jsdeps.js"
lazy val applicationJSContent: Content = Content.classPathOption(fullOpt).getOrElse(Content.classPath(fastOpt))
lazy val applicationJSMapContent: Content = Content.classPathOption(fullOptMap).getOrElse(Content.classPath(fastOptMap))
lazy val applicationJSDepsContent: Option[Content] = Content.classPathOption(jsDeps)
protected def scriptPaths: List[String] = Nil
protected def responseMap(httpConnection: HttpConnection): Map[String, String] = Map.empty
override protected def init(): Future[Unit] = super.init().map { _ =>
// Redirect Hookup errors to error support
Hookup.error.attach(t => ErrorSupport.error @= t)
connectivityEntries.attachAndFire { entries =>
ServerApplication.this.synchronized {
entries.foreach { appComm =>
if (!configuredEndPoints.contains(appComm)) {
val appCommHandler = new ServerConnectionHandler(appComm)
handler.matcher(path.exact(appComm.path)).wrap(appCommHandler)
configuredEndPoints += appComm
}
}
}
}
handler.matcher(path.exact("/source-map.min.js")).resource(Content.classPath("source-map.min.js"))
if (logJavaScriptErrors) {
handler.matcher(path.exact(logPath)).handle { httpConnection =>
val content = httpConnection.request.content
content match {
case Some(requestContent) => requestContent match {
case formData: FormDataContent => {
val ip = httpConnection.request.source
val userAgentString = Headers.Request.`User-Agent`.value(httpConnection.request.headers).getOrElse("")
val userAgent = userAgentParser.parse(userAgentString)
// Error logging
formData.stringOption("error").map(_.value).foreach { jsonString =>
val jsError = JsonUtil.fromJsonString[JavaScriptError](jsonString)
val exception = new JavaScriptException(
error = jsError,
userAgent = userAgent,
ip = ip,
request = httpConnection.request,
info = errorInfo(jsError, httpConnection)
)
if (logJavaScriptException(exception)) {
error(exception)
}
}
// Message logging
formData.stringOption("message").map(_.value).foreach { jsonString =>
val log = JsonUtil.fromJsonString[JavaScriptLog](jsonString)
scribe.info(s"[JS] ${log.message.trim} (ip: $ip, userAgent: $userAgentString)")
}
}
case otherContent => scribe.error(s"Unsupported content type: $otherContent (${otherContent.getClass.getName})")
}
case None => // Ignore
}
Future.successful(httpConnection.modify(_.withContent(Content.empty)))
}
}
val lastModifiedManager = CachingManager.LastModified()
// Serve up application.js
handler.matcher(path.exact(applicationJSPath)).caching(lastModifiedManager).resource(applicationJSContent)
// Serve up application.js.map
handler.matcher(path.exact(applicationJSMapPath)).caching(lastModifiedManager).resource(applicationJSMapContent)
// Serve up application-jsdeps.js (if available)
applicationJSDepsContent.foreach { content =>
handler.matcher(path.exact(applicationJSDepsPath)).caching(lastModifiedManager).resource(content)
}
}
def addTemplate(lookup: String => Option[Content],
mappings: Set[HttpConnection => Option[Content]] = Set.empty,
excludeDotHTML: Boolean = true,
deltas: List[Delta] = Nil,
includeApplication: URL => Boolean = _ => true): HttpHandler = {
// Serve up template files
handler.priority(Priority.Low).handle { httpConnection =>
if (httpConnection.response.content.isEmpty) {
val url = httpConnection.request.url
val fileName = url.path.decoded
val mapped = mappings.toStream.flatMap(_ (httpConnection)).headOption
val content = lookup(fileName).orElse { if (excludeDotHTML) {
lookup(s"$fileName.html")
} else {
None
}}
mapped.orElse(content).map { content =>
if (content.contentType == ContentType.`text/html`) {
CachingManager.NotCached.handle(httpConnection)
serveHTML(httpConnection, content, deltas, includeApplication(url))
} else {
CachingManager.LastModified().handle(httpConnection)
Future.successful(httpConnection.modify(_.withContent(content)))
}
}.getOrElse(Future.successful(httpConnection))
} else {
Future.successful(httpConnection)
}
}
}
protected val cancellable: Option[Cancellable] = Some(system.scheduler.schedule(30.seconds, 30.seconds) {
pingClients()
})
protected def errorInfo(error: JavaScriptError, httpConnection: HttpConnection): Map[String, String] = Map.empty
protected def page(page: Page): Page = {
handlers += page
page
}
protected def logJavaScriptException(exception: JavaScriptException): Boolean = {
val ua = exception.userAgent
ua.getType != UserAgentType.ROBOT
}
implicit class AppHandlerBuilder(builder: HttpHandlerBuilder) {
/**
* Stores deltas on this connection for use serving HTML.
*
* @param function the function that takes in an HttpConnection and returns a list of Deltas.
* @return HttpHandler that has already been added to the server
*/
def deltas(function: HttpConnection => List[Delta]): HttpHandler = builder.handle { connection =>
val d: List[Delta] = function(connection)
connection.deltas ++= d
Future.successful(connection)
}
def page(template: Content = ServerApplication.CanvasTemplate,
deltas: List[Delta] = Nil,
includeApplication: Boolean = true): HttpHandler = builder.handle { connection =>
serveHTML(connection, template, deltas, includeApplication)
}
}
override protected def handleInternal(connection: HttpConnection): Future[HttpConnection] = {
super.handleInternal(connection).flatMap { c =>
c.response.content match {
case Some(content) if content.contentType == ContentType.`text/html` && c.deltas.nonEmpty => {
serveHTML(c.modify(_.removeContent()), content, Nil, includeApplication = false)
}
case _ => Future.successful(c) // Ignore
}
}
}
def serveHTML(httpConnection: HttpConnection, content: Content, deltas: List[Delta], includeApplication: Boolean): Future[HttpConnection] = {
val stream = content match {
case c: FileContent => HTMLParser.cache(c.file)
case c: URLContent => HTMLParser.cache(c.url)
case c: StringContent => HTMLParser.cache(c.value)
}
val responseFields = responseMap(httpConnection).toList.map {
case (name, value) => s"""<input type="hidden" id="$name" value="$value"/>"""
}
val deltasList = httpConnection.deltas() ::: deltas
val applicationDeltas = if (includeApplication) {
val jsDeps = if (applicationJSDepsContent.nonEmpty) {
s"""<script src="$applicationJSDepsPath"></script>"""
} else {
""
}
List(
Delta.InsertLastChild(ByTag("body"),
s"""
|${scriptPaths.map(p => s"""<script src="$p"></script>""").mkString("\n")}
|${responseFields.mkString("\n")}
|$jsDeps
|<script src="$applicationJSPath"></script>
|<script>
| application();
|</script>
""".stripMargin
)
)
} else {
Nil
}
val d = applicationDeltas ::: deltasList
val selector = httpConnection.request.url.param("selector").map(Selector.parse)
val html = stream.stream(d, selector)
httpConnection.deltas.clear()
SenderHandler.handle(httpConnection, Content.string(html, ContentType.`text/html`), caching = CachingManager.NotCached)
}
private class ServerConnectionHandler(appComm: ApplicationConnectivity) extends HttpHandler {
override def handle(httpConnection: HttpConnection): Future[HttpConnection] = appComm.activeConnections.synchronized {
val connection = new Connection(client = false)
connection.store.update("httpConnection", httpConnection)
appComm.activeConnections @= (appComm.activeConnections() + connection)
connected @= connection
connection.connected.attach { b =>
if (!b) appComm.activeConnections.synchronized {
appComm.activeConnections @= (appComm.activeConnections() - connection)
HookupServer().foreach { hs =>
hs.remove(connection)
}
disconnected @= connection
}
}
connection.receive.text.attach {
case "PONG" => // Nothing to do, this finishes the workflow
case _ => // Ignore everything else
}
Future.successful(httpConnection.withWebSocket(connection))
}
}
private def pingClients(): Unit = connectivityEntries().foreach { entry =>
entry.connections().foreach { connection =>
connection.send.text @= "PING"
}
}
// Creates a cached version of the URL and adds an explicit matcher to serve it
override def cached(url: URL): String = {
val path = url.asPath()
val directory = cacheDirectory()
val file = new File(directory, path)
file.getParentFile.mkdirs()
IO.stream(new java.net.URL(url.toString), file)
val content = Content.file(file)
handler.matcher(http.path.exact(path)).resource(content)
path
}
def main(args: Array[String]): Unit = {
Profig.loadDefaults()
Profig.merge(args.toSeq)
start().failed.map { throwable =>
scribe.error("Error during application startup", throwable)
dispose()
}
}
override def dispose(): Unit = {
super.dispose()
system.terminate()
}
}
object ServerApplication {
/**
* Empty page template with overflow on the body disabled.
*/
lazy val CanvasTemplate: Content = Content.string(
"""
|<html>
|<head>
| <title></title>
| <style>
| body {
| margin: 0;
| overflow: hidden;
| width: 100vw;
| height: 100vh;
| }
| :focus {
| outline: none;
| }
| </style>
|</head>
|<body>
|</body>
|</html>
""".stripMargin.trim, ContentType.`text/html`)
/**
* Empty page template with overflow on the body disabled and viewport fixed to avoid zooming.
*/
lazy val AppTemplate: Content = Content.string(
"""
|<html>
|<head>
| <title></title>
| <!-- Required meta tags -->
| <meta charset="utf-8">
| <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
|
| <!-- Bootstrap CSS -->
| <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
| <style>
| body {
| margin: 0;
| overflow: hidden;
| width: 100vw;
| height: 100vh;
| }
| :focus {
| outline: none;
| }
| </style>
| <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
| <meta name="HandheldFriendly" content="true" />
|</head>
|<body>
|<!-- Scripts -->
|<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
|<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
|<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
|</body>
|</html>
""".stripMargin.trim, ContentType.`text/html`)
}