<commit_before>var _ = require('lodash'),
    connection = require('./connection'),
    collection = require('./collection'),
    helper = require('./helper');

var model = {

    connection: connection,

    set: function (key, val) {

        var self = this,
            attr,
            attrs;

        if (key === null
            || key === undefined)
        {
            return self;
        }

        if (_.isObject(key))
        {
            attrs = key;
        }
        else
        {
            (attrs = {})[key] = val;
        }

        for (attr in attrs)
        {
            if (!attr)
            {
                continue;
            }

            self.attributes[attr] = !_.isUndefined(attrs[attr])
                ? attrs[attr]
                : self.schema.get(attr).getDefaultValue();
        }

        return self;
    },

    get: function (attr) {
        return this.attributes[attr]
    },

    getHash: function () {

        var self = this;

        return _.map(self.schema.hashKeyAttributes, function(attr){
            return self.get(attr);
        });
    },

    getRange: function () {

        var self = this;

        return _.map(self.schema.rangeKeyAttributes, function(attr){
            return self.get(attr);
        });
    },

    toJSON: function () {

        var self = this,
            schema = self.schema,
            json = {},
            attrs = _.clone(self.attributes);

        _.forEach(attrs, function(val, attr){
            var transformed = schema.get(attr).toJSON(val);
            if (transformed) json[attr] = transformed;
        });

        return json;
    },

    serialize: function () {

        var self = this,
            schema = self.schema,
            dynamoAttrs = {},
            attrs = _.clone(self.attributes);

        if (schema.hashKeyAttributes.length > 1)
        {
            _.forEach(schema.hashKeyAttributes, function(key){
                delete attrs[key];
            });

            dynamoAttrs[schema.hashKey] = schema.serializeHashAttribute(self.getHash());
        }

        if (_.isArray(schema.rangeKeyAttributes)
            && schema.rangeKeyAttributes.length > 1)
        {
            _.forEach(schema.rangeKeyAttributes, function(key){
                delete attrs[key];
            });

            dynamoAttrs[schema.rangeKey] = schema.serializeRangeAttribute(self.getRange());
        }

        _.forEach(attrs, function(val, attr){

            var transformed = schema.get(attr).serializeObject(val);

            if (transformed)
            {
                dynamoAttrs[attr] = transformed;
            }

        });

        return dynamoAttrs;
    },

    save: function (callback) {

        if (!_.isFunction(callback))
        {
            callback = function () {};
        }

        var self = this;

        self.connection.client.putItem({
            TableName: self.schema.table,
            Item: self.serialize(),
            ReturnConsumedCapacity: 'TOTAL'
        }, function(err, data){
            var consumedCapacity = null;

            if (err) return callback(err);
            if (data.ConsumedCapacity && data.ConsumedCapacity.CapacityUnits) {
                consumedCapacity = data.ConsumedCapacity.CapacityUnits;
            }
            return callback.call(self, err, consumedCapacity);
        });

    },

    destroy: function (callback) {

        if (!_.isFunction(callback))
        {
            callback = function () {};
        }

        var self = this,
            schema = self.schema,
            match = {};

        try
        {
            match[schema.hashKey] = self.getHash().join(schema.keyDelimiter);

            if (schema.hasRangeAttributes())
            {
                match[schema.rangeKey] = self.getRange()[0];
            }
        }
        catch (err)
        {

            return callback(err);
        }

        self.Model.destroy(match, callback);
    }

};

var Model = {

    connection: connection,

    create: function (attributes) {

        attributes = attributes || {};

        var self = this,
            instanceOwnProperties = {
                schema: self.schema,
                connection: self.connection,
                attributes: {},
                Model: this
            },
            reserved = ['options', 'schema', 'connection', 'client', 'attributes', 'Model'];

        _.forEach(self.options, function(val, key){
            if (reserved.indexOf(key) >= 0) return;
            instanceOwnProperties[key] = val;
        });

        _.forEach(self.schema.attributes, function(type, attr){
            attributes[attr] = attributes[attr];
        });

        return _.bindAll(Object.create(model, helper.ownProperties(instanceOwnProperties)).set(attributes));
    },

    findOne: function (attrs, callback) {

        if (!_.isFunction(callback))
        {
            callback = function () {};
        }

        if (_.isEmpty(attrs))
        {
            callback(new Error('You must specify match attributes'));
        }

        var self = this,
            schema = self.schema,
            params;

        if (!schema.hasRangeAttributes()
            && attrs[schema.hashKey])
        {
            params = {
                TableName: schema.table,
                ReturnConsumedCapacity: 'TOTAL',
                ConsistentRead: true,
                Key: {}
            };
            params.Key[schema.hashKey] = schema.serializeHashAttribute(schema.getHashFromMatch(attrs));
            return self.connection.client.getItem(params, function(err, data){
                var consumedCapacity = null;

                if (err) return callback(err);
                if (!data.Item) return callback(new Error('Item does not exist'));
                if (data.ConsumedCapacity && data.ConsumedCapacity.CapacityUnits) {
                    consumedCapacity = data.ConsumedCapacity.CapacityUnits;
                }
                callback(null, self.parse(data.Item), consumedCapacity);
            });
        }

        self.find({ match: attrs }, function(err, collection, units){
            if (err) return callback(err);
            if (collection.models.length < 1) return callback(new Error('Item does not exist'));
            if (collection.models.length > 1) return callback(new Error('You must specify range or secondary attributes'));
            callback(null, collection.models[0], units);
        });
    },

    find: function (options, callback) {

        if (!_.isFunction(callback))
        {
            callback = function () {};
        }

        var self = this,
            schema = self.schema,
            query;

        try
        {
            query = schema.generateQueryParams(options.match);

            if (_.isString(options.sortBy))
            {
                if (schema.secondaryKeyAttributes.indexOf(options.sortBy) < 0)
                {
                    throw new Error('You can only sort by Secondary attributes');
                }

                query.IndexName = schema.table + '.' + options.sortBy;
            }

            if (_.isNumber(options.take))
            {
                query.Limit = options.take;
            }

            if (_.isNumber(options.skip)
                && query.Limit)
            {
                query.Limit += options.skip;
            }
        }
        catch (err)
        {
            return callback(err);
        }

        self.connection.client.query(query, function(err, data){
            var consumedCapacity = null;

            if (err) return callback(err);
            try
            {
                data.Items = _.isNumber(options.skip) ?  data.Items.slice(options.skip) : data.Items;
            }
            catch (err)
            {
                return callback(err);
            }
            if (data.ConsumedCapacity && data.ConsumedCapacity.CapacityUnits) {
                consumedCapacity = data.ConsumedCapacity.CapacityUnits;
            }
            callback(null, collection(_.map(data.Items, self.parse, self)), consumedCapacity);
        });

    },

    destroy: function (attrs, callback) {

        if (!_.isFunction(callback))
        {
            callback = function () {};
        }

        var self = this,
            schema = self.schema,
            params = {
                TableName: schema.table,
                ReturnConsumedCapacity: 'TOTAL',
                Key: {}
            };

        try
        {
            params.Key[schema.hashKey] = schema.serializeHashAttribute(schema.getHashFromMatch(attrs));
        }
        catch (err)
        {
            return callback(err);
        }

        if (!schema.hasRangeAttributes())
        {
            return self.connection.client.deleteItem(params, function(err, data){
                var consumedCapacity = null;

                if (err) return callback(err);
                if (data.ConsumedCapacity && data.ConsumedCapacity.CapacityUnits) {
                    consumedCapacity = data.ConsumedCapacity.CapacityUnits;
                }
                callback(err, consumedCapacity);
            });
        }

        if (schema.isValidRangeMatch(attrs))
        {
            params.Key[schema.rangeKey] = schema.serializeRangeAttribute(schema.getRangeFromMatch(attrs));

            return self.connection.client.deleteItem(params, function(err, data){
                var consumedCapacity = null;

                if (err) return callback(err);
                if (data.ConsumedCapacity && data.ConsumedCapacity.CapacityUnits) {
                    consumedCapacity = data.ConsumedCapacity.CapacityUnits;
                }
                callback(err, consumedCapacity);
            });
        }

        if (schema.isValidSecondaryMatch(attrs))
        {
            return self.findOne(attrs, function(e1, m, u1){
                if (e1) return callback(e1);
                m.destroy(function(e2, u2){
                    if (e2) return callback(e2);
                    callback(null, (u1 + u2));
                });
            });
        }

        return callback(new Error('You must specify range or secondary attribute(s)'));
    },

    parse: function (item_0) {

        var self = this,
            attrs = self.schema.getSerializedAttributes(),
            item = {};

        _.forEach(attrs, function(type, attr){

            var a = item_0[attr];

            if (!a)
            {
                return;
            }

            if (attr === self.schema.hashKey)
            {
                _.assign(item, self.schema.deserializeHashAttribute(a));

                return;
            }

            if (attr === self.schema.rangeKey)
            {
                _.assign(item, self.schema.deserializeRangeAttribute(a));

                return;
            }

            item[attr] = type.deserializeObject(a);
        });

        return self.create(item);
    }

};

module.exports = exports = function (options) {

    options = options || {};

    var ownProperties = {
        options: options,
        schema: options.schema
    };

    if (options.client)
    {
        ownProperties.connection = { client: options.client };
    }

    return _.bindAll(Object.create(Model, helper.ownProperties(ownProperties)));
};
<commit_msg>check if the attribute which should be serialized is a function, then don't try to serialize it<commit_after>var _ = require('lodash'),
    connection = require('./connection'),
    collection = require('./collection'),
    helper = require('./helper');

