<commit_before>$( document ).ready( function() {

    ( function( $ ) {

        $.fn.netteGMap = function( options ) {

            //exist NetteGMap?
            if ( $( '#nette-g-map' ).length === 1 ) {

                infowindow = new google.maps.InfoWindow();
                geocoder = new google.maps.Geocoder();

                // Set defaults
                defaults = {
                    changePositionMarker: function( results ) {}
                };

                // Override defaults with options
                options = $.extend( defaults, options );

				//pri zadavani vyhledavane fraze do naseptace v mape, neukladat cely form na klavesu enter
				$( "#nette-g-map-search-box" ).keydown( function( e ) {
					if ( e.keyCode == 13 ) {
						//stisknut ENTER, neodesilej formular
						return false;
					}
				} );

                //get data atributes
                var dataAttr = $( '#nette-g-map' ).data( "nette-g-map-picker" );

                map = new google.maps.Map( $( '#nette-g-map-canvas' )[0], {
                    mapTypeId: google.maps.MapTypeId.ROADMAP,
                    zoom: dataAttr.zoom,
                    scrollwheel: false
                } );

                //set dimensions of map
                $( "#nette-g-map-canvas" ).width( dataAttr.size.x );
                $( "#nette-g-map-canvas" ).height( dataAttr.size.y );
                //////////////////////////////////

                markers = []; //array of markers

                if ( $( '#nette-g-map #nette-g-map-search-box' ).length === 1 )
                {
                    //picker

                    //set default marker
                    setMarkerPicker( new google.maps.LatLng( $( "input#latitude" ).val(), $( "input#longitude" ).val() ) );

                    //search
                    var searchBox = new google.maps.places.SearchBox( $( "#nette-g-map-search-box" )[0] );

                    //search result
                    google.maps.event.addListener( searchBox, 'places_changed', function() {

                        var places = searchBox.getPlaces();

                        //set first marker from places
                        if ( places.length > 0 ) {
                            changeMarkerPickerLocation( places[0].geometry.location );
                        }
                    } );
                }
                else
                {
                    //viewer
                    bounds = new google.maps.LatLngBounds();

                    //view markers
                    for ( i = 0; i < dataAttr.markers.length; i++ )
                    {
                        setMarkerViewer( dataAttr.markers[i], i );
                    }

                    if ( typeof dataAttr.zoom === 'undefined' ) {
                        //set zoom and center auto - bounds
                        map.fitBounds( bounds );
                    }
                    else
                    {
                        //is defined zoom, set center map
                        //set center from first marker
                        map.setCenter( new google.maps.LatLng( dataAttr.markers[0].latitude, dataAttr.markers[0].longitude ) );
                    }
                }
            }
        };

        function setMarkerPicker( location ) {
            markerPoint = new google.maps.Marker( {
                position: location,
                map: map,
                draggable: true
            } );

            map.setCenter( location );
            markers.push( markerPoint );

            changeMarkerPickerLocation( location );
        }

        function setMarkerViewer( marker, i ) {

            var location = new google.maps.LatLng( marker.latitude, marker.longitude );

            //create marker
            markerPoint = new google.maps.Marker( {
                position: location,
                map: map,
                draggable: false,
                title: marker.title
            } );

            //set icon whenn is set
            if ( typeof marker.icon !== 'undefined' ) {
                markerPoint.setIcon( marker.icon );
            }

            google.maps.event.addListener( markerPoint, 'click', ( function( markerPoint, i ) {
                return function() {
                    infowindow.setContent( marker.description );
                    infowindow.open( map, markerPoint );
                };
            } )( markerPoint, i ) );

            bounds.extend( location );

            //add marker to array
            markers.push( markerPoint );
        }

        //Change location MarkerPicker
        function changeMarkerPickerLocation( location )
        {
            markers[0].setPosition( location );
            map.setCenter( location );

            //set position marker to inputs
            $( "input#latitude" ).val( markerPoint.position.lat() );
            $( "input#longitude" ).val( markerPoint.position.lng() );

            google.maps.event.addListener( markerPoint, 'dragend', function( point ) {

                $( "input#latitude" ).val( point.latLng.lat().toFixed( 10 ) );
                $( "input#longitude" ).val( point.latLng.lng().toFixed( 10 ) );

                getGeocodeData( new google.maps.LatLng( markerPoint.position.lat(), markerPoint.position.lng() ) );

            } );

        }

        function getGeocodeData( latLng )
        {
            geocoder.geocode({'latLng': latLng}, function(results, status) {
                if ( status === google.maps.GeocoderStatus.OK ) {
                    defaults.changePositionMarker( results );//call function to result data geocode
                }
            });
        }

    }( jQuery ) );

} );<commit_msg>Add function for set marker position from out of widget<commit_after>$( document ).ready( function() {

    ( function( $ ) {

        $.fn.netteGMap = function( options ) {

            //exist NetteGMap?
            if ( $( '#nette-g-map' ).length === 1 ) {

                infowindow = new google.maps.InfoWindow();
                geocoder = new google.maps.Geocoder();

                // Set defaults
                defaults = {
                    changePositionMarker: function( results ) {}
                };

                // Override defaults with options
                options = $.extend( defaults, options );

				//pri zadavani vyhledavane fraze do naseptace v mape, neukladat cely form na klavesu enter
				$( "#nette-g-map-search-box" ).keydown( function( e ) {
					if ( e.keyCode == 13 ) {
						//stisknut ENTER, neodesilej formular
						return false;
					}
				} );

                //get data atributes
                var dataAttr = $( '#nette-g-map' ).data( "nette-g-map-picker" );

                map = new google.maps.Map( $( '#nette-g-map-canvas' )[0], {
                    mapTypeId: google.maps.MapTypeId.ROADMAP,
                    zoom: dataAttr.zoom,
                    scrollwheel: false
                } );

                //set dimensions of map
                $( "#nette-g-map-canvas" ).width( dataAttr.size.x );
                $( "#nette-g-map-canvas" ).height( dataAttr.size.y );
                //////////////////////////////////

                markers = []; //array of markers

                if ( $( '#nette-g-map #nette-g-map-search-box' ).length === 1 )
                {
                    //picker

                    //set default marker
                    setMarkerPicker( new google.maps.LatLng( $( "input#latitude" ).val(), $( "input#longitude" ).val() ) );

                    //search
                    var searchBox = new google.maps.places.SearchBox( $( "#nette-g-map-search-box" )[0] );

                    //search result
                    google.maps.event.addListener( searchBox, 'places_changed', function() {

                        var places = searchBox.getPlaces();

                        //set first marker from places
                        if ( places.length > 0 ) {
                            changeMarkerPickerLocation( places[0].geometry.location );
                        }
                    } );
                }
                else
                {
                    //viewer
                    bounds = new google.maps.LatLngBounds();

                    //view markers
                    for ( i = 0; i < dataAttr.markers.length; i++ )
                    {
                        setMarkerViewer( dataAttr.markers[i], i );
                    }

                    if ( typeof dataAttr.zoom === 'undefined' ) {
                        //set zoom and center auto - bounds
                        map.fitBounds( bounds );
                    }
                    else
                    {
                        //is defined zoom, set center map
                        //set center from first marker
                        map.setCenter( new google.maps.LatLng( dataAttr.markers[0].latitude, dataAttr.markers[0].longitude ) );
                    }
                }
            }
        };

        $.fn.setMarkerPosition = function(lon, lat) {
            var location = new google.maps.LatLng( lat, lon );
            changeMarkerPickerLocation( location );
        };

        function setMarkerPicker( location ) {
            markerPoint = new google.maps.Marker( {
                position: location,
                map: map,
                draggable: true
            } );

            map.setCenter( location );
            markers.push( markerPoint );

            changeMarkerPickerLocation( location );
        }

        function setMarkerViewer( marker, i ) {

            var location = new google.maps.LatLng( marker.latitude, marker.longitude );

            //create marker
            markerPoint = new google.maps.Marker( {
                position: location,
                map: map,
                draggable: false,
                title: marker.title
            } );

            //set icon whenn is set
            if ( typeof marker.icon !== 'undefined' ) {
                markerPoint.setIcon( marker.icon );
            }

            google.maps.event.addListener( markerPoint, 'click', ( function( markerPoint, i ) {
                return function() {
                    infowindow.setContent( marker.description );
                    infowindow.open( map, markerPoint );
                };
            } )( markerPoint, i ) );

            bounds.extend( location );

            //add marker to array
            markers.push( markerPoint );
        }

        //Change location MarkerPicker
        function changeMarkerPickerLocation( location )
        {
            markers[0].setPosition( location );
            map.setCenter( location );

            //set position marker to inputs
            $( "input#latitude" ).val( markerPoint.position.lat() );
            $( "input#longitude" ).val( markerPoint.position.lng() );

            google.maps.event.addListener( markerPoint, 'dragend', function( point ) {

                $( "input#latitude" ).val( point.latLng.lat().toFixed( 10 ) );
                $( "input#longitude" ).val( point.latLng.lng().toFixed( 10 ) );

                getGeocodeData( new google.maps.LatLng( markerPoint.position.lat(), markerPoint.position.lng() ) );

            } );

        }

        function getGeocodeData( latLng )
        {
            geocoder.geocode({'latLng': latLng}, function(results, status) {
                if ( status === google.maps.GeocoderStatus.OK ) {
                    defaults.changePositionMarker( results );//call function to result data geocode
                }
            });
        }

    }( jQuery ) );

} );<|endoftext|>


<commit_before>var log = require('bows')('login');
var PageView = require('client/js/pages/base');
var templates = require('client/js/templates');
var auth = require('client/js/auth');
var $ = require('jquery');

module.exports = PageView.extend({
  pageTitle: 'Login',
  template: templates.pages.auth.login,
  render: function  () {
    PageView.prototype.render.apply(this, arguments);

    auth.init();
  },
  events: {
    'click [data-hook=facebook-login]': 'loginWithFacebook',
    'click [data-hook=google-login]': 'loginWithGoogle',
  },
  loginWithFacebook: function () {
    auth.login('facebook', this.handleLogin);
  },
  loginWithGoogle: function () {
    auth.login('google', this.handleLogin);
  },
  handleLogin: function(err, user) {
    var id, token;
    log('handleLogin', arguments);
    if(err) {
      return alert(err.error);
    }

    if (user.authResponse) {
      id = user.authResponse.userID;
      token = user.authResponse.accessToken;
      $.get('95.85.37.125:9000/auth/facebook' + id + '/' + token, function () {
        app.fetchInitialData();
        app.me.authenticated = true;
        app.navigate('/');
      });
    }
  }
});
<commit_msg>misunderstood what to do<commit_after>var log = require('bows')('login');
var PageView = require('client/js/pages/base');
var templates = require('client/js/templates');
var auth = require('client/js/auth');

