<commit_before>'use strict';

var mongoose = require('mongoose'),
    LocalStrategy = require('passport-local').Strategy,
    TwitterStrategy = require('passport-twitter').Strategy,
    FacebookStrategy = require('passport-facebook').Strategy,
    GitHubStrategy = require('passport-github').Strategy,
    GoogleStrategy = require('passport-google-oauth').OAuth2Strategy,
    LinkedinStrategy = require('passport-linkedin').Strategy,
    User = mongoose.model('User'),
    config = require('meanio').loadConfig(),
    Team = mongoose.model('Team'),
    _ = require('lodash'),
    async = require('async');

module.exports = function (passport) {

    // Serialize the user id to push into the session
    passport.serializeUser(function (user, done) {
        done(null, user.id);
    });

    // Deserialize the user object based on a pre-serialized token
    // which is the user id
    passport.deserializeUser(function (id, done) {
        User.findOne({
            _id: id
        }, '-salt -hashed_password', function (err, user) {
            done(err, user);
        });
    });

    // Use local strategy
    passport.use(new LocalStrategy({
        usernameField: 'email', passwordField: 'password'
    }, function (email, password, done) {
        User.findOne({
            email: email
        }, function (err, user) {
            if (err) {
                return done(err);
            }
            if (!user) {
                return done(null, false, {
                    message: 'Unknown user'
                });
            }
            if (!user.authenticate(password)) {
                return done(null, false, {
                    message: 'Invalid password'
                });
            }
            return done(null, user);
        });
    }));

    // Use twitter strategy
    passport.use(new TwitterStrategy({
        consumerKey: config.twitter.clientID,
        consumerSecret: config.twitter.clientSecret,
        callbackURL: config.twitter.callbackURL
    }, function (token, tokenSecret, profile, done) {
        return ssoAuth(profile, 'twitter', done);
    }));

    var multipleStrategyUser = null,
        loginStrategy, profile, user;

    /**
     * If a user with this email has logged on before using another method, add this SSO id and log the user in
     * @param callback
     * @returns {*}
     */
    var checkMultipleSsoMethods = function (callback) {
        // If this strategy returns email, search by email. If not, such as Twitter, SORRY
        if (_.has(profile, 'emails')) {
            // Find the user based on the first email returned
            // @todo This is weak, need to check all emails
            User.findOne({
                email: profile.emails[0].value
            }, function (err, user) {
                // Return on error
                if (err) {
                    return callback('Error on finding user by email');
                }
                // If a user was found using a different login strategy
                if (user) {
                    // Add this login strategy to this user's account
                    user[loginStrategy] = profile;
                    user.save(function (err) {
                        if (err) {
                            return callback(new Error(err));
                        }
                        // Give the next function access to this user
                        multipleStrategyUser = user;
                        return callback(null, user);
                    });
                } else {
                    return callback();
                }
            });
        } else {
            return callback();
        }
    };

    /**
     * If a user was not found using the current SSO method or via email, then create a new user
     * @param callback
     * @returns {*}
     */
    var createNewUserSso = function (callback) {
        if (multipleStrategyUser) {
            return callback(null, multipleStrategyUser);
        }
        // If we've made it this far, go ahead and create the user
        var userObj = {
            name: profile.displayName,
            provider: loginStrategy,
            roles: ['authenticated']
        };
        // Add the details from the login strategy return
        userObj[loginStrategy] = profile._json;
        // Add email if this login strategy has it
        if (_.has(profile, 'emails')) {
            userObj.email = profile.emails[0].value;
        } else {
            // Handling twitter's dumb ass
            userObj.email = profile.id + '@twitter.com';
        }
        user = new User(userObj);
        // Create a team for this user
        var team = new Team({
            name: user.name + '\'s Team'
        });
        // Save the team
        team.save(function (err) {
            if (err) {
                return callback(new Error(err));
            }
            // Add user to team
            user.teams.push(team._id);
            // Save the user
            user.save(function (err) {
                if (err) {
                    // Done from passport takes three parameters: error, false for failure, something truthy for
                    // success, and finally, object with info
                    return callback(new Error(err));
                } else {
                    return callback(null, user);
                }
            });
        });
    };

    /**
     * Generalize SSO authorization function
     *
     * @todo REFACTOR ME
     *
     * @param thisProfile
     * @param thisLoginStrategy
     * @param done
     */
    var ssoAuth = function (thisProfile, thisLoginStrategy, done) {
        var userSearch = {};
        loginStrategy = thisLoginStrategy;
        profile = thisProfile;
        // Search by the login strategy id (some are strings, some are ints...)
        userSearch[loginStrategy + '.id'] = loginStrategy === 'twitter' ? parseInt(profile.id) : profile.id;
        return User.findOne(userSearch, function (err, user) {
            // Return on error
            if (err) {
                return done(err);
            }
            // If the user found, let's log that puppy in
            if (user) {
                return done(err, user);
            }
            // Check for users this email, different strategy. Then create or log the user in
            return async.series([checkMultipleSsoMethods, createNewUserSso],
            // Log the user in, if one was found
            function (err, user) {
                if (err) {
                    return done(null, false, {
                        message: loginStrategy + ' login failed, email already used by other login strategy'}
                    );
                }
                return done(err, user[1]);
            });
        });
    };

    // Use facebook strategy
    passport.use(new FacebookStrategy({
        clientID: config.facebook.clientID,
        clientSecret: config.facebook.clientSecret,
        callbackURL: config.facebook.callbackURL
    }, function (accessToken, refreshToken, profile, done) {
        ssoAuth(profile, 'facebook', done);
    }));

    // Use github strategy
    passport.use(new GitHubStrategy({
        clientID: config.github.clientID,
        clientSecret: config.github.clientSecret,
        callbackURL: config.github.callbackURL
    }, function (accessToken, refreshToken, profile, done) {
        User.findOne({
            'github.id': profile.id
        }, function (err, user) {
            if (user) {
                return done(err, user);
            }
            user = new User({
                name: profile.displayName,
                email: profile.emails[0].value,
                username: profile.username,
                provider: 'github',
                github: profile._json,
                roles: ['authenticated']
            });
            user.save(function (err) {
                if (err) {
                    console.log(err);
                    return done(null, false,
                    {message: 'Github login failed, email already used by other login strategy'});
                } else {
                    return done(err, user);
                }
            });
        });
    }));

    // Use google strategy
    passport.use(new GoogleStrategy({
        clientID: config.google.clientID,
        clientSecret: config.google.clientSecret,
        callbackURL: config.google.callbackURL
    }, function (accessToken, refreshToken, profile, done) {
        return ssoAuth(profile, 'google', done);
    }));

    // use linkedin strategy
    passport.use(new LinkedinStrategy({
        consumerKey: config.linkedin.clientID,
        consumerSecret: config.linkedin.clientSecret,
        callbackURL: config.linkedin.callbackURL,
        profileFields: ['id', 'first-name', 'last-name', 'email-address']
    }, function (accessToken, refreshToken, profile, done) {
        User.findOne({
            'linkedin.id': profile.id
        }, function (err, user) {
            if (user) {
                return done(err, user);
            }
            user = new User({
                name: profile.displayName,
                email: profile.emails[0].value,
                username: profile.emails[0].value,
                provider: 'linkedin',
                roles: ['authenticated']
            });
            user.save(function (err) {
                if (err) {
                    console.log(err);
                    return done(null, false,
                    {message: 'LinkedIn login failed, email already used by other login strategy'});
                } else {
                    return done(err, user);
                }
            });
        });
    }));
};
<commit_msg>Test travis run<commit_after>'use strict';

var mongoose = require('mongoose'),
    LocalStrategy = require('passport-local').Strategy,
    TwitterStrategy = require('passport-twitter').Strategy,
    FacebookStrategy = require('passport-facebook').Strategy,
    GitHubStrategy = require('passport-github').Strategy,
    GoogleStrategy = require('passport-google-oauth').OAuth2Strategy,
    LinkedinStrategy = require('passport-linkedin').Strategy,
    User = mongoose.model('User'),
    config = require('meanio').loadConfig(),
    Team = mongoose.model('Team'),
    _ = require('lodash'),
    async = require('async');