var model = {

    connection: connection,

    set: function (key, val) {

        var self = this,
            attr,
            attrs;

        if (key === null
            || key === undefined)
        {
            return self;
        }

        if (_.isObject(key))
        {
            attrs = key;
        }
        else
        {
            (attrs = {})[key] = val;
        }

        for (attr in attrs)
        {
            if (!attr)
            {
                continue;
            }

            self.attributes[attr] = !_.isUndefined(attrs[attr])
                ? attrs[attr]
                : self.schema.get(attr).getDefaultValue();
        }

        return self;
    },

    get: function (attr) {
        return this.attributes[attr]
    },

    getHash: function () {

        var self = this;

        return _.map(self.schema.hashKeyAttributes, function(attr){
            return self.get(attr);
        });
    },

    getRange: function () {

        var self = this;

        return _.map(self.schema.rangeKeyAttributes, function(attr){
            return self.get(attr);
        });
    },

    toJSON: function () {

        var self = this,
            schema = self.schema,
            json = {},
            attrs = _.clone(self.attributes);

        _.forEach(attrs, function(val, attr){

            // check if the attributes value is a function, if yes don't try to serialize it
            if(_.isFunction(val)){
                return;
            }

            var transformed = schema.get(attr).toJSON(val);
            if (transformed) json[attr] = transformed;
        });

        return json;
    },

    serialize: function () {

        var self = this,
            schema = self.schema,
            dynamoAttrs = {},
            attrs = _.clone(self.attributes);

        if (schema.hashKeyAttributes.length > 1)
        {
            _.forEach(schema.hashKeyAttributes, function(key){
                delete attrs[key];
            });

            dynamoAttrs[schema.hashKey] = schema.serializeHashAttribute(self.getHash());
        }

        if (_.isArray(schema.rangeKeyAttributes)
            && schema.rangeKeyAttributes.length > 1)
        {
            _.forEach(schema.rangeKeyAttributes, function(key){
                delete attrs[key];
            });

            dynamoAttrs[schema.rangeKey] = schema.serializeRangeAttribute(self.getRange());
        }

        _.forEach(attrs, function(val, attr){

            // check if the attributes value is a function, if yes don't try to serialize it
            if(_.isFunction(val)){
                return;
            }

            var transformed = schema.get(attr).serializeObject(val);

            if (transformed)
            {
                dynamoAttrs[attr] = transformed;
            }

        });

        return dynamoAttrs;
    },

    save: function (callback) {

        if (!_.isFunction(callback))
        {
            callback = function () {};
        }

        var self = this;

        self.connection.client.putItem({
            TableName: self.schema.table,
            Item: self.serialize(),
            ReturnConsumedCapacity: 'TOTAL'
        }, function(err, data){
            var consumedCapacity = null;

            if (err) return callback(err);
            if (data.ConsumedCapacity && data.ConsumedCapacity.CapacityUnits) {
                consumedCapacity = data.ConsumedCapacity.CapacityUnits;
            }
            return callback.call(self, err, consumedCapacity);
        });

    },

    destroy: function (callback) {

        if (!_.isFunction(callback))
        {
            callback = function () {};
        }

        var self = this,
            schema = self.schema,
            match = {};

        try
        {
            match[schema.hashKey] = self.getHash().join(schema.keyDelimiter);

            if (schema.hasRangeAttributes())
            {
                match[schema.rangeKey] = self.getRange()[0];
            }
        }
        catch (err)
        {

            return callback(err);
        }

        self.Model.destroy(match, callback);
    }

};

var Model = {

    connection: connection,

    create: function (attributes) {

        attributes = attributes || {};

        var self = this,
            instanceOwnProperties = {
                schema: self.schema,
                connection: self.connection,
                attributes: {},
                Model: this
            },
            reserved = ['options', 'schema', 'connection', 'client', 'attributes', 'Model'];

        _.forEach(self.options, function(val, key){
            if (reserved.indexOf(key) >= 0) return;
            instanceOwnProperties[key] = val;
        });

        _.forEach(self.schema.attributes, function(type, attr){
            attributes[attr] = attributes[attr];
        });

        return _.bindAll(Object.create(model, helper.ownProperties(instanceOwnProperties)).set(attributes));
    },

    findOne: function (attrs, callback) {

        if (!_.isFunction(callback))
        {
            callback = function () {};
        }

        if (_.isEmpty(attrs))
        {
            callback(new Error('You must specify match attributes'));
        }

        var self = this,
            schema = self.schema,
            params;

        if (!schema.hasRangeAttributes()
            && attrs[schema.hashKey])
        {
            params = {
                TableName: schema.table,
                ReturnConsumedCapacity: 'TOTAL',
                ConsistentRead: true,
                Key: {}
            };
            params.Key[schema.hashKey] = schema.serializeHashAttribute(schema.getHashFromMatch(attrs));
            return self.connection.client.getItem(params, function(err, data){
                var consumedCapacity = null;

                if (err) return callback(err);
                if (!data.Item) return callback(new Error('Item does not exist'));
                if (data.ConsumedCapacity && data.ConsumedCapacity.CapacityUnits) {
                    consumedCapacity = data.ConsumedCapacity.CapacityUnits;
                }
                callback(null, self.parse(data.Item), consumedCapacity);
            });
        }

        self.find({ match: attrs }, function(err, collection, units){
            if (err) return callback(err);
            if (collection.models.length < 1) return callback(new Error('Item does not exist'));
            if (collection.models.length > 1) return callback(new Error('You must specify range or secondary attributes'));
            callback(null, collection.models[0], units);
        });
    },

    find: function (options, callback) {

        if (!_.isFunction(callback))
        {
            callback = function () {};
        }

        var self = this,
            schema = self.schema,
            query;

        try
        {
            query = schema.generateQueryParams(options.match);

            if (_.isString(options.sortBy))
            {
                if (schema.secondaryKeyAttributes.indexOf(options.sortBy) < 0)
                {
                    throw new Error('You can only sort by Secondary attributes');
                }

                query.IndexName = schema.table + '.' + options.sortBy;
            }

            if (_.isNumber(options.take))
            {
                query.Limit = options.take;
            }

            if (_.isNumber(options.skip)
                && query.Limit)
            {
                query.Limit += options.skip;
            }
        }
        catch (err)
        {
            return callback(err);
        }

        self.connection.client.query(query, function(err, data){
            var consumedCapacity = null;

            if (err) return callback(err);
            try
            {
                data.Items = _.isNumber(options.skip) ?  data.Items.slice(options.skip) : data.Items;
            }
            catch (err)
            {
                return callback(err);
            }
            if (data.ConsumedCapacity && data.ConsumedCapacity.CapacityUnits) {
                consumedCapacity = data.ConsumedCapacity.CapacityUnits;
            }
            callback(null, collection(_.map(data.Items, self.parse, self)), consumedCapacity);
        });

    },

    destroy: function (attrs, callback) {

        if (!_.isFunction(callback))
        {
            callback = function () {};
        }

        var self = this,
            schema = self.schema,
            params = {
                TableName: schema.table,
                ReturnConsumedCapacity: 'TOTAL',
                Key: {}
            };

        try
        {
            params.Key[schema.hashKey] = schema.serializeHashAttribute(schema.getHashFromMatch(attrs));
        }
        catch (err)
        {
            return callback(err);
        }

        if (!schema.hasRangeAttributes())
        {
            return self.connection.client.deleteItem(params, function(err, data){
                var consumedCapacity = null;

                if (err) return callback(err);
                if (data.ConsumedCapacity && data.ConsumedCapacity.CapacityUnits) {
                    consumedCapacity = data.ConsumedCapacity.CapacityUnits;
                }
                callback(err, consumedCapacity);
            });
        }

        if (schema.isValidRangeMatch(attrs))
        {
            params.Key[schema.rangeKey] = schema.serializeRangeAttribute(schema.getRangeFromMatch(attrs));

            return self.connection.client.deleteItem(params, function(err, data){
                var consumedCapacity = null;

                if (err) return callback(err);
                if (data.ConsumedCapacity && data.ConsumedCapacity.CapacityUnits) {
                    consumedCapacity = data.ConsumedCapacity.CapacityUnits;
                }
                callback(err, consumedCapacity);
            });
        }

        if (schema.isValidSecondaryMatch(attrs))
        {
            return self.findOne(attrs, function(e1, m, u1){
                if (e1) return callback(e1);
                m.destroy(function(e2, u2){
                    if (e2) return callback(e2);
                    callback(null, (u1 + u2));
                });
            });
        }

        return callback(new Error('You must specify range or secondary attribute(s)'));
    },

    parse: function (item_0) {

        var self = this,
            attrs = self.schema.getSerializedAttributes(),
            item = {};

        _.forEach(attrs, function(type, attr){

            var a = item_0[attr];

            if (!a)
            {
                return;
            }

            if (attr === self.schema.hashKey)
            {
                _.assign(item, self.schema.deserializeHashAttribute(a));

                return;
            }

            if (attr === self.schema.rangeKey)
            {
                _.assign(item, self.schema.deserializeRangeAttribute(a));

                return;
            }

            item[attr] = type.deserializeObject(a);
        });

        return self.create(item);
    }

};

module.exports = exports = function (options) {

    options = options || {};

    var ownProperties = {
        options: options,
        schema: options.schema
    };

    if (options.client)
    {
        ownProperties.connection = { client: options.client };
    }

    return _.bindAll(Object.create(Model, helper.ownProperties(ownProperties)));
};
<|endoftext|>


<commit_before>'use strict';

// Include gulp
var gulp = require('gulp');
var pkg  = require('./package.json');
var beep = require('beepbeep');
var onError = function () { beep(); };

// Include Our Plugins
var jshint     = require('gulp-jshint');
var nodeunit   = require('gulp-nodeunit');
var livereload = require('gulp-livereload');
var plumber    = require('gulp-plumber');
var shell      = require('gulp-shell');
var sass       = require('gulp-sass');
var rename     = require("gulp-rename");
var uglify     = require('gulp-uglify');
var postcss    = require('gulp-postcss');
var autoprefixer = require('autoprefixer');

// Lint Task
gulp.task('jshint', function() {
  return gulp.src([
      '*.js',
      pkg.directories.src+'/**/*.js',
      pkg.directories.test+'/**/*.js'
    ])
    .pipe(plumber({errorHandler: onError}))
    .pipe(jshint())
    .pipe(jshint.reporter('default'))
    .pipe(jshint.reporter('fail'))
  ;
});

// Node Unit
gulp.task('nodeunit', function() {
  return gulp.src(pkg.directories.test + '/**/*.js')
    .pipe(plumber({errorHandler: onError}))
    .pipe(nodeunit({
      reporter: 'junit',
      reporterOptions: {
        output: 'test'
      }
    }))
  ;
});

// Lint Task
gulp.task('build-js', function() {
  return gulp.src([
      pkg.directories.theme + '/**/js-src/*.js'
    ])
    .pipe(plumber({errorHandler: onError}))
    .pipe(jshint({ // see https://github.com/jshint/jshint/blob/master/examples/.jshintrc
       browser: true,
       jquery: true,
       strict: true,
       curly: true,
       undef:true
    }))
    .pipe(jshint.reporter('default'))
    .pipe(jshint.reporter('fail'))
    .pipe(uglify({output: {
      max_line_len: 9000
    }}))
    .pipe(rename(function(path){
      path.dirname = path.dirname.replace(/js\-src/, 'js');
      return path;
    }))
    .pipe(gulp.dest(pkg.directories.theme))
  ;
});

