presence_handler.go 29 KB

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