Browse Source

Merge pull request #97 from MutinyChat/94-fix-popup

[WIP] Add static files serving, templating and popup.html
Andrei 2 years ago
parent
commit
8723e97756
9 changed files with 166 additions and 51 deletions
  1. 62 0
      pkg/apps/apps.go
  2. 10 0
      pkg/routes/routes.go
  3. 20 4
      server.go
  4. 11 1
      server/daemon.go
  5. 8 0
      statics/404.html
  6. 9 0
      statics/popup.html
  7. 0 46
      templates.go
  8. 8 0
      templates/404.html
  9. 38 0
      templates/tabulator.html

+ 62 - 0
pkg/apps/apps.go

@@ -0,0 +1,62 @@
+// Package apps provides functions for rendering application templates
+// TODO: implement strategy pattern
+package apps
+
+import(
+	"strings"
+	"html/template"
+	"log"
+	"fmt"
+	"io/ioutil"
+
+	"github.com/linkeddata/gold/pkg/routes"
+)
+
+var(
+	apps = map[string]string {
+		"DataApp": "templates/tabulator.html",
+		"404": routes.NotFound(),
+	}
+	templates = template.New("")
+)
+
+// DataApp renders Data application template
+func DataApp()(string, error) {
+	app, err := render("DataApp", template.URL(routes.Popup()))
+	if err != nil {
+		return "", fmt.Errorf("Failed to render DataApp: %v", err)
+	}
+	return app, nil
+}
+
+// NotFound returns 404 page
+func NotFound()(string, error) {
+	app, err := render("404", nil)
+	if err != nil {
+		return "", fmt.Errorf("Failed to render NotFound: %v", err)
+	}
+	return app, nil
+}
+
+func render(name string, data interface{})(string, error) {
+	var writer strings.Builder
+	err := templates.ExecuteTemplate(&writer, name, data)
+	if err != nil {
+		return "", err
+	}
+	return writer.String(), nil
+}
+	
+func init() {
+	for app, path := range(apps) {
+		tmpFile, err := ioutil.ReadFile(path)
+		if err != nil {
+			log.Panicf("Failed to read template file %s: %v", path, err)
+		}
+
+		_, err = templates.New(app).Parse(string(tmpFile))
+		if err != nil {
+			log.Panicf("Failed to parse template for %s: %v", app, err)
+		}
+	}
+}

+ 10 - 0
pkg/routes/routes.go

@@ -0,0 +1,10 @@
+// Package routes provides helpers for routing
+package routes
+
+func NotFound() string {
+	return "statics/404.html"
+}
+
+func Popup() string {
+	return "statics/popup.html"
+}

+ 20 - 4
server.go