// Sass
gulp.task('build-sass', function() {
  return gulp.src(pkg.directories.theme + '/**/*.scss')
    .pipe(plumber({errorHandler: onError}))
    .pipe(sass({outputStyle: 'compact'}).on('error', sass.logError))
    .pipe(postcss([
      autoprefixer({
        browsers: ['last 3 versions', '> 2%', 'ie 8', 'ie 9']
      })
    ]))
    .pipe(rename(function(path){
      path.dirname = path.dirname.replace(/sass/, 'css');
      return path;
    }))
    .pipe(gulp.dest(pkg.directories.theme))
  ;
});

// Watch Files For Changes
gulp.task('watch', function() {
  livereload.listen();
  gulp.watch(['gulpfile.js','package.json'], process.exit);
  gulp.watch(['*.js',pkg.directories.src+'/**/*.js',pkg.directories.test+'/**/*.js'], ['default']);
  gulp.watch([pkg.directories.data+'/**/*'], ['generate']);
  gulp.watch(pkg.directories.theme + '/**/*.js', ['build-js']);
  gulp.watch(pkg.directories.theme + '/**/*.scss', ['build-sass']);
});

// Default Task
gulp.task('default',     ['jshint','nodeunit']);
gulp.task('test',        ['jshint','nodeunit']);
gulp.task('generate',    shell.task(['npm run generate']));
<commit_msg>Taking care of lesser browsers<commit_after>'use strict';

// Include gulp
var gulp = require('gulp');
var pkg  = require('./package.json');
var beep = require('beepbeep');
var onError = function () { beep(); };

// Include Our Plugins
var jshint     = require('gulp-jshint');
var nodeunit   = require('gulp-nodeunit');
var livereload = require('gulp-livereload');
var plumber    = require('gulp-plumber');
var shell      = require('gulp-shell');
var sass       = require('gulp-sass');
var rename     = require("gulp-rename");
var uglify     = require('gulp-uglify');
var postcss    = require('gulp-postcss');
var autoprefixer = require('autoprefixer');

// Lint Task
gulp.task('jshint', function() {
  return gulp.src([
      '*.js',
      pkg.directories.src+'/**/*.js',
      pkg.directories.test+'/**/*.js'
    ])
    .pipe(plumber({errorHandler: onError}))
    .pipe(jshint())
    .pipe(jshint.reporter('default'))
    .pipe(jshint.reporter('fail'))
  ;
});

// Node Unit
gulp.task('nodeunit', function() {
  return gulp.src(pkg.directories.test + '/**/*.js')
    .pipe(plumber({errorHandler: onError}))
    .pipe(nodeunit({
      reporter: 'junit',
      reporterOptions: {
        output: 'test'
      }
    }))
  ;
});

// Lint Task
gulp.task('build-js', function() {
  return gulp.src([
      pkg.directories.theme + '/**/js-src/*.js'
    ])
    .pipe(plumber({errorHandler: onError}))
    .pipe(jshint({ // see https://github.com/jshint/jshint/blob/master/examples/.jshintrc
       browser: true,
       jquery: true,
       strict: true,
       curly: true,
       undef:true
    }))
    .pipe(jshint.reporter('default'))
    .pipe(jshint.reporter('fail'))
    .pipe(uglify({output: {
      max_line_len: 9000
    }}))
    .pipe(rename(function(path){
      path.dirname = path.dirname.replace(/js\-src/, 'js');
      return path;
    }))
    .pipe(gulp.dest(pkg.directories.theme))
  ;
});

// Sass
gulp.task('build-sass', function() {
  return gulp.src(pkg.directories.theme + '/**/*.scss')
    .pipe(plumber({errorHandler: onError}))
    .pipe(sass({outputStyle: 'compact'}).on('error', sass.logError))
    .pipe(postcss([
      autoprefixer({
        browsers: ['last 3 versions', '> 0.5%', 'ie 8', 'ie 9']
      })
    ]))
    .pipe(rename(function(path){
      path.dirname = path.dirname.replace(/sass/, 'css');
      return path;
    }))
    .pipe(gulp.dest(pkg.directories.theme))
  ;
});

// Watch Files For Changes
gulp.task('watch', function() {
  livereload.listen();
  gulp.watch(['gulpfile.js','package.json'], process.exit);
  gulp.watch(['*.js',pkg.directories.src+'/**/*.js',pkg.directories.test+'/**/*.js'], ['default']);
  gulp.watch([pkg.directories.data+'/**/*'], ['generate']);
  gulp.watch(pkg.directories.theme + '/**/*.js', ['build-js']);
  gulp.watch(pkg.directories.theme + '/**/*.scss', ['build-sass']);
});

// Default Task
gulp.task('default',     ['jshint','nodeunit']);
gulp.task('test',        ['jshint','nodeunit']);
gulp.task('generate',    shell.task(['npm run generate']));
<|endoftext|>


<commit_before>(function() {
    var app = angular.module('config-odin',[]);
    app.run(run);
    function run($rootScope, $location, $cookieStore, $http) {
        $rootScope.$on('$routeChangeSuccess', function (e, current, pre) {
            $rootScope.actualUrl=current.$$route.originalPath;
        	$rootScope.url='http://104.208.247.131/api';
        });
    }
})();
<commit_msg>chaning the url of config.js<commit_after>(function() {
    var app = angular.module('config-odin',[]);
    app.run(run);
    function run($rootScope, $location, $cookieStore, $http) {
        $rootScope.$on('$routeChangeSuccess', function (e, current, pre) {
            $rootScope.actualUrl=current.$$route.originalPath;
-        	$rootScope.url='http://137.135.84.77';
        });
    }
})();
<|endoftext|>


<commit_before>(function() {
  angular.module('ncsaas')
    .controller('CustomerServiceTabController', [
      '$stateParams',
      'baseServiceListController',
      'joinService',
      'servicesService',
      'usersService',
      'ncUtils',
      'ncUtilsFlash',
      'ENV',
      CustomerServiceTabController
    ]);

  function CustomerServiceTabController(
    $stateParams,
    baseServiceListController,
    joinService,
    servicesService,
    usersService,
    ncUtils,
    ncUtilsFlash,
    ENV) {
    var controllerScope = this;
    var Controller = baseServiceListController.extend({
      defaultErrorMessage: "Reason unknown, please contact support",

      init: function() {
        this.controllerScope = controllerScope;
        this.service = joinService;
        this.service.defaultFilter.customer = $stateParams.uuid;
        this.expandableOptions = [
          {
            isList: false,
            addItemBlock: false,
            viewType: 'service',
            title: 'Settings'
          }
        ];
        this.blockUIElement = 'tab-content';
        this._super();
        this.entityOptions.list[0].type = 'editable';
        this.entityOptions.entityData.expandable = true;
      },
      getClass: function(state) {
        return ENV.servicesStateColorClasses[state];
      },
      afterGetList: function() {
        this.expandSelectedItem();
      },
      expandSelectedItem: function() {
        var vm = this;
        var service_type = $stateParams.providerType;
        var uuid = $stateParams.providerUuid;

        if (service_type && uuid) {
          var item = vm.findItem(service_type, uuid);
          if (item) {
            // Move found element to the start of the list for user's convenience
            vm.list.splice(vm.list.indexOf(item), 1);
            vm.list.unshift(item);
            item.expandItemOpen = true;
          } else {
            this.service.$get(service_type, uuid).then(function(provider) {
              vm.list.unshift(provider);
              vm.showMore(provider);
              provider.expandItemOpen = true;
            });
          }
        }
      },
      findItem: function(service_type, uuid) {
        for (var i = 0; i < this.list.length; i++) {
          var item = this.list[i];
          if (item.uuid == uuid && item.service_type == service_type) {
            return item;
          }
        }
      }
    });
    controllerScope.__proto__ = new Controller();
  }
})();

(function() {

  angular.module('ncsaas')
    .controller('CustomerProjectTabController', [
      'BaseProjectListController', CustomerProjectTabController]);

  function CustomerProjectTabController(BaseProjectListController) {
    var controllerScope = this;
    var Controller = BaseProjectListController.extend({
      init: function() {
        this.controllerScope = controllerScope;
        this.blockUIElement = 'tab-content';
        this._super();
        this.entityOptions.entityData.title = '';
        this.entityOptions.entityData.checkQuotas = 'project';
      }
    });

    controllerScope.__proto__ = new Controller();
  }
})();

(function() {
  angular.module('ncsaas')
    .service('BaseCustomerResourcesTabController', [
      '$stateParams',
      'baseResourceListController',
      'ENTITYLISTFIELDTYPES',
      BaseCustomerResourcesTabController]);

  function BaseCustomerResourcesTabController(
    $stateParams,
    baseResourceListController,
    ENTITYLISTFIELDTYPES
  ) {

    var controllerClass = baseResourceListController.extend({
      init:function() {
        this._super();
        this.service.defaultFilter.customer = $stateParams.uuid;
        this.entityOptions.list.push({
          name: 'Project',
          propertyName: 'project_name',
          link: 'projects.details({uuid: entity.project_uuid})',
          type: ENTITYLISTFIELDTYPES.name
        });
      }
    });
    return controllerClass;
  }
})();

(function() {
  angular.module('ncsaas')
    .controller('CustomerResourcesTabController', [
      'BaseCustomerResourcesTabController', 'ENV',
      CustomerResourcesTabController
    ]);

  function CustomerResourcesTabController(BaseCustomerResourcesTabController, ENV) {
    var controllerScope = this;
    var ResourceController = BaseCustomerResourcesTabController.extend({
      init: function() {
        this.controllerScope = controllerScope;
        this.category = ENV.VirtualMachines;
        this._super();
        this.entityOptions.entityData.noMatchesText = 'No VMs found matching filter.';
        this.entityOptions.entityData.openMap = this.openMap.bind(this);
      }
    });
    controllerScope.__proto__ = new ResourceController();
  }
})();

(function() {

  angular.module('ncsaas')
    .controller('CustomerApplicationsTabController', [
      'BaseCustomerResourcesTabController', 'ENV',
      CustomerApplicationsTabController]);

  function CustomerApplicationsTabController(BaseCustomerResourcesTabController, ENV) {
    var controllerScope = this;
    var ResourceController = BaseCustomerResourcesTabController.extend({
      init:function() {
        this.controllerScope = controllerScope;
        this.category = ENV.Applications;
        this._super();

        this.entityOptions.entityData.noDataText = 'You have no applications yet';
        this.entityOptions.entityData.createLinkText = 'Create application';
        this.entityOptions.entityData.importLinkText = 'Import application';
        this.entityOptions.entityData.noMatchesText = 'No applications found matching filter.';
      }
    });
    controllerScope.__proto__ = new ResourceController();
  }
})();

