events.go 7.4 KB

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