<commit_before>/**
 * @todo: recursively send requests until all contacts are fetched
 *
 * @see https://developers.google.com/google-apps/contacts/v3/reference#ContactsFeed
 *
 * To API test requests:
 *
 * @see https://developers.google.com/oauthplayground/
 *
 * To format JSON nicely:
 *
 * @see http://jsonviewer.stack.hu/
 *
 * Note: The Contacts API has a hard limit to the number of results it can return at a
 * time even if you explicitly request all possible results. If the requested feed has
 * more fields than can be returned in a single response, the API truncates the feed and adds
 * a "Next" link that allows you to request the rest of the response.
 */
var EventEmitter = require('events').EventEmitter,
    _ = require('lodash'),
    qs = require('querystring'),
    util = require('util'),
    url = require('url'),
    https = require('https'),
    debug = require('debug')('google-contacts'),
    xml2js = require('xml2js');

var GoogleContacts = function (params) {
    if (typeof params === 'string') {
        params = {token: params}
    }
    if (!params) {
        params = {};
    }

    this.contacts = [];
    this.consumerKey = params.consumerKey ? params.consumerKey : null;
    this.consumerSecret = params.consumerSecret ? params.consumerSecret : null;
    this.token = params.token ? params.token : null;
    this.refreshToken = params.refreshToken ? params.refreshToken : null;

    this.params = _.defaults(params, {thin: true});
};

GoogleContacts.prototype = {};

util.inherits(GoogleContacts, EventEmitter);

GoogleContacts.prototype._get = function (params, cb) {
    if (typeof params === 'function') {
        cb = params;
        params = {};
    }

    var req = {
        host: 'www.google.com',
        port: 443,
        path: this._buildPath(params),
        method: 'GET',
        headers: {
            'Authorization': 'OAuth ' + this.token,
            'GData-Version': 3
        }
    };

    debug(req);

    https.request(req, function (res) {
            var data = '';

            res.on('data', function (chunk) {
                debug('got ' + chunk.length + ' bytes');
                data += chunk.toString('utf-8');
            });

            res.on('error', function (err) {
                cb(err);
            });

            res.on('end', function () {
                if (res.statusCode < 200 || res.statusCode >= 300) {
                    var error = new Error('Bad client request status: ' + res.statusCode);
                    return cb(error);
                }
                try {
                    debug(data);
                    cb(null, JSON.parse(data));
                }
                catch (err) {
                    cb(err);
                }
            });
        })
        .on('error', cb)
        .end();
};

GoogleContacts.prototype._post = function (params, cb) {
    if (typeof params === 'function') {
        cb = params;
        params = {};
    }

    var opts = {
        host: 'www.google.com',
        port: 443,
        path: this._buildPath(params, true),
        method: 'POST',
        headers: {
            'Authorization': 'Bearer ' + this.token,
            'GData-Version': 3,
            'content-type': 'application/atom+xml',
        }
    };

    debug(req);

    var req = https.request(opts, function (res) {
            var data = '';

            res.on('data', function (chunk) {
                debug('got ' + chunk.length + ' bytes');
                data += chunk.toString('utf-8');
            });

            res.on('error', function (err) {
                cb(err);
            });

            res.on('end', function () {
                if (res.statusCode < 200 || res.statusCode >= 300) {
                    var error = new Error('Bad client request status: ' + res.statusCode);
                    return cb(error);
                }
                try {
                    debug(data);
                    parseXml(data, cb);
                }
                catch (err) {
                    cb(err);
                }
            });
        });

    req.write(params.post);
    req.end();

    function parseXml(data, cb){
        var parser = new xml2js.Parser();
        parser.parseString(data, function(err, json){
            if(err) return cb(err)

            cb(null, json);
        });
    }
};

GoogleContacts.prototype.getContacts = function (cb, params) {
    var self = this;

    this._get(_.extend({type: 'contacts'}, params, this.params), receivedContacts);
    function receivedContacts(err, data) {
        if (err) return cb(err);

        var feed = _.get(data, 'feed', []);
        var entry = _.get(data, 'feed.entry', []);
        if (!entry.length) {
            return cb(null, entry);
        }

        self._saveContactsFromFeed(feed);

        var next = false;
        _.each(feed.link, function (link) {
            if (link.rel === 'next') {
                next = true;
                var path = url.parse(link.href).path;
                self._get({path: path}, receivedContacts);
            }
        });
        if (!next) {
            cb(null, self.contacts);
        }
    }
};

GoogleContacts.prototype.getContact = function (cb, params) {
    var self = this;

    if(!_.has(params, 'id')){
        return cb("No id found in params");
    }

    this._get(_.extend({type: 'contacts'}, this.params, params), receivedContact);

    function receivedContact(err, contact) {
        if (err) return cb(err);

        cb(null, contact);
    }

};

/**
 * Receives an object with @layout and create the contact.
 * Unfortunately google apps do not support contact payload in json
 * format, so we have to convert the object in xml.
 *
 * @see https://developers.google.com/google-apps/contacts/v3/#creating_contacts
 *
 * Object layout: Fot convinience we handle the xml -> js conversion adding the
 * required xml namespaces, so the json object can have a simplified layout (see params).
 *
 * @param cb: callback
 * @param params: must contain 'entry' variable with the following format:
 * {
 *   name: {
 *       fullName: 'full contact name'
 *   },
 *   email:[{
 *           primary: true|false,
 *           address: 'email@address.com',
 *           type: 'home|work'
 *       }],
 *   phoneNumber:[{
 *           type: 'home|work|mobile|main|work_fax|home_fax|pager',
 *           phoneNumber: 'phone number'
 *       }]
 * }
 * */
GoogleContacts.prototype.createContact = function (cb, params) {
    var self = this;

    if(!_.has(params, 'entry.name')){
        return cb("No name found in params");
    }

    if(!_.has(params, 'entry.email') && !_.has(params, 'phoneNumber')){
        return cb("No email or phoneNumber found in params");
    }

    var gContact = _getGoogleContactObject(params.entry);

    var builder = new xml2js.Builder({rootName:'entry'});
    params.post = builder.buildObject(gContact);

    this._post(_.extend({type: 'contacts'}, this.params, params), receivedContact);

    function receivedContact(err, contact) {
        if (err) return cb(err);

        cb(null, contact);
    }

    function _addPrefix(obj, prefix){
        var prefixedObj = {};
        _.forOwn(obj, function(value, key){
            if(_.includes(['name', 'email', 'phoneNumber'], key))
                key = prefix + key;

            prefixedObj[key] = value;
        });

        return prefixedObj;
    }

    function _getSchema(schemaName, rootSchema){
        if(rootSchema)
            schemaName = rootSchema + '.' + schemaName;

        var schemas = {
            'xmlns': "http://www.w3.org/2005/Atom",
            'gd': "http://schemas.google.com/g/2005",
            'gContact' : "xmlns:gContact='http://schemas.google.com/contact/2008'",
            'scheme': "http://schemas.google.com/g/2005#kind",
            'term': "http://schemas.google.com/contact/2008#contact",
            email:{
                'work': "http://schemas.google.com/g/2005#work",
                'home': "http://schemas.google.com/g/2005#home"
            },
            phone: {
                'work': "http://schemas.google.com/g/2005#work",
                'home': "http://schemas.google.com/g/2005#home",
                'main': "http://schemas.google.com/g/2005#main",
                'work_fax': "http://schemas.google.com/g/2005#work_fax",
                'home_fax': "http://schemas.google.com/g/2005#home_fax",
                'pager': "http://schemas.google.com/g/2005#pager"
            }
        };

        return _.get(schemas, schemaName, '');
    }

    function _getGoogleContactObject(params){
        var prefix = params.prefix || 'gd:';
        var root = {
            $: {
                'xmlns': _getSchema('xmlns'),
                'xmlns:gd': _getSchema('gd'),
                'xmlns:gContact': _getSchema('gContact')
            },
            category: {
                $: {
                    'scheme' : _getSchema('scheme'),
                    'term' : _getSchema('term')
                }
            }
        };

        root.name = {
            $: {xmlns: _getSchema('gd') }
        }

        if(_.has(params, 'name.fullName')) root.name.fullName = params.name.fullName;
        if(_.has(params, 'name.givenName')) root.name.fullName = params.name.givenName;
        if(_.has(params, 'name.familyName')) root.name.fullName = params.name.familyName;

        root.title = _.get(params, 'title', '');
        root.content = _.get(params, 'content', '');

        if(_.has(params, 'email')){
            root.email = [];
            if(!_.isArray(params.email)) params.email = [params.email];

            _.each(params.email, function(m){
                root.email.push({$: {primary: _.get(m, 'primary', false), address: _.get(m, 'address', ''), rel: _getSchema(_.get(m, 'type', 'work'), 'email')}});
            });
        }

        if(_.has(params, 'phoneNumber')){
            root.phoneNumber = [];
            if(!_.isArray(params.phoneNumber)) params.phoneNumber = [params.phoneNumber];

            _.each(params.phoneNumber, function(p){
                root.phoneNumber.push({$: {rel: _getSchema(_.get(p, 'type', 'work'), 'phone')}, "_": _.get(p, 'phoneNumber', '')});
            });
        }

        return _addPrefix(root, prefix);
    }
};

GoogleContacts.prototype._saveContactsFromFeed = function (feed) {
    var self = this;
    _.each(feed.entry, function (entry) {
        var el, url;
        if (self.params.thin) {
            url = _.get(entry, 'id.$t', '');
            el = {
                name: _.get(entry, 'title.$t'),
                email: _.get(entry, 'gd$email.0.address'), // only save first email
                phoneNumber: _.get(entry, 'gd$phoneNumber.0.uri', '').replace('tel:', ''),
                id: url.substring(_.lastIndexOf(url, '/') + 1)
            };
        } else {
            el = entry;
        }
        self.contacts.push(el);
    });
};

GoogleContacts.prototype._buildPath = function (params, isPost) {
    if (params.path) return params.path;

    params = _.extend({}, params, this.params);
    params.type = params.type || 'contacts';
    params.alt = params.alt || 'json';
    params.projection = params.projection || (params.thin ? 'thin' : 'full');
    params.email = params.email || 'default';
    params['max-results'] = params['max-results'] || 10000;

    var query = {
        alt: params.alt
    };

    if(!params.id) query['max-results'] = params['max-results'];

    if (params['updated-min'])
        query['updated-min'] = params['updated-min'];

    if (params.q || params.query)
        query.q = params.q || params.query;

    var path = '/m8/feeds/';
    path += params.type + '/';
    path += params.email + '/';
    path += params.projection;
    if(params.id) path +=  '/'+ params.id;
    if (!isPost) path += '?' + qs.stringify(query);

    return path;
};

GoogleContacts.prototype.refreshAccessToken = function (refreshToken, params, cb) {
    if (typeof params === 'function') {
        cb = params;
        params = {};
    }

    var data = {
        refresh_token: refreshToken,
        client_id: this.consumerKey,
        client_secret: this.consumerSecret,
        grant_type: 'refresh_token'

    };

    var body = qs.stringify(data);

    var opts = {
        host: 'accounts.google.com',
        port: 443,
        path: '/o/oauth2/token',
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Content-Length': body.length
        }
    };

    var req = https.request(opts, function (res) {
        var data = '';
        res.on('end', function () {
            if (res.statusCode < 200 || res.statusCode >= 300) {
                var error = new Error('Bad client request status: ' + res.statusCode);
                return cb(error);
            }
            try {
                data = JSON.parse(data);
                cb(null, data.access_token);
            }
            catch (err) {
                cb(err);
            }
        });

        res.on('data', function (chunk) {
            data += chunk;
        });

        res.on('error', cb);

    }).on('error', cb);

    req.write(body);
    req.end();
};