(function() {
  angular.module('ncsaas')
    .controller('CustomerAlertsListController', [
      'BaseAlertsListController',
      'currentStateService',
      CustomerAlertsListController]);

  function CustomerAlertsListController(BaseAlertsListController, currentStateService) {
    var controllerScope = this;
    var controllerClass = BaseAlertsListController.extend({
      init: function() {
        this.controllerScope = controllerScope;
        this.blockUIElement = 'tab-content';
        this._super();
      },
      getList: function(filter) {
        var vm = this;
        var fn = this._super.bind(vm);
        filter = filter || {};
        return currentStateService.getCustomer().then(function(customer) {
          vm.service.defaultFilter.aggregate = 'customer';
          vm.service.defaultFilter.uuid = customer.uuid;
          vm.service.defaultFilter.opened = true;
          return fn(filter);
        })
      }
    });

    controllerScope.__proto__ = new controllerClass();
  }
})();

(function() {
  angular.module('ncsaas')
    .controller('CustomerEventTabController', [
      'baseEventListController',
      'currentStateService',
      CustomerEventTabController
    ]);

  function CustomerEventTabController(baseEventListController, currentStateService) {
    var controllerScope = this;
    var EventController = baseEventListController.extend({

      init: function() {
        this.controllerScope = controllerScope;
        this._super();
      },

      getList: function(filter) {
        var vm = this,
          fn = this._super.bind(vm);
        return currentStateService.getCustomer().then(function(customer) {
          vm.service.defaultFilter.scope = customer.url;
          return fn(filter);
        });
      }
    });

    controllerScope.__proto__ = new EventController();
  }

})();

(function() {
  angular.module('ncsaas')
      .controller('CustomerInvoicesTabController', [
        'baseControllerListClass',
        'invoicesService',
        'ENTITYLISTFIELDTYPES',
        CustomerInvoicesTabController
      ]);

  function CustomerInvoicesTabController(
    baseControllerListClass,
    invoicesService,
    ENTITYLISTFIELDTYPES) {
    var controllerScope = this;
    var InvoicesController = baseControllerListClass.extend({
      init: function() {
        this.service = invoicesService;
        this._super();

        this.entityOptions = {
          entityData: {
            noDataText: 'No invoices yet',
            hideActionButtons: true,
            hideTableHead: false,
            rowTemplateUrl: 'views/payment/invoice.html'
          },
          list: [
            {
              name: 'Invoice code',
              propertyName: 'uuid',
              type: ENTITYLISTFIELDTYPES.trimmed,
              limit: 6
            },
            {
              name: 'Amount',
              propertyName: 'total_amount',
              type: ENTITYLISTFIELDTYPES.linkOrText,
            },
            {
              name: 'Start date',
              propertyName: 'start_date',
              type: ENTITYLISTFIELDTYPES.dateShort,
            },
            {
              name: 'End date',
              propertyName: 'end_date',
              type: ENTITYLISTFIELDTYPES.dateShort,
            },
            {
              name: '',
              propertyName: 'pdf',
              iconClass: 'fa-file-pdf-o',
              type: ENTITYLISTFIELDTYPES.staticIconLink,
              className: 'pdf-icon'
            }
          ]
        };
      },
      afterGetList: function() {}
    });

    controllerScope.__proto__ = new InvoicesController();
  }

})();
(function() {
  angular.module('ncsaas')
      .controller('CustomerDeleteTabController', [
        'baseControllerClass',
        'customersService',
        'currentStateService',
        '$state',
        CustomerDeleteTabController
      ]);

  function CustomerDeleteTabController(
      baseControllerClass,
      customersService,
      currentStateService,
      $state
  ) {
    var controllerScope = this;
    var DeleteController = baseControllerClass.extend({
      init: function() {
        this.controllerScope = controllerScope;
        this._super();
        var vm = this;
        currentStateService.getCustomer().then(function(customer) {
          vm.customer = customer;
        });
      },
      removeCustomer: function() {
        var confirmDelete = confirm('Confirm deletion?');
        if (confirmDelete) {
          this.customer.$delete().then(function(instance) {
            customersService.clearAllCacheForCurrentEndpoint();
            customersService.getPersonalOrFirstCustomer(instance.name).then(function(customer) {
              currentStateService.setCustomer(customer);
              $state.go('organizations.details', {uuid: customer.uuid, tab: 'eventlog'});
            });
          });
        }
      }
    });

    controllerScope.__proto__ = new DeleteController();
  }

})();
<commit_msg>Remove leftover<commit_after>(function() {
  angular.module('ncsaas')
    .controller('CustomerServiceTabController', [
      '$stateParams',
      'baseServiceListController',
      'joinService',
      'servicesService',
      'usersService',
      'ncUtils',
      'ncUtilsFlash',
      'ENV',
      CustomerServiceTabController
    ]);

  function CustomerServiceTabController(
    $stateParams,
    baseServiceListController,
    joinService,
    servicesService,
    usersService,
    ncUtils,
    ncUtilsFlash,
    ENV) {
    var controllerScope = this;
    var Controller = baseServiceListController.extend({
      defaultErrorMessage: "Reason unknown, please contact support",

      init: function() {
        this.controllerScope = controllerScope;
        this.service = joinService;
        this.service.defaultFilter.customer = $stateParams.uuid;
        this.expandableOptions = [
          {
            isList: false,
            addItemBlock: false,
            viewType: 'service',
            title: 'Settings'
          }
        ];
        this.blockUIElement = 'tab-content';
        this._super();
        this.entityOptions.list[0].type = 'editable';
        this.entityOptions.entityData.expandable = true;
      },
      getClass: function(state) {
        return ENV.servicesStateColorClasses[state];
      },
      afterGetList: function() {
        this.expandSelectedItem();
      },
      expandSelectedItem: function() {
        var vm = this;
        var service_type = $stateParams.providerType;
        var uuid = $stateParams.providerUuid;

        if (service_type && uuid) {
          var item = vm.findItem(service_type, uuid);
          if (item) {
            // Move found element to the start of the list for user's convenience
            vm.list.splice(vm.list.indexOf(item), 1);
            vm.list.unshift(item);
            item.expandItemOpen = true;
          } else {
            this.service.$get(service_type, uuid).then(function(provider) {
              vm.list.unshift(provider);
              provider.expandItemOpen = true;
            });
          }
        }
      },
      findItem: function(service_type, uuid) {
        for (var i = 0; i < this.list.length; i++) {
          var item = this.list[i];
          if (item.uuid == uuid && item.service_type == service_type) {
            return item;
          }
        }
      }
    });
    controllerScope.__proto__ = new Controller();
  }
})();

(function() {

  angular.module('ncsaas')
    .controller('CustomerProjectTabController', [
      'BaseProjectListController', CustomerProjectTabController]);

  function CustomerProjectTabController(BaseProjectListController) {
    var controllerScope = this;
    var Controller = BaseProjectListController.extend({
      init: function() {
        this.controllerScope = controllerScope;
        this.blockUIElement = 'tab-content';
        this._super();
        this.entityOptions.entityData.title = '';
        this.entityOptions.entityData.checkQuotas = 'project';
      }
    });

    controllerScope.__proto__ = new Controller();
  }
})();

(function() {
  angular.module('ncsaas')
    .service('BaseCustomerResourcesTabController', [
      '$stateParams',
      'baseResourceListController',
      'ENTITYLISTFIELDTYPES',
      BaseCustomerResourcesTabController]);

  function BaseCustomerResourcesTabController(
    $stateParams,
    baseResourceListController,
    ENTITYLISTFIELDTYPES
  ) {

    var controllerClass = baseResourceListController.extend({
      init:function() {
        this._super();
        this.service.defaultFilter.customer = $stateParams.uuid;
        this.entityOptions.list.push({
          name: 'Project',
          propertyName: 'project_name',
          link: 'projects.details({uuid: entity.project_uuid})',
          type: ENTITYLISTFIELDTYPES.name
        });
      }
    });
    return controllerClass;
  }
})();

(function() {
  angular.module('ncsaas')
    .controller('CustomerResourcesTabController', [
      'BaseCustomerResourcesTabController', 'ENV',
      CustomerResourcesTabController
    ]);

  function CustomerResourcesTabController(BaseCustomerResourcesTabController, ENV) {
    var controllerScope = this;
    var ResourceController = BaseCustomerResourcesTabController.extend({
      init: function() {
        this.controllerScope = controllerScope;
        this.category = ENV.VirtualMachines;
        this._super();
        this.entityOptions.entityData.noMatchesText = 'No VMs found matching filter.';
        this.entityOptions.entityData.openMap = this.openMap.bind(this);
      }
    });
    controllerScope.__proto__ = new ResourceController();
  }
})();

(function() {

  angular.module('ncsaas')
    .controller('CustomerApplicationsTabController', [
      'BaseCustomerResourcesTabController', 'ENV',
      CustomerApplicationsTabController]);

  function CustomerApplicationsTabController(BaseCustomerResourcesTabController, ENV) {
    var controllerScope = this;
    var ResourceController = BaseCustomerResourcesTabController.extend({
      init:function() {
        this.controllerScope = controllerScope;
        this.category = ENV.Applications;
        this._super();

        this.entityOptions.entityData.noDataText = 'You have no applications yet';
        this.entityOptions.entityData.createLinkText = 'Create application';
        this.entityOptions.entityData.importLinkText = 'Import application';
        this.entityOptions.entityData.noMatchesText = 'No applications found matching filter.';
      }
    });
    controllerScope.__proto__ = new ResourceController();
  }
})();

(function() {
  angular.module('ncsaas')
    .controller('CustomerAlertsListController', [
      'BaseAlertsListController',
      'currentStateService',
      CustomerAlertsListController]);

  function CustomerAlertsListController(BaseAlertsListController, currentStateService) {
    var controllerScope = this;
    var controllerClass = BaseAlertsListController.extend({
      init: function() {
        this.controllerScope = controllerScope;
        this.blockUIElement = 'tab-content';
        this._super();
      },
      getList: function(filter) {
        var vm = this;
        var fn = this._super.bind(vm);
        filter = filter || {};
        return currentStateService.getCustomer().then(function(customer) {
          vm.service.defaultFilter.aggregate = 'customer';
          vm.service.defaultFilter.uuid = customer.uuid;
          vm.service.defaultFilter.opened = true;
          return fn(filter);
        })
      }
    });

    controllerScope.__proto__ = new controllerClass();
  }
})();

