4
0

memberdir.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. package handlers
  2. import (
  3. "context"
  4. "fmt"
  5. "log/slog"
  6. "net/http"
  7. "strconv"
  8. "strings"
  9. "github.com/mk6i/open-oscar-server/state"
  10. "github.com/mk6i/open-oscar-server/wire"
  11. )
  12. // defaultMemberDirLimit caps how many directory search results are returned
  13. // when the client does not specify nToGet.
  14. const defaultMemberDirLimit = 100
  15. // maxMemberDirTargets caps how many screen names a single memberDir/get may
  16. // resolve. Every target costs its own directory lookup, and the web client only
  17. // ever asks for one, so this bounds the fan-out an arbitrary "t" list can force.
  18. const maxMemberDirTargets = 20
  19. // DirSearchService issues OSCAR ODir directory searches. A single InfoQuery
  20. // dispatches to name/address, email, or interest-keyword search based on which
  21. // TLVs the query carries.
  22. type DirSearchService interface {
  23. InfoQuery(ctx context.Context, inFrame wire.SNACFrame, inBody wire.SNAC_0x0F_0x02_InfoQuery) (wire.SNACMessage, error)
  24. }
  25. // MemberDirLocateService reads and writes stored directory info. memberDir/get
  26. // reads the requested screen names' profiles via DirInfo; memberDir/update
  27. // writes the caller's own via SetDirInfo.
  28. type MemberDirLocateService interface {
  29. DirInfo(ctx context.Context, inFrame wire.SNACFrame, inBody wire.SNAC_0x02_0x0B_LocateGetDirInfo) (wire.SNACMessage, error)
  30. SetDirInfo(ctx context.Context, instance *state.SessionInstance, inFrame wire.SNACFrame, inBody wire.SNAC_0x02_0x09_LocateSetDirInfo) (wire.SNACMessage, error)
  31. }
  32. // dirInfoTags are the directory fields carried in both the ODir get reply and
  33. // the locate set request. SetDirectoryInfo replaces every column, so
  34. // memberDir/update re-sends all of them to preserve fields the web form (which
  35. // only edits first/last name) does not touch.
  36. var dirInfoTags = []uint16{
  37. wire.ODirTLVFirstName,
  38. wire.ODirTLVLastName,
  39. wire.ODirTLVMiddleName,
  40. wire.ODirTLVMaidenName,
  41. wire.ODirTLVCountry,
  42. wire.ODirTLVState,
  43. wire.ODirTLVCity,
  44. wire.ODirTLVNickName,
  45. wire.ODirTLVZIP,
  46. wire.ODirTLVAddress,
  47. }
  48. // MemberDirHandler handles Web AIM API member-directory endpoints
  49. // (memberDir/search, memberDir/get, and memberDir/update).
  50. type MemberDirHandler struct {
  51. DirSearchService DirSearchService
  52. LocateService MemberDirLocateService
  53. Logger *slog.Logger
  54. }
  55. // MemberDirProfile is the per-result directory profile the web client consumes.
  56. // The client keys users by AimID and, for its own directory info, renders
  57. // FirstName/LastName.
  58. type MemberDirProfile struct {
  59. AimID string `json:"aimId" xml:"aimId"`
  60. DisplayID string `json:"displayId,omitempty" xml:"displayId,omitempty"`
  61. FirstName string `json:"firstName,omitempty" xml:"firstName,omitempty"`
  62. LastName string `json:"lastName,omitempty" xml:"lastName,omitempty"`
  63. State string `json:"state,omitempty" xml:"state,omitempty"`
  64. City string `json:"city,omitempty" xml:"city,omitempty"`
  65. Country string `json:"country,omitempty" xml:"country,omitempty"`
  66. }
  67. // MemberDirInfo wraps a profile in the "info" envelope the client expects:
  68. // results are read as data.results.infoArray[i].profile for search and
  69. // data.infoArray[0].profile for get.
  70. type MemberDirInfo struct {
  71. Profile MemberDirProfile `json:"profile" xml:"profile"`
  72. }
  73. // MemberDirResults wraps a directory search result set.
  74. type MemberDirResults struct {
  75. Results MemberDirInfoArray `json:"results" xml:"results"`
  76. }
  77. // MemberDirInfoArray is the list of matched profiles.
  78. type MemberDirInfoArray struct {
  79. InfoArray []MemberDirInfo `json:"infoArray" xml:"infoArray>info"`
  80. }
  81. // Search handles GET /memberDir/search. The web client sends the raw add-contact
  82. // input as a "match" parameter shaped like "keyword=<x>" or
  83. // "firstName=<x>,lastName=<y>". We translate that into an OSCAR ODir InfoQuery
  84. // and let the ODir service pick the search mode.
  85. func (h *MemberDirHandler) Search(w http.ResponseWriter, r *http.Request, session *state.WebAPISession) {
  86. ctx := r.Context()
  87. fields := parseMatch(r.URL.Query().Get("match"))
  88. inBody := buildDirInfoQuery(fields)
  89. reply, err := h.DirSearchService.InfoQuery(ctx, wire.SNACFrame{}, inBody)
  90. if err != nil {
  91. h.Logger.ErrorContext(ctx, "memberDir search failed", "err", err.Error())
  92. h.sendData(w, r, &MemberDirResults{Results: MemberDirInfoArray{InfoArray: []MemberDirInfo{}}})
  93. return
  94. }
  95. body, ok := reply.Body.(wire.SNAC_0x0F_0x03_InfoReply)
  96. if !ok || body.Status != wire.ODirSearchResponseOK {
  97. // Missing/insufficient params or an empty directory: return no results
  98. // rather than an error so the client simply shows an empty result set.
  99. h.sendData(w, r, &MemberDirResults{Results: MemberDirInfoArray{InfoArray: []MemberDirInfo{}}})
  100. return
  101. }
  102. limit := defaultMemberDirLimit
  103. if v := r.URL.Query().Get("nToGet"); v != "" {
  104. if n, err := strconv.Atoi(v); err == nil && n > 0 {
  105. limit = n
  106. }
  107. }
  108. self := session.ScreenName.IdentScreenName()
  109. infoArray := make([]MemberDirInfo, 0, len(body.Results.List))
  110. for _, result := range body.Results.List {
  111. profile := MemberDirProfile{}
  112. if sn, ok := result.String(wire.ODirTLVScreenName); ok && sn != "" {
  113. profile.DisplayID = sn
  114. profile.AimID = state.NewIdentScreenName(sn).String()
  115. }
  116. profile.FirstName, _ = result.String(wire.ODirTLVFirstName)
  117. profile.LastName, _ = result.String(wire.ODirTLVLastName)
  118. profile.State, _ = result.String(wire.ODirTLVState)
  119. profile.City, _ = result.String(wire.ODirTLVCity)
  120. profile.Country, _ = result.String(wire.ODirTLVCountry)
  121. // Exclude the requesting user from their own search results.
  122. if profile.AimID == self.String() {
  123. continue
  124. }
  125. infoArray = append(infoArray, MemberDirInfo{Profile: profile})
  126. if len(infoArray) >= limit {
  127. break
  128. }
  129. }
  130. h.Logger.DebugContext(ctx, "memberDir search",
  131. "aimsid", session.AimSID,
  132. "match", r.URL.Query().Get("match"),
  133. "results", len(infoArray),
  134. )
  135. h.sendData(w, r, &MemberDirResults{Results: MemberDirInfoArray{InfoArray: infoArray}})
  136. }
  137. // Get handles GET /memberDir/get. The "t" param names the screen names to look
  138. // up, defaulting to the caller when absent. Each returned profile carries the
  139. // identity of the target it describes.
  140. func (h *MemberDirHandler) Get(w http.ResponseWriter, r *http.Request, session *state.WebAPISession) {
  141. ctx := r.Context()
  142. targets := parseTargets(r.URL.Query().Get("t"))
  143. if len(targets) == 0 {
  144. targets = []string{session.ScreenName.String()}
  145. }
  146. if len(targets) > maxMemberDirTargets {
  147. h.Logger.WarnContext(ctx, "memberDir get: truncating oversized target list",
  148. "aimsid", session.AimSID,
  149. "requested", len(targets),
  150. "cap", maxMemberDirTargets,
  151. )
  152. targets = targets[:maxMemberDirTargets]
  153. }
  154. infoArray := make([]MemberDirInfo, 0, len(targets))
  155. for _, target := range targets {
  156. reply, err := h.LocateService.DirInfo(ctx, wire.SNACFrame{}, wire.SNAC_0x02_0x0B_LocateGetDirInfo{ScreenName: target})
  157. if err != nil {
  158. h.Logger.ErrorContext(ctx, "memberDir get failed", "screenName", target, "err", err.Error())
  159. continue
  160. }
  161. body, ok := reply.Body.(wire.SNAC_0x02_0x0C_LocateGetDirReply)
  162. if !ok {
  163. continue
  164. }
  165. profile := MemberDirProfile{}
  166. profile.FirstName, _ = body.String(wire.ODirTLVFirstName)
  167. profile.LastName, _ = body.String(wire.ODirTLVLastName)
  168. profile.State, _ = body.String(wire.ODirTLVState)
  169. profile.City, _ = body.String(wire.ODirTLVCity)
  170. profile.Country, _ = body.String(wire.ODirTLVCountry)
  171. profile.AimID = state.NewIdentScreenName(target).String()
  172. profile.DisplayID = target
  173. infoArray = append(infoArray, MemberDirInfo{Profile: profile})
  174. }
  175. h.Logger.DebugContext(ctx, "memberDir get",
  176. "aimsid", session.AimSID,
  177. "targets", len(targets),
  178. )
  179. h.sendData(w, r, &MemberDirInfoArray{InfoArray: infoArray})
  180. }
  181. // Update handles GET /memberDir/update. The "Edit Your Name" form sends repeated
  182. // "set=key=value" params — always firstName and lastName, plus a hideLevel
  183. // web-search visibility flag. We persist first/last name into the user's OSCAR
  184. // directory info; hideLevel has no directory storage, so it is ignored.
  185. //
  186. // SetDirectoryInfo replaces the whole directory record, so we read the current
  187. // info first and re-send every field, overlaying only what the form changed.
  188. func (h *MemberDirHandler) Update(w http.ResponseWriter, r *http.Request, session *state.WebAPISession) {
  189. ctx := r.Context()
  190. sets := parseSet(r.URL.Query()["set"])
  191. // Seed from the current record so untouched fields survive the replace. A
  192. // failed read must abort: writing a record we couldn't seed would blank
  193. // every field the form doesn't edit.
  194. reply, err := h.LocateService.DirInfo(ctx, wire.SNACFrame{}, wire.SNAC_0x02_0x0B_LocateGetDirInfo{ScreenName: session.ScreenName.String()})
  195. if err != nil {
  196. h.Logger.ErrorContext(ctx, "memberDir update: failed to read current dir info", "err", err.Error())
  197. h.sendError(w, r, http.StatusInternalServerError, "failed to update directory info")
  198. return
  199. }
  200. body, ok := reply.Body.(wire.SNAC_0x02_0x0C_LocateGetDirReply)
  201. if !ok {
  202. h.Logger.ErrorContext(ctx, "memberDir update: unexpected dir info reply", "body", fmt.Sprintf("%T", reply.Body))
  203. h.sendError(w, r, http.StatusInternalServerError, "failed to update directory info")
  204. return
  205. }
  206. values := make(map[uint16]string, len(dirInfoTags))
  207. for _, tag := range dirInfoTags {
  208. if v, ok := body.String(tag); ok {
  209. values[tag] = v
  210. }
  211. }
  212. // Overlay the form's edits. Assign unconditionally so clearing a name field
  213. // (the client sends "firstName=" with an empty value) is honored.
  214. if v, ok := sets["firstName"]; ok {
  215. values[wire.ODirTLVFirstName] = v
  216. }
  217. if v, ok := sets["lastName"]; ok {
  218. values[wire.ODirTLVLastName] = v
  219. }
  220. inBody := wire.SNAC_0x02_0x09_LocateSetDirInfo{}
  221. for _, tag := range dirInfoTags {
  222. inBody.Append(wire.NewTLVBE(tag, values[tag]))
  223. }
  224. if _, err := h.LocateService.SetDirInfo(ctx, session.OSCARSession, wire.SNACFrame{}, inBody); err != nil {
  225. h.Logger.ErrorContext(ctx, "memberDir update failed", "err", err.Error())
  226. h.sendError(w, r, http.StatusInternalServerError, "failed to update directory info")
  227. return
  228. }
  229. h.Logger.InfoContext(ctx, "memberDir update",
  230. "aimsid", session.AimSID,
  231. "firstName", values[wire.ODirTLVFirstName],
  232. "lastName", values[wire.ODirTLVLastName],
  233. )
  234. h.sendData(w, r, struct{}{})
  235. }
  236. // sendData wraps data in the standard response envelope and sends it via
  237. // SendResponse, which honors the JSONP callback the web client uses.
  238. func (h *MemberDirHandler) sendData(w http.ResponseWriter, r *http.Request, data any) {
  239. resp := BaseResponse{}
  240. resp.Response.StatusCode = 200
  241. resp.Response.StatusText = "OK"
  242. resp.Response.Data = data
  243. SendResponse(w, r, resp, h.Logger)
  244. }
  245. // sendError returns an error status in the response envelope, routed through
  246. // SendResponse so the JSONP callback is still honored (a raw JSON error would be
  247. // CORB-blocked by the client's <script> transport).
  248. func (h *MemberDirHandler) sendError(w http.ResponseWriter, r *http.Request, code int, msg string) {
  249. resp := BaseResponse{}
  250. resp.Response.StatusCode = code
  251. resp.Response.StatusText = msg
  252. SendResponse(w, r, resp, h.Logger)
  253. }
  254. // buildDirInfoQuery maps the web client's parsed "match" fields onto ODir search
  255. // TLVs. The client only ever sends two shapes: "firstName=<x>,lastName=<y>"
  256. // (input split on the last space) or "keyword=<x>" (everything else). Name
  257. // search takes precedence over interest-keyword search.
  258. func buildDirInfoQuery(fields map[string]string) wire.SNAC_0x0F_0x02_InfoQuery {
  259. inBody := wire.SNAC_0x0F_0x02_InfoQuery{}
  260. switch {
  261. case fields["firstName"] != "" || fields["lastName"] != "":
  262. if v := fields["firstName"]; v != "" {
  263. inBody.Append(wire.NewTLVBE(wire.ODirTLVFirstName, v))
  264. }
  265. if v := fields["lastName"]; v != "" {
  266. inBody.Append(wire.NewTLVBE(wire.ODirTLVLastName, v))
  267. }
  268. case fields["keyword"] != "":
  269. inBody.Append(wire.NewTLVBE(wire.ODirTLVInterest, fields["keyword"]))
  270. }
  271. return inBody
  272. }
  273. // parseMatch splits the web client's "match" value ("key=value,key=value")
  274. // into a field map.
  275. func parseMatch(match string) map[string]string {
  276. fields := make(map[string]string)
  277. for pair := range strings.SplitSeq(match, ",") {
  278. key, val, ok := strings.Cut(pair, "=")
  279. if !ok {
  280. continue
  281. }
  282. if key = strings.TrimSpace(key); key != "" {
  283. fields[key] = strings.TrimSpace(val)
  284. }
  285. }
  286. return fields
  287. }
  288. // parseSet parses the repeated "set=key=value" params the update form sends
  289. // into a field map.
  290. func parseSet(sets []string) map[string]string {
  291. fields := make(map[string]string)
  292. for _, s := range sets {
  293. key, val, ok := strings.Cut(s, "=")
  294. if !ok {
  295. continue
  296. }
  297. if key = strings.TrimSpace(key); key != "" {
  298. fields[key] = strings.TrimSpace(val)
  299. }
  300. }
  301. return fields
  302. }
  303. // parseTargets splits a comma-separated "t" screen-name list, trimming blanks.
  304. func parseTargets(t string) []string {
  305. var targets []string
  306. for name := range strings.SplitSeq(t, ",") {
  307. if name = strings.TrimSpace(name); name != "" {
  308. targets = append(targets, name)
  309. }
  310. }
  311. return targets
  312. }