<commit_before>var events = require('events');

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

//Use asyncblock to manage flow control if it's available
var asyncblock = process.__asyncblock_included__;

var WindowProxy = require('./window_proxy.js');
var ElementProxy = require('./element_proxy.js');
var utility = require('./utility.js');

var Driver = function(now, focusedWindow){
    this.now = now;
    this.focusedWindow = focusedWindow;
    this.events = new events.EventEmitter();
};

Driver.prototype._convertArguments = function(args){
    for(var i = 0; i < args.length; i++){
        var item = args[i];

        if(item && item.isElementArray){
            var elements = item.elements || [];
            elements.__proto__ = ElementProxy.prototype;
            elements.driver = this;

            args[i] = elements;
        } else if(item && item.isElementProxy){
            var array = [ item ];
            array.__proto__ = ElementProxy.prototype;
            array.driver = this;

            args[i] = array;
        }
    }
};

Driver.prototype.exec = function(args, callback){
    var self = this;
    var func, funcArgs;

    //Use asyncblock fibers if it is available
    if(asyncblock && callback == null){
        var flow = asyncblock.getCurrentFlow();

        if(flow){
            return flow.sync( this.exec(args, flow.add()) );
        }
    }

    if(args.func){
        func = args.func;
        funcArgs = args.args;
    } else {
        func = args;
    }

    var cbOnce = _callOnce(callback);

    var timeoutCheck = setTimeout(function(){
        cbOnce(new Error('exec timed out (' + config.timeoutMS + ')'));
    }, config.timeoutMS);

    this.now.exec(
        {
            func: func.toString(),
            args: funcArgs,
            focusedWindow: this.focusedWindow
        },

        function(){
            clearTimeout(timeoutCheck);
            self._convertArguments(arguments);

            cbOnce && cbOnce.apply(null, arguments);
        }
    );
};

Driver.prototype.setUrl = function(url, callback){
    if(asyncblock && callback == null){
        var flow = asyncblock.getCurrentFlow();

        if(flow){
            return flow.sync( this.setUrl(url, flow.add()) );
        }
    }

    if(callback == null){
        throw new Error('callback is required');
    }

    this.now.setUrl(url, callback);
};

Driver.prototype.reuseBrowser = function(harnessUrl, serverUrl){
    if(harnessUrl){
        harnessUrl = utility.constructHarnessUrl(harnessUrl, serverUrl);
    }

    this.now.reuseBrowser(harnessUrl);
};

Driver.prototype.waitFor = function(args, callback){
    var self = this;
    var startTime, func, timeout, exec, funcArgs, timeoutError, inBrowser;
    if(typeof args === 'object'){
        func = args.condition;
        startTime = args.startTime || new Date();
        timeout = args.timeoutMS || config.timeoutMS;
        exec = args.exec;
        funcArgs = args.args;
        timeoutError = args.timeoutError;
        inBrowser = args.inBrowser;
    } else {
        func = args;
        startTime = new Date();
        timeout = config.timeoutMS;
    }

    //Use asyncblock fibers if it is available
    if(asyncblock && callback == null){
        var flow = asyncblock.getCurrentFlow();

        if(flow){
            return flow.sync( this.waitFor(args, flow.add()) );
        }
    }

    if(callback == null){
        throw new Error('callback is required');
    }

    var _resultHandler = function(err, result){
        if(err && err.message.indexOf('exec timed out') < 0){
            return callback(err);
        }

        if(result){
            return callback();
        } else {
            if(new Date() - startTime < timeout){
                setTimeout(function(){
                    //Need to re-create the asyncblock context
                    (asyncblock || function(fn){ fn(); })(function(){
                        self.waitFor({
                            condition: func,
                            timeoutMS: timeout,
                            startTime: startTime,
                            args: funcArgs,
                            timeoutError: timeoutError,
                            inBrowser: inBrowser
                        }, callback);
                    });
                }, config.retryMS);
            } else {
                if(!timeoutError) {
                    return callback(new Error('waitFor condition timed out (' + timeout + ')'));
                } else {
                    return callback(new Error('waitFor condition timed out (' + timeout + '): ' + timeoutError));
                }
            }
        }
    };

    if(inBrowser){
        this.exec({ func: func, args: funcArgs }, _resultHandler);

        if(exec){
            this.exec({ func: exec, args: funcArgs }, function(err){
                if(err){
                    return callback(err); //todo: prevent double callback
                }
            });
        }
    } else {
        //This exec needs to occur "out-of-process" or it'll block waiting on the condition when asyncblock is in use
        process.nextTick(function(){
            (asyncblock || function(fn){ fn(); })(function(){
                if(exec){
                    exec();
                }
            });
        });

        if(func.length === 1){
            func(_resultHandler);
        } else if(func.length === 0){
            _resultHandler(null, func());
        } else {
            throw new Error('func must take 0 arguments, or a callback');
        }
    }
};

Driver.prototype.findElement = function(args, callback){
    var self = this;
    var startTime, selector, context, multi, timeoutMS;
    if(typeof args === 'object'){
        selector = args.selector;
        startTime = args.startTime || new Date();
        context = args.context;
        multi = args.multi;
        timeoutMS = args.timeoutMS || config.timeoutMS;
    } else {
        selector = args;
        startTime = new Date();
        multi = false;
        timeoutMS = config.timeoutMS;
    }

    //Use asyncblock fibers if it is available
    if(asyncblock && callback == null){
        var flow = asyncblock.getCurrentFlow();

        if(flow){
            return flow.sync( this.findElement(args, flow.add()) );
        }
    }

    if(callback == null){
        throw new Error('callback is required');
    }

    this.exec({
        func: function(args){
            return $(args.selector, args.context);
        },

        args: { selector: selector, context: context }
    }, function(err, element){
        if(err){
            return callback(err);
        }

        if(element && (element.length === 1 || (multi && element.length > 0))) {
           callback(null, element);
        } else {
            if(new Date() - startTime < timeoutMS){
                setTimeout(function(){
                   self.findElement({ selector: selector, context: context, startTime: startTime, multi: multi, timeoutMS: timeoutMS }, callback);
                }, config.retryMS);
            } else {
                if(element && element.length > 1){
                    return callback(new Error('Element "' + selector + '" found, but there were too many instances (' + element.length + ')'));
                } else {
                    return callback(new Error('Element "' + selector + '" not found (timeout: ' + timeoutMS + ')'));
                }
            }
        }
    });
};

Driver.prototype.findElements = Driver.prototype.find = function(args, callback){
    if(typeof args === 'object'){
        args.multi = true;
    } else {
        args = { selector: args, multi: true };
    }

    return this.findElement(args, callback);
};

var _isVisible = function(element, callback){
    element._filterVisible(function(err, visibleElements){
        if(err) {
            return callback(err);
        }

        //Not all the elements may be visible, return the visible ones
        if(visibleElements && visibleElements.length > 0){
            callback(null, visibleElements);
        } else {
            callback(null, false);
        }
    });
};

Driver.prototype.findVisible = function(args, callback){
    var selector, multi;
    var self = this;

    if(typeof args === 'object'){
        selector = args.selector;
        multi = args.multi;
        args.startTime = args.startTime || new Date();
    } else {
        args = { selector: args, startTime: new Date() };
    }

    //Use asyncblock fibers if it is available
    if(asyncblock && callback == null){
        var flow = asyncblock.getCurrentFlow();

        if(flow){
            return flow.sync( this.findVisible(args, flow.add()) );
        }
    }

    if(callback == null){
        throw new Error('callback is required');
    }

    this.findElements(args, function(err, element){
        if(err){
            return callback(err);
        }

        _isVisible(element, function(err, visibles){
            if(err){
                return callback(err);
            }

            if(!visibles){
                if(new Date() - args.startTime < config.timeoutMS){
                    setTimeout(function(){
                        self.findVisible(args, callback);
                    }, config.retryMS);
                } else {
                    callback(new Error('Element "' + selector + '" was found, but is not visible.'));
                }

                return;
            }

            if(!multi && visibles.length > 1){
                return callback(new Error('Element "' + selector + '" found, but there were too many visible instances (' + visibles.length + ')'));
            }

            return callback(null, visibles);
        });
    });
};

Driver.prototype.findVisibles = function(args, callback){
    if(typeof args === 'object'){
        args.multi = true;
    } else {
        args = { selector: args, multi: true };
    }

    return this.findVisible(args, callback);
};

Driver.prototype.$ = function(selector, context, callback){
    if (callback == null && typeof context === 'function') {
        callback = context;
        context = null;
    }
    return this.exec({
        func: function(args){
            if (args.context != null) {
                return $(args.selector, args.context);
            } else {
                return $(args.selector);
            }
        },

        args: { selector: selector, context: context }
    }, callback);
};

Driver.prototype.clearLastPopupWindow = function(callback){
    //Use asyncblock fibers if it is available
    if(asyncblock && callback == null){
        var flow = asyncblock.getCurrentFlow();

        if(flow){
            return flow.sync( this.clearLastPopupWindow(flow.add()) );
        }
    }

    this.now.clearLastPopupWindow(callback);
};

Driver.prototype.getLastPopupWindow = function(callback){
    var self = this;

    //Use asyncblock fibers if it is available
    if(asyncblock && callback == null){
        var flow = asyncblock.getCurrentFlow();

        if(flow){
            return flow.sync( this.getLastPopupWindow(flow.add()) );
        }
    }

    return this.now.getLastPopupWindow(function(err, window){
        if(err) { return callback(err); }

        if(window != null){
            window = new WindowProxy(self, window.id);
        }

        return callback(null, window);
    });
};

Driver.prototype.isWindowOpen = function(windowProxy, callback){
    var self = this;

    //Use asyncblock fibers if it is available
    if(asyncblock && callback == null){
        var flow = asyncblock.getCurrentFlow();

        if(flow){
            return flow.sync( this.isWindowOpen(windowProxy, flow.add()) );
        }
    }

    return this.now.isWindowOpen(windowProxy, callback);
};

var _callOnce = function(callback){
    if(callback == null){
        return callback;
    }

    var called = false;
    return function(){
        if(!called){
            called = true;
            callback.apply(this, arguments);
        }
    };
};

module.exports = Driver;<commit_msg>Fix a null ref that can occur on error<commit_after>var events = require('events');

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

//Use asyncblock to manage flow control if it's available
var asyncblock = process.__asyncblock_included__;

var WindowProxy = require('./window_proxy.js');
var ElementProxy = require('./element_proxy.js');
var utility = require('./utility.js');

var Driver = function(now, focusedWindow){
    this.now = now;
    this.focusedWindow = focusedWindow;
    this.events = new events.EventEmitter();
};

Driver.prototype._convertArguments = function(args){
    for(var i = 0; i < args.length; i++){
        var item = args[i];

        if(item && item.isElementArray){
            var elements = item.elements || [];
            elements.__proto__ = ElementProxy.prototype;
            elements.driver = this;

            args[i] = elements;
        } else if(item && item.isElementProxy){
            var array = [ item ];
            array.__proto__ = ElementProxy.prototype;
            array.driver = this;

            args[i] = array;
        }
    }
};

