<commit_before>var blessed = require('blessed');
var db = require('./database_client');
var github = require('octonode');

var screen = blessed.screen({
  smartCSR: true
});

function fetchFromGitHub(repoId) {
  return new Promise(function(fullfill, reject) {
    var client = github.client();
    var ghrepo = client.repo(repoId);
    ghrepo.issues(function(err, issues) {
      if(err) {
        reject(err);
      } else {
        fullfill(issues);
      }
    });
  });
}

function initialFetch(repositoryName) {
  var dbName = db.createDatabaseName(repositoryName);
  return fetchFromGitHub(repositoryName).then(function(issues) {
    return db.saveToDatabase(dbName, issues);
  })
  .then(function() {
    return db.fetchDocuments(dbName);
  });
}

function MainWindow(repositoryName) {
  this.repositoryName = repositoryName;
  this.dbName = db.createDatabaseName(this.repositoryName);
  this.list = this.createList();
}

MainWindow.prototype.initialize = function() {
  var self = this;
  db.fetchDocuments(this.dbName).then((resultSet) => {
    if (resultSet.total_rows > 0) {
      return Promise.resolve(resultSet);
    } else {
      return initialFetch(this.repositoryName);
    }
  })
  .then(function(resultSet) {
    return Promise.resolve(resultSet.rows);
  })
  .then(function(resultSet) {
    self.list.setItems(resultSet.map(function(d) {
      return d.doc.title.toString();
    }));
  })
  .catch(function(err) {
    console.log("ERR", err);
  });
};

MainWindow.prototype.createList = function() {
  return blessed.List({
    width: '100%',
    height: '100%',
    top: 'center',
    left: 'center',
    align: 'center',
    fg: 'blue',
    border: {
      type: 'line'
    },
    selectedBg: 'green',
    mouse: true,
    keys: true,
    vi: true
  });
};

MainWindow.prototype.render = function() {
  screen.title = 'taskboard';
  screen.append(this.list);
  screen.key(['escape', 'q', 'C-c'], function(ch, key) {
    return process.exit(0);
  });
  this.list.focus();
  screen.render();
};

module.exports = MainWindow;
<commit_msg>render issue id into list<commit_after>'use strict';
var blessed = require('blessed');
var db = require('./database_client');
var github = require('octonode');

var screen = blessed.screen({
  smartCSR: true
});

function fetchFromGitHub(repoId) {
  return new Promise(function(fullfill, reject) {
    var client = github.client();
    var ghrepo = client.repo(repoId);
    ghrepo.issues(function(err, issues) {
      if(err) {
        reject(err);
      } else {
        fullfill(issues);
      }
    });
  });
}

function initialFetch(repositoryName) {
  var dbName = db.createDatabaseName(repositoryName);
  return fetchFromGitHub(repositoryName).then(function(issues) {
    return db.saveToDatabase(dbName, issues);
  })
  .then(function() {
    return db.fetchDocuments(dbName);
  });
}

function MainWindow(repositoryName) {
  this.repositoryName = repositoryName;
  this.dbName = db.createDatabaseName(this.repositoryName);
  this.list = this.createList();
}

MainWindow.prototype.initialize = function() {
  var self = this;
  db.fetchDocuments(this.dbName).then((resultSet) => {
    if (resultSet.total_rows > 0) {
      return Promise.resolve(resultSet);
    } else {
      return initialFetch(this.repositoryName);
    }
  })
  .then(function(resultSet) {
    return Promise.resolve(resultSet.rows);
  })
  .then(function(resultSet) {
    self.list.setItems(resultSet.map(function(d) {
      let title = d.doc.title.toString();
      let id = d.doc.number.toString();
      return `${id}-${title}`;
    }));
  })
  .catch(function(err) {
    console.log("ERR", err);
  });
};

MainWindow.prototype.createList = function() {
  return blessed.List({
    width: '100%',
    height: '100%',
    top: 'center',
    left: 'center',
    align: 'center',
    fg: 'blue',
    border: {
      type: 'line'
    },
    selectedBg: 'green',
    mouse: true,
    keys: true,
    vi: true
  });
};

MainWindow.prototype.render = function() {
  screen.title = 'taskboard';
  screen.append(this.list);
  screen.key(['escape', 'q', 'C-c'], function(ch, key) {
    return process.exit(0);
  });
  this.list.focus();
  screen.render();
};

module.exports = MainWindow;
<|endoftext|>


<commit_before>/* jshint -W097 */
/* jshint strict: false */
/* jslint node: true */
/* jshint -W061 */
'use strict';

const WebSocket     = require('ws');
const querystring   = require('querystring');

const MESSAGE_TYPES = {
    MESSAGE: 0,
    PING: 1,
    PONG: 2,
    CALLBACK: 3
};

const DEBUG = false;

function Socket(ws, sessionID, name) {
    this.ws = ws;
    const handlers = {};
    let lastPong = Date.now();
    let id = 0;

    this._name = name;

    // simulate interface of socket.io
    this.conn = {
        request: { sessionID }
    };

    this.id = sessionID;

    let pingInterval = setInterval(() => {
        if (Date.now() - lastPong > 5000) {
            ws.send(JSON.stringify([MESSAGE_TYPES.PING]));
        }
        if (Date.now() - lastPong > 15000) {
            this.close();
        }
    }, 5000);

    this.on = (name, cb) => {
        if (cb) {
            handlers[name] = handlers[name] || [];
            handlers[name].push(cb);
        }
    };

    this.off = (name, cb) => {
        if (handlers[name]) {
            const pos = handlers[name].indexOf(cb);
            if (pos !== -1) {
                handlers[name].splice(pos, 1);
                if (!handlers[name].length) {
                    delete handlers[name];
                }
            }
        }
    };

    this.emit = (name, arg1, arg2, arg3, arg4, arg5) => {
        id++;
        if (arg1 === undefined && arg2 === undefined && arg3 === undefined && arg4 === undefined && arg5 === undefined) {
            this.ws.send(JSON.stringify([MESSAGE_TYPES.MESSAGE, id, name]));
        } else if (arg2 === undefined && arg3 === undefined && arg4 === undefined && arg5 === undefined) {
            this.ws.send(JSON.stringify([MESSAGE_TYPES.MESSAGE, id, name, [arg1]]));
        } else if (arg3 === undefined && arg4 === undefined && arg5 === undefined) {
            this.ws.send(JSON.stringify([MESSAGE_TYPES.MESSAGE, id, name, [arg1, arg2]]));
        } else if (arg4 === undefined && arg5 === undefined) {
            this.ws.send(JSON.stringify([MESSAGE_TYPES.MESSAGE, id, name, [arg1, arg2, arg3]]));
        } else if (arg5 === undefined) {
            this.ws.send(JSON.stringify([MESSAGE_TYPES.MESSAGE, id, name, [arg1, arg2, arg3, arg4]]));
        } else {
            this.ws.send(JSON.stringify([MESSAGE_TYPES.MESSAGE, id, name, [arg1, arg2, arg3, arg4, arg5]]));
        }
    };

    this.responseWithCallback = (name, id, arg1, arg2, arg3, arg4, arg5) => {
        let args;

        // error cannot be converted normally, so try to use internal function for it
        if (arg1 && arg1 instanceof Error) {
            arg1 = arg1.toString();
        }

        if (arg1 === undefined && arg2 === undefined && arg3 === undefined && arg4 === undefined && arg5 === undefined) {
            return ws.send(JSON.stringify([MESSAGE_TYPES.CALLBACK, id, name]));
        } else if (arg2 === undefined && arg3 === undefined && arg4 === undefined && arg5 === undefined) {
            args = [arg1];
        } else if (arg3 === undefined && arg4 === undefined && arg5 === undefined) {
            args = [arg1, arg2];
        } else if (arg4 === undefined && arg5 === undefined) {
            args = [arg1, arg2, arg3];
        } else if (arg5 === undefined) {
            args = [arg1, arg2, arg3, arg4];
        } else {
            args = [arg1, arg2, arg3, arg4, arg5];
        }

        ws.send(JSON.stringify([MESSAGE_TYPES.CALLBACK, id, name, args]));
    };

    this.withCallback = (name, id, args) => {
        if (!args || !args.length) {
            setImmediate(() =>
                handlers[name].forEach(cb => cb.call(this, (arg1, arg2, arg3, arg4, arg5) =>
                    this.responseWithCallback(name, id, arg1, arg2, arg3, arg4, arg5))));
        } else if (args.length === 1) {
            setImmediate(() =>
                handlers[name].forEach(cb => cb.call(this, args[0], (arg1, arg2, arg3, arg4, arg5) =>
                    this.responseWithCallback(name, id, arg1, arg2, arg3, arg4, arg5))));
        } else if (args.length === 2) {
            setImmediate(() =>
                handlers[name].forEach(cb => cb.call(this, args[0], args[1], (arg1, arg2, arg3, arg4, arg5) =>
                    this.responseWithCallback(name, id, arg1, arg2, arg3, arg4, arg5))));
        } else if (args.length === 3) {
            setImmediate(() =>
                handlers[name].forEach(cb => cb.call(this, args[0], args[1], args[2], (arg1, arg2, arg3, arg4, arg5) =>
                    this.responseWithCallback(name, id, arg1, arg2, arg3, arg4, arg5))));
        } else if (args.length === 4) {
            setImmediate(() =>
                handlers[name].forEach(cb => cb.call(this, args[0], args[1], args[2], args[3], (arg1, arg2, arg3, arg4, arg5) =>
                    this.responseWithCallback(name, id, arg1, arg2, arg3, arg4, arg5))));
        } else {
            setImmediate(() =>
                handlers[name].forEach(cb => cb.call(this, args[0], args[1], args[2], args[3], args[4], (arg1, arg2, arg3, arg4, arg5) =>
                    this.responseWithCallback(name, id, arg1, arg2, arg3, arg4, arg5))));
        }
    };

    ws.on('message', message => {
        lastPong = Date.now();

        if (!message || typeof message !== 'string') {
            return console.error('Received invalid message: ' + JSON.stringify(message));
        }
        try {
            message = JSON.parse(message)
        } catch (e) {
            return console.error('Received invalid message: ' + JSON.stringify(message));
        }
        const [type, id, name, args] = message;

        if (type === MESSAGE_TYPES.CALLBACK) {
            DEBUG && console.log(name);
            handlers[name] && this.withCallback(name, id, args);
        } else
        if (type === MESSAGE_TYPES.MESSAGE) {
            DEBUG && console.log(name);
            handlers[name] && setImmediate(() => handlers[name].forEach(cb => cb.call(this, args[0], args[1], args[2], args[3], args[4])));
        } else if (type === MESSAGE_TYPES.PING) {
            ws.send(JSON.stringify([MESSAGE_TYPES.PONG]));
        } else if (type === MESSAGE_TYPES.PONG) {
            // lastPong saved
        } else {
            console.log('Received unknown message type: ' + type)
        }
    });

    this.close = () => {
        pingInterval && clearInterval(pingInterval);
        pingInterval = null;

        handlers.disconnect && handlers.disconnect.forEach(cb => cb.apply(this));

        Object.keys(handlers).forEach(name => handlers[name] = undefined);

        try {
            ws.close();
        } catch (e) {

        }
    }
}

