Use websocket from library

This commit is contained in:
Magnus Åhall 2024-01-07 16:20:21 +01:00
parent ddb49bad13
commit e94ba7a3a9
6 changed files with 19 additions and 85 deletions

2
go.mod
View File

@ -3,7 +3,7 @@ module notes
go 1.21.0 go 1.21.0
require ( require (
git.gibonuddevalla.se/go/webservice v0.2.0 git.gibonuddevalla.se/go/webservice v0.2.2
github.com/google/uuid v1.5.0 github.com/google/uuid v1.5.0
github.com/gorilla/websocket v1.5.0 github.com/gorilla/websocket v1.5.0
github.com/jmoiron/sqlx v1.3.5 github.com/jmoiron/sqlx v1.3.5

27
main.go
View File

@ -60,6 +60,7 @@ func init() { // {{{
VERSION = strings.TrimSpace(string(version)) VERSION = strings.TrimSpace(string(version))
opt := slog.HandlerOptions{} opt := slog.HandlerOptions{}
opt.Level = slog.LevelDebug
logger = slog.New(slog.NewJSONHandler(os.Stdout, &opt)) logger = slog.New(slog.NewJSONHandler(os.Stdout, &opt))
configFilename := os.Getenv("HOME") + "/.config/notes.yaml" configFilename := os.Getenv("HOME") + "/.config/notes.yaml"
@ -79,7 +80,7 @@ func main() { // {{{
} }
logger.Info("application", "version", VERSION) logger.Info("application", "version", VERSION)
service, err = webservice.New(flagConfig, VERSION) service, err = webservice.New(flagConfig, VERSION, logger)
if err != nil { if err != nil {
logger.Error("application", "error", err) logger.Error("application", "error", err)
os.Exit(1) os.Exit(1)
@ -100,7 +101,6 @@ func main() { // {{{
service.Register("/key/retrieve", true, true, keyRetrieve) service.Register("/key/retrieve", true, true, keyRetrieve)
service.Register("/key/create", true, true, keyCreate) service.Register("/key/create", true, true, keyCreate)
service.Register("/key/counter", true, true, keyCounter) service.Register("/key/counter", true, true, keyCounter)
service.Register("/ws", false, false, service.WebsocketHandler)
service.Register("/", false, false, service.StaticHandler) service.Register("/", false, false, service.StaticHandler)
if flagCreateUser { if flagCreateUser {
@ -113,29 +113,6 @@ func main() { // {{{
logger.Error("webserver", "error", err) logger.Error("webserver", "error", err)
os.Exit(1) os.Exit(1)
} }
connectionManager = NewConnectionManager()
go connectionManager.BroadcastLoop()
http.HandleFunc("/css_updated", cssUpdateHandler)
} // }}}
func cssUpdateHandler(w http.ResponseWriter, r *http.Request) { // {{{
logger.Debug("webserver", "css", "updated")
connectionManager.Broadcast(struct {
Ok bool
ID string
Op string
}{Ok: true, Op: "css_reload"})
} // }}}
func websocketHandler(w http.ResponseWriter, r *http.Request) { // {{{
var err error
_, err = connectionManager.NewConnection(w, r)
if err != nil {
logger.Error("websocket", "error", err)
return
}
} // }}} } // }}}
/* /*

View File

@ -19,12 +19,12 @@
"session": "/js/{{ .VERSION }}/session.mjs", "session": "/js/{{ .VERSION }}/session.mjs",
"node": "/js/{{ .VERSION }}/node.mjs", "node": "/js/{{ .VERSION }}/node.mjs",
"key": "/js/{{ .VERSION }}/key.mjs", "key": "/js/{{ .VERSION }}/key.mjs",
"crypto": "/js/{{ .VERSION }}/crypto.mjs" "crypto": "/js/{{ .VERSION }}/crypto.mjs",
"ws": "/_js/{{ .VERSION }}/websocket.mjs"
} }
} }
</script> </script>
<script type="text/javascript" src="/js/{{ .VERSION }}/lib/sjcl.js"></script> <script type="text/javascript" src="/js/{{ .VERSION }}/lib/sjcl.js"></script>
<script type="text/javascript" src="/js/{{ .VERSION }}/lib/css_reload.js"></script>
</head> </head>
<body> <body>

View File

@ -4,17 +4,12 @@ import { h, Component, render, createRef } from 'preact'
import htm from 'htm' import htm from 'htm'
import { Session } from 'session' import { Session } from 'session'
import { Node, NodeUI } from 'node' import { Node, NodeUI } from 'node'
import { Websocket } from 'ws'
const html = htm.bind(h) const html = htm.bind(h)
class App extends Component { class App extends Component {
constructor() {//{{{ constructor() {//{{{
super() super()
this.websocket_uri = `ws://localhost:1371/ws`
this.websocket = null
this.websocket_int_ping = null
this.websocket_int_reconnect = null
//this.wsConnect() // XXX
//this.wsLoop() // XXX
this.session = new Session(this) this.session = new Session(this)
this.session.initialize() this.session.initialize()
@ -25,6 +20,7 @@ class App extends Component {
this.startNode = null this.startNode = null
this.websocketInit()
this.setStartNode() this.setStartNode()
}//}}} }//}}}
render() {//{{{ render() {//{{{
@ -48,45 +44,6 @@ class App extends Component {
` `
}//}}} }//}}}
wsLoop() {//{{{
setInterval(() => {
if (this.websocket === null) {
console.log("wsLoop connect")
this.wsConnect()
}
}, 1000)
}//}}}
wsConnect() {//{{{
this.websocket = new WebSocket(this.websocket_uri)
this.websocket.onopen = evt => this.wsOpen(evt)
this.websocket.onmessage = evt => this.wsMessage(evt)
this.websocket.onerror = evt => this.wsError(evt)
this.websocket.onclose = evt => this.wsClose(evt)
}//}}}
wsOpen() {//{{{
this.setState({ wsConnected: true })
// A ping interval to implement a rudimentary keep-alive.
}//}}}
wsClose() {//{{{
console.log("Lost connection to Notes server")
this.websocket = null
}//}}}
wsError(evt) {//{{{
console.log("websocket error", evt)
this.websocket = null;
}//}}}
wsMessage(evt) {//{{{
let msg = JSON.parse(evt.data)
// Broadcast message
if (msg.ID == '') {
this.broadcastHandler(msg)
} else {
this.msgHandler(msg)
}
}//}}}
responseError({ comm, app, upload }) {//{{{ responseError({ comm, app, upload }) {//{{{
if (comm !== undefined) { if (comm !== undefined) {
comm.text().then(body => alert(body)) comm.text().then(body => alert(body))
@ -146,7 +103,17 @@ class App extends Component {
}) })
}//}}} }//}}}
broadcastHandler(msg) {//{{{ websocketInit() {//{{{
this.websocket = new Websocket()
this.websocket.register('open', ()=>console.log('websocket connected'))
this.websocket.register('close', ()=>console.log('websocket disconnected'))
this.websocket.register('error', msg=>console.log(msg))
this.websocket.register('message', this.websocketMessage)
this.websocket.start()
}//}}}
websocketMessage(data) {//{{{
const msg = JSON.parse(data)
switch (msg.Op) { switch (msg.Op) {
case 'css_reload': case 'css_reload':
refreshCSS() refreshCSS()

View File

@ -1,10 +0,0 @@
function refreshCSS() {
let links = document.getElementsByTagName('link')
Array.from(links).forEach(l=>{
if (l.rel == 'stylesheet' && !l.hasAttribute('x-no-reload')) {
let cache = Math.floor(Math.random()*100000)
l.href = l.href.replace(/\?.*/, '') + `?cache=${cache}`
console.log(l.href)
}
})
}

View File

@ -8,7 +8,7 @@ do
clear clear
if make -j12; then if make -j12; then
echo -e "\n\e[32;1mOK!\e[0m" echo -e "\n\e[32;1mOK!\e[0m"
curl -s http://notes.lan:1371/css_updated curl -s http://notes.lan:1371/_ws/css_update
sleep 1 sleep 1
clear clear
fi fi