im_handler.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. package webapi
  2. import (
  3. "context"
  4. "crypto/rand"
  5. "encoding/binary"
  6. "fmt"
  7. "log/slog"
  8. "net/http"
  9. "strconv"
  10. "time"
  11. "github.com/mk6i/open-oscar-server/state"
  12. "github.com/mk6i/open-oscar-server/wire"
  13. )
  14. // MessagingHandler handles Web AIM API messaging endpoints
  15. type MessagingHandler struct {
  16. ICBMService ICBMService
  17. LocateService LocateService
  18. FeedbagService FeedbagService
  19. Logger *slog.Logger
  20. }
  21. // queryOrFormParam returns a request parameter from the query string or, for POST
  22. // requests, from application/x-www-form-urlencoded body fields. The Web AIM client
  23. // sends t/offlineIM/etc. on the query string and puts message in the POST body.
  24. func queryOrFormParam(r *http.Request, key string) string {
  25. if v := r.URL.Query().Get(key); v != "" {
  26. return v
  27. }
  28. if r.Method == http.MethodPost {
  29. if err := r.ParseForm(); err == nil {
  30. return r.FormValue(key)
  31. }
  32. }
  33. return ""
  34. }
  35. // SendIM handles the /im/sendIM endpoint for sending instant messages
  36. func (h *MessagingHandler) SendIM(w http.ResponseWriter, r *http.Request, sess *Session) {
  37. ctx := r.Context()
  38. // Parse parameters
  39. recipient := queryOrFormParam(r, "t")
  40. if recipient == "" {
  41. SendError(w, r, http.StatusBadRequest, "missing required parameter: t (recipient)")
  42. return
  43. }
  44. message := queryOrFormParam(r, "message")
  45. if message == "" {
  46. SendError(w, r, http.StatusBadRequest, "missing required parameter: message")
  47. return
  48. }
  49. // Parse optional parameters
  50. autoResponse := queryOrFormParam(r, "autoResponse") == "1"
  51. // The client sets offlineIM once it believes the recipient is offline and
  52. // storable; it sends the literal "true" rather than "1".
  53. offlineIM := queryOrFormParam(r, "offlineIM") == "true" || queryOrFormParam(r, "offlineIM") == "1"
  54. // Generate message cookie
  55. var cookie [8]byte
  56. if _, err := rand.Read(cookie[:]); err != nil {
  57. h.Logger.ErrorContext(ctx, "failed to generate message cookie", "error", err)
  58. SendError(w, r, http.StatusInternalServerError, "internal server error")
  59. return
  60. }
  61. cookieUint64 := binary.BigEndian.Uint64(cookie[:])
  62. // Create message ID for response (UUID format like working implementation)
  63. // Using the cookie bytes to generate a UUID-like string
  64. messageID := fmt.Sprintf("%08x-%04x-%04x-%04x-%012x",
  65. binary.BigEndian.Uint32(cookie[:4]),
  66. binary.BigEndian.Uint16(cookie[4:6]),
  67. binary.BigEndian.Uint16(cookie[6:8]),
  68. binary.BigEndian.Uint16([]byte{0x80, 0x00}), // Version bits
  69. time.Now().UnixNano()&0xffffffffffff)
  70. now := float64(time.Now().Unix())
  71. nowSec := time.Now().Unix()
  72. // The client sends t as the normalized aimId it keys the conversation by, so
  73. // it is never a source of display names.
  74. recipientIdent := state.NewIdentScreenName(recipient)
  75. clientIM := wire.SNAC_0x04_0x06_ICBMChannelMsgToHost{
  76. Cookie: cookieUint64,
  77. ChannelID: wire.ICBMChannelIM,
  78. ScreenName: recipient,
  79. TLVRestBlock: wire.TLVRestBlock{},
  80. }
  81. // Add message data
  82. frags, err := wire.ICBMFragmentList(message)
  83. if err != nil {
  84. SendError(w, r, http.StatusInternalServerError, "failed to send message")
  85. return
  86. }
  87. clientIM.Append(wire.NewTLVBE(wire.ICBMTLVAOLIMData, frags))
  88. // Add auto-response flag if applicable
  89. if autoResponse {
  90. clientIM.Append(wire.NewTLVBE(wire.ICBMTLVAutoResponse, []byte{}))
  91. }
  92. // Without this directive the ICBM service rejects messages to offline
  93. // recipients instead of storing them.
  94. if offlineIM {
  95. clientIM.Append(wire.NewTLVBE(wire.ICBMTLVStore, []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. SendError(w, r, 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 && subCode == wire.ICBMSubErrOfflineIMExceedMax {
  115. h.Logger.DebugContext(ctx, "user's offline messages full")
  116. h.sendUndeliverable(w, r, "recipient's offline message store is full")
  117. } else {
  118. h.Logger.DebugContext(ctx, "recipient offline")
  119. h.sendUndeliverable(w, r, "recipient is offline and cannot receive offline messages")
  120. }
  121. return
  122. case wire.ErrorCodeInLocalPermitDeny:
  123. h.Logger.DebugContext(ctx, "you blocked this user")
  124. h.sendUndeliverable(w, r, "you have blocked this user")
  125. return
  126. }
  127. }
  128. h.Logger.DebugContext(ctx, "message rejected by ICBM service")
  129. h.sendUndeliverable(w, r, "failed to send message")
  130. return
  131. case resp.Frame.FoodGroup == wire.ICBM && resp.Frame.SubGroup == wire.ICBMHostAck:
  132. h.Logger.DebugContext(ctx, "received host ack")
  133. }
  134. }
  135. sess.AddStoredIM(recipientIdent.String(), sess.ScreenName.IdentScreenName().String(), message, messageID, nowSec)
  136. recipientDisplay := h.resolveDisplayName(ctx, sess.OSCARSession, recipientIdent)
  137. // The alias lives in the sender's feedbag, so unlike the display name it cannot
  138. // be read off a locate reply.
  139. recipientAlias := sess.Aliases(ctx)[recipientIdent.String()]
  140. h.pushSenderWebAPIEvents(sess, recipientIdent, recipientDisplay, recipientAlias, message, messageID, now, autoResponse)
  141. h.Logger.DebugContext(ctx, "queued sentIM event for sender",
  142. "from", sess.ScreenName.String(),
  143. "to", recipient,
  144. "eventType", EventTypeSentIM,
  145. )
  146. // Send success response
  147. responseData := &SendIMData{MsgID: messageID, State: "delivered"}
  148. SendOK(w, r, responseData, h.Logger)
  149. }
  150. // sendUndeliverable reports an IM the server accepted but could not deliver.
  151. func (h *MessagingHandler) sendUndeliverable(w http.ResponseWriter, r *http.Request, statusText string) {
  152. SendEnvelopeStatus(w, r, statusSendFailed, statusText, h.Logger)
  153. }
  154. // resolveDisplayName returns the recipient's screen name as they formatted it,
  155. // or "" when it cannot be determined because they are offline or blocked.
  156. func (h *MessagingHandler) resolveDisplayName(ctx context.Context, instance *state.SessionInstance, recipient state.IdentScreenName) string {
  157. reply, err := h.LocateService.UserInfoQuery(ctx, instance, wire.SNACFrame{},
  158. wire.SNAC_0x02_0x05_LocateUserInfoQuery{
  159. Type: uint16(wire.LocateTypeUnavailable),
  160. ScreenName: recipient.String(),
  161. })
  162. if err != nil {
  163. h.Logger.DebugContext(ctx, "failed to resolve recipient display name",
  164. "screenName", recipient.String(), "error", err)
  165. return ""
  166. }
  167. info, ok := reply.Body.(wire.SNAC_0x02_0x06_LocateUserInfoReply)
  168. if !ok {
  169. return ""
  170. }
  171. return info.ScreenName
  172. }
  173. // pushSenderWebAPIEvents echoes a just-sent IM back to the sender's own event
  174. // queue. recipientDisplay is the recipient's own formatting of their screen name,
  175. // or "" when it could not be resolved; recipientAlias is the sender's private name
  176. // for them, or "" when unaliased.
  177. //
  178. // The web client merges every user map it receives onto the single user object it
  179. // keys by aimId, so a displayId here overwrites the name the buddy list already
  180. // rendered. Echoing the normalized aimId as a displayId would reduce a buddy named
  181. // "Mike Lee" to "mikelee" the moment you message him. Omitting displayId leaves the
  182. // client's existing name untouched. The merge also deletes any alias it holds, so
  183. // friendly has to be repeated here even though the buddy list already sent it.
  184. func (h *MessagingHandler) pushSenderWebAPIEvents(sess *Session, recipient state.IdentScreenName, recipientDisplay, recipientAlias, message, messageID string, now float64, autoResponse bool) {
  185. senderAimID := sess.ScreenName.IdentScreenName().String()
  186. recipientAimID := recipient.String()
  187. senderEventData := SentIMEvent{
  188. Sender: UserInfo{
  189. AimID: senderAimID,
  190. DisplayID: sess.ScreenName.String(),
  191. UserType: "aim",
  192. },
  193. Dest: UserInfo{
  194. AimID: recipientAimID,
  195. DisplayID: recipientDisplay,
  196. Friendly: recipientAlias,
  197. UserType: "aim",
  198. },
  199. Message: message,
  200. MsgID: messageID,
  201. Timestamp: now,
  202. AutoResp: autoResponse,
  203. }
  204. sess.EventQueue.Push(EventTypeSentIM, senderEventData)
  205. if sess.IsSubscribedTo("conversation") {
  206. sess.EventQueue.Push(EventTypeConversation, ConversationEventData("update", []ConversationEntryData{
  207. ConversationEntry(recipientAimID, recipientDisplay, message, messageID, senderAimID, true, 0),
  208. }))
  209. }
  210. }
  211. // SetTyping handles the /im/setTyping endpoint for typing indicators
  212. func (h *MessagingHandler) SetTyping(w http.ResponseWriter, r *http.Request, sess *Session) {
  213. ctx := r.Context()
  214. // Parse parameters
  215. recipient := r.URL.Query().Get("t")
  216. if recipient == "" {
  217. SendError(w, r, http.StatusBadRequest, "missing required parameter: t (recipient)")
  218. return
  219. }
  220. typingStatus := r.URL.Query().Get("typingStatus")
  221. if typingStatus == "" {
  222. typingStatus = "none"
  223. }
  224. var event uint16
  225. switch typingStatus {
  226. case "typing":
  227. event = 0x0002
  228. case "typed":
  229. event = 0x0001
  230. default:
  231. event = 0x0000
  232. }
  233. inBody := wire.SNAC_0x04_0x14_ICBMClientEvent{
  234. ChannelID: wire.ICBMChannelIM,
  235. ScreenName: recipient,
  236. Event: event,
  237. }
  238. if err := h.ICBMService.ClientEvent(ctx, sess.OSCARSession, wire.SNACFrame{}, inBody); err != nil {
  239. h.Logger.ErrorContext(ctx, "failed to send typing notification", "error", err)
  240. SendError(w, r, http.StatusInternalServerError, "internal server error")
  241. return
  242. }
  243. SendOK(w, r, nil, h.Logger)
  244. }
  245. // SendIMData reports the fate of an accepted IM.
  246. type SendIMData struct {
  247. MsgID string `json:"msgId" xml:"msgId"`
  248. State string `json:"state" xml:"state"`
  249. }
  250. // StoredIMsData is the fetchStoredIMs payload.
  251. type StoredIMsData struct {
  252. Msgs []StoredIM `json:"msgs" xml:"msgs>msg"`
  253. }
  254. // ConversationStubHandler serves Web AIM conversation/imlog endpoints the
  255. // client calls when syncing chat focus and read state.
  256. type ConversationStubHandler struct {
  257. Logger *slog.Logger
  258. }
  259. // Update records active/focus time for a conversation (fire-and-forget).
  260. func (h *ConversationStubHandler) Update(w http.ResponseWriter, r *http.Request) {
  261. SendOK(w, r, nil, h.Logger)
  262. }
  263. // Close acknowledges a conversation was closed in the client.
  264. func (h *ConversationStubHandler) Close(w http.ResponseWriter, r *http.Request) {
  265. SendOK(w, r, nil, h.Logger)
  266. }
  267. // MarkRead acknowledges IM log read state for a buddy.
  268. func (h *ConversationStubHandler) MarkRead(w http.ResponseWriter, r *http.Request) {
  269. SendOK(w, r, nil, h.Logger)
  270. }
  271. // FetchStoredIMs returns stored IM history for a conversation partner.
  272. func (h *ConversationStubHandler) FetchStoredIMs(w http.ResponseWriter, r *http.Request, sess *Session) {
  273. partner := r.URL.Query().Get("to")
  274. if partner == "" {
  275. SendError(w, r, http.StatusBadRequest, "missing required parameter: to")
  276. return
  277. }
  278. q := StoredIMQuery{
  279. PartnerAimID: partner,
  280. SortOrder: r.URL.Query().Get("sortOrder"),
  281. SkipMsgID: r.URL.Query().Get("skipMsgId"),
  282. StopMsgID: r.URL.Query().Get("stopMsgId"),
  283. }
  284. if n := r.URL.Query().Get("nToGet"); n != "" {
  285. if v, err := strconv.Atoi(n); err == nil {
  286. q.NToGet = v
  287. }
  288. }
  289. if start := r.URL.Query().Get("startTime"); start != "" {
  290. if v, err := strconv.ParseInt(start, 10, 64); err == nil {
  291. q.StartTime = v
  292. }
  293. }
  294. if end := r.URL.Query().Get("endTime"); end != "" {
  295. if v, err := strconv.ParseInt(end, 10, 64); err == nil {
  296. q.EndTime = v
  297. }
  298. }
  299. msgs := sess.GetStoredIMs(q)
  300. SendOK(w, r, &StoredIMsData{Msgs: msgs}, h.Logger)
  301. }