urbit_http_api/
subscription.rs

1use eventsource_threaded::event::Event;
2use json;
3
4// ID of the message that created a `Subscription`
5pub type CreationID = u64;
6
7// A subscription on a given Channel
8#[derive(Debug, Clone)]
9pub struct Subscription {
10    /// The uid of the channel this subscription was made in
11    pub channel_uid: String,
12    /// The id of the message that created this subscription
13    pub creation_id: CreationID,
14    /// The app that is being subscribed to
15    pub app: String,
16    /// The path of the app being subscribed to
17    pub path: String,
18    // A list of messages from the given subscription.
19    pub message_list: Vec<String>,
20}
21
22impl Subscription {
23    /// Verifies if the id of the message id in the event matches thea
24    /// `Subscription` `creation_id`.
25    fn event_matches(&self, event: &Event) -> bool {
26        if let Some(json) = &json::parse(&event.data).ok() {
27            return self.creation_id.to_string() == json["id"].dump();
28        }
29        false
30    }
31
32    /// Parses an event and adds it to the message list if it's id
33    /// matches the `Subscription` `creation_id`. On success returns
34    /// the length of the message list.
35    pub fn add_to_message_list(&mut self, event: &Event) -> Option<u64> {
36        if self.event_matches(&event) {
37            let json = &json::parse(&event.data).ok()?["json"];
38            if !json.is_null() {
39                self.message_list.push(json.dump());
40                return Some(self.message_list.len() as u64);
41            }
42        }
43        None
44    }
45
46    /// Pops a message from the front of `Subscription`'s `message_list`.
47    /// If no messages are left, returns `None`.
48    pub fn pop_message(&mut self) -> Option<String> {
49        if self.message_list.len() == 0 {
50            return None;
51        }
52        let messages = self.message_list.clone();
53        let (head, tail) = messages.split_at(1);
54        self.message_list = tail.to_vec();
55        Some(head.to_owned()[0].clone())
56    }
57}