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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
//! Slack integration for [Flows.network](https://flows.network)
//!
//! # Quick Start
//!
//! To get started, the easist way is to write a flow function
//! that acts as a `Hello World` Slack bot.
//!
//! ```
//! use slack_flows::{listen_to_channel, send_message_to_channel};
//!
//! #[no_mangle]
//! pub fn run() {
//!     listen_to_channel("myworkspace", "mychannel", |sm| {
//!         send_message_to_channel("myworkspace", "mychannel", format!("Hello, {}",
//!         sm.text))
//!     }).await;
//! }
//! ```
//!
//! [listen_to_channel()] is responsible for registering a listener for
//! channel `mychannel` of workspace `myworkspace`. Whenever a new message
//! is sent to the channel, the callback closure is called with received
//! message then [send_message_to_channel()]
//! is used to send a response message to the same channel.

use flowsnet_platform_sdk::write_error_log;
use http_req::{
    request::{self, Method, Request},
    uri::Uri,
};
use lazy_static::lazy_static;
use rand::{distributions::Alphanumeric, Rng};
use serde::{Deserialize, Serialize};
use std::future::Future;
use std::io::{self, Write};

lazy_static! {
    static ref SLACK_API_PREFIX: String = String::from(
        std::option_env!("SLACK_API_PREFIX")
            .unwrap_or("https://slack-flows-extension.vercel.app/api")
    );
}

extern "C" {
    // Flag if current running is for listening(1) or message receving(0)
    fn is_listening() -> i32;

    // Return the user id of the flows platform
    fn get_flows_user(p: *mut u8) -> i32;

    // Return the flow id
    fn get_flow_id(p: *mut u8) -> i32;

    fn get_event_body_length() -> i32;
    fn get_event_body(p: *mut u8) -> i32;
    fn set_output(p: *const u8, len: i32);
    fn set_error_code(code: i16);
    // fn redirect_to(p: *const u8, len: i32);
}

/// A struct corresponding to the
/// [Slack message API](https://api.slack.com/events/message)
#[derive(Debug, Serialize, Deserialize)]
pub struct SlackMessage {
    #[serde(rename = "type")]
    pub event_type: String,
    pub channel: String,
    pub user: String,
    pub text: String,
    pub channel_type: String,
}

/// A struct corresponding to the
/// [Slack event API](https://api.slack.com/apis/connections/events-api#the-events-api__receiving-events__callback-field-overview)
#[derive(Debug, Serialize, Deserialize)]
pub struct Event {
    pub challenge: Option<String>,
    pub team_id: Option<String>,
    pub event: Option<SlackMessage>,
}

/// Revoke previous registered listener of current flow.
///
/// Most of the time you do not need to call this function. As inside
/// the [listen_to_channel()] it will revoke previous registered
/// listener, so the only circumstance you need this function is when
/// you want to change the listener from Slack to others.
pub async fn revoke_listeners() {
    unsafe {
        let mut flows_user = Vec::<u8>::with_capacity(100);
        let c = get_flows_user(flows_user.as_mut_ptr());
        flows_user.set_len(c as usize);
        let flows_user = String::from_utf8(flows_user).unwrap();

        let mut flow_id = Vec::<u8>::with_capacity(100);
        let c = get_flow_id(flow_id.as_mut_ptr());
        if c == 0 {
            panic!("Failed to get flow id");
        }
        flow_id.set_len(c as usize);
        let flow_id = String::from_utf8(flow_id).unwrap();

        let mut writer = Vec::new();
        let res = request::get(
            format!(
                "{}/{}/{}/revoke",
                SLACK_API_PREFIX.as_str(),
                flows_user,
                flow_id
            ),
            &mut writer,
        )
        .unwrap();

        match res.status_code().is_success() {
            true => (),
            false => {
                write_error_log!(String::from_utf8_lossy(&writer));
                set_error_code(format!("{}", res.status_code()).parse::<i16>().unwrap_or(0));
            }
        }
    }
}

/// Create a listener for channel `channel_name` of workspace `team_name`.
///
/// If you have not connected your workspace with [Flows.network platform](https://flows.network),
/// you will receive an error in the flow's building log or running log.
///
/// Before creating the listener, this function will revoke previous
/// registered listener of current flow so you don't need to do it manually.
///
/// `cb` is a callback function which will be called when the new [SlackMessage] is received.
pub async fn listen_to_channel<F, Fut>(team_name: &str, channel_name: &str, cb: F)
where
    F: FnOnce(SlackMessage) -> Fut,
    Fut: Future<Output = ()>,
{
    unsafe {
        match is_listening() {
            // Calling register
            1 => {
                let mut flows_user = Vec::<u8>::with_capacity(100);
                let c = get_flows_user(flows_user.as_mut_ptr());
                flows_user.set_len(c as usize);
                let flows_user = String::from_utf8(flows_user).unwrap();

                let mut flow_id = Vec::<u8>::with_capacity(100);
                let c = get_flow_id(flow_id.as_mut_ptr());
                if c == 0 {
                    panic!("Failed to get flow id");
                }
                flow_id.set_len(c as usize);
                let flow_id = String::from_utf8(flow_id).unwrap();

                let mut writer = Vec::new();
                let res = request::get(
                    format!(
                        "{}/{}/{}/listen?team={}&channel={}",
                        SLACK_API_PREFIX.as_str(),
                        flows_user,
                        flow_id,
                        team_name,
                        channel_name
                    ),
                    &mut writer,
                )
                .unwrap();

                match res.status_code().is_success() {
                    true => {
                        let output = format!(
                            "[{}] Listening to channel `{}` on workspace `{}`",
                            std::env!("CARGO_CRATE_NAME"),
                            channel_name,
                            team_name
                        );
                        set_output(output.as_ptr(), output.len() as i32);

                        if let Ok(sm) = serde_json::from_slice::<SlackMessage>(&writer) {
                            cb(sm);
                        }
                    }
                    false => {
                        write_error_log!(String::from_utf8_lossy(&writer));
                        set_error_code(
                            format!("{}", res.status_code()).parse::<i16>().unwrap_or(0),
                        );
                    }
                }
            }
            _ => {
                if let Some(sm) = message_from_channel() {
                    cb(sm).await;
                }
            }
        }
    }
}