module.exports = PageView.extend({
  pageTitle: 'Login',
  template: templates.pages.auth.login,
  render: function  () {
    PageView.prototype.render.apply(this, arguments);

    auth.init();
  },
  events: {
    'click [data-hook=facebook-login]': 'loginWithFacebook',
    'click [data-hook=google-login]': 'loginWithGoogle',
  },
  loginWithFacebook: function () {
    auth.login('facebook', this.handleLogin);
  },
  loginWithGoogle: function () {
    auth.login('google', this.handleLogin);
  },
  handleLogin: function(err, user) {
    log('handleLogin', arguments);
    if(err) {
      return alert(err.error);
    }

    app.fetchInitialData();
    app.navigate('/');
  }
});
<|endoftext|>


<commit_before>"use strict";

const BASE_TIME = 60;
const PLAY_PAGE = `

Welcome to the chat room

    <input id="message" type="text" placeholder="Type your message here" onkeypress="client.handleChatMessage(event, 'message')"/>

    <canvas id="chessboard" width="678" height="682" onclick="client.handleClick()"></canvas>

60

`;

let client = new chessClient();

function joinGame() {
    let name = document.getElementById("name").value;
    client.socketClient.sendName(name);
    client.name = name;
}

function nameOK() {
    document.body.innerHTML = PLAY_PAGE;
    let canvas = document.getElementById("chessboard");
    client.chessRenderer = new chessRenderer(canvas);
    setInterval(client.updateTimer.bind(client), 1000);
    canvas.addEventListener("mousemove", function(evt) {
            client.mouseCoord = client.getMousePos(canvas, evt);
    }, false);
}

function nameTaken() {
    document.getElementById("loginfo").innerHTML = "This name is already taken, please choose another one";
    document.getElementById("loginfo").style.display = "block";
}

image.loaded = 0;
function image(src) {
  let img = new Image();
  img.src = src;
  img.onload = function() {
      image.loaded += 1;
      if(image.loaded === 12) {
          init();
      }
  };
  return img;
}

const images = [0,image("./images/black_pawn.png"), image("./images/black_tower.png"),
 image("./images/black_knight.png"), image("./images/black_bishop.png"),
 image("./images/black_queen.png"), image("./images/black_king.png"),7,8,9,10,
 image("./images/white_pawn.png"), image("./images/white_tower.png"),
 image("./images/white_knight.png"), image("./images/white_bishop.png"),
 image("./images/white_queen.png"), image("./images/white_king.png")];

function init() {
    client.socketClient.connect(onMessageReceived);
}

function chessClient() {
    return {
        socketClient : new socketClient(),
        chessRenderer : undefined,
        team : undefined,
        id : -1,
        open : false,
        name : "",
        engine : undefined,
        mouseCoord : undefined,
        selectedPiece : undefined,
        lastMoves : undefined,
        lastX : undefined,
        lastY : undefined,
        time : 60,
        teamPlaying : -1,

        updateTimer : function() {
            if(this.teamPlaying === this.team) {
                this.time -= 1;
                if(this.time < 0) {
                    this.time = 0;
                }
                document.getElementById("timer").innerHTML = this.time;
            } else {
                this.time = BASE_TIME;
                document.getElementById("timer").innerHTML = "Waiting on opponents";
            }
        },

        handleClick : function() {
            this.chessRenderer.refreshGame(this.engine.board, images);
            let y = Math.floor(this.mouseCoord.y / tileSize);
            let x = Math.floor(this.mouseCoord.x / tileSize);
            let selected = this.engine.board[y][x];
            let moves = this.engine.getAllPossibleMoves(newCell(y, x));
            if(selected.color === this.team) {
                if(moves !== undefined) {
                    moves.forEach(function(move) {
                        this.chessRenderer.highlightTile(move.y, move.x, (this.engine.board[move.x][move.y].piece !== PieceType.EMPTY));
                    }, this);
                }
            }
            let voteOK = false;
            //if we clicked an empty tile or an enemy tile, and we had a piece selected, and the piece had possible moves
            if(selected.piece === PieceType.EMPTY || selected.color !== this.team) {
                if(this.selectedPiece.piece !== PieceType.EMPTY && this.selectedPiece.color === this.team) {
                    if(this.lastMoves !== undefined) {
                        //check if selected tile is part of the possible moves
                        this.lastMoves.forEach(function(move) {
                            if(move.x === y && move.y === x) {
                                voteOK = true;
                            }
                        });

                        if(voteOK) {
                            this.socketClient.sendMove(this.lastY, this.lastX, y, x);
                        }
                    }
                }
            }
            this.lastX = x;
            this.lastY = y;
            this.selectedPiece = selected;
            this.lastMoves = moves;
        },

        getMousePos : function(canvas, e) {
            let rect = canvas.getBoundingClientRect();
            return {
              x: e.clientX - rect.left,
              y: e.clientY - rect.top
            };
        },

        getTeamName : function(i) {
            if(i === PieceColor.WHITE) {
                return "white";
            } else {
                return "black";
            }
        },

        addToChat : function(sender, message) {
            document.getElementById("chat").innerHTML += `<br/><b>${sender}</b>: ${message}`;
            document.getElementById("chat").scrollTop = document.getElementById("chat").scrollHeight;
        },

        removePlayer : function(player) {
            this.addToChat("Server",`Player ${player.name} left`);
            let elem = document.getElementById(player.name);
            elem.parentNode.removeChild(elem);
        },

        addPlayer : function(player) {
            this.addToChat("Server", "Player "+player.name+" has joined team "+this.getTeamName(player.team));
            if(player.name !== this.name) {
                document.getElementById("info").innerHTML += "
"+player.name+"
";
            }
        },

        applyMove : function(mv) {
            this.engine.move(mv);
            this.chessRenderer.refreshGame(this.engine.board, images);
        },

        setPlayerList : function(lst) {
            lst.forEach(function(player) {
                document.getElementById("info").innerHTML += "
"+player.name+"
";
            }, this);
        },

        teamChange : function(team) {
            this.teamPlaying = team;
            this.addToChat("Server", `It is now ${this.getTeamName(team)}'s turn.`);
            document.getElementById("turn").innerHTML = this.getTeamName(team)+"'s turn";
        },

        handleChatMessage : function(e, tagId) {
            if(e.which === 13 || e.keyCode === 13) {
                let msg = document.getElementById(tagId).value;
                if(msg !== "") {
                    this.socketClient.socket.send(communication(this.socketClient.id, newMessage(messageType.CHAT, msg)));
                    document.getElementById(tagId).value = "";
                }
            }
        }
    };
}

function onMessageReceived(msg) {
    let message = JSON.parse(msg.data).message;
    switch(message.type) {
        case messageType.ID:
            client.socketClient.id = message.params;
            break;
        case messageType.PSEUDO_OK:
            nameOK();
            break;
        case messageType.PSEUDO_TAKEN:
            nameTaken();
            break;
        case messageType.NEW_PLAYER:
            let player = message.params;
            client.addPlayer(player);
            break;
        case messageType.INCOMING_CHAT:
            client.addToChat(message.params.sender, message.params.message);
            break;
        case messageType.BOARD:
            client.engine = getNewGame();
            client.engine.setBoard(message.params);
            client.chessRenderer.refreshGame(client.engine.board, images);
            break;
        case messageType.PLAYER_LEFT:
            let playerLeaving = message.params;
            client.removePlayer(playerLeaving);
            break;
        case messageType.TEAM:
            client.team = message.params;
            break;
        case messageType.MOVED:
            client.applyMove(message.params);
            break;
        case messageType.LIST:
            client.setPlayerList(message.params);
            break;
        case messageType.CHANGE:
            client.teamChange(message.params);
            break;
    }
}
<commit_msg>Mreging<commit_after>"use strict";

const PLAY_PAGE = `

Welcome to the chat room

    <input id="message" type="text" placeholder="Type your message here" onkeypress="client.handleChatMessage(event, 'message')"/>

    <canvas id="chessboard" width="678" height="682" onclick="client.handleClick()"></canvas>

60

`;

let client = new chessClient();

function joinGame() {
    let name = document.getElementById("name").value;
    client.socketClient.sendName(name);
    client.name = name;
}

function nameOK() {
    document.body.innerHTML = PLAY_PAGE;
    let canvas = document.getElementById("chessboard");
    client.chessRenderer = new chessRenderer(canvas);
    setInterval(client.updateTimer.bind(client), 1000);
    canvas.addEventListener("mousemove", function(evt) {
            client.mouseCoord = client.getMousePos(canvas, evt);
    }, false);
}

function nameTaken() {
    document.getElementById("loginfo").innerHTML = "This name is already taken, please choose another one";
    document.getElementById("loginfo").style.display = "block";
}

image.loaded = 0;
function image(src) {
  let img = new Image();
  img.src = src;
  img.onload = function() {
      image.loaded += 1;
      if(image.loaded === 12) {
          init();
      }
  };
  return img;
}

const images = [0,image("./images/black_pawn.png"), image("./images/black_tower.png"),
 image("./images/black_knight.png"), image("./images/black_bishop.png"),
 image("./images/black_queen.png"), image("./images/black_king.png"),7,8,9,10,
 image("./images/white_pawn.png"), image("./images/white_tower.png"),
 image("./images/white_knight.png"), image("./images/white_bishop.png"),
 image("./images/white_queen.png"), image("./images/white_king.png")];

function init() {
    client.socketClient.connect(onMessageReceived);
}

