<commit_before>/*!
Copyright 2013 ASTEA

Licensed under the New BSD license. You may not use this file except in
compliance with this License.

You may obtain a copy of the License at
https://github.com/gpii/universal/LICENSE.txt
*/

// Declare dependencies
/*global fluid, jqUnit, expect, jQuery*/

// JSLint options
/*jslint white: true, funcinvoke: true, undef: true, newcap: true, nomen: true, regexp: true, bitwise: true, browser: true, forin: true, maxerr: 100, indent: 4 */

(function ($) {
    fluid.registerNamespace("gpii.prefs.gpiiStore.tests");

    jqUnit.module("GPIIStore Tests");

    var store = gpii.prefs.gpiiStore();

    var userToWorkWith = "sammy";
    var userToBeCreated = "userThatJustHasBeenCreated";

    var exampleModel = '{"gpii_primarySchema_volume":80,' +
                        '"gpii_primarySchema_keyEcho":false,' +
                        '"gpii_primarySchema_wordEcho":false,' +
                        '"gpii_primarySchema_fontSize":12,' +
                        '"gpii_primarySchema_speakText":false,' +
                        '"gpii_primarySchema_voicePitch":80,' +
                        '"gpii_primarySchema_cursorSize":1,' +
                        '"gpii_primarySchema_magnification":100,' +
                        '"gpii_primarySchema_contrast_theme":"black-white",' +
                        '"gpii_primarySchema_showCrosshairs":false,' +
                        '"gpii_primarySchema_universalVolume":80,' +
                        '"gpii_primarySchema_contrastEnabled":false,' +
                        '"gpii_primarySchema_announceCapitals":false,' +
                        '"gpii_primarySchema_textHighlighting":"Word",' +
                        '"gpii_primarySchema_magnifierEnabled":false,' +
                        '"gpii_primarySchema_universalLanguage":"en",' +
                        '"gpii_primarySchema_punctuationVerbosity":"none",' +
                        '"gpii_primarySchema_screenReaderLanguage":"en",' +
                        '"gpii_primarySchema_wordsSpokenPerMinute":130,' +
                        '"gpii_primarySchema_speakTutorialMessages":false,' +
                        '"gpii_primarySchema_magnificationPosition":"TopHalf",' +
                        '"gpii_primarySchema_screenReaderBrailleOutput":false}';

    var convertedExampleModel = '{"http://registry.gpii.org/common/pitch":[{"value":0.8}],' +
                                 '"http://registry.gpii.org/common/volume":[{"value":0.8}],' +
                                 '"http://registry.gpii.org/common/keyEcho":[{"value":false}],' +
                                 '"http://registry.gpii.org/common/language":[{"value":"en"}],' +
                                 '"http://registry.gpii.org/common/wordEcho":[{"value":false}],' +
                                 '"http://registry.gpii.org/common/fontSize":[{"value":12}],' +
                                 '"http://registry.gpii.org/common/volumeTTS":[{"value":0.8}],' +
                                 '"http://registry.gpii.org/common/speechRate":[{"value":130}],' +
                                 '"http://registry.gpii.org/common/cursorSize":[{"value":0.2}],' +
                                 '"http://registry.gpii.org/common/readingUnit":[{"value":"Word"}],' +
                                 '"http://registry.gpii.org/common/magnification":[{"value":1}],' +
                                 '"http://registry.gpii.org/common/showCrosshairs":[{"value":false}],' +
                                 '"http://registry.gpii.org/common/announceCapitals":[{"value":false}],' +
                                 '"http://registry.gpii.org/common/magnifierEnabled":[{"value":false}],' +
                                 '"http://registry.gpii.org/common/highContrastTheme":[{"value":"black-white"}],' +
                                 '"http://registry.gpii.org/common/magnifierPosition":[{"value":"TopHalf"}],' +
                                 '"http://registry.gpii.org/common/auditoryOutLanguage":[{"value":"en"}],' +
                                 '"http://registry.gpii.org/common/highContrastEnabled":[{"value":false}],' +
                                 '"http://registry.gpii.org/common/punctuationVerbosity":[{"value":"none"}],' +
                                 '"http://registry.gpii.org/common/speakTutorialMessages":[{"value":false}],' +
                                 '"http://registry.gpii.org/common/screenReaderTTSEnabled":[{"value":false}],' +
                                 '"http://registry.gpii.org/common/screenReaderBrailleOutput":[{"value":false}]}';

    var loginSuccessMockSettings =
    {
        url: store.gpiiSession.options.url + "user/" + userToWorkWith + "/login",
        responseText: "User with token " + userToWorkWith + " was successfully logged in."
    };

    var loginSuccessNewUserMockSettings =
    {
        url: store.gpiiSession.options.url + "user/" + userToBeCreated + "/login",
        responseText: "User with token " + userToBeCreated + " was successfully logged in."
    };

    var getRequestMockSettings =
    {
        url: store.gpiiSession.options.url + "user/" + userToWorkWith,
        dataType: "json"
    };

    var setRequestNoUserMockSettings =
    {
        url: store.gpiiSession.options.url + "user/",
        dataType: "json",
        responseText: {
            "token": userToBeCreated
        }
    };

    var setRequestUserLoggedMockSettings =
    {
        url: store.gpiiSession.options.url + "user/" + userToWorkWith,
        dataType: "json",
        responseText: {
            "token": userToWorkWith
        }
    };

    gpii.prefs.gpiiStore.tests.assertNotUndefined = function () {
        jqUnit.assertValue("Object should not be null or undefined.", store);
    };

    gpii.prefs.gpiiStore.tests.assertModeflTransofrmation = function () {
        var exampleModelObject = JSON.parse(exampleModel);
        var transformedExampleModel = store.modelTransform(exampleModelObject, gpii.prefs.commonTermsTransformationRules);
        var stringifiedExampleObject = JSON.stringify(transformedExampleModel); // Comparing stringified objects, since JSON.parse(JSON.stringify(obj)) != obj

        jqUnit.assertEquals("Transforming the model from schema to http://registry.gpii.org/common/...", stringifiedExampleObject, convertedExampleModel);
    };

    gpii.prefs.gpiiStore.tests.assertInvertedModeflTransofrmation = function () {
        var exampleTransformedObject = JSON.parse(convertedExampleModel);
        var inverseTransformedExampleModel = store.inverseModelTransform(exampleTransformedObject, gpii.prefs.commonTermsInverseTransformationRules);
        var stringifiedExampleObject = JSON.stringify(inverseTransformedExampleModel);

        jqUnit.assertEquals("Transforming the model from http://registry.gpii.org/common/... to schema-like", stringifiedExampleObject, exampleModel);
    };

    gpii.prefs.gpiiStore.tests.assertGetInvokerNoLoggedUser = function () {
        var gpiiModel = store.get();

        jqUnit.assertNoValue("Settings object is undefined when no user is logged.", gpiiModel);
    };

    gpii.prefs.gpiiStore.tests.assertGetSettingsFromLoggedUser = function () {
        var keys = ["keyEcho", "wordEcho", "fontSize", "tracking", "speakText", "contrast_theme", "showCrosshairs", "contrastEnabled", "announceCapitals", "textHighlighting", "magnifierEnabled", "universalLanguage", "punctuationVerbosity", "screenReaderLanguage", "wordsSpokenPerMinute", "screenReaderTracking", "speakTutorialMessages", "magnificationPosition", "screenReaderBrailleOutput"];
        var modelKeys = [];

        fluid.each(keys, function (key) {
            modelKeys.push("gpii_primarySchema_" + key);
        });

        store.gpiiSession.login(userToWorkWith);
        var gpiiModel = store.get();

        jqUnit.assertEquals("Checking if the GET invoker successfully calls the transform function.", JSON.stringify(Object.keys(gpiiModel)), JSON.stringify(modelKeys));
    };

    gpii.prefs.gpiiStore.tests.assertSetInvokerNoLoggedUser = function () {
        store.set();

        jqUnit.assertValue("Set creates token.", store.gpiiSession.options.loggedUser);
    };

    gpii.prefs.gpiiStore.tests.assertSetInvokerUserLogged = function () {
        store.gpiiSession.login(userToWorkWith);
        store.set();

        jqUnit.assertEquals("Checking if after set the same user is logged.", store.gpiiSession.options.loggedUser, userToWorkWith);
    }

    gpii.prefs.gpiiStore.tests.mockTest = function (testTitle, assertFunction, enabledMockSettings) {
        jqUnit.test(testTitle, function () {
            $.mockjaxClear();
            fluid.each(enabledMockSettings, $.mockjax);
            assertFunction();
            $.mockjaxClear();
        });
    };

    gpii.prefs.gpiiStore.tests.mockTest("Object not undefined.", gpii.prefs.gpiiStore.tests.assertNotUndefined);
    gpii.prefs.gpiiStore.tests.mockTest("Model transformation check.", gpii.prefs.gpiiStore.tests.assertModeflTransofrmation);
    gpii.prefs.gpiiStore.tests.mockTest("Inverted model transformation check.", gpii.prefs.gpiiStore.tests.assertInvertedModeflTransofrmation);
    gpii.prefs.gpiiStore.tests.mockTest("Set when no user is logged.", gpii.prefs.gpiiStore.tests.assertSetInvokerNoLoggedUser, [setRequestNoUserMockSettings, loginSuccessNewUserMockSettings]);
    gpii.prefs.gpiiStore.tests.mockTest("Set when user is already logged.", gpii.prefs.gpiiStore.tests.assertSetInvokerUserLogged, [loginSuccessMockSettings, setRequestUserLoggedMockSettings]);
    gpii.prefs.gpiiStore.tests.mockTest("Get when no user is logged.", gpii.prefs.gpiiStore.tests.assertGetInvokerNoLoggedUser);
    gpii.prefs.gpiiStore.tests.mockTest("Get when user is logged.", gpii.prefs.gpiiStore.tests.assertGetSettingsFromLoggedUser, [loginSuccessMockSettings, getRequestMockSettings]);

})(jQuery);
<commit_msg>GPII-663: Example model is now object, rather than string.<commit_after>/*!
Copyright 2013 ASTEA

Licensed under the New BSD license. You may not use this file except in
compliance with this License.

You may obtain a copy of the License at
https://github.com/gpii/universal/LICENSE.txt
*/

