chat.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package controllers
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "github.com/owncast/owncast/core/chat"
  6. "github.com/owncast/owncast/core/user"
  7. "github.com/owncast/owncast/router/middleware"
  8. log "github.com/sirupsen/logrus"
  9. )
  10. // ExternalGetChatMessages gets all of the chat messages.
  11. func ExternalGetChatMessages(integration user.ExternalAPIUser, w http.ResponseWriter, r *http.Request) {
  12. middleware.EnableCors(w)
  13. GetChatMessages(w, r)
  14. }
  15. // GetChatMessages gets all of the chat messages.
  16. func GetChatMessages(w http.ResponseWriter, r *http.Request) {
  17. w.Header().Set("Content-Type", "application/json")
  18. switch r.Method {
  19. case http.MethodGet:
  20. messages := chat.GetChatHistory()
  21. if err := json.NewEncoder(w).Encode(messages); err != nil {
  22. log.Debugln(err)
  23. }
  24. default:
  25. w.WriteHeader(http.StatusNotImplemented)
  26. if err := json.NewEncoder(w).Encode(j{"error": "method not implemented (PRs are accepted)"}); err != nil {
  27. InternalErrorHandler(w, err)
  28. }
  29. }
  30. }
  31. // RegisterAnonymousChatUser will register a new user.
  32. func RegisterAnonymousChatUser(w http.ResponseWriter, r *http.Request) {
  33. if r.Method != POST {
  34. WriteSimpleResponse(w, false, r.Method+" not supported")
  35. return
  36. }
  37. type registerAnonymousUserRequest struct {
  38. DisplayName string `json:"displayName"`
  39. }
  40. type registerAnonymousUserResponse struct {
  41. ID string `json:"id"`
  42. AccessToken string `json:"accessToken"`
  43. DisplayName string `json:"displayName"`
  44. }
  45. decoder := json.NewDecoder(r.Body)
  46. var request registerAnonymousUserRequest
  47. if err := decoder.Decode(&request); err != nil { //nolint
  48. // this is fine. register a new user anyway.
  49. }
  50. if request.DisplayName == "" {
  51. request.DisplayName = r.Header.Get("X-Forwarded-User")
  52. }
  53. newUser, err := user.CreateAnonymousUser(request.DisplayName)
  54. if err != nil {
  55. WriteSimpleResponse(w, false, err.Error())
  56. return
  57. }
  58. response := registerAnonymousUserResponse{
  59. ID: newUser.ID,
  60. AccessToken: newUser.AccessToken,
  61. DisplayName: newUser.DisplayName,
  62. }
  63. w.Header().Set("Content-Type", "application/json")
  64. middleware.DisableCache(w)
  65. WriteResponse(w, response)
  66. }