<commit_before>var PADDLE_LENGHT = 100;
var speedX = -2;
var speedY = -5;
var score = [0, 0, 0, 0];
var player1 = false;
var players = [];
var y = 0;
var stage;
var master = false;
var ball;
var scoreText;

var webrtc = new SimpleWebRTC({
	// we don't do video
	localVideoEl: '',
	remoteVideosEl: '',
	// dont ask for camera access
	autoRequestMedia: false,
	// dont negotiate media
	receiveMedia: {
		mandatory: {
			OfferToReceiveAudio: false,
			OfferToReceiveVideo: false
		}
	}
});

// join without waiting for media
webrtc.joinRoom('julian');

// called when a peer is created
webrtc.on('createdPeer', function (peer) {
	console.log('createdPeer', peer);
	var div = document.getElementById("peers");
	var channel = peer.getDataChannel("message");
	var allPeers = webrtc.webrtc.peers;
	peer.on('channelClose', function (channel, error) {
		console.log("Losed data channel", channel, error);
		console.log("Should remove player");
		location.reload();
	});

	//handle incoming data
	peer.on('channelMessage', function (peer, channel, msg) {
		// check type, has to be json
		if(msg.type === "json"){
			doStuff(peer, msg.payload);
		}
	});

	//sendPeer(peer, {msg: "Hi, im Player " + webrtc.connection.getSessionid(), job: "init", positions: positions});
	//addPlayer(peer);
	//stage.update();
	if(allPeers.length === 3){
		console.log("Ready to play");
		initGame();
	}

	div.innerHTML = "";
	for (var i = 0; i < allPeers.length; i++)
		div.innerHTML += allPeers[i].id + "
";
});

webrtc.on('joinedRoom', function (room) {
	console.log("entered room " + room);
	//addPlayer(webrtc.connection.getSessionid());
	//stage.update();
});

//send a json to a peer
function sendPeer(peer, data){
	//create data channel
	var channel = peer.getDataChannel("message");

	var isOpen = peer.sendDirectly("message", "json", data);
	if(isOpen){}
	//console.log("Data send");
	else{
		//retry when channel is open
		var saveOldOnopen = channel.onopen;
		channel.onopen = function() {
			sendPeer(peer, data);
			channel.onopen = saveOldOnopen;
		}
		console.log("Problem sending data");
	}
}

//send a json to all peers
function sendAll(data){
	var peers = webrtc.webrtc.peers;
	for (var i = 0; i < peers.length; i++) {
		sendPeer(peers[i], data);
	}
}

function initGame(){
	players = [];
	choosePositon();
}

function choosePositon(){
	var rnd = Math.floor(Math.random() * 100) + 1;
	var myId = webrtc.connection.getSessionid();
	players.push({id: myId, rnd: rnd});
	sendAll({msg: "Hi, im Player " + rnd, job: "posInit", rnd: rnd});
	console.log(rnd);
}

function sortPlacePlayer(){
	//Sort Player list
	console.log(players);
	players.sort(function (a, b) {
		if (a.rnd  b.rnd) return 1;
		if (a.rnd === b.rnd) return 0;
	});
	for(var i = 1; i < players.length; i++) {
		if (players[i].rnd === players[i-1].rnd)
			return false;
 }
	//Place player
	for(var i = 0; i < players.length; i++){
		//add Paddle
		players[i].element = addPlayer(players[i].id);
		players[i].vertical = (i % 2 == 0)? true: false;
	}
	//stage.update();
	return true;

}

function doStuff(peer, data){
	switch (data.job) {
		case "posInit":
			players.push({id: peer.id, rnd: data.rnd});
			if(players.length === 4 && !stage) {
				stage = new createjs.Stage("demoCanvas");
				if(sortPlacePlayer() === true)
					startGame();
				else
					choosePosition();
			}
			break;
		case "movePaddle":
			repositionPaddle(peer.id, data.position);
			break;
		case "setBall":
			setBall(data.position);
			break;
		case "newScore":
			setScore(data.score);
			break;
		default:
			console.log(data);
	}
	//y = data.y;
	//console.log(y);
}

function setBall(pos) {
	ball.x = pos.x;
	ball.y = pos.y;
}

function setScore(score) {
	scoreText.text = score;
}

//createjs
function init() {

}

function startGame() {
	console.log("Start Game");
	//litle delay before game start
	window.setTimeout(function() {
		addBall();
		addScore();
	//set FPS
	createjs.Ticker.setFPS(15);

	if (beMaster())
		createjs.Ticker.addEventListener("tick", gameLoopMaster);
	else
		createjs.Ticker.addEventListener("tick", gameLoop);

	}, 100);
}
function addBall() {
	ball = new createjs.Shape();
	ball.graphics.beginFill("White").drawRect(-5,-5,10,10);
	ball.x = stage.canvas.width / 2;
	ball.y = stage.canvas.height / 2;
	//ball.snapToPixel = false;
	stage.addChild(ball);
	ball.checkCollision = function(a) {
		var b = {x: this.x, y: this.y, width: 10, height: 10};
		if (b.x - b.width/2 < a.x + a.width/2 && b.y - b.height/2  a.x - a.width/2 && b.y + b.height/2 > a.y - a.height/2) {
			return true;
		}
		return false;
	}
}

function addScore() {
	scoreText = new createjs.Text("0,0,0,0", "30px Arial", "#fff");
	scoreText.x = stage.canvas.width / 2;
	scoreText.y = stage.canvas.height / 2;
	scoreText.textAlign = "center";
	scoreText.textBaseline = "middle";
	stage.addChild(scoreText);
}

function gameLoopMaster(event) {
		// Actions carried out each tick (aka frame)
		if (!event.paused) {
			// Actions carried out when the Ticker is not paused.
			var maxWidth = stage.canvas.width;
			var maxHeight = stage.canvas.height;
			//console.log(ball.x, ball.y)
			//collision detection
			for (var i = 0; i < stage.children.length && !collision; i++) {
				if(stage.children[i].playerId)
					var collision = ball.checkCollision(stage.children[i]);
			}
			if (collision) {
				console.log("collision");
				speedX *= -1;
				speedY *= -1;
			}

			var hitWall = false;
			//All 4 walls
			var wall = 10;
			if (ball.x + speedX > maxWidth - wall) {
				score[2]++;
				speedX *= -1;
				hitWall = true;
			}
			if (ball.x + speedX < 0 + wall) {
				score[0]++;
				speedX *= -1;
				hitWall = true;
			}
			if (ball.y + speedY > maxHeight - wall) {
				score[1]++;
				speedY *= -1;
				hitWall = true;
			}
			if (ball.y + speedY < 0 + wall) {
				score[3]++;
				speedY *= -1;
				hitWall = true;
			}

			if(hitWall) {
				sendScore(score);
				scoreText.text = score;
			}

			ball.x += speedX;
			ball.y += speedY;
			sendBallPosition(ball.x, ball.y);
			stage.update();
		}

}

function sendBallPosition(x, y) {
	sendAll({msg: "", job: "setBall", position: {x: x, y: y}});
}

function sendScore(score) {
	sendAll({msg: "", job: "newScore", score: score});
}

function gameLoop(event) {
		// Actions carried out each tick (aka frame)
		if (!event.paused) {
			// Actions carried out when the Ticker is not paused.
			stage.update();
		}
}

function beMaster() {
	var id = webrtc.connection.getSessionid();
	if (players[0].id === id)
		return true;
	return false;
}

function checkState() {
	console.log("Hello");
}

function addPlayer(id) {
	console.log("Add player " + id);
	player = new createjs.Shape();
	var pos = findNextPostion();
	if (pos) {
		if (pos.vertical === true) {
			player.graphics.beginFill("White").drawRect(-(PADDLE_LENGHT/2), -6/2, PADDLE_LENGHT, 6);
			player.width = PADDLE_LENGHT;
			player.height = 10;
		}
		else {
			player.graphics.beginFill("White").drawRect(-6/2, -(PADDLE_LENGHT/2), 6, PADDLE_LENGHT);
			player.width = 10;
			player.height = PADDLE_LENGHT;
		}
		player.playerId = id;
		player.x = pos.x;
		player.y = pos.y;
		stage.addChild(player);
		console.log(player.width);
		return player;
	}
}

function findNextPostion() {
	var nextPos = stage.children.length;
	if (nextPos < 4) {
		var x, y;
		var width = stage.canvas.width;
		var height = stage.canvas.height;
		var vertical = false;

		switch (nextPos) {
			case 0: x = 5; y = height/2;	break;
			case 1: x = width/2; y = 5; vertical = true;	break;
			case 2: x = width - 5; y = height/2;	break;
			case 3: x = width/2; y = height - 5;	vertical = true; break;
		}
		return {x: x, y: y, vertical: vertical};
	}
	return undefined;
}
function repositionPaddle(peerId, position) {
	var peer = findPaddleToMove(peerId);
			peer.element.x = position.x;
			peer.element.y = position.y;
}

function movePaddle(peerId, direction){
	var step;
	var peer = findPaddleToMove(peerId);
	switch (direction){
		case "up":
			step = -2;
			break;
		case "down":
			step = 2;
			break;
	}

	if(peer.vertical) {
		if(peer.element.y + step - PADDLE_LENGHT/2 > 0 && peer.element.y + step + PADDLE_LENGHT/2 < stage.canvas.height)
			peer.element.y += step;
	}
	else {
		if(peer.element.x + step - PADDLE_LENGHT/2 > 0 && peer.element.x + step + PADDLE_LENGHT/2 < stage.canvas.width)
			peer.element.x += step;
	}
	//stage.update();
	return {x: peer.element.x, y: peer.element.y}
}

function findPaddleToMove(peerId){
	for (var i = 0; i < players.length; i++){
		if (players[i].id === peerId)
			return players[i];
	}
}

//add listener
document.onkeydown = function(e){
	var direction;
	var myId = webrtc.connection.getSessionid();
	switch (e.keyCode){
		//up arrow
		case 38:
				direction = "up"
				sendAll({msg: "Please move my paddle", job: "movePaddle", position: movePaddle(myId, direction)});
			break;
			//down arrow
		case 40:
				direction = "down"
				sendAll({msg: "Please move my paddle", job: "movePaddle", position: movePaddle(myId, direction)});
			break;
	}
}
<commit_msg>[feat] add room to the url<commit_after>var PADDLE_LENGHT = 100;
var speedX = -2;
var speedY = -5;
var score = [0, 0, 0, 0];
var players = [];
var y = 0;
var stage;
var master = false;
var ball;
var scoreText;

var webrtc = new SimpleWebRTC({
	// we don't do video
	localVideoEl: '',
	remoteVideosEl: '',
	// dont ask for camera access
	autoRequestMedia: false,
	// dont negotiate media
	receiveMedia: {
		mandatory: {
			OfferToReceiveAudio: false,
			OfferToReceiveVideo: false
		}
	}
});

function createRoom() {
	var room = "room" + parseInt(Math.random()*10000);
	if (history.pushState) {
    var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' + room;
    window.history.pushState({path:newurl},'',newurl);
	}
	return room;
}
// join without waiting for media
webrtc.joinRoom(window.location.search.replace("?", "").split("&")[0] || createRoom());

// called when a peer is created
webrtc.on('createdPeer', function (peer) {
	console.log('createdPeer', peer);
	var div = document.getElementById("peers");
	var channel = peer.getDataChannel("message");
	var allPeers = webrtc.webrtc.peers;
	peer.on('channelClose', function (channel, error) {
		console.log("Losed data channel", channel, error);
		console.log("Should remove player");
		location.reload();
	});

	//handle incoming data
	peer.on('channelMessage', function (peer, channel, msg) {
		// check type, has to be json
		if(msg.type === "json"){
			doStuff(peer, msg.payload);
		}
	});

	//sendPeer(peer, {msg: "Hi, im Player " + webrtc.connection.getSessionid(), job: "init", positions: positions});
	//addPlayer(peer);
	//stage.update();
	if(allPeers.length === 3){
		console.log("Ready to play");
		initGame();
	}

	div.innerHTML = "";
	for (var i = 0; i < allPeers.length; i++)
		div.innerHTML += allPeers[i].id + "
";
});

