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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
use std::fmt;
use std::str::FromStr;

use thiserror::Error;

// ############
// # Protocol #
// ############
//
// [connect]
// > USER <username>
// < 20 <user_id>
// > LISTFEEDS
// < 21
// < 22 <feed_id> <feed_url> :<feed_name>
// < 25
// > LISTUNREAD
// < 23
// < 24 <entry_id> <feed_id> <feed_url> <entry_title> :<entry_link>
// < 25
// > MARKREAD <entry_id>
// < 28

/// Commands sent to seymour server
#[derive(Debug)]
pub enum Command {
    /// Select the user user
    User { username: String },

    /// List the current user's subscriptions
    ///
    /// Requires a client to issue a User
    /// command prior.
    ListSubscriptions,

    /// Subscribe the current user to a new feed
    ///
    /// Requires a client to issue a User
    /// command prior.
    Subscribe { url: String },

    /// Unsubscribe the current user from a feed
    ///
    /// Requires a client to issue a User
    /// command prior.
    Unsubscribe { id: i64 },

    /// List the current user's unread feed entries
    ///
    /// Requires a client to issue a User
    /// command prior.
    ListUnread,

    /// Mark a feed entry as read by the current user
    ///
    /// Requires a client to issue a User
    /// command prior.
    MarkRead { id: i64 },
}

impl fmt::Display for Command {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Command::User { username } => write!(f, "USER {}", username),
            Command::ListSubscriptions => write!(f, "LISTSUBSCRIPTIONS"),
            Command::Subscribe { url } => write!(f, "SUBSCRIBE {}", url),
            Command::Unsubscribe { id } => write!(f, "UNSUBSCRIBE {}", id),
            Command::ListUnread => write!(f, "LISTUNREAD"),
            Command::MarkRead { id } => write!(f, "MARKREAD {}", id),
        }
    }
}

fn check_arguments(parts: &Vec<&str>, expected: usize) -> Result<(), ParseMessageError> {
    if parts.len() > expected + 1 {
        return Err(ParseMessageError::TooManyArguments {
            expected,
            actual: parts.len() - 1,
        });
    }

    Ok(())
}

fn at_position<T: FromStr>(
    parts: &[&str],
    argument_name: &str,
    position: usize,
) -> Result<T, ParseMessageError> {
    let possible = parts
        .get(position)
        .ok_or_else(|| ParseMessageError::MissingArgument(argument_name.to_string()))?;

    possible
        .parse()
        .map_err(|_| ParseMessageError::InvalidIntegerArgument {
            argument: argument_name.to_string(),
            value: possible.to_string(),
        })
}

#[derive(Debug, Error)]
pub enum ParseMessageError {
    #[error("empty message")]
    EmptyMessage,
    #[error("unknown message type \"{0}\"")]
    UnknownType(String),
    #[error("missing argument \"{0}\"")]
    MissingArgument(String),
    #[error("too many arguments (expected {expected}, got {actual})")]
    TooManyArguments { expected: usize, actual: usize },
    #[error("invalid integer value \"{value}\" for argument \"{argument}\"")]
    InvalidIntegerArgument { argument: String, value: String },
}

impl FromStr for Command {
    type Err = ParseMessageError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        let parts: Vec<&str> = value.split(' ').collect();

        let command = parts.get(0).ok_or(ParseMessageError::EmptyMessage)?;

        match *command {
            "USER" => {
                check_arguments(&parts, 1)?;

                let username: String = at_position(&parts, "username", 1)?;

                Ok(Command::User { username })
            }
            "LISTSUBSCRIPTIONS" => {
                check_arguments(&parts, 0)?;

                Ok(Command::ListSubscriptions)
            }
            "SUBSCRIBE" => {
                check_arguments(&parts, 1)?;

                let url: String = at_position(&parts, "url", 1)?;

                Ok(Command::Subscribe { url })
            }
            "UNSUBSCRIBE" => {
                check_arguments(&parts, 1)?;

                let id: i64 = at_position(&parts, "id", 1)?;

                Ok(Command::Unsubscribe { id })
            }
            "LISTUNREAD" => {
                check_arguments(&parts, 0)?;

                Ok(Command::ListUnread)
            }
            "MARKREAD" => {
                check_arguments(&parts, 1)?;

                let id: i64 = at_position(&parts, "id", 1)?;

                Ok(Command::MarkRead { id })
            }
            _ => Err(ParseMessageError::UnknownType(command.to_string())),
        }
    }
}

/// Responses sent from seymour server
#[derive(Debug)]
pub enum Response {
    /// Acknowledgement for selecting current user
    AckUser { id: i64 },

    /// Beginning of a list of subscriptions
    ///
    /// Must be followed by zero or more Subscription lines and
    /// one EndList.
    StartSubscriptionList,

    /// A single subscription entry
    ///
    /// Must be preceeded by one StartSubscriptionList and
    /// followed by one EndList.
    Subscription { id: i64, url: String },

    /// Beginning of a list of feed entries
    ///
    /// Must be followed by zero or more Entry lines and
    /// one EndList.
    StartEntryList,

    /// A single feed entry
    ///
    /// Must be preceeded by one StartEntryList and
    /// followed by one EndList.
    Entry {
        id: i64,
        feed_id: i64,
        feed_url: String,
        title: String,
        url: String,
    },

    /// Ends a list sent by the server
    ///
    /// Must be preceeded by at least either a StartSubscriptionList
    /// or a StartEntryList.
    EndList,

