<commit_before>'use strict';

var mongoose = require('mongoose'),
    restify = require('restify'),
    Promise = require('bluebird'),
    aclManager = require('../lib/auth/acl-manager'),
    rHandler = require('../lib/util/response-handlers');

class CommonController {
    constructor() {

        function deleteProtected(req) {
            delete req.body.region_uuid;
            delete req.body.user_uuid;
            delete req.body.legacy_id;
        }

        this.coroutines = {
            findResource: {
                main: Promise.coroutine(function* (req, res, next, config) {
                    if (req.params.uuid === 'me' && req.user) {
                        req.params.uuid = req.user.uuid;
                    }
                    let query = require('../lib/util/query-mapping')({}, req, config);

                    let paths = mongoose.model(config.resource).schema.paths;
                    if (paths.hasOwnProperty('hidden')) {
                        query.hidden = false;
                    }

                    let q = mongoose.model(config.resource).find(query);
                    q = config.select ? q.select(config.select) : q;
                    if (req.params.skip) {
                        q = q.skip(parseInt(req.params.skip));
                    }
                    if (req.params.limit) {
                        q = q.limit(parseInt(req.params.limit));
                    }
                    if (req.params.sort) {
                        q = q.sort(req.params.sort);
                    }
                    let results = yield q.exec();
                    if (results.length > 0 && results[0].user_uuid) {
                        let output = [];
                        return Promise.map(results, function (result) {
                                return mongoose.model('User')
                                    .findOne({uuid: result.user_uuid})
                                    .select('uuid nickname').exec()
                                    .then(function (user) {
                                        if (result) {
                                            result = result.toObject();
                                            result.user = user;
                                            output.push(result);
                                        }
                                    });
                            })
                            .then(function () {
                                rHandler.handleDataResponse(output, 200, res, next);
                            });
                    } else {
                        rHandler.handleDataResponse(results, 200, res, next);
                    }
                }),
                pre: Promise.resolve
            },
            getResource: {
                main: Promise.coroutine(function* (req, res, next, config) {
                    let query = {$or: [{uuid: req.params.uuid}, {slug: req.params.uuid.toLowerCase()}]},
                        paths = mongoose.model(config.resource).schema.paths,
                        q = mongoose.model(config.resource).findOne(query);
                    q = config.select ? q.select(config.select) : q;
                    let result = yield q.exec();
                    if (result) {
                        result = result.toObject();
                    } else {
                        return rHandler.handleErrorResponse(new restify.NotFoundError(), res, next);
                    }
                    if (paths.hasOwnProperty('hidden') && result.hidden) {
                        let region = yield mongoose.model('Region').findOne({uuid:result.region_uuid});
                        if (!region) {
                            return rHandler.handleErrorResponse(new restify.NotFoundError(), res, next);
                        }
                        // TODO: put this in lib
                        let isAdmin = req.api_key && (
                                req.api_key.scopes.indexOf('admin') ||
                                req.api_key.scopes.indexOf('region-' + region.uuid)
                            );
                        if (!isAdmin) {
                            return rHandler.handleErrorResponse(new restify.NotFoundError(), res, next);
                        }
                    }
                    if (result && result.user_uuid) {
                        result.user = yield mongoose.model('User')
                            .findOne({uuid:result.user_uuid})
                            .select('uuid nickname').exec();
                    }
                    rHandler.handleDataResponse(result, 200, res, next);
                }),
                pre: Promise.resolve
            },
            postResource: {
                main: Promise.coroutine(function* (req, res, next, config) {
                    if (req.user && req.user.uuid && !req.body.user_uuid) req.body.user_uuid = req.user.uuid;
                    if (req.body.hasOwnProperty('region_uuid')) {
                        let region = yield mongoose.model(config.resource).findOne({uuid: req.body.region_uuid});
                        req.body.hidden = region.moderate || false;
                    }
                    let result = yield mongoose.model(config.resource).create(req.body);
                    yield aclManager.setAclEntry(
                        req.url + '/' + result.uuid,
                        [req.user.uuid, 'admin'],
                        ['get', 'put', 'delete']
                    );
                    yield aclManager.setAclEntry(req.url + '/' + result.uuid, ['user'], ['get']);
                    rHandler.handleDataResponse(result, 201, res, next);
                }),
                pre: Promise.resolve
            },
            putResource: {
                main: Promise.coroutine(function* (req, res, next, config) {
                    let data = yield mongoose.model(config.resource).findOne({uuid: req.params.uuid}).exec();
                    if (data) {
                        for (var key in req.body) {
                            data[key] = req.body[key];
                        }
                        yield data.save();
                        rHandler.handleDataResponse(data, 200, res, next);
                    } else {
                        rHandler.handleErrorResponse(new restify.NotFoundError(), res, next);
                    }
                }),
                pre: Promise.resolve
            },
            delResource: {
                main: Promise.coroutine(function* (req, res, next, config) {
                    let result = yield mongoose.model(config.resource).findOneAndRemove({uuid: req.params.uuid});
                    if (result) {
                        yield aclManager.removeAclEntry(req.url, req.user.uuid, '*');
                        yield aclManager.removeAclEntry(req.url, 'admin', '*');
                        yield aclManager.removeAclEntry(req.url, 'user', '*');
                        rHandler.handleDataResponse(result, 200, res, next);
                    } else {
                        rHandler.handleErrorResponse(new restify.NotFoundError(), res, next);
                    }
                }),
                pre: Promise.resolve
            }
        };
    }

    map(verb, config) {
        let instance = this;
        return function executeRequest(req, res, next) {
            return Promise.resolve()
                .then(() => {
                    return instance.coroutines[`${verb}Resource`].pre(req, res, next, config);
                })
                .then(() => {
                    return instance.coroutines[`${verb}Resource`].main(req, res, next, config);
                })
                .catch(err => {
                    rHandler.handleErrorResponse(err, res, next);
                });
        };
    }
}

module.exports = CommonController;<commit_msg>fix region query<commit_after>'use strict';

var mongoose = require('mongoose'),
    restify = require('restify'),
    Promise = require('bluebird'),
    aclManager = require('../lib/auth/acl-manager'),
    rHandler = require('../lib/util/response-handlers');