exports.GoogleContacts = GoogleContacts;
<commit_msg>Fix: removing unnecesary validation<commit_after>/**
 * @todo: recursively send requests until all contacts are fetched
 *
 * @see https://developers.google.com/google-apps/contacts/v3/reference#ContactsFeed
 *
 * To API test requests:
 *
 * @see https://developers.google.com/oauthplayground/
 *
 * To format JSON nicely:
 *
 * @see http://jsonviewer.stack.hu/
 *
 * Note: The Contacts API has a hard limit to the number of results it can return at a
 * time even if you explicitly request all possible results. If the requested feed has
 * more fields than can be returned in a single response, the API truncates the feed and adds
 * a "Next" link that allows you to request the rest of the response.
 */
var EventEmitter = require('events').EventEmitter,
    _ = require('lodash'),
    qs = require('querystring'),
    util = require('util'),
    url = require('url'),
    https = require('https'),
    debug = require('debug')('google-contacts'),
    xml2js = require('xml2js');

var GoogleContacts = function (params) {
    if (typeof params === 'string') {
        params = {token: params}
    }
    if (!params) {
        params = {};
    }

    this.contacts = [];
    this.consumerKey = params.consumerKey ? params.consumerKey : null;
    this.consumerSecret = params.consumerSecret ? params.consumerSecret : null;
    this.token = params.token ? params.token : null;
    this.refreshToken = params.refreshToken ? params.refreshToken : null;

    this.params = _.defaults(params, {thin: true});
};

GoogleContacts.prototype = {};

util.inherits(GoogleContacts, EventEmitter);

GoogleContacts.prototype._get = function (params, cb) {
    if (typeof params === 'function') {
        cb = params;
        params = {};
    }

    var req = {
        host: 'www.google.com',
        port: 443,
        path: this._buildPath(params),
        method: 'GET',
        headers: {
            'Authorization': 'OAuth ' + this.token,
            'GData-Version': 3
        }
    };

    debug(req);

    https.request(req, function (res) {
            var data = '';

            res.on('data', function (chunk) {
                debug('got ' + chunk.length + ' bytes');
                data += chunk.toString('utf-8');
            });

            res.on('error', function (err) {
                cb(err);
            });

            res.on('end', function () {
                if (res.statusCode < 200 || res.statusCode >= 300) {
                    var error = new Error('Bad client request status: ' + res.statusCode);
                    return cb(error);
                }
                try {
                    debug(data);
                    cb(null, JSON.parse(data));
                }
                catch (err) {
                    cb(err);
                }
            });
        })
        .on('error', cb)
        .end();
};

GoogleContacts.prototype._post = function (params, cb) {
    if (typeof params === 'function') {
        cb = params;
        params = {};
    }

    var opts = {
        host: 'www.google.com',
        port: 443,
        path: this._buildPath(params, true),
        method: 'POST',
        headers: {
            'Authorization': 'Bearer ' + this.token,
            'GData-Version': 3,
            'content-type': 'application/atom+xml',
        }
    };

    debug(req);

    var req = https.request(opts, function (res) {
            var data = '';

            res.on('data', function (chunk) {
                debug('got ' + chunk.length + ' bytes');
                data += chunk.toString('utf-8');
            });

            res.on('error', function (err) {
                cb(err);
            });

            res.on('end', function () {
                if (res.statusCode < 200 || res.statusCode >= 300) {
                    var error = new Error('Bad client request status: ' + res.statusCode);
                    return cb(error);
                }
                try {
                    debug(data);
                    parseXml(data, cb);
                }
                catch (err) {
                    cb(err);
                }
            });
        });

    req.write(params.post);
    req.end();

    function parseXml(data, cb){
        var parser = new xml2js.Parser();
        parser.parseString(data, function(err, json){
            if(err) return cb(err)

            cb(null, json);
        });
    }
};

GoogleContacts.prototype.getContacts = function (cb, params) {
    var self = this;

    this._get(_.extend({type: 'contacts'}, params, this.params), receivedContacts);
    function receivedContacts(err, data) {
        if (err) return cb(err);

        var feed = _.get(data, 'feed', []);
        var entry = _.get(data, 'feed.entry', []);
        if (!entry.length) {
            return cb(null, entry);
        }

        self._saveContactsFromFeed(feed);

        var next = false;
        _.each(feed.link, function (link) {
            if (link.rel === 'next') {
                next = true;
                var path = url.parse(link.href).path;
                self._get({path: path}, receivedContacts);
            }
        });
        if (!next) {
            cb(null, self.contacts);
        }
    }
};

GoogleContacts.prototype.getContact = function (cb, params) {
    var self = this;

    if(!_.has(params, 'id')){
        return cb("No id found in params");
    }

    this._get(_.extend({type: 'contacts'}, this.params, params), receivedContact);

    function receivedContact(err, contact) {
        if (err) return cb(err);

        cb(null, contact);
    }

};

/**
 * Receives an object with @layout and create the contact.
 * Unfortunately google apps do not support contact payload in json
 * format, so we have to convert the object in xml.
 *
 * @see https://developers.google.com/google-apps/contacts/v3/#creating_contacts
 *
 * Object layout: Fot convinience we handle the xml -> js conversion adding the
 * required xml namespaces, so the json object can have a simplified layout (see params).
 *
 * @param cb: callback
 * @param params: must contain 'entry' variable with the following format:
 * {
 *   name: {
 *       fullName: 'full contact name'
 *   },
 *   email:[{
 *           primary: true|false,
 *           address: 'email@address.com',
 *           type: 'home|work'
 *       }],
 *   phoneNumber:[{
 *           type: 'home|work|mobile|main|work_fax|home_fax|pager',
 *           phoneNumber: 'phone number'
 *       }]
 * }
 * */
GoogleContacts.prototype.createContact = function (cb, params) {
    var self = this;

    if(!_.has(params, 'entry.name')){
        return cb("No name found in params");
    }

    var gContact = _getGoogleContactObject(params.entry);

    var builder = new xml2js.Builder({rootName:'entry'});
    params.post = builder.buildObject(gContact);

    this._post(_.extend({type: 'contacts'}, this.params, params), receivedContact);

    function receivedContact(err, contact) {
        if (err) return cb(err);

        cb(null, contact);
    }

    function _addPrefix(obj, prefix){
        var prefixedObj = {};
        _.forOwn(obj, function(value, key){
            if(_.includes(['name', 'email', 'phoneNumber'], key))
                key = prefix + key;

            prefixedObj[key] = value;
        });

        return prefixedObj;
    }

    function _getSchema(schemaName, rootSchema){
        if(rootSchema)
            schemaName = rootSchema + '.' + schemaName;

        var schemas = {
            'xmlns': "http://www.w3.org/2005/Atom",
            'gd': "http://schemas.google.com/g/2005",
            'gContact' : "xmlns:gContact='http://schemas.google.com/contact/2008'",
            'scheme': "http://schemas.google.com/g/2005#kind",
            'term': "http://schemas.google.com/contact/2008#contact",
            email:{
                'work': "http://schemas.google.com/g/2005#work",
                'home': "http://schemas.google.com/g/2005#home"
            },
            phone: {
                'work': "http://schemas.google.com/g/2005#work",
                'home': "http://schemas.google.com/g/2005#home",
                'main': "http://schemas.google.com/g/2005#main",
                'work_fax': "http://schemas.google.com/g/2005#work_fax",
                'home_fax': "http://schemas.google.com/g/2005#home_fax",
                'pager': "http://schemas.google.com/g/2005#pager"
            }
        };

        return _.get(schemas, schemaName, '');
    }

    function _getGoogleContactObject(params){
        var prefix = params.prefix || 'gd:';
        var root = {
            $: {
                'xmlns': _getSchema('xmlns'),
                'xmlns:gd': _getSchema('gd'),
                'xmlns:gContact': _getSchema('gContact')
            },
            category: {
                $: {
                    'scheme' : _getSchema('scheme'),
                    'term' : _getSchema('term')
                }
            }
        };

        root.name = {
            $: {xmlns: _getSchema('gd') }
        }

        if(_.has(params, 'name.fullName')) root.name.fullName = params.name.fullName;
        if(_.has(params, 'name.givenName')) root.name.fullName = params.name.givenName;
        if(_.has(params, 'name.familyName')) root.name.fullName = params.name.familyName;

        root.title = _.get(params, 'title', '');
        root.content = _.get(params, 'content', '');

        if(_.has(params, 'email')){
            root.email = [];
            if(!_.isArray(params.email)) params.email = [params.email];

            _.each(params.email, function(m){
                root.email.push({$: {primary: _.get(m, 'primary', false), address: _.get(m, 'address', ''), rel: _getSchema(_.get(m, 'type', 'work'), 'email')}});
            });
        }

        if(_.has(params, 'phoneNumber')){
            root.phoneNumber = [];
            if(!_.isArray(params.phoneNumber)) params.phoneNumber = [params.phoneNumber];

            _.each(params.phoneNumber, function(p){
                root.phoneNumber.push({$: {rel: _getSchema(_.get(p, 'type', 'work'), 'phone')}, "_": _.get(p, 'phoneNumber', '')});
            });
        }

        return _addPrefix(root, prefix);
    }
};

GoogleContacts.prototype._saveContactsFromFeed = function (feed) {
    var self = this;
    _.each(feed.entry, function (entry) {
        var el, url;
        if (self.params.thin) {
            url = _.get(entry, 'id.$t', '');
            el = {
                name: _.get(entry, 'title.$t'),
                email: _.get(entry, 'gd$email.0.address'), // only save first email
                phoneNumber: _.get(entry, 'gd$phoneNumber.0.uri', '').replace('tel:', ''),
                id: url.substring(_.lastIndexOf(url, '/') + 1)
            };
        } else {
            el = entry;
        }
        self.contacts.push(el);
    });
};

GoogleContacts.prototype._buildPath = function (params, isPost) {
    if (params.path) return params.path;

    params = _.extend({}, params, this.params);
    params.type = params.type || 'contacts';
    params.alt = params.alt || 'json';
    params.projection = params.projection || (params.thin ? 'thin' : 'full');
    params.email = params.email || 'default';
    params['max-results'] = params['max-results'] || 10000;

    var query = {
        alt: params.alt
    };

    if(!params.id) query['max-results'] = params['max-results'];

    if (params['updated-min'])
        query['updated-min'] = params['updated-min'];

    if (params.q || params.query)
        query.q = params.q || params.query;

    var path = '/m8/feeds/';
    path += params.type + '/';
    path += params.email + '/';
    path += params.projection;
    if(params.id) path +=  '/'+ params.id;
    if (!isPost) path += '?' + qs.stringify(query);

    return path;
};

GoogleContacts.prototype.refreshAccessToken = function (refreshToken, params, cb) {
    if (typeof params === 'function') {
        cb = params;
        params = {};
    }

    var data = {
        refresh_token: refreshToken,
        client_id: this.consumerKey,
        client_secret: this.consumerSecret,
        grant_type: 'refresh_token'

    };

    var body = qs.stringify(data);

    var opts = {
        host: 'accounts.google.com',
        port: 443,
        path: '/o/oauth2/token',
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Content-Length': body.length
        }
    };

    var req = https.request(opts, function (res) {
        var data = '';
        res.on('end', function () {
            if (res.statusCode < 200 || res.statusCode >= 300) {
                var error = new Error('Bad client request status: ' + res.statusCode);
                return cb(error);
            }
            try {
                data = JSON.parse(data);
                cb(null, data.access_token);
            }
            catch (err) {
                cb(err);
            }
        });

        res.on('data', function (chunk) {
            data += chunk;
        });

        res.on('error', cb);

    }).on('error', cb);

    req.write(body);
    req.end();
};

