2018-11-06 20:40:03 +00:00
|
|
|
package sse
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
|
2019-11-17 07:59:34 +00:00
|
|
|
"github.com/aerogo/aero"
|
2021-11-20 11:52:08 +00:00
|
|
|
"github.com/aerogo/aero/event"
|
2019-11-17 07:59:34 +00:00
|
|
|
"github.com/animenotifier/notify.moe/arn"
|
2018-11-07 07:49:49 +00:00
|
|
|
"github.com/animenotifier/notify.moe/components/css"
|
|
|
|
"github.com/animenotifier/notify.moe/components/js"
|
2018-11-06 20:40:03 +00:00
|
|
|
)
|
|
|
|
|
2018-11-07 07:49:49 +00:00
|
|
|
var (
|
|
|
|
scriptsETag = aero.ETagString(js.Bundle())
|
|
|
|
stylesETag = aero.ETagString(css.Bundle())
|
|
|
|
)
|
|
|
|
|
2018-11-06 20:40:03 +00:00
|
|
|
// Events streams server events to the client.
|
2019-06-01 04:55:49 +00:00
|
|
|
func Events(ctx aero.Context) error {
|
2019-11-17 07:59:34 +00:00
|
|
|
user := arn.GetUserFromContext(ctx)
|
2018-11-06 20:40:03 +00:00
|
|
|
|
|
|
|
if user == nil {
|
|
|
|
return ctx.Error(http.StatusUnauthorized, "Not logged in")
|
|
|
|
}
|
|
|
|
|
2021-11-20 11:52:08 +00:00
|
|
|
stream := event.NewStream()
|
2018-11-07 07:49:49 +00:00
|
|
|
user.AddEventStream(stream)
|
2018-11-06 20:40:03 +00:00
|
|
|
|
|
|
|
go func() {
|
2018-11-08 11:30:36 +00:00
|
|
|
defer user.RemoveEventStream(stream)
|
2018-11-06 20:40:03 +00:00
|
|
|
|
2019-03-31 07:46:44 +00:00
|
|
|
// Send the ETag for the scripts
|
2021-11-20 11:52:08 +00:00
|
|
|
stream.Events <- event.New("etag", struct {
|
|
|
|
URL string `json:"url"`
|
|
|
|
ETag string `json:"etag"`
|
|
|
|
}{
|
|
|
|
URL: "/scripts",
|
|
|
|
ETag: scriptsETag,
|
|
|
|
})
|
2018-11-07 07:49:49 +00:00
|
|
|
|
2019-03-31 07:46:44 +00:00
|
|
|
// Send the ETag for the styles
|
2021-11-20 11:52:08 +00:00
|
|
|
stream.Events <- event.New("etag", struct {
|
|
|
|
URL string `json:"url"`
|
|
|
|
ETag string `json:"etag"`
|
|
|
|
}{
|
|
|
|
URL: "/styles",
|
|
|
|
ETag: stylesETag,
|
|
|
|
})
|
2018-11-07 07:49:49 +00:00
|
|
|
|
2019-03-31 07:46:44 +00:00
|
|
|
// Wait until the user closes the tab or disconnects
|
2018-11-08 11:30:36 +00:00
|
|
|
<-stream.Closed
|
2018-11-06 20:40:03 +00:00
|
|
|
}()
|
|
|
|
|
2018-11-07 07:49:49 +00:00
|
|
|
return ctx.EventStream(stream)
|
2018-11-06 20:40:03 +00:00
|
|
|
}
|