// Declare dependencies
/*global fluid, jqUnit, expect, jQuery*/

// JSLint options
/*jslint white: true, funcinvoke: true, undef: true, newcap: true, nomen: true, regexp: true, bitwise: true, browser: true, forin: true, maxerr: 100, indent: 4 */

(function ($) {
    fluid.registerNamespace("gpii.prefs.gpiiStore.tests");

    jqUnit.module("GPIIStore Tests");

    var store = gpii.prefs.gpiiStore();

    var userToWorkWith = "sammy";
    var userToBeCreated = "userThatJustHasBeenCreated";

     convertedExampleModel = '{"http://registry.gpii.org/common/pitch":[{"value":0.8}],' +
                                 '"http://registry.gpii.org/common/volume":[{"value":0.8}],' +
                                 '"http://registry.gpii.org/common/keyEcho":[{"value":false}],' +
                                 '"http://registry.gpii.org/common/language":[{"value":"en"}],' +
                                 '"http://registry.gpii.org/common/wordEcho":[{"value":false}],' +
                                 '"http://registry.gpii.org/common/fontSize":[{"value":12}],' +
                                 '"http://registry.gpii.org/common/volumeTTS":[{"value":0.8}],' +
                                 '"http://registry.gpii.org/common/speechRate":[{"value":130}],' +
                                 '"http://registry.gpii.org/common/cursorSize":[{"value":0.2}],' +
                                 '"http://registry.gpii.org/common/readingUnit":[{"value":"Word"}],' +
                                 '"http://registry.gpii.org/common/magnification":[{"value":1}],' +
                                 '"http://registry.gpii.org/common/showCrosshairs":[{"value":false}],' +
                                 '"http://registry.gpii.org/common/announceCapitals":[{"value":false}],' +
                                 '"http://registry.gpii.org/common/magnifierEnabled":[{"value":false}],' +
                                 '"http://registry.gpii.org/common/highContrastTheme":[{"value":"black-white"}],' +
                                 '"http://registry.gpii.org/common/magnifierPosition":[{"value":"TopHalf"}],' +
                                 '"http://registry.gpii.org/common/auditoryOutLanguage":[{"value":"en"}],' +
                                 '"http://registry.gpii.org/common/highContrastEnabled":[{"value":false}],' +
                                 '"http://registry.gpii.org/common/punctuationVerbosity":[{"value":"none"}],' +
                                 '"http://registry.gpii.org/common/speakTutorialMessages":[{"value":false}],' +
                                 '"http://registry.gpii.org/common/screenReaderTTSEnabled":[{"value":false}],' +
                                 '"http://registry.gpii.org/common/screenReaderBrailleOutput":[{"value":false}]}';

 var exampleModel = {"gpii_primarySchema_volume": 80, "gpii_primarySchema_keyEcho": false, "gpii_primarySchema_wordEcho": false,
                     "gpii_primarySchema_fontSize": 12, "gpii_primarySchema_speakText": false, "gpii_primarySchema_voicePitch": 80,
                     "gpii_primarySchema_cursorSize": 1, "gpii_primarySchema_magnification": 100, "gpii_primarySchema_contrast_theme": "black-white",
                     "gpii_primarySchema_showCrosshairs": false, "gpii_primarySchema_universalVolume": 80, "gpii_primarySchema_contrastEnabled": false,
                     "gpii_primarySchema_announceCapitals": false, "gpii_primarySchema_textHighlighting": "Word",
                     "gpii_primarySchema_magnifierEnabled": false, "gpii_primarySchema_universalLanguage": "en",
                     "gpii_primarySchema_punctuationVerbosity": "none", "gpii_primarySchema_screenReaderLanguage": "en",
                     "gpii_primarySchema_wordsSpokenPerMinute": 130, "gpii_primarySchema_speakTutorialMessages": false,
                     "gpii_primarySchema_magnificationPosition": "TopHalf", "gpii_primarySchema_screenReaderBrailleOutput": false};

    var loginSuccessMockSettings =
    {
        url: store.gpiiSession.options.url + "user/" + userToWorkWith + "/login",
        responseText: "User with token " + userToWorkWith + " was successfully logged in."
    };

    var loginSuccessNewUserMockSettings =
    {
        url: store.gpiiSession.options.url + "user/" + userToBeCreated + "/login",
        responseText: "User with token " + userToBeCreated + " was successfully logged in."
    };

    var getRequestMockSettings =
    {
        url: store.gpiiSession.options.url + "user/" + userToWorkWith,
        dataType: "json"
    };

    var setRequestNoUserMockSettings =
    {
        url: store.gpiiSession.options.url + "user/",
        dataType: "json",
        responseText: {
            "token": userToBeCreated
        }
    };

    var setRequestUserLoggedMockSettings =
    {
        url: store.gpiiSession.options.url + "user/" + userToWorkWith,
        dataType: "json",
        responseText: {
            "token": userToWorkWith
        }
    };

    gpii.prefs.gpiiStore.tests.assertNotUndefined = function () {
        jqUnit.assertValue("Object should not be null or undefined.", store);
    };

    gpii.prefs.gpiiStore.tests.assertModeflTransofrmation = function () {
        var transformedExampleModel = store.modelTransform(exampleModel, gpii.prefs.commonTermsTransformationRules);
        var stringifiedExampleObject = JSON.stringify(transformedExampleModel); // Comparing stringified objects, since JSON.parse(JSON.stringify(obj)) != obj

        jqUnit.assertEquals("Transforming the model from schema to http://registry.gpii.org/common/...", stringifiedExampleObject, convertedExampleModel);
    };

    gpii.prefs.gpiiStore.tests.assertInvertedModeflTransofrmation = function () {
        var exampleTransformedObject = JSON.parse(convertedExampleModel);
        var inverseTransformedExampleModel = store.inverseModelTransform(exampleTransformedObject, gpii.prefs.commonTermsInverseTransformationRules);
        var stringifiedExampleObject = JSON.stringify(inverseTransformedExampleModel);

        jqUnit.assertEquals("Transforming the model from http://registry.gpii.org/common/... to schema-like", stringifiedExampleObject, JSON.stringify(exampleModel));
    };

    gpii.prefs.gpiiStore.tests.assertGetInvokerNoLoggedUser = function () {
        var gpiiModel = store.get();

        jqUnit.assertNoValue("Settings object is undefined when no user is logged.", gpiiModel);
    };

    gpii.prefs.gpiiStore.tests.assertGetSettingsFromLoggedUser = function () {
        var keys = ["keyEcho", "wordEcho", "fontSize", "tracking", "speakText", "contrast_theme", "showCrosshairs", "contrastEnabled", "announceCapitals", "textHighlighting", "magnifierEnabled", "universalLanguage", "punctuationVerbosity", "screenReaderLanguage", "wordsSpokenPerMinute", "screenReaderTracking", "speakTutorialMessages", "magnificationPosition", "screenReaderBrailleOutput"];
        var modelKeys = [];

        fluid.each(keys, function (key) {
            modelKeys.push("gpii_primarySchema_" + key);
        });

        store.gpiiSession.login(userToWorkWith);
        var gpiiModel = store.get();

        jqUnit.assertEquals("Checking if the GET invoker successfully calls the transform function.", JSON.stringify(Object.keys(gpiiModel)), JSON.stringify(modelKeys));
    };

    gpii.prefs.gpiiStore.tests.assertSetInvokerNoLoggedUser = function () {
        store.set();

        jqUnit.assertValue("Set creates token.", store.gpiiSession.options.loggedUser);
    };

    gpii.prefs.gpiiStore.tests.assertSetInvokerUserLogged = function () {
        store.gpiiSession.login(userToWorkWith);
        store.set();

        jqUnit.assertEquals("Checking if after set the same user is logged.", store.gpiiSession.options.loggedUser, userToWorkWith);
    };

    gpii.prefs.gpiiStore.tests.mockTest = function (testTitle, assertFunction, enabledMockSettings) {
        jqUnit.test(testTitle, function () {
            $.mockjaxClear();
            fluid.each(enabledMockSettings, $.mockjax);
            assertFunction();
            $.mockjaxClear();
        });
    };

    gpii.prefs.gpiiStore.tests.mockTest("Object not undefined.", gpii.prefs.gpiiStore.tests.assertNotUndefined);
    gpii.prefs.gpiiStore.tests.mockTest("Model transformation check.", gpii.prefs.gpiiStore.tests.assertModeflTransofrmation);
    gpii.prefs.gpiiStore.tests.mockTest("Inverted model transformation check.", gpii.prefs.gpiiStore.tests.assertInvertedModeflTransofrmation);
    gpii.prefs.gpiiStore.tests.mockTest("Set when no user is logged.", gpii.prefs.gpiiStore.tests.assertSetInvokerNoLoggedUser, [setRequestNoUserMockSettings, loginSuccessNewUserMockSettings]);
    gpii.prefs.gpiiStore.tests.mockTest("Set when user is already logged.", gpii.prefs.gpiiStore.tests.assertSetInvokerUserLogged, [loginSuccessMockSettings, setRequestUserLoggedMockSettings]);
    gpii.prefs.gpiiStore.tests.mockTest("Get when no user is logged.", gpii.prefs.gpiiStore.tests.assertGetInvokerNoLoggedUser);
    gpii.prefs.gpiiStore.tests.mockTest("Get when user is logged.", gpii.prefs.gpiiStore.tests.assertGetSettingsFromLoggedUser, [loginSuccessMockSettings, getRequestMockSettings]);

})(jQuery);
<|endoftext|>


