b83f3343c40a2b5f357d42003d82435082743687
[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
643 gw.on('onlist_start', function (data) {
644 if (_kiwi.app.channel_list) {
645 _kiwi.app.channel_list.close();
646 delete _kiwi.app.channel_list;
647 }
648
649 var panel = new _kiwi.model.Applet(),
650 applet = new _kiwi.applets.Chanlist();
651
652 panel.load(applet);
653
654 _kiwi.app.panels.add(panel);
655 panel.view.show();
656
657 _kiwi.app.channel_list = applet;
658 });
659
660
661 gw.on('onlist_channel', function (data) {
662 // TODO: Put this listener within the applet itself
663 _kiwi.app.channel_list.addChannel(data.chans);
664 });
665
666
667 gw.on('onlist_end', function (data) {
668 // TODO: Put this listener within the applet itself
669 delete _kiwi.app.channel_list;
670 });
671
672
673 gw.on('onirc_error', function (data) {
674 var panel, tmp;
675
676 if (data.channel !== undefined && !(panel = _kiwi.app.panels.getByName(data.channel))) {
677 panel = _kiwi.app.panels.server;
678 }
679
680 switch (data.error) {
681 case 'banned_from_channel':
682 panel.addMsg(' ', '== You are banned from ' + data.channel + '. ' + data.reason, 'status');
683 _kiwi.app.message.text('You are banned from ' + data.channel + '. ' + data.reason);
684 break;
685 case 'bad_channel_key':
686 panel.addMsg(' ', '== Bad channel key for ' + data.channel, 'status');
687 _kiwi.app.message.text('Bad channel key or password for ' + data.channel);
688 break;
689 case 'invite_only_channel':
690 panel.addMsg(' ', '== ' + data.channel + ' is invite only.', 'status');
691 _kiwi.app.message.text(data.channel + ' is invite only');
692 break;
693 case 'channel_is_full':
694 panel.addMsg(' ', '== ' + data.channel + ' is full.', 'status');
695 _kiwi.app.message.text(data.channel + ' is full');
696 break;
697 case 'chanop_privs_needed':
698 panel.addMsg(' ', '== ' + data.reason, 'status');
699 _kiwi.app.message.text(data.reason + ' (' + data.channel + ')');
700 break;
701 case 'no_such_nick':
702 tmp = _kiwi.app.panels.getByName(data.nick);
703 if (tmp) {
704 tmp.addMsg(' ', '== ' + data.nick + ': ' + data.reason, 'status');
705 } else {
706 _kiwi.app.panels.server.addMsg(' ', '== ' + data.nick + ': ' + data.reason, 'status');
707 }
708 break;
709 case 'nickname_in_use':
710 _kiwi.app.panels.server.addMsg(' ', '== The nickname ' + data.nick + ' is already in use. Please select a new nickname', 'status');
711 if (_kiwi.app.panels.server !== _kiwi.app.panels.active) {
712 _kiwi.app.message.text('The nickname "' + data.nick + '" is already in use. Please select a new nickname');
713 }
714
715 // Only show the nickchange component if the controlbox is open
716 if (that.controlbox.$el.css('display') !== 'none') {
717 (new _kiwi.view.NickChangeBox()).render();
718 }
719
720 break;
721 default:
722 // We don't know what data contains, so don't do anything with it.
723 //_kiwi.front.tabviews.server.addMsg(null, ' ', '== ' + data, 'status');
724 }
725 });
726 };
727
728
729
730 /**
731 * Bind to certain commands that may be typed into the control box
732 */
733 this.bindControllboxCommands = function (controlbox) {
734 // Default aliases
735 $.extend(controlbox.preprocessor.aliases, {
736 // General aliases
737 '/p': '/part $1+',
738 '/me': '/action $1+',
739 '/j': '/join $1+',
740 '/q': '/query $1+',
741
742 // Op related aliases
743 '/op': '/quote mode $channel +o $1+',
744 '/deop': '/quote mode $channel -o $1+',
745 '/hop': '/quote mode $channel +h $1+',
746 '/dehop': '/quote mode $channel -h $1+',
747 '/voice': '/quote mode $channel +v $1+',
748 '/devoice': '/quote mode $channel -v $1+',
749 '/k': '/kick $channel $1+',
750
751 // Misc aliases
752 '/slap': '/me slaps $1 around a bit with a large trout'
753 });
754
755 controlbox.on('unknown_command', unknownCommand);
756
757 controlbox.on('command', allCommands);
758 controlbox.on('command_msg', msgCommand);
759
760 controlbox.on('command_action', actionCommand);
761
762 controlbox.on('command_join', joinCommand);
763
764 controlbox.on('command_part', partCommand);
765
766 controlbox.on('command_nick', function (ev) {
767 _kiwi.gateway.changeNick(ev.params[0]);
768 });
769
770 controlbox.on('command_query', queryCommand);
771
772 controlbox.on('command_topic', topicCommand);
773
774 controlbox.on('command_notice', noticeCommand);
775
776 controlbox.on('command_quote', quoteCommand);
777
778 controlbox.on('command_kick', kickCommand);
779
780
781 controlbox.on('command_css', function (ev) {
782 var queryString = '?reload=' + new Date().getTime();
783 $('link[rel="stylesheet"]').each(function () {
784 this.href = this.href.replace(/\?.*|$/, queryString);
785 });
786 });
787
788 controlbox.on('command_js', function (ev) {
789 if (!ev.params[0]) return;
790 $script(ev.params[0] + '?' + (new Date().getTime()));
791 });
792
793
794 controlbox.on('command_set', function (ev) {
795 if (!ev.params[0]) return;
796
797 var setting = ev.params[0],
798 value;
799
800 // Do we have a second param to set a value?
801 if (ev.params[1]) {
802 ev.params.shift();
803
804 value = ev.params.join(' ');
805 _kiwi.global.settings.set(setting, value);
806 }
807
808 // Read the value to the user
809 _kiwi.app.panels.active.addMsg('', setting + ' = ' + _kiwi.global.settings.get(setting));
810 });
811
812
813 controlbox.on('command_save', function (ev) {
814 _kiwi.global.settings.save();
815 _kiwi.app.panels.active.addMsg('', 'Settings have been saved');
816 });
817
818
819 controlbox.on('command_alias', function (ev) {
820 var name, rule;
821
822 // No parameters passed so list them
823 if (!ev.params[1]) {
824 $.each(controlbox.preprocessor.aliases, function (name, rule) {
825 _kiwi.app.panels.server.addMsg(' ', name + ' => ' + rule);
826 });
827 return;
828 }
829
830 // Deleting an alias?
831 if (ev.params[0] === 'del' || ev.params[0] === 'delete') {
832 name = ev.params[1];
833 if (name[0] !== '/') name = '/' + name;
834 delete controlbox.preprocessor.aliases[name];
835 return;
836 }
837
838 // Add the alias
839 name = ev.params[0];
840 ev.params.shift();
841 rule = ev.params.join(' ');
842
843 // Make sure the name starts with a slash
844 if (name[0] !== '/') name = '/' + name;
845
846 // Now actually add the alias
847 controlbox.preprocessor.aliases[name] = rule;
848 });
849
850 controlbox.on('command_applet', appletCommand);
851 controlbox.on('command_settings', settingsCommand);
852 };
853
854 // A fallback action. Send a raw command to the server
855 function unknownCommand (ev) {
856 var raw_cmd = ev.command + ' ' + ev.params.join(' ');
857 console.log('RAW: ' + raw_cmd);
858 _kiwi.gateway.raw(raw_cmd);
859 }
860
861 function allCommands (ev) {}
862
863 function joinCommand (ev) {
864 var channel, channel_names;
865
866 channel_names = ev.params.join(' ').split(',');
867
868 $.each(channel_names, function (index, channel_name) {
869 // Trim any whitespace off the name
870 channel_name = channel_name.trim();
871
872 // Check if we have the panel already. If not, create it
873 channel = that.panels.getByName(channel_name);
874 if (!channel) {
875 channel = new _kiwi.model.Channel({name: channel_name});
876 _kiwi.app.panels.add(channel);
877 }
878
879 _kiwi.gateway.join(channel_name);
880 });
881
882 if (channel) channel.view.show();
883
884 }
885
886 function queryCommand (ev) {
887 var destination, panel;
888
889 destination = ev.params[0];
890
891 // Check if we have the panel already. If not, create it
892 panel = that.panels.getByName(destination);
893 if (!panel) {
894 panel = new _kiwi.model.Query({name: destination});
895 _kiwi.app.panels.add(panel);
896 }
897
898 if (panel) panel.view.show();
899
900 }
901
902 function msgCommand (ev) {
903 var destination = ev.params[0],
904 panel = that.panels.getByName(destination) || that.panels.server;
905
906 ev.params.shift();
907
908 panel.addMsg(_kiwi.gateway.get('nick'), ev.params.join(' '));
909 _kiwi.gateway.privmsg(destination, ev.params.join(' '));
910 }
911
912 function actionCommand (ev) {
913 if (_kiwi.app.panels.active === _kiwi.app.panels.server) {
914 return;
915 }
916
917 var panel = _kiwi.app.panels.active;
918 panel.addMsg('', '* ' + _kiwi.gateway.get('nick') + ' ' + ev.params.join(' '), 'action');
919 _kiwi.gateway.action(panel.get('name'), ev.params.join(' '));
920 }
921
922 function partCommand (ev) {
923 if (ev.params.length === 0) {
924 _kiwi.gateway.part(_kiwi.app.panels.active.get('name'));
925 } else {
926 _.each(ev.params, function (channel) {
927 _kiwi.gateway.part(channel);
928 });
929 }
930 // TODO: More responsive = close tab now, more accurate = leave until part event
931 //_kiwi.app.panels.remove(_kiwi.app.panels.active);
932 }
933
934 function topicCommand (ev) {
935 var channel_name;
936
937 if (ev.params.length === 0) return;
938
939 if (that.isChannelName(ev.params[0])) {
940 channel_name = ev.params[0];
941 ev.params.shift();
942 } else {
943 channel_name = _kiwi.app.panels.active.get('name');
944 }
945
946 _kiwi.gateway.topic(channel_name, ev.params.join(' '));
947 }
948
949 function noticeCommand (ev) {
950 var destination;
951
952 // Make sure we have a destination and some sort of message
953 if (ev.params.length <= 1) return;
954
955 destination = ev.params[0];
956 ev.params.shift();
957
958 _kiwi.gateway.notice(destination, ev.params.join(' '));
959 }
960
961 function quoteCommand (ev) {
962 var raw = ev.params.join(' ');
963 _kiwi.gateway.raw(raw);
964 }
965
966 function kickCommand (ev) {
967 var nick, panel = _kiwi.app.panels.active;
968
969 if (!panel.isChannel()) return;
970
971 // Make sure we have a nick
972 if (ev.params.length === 0) return;
973
974 nick = ev.params[0];
975 ev.params.shift();
976
977 _kiwi.gateway.kick(panel.get('name'), nick, ev.params.join(' '));
978 }
979
980 function settingsCommand (ev) {
981 var panel = new _kiwi.model.Applet();
982 panel.load(new _kiwi.applets.Settings());
983
984 _kiwi.app.panels.add(panel);
985 panel.view.show();
986 }
987
988 function appletCommand (ev) {
989 if (!ev.params[0]) return;
990
991 var panel = new _kiwi.model.Applet();
992
993 if (ev.params[1]) {
994 // Url and name given
995 panel.load(ev.params[0], ev.params[1]);
996 } else {
997 // Load a pre-loaded applet
998 if (_kiwi.applets[ev.params[0]]) {
999 panel.load(new _kiwi.applets[ev.params[0]]());
1000 } else {
1001 _kiwi.app.panels.server.addMsg('', 'Applet "' + ev.params[0] + '" does not exist');
1002 return;
1003 }
1004 }
1005
1006 _kiwi.app.panels.add(panel);
1007 panel.view.show();
1008 }
1009
1010
1011
1012
1013
1014 this.isChannelName = function (channel_name) {
1015 var channel_prefix = _kiwi.gateway.get('channel_prefix');
1016
1017 if (!channel_name || !channel_name.length) return false;
1018 return (channel_prefix.indexOf(channel_name[0]) > -1);
1019 };
1020
1021 };
1022
1023
1024 model = Backbone.Model.extend(new model());
1025
1026 return new model(arguments);
1027 };