package api import ( "encoding/json" "net/http" "strings" "time" "github.com/ponzischeme89/memby/server/internal/cache" "github.com/ponzischeme89/memby/server/internal/emby" "github.com/ponzischeme89/memby/server/internal/store" ) type loginRequest struct { Username string `json:"username"` Password string `json:"password"` DeviceID string `json:"deviceId"` DeviceName string `json:"deviceName"` } type loginResponse struct { Token string `json:"token"` UserID string `json:"userId"` Username string `json:"username"` ServerID string `json:"serverId"` } type deviceSessionResponse struct { DeviceID string `json:"deviceId"` DeviceName string `json:"deviceName"` ClientVersion string `json:"clientVersion,omitempty"` LastSeenAt time.Time `json:"lastSeenAt"` Current bool `json:"current"` } type renameDeviceRequest struct { DeviceName string `json:"deviceName"` } // handleLogin exchanges Emby credentials for a gateway token. // // The Emby access token stays here: the TV only ever holds the gateway token, so // revoking a device is a DELETE in Postgres rather than an Emby-side cleanup. func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) { var req loginRequest if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 8<<10)).Decode(&req); err != nil { writeError(w, http.StatusBadRequest, "malformed request body") return } req.Username = strings.TrimSpace(req.Username) if req.Username == "" { writeError(w, http.StatusBadRequest, "username is required") return } if req.DeviceID == "" { req.DeviceID = "memby-tv" } req.DeviceName = strings.TrimSpace(req.DeviceName) if req.DeviceName == "" { // Compatibility for APKs released before device naming. New clients require an // editable name in their UI, but an older TV must still be able to sign in while // the household rollout is in progress. req.DeviceName = "Memby TV" } if len([]rune(req.DeviceName)) > 80 { writeError(w, http.StatusBadRequest, "device name is too long") return } auth, err := s.emby.Authenticate( r.Context(), req.Username, req.Password, req.DeviceID, req.DeviceName, ) if err != nil { // Never echo Emby's body here: a failed sign-in is the one place a wrong // password could be reflected back. s.log.Warn("emby authentication failed", "username", req.Username) writeError(w, http.StatusUnauthorized, "sign-in failed") return } token, err := newToken() if err != nil { s.log.Error("token generation failed", "error", err) writeError(w, http.StatusInternalServerError, "could not issue a token") return } sess := store.Session{ TokenHash: hashToken(token), EmbyUserID: auth.User.ID, EmbyToken: auth.AccessToken, Username: auth.User.Name, ServerID: auth.ServerID, DeviceID: req.DeviceID, DeviceName: req.DeviceName, ClientVersion: clientVersion(r), ClientProtocol: clientProtocol(r), ClientCapabilities: clientCapabilities(r), } if sess.Username == "" { sess.Username = req.Username } replacedHash, err := s.store.CreateSession(r.Context(), sess) if err != nil { _ = s.emby.Logout(r.Context(), emby.Credentials{ UserID: auth.User.ID, Token: auth.AccessToken, DeviceID: req.DeviceID, DeviceName: req.DeviceName, }) s.log.Error("session persist failed", "error", err) writeError(w, http.StatusInternalServerError, "could not start a session") return } if len(replacedHash) > 0 { _ = s.cache.Delete(r.Context(), cache.SessionKey(hexHash(replacedHash))) } if s.forYou != nil { s.forYou.MarkDirty(r.Context(), sess) s.forYou.RefreshAsync(sess, false) } writeJSON(w, http.StatusOK, loginResponse{ Token: token, UserID: sess.EmbyUserID, Username: sess.Username, ServerID: sess.ServerID, }) } func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request, sess store.Session) { if err := s.store.DeleteSession(r.Context(), sess.TokenHash); err != nil { s.log.Error("session delete failed", "error", err) } _ = s.cache.Delete(r.Context(), cache.SessionKey(hexHash(sess.TokenHash))) _ = s.cache.InvalidateUser(r.Context(), sess.EmbyUserID) w.WriteHeader(http.StatusNoContent) } // handleSession lets the TV confirm a stored token is still good before rendering. func (s *Server) handleSession(w http.ResponseWriter, _ *http.Request, sess store.Session) { writeJSON(w, http.StatusOK, loginResponse{ UserID: sess.EmbyUserID, Username: sess.Username, ServerID: sess.ServerID, }) } func (s *Server) handleDevices(w http.ResponseWriter, r *http.Request, current store.Session) { sessions, err := s.store.SessionsForUser(r.Context(), current.EmbyUserID) if err != nil { s.log.Error("device list failed", "error", err) writeError(w, http.StatusInternalServerError, "could not list devices") return } devices := make([]deviceSessionResponse, 0, len(sessions)) for _, sess := range sessions { devices = append(devices, deviceSessionResponse{ DeviceID: sess.DeviceID, DeviceName: sess.DeviceName, ClientVersion: sess.ClientVersion, LastSeenAt: sess.LastSeenAt, Current: string(sess.TokenHash) == string(current.TokenHash), }) } writeJSON(w, http.StatusOK, map[string]any{"devices": devices}) } func (s *Server) handleDeleteDevice(w http.ResponseWriter, r *http.Request, current store.Session) { deviceID := strings.TrimSpace(r.PathValue("deviceID")) if deviceID == "" { writeError(w, http.StatusBadRequest, "device id is required") return } if deviceID == current.DeviceID { writeError(w, http.StatusBadRequest, "sign out to remove the current device") return } tokenHash, err := s.store.DeleteUserDevice(r.Context(), current.EmbyUserID, deviceID) if err == store.ErrNotFound { writeError(w, http.StatusNotFound, "device not found") return } if err != nil { s.log.Error("device revoke failed", "error", err) writeError(w, http.StatusInternalServerError, "could not remove device") return } _ = s.cache.Delete(r.Context(), cache.SessionKey(hexHash(tokenHash))) w.WriteHeader(http.StatusNoContent) } func (s *Server) handleRenameDevice(w http.ResponseWriter, r *http.Request, current store.Session) { deviceID := strings.TrimSpace(r.PathValue("deviceID")) var req renameDeviceRequest if deviceID == "" || json.NewDecoder(http.MaxBytesReader(w, r.Body, 2<<10)).Decode(&req) != nil { writeError(w, http.StatusBadRequest, "device id and name are required") return } req.DeviceName = strings.TrimSpace(req.DeviceName) if req.DeviceName == "" { writeError(w, http.StatusBadRequest, "device name is required") return } if len([]rune(req.DeviceName)) > 80 { writeError(w, http.StatusBadRequest, "device name is too long") return } if err := s.store.RenameUserDevice(r.Context(), current.EmbyUserID, deviceID, req.DeviceName); err == store.ErrNotFound { writeError(w, http.StatusNotFound, "device not found") return } else if err != nil { s.log.Error("device rename failed", "error", err) writeError(w, http.StatusInternalServerError, "could not rename device") return } w.WriteHeader(http.StatusNoContent) }