webrtc.on('joinedRoom', function (room) {
	console.log("entered room " + room);

	//addPlayer(webrtc.connection.getSessionid());
	//stage.update();
});

//send a json to a peer
function sendPeer(peer, data){
	//create data channel
	var channel = peer.getDataChannel("message");

	var isOpen = peer.sendDirectly("message", "json", data);
	if(isOpen){}
	//console.log("Data send");
	else{
		//retry when channel is open
		var saveOldOnopen = channel.onopen;
		channel.onopen = function() {
			sendPeer(peer, data);
			channel.onopen = saveOldOnopen;
		}
		console.log("Problem sending data");
	}
}

//send a json to all peers
function sendAll(data){
	var peers = webrtc.webrtc.peers;
	for (var i = 0; i < peers.length; i++) {
		sendPeer(peers[i], data);
	}
}

function initGame(){
	players = [];
	choosePositon();
}

function choosePositon(){
	var rnd = Math.floor(Math.random() * 100) + 1;
	var myId = webrtc.connection.getSessionid();
	players.push({id: myId, rnd: rnd});
	sendAll({msg: "Hi, im Player " + rnd, job: "posInit", rnd: rnd});
	console.log(rnd);
}

function sortPlacePlayer(){
	//Sort Player list
	console.log(players);
	players.sort(function (a, b) {
		if (a.rnd  b.rnd) return 1;
		if (a.rnd === b.rnd) return 0;
	});
	for(var i = 1; i < players.length; i++) {
		if (players[i].rnd === players[i-1].rnd)
			return false;
 }
	//Place player
	for(var i = 0; i < players.length; i++){
		//add Paddle
		players[i].element = addPlayer(players[i].id);
		players[i].vertical = (i % 2 == 0)? true: false;
	}
	//stage.update();
	return true;

}

function doStuff(peer, data){
	switch (data.job) {
		case "posInit":
			players.push({id: peer.id, rnd: data.rnd});
			if(players.length === 4 && !stage) {
				stage = new createjs.Stage("demoCanvas");
				if(sortPlacePlayer() === true)
					startGame();
				else
					choosePosition();
			}
			break;
		case "movePaddle":
			repositionPaddle(peer.id, data.position);
			break;
		case "setBall":
			setBall(data.position);
			break;
		case "newScore":
			setScore(data.score);
			break;
		default:
			console.log(data);
	}
	//y = data.y;
	//console.log(y);
}

function setBall(pos) {
	ball.x = pos.x;
	ball.y = pos.y;
}

function setScore(score) {
	scoreText.text = score;
}

//createjs
function init() {

}

function startGame() {
	console.log("Start Game");
	//litle delay before game start
	window.setTimeout(function() {
		addBall();
		addScore();
	//set FPS
	createjs.Ticker.setFPS(15);

	if (beMaster())
		createjs.Ticker.addEventListener("tick", gameLoopMaster);
	else
		createjs.Ticker.addEventListener("tick", gameLoop);

	}, 100);
}
function addBall() {
	ball = new createjs.Shape();
	ball.graphics.beginFill("White").drawRect(-5,-5,10,10);
	ball.x = stage.canvas.width / 2;
	ball.y = stage.canvas.height / 2;
	//ball.snapToPixel = false;
	stage.addChild(ball);
	ball.checkCollision = function(a) {
		var b = {x: this.x, y: this.y, width: 10, height: 10};
		if (b.x - b.width/2 < a.x + a.width/2 && b.y - b.height/2  a.x - a.width/2 && b.y + b.height/2 > a.y - a.height/2) {
			return true;
		}
		return false;
	}
}

function addScore() {
	scoreText = new createjs.Text("0,0,0,0", "30px Arial", "#fff");
	scoreText.x = stage.canvas.width / 2;
	scoreText.y = stage.canvas.height / 2;
	scoreText.textAlign = "center";
	scoreText.textBaseline = "middle";
	stage.addChild(scoreText);
}

function gameLoopMaster(event) {
		// Actions carried out each tick (aka frame)
		if (!event.paused) {
			// Actions carried out when the Ticker is not paused.
			var maxWidth = stage.canvas.width;
			var maxHeight = stage.canvas.height;
			//console.log(ball.x, ball.y)
			//collision detection
			for (var i = 0; i < stage.children.length && !collision; i++) {
				if(stage.children[i].playerId)
					var collision = ball.checkCollision(stage.children[i]);
			}
			if (collision) {
				console.log("collision");
				speedX *= -1;
				speedY *= -1;
			}

			var hitWall = false;
			//All 4 walls
			var wall = 10;
			if (ball.x + speedX > maxWidth - wall) {
				score[2]++;
				speedX *= -1;
				hitWall = true;
			}
			if (ball.x + speedX < 0 + wall) {
				score[0]++;
				speedX *= -1;
				hitWall = true;
			}
			if (ball.y + speedY > maxHeight - wall) {
				score[1]++;
				speedY *= -1;
				hitWall = true;
			}
			if (ball.y + speedY < 0 + wall) {
				score[3]++;
				speedY *= -1;
				hitWall = true;
			}

			if(hitWall) {
				sendScore(score);
				scoreText.text = score;
			}

			ball.x += speedX;
			ball.y += speedY;
			sendBallPosition(ball.x, ball.y);
			stage.update();
		}

}

function sendBallPosition(x, y) {
	sendAll({msg: "", job: "setBall", position: {x: x, y: y}});
}

function sendScore(score) {
	sendAll({msg: "", job: "newScore", score: score});
}

function gameLoop(event) {
		// Actions carried out each tick (aka frame)
		if (!event.paused) {
			// Actions carried out when the Ticker is not paused.
			stage.update();
		}
}

function beMaster() {
	var id = webrtc.connection.getSessionid();
	if (players[0].id === id)
		return true;
	return false;
}

function checkState() {
	console.log("Hello");
}

function addPlayer(id) {
	console.log("Add player " + id);
	player = new createjs.Shape();
	var pos = findNextPostion();
	if (pos) {
		if (pos.vertical === true) {
			player.graphics.beginFill("White").drawRect(-(PADDLE_LENGHT/2), -6/2, PADDLE_LENGHT, 6);
			player.width = PADDLE_LENGHT;
			player.height = 10;
		}
		else {
			player.graphics.beginFill("White").drawRect(-6/2, -(PADDLE_LENGHT/2), 6, PADDLE_LENGHT);
			player.width = 10;
			player.height = PADDLE_LENGHT;
		}
		player.playerId = id;
		player.x = pos.x;
		player.y = pos.y;
		stage.addChild(player);
		console.log(player.width);
		return player;
	}
}

function findNextPostion() {
	var nextPos = stage.children.length;
	if (nextPos < 4) {
		var x, y;
		var width = stage.canvas.width;
		var height = stage.canvas.height;
		var vertical = false;

		switch (nextPos) {
			case 0: x = 5; y = height/2;	break;
			case 1: x = width/2; y = 5; vertical = true;	break;
			case 2: x = width - 5; y = height/2;	break;
			case 3: x = width/2; y = height - 5;	vertical = true; break;
		}
		return {x: x, y: y, vertical: vertical};
	}
	return undefined;
}
function repositionPaddle(peerId, position) {
	var peer = findPaddleToMove(peerId);
			peer.element.x = position.x;
			peer.element.y = position.y;
}

function movePaddle(peerId, direction){
	var step;
	var peer = findPaddleToMove(peerId);
	switch (direction){
		case "up":
			step = -2;
			break;
		case "down":
			step = 2;
			break;
	}

	if(peer.vertical) {
		if(peer.element.y + step - PADDLE_LENGHT/2 > 0 && peer.element.y + step + PADDLE_LENGHT/2 < stage.canvas.height)
			peer.element.y += step;
	}
	else {
		if(peer.element.x + step - PADDLE_LENGHT/2 > 0 && peer.element.x + step + PADDLE_LENGHT/2 < stage.canvas.width)
			peer.element.x += step;
	}
	//stage.update();
	return {x: peer.element.x, y: peer.element.y}
}

function findPaddleToMove(peerId){
	for (var i = 0; i < players.length; i++){
		if (players[i].id === peerId)
			return players[i];
	}
}

//add listener
document.onkeydown = function(e){
	var direction;
	var myId = webrtc.connection.getSessionid();
	switch (e.keyCode){
		//up arrow
		case 38:
				direction = "up"
				sendAll({msg: "Please move my paddle", job: "movePaddle", position: movePaddle(myId, direction)});
			break;
			//down arrow
		case 40:
				direction = "down"
				sendAll({msg: "Please move my paddle", job: "movePaddle", position: movePaddle(myId, direction)});
			break;
	}
}
<|endoftext|>


<commit_before>(function (w, $) {
	w.toolbelt = {};
	w.toolbelt.resizeFunctions = [];
	w.toolbelt.addEventOnWindowResize = function (f) {
		$(window).unbind('resize').bind('resize', w.toolbelt.runWindowResizeEvents);
		w.toolbelt.resizeFunctions.push(f);
		f();
	};
	w.toolbelt.runWindowResizeEvents = function () {
		for (var i = 0, l = w.toolbelt.resizeFunctions.length; i < l; i++) {
			w.toolbelt.resizeFunctions[i]();
		}
	};
	w.toolbelt.checkSWFObject = function (cb) {
		if (typeof swfobject === 'undefined' || swfobject === null) {
			$.getScript(window.location.protocol + '//ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js', function () {
				if (!!cb) {
					cb();
				}
			});
		} else {
			if (!!cb) {
				cb();
			}
		}
	};
}(window, jQuery));<commit_msg>Add exists check<commit_after>(function (w, $) {
	w.toolbelt = {};
	w.toolbelt.resizeFunctions = [];
	w.toolbelt.addEventOnWindowResize = function (f) {
		$(window).unbind('resize').bind('resize', w.toolbelt.runWindowResizeEvents);
		w.toolbelt.resizeFunctions.push(f);
		f();
	};
	w.toolbelt.runWindowResizeEvents = function () {
		for (var i = 0, l = w.toolbelt.resizeFunctions.length; i < l; i++) {
			w.toolbelt.resizeFunctions[i]();
		}
	};

	w.toolbelt.checkSWFObject = function (cb) {
		if (typeof swfobject === 'undefined' || swfobject === null) {
			$.getScript(window.location.protocol + '//ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js', function () {
				if (!!cb) {
					cb();
				}
			});
		} else {
			if (!!cb) {
				cb();
			}
		}
	};

	w.toolbelt.exists = function(obj) {
		return typeof obj !== 'undefined' && !!obj;
	};
}(window, jQuery));<|endoftext|>


<commit_before>/*** Map ***/

var styles = {
    "daycycle": "daynight.yaml",

    "highways": "//cdn.rawgit.com/tangrams/highways-demo/e05d4f2afd8072f44908d5c096d5ecde7304c35c/scene.yaml",

    "halftone": "halftone.yaml",

    "tron": "//cdn.rawgit.com/tangrams/tangram-sandbox/dac373596f80065d6e77ec4f6fc7c5541fcb3775/styles/tron.yaml",

    "crosshatch": "//cdn.rawgit.com/tangrams/tangram-sandbox/d94ad04ed07a2d53bbd8d965cba7a7616d426d49/styles/crosshatch.yaml",

    "glitter": "//cdn.rawgit.com/tangrams/tangram-sandbox/dac373596f80065d6e77ec4f6fc7c5541fcb3775/styles/specular-dust.yaml",

    "traditional": "traditional.yaml"
};

