preference_handler.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  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. // Send success response
  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. // Send response in requested format
  302. SendOK(w, r, payload, h.Logger)
  303. }
  304. // buddyPrefsItem returns the user's buddy-prefs feedbag item, creating a fresh
  305. // (empty) one if the feedbag does not have it yet.
  306. func buddyPrefsItem(ctx context.Context, fs FeedbagService, instance *state.SessionInstance) (wire.FeedbagItem, error) {
  307. frame := wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagQuery}
  308. fb, err := fs.Query(ctx, instance, frame)
  309. if err != nil {
  310. return wire.FeedbagItem{}, err
  311. }
  312. reply, ok := fb.Body.(wire.SNAC_0x13_0x06_FeedbagReply)
  313. if !ok {
  314. return wire.FeedbagItem{}, fmt.Errorf("unexpected feedbag reply type")
  315. }
  316. for _, item := range reply.Items {
  317. if item.ClassID == wire.FeedbagClassIdBuddyPrefs {
  318. return item, nil
  319. }
  320. }
  321. // No buddy-prefs item yet; create one. Only a single item of this class is
  322. // allowed, with an empty name and no group.
  323. return wire.FeedbagItem{
  324. ClassID: wire.FeedbagClassIdBuddyPrefs,
  325. ItemID: uint16(rand.Intn(0xFFFF)),
  326. }, nil
  327. }
  328. // effectiveBuddyPrefs returns the 0/1 value of every web buddy pref, using the
  329. // feedbag value when the pref's valid bit is set and the spec default otherwise.
  330. // This mirrors GetPreferences so the pushed preference event and the
  331. // preference/get endpoint agree: server-side defaults (e.g. showGroups) reach
  332. // the client even for prefs the user has never explicitly set. The web client
  333. // reads these from the startup preference event and has no other default for
  334. // them, so an omitted pref would silently fall back to the client's own hidden
  335. // default (which, for showGroups, hides group headers).
  336. func effectiveBuddyPrefs(list wire.TLVList) *PreferenceData {
  337. prefs := &PreferenceData{}
  338. for name, pref := range webBuddyPrefs {
  339. prefs.Set(name, effectivePrefValue(list, pref))
  340. }
  341. return prefs
  342. }
  343. // prefFieldIndex maps a preference name to its PreferenceData field.
  344. var prefFieldIndex = func() map[string]int {
  345. t := reflect.TypeOf(PreferenceData{})
  346. index := make(map[string]int, t.NumField())
  347. for i := 0; i < t.NumField(); i++ {
  348. name, _, _ := strings.Cut(t.Field(i).Tag.Get("json"), ",")
  349. index[name] = i
  350. }
  351. return index
  352. }()
  353. // Set records one preference by its Web API name, leaving every preference not
  354. // set this way absent from the payload. It reports whether the name is one this
  355. // server carries.
  356. func (p *PreferenceData) Set(name string, value int) bool {
  357. i, ok := prefFieldIndex[name]
  358. if !ok {
  359. return false
  360. }
  361. reflect.ValueOf(p).Elem().Field(i).Set(reflect.ValueOf(&value))
  362. return true
  363. }
  364. // Get returns a preference by its Web API name and whether it is carried.
  365. func (p *PreferenceData) Get(name string) (int, bool) {
  366. i, ok := prefFieldIndex[name]
  367. if !ok {
  368. return 0, false
  369. }
  370. field := reflect.ValueOf(p).Elem().Field(i)
  371. if field.IsNil() {
  372. return 0, false
  373. }
  374. return int(field.Elem().Int()), true
  375. }
  376. // Map returns the carried preferences keyed by Web API name, for the AMF path
  377. // that reshapes the payload rather than sending it as-is.
  378. func (p *PreferenceData) Map() map[string]any {
  379. out := make(map[string]any, len(prefFieldIndex))
  380. for name := range prefFieldIndex {
  381. if v, ok := p.Get(name); ok {
  382. out[name] = v
  383. }
  384. }
  385. return out
  386. }
  387. // Len reports how many preferences the payload carries.
  388. func (p *PreferenceData) Len() int {
  389. fields := reflect.ValueOf(p).Elem()
  390. n := 0
  391. for i := 0; i < fields.NumField(); i++ {
  392. if !fields.Field(i).IsNil() {
  393. n++
  394. }
  395. }
  396. return n
  397. }
  398. // effectivePrefValue returns the 0/1 value for the buddy pref prefNum, deferring
  399. // to wire.BuddyPref for both the stored value and its default. Values are emitted
  400. // as numbers (not "1"/"0" strings) because the web client evaluates them with
  401. // JavaScript truthiness/numeric comparisons, where the string "0" is truthy.
  402. func effectivePrefValue(list wire.TLVList, prefNum uint16) int {
  403. return boolToPrefInt(wire.BuddyPref(list, prefNum))
  404. }
  405. // parseBoolPref interprets a Web API preference query value as a boolean.
  406. func parseBoolPref(v string) bool {
  407. switch strings.ToLower(v) {
  408. case "1", "true", "yes", "on":
  409. return true
  410. default:
  411. return false
  412. }
  413. }
  414. func boolToPrefInt(b bool) int {
  415. if b {
  416. return 1
  417. }
  418. return 0
  419. }
  420. // SetPermitDeny handles GET /preference/setPermitDeny requests to update permit/deny settings.
  421. func (h *PreferenceHandler) SetPermitDeny(w http.ResponseWriter, r *http.Request, session *Session) {
  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. // Get pdMode parameter
  436. pdModeStr := r.URL.Query().Get("pdMode")
  437. if pdModeStr != "" {
  438. switch pdModeStr { // todo: are the string ints possible inputs?
  439. case "permitAll", "1":
  440. fl.SetMode(uint8(wire.FeedbagPDModePermitAll))
  441. case "denyAll", "2":
  442. fl.SetMode(uint8(wire.FeedbagPDModeDenyAll))
  443. case "permitSome", "3":
  444. fl.SetMode(uint8(wire.FeedbagPDModePermitSome))
  445. case "denySome", "4":
  446. fl.SetMode(uint8(wire.FeedbagPDModeDenySome))
  447. case "permitOnList", "5":
  448. fl.SetMode(uint8(wire.FeedbagPDModePermitOnList))
  449. default:
  450. SendError(w, r, http.StatusBadRequest, "invalid pdMode value")
  451. return
  452. }
  453. }
  454. // Handle permit list updates
  455. if pdAllow := r.URL.Query().Get("pdAllow"); pdAllow != "" {
  456. users := strings.Split(pdAllow, ",")
  457. for _, user := range users {
  458. user = strings.TrimSpace(user)
  459. if user != "" {
  460. fl.PermitUser(user)
  461. }
  462. }
  463. }
  464. if pdAllowRemove := r.URL.Query().Get("pdAllowRemove"); pdAllowRemove != "" {
  465. users := strings.Split(pdAllowRemove, ",")
  466. for _, user := range users {
  467. user = strings.TrimSpace(user)
  468. if user != "" {
  469. fl.DeletePermit(user)
  470. }
  471. }
  472. }
  473. // Handle deny list updates
  474. if pdBlock := r.URL.Query().Get("pdBlock"); pdBlock != "" {
  475. users := strings.Split(pdBlock, ",")
  476. for _, user := range users {
  477. user = strings.TrimSpace(user)
  478. if user != "" {
  479. fl.DenyUser(user)
  480. }
  481. }
  482. }
  483. if pdBlockRemove := r.URL.Query().Get("pdBlockRemove"); pdBlockRemove != "" {
  484. users := strings.Split(pdBlockRemove, ",")
  485. for _, user := range users {
  486. user = strings.TrimSpace(user)
  487. if user != "" {
  488. fl.DeleteDeny(user)
  489. }
  490. }
  491. }
  492. if pending := fl.PendingUpdates(); len(pending) > 0 {
  493. frame := wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagInsertItem}
  494. if _, err := h.FeedbagService.UpsertItem(ctx, session.OSCARSession, frame, pending); err != nil {
  495. h.Logger.ErrorContext(ctx, "failed to set PD mode", "err", err.Error())
  496. SendError(w, r, http.StatusInternalServerError, "failed to update PD mode")
  497. return
  498. }
  499. }
  500. if pending := fl.PendingDeletes(); len(pending) > 0 {
  501. frame := wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagDeleteItem}
  502. body := wire.SNAC_0x13_0x0A_FeedbagDeleteItem{Items: pending}
  503. if _, err := h.FeedbagService.DeleteItem(ctx, session.OSCARSession, frame, body); err != nil {
  504. h.Logger.ErrorContext(ctx, "failed to set PD mode", "err", err.Error())
  505. SendError(w, r, http.StatusInternalServerError, "failed to update PD mode")
  506. return
  507. }
  508. }
  509. pdd := permitDenyData(fl.Items())
  510. // The client reads the privacy state it renders (blocked buddies, the
  511. // block/unblock menu label) only from the permitDeny event, and it sees no
  512. // SNAC for the write it just made. Without this the block takes effect
  513. // server-side but the UI keeps showing the buddy as unblocked.
  514. session.EventQueue.Push(EventTypePermitDeny, pdd)
  515. h.Logger.DebugContext(ctx, "permit/deny settings updated",
  516. "screenName", session.ScreenName.String(),
  517. "pdMode", pdd.PDMode,
  518. "permitCount", len(pdd.PermitList),
  519. "denyCount", len(pdd.DenyList),
  520. )
  521. SendOK(w, r, pdd, h.Logger)
  522. }
  523. func permitDenyData(fl []wire.FeedbagItem) PermitDenyData {
  524. // A feedbag with no PD info item means no restrictions, the same default the
  525. // feedbag store applies. The client drives its block flow off pdMode and
  526. // sends no permit/deny change at all when the mode is absent.
  527. pdd := PermitDenyData{PDMode: "permitAll"}
  528. for _, item := range fl {
  529. switch item.ClassID {
  530. case wire.FeedbagClassIDDeny:
  531. pdd.DenyList = append(pdd.DenyList, item.Name)
  532. case wire.FeedbagClassIDPermit:
  533. pdd.PermitList = append(pdd.PermitList, item.Name)
  534. case wire.FeedbagClassIdPdinfo:
  535. mode, _ := item.Uint8(wire.FeedbagAttributesPdMode)
  536. switch wire.FeedbagPDMode(mode) {
  537. case wire.FeedbagPDModePermitAll:
  538. pdd.PDMode = "permitAll"
  539. case wire.FeedbagPDModeDenyAll:
  540. pdd.PDMode = "denyAll"
  541. case wire.FeedbagPDModePermitSome:
  542. pdd.PDMode = "permitSome"
  543. case wire.FeedbagPDModeDenySome:
  544. pdd.PDMode = "denySome"
  545. case wire.FeedbagPDModePermitOnList:
  546. pdd.PDMode = "permitOnList"
  547. }
  548. }
  549. }
  550. return pdd
  551. }
  552. // GetPermitDeny handles GET /preference/getPermitDeny requests to retrieve permit/deny settings.
  553. func (h *PreferenceHandler) GetPermitDeny(w http.ResponseWriter, r *http.Request, session *Session) {
  554. ctx := r.Context()
  555. frame := wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagQuery}
  556. fb, err := h.FeedbagService.Query(r.Context(), session.OSCARSession, frame)
  557. if err != nil {
  558. SendError(w, r, http.StatusInternalServerError, "failed to retrieve feedbag")
  559. return
  560. }
  561. reply, ok := fb.Body.(wire.SNAC_0x13_0x06_FeedbagReply)
  562. if !ok {
  563. SendError(w, r, http.StatusInternalServerError, "failed to retrieve feedbag")
  564. return
  565. }
  566. pdd := permitDenyData(reply.Items)
  567. h.Logger.DebugContext(ctx, "permit/deny settings retrieved",
  568. "screenName", session.ScreenName.String(),
  569. "pdMode", pdd.PDMode,
  570. "permitCount", len(pdd.PermitList),
  571. "denyCount", len(pdd.DenyList),
  572. )
  573. SendOK(w, r, pdd, h.Logger)
  574. }