fn message_from_channel() -> Option<SlackMessage> {
    unsafe {
        let l = get_event_body_length();
        let mut event_body = Vec::<u8>::with_capacity(l as usize);
        let c = get_event_body(event_body.as_mut_ptr());
        assert!(c == l);
        event_body.set_len(c as usize);
        match serde_json::from_slice::<Event>(&event_body) {
            Ok(e) => e.event,
            Err(_) => None,
        }
    }
}

/// Send message to channel `channel_name` of workspace `team_name`.
///
/// For now this function only support the
/// [text](https://api.slack.com/methods/chat.postMessage#arg_text) message.
///
/// If you have not connected your workspace with [Flows.network platform](https://flows.network),
/// you will receive an error in the flow's building log or running log.
pub async fn send_message_to_channel(team_name: &str, channel_name: &str, text: String) {
    unsafe {
        let mut flows_user = Vec::<u8>::with_capacity(100);
        let c = get_flows_user(flows_user.as_mut_ptr());
        flows_user.set_len(c as usize);
        let flows_user = String::from_utf8(flows_user).unwrap();

        let mut writer = Vec::new();
        if let Ok(res) = request::post(
            format!(
                "{}/{}/send?team={}&channel={}",
                SLACK_API_PREFIX.as_str(),
                flows_user,
                team_name,
                channel_name
            ),
            text.as_bytes(),
            &mut writer,
        ) {
            if !res.status_code().is_success() {
                write_error_log!(String::from_utf8_lossy(&writer));
                set_error_code(format!("{}", res.status_code()).parse::<i16>().unwrap_or(0));
            }
        }
    }
}

/// Upload a file to channel `channel_name` of workspace `team_name`.
///
/// `file_name` is the filename of the uploading file.
///
/// `file_type` refers to [file type](https://api.slack.com/types/file#file_types) of Slack.
///
/// `file_bytes` is file's raw bytes.
pub async fn upload_file(
    team_name: &str,
    channel_name: &str,
    file_name: &str,
    file_type: &str,
    file_bytes: Vec<u8>,
) {
    unsafe {
        let mut flows_user = Vec::<u8>::with_capacity(100);
        let c = get_flows_user(flows_user.as_mut_ptr());
        flows_user.set_len(c as usize);
        let flows_user = String::from_utf8(flows_user).unwrap();

        let boundary: String = rand::thread_rng()
            .sample_iter(&Alphanumeric)
            .take(15)
            .map(char::from)
            .collect();
        let boundary = format!("------------------------{}", boundary);

        if let Ok(file_part) =
            compose_file_part(&boundary, channel_name, file_name, file_type, file_bytes)
        {
            let mut writer = Vec::new();

            let uri = format!(
                "{}/{}/upload?team={}&channel={}",
                SLACK_API_PREFIX.as_str(),
                flows_user,
                team_name,
                channel_name
            );
            let uri = Uri::try_from(uri.as_str()).unwrap();
            if let Ok(res) = Request::new(&uri)
                .method(Method::POST)
                .header(
                    "Content-Type",
                    &format!("multipart/form-data; boundary={}", boundary),
                )
                .header("Content-Length", &file_part.len())
                .body(&file_part)
                .send(&mut writer)
            {
                if !res.status_code().is_success() {
                    write_error_log!(String::from_utf8_lossy(&writer));
                    set_error_code(format!("{}", res.status_code()).parse::<i16>().unwrap_or(0));
                }
            }
        }
    }
}

fn compose_file_part(
    boundary: &str,
    channel: &str,
    file_name: &str,
    file_type: &str,
    file_bytes: Vec<u8>,
) -> io::Result<Vec<u8>> {
    let mut data = Vec::new();
    write!(data, "--{}\r\n", boundary)?;
    write!(data, "Content-Disposition: form-data; name=\"channel\"\r\n")?;
    write!(data, "\r\n{}\r\n", channel)?;
    write!(data, "--{}\r\n", boundary)?;
    write!(
        data,
        "Content-Disposition: form-data; name=\"file\"; filename=\"{}\"\r\n",
        file_name
    )?;
    write!(data, "Content-Type: {}\r\n\r\n", file_type)?;

    data.extend_from_slice(&file_bytes);

    write!(data, "\r\n")?; // The key thing you are missing
    write!(data, "--{}--\r\n", boundary)?;

    Ok(data)
}