function SocketIO (server) {
    const handlers = {};
    const run = [];

    let socketsList = [];

    const wss = new WebSocket.Server({
        server,
        verifyClient: function(info, done) {
            if (run.length) {
                run.forEach(cb => cb(info.req, err => {
                    if (err) {
                        info.req._wsNotAuth = true;
                    }
                    done && done(true);
                    done = null;
                }));
            } else {
                done && done(true);
                done = null;
            }
        }
    });

    wss.on('connection', (ws, request) => {
        DEBUG && console.log('connected');
        if (request._wsNotAuth) {
            const ip = request.headers['x-forwarded-for'] ||
                request.connection.remoteAddress ||
                request.socket.remoteAddress ||
                (request.connection.socket ? request.connection.socket.remoteAddress : null);
            handlers.error && handlers.error.forEach(cb => cb('error', `authentication failed for ${ip}`));
            ws.send(JSON.stringify([MESSAGE_TYPES.MESSAGE, 401, 'reauthenticate']));
            setTimeout(() =>
                ws && ws.destroy && ws.destroy(), 500);
        } else {
            let query;

            try {
                const queryString = request.url.split('?')[1];
                query = querystring.parse(queryString || '');
            } catch (e) {
                query = null;
            }

            if (query && query.sid) {
                const socket = new Socket(ws, request.sessionID || query.sid, query.name);
                socket.query = query;
                socketsList.push(socket);
                this.sockets.engine.clientsCount = socketsList.length;

                ws.on('close', () => {
                    DEBUG && console.log('closed');
                    let i;
                    for (i = 0; i < socketsList.length; i++) {
                        if (socketsList[i].ws === ws) {
                            socketsList[i].close();
                            socketsList.splice(i, 1);
                            this.sockets.engine.clientsCount = socketsList.length;
                            return;
                        }
                    }
                });

                // install handlers
                if (handlers.connection && handlers.connection.length) {
                    // we have a race condition here.
                    // If the user is not admin it will be requested for him the rights and no handlers will be installed.
                    // So we must be sure, that all event handlers are installed before sending ___ready___.
                    let timeout = setTimeout(() => {
                        timeout = null;
                        socket.emit('___ready___');
                        console.warn('Sent ready, but not all handlers installed!');
                    }, 1500); // TODO, This parameter must be configurable

                    handlers.connection.forEach(cb => cb(socket, () => {
                        if (timeout) {
                            clearTimeout(timeout);
                            timeout = null;
                            // say to client we are ready
                            socket.emit('___ready___');
                        }
                    }));
                } else {
                    socket.emit('___ready___');
                }
            } else {
                const ip = request.headers['x-forwarded-for'] ||
                    request.connection.remoteAddress ||
                    request.socket.remoteAddress ||
                    (request.connection.socket ? request.connection.socket.remoteAddress : null);
                handlers.error && handlers.error.forEach(cb => cb('error', 'No sid found from ' + ip));
                ws.send(JSON.stringify([MESSAGE_TYPES.MESSAGE, 501, 'error', ['invalid sid']]));
                setTimeout(() =>
                    ws && ws.destroy && ws.destroy(), 500);
            }
        }
    });

    this.on = (name, cb) => {
        if (cb) {
            handlers[name] = handlers[name] || [];
            handlers[name].push(cb);
        }
    };

    this.off = (name, cb) => {
        if (handlers[name]) {
            const pos = handlers[name].indexOf(cb);
            if (pos !== -1) {
                handlers[name].splice(pos, 1);
                if (!handlers[name].length) {
                    delete handlers[name];
                }
            }
        }
    };

    this.sockets = {
        connected: socketsList,
        emit: (arg1, arg2, arg3, arg4, arg5) => {
            socketsList.forEach(socket =>
                socket.emit(arg1, arg2, arg3, arg4, arg5));
        },
        engine: {
            clientsCount: 0,
        }
    };

    this.engine = this.sockets.engine;

    this.use = cb => {
        run.push(cb);
        return this;
    };

    this.ioBroker = true;
}

module.exports = {
    listen: server => new SocketIO(server)
};<commit_msg>(simatec) WebSocket compression added<commit_after>/* jshint -W097 */
/* jshint strict: false */
/* jslint node: true */
/* jshint -W061 */
'use strict';

const WebSocket     = require('ws');
const querystring   = require('querystring');

const MESSAGE_TYPES = {
    MESSAGE: 0,
    PING: 1,
    PONG: 2,
    CALLBACK: 3
};

const DEBUG = false;

function Socket(ws, sessionID, name) {
    this.ws = ws;
    const handlers = {};
    let lastPong = Date.now();
    let id = 0;

    this._name = name;

    // simulate interface of socket.io
    this.conn = {
        request: { sessionID }
    };

    this.id = sessionID;

    let pingInterval = setInterval(() => {
        if (Date.now() - lastPong > 5000) {
            ws.send(JSON.stringify([MESSAGE_TYPES.PING]));
        }
        if (Date.now() - lastPong > 15000) {
            this.close();
        }
    }, 5000);

    this.on = (name, cb) => {
        if (cb) {
            handlers[name] = handlers[name] || [];
            handlers[name].push(cb);
        }
    };

    this.off = (name, cb) => {
        if (handlers[name]) {
            const pos = handlers[name].indexOf(cb);
            if (pos !== -1) {
                handlers[name].splice(pos, 1);
                if (!handlers[name].length) {
                    delete handlers[name];
                }
            }
        }
    };

    this.emit = (name, arg1, arg2, arg3, arg4, arg5) => {
        id++;
        if (arg1 === undefined && arg2 === undefined && arg3 === undefined && arg4 === undefined && arg5 === undefined) {
            this.ws.send(JSON.stringify([MESSAGE_TYPES.MESSAGE, id, name]));
        } else if (arg2 === undefined && arg3 === undefined && arg4 === undefined && arg5 === undefined) {
            this.ws.send(JSON.stringify([MESSAGE_TYPES.MESSAGE, id, name, [arg1]]));
        } else if (arg3 === undefined && arg4 === undefined && arg5 === undefined) {
            this.ws.send(JSON.stringify([MESSAGE_TYPES.MESSAGE, id, name, [arg1, arg2]]));
        } else if (arg4 === undefined && arg5 === undefined) {
            this.ws.send(JSON.stringify([MESSAGE_TYPES.MESSAGE, id, name, [arg1, arg2, arg3]]));
        } else if (arg5 === undefined) {
            this.ws.send(JSON.stringify([MESSAGE_TYPES.MESSAGE, id, name, [arg1, arg2, arg3, arg4]]));
        } else {
            this.ws.send(JSON.stringify([MESSAGE_TYPES.MESSAGE, id, name, [arg1, arg2, arg3, arg4, arg5]]));
        }
    };

    this.responseWithCallback = (name, id, arg1, arg2, arg3, arg4, arg5) => {
        let args;

        // error cannot be converted normally, so try to use internal function for it
        if (arg1 && arg1 instanceof Error) {
            arg1 = arg1.toString();
        }

        if (arg1 === undefined && arg2 === undefined && arg3 === undefined && arg4 === undefined && arg5 === undefined) {
            return ws.send(JSON.stringify([MESSAGE_TYPES.CALLBACK, id, name]));
        } else if (arg2 === undefined && arg3 === undefined && arg4 === undefined && arg5 === undefined) {
            args = [arg1];
        } else if (arg3 === undefined && arg4 === undefined && arg5 === undefined) {
            args = [arg1, arg2];
        } else if (arg4 === undefined && arg5 === undefined) {
            args = [arg1, arg2, arg3];
        } else if (arg5 === undefined) {
            args = [arg1, arg2, arg3, arg4];
        } else {
            args = [arg1, arg2, arg3, arg4, arg5];
        }

        ws.send(JSON.stringify([MESSAGE_TYPES.CALLBACK, id, name, args]));
    };

    this.withCallback = (name, id, args) => {
        if (!args || !args.length) {
            setImmediate(() =>
                handlers[name].forEach(cb => cb.call(this, (arg1, arg2, arg3, arg4, arg5) =>
                    this.responseWithCallback(name, id, arg1, arg2, arg3, arg4, arg5))));
        } else if (args.length === 1) {
            setImmediate(() =>
                handlers[name].forEach(cb => cb.call(this, args[0], (arg1, arg2, arg3, arg4, arg5) =>
                    this.responseWithCallback(name, id, arg1, arg2, arg3, arg4, arg5))));
        } else if (args.length === 2) {
            setImmediate(() =>
                handlers[name].forEach(cb => cb.call(this, args[0], args[1], (arg1, arg2, arg3, arg4, arg5) =>
                    this.responseWithCallback(name, id, arg1, arg2, arg3, arg4, arg5))));
        } else if (args.length === 3) {
            setImmediate(() =>
                handlers[name].forEach(cb => cb.call(this, args[0], args[1], args[2], (arg1, arg2, arg3, arg4, arg5) =>
                    this.responseWithCallback(name, id, arg1, arg2, arg3, arg4, arg5))));
        } else if (args.length === 4) {
            setImmediate(() =>
                handlers[name].forEach(cb => cb.call(this, args[0], args[1], args[2], args[3], (arg1, arg2, arg3, arg4, arg5) =>
                    this.responseWithCallback(name, id, arg1, arg2, arg3, arg4, arg5))));
        } else {
            setImmediate(() =>
                handlers[name].forEach(cb => cb.call(this, args[0], args[1], args[2], args[3], args[4], (arg1, arg2, arg3, arg4, arg5) =>
                    this.responseWithCallback(name, id, arg1, arg2, arg3, arg4, arg5))));
        }
    };

    ws.on('message', message => {
        lastPong = Date.now();

        if (!message || typeof message !== 'string') {
            return console.error('Received invalid message: ' + JSON.stringify(message));
        }
        try {
            message = JSON.parse(message)
        } catch (e) {
            return console.error('Received invalid message: ' + JSON.stringify(message));
        }
        const [type, id, name, args] = message;

        if (type === MESSAGE_TYPES.CALLBACK) {
            DEBUG && console.log(name);
            handlers[name] && this.withCallback(name, id, args);
        } else
        if (type === MESSAGE_TYPES.MESSAGE) {
            DEBUG && console.log(name);
            handlers[name] && setImmediate(() => handlers[name].forEach(cb => cb.call(this, args[0], args[1], args[2], args[3], args[4])));
        } else if (type === MESSAGE_TYPES.PING) {
            ws.send(JSON.stringify([MESSAGE_TYPES.PONG]));
        } else if (type === MESSAGE_TYPES.PONG) {
            // lastPong saved
        } else {
            console.log('Received unknown message type: ' + type)
        }
    });

    this.close = () => {
        pingInterval && clearInterval(pingInterval);
        pingInterval = null;

        handlers.disconnect && handlers.disconnect.forEach(cb => cb.apply(this));

        Object.keys(handlers).forEach(name => handlers[name] = undefined);

        try {
            ws.close();
        } catch (e) {

        }
    }
}

