<commit_before>var linz = require('../../'),
    formist = require('formist'),
	async = require('async'),
    theme = require('./theme'),
    utils = require('../utils'),
    formtoolUtils = require('./utils'),
    clone = require('clone'),
    moment = require('moment');

var addToFormOrFieldset = function (form, fieldsets, fieldsetKey, element) {

    var container = form;

    if (fieldsetKey !== undefined) {

        // create the fieldset if it currently doesn't exist
        if (fieldsets[fieldsetKey] === undefined) {
            fieldsets[fieldsetKey] = form.add(new formist.Fieldset({
                legend: fieldsetKey
            }));
        }

        container = fieldsets[fieldsetKey];

    }

    container.add(element);

};

var generateFormFromModel = exports.generateFormFromModel = function (m, schemaFields, r, formType, cb) {

	var formFields = {},
        form = new formist.Form({
            renderTag: false,
            theme: theme,
            attributes: {
                'class': 'form-horizontal'
            }
        }),
        fieldsets = {};

    // defaults to 'create'
    formType = formType || 'create';

    // remove fields that are set to be omitted from the form
    Object.keys(schemaFields).forEach(function (fieldName) {

        var field = clone(schemaFields[fieldName]); // we're going to make changes to this object, clone don't reference the original value

        // merge form.edit or form.create onto form
        utils.merge(field, field[formType] || {});
        delete field.edit;
        delete field.create;

        if (field.visible === false || fieldName === m.options.versionKey) {
            return;
        }

        formFields[fieldName] = field;

    });

    async.eachSeries(Object.keys(formFields), function (fieldName, fn) {

        var field = formFields[fieldName];
        var fieldOptions = field.options;
        var formField;
        var choices = {};
        var defaultValue = null;
        var embeddedDocumentForm = null;

        async.series([

            // handle list types
            function (callback) {

                // determine if the field has enumValues
                if (Array.isArray(field.list) && field.list.length) {

                    // add the options to the choices object to be passed to the select box
                    if (field.type !== 'array') field.type = 'enum';

                    // list can contain an aray of strings or objects
                    field.list.forEach(function (val) {
                        if(typeof val === 'object') choices[val.value] = val.name;
                        else choices[val] = val;
                    });

                    return callback(null);

                } else if (typeof field.list === 'function') {

                    if (field.type !== 'array') {
                        field.type = 'enum';
                    }

                    field.list(function (err, listValues) {

                        if (err) {
                            console.log('Encountered error from list value function for the field ' + fieldName);
                            console.log(err);
                        }

                        field.list = (!err && listValues.length) ? listValues : [];

                        return callback(null);

                    });

                } else {

                    return callback(null);

                }

            },

            // handle defaultValues
            function (callback) {

                defaultValue = formtoolUtils.getDefaultValue(m.paths[fieldName]);

                return callback(null);

            },

            // handle ref fields
            function (callback) {

                // if the field has a reference, we need to grab the values for that type and add them in
                // if not, skip this function
                if (field.list || !m.tree[fieldName].ref) {
                    return callback(null);
                }

                // build the query
                var refQuery = linz.mongoose.models[m.tree[fieldName].ref].find(field.query.filter || {});

                if (field.query.sort) {
                    refQuery.sort(field.query.sort);
                }

                if (field.query.select) {
                    refQuery.select(field.query.select);
                }

                refQuery.exec(function (err, docs) {

                    field.type = 'enum';
                    choices = [];

                    async.each(docs, function (doc, cb) {

                        var choice = {
                            value: doc._id.toString(),
                            label: doc.title || doc.label || doc.name || doc.toString()
                        }

                        if (!field.query.label || typeof field.query.label !== 'function') {

                            choices.push(choice);
                            return cb(null);

                        }

                        field.query.label.call(doc, function (err, val) {

                            if (!err && val) {
                                choice.label = val;
                            }

                            choices.push(choice);
                            return cb(null);

                        });

                    }, function () {

                        field.list = choices;
                        callback(null);

                    });

                });

            },

            // handle embedded documents
            function (callback) {

                if (field.type !== 'documentarray') {
                    return callback(null);
                }

                if (!field.linz.formtools.form) {
                    return callback(new Error('Unable to locate the form settings for the field \'' + fieldName + '\' which contains an embedded document schema. Please make sure you have added linz.formtools.plugins.embeddedDocument against the schema for the embedded document.'));
                }

                // render the form to pass into the template
                generateFormFromModel(field.schema, field.linz.formtools.form, {}, formType, function (getEmbeddedFormErr, emdeddedForm) {

                    if (getEmbeddedFormErr) {
                        return callback(getEmbeddedFormErr);
                    }

                    embeddedDocumentForm = emdeddedForm;

                    return callback(null);

                });

            },

            // create form elements where neccessary
            function (callback) {

                var fieldValue;

                // if we have a transpose function, let's use it
                // otherwise, fall back to default processing
                if (field.transpose) {

                    fieldValue = field.transpose(r[fieldName], r);

                } else {

                    switch (field.type) {

                        case 'date':
                        fieldValue = ((r[fieldName] !== undefined && r[fieldName] !== null) ? moment(r[fieldName]).format('YYYY-MM-DD') : null) || defaultValue;
                        break;

                        case 'datetime':
                        fieldValue = ((r[fieldName] !== undefined && r[fieldName] !== null) ? r[fieldName].toISOString().slice(0,23) : defaultValue) || defaultValue;
                        break;

                        case 'boolean':
                        fieldValue = (r[fieldName] !== undefined) ? utils.asBoolean(r[fieldName]) : defaultValue;
                        break;

                        case 'array':
                        fieldValue = (r[fieldName] !== undefined) ? r[fieldName] : defaultValue;
                        break;

                        case 'documentarray':
                        fieldValue = r[fieldName];
                        break;

                        default:
                        fieldValue = (r[fieldName] !== undefined && r[fieldName] !== null ? r[fieldName].toString() : null) || (defaultValue !== null ? defaultValue.toString() : defaultValue);
                        break;

                    }

                }

                var widget = (field.widget && typeof field.widget === 'function')
                        ? field.widget
                        : undefined;

                (function (cb) {

                    var wFn,
                        w;

                    // determine the widget function to execute
                    switch (field.type) {

                        case 'email':
                            wFn = (widget || linz.formtools.widgets.email());
                            break;

                        case 'boolean':
                            wFn = (widget || linz.formtools.widgets.boolean());
                            break;

                        case 'enum':
                            wFn = (widget || linz.formtools.widgets.select());
                            break;

                         case 'array':
                            wFn = (widget || linz.formtools.widgets.checkboxes());
                            break;

                        case 'password':
                            wFn = (widget || linz.formtools.widgets.password());
                            break;

                        case 'text':
                            wFn = (widget || linz.formtools.widgets.textarea());
                            break;

                        case 'date':
                            wFn = (widget || linz.formtools.widgets.date());
                            break;

                        case 'datetime':
                            wFn = (widget || linz.formtools.widgets.datetime());
                            break;

                        case 'datetimeLocal':
                            wFn = (widget || linz.formtools.widgets.datetimeLocal());
                            break;

                        case 'url':
                            wFn = (widget || linz.formtools.widgets.url());
                            break;

                        case 'hidden':
                            wFn = (widget || linz.formtools.widgets.hidden());
                            break;

                        case 'number':
                            wFn = (widget || linz.formtools.widgets.number());
                            break;

                        case 'digit':
                            wFn = (widget || linz.formtools.widgets.digit());
                            break;

                        case 'tel':
                            wFn = (widget || linz.formtools.widgets.tel());
                            break;

                        case 'documentarray':
                            wFn = (widget || linz.formtools.widgets.documents());
                            break;

                        default:
                            wFn = (widget || linz.formtools.widgets.text());
                            break;

                    }

                    // execute the widget function and get the result
                    switch (field.type) {

                        case 'documentarray':
                            w = wFn(fieldName, field, fieldValue, r, formType, embeddedDocumentForm);
                            break;

                        default:
                            w = wFn(fieldName, field, fieldValue, r, formType);
                            break;

                    }

                    // add the field to the form
                    addToFormOrFieldset(form, fieldsets, field.fieldset, w);

                    // we're done here
                    return callback(null);

                })(callback);

            }

        ], function (err, results) {

            fn(err);

        });

    }, function (err) {

        cb(err, form);

    });

};
<commit_msg>Remove extra space<commit_after>var linz = require('../../'),
    formist = require('formist'),
	async = require('async'),
    theme = require('./theme'),
    utils = require('../utils'),
    formtoolUtils = require('./utils'),
    clone = require('clone'),
    moment = require('moment');

var addToFormOrFieldset = function (form, fieldsets, fieldsetKey, element) {

    var container = form;

    if (fieldsetKey !== undefined) {

        // create the fieldset if it currently doesn't exist
        if (fieldsets[fieldsetKey] === undefined) {
            fieldsets[fieldsetKey] = form.add(new formist.Fieldset({
                legend: fieldsetKey
            }));
        }

        container = fieldsets[fieldsetKey];

    }

    container.add(element);

};

