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
use chrono::NaiveDateTime;
use crate::error::{SlackError, Result};
use reqwest::Client;
use url::Url;
use serde::{Serialize, Serializer};
use std::fmt;
use crate::Payload;

/// Handles sending messages to slack
#[derive(Debug, Clone)]
pub struct Slack {
    hook: Url,
    client: Client,
}

impl Slack {
    /// Construct a new instance of slack for a specific incoming url endpoint.
    pub fn new<U: reqwest::IntoUrl>(hook: U) -> Result<Slack> {
        Ok(Slack {
            hook: hook.into_url().map_err(|e| SlackError::Http(format!("failed to convert to reqwest::url: {}", e)))?,
            client: Client::new(),
        })
    }

    /// Send payload to slack service
    pub async fn send(&self, payload: &Payload) -> Result<()> {
        let response = self.client.post(self.hook.clone()).json(payload).send().await
            .map_err(|e| SlackError::Http(format!("HTTP send error to {}: {}", self.hook, e)))?;

        if response.status().is_success(){
            Ok(())
        } else {
            Err(SlackError::Http(format!("HTTP error {}", response.status())))
        }
    }
}

/// Slack timestamp
#[derive(Debug, Clone, PartialEq, PartialOrd)]
pub struct SlackTime(NaiveDateTime);

impl SlackTime {
    /// Construct a new `SlackTime`
    pub fn new(time: &NaiveDateTime) -> SlackTime {
        SlackTime(*time)
    }
}

impl Serialize for SlackTime {
    fn serialize<S>(&self, serializer: S) -> ::std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_i64(self.0.timestamp())
    }
}

/// Representation of any text sent through slack
/// the text must be processed to escape specific characters
#[derive(Serialize, Debug, Default, Clone, PartialEq)]
pub struct SlackText(String);

impl SlackText {
    /// Construct slack text with escaping
    /// Escape &, <, and > in any slack text
    /// https://api.slack.com/docs/formatting
    pub fn new<S: Into<String>>(text: S) -> SlackText {
        let s = text.into().chars().fold(String::new(), |mut s, c| {
            match c {
                '&' => s.push_str("&amp;"),
                '<' => s.push_str("&lt;"),
                '>' => s.push_str("&gt;"),
                _ => s.push(c),
            }
            s
        });
        SlackText(s)
    }

    fn new_raw<S: Into<String>>(text: S) -> SlackText {
        SlackText(text.into())
    }
}

impl<'a> From<&'a str> for SlackText {
    fn from(s: &'a str) -> SlackText {
        SlackText::new(String::from(s))
    }
}

impl<'a> From<String> for SlackText {
    fn from(s: String) -> SlackText {
        SlackText::new(s)
    }
}

/// Enum used for constructing a text field having both `SlackText`(s) and `SlackLink`(s). The
/// variants should be used together in a `Vec` on any function having a `Into<SlackText>` trait
/// bound. The combined text will be space-separated.
#[derive(Debug, Clone, PartialEq)]
pub enum SlackTextContent {
    /// Text that will be escaped via slack api rules
    Text(SlackText),
    /// Link
    Link(SlackLink),
    /// User Link
    User(SlackUserLink),
}

impl<'a> From<&'a [SlackTextContent]> for SlackText {
    fn from(v: &[SlackTextContent]) -> SlackText {
        let st = v
            .iter()
            .map(|item| match *item {
                SlackTextContent::Text(ref s) => format!("{}", s),
                SlackTextContent::Link(ref link) => format!("{}", link),
                SlackTextContent::User(ref u) => format!("{}", u),
            }).collect::<Vec<String>>()
            .join(" ");
        SlackText::new_raw(st)
    }
}

impl fmt::Display for SlackText {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// Representation of a link sent in slack
#[derive(Debug, Clone, PartialEq)]
pub struct SlackLink {
    /// URL for link.
    ///
    /// NOTE: this is NOT a `Url` type because some of the slack "urls", don't conform to standard
    /// url parsing scheme, which are enforced by the `url` crate.
    pub url: String,
    /// Anchor text for link
    pub text: SlackText,
}

impl SlackLink {
    /// Construct new SlackLink with string slices
    pub fn new(url: &str, text: &str) -> SlackLink {
        SlackLink {
            url: url.to_owned(),
            text: SlackText::new(text),
        }
    }
}

impl fmt::Display for SlackLink {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "<{}|{}>", self.url, self.text)
    }
}

impl Serialize for SlackLink {
    fn serialize<S>(&self, serializer: S) -> ::std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&format!("{}", self)[..])
    }
}

