Commit 4d637078 authored by zauberstuhl's avatar zauberstuhl
Browse files

Split template file and handler

parent 455bab78
...@@ -70,7 +70,7 @@ type Uinfo struct { ...@@ -70,7 +70,7 @@ type Uinfo struct {
} }
} }
func authHandler(w http.ResponseWriter, r *http.Request) { func auth_handler(w http.ResponseWriter, r *http.Request) {
db, err := openDatabase() db, err := openDatabase()
if err != nil { if err != nil {
log.Print(err) log.Print(err)
...@@ -81,7 +81,7 @@ func authHandler(w http.ResponseWriter, r *http.Request) { ...@@ -81,7 +81,7 @@ func authHandler(w http.ResponseWriter, r *http.Request) {
userParam := viper.GetString("nginxRewrite") userParam := viper.GetString("nginxRewrite")
if userParam == "" { if userParam == "" {
userParam = "/?user=%s" userParam = "/users/?user=%s"
} }
if codes, ok := r.URL.Query()["code"]; ok { if codes, ok := r.URL.Query()["code"]; ok {
......
#nginxRewrite: "/@%s" #nginxRewrite: "/users/%s"
redirectUrl: http://localhost:8080 redirectUrl: http://localhost:8080
clientID: 1234 clientID: 1234
clientSecret: 123456789 clientSecret: 123456789
......
...@@ -56,8 +56,9 @@ func main() { ...@@ -56,8 +56,9 @@ func main() {
Addr: "0.0.0.0:8080", Addr: "0.0.0.0:8080",
} }
http.HandleFunc("/", handler) http.HandleFunc("/", index_handler)
http.HandleFunc("/auth", authHandler) http.HandleFunc("/users/", user_handler)
http.HandleFunc("/auth", auth_handler)
// assets directory // assets directory
fs := http.FileServer(http.Dir("public")) fs := http.FileServer(http.Dir("public"))
http.Handle("/assets/", http.StripPrefix("/assets/", fs)) http.Handle("/assets/", http.StripPrefix("/assets/", fs))
......
...@@ -34,7 +34,7 @@ type User struct { ...@@ -34,7 +34,7 @@ type User struct {
UpdatedAt time.Time UpdatedAt time.Time
Username string `gorm:"unique_index"` Username string `gorm:"unique_index"`
Token string Token string `gorm:"index"`
TotalBadges int TotalBadges int
TotalFriends int TotalFriends int
...@@ -57,7 +57,7 @@ type Location struct { ...@@ -57,7 +57,7 @@ type Location struct {
ID uint `gorm:"primary_key"` ID uint `gorm:"primary_key"`
CreatedAt time.Time CreatedAt time.Time
UserID uint UserID uint `gorm:"index"`
Lat, Lng float64 Lat, Lng float64
Url, Name, Category, Icon string Url, Name, Category, Icon string
......
html, body {
height: 100%;
}
#mapid {
height: calc(100% - 56px);
height: -o-calc(100% - 56px);
height: -webkit-calc(100% - 56px);
height: -moz-calc(100% - 56px);
}
/* breakpoint-lg is 992px */
@media (max-width: 992px) {
.navbar-text {
display: block;
padding-top: .5rem;
padding-bottom: .5rem;
}
}
<script src="/assets/vendor/js/popper.min.js"></script>
<script src="/assets/vendor/js/bootstrap.min.js"></script>
</body>
</html>
...@@ -12,17 +12,8 @@ ...@@ -12,17 +12,8 @@
<link rel="stylesheet" href="/assets/vendor/css/control.playback.css"/> <link rel="stylesheet" href="/assets/vendor/css/control.playback.css"/>
<link rel="stylesheet" href="/assets/vendor/css/bootstrap.min.css"/> <link rel="stylesheet" href="/assets/vendor/css/bootstrap.min.css"/>
<link rel="stylesheet" href="/assets/vendor/css/leaflet.css"/> <link rel="stylesheet" href="/assets/vendor/css/leaflet.css"/>
<style> <!-- Custom CSS -->
html, body { <link rel="stylesheet" href="/assets/stylesheets/unmappd.css"/>
height: 100%;
}
#mapid {
height: calc(100% - 56px);
height: -o-calc(100% - 56px);
height: -webkit-calc(100% - 56px);
height: -moz-calc(100% - 56px);
}
</style>
</head> </head>
<body> <body>
<header> <header>
...@@ -51,7 +42,7 @@ ...@@ -51,7 +42,7 @@
<span class="navbar-toggler-icon"></span> <span class="navbar-toggler-icon"></span>
</button> </button>
<div class="collapse navbar-collapse" id="navbarNav"> <div class="collapse navbar-collapse" id="navbarNav">
{{if .UserOK}} {{if gt .CurrentUser.ID 0}}
<span class="navbar-text"> <span class="navbar-text">
Checkins {{.CurrentUser.TotalCheckins}}&nbsp; Checkins {{.CurrentUser.TotalCheckins}}&nbsp;
</span> </span>
...@@ -64,15 +55,15 @@ ...@@ -64,15 +55,15 @@
<span class="navbar-text ml-auto"> <span class="navbar-text ml-auto">
Database checkins {{lenLoc .CurrentUser.Locations}} updated at {{.CurrentUser.UpdatedAt.Format "2006-01-02"}} Database checkins {{lenLoc .CurrentUser.Locations}} updated at {{.CurrentUser.UpdatedAt.Format "2006-01-02"}}
</span> </span>
{{end}} {{end}}
<ul class="navbar-nav ml-auto"> <ul class="navbar-nav ml-auto">
{{if or (not .CurrentUser.Locations) (not .UserOK)}} {{if not .CurrentUser.Locations}}
<li class="nav-item"> <li class="nav-item">
<a class="nav-link" href="https://untappd.com/oauth/authenticate?client_id= <a class="nav-link" href="https://untappd.com/oauth/authenticate?client_id=
{{- .Viper.GetString "clientID"}}&response_type=code&redirect_url= {{- .Viper.GetString "clientID"}}&response_type=code&redirect_url=
{{- .Viper.GetString "redirectUrl"}}">Login &amp; pull</a> {{- .Viper.GetString "redirectUrl"}}">Login &amp; pull</a>
</li> </li>
{{else}} {{else}}
<li class="nav-item"> <li class="nav-item">
<script> <script>
function playback() { function playback() {
...@@ -86,115 +77,8 @@ ...@@ -86,115 +77,8 @@
</script> </script>
<a class="nav-link" href="#" onClick="playback()">Playback</a> <a class="nav-link" href="#" onClick="playback()">Playback</a>
</li> </li>
{{end}} {{end}}
</ul> </ul>
</div> </div>
</nav> </nav>
</header> </header>
{{if .CurrentUser.Locations}}
<div id="mapid"></div>
<script src="/assets/vendor/js/leaflet.js"></script>
<script src="/assets/vendor/js/control.trackplayback.js"></script>
<script src="/assets/vendor/js/leaflet.trackplayback.js"></script>
<script>
var mymap = L.map('mapid').setView([49.015,8.269], 2);
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', {
attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
maxZoom: 18,
id: 'mapbox.streets',
accessToken: '{{.Viper.GetString "mapboxKey"}}'
}).addTo(mymap);
{{if .PlaybackOK}}
var trackplayback = new L.TrackPlayBack({{.CurrentUser.Locations.LatLngTimeJSON}}, mymap, {
clockOptions: {
// the default speed
// caculate method: fpstime * Math.pow(2, speed - 1)
// fpstime is the two frame time difference
speed: 20,
// the max speed
maxSpeed: 65
},
// trackPoint options
trackPointOptions: {
isDraw: true,
useCanvas: false,
stroke: false,
color: '#ef0300',
fill: true,
fillColor: '#ef0300',
opacity: 1,
radius: 5
},
trackLineOptions: {
isDraw: false,
},
targetOptions: {
useImg: false,
width: 8,
height: 8,
color: '#000',
fillColor: '#2881c3'
}
});
var trackplaybackControl = L.trackplaybackcontrol(trackplayback);
trackplaybackControl.addTo(mymap);
// remove checkbox
$(".trackplayback-checkbox").hide();
{{else}}
{{range .CurrentUser.Locations}}
var marker = L.marker([{{.Lat}}, {{.Lng}}]).addTo(mymap);
marker.bindPopup(`
<table>
<tr>
<td><img src="{{.Icon}}" alt="{{.Name}}"/></td>
<td><b>{{.Name}}</b></td>
</tr>
<tr>
<td class="text-center pt-2" colspan="2">
Link: <a href="{{.Url}}">{{.Url}}</a><br>
Category: {{.Category}}
</td>
</tr>
</table>
`);
{{end}}
{{end}}
</script>
{{else}}
<main role="main">
<section class="mt-4 text-center">
<div class="container">
<h1 class="jumbotron-heading">Unmappd - Your beer map</h1>
{{if .UserOK}}
{{if ne .CurrentUser.Username ""}}
<object data="/assets/images/waiting.svg" type="image/svg+xml"></object>
<p class="lead text-muted">Your checkins being processed..</p>
{{else}}
<p class="lead text-muted">No data is available for this user! Please login at least once.</p>
<form method="GET" action="https://untappd.com/oauth/authenticate">
<input type="hidden" name="client_id" value="{{.Viper.GetString "clientID"}}"/>
<input type="hidden" name="response_type" value="code"/>
<input type="hidden" name="redirect_url" value="{{.Viper.GetString "redirectUrl"}}"/>
<button class="btn btn-primary" type="submit">Login &amp; pull</button>
</form>
{{end}}
{{else}}
<p class="lead text-muted">Login and display all venues you checked in via Untappd</p>
<p class="text-muted">Latest users:</p>
<ul class="list-group list-group-flush">
{{range .LatestUsers}}
<li class="list-group-item"><a href="{{rwNginx .Username}}">{{.Username}}</a></li>
{{end}}
</ul>
{{end}}
</div>
</section>
</main>
{{end}}
<script src="/assets/vendor/js/popper.min.js"></script>
<script src="/assets/vendor/js/bootstrap.min.js"></script>
</body>
</html>
{{template "header.html" .}}
<main role="main">
<section class="mt-4 text-center">
<div class="container">
<h1 class="jumbotron-heading">Unmappd - Your beer map</h1>
<p class="lead text-muted">Login and display all venues you checked in via Untappd</p>
<p class="text-muted">Latest users:</p>
<ul class="list-group list-group-flush">
{{range .Users}}
<li class="list-group-item"><a href="{{rwNginx .Username}}">{{.Username}}</a></li>
{{end}}
</ul>
</div>
</section>
</main>
{{template "footer.html" .}}
<main role="main">
<section class="mt-4 text-center">
<div class="container">
<h1 class="jumbotron-heading">Unmappd - Your beer map</h1>
{{if gt .CurrentUser.ID 0}}
<object data="/assets/images/waiting.svg" type="image/svg+xml"></object>
<p class="lead text-muted">Your checkins being processed..</p>
{{else}}
<p class="lead text-muted">No data is available for this user! Please login at least once.</p>
<form method="GET" action="https://untappd.com/oauth/authenticate">
<input type="hidden" name="client_id" value="{{.Viper.GetString "clientID"}}"/>
<input type="hidden" name="response_type" value="code"/>
<input type="hidden" name="redirect_url" value="{{.Viper.GetString "redirectUrl"}}"/>
<button class="btn btn-primary" type="submit">Login &amp; pull</button>
</form>
{{end}}
</div>
</section>
</main>
{{template "header.html" .}}
{{if .CurrentUser.Locations}}
<div id="mapid"></div>
<script src="/assets/vendor/js/leaflet.js"></script>
<script src="/assets/vendor/js/control.trackplayback.js"></script>
<script src="/assets/vendor/js/leaflet.trackplayback.js"></script>
<script>
var mymap = L.map('mapid').setView([49.015,8.269], 2);
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', {
attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
maxZoom: 18,
id: 'mapbox.streets',
accessToken: '{{.Viper.GetString "mapboxKey"}}'
}).addTo(mymap);
</script>
{{if .PlaybackOK}}
{{template "map_playback.html" .}}
{{else}}
{{template "map_venues.html" .}}
{{end}}
{{else}}
{{template "loading.html" .}}
{{end}}
{{template "footer.html" .}}
<script>
var trackplayback = new L.TrackPlayBack({{.CurrentUser.Locations.LatLngTimeJSON}}, mymap, {
clockOptions: {
// the default speed
// caculate method: fpstime * Math.pow(2, speed - 1)
// fpstime is the two frame time difference
speed: 20,
// the max speed
maxSpeed: 65
},
// trackPoint options
trackPointOptions: {
isDraw: true,
useCanvas: false,
stroke: false,
color: '#ef0300',
fill: true,
fillColor: '#ef0300',
opacity: 1,
radius: 5
},
trackLineOptions: {
isDraw: false,
},
targetOptions: {
useImg: false,
width: 8,
height: 8,
color: '#000',
fillColor: '#2881c3'
}
});
var trackplaybackControl = L.trackplaybackcontrol(trackplayback);
trackplaybackControl.addTo(mymap);
// remove checkbox
$(".trackplayback-checkbox").hide();
</script>
<script>
{{range .CurrentUser.Locations}}
var marker = L.marker([{{.Lat}}, {{.Lng}}]).addTo(mymap);
marker.bindPopup(`
<table>
<tr>
<td><img src="{{.Icon}}" alt="{{.Name}}"/></td>
<td><b>{{.Name}}</b></td>
</tr>
<tr>
<td class="text-center pt-2" colspan="2">
Link: <a href="{{.Url}}">{{.Url}}</a><br>
Category: {{.Category}}
</td>
</tr>
</table>
`);
{{end}}
</script>
No preview for this file type
...@@ -22,6 +22,7 @@ import ( ...@@ -22,6 +22,7 @@ import (
"fmt" "fmt"
"net/http" "net/http"
"html/template" "html/template"
"io/ioutil"
"log" "log"
"github.com/spf13/viper" "github.com/spf13/viper"
...@@ -29,6 +30,13 @@ import ( ...@@ -29,6 +30,13 @@ import (
"github.com/microcosm-cc/bluemonday" "github.com/microcosm-cc/bluemonday"
) )
type TemplateParams struct{
Viper *viper.Viper
CurrentUser User
Users Users
PlaybackOK bool
}
var TemplateFuncs = map[string]interface{}{ var TemplateFuncs = map[string]interface{}{
"safeHTML": func(text string) template.HTML { "safeHTML": func(text string) template.HTML {
p := bluemonday.UGCPolicy() p := bluemonday.UGCPolicy()
...@@ -41,7 +49,7 @@ var TemplateFuncs = map[string]interface{}{ ...@@ -41,7 +49,7 @@ var TemplateFuncs = map[string]interface{}{
"rwNginx": func(username string) string { "rwNginx": func(username string) string {
nginxRewrite := viper.GetString("nginxRewrite") nginxRewrite := viper.GetString("nginxRewrite")
if nginxRewrite == "" { if nginxRewrite == "" {
nginxRewrite = "/?user=%s" nginxRewrite = "/users/?user=%s"
} }
return fmt.Sprintf(nginxRewrite, username) return fmt.Sprintf(nginxRewrite, username)
}, },
...@@ -50,7 +58,7 @@ var TemplateFuncs = map[string]interface{}{ ...@@ -50,7 +58,7 @@ var TemplateFuncs = map[string]interface{}{
}, },
} }
func handler(w http.ResponseWriter, r *http.Request) { func user_handler(w http.ResponseWriter, r *http.Request) {
db, err := openDatabase() db, err := openDatabase()
if err != nil { if err != nil {
log.Print(err) log.Print(err)
...@@ -58,43 +66,80 @@ func handler(w http.ResponseWriter, r *http.Request) { ...@@ -58,43 +66,80 @@ func handler(w http.ResponseWriter, r *http.Request) {
} }
defer db.Close() defer db.Close()
tmpl := template.Must(
template.New("index.tmpl").
Funcs(TemplateFuncs).ParseFiles("index.tmpl"),
)
var user User var user User
var latestUsers Users
paramUser, userOK := r.URL.Query()["user"] paramUser, userOK := r.URL.Query()["user"]
if userOK { if userOK {
err = db.First(&user, "username = ?", paramUser[0]).Error err = db.First(&user, "username = ?", paramUser[0]).Error
if err == nil { if err == nil {
// first time setup // first time setup
if len(user.Locations) == 0 { if viper.GetBool("worker") && len(user.Locations) == 0 {
go checkin_worker(&user, true) go checkin_worker(&user, true)
} }
} }
} else { } else {
err = db.Order("created_at desc").Limit(5). http.Redirect(w, r, "/", 301)
Find(&latestUsers).Error return
if err != nil {
log.Print(err)
}
} }
tmpl := prepare_templates("map.html")
_, playbackOK := r.URL.Query()["playback"] _, playbackOK := r.URL.Query()["playback"]
if err = tmpl.ExecuteTemplate(w, "index.tmpl", struct{ if err = tmpl.Execute(w, TemplateParams{
Viper *viper.Viper
CurrentUser User
PlaybackOK, UserOK bool
LatestUsers Users
}{
Viper: viper.GetViper(), Viper: viper.GetViper(),
CurrentUser: user, CurrentUser: user,
PlaybackOK: playbackOK, PlaybackOK: playbackOK,
UserOK: userOK,
LatestUsers: latestUsers,
}); err != nil { }); err != nil {
log.Print(err) log.Print(err)
return
} }
} }
func index_handler(w http.ResponseWriter, r *http.Request) {
db, err := openDatabase()
if err != nil {
log.Print(err)
return
}
defer db.Close()
paramUser, userOK := r.URL.Query()["user"]
if userOK {
rwParam := viper.GetString("nginxRewrite")
if rwParam == "" {
rwParam = "/users/?user=%s"
}
http.Redirect(w, r, fmt.Sprintf(rwParam, paramUser[0]), 301)
return
}
var users Users
err = db.Order("created_at desc").
Limit(5).Find(&users).Error
if err != nil {
log.Print(err)
}
tmpl := prepare_templates("index.html")
if err = tmpl.Execute(w, TemplateParams{
Viper: viper.GetViper(),
Users: users,
}); err != nil {
log.Print(err)
return
}
}
func prepare_templates(name string) *template.Template {
files, err := ioutil.ReadDir("templates")
if err != nil {
panic(err.Error())
}
var paths []string
for _, file := range files {
paths = append(paths,
fmt.Sprintf("templates/%s", file.Name()))
}
return template.Must(template.New(name).
Funcs(TemplateFuncs).ParseFiles(paths...))
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment