buddylist_handler.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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. target := state.NewIdentScreenName(buddyName)
  150. fl.AddGroup(groupName)
  151. if pending := fl.PendingUpdates(); len(pending) > 0 {
  152. frame := wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagInsertItem}
  153. if _, err := h.FeedbagService.UpsertItem(ctx, sess.OSCARSession, frame, pending); err != nil {
  154. h.Logger.ErrorContext(ctx, "failed to add buddy", "err", err.Error())
  155. return "error"
  156. }
  157. }
  158. added, err := fl.AddBuddy(groupName, buddyName, "", "")
  159. if err != nil {
  160. h.Logger.ErrorContext(ctx, "failed to add buddy to feedbag", "err", err.Error())
  161. return "error"
  162. }
  163. if !added {
  164. return "alreadyExists"
  165. }
  166. if pending := fl.PendingUpdates(); len(pending) > 0 {
  167. buddyItems := make(map[uint16][]wire.FeedbagItem)
  168. for _, item := range pending {
  169. if item.ClassID == wire.FeedbagClassIdBuddy {
  170. if _, ok := buddyItems[item.GroupID]; !ok {
  171. buddyItems[item.GroupID] = nil
  172. }
  173. buddyItems[item.GroupID] = append(buddyItems[item.GroupID], item)
  174. }
  175. }
  176. if sess.OSCARSession.UIN() != 0 && target.UIN() != 0 {
  177. for _, buddies := range buddyItems {
  178. for i := range buddies {
  179. if state.NewIdentScreenName(buddies[i].Name) == target {
  180. buddies[i].Append(wire.NewTLVBE(wire.FeedbagAttributesPending, []byte{}))
  181. }
  182. }
  183. }
  184. }
  185. for _, buddies := range buddyItems {
  186. frame := wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagInsertItem}
  187. if _, err := h.FeedbagService.UpsertItem(ctx, sess.OSCARSession, frame, buddies); err != nil {
  188. h.Logger.ErrorContext(ctx, "failed to add buddy", "err", err.Error())
  189. return "error"
  190. }
  191. }
  192. for _, item := range pending { // todo why not filter buddies out of pending?
  193. if item.ClassID == wire.FeedbagClassIdGroup {
  194. frame := wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagUpdateItem}
  195. if _, err := h.FeedbagService.UpsertItem(ctx, sess.OSCARSession, frame, []wire.FeedbagItem{item}); err != nil {
  196. h.Logger.ErrorContext(ctx, "failed to add buddy", "err", err.Error())
  197. return "error"
  198. }
  199. }
  200. }
  201. }
  202. if preAuthorized {
  203. frame := wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagPreAuthorizeBuddy}
  204. body := wire.SNAC_0x13_0x14_FeedbagPreAuthorizeBuddy{
  205. ScreenName: buddyName,
  206. Message: authorizationMsg,
  207. }
  208. if _, err := h.FeedbagService.PreAuthorizeBuddy(ctx, sess.OSCARSession, frame, body); err != nil {
  209. h.Logger.ErrorContext(ctx, "failed to pre-authorize buddy",
  210. "buddy", buddyName, "err", err.Error())
  211. }
  212. }
  213. return resultSuccess
  214. }
  215. // RenameGroup handles GET /buddylist/renameGroup requests.
  216. //
  217. // The Web AIM client calls this with oldGroup (current group name) and newGroup
  218. // (the requested new name). This is a stub; it does not yet rename the group in
  219. // the feedbag.
  220. func (h *BuddyListHandler) RenameGroup(w http.ResponseWriter, r *http.Request, session *Session) {
  221. ctx := r.Context()
  222. aimsid := r.URL.Query().Get("aimsid")
  223. oldGroup := strings.TrimSpace(r.URL.Query().Get("oldGroup"))
  224. newGroup := strings.TrimSpace(r.URL.Query().Get("newGroup"))
  225. if oldGroup == "" || newGroup == "" {
  226. SendError(w, r, http.StatusBadRequest, "missing oldGroup or newGroup parameter")
  227. return
  228. }
  229. resultCode, rnErr := h.BuddyListManager.RenameGroupInFeedbag(ctx, session, oldGroup, newGroup)
  230. if rnErr != nil {
  231. h.Logger.ErrorContext(ctx, "rename group failed", "err", rnErr.Error())
  232. }
  233. sendMutationResult(w, r, resultCode, h.Logger)
  234. h.Logger.InfoContext(ctx, "buddy list group renamed",
  235. "aimsid", aimsid,
  236. "oldGroup", oldGroup,
  237. "newGroup", newGroup,
  238. "result", resultCode,
  239. )
  240. }
  241. // MoveBuddy handles GET /buddylist/moveBuddy requests.
  242. //
  243. // The Web AIM client calls this with buddy (the buddy to move), group (the
  244. // current group), and optionally newGroup (destination group) and beforeBuddy
  245. // (buddy to position it before). This is a stub; it does not yet move the buddy
  246. // in the feedbag.
  247. func (h *BuddyListHandler) MoveBuddy(w http.ResponseWriter, r *http.Request, session *Session) {
  248. ctx := r.Context()
  249. aimsid := r.URL.Query().Get("aimsid")
  250. buddyName := strings.TrimSpace(r.URL.Query().Get("buddy"))
  251. groupName := strings.TrimSpace(r.URL.Query().Get("group"))
  252. newGroup := strings.TrimSpace(r.URL.Query().Get("newGroup"))
  253. beforeBuddy := strings.TrimSpace(r.URL.Query().Get("beforeBuddy"))
  254. if buddyName == "" {
  255. SendError(w, r, http.StatusBadRequest, "missing buddy parameter")
  256. return
  257. }
  258. if groupName == "" {
  259. SendError(w, r, http.StatusBadRequest, "missing group parameter")
  260. return
  261. }
  262. resultCode, mvErr := h.BuddyListManager.MoveBuddyInFeedbag(ctx, session, buddyName, groupName, newGroup, beforeBuddy)
  263. if mvErr != nil {
  264. h.Logger.ErrorContext(ctx, "move buddy failed", "err", mvErr.Error())
  265. }
  266. sendMutationResult(w, r, resultCode, h.Logger)
  267. h.Logger.InfoContext(ctx, "buddy moved",
  268. "aimsid", aimsid,
  269. "buddy", buddyName,
  270. "group", groupName,
  271. "newGroup", newGroup,
  272. "beforeBuddy", beforeBuddy,
  273. "result", resultCode,
  274. )
  275. }
  276. // SetBuddyAttribute handles GET /buddylist/setBuddyAttribute requests.
  277. //
  278. // The Web AIM client calls this with t (the buddy) and friendly (the display
  279. // name / alias). This is a stub; it does not yet persist the attribute to the
  280. // feedbag.
  281. func (h *BuddyListHandler) SetBuddyAttribute(w http.ResponseWriter, r *http.Request, session *Session) {
  282. ctx := r.Context()
  283. aimsid := r.URL.Query().Get("aimsid")
  284. buddyName := strings.TrimSpace(r.URL.Query().Get("t"))
  285. friendly := strings.TrimSpace(r.URL.Query().Get("friendly"))
  286. if buddyName == "" {
  287. SendError(w, r, http.StatusBadRequest, "missing t parameter")
  288. return
  289. }
  290. resultCode, saErr := h.BuddyListManager.SetBuddyAttributeInFeedbag(ctx, session, buddyName, friendly)
  291. if saErr != nil {
  292. h.Logger.ErrorContext(ctx, "set buddy attribute failed", "err", saErr.Error())
  293. }
  294. sendMutationResult(w, r, resultCode, h.Logger)
  295. h.Logger.InfoContext(ctx, "buddy attribute set",
  296. "aimsid", aimsid,
  297. "buddy", buddyName,
  298. "friendly", friendly,
  299. "result", resultCode,
  300. )
  301. }
  302. // SetGroupAttribute handles GET /buddylist/setGroupAttribute requests.
  303. //
  304. // The Web AIM client calls this with collapsed (the group's collapsed state)
  305. // and, for named groups, group. The unnamed default group omits group. This is
  306. // a stub; it does not yet persist the attribute to the feedbag.
  307. func (h *BuddyListHandler) SetGroupAttribute(w http.ResponseWriter, r *http.Request, session *Session) {
  308. ctx := r.Context()
  309. aimsid := r.URL.Query().Get("aimsid")
  310. query := r.URL.Query()
  311. groupName := strings.TrimSpace(query.Get("group"))
  312. collapsedParam := strings.TrimSpace(query.Get("collapsed"))
  313. if collapsedParam == "" {
  314. SendError(w, r, http.StatusBadRequest, "missing collapsed parameter")
  315. return
  316. }
  317. collapsed := collapsedParam == "true" || collapsedParam == "1"
  318. resultCode, saErr := h.BuddyListManager.SetGroupAttributeInFeedbag(ctx, session, groupName, collapsed)
  319. if saErr != nil {
  320. h.Logger.ErrorContext(ctx, "set group attribute failed", "err", saErr.Error())
  321. }
  322. sendMutationResult(w, r, resultCode, h.Logger)
  323. h.Logger.InfoContext(ctx, "buddy list group attribute set",
  324. "aimsid", aimsid,
  325. "group", groupName,
  326. "collapsed", collapsed,
  327. "result", resultCode,
  328. )
  329. }
  330. // resultSuccess is the result code the buddy list methods no longer report; see
  331. // sendMutationResult.
  332. const resultSuccess = "success"
  333. func sendMutationResult(w http.ResponseWriter, r *http.Request, resultCode string, logger *slog.Logger) {
  334. if resultCode == resultSuccess {
  335. // Nil data renders as an empty "data":{} — no resultCode, no buddyInfo.
  336. SendOK(w, r, nil, logger)
  337. return
  338. }
  339. SendOK(w, r, &ResultCodeData{ResultCode: resultCode}, logger)
  340. }
  341. // ResultCodeData is the payload the buddy list editing methods answer with.
  342. //
  343. // The spec shows these methods returning an empty data; the Web AIM client
  344. // reads resultCode from it, so the server sends one.
  345. type ResultCodeData struct {
  346. ResultCode string `json:"resultCode" xml:"resultCode"`
  347. }