function chessClient() {
    return {
        socketClient : new socketClient(),
        chessRenderer : undefined,
        team : undefined,
        id : -1,
        open : false,
        name : "",
        engine : undefined,
        mouseCoord : undefined,
        selectedPiece : undefined,
        lastMoves : undefined,
        lastX : undefined,
        lastY : undefined,
        time : 60,
        teamPlaying : -1,

        updateTimer : function() {
            if(this.teamPlaying === this.team) {
                this.time -= 1;
                if(this.time < 0) {
                    this.time = 0;
                }
                document.getElementById("timer").innerHTML = this.time;
            } else {
                this.time = BASE_TIME;
                document.getElementById("timer").innerHTML = "Waiting on opponents";
            }
        },

        handleClick : function() {
            this.chessRenderer.refreshGame(this.engine.board, images);
            let y = Math.floor(this.mouseCoord.y / tileSize);
            let x = Math.floor(this.mouseCoord.x / tileSize);
            let selected = this.engine.board[y][x];
            let moves = this.engine.getAllPossibleMoves(newCell(y, x));
            if(selected.color === this.team) {
                if(moves !== undefined) {
                    moves.forEach(function(move) {
                        this.chessRenderer.highlightTile(move.y, move.x, (this.engine.board[move.x][move.y].piece !== PieceType.EMPTY));
                    }, this);
                }
            }
            let voteOK = false;
            //if we clicked an empty tile or an enemy tile, and we had a piece selected, and the piece had possible moves
            if(selected.piece === PieceType.EMPTY || selected.color !== this.team) {
                if(this.selectedPiece.piece !== PieceType.EMPTY && this.selectedPiece.color === this.team) {
                    if(this.lastMoves !== undefined) {
                        //check if selected tile is part of the possible moves
                        this.lastMoves.forEach(function(move) {
                            if(move.x === y && move.y === x) {
                                voteOK = true;
                            }
                        });

                        if(voteOK) {
                            this.socketClient.sendMove(this.lastY, this.lastX, y, x);
                        }
                    }
                }
            }
            this.lastX = x;
            this.lastY = y;
            this.selectedPiece = selected;
            this.lastMoves = moves;
        },

        getMousePos : function(canvas, e) {
            let rect = canvas.getBoundingClientRect();
            return {
              x: e.clientX - rect.left,
              y: e.clientY - rect.top
            };
        },

        getTeamName : function(i) {
            if(i === PieceColor.WHITE) {
                return "white";
            } else {
                return "black";
            }
        },

        addToChat : function(sender, message) {
            document.getElementById("chat").innerHTML += `<br/><b>${sender}</b>: ${message}`;
            document.getElementById("chat").scrollTop = document.getElementById("chat").scrollHeight;
        },

        removePlayer : function(player) {
            this.addToChat("Server",`Player ${player.name} left`);
            let elem = document.getElementById(player.name);
            elem.parentNode.removeChild(elem);
        },

        addPlayer : function(player) {
            this.addToChat("Server", "Player "+player.name+" has joined team "+this.getTeamName(player.team));
            if(player.name !== this.name) {
                document.getElementById("info").innerHTML += "
"+player.name+"
";
            }
        },

        applyMove : function(mv) {
            this.engine.move(mv);
            this.chessRenderer.refreshGame(this.engine.board, images);
        },

        setPlayerList : function(lst) {
            lst.forEach(function(player) {
                document.getElementById("info").innerHTML += "
"+player.name+"
";
            }, this);
        },

        teamChange : function(team) {
            this.teamPlaying = team;
            this.addToChat("Server", `It is now ${this.getTeamName(team)}'s turn.`);
            document.getElementById("turn").innerHTML = this.getTeamName(team)+"'s turn";
        },

        handleChatMessage : function(e, tagId) {
            if(e.which === 13 || e.keyCode === 13) {
                let msg = document.getElementById(tagId).value;
                if(msg !== "") {
                    this.socketClient.socket.send(communication(this.socketClient.id, newMessage(messageType.CHAT, msg)));
                    document.getElementById(tagId).value = "";
                }
            }
        }
    };
}

function onMessageReceived(msg) {
    let message = JSON.parse(msg.data).message;
    switch(message.type) {
        case messageType.ID:
            client.socketClient.id = message.params;
            break;
        case messageType.PSEUDO_OK:
            nameOK();
            break;
        case messageType.PSEUDO_TAKEN:
            nameTaken();
            break;
        case messageType.NEW_PLAYER:
            let player = message.params;
            client.addPlayer(player);
            break;
        case messageType.INCOMING_CHAT:
            client.addToChat(message.params.sender, message.params.message);
            break;
        case messageType.BOARD:
            client.engine = getNewGame();
            client.engine.setBoard(message.params);
            client.chessRenderer.refreshGame(client.engine.board, images);
            break;
        case messageType.PLAYER_LEFT:
            let playerLeaving = message.params;
            client.removePlayer(playerLeaving);
            break;
        case messageType.TEAM:
            client.team = message.params;
            break;
        case messageType.MOVED:
            client.applyMove(message.params);
            break;
        case messageType.LIST:
            client.setPlayerList(message.params);
            break;
        case messageType.CHANGE:
            client.teamChange(message.params);
            break;
        default:
            console.log(message);
            break;
    }
}
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import qs from 'qs';

class Auth extends Component{
  constructor(props) {
   super(props);
   this.state = {
     username: '',
     password: ''
   };
   this.handleChange = this.handleChange.bind(this);
   this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
     const value = event.target.value;
     const name = event.target.name;
     this.setState({
       [name]: value
     });
   }

    async handleSubmit(event) {
    alert('Attempting to login: ' + this.state.username);
    event.preventDefault();
    const response = await fetch('https://serene-green.herokuapp.com/login',
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
      },
      body: qs.stringify(this.state)
    })
    // let pathEnd = response.url.slice(22);
    // console.log(pathEnd);
    this._reactInternalInstance._context.router.history.push(response, null);
   }

  render(){
    return(

        <form onSubmit={this.handleSubmit}>

Login

            Username:
            <input name="username" type="text" value={this.state.username} onChange={this.handleChange} />

            Password:
            <input name="password" type="text" value={this.state.password} onChange={this.handleChange} />

          <input type="submit" value="Submit" />
        </form>

    );
  }
}

export default Auth;
<commit_msg>tinkering with https<commit_after>import React, { Component } from 'react';
import qs from 'qs';

class Auth extends Component{
  constructor(props) {
   super(props);
   this.state = {
     username: '',
     password: ''
   };
   this.handleChange = this.handleChange.bind(this);
   this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
     const value = event.target.value;
     const name = event.target.name;
     this.setState({
       [name]: value
     });
   }

    async handleSubmit(event) {
    alert('Attempting to login: ' + this.state.username);
    event.preventDefault();
    const response = await fetch('https://serene-green.herokuapp.com/login',
    // const response = await fetch('http://localhost:5000/login',
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
      },
      body: qs.stringify(this.state)
    })
    // let pathEnd = response.url.slice(22);
    console.log(response.url);
    this._reactInternalInstance._context.router.history.push(response.url, null);
   }

  render(){
    return(

        <form onSubmit={this.handleSubmit}>

Login

            Username:
            <input name="username" type="text" value={this.state.username} onChange={this.handleChange} />

            Password:
            <input name="password" type="text" value={this.state.password} onChange={this.handleChange} />

          <input type="submit" value="Submit" />
        </form>

    );
  }
}

export default Auth;
<|endoftext|>


<commit_before>import Autolinker from 'autolinker';
import React from 'react';

const autolinker = new Autolinker({
  stripPrefix: false,
  stripTrailingSlash: false
});

export default function linkify(text) {
  let matches = autolinker.parseText(text);

  if (matches.length === 0) {
    return text;
  }

  const result = [];
  let pos = 0;
  matches = autolinker.compactMatches(matches);

  for (let i = 0; i < matches.length; i++) {
    const match = matches[i];

    if (match.getType() === 'url') {
      if (match.offset > pos) {
        if (typeof result[result.length - 1] === 'string') {
          result[result.length - 1] += text.slice(pos, match.offset);
        } else {
          result.push(text.slice(pos, match.offset));
        }
      }

      result.push(

          {match.matchedText}

      );
    } else if (typeof result[result.length - 1] === 'string') {
      result[result.length - 1] += text.slice(pos, match.offset + match.matchedText.length);
    } else {
      result.push(text.slice(pos, match.offset + match.matchedText.length));
    }

    pos = match.offset + match.matchedText.length;
  }

  if (pos < text.length) {
    if (typeof result[result.length - 1] === 'string') {
      result[result.length - 1] += text.slice(pos);
    } else {
      result.push(text.slice(pos));
    }
  }

  if (result.length === 1 && typeof result[0] === 'string') {
    return text;
  }

  return result;
}
<commit_msg>Dont return an array from linkify if the result is just a single node<commit_after>import Autolinker from 'autolinker';
import React from 'react';

const autolinker = new Autolinker({
  stripPrefix: false,
  stripTrailingSlash: false
});

export default function linkify(text) {
  let matches = autolinker.parseText(text);

  if (matches.length === 0) {
    return text;
  }

  const result = [];
  let pos = 0;
  matches = autolinker.compactMatches(matches);

  for (let i = 0; i < matches.length; i++) {
    const match = matches[i];

    if (match.getType() === 'url') {
      if (match.offset > pos) {
        if (typeof result[result.length - 1] === 'string') {
          result[result.length - 1] += text.slice(pos, match.offset);
        } else {
          result.push(text.slice(pos, match.offset));
        }
      }

      result.push(

          {match.matchedText}

      );
    } else if (typeof result[result.length - 1] === 'string') {
      result[result.length - 1] += text.slice(pos, match.offset + match.matchedText.length);
    } else {
      result.push(text.slice(pos, match.offset + match.matchedText.length));
    }

    pos = match.offset + match.matchedText.length;
  }

  if (pos < text.length) {
    if (typeof result[result.length - 1] === 'string') {
      result[result.length - 1] += text.slice(pos);
    } else {
      result.push(text.slice(pos));
    }
  }

  if (result.length === 1) {
    return result[0];
  }

  return result;
}
<|endoftext|>


<commit_before>Template.registrantsView.onCreated(function () {
  // Get reference to template instance
  const instance = this;

  // Subscribe to registrants for current user
  instance.subscribe("myRegistrants");
});

Template.registrantsView.helpers({
  'registrants': function () {
    return Registrants.find();
  }
});
<commit_msg>Use current user ID in collection helper<commit_after>Template.registrantsView.onCreated(function () {
  // Get reference to template instance
  const instance = this;

  // Subscribe to registrants for current user
  instance.subscribe("myRegistrants");
});

Template.registrantsView.helpers({
  'registrants': function () {
    const currentUserId = Meteor.userId();

    if (currentUserId) {
      return Registrants.find({'createdById': currentUserId});
    }
  }
});
<|endoftext|>


<commit_before>// * * * * * * * * * * * * * * * PLAYER TEMPLATE CALLBACKS  * * * * * * * * * * * * * *

Template.player.created = function() {
  Session.set('youtubePlayerInitialized', false);
};

Template.player.rendered = function() {
  if (Session.equals('youtubePlayerInitialized', false)) {
    $.getScript('https://www.youtube.com/iframe_api', function () {});
  }
};

// * * * * * * * * * * * * * * * YOUTUBE IFRAME PLAYER INITIALIZATION  * * * * * * * * * * * * * *

youtubePlayer=null;
onYouTubeIframeAPIReady = function() {
  youtubePlayer = new YT.Player('youtube-embed', {
    height: '480',
    width: '640',
    videoId: 'M7lc1UVf-VE',
    events: {
      'onReady': onPlayerReady,
      'onStateChange': onPlayerStateChange
    }
  });
  Session.set('youtubePlayerInitialized', true);
};

//  * * * * * * * * * * * * * * Callbacks  * * * * * * * * * * * * * *

function onPlayerReady(event) {
  // the footer is not yet loaded
}
function onPlayerStateChange(event) {
  $("#player-song-title").text(event.target.getVideoData().title);

  $(".player-control-button").removeClass("active");

  console.log("Player State: "+event.data);

  switch (event.data) {
    case -1: //unstarted
      $("#player-stop").addClass("active");
      break;
    case 0: //ended
      $("#player-stop").addClass("active");

      var id = Meteor.userId();
      console.log('song ended');
      Meteor.users.update({_id: id},
        {$inc: {'profile.playing.playlistIndex': 1}}
      );
      break;
    case 1: //playing
      $("#player-play").addClass("active");
      break;
    case 2: //paused
      $("#player-pause").addClass("active");
      break;
    case 3: //buffering
      break;
    case 5: //video cued
      break;
  }
}