<commit_before>exports.getSignUp = (req, res, next) => {
    if (req.user) return res.redirect("/");
    return req.responseFactory.sendRenderedResponse("public/signup", req, res, { captcha: req.place.enableCaptcha });
}

exports.postSignUp = (req, res, next) => {
    function renderResponse(errorMsg) {
        return req.responseFactory.sendRenderedResponse("public/signup", req, res, { captcha: req.place.enableCaptcha, error: { message: errorMsg || "An unknown error occurred" }, username: req.body.username });
    }
    var redirectURL = typeof req.query.redirectURL !== 'undefined' ? req.query.redirectURL : null;
    function doSignup() {
        User.register(req.body.username, req.body.password, function(user, error) {
            if(!user) return renderResponse(error.message);
            req.login(user, function(err) {
                if (err) return renderResponse(null);
                return res.redirect(`/${(redirectURL == "/" ? "" : redirectURL) || ""}`);
            });
        });
    }
    if (req.user) return res.redirect("/");
    fs.exists(__dirname + "/../config/community_guidelines.md", exists => {
        if (!req.body.username || !req.body.password || !req.body.passwordverify) return renderResponse("Please fill out all the fields.")
        if (req.body.password != req.body.passwordverify) return renderResponse("The passwords you entered did not match.");
        if (!req.body.agreeToGuidelines && exists) return renderResponse("You must agree to the community guidelines to use this service.");
        if(req.place.enableCaptcha) {
            req.place.recaptcha.verify(req, error => {
                if(error) return renderResponse("Please fill in the captcha properly.");
                doSignup();
            });
        } else doSignup();
    });
}<commit_msg>another hotfix<commit_after>const fs = require("fs");

exports.getSignUp = (req, res, next) => {
    if (req.user) return res.redirect("/");
    return req.responseFactory.sendRenderedResponse("public/signup", req, res, { captcha: req.place.enableCaptcha });
}

exports.postSignUp = (req, res, next) => {
    function renderResponse(errorMsg) {
        return req.responseFactory.sendRenderedResponse("public/signup", req, res, { captcha: req.place.enableCaptcha, error: { message: errorMsg || "An unknown error occurred" }, username: req.body.username });
    }
    var redirectURL = typeof req.query.redirectURL !== 'undefined' ? req.query.redirectURL : null;
    function doSignup() {
        User.register(req.body.username, req.body.password, function(user, error) {
            if(!user) return renderResponse(error.message);
            req.login(user, function(err) {
                if (err) return renderResponse(null);
                return res.redirect(`/${(redirectURL == "/" ? "" : redirectURL) || ""}`);
            });
        });
    }
    if (req.user) return res.redirect("/");
    fs.exists(__dirname + "/../config/community_guidelines.md", exists => {
        if (!req.body.username || !req.body.password || !req.body.passwordverify) return renderResponse("Please fill out all the fields.")
        if (req.body.password != req.body.passwordverify) return renderResponse("The passwords you entered did not match.");
        if (!req.body.agreeToGuidelines && exists) return renderResponse("You must agree to the community guidelines to use this service.");
        if(req.place.enableCaptcha) {
            req.place.recaptcha.verify(req, error => {
                if(error) return renderResponse("Please fill in the captcha properly.");
                doSignup();
            });
        } else doSignup();
    });
}<|endoftext|>


<commit_before>// The Review controller

var mongoose = require('mongoose');
var Review = require('../models/reviewModel.js');
var Business = require('../models/businessModel.js');
var User = require('../models/userModel.js');

/**
 * Creates a new Review from the data request
 * @param {Object} req HTTP request object.
 * @param {Object} res HTTP response object.
 */
exports.createNewReview = function(req, res) {

    console.log('POST - /review');

    if (!req.user) {
        res.statusCode = 403;
        console.log('User not logged in, unauthorized',res.statusCode);
        return res.send({ error: 'User not logged in, unauthorized' });
    }

    var errors = [];
    var userId = req.body.userId;
    var businessId = req.body.businessId;
    var content = req.body.content;

    // validate the user exists
    var user = User.findOne({ "_id": userId }, function (err, user) {
        if (err) {
            var errorMsg = "Could not add the review. No user found with id: " + userId;
            console.log(errorMsg);
            errors.push(errorMsg);
        }
        if (user) {
            // validate the business exists

            var business = Business.findOne({ "_id": businessId }, function (err, business) {
                if (err) {
                    var errorMsg = "Could not add the review. No business found with id: " + businessId;
                    console.log(errorMsg);
                    errors.push(errorMsg);
                }

                if (business) {
                    // save the new review
                    var reviewModel = new Review();
                    reviewModel.userId = userId;
                    reviewModel.businessId = mongoose.Types.ObjectId(businessId);
                    reviewModel.content = content;
                    reviewModel.date = new Date();
                    reviewModel.save(function(err) {

                        if(err) {
                            console.log('Error while saving review: ' + err);
                            res.send({ error:err });

                        } else {
                            // update the user which created the review with the review
                            User.update({"_id": userId}, {$push: { reviews: reviewModel } }, function(err) {
                                if (err) {
                                    var errorMsg = "Could not add the review to the user " + userId;
                                    console.log(errorMsg);
                                    errors.push(errorMsg);
                                }
                            });

                            // update the business which was reviewed with the review
                            Business.update({"_id": businessId}, {$push: { reviews: reviewModel._id } }, function(err) {
                                if (err) {
                                    var errorMsg = "Could not add the review to the business " + businessId;
                                    console.log(errorMsg);
                                    errors.push(errorMsg);
                                }
                            });

                            // validate no errors and send the review as response
                            if (errors.length > 0) {
                                console.log('Error while saving review');
                                res.send({ errors:errors });

                            } else {
                                console.log("Review created");
                                return res.send(reviewModel);
                            }
                        }
                    });
                }
            });
        }});
};

/**
 * Find and retrieves a single review by its id
 * @param {Object} req HTTP request object.
 * @param {Object} res HTTP response object.
 */
exports.findReviewById = function(req, res) {
    console.log("GET - /review/:id");
    return Review.find({"_id": req.params.id}, function(err, review) {
        if(!review || !review[0]) {
            res.statusCode = 404;
            return res.send({ error: 'Review Not found' });
        }

        if(!err) {
            return res.send(review[0]);
        } else {

            res.statusCode = 500;
            console.log('Internal error(%d): %s', res.statusCode, err.message);
            return res.send({ error: 'Server error' });
        }
    });
};

/**
 * Find and retrieves all reviews by userId.
 * @param {Object} req HTTP request object.
 * @param {Object} res HTTP response object.
 */
exports.findReviewsByUserId = function(req, res) {
    console.log("GET - /review/user/:userId");

    return Review.find({"userId": req.params.userId}, function(err, reviews) {
        if(!reviews || !reviews[0]) {
            res.statusCode = 404;
            return res.send({ error: 'Reviews Not found' });
        }

        if(!err) {
            return res.send(reviews);
        } else {

            res.statusCode = 500;
            console.log('Internal error(%d): %s', res.statusCode, err.message);
            return res.send({ error: 'Server error' });
        }
    });
};

/**
 * Find and retrieves all reviews by businessId.
 * @param {Object} req HTTP request object.
 * @param {Object} res HTTP response object.
 */
exports.findReviewsByBusinessId = function(req, res) {
    console.log("GET - /review/business/:businessId");
    return Review.find({"businessId": req.params.businessId}, function(err, reviews) {
        if(!reviews || !reviews[0]) {
            res.statusCode = 404;
            return res.send({ error: 'Reviews Not found' });
        }

        if(!err) {
            return res.send(reviews);
        } else {

            res.statusCode = 500;
            console.log('Internal error(%d): %s', res.statusCode, err.message);
            return res.send({ error: 'Server error' });
        }
    });
};