var generateFormFromModel = exports.generateFormFromModel = function (m, schemaFields, r, formType, cb) {

	var formFields = {},
        form = new formist.Form({
            renderTag: false,
            theme: theme,
            attributes: {
                'class': 'form-horizontal'
            }
        }),
        fieldsets = {};

    // defaults to 'create'
    formType = formType || 'create';

    // remove fields that are set to be omitted from the form
    Object.keys(schemaFields).forEach(function (fieldName) {

        var field = clone(schemaFields[fieldName]); // we're going to make changes to this object, clone don't reference the original value

        // merge form.edit or form.create onto form
        utils.merge(field, field[formType] || {});
        delete field.edit;
        delete field.create;

        if (field.visible === false || fieldName === m.options.versionKey) {
            return;
        }

        formFields[fieldName] = field;

    });

    async.eachSeries(Object.keys(formFields), function (fieldName, fn) {

        var field = formFields[fieldName];
        var fieldOptions = field.options;
        var formField;
        var choices = {};
        var defaultValue = null;
        var embeddedDocumentForm = null;

        async.series([

            // handle list types
            function (callback) {

                // determine if the field has enumValues
                if (Array.isArray(field.list) && field.list.length) {

                    // add the options to the choices object to be passed to the select box
                    if (field.type !== 'array') field.type = 'enum';

                    // list can contain an aray of strings or objects
                    field.list.forEach(function (val) {
                        if(typeof val === 'object') choices[val.value] = val.name;
                        else choices[val] = val;
                    });

                    return callback(null);

                } else if (typeof field.list === 'function') {

                    if (field.type !== 'array') {
                        field.type = 'enum';
                    }

                    field.list(function (err, listValues) {

                        if (err) {
                            console.log('Encountered error from list value function for the field ' + fieldName);
                            console.log(err);
                        }

                        field.list = (!err && listValues.length) ? listValues : [];

                        return callback(null);

                    });

                } else {

                    return callback(null);

                }

            },

            // handle defaultValues
            function (callback) {

                defaultValue = formtoolUtils.getDefaultValue(m.paths[fieldName]);

                return callback(null);

            },

            // handle ref fields
            function (callback) {

                // if the field has a reference, we need to grab the values for that type and add them in
                // if not, skip this function
                if (field.list || !m.tree[fieldName].ref) {
                    return callback(null);
                }

                // build the query
                var refQuery = linz.mongoose.models[m.tree[fieldName].ref].find(field.query.filter || {});

                if (field.query.sort) {
                    refQuery.sort(field.query.sort);
                }

                if (field.query.select) {
                    refQuery.select(field.query.select);
                }

                refQuery.exec(function (err, docs) {

                    field.type = 'enum';
                    choices = [];

                    async.each(docs, function (doc, cb) {

                        var choice = {
                            value: doc._id.toString(),
                            label: doc.title || doc.label || doc.name || doc.toString()
                        }

                        if (!field.query.label || typeof field.query.label !== 'function') {

                            choices.push(choice);
                            return cb(null);

                        }

                        field.query.label.call(doc, function (err, val) {

                            if (!err && val) {
                                choice.label = val;
                            }

                            choices.push(choice);
                            return cb(null);

                        });

                    }, function () {

                        field.list = choices;
                        callback(null);

                    });

                });

            },

            // handle embedded documents
            function (callback) {

                if (field.type !== 'documentarray') {
                    return callback(null);
                }

                if (!field.linz.formtools.form) {
                    return callback(new Error('Unable to locate the form settings for the field \'' + fieldName + '\' which contains an embedded document schema. Please make sure you have added linz.formtools.plugins.embeddedDocument against the schema for the embedded document.'));
                }

                // render the form to pass into the template
                generateFormFromModel(field.schema, field.linz.formtools.form, {}, formType, function (getEmbeddedFormErr, emdeddedForm) {

                    if (getEmbeddedFormErr) {
                        return callback(getEmbeddedFormErr);
                    }

                    embeddedDocumentForm = emdeddedForm;

                    return callback(null);

                });

            },

            // create form elements where neccessary
            function (callback) {

                var fieldValue;

                // if we have a transpose function, let's use it
                // otherwise, fall back to default processing
                if (field.transpose) {

                    fieldValue = field.transpose(r[fieldName], r);

                } else {

                    switch (field.type) {

                        case 'date':
                        fieldValue = ((r[fieldName] !== undefined && r[fieldName] !== null) ? moment(r[fieldName]).format('YYYY-MM-DD') : null) || defaultValue;
                        break;

                        case 'datetime':
                        fieldValue = ((r[fieldName] !== undefined && r[fieldName] !== null) ? r[fieldName].toISOString().slice(0,23) : defaultValue) || defaultValue;
                        break;

                        case 'boolean':
                        fieldValue = (r[fieldName] !== undefined) ? utils.asBoolean(r[fieldName]) : defaultValue;
                        break;

                        case 'array':
                        fieldValue = (r[fieldName] !== undefined) ? r[fieldName] : defaultValue;
                        break;

                        case 'documentarray':
                        fieldValue = r[fieldName];
                        break;

                        default:
                        fieldValue = (r[fieldName] !== undefined && r[fieldName] !== null ? r[fieldName].toString() : null) || (defaultValue !== null ? defaultValue.toString() : defaultValue);
                        break;

                    }

                }

                var widget = (field.widget && typeof field.widget === 'function')
                        ? field.widget
                        : undefined;

                (function (cb) {

                    var wFn,
                        w;

                    // determine the widget function to execute
                    switch (field.type) {

                        case 'email':
                            wFn = (widget || linz.formtools.widgets.email());
                            break;

                        case 'boolean':
                            wFn = (widget || linz.formtools.widgets.boolean());
                            break;

                        case 'enum':
                            wFn = (widget || linz.formtools.widgets.select());
                            break;

                         case 'array':
                            wFn = (widget || linz.formtools.widgets.checkboxes());
                            break;

                        case 'password':
                            wFn = (widget || linz.formtools.widgets.password());
                            break;

                        case 'text':
                            wFn = (widget || linz.formtools.widgets.textarea());
                            break;

                        case 'date':
                            wFn = (widget || linz.formtools.widgets.date());
                            break;

                        case 'datetime':
                            wFn = (widget || linz.formtools.widgets.datetime());
                            break;

                        case 'datetimeLocal':
                            wFn = (widget || linz.formtools.widgets.datetimeLocal());
                            break;

                        case 'url':
                            wFn = (widget || linz.formtools.widgets.url());
                            break;

                        case 'hidden':
                            wFn = (widget || linz.formtools.widgets.hidden());
                            break;

                        case 'number':
                            wFn = (widget || linz.formtools.widgets.number());
                            break;

                        case 'digit':
                            wFn = (widget || linz.formtools.widgets.digit());
                            break;

                        case 'tel':
                            wFn = (widget || linz.formtools.widgets.tel());
                            break;

                        case 'documentarray':
                            wFn = (widget || linz.formtools.widgets.documents());
                            break;

                        default:
                            wFn = (widget || linz.formtools.widgets.text());
                            break;

                    }

                    // execute the widget function and get the result
                    switch (field.type) {

                        case 'documentarray':
                            w = wFn(fieldName, field, fieldValue, r, formType, embeddedDocumentForm);
                            break;

                        default:
                            w = wFn(fieldName, field, fieldValue, r, formType);
                            break;

                    }

                    // add the field to the form
                    addToFormOrFieldset(form, fieldsets, field.fieldset, w);

                    // we're done here
                    return callback(null);

                })(callback);

            }

        ], function (err, results) {

            fn(err);

        });

    }, function (err) {

        cb(err, form);

    });

};
<|endoftext|>


<commit_before>'use strict';

const fs = require('fs');
const path = require('path');
const process = require('process');

const chalk = require('chalk');
const needle = require('needle');
const _ = require('lodash');

const utils = require('../utils');

const Parser = require('./parser');
const Filterer = require('./filterer');
const Transformer = require('./transformer');

const currentDir = process.cwd();

function handleSwagger(swagger, profile, profileKey) {
    // Ensure swagger is an object and not the swagger JSON string
    swagger = utils.resolveSwaggerObject(swagger);

    // Parse the swagger and create a in-memory definition
    const parser = new Parser(swagger);
    const definition = parser.parse();

    // Run any filter logic on the definition and remove unwanted services and models
    const filterer = new Filterer(profile);
    filterer.filterDefinition(definition);

    // Run any transforms on the definition
    const transformer = new Transformer(profile);
    transformer.transformDefinition(definition);

    // Write the definition to a file if configured so
    if (profile.debug.definition) {
        const definitionJson = JSON.stringify(definition, null, 4);
        fs.writeFileSync(path.resolve(currentDir, profile.debug.definition), definitionJson, 'utf8');
        console.log(chalk`{green [${profileKey}]} Definition file written to '{cyan ${profile.debug.definition}}'.`);
    }

    // Load the generator package
    let generatorPkg;
    if (_.startsWith(profile.generator, '.')) {
        generatorPkg = require(path.resolve(currentDir, profile.generator));
    } else {
        generatorPkg = require(`swagen-${profile.generator}`);
    }

    const modes = generatorPkg instanceof Array ? generatorPkg : [generatorPkg];
    const mode = modes.find(m => m.name === profile.mode);

    // If the generator package exports a validateProfile function, call it to validate the profile.
    // If the profile fails validation, it should throw an exception.
    if (typeof mode.validateProfile === 'function') {
        mode.validateProfile(profile);
    }

    // Generate the code from the generator package
    const output = mode.generate(definition, profile);

    // Write the generated code to a file
    const outputFilePath = path.resolve(currentDir, profile.output);
    fs.writeFileSync(path.resolve(currentDir, outputFilePath), output, 'utf8');
    console.log(chalk`{green [${profileKey}]} Code generated at '{cyan ${outputFilePath}}'.`);
}

/**
 * Reads the swagger json from a file specified in the profile.
 * @param {Profile} profile - The profile being handled.
 * @param {String} profileKey - The name of the profile.
 */
function handleFileSwagger(profile, profileKey) {
    const inputFilePath = path.resolve(currentDir, profile.file);
    console.log(chalk`{green [${profileKey}]} Input swagger file : {cyan ${inputFilePath}}`);
    fs.readFile(inputFilePath, 'utf8', (error, swagger) => {
        if (error) {
            console.log(chalk`{red Cannot read swagger file '{bold ${profile.file}}'.}`);
            console.log(chalk.red(error));
        } else {
            handleSwagger(swagger, profile, profileKey);
        }
    });
}

/**
 * Reads the swagger json from a URL specified in the profile.
 * @param {Profile} profile The profile being handled.
 * @param {String} profileKey The name of the profile.
 */
function handleUrlSwagger(profile, profileKey) {
    console.log(chalk`{green [${profileKey}]} Input swagger URL : {cyan ${profile.url}}`);
    needle.get(profile.url, (err, resp, body) => {
        if (err) {
            console.log(chalk`{red Cannot read swagger URL '{bold ${profile.url}}'.}`);
            console.log(chalk.red(err));
        } else {
            handleSwagger(body, profile, profileKey);
        }
    });
}

/**
 * Ensure that the profile structure is valid.
 */
function verifyProfile(profile, profileKey) {
    if (!profile.file && !profile.url) {
        throw new Error(`[${profileKey}] Must specify a file or url in the configuration.`);
    }
    if (!profile.output) {
        throw new Error(`[${profileKey}] Must specify an output file path in the configuration.`);
    }
    if (!profile.generator) {
        throw new Error(`[${profileKey}] Must specify a generator in the configuration.`);
    }
    if (profile.generator.toLowerCase() === 'core') {
        throw new Error(`[${profileKey}] Invalid generator ${profile.generator}. This name is reserved.`);
    }
    if (profile.generator.match(/^[\w-]+-language$/i)) {
        throw new Error(`[${profileKey}] Invalid generator ${profile.generator}. The -language suffix is reserved for language helper packages.`);
    }
    profile.debug = profile.debug || {};
    profile.filters = profile.filters || {};
    profile.transforms = profile.transforms || {};
    profile.options = profile.options || {};
}

/**
 * Iterates through each profile in the config and handles the swagger.
 * @param {Object} config Configuration object
 */
function processInputs(config) {
    for (const profileKey in config) {
        const profile = config[profileKey];
        if (profile.skip) {
            continue;
        }

        verifyProfile(profile, profileKey);

        if (profile.file) {
            handleFileSwagger(profile, profileKey);
        } else {
            handleUrlSwagger(profile, profileKey);
        }
    }
}