function SocketIO (server) {
    const handlers = {};
    const run = [];

    let socketsList = [];

    const wss = new WebSocket.Server({
        server,
        verifyClient: function(info, done) {
            if (run.length) {
                run.forEach(cb => cb(info.req, err => {
                    if (err) {
                        info.req._wsNotAuth = true;
                    }
                    done && done(true);
                    done = null;
                }));
            } else {
                done && done(true);
                done = null;
            }
        },
        perMessageDeflate: {
			zlibDeflateOptions: {
			chunkSize: 1024,
			memLevel: 9,
			level: 9
			},
			zlibInflateOptions: {
				chunkSize: 16 * 1024
			},
			clientNoContextTakeover: true,
			serverNoContextTakeover: true
		}
    });

    wss.on('connection', (ws, request) => {
        DEBUG && console.log('connected');
        if (request._wsNotAuth) {
            const ip = request.headers['x-forwarded-for'] ||
                request.connection.remoteAddress ||
                request.socket.remoteAddress ||
                (request.connection.socket ? request.connection.socket.remoteAddress : null);
            handlers.error && handlers.error.forEach(cb => cb('error', `authentication failed for ${ip}`));
            ws.send(JSON.stringify([MESSAGE_TYPES.MESSAGE, 401, 'reauthenticate']));
            setTimeout(() =>
                ws && ws.destroy && ws.destroy(), 500);
        } else {
            let query;

            try {
                const queryString = request.url.split('?')[1];
                query = querystring.parse(queryString || '');
            } catch (e) {
                query = null;
            }

            if (query && query.sid) {
                const socket = new Socket(ws, request.sessionID || query.sid, query.name);
                socket.query = query;
                socketsList.push(socket);
                this.sockets.engine.clientsCount = socketsList.length;

                ws.on('close', () => {
                    DEBUG && console.log('closed');
                    let i;
                    for (i = 0; i < socketsList.length; i++) {
                        if (socketsList[i].ws === ws) {
                            socketsList[i].close();
                            socketsList.splice(i, 1);
                            this.sockets.engine.clientsCount = socketsList.length;
                            return;
                        }
                    }
                });

                // install handlers
                if (handlers.connection && handlers.connection.length) {
                    // we have a race condition here.
                    // If the user is not admin it will be requested for him the rights and no handlers will be installed.
                    // So we must be sure, that all event handlers are installed before sending ___ready___.
                    let timeout = setTimeout(() => {
                        timeout = null;
                        socket.emit('___ready___');
                        console.warn('Sent ready, but not all handlers installed!');
                    }, 1500); // TODO, This parameter must be configurable

                    handlers.connection.forEach(cb => cb(socket, () => {
                        if (timeout) {
                            clearTimeout(timeout);
                            timeout = null;
                            // say to client we are ready
                            socket.emit('___ready___');
                        }
                    }));
                } else {
                    socket.emit('___ready___');
                }
            } else {
                const ip = request.headers['x-forwarded-for'] ||
                    request.connection.remoteAddress ||
                    request.socket.remoteAddress ||
                    (request.connection.socket ? request.connection.socket.remoteAddress : null);
                handlers.error && handlers.error.forEach(cb => cb('error', 'No sid found from ' + ip));
                ws.send(JSON.stringify([MESSAGE_TYPES.MESSAGE, 501, 'error', ['invalid sid']]));
                setTimeout(() =>
                    ws && ws.destroy && ws.destroy(), 500);
            }
        }
    });

    this.on = (name, cb) => {
        if (cb) {
            handlers[name] = handlers[name] || [];
            handlers[name].push(cb);
        }
    };

    this.off = (name, cb) => {
        if (handlers[name]) {
            const pos = handlers[name].indexOf(cb);
            if (pos !== -1) {
                handlers[name].splice(pos, 1);
                if (!handlers[name].length) {
                    delete handlers[name];
                }
            }
        }
    };

    this.sockets = {
        connected: socketsList,
        emit: (arg1, arg2, arg3, arg4, arg5) => {
            socketsList.forEach(socket =>
                socket.emit(arg1, arg2, arg3, arg4, arg5));
        },
        engine: {
            clientsCount: 0,
        }
    };

    this.engine = this.sockets.engine;

    this.use = cb => {
        run.push(cb);
        return this;
    };

    this.ioBroker = true;
}

module.exports = {
    listen: server => new SocketIO(server)
};
<|endoftext|>


