example_timeline/
main.rs

1use anyhow::Result;
2use clap::Parser;
3use futures_util::StreamExt;
4use matrix_sdk::{config::SyncSettings, ruma::OwnedRoomId, Client};
5use matrix_sdk_ui::timeline::RoomExt;
6use url::Url;
7
8#[derive(Parser, Debug)]
9struct Cli {
10    /// The homeserver to connect to.
11    #[clap(value_parser)]
12    homeserver: Url,
13
14    /// The user name that should be used for the login.
15    #[clap(value_parser)]
16    user_name: String,
17
18    /// The password that should be used for the login.
19    #[clap(value_parser)]
20    password: String,
21
22    /// Set the proxy that should be used for the connection.
23    #[clap(short, long)]
24    proxy: Option<Url>,
25
26    /// Enable verbose logging output.
27    #[clap(short, long, action)]
28    verbose: bool,
29
30    /// The room id that we should listen for the,
31    #[clap(value_parser)]
32    room_id: OwnedRoomId,
33}
34
35async fn login(cli: Cli) -> Result<Client> {
36    // Note that when encryption is enabled, you should use a persistent store to be
37    // able to restore the session with a working encryption setup.
38    // See the `persist_session` example.
39    let mut builder = Client::builder().homeserver_url(cli.homeserver);
40
41    if let Some(proxy) = cli.proxy {
42        builder = builder.proxy(proxy);
43    }
44
45    let client = builder.build().await?;
46
47    client
48        .matrix_auth()
49        .login_username(&cli.user_name, &cli.password)
50        .initial_device_display_name("rust-sdk")
51        .await?;
52
53    Ok(client)
54}
55
56#[tokio::main]
57async fn main() -> Result<()> {
58    tracing_subscriber::fmt::init();
59
60    let cli = Cli::parse();
61    let room_id = cli.room_id.clone();
62    let client = login(cli).await?;
63
64    let sync_settings = SyncSettings::default();
65
66    // Wait for the first sync response
67    println!("Wait for the first sync");
68
69    client.sync_once(sync_settings.clone()).await?;
70
71    // Get the timeline stream and listen to it.
72    let room = client.get_room(&room_id).unwrap();
73    let timeline = room.timeline().await.unwrap();
74    let (timeline_items, mut timeline_stream) = timeline.subscribe().await;
75
76    println!("Initial timeline items: {timeline_items:#?}");
77    tokio::spawn(async move {
78        while let Some(diffs) = timeline_stream.next().await {
79            println!("Received timeline diffs: {diffs:#?}");
80        }
81    });
82
83    // Sync forever
84    client.sync(sync_settings).await?;
85
86    Ok(())
87}