messaging.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. package handlers
  2. import (
  3. "context"
  4. "crypto/rand"
  5. "encoding/binary"
  6. "fmt"
  7. "log/slog"
  8. "net/http"
  9. "time"
  10. "github.com/mk6i/open-oscar-server/server/webapi/types"
  11. "github.com/mk6i/open-oscar-server/state"
  12. "github.com/mk6i/open-oscar-server/wire"
  13. )
  14. // ICBMService defines methods for ICBM operations
  15. type ICBMService interface {
  16. ChannelMsgToHost(ctx context.Context, instance *state.SessionInstance, inFrame wire.SNACFrame, inBody wire.SNAC_0x04_0x06_ICBMChannelMsgToHost) (*wire.SNACMessage, error)
  17. ClientEvent(ctx context.Context, instance *state.SessionInstance, inFrame wire.SNACFrame, inBody wire.SNAC_0x04_0x14_ICBMClientEvent) error
  18. }
  19. // MessagingHandler handles Web AIM API messaging endpoints
  20. type MessagingHandler struct {
  21. SessionManager *state.WebAPISessionManager
  22. ICBMService ICBMService
  23. LocateService LocateService
  24. FeedbagService FeedbagService
  25. Logger *slog.Logger
  26. }
  27. // queryOrFormParam returns a request parameter from the query string or, for POST
  28. // requests, from application/x-www-form-urlencoded body fields. The Web AIM client
  29. // sends t/offlineIM/etc. on the query string and puts message in the POST body.
  30. func queryOrFormParam(r *http.Request, key string) string {
  31. if v := r.URL.Query().Get(key); v != "" {
  32. return v
  33. }
  34. if r.Method == http.MethodPost {
  35. if err := r.ParseForm(); err == nil {
  36. return r.FormValue(key)
  37. }
  38. }
  39. return ""
  40. }
  41. // SendIM handles the /im/sendIM endpoint for sending instant messages
  42. func (h *MessagingHandler) SendIM(w http.ResponseWriter, r *http.Request, sess *state.WebAPISession) {
  43. ctx := r.Context()
  44. // Parse parameters
  45. recipient := queryOrFormParam(r, "t")
  46. if recipient == "" {
  47. h.sendErrorResponse(w, http.StatusBadRequest, "missing required parameter: t (recipient)")
  48. return
  49. }
  50. message := queryOrFormParam(r, "message")
  51. if message == "" {
  52. h.sendErrorResponse(w, http.StatusBadRequest, "missing required parameter: message")
  53. return
  54. }
  55. // Parse optional parameters
  56. autoResponse := queryOrFormParam(r, "autoResponse") == "1"
  57. // Generate message cookie
  58. var cookie [8]byte
  59. if _, err := rand.Read(cookie[:]); err != nil {
  60. h.Logger.ErrorContext(ctx, "failed to generate message cookie", "error", err)
  61. h.sendErrorResponse(w, http.StatusInternalServerError, "internal server error")
  62. return
  63. }
  64. cookieUint64 := binary.BigEndian.Uint64(cookie[:])
  65. // Create message ID for response (UUID format like working implementation)
  66. // Using the cookie bytes to generate a UUID-like string
  67. messageID := fmt.Sprintf("%08x-%04x-%04x-%04x-%012x",
  68. binary.BigEndian.Uint32(cookie[:4]),
  69. binary.BigEndian.Uint16(cookie[4:6]),
  70. binary.BigEndian.Uint16(cookie[6:8]),
  71. binary.BigEndian.Uint16([]byte{0x80, 0x00}), // Version bits
  72. time.Now().UnixNano()&0xffffffffffff)
  73. now := float64(time.Now().Unix())
  74. nowSec := time.Now().Unix()
  75. // The client sends t as the normalized aimId it keys the conversation by, so
  76. // it is never a source of display names.
  77. recipientIdent := state.NewIdentScreenName(recipient)
  78. sess.AddStoredIM(recipientIdent.String(), sess.ScreenName.IdentScreenName().String(), message, messageID, nowSec)
  79. // Recipient is online, deliver message
  80. clientIM := wire.SNAC_0x04_0x06_ICBMChannelMsgToHost{
  81. Cookie: cookieUint64,
  82. ChannelID: wire.ICBMChannelIM,
  83. ScreenName: recipient,
  84. TLVRestBlock: wire.TLVRestBlock{},
  85. }
  86. // Add message data
  87. frags, err := wire.ICBMFragmentList(message)
  88. if err != nil {
  89. h.sendErrorResponse(w, http.StatusInternalServerError, "failed to send message")
  90. return
  91. }
  92. clientIM.Append(wire.NewTLVBE(wire.ICBMTLVAOLIMData, frags))
  93. // Add auto-response flag if applicable
  94. if autoResponse {
  95. clientIM.Append(wire.NewTLVBE(wire.ICBMTLVAutoResponse, []byte{}))
  96. }
  97. frame := wire.SNACFrame{
  98. FoodGroup: wire.ICBM,
  99. SubGroup: wire.ICBMChannelMsgToHost,
  100. RequestID: wire.ReqIDFromServer,
  101. }
  102. resp, err := h.ICBMService.ChannelMsgToHost(r.Context(), sess.OSCARSession, frame, clientIM)
  103. if err != nil {
  104. h.sendErrorResponse(w, http.StatusInternalServerError, "failed to send message")
  105. return
  106. }
  107. if resp != nil {
  108. switch {
  109. case resp.Frame.FoodGroup == wire.ICBM && resp.Frame.SubGroup == wire.ICBMErr:
  110. if errSn, ok := resp.Body.(wire.SNACError); ok {
  111. switch errSn.Code {
  112. case wire.ErrorCodeNotLoggedOn:
  113. subCode, hasSubCode := errSn.Uint16BE(wire.ErrorTLVErrorSubcode)
  114. if hasSubCode {
  115. if subCode == wire.ICBMSubErrOfflineIMExceedMax {
  116. h.Logger.DebugContext(r.Context(), "user's offline messages full")
  117. }
  118. } else {
  119. h.Logger.DebugContext(r.Context(), "recipient offline")
  120. }
  121. return
  122. case wire.ErrorCodeInLocalPermitDeny:
  123. h.Logger.DebugContext(r.Context(), "you blocked this user")
  124. return
  125. }
  126. }
  127. case resp.Frame.FoodGroup == wire.ICBM && resp.Frame.SubGroup == wire.ICBMHostAck:
  128. h.Logger.DebugContext(r.Context(), "received host ack")
  129. }
  130. }
  131. recipientDisplay := h.resolveDisplayName(ctx, sess.OSCARSession, recipientIdent)
  132. // The alias lives in the sender's feedbag, so unlike the display name it cannot
  133. // be read off a locate reply.
  134. recipientAlias := sess.Aliases(ctx)[recipientIdent.String()]
  135. h.pushSenderWebAPIEvents(sess, recipientIdent, recipientDisplay, recipientAlias, message, messageID, now, autoResponse)
  136. h.Logger.DebugContext(ctx, "queued sentIM event for sender",
  137. "from", sess.ScreenName.String(),
  138. "to", recipient,
  139. "eventType", types.EventTypeSentIM,
  140. )
  141. // Send success response
  142. responseData := map[string]interface{}{
  143. "msgId": messageID,
  144. "state": "delivered",
  145. }
  146. response := BaseResponse{}
  147. response.Response.StatusCode = 200
  148. response.Response.StatusText = "OK"
  149. response.Response.Data = responseData
  150. SendResponse(w, r, response, h.Logger)
  151. }
  152. // resolveDisplayName returns the recipient's screen name as they formatted it,
  153. // or "" when it cannot be determined because they are offline or blocked.
  154. func (h *MessagingHandler) resolveDisplayName(ctx context.Context, instance *state.SessionInstance, recipient state.IdentScreenName) string {
  155. reply, err := h.LocateService.UserInfoQuery(ctx, instance, wire.SNACFrame{},
  156. wire.SNAC_0x02_0x05_LocateUserInfoQuery{
  157. Type: uint16(wire.LocateTypeUnavailable),
  158. ScreenName: recipient.String(),
  159. })
  160. if err != nil {
  161. h.Logger.DebugContext(ctx, "failed to resolve recipient display name",
  162. "screenName", recipient.String(), "error", err)
  163. return ""
  164. }
  165. info, ok := reply.Body.(wire.SNAC_0x02_0x06_LocateUserInfoReply)
  166. if !ok {
  167. return ""
  168. }
  169. return info.ScreenName
  170. }
  171. // pushSenderWebAPIEvents echoes a just-sent IM back to the sender's own event
  172. // queue. recipientDisplay is the recipient's own formatting of their screen name,
  173. // or "" when it could not be resolved; recipientAlias is the sender's private name
  174. // for them, or "" when unaliased.
  175. //
  176. // The web client merges every user map it receives onto the single user object it
  177. // keys by aimId, so a displayId here overwrites the name the buddy list already
  178. // rendered. Echoing the normalized aimId as a displayId would reduce a buddy named
  179. // "Mike Lee" to "mikelee" the moment you message him. Omitting displayId leaves the
  180. // client's existing name untouched. The merge also deletes any alias it holds, so
  181. // friendly has to be repeated here even though the buddy list already sent it.
  182. func (h *MessagingHandler) pushSenderWebAPIEvents(sess *state.WebAPISession, recipient state.IdentScreenName, recipientDisplay, recipientAlias, message, messageID string, now float64, autoResponse bool) {
  183. senderAimID := sess.ScreenName.IdentScreenName().String()
  184. recipientAimID := recipient.String()
  185. senderEventData := types.SentIMEvent{
  186. Sender: types.UserInfo{
  187. AimID: senderAimID,
  188. DisplayID: sess.ScreenName.String(),
  189. UserType: "aim",
  190. },
  191. Dest: types.UserInfo{
  192. AimID: recipientAimID,
  193. DisplayID: recipientDisplay,
  194. Friendly: recipientAlias,
  195. UserType: "aim",
  196. },
  197. Message: message,
  198. MsgID: messageID,
  199. Timestamp: now,
  200. AutoResp: autoResponse,
  201. }
  202. sess.EventQueue.Push(types.EventTypeSentIM, senderEventData)
  203. if sess.IsSubscribedTo("conversation") {
  204. sess.EventQueue.Push(types.EventTypeConversation, types.ConversationEventData("update", []map[string]interface{}{
  205. types.ConversationEntry(recipientAimID, recipientDisplay, message, messageID, senderAimID, true, 0),
  206. }))
  207. }
  208. }
  209. // sendErrorResponse sends an error response in Web AIM API format
  210. func (h *MessagingHandler) sendErrorResponse(w http.ResponseWriter, statusCode int, errorText string) {
  211. SendError(w, statusCode, errorText)
  212. }
  213. // SetTyping handles the /im/setTyping endpoint for typing indicators
  214. func (h *MessagingHandler) SetTyping(w http.ResponseWriter, r *http.Request, sess *state.WebAPISession) {
  215. ctx := r.Context()
  216. // Parse parameters
  217. recipient := r.URL.Query().Get("t")
  218. if recipient == "" {
  219. h.sendErrorResponse(w, http.StatusBadRequest, "missing required parameter: t (recipient)")
  220. return
  221. }
  222. typingStatus := r.URL.Query().Get("typingStatus")
  223. if typingStatus == "" {
  224. typingStatus = "none"
  225. }
  226. var event uint16
  227. switch typingStatus {
  228. case "typing":
  229. event = 0x0002
  230. case "typed":
  231. event = 0x0001
  232. default:
  233. event = 0x0000
  234. }
  235. inBody := wire.SNAC_0x04_0x14_ICBMClientEvent{
  236. ChannelID: wire.ICBMChannelIM,
  237. ScreenName: recipient,
  238. Event: event,
  239. }
  240. if err := h.ICBMService.ClientEvent(ctx, sess.OSCARSession, wire.SNACFrame{}, inBody); err != nil {
  241. h.Logger.ErrorContext(ctx, "failed to send typing notification", "error", err)
  242. h.sendErrorResponse(w, http.StatusInternalServerError, "internal server error")
  243. return
  244. }
  245. h.sendSuccessResponse(w, r, nil)
  246. }
  247. // sendSuccessResponse sends a success response in Web AIM API format
  248. func (h *MessagingHandler) sendSuccessResponse(w http.ResponseWriter, r *http.Request, data interface{}) {
  249. response := BaseResponse{}
  250. response.Response.StatusCode = 200
  251. response.Response.StatusText = "OK"
  252. response.Response.Data = data
  253. SendResponse(w, r, response, h.Logger)
  254. }