events.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. package types
  2. import (
  3. "context"
  4. "sync"
  5. "sync/atomic"
  6. "time"
  7. )
  8. // EventType defines the type of WebAPI event.
  9. type EventType string
  10. const (
  11. EventTypeBuddyList EventType = "buddylist"
  12. EventTypeConversation EventType = "conversation"
  13. EventTypeIM EventType = "im"
  14. EventTypeMyInfo EventType = "myInfo"
  15. EventTypeOfflineIM EventType = "offlineIM"
  16. EventTypePreference EventType = "preference"
  17. EventTypePresence EventType = "presence"
  18. EventTypeRateLimit EventType = "rateLimit"
  19. EventTypeSentIM EventType = "sentIM"
  20. EventTypeSessionEnded EventType = "sessionEnded"
  21. EventTypeStatus EventType = "status"
  22. EventTypeTyping EventType = "typing"
  23. EventTypePermitDeny EventType = "permitDeny"
  24. )
  25. // Event represents an event to be delivered to a web client.
  26. type Event struct {
  27. Type EventType `json:"type" xml:"type"`
  28. SeqNum uint64 `json:"seqNum" xml:"seqNum"`
  29. Timestamp int64 `json:"timestamp" xml:"timestamp"`
  30. Data interface{} `json:"eventData" xml:"eventData"`
  31. }
  32. // PresenceEvent represents a presence change event.
  33. // Friendly repeats the viewer's alias for the user. The client's merge deletes any
  34. // alias it already holds, so a presence update that omits it silently renames the
  35. // buddy back to their screen name. See UserInfo.
  36. type PresenceEvent struct {
  37. AimID string `json:"aimId" xml:"aimId"`
  38. Friendly string `json:"friendly,omitempty" xml:"friendly,omitempty"`
  39. State string `json:"state" xml:"state"` // "online", "offline", "away", "idle"
  40. StatusMsg string `json:"statusMsg,omitempty" xml:"statusMsg,omitempty"`
  41. AwayMsg string `json:"awayMsg,omitempty" xml:"awayMsg,omitempty"`
  42. IdleTime int `json:"idleTime,omitempty" xml:"idleTime,omitempty"` // Minutes idle
  43. OnlineTime int64 `json:"onlineTime,omitempty" xml:"onlineTime,omitempty"` // Unix timestamp
  44. UserType string `json:"userType" xml:"userType"` // "aim", "icq", "admin"
  45. BuddyIcon string `json:"buddyIcon,omitempty" xml:"buddyIcon,omitempty"` // Absolute icon URL; empty preserves the client's current icon, the placeholder URL clears it
  46. }
  47. // IMEvent represents an instant message event.
  48. type IMEvent struct {
  49. Source UserInfo `json:"source" xml:"source"`
  50. Message string `json:"message" xml:"message"`
  51. MsgID string `json:"msgId,omitempty" xml:"msgId,omitempty"`
  52. Timestamp float64 `json:"timestamp" xml:"timestamp"` // float64 for AMF3 encoding
  53. AutoResp bool `json:"autoresponse,omitempty" xml:"autoresponse,omitempty"`
  54. }
  55. // OfflineIMEvent represents a message that was stored while the user was signed
  56. // off and is replayed when they next start a session.
  57. //
  58. // The client models this separately from IMEvent: it reads the sender from a bare
  59. // aimId rather than a source user object, and resolves the display name from the
  60. // buddy list it already holds. Timestamp is when the sender sent the message, not
  61. // when it was delivered.
  62. type OfflineIMEvent struct {
  63. AimID string `json:"aimId" xml:"aimId"`
  64. Message string `json:"message" xml:"message"`
  65. MsgID string `json:"msgId,omitempty" xml:"msgId,omitempty"`
  66. Timestamp float64 `json:"timestamp" xml:"timestamp"` // float64 for AMF3 encoding
  67. AutoResp bool `json:"autoresponse,omitempty" xml:"autoresponse,omitempty"`
  68. }
  69. // SentIMEvent represents a sent instant message event.
  70. type SentIMEvent struct {
  71. Sender UserInfo `json:"sender" xml:"sender"` // Sender user info
  72. Dest UserInfo `json:"dest" xml:"dest"` // Destination user info
  73. Message string `json:"message" xml:"message"`
  74. MsgID string `json:"msgId,omitempty" xml:"msgId,omitempty"`
  75. Timestamp float64 `json:"timestamp" xml:"timestamp"` // float64 for AMF3 encoding
  76. AutoResp bool `json:"autoResponse,omitempty" xml:"autoResponse,omitempty"`
  77. }
  78. // UserInfo represents basic user information in events.
  79. // AimID is the normalized screen name the client keys users by. DisplayID is the
  80. // screen name as its owner formatted it. Friendly is the viewer's private alias for
  81. // that user, and takes precedence over DisplayID when the client renders a name.
  82. //
  83. // The client merges every user map it receives onto the single user object it holds
  84. // per aimId, and that merge deletes friendly before applying the map. An alias
  85. // therefore has to be repeated on every user map, or it is lost.
  86. type UserInfo struct {
  87. AimID string `json:"aimId" xml:"aimId"`
  88. DisplayID string `json:"displayId,omitempty" xml:"displayId,omitempty"`
  89. Friendly string `json:"friendly,omitempty" xml:"friendly,omitempty"`
  90. UserType string `json:"userType,omitempty" xml:"userType,omitempty"`
  91. State string `json:"state,omitempty" xml:"state,omitempty"`
  92. OnlineTime float64 `json:"onlineTime,omitempty" xml:"onlineTime,omitempty"` // float64 for AMF3 encoding
  93. }
  94. // TypingEvent represents a typing notification event.
  95. type TypingEvent struct {
  96. AimID string `json:"aimId" xml:"aimId"`
  97. TypingStatus string `json:"typingStatus" xml:"typingStatus"`
  98. }
  99. // RateLimitEvent tells the client that its rate limit status changed.
  100. //
  101. // The client reads classes[0] only: it takes the status string and feeds it
  102. // straight into a switch on "clear" | "warn" | "limit" | "disconnect" to render
  103. // the in-conversation alert (e.g. "You have been rate limited. Wait for a few
  104. // moments until you can chat again."). The "clear" alert is only shown if the
  105. // client's last recorded status was "limit", so this event must be pushed on
  106. // status transitions rather than on every rate-limited request.
  107. type RateLimitEvent struct {
  108. Classes []RateLimitClass `json:"classes" xml:"classes>class"`
  109. }
  110. // RateLimitClass is the per-rate-class state carried by a RateLimitEvent.
  111. type RateLimitClass struct {
  112. ID int `json:"id" xml:"id"`
  113. Status string `json:"status" xml:"status"` // "clear", "warn", "limit", or "disconnect"
  114. }
  115. // EventQueue manages a queue of events for a WebAPI session.
  116. type EventQueue struct {
  117. events []Event
  118. seqNum uint64
  119. maxSize int
  120. mu sync.RWMutex
  121. waitChan chan struct{}
  122. closeChan chan struct{}
  123. closeOnce sync.Once
  124. }
  125. // isClosed reports whether Close has been called.
  126. func (q *EventQueue) isClosed() bool {
  127. select {
  128. case <-q.closeChan:
  129. return true
  130. default:
  131. return false
  132. }
  133. }
  134. // NewEventQueue creates a new event queue with the specified maximum size.
  135. func NewEventQueue(maxSize int) *EventQueue {
  136. return &EventQueue{
  137. events: make([]Event, 0),
  138. maxSize: maxSize,
  139. waitChan: make(chan struct{}, 1),
  140. closeChan: make(chan struct{}),
  141. }
  142. }
  143. // Push adds an event to the queue.
  144. func (q *EventQueue) Push(eventType EventType, data interface{}) {
  145. if q.isClosed() {
  146. return
  147. }
  148. q.mu.Lock()
  149. defer q.mu.Unlock()
  150. // Increment sequence number atomically
  151. seqNum := atomic.AddUint64(&q.seqNum, 1)
  152. event := Event{
  153. Type: eventType,
  154. SeqNum: seqNum,
  155. Timestamp: time.Now().Unix(),
  156. Data: data,
  157. }
  158. // Add event to queue
  159. q.events = append(q.events, event)
  160. // If queue exceeds max size, remove oldest events
  161. if len(q.events) > q.maxSize {
  162. // Keep only the most recent maxSize events
  163. q.events = q.events[len(q.events)-q.maxSize:]
  164. }
  165. // Signal any waiting fetchers
  166. select {
  167. case q.waitChan <- struct{}{}:
  168. default:
  169. // Channel already has a signal
  170. }
  171. }
  172. // Fetch retrieves events from the queue, optionally waiting for new events.
  173. func (q *EventQueue) Fetch(ctx context.Context, lastSeqNum uint64, timeout time.Duration) ([]Event, error) {
  174. if q.isClosed() {
  175. return []Event{}, nil
  176. }
  177. // First, check if we have any events newer than lastSeqNum
  178. q.mu.RLock()
  179. events := q.getEventsAfter(lastSeqNum)
  180. q.mu.RUnlock()
  181. if len(events) > 0 {
  182. return events, nil
  183. }
  184. // No events available, wait for new ones or timeout
  185. timeoutChan := time.After(timeout)
  186. for {
  187. select {
  188. case <-q.closeChan:
  189. return []Event{}, nil
  190. case <-q.waitChan:
  191. // New events may be available
  192. q.mu.RLock()
  193. events = q.getEventsAfter(lastSeqNum)
  194. q.mu.RUnlock()
  195. if len(events) > 0 {
  196. return events, nil
  197. }
  198. // False alarm, keep waiting
  199. case <-timeoutChan:
  200. // Timeout reached, return empty array
  201. return []Event{}, nil
  202. case <-ctx.Done():
  203. // Context cancelled
  204. return nil, ctx.Err()
  205. }
  206. }
  207. }
  208. // getEventsAfter returns all events with sequence number greater than the specified value.
  209. // Must be called with at least a read lock held.
  210. func (q *EventQueue) getEventsAfter(seqNum uint64) []Event {
  211. var result []Event
  212. for _, event := range q.events {
  213. if event.SeqNum > seqNum {
  214. result = append(result, event)
  215. }
  216. }
  217. return result
  218. }
  219. // GetAllEvents returns all events in the queue (for debugging).
  220. func (q *EventQueue) GetAllEvents() []Event {
  221. q.mu.RLock()
  222. defer q.mu.RUnlock()
  223. result := make([]Event, len(q.events))
  224. copy(result, q.events)
  225. return result
  226. }
  227. // Close closes the event queue, unblocking any waiting fetchers. Safe to call
  228. // more than once.
  229. func (q *EventQueue) Close() {
  230. q.closeOnce.Do(func() {
  231. close(q.closeChan)
  232. })
  233. }