var currentStyle = "daycycle";
var qs = window.location.search;
if (qs) {
    qs = qs.slice(1);
    if (qs[qs.length-1] === '/') {
        qs = qs.slice(0, qs.length-1);
    }
    if (styles[qs]) {
        currentStyle = qs;
    }
}

var map = L.map('map',
    {'keyboardZoomOffset': .05}
);

map.attributionControl.setPrefix('Leaflet');

var layer = Tangram.leafletLayer({
    scene: styles[currentStyle],
    preUpdate: preUpdate,
    postUpdate: postUpdate,
    attribution: 'Tangram | © OSM contributors | Mapzen'
});

var scene = layer.scene;

layer.on('init', function() {
   // everything's good, carry on
  window.addEventListener('resize', resizeMap);
  resizeMap();
});

layer.on('error', function(error) {
  // something went wrong
  var errorEL = document.createElement('div');
  errorEL.setAttribute("class", "error-msg");
     // WebGL not supported (or at least didn't initialize properly!)
  if (layer.scene && !layer.scene.gl) {
    var noticeTxt = document.createTextNode("Your browser doesn't support WebGL. Please try with recent Firefox or Chrome, Tangram is totally worth it.");
    errorEL.appendChild(noticeTxt);
   }
   // Something else went wrong, generic error message
   else {
    var noticeTxt = document.createTextNode("We are sorry, but something went wrong, please try later.");
    errorEL.appendChild(noticeTxt);
   }
   document.body.appendChild(errorEL);
});

layer.addTo(map);

// leaflet-style URL hash pattern:
// ?style.yaml#[zoom],[lat],[lng]
var map_start_location = [40.7076, -74.0094, 15];
var url_hash = window.location.hash.slice(1).split('/');
if (url_hash.length === 3) {
    map_start_location = [url_hash[1],url_hash[2], url_hash[0]];
    // convert from strings
    map_start_location = map_start_location.map(Number);
}

map.setView(map_start_location.slice(0, 2), map_start_location[2]);

var hash = new L.Hash(map);

// Resize map to window
function resizeMap() {
    document.getElementById('map').style.width = window.innerWidth + 'px';
    document.getElementById('map').style.height = window.innerHeight + 'px';
    map.invalidateSize(false);
}

function switchStyles(style) {
    if (styles[style]) {
        currentStyle = style;
        layer.scene.reload(styles[currentStyle]);
    }
}

function preUpdate(will_render) {
    if (!will_render) {
        return;
    }

    switch(currentStyle) {
        case "daycycle":
            daycycle();
            break;
    }
}

function postUpdate() {
}

function daycycle() {
    d = new Date();
    t = d.getTime()/10000;

    x = Math.sin(t);
    y = Math.sin(t+(3.14159/2)); // 1/4 offset
    z = Math.sin(t+(3.14159)); // 1/2 offset

    scene.camera.axis = {x: x, y: y};

    // offset blue and red for sunset and moonlight effect
    B = x + Math.abs(Math.sin(t+(3.14159*.5)))/4;
    R = y + Math.abs(Math.sin(t*2))/4;

    scene.lights.sun.diffuse = [R, y, B, 1];
    scene.lights.sun.direction = [x, 1, -.5];

    px = Math.min(x, 0); // positive x
    py = Math.min(y, 0); // positive y
    // light up the roads at night
    scene.styles["roads"].material.emission.amount = [-py, -py, -py, 1];
    // turn water black at night
    scene.styles["water"].material.ambient.amount = [py+1, py+1, py+1, 1];
    scene.styles["water"].material.diffuse.amount = [py+1, py+1, py+1, 1];

    // turn up buildings' ambient response at night
    ba = -py*.75+.75;
    scene.styles["buildings"].material.ambient.amount = [ba, ba, ba, 1];

    scene.animated = true;
}

// iFrame integration
window.addEventListener("DOMContentLoaded", function() {

  if (window.self !== window.top) {
    //disable scroll zoom if it is iframed
    map.scrollWheelZoom.disable();
    //sending message that child frame is ready to parent window
    window.parent.postMessage("loaded", "*");
    window.addEventListener("message", function (e) {
      // Ignore the message if origin is self (this fixes a Safari bug where iframed documents posts messages at itself)
      if (e.origin === window.location.origin) return;
      switchStyles(e.data);
    }, false);
  }
}, false);
<commit_msg>update crosshatch<commit_after>/*** Map ***/

var styles = {
    "daycycle": "daynight.yaml",

    "highways": "//cdn.rawgit.com/tangrams/highways-demo/e05d4f2afd8072f44908d5c096d5ecde7304c35c/scene.yaml",

    "halftone": "halftone.yaml",

    "tron": "//cdn.rawgit.com/tangrams/tangram-sandbox/dac373596f80065d6e77ec4f6fc7c5541fcb3775/styles/tron.yaml",

    "crosshatch": "//cdn.rawgit.com/tangrams/tangram-sandbox/984f7f26d416cd209c8cd7b487d25dd7524fdaa0/styles/crosshatch.yaml",

    "glitter": "//cdn.rawgit.com/tangrams/tangram-sandbox/dac373596f80065d6e77ec4f6fc7c5541fcb3775/styles/specular-dust.yaml",

    "traditional": "traditional.yaml"
};

var currentStyle = "daycycle";
var qs = window.location.search;
if (qs) {
    qs = qs.slice(1);
    if (qs[qs.length-1] === '/') {
        qs = qs.slice(0, qs.length-1);
    }
    if (styles[qs]) {
        currentStyle = qs;
    }
}

var map = L.map('map',
    {'keyboardZoomOffset': .05}
);

map.attributionControl.setPrefix('Leaflet');

var layer = Tangram.leafletLayer({
    scene: styles[currentStyle],
    preUpdate: preUpdate,
    postUpdate: postUpdate,
    attribution: 'Tangram | © OSM contributors | Mapzen'
});

var scene = layer.scene;

layer.on('init', function() {
   // everything's good, carry on
  window.addEventListener('resize', resizeMap);
  resizeMap();
});

layer.on('error', function(error) {
  // something went wrong
  var errorEL = document.createElement('div');
  errorEL.setAttribute("class", "error-msg");
     // WebGL not supported (or at least didn't initialize properly!)
  if (layer.scene && !layer.scene.gl) {
    var noticeTxt = document.createTextNode("Your browser doesn't support WebGL. Please try with recent Firefox or Chrome, Tangram is totally worth it.");
    errorEL.appendChild(noticeTxt);
   }
   // Something else went wrong, generic error message
   else {
    var noticeTxt = document.createTextNode("We are sorry, but something went wrong, please try later.");
    errorEL.appendChild(noticeTxt);
   }
   document.body.appendChild(errorEL);
});

layer.addTo(map);

// leaflet-style URL hash pattern:
// ?style.yaml#[zoom],[lat],[lng]
var map_start_location = [40.7076, -74.0094, 15];
var url_hash = window.location.hash.slice(1).split('/');
if (url_hash.length === 3) {
    map_start_location = [url_hash[1],url_hash[2], url_hash[0]];
    // convert from strings
    map_start_location = map_start_location.map(Number);
}

map.setView(map_start_location.slice(0, 2), map_start_location[2]);

var hash = new L.Hash(map);

// Resize map to window
function resizeMap() {
    document.getElementById('map').style.width = window.innerWidth + 'px';
    document.getElementById('map').style.height = window.innerHeight + 'px';
    map.invalidateSize(false);
}

function switchStyles(style) {
    if (styles[style]) {
        currentStyle = style;
        layer.scene.reload(styles[currentStyle]);
    }
}

function preUpdate(will_render) {
    if (!will_render) {
        return;
    }

    switch(currentStyle) {
        case "daycycle":
            daycycle();
            break;
    }
}

function postUpdate() {
}

function daycycle() {
    d = new Date();
    t = d.getTime()/10000;

    x = Math.sin(t);
    y = Math.sin(t+(3.14159/2)); // 1/4 offset
    z = Math.sin(t+(3.14159)); // 1/2 offset

    scene.camera.axis = {x: x, y: y};

    // offset blue and red for sunset and moonlight effect
    B = x + Math.abs(Math.sin(t+(3.14159*.5)))/4;
    R = y + Math.abs(Math.sin(t*2))/4;

    scene.lights.sun.diffuse = [R, y, B, 1];
    scene.lights.sun.direction = [x, 1, -.5];

    px = Math.min(x, 0); // positive x
    py = Math.min(y, 0); // positive y
    // light up the roads at night
    scene.styles["roads"].material.emission.amount = [-py, -py, -py, 1];
    // turn water black at night
    scene.styles["water"].material.ambient.amount = [py+1, py+1, py+1, 1];
    scene.styles["water"].material.diffuse.amount = [py+1, py+1, py+1, 1];

    // turn up buildings' ambient response at night
    ba = -py*.75+.75;
    scene.styles["buildings"].material.ambient.amount = [ba, ba, ba, 1];

    scene.animated = true;
}

// iFrame integration
window.addEventListener("DOMContentLoaded", function() {

  if (window.self !== window.top) {
    //disable scroll zoom if it is iframed
    map.scrollWheelZoom.disable();
    //sending message that child frame is ready to parent window
    window.parent.postMessage("loaded", "*");
    window.addEventListener("message", function (e) {
      // Ignore the message if origin is self (this fixes a Safari bug where iframed documents posts messages at itself)
      if (e.origin === window.location.origin) return;
      switchStyles(e.data);
    }, false);
  }
}, false);
<|endoftext|>


<commit_before>/*!
 * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements;
 * and to You under the Apache License, Version 2.0.
 */
'use strict';

/**
 * @ngdoc overview
 * @name playerApp
 * @description
 * # playerApp
 *
 * Main module of the application.
 */

var baseUrl = window.location.host;

// Angular templates (used to feed $templateCache)
//angular.module('templates', []);