class CommonController {
    constructor() {

        function deleteProtected(req) {
            delete req.body.region_uuid;
            delete req.body.user_uuid;
            delete req.body.legacy_id;
        }

        this.coroutines = {
            findResource: {
                main: Promise.coroutine(function* (req, res, next, config) {
                    if (req.params.uuid === 'me' && req.user) {
                        req.params.uuid = req.user.uuid;
                    }
                    let query = require('../lib/util/query-mapping')({}, req, config);

                    let paths = mongoose.model(config.resource).schema.paths;
                    if (paths.hasOwnProperty('hidden')) {
                        query.hidden = false;
                    }

                    let q = mongoose.model(config.resource).find(query);
                    q = config.select ? q.select(config.select) : q;
                    if (req.params.skip) {
                        q = q.skip(parseInt(req.params.skip));
                    }
                    if (req.params.limit) {
                        q = q.limit(parseInt(req.params.limit));
                    }
                    if (req.params.sort) {
                        q = q.sort(req.params.sort);
                    }
                    let results = yield q.exec();
                    if (results.length > 0 && results[0].user_uuid) {
                        let output = [];
                        return Promise.map(results, function (result) {
                                return mongoose.model('User')
                                    .findOne({uuid: result.user_uuid})
                                    .select('uuid nickname').exec()
                                    .then(function (user) {
                                        if (result) {
                                            result = result.toObject();
                                            result.user = user;
                                            output.push(result);
                                        }
                                    });
                            })
                            .then(function () {
                                rHandler.handleDataResponse(output, 200, res, next);
                            });
                    } else {
                        rHandler.handleDataResponse(results, 200, res, next);
                    }
                }),
                pre: Promise.resolve
            },
            getResource: {
                main: Promise.coroutine(function* (req, res, next, config) {
                    let query = {$or: [{uuid: req.params.uuid}, {slug: req.params.uuid.toLowerCase()}]},
                        paths = mongoose.model(config.resource).schema.paths,
                        q = mongoose.model(config.resource).findOne(query);
                    q = config.select ? q.select(config.select) : q;
                    let result = yield q.exec();
                    if (result) {
                        result = result.toObject();
                    } else {
                        return rHandler.handleErrorResponse(new restify.NotFoundError(), res, next);
                    }
                    if (paths.hasOwnProperty('hidden') && result.hidden) {
                        let region = yield mongoose.model('Region').findOne({uuid:result.region_uuid});
                        if (!region) {
                            return rHandler.handleErrorResponse(new restify.NotFoundError(), res, next);
                        }
                        // TODO: put this in lib
                        let isAdmin = req.api_key && (
                                req.api_key.scopes.indexOf('admin') ||
                                req.api_key.scopes.indexOf('region-' + region.uuid)
                            );
                        if (!isAdmin) {
                            return rHandler.handleErrorResponse(new restify.NotFoundError(), res, next);
                        }
                    }
                    if (result && result.user_uuid) {
                        result.user = yield mongoose.model('User')
                            .findOne({uuid:result.user_uuid})
                            .select('uuid nickname').exec();
                    }
                    rHandler.handleDataResponse(result, 200, res, next);
                }),
                pre: Promise.resolve
            },
            postResource: {
                main: Promise.coroutine(function* (req, res, next, config) {
                    if (req.user && req.user.uuid && !req.body.user_uuid) req.body.user_uuid = req.user.uuid;
                    if (req.body.hasOwnProperty('region_uuid')) {
                        let region = yield mongoose.model('Region').findOne({uuid: req.body.region_uuid});
                        req.body.hidden = region.moderate || false;
                    }
                    let result = yield mongoose.model(config.resource).create(req.body);
                    yield aclManager.setAclEntry(
                        req.url + '/' + result.uuid,
                        [req.user.uuid, 'admin'],
                        ['get', 'put', 'delete']
                    );
                    yield aclManager.setAclEntry(req.url + '/' + result.uuid, ['user'], ['get']);
                    rHandler.handleDataResponse(result, 201, res, next);
                }),
                pre: Promise.resolve
            },
            putResource: {
                main: Promise.coroutine(function* (req, res, next, config) {
                    let data = yield mongoose.model(config.resource).findOne({uuid: req.params.uuid}).exec();
                    if (data) {
                        for (var key in req.body) {
                            data[key] = req.body[key];
                        }
                        yield data.save();
                        rHandler.handleDataResponse(data, 200, res, next);
                    } else {
                        rHandler.handleErrorResponse(new restify.NotFoundError(), res, next);
                    }
                }),
                pre: Promise.resolve
            },
            delResource: {
                main: Promise.coroutine(function* (req, res, next, config) {
                    let result = yield mongoose.model(config.resource).findOneAndRemove({uuid: req.params.uuid});
                    if (result) {
                        yield aclManager.removeAclEntry(req.url, req.user.uuid, '*');
                        yield aclManager.removeAclEntry(req.url, 'admin', '*');
                        yield aclManager.removeAclEntry(req.url, 'user', '*');
                        rHandler.handleDataResponse(result, 200, res, next);
                    } else {
                        rHandler.handleErrorResponse(new restify.NotFoundError(), res, next);
                    }
                }),
                pre: Promise.resolve
            }
        };
    }

    map(verb, config) {
        let instance = this;
        return function executeRequest(req, res, next) {
            return Promise.resolve()
                .then(() => {
                    return instance.coroutines[`${verb}Resource`].pre(req, res, next, config);
                })
                .then(() => {
                    return instance.coroutines[`${verb}Resource`].main(req, res, next, config);
                })
                .catch(err => {
                    rHandler.handleErrorResponse(err, res, next);
                });
        };
    }
}

module.exports = CommonController;<|endoftext|>


