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
use crate::client::TrendsClient;
use crate::models::{RealtimeTrend, TrendArticle, TrendImage};
use crate::Result;
impl TrendsClient {
pub async fn realtime_trends(&self, geo: &str, category: &str) -> Result<Vec<RealtimeTrend>> {
let url = "https://trends.google.com/trends/api/realtimetrends";
let tz_str = self.tz.to_string();
let params = vec![
("hl", self.hl.as_str()),
("tz", tz_str.as_str()),
("geo", geo),
("cat", category),
("fi", "0"),
("fs", "0"),
("ri", "300"),
("rs", "20"),
("sort", "0"),
];
let result = self.get_json_with_params(url, ¶ms).await?;
let mut trends = Vec::new();
if let Some(stories_arr) = result
.pointer("/storySummaries/trendingStories")
.and_then(|s| s.as_array())
{
for story in stories_arr {
let mut title = Vec::new();
if let Some(title_arr) = story.get("title").and_then(|t| t.as_array()) {
for t in title_arr {
if let Some(s) = t.as_str() {
title.push(s.to_string());
}
}
} else if let Some(title_str) = story.get("title").and_then(|t| t.as_str()) {
title.push(title_str.to_string());
}
let mut entity_names = Vec::new();
if let Some(entity_arr) = story.get("entityNames").and_then(|e| e.as_array()) {
for e in entity_arr {
if let Some(s) = e.as_str() {
entity_names.push(s.to_string());
}
}
}
let mut articles = Vec::new();
if let Some(articles_arr) = story.get("articles").and_then(|a| a.as_array()) {
for article in articles_arr {
articles.push(TrendArticle {
article_title: article
.get("articleTitle")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string(),
url: article
.get("url")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string(),
source: article
.get("source")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string(),
time_ago: article
.get("timeAgo")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string(),
});
}
}
let image = story.get("image").map(|img_obj| TrendImage {
news_url: img_obj
.get("newsUrl")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string(),
source: img_obj
.get("source")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string(),
img_url: img_obj
.get("imgUrl")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string(),
});
let share_url = story
.get("shareUrl")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
trends.push(RealtimeTrend {
title,
entity_names,
articles,
image,
share_url,
});
}
}
Ok(trends)
}
}