presence_handler.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785
  1. package webapi
  2. import (
  3. "context"
  4. "errors"
  5. "log/slog"
  6. "net/http"
  7. "slices"
  8. "strings"
  9. "time"
  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 *SessionManager
  16. FeedbagService FeedbagService
  17. LocateService LocateService
  18. OServiceService OServiceService
  19. IconSource BuddyIconSource
  20. Logger *slog.Logger
  21. }
  22. const maxPresenceTargets = 32
  23. // ProfileData is the getProfile payload.
  24. type ProfileData struct {
  25. ScreenName string `json:"screenName" xml:"screenName"`
  26. Profile string `json:"profile" xml:"profile"`
  27. LastUpdated int64 `json:"lastUpdated" xml:"lastUpdated"`
  28. }
  29. // SetStateData echoes the identity fields a setState changed.
  30. type SetStateData struct {
  31. AimID string `json:"aimId" xml:"aimId"`
  32. DisplayID string `json:"displayId" xml:"displayId"`
  33. State string `json:"state" xml:"state"`
  34. AwayMsg string `json:"awayMsg" xml:"awayMsg"`
  35. StatusMsg string `json:"statusMsg" xml:"statusMsg"`
  36. UserType string `json:"userType" xml:"userType"` // "aim", "icq"
  37. OnlineTime int64 `json:"onlineTime" xml:"onlineTime"`
  38. }
  39. // PresenceData contains presence information. Each query fills in one field and
  40. // leaves the other nil.
  41. //
  42. // omitzero, not omitempty: a query matching nothing must still render its key as an
  43. // empty array, since clients read data.groups and data.users strictly.
  44. type PresenceData struct {
  45. Groups []BuddyGroupInfo `json:"groups,omitzero" xml:"groups>group,omitempty"`
  46. Users []BuddyPresenceInfo `json:"users,omitzero" xml:"users>user,omitempty"`
  47. }
  48. // BuddyGroupInfo represents a buddy group with its members.
  49. type BuddyGroupInfo struct {
  50. Name string `json:"name" xml:"name"`
  51. Buddies []BuddyPresenceInfo `json:"buddies" xml:"buddies>buddy"`
  52. }
  53. // BuddyPresenceInfo represents presence information for a buddy.
  54. //
  55. // AimID is the normalized screen name the web client keys users by; DisplayID
  56. // preserves the casing and spacing the user signed on with. The client renders
  57. // DisplayID and falls back to AimID when it is absent.
  58. type BuddyPresenceInfo struct {
  59. AimID string `json:"aimId" xml:"aimId"`
  60. DisplayID string `json:"displayId,omitempty" xml:"displayId,omitempty"`
  61. Friendly string `json:"friendly,omitempty" xml:"friendly,omitempty"` // Viewer's private alias, rendered in preference to DisplayID
  62. State string `json:"state" xml:"state"` // "online", "offline", "away", "idle"
  63. StatusMsg string `json:"statusMsg,omitempty" xml:"statusMsg,omitempty"`
  64. AwayMsg string `json:"awayMsg,omitempty" xml:"awayMsg,omitempty"`
  65. ProfileMsg string `json:"profileMsg,omitempty" xml:"profileMsg,omitempty"`
  66. IdleTime int `json:"idleTime,omitempty" xml:"idleTime,omitempty"`
  67. OnlineTime int64 `json:"onlineTime,omitempty" xml:"onlineTime,omitempty"`
  68. UserType string `json:"userType" xml:"userType"` // "aim", "icq"
  69. Service string `json:"service,omitempty" xml:"service,omitempty"` // Non-native network; omitted for AIM
  70. BuddyIcon string `json:"buddyIcon,omitempty" xml:"buddyIcon,omitempty"`
  71. MoodIcon string `json:"moodIcon,omitempty" xml:"moodIcon,omitempty"`
  72. // Profile carries member-directory fields, present only under mdir=1. It must be
  73. // non-nil even when empty: clients treat a missing profile as "not a user".
  74. Profile *BuddyProfileInfo `json:"profile,omitempty" xml:"profile,omitempty"`
  75. }
  76. // BuddyProfileInfo is the nested "profile" object carried under mdir=1. Gender and
  77. // birth date are absent because the directory record has nowhere to store them.
  78. type BuddyProfileInfo struct {
  79. FriendlyName string `json:"friendlyName,omitempty" xml:"friendlyName,omitempty"`
  80. FirstName string `json:"firstName,omitempty" xml:"firstName,omitempty"`
  81. LastName string `json:"lastName,omitempty" xml:"lastName,omitempty"`
  82. HomeAddress []BuddyAddressInfo `json:"homeAddress,omitempty" xml:"homeAddress,omitempty"`
  83. }
  84. // BuddyAddressInfo is one entry of a profile's homeAddress array.
  85. type BuddyAddressInfo struct {
  86. City string `json:"city,omitempty" xml:"city,omitempty"`
  87. State string `json:"state,omitempty" xml:"state,omitempty"`
  88. Country string `json:"country,omitempty" xml:"country,omitempty"`
  89. }
  90. // GetPresence handles GET /presence/get requests.
  91. func (h *PresenceHandler) GetPresence(w http.ResponseWriter, r *http.Request, session *Session) {
  92. ctx := r.Context()
  93. aimsid := session.AimSID
  94. getBuddyList := r.URL.Query().Get("bl") == "1"
  95. wantProfileMsg := r.URL.Query().Get("profileMsg") == "1"
  96. // mdir asks for member-directory fields alongside presence.
  97. wantDirInfo := isTrueParam(r.URL.Query().Get("mdir"))
  98. targetUsers := targetNames(r)
  99. // Create PresenceData struct to hold the response data
  100. presenceData := PresenceData{}
  101. if getBuddyList {
  102. // Retrieve buddy list from feedbag
  103. groups, err := h.getBuddyListGroups(ctx, session, wantProfileMsg)
  104. if err != nil {
  105. h.Logger.ErrorContext(ctx, "failed to get buddy list", "err", err.Error())
  106. // Return empty buddy list on error instead of failing
  107. groups = []BuddyGroupInfo{}
  108. }
  109. presenceData.Groups = groups
  110. } else if len(targetUsers) > 0 {
  111. // Get presence for specific users
  112. if len(targetUsers) > maxPresenceTargets {
  113. // truncate rather than reject
  114. h.Logger.WarnContext(ctx, "presence get: truncating oversized target list",
  115. "aimsid", session.AimSID,
  116. "requested", len(targetUsers),
  117. "cap", maxPresenceTargets,
  118. )
  119. targetUsers = targetUsers[:maxPresenceTargets]
  120. }
  121. presenceList := make([]BuddyPresenceInfo, 0, len(targetUsers))
  122. // The client's user-object merge deletes any alias it holds, so every
  123. // presence payload has to carry friendly for aliased buddies.
  124. aliases := session.Aliases(ctx)
  125. for _, user := range targetUsers {
  126. info := h.targetPresence(ctx, session, state.DisplayScreenName(user), wantProfileMsg)
  127. info.Friendly = aliases[info.AimID]
  128. if wantDirInfo {
  129. info.Profile = h.directoryProfile(ctx, user)
  130. }
  131. presenceList = append(presenceList, info)
  132. }
  133. presenceData.Users = presenceList
  134. } else {
  135. presenceData.Groups = []BuddyGroupInfo{}
  136. presenceData.Users = []BuddyPresenceInfo{}
  137. }
  138. SendOK(w, r, presenceData, h.Logger)
  139. h.Logger.DebugContext(ctx, "presence retrieved",
  140. "aimsid", aimsid,
  141. "buddy_list", getBuddyList,
  142. "targets", targetUsers,
  143. )
  144. }
  145. // directoryProfile reads a user's member-directory record for the mdir=1 profile
  146. // object. It never returns nil: a user with no directory record must still appear
  147. // as an empty profile rather than be dropped.
  148. func (h *PresenceHandler) directoryProfile(ctx context.Context, screenName string) *BuddyProfileInfo {
  149. profile := &BuddyProfileInfo{}
  150. reply, err := h.LocateService.DirInfo(ctx, wire.SNACFrame{}, wire.SNAC_0x02_0x0B_LocateGetDirInfo{ScreenName: screenName})
  151. if err != nil {
  152. h.Logger.ErrorContext(ctx, "presence: directory lookup failed",
  153. "screenName", screenName, "err", err.Error())
  154. return profile
  155. }
  156. body, ok := reply.Body.(wire.SNAC_0x02_0x0C_LocateGetDirReply)
  157. if !ok {
  158. return profile
  159. }
  160. profile.FirstName, _ = body.String(wire.ODirTLVFirstName)
  161. profile.LastName, _ = body.String(wire.ODirTLVLastName)
  162. profile.FriendlyName, _ = body.String(wire.ODirTLVNickName)
  163. city, _ := body.String(wire.ODirTLVCity)
  164. stateName, _ := body.String(wire.ODirTLVState)
  165. country, _ := body.String(wire.ODirTLVCountry)
  166. if city != "" || stateName != "" || country != "" {
  167. profile.HomeAddress = []BuddyAddressInfo{{City: city, State: stateName, Country: country}}
  168. }
  169. return profile
  170. }
  171. // getBuddyListGroups retrieves the buddy list organized by groups.
  172. func (h *PresenceHandler) getBuddyListGroups(ctx context.Context, session *Session, wantProfileMsg bool) ([]BuddyGroupInfo, error) {
  173. items, err := session.Feedbag(ctx)
  174. if err != nil {
  175. return nil, err
  176. }
  177. // Organize items into groups, keyed by GroupID. Group rows store their
  178. // identity in GroupID (ItemID is 0 for every group), so a GroupID-keyed map
  179. // is the only way to associate buddies — which reference their group via
  180. // GroupID — with the right group.
  181. groupMap := make(map[uint16]*BuddyGroupInfo)
  182. // First pass: identify groups. Skip the root group (GroupID 0), which holds
  183. // the master group order rather than buddies.
  184. for _, item := range items {
  185. if item.ClassID != wire.FeedbagClassIdGroup || item.GroupID == 0 {
  186. continue
  187. }
  188. name := item.Name
  189. if name == "" {
  190. name = "Buddies" // Default group name
  191. }
  192. groupMap[item.GroupID] = &BuddyGroupInfo{
  193. Name: name,
  194. Buddies: []BuddyPresenceInfo{},
  195. }
  196. }
  197. // Second pass: add buddies to their group with presence info.
  198. for _, item := range items {
  199. if item.ClassID != wire.FeedbagClassIdBuddy || item.Name == "" {
  200. continue
  201. }
  202. group, exists := groupMap[item.GroupID]
  203. if !exists {
  204. // Orphan buddy whose group row is missing: synthesize a default
  205. // group for its GroupID so the buddy is not dropped.
  206. group = &BuddyGroupInfo{Name: "Buddies", Buddies: []BuddyPresenceInfo{}}
  207. groupMap[item.GroupID] = group
  208. }
  209. // Served from the presence view, where blocked and offline buddies alike
  210. // come back as "offline". profileMsg is the exception: profile text is only
  211. // reachable through a locate reply.
  212. var presence BuddyPresenceInfo
  213. if wantProfileMsg {
  214. presence = h.getUserPresence(ctx, session.OSCARSession, session.BaseURL, state.DisplayScreenName(item.Name), true)
  215. } else {
  216. presence = h.cachedPresence(ctx, session, item.Name)
  217. }
  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. // offlinePresenceInfo is the presence a user renders as when the session has no
  235. // maintained record of them.
  236. func offlinePresenceInfo(ident state.IdentScreenName, target string) BuddyPresenceInfo {
  237. return BuddyPresenceInfo{
  238. AimID: ident.String(),
  239. DisplayID: target,
  240. State: "offline",
  241. UserType: userTypeFor(ident),
  242. Service: serviceFor(ident),
  243. }
  244. }
  245. // cachedPresence renders a user's presence from the session's presence view. A
  246. // user the view has never seen renders offline, as does one who blocks the
  247. // caller: the broadcaster sends them a departure rather than an arrival.
  248. //
  249. // ProfileMsg is absent; callers that want it take the locate path. AwayMsg costs
  250. // a locate query per unavailable buddy.
  251. func (h *PresenceHandler) cachedPresence(ctx context.Context, session *Session, target string) BuddyPresenceInfo {
  252. ident := state.NewIdentScreenName(target)
  253. presence, ok := session.BuddyPresence(ident)
  254. if !ok {
  255. return offlinePresenceInfo(ident, target)
  256. }
  257. return h.presenceInfo(ctx, session, target, presence)
  258. }
  259. // presenceInfo renders a presence record the caller has already read out of the
  260. // view. Callers that branched on a cache hit pass the record in, so an eviction
  261. // racing them cannot turn the hit into an offline reading.
  262. func (h *PresenceHandler) presenceInfo(ctx context.Context, session *Session, target string, presence BuddyPresence) BuddyPresenceInfo {
  263. ident := state.NewIdentScreenName(target)
  264. info := offlinePresenceInfo(ident, target)
  265. // A departure keeps the last display name seen, which beats the normalized
  266. // spelling the caller passed in.
  267. if presence.DisplayID != "" {
  268. info.DisplayID = presence.DisplayID
  269. }
  270. info.State = presence.State
  271. info.StatusMsg = presence.StatusMsg
  272. info.OnlineTime = presence.OnlineTime
  273. info.IdleTime = presence.IdleTime
  274. if !presence.Online() {
  275. // Offline and blocking users publish no icon, so neither their icon nor
  276. // its activity-revealing hash leaks to a caller they are invisible to.
  277. return info
  278. }
  279. if hasAwayMsg(presence.State) {
  280. info.AwayMsg = awayMessage(ctx, h.LocateService, session.OSCARSession, ident, h.Logger)
  281. }
  282. // The presence SNAC carried the icon hash, so no metadata lookup is needed.
  283. info.BuddyIcon = h.IconSource.URLForHash(session.BaseURL, ident, presence.IconHash)
  284. info.MoodIcon = moodIconURL(session.BaseURL, presence.State, presence.Caps)
  285. return info
  286. }
  287. // targetPresence resolves one of the users named by presence/get?t=. Unlike the
  288. // roster, a target need not be a buddy, so a user missing from the view gets a
  289. // locate query rather than reading as offline. profileMsg takes that path too.
  290. func (h *PresenceHandler) targetPresence(ctx context.Context, session *Session, target state.DisplayScreenName, wantProfileMsg bool) BuddyPresenceInfo {
  291. if !wantProfileMsg {
  292. if presence, ok := session.BuddyPresence(target.IdentScreenName()); ok {
  293. return h.presenceInfo(ctx, session, target.String(), presence)
  294. }
  295. }
  296. return h.getUserPresence(ctx, session.OSCARSession, session.BaseURL, target, wantProfileMsg)
  297. }
  298. // getUserPresence resolves a user's presence by issuing a locate UserInfoQuery
  299. // on behalf of the requesting OSCAR session (instance). UserInfoQuery performs
  300. // the OSCAR blocking check and online lookup internally: blocked and offline
  301. // users both come back as a locate error, which we surface as "offline".
  302. func (h *PresenceHandler) getUserPresence(ctx context.Context, instance *state.SessionInstance, baseURL string, target state.DisplayScreenName, wantProfileMsg bool) BuddyPresenceInfo {
  303. ident := target.IdentScreenName()
  304. // Default offline presence
  305. presence := BuddyPresenceInfo{
  306. AimID: ident.String(),
  307. DisplayID: target.String(),
  308. State: "offline",
  309. UserType: userTypeFor(ident),
  310. Service: serviceFor(ident),
  311. }
  312. // The unauthenticated icon endpoint resolves presence without a session, so
  313. // there may be no OSCAR instance to query on behalf of.
  314. if instance == nil {
  315. return presence
  316. }
  317. reqType := wire.LocateTypeUnavailable // away message
  318. if wantProfileMsg {
  319. reqType |= wire.LocateTypeSig // profile text
  320. }
  321. reply, err := h.LocateService.UserInfoQuery(ctx, instance, wire.SNACFrame{},
  322. wire.SNAC_0x02_0x05_LocateUserInfoQuery{Type: uint16(reqType), ScreenName: ident.String()})
  323. if err != nil {
  324. h.Logger.WarnContext(ctx, "failed to query user info", "screenName", ident.String(), "error", err)
  325. return presence
  326. }
  327. info, ok := reply.Body.(wire.SNAC_0x02_0x06_LocateUserInfoReply)
  328. if !ok {
  329. // Locate error => user is blocked or offline.
  330. return presence
  331. }
  332. presence.State, presence.IdleTime = buddyWebState(info.TLVUserInfo, instance.IdentScreenName().UIN() == 0)
  333. // An offline user publishes nothing; locate still answers for an invisible one.
  334. if presence.State == "offline" {
  335. return presence
  336. }
  337. // Offline, blocking and invisible users return before this, so neither their
  338. // icon nor its activity-revealing hash leaks to a caller they are hidden from.
  339. presence.BuddyIcon = h.IconSource.PublishedURL(ctx, baseURL, ident)
  340. // The locate reply carries the screen name as the user formatted it, which
  341. // beats whatever casing the caller happened to pass in.
  342. if info.ScreenName != "" {
  343. presence.DisplayID = info.ScreenName
  344. }
  345. if tod, ok := info.Uint32BE(wire.OServiceUserInfoSignonTOD); ok {
  346. presence.OnlineTime = int64(tod)
  347. }
  348. if msg, ok := info.LocateInfo.String(wire.LocateTLVTagsInfoUnavailableData); ok {
  349. presence.AwayMsg = msg
  350. }
  351. if wantProfileMsg {
  352. if prof, ok := info.LocateInfo.String(wire.LocateTLVTagsInfoSigData); ok {
  353. presence.ProfileMsg = prof
  354. }
  355. }
  356. presence.MoodIcon = moodIconURL(baseURL, presence.State, userInfoCaps(info.TLVUserInfo))
  357. presence.StatusMsg = userStatusMsg(info.TLVUserInfo)
  358. return presence
  359. }
  360. // SetState handles GET /presence/setState requests to update user's presence state.
  361. func (h *PresenceHandler) SetState(w http.ResponseWriter, r *http.Request, session *Session) {
  362. ctx := r.Context()
  363. stateParam := r.URL.Query().Get("state")
  364. if stateParam == "" {
  365. stateParam = r.URL.Query().Get("view")
  366. }
  367. awayMsg := r.URL.Query().Get("awayMsg")
  368. if awayMsg == "" {
  369. awayMsg = r.URL.Query().Get("away")
  370. }
  371. oscarSession := session.OSCARSession
  372. // Map web state to OSCAR status bits. setAwayMsg reports whether the away
  373. // message needs rewriting: only going online clears it, and only an away
  374. // state with text replaces it, so the other states keep what is there.
  375. var statusBitmask uint32
  376. var setAwayMsg bool
  377. switch stateParam {
  378. case "online":
  379. statusBitmask = 0x0000 // Clear all status bits
  380. awayMsg = ""
  381. setAwayMsg = true
  382. case "away":
  383. statusBitmask = wire.OServiceUserStatusAway
  384. setAwayMsg = awayMsg != ""
  385. case "invisible":
  386. statusBitmask = wire.OServiceUserStatusInvisible
  387. case "dnd":
  388. statusBitmask = wire.OServiceUserStatusDND
  389. case "occupied":
  390. // ICQ's Busy, a distinct status bit from DND.
  391. statusBitmask = wire.OServiceUserStatusBusy
  392. default:
  393. SendError(w, r, http.StatusBadRequest, "invalid state parameter")
  394. return
  395. }
  396. // Set the away message first, so that the user info update the status change
  397. // relays back carries the new message.
  398. if setAwayMsg {
  399. setInfo := wire.SNAC_0x02_0x04_LocateSetInfo{
  400. TLVRestBlock: wire.TLVRestBlock{
  401. TLVList: wire.TLVList{
  402. wire.NewTLVBE(wire.LocateTLVTagsInfoUnavailableData, awayMsg),
  403. },
  404. },
  405. }
  406. if err := h.LocateService.SetInfo(ctx, oscarSession, setInfo); err != nil {
  407. h.Logger.ErrorContext(ctx, "failed to set away message", "err", err.Error())
  408. SendError(w, r, http.StatusInternalServerError, "failed to set state")
  409. return
  410. }
  411. }
  412. setFields := wire.SNAC_0x01_0x1E_OServiceSetUserInfoFields{
  413. TLVRestBlock: wire.TLVRestBlock{
  414. TLVList: wire.TLVList{
  415. wire.NewTLVBE(wire.OServiceUserInfoStatus, statusBitmask),
  416. },
  417. },
  418. }
  419. if err := h.OServiceService.SetUserInfoFields(ctx, oscarSession, wire.SNACFrame{}, setFields); err != nil {
  420. h.Logger.ErrorContext(ctx, "failed to set user info fields", "err", err.Error())
  421. SendError(w, r, http.StatusInternalServerError, "failed to set state")
  422. return
  423. }
  424. reportedState := stateParam
  425. if st := statusMaskState(statusBitmask, oscarSession.IdentScreenName().UIN() == 0); st != "" {
  426. reportedState = st
  427. }
  428. h.Logger.InfoContext(ctx, "presence state updated",
  429. "screenName", session.ScreenName.String(),
  430. "state", stateParam,
  431. "hasAwayMsg", awayMsg != "",
  432. )
  433. SendOK(w, r, &SetStateData{
  434. AimID: session.ScreenName.IdentScreenName().String(),
  435. DisplayID: session.ScreenName.String(),
  436. State: reportedState,
  437. AwayMsg: awayMsg,
  438. StatusMsg: sessionStatusMsg(oscarSession),
  439. UserType: userTypeFor(session.ScreenName.IdentScreenName()),
  440. OnlineTime: time.Now().Unix(),
  441. }, h.Logger)
  442. }
  443. // SetStatus handles GET /presence/setStatus requests to update user's status message.
  444. func (h *PresenceHandler) SetStatus(w http.ResponseWriter, r *http.Request, session *Session) {
  445. ctx := r.Context()
  446. statusMsg := r.URL.Query().Get("statusMsg")
  447. statusCode := r.URL.Query().Get("statusCode")
  448. if r.URL.Query().Has("statusMsg") {
  449. var bid wire.BARTID
  450. if err := bid.SetStatusText(statusMsg); err != nil {
  451. if errors.Is(err, wire.ErrStatusTextSizeExceeded) {
  452. SendError(w, r, http.StatusBadRequest, err.Error())
  453. } else {
  454. h.Logger.ErrorContext(ctx, "failed to marshal status message", "err", err.Error())
  455. SendError(w, r, http.StatusInternalServerError, "failed to set status")
  456. }
  457. return
  458. }
  459. setFields := wire.SNAC_0x01_0x1E_OServiceSetUserInfoFields{
  460. TLVRestBlock: wire.TLVRestBlock{
  461. TLVList: wire.TLVList{
  462. wire.NewTLVBE(wire.OServiceUserInfoBARTInfo, bid),
  463. },
  464. },
  465. }
  466. if err := h.OServiceService.SetUserInfoFields(ctx, session.OSCARSession, wire.SNACFrame{}, setFields); err != nil {
  467. h.Logger.ErrorContext(ctx, "failed to set user info fields", "err", err.Error())
  468. SendError(w, r, http.StatusInternalServerError, "failed to set status")
  469. return
  470. }
  471. }
  472. if r.URL.Query().Has("mood") {
  473. moodID := r.URL.Query().Get("mood")
  474. if moodID == "" {
  475. session.ClearMood()
  476. } else {
  477. m, hasMood := wire.MoodByID(moodID)
  478. if !hasMood {
  479. SendError(w, r, http.StatusBadRequest, "invalid mood ID")
  480. return
  481. }
  482. session.SetMood(m.Cap)
  483. }
  484. setInfo := wire.SNAC_0x02_0x04_LocateSetInfo{
  485. TLVRestBlock: wire.TLVRestBlock{
  486. TLVList: wire.TLVList{
  487. wire.NewTLVBE(wire.LocateTLVTagsInfoCapabilities, session.Caps()),
  488. },
  489. },
  490. }
  491. if err := h.LocateService.SetInfo(ctx, session.OSCARSession, setInfo); err != nil {
  492. h.Logger.ErrorContext(ctx, "failed to set mood capability", "err", err.Error())
  493. SendError(w, r, http.StatusInternalServerError, "failed to save status")
  494. return
  495. }
  496. }
  497. h.Logger.InfoContext(ctx, "status message updated",
  498. "screenName", session.ScreenName.String(),
  499. "statusMsg", statusMsg,
  500. "statusCode", statusCode,
  501. "mood", r.URL.Query().Get("mood"),
  502. )
  503. SendOK(w, r, nil, h.Logger)
  504. }
  505. // SetProfile handles GET /presence/setProfile requests to update user's profile.
  506. func (h *PresenceHandler) SetProfile(w http.ResponseWriter, r *http.Request, session *Session) {
  507. ctx := r.Context()
  508. profileText := r.URL.Query().Get("profile")
  509. if len(profileText) > 4096 {
  510. SendError(w, r, http.StatusBadRequest, "profile too large (max 4KB)")
  511. return
  512. }
  513. instance := session.OSCARSession
  514. // Save profile via OSCAR LocateService.
  515. setInfo := wire.SNAC_0x02_0x04_LocateSetInfo{
  516. TLVRestBlock: wire.TLVRestBlock{
  517. TLVList: wire.TLVList{
  518. wire.NewTLVBE(wire.LocateTLVTagsInfoSigData, profileText),
  519. },
  520. },
  521. }
  522. if err := h.LocateService.SetInfo(ctx, instance, setInfo); err != nil {
  523. h.Logger.ErrorContext(ctx, "failed to set profile", "err", err.Error())
  524. SendError(w, r, http.StatusInternalServerError, "failed to save profile")
  525. return
  526. }
  527. h.Logger.InfoContext(ctx, "profile updated",
  528. "screenName", session.ScreenName.String(),
  529. "profileSize", len(profileText),
  530. )
  531. SendOK(w, r, nil, h.Logger)
  532. }
  533. // GetProfile handles GET /presence/getProfile requests to retrieve user's profile.
  534. func (h *PresenceHandler) GetProfile(w http.ResponseWriter, r *http.Request, session *Session) {
  535. ctx := r.Context()
  536. targetSN := r.URL.Query().Get("sn")
  537. if targetSN == "" {
  538. targetSN = session.ScreenName.String()
  539. }
  540. var profileText string
  541. instance := session.OSCARSession
  542. reply, err := h.LocateService.UserInfoQuery(ctx, instance, wire.SNACFrame{},
  543. wire.SNAC_0x02_0x05_LocateUserInfoQuery{Type: uint16(wire.LocateTypeSig), ScreenName: targetSN})
  544. if err != nil {
  545. h.Logger.WarnContext(ctx, "failed to get profile", "err", err.Error())
  546. } else if info, ok := reply.Body.(wire.SNAC_0x02_0x06_LocateUserInfoReply); ok {
  547. if prof, ok := info.LocateInfo.String(wire.LocateTLVTagsInfoSigData); ok {
  548. profileText = prof
  549. }
  550. }
  551. responseData := &ProfileData{ScreenName: targetSN, Profile: profileText}
  552. SendOK(w, r, responseData, h.Logger)
  553. }
  554. // Icon handles GET /presence/icon requests for presence icons.
  555. func (h *PresenceHandler) Icon(w http.ResponseWriter, r *http.Request) {
  556. name := r.URL.Query().Get("name")
  557. size := r.URL.Query().Get("size")
  558. iconType := r.URL.Query().Get("type")
  559. if name == "" {
  560. SendError(w, r, http.StatusBadRequest, "missing name parameter")
  561. return
  562. }
  563. // Default values
  564. if size == "" {
  565. size = "32"
  566. }
  567. if iconType == "" {
  568. iconType = "aim"
  569. }
  570. // For now, redirect to a placeholder icon
  571. // In production, this would redirect to actual icon storage/CDN
  572. var iconURL string
  573. // If it's an email lookup, extract username
  574. if strings.Contains(name, "@") {
  575. parts := strings.Split(name, "@")
  576. if len(parts) > 0 {
  577. name = parts[0]
  578. }
  579. }
  580. // Resolve the target's presence via OSCAR LocateService, querying on behalf
  581. // of the caller's session. This endpoint is unauthenticated, so fall back to
  582. // the offline icon when no valid session is supplied.
  583. var instance *state.SessionInstance
  584. if aimsid := r.URL.Query().Get("aimsid"); aimsid != "" {
  585. if session, err := h.SessionManager.GetSession(r.Context(), aimsid); err == nil {
  586. instance = session.OSCARSession
  587. }
  588. }
  589. // This endpoint serves a presence state badge, not the user's buddy icon, so
  590. // it has no use for a buddy icon URL.
  591. switch h.getUserPresence(r.Context(), instance, "", state.DisplayScreenName(name), false).State {
  592. // occupied and dnd have no badge of their own and both mean unavailable.
  593. case "away", "occupied", "dnd":
  594. iconURL = "/static/icons/away_" + iconType + "_" + size + ".png"
  595. case "idle":
  596. iconURL = "/static/icons/idle_" + iconType + "_" + size + ".png"
  597. case "offline":
  598. iconURL = "/static/icons/offline_" + iconType + "_" + size + ".png"
  599. default:
  600. iconURL = "/static/icons/online_" + iconType + "_" + size + ".png"
  601. }
  602. // Redirect to icon URL
  603. http.Redirect(w, r, iconURL, http.StatusFound)
  604. }
  605. // statusBitState reports the web state named by a user's ICQ status bits, or ""
  606. // when neither Busy nor DND is set. Callers must consult it before IsAway(): Busy
  607. // and DND also raise the unavailable flag, so an away-first test reports every busy
  608. // user as away.
  609. func statusBitState(info wire.TLVUserInfo, isAIMCaller bool) string {
  610. status, ok := info.Uint32BE(wire.OServiceUserInfoStatus)
  611. if !ok {
  612. return ""
  613. }
  614. return statusMaskState(status, isAIMCaller)
  615. }
  616. // statusMaskState names the web state a status bitmask describes, or "" when
  617. // neither Busy nor DND is set.
  618. func statusMaskState(status uint32, isAIMCaller bool) string {
  619. var st string
  620. switch {
  621. case status&wire.OServiceUserStatusBusy != 0:
  622. st = "occupied"
  623. case status&wire.OServiceUserStatusDND != 0:
  624. st = "dnd"
  625. default:
  626. return ""
  627. }
  628. if isAIMCaller {
  629. return "away"
  630. }
  631. return st
  632. }
  633. // selfWebState maps a user's own user info block to the web state string the
  634. // clients expect ("online", "away", "idle", "invisible", "occupied", "dnd").
  635. // Invisibility yields "invisible", not the "offline" a buddy sees.
  636. func selfWebState(info wire.TLVUserInfo, isAIMCaller bool) string {
  637. if info.IsInvisible() {
  638. return "invisible"
  639. }
  640. if st := statusBitState(info, isAIMCaller); st != "" {
  641. return st
  642. }
  643. if info.IsAway() {
  644. return "away"
  645. }
  646. if mask, ok := info.Uint32BE(wire.OServiceUserInfoStatus); ok && mask&wire.OServiceUserStatusAway != 0 {
  647. return "away"
  648. }
  649. if idle, ok := info.Uint16BE(wire.OServiceUserInfoIdleTime); ok && idle > 0 {
  650. return "idle"
  651. }
  652. return "online"
  653. }
  654. // userInfoCaps returns the capability UUIDs a user info block advertises.
  655. func userInfoCaps(info wire.TLVUserInfo) [][16]byte {
  656. b, ok := info.Bytes(wire.OServiceUserInfoOscarCaps)
  657. if !ok {
  658. return nil
  659. }
  660. caps := make([][16]byte, 0, len(b)/16)
  661. for chunk := range slices.Chunk(b, 16) {
  662. if len(chunk) < 16 {
  663. break
  664. }
  665. caps = append(caps, [16]byte(chunk))
  666. }
  667. return caps
  668. }
  669. // moodIconURL returns the mood icon URL for the mood advertised in caps, or ""
  670. // when there is none. A mood supersedes webState on the client, so a user who is
  671. // not visibly online never gets one.
  672. func moodIconURL(baseURL, webState string, caps [][16]byte) string {
  673. if webState == "offline" || webState == "invisible" {
  674. return ""
  675. }
  676. for _, c := range caps {
  677. if m, ok := wire.MoodByCap(c); ok {
  678. return baseURL + "/mood?id=" + wire.MoodIconID(m.ID)
  679. }
  680. }
  681. return ""
  682. }