exports.GoogleContacts = GoogleContacts;
<|endoftext|>


<commit_before>L.UGeoJSONLayer = L.GeoJSON.extend({
    options: {
      debug: false,
      light: true,
      usebbox: false,
      endpoint: "-1",
      parameters: {},
      maxRequests: 5,
      pollTime:0,
      once: false,
      after: function(data){}
    },

    callback: function(data) {
      if(this.options.light)
      {
        this.clearLayers();//if needed, we clean the layers
      }

      //Then we add the new data
      this.addData(data);
      this.options.after(data);
    },

  initialize: function (uOptions, options) {
    L.GeoJSON.prototype.initialize.call(this, undefined, options);
    L.Util.setOptions(this, uOptions);

    this._layersOld = [];
    this._requests = [];
  },

  onMoveEnd: function () {
    if (this.options.debug) {
      console.debug("load Data");
    }

    while(this._requests.length > this.options.maxRequests) //This allows to stop the oldest requests
    {
      this._requests.shift().abort();
    }

    var postData = new FormData();

    for(var k in this.options.parameters)
    {
      if(this.options.parameters[k].scope != undefined)
      {
        postData.append(k,this.options.parameters[k].scope[k]);
      }
      else
      {
        postData.append(k,this.options.parameters[k]);
      }
    }

    var bounds = this._map.getBounds();

    if ( this.options.usebbox ) {
      postData.append('bbox', bounds.toBBoxString());

    } else {
      postData.append('south', bounds.getSouth());
      postData.append('north', bounds.getNorth());
      postData.append('east', bounds.getEast());
      postData.append('west', bounds.getWest());
    }
    postData.append('zoom', this._map.getZoom());

    var self = this;
    var request = new XMLHttpRequest();
    request.open("POST", this.options.endpoint, true);
    request.onload = function() {
      for(var i in self._requests)
      {
        if(self._requests[i] === request)
        {
          self._requests.splice(i,1); //We remove the request from the list of currently running requests.
          break;
        }
      }

      if (this.status >= 200 && this.status < 400) {
        self.callback(JSON.parse(this.responseText));
      }
    };

    this._requests.push(request);
    request.send(postData);
  },

  onAdd: function (map) {
    this._map = map;

    if (this.options.endpoint.indexOf("http") != -1) {
		this.onMoveEnd();

		if(!this.options.once) {
			map.on('dragend', this.onMoveEnd, this);
			map.on('zoomend', this.onMoveEnd, this);

			if (this.options.pollTime > 0) {
			  this.intervalID = window.setInterval(this.onMoveEnd, this.options.pollTime);
			}
		}
	}

    if (this.options.debug) {
      console.debug("add layer");
    }
  },

  onRemove: function (map) {
    if (this.options.debug) {
      console.debug("remove layer");
    }
    L.LayerGroup.prototype.onRemove.call(this, map);

    if (!this.options.once && this.options.pollTime > 0) {
      window.clearInterval(this.intervalID);
    }

    while(this._requests.length > 0)
    {
      this._requests.shift().abort();
    }

    if(!this.options.once) {
		map.off({
		  'dragend': this.onMoveEnd
		}, this);
		map.off({
		  'zoomend': this.onMoveEnd
		}, this);
	}

    this._map = null;
  }

});

L.uGeoJSONLayer = function (uOptions, options) {
  return new L.UGeoJSONLayer(uOptions, options);
};
<commit_msg>Fixed interval problem<commit_after>L.UGeoJSONLayer = L.GeoJSON.extend({
    options: {
      debug: false,
      light: true,
      usebbox: false,
      endpoint: "-1",
      parameters: {},
      maxRequests: 5,
      pollTime:0,
      once: false,
      after: function(data){}
    },

    callback: function(data) {
      if(this.options.light)
      {
        this.clearLayers();//if needed, we clean the layers
      }

      //Then we add the new data
      this.addData(data);
      this.options.after(data);
    },

  initialize: function (uOptions, options) {
    L.GeoJSON.prototype.initialize.call(this, undefined, options);
    L.Util.setOptions(this, uOptions);

    this._layersOld = [];
    this._requests = [];
  },

  onMoveEnd: function () {
    if (this.options.debug) {
      console.debug("load Data");
    }

    while(this._requests.length > this.options.maxRequests) //This allows to stop the oldest requests
    {
      this._requests.shift().abort();
    }

    var postData = new FormData();

    for(var k in this.options.parameters)
    {
      if(this.options.parameters[k].scope != undefined)
      {
        postData.append(k,this.options.parameters[k].scope[k]);
      }
      else
      {
        postData.append(k,this.options.parameters[k]);
      }
    }

    var bounds = this._map.getBounds();

    if ( this.options.usebbox ) {
      postData.append('bbox', bounds.toBBoxString());

    } else {
      postData.append('south', bounds.getSouth());
      postData.append('north', bounds.getNorth());
      postData.append('east', bounds.getEast());
      postData.append('west', bounds.getWest());
    }
    postData.append('zoom', this._map.getZoom());

    var self = this;
    var request = new XMLHttpRequest();
    request.open("POST", this.options.endpoint, true);
    request.onload = function() {
      for(var i in self._requests)
      {
        if(self._requests[i] === request)
        {
          self._requests.splice(i,1); //We remove the request from the list of currently running requests.
          break;
        }
      }

      if (this.status >= 200 && this.status < 400) {
        self.callback(JSON.parse(this.responseText));
      }
    };

    this._requests.push(request);
    request.send(postData);
  },

  onAdd: function (map) {
    this._map = map;

    if (this.options.endpoint.indexOf("http") != -1) {
		this.onMoveEnd();

		if(!this.options.once) {
			map.on('dragend', this.onMoveEnd, this);
			map.on('zoomend', this.onMoveEnd, this);

			if (this.options.pollTime > 0) {
			  this.intervalID = window.setInterval(this.onMoveEnd.bind(this), this.options.pollTime);
			}
		}
	}

    if (this.options.debug) {
      console.debug("add layer");
    }
  },

  onRemove: function (map) {
    if (this.options.debug) {
      console.debug("remove layer");
    }
    L.LayerGroup.prototype.onRemove.call(this, map);

    if (!this.options.once && this.options.pollTime > 0) {
      window.clearInterval(this.intervalID);
    }

    while(this._requests.length > 0)
    {
      this._requests.shift().abort();
    }

    if(!this.options.once) {
		map.off({
		  'dragend': this.onMoveEnd
		}, this);
		map.off({
		  'zoomend': this.onMoveEnd
		}, this);
	}

    this._map = null;
  }

});

L.uGeoJSONLayer = function (uOptions, options) {
  return new L.UGeoJSONLayer(uOptions, options);
};
<|endoftext|>


<commit_before>'use strict';

class SQLString {
  constructor(query, ...args) {
    this.query = query == null ? '' : query.toString();
    this.args = args;
  }

  escape(obj, quote, name, format='$&') {
    let type = typeof obj;
    if (obj == null) {
      return 'NULL';
    }
    if (type === 'number' || type === 'boolean') {
      obj = +obj;
    }
    if (type !== 'object') {
      return this.escapeString(obj.toString(), quote);
    }
    if (obj instanceof SQLString) {
      let res = obj.toString().replace(/.*/, format);
      if (name != null && quote === '`') {
        let alias = this.escapeString(name, '`');
        res = `(${res}) AS ${alias}`;
      }
      return res;
    }
    if (obj instanceof Date) {
      return this.escapeDate(obj);
    }
    if (Array.isArray(obj)) {
      return this.escapeArray(obj, quote).replace(/.*/, format);
    }
    return this.escapeObject(obj, quote).replace(/.*/, format);
  }

  escapeString(str, quote="'") {
    let map = {
      '\0': '\\0',
      '\b': '\\b',
      '\t': '\\t',
      '\n': '\\n',
      '\r': '\\r',
      '\x1a': '\\Z',
      '"': '\\"',
      "'": "\\'",
      '`': '\\`',
      '\\': '\\\\',
    };
    let re = new RegExp('[' + Object.keys(map).map(c => {
      return '\\x' + ('0' + c.charCodeAt(0).toString(16)).slice(-2);
    }).join('') + ']', 'g');
    return quote + str.replace(re, c => map[c]) + quote;
  }

  escapeArray(arr, quote="'", separator=', ') {
    return arr.map(e => this.escape(e, quote, null, '($&)')).join(separator);
  }

  escapeObject(obj, quote="'", separator=', ') {
    return Object.keys(obj).map(key => {
      let k = this.escape(key, '`');
      let v = this.escape(obj[key], quote, null, '($&)');
      if (quote === '`') {
        return `${v} AS ${k}`;
      }
      return `${k} = ${v}`;
    }).join(separator);
  }

  escapeDate(d) {
    let year = ('000' + d.getFullYear()).slice(-4);
    let month = ('0' + (d.getMonth() + 1)).slice(-2);
    let date = ('0' + d.getDate()).slice(-2);
    let hour = ('0' + d.getHours()).slice(-2);
    let minute = ('0' + d.getMinutes()).slice(-2);
    let second = ('0' + d.getSeconds()).slice(-2);
    let msecond = ('00' + d.getMilliseconds()).slice(-3) + '000';
    if (+msecond) {
      return `${year}/${month}/${date} ${hour}:${minute}:${second}.${msecond}`;
    }
    return `${year}/${month}/${date} ${hour}:${minute}:${second}`;
  }

  toString() {
    let args = Array.from(this.args);
    return this.query.replace(/(\?\??)|(::?)(\w+)/g, (all, q, c, name) => {
      if (q != null) {
        let arg = args.shift();
        return this.escape(arg, q.length === 1 ? "'" : '`');
      }
      for (let arg of args) {
        if (typeof arg !== 'object' || arg[name] == null) {
          continue;
        }
        return this.escape(arg[name], c.length === 1 ? "'" : '`', name);
      }
      return all;
    }).replace(/^\s*|\s*$/, '');
  }
}

var sql = function(...args) {
  return new SQLString(...args).toString();
};
sql.SQLString = SQLString;
module.exports = sql;
<commit_msg>Fix to quote Date type<commit_after>'use strict';

class SQLString {
  constructor(query, ...args) {
    this.query = query == null ? '' : query.toString();
    this.args = args;
  }

  escape(obj, quote, name, format='$&') {
    let type = typeof obj;
    if (obj == null) {
      return 'NULL';
    }
    if (type === 'number' || type === 'boolean') {
      obj = +obj;
    }
    if (type !== 'object') {
      return this.escapeString(obj.toString(), quote);
    }
    if (obj instanceof SQLString) {
      let res = obj.toString().replace(/.*/, format);
      if (name != null && quote === '`') {
        let alias = this.escapeString(name, '`');
        res = `(${res}) AS ${alias}`;
      }
      return res;
    }
    if (obj instanceof Date) {
      return this.escapeDate(obj);
    }
    if (Array.isArray(obj)) {
      return this.escapeArray(obj, quote).replace(/.*/, format);
    }
    return this.escapeObject(obj, quote).replace(/.*/, format);
  }