<commit_before>(function (ns) {

    // Dependencies
    var FunctionAnnotation = require("./../../base/annotation.js").FunctionAnnotation;
    var Shade = require("./../../interfaces.js");
    var walk = require('estraverse');
    var ExpressionHandler = require('../base/expression-handler.js').ExpressionHandler,
        Syntax = walk.Syntax,
        VisitorOption = walk.VisitorOption,
        ANNO = require("../../base/annotation.js").ANNO;

    // Shortcuts
    var Types = Shade.TYPES,
        Kinds = Shade.OBJECT_KINDS,
        Sources = Shade.SOURCES;

    var InternalFunctions = {
        "MatCol" : function(name, details){
            var matType = details.matType,
                colType = details.colType;
            return [matType + " " + name + "(" + matType + " mat, int idx, " + colType + " value){",
                  "  " + matType + " result = " + matType + "(mat);",
                  "  result[idx] = value;",
                  "  return result;",
                  "}"];
        }
    }

    var GLSL = {
        Storage: {
            CONST: "const",
            UNIFORM: "uniform",
            VARYING: "varying",
            ATTRIBUTE: "attribtue"
        }
    }

    var handler = new ExpressionHandler( {
        type: toGLSLType
    });

    /**
     * @param {object} opt
     */
    var getHeader = function (opt) {
        if (opt.omitHeader == true)
            return [];
        var header = [
            "// Generated by shade.js"
        ];
        if (opt.headers)
            header = header.concat(opt.headers)
        var floatPrecision = opt.floatPrecision || "highp";
        header.push("precision " + floatPrecision + " float;");
        header.push("");
        return header;
    }

    function toGLSLType(info, options) {
        if(!info) return "?";
        options = options || {};

        switch (info.type) {
            case Types.OBJECT:
                switch (info.kind) {
                    case Kinds.FLOAT4:
                        return "vec4";
                    case Kinds.FLOAT3:
                        return "vec3";
                    case Kinds.FLOAT2:
                        return "vec2";
                    case Kinds.TEXTURE:
                        return "sampler2D";
                    case Kinds.MATRIX3:
                        return "mat3";
                    case Kinds.MATRIX4:
                        return "mat4";
                    case Kinds.COLOR_CLOSURE:
                        return "vec4";
                    default:
                        return "<undefined>";
                }
            case Types.ARRAY:
                return toGLSLType(info.elements, options);

            case Types.UNDEFINED:
                if (options.allowUndefined)
                    return "void";
                throw new Error("Could not determine type");
            case Types.NUMBER:
                return "float";
            case Types.BOOLEAN:
                return "bool";
            case Types.INT:
                return "int";
            default:
                //throw new Error("toGLSLType: Unhandled type: " + info.type);
                return info.type;

        }
    }

    var toGLSLStorage = function(info) {
        if (!info.source)
            return null;
        if (info.source == Sources.VERTEX)
            return GLSL.Storage.VARYING;
        if (info.source == Sources.UNIFORM)
            return GLSL.Storage.UNIFORM;
        if (info.source == Sources.CONSTANT)
            return GLSL.Storage.CONST;
        throw new Error("toGLSLSource: Unhandled type: " + info.source);
    }

    function filterUndefined(arr) {
        return arr.filter(function(n) { return n.extra.type != Types.UNDEFINED; });
    }

    function createLineStack() {
        var arr = [];
        arr.push.apply(arr, arguments);
        var indent = "";
        arr.appendLine = function(line){
            line ? this.push(indent + line) : this.push("");
        };
        arr.changeIndention = function(add){
            while(add > 0){
                indent += "    "; add--;
            }
            if(add < 0){
                indent = indent.substr(0, indent.length + add*4);
            }
        };
        arr.append = function(str){
            this[this.length-1] = this[this.length-1] + str;
        };
        return arr;
    };

    /*Base.extend(LineStack.prototype, {

    });*/

    var generate = function (ast, opt) {

        opt = opt || {};

        var lines = createLineStack();

        traverse(ast, lines, opt);

        return lines.join("\n");
    }

    function appendInternalFunctions(lines, internalFunctions){
        if(!internalFunctions) return;
        for(var key in internalFunctions){
            var entry = internalFunctions[key];
            if(InternalFunctions[entry.type]){
                var linesToAdd = InternalFunctions[entry.type](entry.name, entry.details);
                lines.push.apply(lines, linesToAdd);
            }
            else{
                throw Error("Internal: InlineFunction of type '" + entry.type + "' not available!");
            }
        }
    }

    function traverse(ast, lines, opt) {
        var insideMain = false;

        walk.traverse(ast, {
                enter: function (node) {
                    try {
                        var type = node.type;
                        switch (type) {

                            case Syntax.Program:
                                getHeader(opt).forEach(function (e) {
                                    lines.push(e)
                                });
                                appendInternalFunctions(lines, ANNO(ast).getUserData().internalFunctions);
                                addForwardDeclarations(lines, node);
                                break;

                            case Syntax.FunctionDeclaration:
                                opt.newLines && lines.appendLine();
                                if(node.id.name == "main")
                                    insideMain = true;

                                lines.appendLine(generateFunctionSignature(node) + " {");
                                lines.changeIndention(1);
                                return;

                            case Syntax.ReturnStatement:
                                lines.appendLine(handler.statement(node));
                                return;

                            case Syntax.VariableDeclarator :
                                // console.log("Meep!");
                                var decl = handleVariableDeclaration(node, insideMain, opt);
                                lines.appendLine(decl);
                                return;

                            case Syntax.AssignmentExpression:
                            case Syntax.ExpressionStatement:
                                lines.appendLine(handler.expression(node) + ";")
                                return VisitorOption.Skip;;

                            case Syntax.IfStatement:
                                lines.appendLine("if(" + handler.expression(node.test, opt) + ") {");

                                lines.changeIndention(1);
                                traverse(node.consequent, lines, opt);
                                lines.changeIndention(-1);

                                if (node.alternate) {
                                    lines.appendLine("} else {");
                                    lines.changeIndention(1);
                                    traverse(node.alternate, lines, opt);
                                    lines.changeIndention(-1);
                                }
                                lines.appendLine("}");
                                return VisitorOption.Skip;

                            case Syntax.ForStatement:
                                lines.appendLine("for (" + handleInlineDeclaration(node.init, opt) + "; " + handler.expression(node.test, opt) +"; " + handler.expression(node.update, opt) + ") {");
                                lines.changeIndention(1);
                                traverse(node.body, lines, opt);
                                lines.changeIndention(-1);
                                lines.appendLine("}");
                                return VisitorOption.Skip;

                            case Syntax.ContinueStatement:
                                lines.appendLine("continue;");

                            default:
                            //console.log("Unhandled: " + type);

                        }
                    } catch (e) {
                        throw e;//console.error(e);
                        //Shade.throwError(node, e.message);
                    }
                },
                leave: function (node) {
                    var type = node.type;
                    switch (type) {
                        case Syntax.Program:
                            break;
                        case Syntax.FunctionDeclaration:
                            lines.changeIndention(-1);
                            lines.appendLine("}");
                            break;
                    }
                }
            }
        );
    }

    function addForwardDeclarations(lines, node) {
        var first = true;
        walk.traverse(node, {
            enter: function(node) {
                if(node.type == Syntax.FunctionDeclaration) {
                    if(node.id.name == "main") {
                        return;
                    }
                    if (first) {
                        first = false;
                        lines.appendLine("// Forward declarations");
                    }
                    lines.appendLine(generateFunctionSignature(node)+";");
                }
            }
        });
        if(!first) {
            lines.appendLine("");
        }
    }

    function generateFunctionSignature(node) {
        var func = new FunctionAnnotation(node);
        var methodStart = [toGLSLType(func.getReturnInfo(), { allowUndefined: true })];
        methodStart.push(node.id.name, '(');
        if (!(node.params && node.params.length)) {
            methodStart.push("void");
        } else {
            var methodArgs = [];
            node.params.forEach(function (param) {
                methodArgs.push(toGLSLType(param.extra) + " " + param.name);
            })
            methodStart.push(methodArgs.join(", "));
        }
        methodStart.push(")");
        return methodStart.join(" ");
    }

    function getStaticValue(extra) {
        if (!extra || extra.staticValue === undefined) return "";
        return extra.staticValue;
    };

    function handleVariableDeclaration(node, writeStorageQualifier, opt) {
        var storageQualifier = !writeStorageQualifier ? toGLSLStorage(node.extra) : null;
        var result = storageQualifier ? storageQualifier + " " : "";
        result += toGLSLType(node.extra) + " " + node.id.name;
        if (node.extra.elements) {
            result += "[" + (node.extra.staticSize ? node.extra.staticSize : "0") + "]";
        }
        if (node.init) result += " = " + handler.expression(node.init);
        if (!node.init && storageQualifier == GLSL.Storage.CONST) {
            result += " = " + getStaticValue(node.extra);
        }
        return result + ";";
    }

    function handleInlineDeclaration(node, opt) {
        if(!node)
            return "";
        if (node.type == Syntax.VariableDeclaration) {
            var result = node.declarations.reduce(function (declString, declaration) {
                var decl = toGLSLType(declaration.extra) + " " + declaration.id.name;
                if (declaration.init) {
                    decl += " = " + handler.expression(declaration.init);
                }
                return declString + decl;
            }, "");
            return result;
        }

        // GLSL allows only declaration in init, but since this is a new scope, it should be fine
        if (node.type == Syntax.AssignmentExpression) {
            return toGLSLType(node.extra) + " " + handler.expression(node.left) + " = " + handler.expression(node.right);
        }
        Shade.throwError(node, "Internal error in GLSL::handleInlineDeclaration, found " + node.type);
    }

    exports.generate = generate;

}(exports));
<commit_msg>GLSL: Added break statement<commit_after>(function (ns) {

    // Dependencies
    var FunctionAnnotation = require("./../../base/annotation.js").FunctionAnnotation;
    var Shade = require("./../../interfaces.js");
    var walk = require('estraverse');
    var ExpressionHandler = require('../base/expression-handler.js').ExpressionHandler,
        Syntax = walk.Syntax,
        VisitorOption = walk.VisitorOption,
        ANNO = require("../../base/annotation.js").ANNO;

    // Shortcuts
    var Types = Shade.TYPES,
        Kinds = Shade.OBJECT_KINDS,
        Sources = Shade.SOURCES;

    var InternalFunctions = {
        "MatCol" : function(name, details){
            var matType = details.matType,
                colType = details.colType;
            return [matType + " " + name + "(" + matType + " mat, int idx, " + colType + " value){",
                  "  " + matType + " result = " + matType + "(mat);",
                  "  result[idx] = value;",
                  "  return result;",
                  "}"];
        }
    }

    var GLSL = {
        Storage: {
            CONST: "const",
            UNIFORM: "uniform",
            VARYING: "varying",
            ATTRIBUTE: "attribtue"
        }
    }

    var handler = new ExpressionHandler( {
        type: toGLSLType
    });

    /**
     * @param {object} opt
     */
    var getHeader = function (opt) {
        if (opt.omitHeader == true)
            return [];
        var header = [
            "// Generated by shade.js"
        ];
        if (opt.headers)
            header = header.concat(opt.headers)
        var floatPrecision = opt.floatPrecision || "highp";
        header.push("precision " + floatPrecision + " float;");
        header.push("");
        return header;
    }

    function toGLSLType(info, options) {
        if(!info) return "?";
        options = options || {};

        switch (info.type) {
            case Types.OBJECT:
                switch (info.kind) {
                    case Kinds.FLOAT4:
                        return "vec4";
                    case Kinds.FLOAT3:
                        return "vec3";
                    case Kinds.FLOAT2:
                        return "vec2";
                    case Kinds.TEXTURE:
                        return "sampler2D";
                    case Kinds.MATRIX3:
                        return "mat3";
                    case Kinds.MATRIX4:
                        return "mat4";
                    case Kinds.COLOR_CLOSURE:
                        return "vec4";
                    default:
                        return "<undefined>";
                }
            case Types.ARRAY:
                return toGLSLType(info.elements, options);

            case Types.UNDEFINED:
                if (options.allowUndefined)
                    return "void";
                throw new Error("Could not determine type");
            case Types.NUMBER:
                return "float";
            case Types.BOOLEAN:
                return "bool";
            case Types.INT:
                return "int";
            default:
                //throw new Error("toGLSLType: Unhandled type: " + info.type);
                return info.type;

        }
    }

    var toGLSLStorage = function(info) {
        if (!info.source)
            return null;
        if (info.source == Sources.VERTEX)
            return GLSL.Storage.VARYING;
        if (info.source == Sources.UNIFORM)
            return GLSL.Storage.UNIFORM;
        if (info.source == Sources.CONSTANT)
            return GLSL.Storage.CONST;
        throw new Error("toGLSLSource: Unhandled type: " + info.source);
    }

    function filterUndefined(arr) {
        return arr.filter(function(n) { return n.extra.type != Types.UNDEFINED; });
    }

    function createLineStack() {
        var arr = [];
        arr.push.apply(arr, arguments);
        var indent = "";
        arr.appendLine = function(line){
            line ? this.push(indent + line) : this.push("");
        };
        arr.changeIndention = function(add){
            while(add > 0){
                indent += "    "; add--;
            }
            if(add < 0){
                indent = indent.substr(0, indent.length + add*4);
            }
        };
        arr.append = function(str){
            this[this.length-1] = this[this.length-1] + str;
        };
        return arr;
    };

    /*Base.extend(LineStack.prototype, {

    });*/

    var generate = function (ast, opt) {

        opt = opt || {};

        var lines = createLineStack();

        traverse(ast, lines, opt);

        return lines.join("\n");
    }

    function appendInternalFunctions(lines, internalFunctions){
        if(!internalFunctions) return;
        for(var key in internalFunctions){
            var entry = internalFunctions[key];
            if(InternalFunctions[entry.type]){
                var linesToAdd = InternalFunctions[entry.type](entry.name, entry.details);
                lines.push.apply(lines, linesToAdd);
            }
            else{
                throw Error("Internal: InlineFunction of type '" + entry.type + "' not available!");
            }
        }
    }

    function traverse(ast, lines, opt) {
        var insideMain = false;

        walk.traverse(ast, {
                enter: function (node) {
                    try {
                        var type = node.type;
                        switch (type) {

                            case Syntax.Program:
                                getHeader(opt).forEach(function (e) {
                                    lines.push(e)
                                });
                                appendInternalFunctions(lines, ANNO(ast).getUserData().internalFunctions);
                                addForwardDeclarations(lines, node);
                                break;

                            case Syntax.FunctionDeclaration:
                                opt.newLines && lines.appendLine();
                                if(node.id.name == "main")
                                    insideMain = true;

                                lines.appendLine(generateFunctionSignature(node) + " {");
                                lines.changeIndention(1);
                                return;

                            case Syntax.ReturnStatement:
                                lines.appendLine(handler.statement(node));
                                return;

                            case Syntax.VariableDeclarator :
                                // console.log("Meep!");
                                var decl = handleVariableDeclaration(node, insideMain, opt);
                                lines.appendLine(decl);
                                return;

                            case Syntax.AssignmentExpression:
                            case Syntax.ExpressionStatement:
                                lines.appendLine(handler.expression(node) + ";")
                                return VisitorOption.Skip;;

                            case Syntax.IfStatement:
                                lines.appendLine("if(" + handler.expression(node.test, opt) + ") {");

                                lines.changeIndention(1);
                                traverse(node.consequent, lines, opt);
                                lines.changeIndention(-1);

                                if (node.alternate) {
                                    lines.appendLine("} else {");
                                    lines.changeIndention(1);
                                    traverse(node.alternate, lines, opt);
                                    lines.changeIndention(-1);
                                }
                                lines.appendLine("}");
                                return VisitorOption.Skip;

                            case Syntax.ForStatement:
                                lines.appendLine("for (" + handleInlineDeclaration(node.init, opt) + "; " + handler.expression(node.test, opt) +"; " + handler.expression(node.update, opt) + ") {");
                                lines.changeIndention(1);
                                traverse(node.body, lines, opt);
                                lines.changeIndention(-1);
                                lines.appendLine("}");
                                return VisitorOption.Skip;

                            case Syntax.ContinueStatement:
                                lines.appendLine("continue;");
                                return;
                            case Syntax.BreakStatement:
                                lines.appendLine("break;");
                                return;

                            default:
                            //console.log("Unhandled: " + type);

                        }
                    } catch (e) {
                        throw e;//console.error(e);
                        //Shade.throwError(node, e.message);
                    }
                },
                leave: function (node) {
                    var type = node.type;
                    switch (type) {
                        case Syntax.Program:
                            break;
                        case Syntax.FunctionDeclaration:
                            lines.changeIndention(-1);
                            lines.appendLine("}");
                            break;
                    }
                }
            }
        );
    }

    function addForwardDeclarations(lines, node) {
        var first = true;
        walk.traverse(node, {
            enter: function(node) {
                if(node.type == Syntax.FunctionDeclaration) {
                    if(node.id.name == "main") {
                        return;
                    }
                    if (first) {
                        first = false;
                        lines.appendLine("// Forward declarations");
                    }
                    lines.appendLine(generateFunctionSignature(node)+";");
                }
            }
        });
        if(!first) {
            lines.appendLine("");
        }
    }

    function generateFunctionSignature(node) {
        var func = new FunctionAnnotation(node);
        var methodStart = [toGLSLType(func.getReturnInfo(), { allowUndefined: true })];
        methodStart.push(node.id.name, '(');
        if (!(node.params && node.params.length)) {
            methodStart.push("void");
        } else {
            var methodArgs = [];
            node.params.forEach(function (param) {
                methodArgs.push(toGLSLType(param.extra) + " " + param.name);
            })
            methodStart.push(methodArgs.join(", "));
        }
        methodStart.push(")");
        return methodStart.join(" ");
    }

    function getStaticValue(extra) {
        if (!extra || extra.staticValue === undefined) return "";
        return extra.staticValue;
    };

    function handleVariableDeclaration(node, writeStorageQualifier, opt) {
        var storageQualifier = !writeStorageQualifier ? toGLSLStorage(node.extra) : null;
        var result = storageQualifier ? storageQualifier + " " : "";
        result += toGLSLType(node.extra) + " " + node.id.name;
        if (node.extra.elements) {
            result += "[" + (node.extra.staticSize ? node.extra.staticSize : "0") + "]";
        }
        if (node.init) result += " = " + handler.expression(node.init);
        if (!node.init && storageQualifier == GLSL.Storage.CONST) {
            result += " = " + getStaticValue(node.extra);
        }
        return result + ";";
    }

    function handleInlineDeclaration(node, opt) {
        if(!node)
            return "";
        if (node.type == Syntax.VariableDeclaration) {
            var result = node.declarations.reduce(function (declString, declaration) {
                var decl = toGLSLType(declaration.extra) + " " + declaration.id.name;
                if (declaration.init) {
                    decl += " = " + handler.expression(declaration.init);
                }
                return declString + decl;
            }, "");
            return result;
        }

        // GLSL allows only declaration in init, but since this is a new scope, it should be fine
        if (node.type == Syntax.AssignmentExpression) {
            return toGLSLType(node.extra) + " " + handler.expression(node.left) + " = " + handler.expression(node.right);
        }
        Shade.throwError(node, "Internal error in GLSL::handleInlineDeclaration, found " + node.type);
    }

    exports.generate = generate;

}(exports));
<|endoftext|>


