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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
use std::io::{Read, Write};
use super::event::{Event, EventType};
use super::handler::{Handler, Message};
use super::listener::{ListenerHandle, Listener};
use super::request::{ConfigGroup, Request};
use super::response::Response;
use super::scope::Scope;
use super::error::{ReceiveError, Error};
use std::cell::RefCell;


/// The base DaZeus struct.
///
/// See the [crate documentation](./index.html) for a more detailed instruction on how to get
/// started with these DaZeus bindings.
pub struct DaZeus<'a, T> {
    handler: RefCell<Handler<T>>,
    listeners: Vec<Listener<'a>>,
    current_handle: u64,
}

impl<'a, T> DaZeus<'a, T> where T: Read + Write {
    /// Create a new instance of DaZeus from the given connection.
    pub fn new(conn: T) -> DaZeus<'a, T> {
        DaZeus {
            handler: RefCell::new(Handler::new(conn)),
            listeners: Vec::new(),
            current_handle: 1
        }
    }

    /// Loop wait for messages to receive in a blocking way.
    pub fn listen(&self) -> Result<(), Error> {
        loop {
            try!(self.try_next_event());
        }
    }

    fn next_response(&self) -> Result<Response, Error> {
        loop {
            let msg = { self.handler.borrow_mut().read() };
            match try!(msg) {
                Message::Event(e) => self.handle_event(e),
                Message::Response(r) => return Ok(r),
            }
        }
    }

    fn try_next_event(&self) -> Result<Event, Error> {
        let msg = { self.handler.borrow_mut().read() };
        match try!(msg) {
            Message::Event(e) => {
                self.handle_event(e.clone());
                Ok(e)
            },
            Message::Response(_) => Err(Error::ReceiveError(ReceiveError::new())),
        }
    }

    fn next_event(&self) -> Event {
        match self.try_next_event() {
            Ok(evt) => evt,
            Err(e) => panic!("{}", e),
        }
    }

    /// Handle an event received by calling all event listeners listening for that event type.
    fn handle_event(&self, event: Event) {
        for listener in self.listeners.iter() {
            if listener.event == event.event {
                listener.call(event.clone(), self);
            }
        }
    }

    /// Subscribe to an event type and call the callback function every time such an event occurs.
    pub fn subscribe<F>(&mut self, event: EventType, callback: F) -> (ListenerHandle, Response)
        where F: FnMut(Event, &DaZeusClient) + 'a
    {
        let request = match event {
            EventType::Command(ref cmd) => Request::SubscribeCommand(cmd.clone(), None),
            _ => Request::Subscribe(event.clone()),
        };

        let handle = self.current_handle;
        self.current_handle += 1;
        let listener = Listener::new(handle, event, callback);

        self.listeners.push(listener);
        (handle, self.send(request))
    }

    /// Subscribe to a command and call the callback function every time such a command occurs.
    pub fn subscribe_command<F>(&mut self, command: &str, callback: F) -> (ListenerHandle, Response)
        where F: FnMut(Event, &DaZeusClient) + 'a
    {
        self.subscribe(EventType::Command(command.to_string()), callback)
    }
}

