internal/httpd/searchweb.go
200 lines · 5948 bytes
1package httpd
2
3import (
4 "encoding/json"
5 "net/http"
6 "strconv"
7 "strings"
8
9 "gitbay.org/gitbay/internal/control"
10 "gitbay.org/gitbay/internal/gitutil"
11 "gitbay.org/gitbay/internal/policy"
12 "gitbay.org/gitbay/internal/store"
13)
14
15// searchResult is one hit as the template renders it: the link is built
16// here so the template does not have to know each kind's URL shape.
17type searchResult struct {
18 control.SearchResult
19 Marker string
20 Href string
21}
22
23type paletteEntry struct {
24 Group string `json:"group"`
25 Label string `json:"label"`
26 Href string `json:"href"`
27}
28
29// globalSearch is /search: repositories, issues and merge requests across
30// the instance. It is readable without a session — a visitor sees exactly
31// the public rows — so it runs control.Search directly rather than
32// dispatching a command as a user who may not exist.
33func (s *Server) globalSearch(w http.ResponseWriter, r *http.Request) {
34 var viewer store.User
35 if s.cfg.Web.Mode == "accounts" {
36 viewer = s.viewer(r)
37 }
38 if r.URL.Query().Get("format") == "palette" {
39 s.servePalette(w, r, viewer)
40 return
41 }
42 q := strings.TrimSpace(r.URL.Query().Get("q"))
43 kind := r.URL.Query().Get("kind")
44 if kind != "repo" && kind != "issue" && kind != "mr" {
45 kind = ""
46 }
47 var kinds []string
48 if kind != "" {
49 kinds = []string{kind}
50 }
51 var results []searchResult
52 var queryErr string
53 if q != "" {
54 if len(q) < 2 || len(q) > 200 {
55 queryErr = "query must be 2 to 200 characters"
56 } else {
57 hits, err := control.Search(s.st, s.cfg.Server.Root, viewer.ID, q, kinds)
58 if err != nil {
59 http.Error(w, "internal error", http.StatusInternalServerError)
60 return
61 }
62 for _, h := range hits {
63 results = append(results, searchResult{h, control.SearchMarker(h.Kind), searchHref(h)})
64 }
65 }
66 }
67 s.render(w, "globalsearch.html", struct {
68 basePage
69 Tab string
70 Query string
71 Kind string
72 QueryErr string
73 Results []searchResult
74 }{s.baseFor(viewer), "sitesearch", q, kind, queryErr, results})
75}
76
77func searchHref(h control.SearchResult) string {
78 switch h.Kind {
79 case "issue":
80 return "/" + h.Repo + "/issues/" + strconv.FormatInt(h.Number, 10)
81 case "mr":
82 return "/" + h.Repo + "/mrs/" + strconv.FormatInt(h.Number, 10)
83 default:
84 return "/" + h.Repo
85 }
86}
87
88// servePalette answers Cmd+K / 't' jump queries with files, symbols, issues,
89// merge requests, and repositories the viewer can read.
90func (s *Server) servePalette(w http.ResponseWriter, r *http.Request, viewer store.User) {
91 // Each call can walk a whole tree, and anonymous callers reach it, so
92 // it draws on the API's per-caller read budget.
93 key := "palette:" + s.clientIP(r)
94 if viewer.ID != 0 {
95 key = "palette:" + strconv.FormatInt(viewer.ID, 10)
96 }
97 if allowed, wait := s.apiLimit.allow(key, false); !allowed {
98 w.Header().Set("Retry-After", strconv.Itoa(int(wait.Seconds())+1))
99 http.Error(w, "too many requests", http.StatusTooManyRequests)
100 return
101 }
102 q := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("q")))
103 repoPath := strings.TrimSpace(r.URL.Query().Get("repo"))
104 var items []paletteEntry
105
106 if repoPath != "" {
107 if repo, err := s.st.RepoByPath(repoPath); err == nil {
108 grant := ""
109 if viewer.ID != 0 {
110 grant, _ = s.st.AccessRole(repo.ID, viewer.ID)
111 }
112 if policy.CanRead(viewer, repo, grant) {
113 dir := control.RepoDir(s.cfg.Server.Root, repo.OwnerName, repo.Name)
114 ref := strings.TrimSpace(r.URL.Query().Get("ref"))
115 if ref == "" {
116 ref = repo.DefaultBranch
117 }
118 if entries, err := gitutil.ListTreeRecursive(dir, ref, ""); err == nil {
119 count := 0
120 for _, e := range entries {
121 if e.Type != "blob" {
122 continue
123 }
124 if q != "" && !strings.Contains(strings.ToLower(e.Name), q) {
125 continue
126 }
127 items = append(items, paletteEntry{
128 Group: "File",
129 Label: e.Name,
130 Href: "/" + repo.Path() + "/blob/" + escapePath(ref) + "/" + escapePath(e.Name),
131 })
132 count++
133 if count >= 40 {
134 break
135 }
136 }
137 }
138 if mrs, err := s.st.QueryMRs(repo.ID, store.MRFilter{State: "open", Limit: 15}); err == nil {
139 for _, m := range mrs {
140 lbl := "!" + strconv.FormatInt(m.Number, 10) + " " + m.Title
141 if q == "" || strings.Contains(strings.ToLower(lbl), q) {
142 items = append(items, paletteEntry{
143 Group: "MR",
144 Label: lbl,
145 Href: "/" + repo.Path() + "/mrs/" + strconv.FormatInt(m.Number, 10),
146 })
147 }
148 }
149 }
150 if issues, err := s.st.QueryIssues(repo.ID, store.IssueFilter{State: "open", Limit: 15}); err == nil {
151 for _, iss := range issues {
152 lbl := "#" + strconv.FormatInt(iss.Number, 10) + " " + iss.Title
153 if q == "" || strings.Contains(strings.ToLower(lbl), q) {
154 items = append(items, paletteEntry{
155 Group: "Issue",
156 Label: lbl,
157 Href: "/" + repo.Path() + "/issues/" + strconv.FormatInt(iss.Number, 10),
158 })
159 }
160 }
161 }
162 }
163 }
164 }
165
166 if len(q) >= 2 && len(q) <= 100 {
167 if hits, err := control.Search(s.st, s.cfg.Server.Root, viewer.ID, q, nil); err == nil {
168 for i, h := range hits {
169 if i >= 20 {
170 break
171 }
172 lbl := h.Repo
173 grp := "Repo"
174 if h.Number > 0 {
175 lbl = h.Repo + control.SearchMarker(h.Kind) + strconv.FormatInt(h.Number, 10) + " " + h.Title
176 if h.Kind == "mr" {
177 grp = "MR"
178 } else {
179 grp = "Issue"
180 }
181 }
182 items = append(items, paletteEntry{Group: grp, Label: lbl, Href: searchHref(h)})
183 }
184 }
185 } else if repoPath == "" {
186 if repos, err := s.st.ListPublicReposByActivity(); err == nil {
187 for i, rp := range repos {
188 if i >= 15 {
189 break
190 }
191 if q == "" || strings.Contains(strings.ToLower(rp.Path()), q) {
192 items = append(items, paletteEntry{Group: "Repo", Label: rp.Path(), Href: "/" + rp.Path()})
193 }
194 }
195 }
196 }
197
198 w.Header().Set("Content-Type", "application/json; charset=utf-8")
199 json.NewEncoder(w).Encode(map[string]any{"items": items})
200}