2019-11-16 16:06:34 +01:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"github.com/gorilla/websocket"
|
|
|
|
"github.com/photoprism/photoprism/internal/config"
|
|
|
|
"github.com/photoprism/photoprism/internal/event"
|
|
|
|
)
|
|
|
|
|
|
|
|
var wsConnection = websocket.Upgrader{}
|
|
|
|
var wsTimeout = 60 * time.Second
|
|
|
|
|
|
|
|
func wsReader(ws *websocket.Conn) {
|
|
|
|
defer ws.Close()
|
|
|
|
|
|
|
|
ws.SetReadLimit(512)
|
|
|
|
ws.SetReadDeadline(time.Now().Add(wsTimeout))
|
|
|
|
ws.SetPongHandler(func(string) error { ws.SetReadDeadline(time.Now().Add(wsTimeout)); return nil })
|
|
|
|
|
|
|
|
for {
|
|
|
|
_, m, err := ws.ReadMessage()
|
|
|
|
if err != nil {
|
|
|
|
break
|
|
|
|
}
|
2019-12-03 12:51:23 +01:00
|
|
|
log.Debugf("websocket: received %d bytes", len(m))
|
2019-11-16 16:06:34 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func wsWriter(ws *websocket.Conn, conf *config.Config) {
|
|
|
|
pingTicker := time.NewTicker(10 * time.Second)
|
2019-12-11 04:12:54 +01:00
|
|
|
s := event.Subscribe("log.*", "notify.*", "index.*", "upload.*", "import.*", "config.*", "count.*")
|
2019-11-16 16:06:34 +01:00
|
|
|
|
|
|
|
defer func() {
|
|
|
|
pingTicker.Stop()
|
|
|
|
event.Unsubscribe(s)
|
|
|
|
ws.Close()
|
|
|
|
}()
|
|
|
|
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-pingTicker.C:
|
|
|
|
ws.SetWriteDeadline(time.Now().Add(10 * time.Second))
|
|
|
|
if err := ws.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
case msg := <-s.Receiver:
|
|
|
|
ws.SetWriteDeadline(time.Now().Add(10 * time.Second))
|
|
|
|
|
|
|
|
if err := ws.WriteJSON(gin.H{"event": msg.Name, "data": msg.Fields}); err != nil {
|
2019-12-02 13:14:01 +01:00
|
|
|
log.Debug(err)
|
2019-11-16 16:06:34 +01:00
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// GET /api/v1/ws
|
|
|
|
func Websocket(router *gin.RouterGroup, conf *config.Config) {
|
|
|
|
router.GET("/ws", func(c *gin.Context) {
|
|
|
|
w := c.Writer
|
|
|
|
r := c.Request
|
|
|
|
|
|
|
|
ws, err := wsConnection.Upgrade(w, r, nil)
|
|
|
|
if err != nil {
|
2019-12-03 12:51:23 +01:00
|
|
|
log.Error(err)
|
2019-11-16 16:06:34 +01:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
defer ws.Close()
|
|
|
|
|
2019-12-03 12:51:23 +01:00
|
|
|
log.Debug("websocket: connected")
|
2019-11-16 16:06:34 +01:00
|
|
|
|
|
|
|
go wsWriter(ws, conf)
|
|
|
|
|
|
|
|
wsReader(ws)
|
|
|
|
})
|
|
|
|
}
|