Driver.prototype.exec = function(args, callback){
    var self = this;
    var func, funcArgs;

    //Use asyncblock fibers if it is available
    if(asyncblock && callback == null){
        var flow = asyncblock.getCurrentFlow();

        if(flow){
            return flow.sync( this.exec(args, flow.add()) );
        }
    }

    if(args.func){
        func = args.func;
        funcArgs = args.args;
    } else {
        func = args;
    }

    var cbOnce = _callOnce(callback);

    var timeoutCheck = setTimeout(function(){
        cbOnce(new Error('exec timed out (' + config.timeoutMS + ')'));
    }, config.timeoutMS);

    this.now.exec(
        {
            func: func.toString(),
            args: funcArgs,
            focusedWindow: this.focusedWindow
        },

        function(){
            clearTimeout(timeoutCheck);
            self._convertArguments(arguments);

            cbOnce && cbOnce.apply(null, arguments);
        }
    );
};

Driver.prototype.setUrl = function(url, callback){
    if(asyncblock && callback == null){
        var flow = asyncblock.getCurrentFlow();

        if(flow){
            return flow.sync( this.setUrl(url, flow.add()) );
        }
    }

    if(callback == null){
        throw new Error('callback is required');
    }

    this.now.setUrl(url, callback);
};

Driver.prototype.reuseBrowser = function(harnessUrl, serverUrl){
    if(harnessUrl){
        harnessUrl = utility.constructHarnessUrl(harnessUrl, serverUrl);
    }

    this.now.reuseBrowser(harnessUrl);
};

Driver.prototype.waitFor = function(args, callback){
    var self = this;
    var startTime, func, timeout, exec, funcArgs, timeoutError, inBrowser;
    if(typeof args === 'object'){
        func = args.condition;
        startTime = args.startTime || new Date();
        timeout = args.timeoutMS || config.timeoutMS;
        exec = args.exec;
        funcArgs = args.args;
        timeoutError = args.timeoutError;
        inBrowser = args.inBrowser;
    } else {
        func = args;
        startTime = new Date();
        timeout = config.timeoutMS;
    }

    //Use asyncblock fibers if it is available
    if(asyncblock && callback == null){
        var flow = asyncblock.getCurrentFlow();

        if(flow){
            return flow.sync( this.waitFor(args, flow.add()) );
        }
    }

    if(callback == null){
        throw new Error('callback is required');
    }

    var _resultHandler = function(err, result){
        if(err && (!err.message || err.message.indexOf('exec timed out') < 0)){
            return callback(err);
        }

        if(result){
            return callback();
        } else {
            if(new Date() - startTime < timeout){
                setTimeout(function(){
                    //Need to re-create the asyncblock context
                    (asyncblock || function(fn){ fn(); })(function(){
                        self.waitFor({
                            condition: func,
                            timeoutMS: timeout,
                            startTime: startTime,
                            args: funcArgs,
                            timeoutError: timeoutError,
                            inBrowser: inBrowser
                        }, callback);
                    });
                }, config.retryMS);
            } else {
                if(!timeoutError) {
                    return callback(new Error('waitFor condition timed out (' + timeout + ')'));
                } else {
                    return callback(new Error('waitFor condition timed out (' + timeout + '): ' + timeoutError));
                }
            }
        }
    };

    if(inBrowser){
        this.exec({ func: func, args: funcArgs }, _resultHandler);

        if(exec){
            this.exec({ func: exec, args: funcArgs }, function(err){
                if(err){
                    return callback(err); //todo: prevent double callback
                }
            });
        }
    } else {
        //This exec needs to occur "out-of-process" or it'll block waiting on the condition when asyncblock is in use
        process.nextTick(function(){
            (asyncblock || function(fn){ fn(); })(function(){
                if(exec){
                    exec();
                }
            });
        });

        if(func.length === 1){
            func(_resultHandler);
        } else if(func.length === 0){
            _resultHandler(null, func());
        } else {
            throw new Error('func must take 0 arguments, or a callback');
        }
    }
};

Driver.prototype.findElement = function(args, callback){
    var self = this;
    var startTime, selector, context, multi, timeoutMS;
    if(typeof args === 'object'){
        selector = args.selector;
        startTime = args.startTime || new Date();
        context = args.context;
        multi = args.multi;
        timeoutMS = args.timeoutMS || config.timeoutMS;
    } else {
        selector = args;
        startTime = new Date();
        multi = false;
        timeoutMS = config.timeoutMS;
    }

    //Use asyncblock fibers if it is available
    if(asyncblock && callback == null){
        var flow = asyncblock.getCurrentFlow();

        if(flow){
            return flow.sync( this.findElement(args, flow.add()) );
        }
    }

    if(callback == null){
        throw new Error('callback is required');
    }

    this.exec({
        func: function(args){
            return $(args.selector, args.context);
        },

        args: { selector: selector, context: context }
    }, function(err, element){
        if(err){
            return callback(err);
        }

        if(element && (element.length === 1 || (multi && element.length > 0))) {
           callback(null, element);
        } else {
            if(new Date() - startTime < timeoutMS){
                setTimeout(function(){
                   self.findElement({ selector: selector, context: context, startTime: startTime, multi: multi, timeoutMS: timeoutMS }, callback);
                }, config.retryMS);
            } else {
                if(element && element.length > 1){
                    return callback(new Error('Element "' + selector + '" found, but there were too many instances (' + element.length + ')'));
                } else {
                    return callback(new Error('Element "' + selector + '" not found (timeout: ' + timeoutMS + ')'));
                }
            }
        }
    });
};

Driver.prototype.findElements = Driver.prototype.find = function(args, callback){
    if(typeof args === 'object'){
        args.multi = true;
    } else {
        args = { selector: args, multi: true };
    }

    return this.findElement(args, callback);
};

var _isVisible = function(element, callback){
    element._filterVisible(function(err, visibleElements){
        if(err) {
            return callback(err);
        }

        //Not all the elements may be visible, return the visible ones
        if(visibleElements && visibleElements.length > 0){
            callback(null, visibleElements);
        } else {
            callback(null, false);
        }
    });
};

Driver.prototype.findVisible = function(args, callback){
    var selector, multi;
    var self = this;

    if(typeof args === 'object'){
        selector = args.selector;
        multi = args.multi;
        args.startTime = args.startTime || new Date();
    } else {
        args = { selector: args, startTime: new Date() };
    }

    //Use asyncblock fibers if it is available
    if(asyncblock && callback == null){
        var flow = asyncblock.getCurrentFlow();

        if(flow){
            return flow.sync( this.findVisible(args, flow.add()) );
        }
    }

    if(callback == null){
        throw new Error('callback is required');
    }

    this.findElements(args, function(err, element){
        if(err){
            return callback(err);
        }

        _isVisible(element, function(err, visibles){
            if(err){
                return callback(err);
            }

            if(!visibles){
                if(new Date() - args.startTime < config.timeoutMS){
                    setTimeout(function(){
                        self.findVisible(args, callback);
                    }, config.retryMS);
                } else {
                    callback(new Error('Element "' + selector + '" was found, but is not visible.'));
                }

                return;
            }

            if(!multi && visibles.length > 1){
                return callback(new Error('Element "' + selector + '" found, but there were too many visible instances (' + visibles.length + ')'));
            }

            return callback(null, visibles);
        });
    });
};

Driver.prototype.findVisibles = function(args, callback){
    if(typeof args === 'object'){
        args.multi = true;
    } else {
        args = { selector: args, multi: true };
    }

    return this.findVisible(args, callback);
};

Driver.prototype.$ = function(selector, context, callback){
    if (callback == null && typeof context === 'function') {
        callback = context;
        context = null;
    }
    return this.exec({
        func: function(args){
            if (args.context != null) {
                return $(args.selector, args.context);
            } else {
                return $(args.selector);
            }
        },

        args: { selector: selector, context: context }
    }, callback);
};

Driver.prototype.clearLastPopupWindow = function(callback){
    //Use asyncblock fibers if it is available
    if(asyncblock && callback == null){
        var flow = asyncblock.getCurrentFlow();

        if(flow){
            return flow.sync( this.clearLastPopupWindow(flow.add()) );
        }
    }

    this.now.clearLastPopupWindow(callback);
};

Driver.prototype.getLastPopupWindow = function(callback){
    var self = this;

    //Use asyncblock fibers if it is available
    if(asyncblock && callback == null){
        var flow = asyncblock.getCurrentFlow();

        if(flow){
            return flow.sync( this.getLastPopupWindow(flow.add()) );
        }
    }

    return this.now.getLastPopupWindow(function(err, window){
        if(err) { return callback(err); }

        if(window != null){
            window = new WindowProxy(self, window.id);
        }

        return callback(null, window);
    });
};

Driver.prototype.isWindowOpen = function(windowProxy, callback){
    var self = this;

    //Use asyncblock fibers if it is available
    if(asyncblock && callback == null){
        var flow = asyncblock.getCurrentFlow();

        if(flow){
            return flow.sync( this.isWindowOpen(windowProxy, flow.add()) );
        }
    }

    return this.now.isWindowOpen(windowProxy, callback);
};

var _callOnce = function(callback){
    if(callback == null){
        return callback;
    }

    var called = false;
    return function(){
        if(!called){
            called = true;
            callback.apply(this, arguments);
        }
    };
};

module.exports = Driver;<|endoftext|>


<commit_before>var events = require('events');

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

//Use asyncblock to manage flow control if it's available
var asyncblock = process.__asyncblock_included__;

var WindowProxy = require('./window_proxy.js');
var ElementProxy = require('./element_proxy.js');
var utility = require('./utility.js');

var Driver = function(now, focusedWindow){
    this.now = now;
    this.focusedWindow = focusedWindow;
    this.events = new events.EventEmitter();
};

Driver.prototype._convertArguments = function(args){
    for(var i = 0; i < args.length; i++){
        var item = args[i];

        if(item && item.isElementArray){
            var elements = item.elements || [];
            elements.__proto__ = ElementProxy.prototype;
            elements.driver = this;

            args[i] = elements;
        } else if(item && item.isElementProxy){
            var array = [ item ];
            array.__proto__ = ElementProxy.prototype;
            array.driver = this;

            args[i] = array;
        }
    }
};

Driver.prototype.exec = function(args, callback){
    var self = this;
    var func, funcArgs;

    //Use asyncblock fibers if it is available
    if(asyncblock && callback == null){
        var flow = asyncblock.getCurrentFlow();

        if(flow){
            return flow.sync( this.exec(args, flow.add()) );
        }
    }

    if(args.func){
        func = args.func;
        funcArgs = args.args;
    } else {
        func = args;
    }

    var cbOnce = _callOnce(callback);

    var timeoutCheck = setTimeout(function(){
        cbOnce(new Error('exec timed out (' + config.timeoutMS + ')'));
    }, config.timeoutMS);

    this.now.exec(
        {
            func: func.toString(),
            args: funcArgs,
            focusedWindow: this.focusedWindow
        },

        function(){
            clearTimeout(timeoutCheck);
            self._convertArguments(arguments);

            cbOnce && cbOnce.apply(null, arguments);
        }
    );
};

Driver.prototype.setUrl = function(url, callback){
    if(asyncblock && callback == null){
        var flow = asyncblock.getCurrentFlow();

        if(flow){
            return flow.sync( this.setUrl(url, flow.add()) );
        }
    }

    if(callback == null){
        throw new Error('callback is required');
    }

    this.now.setUrl(url, callback);
};

Driver.prototype.reuseBrowser = function(harnessUrl, serverUrl){
    if(harnessUrl){
        harnessUrl = utility.constructHarnessUrl(harnessUrl, serverUrl);
    }

    this.now.reuseBrowser(harnessUrl);
};

