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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
use super::scope::Scope;
use serialize::json::{Json, ToJson, Object, Array};
use super::event::EventType;
use std::string::ToString;
use std::str::FromStr;
use super::error::ParseConfigGroupError;
use std::ascii::AsciiExt;

/// The version of the DaZeus plugin communication protocol that these bindings understand.
pub const PROTOCOL_VERSION: &'static str = "1";

/// A `String` for the target IRC network.
pub type Network = String;

/// A `String` containing the message to be sent.
pub type Message = String;

/// A `String` containing the target (receiver) of some command or message.
///
/// Typically this is a client or some channel on an IRC network.
pub type Target = String;

/// A `String` indicating the name of some command.
pub type Command = String;

/// A `String` indicating the name of the plugin. This is used for retrieving configuration.
pub type PluginName = String;

/// A `String` indicating the version of the protocol used by the bindings.
pub type PluginVersion = String;

/// The type of config that should be retrieved.
#[derive(Debug, Clone, PartialEq)]
pub enum ConfigGroup {
    /// Indicates a config value that should be retrieved from the plugin settings.
    Plugin,
    /// Indicates a config value that should be retrieved from the core settings.
    Core,
}

impl ToString for ConfigGroup {
    fn to_string(&self) -> String {
        match *self {
            ConfigGroup::Plugin => "plugin".to_string(),
            ConfigGroup::Core => "core".to_string(),
        }
    }
}

impl FromStr for ConfigGroup {
    type Err = ParseConfigGroupError;

    fn from_str(s: &str) -> Result<Self, ParseConfigGroupError> {
        match &s.to_ascii_lowercase()[..] {
            "plugin" => Ok(ConfigGroup::Plugin),
            "core" => Ok(ConfigGroup::Core),
            _ => Err(ParseConfigGroupError::new())
        }
    }
}