module.exports = function() {
    const config = utils.loadConfig();
    processInputs(config);
};
<commit_msg>Temporarily allowing certificate errors.<commit_after>'use strict';

const fs = require('fs');
const path = require('path');
const process = require('process');

const chalk = require('chalk');
const needle = require('needle');
const _ = require('lodash');

const utils = require('../utils');

const Parser = require('./parser');
const Filterer = require('./filterer');
const Transformer = require('./transformer');

const currentDir = process.cwd();

function handleSwagger(swagger, profile, profileKey) {
    // Ensure swagger is an object and not the swagger JSON string
    swagger = utils.resolveSwaggerObject(swagger);

    // Parse the swagger and create a in-memory definition
    const parser = new Parser(swagger);
    const definition = parser.parse();

    // Run any filter logic on the definition and remove unwanted services and models
    const filterer = new Filterer(profile);
    filterer.filterDefinition(definition);

    // Run any transforms on the definition
    const transformer = new Transformer(profile);
    transformer.transformDefinition(definition);

    // Write the definition to a file if configured so
    if (profile.debug.definition) {
        const definitionJson = JSON.stringify(definition, null, 4);
        fs.writeFileSync(path.resolve(currentDir, profile.debug.definition), definitionJson, 'utf8');
        console.log(chalk`{green [${profileKey}]} Definition file written to '{cyan ${profile.debug.definition}}'.`);
    }

    // Load the generator package
    let generatorPkg;
    if (_.startsWith(profile.generator, '.')) {
        generatorPkg = require(path.resolve(currentDir, profile.generator));
    } else {
        generatorPkg = require(`swagen-${profile.generator}`);
    }

    const modes = generatorPkg instanceof Array ? generatorPkg : [generatorPkg];
    const mode = modes.find(m => m.name === profile.mode);

    // If the generator package exports a validateProfile function, call it to validate the profile.
    // If the profile fails validation, it should throw an exception.
    if (typeof mode.validateProfile === 'function') {
        mode.validateProfile(profile);
    }

    // Generate the code from the generator package
    const output = mode.generate(definition, profile);

    // Write the generated code to a file
    const outputFilePath = path.resolve(currentDir, profile.output);
    fs.writeFileSync(path.resolve(currentDir, outputFilePath), output, 'utf8');
    console.log(chalk`{green [${profileKey}]} Code generated at '{cyan ${outputFilePath}}'.`);
}

/**
 * Reads the swagger json from a file specified in the profile.
 * @param {Profile} profile - The profile being handled.
 * @param {String} profileKey - The name of the profile.
 */
function handleFileSwagger(profile, profileKey) {
    const inputFilePath = path.resolve(currentDir, profile.file);
    console.log(chalk`{green [${profileKey}]} Input swagger file : {cyan ${inputFilePath}}`);
    fs.readFile(inputFilePath, 'utf8', (error, swagger) => {
        if (error) {
            console.log(chalk`{red Cannot read swagger file '{bold ${profile.file}}'.}`);
            console.log(chalk.red(error));
        } else {
            handleSwagger(swagger, profile, profileKey);
        }
    });
}

/**
 * Reads the swagger json from a URL specified in the profile.
 * @param {Profile} profile The profile being handled.
 * @param {String} profileKey The name of the profile.
 */
function handleUrlSwagger(profile, profileKey) {
    console.log(chalk`{green [${profileKey}]} Input swagger URL : {cyan ${profile.url}}`);
    const options = {
        rejectUnauthorized: false
    };
    needle.get(profile.url, options, (err, resp, body) => {
        if (err) {
            console.log(chalk`{red Cannot read swagger URL '{bold ${profile.url}}'.}`);
            console.log(chalk.red(err));
        } else {
            handleSwagger(body, profile, profileKey);
        }
    });
}

/**
 * Ensure that the profile structure is valid.
 */
function verifyProfile(profile, profileKey) {
    if (!profile.file && !profile.url) {
        throw new Error(`[${profileKey}] Must specify a file or url in the configuration.`);
    }
    if (!profile.output) {
        throw new Error(`[${profileKey}] Must specify an output file path in the configuration.`);
    }
    if (!profile.generator) {
        throw new Error(`[${profileKey}] Must specify a generator in the configuration.`);
    }
    if (profile.generator.toLowerCase() === 'core') {
        throw new Error(`[${profileKey}] Invalid generator ${profile.generator}. This name is reserved.`);
    }
    if (profile.generator.match(/^[\w-]+-language$/i)) {
        throw new Error(`[${profileKey}] Invalid generator ${profile.generator}. The -language suffix is reserved for language helper packages.`);
    }
    profile.debug = profile.debug || {};
    profile.filters = profile.filters || {};
    profile.transforms = profile.transforms || {};
    profile.options = profile.options || {};
}

/**
 * Iterates through each profile in the config and handles the swagger.
 * @param {Object} config Configuration object
 */
function processInputs(config) {
    for (const profileKey in config) {
        const profile = config[profileKey];
        if (profile.skip) {
            continue;
        }

        verifyProfile(profile, profileKey);

        if (profile.file) {
            handleFileSwagger(profile, profileKey);
        } else {
            handleUrlSwagger(profile, profileKey);
        }
    }
}

module.exports = function() {
    const config = utils.loadConfig();
    processInputs(config);
};
<|endoftext|>


<commit_before>/* jshint unused:true, node:true */
"use strict";

var debug     = require('debug')('irc-gitter-adapter');
var irc       = require('./protocol');
var Gitter    = require('node-gitter');
var manifest  = require('../package.json');
var VERSION   = manifest.version;
var DATE      = Date();

function Adapter(client) {
  this.client = client;

  // Keep track of the active rooms
  this.rooms = {};

  this.hookEvents();
}

// Map IRC commands to adapter functions
Adapter.prototype.hookEvents = function() {
  var commands = {
    PASS:     this.setup,
    PRIVMSG:  this.sendMessage,
    QUIT:     this.quit,
    NICK:     this.nick,
    USER:     this.register,
    JOIN:     this.joinRooms,
    PART:     this.leaveRooms,
    WHO:      this.listUsers,
    LIST:     this.listRooms,
    MOTD:     this.messageOfTheDay
  };

  Object.keys(commands).map(function(cmd) {
    this.client.on(cmd, commands[cmd].bind(this));
  }.bind(this));
};

Adapter.prototype.listenForOneToOnes = function() {
  function subscribeIfoneToOne(room) {
    if (!room.oneToOne || this.rooms[room.name]) return;

    this.subscribeToRoom(room);
    var mask = ':' + room.name + '!' + room.name + '@gitter.im';
    this.client.send(mask, 'PRIVMSG', room.name, ':' + msg.text);
  }

  function handleNotification(msg) {
    if (msg.notification !== 'user_notification') return;

    this.gitterClient.rooms.find(msg.troupeId)
    .then(subscribeIfoneToOne.bind(this))
    .catch(function(err) {
      debug('Error handling user_notification', err);
    });
  }

  this.gitterClient.faye.client.subscribe('/api/v1/user/' + this.user.id, handleNotification.bind(this));
};

Adapter.prototype.setup = function(token) {
  var opts = {};
  // TODO move this to a config file
  if (process.env.DEV) opts = {client: {host: "localhost", port: 5000, prefix: true}, faye: {host: 'http://localhost:5000/faye'}};
  this.gitterClient = new Gitter(token, opts);
  this.gitterClient.currentUser()
  .then(function(user) {
    debug('Logged in as ' + user.username);
    this.user = user;
    this.client.authenticate(user);
    this.listenForOneToOnes();
  }.bind(this))
  .catch(function(err) {
    debug('Authentication failed', err);
  });
};

Adapter.prototype.subscribeToRoom = function(room) {
  var uri = (room.uri || room.name).toLowerCase();

  if (this.rooms[uri]) return;

  var c = this.client;

  room.subscribe();

  function channel() {
    return room.oneToOne ? room.name : '#' + room.uri;
  }

  room.on('chatMessages', function(evt) {
    if (evt.operation !== 'create') return;
    var message = evt.model;
    var nick = message.fromUser.username;
    if (nick !== c.nick) {
      var mask = ':' + nick + '!' + nick + '@gitter.im';
      c.send(mask, 'PRIVMSG', channel(), ':' + message.text);
      this.user.markAsRead(room.id, [message.id]);
    }
  }.bind(this));

  room.on('events', function(evt) {
    if (evt.operation !== 'create') return;
    var message = evt.model;
    var mask = ':gitter!gitter@gitter.im';
    c.send(mask, 'PRIVMSG', channel(), ':' + message.text);
    this.user.markAsRead(room.id, [message.id]);
  }.bind(this));

  room.on('users', function(evt) {});

  this.rooms[uri] = room;
};

Adapter.prototype.sendMessage = function(target, message) {
  var uri = target.replace('#','');
  this.gitterClient.rooms.join(uri)
  .then(function(room) {
    room.send(message);
  })
  .catch(function(err){
    debug('Invalid room/user:' + uri);
  });
};

Adapter.prototype.nick = function(nick) {
  var c = this.client;
  c.send(c.mask(), 'NICK', ':' + c.nick);
};

Adapter.prototype.register = function(username, hostname, servername, realname) {
  var c = this.client;
  c.send(c.host, irc.reply.welcome, c.nick, 'Gitter', c.mask());
  c.send(c.host, irc.reply.yourHost, c.nick, 'Version:', VERSION);
  c.send(c.host, irc.reply.created, c.nick, 'Created on', DATE);
  c.send(c.host, irc.reply.myInfo, c.hostname, VERSION, 'wo', 'ntr');
  this.messageOfTheDay();
};

Adapter.prototype.joinRooms = function(channels, key) {
  channels.split(',').map(this.joinRoom.bind(this));
};

Adapter.prototype.joinRoom = function(channel) {
  var self  = this;
  var c     = this.client;
  var uri   = channel.replace('#','');

  this.gitterClient.rooms.join(uri)
  .then(function(room) {
    if (room.oneToOne) throw('Room is one-to-one');
    return [room, room.users()];
  })
  .spread(function(room, users) {
    var chanType = '*'; // * private, @ secret, = public
    var usernames = users.map(function(u) { return u.username; });
    usernames.push('gitter'); // Fake gitter user for Events
    c.send(c.mask(), 'JOIN', channel);
    c.send(c.host, irc.reply.topic, c.nick, channel, ':' + room.topic);
    c.send(c.host, irc.reply.nameReply, c.nick, chanType, channel, ':' + usernames.join(' '));
    c.send(c.host, irc.reply.endNames, c.nick, channel, ': /NAMES');
    return room;
  })
  .then(function(room) {
    self.subscribeToRoom(room);
  })
  .catch(function() {
    c.send(c.host, irc.errors.noSuchChannel, ': Invalid channel or insufficient permissions');
  });
};

Adapter.prototype.leaveRooms = function(channels, key) {
  channels.split(',').map(this.leaveRoom.bind(this));
};