Driver.prototype.waitFor = function(args, callback){
    var self = this;
    var startTime, func, timeout, exec, funcArgs, timeoutError, inBrowser;
    if(typeof args === 'object'){
        func = args.condition;
        startTime = args.startTime || new Date();
        timeout = args.timeoutMS || config.timeoutMS;
        exec = args.exec;
        funcArgs = args.args;
        timeoutError = args.timeoutError;
        inBrowser = args.inBrowser;
    } else {
        func = args;
        startTime = new Date();
        timeout = config.timeoutMS;
    }

    //Use asyncblock fibers if it is available
    if(asyncblock && callback == null){
        var flow = asyncblock.getCurrentFlow();

        if(flow){
            return flow.sync( this.waitFor(args, flow.add()) );
        }
    }

    if(callback == null){
        throw new Error('callback is required');
    }

    var _resultHandler = function(err, result){
        if(err && (!err.message || err.message.indexOf('exec timed out') < 0)){
            return callback(err);
        }

        if(result){
            return callback();
        } else {
            if(new Date() - startTime < timeout){
                setTimeout(function(){
                    //Need to re-create the asyncblock context
                    (asyncblock || function(fn){ fn(); })(function(){
                        self.waitFor({
                            condition: func,
                            timeoutMS: timeout,
                            startTime: startTime,
                            args: funcArgs,
                            timeoutError: timeoutError,
                            inBrowser: inBrowser
                        }, callback);
                    });
                }, config.retryMS);
            } else {
                if(!timeoutError) {
                    return callback(new Error('waitFor condition timed out (' + timeout + ')'));
                } else {
                    return callback(new Error('waitFor condition timed out (' + timeout + '): ' + timeoutError));
                }
            }
        }
    };

    if(inBrowser){
        this.exec({ func: func, args: funcArgs }, _resultHandler);

        if(exec){
            this.exec({ func: exec, args: funcArgs }, function(err){
                if(err){
                    return callback(err); //todo: prevent double callback
                }
            });
        }
    } else {
        //This exec needs to occur "out-of-process" or it'll block waiting on the condition when asyncblock is in use
        process.nextTick(function(){
            (asyncblock || function(fn){ fn(); })(function(){
                if(exec){
                    exec();
                }
            });
        });

        if(func.length === 1){
            func(_resultHandler);
        } else if(func.length === 0){
            _resultHandler(null, func());
        } else {
            throw new Error('func must take 0 arguments, or a callback');
        }
    }
};

Driver.prototype.findElement = function(args, callback){
    var self = this;
    var startTime, selector, context, multi, timeoutMS;
    if(typeof args === 'object'){
        selector = args.selector;
        startTime = args.startTime || new Date();
        context = args.context;
        multi = args.multi;
        timeoutMS = args.timeoutMS || config.timeoutMS;
    } else {
        selector = args;
        startTime = new Date();
        multi = false;
        timeoutMS = config.timeoutMS;
    }

    //Use asyncblock fibers if it is available
    if(asyncblock && callback == null){
        var flow = asyncblock.getCurrentFlow();

        if(flow){
            return flow.sync( this.findElement(args, flow.add()) );
        }
    }

    if(callback == null){
        throw new Error('callback is required');
    }

    this.exec({
        func: function(args){
            return $(args.selector, args.context);
        },

        args: { selector: selector, context: context }
    }, function(err, element){
        if(err){
            return callback(err);
        }

        if(element && (element.length === 1 || (multi && element.length > 0))) {
           callback(null, element);
        } else {
            if(new Date() - startTime < timeoutMS){
                setTimeout(function(){
                   self.findElement({ selector: selector, context: context, startTime: startTime, multi: multi, timeoutMS: timeoutMS }, callback);
                }, config.retryMS);
            } else {
                if(element && element.length > 1){
                    return callback(new Error('Element "' + selector + '" found, but there were too many instances (' + element.length + ')'));
                } else {
                    return callback(new Error('Element "' + selector + '" not found (timeout: ' + timeoutMS + ')'));
                }
            }
        }
    });
};

Driver.prototype.findElements = Driver.prototype.find = function(args, callback){
    if(typeof args === 'object'){
        args.multi = true;
    } else {
        args = { selector: args, multi: true };
    }

    return this.findElement(args, callback);
};

var _isVisible = function(element, callback){
    element._filterVisible(function(err, visibleElements){
        if(err) {
            return callback(err);
        }

        //Not all the elements may be visible, return the visible ones
        if(visibleElements && visibleElements.length > 0){
            callback(null, visibleElements);
        } else {
            callback(null, false);
        }
    });
};

Driver.prototype.findVisible = function(args, callback){
    var selector, multi;
    var self = this;

    if(typeof args === 'object'){
        selector = args.selector;
        multi = args.multi;
        args.startTime = args.startTime || new Date();
    } else {
        args = { selector: args, startTime: new Date() };
    }

    //Use asyncblock fibers if it is available
    if(asyncblock && callback == null){
        var flow = asyncblock.getCurrentFlow();

        if(flow){
            return flow.sync( this.findVisible(args, flow.add()) );
        }
    }

    if(callback == null){
        throw new Error('callback is required');
    }

    this.findElements(args, function(err, element){
        if(err){
            return callback(err);
        }

        _isVisible(element, function(err, visibles){
            if(err){
                return callback(err);
            }

            if(!visibles){
                if(new Date() - args.startTime < config.timeoutMS){
                    setTimeout(function(){
                        self.findVisible(args, callback);
                    }, config.retryMS);
                } else {
                    callback(new Error('Element "' + selector + '" was found, but is not visible.'));
                }

                return;
            }

            if(!multi && visibles.length > 1){
                return callback(new Error('Element "' + selector + '" found, but there were too many visible instances (' + visibles.length + ')'));
            }

            return callback(null, visibles);
        });
    });
};

Driver.prototype.findVisibles = function(args, callback){
    if(typeof args === 'object'){
        args.multi = true;
    } else {
        args = { selector: args, multi: true };
    }

    return this.findVisible(args, callback);
};

Driver.prototype.$ = function(selector, context, callback){
    if (callback == null && typeof context === 'function') {
        callback = context;
        context = null;
    }
    return this.exec({
        func: function(args){
            if (args.context != null) {
                return $(args.selector, args.context);
            } else {
                return $(args.selector);
            }
        },

        args: { selector: selector, context: context }
    }, callback);
};

Driver.prototype.clearLastPopupWindow = function(callback){
    //Use asyncblock fibers if it is available
    if(asyncblock && callback == null){
        var flow = asyncblock.getCurrentFlow();

        if(flow){
            return flow.sync( this.clearLastPopupWindow(flow.add()) );
        }
    }

    this.now.clearLastPopupWindow(callback);
};

Driver.prototype.getLastPopupWindow = function(callback){
    var self = this;

    //Use asyncblock fibers if it is available
    if(asyncblock && callback == null){
        var flow = asyncblock.getCurrentFlow();

        if(flow){
            return flow.sync( this.getLastPopupWindow(flow.add()) );
        }
    }

    return this.now.getLastPopupWindow(function(err, window){
        if(err) { return callback(err); }

        if(window != null){
            window = new WindowProxy(self, window.id);
        }

        return callback(null, window);
    });
};

Driver.prototype.isWindowOpen = function(windowProxy, callback){
    var self = this;

    //Use asyncblock fibers if it is available
    if(asyncblock && callback == null){
        var flow = asyncblock.getCurrentFlow();

        if(flow){
            return flow.sync( this.isWindowOpen(windowProxy, flow.add()) );
        }
    }

    return this.now.isWindowOpen(windowProxy, callback);
};

var _callOnce = function(callback){
    if(callback == null){
        return callback;
    }

    var called = false;
    return function(){
        if(!called){
            called = true;
            callback.apply(this, arguments);
        }
    };
};

module.exports = Driver;<commit_msg>Switching up driver.find to work like jQuery.find instead of driver.findElements<commit_after>var events = require('events');

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

//Use asyncblock to manage flow control if it's available
var asyncblock = process.__asyncblock_included__;

var WindowProxy = require('./window_proxy.js');
var ElementProxy = require('./element_proxy.js');
var utility = require('./utility.js');

var Driver = function(now, focusedWindow){
    this.now = now;
    this.focusedWindow = focusedWindow;
    this.events = new events.EventEmitter();
};

Driver.prototype._convertArguments = function(args){
    for(var i = 0; i < args.length; i++){
        var item = args[i];

        if(item && item.isElementArray){
            var elements = item.elements || [];
            elements.__proto__ = ElementProxy.prototype;
            elements.driver = this;

            args[i] = elements;
        } else if(item && item.isElementProxy){
            var array = [ item ];
            array.__proto__ = ElementProxy.prototype;
            array.driver = this;

            args[i] = array;
        }
    }
};

Driver.prototype.exec = function(args, callback){
    var self = this;
    var func, funcArgs;

    //Use asyncblock fibers if it is available
    if(asyncblock && callback == null){
        var flow = asyncblock.getCurrentFlow();

        if(flow){
            return flow.sync( this.exec(args, flow.add()) );
        }
    }

    if(args.func){
        func = args.func;
        funcArgs = args.args;
    } else {
        func = args;
    }

    var cbOnce = _callOnce(callback);

    var timeoutCheck = setTimeout(function(){
        cbOnce(new Error('exec timed out (' + config.timeoutMS + ')'));
    }, config.timeoutMS);

    this.now.exec(
        {
            func: func.toString(),
            args: funcArgs,
            focusedWindow: this.focusedWindow
        },

        function(){
            clearTimeout(timeoutCheck);
            self._convertArguments(arguments);

            cbOnce && cbOnce.apply(null, arguments);
        }
    );
};

Driver.prototype.setUrl = function(url, callback){
    if(asyncblock && callback == null){
        var flow = asyncblock.getCurrentFlow();

        if(flow){
            return flow.sync( this.setUrl(url, flow.add()) );
        }
    }

    if(callback == null){
        throw new Error('callback is required');
    }

    this.now.setUrl(url, callback);
};

Driver.prototype.reuseBrowser = function(harnessUrl, serverUrl){
    if(harnessUrl){
        harnessUrl = utility.constructHarnessUrl(harnessUrl, serverUrl);
    }

    this.now.reuseBrowser(harnessUrl);
};

Driver.prototype.waitFor = function(args, callback){
    var self = this;
    var startTime, func, timeout, exec, funcArgs, timeoutError, inBrowser;
    if(typeof args === 'object'){
        func = args.condition;
        startTime = args.startTime || new Date();
        timeout = args.timeoutMS || config.timeoutMS;
        exec = args.exec;
        funcArgs = args.args;
        timeoutError = args.timeoutError;
        inBrowser = args.inBrowser;
    } else {
        func = args;
        startTime = new Date();
        timeout = config.timeoutMS;
    }

    //Use asyncblock fibers if it is available
    if(asyncblock && callback == null){
        var flow = asyncblock.getCurrentFlow();

        if(flow){
            return flow.sync( this.waitFor(args, flow.add()) );
        }
    }

    if(callback == null){
        throw new Error('callback is required');
    }

    var _resultHandler = function(err, result){
        if(err && (!err.message || err.message.indexOf('exec timed out') < 0)){
            return callback(err);
        }

        if(result){
            return callback();
        } else {
            if(new Date() - startTime < timeout){
                setTimeout(function(){
                    //Need to re-create the asyncblock context
                    (asyncblock || function(fn){ fn(); })(function(){
                        self.waitFor({
                            condition: func,
                            timeoutMS: timeout,
                            startTime: startTime,
                            args: funcArgs,
                            timeoutError: timeoutError,
                            inBrowser: inBrowser
                        }, callback);
                    });
                }, config.retryMS);
            } else {
                if(!timeoutError) {
                    return callback(new Error('waitFor condition timed out (' + timeout + ')'));
                } else {
                    return callback(new Error('waitFor condition timed out (' + timeout + '): ' + timeoutError));
                }
            }
        }
    };

    if(inBrowser){
        this.exec({ func: func, args: funcArgs }, _resultHandler);

        if(exec){
            this.exec({ func: exec, args: funcArgs }, function(err){
                if(err){
                    return callback(err); //todo: prevent double callback
                }
            });
        }
    } else {
        //This exec needs to occur "out-of-process" or it'll block waiting on the condition when asyncblock is in use
        process.nextTick(function(){
            (asyncblock || function(fn){ fn(); })(function(){
                if(exec){
                    exec();
                }
            });
        });

        if(func.length === 1){
            func(_resultHandler);
        } else if(func.length === 0){
            _resultHandler(null, func());
        } else {
            throw new Error('func must take 0 arguments, or a callback');
        }
    }
};