// observe changes in the user.playing object
var lastPlaylistIndex, lastPlaylistId, lastVideoId;
Deps.autorun(function () {

  var user = Meteor.user();
  if (!user || !user.profile)
    return;

  var playing = user.profile.playing;
  if (!playing || playing.status == 'pause')
    return;

  // start the youtube video on pause,
  // on page load, both are undefined
  /*
  var startPaused = (!lastPlaylistIndex || !lastPlaylistId);
  if (startPaused) {
    console.log('starting paused');
    youtubePlayer.pauseVideo();
    return;
  }
  */

  var playlist = Playlists.findOne({_id: playing.playlist});
  if (!playlist)
    return;

  var videoId = playlist.songs[playing.playlistIndex].songId;
  if (!videoId)
    return;

  if (lastVideoId       == videoId /* &&
      lastPlaylistId    == playing.playlist &&
      lastPlaylistIndex == playing.playlistIndex */
  ) {
    console.log('not playing: same song');
    return;
  }
  lastVideoId       = videoId;
  lastPlaylistIndex = playing.playlistIndex;
  lastPlaylistId    = playing.playlist;

  if (typeof youtubePlayer == 'undefined') {
    console.warn('youtubePlayer undefined');
    return;
  }

  //load and play next video
  console.log('playing youtube video: ', videoId);
  if (youtubePlayer) {
	youtubePlayer.loadVideoById(videoId, 0, "large");
  }
});

// Sync player status with youtube player
var playerProgress = setInterval(function() {
  if(!youtubePlayer) {return;}
  if(Session.equals('youtubePlayerInitialized', true)) {
    if (youtubePlayer.getCurrentTime) {
      var percentage = 100*(youtubePlayer.getCurrentTime()/youtubePlayer.getDuration());
      $("#player-progressbar").width(percentage + "%");
      $("#player-song-duration").text((youtubePlayer.getDuration()-youtubePlayer.getCurrentTime()).toString().toHHMMSS());
    }
  }
}, 500);

//  * * * * * * * * * * * * * * Player TEMPLATE Controls  * * * * * * * * * * * * * *

Template.player.events = {
  'click a#player-play': function (e) {
    youtubePlayer.playVideo();
  },
  'click a#player-pause': function (e) {
    youtubePlayer.pauseVideo();
  },
  'click a#player-stop': function (e) {
    youtubePlayer.stopVideo();
  },
  'click #player-progressbar-container-overlay': function (e) {
    var fraction = e.offsetX / $(e.target).width();
    youtubePlayer.seekTo( youtubePlayer.getDuration() * fraction );
  },
};

String.prototype.toHHMMSS = function () {
    var sec_num = parseInt(this, 10); // don't forget the second param
    var hours   = Math.floor(sec_num / 3600);
    var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
    var seconds = sec_num - (hours * 3600) - (minutes * 60);

    if (hours   < 10) {hours   = "0"+hours;}
    if (minutes < 10) {minutes = "0"+minutes;}
    if (seconds < 10) {seconds = "0"+seconds;}
    var time    = hours+':'+minutes+':'+seconds;
    return time;
}

// always subscribe to the current playing playlist
Deps.autorun(function () {
  var user = Meteor.user();

  if (user &&
      user.profile &&
      user.profile.playing &&
      user.profile.playing.playlist) {
    Meteor.subscribe('playlist', user.profile.playing.playlist);

    // subscribe to songs
    var playlist = Playlists.findOne({_id: user.profile.playing.playlist});
    if (playlist) {
      var songs = playlist.songs;
      songs = _.pluck(songs, 'songId');
      check(songs, [string]);
      Meteor.subscribe('songs', songs);
    }
  }
});

Template.currentPlaylist.currentPlaylist = function () {
  var user = Meteor.user();
  if (!user) {
    return;
  }

  var profile = user.profile;
  if (!profile.playing) {
    console.warn('not yet playing any song!!!');
    return;
  }

  var playing = profile.playing;
  if (!playing) {
    return;
  }

  var playlist = Playlists.findOne({_id: playing.playlist});
  return {
    playlist: playlist,
    playlistId: playing.playlist,
    index: playing.playlistIndex,
    modified: playing.modified,
    status: playing.status,
  };
};

Template.queueSong.song = function() {
  return Songs.findOne({_id: ""+this});
};

Template.queueSong.isCurrent = function (playlist, index) {
  return playlist.songs[index] == ""+this;
};
<commit_msg>fix type in the footer<commit_after>// * * * * * * * * * * * * * * * PLAYER TEMPLATE CALLBACKS  * * * * * * * * * * * * * *

Template.player.created = function() {
  Session.set('youtubePlayerInitialized', false);
};

Template.player.rendered = function() {
  if (Session.equals('youtubePlayerInitialized', false)) {
    $.getScript('https://www.youtube.com/iframe_api', function () {});
  }
};

// * * * * * * * * * * * * * * * YOUTUBE IFRAME PLAYER INITIALIZATION  * * * * * * * * * * * * * *

youtubePlayer=null;
onYouTubeIframeAPIReady = function() {
  youtubePlayer = new YT.Player('youtube-embed', {
    height: '480',
    width: '640',
    videoId: 'M7lc1UVf-VE',
    events: {
      'onReady': onPlayerReady,
      'onStateChange': onPlayerStateChange
    }
  });
  Session.set('youtubePlayerInitialized', true);
};

//  * * * * * * * * * * * * * * Callbacks  * * * * * * * * * * * * * *

function onPlayerReady(event) {
  // the footer is not yet loaded
}
function onPlayerStateChange(event) {
  $("#player-song-title").text(event.target.getVideoData().title);

  $(".player-control-button").removeClass("active");

  console.log("Player State: "+event.data);

  switch (event.data) {
    case -1: //unstarted
      $("#player-stop").addClass("active");
      break;
    case 0: //ended
      $("#player-stop").addClass("active");

      var id = Meteor.userId();
      console.log('song ended');
      Meteor.users.update({_id: id},
        {$inc: {'profile.playing.playlistIndex': 1}}
      );
      break;
    case 1: //playing
      $("#player-play").addClass("active");
      break;
    case 2: //paused
      $("#player-pause").addClass("active");
      break;
    case 3: //buffering
      break;
    case 5: //video cued
      break;
  }
}

// observe changes in the user.playing object
var lastPlaylistIndex, lastPlaylistId, lastVideoId;
Deps.autorun(function () {

  var user = Meteor.user();
  if (!user || !user.profile)
    return;

  var playing = user.profile.playing;
  if (!playing || playing.status == 'pause')
    return;

  // start the youtube video on pause,
  // on page load, both are undefined
  /*
  var startPaused = (!lastPlaylistIndex || !lastPlaylistId);
  if (startPaused) {
    console.log('starting paused');
    youtubePlayer.pauseVideo();
    return;
  }
  */

  var playlist = Playlists.findOne({_id: playing.playlist});
  if (!playlist)
    return;

  var videoId = playlist.songs[playing.playlistIndex].songId;
  if (!videoId)
    return;

  if (lastVideoId       == videoId /* &&
      lastPlaylistId    == playing.playlist &&
      lastPlaylistIndex == playing.playlistIndex */
  ) {
    console.log('not playing: same song');
    return;
  }
  lastVideoId       = videoId;
  lastPlaylistIndex = playing.playlistIndex;
  lastPlaylistId    = playing.playlist;

  if (typeof youtubePlayer == 'undefined') {
    console.warn('youtubePlayer undefined');
    return;
  }

  //load and play next video
  console.log('playing youtube video: ', videoId);
  if (youtubePlayer) {
	youtubePlayer.loadVideoById(videoId, 0, "large");
  }
});

// Sync player status with youtube player
var playerProgress = setInterval(function() {
  if(!youtubePlayer) {return;}
  if(Session.equals('youtubePlayerInitialized', true)) {
    if (youtubePlayer.getCurrentTime) {
      var percentage = 100*(youtubePlayer.getCurrentTime()/youtubePlayer.getDuration());
      $("#player-progressbar").width(percentage + "%");
      $("#player-song-duration").text((youtubePlayer.getDuration()-youtubePlayer.getCurrentTime()).toString().toHHMMSS());
    }
  }
}, 500);

//  * * * * * * * * * * * * * * Player TEMPLATE Controls  * * * * * * * * * * * * * *

Template.player.events = {
  'click a#player-play': function (e) {
    youtubePlayer.playVideo();
  },
  'click a#player-pause': function (e) {
    youtubePlayer.pauseVideo();
  },
  'click a#player-stop': function (e) {
    youtubePlayer.stopVideo();
  },
  'click #player-progressbar-container-overlay': function (e) {
    var fraction = e.offsetX / $(e.target).width();
    youtubePlayer.seekTo( youtubePlayer.getDuration() * fraction );
  },
};

String.prototype.toHHMMSS = function () {
    var sec_num = parseInt(this, 10); // don't forget the second param
    var hours   = Math.floor(sec_num / 3600);
    var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
    var seconds = sec_num - (hours * 3600) - (minutes * 60);

    if (hours   < 10) {hours   = "0"+hours;}
    if (minutes < 10) {minutes = "0"+minutes;}
    if (seconds < 10) {seconds = "0"+seconds;}
    var time    = hours+':'+minutes+':'+seconds;
    return time;
}

// always subscribe to the current playing playlist
Deps.autorun(function () {
  var user = Meteor.user();

  if (user &&
      user.profile &&
      user.profile.playing &&
      user.profile.playing.playlist) {
    Meteor.subscribe('playlist', user.profile.playing.playlist);

    // subscribe to songs
    var playlist = Playlists.findOne({_id: user.profile.playing.playlist});
    if (playlist) {
      var songs = playlist.songs;
      songs = _.pluck(songs, 'songId');
      check(songs, [String]);
      Meteor.subscribe('songs', songs);
    }
  }
});

Template.currentPlaylist.currentPlaylist = function () {
  var user = Meteor.user();
  if (!user) {
    return;
  }

  var profile = user.profile;
  if (!profile.playing) {
    console.warn('not yet playing any song!!!');
    return;
  }

  var playing = profile.playing;
  if (!playing) {
    return;
  }

  var playlist = Playlists.findOne({_id: playing.playlist});
  return {
    playlist: playlist,
    playlistId: playing.playlist,
    index: playing.playlistIndex,
    modified: playing.modified,
    status: playing.status,
  };
};

Template.queueSong.song = function() {
  return Songs.findOne({_id: ""+this});
};

Template.queueSong.isCurrent = function (playlist, index) {
  return playlist.songs[index] == ""+this;
};
<|endoftext|>


<commit_before>import fs from 'fs';
import _ from 'lodash';
import initalSettings from './_initialSettings';
import createJSON from './_jsonCreator';

class Settings {
  constructor(jsonPrefix, wipeOldData) {
    this.PATH = createJSON(`${jsonPrefix || ''}.settings`);
    this.data = Object.assign({}, initalSettings);
    this.lastSync = 0;

    if (fs.existsSync(this.PATH) && !wipeOldData) {
      this._load();
    } else {
      this._save(true);
      // DEV: Handle windows users running as admin...
      fs.chmodSync(this.PATH, '777');
    }
    this.coupled = true;

    this._hooks = {};
  }

