events.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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. }
  149. // ClientErrorEvent tells a sender that the recipient rejected a message the server
  150. // had already delivered. im/sendIM answers synchronously when the ICBM service
  151. // itself refuses a send; a rejection from the recipient's own client arrives here
  152. // instead. Channel "data" names the rendezvous channel.
  153. type ClientErrorEvent struct {
  154. Source UserInfo `json:"source" xml:"source"`
  155. // Cookie names the failed message by the msgId im/sendIM returned. It is empty
  156. // when another instance of the account sent the message.
  157. Cookie string `json:"cookie" xml:"cookie"`
  158. Channel string `json:"channel" xml:"channel"`
  159. }
  160. // UserInfo represents basic user information in events.
  161. // AimID is the normalized screen name the client keys users by. DisplayID is the
  162. // screen name as its owner formatted it. Friendly is the viewer's private alias for
  163. // that user, and takes precedence over DisplayID when the client renders a name.
  164. //
  165. // The client merges every user map it receives onto the single user object it holds
  166. // per aimId, and that merge deletes friendly before applying the map. An alias
  167. // therefore has to be repeated on every user map, or it is lost.
  168. type UserInfo struct {
  169. AimID string `json:"aimId" xml:"aimId"`
  170. DisplayID string `json:"displayId,omitempty" xml:"displayId,omitempty"`
  171. Friendly string `json:"friendly,omitempty" xml:"friendly,omitempty"`
  172. UserType string `json:"userType,omitempty" xml:"userType,omitempty"`
  173. State string `json:"state,omitempty" xml:"state,omitempty"`
  174. OnlineTime int64 `json:"onlineTime,omitempty" xml:"onlineTime,omitempty"`
  175. }
  176. // TypingEvent represents a typing notification event.
  177. type TypingEvent struct {
  178. AimID string `json:"aimId" xml:"aimId"`
  179. TypingStatus string `json:"typingStatus" xml:"typingStatus"`
  180. }
  181. // RateLimitEvent tells the client that its rate limit status changed.
  182. //
  183. // The client reads classes[0] only: it takes the status string and feeds it
  184. // straight into a switch on "clear" | "warn" | "limit" | "disconnect" to render
  185. // the in-conversation alert (e.g. "You have been rate limited. Wait for a few
  186. // moments until you can chat again."). The "clear" alert is only shown if the
  187. // client's last recorded status was "limit", so this event must be pushed on
  188. // status transitions rather than on every rate-limited request.
  189. type RateLimitEvent struct {
  190. Classes []RateLimitClass `json:"classes" xml:"classes>class"`
  191. }
  192. // RateLimitClass is the per-rate-class state carried by a RateLimitEvent.
  193. type RateLimitClass struct {
  194. ID int `json:"id" xml:"id"`
  195. Status string `json:"status" xml:"status"` // "clear", "warn", "limit", or "disconnect"
  196. }
  197. // EventQueue manages a queue of events for a WebAPI session.
  198. type EventQueue struct {
  199. events []Event
  200. seqNum atomic.Uint64
  201. maxSize int
  202. mu sync.RWMutex
  203. waitChan chan struct{}
  204. closeChan chan struct{}
  205. closeOnce sync.Once
  206. }
  207. // isClosed reports whether Close has been called.
  208. func (q *EventQueue) isClosed() bool {
  209. select {
  210. case <-q.closeChan:
  211. return true
  212. default:
  213. return false
  214. }
  215. }
  216. // NewEventQueue creates a new event queue with the specified maximum size.
  217. func NewEventQueue(maxSize int) *EventQueue {
  218. return &EventQueue{
  219. events: make([]Event, 0),
  220. maxSize: maxSize,
  221. waitChan: make(chan struct{}, 1),
  222. closeChan: make(chan struct{}),
  223. }
  224. }
  225. // Push adds an event to the queue.
  226. func (q *EventQueue) Push(eventType EventType, data any) {
  227. if q.isClosed() {
  228. return
  229. }
  230. q.mu.Lock()
  231. defer q.mu.Unlock()
  232. // Increment sequence number atomically
  233. seqNum := q.seqNum.Add(1)
  234. event := Event{
  235. Type: eventType,
  236. SeqNum: seqNum,
  237. Timestamp: time.Now().Unix(),
  238. Data: data,
  239. }
  240. // Add event to queue
  241. q.events = append(q.events, event)
  242. // If queue exceeds max size, remove oldest events
  243. if len(q.events) > q.maxSize {
  244. // Keep only the most recent maxSize events
  245. q.events = q.events[len(q.events)-q.maxSize:]
  246. }
  247. // Signal any waiting fetchers
  248. select {
  249. case q.waitChan <- struct{}{}:
  250. default:
  251. // Channel already has a signal
  252. }
  253. }
  254. // Fetch retrieves events from the queue, optionally waiting for new events.
  255. func (q *EventQueue) Fetch(ctx context.Context, lastSeqNum uint64, timeout time.Duration) ([]Event, error) {
  256. if q.isClosed() {
  257. return []Event{}, nil
  258. }
  259. // First, check if we have any events newer than lastSeqNum
  260. q.mu.RLock()
  261. events := q.getEventsAfter(lastSeqNum)
  262. q.mu.RUnlock()
  263. if len(events) > 0 {
  264. return events, nil
  265. }
  266. // No events available, wait for new ones or timeout
  267. timeoutChan := time.After(timeout)
  268. for {
  269. select {
  270. case <-q.closeChan:
  271. return []Event{}, nil
  272. case <-q.waitChan:
  273. // New events may be available
  274. q.mu.RLock()
  275. events = q.getEventsAfter(lastSeqNum)
  276. q.mu.RUnlock()
  277. if len(events) > 0 {
  278. return events, nil
  279. }
  280. // False alarm, keep waiting
  281. case <-timeoutChan:
  282. // Timeout reached, return empty array
  283. return []Event{}, nil
  284. case <-ctx.Done():
  285. // Context cancelled
  286. return nil, ctx.Err()
  287. }
  288. }
  289. }
  290. // getEventsAfter returns all events with sequence number greater than the specified value.
  291. // Must be called with at least a read lock held.
  292. func (q *EventQueue) getEventsAfter(seqNum uint64) []Event {
  293. var result []Event
  294. for _, event := range q.events {
  295. if event.SeqNum > seqNum {
  296. result = append(result, event)
  297. }
  298. }
  299. return result
  300. }
  301. // GetAllEvents returns all events in the queue (for debugging).
  302. func (q *EventQueue) GetAllEvents() []Event {
  303. q.mu.RLock()
  304. defer q.mu.RUnlock()
  305. result := make([]Event, len(q.events))
  306. copy(result, q.events)
  307. return result
  308. }
  309. // Close closes the event queue, unblocking any waiting fetchers. Safe to call
  310. // more than once.
  311. func (q *EventQueue) Close() {
  312. q.closeOnce.Do(func() {
  313. close(q.closeChan)
  314. })
  315. }
  316. // ConversationData is a conversation event payload: an operation and the
  317. // conversations it applies to.
  318. type ConversationData struct {
  319. Operation string `json:"operation" xml:"operation"`
  320. Conversations []ConversationEntryData `json:"conversations" xml:"conversations>conversation"`
  321. }
  322. // ConversationEntryData is one conversation in the client's list.
  323. type ConversationEntryData struct {
  324. AimID string `json:"aimId" xml:"aimId"`
  325. // Active is always sent, zero included, because the client reads it
  326. // unconditionally.
  327. Active int `json:"active" xml:"active"`
  328. UnreadCount int `json:"unreadCount" xml:"unreadCount"`
  329. // DisplayID is omitted when empty rather than sent blank: the client falls
  330. // back to the name it already has for aimID, whereas any value present here
  331. // replaces it.
  332. DisplayID string `json:"displayId,omitempty" xml:"displayId,omitempty"`
  333. LastIM *LastIM `json:"lastIM,omitempty" xml:"lastIM,omitempty"`
  334. }
  335. // LastIM is the most recent message in a conversation.
  336. type LastIM struct {
  337. Message string `json:"message" xml:"message"`
  338. MsgID string `json:"msgId" xml:"msgId"`
  339. Sender string `json:"sender" xml:"sender"`
  340. Sent bool `json:"sent" xml:"sent"`
  341. Timestamp int64 `json:"timestamp" xml:"timestamp"`
  342. }
  343. // ConversationEventData builds a conversation fetchEvents payload.
  344. func ConversationEventData(operation string, conversations []ConversationEntryData) *ConversationData {
  345. if conversations == nil {
  346. conversations = []ConversationEntryData{}
  347. }
  348. return &ConversationData{
  349. Operation: operation,
  350. Conversations: conversations,
  351. }
  352. }
  353. // ConversationEntry builds one conversation object for the Web AIM client.
  354. func ConversationEntry(aimID, displayID, message, msgID, sender string, sent bool, unread int) ConversationEntryData {
  355. entry := ConversationEntryData{
  356. AimID: aimID,
  357. Active: 0,
  358. UnreadCount: unread,
  359. DisplayID: displayID,
  360. }
  361. if message != "" {
  362. entry.LastIM = &LastIM{
  363. Message: message,
  364. MsgID: msgID,
  365. Sender: sender,
  366. Sent: sent,
  367. Timestamp: time.Now().Unix(),
  368. }
  369. }
  370. return entry
  371. }