Adapter.prototype.leaveRoom = function(channel) {
  var uri = channel.replace('#','').toLowerCase();

  if (!this.rooms[uri]) return;

  var room = this.rooms[uri];
  room.unsubscribe();
  room.removeAllListeners();
  delete this.rooms[uri];

  this.client.send(this.client.mask(), 'PART', channel);
};

Adapter.prototype.listUsers = function(channel, key) {
  var c = this.client;
  var uri = channel.replace('#','');

  this.gitterClient.rooms.join(uri)
  .then(function(room) {
    return room.users();
  })
  .then(function(users) {
    users.forEach(function(user) {
      c.send(c.host, irc.reply.who, c.nick, channel, user.username, c.hostname, c.hostname, user.username, 'H', ':0', user.displayName);
    });
    c.send(c.host, irc.reply.who, c.nick, channel, 'gitter', c.host, c.hostname, 'gitter', 'H', ':0', 'Gitter Bot');
    c.send(c.host, irc.reply.endWho, c.nick, channel, ':End of /WHO list.');
  })
  .catch(function() {
    c.send(c.host, irc.errors.noSuchChannel, c.nick, ':No such channel');
  });
};

Adapter.prototype.quit = function() {
  Object.keys(this.rooms).forEach(function(channel) {
    this.rooms[channel].unsubscribe();
  }.bind(this));
  this.client.disconnect();
};

Adapter.prototype.listRooms = function() {
  var c = this.client;

  this.gitterClient.currentUser()
  .then(function(user) {
    return user.rooms();
  })
  .then(function(rooms) {
    c.send(c.host, irc.reply.listStart, c.nick, 'Channel', ':Users Name');

    rooms.forEach(function(room) {
      if (room.oneToOne) return; // Do not show 1-to-1 chats
      c.send(c.host, irc.reply.list, c.nick, '#' + room.uri, room.userCount, ': ' + room.topic);
    });

    c.send(c.host, irc.reply.listEnd, c.nick, ':End of /LIST');
  })
};

Adapter.prototype.messageOfTheDay = function() {
  var c = this.client;

  c.send(c.host, irc.reply.motdStart, c.nick, ':- Message of the Day -');
  c.send(c.host, irc.reply.motd,      c.nick, 'Welcome To Gitter IRC!');
  c.send(c.host, irc.reply.motd,      c.nick, 'Info at https://irc.gitter.im');
  c.send(c.host, irc.reply.motd,      c.nick, 'Code at https://github.com/gitterHQ/irc-bridge');
  c.send(c.host, irc.reply.motdEnd,   c.nick, ':End of /MOTD command.');
};

module.exports = Adapter;
<commit_msg>Support for message edits<commit_after>/* jshint unused:true, node:true */
"use strict";

var debug     = require('debug')('irc-gitter-adapter');
var irc       = require('./protocol');
var Gitter    = require('node-gitter');
var manifest  = require('../package.json');
var VERSION   = manifest.version;
var DATE      = Date();

function Adapter(client) {
  this.client = client;

  // Keep track of the active rooms
  this.rooms = {};

  this.hookEvents();
}

// Map IRC commands to adapter functions
Adapter.prototype.hookEvents = function() {
  var commands = {
    PASS:     this.setup,
    PRIVMSG:  this.sendMessage,
    QUIT:     this.quit,
    NICK:     this.nick,
    USER:     this.register,
    JOIN:     this.joinRooms,
    PART:     this.leaveRooms,
    WHO:      this.listUsers,
    LIST:     this.listRooms,
    MOTD:     this.messageOfTheDay
  };

  Object.keys(commands).map(function(cmd) {
    this.client.on(cmd, commands[cmd].bind(this));
  }.bind(this));
};

Adapter.prototype.listenForOneToOnes = function() {
  function subscribeIfoneToOne(room) {
    if (!room.oneToOne || this.rooms[room.name]) return;

    this.subscribeToRoom(room);
    var mask = ':' + room.name + '!' + room.name + '@gitter.im';
    this.client.send(mask, 'PRIVMSG', room.name, ':' + msg.text);
  }

  function handleNotification(msg) {
    if (msg.notification !== 'user_notification') return;

    this.gitterClient.rooms.find(msg.troupeId)
    .then(subscribeIfoneToOne.bind(this))
    .catch(function(err) {
      debug('Error handling user_notification', err);
    });
  }

  this.gitterClient.faye.client.subscribe('/api/v1/user/' + this.user.id, handleNotification.bind(this));
};

Adapter.prototype.setup = function(token) {
  var opts = {};
  // TODO move this to a config file
  if (process.env.DEV) opts = {client: {host: "localhost", port: 5000, prefix: true}, faye: {host: 'http://localhost:5000/faye'}};
  this.gitterClient = new Gitter(token, opts);
  this.gitterClient.currentUser()
  .then(function(user) {
    debug('Logged in as ' + user.username);
    this.user = user;
    this.client.authenticate(user);
    this.listenForOneToOnes();
  }.bind(this))
  .catch(function(err) {
    debug('Authentication failed', err);
  });
};

Adapter.prototype.subscribeToRoom = function(room) {
  var uri = (room.uri || room.name).toLowerCase();

  if (this.rooms[uri]) return;

  var c = this.client;
  this.rooms[uri] = room;
  room.subscribe();

  function channel() {
    return room.oneToOne ? room.name : '#' + room.uri;
  }

  room.on('chatMessages', function(evt) {
    if (['create','update'].indexOf(evt.operation) === -1) return;

    var message = evt.model;
    var nick = message.fromUser.username;
    if (nick === c.nick) return; // User's own message

    var mask = ':' + nick + '!' + nick + '@gitter.im';
    var text = evt.operation === 'update' ? '[edit] ' + message.text : message.text;

    c.send(mask, 'PRIVMSG', channel(), ':' + text);

    this.user.markAsRead(room.id, [message.id]);
  }.bind(this));

  room.on('events', function(evt) {
    if (evt.operation !== 'create') return;
    var message = evt.model;
    var mask = ':gitter!gitter@gitter.im';

    c.send(mask, 'PRIVMSG', channel(), ':' + message.text);
  }.bind(this));

  room.on('users', function(evt) {});

};

Adapter.prototype.sendMessage = function(target, message) {
  var uri = target.replace('#','');
  this.gitterClient.rooms.join(uri)
  .then(function(room) {
    room.send(message);
  })
  .catch(function(err){
    debug('Invalid room/user:' + uri);
  });
};

Adapter.prototype.nick = function(nick) {
  var c = this.client;
  c.send(c.mask(), 'NICK', ':' + c.nick);
};

Adapter.prototype.register = function(username, hostname, servername, realname) {
  var c = this.client;
  c.send(c.host, irc.reply.welcome, c.nick, 'Gitter', c.mask());
  c.send(c.host, irc.reply.yourHost, c.nick, 'Version:', VERSION);
  c.send(c.host, irc.reply.created, c.nick, 'Created on', DATE);
  c.send(c.host, irc.reply.myInfo, c.hostname, VERSION, 'wo', 'ntr');
  this.messageOfTheDay();
};

Adapter.prototype.joinRooms = function(channels, key) {
  channels.split(',').map(this.joinRoom.bind(this));
};

Adapter.prototype.joinRoom = function(channel) {
  var self  = this;
  var c     = this.client;
  var uri   = channel.replace('#','');

  this.gitterClient.rooms.join(uri)
  .then(function(room) {
    if (room.oneToOne) throw('Room is one-to-one');
    return [room, room.users()];
  })
  .spread(function(room, users) {
    var chanType = '*'; // * private, @ secret, = public
    var usernames = users.map(function(u) { return u.username; });
    usernames.push('gitter'); // Fake gitter user for Events
    c.send(c.mask(), 'JOIN', channel);
    c.send(c.host, irc.reply.topic, c.nick, channel, ':' + room.topic);
    c.send(c.host, irc.reply.nameReply, c.nick, chanType, channel, ':' + usernames.join(' '));
    c.send(c.host, irc.reply.endNames, c.nick, channel, ': /NAMES');
    return room;
  })
  .then(function(room) {
    self.subscribeToRoom(room);
  })
  .catch(function() {
    c.send(c.host, irc.errors.noSuchChannel, ': Invalid channel or insufficient permissions');
  });
};

Adapter.prototype.leaveRooms = function(channels, key) {
  channels.split(',').map(this.leaveRoom.bind(this));
};

Adapter.prototype.leaveRoom = function(channel) {
  var uri = channel.replace('#','').toLowerCase();

  if (!this.rooms[uri]) return;

  var room = this.rooms[uri];
  room.unsubscribe();
  room.removeAllListeners();
  delete this.rooms[uri];

  this.client.send(this.client.mask(), 'PART', channel);
};

Adapter.prototype.listUsers = function(channel, key) {
  var c = this.client;
  var uri = channel.replace('#','');

  this.gitterClient.rooms.join(uri)
  .then(function(room) {
    return room.users();
  })
  .then(function(users) {
    users.forEach(function(user) {
      c.send(c.host, irc.reply.who, c.nick, channel, user.username, c.hostname, c.hostname, user.username, 'H', ':0', user.displayName);
    });
    c.send(c.host, irc.reply.who, c.nick, channel, 'gitter', c.host, c.hostname, 'gitter', 'H', ':0', 'Gitter Bot');
    c.send(c.host, irc.reply.endWho, c.nick, channel, ':End of /WHO list.');
  })
  .catch(function() {
    c.send(c.host, irc.errors.noSuchChannel, c.nick, ':No such channel');
  });
};

Adapter.prototype.quit = function() {
  Object.keys(this.rooms).forEach(function(channel) {
    this.rooms[channel].unsubscribe();
  }.bind(this));
  this.client.disconnect();
};

Adapter.prototype.listRooms = function() {
  var c = this.client;

  this.gitterClient.currentUser()
  .then(function(user) {
    return user.rooms();
  })
  .then(function(rooms) {
    c.send(c.host, irc.reply.listStart, c.nick, 'Channel', ':Users Name');

    rooms.forEach(function(room) {
      if (room.oneToOne) return; // Do not show 1-to-1 chats
      c.send(c.host, irc.reply.list, c.nick, '#' + room.uri, room.userCount, ': ' + room.topic);
    });

    c.send(c.host, irc.reply.listEnd, c.nick, ':End of /LIST');
  })
};

Adapter.prototype.messageOfTheDay = function() {
  var c = this.client;

  c.send(c.host, irc.reply.motdStart, c.nick, ':- Message of the Day -');
  c.send(c.host, irc.reply.motd,      c.nick, 'Welcome To Gitter IRC!');
  c.send(c.host, irc.reply.motd,      c.nick, 'Info at https://irc.gitter.im');
  c.send(c.host, irc.reply.motd,      c.nick, 'Code at https://github.com/gitterHQ/irc-bridge');
  c.send(c.host, irc.reply.motdEnd,   c.nick, ':End of /MOTD command.');
};