  uncouple() {
    this.coupled = false;
  }

  get(key, defaultValue = null) {
    if (!this.coupled) {
      this._load();
    }
    return typeof this.data[key] === 'undefined' ? defaultValue : this.data[key];
  }

  onChange(key, fn) {
    this._hooks[key] = this._hooks[key] || [];
    this._hooks[key].push(fn);
  }

  set(key, value) {
    if (this.coupled) {
      if (this._hooks[key] && this.data[key] !== value) {
        this._hooks[key].forEach((hookFn) => hookFn(value));
      }
      this.data[key] = value;
      this._save();
    }
  }

  _load(retryCount = 5) {
    let userSettings;
    try {
      userSettings = JSON.parse(fs.readFileSync(this.PATH, 'utf8'));
    } catch (e) {
      if (retryCount > 0) {
        setTimeout(this._load.bind(this, retryCount - 1), 10);
        Logger.error('Failed to load settings JSON file, retyring in 10 milliseconds');
        return;
      }
      userSettings = {};
      Logger.error('Failed to load settings JSON file, giving up and resetting');
    }
    this.data = _.extend({}, initalSettings, userSettings);
  }

  _save(force) {
    const now = (new Date).getTime();
    // During some save events (like resize) we need to queue the disk writes
    // so that we don't blast the disk every millisecond
    if ((now - this.lastSync > 250 || force)) {
      if (this.data) {
        try {
          fs.writeFileSync(this.PATH, JSON.stringify(this.data, null, 4));
        } catch (e) {
          if (this.saving) clearTimeout(this.saving);
          this.saving = setTimeout(this._save.bind(this), 275);
        }
      }
      if (this.saving) clearTimeout(this.saving);
    } else {
      if (this.saving) clearTimeout(this.saving);
      this.saving = setTimeout(this._save.bind(this), 275);
    }
    this.lastSync = now;
  }

  destroy() {
    this.data = null;
    fs.unlinkSync(this.PATH);
  }
}

export default Settings;
<commit_msg>Ensure logger is defined before trying to call it<commit_after>import fs from 'fs';
import _ from 'lodash';
import initalSettings from './_initialSettings';
import createJSON from './_jsonCreator';

class Settings {
  constructor(jsonPrefix, wipeOldData) {
    this.PATH = createJSON(`${jsonPrefix || ''}.settings`);
    this.data = Object.assign({}, initalSettings);
    this.lastSync = 0;

    if (fs.existsSync(this.PATH) && !wipeOldData) {
      this._load();
    } else {
      this._save(true);
      // DEV: Handle windows users running as admin...
      fs.chmodSync(this.PATH, '777');
    }
    this.coupled = true;

    this._hooks = {};
  }

  uncouple() {
    this.coupled = false;
  }

  get(key, defaultValue = null) {
    if (!this.coupled) {
      this._load();
    }
    return typeof this.data[key] === 'undefined' ? defaultValue : this.data[key];
  }

  onChange(key, fn) {
    this._hooks[key] = this._hooks[key] || [];
    this._hooks[key].push(fn);
  }

  set(key, value) {
    if (this.coupled) {
      if (this._hooks[key] && this.data[key] !== value) {
        this._hooks[key].forEach((hookFn) => hookFn(value));
      }
      this.data[key] = value;
      this._save();
    }
  }

  _load(retryCount = 5) {
    let userSettings;
    try {
      userSettings = JSON.parse(fs.readFileSync(this.PATH, 'utf8'));
    } catch (e) {
      if (retryCount > 0) {
        setTimeout(this._load.bind(this, retryCount - 1), 10);
        if (global.Logger) Logger.error('Failed to load settings JSON file, retyring in 10 milliseconds');
        return;
      }
      userSettings = {};
      if (global.Logger) Logger.error('Failed to load settings JSON file, giving up and resetting');
    }
    this.data = _.extend({}, initalSettings, userSettings);
  }

  _save(force) {
    const now = (new Date).getTime();
    // During some save events (like resize) we need to queue the disk writes
    // so that we don't blast the disk every millisecond
    if ((now - this.lastSync > 250 || force)) {
      if (this.data) {
        try {
          fs.writeFileSync(this.PATH, JSON.stringify(this.data, null, 4));
        } catch (e) {
          if (this.saving) clearTimeout(this.saving);
          this.saving = setTimeout(this._save.bind(this), 275);
        }
      }
      if (this.saving) clearTimeout(this.saving);
    } else {
      if (this.saving) clearTimeout(this.saving);
      this.saving = setTimeout(this._save.bind(this), 275);
    }
    this.lastSync = now;
  }

  destroy() {
    this.data = null;
    fs.unlinkSync(this.PATH);
  }
}

export default Settings;
<|endoftext|>


<commit_before>'use strict';

// ------- Imports -------------------------------------------------------------

const test = require('ava');
const chai = require('chai');
const Chance = require('chance');
const sinonChai = require('sinon-chai');

// ------- Internal imports ----------------------------------------------------

const RabbitMQBroker = require('../../../../../src/lib/brokers/RabbitMQ/RabbitMQBroker');
const MessageFactoryHelper = require('../../../../helpers/MessageFactoryHelper');
const UnitHooksHelper = require('../../../../helpers/UnitHooksHelper');

// ------- Init ----------------------------------------------------------------

const chance = new Chance();

chai.should();
chai.use(sinonChai);

// Prepare fakes for each test and clean up after them.
test.beforeEach(UnitHooksHelper.createFakeRabbitMQBroker);
test.afterEach.always(UnitHooksHelper.destroyFakeRabbitMQBroker);

// ------- Tests ---------------------------------------------------------------

/**
 * Dequeuer: constructor()
 */
test('RabbitMQBroker: Should implement Broker interface', () => {
  const broker = new RabbitMQBroker({});
  broker.should.respondTo('connect');
  broker.should.respondTo('disconnect');
  broker.should.respondTo('publishToRoute');
  broker.should.respondTo('subscribe');
  broker.should.respondTo('ack');
  broker.should.respondTo('nack');
  broker.should.respondTo('createQueue');
  broker.should.respondTo('purgeQueue');
  broker.should.respondTo('deleteQueue');
});

/**
 * RabbitMQBroker: connect()
 */
test('RabbitMQBroker.connect(): Should delegate connection to the connection manager and assert dependencies', async (t) => {
  // Set variables from the context.
  const { sandbox, broker } = t.context;

  // Stub connection manager's connect.
  const connectStub = sandbox.stub(broker.connectionManager, 'connect').resolves(true);
  const assertExchangesStub = sandbox.stub(broker, 'assertExchanges').resolves(true);

  // Execute the connect.
  const result = await broker.connect();
  result.should.be.true;

  // Ensure connection is delegated
  connectStub.should.have.been.calledOnce;

  // Ensure dependencies are asserted.
  assertExchangesStub.should.have.been.calledOnce;
});

/**
 * RabbitMQBroker: connect()
 */
test('RabbitMQBroker.connect(): Should fail on unsuccessful connection', async (t) => {
  // Set variables from the context.
  const { sandbox, broker } = t.context;

  // Stub connection manager's connect.
  const connectStub = sandbox.stub(broker.connectionManager, 'connect').resolves(false);
  const assertExchangesStub = sandbox.stub(broker, 'assertExchanges').resolves(true);

  // Execute the connect.
  const result = await broker.connect();
  result.should.be.false;

  // Ensure connection is delegated
  connectStub.should.have.been.calledOnce;

  // Ensure dependencies are asserted.
  assertExchangesStub.should.have.not.been.called;
});

/**
 * RabbitMQBroker: connect()
 */
test('RabbitMQBroker.connect(): Should fail on unsuccessful dependencies assertion', async (t) => {
  // Set variables from the context.
  const { sandbox, broker } = t.context;

  // Stub connection manager's connect.
  const connectStub = sandbox.stub(broker.connectionManager, 'connect').resolves(true);
  const assertExchangesStub = sandbox.stub(broker, 'assertExchanges').resolves(false);

  // Execute the connect.
  const result = await broker.connect();
  result.should.be.false;

  // Ensure connection is delegated
  connectStub.should.have.been.calledOnce;

  // Ensure dependencies are asserted.
  assertExchangesStub.should.have.been.calledOnce;
});

/**
 * RabbitMQBroker: disconnect()
 */
test('RabbitMQBroker.disconnect(): Should delegate disconnect to the connection manager', async (t) => {
  // Set variables from the context.
  const { sandbox, broker } = t.context;

  // Stub connection manager's connect.
  const disconnectStub = sandbox.stub(broker.connectionManager, 'disconnect').resolves(true);

  // Execute the connect.
  await broker.disconnect();

  // Ensure connection is delegated
  disconnectStub.should.have.been.calledOnce;
});

/**
 * RabbitMQBroker: ack()
 */
test('RabbitMQBroker.ack(): Should delegate message ack to amqplib', (t) => {
  // Set variables from the context.
  const { sandbox, channel, broker } = t.context;

  // Stub channel.sendImmediately() that sends all synchronous requests
  // the socket.
  // @see https://github.com/squaremo/amqp.node/blob/master/lib/channel.js#L63
  const sendImmediatelyStub = sandbox.stub(channel, 'sendImmediately').returns(42);

  // Spy on ack. We don't need to replace this completely, as it
  // uses channel.sendImmediately() to perform actual call.
  // @see https://github.com/squaremo/amqp.node/blob/master/lib/channel_model.js#L218
  const ackSpy = sandbox.spy(channel, 'ack');

  // Prepare fake message to acknowledgement.
  const message = MessageFactoryHelper.getFakeRabbitMessage();
  // AMQPLib's ack method implicitly depends on mesaage.fields.deliveryTag.
  // We'll ensure it works correctly by by spying on sendImmediately();
  message.fields.deliveryTag.should.be.not.empty;
  // Acknowledge the fake message.
  broker.ack(message);

  // Ack should be called.
  ackSpy.should.have.been.calledOnce;

  // Channel.ack() should pass message delivery tag to sendImmediately().
  sendImmediatelyStub.should.have.been.calledOnce;
  // Arg[0] = operation code, arg[1] = arguments object.
  const deliveryTagCallArgument = sendImmediatelyStub.firstCall.args[1].deliveryTag;
  message.fields.deliveryTag.should.be.equal(deliveryTagCallArgument);
});

/**
 * RabbitMQBroker: nack()
 */
