route_feeds.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // SPDX-FileCopyrightText: Adam Evyčędo
  2. //
  3. // SPDX-License-Identifier: AGPL-3.0-or-later
  4. package server
  5. import (
  6. "apiote.xyz/p/szczanieckiej/api"
  7. "apiote.xyz/p/szczanieckiej/config"
  8. "apiote.xyz/p/szczanieckiej/traffic"
  9. "errors"
  10. "net/http"
  11. "time"
  12. "apiote.xyz/p/gott/v2"
  13. "git.sr.ht/~sircmpwn/go-bare"
  14. )
  15. type FeedsHandlerVars struct {
  16. HandlerVars
  17. feedInfos map[string]traffic.FeedInfo
  18. lastUpdates map[string]time.Time
  19. }
  20. func getFeedInfos(v AbstractHandlerVars) (AbstractHandlerVars, error) {
  21. vv := v.(*FeedsHandlerVars)
  22. feedInfos, lastUpdates, err := traffic.GetFeedInfos(v.getTraffic(), v.getConfig())
  23. vv.feedInfos = feedInfos
  24. vv.lastUpdates = lastUpdates
  25. return vv, err
  26. }
  27. func makeFeedsResponse(v AbstractHandlerVars) (AbstractHandlerVars, error) {
  28. vv := v.(*FeedsHandlerVars)
  29. response, err := api.MakeFeedsResponse(vv.feedInfos, vv.lastUpdates, v.getAccept(), v.getPreferredLanguages())
  30. v.setResponse(response)
  31. if err != nil && errors.Is(err, api.AcceptError) {
  32. err = ServerError{
  33. code: http.StatusNotAcceptable,
  34. }
  35. }
  36. return vv, err
  37. }
  38. func marshalFeedsResponse(v AbstractHandlerVars) (AbstractHandlerVars, error) {
  39. r := v.getResponse().(api.FeedsResponse)
  40. bytes, err := bare.Marshal(&r)
  41. v.setResponseBytes(bytes)
  42. return v, err
  43. }
  44. func handleFeeds(w http.ResponseWriter, r *http.Request, cfg config.Config, t *traffic.Traffic, accept map[uint]struct{}) error {
  45. handlerVars := &FeedsHandlerVars{
  46. HandlerVars: HandlerVars{
  47. w: w,
  48. r: r,
  49. t: t,
  50. c: cfg,
  51. a: accept,
  52. },
  53. }
  54. result := gott.R[AbstractHandlerVars]{
  55. S: handlerVars,
  56. }
  57. result = result.
  58. Map(getAcceptLanguage).
  59. Bind(parseAcceptLanguage).
  60. Bind(getFeedInfos).
  61. Bind(makeFeedsResponse).
  62. Bind(marshalFeedsResponse).
  63. Tee(writeResponse)
  64. return result.E
  65. }