search.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package api
  2. import (
  3. "regexp"
  4. "strings"
  5. "github.com/torkelo/grafana-pro/pkg/bus"
  6. "github.com/torkelo/grafana-pro/pkg/middleware"
  7. m "github.com/torkelo/grafana-pro/pkg/models"
  8. "github.com/torkelo/grafana-pro/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. result := m.SearchResult{
  30. Dashboards: []*m.DashboardSearchHit{},
  31. Tags: []*m.DashboardTagCloudItem{},
  32. }
  33. if strings.HasPrefix(queryText, "tags!:") {
  34. query := m.GetDashboardTagsQuery{AccountId: c.AccountId}
  35. err := bus.Dispatch(&query)
  36. if err != nil {
  37. c.JsonApiErr(500, "Failed to get tags from database", err)
  38. return
  39. }
  40. result.Tags = query.Result
  41. result.TagsOnly = true
  42. } else {
  43. searchQueryRegEx, _ := regexp.Compile(`(tags:(\w*)\sAND\s)?(?:title:)?(.*)?`)
  44. matches := searchQueryRegEx.FindStringSubmatch(queryText)
  45. query := m.SearchDashboardsQuery{
  46. Title: matches[3],
  47. Tag: matches[2],
  48. UserId: c.UserId,
  49. IsStarred: starred == "1",
  50. AccountId: c.AccountId,
  51. }
  52. err := bus.Dispatch(&query)
  53. if err != nil {
  54. c.JsonApiErr(500, "Search failed", err)
  55. return
  56. }
  57. if err := setIsStarredFlagOnSearchResults(c, query.Result); err != nil {
  58. c.JsonApiErr(500, "Failed to get user stars", err)
  59. return
  60. }
  61. result.Dashboards = query.Result
  62. for _, dash := range result.Dashboards {
  63. dash.Url = setting.AbsUrlTo("dashboard/db/" + dash.Slug)
  64. }
  65. }
  66. c.JSON(200, result)
  67. }