|
| 1 | +use std::collections::HashMap; |
| 2 | + |
| 3 | +use futures::StreamExt; |
| 4 | +use serde::Deserialize; |
| 5 | +use std::env; |
| 6 | + |
| 7 | +use pubnub::subscribe::{SubscriptionOptions, SubscriptionParams}; |
| 8 | +use pubnub::{ |
| 9 | + dx::subscribe::Update, |
| 10 | + subscribe::{EventEmitter, EventSubscriber}, |
| 11 | + Keyset, PubNubClientBuilder, |
| 12 | +}; |
| 13 | + |
| 14 | +#[derive(Debug, Deserialize)] |
| 15 | +struct Message { |
| 16 | + // Allowing dead code because we don't use these fields |
| 17 | + // in this example. |
| 18 | + #[allow(dead_code)] |
| 19 | + url: String, |
| 20 | + #[allow(dead_code)] |
| 21 | + description: String, |
| 22 | +} |
| 23 | + |
| 24 | +#[tokio::main] |
| 25 | +async fn main() -> Result<(), Box<dyn snafu::Error>> { |
| 26 | + let publish_key = env::var("SDK_PUB_KEY")?; |
| 27 | + let subscribe_key = env::var("SDK_SUB_KEY")?; |
| 28 | + |
| 29 | + let pubnub = PubNubClientBuilder::with_reqwest_transport() |
| 30 | + .with_keyset(Keyset { |
| 31 | + subscribe_key, |
| 32 | + publish_key: Some(publish_key), |
| 33 | + secret_key: None, |
| 34 | + }) |
| 35 | + .with_user_id("user_id") |
| 36 | + .with_filter_expression("some_filter") |
| 37 | + .with_heartbeat_value(100) |
| 38 | + .with_heartbeat_interval(5) |
| 39 | + .build()?; |
| 40 | + |
| 41 | + println!("running!"); |
| 42 | + |
| 43 | + // Setting up state which will be associated with the user id as long as he is |
| 44 | + // subscribed and not timeout. |
| 45 | + pubnub |
| 46 | + .set_presence_state(HashMap::<String, String>::from([ |
| 47 | + ( |
| 48 | + "is_doing".to_string(), |
| 49 | + "Nothing... Just hanging around...".to_string(), |
| 50 | + ), |
| 51 | + ("flag".to_string(), "false".to_string()), |
| 52 | + ])) |
| 53 | + .channels(["my_channel".into(), "other_channel".into()].to_vec()) |
| 54 | + .user_id("user_id") |
| 55 | + .execute() |
| 56 | + .await?; |
| 57 | + |
| 58 | + tokio::time::sleep(tokio::time::Duration::from_secs(3)).await; |
| 59 | + |
| 60 | + let subscription = pubnub.subscription(SubscriptionParams { |
| 61 | + channels: Some(&["my_channel", "other_channel"]), |
| 62 | + channel_groups: None, |
| 63 | + options: Some(vec![SubscriptionOptions::ReceivePresenceEvents]), |
| 64 | + }); |
| 65 | + subscription.subscribe(None); |
| 66 | + let subscription_clone = subscription.clone_empty(); |
| 67 | + |
| 68 | + // Attach connection status to the PubNub client instance. |
| 69 | + tokio::spawn( |
| 70 | + pubnub |
| 71 | + .status_stream() |
| 72 | + .for_each(|status| async move { println!("\nstatus: {:?}", status) }), |
| 73 | + ); |
| 74 | + |
| 75 | + tokio::spawn(subscription.stream().for_each(|event| async move { |
| 76 | + match event { |
| 77 | + Update::Message(message) | Update::Signal(message) => { |
| 78 | + // Deserialize the message payload as you wish |
| 79 | + match serde_json::from_slice::<Message>(&message.data) { |
| 80 | + Ok(message) => println!("(a) defined message: {:?}", message), |
| 81 | + Err(_) => { |
| 82 | + println!("(a) other message: {:?}", String::from_utf8(message.data)) |
| 83 | + } |
| 84 | + } |
| 85 | + } |
| 86 | + Update::Presence(presence) => { |
| 87 | + println!("(a) presence: {:?}", presence) |
| 88 | + } |
| 89 | + Update::AppContext(object) => { |
| 90 | + println!("(a) object: {:?}", object) |
| 91 | + } |
| 92 | + Update::MessageAction(action) => { |
| 93 | + println!("(a) message action: {:?}", action) |
| 94 | + } |
| 95 | + Update::File(file) => { |
| 96 | + println!("(a) file: {:?}", file) |
| 97 | + } |
| 98 | + } |
| 99 | + })); |
| 100 | + |
| 101 | + // Explicitly listen only for real-time `message` updates. |
| 102 | + tokio::spawn( |
| 103 | + subscription_clone |
| 104 | + .messages_stream() |
| 105 | + .for_each(|message| async move { |
| 106 | + // Deserialize the message payload as you wish |
| 107 | + match serde_json::from_slice::<Message>(&message.data) { |
| 108 | + Ok(message) => println!("(b) defined message: {:?}", message), |
| 109 | + Err(_) => { |
| 110 | + println!("(b) other message: {:?}", String::from_utf8(message.data)) |
| 111 | + } |
| 112 | + } |
| 113 | + }), |
| 114 | + ); |
| 115 | + |
| 116 | + // Explicitly listen only for real-time `file` updates. |
| 117 | + tokio::spawn( |
| 118 | + subscription_clone |
| 119 | + .files_stream() |
| 120 | + .for_each(|file| async move { println!("(b) file: {:?}", file) }), |
| 121 | + ); |
| 122 | + |
| 123 | + // Sleep for a minute. Now you can send messages to the channels |
| 124 | + // "my_channel" and "other_channel" and see them printed in the console. |
| 125 | + // You can use the publishing example or [PubNub console](https://www.pubnub.com/docs/console/) |
| 126 | + // to send messages. |
| 127 | + tokio::time::sleep(tokio::time::Duration::from_secs(15)).await; |
| 128 | + |
| 129 | + // You can also cancel the subscription at any time. |
| 130 | + // subscription.unsubscribe(); |
| 131 | + |
| 132 | + println!("\nDisconnect from the real-time data stream"); |
| 133 | + pubnub.disconnect(); |
| 134 | + |
| 135 | + tokio::time::sleep(tokio::time::Duration::from_secs(3)).await; |
| 136 | + |
| 137 | + println!("\nReconnect to the real-time data stream"); |
| 138 | + pubnub.reconnect(None); |
| 139 | + |
| 140 | + // Let event engine process unsubscribe request |
| 141 | + tokio::time::sleep(tokio::time::Duration::from_secs(3)).await; |
| 142 | + |
| 143 | + // If Subscription or Subscription will go out of scope they will unsubscribe. |
| 144 | + // drop(subscription); |
| 145 | + // drop(subscription_clone); |
| 146 | + |
| 147 | + println!( |
| 148 | + "\nUnsubscribe from all data streams. To restore requires `subscription.subscribe(None)` call." ); |
| 149 | + // Clean up before complete work with PubNub client instance. |
| 150 | + pubnub.unsubscribe_all(); |
| 151 | + tokio::time::sleep(tokio::time::Duration::from_secs(1)).await; |
| 152 | + |
| 153 | + Ok(()) |
| 154 | +} |
0 commit comments