Driver.prototype.findElement = function(args, callback){
    var self = this;
    var startTime, selector, context, multi, timeoutMS;
    if(typeof args === 'object'){
        selector = args.selector;
        startTime = args.startTime || new Date();
        context = args.context;
        multi = args.multi;
        timeoutMS = args.timeoutMS || config.timeoutMS;
    } else {
        selector = args;
        startTime = new Date();
        multi = false;
        timeoutMS = config.timeoutMS;
    }

    //Use asyncblock fibers if it is available
    if(asyncblock && callback == null){
        var flow = asyncblock.getCurrentFlow();

        if(flow){
            return flow.sync( this.findElement(args, flow.add()) );
        }
    }

    if(callback == null){
        throw new Error('callback is required');
    }

    this.exec({
        func: function(args){
            return $(args.selector, args.context);
        },

        args: { selector: selector, context: context }
    }, function(err, element){
        if(err){
            return callback(err);
        }

        if(element && (element.length === 1 || (multi && element.length > 0))) {
           callback(null, element);
        } else {
            if(new Date() - startTime < timeoutMS){
                setTimeout(function(){
                   self.findElement({ selector: selector, context: context, startTime: startTime, multi: multi, timeoutMS: timeoutMS }, callback);
                }, config.retryMS);
            } else {
                if(element && element.length > 1){
                    return callback(new Error('Element "' + selector + '" found, but there were too many instances (' + element.length + ')'));
                } else {
                    return callback(new Error('Element "' + selector + '" not found (timeout: ' + timeoutMS + ')'));
                }
            }
        }
    });
};

Driver.prototype.findElements = function(args, callback){
    if(typeof args === 'object'){
        args.multi = true;
    } else {
        args = { selector: args, multi: true };
    }

    return this.findElement(args, callback);
};

var _isVisible = function(element, callback){
    element._filterVisible(function(err, visibleElements){
        if(err) {
            return callback(err);
        }

        //Not all the elements may be visible, return the visible ones
        if(visibleElements && visibleElements.length > 0){
            callback(null, visibleElements);
        } else {
            callback(null, false);
        }
    });
};

Driver.prototype.findVisible = function(args, callback){
    var selector, multi;
    var self = this;

    if(typeof args === 'object'){
        selector = args.selector;
        multi = args.multi;
        args.startTime = args.startTime || new Date();
    } else {
        args = { selector: args, startTime: new Date() };
    }

    //Use asyncblock fibers if it is available
    if(asyncblock && callback == null){
        var flow = asyncblock.getCurrentFlow();

        if(flow){
            return flow.sync( this.findVisible(args, flow.add()) );
        }
    }

    if(callback == null){
        throw new Error('callback is required');
    }

    this.findElements(args, function(err, element){
        if(err){
            return callback(err);
        }

        _isVisible(element, function(err, visibles){
            if(err){
                return callback(err);
            }

            if(!visibles){
                if(new Date() - args.startTime < config.timeoutMS){
                    setTimeout(function(){
                        self.findVisible(args, callback);
                    }, config.retryMS);
                } else {
                    callback(new Error('Element "' + selector + '" was found, but is not visible.'));
                }

                return;
            }

            if(!multi && visibles.length > 1){
                return callback(new Error('Element "' + selector + '" found, but there were too many visible instances (' + visibles.length + ')'));
            }

            return callback(null, visibles);
        });
    });
};

Driver.prototype.findVisibles = function(args, callback){
    if(typeof args === 'object'){
        args.multi = true;
    } else {
        args = { selector: args, multi: true };
    }

    return this.findVisible(args, callback);
};

Driver.prototype.$ = Driver.prototype.find = function(selector, context, callback){
    if (callback == null && typeof context === 'function') {
        callback = context;
        context = null;
    }
    return this.exec({
        func: function(args){
            if (args.context != null) {
                return $(args.selector, args.context);
            } else {
                return $(args.selector);
            }
        },

        args: { selector: selector, context: context }
    }, callback);
};

Driver.prototype.clearLastPopupWindow = function(callback){
    //Use asyncblock fibers if it is available
    if(asyncblock && callback == null){
        var flow = asyncblock.getCurrentFlow();

        if(flow){
            return flow.sync( this.clearLastPopupWindow(flow.add()) );
        }
    }

    this.now.clearLastPopupWindow(callback);
};

Driver.prototype.getLastPopupWindow = function(callback){
    var self = this;

    //Use asyncblock fibers if it is available
    if(asyncblock && callback == null){
        var flow = asyncblock.getCurrentFlow();

        if(flow){
            return flow.sync( this.getLastPopupWindow(flow.add()) );
        }
    }

    return this.now.getLastPopupWindow(function(err, window){
        if(err) { return callback(err); }

        if(window != null){
            window = new WindowProxy(self, window.id);
        }

        return callback(null, window);
    });
};

Driver.prototype.isWindowOpen = function(windowProxy, callback){
    var self = this;

    //Use asyncblock fibers if it is available
    if(asyncblock && callback == null){
        var flow = asyncblock.getCurrentFlow();

        if(flow){
            return flow.sync( this.isWindowOpen(windowProxy, flow.add()) );
        }
    }

    return this.now.isWindowOpen(windowProxy, callback);
};

var _callOnce = function(callback){
    if(callback == null){
        return callback;
    }

    var called = false;
    return function(){
        if(!called){
            called = true;
            callback.apply(this, arguments);
        }
    };
};

module.exports = Driver;<|endoftext|>


<commit_before>var speedInterval = 50;
var acceleration = .4;
var speedRange = 256;

var speedOffset = 150;
var speedFactor = 0.4;
var startingPulse = 40;
var startingPulseDecrement = 10;

var pwmPin = 1;
var directionPin = 5;

var frontWhitePin = 3;
var frontRedPin = 15;
var rearWhitePin = 4;
var rearRedPin = 7;

Meteor.startup(function() {

	function sign(x) {
		return x > 0 ? 1 : x == 0 ? 0 : -1;
	}

	function oneIf(x) {
		return x ? 1 : 0;
	}

	try {
		var wpi = Meteor.npmRequire("wiring-pi");
		wpi.setup("wpi");
	} catch(e) {
		wpi = null;
	}

	Train.update({}, {$set: {wpi: wpi ? "available" : "not-available", targetspeed: 0, direction: 1, currentspeed: 0, currentdirection: 1, currentengineman: ''}}, {upsert: true});

	if (wpi) {

		// Initialize PWM

		wpi.pinMode(pwmPin, wpi.PWM_OUTPUT);
		wpi.pwmSetMode(wpi.PWM_MODE_MS);
		wpi.pwmSetClock(4);
		wpi.pwmSetRange(speedRange);
		wpi.pwmWrite(pwmPin, 0);

		// Initialize direction pin

		wpi.pinMode(directionPin, wpi.OUTPUT);
		wpi.digitalWrite(directionPin, 1);

		// Initialize light pins

		wpi.pinMode(frontWhitePin, wpi.OUTPUT);
		wpi.digitalWrite(frontWhitePin, 0);
		wpi.pinMode(frontRedPin, wpi.OUTPUT);
		wpi.digitalWrite(frontRedPin, 0);
		wpi.pinMode(rearWhitePin, wpi.OUTPUT);
		wpi.digitalWrite(rearWhitePin, 0);
		wpi.pinMode(rearRedPin, wpi.OUTPUT);
		wpi.digitalWrite(rearRedPin, 0);

	}

	var starting = startingPulse;

	// Initialize interval for speed updates

	Meteor.setInterval(function() {

		var train = Train.findOne();

		var signedTargetspeed = train.targetspeed * train.direction;
		var signedCurrentspeed = train.currentspeed * train.currentdirection;

		if (signedTargetspeed != signedCurrentspeed) {

			var newspeed = signedCurrentspeed +
				sign(signedTargetspeed - signedCurrentspeed) *
				Math.min(Math.abs(signedTargetspeed - signedCurrentspeed), acceleration);

			Train.update({}, {$set: {currentspeed: Math.abs(newspeed), currentdirection: sign(newspeed)}});

			if(sign(newspeed) != train.currentdirection) {
				starting = startingPulse;
			}

			if (wpi) {

				// control the engine

				wpi.pwmWrite(pwmPin, Math.floor(speedFactor * Math.abs(newspeed)) + (Math.abs(newspeed) > 0 ? speedOffset + starting : 0));
				if (starting > 0) starting -= startingPulseDecrement;

				wpi.digitalWrite(directionPin, newspeed >= 0 ? 1 : 0);

				// switch the lights

				if (newspeed != 0) {
					wpi.digitalWrite(frontWhitePin, oneIf(newspeed > 0));
					wpi.digitalWrite(frontRedPin, oneIf(newspeed < 0));
					wpi.digitalWrite(rearWhitePin, oneIf(newspeed < 0));
					wpi.digitalWrite(rearRedPin, oneIf(newspeed > 0));
				}

			} else {
				console.log("Controlling train: speed = " + Math.abs(newspeed) + "  direction = " + (newspeed >= 0));
			}

		}

		if (signedCurrentspeed == 0 && wpi) {

			var engineman = (train.currentengineman != "");

			wpi.digitalWrite(frontWhitePin, oneIf(engineman && train.direction > 0));
			wpi.digitalWrite(frontRedPin, oneIf(engineman && train.direction <= 0));
			wpi.digitalWrite(rearWhitePin, oneIf(engineman && train.direction < 0));
			wpi.digitalWrite(rearRedPin, oneIf(engineman && train.direction >= 0));
		}

	}, speedInterval);

});

<commit_msg>fix: assigned pins<commit_after>var speedInterval = 50;
var acceleration = .4;
var speedRange = 256;

var speedOffset = 150;
var speedFactor = 0.4;
var startingPulse = 40;
var startingPulseDecrement = 10;

var pwmPin = 1;
var directionPin1 = 2;
var directionPin2 = 3;

var frontWhitePin = 6;
var frontRedPin = 7;
var rearWhitePin = 5;
var rearRedPin = 4;

