buddylist_handler.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. package webapi
  2. import (
  3. "context"
  4. "log/slog"
  5. "math/rand"
  6. "net/http"
  7. "strings"
  8. "github.com/mk6i/open-oscar-server/state"
  9. "github.com/mk6i/open-oscar-server/wire"
  10. )
  11. // BuddyListHandler handles Web AIM API buddy list management endpoints.
  12. type BuddyListHandler struct {
  13. BuddyListManager *BuddyListManager
  14. Logger *slog.Logger
  15. FeedbagService FeedbagService
  16. }
  17. // AddBuddy handles GET /buddylist/addBuddy requests.
  18. func (h *BuddyListHandler) AddBuddy(w http.ResponseWriter, r *http.Request, session *Session) {
  19. ctx := r.Context()
  20. aimsid := r.URL.Query().Get("aimsid")
  21. buddyName := strings.TrimSpace(param(r, "buddy"))
  22. groupName := strings.TrimSpace(param(r, "group"))
  23. preAuthorized := isTrueParam(param(r, "preAuthorized"))
  24. authorizationMsg := strings.TrimSpace(param(r, "authorizationMsg"))
  25. if buddyName == "" {
  26. SendError(w, r, http.StatusBadRequest, "missing buddy parameter")
  27. return
  28. }
  29. if groupName == "" {
  30. groupName = "Buddies" // Default group
  31. }
  32. // Add buddy to feedbag
  33. resultCode := h.addBuddyToFeedbag(ctx, session, buddyName, groupName, preAuthorized, authorizationMsg)
  34. // Prepare response
  35. sendMutationResult(w, r, resultCode, h.Logger)
  36. h.Logger.InfoContext(ctx, "buddy added",
  37. "aimsid", aimsid,
  38. "buddy", buddyName,
  39. "group", groupName,
  40. "preAuthorized", preAuthorized,
  41. "result", resultCode,
  42. )
  43. }
  44. // AddGroup handles GET /buddylist/addGroup requests.
  45. func (h *BuddyListHandler) AddGroup(w http.ResponseWriter, r *http.Request, session *Session) {
  46. ctx := r.Context()
  47. aimsid := r.URL.Query().Get("aimsid")
  48. groupName := strings.TrimSpace(r.URL.Query().Get("group"))
  49. if groupName == "" {
  50. SendError(w, r, http.StatusBadRequest, "missing group parameter")
  51. return
  52. }
  53. resultCode := h.addGroupToFeedbag(ctx, session, groupName)
  54. sendMutationResult(w, r, resultCode, h.Logger)
  55. h.Logger.InfoContext(ctx, "buddy list group added",
  56. "aimsid", aimsid,
  57. "group", groupName,
  58. "result", resultCode,
  59. )
  60. }
  61. func (h *BuddyListHandler) addGroupToFeedbag(ctx context.Context, sess *Session, groupName string) string {
  62. // A session sees no SNAC for its own feedbag writes, so it drops the alias
  63. // cache itself. See WebAPISession.InvalidateAliases.
  64. defer sess.InvalidateAliases()
  65. frame := wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagQuery}
  66. snac, err := h.FeedbagService.Query(ctx, sess.OSCARSession, frame)
  67. if err != nil {
  68. h.Logger.ErrorContext(ctx, "failed to retrieve feedbag", "err", err.Error())
  69. return "error"
  70. }
  71. reply, ok := snac.Body.(wire.SNAC_0x13_0x06_FeedbagReply)
  72. if !ok {
  73. return "error"
  74. }
  75. fl := state.NewFeedbagList(reply.Items, rand.Intn)
  76. fl.AddGroup(groupName)
  77. pending := fl.PendingUpdates()
  78. if len(pending) == 0 {
  79. return "alreadyExists"
  80. }
  81. insertFrame := wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagInsertItem}
  82. if _, err := h.FeedbagService.UpsertItem(ctx, sess.OSCARSession, insertFrame, pending); err != nil {
  83. h.Logger.ErrorContext(ctx, "failed to add group", "err", err.Error())
  84. return "error"
  85. }
  86. return resultSuccess
  87. }
  88. // RemoveBuddy handles GET /buddylist/removeBuddy requests.
  89. func (h *BuddyListHandler) RemoveBuddy(w http.ResponseWriter, r *http.Request, session *Session) {
  90. ctx := r.Context()
  91. aimsid := r.URL.Query().Get("aimsid")
  92. buddyName := strings.TrimSpace(r.URL.Query().Get("buddy"))
  93. groupName := strings.TrimSpace(r.URL.Query().Get("group"))
  94. allGroupsParam := r.URL.Query().Get("allGroups")
  95. allGroups := allGroupsParam == "true" || allGroupsParam == "1"
  96. if buddyName == "" {
  97. SendError(w, r, http.StatusBadRequest, "missing buddy parameter")
  98. return
  99. }
  100. resultCode, rmErr := h.BuddyListManager.RemoveBuddyFromFeedbag(ctx, session, buddyName, groupName, allGroups)
  101. if rmErr != nil {
  102. h.Logger.ErrorContext(ctx, "remove buddy failed", "err", rmErr.Error())
  103. }
  104. sendMutationResult(w, r, resultCode, h.Logger)
  105. h.Logger.InfoContext(ctx, "buddy removed",
  106. "aimsid", aimsid,
  107. "buddy", buddyName,
  108. "group", groupName,
  109. "result", resultCode,
  110. )
  111. }
  112. // todo don't remove empty group?
  113. // RemoveGroup handles GET /buddylist/removeGroup requests.
  114. func (h *BuddyListHandler) RemoveGroup(w http.ResponseWriter, r *http.Request, session *Session) {
  115. ctx := r.Context()
  116. aimsid := r.URL.Query().Get("aimsid")
  117. groupName := strings.TrimSpace(r.URL.Query().Get("group"))
  118. if groupName == "" {
  119. SendError(w, r, http.StatusBadRequest, "missing group parameter")
  120. return
  121. }
  122. resultCode, rmErr := h.BuddyListManager.RemoveGroupFromFeedbag(ctx, session, groupName)
  123. if rmErr != nil {
  124. h.Logger.ErrorContext(ctx, "remove group failed", "err", rmErr.Error())
  125. }
  126. sendMutationResult(w, r, resultCode, h.Logger)
  127. h.Logger.InfoContext(ctx, "buddy list group removed",
  128. "aimsid", aimsid,
  129. "group", groupName,
  130. "result", resultCode,
  131. )
  132. }
  133. // addBuddyToFeedbag adds a buddy to the user's feedbag.
  134. func (h *BuddyListHandler) addBuddyToFeedbag(ctx context.Context, sess *Session, buddyName, groupName string, preAuthorized bool, authorizationMsg string) string {
  135. defer sess.InvalidateAliases()
  136. // Retrieve current feedbag
  137. frame := wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagQuery}
  138. snac, err := h.FeedbagService.Query(ctx, sess.OSCARSession, frame)
  139. if err != nil {
  140. h.Logger.ErrorContext(ctx, "failed to retrieve feedbag", "err", err.Error())
  141. return "error"
  142. }
  143. reply, ok := snac.Body.(wire.SNAC_0x13_0x06_FeedbagReply)
  144. if !ok {
  145. // todo what
  146. return "error"
  147. }
  148. fl := state.NewFeedbagList(reply.Items, rand.Intn)
  149. fl.AddGroup(groupName)
  150. if pending := fl.PendingUpdates(); len(pending) > 0 {
  151. frame := wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagInsertItem}
  152. if _, err := h.FeedbagService.UpsertItem(ctx, sess.OSCARSession, frame, pending); err != nil {
  153. h.Logger.ErrorContext(ctx, "failed to add buddy", "err", err.Error())
  154. return "error"
  155. }
  156. }
  157. added, err := fl.AddBuddy(groupName, buddyName, "", "")
  158. if err != nil {
  159. h.Logger.ErrorContext(ctx, "failed to add buddy to feedbag", "err", err.Error())
  160. return "error"
  161. }
  162. if !added {
  163. return "alreadyExists"
  164. }
  165. if pending := fl.PendingUpdates(); len(pending) > 0 {
  166. buddyItems := make(map[uint16][]wire.FeedbagItem)
  167. for _, item := range pending {
  168. if item.ClassID == wire.FeedbagClassIdBuddy {
  169. if _, ok := buddyItems[item.GroupID]; !ok {
  170. buddyItems[item.GroupID] = nil
  171. }
  172. buddyItems[item.GroupID] = append(buddyItems[item.GroupID], item)
  173. }
  174. }
  175. for _, buddies := range buddyItems {
  176. frame := wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagInsertItem}
  177. if _, err := h.FeedbagService.UpsertItem(ctx, sess.OSCARSession, frame, buddies); err != nil {
  178. h.Logger.ErrorContext(ctx, "failed to add buddy", "err", err.Error())
  179. return "error"
  180. }
  181. }
  182. for _, item := range pending { // todo why not filter buddies out of pending?
  183. if item.ClassID == wire.FeedbagClassIdGroup {
  184. frame := wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagUpdateItem}
  185. if _, err := h.FeedbagService.UpsertItem(ctx, sess.OSCARSession, frame, []wire.FeedbagItem{item}); err != nil {
  186. h.Logger.ErrorContext(ctx, "failed to add buddy", "err", err.Error())
  187. return "error"
  188. }
  189. }
  190. }
  191. }
  192. if preAuthorized {
  193. frame := wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagPreAuthorizeBuddy}
  194. body := wire.SNAC_0x13_0x14_FeedbagPreAuthorizeBuddy{
  195. ScreenName: buddyName,
  196. Message: authorizationMsg,
  197. }
  198. if _, err := h.FeedbagService.PreAuthorizeBuddy(ctx, sess.OSCARSession, frame, body); err != nil {
  199. h.Logger.ErrorContext(ctx, "failed to pre-authorize buddy",
  200. "buddy", buddyName, "err", err.Error())
  201. }
  202. }
  203. return resultSuccess
  204. }
  205. // RenameGroup handles GET /buddylist/renameGroup requests.
  206. //
  207. // The Web AIM client calls this with oldGroup (current group name) and newGroup
  208. // (the requested new name). This is a stub; it does not yet rename the group in
  209. // the feedbag.
  210. func (h *BuddyListHandler) RenameGroup(w http.ResponseWriter, r *http.Request, session *Session) {
  211. ctx := r.Context()
  212. aimsid := r.URL.Query().Get("aimsid")
  213. oldGroup := strings.TrimSpace(r.URL.Query().Get("oldGroup"))
  214. newGroup := strings.TrimSpace(r.URL.Query().Get("newGroup"))
  215. if oldGroup == "" || newGroup == "" {
  216. SendError(w, r, http.StatusBadRequest, "missing oldGroup or newGroup parameter")
  217. return
  218. }
  219. resultCode, rnErr := h.BuddyListManager.RenameGroupInFeedbag(ctx, session, oldGroup, newGroup)
  220. if rnErr != nil {
  221. h.Logger.ErrorContext(ctx, "rename group failed", "err", rnErr.Error())
  222. }
  223. sendMutationResult(w, r, resultCode, h.Logger)
  224. h.Logger.InfoContext(ctx, "buddy list group renamed",
  225. "aimsid", aimsid,
  226. "oldGroup", oldGroup,
  227. "newGroup", newGroup,
  228. "result", resultCode,
  229. )
  230. }
  231. // MoveBuddy handles GET /buddylist/moveBuddy requests.
  232. //
  233. // The Web AIM client calls this with buddy (the buddy to move), group (the
  234. // current group), and optionally newGroup (destination group) and beforeBuddy
  235. // (buddy to position it before). This is a stub; it does not yet move the buddy
  236. // in the feedbag.
  237. func (h *BuddyListHandler) MoveBuddy(w http.ResponseWriter, r *http.Request, session *Session) {
  238. ctx := r.Context()
  239. aimsid := r.URL.Query().Get("aimsid")
  240. buddyName := strings.TrimSpace(r.URL.Query().Get("buddy"))
  241. groupName := strings.TrimSpace(r.URL.Query().Get("group"))
  242. newGroup := strings.TrimSpace(r.URL.Query().Get("newGroup"))
  243. beforeBuddy := strings.TrimSpace(r.URL.Query().Get("beforeBuddy"))
  244. if buddyName == "" {
  245. SendError(w, r, http.StatusBadRequest, "missing buddy parameter")
  246. return
  247. }
  248. if groupName == "" {
  249. SendError(w, r, http.StatusBadRequest, "missing group parameter")
  250. return
  251. }
  252. resultCode, mvErr := h.BuddyListManager.MoveBuddyInFeedbag(ctx, session, buddyName, groupName, newGroup, beforeBuddy)
  253. if mvErr != nil {
  254. h.Logger.ErrorContext(ctx, "move buddy failed", "err", mvErr.Error())
  255. }
  256. sendMutationResult(w, r, resultCode, h.Logger)
  257. h.Logger.InfoContext(ctx, "buddy moved",
  258. "aimsid", aimsid,
  259. "buddy", buddyName,
  260. "group", groupName,
  261. "newGroup", newGroup,
  262. "beforeBuddy", beforeBuddy,
  263. "result", resultCode,
  264. )
  265. }
  266. // SetBuddyAttribute handles GET /buddylist/setBuddyAttribute requests.
  267. //
  268. // The Web AIM client calls this with t (the buddy) and friendly (the display
  269. // name / alias). This is a stub; it does not yet persist the attribute to the
  270. // feedbag.
  271. func (h *BuddyListHandler) SetBuddyAttribute(w http.ResponseWriter, r *http.Request, session *Session) {
  272. ctx := r.Context()
  273. aimsid := r.URL.Query().Get("aimsid")
  274. buddyName := strings.TrimSpace(r.URL.Query().Get("t"))
  275. friendly := strings.TrimSpace(r.URL.Query().Get("friendly"))
  276. if buddyName == "" {
  277. SendError(w, r, http.StatusBadRequest, "missing t parameter")
  278. return
  279. }
  280. resultCode, saErr := h.BuddyListManager.SetBuddyAttributeInFeedbag(ctx, session, buddyName, friendly)
  281. if saErr != nil {
  282. h.Logger.ErrorContext(ctx, "set buddy attribute failed", "err", saErr.Error())
  283. }
  284. sendMutationResult(w, r, resultCode, h.Logger)
  285. h.Logger.InfoContext(ctx, "buddy attribute set",
  286. "aimsid", aimsid,
  287. "buddy", buddyName,
  288. "friendly", friendly,
  289. "result", resultCode,
  290. )
  291. }
  292. // SetGroupAttribute handles GET /buddylist/setGroupAttribute requests.
  293. //
  294. // The Web AIM client calls this with collapsed (the group's collapsed state)
  295. // and, for named groups, group. The unnamed default group omits group. This is
  296. // a stub; it does not yet persist the attribute to the feedbag.
  297. func (h *BuddyListHandler) SetGroupAttribute(w http.ResponseWriter, r *http.Request, session *Session) {
  298. ctx := r.Context()
  299. aimsid := r.URL.Query().Get("aimsid")
  300. query := r.URL.Query()
  301. groupName := strings.TrimSpace(query.Get("group"))
  302. collapsedParam := strings.TrimSpace(query.Get("collapsed"))
  303. if collapsedParam == "" {
  304. SendError(w, r, http.StatusBadRequest, "missing collapsed parameter")
  305. return
  306. }
  307. collapsed := collapsedParam == "true" || collapsedParam == "1"
  308. resultCode, saErr := h.BuddyListManager.SetGroupAttributeInFeedbag(ctx, session, groupName, collapsed)
  309. if saErr != nil {
  310. h.Logger.ErrorContext(ctx, "set group attribute failed", "err", saErr.Error())
  311. }
  312. sendMutationResult(w, r, resultCode, h.Logger)
  313. h.Logger.InfoContext(ctx, "buddy list group attribute set",
  314. "aimsid", aimsid,
  315. "group", groupName,
  316. "collapsed", collapsed,
  317. "result", resultCode,
  318. )
  319. }
  320. // resultSuccess is the result code the buddy list methods no longer report; see
  321. // sendMutationResult.
  322. const resultSuccess = "success"
  323. func sendMutationResult(w http.ResponseWriter, r *http.Request, resultCode string, logger *slog.Logger) {
  324. if resultCode == resultSuccess {
  325. // Nil data renders as an empty "data":{} — no resultCode, no buddyInfo.
  326. SendOK(w, r, nil, logger)
  327. return
  328. }
  329. SendOK(w, r, &ResultCodeData{ResultCode: resultCode}, logger)
  330. }
  331. // ResultCodeData is the payload the buddy list editing methods answer with.
  332. //
  333. // The spec shows these methods returning an empty data; the Web AIM client
  334. // reads resultCode from it, so the server sends one.
  335. type ResultCodeData struct {
  336. ResultCode string `json:"resultCode" xml:"resultCode"`
  337. }