golgi/examples/ssb-stream-example.rs

86 lines
2.5 KiB
Rust
Raw Normal View History

2022-01-04 19:09:49 +00:00
use std::process;
2022-01-05 18:58:48 +00:00
use async_std::stream::StreamExt;
2022-01-05 15:58:07 +00:00
use futures::{pin_mut, TryStreamExt};
2022-01-04 19:09:49 +00:00
2022-01-05 18:58:48 +00:00
use golgi::error::GolgiError;
use golgi::messages::{SsbMessageContentType, SsbMessageValue};
use golgi::sbot::Sbot;
2022-01-04 19:09:49 +00:00
async fn run() -> Result<(), GolgiError> {
let mut sbot_client = Sbot::init(None, None).await?;
let id = sbot_client.whoami().await?;
println!("{}", id);
let author = "@L/z54cbc8V1kL1/MiBhpEKuN3QJkSoZYNaukny3ghIs=.ed25519";
2022-01-04 19:58:08 +00:00
// create a history stream
2022-01-05 18:58:48 +00:00
let history_stream = sbot_client
.create_history_stream(author.to_string())
.await?;
2022-01-04 19:09:49 +00:00
2022-01-04 19:58:08 +00:00
// loop through the results until the end of the stream
pin_mut!(history_stream); // needed for iteration
println!("looping through stream");
2022-01-04 19:09:49 +00:00
while let Some(res) = history_stream.next().await {
match res {
Ok(value) => {
println!("value: {:?}", value);
2022-01-05 18:58:48 +00:00
}
2022-01-04 19:09:49 +00:00
Err(err) => {
println!("err: {:?}", err);
}
}
2022-01-04 19:58:08 +00:00
}
println!("reached end of stream");
2022-01-04 19:09:49 +00:00
2022-01-05 15:58:07 +00:00
// create a history stream and convert it into a Vec<SsbMessageValue> using try_collect
// (if there is any error in the results, it will be raised)
2022-01-05 18:58:48 +00:00
let history_stream = sbot_client
.create_history_stream(author.to_string())
.await?;
let results: Vec<SsbMessageValue> = history_stream.try_collect().await?;
2022-01-05 15:58:07 +00:00
for x in results {
println!("x: {:?}", x);
}
// example to create a history stream and use a map to convert stream of SsbMessageValue
2022-01-05 18:58:48 +00:00
// into a stream of tuples of (String, SsbMessageContentType)
let history_stream = sbot_client
.create_history_stream(author.to_string())
.await?;
let type_stream = history_stream.map(|msg| match msg {
Ok(val) => {
let message_type = val.get_message_type()?;
let tuple: (String, SsbMessageContentType) = (val.signature, message_type);
Ok(tuple)
2022-01-05 15:58:07 +00:00
}
2022-01-05 18:58:48 +00:00
Err(err) => Err(err),
2022-01-05 15:58:07 +00:00
});
pin_mut!(type_stream); // needed for iteration
println!("looping through type stream");
while let Some(res) = type_stream.next().await {
match res {
Ok(value) => {
println!("value: {:?}", value);
2022-01-05 18:58:48 +00:00
}
2022-01-05 15:58:07 +00:00
Err(err) => {
println!("err: {:?}", err);
}
}
}
println!("reached end of type stream");
// return Ok
2022-01-04 20:00:25 +00:00
Ok(())
2022-01-04 19:09:49 +00:00
}
#[async_std::main]
async fn main() {
if let Err(e) = run().await {
eprintln!("Application error: {}", e);
process::exit(1);
}
}