urbit_http_api/apps/dm.rs
1use crate::error::Result;
2use crate::traits::messaging::{AuthoredMessage, Message, Messaging};
3use crate::Channel;
4use crossbeam::channel::Receiver;
5
6/// A struct that provides an interface for interacting with Urbit DMs
7pub struct DM<'a> {
8 pub channel: &'a mut Channel,
9}
10
11impl<'a> Messaging for DM<'a> {
12 fn channel(&mut self) -> &mut Channel {
13 self.channel
14 }
15}
16
17impl<'a> DM<'a> {
18 /// Converts a ship @p to the `dm_name` string format used for DM channels
19 pub fn ship_to_dm_name(&self, ship: &str) -> String {
20 format!("dm--{}", ship)
21 }
22
23 /// Send a message to an Urbit DM chat.
24 /// Returns the index of the node that was added to Graph Store.
25 pub fn send_dm_message(
26 &mut self,
27 dm_ship: &str,
28 dm_name: &str,
29 message: &Message,
30 ) -> Result<String> {
31 self.send_message(dm_ship, dm_name, message)
32 }
33
34 /// Extracts DM chat log automatically into a list of formatted `String`s
35 pub fn export_dm_log(&mut self, dm_ship: &str, dm_name: &str) -> Result<Vec<String>> {
36 self.export_message_log(dm_ship, dm_name)
37 }
38
39 /// Extracts a DM chat's messages as `AuthoredMessage`s
40 pub fn export_dm_authored_messages(
41 &mut self,
42 dm_ship: &str,
43 dm_name: &str,
44 ) -> Result<Vec<AuthoredMessage>> {
45 self.export_authored_messages(dm_ship, dm_name)
46 }
47
48 /// Subscribe to and watch for messages. This method returns a `Receiver` with the
49 /// `AuthoredMessage`s that are posted after subscribing. Simply call `receiver.try_recv()`
50 /// to read the next `AuthoredMessage` if one has been posted.
51 ///
52 /// Technical Note: This method actually creates a new `Channel` with your Urbit Ship, and spawns a new unix thread
53 /// locally that processes all messages on said channel. This is required due to borrowing mechanisms in Rust, however
54 /// on the plus side this makes it potentially more performant by each subscription having it's own unix thread.
55 pub fn subscribe_to_dm(
56 &mut self,
57 dm_ship: &str,
58 dm_name: &str,
59 ) -> Result<Receiver<AuthoredMessage>> {
60 self.subscribe_to_messages(dm_ship, dm_name)
61 }
62}