test('RabbitMQBroker.nack(): Should delegate message nack to amqplib', (t) => {
  // Set variables from the context.
  const { sandbox, channel, broker } = t.context;

  // Stub channel.sendImmediately() that sends all synchronous requests
  // the socket.
  // @see https://github.com/squaremo/amqp.node/blob/master/lib/channel.js#L63
  const sendImmediatelyStub = sandbox.stub(channel, 'sendImmediately').returns(42);

  // Spy on reject. We don't need to replace this completely, as it
  // uses channel.sendImmediately() to perform actual call.
  // @see https://github.com/squaremo/amqp.node/blob/master/lib/channel_model.js#L243
  const rejectSpy = sandbox.spy(channel, 'reject');

  // Prepare fake message to acknowledgement.
  const message = MessageFactoryHelper.getFakeRabbitMessage();
  // AMQPLib's reject() method implicitly depends on mesaage.fields.deliveryTag.
  // We'll ensure it works correctly by by spying on sendImmediately();
  message.fields.deliveryTag.should.be.not.empty;
  // Negative acknowledge the fake message.
  broker.nack(message);

  // Reject should be called.
  rejectSpy.should.have.been.calledOnce;

  // Channel.reject() should pass message delivery tag to sendImmediately().
  sendImmediatelyStub.should.have.been.calledOnce;
  // Arg[0] = operation code, arg[1] = arguments object.
  const deliveryTagCallArgument = sendImmediatelyStub.firstCall.args[1].deliveryTag;
  message.fields.deliveryTag.should.be.equal(deliveryTagCallArgument);
});

/**
 * RabbitMQBroker: createQueue()
 */
test('RabbitMQBroker.createQueue(): Happy path', async (t) => {
  // Set variables from the context.
  const { sandbox, channel, broker } = t.context;

  // Define test parameters.
  const queueName = chance.word();
  const numberOfRoutes = 5;
  const queueRoutes = chance.n(chance.word, numberOfRoutes);

  // Stub amqplib's assertQueue().
  // Response example take from the docs.
  // @see http://www.squaremobius.net/amqp.node/channel_api.html#channel_assertQueue
  const assertQueueStub = sandbox.stub(channel, 'assertQueue').resolves({
    queue: queueName,
    messageCount: 0,
    consumerCount: 0,
  });

  // Stub amqplib's bindQueue().
  // The server reply resolves to an empty object.
  // @see http://www.squaremobius.net/amqp.node/channel_api.html#channel_bindExchange
  const bindQueueStub = sandbox.stub(channel, 'bindQueue').resolves({});

  // Execute the function.
  const result = await broker.createQueue(queueName, queueRoutes);
  result.should.be.true;

  // Ensure queue assertion has been called.
  assertQueueStub.should.have.been.calledOnce;

  // Ensure the queue has been bound to the topic exchange on expected routes.
  bindQueueStub.should.have.callCount(numberOfRoutes);
  for (const [queueArg, exchangeArg, routeArg] of bindQueueStub.args) {
    queueArg.should.equal(queueName);
    exchangeArg.should.equal(broker.topicExchange);
    routeArg.should.be.oneOf(queueRoutes);
  }
});

/**
 * RabbitMQBroker: purgeQueue()
 */
test('RabbitMQBroker.purgeQueue(): Happy path', async (t) => {
  // Set variables from the context.
  const { sandbox, channel, broker } = t.context;

  // Define test parameters.
  const queueName = chance.word();
  const messageCount = chance.integer({ min: 1 });

  // Stub amqplib's purgeQueue().
  // Response example take from the docs.
  // http://www.squaremobius.net/amqp.node/channel_api.html#channel_purgeQueue
  const purgeQueueStub = sandbox.stub(channel, 'purgeQueue').resolves({
    messageCount,
  });

  // Execute the function.
  const result = await broker.purgeQueue(queueName);
  result.should.equal(messageCount);

  // Ensure queue purging has been correctly delegated to amqplib.
  purgeQueueStub.should.have.been.calledOnce;
  purgeQueueStub.should.have.been.calledWithExactly(queueName);
});

/**
 * RabbitMQBroker: deleteQueue()
 */
test('RabbitMQBroker.deleteQueue(): Happy path', async (t) => {
  // Set variables from the context.
  const { sandbox, channel, broker } = t.context;

  // Define test parameters.
  const queueName = chance.word();
  const messageCount = chance.integer({ min: 1 });

  // Stub amqplib's deleteQueue().
  // Response example take from the docs.
  // http://www.squaremobius.net/amqp.node/channel_api.html#channel_deleteQueue
  const deleteQueueStub = sandbox.stub(channel, 'deleteQueue').resolves({
    messageCount,
  });

  // Execute the function.
  const result = await broker.deleteQueue(queueName);
  result.should.equal(messageCount);

  // Ensure queue deletion has been correctly delegated to amqplib.
  deleteQueueStub.should.have.been.calledOnce;
  deleteQueueStub.should.have.been.calledWithExactly(queueName, {
    ifUnused: false,
    ifEmpty: false,
  });
});

/**
 * RabbitMQBroker: publishToRoute()
 */
test('RabbitMQBroker.publishToRoute(): Happy path', (t) => {
  // Set variables from the context.
  const { sandbox, channel, broker } = t.context;

  // Define test parameters.
  const routeName = chance.word();
  const message = MessageFactoryHelper.getRandomMessage(true);

  // Stub amqplib's publish().
  // Response example take from the docs.
  // http://www.squaremobius.net/amqp.node/channel_api.html#channel_publish
  const publishStub = sandbox.stub(channel, 'publish').returns(true);

  // Execute the function.
  broker.publishToRoute(routeName, message);

  // Check that the message publishing has been correctly delegated to amqplib.
  publishStub.should.have.been.calledOnce;
  const [exchangeArg, routeArg, bufferArg, optionsArg] = publishStub.firstCall.args;
  exchangeArg.should.be.equal(broker.topicExchange);
  routeArg.should.be.equal(routeName);
  bufferArg.toString().should.be.equal(message.toString());
  optionsArg.should.be.have.property('mandatory', true);
  optionsArg.should.be.have.property('persistent', true);
});

/**
 * RabbitMQBroker: subscribe()
 */
test('RabbitMQBroker.subscribe(): Happy path', async (t) => {
  // Set variables from the context.
  const { sandbox, channel, broker } = t.context;

  // Define test parameters.
  const queueName = chance.word();
  const consumerTag = chance.word();
  const callback = () => true;

  // Stub amqplib's consume().
  // Response example take from the docs.
  // http://www.squaremobius.net/amqp.node/channel_api.html#channel_consume
  const consumeStub = sandbox.stub(channel, 'consume').resolves({
    consumerTag,
  });

  // Execute the function.
  const result = await broker.subscribe(queueName, callback, consumerTag);
  result.should.be.equal(consumerTag);

  // Check that the callback subscription has been correctly delegated to amqplib.
  consumeStub.should.have.been.calledOnce;
  const [queueArg, callbackArg, optionsArg] = consumeStub.firstCall.args;
  queueArg.should.be.equal(queueName);
  callbackArg.should.be.equal(callback);
  callbackArg.should.be.equal(callback);
  optionsArg.should.be.have.property('noAck', false);
  optionsArg.should.be.have.property('exclusive', false);
  optionsArg.should.be.have.property('consumerTag', consumerTag);
});

/**
 * RabbitMQBroker: subscribe()
 */
test('RabbitMQBroker.subscribe(): Callback is executed on new message', async (t) => {
  // Set variables from the context.
  const { sandbox, channel, broker } = t.context;

  // Define test parameters.
  const queueName = chance.word();
  const consumerTag = chance.word();
  const dequeuerSpy = sandbox.spy(rabbitMessage => rabbitMessage);

  // Stub amqplib's consume().
  // @see https://github.com/squaremo/amqp.node/blob/master/lib/callback_model.js#L186
  // Make it register consumer without actually performing RPC to rabbit.
  const consumeStub = sandbox.stub(channel, 'consume').callsFake(async function () {
    // `this` is amqplib's Channel.
    this.registerConsumer(consumerTag, dequeuerSpy);
    return consumerTag;
  });

  // Execute the function.
  await broker.subscribe(queueName, dequeuerSpy);
  consumeStub.should.have.been.calledOnce;

  // Imitate broker senfing a message to the consumer.
  const message = MessageFactoryHelper.getFakeRabbitMessage(false, consumerTag);
  channel.emit('delivery', message);

  // Ensure the callback recieved the message. So cool.
  dequeuerSpy.should.have.been.calledOnce;
  const [messageArg] = dequeuerSpy.firstCall.args;
  messageArg.should.be.deep.equal(message);
});

// ------- End -----------------------------------------------------------------
<commit_msg>Ensure assertExchanges creates all exchanges<commit_after>'use strict';

// ------- Imports -------------------------------------------------------------

const test = require('ava');
const chai = require('chai');
const Chance = require('chance');
const sinonChai = require('sinon-chai');

// ------- Internal imports ----------------------------------------------------

const RabbitMQBroker = require('../../../../../src/lib/brokers/RabbitMQ/RabbitMQBroker');
const MessageFactoryHelper = require('../../../../helpers/MessageFactoryHelper');
const UnitHooksHelper = require('../../../../helpers/UnitHooksHelper');

// ------- Init ----------------------------------------------------------------

const chance = new Chance();

chai.should();
chai.use(sinonChai);

// Prepare fakes for each test and clean up after them.
test.beforeEach(UnitHooksHelper.createFakeRabbitMQBroker);
test.afterEach.always(UnitHooksHelper.destroyFakeRabbitMQBroker);

// ------- Tests ---------------------------------------------------------------

/**
 * Dequeuer: constructor()
 */
test('RabbitMQBroker: Should implement Broker interface', () => {
  const broker = new RabbitMQBroker({});
  broker.should.respondTo('connect');
  broker.should.respondTo('disconnect');
  broker.should.respondTo('publishToRoute');
  broker.should.respondTo('subscribe');
  broker.should.respondTo('ack');
  broker.should.respondTo('nack');
  broker.should.respondTo('createQueue');
  broker.should.respondTo('purgeQueue');
  broker.should.respondTo('deleteQueue');
});

/**
 * RabbitMQBroker: connect()
 */
test('RabbitMQBroker.connect(): Should delegate connection to the connection manager and assert dependencies', async (t) => {
  // Set variables from the context.
  const { sandbox, broker } = t.context;

  // Stub connection manager's connect.
  const connectStub = sandbox.stub(broker.connectionManager, 'connect').resolves(true);
  const assertExchangesStub = sandbox.stub(broker, 'assertExchanges').resolves(true);

  // Execute the connect.
  const result = await broker.connect();
  result.should.be.true;

  // Ensure connection is delegated
  connectStub.should.have.been.calledOnce;

  // Ensure dependencies are asserted.
  assertExchangesStub.should.have.been.calledOnce;
});

/**
 * RabbitMQBroker: assertExchanges()
 */
test('RabbitMQBroker.assertExchanges(): Should assert all dependencies', async (t) => {
  // Set variables from the context.
  const { sandbox, channel, broker } = t.context;

  // // Define test parameters.
  // const queueName = chance.word();
  // const numberOfRoutes = 5;
  // const queueRoutes = chance.n(chance.word, numberOfRoutes);

  // Stub channel.assertExchange()
  // @see https://github.com/squaremo/amqp.node/blob/master/lib/channel.js#L63
  const assertExchangeStub = sandbox.stub(channel, 'assertExchange')
    .onFirstCall().resolves({ exchange: broker.topicExchange });

  // Execute the connect.
  const result = await broker.assertExchanges();
  result.should.be.true;

  // Ensure all exchanges have been created.
  assertExchangeStub.should.have.callCount(1);

  // Ensure dependencies are asserted.
  assertExchangeStub.getCall(0).args.should.deep.equal([
    broker.topicExchange,
    'topic',
  ]);
});