// Test
module.exports = function (passport) {

    // Serialize the user id to push into the session
    passport.serializeUser(function (user, done) {
        done(null, user.id);
    });

    // Deserialize the user object based on a pre-serialized token
    // which is the user id
    passport.deserializeUser(function (id, done) {
        User.findOne({
            _id: id
        }, '-salt -hashed_password', function (err, user) {
            done(err, user);
        });
    });

    // Use local strategy
    passport.use(new LocalStrategy({
        usernameField: 'email', passwordField: 'password'
    }, function (email, password, done) {
        User.findOne({
            email: email
        }, function (err, user) {
            if (err) {
                return done(err);
            }
            if (!user) {
                return done(null, false, {
                    message: 'Unknown user'
                });
            }
            if (!user.authenticate(password)) {
                return done(null, false, {
                    message: 'Invalid password'
                });
            }
            return done(null, user);
        });
    }));

    // Use twitter strategy
    passport.use(new TwitterStrategy({
        consumerKey: config.twitter.clientID,
        consumerSecret: config.twitter.clientSecret,
        callbackURL: config.twitter.callbackURL
    }, function (token, tokenSecret, profile, done) {
        return ssoAuth(profile, 'twitter', done);
    }));

    var multipleStrategyUser = null,
        loginStrategy, profile, user;

    /**
     * If a user with this email has logged on before using another method, add this SSO id and log the user in
     * @param callback
     * @returns {*}
     */
    var checkMultipleSsoMethods = function (callback) {
        // If this strategy returns email, search by email. If not, such as Twitter, SORRY
        if (_.has(profile, 'emails')) {
            // Find the user based on the first email returned
            // @todo This is weak, need to check all emails
            User.findOne({
                email: profile.emails[0].value
            }, function (err, user) {
                // Return on error
                if (err) {
                    return callback('Error on finding user by email');
                }
                // If a user was found using a different login strategy
                if (user) {
                    // Add this login strategy to this user's account
                    user[loginStrategy] = profile;
                    user.save(function (err) {
                        if (err) {
                            return callback(new Error(err));
                        }
                        // Give the next function access to this user
                        multipleStrategyUser = user;
                        return callback(null, user);
                    });
                } else {
                    return callback();
                }
            });
        } else {
            return callback();
        }
    };

    /**
     * If a user was not found using the current SSO method or via email, then create a new user
     * @param callback
     * @returns {*}
     */
    var createNewUserSso = function (callback) {
        if (multipleStrategyUser) {
            return callback(null, multipleStrategyUser);
        }
        // If we've made it this far, go ahead and create the user
        var userObj = {
            name: profile.displayName,
            provider: loginStrategy,
            roles: ['authenticated']
        };
        // Add the details from the login strategy return
        userObj[loginStrategy] = profile._json;
        // Add email if this login strategy has it
        if (_.has(profile, 'emails')) {
            userObj.email = profile.emails[0].value;
        } else {
            // Handling twitter's dumb ass
            userObj.email = profile.id + '@twitter.com';
        }
        user = new User(userObj);
        // Create a team for this user
        var team = new Team({
            name: user.name + '\'s Team'
        });
        // Save the team
        team.save(function (err) {
            if (err) {
                return callback(new Error(err));
            }
            // Add user to team
            user.teams.push(team._id);
            // Save the user
            user.save(function (err) {
                if (err) {
                    // Done from passport takes three parameters: error, false for failure, something truthy for
                    // success, and finally, object with info
                    return callback(new Error(err));
                } else {
                    return callback(null, user);
                }
            });
        });
    };

    /**
     * Generalize SSO authorization function
     *
     * @todo REFACTOR ME
     *
     * @param thisProfile
     * @param thisLoginStrategy
     * @param done
     */
    var ssoAuth = function (thisProfile, thisLoginStrategy, done) {
        var userSearch = {};
        loginStrategy = thisLoginStrategy;
        profile = thisProfile;
        // Search by the login strategy id (some are strings, some are ints...)
        userSearch[loginStrategy + '.id'] = loginStrategy === 'twitter' ? parseInt(profile.id) : profile.id;
        return User.findOne(userSearch, function (err, user) {
            // Return on error
            if (err) {
                return done(err);
            }
            // If the user found, let's log that puppy in
            if (user) {
                return done(err, user);
            }
            // Check for users this email, different strategy. Then create or log the user in
            return async.series([checkMultipleSsoMethods, createNewUserSso],
            // Log the user in, if one was found
            function (err, user) {
                if (err) {
                    return done(null, false, {
                        message: loginStrategy + ' login failed, email already used by other login strategy'}
                    );
                }
                return done(err, user[1]);
            });
        });
    };

    // Use facebook strategy
    passport.use(new FacebookStrategy({
        clientID: config.facebook.clientID,
        clientSecret: config.facebook.clientSecret,
        callbackURL: config.facebook.callbackURL
    }, function (accessToken, refreshToken, profile, done) {
        ssoAuth(profile, 'facebook', done);
    }));

    // Use github strategy
    passport.use(new GitHubStrategy({
        clientID: config.github.clientID,
        clientSecret: config.github.clientSecret,
        callbackURL: config.github.callbackURL
    }, function (accessToken, refreshToken, profile, done) {
        User.findOne({
            'github.id': profile.id
        }, function (err, user) {
            if (user) {
                return done(err, user);
            }
            user = new User({
                name: profile.displayName,
                email: profile.emails[0].value,
                username: profile.username,
                provider: 'github',
                github: profile._json,
                roles: ['authenticated']
            });
            user.save(function (err) {
                if (err) {
                    console.log(err);
                    return done(null, false,
                    {message: 'Github login failed, email already used by other login strategy'});
                } else {
                    return done(err, user);
                }
            });
        });
    }));

    // Use google strategy
    passport.use(new GoogleStrategy({
        clientID: config.google.clientID,
        clientSecret: config.google.clientSecret,
        callbackURL: config.google.callbackURL
    }, function (accessToken, refreshToken, profile, done) {
        return ssoAuth(profile, 'google', done);
    }));

    // use linkedin strategy
    passport.use(new LinkedinStrategy({
        consumerKey: config.linkedin.clientID,
        consumerSecret: config.linkedin.clientSecret,
        callbackURL: config.linkedin.callbackURL,
        profileFields: ['id', 'first-name', 'last-name', 'email-address']
    }, function (accessToken, refreshToken, profile, done) {
        User.findOne({
            'linkedin.id': profile.id
        }, function (err, user) {
            if (user) {
                return done(err, user);
            }
            user = new User({
                name: profile.displayName,
                email: profile.emails[0].value,
                username: profile.emails[0].value,
                provider: 'linkedin',
                roles: ['authenticated']
            });
            user.save(function (err) {
                if (err) {
                    console.log(err);
                    return done(null, false,
                    {message: 'LinkedIn login failed, email already used by other login strategy'});
                } else {
                    return done(err, user);
                }
            });
        });
    }));
};
<|endoftext|>