angular.module('playerApp', ['ngResource', 'ngSanitize', 'ui.router', 'ngWebSocket', 'luegg.directives', 'hc.marked', 'templates'])
  .run(
    ['$rootScope', '$state', '$stateParams',
      function ($rootScope, $state, $stateParams) {
        // make life easier
        $rootScope.$on("$stateChangeError", console.log.bind(console));

        // From https://github.com/angular-ui/ui-router/blob/gh-pages/sample/app/app.js
        $rootScope.$state = $state;
        $rootScope.$stateParams = $stateParams;
      }
    ])
  .constant("API", {
    "HOST": baseUrl,
    "PROFILE_URL": "https://" + baseUrl + "/players/v1/",
    "WS_URL": "wss://" + baseUrl + "/mediator/ws/",
    "CERT_URL": "https://" + baseUrl + "/auth/PublicCertificate",
    "GOOGLE": "https://" + baseUrl + "/auth/GoogleAuth",
    "TWITTER": "https://" + baseUrl + "/auth/TwitterAuth",
    "FACEBOOK": "https://" + baseUrl + "/auth/FacebookAuth",
    "GITHUB": "https://" + baseUrl + "/auth/GitHubAuth",
    "REDHAT": "https://" + baseUrl + "/auth/RedHatAuth",
    "DUMMY": "https://" + baseUrl + "/auth/DummyAuth?dummyUserName=DevUser&callbackHost=https://" + baseUrl
  })
  .config(['markedProvider', function (markedProvider) {
    markedProvider.setOptions({ sanitize: true });
  }])
  .config(['$locationProvider', function ($locationProvider) {
    $locationProvider.hashPrefix('');
  }])
  .config(
    ['$stateProvider', '$urlServiceProvider',
      function ($stateProvider, $urlServiceProvider) {

        // Use $urlServiceProvider to configure any redirects (when) and invalid urls (otherwise).
        // The `when` method says if the url is ever the 1st param, then redirect to the 2nd param
        $urlServiceProvider.rules.otherwise('/');

        //////////////////////////
        // State Configurations

        $stateProvider
          .state('default', {
            url: '/',
            templateUrl: '/default.html',
            controller: 'DefaultCtrl as ctrl',
            onEnter: function ($window, auth, go_ga) {
              go_ga.hit('default');
              auth.setStartingState('default');
              var original = $window.location.href;
              if ( original.indexOf('gameontext.org') >= 0 ) {
                var path = original.replace(baseUrl, '').replace(/https?:\/\/\//, '');
                var bits = path.split('#');
                if ( bits[0].length > 1 ) {
                  if ( bits[0] === 'redhat' ) {
                    $window.location.href = original.replace(bits[0]+'#', '#') + 'redhat';
                  } else {
                    $window.location.href = original.replace(bits[0]+'#', '#');
                  }
                }
              }
            }
          })
          .state('default.terms', {
            url: '^/terms'
          })
          .state('default.login', {
            url: '^/login',
            onEnter: function (auth, go_ga) {
              console.info("state -> default.login");
              auth.setStartingState('default');
              go_ga.hit('login');
              go_ga.report('send', 'event', 'GameOn', 'App', 'login');
            }
          })
          .state('default.auth', {
            url: '^/login/callback/{jwt:.*}',
            // State triggered by authentication callback (only).
            onEnter: function ($state, $stateParams, auth) {
              console.info("state -> default.auth using %o", auth);
              return auth.get_public_key().then((result) => {
                if ( result ) {
                  console.log("got public cert.. proceeding to jwt validation.");
                  // remember jwt for later
                  auth.remember_jwt($stateParams.jwt);
                  return $state.target('default.validatejwt');
                } else {
                  return $state.target('default.yuk');
                }
              });
            }
          })
          .state('default.validatejwt', {
            // State triggered by default.auth after obtaining public key
            onEnter: function ($state, auth, go_ga) {
              console.info("state -> default.validatejwt using %o", auth);
              if (auth.validate_jwt()) {
                console.log("token callback from auth service was valid");
                go_ga.report('send', 'event', 'GameOn', 'App', 'login-pass');
                return $state.target('default.usersetup');
              } else {
                //TODO: goto a login failed page..
                go_ga.report('send', 'event', 'GameOn', 'App', 'login-fail');
                return $state.target(auth.getStartingState());
              }
            }
          })
          .state('default.usersetup', {
            url: '^/login/usersetup',
            // State triggered by default.validatejwt
            onEnter: function ($state, auth, user, go_ga) {
              console.info("state -> default.usersetup");
              var jwt = auth.get_jwt();
              if (jwt !== null) {
                // Verify the returned token...
                go_ga.hit('usersetup');
                console.log("building user object; token info object was %o", jwt);
                // user.load returns a promise that resolves to true if the user was found, or false.
                return user.load().then(function (userKnownToDB) {
                  if (userKnownToDB) {
                    go_ga.report('send', 'event', 'GameOn', 'App', 'login-existing');
                    return $state.target('play.room');
                  } else {
                    go_ga.report('send', 'event', 'GameOn', 'App', 'login-new');
                    return $state.target('default.profile');
                  }
                });
              } else {
                // cached / recovered token was invalid.
                // TODO: goto a login failed page..
                go_ga.report('send', 'event', 'GameOn', 'App', 'login-missing-token');
                return $state.target(auth.getStartingState());
              }
            }
          })
          .state('default.profile', { // initial profile creation
            url: '^/login/profile',
            onEnter: function ($state, user, auth, go_ga) {
              console.info("state: default.profile: %o", user.profile);
              // if we're missing our auth token info.. user may have hit refresh here..
              // since we've just lost all our context, send them back to the start..
              // mebbe can make this nicer ;p
              if ( user.profile.name != null ) {
                go_ga.hit('profile');
              } else {
                console.log("Missing user info.. redirecting.. ");
                return $state.target('default.usersetup');
              }
            }
          })
          .state('default.yuk', {
            url: '^/yuk',
            onEnter: function (auth, go_ga) {
              console.info("state -> yuk");
              go_ga.hit('yuk');
              var start = auth.getStartingState();
              auth.logout(); // reset to try again
              auth.setStartingState(start);
            }
          })
          .state('default.logout', {
            url: '^/logout',
            onEnter: function ($state, auth, go_ga) {
              console.info("state -> logout");
              go_ga.hit('logout');
              var start = auth.getStartingState();
              auth.logout(); // reset to try again
              return $state.target(start);
            }
          })
          .state('redhat', {
            url: '^/redhat',
            templateUrl: '/redhat.html',
            controller: 'RedHatCtrl as redhatCtrl',
            onEnter: function (go_ga) {
              console.info("state -> redhat");
              auth.setStartingState('redhat');
              go_ga.hit('redhat');
              go_ga.report('send', 'event', 'GameOn', 'App', 'redhat-intro');
            }
          })
          .state('redhat.login', {
            url: '^/redhat/login',
            onEnter: function (auth, go_ga) {
              console.info('state -> redhat.login');
              auth.setStartingState('redhat');
              go_ga.report('send', 'event', 'GameOn', 'App', 'redhat-login');
            }
          })
          .state('play', {
            // With abstract set to true, that means this state can not be explicitly activated.
            // It can only be implicitly activated by activating one of its children.
            abstract: true,
            url: '/play',
            templateUrl: '/play.html',
            controller: 'PlayCtrl as play',
            resolve: {
              // a fictional var that we'll have injected to onEntry and into the PlayCtrl.
              // resolve will make sure we don't create PlayCtrl or enter onEntry until
              // the promises below are all complete.
              "userAndAuth": function (auth, user) {
                return auth.getAuthenticationState().then(function (isAuthenticated) {
                  if (!isAuthenticated || typeof user.profile._id === 'undefined') {
                      return false;
                  } else {
                      return true;
                  }
                });
              }
            },
            onEnter: function ($state, auth, user, userAndAuth) {
              console.info("state -> play", user.profile, userAndAuth);
              if ( ! userAndAuth ) {
                return $state.target(auth.getStartingState());
              }
            }
          })
          .state('play.room', {
            url: '',
            templateUrl: '/play.room.html',
            onEnter: function (go_ga) {
              go_ga.hit('game_screen');
              go_ga.report('send', 'event', 'GameOn', 'App', 'play');
            }
          })
          .state('play.myrooms', {
            url: '/myrooms',
            templateUrl: '/play.myrooms.html',
            onEnter: function (go_ga) {
              go_ga.hit('room_editor');
              go_ga.report('send', 'event', 'GameOn', 'App', 'edit_rooms');
            }
          })
          .state('play.me', {
            url: '/me',
            templateUrl: '/play.me.html',
            onEnter: function (go_ga, user) {
              user.refresh();
              go_ga.hit('profile_editor');
              go_ga.report('send', 'event', 'GameOn', 'App', 'edit_profile');
            }
          });
      }
    ]);
<commit_msg>missed auth<commit_after>/*!
 * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements;
 * and to You under the Apache License, Version 2.0.
 */
'use strict';

/**
 * @ngdoc overview
 * @name playerApp
 * @description
 * # playerApp
 *
 * Main module of the application.
 */

var baseUrl = window.location.host;

// Angular templates (used to feed $templateCache)
//angular.module('templates', []);

angular.module('playerApp', ['ngResource', 'ngSanitize', 'ui.router', 'ngWebSocket', 'luegg.directives', 'hc.marked', 'templates'])
  .run(
    ['$rootScope', '$state', '$stateParams',
      function ($rootScope, $state, $stateParams) {
        // make life easier
        $rootScope.$on("$stateChangeError", console.log.bind(console));

        // From https://github.com/angular-ui/ui-router/blob/gh-pages/sample/app/app.js
        $rootScope.$state = $state;
        $rootScope.$stateParams = $stateParams;
      }
    ])
  .constant("API", {
    "HOST": baseUrl,
    "PROFILE_URL": "https://" + baseUrl + "/players/v1/",
    "WS_URL": "wss://" + baseUrl + "/mediator/ws/",
    "CERT_URL": "https://" + baseUrl + "/auth/PublicCertificate",
    "GOOGLE": "https://" + baseUrl + "/auth/GoogleAuth",
    "TWITTER": "https://" + baseUrl + "/auth/TwitterAuth",
    "FACEBOOK": "https://" + baseUrl + "/auth/FacebookAuth",
    "GITHUB": "https://" + baseUrl + "/auth/GitHubAuth",
    "REDHAT": "https://" + baseUrl + "/auth/RedHatAuth",
    "DUMMY": "https://" + baseUrl + "/auth/DummyAuth?dummyUserName=DevUser&callbackHost=https://" + baseUrl
  })
  .config(['markedProvider', function (markedProvider) {
    markedProvider.setOptions({ sanitize: true });
  }])
  .config(['$locationProvider', function ($locationProvider) {
    $locationProvider.hashPrefix('');
  }])
  .config(
    ['$stateProvider', '$urlServiceProvider',
      function ($stateProvider, $urlServiceProvider) {

        // Use $urlServiceProvider to configure any redirects (when) and invalid urls (otherwise).
        // The `when` method says if the url is ever the 1st param, then redirect to the 2nd param
        $urlServiceProvider.rules.otherwise('/');

        //////////////////////////
        // State Configurations

        $stateProvider
          .state('default', {
            url: '/',
            templateUrl: '/default.html',
            controller: 'DefaultCtrl as ctrl',
            onEnter: function ($window, auth, go_ga) {
              go_ga.hit('default');
              auth.setStartingState('default');
              var original = $window.location.href;
              if ( original.indexOf('gameontext.org') >= 0 ) {
                var path = original.replace(baseUrl, '').replace(/https?:\/\/\//, '');
                var bits = path.split('#');
                if ( bits[0].length > 1 ) {
                  if ( bits[0] === 'redhat' ) {
                    $window.location.href = original.replace(bits[0]+'#', '#') + 'redhat';
                  } else {
                    $window.location.href = original.replace(bits[0]+'#', '#');
                  }
                }
              }
            }
          })
          .state('default.terms', {
            url: '^/terms'
          })
          .state('default.login', {
            url: '^/login',
            onEnter: function (auth, go_ga) {
              console.info("state -> default.login");
              auth.setStartingState('default');
              go_ga.hit('login');
              go_ga.report('send', 'event', 'GameOn', 'App', 'login');
            }
          })
          .state('default.auth', {
            url: '^/login/callback/{jwt:.*}',
            // State triggered by authentication callback (only).
            onEnter: function ($state, $stateParams, auth) {
              console.info("state -> default.auth using %o", auth);
              return auth.get_public_key().then((result) => {
                if ( result ) {
                  console.log("got public cert.. proceeding to jwt validation.");
                  // remember jwt for later
                  auth.remember_jwt($stateParams.jwt);
                  return $state.target('default.validatejwt');
                } else {
                  return $state.target('default.yuk');
                }
              });
            }
          })
          .state('default.validatejwt', {
            // State triggered by default.auth after obtaining public key
            onEnter: function ($state, auth, go_ga) {
              console.info("state -> default.validatejwt using %o", auth);
              if (auth.validate_jwt()) {
                console.log("token callback from auth service was valid");
                go_ga.report('send', 'event', 'GameOn', 'App', 'login-pass');
                return $state.target('default.usersetup');
              } else {
                //TODO: goto a login failed page..
                go_ga.report('send', 'event', 'GameOn', 'App', 'login-fail');
                return $state.target(auth.getStartingState());
              }
            }
          })
          .state('default.usersetup', {
            url: '^/login/usersetup',
            // State triggered by default.validatejwt
            onEnter: function ($state, auth, user, go_ga) {
              console.info("state -> default.usersetup");
              var jwt = auth.get_jwt();
              if (jwt !== null) {
                // Verify the returned token...
                go_ga.hit('usersetup');
                console.log("building user object; token info object was %o", jwt);
                // user.load returns a promise that resolves to true if the user was found, or false.
                return user.load().then(function (userKnownToDB) {
                  if (userKnownToDB) {
                    go_ga.report('send', 'event', 'GameOn', 'App', 'login-existing');
                    return $state.target('play.room');
                  } else {
                    go_ga.report('send', 'event', 'GameOn', 'App', 'login-new');
                    return $state.target('default.profile');
                  }
                });
              } else {
                // cached / recovered token was invalid.
                // TODO: goto a login failed page..
                go_ga.report('send', 'event', 'GameOn', 'App', 'login-missing-token');
                return $state.target(auth.getStartingState());
              }
            }
          })
          .state('default.profile', { // initial profile creation
            url: '^/login/profile',
            onEnter: function ($state, user, auth, go_ga) {
              console.info("state: default.profile: %o", user.profile);
              // if we're missing our auth token info.. user may have hit refresh here..
              // since we've just lost all our context, send them back to the start..
              // mebbe can make this nicer ;p
              if ( user.profile.name != null ) {
                go_ga.hit('profile');
              } else {
                console.log("Missing user info.. redirecting.. ");
                return $state.target('default.usersetup');
              }
            }
          })
          .state('default.yuk', {
            url: '^/yuk',
            onEnter: function (auth, go_ga) {
              console.info("state -> yuk");
              go_ga.hit('yuk');
              var start = auth.getStartingState();
              auth.logout(); // reset to try again
              auth.setStartingState(start);
            }
          })
          .state('default.logout', {
            url: '^/logout',
            onEnter: function ($state, auth, go_ga) {
              console.info("state -> logout");
              go_ga.hit('logout');
              var start = auth.getStartingState();
              auth.logout(); // reset to try again
              return $state.target(start);
            }
          })
          .state('redhat', {
            url: '^/redhat',
            templateUrl: '/redhat.html',
            controller: 'RedHatCtrl as redhatCtrl',
            onEnter: function (auth, go_ga) {
              console.info("state -> redhat");
              auth.setStartingState('redhat');
              go_ga.hit('redhat');
              go_ga.report('send', 'event', 'GameOn', 'App', 'redhat-intro');
            }
          })
          .state('redhat.login', {
            url: '^/redhat/login',
            onEnter: function (auth, go_ga) {
              console.info('state -> redhat.login');
              auth.setStartingState('redhat');
              go_ga.report('send', 'event', 'GameOn', 'App', 'redhat-login');
            }
          })
          .state('play', {
            // With abstract set to true, that means this state can not be explicitly activated.
            // It can only be implicitly activated by activating one of its children.
            abstract: true,
            url: '/play',
            templateUrl: '/play.html',
            controller: 'PlayCtrl as play',
            resolve: {
              // a fictional var that we'll have injected to onEntry and into the PlayCtrl.
              // resolve will make sure we don't create PlayCtrl or enter onEntry until
              // the promises below are all complete.
              "userAndAuth": function (auth, user) {
                return auth.getAuthenticationState().then(function (isAuthenticated) {
                  if (!isAuthenticated || typeof user.profile._id === 'undefined') {
                      return false;
                  } else {
                      return true;
                  }
                });
              }
            },
            onEnter: function ($state, auth, user, userAndAuth) {
              console.info("state -> play", user.profile, userAndAuth);
              if ( ! userAndAuth ) {
                return $state.target(auth.getStartingState());
              }
            }
          })
          .state('play.room', {
            url: '',
            templateUrl: '/play.room.html',
            onEnter: function (go_ga) {
              go_ga.hit('game_screen');
              go_ga.report('send', 'event', 'GameOn', 'App', 'play');
            }
          })
          .state('play.myrooms', {
            url: '/myrooms',
            templateUrl: '/play.myrooms.html',
            onEnter: function (go_ga) {
              go_ga.hit('room_editor');
              go_ga.report('send', 'event', 'GameOn', 'App', 'edit_rooms');
            }
          })
          .state('play.me', {
            url: '/me',
            templateUrl: '/play.me.html',
            onEnter: function (go_ga, user) {
              user.refresh();
              go_ga.hit('profile_editor');
              go_ga.report('send', 'event', 'GameOn', 'App', 'edit_profile');
            }
          });
      }
    ]);
<|endoftext|>


<commit_before>/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var extendFlat = require('../../lib/extend').extendFlat;

var barAttrs = require('../bar/attributes');

var dash = require('../../components/drawing/attributes').dash;
var scatterAttrs = require('../scatter/attributes');
var lineAttrs = scatterAttrs.line;

module.exports = {

    x: barAttrs.x,
    x0: barAttrs.x0,
    dx: barAttrs.dx,
    y: barAttrs.y,
    y0: barAttrs.y0,
    dy: barAttrs.dy,

    r: barAttrs.r,
    t: barAttrs.t,

    text: barAttrs.text,
    hovertext: barAttrs.hovertext,
    hovertemplate: barAttrs.hovertemplate,

    textposition: barAttrs.textposition,

    textfont: barAttrs.textfont,

    insidetextfont: barAttrs.insidetextfont,

    outsidetextfont: barAttrs.outsidetextfont,

    constraintext: barAttrs.constraintext,

    cliponaxis: barAttrs.cliponaxis,

    orientation: barAttrs.orientation,

    offset: barAttrs.offset,

    width: barAttrs.width,

    marker: extendFlat({}, barAttrs.marker, {
        shape: {
            valType: 'enumerated',
            values: ['rectangle', 'triangle'],
            dflt: 'rectangle',
            role: 'style',
            editType: 'style',
            description: [
                'Defines the shape of positive/negative bars on the plot.',
                'Namely \'triangle`\ option could be used to emphasize on',
                'the direction of the changes.'
            ].join(' ')
        }
    }),

    connector: {
        color: extendFlat({}, lineAttrs.color, {dflt: '#BBBBBB'}),
        width: lineAttrs.width,
        dash: dash,
        editType: 'style'
    },

    selected: barAttrs.selected,
    unselected: barAttrs.unselected
};
<commit_msg>revised includes<commit_after>/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var extendFlat = require('../../lib/extend').extendFlat;

var barAttrs = require('../bar/attributes');

var dash = require('../../components/drawing/attributes').dash;
var lineAttrs = require('../scatter/attributes').line;

module.exports = {

    x: barAttrs.x,
    x0: barAttrs.x0,
    dx: barAttrs.dx,
    y: barAttrs.y,
    y0: barAttrs.y0,
    dy: barAttrs.dy,

    r: barAttrs.r,
    t: barAttrs.t,

    text: barAttrs.text,
    hovertext: barAttrs.hovertext,
    hovertemplate: barAttrs.hovertemplate,

    textposition: barAttrs.textposition,

    textfont: barAttrs.textfont,

    insidetextfont: barAttrs.insidetextfont,

    outsidetextfont: barAttrs.outsidetextfont,

    constraintext: barAttrs.constraintext,

    cliponaxis: barAttrs.cliponaxis,

    orientation: barAttrs.orientation,

    offset: barAttrs.offset,

    width: barAttrs.width,

    marker: extendFlat({}, barAttrs.marker, {
        shape: {
            valType: 'enumerated',
            values: ['rectangle', 'triangle'],
            dflt: 'rectangle',
            role: 'style',
            editType: 'style',
            description: [
                'Defines the shape of positive/negative bars on the plot.',
                'Namely \'triangle`\ option could be used to emphasize on',
                'the direction of the changes.'
            ].join(' ')
        }
    }),

    connector: {
        color: extendFlat({}, lineAttrs.color, {dflt: '#FFFFFF'}),
        width: lineAttrs.width,
        dash: dash,
        editType: 'style'
    },

    selected: barAttrs.selected,
    unselected: barAttrs.unselected
};
<|endoftext|>


<commit_before>/*
 * This program is part of the OpenLMIS logistics management information system platform software.
 * Copyright © 2013 VillageReach
 *
 * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
 * You should have received a copy of the GNU Affero General Public License along with this program.  If not, see http://www.gnu.org/licenses.  For additional information contact info@OpenLMIS.org.
 */

function StockMovementViewController($scope, $window,SaveDistribution,StockEvent, UpdateOrderRequisitionStatus,VaccineLastStockMovement, StockCardsByCategoryAndRequisition, StockCardsForProgramByCategory, $dialog, homeFacility, programs, $routeParams, $location) {

    var orderId = parseInt($routeParams.id, 10);
    var programId = parseInt($routeParams.programId, 10);
    var periodId = parseInt($routeParams.periodId, 10);

    var homeFacilityId = parseInt(homeFacility.id, 10);
    var toFacilityId = parseInt($routeParams.facilityId, 10);
    $scope.toFacilityName = $routeParams.facilityName;

    var program = programs;

    $scope.line = [];
    $scope.facilities = [];
    $scope.date = new Date();

    $scope.pageSize = parseInt(10, 10);
    var pageLineItems = [];

    $scope.homeFacility = $routeParams.facility;

    var refreshPageLineItems = function () {

        if (isUndefined(homeFacilityId) && isUndefined(programs[0].id &&
                isUndefined(periodId) && isUndefined(toFacilityId))) {

            return 'No pending Requisition';

        } else {

            StockCardsForProgramByCategory.get(program[0].id, homeFacilityId, periodId, toFacilityId).then(function (data) {
                $scope.pageLineItems = data;
                pageLineItems = data;
                $scope.numberOfPages = Math.ceil(pageLineItems.length / $scope.pageSize) || 1;
                $scope.currentPage = (utils.isValidPage($routeParams.page, $scope.numberOfPages)) ? parseInt($routeParams.page, 10) : 1;
                $scope.stockCardsByCategory = $scope.pageLineItems.slice($scope.pageSize * ($scope.currentPage - 1), $scope.pageSize * $scope.currentPage);
              // console.log(JSON.stringify($scope.stockCardsByCategory));
            });
        }

    };

    refreshPageLineItems();

    $scope.$watch('currentPage', function () {
        $location.search('page', $scope.currentPage);
    });

    $scope.$on('$routeUpdate', function () {
        refreshPageLineItems();
    });

    $scope.sumLots = function (c) {

        var total = 0;
        c.lotsOnHand.forEach(function (l) {
            var x = ((l.quantity === '' || l.quantity === undefined) ? 0 : parseInt(l.quantity, 10));
            total = total + x;

        });

        $scope.total = total;

        c.sum = parseInt(c.quantityRequested, 10) - total;

    };

    $scope.save = function () {
        $scope.message = 'Saved Successfully';
        return $scope.message;
    };
    var printTest = false;

    $scope.submit = function () {
        if ($scope.orderRequisitionForm.$error.required) {
            $scope.showError = true;
            $scope.error = "The form you submitted is invalid. Please revise and try again.";
            return;
        }

        var transaction = {};
        transaction.transactionList = [];

        var lastInsertedReport = {};
        lastInsertedReport.list = [];

        var callBack = function (result) {
            if (result) {
                var distribution = {};
                var events=[];

                distribution.fromFacilityId = homeFacility.id;
                distribution.toFacilityId= toFacilityId;
                distribution.distributionDate = $scope.stockCardsByCategory[0].issueDate;
                distribution.periodId = periodId;
                distribution.orderId = orderId;
                distribution.lineItems=[];
                distribution.distributionType="SCHEDULED";
                distribution.status="PENDING";

                $scope.stockCardsByCategory.forEach(function (st) {

                    st.stockCards.forEach(function (s) {

                           var lineItem = {};

                           lineItem.productId = s.product.id;
                           if(s.lotsOnHand.length >0)
                           {
                           lineItem.lots = [];
                           var lotSum = 0;
                           s.lotsOnHand.forEach(function (l) {

                               if( l.quantity >0)
                               {
                                   var lot = {};
                                   var event={};
                                   event.type="ISSUE";
                                   event.productCode= s.product.code;
                                   event.facilityId=toFacilityId;
                                   event.lotId= l.lot.id;
                                   event.quantity= l.quantity;
                                   event.customProps={"occurred":st.issueDate};
                                   events.push(event);

                                   lot.lotId = l.lot.id;
                                   lot.quantity = l.quantity;
                                   lot.vvmStatus=l.customProps.vvmstatus;
                                   lineItem.lots.push(lot);
                                   lotSum = lotSum + l.quantity;
                               }
                              });
                               lineItem.quantity = lotSum;

                           }
                        else{
                               var event={};
                               event.type="ISSUE";
                               event.productCode= s.product.code;
                               event.facilityId=toFacilityId;
                               event.quantity= st.quantity;
                               event.customPros={"occurred":st.issueDate};
                               events.push(event);

                           }

                       distribution.lineItems.push(lineItem);

                    });

                });
              StockEvent.save({facilityId:homeFacility.id},events,function(data){
                   SaveDistribution.save(distribution,function(distribution) {
                        UpdateOrderRequisitionStatus.update({orderId: orderId}, function () {
                            print(distribution.distributionId);
                            $scope.message = "label.form.Submitted.Successfully";
                         });
                   });
               });

            }
        };

        var options = {
            id: "confirmDialog",
            header: "label.confirm.issue.submit.action",
            body: "msg.question.submit.order.confirmation"
        };

        OpenLmisDialog.newDialog(options, callBack, $dialog);

    };

    var print = function(distributionId){
              var url = '/vaccine/orderRequisition/issue/print/'+distributionId;
               $window.open(url, '_blank');

               $window.location = '/public/pages/vaccine/inventory/dashboard/index.html#/stock-on-hand';

         };

    $scope.cancel = function () {
        $window.location = '/public/pages/vaccine/order-requisition/index.html#/view';
    };

}

StockMovementViewController.resolve = {

    homeFacility: function ($q, $timeout, UserFacilityList) {
        var deferred = $q.defer();
        var homeFacility = {};

        $timeout(function () {
            UserFacilityList.get({}, function (data) {
                homeFacility = data.facilityList[0];
                deferred.resolve(homeFacility);
            });

        }, 100);
        return deferred.promise;
    },
    programs: function ($q, $timeout, VaccineHomeFacilityPrograms) {
        var deferred = $q.defer();
        $timeout(function () {
            VaccineHomeFacilityPrograms.get({}, function (data) {
                deferred.resolve(data.programs);
            });
        }, 100);

        return deferred.promise;
    }

};
<commit_msg>Undo issue date required<commit_after>/*
 * This program is part of the OpenLMIS logistics management information system platform software.
 * Copyright © 2013 VillageReach
 *
 * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
 * You should have received a copy of the GNU Affero General Public License along with this program.  If not, see http://www.gnu.org/licenses.  For additional information contact info@OpenLMIS.org.
 */

function StockMovementViewController($scope, $window,SaveDistribution,StockEvent, UpdateOrderRequisitionStatus,VaccineLastStockMovement, StockCardsByCategoryAndRequisition, StockCardsForProgramByCategory, $dialog, homeFacility, programs, $routeParams, $location) {

    var orderId = parseInt($routeParams.id, 10);
    var programId = parseInt($routeParams.programId, 10);
    var periodId = parseInt($routeParams.periodId, 10);

    var homeFacilityId = parseInt(homeFacility.id, 10);
    var toFacilityId = parseInt($routeParams.facilityId, 10);
    $scope.toFacilityName = $routeParams.facilityName;

    var program = programs;

    $scope.line = [];
    $scope.facilities = [];
    $scope.date = new Date();

    $scope.pageSize = parseInt(10, 10);
    var pageLineItems = [];

    $scope.homeFacility = $routeParams.facility;

    var refreshPageLineItems = function () {

        if (isUndefined(homeFacilityId) && isUndefined(programs[0].id &&
                isUndefined(periodId) && isUndefined(toFacilityId))) {

            return 'No pending Requisition';

        } else {

            StockCardsForProgramByCategory.get(program[0].id, homeFacilityId, periodId, toFacilityId).then(function (data) {
                $scope.pageLineItems = data;
                pageLineItems = data;
                $scope.numberOfPages = Math.ceil(pageLineItems.length / $scope.pageSize) || 1;
                $scope.currentPage = (utils.isValidPage($routeParams.page, $scope.numberOfPages)) ? parseInt($routeParams.page, 10) : 1;
                $scope.stockCardsByCategory = $scope.pageLineItems.slice($scope.pageSize * ($scope.currentPage - 1), $scope.pageSize * $scope.currentPage);
              // console.log(JSON.stringify($scope.stockCardsByCategory));
            });
        }

    };

    refreshPageLineItems();

    $scope.$watch('currentPage', function () {
        $location.search('page', $scope.currentPage);
    });

    $scope.$on('$routeUpdate', function () {
        refreshPageLineItems();
    });

    $scope.sumLots = function (c) {

        var total = 0;
        c.lotsOnHand.forEach(function (l) {
            var x = ((l.quantity === '' || l.quantity === undefined) ? 0 : parseInt(l.quantity, 10));
            total = total + x;

        });

        $scope.total = total;

        c.sum = parseInt(c.quantityRequested, 10) - total;

    };

    $scope.save = function () {
        $scope.message = 'Saved Successfully';
        return $scope.message;
    };
    var printTest = false;

    $scope.submit = function () {
//        if ($scope.orderRequisitionForm.$error.required) {
//            $scope.showError = true;
//            $scope.error = "The form you submitted is invalid. Please revise and try again.";
//            return;
//        }

        var transaction = {};
        transaction.transactionList = [];

        var lastInsertedReport = {};
        lastInsertedReport.list = [];

        var callBack = function (result) {
            if (result) {
                var distribution = {};
                var events=[];

                distribution.fromFacilityId = homeFacility.id;
                distribution.toFacilityId= toFacilityId;
                distribution.distributionDate = $scope.stockCardsByCategory[0].issueDate;
                distribution.periodId = periodId;
                distribution.orderId = orderId;
                distribution.lineItems=[];
                distribution.distributionType="SCHEDULED";
                distribution.status="PENDING";

                $scope.stockCardsByCategory.forEach(function (st) {

                    st.stockCards.forEach(function (s) {

                           var lineItem = {};

                           lineItem.productId = s.product.id;
                           if(s.lotsOnHand.length >0)
                           {
                           lineItem.lots = [];
                           var lotSum = 0;
                           s.lotsOnHand.forEach(function (l) {

                               if( l.quantity >0)
                               {
                                   var lot = {};
                                   var event={};
                                   event.type="ISSUE";
                                   event.productCode= s.product.code;
                                   event.facilityId=toFacilityId;
                                   event.lotId= l.lot.id;
                                   event.quantity= l.quantity;
                                   event.customProps={"occurred":st.issueDate};
                                   events.push(event);

                                   lot.lotId = l.lot.id;
                                   lot.quantity = l.quantity;
                                   lot.vvmStatus=l.customProps.vvmstatus;
                                   lineItem.lots.push(lot);
                                   lotSum = lotSum + l.quantity;
                               }
                              });
                               lineItem.quantity = lotSum;

                           }
                        else{
                               var event={};
                               event.type="ISSUE";
                               event.productCode= s.product.code;
                               event.facilityId=toFacilityId;
                               event.quantity= st.quantity;
                               event.customPros={"occurred":st.issueDate};
                               events.push(event);

                           }

                       distribution.lineItems.push(lineItem);

                    });

                });
              StockEvent.save({facilityId:homeFacility.id},events,function(data){
                   SaveDistribution.save(distribution,function(distribution) {
                        UpdateOrderRequisitionStatus.update({orderId: orderId}, function () {
                            print(distribution.distributionId);
                            $scope.message = "label.form.Submitted.Successfully";
                         });
                   });
               });

            }
        };

        var options = {
            id: "confirmDialog",
            header: "label.confirm.issue.submit.action",
            body: "msg.question.submit.order.confirmation"
        };

        OpenLmisDialog.newDialog(options, callBack, $dialog);

    };

    var print = function(distributionId){
              var url = '/vaccine/orderRequisition/issue/print/'+distributionId;
               $window.open(url, '_blank');

               $window.location = '/public/pages/vaccine/inventory/dashboard/index.html#/stock-on-hand';

         };

    $scope.cancel = function () {
        $window.location = '/public/pages/vaccine/order-requisition/index.html#/view';
    };

}

StockMovementViewController.resolve = {

    homeFacility: function ($q, $timeout, UserFacilityList) {
        var deferred = $q.defer();
        var homeFacility = {};

        $timeout(function () {
            UserFacilityList.get({}, function (data) {
                homeFacility = data.facilityList[0];
                deferred.resolve(homeFacility);
            });

        }, 100);
        return deferred.promise;
    },
    programs: function ($q, $timeout, VaccineHomeFacilityPrograms) {
        var deferred = $q.defer();
        $timeout(function () {
            VaccineHomeFacilityPrograms.get({}, function (data) {
                deferred.resolve(data.programs);
            });
        }, 100);

        return deferred.promise;
    }

};
<|endoftext|>


<commit_before>describe('Confirm widget service', function() {
    'use strict';

    beforeEach(module('talend.widget'));
    beforeEach(module('htmlTemplates'));

    it('should create scope and confirm element', inject(function(TalendConfirmService) {
        //given
        var text1 = 'text 1';
        var text2 = 'text 2';
        var body = angular.element('body');
        expect(TalendConfirmService.modalScope).toBeFalsy();
        expect(TalendConfirmService.element).toBeFalsy();
        expect(body.has('talend-confirm').length).toBe(0);

        //when
        TalendConfirmService.confirm(text1, text2);

        //then
        expect(TalendConfirmService.modalScope).toBeTruthy();
        expect(TalendConfirmService.modalScope.texts).toEqual([text1, text2]);
        expect(TalendConfirmService.element).toBeTruthy();
        expect(TalendConfirmService.element.scope()).toBe(TalendConfirmService.modalScope);

        expect(body.has('talend-confirm').length).toBe(1);
    }));

    describe('with existing confirm', function() {
        var promise, element, scope;

        beforeEach(inject(function(TalendConfirmService) {
            promise = TalendConfirmService.confirm();
            scope = TalendConfirmService.modalScope;
            element = TalendConfirmService.element;

            spyOn(element, 'remove').and.callThrough();
        }));

        it('should throw error on confirm create but another confirm modal is already created', inject(function(TalendConfirmService) {
            //when
            try {
                TalendConfirmService.confirm();
            }

                //then
            catch(error) {
                expect(error.message).toBe('A confirm popup is already created');
                return;
            }
            throw Error('should have thrown error on second confirm() call');
        }));

        it('should resolve promise and remove/destroy scope and element', inject(function($timeout, TalendConfirmService) {
            //given
            var resolved = false;
            promise.then(function() {
                resolved = true;
            });

            var scopeDestroyed = false;
            scope.$on('$destroy', function() {
                scopeDestroyed = true;
            });

            //when
            TalendConfirmService.resolve();
            $timeout.flush();

            //then
            expect(resolved).toBe(true);
            expect(scopeDestroyed).toBe(true);
            expect(element.remove).toHaveBeenCalled();
            expect(TalendConfirmService.modalScope).toBeFalsy();
            expect(TalendConfirmService.element).toBeFalsy();
        }));

        it('should reject promise and remove/destroy scope and element', inject(function($timeout, TalendConfirmService) {
            //given
            var cause = false;
            promise.catch(function(error) {
                cause = error;
            });

            var scopeDestroyed = false;
            scope.$on('$destroy', function() {
                scopeDestroyed = true;
            });

            //when
            TalendConfirmService.reject('dismiss');
            $timeout.flush();

            //then
            expect(cause).toBe('dismiss');
            expect(scopeDestroyed).toBe(true);
            expect(element.remove).toHaveBeenCalled();
            expect(TalendConfirmService.modalScope).toBeFalsy();
            expect(TalendConfirmService.element).toBeFalsy();
        }));
    });
});<commit_msg>TDP-41 : correct unit tests after master merge<commit_after>describe('Confirm widget service', function() {
    'use strict';

    beforeEach(module('talend.widget'));
    beforeEach(module('htmlTemplates'));

    afterEach(inject(function($timeout, TalendConfirmService) {
        if(TalendConfirmService.element) {
            TalendConfirmService.resolve();
            $timeout.flush();
        }
    }));

    it('should create scope and confirm element', inject(function($rootScope, TalendConfirmService) {
        //given
        var text1 = 'text 1';
        var text2 = 'text 2';
        var body = angular.element('body');
        expect(TalendConfirmService.modalScope).toBeFalsy();
        expect(TalendConfirmService.element).toBeFalsy();
        expect(body.has('talend-confirm').length).toBe(0);

        //when
        TalendConfirmService.confirm(text1, text2);
        $rootScope.$digest();

        //then
        expect(TalendConfirmService.modalScope).toBeTruthy();
        expect(TalendConfirmService.modalScope.texts).toEqual([text1, text2]);
        expect(TalendConfirmService.element).toBeTruthy();
        expect(TalendConfirmService.element.scope()).toBe(TalendConfirmService.modalScope);

        expect(body.has('talend-confirm').length).toBe(1);
    }));

    describe('with existing confirm', function() {
        var promise, element, scope;

        beforeEach(inject(function($rootScope, TalendConfirmService) {
            promise = TalendConfirmService.confirm();
            $rootScope.$digest();

            scope = TalendConfirmService.modalScope;
            element = TalendConfirmService.element;

            spyOn(element, 'remove').and.callThrough();
        }));

        it('should throw error on confirm create but another confirm modal is already created', inject(function($timeout, TalendConfirmService) {
            //when
            try {
                TalendConfirmService.confirm();
            }

            //then
            catch(error) {
                expect(error.message).toBe('A confirm popup is already created');
                TalendConfirmService.resolve();
                $timeout.flush();
                return;
            }
            throw Error('should have thrown error on second confirm() call');
        }));

        it('should resolve promise and remove/destroy scope and element', inject(function($timeout, TalendConfirmService) {
            //given
            var resolved = false;
            promise.then(function() {
                resolved = true;
            });

            var scopeDestroyed = false;
            scope.$on('$destroy', function() {
                scopeDestroyed = true;
            });

            //when
            TalendConfirmService.resolve();
            $timeout.flush();

            //then
            expect(resolved).toBe(true);
            expect(scopeDestroyed).toBe(true);
            expect(element.remove).toHaveBeenCalled();
            expect(TalendConfirmService.modalScope).toBeFalsy();
            expect(TalendConfirmService.element).toBeFalsy();
        }));

        it('should reject promise and remove/destroy scope and element', inject(function($timeout, TalendConfirmService) {
            //given
            var cause = false;
            promise.catch(function(error) {
                cause = error;
            });

            var scopeDestroyed = false;
            scope.$on('$destroy', function() {
                scopeDestroyed = true;
            });

            //when
            TalendConfirmService.reject('dismiss');
            $timeout.flush();

            //then
            expect(cause).toBe('dismiss');
            expect(scopeDestroyed).toBe(true);
            expect(element.remove).toHaveBeenCalled();
            expect(TalendConfirmService.modalScope).toBeFalsy();
            expect(TalendConfirmService.element).toBeFalsy();
        }));
    });
});<|endoftext|>


<commit_before>const ROMVID = 0x0451;
const ROMPID = 0x6141;
const BOOTPS = 67;
const BOOTPC = 68;
const IPUDP = 17;
const SPLVID = 0x0525;
const SPLPID = 0xA4A2;
const ETHIPP = 0x0800;
const ETHARPP = 0x0806;
const MAXBUF = 450;
const server_hwaddr = [0x9a, 0x1f, 0x85, 0x1c, 0x3d, 0x0e];
const server_ip = [0xc0, 0xa8, 0x01, 0x09];     // 192.168.1.9
const BB_ip = [0xc0, 0xa8, 0x01, 0x03];         // 192.168.1.3
const servername = [66, 69, 65, 71, 76, 69, 66, 79, 79, 84];       // ASCII ['B','E','A','G','L','E','B','O','O','T']
const file_spl = [83, 80, 76, 0, 0];                             // ASCII ['S','P','L']
const file_uboot = [85, 66, 79, 79, 84];                           // ASCII ['U','B','O','O','T']

// Size of all packets
var rndisSize = 44;
var etherSize = 14;
var arp_Size = 28;
var ipSize = 20;
var udpSize = 8;
var bootpSize = 300;
var tftpSize = 4;
var fullSize = 386;

// Include modules
var usb = require('usb');
var protocols = require('./src/protocols');
var deasync = require('deasync');
var fs = require('fs');

// Connect to BeagleBone
var device = usb.findByIds(ROMVID, ROMPID);
device.open();
var interface = device.interface(1);    // Select interface 1

// Detach Kernel Driver
if(interface.isKernelDriverActive()){
    interface.detachKernelDriver();
}

interface.claim();

// Set endpoints for usb transfer
var inEndpoint = interface.endpoint(0x81);
var outEndpoint = interface.endpoint(0x02);

// Set endpoint transfer type
inEndpoint.transferType = usb.LIBUSB_TRANSFER_TYPE_BULK;
outEndpoint.transferType = usb.LIBUSB_TRANSFER_TYPE_BULK;

// Receive BOOTP
var bootp_buf = Buffer.alloc(MAXBUF-rndisSize);     // Buffer for InEnd transfer
inEndpoint.timeout = 0;
inEndpoint.transfer(MAXBUF, onFirstIn);             // InEnd transfer
var done = false;                                   // Boolean for sync function
function onFirstIn(error, data) {                   // Callback for InEnd transfer
        data.copy(bootp_buf, 0, rndisSize, MAXBUF);
        done = true;
}
deasync.loopWhile(function(){return !done;});       // Synchronize InEnd transfer function

var ether = protocols.decode_ether(bootp_buf);      // Gets decoded ether packet data

var rndis = protocols.make_rndis(fullSize-rndisSize);   // Make RNDIS

var eth2 = protocols.make_ether2(ether.h_source, server_hwaddr, ETHIPP);    // Make ether2

var ip = protocols.make_ipv4(server_ip, BB_ip, IPUDP, 0, ipSize + udpSize + bootpSize, 0); // Make ipv4

var udp = protocols.make_udp(bootpSize, BOOTPS, BOOTPC);    // Make udp

var bootreply = protocols.make_bootp(servername, file_spl, 1, ether.h_source, BB_ip, server_ip);    // Make BOOTP for reply

var data = Buffer.concat([rndis, eth2, ip, udp, bootreply], fullSize);      // BOOT Reply

// Send BOOT reply
outEndpoint.timeout = 0;
done = false;
outEndpoint.transfer(data, function(error){
    console.log(error);
    done = true;
});
deasync.loopWhile(function(){return !done;});           // Synchronize OutEnd transfer

// Receive ARP request
var arp_buf = Buffer.alloc(arp_Size);
inEndpoint.timeout = 0;
done = false;
inEndpoint.transfer(MAXBUF, function(error, data){
    data.copy(arp_buf, 0, rndisSize + etherSize, rndisSize + etherSize + arp_Size);
    done = true;
});
deasync.loopWhile(function(){ return !done;});

var receivedARP = protocols.parse_arp(arp_buf);         // Parsed received ARP request

// ARP response
var arpResponse = protocols.make_arp(2, server_hwaddr, receivedARP.ip_dest, receivedARP.hw_source, receivedARP.ip_source );

rndis = protocols.make_rndis(etherSize + arp_Size);

eth2 = protocols.make_ether2(ether.h_source, server_hwaddr, ETHARPP);

data = Buffer.concat([rndis, eth2, arpResponse], rndisSize + etherSize + arp_Size);

// Send ARP response
outEndpoint.timeout = 0;
done = false;
outEndpoint.transfer(data, function(error){
    console.log(error);
    done = true;
});
deasync.loopWhile(function(){return !done;});

// Receive SPL TFTP request
var udpSPL_buf = Buffer.alloc(udpSize);
inEndpoint.timeout = 0;
done = false;
inEndpoint.transfer(MAXBUF, function(error, data){
    data.copy(udpSPL_buf, 0, rndisSize + etherSize + ipSize, rndisSize + etherSize + ipSize + udpSize);
    done = true;
});
deasync.loopWhile(function(){ return !done;});

var udpSPL = protocols.parse_udp(udpSPL_buf);           // Received UDP packet for SPL tftp

////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////// SPL File Transfer ////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////

var spl = fs.readFileSync("./bin/spl");
var blocks = Math.ceil(spl.length/512);         // Total number of blocks of file

eth2 = protocols.make_ether2(ether.h_source, server_hwaddr, ETHIPP);

var start = 0;                                  // Source start for copy

for(var i=1; i<=blocks; i++){                   // i is block number

    var blk_size = (i==blocks)? spl.length - (blocks-1)*512 : 512;  // Different block size for last block

    var blk_data = Buffer.alloc(blk_size);
    spl.copy(blk_data, 0, start, start + blk_size);                 // Copying data to block
    start += blk_size;

    rndis = protocols.make_rndis(etherSize + ipSize + udpSize + tftpSize + blk_size);
    ip = protocols.make_ipv4(server_ip, BB_ip, IPUDP, 0, ipSize + udpSize + tftpSize + blk_size, 0);
    udp = protocols.make_udp(tftpSize + blk_size, udpSPL.udpDest, udpSPL.udpSrc);
    tftp = protocols.make_tftp(3, i);

    var spl_data = Buffer.concat([rndis, eth2, ip, udp, tftp, blk_data], rndisSize + etherSize + ipSize + udpSize + tftpSize + blk_size);

    // Send SPL file data
    outEndpoint.timeout = 0;
    done = false;
    outEndpoint.transfer(spl_data, function(error){
    console.log(error);
    done = true;
    });
    deasync.loopWhile(function(){return !done;});

    // Receive buffer back
    inEndpoint.timeout = 0;
    done = false;
    inEndpoint.transfer(MAXBUF, function(error, data){
    done = true;
    });
    deasync.loopWhile(function(){ return !done;});
}

// Wait for SPL initialization
function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}
sleep(2000);

// Connect to BeagleBone via SPL
device = usb.findByIds(SPLVID, SPLPID);
device.open();
interface = device.interface(1);

// Detach Kernel Driver
if(interface.isKernelDriverActive()){
    interface.detachKernelDriver();
}

interface.claim();
console.log("SPL started running");

// Set endpoints for usb transfer
inEndpoint = interface.endpoint(0x81);
outEndpoint = interface.endpoint(0x01);

// Set endpoint transfer type
inEndpoint.transferType = usb.LIBUSB_TRANSFER_TYPE_BULK;
outEndpoint.transferType = usb.LIBUSB_TRANSFER_TYPE_BULK;

// Receive BOOTP
var udpUboot_buf = Buffer.alloc(udpSize);
var spl_bootp_buf = Buffer.alloc(bootpSize);
inEndpoint.timeout = 0;
var done = false;
inEndpoint.transfer(MAXBUF, function (error, data) {
        data.copy(udpUboot_buf, 0, rndisSize + etherSize + ipSize, MAXBUF);
        data.copy(spl_bootp_buf, 0, rndisSize + etherSize + ipSize + udpSize, MAXBUF);
        done = true;
});
deasync.loopWhile(function(){return !done;});

var udpUboot = protocols.parse_udp(udpUboot_buf);       // parsed udp header
var spl_bootp = protocols.parse_bootp(spl_bootp_buf);   // parsed bootp header

rndis = protocols.make_rndis(rndisSize);
eth2 = protocols.make_ether2(ether.h_source, server_hwaddr, ETHIPP);
ip = protocols.make_ipv4(server_ip, BB_ip, IPUDP, 0, ipSize + udpSize + bootpSize, 0);
udp = protocols.make_udp(bootpSize, udpUboot.udpDest, udpUboot.udpSrc);
bootreply = protocols.make_bootp(servername, file_uboot, spl_bootp.xid, ether.h_source, BB_ip, server_ip);

data = Buffer.concat([rndis, eth2, ip, udp, bootreply], fullSize);

// Send BOOT reply
outEndpoint.timeout = 0;
done = false;
outEndpoint.transfer(data, function(error){
    console.log(error);
    done = true;
});
deasync.loopWhile(function(){return !done;});   <commit_msg>send arp response for spl<commit_after>const ROMVID = 0x0451;
const ROMPID = 0x6141;
const BOOTPS = 67;
const BOOTPC = 68;
const IPUDP = 17;
const SPLVID = 0x0525;
const SPLPID = 0xA4A2;
const ETHIPP = 0x0800;
const ETHARPP = 0x0806;
const MAXBUF = 450;
const server_hwaddr = [0x9a, 0x1f, 0x85, 0x1c, 0x3d, 0x0e];
const server_ip = [0xc0, 0xa8, 0x01, 0x09];     // 192.168.1.9
const BB_ip = [0xc0, 0xa8, 0x01, 0x03];         // 192.168.1.3
const servername = [66, 69, 65, 71, 76, 69, 66, 79, 79, 84];       // ASCII ['B','E','A','G','L','E','B','O','O','T']
const file_spl = [83, 80, 76, 0, 0];                             // ASCII ['S','P','L']
const file_uboot = [85, 66, 79, 79, 84];                           // ASCII ['U','B','O','O','T']

// Size of all packets
var rndisSize = 44;
var etherSize = 14;
var arp_Size = 28;
var ipSize = 20;
var udpSize = 8;
var bootpSize = 300;
var tftpSize = 4;
var fullSize = 386;

// Include modules
var usb = require('usb');
var protocols = require('./src/protocols');
var deasync = require('deasync');
var fs = require('fs');

// Connect to BeagleBone
var device = usb.findByIds(ROMVID, ROMPID);
device.open();
var interface = device.interface(1);    // Select interface 1

// Detach Kernel Driver
if(interface.isKernelDriverActive()){
    interface.detachKernelDriver();
}

interface.claim();

// Set endpoints for usb transfer
var inEndpoint = interface.endpoint(0x81);
var outEndpoint = interface.endpoint(0x02);

// Set endpoint transfer type
inEndpoint.transferType = usb.LIBUSB_TRANSFER_TYPE_BULK;
outEndpoint.transferType = usb.LIBUSB_TRANSFER_TYPE_BULK;

// Receive BOOTP
var bootp_buf = Buffer.alloc(MAXBUF-rndisSize);     // Buffer for InEnd transfer
inEndpoint.timeout = 0;
inEndpoint.transfer(MAXBUF, onFirstIn);             // InEnd transfer
var done = false;                                   // Boolean for sync function
function onFirstIn(error, data) {                   // Callback for InEnd transfer
        data.copy(bootp_buf, 0, rndisSize, MAXBUF);
        done = true;
}
deasync.loopWhile(function(){return !done;});       // Synchronize InEnd transfer function

var ether = protocols.decode_ether(bootp_buf);      // Gets decoded ether packet data

var rndis = protocols.make_rndis(fullSize-rndisSize);   // Make RNDIS

var eth2 = protocols.make_ether2(ether.h_source, server_hwaddr, ETHIPP);    // Make ether2

var ip = protocols.make_ipv4(server_ip, BB_ip, IPUDP, 0, ipSize + udpSize + bootpSize, 0); // Make ipv4

var udp = protocols.make_udp(bootpSize, BOOTPS, BOOTPC);    // Make udp

var bootreply = protocols.make_bootp(servername, file_spl, 1, ether.h_source, BB_ip, server_ip);    // Make BOOTP for reply

var data = Buffer.concat([rndis, eth2, ip, udp, bootreply], fullSize);      // BOOT Reply

// Send BOOT reply
outEndpoint.timeout = 0;
done = false;
outEndpoint.transfer(data, function(error){
    console.log(error);
    done = true;
});
deasync.loopWhile(function(){return !done;});           // Synchronize OutEnd transfer

// Receive ARP request
var arp_buf = Buffer.alloc(arp_Size);
inEndpoint.timeout = 0;
done = false;
inEndpoint.transfer(MAXBUF, function(error, data){
    data.copy(arp_buf, 0, rndisSize + etherSize, rndisSize + etherSize + arp_Size);
    done = true;
});
deasync.loopWhile(function(){ return !done;});

var receivedARP = protocols.parse_arp(arp_buf);         // Parsed received ARP request

// ARP response
var arpResponse = protocols.make_arp(2, server_hwaddr, receivedARP.ip_dest, receivedARP.hw_source, receivedARP.ip_source );

rndis = protocols.make_rndis(etherSize + arp_Size);

eth2 = protocols.make_ether2(ether.h_source, server_hwaddr, ETHARPP);

data = Buffer.concat([rndis, eth2, arpResponse], rndisSize + etherSize + arp_Size);

// Send ARP response
outEndpoint.timeout = 0;
done = false;
outEndpoint.transfer(data, function(error){
    console.log(error);
    done = true;
});
deasync.loopWhile(function(){return !done;});

// Receive SPL TFTP request
var udpSPL_buf = Buffer.alloc(udpSize);
inEndpoint.timeout = 0;
done = false;
inEndpoint.transfer(MAXBUF, function(error, data){
    data.copy(udpSPL_buf, 0, rndisSize + etherSize + ipSize, rndisSize + etherSize + ipSize + udpSize);
    done = true;
});
deasync.loopWhile(function(){ return !done;});

var udpSPL = protocols.parse_udp(udpSPL_buf);           // Received UDP packet for SPL tftp

////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////// SPL File Transfer ////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////

var spl = fs.readFileSync("./bin/spl");
var blocks = Math.ceil(spl.length/512);         // Total number of blocks of file

eth2 = protocols.make_ether2(ether.h_source, server_hwaddr, ETHIPP);

var start = 0;                                  // Source start for copy

for(var i=1; i<=blocks; i++){                   // i is block number

    var blk_size = (i==blocks)? spl.length - (blocks-1)*512 : 512;  // Different block size for last block

    var blk_data = Buffer.alloc(blk_size);
    spl.copy(blk_data, 0, start, start + blk_size);                 // Copying data to block
    start += blk_size;

    rndis = protocols.make_rndis(etherSize + ipSize + udpSize + tftpSize + blk_size);
    ip = protocols.make_ipv4(server_ip, BB_ip, IPUDP, 0, ipSize + udpSize + tftpSize + blk_size, 0);
    udp = protocols.make_udp(tftpSize + blk_size, udpSPL.udpDest, udpSPL.udpSrc);
    tftp = protocols.make_tftp(3, i);

    var spl_data = Buffer.concat([rndis, eth2, ip, udp, tftp, blk_data], rndisSize + etherSize + ipSize + udpSize + tftpSize + blk_size);

    // Send SPL file data
    outEndpoint.timeout = 0;
    done = false;
    outEndpoint.transfer(spl_data, function(error){
    console.log(error);
    done = true;
    });
    deasync.loopWhile(function(){return !done;});

    // Receive buffer back
    inEndpoint.timeout = 0;
    done = false;
    inEndpoint.transfer(MAXBUF, function(error, data){
    done = true;
    });
    deasync.loopWhile(function(){ return !done;});
}

// Wait for SPL initialization
function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}
sleep(2000);