  escapeString(str, quote="'") {
    let map = {
      '\0': '\\0',
      '\b': '\\b',
      '\t': '\\t',
      '\n': '\\n',
      '\r': '\\r',
      '\x1a': '\\Z',
      '"': '\\"',
      "'": "\\'",
      '`': '\\`',
      '\\': '\\\\',
    };
    let re = new RegExp('[' + Object.keys(map).map(c => {
      return '\\x' + ('0' + c.charCodeAt(0).toString(16)).slice(-2);
    }).join('') + ']', 'g');
    return quote + str.replace(re, c => map[c]) + quote;
  }

  escapeArray(arr, quote="'", separator=', ') {
    return arr.map(e => this.escape(e, quote, null, '($&)')).join(separator);
  }

  escapeObject(obj, quote="'", separator=', ') {
    return Object.keys(obj).map(key => {
      let k = this.escape(key, '`');
      let v = this.escape(obj[key], quote, null, '($&)');
      if (quote === '`') {
        return `${v} AS ${k}`;
      }
      return `${k} = ${v}`;
    }).join(separator);
  }

  escapeDate(d) {
    let year = ('000' + d.getFullYear()).slice(-4);
    let month = ('0' + (d.getMonth() + 1)).slice(-2);
    let date = ('0' + d.getDate()).slice(-2);
    let hour = ('0' + d.getHours()).slice(-2);
    let minute = ('0' + d.getMinutes()).slice(-2);
    let second = ('0' + d.getSeconds()).slice(-2);
    let msecond = ('00' + d.getMilliseconds()).slice(-3) + '000';
    let res = `${year}/${month}/${date} ${hour}:${minute}:${second}`;
    if (+msecond) {
      res += `.${msecond}`;
    }
    return this.escapeString(res);
  }

  toString() {
    let args = Array.from(this.args);
    return this.query.replace(/(\?\??)|(::?)(\w+)/g, (all, q, c, name) => {
      if (q != null) {
        let arg = args.shift();
        return this.escape(arg, q.length === 1 ? "'" : '`');
      }
      for (let arg of args) {
        if (typeof arg !== 'object' || arg[name] == null) {
          continue;
        }
        return this.escape(arg[name], c.length === 1 ? "'" : '`', name);
      }
      return all;
    }).replace(/^\s*|\s*$/, '');
  }
}

var sql = function(...args) {
  return new SQLString(...args).toString();
};
sql.SQLString = SQLString;
module.exports = sql;
<|endoftext|>


<commit_before>const Discord = require("discord.js");
const client = new Discord.Client();
const ytdl = require("ytdl-core");
//gotta import that fancy config file
const config = require("./config.json")['configuration'];

client.on("ready", () => {
  console.log(`Logged in as ${client.user.tag}`);
  if (config['custom-game'] == "") {
    client.user.setGame(config['prefix'] + "help");
  } else {
    client.user.setGame(config['custom-game']);
  }
  console.log('SalmonSounds bot is successfully up and running!');
});
client.on("disconnect", () => {
  console.log('Disconnected!');
});
client.on("reconnecting", ()=>{
  console.log('Attempting to reconnect.');
});

client.on("message", (message) => { //eww these indents suck but i'm too lazy to change the setting
  if(message.author.id == client.user.id || message.author.bot) return;
  if(message.content.toLowerCase().startsWith(config['prefix'] + 'join')){
    if(message.member.voiceChannel){
      if(message.member.voiceChannel.joinable){
        message.member.voiceChannel.join().then((vc)=>{
          message.reply('Joining `' + message.member.voiceChannel.name + '`');
        });
      } else {
        message.reply("It seems that you are in a voice channel, but I can't join!");
      }
    } else {
      message.reply("You are not in a voice channel!");
    }
  }

  if (message.content.toLowerCase().startsWith(config["prefix"] + "play")) {
    if (message.member.voiceChannel) {
      if (message.member.voiceChannel.joinable) {
        var parser = message.content.split(" "), parsed = [];
        for (let i = 0; i <= parser.length; i++) {
          if (i >= 1) {
          	parsed.push(parser[i]);		//Horrible parser because javascript sucks
          }
        }
        parsed = parsed.join(" ");
        parsed = parsed.substring(0, parsed.length - 1);

        //Parser debug
        //message.channel.send(parsed);
        try {
          var stream = ytdl(parsed, {filter: "audioonly"});
          ytdl.getInfo(parsed).then((i, f) => {
            message.channel.send({embed: {
              color: 16753920,
              thumbnail: {
                url: i["iurl"]
              },
              author: {
                name: client.user.username,
                icon_url: client.user.displayAvatarURL
              },
              fields: [
                {
                  name: "Title",
                  value: i["title"],
                  inline: true
                },
                {
                  name: "Author",
                  value: i["author"]["name"],
                  inline: true
                },
                {
                  name: "Length (seconds)",
                  value: i["length_seconds"],
                  inline: true
                },
                {
                  name: "Views",
                  value: i["view_count"],
                  inline: true
                }
              ]
            }});
            message.member.voiceChannel.join().then((connection) => {
              message.channel.send("Joining `" + message.member.voiceChannel.name + "`");
              connection.playStream(stream).on("end", ()=> {connection.disconnect();});
            });
          });
        } catch (e) {
          message.channel.send(e.message);
        }
      } else {
        message.reply("It seems that you are in a voice channel, but I can't join!");
      }
    } else {
      message.reply("You are not in a voice channel!");
    }
  }

  if(message.content.toLowerCase() == config['prefix'] + 'invite'){
    message.reply('join our server! ' + config['guild-invite-link']);
  }
  if (message.content.toLowerCase() == config["prefix"] + "stop" || message.content.toLowerCase() == config["prefix"] + "disconnect" || message.content.toLowerCase() == config["prefix"] + "leave") {
  	if (message.guild.voiceConnection) {
      message.guild.voiceConnection.disconnect();
      message.channel.send("Disconnected.");
      return;
  	} else {
  		message.reply("I am not in a voice channel!");
    }
	}/*
Broken

  if(message.content.toLowerCase() == config['prefix'] + 'eval' && config["enable-eval"] == true){
    if(config['botAdmins'].includes(message.author.id)){
      console.log(`EVAL RAN BY <${message.author}>: ${message.content.substring((config['prefix'] + 'eval').length)}`);
      eval(message.content.substring((config['prefix'] + 'eval').length));
    }else{
      console.log(`EVAL ATTEMPT FROM <${message.author}> FAILED`);
    }
  }*/
  if(message.content.toLowerCase() == config['prefix'] + 'view-config'){
    message.channel.send({embed: {
      color: 16753920,
      author: {
        name: client.user.username,
        icon_url: client.user.displayAvatarURL
      },
      fields: [
        {
          name: "Token",
          value: "**SECRET**",
          inline: true
        },
        {
          name: "Blacklisted Sites",
          value: (function(){
            if(config['blacklisted-sites'] == ''){
              return 'None set';
            }else{
              return config['blacklisted-sites'].join(', ');
            }
          })(),
          inline: true
        },
        {
          name: "Custom Game Text",
          value: (function(){
            if (config['custom-game'] == "") {
              return "Not set";
            } else {
              return config['custom-game'];
            }
          })(),
          inline: true
        },
        {
          name:'Status',
          value: client.user.presence.status,
          inline: true
        },
        {
          name: 'prefix',
          value: config['prefix'],
          inline: true
        },
        {
          name: 'Discord Server Invite Link',
          value: (function(){
            if (config['guild-invite-link'] == "") {
              return "Not set";
            } else {
              return config['guild-invite-link'];
            }
          })(),
          inline: true
        },
        {
          name: 'Bot Administrators (User IDs)',
          value: (function(){
            if(config['botAdmins'] == ''){
              return 'None set';
            }else{
              return config['botAdmins'].join(', ');
            }
          })(),
          inline: true
        },
        {
          name: 'Eval for Administrators',
          value: config['enable-eval'],
          inline: true
        }]

    }});
  }
});

client.login(config['token']);
<commit_msg>Link to video on embed<commit_after>const Discord = require("discord.js");
const client = new Discord.Client();
const ytdl = require("ytdl-core");
//gotta import that fancy config file
const config = require("./config.json")['configuration'];

client.on("ready", () => {
  console.log(`Logged in as ${client.user.tag}`);
  if (config['custom-game'] == "") {
    client.user.setGame(config['prefix'] + "help");
  } else {
    client.user.setGame(config['custom-game']);
  }
  console.log('SalmonSounds bot is successfully up and running!');
});
client.on("disconnect", () => {
  console.log('Disconnected!');
});
client.on("reconnecting", ()=>{
  console.log('Attempting to reconnect.');
});

client.on("message", (message) => { //eww these indents suck but i'm too lazy to change the setting
  if(message.author.id == client.user.id || message.author.bot) return;
  if(message.content.toLowerCase().startsWith(config['prefix'] + 'join')){
    if(message.member.voiceChannel){
      if(message.member.voiceChannel.joinable){
        message.member.voiceChannel.join().then((vc)=>{
          message.reply('Joining `' + message.member.voiceChannel.name + '`');
        });
      } else {
        message.reply("It seems that you are in a voice channel, but I can't join!");
      }
    } else {
      message.reply("You are not in a voice channel!");
    }
  }

  if (message.content.toLowerCase().startsWith(config["prefix"] + "play")) {
    if (message.member.voiceChannel) {
      if (message.member.voiceChannel.joinable) {
        var parser = message.content.split(" "), parsed = [];
        for (let i = 0; i <= parser.length; i++) {
          if (i >= 1) {
          	parsed.push(parser[i]);		//Horrible parser because javascript sucks
          }
        }
        parsed = parsed.join(" ");
        parsed = parsed.substring(0, parsed.length - 1);

        //Parser debug
        //message.channel.send(parsed);
        try {
          var stream = ytdl(parsed, {filter: "audioonly"});
          ytdl.getInfo(parsed).then((i, f) => {
            message.channel.send({embed: {
              color: 16753920,
              thumbnail: {
                url: i["iurl"]
              },
              author: {
                name: client.user.username,
                icon_url: client.user.displayAvatarURL,
              },
              title: i["title"],
              url: i["video_url"],
              fields: [
                {
                  name: "Author",
                  value: i["author"]["name"],
                  inline: true
                },
                {
                  name: "Length (seconds)",
                  value: i["length_seconds"],
                  inline: true
                },
                {
                  name: "Views",
                  value: i["view_count"],
                  inline: true
                }
              ]
            }});
            message.member.voiceChannel.join().then((connection) => {
              message.channel.send("Joining `" + message.member.voiceChannel.name + "`");
              connection.playStream(stream).on("end", ()=> {connection.disconnect();});
            });
          });
        } catch (e) {
          message.channel.send(e.message);
        }
      } else {
        message.reply("It seems that you are in a voice channel, but I can't join!");
      }
    } else {
      message.reply("You are not in a voice channel!");
    }
  }

  if(message.content.toLowerCase() == config['prefix'] + 'invite'){
    message.reply('join our server! ' + config['guild-invite-link']);
  }
  if (message.content.toLowerCase() == config["prefix"] + "stop" || message.content.toLowerCase() == config["prefix"] + "disconnect" || message.content.toLowerCase() == config["prefix"] + "leave") {
  	if (message.guild.voiceConnection) {
      message.guild.voiceConnection.disconnect();
      message.channel.send("Disconnected.");
      return;
  	} else {
  		message.reply("I am not in a voice channel!");
    }
	}/*
Broken

  if(message.content.toLowerCase() == config['prefix'] + 'eval' && config["enable-eval"] == true){
    if(config['botAdmins'].includes(message.author.id)){
      console.log(`EVAL RAN BY <${message.author}>: ${message.content.substring((config['prefix'] + 'eval').length)}`);
      eval(message.content.substring((config['prefix'] + 'eval').length));
    }else{
      console.log(`EVAL ATTEMPT FROM <${message.author}> FAILED`);
    }
  }*/
  if(message.content.toLowerCase() == config['prefix'] + 'view-config'){
    message.channel.send({embed: {
      color: 16753920,
      author: {
        name: client.user.username,
        icon_url: client.user.displayAvatarURL
      },
      fields: [
        {
          name: "Token",
          value: "**SECRET**",
          inline: true
        },
        {
          name: "Blacklisted Sites",
          value: (function(){
            if(config['blacklisted-sites'] == ''){
              return 'None set';
            }else{
              return config['blacklisted-sites'].join(', ');
            }
          })(),
          inline: true
        },
        {
          name: "Custom Game Text",
          value: (function(){
            if (config['custom-game'] == "") {
              return "Not set";
            } else {
              return config['custom-game'];
            }
          })(),
          inline: true
        },
        {
          name:'Status',
          value: client.user.presence.status,
          inline: true
        },
        {
          name: 'prefix',
          value: config['prefix'],
          inline: true
        },
        {
          name: 'Discord Server Invite Link',
          value: (function(){
            if (config['guild-invite-link'] == "") {
              return "Not set";
            } else {
              return config['guild-invite-link'];
            }
          })(),
          inline: true
        },
        {
          name: 'Bot Administrators (User IDs)',
          value: (function(){
            if(config['botAdmins'] == ''){
              return 'None set';
            }else{
              return config['botAdmins'].join(', ');
            }
          })(),
          inline: true
        },
        {
          name: 'Eval for Administrators',
          value: config['enable-eval'],
          inline: true
        }]

    }});
  }
});

