presence.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  1. package handlers
  2. import (
  3. "context"
  4. "fmt"
  5. "log/slog"
  6. "net/http"
  7. "strings"
  8. "time"
  9. "github.com/mk6i/open-oscar-server/server/webapi/types"
  10. "github.com/mk6i/open-oscar-server/state"
  11. "github.com/mk6i/open-oscar-server/wire"
  12. )
  13. // PresenceHandler handles Web AIM API presence-related endpoints.
  14. type PresenceHandler struct {
  15. SessionManager *state.WebAPISessionManager
  16. FeedbagService FeedbagService
  17. BuddyBroadcaster BuddyBroadcaster
  18. LocateService LocateService
  19. Logger *slog.Logger
  20. }
  21. // LocateService issues OSCAR locate user-info queries. A single query performs
  22. // the blocking relationship check, the online/offline session lookup, and
  23. // returns the user's presence info plus optional profile and away-message data.
  24. type LocateService interface {
  25. SetInfo(ctx context.Context, instance *state.SessionInstance, inBody wire.SNAC_0x02_0x04_LocateSetInfo) error
  26. UserInfoQuery(ctx context.Context, instance *state.SessionInstance, inFrame wire.SNACFrame, inBody wire.SNAC_0x02_0x05_LocateUserInfoQuery) (wire.SNACMessage, error)
  27. }
  28. // BuddyBroadcaster broadcasts buddy presence updates
  29. type BuddyBroadcaster interface {
  30. BroadcastBuddyArrived(ctx context.Context, screenName state.IdentScreenName, userInfo wire.TLVUserInfo) error
  31. BroadcastBuddyDeparted(ctx context.Context, screenName state.IdentScreenName) error
  32. }
  33. // maxPresenceTargets caps how many screen names a single presence/get request
  34. // may query in target-list ("t=") mode.
  35. const maxPresenceTargets = 10
  36. // PresenceData contains presence information.
  37. type PresenceData struct {
  38. Groups []BuddyGroupInfo `json:"groups,omitempty" xml:"groups>group,omitempty"`
  39. Users []BuddyPresenceInfo `json:"users,omitempty" xml:"users>user,omitempty"`
  40. }
  41. // BuddyGroupInfo represents a buddy group with its members.
  42. type BuddyGroupInfo struct {
  43. Name string `json:"name" xml:"name"`
  44. Buddies []BuddyPresenceInfo `json:"buddies" xml:"buddies>buddy"`
  45. }
  46. // BuddyPresenceInfo represents presence information for a buddy.
  47. //
  48. // AimID is the normalized screen name the web client keys users by; DisplayID
  49. // preserves the casing and spacing the user signed on with. The client renders
  50. // DisplayID and falls back to AimID when it is absent.
  51. type BuddyPresenceInfo struct {
  52. AimID string `json:"aimId" xml:"aimId"`
  53. DisplayID string `json:"displayId,omitempty" xml:"displayId,omitempty"`
  54. Friendly string `json:"friendly,omitempty" xml:"friendly,omitempty"` // Viewer's private alias, rendered in preference to DisplayID
  55. State string `json:"state" xml:"state"` // "online", "offline", "away", "idle"
  56. StatusMsg string `json:"statusMsg,omitempty" xml:"statusMsg,omitempty"`
  57. AwayMsg string `json:"awayMsg,omitempty" xml:"awayMsg,omitempty"`
  58. ProfileMsg string `json:"profileMsg,omitempty" xml:"profileMsg,omitempty"`
  59. IdleTime int `json:"idleTime,omitempty" xml:"idleTime,omitempty"`
  60. OnlineTime int64 `json:"onlineTime,omitempty" xml:"onlineTime,omitempty"`
  61. UserType string `json:"userType" xml:"userType"` // "aim", "icq", "admin"
  62. }
  63. // GetPresence handles GET /presence/get requests.
  64. func (h *PresenceHandler) GetPresence(w http.ResponseWriter, r *http.Request, session *state.WebAPISession) {
  65. ctx := r.Context()
  66. aimsid := session.AimSID
  67. // Check if buddy list is requested
  68. getBuddyList := r.URL.Query().Get("bl") == "1"
  69. wantProfileMsg := r.URL.Query().Get("profileMsg") == "1"
  70. // Get target users if specified
  71. targetUsers := r.URL.Query().Get("t")
  72. // Prepare response
  73. resp := BaseResponse{}
  74. resp.Response.StatusCode = 200
  75. resp.Response.StatusText = "OK"
  76. // Create PresenceData struct to hold the response data
  77. presenceData := PresenceData{}
  78. if getBuddyList {
  79. // Retrieve buddy list from feedbag
  80. groups, err := h.getBuddyListGroups(ctx, session, wantProfileMsg)
  81. if err != nil {
  82. h.Logger.ErrorContext(ctx, "failed to get buddy list", "err", err.Error())
  83. // Return empty buddy list on error instead of failing
  84. groups = []BuddyGroupInfo{}
  85. }
  86. presenceData.Groups = groups
  87. } else if targetUsers != "" {
  88. // Get presence for specific users
  89. users := strings.Split(targetUsers, ",")
  90. if len(users) > maxPresenceTargets {
  91. h.sendError(w, http.StatusBadRequest, fmt.Sprintf("too many screen names requested (max %d)", maxPresenceTargets))
  92. return
  93. }
  94. presenceList := make([]BuddyPresenceInfo, 0, len(users))
  95. // The client's user-object merge deletes any alias it holds, so every
  96. // presence payload has to carry friendly for aliased buddies.
  97. aliases := session.Aliases(ctx)
  98. for _, user := range users {
  99. user = strings.TrimSpace(user)
  100. if user == "" {
  101. continue
  102. }
  103. info := h.getUserPresence(ctx, session.OSCARSession, state.DisplayScreenName(user), wantProfileMsg)
  104. info.Friendly = aliases[info.AimID]
  105. presenceList = append(presenceList, info)
  106. }
  107. presenceData.Users = presenceList
  108. } else {
  109. // No specific request, return empty data
  110. presenceData.Groups = []BuddyGroupInfo{}
  111. }
  112. // Set the data to the response
  113. resp.Response.Data = presenceData
  114. // Send response in requested format
  115. SendResponse(w, r, resp, h.Logger)
  116. h.Logger.DebugContext(ctx, "presence retrieved",
  117. "aimsid", aimsid,
  118. "buddy_list", getBuddyList,
  119. "targets", targetUsers,
  120. )
  121. }
  122. // getBuddyListGroups retrieves the buddy list organized by groups.
  123. func (h *PresenceHandler) getBuddyListGroups(ctx context.Context, session *state.WebAPISession, wantProfileMsg bool) ([]BuddyGroupInfo, error) {
  124. // Get feedbag items via the feedbag service
  125. frame := wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagQuery}
  126. reply, err := h.FeedbagService.Query(ctx, session.OSCARSession, frame)
  127. if err != nil {
  128. return nil, err
  129. }
  130. body, ok := reply.Body.(wire.SNAC_0x13_0x06_FeedbagReply)
  131. if !ok {
  132. return nil, fmt.Errorf("unexpected feedbag reply body type %T", reply.Body)
  133. }
  134. items := body.Items
  135. // Organize items into groups, keyed by GroupID. Group rows store their
  136. // identity in GroupID (ItemID is 0 for every group), so a GroupID-keyed map
  137. // is the only way to associate buddies — which reference their group via
  138. // GroupID — with the right group.
  139. groupMap := make(map[uint16]*BuddyGroupInfo)
  140. // First pass: identify groups. Skip the root group (GroupID 0), which holds
  141. // the master group order rather than buddies.
  142. for _, item := range items {
  143. if item.ClassID != wire.FeedbagClassIdGroup || item.GroupID == 0 {
  144. continue
  145. }
  146. name := item.Name
  147. if name == "" {
  148. name = "Buddies" // Default group name
  149. }
  150. groupMap[item.GroupID] = &BuddyGroupInfo{
  151. Name: name,
  152. Buddies: []BuddyPresenceInfo{},
  153. }
  154. }
  155. // Second pass: add buddies to their group with presence info.
  156. for _, item := range items {
  157. if item.ClassID != wire.FeedbagClassIdBuddy || item.Name == "" {
  158. continue
  159. }
  160. group, exists := groupMap[item.GroupID]
  161. if !exists {
  162. // Orphan buddy whose group row is missing: synthesize a default
  163. // group for its GroupID so the buddy is not dropped.
  164. group = &BuddyGroupInfo{Name: "Buddies", Buddies: []BuddyPresenceInfo{}}
  165. groupMap[item.GroupID] = group
  166. }
  167. // UserInfoQuery performs the blocking check and online lookup; blocked or
  168. // offline buddies come back as "offline", preserving the list structure.
  169. presence := h.getUserPresence(ctx, session.OSCARSession, state.DisplayScreenName(item.Name), wantProfileMsg)
  170. group.Buddies = append(group.Buddies, presence)
  171. }
  172. // If no groups exist at all, return a single default group.
  173. if len(groupMap) == 0 {
  174. groupMap[0] = &BuddyGroupInfo{
  175. Name: "Buddies",
  176. Buddies: []BuddyPresenceInfo{},
  177. }
  178. }
  179. // Convert map to slice
  180. groups := make([]BuddyGroupInfo, 0, len(groupMap))
  181. for _, group := range groupMap {
  182. groups = append(groups, *group)
  183. }
  184. return groups, nil
  185. }
  186. // getUserPresence resolves a user's presence by issuing a locate UserInfoQuery
  187. // on behalf of the requesting OSCAR session (instance). UserInfoQuery performs
  188. // the OSCAR blocking check and online lookup internally: blocked and offline
  189. // users both come back as a locate error, which we surface as "offline".
  190. func (h *PresenceHandler) getUserPresence(ctx context.Context, instance *state.SessionInstance, target state.DisplayScreenName, wantProfileMsg bool) BuddyPresenceInfo {
  191. ident := target.IdentScreenName()
  192. // Default offline presence
  193. presence := BuddyPresenceInfo{
  194. AimID: ident.String(),
  195. DisplayID: target.String(),
  196. State: "offline",
  197. UserType: "aim",
  198. }
  199. // Determine user type
  200. if strings.HasPrefix(ident.String(), "admin") {
  201. presence.UserType = "admin"
  202. } else if isICQScreenName(ident.String()) {
  203. presence.UserType = "icq"
  204. }
  205. // The unauthenticated icon endpoint resolves presence without a session, so
  206. // there may be no OSCAR instance to query on behalf of.
  207. if instance == nil {
  208. return presence
  209. }
  210. reqType := wire.LocateTypeUnavailable // away message
  211. if wantProfileMsg {
  212. reqType |= wire.LocateTypeSig // profile text
  213. }
  214. reply, err := h.LocateService.UserInfoQuery(ctx, instance, wire.SNACFrame{},
  215. wire.SNAC_0x02_0x05_LocateUserInfoQuery{Type: uint16(reqType), ScreenName: ident.String()})
  216. if err != nil {
  217. h.Logger.WarnContext(ctx, "failed to query user info", "screenName", ident.String(), "error", err)
  218. return presence
  219. }
  220. info, ok := reply.Body.(wire.SNAC_0x02_0x06_LocateUserInfoReply)
  221. if !ok {
  222. // Locate error => user is blocked or offline.
  223. return presence
  224. }
  225. presence.State = "online"
  226. // The locate reply carries the screen name as the user formatted it, which
  227. // beats whatever casing the caller happened to pass in.
  228. if info.ScreenName != "" {
  229. presence.DisplayID = info.ScreenName
  230. }
  231. if tod, ok := info.Uint32BE(wire.OServiceUserInfoSignonTOD); ok {
  232. presence.OnlineTime = int64(tod)
  233. }
  234. if info.IsAway() {
  235. presence.State = "away"
  236. } else if status, ok := info.Uint32BE(wire.OServiceUserInfoStatus); ok && status&wire.OServiceUserStatusDND != 0 {
  237. presence.State = "dnd"
  238. }
  239. if idle, ok := info.Uint16BE(wire.OServiceUserInfoIdleTime); ok && idle > 0 {
  240. presence.State = "idle"
  241. presence.IdleTime = int(idle)
  242. }
  243. if msg, ok := info.LocateInfo.String(wire.LocateTLVTagsInfoUnavailableData); ok {
  244. presence.AwayMsg = msg
  245. }
  246. if wantProfileMsg {
  247. if prof, ok := info.LocateInfo.String(wire.LocateTLVTagsInfoSigData); ok {
  248. presence.ProfileMsg = prof
  249. }
  250. }
  251. return presence
  252. }
  253. // isICQScreenName checks if a screen name is an ICQ number.
  254. func isICQScreenName(screenName string) bool {
  255. if len(screenName) == 0 {
  256. return false
  257. }
  258. for _, r := range screenName {
  259. if r < '0' || r > '9' {
  260. return false
  261. }
  262. }
  263. return true
  264. }
  265. // sendError is a convenience method that wraps the common SendError function.
  266. func (h *PresenceHandler) sendError(w http.ResponseWriter, statusCode int, message string) {
  267. SendError(w, statusCode, message)
  268. }
  269. // SetState handles GET /presence/setState requests to update user's presence state.
  270. func (h *PresenceHandler) SetState(w http.ResponseWriter, r *http.Request, session *state.WebAPISession) {
  271. ctx := r.Context()
  272. stateParam := r.URL.Query().Get("state")
  273. if stateParam == "" {
  274. stateParam = r.URL.Query().Get("view")
  275. }
  276. awayMsg := r.URL.Query().Get("awayMsg")
  277. if awayMsg == "" {
  278. awayMsg = r.URL.Query().Get("away")
  279. }
  280. oscarSession := session.OSCARSession
  281. // Map web state to OSCAR status bits
  282. var statusBitmask uint32
  283. switch stateParam {
  284. case "online":
  285. statusBitmask = 0x0000 // Clear all status bits
  286. oscarSession.SetAwayMessage("")
  287. oscarSession.ClearUserInfoFlag(wire.OServiceUserFlagUnavailable)
  288. case "away":
  289. statusBitmask = wire.OServiceUserStatusAway
  290. oscarSession.SetUserInfoFlag(wire.OServiceUserFlagUnavailable)
  291. if awayMsg != "" {
  292. oscarSession.SetAwayMessage(awayMsg)
  293. }
  294. case "invisible":
  295. statusBitmask = wire.OServiceUserStatusInvisible
  296. case "dnd":
  297. statusBitmask = wire.OServiceUserStatusDND
  298. default:
  299. h.sendError(w, http.StatusBadRequest, "invalid state parameter")
  300. return
  301. }
  302. // Update OSCAR session status
  303. oscarSession.SetUserStatusBitmask(statusBitmask)
  304. // Broadcast presence update
  305. if statusBitmask&wire.OServiceUserStatusInvisible != 0 {
  306. // User going invisible - broadcast departure
  307. if err := h.BuddyBroadcaster.BroadcastBuddyDeparted(ctx, oscarSession.IdentScreenName()); err != nil {
  308. h.Logger.ErrorContext(ctx, "failed to broadcast buddy departed", "err", err.Error())
  309. }
  310. } else {
  311. // User visible - broadcast arrival/update
  312. if err := h.BuddyBroadcaster.BroadcastBuddyArrived(ctx, oscarSession.IdentScreenName(), oscarSession.Session().TLVUserInfo()); err != nil {
  313. h.Logger.ErrorContext(ctx, "failed to broadcast buddy arrived", "err", err.Error())
  314. }
  315. }
  316. // Notify the user's own client so its status indicator re-renders. The AIM
  317. // client updates its self-presence badge only from "myInfo" events; the
  318. // "presence" broadcast above drives buddy dots, not the user's own state.
  319. // Without this, changing to Busy/Away leaves the user still showing as
  320. // available in their own UI.
  321. h.pushMyInfo(session, stateParam, awayMsg, "")
  322. h.Logger.InfoContext(ctx, "presence state updated",
  323. "screenName", session.ScreenName.String(),
  324. "state", stateParam,
  325. "hasAwayMsg", awayMsg != "",
  326. )
  327. // Send success response
  328. response := BaseResponse{}
  329. response.Response.StatusCode = 200
  330. response.Response.StatusText = "OK"
  331. response.Response.Data = map[string]interface{}{
  332. "aimId": session.ScreenName.IdentScreenName().String(),
  333. "displayId": session.ScreenName.String(),
  334. "state": stateParam,
  335. "awayMsg": awayMsg,
  336. "statusMsg": "",
  337. "userType": "aim",
  338. "onlineTime": time.Now().Unix(),
  339. }
  340. SendResponse(w, r, response, h.Logger)
  341. }
  342. // SetStatus handles GET /presence/setStatus requests to update user's status message.
  343. func (h *PresenceHandler) SetStatus(w http.ResponseWriter, r *http.Request, session *state.WebAPISession) {
  344. ctx := r.Context()
  345. // Get the status message
  346. statusMsg := r.URL.Query().Get("statusMsg")
  347. statusCode := r.URL.Query().Get("statusCode")
  348. // Store status message in session (this would normally be stored in a profile/status service)
  349. // For now, we'll broadcast it as part of presence
  350. oscarSession := session.OSCARSession
  351. // In OSCAR, status messages are typically part of the profile
  352. // We'll need to extend this based on the actual implementation
  353. // Broadcast presence update with new status
  354. if err := h.BuddyBroadcaster.BroadcastBuddyArrived(ctx, oscarSession.IdentScreenName(), oscarSession.Session().TLVUserInfo()); err != nil {
  355. h.Logger.ErrorContext(ctx, "failed to broadcast status update", "err", err.Error())
  356. }
  357. // Notify the user's own client so its status message re-renders. Preserve the
  358. // current presence state so a status-only change does not flip the self badge.
  359. h.pushMyInfo(session, currentWebState(oscarSession), oscarSession.Session().AwayMessage(), statusMsg)
  360. h.Logger.InfoContext(ctx, "status message updated",
  361. "screenName", session.ScreenName.String(),
  362. "statusMsg", statusMsg,
  363. "statusCode", statusCode,
  364. )
  365. // Send success response
  366. response := BaseResponse{}
  367. response.Response.StatusCode = 200
  368. response.Response.StatusText = "OK"
  369. SendResponse(w, r, response, h.Logger)
  370. }
  371. // SetProfile handles GET /presence/setProfile requests to update user's profile.
  372. func (h *PresenceHandler) SetProfile(w http.ResponseWriter, r *http.Request, session *state.WebAPISession) {
  373. ctx := r.Context()
  374. // Get the profile content
  375. profileText := r.URL.Query().Get("profile")
  376. // Limit profile size (4KB max)
  377. if len(profileText) > 4096 {
  378. h.sendError(w, http.StatusBadRequest, "profile too large (max 4KB)")
  379. return
  380. }
  381. instance := session.OSCARSession
  382. // Save profile via OSCAR LocateService.
  383. setInfo := wire.SNAC_0x02_0x04_LocateSetInfo{
  384. TLVRestBlock: wire.TLVRestBlock{
  385. TLVList: wire.TLVList{
  386. wire.NewTLVBE(wire.LocateTLVTagsInfoSigData, profileText),
  387. },
  388. },
  389. }
  390. if err := h.LocateService.SetInfo(ctx, instance, setInfo); err != nil {
  391. h.Logger.ErrorContext(ctx, "failed to set profile", "err", err.Error())
  392. h.sendError(w, http.StatusInternalServerError, "failed to save profile")
  393. return
  394. }
  395. h.Logger.InfoContext(ctx, "profile updated",
  396. "screenName", session.ScreenName.String(),
  397. "profileSize", len(profileText),
  398. )
  399. // Send success response
  400. response := BaseResponse{}
  401. response.Response.StatusCode = 200
  402. response.Response.StatusText = "OK"
  403. SendResponse(w, r, response, h.Logger)
  404. }
  405. // GetProfile handles GET /presence/getProfile requests to retrieve user's profile.
  406. func (h *PresenceHandler) GetProfile(w http.ResponseWriter, r *http.Request, session *state.WebAPISession) {
  407. ctx := r.Context()
  408. // Get target screen name (optional - defaults to self)
  409. targetSN := r.URL.Query().Get("sn")
  410. if targetSN == "" {
  411. targetSN = session.ScreenName.String()
  412. }
  413. // Retrieve profile via OSCAR LocateService.
  414. var profileText string
  415. instance := session.OSCARSession
  416. reply, err := h.LocateService.UserInfoQuery(ctx, instance, wire.SNACFrame{},
  417. wire.SNAC_0x02_0x05_LocateUserInfoQuery{Type: uint16(wire.LocateTypeSig), ScreenName: targetSN})
  418. if err != nil {
  419. h.Logger.WarnContext(ctx, "failed to get profile", "err", err.Error())
  420. } else if info, ok := reply.Body.(wire.SNAC_0x02_0x06_LocateUserInfoReply); ok {
  421. if prof, ok := info.LocateInfo.String(wire.LocateTLVTagsInfoSigData); ok {
  422. profileText = prof
  423. }
  424. }
  425. // Send response
  426. responseData := map[string]interface{}{
  427. "screenName": targetSN,
  428. "profile": profileText,
  429. "lastUpdated": int64(0),
  430. }
  431. response := BaseResponse{}
  432. response.Response.StatusCode = 200
  433. response.Response.StatusText = "OK"
  434. response.Response.Data = responseData
  435. SendResponse(w, r, response, h.Logger)
  436. }
  437. // Icon handles GET /presence/icon requests for presence icons.
  438. func (h *PresenceHandler) Icon(w http.ResponseWriter, r *http.Request) {
  439. // Get parameters
  440. name := r.URL.Query().Get("name")
  441. size := r.URL.Query().Get("size")
  442. iconType := r.URL.Query().Get("type")
  443. if name == "" {
  444. h.sendError(w, http.StatusBadRequest, "missing name parameter")
  445. return
  446. }
  447. // Default values
  448. if size == "" {
  449. size = "32"
  450. }
  451. if iconType == "" {
  452. iconType = "aim"
  453. }
  454. // For now, redirect to a placeholder icon
  455. // In production, this would redirect to actual icon storage/CDN
  456. var iconURL string
  457. // If it's an email lookup, extract username
  458. if strings.Contains(name, "@") {
  459. parts := strings.Split(name, "@")
  460. if len(parts) > 0 {
  461. name = parts[0]
  462. }
  463. }
  464. // Resolve the target's presence via OSCAR LocateService, querying on behalf
  465. // of the caller's session. This endpoint is unauthenticated, so fall back to
  466. // the offline icon when no valid session is supplied.
  467. var instance *state.SessionInstance
  468. if aimsid := r.URL.Query().Get("aimsid"); aimsid != "" {
  469. if session, err := h.SessionManager.GetSession(r.Context(), aimsid); err == nil {
  470. instance = session.OSCARSession
  471. }
  472. }
  473. switch h.getUserPresence(r.Context(), instance, state.DisplayScreenName(name), false).State {
  474. case "away":
  475. iconURL = "/static/icons/away_" + iconType + "_" + size + ".png"
  476. case "idle":
  477. iconURL = "/static/icons/idle_" + iconType + "_" + size + ".png"
  478. case "offline":
  479. iconURL = "/static/icons/offline_" + iconType + "_" + size + ".png"
  480. default:
  481. iconURL = "/static/icons/online_" + iconType + "_" + size + ".png"
  482. }
  483. // Redirect to icon URL
  484. http.Redirect(w, r, iconURL, http.StatusFound)
  485. }
  486. // currentWebState maps an OSCAR session's presence flags to the web state string
  487. // the AIM client expects ("online", "away", "idle", "invisible").
  488. func currentWebState(instance *state.SessionInstance) string {
  489. sess := instance.Session()
  490. switch {
  491. case sess.Invisible():
  492. return "invisible"
  493. case sess.Away():
  494. return "away"
  495. case instance.Idle():
  496. return "idle"
  497. default:
  498. return "online"
  499. }
  500. }
  501. // pushMyInfo queues a "myInfo" event on the user's own session so the AIM client
  502. // re-renders its self-presence badge. The client binds its identity-badge render
  503. // to "myInfo" events only, so state changes made via setState/setStatus are
  504. // invisible in the user's own UI unless a myInfo event is delivered.
  505. func (h *PresenceHandler) pushMyInfo(session *state.WebAPISession, webState, awayMsg, statusMsg string) {
  506. if session.EventQueue == nil {
  507. return
  508. }
  509. if !session.IsSubscribedTo("myInfo") && !session.IsSubscribedTo("presence") {
  510. return
  511. }
  512. screenName := session.ScreenName.String()
  513. myInfo := map[string]interface{}{
  514. "aimId": session.ScreenName.IdentScreenName().String(),
  515. "displayId": screenName,
  516. "friendly": screenName,
  517. "state": webState,
  518. "userType": "aim",
  519. }
  520. if awayMsg != "" {
  521. myInfo["awayMsg"] = awayMsg
  522. }
  523. if statusMsg != "" {
  524. myInfo["statusMsg"] = statusMsg
  525. }
  526. session.EventQueue.Push(types.EventType("myInfo"), myInfo)
  527. }