<commit_before>//Dont change it
requirejs(['ext_editor_1', 'jquery_190', 'raphael_210'],
    function (ext, $, TableComponent) {

        var cur_slide = {};

        ext.set_start_game(function (this_e) {
        });

        ext.set_process_in(function (this_e, data) {
            cur_slide["in"] = data[0];
        });

        ext.set_process_out(function (this_e, data) {
            cur_slide["out"] = data[0];
        });

        ext.set_process_ext(function (this_e, data) {
            cur_slide.ext = data;
            this_e.addAnimationSlide(cur_slide);
            cur_slide = {};
        });

        ext.set_process_err(function (this_e, data) {
            cur_slide['error'] = data[0];
            this_e.addAnimationSlide(cur_slide);
            cur_slide = {};
        });

        ext.set_animate_success_slide(function (this_e, options) {
            var $h = $(this_e.setHtmlSlide('

'));
            this_e.setAnimationHeight(115);
        });

        ext.set_animate_slide(function (this_e, data, options) {
            var $content = $(this_e.setHtmlSlide(ext.get_template('animation'))).find('.animation-content');
            if (!data) {
                console.log("data is undefined");
                return false;
            }
            if (data.error) {
                $content.find('.call').html('Fail: checkio(' + JSON.stringify(data.in) + ')');
                $content.find('.output').html(data.error.replace(/\n/g, ","));

                $content.find('.output').addClass('error');
                $content.find('.call').addClass('error');
                $content.find('.answer').remove();
                $content.find('.explanation').remove();
                this_e.setAnimationHeight($content.height() + 60);
                return false;
            }

            var checkioInput = data.in;
            var rightResult = data.ext["answer"];
            var userResult = data.out;
            var result = data.ext["result"];
            var result_addon = data.ext["result_addon"];

            //if you need additional info from tests (if exists)
            var explanation = data.ext["explanation"];

            $content.find('.output').html(' Your result: ' + JSON.stringify(userResult));

            if (!result) {
                $content.find('.call').html('Fail: checkio(' + JSON.stringify(checkioInput) + ')');
                $content.find('.answer').html('Right result: ' + JSON.stringify(rightResult));
                $content.find('.answer').addClass('error');
                $content.find('.output').addClass('error');
                $content.find('.call').addClass('error');
            }
            else {
                $content.find('.call').html('Pass: checkio(' + JSON.stringify(checkioInput) + ')');
                $content.find('.answer').remove();
            }
            //Dont change the code before it

            //Your code here about test explanation animation
            //$content.find(".explanation").html("Something text for example");
            //
            //
            //
            //
            //

            this_e.setAnimationHeight($content.height() + 60);

        });

        var colorOrange4 = "#F0801A";
        var colorOrange3 = "#FA8F00";
        var colorOrange2 = "#FAA600";
        var colorOrange1 = "#FABA00";

        var colorBlue4 = "#294270";
        var colorBlue3 = "#006CA9";
        var colorBlue2 = "#65A1CF";
        var colorBlue1 = "#8FC7ED";

        var colorGrey4 = "#737370";
        var colorGrey3 = "#D9E9E";
        var colorGrey2 = "#C5C6C6";
        var colorGrey1 = "#EBEDED";

        var colorWhite = "#FFFFFF";
        //Your Additional functions or objects inside scope
        //
        //
        //

    }
);
<commit_msg>fix color<commit_after>//Dont change it
requirejs(['ext_editor_1', 'jquery_190', 'raphael_210'],
    function (ext, $, TableComponent) {

        var cur_slide = {};

        ext.set_start_game(function (this_e) {
        });

        ext.set_process_in(function (this_e, data) {
            cur_slide["in"] = data[0];
        });

        ext.set_process_out(function (this_e, data) {
            cur_slide["out"] = data[0];
        });

        ext.set_process_ext(function (this_e, data) {
            cur_slide.ext = data;
            this_e.addAnimationSlide(cur_slide);
            cur_slide = {};
        });

        ext.set_process_err(function (this_e, data) {
            cur_slide['error'] = data[0];
            this_e.addAnimationSlide(cur_slide);
            cur_slide = {};
        });

        ext.set_animate_success_slide(function (this_e, options) {
            var $h = $(this_e.setHtmlSlide('

'));
            this_e.setAnimationHeight(115);
        });

        ext.set_animate_slide(function (this_e, data, options) {
            var $content = $(this_e.setHtmlSlide(ext.get_template('animation'))).find('.animation-content');
            if (!data) {
                console.log("data is undefined");
                return false;
            }
            if (data.error) {
                $content.find('.call').html('Fail: checkio(' + JSON.stringify(data.in) + ')');
                $content.find('.output').html(data.error.replace(/\n/g, ","));

                $content.find('.output').addClass('error');
                $content.find('.call').addClass('error');
                $content.find('.answer').remove();
                $content.find('.explanation').remove();
                this_e.setAnimationHeight($content.height() + 60);
                return false;
            }

            var checkioInput = data.in;
            var rightResult = data.ext["answer"];
            var userResult = data.out;
            var result = data.ext["result"];
            var result_addon = data.ext["result_addon"];

            //if you need additional info from tests (if exists)
            var explanation = data.ext["explanation"];

            $content.find('.output').html(' Your result: ' + JSON.stringify(userResult));

            if (!result) {
                $content.find('.call').html('Fail: checkio(' + JSON.stringify(checkioInput) + ')');
                $content.find('.answer').html('Right result: ' + JSON.stringify(rightResult));
                $content.find('.answer').addClass('error');
                $content.find('.output').addClass('error');
                $content.find('.call').addClass('error');
            }
            else {
                $content.find('.call').html('Pass: checkio(' + JSON.stringify(checkioInput) + ')');
                $content.find('.answer').remove();
            }
            //Dont change the code before it

            //Your code here about test explanation animation
            //$content.find(".explanation").html("Something text for example");
            //
            //
            //
            //
            //

            this_e.setAnimationHeight($content.height() + 60);

        });

        var colorOrange4 = "#F0801A";
        var colorOrange3 = "#FA8F00";
        var colorOrange2 = "#FAA600";
        var colorOrange1 = "#FABA00";

        var colorBlue4 = "#294270";
        var colorBlue3 = "#006CA9";
        var colorBlue2 = "#65A1CF";
        var colorBlue1 = "#8FC7ED";

        var colorGrey4 = "#737370";
        var colorGrey3 = "#9D9E9E";
        var colorGrey2 = "#C5C6C6";
        var colorGrey1 = "#EBEDED";

        var colorWhite = "#FFFFFF";
        //Your Additional functions or objects inside scope
        //
        //
        //

    }
);
<|endoftext|>


<commit_before>// Dependencies

let builder = require('focus').component.builder;
let type = require('focus').component.types;
let React = require('react');
let words = require('lodash/string/words');

// Components

let Scope = require('./scope').component;

// Mixins

let stylable = require('../../mixin/stylable');
let i18n = require('../../common/i18n/mixin');

/**
 * SearchBar component
 * @type {Object}
 */
let SearchBar = {
    mixins: [i18n, stylable],
    displayName: 'SearchBar',
    getDefaultProps() {
        return {
            placeholder: 'Enter your search here...',
            value: 'defaultValue',
            scope: undefined,
            scopes: [],
            minChar: 0,
            loading: false,
            helpTranslationPath: 'search.bar.help'
        };
    },
    propTypes: {
        placeholder: type('string'),
        value: type('string'),
        scope: type(['string', 'number']),
        scopes: type('array'),
        minChar: type('number'),
        loading: type('bool'),
        helpTranslationPath: type('string')
    },
    getInitialState() {
        return {
            value: this.props.value,
            scope: this.props.scope,
            loading: this.props.loading
        };
    },
    componentWillReceiveProps(newProps) {
        if (newProps && newProps.loading !== undefined) {
            this.setState({loading: newProps.loading, scope: newProps.scope});
        }
    },
    componentDidMount() {
        React.findDOMNode(this.refs.query).focus();
    },
    getValue() {
        return {
            scope: this.refs.scope.getValue(),
            query: React.findDOMNode(this.refs.query).value
        };
    },
    _getClassName() {
        return `form-control`;
    },
    _handleChange() {
        if (this.props.handleChange) {
            return this.props.handleChange(this.getValue());
        }
    },
    _handleKeyUp(event) {
        let val = event.target.value;
        if (val.length >= this.props.minChar) {
            if (this.props.handleKeyUp) {
                this.props.handleKeyUp(event);
            }
            this._handleChange();
        }
    },
    _handleChangeScope(event) {
        this._focusQuery();
        //If query not empty
        let query = this.getValue().query;
        if (!query || 0 === query.length) {
            return;
        }
        if (this.props.handleChangeScope) {
            this.props.handleChangeScope(event);
        }
        this._handleChange();
    },
    _handleOnClickScope() {
        this.setState({scope: this.refs.scope.getValue()}, this._handleChangeScope(event));
    },
    _renderHelp() {
        return (

{this.i18n(this.props.helpTranslationPath)}

        );
    },
    _focusQuery() {
        React.findDOMNode(this.refs.query).focus();
    },
    setStateFromSubComponent() {
        return this.setState(this.getValue(), this._focusQuery);
    },
    render() {
        let loadingClassName = this.props.loading ? 'sb-loading' : '';
        return (
            <div className={`${this._getStyleClassName()}`} data-focus='search-bar'>

<Scope handleOnClick={this._handleOnClickScope} list={this.props.scopes} ref='scope' value={this.state.scope}/>

                    <input autofocus className={this._getClassName()} onKeyUp={this._handleKeyUp} ref='query'  type='search' placeholder={this.props.placeholder} />
                    <div className={`sb-spinner three-quarters-loader ${loadingClassName}`}>

                {this._renderHelp()}

        );
    }
};

module.exports = builder(SearchBar);
<commit_msg>[search-bar] Add the query as initial param.<commit_after>// Dependencies

let builder = require('focus').component.builder;
let type = require('focus').component.types;
let React = require('react');
let words = require('lodash/string/words');

// Components

let Scope = require('./scope').component;

// Mixins

let stylable = require('../../mixin/stylable');
let i18n = require('../../common/i18n/mixin');

/**
 * SearchBar component
 * @type {Object}
 */
let SearchBar = {
    mixins: [i18n, stylable],
    displayName: 'SearchBar',
    getDefaultProps() {
        return {
            placeholder: 'Enter your search here...',
            value: '',
            scope: undefined,
            scopes: [],
            minChar: 0,
            loading: false,
            helpTranslationPath: 'search.bar.help'
        };
    },
    propTypes: {
        placeholder: type('string'),
        value: type('string'),
        scope: type(['string', 'number']),
        scopes: type('array'),
        minChar: type('number'),
        loading: type('bool'),
        helpTranslationPath: type('string')
    },
    getInitialState() {
        return {
            value: this.props.value,
            scope: this.props.scope,
            loading: this.props.loading
        };
    },
    componentWillReceiveProps(newProps) {
        if (newProps && newProps.loading !== undefined) {
            this.setState({loading: newProps.loading, scope: newProps.scope});
        }
    },
    componentDidMount() {
        React.findDOMNode(this.refs.query).focus();
    },
    getValue() {
        return {
            scope: this.refs.scope.getValue(),
            query: React.findDOMNode(this.refs.query).value
        };
    },
    _getClassName() {
        return `form-control`;
    },
    _handleChange() {
        if (this.props.handleChange) {
            return this.props.handleChange(this.getValue());
        }
    },
    _handleKeyUp(event) {

          this.setState({value: event.target.value}, ()=>{
            if (this.state.value.length >= this.props.minChar) {
              if (this.props.handleKeyUp) {
                  this.props.handleKeyUp(event);
              }
              this._handleChange();
            }
          });

    },
    _handleChangeScope(event) {
        this._focusQuery();
        //If query not empty
        let query = this.getValue().query;
        if (!query || 0 === query.length) {
            return;
        }
        if (this.props.handleChangeScope) {
            this.props.handleChangeScope(event);
        }
        this._handleChange();
    },
    _handleOnClickScope() {
        this.setState({scope: this.refs.scope.getValue()}, this._handleChangeScope(event));
    },
    _renderHelp() {
        return (

{this.i18n(this.props.helpTranslationPath)}

        );
    },
    _focusQuery() {
        React.findDOMNode(this.refs.query).focus();
    },
    setStateFromSubComponent() {
        return this.setState(this.getValue(), this._focusQuery);
    },
    render() {
        let loadingClassName = this.props.loading ? 'sb-loading' : '';
        return (
            <div className={`${this._getStyleClassName()}`} data-focus='search-bar'>

<Scope handleOnClick={this._handleOnClickScope} list={this.props.scopes} ref='scope' value={this.state.scope}/>

                    <input autofocus className={this._getClassName()} onChange={this._handleKeyUp} ref='query'  type='search' placeholder={this.props.placeholder} value={this.state.value} />
                    <div className={`sb-spinner three-quarters-loader ${loadingClassName}`}>

                {this._renderHelp()}

        );
    }
};

module.exports = builder(SearchBar);
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies
 */
var path = require('path'),
	mongoose = require('mongoose'),
	Discussion = mongoose.model('Discussion'),
	errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller'));

/**
 * Create a discussion
 */
exports.create = function (req, res) {
	var discussion = new Discussion(req.body);
	discussion.public = req.body.visibility === 'public';
	discussion.recipient = ['teacher'];
	if (req.body.recipient === 'supervisor') {
		discussion.recipient.push('supervisor');
	}
	discussion.user = req.user;
	discussion.save(function (err) {
		if (err) {
			console.log(err);
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		}
		res.json(discussion);
	});
};

/**
 * Answer a discussion
 */
exports.answer = function (req, res) {
	var answer = {
		user: req.user,
		date: Date.now(),
		message: req.body.answer
	};
	// Add answer to discussion
	var discussion = req.discussion;
	discussion.answers.push(answer);
	discussion.save(function (err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		}
		res.json(answer);
	});
};

/**
 * Show the current discussion
 */
exports.read = function (req, res) {
	res.json(req.discussion);
};

/**
 * List of discussions
 */
exports.list = function (req, res) {
	// Find list of discussions
	Discussion.find({}).sort({created: 1}).exec(function (err, discussions) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		}
		res.json(discussions);
	});
};

/**
 * Discussion middleware
 */
exports.discussionByID = function (req, res, next, id) {
	if (! mongoose.Types.ObjectId.isValid(id)) {
		return res.status(400).send({
			message: 'Discussion is invalid.'
		});
	}

	Discussion.findById(id, 'title message user created answers').deepPopulate('user answers.user').exec(function (err, discussion) {
		if (err) {
			return next(err);
		}
		if (! discussion) {
			return res.status(404).send({
				message: 'No discussion with that identifier has been found.'
			});
		}
	    req.discussion = discussion;
		next();
	});
};
<commit_msg>Fix permissions for discussions<commit_after>'use strict';

/**
 * Module dependencies
 */
var path = require('path'),
	mongoose = require('mongoose'),
	Discussion = mongoose.model('Discussion'),
	errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller'));

/**
 * Create a discussion
 */
exports.create = function (req, res) {
	var discussion = new Discussion(req.body);
	discussion.public = req.body.visibility === 'public';
	discussion.recipient = ['teacher'];
	if (req.body.recipient === 'supervisor') {
		discussion.recipient.push('supervisor');
	}
	discussion.user = req.user;
	discussion.save(function (err) {
		if (err) {
			console.log(err);
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		}
		res.json(discussion);
	});
};

/**
 * Answer a discussion
 */
exports.answer = function (req, res) {
	var answer = {
		user: req.user,
		date: Date.now(),
		message: req.body.answer
	};
	// Add answer to discussion
	var discussion = req.discussion;
	discussion.answers.push(answer);
	discussion.save(function (err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		}
		res.json(answer);
	});
};

/**
 * Show the current discussion
 */
exports.read = function (req, res) {
	res.json(req.discussion);
};

/**
 * List of discussions
 */
exports.list = function (req, res) {
	// Find list of discussions
	Discussion.find({}).populate('user', 'displayName').sort({created: 1}).exec(function (err, discussions) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		}
		var filteredDiscussions = [];
		for (var i = 0; i < discussions.length; i++) {
			// If not admin, teacher or supervisor, only select discussions by logged user
			if (req.user.roles.indexOf('admin') === -1 && req.user.roles.indexOf('teacher') === -1 && req.user.roles.indexOf('supervisor') === -1) {
				if (discussions[i].user.id === req.user.id) {
					filteredDiscussions.push(discussions[i]);
				}
			}
		}
		res.json(filteredDiscussions);
	});
};

/**
 * Discussion middleware
 */
exports.discussionByID = function (req, res, next, id) {
	if (! mongoose.Types.ObjectId.isValid(id)) {
		return res.status(400).send({
			message: 'Discussion is invalid.'
		});
	}

	Discussion.findById(id, 'title message user created answers').deepPopulate('user answers.user').exec(function (err, discussion) {
		if (err) {
			return next(err);
		}
		if (! discussion) {
			return res.status(404).send({
				message: 'No discussion with that identifier has been found.'
			});
		}
	    req.discussion = discussion;
		next();
	});
};
<|endoftext|>


<commit_before>var Discord = require('discord.js');

var ytdl = require('ytdl-core');
var request = require('request');
var url = require('url');

// Output version information in console
var git = require('git-rev');

git.short(commit => git.branch(branch => {
  console.log(`Lethe#${branch}@${commit}`);
}));

var shouldDisallowQueue = require('./lib/permission-checks.js');
var VideoFormat = require('./lib/video-format.js');
var YoutubeStream = require('./lib/youtube-stream.js');
var Saved = require('./lib/saved.js');
Saved.read();

var Config = require('./lib/config.js');

var client = new Discord.Client();

// Handle discord.js warnings
client.on('warn', (m) => console.log('[warn]', m));
client.on('debug', (m) => console.log('[debug]', m));