/// Methods for interaction with the DaZeus server.
pub trait DaZeusClient<'a> {
    /// Try to send a request to DaZeus
    fn try_send(&self, request: Request) -> Result<Response, Error>;

    /// Send a request to DaZeus and retrieve a Future in which the response will be contained.
    fn send(&self, request: Request) -> Response;

    /// Unsubscribe a listener for some event.
    fn unsubscribe(&mut self, handle: ListenerHandle) -> Response;

    /// Remove all subscriptions for a specific event type.
    fn unsubscribe_all(&mut self, event: EventType) -> Response;

    /// Check if there is any active listener for the given event type.
    fn has_any_subscription(&self, event: EventType) -> bool;

    /// Retrieve the networks the bot is connected to.
    fn networks(&self) -> Response;

    /// Retrieve the channels the bot is in for a given network.
    fn channels(&self, network: &str) -> Response;

    /// Send a message to a specific channel using the PRIVMSG method.
    fn message(&self, network: &str, channel: &str, message: &str) -> Response;

    /// Send a CTCP NOTICE to a specific channel.
    fn notice(&self, network: &str, channel: &str, message: &str) -> Response;

    /// Send a CTCP REQUEST to a specific channel.
    fn ctcp(&self, network: &str, channel: &str, message: &str) -> Response;

    /// Send a CTCP REPLY to a specific channel.
    fn ctcp_reply(&self, network: &str, channel: &str, message: &str) -> Response;

    /// Send a CTCP ACTION to a specific channel
    fn action(&self, network: &str, channel: &str, message: &str) -> Response;

    /// Send a request for the list of nicks in a channel.
    ///
    /// Note that the response will not contain the names data, instead listen for a names event.
    /// The Response will only indicate whether or not the request has been submitted successfully.
    /// The server may respond with an `EventType::Names` event any time after this request has
    /// been submitted.
    fn send_names(&self, network: &str, channel: &str) -> Response;

    /// Send a request for a whois of a specific nick on some network.
    ///
    /// Note that the response will not contain the whois data, instead listen for a whois event.
    /// The Response will only indicate whether or not the request has been submitted successfully.
    /// The server may respond with an `EventType::Whois` event any time after this request has
    /// been submitted.
    fn send_whois(&self, network: &str, nick: &str) -> Response;

    /// Try to join a channel on some network.
    fn join(&self, network: &str, channel: &str) -> Response;

    /// Try to leave a channel on some network.
    fn part(&self, network: &str, channel: &str) -> Response;

    /// Retrieve the nickname of the bot on the given network.
    fn nick(&self, network: &str) -> Response;

    /// Send a handshake to the DaZeus core.
    fn handshake(&self, name: &str, version: &str, config: Option<&str>) -> Response;

    /// Retrieve a config value from the DaZeus config.
    fn get_config(&self, name: &str, group: ConfigGroup) -> Response;

    /// Retrieve the character that is used by the bot for highlighting.
    fn get_highlight_char(&self) -> Response;

    /// Retrieve a property stored in the bot database.
    fn get_property(&self, name: &str, scope: Scope) -> Response;

    /// Set a property to be stored in the bot database.
    fn set_property(&self, name: &str, value: &str, scope: Scope) -> Response;

    /// Remove a property stored in the bot database.
    fn unset_property(&self, name: &str, scope: Scope) -> Response;

    /// Retrieve a list of keys starting with the common prefix with the given scope.
    fn get_property_keys(&self, prefix: &str, scope: Scope) -> Response;

    /// Set a permission to either allow or deny for a specific scope.
    fn set_permission(&self, permission: &str, allow: bool, scope: Scope) -> Response;

    /// Retrieve whether for some scope the given permission was set.
    ///
    /// Will return the default if it was not.
    fn has_permission(&self, permission: &str, default: bool, scope: Scope) -> Response;

    /// Remove a set permission from the bot.
    fn unset_permission(&self, permission: &str, scope: Scope) -> Response;

    /// Send a whois request and wait for an event that answers this request (blocking).
    ///
    /// Note that the IRC server may not respond to the whois request (if it has been configured
    /// this way), in which case this request will block forever.
    fn whois(&mut self, network: &str, nick: &str) -> Event;

    /// Send a names request and wait for an event that answers this request (blocking).
    ///
    /// Note that the IRC server may not respond to the names request (if it has been configured
    /// this way), in which case this request will block forever.
    fn names(&mut self, network: &str, channel: &str) -> Event;

    /// Send a reply in response to some event.
    ///
    /// Note that not all types of events can be responded to. Mostly message type events
    /// concerning some IRC user can be responded to. Join events can also be responded to.
    fn reply(&self, event: &Event, message: &str, highlight: bool) -> Response;

    /// Send a reply (as a notice) in response to some event.
    ///
    /// Note that not all types of events can be responded to. Mostly message type events
    /// concerning some IRC user can be responded to. Join events can also be responded to.
    fn reply_with_notice(&self, event: &Event, message: &str) -> Response;

    /// Send a reply (as a ctcp action) in response to some event.
    ///
    /// Note that not all types of events can be responded to. Mostly message type events
    /// concerning some IRC user can be responded to. Join events can also be responded to.
    fn reply_with_action(&self, event: &Event, message: &str) -> Response;
}