module.exports = Adapter;
<|endoftext|>


<commit_before>'use babel'

import {CompositeDisposable} from 'atom'
import path from 'path'
import _ from 'lodash'

class GocodeProvider {
  constructor (goconfigFunc, gogetFunc) {
    this.goconfig = goconfigFunc
    this.goget = gogetFunc
    this.subscriptions = new CompositeDisposable()
    this.subscribers = []

    this.selector = '.source.go'
    this.inclusionPriority = 1
    this.excludeLowerPriority = atom.config.get('autocomplete-go.suppressBuiltinAutocompleteProvider')
    this.suppressForCharacters = []
    this.disableForSelector = atom.config.get('autocomplete-go.scopeBlacklist')
    let suppressSubscrition = atom.config.observe('autocomplete-go.suppressActivationForCharacters', (value) => {
      this.suppressForCharacters = _.map(value, (c) => {
        let char = c ? c.trim() : ''
        char = (() => {
          switch (false) {
            case char.toLowerCase() !== 'comma':
              return ','
            case char.toLowerCase() !== 'newline':
              return '\n'
            case char.toLowerCase() !== 'space':
              return ' '
            case char.toLowerCase() !== 'tab':
              return '\t'
            default:
              return char
          }
        })()
        return char
      })
      this.suppressForCharacters = _.compact(this.suppressForCharacters)
    })
    this.subscriptions.add(suppressSubscrition)
    this.funcRegex = /^(?:func[(]{1})([^\)]*)(?:[)]{1})(?:$|(?:\s)([^\(]*$)|(?: [(]{1})([^\)]*)(?:[)]{1}))/i
  }

  dispose () {
    if (this.subscriptions) {
      this.subscriptions.dispose()
    }
    this.subscriptions = null
    this.goconfig = null
    this.subscribers = null
    this.selector = null
    this.inclusionPriority = null
    this.excludeLowerPriority = null
    this.suppressForCharacters = null
    this.disableForSelector = null
    this.funcRegex = null
  }

  ready () {
    if (!this.goconfig) {
      return false
    }
    let config = this.goconfig()
    if (!config) {
      return false
    }
    return true
  }

  isValidEditor (editor) {
    if (!editor || !editor.getGrammar) {
      return false
    }
    let grammar = editor.getGrammar()
    if (!grammar) {
      return false
    }
    if (grammar.scopeName === 'source.go') {
      return true
    }
    return false
  }

  characterIsSuppressed (char) {
    return this.suppressForCharacters.indexOf(char) !== -1
  }

  getSuggestions (options) {
    let p = new Promise((resolve) => {
      if (!options || !this.ready() || !this.isValidEditor(options.editor)) {
        return resolve()
      }
      let config = this.goconfig()
      let buffer = options.editor.getBuffer()
      if (!buffer || !options.bufferPosition) {
        return resolve()
      }

      let index = buffer.characterIndexForPosition(options.bufferPosition)
      let text = options.editor.getText()
      if (index > 0 && this.characterIsSuppressed(text[index - 1])) {
        return resolve()
      }
      let quotedRange = options.editor.displayBuffer.bufferRangeForScopeAtPosition('.string.quoted', options.bufferPosition)
      if (quotedRange) {
        return resolve()
      }
      let offset = Buffer.byteLength(text.substring(0, index), 'utf8')

      let locatorOptions = {
        file: options.editor.getPath(),
        directory: path.dirname(options.editor.getPath())
      }

      let args = ['-f=json', 'autocomplete', buffer.getPath(), offset]
      config.locator.findTool('gocode', locatorOptions).then((cmd) => {
        if (!cmd) {
          resolve()
          return false
        }
        let cwd = path.dirname(buffer.getPath())
        let env = config.environment(locatorOptions)
        config.executor.exec(cmd, args, {cwd: cwd, env: env, input: text}).then((r) => {
          if (r.stderr && r.stderr.trim() !== '') {
            console.log('autocomplete-go: (stderr) ' + r.stderr)
          }
          let messages = []
          if (r.stdout && r.stdout.trim() !== '') {
            messages = this.mapMessages(r.stdout, options.editor, options.bufferPosition)
          }
          if (!messages || messages.length < 1) {
            return resolve()
          }
          resolve(messages)
        }).catch((e) => {
          console.log(e)
          resolve()
        })
      })
    })

    if (this.subscribers && this.subscribers.length > 0) {
      for (let subscriber of this.subscribers) {
        subscriber(p)
      }
    }
    return p
  }

  onDidGetSuggestions (s) {
    if (this.subscribers) {
      this.subscribers.push(s)
    }
  }

  mapMessages (data, editor, position) {
    if (!data) {
      return []
    }
    let res
    try {
      res = JSON.parse(data)
    } catch (e) {
      if (e && e.handle) {
        e.handle()
      }
      console.log(e)
      return []
    }

    let numPrefix = res[0]
    let candidates = res[1]
    if (!candidates) {
      return []
    }
    let prefix = editor.getTextInBufferRange([[position.row, position.column - numPrefix], position])
    let suffix = false
    try {
      suffix = editor.getTextInBufferRange([position, [position.row, position.column + 1]])
    } catch (e) {
      console.log(e)
    }
    let suggestions = []
    for (let c of candidates) {
      let suggestion = {
        replacementPrefix: prefix,
        leftLabel: c.type || c.class,
        type: this.translateType(c.class)
      }
      if (c.class === 'func' && (!suffix || suffix !== '(')) {
        suggestion = this.upgradeSuggestion(suggestion, c)
      } else {
        suggestion.text = c.name
      }
      if (suggestion.type === 'package') {
        suggestion.iconHTML = ''
      }
      suggestions.push(suggestion)
    }
    return suggestions
  }

  translateType (type) {
    if (type === 'func') {
      return 'function'
    }
    if (type === 'var') {
      return 'variable'
    }
    if (type === 'const') {
      return 'constant'
    }
    if (type === 'PANIC') {
      return 'panic'
    }
    return type
  }

  upgradeSuggestion (suggestion, c) {
    if (!c || !c.type || c.type === '') {
      return suggestion
    }
    let match = this.funcRegex.exec(c.type)
    if (!match || !match[0]) { // Not a function
      suggestion.snippet = c.name + '()'
      suggestion.leftLabel = ''
      return suggestion
    }
    suggestion.leftLabel = match[2] || match[3] || ''
    suggestion.snippet = this.generateSnippet(c.name, match)
    return suggestion
  }

  generateSnippet (name, match) {
    let signature = name
    if (!match || !match[1] || match[1] === '') {
      // Has no arguments, shouldn't be a snippet, for now
      return signature + '()'
    }
    let args = match[1].split(/, /)
    args = _.map(args, (a) => {
      if (!a || a.length <= 2) {
        return a
      }
      if (a.substring(a.length - 2, a.length) === '{}') {
        return a.substring(0, a.length - 1) + '\\}'
      }
      return a
    })

    if (args.length === 1) {
      return signature + '(${1:' + args[0] + '})'
    }
    let i = 1
    for (let arg of args) {
      if (i === 1) {
        signature = signature + '(${' + i + ':' + arg + '}'
      } else {
        signature = signature + ', ${' + i + ':' + arg + '}'
      }
      i = i + 1
    }

    signature = signature + ')'
    return signature
    // TODO: Emit function's result(s) in snippet, when appropriate
  }
}
export {GocodeProvider}
<commit_msg>Warn User Of Error<commit_after>'use babel'

import {CompositeDisposable} from 'atom'
import path from 'path'
import _ from 'lodash'