var playQueue = [];
var boundChannel = false;
var currentStream = false;
var currentVideo = false;

var botMention = false;

// Handling api key
if (process.argv[4]) {
  var apiKey = process.argv[4];
} else {
  var apiKey = false;
}

client.on('ready', () => {
  botMention = `<@${client.user.id}>`;
  console.log(`Bot mention: ${botMention}`);
});

client.on('message', m => {
  if (!botMention) return;
  if (client.user.id == m.author.id) return;

  if (m.content.startsWith(`${botMention} info`)) {
    if (!checkCommand(m, 'info')) return;
    git.short(commit => git.branch(branch => {
      client.reply(m, `Version: \`Lethe#${branch}@${commit}\`. Info about Lethe can be found at https://github.com/meew0/Lethe.`);
    }));
    return;
  }

  if (m.content.startsWith(`${botMention} i`)) { // init
    if (!checkCommand(m, 'init')) return;
    if (boundChannel) return;
    var channelToJoin = spliceArguments(m.content)[1];
    for (var channel of m.channel.server.channels) {
      if (channel instanceof Discord.VoiceChannel) {
        if (!channelToJoin || channel.name === channelToJoin) {
          boundChannel = m.channel;
          client.reply(m, `Binding to text channel <#${boundChannel.id}> and voice channel **${channel.name}** \`(${channel.id})\``);
          client.joinVoiceChannel(channel).catch(error);
          break;
        }
      }
    }
  }

  if (m.content.startsWith(`${botMention} d`)) { // destroy
    if (!checkCommand(m, 'destroy')) return;
    if (!boundChannel) return;
    client.reply(m, `Unbinding from <#${boundChannel.id}> and destroying voice connection`);
    playQueue = [];
    client.internal.leaveVoiceChannel();
    boundChannel = false;
    currentStream = false;
    currentVideo = false;
    return;
  }

  // Only respond to other messages inside the bound channel
  if (!m.channel.equals(boundChannel)) return;

  if (m.content.startsWith(`${botMention} n`)) { // next
    if (!checkCommand(m, 'next')) return;
    playStopped();
  }

  if (m.content.startsWith(`${botMention} yq`) // youtube query
    || m.content.startsWith(`${botMention} qq`) // queue query
    || m.content.startsWith(`${botMention} pq`) // play query
    || m.content.startsWith(`${botMention} ytq`)) {

    if (!checkCommand(m, 'yq')) return;

    if (apiKey == false) {
      client.reply(m, 'Search is disabled (no API KEY found).');
      return;
    }

    var args = spliceArguments(m.content)[1];

    if (!args) {
      client.reply(m, 'You need to specify a search parameter.');
      return;
    }

    var requestUrl = 'https://www.googleapis.com/youtube/v3/search' +
      `?part=snippet&q=${escape(args)}&key=${apiKey}`;

    request(requestUrl, (error, response, body) => {
      if (!error && response.statusCode == 200) {
        body = JSON.parse(body);
        if (body.items.length == 0) {
          client.reply(m, 'Your query gave 0 results.');
          return;
        }

        var vid = body.items[0].id.videoId;
        getInfoAndQueue(vid, m);
      } else {
        client.reply(m, 'There was an error searching.');
        return;
      }
    });

    return; // have to stop propagation
  }

  if (m.content.startsWith(`${botMention} pl`)) { // playlist
    if (!checkCommand(m, 'pl')) return;

    if (apiKey == false) {
      client.reply(m, 'Playlist adding is disabled (no API KEY found).');
      return;
    }

    var pid = spliceArguments(m.content)[1];

    if (!pid) {
      client.reply(m, 'You need to specify a playlist ID!');
      return;
    }

    var requestUrl = 'https://www.googleapis.com/youtube/v3/playlistItems' +
      `?part=contentDetails&maxResults=50&playlistId=${pid}&key=${apiKey}`;

    request(requestUrl, (error, response, body) => {
      if (!error && response.statusCode == 200) {
        body = JSON.parse(body);
        if (body.items.length == 0) {
          client.reply(m, 'That playlist has no videos.');
          return;
        }

        client.reply(m, `Loading ${body.items.length} videos...`);
        var suppress = 0;
        body.items.forEach((elem, idx) => {
          var vid = elem.contentDetails.videoId;
          if (idx == 1) suppress = body.items.length - 2;
          if (idx == 2) suppress = -1;
          getInfoAndQueue(vid, m, suppress);
        });
      } else {
        client.reply(m, 'There was an error finding playlist with that id.');
        return;
      }
    });

    return;
  }

  if (m.content.startsWith(`${botMention} y`) // youtube
    || m.content.startsWith(`${botMention} q`) // queue
    || m.content.startsWith(`${botMention} p`)) { // play

    if (!checkCommand(m, 'yt')) return;

    var vidList = spliceArguments(m.content)[1];

    var vids = vidList.split(',');
    var suppress = 0;
    vids.forEach((vid, idx) => {
      if (idx == 1) suppress = vids.length - 2;
      if (idx == 2) suppress = -1;
      parseVidAndQueue(vid, m, suppress);
    });
  }

  if (m.content.startsWith(`${botMention} r`)) { // replay
    if (!checkCommand(m, 'replay')) return;
    playQueue.push(currentVideo);
    client.reply(m, `Queued ${VideoFormat.prettyPrint(currentVideo)}`);
  }

  if (m.content.startsWith(`${botMention} sh`)) { // shuffle
    if (!checkCommand(m, 'shuffle')) return;
    if (playQueue.length < 2) {
      client.reply(m, 'Not enough songs in the queue.');
      return;
    } else {
      shuffle(playQueue);
      client.reply(m, 'Songs in the queue have been shuffled.');
    }

    return;
  }

  if (m.content.startsWith(`${botMention} link`)) {
    if (!checkCommand(m, 'link')) return;
    if (currentVideo) client.reply(m, `<${currentVideo.loaderUrl}>`);
    return; // stop propagation
  }

  if (m.content.startsWith(`${botMention} list s`)) { // list saved
    if (!checkCommand(m, 'list saved')) return;
    var formattedList = 'Here are the videos currently saved: \n';
    for (var key in Saved.saved.videos) {
      if (Saved.saved.videos.hasOwnProperty(key)) {
        formattedList += `*${key}*: ${VideoFormat.prettyPrint(Saved.saved.videos[key])}\n`;
      }
    }

    client.reply(m, formattedList);
    return; // so list doesn't get triggered
  }

  if (m.content.startsWith(`${botMention} l`)) { // list
    if (!checkCommand(m, 'list')) return;
    var formattedList = 'Here are the videos currently in the play queue, from first added to last added: \n';
    formattedList += `Currently playing: ${VideoFormat.prettyPrintWithUser(currentVideo)}\n`;

    var shouldBreak = false;

    playQueue.forEach((video, idx) => {
      if (shouldBreak) return;

      var formattedVideo = `${idx + 1}. ${VideoFormat.prettyPrintWithUser(video)}\n`;

      if ((formattedList.length + formattedVideo.length) > 1950) {
        formattedList += `... and ${playQueue.length - idx} more`;
        shouldBreak = true;
      } else {
        formattedList += formattedVideo;
      }
    });
    client.reply(m, formattedList);
  }

  if (m.content.startsWith(`${botMention} s`)) { // save
    if (!checkCommand(m, 'save')) return;
    var argument = spliceArguments(m.content)[1];
    if (!argument) {
      client.reply(m, 'You need to specify a video and a keyword!');
      return;
    }

    var splitArgs = spliceArguments(argument, 1);

    var vid = splitArgs[0];

    if (vid === 'current') {
      if (currentVideo) vid = currentVideo.vid;
      else {
        client.reply(m, `Couldn't retrieve video information of current video!`);
      }
    }

    var requestUrl = 'http://www.youtube.com/watch?v=' + vid;
    ytdl.getInfo(requestUrl, (err, info) => {
      if (err) handleYTError(err);
      else saveVideo(info, vid, splitArgs[1], m);
    });
  }

  if (m.content.startsWith(`${botMention} t`)) { // time
    if (!checkCommand(m, 'time')) return;
    var streamTime = client.internal.voiceConnection.streamTime; // in ms
    var videoTime = currentVideo.length_seconds;
    client.reply(m, `${VideoFormat.prettyTime(streamTime)} / ${VideoFormat.prettyTime(videoTime * 1000)} (${(streamTime / (videoTime * 10)).toFixed(2)} %)`);
  }
});

function parseVidAndQueue(vid, m, suppress) {
  if (/^http/.test(vid)) {
    if (url.parse(vid, true).query.v) {
      vid = url.parse(vid, true).query.v;
    }
  }

  vid = Saved.possiblyRetrieveVideo(vid);
  if (!vid) {
    client.reply(m, 'You need to specify a video!');
    return;
  }

  getInfoAndQueue(vid, m, suppress);
}

function getInfoAndQueue(vid, m, suppress) {
  requestUrl = 'http://www.youtube.com/watch?v=' + vid;
  ytdl.getInfo(requestUrl, (err, info) => {
    if (err) handleYTError(err);
    else {
      info.vid = vid;
      possiblyQueue(info, m.author.id, m, suppress);
    }
  });
}

function spliceArguments(message, after) {
  after = after || 2;
  var rest = message.split(' ');
  var removed = rest.splice(0, after);
  return [removed.join(' '), rest.join(' ')];
}

function saveVideo(video, vid, keywords, m) {
  simplified = VideoFormat.simplify(video, vid);
  if (Saved.saved.videos.hasOwnProperty(keywords)) client.reply(m, `Warning: ${VideoFormat.simplePrint(Saved.saved.videos[keywords])} is already saved as *${keywords}*! Overwriting.`);

  var key;
  if (key = Saved.isVideoSaved(vid)) client.reply(m, `Warning: This video is already saved as *${key}*! Adding it anyway as *${keywords}*.`);

  Saved.saved.videos[keywords] = simplified;
  client.reply(m, `Saved video ${VideoFormat.prettyPrint(video)} as *${keywords}*`);
  Saved.write();
}

function possiblyQueue(video, userId, m, suppress) {
  video.userId = userId;
  suppress = (suppress === undefined) ? false : suppress;
  reason = shouldDisallowQueue(playQueue, video, Config);
  if (!userIsAdmin(userId) && reason) {
    client.reply(m, `You can't queue ${VideoFormat.simplePrint(video)} right now! Reason: ${reason}`);
  } else {
    playQueue.push(video);
    if (suppress == 0) client.reply(m, `Queued ${VideoFormat.prettyPrint(video)}`);
    else if (suppress > -1) client.reply(m, `Queued ${VideoFormat.prettyPrint(video)} and ${suppress} other videos`);

    // Start playing if not playing yet
    if (!currentVideo) nextInQueue();
  }
}