/// An enum of all requests that can be sent to your DaZeus instance.
///
/// Note that typically you won't create these request instances directly. Instead you can use the
/// different `DaZeus` methods. However if you wish, you can directly use `DaZeus::send()` to send
/// these requests yourself.
#[derive(Debug, Clone, PartialEq)]
pub enum Request {
    /// Subscribe to a certain event type.
    ///
    /// # Example
    /// ```
    /// Request::Subscribe(EventType::PrivMsg)
    /// ```
    Subscribe(EventType),
    /// Unsubscribe from an event.
    ///
    /// Note that you cannot specify `EventType::Command()` for this request, as registered
    /// commands cannot be unregistered from the DaZeus server. To stop listening, just let DaZeus
    /// remove the listener.
    ///
    /// # Example
    /// ```
    /// Request::Unsubscribe(EventType::Join)
    /// ```
    Unsubscribe(EventType),
    /// Subscribe to a command (optionally on a specific network).
    ///
    /// You can use `Request::Subscribe(EventType::Command("example".to_string())` as an
    /// alternative to `Request::SubscribeCommand("example".to_string())`. Note that the
    /// former does not allow you to optionally specify a network on which the command is actively
    /// listened to.
    ///
    /// # Example
    /// ```
    /// Request::SubscribeCommand("greet".to_string(), Some("freenode".to_string()))
    /// ```
    SubscribeCommand(Command, Option<Network>),
    /// Retrieve a list of networks that the DaZeus core is currently connected to.
    ///
    /// # Example
    /// ```
    /// Request::Networks
    /// ```
    Networks,
    /// Retrieve a list of channels on the specified network that the bot has joined.
    ///
    /// # Example
    /// ```
    /// Request::Channels("freenode".to_string())
    /// ```
    Channels(Network),
    /// Request to send a message to a specific target on some network.
    ///
    /// This will request DaZeus to send a PRIVMSG.
    ///
    /// # Example
    /// ```
    /// Request::Message("freenode".to_string(), "#botters-test".to_string(), "Hello!".to_string())
    /// ```
    Message(Network, Target, Message),
    /// Request to send a notice to some target on some network.
    ///
    /// This will request DaZeus to send a NOTICE.
    ///
    /// # Example
    /// ```
    /// Request::Notice("example".to_string(), "MrExample".to_string(), "Message!".to_string())
    /// ```
    Notice(Network, Target, Message),
    /// Request to send a CTCP message to some client on some network.
    ///
    /// # Example
    /// ```
    /// Request::Ctcp("example".to_string(), "MrExample".to_string(), "VERSION".to_string())
    /// ```
    Ctcp(Network, Target, Message),
    /// Request to send a CTCP message reply to some client on some network.
    ///
    /// # Example
    /// ```
    /// Request::CtcpReply("example".to_string(), "MrExample".to_string(), "VERSION DaZeus 2.0".to_string())
    /// ```
    CtcpReply(Network, Target, Message),
    /// Request to send a CTCP ACTION message to some target on some network.
    ///
    /// A CTCP ACTION is most known by users as the `/me` command.
    ///
    /// # Example
    /// ```
    /// Request::Action("example".to_string(), "#example", "is creating an example".to_string())
    /// ```
    Action(Network, Target, Message),
    /// Request to send the list of names in some channel.
    ///
    /// Note that such a request will generate an `EventType::Names` event if the server allows it,
    /// instead of responding to this request directly.
    ///
    /// # Example
    /// ```
    /// Request::Names("freenode".to_string(), "#freenode".to_string())
    /// ```
    Names(Network, Target),
    /// Request to send a whois on some target.
    ///
    /// Note that such a request will generate an `EventType::Whois` event if the server allows it,
    /// instead of responding to this request directly.
    ///
    /// # Example
    /// ```
    /// Request::Whois("example".to_string(), "MrExample".to_string())
    /// ```
    Whois(Network, Target),
    /// Request to join a channel on some network.
    ///
    /// # Example
    /// ```
    /// Request::Join("freenode".to_string(), "#freenode".to_string())
    /// ```
    Join(Network, Target),
    /// Request to leave a channel on some network.
    ///
    /// # Example
    /// ```
    /// Request::Part("freenode".to_string(), "#freenode".to_string())
    /// ```
    Part(Network, Target),
    /// Request the nickname of the bot on a network.
    ///
    /// # Example
    /// ```
    /// Request::Nick("freenode".to_string())
    /// ```
    Nick(Network),
    /// Request for a handshake to the DaZeus Core.
    ///
    /// The handshake allows the plugin to retrieve configuration options.
    ///
    /// The second parameter of this request variant is the plugin version. Note that this
    /// parameter should be equal to the version that these bindings understand.
    ///
    /// The optional third parameter may provide an alternative name to be used to retrieve
    /// options from the DaZeus core config. By default the name of the plugin will be used.
    ///
    /// # Example
    /// ```
    /// Request::Handshake("my_plugin".to_string(), PROTOCOL_VERSION.to_string(), None)
    /// ```
    Handshake(PluginName, PluginVersion, Option<String>),
    /// Retrieve some option from the DaZeus core config.
    ///
    /// The second parameter is the section from which the configuration parameter should be
    /// retrieved. This may either be `ConfigGroup::Core` or `ConfigGroup::Plugin`
    ///
    /// Note that in order to successfully retrieve these configuration values the plugin first
    /// needs to have completed a succesful handshake with the core.
    ///
    /// # Example
    /// ```
    /// Request::Config("highlight".to_string(), ConfigGroup::Core)
    /// ```
    Config(String, ConfigGroup),
    /// Retrieve a property from the internal DaZeus core database.
    ///
    /// # Example
    /// ```
    /// Request::GetProperty("example".to_string(), Scope::any())
    /// ```
    GetProperty(String, Scope),
    /// Set a property in the internal DaZeus core database.
    ///
    /// # Example
    /// ```
    /// Request::SetProperty("example".to_string(), "value".to_string(), Scope::any())
    /// ```
    SetProperty(String, String, Scope),
    /// Remove a property from the internal DaZeus core database.
    ///
    /// # Example
    /// ```
    /// Request::UnsetProperty("example".to_string(), Scope::any())
    /// ```
    UnsetProperty(String, Scope),
    /// Retrieve a set of keys that is available for some prefix and scope.
    ///
    /// The first parameter of the variant is the prefix string for retrieving property keys.
    ///
    /// # Example
    /// ```
    /// Request::PropertyKeys("path.to".to_string(), Scope::network("example"))
    /// ```
    PropertyKeys(String, Scope),
    /// Set a permission in the permission database of the DaZeus core.
    ///
    /// # Example
    /// ```
    /// Request::SetPermission("edit".to_string(), true, Scope::sender("example", "MrExample"))
    /// ```
    SetPermission(String, bool, Scope),
    /// Request a permission to be retrieved from the permission database of the DaZeus core.
    ///
    /// The second parameter of this variant indicates the default value that the core should
    /// return if the permission was not found inside the permission database.
    ///
    /// # Example
    /// ```
    /// Request::HasPermission("edit".to_string(), false, Scope::sender("example", "MrExample"))
    /// ```
    HasPermission(String, bool, Scope),
    /// Remove a permission from the permission database of the DaZeus core.
    ///
    /// # Example
    /// ```
    /// Request::UnsetPermission("edit".to_string(), Scope::sender("example", "MrExample"))
    /// ```
    UnsetPermission(String, Scope),
}

impl Request {
    fn get_json_name(&self) -> Json {
        let s = match *self {
            Request::Subscribe(EventType::Command(_)) => "command",
            Request::Subscribe(_) => "subscribe",
            Request::Unsubscribe(_) => "unsubscribe",
            Request::SubscribeCommand(_, _) => "command",
            Request::Networks => "networks",
            Request::Channels(_) => "channels",
            Request::Message(_, _, _) => "message",
            Request::Notice(_, _, _) => "notice",
            Request::Ctcp(_, _, _) => "ctcp",
            Request::CtcpReply(_, _, _) => "ctcp_rep",
            Request::Action(_, _, _) => "action",
            Request::Names(_, _) => "names",
            Request::Whois(_, _) => "whois",
            Request::Join(_, _) => "join",
            Request::Part(_, _) => "part",
            Request::Nick(_) => "nick",
            Request::Handshake(_, _, _) => "handshake",
            Request::Config(_, _) => "config",
            Request::GetProperty(_, _) => "property",
            Request::SetProperty(_, _, _) => "property",
            Request::UnsetProperty(_, _) => "property",
            Request::PropertyKeys(_, _) => "property",
            Request::SetPermission(_, _, _) => "permission",
            Request::HasPermission(_, _, _) => "permission",
            Request::UnsetPermission(_, _) => "permission",
        };

        Json::String(s.to_string())
    }

