presence.go 21 KB

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