<commit_before>/*
 Copyright 2016 Aleksandar Jankovic

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

require('../library/polyfills');

const LoginBox = require('../library/view/templates/LoginBox');
const Messenger = require('../library/view/templates/Messenger');
const Time = require('../library/view/templates/Clock');
const OnlineStatus = require('../library/view/templates/OnlineStatus');
const WorldMap = require('../library/view/worldMap/WorldMap');
const DocsViewer = require('../library/view/templates/DocsViewer');
const Home = require('../library/view/templates/Home');
const SoundElement = require('../library/audio/SoundElement');
const Tracker = require('../library/view/worldMap/Tracker');
const Boot = require('../library/view/templates/TextAnimation');

const keyHandler = require('../library/KeyHandler');
const deviceChecker = require('../library/DeviceChecker');
const socketManager = require('../library/SocketManager');
const storageManager = require('../library/StorageManager');
const textTools = require('../library/TextTools');
const viewTools = require('../library/ViewTools');
const eventCentral = require('../library/EventCentral');
const soundLibrary = require('../library/audio/SoundLibrary');

const mainView = document.getElementById('main');
const top = document.getElementById('top');
const onlineStatus = new OnlineStatus(document.getElementById('onlineStatus'));
const tracker = new Tracker();

const boot = new Boot({ removeTime: 4000 });
boot.setQueue([
  { func: boot.addCode, params: { iteration: 0, maxIteration: 12, row: 0, maxRows: 2 } },
  {
    func: boot.printLines,
    params: {
      code: true,
      classes: 'logo',
      array: [
        '                          ####',
        '                ####    #########    ####',
        '               ###########################',
        '              #############################',
        '            #######        ##   #  ##########',
        '      ##########           ##    #  ###  ##########',
        '     #########             #########   #   #########',
        '       #####               ##     ########   #####',
        '     #####                 ##     ##     ##########',
        '     ####                  ##      ##     #   ######',
        ' #######                   ##########     ##    ########',
        '########                   ##       ########     ########',
        ' ######      Organica      ##       #      #############',
        '   ####     Oracle         ##       #      ##     ####',
        '   ####     Operations     ##       #      ##    #####',
        '   ####      Center        ##       #      ###########',
        '########                   ##       #########    ########',
        '########                   ##########      #    #########',
        ' ########                  ##      ##     ## ###########',
        '     #####                 ##      ##     ### #####',
        '       #####               ##     ########   #####',
        '      #######              ##########   #  ########',
        '     ###########           ##    ##    # ###########',
        '      #############        ##    #   #############',
        '            ################################',
        '              ############################',
        '              #######  ##########  #######',
        '                ###      ######      ###',
        '                          ####',
      ],
    },
  },
  {
    func: boot.printLines,
    params: {
      code: false,
      array: [
        'Welcome to the Oracle, employee UNDEFINED.',
        'May you have a productive day!',
        '',
        'Establishing uplink to relays',
      ],
    },
  },
  { func: boot.addCode, params: { iteration: 0, maxIteration: 12, row: 0, maxRows: 4, binary: true } },
  {
    func: boot.printLines,
    params: {
      code: false,
      array: [
        'Uplink established',
        'Booting OOC 5.0',
      ],
    },
  },
  {
    func: boot.printLines,
    params: {
      classes: 'logo',
      code: false,
      array: [
        'THIS RELEASE OF OOC WAS BROUGHT TO YOU BY',
        '   ####',
        '###############',
        ' #####  #########                                           ####',
        '  ####     #######  ########     ###########    ####     ###########',
        '  ####    ######      #######   ####   #####  ########    ####   #####',
        '  ####  ###         ####  ####        ####  ###    ###### ####   #####',
        '  #########        ####    ####     ####   #####     ##############',
        '  #### ######     ####     #####  ####     #######   ###  ########',
        '  ####   ######  ##### #### #### ############  #######    ####   ###',
        ' ######    #############    ################     ###      ####    #####',
        '########     ########        ####                        ######      #####   ##',
        '               ###########        ##                                    ###### ',
        '                    ###############',
        '                  Razor  #####  Demos - Warez - Honey',
        'ENJOY',
      ],
    },
  },
  {
    func: boot.printLines,
    params: {
      code: false,
      array: [
        'Loading',
        '...',
        '...',
        '...',
        '...',
        '...',
      ],
    },
  },
]);
// boot.appendTo(mainView);

tracker.startTracker();
soundLibrary.toggleSounds();

if (storageManager.getDeviceId() === null) {
  storageManager.setDeviceId(textTools.createAlphaNumbericalString(16, false));
}

window.addEventListener('error', (event) => {
  console.log(event.error);

  return false;
});

const home = new Home();
const messenger = new Messenger({ isFullscreen: true, sendButtonText: 'Send', isTopDown: false });
const docsViewer = new DocsViewer({ isFullscreen: true });
const map = new WorldMap({
  mapView: WorldMap.MapViews.OVERVIEW,
  clusterStyle: {
    gridSize: 24,
    maxZoom: 17,
    zoomOnClick: false,
    singleSize: true,
    averageCenter: true,
    styles: [{
      width: 24,
      height: 24,
      iconAnchor: [12, 12],
      textSize: 12,
      url: 'images/mapcluster.png',
      textColor: '00ffcc',
      fontFamily: 'monospace',
    }],
  },
  mapStyles: [
    {
      featureType: 'all',
      elementType: 'all',
      stylers: [
        { color: '#11000f' },
      ],
    }, {
      featureType: 'road',
      elementType: 'geometry',
      stylers: [
        { color: '#00ffcc' },
      ],
    }, {
      featureType: 'road',
      elementType: 'labels',
      stylers: [
        { visibility: 'off' },
      ],
    }, {
      featureType: 'poi',
      elementType: 'all',
      stylers: [
        { visibility: 'off' },
      ],
    }, {
      featureType: 'administrative',
      elementType: 'all',
      stylers: [
        { visibility: 'off' },
      ],
    }, {
      featureType: 'water',
      elementType: 'all',
      stylers: [
        { color: '#ff02e5' },
      ],
    },
  ],
  labelStyle: {
    fontFamily: 'monospace',
    fontColor: '#00ffcc',
    strokeColor: '#001e15',
    fontSize: 12,
  },
  mapBackground: '#11000f',
});

soundLibrary.addSound(new SoundElement({ path: '/sounds/msgReceived.wav', soundId: 'msgReceived' }));
soundLibrary.addSound(new SoundElement({ path: '/sounds/button.wav', soundId: 'button', volume: 0.7 }));
soundLibrary.addSound(new SoundElement({ path: '/sounds/button2.wav', soundId: 'button2' }));
soundLibrary.addSound(new SoundElement({ path: '/sounds/fail.wav', soundId: 'fail' }));
soundLibrary.addSound(new SoundElement({ path: '/sounds/keyInput.wav', soundId: 'keyInput', multi: true }));
soundLibrary.addSound(new SoundElement({ path: '/sounds/topBar.wav', soundId: 'topBar' }));

mainView.addEventListener('contextmenu', (event) => {
  event.preventDefault();
});

top.addEventListener('click', () => {
  home.appendTo(mainView);
});
keyHandler.addKey(32, () => { home.appendTo(mainView); });

if (deviceChecker.deviceType === deviceChecker.DeviceEnum.IOS) {
  if (!viewTools.isLandscape()) {
    top.classList.add('appleMenuFix');
  }

  window.addEventListener('orientationchange', () => {
    if (viewTools.isLandscape()) {
      top.classList.remove('appleMenuFix');
    } else {
      top.classList.add('appleMenuFix');
    }
  });
}

eventCentral.addWatcher({
  watcherParent: this,
  event: eventCentral.Events.LOGOUT,
  func: () => {
    storageManager.removeUser();
    storageManager.setRoom('');
    eventCentral.triggerEvent({ event: eventCentral.Events.USER });
  },
});

eventCentral.addWatcher({
  watcherParent: this,
  event: eventCentral.Events.LOGIN,
  func: () => {
    eventCentral.triggerEvent({ event: eventCentral.Events.USER });
  },
});

eventCentral.addWatcher({
  watcherParent: messenger,
  event: eventCentral.Events.CHATMSG,
  func: () => { soundLibrary.playSound('msgReceived'); },
});

eventCentral.triggerEvent({
  event: eventCentral.Events.SWITCHROOM,
  params: { room: storageManager.getRoom() },
});

keyHandler.addKey(112, viewTools.goFullScreen);

window.addEventListener('click', () => {
  viewTools.goFullScreen();
});

if (!storageManager.getUserName()) {
  eventCentral.triggerEvent({ event: eventCentral.Events.LOGOUT });
}

home.addLink({
  linkName: 'Coms',
  startFunc: () => { messenger.appendTo(mainView); },
  endFunc: () => { messenger.removeView(); },
});
home.addLink({
  linkName: 'Map',
  startFunc: () => { map.appendTo(mainView); },
  endFunc: () => { map.removeView(); },
});
home.addLink({
  linkName: 'Docs',
  startFunc: () => { docsViewer.appendTo(mainView); },
  endFunc: () => { docsViewer.removeView(); },
});
home.addLink({
  linkName: 'Login',
  startFunc: () => {
    new LoginBox({
      description: ['Welcome, employee! You have to login to begin your productive day!', 'All your actions in O3C will be monitored'],
      extraDescription: ['Input your user name and password'],
      parentElement: mainView,
      socketManager,
      keyHandler,
    }).appendTo(mainView);
  },
  endFunc: () => {},
  accessLevel: 0,
  maxAccessLevel: 0,
  keepHome: true,
  classes: ['hide'],
});
home.addLink({
  linkName: 'Logout',
  startFunc: () => {
    socketManager.emitEvent('logout', {}, (error) => {
      if (error) {
        console.log(error);
      }

      eventCentral.triggerEvent({ event: eventCentral.Events.LOGOUT });
    });
  },
  endFunc: () => {},
  accessLevel: 1,
  keepHome: true,
  classes: ['hide'],
});
home.appendTo(mainView);

map.setCornerCoordinates(storageManager.getCornerOneCoordinates(), storageManager.getCornerTwoCoordinates());
map.setCenterCoordinates(storageManager.getCenterCoordinates());
map.setDefaultZoomLevel(storageManager.getDefaultZoomlevel());

socketManager.addEvents([
  {
    event: 'disconnect',
    func: () => {
      onlineStatus.setOffline();
    },
  }, {
    event: 'reconnect',
    func: () => {
      onlineStatus.setOnline();
      socketManager.reconnectDone();
    },
  }, {
    event: 'startup',
    func: ({ yearModification, centerLat, centerLong, cornerOneLat, cornerOneLong, cornerTwoLat, cornerTwoLong, defaultZoomLevel }) => {
      storageManager.setYearModification(yearModification);
      storageManager.setCenterCoordinates(centerLong, centerLat);
      storageManager.setCornerOneCoordinates(cornerOneLong, cornerOneLat);
      storageManager.setCornerTwoCoordinates(cornerTwoLong, cornerTwoLat);
      storageManager.setDefaultZoomLevel(defaultZoomLevel);
      onlineStatus.setOnline();

      if (!socketManager.hasConnected) {
        new Time(document.getElementById('time')).startClock();
        map.setCornerCoordinates(storageManager.getCornerOneCoordinates(), storageManager.getCornerTwoCoordinates());
        map.setCenterCoordinates(storageManager.getCenterCoordinates());
        map.setDefaultZoomLevel(storageManager.getDefaultZoomlevel());
      }

      socketManager.emitEvent('updateId', {
        user: { userName: storageManager.getUserName() },
        device: { deviceId: storageManager.getDeviceId() },
      }, ({ error, data = {} }) => {
        if (error) {
          return;
        }

        const userName = storageManager.getUserName();

        if ((userName && data.anonUser) || data.anonUser) {
          storageManager.removeUser();
          storageManager.setAccessLevel(0);
        } else {
          storageManager.setAccessLevel(data.user.accessLevel);
          eventCentral.triggerEvent({ event: eventCentral.Events.ALIAS, params: { aliases: data.user.aliases } });
        }

        eventCentral.triggerEvent({ event: eventCentral.Events.USER, params: { changedUser: userName !== data.user.userName } });
        socketManager.setConnected();
      });
    },
  }, {
    event: 'message',
    func: ({ message }) => {
      console.log(message);
    },
  }, {
    event: 'chatMsgs',
    func: ({ messages }) => {
      eventCentral.triggerEvent({ event: eventCentral.Events.CHATMSG, params: { messages, options: { printable: false } } });
    },
  }, {
    event: 'archive',
    func: ({ archive }) => {
      eventCentral.triggerEvent({ event: eventCentral.Events.ARCHIVE, params: { archive } });
    },
  }, {
    event: 'logout',
    func: () => {
      eventCentral.triggerEvent({ event: eventCentral.Events.USER, params: {} });
    },
  },
]);
<commit_msg>Boot animation runs at start<commit_after>/*
 Copyright 2016 Aleksandar Jankovic

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

require('../library/polyfills');

const LoginBox = require('../library/view/templates/LoginBox');
const Messenger = require('../library/view/templates/Messenger');
const Time = require('../library/view/templates/Clock');
const OnlineStatus = require('../library/view/templates/OnlineStatus');
const WorldMap = require('../library/view/worldMap/WorldMap');
const DocsViewer = require('../library/view/templates/DocsViewer');
const Home = require('../library/view/templates/Home');
const SoundElement = require('../library/audio/SoundElement');
const Tracker = require('../library/view/worldMap/Tracker');
const Boot = require('../library/view/templates/TextAnimation');

const keyHandler = require('../library/KeyHandler');
const deviceChecker = require('../library/DeviceChecker');
const socketManager = require('../library/SocketManager');
const storageManager = require('../library/StorageManager');
const textTools = require('../library/TextTools');
const viewTools = require('../library/ViewTools');
const eventCentral = require('../library/EventCentral');
const soundLibrary = require('../library/audio/SoundLibrary');

const mainView = document.getElementById('main');
const top = document.getElementById('top');
const onlineStatus = new OnlineStatus(document.getElementById('onlineStatus'));
const tracker = new Tracker();

const boot = new Boot({ removeTime: 4000 });
boot.setQueue([
  { func: boot.addCode, params: { iteration: 0, maxIteration: 12, row: 0, maxRows: 2 } },
  {
    func: boot.printLines,
    params: {
      code: true,
      classes: 'logo',
      array: [
        '                          ####',
        '                ####    #########    ####',
        '               ###########################',
        '              #############################',
        '            #######        ##   #  ##########',
        '      ##########           ##    #  ###  ##########',
        '     #########             #########   #   #########',
        '       #####               ##     ########   #####',
        '     #####                 ##     ##     ##########',
        '     ####                  ##      ##     #   ######',
        ' #######                   ##########     ##    ########',
        '########                   ##       ########     ########',
        ' ######      Organica      ##       #      #############',
        '   ####     Oracle         ##       #      ##     ####',
        '   ####     Operations     ##       #      ##    #####',
        '   ####      Center        ##       #      ###########',
        '########                   ##       #########    ########',
        '########                   ##########      #    #########',
        ' ########                  ##      ##     ## ###########',
        '     #####                 ##      ##     ### #####',
        '       #####               ##     ########   #####',
        '      #######              ##########   #  ########',
        '     ###########           ##    ##    # ###########',
        '      #############        ##    #   #############',
        '            ################################',
        '              ############################',
        '              #######  ##########  #######',
        '                ###      ######      ###',
        '                          ####',
      ],
    },
  },
  {
    func: boot.printLines,
    params: {
      code: false,
      array: [
        'Welcome to the Oracle, employee UNDEFINED.',
        'May you have a productive day!',
        '',
        'Establishing uplink to relays',
      ],
    },
  },
  { func: boot.addCode, params: { iteration: 0, maxIteration: 12, row: 0, maxRows: 4, binary: true } },
  {
    func: boot.printLines,
    params: {
      code: false,
      array: [
        'Uplink established',
        'Booting OOC 5.0',
      ],
    },
  },
  {
    func: boot.printLines,
    params: {
      classes: 'logo',
      code: false,
      array: [
        'THIS RELEASE OF OOC WAS BROUGHT TO YOU BY',
        '   ####',
        '###############',
        ' #####  #########                                           ####',
        '  ####     #######  ########     ###########    ####     ###########',
        '  ####    ######      #######   ####   #####  ########    ####   #####',
        '  ####  ###         ####  ####        ####  ###    ###### ####   #####',
        '  #########        ####    ####     ####   #####     ##############',
        '  #### ######     ####     #####  ####     #######   ###  ########',
        '  ####   ######  ##### #### #### ############  #######    ####   ###',
        ' ######    #############    ################     ###      ####    #####',
        '########     ########        ####                        ######      #####   ##',
        '               ###########        ##                                    ###### ',
        '                    ###############',
        '                  Razor  #####  Demos - Warez - Honey',
        'ENJOY',
      ],
    },
  },
  {
    func: boot.printLines,
    params: {
      code: false,
      array: [
        'Loading',
        '...',
        '...',
        '...',
        '...',
        '...',
      ],
    },
  },
]);
boot.appendTo(mainView);

tracker.startTracker();
soundLibrary.toggleSounds();

if (storageManager.getDeviceId() === null) {
  storageManager.setDeviceId(textTools.createAlphaNumbericalString(16, false));
}

window.addEventListener('error', (event) => {
  console.log(event.error);

  return false;
});

const home = new Home();
const messenger = new Messenger({ isFullscreen: true, sendButtonText: 'Send', isTopDown: false });
const docsViewer = new DocsViewer({ isFullscreen: true });
const map = new WorldMap({
  mapView: WorldMap.MapViews.OVERVIEW,
  clusterStyle: {
    gridSize: 24,
    maxZoom: 17,
    zoomOnClick: false,
    singleSize: true,
    averageCenter: true,
    styles: [{
      width: 24,
      height: 24,
      iconAnchor: [12, 12],
      textSize: 12,
      url: 'images/mapcluster.png',
      textColor: '00ffcc',
      fontFamily: 'monospace',
    }],
  },
  mapStyles: [
    {
      featureType: 'all',
      elementType: 'all',
      stylers: [
        { color: '#11000f' },
      ],
    }, {
      featureType: 'road',
      elementType: 'geometry',
      stylers: [
        { color: '#00ffcc' },
      ],
    }, {
      featureType: 'road',
      elementType: 'labels',
      stylers: [
        { visibility: 'off' },
      ],
    }, {
      featureType: 'poi',
      elementType: 'all',
      stylers: [
        { visibility: 'off' },
      ],
    }, {
      featureType: 'administrative',
      elementType: 'all',
      stylers: [
        { visibility: 'off' },
      ],
    }, {
      featureType: 'water',
      elementType: 'all',
      stylers: [
        { color: '#ff02e5' },
      ],
    },
  ],
  labelStyle: {
    fontFamily: 'monospace',
    fontColor: '#00ffcc',
    strokeColor: '#001e15',
    fontSize: 12,
  },
  mapBackground: '#11000f',
});

soundLibrary.addSound(new SoundElement({ path: '/sounds/msgReceived.wav', soundId: 'msgReceived' }));
soundLibrary.addSound(new SoundElement({ path: '/sounds/button.wav', soundId: 'button', volume: 0.7 }));
soundLibrary.addSound(new SoundElement({ path: '/sounds/button2.wav', soundId: 'button2' }));
soundLibrary.addSound(new SoundElement({ path: '/sounds/fail.wav', soundId: 'fail' }));
soundLibrary.addSound(new SoundElement({ path: '/sounds/keyInput.wav', soundId: 'keyInput', multi: true }));
soundLibrary.addSound(new SoundElement({ path: '/sounds/topBar.wav', soundId: 'topBar' }));

mainView.addEventListener('contextmenu', (event) => {
  event.preventDefault();
});

top.addEventListener('click', () => {
  home.appendTo(mainView);
});
keyHandler.addKey(32, () => { home.appendTo(mainView); });

if (deviceChecker.deviceType === deviceChecker.DeviceEnum.IOS) {
  if (!viewTools.isLandscape()) {
    top.classList.add('appleMenuFix');
  }

  window.addEventListener('orientationchange', () => {
    if (viewTools.isLandscape()) {
      top.classList.remove('appleMenuFix');
    } else {
      top.classList.add('appleMenuFix');
    }
  });
}

eventCentral.addWatcher({
  watcherParent: this,
  event: eventCentral.Events.LOGOUT,
  func: () => {
    storageManager.removeUser();
    storageManager.setRoom('');
    eventCentral.triggerEvent({ event: eventCentral.Events.USER });
  },
});

eventCentral.addWatcher({
  watcherParent: this,
  event: eventCentral.Events.LOGIN,
  func: () => {
    eventCentral.triggerEvent({ event: eventCentral.Events.USER });
  },
});

eventCentral.addWatcher({
  watcherParent: messenger,
  event: eventCentral.Events.CHATMSG,
  func: () => { soundLibrary.playSound('msgReceived'); },
});

eventCentral.triggerEvent({
  event: eventCentral.Events.SWITCHROOM,
  params: { room: storageManager.getRoom() },
});

keyHandler.addKey(112, viewTools.goFullScreen);

window.addEventListener('click', () => {
  viewTools.goFullScreen();
});

if (!storageManager.getUserName()) {
  eventCentral.triggerEvent({ event: eventCentral.Events.LOGOUT });
}

home.addLink({
  linkName: 'Coms',
  startFunc: () => { messenger.appendTo(mainView); },
  endFunc: () => { messenger.removeView(); },
});
home.addLink({
  linkName: 'Map',
  startFunc: () => { map.appendTo(mainView); },
  endFunc: () => { map.removeView(); },
});
home.addLink({
  linkName: 'Docs',
  startFunc: () => { docsViewer.appendTo(mainView); },
  endFunc: () => { docsViewer.removeView(); },
});
home.addLink({
  linkName: 'Login',
  startFunc: () => {
    new LoginBox({
      description: ['Welcome, employee! You have to login to begin your productive day!', 'All your actions in O3C will be monitored'],
      extraDescription: ['Input your user name and password'],
      parentElement: mainView,
      socketManager,
      keyHandler,
    }).appendTo(mainView);
  },
  endFunc: () => {},
  accessLevel: 0,
  maxAccessLevel: 0,
  keepHome: true,
  classes: ['hide'],
});
home.addLink({
  linkName: 'Logout',
  startFunc: () => {
    socketManager.emitEvent('logout', {}, (error) => {
      if (error) {
        console.log(error);
      }

      eventCentral.triggerEvent({ event: eventCentral.Events.LOGOUT });
    });
  },
  endFunc: () => {},
  accessLevel: 1,
  keepHome: true,
  classes: ['hide'],
});
home.appendTo(mainView);

map.setCornerCoordinates(storageManager.getCornerOneCoordinates(), storageManager.getCornerTwoCoordinates());
map.setCenterCoordinates(storageManager.getCenterCoordinates());
map.setDefaultZoomLevel(storageManager.getDefaultZoomlevel());

socketManager.addEvents([
  {
    event: 'disconnect',
    func: () => {
      onlineStatus.setOffline();
    },
  }, {
    event: 'reconnect',
    func: () => {
      onlineStatus.setOnline();
      socketManager.reconnectDone();
    },
  }, {
    event: 'startup',
    func: ({ yearModification, centerLat, centerLong, cornerOneLat, cornerOneLong, cornerTwoLat, cornerTwoLong, defaultZoomLevel }) => {
      storageManager.setYearModification(yearModification);
      storageManager.setCenterCoordinates(centerLong, centerLat);
      storageManager.setCornerOneCoordinates(cornerOneLong, cornerOneLat);
      storageManager.setCornerTwoCoordinates(cornerTwoLong, cornerTwoLat);
      storageManager.setDefaultZoomLevel(defaultZoomLevel);
      onlineStatus.setOnline();

      if (!socketManager.hasConnected) {
        new Time(document.getElementById('time')).startClock();
        map.setCornerCoordinates(storageManager.getCornerOneCoordinates(), storageManager.getCornerTwoCoordinates());
        map.setCenterCoordinates(storageManager.getCenterCoordinates());
        map.setDefaultZoomLevel(storageManager.getDefaultZoomlevel());
      }

      socketManager.emitEvent('updateId', {
        user: { userName: storageManager.getUserName() },
        device: { deviceId: storageManager.getDeviceId() },
      }, ({ error, data = {} }) => {
        if (error) {
          return;
        }

        const userName = storageManager.getUserName();

        if ((userName && data.anonUser) || data.anonUser) {
          storageManager.removeUser();
          storageManager.setAccessLevel(0);
        } else {
          storageManager.setAccessLevel(data.user.accessLevel);
          eventCentral.triggerEvent({ event: eventCentral.Events.ALIAS, params: { aliases: data.user.aliases } });
        }

        eventCentral.triggerEvent({ event: eventCentral.Events.USER, params: { changedUser: userName !== data.user.userName } });
        socketManager.setConnected();
      });
    },
  }, {
    event: 'message',
    func: ({ message }) => {
      console.log(message);
    },
  }, {
    event: 'chatMsgs',
    func: ({ messages }) => {
      eventCentral.triggerEvent({ event: eventCentral.Events.CHATMSG, params: { messages, options: { printable: false } } });
    },
  }, {
    event: 'archive',
    func: ({ archive }) => {
      eventCentral.triggerEvent({ event: eventCentral.Events.ARCHIVE, params: { archive } });
    },
  }, {
    event: 'logout',
    func: () => {
      eventCentral.triggerEvent({ event: eventCentral.Events.USER, params: {} });
    },
  },
]);
<|endoftext|>


<commit_before>var fs = require('fs');
const debug = require('debug')('doc-processor-server')
var execSync = require('child_process').execSync;

const downloadHelper = function download(processor,filetype,hash, dlname, conf, res, next) {
    let jobdir = conf.tmpFolder +"/job-"+ processor + "-" + hash;
    var filepath=jobdir+'/out.'+filetype;
    fs.readFile(filepath, function (err, data) {
        if (err) {
            let e = {
                code: 404,
                message: "Could not find the file."
            };
            res.writeHead(e.code);
            res.end(e.message);
            next(e);
            return;
        }
        // "Content-Disposition": "attachment;filename=" + dlname + "."+filetype,
        res.writeHead(200, {
            "Content-Disposition":"filename=" + dlname + "."+filetype,
            "Content-Type":"application/"+filetype
        });
        res.end(data);
        if (!conf.keepFilesForDebugging ) {
            debug("remove " + jobdir);
            execSync("rm -rf  " + jobdir);
        }
        return next();
    });
}
exports.downloadHelper = downloadHelper;<commit_msg>added more headers to the download request to prevent errors on the downloading system (till no no succuess)<commit_after>var fs = require('fs');
const debug = require('debug')('doc-processor-server')
var execSync = require('child_process').execSync;

const downloadHelper = function download(processor,filetype,hash, dlname, conf, res, next) {
    let jobdir = conf.tmpFolder +"/job-"+ processor + "-" + hash;
    var filepath=jobdir+'/out.'+filetype;
    fs.readFile(filepath, function (err, data) {
        if (err) {
            let e = {
                code: 404,
                message: "Could not find the file."
            };
            res.writeHead(e.code);
            res.end(e.message);
            next(e);
            return;
        }
        // "Content-Disposition": "attachment;filename=" + dlname + "."+filetype,
        res.writeHead(200, {
           "Content-Disposition":"filename=" + dlname + "."+filetype,
           "Cache-Control":"public, max-age=0",
           "Accept-Ranges":"bytes",
           "Content-Type":"application/"+filetype,
           "Content-Length":Buffer.byteLength(data, 'utf-8')

        });
        res.end(data);
        if (!conf.keepFilesForDebugging ) {
            debug("remove " + jobdir);
            execSync("rm -rf  " + jobdir);
        }
        return next();
    });
}
exports.downloadHelper = downloadHelper;<|endoftext|>


<commit_before>module.exports = {
  'secret': proccess.env.PASSPORT_KEY,
  'database': process.env.MONGO_DB
}
<commit_msg>Fix typo.<commit_after>module.exports = {
  'secret': process.env.PASSPORT_KEY,
  'database': process.env.MONGO_DB
}
<|endoftext|>


<commit_before>/* File: images.js
 *
 * Copyright (c) 2014
 * Centre National d’Enseignement à Distance (Cned), Boulevard Nicephore Niepce, 86360 CHASSENEUIL-DU-POITOU, France
 * (direction-innovation@cned.fr)
 *
 * GNU Affero General Public License (AGPL) version 3.0 or later version
 *
 * This file is part of a program which is free software: you can
 * redistribute it and/or modify it under the terms of the
 * GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this program.
 * If not, see <http://www.gnu.org/licenses/>.
 *
 */