/**
 * Delete a Review by its id
 * @param {Object} req HTTP request object.
 * @param {Object} res HTTP response object.
 */
exports.deleteReview = function(req, res) {

    console.log("DELETE - /review/:id");
    if (!req.user) {
        res.statusCode = 401;
        console.log('User not logged in, unauthorized',res.statusCode);
        return res.send({ error: 'User not logged in, unauthorized' });
    }

    return Review.findOne({"_id": req.params.id}, function(err, review) {
        if (!review) {
            res.statusCode = 404;
            console.log("error: Review Not Found");
            return res.send({ error: 'Review Not found' });
        }

        if (req.user._doc.id != review.userId) {
            res.statusCode = 403;
            console.log('Session user id does not match the review user id, permission denied',res.statusCode);
            return res.send({ error: 'Session user id does not match the review user id, permission denied' });
        }

        var userid = review.userId;
        var businessid = review.businessId;
        var reviewToRemove = review;
        return review.remove(function(err) {
            if(!err) {
                //remove embedded review from user
                User.findOne({"_id":userid}, function(err,user) {
                    if (err) {
                        console.log(err);
                        res.result = 404;
                        res.send({error: 'Failed to remove review from user'})
                    }
                    else if (user) {
                        var index = user.reviews.indexOf(reviewToRemove);
                        //The second parameter of splice is the number of elements to remove
                        user.reviews.splice(index, 1);
                        user.save(function(err) {
                            if (err) {
                                res.statusCode = 500;
                                console.log('Failed to update user (remove review)', res.statusCode, err.message);
                                return res.send({ error: 'Server error' });
                            } else {
                                //remove reference review from business
                                Business.findOne({"_id": businessid}, function(err,business) {
                                    if (err) {
                                        console.log(err);
                                        res.result = 404;
                                        res.send({error: 'Failed to remove review from business'});
                                    } else if (business) {
                                        index = business.reviews.indexOf(reviewToRemove._id);
                                        business.reviews.splice(index,1);
                                        business.save(function(err) {
                                            if (err) {
                                                res.statusCode = 500;
                                                console.log('Failed to update user (remove review)', res.statusCode, err.message);
                                                return res.send({ error: 'Server error' });
                                            } else {
                                                console.log('Removed Review');
                                                res.statusCode = 200;
                                                return res.send({ status: 'OK' });
                                            }
                                        });
                                    }
                                });
                            }
                        });
                    }
                });

            } else {
                res.statusCode = 500;
                console.log('Internal error(%d): %s',res.statusCode,err.message);
                return res.send({ error: 'Server error' });
            }
        })
    });
};<commit_msg>Review Works<commit_after>// The Review controller

var mongoose = require('mongoose');
var Review = require('../models/reviewModel.js');
var Business = require('../models/businessModel.js');
var User = require('../models/userModel.js');

/**
 * Creates a new Review from the data request
 * @param {Object} req HTTP request object.
 * @param {Object} res HTTP response object.
 */
exports.createNewReview = function(req, res) {

    console.log('POST - /review');

    if (!req.user) {
        res.statusCode = 403;
        console.log('User not logged in, unauthorized',res.statusCode);
        return res.send({ error: 'User not logged in, unauthorized' });
    }

    var errors = [];
    var userId = req.body.userId;
    var businessId = req.body.businessId;
    var content = req.body.content;

    // validate the user exists
    var user = User.findOne({ "_id": userId }, function (err, user) {
        if (err) {
            var errorMsg = "Could not add the review. No user found with id: " + userId;
            console.log(errorMsg);
            errors.push(errorMsg);
        }
        if (user) {
            // validate the business exists

            var business = Business.findOne({ "_id": businessId }, function (err, business) {
                if (err) {
                    var errorMsg = "Could not add the review. No business found with id: " + businessId;
                    console.log(errorMsg);
                    errors.push(errorMsg);
                }

                if (business) {
                    // save the new review
                    var reviewModel = new Review();
                    reviewModel.userId = userId;
                    reviewModel.businessId = mongoose.Types.ObjectId(businessId);
                    reviewModel.content = content;
                    reviewModel.date = new Date();
                    reviewModel.save(function(err) {

                        if(err) {
                            console.log('Error while saving review: ' + err);
                            res.send({ error:err });

                        } else {
                            // update the user which created the review with the review
                            User.update({"_id": userId}, {$push: { reviews: reviewModel } }, function(err) {
                                if (err) {
                                    var errorMsg = "Could not add the review to the user " + userId;
                                    console.log(errorMsg);
                                    errors.push(errorMsg);
                                }
                            });

                            // update the business which was reviewed with the review
                            Business.update({"_id": businessId}, {$push: { reviews: reviewModel._id } }, function(err) {
                                if (err) {
                                    var errorMsg = "Could not add the review to the business " + businessId;
                                    console.log(errorMsg);
                                    errors.push(errorMsg);
                                }
                            });

                            // validate no errors and send the review as response
                            if (errors.length > 0) {
                                console.log('Error while saving review');
                                res.send({ errors:errors });

                            } else {
                                console.log("Review created");
                                return res.send(reviewModel);
                            }
                        }
                    });
                }
            });
        }});
};

/**
 * Find and retrieves a single review by its id
 * @param {Object} req HTTP request object.
 * @param {Object} res HTTP response object.
 */
exports.findReviewById = function(req, res) {
    console.log("GET - /review/:id");
    return Review.find({"_id": req.params.id}, function(err, review) {
        if(!review || !review[0]) {
            res.statusCode = 404;
            return res.send({ error: 'Review Not found' });
        }

        if(!err) {
            return res.send(review[0]);
        } else {

            res.statusCode = 500;
            console.log('Internal error(%d): %s', res.statusCode, err.message);
            return res.send({ error: 'Server error' });
        }
    });
};

/**
 * Find and retrieves all reviews by userId.
 * @param {Object} req HTTP request object.
 * @param {Object} res HTTP response object.
 */
exports.findReviewsByUserId = function(req, res) {
    console.log("GET - /review/user/:userId");

    return Review.find({"userId": req.params.userId}, function(err, reviews) {
        if(!reviews || !reviews[0]) {
            res.statusCode = 404;
            return res.send({ error: 'Reviews Not found' });
        }

        if(!err) {
            return res.send(reviews);
        } else {

            res.statusCode = 500;
            console.log('Internal error(%d): %s', res.statusCode, err.message);
            return res.send({ error: 'Server error' });
        }
    });
};

/**
 * Find and retrieves all reviews by businessId.
 * @param {Object} req HTTP request object.
 * @param {Object} res HTTP response object.
 */
exports.findReviewsByBusinessId = function(req, res) {
    console.log("GET - /review/business/:businessId");
    return Review.find({"businessId": req.params.businessId}, function(err, reviews) {
        if(!reviews || !reviews[0]) {
            res.statusCode = 404;
            return res.send({ error: 'Reviews Not found' });
        }

        if(!err) {
            return res.send(reviews);
        } else {

            res.statusCode = 500;
            console.log('Internal error(%d): %s', res.statusCode, err.message);
            return res.send({ error: 'Server error' });
        }
    });
};

/**
 * Delete a Review by its id
 * @param {Object} req HTTP request object.
 * @param {Object} res HTTP response object.
 */
exports.deleteReview = function(req, res) {

    console.log("DELETE - /review/:id");
    if (!req.user) {
        res.statusCode = 401;
        console.log('User not logged in, unauthorized',res.statusCode);
        return res.send({ error: 'User not logged in, unauthorized' });
    }

    return Review.findOne({"_id": req.params.id}, function(err, review) {
        if (!review) {
            res.statusCode = 404;
            console.log("error: Review Not Found");
            return res.send({ error: 'Review Not found' });
        }

        if (req.user._doc._id != review.userId) {
            res.statusCode = 403;
            console.log('Session user id does not match the review user id, permission denied',res.statusCode);
            return res.send({ error: 'Session user id does not match the review user id, permission denied' });
        }

        var userid = review.userId;
        var businessid = review.businessId;
        var reviewToRemove = review;
        return review.remove(function(err) {
            if(!err) {
                //remove embedded review from user
                User.findOne({"_id":userid}, function(err,user) {
                    if (err) {
                        console.log(err);
                        res.result = 404;
                        res.send({error: 'Failed to remove review from user'})
                    }
                    else if (user) {
                        var index = user.reviews.indexOf(reviewToRemove);
                        //The second parameter of splice is the number of elements to remove
                        user.reviews.splice(index, 1);
                        user.save(function(err) {
                            if (err) {
                                res.statusCode = 500;
                                console.log('Failed to update user (remove review)', res.statusCode, err.message);
                                return res.send({ error: 'Server error' });
                            } else {
                                //remove reference review from business
                                Business.findOne({"_id": businessid}, function(err,business) {
                                    if (err) {
                                        console.log(err);
                                        res.result = 404;
                                        res.send({error: 'Failed to remove review from business'});
                                    } else if (business) {
                                        index = business.reviews.indexOf(reviewToRemove._id);
                                        business.reviews.splice(index,1);
                                        business.save(function(err) {
                                            if (err) {
                                                res.statusCode = 500;
                                                console.log('Failed to update user (remove review)', res.statusCode, err.message);
                                                return res.send({ error: 'Server error' });
                                            } else {
                                                console.log('Removed Review');
                                                res.statusCode = 200;
                                                return res.send({ status: 'OK' });
                                            }
                                        });
                                    }
                                });
                            }
                        });
                    }
                });

            } else {
                res.statusCode = 500;
                console.log('Internal error(%d): %s',res.statusCode,err.message);
                return res.send({ error: 'Server error' });
            }
        })
    });
};<|endoftext|>