function handleYTError(err) {
  if (err.toString().indexOf('Code 150') > -1) {
    // Video unavailable in country
    boundChannel.sendMessage('This video is unavailable in the country the bot is running in! Please try a different video.');
  } else if (err.message == 'Could not extract signature deciphering actions') {
    boundChannel.sendMessage('YouTube streams have changed their formats, please update `ytdl-core` to account for the change!');
  } else if (err.message == 'status code 404') {
    boundChannel.sendMessage('That video does not exist!');
  } else {
    boundChannel.sendMessage('An error occurred while getting video information! Please try a different video.');
  }

  console.log(err.toString());
}

function playStopped() {
  if (client.internal.voiceConnection) client.internal.voiceConnection.stopPlaying();

  boundChannel.sendMessage(`Finished playing ${VideoFormat.simplePrint(currentVideo)}`);
  currentVideo = false;
  nextInQueue();
}

function play(video) {
  currentVideo = video;
  if (client.internal.voiceConnection) {
    var connection = client.internal.voiceConnection;
    currentStream = YoutubeStream.getStream(video.loaderUrl);

    currentStream.on('error', (err) => {
      boundChannel.sendMessage(`There was an error during playback! **${err}**`);
    });

    currentStream.on('end', () => setTimeout(playStopped, Config.timeOffset || 8000)); // 8 second leeway for bad timing
    connection.playRawStream(currentStream).then(intent => {
      boundChannel.sendMessage(`Playing ${VideoFormat.prettyPrint(video)}`);
    });
  }
}

function userIsAdmin(userId) {
  return Config.adminIds.indexOf(userId) > -1;
}

function checkCommand(m, command) {
  if (Config.commandsRestrictedToAdmins[command]) {
    if (!userIsAdmin(m.author.id)) {
      client.reply(m, `You don't have permission to execute that command!`);
      return false;
    }
  }

  return true;
}

function nextInQueue() {
  if (playQueue.length > 0) {
    next = playQueue.shift();
    play(next);
  }
}

function shuffle(array) {
  var counter = array.length;
  var temp;
  var index;

  // While there are elements in the array
  while (counter > 0) {
    index = Math.floor(Math.random() * counter);

    counter--;

    temp = array[counter];
    array[counter] = array[index];
    array[index] = temp;
  }

  return array;
}

function error(argument) {
  console.log(argument.stack);
}

// Email and password over command line
client.login(process.argv[2], process.argv[3]).catch((e) => console.log(e));
<commit_msg>Add lastVideo to hold a reference to the last played video<commit_after>var Discord = require('discord.js');

var ytdl = require('ytdl-core');
var request = require('request');
var url = require('url');

// Output version information in console
var git = require('git-rev');

git.short(commit => git.branch(branch => {
  console.log(`Lethe#${branch}@${commit}`);
}));

var shouldDisallowQueue = require('./lib/permission-checks.js');
var VideoFormat = require('./lib/video-format.js');
var YoutubeStream = require('./lib/youtube-stream.js');
var Saved = require('./lib/saved.js');
Saved.read();

var Config = require('./lib/config.js');

var client = new Discord.Client();

// Handle discord.js warnings
client.on('warn', (m) => console.log('[warn]', m));
client.on('debug', (m) => console.log('[debug]', m));

var playQueue = [];
var boundChannel = false;
var currentStream = false;

// Video that is currently being played
var currentVideo = false;

// Last video played
var lastVideo = false;

var botMention = false;

// Handling api key
if (process.argv[4]) {
  var apiKey = process.argv[4];
} else {
  var apiKey = false;
}

client.on('ready', () => {
  botMention = `<@${client.user.id}>`;
  console.log(`Bot mention: ${botMention}`);
});

client.on('message', m => {
  if (!botMention) return;
  if (client.user.id == m.author.id) return;

  if (m.content.startsWith(`${botMention} info`)) {
    if (!checkCommand(m, 'info')) return;
    git.short(commit => git.branch(branch => {
      client.reply(m, `Version: \`Lethe#${branch}@${commit}\`. Info about Lethe can be found at https://github.com/meew0/Lethe.`);
    }));
    return;
  }

  if (m.content.startsWith(`${botMention} i`)) { // init
    if (!checkCommand(m, 'init')) return;
    if (boundChannel) return;
    var channelToJoin = spliceArguments(m.content)[1];
    for (var channel of m.channel.server.channels) {
      if (channel instanceof Discord.VoiceChannel) {
        if (!channelToJoin || channel.name === channelToJoin) {
          boundChannel = m.channel;
          client.reply(m, `Binding to text channel <#${boundChannel.id}> and voice channel **${channel.name}** \`(${channel.id})\``);
          client.joinVoiceChannel(channel).catch(error);
          break;
        }
      }
    }
  }

  if (m.content.startsWith(`${botMention} d`)) { // destroy
    if (!checkCommand(m, 'destroy')) return;
    if (!boundChannel) return;
    client.reply(m, `Unbinding from <#${boundChannel.id}> and destroying voice connection`);
    playQueue = [];
    client.internal.leaveVoiceChannel();
    boundChannel = false;
    currentStream = false;
    currentVideo = false;
    return;
  }

  // Only respond to other messages inside the bound channel
  if (!m.channel.equals(boundChannel)) return;

  if (m.content.startsWith(`${botMention} n`)) { // next
    if (!checkCommand(m, 'next')) return;
    playStopped();
  }

  if (m.content.startsWith(`${botMention} yq`) // youtube query
    || m.content.startsWith(`${botMention} qq`) // queue query
    || m.content.startsWith(`${botMention} pq`) // play query
    || m.content.startsWith(`${botMention} ytq`)) {

    if (!checkCommand(m, 'yq')) return;

    if (apiKey == false) {
      client.reply(m, 'Search is disabled (no API KEY found).');
      return;
    }

    var args = spliceArguments(m.content)[1];

    if (!args) {
      client.reply(m, 'You need to specify a search parameter.');
      return;
    }

    var requestUrl = 'https://www.googleapis.com/youtube/v3/search' +
      `?part=snippet&q=${escape(args)}&key=${apiKey}`;

    request(requestUrl, (error, response, body) => {
      if (!error && response.statusCode == 200) {
        body = JSON.parse(body);
        if (body.items.length == 0) {
          client.reply(m, 'Your query gave 0 results.');
          return;
        }

        var vid = body.items[0].id.videoId;
        getInfoAndQueue(vid, m);
      } else {
        client.reply(m, 'There was an error searching.');
        return;
      }
    });

    return; // have to stop propagation
  }

  if (m.content.startsWith(`${botMention} pl`)) { // playlist
    if (!checkCommand(m, 'pl')) return;

    if (apiKey == false) {
      client.reply(m, 'Playlist adding is disabled (no API KEY found).');
      return;
    }

    var pid = spliceArguments(m.content)[1];

    if (!pid) {
      client.reply(m, 'You need to specify a playlist ID!');
      return;
    }

    var requestUrl = 'https://www.googleapis.com/youtube/v3/playlistItems' +
      `?part=contentDetails&maxResults=50&playlistId=${pid}&key=${apiKey}`;

    request(requestUrl, (error, response, body) => {
      if (!error && response.statusCode == 200) {
        body = JSON.parse(body);
        if (body.items.length == 0) {
          client.reply(m, 'That playlist has no videos.');
          return;
        }

        client.reply(m, `Loading ${body.items.length} videos...`);
        var suppress = 0;
        body.items.forEach((elem, idx) => {
          var vid = elem.contentDetails.videoId;
          if (idx == 1) suppress = body.items.length - 2;
          if (idx == 2) suppress = -1;
          getInfoAndQueue(vid, m, suppress);
        });
      } else {
        client.reply(m, 'There was an error finding playlist with that id.');
        return;
      }
    });

    return;
  }

  if (m.content.startsWith(`${botMention} y`) // youtube
    || m.content.startsWith(`${botMention} q`) // queue
    || m.content.startsWith(`${botMention} p`)) { // play

    if (!checkCommand(m, 'yt')) return;

    var vidList = spliceArguments(m.content)[1];

    var vids = vidList.split(',');
    var suppress = 0;
    vids.forEach((vid, idx) => {
      if (idx == 1) suppress = vids.length - 2;
      if (idx == 2) suppress = -1;
      parseVidAndQueue(vid, m, suppress);
    });
  }

  if (m.content.startsWith(`${botMention} r`)) { // replay
    if (!checkCommand(m, 'replay')) return;
    playQueue.push(currentVideo);
    client.reply(m, `Queued ${VideoFormat.prettyPrint(currentVideo)}`);
  }

  if (m.content.startsWith(`${botMention} sh`)) { // shuffle
    if (!checkCommand(m, 'shuffle')) return;
    if (playQueue.length < 2) {
      client.reply(m, 'Not enough songs in the queue.');
      return;
    } else {
      shuffle(playQueue);
      client.reply(m, 'Songs in the queue have been shuffled.');
    }

    return;
  }

  if (m.content.startsWith(`${botMention} link`)) {
    if (!checkCommand(m, 'link')) return;
    if (currentVideo) client.reply(m, `<${currentVideo.loaderUrl}>`);
    return; // stop propagation
  }

  if (m.content.startsWith(`${botMention} list s`)) { // list saved
    if (!checkCommand(m, 'list saved')) return;
    var formattedList = 'Here are the videos currently saved: \n';
    for (var key in Saved.saved.videos) {
      if (Saved.saved.videos.hasOwnProperty(key)) {
        formattedList += `*${key}*: ${VideoFormat.prettyPrint(Saved.saved.videos[key])}\n`;
      }
    }

    client.reply(m, formattedList);
    return; // so list doesn't get triggered
  }

  if (m.content.startsWith(`${botMention} l`)) { // list
    if (!checkCommand(m, 'list')) return;
    var formattedList = 'Here are the videos currently in the play queue, from first added to last added: \n';
    formattedList += `Currently playing: ${VideoFormat.prettyPrintWithUser(currentVideo)}\n`;

    var shouldBreak = false;

    playQueue.forEach((video, idx) => {
      if (shouldBreak) return;

      var formattedVideo = `${idx + 1}. ${VideoFormat.prettyPrintWithUser(video)}\n`;

      if ((formattedList.length + formattedVideo.length) > 1950) {
        formattedList += `... and ${playQueue.length - idx} more`;
        shouldBreak = true;
      } else {
        formattedList += formattedVideo;
      }
    });
    client.reply(m, formattedList);
  }

  if (m.content.startsWith(`${botMention} s`)) { // save
    if (!checkCommand(m, 'save')) return;
    var argument = spliceArguments(m.content)[1];
    if (!argument) {
      client.reply(m, 'You need to specify a video and a keyword!');
      return;
    }

    var splitArgs = spliceArguments(argument, 1);

    var vid = splitArgs[0];

    if (vid === 'current') {
      if (currentVideo) vid = currentVideo.vid;
      else {
        client.reply(m, `Couldn't retrieve video information of current video!`);
      }
    }

    var requestUrl = 'http://www.youtube.com/watch?v=' + vid;
    ytdl.getInfo(requestUrl, (err, info) => {
      if (err) handleYTError(err);
      else saveVideo(info, vid, splitArgs[1], m);
    });
  }

  if (m.content.startsWith(`${botMention} t`)) { // time
    if (!checkCommand(m, 'time')) return;
    var streamTime = client.internal.voiceConnection.streamTime; // in ms
    var videoTime = currentVideo.length_seconds;
    client.reply(m, `${VideoFormat.prettyTime(streamTime)} / ${VideoFormat.prettyTime(videoTime * 1000)} (${(streamTime / (videoTime * 10)).toFixed(2)} %)`);
  }
});

