4
0

presence_handler.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759
  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. fl := state.NewFeedbagList(items, nil)
  178. var groups []BuddyGroupInfo
  179. for _, group := range fl.Groups() {
  180. name := group.Name
  181. if name == "" {
  182. name = "Buddies" // Default group name
  183. }
  184. info := BuddyGroupInfo{Name: name, Buddies: []BuddyPresenceInfo{}}
  185. for _, buddy := range fl.Buddies(group) {
  186. if buddy.Name == "" {
  187. continue
  188. }
  189. // Served from the presence view, where blocked and offline buddies
  190. // alike come back as "offline". profileMsg is the exception: profile
  191. // text is only reachable through a locate reply.
  192. var presence BuddyPresenceInfo
  193. if wantProfileMsg {
  194. presence = h.getUserPresence(ctx, session.OSCARSession, session.BaseURL, state.DisplayScreenName(buddy.Name), true)
  195. } else {
  196. presence = h.cachedPresence(ctx, session, buddy.Name)
  197. }
  198. // The client's user-object merge deletes any alias it holds, so the
  199. // buddy list has to carry friendly for aliased buddies.
  200. presence.Friendly, _ = buddy.String(wire.FeedbagAttributesAlias)
  201. info.Buddies = append(info.Buddies, presence)
  202. }
  203. groups = append(groups, info)
  204. }
  205. // If no groups exist at all, return a single default group.
  206. if len(groups) == 0 {
  207. groups = []BuddyGroupInfo{{Name: "Buddies", Buddies: []BuddyPresenceInfo{}}}
  208. }
  209. return groups, nil
  210. }
  211. // offlinePresenceInfo is the presence a user renders as when the session has no
  212. // maintained record of them.
  213. func offlinePresenceInfo(ident state.IdentScreenName, target string) BuddyPresenceInfo {
  214. return BuddyPresenceInfo{
  215. AimID: ident.String(),
  216. DisplayID: target,
  217. State: "offline",
  218. UserType: userTypeFor(ident),
  219. Service: serviceFor(ident),
  220. }
  221. }
  222. // cachedPresence renders a user's presence from the session's presence view. A
  223. // user the view has never seen renders offline, as does one who blocks the
  224. // caller: the broadcaster sends them a departure rather than an arrival.
  225. //
  226. // ProfileMsg is absent; callers that want it take the locate path. AwayMsg costs
  227. // a locate query per unavailable buddy.
  228. func (h *PresenceHandler) cachedPresence(ctx context.Context, session *Session, target string) BuddyPresenceInfo {
  229. ident := state.NewIdentScreenName(target)
  230. presence, ok := session.BuddyPresence(ident)
  231. if !ok {
  232. return offlinePresenceInfo(ident, target)
  233. }
  234. return h.presenceInfo(ctx, session, target, presence)
  235. }
  236. // presenceInfo renders a presence record the caller has already read out of the
  237. // view. Callers that branched on a cache hit pass the record in, so an eviction
  238. // racing them cannot turn the hit into an offline reading.
  239. func (h *PresenceHandler) presenceInfo(ctx context.Context, session *Session, target string, presence BuddyPresence) BuddyPresenceInfo {
  240. ident := state.NewIdentScreenName(target)
  241. info := offlinePresenceInfo(ident, target)
  242. // A departure keeps the last display name seen, which beats the normalized
  243. // spelling the caller passed in.
  244. if presence.DisplayID != "" {
  245. info.DisplayID = presence.DisplayID
  246. }
  247. info.State = presence.State
  248. info.StatusMsg = presence.StatusMsg
  249. info.OnlineTime = presence.OnlineTime
  250. info.IdleTime = presence.IdleTime
  251. if !presence.Online() {
  252. // Offline and blocking users publish no icon, so neither their icon nor
  253. // its activity-revealing hash leaks to a caller they are invisible to.
  254. return info
  255. }
  256. if hasAwayMsg(presence.State) {
  257. info.AwayMsg = awayMessage(ctx, h.LocateService, session.OSCARSession, ident, h.Logger)
  258. }
  259. // The presence SNAC carried the icon hash, so no metadata lookup is needed.
  260. info.BuddyIcon = h.IconSource.URLForHash(session.BaseURL, ident, presence.IconHash)
  261. info.MoodIcon = moodIconURL(session.BaseURL, presence.State, presence.Caps)
  262. return info
  263. }
  264. // targetPresence resolves one of the users named by presence/get?t=. Unlike the
  265. // roster, a target need not be a buddy, so a user missing from the view gets a
  266. // locate query rather than reading as offline. profileMsg takes that path too.
  267. func (h *PresenceHandler) targetPresence(ctx context.Context, session *Session, target state.DisplayScreenName, wantProfileMsg bool) BuddyPresenceInfo {
  268. if !wantProfileMsg {
  269. if presence, ok := session.BuddyPresence(target.IdentScreenName()); ok {
  270. return h.presenceInfo(ctx, session, target.String(), presence)
  271. }
  272. }
  273. return h.getUserPresence(ctx, session.OSCARSession, session.BaseURL, target, wantProfileMsg)
  274. }
  275. // getUserPresence resolves a user's presence by issuing a locate UserInfoQuery
  276. // on behalf of the requesting OSCAR session (instance). UserInfoQuery performs
  277. // the OSCAR blocking check and online lookup internally: blocked and offline
  278. // users both come back as a locate error, which we surface as "offline".
  279. func (h *PresenceHandler) getUserPresence(ctx context.Context, instance *state.SessionInstance, baseURL string, target state.DisplayScreenName, wantProfileMsg bool) BuddyPresenceInfo {
  280. ident := target.IdentScreenName()
  281. // Default offline presence
  282. presence := BuddyPresenceInfo{
  283. AimID: ident.String(),
  284. DisplayID: target.String(),
  285. State: "offline",
  286. UserType: userTypeFor(ident),
  287. Service: serviceFor(ident),
  288. }
  289. // The unauthenticated icon endpoint resolves presence without a session, so
  290. // there may be no OSCAR instance to query on behalf of.
  291. if instance == nil {
  292. return presence
  293. }
  294. reqType := wire.LocateTypeUnavailable // away message
  295. if wantProfileMsg {
  296. reqType |= wire.LocateTypeSig // profile text
  297. }
  298. reply, err := h.LocateService.UserInfoQuery(ctx, instance, wire.SNACFrame{},
  299. wire.SNAC_0x02_0x05_LocateUserInfoQuery{Type: uint16(reqType), ScreenName: ident.String()})
  300. if err != nil {
  301. h.Logger.WarnContext(ctx, "failed to query user info", "screenName", ident.String(), "error", err)
  302. return presence
  303. }
  304. info, ok := reply.Body.(wire.SNAC_0x02_0x06_LocateUserInfoReply)
  305. if !ok {
  306. // Locate error => user is blocked or offline.
  307. return presence
  308. }
  309. presence.State, presence.IdleTime = buddyWebState(info.TLVUserInfo, instance.IdentScreenName().UIN() == 0)
  310. // An offline user publishes nothing; locate still answers for an invisible one.
  311. if presence.State == "offline" {
  312. return presence
  313. }
  314. // Offline, blocking and invisible users return before this, so neither their
  315. // icon nor its activity-revealing hash leaks to a caller they are hidden from.
  316. presence.BuddyIcon = h.IconSource.PublishedURL(ctx, baseURL, ident)
  317. // The locate reply carries the screen name as the user formatted it, which
  318. // beats whatever casing the caller happened to pass in.
  319. if info.ScreenName != "" {
  320. presence.DisplayID = info.ScreenName
  321. }
  322. if tod, ok := info.Uint32BE(wire.OServiceUserInfoSignonTOD); ok {
  323. presence.OnlineTime = int64(tod)
  324. }
  325. if msg, ok := info.LocateInfo.String(wire.LocateTLVTagsInfoUnavailableData); ok {
  326. presence.AwayMsg = msg
  327. }
  328. if wantProfileMsg {
  329. if prof, ok := info.LocateInfo.String(wire.LocateTLVTagsInfoSigData); ok {
  330. presence.ProfileMsg = prof
  331. }
  332. }
  333. presence.MoodIcon = moodIconURL(baseURL, presence.State, userInfoCaps(info.TLVUserInfo))
  334. presence.StatusMsg = userStatusMsg(info.TLVUserInfo)
  335. return presence
  336. }
  337. // SetState handles GET /presence/setState requests to update user's presence state.
  338. func (h *PresenceHandler) SetState(w http.ResponseWriter, r *http.Request, session *Session) {
  339. ctx := r.Context()
  340. stateParam := r.URL.Query().Get("state")
  341. if stateParam == "" {
  342. stateParam = r.URL.Query().Get("view")
  343. }
  344. awayMsg := r.URL.Query().Get("awayMsg")
  345. if awayMsg == "" {
  346. awayMsg = r.URL.Query().Get("away")
  347. }
  348. oscarSession := session.OSCARSession
  349. // Map web state to OSCAR status bits. setAwayMsg reports whether the away
  350. // message needs rewriting: only going online clears it, and only an away
  351. // state with text replaces it, so the other states keep what is there.
  352. var statusBitmask uint32
  353. var setAwayMsg bool
  354. switch stateParam {
  355. case "online":
  356. statusBitmask = 0x0000 // Clear all status bits
  357. awayMsg = ""
  358. setAwayMsg = true
  359. case "away":
  360. statusBitmask = wire.OServiceUserStatusAway
  361. setAwayMsg = awayMsg != ""
  362. case "invisible":
  363. statusBitmask = wire.OServiceUserStatusInvisible
  364. case "dnd":
  365. statusBitmask = wire.OServiceUserStatusDND
  366. case "occupied":
  367. // ICQ's Busy, a distinct status bit from DND.
  368. statusBitmask = wire.OServiceUserStatusBusy
  369. default:
  370. SendError(w, r, http.StatusBadRequest, "invalid state parameter")
  371. return
  372. }
  373. // Set the away message first, so that the user info update the status change
  374. // relays back carries the new message.
  375. if setAwayMsg {
  376. setInfo := wire.SNAC_0x02_0x04_LocateSetInfo{
  377. TLVRestBlock: wire.TLVRestBlock{
  378. TLVList: wire.TLVList{
  379. wire.NewTLVBE(wire.LocateTLVTagsInfoUnavailableData, awayMsg),
  380. },
  381. },
  382. }
  383. if err := h.LocateService.SetInfo(ctx, oscarSession, setInfo); err != nil {
  384. h.Logger.ErrorContext(ctx, "failed to set away message", "err", err.Error())
  385. SendError(w, r, http.StatusInternalServerError, "failed to set state")
  386. return
  387. }
  388. }
  389. setFields := wire.SNAC_0x01_0x1E_OServiceSetUserInfoFields{
  390. TLVRestBlock: wire.TLVRestBlock{
  391. TLVList: wire.TLVList{
  392. wire.NewTLVBE(wire.OServiceUserInfoStatus, statusBitmask),
  393. },
  394. },
  395. }
  396. if err := h.OServiceService.SetUserInfoFields(ctx, oscarSession, wire.SNACFrame{}, setFields); err != nil {
  397. h.Logger.ErrorContext(ctx, "failed to set user info fields", "err", err.Error())
  398. SendError(w, r, http.StatusInternalServerError, "failed to set state")
  399. return
  400. }
  401. reportedState := stateParam
  402. if st := statusMaskState(statusBitmask, oscarSession.IdentScreenName().UIN() == 0); st != "" {
  403. reportedState = st
  404. }
  405. h.Logger.InfoContext(ctx, "presence state updated",
  406. "screenName", session.ScreenName.String(),
  407. "state", stateParam,
  408. "hasAwayMsg", awayMsg != "",
  409. )
  410. SendOK(w, r, &SetStateData{
  411. AimID: session.ScreenName.IdentScreenName().String(),
  412. DisplayID: session.ScreenName.String(),
  413. State: reportedState,
  414. AwayMsg: awayMsg,
  415. StatusMsg: sessionStatusMsg(oscarSession),
  416. UserType: userTypeFor(session.ScreenName.IdentScreenName()),
  417. OnlineTime: time.Now().Unix(),
  418. }, h.Logger)
  419. }
  420. // SetStatus handles GET /presence/setStatus requests to update user's status message.
  421. func (h *PresenceHandler) SetStatus(w http.ResponseWriter, r *http.Request, session *Session) {
  422. ctx := r.Context()
  423. statusMsg := r.URL.Query().Get("statusMsg")
  424. statusCode := r.URL.Query().Get("statusCode")
  425. if r.URL.Query().Has("statusMsg") {
  426. var bid wire.BARTID
  427. if err := bid.SetStatusText(statusMsg); err != nil {
  428. if errors.Is(err, wire.ErrStatusTextSizeExceeded) {
  429. SendError(w, r, http.StatusBadRequest, err.Error())
  430. } else {
  431. h.Logger.ErrorContext(ctx, "failed to marshal status message", "err", err.Error())
  432. SendError(w, r, http.StatusInternalServerError, "failed to set status")
  433. }
  434. return
  435. }
  436. setFields := wire.SNAC_0x01_0x1E_OServiceSetUserInfoFields{
  437. TLVRestBlock: wire.TLVRestBlock{
  438. TLVList: wire.TLVList{
  439. wire.NewTLVBE(wire.OServiceUserInfoBARTInfo, bid),
  440. },
  441. },
  442. }
  443. if err := h.OServiceService.SetUserInfoFields(ctx, session.OSCARSession, wire.SNACFrame{}, setFields); err != nil {
  444. h.Logger.ErrorContext(ctx, "failed to set user info fields", "err", err.Error())
  445. SendError(w, r, http.StatusInternalServerError, "failed to set status")
  446. return
  447. }
  448. }
  449. if r.URL.Query().Has("mood") {
  450. moodID := r.URL.Query().Get("mood")
  451. if moodID == "" {
  452. session.ClearMood()
  453. } else {
  454. m, hasMood := wire.MoodByID(moodID)
  455. if !hasMood {
  456. SendError(w, r, http.StatusBadRequest, "invalid mood ID")
  457. return
  458. }
  459. session.SetMood(m.Cap)
  460. }
  461. setInfo := wire.SNAC_0x02_0x04_LocateSetInfo{
  462. TLVRestBlock: wire.TLVRestBlock{
  463. TLVList: wire.TLVList{
  464. wire.NewTLVBE(wire.LocateTLVTagsInfoCapabilities, session.Caps()),
  465. },
  466. },
  467. }
  468. if err := h.LocateService.SetInfo(ctx, session.OSCARSession, setInfo); err != nil {
  469. h.Logger.ErrorContext(ctx, "failed to set mood capability", "err", err.Error())
  470. SendError(w, r, http.StatusInternalServerError, "failed to save status")
  471. return
  472. }
  473. }
  474. h.Logger.InfoContext(ctx, "status message updated",
  475. "screenName", session.ScreenName.String(),
  476. "statusMsg", statusMsg,
  477. "statusCode", statusCode,
  478. "mood", r.URL.Query().Get("mood"),
  479. )
  480. SendOK(w, r, nil, h.Logger)
  481. }
  482. // SetProfile handles GET /presence/setProfile requests to update user's profile.
  483. func (h *PresenceHandler) SetProfile(w http.ResponseWriter, r *http.Request, session *Session) {
  484. ctx := r.Context()
  485. profileText := r.URL.Query().Get("profile")
  486. if len(profileText) > 4096 {
  487. SendError(w, r, http.StatusBadRequest, "profile too large (max 4KB)")
  488. return
  489. }
  490. instance := session.OSCARSession
  491. // Save profile via OSCAR LocateService.
  492. setInfo := wire.SNAC_0x02_0x04_LocateSetInfo{
  493. TLVRestBlock: wire.TLVRestBlock{
  494. TLVList: wire.TLVList{
  495. wire.NewTLVBE(wire.LocateTLVTagsInfoSigData, profileText),
  496. },
  497. },
  498. }
  499. if err := h.LocateService.SetInfo(ctx, instance, setInfo); err != nil {
  500. h.Logger.ErrorContext(ctx, "failed to set profile", "err", err.Error())
  501. SendError(w, r, http.StatusInternalServerError, "failed to save profile")
  502. return
  503. }
  504. h.Logger.InfoContext(ctx, "profile updated",
  505. "screenName", session.ScreenName.String(),
  506. "profileSize", len(profileText),
  507. )
  508. SendOK(w, r, nil, h.Logger)
  509. }
  510. // GetProfile handles GET /presence/getProfile requests to retrieve user's profile.
  511. func (h *PresenceHandler) GetProfile(w http.ResponseWriter, r *http.Request, session *Session) {
  512. ctx := r.Context()
  513. targetSN := r.URL.Query().Get("sn")
  514. if targetSN == "" {
  515. targetSN = session.ScreenName.String()
  516. }
  517. var profileText string
  518. instance := session.OSCARSession
  519. reply, err := h.LocateService.UserInfoQuery(ctx, instance, wire.SNACFrame{},
  520. wire.SNAC_0x02_0x05_LocateUserInfoQuery{Type: uint16(wire.LocateTypeSig), ScreenName: targetSN})
  521. if err != nil {
  522. h.Logger.WarnContext(ctx, "failed to get profile", "err", err.Error())
  523. } else if info, ok := reply.Body.(wire.SNAC_0x02_0x06_LocateUserInfoReply); ok {
  524. if prof, ok := info.LocateInfo.String(wire.LocateTLVTagsInfoSigData); ok {
  525. profileText = prof
  526. }
  527. }
  528. responseData := &ProfileData{ScreenName: targetSN, Profile: profileText}
  529. SendOK(w, r, responseData, h.Logger)
  530. }
  531. // Icon handles GET /presence/icon requests for presence icons.
  532. func (h *PresenceHandler) Icon(w http.ResponseWriter, r *http.Request) {
  533. name := r.URL.Query().Get("name")
  534. size := r.URL.Query().Get("size")
  535. iconType := r.URL.Query().Get("type")
  536. if name == "" {
  537. SendError(w, r, http.StatusBadRequest, "missing name parameter")
  538. return
  539. }
  540. // Default values
  541. if size == "" {
  542. size = "32"
  543. }
  544. if iconType == "" {
  545. iconType = "aim"
  546. }
  547. // For now, redirect to a placeholder icon
  548. // In production, this would redirect to actual icon storage/CDN
  549. var iconURL string
  550. // If it's an email lookup, extract username
  551. if strings.Contains(name, "@") {
  552. parts := strings.Split(name, "@")
  553. if len(parts) > 0 {
  554. name = parts[0]
  555. }
  556. }
  557. // Resolve the target's presence via OSCAR LocateService, querying on behalf
  558. // of the caller's session. This endpoint is unauthenticated, so fall back to
  559. // the offline icon when no valid session is supplied.
  560. var instance *state.SessionInstance
  561. if aimsid := r.URL.Query().Get("aimsid"); aimsid != "" {
  562. if session, err := h.SessionManager.GetSession(r.Context(), aimsid); err == nil {
  563. instance = session.OSCARSession
  564. }
  565. }
  566. // This endpoint serves a presence state badge, not the user's buddy icon, so
  567. // it has no use for a buddy icon URL.
  568. switch h.getUserPresence(r.Context(), instance, "", state.DisplayScreenName(name), false).State {
  569. // occupied and dnd have no badge of their own and both mean unavailable.
  570. case "away", "occupied", "dnd":
  571. iconURL = "/static/icons/away_" + iconType + "_" + size + ".png"
  572. case "idle":
  573. iconURL = "/static/icons/idle_" + iconType + "_" + size + ".png"
  574. case "offline":
  575. iconURL = "/static/icons/offline_" + iconType + "_" + size + ".png"
  576. default:
  577. iconURL = "/static/icons/online_" + iconType + "_" + size + ".png"
  578. }
  579. // Redirect to icon URL
  580. http.Redirect(w, r, iconURL, http.StatusFound)
  581. }
  582. // statusBitState reports the web state named by a user's ICQ status bits, or ""
  583. // when neither Busy nor DND is set. Callers must consult it before IsAway(): Busy
  584. // and DND also raise the unavailable flag, so an away-first test reports every busy
  585. // user as away.
  586. func statusBitState(info wire.TLVUserInfo, isAIMCaller bool) string {
  587. status, ok := info.Uint32BE(wire.OServiceUserInfoStatus)
  588. if !ok {
  589. return ""
  590. }
  591. return statusMaskState(status, isAIMCaller)
  592. }
  593. // statusMaskState names the web state a status bitmask describes, or "" when
  594. // neither Busy nor DND is set.
  595. func statusMaskState(status uint32, isAIMCaller bool) string {
  596. var st string
  597. switch {
  598. case status&wire.OServiceUserStatusBusy != 0:
  599. st = "occupied"
  600. case status&wire.OServiceUserStatusDND != 0:
  601. st = "dnd"
  602. default:
  603. return ""
  604. }
  605. if isAIMCaller {
  606. return "away"
  607. }
  608. return st
  609. }
  610. // selfWebState maps a user's own user info block to the web state string the
  611. // clients expect ("online", "away", "idle", "invisible", "occupied", "dnd").
  612. // Invisibility yields "invisible", not the "offline" a buddy sees.
  613. func selfWebState(info wire.TLVUserInfo, isAIMCaller bool) string {
  614. if info.IsInvisible() {
  615. return "invisible"
  616. }
  617. if st := statusBitState(info, isAIMCaller); st != "" {
  618. return st
  619. }
  620. if info.IsAway() {
  621. return "away"
  622. }
  623. if mask, ok := info.Uint32BE(wire.OServiceUserInfoStatus); ok && mask&wire.OServiceUserStatusAway != 0 {
  624. return "away"
  625. }
  626. if idle, ok := info.Uint16BE(wire.OServiceUserInfoIdleTime); ok && idle > 0 {
  627. return "idle"
  628. }
  629. return "online"
  630. }
  631. // userInfoCaps returns the capability UUIDs a user info block advertises.
  632. func userInfoCaps(info wire.TLVUserInfo) [][16]byte {
  633. b, ok := info.Bytes(wire.OServiceUserInfoOscarCaps)
  634. if !ok {
  635. return nil
  636. }
  637. caps := make([][16]byte, 0, len(b)/16)
  638. for chunk := range slices.Chunk(b, 16) {
  639. if len(chunk) < 16 {
  640. break
  641. }
  642. caps = append(caps, [16]byte(chunk))
  643. }
  644. return caps
  645. }
  646. // moodIconURL returns the mood icon URL for the mood advertised in caps, or ""
  647. // when there is none. A mood supersedes webState on the client, so a user who is
  648. // not visibly online never gets one.
  649. func moodIconURL(baseURL, webState string, caps [][16]byte) string {
  650. if webState == "offline" || webState == "invisible" {
  651. return ""
  652. }
  653. for _, c := range caps {
  654. if m, ok := wire.MoodByCap(c); ok {
  655. return baseURL + "/mood?id=" + wire.MoodIconID(m.ID)
  656. }
  657. }
  658. return ""
  659. }