'use strict';

// Require helpers
var helper = require('../helpers/helpers');

//
// var docStructureDao = require('../dao/docStructure');

var numberCalls = 0;
var sourcesUpload = [];
var counter = 0;

/**
 * Crop Image
 */
exports.cropImage = function(req, res) {

	var extension = helper.getFileExtension(req.body.DataCrop.srcImg);
	var source = req.body.DataCrop.srcImg;
	var targetImage = './files/decoup.thumb_' + Math.random() + extension;

	/* Crop image with ImageMagick */
	var exec = require('child_process').exec;
	exec('convert ' + source + ' +repage -density 450 -crop ' + req.body.DataCrop.w + 'x' + req.body.DataCrop.h + '+' + req.body.DataCrop.x + '+' + req.body.DataCrop.y + ' ' + targetImage, function(err, stdout, stderr) {
		console.log(stderr);
		console.log(stdout);
		if (err) {
			throw err;
		} else {
			return res.jsonp({
				source: targetImage,
				order: req.body.DataCrop.order
			});
		}
	});
};

/* Based on node-teseract module*/
exports.oceriser = function(req, res) {

	var exec = require('child_process').exec;
	var fs = require('fs');
	var crypto = require('crypto');

	var image = './' + req.body.sourceImage;
	var date = new Date().getTime();
	var output = crypto.createHash('md5').update(image + date).digest('hex') + '.tif';

	// exec('convert ' + image + ' -type Grayscale ' + output, function(err) {

	// 	fs.exists(output, function(exists) {
	// 		if (exists) {
	// 			return 'File is there';
	// 		} else {
	// 			return 'File is not there';
	// 		}
	// 		return 'error';
	// 	});

	// 	if (err) throw err;
		//console.log("tesseract " + output + " " + output + " -psm 047"); tesseract image.png out -l fra
		// 'tesseract ' + output + ' ' + output + ' -l fra'
		exec('tesseract ' + image + ' ' + output + ' -l fra', function(errTess) {
			if (errTess) {
				throw errTess;
			}
			fs.readFile(output + '.txt', function(err, data) {
				if (err) throw err;
				// text = data.toString('utf8').replace(/\W/g, ' ');
				var text = data.toString('utf8');
				res.jsonp(text);
				// fs.unlink(output + '.txt', function(err) {
				// 	if (err) throw err;
				// 	fs.unlink(output, function(err) {
				// 		if (err) {
				// 			throw err;
				// 		}
				// 	});
				// });
			});
		});
	// });

};