(function() {
  angular.module('ncsaas')
    .controller('CustomerEventTabController', [
      'baseEventListController',
      'currentStateService',
      CustomerEventTabController
    ]);

  function CustomerEventTabController(baseEventListController, currentStateService) {
    var controllerScope = this;
    var EventController = baseEventListController.extend({

      init: function() {
        this.controllerScope = controllerScope;
        this._super();
      },

      getList: function(filter) {
        var vm = this,
          fn = this._super.bind(vm);
        return currentStateService.getCustomer().then(function(customer) {
          vm.service.defaultFilter.scope = customer.url;
          return fn(filter);
        });
      }
    });

    controllerScope.__proto__ = new EventController();
  }

})();

(function() {
  angular.module('ncsaas')
      .controller('CustomerInvoicesTabController', [
        'baseControllerListClass',
        'invoicesService',
        'ENTITYLISTFIELDTYPES',
        CustomerInvoicesTabController
      ]);

  function CustomerInvoicesTabController(
    baseControllerListClass,
    invoicesService,
    ENTITYLISTFIELDTYPES) {
    var controllerScope = this;
    var InvoicesController = baseControllerListClass.extend({
      init: function() {
        this.service = invoicesService;
        this._super();

        this.entityOptions = {
          entityData: {
            noDataText: 'No invoices yet',
            hideActionButtons: true,
            hideTableHead: false,
            rowTemplateUrl: 'views/payment/invoice.html'
          },
          list: [
            {
              name: 'Invoice code',
              propertyName: 'uuid',
              type: ENTITYLISTFIELDTYPES.trimmed,
              limit: 6
            },
            {
              name: 'Amount',
              propertyName: 'total_amount',
              type: ENTITYLISTFIELDTYPES.linkOrText,
            },
            {
              name: 'Start date',
              propertyName: 'start_date',
              type: ENTITYLISTFIELDTYPES.dateShort,
            },
            {
              name: 'End date',
              propertyName: 'end_date',
              type: ENTITYLISTFIELDTYPES.dateShort,
            },
            {
              name: '',
              propertyName: 'pdf',
              iconClass: 'fa-file-pdf-o',
              type: ENTITYLISTFIELDTYPES.staticIconLink,
              className: 'pdf-icon'
            }
          ]
        };
      },
      afterGetList: function() {}
    });

    controllerScope.__proto__ = new InvoicesController();
  }

})();
(function() {
  angular.module('ncsaas')
      .controller('CustomerDeleteTabController', [
        'baseControllerClass',
        'customersService',
        'currentStateService',
        '$state',
        CustomerDeleteTabController
      ]);

  function CustomerDeleteTabController(
      baseControllerClass,
      customersService,
      currentStateService,
      $state
  ) {
    var controllerScope = this;
    var DeleteController = baseControllerClass.extend({
      init: function() {
        this.controllerScope = controllerScope;
        this._super();
        var vm = this;
        currentStateService.getCustomer().then(function(customer) {
          vm.customer = customer;
        });
      },
      removeCustomer: function() {
        var confirmDelete = confirm('Confirm deletion?');
        if (confirmDelete) {
          this.customer.$delete().then(function(instance) {
            customersService.clearAllCacheForCurrentEndpoint();
            customersService.getPersonalOrFirstCustomer(instance.name).then(function(customer) {
              currentStateService.setCustomer(customer);
              $state.go('organizations.details', {uuid: customer.uuid, tab: 'eventlog'});
            });
          });
        }
      }
    });

    controllerScope.__proto__ = new DeleteController();
  }

})();
<|endoftext|>


<commit_before>window.addEventListener("deviceorientation", function (e) {
  var absolute = event.absolute;
  var alpha    = event.alpha;
  var x     = event.beta;
  var y    = event.gamma;

  document.getElementById("content").innerHTML =  "gamma: " + y + "
";

  document.getElementById("content").style.transform = "rotate3d(1, 0, 0, " + gamma + "deg)";
}, true);<commit_msg>Test on smartphone<commit_after>window.addEventListener("deviceorientation", function (e) {
  var absolute = event.absolute;
  var alpha    = event.alpha;
  var x     = event.beta;
  var y    = event.gamma;

  // document.getElementById("content").innerHTML =  "gamma: " + y + "
";

  document.getElementById("content").style.transform = "rotate3d(1, 0, 0, " + y + "deg)";
}, true);<|endoftext|>


<commit_before>'use strict';

//add dependencies
var express= require('express');
var bodyParser= require('body-parser')
var mongoose = require('mongoose');
var http = require('http');
// mongoose.connect('mongodb://localhost:27017');
// var db = mongoose.connection;
// db.on('error', console.error.bind(console, 'connection error:'));
// db.once('open', function() {
//   // we're connected!
// });
var app=express();
var PORT = 8080;

function handleRequest(request, response){
  if(request.method === "POST") {
    if (request.url === "/loadWorld") {
      console.log("Sending world data");
      response.writeHead(200,{"Content-Type": "application/JSON"})
      var otherArray = ["item1", "item2"];
      var otherObject = { item1: "item1val", item2: "item2val" };
      var json = JSON.stringify({
        anObject: otherObject,
        anArray: otherArray,
        another: "item"
      });
      response.end(json);
    }
    else if (request.url === "/saveWorld"){
      console.log("Save world data");
      response.writeHead(200,{"Content-Type": "text/plain"})
      // response.setEncoding('utf8');
      request.on('data', function (chunk) {
        console.log('BODY: ' + chunk);
      });
      response.end('I think I managed to save' )

    }
  }
}

//Create a server
var server = http.createServer(handleRequest);

//Lets start our server
server.listen(PORT, function(){
    //Callback triggered when server is successfully listening. Hurray!
    console.log("Server listening on: http://localhost:%s", PORT);
});

// app.use(express.static('/Client'));
// app.use(bodyParser);
//
//
//
// app.use(function(err, req, res, next) {
//   res.status(500).send('Something broke');
// });
// var router = express.Router();
//
// app.post('/test', function(req, res, next) {
// var body = JSON.parse(req.body.data);
// //   var queryNum = parseInt(body.num);
// var data = body.data;
// console.log(data)
// console.log("HOOGA")
// //   // get(queryNum, data, function(err, data) {
// //   //   if (err) {
// //   //     return next(err);
// //   //   }
// //     data='successful'
// //     res.send(data);
// //     next();
//   });
//
//
//
// app.listen(8080, function () {console.log('App listening');});
<commit_msg>Preparing for DB push<commit_after>'use strict';

//add dependencies
var express= require('express');
var bodyParser= require('body-parser')
var mongoose = require('mongoose');
var http = require('http');
mongoose.connect('mongodb://localhost:27017');
var Schema = mongoose.Schema;

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  // we're connected!
});
//mongod
//mongo
// show dbs
// use db
// show collections
// var Schema = mongoose.Schema;
// var state = new Schema({
//   spawnX: double,
//   spawnY: double,
//   spawnZ: double,
//
// })
// db.gameStates.find().skip(db.collection.count()-1)
var GameSchema = new Schema({
  spawnX: Number,
  spawnY: Number,
  spawnZ: Number,
  enemies: Number
});
var GameStates = mongoose.model('gameStates', GameSchema);

var app=express();
var PORT = 8080;

function handleRequest(request, response){
  if(request.method === "POST") {
    if (request.url === "/loadWorld") {
      console.log("Sending world data");
      response.writeHead(200,{"Content-Type": "application/JSON"})
      var otherArray = ["item1", "item2"];
      var otherObject = { item1: "item1val", item2: "item2val" };
      var json = JSON.stringify({
        anObject: otherObject,
        anArray: otherArray,
        another: "item"
      });
      response.end(json);
    }
    else if (request.url === "/saveWorld"){
      console.log("Save world data");
      response.writeHead(200,{"Content-Type": "text/plain"})
      // response.setEncoding('utf8');
      request.on('data', function (chunk) {
        console.log('BODY: ' + chunk);
        var state = new GameStates(chunk);
        state.save(function(err){
          if (err) throw err;
        });
      });
      response.end('I think I managed to save' )

    }
  }
}

//Create a server
var server = http.createServer(handleRequest);

//Lets start our server
server.listen(PORT, function(){
    //Callback triggered when server is successfully listening. Hurray!
    console.log("Server listening on: http://localhost:%s", PORT);
});

// app.use(express.static('/Client'));
// app.use(bodyParser);
//
//
//
// app.use(function(err, req, res, next) {
//   res.status(500).send('Something broke');
// });
// var router = express.Router();
//
// app.post('/test', function(req, res, next) {
// var body = JSON.parse(req.body.data);
// //   var queryNum = parseInt(body.num);
// var data = body.data;
// console.log(data)
// console.log("HOOGA")
// //   // get(queryNum, data, function(err, data) {
// //   //   if (err) {
// //   //     return next(err);
// //   //   }
// //     data='successful'
// //     res.send(data);
// //     next();
//   });
//
//
//
// app.listen(8080, function () {console.log('App listening');});
<|endoftext|>


<commit_before>'use strict';

var once           = require('timers-ext/once')
  , resolveTrigger = require('./_resolve-trigger')

  , create = Object.create;

module.exports = function (conf, onTrigger) {
	var postTrigger = resolveTrigger(conf.trigger, conf.triggerValue)
	  , preTrigger, prePool, clearPrePool, onPreTarget, onPostTarget;

	if (conf.preTrigger) preTrigger = resolveTrigger(conf.preTrigger, conf.preTriggerValue);

	if (preTrigger) {
		prePool = create(null);
		clearPrePool = once(function () { prePool = create(null); });
		onPreTarget = function (target) {
			if (prePool[target.__id__] === 'post') {
				onTrigger(target);
				return;
			}
			prePool[target.__id__] = 'pre';
			clearPrePool();
		};
		onPostTarget = function (target) {
			if (prePool[target.__id__] === 'pre') {
				onTrigger(target);
				return;
			}
			prePool[target.__id__] = 'post';
			clearPrePool();
		};
		preTrigger.on('change', function (event) {
			if (event.type === 'delete') {
				onPreTarget(event.value);
				return;
			}
			if (event.type === 'add') return;
			if (event.type === 'batch') {
				if (!event.deleted) return;
				event.deleted.forEach(onPreTarget);
				return;
			}
			console.log("Errorneous event:", event);
			throw new Error("Unsupported event: " + event.type);
		});
		postTrigger.on('change', function (event) {
			if (event.type === 'add') {
				onPostTarget(event.value);
				return;
			}
			if (event.type === 'delete') return;
			if (event.type === 'batch') {
				if (!event.added) return;
				event.added.forEach(onPostTarget);
				return;
			}
			console.log("Errorneous event:", event);
			throw new Error("Unsupported event: " + event.type);
		});
	} else {
		postTrigger.on('change', function (event) {
			if (event.type === 'add') {
				onTrigger(event.value);
				return;
			}
			if (event.type === 'delete') return;
			if (event.type === 'batch') {
				if (!event.added) return;
				event.added.forEach(onTrigger);
				return;
			}
			console.log("Errorneous event:", event);
			throw new Error("Unsupported event: " + event.type);
		});
	}

};
<commit_msg>Rename clearPrePool into clearPool<commit_after>'use strict';