Meteor.startup(function() {

	function sign(x) {
		return x > 0 ? 1 : x == 0 ? 0 : -1;
	}

	function oneIf(x) {
		return x ? 1 : 0;
	}

	try {
		var wpi = Meteor.npmRequire("wiring-pi");
		wpi.setup("wpi");
	} catch(e) {
		wpi = null;
	}

	Train.update({}, {$set: {wpi: wpi ? "available" : "not-available", targetspeed: 0, direction: 1, currentspeed: 0, currentdirection: 1, currentengineman: ''}}, {upsert: true});

	if (wpi) {

		// Initialize PWM

		wpi.pinMode(pwmPin, wpi.PWM_OUTPUT);
		wpi.pwmSetMode(wpi.PWM_MODE_MS);
		wpi.pwmSetClock(4);
		wpi.pwmSetRange(speedRange);
		wpi.pwmWrite(pwmPin, 0);

		// Initialize direction pin

		wpi.pinMode(directionPin1, wpi.OUTPUT);
		wpi.digitalWrite(directionPin1, 1);
		wpi.pinMode(directionPin2, wpi.OUTPUT);
		wpi.digitalWrite(directionPin2, 1);

		// Initialize light pins

		wpi.pinMode(frontWhitePin, wpi.OUTPUT);
		wpi.digitalWrite(frontWhitePin, 0);
		wpi.pinMode(frontRedPin, wpi.OUTPUT);
		wpi.digitalWrite(frontRedPin, 0);
		wpi.pinMode(rearWhitePin, wpi.OUTPUT);
		wpi.digitalWrite(rearWhitePin, 0);
		wpi.pinMode(rearRedPin, wpi.OUTPUT);
		wpi.digitalWrite(rearRedPin, 0);

	}

	var starting = startingPulse;

	// Initialize interval for speed updates

	Meteor.setInterval(function() {

		var train = Train.findOne();

		var signedTargetspeed = train.targetspeed * train.direction;
		var signedCurrentspeed = train.currentspeed * train.currentdirection;

		if (signedTargetspeed != signedCurrentspeed) {

			var newspeed = signedCurrentspeed +
				sign(signedTargetspeed - signedCurrentspeed) *
				Math.min(Math.abs(signedTargetspeed - signedCurrentspeed), acceleration);

			Train.update({}, {$set: {currentspeed: Math.abs(newspeed), currentdirection: sign(newspeed)}});

			if(sign(newspeed) != train.currentdirection) {
				starting = startingPulse;
			}

			if (wpi) {

				// control the engine

				wpi.pwmWrite(pwmPin, Math.floor(speedFactor * Math.abs(newspeed)) + (Math.abs(newspeed) > 0 ? speedOffset + starting : 0));
				if (starting > 0) starting -= startingPulseDecrement;

				wpi.digitalWrite(directionPin1, newspeed >= 0 ? 1 : 0);
				wpi.digitalWrite(directionPin2, newspeed >= 0 ? 0 : 1);

				// switch the lights

				if (newspeed != 0) {
					wpi.digitalWrite(frontWhitePin, oneIf(newspeed > 0));
					wpi.digitalWrite(frontRedPin, oneIf(newspeed < 0));
					wpi.digitalWrite(rearWhitePin, oneIf(newspeed < 0));
					wpi.digitalWrite(rearRedPin, oneIf(newspeed > 0));
				}

			} else {
				console.log("Controlling train: speed = " + Math.abs(newspeed) + "  direction = " + (newspeed >= 0));
			}

		}

		if (signedCurrentspeed == 0 && wpi) {

			var engineman = (train.currentengineman != "");

			wpi.digitalWrite(frontWhitePin, oneIf(engineman && train.direction > 0));
			wpi.digitalWrite(frontRedPin, oneIf(engineman && train.direction <= 0));
			wpi.digitalWrite(rearWhitePin, oneIf(engineman && train.direction < 0));
			wpi.digitalWrite(rearRedPin, oneIf(engineman && train.direction >= 0));
		}

	}, speedInterval);

});

<|endoftext|>


<commit_before>'use strict';

var errors = {
  BADGE_NOT_FOUND: 'Badge not found.',
  USER_NOT_IDEA_USER: 'You must first register in the iDEA hub.',
  AUTHENTICATION_FAILURE: 'Authentication failure.',
  DATABASE_ERROR_SAVE: 'Error saving to database.',
  USER_UNAUTHORIZED: 'You are not authorized to use Badge Builder. Please contact the iDEA team by emailing to XYZ to get instructions on how to get started.'
};

module.exports = errors;
<commit_msg>Changed error text<commit_after>'use strict';

var errors = {
  BADGE_NOT_FOUND: 'Badge not found.',
  USER_NOT_IDEA_USER: 'You must first register in the iDEA hub.',
  AUTHENTICATION_FAILURE: 'Authentication failure.',
  DATABASE_ERROR_SAVE: 'Error saving to database.',
  USER_UNAUTHORIZED: 'You are not authorized to use Badge Builder. Please contact the iDEA team for instructions on how to get started.'
};

module.exports = errors;
<|endoftext|>


<commit_before>const { assign } = require('lodash');
const { getDb } = require('./db');

async function logEvent(payload) {
    const db = await getDb(process.env.DB_URL);
    const collection = await db.collection('eventlog');
    await collection.insertOne(assign({}, payload, { time: Date.now() }));
}

module.exports = {
    logGetAllRooms: id => logEvent({ type: 'GET_ALL_ROOMS', user: id }),
    logError: e => logEvent({ type: 'SERVER_ERROR', error: JSON.stringify(e) })
};
<commit_msg>added an event for getting one room<commit_after>const { assign } = require('lodash');
const { getDb } = require('./db');

async function logEvent(payload) {
    const db = await getDb(process.env.DB_URL);
    const collection = await db.collection('eventlog');
    await collection.insertOne(assign({}, payload, { time: Date.now() }));
}

/* eslint-disable object-shorthand */
module.exports = {
    logGetAllRooms: user => logEvent({ type: 'GET_ALL_ROOMS', user }),
    logGetRoomLights: (user, room) => logEvent({ type: 'GET_ROOM_LIGHTS', user, room }),
    logError: e => logEvent({ type: 'SERVER_ERROR', error: JSON.stringify(e) })
};
/* eslint-enable object-shorthand */
<|endoftext|>


<commit_before>import del from 'del'
import cp from 'recursive-copy'
import mkdirp from 'mkdirp-then'
import walk from 'walk'
import { resolve, join, dirname, sep } from 'path'
import { existsSync, readFileSync, writeFileSync } from 'fs'
import getConfig from './config'
import { renderToHTML } from './render'
import { printAndExit } from '../lib/utils'

export default async function (dir, options) {
  dir = resolve(dir)
  const outDir = options.outdir
  const nextDir = join(dir, '.next')

  log(`  Exporting to: ${outDir}\n`)

  if (!existsSync(nextDir)) {
    console.error('Build your with "next build" before running "next start".')
    process.exit(1)
  }

  const config = getConfig(dir)
  const buildId = readFileSync(join(nextDir, 'BUILD_ID'), 'utf8')
  const buildStats = require(join(nextDir, 'build-stats.json'))

  // Initialize the output directory
  await del(join(outDir, '*'))
  await mkdirp(join(outDir, '_next', buildStats['app.js'].hash))
  await mkdirp(join(outDir, '_next', buildId))

  // Copy files
  await cp(
    join(nextDir, 'app.js'),
    join(outDir, '_next', buildStats['app.js'].hash, 'app.js')
  )

  // Copy static directory
  if (existsSync(join(dir, 'static'))) {
    log('  copying "static" directory')
    await cp(
      join(dir, 'static'),
      join(outDir, 'static')
    )
  }

  // Copy dynamic import chunks
  if (existsSync(join(nextDir, 'chunks'))) {
    log('  copying dynamic import chunks')

    await mkdirp(join(outDir, '_next', 'webpack'))
    await cp(
      join(nextDir, 'chunks'),
      join(outDir, '_next', 'webpack', 'chunks')
    )
  }

  await copyPages(nextDir, outDir, buildId)

  // Get the exportPathMap from the `next.config.js`
  if (typeof config.exportPathMap !== 'function') {
    printAndExit(
      '> Could not found "exportPathMap" function inside "next.config.js"\n' +
      '> "next export" uses that function build html pages.'
    )
  }

  const exportPathMap = await config.exportPathMap()
  const exportPaths = Object.keys(exportPathMap)

  // Start the rendering process
  const renderOpts = {
    dir,
    buildStats,
    buildId,
    nextExport: true,
    assetPrefix: config.assetPrefix.replace(/\/$/, ''),
    dev: false,
    staticMarkup: false,
    hotReloader: null
  }

  // We need this for server rendering the Link component.
  global.__NEXT_DATA__ = {
    nextExport: true
  }

  for (const path of exportPaths) {
    log(`  exporting path: ${path}`)

    const { page, query = {} } = exportPathMap[path]
    const req = { url: path }
    const res = {}

    const htmlFilename = path === '/' ? 'index.html' : `${path}${sep}index.html`
    const baseDir = join(outDir, dirname(htmlFilename))
    const htmlFilepath = join(outDir, htmlFilename)

    await mkdirp(baseDir)

    const html = await renderToHTML(req, res, page, query, renderOpts)
    writeFileSync(htmlFilepath, html, 'utf8')
  }

  // Add an empty line to the console for the better readability.
  log('')

  function log (message) {
    if (options.silent) return
    console.log(message)
  }
}

