events.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. package webapi
  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. 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" xml:"type"`
  27. SeqNum uint64 `json:"seqNum" xml:"seqNum"`
  28. Timestamp int64 `json:"timestamp" xml:"timestamp"`
  29. Data interface{} `json:"eventData" xml:"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" xml:"aimId"`
  37. Friendly string `json:"friendly,omitempty" xml:"friendly,omitempty"`
  38. State string `json:"state" xml:"state"` // "online", "offline", "away", "idle"
  39. StatusMsg string `json:"statusMsg,omitempty" xml:"statusMsg,omitempty"`
  40. AwayMsg string `json:"awayMsg,omitempty" xml:"awayMsg,omitempty"`
  41. IdleTime int `json:"idleTime,omitempty" xml:"idleTime,omitempty"` // Minutes idle
  42. OnlineTime int64 `json:"onlineTime,omitempty" xml:"onlineTime,omitempty"` // Unix timestamp
  43. UserType string `json:"userType" xml:"userType"` // "aim", "icq", "admin"
  44. BuddyIcon string `json:"buddyIcon,omitempty" xml:"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" xml:"source"`
  49. Message string `json:"message" xml:"message"`
  50. MsgID string `json:"msgId,omitempty" xml:"msgId,omitempty"`
  51. Timestamp int64 `json:"timestamp" xml:"timestamp"`
  52. // AutoResp is always sent to AMF clients, false included, because the client
  53. // reads it unconditionally when it builds the message.
  54. AutoResp bool `json:"autoresponse,omitempty" xml:"autoresponse,omitempty" amf3:"autoresponse"`
  55. }
  56. // OfflineIMEvent represents a message that was stored while the user was signed
  57. // off and is replayed when they next start a session.
  58. //
  59. // The client models this separately from IMEvent: it reads the sender from a bare
  60. // aimId rather than a source user object, and resolves the display name from the
  61. // buddy list it already holds. Timestamp is when the sender sent the message, not
  62. // when it was delivered.
  63. type OfflineIMEvent struct {
  64. AimID string `json:"aimId" xml:"aimId"`
  65. // Friendly is the sender's display name. The client resolves an offline
  66. // sender from this pair alone, so without it the message renders under the
  67. // normalized aimId.
  68. Friendly string `json:"friendly,omitempty" xml:"friendly,omitempty"`
  69. Message string `json:"message" xml:"message"`
  70. MsgID string `json:"msgId,omitempty" xml:"msgId,omitempty"`
  71. Timestamp int64 `json:"timestamp" xml:"timestamp"`
  72. AutoResp bool `json:"autoresponse,omitempty" xml:"autoresponse,omitempty" amf3:"autoresponse"`
  73. }
  74. // SentIMEvent represents a sent instant message event.
  75. // The AMF3 spellings differ from the documented JSON ones: the client reads the
  76. // sender from "source" and the flag from "autoresponse", while the spec names
  77. // them "sender" and "autoResponse".
  78. type SentIMEvent struct {
  79. Sender UserInfo `json:"sender" xml:"sender" amf3:"source"`
  80. Dest UserInfo `json:"dest" xml:"dest"`
  81. Message string `json:"message" xml:"message"`
  82. MsgID string `json:"msgId,omitempty" xml:"msgId,omitempty"`
  83. Timestamp int64 `json:"timestamp" xml:"timestamp"`
  84. AutoResp bool `json:"autoResponse,omitempty" xml:"autoResponse,omitempty" amf3:"autoresponse"`
  85. }
  86. // UserInfo represents basic user information in events.
  87. // AimID is the normalized screen name the client keys users by. DisplayID is the
  88. // screen name as its owner formatted it. Friendly is the viewer's private alias for
  89. // that user, and takes precedence over DisplayID when the client renders a name.
  90. //
  91. // The client merges every user map it receives onto the single user object it holds
  92. // per aimId, and that merge deletes friendly before applying the map. An alias
  93. // therefore has to be repeated on every user map, or it is lost.
  94. type UserInfo struct {
  95. AimID string `json:"aimId" xml:"aimId"`
  96. DisplayID string `json:"displayId,omitempty" xml:"displayId,omitempty"`
  97. Friendly string `json:"friendly,omitempty" xml:"friendly,omitempty"`
  98. UserType string `json:"userType,omitempty" xml:"userType,omitempty"`
  99. State string `json:"state,omitempty" xml:"state,omitempty"`
  100. OnlineTime int64 `json:"onlineTime,omitempty" xml:"onlineTime,omitempty"`
  101. }
  102. // TypingEvent represents a typing notification event.
  103. type TypingEvent struct {
  104. AimID string `json:"aimId" xml:"aimId"`
  105. TypingStatus string `json:"typingStatus" xml:"typingStatus"`
  106. }
  107. // RateLimitEvent tells the client that its rate limit status changed.
  108. //
  109. // The client reads classes[0] only: it takes the status string and feeds it
  110. // straight into a switch on "clear" | "warn" | "limit" | "disconnect" to render
  111. // the in-conversation alert (e.g. "You have been rate limited. Wait for a few
  112. // moments until you can chat again."). The "clear" alert is only shown if the
  113. // client's last recorded status was "limit", so this event must be pushed on
  114. // status transitions rather than on every rate-limited request.
  115. type RateLimitEvent struct {
  116. Classes []RateLimitClass `json:"classes" xml:"classes>class"`
  117. }
  118. // RateLimitClass is the per-rate-class state carried by a RateLimitEvent.
  119. type RateLimitClass struct {
  120. ID int `json:"id" xml:"id"`
  121. Status string `json:"status" xml:"status"` // "clear", "warn", "limit", or "disconnect"
  122. }
  123. // EventQueue manages a queue of events for a WebAPI session.
  124. type EventQueue struct {
  125. events []Event
  126. seqNum uint64
  127. maxSize int
  128. mu sync.RWMutex
  129. waitChan chan struct{}
  130. closeChan chan struct{}
  131. closeOnce sync.Once
  132. }
  133. // isClosed reports whether Close has been called.
  134. func (q *EventQueue) isClosed() bool {
  135. select {
  136. case <-q.closeChan:
  137. return true
  138. default:
  139. return false
  140. }
  141. }
  142. // NewEventQueue creates a new event queue with the specified maximum size.
  143. func NewEventQueue(maxSize int) *EventQueue {
  144. return &EventQueue{
  145. events: make([]Event, 0),
  146. maxSize: maxSize,
  147. waitChan: make(chan struct{}, 1),
  148. closeChan: make(chan struct{}),
  149. }
  150. }
  151. // Push adds an event to the queue.
  152. func (q *EventQueue) Push(eventType EventType, data interface{}) {
  153. if q.isClosed() {
  154. return
  155. }
  156. q.mu.Lock()
  157. defer q.mu.Unlock()
  158. // Increment sequence number atomically
  159. seqNum := atomic.AddUint64(&q.seqNum, 1)
  160. event := Event{
  161. Type: eventType,
  162. SeqNum: seqNum,
  163. Timestamp: time.Now().Unix(),
  164. Data: data,
  165. }
  166. // Add event to queue
  167. q.events = append(q.events, event)
  168. // If queue exceeds max size, remove oldest events
  169. if len(q.events) > q.maxSize {
  170. // Keep only the most recent maxSize events
  171. q.events = q.events[len(q.events)-q.maxSize:]
  172. }
  173. // Signal any waiting fetchers
  174. select {
  175. case q.waitChan <- struct{}{}:
  176. default:
  177. // Channel already has a signal
  178. }
  179. }
  180. // Fetch retrieves events from the queue, optionally waiting for new events.
  181. func (q *EventQueue) Fetch(ctx context.Context, lastSeqNum uint64, timeout time.Duration) ([]Event, error) {
  182. if q.isClosed() {
  183. return []Event{}, nil
  184. }
  185. // First, check if we have any events newer than lastSeqNum
  186. q.mu.RLock()
  187. events := q.getEventsAfter(lastSeqNum)
  188. q.mu.RUnlock()
  189. if len(events) > 0 {
  190. return events, nil
  191. }
  192. // No events available, wait for new ones or timeout
  193. timeoutChan := time.After(timeout)
  194. for {
  195. select {
  196. case <-q.closeChan:
  197. return []Event{}, nil
  198. case <-q.waitChan:
  199. // New events may be available
  200. q.mu.RLock()
  201. events = q.getEventsAfter(lastSeqNum)
  202. q.mu.RUnlock()
  203. if len(events) > 0 {
  204. return events, nil
  205. }
  206. // False alarm, keep waiting
  207. case <-timeoutChan:
  208. // Timeout reached, return empty array
  209. return []Event{}, nil
  210. case <-ctx.Done():
  211. // Context cancelled
  212. return nil, ctx.Err()
  213. }
  214. }
  215. }
  216. // getEventsAfter returns all events with sequence number greater than the specified value.
  217. // Must be called with at least a read lock held.
  218. func (q *EventQueue) getEventsAfter(seqNum uint64) []Event {
  219. var result []Event
  220. for _, event := range q.events {
  221. if event.SeqNum > seqNum {
  222. result = append(result, event)
  223. }
  224. }
  225. return result
  226. }
  227. // GetAllEvents returns all events in the queue (for debugging).
  228. func (q *EventQueue) GetAllEvents() []Event {
  229. q.mu.RLock()
  230. defer q.mu.RUnlock()
  231. result := make([]Event, len(q.events))
  232. copy(result, q.events)
  233. return result
  234. }
  235. // Close closes the event queue, unblocking any waiting fetchers. Safe to call
  236. // more than once.
  237. func (q *EventQueue) Close() {
  238. q.closeOnce.Do(func() {
  239. close(q.closeChan)
  240. })
  241. }
  242. // ConversationData is a conversation event payload: an operation and the
  243. // conversations it applies to.
  244. type ConversationData struct {
  245. Operation string `json:"operation" xml:"operation"`
  246. Conversations []ConversationEntryData `json:"conversations" xml:"conversations>conversation"`
  247. }
  248. // ConversationEntryData is one conversation in the client's list.
  249. type ConversationEntryData struct {
  250. AimID string `json:"aimId" xml:"aimId"`
  251. // Active is always sent, zero included, because the client reads it
  252. // unconditionally.
  253. Active int `json:"active" xml:"active"`
  254. UnreadCount int `json:"unreadCount" xml:"unreadCount"`
  255. // DisplayID is omitted when empty rather than sent blank: the client falls
  256. // back to the name it already has for aimID, whereas any value present here
  257. // replaces it.
  258. DisplayID string `json:"displayId,omitempty" xml:"displayId,omitempty"`
  259. LastIM *LastIM `json:"lastIM,omitempty" xml:"lastIM,omitempty"`
  260. }
  261. // LastIM is the most recent message in a conversation.
  262. type LastIM struct {
  263. Message string `json:"message" xml:"message"`
  264. MsgID string `json:"msgId" xml:"msgId"`
  265. Sender string `json:"sender" xml:"sender"`
  266. Sent bool `json:"sent" xml:"sent"`
  267. Timestamp int64 `json:"timestamp" xml:"timestamp"`
  268. }
  269. // ConversationEventData builds a conversation fetchEvents payload.
  270. func ConversationEventData(operation string, conversations []ConversationEntryData) *ConversationData {
  271. if conversations == nil {
  272. conversations = []ConversationEntryData{}
  273. }
  274. return &ConversationData{
  275. Operation: operation,
  276. Conversations: conversations,
  277. }
  278. }
  279. // ConversationEntry builds one conversation object for the Web AIM client.
  280. func ConversationEntry(aimID, displayID, message, msgID, sender string, sent bool, unread int) ConversationEntryData {
  281. entry := ConversationEntryData{
  282. AimID: aimID,
  283. Active: 0,
  284. UnreadCount: unread,
  285. DisplayID: displayID,
  286. }
  287. if message != "" {
  288. entry.LastIM = &LastIM{
  289. Message: message,
  290. MsgID: msgID,
  291. Sender: sender,
  292. Sent: sent,
  293. Timestamp: time.Now().Unix(),
  294. }
  295. }
  296. return entry
  297. }