client.login(config['token']);
<|endoftext|>


<commit_before>const getParameterNames = require('get-parameter-names');
const RSVP = require('rsvp');

function Module(){
   this.binds = {};
}

Module.prototype = {

    bind: function(paramName, factory){

       this.binds[paramName] = factory;

    },

    bindClass: function(paramName, ctor){

       var paramNames = getParameterNames(ctor);
       var paramList = paramNames.join();

       eval(['var f=function('+paramList+'){',
             ' return new ctor('+paramList+');',
             '}'].join('\n')) ;

       var ctorWraperFactory = f;

       this.binds[paramName] = ctorWraperFactory;

    }
}

function Container(){
   this.binds = {};
}

Container.prototype = {

   load: function(modules){

      for(var i=0; i < modules.length; i++){
         var m = modules[i];

         for(p in m.binds){
            this.binds[p] = m.binds[p];
         }
      }

   },

   get: function(callback){

      var factory = callback;

      this.resolve(factory)
          .catch(function(error){
               callback.apply(null, [error]);
          });

   },

   resolve: function(factory){
      var injections = [];
      var dependencies = getParameterNames(factory);

      for(var i=0; i < dependencies.length; i++){
         var dependency = dependencies[i];
         var dependencyBind = this.binds[dependency];
         var dependencyResolution = null;

         if(dependencyBind != null){
             dependencyResolution = this.resolve(dependencyBind);
         }

         var dependencyResolutionIsAPromise = dependencyResolution != null
                                              && typeof(dependencyResolution.then) == 'function';

         var dependencyResolutionPromise = dependencyResolutionIsAPromise ?
                                           dependencyResolution :
                                           this.wrapInPromise(dependencyResolution);

         injections.push(dependencyResolutionPromise);

      }

      var injectionsPromise = RSVP.all(injections).then(function(i){

           return factory.apply(null, i);

      });

      return injectionsPromise
   },

   wrapInPromise: function(value){
       return new Promise(function(resolve, reject){
           resolve(value);
       });
   }
}

exports = module.exports = {
   Module: Module,
   Container: Container
}
<commit_msg>Container refactor<commit_after>const getParameterNames = require('get-parameter-names');
const RSVP = require('rsvp');

function Module(){
   this.binds = {};
}

Module.prototype = {

    bind: function(paramName, factory){

       this.binds[paramName] = factory;

    },

    bindClass: function(paramName, ctor){

       var paramNames = getParameterNames(ctor);
       var paramList = paramNames.join();

       eval(['var f=function('+paramList+'){',
             ' return new ctor('+paramList+');',
             '}'].join('\n')) ;

       var ctorWraperFactory = f;

       this.binds[paramName] = ctorWraperFactory;

    },
    getBinds(){
        return this.binds;
    }
}

function Container(){
   this.module = new Module();
}

Container.prototype = {
   getBinds: function(){
       return this.module.getBinds();
   },

   bind: function (paramName, factory) {
       this.module.bind(paramName, factory);
   },

   bindClass: function (paramName, ctor) {
       this.module.bindClass(paramName, ctor);
   },

   load: function(modules){

      for(var i=0; i < modules.length; i++){
         var module = modules[i];
         var moduleBinds = module.getBinds();

         for(p in moduleBinds){
            this.bind(p, moduleBinds[p]);
         }
      }

   },

   get: function(callback){

      var factory = callback;

      this.resolve(factory)
          .catch(function(error){
               callback.apply(null, [error]);
          });

   },

   resolve: function(factory){
      var injections = [];
      var dependencies = getParameterNames(factory);

      for(var i=0; i < dependencies.length; i++){
         var dependency = dependencies[i];
         var dependencyBind = this.getBinds()[dependency];
         var dependencyResolution = null;

         if(dependencyBind != null){
             dependencyResolution = this.resolve(dependencyBind);
         }

         var dependencyResolutionIsAPromise = dependencyResolution != null
                                              && typeof(dependencyResolution.then) == 'function';

         var dependencyResolutionPromise = dependencyResolutionIsAPromise ?
                                           dependencyResolution :
                                           this.wrapInPromise(dependencyResolution);

         injections.push(dependencyResolutionPromise);

      }

      var injectionsPromise = RSVP.all(injections).then(function(i){

           return factory.apply(null, i);

      });

      return injectionsPromise
   },

   wrapInPromise: function(value){
       return new Promise(function(resolve, reject){
           resolve(value);
       });
   }
}

exports = module.exports = {
   Module: Module,
   Container: Container
}
<|endoftext|>


<commit_before>'use strict';

var match = require('string-match');

module.exports = function(name){
  // TODO: split out RegExps for each type(x264, TV, MP3, Games, etc.)
  var data = {
    year: match(name, /(?!^)[1,2]\d{3}/),
    resolution: match(name, /\d{3,4}p/i),
    type: match(name, /CAM|TS|TELESYNC|(DVD|BD)SCR|SCR|DDC|R5\.LINE|R5|DVDR|(HD|PD)TV|WEB-DL|WEBDL|BluRay|(DVD|HD|BR|BD)Rip/i),
    video: match(name, /[xh][\.\s]?264/i),
    audio: match(name, /AAC2[\.\s]0|AAC|AC3|DTS|DD5[\.\s]1/i),
    language: match(name, /MULTiSUBS|MULTi|NORDiC|DANiSH|SWEDiSH|NORWEGiAN|GERMAN|iTALiAN|FRENCH|SPANiSH/i),
    edition: match(name, /UNRATED|DC|(Directors|EXTENDED)\.(CUT|EDITION)|EXTENDED|3D|2D/i),
    tags: name.match(/COMPLETE|LiMiTED|iNTERNAL/i),
    release: match(name, /PROPER|REPACK|READNFO|READ\.NFO|DiRFiX|NFOFiX/i),
    group: match(name, /[A-Za-z0-9]+$/)
  };

  var matches = '';
  for(var key in data){
    var value = data[key];
    if(!value) continue;

    matches += value + '|';
  }

  data.title = name
    .replace(RegExp(matches + '-', 'g'), '')
    .replace(/\./g, ' ')
    .trim();
  data.original = name;

  Object.keys(data).forEach(function(key) {
    if(!data[key]){
      delete data[key];
    }
  });

  return data;
};
<commit_msg>Fix usage of string-match for `tags`<commit_after>'use strict';

var match = require('string-match');

module.exports = function(name){
  // TODO: split out RegExps for each type(x264, TV, MP3, Games, etc.)
  var data = {
    year: match(name, /(?!^)[1,2]\d{3}/),
    resolution: match(name, /\d{3,4}p/i),
    type: match(name, /CAM|TS|TELESYNC|(DVD|BD)SCR|SCR|DDC|R5\.LINE|R5|DVDR|(HD|PD)TV|WEB-DL|WEBDL|BluRay|(DVD|HD|BR|BD)Rip/i),
    video: match(name, /[xh][\.\s]?264/i),
    audio: match(name, /AAC2[\.\s]0|AAC|AC3|DTS|DD5[\.\s]1/i),
    language: match(name, /MULTiSUBS|MULTi|NORDiC|DANiSH|SWEDiSH|NORWEGiAN|GERMAN|iTALiAN|FRENCH|SPANiSH/i),
    edition: match(name, /UNRATED|DC|(Directors|EXTENDED)\.(CUT|EDITION)|EXTENDED|3D|2D/i),
    tags: match(name, /COMPLETE|LiMiTED|iNTERNAL/i),
    release: match(name, /PROPER|REPACK|READNFO|READ\.NFO|DiRFiX|NFOFiX/i),
    group: match(name, /[A-Za-z0-9]+$/)
  };

  var matches = '';
  for(var key in data){
    var value = data[key];
    if(!value) continue;

    matches += value + '|';
  }

  data.title = name
    .replace(RegExp(matches + '-', 'g'), '')
    .replace(/\./g, ' ')
    .trim();
  data.original = name;

  Object.keys(data).forEach(function(key) {
    if(!data[key]){
      delete data[key];
    }
  });

  return data;
};
<|endoftext|>


<commit_before>var _ = require('lodash'),
    q = require('bluebird'),
    fs = require('fs'),
    glob = require('glob'),
    introspect = require('introspect'),
    TimeoutError = q.TimeoutError;

function defer() {
    var deferred = { };
    deferred.promise = new q(function() {
        deferred.resolve = arguments[0];
        deferred.reject = arguments[1];
    });
    return deferred;
}

var Majic = function options(opts, defs) {
    if (!_.isObject(opts)) opts = { root: opts };

    _.defaults(this, opts, defs, {
        PREFIX: "majic:",
        ready: defer(),
        container: {},
        root: __dirname,
        verbose: true,
        scan: [ "config/**", "src/lib/**", "src/main/**" ]
    });
}

Majic.prototype.declare = function(name, timeout, override) {
    var v = override ? undefined : this.container[name];
    if (!v) {
        this.container[name] = v = defer();
        if (timeout) {
            v.promise.timeout(timeout).catch(TimeoutError, function() {
                if (this.verbose) console.warn(this.PREFIX, "timeout resolving " + name);
            }.bind(this));
        }
    }
    return v;
}

Majic.prototype.resolve = function(name, timeout) {
    return this.declare(name, timeout).promise;
}

Majic.prototype.alias = function(src, dst) {
    this.resolve(src).then(function(v) {
        if (this.verbose) console.log(this.PREFIX, "aliased module", dst, "from", src);
        this.declare(dst).resolve(v);
    }.bind(this));
}

