preference_handler.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. package webapi
  2. import (
  3. "context"
  4. "fmt"
  5. "log/slog"
  6. "math/rand"
  7. "net/http"
  8. "reflect"
  9. "strings"
  10. "github.com/mk6i/open-oscar-server/state"
  11. "github.com/mk6i/open-oscar-server/wire"
  12. )
  13. // PreferenceHandler handles Web AIM API preference-related endpoints.
  14. type PreferenceHandler struct {
  15. FeedbagService FeedbagService
  16. SessionManager *SessionManager
  17. Logger *slog.Logger
  18. }
  19. // webBuddyPrefs maps Web AIM API preference names to OSCAR buddy-pref bit
  20. // numbers, which are stored as a bitmask in the user's feedbag (see
  21. // wire.BuddyPref). Default values for absent prefs are owned by wire.BuddyPref,
  22. // not here.
  23. var webBuddyPrefs = map[string]uint16{
  24. "displayLogin": wire.FeedbagBuddyPrefsDisplayLogin,
  25. "displayEBuddy": wire.FeedbagBuddyPrefsDisplayEBuddy,
  26. "playEnter": wire.FeedbagBuddyPrefsPlayEnter,
  27. "playExit": wire.FeedbagBuddyPrefsPlayExit,
  28. "viewIMTimestamps": wire.FeedbagBuddyPrefsViewIMStamp,
  29. "viewSmilies": wire.FeedbagBuddyPrefsViewSmileys,
  30. "acceptIcons": wire.FeedbagBuddyPrefsAcceptIcons,
  31. "knockNonAOLIMs": wire.FeedbagBuddyPrefsKnockNonAOLIMs,
  32. "knockNonListIMs": wire.FeedbagBuddyPrefsKnockNonListIMs,
  33. "discloseIdle": wire.FeedbagBuddyPrefsDiscloseIdle,
  34. "acceptCustomBart": wire.FeedbagBuddyPrefsAcceptCustomBart,
  35. "acceptNonListBart": wire.FeedbagBuddyPrefsAcceptNonListBart,
  36. "acceptBgs": wire.FeedbagBuddyPrefsAcceptBgs,
  37. "acceptChromes": wire.FeedbagBuddyPrefsAcceptChromes,
  38. "acceptBLSounds": wire.FeedbagBuddyPrefsAcceptBLSounds,
  39. "acceptIMsounds": wire.FeedbagBuddyPrefsAcceptIMSounds,
  40. "noSeeRecentBuddies": wire.FeedbagBuddyPrefsNoSeeRecentBuddies,
  41. "acceptSMSLegal": wire.FeedbagBuddyPrefsAcceptSMSLegal,
  42. "enterDoesCRLF": wire.FeedbagBuddyPrefsEnterDoesCRLF,
  43. "playIMSound": wire.FeedbagBuddyPrefsPlayIMSound,
  44. "discloseTyping": wire.FeedbagBuddyPrefsDiscloseTyping,
  45. "acceptSuperIcons": wire.FeedbagBuddyPrefsAcceptSuperIcons,
  46. "acceptBLRichText": wire.FeedbagBuddyPrefsAcceptBLRichText,
  47. "reduceIMSound": wire.FeedbagBuddyPrefsReduceIMSound,
  48. "confirmDirectIM": wire.FeedbagBuddyPrefsConfirmDirectIM,
  49. "oneTabbedIMWindow": wire.FeedbagBuddyPrefsOneTabbedIMWindow,
  50. "buddyInfoOnMouseover": wire.FeedbagBuddyPrefsBuddyInfoOnMouseover,
  51. "discloseBuddyMatches": wire.FeedbagBuddyPrefsDiscloseBuddyMatches,
  52. "catchIMs": wire.FeedbagBuddyPrefsCatchIMs,
  53. "showFriendlyName": wire.FeedbagBuddyPrefsShowFriendlyName,
  54. "discloseRadio": wire.FeedbagBuddyPrefsDiscloseRadio,
  55. "showCapabilities": wire.FeedbagBuddyPrefsShowCapabilities,
  56. "showBuddyListFilter": wire.FeedbagBuddyPrefsShowBuddyListFilter,
  57. "showAwayIdle": wire.FeedbagBuddyPrefsShowAwayIdle,
  58. "showMobile": wire.FeedbagBuddyPrefsShowMobile,
  59. "sortBuddyList": wire.FeedbagBuddyPrefsSortBuddyList,
  60. "catchIMsForClient": wire.FeedbagBuddyPrefsCatchIMsForClient,
  61. "newMessageSmallNotification": wire.FeedbagBuddyPrefsNewMessageSmallNotify,
  62. "noFrequentBuddies": wire.FeedbagBuddyPrefsNoFrequentBuddies,
  63. "blogAwayMessages": wire.FeedbagBuddyPrefsBlogAwayMessages,
  64. "blogAIMSigMessages": wire.FeedbagBuddyPrefsBlogAIMSigMessages,
  65. "blogNoComments": wire.FeedbagBuddyPrefsBlogNoComments,
  66. "friendOfFriend": wire.FeedbagBuddyPrefsFriendOfFriend,
  67. "friendGetContactList": wire.FeedbagBuddyPrefsFriendGetContactList,
  68. "compadInit": wire.FeedbagBuddyPrefsCompadInit,
  69. "sendBuddyFeed": wire.FeedbagBuddyPrefsSendBuddyFeed,
  70. "blkSendIMWhileAway": wire.FeedbagBuddyPrefsBlkSendIMWhileAway,
  71. "showBuddyFeed": wire.FeedbagBuddyPrefsShowBuddyFeed,
  72. "noSaveVanityInfo": wire.FeedbagBuddyPrefsNoSaveVanityInfo,
  73. "acceptOffLineIM": wire.FeedbagBuddyPrefsAcceptOfflineIM,
  74. "showGroups": wire.FeedbagBuddyPrefsShowGroups,
  75. "sortGroup": wire.FeedbagBuddyPrefsSortGroup,
  76. "showOffLineBuddies": wire.FeedbagBuddyPrefsShowOfflineBuddies,
  77. "expandBuddies": wire.FeedbagBuddyPrefsExpandBuddies,
  78. "thirdPartyFeeds": wire.FeedbagBuddyPrefsThirdPartyFeeds,
  79. "notifyReceivedInvite": wire.FeedbagBuddyPrefsNotifyReceivedInvite,
  80. "apfAutoAccept": wire.FeedbagBuddyPrefsApfAutoAccept,
  81. "apfAutoAcceptBuddy": wire.FeedbagBuddyPrefsApfAutoAcceptBuddy,
  82. "blockAwayMsgFeed": wire.FeedbagBuddyPrefsBlockAwayMsgFeed,
  83. "blockAIMProfileFeed": wire.FeedbagBuddyPrefsBlockAIMProfileFeed,
  84. "blockAIMPagesFeed": wire.FeedbagBuddyPrefsBlockAIMPagesFeed,
  85. "blockJournalsFeed": wire.FeedbagBuddyPrefsBlockJournalsFeed,
  86. "blockLocationFeed": wire.FeedbagBuddyPrefsBlockLocationFeed,
  87. "blockStickiesFeed": wire.FeedbagBuddyPrefsBlockStickiesFeed,
  88. "blockUncutFeed": wire.FeedbagBuddyPrefsBlockUncutFeed,
  89. "blockLinksFeed": wire.FeedbagBuddyPrefsBlockLinksFeed,
  90. "blockAIMBulletinFeed": wire.FeedbagBuddyPrefsBlockAIMBulletinFeed,
  91. "saveStatusMsg": wire.FeedbagBuddyPrefsSaveStatusMsg,
  92. // Not in the spec Preferences enum, but sent by the web client.
  93. "apfNotifyReceivedInviteByEmail": wire.FeedbagBuddyPrefsApfNotifyReceivedByEmail,
  94. "showOfflineGrp": wire.FeedbagBuddyPrefsShowOfflineGrp,
  95. "offlineGrpCollapsed": wire.FeedbagBuddyPrefsOfflineGrpCollapsed,
  96. "firstImSoundOnly": wire.FeedbagBuddyPrefsFirstIMSoundOnly,
  97. "imblastInviteNotify": wire.FeedbagBuddyPrefsImblastInviteNotify,
  98. // Web-client-only preferences with no OSCAR buddy-pref equivalent. OSCAR
  99. // defines prefs through 0x4B, so we persist these in the same feedbag
  100. // buddy-prefs bitmask at positions above that range; no real OSCAR client
  101. // reads or writes these bits.
  102. "viewIMsInBubbles": wire.FeedbagBuddyPrefsViewIMsInBubbles,
  103. "viewIMTimestampsRelative": wire.FeedbagBuddyPrefsViewIMTimestampsRelative,
  104. "globalOTR": wire.FeedbagBuddyPrefsGlobalOTR,
  105. "imblastInviteFromBuddyOnly": wire.FeedbagBuddyPrefsImblastInviteFromBuddyOnly,
  106. }
  107. // PreferenceData carries Web API buddy preferences.
  108. //
  109. // Values are numbers, not "1"/"0" strings, because the client evaluates them
  110. // with JavaScript truthiness and numeric comparison, where the string "0" is
  111. // truthy. They are pointers because a preference set to 0 and a preference not
  112. // carried at all mean different things and both occur: getPreference and
  113. // setPreference answer with just the preferences the request named, while the
  114. // startSession seed carries every one. A plain int could not tell the two
  115. // apart, and the client reads its buddy-list display preferences only from
  116. // here — an omitted showGroups falls back to a hidden client default that hides
  117. // group headers.
  118. //
  119. // The fields mirror webBuddyPrefs one for one; TestPreferenceDataMatchesPrefTable
  120. // fails if the two drift apart.
  121. type PreferenceData struct {
  122. DisplayLogin *int `json:"displayLogin,omitempty" xml:"displayLogin,omitempty"`
  123. DisplayEBuddy *int `json:"displayEBuddy,omitempty" xml:"displayEBuddy,omitempty"`
  124. PlayEnter *int `json:"playEnter,omitempty" xml:"playEnter,omitempty"`
  125. PlayExit *int `json:"playExit,omitempty" xml:"playExit,omitempty"`
  126. ViewIMTimestamps *int `json:"viewIMTimestamps,omitempty" xml:"viewIMTimestamps,omitempty"`
  127. ViewSmilies *int `json:"viewSmilies,omitempty" xml:"viewSmilies,omitempty"`
  128. AcceptIcons *int `json:"acceptIcons,omitempty" xml:"acceptIcons,omitempty"`
  129. KnockNonAOLIMs *int `json:"knockNonAOLIMs,omitempty" xml:"knockNonAOLIMs,omitempty"`
  130. KnockNonListIMs *int `json:"knockNonListIMs,omitempty" xml:"knockNonListIMs,omitempty"`
  131. DiscloseIdle *int `json:"discloseIdle,omitempty" xml:"discloseIdle,omitempty"`
  132. AcceptCustomBart *int `json:"acceptCustomBart,omitempty" xml:"acceptCustomBart,omitempty"`
  133. AcceptNonListBart *int `json:"acceptNonListBart,omitempty" xml:"acceptNonListBart,omitempty"`
  134. AcceptBgs *int `json:"acceptBgs,omitempty" xml:"acceptBgs,omitempty"`
  135. AcceptChromes *int `json:"acceptChromes,omitempty" xml:"acceptChromes,omitempty"`
  136. AcceptBLSounds *int `json:"acceptBLSounds,omitempty" xml:"acceptBLSounds,omitempty"`
  137. AcceptIMsounds *int `json:"acceptIMsounds,omitempty" xml:"acceptIMsounds,omitempty"`
  138. NoSeeRecentBuddies *int `json:"noSeeRecentBuddies,omitempty" xml:"noSeeRecentBuddies,omitempty"`
  139. AcceptSMSLegal *int `json:"acceptSMSLegal,omitempty" xml:"acceptSMSLegal,omitempty"`
  140. EnterDoesCRLF *int `json:"enterDoesCRLF,omitempty" xml:"enterDoesCRLF,omitempty"`
  141. PlayIMSound *int `json:"playIMSound,omitempty" xml:"playIMSound,omitempty"`
  142. DiscloseTyping *int `json:"discloseTyping,omitempty" xml:"discloseTyping,omitempty"`
  143. AcceptSuperIcons *int `json:"acceptSuperIcons,omitempty" xml:"acceptSuperIcons,omitempty"`
  144. AcceptBLRichText *int `json:"acceptBLRichText,omitempty" xml:"acceptBLRichText,omitempty"`
  145. ReduceIMSound *int `json:"reduceIMSound,omitempty" xml:"reduceIMSound,omitempty"`
  146. ConfirmDirectIM *int `json:"confirmDirectIM,omitempty" xml:"confirmDirectIM,omitempty"`
  147. OneTabbedIMWindow *int `json:"oneTabbedIMWindow,omitempty" xml:"oneTabbedIMWindow,omitempty"`
  148. BuddyInfoOnMouseover *int `json:"buddyInfoOnMouseover,omitempty" xml:"buddyInfoOnMouseover,omitempty"`
  149. DiscloseBuddyMatches *int `json:"discloseBuddyMatches,omitempty" xml:"discloseBuddyMatches,omitempty"`
  150. CatchIMs *int `json:"catchIMs,omitempty" xml:"catchIMs,omitempty"`
  151. ShowFriendlyName *int `json:"showFriendlyName,omitempty" xml:"showFriendlyName,omitempty"`
  152. DiscloseRadio *int `json:"discloseRadio,omitempty" xml:"discloseRadio,omitempty"`
  153. ShowCapabilities *int `json:"showCapabilities,omitempty" xml:"showCapabilities,omitempty"`
  154. ShowBuddyListFilter *int `json:"showBuddyListFilter,omitempty" xml:"showBuddyListFilter,omitempty"`
  155. ShowAwayIdle *int `json:"showAwayIdle,omitempty" xml:"showAwayIdle,omitempty"`
  156. ShowMobile *int `json:"showMobile,omitempty" xml:"showMobile,omitempty"`
  157. SortBuddyList *int `json:"sortBuddyList,omitempty" xml:"sortBuddyList,omitempty"`
  158. CatchIMsForClient *int `json:"catchIMsForClient,omitempty" xml:"catchIMsForClient,omitempty"`
  159. NewMessageSmallNotification *int `json:"newMessageSmallNotification,omitempty" xml:"newMessageSmallNotification,omitempty"`
  160. NoFrequentBuddies *int `json:"noFrequentBuddies,omitempty" xml:"noFrequentBuddies,omitempty"`
  161. BlogAwayMessages *int `json:"blogAwayMessages,omitempty" xml:"blogAwayMessages,omitempty"`
  162. BlogAIMSigMessages *int `json:"blogAIMSigMessages,omitempty" xml:"blogAIMSigMessages,omitempty"`
  163. BlogNoComments *int `json:"blogNoComments,omitempty" xml:"blogNoComments,omitempty"`
  164. FriendOfFriend *int `json:"friendOfFriend,omitempty" xml:"friendOfFriend,omitempty"`
  165. FriendGetContactList *int `json:"friendGetContactList,omitempty" xml:"friendGetContactList,omitempty"`
  166. CompadInit *int `json:"compadInit,omitempty" xml:"compadInit,omitempty"`
  167. SendBuddyFeed *int `json:"sendBuddyFeed,omitempty" xml:"sendBuddyFeed,omitempty"`
  168. BlkSendIMWhileAway *int `json:"blkSendIMWhileAway,omitempty" xml:"blkSendIMWhileAway,omitempty"`
  169. ShowBuddyFeed *int `json:"showBuddyFeed,omitempty" xml:"showBuddyFeed,omitempty"`
  170. NoSaveVanityInfo *int `json:"noSaveVanityInfo,omitempty" xml:"noSaveVanityInfo,omitempty"`
  171. AcceptOffLineIM *int `json:"acceptOffLineIM,omitempty" xml:"acceptOffLineIM,omitempty"`
  172. ShowGroups *int `json:"showGroups,omitempty" xml:"showGroups,omitempty"`
  173. SortGroup *int `json:"sortGroup,omitempty" xml:"sortGroup,omitempty"`
  174. ShowOffLineBuddies *int `json:"showOffLineBuddies,omitempty" xml:"showOffLineBuddies,omitempty"`
  175. ExpandBuddies *int `json:"expandBuddies,omitempty" xml:"expandBuddies,omitempty"`
  176. ThirdPartyFeeds *int `json:"thirdPartyFeeds,omitempty" xml:"thirdPartyFeeds,omitempty"`
  177. NotifyReceivedInvite *int `json:"notifyReceivedInvite,omitempty" xml:"notifyReceivedInvite,omitempty"`
  178. ApfAutoAccept *int `json:"apfAutoAccept,omitempty" xml:"apfAutoAccept,omitempty"`
  179. ApfAutoAcceptBuddy *int `json:"apfAutoAcceptBuddy,omitempty" xml:"apfAutoAcceptBuddy,omitempty"`
  180. BlockAwayMsgFeed *int `json:"blockAwayMsgFeed,omitempty" xml:"blockAwayMsgFeed,omitempty"`
  181. BlockAIMProfileFeed *int `json:"blockAIMProfileFeed,omitempty" xml:"blockAIMProfileFeed,omitempty"`
  182. BlockAIMPagesFeed *int `json:"blockAIMPagesFeed,omitempty" xml:"blockAIMPagesFeed,omitempty"`
  183. BlockJournalsFeed *int `json:"blockJournalsFeed,omitempty" xml:"blockJournalsFeed,omitempty"`
  184. BlockLocationFeed *int `json:"blockLocationFeed,omitempty" xml:"blockLocationFeed,omitempty"`
  185. BlockStickiesFeed *int `json:"blockStickiesFeed,omitempty" xml:"blockStickiesFeed,omitempty"`
  186. BlockUncutFeed *int `json:"blockUncutFeed,omitempty" xml:"blockUncutFeed,omitempty"`
  187. BlockLinksFeed *int `json:"blockLinksFeed,omitempty" xml:"blockLinksFeed,omitempty"`
  188. BlockAIMBulletinFeed *int `json:"blockAIMBulletinFeed,omitempty" xml:"blockAIMBulletinFeed,omitempty"`
  189. SaveStatusMsg *int `json:"saveStatusMsg,omitempty" xml:"saveStatusMsg,omitempty"`
  190. ApfNotifyReceivedInviteByEmail *int `json:"apfNotifyReceivedInviteByEmail,omitempty" xml:"apfNotifyReceivedInviteByEmail,omitempty"`
  191. ShowOfflineGrp *int `json:"showOfflineGrp,omitempty" xml:"showOfflineGrp,omitempty"`
  192. OfflineGrpCollapsed *int `json:"offlineGrpCollapsed,omitempty" xml:"offlineGrpCollapsed,omitempty"`
  193. FirstImSoundOnly *int `json:"firstImSoundOnly,omitempty" xml:"firstImSoundOnly,omitempty"`
  194. ImblastInviteNotify *int `json:"imblastInviteNotify,omitempty" xml:"imblastInviteNotify,omitempty"`
  195. ViewIMsInBubbles *int `json:"viewIMsInBubbles,omitempty" xml:"viewIMsInBubbles,omitempty"`
  196. ViewIMTimestampsRelative *int `json:"viewIMTimestampsRelative,omitempty" xml:"viewIMTimestampsRelative,omitempty"`
  197. GlobalOTR *int `json:"globalOTR,omitempty" xml:"globalOTR,omitempty"`
  198. ImblastInviteFromBuddyOnly *int `json:"imblastInviteFromBuddyOnly,omitempty" xml:"imblastInviteFromBuddyOnly,omitempty"`
  199. }
  200. // PermitDenyData contains permit/deny list information.
  201. //
  202. // The XML item names follow the spec's getPermitDeny, which nests <allow> under
  203. // <allows> and <block> under <blocks>.
  204. type PermitDenyData struct {
  205. PDMode string `json:"pdMode" xml:"pdMode"`
  206. PermitList []string `json:"allows,omitempty" xml:"allows>allow,omitempty"`
  207. DenyList []string `json:"blocks,omitempty" xml:"blocks>block,omitempty"`
  208. }
  209. // SetPreferences handles GET /preference/set requests to update user preferences.
  210. func (h *PreferenceHandler) SetPreferences(w http.ResponseWriter, r *http.Request, session *Session) {
  211. defer session.InvalidateFeedbag()
  212. ctx := r.Context()
  213. // Preferences are stored as OSCAR buddy prefs in the feedbag, which requires
  214. // an OSCAR session to act on behalf of.
  215. instance := session.OSCARSession
  216. // Read-modify-write the buddy-prefs item so bits the web client doesn't
  217. // manage (e.g. the typing-events bit consumed by the OSCAR session) survive.
  218. item, err := buddyPrefsItem(ctx, h.FeedbagService, instance)
  219. if err != nil {
  220. h.Logger.ErrorContext(ctx, "failed to retrieve feedbag", "err", err.Error())
  221. SendError(w, r, http.StatusInternalServerError, "failed to retrieve feedbag")
  222. return
  223. }
  224. applied := &PreferenceData{}
  225. for name, pref := range webBuddyPrefs {
  226. val := r.URL.Query().Get(name)
  227. if val == "" {
  228. continue
  229. }
  230. on := parseBoolPref(val)
  231. item.TLVList = wire.SetBuddyPref(item.TLVList, pref, on)
  232. applied.Set(name, boolToPrefInt(on))
  233. }
  234. if applied.Len() > 0 {
  235. frame := wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagInsertItem}
  236. if _, err := h.FeedbagService.UpsertItem(ctx, instance, frame, []wire.FeedbagItem{item}); err != nil {
  237. h.Logger.ErrorContext(ctx, "failed to set preferences", "err", err.Error())
  238. SendError(w, r, http.StatusInternalServerError, "failed to save preferences")
  239. return
  240. }
  241. // Notify the client's open windows via the event stream so display
  242. // changes (e.g. bubbles/classic) take effect immediately without a
  243. // browser refresh.
  244. session.EventQueue.Push(EventTypePreference, applied)
  245. }
  246. h.Logger.DebugContext(ctx, "preferences updated",
  247. "screenName", session.ScreenName.String(),
  248. "prefCount", applied.Len(),
  249. )
  250. SendOK(w, r, applied, h.Logger)
  251. }
  252. // GetPreferences handles GET /preference/get requests to retrieve user preferences.
  253. func (h *PreferenceHandler) GetPreferences(w http.ResponseWriter, r *http.Request, session *Session) {
  254. ctx := r.Context()
  255. // Load the buddy-prefs bitmask from the feedbag. Absent prefs fall back to
  256. // the spec default.
  257. var prefsList wire.TLVList
  258. if item, err := buddyPrefsItem(ctx, h.FeedbagService, session.OSCARSession); err != nil {
  259. h.Logger.WarnContext(ctx, "failed to get preferences", "err", err.Error())
  260. } else {
  261. prefsList = item.TLVList
  262. }
  263. // When specific preferences are named in the query (e.g. playIMSound=1), the
  264. // client is selecting those; otherwise return all preferences.
  265. requestedPrefs := &PreferenceData{}
  266. for name, pref := range webBuddyPrefs {
  267. if r.URL.Query().Has(name) {
  268. requestedPrefs.Set(name, effectivePrefValue(prefsList, pref))
  269. }
  270. }
  271. prefs := requestedPrefs
  272. if prefs.Len() == 0 {
  273. prefs = effectiveBuddyPrefs(prefsList)
  274. }
  275. h.Logger.DebugContext(ctx, "preferences retrieved",
  276. "screenName", session.ScreenName.String(),
  277. "prefCount", prefs.Len(),
  278. "requested", requestedPrefs.Len() > 0,
  279. )
  280. var payload any = prefs
  281. // AMF clients (e.g. Gromit) expect the payload shaped a specific way. Pref
  282. // values are already numeric 0/1, which is what these clients expect.
  283. format := requestFormat(r)
  284. if format == "amf" || format == "amf3" {
  285. amfPrefs := prefs.Map()
  286. // Ensure prefs is never empty for Gromit.
  287. if len(amfPrefs) == 0 {
  288. amfPrefs = map[string]any{"playIMSound": 1}
  289. }
  290. // A single preference is returned directly; multiple are wrapped in
  291. // jsonData for Gromit compatibility.
  292. if len(amfPrefs) != 1 {
  293. amfPrefs = map[string]any{"jsonData": amfPrefs}
  294. }
  295. payload = amfPrefs
  296. h.Logger.DebugContext(ctx, "AMF preference response",
  297. "prefCount", prefs.Len(),
  298. "format", format,
  299. )
  300. }
  301. SendOK(w, r, payload, h.Logger)
  302. }
  303. // buddyPrefsItem returns the user's buddy-prefs feedbag item, creating a fresh
  304. // (empty) one if the feedbag does not have it yet.
  305. func buddyPrefsItem(ctx context.Context, fs FeedbagService, instance *state.SessionInstance) (wire.FeedbagItem, error) {
  306. frame := wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagQuery}
  307. fb, err := fs.Query(ctx, instance, frame)
  308. if err != nil {
  309. return wire.FeedbagItem{}, err
  310. }
  311. reply, ok := fb.Body.(wire.SNAC_0x13_0x06_FeedbagReply)
  312. if !ok {
  313. return wire.FeedbagItem{}, fmt.Errorf("unexpected feedbag reply type")
  314. }
  315. for _, item := range reply.Items {
  316. if item.ClassID == wire.FeedbagClassIdBuddyPrefs {
  317. return item, nil
  318. }
  319. }
  320. // No buddy-prefs item yet; create one. Only a single item of this class is
  321. // allowed, with an empty name and no group.
  322. return wire.FeedbagItem{
  323. ClassID: wire.FeedbagClassIdBuddyPrefs,
  324. ItemID: uint16(rand.Intn(0xFFFF)),
  325. }, nil
  326. }
  327. // effectiveBuddyPrefs returns the 0/1 value of every web buddy pref, using the
  328. // feedbag value when the pref's valid bit is set and the spec default otherwise.
  329. // This mirrors GetPreferences so the pushed preference event and the
  330. // preference/get endpoint agree: server-side defaults (e.g. showGroups) reach
  331. // the client even for prefs the user has never explicitly set. The web client
  332. // reads these from the startup preference event and has no other default for
  333. // them, so an omitted pref would silently fall back to the client's own hidden
  334. // default (which, for showGroups, hides group headers).
  335. func effectiveBuddyPrefs(list wire.TLVList) *PreferenceData {
  336. prefs := &PreferenceData{}
  337. for name, pref := range webBuddyPrefs {
  338. prefs.Set(name, effectivePrefValue(list, pref))
  339. }
  340. return prefs
  341. }
  342. // prefFieldIndex maps a preference name to its PreferenceData field.
  343. var prefFieldIndex = func() map[string]int {
  344. t := reflect.TypeFor[PreferenceData]()
  345. index := make(map[string]int, t.NumField())
  346. for i := 0; i < t.NumField(); i++ {
  347. name, _, _ := strings.Cut(t.Field(i).Tag.Get("json"), ",")
  348. index[name] = i
  349. }
  350. return index
  351. }()
  352. // Set records one preference by its Web API name, leaving every preference not
  353. // set this way absent from the payload. It reports whether the name is one this
  354. // server carries.
  355. func (p *PreferenceData) Set(name string, value int) bool {
  356. i, ok := prefFieldIndex[name]
  357. if !ok {
  358. return false
  359. }
  360. reflect.ValueOf(p).Elem().Field(i).Set(reflect.ValueOf(&value))
  361. return true
  362. }
  363. // Get returns a preference by its Web API name and whether it is carried.
  364. func (p *PreferenceData) Get(name string) (int, bool) {
  365. i, ok := prefFieldIndex[name]
  366. if !ok {
  367. return 0, false
  368. }
  369. field := reflect.ValueOf(p).Elem().Field(i)
  370. if field.IsNil() {
  371. return 0, false
  372. }
  373. return int(field.Elem().Int()), true
  374. }
  375. // Map returns the carried preferences keyed by Web API name, for the AMF path
  376. // that reshapes the payload rather than sending it as-is.
  377. func (p *PreferenceData) Map() map[string]any {
  378. out := make(map[string]any, len(prefFieldIndex))
  379. for name := range prefFieldIndex {
  380. if v, ok := p.Get(name); ok {
  381. out[name] = v
  382. }
  383. }
  384. return out
  385. }
  386. // Len reports how many preferences the payload carries.
  387. func (p *PreferenceData) Len() int {
  388. fields := reflect.ValueOf(p).Elem()
  389. n := 0
  390. for _, field := range fields.Fields() {
  391. if !field.IsNil() {
  392. n++
  393. }
  394. }
  395. return n
  396. }
  397. // effectivePrefValue returns the 0/1 value for the buddy pref prefNum, deferring
  398. // to wire.BuddyPref for both the stored value and its default. Values are emitted
  399. // as numbers (not "1"/"0" strings) because the web client evaluates them with
  400. // JavaScript truthiness/numeric comparisons, where the string "0" is truthy.
  401. func effectivePrefValue(list wire.TLVList, prefNum uint16) int {
  402. return boolToPrefInt(wire.BuddyPref(list, prefNum))
  403. }
  404. // parseBoolPref interprets a Web API preference query value as a boolean.
  405. func parseBoolPref(v string) bool {
  406. switch strings.ToLower(v) {
  407. case "1", "true", "yes", "on":
  408. return true
  409. default:
  410. return false
  411. }
  412. }
  413. func boolToPrefInt(b bool) int {
  414. if b {
  415. return 1
  416. }
  417. return 0
  418. }
  419. // SetPermitDeny handles GET /preference/setPermitDeny requests to update permit/deny settings.
  420. func (h *PreferenceHandler) SetPermitDeny(w http.ResponseWriter, r *http.Request, session *Session) {
  421. defer session.InvalidateFeedbag()
  422. ctx := r.Context()
  423. frame := wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagQuery}
  424. fb, err := h.FeedbagService.Query(r.Context(), session.OSCARSession, frame)
  425. if err != nil {
  426. SendError(w, r, http.StatusInternalServerError, "failed to retrieve feedbag")
  427. return
  428. }
  429. reply, ok := fb.Body.(wire.SNAC_0x13_0x06_FeedbagReply)
  430. if !ok {
  431. SendError(w, r, http.StatusInternalServerError, "failed to retrieve feedbag")
  432. return
  433. }
  434. fl := state.NewFeedbagList(reply.Items, rand.Intn)
  435. pdModeStr := r.URL.Query().Get("pdMode")
  436. if pdModeStr != "" {
  437. switch pdModeStr { // todo: are the string ints possible inputs?
  438. case "permitAll", "1":
  439. fl.SetMode(uint8(wire.FeedbagPDModePermitAll))
  440. case "denyAll", "2":
  441. fl.SetMode(uint8(wire.FeedbagPDModeDenyAll))
  442. case "permitSome", "3":
  443. fl.SetMode(uint8(wire.FeedbagPDModePermitSome))
  444. case "denySome", "4":
  445. fl.SetMode(uint8(wire.FeedbagPDModeDenySome))
  446. case "permitOnList", "5":
  447. fl.SetMode(uint8(wire.FeedbagPDModePermitOnList))
  448. default:
  449. SendError(w, r, http.StatusBadRequest, "invalid pdMode value")
  450. return
  451. }
  452. }
  453. // Handle permit list updates
  454. if pdAllow := r.URL.Query().Get("pdAllow"); pdAllow != "" {
  455. users := strings.SplitSeq(pdAllow, ",")
  456. for user := range users {
  457. user = strings.TrimSpace(user)
  458. if user != "" {
  459. fl.PermitUser(user)
  460. }
  461. }
  462. }
  463. if pdAllowRemove := r.URL.Query().Get("pdAllowRemove"); pdAllowRemove != "" {
  464. users := strings.SplitSeq(pdAllowRemove, ",")
  465. for user := range users {
  466. user = strings.TrimSpace(user)
  467. if user != "" {
  468. fl.DeletePermit(user)
  469. }
  470. }
  471. }
  472. // Handle deny list updates
  473. if pdBlock := r.URL.Query().Get("pdBlock"); pdBlock != "" {
  474. users := strings.SplitSeq(pdBlock, ",")
  475. for user := range users {
  476. user = strings.TrimSpace(user)
  477. if user != "" {
  478. fl.DenyUser(user)
  479. }
  480. }
  481. }
  482. if pdBlockRemove := r.URL.Query().Get("pdBlockRemove"); pdBlockRemove != "" {
  483. users := strings.SplitSeq(pdBlockRemove, ",")
  484. for user := range users {
  485. user = strings.TrimSpace(user)
  486. if user != "" {
  487. fl.DeleteDeny(user)
  488. }
  489. }
  490. }
  491. if pending := fl.PendingUpdates(); len(pending) > 0 {
  492. frame := wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagInsertItem}
  493. if _, err := h.FeedbagService.UpsertItem(ctx, session.OSCARSession, frame, pending); err != nil {
  494. h.Logger.ErrorContext(ctx, "failed to set PD mode", "err", err.Error())
  495. SendError(w, r, http.StatusInternalServerError, "failed to update PD mode")
  496. return
  497. }
  498. }
  499. if pending := fl.PendingDeletes(); len(pending) > 0 {
  500. frame := wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagDeleteItem}
  501. body := wire.SNAC_0x13_0x0A_FeedbagDeleteItem{Items: pending}
  502. if _, err := h.FeedbagService.DeleteItem(ctx, session.OSCARSession, frame, body); err != nil {
  503. h.Logger.ErrorContext(ctx, "failed to set PD mode", "err", err.Error())
  504. SendError(w, r, http.StatusInternalServerError, "failed to update PD mode")
  505. return
  506. }
  507. }
  508. pdd := permitDenyData(fl.Items())
  509. // The client reads the privacy state it renders (blocked buddies, the
  510. // block/unblock menu label) only from the permitDeny event, and it sees no
  511. // SNAC for the write it just made. Without this the block takes effect
  512. // server-side but the UI keeps showing the buddy as unblocked.
  513. session.EventQueue.Push(EventTypePermitDeny, pdd)
  514. h.Logger.DebugContext(ctx, "permit/deny settings updated",
  515. "screenName", session.ScreenName.String(),
  516. "pdMode", pdd.PDMode,
  517. "permitCount", len(pdd.PermitList),
  518. "denyCount", len(pdd.DenyList),
  519. )
  520. SendOK(w, r, pdd, h.Logger)
  521. }
  522. func permitDenyData(fl []wire.FeedbagItem) PermitDenyData {
  523. // A feedbag with no PD info item means no restrictions, the same default the
  524. // feedbag store applies. The client drives its block flow off pdMode and
  525. // sends no permit/deny change at all when the mode is absent.
  526. pdd := PermitDenyData{PDMode: "permitAll"}
  527. for _, item := range fl {
  528. switch item.ClassID {
  529. case wire.FeedbagClassIDDeny:
  530. pdd.DenyList = append(pdd.DenyList, item.Name)
  531. case wire.FeedbagClassIDPermit:
  532. pdd.PermitList = append(pdd.PermitList, item.Name)
  533. case wire.FeedbagClassIdPdinfo:
  534. mode, _ := item.Uint8(wire.FeedbagAttributesPdMode)
  535. switch wire.FeedbagPDMode(mode) {
  536. case wire.FeedbagPDModePermitAll:
  537. pdd.PDMode = "permitAll"
  538. case wire.FeedbagPDModeDenyAll:
  539. pdd.PDMode = "denyAll"
  540. case wire.FeedbagPDModePermitSome:
  541. pdd.PDMode = "permitSome"
  542. case wire.FeedbagPDModeDenySome:
  543. pdd.PDMode = "denySome"
  544. case wire.FeedbagPDModePermitOnList:
  545. pdd.PDMode = "permitOnList"
  546. }
  547. }
  548. }
  549. return pdd
  550. }
  551. // GetPermitDeny handles GET /preference/getPermitDeny requests to retrieve permit/deny settings.
  552. func (h *PreferenceHandler) GetPermitDeny(w http.ResponseWriter, r *http.Request, session *Session) {
  553. ctx := r.Context()
  554. items, err := session.Feedbag(ctx)
  555. if err != nil {
  556. SendError(w, r, http.StatusInternalServerError, "failed to retrieve feedbag")
  557. return
  558. }
  559. pdd := permitDenyData(items)
  560. h.Logger.DebugContext(ctx, "permit/deny settings retrieved",
  561. "screenName", session.ScreenName.String(),
  562. "pdMode", pdd.PDMode,
  563. "permitCount", len(pdd.PermitList),
  564. "denyCount", len(pdd.DenyList),
  565. )
  566. SendOK(w, r, pdd, h.Logger)
  567. }