<commit_before>var generic = require('./generic');
var enums = require('../enums');
var swig = require('swig');
var async = require('async');
var utils = require('utilities');
var mode = require('../mode');

var common = require('../static/js/common');
var userController = require('./users');

var role = require('../lib/roles').user;

var trueValue;
var falseValue;
if (mode.isHeroku()) {
    trueValue = true;
    falseValue = false;
} else {
    trueValue = 1;
    falseValue = 0;
}

// View to create crisis
var createCrisis = function (req, res) {
    res.status(200);
    if (req.user){var user = req.user; }
    res.render('crisis/create', {
        page: {
            title: 'Add Crisis'
        },
        user: user
    });
}

var checkRole = role.can('create a crisis');

exports.create = [checkRole, createCrisis];

//create new crisis
var newCrisis = function (req, res) {
    // This is a POST request, so by default, fields go into the body.

    // only extra columns (apart from post) need to be written here
    var data = {

    };
    generic.create(req.models.Crisis, data, req, function (err, crisis) {
        if (!err && crisis) {
            res.redirect('/crisis/' + crisis.id);
            res.end();
        } else {
            generic.genericErrorHandler(req, res, err);
        }
    });
};
var checkRole = role.can('create a crisis');
exports.new = [checkRole, newCrisis];

// All Crises
var all = function (req, res) {
    //Redirect to crisis/1 for Challenge purposes
    res.redirect('/crisis/1');
    res.end();
}
exports.all = [role.can('view challenge pages'), all];