Majic.prototype.inject = function(fn, name) {
    var params = introspect(fn);

    return this.ready.promise.then(function() {
        return q.all(_.map(params, function(p) { return this.resolve(p, 2000) }.bind(this))).then(function(args) {
            if (this.verbose && name) console.log(this.PREFIX, "resolving module", name, "with args", params);
            return fn.apply(null, args);
        }.bind(this));
    }.bind(this));
}

Majic.prototype.crequire = function(name, path, module, override) {
    name = name.replace(/\-/gi, '_');

    var from = module ? "from npm" : "from"
    var deferred = this.declare(name, module ? undefined : 2000, override);
    var req = require(path);

    if (_.isFunction(req) && !module) {
        if (this.verbose) console.log(this.PREFIX, "loading module", name, from, path);
        this.inject(req, name).then(deferred.resolve);
    } else {
        if (this.verbose) console.log(this.PREFIX, "defined module", name, from, path);
        deferred.resolve(req);
    }

    return deferred.promise;
}

Majic.prototype.load_module = function(file, override) {
    return new q(function(resolve, reject) {
        fs.stat(file, function(err, stats) {
            if (err) { return reject(err); }

            var path = file.split("/");
            var name = path[path.length-1].split('.')[0]

            if (stats.isFile() && !_.contains(this.exclude, name)) {
                this.crequire(name, file, false, override);
            }
            resolve(true);
        }.bind(this));
    }.bind(this));
}

Majic.prototype.scan_paths = function(globs, override) {
    return q.all(_.map(globs, function(pattern) {
        return new q(function(resolve, reject) {
            var path = this.root+"/"+pattern
            if (this.verbose) console.log(this.PREFIX, "scanning path", path, "for modules")
            glob(path, function(err, files) {
                if (err) { return reject(err); }
                q.all(_.map(files, function(f) {
                    return this.load_module(f, override);
                }.bind(this))).then(resolve, reject);
            }.bind(this));
        }.bind(this));
    }.bind(this)));
}

Majic.prototype.dependencies = function(dependencies) {
    _.each(dependencies, function (version, name) {
        if (name == 'Majic') { return; }

        resolved = this.crequire(name, name, true);

        if (name == "coffee-script") {
            require('coffee-script/register');
        }

        if (name == "chai") {
            resolved.then(function (chai) {
                this.declare('expect').resolve(chai.expect);
            }.bind(this));
        }
    }.bind(this));
}

Majic.prototype.init = function() {
    this.alias('bluebird', 'q');
    this.alias('lodash', '_');
    this.alias('underscore', '_');

    this.package = require(this.root+'/package.json');

    if (this.package.dependencies) { this.dependencies(this.package.dependencies); }
    if (!this.package.cio) { this.package.cio = {} };

    return this.scan_paths(this.package.cio.scan || this.scan);
}

Majic.prototype.start = function() {
    this.ready.resolve();
    return this.ready.promise;
}

function start(opts) {
    var majic = new Majic(opts);
    return majic.init().then(majic.start.bind(majic));
}

function test(opts) {
    var majic = new Majic(opts, { scan: [ "config/**", "src/lib/**" ], verbose: false });

    majic.init().then(function() {
        if (majic.package.devDependencies) { majic.dependencies(majic.package.devDependencies); }
        return majic.scan_paths([ "test/mock/**" ], true).then(majic.start.bind(majic));
    });

    return function(fn) {
        return function() { return majic.inject(fn, "injected test"); }
    }
}

module.exports = {
    start: start,
    test: test
}
<commit_msg>slightly more compact<commit_after>var _ = require('lodash'),
    q = require('bluebird'),
    fs = require('fs'),
    glob = require('glob'),
    introspect = require('introspect'),
    TimeoutError = q.TimeoutError;

function defer() {
    var deferred = { };
    deferred.promise = new q(function() {
        deferred.resolve = arguments[0];
        deferred.reject = arguments[1];
    });
    return deferred;
}

var Majic = function options(opts, defs) {
    if (!_.isObject(opts)) opts = { root: opts };

    _.defaults(this, opts, defs, {
        PREFIX: "majic:",
        ready: defer(),
        container: {},
        root: __dirname,
        verbose: true,
        scan: [ "config/**", "src/lib/**", "src/main/**" ]
    });
}

Majic.prototype.declare = function(name, timeout, override) {
    var v = override ? undefined : this.container[name];
    if (!v) {
        this.container[name] = v = defer();
        if (timeout) {
            v.promise.timeout(timeout).catch(TimeoutError, function() {
                if (this.verbose) console.warn(this.PREFIX, "timeout resolving " + name);
            }.bind(this));
        }
    }
    return v;
}

Majic.prototype.resolve = function(name, timeout) {
    return this.declare(name, timeout).promise;
}

Majic.prototype.alias = function(src, dst) {
    this.resolve(src).then(function(v) {
        if (this.verbose) console.log(this.PREFIX, "aliased module", dst, "from", src);
        this.declare(dst).resolve(v);
    }.bind(this));
}

Majic.prototype.inject = function(fn, name) {
    var params = introspect(fn);

    return this.ready.promise.then(function() {
        return q.all(_.map(params, function(p) { return this.resolve(p, 2000) }.bind(this))).then(function(args) {
            if (this.verbose && name) console.log(this.PREFIX, "resolving module", name, "with args", params);
            return fn.apply(null, args);
        }.bind(this));
    }.bind(this));
}

Majic.prototype.crequire = function(name, path, module, override) {
    name = name.replace(/\-/gi, '_');

    var from = module ? "from npm" : "from"
    var deferred = this.declare(name, module ? undefined : 2000, override);
    var req = require(path);

    if (_.isFunction(req) && !module) {
        if (this.verbose) console.log(this.PREFIX, "loading module", name, from, path);
        this.inject(req, name).then(deferred.resolve);
    } else {
        if (this.verbose) console.log(this.PREFIX, "defined module", name, from, path);
        deferred.resolve(req);
    }

    return deferred.promise;
}

Majic.prototype.load_module = function(file, override) {
    return new q(function(resolve, reject) {
        fs.stat(file, function(err, stats) {
            if (err) { return reject(err); }

            var path = file.split("/");
            var name = path[path.length-1].split('.')[0]

            if (stats.isFile() && !_.contains(this.exclude, name)) {
                this.crequire(name, file, false, override);
            }
            resolve(true);
        }.bind(this));
    }.bind(this));
}

Majic.prototype.scan_paths = function(globs, override) {
    return q.all(_.map(globs, function(pattern) {
        return new q(function(resolve, reject) {
            var path = this.root+"/"+pattern
            if (this.verbose) console.log(this.PREFIX, "scanning path", path, "for modules")
            glob(path, function(err, files) {
                if (err) { return reject(err); }
                q.all(_.map(files, function(f) {
                    return this.load_module(f, override);
                }.bind(this))).then(resolve, reject);
            }.bind(this));
        }.bind(this));
    }.bind(this)));
}

Majic.prototype.dependencies = function(dependencies) {
    _.each(dependencies, function (version, name) {
        if (name == 'Majic') { return; }

        resolved = this.crequire(name, name, true);

        if (name == "coffee-script") {
            require('coffee-script/register');
        }

        if (name == "chai") {
            resolved.then(function (chai) {
                this.declare('expect').resolve(chai.expect);
            }.bind(this));
        }
    }.bind(this));
}

Majic.prototype.init = function() {
    this.alias('bluebird', 'q');
    this.alias('lodash', '_');
    this.alias('underscore', '_');

    this.package = require(this.root+'/package.json');

    if (this.package.dependencies) { this.dependencies(this.package.dependencies); }
    if (!this.package.cio) { this.package.cio = {} };

    return this.scan_paths(this.package.cio.scan || this.scan);
}

Majic.prototype.start = function() {
    this.ready.resolve();
    return this.ready.promise;
}

module.exports = {
    start: function (opts) {
        var majic = new Majic(opts);
        return majic.init().then(majic.start.bind(majic));
    },
    test: function test(opts) {
        var majic = new Majic(opts, { scan: [ "config/**", "src/lib/**" ], verbose: false });

        majic.init().then(function() {
            if (majic.package.devDependencies) { majic.dependencies(majic.package.devDependencies); }
            return majic.scan_paths([ "test/mock/**" ], true).then(majic.start.bind(majic));
        });

        return function(fn) {
            return function() { return majic.inject(fn, "injected test"); }
        }
    }
}
<|endoftext|>


<commit_before>"use strict";

// Socket Connections - All sockets connected will be stored in this connections array
const connections = [];
// This is the interface of connections (Just for our reference becos we love typescript so much)
// Connections: []Connection
// Connection {
//     id: string;
//     profileName: string;
//     secretCode: string;
//     ready: boolean
//     userType: string;
// }
const rooms = [];
// room: Room
// Room {
  // name: string;
  // secretCode: string;
  // readySessionEnabled: boolean;
// }
var availableCodeList = ['MARTINI','FAITH','DIAGONAL','MAGIC','BOOZE','MASTER', 'HEROIC','HUSTLE','CODE','RUBY','PARADOX','CANVAS','ISLAND','WONDER'];
var usedCodeList = [];

function findConnection(id){
  return connections.filter(function(connection) {return connection.id === id;})[0];
}
function findRoom(secretCode){
  return rooms.filter(function(room) {return room.secretCode === secretCode;})[0];
}
function findNumberOfRoomConnections(secretCode){
  var roomConnections = connections.filter(function(connection) {return connection.secretCode === secretCode})
  return roomConnections.length;
}
function findNumberOfReadyConnections(secretCode){
  var readyConnections = connections.filter(function(connection) {return (connection.ready === true && connection.secretCode === secretCode)})
  return readyConnections.length;
}
function resetAllStatusForRoomConnections(socket,secretCode){
  var allRoomConnections = connections.filter(function(connection) {return connection.secretCode === secretCode;});
  allRoomConnections.forEach(function(element){
    // may not necessarily want to reset profile name in future
    element.profileName = null;
    element.secretCode = null;
    element.ready = null;
    element.userType = null;
    // we need to get all sockets to leave
  })
}
function resetReadyStatusForRoomConnections(socket,secretCode){
  var allRoomConnections = connections.filter(function(connection) {return connection.secretCode === secretCode;});
  allRoomConnections.forEach(function(element){
    // may not necessarily want to reset profile name in future
    element.ready = null;
  })
}
function socketsLeaveRoom(secretCode){
  var allRoomConnections = connections.filter(function(connection) {return connection.secretCode === secretCode;});
  allRoomConnections.forEach(function(element){
    element.socket.leave(secretCode)
  })
}
function secretCodeGenerator(availableList, usedList) {
 //take first element of availableCodeList array,
 //add to end of usedCodeList
 var secretCode = availableList.shift();
 usedList.push(secretCode);
 return secretCode;
}
function returnBackSecretCode(availableList, usedList, secretCode){
  var indexOfRemovedCode = usedList.indexOf(secretCode);
  usedCodeList.splice(indexOfRemovedCode, 1);
  availableList.push(secretCode);
}

// =================================== Socket Controller Functions =================================

function connect(socket){
  //new connection, save the socket to them
  // when a socket first connects, provide all these attributes so that you would not get error when you do a status reset
  connections.push({
    socket: socket,
    id: socket.id,
    profileName: null,
    secretCode: null,
    ready: null,
    userType: null
  });
  console.log(`## New connection (${socket.id}). Total: ${connections.length}.`);
}