// Connect to BeagleBone via SPL
device = usb.findByIds(SPLVID, SPLPID);
device.open();
interface = device.interface(1);

// Detach Kernel Driver
if(interface.isKernelDriverActive()){
    interface.detachKernelDriver();
}

interface.claim();
console.log("SPL started running");

// Set endpoints for usb transfer
inEndpoint = interface.endpoint(0x81);
outEndpoint = interface.endpoint(0x01);

// Set endpoint transfer type
inEndpoint.transferType = usb.LIBUSB_TRANSFER_TYPE_BULK;
outEndpoint.transferType = usb.LIBUSB_TRANSFER_TYPE_BULK;

// Receive BOOTP
var udpUboot_buf = Buffer.alloc(udpSize);
var spl_bootp_buf = Buffer.alloc(bootpSize);
inEndpoint.timeout = 0;
var done = false;
inEndpoint.transfer(MAXBUF, function (error, data) {
        data.copy(udpUboot_buf, 0, rndisSize + etherSize + ipSize, MAXBUF);
        data.copy(spl_bootp_buf, 0, rndisSize + etherSize + ipSize + udpSize, MAXBUF);
        done = true;
});
deasync.loopWhile(function(){return !done;});

var udpUboot = protocols.parse_udp(udpUboot_buf);       // parsed udp header
var spl_bootp = protocols.parse_bootp(spl_bootp_buf);   // parsed bootp header