var once           = require('timers-ext/once')
  , resolveTrigger = require('./_resolve-trigger')

  , create = Object.create;

module.exports = function (conf, onTrigger) {
	var postTrigger = resolveTrigger(conf.trigger, conf.triggerValue)
	  , preTrigger, prePool, clearPool, onPreTarget, onPostTarget;

	if (conf.preTrigger) preTrigger = resolveTrigger(conf.preTrigger, conf.preTriggerValue);

	if (preTrigger) {
		prePool = create(null);
		clearPool = once(function () { prePool = create(null); });
		onPreTarget = function (target) {
			if (prePool[target.__id__] === 'post') {
				onTrigger(target);
				return;
			}
			prePool[target.__id__] = 'pre';
			clearPool();
		};
		onPostTarget = function (target) {
			if (prePool[target.__id__] === 'pre') {
				onTrigger(target);
				return;
			}
			prePool[target.__id__] = 'post';
			clearPool();
		};
		preTrigger.on('change', function (event) {
			if (event.type === 'delete') {
				onPreTarget(event.value);
				return;
			}
			if (event.type === 'add') return;
			if (event.type === 'batch') {
				if (!event.deleted) return;
				event.deleted.forEach(onPreTarget);
				return;
			}
			console.log("Errorneous event:", event);
			throw new Error("Unsupported event: " + event.type);
		});
		postTrigger.on('change', function (event) {
			if (event.type === 'add') {
				onPostTarget(event.value);
				return;
			}
			if (event.type === 'delete') return;
			if (event.type === 'batch') {
				if (!event.added) return;
				event.added.forEach(onPostTarget);
				return;
			}
			console.log("Errorneous event:", event);
			throw new Error("Unsupported event: " + event.type);
		});
	} else {
		postTrigger.on('change', function (event) {
			if (event.type === 'add') {
				onTrigger(event.value);
				return;
			}
			if (event.type === 'delete') return;
			if (event.type === 'batch') {
				if (!event.added) return;
				event.added.forEach(onTrigger);
				return;
			}
			console.log("Errorneous event:", event);
			throw new Error("Unsupported event: " + event.type);
		});
	}

};
<|endoftext|>