/// Representation of a user id link sent in slack
///
/// Cannot do @UGUID|handle links using SlackLink in the future due to
/// https://api.slack.com/changelog/2017-09-the-one-about-usernames
#[derive(Debug, Clone, PartialEq, PartialOrd)]
pub struct SlackUserLink {
    /// User ID (U1231232123) style
    pub uid: String,
}

impl SlackUserLink {
    /// Construct new `SlackUserLink` with a string slice
    pub fn new(uid: &str) -> SlackUserLink {
        SlackUserLink {
            uid: uid.to_owned(),
        }
    }
}

impl fmt::Display for SlackUserLink {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "<{}>", self.uid)
    }
}

impl Serialize for SlackUserLink {
    fn serialize<S>(&self, serializer: S) -> ::std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&format!("{}", self)[..])
    }
}

#[cfg(test)]
mod test {
    use chrono::NaiveDateTime;
    use crate::slack::{Slack, SlackLink};
    #[cfg(feature = "unstable")]
    use test::Bencher;
    use serde_json;
    use crate::{AttachmentBuilder, Field, Parse, PayloadBuilder, SlackText};

    #[test]
    fn slack_incoming_url_test() {
        let s = Slack::new("https://hooks.slack.com/services/abc/123/45z").unwrap();
        assert_eq!(
            s.hook.to_string(),
            "https://hooks.slack.com/services/abc/123/45z".to_owned()
        );
    }

    #[test]
    fn slack_text_test() {
        let s = SlackText::new("moo <&> moo");
        assert_eq!(format!("{}", s), "moo &lt;&amp;&gt; moo".to_owned());
    }

    #[test]
    fn slack_link_test() {
        let s = SlackLink {
            text: SlackText::new("moo <&> moo"),
            url: "http://google.com".to_owned(),
        };
        assert_eq!(
            format!("{}", s),
            "<http://google.com|moo &lt;&amp;&gt; moo>".to_owned()
        );
    }

    #[test]
    fn json_slacklink_test() {
        let s = SlackLink {
            text: SlackText::new("moo <&> moo"),
            url: "http://google.com".to_owned(),
        };
        assert_eq!(
            serde_json::to_string(&s).unwrap().to_owned(),
            "\"<http://google.com|moo &lt;&amp;&gt; moo>\"".to_owned()
        )
    }

    #[test]
    fn json_complete_payload_test() {
        let a = vec![
            AttachmentBuilder::new("fallback <&>")
                .text("text <&>")
                .color("#6800e8")
                .fields(vec![Field::new("title", "value", None)])
                .title_link("https://title_link.com/")
                .ts(&NaiveDateTime::from_timestamp(123_456_789, 0))
                .build()
                .unwrap(),
        ];

        let p = PayloadBuilder::new()
            .text("test message")
            .channel("#abc")
            .username("Bot")
            .icon_emoji(":chart_with_upwards_trend:")
            .icon_url("https://example.com")
            .attachments(a)
            .unfurl_links(false)
            .link_names(true)
            .parse(Parse::Full)
            .build()
            .unwrap();

        assert_eq!(serde_json::to_string(&p).unwrap().to_owned(),
            r##"{"text":"test message","channel":"#abc","username":"Bot","icon_url":"https://example.com/","icon_emoji":":chart_with_upwards_trend:","attachments":[{"fallback":"fallback &lt;&amp;&gt;","text":"text &lt;&amp;&gt;","color":"#6800e8","fields":[{"title":"title","value":"value"}],"title_link":"https://title_link.com/","ts":123456789}],"unfurl_links":false,"link_names":1,"parse":"full"}"##.to_owned())
    }

    #[test]
    fn json_message_payload_test() {
        let p = PayloadBuilder::new().text("test message").build().unwrap();

        assert_eq!(
            serde_json::to_string(&p).unwrap().to_owned(),
            r##"{"text":"test message"}"##.to_owned()
        )
    }

    #[test]
    fn slack_text_content_test() {
        use super::SlackTextContent;
        use super::SlackTextContent::{Link, Text};
        let message: Vec<SlackTextContent> = vec![
            Text("moo <&> moo".into()),
            Link(SlackLink::new("@USER", "M<E>")),
            Text("wow.".into()),
        ];
        let st: SlackText = SlackText::from(&message[..]);
        assert_eq!(
            format!("{}", st),
            "moo &lt;&amp;&gt; moo <@USER|M&lt;E&gt;> wow."
        );
    }
}