class GocodeProvider {
  constructor (goconfigFunc, gogetFunc) {
    this.goconfig = goconfigFunc
    this.goget = gogetFunc
    this.subscriptions = new CompositeDisposable()
    this.subscribers = []

    this.selector = '.source.go'
    this.inclusionPriority = 1
    this.excludeLowerPriority = atom.config.get('autocomplete-go.suppressBuiltinAutocompleteProvider')
    this.suppressForCharacters = []
    this.disableForSelector = atom.config.get('autocomplete-go.scopeBlacklist')
    let suppressSubscrition = atom.config.observe('autocomplete-go.suppressActivationForCharacters', (value) => {
      this.suppressForCharacters = _.map(value, (c) => {
        let char = c ? c.trim() : ''
        char = (() => {
          switch (false) {
            case char.toLowerCase() !== 'comma':
              return ','
            case char.toLowerCase() !== 'newline':
              return '\n'
            case char.toLowerCase() !== 'space':
              return ' '
            case char.toLowerCase() !== 'tab':
              return '\t'
            default:
              return char
          }
        })()
        return char
      })
      this.suppressForCharacters = _.compact(this.suppressForCharacters)
    })
    this.subscriptions.add(suppressSubscrition)
    this.funcRegex = /^(?:func[(]{1})([^\)]*)(?:[)]{1})(?:$|(?:\s)([^\(]*$)|(?: [(]{1})([^\)]*)(?:[)]{1}))/i
  }

  dispose () {
    if (this.subscriptions) {
      this.subscriptions.dispose()
    }
    this.subscriptions = null
    this.goconfig = null
    this.subscribers = null
    this.selector = null
    this.inclusionPriority = null
    this.excludeLowerPriority = null
    this.suppressForCharacters = null
    this.disableForSelector = null
    this.funcRegex = null
  }

  ready () {
    if (!this.goconfig) {
      return false
    }
    let config = this.goconfig()
    if (!config) {
      return false
    }
    return true
  }

  isValidEditor (editor) {
    if (!editor || !editor.getGrammar) {
      return false
    }
    let grammar = editor.getGrammar()
    if (!grammar) {
      return false
    }
    if (grammar.scopeName === 'source.go') {
      return true
    }
    return false
  }

  characterIsSuppressed (char) {
    return this.suppressForCharacters.indexOf(char) !== -1
  }

  getSuggestions (options) {
    let p = new Promise((resolve) => {
      if (!options || !this.ready() || !this.isValidEditor(options.editor)) {
        return resolve()
      }
      let config = this.goconfig()
      let buffer = options.editor.getBuffer()
      if (!buffer || !options.bufferPosition) {
        return resolve()
      }

      let index = buffer.characterIndexForPosition(options.bufferPosition)
      let text = options.editor.getText()
      if (index > 0 && this.characterIsSuppressed(text[index - 1])) {
        return resolve()
      }
      let quotedRange = options.editor.displayBuffer.bufferRangeForScopeAtPosition('.string.quoted', options.bufferPosition)
      if (quotedRange) {
        return resolve()
      }
      let offset = Buffer.byteLength(text.substring(0, index), 'utf8')

      let locatorOptions = {
        file: options.editor.getPath(),
        directory: path.dirname(options.editor.getPath())
      }

      let args = ['-f=json', 'autocomplete', buffer.getPath(), offset]
      config.locator.findTool('gocode', locatorOptions).then((cmd) => {
        if (!cmd) {
          resolve()
          return false
        }
        let cwd = path.dirname(buffer.getPath())
        let env = config.environment(locatorOptions)
        config.executor.exec(cmd, args, {cwd: cwd, env: env, input: text}).then((r) => {
          if (r.stderr && r.stderr.trim() !== '') {
            console.log('autocomplete-go: (stderr) ' + r.stderr)
          }
          let messages = []
          if (r.stdout && r.stdout.trim() !== '') {
            messages = this.mapMessages(r.stdout, options.editor, options.bufferPosition)
          }
          if (!messages || messages.length < 1) {
            return resolve()
          }
          resolve(messages)
        }).catch((e) => {
          console.log(e)
          resolve()
        })
      })
    })

    if (this.subscribers && this.subscribers.length > 0) {
      for (let subscriber of this.subscribers) {
        subscriber(p)
      }
    }
    return p
  }

  onDidGetSuggestions (s) {
    if (this.subscribers) {
      this.subscribers.push(s)
    }
  }

  mapMessages (data, editor, position) {
    if (!data) {
      return []
    }
    let res
    try {
      res = JSON.parse(data)
    } catch (e) {
      if (e && e.handle) {
        e.handle()
      }
      atom.notifications.addError('gocode error', {
        detail: data,
        dismissable: true
      })
      console.log(e)
      return []
    }

    let numPrefix = res[0]
    let candidates = res[1]
    if (!candidates) {
      return []
    }
    let prefix = editor.getTextInBufferRange([[position.row, position.column - numPrefix], position])
    let suffix = false
    try {
      suffix = editor.getTextInBufferRange([position, [position.row, position.column + 1]])
    } catch (e) {
      console.log(e)
    }
    let suggestions = []
    for (let c of candidates) {
      let suggestion = {
        replacementPrefix: prefix,
        leftLabel: c.type || c.class,
        type: this.translateType(c.class)
      }
      if (c.class === 'func' && (!suffix || suffix !== '(')) {
        suggestion = this.upgradeSuggestion(suggestion, c)
      } else {
        suggestion.text = c.name
      }
      if (suggestion.type === 'package') {
        suggestion.iconHTML = ''
      }
      suggestions.push(suggestion)
    }
    return suggestions
  }

  translateType (type) {
    if (type === 'func') {
      return 'function'
    }
    if (type === 'var') {
      return 'variable'
    }
    if (type === 'const') {
      return 'constant'
    }
    if (type === 'PANIC') {
      return 'panic'
    }
    return type
  }

  upgradeSuggestion (suggestion, c) {
    if (!c || !c.type || c.type === '') {
      return suggestion
    }
    let match = this.funcRegex.exec(c.type)
    if (!match || !match[0]) { // Not a function
      suggestion.snippet = c.name + '()'
      suggestion.leftLabel = ''
      return suggestion
    }
    suggestion.leftLabel = match[2] || match[3] || ''
    suggestion.snippet = this.generateSnippet(c.name, match)
    return suggestion
  }

  generateSnippet (name, match) {
    let signature = name
    if (!match || !match[1] || match[1] === '') {
      // Has no arguments, shouldn't be a snippet, for now
      return signature + '()'
    }
    let args = match[1].split(/, /)
    args = _.map(args, (a) => {
      if (!a || a.length <= 2) {
        return a
      }
      if (a.substring(a.length - 2, a.length) === '{}') {
        return a.substring(0, a.length - 1) + '\\}'
      }
      return a
    })

    if (args.length === 1) {
      return signature + '(${1:' + args[0] + '})'
    }
    let i = 1
    for (let arg of args) {
      if (i === 1) {
        signature = signature + '(${' + i + ':' + arg + '}'
      } else {
        signature = signature + ', ${' + i + ':' + arg + '}'
      }
      i = i + 1
    }

    signature = signature + ')'
    return signature
    // TODO: Emit function's result(s) in snippet, when appropriate
  }
}
export {GocodeProvider}
<|endoftext|>


<commit_before>'use strict';

const uuid = require('uuid');

module.exports = bridge => {
	bridge.api.emitter.on('authentication', (username, allow, deny) => {
		if(username in bridge.config.get('whitelist')) allow();
		else deny();
	});

	bridge.api.emitter.on('config.createuser', (respond, body) => {
		let username = uuid.v4();

		bridge.config.addUser(username);
		respond.success([ 'username', username ]);
	});

	bridge.api.emitter.on('config.list', (respond, body) => respond.success(bridge.config.list()) );

	bridge.api.emitter.on('config.update', (respond, body) => {
		bridge.config.update(body);

		respond.success();
	});

	bridge.api.emitter.on('config.deleteuser', (respond, body, username, target) => {
		bridge.config.delUser(target);

		respond.success();
	});

	bridge.api.emitter.on('config.full', (respond, body) => respond.success(bridge.state()) );
};<commit_msg>'linkbutton' has to be set to true in order to create a new user<commit_after>'use strict';

const uuid = require('uuid');

module.exports = bridge => {
	bridge.api.emitter.on('authentication', (username, allow, deny) => {
		if(username in bridge.config.get('whitelist')) allow();
		else deny();
	});

	bridge.api.emitter.on('config.createuser', (respond, body) => {
		let linkbutton = bridge.config.get('linkbutton');

		if(linkbutton) {
			let username = uuid.v4();

			bridge.config.addUser(username);
			respond.success([ 'username', username ]);
		} else {
			respond.error(101);
		}
	});

	bridge.api.emitter.on('config.list', (respond, body) => respond.success(bridge.config.list()) );

	bridge.api.emitter.on('config.update', (respond, body) => {
		bridge.config.update(body);

		respond.success();
	});

	bridge.api.emitter.on('config.deleteuser', (respond, body, username, target) => {
		bridge.config.delUser(target);

		respond.success();
	});

	bridge.api.emitter.on('config.full', (respond, body) => respond.success(bridge.state()) );
};<|endoftext|>


<commit_before>'use strict';

var async = require('async');
var restify = require('restify');
var crypto = require('crypto');
var dbox = require("dbox");
var anyfetchProvider = require('anyfetch-provider');

var config = require('../../config/configuration.js');

module.exports.get = function(req, res, next) {

  async.waterfall([
    function noMissingParameters(cb) {
      // All params must be here
      if(!req.params.oauth_token) {
        return cb(new restify.MissingParameterError("specify oauth_token"));
      }
      if(!req.params.path) {
        return cb(new restify.MissingParameterError("specify path"));
      }
      if(!req.params.hash) {
        return cb(new restify.MissingParameterError("specify hash"));
      }
      req.params.format = encodeURIComponent(req.params.format) || 'jpeg';
      req.params.size = encodeURIComponent(req.params.size) || 'm';

      cb();
    },
    function checkValidHash(cb) {
      // Hash params must be valid
      var shasum = crypto.createHash('sha1');
      shasum.update(req.params.oauth_token);
      shasum.update(req.params.path);
      shasum.update(config.anyfetch_secret);

      var validHash = shasum.digest('hex').toString();

      if(validHash !== req.params.hash) {
        return cb(new restify.InvalidArgumentError("invalid hash"));
      }

      cb();
    },
    function retrieveToken(cb) {
      anyfetchProvider.retrieveDatas({'datas.oauth_token': req.params.oauth_token}, cb);
    },
    function retrieveThumbnail(oauthToken, cb) {
      var app = dbox.app({
        "app_key": config.dropbox_id,
        "app_secret": config.dropbox_secret
      });

      var client = app.client(oauthToken);
      var options = {
        root: "dropbox",
        size: req.params.size,
        format: req.params.format
      };

      client.thumbnails(req.params.path, options, function(status, reply, metadatas) {
        var err;
        if(status !== 200) {
          err = new Error("Invalid Dropbox status code:" + status);
          console.log("Failed to retrieve image", reply.toString());
        }

        cb(err, reply, metadatas);
      });
    },
    function sendThumbnail(reply, metadatas, cb) {
      res.writeHead(200, {
        'Content-Type': 'image/' + req.params.format
      });
      res.write(reply);
      res.end();

      cb();
    }
  ], next);

};
<commit_msg>Default values for size and format<commit_after>'use strict';

var async = require('async');
var restify = require('restify');
var crypto = require('crypto');
var dbox = require("dbox");
var anyfetchProvider = require('anyfetch-provider');

var config = require('../../config/configuration.js');

module.exports.get = function(req, res, next) {

  async.waterfall([
    function noMissingParameters(cb) {
      // All params must be here
      if(!req.params.oauth_token) {
        return cb(new restify.MissingParameterError("specify oauth_token"));
      }
      if(!req.params.path) {
        return cb(new restify.MissingParameterError("specify path"));
      }
      if(!req.params.hash) {
        return cb(new restify.MissingParameterError("specify hash"));
      }
      req.params.format = encodeURIComponent(req.params.format || 'jpeg');
      req.params.size = encodeURIComponent(req.params.size || 'm');

      cb();
    },
    function checkValidHash(cb) {
      // Hash params must be valid
      var shasum = crypto.createHash('sha1');
      shasum.update(req.params.oauth_token);
      shasum.update(req.params.path);
      shasum.update(config.anyfetch_secret);

      var validHash = shasum.digest('hex').toString();

      if(validHash !== req.params.hash) {
        return cb(new restify.InvalidArgumentError("invalid hash"));
      }

      cb();
    },
    function retrieveToken(cb) {
      anyfetchProvider.retrieveDatas({'datas.oauth_token': req.params.oauth_token}, cb);
    },
    function retrieveThumbnail(oauthToken, cb) {
      var app = dbox.app({
        "app_key": config.dropbox_id,
        "app_secret": config.dropbox_secret
      });

      var client = app.client(oauthToken);
      var options = {
        root: "dropbox",
        size: req.params.size,
        format: req.params.format
      };

      client.thumbnails(req.params.path, options, function(status, reply, metadatas) {
        var err;
        if(status !== 200) {
          err = new Error("Invalid Dropbox status code:" + status);
          console.log("Failed to retrieve image", reply.toString());
        }

        cb(err, reply, metadatas);
      });
    },
    function sendThumbnail(reply, metadatas, cb) {
      res.writeHead(200, {
        'Content-Type': 'image/' + req.params.format
      });
      res.write(reply);
      res.end();

      cb();
    }
  ], next);

};
<|endoftext|>


<commit_before>'use strict';