    /// Acknowledgement for subscribing the current user
    /// to a new feed
    AckSubscribe,

    /// Acknowledgement for unsubscribing the current user
    /// from a feed
    AckUnsubscribe,

    /// Acknowledgement for marking a feed entry as read
    /// by the current user
    AckMarkRead,

    /// Error stating that the specified resource was
    /// not found
    ResourceNotFound(String),

    /// Error stating that the command sent was not valid
    BadCommand(String),

    /// Error stating that the command sent requires a
    /// selected user, but no user has been selected
    NeedUser(String),

    /// Error stating that the seymour server hit an
    /// internal problem while attempting to serve
    /// the request
    InternalError(String),
}

impl From<ParseMessageError> for Response {
    fn from(e: ParseMessageError) -> Response {
        Response::BadCommand(e.to_string())
    }
}

impl fmt::Display for Response {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Response::AckUser { id } => write!(f, "20 {}", id),
            Response::StartSubscriptionList => write!(f, "21"),
            Response::Subscription { id, url } => write!(f, "22 {} {}", id, url),
            Response::StartEntryList => write!(f, "23"),
            Response::Entry {
                id,
                feed_id,
                feed_url,
                title,
                url,
            } => write!(f, "24 {} {} {} {} {}", id, feed_id, feed_url, url, title),
            Response::EndList => write!(f, "25"),
            Response::AckSubscribe => write!(f, "26"),
            Response::AckUnsubscribe => write!(f, "27"),
            Response::AckMarkRead => write!(f, "28"),

            Response::ResourceNotFound(message) => write!(f, "40 {}", message),
            Response::BadCommand(message) => write!(f, "41 {}", message),
            Response::NeedUser(message) => write!(f, "42 {}", message),

            Response::InternalError(message) => write!(f, "51 {}", message),
        }
    }
}

impl FromStr for Response {
    type Err = ParseMessageError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        let parts: Vec<&str> = value.split(' ').collect();

        let response = parts.get(0).ok_or(ParseMessageError::EmptyMessage)?;

        match *response {
            "20" => {
                check_arguments(&parts, 1)?;

                let id: i64 = at_position(&parts, "id", 1)?;

                Ok(Response::AckUser { id })
            }
            "21" => {
                check_arguments(&parts, 0)?;

                Ok(Response::StartSubscriptionList)
            }
            "22" => {
                check_arguments(&parts, 2)?;

                let id: i64 = at_position(&parts, "id", 1)?;
                let url: String = at_position(&parts, "url", 2)?;

                Ok(Response::Subscription { id, url })
            }
            "23" => {
                check_arguments(&parts, 0)?;

                Ok(Response::StartEntryList)
            }
            "24" => {
                let index = value
                    .find(' ')
                    .ok_or_else(|| ParseMessageError::MissingArgument("code".to_string()))?;

                let line = &value[index + 1..];

                let index = line
                    .find(' ')
                    .ok_or_else(|| ParseMessageError::MissingArgument("id".to_string()))?;

                let id: i64 = line[..index].parse().map_err(|_| {
                    ParseMessageError::InvalidIntegerArgument {
                        argument: "id".to_string(),
                        value: line[..index].to_string(),
                    }
                })?;

                let line = &line[index + 1..];
                let index = line
                    .find(' ')
                    .ok_or_else(|| ParseMessageError::MissingArgument("feed_id".to_string()))?;

                let feed_id: i64 = line[..index].parse().map_err(|_| {
                    ParseMessageError::InvalidIntegerArgument {
                        argument: "feed_id".to_string(),
                        value: line[..index].to_string(),
                    }
                })?;

                let line = &line[index + 1..];
                let index = line
                    .find(' ')
                    .ok_or_else(|| ParseMessageError::MissingArgument("feed_url".to_string()))?;
                let feed_url = line[..index].to_string();

                let line = &line[index + 1..];
                let index = line
                    .find(' ')
                    .ok_or_else(|| ParseMessageError::MissingArgument("url".to_string()))?;
                let url = line[..index].to_string();

                let title = line[index + 1..].to_string();

                Ok(Response::Entry {
                    id,
                    feed_id,
                    feed_url,
                    title,
                    url,
                })
            }
            "25" => {
                check_arguments(&parts, 0)?;

                Ok(Response::EndList)
            }
            "26" => {
                check_arguments(&parts, 0)?;

                Ok(Response::AckSubscribe)
            }
            "27" => {
                check_arguments(&parts, 0)?;

                Ok(Response::AckUnsubscribe)
            }
            "28" => {
                check_arguments(&parts, 0)?;

                Ok(Response::AckMarkRead)
            }

            "40" => {
                check_arguments(&parts, 1)?;

                let message: String = at_position(&parts, "message", 1)?;

                Ok(Response::ResourceNotFound(message))
            }
            "41" => {
                check_arguments(&parts, 1)?;

                let message: String = at_position(&parts, "message", 1)?;

                Ok(Response::BadCommand(message))
            }
            "42" => {
                check_arguments(&parts, 1)?;

                let message: String = at_position(&parts, "message", 1)?;

                Ok(Response::NeedUser(message))
            }

            "50" => {
                check_arguments(&parts, 1)?;

                let message: String = at_position(&parts, "message", 1)?;

                Ok(Response::InternalError(message))
            }
            _ => Err(ParseMessageError::UnknownType(response.to_string())),
        }
    }
}