// Homepage
exports.index = function (req, res) {
    req.models.Crisis.find({}, 10,function (err, crises) {
        if (err) {
            generic.genericErrorHandler(req, res, err);
        } else {
            res.status(200);
            if (req.user){var user = req.user; }

            var cookieMessageSeen = true;

            if (!req.session.hasOwnProperty('cookieMessageSeen') || !req.session.cookieMessageSeen) {
                // Cookie message not seen yet.
                cookieMessageSeen = false;
                // True because they will have seen the cookie message upon this response
                // so that on next request cookieMessageSeen will return as true.
                req.session.cookieMessageSeen = true;
            }

            //res.json(crises);
            res.render('generic/index', {
                page: {

                },
                path: '/',
                crises: crises,
                user: user,
                cookieMessageSeen: cookieMessageSeen,
                info: req.flash('info'),
                error: req.flash('error')
            });
        }
    });
};

exports.about = function (req, res) {
    res.status(200);
    if (req.user){var user = req.user; }
    res.render('generic/about', {
        page: {
        },
        path: '/about',
        user: user,
        info: req.flash('info'),
        error: req.flash('error')
    });
};

exports.terms = function (req, res) {
    res.status(200);
    if (req.user){var user = req.user; }
    res.render('generic/terms', {
        page: {
        },
        path: '/terms',
        user: user,
        info: req.flash('info'),
        error: req.flash('error')
    });
};

exports.help = function (req, res) {
    res.status(200);
    if (req.user){var user = req.user; }
    res.render('generic/help', {
        page: {
        },
        path: '/help',
        user: user,
        info: req.flash('info'),
        error: req.flash('error')
    });
};

var oneCrisisResponse = function(req, res, responseData) {
    res.render('crisis/one', responseData);
}

//get a specific crisis
var getOne = function (req, res) {
    //Redirection if different than 1 for Challenge purpose
    if(req.params.crisis_id != 1){
        res.redirect('/crisis/1');
        res.end();
    }
    generic.get(req.models.Crisis, req.params.crisis_id, undefined, function (err, crisis) {

        if (!err){
            req.models.Question.find({show: trueValue}, function (err, questions) {
                // Sort questions by created date with latest first.
                questions.sort(function(a, b) {
                    return a.post.date.getTime() - b.post.date.getTime();
                });

                if (err) {
                    generic.genericErrorHandler(req, res, err);
                } else {

                    // Questions with Post data included in each question.
                    async.each(questions, generic.load_question_extra_fields, function (err) {
                        if (err) {
                            generic.genericErrorHandler(req, res, err);
                        } else {
                            crisis.post.addViewCount();
                            generic.load_crisis_extra_fields(crisis, function(err){

                                // For each question, add relative created date.
                                questions.forEach(function(question) {
                                    var relativeCreatedDate = utils.date.relativeTime(question.post.date, {abbreviated: true});
                                    question.relativeCreatedDate = relativeCreatedDate;

                                    // Canonicalise the path to the pretty format
                                    // that works well for bookmarks.
                                    question.canonicalPath = common.prettyPath({
                                        req: req,
                                        postPrefix: 'question',
                                        id: question.id,
                                        string: question.post.title
                                    });

                                })

                                var relativeCreatedDate = utils.date.relativeTime(crisis.post.date, {abbreviated: true});
                                crisis.relativeCreatedDate = relativeCreatedDate;

                                generic.generateRefCodes(4, function(refcodeArray) {
                                    var refcodes = {
                                        twitter: refcodeArray[0],
                                        facebook: refcodeArray[1],
                                        email: refcodeArray[2],
                                        link: refcodeArray[3]
                                    };

                                    var responseData = {
                                        crisis: crisis,
                                        questions: questions,
                                        page: {
                                            title: crisis.post.title
                                        },
                                        path: req.path,
                                        refcodes: refcodes,
                                        info: req.flash('info'),
                                        error: req.flash('error')
                                    };

                                    if (req.user) {
                                        responseData.user = req.user;
                                        // Respond.
                                        oneCrisisResponse(req, res, responseData);
                                    } else {
                                        // User is not currently logged in --
                                        // let's make them a provisional account
                                        // so they can immediately do stuff.
                                        userController.newProvisionalUser(req, function(err, user) {
                                            // Provisional user account created.
                                            // Respond.
                                            responseData.user = user;
                                            oneCrisisResponse(req, res, responseData);
                                        });
                                    }

                                });

                            });
                        }
                    });
                }
            });
        }
        else{
            generic.genericErrorHandler(req, res, err);
        }
    });
};