function parseVidAndQueue(vid, m, suppress) {
  if (/^http/.test(vid)) {
    if (url.parse(vid, true).query.v) {
      vid = url.parse(vid, true).query.v;
    }
  }

  vid = Saved.possiblyRetrieveVideo(vid);
  if (!vid) {
    client.reply(m, 'You need to specify a video!');
    return;
  }

  getInfoAndQueue(vid, m, suppress);
}

function getInfoAndQueue(vid, m, suppress) {
  requestUrl = 'http://www.youtube.com/watch?v=' + vid;
  ytdl.getInfo(requestUrl, (err, info) => {
    if (err) handleYTError(err);
    else {
      info.vid = vid;
      possiblyQueue(info, m.author.id, m, suppress);
    }
  });
}

function spliceArguments(message, after) {
  after = after || 2;
  var rest = message.split(' ');
  var removed = rest.splice(0, after);
  return [removed.join(' '), rest.join(' ')];
}

function saveVideo(video, vid, keywords, m) {
  simplified = VideoFormat.simplify(video, vid);
  if (Saved.saved.videos.hasOwnProperty(keywords)) client.reply(m, `Warning: ${VideoFormat.simplePrint(Saved.saved.videos[keywords])} is already saved as *${keywords}*! Overwriting.`);

  var key;
  if (key = Saved.isVideoSaved(vid)) client.reply(m, `Warning: This video is already saved as *${key}*! Adding it anyway as *${keywords}*.`);

  Saved.saved.videos[keywords] = simplified;
  client.reply(m, `Saved video ${VideoFormat.prettyPrint(video)} as *${keywords}*`);
  Saved.write();
}

function possiblyQueue(video, userId, m, suppress) {
  video.userId = userId;
  suppress = (suppress === undefined) ? false : suppress;
  reason = shouldDisallowQueue(playQueue, video, Config);
  if (!userIsAdmin(userId) && reason) {
    client.reply(m, `You can't queue ${VideoFormat.simplePrint(video)} right now! Reason: ${reason}`);
  } else {
    playQueue.push(video);
    if (suppress == 0) client.reply(m, `Queued ${VideoFormat.prettyPrint(video)}`);
    else if (suppress > -1) client.reply(m, `Queued ${VideoFormat.prettyPrint(video)} and ${suppress} other videos`);

    // Start playing if not playing yet
    if (!currentVideo) nextInQueue();
  }
}

function handleYTError(err) {
  if (err.toString().indexOf('Code 150') > -1) {
    // Video unavailable in country
    boundChannel.sendMessage('This video is unavailable in the country the bot is running in! Please try a different video.');
  } else if (err.message == 'Could not extract signature deciphering actions') {
    boundChannel.sendMessage('YouTube streams have changed their formats, please update `ytdl-core` to account for the change!');
  } else if (err.message == 'status code 404') {
    boundChannel.sendMessage('That video does not exist!');
  } else {
    boundChannel.sendMessage('An error occurred while getting video information! Please try a different video.');
  }

  console.log(err.toString());
}

function playStopped() {
  if (client.internal.voiceConnection) client.internal.voiceConnection.stopPlaying();

  boundChannel.sendMessage(`Finished playing ${VideoFormat.simplePrint(currentVideo)}`);
  currentVideo = false;
  nextInQueue();
}

function play(video) {
  lastVideo = currentVideo;
  currentVideo = video;
  if (client.internal.voiceConnection) {
    var connection = client.internal.voiceConnection;
    currentStream = YoutubeStream.getStream(video.loaderUrl);

    currentStream.on('error', (err) => {
      boundChannel.sendMessage(`There was an error during playback! **${err}**`);
    });

    currentStream.on('end', () => setTimeout(playStopped, Config.timeOffset || 8000)); // 8 second leeway for bad timing
    connection.playRawStream(currentStream).then(intent => {
      boundChannel.sendMessage(`Playing ${VideoFormat.prettyPrint(video)}`);
    });
  }
}

function userIsAdmin(userId) {
  return Config.adminIds.indexOf(userId) > -1;
}

function checkCommand(m, command) {
  if (Config.commandsRestrictedToAdmins[command]) {
    if (!userIsAdmin(m.author.id)) {
      client.reply(m, `You don't have permission to execute that command!`);
      return false;
    }
  }

  return true;
}

function nextInQueue() {
  if (playQueue.length > 0) {
    next = playQueue.shift();
    play(next);
  }
}

function shuffle(array) {
  var counter = array.length;
  var temp;
  var index;

  // While there are elements in the array
  while (counter > 0) {
    index = Math.floor(Math.random() * counter);

    counter--;

    temp = array[counter];
    array[counter] = array[index];
    array[index] = temp;
  }

  return array;
}

function error(argument) {
  console.log(argument.stack);
}

// Email and password over command line
client.login(process.argv[2], process.argv[3]).catch((e) => console.log(e));
<|endoftext|>


<commit_before>/* Note: this mostly comes from https://github.com/chrisjaure/travisci-webhook-handler
 * modified to support express */
var EventEmitter = require('events').EventEmitter;
var crypto = require('crypto');
var statusMessages = {
	success: [
		'Passed',
		'Fixed'
	],
	failure: [
		'Broken',
		'Failed',
		'Still Failing'
	],
	start: [
		'Pending'
	]
};

function bindEmitter(obj, emitter) {
	var methods = 'addListener,on,once,removeListener,removeAllListeners,setMaxListeners,listeners,emit';
	methods.split(',').forEach(function (fn) {
		obj[fn] = emitter[fn].bind(emitter);
	});
}

function signRequest(repoSlug, userToken) {
	return crypto.createHash('sha256').update(repoSlug + userToken).digest('hex');
}

function create(token) {

	var handler = function (req, res, next) {
		function hasError(msg) {
			var err = new Error(msg);
			next(err);
		}

		if (token) {
			var repoSlug = req.headers['travis-repo-slug'];
			var sig = req.headers['authorization'];
			if (!sig) {
				return hasError('No authorization found on request');
			}
			if (!repoSlug) {
				return hasError('No repo found on request');
			}
			if (sig !== signRequest(repoSlug, token)) {
				return hasError('Authentication does not match');
			}
		}

		var result;
		try {
			result = JSON.parse(req.body.payload);
		} catch (err) {
			return hasError(err.message);
		}
		var status = null;
		Object.keys(statusMessages).some(key=> {
			var value = statusMessages[key];
			if (value.indexOf(result.status_message) !== -1) {
				status = key;
				return true;
			}
			else return false;
		});
		if (status === null) return hasError('An invalid status message was sent.');
		res.json({ok: true});

		handler.emit('*', result);
		handler.emit(status, result);
	};
	handler.emitter = new EventEmitter();
	bindEmitter(handler, handler.emitter);
	return handler;
}

module.exports = create;<commit_msg>Fix travis webhooks<commit_after>/* Note: this mostly comes from https://github.com/chrisjaure/travisci-webhook-handler
 * modified to support express */
var EventEmitter = require('events').EventEmitter;
var NodeRSA = require('node-rsa');
var statusMessages = {
	success: [
		'Passed',
		'Fixed'
	],
	failure: [
		'Broken',
		'Failed',
		'Still Failing'
	],
	start: [
		'Pending'
	]
};

function bindEmitter(obj, emitter) {
	var methods = 'addListener,on,once,removeListener,removeAllListeners,setMaxListeners,listeners,emit';
	methods.split(',').forEach(function (fn) {
		obj[fn] = emitter[fn].bind(emitter);
	});
}

function signRequest(repoSlug, userToken) {
	return crypto.createHash('sha256').update(repoSlug + userToken).digest('hex');
}

function create(publicKey) {

	var handler = function (req, res, next) {
		if (!sig) {
			return hasError('No Signature found on request');
		}
		if (!repoSlug) {
			return hasError('No repo found on request');
		}
		var key = new NodeRSA(publicKey, {signingScheme: 'sha1'});

		function hasError(msg) {
			var err = new Error(msg);
			next(err);
		}

		if (!key.verify(JSON.parse(req.body.payload), sig, 'base64', 'base64'))
			return hasError('Signed payload does not match signature');

		var result;
		try {
			result = JSON.parse(req.body.payload);
		} catch (err) {
			return hasError(err.message);
		}
		var status = null;
		Object.keys(statusMessages).some(key => {
			var value = statusMessages[key];
			if (value.indexOf(result.status_message) !== -1) {
				status = key;
				return true;
			}
			else return false;
		});
		if (status === null) return hasError('An invalid status message was sent.');
		res.json({ok: true});

		handler.emit('*', result);
		handler.emit(event, result);
	};
	handler.emitter = new EventEmitter();
	bindEmitter(handler, handler.emitter);
	return handler;
}

module.exports = create;<|endoftext|>


<commit_before>// Get URL parameters as an object
// USAGE:
// getAllUrlParams().product; // 'shirt'
// getAllUrlParams().color; // 'blue'
// getAllUrlParams().newuser; // true
// getAllUrlParams().nonexistent; // undefined
// getAllUrlParams('http://test.com/?a=abc').a; // 'abc'

function getAllUrlParams(url) {

  // get query string from url (optional) or window
  var queryString = url ? url.split('?')[1] : window.location.search.slice(1);

  // we'll store the parameters here
  var obj = {};

  // if query string exists
  if (queryString) {

    // stuff after # is not part of query string, so get rid of it
    queryString = queryString.split('#')[0];

    // split our query string into its component parts
    var arr = queryString.split('&');

    for (var i=0; i<arr.length; i++) {
      // separate the keys and the values
      var a = arr[i].split('=');

      // in case params look like: list[]=thing1&list[]=thing2
      var paramNum = undefined;
      var paramName = a[0].replace(/\[\d*\]/, function(v) {
        paramNum = v.slice(1,-1);
        return '';
      });

      // set parameter value (use 'true' if empty)
      var paramValue = typeof(a[1])==='undefined' ? true : a[1];

      // (optional) keep case consistent
      paramName = paramName.toLowerCase();
      paramValue = paramValue.toLowerCase();

      // if parameter name already exists
      if (obj[paramName]) {
        // convert value to array (if still string)
        if (typeof obj[paramName] === 'string') {
          obj[paramName] = [obj[paramName]];
        }
        // if no array index number specified...
        if (typeof paramNum === 'undefined') {
          // put the value on the end of the array
          obj[paramName].push(paramValue);
        }
        // if array index number specified...
        else {
          // put the value at that index number
          obj[paramName][paramNum] = paramValue;
        }
      }
      // if param name doesn't exist yet, set it
      else {
        obj[paramName] = paramValue;
      }
    }
  }

  return obj;
}