module.exports = function (shipit) {
  require('shipit-deploy')(shipit);
  const cmdOptions = { maxBuffer: 100 * 1024 * 1024 };

  shipit.initConfig({
    default: {
      repositoryUrl: 'https://github.com/godong9/MuggleNews.git',
      ignores: ['.git', 'node_modules'],
      keepReleases: 2,
      deleteOnRollback: false,
      shallowClone: true
    },
    local: {
      workspace: '/tmp/muggle-news',
      deployTo: '/Users/godong9/muggle-news',
      servers: 'godong9@localhost',
      branch: 'master'
    },
    production: {
      workspace: '/Users/godong9/muggle-news',
      deployTo: '/home/godong/muggle-news',
      servers: 'godong@godong9.com',
      branch: 'master',
      key: '/Users/godong9/.ssh/id_rsa'
    }
  });

  shipit.task('pwd', function () {
    return shipit.remote('pwd');
  });

  shipit.blTask('build', function () {
    let buildCommand = [
      'cd ' + shipit.config.deployTo + '/current/server',
      //package 설치
      'npm install',
      'bower install',
      'gulp build'
    ];

    return shipit.remote(makeCommandStr(buildCommand), cmdOptions);
  });

  shipit.blTask('deploy-config', function () {
    let buildCommand = [
      'scp /Users/godong9/project/MuggleNews/server/config/env/production.js godong@godong9.com:/home/godong/muggle-news/current/server/config/env',
      'scp /Users/godong9/project/MuggleNews/server/config/env/test.js godong@godong9.com:/home/godong/muggle-news/current/server/config/env'
    ];

    return shipit.local(makeCommandStr(buildCommand), cmdOptions);
  });

  shipit.blTask('deploy-start', function () {
    let buildCommand = [
      'cd ' + shipit.config.deployTo + '/current',
      'pm2 startOrRestart --env production process.json'
    ];

    return shipit.remote(makeCommandStr(buildCommand), cmdOptions);
  });

  shipit.blTask('deploy-restart', function () {
    let buildCommand = [
      'cd ' + shipit.config.deployTo + '/current',
      'pm2 restart MuggleNews'
    ];

    return shipit.remote(makeCommandStr(buildCommand), cmdOptions);
  });

  shipit.blTask('deploy-server', ['deploy', 'deploy-config', 'build'], function() {

  });

  /**
   * Array를 remote command용 문자열로 변경 한다.
   *
   * @param {Array} cmds bash command array
   * @returns {string} "cmd[0] && cmd[1] && cmd[2]" 형식의 stirng
   */
  function makeCommandStr(cmds){
    let cmdStr = "";
    let i;
    for (i = 0; i < cmds.length-1; i++) {
      let cmd = cmds[i];
      cmdStr += cmd + " && ";
    }
    cmdStr += cmds[cmds.length-1];
    return cmdStr;
  }
};<commit_msg>Update<commit_after>'use strict';

module.exports = function (shipit) {
  require('shipit-deploy')(shipit);
  const cmdOptions = { maxBuffer: 100 * 1024 * 1024 };

  shipit.initConfig({
    default: {
      repositoryUrl: 'https://github.com/godong9/MuggleNews.git',
      ignores: ['.git', 'node_modules'],
      keepReleases: 2,
      deleteOnRollback: false,
      shallowClone: true
    },
    local: {
      workspace: '/tmp/muggle-news',
      deployTo: '/Users/godong9/muggle-news',
      servers: 'godong9@localhost',
      branch: 'master'
    },
    production: {
      workspace: '/Users/godong9/muggle-news',
      deployTo: '/home/godong/muggle-news',
      servers: 'godong@godong9.com',
      branch: 'master',
      key: '/Users/godong9/.ssh/id_rsa'
    }
  });

  shipit.task('pwd', function () {
    return shipit.remote('pwd');
  });

  shipit.blTask('build', function () {
    let buildCommand = [
      'cd ' + shipit.config.deployTo + '/current/server',
      //package 설치
      'npm install',
      'bower install',
      'gulp build'
    ];

    return shipit.remote(makeCommandStr(buildCommand), cmdOptions);
  });

  shipit.blTask('deploy-config', function () {
    let buildCommand = [
      'scp /Users/godong9/project/MuggleNews/server/config/env/production.js godong@godong9.com:/home/godong/muggle-news/current/server/config/env',
      'scp /Users/godong9/project/MuggleNews/server/config/env/test.js godong@godong9.com:/home/godong/muggle-news/current/server/config/env'
    ];

    return shipit.local(makeCommandStr(buildCommand), cmdOptions);
  });

  shipit.blTask('deploy-start', function () {
    let buildCommand = [
      'source ~/.bashrc',
      'cd ' + shipit.config.deployTo + '/current',
      'pm2 startOrRestart --env production process.json'
    ];

    return shipit.remote(makeCommandStr(buildCommand), cmdOptions);
  });

  shipit.blTask('deploy-server', ['deploy', 'deploy-config', 'build', 'deploy-start'], function() {

  });

  /**
   * Array를 remote command용 문자열로 변경 한다.
   *
   * @param {Array} cmds bash command array
   * @returns {string} "cmd[0] && cmd[1] && cmd[2]" 형식의 stirng
   */
  function makeCommandStr(cmds){
    let cmdStr = "";
    let i;
    for (i = 0; i < cmds.length-1; i++) {
      let cmd = cmds[i];
      cmdStr += cmd + " && ";
    }
    cmdStr += cmds[cmds.length-1];
    return cmdStr;
  }
};<|endoftext|>


<commit_before>module.exports = (listen) => {
  const io = require('socket.io').listen(listen);
  const rooms = io.sockets.adapter.rooms;

  io.on('connection', (socket) => {
    //console.log('a user connected');

    socket.on('join room', (room) => {
      if (room && room.length === 5 && rooms[room]) {
        socket.room = room;
        socket.emit('join room success');
        socket.join(room);
        // console.log(socket.id);
        // console.log(socket.adapter.rooms);
        // console.log(io.sockets.adapter.rooms[room]);
        // io.in(room).emit('user joined', room);
      } else {
        socket.emit('join room error', `Room '${room}' was not found`);
      }
    });

    socket.on('create room', (room) => {
      if (room && room.length === 5) {
        socket.room = room;
        socket.emit('create room success');
        socket.join(room);
      } else {
        socket.emit('create room error', `Room '${room}' is invalid`);
      }
    });

    socket.on('lecture start', (room) => {
      if (socket.room) {
        io.in(socket.room).emit('lecture started');
      } else {
        socket.emit('lecture start error', 'You do not belong to a room');
      }
    });

    socket.on('lecture end', (room) => {
      if (socket.room) {
        io.in(socket.room).emit('lecture ended');
      } else {
        socket.emit('lecture end error', 'You do not belong to a room');
      }
    });

    socket.on('new note', (note) => {
      if (note) {
        // save notes into redis
      }
    });

    //socket.on('disconnect', () => console.log('a user disconnected'));
  });
  return io;
};<commit_msg>(dev) add comments for dev<commit_after>module.exports = (listen) => {
  const io = require('socket.io').listen(listen);
  const rooms = io.sockets.adapter.rooms;

  io.on('connection', (socket) => {
    //console.log('a user connected');

    socket.on('join room', (room) => {
      if (room && room.length === 5 && rooms[room]) {
        socket.room = room;
        socket.emit('join room success');
        socket.join(room);
        // console.log(socket.id);
        // console.log(socket.adapter.rooms);
        // console.log(io.sockets.adapter.rooms[room]);
        // io.in(room).emit('user joined', room);

        /* redis ==> add userId to "roomId" Set */
      } else {
        socket.emit('join room error', `Room '${room}' was not found`);
      }
    });

    socket.on('create room', (room) => {
      if (room && room.length === 5) {
        socket.room = room;
        socket.emit('create room success');
        socket.join(room);
      } else {
        socket.emit('create room error', `Room '${room}' is invalid`);
      }
    });

    socket.on('lecture start', (room) => {
      if (socket.room) {
        io.in(socket.room).emit('lecture started');
      } else {
        socket.emit('lecture start error', 'You do not belong to a room');
      }
    });

    socket.on('lecture end', (room) => {
      if (socket.room) {
        io.in(socket.room).emit('lecture ended');
      } else {
        socket.emit('lecture end error', 'You do not belong to a room');
      }
    });

    socket.on('new note', (note) => {
      if (note) {

        /* redis ==> add note to "userId:roomId" List of notes*/
        // note = { userId, content, roomId, timeStamp }
        // userId:roomId
        // save notes into redis
      }
    });

    //socket.on('disconnect', () => console.log('a user disconnected'));
  });
  return io;
};
<|endoftext|>


<commit_before>// server.js

// BASE SETUP
// =============================================================================

// call the packages we need
var express    = require('express');        // call express
var app        = express();                 // define our app using express
var bodyParser = require('body-parser');

// sequelize prpr_man
var Sequelize = require('sequelize');
var database = new Sequelize('sample','','',{dialect:'sqlite',storage:'./database.db'});

// use Model
var User =  database.define('User', {
    twitter_id: Sequelize.STRING,
    room_id: Sequelize.STRING,
    longitude: Sequelize.INTEGER,
    latitude: Sequelize.INTEGER,
    is_abnormality: Sequelize.BOOLEAN
});
var Room =  database.define('Room', {
    host_user: Sequelize.STRING
});

User.belongsTo(Room, {foreignKey: 'room_id'});
Room.hasMany(User , {foreignKey: 'room_id'});

// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var port = process.env.PORT || 3000;        // set our port

// ROUTES FOR OUR API
// =============================================================================
var router = express.Router();              // get an instance of the express Router

// middleware to use for all requests
router.use(function(req, res, next) {
    // do logging
    console.log('Something is happening.');
    next(); // make sure we go to the next routes and don't stop here
});

// test route to make sure everything is working (accessed at GET http://localhost:3000/api)
router.get('/', function(req, res) {
    res.json({ message: 'Post a test message.' });
});

// on routes that end in /rooms
// ----------------------------------------------------
router.route('/rooms')

// create a users (accessed at POST http://localhost:3000/api/rooms)
    .post(function(req, res) {
        var room = Room.build({
            host_user: req.body.host_user
        }).save();
        if(req.query.userID != null){
            var users = req.query.userID.split(" ");
            for(var i = 0;i<users.length;i++){
                User.findOne({ where: {twitter_id: users[i]} }).then(function(user) {
                    if(user){
                        Room.findOne({where:{host_user: req.body.host_user}})
                            .then(function(room)
                                  {
                                      var RoomId = room.dataValues.id;
                                      user.updateAttributes({
                                          room_id: RoomId
                                      }).then(function(log){
                                          console.log(log.dataValues.twitter_id + " is Updated");
                                      });
                                  });                    }
                });
            }
            res.json({message:'DB save success'});
        }
    })

// get all the rooms (accessed at GET http://localhost:8080/api/rooms)
    .get(function(req, res) {

        if(req.query.getRoomFromHostUserID != null){
            req.params.host_user = req.query.getRoomFromHostUserId;
            Room.findAll({where:{host_user:req.params.host_user}})
                .then(function(room){
                    res.json(room);
                });
        }else{
            Room.findAll()
                .then(function(room){
                    res.json(room);
                });
        }
    });

