61 lines
1.2 KiB
Go
Raw Normal View History

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