<commit_before>var sys = require('pex-sys');
var glu = require('pex-glu');
var materials = require('pex-materials');
var color = require('pex-color');
var gen = require('pex-gen');
var geom = require('pex-geom');
var helpers = require('pex-helpers');

var Octree = geom.Octree;
var OctreeHelper = helpers.OctreeHelper;
var Cube = gen.Cube;
var Vec3 = geom.Vec3;
var Mesh = glu.Mesh;
var ShowNormals = materials.ShowNormals;
var SolidColor = materials.SolidColor;
var PerspectiveCamera = glu.PerspectiveCamera;
var Arcball = glu.Arcball;
var Color = color.Color;
var Platform = sys.Platform;
var Time = sys.Time;

sys.Window.create({
  settings: {
    width: 1280,
    height: 720,
    type: '3d',
    fullscreen: Platform.isBrowser ? true : false
  },
  init: function() {
    this.pointMesh = new Mesh(new Cube(0.05), new SolidColor({ color: Color.Red }));

    this.camera = new PerspectiveCamera(60, this.width / this.height);
    this.arcball = new Arcball(this, this.camera, 5);
    this.arcball.setTarget(new Vec3(1, 1, 0));
    this.arcball.setPosition(new Vec3(1, 1, 4));

    this.octree = new Octree(new Vec3(0, 0, 0), new Vec3(2, 2, 2));
    this.points = [];

    //this.testRandom(this.octree);
    this.testNearest(this.octree);

    this.pointInstances = this.points.map(function(p) {
      return { position: p, uniforms: { color: Color.Red } };
    })

    this.octreeHelper0 = new OctreeHelper(this.octree, Color.Green, 0);
    this.octreeHelper0.z = -0.01;
    this.octreeHelper1 = new OctreeHelper(this.octree, Color.Blue, 1);
    this.octreeHelper1.x = -0.01;
    this.octreeHelper2 = new OctreeHelper(this.octree, Color.Red, 2);
    this.octreeHelper2.x = 0.01;
    this.octreeHelper3 = new OctreeHelper(this.octree, Color.White, 3);

    this.on('mouseMoved', function(e){
      var ray = this.camera.getWorldRay(e.x, e.y, this.width, this.height);
      var hit = ray.hitTestPlane(new Vec3(0, 0, 1), new Vec3(0, 0, -1));
      if (hit.length > 0) {
        this.targetPoint = hit[0];
      }
      else {
        console.log('bla')
      }
    }.bind(this))
  },
  testRandom: function(octree) {
    var n = 10;

    for(var i=0; i<n; i++) {
      var p = geom.randomVec3(1).add(new Vec3(1, 1, 1)); //move the points to (0,0,0),(2,2,2) box
      this.points.push(p);
      octree.add(p);
    }
  },
  testNearest: function(octree) {
    var n = 100;

    geom.randomSeed(1);
    for(var i=0; i<n; i++) {
      var p = geom.randomVec3(1).add(new Vec3(1, 1, 1)); //move the points to (0,0,0),(2,2,2) box
      p.z = 1; //for easier debugging
      this.points.push(p);
    }

    //this.points.push(new Vec3(0, 0, 0));
    //this.points.push(new Vec3(1, 0, 0));
    //this.points.push(new Vec3(0, 1, 0));
    //this.points.push(new Vec3(0, 0, 1));
    //this.points.push(new Vec3(1, 0, 1));
    //this.points.push(new Vec3(1, 1, 0));
    //this.points.push(new Vec3(0, 1, 1));
    //this.points.push(new Vec3(1, 1, 1));
    //this.points.push(new Vec3(0.5, 0.5, 0.5));
    //this.points.push(new Vec3(0.75, 0.75, 0.75));

    this.points.forEach(function(p) {
      octree.add(p);
    })

    console.log('this.nearestPoint', this.nearestPoint)
  },
  draw: function() {
    glu.clearColorAndDepth(Color.Black);
    glu.enableDepthReadAndWrite(true);
    this.octreeHelper0.draw(this.camera);
    this.octreeHelper1.draw(this.camera);
    this.octreeHelper2.draw(this.camera);
    this.octreeHelper3.draw(this.camera);
    this.pointMesh.drawInstances(this.camera, this.pointInstances);

    if (!this.once) {
      //this.targetPoint = new Vec3(
      //  1 + 0.9 * Math.cos(1 * Time.seconds),
      //  1, //1 + 0.9 * Math.sin(1 * Time.seconds*1.5), //for easier debugging
      //  1 - 0.9 * Math.cos(1 * Time.seconds*0.2)
      //);
      this.targetPoint = new Vec3(1-0.51, 1, 1 + 0.49); //tricky edge case
      this.once = true;
    }

    this.nearestPoint = this.octree.findNearestPoint(this.targetPoint);

    if (this.targetPoint) this.pointMesh.drawInstances(this.camera, [ { position: this.targetPoint, uniforms: { color: Color.Yellow } }]);
    if (this.nearestPoint) this.pointMesh.drawInstances(this.camera, [ { position: this.nearestPoint, uniforms: { color: Color.Green }, scale: new Vec3(1.1, 1.1, 1.1) }]);
  }
});
<commit_msg>Added data storage to Octree example<commit_after>var sys = require('pex-sys');
var glu = require('pex-glu');
var materials = require('pex-materials');
var color = require('pex-color');
var gen = require('pex-gen');
var geom = require('pex-geom');
var helpers = require('pex-helpers');

var Octree = geom.Octree;
var OctreeHelper = helpers.OctreeHelper;
var Cube = gen.Cube;
var Vec3 = geom.Vec3;
var Mesh = glu.Mesh;
var ShowNormals = materials.ShowNormals;
var SolidColor = materials.SolidColor;
var PerspectiveCamera = glu.PerspectiveCamera;
var Arcball = glu.Arcball;
var Color = color.Color;
var Platform = sys.Platform;
var Time = sys.Time;

sys.Window.create({
  settings: {
    width: 1280,
    height: 720,
    type: '3d',
    fullscreen: Platform.isBrowser ? true : false
  },
  init: function() {
    this.pointMesh = new Mesh(new Cube(0.05), new SolidColor({ color: Color.Red }));

    this.camera = new PerspectiveCamera(60, this.width / this.height);
    this.arcball = new Arcball(this, this.camera, 5);
    this.arcball.setTarget(new Vec3(1, 1, 0));
    this.arcball.setPosition(new Vec3(1, 1, 4));

    this.octree = new Octree(new Vec3(0, 0, 0), new Vec3(2, 2, 2));
    this.points = [];

    this.testNearest(this.octree);

    this.pointInstances = this.points.map(function(p) {
      return { position: p, uniforms: { color: Color.White } };
    })

    this.octreeHelper0 = new OctreeHelper(this.octree, Color.Green, 0);
    this.octreeHelper0.z = -0.01;
    this.octreeHelper1 = new OctreeHelper(this.octree, Color.Blue, 1);
    this.octreeHelper1.x = -0.01;
    this.octreeHelper2 = new OctreeHelper(this.octree, Color.Red, 2);
    this.octreeHelper2.x = 0.01;
    this.octreeHelper3 = new OctreeHelper(this.octree, Color.White, 3);

    this.on('mouseMoved', function(e){
      var ray = this.camera.getWorldRay(e.x, e.y, this.width, this.height);
      var hit = ray.hitTestPlane(new Vec3(0, 0, 1), new Vec3(0, 0, -1));
      if (hit.length > 0) {
        this.targetPoint = hit[0];
      }
      else {
        console.log('bla')
      }
    }.bind(this))
  },

  testNearest: function(octree) {
    var n = 100;

    geom.randomSeed(1);
    for(var i=0; i<n; i++) {
      var p = geom.randomVec3(1).add(new Vec3(1, 1, 1)); //move the points to (0,0,0),(2,2,2) box
      p.z = 1; //for easier debugging
      this.points.push(p);
    }

    this.points.forEach(function(p) {
      octree.add(p, Color.fromHSL(Math.random(), 1, 0.5));
    })

    console.log('this.nearestPoint', this.nearestPoint)
  },
  draw: function() {
    glu.clearColorAndDepth(Color.Black);
    glu.enableDepthReadAndWrite(true);
    this.octreeHelper0.draw(this.camera);
    this.octreeHelper1.draw(this.camera);
    this.octreeHelper2.draw(this.camera);
    this.octreeHelper3.draw(this.camera);
    this.pointMesh.drawInstances(this.camera, this.pointInstances);

    if (!this.once) {
      this.targetPoint = new Vec3(1-0.51, 1, 1 + 0.49); //tricky edge case
      this.once = true;
    }

    var nearestResult = this.octree.findNearestPoint(this.targetPoint, { includeData: true });
    this.nearestPoint = nearestResult.point;

    if (this.targetPoint) this.pointMesh.drawInstances(this.camera, [ { position: this.targetPoint, uniforms: { color: nearestResult.data } }]);
    if (this.nearestPoint) this.pointMesh.drawInstances(this.camera, [ { position: this.nearestPoint, uniforms: { color: nearestResult.data  }, scale: new Vec3(1.1, 1.1, 1.1) }]);
  }
});
<|endoftext|>


<commit_before>var dnode = require('dnode');
var shoe = require('shoe');
var swig = require('swig/lib/swig');

var templates = {
    'twitter': require('./templates/posts/twitter.html'),
    'facebook': require('./templates/posts/facebook.html')
};

var $ = require('jquery-browserify');

var FACEBOOK_POST_REGEXP = /(\d+)_(\d+)/;
var DOTS = /\.\.\.$/;

var postsCount = 0;
var displayedPosts = {};

function createPost(post) {
    switch (post.type) {
        case 'twitter':
            return $(templates.twitter({
                'post': post
            })).data('foreign_timestamp', post.foreign_timestamp);
        case 'facebook':
            var post_id = null;
            var post_link = null;
            var post_match = FACEBOOK_POST_REGEXP.exec(post.data.id);
            if (post_match) {
                post_id = post_match[2];
                post_link = 'https://www.facebook.com/' + post_match[1] + '/posts/' + post_match[2];
            }
            else {
                console.warning("Facebook post does not have a link and ID: %s", post.foreign_id, post);
            }

            // Override with a better version
            if (post.data.actions && post.data.actions.length > 0 && post.data.actions[0].link) {
                post_link = post.data.actions[0].link.split('http://').join('https://');
            }

            if (post.data.actions) {
                $.each(post.data.actions, function (i, action) {
                    post.data.actions[action.name.toLowerCase()] = action;
                });
            }

            var event_in_past = false;
            if (post.facebook_event && post.facebook_event.start_time) {
                if (new Date(post.facebook_event.start_time) < new Date()) {
                    event_in_past = true;
                }
            }

            return $(templates.facebook({
                'post': post,
                'post_link': post_link,
                'post_id': post_id,
                'event_in_past': event_in_past
            })).data('foreign_timestamp', post.foreign_timestamp);
        default:
            console.error("Unknown post type: %s", post.type, post);
            return null;
    }
}

function renderTweets() {
    if (typeof twttr === 'undefined') {
        alert("Not all necessary scripts have loaded. Are you using ad-block or something similar?");
        return;
    }

    twttr.widgets.load();
}

function postsRelayout() {
    $('#posts').isotope('reLayout');
}