function disconnect(socket,io){
  //find the connection and remove  from the collection
  let connection = findConnection(socket.id);
  if (connection){
    if (connection.userType === "instructor") {
      let room = findRoom(connection.secretCode);
      if (room.readySessionEnabled === true) {
        instructorEndsReadySession(socket)
      }
      closeClass(socket,io);
    }
    if (connection.userType === "student") {
      if (connection.ready === true) {
        studentNotReady(socket, io)
      }
      studentLeaveClass(socket,io)
    }
    connections.splice(connections.indexOf(connection), 1);
    console.log(`## Connection (${connection.id}) (${socket.id}) disconnected. Remaining: ${connections.length}.`);
  }
  socket.disconnect();
}
      // =================================== Instructor ===========================

function submitClassName(socket, className){
  // this connection guy does nothing yet (just put here in case)
  var room = {
    name: className,
    // pass in secretcodefunction
    secretCode: secretCodeGenerator(availableCodeList,usedCodeList)
  }
  socket.join(room.secretCode)
  rooms.push(room);
  let connection = findConnection(socket.id);
  if (connection){
    connection.secretCode = room.secretCode;
    connection.userType = "instructor";
    socket.emit('createSecretCode', room)
  }
}

function closeClass(socket,io){
  let connection = findConnection(socket.id);
  if (connection) {
    let room = findRoom(connection.secretCode);
    if (room){
      console.log(`## Room (${room.name}) closed. Remaining: ${rooms.length}.`);
      rooms.splice(rooms.indexOf(room), 1);
      returnBackSecretCode(availableCodeList,usedCodeList,room.secretCode);
      // you want to find all connections in the room with a ready status and set them all to false
      resetAllStatusForRoomConnections(socket,room.secretCode)
      // reset room connection back to 0 for everyone when room is closed so that when you start a new room, the room starts with 0 connection
      io.to(room.secretCode).emit("updateNumberOfRoomConnections", (findNumberOfRoomConnections(room.secretCode)));
      // this socketsLeaveRoom function must come after the io because if it comes first, we would not be able to emit to all sockets in that room anymore
      socketsLeaveRoom(room.secretCode)
      socket.broadcast.to(room.secretCode).emit('studentsCloseClass')
    }
  }
}

function instructorCallReady(socket){
  // use the classroomService to emit instructorReady() to the server that we are starting are u ready
  // use the server to emit startStudentReady() to all those in the room (excluding instructor) - use broadcast
  // and in the service (listen for an emit)
  // in the emit (reroute the student into student ready)
  let connection = findConnection(socket.id);
  if (connection) {
    let room = findRoom(connection.secretCode);
    if (room) {
      room.readySessionEnabled = true;
      socket.broadcast.to(room.secretCode).emit('startStudentReady')
    }
  }
}

function instructorEndsReadySession(socket){
  let connection = findConnection(socket.id);
  if (connection){
    let room = findRoom(connection.secretCode);
    if (room) {
      // you want to find all connections in the room with a ready status and set them all to false
      room.readySessionEnabled = false;
      resetReadyStatusForRoomConnections(socket,room.secretCode)
      socket.broadcast.to(room.secretCode).emit('studentsEndReadySession')
    }
  }
}
      // =================================== Student ===========================

function submitProfileName(socket, profileName){
  let connection = findConnection(socket.id);
  if (connection){
    connection.profileName = profileName;
  }
}

function submitSecretCode(socket, secretCode, io){
  // this connection guy does nothing yet (just put here in case)
  let room = findRoom(secretCode);
  if (room) {
    let connection = findConnection(socket.id);
    if (connection){
      connection.secretCode = secretCode;
      connection.userType = "student"
      socket.join(room.secretCode)
      // emit something back so that we can route him to the next page
      // =>> added this shit in when we were sleepy
      socket.emit('secretCodeExist', {secretCodeExist: true, room: room})
      // connections should be number of sockets who are joined to the room - 1 (instructor)
      io.to(room.secretCode).emit("updateNumberOfRoomConnections", (findNumberOfRoomConnections(secretCode)-1));
    }
  } else {
    // emit him some message so that client knows that the secret code is wrong
    socket.emit('secretCodeExist', false)
  }
}

function studentLeaveClass(socket,io){
  let connection = findConnection(socket.id);
  if (connection){
    var secretCodeOfPreviousRoom = connection.secretCode
    connection.secretCode = null;
    if (connection.ready){
      connection.ready = null;
    }
    io.to(secretCodeOfPreviousRoom).emit("updateNumberOfRoomConnections", (findNumberOfRoomConnections(secretCodeOfPreviousRoom)-1))
    socket.leave(connection.secretCode)
  }
}

function studentReady(socket,io){
  let connection = findConnection(socket.id);
  if (connection){
    // the difference between studentReady and studentNotReady is setting connection.ready true and false
    connection.ready = true;
    // end of difference
    let room = findRoom(connection.secretCode);
    if (room) {
      // this socket emit is for the individual student's ready toggle button
      socket.emit("RecievedYourLovelyReadyResponse")
      // this socket broadcast is for everyone in the room so that everyone knows the number of students who are ready
      io.to(room.secretCode).emit("updateStudentReady", findNumberOfReadyConnections(connection.secretCode))
      // on the client side, it is waiting for updatestudentready
      // it will save a property for the number of studentready
      // display it on both the instructor and student dashboard
      // so we need to use the service reference hack so that both student and instructor ready component will be able to access the updated property
      // 1)Once i receive the emit, i need to save that argument that is passed to me under a property object
      // 2)I need to create a getProperty in the service (just above the constructor)
      // 3)In my two components, i need to make a getPropertyRequest
    }
  }
}

function studentNotReady(socket, io){
  let connection = findConnection(socket.id);
  if (connection){
    connection.ready = false;
    let room = findRoom(connection.secretCode);
    if (room) {
      // this socket emit is for the individual student's ready toggle button
      socket.emit("RecievedYourLovelyNotReadyResponse")
      console.log("server received lovely not ready response")
      // this socket broadcast is for everyone in the room so that everyone knows the number of students who are ready
      io.to(room.secretCode).emit("updateStudentReady", findNumberOfReadyConnections(connection.secretCode))
      console.log("studentNotReady completed run")
    }
  }
}

// Functions we are exporting to (server.js)
module.exports = {
  connect: connect,
  disconnect: disconnect,
  submitClassName: submitClassName,
  closeClass: closeClass,
  instructorEndsReadySession: instructorEndsReadySession,
  submitProfileName: submitProfileName,
  submitSecretCode: submitSecretCode,
  studentLeaveClass: studentLeaveClass,
  instructorCallReady: instructorCallReady,
  studentReady: studentReady,
  studentNotReady: studentNotReady
}
<commit_msg>change secretRoomGenerator to be random & add new codes<commit_after>"use strict";

// Socket Connections - All sockets connected will be stored in this connections array
const connections = [];
// This is the interface of connections (Just for our reference becos we love typescript so much)
// Connections: []Connection
// Connection {
//     id: string;
//     profileName: string;
//     secretCode: string;
//     ready: boolean
//     userType: string;
// }
const rooms = [];
// room: Room
// Room {
  // name: string;
  // secretCode: string;
  // readySessionEnabled: boolean;
// }
var availableCodeList = ['GROWTH','AMAZE','REFRESH','MAGIC','BOOZE','MASTER', 'HEROIC','HUSTLE','TEQUILA','POLISH','PARADOX','CANVAS','ISLAND','WONDER'];
var usedCodeList = [];

function findConnection(id){
  return connections.filter(function(connection) {return connection.id === id;})[0];
}
function findRoom(secretCode){
  return rooms.filter(function(room) {return room.secretCode === secretCode;})[0];
}
function findNumberOfRoomConnections(secretCode){
  var roomConnections = connections.filter(function(connection) {return connection.secretCode === secretCode})
  return roomConnections.length;
}
function findNumberOfReadyConnections(secretCode){
  var readyConnections = connections.filter(function(connection) {return (connection.ready === true && connection.secretCode === secretCode)})
  return readyConnections.length;
}
function resetAllStatusForRoomConnections(socket,secretCode){
  var allRoomConnections = connections.filter(function(connection) {return connection.secretCode === secretCode;});
  allRoomConnections.forEach(function(element){
    // may not necessarily want to reset profile name in future
    element.profileName = null;
    element.secretCode = null;
    element.ready = null;
    element.userType = null;
    // we need to get all sockets to leave
  })
}
function resetReadyStatusForRoomConnections(socket,secretCode){
  var allRoomConnections = connections.filter(function(connection) {return connection.secretCode === secretCode;});
  allRoomConnections.forEach(function(element){
    // may not necessarily want to reset profile name in future
    element.ready = null;
  })
}
function socketsLeaveRoom(secretCode){
  var allRoomConnections = connections.filter(function(connection) {return connection.secretCode === secretCode;});
  allRoomConnections.forEach(function(element){
    element.socket.leave(secretCode)
  })
}
function secretCodeGenerator(availableList, usedList) {
 //take first element of availableCodeList array,
 //add to end of usedCodeList
 var secretCode = availableList.splice(Math.floor(Math.random() * availableList.length), 1);
 console.log('secret code is ' + secretCode);
 usedList.push(secretCode);
 return secretCode;
}
function returnBackSecretCode(availableList, usedList, secretCode){
  var indexOfRemovedCode = usedList.indexOf(secretCode);
  usedCodeList.splice(indexOfRemovedCode, 1);
  availableList.push(secretCode);
}

// =================================== Socket Controller Functions =================================

function connect(socket){
  //new connection, save the socket to them
  // when a socket first connects, provide all these attributes so that you would not get error when you do a status reset
  connections.push({
    socket: socket,
    id: socket.id,
    profileName: null,
    secretCode: null,
    ready: null,
    userType: null
  });
  console.log(`## New connection (${socket.id}). Total: ${connections.length}.`);
}

function disconnect(socket,io){
  //find the connection and remove  from the collection
  let connection = findConnection(socket.id);
  if (connection){
    if (connection.userType === "instructor") {
      let room = findRoom(connection.secretCode);
      if (room.readySessionEnabled === true) {
        instructorEndsReadySession(socket)
      }
      closeClass(socket,io);
    }
    if (connection.userType === "student") {
      if (connection.ready === true) {
        studentNotReady(socket, io)
      }
      studentLeaveClass(socket,io)
    }
    connections.splice(connections.indexOf(connection), 1);
    console.log(`## Connection (${connection.id}) (${socket.id}) disconnected. Remaining: ${connections.length}.`);
  }
  socket.disconnect();
}
      // =================================== Instructor ===========================

function submitClassName(socket, className){
  // this connection guy does nothing yet (just put here in case)
  var room = {
    name: className,
    // pass in secretcodefunction
    secretCode: secretCodeGenerator(availableCodeList,usedCodeList)
  }
  socket.join(room.secretCode)
  rooms.push(room);
  let connection = findConnection(socket.id);
  if (connection){
    connection.secretCode = room.secretCode;
    connection.userType = "instructor";
    socket.emit('createSecretCode', room)
  }
}