/* Upload Files */
exports.uploadFiles = function(req, res) {

	var fs = require('fs');
	var filesToUpload = [];
	sourcesUpload = [];
	counter = 0;

	if (!req.files.uploadedFile.length) {
		filesToUpload.push(req.files.uploadedFile);
		numberCalls = 1;
	} else {
		for (var i = 0; i < req.files.uploadedFile.length; i++) {
			filesToUpload.push(req.files.uploadedFile[i]);
		}
		numberCalls = filesToUpload.length;
	}

	// parcourir la liste des fichiers a uploader
	for (var k = 0; k < filesToUpload.length; k++) {

		var currentFile = filesToUpload[k];
		// Detect file type
		var extension = helper.getFileExtension(filesToUpload[k].originalFilename);

		var newPath = './files/file-' + Math.random() + extension;

		// Ouvrir et ecrire les fichier uploadés de meniere synchronous
		var fileReaded = fs.readFileSync(filesToUpload[k].path);
		var fileWrited = fs.writeFileSync(newPath, fileReaded);
		if (extension === '.pdf') {
			// (if PDF convert to JPEGs)
			/*return number pages of PDF*/
			exports.getNumberPagesPDF(newPath, extension, res);
			// exports.convertsPdfToPng(newPath, res);
		} else if (extension === '.jpg' || extension === '.jpeg') {
			// (if PDF convert to JPEGs)
			exports.convertsJpegToPng(newPath, res);
		} else {
			sourcesUpload.push({
				path: newPath,
				extension: extension
			});
			counter += 1;
			if (numberCalls === counter) {
				return res.jsonp(sourcesUpload);
			}
		}
	}
};

/* Get number pages of PDF */
exports.getNumberPagesPDF = function(filePath, extension, res) {
	var exec = require('child_process').exec;
	exec('gs  -c "(' + filePath + ') (r) file runpdfbegin pdfpagecount = quit"', function(error, stdout) {
		if (error) {
			return error;
		}
		var numbPages = stdout.split('\n')[3];
		sourcesUpload.push({
			path: filePath,
			extension: extension,
			numberPages: numbPages
		});
		res.jsonp(sourcesUpload);
	});
};

/* Convert PDF to JPEG */
exports.convertsPdfToPng = function(req, res) {

	//console.log(req.body.pdfData);

	var exec = require('child_process').exec;
	var imageFileName = req.body.pdfData.source.substr(0, req.body.pdfData.source.lastIndexOf('.')) + Math.random();
	var imageConverted = imageFileName + '[' + req.body.pdfData.page + ']' + '.png';

	// Render image with imagemagick
	exec('convert -geometry 595x842 -density 450 ' + req.body.pdfData.source + '[' + req.body.pdfData.page + '] -background white -alpha remove -alpha off ' + imageConverted, function(error) {
		if (error !== null) {
			console.log(error);
			return 'error';
		} else {
			// console.log('[Done] Conversion from PDF to JPEG image' + imageFileName + '.jpg');

			return res.jsonp({
				path: imageConverted,
				extension: '.png'
			});

			// Get converted files by Command
			/*exec('ls files | grep  ' + imageFileName.substr(8, imageFileName.length), function(errorls, stdoutls) {

				if (errorls !== null) {
					console.log(errorls);
					return 'error';
				}

				var files = stdoutls.replace(/\n/g, ' ').split(' ');
				for (var i = 0; i < files.length; i++) {
					if (files[i] !== '') {
						sourcesUpload.push('./files/' + files[i]);
					}
				}
				counter += 1;
				if (numberCalls === counter) {
					return res.jsonp(sourcesUpload);
				}

			});*/
		}
	});
};

exports.convertsJpegToPng = function(source, res) {

	var exec = require('child_process').exec;
	var imageFileName = source.substr(0, source.lastIndexOf('.')) + Math.random();

	// Render image with imagemagick
	exec('convert ' + source + ' ' + imageFileName + '.png', function(error) {
		if (error !== null) {
			console.log(error);
			return 'error';
		} else {
			// console.log('[Done] Conversion from PDF to JPEG image' + imageFileName + '.jpg');
			//
			sourcesUpload.push({
				path: imageFileName + '.png',
				extension: '.png'
			});
			counter += 1;
			if (numberCalls === counter) {
				return res.jsonp(sourcesUpload);
			}
		}
	});
};

/*Text to speech*/
exports.textToSpeech = function(req, res) {
	var exec = require('child_process').exec;

	var fileName = './files/audio/mp3/audio_' + Math.random() + '.mp3';

	var tmpStr = req.body.text;

	// text to speech using espeak API
	exec('espeak -v french -s 110 "' + tmpStr + '" && espeak -v french -s 110 "' + tmpStr + '" --stdout | lame - ' + fileName, function(error) {
		if (error !== null) {
			console.log(error);
		} else {
			res.jsonp(fileName);
		}

	});
};

/*Festival Demo Text to speech*/
exports.festivalTextToSpeech = function(req, res) {
	var exec = require('child_process').exec;

	var tmpStr = req.body.texte;

	exec('echo \'' + tmpStr + '\'  | festival --tts ', function(error) {
		if (error !== null) {
			console.log(error);
		} else {
			res.jsonp('[Done] festival');
		}

	});
};

/*Espeak Demo Text to speech*/
exports.espeakTextToSpeech = function(req, res) {
	var exec = require('child_process').exec;

	var tmpStr = req.body.text;

	// text to speech using espeak API
	exec('espeak -v french \'' + tmpStr + '\' ', function(error) {
		if (error !== null) {
			console.log(error);
		} else {
			res.jsonp(200);
			//console.log('[Done] espeak');
		}

	});
};<commit_msg>Exception OCR<commit_after>/* File: images.js
 *
 * Copyright (c) 2014
 * Centre National d’Enseignement à Distance (Cned), Boulevard Nicephore Niepce, 86360 CHASSENEUIL-DU-POITOU, France
 * (direction-innovation@cned.fr)
 *
 * GNU Affero General Public License (AGPL) version 3.0 or later version
 *
 * This file is part of a program which is free software: you can
 * redistribute it and/or modify it under the terms of the
 * GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this program.
 * If not, see <http://www.gnu.org/licenses/>.
 *
 */

'use strict';

// Require helpers
var helper = require('../helpers/helpers');

//
// var docStructureDao = require('../dao/docStructure');

var numberCalls = 0;
var sourcesUpload = [];
var counter = 0;

/**
 * Crop Image
 */
exports.cropImage = function(req, res) {

	var extension = helper.getFileExtension(req.body.DataCrop.srcImg);
	var source = req.body.DataCrop.srcImg;
	var targetImage = './files/decoup.thumb_' + Math.random() + extension;

	/* Crop image with ImageMagick */
	var exec = require('child_process').exec;
	exec('convert ' + source + ' +repage -density 450 -crop ' + req.body.DataCrop.w + 'x' + req.body.DataCrop.h + '+' + req.body.DataCrop.x + '+' + req.body.DataCrop.y + ' ' + targetImage, function(err, stdout, stderr) {
		console.log(stderr);
		console.log(stdout);
		if (err) {
			throw err;
		} else {
			return res.jsonp({
				source: targetImage,
				order: req.body.DataCrop.order
			});
		}
	});
};

/* Based on node-teseract module*/
exports.oceriser = function(req, res) {

	var exec = require('child_process').exec;
	var fs = require('fs');
	var crypto = require('crypto');

	var image = './' + req.body.sourceImage;
	var date = new Date().getTime();
	var output = crypto.createHash('md5').update(image + date).digest('hex') + '.tif';

	exec('convert ' + image + ' -type Grayscale ' + output, function(err) {

		fs.exists(output, function(exists) {
			if (exists) {
				return 'File is there';
			} else {
				return 'File is not there';
			}
			return 'error';
		});

		if (err) {
			throw err;
		}
		//console.log("tesseract " + output + " " + output + " -psm 047"); tesseract image.png out -l fra
		// 'tesseract ' + output + ' ' + output + ' -l fra'
		exec('tesseract ' + image + ' ' + output + ' -l fra', function(errTess) {
			if (errTess) {
				throw errTess;
			}
			fs.readFile(output + '.txt', function(err, data) {
				if (err) throw err;
				// text = data.toString('utf8').replace(/\W/g, ' ');
				var text = data.toString('utf8');
				res.jsonp(text);
				fs.unlink(output + '.txt', function(err) {
					if (err) throw err;
					fs.unlink(output, function(err) {
						if (err) {
							throw err;
						}
					});
				});
			});
		});
	});

};

/* Upload Files */
exports.uploadFiles = function(req, res) {

	var fs = require('fs');
	var filesToUpload = [];
	sourcesUpload = [];
	counter = 0;

	if (!req.files.uploadedFile.length) {
		filesToUpload.push(req.files.uploadedFile);
		numberCalls = 1;
	} else {
		for (var i = 0; i < req.files.uploadedFile.length; i++) {
			filesToUpload.push(req.files.uploadedFile[i]);
		}
		numberCalls = filesToUpload.length;
	}

	// parcourir la liste des fichiers a uploader
	for (var k = 0; k < filesToUpload.length; k++) {

		var currentFile = filesToUpload[k];
		// Detect file type
		var extension = helper.getFileExtension(filesToUpload[k].originalFilename);

		var newPath = './files/file-' + Math.random() + extension;

		// Ouvrir et ecrire les fichier uploadés de meniere synchronous
		var fileReaded = fs.readFileSync(filesToUpload[k].path);
		var fileWrited = fs.writeFileSync(newPath, fileReaded);
		if (extension === '.pdf') {
			// (if PDF convert to JPEGs)
			/*return number pages of PDF*/
			exports.getNumberPagesPDF(newPath, extension, res);
			// exports.convertsPdfToPng(newPath, res);
		} else if (extension === '.jpg' || extension === '.jpeg') {
			// (if PDF convert to JPEGs)
			exports.convertsJpegToPng(newPath, res);
		} else {
			sourcesUpload.push({
				path: newPath,
				extension: extension
			});
			counter += 1;
			if (numberCalls === counter) {
				return res.jsonp(sourcesUpload);
			}
		}
	}
};

