search.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package api
  2. import (
  3. "regexp"
  4. "strings"
  5. "github.com/grafana/grafana/pkg/bus"
  6. "github.com/grafana/grafana/pkg/middleware"
  7. m "github.com/grafana/grafana/pkg/models"
  8. "github.com/grafana/grafana/pkg/setting"
  9. )
  10. // TODO: this needs to be cached or improved somehow
  11. func setIsStarredFlagOnSearchResults(c *middleware.Context, hits []*m.DashboardSearchHit) error {
  12. if !c.IsSignedIn {
  13. return nil
  14. }
  15. query := m.GetUserStarsQuery{UserId: c.UserId}
  16. if err := bus.Dispatch(&query); err != nil {
  17. return err
  18. }
  19. for _, dash := range hits {
  20. if _, exists := query.Result[dash.Id]; exists {
  21. dash.IsStarred = true
  22. }
  23. }
  24. return nil
  25. }
  26. func Search(c *middleware.Context) {
  27. queryText := c.Query("q")
  28. starred := c.Query("starred")
  29. limit := c.QueryInt("limit")
  30. if limit == 0 {
  31. limit = 200
  32. }
  33. result := m.SearchResult{
  34. Dashboards: []*m.DashboardSearchHit{},
  35. Tags: []*m.DashboardTagCloudItem{},
  36. }
  37. if strings.HasPrefix(queryText, "tags!:") {
  38. query := m.GetDashboardTagsQuery{AccountId: c.AccountId}
  39. err := bus.Dispatch(&query)
  40. if err != nil {
  41. c.JsonApiErr(500, "Failed to get tags from database", err)
  42. return
  43. }
  44. result.Tags = query.Result
  45. result.TagsOnly = true
  46. } else {
  47. searchQueryRegEx, _ := regexp.Compile(`(tags:(\w*)\sAND\s)?(?:title:)?(.*)?`)
  48. matches := searchQueryRegEx.FindStringSubmatch(queryText)
  49. query := m.SearchDashboardsQuery{
  50. Title: matches[3],
  51. Tag: matches[2],
  52. UserId: c.UserId,
  53. Limit: limit,
  54. IsStarred: starred == "1",
  55. AccountId: c.AccountId,
  56. }
  57. err := bus.Dispatch(&query)
  58. if err != nil {
  59. c.JsonApiErr(500, "Search failed", err)
  60. return
  61. }
  62. if err := setIsStarredFlagOnSearchResults(c, query.Result); err != nil {
  63. c.JsonApiErr(500, "Failed to get user stars", err)
  64. return
  65. }
  66. result.Dashboards = query.Result
  67. for _, dash := range result.Dashboards {
  68. dash.Url = setting.ToAbsUrl("dashboard/db/" + dash.Slug)
  69. }
  70. }
  71. c.JSON(200, result)
  72. }