// Strip the + delimeters
function stripDelimeters(string) {
	return string.split('+').join(' ');
}

// only run Lunr code on the search page
// as Lunr.min.js is not loaded by default
if (window.location.pathname == "/search/" ) {

	var rawQuery = getAllUrlParams().q;

	// strip + delimeters from query
	var query = stripDelimeters(rawQuery);
	//var query = rawQuery.replace("+"," ");

	var searchresults__count = document.getElementById("searchresults__count");
	var searchresults__resultslist = document.getElementById("searchresults__resultslist");
	var resultsObj = new Object();
	var htmlstring = "";

	function reqListener() {
	  var obj = JSON.parse(this.responseText);
		var index = lunr.Index.load(obj);
		var searchresults_json = index.search(query, {});
		resultsObj = searchresults_json;
		searchresults__count.innerHTML = resultsObj.length;
		//console.log(JSON.stringify(searchresults_json));

		// fetch the path map to lookup title and form the link
		var load_pathmap = new XMLHttpRequest();
		load_pathmap.onload = pmListener;
		load_pathmap.onerror = reqError;
		load_pathmap.open('get', '../pathmap.json', true);
		load_pathmap.send();

	}

	function pmListener() {
		var documentsjson = JSON.parse(this.responseText);
		var resultcount = 0;
		// form the results list
		resultsObj.forEach (function (result) {
			resultcount ++;
			// lookup the title
			var pagetitle = "";
			var pagedescription = "";
			var url = "";

			for (var i = 0; i < documentsjson.length; i++ ) {
				if (documentsjson[i].id == result.ref) {
					pagetitle = documentsjson[i].title;
					pagedescription = documentsjson[i].description;
					url = documentsjson[i].path;
					continue;
				}
			}
			//if (resultcount < 15) {
				htmlstring = htmlstring + "
" + pagetitle + "

" + pagedescription + "
";
			//}
		});
		searchresults__resultslist.innerHTML = htmlstring;
	}

	function reqError(err) {
	  console.log('Fetch Error :-S', err);
	}

	var load_index = new XMLHttpRequest();
	load_index.onload = reqListener;
	load_index.onerror = reqError;
	load_index.open('get', '../search_index.json', true);
	load_index.send();

}
<commit_msg>No search results, query now displayed on SERP<commit_after>// Get URL parameters as an object
// USAGE:
// getAllUrlParams().product; // 'shirt'
// getAllUrlParams().color; // 'blue'
// getAllUrlParams().newuser; // true
// getAllUrlParams().nonexistent; // undefined
// getAllUrlParams('http://test.com/?a=abc').a; // 'abc'

function getAllUrlParams(url) {

  // get query string from url (optional) or window
  var queryString = url ? url.split('?')[1] : window.location.search.slice(1);

  // we'll store the parameters here
  var obj = {};

  // if query string exists
  if (queryString) {

    // stuff after # is not part of query string, so get rid of it
    queryString = queryString.split('#')[0];

    // split our query string into its component parts
    var arr = queryString.split('&');

    for (var i=0; i<arr.length; i++) {
      // separate the keys and the values
      var a = arr[i].split('=');

      // in case params look like: list[]=thing1&list[]=thing2
      var paramNum = undefined;
      var paramName = a[0].replace(/\[\d*\]/, function(v) {
        paramNum = v.slice(1,-1);
        return '';
      });

      // set parameter value (use 'true' if empty)
      var paramValue = typeof(a[1])==='undefined' ? true : a[1];

      // (optional) keep case consistent
      paramName = paramName.toLowerCase();
      paramValue = paramValue.toLowerCase();

      // if parameter name already exists
      if (obj[paramName]) {
        // convert value to array (if still string)
        if (typeof obj[paramName] === 'string') {
          obj[paramName] = [obj[paramName]];
        }
        // if no array index number specified...
        if (typeof paramNum === 'undefined') {
          // put the value on the end of the array
          obj[paramName].push(paramValue);
        }
        // if array index number specified...
        else {
          // put the value at that index number
          obj[paramName][paramNum] = paramValue;
        }
      }
      // if param name doesn't exist yet, set it
      else {
        obj[paramName] = paramValue;
      }
    }
  }

  return obj;
}

// Strip the + delimeters
function stripDelimeters(string) {
	return string.split('+').join(' ');
}

// only run Lunr code on the search page
// as Lunr.min.js is not loaded by default
if (window.location.pathname == "/search/" ) {

	var rawQuery = getAllUrlParams().q;

	// strip + delimeters from query
	var query = stripDelimeters(rawQuery);
	//var query = rawQuery.replace("+"," ");

	var searchresults__count = document.getElementById("searchresults__count");
	var searchresults__resultslist = document.getElementById("searchresults__resultslist");
  var searchresults__query = document.getElementById("searchresults__query");
	var resultsObj = new Object();
	var htmlstring = "";

	function reqListener() {
	  var obj = JSON.parse(this.responseText);
		var index = lunr.Index.load(obj);
		var searchresults_json = index.search(query, {});
		resultsObj = searchresults_json;

    if (resultsObj.length == 0){
      searchresults__count.innerHTML = "No";
    }
    else {
      searchresults__count.innerHTML = resultsObj.length;
    }
		searchresults__query.innerHTML = "" + query + "";
		//console.log(JSON.stringify(searchresults_json));

		// fetch the path map to lookup title and form the link
		var load_pathmap = new XMLHttpRequest();
		load_pathmap.onload = pmListener;
		load_pathmap.onerror = reqError;
		load_pathmap.open('get', '../pathmap.json', true);
		load_pathmap.send();

	}

	function pmListener() {
		var documentsjson = JSON.parse(this.responseText);
		var resultcount = 0;
		// form the results list
		resultsObj.forEach (function (result) {
			resultcount ++;
			// lookup the title
			var pagetitle = "";
			var pagedescription = "";
			var url = "";

			for (var i = 0; i < documentsjson.length; i++ ) {
				if (documentsjson[i].id == result.ref) {
					pagetitle = documentsjson[i].title;
					pagedescription = documentsjson[i].description;
					url = documentsjson[i].path;
					continue;
				}
			}
			//if (resultcount < 15) {
				htmlstring = htmlstring + "
" + pagetitle + "

" + pagedescription + "
";
			//}
		});
		searchresults__resultslist.innerHTML = htmlstring;
	}

	function reqError(err) {
	  console.log('Fetch Error :-S', err);
	}

	var load_index = new XMLHttpRequest();
	load_index.onload = reqListener;
	load_index.onerror = reqError;
	load_index.open('get', '../search_index.json', true);
	load_index.send();

}
<|endoftext|>


<commit_before>var x11 = require('x11')
var Rec2 = require('rec2')

module.exports = function (cb) {
  var X
  var all = {}

  function each(obj, iter) {
    for(var k in obj)
      iter(obj[k], k, obj)
  }

  function createWindow (wid) {
    if(all[wid]) return all[wid]
    if(null == wid) {
      throw new Error('create window!')
      wid = X.AllocID()
      X.createWindow(wid)
    }
    return all[wid] = new Window(wid)
  }

  var util = require('util')
  var EventEmitter = require('events').EventEmitter
  util.inherits(Window, EventEmitter)

  function Window (wid, opts) {
    if(wid == null) {
      this.id = X.AllocID()
      X.CreateWindow(this.id, opts)
    }
    this.event
    this.id = wid
    X.event_consumers[wid] = X
  }

  var w = Window.prototype
  var methods = {
    MoveWindow:   'move',
    ResizeWindow: 'resize',
    MapWindow:    'map',
    ChangeWindowAttributes: 'set',
    QueryTree: 'tree',
    GetWindowAttributes: 'get',
    GetGeometry: 'getBounds'
  }

  each(methods, function (_name, name) {
    w[_name] = function () {
      var args = [].slice.call(arguments)
      args.unshift(this.id)
      console.log(name, args)
      return X[name].apply(X, args)
    }
  })

  w.load = function (cb) {
    var self = this

    this.get(function (err, attrs) {
      self.attrs = attrs
      if(self.attrs && self.bounds) cb()
    })

    this.getBounds(function (err, bounds) {
      //self.bounds = bounds
      self.bounds = new Rec2(bounds.posX, bounds.posY, bounds.width, bounds.height)
      self.bounds.change(function () {
        self.move(self.bounds.x, self.bounds.y)
      })
      self.bounds.size.change(function () {
        self.resize(self.bounds.size.x, self.bounds.size.y)
      })
      if(self.attrs && self.bounds) cb()
    })
    return this
  }

  w.children = function (cb) {
    var self = this
    self._children = []
    this.tree(function (err, tree) {
      var n = tree.children.length
      console.log(tree)

      if(n === 0)
        return n = 1, next()

      tree.children.forEach(function (wid) {
        var w = createWindow(wid).load(function (err) {
          if(err) next(err)
          self._children.push(w)
          next()
        })
      });

      function next (err) {
        if(err) return n = -1, cb(err)
        if(--n) return
        cb(null, self._children)
      }

    })
    return this
  }

  function createWindow (wid) {
    if(wid != null && 'number' != typeof wid)
      throw new Error('must be number, was:' + wid)
    if(all[wid]) return all[wid]
    if(null == wid) {
      throw new Error('CREATE WINDOW', wid)
      wid = X.AllocID()
      X.CreateWindow(wid)
    }
    return all[wid] = new Window(wid)
  }

  X = x11.createClient(function (err, display) {
    if(err) return cb(err)
//    var client = display
    var rid = display.screen[0].root
    var root = createWindow(+rid).load(function (_err) {
      display.root = root
      console.log('ROOT')
      cb(err, display, display)
    })
    X.on('event', function (ev) {
      console.log('event', ev.name)
      console.log(ev)
      var wid = (ev.wid1 || ev.wid), win

      if(wid)
        win = createWindow(wid)

      if(ev.name === 'DestroyNotify') {
        delete all[ev.wid1]
      }
      if(!root)
        throw new Error('no root')
      root.emit(ev.name, ev, win)
    })

  })
}
<commit_msg>comments<commit_after>//I want to make this into a convienent api for working with X.
//my aim to be to make it browserify where possible,
//so that your expectations from web development apply.

var x11 = require('x11')
var Rec2 = require('rec2')

