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