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
use {
    daumdic, daummap,
    failure::{Error, Fail},
    futures::prelude::*,
    howto,
    lazy_static::lazy_static,
    regex::Regex,
    serde_derive::{Deserialize, Serialize},
    std::{fmt, str::FromStr},
};

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Config {
    pub daummap_app_key: String,
}

#[derive(Debug, Fail, PartialEq, Eq)]
pub enum RequestError {
    #[fail(display = "cannot parse request {}", _0)]
    CannotParseRequest(String),
    #[fail(display = "address is not found for {}", _0)]
    AddressNotFound(String),
    #[fail(display = "{} is not a valid command for airkorea", _0)]
    InvalidAirkoreaCommand(String),
    #[fail(display = "answer is not found for {}", _0)]
    HowtoNotFound(String),
}

#[derive(Debug, Clone)]
pub enum Response {
    Dictionary(daumdic::Search),
    AirPollution(airkorea::AirStatus),
    HowTo(howto::Answer),
}

impl fmt::Display for Response {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Response::Dictionary(ref search) => {
                if !search.alternatives.is_empty() {
                    writeln!(f, "{}", search.alternatives.join(", "))?;
                }
                for word in search.words.iter() {
                    writeln!(f, "{}", word)?;
                }
            }
            Response::AirPollution(ref status) => {
                if !status.station_address.is_empty() {
                    writeln!(f, "Station: {}", status.station_address)?;
                }
                for pollutant in status.pollutants.iter() {
                    writeln!(
                        f,
                        "{}: {}{} {}",
                        pollutant.name,
                        pollutant
                            .level
                            .map(|f| f.to_string())
                            .unwrap_or_else(|| "--".to_string()),
                        pollutant.unit,
                        pollutant.grade,
                    )?;
                }
            }
            Response::HowTo(answer) => {
                writeln!(f, "Answer from: {}", answer.link)?;
                write!(f, "{}", answer.instruction)?;
            }
        }
        Ok(())
    }
}

#[derive(Debug, Clone)]
pub enum Request {
    Dictionary(String),
    AirPollution(String, String),
    HowTo(String),
}

impl FromStr for Request {
    type Err = Error;

    fn from_str(message: &str) -> Result<Self, Self::Err> {
        lazy_static! {
            static ref REGEX_DIC: Regex = Regex::new(r"^[dD](?:ic)? (.+)$").unwrap();
            static ref REGEX_AIR: Regex =
                Regex::new(r"^(air|pm|pm10|pm25|o3|so2|no2|co|so2) (.+)$").unwrap();
            static ref REGEX_HOWTO: Regex = Regex::new(r"^[hH](?:owto)? (.+)$").unwrap();
        }

        REGEX_DIC
            .captures(message)
            .map(|c| c.get(1).unwrap().as_str().to_owned())
            .map(Request::Dictionary)
            .or_else(|| {
                REGEX_AIR
                    .captures(message)
                    .map(|c| {
                        (
                            c.get(1).unwrap().as_str().to_owned(),
                            c.get(2).unwrap().as_str().to_owned(),
                        )
                    })
                    .map(|(s1, s2)| Request::AirPollution(s1, s2))
            })
            .or_else(|| {
                REGEX_HOWTO
                    .captures(message)
                    .map(|c| c.get(1).unwrap().as_str().to_owned())
                    .map(Request::HowTo)
            })
            .ok_or_else(|| RequestError::CannotParseRequest(message.to_string()).into())
    }
}

impl Request {
    pub fn request(self, config: &Config) -> impl Future<Item = Response, Error = Error> {
        use futures::future::Either;

        match self {
            Request::Dictionary(query) => Either::A(search_dic(&query)),
            Request::AirPollution(command, query) => Either::B(Either::A(search_air(
                &command,
                &query,
                &config.daummap_app_key,
            ))),
            Request::HowTo(query) => Either::B(Either::B(search_howto(&query))),
        }
    }
}

fn join<T, U>(e: (Option<T>, Option<U>)) -> Option<(T, U)> {
    match e {
        (Some(t), Some(u)) => Some((t, u)),
        _ => None,
    }
}

fn get_coord_from_address(address: &daummap::Address) -> Option<(f32, f32)> {
    address
        .land_lot
        .as_ref()
        .map(|land_lot| (land_lot.longitude, land_lot.latitude))
        .and_then(join)
}

fn get_coord_from_place(place: &daummap::Place) -> Option<(f32, f32)> {
    join((place.longitude, place.latitude))
}

fn search_dic(query: &str) -> impl Future<Item = Response, Error = Error> {
    daumdic::search(query).map(Response::Dictionary)
}

fn search_air(
    command: &str,
    query: &str,
    app_key: &str,
) -> impl Future<Item = Response, Error = Error> {
    let command = command.to_string();
    let query = query.to_string();
    let app_key = app_key.to_string();

    daummap::AddressRequest::new(&app_key, &query)
        .get()
        .filter_map(|address| get_coord_from_address(&address))
        .into_future()
        .map_err(|(e, _)| e)
        .and_then({
            let query = query.clone();
            move |(o, _)| o.ok_or_else(|| RequestError::AddressNotFound(query).into())
        })
        .or_else({
            let query = query.clone();
            let app_key = app_key.clone();
            move |_| {
                daummap::KeywordRequest::new(&app_key, &query)
                    .get()
                    .filter_map(|place| get_coord_from_place(&place))
                    .into_future()
                    .map_err(|(e, _)| e)
                    .and_then(|(o, _)| o.ok_or_else(|| RequestError::AddressNotFound(query).into()))
            }
        })
        .and_then(|(longitude, latitude)| airkorea::search(longitude, latitude))
        .and_then(move |status| {
            let station_address = status.station_address.clone();
            let pollutants = match command.as_ref() {
                "air" => status.pollutants,
                "pm" => status
                    .into_iter()
                    .filter(|p| p.name.contains("PM"))
                    .collect(),
                command => status
                    .into_iter()
                    .filter(|p| p.name.to_lowercase().contains(&command))
                    .collect(),
            };

            if pollutants.is_empty() {
                Err(RequestError::InvalidAirkoreaCommand(command).into())
            } else {
                Ok(airkorea::AirStatus {
                    station_address,
                    pollutants,
                })
            }
        })
        .map(Response::AirPollution)
}

fn search_howto(query: &str) -> impl Future<Item = Response, Error = Error> {
    let query = query.to_string();
    howto::howto(&query)
        .into_future()
        .map_err(|(e, _)| e)
        .and_then(|(answer, _)| answer.ok_or_else(|| RequestError::HowtoNotFound(query).into()))
        .map(Response::HowTo)
}