/**
 * RabbitMQBroker: connect()
 */
test('RabbitMQBroker.connect(): Should fail on unsuccessful connection', async (t) => {
  // Set variables from the context.
  const { sandbox, broker } = t.context;

  // Stub connection manager's connect.
  const connectStub = sandbox.stub(broker.connectionManager, 'connect').resolves(false);
  const assertExchangesStub = sandbox.stub(broker, 'assertExchanges').resolves(true);

  // Execute the connect.
  const result = await broker.connect();
  result.should.be.false;

  // Ensure connection is delegated
  connectStub.should.have.been.calledOnce;

  // Ensure dependencies are asserted.
  assertExchangesStub.should.have.not.been.called;
});

/**
 * RabbitMQBroker: connect()
 */
test('RabbitMQBroker.connect(): Should fail on unsuccessful dependencies assertion', async (t) => {
  // Set variables from the context.
  const { sandbox, broker } = t.context;

  // Stub connection manager's connect.
  const connectStub = sandbox.stub(broker.connectionManager, 'connect').resolves(true);
  const assertExchangesStub = sandbox.stub(broker, 'assertExchanges').resolves(false);

  // Execute the connect.
  const result = await broker.connect();
  result.should.be.false;

  // Ensure connection is delegated
  connectStub.should.have.been.calledOnce;

  // Ensure dependencies are asserted.
  assertExchangesStub.should.have.been.calledOnce;
});

/**
 * RabbitMQBroker: disconnect()
 */
test('RabbitMQBroker.disconnect(): Should delegate disconnect to the connection manager', async (t) => {
  // Set variables from the context.
  const { sandbox, broker } = t.context;

  // Stub connection manager's connect.
  const disconnectStub = sandbox.stub(broker.connectionManager, 'disconnect').resolves(true);

  // Execute the connect.
  await broker.disconnect();

  // Ensure connection is delegated
  disconnectStub.should.have.been.calledOnce;
});

/**
 * RabbitMQBroker: ack()
 */
test('RabbitMQBroker.ack(): Should delegate message ack to amqplib', (t) => {
  // Set variables from the context.
  const { sandbox, channel, broker } = t.context;

  // Stub channel.sendImmediately() that sends all synchronous requests
  // the socket.
  // @see https://github.com/squaremo/amqp.node/blob/master/lib/channel.js#L63
  const sendImmediatelyStub = sandbox.stub(channel, 'sendImmediately').returns(42);

  // Spy on ack. We don't need to replace this completely, as it
  // uses channel.sendImmediately() to perform actual call.
  // @see https://github.com/squaremo/amqp.node/blob/master/lib/channel_model.js#L218
  const ackSpy = sandbox.spy(channel, 'ack');

  // Prepare fake message to acknowledgement.
  const message = MessageFactoryHelper.getFakeRabbitMessage();
  // AMQPLib's ack method implicitly depends on mesaage.fields.deliveryTag.
  // We'll ensure it works correctly by by spying on sendImmediately();
  message.fields.deliveryTag.should.be.not.empty;
  // Acknowledge the fake message.
  broker.ack(message);

  // Ack should be called.
  ackSpy.should.have.been.calledOnce;

  // Channel.ack() should pass message delivery tag to sendImmediately().
  sendImmediatelyStub.should.have.been.calledOnce;
  // Arg[0] = operation code, arg[1] = arguments object.
  const deliveryTagCallArgument = sendImmediatelyStub.firstCall.args[1].deliveryTag;
  message.fields.deliveryTag.should.be.equal(deliveryTagCallArgument);
});

/**
 * RabbitMQBroker: nack()
 */
test('RabbitMQBroker.nack(): Should delegate message nack to amqplib', (t) => {
  // Set variables from the context.
  const { sandbox, channel, broker } = t.context;

  // Stub channel.sendImmediately() that sends all synchronous requests
  // the socket.
  // @see https://github.com/squaremo/amqp.node/blob/master/lib/channel.js#L63
  const sendImmediatelyStub = sandbox.stub(channel, 'sendImmediately').returns(42);

  // Spy on reject. We don't need to replace this completely, as it
  // uses channel.sendImmediately() to perform actual call.
  // @see https://github.com/squaremo/amqp.node/blob/master/lib/channel_model.js#L243
  const rejectSpy = sandbox.spy(channel, 'reject');

  // Prepare fake message to acknowledgement.
  const message = MessageFactoryHelper.getFakeRabbitMessage();
  // AMQPLib's reject() method implicitly depends on mesaage.fields.deliveryTag.
  // We'll ensure it works correctly by by spying on sendImmediately();
  message.fields.deliveryTag.should.be.not.empty;
  // Negative acknowledge the fake message.
  broker.nack(message);

  // Reject should be called.
  rejectSpy.should.have.been.calledOnce;

  // Channel.reject() should pass message delivery tag to sendImmediately().
  sendImmediatelyStub.should.have.been.calledOnce;
  // Arg[0] = operation code, arg[1] = arguments object.
  const deliveryTagCallArgument = sendImmediatelyStub.firstCall.args[1].deliveryTag;
  message.fields.deliveryTag.should.be.equal(deliveryTagCallArgument);
});

/**
 * RabbitMQBroker: createQueue()
 */
test('RabbitMQBroker.createQueue(): Happy path', async (t) => {
  // Set variables from the context.
  const { sandbox, channel, broker } = t.context;

  // Define test parameters.
  const queueName = chance.word();
  const numberOfRoutes = 5;
  const queueRoutes = chance.n(chance.word, numberOfRoutes);

  // Stub amqplib's assertQueue().
  // Response example take from the docs.
  // @see http://www.squaremobius.net/amqp.node/channel_api.html#channel_assertQueue
  const assertQueueStub = sandbox.stub(channel, 'assertQueue').resolves({
    queue: queueName,
    messageCount: 0,
    consumerCount: 0,
  });

  // Stub amqplib's bindQueue().
  // The server reply resolves to an empty object.
  // @see http://www.squaremobius.net/amqp.node/channel_api.html#channel_bindExchange
  const bindQueueStub = sandbox.stub(channel, 'bindQueue').resolves({});

  // Execute the function.
  const result = await broker.createQueue(queueName, queueRoutes);
  result.should.be.true;

  // Ensure queue assertion has been called.
  assertQueueStub.should.have.been.calledOnce;

  // Ensure the queue has been bound to the topic exchange on expected routes.
  bindQueueStub.should.have.callCount(numberOfRoutes);
  for (const [queueArg, exchangeArg, routeArg] of bindQueueStub.args) {
    queueArg.should.equal(queueName);
    exchangeArg.should.equal(broker.topicExchange);
    routeArg.should.be.oneOf(queueRoutes);
  }
});

/**
 * RabbitMQBroker: purgeQueue()
 */
test('RabbitMQBroker.purgeQueue(): Happy path', async (t) => {
  // Set variables from the context.
  const { sandbox, channel, broker } = t.context;

  // Define test parameters.
  const queueName = chance.word();
  const messageCount = chance.integer({ min: 1 });

  // Stub amqplib's purgeQueue().
  // Response example take from the docs.
  // http://www.squaremobius.net/amqp.node/channel_api.html#channel_purgeQueue
  const purgeQueueStub = sandbox.stub(channel, 'purgeQueue').resolves({
    messageCount,
  });

  // Execute the function.
  const result = await broker.purgeQueue(queueName);
  result.should.equal(messageCount);

  // Ensure queue purging has been correctly delegated to amqplib.
  purgeQueueStub.should.have.been.calledOnce;
  purgeQueueStub.should.have.been.calledWithExactly(queueName);
});

/**
 * RabbitMQBroker: deleteQueue()
 */
test('RabbitMQBroker.deleteQueue(): Happy path', async (t) => {
  // Set variables from the context.
  const { sandbox, channel, broker } = t.context;

  // Define test parameters.
  const queueName = chance.word();
  const messageCount = chance.integer({ min: 1 });

  // Stub amqplib's deleteQueue().
  // Response example take from the docs.
  // http://www.squaremobius.net/amqp.node/channel_api.html#channel_deleteQueue
  const deleteQueueStub = sandbox.stub(channel, 'deleteQueue').resolves({
    messageCount,
  });

  // Execute the function.
  const result = await broker.deleteQueue(queueName);
  result.should.equal(messageCount);

  // Ensure queue deletion has been correctly delegated to amqplib.
  deleteQueueStub.should.have.been.calledOnce;
  deleteQueueStub.should.have.been.calledWithExactly(queueName, {
    ifUnused: false,
    ifEmpty: false,
  });
});

/**
 * RabbitMQBroker: publishToRoute()
 */
test('RabbitMQBroker.publishToRoute(): Happy path', (t) => {
  // Set variables from the context.
  const { sandbox, channel, broker } = t.context;

  // Define test parameters.
  const routeName = chance.word();
  const message = MessageFactoryHelper.getRandomMessage(true);

  // Stub amqplib's publish().
  // Response example take from the docs.
  // http://www.squaremobius.net/amqp.node/channel_api.html#channel_publish
  const publishStub = sandbox.stub(channel, 'publish').returns(true);

  // Execute the function.
  broker.publishToRoute(routeName, message);

  // Check that the message publishing has been correctly delegated to amqplib.
  publishStub.should.have.been.calledOnce;
  const [exchangeArg, routeArg, bufferArg, optionsArg] = publishStub.firstCall.args;
  exchangeArg.should.be.equal(broker.topicExchange);
  routeArg.should.be.equal(routeName);
  bufferArg.toString().should.be.equal(message.toString());
  optionsArg.should.be.have.property('mandatory', true);
  optionsArg.should.be.have.property('persistent', true);
});

/**
 * RabbitMQBroker: subscribe()
 */
test('RabbitMQBroker.subscribe(): Happy path', async (t) => {
  // Set variables from the context.
  const { sandbox, channel, broker } = t.context;

  // Define test parameters.
  const queueName = chance.word();
  const consumerTag = chance.word();
  const callback = () => true;

  // Stub amqplib's consume().
  // Response example take from the docs.
  // http://www.squaremobius.net/amqp.node/channel_api.html#channel_consume
  const consumeStub = sandbox.stub(channel, 'consume').resolves({
    consumerTag,
  });

  // Execute the function.
  const result = await broker.subscribe(queueName, callback, consumerTag);
  result.should.be.equal(consumerTag);

  // Check that the callback subscription has been correctly delegated to amqplib.
  consumeStub.should.have.been.calledOnce;
  const [queueArg, callbackArg, optionsArg] = consumeStub.firstCall.args;
  queueArg.should.be.equal(queueName);
  callbackArg.should.be.equal(callback);
  callbackArg.should.be.equal(callback);
  optionsArg.should.be.have.property('noAck', false);
  optionsArg.should.be.have.property('exclusive', false);
  optionsArg.should.be.have.property('consumerTag', consumerTag);
});

