events.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. package webapi
  2. import (
  3. "context"
  4. "sync"
  5. "sync/atomic"
  6. "time"
  7. "github.com/mk6i/open-oscar-server/state"
  8. )
  9. // EventType defines the type of WebAPI event.
  10. type EventType string
  11. const (
  12. EventTypeBuddyList EventType = "buddylist"
  13. EventTypeConversation EventType = "conversation"
  14. EventTypeIM EventType = "im"
  15. EventTypeMyInfo EventType = "myInfo"
  16. EventTypeOfflineIM EventType = "offlineIM"
  17. EventTypePreference EventType = "preference"
  18. EventTypePresence EventType = "presence"
  19. EventTypeRateLimit EventType = "rateLimit"
  20. EventTypeSentIM EventType = "sentIM"
  21. EventTypeSessionEnded EventType = "sessionEnded"
  22. EventTypeTyping EventType = "typing"
  23. EventTypePermitDeny EventType = "permitDeny"
  24. EventTypeClientError EventType = "clientError"
  25. EventTypeService EventType = "service"
  26. )
  27. // Event represents an event to be delivered to a web client.
  28. type Event struct {
  29. Type EventType `json:"type" xml:"type"`
  30. SeqNum uint64 `json:"seqNum" xml:"seqNum"`
  31. Timestamp int64 `json:"timestamp" xml:"timestamp"`
  32. Data any `json:"eventData" xml:"eventData"`
  33. }
  34. // PresenceEvent represents a presence change event.
  35. // Friendly repeats the viewer's alias for the user. The client's merge deletes any
  36. // alias it already holds, so a presence update that omits it silently renames the
  37. // buddy back to their screen name. See UserInfo.
  38. type PresenceEvent struct {
  39. AimID string `json:"aimId" xml:"aimId"`
  40. Friendly string `json:"friendly,omitempty" xml:"friendly,omitempty"`
  41. State string `json:"state" xml:"state"` // "online", "offline", "away", "idle"
  42. MoodIcon string `json:"moodIcon,omitempty" xml:"moodIcon,omitempty"`
  43. MoodTitle string `json:"moodTitle,omitempty" xml:"moodTitle,omitempty"`
  44. StatusMsg string `json:"statusMsg,omitempty" xml:"statusMsg,omitempty"`
  45. AwayMsg string `json:"awayMsg,omitempty" xml:"awayMsg,omitempty"`
  46. IdleTime int `json:"idleTime,omitempty" xml:"idleTime,omitempty"` // Minutes idle
  47. OnlineTime int64 `json:"onlineTime,omitempty" xml:"onlineTime,omitempty"` // Unix timestamp
  48. UserType string `json:"userType" xml:"userType"` // "aim", "icq"
  49. BuddyIcon string `json:"buddyIcon,omitempty" xml:"buddyIcon,omitempty"` // Absolute icon URL; empty preserves the client's current icon, the placeholder URL clears it
  50. }
  51. // imfPlainText is the message-format tag put on delivered IMs; bodies are always
  52. // plain text.
  53. const imfPlainText = "plain"
  54. // User-type tags, which clients compare case-sensitively.
  55. const (
  56. userTypeAIM = "aim"
  57. userTypeICQ = "icq"
  58. )
  59. // serviceICQ names ICQ in both a user's service tag and the config list the
  60. // client joins it to.
  61. const serviceICQ = "icq"
  62. // userTypeFor returns the user-type tag for a screen name. A numeric screen
  63. // name is an ICQ UIN.
  64. func userTypeFor(sn state.IdentScreenName) string {
  65. if sn.UIN() != 0 {
  66. return userTypeICQ
  67. }
  68. return userTypeAIM
  69. }
  70. // serviceFor returns the network tag for a screen name, empty for AIM. An absent
  71. // tag reads as the native network.
  72. func serviceFor(sn state.IdentScreenName) string {
  73. if userTypeFor(sn) == userTypeICQ {
  74. return serviceICQ
  75. }
  76. return ""
  77. }
  78. // ServiceData is the service event payload and the service half of the
  79. // startSession seed.
  80. type ServiceData struct {
  81. ServiceConfigs []ServiceConfig `json:"serviceConfigs" xml:"serviceConfigs>serviceConfig"`
  82. }
  83. // ServiceConfig describes one network a user's service tag can name. The client
  84. // looks the tag up by Name and renders FriendlyName as the user's label.
  85. type ServiceConfig struct {
  86. Name string `json:"name" xml:"name"`
  87. FriendlyName string `json:"friendlyName" xml:"friendlyName"`
  88. Associated bool `json:"associated" xml:"associated"`
  89. ConnectionState string `json:"connectionState" xml:"connectionState"`
  90. }
  91. // newServiceData lists the networks a user's service tag can name. ICQ is the
  92. // only one, since an AIM user carries no tag. An associated network the client
  93. // reads as unconnected prompts it to open a connection.
  94. func newServiceData() *ServiceData {
  95. return &ServiceData{
  96. ServiceConfigs: []ServiceConfig{
  97. {
  98. Name: serviceICQ,
  99. FriendlyName: "ICQ",
  100. Associated: true,
  101. ConnectionState: "connected",
  102. },
  103. },
  104. }
  105. }
  106. // IMEvent represents an instant message event.
  107. type IMEvent struct {
  108. Source UserInfo `json:"source" xml:"source"`
  109. Message string `json:"message" xml:"message"`
  110. MsgID string `json:"msgId,omitempty" xml:"msgId,omitempty"`
  111. Timestamp int64 `json:"timestamp" xml:"timestamp"`
  112. // Imf is read strictly and then ignored, so its only job is to exist.
  113. Imf string `json:"imf" xml:"imf"`
  114. // AutoResp is always sent, false included: clients read it unconditionally.
  115. AutoResp bool `json:"autoresponse" xml:"autoresponse" amf3:"autoresponse"`
  116. }
  117. // OfflineIMEvent represents a message that was stored while the user was signed
  118. // off and is replayed when they next start a session.
  119. //
  120. // The client models this separately from IMEvent: it reads the sender from a bare
  121. // aimId rather than a source user object, and resolves the display name from the
  122. // buddy list it already holds. Timestamp is when the sender sent the message, not
  123. // when it was delivered.
  124. type OfflineIMEvent struct {
  125. AimID string `json:"aimId" xml:"aimId"`
  126. // Friendly is the sender's display name. The client resolves an offline
  127. // sender from this pair alone, so without it the message renders under the
  128. // normalized aimId.
  129. Friendly string `json:"friendly,omitempty" xml:"friendly,omitempty"`
  130. Message string `json:"message" xml:"message"`
  131. MsgID string `json:"msgId,omitempty" xml:"msgId,omitempty"`
  132. Timestamp int64 `json:"timestamp" xml:"timestamp"`
  133. // Imf and AutoResp must be present, as on IMEvent.
  134. Imf string `json:"imf" xml:"imf"`
  135. AutoResp bool `json:"autoresponse" xml:"autoresponse" amf3:"autoresponse"`
  136. }
  137. // SentIMEvent represents a sent instant message event.
  138. // The AMF3 spellings differ from the documented JSON ones: the client reads the
  139. // sender from "source" and the flag from "autoresponse", while the spec names
  140. // them "sender" and "autoResponse".
  141. type SentIMEvent struct {
  142. Sender UserInfo `json:"sender" xml:"sender" amf3:"source"`
  143. Dest UserInfo `json:"dest" xml:"dest"`
  144. Message string `json:"message" xml:"message"`
  145. MsgID string `json:"msgId,omitempty" xml:"msgId,omitempty"`
  146. Timestamp int64 `json:"timestamp" xml:"timestamp"`
  147. AutoResp bool `json:"autoResponse,omitempty" xml:"autoResponse,omitempty" amf3:"autoresponse"`
  148. // ISent marks the echo to the session that sent the message. The client
  149. // already shows that message, so it only renders a sentIM without it.
  150. ISent bool `json:"iSent" xml:"iSent"`
  151. }
  152. // ClientErrorEvent tells a sender that the recipient rejected a message the server
  153. // had already delivered. im/sendIM answers synchronously when the ICBM service
  154. // itself refuses a send; a rejection from the recipient's own client arrives here
  155. // instead. Channel "data" names the rendezvous channel.
  156. type ClientErrorEvent struct {
  157. Source UserInfo `json:"source" xml:"source"`
  158. // Cookie names the failed message by the msgId im/sendIM returned. It is empty
  159. // when another instance of the account sent the message.
  160. Cookie string `json:"cookie" xml:"cookie"`
  161. Channel string `json:"channel" xml:"channel"`
  162. }
  163. // UserInfo represents basic user information in events.
  164. // AimID is the normalized screen name the client keys users by. DisplayID is the
  165. // screen name as its owner formatted it. Friendly is the viewer's private alias for
  166. // that user, and takes precedence over DisplayID when the client renders a name.
  167. //
  168. // The client merges every user map it receives onto the single user object it holds
  169. // per aimId, and that merge deletes friendly before applying the map. An alias
  170. // therefore has to be repeated on every user map, or it is lost.
  171. type UserInfo struct {
  172. AimID string `json:"aimId" xml:"aimId"`
  173. DisplayID string `json:"displayId,omitempty" xml:"displayId,omitempty"`
  174. Friendly string `json:"friendly,omitempty" xml:"friendly,omitempty"`
  175. UserType string `json:"userType,omitempty" xml:"userType,omitempty"`
  176. State string `json:"state,omitempty" xml:"state,omitempty"`
  177. OnlineTime int64 `json:"onlineTime,omitempty" xml:"onlineTime,omitempty"`
  178. }
  179. // TypingEvent represents a typing notification event.
  180. type TypingEvent struct {
  181. AimID string `json:"aimId" xml:"aimId"`
  182. TypingStatus string `json:"typingStatus" xml:"typingStatus"`
  183. }
  184. // RateLimitEvent tells the client that its rate limit status changed.
  185. //
  186. // The client reads classes[0] only: it takes the status string and feeds it
  187. // straight into a switch on "clear" | "warn" | "limit" | "disconnect" to render
  188. // the in-conversation alert (e.g. "You have been rate limited. Wait for a few
  189. // moments until you can chat again."). The "clear" alert is only shown if the
  190. // client's last recorded status was "limit", so this event must be pushed on
  191. // status transitions rather than on every rate-limited request.
  192. type RateLimitEvent struct {
  193. Classes []RateLimitClass `json:"classes" xml:"classes>class"`
  194. }
  195. // RateLimitClass is the per-rate-class state carried by a RateLimitEvent.
  196. type RateLimitClass struct {
  197. ID int `json:"id" xml:"id"`
  198. Status string `json:"status" xml:"status"` // "clear", "warn", "limit", or "disconnect"
  199. }
  200. // EventQueue manages a queue of events for a WebAPI session.
  201. type EventQueue struct {
  202. events []Event
  203. seqNum atomic.Uint64
  204. maxSize int
  205. mu sync.RWMutex
  206. waitChan chan struct{}
  207. closeChan chan struct{}
  208. closeOnce sync.Once
  209. }
  210. // isClosed reports whether Close has been called.
  211. func (q *EventQueue) isClosed() bool {
  212. select {
  213. case <-q.closeChan:
  214. return true
  215. default:
  216. return false
  217. }
  218. }
  219. // NewEventQueue creates a new event queue with the specified maximum size.
  220. func NewEventQueue(maxSize int) *EventQueue {
  221. return &EventQueue{
  222. events: make([]Event, 0),
  223. maxSize: maxSize,
  224. waitChan: make(chan struct{}, 1),
  225. closeChan: make(chan struct{}),
  226. }
  227. }
  228. // Push adds an event to the queue.
  229. func (q *EventQueue) Push(eventType EventType, data any) {
  230. if q.isClosed() {
  231. return
  232. }
  233. q.mu.Lock()
  234. defer q.mu.Unlock()
  235. // Increment sequence number atomically
  236. seqNum := q.seqNum.Add(1)
  237. event := Event{
  238. Type: eventType,
  239. SeqNum: seqNum,
  240. Timestamp: time.Now().Unix(),
  241. Data: data,
  242. }
  243. // Add event to queue
  244. q.events = append(q.events, event)
  245. // If queue exceeds max size, remove oldest events
  246. if len(q.events) > q.maxSize {
  247. // Keep only the most recent maxSize events
  248. q.events = q.events[len(q.events)-q.maxSize:]
  249. }
  250. // Signal any waiting fetchers
  251. select {
  252. case q.waitChan <- struct{}{}:
  253. default:
  254. // Channel already has a signal
  255. }
  256. }
  257. // Fetch retrieves events from the queue, optionally waiting for new events.
  258. func (q *EventQueue) Fetch(ctx context.Context, lastSeqNum uint64, timeout time.Duration) ([]Event, error) {
  259. if q.isClosed() {
  260. return []Event{}, nil
  261. }
  262. // First, check if we have any events newer than lastSeqNum
  263. q.mu.RLock()
  264. events := q.getEventsAfter(lastSeqNum)
  265. q.mu.RUnlock()
  266. if len(events) > 0 {
  267. return events, nil
  268. }
  269. // No events available, wait for new ones or timeout
  270. timeoutChan := time.After(timeout)
  271. for {
  272. select {
  273. case <-q.closeChan:
  274. return []Event{}, nil
  275. case <-q.waitChan:
  276. // New events may be available
  277. q.mu.RLock()
  278. events = q.getEventsAfter(lastSeqNum)
  279. q.mu.RUnlock()
  280. if len(events) > 0 {
  281. return events, nil
  282. }
  283. // False alarm, keep waiting
  284. case <-timeoutChan:
  285. // Timeout reached, return empty array
  286. return []Event{}, nil
  287. case <-ctx.Done():
  288. // Context cancelled
  289. return nil, ctx.Err()
  290. }
  291. }
  292. }
  293. // getEventsAfter returns all events with sequence number greater than the specified value.
  294. // Must be called with at least a read lock held.
  295. func (q *EventQueue) getEventsAfter(seqNum uint64) []Event {
  296. var result []Event
  297. for _, event := range q.events {
  298. if event.SeqNum > seqNum {
  299. result = append(result, event)
  300. }
  301. }
  302. return result
  303. }
  304. // GetAllEvents returns all events in the queue (for debugging).
  305. func (q *EventQueue) GetAllEvents() []Event {
  306. q.mu.RLock()
  307. defer q.mu.RUnlock()
  308. result := make([]Event, len(q.events))
  309. copy(result, q.events)
  310. return result
  311. }
  312. // Close closes the event queue, unblocking any waiting fetchers. Safe to call
  313. // more than once.
  314. func (q *EventQueue) Close() {
  315. q.closeOnce.Do(func() {
  316. close(q.closeChan)
  317. })
  318. }
  319. // ConversationData is a conversation event payload: an operation and the
  320. // conversations it applies to.
  321. type ConversationData struct {
  322. Operation string `json:"operation" xml:"operation"`
  323. Conversations []ConversationEntryData `json:"conversations" xml:"conversations>conversation"`
  324. }
  325. // ConversationEntryData is one conversation in the client's list.
  326. type ConversationEntryData struct {
  327. AimID string `json:"aimId" xml:"aimId"`
  328. // Active is always sent, zero included, because the client reads it
  329. // unconditionally.
  330. Active int `json:"active" xml:"active"`
  331. UnreadCount int `json:"unreadCount" xml:"unreadCount"`
  332. // DisplayID is omitted when empty rather than sent blank: the client falls
  333. // back to the name it already has for aimID, whereas any value present here
  334. // replaces it.
  335. DisplayID string `json:"displayId,omitempty" xml:"displayId,omitempty"`
  336. LastIM *LastIM `json:"lastIM,omitempty" xml:"lastIM,omitempty"`
  337. }
  338. // LastIM is the most recent message in a conversation.
  339. type LastIM struct {
  340. Message string `json:"message" xml:"message"`
  341. MsgID string `json:"msgId" xml:"msgId"`
  342. Sender string `json:"sender" xml:"sender"`
  343. Sent bool `json:"sent" xml:"sent"`
  344. Timestamp int64 `json:"timestamp" xml:"timestamp"`
  345. }
  346. // ConversationEventData builds a conversation fetchEvents payload.
  347. func ConversationEventData(operation string, conversations []ConversationEntryData) *ConversationData {
  348. if conversations == nil {
  349. conversations = []ConversationEntryData{}
  350. }
  351. return &ConversationData{
  352. Operation: operation,
  353. Conversations: conversations,
  354. }
  355. }
  356. // ConversationEntry builds one conversation object for the Web AIM client.
  357. func ConversationEntry(aimID, displayID, message, msgID, sender string, sent bool, unread int) ConversationEntryData {
  358. entry := ConversationEntryData{
  359. AimID: aimID,
  360. Active: 0,
  361. UnreadCount: unread,
  362. DisplayID: displayID,
  363. }
  364. if message != "" {
  365. entry.LastIM = &LastIM{
  366. Message: message,
  367. MsgID: msgID,
  368. Sender: sender,
  369. Sent: sent,
  370. Timestamp: time.Now().Unix(),
  371. }
  372. }
  373. return entry
  374. }