.say() alias .msg() on public Network object
[KiwiIRC.git] / client / src / app.js
1 // Holds anything kiwi client specific (ie. front, gateway, _kiwi.plugs..)
2 /**
3 * @namespace
4 */
5 var _kiwi = {};
6
7 _kiwi.misc = {};
8 _kiwi.model = {};
9 _kiwi.view = {};
10 _kiwi.applets = {};
11
12
13 /**
14 * A global container for third party access
15 * Will be used to access a limited subset of kiwi functionality
16 * and data (think: plugins)
17 */
18 _kiwi.global = {
19 build_version: '', // Kiwi IRC version this is built from (Set from index.html)
20 settings: undefined, // Instance of _kiwi.model.DataStore
21 plugins: undefined, // Instance of _kiwi.model.PluginManager
22 events: undefined, // Instance of PluginInterface
23 rpc: undefined, // Instance of WebsocketRpc
24 utils: {}, // References to misc. re-usable helpers / functions
25
26 initUtils: function() {
27 this.utils.randomString = randomString;
28 this.utils.secondsToTime = secondsToTime;
29 this.utils.parseISO8601 = parseISO8601;
30 this.utils.escapeRegex = escapeRegex;
31 this.utils.formatIRCMsg = formatIRCMsg;
32 this.utils.styleText = styleText;
33 this.utils.hsl2rgb = hsl2rgb;
34 },
35
36 addMediaMessageType: function(match, buildHtml) {
37 _kiwi.view.MediaMessage.addType(match, buildHtml);
38 },
39
40 // Event managers for plugins
41 components: {
42 EventComponent: function(event_source, proxy_event_name) {
43 /*
44 * proxyEvent() listens for events then re-triggers them on its own
45 * event emitter. Why? So we can .off() on this emitter without
46 * effecting the source of events. Handy for plugins that we don't
47 * trust meddling with the core events.
48 *
49 * If listening for 'all' events the arguments are as follows:
50 * 1. Name of the triggered event
51 * 2. The event data
52 * For all other events, we only have one argument:
53 * 1. The event data
54 *
55 * When this is used via `new kiwi.components.Network()`, this listens
56 * for 'all' events so the first argument is the event name which is
57 * the connection ID. We don't want to re-trigger this event name so
58 * we need to juggle the arguments to find the real event name we want
59 * to emit.
60 */
61 function proxyEvent(event_name, event_data) {
62 if (proxy_event_name == 'all') {
63 } else {
64 event_data = event_name.event_data;
65 event_name = event_name.event_name;
66 }
67
68 this.trigger(event_name, event_data);
69 }
70
71 // The event we are to proxy
72 proxy_event_name = proxy_event_name || 'all';
73
74 _.extend(this, Backbone.Events);
75 this._source = event_source;
76
77 // Proxy the events to this dispatcher
78 event_source.on(proxy_event_name, proxyEvent, this);
79
80 // Clean up this object
81 this.dispose = function () {
82 event_source.off(proxy_event_name, proxyEvent);
83 this.off();
84 delete this.event_source;
85 };
86 },
87
88 Network: function(connection_id) {
89 var connection_event;
90
91 // If no connection id given, use all connections
92 if (typeof connection_id !== 'undefined') {
93 connection_event = 'connection:' + connection_id.toString();
94 } else {
95 connection_event = 'connection';
96 }
97
98 // Helper to get the network object
99 var getNetwork = function() {
100 var network = typeof connection_id === 'undefined' ?
101 _kiwi.app.connections.active_connection :
102 _kiwi.app.connections.getByConnectionId(connection_id);
103
104 return network ?
105 network :
106 undefined;
107 };
108
109 // Create the return object (events proxy from the gateway)
110 var obj = new this.EventComponent(_kiwi.gateway, connection_event);
111
112 // Proxy several gateway functions onto the return object
113 var funcs = {
114 kiwi: 'kiwi', raw: 'raw', kick: 'kick', topic: 'topic',
115 part: 'part', join: 'join', action: 'action', ctcp: 'ctcp',
116 ctcpRequest: 'ctcpRequest', ctcpResponse: 'ctcpResponse',
117 notice: 'notice', msg: 'privmsg', say: 'privmsg',
118 changeNick: 'changeNick', channelInfo: 'channelInfo',
119 mode: 'mode', quit: 'quit'
120 };
121
122 _.each(funcs, function(gateway_fn, func_name) {
123 obj[func_name] = function() {
124 var fn_name = gateway_fn;
125
126 // Add connection_id to the argument list
127 var args = Array.prototype.slice.call(arguments, 0);
128 args.unshift(connection_id);
129
130 // Call the gateway function on behalf of this connection
131 return _kiwi.gateway[fn_name].apply(_kiwi.gateway, args);
132 };
133 });
134
135 // Now for some network related functions...
136 obj.createQuery = function(nick) {
137 var network, restricted_keys;
138
139 network = getNetwork();
140 if (!network) {
141 return;
142 }
143
144 return network.createQuery(nick);
145 };
146
147 // Add the networks getters/setters
148 obj.get = function(name) {
149 var network, restricted_keys;
150
151 network = getNetwork();
152 if (!network) {
153 return;
154 }
155
156 restricted_keys = [
157 'password'
158 ];
159 if (restricted_keys.indexOf(name) > -1) {
160 return undefined;
161 }
162
163 return network.get(name);
164 };
165
166 obj.set = function() {
167 var network = getNetwork();
168 if (!network) {
169 return;
170 }
171
172 return network.set.apply(network, arguments);
173 };
174
175 return obj;
176 },
177
178 ControlInput: function() {
179 var obj = new this.EventComponent(_kiwi.app.controlbox);
180 var funcs = {
181 run: 'processInput', addPluginIcon: 'addPluginIcon'
182 };
183
184 _.each(funcs, function(controlbox_fn, func_name) {
185 obj[func_name] = function() {
186 var fn_name = controlbox_fn;
187 return _kiwi.app.controlbox[fn_name].apply(_kiwi.app.controlbox, arguments);
188 };
189 });
190
191 return obj;
192 }
193 },
194
195 // Entry point to start the kiwi application
196 init: function (opts, callback) {
197 var locale_promise, theme_promise,
198 that = this;
199
200 opts = opts || {};
201
202 this.initUtils();
203
204 // Set up the settings datastore
205 _kiwi.global.settings = _kiwi.model.DataStore.instance('kiwi.settings');
206 _kiwi.global.settings.load();
207
208 // Set the window title
209 window.document.title = opts.server_settings.client.window_title || 'Kiwi IRC';
210
211 locale_promise = new Promise(function (resolve) {
212 var locale = _kiwi.global.settings.get('locale') || 'magic';
213 $.getJSON(opts.base_path + '/assets/locales/' + locale + '.json', function (locale) {
214 if (locale) {
215 that.i18n = new Jed(locale);
216 } else {
217 that.i18n = new Jed();
218 }
219 resolve();
220 });
221 });
222
223 theme_promise = new Promise(function (resolve) {
224 var text_theme = opts.server_settings.client.settings.text_theme || 'default';
225 $.getJSON(opts.base_path + '/assets/text_themes/' + text_theme + '.json', function(text_theme) {
226 opts.text_theme = text_theme;
227 resolve();
228 });
229 });
230
231
232 Promise.all([locale_promise, theme_promise]).then(function () {
233 _kiwi.app = new _kiwi.model.Application(opts);
234
235 // Start the client up
236 _kiwi.app.initializeInterfaces();
237
238 // Event emitter to let plugins interface with parts of kiwi
239 _kiwi.global.events = new PluginInterface();
240
241 // Now everything has started up, load the plugin manager for third party plugins
242 _kiwi.global.plugins = new _kiwi.model.PluginManager();
243
244 callback();
245 });
246 },
247
248 start: function() {
249 _kiwi.app.showStartup();
250 },
251
252 // Allow plugins to change the startup applet
253 registerStartupApplet: function(startup_applet_name) {
254 _kiwi.app.startup_applet_name = startup_applet_name;
255 },
256
257 /**
258 * Open a new IRC connection
259 * @param {Object} connection_details {nick, host, port, ssl, password, options}
260 * @param {Function} callback function(err, network){}
261 */
262 newIrcConnection: function(connection_details, callback) {
263 _kiwi.gateway.newConnection(connection_details, callback);
264 },
265
266
267 /**
268 * Taking settings from the server and URL, extract the default server/channel/nick settings
269 */
270 defaultServerSettings: function () {
271 var parts;
272 var defaults = {
273 nick: '',
274 server: '',
275 port: 6667,
276 ssl: false,
277 channel: '',
278 channel_key: ''
279 };
280 var uricheck;
281
282
283 /**
284 * Get any settings set by the server
285 * These settings may be changed in the server selection dialog or via URL parameters
286 */
287 if (_kiwi.app.server_settings.client) {
288 if (_kiwi.app.server_settings.client.nick)
289 defaults.nick = _kiwi.app.server_settings.client.nick;
290
291 if (_kiwi.app.server_settings.client.server)
292 defaults.server = _kiwi.app.server_settings.client.server;
293
294 if (_kiwi.app.server_settings.client.port)
295 defaults.port = _kiwi.app.server_settings.client.port;
296
297 if (_kiwi.app.server_settings.client.ssl)
298 defaults.ssl = _kiwi.app.server_settings.client.ssl;
299
300 if (_kiwi.app.server_settings.client.channel)
301 defaults.channel = _kiwi.app.server_settings.client.channel;
302
303 if (_kiwi.app.server_settings.client.channel_key)
304 defaults.channel_key = _kiwi.app.server_settings.client.channel_key;
305 }
306
307
308
309 /**
310 * Get any settings passed in the URL
311 * These settings may be changed in the server selection dialog
312 */
313
314 // Any query parameters first
315 if (getQueryVariable('nick'))
316 defaults.nick = getQueryVariable('nick');
317
318 if (window.location.hash)
319 defaults.channel = window.location.hash;
320
321
322 // Process the URL part by part, extracting as we go
323 parts = window.location.pathname.toString().replace(_kiwi.app.get('base_path'), '').split('/');
324
325 if (parts.length > 0) {
326 parts.shift();
327
328 if (parts.length > 0 && parts[0]) {
329 // 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.
330 uricheck = parts[0].substr(0, 7).toLowerCase();
331 if ((uricheck === 'ircs%3a') || (uricheck.substr(0,6) === 'irc%3a')) {
332 parts[0] = decodeURIComponent(parts[0]);
333 // irc[s]://<host>[:<port>]/[<channel>[?<password>]]
334 uricheck = /^irc(s)?:(?:\/\/?)?([^:\/]+)(?::([0-9]+))?(?:(?:\/)([^\?]*)(?:(?:\?)(.*))?)?$/.exec(parts[0]);
335 /*
336 uricheck[1] = ssl (optional)
337 uricheck[2] = host
338 uricheck[3] = port (optional)
339 uricheck[4] = channel (optional)
340 uricheck[5] = channel key (optional, channel must also be set)
341 */
342 if (uricheck) {
343 if (typeof uricheck[1] !== 'undefined') {
344 defaults.ssl = true;
345 if (defaults.port === 6667) {
346 defaults.port = 6697;
347 }
348 }
349 defaults.server = uricheck[2];
350 if (typeof uricheck[3] !== 'undefined') {
351 defaults.port = uricheck[3];
352 }
353 if (typeof uricheck[4] !== 'undefined') {
354 defaults.channel = '#' + uricheck[4];
355 if (typeof uricheck[5] !== 'undefined') {
356 defaults.channel_key = uricheck[5];
357 }
358 }
359 }
360 parts = [];
361 } else {
362 // Extract the port+ssl if we find one
363 if (parts[0].search(/:/) > 0) {
364 defaults.port = parts[0].substring(parts[0].search(/:/) + 1);
365 defaults.server = parts[0].substring(0, parts[0].search(/:/));
366 if (defaults.port[0] === '+') {
367 defaults.port = parseInt(defaults.port.substring(1), 10);
368 defaults.ssl = true;
369 } else {
370 defaults.ssl = false;
371 }
372
373 } else {
374 defaults.server = parts[0];
375 }
376
377 parts.shift();
378 }
379 }
380
381 if (parts.length > 0 && parts[0]) {
382 defaults.channel = '#' + parts[0];
383 parts.shift();
384 }
385 }
386
387 // If any settings have been given by the server.. override any auto detected settings
388 /**
389 * Get any server restrictions as set in the server config
390 * These settings can not be changed in the server selection dialog
391 */
392 if (_kiwi.app.server_settings && _kiwi.app.server_settings.connection) {
393 if (_kiwi.app.server_settings.connection.server) {
394 defaults.server = _kiwi.app.server_settings.connection.server;
395 }
396
397 if (_kiwi.app.server_settings.connection.port) {
398 defaults.port = _kiwi.app.server_settings.connection.port;
399 }
400
401 if (_kiwi.app.server_settings.connection.ssl) {
402 defaults.ssl = _kiwi.app.server_settings.connection.ssl;
403 }
404
405 if (_kiwi.app.server_settings.connection.channel) {
406 defaults.channel = _kiwi.app.server_settings.connection.channel;
407 }
408
409 if (_kiwi.app.server_settings.connection.channel_key) {
410 defaults.channel_key = _kiwi.app.server_settings.connection.channel_key;
411 }
412
413 if (_kiwi.app.server_settings.connection.nick) {
414 defaults.nick = _kiwi.app.server_settings.connection.nick;
415 }
416 }
417
418 // Set any random numbers if needed
419 defaults.nick = defaults.nick.replace('?', Math.floor(Math.random() * 100000).toString());
420
421 if (getQueryVariable('encoding'))
422 defaults.encoding = getQueryVariable('encoding');
423
424 return defaults;
425 },
426 };
427
428
429
430 // If within a closure, expose the kiwi globals
431 if (typeof global !== 'undefined') {
432 global.kiwi = _kiwi.global;
433 } else {
434 // Not within a closure so set a var in the current scope
435 var kiwi = _kiwi.global;
436 }