package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/matrix-org/gomatrix"
)
type Status struct {
FuzIsOpen bool `json:"fuzIsOpen"`
LastSeenAsOpen bool `json:"lastSeenAsOpen"`
LastSeen time.Time `json:"lastSeen"`
LastOpened time.Time `json:"lastOpened"`
LastClosed time.Time `json:"lastClosed"`
ProcessUptime string `json:"processUptime"`
}
type Config struct {
PORT string
MATRIXROOM string
MATRIXOPENINGMESSAGE string
MATRIXCLOSINGMESSAGE string
MATRIXACCESSTOKEN string
MATRIXUSERNAME string
ESPUSERNAME string
ESPPASSWORD string
}
const (
dbPath = "./.data/data.json"
defaultClosingTimeout = 5 * time.Minute
)
var (
status Status
config = Config{
PORT: "8080",
}
startTime = time.Now()
imgs = map[bool]string{
// https://www.iconfinder.com/icons/1871431/online_open_shop_shopping_sign_icon
// formerly https://www.flaticon.com/free-icon/open_1234189, maybe try https://flaticons.net/customize.php?dir=Miscellaneous&icon=Open.png without attribution
true: ``,
// https://www.iconfinder.com/icons/1871435/closed_online_shop_shopping_sign_icon
// formerly https://www.flaticon.com/free-icon/closed_1234190, maybe try https://flaticons.net/customize.php?dir=Miscellaneous&icon=Closed.png without attribution
false: ``,
}
db *os.File
matrix *gomatrix.Client
)
func init() {
port := os.Getenv("PORT")
if val, _ := strconv.Atoi(port); val > 0 {
config.PORT = port
}
config.MATRIXUSERNAME = os.Getenv("MATRIXUSERNAME")
config.MATRIXACCESSTOKEN = os.Getenv("MATRIXACCESSTOKEN")
config.MATRIXROOM = os.Getenv("MATRIXROOM")
config.MATRIXOPENINGMESSAGE = os.Getenv("MATRIXOPENINGMESSAGE")
config.MATRIXCLOSINGMESSAGE = os.Getenv("MATRIXCLOSINGMESSAGE")
config.ESPUSERNAME = os.Getenv("ESPUSERNAME")
config.ESPPASSWORD = os.Getenv("ESPPASSWORD")
if config.MATRIXUSERNAME == "" {
panic("MATRIXUSERNAME is empty")
}
if config.MATRIXACCESSTOKEN == "" {
panic("MATRIXACCESSTOKEN is empty")
}
var err error
matrix, err = gomatrix.NewClient(fmt.Sprintf("https://%s", config.MATRIXUSERNAME[strings.Index(config.MATRIXUSERNAME, ":")+1:]), config.MATRIXUSERNAME, config.MATRIXACCESSTOKEN)
if err != nil {
panic(fmt.Sprintf("error creating matrix client: %s", err))
}
if _, err := matrix.GetOwnStatus(); err != nil { // a way to quickly check if access token is valid
panic(fmt.Sprintf("error getting matrix status: %s", err))
}
if config.MATRIXROOM == "" {
panic("MATRIXROOM is empty")
}
if config.MATRIXOPENINGMESSAGE == "" {
panic("MATRIXOPENINGMESSAGE is empty")
}
if config.MATRIXCLOSINGMESSAGE == "" {
panic("MATRIXCLOSINGMESSAGE is empty")
}
if config.ESPUSERNAME == "" {
panic("ESPUSERNAME is empty")
}
if config.ESPPASSWORD == "" {
panic("ESPPASSWORD is empty")
}
err = os.MkdirAll(filepath.Dir(dbPath), 0755)
if err != nil {
panic(err)
}
db, err = os.OpenFile(dbPath, os.O_RDWR|os.O_CREATE, 0600)
if err != nil && !os.IsNotExist(err) {
panic(err)
}
err = json.NewDecoder(db).Decode(&status)
if err != nil {
fmt.Println("error unmarshalling db:", err)
}
}
func updateUptime() {
for range time.Tick(time.Second) {
status.ProcessUptime = time.Since(startTime).Truncate(time.Second).String()
}
}
func checkClosure() {
time.Sleep(time.Minute) // give some time for presence button to show up
for {
if status.LastSeen.Add(defaultClosingTimeout).Before(time.Now()) && status.LastClosed.Before(status.LastSeen) {
// the Fuz is newly closed, notify on matrix and write file to survive reboot
fmt.Println("the Fuz is newly closed, notify on matrix and write file to survive reboot")
msg := config.MATRIXCLOSINGMESSAGE
if !status.FuzIsOpen {
msg = fmt.Sprintf("%s : passage bref", msg)
}
_, err := matrix.SendText(config.MATRIXROOM, msg)
if err != nil {
fmt.Println("err:", err)
time.Sleep(10 * time.Second)
continue
}
status.LastClosed = time.Now()
status.FuzIsOpen = false
db.Truncate(0)
db.Seek(0, 0)
e := json.NewEncoder(db)
e.SetIndent("", " ")
e.Encode(status)
}
time.Sleep(10 * time.Second)
}
}
func rootHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
fmt.Fprintf(w, `Fuz presence button public API
This API provides the current opening status of the hackerspace. This server also posts messages on Matrix to notify when the space opens and closes.
Usage:
/ Shows help
/api Serves some JSON with lax CORS headers to get the current opening status programatically. The properties are the following:
* fuzIsOpen: (boolean) reflects if the space is currently open
* lastSeenAsOpen: (boolean) reflects if the last ping by the ESP was after being pushed (space officially opened)
* lastSeen: (date) last ESP ping timestamp
* lastOpened: (date) last space opening timestamp
* lastClosed: (date) last space closing timestamp
* processUptime: (duration) API process uptime
/img Serves an svg image showing if the space is open or closed.
/status Private endpoint used by the ESP (physical button) to regularly ping/update the opening status.
Source code: https://github.com/Lomanic/presence-button-web
Source code mirror: https://git.interhacker.space/Lomanic/presence-button-web
Documentation: https://wiki.fuz.re/doku.php?id=projets:fuz:presence_button`)
}
func apiHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
e := json.NewEncoder(w)
e.SetIndent("", " ")
e.Encode(status)
}
func imgHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "image/svg+xml")
w.Header().Set("Cache-Control", "no-store, no-cache, must-revalidate, proxy-revalidate")
w.Header().Set("Pragma", "no-cache")
w.Header().Set("Expires", "0")
fmt.Fprintf(w, imgs[status.FuzIsOpen])
}
func statusHandler(w http.ResponseWriter, r *http.Request) {
user, pass, ok := r.BasicAuth()
fmt.Printf("status notification by button... ")
if !ok || user != config.ESPUSERNAME || pass != config.ESPPASSWORD {
fmt.Printf("bad authentication: user:%v pass:%v\n", user, pass)
w.Header().Set("WWW-Authenticate", `Basic realm="Authentication required"`)
http.Error(w, "Authentication required", 401)
return
}
q := r.URL.Query()
fuzIsOpen := q.Get("fuzisopen") == "1"
fmt.Printf("button pushed: %v\n", fuzIsOpen)
status.FuzIsOpen = fuzIsOpen
status.LastSeenAsOpen = fuzIsOpen
status.LastSeen = time.Now()
fmt.Fprintf(w, "OK")
db.Truncate(0)
db.Seek(0, 0)
e := json.NewEncoder(db)
e.SetIndent("", " ")
e.Encode(status)
if status.FuzIsOpen && (status.LastOpened.Equal(status.LastClosed) || status.LastOpened.Before(status.LastClosed)) {
// the Fuz is newly opened, notify on matrix and write file to survive reboot
fmt.Println("the Fuz is newly opened, notify on matrix and write file to survive reboot")
_, err := matrix.SendText(config.MATRIXROOM, config.MATRIXOPENINGMESSAGE)
if err != nil {
fmt.Println("err:", err)
return
}
status.LastOpened = time.Now()
db.Truncate(0)
db.Seek(0, 0)
e := json.NewEncoder(db)
e.SetIndent("", " ")
e.Encode(status)
}
}
func syncMatrix() {
syncer := matrix.Syncer.(*gomatrix.DefaultSyncer)
syncer.OnEventType("m.room.message", func(ev *gomatrix.Event) {
if ev.Sender != matrix.UserID {
matrix.MarkRead(ev.RoomID, ev.ID)
}
})
go func() { // set online status every 15 seconds
for {
if err := matrix.SetStatus("online", "up and running"); err != nil {
fmt.Println("error setting matrix status:", err)
}
time.Sleep(15 * time.Second)
}
}()
for {
if err := matrix.Sync(); err != nil {
fmt.Println("error syncing with matrix:", err)
}
}
}
func main() {
go updateUptime()
go checkClosure()
go syncMatrix()
http.HandleFunc("/", rootHandler)
http.HandleFunc("/api", apiHandler)
http.HandleFunc("/img", imgHandler)
http.HandleFunc("/status", statusHandler)
log.Fatal(http.ListenAndServe(":"+config.PORT, nil))
}