preference_handler.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  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. ctx := r.Context()
  212. // Preferences are stored as OSCAR buddy prefs in the feedbag, which requires
  213. // an OSCAR session to act on behalf of.
  214. instance := session.OSCARSession
  215. // Read-modify-write the buddy-prefs item so bits the web client doesn't
  216. // manage (e.g. the typing-events bit consumed by the OSCAR session) survive.
  217. item, err := buddyPrefsItem(ctx, h.FeedbagService, instance)
  218. if err != nil {
  219. h.Logger.ErrorContext(ctx, "failed to retrieve feedbag", "err", err.Error())
  220. SendError(w, r, http.StatusInternalServerError, "failed to retrieve feedbag")
  221. return
  222. }
  223. applied := &PreferenceData{}
  224. for name, pref := range webBuddyPrefs {
  225. val := r.URL.Query().Get(name)
  226. if val == "" {
  227. continue
  228. }
  229. on := parseBoolPref(val)
  230. item.TLVList = wire.SetBuddyPref(item.TLVList, pref, on)
  231. applied.Set(name, boolToPrefInt(on))
  232. }
  233. if applied.Len() > 0 {
  234. frame := wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagInsertItem}
  235. if _, err := h.FeedbagService.UpsertItem(ctx, instance, frame, []wire.FeedbagItem{item}); err != nil {
  236. h.Logger.ErrorContext(ctx, "failed to set preferences", "err", err.Error())
  237. SendError(w, r, http.StatusInternalServerError, "failed to save preferences")
  238. return
  239. }
  240. // Notify the client's open windows via the event stream so display
  241. // changes (e.g. bubbles/classic) take effect immediately without a
  242. // browser refresh.
  243. session.EventQueue.Push(EventTypePreference, applied)
  244. }
  245. h.Logger.DebugContext(ctx, "preferences updated",
  246. "screenName", session.ScreenName.String(),
  247. "prefCount", applied.Len(),
  248. )
  249. SendOK(w, r, applied, h.Logger)
  250. }
  251. // GetPreferences handles GET /preference/get requests to retrieve user preferences.
  252. func (h *PreferenceHandler) GetPreferences(w http.ResponseWriter, r *http.Request, session *Session) {
  253. ctx := r.Context()
  254. // Load the buddy-prefs bitmask from the feedbag. Absent prefs fall back to
  255. // the spec default.
  256. var prefsList wire.TLVList
  257. if item, err := buddyPrefsItem(ctx, h.FeedbagService, session.OSCARSession); err != nil {
  258. h.Logger.WarnContext(ctx, "failed to get preferences", "err", err.Error())
  259. } else {
  260. prefsList = item.TLVList
  261. }
  262. // When specific preferences are named in the query (e.g. playIMSound=1), the
  263. // client is selecting those; otherwise return all preferences.
  264. requestedPrefs := &PreferenceData{}
  265. for name, pref := range webBuddyPrefs {
  266. if r.URL.Query().Has(name) {
  267. requestedPrefs.Set(name, effectivePrefValue(prefsList, pref))
  268. }
  269. }
  270. prefs := requestedPrefs
  271. if prefs.Len() == 0 {
  272. prefs = effectiveBuddyPrefs(prefsList)
  273. }
  274. h.Logger.DebugContext(ctx, "preferences retrieved",
  275. "screenName", session.ScreenName.String(),
  276. "prefCount", prefs.Len(),
  277. "requested", requestedPrefs.Len() > 0,
  278. )
  279. var payload any = prefs
  280. // AMF clients (e.g. Gromit) expect the payload shaped a specific way. Pref
  281. // values are already numeric 0/1, which is what these clients expect.
  282. format := requestFormat(r)
  283. if format == "amf" || format == "amf3" {
  284. amfPrefs := prefs.Map()
  285. // Ensure prefs is never empty for Gromit.
  286. if len(amfPrefs) == 0 {
  287. amfPrefs = map[string]any{"playIMSound": 1}
  288. }
  289. // A single preference is returned directly; multiple are wrapped in
  290. // jsonData for Gromit compatibility.
  291. if len(amfPrefs) != 1 {
  292. amfPrefs = map[string]any{"jsonData": amfPrefs}
  293. }
  294. payload = amfPrefs
  295. h.Logger.DebugContext(ctx, "AMF preference response",
  296. "prefCount", prefs.Len(),
  297. "format", format,
  298. )
  299. }
  300. SendOK(w, r, payload, h.Logger)
  301. }
  302. // buddyPrefsItem returns the user's buddy-prefs feedbag item, creating a fresh
  303. // (empty) one if the feedbag does not have it yet.
  304. func buddyPrefsItem(ctx context.Context, fs FeedbagService, instance *state.SessionInstance) (wire.FeedbagItem, error) {
  305. frame := wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagQuery}
  306. fb, err := fs.Query(ctx, instance, frame)
  307. if err != nil {
  308. return wire.FeedbagItem{}, err
  309. }
  310. reply, ok := fb.Body.(wire.SNAC_0x13_0x06_FeedbagReply)
  311. if !ok {
  312. return wire.FeedbagItem{}, fmt.Errorf("unexpected feedbag reply type")
  313. }
  314. for _, item := range reply.Items {
  315. if item.ClassID == wire.FeedbagClassIdBuddyPrefs {
  316. return item, nil
  317. }
  318. }
  319. // No buddy-prefs item yet; create one. Only a single item of this class is
  320. // allowed, with an empty name and no group.
  321. return wire.FeedbagItem{
  322. ClassID: wire.FeedbagClassIdBuddyPrefs,
  323. ItemID: uint16(rand.Intn(0xFFFF)),
  324. }, nil
  325. }
  326. // effectiveBuddyPrefs returns the 0/1 value of every web buddy pref, using the
  327. // feedbag value when the pref's valid bit is set and the spec default otherwise.
  328. // This mirrors GetPreferences so the pushed preference event and the
  329. // preference/get endpoint agree: server-side defaults (e.g. showGroups) reach
  330. // the client even for prefs the user has never explicitly set. The web client
  331. // reads these from the startup preference event and has no other default for
  332. // them, so an omitted pref would silently fall back to the client's own hidden
  333. // default (which, for showGroups, hides group headers).
  334. func effectiveBuddyPrefs(list wire.TLVList) *PreferenceData {
  335. prefs := &PreferenceData{}
  336. for name, pref := range webBuddyPrefs {
  337. prefs.Set(name, effectivePrefValue(list, pref))
  338. }
  339. return prefs
  340. }
  341. // prefFieldIndex maps a preference name to its PreferenceData field.
  342. var prefFieldIndex = func() map[string]int {
  343. t := reflect.TypeFor[PreferenceData]()
  344. index := make(map[string]int, t.NumField())
  345. for i := 0; i < t.NumField(); i++ {
  346. name, _, _ := strings.Cut(t.Field(i).Tag.Get("json"), ",")
  347. index[name] = i
  348. }
  349. return index
  350. }()
  351. // Set records one preference by its Web API name, leaving every preference not
  352. // set this way absent from the payload. It reports whether the name is one this
  353. // server carries.
  354. func (p *PreferenceData) Set(name string, value int) bool {
  355. i, ok := prefFieldIndex[name]
  356. if !ok {
  357. return false
  358. }
  359. reflect.ValueOf(p).Elem().Field(i).Set(reflect.ValueOf(&value))
  360. return true
  361. }
  362. // Get returns a preference by its Web API name and whether it is carried.
  363. func (p *PreferenceData) Get(name string) (int, bool) {
  364. i, ok := prefFieldIndex[name]
  365. if !ok {
  366. return 0, false
  367. }
  368. field := reflect.ValueOf(p).Elem().Field(i)
  369. if field.IsNil() {
  370. return 0, false
  371. }
  372. return int(field.Elem().Int()), true
  373. }
  374. // Map returns the carried preferences keyed by Web API name, for the AMF path
  375. // that reshapes the payload rather than sending it as-is.
  376. func (p *PreferenceData) Map() map[string]any {
  377. out := make(map[string]any, len(prefFieldIndex))
  378. for name := range prefFieldIndex {
  379. if v, ok := p.Get(name); ok {
  380. out[name] = v
  381. }
  382. }
  383. return out
  384. }
  385. // Len reports how many preferences the payload carries.
  386. func (p *PreferenceData) Len() int {
  387. fields := reflect.ValueOf(p).Elem()
  388. n := 0
  389. for _, field := range fields.Fields() {
  390. if !field.IsNil() {
  391. n++
  392. }
  393. }
  394. return n
  395. }
  396. // effectivePrefValue returns the 0/1 value for the buddy pref prefNum, deferring
  397. // to wire.BuddyPref for both the stored value and its default. Values are emitted
  398. // as numbers (not "1"/"0" strings) because the web client evaluates them with
  399. // JavaScript truthiness/numeric comparisons, where the string "0" is truthy.
  400. func effectivePrefValue(list wire.TLVList, prefNum uint16) int {
  401. return boolToPrefInt(wire.BuddyPref(list, prefNum))
  402. }
  403. // parseBoolPref interprets a Web API preference query value as a boolean.
  404. func parseBoolPref(v string) bool {
  405. switch strings.ToLower(v) {
  406. case "1", "true", "yes", "on":
  407. return true
  408. default:
  409. return false
  410. }
  411. }
  412. func boolToPrefInt(b bool) int {
  413. if b {
  414. return 1
  415. }
  416. return 0
  417. }
  418. // SetPermitDeny handles GET /preference/setPermitDeny requests to update permit/deny settings.
  419. func (h *PreferenceHandler) SetPermitDeny(w http.ResponseWriter, r *http.Request, session *Session) {
  420. ctx := r.Context()
  421. frame := wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagQuery}
  422. fb, err := h.FeedbagService.Query(r.Context(), session.OSCARSession, frame)
  423. if err != nil {
  424. SendError(w, r, http.StatusInternalServerError, "failed to retrieve feedbag")
  425. return
  426. }
  427. reply, ok := fb.Body.(wire.SNAC_0x13_0x06_FeedbagReply)
  428. if !ok {
  429. SendError(w, r, http.StatusInternalServerError, "failed to retrieve feedbag")
  430. return
  431. }
  432. fl := state.NewFeedbagList(reply.Items, rand.Intn)
  433. pdModeStr := r.URL.Query().Get("pdMode")
  434. if pdModeStr != "" {
  435. switch pdModeStr { // todo: are the string ints possible inputs?
  436. case "permitAll", "1":
  437. fl.SetMode(uint8(wire.FeedbagPDModePermitAll))
  438. case "denyAll", "2":
  439. fl.SetMode(uint8(wire.FeedbagPDModeDenyAll))
  440. case "permitSome", "3":
  441. fl.SetMode(uint8(wire.FeedbagPDModePermitSome))
  442. case "denySome", "4":
  443. fl.SetMode(uint8(wire.FeedbagPDModeDenySome))
  444. case "permitOnList", "5":
  445. fl.SetMode(uint8(wire.FeedbagPDModePermitOnList))
  446. default:
  447. SendError(w, r, http.StatusBadRequest, "invalid pdMode value")
  448. return
  449. }
  450. }
  451. // Handle permit list updates
  452. if pdAllow := r.URL.Query().Get("pdAllow"); pdAllow != "" {
  453. users := strings.SplitSeq(pdAllow, ",")
  454. for user := range users {
  455. user = strings.TrimSpace(user)
  456. if user != "" {
  457. fl.PermitUser(user)
  458. }
  459. }
  460. }
  461. if pdAllowRemove := r.URL.Query().Get("pdAllowRemove"); pdAllowRemove != "" {
  462. users := strings.SplitSeq(pdAllowRemove, ",")
  463. for user := range users {
  464. user = strings.TrimSpace(user)
  465. if user != "" {
  466. fl.DeletePermit(user)
  467. }
  468. }
  469. }
  470. // Handle deny list updates
  471. if pdBlock := r.URL.Query().Get("pdBlock"); pdBlock != "" {
  472. users := strings.SplitSeq(pdBlock, ",")
  473. for user := range users {
  474. user = strings.TrimSpace(user)
  475. if user != "" {
  476. fl.DenyUser(user)
  477. }
  478. }
  479. }
  480. if pdBlockRemove := r.URL.Query().Get("pdBlockRemove"); pdBlockRemove != "" {
  481. users := strings.SplitSeq(pdBlockRemove, ",")
  482. for user := range users {
  483. user = strings.TrimSpace(user)
  484. if user != "" {
  485. fl.DeleteDeny(user)
  486. }
  487. }
  488. }
  489. if pending := fl.PendingUpdates(); len(pending) > 0 {
  490. frame := wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagInsertItem}
  491. if _, err := h.FeedbagService.UpsertItem(ctx, session.OSCARSession, frame, pending); err != nil {
  492. h.Logger.ErrorContext(ctx, "failed to set PD mode", "err", err.Error())
  493. SendError(w, r, http.StatusInternalServerError, "failed to update PD mode")
  494. return
  495. }
  496. }
  497. if pending := fl.PendingDeletes(); len(pending) > 0 {
  498. frame := wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagDeleteItem}
  499. body := wire.SNAC_0x13_0x0A_FeedbagDeleteItem{Items: pending}
  500. if _, err := h.FeedbagService.DeleteItem(ctx, session.OSCARSession, frame, body); err != nil {
  501. h.Logger.ErrorContext(ctx, "failed to set PD mode", "err", err.Error())
  502. SendError(w, r, http.StatusInternalServerError, "failed to update PD mode")
  503. return
  504. }
  505. }
  506. pdd := permitDenyData(fl.Items())
  507. // The client reads the privacy state it renders (blocked buddies, the
  508. // block/unblock menu label) only from the permitDeny event, and it sees no
  509. // SNAC for the write it just made. Without this the block takes effect
  510. // server-side but the UI keeps showing the buddy as unblocked.
  511. session.EventQueue.Push(EventTypePermitDeny, pdd)
  512. h.Logger.DebugContext(ctx, "permit/deny settings updated",
  513. "screenName", session.ScreenName.String(),
  514. "pdMode", pdd.PDMode,
  515. "permitCount", len(pdd.PermitList),
  516. "denyCount", len(pdd.DenyList),
  517. )
  518. SendOK(w, r, pdd, h.Logger)
  519. }
  520. func permitDenyData(fl []wire.FeedbagItem) PermitDenyData {
  521. // A feedbag with no PD info item means no restrictions, the same default the
  522. // feedbag store applies. The client drives its block flow off pdMode and
  523. // sends no permit/deny change at all when the mode is absent.
  524. pdd := PermitDenyData{PDMode: "permitAll"}
  525. for _, item := range fl {
  526. switch item.ClassID {
  527. case wire.FeedbagClassIDDeny:
  528. pdd.DenyList = append(pdd.DenyList, item.Name)
  529. case wire.FeedbagClassIDPermit:
  530. pdd.PermitList = append(pdd.PermitList, item.Name)
  531. case wire.FeedbagClassIdPdinfo:
  532. mode, _ := item.Uint8(wire.FeedbagAttributesPdMode)
  533. switch wire.FeedbagPDMode(mode) {
  534. case wire.FeedbagPDModePermitAll:
  535. pdd.PDMode = "permitAll"
  536. case wire.FeedbagPDModeDenyAll:
  537. pdd.PDMode = "denyAll"
  538. case wire.FeedbagPDModePermitSome:
  539. pdd.PDMode = "permitSome"
  540. case wire.FeedbagPDModeDenySome:
  541. pdd.PDMode = "denySome"
  542. case wire.FeedbagPDModePermitOnList:
  543. pdd.PDMode = "permitOnList"
  544. }
  545. }
  546. }
  547. return pdd
  548. }
  549. // GetPermitDeny handles GET /preference/getPermitDeny requests to retrieve permit/deny settings.
  550. func (h *PreferenceHandler) GetPermitDeny(w http.ResponseWriter, r *http.Request, session *Session) {
  551. ctx := r.Context()
  552. frame := wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagQuery}
  553. fb, err := h.FeedbagService.Query(r.Context(), session.OSCARSession, frame)
  554. if err != nil {
  555. SendError(w, r, http.StatusInternalServerError, "failed to retrieve feedbag")
  556. return
  557. }
  558. reply, ok := fb.Body.(wire.SNAC_0x13_0x06_FeedbagReply)
  559. if !ok {
  560. SendError(w, r, http.StatusInternalServerError, "failed to retrieve feedbag")
  561. return
  562. }
  563. pdd := permitDenyData(reply.Items)
  564. h.Logger.DebugContext(ctx, "permit/deny settings retrieved",
  565. "screenName", session.ScreenName.String(),
  566. "pdMode", pdd.PDMode,
  567. "permitCount", len(pdd.PermitList),
  568. "denyCount", len(pdd.DenyList),
  569. )
  570. SendOK(w, r, pdd, h.Logger)
  571. }