<commit_before>/*jslint node: true */
'use strict';

/**
 * Module dependencies.
 */
var config = require('../config.json');
var async = require('async');
var request = require('request');
var exec = require('child_process').exec;
var mongoose = require('mongoose');

var getRequest = function(url, callback) {
  var options = {
    url: url
  };
  request(options, callback);
};

/**
 * show chat list
 */
var channelsList = ' https://slack.com/api/channels.list?exclude_archived=1&pretty=1';
var groupsList = 'https://slack.com/api/groups.list?exclude_archived=1&pretty=1';

exports.lists = function(req, res, next) {
  var accessToken = req.headers.token;
  if (!accessToken) {
    var error = new Error();
    error.status = 400;
    error.message = 'Bad Request';
    next(error);
  } else {
    async.waterfall([
      function(callback) {
        getRequest(channelsList + '&token=' + accessToken, function(error, response, body) {
          var json = {};
          if (error) {
            callback(error);
          } else {
            json = JSON.parse(body);
            callback(null, json);
          }
        });
      },
      function(channels, callback) {
        getRequest(groupsList + '&token=' + accessToken, function(error, response, body) {
          var json = {};
          if (error) {
            callback(error);
          } else {
            json = JSON.parse(body);
            callback(null, channels, json);
          }
        });
      },
      function(channels, groups, callback) {
        var lists = [];
        if (channels.ok) {
          channels.channels.forEach(function(element) {
            lists.push({
              'id': element.id,
              'name': element.name
            });
          });
        }
        if (groups.ok) {
          groups.groups.forEach(function(element) {
            lists.push({
              'id': element.id,
              'name': element.name
            });
          });
        }
        res.json(lists);
      }
    ], function(err) {
      if (err) {
        var error = new Error(err);
        error.status = 400;
        error.message = 'Bad Request';
        next(error);
      }
    });
  }
};

/**
 * listen
 */
var execPath = './daemon/slack.js';

exports.listen = function(req, res, next) {
  var accessToken = req.headers.token;
  var channelId = req.headers.id;

  if (!accessToken || !channelId) {
    var error = new Error();
    error.status = 400;
    error.message = 'Bad Request';
    next(error);
  } else {
    var ExecModel = mongoose.model('Exec');

    ExecModel.find({
      $and: [{
        channelId: channelId,
        accessToken: accessToken
      }]
    }, function(err, data) {
      if (!data || data.length !== 0) {
        var error = new Error();
        error.status = 400;
        error.message = 'Bad Request';
        next(error);
      } else {
        var execNew = new ExecModel({
          'channelId': channelId,
          'accessToken': accessToken
        });
        execNew.save(function(err, data) {
          var cmd = 'forever start --append --uid ' + data._id + ' ' + execPath + ' ' + channelId + ' ' + accessToken;
          exec(cmd, function(error, stdout, stderr) {
            if (error !== null) {
              error = new Error();
              error.status = 400;
              error.message = 'Bad Request';
              next(error);
            } else {
              res.send('success');
            }
          });
        });
      }
    });
  }
};

/**
 * listen stop
 */
exports.stop = function(req, res, next) {
  var accessToken = req.headers.token;
  var channelId = req.headers.id;

  if (!accessToken || !channelId) {
    var error = new Error();
    error.status = 400;
    error.message = 'Bad Request';
    next(error);
  } else {
    var ExecModel = mongoose.model('Exec');

    ExecModel.findOne({
      $and: [{
        channelId: channelId,
        accessToken: accessToken
      }]
    }, function(err, data) {
      if (!data || data.length === 0) {
        var error = new Error();
        error.status = 400;
        error.message = 'Bad Request';
        next(error);
      } else {
        var id = data._id;
        ExecModel.remove({
            '_id': id
          },
          function(err, data) {
            exec('forever stop ' + id,
              function(error, stdout, stderr) {
                if (error !== null) {
                  error = new Error();
                  error.status = 400;
                  error.message = 'Bad Request';
                  next(error);
                } else {
                  res.send('success');
                }
              });
          });
      }
    });
  }
};

exports.status = function(req, res, next) {
  var accessToken = req.headers.token;
  var channelId = req.headers.id;

  if (!accessToken || !channelId) {
    var error = new Error();
    error.status = 400;
    error.message = 'Bad Request';
    next(error);
  } else {
    var ExecModel = mongoose.model('Exec');

    ExecModel.findOne({
      $and: [{
        channelId: channelId,
        accessToken: accessToken
      }]
    }, function(err, data) {
      if (!data || data.length === 0) {
        res.json({
          'ok': false
        });
      } else {
        res.json({
          'ok': true
        });
      }
    });
  }
};

var userLists = 'https://slack.com/api/users.list?pretty=1';

exports.members = function(req, res, next) {
  var accessToken = req.headers.token;

  if (!accessToken) {
    var error = new Error();
    error.status = 400;
    error.message = 'Bad Request';
    next(error);
  } else {
    var MemberModel = mongoose.model('Member');

    async.waterfall([
      function(callback) {
        getRequest(userLists + '&token=' + accessToken, function(error, response, body) {
          var json = {};
          if (error) {
            callback(error);
          } else {
            json = JSON.parse(body);
            callback(null, json);
          }
        });
      },
      function(members, callback) {
        var idx = 0;
        members.members.forEach(function(member) {
          idx++;
          if (!member.deleted && !member.is_bot) {

            var memberModel = new MemberModel({
              'id': member.id,
              'name': member.name,
              'real_name': member.real_name,
              'image': member.image_72
            });
            memberModel.save(function(err) {
              if (idx === members.members.length) {
                callback(null);
              }
            });
          }
        });
      },
      function(callback) {
        MemberModel.find({}, function(err, data) {
          if (err) {
            callback(err);
          } else {
            res.json(data);
          }
        });
      }
    ], function(err) {
      if (err) {
        var error = new Error();
        error.status = 400;
        error.message = 'Bad Request';
        next(error);
      }
    });
  }
};
<commit_msg>Fix url<commit_after>/*jslint node: true */
'use strict';

/**
 * Module dependencies.
 */
var config = require('../config.json');
var async = require('async');
var request = require('request');
var exec = require('child_process').exec;
var mongoose = require('mongoose');

var getRequest = function(url, callback) {
  var options = {
    url: url
  };
  request(options, callback);
};

/**
 * show chat list
 */
var channelsList = 'https://slack.com/api/channels.list?exclude_archived=1&pretty=1';
var groupsList = 'https://slack.com/api/groups.list?exclude_archived=1&pretty=1';

exports.lists = function(req, res, next) {
  var accessToken = req.headers.token;
  if (!accessToken) {
    var error = new Error();
    error.status = 400;
    error.message = 'Bad Request';
    next(error);
  } else {
    async.waterfall([
      function(callback) {
        getRequest(channelsList + '&token=' + accessToken, function(error, response, body) {
          var json = {};
          if (error) {
            callback(error);
          } else {
            json = JSON.parse(body);
            callback(null, json);
          }
        });
      },
      function(channels, callback) {
        getRequest(groupsList + '&token=' + accessToken, function(error, response, body) {
          var json = {};
          if (error) {
            callback(error);
          } else {
            json = JSON.parse(body);
            callback(null, channels, json);
          }
        });
      },
      function(channels, groups, callback) {
        var lists = [];
        if (channels.ok) {
          channels.channels.forEach(function(element) {
            lists.push({
              'id': element.id,
              'name': element.name
            });
          });
        }
        if (groups.ok) {
          groups.groups.forEach(function(element) {
            lists.push({
              'id': element.id,
              'name': element.name
            });
          });
        }
        res.json(lists);
      }
    ], function(err) {
      if (err) {
        var error = new Error(err);
        error.status = 400;
        error.message = 'Bad Request';
        next(error);
      }
    });
  }
};

/**
 * listen
 */
var execPath = './daemon/slack.js';

exports.listen = function(req, res, next) {
  var accessToken = req.headers.token;
  var channelId = req.headers.id;

  if (!accessToken || !channelId) {
    var error = new Error();
    error.status = 400;
    error.message = 'Bad Request';
    next(error);
  } else {
    var ExecModel = mongoose.model('Exec');

    ExecModel.find({
      $and: [{
        channelId: channelId,
        accessToken: accessToken
      }]
    }, function(err, data) {
      if (!data || data.length !== 0) {
        var error = new Error();
        error.status = 400;
        error.message = 'Bad Request';
        next(error);
      } else {
        var execNew = new ExecModel({
          'channelId': channelId,
          'accessToken': accessToken
        });
        execNew.save(function(err, data) {
          var cmd = 'forever start --append --uid ' + data._id + ' ' + execPath + ' ' + channelId + ' ' + accessToken;
          exec(cmd, function(error, stdout, stderr) {
            if (error !== null) {
              error = new Error();
              error.status = 400;
              error.message = 'Bad Request';
              next(error);
            } else {
              res.send('success');
            }
          });
        });
      }
    });
  }
};