    fn get_action_type(&self) -> String {
        let s = match *self {
            Request::Networks | Request::Channels(_) | Request::Nick(_) | Request::Config(_, _) => "get",
            _ => "do",
        };

        s.to_string()
    }
}

/// Implements transforming the request to a Json object that is ready to be sent a DaZeus core.
impl ToJson for Request {
    fn to_json(&self) -> Json {
        let mut obj = Object::new();
        obj.insert(self.get_action_type(), self.get_json_name());

        let mut params = Array::new();

        macro_rules! push_str { ($x: expr) => ( params.push(Json::String($x.clone())) ) }

        match *self {
            Request::Subscribe(EventType::Command(ref cmd)) => {
                push_str!(cmd);
            },
            Request::Unsubscribe(EventType::Command(_)) => {
                // we can't actually unsubscribe a command
                panic!("Cannot unsubscribe from command");
            },
            Request::Subscribe(ref evt) => {
                push_str!(evt.to_string());
            },
            Request::Unsubscribe(ref evt) => {
                push_str!(evt.to_string());
            },
            Request::SubscribeCommand(ref cmd, Some(ref network)) => {
                push_str!(cmd);
                push_str!(network);
            },
            Request::SubscribeCommand(ref cmd, None) => {
                push_str!(cmd);
            },
            Request::Networks => (),
            Request::Channels(ref network)
            | Request::Nick(ref network) => {
                push_str!(network);
            },
            Request::Message(ref network, ref channel, ref message)
            | Request::Notice(ref network, ref channel, ref message)
            | Request::Ctcp(ref network, ref channel, ref message)
            | Request::CtcpReply(ref network, ref channel, ref message)
            | Request::Action(ref network, ref channel, ref message) => {
                push_str!(network);
                push_str!(channel);
                push_str!(message);
            },
            Request::Names(ref network, ref channel)
            | Request::Join(ref network, ref channel)
            | Request::Part(ref network, ref channel) => {
                push_str!(network);
                push_str!(channel);
            },
            Request::Whois(ref network, ref user) => {
                push_str!(network);
                push_str!(user);
            },
            Request::Handshake(ref name, ref version, Some(ref config_name)) => {
                push_str!(name);
                push_str!(version);
                push_str!(PROTOCOL_VERSION.to_string());
                push_str!(config_name);
            },
            Request::Handshake(ref name, ref version, None) => {
                push_str!(name);
                push_str!(version);
                push_str!(PROTOCOL_VERSION.to_string());
                push_str!(name);
            },
            Request::Config(ref key, ref ctype) => {
                push_str!(key);
                push_str!(ctype.to_string());
            },
            Request::GetProperty(ref property, ref scope) => {
                push_str!("get".to_string());
                push_str!(property);
                if !scope.is_any() {
                    obj.insert("scope".to_string(), scope.to_json());
                }
            },
            Request::SetProperty(ref property, ref value, ref scope) => {
                push_str!("set".to_string());
                push_str!(property);
                push_str!(value);
                if !scope.is_any() {
                    obj.insert("scope".to_string(), scope.to_json());
                }
            },
            Request::UnsetProperty(ref property, ref scope) => {
                push_str!("unset".to_string());
                push_str!(property);
                if !scope.is_any() {
                    obj.insert("scope".to_string(), scope.to_json());
                }
            },
            Request::PropertyKeys(ref prefix, ref scope) => {
                push_str!("keys".to_string());
                push_str!(prefix);
                if !scope.is_any() {
                    obj.insert("scope".to_string(), scope.to_json());
                }
            },
            Request::SetPermission(ref permission, ref default, ref scope) => {
                push_str!("set".to_string());
                push_str!(permission);
                params.push(Json::Boolean(*default));
                if !scope.is_any() {
                    obj.insert("scope".to_string(), scope.to_json());
                }
            },
            Request::HasPermission(ref permission, ref default, ref scope) => {
                push_str!("get".to_string());
                push_str!(permission);
                params.push(Json::Boolean(*default));
                if !scope.is_any() {
                    obj.insert("scope".to_string(), scope.to_json());
                }
            },
            Request::UnsetPermission(ref permission, ref scope) => {
                push_str!("unset".to_string());
                push_str!(permission);
                if !scope.is_any() {
                    obj.insert("scope".to_string(), scope.to_json());
                }
            },
        }

        if params.len() > 0 {
            obj.insert("params".to_string(), Json::Array(params));
        }

        Json::Object(obj)
    }
}