function closeClass(socket,io){
  let connection = findConnection(socket.id);
  if (connection) {
    let room = findRoom(connection.secretCode);
    if (room){
      console.log(`## Room (${room.name}) closed. Remaining: ${rooms.length}.`);
      rooms.splice(rooms.indexOf(room), 1);
      returnBackSecretCode(availableCodeList,usedCodeList,room.secretCode);
      // you want to find all connections in the room with a ready status and set them all to false
      resetAllStatusForRoomConnections(socket,room.secretCode)
      // reset room connection back to 0 for everyone when room is closed so that when you start a new room, the room starts with 0 connection
      io.to(room.secretCode).emit("updateNumberOfRoomConnections", (findNumberOfRoomConnections(room.secretCode)));
      // this socketsLeaveRoom function must come after the io because if it comes first, we would not be able to emit to all sockets in that room anymore
      socketsLeaveRoom(room.secretCode)
      socket.broadcast.to(room.secretCode).emit('studentsCloseClass')
    }
  }
}

function instructorCallReady(socket){
  // use the classroomService to emit instructorReady() to the server that we are starting are u ready
  // use the server to emit startStudentReady() to all those in the room (excluding instructor) - use broadcast
  // and in the service (listen for an emit)
  // in the emit (reroute the student into student ready)
  let connection = findConnection(socket.id);
  if (connection) {
    let room = findRoom(connection.secretCode);
    if (room) {
      room.readySessionEnabled = true;
      socket.broadcast.to(room.secretCode).emit('startStudentReady')
    }
  }
}

function instructorEndsReadySession(socket){
  let connection = findConnection(socket.id);
  if (connection){
    let room = findRoom(connection.secretCode);
    if (room) {
      // you want to find all connections in the room with a ready status and set them all to false
      room.readySessionEnabled = false;
      resetReadyStatusForRoomConnections(socket,room.secretCode)
      socket.broadcast.to(room.secretCode).emit('studentsEndReadySession')
    }
  }
}
      // =================================== Student ===========================

function submitProfileName(socket, profileName){
  let connection = findConnection(socket.id);
  if (connection){
    connection.profileName = profileName;
  }
}

function submitSecretCode(socket, secretCode, io){
  // this connection guy does nothing yet (just put here in case)
  let room = findRoom(secretCode);
  if (room) {
    let connection = findConnection(socket.id);
    if (connection){
      connection.secretCode = secretCode;
      connection.userType = "student"
      socket.join(room.secretCode)
      // emit something back so that we can route him to the next page
      // =>> added this shit in when we were sleepy
      socket.emit('secretCodeExist', {secretCodeExist: true, room: room})
      // connections should be number of sockets who are joined to the room - 1 (instructor)
      io.to(room.secretCode).emit("updateNumberOfRoomConnections", (findNumberOfRoomConnections(secretCode)-1));
    }
  } else {
    // emit him some message so that client knows that the secret code is wrong
    socket.emit('secretCodeExist', false)
  }
}

function studentLeaveClass(socket,io){
  let connection = findConnection(socket.id);
  if (connection){
    var secretCodeOfPreviousRoom = connection.secretCode
    connection.secretCode = null;
    if (connection.ready){
      connection.ready = null;
    }
    io.to(secretCodeOfPreviousRoom).emit("updateNumberOfRoomConnections", (findNumberOfRoomConnections(secretCodeOfPreviousRoom)-1))
    socket.leave(connection.secretCode)
  }
}

function studentReady(socket,io){
  let connection = findConnection(socket.id);
  if (connection){
    // the difference between studentReady and studentNotReady is setting connection.ready true and false
    connection.ready = true;
    // end of difference
    let room = findRoom(connection.secretCode);
    if (room) {
      // this socket emit is for the individual student's ready toggle button
      socket.emit("RecievedYourLovelyReadyResponse")
      // this socket broadcast is for everyone in the room so that everyone knows the number of students who are ready
      io.to(room.secretCode).emit("updateStudentReady", findNumberOfReadyConnections(connection.secretCode))
      // on the client side, it is waiting for updatestudentready
      // it will save a property for the number of studentready
      // display it on both the instructor and student dashboard
      // so we need to use the service reference hack so that both student and instructor ready component will be able to access the updated property
      // 1)Once i receive the emit, i need to save that argument that is passed to me under a property object
      // 2)I need to create a getProperty in the service (just above the constructor)
      // 3)In my two components, i need to make a getPropertyRequest
    }
  }
}

function studentNotReady(socket, io){
  let connection = findConnection(socket.id);
  if (connection){
    connection.ready = false;
    let room = findRoom(connection.secretCode);
    if (room) {
      // this socket emit is for the individual student's ready toggle button
      socket.emit("RecievedYourLovelyNotReadyResponse")
      console.log("server received lovely not ready response")
      // this socket broadcast is for everyone in the room so that everyone knows the number of students who are ready
      io.to(room.secretCode).emit("updateStudentReady", findNumberOfReadyConnections(connection.secretCode))
      console.log("studentNotReady completed run")
    }
  }
}

// Functions we are exporting to (server.js)
module.exports = {
  connect: connect,
  disconnect: disconnect,
  submitClassName: submitClassName,
  closeClass: closeClass,
  instructorEndsReadySession: instructorEndsReadySession,
  submitProfileName: submitProfileName,
  submitSecretCode: submitSecretCode,
  studentLeaveClass: studentLeaveClass,
  instructorCallReady: instructorCallReady,
  studentReady: studentReady,
  studentNotReady: studentNotReady
}
<|endoftext|>


<commit_before>'use strict';
var fp = require('annofp');
var extend = require('xtend');

module.exports = function(schema) {
    var definitions = schema.definitions;
    var paths = schema.paths;

    if(!definitions) {
        return console.trace('missing definitions to resolve');
    }

    var ret = fp.deepcopy(schema);

    ret.definitions = resolveDefinitionRefs(definitions);
    ret.paths = resolvePathRefs(definitions, paths);

    return ret;
};

function resolveDefinitionRefs(definitions) {
    return fp.map(function(name, definition) {
        if(!definition.properties) {
            return definition;
        }

        definition.properties = fp.map(function(name, field) {
            var def;

            def = resolveRef(definitions, field);

            if(def) {
                return extend(def, field);
            }

            def = resolveArrayRef(definitions, field);

            if(def) {
                field.items = def;
            }

            return field;
        }, definition.properties);

        return definition;
    }, definitions);
}

function resolvePathRefs(definitions, paths) {
    return fp.map(function(name, path) {
        return fp.map(function(operation, meta) {
            meta.parameters = resolveParameterRefs(definitions, meta.parameters);
            meta.responses = resolveResponseRefs(definitions, meta.responses);

            return meta;
        }, path);
    }, paths);
}

function resolveParameterRefs(definitions, parameters) {
    if(!parameters) {
        return;
    }

    return fp.map(function(meta) {
        var def;

        def = resolveRef(definitions, meta.schema);

        if(def) {
            meta.schema = def;
        }
        else {
            // map through parameters
            meta.schema = fp.map(function(name, item) {
                var def = resolveArrayRef(definitions, item);

                if(def) {
                    item.items = def;
                }

                return item;
            }, meta.schema);
        }

        return meta;
    }, parameters);
}

function resolveResponseRefs(definitions, responses) {
    return fp.map(function(code, meta) {
        var def;

        def = resolveRef(definitions, meta.schema);

        if(def) {
            meta.schema = def;
        }

        def = resolveArrayRef(definitions, meta.schema);

        if(def) {
            meta.schema.items = def;
        }

        return meta;
    }, responses);
}

function resolveRef(definitions, field) {
    var ref = field.$ref;

    return definitions[getRefName(ref)];
}

function resolveArrayRef(definitions, field) {
    var ref = field.items && field.items.$ref;

    return definitions[getRefName(ref)];
}

function getRefName(ref) {
    if(ref) {
        return ref.split('/').slice(-1)[0];
    }
}
<commit_msg>Delete $refs from created definitions<commit_after>'use strict';
var fp = require('annofp');
var extend = require('xtend');

module.exports = function(schema) {
    var definitions = schema.definitions;
    var paths = schema.paths;

    if(!definitions) {
        return console.trace('missing definitions to resolve');
    }

    var ret = fp.deepcopy(schema);

    ret.definitions = resolveDefinitionRefs(definitions);
    ret.paths = resolvePathRefs(definitions, paths);

    return ret;
};

function resolveDefinitionRefs(definitions) {
    return fp.map(function(name, definition) {
        if(!definition.properties) {
            return definition;
        }

        definition.properties = fp.map(function(name, field) {
            var def;

            def = resolveRef(definitions, field);

            if(def) {
                delete field.$ref;

                return extend(def, field);
            }

            def = resolveArrayRef(definitions, field);

            if(def) {
                field.items = def;
            }

            return field;
        }, definition.properties);

        return definition;
    }, definitions);
}

function resolvePathRefs(definitions, paths) {
    return fp.map(function(name, path) {
        return fp.map(function(operation, meta) {
            meta.parameters = resolveParameterRefs(definitions, meta.parameters);
            meta.responses = resolveResponseRefs(definitions, meta.responses);

            return meta;
        }, path);
    }, paths);
}

function resolveParameterRefs(definitions, parameters) {
    if(!parameters) {
        return;
    }

    return fp.map(function(meta) {
        var def;

        def = resolveRef(definitions, meta.schema);

        if(def) {
            meta.schema = def;
        }
        else {
            // map through parameters
            meta.schema = fp.map(function(name, item) {
                var def = resolveArrayRef(definitions, item);

                if(def) {
                    item.items = def;
                }

                return item;
            }, meta.schema);
        }

        return meta;
    }, parameters);
}

function resolveResponseRefs(definitions, responses) {
    return fp.map(function(code, meta) {
        var def;

        def = resolveRef(definitions, meta.schema);

        if(def) {
            meta.schema = def;
        }

        def = resolveArrayRef(definitions, meta.schema);

        if(def) {
            meta.schema.items = def;
        }

        return meta;
    }, responses);
}

function resolveRef(definitions, field) {
    var ref = field.$ref;

    return definitions[getRefName(ref)];
}

function resolveArrayRef(definitions, field) {
    var ref = field.items && field.items.$ref;

    return definitions[getRefName(ref)];
}

function getRefName(ref) {
    if(ref) {
        return ref.split('/').slice(-1)[0];
    }
}
<|endoftext|>


<commit_before>var blogServer = require("./blogServer");

blogServer.run();
<commit_msg>cleaning up files<commit_after>var blogServer = require("./blogserver.js");

blogServer.run();
<|endoftext|>


<commit_before>/*!
 * multer
 * Copyright(c) 2014 Hage Yaapa
 * Copyright(c) 2015 Fangdun Cai
 * MIT Licensed
 */

/**
 * Module dependencies.
 */

var thenify = require('thenify');
var originalMulter = require('multer');

/**
 * @param {Object} options
 * @return {GeneratorFunction}
 * @api public
 */

module.exports = function multerWrapper(options) {
  var middleware = thenify(originalMulter(options));

  return multer;

  function* multer(next) {
    yield middleware(this.req, this.res);
    yield next;
  }
}
<commit_msg>Just added a ref to this.request.body<commit_after>/*!
 * multer
 * Copyright(c) 2014 Hage Yaapa
 * Copyright(c) 2015 Fangdun Cai
 * MIT Licensed
 */

/**
 * Module dependencies.
 */

var thenify = require('thenify');
var originalMulter = require('multer');

/**
 * @param {Object} options
 * @return {GeneratorFunction}
 * @api public
 */

module.exports = function multerWrapper(options) {
  var middleware = thenify(originalMulter(options));

  return multer;

  function* multer(next) {
    yield middleware(this.req, this.res);
    this.request.body = this.req.body;
    yield next;
  }
}
<|endoftext|>