summaryrefslogtreecommitdiffstats
path: root/cli/src/profile.rs
blob: d751116929e6eab0b162a16e593f1bc747ca1e25 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::sync::Arc;

use anyhow::Context;
use anyhow::Result;
use clap::ArgMatches;

use distrox_lib::profile::Profile;
use distrox_lib::types::Payload;

pub async fn profile(matches: &ArgMatches) -> Result<()> {
    match matches.subcommand() {
        Some(("create", m)) => profile_create(m).await,
        Some(("serve", m)) => profile_serve(m).await,
        Some(("post", m)) => profile_post(m).await,
        Some(("cat", m)) => profile_cat(m).await,
        _ => unimplemented!(),
    }
}

async fn profile_create(matches: &ArgMatches) -> Result<()> {
    let name = matches.value_of("name").map(String::from).unwrap(); // required
    let state_dir = Profile::state_dir_path(&name)?;
    log::info!("Creating '{}' in {}", name, state_dir.display());

    let profile = Profile::create(&state_dir, &name).await?;
    log::info!("Saving...");
    profile.save().await?;

    log::info!("Shutting down...");
    profile.exit().await
}

async fn profile_serve(matches: &ArgMatches) -> Result<()> {
    use ipfs::MultiaddrWithPeerId;

    let name = matches.value_of("name").map(String::from).unwrap(); // required
    let listen_addrs = matches.values_of("listen")
        .map(|v| {
            v.map(|s| s.parse::<ipfs::Multiaddr>().map_err(anyhow::Error::from))
                .collect::<Result<Vec<_>>>()
        })
        .transpose()?;
    let connect_peer = matches.values_of("connect")
        .map(|v| {
            v.map(|s| {
                s.parse::<MultiaddrWithPeerId>().map_err(anyhow::Error::from)
            })
            .collect::<Result<Vec<_>>>()
        })
        .transpose()?;

    let state_dir = Profile::state_dir_path(&name)?;

    log::info!("Loading '{}' from {}", name, state_dir.display());
    let profile = Profile::load(&name).await?;
    log::info!("Profile loaded");
    if let Some(head) = profile.head().as_ref() {
        log::info!("Profile HEAD = {}", head);
    }

    if let Some(listen) = listen_addrs {
        for l in listen {
            log::debug!("Adding listening address: {}", l);
            profile.listen_on(l).await?;
        }
    }

    {
        let addrs = profile.client().own_addresses().await?;
        if addrs.is_empty() {
            log::error!("No own address");
        } else {
            for addr in addrs {
                log::info!("Own addr: {}", addr);
            }
        }
    }

    if let Some(connect_to) = connect_peer {
        for c in connect_to {
            log::info!("Connecting to {:?}", c);
            profile.connect(c).await?;
        }
    }

    let mut gossip_channel = Box::pin({
        profile.client()
            .pubsub_subscribe("distrox".to_string())
            .await
            .map(|stream| {
                use distrox_lib::gossip::GossipDeserializer;
                use distrox_lib::gossip::LogStrategy;

                GossipDeserializer::<LogStrategy>::new().run(stream)
            })?
    });

    let running = Arc::new(AtomicBool::new(true));
    let r = running.clone();

    let own_peer_id = profile.client().own_id().await?;

    ctrlc::set_handler(move || {
        r.store(false, Ordering::SeqCst);
    }).context("Error setting Ctrl-C handler")?;

    log::info!("Serving...");
    while running.load(Ordering::SeqCst) {
        use futures::stream::StreamExt;
        use distrox_lib::gossip::GossipMessage;

        tokio::time::sleep(std::time::Duration::from_millis(500)).await; // sleep not so busy

        tokio::select! {
            own = profile.gossip_own_state("distrox".to_string()) => own?,
            other = gossip_channel.next() => {
                let gossip_myself = other.as_ref().map(|(source, _)| *source == own_peer_id).unwrap_or(false);

                if !gossip_myself {
                    log::trace!("Received gossip: {:?}", other);
                }
            }
        }
    }
    log::info!("Shutting down...");
    profile.exit().await
}

async fn profile_post(matches: &ArgMatches) -> Result<()> {
    let text = match matches.value_of("text") {
        Some(text) => String::from(text),
        None => if matches.is_present("editor") {
            editor_input::input_from_editor("")?
        } else {
            unreachable!()
        }
    };

    let name = matches.value_of("name").map(String::from).unwrap(); // required
    let state_dir = Profile::state_dir_path(&name)?;
    log::info!("Creating '{}' in {}", name, state_dir.display());

    log::info!("Loading '{}' from {}", name, state_dir.display());
    let mut profile = Profile::load(&name).await?;
    log::info!("Profile loaded");
    log::info!("Profile HEAD = {:?}", profile.head());

    log::info!("Posting text...");
    profile.post_text(text).await?;
    log::info!("Posting text finished");
    profile.save().await?;
    log::info!("Saving profile state to disk finished");
    profile.exit().await
}

async fn profile_cat(matches: &ArgMatches) -> Result<()> {
    use distrox_lib::stream::NodeStreamBuilder;
    use futures::stream::StreamExt;

    let name = matches.value_of("name").map(String::from).unwrap(); // required
    let state_dir = Profile::state_dir_path(&name)?;
    log::info!("Creating '{}' in {}", name, state_dir.display());

    log::info!("Loading '{}' from {}", name, state_dir.display());
    let profile = Profile::load(&name).await?;
    log::info!("Profile loaded");
    if let Some(head) = profile.head() {
        log::info!("Profile HEAD = {:?}", head);
        NodeStreamBuilder::starting_from(head.clone())
            .into_stream(profile.client().clone())
            .then(|node| async {
                match node {
                    Err(e) => Err(e),
                    Ok(node) => {
                        profile.client()
                            .get_payload(node.payload())
                            .await
                    }
                }
            })
            .then(|payload| async {
                match payload {
                    Err(e) => Err(e),
                    Ok(payload) => {
                        profile.client()
                            .get_content_text(payload.content())
                            .await
                            .map(|text| (payload, text))
                    }
                }
            })
            .then(|res| async {
                use std::io::Write;
                match res {
                    Err(e) => {
                        let out = std::io::stderr();
                        let mut lock = out.lock();
                        writeln!(lock, "Error: {:?}", e)?;
                    }
                    Ok((payload, text)) => {
                        let out = std::io::stdout();
                        let mut lock = out.lock();
                        writeln!(lock, "{time} - {cid}",
                            time = payload.timestamp().inner(),
                            cid = payload.content())?;

                        writeln!(lock, "{text}", text = text)?;
                        writeln!(lock, "")?;
                    },
                }
                Ok(())
            })
            .collect::<Vec<Result<()>>>()
            .await
            .into_iter()
            .collect::<Result<()>>()?;
    } else {
        eprintln!("Profile has no posts");
    }

    Ok(())
}