@@ -19,6 +19,9 @@ import (
 	"github.com/boltdb/bolt"
 	"github.com/gorilla/securecookie"
 	"golang.org/x/net/webdav"
+
+	"github.com/linkeddata/gold/pkg/apps"
+//	"github.com/linkeddata/gold/pkg/routes"
 )
 
 const (
@@ -193,6 +196,14 @@ func (r *response) respond(status int, a ...interface{}) *response {
 	return r
 }
 
+func (r *response) respondNotFound() *response {
+	page404, err := apps.NotFound()
+	if err != nil {
+		return r.respond(500, err)
+	}
+	return r.respond(404, page404)
+}
+
 // ServeHTTP handles the response
 func (s *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
 	// add HSTS
@@ -313,7 +324,7 @@ func (s *Server) handle(w http.ResponseWriter, req *httpRequest) (r *response) {
 	w.Header().Set("MS-Author-Via", "DAV, SPARQL")
 	w.Header().Set("Updates-Via", "wss://"+req.Host+"/")
 
-	// Get request key
+ 	// Get request key
 	rKey := req.Request.FormValue("key")
 
 	// Authentication
@@ -453,7 +464,7 @@ func (s *Server) handle(w http.ResponseWriter, req *httpRequest) (r *response) {
 		}
 
 		if !resource.Exists {
-			return r.respond(404, Apps["404"])
+			return r.respondNotFound()
 		}
 
 		// First redirect to path + trailing slash if it's missing
@@ -697,7 +708,12 @@ func (s *Server) handle(w http.ResponseWriter, req *httpRequest) (r *response) {
 				w.Header().Set("Link", brack(resource.MetaURI)+"; rel=\"meta\", "+brack(resource.AclURI)+"; rel=\"acl\"")
 				if maybeRDF {
 					w.Header().Set(HCType, contentType)
-					return r.respond(200, Apps[s.Config.DataApp])
+					s.debug.Println("Rendering data app")
+					app, err := apps.DataApp()
+					if err != nil {
+						return r.respond(500, "")
+					}
+					return r.respond(200, app)
 				}
 				w.Header().Set(HCType, magicType)
 				w.WriteHeader(200)
@@ -1191,7 +1207,7 @@ func (s *Server) handle(w http.ResponseWriter, req *httpRequest) (r *response) {
 		err = os.Remove(resource.File)
 		if err != nil {
 			if os.IsNotExist(err) {
-				return r.respond(404, Apps["404"])
+				return r.respondNotFound()
 			}
 			return r.respond(500, err)
 		}

+ 11 - 1
server/daemon.go

@@ -165,6 +165,15 @@ func main() {
 		return
 	}
 
+	// Serve files from /statics/
+	if os.Getenv("SERVE_STATIC_FILES") == "true" {
+		fs := http.FileServer(http.Dir("statics"))
+		http.Handle("/statics/", http.StripPrefix("/statics/", fs))
+	}
+
+	// Main handler
+	http.Handle("/", handler)
+	
 	if config.Insecure {
 		err = http.ListenAndServe(config.ListenHTTP, handler)
 		if err != nil {
@@ -183,11 +192,12 @@ func main() {
 	}
 
 	var (
-		srv  = &http.Server{Addr: config.ListenHTTPS, Handler: handler}
+		srv  = &http.Server{Addr: config.ListenHTTPS}
 		tcpL net.Listener
 		tlsL net.Listener
 	)
 
+	
 	tlsConfig := NewTLSConfig(config.WebIDTLS)
 
 	tlsConfig.Certificates = make([]tls.Certificate, 1)

+ 8 - 0
statics/404.html

@@ -0,0 +1,8 @@
+<!DOCTYPE html>
+<html id="docHTML">
+<head>
+</head>
+<body>
+    <h1>404 - oh noes, there's nothing here</h1>
+</body>
+</html>

File diff suppressed because it is too large
+ 9 - 0
statics/popup.html


+ 0 - 46
templates.go

@@ -3,44 +3,6 @@ package gold
 var (
 	// Apps contains a list of default apps that get server instead of RDF
 	Apps = map[string]string{
-		"tabulator": `<!DOCTYPE html>
-<html id="docHTML">
-<head>
-    <link type="text/css" rel="stylesheet" href="https://solid.github.io/solid-panes/style/tabbedtab.css" />
-    <script>
-      var $SOLID_GLOBAL_config = {
-        popupUri: window.location.origin + '/common/popup.html'
-      }
-    </script>
-    <script type="text/javascript" src="https://linkeddata.github.io/mashlib/dist/mashlib.min.js"></script>
-    <script>
-      document.addEventListener('DOMContentLoaded', function () {
-        const panes = require('mashlib')
-        const UI = panes.UI
-
-        // Set up cross-site proxy
-        const $rdf = UI.rdf
-        $rdf.Fetcher.crossSiteProxyTemplate = document.origin + '/xss/?uri={uri}'
-
-        // Authenticate the user
-        UI.authn.checkUser()
-          .then(function () {
-            // Set up the view for the current subject
-            const kb = UI.store
-            const uri = window.location.href
-            const subject = kb.sym(uri)
-            const outliner = panes.getOutliner(document)
-            outliner.GotoSubject(subject, true, undefined, true, undefined)
-          })
-      })
-    </script>
-</head>
-<body>
-<div class="TabulatorOutline" id="DummyUUID">
-    <table id="outline"></table>
-</div>
-</body>
-</html>`,
 		"newCert": `<!DOCTYPE html>
 <html id="docHTML">
 <body>
@@ -96,14 +58,6 @@ var (
     <h1>403 - oh noes, access denied!</h1>
     <h2>Please visit the <a href="/` + SystemPrefix + `/accountRecovery">recovery page</a> in case you have lost access to your credentials.</h2>
 </body>
-</html>`,
-		"404": `<!DOCTYPE html>
-<html id="docHTML">
-<head>
-</head>
-<body>
-    <h1>404 - oh noes, there's nothing here</h1>
-</body>
 </html>`,
 	}
 	// SMTPTemplates contains a list of templates for sending emails

+ 8 - 0
templates/404.html

@@ -0,0 +1,8 @@
+<!DOCTYPE html>
+<html id="docHTML">
+<head>
+</head>
+<body>
+    <h1>404 - oh noes, there's nothing here</h1>
+</body>
+</html>

+ 38 - 0
templates/tabulator.html

@@ -0,0 +1,38 @@
+<!DOCTYPE html>
+<html id="docHTML">
+  <head>
+    <link type="text/css" rel="stylesheet" href="https://solid.github.io/solid-panes/style/tabbedtab.css" />
+    <script>
+      var $SOLID_GLOBAL_config = {
+      popupUri: window.location.origin + '/' + {{ . }}
+      }
+    </script>
+    <script type="text/javascript" src="https://linkeddata.github.io/mashlib/dist/mashlib.min.js"></script>
+    <script>
+      document.addEventListener('DOMContentLoaded', function () {
+        const panes = require('mashlib')
+        const UI = panes.UI
+
+        // Set up cross-site proxy
+        const $rdf = UI.rdf
+        $rdf.Fetcher.crossSiteProxyTemplate = document.origin + '/xss/?uri={uri}'
+
+        // Authenticate the user
+        UI.authn.checkUser()
+          .then(function () {
+            // Set up the view for the current subject
+            const kb = UI.store
+            const uri = window.location.href
+            const subject = kb.sym(uri)
+            const outliner = panes.getOutliner(document)
+            outliner.GotoSubject(subject, true, undefined, true, undefined)
+          })
+      })
+    </script>
+</head>
+<body>
+<div class="TabulatorOutline" id="DummyUUID">
+    <table id="outline"></table>
+</div>
+</body>
+</html>

Some files were not shown because too many files changed in this diff