<commit_before>(function () {
    var os = require("os");
    var winston = require('winston');
    require('winston-logstash-udp');
    var extend = require('extend');
    winston.emitErrs = true;

    var devmetricsObj;

    module.exports = function devmetricsCoreInit(options) {
        options = options || {};
        if (devmetricsObj && !options['no_cache']) return devmetricsObj;

        // Parse options
        var hostname = os.hostname() || 'undefined_host';
        var version = options['code_version'] ? options['software_version'] : 1;
        var host = options['host'] || 'service.devmetrics.io';
        var port = options['port'] || 5546;
        var app_id = options['app_id'] ? options['app_id'] : hostname.replace(/[\W_]+/g, "_"); // alphanum for token
        app_id = app_id.toLowerCase();

        // UDP transport
        var loggerObj = new winston.Logger({
            transports: [
                new winston.transports.LogstashUDP({
                    level: 'debug',
                    port: port,
                    node_name: app_id,
                    host: host,
                    handleExceptions: true
                })
            ],
            exitOnError: false
        });

        // Console logger, optional
        var stdLogger = false;
        if (!options['no_console']) {
            stdLogger = new winston.Logger({
                transports: [
                    new winston.transports.Console({
                        level: 'info',
                        handleExceptions: true,
                        json: false,
                        colorize: true
                    })
                ],
                exitOnError: false
            });
        }

        // morgan request logger
        var enableHttpLogger = function(app) {
            if (!app) {
                return;
            }
            var morgan = require('morgan');
            morgan.token('statsdKey', function getStatsdKey(req) {
                return req.statsdKey
            });
            morgan.token('sessionId', function(req, res) {
                return req.session ? req.session.id : 'N/A';
            });
            var requestObjDescr = {
                app_id: app_id,
                event_type: "http_request",
                metric_name: ":statsdKey",
                host: hostname,
                session: ":sessionId",
                referrer: ":referrer",
                user_agent: ":user-agent",
                request_uri: ":statsdKey",
                message: "[:date] :method :url :status :response-time ms",
                status_code: ":status",
                method: ":method",
                gauge_value: ":response-time"
            }

            var logsStream  = {
                write: function(message, encoding) {
                    var obj = JSON.parse(message);
                    var msg = 'http_request: ' + obj['method'] + ' ' + obj['request_uri'] + ' ' + obj['status_code'] + ' ' + 'took ' + Math.round(obj['response_time']) + ' ms';
                    if (obj['status_code'] >= 400) {
                        loggerObj.error(message);
                        if (stdLogger) {
                            stdLogger.error(msg);
                        }
                    } else {
                        loggerObj.info(message);
                        if (stdLogger) {
                            stdLogger.info(msg);
                        }
                    }
                }
            };

            var requestLogHandler = morgan(JSON.stringify(requestObjDescr), {stream: logsStream});

            var statsdURL = function (req, res, next) {
                req.statsdKey = ['http', req.path.replace(/[\/\.]/g, "-")].join('-');
                next();
            };

            app.use(statsdURL);
            app.use(requestLogHandler);
        }

        // mongoose request logger
        var enableMongooseLogger = function(mongoose) {
            if (!mongoose) {
                return false;
            }
            mongoose.set('debug', function (collectionName, method, query, doc, options) {
                var msg = 'mongo collection: ' + collectionName + ' method: ' + method;
                var uri = 'db--' + collectionName + '-' + method;
                var event = {
                    "app_id": app_id,
                    "event_type": "db_call",
                    "metric_name": collectionName + '.' + method,
                    "host": hostname,
                    "message": msg,
                    "uri": uri,
                    "method": method,
                    "response_time": 0 // request duration coming soon
                };
                loggerObj.info(event);
                if (stdLogger) {
                    stdLogger.info(msg);
                }
            });
        }

        var functionWrap = function (fn, funcName) {
            return function () {
                var dmFuncStart = new Date().getTime();
                var res = fn.apply(this, arguments);
                var duration = new Date ().getTime() - dmFuncStart;
                var msg = funcName + 'with args ' + arguments + ' took ' + duration + ' ms';
                constructObj('measurement', msg, [], false, false, false, duration);
                loggerObj.info(event);
                if (stdLogger) {
                    stdLogger.info(msg);
                }
                return res;
            };
        };

        // generic function to construct object for logstash
        var constructObj = function (event_type, message, dimensions, level, request, uid, gauge) {
            var stack_trace = null;
            var exception = null;
            uid = uid || (request && request.session ? request.session.id : '');
            var text = message;
            var obj = {};
            if (event_type == 'exception') {
                obj = extend(obj, {
                    'exception_stack': message.stack,
                    'error': 1
                });
                text = message.message;
            }
            for (var i in dimensions) {
                dimensions[i] = dimensions[i].replace(/[\W_]+/g, "_");
            }
            var metric_name = dimensions[0];
            obj = extend(obj, {
                "app_id": app_id,
                "metric_name": metric_name,
                "event_type": event_type,
                "host": hostname,
                "session": uid,
                "uri": request && request.path ? request.path.replace(/[\/\.]/g, "-").join('-') : '',
                "message": event_type + ": " + text,
                "version": version,
                "timestamp": new Date().getTime(),
                "gauge_value": gauge || 1,

                "severity": level || 'info',
                d1: dimensions[1] || '',
                d2: dimensions[2] || '',
                d3: dimensions[3] || '',
                d4: dimensions[4] || '',
                d5: dimensions[5] || '',
                d6: dimensions[6] || '',
                d7: dimensions[7] || ''
            });
            return obj;
        }

        var mainLogger = function (event_type, message, dimensions, request, params) {
            dimensions = dimensions || [];
            var level = dimensions[0] || 'info';
            params = params || {};
            var obj2send = constructObj(event_type, message, dimensions, level, request, params['uid'] || false);
            if (params) obj2send['params'] = params;

            obj2send = JSON.stringify(obj2send);

            if (loggerObj[level] && typeof loggerObj[level] == 'function') {
                loggerObj[level](obj2send);
            } else {
                loggerObj.info(obj2send);
            }

            if (stdLogger[level] && typeof stdLogger[level] == 'function') {
                stdLogger[level](message);
            } else {
                stdLogger.info(message);
            }
        };

        var utilTagsParser = function(event_tags) {
            event_tags = event_tags || [];
            if( Object.prototype.toString.call( event_tags ) !== '[object Array]' ) { // if not array, convert
                event_tags = [event_tags.toString()];
            }
            return event_tags;
        }

        devmetricsObj = {
            /**
             * @param event_name Metric name, all events with same metric name are aggregated
             * @param user_id optional, User unique identifier, used only for log
             * @param event_tags optional, Additional info, metric dimensions, string or array
             * @param request optional, request object if applicable, to fetch request context
             */
            userEvent: function (event_name, user_id, event_tags, request) {
                event_name = event_name.toString() || 'undefined';
                user_id = user_id.toString() || 0;
                event_tags = utilTagsParser(event_tags);
                event_tags.unshift(event_name);
                var msg = event_name;
                msg += user_id ? ', user: ' + user_id : '';
                msg += event_tags ? ', tags: ' + event_tags.join('.') : '';
                mainLogger('user_event', msg, event_tags, request, {uid: user_id});
            },
            /**
             * @param event_name Metric name, all events with same metric name are aggregated
             * @param event_tags optional, Additional info, metric dimensions, string or array
             * @param request optional, request object if applicable, to fetch request context
             */
            appEvent: function (event_name, event_tags, request) {
                event_name = event_name.toString() || 'undefined';
                event_tags = utilTagsParser(event_tags);
                event_tags.unshift(event_name);
                var msg = event_name;
                msg += event_tags ? ', tags: ' + event_tags.join('.') : '';
                mainLogger('app_event', msg, event_tags, request);
            },
            info: function (text, request) {
                mainLogger('log', text, ['info'], request);
            },
            warn: function (text, request) {
                mainLogger('log', text, ['warn'], request);
            },
            warning: function (text, request) {
                mainLogger('log', text, ['warn'], request);
            },
            error: function (text, request) {
                mainLogger('log', text, ['error'], request);
            },
            exception: function (err, request) {
                mainLogger('exception', err, ['error'], request);
            },
            /**
             * Out-of-the-box Express.js requests intrumentation
             */
            enableHttpLogger : enableHttpLogger,
            /**
             * Basic mongoose requests instrumentation
             */
            enableMongooseLogger: enableMongooseLogger,
            /**
             * Measure a specific function execution time.
             */
            measureTimeWrap: functionWrap
        };

        devmetricsObj.info('Checkout logs @ http://www.devmetrics.io/logs/' + app_id + '/tail');

        return devmetricsObj;
    }

})();
<commit_msg>fixed structure for http/db methods<commit_after>(function () {
    var os = require("os");
    var winston = require('winston');
    require('winston-logstash-udp');
    var extend = require('extend');
    winston.emitErrs = true;

    var devmetricsObj;

    module.exports = function devmetricsCoreInit(options) {
        options = options || {};
        if (devmetricsObj && !options['no_cache']) return devmetricsObj;

        // Parse options
        var hostname = os.hostname() || 'undefined_host';
        var version = options['code_version'] ? options['software_version'] : 1;
        var host = options['host'] || 'service.devmetrics.io';
        var port = options['port'] || 5546;
        var app_id = options['app_id'] ? options['app_id'] : hostname.replace(/[\W_]+/g, "_"); // alphanum for token
        app_id = app_id.toLowerCase();

        // UDP transport
        var loggerObj = new winston.Logger({
            transports: [
                new winston.transports.LogstashUDP({
                    level: 'debug',
                    port: port,
                    node_name: app_id,
                    host: host,
                    handleExceptions: true
                })
            ],
            exitOnError: false
        });

        // Console logger, optional
        var stdLogger = false;
        if (!options['no_console']) {
            stdLogger = new winston.Logger({
                transports: [
                    new winston.transports.Console({
                        level: 'info',
                        handleExceptions: true,
                        json: false,
                        colorize: true
                    })
                ],
                exitOnError: false
            });
        }

        // morgan request logger
        var enableHttpLogger = function(app) {
            if (!app) {
                return;
            }
            var morgan = require('morgan');
            morgan.token('statsdKey', function getStatsdKey(req) {
                return req.statsdKey
            });
            morgan.token('sessionId', function(req, res) {
                return req.session ? req.session.id : 'N/A';
            });
            var requestObjDescr = {
                app_id: app_id,
                event_type: "app_event",
                metric_name: "http_request",
                host: hostname,
                session: ":sessionId",
                referrer: ":referrer",
                user_agent: ":user-agent",
                request_uri: ":statsdKey",
                message: "[:date] :method :url :status :response-time ms",
                status_code: ":status",
                method: ":method",
                gauge_value: ":response-time",
                d1: ":statsdKey",
                d2: ":status",
                d3: ":method"
            }

            var logsStream  = {
                write: function(message, encoding) {
                    var obj = JSON.parse(message);
                    var msg = 'http_request: ' + obj['method'] + ' ' + obj['request_uri'] + ' ' + obj['status_code'] + ' ' + 'took ' + Math.round(obj['gauge_value']) + ' ms';
                    if (obj['status_code'] >= 400) {
                        loggerObj.error(message);
                        if (stdLogger) {
                            stdLogger.error(msg);
                        }
                    } else {
                        loggerObj.info(message);
                        if (stdLogger) {
                            stdLogger.info(msg);
                        }
                    }
                }
            };

            var requestLogHandler = morgan(JSON.stringify(requestObjDescr), {stream: logsStream});

            var statsdURL = function (req, res, next) {
                req.statsdKey = ['http', req.path.replace(/[\/\.]/g, "-")].join('-');
                next();
            };

            app.use(statsdURL);
            app.use(requestLogHandler);
        }

        // mongoose request logger
        var enableMongooseLogger = function(mongoose) {
            if (!mongoose) {
                return false;
            }
            mongoose.set('debug', function (collectionName, method, query, doc, options) {
                var msg = 'mongo collection: ' + collectionName + ' method: ' + method;
                var uri = 'db--' + collectionName + '-' + method;
                var event = {
                    "app_id": app_id,
                    "event_type": "app_event",
                    "metric_name": "mongoose",
                    "host": hostname,
                    "message": msg,
                    "uri": uri,
                    "method": method,
                    "response_time": 0, // request duration coming soon
                    "d1": collectionName,
                    "d2": method
                };
                loggerObj.info(event);
                if (stdLogger) {
                    stdLogger.info(msg);
                }
            });
        }

        var functionWrap = function (fn, funcName) {
            return function () {
                var dmFuncStart = new Date().getTime();
                var res = fn.apply(this, arguments);
                var duration = new Date ().getTime() - dmFuncStart;
                var msg = funcName + 'with args ' + arguments + ' took ' + duration + ' ms';
                constructObj('measurement', msg, [], false, false, false, duration);
                loggerObj.info(event);
                if (stdLogger) {
                    stdLogger.info(msg);
                }
                return res;
            };
        };

        // generic function to construct object for logstash
        var constructObj = function (event_type, message, dimensions, level, request, uid, gauge) {
            var stack_trace = null;
            var exception = null;
            uid = uid || (request && request.session ? request.session.id : '');
            var text = message;
            var obj = {};
            if (event_type == 'exception') {
                obj = extend(obj, {
                    'exception_stack': message.stack,
                    'error': 1
                });
                text = message.message;
            }
            for (var i in dimensions) {
                dimensions[i] = dimensions[i].replace(/[\W_]+/g, "_");
            }
            var metric_name = dimensions[0];
            obj = extend(obj, {
                "app_id": app_id,
                "metric_name": metric_name,
                "event_type": event_type,
                "host": hostname,
                "session": uid,
                "uri": request && request.path ? request.path.replace(/[\/\.]/g, "-").join('-') : '',
                "message": event_type + ": " + text,
                "version": version,
                "timestamp": new Date().getTime(),
                "gauge_value": gauge || 1,

                "severity": level || 'info',
                d1: dimensions[1] || '',
                d2: dimensions[2] || '',
                d3: dimensions[3] || '',
                d4: dimensions[4] || '',
                d5: dimensions[5] || '',
                d6: dimensions[6] || '',
                d7: dimensions[7] || ''
            });
            return obj;
        }

        var mainLogger = function (event_type, message, dimensions, request, params) {
            dimensions = dimensions || [];
            var level = dimensions[0] || 'info';
            params = params || {};
            var obj2send = constructObj(event_type, message, dimensions, level, request, params['uid'] || false);
            if (params) obj2send['params'] = params;

            obj2send = JSON.stringify(obj2send);

            if (loggerObj[level] && typeof loggerObj[level] == 'function') {
                loggerObj[level](obj2send);
            } else {
                loggerObj.info(obj2send);
            }

            if (stdLogger[level] && typeof stdLogger[level] == 'function') {
                stdLogger[level](message);
            } else {
                stdLogger.info(message);
            }
        };

        var utilTagsParser = function(event_tags) {
            event_tags = event_tags || [];
            if( Object.prototype.toString.call( event_tags ) !== '[object Array]' ) { // if not array, convert
                event_tags = [event_tags.toString()];
            }
            return event_tags;
        }

        devmetricsObj = {
            /**
             * @param event_name Metric name, all events with same metric name are aggregated
             * @param user_id optional, User unique identifier, used only for log
             * @param event_tags optional, Additional info, metric dimensions, string or array
             * @param request optional, request object if applicable, to fetch request context
             */
            userEvent: function (event_name, user_id, event_tags, request) {
                event_name = event_name.toString() || 'undefined';
                user_id = user_id.toString() || 0;
                event_tags = utilTagsParser(event_tags);
                event_tags.unshift(event_name);
                var msg = event_name;
                msg += user_id ? ', user: ' + user_id : '';
                msg += event_tags ? ', tags: ' + event_tags.join('.') : '';
                mainLogger('user_event', msg, event_tags, request, {uid: user_id});
            },
            /**
             * @param event_name Metric name, all events with same metric name are aggregated
             * @param event_tags optional, Additional info, metric dimensions, string or array
             * @param request optional, request object if applicable, to fetch request context
             */
            appEvent: function (event_name, event_tags, request) {
                event_name = event_name.toString() || 'undefined';
                event_tags = utilTagsParser(event_tags);
                event_tags.unshift(event_name);
                var msg = event_name;
                msg += event_tags ? ', tags: ' + event_tags.join('.') : '';
                mainLogger('app_event', msg, event_tags, request);
            },
            info: function (text, request) {
                mainLogger('log', text, ['info'], request);
            },
            warn: function (text, request) {
                mainLogger('log', text, ['warn'], request);
            },
            warning: function (text, request) {
                mainLogger('log', text, ['warn'], request);
            },
            error: function (text, request) {
                mainLogger('log', text, ['error'], request);
            },
            exception: function (err, request) {
                mainLogger('exception', err, ['error'], request);
            },
            /**
             * Out-of-the-box Express.js requests intrumentation
             */
            enableHttpLogger : enableHttpLogger,
            /**
             * Basic mongoose requests instrumentation
             */
            enableMongooseLogger: enableMongooseLogger,
            /**
             * Measure a specific function execution time.
             */
            measureTimeWrap: functionWrap
        };

        devmetricsObj.info('Checkout logs @ http://www.devmetrics.io/logs/' + app_id + '/tail');

        return devmetricsObj;
    }

})();
<|endoftext|>


<commit_before>window.addEventListener("deviceorientation", function (e) {
  var absolute = event.absolute;
  var alpha    = event.alpha;
  var beta     = event.beta;
  var gamma    = event.gamma;

  document.getElementById("content").style.transform = "rotate3d(1, 0, 0, " + gamma + "deg)";
}, true);<commit_msg>Test on smartphone<commit_after>window.addEventListener("deviceorientation", function (e) {
  var absolute = event.absolute;
  var alpha    = event.alpha;
  var x     = event.beta;
  var y    = event.gamma;

  document.getElementById("content").innerHTML =  "gamma: " + y + "<br />";

  document.getElementById("content").style.transform = "rotate3d(1, 0, 0, " + gamma + "deg)";
}, true);<|endoftext|>


