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