impl<'a, T> DaZeusClient<'a> for DaZeus<'a, T> where T: Read + Write {
    /// Try to send a request to DaZeus
    fn try_send(&self, request: Request) -> Result<Response, Error> {
        { try!(self.handler.borrow_mut().write(request)) };
        self.next_response()
    }

    /// Send a request to DaZeus and retrieve a Future in which the response will be contained.
    fn send(&self, request: Request) -> Response {
        match self.try_send(request) {
            Ok(response) => response,
            Err(e) => panic!("{}", e),
        }
    }

    /// Unsubscribe a listener for some event.
    fn unsubscribe(&mut self, handle: ListenerHandle) -> Response {
        // first find the event type
        let event = {
            match self.listeners.iter().find(|&ref l| l.has_handle(handle)) {
                Some(listener) => Some(listener.event.clone()),
                None => None,
            }
        };

        self.listeners.retain(|&ref l| !l.has_handle(handle));
        match event {
            // we can't unsubscribe commands
            Some(EventType::Command(_)) => Response::for_success(),

            // unsubscribe if there are no more listeners for the event
            Some(evt) => match self.listeners.iter().any(|&ref l| l.event == evt) {
                false => self.send(Request::Unsubscribe(evt)),
                true => Response::for_success(),
            },

            None => Response::for_fail("Could not find listener with given handle"),
        }
    }

    /// Remove all subscriptions for a specific event type.
    fn unsubscribe_all(&mut self, event: EventType) -> Response {
        self.listeners.retain(|&ref l| l.event != event);
        match event {
            EventType::Command(_) => Response::for_success(),
            _ => self.send(Request::Unsubscribe(event)),
        }
    }

    /// Check if there is any active listener for the given event type.
    fn has_any_subscription(&self, event: EventType) -> bool {
        self.listeners.iter().any(|&ref l| l.event == event)
    }

    /// Retrieve the networks the bot is connected to.
    fn networks(&self) -> Response {
        self.send(Request::Networks)
    }

    /// Retrieve the channels the bot is in for a given network.
    fn channels(&self, network: &str) -> Response {
        self.send(Request::Channels(network.to_string()))
    }

    /// Send a message to a specific channel using the PRIVMSG method.
    fn message(&self, network: &str, channel: &str, message: &str) -> Response {
        self.send(Request::Message(
            network.to_string(),
            channel.to_string(),
            message.to_string()
        ))
    }

    /// Send a CTCP NOTICE to a specific channel.
    fn notice(&self, network: &str, channel: &str, message: &str) -> Response {
        self.send(Request::Notice(
            network.to_string(),
            channel.to_string(),
            message.to_string()
        ))
    }

    /// Send a CTCP REQUEST to a specific channel.
    fn ctcp(&self, network: &str, channel: &str, message: &str) -> Response {
        self.send(Request::Ctcp(
            network.to_string(),
            channel.to_string(),
            message.to_string()
        ))
    }

    /// Send a CTCP REPLY to a specific channel.
    fn ctcp_reply(&self, network: &str, channel: &str, message: &str) -> Response {
        self.send(Request::CtcpReply(
            network.to_string(),
            channel.to_string(),
            message.to_string()
        ))
    }

    /// Send a CTCP ACTION to a specific channel
    fn action(&self, network: &str, channel: &str, message: &str) -> Response {
        self.send(Request::Action(
            network.to_string(),
            channel.to_string(),
            message.to_string()
        ))
    }

    /// Send a request for the list of nicks in a channel.
    ///
    /// Note that the response will not contain the names data, instead listen for a names event.
    /// The Response will only indicate whether or not the request has been submitted successfully.
    /// The server may respond with an `EventType::Names` event any time after this request has
    /// been submitted.
    fn send_names(&self, network: &str, channel: &str) -> Response {
        self.send(Request::Names(network.to_string(), channel.to_string()))
    }

    /// Send a request for a whois of a specific nick on some network.
    ///
    /// Note that the response will not contain the whois data, instead listen for a whois event.
    /// The Response will only indicate whether or not the request has been submitted successfully.
    /// The server may respond with an `EventType::Whois` event any time after this request has
    /// been submitted.
    fn send_whois(&self, network: &str, nick: &str) -> Response {
        self.send(Request::Whois(network.to_string(), nick.to_string()))
    }

    /// Try to join a channel on some network.
    fn join(&self, network: &str, channel: &str) -> Response {
        self.send(Request::Join(network.to_string(), channel.to_string()))
    }

    /// Try to leave a channel on some network.
    fn part(&self, network: &str, channel: &str) -> Response {
        self.send(Request::Part(network.to_string(), channel.to_string()))
    }

    /// Retrieve the nickname of the bot on the given network.
    fn nick(&self, network: &str) -> Response {
        self.send(Request::Nick(network.to_string()))
    }

    /// Send a handshake to the DaZeus core.
    fn handshake(&self, name: &str, version: &str, config: Option<&str>) -> Response {
        let n = name.to_string();
        let v = version.to_string();
        let req = match config {
            Some(config_name) => Request::Handshake(n, v, Some(config_name.to_string())),
            None => Request::Handshake(n, v, None),
        };
        self.send(req)
    }

    /// Retrieve a config value from the DaZeus config.
    fn get_config(&self, name: &str, group: ConfigGroup) -> Response {
        self.send(Request::Config(name.to_string(), group))
    }

    /// Retrieve the character that is used by the bot for highlighting.
    fn get_highlight_char(&self) -> Response {
        self.get_config("highlight", ConfigGroup::Core)
    }

    /// Retrieve a property stored in the bot database.
    fn get_property(&self, name: &str, scope: Scope) -> Response {
        self.send(Request::GetProperty(name.to_string(), scope))
    }

    /// Set a property to be stored in the bot database.
    fn set_property(&self, name: &str, value: &str, scope: Scope) -> Response {
        self.send(Request::SetProperty(name.to_string(), value.to_string(), scope))
    }

    /// Remove a property stored in the bot database.
    fn unset_property(&self, name: &str, scope: Scope) -> Response {
        self.send(Request::UnsetProperty(name.to_string(), scope))
    }

    /// Retrieve a list of keys starting with the common prefix with the given scope.
    fn get_property_keys(&self, prefix: &str, scope: Scope) -> Response {
        self.send(Request::PropertyKeys(prefix.to_string(), scope))
    }

    /// Set a permission to either allow or deny for a specific scope.
    fn set_permission(&self, permission: &str, allow: bool, scope: Scope) -> Response {
        self.send(Request::SetPermission(permission.to_string(), allow, scope))
    }

    /// Retrieve whether for some scope the given permission was set.
    ///
    /// Will return the default if it was not.
    fn has_permission(&self, permission: &str, default: bool, scope: Scope) -> Response {
        self.send(Request::HasPermission(permission.to_string(), default, scope))
    }

    /// Remove a set permission from the bot.
    fn unset_permission(&self, permission: &str, scope: Scope) -> Response {
        self.send(Request::UnsetPermission(permission.to_string(), scope))
    }

    /// Send a whois request and wait for an event that answers this request (blocking).
    ///
    /// Note that the IRC server may not respond to the whois request (if it has been configured
    /// this way), in which case this request will block forever.
    fn whois(&mut self, network: &str, nick: &str) -> Event {
        if !self.has_any_subscription(EventType::Whois) {
            self.send(Request::Subscribe(EventType::Whois));
        }
        self.send_whois(network, nick);

        loop {
            let evt = self.next_event();
            match evt.event {
                EventType::Whois if &evt[0] == network && &evt[2] == nick => {
                    if !self.has_any_subscription(EventType::Whois) {
                        self.send(Request::Unsubscribe(EventType::Whois));
                    }
                    return evt;
                },
                _ => (),
            }
        }
    }

    /// Send a names request and wait for an event that answers this request (blocking).
    ///
    /// Note that the IRC server may not respond to the names request (if it has been configured
    /// this way), in which case this request will block forever.
    fn names(&mut self, network: &str, channel: &str) -> Event {
        if !self.has_any_subscription(EventType::Names) {
            self.send(Request::Subscribe(EventType::Names));
        }
        self.send_names(network, channel);

        loop {
            let evt = self.next_event();
            match evt.event {
                EventType::Names if &evt[0] == network && &evt[2] == channel => {
                    if !self.has_any_subscription(EventType::Names) {
                        self.send(Request::Unsubscribe(EventType::Names));
                    }
                    return evt;
                },
                _ => (),
            }
        }
    }

    /// Send a reply in response to some event.
    ///
    /// Note that not all types of events can be responded to. Mostly message type events
    /// concerning some IRC user can be responded to. Join events can also be responded to.
    fn reply(&self, event: &Event, message: &str, highlight: bool) -> Response {
        if let Some((network, channel, user)) = targets_for_event(event) {
            let resp = self.nick(network);
            let nick = resp.get_str_or("nick", "");
            if channel == nick {
                self.message(network, user, message)
            } else {
                if highlight {
                    let msg = format!("{}: {}", user, message);
                    self.message(network, channel, &msg[..])
                } else {
                    self.message(network, channel, message)
                }
            }
        } else {
            Response::for_fail("Not an event to reply to")
        }
    }

    /// Send a reply (as a notice) in response to some event.
    ///
    /// Note that not all types of events can be responded to. Mostly message type events
    /// concerning some IRC user can be responded to. Join events can also be responded to.
    fn reply_with_notice(&self, event: &Event, message: &str) -> Response {
        if let Some((network, channel, user)) = targets_for_event(event) {
            let resp = self.nick(network);
            let nick = resp.get_str_or("nick", "");
            if channel == nick {
                self.notice(network, user, message)
            } else {
                self.notice(network, channel, message)
            }
        } else {
            Response::for_fail("Not an event to reply to")
        }
    }

    /// Send a reply (as a ctcp action) in response to some event.
    ///
    /// Note that not all types of events can be responded to. Mostly message type events
    /// concerning some IRC user can be responded to. Join events can also be responded to.
    fn reply_with_action(&self, event: &Event, message: &str) -> Response {
        if let Some((network, channel, user)) = targets_for_event(event) {
            let resp = self.nick(network);
            let nick = resp.get_str_or("nick", "");
            if channel == nick {
                self.action(network, user, message)
            } else {
                self.action(network, channel, message)
            }
        } else {
            Response::for_fail("Not an event to reply to")
        }
    }
}

fn targets_for_event(event: &Event) -> Option<(&str, &str, &str)> {
    let params = &event.params;
    match event.event {
        EventType::Join
        | EventType::PrivMsg
        | EventType::Notice
        | EventType::Ctcp
        | EventType::Command(_)
        | EventType::Action => Some((&params[0][..], &params[2][..], &params[1][..])),
        _ => None,
    }
}