rndis = protocols.make_rndis(fullSize - rndisSize);
eth2 = protocols.make_ether2(ether.h_source, server_hwaddr, ETHIPP);
ip = protocols.make_ipv4(server_ip, BB_ip, IPUDP, 0, ipSize + udpSize + bootpSize, 0);
udp = protocols.make_udp(bootpSize, udpUboot.udpDest, udpUboot.udpSrc);
bootreply = protocols.make_bootp(servername, file_uboot, spl_bootp.xid, ether.h_source, BB_ip, server_ip);

data = Buffer.concat([rndis, eth2, ip, udp, bootreply], fullSize);

// Send BOOT reply
outEndpoint.timeout = 0;
done = false;
outEndpoint.transfer(data, function(error){
    console.log(error);
    done = true;
});
deasync.loopWhile(function(){return !done;});

// Receive ARP request
inEndpoint.timeout = 0;
done = false;
inEndpoint.transfer(MAXBUF, function(error, data){
    //data.copy(arp_buf, 0, rndisSize + etherSize, rndisSize + etherSize + arp_Size);
    done = true;
});
deasync.loopWhile(function(){ return !done;});

// ARP response
arpResponse = protocols.make_arp(2, server_hwaddr, receivedARP.ip_dest, receivedARP.hw_source, receivedARP.ip_source );