exports.get = [role.can('view challenge pages'), getOne];

// Mark crisis as Important
var markImportant = function (req, res) {
    generic.get(req.models.Crisis, req.params.crisis_id, undefined, function (err, crisis) {
        if (!err && crisis) {
            require('./ratings').importance(req, crisis.post, function(err, rating){
                generic.load_crisis_extra_fields(crisis, function(){
                    if(!err){
                        res.status(200);
                        // res.json(crisis);
                        res.end();
                    } else {
                        generic.genericErrorHandler(req, res, err);
                    }
                });
            });
        } else {
            generic.genericErrorHandler(req, res, err);
        }
    });
};
var checkRole = role.can('mark important');

exports.markImportant = [checkRole, markImportant];

// View to edit a crisis
var editCrisis = function (req, res) {
    generic.get(req.models.Crisis, req.params.crisis_id, undefined, function (err, crisis) {
        if (err) throw err;
            // No errors.
            res.status(200);

            // Goes into post object because
            // all fields are in Post and this allows
            // a generic form.
            if (req.user){var user = req.user; }
            res.render('crisis/edit', {
                crisis: crisis,
                post: crisis.post,
                page: {
                    title: 'Edit crisis'
                },
                user: user
        });
    });
}

var checkRole = role.can('edit a crisis');

exports.edit = [checkRole, editCrisis];

// Update crisis
var update = function (req, res) {
    var crisis_id = req.params.crisis_id;
    generic.get(req.models.Crisis, crisis_id, undefined, function (err, question) {
        if (!err && question) {
            generic.update(req.models.Crisis, crisis_id, req, function (err) {
                if (!err) {

                    res.redirect('/crisis/' + crisis_id);

                    res.end();
                } else {
                    generic.genericErrorHandler(req, res, err);
                }
            });
        } else {
            generic.genericErrorHandler(req, res, err);
        }

    });

};

var checkRole = role.can('edit a crisis');

exports.update = [checkRole, update];<commit_msg>Testing on heroku<commit_after>var generic = require('./generic');
var enums = require('../enums');
var swig = require('swig');
var async = require('async');
var utils = require('utilities');
var mode = require('../mode');

var common = require('../static/js/common');
var userController = require('./users');

var role = require('../lib/roles').user;

var trueValue;
var falseValue;
if (mode.isHeroku()) {
    trueValue = true;
    falseValue = false;
} else {
    trueValue = 1;
    falseValue = 0;
}

// View to create crisis
var createCrisis = function (req, res) {
    res.status(200);
    if (req.user){var user = req.user; }
    res.render('crisis/create', {
        page: {
            title: 'Add Crisis'
        },
        user: user
    });
}

var checkRole = role.can('create a crisis');

exports.create = [checkRole, createCrisis];

//create new crisis
var newCrisis = function (req, res) {
    // This is a POST request, so by default, fields go into the body.

    // only extra columns (apart from post) need to be written here
    var data = {

    };
    generic.create(req.models.Crisis, data, req, function (err, crisis) {
        if (!err && crisis) {
            res.redirect('/crisis/' + crisis.id);
            res.end();
        } else {
            generic.genericErrorHandler(req, res, err);
        }
    });
};
var checkRole = role.can('create a crisis');
exports.new = [checkRole, newCrisis];

// All Crises
var all = function (req, res) {
    //Redirect to crisis/1 for Challenge purposes
    res.redirect('/crisis/1');
    res.end();
}
exports.all = [role.can('view challenge pages'), all];

// Homepage
exports.index = function (req, res) {
    req.models.Crisis.find({}, 10,function (err, crises) {
        if (err) {
            generic.genericErrorHandler(req, res, err);
        } else {
            res.status(200);
            if (req.user){var user = req.user; }

            var cookieMessageSeen = true;

            if (!req.session.hasOwnProperty('cookieMessageSeen') || !req.session.cookieMessageSeen) {
                // Cookie message not seen yet.
                cookieMessageSeen = false;
                // True because they will have seen the cookie message upon this response
                // so that on next request cookieMessageSeen will return as true.
                req.session.cookieMessageSeen = true;
            }

            //res.json(crises);
            res.render('generic/index', {
                page: {

                },
                path: '/',
                crises: crises,
                user: user,
                cookieMessageSeen: cookieMessageSeen,
                info: req.flash('info'),
                error: req.flash('error')
            });
        }
    });
};

exports.about = function (req, res) {
    res.status(200);
    if (req.user){var user = req.user; }
    res.render('generic/about', {
        page: {
        },
        path: '/about',
        user: user,
        info: req.flash('info'),
        error: req.flash('error')
    });
};

exports.terms = function (req, res) {
    res.status(200);
    if (req.user){var user = req.user; }
    res.render('generic/terms', {
        page: {
        },
        path: '/terms',
        user: user,
        info: req.flash('info'),
        error: req.flash('error')
    });
};

exports.help = function (req, res) {
    res.status(200);
    if (req.user){var user = req.user; }
    res.render('generic/help', {
        page: {
        },
        path: '/help',
        user: user,
        info: req.flash('info'),
        error: req.flash('error')
    });
};

var oneCrisisResponse = function(req, res, responseData) {
    res.render('crisis/one', responseData);
}

