aboutsummaryrefslogtreecommitdiffstats
path: root/examples
diff options
context:
space:
mode:
Diffstat (limited to 'examples')
-rw-r--r--examples/channel_stream.rs55
1 files changed, 52 insertions, 3 deletions
diff --git a/examples/channel_stream.rs b/examples/channel_stream.rs
index 4e77d1c..38b0ee4 100644
--- a/examples/channel_stream.rs
+++ b/examples/channel_stream.rs
@@ -18,6 +18,7 @@
use zotapi;
use serde_json;
+use std::iter::Iterator;
pub fn fetch(client: &zotapi::Client, raw: bool) {
match client.channel_stream() {
@@ -26,7 +27,7 @@ pub fn fetch(client: &zotapi::Client, raw: bool) {
println!("{}", payload);
}
else {
- print(&payload);
+ list(&payload);
}
},
Err(e) => {
@@ -35,11 +36,12 @@ pub fn fetch(client: &zotapi::Client, raw: bool) {
}
}
-fn print(payload: &str) {
+fn list(payload: &str) {
match serde_json::from_str(&payload) {
Ok(serde_json::Value::Array(v)) => {
for item in v.into_iter() {
- println!("{} {} {}", item["title"], item["type"], item["author"]["name"]);
+ print_item(&item);
+ println!("-----");
}
},
Ok(_) => {
@@ -50,3 +52,50 @@ fn print(payload: &str) {
}
}
}
+
+fn get_str(v: &serde_json::Value) -> &str {
+ v.as_str().unwrap_or("")
+}
+
+fn get_verb(item: &serde_json::Value) -> &str {
+ match get_str(&item["verb"]).split("/").last() {
+ Some("post") => "posted",
+ Some("like") => "liked",
+ Some("share") => "shared",
+ Some("dislike") => "disliked",
+ _ => "unknown verb",
+ }
+}
+
+fn get_object_type(item: &serde_json::Value) -> &str {
+ get_str(&item["object_type"])
+ .split("/")
+ .last()
+ .unwrap_or("unknown object")
+}
+
+fn get_hashtags(item: &serde_json::Value) -> String {
+ match item["tags"] {
+ serde_json::Value::Array(ref v) => {
+ v.iter().map(|t| get_str(&t["tag"])).collect::<Vec<_>>().join(", ")
+ },
+ serde_json::Value::Null => {
+ String::new()
+ },
+ _ => {
+ String::from("invalid tags, expected array...")
+ }
+ }
+}
+
+fn print_item(item: &serde_json::Value) {
+ let author = &item["author"];
+ print!("{} ", get_str(&item["created"]));
+ print!("{} ", get_str(&author["name"]));
+ println!("{} a {}", get_verb(&item), get_object_type(&item));
+ println!("URL: {}", get_str(&author["url"]));
+ println!("Proto: {}", get_str(&author["network"]));
+ println!("Title: {}", get_str(&item["title"]));
+ println!("Tags : {}", get_hashtags(&item));
+ println!("Message:\n{}", get_str(&item["body"]));
+}