rndis = protocols.make_rndis(etherSize + arp_Size);

eth2 = protocols.make_ether2(ether.h_source, server_hwaddr, ETHARPP);

data = Buffer.concat([rndis, eth2, arpResponse], rndisSize + etherSize + arp_Size);

// Send ARP response
outEndpoint.timeout = 0;
done = false;
outEndpoint.transfer(data, function(error){
    console.log(error);
    done = true;
});
deasync.loopWhile(function(){return !done;});   <|endoftext|>


<commit_before>var Response = require("ringo/webapp/response").Response;

exports.app = function(app) {
    return Response.skin(module.resolve("../skins/composer.html"));
};
<commit_msg>Redirecting to index if not authorized for composer.<commit_after>var Response = require("ringo/webapp/response").Response;
var Request = require("ringo/webapp/request").Request;
var auth = require("../auth");

exports.app = function(req) {
    var request = new Request(req);
    var details = auth.getDetails(request);
    var response;
    if (details.status === 401) {
        var parts = request.path.split("/");
        parts.pop();
        parts.push("");
        response = {
            status: 301,
            headers: {"Location": request.scheme + "://" + request.host + ":" + request.port + parts.join("/")},
            body: []
        };
    } else {
        response = Response.skin(module.resolve("../skins/composer.html"));
    }
    return response;
};
<|endoftext|>