//get a specific crisis
var getOne = function (req, res) {
    //Redirection if different than 1 for Challenge purpose
    if(req.params.crisis_id != 1){
        res.redirect('/crisis/1');
        res.end();
    }
    var datetime = new Date();
    console.log('-----Entered crisis-----' + datetime.getMinutes()+":"+datetime.getSeconds() );
    generic.get(req.models.Crisis, req.params.crisis_id, undefined, function (err, crisis) {

        if (!err){
            req.models.Question.find({show: trueValue}, function (err, questions) {
                // Sort questions by created date with latest first.
                questions.sort(function(a, b) {
                    return a.post.date.getTime() - b.post.date.getTime();
                });

                if (err) {
                    generic.genericErrorHandler(req, res, err);
                } else {

                    var datetime = new Date();
                    console.log('-----Question Found-----' + datetime.getMinutes()+":"+datetime.getSeconds() );
                    // Questions with Post data included in each question.
                    async.eachSeries(questions, generic.load_question_extra_fields, function (err) {
                        if (err) {
                            generic.genericErrorHandler(req, res, err);
                        } else {
                            crisis.post.addViewCount();
                            generic.load_crisis_extra_fields(crisis, function(err){

                                // For each question, add relative created date.
                                questions.forEach(function(question) {
                                    var relativeCreatedDate = utils.date.relativeTime(question.post.date, {abbreviated: true});
                                    question.relativeCreatedDate = relativeCreatedDate;

                                    // Canonicalise the path to the pretty format
                                    // that works well for bookmarks.
                                    question.canonicalPath = common.prettyPath({
                                        req: req,
                                        postPrefix: 'question',
                                        id: question.id,
                                        string: question.post.title
                                    });

                                });

                                var relativeCreatedDate = utils.date.relativeTime(crisis.post.date, {abbreviated: true});
                                crisis.relativeCreatedDate = relativeCreatedDate;

                                generic.generateRefCodes(4, function(refcodeArray) {
                                    var refcodes = {
                                        twitter: refcodeArray[0],
                                        facebook: refcodeArray[1],
                                        email: refcodeArray[2],
                                        link: refcodeArray[3]
                                    };

                                    var responseData = {
                                        crisis: crisis,
                                        questions: questions,
                                        page: {
                                            title: crisis.post.title
                                        },
                                        path: req.path,
                                        refcodes: refcodes,
                                        info: req.flash('info'),
                                        error: req.flash('error')
                                    };
                                    if (req.user) {
                                        var datetime = new Date();
                                        console.log('-----Responding crisis-----' + datetime.getMinutes()+":"+datetime.getSeconds() );
                                        responseData.user = req.user;
                                        // Respond.
                                        oneCrisisResponse(req, res, responseData);
                                    } else {
                                        // User is not currently logged in --
                                        // let's make them a provisional account
                                        // so they can immediately do stuff.
                                        userController.newProvisionalUser(req, function(err, user) {
                                            // Provisional user account created.
                                            // Respond.
                                            responseData.user = user;
                                            oneCrisisResponse(req, res, responseData);
                                        });
                                    }

                                });

                            });
                        }
                    });
                }
            });
        }
        else{
            generic.genericErrorHandler(req, res, err);
        }
    });
};

exports.get = [role.can('view challenge pages'), getOne];

// Mark crisis as Important
var markImportant = function (req, res) {
    generic.get(req.models.Crisis, req.params.crisis_id, undefined, function (err, crisis) {
        if (!err && crisis) {
            require('./ratings').importance(req, crisis.post, function(err, rating){
                generic.load_crisis_extra_fields(crisis, function(){
                    if(!err){
                        res.status(200);
                        // res.json(crisis);
                        res.end();
                    } else {
                        generic.genericErrorHandler(req, res, err);
                    }
                });
            });
        } else {
            generic.genericErrorHandler(req, res, err);
        }
    });
};
var checkRole = role.can('mark important');

exports.markImportant = [checkRole, markImportant];

// View to edit a crisis
var editCrisis = function (req, res) {
    generic.get(req.models.Crisis, req.params.crisis_id, undefined, function (err, crisis) {
        if (err) throw err;
            // No errors.
            res.status(200);

            // Goes into post object because
            // all fields are in Post and this allows
            // a generic form.
            if (req.user){var user = req.user; }
            res.render('crisis/edit', {
                crisis: crisis,
                post: crisis.post,
                page: {
                    title: 'Edit crisis'
                },
                user: user
        });
    });
}

var checkRole = role.can('edit a crisis');

exports.edit = [checkRole, editCrisis];

// Update crisis
var update = function (req, res) {
    var crisis_id = req.params.crisis_id;
    generic.get(req.models.Crisis, crisis_id, undefined, function (err, question) {
        if (!err && question) {
            generic.update(req.models.Crisis, crisis_id, req, function (err) {
                if (!err) {

                    res.redirect('/crisis/' + crisis_id);

                    res.end();
                } else {
                    generic.genericErrorHandler(req, res, err);
                }
            });
        } else {
            generic.genericErrorHandler(req, res, err);
        }

    });

};

var checkRole = role.can('edit a crisis');

exports.update = [checkRole, update];<|endoftext|>


<commit_before>// Please use HTTPs on non-localhost domains.
var isUseHTTPs = false && !(!!process.env.PORT || !!process.env.IP);

// user-guide: change port via "config.json"
var port = process.env.PORT || 9001;

var autoRebootServerOnFailure = false;

try {
    var config = require('./config.json');

    if ((config.port || '').toString() !== '9001') {
        port = parseInt(config.port);
    }

    if ((config.autoRebootServerOnFailure || '').toString() !== true) {
        autoRebootServerOnFailure = true;
    }
} catch (e) {}

var server = require(isUseHTTPs ? 'https' : 'http'),
    url = require('url'),
    path = require('path'),
    fs = require('fs');