/**
 * listen stop
 */
exports.stop = function(req, res, next) {
  var accessToken = req.headers.token;
  var channelId = req.headers.id;

  if (!accessToken || !channelId) {
    var error = new Error();
    error.status = 400;
    error.message = 'Bad Request';
    next(error);
  } else {
    var ExecModel = mongoose.model('Exec');

    ExecModel.findOne({
      $and: [{
        channelId: channelId,
        accessToken: accessToken
      }]
    }, function(err, data) {
      if (!data || data.length === 0) {
        var error = new Error();
        error.status = 400;
        error.message = 'Bad Request';
        next(error);
      } else {
        var id = data._id;
        ExecModel.remove({
            '_id': id
          },
          function(err, data) {
            exec('forever stop ' + id,
              function(error, stdout, stderr) {
                if (error !== null) {
                  error = new Error();
                  error.status = 400;
                  error.message = 'Bad Request';
                  next(error);
                } else {
                  res.send('success');
                }
              });
          });
      }
    });
  }
};

exports.status = function(req, res, next) {
  var accessToken = req.headers.token;
  var channelId = req.headers.id;

  if (!accessToken || !channelId) {
    var error = new Error();
    error.status = 400;
    error.message = 'Bad Request';
    next(error);
  } else {
    var ExecModel = mongoose.model('Exec');

    ExecModel.findOne({
      $and: [{
        channelId: channelId,
        accessToken: accessToken
      }]
    }, function(err, data) {
      if (!data || data.length === 0) {
        res.json({
          'ok': false
        });
      } else {
        res.json({
          'ok': true
        });
      }
    });
  }
};

var userLists = 'https://slack.com/api/users.list?pretty=1';

exports.members = function(req, res, next) {
  var accessToken = req.headers.token;

  if (!accessToken) {
    var error = new Error();
    error.status = 400;
    error.message = 'Bad Request';
    next(error);
  } else {
    var MemberModel = mongoose.model('Member');

    async.waterfall([
      function(callback) {
        getRequest(userLists + '&token=' + accessToken, function(error, response, body) {
          var json = {};
          if (error) {
            callback(error);
          } else {
            json = JSON.parse(body);
            callback(null, json);
          }
        });
      },
      function(members, callback) {
        var idx = 0;
        members.members.forEach(function(member) {
          idx++;
          if (!member.deleted && !member.is_bot) {

            var memberModel = new MemberModel({
              'id': member.id,
              'name': member.name,
              'real_name': member.real_name,
              'image': member.image_72
            });
            memberModel.save(function(err) {
              if (idx === members.members.length) {
                callback(null);
              }
            });
          }
        });
      },
      function(callback) {
        MemberModel.find({}, function(err, data) {
          if (err) {
            callback(err);
          } else {
            res.json(data);
          }
        });
      }
    ], function(err) {
      if (err) {
        var error = new Error();
        error.status = 400;
        error.message = 'Bad Request';
        next(error);
      }
    });
  }
};
<|endoftext|>


<commit_before>opera.isReady(function() {
    var win = null, tab = null;
    var tests = {}, // Asynchronous tests
    eventsReceived = [], // List of received events
    eventsExpected = [ // List of expected events
    // Step 1
    {
        target : "tab",
        type : "close"
    },

    // Step 2
    {
        target : "browserWindow",
        type : "close"
    } ];

    tests["close"] = async_test("Tab Group close event");
    tests["order"] = async_test("Order of events");

    function getHandler(type) {
        return function(evt) {
            tests[type].step(function() {
                assert_equals(evt.type, type, "Event type should be '" + type + "'");
                assert_exists(evt, "tab", "The event object should have a tabGroup property");
                assert_equals(evt.tab.id, tab.id, "The event should refer to the created tab group");
            });
            tests[type].done();
        }
    }

    function eventOrder(evt) {
        var evtTarget = evt.browserWindow ? "browserWindow" : evt.tabGroup ? "tabGroup" : evt.tab ? "tab" : "unknown"

        eventsReceived.push({
            target : evtTarget,
            type : evt.type
        });

        if (eventsReceived.length === eventsExpected.length) {
            setTimeout(function() {
                tests["order"].step(function() {
                    // for (i = 0; i < eventsReceived.length; i++) {
                    // opera.postError(eventsReceived[i].target + ": " +
                    // eventsReceived[i].type)
                    // }

                    for (i = 0; i < eventsReceived.length; i++) {
                        assert_equals("{" + eventsReceived[i].target + ", " + eventsReceived[i].type + "}", "{" + eventsExpected[i].target + ", " + eventsExpected[i].type + "}",
                                "The event order, type and target should match. Event number: " + i)
                    }
                });
                tests["order"].done();
            }, 500); // Wait, incase new unexpected events fire
        }
    }

    // Setup
    try {
        win = createWindow({}, {
            focused : true
        }); // Create a window
    } catch (e) {
        for ( var n in tests)
            tests[n].step(function() {
                assert_unreached("Couldn't create new window")
            });
    }
    tab = win.tabs.getAll()[0];

    tabs.addEventListener("close", getHandler("close"), false);

    windows.addEventListener("create", eventOrder, false);
    windows.addEventListener("close", eventOrder, false);
    groups.addEventListener("create", eventOrder, false);
    groups.addEventListener("move", eventOrder, false);
    groups.addEventListener("close", eventOrder, false);
    tabs.addEventListener("create", eventOrder, false);
    tabs.addEventListener("move", eventOrder, false);
    tabs.addEventListener("close", eventOrder, false);

    setTimeout(function() {
        // Step 1
        tab.close(); // Close the tab and its tabs, fire close events

        // Step 2
        win.close(); // Close the window, if it didn't close automatically
    }, 100);
});
<commit_msg>fixed testcase, added timeout before attaching events, removed parts of tab-groups<commit_after>opera.isReady(function() {
    var win = null, tab = null;
    var tests = {}, // Asynchronous tests
    eventsReceived = [], // List of received events
    eventsExpected = [ // List of expected events
    // Step 1
    {
        target : "tab",
        type : "close"
    },

    // Step 2
    {
        target : "browserWindow",
        type : "close"
    } ];

    tests["close"] = async_test("Tab Window close event");
    tests["order"] = async_test("Order of events");

    function getHandler(type) {
        return function(evt) {
            tests[type].step(function() {
                assert_equals(evt.type, type, "Event type should be '" + type + "'");
                assert_exists(evt, "tab", "The event object should have a tab property");
                assert_equals(evt.tab.id, tab.id, "The event should refer to the created tab");
            });
            tests[type].done();
        }
    }

    function eventOrder(evt) {
        var evtTarget = evt.browserWindow ? "browserWindow" : evt.tab ? "tab" : "unknown";

        eventsReceived.push({
            target : evtTarget,
            type : evt.type
        });

        if (eventsReceived.length === eventsExpected.length) {
            setTimeout(function() {
                tests["order"].step(function() {
                    // for (i = 0; i < eventsReceived.length; i++) {
                    // opera.postError(eventsReceived[i].target + ": " +
                    // eventsReceived[i].type)
                    // }

                    for (i = 0; i < eventsReceived.length; i++) {
                        assert_equals("{" + eventsReceived[i].target + ", " + eventsReceived[i].type + "}", "{" + eventsExpected[i].target + ", " + eventsExpected[i].type + "}",
                                "The event order, type and target should match. Event number: " + i)
                    }
                });
                tests["order"].done();
            }, 500); // Wait, incase new unexpected events fire
        }
    }

    // Setup

    try {
        win = createWindow({}, {
            focused : true
        }); // Create a window
    } catch (e) {
        for ( var n in tests)
            tests[n].step(function() {
                assert_unreached("Couldn't create new window")
            });
    }
    tab = win.tabs.getAll()[0];

    //window create-event may be delayed
    setTimeout(function() {
	tabs.addEventListener("close", getHandler("close"), false);
	windows.addEventListener("create", eventOrder, false);
	windows.addEventListener("close", eventOrder, false);
	    //groups.addEventListener("create", eventOrder, false);
	    //groups.addEventListener("move", eventOrder, false);
	    //groups.addEventListener("close", eventOrder, false);
	tabs.addEventListener("create", eventOrder, false);
	tabs.addEventListener("move", eventOrder, false);
	tabs.addEventListener("close", eventOrder, false);

	setTimeout(function() {
            // Step 1
            tab.close(); // Close the tab and its tabs, fire close events

            // Step 2
            win.close(); // Close the window, if it didn't close automatically
        }, 100);
    }, 100);
});
<|endoftext|>


<commit_before>import React from 'react'
import A_Title_H from 'A_Title_H'
import A_Btn_H from 'A_Btn_H'
import SectionCounter from '../common/SectionCounter/index.js'
import InfoColumns from '../common/InfoColumns'
import './styles.scss'
import { cssClassName } from 'utils'

const cn = cssClassName('SE_Home_Expedition')