module.exports = function (cb) {
  var X
  var all = {}

  function each(obj, iter) {
    for(var k in obj)
      iter(obj[k], k, obj)
  }

  function createWindow (wid) {
    if(all[wid]) return all[wid]
    if(null == wid) {
      throw new Error('create window!')
      wid = X.AllocID()
      X.createWindow(wid)
    }
    return all[wid] = new Window(wid)
  }

  var util = require('util')
  var EventEmitter = require('events').EventEmitter
  util.inherits(Window, EventEmitter)

  function Window (wid, opts) {
    if(wid == null) {
      this.id = X.AllocID()
      X.CreateWindow(this.id, opts)
    }
    this.event
    this.id = wid
    X.event_consumers[wid] = X
  }

  var w = Window.prototype
  var methods = {
    MoveWindow:   'move',
    ResizeWindow: 'resize',
    MapWindow:    'map',
    ChangeWindowAttributes: 'set',
    QueryTree: 'tree',
    GetWindowAttributes: 'get',
    GetGeometry: 'getBounds'
  }

  each(methods, function (_name, name) {
    w[_name] = function () {
      var args = [].slice.call(arguments)
      args.unshift(this.id)
      console.log(name, args)
      return X[name].apply(X, args)
    }
  })

  w.load = function (cb) {
    var self = this

    this.get(function (err, attrs) {
      self.attrs = attrs
      if(self.attrs && self.bounds) cb()
    })

    this.getBounds(function (err, bounds) {
      //self.bounds = bounds
      self.bounds = new Rec2(bounds.posX, bounds.posY, bounds.width, bounds.height)
      self.bounds.change(function () {
        self.move(self.bounds.x, self.bounds.y)
      })
      self.bounds.size.change(function () {
        self.resize(self.bounds.size.x, self.bounds.size.y)
      })
      if(self.attrs && self.bounds) cb()
    })
    return this
  }

  w.children = function (cb) {
    var self = this
    self._children = []
    this.tree(function (err, tree) {
      var n = tree.children.length
      console.log(tree)

      if(n === 0)
        return n = 1, next()

      tree.children.forEach(function (wid) {
        var w = createWindow(wid).load(function (err) {
          if(err) next(err)
          self._children.push(w)
          next()
        })
      });

      function next (err) {
        if(err) return n = -1, cb(err)
        if(--n) return
        cb(null, self._children)
      }

    })
    return this
  }

  function createWindow (wid) {
    if(wid != null && 'number' != typeof wid)
      throw new Error('must be number, was:' + wid)
    if(all[wid]) return all[wid]
    if(null == wid) {
      throw new Error('CREATE WINDOW', wid)
      wid = X.AllocID()
      X.CreateWindow(wid)
    }
    return all[wid] = new Window(wid)
  }

  X = x11.createClient(function (err, display) {
    if(err) return cb(err)
//    var client = display
    var rid = display.screen[0].root
    var root = createWindow(+rid).load(function (_err) {
      display.root = root
      console.log('ROOT')
      cb(err, display, display)
    })
    X.on('event', function (ev) {
      console.log('event', ev.name)
      console.log(ev)
      var wid = (ev.wid1 || ev.wid), win

      if(wid)
        win = createWindow(wid)

      if(ev.name === 'DestroyNotify') {
        delete all[ev.wid1]
      }
      if(!root)
        throw new Error('no root')
      root.emit(ev.name, ev, win)
    })

  })
}
<|endoftext|>


<commit_before>var http = require('http'),
    app = {}

// ! Communicate
app.talk = function( path, props, callback ) {
	if( typeof props === 'function' ) {
		var callback = props
		var props = {}
	}

	var options = {
		host:	'webservices.ns.nl',
		port:	80,
		path:	'/ns-api-'+ path +'?'+ querystring.stringify( props ),
		method:	'GET'
	}

	var req = http.request( options )

	req.on( 'response', function( response ) {
		var data = ''
		response.on( 'data', function( ch ) { data += ch })
		response.on( 'close', function() { callback( new Error('disconnected') ) })
		response.on( 'end', function() {

		})
	})

	req.on( 'error', function( error ) {
		var err = new Error('request')
		err.details = error
		callback( err )
	})

	req.end()
}

// ready
module.exports = app
<commit_msg>Talk: added response parsing<commit_after>var http = require('http'),
    app = {}
    querystring = require('querystring'),
    xml2json = require('node-xml2json'),
    app = {user: '', pass: ''}

// ! Communicate
app.talk = function( path, props, callback ) {
	if( typeof props === 'function' ) {
		var callback = props
		var props = {}
	}

	var options = {
		host:	'webservices.ns.nl',
		port:	80,
		path:	'/ns-api-'+ path +'?'+ querystring.stringify( props ),
		method:	'GET',
		auth:	app.user +':'+ app.pass
	}

	var req = http.request( options )

	req.on( 'response', function( response ) {
		var data = ''
		response.on( 'data', function( ch ) { data += ch })
		response.on( 'close', function() { callback( new Error('disconnected') ) })
		response.on( 'end', function() {
			data = data.toString('utf8').trim()
			if( data.match('<faultstring>') ) {
				data.replace( /<faultstring>([0-9]+):([^<]+)<\/faultstring>/, function( s, code, error ) {
					var err = new Error('API error')
					err.details = {
						code:		code,
						message:	error
					}
					callback( err )
				})
			} else if( data.match('<?xml') ) {
				data = xml2json.parser( data )
				callback( null, data )
			} else {
				var err = new Error('invalid response')
				err.details = {
					request: options,
					response: {
						headers: response.headers,
						data: data
					}
				}
				callback( err )
			}
		})
	})

	req.on( 'error', function( error ) {
		var err = new Error('request')
		err.details = error
		callback( err )
	})

	req.end()
}

// ready
module.exports = app
<|endoftext|>


<commit_before>'use strict';

const fs = require('fs');
const color = require('../config/color');

let adWhitelist = (Config.adWhitelist ? Config.adWhitelist : ['dragonheaven.psim.us']);
let bannedMessages = (Config.bannedMessages ? Config.bannedMessages : []);
let adRegex = new RegExp("(play.pokemonshowdown.com\\/~~)(?!(" + adWhitelist.join('|') + "))", "g");

Config.chatfilter = function (message, user, room, connection) {
	user.lastActive = Date.now();

	for (let x in bannedMessages) {
		if (message.toLowerCase().indexOf(bannedMessages[x]) > -1 && bannedMessages[x] !== '' && message.substr(0, 1) !== '/') {
			if (user.locked) return false;
			Punishments.lock(user, Date.now() + 7 * 24 * 60 * 60 * 1000, "Said a banned word: " + bannedMessages[x]);
			user.popup('You have been automatically locked for sending a message containing a banned word.');
			Rooms('staff').add('[AutoLockMonitor] ' + (room ? '(' + room + ') ' : '') + Tools.escapeHTML(user.name) +
			' was automatically locked for trying to say "' + message + '"').update();
			fs.appendFile('logs/modlog/modlog_staff.txt', '[' + (new Date().toJSON()) + '] (staff) ' + user.name + ' was locked from talking for saying a banned phrase.');
			return false;
		}
	}
	let pre_matches = (message.match(/psim|psim.us|psim us|psm.us|psm us|JAxq0kSF|/g) || []).length;
	let final_check = (pre_matches >= 1 ? adWhitelist.filter(server => { return ~message.indexOf(server); }).length : 0);

	if (!user.can('hotpatch') && (pre_matches >= 1 && final_check === 0 || pre_matches >= 2 && final_check >= 1 || message.match(adRegex))) {
		if (user.locked) return false;
		if (!user.advWarns) user.advWarns = 0;
		user.advWarns++;
		if (user.advWarns > 1) {
			Punishments.lock(user, Date.now() + 7 * 24 * 60 * 60 * 1000, "Advertising");
			fs.appendFile('logs/modlog/modlog_staff.txt', '[' + (new Date().toJSON()) + '] (staff) ' + user.name +
				' was locked from talking by the Server. (Advertising) (' + connection.ip + ')\n');
			connection.sendTo(room, '|raw|You have been locked for attempting to advertise.');
			Rooms('staff').add("|raw|" + user.name + " has been locked for attempting to advertise" + (room ? ". Room: " + room.id : " in a private message.") + " Message: " + message).update();
			return false;
		}
		Rooms('staff').add("|raw|" + user.name + " has attempted to advertise" + (room ? ". Room: " + room.id : " in a private message.") + " Message: " + message).update();
		connection.sendTo(room, '|raw|Advertising detected, your message has not been sent and upper staff has been notified.' +
			'
Further attempts to advertise will result in being locked');
		connection.user.popup("Advertising detected, your message has not been sent and upper staff has been notified.\n" +
			"Further attempts to advertise will result in being locked");
		return false;
	}
	return message;
};
<commit_msg>problems, reverting<commit_after>'use strict';

const fs = require('fs');
const color = require('../config/color');

let adWhitelist = (Config.adWhitelist ? Config.adWhitelist : ['dragonheaven.psim.us']);
let bannedMessages = (Config.bannedMessages ? Config.bannedMessages : []);
let adRegex = new RegExp("(play.pokemonshowdown.com\\/~~)(?!(" + adWhitelist.join('|') + "))", "g");

Config.chatfilter = function (message, user, room, connection) {
	user.lastActive = Date.now();

	for (let x in bannedMessages) {
		if (message.toLowerCase().indexOf(bannedMessages[x]) > -1 && bannedMessages[x] !== '' && message.substr(0, 1) !== '/') {
			if (user.locked) return false;
			Punishments.lock(user, Date.now() + 7 * 24 * 60 * 60 * 1000, "Said a banned word: " + bannedMessages[x]);
			user.popup('You have been automatically locked for sending a message containing a banned word.');
			Rooms('staff').add('[AutoLockMonitor] ' + (room ? '(' + room + ') ' : '') + Tools.escapeHTML(user.name) +
			' was automatically locked for trying to say "' + message + '"').update();
			fs.appendFile('logs/modlog/modlog_staff.txt', '[' + (new Date().toJSON()) + '] (staff) ' + user.name + ' was locked from talking for saying a banned phrase.');
			return false;
		}
	}
	let pre_matches = (message.match(/psim|psim.us|psim us|psm.us|psm us|/g) || []).length;
	let final_check = (pre_matches >= 1 ? adWhitelist.filter(server => { return ~message.indexOf(server); }).length : 0);

	if (!user.can('hotpatch') && (pre_matches >= 1 && final_check === 0 || pre_matches >= 2 && final_check >= 1 || message.match(adRegex))) {
		if (user.locked) return false;
		if (!user.advWarns) user.advWarns = 0;
		user.advWarns++;
		if (user.advWarns > 1) {
			Punishments.lock(user, Date.now() + 7 * 24 * 60 * 60 * 1000, "Advertising");
			fs.appendFile('logs/modlog/modlog_staff.txt', '[' + (new Date().toJSON()) + '] (staff) ' + user.name +
				' was locked from talking by the Server. (Advertising) (' + connection.ip + ')\n');
			connection.sendTo(room, '|raw|You have been locked for attempting to advertise.');
			Rooms('staff').add("|raw|" + user.name + " has been locked for attempting to advertise" + (room ? ". Room: " + room.id : " in a private message.") + " Message: " + message).update();
			return false;
		}
		Rooms('staff').add("|raw|" + user.name + " has attempted to advertise" + (room ? ". Room: " + room.id : " in a private message.") + " Message: " + message).update();
		connection.sendTo(room, '|raw|Advertising detected, your message has not been sent and upper staff has been notified.' +
			'
Further attempts to advertise will result in being locked');
		connection.user.popup("Advertising detected, your message has not been sent and upper staff has been notified.\n" +
			"Further attempts to advertise will result in being locked");
		return false;
	}
	return message;
};
<|endoftext|>