function serverHandler(request, response) {
    try {
        var uri = url.parse(request.url).pathname,
            filename = path.join(process.cwd(), uri);

        if (filename && filename.search(/server.js|Scalable-Broadcast.js|Signaling-Server.js/g) !== -1) {
            response.writeHead(404, {
                'Content-Type': 'text/plain'
            });
            response.write('404 Not Found: ' + path.join('/', uri) + '\n');
            response.end();
            return;
        }

        var stats;

        try {
            stats = fs.lstatSync(filename);

            if (filename && filename.search(/demos/g) === -1 && stats.isDirectory()) {
                response.writeHead(200, {
                    'Content-Type': 'text/html'
                });
                response.write('<!DOCTYPE html><meta http-equiv="refresh" content="0;url=/demos/">');
                response.end();
                return;
            }
        } catch (e) {
            response.writeHead(404, {
                'Content-Type': 'text/plain'
            });
            response.write('404 Not Found: ' + path.join('/', uri) + '\n');
            response.end();
            return;
        }

        if (fs.statSync(filename).isDirectory()) {
            response.writeHead(404, {
                'Content-Type': 'text/html'
            });

            if (filename.indexOf('/demos/MultiRTC/') !== -1) {
                filename = filename.replace('/demos/MultiRTC/', '');
                filename += '/demos/MultiRTC/index.html';
            } else if (filename.indexOf('/demos/') !== -1) {
                filename = filename.replace('/demos/', '');
                filename += '/demos/index.html';
            } else {
                filename += '/demos/index.html';
            }
        }

        fs.readFile(filename, 'utf8', function(err, file) {
            if (err) {
                response.writeHead(500, {
                    'Content-Type': 'text/plain'
                });
                response.write('404 Not Found: ' + path.join('/', uri) + '\n');
                response.end();
                return;
            }

            try {
                var demos = (fs.readdirSync('demos') || []);

                if (demos.length) {
                    var h2 = '

';
                    var otherDemos = '
Check ' + (demos.length - 1) + ' other RTCMultiConnection-v3 demos' + h2 + '
';
                    demos.forEach(function(f) {
                        if (f && f !== 'index.html' && f.indexOf('.html') !== -1) {
                            otherDemos += '
' + f + ' (Source)
';
                        }
                    });
                    otherDemos += '

';

                    file = file.replace('
', otherDemos);
                }
            } catch (e) {}

            try {
                var docs = (fs.readdirSync('docs') || []);

                if (docs.length) {
                    var html = '
';
                    html += 'RTCMultiConnection Docs';
                    html += '
http://www.rtcmulticonnection.org/docs/
';
                    html += '
';

                    docs.forEach(function(f) {
                        if (f.indexOf('DS_Store') == -1) {
                            html += '
' + f + '
';
                        }
                    });

                    html += '

';

                    file = file.replace('
', html);
                }
            } catch (e) {}

            response.writeHead(200);
            response.write(file, 'utf8');
            response.end();
        });
    } catch (e) {
        response.writeHead(404, {
            'Content-Type': 'text/plain'
        });
        response.write('
Unexpected error:

' + e.stack || e.message || JSON.stringify(e));
        response.end();
    }
}

var app;

if (isUseHTTPs) {
    var options = {
        key: fs.readFileSync(path.join(__dirname, 'fake-keys/privatekey.pem')),
        cert: fs.readFileSync(path.join(__dirname, 'fake-keys/certificate.pem'))
    };
    app = server.createServer(options, serverHandler);
} else app = server.createServer(serverHandler);

function runServer() {
    app = app.listen(port, process.env.IP || '0.0.0.0', function() {
        var addr = app.address();

        if (addr.address === '0.0.0.0') {
            addr.address = 'localhost';
        }

        console.log('Server listening at ' + (isUseHTTPs ? 'https' : 'http') + '://' + addr.address + ':' + addr.port);
    });

    require('./Signaling-Server.js')(app, function(socket) {
        try {
            var params = socket.handshake.query;

            // "socket" object is totally in your own hands!
            // do whatever you want!

            // in your HTML page, you can access socket as following:
            // connection.socketCustomEvent = 'custom-message';
            // var socket = connection.getSocket();
            // socket.emit(connection.socketCustomEvent, { test: true });

            if (!params.socketCustomEvent) {
                params.socketCustomEvent = 'custom-message';
            }

            socket.on(params.socketCustomEvent, function(message) {
                try {
                    socket.broadcast.emit(params.socketCustomEvent, message);
                } catch (e) {}
            });
        } catch (e) {}
    });
}

if (autoRebootServerOnFailure) {
    // auto restart app on failure
    var cluster = require('cluster');
    if (cluster.isMaster) {
        cluster.fork();

        cluster.on('exit', function(worker, code, signal) {
            cluster.fork();
        });
    }

    if (cluster.isWorker) {
        runServer();
    }
} else {
    runServer();
}
<commit_msg>removed demos folder<commit_after>// Please use HTTPs on non-localhost domains.
var isUseHTTPs = false && !(!!process.env.PORT || !!process.env.IP);

// user-guide: change port via "config.json"
var port = process.env.PORT || 9001;

var autoRebootServerOnFailure = false;

try {
    var config = require('./config.json');

    if ((config.port || '').toString() !== '9001') {
        port = parseInt(config.port);
    }

    if ((config.autoRebootServerOnFailure || '').toString() !== true) {
        autoRebootServerOnFailure = true;
    }
} catch (e) {}

var server = require(isUseHTTPs ? 'https' : 'http'),
    url = require('url'),
    path = require('path'),
    fs = require('fs');

function serverHandler(request, response) {
    try {
        var uri = url.parse(request.url).pathname,
            filename = path.join(process.cwd(), uri);

        if (filename && filename.search(/server.js|Scalable-Broadcast.js|Signaling-Server.js/g) !== -1) {
            response.writeHead(404, {
                'Content-Type': 'text/plain'
            });
            response.write('404 Not Found: ' + path.join('/', uri) + '\n');
            response.end();
            return;
        }

        var stats;

        try {
            stats = fs.lstatSync(filename);

            if (filename && filename.search(/demos/g) === -1 && stats.isDirectory()) {
                response.writeHead(200, {
                    'Content-Type': 'text/html'
                });
                response.write('<!DOCTYPE html><meta http-equiv="refresh" content="0;url=Video-Conferencing.html">');
                response.end();
                return;
            }
        } catch (e) {
            response.writeHead(404, {
                'Content-Type': 'text/plain'
            });
            response.write('404 Not Found: ' + path.join('/', uri) + '\n');
            response.end();
            return;
        }

        if (fs.statSync(filename).isDirectory()) {
            response.writeHead(404, {
                'Content-Type': 'text/html'
            });

            if (filename.indexOf('/demos/MultiRTC/') !== -1) {
                filename = filename.replace('/demos/MultiRTC/', '');
                filename += 'Video-Conferencing.html';
            } else if (filename.indexOf('/demos/') !== -1) {
                filename = filename.replace('/demos/', '');
                filename += 'Video-Conferencing.html';
            } else {
                filename += 'Video-Conferencing.html';
            }
        }

        fs.readFile(filename, 'utf8', function(err, file) {
            if (err) {
                response.writeHead(500, {
                    'Content-Type': 'text/plain'
                });
                response.write('404 Not Found: ' + path.join('/', uri) + '\n');
                response.end();
                return;
            }

            try {
                var demos = (fs.readdirSync('demos') || []);

                if (demos.length) {
                    var h2 = '

';
                    var otherDemos = '
Check ' + (demos.length - 1) + ' other RTCMultiConnection-v3 demos' + h2 + '
';
                    demos.forEach(function(f) {
                        if (f && f !== 'index.html' && f.indexOf('.html') !== -1) {
                            otherDemos += '
' + f + ' (Source)
';
                        }
                    });
                    otherDemos += '

';

                    file = file.replace('
', otherDemos);
                }
            } catch (e) {}

            try {
                var docs = (fs.readdirSync('docs') || []);

                if (docs.length) {
                    var html = '
';
                    html += 'RTCMultiConnection Docs';
                    html += '
http://www.rtcmulticonnection.org/docs/
';
                    html += '
';

                    docs.forEach(function(f) {
                        if (f.indexOf('DS_Store') == -1) {
                            html += '
' + f + '
';
                        }
                    });

                    html += '

';

                    file = file.replace('
', html);
                }
            } catch (e) {}

            response.writeHead(200);
            response.write(file, 'utf8');
            response.end();
        });
    } catch (e) {
        response.writeHead(404, {
            'Content-Type': 'text/plain'
        });
        response.write('
Unexpected error:

' + e.stack || e.message || JSON.stringify(e));
        response.end();
    }
}

var app;

if (isUseHTTPs) {
    var options = {
        key: fs.readFileSync(path.join(__dirname, 'fake-keys/privatekey.pem')),
        cert: fs.readFileSync(path.join(__dirname, 'fake-keys/certificate.pem'))
    };
    app = server.createServer(options, serverHandler);
} else app = server.createServer(serverHandler);

function runServer() {
    app = app.listen(port, process.env.IP || '0.0.0.0', function() {
        var addr = app.address();

        if (addr.address === '0.0.0.0') {
            addr.address = 'localhost';
        }

        console.log('Server listening at ' + (isUseHTTPs ? 'https' : 'http') + '://' + addr.address + ':' + addr.port);
    });

    require('./Signaling-Server.js')(app, function(socket) {
        try {
            var params = socket.handshake.query;

            // "socket" object is totally in your own hands!
            // do whatever you want!

            // in your HTML page, you can access socket as following:
            // connection.socketCustomEvent = 'custom-message';
            // var socket = connection.getSocket();
            // socket.emit(connection.socketCustomEvent, { test: true });

            if (!params.socketCustomEvent) {
                params.socketCustomEvent = 'custom-message';
            }

            socket.on(params.socketCustomEvent, function(message) {
                try {
                    socket.broadcast.emit(params.socketCustomEvent, message);
                } catch (e) {}
            });
        } catch (e) {}
    });
}

if (autoRebootServerOnFailure) {
    // auto restart app on failure
    var cluster = require('cluster');
    if (cluster.isMaster) {
        cluster.fork();

        cluster.on('exit', function(worker, code, signal) {
            cluster.fork();
        });
    }

    if (cluster.isWorker) {
        runServer();
    }
} else {
    runServer();
}
<|endoftext|>