const SE_Home_Expedition = ({ mix }) => (

      <A_Title_H mix={cn('title')} type="section" theme="dark">
        Humaniq expedition: the first
 step in financial inclusion
      </A_Title_H>

      <InfoColumns mix={cn('info-columns')} columns={infoColumns} type="narrow" />

        <A_Btn_H to="http://humaniqchallenge.com">About expedition</A_Btn_H>

    <SectionCounter sectionNum={11} theme="bright" />

)

export default SE_Home_Expedition

const infoColumns = [
  {
    title: 'Startup contest',
    text:
      'In order to bring together a network of like-minded individuals and then choose 10 projects for entry into the Humaniq system, we are launching the Humaniq Global Challenge for entrepreneurs, developers, marketing specialists and economists.',
  },
  {
    title: 'Benefits',
    text:
      '10 Finalists will receive expert advice from top consultants in their field, as well as the chance to gain investment and to enter the Humaniq accelerator.',
  },
  {
    title: 'Trip to Kenia',
    text:
      'The three best teams will go on a trip to Kenya to learn more about the lives of the unbanked and put the finishing touches to their projects ahead of an ICO, which will be supported by Humaniq.',
  },
]
<commit_msg>[fix] kenya fixed<commit_after>import React from 'react'
import A_Title_H from 'A_Title_H'
import A_Btn_H from 'A_Btn_H'
import SectionCounter from '../common/SectionCounter/index.js'
import InfoColumns from '../common/InfoColumns'
import './styles.scss'
import { cssClassName } from 'utils'

const cn = cssClassName('SE_Home_Expedition')

const SE_Home_Expedition = ({ mix }) => (

      <A_Title_H mix={cn('title')} type="section" theme="dark">
        Humaniq expedition: the first
 step in financial inclusion
      </A_Title_H>

      <InfoColumns mix={cn('info-columns')} columns={infoColumns} type="narrow" />

        <A_Btn_H to="http://humaniqchallenge.com">About expedition</A_Btn_H>

    <SectionCounter sectionNum={11} theme="bright" />

)

export default SE_Home_Expedition

const infoColumns = [
  {
    title: 'Startup contest',
    text:
      'In order to bring together a network of like-minded individuals and then choose 10 projects for entry into the Humaniq system, we are launching the Humaniq Global Challenge for entrepreneurs, developers, marketing specialists and economists.',
  },
  {
    title: 'Benefits',
    text:
      '10 Finalists will receive expert advice from top consultants in their field, as well as the chance to gain investment and to enter the Humaniq accelerator.',
  },
  {
    title: 'Trip to Kenya',
    text:
      'The three best teams will go on a trip to Kenya to learn more about the lives of the unbanked and put the finishing touches to their projects ahead of an ICO, which will be supported by Humaniq.',
  },
]
<|endoftext|>


<commit_before>const restify = require('restify')
const safeExtend = require('../lib/safe-extend');
const ImageHelper = require('../lib/image-helper')
const Badges = require('../models/badge');

const putBadge = ImageHelper.putModel(Badges)

exports = module.exports = function applyBadgeRoutes (server) {

  server.get('/badges', showAllBadges);
  function showAllBadges (req, res, next) {
    var query;
    var options = {relationships: true};

    switch ('' + req.query.archived) {
      case 'true':
      case '1':
        query = {archived: true};
        break;

      case 'false':
      case '0':
      case 'undefined':
        query = {archived: false};
        break;

      case 'any':
      case '':
        query = {};
        break;

      default:
        return res.send(400, {
          code: 'InvalidParameter',
          parameter: 'archived',
          message: 'Invalid `archived` parameter. Expecting one of \'true\', \'false\' or \'any\'.',
        });
    }

    Badges.get(query, options, function foundRows (error, rows) {
      if (error)
        return handleError(error, null, res, next);

      res.send({badges: rows.map(badgeFromDb)});
      return next();
    });
  }

  server.post('/badges', saveBadge);
  function saveBadge (req, res, next) {
    var row = fromPostToRow(req.body);
    var image = (req.files || {}).image || {};
    if (!image.size)
      image = req.body.image || {};

    putBadge(row, image, function (err, result) {
      if (err) {
        if (!Array.isArray(err))
          return handleError(err, row, res, next);

        return res.send(400, {
          code: 'ValidationError',
          message: 'Could not validate required fields',
          details: err,
        });
      }

      res.send(201, {status: 'created'});
    });
  }

  server.get('/badges/:badgeId', showOneBadge);
  function showOneBadge (req, res, next) {
    getBadge(req, res, next, function (row) {
      res.send({badge: badgeFromDb(row)});
      return next();
    });
  }

  server.del('/badges/:badgeId', deleteBadge);
  function deleteBadge (req, res, next) {
    getBadge(req, res, next, function (row) {
      Badges.del({id: row.id}, function deletedRow (error, result) {
        if (error)
          return handleError(error, row, req, next);
        res.send({status: 'deleted', badge: badgeFromDb(row)});
      });
    });
  }

  server.put('/badges/:badgeId', updateBadge);
  function updateBadge (req, res, next) {
    getBadge(req, res, next, function (badge) {
      var row = safeExtend(badge, req.body);
      delete row.image

      row.issuerId = row.issuerId || undefined;
      var image = (req.files || {}).image || {};
      if (!image.size)
        image = req.body.image || null;

      putBadge(row, image, function (err, result) {
        if (err) {
          if (!Array.isArray(err))
            return handleError(err, row, res, next);

          return res.send(400, {
            code: 'ValidationError',
            message: 'Could not validate required fields',
            details: err,
          });
        }

        res.send({status: 'updated'});
      });
    });
  }

};

function getBadge (req, res, next, callback) {
  const query = {slug: req.params.badgeId};
  const options = {relationships: true};
  Badges.getOne(query, options, function foundBadge (error, row) {
    if (error)
      return handleError(error, row, res, next);

    if (!row) {
      const notFoundErr = new restify.ResourceNotFoundError('Could not find badge with slug `'+query.slug+'`')
      return next(notFoundErr);
    }

    return callback(row);
  });
}

const errorCodes = {
  ER_DUP_ENTRY: [409, {error: 'A badge with that `slug` already exists'}]
};

function handleError (error, row, res, next) {
  const expected = knownError(error, row);
  if (!expected) return next(error);
  res.send.apply(res, expected);
  return next();
}

function knownError (error, row) {
  const err = errorCodes[error.code];
  if (!err) return;
  if (row) err[1].received = row;
  return err;
}

function fromPostToRow (post) {
  return {
    slug: post.slug,
    name: post.name,
    strapline: post.strapline,
    description: post.description
  };
}

function badgeFromDb (row) {
  return {
    slug: row.slug,
    name: row.name,
    strapline: row.strapline,
    description: row.description,
    imageUrl: row.image ? row.image.toUrl() : null,
    archived: !!row.archived
  };
}
<commit_msg>Send back row on PUT, POST, DELETE for badges<commit_after>const restify = require('restify')
const safeExtend = require('../lib/safe-extend');
const ImageHelper = require('../lib/image-helper')
const Badges = require('../models/badge');

const putBadge = ImageHelper.putModel(Badges)

exports = module.exports = function applyBadgeRoutes (server) {

  server.get('/badges', showAllBadges);
  function showAllBadges (req, res, next) {
    var query;
    var options = {relationships: true};

    switch ('' + req.query.archived) {
      case 'true':
      case '1':
        query = {archived: true};
        break;

      case 'false':
      case '0':
      case 'undefined':
        query = {archived: false};
        break;

      case 'any':
      case '':
        query = {};
        break;

      default:
        return res.send(400, {
          code: 'InvalidParameter',
          parameter: 'archived',
          message: 'Invalid `archived` parameter. Expecting one of \'true\', \'false\' or \'any\'.',
        });
    }

    Badges.get(query, options, function foundRows (error, rows) {
      if (error)
        return handleError(error, null, res, next);

      res.send({badges: rows.map(badgeFromDb)});
      return next();
    });
  }

  server.post('/badges', saveBadge);
  function saveBadge (req, res, next) {
    var row = fromPostToRow(req.body);
    var image = (req.files || {}).image || {};
    if (!image.size)
      image = req.body.image || {};

    putBadge(row, image, function (err, result) {
      if (err) {
        if (!Array.isArray(err))
          return handleError(err, row, res, next);

        return res.send(400, {
          code: 'ValidationError',
          message: 'Could not validate required fields',
          details: err,
        });
      }

      res.send(201, {status: 'created', badge: row});
    });
  }

  server.get('/badges/:badgeId', showOneBadge);
  function showOneBadge (req, res, next) {
    getBadge(req, res, next, function (row) {
      res.send({badge: badgeFromDb(row)});
      return next();
    });
  }

  server.del('/badges/:badgeId', deleteBadge);
  function deleteBadge (req, res, next) {
    getBadge(req, res, next, function (row) {
      Badges.del({id: row.id}, function deletedRow (error, result) {
        if (error)
          return handleError(error, row, req, next);
        res.send({status: 'deleted', badge: badgeFromDb(row)});
      });
    });
  }

  server.put('/badges/:badgeId', updateBadge);
  function updateBadge (req, res, next) {
    getBadge(req, res, next, function (badge) {
      var row = safeExtend(badge, req.body);
      delete row.image

      row.issuerId = row.issuerId || undefined;
      var image = (req.files || {}).image || {};
      if (!image.size)
        image = req.body.image || null;

      putBadge(row, image, function (err, result) {
        if (err) {
          if (!Array.isArray(err))
            return handleError(err, row, res, next);

          return res.send(400, {
            code: 'ValidationError',
            message: 'Could not validate required fields',
            details: err,
          });
        }

        res.send({status: 'updated', badge: row});
      });
    });
  }

};