function shortenPosts() {
    $('#posts .short').dotdotdot({
        'callback': function(isTruncated, orgContent) {
            var t = $(this);
            t.removeClass('short');
            if (isTruncated) {
                var link = $('').addClass('see-more');
                if (DOTS.test($.trim(t.text()))) {
                    link.append($('
'));
                }
                link.append(
                    $('').text("See More").click(function (event) {
                        t.trigger('destroy').html(orgContent);
                        postsRelayout();
                    })
                );
                t.append(link);
                postsRelayout();
            }
        }
    });
}

function displayNewPost(post) {
    if (displayedPosts[post.type + '-' + post.foreign_id]) {
        return;
    }
    displayedPosts[post.type + '-' + post.foreign_id] = true;
    postsCount++;

    var postElement = createPost(post);
    if (postElement) {
        $('#posts').isotope('insert', postElement, function () {
            renderTweets();
            shortenPosts();

            // Twitter and Facebook posts can resize after loading
            // because images and other media can be loaded, so we
            // wait a bit and relayout posts again
            // TODO: Should call this probably after all DOM manipulations and media has loaded - is there such an event?
            setTimeout(postsRelayout, 1000);
            setTimeout(postsRelayout, 5000);
            setTimeout(postsRelayout, 30000);
            setTimeout(postsRelayout, 60000);
        });
    }
}

function displayOldPosts(posts) {
    var postElements = $();
    $.each(posts, function (i, post) {
        if (displayedPosts[post.type + '-' + post.foreign_id]) {
            return;
        }
        displayedPosts[post.type + '-' + post.foreign_id] = true;
        postsCount++;

        postElements = postElements.add(createPost(post));
    });

    if (postElements.length > 0) {
        $('#posts').isotope('insert', postElements, function () {
            renderTweets();
            shortenPosts();

            // Twitter and Facebook posts can resize after loading
            // because images and other media can be loaded, so we
            // wait a bit and relayout posts again
            // TODO: Should call this probably after all DOM manipulations and media has loaded - is there such an event?
            setTimeout(postsRelayout, 1000);
            setTimeout(postsRelayout, 5000);
            setTimeout(postsRelayout, 30000);
            setTimeout(postsRelayout, 60000);
        });
    }
}

function loadMorePosts(remote) {
    // TODO: Fix comment
    // We can use a simple counter because we are not deleting any posts
    // Otherwise, if we would be deleting posts, simply counting could make us skip some posts
    remote.getPosts(postsCount, 10, function (err, posts) {
        if (err) {
            console.error(err);
            return;
        }

        displayOldPosts(posts);
    });
}

function displayNewEvent(event) {
    // TOOD: Implement
    console.log(event);
}

$(document).ready(function () {
    $('#posts').isotope({
        'itemSelector': '.post',
        'getSortData': {
            'foreign_timestamp': function (elem) {
                return elem.data('foreign_timestamp');
            }
        },
        'sortBy': 'foreign_timestamp',
        'sortAscending': false,
        // We disable animations
        'transformsEnabled': false,
        'animationEngine': 'css'
    });

    var stream = shoe('/dnode');

    var d = dnode({
        'newPost': function (post) {
            displayNewPost(post);
        },
        'newEvent': function (event) {
            displayNewEvent(event);
        }
    });
    d.on('remote', function (remote) {
        remote.getPosts(0, 10, function (err, posts) {
            if (err) {
                console.error(err);
                return;
            }

            displayOldPosts(posts);
        });

        $('#load-posts').click(function (event) {
            loadMorePosts(remote);
        }).show();

        $(window).scroll(function (event) {
            // Two screens before the end we start loading more posts
            if (document.body.scrollHeight - $(this).scrollTop() <= 3 * $(this).height()) {
                // Make sure initial posts have been already loaded
                if (postsCount > 0) {
                    loadMorePosts(remote);
                }
            }
        });
    }).on('end', function () {
        // TODO: Handle better?
        alert("Connection to the server failed. Please reload to continue with real-time updates.");
    }).pipe(stream).pipe(d);
});
<commit_msg>Parse timestamps when sorting posts so that timezone information is used, too.<commit_after>var dnode = require('dnode');
var shoe = require('shoe');
var swig = require('swig/lib/swig');

var templates = {
    'twitter': require('./templates/posts/twitter.html'),
    'facebook': require('./templates/posts/facebook.html')
};

var $ = require('jquery-browserify');

var FACEBOOK_POST_REGEXP = /(\d+)_(\d+)/;
var DOTS = /\.\.\.$/;

var postsCount = 0;
var displayedPosts = {};

function createPost(post) {
    switch (post.type) {
        case 'twitter':
            return $(templates.twitter({
                'post': post
            })).data('foreign_timestamp', post.foreign_timestamp);
        case 'facebook':
            var post_id = null;
            var post_link = null;
            var post_match = FACEBOOK_POST_REGEXP.exec(post.data.id);
            if (post_match) {
                post_id = post_match[2];
                post_link = 'https://www.facebook.com/' + post_match[1] + '/posts/' + post_match[2];
            }
            else {
                console.warning("Facebook post does not have a link and ID: %s", post.foreign_id, post);
            }

            // Override with a better version
            if (post.data.actions && post.data.actions.length > 0 && post.data.actions[0].link) {
                post_link = post.data.actions[0].link.split('http://').join('https://');
            }

            if (post.data.actions) {
                $.each(post.data.actions, function (i, action) {
                    post.data.actions[action.name.toLowerCase()] = action;
                });
            }

            var event_in_past = false;
            if (post.facebook_event && post.facebook_event.start_time) {
                if (new Date(post.facebook_event.start_time) < new Date()) {
                    event_in_past = true;
                }
            }

            return $(templates.facebook({
                'post': post,
                'post_link': post_link,
                'post_id': post_id,
                'event_in_past': event_in_past
            })).data('foreign_timestamp', post.foreign_timestamp);
        default:
            console.error("Unknown post type: %s", post.type, post);
            return null;
    }
}

function renderTweets() {
    if (typeof twttr === 'undefined') {
        alert("Not all necessary scripts have loaded. Are you using ad-block or something similar?");
        return;
    }

    twttr.widgets.load();
}

function postsRelayout() {
    $('#posts').isotope('reLayout');
}

function shortenPosts() {
    $('#posts .short').dotdotdot({
        'callback': function(isTruncated, orgContent) {
            var t = $(this);
            t.removeClass('short');
            if (isTruncated) {
                var link = $('').addClass('see-more');
                if (DOTS.test($.trim(t.text()))) {
                    link.append($('
'));
                }
                link.append(
                    $('').text("See More").click(function (event) {
                        t.trigger('destroy').html(orgContent);
                        postsRelayout();
                    })
                );
                t.append(link);
                postsRelayout();
            }
        }
    });
}

function displayNewPost(post) {
    if (displayedPosts[post.type + '-' + post.foreign_id]) {
        return;
    }
    displayedPosts[post.type + '-' + post.foreign_id] = true;
    postsCount++;

    var postElement = createPost(post);
    if (postElement) {
        $('#posts').isotope('insert', postElement, function () {
            renderTweets();
            shortenPosts();

            // Twitter and Facebook posts can resize after loading
            // because images and other media can be loaded, so we
            // wait a bit and relayout posts again
            // TODO: Should call this probably after all DOM manipulations and media has loaded - is there such an event?
            setTimeout(postsRelayout, 1000);
            setTimeout(postsRelayout, 5000);
            setTimeout(postsRelayout, 30000);
            setTimeout(postsRelayout, 60000);
        });
    }
}

function displayOldPosts(posts) {
    var postElements = $();
    $.each(posts, function (i, post) {
        if (displayedPosts[post.type + '-' + post.foreign_id]) {
            return;
        }
        displayedPosts[post.type + '-' + post.foreign_id] = true;
        postsCount++;

        postElements = postElements.add(createPost(post));
    });

    if (postElements.length > 0) {
        $('#posts').isotope('insert', postElements, function () {
            renderTweets();
            shortenPosts();

            // Twitter and Facebook posts can resize after loading
            // because images and other media can be loaded, so we
            // wait a bit and relayout posts again
            // TODO: Should call this probably after all DOM manipulations and media has loaded - is there such an event?
            setTimeout(postsRelayout, 1000);
            setTimeout(postsRelayout, 5000);
            setTimeout(postsRelayout, 30000);
            setTimeout(postsRelayout, 60000);
        });
    }
}

function loadMorePosts(remote) {
    // TODO: Fix comment
    // We can use a simple counter because we are not deleting any posts
    // Otherwise, if we would be deleting posts, simply counting could make us skip some posts
    remote.getPosts(postsCount, 10, function (err, posts) {
        if (err) {
            console.error(err);
            return;
        }

        displayOldPosts(posts);
    });
}

function displayNewEvent(event) {
    // TOOD: Implement
    console.log(event);
}

$(document).ready(function () {
    $('#posts').isotope({
        'itemSelector': '.post',
        'getSortData': {
            'foreign_timestamp': function (elem) {
                return Date.parse(elem.data('foreign_timestamp'));
            }
        },
        'sortBy': 'foreign_timestamp',
        'sortAscending': false,
        // We disable animations
        'transformsEnabled': false,
        'animationEngine': 'css'
    });

    var stream = shoe('/dnode');

    var d = dnode({
        'newPost': function (post) {
            displayNewPost(post);
        },
        'newEvent': function (event) {
            displayNewEvent(event);
        }
    });
    d.on('remote', function (remote) {
        remote.getPosts(0, 10, function (err, posts) {
            if (err) {
                console.error(err);
                return;
            }

            displayOldPosts(posts);
        });

        $('#load-posts').click(function (event) {
            loadMorePosts(remote);
        }).show();

        $(window).scroll(function (event) {
            // Two screens before the end we start loading more posts
            if (document.body.scrollHeight - $(this).scrollTop() <= 3 * $(this).height()) {
                // Make sure initial posts have been already loaded
                if (postsCount > 0) {
                    loadMorePosts(remote);
                }
            }
        });
    }).on('end', function () {
        // TODO: Handle better?
        alert("Connection to the server failed. Please reload to continue with real-time updates.");
    }).pipe(stream).pipe(d);
});
<|endoftext|>


<commit_before>/*
 * CODENVY CONFIDENTIAL
 * __________________
 *
 *  [2012] - [2013] Codenvy, S.A.
 *  All Rights Reserved.
 *
 * NOTICE:  All information contained herein is, and remains
 * the property of Codenvy S.A. and its suppliers,
 * if any.  The intellectual and technical concepts contained
 * herein are proprietary to Codenvy S.A.
 * and its suppliers and may be covered by U.S. and Foreign Patents,
 * patents in process, and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Codenvy S.A..
 */

define(["underscore","views/accountformbase","models/account"],

    function(_,AccountFormBase,Account){

        var ForgotPasswordForm = AccountFormBase.extend({
            __submit : function(){
                this.__showProgress();
                this.trigger("submitting");

                Account.recoverPassword(
                    this.$("input[name='email']").val(),
                    _.bind(function(d){
                        this.__showResultMessage();
                        this.trigger("success",d);
                    },this),
                    _.bind(function(errors){

                        this.__restoreForm();

                        if(errors.length > 0){
                            this.trigger(
                                "invalid",
                                errors[0].getFieldName(),
                                errors[0].getErrorDescription()
                            );
                        }
                    },this)
                );
            },

            __showResultMessage : function(){
				$(".forgotpassword-form").addClass("hide");
				$(".forgotpassword-result").removeClass("hide");
            }
        });

        return {
            get : function(form){
                if(typeof form === 'undefined'){
                    throw new Error("Need a form");
                }

                return new ForgotPasswordForm({ el : form });
            },

            ForgotPasswordForm : ForgotPasswordForm
        };

    }
);
<commit_msg>fix build<commit_after>/*
 * CODENVY CONFIDENTIAL
 * __________________
 *
 *  [2012] - [2013] Codenvy, S.A.
 *  All Rights Reserved.
 *
 * NOTICE:  All information contained herein is, and remains
 * the property of Codenvy S.A. and its suppliers,
 * if any.  The intellectual and technical concepts contained
 * herein are proprietary to Codenvy S.A.
 * and its suppliers and may be covered by U.S. and Foreign Patents,
 * patents in process, and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Codenvy S.A..
 */

define(["jquery","underscore","views/accountformbase","models/account"],

    function($,_,AccountFormBase,Account){

        var ForgotPasswordForm = AccountFormBase.extend({
            __submit : function(){
                this.__showProgress();
                this.trigger("submitting");

                Account.recoverPassword(
                    this.$("input[name='email']").val(),
                    _.bind(function(d){
                        this.__showResultMessage();
                        this.trigger("success",d);
                    },this),
                    _.bind(function(errors){

                        this.__restoreForm();

                        if(errors.length > 0){
                            this.trigger(
                                "invalid",
                                errors[0].getFieldName(),
                                errors[0].getErrorDescription()
                            );
                        }
                    },this)
                );
            },

            __showResultMessage : function(){
				$(".forgotpassword-form").addClass("hide");
				$(".forgotpassword-result").removeClass("hide");
            }
        });

        return {
            get : function(form){
                if(typeof form === 'undefined'){
                    throw new Error("Need a form");
                }

                return new ForgotPasswordForm({ el : form });
            },

            ForgotPasswordForm : ForgotPasswordForm
        };

    }
);
<|endoftext|>


<commit_before>/**
 * mediaPlayers is a collection of mediaPlayer objects supported by the client.
 *
 * @constructor
 */
( function( mw, $ ) { "use strict";

mw.MediaPlayers = function(){
	this.init();
};

mw.MediaPlayers.prototype = {
	// The list of players supported
	players : null,

	// Store per mime-type preferences for players
	preference : { },

	// Stores the default set of players for a given mime type
	defaultPlayers : { },

	/**
	 * Initialization function sets the default order for players for a given
	 * mime type
	 */
	init: function() {
		this.players = new Array();
		this.loadPreferences();

		// Set up default players order for each library type
		this.defaultPlayers['video/wvm'] = ['NativeComponent'];
		this.defaultPlayers['video/live'] = ['Kplayer'];
		this.defaultPlayers['video/kontiki'] = ['Kplayer'];
		this.defaultPlayers['video/x-flv'] = ['Kplayer', 'Vlc'];
		this.defaultPlayers['video/h264'] = ['NativeComponent', 'Native', 'Kplayer', 'Silverlight', 'Vlc'];
		this.defaultPlayers['video/mp4'] = ['NativeComponent', 'Native', 'Kplayer', 'Silverlight', 'Vlc'];
		this.defaultPlayers['application/vnd.apple.mpegurl'] = ['Native'];
		this.defaultPlayers['application/x-shockwave-flash'] = ['Kplayer'];

		this.defaultPlayers['video/ogg'] = ['Native', 'Vlc', 'Java', 'Generic'];
		this.defaultPlayers['video/webm'] = ['Native', 'Vlc'];
		this.defaultPlayers['application/ogg'] = ['Native', 'Vlc', 'Java', 'Generic'];
		this.defaultPlayers['audio/ogg'] = ['Native', 'Vlc', 'Java' ];
		this.defaultPlayers['audio/mpeg']= ['Native', 'Kplayer'];
		this.defaultPlayers['audio/mp3']= ['Native', 'Kplayer'];
		this.defaultPlayers['video/mpeg'] = ['Vlc'];
		this.defaultPlayers['video/x-msvideo'] = ['Vlc'];
		this.defaultPlayers['video/multicast'] = ['Silverlight'];
		this.defaultPlayers['video/ism'] = ['Silverlight'];
		this.defaultPlayers['video/playreadySmooth'] = ['Silverlight'];
		// this.defaultPlayers['text/html'] = ['Html'];
		//this.defaultPlayers['image/svg'] = ['ImageOverlay'];

		this.defaultPlayers['image/jpeg'] = ['ImageOverlay'];
		this.defaultPlayers['image/png'] = ['ImageOverlay'];
		if ( mw.getConfig("LeadWithHLSOnFlash") ) {
			this.defaultPlayers['application/vnd.apple.mpegurl'].push('Kplayer');
		}
		// If nativeComponent can play dash, use it.
        if ($.inArray('application/dash+xml',  window.kNativeSdk && window.kNativeSdk.allFormats) >= 0) {
            this.defaultPlayers['application/dash+xml'] = ['NativeComponent'];
        }

		// If nativeComponent can play hls, use it.
		if (window.kNativeSdk && window.kNativeSdk.allFormats) {
			if ( $.inArray( 'application/vnd.apple.mpegurl' , window.kNativeSdk && window.kNativeSdk.allFormats ) >= 0 ) {
				this.defaultPlayers['application/vnd.apple.mpegurl'] = ['NativeComponent'];
			}
		} else {
			//backward compatibility for sdk that don't send the allFormats param
			this.defaultPlayers['application/vnd.apple.mpegurl'] = ['NativeComponent','Native'];
		}
	},

	/**
	 * Adds a Player to the player list
	 *
	 * @param {Object}
	 *	  player Player object to be added
	 */
	addPlayer: function( player ) {
		for ( var i = 0; i < this.players.length; i++ ) {
			if ( this.players[i].id == player.id ) {
				// Player already found
				return ;
			}
		}
		// Add the player:
		this.players.push( player );
	},

	/**
	 * Checks if a player is supported by id
	 */
	isSupportedPlayer: function( playerId ){
		for( var i=0; i < this.players.length; i++ ){
			if( this.players[i].id == playerId ){
				return true;
			}
		}
		return false;
	},
	getPlayerById: function(playerId){
		for( var i=0; i < this.players.length; i++ ){
			if( this.players[i].id.toLowerCase() == playerId.toLowerCase() ){
				return this.players[i];
			}
		}
		return null;
	},
	/**
	 * get players that support a given mimeType
	 *
	 * @param {String}
	 *	  mimeType Mime type of player set
	 * @return {Array} Array of players that support a the requested mime type
	 */
	getMIMETypePlayers: function( mimeType ) {
		var mimePlayers = new Array();
		var _this = this;
		if ( this.defaultPlayers[mimeType] ) {
			$.each( this.defaultPlayers[ mimeType ], function( d, lib ) {
				var library = _this.defaultPlayers[ mimeType ][ d ];
				for ( var i = 0; i < _this.players.length; i++ ) {
					if ( _this.players[i].library == library && _this.players[i].supportsMIMEType( mimeType ) ) {
						mimePlayers.push( _this.players[i] );
					}
				}
			} );
		}
		return mimePlayers;
	},
	/**
	 * Deprecated method call lacked get prefix for getter.
	 */
	defaultPlayer: function( mimeType ){
		mw.log( "MediaPlayer:: defaultPlayer has been deprecated, use getDefaultPlayer method instead" );
		return getDefaultPlayer( mimeType );
	},
	/**
	 * Default player for a given mime type
	 *
	 * @param {String}
	 *	  mimeType Mime type of the requested player
	 * @return Player for mime type null if no player found
	 */
	getDefaultPlayer : function( mimeType ) {
		// mw.log( "get defaultPlayer for " + mimeType );
		var mimePlayers = this.getMIMETypePlayers( mimeType );
		if (mw.getConfig( 'chromecastReceiver')) {
			return this.getPlayerById('chromecastReceiver');
		}
		if ( mw.getConfig( 'EmbedPlayer.ForceNativeComponent' ) && this.isSupportedPlayer( 'nativeComponentPlayer' )) {
			var nativeComponentPlayer = mw.EmbedTypes.getNativeComponentPlayerVideo();
			var imageOverlayPlayer = mw.EmbedTypes.getNativeImageOverlayPlayer();
			if (this.isPlayerSupportMimeType(mimePlayers, nativeComponentPlayer)) {
				mimePlayers = [nativeComponentPlayer];
			} else if(imageOverlayPlayer.supportsMIMEType(mimeType) ) {
				mimePlayers = [imageOverlayPlayer];
			} else {
				mimePlayers = [];
			}
		}
		if ( ( mw.getConfig( 'EmbedPlayer.ForceKPlayer' ) ||
			( mw.getConfig( 'ForceFlashOnDesktopSafari') && mw.isDesktopSafari() ) ) &&
			this.isSupportedPlayer( 'kplayer' ) && mimeType !== "video/youtube" ) {
			var kplayer = mw.EmbedTypes.getKplayer();
			if (this.isPlayerSupportMimeType(mimePlayers, kplayer)) {
				mimePlayers = [kplayer];
			} else {
				mimePlayers = [];
			}
		}
		if (mw.getConfig( 'EmbedPlayer.ForceSPlayer') && this.isSupportedPlayer('splayer')) {
			var silverlightPlayer = mw.EmbedTypes.getSilverlightPlayer();
			if (this.isPlayerSupportMimeType(mimePlayers, silverlightPlayer)) {
				mimePlayers = [silverlightPlayer];
			} else {
				mimePlayers = [];
			}
		}

		// Check for prior preference for this mime type
		for ( var i = 0; i < mimePlayers.length; i++ ) {
			if ( mimePlayers[i].id == this.preference[mimeType] ){
				mimePlayers = [mimePlayers[i]];
				break;
			}
		}
		// Otherwise just return the first compatible player
		// (it will be chosen according to the defaultPlayers list
		if( mimePlayers[0] ){
			return mimePlayers[0];
		}
		// mw.log( 'No default player found for ' + mimeType );
		return null;
	},
	isPlayerSupportMimeType: function(mimePlayers, player){
		var playerSupported = mimePlayers.filter(function(mimePlayer){
			return mimePlayer.id === player.id;
		});
		return (playerSupported.length > 0);
	},
	/**
	 * Returns only a native video tag player
	 * @param {String}
	 * 	mimeType for player selection criteria
	 */
	getNativePlayer: function( mimeType ){
		var mimePlayers = this.getMIMETypePlayers( mimeType );
		for ( var i = 0; i < mimePlayers.length; i++ ) {
			if( mimePlayers[i].library == 'Native' ){
				return mimePlayers[i];
			}
		}
		return null;
	},

	/**
	 * Sets the format preference.
	 *
	 * @param {String}
	 *	  mimeFormat Prefered format
	 */
	setFormatPreference : function ( mimeFormat ) {
		 this.preference['formatPreference'] = mimeFormat;
		 $.cookie( 'EmbedPlayer.Preference', JSON.stringify( this.preference) );
	},

	/**
	 * Loads the user preference settings from a cookie
	 */
	loadPreferences : function ( ) {
		this.preference = { };
		// See if we have a cookie set to a clientSupported type:
		if( $.cookie( 'EmbedPlayer.Preference' ) ) {
			this.preference = JSON.parse( $.cookie( 'EmbedPlayer.Preference' ) );
		}
	},

	/**
	 * Sets the player preference
	 *
	 * @param {String}
	 *	  playerId Prefered player id
	 * @param {String}
	 *	  mimeType Mime type for the associated player stream
	 */
	setPlayerPreference : function( playerId, mimeType ) {
		var selectedPlayer = null;
		for ( var i = 0; i < this.players.length; i++ ) {
			if ( this.players[i].id == playerId ) {
				selectedPlayer = this.players[i];
				mw.log( 'EmbedPlayer::setPlayerPreference: choosing ' + playerId + ' for ' + mimeType );
				this.preference[ mimeType ] = playerId;
				$.cookie( 'EmbedPlayer.Preference', JSON.stringify( this.preference ) );
				break;
			}
		}
		// Update All the player instances on the page
		if ( selectedPlayer ) {
			$('.mwEmbedPlayer').each(function(inx, playerTarget ){
				var embedPlayer = $( playerTarget ).get( 0 );
				if ( embedPlayer.mediaElement.selectedSource
						&& ( embedPlayer.mediaElement.selectedSource.mimeType == mimeType ) )
				{
					embedPlayer.selectPlayer( selectedPlayer );
				}
			});
		}
	}
};

} )( mediaWiki, jQuery );
<commit_msg> push native componenet if needed<commit_after>/**
 * mediaPlayers is a collection of mediaPlayer objects supported by the client.
 *
 * @constructor
 */
( function( mw, $ ) { "use strict";

mw.MediaPlayers = function(){
	this.init();
};

mw.MediaPlayers.prototype = {
	// The list of players supported
	players : null,

	// Store per mime-type preferences for players
	preference : { },

	// Stores the default set of players for a given mime type
	defaultPlayers : { },

	/**
	 * Initialization function sets the default order for players for a given
	 * mime type
	 */
	init: function() {
		this.players = new Array();
		this.loadPreferences();

		// Set up default players order for each library type
		this.defaultPlayers['video/wvm'] = ['NativeComponent'];
		this.defaultPlayers['video/live'] = ['Kplayer'];
		this.defaultPlayers['video/kontiki'] = ['Kplayer'];
		this.defaultPlayers['video/x-flv'] = ['Kplayer', 'Vlc'];
		this.defaultPlayers['video/h264'] = ['NativeComponent', 'Native', 'Kplayer', 'Silverlight', 'Vlc'];
		this.defaultPlayers['video/mp4'] = ['NativeComponent', 'Native', 'Kplayer', 'Silverlight', 'Vlc'];
		this.defaultPlayers['application/vnd.apple.mpegurl'] = ['Native'];
		this.defaultPlayers['application/x-shockwave-flash'] = ['Kplayer'];

		this.defaultPlayers['video/ogg'] = ['Native', 'Vlc', 'Java', 'Generic'];
		this.defaultPlayers['video/webm'] = ['Native', 'Vlc'];
		this.defaultPlayers['application/ogg'] = ['Native', 'Vlc', 'Java', 'Generic'];
		this.defaultPlayers['audio/ogg'] = ['Native', 'Vlc', 'Java' ];
		this.defaultPlayers['audio/mpeg']= ['Native', 'Kplayer'];
		this.defaultPlayers['audio/mp3']= ['Native', 'Kplayer'];
		this.defaultPlayers['video/mpeg'] = ['Vlc'];
		this.defaultPlayers['video/x-msvideo'] = ['Vlc'];
		this.defaultPlayers['video/multicast'] = ['Silverlight'];
		this.defaultPlayers['video/ism'] = ['Silverlight'];
		this.defaultPlayers['video/playreadySmooth'] = ['Silverlight'];
		// this.defaultPlayers['text/html'] = ['Html'];
		//this.defaultPlayers['image/svg'] = ['ImageOverlay'];

		this.defaultPlayers['image/jpeg'] = ['ImageOverlay'];
		this.defaultPlayers['image/png'] = ['ImageOverlay'];
		if ( mw.getConfig("LeadWithHLSOnFlash") ) {
			this.defaultPlayers['application/vnd.apple.mpegurl'].push('Kplayer');
		}
		// If nativeComponent can play dash, use it.
        if ($.inArray('application/dash+xml',  window.kNativeSdk && window.kNativeSdk.allFormats) >= 0) {
            this.defaultPlayers['application/dash+xml'] = ['NativeComponent'];
        }

		// If nativeComponent can play hls, use it.
		if (window.kNativeSdk && window.kNativeSdk.allFormats) {
			if ( $.inArray( 'application/vnd.apple.mpegurl' , window.kNativeSdk && window.kNativeSdk.allFormats ) >= 0 ) {
				this.defaultPlayers['application/vnd.apple.mpegurl'] = ['NativeComponent'];
			}
		} else {
			//backward compatibility for sdk that don't send the allFormats param
			this.defaultPlayers['application/vnd.apple.mpegurl'].push('NativeComponent');
		}
	},

	/**
	 * Adds a Player to the player list
	 *
	 * @param {Object}
	 *	  player Player object to be added
	 */
	addPlayer: function( player ) {
		for ( var i = 0; i < this.players.length; i++ ) {
			if ( this.players[i].id == player.id ) {
				// Player already found
				return ;
			}
		}
		// Add the player:
		this.players.push( player );
	},

	/**
	 * Checks if a player is supported by id
	 */
	isSupportedPlayer: function( playerId ){
		for( var i=0; i < this.players.length; i++ ){
			if( this.players[i].id == playerId ){
				return true;
			}
		}
		return false;
	},
	getPlayerById: function(playerId){
		for( var i=0; i < this.players.length; i++ ){
			if( this.players[i].id.toLowerCase() == playerId.toLowerCase() ){
				return this.players[i];
			}
		}
		return null;
	},
	/**
	 * get players that support a given mimeType
	 *
	 * @param {String}
	 *	  mimeType Mime type of player set
	 * @return {Array} Array of players that support a the requested mime type
	 */
	getMIMETypePlayers: function( mimeType ) {
		var mimePlayers = new Array();
		var _this = this;
		if ( this.defaultPlayers[mimeType] ) {
			$.each( this.defaultPlayers[ mimeType ], function( d, lib ) {
				var library = _this.defaultPlayers[ mimeType ][ d ];
				for ( var i = 0; i < _this.players.length; i++ ) {
					if ( _this.players[i].library == library && _this.players[i].supportsMIMEType( mimeType ) ) {
						mimePlayers.push( _this.players[i] );
					}
				}
			} );
		}
		return mimePlayers;
	},
	/**
	 * Deprecated method call lacked get prefix for getter.
	 */
	defaultPlayer: function( mimeType ){
		mw.log( "MediaPlayer:: defaultPlayer has been deprecated, use getDefaultPlayer method instead" );
		return getDefaultPlayer( mimeType );
	},
	/**
	 * Default player for a given mime type
	 *
	 * @param {String}
	 *	  mimeType Mime type of the requested player
	 * @return Player for mime type null if no player found
	 */
	getDefaultPlayer : function( mimeType ) {
		// mw.log( "get defaultPlayer for " + mimeType );
		var mimePlayers = this.getMIMETypePlayers( mimeType );
		if (mw.getConfig( 'chromecastReceiver')) {
			return this.getPlayerById('chromecastReceiver');
		}
		if ( mw.getConfig( 'EmbedPlayer.ForceNativeComponent' ) && this.isSupportedPlayer( 'nativeComponentPlayer' )) {
			var nativeComponentPlayer = mw.EmbedTypes.getNativeComponentPlayerVideo();
			var imageOverlayPlayer = mw.EmbedTypes.getNativeImageOverlayPlayer();
			if (this.isPlayerSupportMimeType(mimePlayers, nativeComponentPlayer)) {
				mimePlayers = [nativeComponentPlayer];
			} else if(imageOverlayPlayer.supportsMIMEType(mimeType) ) {
				mimePlayers = [imageOverlayPlayer];
			} else {
				mimePlayers = [];
			}
		}
		if ( ( mw.getConfig( 'EmbedPlayer.ForceKPlayer' ) ||
			( mw.getConfig( 'ForceFlashOnDesktopSafari') && mw.isDesktopSafari() ) ) &&
			this.isSupportedPlayer( 'kplayer' ) && mimeType !== "video/youtube" ) {
			var kplayer = mw.EmbedTypes.getKplayer();
			if (this.isPlayerSupportMimeType(mimePlayers, kplayer)) {
				mimePlayers = [kplayer];
			} else {
				mimePlayers = [];
			}
		}
		if (mw.getConfig( 'EmbedPlayer.ForceSPlayer') && this.isSupportedPlayer('splayer')) {
			var silverlightPlayer = mw.EmbedTypes.getSilverlightPlayer();
			if (this.isPlayerSupportMimeType(mimePlayers, silverlightPlayer)) {
				mimePlayers = [silverlightPlayer];
			} else {
				mimePlayers = [];
			}
		}

		// Check for prior preference for this mime type
		for ( var i = 0; i < mimePlayers.length; i++ ) {
			if ( mimePlayers[i].id == this.preference[mimeType] ){
				mimePlayers = [mimePlayers[i]];
				break;
			}
		}
		// Otherwise just return the first compatible player
		// (it will be chosen according to the defaultPlayers list
		if( mimePlayers[0] ){
			return mimePlayers[0];
		}
		// mw.log( 'No default player found for ' + mimeType );
		return null;
	},
	isPlayerSupportMimeType: function(mimePlayers, player){
		var playerSupported = mimePlayers.filter(function(mimePlayer){
			return mimePlayer.id === player.id;
		});
		return (playerSupported.length > 0);
	},
	/**
	 * Returns only a native video tag player
	 * @param {String}
	 * 	mimeType for player selection criteria
	 */
	getNativePlayer: function( mimeType ){
		var mimePlayers = this.getMIMETypePlayers( mimeType );
		for ( var i = 0; i < mimePlayers.length; i++ ) {
			if( mimePlayers[i].library == 'Native' ){
				return mimePlayers[i];
			}
		}
		return null;
	},

	/**
	 * Sets the format preference.
	 *
	 * @param {String}
	 *	  mimeFormat Prefered format
	 */
	setFormatPreference : function ( mimeFormat ) {
		 this.preference['formatPreference'] = mimeFormat;
		 $.cookie( 'EmbedPlayer.Preference', JSON.stringify( this.preference) );
	},

	/**
	 * Loads the user preference settings from a cookie
	 */
	loadPreferences : function ( ) {
		this.preference = { };
		// See if we have a cookie set to a clientSupported type:
		if( $.cookie( 'EmbedPlayer.Preference' ) ) {
			this.preference = JSON.parse( $.cookie( 'EmbedPlayer.Preference' ) );
		}
	},

	/**
	 * Sets the player preference
	 *
	 * @param {String}
	 *	  playerId Prefered player id
	 * @param {String}
	 *	  mimeType Mime type for the associated player stream
	 */
	setPlayerPreference : function( playerId, mimeType ) {
		var selectedPlayer = null;
		for ( var i = 0; i < this.players.length; i++ ) {
			if ( this.players[i].id == playerId ) {
				selectedPlayer = this.players[i];
				mw.log( 'EmbedPlayer::setPlayerPreference: choosing ' + playerId + ' for ' + mimeType );
				this.preference[ mimeType ] = playerId;
				$.cookie( 'EmbedPlayer.Preference', JSON.stringify( this.preference ) );
				break;
			}
		}
		// Update All the player instances on the page
		if ( selectedPlayer ) {
			$('.mwEmbedPlayer').each(function(inx, playerTarget ){
				var embedPlayer = $( playerTarget ).get( 0 );
				if ( embedPlayer.mediaElement.selectedSource
						&& ( embedPlayer.mediaElement.selectedSource.mimeType == mimeType ) )
				{
					embedPlayer.selectPlayer( selectedPlayer );
				}
			});
		}
	}
};

} )( mediaWiki, jQuery );
<|endoftext|>


<commit_before>var url = require('url');
var path = require('path');
var fs = require('fs');
var http = require('http');
var socksClient = require('socks-client')
var socks = require('socksv5')

var ca_file = process.env.ETCDCTL_CA_FILE || false;
var key_file = process.env.ETCDCTL_KEY_FILE || false;
var cert_file = process.env.ETCDCTL_CERT_FILE || false;
var proxy_host = process.env.PROXY_HOST || '127.0.0.1';
var proxy_port = process.env.PROXY_PORT || '4000';

var requester = http.request;
if(cert_file) {
  // use https requests if theres a cert file
  var https = require('https');
  requester = https.request;

  if(!fs.existsSync(cert_file)) {
    console.error('CERT FILE', cert_file, 'not found!');
    process.exit(1);
  }
  if(!fs.existsSync(key_file)) {
    console.error('KEY FILE', key_file, 'not found!');
    process.exit(1);
  }
  if(!fs.existsSync(ca_file)) {
    console.error('CA FILE', ca_file, 'not found!');
    process.exit(1);
  }
}

var etcdHost = process.env.ETCD_HOST || '172.17.42.1';
var etcdPort = process.env.ETCD_PORT || 4001;
var serverPort = process.env.SERVER_PORT || 8100;
var publicDir = 'frontend';
var authUser = process.env.AUTH_USER;
var authPass = process.env.AUTH_PASS;

var mimeTypes = {
  "html": "text/html",
  "jpeg": "image/jpeg",
  "jpg": "image/jpeg",
  "png": "image/png",
  "js": "text/javascript",
  "css": "text/css"
};

http.createServer(function serverFile(req, res) {
  // authenticaton
  if(!auth(req, res)) {
    res.statusCode = 401;
    res.setHeader('WWW-Authenticate', 'Basic realm="MyRealmName"');
    res.end('Unauthorized');
    return;
  }

  if(req.url === '/'){
    req.url = '/index.html';
  } else if(req.url.substr(0, 3) === '/v2') {
    // avoid fileExists for /v2 routes
    return proxy(req, res);
  }
  var uri = url.parse(req.url).pathname;
  var filename = path.join(process.cwd(), publicDir, uri);

  fs.exists(filename, function(exists) {
    // proxy if file does not exist
    if(!exists) return proxy(req, res);

    // serve static file if exists
    res.writeHead(200, mimeTypes[path.extname(filename).split(".")[1]]);
    fs.createReadStream(filename).pipe(res);
  });
}).listen(serverPort, function() {
  console.log('proxy /api requests to etcd on ' + etcdHost + ':' + etcdPort);
  console.log('etc-browser listening on port ' + serverPort);
});

function proxy(client_req, client_res) {
  var opts = {
    hostname: etcdHost,
    port: etcdPort,
    path: client_req.url,
    method: client_req.method
  };
  // https/certs supprt
  if(cert_file) {
    opts.key = fs.readFileSync(key_file);
    opts.ca = fs.readFileSync(ca_file);
    opts.cert = fs.readFileSync(cert_file);

    if (proxy_host != undefined &&proxy_port != undefined){
      var socksConfig = {
        proxyHost: proxy_host,
        proxyPort: proxy_port,
        auths: [ socks.auth.None() ]
      };
      opts.agent = new socks.HttpsAgent(socksConfig)
    }
  }
  client_req.pipe(requester(opts, function(res) {
    // if etcd returns that the requested  page  has been moved
    // to a different location, indicates that the node we are
    // querying is not the leader. This will redo the request
    // on the leader which is reported by the Location header
    if (res.statusCode === 307) {
        opts.hostname = url.parse(res.headers['location']).hostname;
        client_req.pipe(requester(opts, function(res) {
            console.log('Got response: ' + res.statusCode);
            res.pipe(client_res, {end: true});
        }, {end: true}));
    } else {
        res.pipe(client_res, {end: true});
    }
  }, {end: true}));
}

function auth(req, res) {
  if(!authUser) return true;

  var auth = req.headers.authorization;
  if(!auth) return false;

  // malformed
  var parts = auth.split(' ');
  if('basic' != parts[0].toLowerCase()) return false;
  if(!parts[1]) return false;
  auth = parts[1];

  // credentials
  auth = new Buffer(auth, 'base64').toString();
  auth = auth.match(/^([^:]*):(.*)$/);
  if(!auth) return false;

  return (auth[1] === authUser && auth[2] === authPass)
}
<commit_msg>fix proxy host<commit_after>var url = require('url');
var path = require('path');
var fs = require('fs');
var http = require('http');
var socksClient = require('socks-client')
var socks = require('socksv5')

var ca_file = process.env.ETCDCTL_CA_FILE || false;
var key_file = process.env.ETCDCTL_KEY_FILE || false;
var cert_file = process.env.ETCDCTL_CERT_FILE || false;
var proxy_host = process.env.PROXY_HOST;
var proxy_port = process.env.PROXY_PORT;

var requester = http.request;
if(cert_file) {
  // use https requests if theres a cert file
  var https = require('https');
  requester = https.request;

  if(!fs.existsSync(cert_file)) {
    console.error('CERT FILE', cert_file, 'not found!');
    process.exit(1);
  }
  if(!fs.existsSync(key_file)) {
    console.error('KEY FILE', key_file, 'not found!');
    process.exit(1);
  }
  if(!fs.existsSync(ca_file)) {
    console.error('CA FILE', ca_file, 'not found!');
    process.exit(1);
  }
}

var etcdHost = process.env.ETCD_HOST || '172.17.42.1';
var etcdPort = process.env.ETCD_PORT || 4001;
var serverPort = process.env.SERVER_PORT || 8100;
var publicDir = 'frontend';
var authUser = process.env.AUTH_USER;
var authPass = process.env.AUTH_PASS;

var mimeTypes = {
  "html": "text/html",
  "jpeg": "image/jpeg",
  "jpg": "image/jpeg",
  "png": "image/png",
  "js": "text/javascript",
  "css": "text/css"
};

http.createServer(function serverFile(req, res) {
  // authenticaton
  if(!auth(req, res)) {
    res.statusCode = 401;
    res.setHeader('WWW-Authenticate', 'Basic realm="MyRealmName"');
    res.end('Unauthorized');
    return;
  }

  if(req.url === '/'){
    req.url = '/index.html';
  } else if(req.url.substr(0, 3) === '/v2') {
    // avoid fileExists for /v2 routes
    return proxy(req, res);
  }
  var uri = url.parse(req.url).pathname;
  var filename = path.join(process.cwd(), publicDir, uri);

  fs.exists(filename, function(exists) {
    // proxy if file does not exist
    if(!exists) return proxy(req, res);

    // serve static file if exists
    res.writeHead(200, mimeTypes[path.extname(filename).split(".")[1]]);
    fs.createReadStream(filename).pipe(res);
  });
}).listen(serverPort, function() {
  console.log('proxy /api requests to etcd on ' + etcdHost + ':' + etcdPort);
  console.log('etc-browser listening on port ' + serverPort);
});

function proxy(client_req, client_res) {
  var opts = {
    hostname: etcdHost,
    port: etcdPort,
    path: client_req.url,
    method: client_req.method
  };
  // https/certs supprt
  if(cert_file) {
    opts.key = fs.readFileSync(key_file);
    opts.ca = fs.readFileSync(ca_file);
    opts.cert = fs.readFileSync(cert_file);

    if (proxy_host != undefined &&proxy_port != undefined){
      var socksConfig = {
        proxyHost: proxy_host,
        proxyPort: proxy_port,
        auths: [ socks.auth.None() ]
      };
      opts.agent = new socks.HttpsAgent(socksConfig)
    }
  }
  client_req.pipe(requester(opts, function(res) {
    // if etcd returns that the requested  page  has been moved
    // to a different location, indicates that the node we are
    // querying is not the leader. This will redo the request
    // on the leader which is reported by the Location header
    if (res.statusCode === 307) {
        opts.hostname = url.parse(res.headers['location']).hostname;
        client_req.pipe(requester(opts, function(res) {
            console.log('Got response: ' + res.statusCode);
            res.pipe(client_res, {end: true});
        }, {end: true}));
    } else {
        res.pipe(client_res, {end: true});
    }
  }, {end: true}));
}

function auth(req, res) {
  if(!authUser) return true;

  var auth = req.headers.authorization;
  if(!auth) return false;

  // malformed
  var parts = auth.split(' ');
  if('basic' != parts[0].toLowerCase()) return false;
  if(!parts[1]) return false;
  auth = parts[1];

  // credentials
  auth = new Buffer(auth, 'base64').toString();
  auth = auth.match(/^([^:]*):(.*)$/);
  if(!auth) return false;

  return (auth[1] === authUser && auth[2] === authPass)
}
<|endoftext|>


<commit_before>App.plugin('zendesk', (function () {
    var init = function (params, callback) {
        if (window.location.hostname.indexOf('.zendesk.com') === -1) {
            // return true as response if plugin should be activated
            return callback(null, false);
        }

        Settings.get('settings', {}, function (settings) {
            if (settings.suggestions && settings.suggestions.enabled === false) {
                return callback(null, false);
            }

            // here we're making sure that we have the current user as a client and we're not sending requests for now reason.
            chrome.runtime.sendMessage({
                'request': 'suggestion-enabled',
                'data': {
                    'domain': window.location.hostname
                }
            }, function(enabled){
                callback(null, enabled);

                if (enabled) {
                    injectScript();
                    load();
                }
            })
        });
    };

    // inject the zendesk script into the dom - this is done for interacting with the macro insertion
    var injectScript = function () {
        var script = document.createElement('script');
        script.type = "text/javascript";
        script.src = chrome.extension.getURL("pages/helpdesk/zendesk.js");
        if (document.body) {
            document.body.appendChild(script);
            script.onload = function () {
                document.body.removeChild(script);
            };
        }
    };

    var bindOnce = function () {
        // forward the message of usage to the bg script (for stats)
        window.addEventListener('message', function (event) {
            if (event.data && event.data.request && event.data.request === 'macro-used') {
                chrome.runtime.sendMessage({
                    'request': 'suggestion-used',
                    'data': {
                        'agent': {
                            'host': window.location.host,
                            'name': $('#face_box .name').text()
                        },
                        'url': window.location.href,
                        'template_id': event.data.template_id
                    }
                });

                var score = 0;
                if (event.data.score) {
                    score = event.data.score;
                }

                chrome.runtime.sendMessage({
                    'request': 'track',
                    'event': 'Used Macro',
                    'data': {
                        'is_suggested': score > 0,
                        'helpdesk_host': window.location.hostname,
                        'score': score
                    }
                });
            }
        });
    };

    var load = function () {
        // continuously check if our URL has changed and load the data accordingly

        //bind events only once here
        bindOnce();
        var ticketUrl = "";
        var ticketCheck = function () {
            if (window.location.pathname.indexOf('/agent/tickets/') === -1) {
                // reset the ticket url if we're not inside a ticket anymore
                ticketUrl = "";
                return;
            }
            // don't fetch for the same ticket
            if (ticketUrl === window.location.pathname) {
                return;
            }
            ticketUrl = window.location.pathname;

            $('.macro-suggestions-container').remove();

            loadEmail();
            loadMacroWidget();
        };
        setInterval(ticketCheck, 300);
    };

    // add tooltip to the email link
    var loadEmail = function () {
        var emailCheck = function() {
            var emailLink = $('a.email');
            if (emailLink.length) {
                emailLink.
                    attr('title', "Copy email shortcut: CTRL+SHIFT+C").
                    attr('data-toggle', "tooltip").
                    attr('data-html', "true").
                    attr('data-placement', "bottom");
                clearInterval(emailInterval);
            }
        };
        var emailInterval = setInterval(emailCheck, 1000);
    };

    // Populate our macro widget
    var loadMacroWidget = function () {
        // make sure we have the content loaded before inserting stuff
        var bodyCheck = function () {

            var subject = '';
            var body = '';

            var currentWorkspace = null;
            var isAgent = false;
            $('.workspace').each(function (_, workspace) {
                workspace = $(workspace);

                if (workspace.css('display') !== 'none') {
                    subject = workspace.find('input[name=subject]').val();
                    if (!subject.length){
                        return;
                    }

                    currentWorkspace = workspace;
                    var firstEvent = workspace.find('.event-container .event.is-public:first');

                    isAgent = firstEvent.find('.user_photo').hasClass('agent');
                    body = firstEvent.find('.zd-comment').text();
                }
            });

            if (!currentWorkspace) {
                return;
            }

            clearInterval(bodyInterval);

            if (!isAgent && !subject || !subject.length || !body.length) {
                return;
            }

            // query our servers for suggestions
            chrome.runtime.sendMessage({
                'request': 'suggestion',
                'data': {
                    'agent': {
                        'host': window.location.host,
                        'name': $('#face_box .name').text()
                    },
                    'url': window.location.href,
                    'subject': subject,
                    'to': '',
                    'cc': '',
                    'bcc': '',
                    'from': '',
                    'body': body,
                    'helpdesk': 'zendesk'
                }
            }, function (suggestedMacros) {
                if (!_.size(suggestedMacros)) {
                    return;
                }

                var macroContainer = $('
');
                $.each(suggestedMacros, function (macroIndex, macro) {
                    if (macroIndex > 2) { // show only 3 macros
                        return false;
                    }

                    var macroBtn = $("");
                    var macroTitle = $("");

                    macroBtn.attr('onclick', "gorgiasApplyMacro(" + macro.external_id + ")");
                    macroBtn.attr('macro-id', macro.external_id);

                    var title = macro.body.replace(/\n/g, "
");
                    macroBtn.attr('title', title);
                    macroBtn.attr('data-toggle', "tooltip");
                    macroBtn.attr('data-html', "true");
                    macroBtn.attr('data-placement', "bottom");
                    macroBtn.on('mouseenter', function () {
                        // remove others
                        $('.macro-list-item').removeClass('zd-item-focus');
                        $(this).parent().addClass('zd-item-focus');
                    });

                    macroTitle.html(macro.title);
                    macroBtn.append(macroTitle);

                    macroContainer.append(macroBtn);
                });

                var before = currentWorkspace.find('.comment_input .content .options');
                if (before.length) {
                    before.before(macroContainer);
                } else {
                    currentWorkspace.find('.comment_input .content .editor').after('
').after(macroContainer);
                }

                chrome.runtime.sendMessage({
                    'request': 'track',
                    'event': 'Suggested macros',
                    'data': {
                        'suggested_macros_count': _.size(suggestedMacros),
                        'helpdesk_host': window.location.hostname
                    }
                });
            });
        };
        var bodyInterval = setInterval(bodyCheck, 300);
    };

    var getData = function (params, callback) {
        $('.workspace').each(function (_, workspace) {
            workspace = $(workspace);

            if (workspace.css('display') !== 'none') {

                var agent_name = $('#face_box .name').text();
                var agent_first_name = agent_name.split(' ')[0];
                var agent_last_name = agent_name.split(' ')[1];

                var name = workspace.find('span.sender').text().split('<')[0];
                var first_name = name.split(' ')[0];
                var last_name = name.split(' ')[1];

                var vars = {
                    from: [{
                        'name': agent_name,
                        'first_name': agent_first_name,
                        'last_name': agent_last_name,
                        'email': ''
                    }],
                    to: [{
                        'name': name,
                        'first_name': first_name,
                        'last_name': last_name,
                        'email': workspace.find('span.sender .email').text()
                    }],
                    cc: [],
                    bcc: [],
                    subject: workspace.find('input[name=subject]').val()
                };

                if(callback) {
                    return callback(null, vars);
                }
            }
        });
    };

    var setTitle = function (params, callback) {

    };

    return {
        init: init,
        getData: getData,
        setTitle: setTitle
    };

})());
<commit_msg>Fixed zendesk bug with subject<commit_after>App.plugin('zendesk', (function () {
    var init = function (params, callback) {
        if (window.location.hostname.indexOf('.zendesk.com') === -1) {
            // return true as response if plugin should be activated
            return callback(null, false);
        }

        Settings.get('settings', {}, function (settings) {
            if (settings.suggestions && settings.suggestions.enabled === false) {
                return callback(null, false);
            }

            // here we're making sure that we have the current user as a client and we're not sending requests for now reason.
            chrome.runtime.sendMessage({
                'request': 'suggestion-enabled',
                'data': {
                    'domain': window.location.hostname
                }
            }, function(enabled){
                callback(null, enabled);

                if (enabled) {
                    injectScript();
                    load();
                }
            })
        });
    };

    // inject the zendesk script into the dom - this is done for interacting with the macro insertion
    var injectScript = function () {
        var script = document.createElement('script');
        script.type = "text/javascript";
        script.src = chrome.extension.getURL("pages/helpdesk/zendesk.js");
        if (document.body) {
            document.body.appendChild(script);
            script.onload = function () {
                document.body.removeChild(script);
            };
        }
    };

    var bindOnce = function () {
        // forward the message of usage to the bg script (for stats)
        window.addEventListener('message', function (event) {
            if (event.data && event.data.request && event.data.request === 'macro-used') {
                chrome.runtime.sendMessage({
                    'request': 'suggestion-used',
                    'data': {
                        'agent': {
                            'host': window.location.host,
                            'name': $('#face_box .name').text()
                        },
                        'url': window.location.href,
                        'template_id': event.data.template_id
                    }
                });

                var score = 0;
                if (event.data.score) {
                    score = event.data.score;
                }

                chrome.runtime.sendMessage({
                    'request': 'track',
                    'event': 'Used Macro',
                    'data': {
                        'is_suggested': score > 0,
                        'helpdesk_host': window.location.hostname,
                        'score': score
                    }
                });
            }
        });
    };

    var load = function () {
        // continuously check if our URL has changed and load the data accordingly

        //bind events only once here
        bindOnce();
        var ticketUrl = "";
        var ticketCheck = function () {
            if (window.location.pathname.indexOf('/agent/tickets/') === -1) {
                // reset the ticket url if we're not inside a ticket anymore
                ticketUrl = "";
                return;
            }
            // don't fetch for the same ticket
            if (ticketUrl === window.location.pathname) {
                return;
            }
            ticketUrl = window.location.pathname;

            $('.macro-suggestions-container').remove();

            loadEmail();
            loadMacroWidget();
        };
        setInterval(ticketCheck, 300);
    };

    // add tooltip to the email link
    var loadEmail = function () {
        var emailCheck = function() {
            var emailLink = $('a.email');
            if (emailLink.length) {
                emailLink.
                    attr('title', "Copy email shortcut: CTRL+SHIFT+C").
                    attr('data-toggle', "tooltip").
                    attr('data-html', "true").
                    attr('data-placement', "bottom");
                clearInterval(emailInterval);
            }
        };
        var emailInterval = setInterval(emailCheck, 1000);
    };

    // Populate our macro widget
    var loadMacroWidget = function () {
        // make sure we have the content loaded before inserting stuff
        var bodyCheck = function () {

            var subject = '';
            var body = '';

            var currentWorkspace = null;
            var isAgent = false;
            $('.workspace').each(function (_, workspace) {
                workspace = $(workspace);

                if (workspace.css('display') !== 'none') {
                    subject = workspace.find('input[name=subject]').val();
                    if (!(subject && subject.length)){
                        return;
                    }

                    currentWorkspace = workspace;
                    var firstEvent = workspace.find('.event-container .event.is-public:first');

                    isAgent = firstEvent.find('.user_photo').hasClass('agent');
                    body = firstEvent.find('.zd-comment').text();
                }
            });

            if (!currentWorkspace) {
                return;
            }

            clearInterval(bodyInterval);

            if (!isAgent && !subject || !subject.length || !body.length) {
                return;
            }

            // query our servers for suggestions
            chrome.runtime.sendMessage({
                'request': 'suggestion',
                'data': {
                    'agent': {
                        'host': window.location.host,
                        'name': $('#face_box .name').text()
                    },
                    'url': window.location.href,
                    'subject': subject,
                    'to': '',
                    'cc': '',
                    'bcc': '',
                    'from': '',
                    'body': body,
                    'helpdesk': 'zendesk'
                }
            }, function (suggestedMacros) {
                if (!_.size(suggestedMacros)) {
                    return;
                }

                var macroContainer = $('
');
                $.each(suggestedMacros, function (macroIndex, macro) {
                    if (macroIndex > 2) { // show only 3 macros
                        return false;
                    }

                    var macroBtn = $("");
                    var macroTitle = $("");

                    macroBtn.attr('onclick', "gorgiasApplyMacro(" + macro.external_id + ")");
                    macroBtn.attr('macro-id', macro.external_id);

                    var title = macro.body.replace(/\n/g, "
");
                    macroBtn.attr('title', title);
                    macroBtn.attr('data-toggle', "tooltip");
                    macroBtn.attr('data-html', "true");
                    macroBtn.attr('data-placement', "bottom");
                    macroBtn.on('mouseenter', function () {
                        // remove others
                        $('.macro-list-item').removeClass('zd-item-focus');
                        $(this).parent().addClass('zd-item-focus');
                    });

                    macroTitle.html(macro.title);
                    macroBtn.append(macroTitle);

                    macroContainer.append(macroBtn);
                });

                var before = currentWorkspace.find('.comment_input .content .options');
                if (before.length) {
                    before.before(macroContainer);
                } else {
                    currentWorkspace.find('.comment_input .content .editor').after('
').after(macroContainer);
                }

                chrome.runtime.sendMessage({
                    'request': 'track',
                    'event': 'Suggested macros',
                    'data': {
                        'suggested_macros_count': _.size(suggestedMacros),
                        'helpdesk_host': window.location.hostname
                    }
                });
            });
        };
        var bodyInterval = setInterval(bodyCheck, 300);
    };

    var getData = function (params, callback) {
        $('.workspace').each(function (_, workspace) {
            workspace = $(workspace);

            if (workspace.css('display') !== 'none') {

                var agent_name = $('#face_box .name').text();
                var agent_first_name = agent_name.split(' ')[0];
                var agent_last_name = agent_name.split(' ')[1];

                var name = workspace.find('span.sender').text().split('<')[0];
                var first_name = name.split(' ')[0];
                var last_name = name.split(' ')[1];

                var vars = {
                    from: [{
                        'name': agent_name,
                        'first_name': agent_first_name,
                        'last_name': agent_last_name,
                        'email': ''
                    }],
                    to: [{
                        'name': name,
                        'first_name': first_name,
                        'last_name': last_name,
                        'email': workspace.find('span.sender .email').text()
                    }],
                    cc: [],
                    bcc: [],
                    subject: workspace.find('input[name=subject]').val()
                };

                if(callback) {
                    return callback(null, vars);
                }
            }
        });
    };

    var setTitle = function (params, callback) {

    };

    return {
        init: init,
        getData: getData,
        setTitle: setTitle
    };

})());
<|endoftext|>


<commit_before>(function () {
    "use strict";

    var app = angular.module("piadinamia", [
            "firebase",
            "ui.bootstrap",
            "ngRoute"
        ]);

    app.constant("FBURL", "https://piadinamia.firebaseio.com/");

    app.config(["$routeProvider", function ($routeProvider) {
        $routeProvider
        .when("/", { templateUrl: "views/default.html" })
        .when("/signin", { templateUrl: "views/users/signin.html" })
        .when("/signup", { templateUrl: "views/users/signup.html" })
        .otherwise({ redirectTo: "/" });
    }]);

    app.run(["sessionService", "$rootScope", "FBURL",
        function (sessionService, $rootScope, FBURL) {
        $rootScope.auth = sessionService.init("/signin");
        $rootScope.FBURL = FBURL;
    }]);
}());
<commit_msg>Reformat app.js.<commit_after>(function () {
    "use strict";

    var app = angular.module("piadinamia", [
        "firebase",
        "ui.bootstrap",
        "ngRoute"
    ]);

    app.constant("FBURL", "https://piadinamia.firebaseio.com/");

    app.config(["$routeProvider", function ($routeProvider) {
        $routeProvider
            .when("/", { templateUrl: "views/default.html" })
            .when("/signin", { templateUrl: "views/users/signin.html" })
            .when("/signup", { templateUrl: "views/users/signup.html" })
            .otherwise({ redirectTo: "/" });
    }]);

    app.run(["sessionService", "$rootScope", "FBURL",
        function (sessionService, $rootScope, FBURL) {
            $rootScope.auth = sessionService.init("/signin");
            $rootScope.FBURL = FBURL;
        }]);
}());
<|endoftext|>


<commit_before>$(function() {

    var headerSelect = $("select[name=header]");
    var mainBodySelect = $("select[name=mainBody]");
    var sidebarSelect = $("select[name=sidebar]");
    var backgroundSelect = $("select[name=background]");
    var resetter = $("#resetButton");

    function ColorSet(headerHex, mainHex, sideHex, bgHex) {
        // Constructor for an object that stores a set of the hexcodes
        // for a specified color scheme
        this.headerHex = headerHex;
        this.mainHex = mainHex;
        this.sideHex = sideHex;
        this.bgHex = bgHex;
    }

    function defaultColorSet() {
        return new ColorSet('#0000FF', '#FFFFFF', '#808080',
                            '#B0C4DE');
    }

    function changeColor(selector, color) {
        // changes the backgroudn-color of the elements covered
        // by selector to color
        $(selector).css("background-color", color);
    }

    function animateColor(selector, color) {
        // like changeColor, but does the change with an
        // animation, using jquery.colors.js
        // we only animate the initial change of color when the
        // user first picks the new color, all other changes of
        // the css value are done instantly with changeColor
        $(selector).animate({backgroundColor: color}, 'slow');
    }

    function save() {
        var newColors = new ColorSet(headerSelect.val(),
                                     mainBodySelect.val(),
                                     sidebarSelect.val(),
                                     backgroundSelect.val());
        $.cookie("colorCookie", JSON.stringify(newColors),{expires: 7});
    }

    headerSelect.change(function() {
        animateColor("header", $(this).val());
        save();
    });

    mainBodySelect.change(function() {
        animateColor("#mainText", $(this).val());
        save();
    });

    sidebarSelect.change(function() {
        // In case the user highlighted nav li's via
        // highlightNav.js, change them too
        animateColor("nav, nav li", $(this).val());
        save();
    });

    backgroundSelect.change(function() {
        animateColor("body", $(this).val());
        save();
    });

    function set(colSet) {
        // sets the selects' names and the background colors as
        // specified by colSet
        var defaultColors = defaultColorSet();
        colSet = $.extend(defaultColors, colSet);//remove null values just in case

        headerSelect.val(colSet.headerHex);
        mainBodySelect.val(colSet.mainHex);
        sidebarSelect.val(colSet.sideHex);
        backgroundSelect.val(colSet.bgHex);

        changeColor("header", colSet.headerHex);
        changeColor("#mainText", colSet.mainHex);
        changeColor("nav, nav li", colSet.sideHex);
        changeColor("body", colSet.bgHex);
        /*$("header").css("background-color", colSet.headerHex);
        $("#mainText").css("background-color", colSet.mainHex);
        $("nav").css("background-color", colSet.sideHex);

        // In case the user highlighted nav li's via highlightNav.js
        // nav li's CSS overrides nav's so it must be updated manually
        $("nav li").css("background-color", colSet.sideHex);

        $("body").css("background-color", colSet.bgHex);*/
        return true;
    }

    function resetCookie() {
        $.cookie("colorCookie", null);
    }

    resetter.click(function() {
        var resetColors = defaultColorSet();
        set(resetColors);
        resetCookie();
    });

    function setColorsFromCookie() {
        // reads colorCookie and sets the colors accordingly
        set(JSON.parse($.cookie("colorCookie")));
    }

    setColorsFromCookie();
});
<commit_msg>Added a parameter to set to check if the change in colors should or should not be animated<commit_after>$(function() {

    var headerSelect = $("select[name=header]");
    var mainBodySelect = $("select[name=mainBody]");
    var sidebarSelect = $("select[name=sidebar]");
    var backgroundSelect = $("select[name=background]");
    var resetter = $("#resetButton");

    function ColorSet(headerHex, mainHex, sideHex, bgHex) {
        // Constructor for an object that stores a set of the hexcodes
        // for a specified color scheme
        this.headerHex = headerHex;
        this.mainHex = mainHex;
        this.sideHex = sideHex;
        this.bgHex = bgHex;
    }

    function defaultColorSet() {
        return new ColorSet('#0000FF', '#FFFFFF', '#808080',
                            '#B0C4DE');
    }

    function changeColor(selector, color) {
        // changes the backgroudn-color of the elements covered
        // by selector to color
        $(selector).css("background-color", color);
    }

    function animateColor(selector, color) {
        // like changeColor, but does the change with an
        // animation, using jquery.colors.js
        // we only animate the initial change of color when the
        // user first picks the new color, all other changes of
        // the css value are done instantly with changeColor
        $(selector).animate({backgroundColor: color}, 'slow');
    }

    function save() {
        var newColors = new ColorSet(headerSelect.val(),
                                     mainBodySelect.val(),
                                     sidebarSelect.val(),
                                     backgroundSelect.val());
        $.cookie("colorCookie", JSON.stringify(newColors),{expires: 7});
    }

    headerSelect.change(function() {
        animateColor("header", $(this).val());
        save();
    });

    mainBodySelect.change(function() {
        animateColor("#mainText", $(this).val());
        save();
    });

    sidebarSelect.change(function() {
        // In case the user highlighted nav li's via
        // highlightNav.js, change them too
        animateColor("nav, nav li", $(this).val());
        save();
    });

    backgroundSelect.change(function() {
        animateColor("body", $(this).val());
        save();
    });

    function set(colSet, shouldAnimate) {
        // sets the selects' names and the background colors as
        // specified by colSet, animates if shouldAnimate is
        // true, else just changes the colors
        var defaultColors = defaultColorSet();
        colSet = $.extend(defaultColors, colSet);//remove null values just in case

        headerSelect.val(colSet.headerHex);
        mainBodySelect.val(colSet.mainHex);
        sidebarSelect.val(colSet.sideHex);
        backgroundSelect.val(colSet.bgHex);

        var colorFun = changeColor;
        if (shouldAnimate) {
            colorFun = animateColor;
        }

        colorFun("header", colSet.headerHex);
        colorFun("#mainText", colSet.mainHex);
        colorFun("nav, nav li", colSet.sideHex);
        colorFun("body", colSet.bgHex);
        return true;
    }

    function resetCookie() {
        $.cookie("colorCookie", null);
    }

    resetter.click(function() {
        var resetColors = defaultColorSet();
        set(resetColors, true);
        resetCookie();
    });

    function setColorsFromCookie() {
        // reads colorCookie and sets the colors accordingly
        set(JSON.parse($.cookie("colorCookie")), false);
    }

    setColorsFromCookie();
});
<|endoftext|>


<commit_before>import { flatten, has, isEmpty, toArray } from 'lodash'

class FormErrors
{
    /*
     * Create a new FormErrors instance.
     */
    constructor() {
        this.errors = {};
    }

    /*
     * Get all of the raw errors for the collection.
     */
    all() {
        return this.errors;
    }

    /*
     * Determine if the collection has any errors.
     */
    hasErrors() {
        return ! isEmpty(this.errors);
    }

    /*
     * Get all of the errors for the collection in a flat array.
     */
    flatten() {
        return flatten(toArray(this.errors));
    }

    /*
     * Forget all of the errors currently in the collection.
     */
    forget() {
        this.errors = {};
    }

    /*
     * Get the first error for the given field.
     */
    get(field) {
        if (this.has(field)) {
            return this.errors[field][0];
        }
    }

    /*
     * Determine if the collection has any errors for the given field.
     */
    has(field) {
        return has(this.errors, field);
    }

    /*
     * Set the raw errors for the collection.
     */
    set(errors) {
        if (typeof errors === 'object') {
            this.errors = errors;
        } else {
            this.errors = {
                form: ['An unknown error has occured']
            }
        }
    }
}

export default FormErrors;<commit_msg>change default error message<commit_after>import { flatten, has, isEmpty, toArray } from 'lodash'

class FormErrors
{
    /*
     * Create a new FormErrors instance.
     */
    constructor() {
        this.errors = {};
    }

    /*
     * Get all of the raw errors for the collection.
     */
    all() {
        return this.errors;
    }

    /*
     * Determine if the collection has any errors.
     */
    hasErrors() {
        return ! isEmpty(this.errors);
    }

    /*
     * Get all of the errors for the collection in a flat array.
     */
    flatten() {
        return flatten(toArray(this.errors));
    }

    /*
     * Forget all of the errors currently in the collection.
     */
    forget() {
        this.errors = {};
    }

    /*
     * Get the first error for the given field.
     */
    get(field) {
        if (this.has(field)) {
            return this.errors[field][0];
        }
    }

    /*
     * Determine if the collection has any errors for the given field.
     */
    has(field) {
        return has(this.errors, field);
    }

    /*
     * Set the raw errors for the collection.
     */
    set(errors) {
        if (typeof errors === 'object') {
            this.errors = errors;
        } else {
            this.errors = {
                form: ['Something went wrong. Please try again or contact customer support.']
            }
        }
    }
}

export default FormErrors;<|endoftext|>


<commit_before>'use strict';

angular.module('deckApp.account.service', [
  'restangular',
  'deckApp.utils.lodash',
  'deckApp.caches.scheduled',
  'deckApp.caches.infrastructure'
])
  .factory('accountService', function(settings, _, Restangular, $q, scheduledCache, infrastructureCaches) {

    function getPreferredZonesByAccount(providerName) {
      var _providerName = providerName || 'aws';
      return $q.when(settings.providers[_providerName].preferredZonesByAccount);
    }

    function getAvailabilityZonesForAccountAndRegion(providerName, accountName, regionName) {

      return getPreferredZonesByAccount(providerName).then( function(defaults) {
        return {preferredZones: defaults[accountName][regionName]};
      })
      .then(function(zonesCollection) {
        return getRegionsForAccount(accountName).then(function(regions){
          zonesCollection.actualZones = _.find(regions, {name: regionName}).availabilityZones;
          return zonesCollection;
        });
      })
      .then(function(zonesCollection) {
        return _.intersection(zonesCollection.preferredZones, zonesCollection.actualZones);
      })
      .catch(function() {
         return settings.providers[providerName].preferredZonesByAccount.default[regionName];
      });
    }

    function listAccounts(provider) {
      if (provider) {
        return listAccounts().then(function(accounts) {
          return _.filter(accounts, { type: provider });
        });
      }
      return Restangular
        .all('credentials')
        .withHttpConfig({cache: infrastructureCaches.credentials})
        .getList();
    }

    function listProviders() {
      return listAccounts().then(function(accounts) {
        return _.uniq(_.pluck(accounts, 'type'));
      });
    }

    var getRegionsKeyedByAccount = _.memoize(function(provider) {
      var deferred = $q.defer();
      listAccounts(provider).then(function(accounts) {
        $q.all(accounts.reduce(function(acc, account) {
          acc[account.name] = Restangular
            .all('credentials')
            .one(account.name)
            .withHttpConfig({cache: infrastructureCaches.credentials})
            .get();
          return acc;
        }, {})).then(function(result) {
          deferred.resolve(result);
        });
      });
      return deferred.promise;
    });

    function getAccountDetails(accountName) {
      return Restangular.one('credentials', accountName)
        .withHttpConfig({cache: infrastructureCaches.credentials})
        .get();
    }

    function getRegionsForAccount(accountName) {
      return getAccountDetails(accountName).then(function(details) {
        return details ? details.regions : null;
      });
    }

    function challengeDestructiveActions(provider, account) {
      return account &&
        settings.providers[provider] &&
        settings.providers[provider].challengeDestructiveActions &&
        settings.providers[provider].challengeDestructiveActions.indexOf(account) > -1;
    }

    return {
      challengeDestructiveActions: challengeDestructiveActions,
      listAccounts: listAccounts,
      listProviders: listProviders,
      getAccountDetails: getAccountDetails,
      getRegionsForAccount: getRegionsForAccount,
      getRegionsKeyedByAccount: getRegionsKeyedByAccount,
      getPreferredZonesByAccount: getPreferredZonesByAccount,
      getAvailabilityZonesForAccountAndRegion: getAvailabilityZonesForAccountAndRegion
    };
  });
<commit_msg>Fix for #649: - Moving the preferred list of AZ into settings.js - Now taking the intersection of the preferred AZ in setting.js with the actual AZs for the account/region.<commit_after>'use strict';

angular.module('deckApp.account.service', [
  'restangular',
  'deckApp.utils.lodash',
  'deckApp.caches.scheduled',
  'deckApp.caches.infrastructure'
])
  .factory('accountService', function(settings, _, Restangular, $q, scheduledCache, infrastructureCaches) {

    function getPreferredZonesByAccount(providerName) {
      var _providerName = providerName || 'aws';
      return $q.when(settings.providers[_providerName].preferredZonesByAccount);
    }

    function getAvailabilityZonesForAccountAndRegion(providerName, accountName, regionName) {

      return getPreferredZonesByAccount(providerName).then( function(defaults) {
        return {preferredZones: defaults[accountName][regionName]};
      })
      .then(function(zonesCollection) {
        return getRegionsForAccount(accountName).then(function(regions){
          zonesCollection.actualZones = _.find(regions, {name: regionName}).availabilityZones;
          return zonesCollection;
        });
      })
      .then(function(zonesCollection) {
        return _.intersection(zonesCollection.preferredZones, zonesCollection.actualZones);
      })
      .catch(function() {
         return settings.providers[providerName].preferredZonesByAccount.default[regionName];
      });
    }

    function getAvailabilityZonesForAccountAndRegion(accountName, regionName) {

      return getPreferredZonesByAccount().then( function(defaults) {
        return {preferredZones: defaults[accountName][regionName]};
      })
      .then(function(zonesCollection) {
        return getRegionsForAccount(accountName).then(function(regions){
          zonesCollection.actualZones = _.find(regions, {name: regionName}).availabilityZones;
          return zonesCollection;
        });
      })
      .then(function(zonesCollection) {
        return _.intersection(zonesCollection.preferredZones, zonesCollection.actualZones);
      })
      .catch(function() {
         return settings.preferredZonesByAccount.default[regionName];
      });
    }

    function listAccounts(provider) {
      if (provider) {
        return listAccounts().then(function(accounts) {
          return _.filter(accounts, { type: provider });
        });
      }
      return Restangular
        .all('credentials')
        .withHttpConfig({cache: infrastructureCaches.credentials})
        .getList();
    }

    function listProviders() {
      return listAccounts().then(function(accounts) {
        return _.uniq(_.pluck(accounts, 'type'));
      });
    }

    var getRegionsKeyedByAccount = _.memoize(function(provider) {
      var deferred = $q.defer();
      listAccounts(provider).then(function(accounts) {
        $q.all(accounts.reduce(function(acc, account) {
          acc[account.name] = Restangular
            .all('credentials')
            .one(account.name)
            .withHttpConfig({cache: infrastructureCaches.credentials})
            .get();
          return acc;
        }, {})).then(function(result) {
          deferred.resolve(result);
        });
      });
      return deferred.promise;
    });

    function getAccountDetails(accountName) {
      return Restangular.one('credentials', accountName)
        .withHttpConfig({cache: infrastructureCaches.credentials})
        .get();
    }

    function getRegionsForAccount(accountName) {
      return getAccountDetails(accountName).then(function(details) {
        return details ? details.regions : null;
      });
    }

    function challengeDestructiveActions(provider, account) {
      return account &&
        settings.providers[provider] &&
        settings.providers[provider].challengeDestructiveActions &&
        settings.providers[provider].challengeDestructiveActions.indexOf(account) > -1;
    }

    return {
      challengeDestructiveActions: challengeDestructiveActions,
      listAccounts: listAccounts,
      listProviders: listProviders,
      getAccountDetails: getAccountDetails,
      getRegionsForAccount: getRegionsForAccount,
      getRegionsKeyedByAccount: getRegionsKeyedByAccount,
      getPreferredZonesByAccount: getPreferredZonesByAccount,
      getAvailabilityZonesForAccountAndRegion: getAvailabilityZonesForAccountAndRegion
    };
  });
<|endoftext|>


<commit_before>/*
 * Licensed to Cloudkick, Inc ('Cloudkick') under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * Cloudkick licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var querystring = require('querystring');

var httpUtil = require('util/http');

function attachMiddleware(requiredParams) {
  return function(req, res, next) {
    var missingParams, errMsg;

    if (!requiredParams || requiredParams.length === 0) {
      next();
      return;
    }

    missingParams = requiredParams.filter(function(param) {
      return (!req.body || !req.body[param]);
    });

    if (missingParams.length > 0) {
      errMsg = 'Missing required parameters: ' + missingParams.join(', ');
      httpUtil.returnError(res, 400, errMsg);
      return;
    }

    next();
  };
}

exports.attachMiddleware = attachMiddleware;
<commit_msg>update required-params returnError call<commit_after>/*
 * Licensed to Cloudkick, Inc ('Cloudkick') under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * Cloudkick licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var querystring = require('querystring');

var httpUtil = require('util/http');

function attachMiddleware(requiredParams) {
  return function(req, res, next) {
    var missingParams, errMsg;

    if (!requiredParams || requiredParams.length === 0) {
      next();
      return;
    }

    missingParams = requiredParams.filter(function(param) {
      return (!req.body || !req.body[param]);
    });

    if (missingParams.length > 0) {
      errMsg = 'Missing required parameters: ' + missingParams.join(', ');
      httpUtil.returnError(res, new Error(errMsg), 400);
      return;
    }

    next();
  };
}

exports.attachMiddleware = attachMiddleware;
<|endoftext|>


<commit_before>app.controller('playerController', ["$scope", "playerService", "playerStatsService", function($scope, playerService) {
	$scope.players = [];
	$scope.playerCollapse = {};

	// pagination & search variables
	$scope.pagination = {
		filteredPlayers: [],
		currentPage: -1,
		pageSize: 10,
		numPages: 5,
		search: "",
		searching: false
	};

	$scope.isPlayerCollapsed = function(index) {
		return($scope.playerCollapse[index]);
	};

	$scope.flipPlayerCollapsed = function(index) {
		$scope.playerCollapse[index] = !($scope.playerCollapse[index]);
	};

	$scope.getAllPlayers = function () {
		playerService.all()
			.then(function (result) {
				if (result.data.status === 200) {
					$scope.players = result.data.data;
					console.log($scope.players);
					for(index in $scope.players) {
						$scope.playerCollapse[index] = true;
					}
					$scope.switchPlayerArray();
				}
			});
	};
	$scope.getAllPlayerStatistics = function () {
		playerService.all()
			.then(function (result) {
				if (result.data.status === 200) {
					$scope.players = result.data.data;
					$scope.switchPlayerArray();
				}
			});
	};
	$scope.switchPlayerArray = function() {
		if($scope.pagination.search !== undefined && $scope.pagination.search !== "") {
			$scope.pagination.searching = true;
			$scope.pagination.currentPage = -1;
			$scope.pagination.filteredPlayers = $scope.players;
		} else {
			$scope.pagination.searching = false;
			var begin = ($scope.pagination.currentPage - 1) * $scope.pagination.pageSize;
			var end = begin + $scope.pagination.pageSize;
			$scope.pagination.filteredPlayers = $scope.players.slice(begin, end);
		}
	};

	if ($scope.players.length === 0) {
		$scope.players = $scope.getAllPlayers();
		$scope.pagination.currentPage = 1;
	}
}]);
<commit_msg>player controller<commit_after>app.controller('playerController', ["$scope", "playerService", "playerStatsService", function($scope, playerService) {
	$scope.players = [];
	$scope.playerCollapse = {};

	// pagination & search variables
	$scope.pagination = {
		filteredPlayers: [],
		currentPage: -1,
		pageSize: 10,
		numPages: 5,
		search: "",
		searching: false
	};

	$scope.isPlayerCollapsed = function(index) {
		return($scope.playerCollapse[index]);
	};

	$scope.flipPlayerCollapsed = function(index) {
		$scope.playerCollapse[index] = !($scope.playerCollapse[index]);
	};

	$scope.getAllPlayers = function () {
		playerService.all()
			.then(function (result) {
				if (result.data.status === 200) {
					$scope.players = result.data.data;
					console.log($scope.players);
					for(index in $scope.players) {
						$scope.playerCollapse[index] = true;
					}
					$scope.switchPlayerArray();
				}
			});
	};
	$scope.getAllPlayersStatisticsForId = function (playerId) {
		playerStatsService.getAllPlayersStatisticsForId(playerId)
			.then(function (result) {
				if (result.data.status === 200) {
					$scope.playerStats.playerId = result.data.data;
				}
			});
	};
	$scope.switchPlayerArray = function() {
		if($scope.pagination.search !== undefined && $scope.pagination.search !== "") {
			$scope.pagination.searching = true;
			$scope.pagination.currentPage = -1;
			$scope.pagination.filteredPlayers = $scope.players;
		} else {
			$scope.pagination.searching = false;
			var begin = ($scope.pagination.currentPage - 1) * $scope.pagination.pageSize;
			var end = begin + $scope.pagination.pageSize;
			$scope.pagination.filteredPlayers = $scope.players.slice(begin, end);
		}
	};

	if ($scope.players.length === 0) {
		$scope.players = $scope.getAllPlayers();
		$scope.pagination.currentPage = 1;
	}
}]);
<|endoftext|>