<commit_before>var sspage = require("./lib/SilverstripePage");
var ConsoleOutput = require("./lib/ConsoleOutput.js");
var fs = require("fs");
var _SITES;
var __CFGFILE = "sites.json";

if(process.argv.indexOf('--debug') > 1)
    process.__DEBUG = true;

if(!fs.existsSync(__CFGFILE)){
    fs.writeFileSync(__CFGFILE,'[]');
}

try{
    _SITES = JSON.parse(fs.readFileSync(__CFGFILE));
}catch(e){
    console.log("Can't parse "+__CFGFILE);
    return;
}

if(process.argv[2] === "add") {
    if(process.argv[3] && process.argv[4]){
        addSite(process.argv[3],process.argv[4]);
    }
    return;
}

if(process.argv[2] === "remove" && process.argv[3]){
    removeSite(process.argv[3]);
    return;
}

filterSites();
printSites(findFormat());

/***********************************************************************/

function addSite(sitename,projectpath){
    var siteexists = false;
    if(!_SITES) _SITES = [];
    _SITES.map(function(i){
        if(i.name == sitename){
            siteexists = true;
        }
    });
    if(!siteexists) {
        _SITES.push({
            name: sitename,
            path: projectpath
        });
        fs.writeFileSync(__CFGFILE, JSON.stringify(_SITES));
        console.log("Site added: "+sitename);
    }else{
        console.log("Site with that name already exists: "+sitename);
    }
}

function removeSite(sitename){
    var siteindex = -1;
    if(!_SITES) _SITES = [];

    for(var i in _SITES){
        if(_SITES[i].name == sitename){
            siteindex = i;
        }
    }
    if(siteindex) {
        _SITES.splice(siteindex,siteindex+1);
        fs.writeFileSync(__CFGFILE, JSON.stringify(_SITES));
        console.log("Site removed: "+sitename);
    }else{
        console.log("Site with that did not exist: "+sitename);
    }
}

function printSites(format){
    if(!_SITES.length){
        console.log("No sites found. Add sites with: node analyzer add NAME PATH");
    }
    if(process.argv.indexOf("--table") > 1)
        var isTable = true;

    if(isTable) {
        var couttable = ConsoleOutput.ConsoleOutputTable(findColumns());
    }

    for (var i in _SITES) {
        var site = _SITES[i];
        var page = sspage.create(site);
        if(!page)continue;

        if(isTable){
            couttable.addPage(page);
        }else {
            var coutformat = ConsoleOutput.ConsoleOutputFormat(format);
            coutformat.print(page);
        }
    }

    if(isTable)
        couttable.print();
}

function findColumns(){
    var format;
    process.argv.forEach(function(e){
        var rex = /^--table-columns=/;
        if(e.search(rex) > -1) {
            format = e.replace(rex,"");
        }
    });
    return format;
}

function findFormat(){
    var format;
    process.argv.forEach(function(e){
        var rex = /^--format=/;
        if(e.search(rex) > -1) {
            format = e.replace(rex,"");
        }
    });
    return format;
}

function filterSites(){
    process.argv.forEach(function(e){
        if(e.search(/^--filter-name=/) > -1) {
            var filterName = e.replace(/^--filter-name=/,"");
            for (var i in _SITES) {
                if(_SITES[i].name.search(filterName) == -1){
                    delete _SITES[i];
                }
            }
        }

    });
}<commit_msg>sites.json is now written with spaces for better readability<commit_after>var sspage = require("./lib/SilverstripePage");
var ConsoleOutput = require("./lib/ConsoleOutput.js");
var fs = require("fs");
var _SITES;
var __CFGFILE = "sites.json";

if(process.argv.indexOf('--debug') > 1)
    process.__DEBUG = true;

if(!fs.existsSync(__CFGFILE)){
    fs.writeFileSync(__CFGFILE,'[]');
}

try{
    _SITES = JSON.parse(fs.readFileSync(__CFGFILE));
}catch(e){
    console.log("Can't parse "+__CFGFILE);
    return;
}

if(process.argv[2] === "add") {
    if(process.argv[3] && process.argv[4]){
        addSite(process.argv[3],process.argv[4]);
    }
    return;
}

if(process.argv[2] === "remove" && process.argv[3]){
    removeSite(process.argv[3]);
    return;
}

filterSites();
printSites(findFormat());

/***********************************************************************/

function addSite(sitename,projectpath){
    var siteexists = false;
    if(!_SITES) _SITES = [];
    _SITES.map(function(i){
        if(i.name == sitename){
            siteexists = true;
        }
    });
    if(!siteexists) {
        _SITES.push({
            name: sitename,
            path: projectpath
        });
        fs.writeFileSync(__CFGFILE, JSON.stringify(_SITES,null,4));
        console.log("Site added: "+sitename);
    }else{
        console.log("Site with that name already exists: "+sitename);
    }
}

function removeSite(sitename){
    var siteindex = -1;
    if(!_SITES) _SITES = [];

    for(var i in _SITES){
        if(_SITES[i].name == sitename){
            siteindex = i;
        }
    }
    if(siteindex) {
        _SITES.splice(siteindex,siteindex+1);
        fs.writeFileSync(__CFGFILE, JSON.stringify(_SITES,null,4));
        console.log("Site removed: "+sitename);
    }else{
        console.log("Site with that did not exist: "+sitename);
    }
}

function printSites(format){
    if(!_SITES.length){
        console.log("No sites found. Add sites with: node analyzer add NAME PATH");
    }
    if(process.argv.indexOf("--table") > 1)
        var isTable = true;

    if(isTable) {
        var couttable = ConsoleOutput.ConsoleOutputTable(findColumns());
    }

    for (var i in _SITES) {
        var site = _SITES[i];
        var page = sspage.create(site);
        if(!page)continue;

        if(isTable){
            couttable.addPage(page);
        }else {
            var coutformat = ConsoleOutput.ConsoleOutputFormat(format);
            coutformat.print(page);
        }
    }

    if(isTable)
        couttable.print();
}

function findColumns(){
    var format;
    process.argv.forEach(function(e){
        var rex = /^--table-columns=/;
        if(e.search(rex) > -1) {
            format = e.replace(rex,"");
        }
    });
    return format;
}

function findFormat(){
    var format;
    process.argv.forEach(function(e){
        var rex = /^--format=/;
        if(e.search(rex) > -1) {
            format = e.replace(rex,"");
        }
    });
    return format;
}

function filterSites(){
    process.argv.forEach(function(e){
        if(e.search(/^--filter-name=/) > -1) {
            var filterName = e.replace(/^--filter-name=/,"");
            for (var i in _SITES) {
                if(_SITES[i].name.search(filterName) == -1){
                    delete _SITES[i];
                }
            }
        }

    });
}<|endoftext|>


<commit_before><commit_msg>Add work from class<commit_after><|endoftext|>


<commit_before>/**
 * AngularJS directives for social sharing buttons - Facebook Like, Google+, Twitter and Pinterest
 * @author Jason Watmore <jason@pointblankdevelopment.com.au> (http://jasonwatmore.com)
 * @version 1.2.0
 */
