1 /* |
|
2 Copyright 2017-2018 Mikael Berthe |
|
3 |
|
4 Licensed under the MIT license. Please see the LICENSE file is this directory. |
|
5 */ |
|
6 |
|
7 package madon |
|
8 |
|
9 import ( |
|
10 "strings" |
|
11 |
|
12 "github.com/sendgrid/rest" |
|
13 ) |
|
14 |
|
15 // Search search for contents (accounts or statuses) and returns a Results |
|
16 func (mc *Client) searchV1(params apiCallParams) (*Results, error) { |
|
17 // We use a custom structure with shadowed Hashtags field, |
|
18 // since the v1 version only returns strings. |
|
19 var resultsV1 struct { |
|
20 Results |
|
21 Hashtags []string `json:"hashtags"` |
|
22 } |
|
23 if err := mc.apiCall("v1/"+"search", rest.Get, params, nil, nil, &resultsV1); err != nil { |
|
24 return nil, err |
|
25 } |
|
26 |
|
27 var results Results |
|
28 results.Accounts = resultsV1.Accounts |
|
29 results.Statuses = resultsV1.Statuses |
|
30 for _, t := range resultsV1.Hashtags { |
|
31 results.Hashtags = append(results.Hashtags, Tag{Name: t}) |
|
32 } |
|
33 |
|
34 return &results, nil |
|
35 } |
|
36 |
|
37 func (mc *Client) searchV2(params apiCallParams) (*Results, error) { |
|
38 var results Results |
|
39 if err := mc.apiCall("v2/"+"search", rest.Get, params, nil, nil, &results); err != nil { |
|
40 return nil, err |
|
41 } |
|
42 |
|
43 return &results, nil |
|
44 } |
|
45 |
|
46 // Search search for contents (accounts or statuses) and returns a Results |
|
47 func (mc *Client) Search(query string, resolve bool) (*Results, error) { |
|
48 if query == "" { |
|
49 return nil, ErrInvalidParameter |
|
50 } |
|
51 |
|
52 // The parameters are the same in both v1 & v2 API versions |
|
53 params := make(apiCallParams) |
|
54 params["q"] = query |
|
55 if resolve { |
|
56 params["resolve"] = "true" |
|
57 } |
|
58 |
|
59 r, err := mc.searchV2(params) |
|
60 |
|
61 // This is not a very beautiful way to check the error cause, I admit. |
|
62 if err != nil && strings.Contains(err.Error(), "bad server status code (404)") { |
|
63 // Fall back to v1 API endpoint |
|
64 r, err = mc.searchV1(params) |
|
65 } |
|
66 |
|
67 return r, err |
|
68 } |
|