function getBadge (req, res, next, callback) {
  const query = {slug: req.params.badgeId};
  const options = {relationships: true};
  Badges.getOne(query, options, function foundBadge (error, row) {
    if (error)
      return handleError(error, row, res, next);

    if (!row) {
      const notFoundErr = new restify.ResourceNotFoundError('Could not find badge with slug `'+query.slug+'`')
      return next(notFoundErr);
    }

    return callback(row);
  });
}

const errorCodes = {
  ER_DUP_ENTRY: [409, {error: 'A badge with that `slug` already exists'}]
};

function handleError (error, row, res, next) {
  const expected = knownError(error, row);
  if (!expected) return next(error);
  res.send.apply(res, expected);
  return next();
}

function knownError (error, row) {
  const err = errorCodes[error.code];
  if (!err) return;
  if (row) err[1].received = row;
  return err;
}

function fromPostToRow (post) {
  return {
    slug: post.slug,
    name: post.name,
    strapline: post.strapline,
    description: post.description
  };
}

function badgeFromDb (row) {
  return {
    slug: row.slug,
    name: row.name,
    strapline: row.strapline,
    description: row.description,
    imageUrl: row.image ? row.image.toUrl() : null,
    archived: !!row.archived
  };
}
<|endoftext|>


<commit_before>if (typeof user === 'undefined') user = "highfidelity/";
if (typeof repository === 'undefined') repository = "hifi_tests/";
if (typeof branch === 'undefined') branch = "master/";

var autoTester = Script.require("https://github.com/" + user + repository + "blob/" + branch + "tests/utils/autoTester.js?raw=true" );

autoTester.perform("Apply Material Entities to Avatars", Script.resolvePath("."), "primary", function(testType) {
    Script.include("../../../../../utils/test_stage.js?raw=true");

    // Add the test Cases
    var flags = {
        hasAmbientLight: false
    };
    var createdEntities = setupStage(flags)

    var posOri = getStagePosOriAt(0, 0, 0);

    MyAvatar.orientation = Quat.fromVec3Degrees({x:0, y:180, z:0});

    var LIFETIME = 120;

    createdEntities.push(Entities.addEntity({
        type: "Material",
        materialURL: "materialData",
        position: MyAvatar.position,
        materialData: JSON.stringify({ "materials": {
            "albedo": [0, 0, 1]
        }}),
        lifetime: LIFETIME,
        priority: 1,
        parentMaterialName: 2,
        parentID: MyAvatar.SELF_ID
    }, true));

    var previousSkeletonURL;
    var previousScale;
    var previousAvatarVisibility;

    autoTester.addStep("Setup avatar", function () {
        // Use a specific avatar.  This is needed because we want the avatar's height to be fixed.
        previousSkeletonURL = MyAvatar.skeletonModelURL;
        MyAvatar.skeletonModelURL = "https://highfidelity.com/api/v1/commerce/entity_edition/813addb9-b985-49c8-9912-36fdbb57e04a.fst?certificate_id=MEUCIQDgYR2%2BOrCh5HXeHCm%2BkR0a2JniEO%2BY4y9tbApxCAPo4wIgXZEQdI4cQc%2FstAcr9tFT9k4k%2Fbuj3ufB1aB4W0tjIJc%3D";

        previousScale = MyAvatar.scale;
        MyAvatar.scale = 1.0;

        // Wait for skeleton to load (for now - only in test mode)
        if (typeof Test !== 'undefined') {
            Test.waitIdle();
        }

        // Set Avatar to T-pose
        for (var i = 0; i < MyAvatar.getJointNames().length; ++i) {
            MyAvatar.setJointData(i, MyAvatar.getDefaultJointRotation(i), MyAvatar.getDefaultJointTranslation(i));
        }

        Camera.mode = "first person";
    });

    autoTester.addStep("Setup avatar, and make sure it is visible", function () {
        Camera.mode = "mirror";

        previousAvatarVisibility = MyAvatar.getEnableMeshVisible();
        MyAvatar.setEnableMeshVisible(true);
    });

    autoTester.addStepSnapshot("Avatar without material");

    autoTester.addStep("Add material to avatar", function () {
        createdEntities.push(Entities.addEntity({
            type: "Material",
            materialURL: "materialData",
            position: MyAvatar.position,
            materialData: JSON.stringify({ "materials": {
            "albedo": [0, 0, 1]
            }}),
            lifetime: LIFETIME,
            priority: 1,
            parentMaterialName: 0,
            parentID: MyAvatar.SELF_ID
            }, true)
        );
    });

    autoTester.addStepSnapshot("Display material on avatar");

    autoTester.addStep("Clean up after test", function () {
        for (var i = 0; i < createdEntities.length; i++) {
            Entities.deleteEntity(createdEntities[i]);
        }

        // Restore avatar and camera mode
        MyAvatar.skeletonModelURL = previousSkeletonURL;
        MyAvatar.scale = previousScale;
        MyAvatar.clearJointsData();

        MyAvatar.setEnableMeshVisible(previousAvatarVisibility);
    });

    var result = autoTester.runTest(testType);
});<commit_msg>Do not use mirror mode.<commit_after>if (typeof user === 'undefined') user = "highfidelity/";
if (typeof repository === 'undefined') repository = "hifi_tests/";
if (typeof branch === 'undefined') branch = "master/";

var autoTester = Script.require("https://github.com/" + user + repository + "blob/" + branch + "tests/utils/autoTester.js?raw=true" );

autoTester.perform("Apply Material Entities to Avatars", Script.resolvePath("."), "primary", function(testType) {
    Script.include("../../../../../utils/test_stage.js?raw=true");

    // Add the test Cases
    var flags = {
        hasAmbientLight: false
    };
    var createdEntities = setupStage(flags)

    var posOri = getStagePosOriAt(0, 0, 0);

    MyAvatar.orientation = Quat.fromVec3Degrees({x:0, y:180, z:0});

    var LIFETIME = 120;

    createdEntities.push(Entities.addEntity({
        type: "Material",
        materialURL: "materialData",
        position: MyAvatar.position,
        materialData: JSON.stringify({ "materials": {
            "albedo": [0, 0, 1]
        }}),
        lifetime: LIFETIME,
        priority: 1,
        parentMaterialName: 2,
        parentID: MyAvatar.SELF_ID
    }, true));

    var previousSkeletonURL;
    var previousScale;
    var previousAvatarVisibility;

    autoTester.addStep("Setup avatar", function () {
        // Use a specific avatar.  This is needed because we want the avatar's height to be fixed.
        previousSkeletonURL = MyAvatar.skeletonModelURL;
        MyAvatar.skeletonModelURL = "https://highfidelity.com/api/v1/commerce/entity_edition/813addb9-b985-49c8-9912-36fdbb57e04a.fst?certificate_id=MEUCIQDgYR2%2BOrCh5HXeHCm%2BkR0a2JniEO%2BY4y9tbApxCAPo4wIgXZEQdI4cQc%2FstAcr9tFT9k4k%2Fbuj3ufB1aB4W0tjIJc%3D";

        previousScale = MyAvatar.scale;
        MyAvatar.scale = 1.0;

        previousAvatarVisibility = MyAvatar.getEnableMeshVisible();
        MyAvatar.setEnableMeshVisible(true);

        // Wait for skeleton to load (for now - only in test mode)
        if (typeof Test !== 'undefined') {
            Test.waitIdle();
        }

        validationCamera_translate({ x: 0.0, y: -0.25, z: 0.4 });
    });

    autoTester.addStep("Set T-Pose", function () {
        // Set Avatar to T-pose
        for (var i = 0; i < MyAvatar.getJointNames().length; ++i) {
            MyAvatar.setJointData(i, MyAvatar.getDefaultJointRotation(i), MyAvatar.getDefaultJointTranslation(i));
        }
    });

    autoTester.addStepSnapshot("Avatar without material");

    autoTester.addStep("Add material to avatar", function () {
        createdEntities.push(Entities.addEntity({
            type: "Material",
            materialURL: "materialData",
            position: MyAvatar.position,
            materialData: JSON.stringify({ "materials": {
            "albedo": [0, 0, 1]
            }}),
            lifetime: LIFETIME,
            priority: 1,
            parentMaterialName: 0,
            parentID: MyAvatar.SELF_ID
            }, true)
        );
    });

    autoTester.addStepSnapshot("Display material on avatar");

    autoTester.addStep("Clean up after test", function () {
        for (var i = 0; i < createdEntities.length; i++) {
            Entities.deleteEntity(createdEntities[i]);
        }

        // Restore avatar and camera mode
        MyAvatar.skeletonModelURL = previousSkeletonURL;
        MyAvatar.scale = previousScale;
        MyAvatar.clearJointsData();

        MyAvatar.setEnableMeshVisible(previousAvatarVisibility);
    });

    var result = autoTester.runTest(testType);
});<|endoftext|>