2018-11-06 20:40:03 +00:00
|
|
|
package sse
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
|
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
|
|
|
"github.com/aerogo/aero"
|
|
|
|
"github.com/animenotifier/notify.moe/utils"
|
|
|
|
)
|
|
|
|
|
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.
|
|
|
|
func Events(ctx *aero.Context) string {
|
|
|
|
user := utils.GetUser(ctx)
|
|
|
|
|
|
|
|
if user == nil {
|
|
|
|
return ctx.Error(http.StatusUnauthorized, "Not logged in")
|
|
|
|
}
|
|
|
|
|
|
|
|
fmt.Println(user.Nick, "receiving live events")
|
2018-11-07 07:49:49 +00:00
|
|
|
stream := aero.NewEventStream()
|
|
|
|
user.AddEventStream(stream)
|
2018-11-06 20:40:03 +00:00
|
|
|
|
|
|
|
go func() {
|
|
|
|
defer fmt.Println(user.Nick, "disconnected, stop sending events")
|
2018-11-08 11:30:36 +00:00
|
|
|
defer user.RemoveEventStream(stream)
|
2018-11-06 20:40:03 +00:00
|
|
|
|
2018-11-07 07:49:49 +00:00
|
|
|
stream.Events <- &aero.Event{
|
|
|
|
Name: "etag",
|
|
|
|
Data: struct {
|
|
|
|
URL string `json:"url"`
|
|
|
|
ETag string `json:"etag"`
|
|
|
|
}{
|
|
|
|
URL: "/scripts",
|
|
|
|
ETag: scriptsETag,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
stream.Events <- &aero.Event{
|
|
|
|
Name: "etag",
|
|
|
|
Data: struct {
|
|
|
|
URL string `json:"url"`
|
|
|
|
ETag string `json:"etag"`
|
|
|
|
}{
|
|
|
|
URL: "/styles",
|
|
|
|
ETag: stylesETag,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
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
|
|
|
}
|