262383b4567929d8959b194ee9ce6b4a526d2def
[KiwiIRC.git] / client / assets / dev / model_application.js
1 _kiwi.model.Application = function () {
2 // Set to a reference to this object within initialize()
3 var that = null;
4
5 // The auto connect details entered into the server select box
6 var auto_connect_details = {};
7
8
9 var model = function () {
10 /** Instance of _kiwi.model.PanelList */
11 this.panels = null;
12
13 /** _kiwi.view.Application */
14 this.view = null;
15
16 /** _kiwi.view.StatusMessage */
17 this.message = null;
18
19 /* Address for the kiwi server */
20 this.kiwi_server = null;
21
22 this.initialize = function (options) {
23 that = this;
24
25 if (options[0].container) {
26 this.set('container', options[0].container);
27 }
28
29 // The base url to the kiwi server
30 this.set('base_path', options[0].base_path ? options[0].base_path : '/kiwi');
31
32 // Any options sent down from the server
33 this.server_settings = options[0].server_settings || {};
34
35 // Best guess at where the kiwi server is
36 this.detectKiwiServer();
37 };
38
39 this.start = function () {
40 // Only debug if set in the querystring
41 if (!getQueryVariable('debug')) {
42 manageDebug(false);
43 } else {
44 //manageDebug(true);
45 }
46
47 // Set the gateway up
48 _kiwi.gateway = new _kiwi.model.Gateway();
49 this.bindGatewayCommands(_kiwi.gateway);
50
51 this.initializeClient();
52 this.initializeGlobals();
53
54 this.view.barsHide(true);
55
56 this.panels.server.server_login.bind('server_connect', function (event) {
57 var server_login = this,
58 transport_path = '';
59 auto_connect_details = event;
60
61 server_login.networkConnecting();
62
63 // Path to get the socket.io transport code
64 transport_path = that.kiwi_server + that.get('base_path') + '/transport/socket.io.js?ts='+(new Date().getTime());
65
66 $script(transport_path, function () {
67 if (!window.io) {
68 kiwiServerNotFound();
69 return;
70 }
71 _kiwi.gateway.set('kiwi_server', that.kiwi_server + '/kiwi');
72 _kiwi.gateway.set('nick', event.nick);
73
74 _kiwi.gateway.connect(event.server, event.port, event.ssl, event.password, function (error) {
75 if (error) {
76 kiwiServerNotFound();
77 }
78 });
79 });
80 });
81
82 // TODO: Shouldn't really be here but it's not working in the view.. :/
83 // Hack for firefox browers: Focus is not given on this event loop iteration
84 setTimeout(function(){
85 _kiwi.app.panels.server.server_login.$el.find('.nick').select();
86 }, 0);
87 };
88
89
90 function kiwiServerNotFound (e) {
91 that.panels.server.server_login.showError();
92 }
93
94
95 this.detectKiwiServer = function () {
96 // If running from file, default to localhost:7777 by default
97 if (window.location.protocol === 'file:') {
98 this.kiwi_server = 'http://localhost:7778';
99 } else {
100 // Assume the kiwi server is on the same server
101 this.kiwi_server = window.location.protocol + '//' + window.location.host;
102 }
103 };
104
105
106 this.initializeClient = function () {
107 this.view = new _kiwi.view.Application({model: this, el: this.get('container')});
108
109 /**
110 * Set the UI components up
111 */
112 this.panels = new _kiwi.model.PanelList();
113
114 this.controlbox = new _kiwi.view.ControlBox({el: $('#controlbox')[0]});
115 this.bindControllboxCommands(this.controlbox);
116
117 this.topicbar = new _kiwi.view.TopicBar({el: $('#topic')[0]});
118
119 new _kiwi.view.AppToolbar({el: $('#toolbar .app_tools')[0]});
120
121 this.message = new _kiwi.view.StatusMessage({el: $('#status_message')[0]});
122
123 this.resize_handle = new _kiwi.view.ResizeHandler({el: $('#memberlists_resize_handle')[0]});
124
125 this.panels.server.view.show();
126
127 // Rejigg the UI sizes
128 this.view.doLayout();
129
130 this.populateDefaultServerSettings();
131 };
132
133
134 this.initializeGlobals = function () {
135 _kiwi.global.control = this.controlbox;
136 _kiwi.global.gateway = _kiwi.gateway;
137 _kiwi.global.panels = this.panels;
138
139 _kiwi.global.components = {
140 Applet: _kiwi.model.Applet,
141 Panel: _kiwi.model.Panel
142 };
143 };
144
145
146 this.populateDefaultServerSettings = function () {
147 var parts;
148 var defaults = {
149 nick: getQueryVariable('nick') || 'kiwi_' + Math.ceil(Math.random() * 10000).toString(),
150 server: 'irc.kiwiirc.com',
151 port: 6667,
152 ssl: false,
153 channel: window.location.hash || '#kiwiirc',
154 channel_key: ''
155 };
156 var uricheck;
157
158 // Process the URL part by part, extracting as we go
159 parts = window.location.pathname.toString().replace(this.get('base_path'), '').split('/');
160
161 if (parts.length > 0) {
162 parts.shift();
163
164 if (parts.length > 0 && parts[0]) {
165 // Check to see if we're dealing with an irc: uri, or whether we need to extract the server/channel info from the HTTP URL path.
166 uricheck = parts[0].substr(0, 7).toLowerCase();
167 if ((uricheck === 'ircs%3a') || (uricheck.substr(0,6) === 'irc%3a')) {
168 parts[0] = decodeURIComponent(parts[0]);
169 // irc[s]://<host>[:<port>]/[<channel>[?<password>]]
170 uricheck = /^irc(s)?:(?:\/\/?)?([^:\/]+)(?::([0-9]+))?(?:(?:\/)([^\?]*)(?:(?:\?)(.*))?)?$/.exec(parts[0]);
171 /*
172 uricheck[1] = ssl (optional)
173 uricheck[2] = host
174 uricheck[3] = port (optional)
175 uricheck[4] = channel (optional)
176 uricheck[5] = channel key (optional, channel must also be set)
177 */
178 if (uricheck) {
179 if (typeof uricheck[1] !== 'undefined') {
180 defaults.ssl = true;
181 if (defaults.port === 6667) {
182 defaults.port = 6697;
183 }
184 }
185 defaults.server = uricheck[2];
186 if (typeof uricheck[3] !== 'undefined') {
187 defaults.port = uricheck[3];
188 }
189 if (typeof uricheck[4] !== 'undefined') {
190 defaults.channel = '#' + uricheck[4];
191 if (typeof uricheck[5] !== 'undefined') {
192 defaults.channel_key = uricheck[5];
193 }
194 }
195 }
196 parts = [];
197 } else {
198 // Extract the port+ssl if we find one
199 if (parts[0].search(/:/) > 0) {
200 defaults.port = parts[0].substring(parts[0].search(/:/) + 1);
201 defaults.server = parts[0].substring(0, parts[0].search(/:/));
202 if (defaults.port[0] === '+') {
203 defaults.port = parseInt(defaults.port.substring(1), 10);
204 defaults.ssl = true;
205 } else {
206 defaults.ssl = false;
207 }
208
209 } else {
210 defaults.server = parts[0];
211 }
212
213 parts.shift();
214 }
215 }
216
217 if (parts.length > 0 && parts[0]) {
218 defaults.channel = '#' + parts[0];
219 parts.shift();
220 }
221 }
222
223 // If any settings have been given by the server.. override any auto detected settings
224 if (this.server_settings && this.server_settings.connection) {
225 if (this.server_settings.connection.server) {
226 defaults.server = this.server_settings.connection.server;
227 }
228
229 if (this.server_settings.connection.port) {
230 defaults.port = this.server_settings.connection.port;
231 }
232
233 if (this.server_settings.connection.ssl) {
234 defaults.ssl = this.server_settings.connection.ssl;
235 }
236
237 if (this.server_settings.connection.channel) {
238 defaults.channel = this.server_settings.connection.channel;
239 }
240
241 if (this.server_settings.connection.nick) {
242 defaults.nick = this.server_settings.connection.nick;
243 }
244 }
245
246 // Set any random numbers if needed
247 defaults.nick = defaults.nick.replace('?', Math.floor(Math.random() * 100000).toString());
248
249 // Populate the server select box with defaults
250 this.panels.server.server_login.populateFields(defaults);
251 };
252
253
254 this.bindGatewayCommands = function (gw) {
255 gw.on('onmotd', function (event) {
256 that.panels.server.addMsg(_kiwi.gateway.get('name'), event.msg, 'motd');
257 });
258
259
260 gw.on('onconnect', function (event) {
261 that.view.barsShow();
262
263 if (auto_connect_details.channel) {
264 that.controlbox.processInput('/JOIN ' + auto_connect_details.channel + ' ' + auto_connect_details.channel_key);
265 }
266 });
267
268
269 (function () {
270 var gw_stat = 0;
271
272 gw.on('disconnect', function (event) {
273 var msg = 'You have been disconnected. Attempting to reconnect for you..';
274 that.message.text(msg, {timeout: 10000});
275
276 // Mention the disconnection on every channel
277 $.each(_kiwi.app.panels.models, function (idx, panel) {
278 if (!panel || !panel.isChannel()) return;
279 panel.addMsg('', msg, 'action quit');
280 });
281 _kiwi.app.panels.server.addMsg('', msg, 'action quit');
282
283 gw_stat = 1;
284 });
285 gw.on('reconnecting', function (event) {
286 msg = 'You have been disconnected. Attempting to reconnect again in ' + (event.delay/1000) + ' seconds..';
287 _kiwi.app.panels.server.addMsg('', msg, 'action quit');
288 });
289 gw.on('connect', function (event) {
290 if (gw_stat !== 1) return;
291
292 var msg = 'It\'s OK, you\'re connected again :)';
293 that.message.text(msg, {timeout: 5000});
294
295 // Mention the disconnection on every channel
296 $.each(_kiwi.app.panels.models, function (idx, panel) {
297 if (!panel || !panel.isChannel()) return;
298 panel.addMsg('', msg, 'action join');
299 });
300 _kiwi.app.panels.server.addMsg('', msg, 'action join');
301
302 gw_stat = 0;
303 });
304 })();
305
306
307 gw.on('onjoin', function (event) {
308 var c, members, user;
309 c = that.panels.getByName(event.channel);
310 if (!c) {
311 c = new _kiwi.model.Channel({name: event.channel});
312 that.panels.add(c);
313 }
314
315 members = c.get('members');
316 if (!members) return;
317
318 user = new _kiwi.model.Member({nick: event.nick, ident: event.ident, hostname: event.hostname});
319 members.add(user);
320 // TODO: highlight the new channel in some way
321 });
322
323
324 gw.on('onpart', function (event) {
325 var channel, members, user,
326 part_options = {};
327
328 part_options.type = 'part';
329 part_options.message = event.message || '';
330
331 channel = that.panels.getByName(event.channel);
332 if (!channel) return;
333
334 // If this is us, close the panel
335 if (event.nick === _kiwi.gateway.get('nick')) {
336 channel.close();
337 return;
338 }
339
340 members = channel.get('members');
341 if (!members) return;
342
343 user = members.getByNick(event.nick);
344 if (!user) return;
345
346 members.remove(user, part_options);
347 });
348
349
350 gw.on('onquit', function (event) {
351 var member, members,
352 quit_options = {};
353
354 quit_options.type = 'quit';
355 quit_options.message = event.message || '';
356
357 $.each(that.panels.models, function (index, panel) {
358 if (!panel.isChannel()) return;
359
360 member = panel.get('members').getByNick(event.nick);
361 if (member) {
362 panel.get('members').remove(member, quit_options);
363 }
364 });
365 });
366
367
368 gw.on('onkick', function (event) {
369 var channel, members, user,
370 part_options = {};
371
372 part_options.type = 'kick';
373 part_options.by = event.nick;
374 part_options.message = event.message || '';
375
376 channel = that.panels.getByName(event.channel);
377 if (!channel) return;
378
379 members = channel.get('members');
380 if (!members) return;
381
382 user = members.getByNick(event.kicked);
383 if (!user) return;
384
385 members.remove(user, part_options);
386
387 if (event.kicked === _kiwi.gateway.get('nick')) {
388 members.reset([]);
389 }
390
391 });
392
393
394 gw.on('onmsg', function (event) {
395 var panel,
396 is_pm = (event.channel == _kiwi.gateway.get('nick'));
397
398 if (is_pm) {
399 // If a panel isn't found for this PM, create one
400 panel = that.panels.getByName(event.nick);
401 if (!panel) {
402 panel = new _kiwi.model.Query({name: event.nick});
403 that.panels.add(panel);
404 }
405
406 } else {
407 // If a panel isn't found for this channel, reroute to the
408 // server panel
409 panel = that.panels.getByName(event.channel);
410 if (!panel) {
411 panel = that.panels.server;
412 }
413 }
414
415 panel.addMsg(event.nick, event.msg);
416 });
417
418
419 gw.on('onnotice', function (event) {
420 var panel;
421
422 // Find a panel for the destination(channel) or who its from
423 panel = that.panels.getByName(event.target) || that.panels.getByName(event.nick);
424 if (!panel) {
425 panel = that.panels.server;
426 }
427
428 panel.addMsg('[' + (event.nick||'') + ']', event.msg);
429 });
430
431
432 gw.on('onaction', function (event) {
433 var panel,
434 is_pm = (event.channel == _kiwi.gateway.get('nick'));
435
436 if (is_pm) {
437 // If a panel isn't found for this PM, create one
438 panel = that.panels.getByName(event.nick);
439 if (!panel) {
440 panel = new _kiwi.model.Channel({name: event.nick});
441 that.panels.add(panel);
442 }
443
444 } else {
445 // If a panel isn't found for this channel, reroute to the
446 // server panel
447 panel = that.panels.getByName(event.channel);
448 if (!panel) {
449 panel = that.panels.server;
450 }
451 }
452
453 panel.addMsg('', '* ' + event.nick + ' ' + event.msg, 'action');
454 });
455
456
457 gw.on('ontopic', function (event) {
458 var c;
459 c = that.panels.getByName(event.channel);
460 if (!c) return;
461
462 // Set the channels topic
463 c.set('topic', event.topic);
464
465 // If this is the active channel, update the topic bar too
466 if (c.get('name') === _kiwi.app.panels.active.get('name')) {
467 that.topicbar.setCurrentTopic(event.topic);
468 }
469 });
470
471
472 gw.on('ontopicsetby', function (event) {
473 var c, when;
474 c = that.panels.getByName(event.channel);
475 if (!c) return;
476
477 when = formatDate(new Date(event.when * 1000));
478 c.addMsg('', 'Topic set by ' + event.nick + ' at ' + when, 'topic');
479 });
480
481
482 gw.on('onuserlist', function (event) {
483 var channel;
484 channel = that.panels.getByName(event.channel);
485
486 // If we didn't find a channel for this, may aswell leave
487 if (!channel) return;
488
489 channel.temp_userlist = channel.temp_userlist || [];
490 _.each(event.users, function (item) {
491 var user = new _kiwi.model.Member({nick: item.nick, modes: item.modes});
492 channel.temp_userlist.push(user);
493 });
494 });
495
496
497 gw.on('onuserlist_end', function (event) {
498 var channel;
499 channel = that.panels.getByName(event.channel);
500
501 // If we didn't find a channel for this, may aswell leave
502 if (!channel) return;
503
504 // Update the members list with the new list
505 channel.get('members').reset(channel.temp_userlist || []);
506
507 // Clear the temporary userlist
508 delete channel.temp_userlist;
509 });
510
511
512 gw.on('onmode', function (event) {
513 var channel, i, prefixes, members, member, find_prefix;
514
515 // Build a nicely formatted string to be displayed to a regular human
516 function friendlyModeString (event_modes, alt_target) {
517 var modes = {}, return_string;
518
519 // If no default given, use the main event info
520 if (!event_modes) {
521 event_modes = event.modes;
522 alt_target = event.target;
523 }
524
525 // Reformat the mode object to make it easier to work with
526 _.each(event_modes, function (mode){
527 var param = mode.param || alt_target || '';
528
529 // Make sure we have some modes for this param
530 if (!modes[param]) {
531 modes[param] = {'+':'', '-':''};
532 }
533
534 modes[param][mode.mode[0]] += mode.mode.substr(1);
535 });
536
537 // Put the string together from each mode
538 return_string = [];
539 _.each(modes, function (modeset, param) {
540 var str = '';
541 if (modeset['+']) str += '+' + modeset['+'];
542 if (modeset['-']) str += '-' + modeset['-'];
543 return_string.push(str + ' ' + param);
544 });
545 return_string = return_string.join(', ');
546
547 return return_string;
548 }
549
550
551 channel = that.panels.getByName(event.target);
552 if (channel) {
553 prefixes = _kiwi.gateway.get('user_prefixes');
554 find_prefix = function (p) {
555 return event.modes[i].mode[1] === p.mode;
556 };
557 for (i = 0; i < event.modes.length; i++) {
558 if (_.any(prefixes, find_prefix)) {
559 if (!members) {
560 members = channel.get('members');
561 }
562 member = members.getByNick(event.modes[i].param);
563 if (!member) {
564 console.log('MODE command recieved for unknown member %s on channel %s', event.modes[i].param, event.target);
565 return;
566 } else {
567 if (event.modes[i].mode[0] === '+') {
568 member.addMode(event.modes[i].mode[1]);
569 } else if (event.modes[i].mode[0] === '-') {
570 member.removeMode(event.modes[i].mode[1]);
571 }
572 members.sort();
573 //channel.addMsg('', '== ' + event.nick + ' set mode ' + event.modes[i].mode + ' ' + event.modes[i].param, 'action mode');
574 }
575 } else {
576 // Channel mode being set
577 // TODO: Store this somewhere?
578 //channel.addMsg('', 'CHANNEL === ' + event.nick + ' set mode ' + event.modes[i].mode + ' on ' + event.target, 'action mode');
579 }
580 }
581
582 channel.addMsg('', '== ' + event.nick + ' sets mode ' + friendlyModeString(), 'action mode');
583 } else {
584 // This is probably a mode being set on us.
585 if (event.target.toLowerCase() === _kiwi.gateway.get("nick").toLowerCase()) {
586 that.panels.server.addMsg('', '== ' + event.nick + ' set mode ' + friendlyModeString(), 'action mode');
587 } else {
588 console.log('MODE command recieved for unknown target %s: ', event.target, event);
589 }
590 }
591 });
592
593
594 gw.on('onnick', function (event) {
595 var member;
596
597 $.each(that.panels.models, function (index, panel) {
598 if (!panel.isChannel()) return;
599
600 member = panel.get('members').getByNick(event.nick);
601 if (member) {
602 member.set('nick', event.newnick);
603 panel.addMsg('', '== ' + event.nick + ' is now known as ' + event.newnick, 'action nick');
604 }
605 });
606 });
607
608
609 gw.on('onwhois', function (event) {
610 /*globals secondsToTime */
611 var logon_date, idle_time = '', panel;
612
613 if (event.end) {
614 return;
615 }
616
617 if (typeof event.idle !== 'undefined') {
618 idle_time = secondsToTime(parseInt(event.idle, 10));
619 idle_time = idle_time.h.toString().lpad(2, "0") + ':' + idle_time.m.toString().lpad(2, "0") + ':' + idle_time.s.toString().lpad(2, "0");
620 }
621
622 panel = _kiwi.app.panels.active;
623 if (event.ident) {
624 panel.addMsg(event.nick, 'is ' + event.nick + '!' + event.ident + '@' + event.host + ' * ' + event.msg, 'whois');
625 } else if (event.chans) {
626 panel.addMsg(event.nick, 'on ' + event.chans, 'whois');
627 } else if (event.irc_server) {
628 panel.addMsg(event.nick, 'using ' + event.server, 'whois');
629 } else if (event.msg) {
630 panel.addMsg(event.nick, event.msg, 'whois');
631 } else if (event.logon) {
632 logon_date = new Date();
633 logon_date.setTime(event.logon * 1000);
634 logon_date = formatDate(logon_date);
635
636 panel.addMsg(event.nick, 'idle for ' + idle_time + ', signed on ' + logon_date, 'whois');
637 } else {
638 panel.addMsg(event.nick, 'idle for ' + idle_time, 'whois');
639 }
640 });
641
642 gw.on('onaway', function (event) {
643 $.each(that.panels.models, function (index, panel) {
644 if (!panel.isChannel()) return;
645
646 member = panel.get('members').getByNick(event.nick);
647 if (member) {
648 member.set('away', !(!event.trailing));
649 }
650 });
651 });
652
653
654 gw.on('onlist_start', function (data) {
655 if (_kiwi.app.channel_list) {
656 _kiwi.app.channel_list.close();
657 delete _kiwi.app.channel_list;
658 }
659
660 var panel = new _kiwi.model.Applet(),
661 applet = new _kiwi.applets.Chanlist();
662
663 panel.load(applet);
664
665 _kiwi.app.panels.add(panel);
666 panel.view.show();
667
668 _kiwi.app.channel_list = applet;
669 });
670
671
672 gw.on('onlist_channel', function (data) {
673 // TODO: Put this listener within the applet itself
674 _kiwi.app.channel_list.addChannel(data.chans);
675 });
676
677
678 gw.on('onlist_end', function (data) {
679 // TODO: Put this listener within the applet itself
680 delete _kiwi.app.channel_list;
681 });
682
683
684 gw.on('onirc_error', function (data) {
685 var panel, tmp;
686
687 if (data.channel !== undefined && !(panel = _kiwi.app.panels.getByName(data.channel))) {
688 panel = _kiwi.app.panels.server;
689 }
690
691 switch (data.error) {
692 case 'banned_from_channel':
693 panel.addMsg(' ', '== You are banned from ' + data.channel + '. ' + data.reason, 'status');
694 _kiwi.app.message.text('You are banned from ' + data.channel + '. ' + data.reason);
695 break;
696 case 'bad_channel_key':
697 panel.addMsg(' ', '== Bad channel key for ' + data.channel, 'status');
698 _kiwi.app.message.text('Bad channel key or password for ' + data.channel);
699 break;
700 case 'invite_only_channel':
701 panel.addMsg(' ', '== ' + data.channel + ' is invite only.', 'status');
702 _kiwi.app.message.text(data.channel + ' is invite only');
703 break;
704 case 'channel_is_full':
705 panel.addMsg(' ', '== ' + data.channel + ' is full.', 'status');
706 _kiwi.app.message.text(data.channel + ' is full');
707 break;
708 case 'chanop_privs_needed':
709 panel.addMsg(' ', '== ' + data.reason, 'status');
710 _kiwi.app.message.text(data.reason + ' (' + data.channel + ')');
711 break;
712 case 'no_such_nick':
713 tmp = _kiwi.app.panels.getByName(data.nick);
714 if (tmp) {
715 tmp.addMsg(' ', '== ' + data.nick + ': ' + data.reason, 'status');
716 } else {
717 _kiwi.app.panels.server.addMsg(' ', '== ' + data.nick + ': ' + data.reason, 'status');
718 }
719 break;
720 case 'nickname_in_use':
721 _kiwi.app.panels.server.addMsg(' ', '== The nickname ' + data.nick + ' is already in use. Please select a new nickname', 'status');
722 if (_kiwi.app.panels.server !== _kiwi.app.panels.active) {
723 _kiwi.app.message.text('The nickname "' + data.nick + '" is already in use. Please select a new nickname');
724 }
725
726 // Only show the nickchange component if the controlbox is open
727 if (that.controlbox.$el.css('display') !== 'none') {
728 (new _kiwi.view.NickChangeBox()).render();
729 }
730
731 break;
732 default:
733 // We don't know what data contains, so don't do anything with it.
734 //_kiwi.front.tabviews.server.addMsg(null, ' ', '== ' + data, 'status');
735 }
736 });
737 };
738
739
740
741 /**
742 * Bind to certain commands that may be typed into the control box
743 */
744 this.bindControllboxCommands = function (controlbox) {
745 // Default aliases
746 $.extend(controlbox.preprocessor.aliases, {
747 // General aliases
748 '/p': '/part $1+',
749 '/me': '/action $1+',
750 '/j': '/join $1+',
751 '/q': '/query $1+',
752
753 // Op related aliases
754 '/op': '/quote mode $channel +o $1+',
755 '/deop': '/quote mode $channel -o $1+',
756 '/hop': '/quote mode $channel +h $1+',
757 '/dehop': '/quote mode $channel -h $1+',
758 '/voice': '/quote mode $channel +v $1+',
759 '/devoice': '/quote mode $channel -v $1+',
760 '/k': '/kick $channel $1+',
761
762 // Misc aliases
763 '/slap': '/me slaps $1 around a bit with a large trout'
764 });
765
766 controlbox.on('unknown_command', unknownCommand);
767
768 controlbox.on('command', allCommands);
769 controlbox.on('command_msg', msgCommand);
770
771 controlbox.on('command_action', actionCommand);
772
773 controlbox.on('command_join', joinCommand);
774
775 controlbox.on('command_part', partCommand);
776
777 controlbox.on('command_nick', function (ev) {
778 _kiwi.gateway.changeNick(ev.params[0]);
779 });
780
781 controlbox.on('command_query', queryCommand);
782
783 controlbox.on('command_topic', topicCommand);
784
785 controlbox.on('command_notice', noticeCommand);
786
787 controlbox.on('command_quote', quoteCommand);
788
789 controlbox.on('command_kick', kickCommand);
790
791
792 controlbox.on('command_css', function (ev) {
793 var queryString = '?reload=' + new Date().getTime();
794 $('link[rel="stylesheet"]').each(function () {
795 this.href = this.href.replace(/\?.*|$/, queryString);
796 });
797 });
798
799 controlbox.on('command_js', function (ev) {
800 if (!ev.params[0]) return;
801 $script(ev.params[0] + '?' + (new Date().getTime()));
802 });
803
804
805 controlbox.on('command_set', function (ev) {
806 if (!ev.params[0]) return;
807
808 var setting = ev.params[0],
809 value;
810
811 // Do we have a second param to set a value?
812 if (ev.params[1]) {
813 ev.params.shift();
814
815 value = ev.params.join(' ');
816 _kiwi.global.settings.set(setting, value);
817 }
818
819 // Read the value to the user
820 _kiwi.app.panels.active.addMsg('', setting + ' = ' + _kiwi.global.settings.get(setting));
821 });
822
823
824 controlbox.on('command_save', function (ev) {
825 _kiwi.global.settings.save();
826 _kiwi.app.panels.active.addMsg('', 'Settings have been saved');
827 });
828
829
830 controlbox.on('command_alias', function (ev) {
831 var name, rule;
832
833 // No parameters passed so list them
834 if (!ev.params[1]) {
835 $.each(controlbox.preprocessor.aliases, function (name, rule) {
836 _kiwi.app.panels.server.addMsg(' ', name + ' => ' + rule);
837 });
838 return;
839 }
840
841 // Deleting an alias?
842 if (ev.params[0] === 'del' || ev.params[0] === 'delete') {
843 name = ev.params[1];
844 if (name[0] !== '/') name = '/' + name;
845 delete controlbox.preprocessor.aliases[name];
846 return;
847 }
848
849 // Add the alias
850 name = ev.params[0];
851 ev.params.shift();
852 rule = ev.params.join(' ');
853
854 // Make sure the name starts with a slash
855 if (name[0] !== '/') name = '/' + name;
856
857 // Now actually add the alias
858 controlbox.preprocessor.aliases[name] = rule;
859 });
860
861 controlbox.on('command_applet', appletCommand);
862 controlbox.on('command_settings', settingsCommand);
863 };
864
865 // A fallback action. Send a raw command to the server
866 function unknownCommand (ev) {
867 var raw_cmd = ev.command + ' ' + ev.params.join(' ');
868 console.log('RAW: ' + raw_cmd);
869 _kiwi.gateway.raw(raw_cmd);
870 }
871
872 function allCommands (ev) {}
873
874 function joinCommand (ev) {
875 var channel, channel_names;
876
877 channel_names = ev.params.join(' ').split(',');
878
879 $.each(channel_names, function (index, channel_name) {
880 // Trim any whitespace off the name
881 channel_name = channel_name.trim();
882
883 // Check if we have the panel already. If not, create it
884 channel = that.panels.getByName(channel_name);
885 if (!channel) {
886 channel = new _kiwi.model.Channel({name: channel_name});
887 _kiwi.app.panels.add(channel);
888 }
889
890 _kiwi.gateway.join(channel_name);
891 });
892
893 if (channel) channel.view.show();
894
895 }
896
897 function queryCommand (ev) {
898 var destination, panel;
899
900 destination = ev.params[0];
901
902 // Check if we have the panel already. If not, create it
903 panel = that.panels.getByName(destination);
904 if (!panel) {
905 panel = new _kiwi.model.Query({name: destination});
906 _kiwi.app.panels.add(panel);
907 }
908
909 if (panel) panel.view.show();
910
911 }
912
913 function msgCommand (ev) {
914 var destination = ev.params[0],
915 panel = that.panels.getByName(destination) || that.panels.server;
916
917 ev.params.shift();
918
919 panel.addMsg(_kiwi.gateway.get('nick'), ev.params.join(' '));
920 _kiwi.gateway.privmsg(destination, ev.params.join(' '));
921 }
922
923 function actionCommand (ev) {
924 if (_kiwi.app.panels.active === _kiwi.app.panels.server) {
925 return;
926 }
927
928 var panel = _kiwi.app.panels.active;
929 panel.addMsg('', '* ' + _kiwi.gateway.get('nick') + ' ' + ev.params.join(' '), 'action');
930 _kiwi.gateway.action(panel.get('name'), ev.params.join(' '));
931 }
932
933 function partCommand (ev) {
934 if (ev.params.length === 0) {
935 _kiwi.gateway.part(_kiwi.app.panels.active.get('name'));
936 } else {
937 _.each(ev.params, function (channel) {
938 _kiwi.gateway.part(channel);
939 });
940 }
941 // TODO: More responsive = close tab now, more accurate = leave until part event
942 //_kiwi.app.panels.remove(_kiwi.app.panels.active);
943 }
944
945 function topicCommand (ev) {
946 var channel_name;
947
948 if (ev.params.length === 0) return;
949
950 if (that.isChannelName(ev.params[0])) {
951 channel_name = ev.params[0];
952 ev.params.shift();
953 } else {
954 channel_name = _kiwi.app.panels.active.get('name');
955 }
956
957 _kiwi.gateway.topic(channel_name, ev.params.join(' '));
958 }
959
960 function noticeCommand (ev) {
961 var destination;
962
963 // Make sure we have a destination and some sort of message
964 if (ev.params.length <= 1) return;
965
966 destination = ev.params[0];
967 ev.params.shift();
968
969 _kiwi.gateway.notice(destination, ev.params.join(' '));
970 }
971
972 function quoteCommand (ev) {
973 var raw = ev.params.join(' ');
974 _kiwi.gateway.raw(raw);
975 }
976
977 function kickCommand (ev) {
978 var nick, panel = _kiwi.app.panels.active;
979
980 if (!panel.isChannel()) return;
981
982 // Make sure we have a nick
983 if (ev.params.length === 0) return;
984
985 nick = ev.params[0];
986 ev.params.shift();
987
988 _kiwi.gateway.kick(panel.get('name'), nick, ev.params.join(' '));
989 }
990
991 function settingsCommand (ev) {
992 var panel = new _kiwi.model.Applet();
993 panel.load(new _kiwi.applets.Settings());
994
995 _kiwi.app.panels.add(panel);
996 panel.view.show();
997 }
998
999 function appletCommand (ev) {
1000 if (!ev.params[0]) return;
1001
1002 var panel = new _kiwi.model.Applet();
1003
1004 if (ev.params[1]) {
1005 // Url and name given
1006 panel.load(ev.params[0], ev.params[1]);
1007 } else {
1008 // Load a pre-loaded applet
1009 if (_kiwi.applets[ev.params[0]]) {
1010 panel.load(new _kiwi.applets[ev.params[0]]());
1011 } else {
1012 _kiwi.app.panels.server.addMsg('', 'Applet "' + ev.params[0] + '" does not exist');
1013 return;
1014 }
1015 }
1016
1017 _kiwi.app.panels.add(panel);
1018 panel.view.show();
1019 }
1020
1021
1022
1023
1024
1025 this.isChannelName = function (channel_name) {
1026 var channel_prefix = _kiwi.gateway.get('channel_prefix');
1027
1028 if (!channel_name || !channel_name.length) return false;
1029 return (channel_prefix.indexOf(channel_name[0]) > -1);
1030 };
1031
1032 };
1033
1034
1035 model = Backbone.Model.extend(new model());
1036
1037 return new model(arguments);
1038 };