/**
 * RabbitMQBroker: subscribe()
 */
test('RabbitMQBroker.subscribe(): Callback is executed on new message', async (t) => {
  // Set variables from the context.
  const { sandbox, channel, broker } = t.context;

  // Define test parameters.
  const queueName = chance.word();
  const consumerTag = chance.word();
  const dequeuerSpy = sandbox.spy(rabbitMessage => rabbitMessage);

  // Stub amqplib's consume().
  // @see https://github.com/squaremo/amqp.node/blob/master/lib/callback_model.js#L186
  // Make it register consumer without actually performing RPC to rabbit.
  const consumeStub = sandbox.stub(channel, 'consume').callsFake(async function () {
    // `this` is amqplib's Channel.
    this.registerConsumer(consumerTag, dequeuerSpy);
    return consumerTag;
  });

  // Execute the function.
  await broker.subscribe(queueName, dequeuerSpy);
  consumeStub.should.have.been.calledOnce;

  // Imitate broker senfing a message to the consumer.
  const message = MessageFactoryHelper.getFakeRabbitMessage(false, consumerTag);
  channel.emit('delivery', message);

  // Ensure the callback recieved the message. So cool.
  dequeuerSpy.should.have.been.calledOnce;
  const [messageArg] = dequeuerSpy.firstCall.args;
  messageArg.should.be.deep.equal(message);
});

// ------- End -----------------------------------------------------------------
<|endoftext|>


<commit_before>/**Copyright 2019 Google LLC
Licensed 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
    https://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.*/

// call docCount servlet for no of documents in a index
const getCount = async (index, fileType) => {
    const params = new URLSearchParams();
    params.append(FILE_NAME, index);
    params.append(FILE_TYPE, fileType);
    const response = await fetch(GET_COUNT, {
        method: POST,
        body: params
    });
    const count = await response.json();
    return count;
}

// call stackTrace servlet for stack trace of a error
const callStackTraceServlet = async (logLineNo, fileName) => {
    const params = new URLSearchParams();
    params.append(LOG_LINE_NUMBER, logLineNo);
    params.append(FILE_NAME, fileName);
    const response = await fetch(STACK_TRACE, {
        method: POST,
        body: params
    });
    const stackTrace = await response.json();
    return stackTrace;
}

// fetch logs/errors/search results from pagination servlet
const callPaginationServlet = async(fileName, fileType, searchString, pageSpecs) => {
    const params = new URLSearchParams();
    params.append(START, pageSpecs.START);
    params.append(SIZE,  pageSpecs.SIZE);
    params.append(SEARCH_STRING, searchString);
    params.append(FILE_TYPE, fileType);
    params.append(FILE_NAME, fileName);
    const response = await fetch(PAGINATION, {
        method: POST,
        body: params
    });
    const fetchedData = await response.json();
    return fetchedData;
}

// delete all the
const deleteIndices = async() => {
    await fetch(DELETE, {
        method: POST
});
    alert("Data Deleted");
}<commit_msg>change alert message<commit_after>/**Copyright 2019 Google LLC
Licensed 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
    https://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.*/

// call docCount servlet for no of documents in a index
const getCount = async (index, fileType) => {
    const params = new URLSearchParams();
    params.append(FILE_NAME, index);
    params.append(FILE_TYPE, fileType);
    const response = await fetch(GET_COUNT, {
        method: POST,
        body: params
    });
    const count = await response.json();
    return count;
}

// call stackTrace servlet for stack trace of a error
const callStackTraceServlet = async (logLineNo, fileName) => {
    const params = new URLSearchParams();
    params.append(LOG_LINE_NUMBER, logLineNo);
    params.append(FILE_NAME, fileName);
    const response = await fetch(STACK_TRACE, {
        method: POST,
        body: params
    });
    const stackTrace = await response.json();
    return stackTrace;
}

// fetch logs/errors/search results from pagination servlet
const callPaginationServlet = async(fileName, fileType, searchString, pageSpecs) => {
    const params = new URLSearchParams();
    params.append(START, pageSpecs.START);
    params.append(SIZE,  pageSpecs.SIZE);
    params.append(SEARCH_STRING, searchString);
    params.append(FILE_TYPE, fileType);
    params.append(FILE_NAME, fileName);
    const response = await fetch(PAGINATION, {
        method: POST,
        body: params
    });
    const fetchedData = await response.json();
    return fetchedData;
}

// delete all the
const deleteIndices = async() => {
    await fetch(DELETE, {
        method: POST
});
    alert("Log files deleted");
}<|endoftext|>


<commit_before>var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var AdvancedVariables = require('postcss-advanced-variables');
var merge = require('webpack-merge');
var prettyjson = require('prettyjson');
var config = require('../src/utils/config');

module.exports = function(env) {
	var isProd = env === 'production';

	var includes = [
		__dirname,
		config.rootDir
	];
	var codeMirrorPath = path.join(__dirname, '../node_modules/react-codemirror/node_modules/codemirror');
	var webpackConfig = {
		output: {
			path: config.styleguideDir,
			filename: 'build/bundle.js'
		},
		resolve: {
			root: [
				__dirname
			],
			alias: {
				'codemirror': codeMirrorPath
			}
		},
		resolveLoader: {
			modulesDirectories: [
				'loaders',
				'node_modules'
			]
		},
		plugins: [
			new HtmlWebpackPlugin({
				title: config.title,
				template: './src/templates/index.html',
				inject: true
			}),
			new webpack.DefinePlugin({
				'process.env': {
					NODE_ENV: JSON.stringify(env)
				}
			})
		],
		module: {
			loaders: [
				{
					test: /\.js$/,
					include: includes,
					loader: 'babel'
				}
			]
		},
		postcss: function() {
			return [
				AdvancedVariables
			];
		}
	};

	var entryScript = './src/index';

	if (isProd) {
		webpackConfig = merge(webpackConfig, {
			entry: [
				entryScript
			],
			devtool: false,
			debug: false,
			cache: false,
			plugins: [
				new webpack.optimize.UglifyJsPlugin({
					compress: {
						warnings: false
					},
					output: {
						comments: false
					},
					mangle: false
				}),
				new webpack.optimize.DedupePlugin(),
				new ExtractTextPlugin('build/styles.css', {
					allChunks: true
				})
			],
			module: {
				loaders: [
					{
						test: /\.css$/,
						include: codeMirrorPath,
						loader: ExtractTextPlugin.extract('style', 'css')
					},
					{
						test: /\.css$/,
						include: includes,
						loader: ExtractTextPlugin.extract('style', 'css?modules&-minimize&importLoaders=1!postcss')
					}
				]
			}
		});
	}
	else {
		webpackConfig = merge(webpackConfig, {
			entry: [
				'webpack-hot-middleware/client',
				entryScript
			],
			debug: true,
			cache: true,
			devtool: 'eval-source-map',
			stats: {
				colors: true,
				reasons: true
			},
			plugins: [
				new webpack.optimize.OccurenceOrderPlugin(),
				new webpack.HotModuleReplacementPlugin(),
				new webpack.NoErrorsPlugin()
			],
			module: {
				loaders: [
					{
						test: /\.css$/,
						include: codeMirrorPath,
						loader: 'style!css'
					},
					{
						test: /\.css$/,
						include: includes,
						loader: 'style!css?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!postcss'
					}
				]
			}
		});
	}

	if (config.updateWebpackConfig) {
		webpackConfig = config.updateWebpackConfig(webpackConfig, env);
	}

	if (config.verbose) {
		console.log();
		console.log('Using Webpack config:');
		console.log(prettyjson.render(webpackConfig));
		console.log();
	}

	return webpackConfig;
};
<commit_msg>Make Webpack import modules from the Styleguidist instead of the host project (fix #5).<commit_after>var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var AdvancedVariables = require('postcss-advanced-variables');
var merge = require('webpack-merge');
var prettyjson = require('prettyjson');
var config = require('../src/utils/config');

module.exports = function(env) {
	var isProd = env === 'production';

	var includes = [
		__dirname,
		config.rootDir
	];
	var codeMirrorPath = path.join(__dirname, '../node_modules/react-codemirror/node_modules/codemirror');
	var webpackConfig = {
		output: {
			path: config.styleguideDir,
			filename: 'build/bundle.js'
		},
		resolve: {
			root: path.join(__dirname),
			alias: {
				'codemirror': codeMirrorPath
			}
		},
		resolveLoader: {
			modulesDirectories: [
				path.resolve(__dirname, '../loaders'),
				path.resolve(__dirname, '../node_modules')
			]
		},
		plugins: [
			new HtmlWebpackPlugin({
				title: config.title,
				template: './src/templates/index.html',
				inject: true
			}),
			new webpack.DefinePlugin({
				'process.env': {
					NODE_ENV: JSON.stringify(env)
				}
			})
		],
		module: {
			loaders: [
				{
					test: /\.js$/,
					include: includes,
					loader: 'babel'
				}
			]
		},
		postcss: function() {
			return [
				AdvancedVariables
			];
		}
	};

	var entryScript = path.join(__dirname, 'index');

	if (isProd) {
		webpackConfig = merge(webpackConfig, {
			entry: [
				entryScript
			],
			devtool: false,
			debug: false,
			cache: false,
			plugins: [
				new webpack.optimize.UglifyJsPlugin({
					compress: {
						warnings: false
					},
					output: {
						comments: false
					},
					mangle: false
				}),
				new webpack.optimize.DedupePlugin(),
				new ExtractTextPlugin('build/styles.css', {
					allChunks: true
				})
			],
			module: {
				loaders: [
					{
						test: /\.css$/,
						include: codeMirrorPath,
						loader: ExtractTextPlugin.extract('style', 'css')
					},
					{
						test: /\.css$/,
						include: includes,
						loader: ExtractTextPlugin.extract('style', 'css?modules&-minimize&importLoaders=1!postcss')
					}
				]
			}
		});
	}
	else {
		webpackConfig = merge(webpackConfig, {
			entry: [
				path.resolve(__dirname, '../node_modules/webpack-hot-middleware/client'),
				entryScript
			],
			debug: true,
			cache: true,
			devtool: 'eval-source-map',
			stats: {
				colors: true,
				reasons: true
			},
			plugins: [
				new webpack.optimize.OccurenceOrderPlugin(),
				new webpack.HotModuleReplacementPlugin(),
				new webpack.NoErrorsPlugin()
			],
			module: {
				loaders: [
					{
						test: /\.css$/,
						include: codeMirrorPath,
						loader: 'style!css'
					},
					{
						test: /\.css$/,
						include: includes,
						loader: 'style!css?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!postcss'
					}
				]
			}
		});
	}

	if (config.updateWebpackConfig) {
		webpackConfig = config.updateWebpackConfig(webpackConfig, env);
	}

	if (config.verbose) {
		console.log();
		console.log('Using Webpack config:');
		console.log(prettyjson.render(webpackConfig));
		console.log();
	}

	return webpackConfig;
};
<|endoftext|>