notfall/main.go

102 lines
2.1 KiB
Go

package main
import (
_ "embed"
"encoding/json"
"github.com/sms77io/go-client/sms77api"
"html/template"
"net/http"
"os"
"time"
)
var lastData map[string]interface{}
//go:embed notfall.tmpl
var templateContent []byte
var active = false
var activeSince time.Time
var getData = false
func main() {
http.HandleFunc("/owntrack", func(writer http.ResponseWriter, request *http.Request) {
var p map[string]interface{}
err := json.NewDecoder(request.Body).Decode(&p)
if err != nil {
writer.WriteHeader(http.StatusInternalServerError)
return
}
if p["_type"] == "location"{
lastData = p
}
getData = true
writer.Write([]byte("[]"))
})
http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
templ := template.Must(template.New("page").Parse(string(templateContent)))
templ.Execute(writer, map[string]interface{}{
})
})
http.HandleFunc("/activate", func(writer http.ResponseWriter, request *http.Request) {
if active == true {
return
}
var klient = sms77api.New(sms77api.Options{
ApiKey: os.Getenv("sms77key"),
})
sms := sms77api.SmsBaseParams{
Text: "Jemand greift auf deine Position zu",
To: "004917655424258",
From: "Notfall-Portal",
}
_, err := klient.Sms.Text(sms77api.SmsTextParams{
SmsBaseParams: sms,
Details: false,
ReturnMessageId: false,
})
if err != nil {
panic(err)
}
active = true
activeSince = time.Now()
http.Redirect(writer, request, "/", http.StatusSeeOther)
})
http.HandleFunc("/json", func(writer http.ResponseWriter, request *http.Request) {
if getData == false || active == false {
writer.WriteHeader(http.StatusInternalServerError)
return
}
diff := time.Now().Sub(activeSince)
if diff.Minutes() > 2 {
active = false
writer.WriteHeader(http.StatusInternalServerError)
return
}
data := make(map[string]interface{})
data["lat"] = lastData["lat"]
data["lon"] = lastData["lon"]
data["tst"] = lastData["tst"]
data["acc"] = lastData["acc"]
r, err := json.Marshal(data)
if err != nil {
panic(err)
}
writer.Write(r)
})
http.ListenAndServe(":8080", nil)
}