// on routes that end in /rooms/:room_id
// ----------------------------------------------------
router.route('/rooms/:room_id')

// get the room with that id (accessed at GET http://localhost:3000/api/rooms/:room_id)
    .get(function(req, res) {
        Room.findById(req.params.room_id)
            .then(function(room){
                res.json(room);
            });
    })
// update the room with this id (accessed at PUT http://localhost:3000/api/rooms/:room_id)
    .put(function(req, res) {

        // use our room model to find the user we want
        Room.findById(req.params.room_id)
            .then(function(room){
                room.updateAttributes({
                    id: req.body.id,
                    host_user: req.body.host_user
                }).then(function(log){
                    console.log("Room_id: " + log.dataValues.id + " is Updated");
                });
                res.json({ message: 'Room updated!' });
            });
    })

// delete the room with this id (accessed at DELETE http://localhost:3000/api/users/:room_id)
    .delete(function(req, res) {
        Room.destroy({where:{id: req.params.room_id}})
            .then(function(){
                res.json({ message: 'Successfully deleted' });
            });
    });

// on routes that end in /users
// ----------------------------------------------------
router.route('/users')

// create a users (accessed at POST http://localhost:3000/api/users)
    .post(function(req, res) {

        var user = User.build({
            twitter_id: req.body.twitter_id,
            room_id: req.body.room_id,
            longitude: req.body.longitude,
            latitude: req.body.latitude,
            is_abnormality: req.body.is_abnormality
        }).save();
        res.json({ message: 'User created!' });
    })

// get all the rooms (accessed at GET http://localhost:8080/api/users)
    .get(function(req, res) {

        if(req.query.getUsersFromRoomID != null){
            req.params.room_id = req.query.getUsersFromRoomId;
            User.findAll({where:{room_id:req.params.room_id}})
                .then(function(user){
                    res.json(user);
                });
        }else{
            User.findAll()
                .then(function(user){
                    res.json(user);
                });
        }
    });

// on routes that end in /users/:twitter_id
// ----------------------------------------------------
router.route('/users/:twitter_id')

// get the user with that id (accessed at GET http://localhost:3000/api/users/:twitter_id)
    .get(function(req, res) {
        User.findOne({where:{twitter_id:req.params.twitter_id}})
            .then(function(user){
                res.json(user);
            });
    })
// update the user with this id (accessed at PUT http://localhost:3000/api/users/:twitter_id)
    .put(function(req, res) {

        // use our room model to find the user we want
        User.findOne({twitter_id : req.params.twitter_id}, function(err, user) {
            if (err)
                res.send(err);
            user.twitter_id = req.body.twitter_id;
            user.longitude = req.body.longitude;
            user.latitude = req.body.latitude;
            user.is_abnormality = req.body.is_abnormality;
            user.room_id = req.body.room_id;

            // save the bear
            user.save(function(err) {
                if (err)
                    res.send(err);
                res.json({ message: 'User updated!' });
            });
        });
    })

// delete the user with this id (accessed at DELETE http://localhost:3000/api/users/:twitter_id)
    .delete(function(req, res) {
        User.remove({
            twitter_id: req.params.twitter_id
        }, function(err, user) {
            if (err)
                res.send(err);
            res.json({ message: 'Successfully deleted' });
        });
    });

// on routes that end in /tmps/:tmp_id
// ----------------------------------------------------
router.route('/tmps/:tmp_id')

// delete the user with this id (accessed at DELETE http://localhost:3000/api/tmps/:tmp_id)
    .delete(function(req, res) {
        Tmp.remove({
            _id: req.params.tmp_id
        }, function(err, tmp) {
            if (err)
                res.send(err);
            res.json({ message: 'Successfully deleted' });
        });
    });

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);

// START THE SERVER AND CREATE DATABASE
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);
<commit_msg>ADD chatch() Error<commit_after>// server.js

// BASE SETUP
// =============================================================================

// call the packages we need
var express    = require('express');        // call express
var app        = express();                 // define our app using express
var bodyParser = require('body-parser');

// sequelize prpr_man
var Sequelize = require('sequelize');
var database = new Sequelize('sample','','',{dialect:'sqlite',storage:'./database.db'});

// use Model
var User =  database.define('User', {
    twitter_id: Sequelize.STRING,
    room_id: Sequelize.STRING,
    longitude: Sequelize.INTEGER,
    latitude: Sequelize.INTEGER,
    is_abnormality: Sequelize.BOOLEAN
});
var Room =  database.define('Room', {
    host_user: Sequelize.STRING
});

User.belongsTo(Room, {foreignKey: 'room_id'});
Room.hasMany(User , {foreignKey: 'room_id'});

// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var port = process.env.PORT || 3000;        // set our port

// ROUTES FOR OUR API
// =============================================================================
var router = express.Router();              // get an instance of the express Router

// middleware to use for all requests
router.use(function(req, res, next) {
    // do logging
    console.log('Something is happening.');
    next(); // make sure we go to the next routes and don't stop here
});

// test route to make sure everything is working (accessed at GET http://localhost:3000/api)
router.get('/', function(req, res) {
    res.json({ message: 'Post a test message.' });
});

// on routes that end in /rooms
// ----------------------------------------------------
router.route('/rooms')

// create a users (accessed at POST http://localhost:3000/api/rooms)
    .post(function(req, res) {
        var room = Room.build({
            host_user: req.body.host_user
        }).save();
        if(req.query.userID != null){
            var users = req.query.userID.split(" ");
            for(var i = 0;i<users.length;i++){
                User.findOne({ where: {twitter_id: users[i]} }).then(function(user) {
                    if(user){
                        Room.findOne({where:{host_user: req.body.host_user}})
                            .then(function(room)
                                  {
                                      var RoomId = room.dataValues.id;
                                      user.updateAttributes({
                                          room_id: RoomId
                                      }).then(function(log){
                                          console.log(log.dataValues.twitter_id + " is Updated");
                                      });
                                  });
                    }
                });
            }
            res.json({message:'DB save success'});
        }
    })

// get all the rooms (accessed at GET http://localhost:8080/api/rooms)
    .get(function(req, res) {

        if(req.query.getRoomFromHostUserID != null){
            req.params.host_user = req.query.getRoomFromHostUserId;
            Room.findAll({where:{host_user:req.params.host_user}})
                .then(function(room){
                    res.json(room);
                })
                .catch(function(err) {
                    if(err)
                        res.json(err);
                });
        }else{
            Room.findAll()
                .then(function(room){
                    res.json(room);
                })
                .catch(function(err) {
                    if(err)
                        res.json(err);
                });
        }
    });

// on routes that end in /rooms/:room_id
// ----------------------------------------------------
router.route('/rooms/:room_id')

// get the room with that id (accessed at GET http://localhost:3000/api/rooms/:room_id)
    .get(function(req, res) {
        Room.findById(req.params.room_id)
            .then(function(room){
                res.json(room);
            })
            .catch(function(err) {
                if(err)
                    res.json(err);
            });
    })
// update the room with this id (accessed at PUT http://localhost:3000/api/rooms/:room_id)
    .put(function(req, res) {

        // use our room model to find the user we want
        Room.findById(req.params.room_id)
            .then(function(room){
                room.updateAttributes({
                    id: req.body.id,
                    host_user: req.body.host_user
                }).then(function(log){
                    console.log("Room_id: " + log.dataValues.id + " is Updated");
                });
                res.json({ message: 'Room updated!' });
            })
            .catch(function(err) {
                if(err)
                    res.json(err);
            });
    })

// delete the room with this id (accessed at DELETE http://localhost:3000/api/users/:room_id)
    .delete(function(req, res) {
        Room.destroy({where:{id: req.params.room_id}})
            .then(function(){
                res.json({ message: 'Successfully deleted' });
            })
            .catch(function(err) {
                if(err)
                    res.json(err);
            });

    });

// on routes that end in /users
// ----------------------------------------------------
router.route('/users')

// create a users (accessed at POST http://localhost:3000/api/users)
    .post(function(req, res) {

        var user = User.build({
            twitter_id: req.body.twitter_id,
            room_id: req.body.room_id,
            longitude: req.body.longitude,
            latitude: req.body.latitude,
            is_abnormality: req.body.is_abnormality
        })
                .save().then(function(){
                    res.json({ message: 'User created!' });
                })
                .catch(function(err) {
                    if(err)
                        res.json(err);
                });
    })

// get all the rooms (accessed at GET http://localhost:8080/api/users)
    .get(function(req, res) {

        if(req.query.getUsersFromRoomID != null){
            req.params.room_id = req.query.getUsersFromRoomId;
            User.findAll({where:{room_id:req.params.room_id}})
                .then(function(user){
                    res.json(user);
                })
                .catch(function(err) {
                    if(err)
                        res.json(err);
                });
        }else{
            User.findAll()
                .then(function(user){
                    res.json(user);
                })
                .catch(function(err) {
                    if(err)
                        res.json(err);
                });
        }
    });

// on routes that end in /users/:twitter_id
// ----------------------------------------------------
router.route('/users/:twitter_id')

// get the user with that id (accessed at GET http://localhost:3000/api/users/:twitter_id)
    .get(function(req, res) {
        User.findOne({where:{twitter_id:req.params.twitter_id}})
            .then(function(user){
                res.json(user);
            })
            .catch(function(err) {
                if(err)
                    res.json(err);
            });
    })
// update the user with this id (accessed at PUT http://localhost:3000/api/users/:twitter_id)
    .put(function(req, res) {

        // use our room model to find the user we want
        User.findOne({twitter_id : req.params.twitter_id}, function(err, user) {
            if (err)
                res.send(err);
            user.twitter_id = req.body.twitter_id;
            user.longitude = req.body.longitude;
            user.latitude = req.body.latitude;
            user.is_abnormality = req.body.is_abnormality;
            user.room_id = req.body.room_id;

            // save the bear
            user.save(function(err) {
                if (err)
                    res.send(err);
                res.json({ message: 'User updated!' });
            });
        });
    })

// delete the user with this id (accessed at DELETE http://localhost:3000/api/users/:twitter_id)
    .delete(function(req, res) {
        User.remove({
            twitter_id: req.params.twitter_id
        }, function(err, user) {
            if (err)
                res.send(err);
            res.json({ message: 'Successfully deleted' });
        });
    });

// on routes that end in /tmps/:tmp_id
// ----------------------------------------------------
router.route('/tmps/:tmp_id')

// delete the user with this id (accessed at DELETE http://localhost:3000/api/tmps/:tmp_id)
    .delete(function(req, res) {
        Tmp.remove({
            _id: req.params.tmp_id
        }, function(err, tmp) {
            if (err)
                res.send(err);
            res.json({ message: 'Successfully deleted' });
        });
    });

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);

// START THE SERVER AND CREATE DATABASE
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);
<|endoftext|>