presence.go 21 KB

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