function copyPages (nextDir, outDir, buildId) {
  // TODO: do some proper error handling
  return new Promise((resolve, reject) => {
    const nextBundlesDir = join(nextDir, 'bundles', 'pages')
    const walker = walk.walk(nextBundlesDir, { followLinks: false })

    walker.on('file', (root, stat, next) => {
      const filename = stat.name
      const fullFilePath = `${root}${sep}${filename}`
      const relativeFilePath = fullFilePath.replace(nextBundlesDir, '')

      // We should not expose this page to the client side since
      // it has no use in the client side.
      if (relativeFilePath === '/_document.js') {
        next()
        return
      }

      let destFilePath = null
      if (/index\.js$/.test(filename)) {
        destFilePath = join(outDir, '_next', buildId, 'page', relativeFilePath)
      } else {
        const newRelativeFilePath = relativeFilePath.replace(/\.js/, `${sep}index.js`)
        destFilePath = join(outDir, '_next', buildId, 'page', newRelativeFilePath)
      }

      cp(fullFilePath, destFilePath)
        .then(next)
        .catch(reject)
    })

    walker.on('end', resolve)
  })
}
<commit_msg>support custom build directory in next export (#2135)<commit_after>import del from 'del'
import cp from 'recursive-copy'
import mkdirp from 'mkdirp-then'
import walk from 'walk'
import { resolve, join, dirname, sep } from 'path'
import { existsSync, readFileSync, writeFileSync } from 'fs'
import getConfig from './config'
import { renderToHTML } from './render'
import { printAndExit } from '../lib/utils'

export default async function (dir, options) {
  dir = resolve(dir)
  const config = getConfig(dir)
  const nextDir = join(dir, config.distDir || '.next')

  log(`  using build directory: ${nextDir}`)

  if (!existsSync(nextDir)) {
    console.error(
      `Build directory ${nextDir} does not exist. Make sure you run "next build" before running "next start" or "next export".`
    )
    process.exit(1)
  }

  const buildId = readFileSync(join(nextDir, 'BUILD_ID'), 'utf8')
  const buildStats = require(join(nextDir, 'build-stats.json'))

  // Initialize the output directory
  const outDir = options.outdir
  await del(join(outDir, '*'))
  await mkdirp(join(outDir, '_next', buildStats['app.js'].hash))
  await mkdirp(join(outDir, '_next', buildId))

  // Copy files
  await cp(
    join(nextDir, 'app.js'),
    join(outDir, '_next', buildStats['app.js'].hash, 'app.js')
  )

  // Copy static directory
  if (existsSync(join(dir, 'static'))) {
    log('  copying "static" directory')
    await cp(
      join(dir, 'static'),
      join(outDir, 'static')
    )
  }

  // Copy dynamic import chunks
  if (existsSync(join(nextDir, 'chunks'))) {
    log('  copying dynamic import chunks')

    await mkdirp(join(outDir, '_next', 'webpack'))
    await cp(
      join(nextDir, 'chunks'),
      join(outDir, '_next', 'webpack', 'chunks')
    )
  }

  await copyPages(nextDir, outDir, buildId)

  // Get the exportPathMap from the `next.config.js`
  if (typeof config.exportPathMap !== 'function') {
    printAndExit(
      '> Could not found "exportPathMap" function inside "next.config.js"\n' +
      '> "next export" uses that function build html pages.'
    )
  }

  const exportPathMap = await config.exportPathMap()
  const exportPaths = Object.keys(exportPathMap)

  // Start the rendering process
  const renderOpts = {
    dir,
    buildStats,
    buildId,
    nextExport: true,
    assetPrefix: config.assetPrefix.replace(/\/$/, ''),
    dev: false,
    staticMarkup: false,
    hotReloader: null
  }

  // We need this for server rendering the Link component.
  global.__NEXT_DATA__ = {
    nextExport: true
  }

  for (const path of exportPaths) {
    log(`  exporting path: ${path}`)

    const { page, query = {} } = exportPathMap[path]
    const req = { url: path }
    const res = {}

    const htmlFilename = path === '/' ? 'index.html' : `${path}${sep}index.html`
    const baseDir = join(outDir, dirname(htmlFilename))
    const htmlFilepath = join(outDir, htmlFilename)

    await mkdirp(baseDir)

    const html = await renderToHTML(req, res, page, query, renderOpts)
    writeFileSync(htmlFilepath, html, 'utf8')
  }

  // Add an empty line to the console for the better readability.
  log('')

  function log (message) {
    if (options.silent) return
    console.log(message)
  }
}

function copyPages (nextDir, outDir, buildId) {
  // TODO: do some proper error handling
  return new Promise((resolve, reject) => {
    const nextBundlesDir = join(nextDir, 'bundles', 'pages')
    const walker = walk.walk(nextBundlesDir, { followLinks: false })

    walker.on('file', (root, stat, next) => {
      const filename = stat.name
      const fullFilePath = `${root}${sep}${filename}`
      const relativeFilePath = fullFilePath.replace(nextBundlesDir, '')

      // We should not expose this page to the client side since
      // it has no use in the client side.
      if (relativeFilePath === '/_document.js') {
        next()
        return
      }

      let destFilePath = null
      if (/index\.js$/.test(filename)) {
        destFilePath = join(outDir, '_next', buildId, 'page', relativeFilePath)
      } else {
        const newRelativeFilePath = relativeFilePath.replace(/\.js/, `${sep}index.js`)
        destFilePath = join(outDir, '_next', buildId, 'page', newRelativeFilePath)
      }

      cp(fullFilePath, destFilePath)
        .then(next)
        .catch(reject)
    })

    walker.on('end', resolve)
  })
}
<|endoftext|>


<commit_before>import del from 'del'
import cp from 'recursive-copy'
import mkdirp from 'mkdirp-then'
import walk from 'walk'
import { resolve, join, dirname, sep } from 'path'
import { existsSync, readFileSync, writeFileSync } from 'fs'
import getConfig from './config'
import { renderToHTML } from './render'
import { printAndExit } from '../lib/utils'

export default async function (dir, options) {
  dir = resolve(dir)
  const outDir = options.outdir
  const nextDir = join(dir, '.next')

  if (!existsSync(nextDir)) {
    console.error('Build your with "next build" before running "next start".')
    process.exit(1)
  }

  const config = getConfig(dir)
  const buildId = readFileSync(join(nextDir, 'BUILD_ID'), 'utf8')
  const buildStats = require(join(nextDir, 'build-stats.json'))

  // Initialize the output directory
  await del(outDir)
  await mkdirp(join(outDir, '_next', buildStats['app.js'].hash))
  await mkdirp(join(outDir, '_next', buildId))

  // Copy files
  await cp(
    join(nextDir, 'app.js'),
    join(outDir, '_next', buildStats['app.js'].hash, 'app.js')
  )

  await copyPages(nextDir, outDir, buildId)

  // Get the exportPathMap from the `next.config.js`
  if (typeof config.exportPathMap !== 'function') {
    printAndExit(
      '> Could not found "exportPathMap" function inside "next.config.js"\n' +
      '> "next export" uses that function build html pages.'
    )
  }

  const exportPathMap = await config.exportPathMap()
  const exportPaths = Object.keys(exportPathMap)

  // Start the rendering process
  const renderOpts = {
    dir,
    buildStats,
    buildId,
    nextExport: true,
    assetPrefix: config.assetPrefix.replace(/\/$/, ''),
    dev: false,
    staticMarkup: false,
    hotReloader: null
  }

  // We need this for server rendering the Link component.
  global.__NEXT_DATA__ = {
    nextExport: true
  }

  for (const path of exportPaths) {
    if (options.verbose) {
      console.log(`  exporing path: ${path}`)
    }

    const { page, query } = exportPathMap[path]
    const req = { url: path }
    const res = {}

    const htmlFilename = path === '/' ? 'index.html' : `${path}${sep}index.html`
    const baseDir = join(outDir, dirname(htmlFilename))
    const htmlFilepath = join(outDir, htmlFilename)

    await mkdirp(baseDir)

    const html = await renderToHTML(req, res, page, query, renderOpts)
    writeFileSync(htmlFilepath, html, 'utf8')
  }
}

function copyPages (nextDir, outDir, buildId) {
  // TODO: do some proper error handling
  return new Promise((resolve, reject) => {
    const nextBundlesDir = join(nextDir, 'bundles', 'pages')
    const walker = walk.walk(nextBundlesDir, { followLinks: false })

    walker.on('file', (root, stat, next) => {
      const filename = stat.name
      const fullFilePath = `${root}${sep}${filename}`
      const relativeFilePath = fullFilePath.replace(nextBundlesDir, '')

      let destFilePath = null
      if (/index\.js$/.test(filename)) {
        destFilePath = join(outDir, '_next', buildId, 'page', relativeFilePath)
      } else {
        const newRelativeFilePath = relativeFilePath.replace(/\.js/, `${sep}index.js`)
        destFilePath = join(outDir, '_next', buildId, 'page', newRelativeFilePath)
      }

      cp(fullFilePath, destFilePath)
        .then(next)
        .catch(reject)
    })

    walker.on('end', resolve)
  })
}
<commit_msg>Do not include /_document.js when running 'next export'<commit_after>import del from 'del'
import cp from 'recursive-copy'
import mkdirp from 'mkdirp-then'
import walk from 'walk'
import { resolve, join, dirname, sep } from 'path'
import { existsSync, readFileSync, writeFileSync } from 'fs'
import getConfig from './config'
import { renderToHTML } from './render'
import { printAndExit } from '../lib/utils'

export default async function (dir, options) {
  dir = resolve(dir)
  const outDir = options.outdir
  const nextDir = join(dir, '.next')

  if (!existsSync(nextDir)) {
    console.error('Build your with "next build" before running "next start".')
    process.exit(1)
  }

  const config = getConfig(dir)
  const buildId = readFileSync(join(nextDir, 'BUILD_ID'), 'utf8')
  const buildStats = require(join(nextDir, 'build-stats.json'))

  // Initialize the output directory
  await del(outDir)
  await mkdirp(join(outDir, '_next', buildStats['app.js'].hash))
  await mkdirp(join(outDir, '_next', buildId))

  // Copy files
  await cp(
    join(nextDir, 'app.js'),
    join(outDir, '_next', buildStats['app.js'].hash, 'app.js')
  )

  await copyPages(nextDir, outDir, buildId)

  // Get the exportPathMap from the `next.config.js`
  if (typeof config.exportPathMap !== 'function') {
    printAndExit(
      '> Could not found "exportPathMap" function inside "next.config.js"\n' +
      '> "next export" uses that function build html pages.'
    )
  }

  const exportPathMap = await config.exportPathMap()
  const exportPaths = Object.keys(exportPathMap)

  // Start the rendering process
  const renderOpts = {
    dir,
    buildStats,
    buildId,
    nextExport: true,
    assetPrefix: config.assetPrefix.replace(/\/$/, ''),
    dev: false,
    staticMarkup: false,
    hotReloader: null
  }

  // We need this for server rendering the Link component.
  global.__NEXT_DATA__ = {
    nextExport: true
  }

  for (const path of exportPaths) {
    if (options.verbose) {
      console.log(`  exporing path: ${path}`)
    }

    const { page, query } = exportPathMap[path]
    const req = { url: path }
    const res = {}

    const htmlFilename = path === '/' ? 'index.html' : `${path}${sep}index.html`
    const baseDir = join(outDir, dirname(htmlFilename))
    const htmlFilepath = join(outDir, htmlFilename)

    await mkdirp(baseDir)

    const html = await renderToHTML(req, res, page, query, renderOpts)
    writeFileSync(htmlFilepath, html, 'utf8')
  }
}

function copyPages (nextDir, outDir, buildId) {
  // TODO: do some proper error handling
  return new Promise((resolve, reject) => {
    const nextBundlesDir = join(nextDir, 'bundles', 'pages')
    const walker = walk.walk(nextBundlesDir, { followLinks: false })

    walker.on('file', (root, stat, next) => {
      const filename = stat.name
      const fullFilePath = `${root}${sep}${filename}`
      const relativeFilePath = fullFilePath.replace(nextBundlesDir, '')

      // We should not expose this page to the client side since
      // it has no use in the client side.
      if (relativeFilePath === '/_document.js') {
        next()
        return
      }

      let destFilePath = null
      if (/index\.js$/.test(filename)) {
        destFilePath = join(outDir, '_next', buildId, 'page', relativeFilePath)
      } else {
        const newRelativeFilePath = relativeFilePath.replace(/\.js/, `${sep}index.js`)
        destFilePath = join(outDir, '_next', buildId, 'page', newRelativeFilePath)
      }

      cp(fullFilePath, destFilePath)
        .then(next)
        .catch(reject)
    })

    walker.on('end', resolve)
  })
}
<|endoftext|>


<commit_before>var Fiber = Npm.require('fibers');
var SockJS = Meteor.require('sockjs-client');
var Q = Meteor.require('q');

function toJson(v) {
	if (typeof v == 'string') {
		try {
			return JSON.parse(v);
		} catch (err) {
			return v;
		}
	}
	return v;
}

function fbsync_startup() {
	// TODO sync existing work items
	// TODO fetch new milestones
}

// helper function to create session with fogbugz service
function fbc(endpoint) {
	if (endpoint.charAt(endpoint.length - 1) != '/') {
		endpoint += '/';
	}

	// TODO use admin credentials
	var user = Meteor.users.findOne({"services.fogbugz.endpoint": endpoint});
	if (!user) {
		return Q.reject("unknown fogbugz service " + endpoint);
	}

	var service = user.services.fogbugz;
	return fogbugz({
		url: endpoint,
		token: service.token,
		// verbose: true // uncomment for verbose logging of fogbugz requests
	});
}

function fbsync(e) {
	if (!e) return;

	console.log('[fbsync] operation start');

	if (!e.from) {
		// TODO handle anonymous event
		console.log('[fbsync] does not support anonymous events for now');
		return;
	}

	var event = (e.event || '').toLowerCase();
	if (!event || !e.id) {
		// ignore unknown events
		console.log('[fbsync] event is ignored');
		return;
	}

	if (event.indexOf('case') >= 0) {
		fbc(e.from).then(function(client) {
			return client.caseInfo(id);
		}).then(function(info) {
					var item = FogBugzService.toWorkItem(info);
					return updateWorkItem(item);
				});
	}
}

function updateWorkItem(item) {
	// meteor requires fibers
	Fiber(function() {
		console.log("[fbsync] updating item %s", item.id);
		var oldItem = WorkItems.findOne({id: item.id});
		if (!oldItem) {
			WorkItems.insert(item);
		} else {
			WorkItems.update(oldItem._id, item);
		}
	}).run();
}

// TODO disconnect from fogbus on meteor restart and process exit
function fogbus_connect(callback) {
	var connected = false;
	var sock = SockJS.create('http://fogbus.herokuapp.com/fogbus');
	sock.on('connection', function() {
		connected = true;
		console.log('[fogbus] connection is established');
		callback(sock);
	});
	sock.on('error', function(err) {
		console.log('[fogbus] error:\n', JSON.stringify(err, null, 2));
		if (!connected) {
			// try again
			fogbus_connect(callback);
		}
	});
}

// creates sockjs client to listen fogbus events
function fogbus_startup() {
	fogbus_connect(function(sock) {
		sock.on('data', function(e) {
			e = toJson(e);
			console.log('[fogbus] message:\n', JSON.stringify(e, null, 2));
			// meteor requires fibers
			Fiber(function() {
				fbsync(e);
			}).run();
		});
		sock.on('error', function(err) {
			err = toJson(err);
			console.log('[fogbus] error:\n', JSON.stringify(err, null, 2));
		});
	});
}

Meteor.startup(function() {
	fbsync_startup();
	fogbus_startup();
});
<commit_msg>fix fogbugz ref<commit_after>var Fiber = Npm.require('fibers');
var SockJS = Meteor.require('sockjs-client');
var Q = Meteor.require('q');

function toJson(v) {
	if (typeof v == 'string') {
		try {
			return JSON.parse(v);
		} catch (err) {
			return v;
		}
	}
	return v;
}

function fbsync_startup() {
	// TODO sync existing work items
	// TODO fetch new milestones
}

// helper function to create session with fogbugz service
function fbc(endpoint) {
	if (endpoint.charAt(endpoint.length - 1) != '/') {
		endpoint += '/';
	}

	// TODO use admin credentials
	var user = Meteor.users.findOne({"services.fogbugz.endpoint": endpoint});
	if (!user) {
		return Q.reject("unknown fogbugz service " + endpoint);
	}

	var service = user.services.fogbugz;
	var fogbugz = Meteor.require('fogbugz.js');
	return fogbugz({
		url: endpoint,
		token: service.token,
		// verbose: true // uncomment for verbose logging of fogbugz requests
	});
}

function fbsync(e) {
	if (!e) return;

	console.log('[fbsync] operation start');

	if (!e.from) {
		// TODO handle anonymous event
		console.log('[fbsync] does not support anonymous events for now');
		return;
	}

	var event = (e.event || '').toLowerCase();
	if (!event || !e.id) {
		// ignore unknown events
		console.log('[fbsync] event is ignored');
		return;
	}

	if (event.indexOf('case') >= 0) {
		fbc(e.from).then(function(client) {
			return client.caseInfo(id);
		}).then(function(info) {
					var item = FogBugzService.toWorkItem(info);
					return updateWorkItem(item);
				});
	}
}

function updateWorkItem(item) {
	// meteor requires fibers
	Fiber(function() {
		console.log("[fbsync] updating item %s", item.id);
		var oldItem = WorkItems.findOne({id: item.id});
		if (!oldItem) {
			WorkItems.insert(item);
		} else {
			WorkItems.update(oldItem._id, item);
		}
	}).run();
}

// TODO disconnect from fogbus on meteor restart and process exit
function fogbus_connect(callback) {
	var connected = false;
	var sock = SockJS.create('http://fogbus.herokuapp.com/fogbus');
	sock.on('connection', function() {
		connected = true;
		console.log('[fogbus] connection is established');
		callback(sock);
	});
	sock.on('error', function(err) {
		console.log('[fogbus] error:\n', JSON.stringify(err, null, 2));
		if (!connected) {
			// try again
			fogbus_connect(callback);
		}
	});
}

// creates sockjs client to listen fogbus events
function fogbus_startup() {
	fogbus_connect(function(sock) {
		sock.on('data', function(e) {
			e = toJson(e);
			console.log('[fogbus] message:\n', JSON.stringify(e, null, 2));
			// meteor requires fibers
			Fiber(function() {
				fbsync(e);
			}).run();
		});
		sock.on('error', function(err) {
			err = toJson(err);
			console.log('[fogbus] error:\n', JSON.stringify(err, null, 2));
		});
	});
}

Meteor.startup(function() {
	fbsync_startup();
	fogbus_startup();
});
<|endoftext|>


<commit_before>Meteor.startup(function () {
  Kadira.connect('XQQfFaD3MckQS2adc', '5b1679c8-4ad6-4810-803c-555081b652bd')
});<commit_msg>Move kadira keys to settings file<commit_after>Meteor.startup(function () {
  Kadira.connect(Meteor.settings.kadiraId, Meteor.settings.kadiraSecret);
});
<|endoftext|>


<commit_before>'use strict'

const db = require('APP/db')
const Order = db.model('orders')
const OrderItem = db.model('order_items')

const {mustBeLoggedIn, forbidden, selfOnly} = require('./auth.filters')

module.exports = require('express').Router()
  .get('/',
    // The forbidden middleware will fail *all* requests to list users.
    // Remove it if you want to allow anyone to list all users on the site.
    //
    // If you want to only let admins list all the users, then you'll
    // have to add a role column to the users table to support
    // the concept of admin users.
    forbidden('listing orders is not allowed'),
    (req, res, next) =>
      Order.findAll()
        .then(orders => res.json(orders))
        .catch(next))
  .post('/',
    (req, res, next) =>
      Order.create({
        date_fulfilled: req.body.date,
        email: req.body.email ? req.body.email : req.user.email,
        user_id: req.body.email ? null : req.user.id
      })
      .then(createdOrder => {
        return OrderItem.bulkCreate(req.body.orderItems)
      })
      .then(orderItems => res.status(201).json(orderItems))
      .catch(next))
  .get('/:id',
    mustBeLoggedIn,
    (req, res, next) =>
      Order.findById(req.params.id)
      .then(order => res.json(order))
      .catch(next))
  .put('/:id',
    selfOnly,
    (req, res, next) =>
      Order.findById(req.params.id)
      .then(order => order.updateAttributes(req.body))
      .catch(next))
  .delete('/:id',
    forbidden('deleting orders is not allowed'),
    (req, res, next) =>
      Order.findById(req.params.id)
      .then(order => order.destroy())
      .catch(next))
<commit_msg>updated order routes<commit_after>'use strict'

const db = require('APP/db')
const Order = db.model('orders')
const OrderItem = db.model('order_items')

const {mustBeLoggedIn, forbidden, selfOnly} = require('./auth.filters')

module.exports = require('express').Router()
  .get('/',
    // The forbidden middleware will fail *all* requests to list users.
    // Remove it if you want to allow anyone to list all users on the site.
    //
    // If you want to only let admins list all the users, then you'll
    // have to add a role column to the users table to support
    // the concept of admin users.
    forbidden('listing orders is not allowed'),
    (req, res, next) =>
      Order.findAll()
        .then(orders => res.json(orders))
        .catch(next))
  .post('/',
    (req, res, next) =>
      Order.create({
        date_fulfilled: req.body.date,
        email: req.body.email ? req.body.email : req.user.email,
        user_id: req.body.email ? null : req.user.id
      })
      .then(createdOrder => {
        return OrderItem.bulkCreate(req.body.orderItems)
      })
      .then(orderItems => res.status(201).json(orderItems))
      .catch(next))
  .get('/:id',
    forbidden('Unauthorize access.'),
    (req, res, next) =>
      OrderItem.findAll({
        where: {
          order_id: req.params.id,
        }
      })
      .then(order => res.json(order))
      .catch(next))
  .put('/:id',
    selfOnly,
    (req, res, next) =>
      Order.findById(req.params.id)
      .then(order => order.updateAttributes(req.body))
      .catch(next))
  .delete('/:id',
    forbidden('deleting orders is not allowed'),
    (req, res, next) =>
      Order.findById(req.params.id)
      .then(order => order.destroy())
      .catch(next))
<|endoftext|>


<commit_before>var path = require('path');

//uui定制
var customized = require("./customized");
var down = require("./down");

module.exports = {
  setRouters: function(router ,ctx){
    router.get('/loadMenu', function *(next) {
        var demos = require('../conf/snippets.conf.json');
        this.body = demos;//JSON.stringify('test');
    });

    router.get('/loadMenuPure', function *(next) {
        var demos = require('./demos-pure.json');
        this.body = demos;//JSON.stringify('test');
    });

    router.post('/getWidgets', function *(next) {
      var fs = require("fs");
      var url = this.request.body.wUrl;
      var datas = {}
      var _html  = _css = _script = '';

      // 相对于当前执行文件的目录
      if (fs.existsSync('../dist/pages/webIDE/' + url + '/widget.html'))
        _html = fs.readFileSync('../dist/pages/webIDE/' + url + '/widget.html');
      if (fs.existsSync('../dist/pages/webIDE/' + url + '/widget.css'))
        _css = fs.readFileSync('../dist/pages/webIDE/' + url + '/widget.css');
      if (fs.existsSync('../dist/pages/webIDE/' + url + '/widget.js'))
        _script = fs.readFileSync('../dist/pages/webIDE/' + url + '/widget.js');

      datas.html = _html.toString();
      datas.css = _css.toString();
      datas.script = _script.toString();
      this.body = datas;
    });

    router.post('/runDemo', function *(next) {
        // this.request.body;
        // console.log(this.request.body.html_code);
        var styles = this.request.body.css_code;
        var htmls = this.request.body.html_code;
        var scripts = this.request.body.script_code;
        var ctxPath='http://design.yyuap.com/static/uui-original/1.0.1';
        var tpl = [
          '<!DOCTYPE html>',
          '',
          '',
          '<meta charset="UTF-8">',
          '<meta name="viewport" content="width=device-width, initial-scale=1">',
          '<title>Title</title>',
		  '<link rel="stylesheet" href="'+ ctxPath +'/fonts/font-awesome/css/font-awesome.css">',
          '<link rel="stylesheet" type="text/css" href="'+ ctxPath +'/css/u.css">',
          '<link rel="stylesheet" type="text/css" href="'+ ctxPath +'/css/u-extend.css">',
		      '<link rel="stylesheet" type="text/css" href="'+ ctxPath +'/css/tree.css">',
          '<link rel="stylesheet" type="text/css" href="'+ ctxPath +'/css/grid.css">',
          '',
          '',
          '',
          htmls,
          '',
    	    '',
          '',
          '',
          '',
          '',
			    '',
          '',
          '',
          ''
        ]
        this.body = tpl.join(""); ;//JSON.stringify('test');
    });

    //uui定制相关
    router.post('/customized', function *(next) {
      var self = this;
      yield function(cb){
          customized.run(self,cb);
      }

    });

    router.get('/down', function *(next) {
      var self = this;
      yield function(cb){
          down.run(self,cb);
      }
    });

  }

}
<commit_msg>修改node路由上路径的bug<commit_after>var path = require('path');

//uui定制
var customized = require("./customized");
var down = require("./down");

module.exports = {
  setRouters: function(router ,ctx){
    router.get('/loadMenu', function *(next) {
        var demos = require('../conf/snippets.conf.json');
        this.body = demos;//JSON.stringify('test');
    });

    router.get('/loadMenuPure', function *(next) {
        var demos = require('./demos-pure.json');
        this.body = demos;//JSON.stringify('test');
    });

    router.post('/getWidgets', function *(next) {
      var fs = require("fs");
      var url = this.request.body.wUrl;
      var datas = {}
      var _html  = _css = _script = '';

      // 相对于当前执行文件的目录
      var widgetPath = path.resolve(__dirname, '../dist/pages/webIDE/' + url + '/widget.html');
      var cssPath = path.resolve(__dirname, '../dist/pages/webIDE/' + url + '/widget.css');
      var scriptPath = path.resolve(__dirname, '../dist/pages/webIDE/' + url + '/widget.js');

      if (fs.existsSync( widgetPath ))
        _html = fs.readFileSync( widgetPath );
      if (fs.existsSync( cssPath ))
        _css = fs.readFileSync( cssPath );
      if (fs.existsSync( scriptPath ))
        _script = fs.readFileSync( scriptPath );

      datas.html = _html.toString();
      datas.css = _css.toString();
      datas.script = _script.toString();
      this.body = datas;
    });

    router.post('/runDemo', function *(next) {
        // this.request.body;
        // console.log(this.request.body.html_code);
        var styles = this.request.body.css_code;
        var htmls = this.request.body.html_code;
        var scripts = this.request.body.script_code;
        var ctxPath='http://design.yyuap.com/static/uui-original/1.0.1';
        var tpl = [
          '<!DOCTYPE html>',
          '',
          '',
          '<meta charset="UTF-8">',
          '<meta name="viewport" content="width=device-width, initial-scale=1">',
          '<title>Title</title>',
		  '<link rel="stylesheet" href="'+ ctxPath +'/fonts/font-awesome/css/font-awesome.css">',
          '<link rel="stylesheet" type="text/css" href="'+ ctxPath +'/css/u.css">',
          '<link rel="stylesheet" type="text/css" href="'+ ctxPath +'/css/u-extend.css">',
		      '<link rel="stylesheet" type="text/css" href="'+ ctxPath +'/css/tree.css">',
          '<link rel="stylesheet" type="text/css" href="'+ ctxPath +'/css/grid.css">',
          '',
          '',
          '',
          htmls,
          '',
    	    '',
          '',
          '',
          '',
          '',
			    '',
          '',
          '',
          ''
        ]
        this.body = tpl.join(""); ;//JSON.stringify('test');
    });

    //uui定制相关
    router.post('/customized', function *(next) {
      var self = this;
      yield function(cb){
          customized.run(self,cb);
      }

    });

    router.get('/down', function *(next) {
      var self = this;
      yield function(cb){
          down.run(self,cb);
      }
    });

  }

}
<|endoftext|>


<commit_before>var path = require('path');
var zip = require("node-native-zip");

var gulp = require('gulp');
var zip = require('gulp-zip');
//uui定制
var customized = require("./customized");
var down = require("./down");

// 新定制
var concat = require('gulp-concat');
var fs = require('fs');

module.exports = {

  setRouters: function(router ,ctx){
    router.get('/loadMenu', function *(next) {
        var demos = require('../conf/snippets.conf.json');
        this.body = demos;//JSON.stringify('test');
    });

    var getTpl = function(styles,htmls,scripts){

      //var ctxPath='http://design.yyuap.com/static/uui-original/stable';
       var ctxPath='/dist/vendor/uui';
      var tpl = [
        '<!DOCTYPE html>',
        '',
        '',
        '<meta charset="UTF-8">',
        '<meta name="viewport" content="width=device-width, initial-scale=1">',
        '<title>Title</title>',
        '<link rel="stylesheet" href="http://design.yyuap.com/static/uploader/css/webuploader.css">',
        '<link rel="stylesheet" href="'+ ctxPath +'/css/font-awesome.css">',
        '<link rel="stylesheet" type="text/css" href="'+ ctxPath +'/css/u.css">',
        '<link rel="stylesheet" type="text/css" href="'+ ctxPath +'/css/tree.css">',
        '<link rel="stylesheet" type="text/css" href="'+ ctxPath +'/css/grid.css">',
        '',
        '',
        '',
        htmls,
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        ''
      ]
      return tpl;

    };
    router.post('/getWidgets', function *(next) {
      var fs = require("fs");
      var url = this.request.body.wUrl;
      var datas = {}
      var _html  = _css = _script = '';

      // 相对于当前执行文件的目录
      var widgetPath = path.resolve(__dirname, '../dist/pages/webIDE/' + url + '/widget.html');
      var cssPath = path.resolve(__dirname, '../dist/pages/webIDE/' + url + '/widget.css');
      var scriptPath = path.resolve(__dirname, '../dist/pages/webIDE/' + url + '/widget.js');

      if (fs.existsSync( widgetPath ))
        _html = fs.readFileSync( widgetPath );
      if (fs.existsSync( cssPath ))
        _css = fs.readFileSync( cssPath );
      if (fs.existsSync( scriptPath ))
        _script = fs.readFileSync( scriptPath );

      datas.html = _html.toString();
      datas.css = _css.toString();
      datas.script = _script.toString();
      this.body = datas;
    });

    router.post('/runDemo', function *(next) {
        // this.request.body;
        // console.log(this.request.body.html_code);
        var styles = this.request.body.css_code;
        var htmls = this.request.body.html_code;
        var scripts = this.request.body.script_code;

        var tpl = getTpl(styles,htmls,scripts);

        this.body = tpl.join("");//JSON.stringify('test');
    });

    //uui定制相关
    router.post('/customized', function *(next) {
      var self = this;
      yield function(cb){
          customized.run(self,cb);
      }

    });

    // 新定制
    router.post('/package', function *(next) {
      var self = this;
      console.log(this.request.body);

      var data = this.request.body;
      var pack = require('./pack.js');
      yield function(cb) {
        pack(data,self,cb);
      };
      // this.body = pack(data);
    });

    router.post('/downloadDemo',function *(next) {
        var viewCode = "",zipName='';
        var styles = this.request.body.cssCode;
        var htmls = this.request.body.htmlCode;
        var scripts = this.request.body.jsCode;

         var tpl = getTpl(styles,htmls,scripts);
        viewCode = tpl.join('\r\n');
        var fs = require("fs");
        var downPath = '../dist/pages/webIDE/temp';
        var tempDir = path.resolve(__dirname, downPath);
        fs.exists( tempDir, function(exist) {
          if(!exist){
            fs.mkdirSync(tempDir);
          }
        });

        fs.writeFile(downPath+'/download.html', viewCode ,  function(err) {
           if (err) {
               return console.error(err);
           }
        });

        // zipName = 'download'+new Date().getTime()+'.zip';
        zipName = 'download.zip';
        // 生成zip
        gulp.task('downzip',function(){
          return  gulp.src(downPath+'/download.html')
                .pipe(zip(zipName))
                .pipe(gulp.dest(downPath))
        });

        gulp.run('downzip');

        this.body = downPath+"/"+zipName;

    });

    router.get('/down', function *(next) {
      var self = this;
      yield function(cb){
          down.run(self,cb);
      }
    });

  }

}
<commit_msg>更改路由js路径<commit_after>var path = require('path');
var zip = require("node-native-zip");

var gulp = require('gulp');
var zip = require('gulp-zip');
//uui定制
var customized = require("./customized");
var down = require("./down");

// 新定制
var concat = require('gulp-concat');
var fs = require('fs');

module.exports = {

  setRouters: function(router ,ctx){
    router.get('/loadMenu', function *(next) {
        var demos = require('../conf/snippets.conf.json');
        this.body = demos;//JSON.stringify('test');
    });

    var getTpl = function(styles,htmls,scripts){

      var ctxPath='http://design.yyuap.com/static/uui-original/stable';
    //    var ctxPath='/dist/vendor/uui';
      var tpl = [
        '<!DOCTYPE html>',
        '',
        '',
        '<meta charset="UTF-8">',
        '<meta name="viewport" content="width=device-width, initial-scale=1">',
        '<title>Title</title>',
        '<link rel="stylesheet" href="http://design.yyuap.com/static/uploader/css/webuploader.css">',
        '<link rel="stylesheet" href="'+ ctxPath +'/css/font-awesome.css">',
        '<link rel="stylesheet" type="text/css" href="'+ ctxPath +'/css/u.css">',
        '<link rel="stylesheet" type="text/css" href="'+ ctxPath +'/css/tree.css">',
        '<link rel="stylesheet" type="text/css" href="'+ ctxPath +'/css/grid.css">',
        '',
        '',
        '',
        htmls,
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        ''
      ]
      return tpl;

    };
    router.post('/getWidgets', function *(next) {
      var fs = require("fs");
      var url = this.request.body.wUrl;
      var datas = {}
      var _html  = _css = _script = '';

      // 相对于当前执行文件的目录
      var widgetPath = path.resolve(__dirname, '../dist/pages/webIDE/' + url + '/widget.html');
      var cssPath = path.resolve(__dirname, '../dist/pages/webIDE/' + url + '/widget.css');
      var scriptPath = path.resolve(__dirname, '../dist/pages/webIDE/' + url + '/widget.js');

      if (fs.existsSync( widgetPath ))
        _html = fs.readFileSync( widgetPath );
      if (fs.existsSync( cssPath ))
        _css = fs.readFileSync( cssPath );
      if (fs.existsSync( scriptPath ))
        _script = fs.readFileSync( scriptPath );

      datas.html = _html.toString();
      datas.css = _css.toString();
      datas.script = _script.toString();
      this.body = datas;
    });

    router.post('/runDemo', function *(next) {
        // this.request.body;
        // console.log(this.request.body.html_code);
        var styles = this.request.body.css_code;
        var htmls = this.request.body.html_code;
        var scripts = this.request.body.script_code;

        var tpl = getTpl(styles,htmls,scripts);

        this.body = tpl.join("");//JSON.stringify('test');
    });

    //uui定制相关
    router.post('/customized', function *(next) {
      var self = this;
      yield function(cb){
          customized.run(self,cb);
      }

    });

    // 新定制
    router.post('/package', function *(next) {
      var self = this;
      console.log(this.request.body);

      var data = this.request.body;
      var pack = require('./pack.js');
      yield function(cb) {
        pack(data,self,cb);
      };
      // this.body = pack(data);
    });

    router.post('/downloadDemo',function *(next) {
        var viewCode = "",zipName='';
        var styles = this.request.body.cssCode;
        var htmls = this.request.body.htmlCode;
        var scripts = this.request.body.jsCode;

         var tpl = getTpl(styles,htmls,scripts);
        viewCode = tpl.join('\r\n');
        var fs = require("fs");
        var downPath = '../dist/pages/webIDE/temp';
        var tempDir = path.resolve(__dirname, downPath);
        fs.exists( tempDir, function(exist) {
          if(!exist){
            fs.mkdirSync(tempDir);
          }
        });

        fs.writeFile(downPath+'/download.html', viewCode ,  function(err) {
           if (err) {
               return console.error(err);
           }
        });

        // zipName = 'download'+new Date().getTime()+'.zip';
        zipName = 'download.zip';
        // 生成zip
        gulp.task('downzip',function(){
          return  gulp.src(downPath+'/download.html')
                .pipe(zip(zipName))
                .pipe(gulp.dest(downPath))
        });

        gulp.run('downzip');

        this.body = downPath+"/"+zipName;

    });

    router.get('/down', function *(next) {
      var self = this;
      yield function(cb){
          down.run(self,cb);
      }
    });

  }

}
<|endoftext|>