<commit_before>// @flow
import * as React from 'react'
import {connect} from 'react-redux'
import {push} from 'react-router-redux'

import {
  updateRobotServer,
  restartRobotServer,
  clearUpdateResponse,
  makeGetRobotUpdateInfo,
  makeGetRobotUpdateRequest,
  makeGetRobotRestartRequest,
  setIgnoredUpdate,
} from '../../http-api-client'

import {getShellUpdateState} from '../../shell'

import type {ShellUpdateState} from '../../shell'

import {Icon} from '@opentrons/components'
import {ScrollableAlertModal} from '../modals'
import UpdateAppMessage from './UpdateAppMessage'
import UpdateRobotMessage from './UpdateRobotMessage'
import ReleaseNotes from '../ReleaseNotes'

import type {State, Dispatch} from '../../types'
import type {ViewableRobot} from '../../discovery'
import type {
  RobotServerUpdate,
  RobotServerRestart,
  RobotUpdateInfo,
} from '../../http-api-client'

type OP = {robot: ViewableRobot}

type SP = {|
  appUpdate: ShellUpdateState,
  updateInfo: RobotUpdateInfo,
  updateRequest: RobotServerUpdate,
  restartRequest: RobotServerRestart,
|}

type DP = {dispatch: Dispatch}

type Props = {
  ...$Exact<OP>,
  ...SP,
  update: () => mixed,
  restart: () => mixed,
  ignoreUpdate: () => mixed,
}

const DOWNGRADE_MSG =
  'Your app is at an older version than your robot. You may want to downgrade your robot to ensure compatability.'
const UPGRADE_MSG =
  'Your robot is at an older version than your app. We recommend you upgrade your robot to ensure compatability.'
const ALREADY_UPDATED_MSG =
  "It looks like your robot is already up to date, but if you're experiencing issues you can re-apply the latest update."
const RESTART_MSG =
  'Restart your robot to finish the update. It may take several minutes for your robot to restart.'

// TODO(mc, 2018-03-19): prop or component for text-height icons
const Spinner = () => <Icon name="ot-spinner" height="1em" spin />

export default connect(
  makeMapStateToProps,
  null,
  mergeProps
)(RobotUpdateModal)

function RobotUpdateModal (props: Props) {
  const {
    updateInfo,
    ignoreUpdate,
    update,
    restart,
    updateRequest,
    restartRequest,
    appUpdate: {available, info},
  } = props
  const inProgress = updateRequest.inProgress || restartRequest.inProgress
  let closeButtonText = 'not now'
  let message
  let button

  const heading = updateInfo.type
    ? `Version ${updateInfo.version} available`
    : 'Robot is up to date'

  let buttonAction
  let buttonText
  if (!updateRequest.response) {
    buttonAction = update
    if (updateInfo.type) {
      message = updateInfo.type === 'upgrade' ? UPGRADE_MSG : DOWNGRADE_MSG
      buttonText = updateInfo.type
    } else {
      message = ALREADY_UPDATED_MSG
      buttonText = 'reinstall'
    }
  } else {
    message = RESTART_MSG
    buttonText = 'restart'
    buttonAction = restart
  }

  button = inProgress
    ? {disabled: true, children: <Spinner />}
    : {onClick: buttonAction, children: buttonText}

  let source =
    info && info.releaseNotes ? removeAppNotes(info.releaseNotes) : null

  return (
    <ScrollableAlertModal
      heading={heading}
      buttons={[{onClick: ignoreUpdate, children: closeButtonText}, button]}
      alertOverlay
    >
      {available && <UpdateAppMessage />}
      <UpdateRobotMessage message={message} />
      <ReleaseNotes source={source} />
    </ScrollableAlertModal>
  )
}

function makeMapStateToProps (): (State, OP) => SP {
  const getRobotUpdateInfo = makeGetRobotUpdateInfo()
  const getRobotUpdateRequest = makeGetRobotUpdateRequest()
  const getRobotRestartRequest = makeGetRobotRestartRequest()

  return (state, ownProps) => ({
    appUpdate: getShellUpdateState(state),
    updateInfo: getRobotUpdateInfo(state, ownProps.robot),
    updateRequest: getRobotUpdateRequest(state, ownProps.robot),
    restartRequest: getRobotRestartRequest(state, ownProps.robot),
  })
}

function mergeProps (stateProps: SP, dispatchProps: DP, ownProps: OP): Props {
  const {robot} = ownProps
  const {updateInfo} = stateProps
  const {dispatch} = dispatchProps

  const close = () => dispatch(push(`/robots/${robot.name}`))
  let ignoreUpdate = updateInfo.type
    ? () => dispatch(setIgnoredUpdate(robot, updateInfo.version)).then(close)
    : close

  return {
    ...stateProps,
    ...ownProps,
    ignoreUpdate,
    update: () => dispatch(updateRobotServer(robot)),
    restart: () => {
      dispatch(restartRobotServer(robot))
        .then(() => dispatch(clearUpdateResponse(robot)))
        .then(close)
    },
  }
}

// TODO (ka, 2018-10-1):
// Grabbing only the api notes removes changes since and technical change log

const RE_APP_NOTES = /<!-- start:@opentrons\/app -->([\S\s]*?)<!-- end:@opentrons\/app -->/

function removeAppNotes (notes: string) {
  return notes.replace(RE_APP_NOTES, '')
}
<commit_msg>fix(app): Show the correct release notes for robot update (#2560)<commit_after>// @flow
import * as React from 'react'
import {connect} from 'react-redux'
import {push} from 'react-router-redux'

import {
  updateRobotServer,
  restartRobotServer,
  clearUpdateResponse,
  makeGetRobotUpdateInfo,
  makeGetRobotUpdateRequest,
  makeGetRobotRestartRequest,
  setIgnoredUpdate,
} from '../../http-api-client'

import {CURRENT_RELEASE_NOTES, getShellUpdateState} from '../../shell'

import type {ShellUpdateState} from '../../shell'

import {Icon} from '@opentrons/components'
import {ScrollableAlertModal} from '../modals'
import UpdateAppMessage from './UpdateAppMessage'
import UpdateRobotMessage from './UpdateRobotMessage'
import ReleaseNotes from '../ReleaseNotes'

import type {State, Dispatch} from '../../types'
import type {ViewableRobot} from '../../discovery'
import type {
  RobotServerUpdate,
  RobotServerRestart,
  RobotUpdateInfo,
} from '../../http-api-client'

type OP = {robot: ViewableRobot}

type SP = {|
  appUpdate: ShellUpdateState,
  updateInfo: RobotUpdateInfo,
  updateRequest: RobotServerUpdate,
  restartRequest: RobotServerRestart,
|}

type DP = {dispatch: Dispatch}

type Props = {
  ...$Exact<OP>,
  ...SP,
  update: () => mixed,
  restart: () => mixed,
  ignoreUpdate: () => mixed,
}

const API_RELEASE_NOTES = CURRENT_RELEASE_NOTES.replace(
  /<!-- start:@opentrons\/app -->([\S\s]*?)<!-- end:@opentrons\/app -->/,
  ''
)

const DOWNGRADE_MSG =
  'Your app is at an older version than your robot. You may want to downgrade your robot to ensure compatability.'
const UPGRADE_MSG =
  'Your robot is at an older version than your app. We recommend you upgrade your robot to ensure compatability.'
const ALREADY_UPDATED_MSG =
  "It looks like your robot is already up to date, but if you're experiencing issues you can re-apply the latest update."
const RESTART_MSG =
  'Restart your robot to finish the update. It may take several minutes for your robot to restart.'

// TODO(mc, 2018-03-19): prop or component for text-height icons
const Spinner = () => <Icon name="ot-spinner" height="1em" spin />

export default connect(
  makeMapStateToProps,
  null,
  mergeProps
)(RobotUpdateModal)

function RobotUpdateModal (props: Props) {
  const {
    updateInfo,
    ignoreUpdate,
    update,
    restart,
    updateRequest,
    restartRequest,
    appUpdate: {available},
  } = props
  const inProgress = updateRequest.inProgress || restartRequest.inProgress
  let closeButtonText = 'not now'
  let message
  let button

  const heading = updateInfo.type
    ? `Version ${updateInfo.version} available`
    : 'Robot is up to date'

  let buttonAction
  let buttonText
  if (!updateRequest.response) {
    buttonAction = update
    if (updateInfo.type) {
      message = updateInfo.type === 'upgrade' ? UPGRADE_MSG : DOWNGRADE_MSG
      buttonText = updateInfo.type
    } else {
      message = ALREADY_UPDATED_MSG
      buttonText = 'reinstall'
    }
  } else {
    message = RESTART_MSG
    buttonText = 'restart'
    buttonAction = restart
  }

  button = inProgress
    ? {disabled: true, children: <Spinner />}
    : {onClick: buttonAction, children: buttonText}

  return (
    <ScrollableAlertModal
      heading={heading}
      buttons={[{onClick: ignoreUpdate, children: closeButtonText}, button]}
      alertOverlay
    >
      {available && <UpdateAppMessage />}
      <UpdateRobotMessage message={message} />
      <ReleaseNotes source={API_RELEASE_NOTES} />
    </ScrollableAlertModal>
  )
}

function makeMapStateToProps (): (State, OP) => SP {
  const getRobotUpdateInfo = makeGetRobotUpdateInfo()
  const getRobotUpdateRequest = makeGetRobotUpdateRequest()
  const getRobotRestartRequest = makeGetRobotRestartRequest()

  return (state, ownProps) => ({
    appUpdate: getShellUpdateState(state),
    updateInfo: getRobotUpdateInfo(state, ownProps.robot),
    updateRequest: getRobotUpdateRequest(state, ownProps.robot),
    restartRequest: getRobotRestartRequest(state, ownProps.robot),
  })
}

function mergeProps (stateProps: SP, dispatchProps: DP, ownProps: OP): Props {
  const {robot} = ownProps
  const {updateInfo} = stateProps
  const {dispatch} = dispatchProps

  const close = () => dispatch(push(`/robots/${robot.name}`))
  let ignoreUpdate = updateInfo.type
    ? () => dispatch(setIgnoredUpdate(robot, updateInfo.version)).then(close)
    : close

  return {
    ...stateProps,
    ...ownProps,
    ignoreUpdate,
    update: () => dispatch(updateRobotServer(robot)),
    restart: () => {
      dispatch(restartRobotServer(robot))
        .then(() => dispatch(clearUpdateResponse(robot)))
        .then(close)
    },
  }
}
<|endoftext|>