events.go 12 KB

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