session.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. package server
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "github.com/mkaminski/goaim/oscar"
  7. "log/slog"
  8. "sync"
  9. "time"
  10. )
  11. var (
  12. ErrSessNotFound = errors.New("session was not found")
  13. ErrSignedOff = errors.New("user signed off")
  14. )
  15. type SessSendStatus int
  16. const (
  17. // SessSendOK indicates message was sent to recipient
  18. SessSendOK SessSendStatus = iota
  19. // SessSendClosed indicates send did not complete because session is closed
  20. SessSendClosed
  21. // SessSendTimeout indicates send timed out due to blocked recipient
  22. SessSendTimeout
  23. )
  24. const sendTimeout = 10 * time.Second
  25. type Session struct {
  26. ID string
  27. ScreenName string
  28. msgCh chan XMessage
  29. stopCh chan struct{}
  30. Mutex sync.RWMutex
  31. Warning uint16
  32. AwayMessage string
  33. SignonTime time.Time
  34. invisible bool
  35. idle bool
  36. idleTime time.Time
  37. sendTimeout time.Duration
  38. closed bool
  39. }
  40. func (s *Session) IncreaseWarning(incr uint16) {
  41. s.Mutex.RLock()
  42. defer s.Mutex.RUnlock()
  43. s.Warning += incr
  44. }
  45. func (s *Session) SetInvisible(invisible bool) {
  46. s.Mutex.RLock()
  47. defer s.Mutex.RUnlock()
  48. s.invisible = invisible
  49. }
  50. func (s *Session) Invisible() bool {
  51. s.Mutex.RLock()
  52. defer s.Mutex.RUnlock()
  53. return s.invisible
  54. }
  55. func (s *Session) SetIdle(dur time.Duration) {
  56. s.Mutex.RLock()
  57. defer s.Mutex.RUnlock()
  58. s.idle = true
  59. // set the time the user became idle
  60. s.idleTime = time.Now().Add(-dur)
  61. }
  62. func (s *Session) SetActive() {
  63. s.Mutex.RLock()
  64. defer s.Mutex.RUnlock()
  65. s.idle = false
  66. }
  67. func (s *Session) Idle() bool {
  68. s.Mutex.RLock()
  69. defer s.Mutex.RUnlock()
  70. return s.idle
  71. }
  72. func (s *Session) SetAwayMessage(awayMessage string) {
  73. s.Mutex.RLock()
  74. defer s.Mutex.RUnlock()
  75. s.AwayMessage = awayMessage
  76. }
  77. func (s *Session) GetAwayMessage() string {
  78. s.Mutex.RLock()
  79. defer s.Mutex.RUnlock()
  80. return s.AwayMessage
  81. }
  82. func (s *Session) GetTLVUserInfo() oscar.TLVUserInfo {
  83. return oscar.TLVUserInfo{
  84. ScreenName: s.ScreenName,
  85. WarningLevel: s.GetWarning(),
  86. TLVBlock: oscar.TLVBlock{
  87. TLVList: s.GetUserInfo(),
  88. },
  89. }
  90. }
  91. func (s *Session) GetUserInfo() oscar.TLVList {
  92. s.Mutex.RLock()
  93. defer s.Mutex.RUnlock()
  94. // sign-in timestamp
  95. tlvs := oscar.TLVList{}
  96. tlvs.AddTLV(oscar.NewTLV(0x03, uint32(s.SignonTime.Unix())))
  97. // away message status
  98. if s.AwayMessage != "" {
  99. tlvs.AddTLV(oscar.NewTLV(0x01, uint16(0x0010)|uint16(0x0020)))
  100. } else {
  101. tlvs.AddTLV(oscar.NewTLV(0x01, uint16(0x0010)))
  102. }
  103. // invisibility status
  104. if s.invisible {
  105. tlvs.AddTLV(oscar.NewTLV(0x06, uint16(0x0100)))
  106. } else {
  107. tlvs.AddTLV(oscar.NewTLV(0x06, uint16(0x0000)))
  108. }
  109. // idle status
  110. if s.idle {
  111. tlvs.AddTLV(oscar.NewTLV(0x04, uint16(time.Now().Sub(s.idleTime).Seconds())))
  112. } else {
  113. tlvs.AddTLV(oscar.NewTLV(0x04, uint16(0)))
  114. }
  115. // capabilities
  116. var caps []byte
  117. // chat capability
  118. caps = append(caps, CapChat...)
  119. tlvs.AddTLV(oscar.NewTLV(0x0D, caps))
  120. return tlvs
  121. }
  122. func (s *Session) GetWarning() uint16 {
  123. var w uint16
  124. s.Mutex.RLock()
  125. w = s.Warning
  126. s.Mutex.RUnlock()
  127. return w
  128. }
  129. func (s *Session) RecvMessage() chan XMessage {
  130. return s.msgCh
  131. }
  132. func (s *Session) SendMessage(msg XMessage) SessSendStatus {
  133. select {
  134. case s.msgCh <- msg:
  135. return SessSendOK
  136. case <-s.stopCh:
  137. return SessSendClosed
  138. case <-time.After(s.sendTimeout):
  139. return SessSendTimeout
  140. }
  141. }
  142. func (s *Session) Close() {
  143. s.Mutex.Lock()
  144. defer s.Mutex.Unlock()
  145. if s.closed {
  146. return
  147. }
  148. close(s.stopCh)
  149. s.closed = true
  150. }
  151. func (s *Session) Closed() <-chan struct{} {
  152. return s.stopCh
  153. }
  154. type InMemorySessionManager struct {
  155. store map[string]*Session
  156. mapMutex sync.RWMutex
  157. logger *slog.Logger
  158. }
  159. func NewSessionManager(logger *slog.Logger) *InMemorySessionManager {
  160. return &InMemorySessionManager{
  161. logger: logger,
  162. store: make(map[string]*Session),
  163. }
  164. }
  165. func (s *InMemorySessionManager) Broadcast(ctx context.Context, msg XMessage) {
  166. s.mapMutex.RLock()
  167. defer s.mapMutex.RUnlock()
  168. for _, sess := range s.store {
  169. go s.maybeSendMessage(ctx, msg, sess)
  170. }
  171. }
  172. func (s *InMemorySessionManager) maybeSendMessage(ctx context.Context, msg XMessage, sess *Session) {
  173. switch sess.SendMessage(msg) {
  174. case SessSendClosed:
  175. s.logger.WarnContext(ctx, "can't send notification because the user's session is closed", "recipient", sess.ScreenName, "message", msg)
  176. case SessSendTimeout:
  177. s.logger.WarnContext(ctx, "can't send notification because of send timeout", "recipient", sess.ScreenName, "message", msg)
  178. sess.Close()
  179. }
  180. }
  181. func (s *InMemorySessionManager) Empty() bool {
  182. s.mapMutex.RLock()
  183. defer s.mapMutex.RUnlock()
  184. return len(s.store) == 0
  185. }
  186. func (s *InMemorySessionManager) Participants() []*Session {
  187. s.mapMutex.RLock()
  188. defer s.mapMutex.RUnlock()
  189. var sessions []*Session
  190. for _, sess := range s.store {
  191. sessions = append(sessions, sess)
  192. }
  193. return sessions
  194. }
  195. func (s *InMemorySessionManager) BroadcastExcept(ctx context.Context, except *Session, msg XMessage) {
  196. s.mapMutex.RLock()
  197. defer s.mapMutex.RUnlock()
  198. for _, sess := range s.store {
  199. if sess == except {
  200. continue
  201. }
  202. go s.maybeSendMessage(ctx, msg, sess)
  203. }
  204. }
  205. func (s *InMemorySessionManager) Retrieve(ID string) (*Session, bool) {
  206. s.mapMutex.RLock()
  207. defer s.mapMutex.RUnlock()
  208. sess, found := s.store[ID]
  209. return sess, found
  210. }
  211. func (s *InMemorySessionManager) RetrieveByScreenName(screenName string) (*Session, error) {
  212. s.mapMutex.RLock()
  213. defer s.mapMutex.RUnlock()
  214. for _, sess := range s.store {
  215. if screenName == sess.ScreenName {
  216. return sess, nil
  217. }
  218. }
  219. return nil, fmt.Errorf("%w: %s", ErrSessNotFound, screenName)
  220. }
  221. func (s *InMemorySessionManager) retrieveByScreenNames(screenNames []string) []*Session {
  222. s.mapMutex.RLock()
  223. defer s.mapMutex.RUnlock()
  224. var ret []*Session
  225. for _, sn := range screenNames {
  226. for _, sess := range s.store {
  227. if sn == sess.ScreenName {
  228. ret = append(ret, sess)
  229. }
  230. }
  231. }
  232. return ret
  233. }
  234. func (s *InMemorySessionManager) SendToScreenName(ctx context.Context, screenName string, msg XMessage) {
  235. sess, err := s.RetrieveByScreenName(screenName)
  236. if err != nil {
  237. s.logger.WarnContext(ctx, "can't send notification because user is not online", "recipient", screenName, "message", msg)
  238. return
  239. }
  240. go s.maybeSendMessage(ctx, msg, sess)
  241. }
  242. func (s *InMemorySessionManager) BroadcastToScreenNames(ctx context.Context, screenNames []string, msg XMessage) {
  243. for _, sess := range s.retrieveByScreenNames(screenNames) {
  244. go s.maybeSendMessage(ctx, msg, sess)
  245. }
  246. }
  247. func makeSession() *Session {
  248. return &Session{
  249. msgCh: make(chan XMessage, 1),
  250. stopCh: make(chan struct{}),
  251. sendTimeout: sendTimeout,
  252. SignonTime: time.Now(),
  253. }
  254. }
  255. func (s *InMemorySessionManager) NewSessionWithSN(sessID string, screenName string) *Session {
  256. s.mapMutex.Lock()
  257. defer s.mapMutex.Unlock()
  258. // Only allow one session at a time per screen name. A session may already
  259. // exist because:
  260. // 1) the user is signing on using an already logged-on screen name.
  261. // 2) the session might be orphaned due to an undetected client
  262. // disconnection.
  263. for _, sess := range s.store {
  264. if screenName == sess.ScreenName {
  265. sess.Close()
  266. delete(s.store, sess.ID)
  267. break
  268. }
  269. }
  270. sess := makeSession()
  271. sess.ID = sessID
  272. sess.ScreenName = screenName
  273. s.store[sess.ID] = sess
  274. return sess
  275. }
  276. func (s *InMemorySessionManager) Remove(sess *Session) {
  277. s.mapMutex.Lock()
  278. defer s.mapMutex.Unlock()
  279. delete(s.store, sess.ID)
  280. }
  281. type ChatRoom struct {
  282. CreateTime time.Time
  283. DetailLevel uint8
  284. Exchange uint16
  285. Cookie string
  286. InstanceNumber uint16
  287. Name string
  288. SessionManager
  289. }
  290. func (c ChatRoom) TLVList() []oscar.TLV {
  291. return []oscar.TLV{
  292. oscar.NewTLV(0x00c9, uint16(15)),
  293. oscar.NewTLV(0x00ca, uint32(c.CreateTime.Unix())),
  294. oscar.NewTLV(0x00d1, uint16(1024)),
  295. oscar.NewTLV(0x00d2, uint16(100)),
  296. oscar.NewTLV(0x00d5, uint8(2)),
  297. oscar.NewTLV(0x006a, c.Name),
  298. oscar.NewTLV(0x00d3, c.Name),
  299. }
  300. }
  301. type ChatRegistry struct {
  302. store map[string]ChatRoom
  303. mapMutex sync.RWMutex
  304. }
  305. func NewChatRegistry() *ChatRegistry {
  306. return &ChatRegistry{
  307. store: make(map[string]ChatRoom),
  308. }
  309. }
  310. func (c *ChatRegistry) Register(room ChatRoom) {
  311. c.mapMutex.Lock()
  312. defer c.mapMutex.Unlock()
  313. c.store[room.Cookie] = room
  314. }
  315. func (c *ChatRegistry) Retrieve(chatID string) (ChatRoom, error) {
  316. c.mapMutex.RLock()
  317. defer c.mapMutex.RUnlock()
  318. sm, found := c.store[chatID]
  319. if !found {
  320. return sm, errors.New("unable to find session manager for chat")
  321. }
  322. return sm, nil
  323. }
  324. func (c *ChatRegistry) MaybeRemoveRoom(chatID string) {
  325. c.mapMutex.Lock()
  326. defer c.mapMutex.Unlock()
  327. room, found := c.store[chatID]
  328. if found && room.Empty() {
  329. delete(c.store, chatID)
  330. }
  331. }