4
0

presence_handler.go 24 KB

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