/* Get number pages of PDF */
exports.getNumberPagesPDF = function(filePath, extension, res) {
	var exec = require('child_process').exec;
	exec('gs  -c "(' + filePath + ') (r) file runpdfbegin pdfpagecount = quit"', function(error, stdout) {
		if (error) {
			return error;
		}
		var numbPages = stdout.split('\n')[3];
		sourcesUpload.push({
			path: filePath,
			extension: extension,
			numberPages: numbPages
		});
		res.jsonp(sourcesUpload);
	});
};

/* Convert PDF to JPEG */
exports.convertsPdfToPng = function(req, res) {

	//console.log(req.body.pdfData);

	var exec = require('child_process').exec;
	var imageFileName = req.body.pdfData.source.substr(0, req.body.pdfData.source.lastIndexOf('.')) + Math.random();
	var imageConverted = imageFileName + '[' + req.body.pdfData.page + ']' + '.png';

	// Render image with imagemagick
	exec('convert -geometry 595x842 -density 450 ' + req.body.pdfData.source + '[' + req.body.pdfData.page + '] -background white -alpha remove -alpha off ' + imageConverted, function(error) {
		if (error !== null) {
			console.log(error);
			return 'error';
		} else {
			// console.log('[Done] Conversion from PDF to JPEG image' + imageFileName + '.jpg');

			return res.jsonp({
				path: imageConverted,
				extension: '.png'
			});

			// Get converted files by Command
			/*exec('ls files | grep  ' + imageFileName.substr(8, imageFileName.length), function(errorls, stdoutls) {

				if (errorls !== null) {
					console.log(errorls);
					return 'error';
				}

				var files = stdoutls.replace(/\n/g, ' ').split(' ');
				for (var i = 0; i < files.length; i++) {
					if (files[i] !== '') {
						sourcesUpload.push('./files/' + files[i]);
					}
				}
				counter += 1;
				if (numberCalls === counter) {
					return res.jsonp(sourcesUpload);
				}

			});*/
		}
	});
};

exports.convertsJpegToPng = function(source, res) {

	var exec = require('child_process').exec;
	var imageFileName = source.substr(0, source.lastIndexOf('.')) + Math.random();

	// Render image with imagemagick
	exec('convert ' + source + ' ' + imageFileName + '.png', function(error) {
		if (error !== null) {
			console.log(error);
			return 'error';
		} else {
			// console.log('[Done] Conversion from PDF to JPEG image' + imageFileName + '.jpg');
			//
			sourcesUpload.push({
				path: imageFileName + '.png',
				extension: '.png'
			});
			counter += 1;
			if (numberCalls === counter) {
				return res.jsonp(sourcesUpload);
			}
		}
	});
};

/*Text to speech*/
exports.textToSpeech = function(req, res) {
	var exec = require('child_process').exec;

	var fileName = './files/audio/mp3/audio_' + Math.random() + '.mp3';

	var tmpStr = req.body.text;

	// text to speech using espeak API
	exec('espeak -v french -s 110 "' + tmpStr + '" && espeak -v french -s 110 "' + tmpStr + '" --stdout | lame - ' + fileName, function(error) {
		if (error !== null) {
			console.log(error);
		} else {
			res.jsonp(fileName);
		}

	});
};

/*Festival Demo Text to speech*/
exports.festivalTextToSpeech = function(req, res) {
	var exec = require('child_process').exec;

	var tmpStr = req.body.texte;

	exec('echo \'' + tmpStr + '\'  | festival --tts ', function(error) {
		if (error !== null) {
			console.log(error);
		} else {
			res.jsonp('[Done] festival');
		}

	});
};

/*Espeak Demo Text to speech*/
exports.espeakTextToSpeech = function(req, res) {
	var exec = require('child_process').exec;

	var tmpStr = req.body.text;

	// text to speech using espeak API
	exec('espeak -v french \'' + tmpStr + '\' ', function(error) {
		if (error !== null) {
			console.log(error);
		} else {
			res.jsonp(200);
			//console.log('[Done] espeak');
		}

	});
};<|endoftext|>


<commit_before>function Udp_firefox(channel, dispatchEvent) {
  this.dispatchEvent = dispatchEvent;
  // http://dxr.mozilla.org/mozilla-central/source/netwerk/base/public/nsIUDPSocket.idl
  this._nsIUDPSocket = Components.classes["@mozilla.org/network/udp-socket;1"]
    .createInstance(Components.interfaces.nsIUDPSocket);
}

Udp_firefox.prototype.bind = function(address, port, continuation) {
  if (port < 1) {
    port = -1;
  }
  try {
    this._nsIUDPSocket.init(port, false);
    this._nsIUDPSocket.asyncListen(new nsIUDPSocketListener(this));
    continuation(0);
  } catch (e) {
    continuation(-1);
  }
};

Udp_firefox.prototype.getInfo = function(continuation) {
  var returnValue = {
    localAddress: "127.0.0.1",
    localPort: this._nsIUDPSocket
  };
  continuation(returnValue);
};

Udp_firefox.prototype.sendTo = function(buffer, address, port, continuation) {
  http://lxr.mozilla.org/mozilla-central/source/netwerk/base/public/nsINetAddr.idl
  var nsINetAddr = {
    family: Components.interfaces.nsINetAddr.FAMILY_INET,
    port: port,
    address: address
  };
  var bytesWritten = this._nsIUDPSocket.sendWithAddr(nsINetAddr,
                                                     buffer,
                                                     buffer.length);
  continuation(bytesWritten);
};

Udp_firefox.prototype.destroy = function(continuation) {
  this._nsIUDPSocket.close();
  continuation();
};

function nsIUDPSocketListener(udpSocket) {
  this._udpSocket = udpSocket;
}

nsIUDPSocketListener.prototype.onPacketReceived = function(nsIUDPSocket,
                                                           message) {
  var eventData = {
    resultCode: 0,
    address: message.fromAddr.address,
    port: message.fromAddr.address,
    data: this.str2ab(message.data)
  };
  this._udpSocket.dispatchEvent("onData",
                                eventData);
};

nsIUDPSocketListener.prototype.onStopListening = function(nsIUDPSocket,
                                                          status) {
};

nsIUDPSocketListener.prototype.str2ab = function(str) {
  var buf = new ArrayBuffer(str.length);
  var bufView = new Uint8Array(buf);
  for (var i=0, strLen=str.length; i<strLen; i++) {
    bufView[i] = str.charCodeAt(i);
  }
  return buf;
};

/** REGISTER PROVIDER **/
if (typeof fdom !== 'undefined') {
  fdom.apis.register("core.udpsocket", Udp_firefox);
}
<commit_msg>Fix issue with comment in udp_socket<commit_after>function Udp_firefox(channel, dispatchEvent) {
  this.dispatchEvent = dispatchEvent;
  // http://dxr.mozilla.org/mozilla-central/source/netwerk/base/public/nsIUDPSocket.idl
  this._nsIUDPSocket = Components.classes["@mozilla.org/network/udp-socket;1"]
    .createInstance(Components.interfaces.nsIUDPSocket);
}

Udp_firefox.prototype.bind = function(address, port, continuation) {
  if (port < 1) {
    port = -1;
  }
  try {
    this._nsIUDPSocket.init(port, false);
    this._nsIUDPSocket.asyncListen(new nsIUDPSocketListener(this));
    continuation(0);
  } catch (e) {
    continuation(-1);
  }
};

Udp_firefox.prototype.getInfo = function(continuation) {
  var returnValue = {
    localAddress: "127.0.0.1",
    localPort: this._nsIUDPSocket
  };
  continuation(returnValue);
};

Udp_firefox.prototype.sendTo = function(buffer, address, port, continuation) {
  // http://lxr.mozilla.org/mozilla-central/source/netwerk/base/public/nsINetAddr.idl
  var nsINetAddr = {
    family: Components.interfaces.nsINetAddr.FAMILY_INET,
    port: port,
    address: address
  };
  var bytesWritten = this._nsIUDPSocket.sendWithAddr(nsINetAddr,
                                                     buffer,
                                                     buffer.length);
  continuation(bytesWritten);
};

Udp_firefox.prototype.destroy = function(continuation) {
  this._nsIUDPSocket.close();
  continuation();
};

function nsIUDPSocketListener(udpSocket) {
  this._udpSocket = udpSocket;
}

nsIUDPSocketListener.prototype.onPacketReceived = function(nsIUDPSocket,
                                                           message) {
  var eventData = {
    resultCode: 0,
    address: message.fromAddr.address,
    port: message.fromAddr.address,
    data: this.str2ab(message.data)
  };
  this._udpSocket.dispatchEvent("onData",
                                eventData);
};

nsIUDPSocketListener.prototype.onStopListening = function(nsIUDPSocket,
                                                          status) {
};

nsIUDPSocketListener.prototype.str2ab = function(str) {
  var buf = new ArrayBuffer(str.length);
  var bufView = new Uint8Array(buf);
  for (var i=0, strLen=str.length; i<strLen; i++) {
    bufView[i] = str.charCodeAt(i);
  }
  return buf;
};

/** REGISTER PROVIDER **/
if (typeof fdom !== 'undefined') {
  fdom.apis.register("core.udpsocket", Udp_firefox);
}
<|endoftext|>