(function() {
    angular.module('angulike', []).directive('fbLike', ['$window', 'setting', function($window, setting) {
        return {
            restrict: 'A',
            scope: {
                fbLike: '=?'
            },
            link: function(scope, element, attrs) {
                if (!$window.FB) {
                    // Load Facebook SDK if not already loaded
                    $.getScript('//connect.facebook.net/pt_BR/sdk.js', function() {
                        $window.FB.init({
                            appId: setting.facebook.appId, //@todo make me an attribute
                            xfbml: true,
                            version: 'v2.0'
                        });
                        renderLikeButton();
                    });
                } else {
                    renderLikeButton();
                }
                scope.$watch('fbLike', function(nv, ov) {
                    if (nv != ov) {
                        renderLikeButton();
                    }
                });
                var watchAdded = false;

                function renderLikeButton() {
                    if (!!attrs.fbLike && !scope.fbLike && !watchAdded) {
                        // wait for data if it hasn't loaded yet
                        var watchAdded = true;
                        var unbindWatch = scope.$watch('fbLike', function(newValue, oldValue) {
                            if (newValue) {
                                renderLikeButton();
                                // only need to run once
                                unbindWatch();
                            }
                        });
                        return;
                    } else {
                        element.html('

');
                        $window.FB.XFBML.parse(element.parent()[0]);
                    }
                }
            }
        };
    }]).directive('googlePlus', ['$window', '$rootScope', function($window, $rootScope) {
        return {
            restrict: 'A',
            scope: {
                googlePlus: '=?'
            },
            link: function(scope, element, attrs) {
                if (!$window.gapi) {
                    // Load Google SDK if not already loaded
                    $.getScript('//apis.google.com/js/platform.js', function() {
                        renderPlusButton();
                    });
                } else {
                    renderPlusButton();
                }
                scope.$watch('googlePlus', function(nv, ov) {
                    if (nv != ov) {
                        renderPlusButton();
                    }
                });
                var watchAdded = false;

                function renderPlusButton() {
                    if (!!attrs.googlePlus && !scope.googlePlus && !watchAdded) {
                        // wait for data if it hasn't loaded yet
                        var watchAdded = true;
                        var unbindWatch = scope.$watch('googlePlus', function(newValue, oldValue) {
                            if (newValue) {
                                renderPlusButton();
                                // only need to run once
                                unbindWatch();
                            }
                        });
                        return;
                    } else {
                        element.html('

');
                        $window.gapi.plusone.go(element.parent()[0]);
                    }
                }
            }
        };
    }]).directive('tweet', ['$window', '$location', '$rootScope',
        function($window, $location, $rootScope) {
            return {
                restrict: 'A',
                scope: {
                    tweet: '=',
                    tweetUrl: '='
                },
                link: function(scope, element, attrs) {
                    if (!$window.twttr) {
                        // Load Twitter SDK if not already loaded
                        $.getScript('//platform.twitter.com/widgets.js', function() {
                            renderTweetButton();
                        });
                    } else {
                        renderTweetButton();
                    }
                    scope.$watch('tweetUrl+tweet', function(nv, ov) {
                        if (nv != ov) {
                            renderTweetButton();
                        }
                    });
                    var watchAdded = false;

                    function renderTweetButton() {
                        if (!scope.tweet && !watchAdded) {
                            // wait for data if it hasn't loaded yet
                            watchAdded = true;
                            var unbindWatch = scope.$watch('tweet', function(newValue, oldValue) {
                                if (newValue) {
                                    renderTweetButton();
                                    // only need to run once
                                    unbindWatch();
                                }
                            });
                            return;
                        } else {
                            element.html('Tweet');
                            $window.twttr.widgets.load(element.parent()[0]);
                        }
                    }
                }
            };
        }
    ]).directive('pinIt', ['$window', '$location',
        function($window, $location) {
            return {
                restrict: 'A',
                scope: {
                    pinIt: '=',
                    pinItImage: '=',
                    pinItUrl: '='
                },
                link: function(scope, element, attrs) {
                    if (!$window.parsePins) {
                        // Load Pinterest SDK if not already loaded
                        (function(d) {
                            var f = d.getElementsByTagName('SCRIPT')[0],
                                p = d.createElement('SCRIPT');
                            p.type = 'text/javascript';
                            p.async = true;
                            p.src = '//assets.pinterest.com/js/pinit.js';
                            p['data-pin-build'] = 'parsePins';
                            p.onload = function() {
                                if (!!$window.parsePins) {
                                    renderPinItButton();
                                } else {
                                    setTimeout(p.onload, 100);
                                }
                            };
                            f.parentNode.insertBefore(p, f);
                        }($window.document));
                    } else {
                        renderPinItButton();
                    }
                    var watchAdded = false;

                    function renderPinItButton() {
                        if (!scope.pinIt && !watchAdded) {
                            // wait for data if it hasn't loaded yet
                            watchAdded = true;
                            var unbindWatch = scope.$watch('pinIt', function(newValue, oldValue) {
                                if (newValue) {
                                    renderPinItButton();
                                    // only need to run once
                                    unbindWatch();
                                }
                            });
                            return;
                        } else {
                            element.html('');
                            $window.parsePins(element.parent()[0]);
                        }
                    }
                }
            };
        }
    ]);
})();
<commit_msg>update(pin): now supports 2way<commit_after>/**
 * AngularJS directives for social sharing buttons - Facebook Like, Google+, Twitter and Pinterest
 * @author Jason Watmore <jason@pointblankdevelopment.com.au> (http://jasonwatmore.com)
 * @version 1.2.0
 */
(function() {
    angular.module('angulike', []).directive('fbLike', ['$window', 'setting', function($window, setting) {
        return {
            restrict: 'A',
            scope: {
                fbLike: '=?'
            },
            link: function(scope, element, attrs) {
                if (!$window.FB) {
                    // Load Facebook SDK if not already loaded
                    $.getScript('//connect.facebook.net/pt_BR/sdk.js', function() {
                        $window.FB.init({
                            appId: setting.facebook.appId, //@todo make me an attribute
                            xfbml: true,
                            version: 'v2.0'
                        });
                        renderLikeButton();
                    });
                } else {
                    renderLikeButton();
                }
                scope.$watch('fbLike', function(nv, ov) {
                    if (nv != ov) {
                        renderLikeButton();
                    }
                });
                var watchAdded = false;

                function renderLikeButton() {
                    if (!!attrs.fbLike && !scope.fbLike && !watchAdded) {
                        // wait for data if it hasn't loaded yet
                        var watchAdded = true;
                        var unbindWatch = scope.$watch('fbLike', function(newValue, oldValue) {
                            if (newValue) {
                                renderLikeButton();
                                // only need to run once
                                unbindWatch();
                            }
                        });
                        return;
                    } else {
                        element.html('

');
                        $window.FB.XFBML.parse(element.parent()[0]);
                    }
                }
            }
        };
    }]).directive('googlePlus', ['$window', '$rootScope', function($window, $rootScope) {
        return {
            restrict: 'A',
            scope: {
                googlePlus: '=?'
            },
            link: function(scope, element, attrs) {
                if (!$window.gapi) {
                    // Load Google SDK if not already loaded
                    $.getScript('//apis.google.com/js/platform.js', function() {
                        renderPlusButton();
                    });
                } else {
                    renderPlusButton();
                }
                scope.$watch('googlePlus', function(nv, ov) {
                    if (nv != ov) {
                        renderPlusButton();
                    }
                });
                var watchAdded = false;

                function renderPlusButton() {
                    if (!!attrs.googlePlus && !scope.googlePlus && !watchAdded) {
                        // wait for data if it hasn't loaded yet
                        var watchAdded = true;
                        var unbindWatch = scope.$watch('googlePlus', function(newValue, oldValue) {
                            if (newValue) {
                                renderPlusButton();
                                // only need to run once
                                unbindWatch();
                            }
                        });
                        return;
                    } else {
                        element.html('

');
                        $window.gapi.plusone.go(element.parent()[0]);
                    }
                }
            }
        };
    }]).directive('tweet', ['$window', '$location', '$rootScope',
        function($window, $location, $rootScope) {
            return {
                restrict: 'A',
                scope: {
                    tweet: '=',
                    tweetUrl: '='
                },
                link: function(scope, element, attrs) {
                    if (!$window.twttr) {
                        // Load Twitter SDK if not already loaded
                        $.getScript('//platform.twitter.com/widgets.js', function() {
                            renderTweetButton();
                        });
                    } else {
                        renderTweetButton();
                    }
                    scope.$watch('tweetUrl+tweet', function(nv, ov) {
                        if (nv != ov) {
                            renderTweetButton();
                        }
                    });
                    var watchAdded = false;

                    function renderTweetButton() {
                        if (!scope.tweet && !watchAdded) {
                            // wait for data if it hasn't loaded yet
                            watchAdded = true;
                            var unbindWatch = scope.$watch('tweet', function(newValue, oldValue) {
                                if (newValue) {
                                    renderTweetButton();
                                    // only need to run once
                                    unbindWatch();
                                }
                            });
                            return;
                        } else {
                            element.html('Tweet');
                            $window.twttr.widgets.load(element.parent()[0]);
                        }
                    }
                }
            };
        }
    ]).directive('pinIt', ['$window', '$location',
        function($window, $location) {
            return {
                restrict: 'A',
                scope: {
                    pinIt: '=',
                    pinItImage: '=',
                    pinItUrl: '='
                },
                link: function(scope, element, attrs) {
                    if (!$window.parsePins) {
                        // Load Pinterest SDK if not already loaded
                        (function(d) {
                            var f = d.getElementsByTagName('SCRIPT')[0],
                                p = d.createElement('SCRIPT');
                            p.type = 'text/javascript';
                            p.async = true;
                            p.src = '//assets.pinterest.com/js/pinit.js';
                            p['data-pin-build'] = 'parsePins';
                            p.onload = function() {
                                if (!!$window.parsePins) {
                                    renderPinItButton();
                                } else {
                                    setTimeout(p.onload, 100);
                                }
                            };
                            f.parentNode.insertBefore(p, f);
                        }($window.document));
                    } else {
                        renderPinItButton();
                    }

                    scope.$watch('pinItUrl', function(nv, ov) {
                    if (nv != ov) {
                        renderPinItButton();
                    }
                });
                    var watchAdded = false;

                    function renderPinItButton() {
                        if (!scope.pinIt && !watchAdded) {
                            // wait for data if it hasn't loaded yet
                            watchAdded = true;
                            var unbindWatch = scope.$watch('pinIt', function(newValue, oldValue) {
                                if (newValue) {
                                    renderPinItButton();
                                    // only need to run once
                                    unbindWatch();
                                }
                            });
                            return;
                        } else {
                            element.html('');
                            $window.parsePins(element.parent()[0]);
                        }
                    }
                }
            };
        }
    ]);
})();
<|endoftext|>


<commit_before>angular.module('fitness.game', [])

// directive for auto-focusing popup input when shown
.directive('focusMe', function($timeout) {
  return {
    link: function(scope, element, attrs) {
      $timeout(function() {
        element[0].focus();
      }, 150);
    }
  };
})
.directive('advanceInputArea', function($timeout) {
	return {
		restrict: 'A',
		link: function(scope, element, attrs) {
			$timeout(function() {
				scope.inputs = document.getElementById('popup-input-container').getElementsByTagName('input');
				scope.index = 0;
				scope.done = false;
				scope.indexStack = [];
				findInitialInput();

				element.bind('keydown', function(e) {
					 if(e.key == "Backspace" || e.key == "Delete") {
						e.preventDefault();
						findPrevInput();
					} else if(e.key.match(/^[a-z]$/i)) {
						if(!scope.done) {
							e.preventDefault();
							scope.inputs[scope.index].value = e.key;
							findNextInput(scope.index);
						}
					} else {
						console.error("Incorrect key: " + e.key)
						e.preventDefault();
					}
				});
			}, 150);

			function findInitialInput() {
				for(var i = 0; i < scope.inputs.length; i++) {
					if(scope.inputs[i].value == ".") {
						scope.inputs[i].select();
						scope.inputs[i].focus();
						scope.index = i;
						return;
					}
				}
				scope.inputs[scope.index].blur();
				scope.done = true;
			}

			function findPrevInput() {
				if(scope.indexStack.length > 0) {
					var ind = scope.indexStack.shift();
					scope.inputs[ind].value = ".";
					scope.inputs[ind].select();
					scope.inputs[ind].focus();
					scope.index = ind;
				} else {
					console.error("beginning reached!")
				}
			}

			function findNextInput(startIndex) {
				scope.indexStack.unshift(startIndex);
				for(var i = startIndex; i < scope.inputs.length; i++) {
					if(scope.inputs[i].value == ".") {
						scope.inputs[i].select();
						scope.inputs[i].focus();
						scope.index = i;
						return;
					}
				}
				scope.inputs[scope.index].blur();
				scope.done = true;
			}
		}
	}
})
.controller('GameCtrl', function($ionicPopup, $ionicModal, $timeout, $interval, gameService, $scope, $state) {

	console.log('Game Controller loaded');

	var self = this;
	var vowels = ['A', 'E', 'I', 'O', 'U'];
	var numVowels;
	var numCons;
	var vowelsRevealed;
	var consRevealed;
	var vowelStack, consStack, thePhrase, noSpace;
	var thePhrase;

	this.init = function(){
		console.log('init game function');
		var obj = {} ;

		self.loadGame();
	};

	this.showPopup = function() {
		$scope.copy = _.cloneDeep(self.phrase)
		console.info(thePhrase)
		var guessPopup = $ionicPopup.show({
			templateUrl: 'pages/game/guess-popup.html',
			title: 'Enter Phrase',
			scope: $scope,
			buttons: [
				{
					text: 'Cancel',
					type: 'button-dark'
				},
				{
					text: 'Solve The Puzzle',
					type: 'button-positive',
					onTap: function(e) {
						var expected = thePhrase.toUpperCase().trim();
						var actual = self.stringifyViewModel($scope.copy).toUpperCase().trim();
						if(actual && actual === expected) {
							guessPopup.close();
							self.goodGuess();
						} else {
							self.badGuess();
						}
					}
				}
			]
		});
	};

	this.stringifyViewModel = function(viewModel) {
		var str = "";
		for(var a = 0; a < viewModel.length; a++) {
			for(var b = 0; b < viewModel[a].length; b++) {
				str += viewModel[a][b].letter;
			}
			str += " ";
		}

		return str;
	};

	this.goodGuess = function() {
		console.log("good guess!")
		$ionicPopup.alert({
	     	title: 'You are correct!',
	    	 template: 'Great Job! Play another.'
	   });
		self.revealAll();
		self.closeGame();
		gameService.addScore();

	};

	this.badGuess = function() {
		self.guess = "";
		$ionicPopup.alert({
	     title: 'Wrong Guess!',
	     template: 'Penalty points were added to your goals. Try again!'
	   });

	   gameService.addPenalty();
	};

	this.timeExpired = function(){
		self.guess = "";
			$ionicPopup.alert({
	  		   title: 'Time Expired!',
	  		   template: 'Uh no! You ran out of time. Better luck next time!'
	   });

	   $state.go('app.home');

	}

	this.initModal = function(template) {
		$ionicModal.fromTemplateUrl(template, {
			scope: $scope,
			animation: 'slide-in-up'
		}).then(function(modal) {
			self.modal = modal;
			self.modal.show();
		});
	};

	this.reveal = function(letterType) {
		var curr;
		if(letterType === "V" && vowelStack.length > 1) {
			curr = vowelStack.shift();
			if (curr) {
				curr.model = curr.letter;
				curr.revealed = true;
				vowelsRevealed++;
			}
		} else if(letterType === "C" && consStack.length > 1) {
			curr = consStack.shift();
			if (curr) {
				curr.model = curr.letter;
				curr.revealed = true;
				consRevealed++;
			}
		} else {
			console.error("something went wrong")
			// either we have a bad lettertype or both stacks are empty
		}
	};

	// reveals the entire phrase
	this.revealAll = function() {
		vowelStack.forEach(function(d) {
			d.model = d.letter;
		});

		consStack.forEach(function(d) {
			d.model = d.letter;
		});
	}

	// takes the number of vowels and consonants that should be revealed and reveals them
	this.catchUp = function(vowels, consonants) {
		console.log('catch up to ' + vowels, consonants);
		if(vowels < 0 || consonants < 0) {
			return;
		}

		for(var a = 0; a < vowels; a++) {
			self.reveal("V");
		}

		for(var b = 0; b < consonants; b++) {
			self.reveal("C");
		}

		self.saveGame();
	};

	this.saveGame = function() {
		console.info("game saved!")

		if (!gameService.activeGame)
			return null ;

		var state = {
			numVowels: numVowels,
			numCons: numCons,
			vowelsRevealed: vowelsRevealed,
			consRevealed: consRevealed,
			vowelStack: vowelStack,
			consStack: consStack,
			viewModel: self.phrase,
			thePhrase: thePhrase,
			noSpace: noSpace
		};

		return localforage.setItem("gameState", JSON.stringify(state));
	};

	this.loadGame = function() {
		console.info("game loaded!")
		localforage.getItem("gameState").then(function(savedState) {

			if (savedState){

				savedState = JSON.parse(savedState);

				numVowels = savedState.numVowels;
				numCons = savedState.numCons;
				vowelsRevealed = savedState.vowelsRevealed;
				consRevealed = savedState.consRevealed;
				vowelStack = savedState.vowelStack;
				consStack = savedState.consStack;
				self.phrase = savedState.viewModel;
				thePhrase = savedState.thePhrase;
				noSpace = savedState.noSpace;
			}
			else{
				obj = gameService.startGame();
				self.guess = "" ;

				gameService.activeGame = obj ;
				gameService.activeGameFlag = true ;

				numVowels = obj.numVowels;
				numCons = obj.numCons;
				vowelsRevealed = 0;
				consRevealed = 0;
				vowelStack = obj.vowelStack;
				consStack = obj.consStack;
				self.phrase = obj.viewModel;
				thePhrase = obj.phrase;
				noSpace = obj.noSpace;

				self.saveGame();

			}
			gameService.activeGame = true;
		});
	};

	this.testReveal = function() {
		if(vowelStack.length > 0) {
			self.reveal("V");
		} else {
			self.reveal("C");
		}
	}

	this.drawFriendly = function() {

		console.log('goal steps ' + self.fitbitData.goals.steps);

		jQuery("#friend-progress").empty();

			self.friendlyProgress = jQuery("#friend-progress").radialMultiProgress("init", {
				'fill': 25,
				'font-size': 14,
				'size': 100,
				'data': [
					{'color': "#2DB1E4", 'range': [0, self.fitbitData.goals.steps]}, // steps
					{'color': "#9CCA13", 'range': [0, self.fitbitData.goals.floors]}, // floors
					{'color': "#cf2583", 'range': [0, 24]} // time
				]
			});

		var dh, dm, ds;
	//	setInterval(function() {
			console.log('in the draw circle func.');

			var date = new Date(),
	        h = date.getHours(),
	        m = date.getMinutes(),
	        s = date.getSeconds();

			self.fitbitData.time = gameService.updateTime(h);

			console.log('hours is ' + h);

	    	self.friendlyProgress.radialMultiProgress("to", {
	      		"index": 0, 'perc': self.fitbitData.steps, 'time': 10
	      	});
	    	self.friendlyProgress.radialMultiProgress("to", {
	    		"index": 1, 'perc': self.fitbitData.floors, 'time': 10
	    	});
	    	self.friendlyProgress.radialMultiProgress("to", {
	    		"index": 2, 'perc': h, 'time': 10
	    	});
	  //  }
//	  }, 1000);
	};

	$scope.$on('$ionicView.leave', function(e) {
		self.saveGame();
	});

	$scope.$on('$ionicView.enter', function(e) {

		self.fitbitData = {} ;
		self.fitbitData.goals = {} ;

		self.fitbitData = gameService.data ;

		console.log('steps in game.js: ' + self.fitbitData.steps);

		console.log('getting access token from storage');
		localforage.getItem('fitbitToken').then(function(token){
			if (!token)
				gameService.reload();

			gameService.fitbitToken = token;
			console.log('saving token to game service: ' + token);
			gameService.getFitbitData();
			$timeout( self.computeGameLogic, 4000);
		});

		self.init();

		$interval.cancel(self.queryInterval);

		self.queryInterval = $interval( function(){ self.refreshData(); } , 260000);

		$timeout( self.drawFriendly, 1000);
	});

	this.refreshData = function(){

		gameService.getFitbitData();
		$timeout( self.computeGameLogic, 2000);
		$timeout( self.drawFriendly, 750);
		$scope.$broadcast('scroll.refreshComplete');
	}

	this.computeGameLogic = function(){
		var vowelWorth = parseInt( self.fitbitData.goals.floors /  numVowels);
		var consWorth = parseInt(self.fitbitData.goals.steps /  numCons) ;

		if (consWorth < 200) // min steps required
			consWorth = 200 ;

		if (vowelWorth < 1) // min floors required
			vowelWorth = 1 ;

		var vowelCount = parseInt(self.fitbitData.floors / vowelWorth ) - vowelsRevealed;
		var consCount = parseInt(self.fitbitData.steps / consWorth ) - consRevealed;

		if (vowelCount < 0)
			vowelCount = 0;
		if (consCount < 0)
			consCount = 0 ;

		self.catchUp( vowelCount, consCount );
	}

	this.openGiveUpAlert = function() {
		$ionicPopup.confirm({
	     title: 'Aww You\'re Ready To Give Up Already?',
	     template: 'Are you sure you want to give up on this puzzle? All progress will be lost.',
		 okText: 'Give Up'
	   }).then(function(res) {
	   	if(res) {
	   		self.closeGame();
	   	} else {
	   		// do nothing
	   	}
	   });
	};

	this.closeGame = function(){
		// needs a prompt

		localforage.removeItem("gameState");

		gameService.activeGame = false;
		gameService.clearGame();
		$state.transitionTo('app.home');
	}
});
<commit_msg>Fixed (hopefully) problem where guess was always correct<commit_after>angular.module('fitness.game', [])

// directive for auto-focusing popup input when shown
.directive('focusMe', function($timeout) {
  return {
    link: function(scope, element, attrs) {
      $timeout(function() {
        element[0].focus();
      }, 150);
    }
  };
})
.directive('advanceInputArea', function($timeout, $rootScope) {
	return {
		restrict: 'A',
		link: function(scope, element, attrs) {
			$timeout(function() {
				scope.inputs = document.getElementById('popup-input-container').getElementsByTagName('input');
				scope.index = 0;
				scope.done = false;
				scope.indexStack = [];
				$rootScope.letters = [];
				findInitialInput();

				element.bind('keydown', function(e) {
					 if(e.key == "Backspace" || e.key == "Delete") {
						e.preventDefault();
						findPrevInput();
					} else if(e.key.match(/^[a-z]$/i)) {
						if(!scope.done) {
							e.preventDefault();
							scope.inputs[scope.index].value = e.key;
							$rootScope.letters[scope.index] = e.key;
							findNextInput(scope.index);
						}
					} else {
						console.error("Incorrect key: " + e.key)
						e.preventDefault();
					}
				});
			}, 150);

			function findInitialInput() {
				for(var i = 0; i < scope.inputs.length; i++) {
					if(scope.inputs[i].value == ".") {
						scope.inputs[i].select();
						scope.inputs[i].focus();
						scope.index = i;
						return;
					}
				}
				scope.inputs[scope.index].blur();
				scope.done = true;
			}

			function findPrevInput() {
				if(scope.indexStack.length > 0) {
					var ind = scope.indexStack.shift();
					scope.inputs[ind].value = ".";
					scope.inputs[ind].select();
					scope.inputs[ind].focus();
					scope.index = ind;
				} else {
					console.error("beginning reached!")
				}
			}

			function findNextInput(startIndex) {
				scope.indexStack.unshift(startIndex);
				for(var i = startIndex; i < scope.inputs.length; i++) {
					if(scope.inputs[i].value == ".") {
						scope.inputs[i].select();
						scope.inputs[i].focus();
						scope.index = i;
						return;
					}
				}
				scope.inputs[scope.index].blur();
				scope.done = true;
			}
		}
	}
})
.controller('GameCtrl', function($ionicPopup, $ionicModal, $timeout, $interval, $rootScope, gameService, $scope, $state) {

	console.log('Game Controller loaded');

	var self = this;
	var vowels = ['A', 'E', 'I', 'O', 'U'];
	var numVowels;
	var numCons;
	var vowelsRevealed;
	var consRevealed;
	var vowelStack, consStack, thePhrase, noSpace;
	var thePhrase;

	this.init = function(){
		console.log('init game function');
		var obj = {} ;

		self.loadGame();
	};

	this.showPopup = function() {
		$scope.copy = _.cloneDeep(self.phrase)
		console.info(thePhrase)
		var guessPopup = $ionicPopup.show({
			templateUrl: 'pages/game/guess-popup.html',
			title: 'Enter Phrase',
			scope: $scope,
			buttons: [
				{
					text: 'Cancel',
					type: 'button-dark'
				},
				{
					text: 'Solve The Puzzle',
					type: 'button-positive',
					onTap: function(e) {
						var expected = thePhrase.toUpperCase().trim();
						var actual = self.stringifyViewModel($scope.copy).toUpperCase().trim();
						console.warn(expected)
						console.warn(actual)
						console.error(actual === expected)
						if(actual && actual === expected) {
							guessPopup.close();
							self.goodGuess();
						} else {
							self.badGuess();
						}
					}
				}
			]
		});
	};

	this.stringifyViewModel = function(viewModel) {
		var str = "";
		for(var a = 0; a < viewModel.length; a++) {
			for(var b = 0; b < viewModel[a].length; b++) {
				if(viewModel[a][b].model === ".") {
					str += $rootScope.letters.shift();
				} else {
					str += viewModel[a][b].model;
					$rootScope.letters.shift();
				}
			}
			str += " ";
		}
		return str;
	};

	this.goodGuess = function() {
		console.log("good guess!")
		$ionicPopup.alert({
	     	title: 'You are correct!',
	    	 template: 'Great Job! Play another.'
	   });
		self.revealAll();
		self.closeGame();
		gameService.addScore();

	};

	this.badGuess = function() {
		self.guess = "";
		$ionicPopup.alert({
	     title: 'Wrong Guess!',
	     template: 'Penalty points were added to your goals. Try again!'
	   });

	   gameService.addPenalty();
	};

	this.timeExpired = function(){
		self.guess = "";
			$ionicPopup.alert({
	  		   title: 'Time Expired!',
	  		   template: 'Uh no! You ran out of time. Better luck next time!'
	   });

	   $state.go('app.home');

	}

	this.initModal = function(template) {
		$ionicModal.fromTemplateUrl(template, {
			scope: $scope,
			animation: 'slide-in-up'
		}).then(function(modal) {
			self.modal = modal;
			self.modal.show();
		});
	};

	this.reveal = function(letterType) {
		var curr;
		if(letterType === "V" && vowelStack.length > 1) {
			curr = vowelStack.shift();
			if (curr) {
				curr.model = curr.letter;
				curr.revealed = true;
				vowelsRevealed++;
			}
		} else if(letterType === "C" && consStack.length > 1) {
			curr = consStack.shift();
			if (curr) {
				curr.model = curr.letter;
				curr.revealed = true;
				consRevealed++;
			}
		} else {
			console.error("something went wrong")
			// either we have a bad lettertype or both stacks are empty
		}
	};

	// reveals the entire phrase
	this.revealAll = function() {
		vowelStack.forEach(function(d) {
			d.model = d.letter;
		});

		consStack.forEach(function(d) {
			d.model = d.letter;
		});
	}

	// takes the number of vowels and consonants that should be revealed and reveals them
	this.catchUp = function(vowels, consonants) {
		console.log('catch up to ' + vowels, consonants);
		if(vowels < 0 || consonants < 0) {
			return;
		}

		for(var a = 0; a < vowels; a++) {
			self.reveal("V");
		}

		for(var b = 0; b < consonants; b++) {
			self.reveal("C");
		}

		self.saveGame();
	};

	this.saveGame = function() {
		console.info("game saved!")

		if (!gameService.activeGame)
			return null ;

		var state = {
			numVowels: numVowels,
			numCons: numCons,
			vowelsRevealed: vowelsRevealed,
			consRevealed: consRevealed,
			vowelStack: vowelStack,
			consStack: consStack,
			viewModel: self.phrase,
			thePhrase: thePhrase,
			noSpace: noSpace
		};

		return localforage.setItem("gameState", JSON.stringify(state));
	};

	this.loadGame = function() {
		console.info("game loaded!")
		localforage.getItem("gameState").then(function(savedState) {

			if (savedState){

				savedState = JSON.parse(savedState);

				numVowels = savedState.numVowels;
				numCons = savedState.numCons;
				vowelsRevealed = savedState.vowelsRevealed;
				consRevealed = savedState.consRevealed;
				vowelStack = savedState.vowelStack;
				consStack = savedState.consStack;
				self.phrase = savedState.viewModel;
				thePhrase = savedState.thePhrase;
				noSpace = savedState.noSpace;
			}
			else{
				obj = gameService.startGame();
				self.guess = "" ;

				gameService.activeGame = obj ;
				gameService.activeGameFlag = true ;

				numVowels = obj.numVowels;
				numCons = obj.numCons;
				vowelsRevealed = 0;
				consRevealed = 0;
				vowelStack = obj.vowelStack;
				consStack = obj.consStack;
				self.phrase = obj.viewModel;
				thePhrase = obj.phrase;
				noSpace = obj.noSpace;

				self.saveGame();

			}
			gameService.activeGame = true;
		});
	};

	this.testReveal = function() {
		if(vowelStack.length > 0) {
			self.reveal("V");
		} else {
			self.reveal("C");
		}
	}

	this.drawFriendly = function() {

		console.log('goal steps ' + self.fitbitData.goals.steps);

		jQuery("#friend-progress").empty();

			self.friendlyProgress = jQuery("#friend-progress").radialMultiProgress("init", {
				'fill': 25,
				'font-size': 14,
				'size': 100,
				'data': [
					{'color': "#2DB1E4", 'range': [0, self.fitbitData.goals.steps]}, // steps
					{'color': "#9CCA13", 'range': [0, self.fitbitData.goals.floors]}, // floors
					{'color': "#cf2583", 'range': [0, 24]} // time
				]
			});

		var dh, dm, ds;
	//	setInterval(function() {
			console.log('in the draw circle func.');

			var date = new Date(),
	        h = date.getHours(),
	        m = date.getMinutes(),
	        s = date.getSeconds();

			self.fitbitData.time = gameService.updateTime(h);

			console.log('hours is ' + h);

	    	self.friendlyProgress.radialMultiProgress("to", {
	      		"index": 0, 'perc': self.fitbitData.steps, 'time': 10
	      	});
	    	self.friendlyProgress.radialMultiProgress("to", {
	    		"index": 1, 'perc': self.fitbitData.floors, 'time': 10
	    	});
	    	self.friendlyProgress.radialMultiProgress("to", {
	    		"index": 2, 'perc': h, 'time': 10
	    	});
	  //  }
//	  }, 1000);
	};

	$scope.$on('$ionicView.leave', function(e) {
		self.saveGame();
	});

	$scope.$on('$ionicView.enter', function(e) {

		self.fitbitData = {} ;
		self.fitbitData.goals = {} ;

		self.fitbitData = gameService.data ;

		console.log('steps in game.js: ' + self.fitbitData.steps);

		console.log('getting access token from storage');
		localforage.getItem('fitbitToken').then(function(token){
			if (!token)
				gameService.reload();

			gameService.fitbitToken = token;
			console.log('saving token to game service: ' + token);
			gameService.getFitbitData();
			$timeout( self.computeGameLogic, 4000);
		});

		self.init();

		$interval.cancel(self.queryInterval);

		self.queryInterval = $interval( function(){ self.refreshData(); } , 260000);

		$timeout( self.drawFriendly, 1000);
	});

	this.refreshData = function(){

		gameService.getFitbitData();
		$timeout( self.computeGameLogic, 2000);
		$timeout( self.drawFriendly, 750);
		$scope.$broadcast('scroll.refreshComplete');
	}

	this.computeGameLogic = function(){
		var vowelWorth = parseInt( self.fitbitData.goals.floors /  numVowels);
		var consWorth = parseInt(self.fitbitData.goals.steps /  numCons) ;

		if (consWorth < 200) // min steps required
			consWorth = 200 ;

		if (vowelWorth < 1) // min floors required
			vowelWorth = 1 ;

		var vowelCount = parseInt(self.fitbitData.floors / vowelWorth ) - vowelsRevealed;
		var consCount = parseInt(self.fitbitData.steps / consWorth ) - consRevealed;

		if (vowelCount < 0)
			vowelCount = 0;
		if (consCount < 0)
			consCount = 0 ;

		self.catchUp( vowelCount, consCount );
	}

	this.openGiveUpAlert = function() {
		$ionicPopup.confirm({
	     title: 'Aww You\'re Ready To Give Up Already?',
	     template: 'Are you sure you want to give up on this puzzle? All progress will be lost.',
		 okText: 'Give Up'
	   }).then(function(res) {
	   	if(res) {
	   		self.closeGame();
	   	} else {
	   		// do nothing
	   	}
	   });
	};

	this.closeGame = function(){
		// needs a prompt

		localforage.removeItem("gameState");

		gameService.activeGame = false;
		gameService.clearGame();
		$state.transitionTo('app.home');
	}
});
<|endoftext|>


<commit_before>'use strict';

// Committees controller
angular.module('committees').controller('CommitteesController', ['$rootScope', '$scope', '$stateParams', '$location', 'Authentication', 'Users', 'Committees', '$q', '$log',
	function($rootScope, $scope, $stateParams, $location, Authentication,Users, Committees, $q, $log) {
		$scope.authentication = Authentication;
		$scope.currentUser = Authentication.user;

		// Create new Committee
		$scope.create = function() {
			// Create new Committee object
			var committee = new Committees ({
				name: this.name,
				chair: this.chair
			});

			// Redirect after save
			committee.$save(function(response) {
				$location.path('committees/' + response._id);

				// Clear form fields
				$scope.name = '';
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Remove existing Committee
		$scope.remove = function( committee ) {
			if ( committee ) { committee.$remove();

				for (var i in $scope.committees ) {
					if ($scope.committees [i] === committee ) {
						$scope.committees.splice(i, 1);
					}
				}
			} else {
				$scope.committee.$remove(function() {
					$location.path('committees');
				});
			}
		};

		// Update existing Committee
		$scope.update = function() {
			var committee = $scope.committee ;

			committee.$update(function() {
				$location.path('committees/' + committee._id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		//Add member to committee
		$scope.addMember = function(user){
			var committee = $scope.committee;
			committee.members.push(user);
			committee.$update(function(){
				$location.path('committees/'+committee._id+'/edit');
			}, function(errorResponse){
				$scope.error = errorResponse.data.message;
			});
		};

		$scope.removeMember = function(index){
			var committee = $scope.committee;
			committee.members.splice(index, 1);
			committee.$update(function(){
				$location.path('committees/'+committee._id);
			}, function(errorResponse){
				$scope.error = errorResponse.data.message;
			});
		};

		// Find a list of Committees
		$scope.find = function() {
			// $scope.committees = Committees.query();

			Committees.query().$promise.then(function(data) {
				$scope.committees = data;

				// $log.debug('data: ');
				// $log.debug(data);

				// $log.debug('$scope.committees: ');
				// $log.debug($scope.committees);
			});

		};

		$scope.checkAdmin = function(){
			var user = new Users($scope.currentUser);
			if(user.role === 'Admin'){
				return true;
			}
			else{
				return false;
			};
		};

		$scope.checkLoggedIn = function(){
			var user = new Users($scope.currentUser);
			if(!$scope.currentUser){
				return false;
			}
			else{
				return true;
			};
		};

		$scope.checkOwner = function(committee){
		//	var user = new Users($scope.currentUser);
		//	var committee = $scope.committee;
			if($scope.currentUser.displayName===committee.user.displayName){
				return true;
			}
			else{
				return false;
			};
		};

		$scope.userInCommittee = function(committee){
			//console.log($scope.committee.members);
			//console.log($scope.committee._id);
			//console.log(user);

			if(typeof committee !== 'undefined'){
				for(var i = 0; i < committee.members.length; i++){
					if($scope.currentUser._id === committee.members[i]._id){
						return true;
					}
				}
				return false;
			}
			return false;

			/*for(var i = 0; i < committee.members.length; i++){
				var temp = committee.members[i]._id;
				console.log(temp);
				//console.log(Users.get({userId: $stateParams.userId});
				console.log(Users.get({
					 temp: $stateParams.userId
				}));
			}*/
		};

		// Find existing Committee
		$scope.findOne = function() {
			Committees.get({
				committeeId: $stateParams.committeeId
			}).$promise.then(function(data) {
				//TEMPORARY SOLUTION FOR SPRINT 1
				$rootScope.committee = data;

				// $log.debug('$scope.committee: ');
				// $log.debug($scope.committee);
				// $log.debug('$scope.committee._id');
				// $log.debug($scope.committee._id);
			});

			// $scope.test =

			// 	Committees.get({
			// 		committeeId: $stateParams.committeeId
			// 	}).$promise.then(function(data) {
			// 		$scope.committee = data;
			// 		return data;
			// 	});

			// test.then(function(data) {

			// 	// $log.debug( $state.href('edit', {data._id}) );

			// 	console.log("data:");
			// 	console.log(data);

			// 	console.log("$scope.committee:");
			// 	console.log($scope.committee);
			// 	console.log("$scope.committee.members:")
			// 	console.log($scope.committee.members);
			// 	console.log("$scope.committee.name:");
			// 	console.log($scope.committee.name);

			// });
		};

		// // Show edit button
		// $scope.showEdit = function($stateParams) {

		// 	$log.debug('$stateParams:');
		// 	$log.debug($stateParams.committeeId);
		// 	$log.debug('$scope.committee._id:');
		// 	$log.debug($scope.committee._id);

		// 	if($stateParams.committeeId === $scope.committee._id){
		// 		return true;
		// 	}

		// 	return false;

		// };
	}
]);<commit_msg>Fixed add member issue<commit_after>'use strict';

// Committees controller
angular.module('committees').controller('CommitteesController', ['$rootScope', '$scope', '$stateParams', '$location', 'Authentication', 'Users', 'Committees', '$q', '$log',
	function($rootScope, $scope, $stateParams, $location, Authentication,Users, Committees, $q, $log) {
		$scope.authentication = Authentication;
		$scope.currentUser = Authentication.user;

		// Create new Committee
		$scope.create = function() {
			// Create new Committee object
			var committee = new Committees ({
				name: this.name,
				chair: this.chair
			});

			// Redirect after save
			committee.$save(function(response) {
				$location.path('committees/' + response._id);

				// Clear form fields
				$scope.name = '';
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Remove existing Committee
		$scope.remove = function( committee ) {
			if ( committee ) { committee.$remove();

				for (var i in $scope.committees ) {
					if ($scope.committees [i] === committee ) {
						$scope.committees.splice(i, 1);
					}
				}
			} else {
				$scope.committee.$remove(function() {
					$location.path('committees');
				});
			}
		};

		// Update existing Committee
		$scope.update = function() {
			var committee = $scope.committee ;

			committee.$update(function() {
				$location.path('committees/' + committee._id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		//Add member to committee
		$scope.addMember = function(user){
			var committee = $scope.committee;
			var check = 1;
			for(var i = 0; i < committee.members.length; i++){
				if($scope.currentUser._id === committee.members[i]._id){
					check = 0;
				}
			}
			if(check===1){
			committee.members.push(user);}
			else{
				console.log("NOPE!");
			}
			committee.$update(function(){
				$location.path('committees/'+committee._id+'/edit');
			}, function(errorResponse){
				$scope.error = errorResponse.data.message;
			});
		};

		$scope.removeMember = function(index){
			var committee = $scope.committee;
			committee.members.splice(index, 1);
			committee.$update(function(){
				$location.path('committees/'+committee._id);
			}, function(errorResponse){
				$scope.error = errorResponse.data.message;
			});
		};

		// Find a list of Committees
		$scope.find = function() {
			// $scope.committees = Committees.query();

			Committees.query().$promise.then(function(data) {
				$scope.committees = data;

				// $log.debug('data: ');
				// $log.debug(data);

				// $log.debug('$scope.committees: ');
				// $log.debug($scope.committees);
			});

		};

		$scope.checkAdmin = function(){
			var user = new Users($scope.currentUser);
			if(user.role === 'Admin'){
				return true;
			}
			else{
				return false;
			};
		};

		$scope.checkLoggedIn = function(){
			var user = new Users($scope.currentUser);
			if(!$scope.currentUser){
				return false;
			}
			else{
				return true;
			};
		};

		$scope.checkOwner = function(committee){
		//	var user = new Users($scope.currentUser);
		//	var committee = $scope.committee;
			if($scope.currentUser.displayName===committee.user.displayName){
				return true;
			}
			else{
				return false;
			};
		};

		$scope.userInCommittee = function(committee){
			//console.log($scope.committee.members);
			//console.log($scope.committee._id);
			//console.log(user);

			if(typeof committee !== 'undefined'){
				for(var i = 0; i < committee.members.length; i++){
					if($scope.currentUser._id === committee.members[i]._id){
						return true;
					}
				}
				return false;
			}
			return false;

			/*for(var i = 0; i < committee.members.length; i++){
				var temp = committee.members[i]._id;
				console.log(temp);
				//console.log(Users.get({userId: $stateParams.userId});
				console.log(Users.get({
					 temp: $stateParams.userId
				}));
			}*/
		};

		// Find existing Committee
		$scope.findOne = function() {
			Committees.get({
				committeeId: $stateParams.committeeId
			}).$promise.then(function(data) {
				//TEMPORARY SOLUTION FOR SPRINT 1
				$rootScope.committee = data;

				// $log.debug('$scope.committee: ');
				// $log.debug($scope.committee);
				// $log.debug('$scope.committee._id');
				// $log.debug($scope.committee._id);
			});

			// $scope.test =

			// 	Committees.get({
			// 		committeeId: $stateParams.committeeId
			// 	}).$promise.then(function(data) {
			// 		$scope.committee = data;
			// 		return data;
			// 	});

			// test.then(function(data) {

			// 	// $log.debug( $state.href('edit', {data._id}) );

			// 	console.log("data:");
			// 	console.log(data);

			// 	console.log("$scope.committee:");
			// 	console.log($scope.committee);
			// 	console.log("$scope.committee.members:")
			// 	console.log($scope.committee.members);
			// 	console.log("$scope.committee.name:");
			// 	console.log($scope.committee.name);

			// });
		};

		// // Show edit button
		// $scope.showEdit = function($stateParams) {

		// 	$log.debug('$stateParams:');
		// 	$log.debug($stateParams.committeeId);
		// 	$log.debug('$scope.committee._id:');
		// 	$log.debug($scope.committee._id);

		// 	if($stateParams.committeeId === $scope.committee._id){
		// 		return true;
		// 	}

		// 	return false;

		// };
	}
]);<|endoftext|>


<commit_before>const fse = require('fs-extra');
const got = require('got');
const unzipper = require('unzipper');
const chalk = require('chalk');

const debug = require('./utils/debug.js');
const db = require('./db.js');

// Download data into temporary folder.
function download() {
	return new Promise(async (resolve) => {

		debug.info('Starting data update');
		debug.time('data-update');
		debug.time('data-download', 'Downloading data');

		// Download and extract GTFS data into temporary folder.
		await got.stream('http://peatus.ee/gtfs/gtfs.zip').pipe(unzipper.Extract({ path: 'tmp' })).promise();

		// Correct GTFS filetypes.
		for (const file of await fse.readdir('tmp')) await fse.rename(`tmp/${file}`, `tmp/${file.substr(0, file.lastIndexOf('.'))}.csv`);

		// Download and write Elron stop data into temporary folder.
		let data = 'name,lat,lng\n';
		for (const stop of JSON.parse((await got('https://elron.ee/api/v1/stops')).body).data) data += `${stop.peatus},${stop.latitude},${stop.longitude}\n`;
		await fse.writeFile('tmp/elron.csv', data);

		debug.timeEnd('data-download', 'Downloaded data');
		resolve();

	});
};

// Run all SQL files in a folder.
function prepare(path, msgIncomplete, msgComplete) {
	return new Promise(async (resolve) => {

		for (const file of await fse.readdir(path)) {

			const name = file.slice(0, -4);

			debug.time(`data-prepare-${name}`, `${msgIncomplete} ${chalk.blue(name)}`);
			await db.query((await fse.readFile(`${path}/${file}`)).toString());
			debug.timeEnd(`data-prepare-${name}`, `${msgComplete} ${chalk.blue(name)}`);

		}

		resolve();

	});
}

// Start data update.
function update() {
	return new Promise(async (resolve) => {

		await download();
		await prepare('sql/importers', 'Importing', 'Imported');
		await prepare('sql/generators', 'Generating', 'Generated');

		debug.timeEnd('data-update', 'Data update completed');
		resolve();

	});
};

module.exports = {
	update
};
<commit_msg>Add support for JS importers/generators (api)<commit_after>const fse = require('fs-extra');
const got = require('got');
const unzipper = require('unzipper');
const chalk = require('chalk');

const debug = require('./utils/debug.js');
const db = require('./db.js');

// Download data into temporary folder.
function download() {
	return new Promise(async (resolve) => {

		debug.info('Starting data update');
		debug.time('data-update');
		debug.time('data-download', 'Downloading data');

		// Download and extract GTFS data into temporary folder.
		await got.stream('http://peatus.ee/gtfs/gtfs.zip').pipe(unzipper.Extract({ path: 'tmp' })).promise();

		// Correct GTFS filetypes.
		for (const file of await fse.readdir('tmp')) await fse.rename(`tmp/${file}`, `tmp/${file.substr(0, file.lastIndexOf('.'))}.csv`);

		// Download and write Elron stop data into temporary folder.
		let data = 'name,lat,lng\n';
		for (const stop of JSON.parse((await got('https://elron.ee/api/v1/stops')).body).data) data += `${stop.peatus},${stop.latitude},${stop.longitude}\n`;
		await fse.writeFile('tmp/elron.csv', data);

		debug.timeEnd('data-download', 'Downloaded data');
		resolve();

	});
};

// Run all SQL files in a folder.
function prepare(path, msgIncomplete, msgComplete) {
	return new Promise(async (resolve) => {

		for (const file of await fse.readdir(path)) {

			const name = file.split('.')[0];

			debug.time(`data-prepare-${name}`, `${msgIncomplete} ${chalk.blue(name)}`);

			switch (file.split('.')[1]) {

				case 'sql': {
					await db.query((await fse.readFile(`${path}/${file}`)).toString());
					break;
				}

				case 'js': {
					await (require(`./${path}/${file}`))();
					break;
				}

			}

			debug.timeEnd(`data-prepare-${name}`, `${msgComplete} ${chalk.blue(name)}`);

		}

		resolve();

	});
}

// Start data update.
function update() {
	return new Promise(async (resolve) => {

		await download();
		await prepare('sql/importers', 'Importing', 'Imported');
		await prepare('sql/generators', 'Generating', 'Generated');

		debug.timeEnd('data-update', 'Data update completed');
		resolve();

	});
};

module.exports = {
	update
};
<|endoftext|>


<commit_before>const assert = require('assert');
const chai = require('chai');
const chaiHttp = require('chai-http');
const config = require('config');
const reqPromise = require('request-promise');
const sinon = require('sinon');

const app = require('../../src/messenger/app');

chai.use(chaiHttp);

describe('app', () => {
  const messenger = new app.Messenger(config);
  let session;

  beforeEach(() => {
    sinon.stub(messenger, 'send');
    session = {
      profile: {
        first_name: '  Guy  ',
        last_name: '  Hoozdis  '
      }
    };
  });

  afterEach(() => {
    // TODO investigate making the suite mock `reqPromise.post` instead of `send`
    messenger.send.restore && messenger.send.restore();
  });

  describe('doLogin', function () {
    this.timeout(100);
    it('emits login event', () => {
      messenger.once('login', (payload) => {
        assert.ok(payload.event);
        assert.equal(payload.senderId, 'narf');
      });

      messenger.doLogin('narf');

      assert.equal(messenger.send.callCount, 1);
    });
  });

  describe('onAuth', function () {
    this.timeout(100);
    const baseEvent = {
      sender: {id: 'senderId'},
      recipient: {id: 'recipientId'},
      timestamp: 0,
      optin: {ref: ''}
    };

    it('emits auth event', () => {
      messenger.once('auth', (payload) => {
        assert.ok(payload.event);
        assert.ok(payload.session);
        assert.equal(payload.senderId, 'senderId');
        assert.equal(payload.optinRef, 'narf');
      });
      const event = Object.assign({}, baseEvent, {
        optin: {
          ref: 'narf'
        }
      });

      messenger.onAuth(event, {});

      assert.equal(messenger.send.callCount, 0);
    });
  });

  describe('onLink', function () {
    this.timeout(100);
    const baseEvent = {
      sender: {id: 'senderId'},
      recipient: {id: 'recipientId'},
      timestamp: 0,
      facebook: {id: ''}
    };

    it('emits link event', () => {
      messenger.once('link', (payload) => {
        assert.ok(payload.event);
        assert.equal(payload.senderId, 'senderId');
        assert.equal(payload.fbData.id, 'narf');
      });
      const event = Object.assign({}, baseEvent, {
        facebook: {
          id: 'narf'
        }
      });

      messenger.onLink(event);
    });
  });

  describe('onMessage message router', function () {
    this.timeout(100);
    const baseEvent = {
      sender: {id: 'senderId'},
      recipient: {id: 'recipientId'},
      timestamp: 0,
      message: {}
    };

    it('emits "message" event', () => {
      messenger.once('message', (payload) => {
        assert.ok(payload.event);
        assert.equal(payload.senderId, 'senderId');
        assert.deepEqual(payload.message, {foo: 'bar'});
      });
      const event = Object.assign({}, baseEvent, {
        message: {foo: 'bar'}
      });

      messenger.onMessage(event);
    });

    it('emits "text" event', () => {
      const event = Object.assign({}, baseEvent, {
        message: {
          text: 'message text'
        }
      });
      const fakeSession = {};
      messenger.once('text', (payload) => {
        assert.ok(payload.event);
        assert.equal(payload.senderId, 'senderId');
        assert.equal(payload.source, 'text');
        assert.equal(payload.text, 'message text');
      });

      messenger.onMessage(event, fakeSession);
    });

    it('emits "quick reply" event', () => {
      const messageText = 'Text message test';
      const quickReplyPayload = 'quick-reply-payload';
      messenger.once('text', (quickReply) => {
        assert.ok(quickReply.event);
        assert.equal(quickReply.senderId, 'senderId');
        assert.equal(quickReply.source, 'quickReply');
        assert.equal(quickReply.text, quickReplyPayload);
      });
      const event = Object.assign({}, baseEvent, {
        message: {
          quick_reply: { payload: quickReplyPayload },
          text: messageText
        }
      });

      messenger.onMessage(event, {});
    });

    it('emits "image" event', () => {
      messenger.once('message.image', (payload) => {
        assert.ok(payload.event);
        assert.equal(payload.senderId, 'senderId');
        assert.equal(payload.url, 'http://i.imgur.com/w1F7dae.jpg');
      });
      const event = Object.assign({}, baseEvent, {
        message: {
          attachments: [
            {
              type: 'image',
              payload: {
                url: 'http://i.imgur.com/w1F7dae.jpg'
              }
            }
          ]
        }
      });

      messenger.onMessage(event);
    });

    it('emits "sticker" event', () => {
      messenger.once('message.sticker', () => {});
      const event = Object.assign({}, baseEvent, {
        message: {
          sticker_id: 201013950048539,
          attachments: [
            {
              type: 'image',
              payload: {
                url: 'https://scontent.xx.fbcdn.net/t39.1997-6/p100x100/851576_201013953381872_1273966384_n.png?_nc_ad=z-m',
                sticker_id: 201013950048539
              }
            }
          ]
        }
      });

      messenger.onMessage(event);
    });

    it('emits "thumbsup" event', () => {
      messenger.once('message.thumbsup', (payload) => {
        assert.equal(payload.senderId, 'senderId');
      });
      const event = Object.assign({}, baseEvent, {
        message: {
          sticker_id: 369239263222822,
          attachments: [
            {
              type: 'image',
              payload: {
                url: 'https://scontent.xx.fbcdn.net/t39.1997-6/851557_369239266556155_759568595_n.png?_nc_ad=z-m',
                sticker_id: 369239263222822
              }
            }
          ]
        }
      });

      messenger.onMessage(event);
    });

    it('emits "greeting" event', () => {
      const text = "hello, is it me you're looking for?";
      const event = Object.assign({}, baseEvent, { message: { text: text } });
      messenger.once('text.greeting', (payload) => {
        assert.ok(payload.event);
        assert.equal(payload.senderId, 'senderId');

        assert.ok(payload.firstName);
        assert.ok(payload.surName);
        assert.ok(payload.fullName);
      });

      messenger.once('message.text', (payload) => {
        assert.fail('message.text', 'text.greeting', 'incorrect event emitted');
      });

      messenger.onMessage(event, session);
    });

    it('emits "text" event for greeting when emitGreetings is disabled', () => {
      const myMessenger = new app.Messenger(config, {emitGreetings: false});
      sinon.stub(myMessenger, 'send');

      const text = "hello, is it me you're looking for?";
      const event = Object.assign({}, baseEvent, {
        message: { text: text }
      });
      myMessenger.once('text.greeting', (payload) => {
        assert.fail('text', 'text.greeting', 'incorrect event emitted');
      });

      myMessenger.once('text', (payload) => {
        assert.ok(payload.event);
        assert.equal(payload.senderId, 'senderId');
      });

      myMessenger.onMessage(event, {});
    });

  });

  describe('onPostback', function () {
    this.timeout(100);
    const baseEvent = {
      sender: {id: 'senderId'},
      recipient: {id: 'recipientId'},
      timestamp: 0,
      postback: {payload: ''}
    };

    it('emits postback event', () => {
      messenger.once('text', (payload) => {
        assert.ok(payload.event);
        assert.equal(payload.senderId, 'senderId');
        assert.equal(payload.source, 'postback');
        assert.equal(payload.text, 'narf');
      });
      const event = Object.assign({}, baseEvent, {
        postback: {
          payload: 'narf'
        }
      });

      messenger.onPostback(event);
    });
  });

  describe('send', function () {
    let postStub;

    beforeEach(() => {
      postStub = sinon.stub(reqPromise, 'post').returns(Promise.resolve({}));
    });

    afterEach(() => {
      postStub.restore();
    });

    it('passed sender id and message', () => {
      messenger.send.restore();

      return messenger.send('senderId', {foo: 'bar'})
        .then(() => {
          assert.equal(reqPromise.post.args[0][0].json.recipient.id, 'senderId');
          assert.deepEqual(reqPromise.post.args[0][0].json.message, {foo: 'bar'});
        });
    });
  });

  describe('staticContent', function () {
    it('provides a homepage', (done) => {
      chai.request(messenger.app)
        .get('/')
        .end(function (err, res) {
          assert.equal(res.statusCode, 200);
          done();
        });
    });

    xit('provides a Send to Messenger button', (done) => {
      chai.request(messenger.app)
        .get('/send-to-messenger')
        .end(function (err, res) {
          assert.equal(res.statusCode, 200);
          assert.ok(res.text.includes('fb-send-to-messenger'));
          done();
        });
    });

    xit('provides a Message Us button', (done) => {
      chai.request(messenger.app)
        .get('/send-to-messenger')
        .end(function (err, res) {
          assert.equal(res.statusCode, 200);
          assert.ok(res.text.includes('fb-messengermessageus'));
          done();
        });
    });

    it('provides a departures healthcheck', (done) => {
      chai.request(messenger.app)
        .get('/ping')
        .end(function (err, res) {
          assert.equal(res.statusCode, 200);
          done();
        });
    });

  });

  describe('routeEachMessage session', () => {
    const baseMessage = {
      sender: {id: 'teehee'}
    };
    let messenger;

    beforeEach(() => {
      messenger = new app.Messenger(config);
      sinon.stub(messenger, 'getPublicProfile').returns({then: (resolve) => resolve({})});
    });

    afterEach(() => {
      messenger.getPublicProfile.restore();
    });

    it('counts every message received', () =>
      messenger.routeEachMessage(baseMessage)
        .then(() => messenger.routeEachMessage(baseMessage))
        .then((session) => {
          assert.equal(session.count, 2);
        })
    );

    it('sets lastSeen', () =>
      messenger.routeEachMessage(baseMessage)
        .then((session) => {
          assert.equal(typeof session.lastSeen, 'number');
        })
    );

    it('sets source for auth messages', () => {
      const authMessage = Object.assign({optin: 'foo'}, baseMessage);
      return messenger.routeEachMessage(authMessage)
        .then(() => app.__internals__.cache.get(baseMessage.sender.id))
        .then((session) => {
          assert.equal(session.source, 'web');
        });
    });

    describe('return user', () => {
      let originalValue;

      before(() => {
        originalValue = app.__internals__.SESSION_TIMEOUT_MS;
        app.__internals__.SESSION_TIMEOUT_MS = 0;
      });

      after(() => {
        app.__internals__.SESSION_TIMEOUT_MS = originalValue;
      });

      it('sets source for return user', () =>
        messenger.routeEachMessage(baseMessage)
          .then((session) => {
            session.source = 'foo';
            return messenger.routeEachMessage(baseMessage);
          })
          .then((session) => {
            assert.equal(session.source, 'return');
          })
      );
    });

    it('does not set source for user still in session', () =>
      messenger.routeEachMessage(baseMessage)
        .then((session) => {
          session.source = 'foo this should not change';
          return app.__internals__.cache.set(baseMessage.sender.id, session);
        })
        .then(() => {
          return messenger.routeEachMessage(baseMessage);
        })
        .then((session) => {
          assert.equal(session.source, 'foo this should not change');
        })
    );
  });
});
<commit_msg>Bots should respond to help requests / `text.help` in SDK (#35)<commit_after>const assert = require('assert');
const chai = require('chai');
const chaiHttp = require('chai-http');
const config = require('config');
const reqPromise = require('request-promise');
const sinon = require('sinon');

const app = require('../../src/messenger/app');

chai.use(chaiHttp);

describe('app', () => {
  const messenger = new app.Messenger(config);
  let session;

  beforeEach(() => {
    sinon.stub(messenger, 'send');
    session = {
      profile: {
        first_name: '  Guy  ',
        last_name: '  Hoozdis  '
      }
    };
  });

  afterEach(() => {
    // TODO investigate making the suite mock `reqPromise.post` instead of `send`
    messenger.send.restore && messenger.send.restore();
  });

  describe('doLogin', function () {
    this.timeout(100);
    it('emits login event', () => {
      messenger.once('login', (payload) => {
        assert.ok(payload.event);
        assert.equal(payload.senderId, 'narf');
      });

      messenger.doLogin('narf');

      assert.equal(messenger.send.callCount, 1);
    });
  });

  describe('onAuth', function () {
    this.timeout(100);
    const baseEvent = {
      sender: {id: 'senderId'},
      recipient: {id: 'recipientId'},
      timestamp: 0,
      optin: {ref: ''}
    };

    it('emits auth event', () => {
      messenger.once('auth', (payload) => {
        assert.ok(payload.event);
        assert.ok(payload.session);
        assert.equal(payload.senderId, 'senderId');
        assert.equal(payload.optinRef, 'narf');
      });
      const event = Object.assign({}, baseEvent, {
        optin: {
          ref: 'narf'
        }
      });

      messenger.onAuth(event, {});

      assert.equal(messenger.send.callCount, 0);
    });
  });

  describe('onLink', function () {
    this.timeout(100);
    const baseEvent = {
      sender: {id: 'senderId'},
      recipient: {id: 'recipientId'},
      timestamp: 0,
      facebook: {id: ''}
    };

    it('emits link event', () => {
      messenger.once('link', (payload) => {
        assert.ok(payload.event);
        assert.equal(payload.senderId, 'senderId');
        assert.equal(payload.fbData.id, 'narf');
      });
      const event = Object.assign({}, baseEvent, {
        facebook: {
          id: 'narf'
        }
      });

      messenger.onLink(event);
    });
  });

  describe('onMessage message router', function () {
    this.timeout(100);
    const baseEvent = {
      sender: {id: 'senderId'},
      recipient: {id: 'recipientId'},
      timestamp: 0,
      message: {}
    };

    it('emits "message" event', () => {
      messenger.once('message', (payload) => {
        assert.ok(payload.event);
        assert.equal(payload.senderId, 'senderId');
        assert.deepEqual(payload.message, {foo: 'bar'});
      });
      const event = Object.assign({}, baseEvent, {
        message: {foo: 'bar'}
      });

      messenger.onMessage(event);
    });

    it('emits "text" event', () => {
      const event = Object.assign({}, baseEvent, {
        message: {
          text: 'message text'
        }
      });
      const fakeSession = {};
      messenger.once('text', (payload) => {
        assert.ok(payload.event);
        assert.equal(payload.senderId, 'senderId');
        assert.equal(payload.source, 'text');
        assert.equal(payload.text, 'message text');
      });

      messenger.onMessage(event, fakeSession);
    });

    it('emits "quick reply" event', () => {
      const messageText = 'Text message test';
      const quickReplyPayload = 'quick-reply-payload';
      messenger.once('text', (quickReply) => {
        assert.ok(quickReply.event);
        assert.equal(quickReply.senderId, 'senderId');
        assert.equal(quickReply.source, 'quickReply');
        assert.equal(quickReply.text, quickReplyPayload);
      });
      const event = Object.assign({}, baseEvent, {
        message: {
          quick_reply: { payload: quickReplyPayload },
          text: messageText
        }
      });

      messenger.onMessage(event, {});
    });

    it('emits "image" event', () => {
      messenger.once('message.image', (payload) => {
        assert.ok(payload.event);
        assert.equal(payload.senderId, 'senderId');
        assert.equal(payload.url, 'http://i.imgur.com/w1F7dae.jpg');
      });
      const event = Object.assign({}, baseEvent, {
        message: {
          attachments: [
            {
              type: 'image',
              payload: {
                url: 'http://i.imgur.com/w1F7dae.jpg'
              }
            }
          ]
        }
      });

      messenger.onMessage(event);
    });

    it('emits "sticker" event', () => {
      messenger.once('message.sticker', () => {});
      const event = Object.assign({}, baseEvent, {
        message: {
          sticker_id: 201013950048539,
          attachments: [
            {
              type: 'image',
              payload: {
                url: 'https://scontent.xx.fbcdn.net/t39.1997-6/p100x100/851576_201013953381872_1273966384_n.png?_nc_ad=z-m',
                sticker_id: 201013950048539
              }
            }
          ]
        }
      });

      messenger.onMessage(event);
    });

    it('emits "thumbsup" event', () => {
      messenger.once('message.thumbsup', (payload) => {
        assert.equal(payload.senderId, 'senderId');
      });
      const event = Object.assign({}, baseEvent, {
        message: {
          sticker_id: 369239263222822,
          attachments: [
            {
              type: 'image',
              payload: {
                url: 'https://scontent.xx.fbcdn.net/t39.1997-6/851557_369239266556155_759568595_n.png?_nc_ad=z-m',
                sticker_id: 369239263222822
              }
            }
          ]
        }
      });

      messenger.onMessage(event);
    });

    it('emits "greeting" event', () => {
      const text = "hello, is it me you're looking for?";
      const event = Object.assign({}, baseEvent, { message: { text: text } });
      messenger.once('text.greeting', (payload) => {
        assert.ok(payload.event);
        assert.equal(payload.senderId, 'senderId');

        assert.ok(payload.firstName);
        assert.ok(payload.surName);
        assert.ok(payload.fullName);
      });

      messenger.once('message.text', (payload) => {
        assert.fail('message.text', 'text.greeting', 'incorrect event emitted');
      });

      messenger.onMessage(event, session);
    });

    it('emits "text" event for greeting when emitGreetings is disabled', () => {
      const myMessenger = new app.Messenger(config, {emitGreetings: false});
      sinon.stub(myMessenger, 'send');

      const text = "hello, is it me you're looking for?";
      const event = Object.assign({}, baseEvent, {
        message: { text: text }
      });
      myMessenger.once('text.greeting', (payload) => {
        assert.fail('text', 'text.greeting', 'incorrect event emitted');
      });

      myMessenger.once('text', (payload) => {
        assert.ok(payload.event);
        assert.equal(payload.senderId, 'senderId');
      });

      myMessenger.onMessage(event, {});
    });

    it('emits "help" event', () => {
      const text = "help me out";
      const event = Object.assign({}, baseEvent, { message: { text: text } });
      messenger.once('text.help', (payload) => {
        assert.ok(payload.event);
        assert.equal(payload.senderId, 'senderId');
      });

      messenger.once('message.text', (payload) => {
        assert.fail('message.text', 'text.help', 'incorrect event emitted');
      });

      messenger.onMessage(event, {});
    });
  });

  describe('onPostback', function () {
    this.timeout(100);
    const baseEvent = {
      sender: {id: 'senderId'},
      recipient: {id: 'recipientId'},
      timestamp: 0,
      postback: {payload: ''}
    };

    it('emits postback event', () => {
      messenger.once('text', (payload) => {
        assert.ok(payload.event);
        assert.equal(payload.senderId, 'senderId');
        assert.equal(payload.source, 'postback');
        assert.equal(payload.text, 'narf');
      });
      const event = Object.assign({}, baseEvent, {
        postback: {
          payload: 'narf'
        }
      });

      messenger.onPostback(event);
    });
  });

  describe('send', function () {
    let postStub;

    beforeEach(() => {
      postStub = sinon.stub(reqPromise, 'post').returns(Promise.resolve({}));
    });

    afterEach(() => {
      postStub.restore();
    });

    it('passed sender id and message', () => {
      messenger.send.restore();

      return messenger.send('senderId', {foo: 'bar'})
        .then(() => {
          assert.equal(reqPromise.post.args[0][0].json.recipient.id, 'senderId');
          assert.deepEqual(reqPromise.post.args[0][0].json.message, {foo: 'bar'});
        });
    });
  });

  describe('staticContent', function () {
    it('provides a homepage', (done) => {
      chai.request(messenger.app)
        .get('/')
        .end(function (err, res) {
          assert.equal(res.statusCode, 200);
          done();
        });
    });

    xit('provides a Send to Messenger button', (done) => {
      chai.request(messenger.app)
        .get('/send-to-messenger')
        .end(function (err, res) {
          assert.equal(res.statusCode, 200);
          assert.ok(res.text.includes('fb-send-to-messenger'));
          done();
        });
    });

    xit('provides a Message Us button', (done) => {
      chai.request(messenger.app)
        .get('/send-to-messenger')
        .end(function (err, res) {
          assert.equal(res.statusCode, 200);
          assert.ok(res.text.includes('fb-messengermessageus'));
          done();
        });
    });

    it('provides a departures healthcheck', (done) => {
      chai.request(messenger.app)
        .get('/ping')
        .end(function (err, res) {
          assert.equal(res.statusCode, 200);
          done();
        });
    });

  });

  describe('routeEachMessage session', () => {
    const baseMessage = {
      sender: {id: 'teehee'}
    };
    let messenger;

    beforeEach(() => {
      messenger = new app.Messenger(config);
      sinon.stub(messenger, 'getPublicProfile').returns({then: (resolve) => resolve({})});
    });

    afterEach(() => {
      messenger.getPublicProfile.restore();
    });

    it('counts every message received', () =>
      messenger.routeEachMessage(baseMessage)
        .then(() => messenger.routeEachMessage(baseMessage))
        .then((session) => {
          assert.equal(session.count, 2);
        })
    );

    it('sets lastSeen', () =>
      messenger.routeEachMessage(baseMessage)
        .then((session) => {
          assert.equal(typeof session.lastSeen, 'number');
        })
    );

    it('sets source for auth messages', () => {
      const authMessage = Object.assign({optin: 'foo'}, baseMessage);
      return messenger.routeEachMessage(authMessage)
        .then(() => app.__internals__.cache.get(baseMessage.sender.id))
        .then((session) => {
          assert.equal(session.source, 'web');
        });
    });

    describe('return user', () => {
      let originalValue;

      before(() => {
        originalValue = app.__internals__.SESSION_TIMEOUT_MS;
        app.__internals__.SESSION_TIMEOUT_MS = 0;
      });

      after(() => {
        app.__internals__.SESSION_TIMEOUT_MS = originalValue;
      });

      it('sets source for return user', () =>
        messenger.routeEachMessage(baseMessage)
          .then((session) => {
            session.source = 'foo';
            return messenger.routeEachMessage(baseMessage);
          })
          .then((session) => {
            assert.equal(session.source, 'return');
          })
      );
    });

    it('does not set source for user still in session', () =>
      messenger.routeEachMessage(baseMessage)
        .then((session) => {
          session.source = 'foo this should not change';
          return app.__internals__.cache.set(baseMessage.sender.id, session);
        })
        .then(() => {
          return messenger.routeEachMessage(baseMessage);
        })
        .then((session) => {
          assert.equal(session.source, 'foo this should not change');
        })
    );
  });
});
<|endoftext|>


<commit_before>'use strict';

function EntityGroup(world, entity) {
    this.__init__(world, entity);
}

EntityGroup.prototype = {

    __init__: function(world, entity) {
        this.initialize(world, entity);

        // Subscribe to entity notification events.
        EntityChangesSubscriber.call(this, world, true);
    },

    _edit_entity: function(entity_relative_id, entity_button) {
        this.wall_entity_editor.edit_entity(entity_relative_id, entity_button);
    },

    /*___      ___   ___         ___       ___      ___  __                     __               __
     |__  |\ |  |  |  |  \ /    |__  \  / |__  |\ |  |  /__`    |__|  /\  |\ | |  \ |    | |\ | / _`
     |___ | \|  |  |  |   |     |___  \/  |___ | \|  |  .__/    |  | /~~\ | \| |__/ |___ | | \| \__> */
    on_entity_added: function(entity) {
        // TODO : Move the logic of this line?
        //entity.set_property(ENTITY_PROPERTY_GROUP_NAME, this.entity_wall_title.get_text());

        var entity_name = entity.get_value(ENTITY_PROPERTY_NAME);
        var entity_relative_id = entity.get_relative_id();
        var entity_button = this.entity_wall.add_row(null, entity_relative_id).add_2D_button([0, 1], entity_name, COLOR_YELLOW, null);
        entity_button.set_engage_function(this._edit_entity.bind(this, entity_relative_id, entity_button));

        // Entities that get added to an EntityGroup must set the EntityGroupEntity as its parent.
        entity.add_parent(this.entity_group_entity);

        this.base_wall.refresh_position_and_look_at();
    },

    on_entity_deleted: function(entity) {
        this.entity_wall.delete_row_by_name(entity.get_relative_id());
        this.base_wall.refresh_position_and_look_at();
    },

    /*        ___                 __   __   ___      ___         __                __           __        __          __
     | |\ | |  |  |  /\  |       /  ` |__) |__   /\   |  | |\ | / _`     /\  |\ | |  \    |    /  \  /\  |  \ | |\ | / _`
     | | \| |  |  | /~~\ |___    \__, |  \ |___ /~~\  |  | | \| \__>    /~~\ | \| |__/    |___ \__/ /~~\ |__/ | | \| \__> */
    initialize: function(world, entity) {
        var was_loaded = false;

        if (!is_defined(entity)) {
            this.create_new(world);
        } else {
            was_loaded = true;
            this.load_from_entity(world, entity);
        }
        this.base_wall_init_start();

        if (!was_loaded) {
            this.create_new_finalize();
        } else {
            this.load_from_entity_finalize();
        }

        this.wall_entity_editor = new EntityEditor(this, this.base_wall);
        this.wall_entity_editor.set_create_entity_display_button(this.create_new_entity_button);

        this.base_wall.refresh_position_and_look_at();
    },

    create_new: function(world) {
        var data = get_player_blink_spot(1000);

        this.base_wall = new FloatingWall(400, 600, data[0], data[1], world, true);
        this.entity_wall_title = this.base_wall.add_row(-1).add_3D_element('Entity Group', TYPE_INPUT);

        this.base_wall.set_to_saveable(world.entity);
    },

    load_from_entity: function(world, entity) {
        this.entity_group_entity = entity;

        this.base_wall = new FloatingWall(400, 600, null, null, world, true);
        this.base_wall.load_from_entity_data(this.entity_group_entity.get_parent());

        this.entity_wall_title = this.base_wall.get_row_with_index(-1).elements[0];
    },

    base_wall_init_start: function() {
        // Create the standard functionality of the entity wall.
        this.create_new_entity_button = this.base_wall.add_row(0).add_2D_button([0, 1], 'create new entity', COLOR_GREEN, null);

        // TODO : Create a button for deleting the entity wall!!

        this.base_wall.world.root_attachables.push(this.base_wall);

        this.entity_wall = this.base_wall.add_floating_wall_attachment(this.base_wall.width * .8, this.base_wall.height * .8, 0, 0, 5, false);
        this.entity_wall.set_background_color(COLOR_BLACK, true);
    },

    create_new_finalize: function() {
        this.entity_wall.set_to_saveable();
        this.entity_group_entity = this.entity_wall.get_self_entity();
        this.entity_group_entity.set_property(ENTITY_DEFAULT_PROPERTY_TYPE, ENTITY_TYPE_ENTITY_GROUP);
        this.entity_group_entity.add_parent(this.base_wall.get_self_entity());
    },

    load_from_entity_finalize: function() {
        var number_of_children = this.entity_group_entity.number_of_children();
        for (var e = 0; e < number_of_children; e++) {
            this.entity_group_entity.children[e].user_created = true;
            this.entity_added(this.entity_group_entity.children[e]);
        }
    }
};<commit_msg>client side dynamic content management work 17<commit_after>'use strict';

function EntityGroup(world, entity) {
    this.__init__(world, entity);
}

EntityGroup.prototype = {

    __init__: function(world, entity) {
        // Subscribe to entity notification events.
        EntityChangesSubscriber.call(this, world, true);

        this.initialize(world, entity);
    },

    _edit_entity: function(entity_relative_id, entity_button) {
        this.wall_entity_editor.edit_entity(entity_relative_id, entity_button);
    },

    /*___      ___   ___         ___       ___      ___  __                     __               __
     |__  |\ |  |  |  |  \ /    |__  \  / |__  |\ |  |  /__`    |__|  /\  |\ | |  \ |    | |\ | / _`
     |___ | \|  |  |  |   |     |___  \/  |___ | \|  |  .__/    |  | /~~\ | \| |__/ |___ | | \| \__> */
    on_entity_added: function(entity) {
        // TODO : Move the logic of this line?
        //entity.set_property(ENTITY_PROPERTY_GROUP_NAME, this.entity_wall_title.get_text());

        var entity_name = entity.get_value(ENTITY_PROPERTY_NAME);
        var entity_relative_id = entity.get_relative_id();
        var entity_button = this.entity_wall.add_row(null, entity_relative_id).add_2D_button([0, 1], entity_name, COLOR_YELLOW, null);
        entity_button.set_engage_function(this._edit_entity.bind(this, entity_relative_id, entity_button));

        // Entities that get added to an EntityGroup must set the EntityGroupEntity as its parent.
        entity.add_parent(this.entity_group_entity);

        this.base_wall.refresh_position_and_look_at();
    },

    on_entity_deleted: function(entity) {
        this.entity_wall.delete_row_by_name(entity.get_relative_id());
        this.base_wall.refresh_position_and_look_at();
    },

    /*        ___                 __   __   ___      ___         __                __           __        __          __
     | |\ | |  |  |  /\  |       /  ` |__) |__   /\   |  | |\ | / _`     /\  |\ | |  \    |    /  \  /\  |  \ | |\ | / _`
     | | \| |  |  | /~~\ |___    \__, |  \ |___ /~~\  |  | | \| \__>    /~~\ | \| |__/    |___ \__/ /~~\ |__/ | | \| \__> */
    initialize: function(world, entity) {
        var was_loaded = false;

        if (!is_defined(entity)) {
            this.create_new(world);
        } else {
            was_loaded = true;
            this.load_from_entity(world, entity);
        }
        this.base_wall_init_start();

        if (!was_loaded) {
            this.create_new_finalize();
        } else {
            this.load_from_entity_finalize();
        }

        this.wall_entity_editor = new EntityEditor(this, this.base_wall);
        this.wall_entity_editor.set_create_entity_display_button(this.create_new_entity_button);

        this.base_wall.refresh_position_and_look_at();
    },

    create_new: function(world) {
        var data = get_player_blink_spot(1000);

        this.base_wall = new FloatingWall(400, 600, data[0], data[1], world, true);
        this.entity_wall_title = this.base_wall.add_row(-1).add_3D_element('Entity Group', TYPE_INPUT);

        this.base_wall.set_to_saveable(world.entity);
    },

    load_from_entity: function(world, entity) {
        this.entity_group_entity = entity;

        this.base_wall = new FloatingWall(400, 600, null, null, world, true);
        this.base_wall.load_from_entity_data(this.entity_group_entity.get_parent());

        this.entity_wall_title = this.base_wall.get_row_with_index(-1).elements[0];
    },

    base_wall_init_start: function() {
        // Create the standard functionality of the entity wall.
        this.create_new_entity_button = this.base_wall.add_row(0).add_2D_button([0, 1], 'create new entity', COLOR_GREEN, null);

        // TODO : Create a button for deleting the entity wall!!

        this.base_wall.world.root_attachables.push(this.base_wall);

        this.entity_wall = this.base_wall.add_floating_wall_attachment(this.base_wall.width * .8, this.base_wall.height * .8, 0, 0, 5, false);
        this.entity_wall.set_background_color(COLOR_BLACK, true);
    },

    create_new_finalize: function() {
        this.entity_wall.set_to_saveable();
        this.entity_group_entity = this.entity_wall.get_self_entity();
        this.entity_group_entity.set_property(ENTITY_DEFAULT_PROPERTY_TYPE, ENTITY_TYPE_ENTITY_GROUP);
        this.entity_group_entity.add_parent(this.base_wall.get_self_entity());
    },

    load_from_entity_finalize: function() {
        var number_of_children = this.entity_group_entity.number_of_children();
        for (var e = 0; e < number_of_children; e++) {
            this.entity_group_entity.children[e].user_created = true;
            this.entity_added(this.entity_group_entity.children[e]);
        }
    }
};<|endoftext|>