-
Notifications
You must be signed in to change notification settings - Fork 34
/
gogtrends.go
328 lines (251 loc) · 7.7 KB
/
gogtrends.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
package gogtrends
import (
"context"
"fmt"
"net/url"
"strings"
jsoniter "github.com/json-iterator/go"
"github.com/pkg/errors"
)
var client = newGClient()
// Debug allows to see request-response details.
func Debug(debug bool) {
client.debug = debug
}
// TrendsCategories return list of available categories for Realtime method as [param]description map.
func TrendsCategories() map[string]string {
return client.trendsCats
}
// Daily gets daily trends descending ordered by days and articles corresponding to it.
func Daily(ctx context.Context, hl, loc string) ([]*TrendingSearch, error) {
data, err := client.trends(ctx, gAPI+gDaily, hl, loc)
if err != nil {
return nil, err
}
// google api returns not valid json :(
str := strings.Replace(data, ")]}',", "", 1)
out := new(dailyOut)
if err := client.unmarshal(str, out); err != nil {
return nil, err
}
// split searches by days together
searches := make([]*TrendingSearch, 0)
for _, v := range out.Default.Searches {
searches = append(searches, v.Searches...)
}
return searches, nil
}
// Realtime represents realtime trends with included articles and sources.
func Realtime(ctx context.Context, hl, loc, cat string) ([]*TrendingStory, error) {
if !client.validateCategory(cat) {
return nil, ErrInvalidCategory
}
data, err := client.trends(ctx, gAPI+gRealtime, hl, loc, map[string]string{paramCat: cat})
if err != nil {
return nil, err
}
// google api returns not valid json :(
str := strings.Replace(data, ")]}'", "", 1)
out := new(realtimeOut)
if err := client.unmarshal(str, out); err != nil {
return nil, err
}
return out.StorySummaries.TrendingStories, nil
}
// ExploreCategories gets available categories for explore and comparison and caches it in client.
func ExploreCategories(ctx context.Context) (*ExploreCatTree, error) {
if cats := client.getCategories(); cats != nil {
return cats, nil
}
u, _ := url.Parse(gAPI + gSCategories)
b, err := client.do(ctx, u)
if err != nil {
return nil, err
}
// google api returns not valid json :(
str := strings.Replace(string(b), ")]}'", "", 1)
out := new(ExploreCatTree)
if err := client.unmarshal(str, out); err != nil {
return nil, err
}
// cache in client
client.setCategories(out)
return out, nil
}
// ExploreLocations gets available locations for explore and comparison and caches it in client.
func ExploreLocations(ctx context.Context) (*ExploreLocTree, error) {
if locs := client.getLocations(); locs != nil {
return locs, nil
}
u, _ := url.Parse(gAPI + gSGeo)
b, err := client.do(ctx, u)
if err != nil {
return nil, err
}
// google api returns not valid json :(
str := strings.Replace(string(b), ")]}'", "", 1)
out := new(ExploreLocTree)
if err := client.unmarshal(str, out); err != nil {
return nil, err
}
// cache in client
client.setLocations(out)
return out, nil
}
// Explore list of widgets with tokens. Every widget
// is related to specific method (`InterestOverTime`, `InterestOverLoc`, `RelatedSearches`, `Suggestions`)
// and contains required token and request information.
func Explore(ctx context.Context, r *ExploreRequest, hl string) (ExploreResponse, error) {
// hook for using incorrect `time` request (backward compatibility)
for _, r := range r.ComparisonItems {
r.Time = strings.ReplaceAll(r.Time, "+", " ")
}
u, _ := url.Parse(gAPI + gSExplore)
p := make(url.Values)
p.Set(paramTZ, "0")
p.Set(paramHl, hl)
// marshal request for query param
mReq, err := jsoniter.MarshalToString(r)
if err != nil {
return nil, errors.Wrapf(err, errInvalidRequest)
}
p.Set(paramReq, mReq)
u.RawQuery = p.Encode()
b, err := client.do(ctx, u)
if err != nil {
return nil, err
}
// google api returns not valid json :(
str := strings.Replace(string(b), ")]}'", "", 1)
out := new(exploreOut)
if err := client.unmarshal(str, out); err != nil {
return nil, err
}
return out.Widgets, nil
}
// InterestOverTime as list of `Timeline` dots for chart.
func InterestOverTime(ctx context.Context, w *ExploreWidget, hl string) ([]*Timeline, error) {
if !strings.HasPrefix(w.ID, string(IntOverTimeWidgetID)) {
return nil, ErrInvalidWidgetType
}
u, _ := url.Parse(gAPI + gSIntOverTime)
p := make(url.Values)
p.Set(paramTZ, "0")
p.Set(paramHl, hl)
p.Set(paramToken, w.Token)
for i, v := range w.Request.CompItem {
if len(v.Geo) == 0 {
w.Request.CompItem[i].Geo[""] = ""
}
}
// marshal request for query param
mReq, err := jsoniter.MarshalToString(w.Request)
if err != nil {
return nil, errors.Wrapf(err, errInvalidRequest)
}
p.Set(paramReq, mReq)
u.RawQuery = p.Encode()
b, err := client.do(ctx, u)
if err != nil {
return nil, err
}
// google api returns not valid json :(
str := strings.Replace(string(b), ")]}',", "", 1)
out := new(multilineOut)
if err := client.unmarshal(str, out); err != nil {
return nil, err
}
return out.Default.TimelineData, nil
}
// InterestByLocation as list of `GeoMap`, with geo codes and interest values.
func InterestByLocation(ctx context.Context, w *ExploreWidget, hl string) ([]*GeoMap, error) {
if !strings.HasPrefix(w.ID, string(IntOverRegionID)) {
return nil, ErrInvalidWidgetType
}
u, _ := url.Parse(gAPI + gSIntOverReg)
p := make(url.Values)
p.Set(paramTZ, "0")
p.Set(paramHl, hl)
p.Set(paramToken, w.Token)
if len(w.Request.CompItem) > 1 {
w.Request.DataMode = compareDataMode
}
// marshal request for query param
mReq, err := jsoniter.MarshalToString(w.Request)
if err != nil {
return nil, errors.Wrapf(err, errInvalidRequest)
}
p.Set(paramReq, mReq)
u.RawQuery = p.Encode()
b, err := client.do(ctx, u)
if err != nil {
return nil, err
}
// google api returns not valid json :(
str := strings.Replace(string(b), ")]}',", "", 1)
out := new(geoOut)
if err := client.unmarshal(str, out); err != nil {
return nil, err
}
return out.Default.GeoMapData, nil
}
// Related topics or queries, list of `RankedKeyword`, supports two types of widgets.
func Related(ctx context.Context, w *ExploreWidget, hl string) ([]*RankedKeyword, error) {
if !strings.HasPrefix(w.ID, string(RelatedQueriesID)) && !strings.HasPrefix(w.ID, string(RelatedTopicsID)) {
return nil, ErrInvalidWidgetType
}
u, _ := url.Parse(gAPI + gSRelated)
p := make(url.Values)
p.Set(paramTZ, "0")
p.Set(paramHl, hl)
p.Set(paramToken, w.Token)
if len(w.Request.Restriction.Geo) == 0 {
w.Request.Restriction.Geo[""] = ""
}
// marshal request for query param
mReq, err := jsoniter.MarshalToString(w.Request)
if err != nil {
return nil, errors.Wrapf(err, errInvalidRequest)
}
p.Set(paramReq, mReq)
u.RawQuery = p.Encode()
b, err := client.do(ctx, u)
if err != nil {
return nil, err
}
// google api returns not valid json :(
str := strings.Replace(string(b), ")]}',", "", 1)
out := new(relatedOut)
if err := client.unmarshal(str, out); err != nil {
return nil, err
}
// split all keywords together
keywords := make([]*RankedKeyword, 0)
for _, v := range out.Default.Ranked {
keywords = append(keywords, v.Keywords...)
}
return keywords, nil
}
// Related topics or queries, list of `RankedKeyword`, supports two types of widgets.
func Search(ctx context.Context, word, hl string) ([]*KeywordTopic, error) {
req := fmt.Sprintf("%s%s/%s", gAPI, gSAutocomplete, url.QueryEscape(word))
u, _ := url.Parse(req)
p := make(url.Values)
p.Set(paramTZ, "0")
p.Set(paramHl, hl)
u.RawQuery = p.Encode()
b, err := client.do(ctx, u)
if err != nil {
return nil, err
}
// google api returns not valid json :(
str := strings.Replace(string(b), ")]}',", "", 1)
out := new(searchOut)
if err := client.unmarshal(str, out); err != nil {
return nil, err
}
// split all keywords together
keywords := make([]*KeywordTopic, 0)
keywords = append(keywords, out.Default.Keywords...)
return keywords, nil
}