<commit_before>!function( $ ){

    "use strict";

    $(function () {

        /**
         * Delete attachment
         */
        $('.delete-attachment').click(function(){

            var field  = $(this).data('field'),
                id     = $(this).data('id'),
                table  = $(this).data('table'),
                data   = {},
                $this  = $(this),
                url    = '/api/' + table + '/' + id;

            if (! confirm('Delete ' + field + '?')) {
                return false;
            }

            data['id'] = id;
            data[field] = 'delete';

            $.ajax({
                type: 'PUT',
                url: url,
                data: data
            }).done(function() {
                $this.parent().remove();
            }).fail(function () {
                alertify.error('An error occurred while deleting attachment.');
            });

            return false;
        });

        /**
         * Selectize for select input
         */
        $('select#galleries').selectize();
        $('select#category_id').selectize();
        $('select#page_id').selectize();
        $('select#target').selectize();

        /**
         * Selectize for tags
         */
        if ($('#tags').length) {
            var tags = TypiCMS.tags.map(function(x) { return { item: x }; });
            $('#tags').selectize({
                persist: false,
                create: true,
                delimiter: ', ',
                options: tags,
                searchField: ['item'],
                labelField: 'item',
                valueField: 'item',
                createOnBlur: true
            });
        }

        /**
         * Set button in red on validation errors
         */
        var firstErrorTabActive = false;
        $('.tab-pane').each(function(index, el) {
            if ($(this).find('.has-error').length) {
                var tabButton = $('a[data-target="#' + $(this).attr('id') + '"]');
                if ( ! firstErrorTabActive) {
                    tabButton.tab('show');
                    firstErrorTabActive = true;
                }
                var dangerClass = 'text-danger';
                if (tabButton.hasClass('btn')) {
                    dangerClass = 'btn-danger';
                }
                tabButton.addClass(dangerClass);
            };
        });

        /**
         * Locale switcher : set active button
         */
        $('#btn-group-form-locales .btn').click(function(){
            $(this).parent().children('.active').removeClass('active');
            $(this).addClass('active');
        });

    });

}( window.jQuery || window.ender );
<commit_msg>new method to get all tags<commit_after>!function( $ ){

    "use strict";

    $(function () {

        /**
         * Delete attachment
         */
        $('.delete-attachment').click(function(){

            var field  = $(this).data('field'),
                id     = $(this).data('id'),
                table  = $(this).data('table'),
                data   = {},
                $this  = $(this),
                url    = '/api/' + table + '/' + id;

            if (! confirm('Delete ' + field + '?')) {
                return false;
            }

            data['id'] = id;
            data[field] = 'delete';

            $.ajax({
                type: 'PUT',
                url: url,
                data: data
            }).done(function() {
                $this.parent().remove();
            }).fail(function () {
                alertify.error('An error occurred while deleting attachment.');
            });

            return false;
        });

        /**
         * Selectize for select input
         */
        $('select#galleries').selectize();
        $('select#category_id').selectize();
        $('select#page_id').selectize();
        $('select#target').selectize();

        /**
         * Selectize for tags
         */
        if ($('#tags').length) {
            $.ajax({
                type: 'GET',
                url: '/api/tags'
            }).done(function(data) {
                var tags = data.map(function(x) { return { item: x.tag }; });
                $('#tags').selectize({
                    persist: false,
                    create: true,
                    delimiter: ', ',
                    options: tags,
                    searchField: ['item'],
                    labelField: 'item',
                    valueField: 'item',
                    createOnBlur: true
                });
            }).fail(function () {
                alertify.error('An error occurred while getting tags.');
            });
        }

        /**
         * Set button in red on validation errors
         */
        var firstErrorTabActive = false;
        $('.tab-pane').each(function(index, el) {
            if ($(this).find('.has-error').length) {
                var tabButton = $('a[data-target="#' + $(this).attr('id') + '"]');
                if ( ! firstErrorTabActive) {
                    tabButton.tab('show');
                    firstErrorTabActive = true;
                }
                var dangerClass = 'text-danger';
                if (tabButton.hasClass('btn')) {
                    dangerClass = 'btn-danger';
                }
                tabButton.addClass(dangerClass);
            };
        });

        /**
         * Locale switcher : set active button
         */
        $('#btn-group-form-locales .btn').click(function(){
            $(this).parent().children('.active').removeClass('active');
            $(this).addClass('active');
        });

    });

}( window.jQuery || window.ender );
<|endoftext|>


<commit_before>(function (window, io, $, _, Backbone, location, app) {
    "use strict";

    var ID = "id",
        SECURE = "{{secure}}" == "true",
        PORT = "{{port}}",
        watchedEvents = {};

    app.middle = app.middle || {};

    function getServerURL() {
        var protocol = SECURE ? "https://" : "http://",
            port = PORT || location.port;

        if (port) {
            port = ":" + port;
        }

        return protocol + location.hostname + port;
    }

    function convert(arg) {
        try {
            return JSON.stringify(arg);
        }
        catch (e) {
            var simpified = {};

            _.each(arg, function (entry, key) {
                if (entry !== window) {
                    simpified[key] = entry;
                }
            });

            return convert(simpified);
        }
    }

    function log(socket, level, _args) {
        var args = Array.prototype.slice.call(_args),
            params = [
                "log",
                level,
                new Date()
            ];

        _.each(args, function (arg) {
            var param = convert(arg);

            params.push(param);
        });

        return socket.emit.apply(socket, params);
    }

    function emitter(socket) {
        return function () {
            return socket.emit.apply(socket, arguments);
        };
    }

    function connect(url, cb) {
        try {
            return cb(io.connect(url, {
                "reconnection limit":4001, // four second max delay
                "max reconnection attempts":Infinity,
                "force new connection": true
            }));
        }
        catch(e) {
            setTimeout(function() {
                connect(url, cb);
            }, 500);

            return app.error("io.connect exception", e);
        }
    }

    function openSocket(cb) {
        var tryAgain = function() {
                if (cb) {
                    app.log("middle trying to connect again");
                    setTimeout(function() {
                        openSocket(cb);
                    }, 500);
                }
            },
            app_log = app.log,
            app_debug = app.debug,
            app_error = app.error,
            url = getServerURL();

        return connect(url, function(socket) {
            socket.on('error', function (err) {
                app.error("middle socket error", err);
                tryAgain();
            });
            socket.on('connecting', function () {
                return app.log("middle connecting");
            });
            socket.on('connect_failed', function (err) {
                app.error("connect_failed", err);
                tryAgain();
            });
            socket.on('reconnect', function () {
                return app.log("middle reconnect");
            });
            socket.on('reconnecting', function () {
                return app.log("middle reconnecting");
            });
            socket.on('connect', function () {
                app.middle.connected = true;

                var _cb = cb;

                cb = undefined;

                socket.emit("middle-initialize", app.middle.id);

                app.log = function () {
                    return log(socket, "info", arguments);
                };
                app.debug = function () {
                    return log(socket, "debug", arguments);
                };
                app.error = function () {
                    return log(socket, "error", arguments);
                };

                app.log("middle connected");

                return _cb && _cb(socket);
            });
            socket.on('disconnect', function () {
                app.middle.connected = false;

                app.log = app_log;
                app.debug = app_debug;
                app.error = app_error;
                app.middle.trigger("disconnect", app.middle.id);

                return app.log("disconnected", app.middle.id);
            });
        });
    }

    app.starter.$(function (next) {
        app.store("middle", function (store) {
            store.get(ID, function (device) {
                app.middle.id = (device && device.id) || app.utils.uuid();

                if (!device) {
                    store.save(ID, app.middle.id);
                }

                return openSocket(function(socket) {
                    app.middle.bind = app.middle.on = app.middle.on || function (event, callback, context) {
                        var events = event.split(/\s+/);

                        _.each(events, function (event) {
                            if (!watchedEvents[event]) {
                                watchedEvents[event] = true;
                                socket.on(event, function () {
                                    var args = Array.prototype.slice.call(arguments);

                                    args.unshift(event);

                                    return app.middle.trigger.apply(app.middle, args);
                                });
                            }
                        });

                        Backbone.Events.on.call(app.middle, event, callback, context);
                    };
                    app.middle.unbind = app.middle.off = app.middle.off || function () {
                        Backbone.Events.off.apply(app.middle, arguments);
                    };
                    app.middle.trigger = app.middle.trigger = app.middle.trigger || function () {
                        Backbone.Events.trigger.apply(app.middle, arguments);
                    };
                    app.middle.emit = emitter(socket);

                    return next();
                });
            });
        });
    });
})(window, window.io, $, _, Backbone, window.location, window["jolira-app"]);
<commit_msg>log the device information that is provided by PhoneGap (Apache Cordova)<commit_after>(function (window, io, $, _, Backbone, location, app) {
    "use strict";

    var ID = "id",
        SECURE = "{{secure}}" == "true",
        PORT = "{{port}}",
        watchedEvents = {};

    app.middle = app.middle || {};

    function getServerURL() {
        var protocol = SECURE ? "https://" : "http://",
            port = PORT || location.port;

        if (port) {
            port = ":" + port;
        }

        return protocol + location.hostname + port;
    }

    function convert(arg) {
        try {
            return JSON.stringify(arg);
        }
        catch (e) {
            var simpified = {};

            _.each(arg, function (entry, key) {
                if (entry !== window) {
                    simpified[key] = entry;
                }
            });

            return convert(simpified);
        }
    }

    function log(socket, level, _args) {
        var args = Array.prototype.slice.call(_args),
            params = [
                "log",
                level,
                new Date()
            ];

        _.each(args, function (arg) {
            var param = convert(arg);

            params.push(param);
        });

        return socket.emit.apply(socket, params);
    }

    function emitter(socket) {
        return function () {
            return socket.emit.apply(socket, arguments);
        };
    }

    function connect(url, cb) {
        try {
            return cb(io.connect(url, {
                "reconnection limit":4001, // four second max delay
                "max reconnection attempts":Infinity,
                "force new connection":true
            }));
        }
        catch (e) {
            setTimeout(function () {
                connect(url, cb);
            }, 500);

            return app.error("io.connect exception", e);
        }
    }

    function openSocket(cb) {
        var tryAgain = function () {
                if (cb) {
                    app.log("middle trying to connect again");
                    setTimeout(function () {
                        openSocket(cb);
                    }, 500);
                }
            },
            app_log = app.log,
            app_debug = app.debug,
            app_error = app.error,
            url = getServerURL();

        return connect(url, function (socket) {
            socket.on('error', function (err) {
                app.error("middle socket error", err);
                tryAgain();
            });
            socket.on('connecting', function () {
                return app.log("middle connecting");
            });
            socket.on('connect_failed', function (err) {
                app.error("connect_failed", err);
                tryAgain();
            });
            socket.on('reconnect', function () {
                return app.log("middle reconnect");
            });
            socket.on('reconnecting', function () {
                return app.log("middle reconnecting");
            });
            socket.on('connect', function () {
                app.middle.connected = true;

                var _cb = cb,
                    device = window.device || {};

                cb = undefined;

                socket.emit("middle-initialize", {
                    id:app.middle.id,
                    uuid:device.uuid,
                    name:device.name,
                    platform:device.platform,
                    version:device.version,
                    cordova:device.cordova
                });

                app.log = function () {
                    return log(socket, "info", arguments);
                };
                app.debug = function () {
                    return log(socket, "debug", arguments);
                };
                app.error = function () {
                    return log(socket, "error", arguments);
                };

                app.log("middle connected");

                return _cb && _cb(socket);
            });
            socket.on('disconnect', function () {
                app.middle.connected = false;

                app.log = app_log;
                app.debug = app_debug;
                app.error = app_error;
                app.middle.trigger("disconnect", app.middle.id);

                return app.log("disconnected", app.middle.id);
            });
        });
    }

    app.starter.$(function (next) {
        app.store("middle", function (store) {
            store.get(ID, function (id) {
                app.middle.id = (id && id.id) || app.utils.uuid();

                if (!id) {
                    store.save(ID, app.middle.id);
                }

                return openSocket(function (socket) {
                    app.middle.bind = app.middle.on = app.middle.on || function (event, callback, context) {
                        var events = event.split(/\s+/);

                        _.each(events, function (event) {
                            if (!watchedEvents[event]) {
                                watchedEvents[event] = true;
                                socket.on(event, function () {
                                    var args = Array.prototype.slice.call(arguments);

                                    args.unshift(event);

                                    return app.middle.trigger.apply(app.middle, args);
                                });
                            }
                        });

                        Backbone.Events.on.call(app.middle, event, callback, context);
                    };
                    app.middle.unbind = app.middle.off = app.middle.off || function () {
                        Backbone.Events.off.apply(app.middle, arguments);
                    };
                    app.middle.trigger = app.middle.trigger = app.middle.trigger || function () {
                        Backbone.Events.trigger.apply(app.middle, arguments);
                    };
                    app.middle.emit = emitter(socket);

                    return next();
                });
            });
        });
    });
})(window, window.io, $, _, Backbone, window.location, window["jolira-app"]);
<|endoftext|>