4
0

presence_handler.go 23 KB

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