<commit_before>/* Magic Mirror
 * Module: MMM-DWD-WarnWeather
 *
 * By Luke Scheffler https://github.com/LukeSkywalker92
 * MIT Licensed.
 */

var NodeHelper = require('node_helper');
var request = require('request');

module.exports = NodeHelper.create({
	start: function () {
		console.log('MMM-DWD-WarnWeather helper started...')
	},

	dataLoadingComplete: function (self, warningData, region, communityData){
		self.sendSocketNotification('WARNINGS_DATA', {warnings: warningData, region: region, community: communityData});
	},

	getWarningData: function (region, callback) {
		var self = this;
		var severityStr = " AND SEVERITY IN ('Extreme'";

		if (region.sevThres < 4) {
			severityStr = severityStr + ",'Severe'";
		}
		else if (region.sevThres < 3) {
			severityStr = severityStr + ",'Moderate'";
		}
		else if (region.sevThres < 2) {
			severityStr = severityStr + ",'Minor'";
		}

		severityStr = severityStr + ")";

		if (region.lng) {
			var regionFilter = encodeURIComponent("CONTAINS(THE_GEOM, POINT(" + region.lng + " " + region.lat + "))" + severityStr);
		}
    else {
		  var regionFilter = encodeURIComponent("AREADESC='" + region.reg + "'" + severityStr);
    }

		var communityData = [];
		var warningData = [];

		var nameurl = 'https://maps.dwd.de/geoserver/dwd/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=dwd:Warngebiete_Gemeinden&outputFormat=application%2Fjson&CQL_FILTER=' +
					(regionFilter.includes("AREADESC")?regionFilter.replace("AREADESC", "DWD_NAME"):regionFilter);
		var warnurl = 'https://maps.dwd.de/geoserver/dwd/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=dwd:Warnungen_Gemeinden&outputFormat=application%2Fjson&CQL_FILTER=' + regionFilter;

		var requests = 2;

		//get name
		request({
			url: nameurl,
			method: 'GET'
		}, function (error, response, body) {
			var result = JSON.parse(body);
			if (result.totalFeatures == 1) {
				communityData = result.features[0];
			}
			if(--requests == 0) {
				callback(self, warningData, region, communityData);
			}
		});

		//get warnings
		request({
			url: warnurl,
			method: 'GET'
		}, function (error, response, body) {

			var result = JSON.parse(body);

			if (result.totalFeatures > 0) {
				for (var i = 0; i < result.totalFeatures; i++) {
					warningData.push(result.features[i]);
				}
			}
			if(--requests == 0) {
				callback(self, warningData, region, communityData);
			}
		});
	},

	socketNotificationReceived: function (notification, payload) {
    if (notification === 'GET_WARNINGS') {
			this.getWarningData(payload, this.dataLoadingComplete);
		}
	}

});
<commit_msg>Update node_helper.js<commit_after>/* Magic Mirror
 * Module: MMM-DWD-WarnWeather
 *
 * By Luke Scheffler https://github.com/LukeSkywalker92
 * MIT Licensed.
 */

var NodeHelper = require('node_helper');
var request = require('request');

module.exports = NodeHelper.create({
	start: function () {
		console.log('MMM-DWD-WarnWeather helper started...')
	},

	dataLoadingComplete: function (self, warningData, region, communityData){
		self.sendSocketNotification('WARNINGS_DATA', {warnings: warningData, region: region, community: communityData});
	},

	getWarningData: function (region, callback) {
		var self = this;
		var severityStr = " AND SEVERITY IN ('Extreme'";

		if (region.sevThres < 4) {
			severityStr = severityStr + ",'Severe'";
		};
		if (region.sevThres < 3) {
			severityStr = severityStr + ",'Moderate'";
		};
		if (region.sevThres < 2) {
			severityStr = severityStr + ",'Minor'";
		};

		severityStr = encodeURIComponent(severityStr + ")");

		if (region.lng) {
			var regionFilter = encodeURIComponent("CONTAINS(THE_GEOM, POINT(" + region.lng + " " + region.lat + "))");
		}
    else {
		  var regionFilter = encodeURIComponent("AREADESC='" + region.reg + "'");
    }

		var communityData = [];
		var warningData = [];

		var nameurl = 'https://maps.dwd.de/geoserver/dwd/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=dwd:Warngebiete_Gemeinden&outputFormat=application%2Fjson&CQL_FILTER=' +
					(regionFilter.includes("AREADESC")?regionFilter.replace("AREADESC", "DWD_NAME"):regionFilter);
		// console.error(nameurl);
		var warnurl = 'https://maps.dwd.de/geoserver/dwd/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=dwd:Warnungen_Gemeinden&outputFormat=application%2Fjson&CQL_FILTER=' + regionFilter + severityStr;
		// console.error(warnurl);

		var requests = 2;

		//get name
		request({
			url: nameurl,
			method: 'GET'
		}, function (error, response, body) {
			var result = JSON.parse(body);
			if (result.totalFeatures == 1) {
				communityData = result.features[0];
			}
			if(--requests == 0) {
				callback(self, warningData, region.reg, communityData);
			}
		});

		//get warnings
		request({
			url: warnurl,
			method: 'GET'
		}, function (error, response, body) {

			var result = JSON.parse(body);

			if (result.totalFeatures > 0) {
				for (var i = 0; i < result.totalFeatures; i++) {
					warningData.push(result.features[i]);
				}
			}
			if(--requests == 0) {
				callback(self, warningData, region.reg, communityData);
			}
		});
	},

	socketNotificationReceived: function (notification, payload) {
    if (notification === 'GET_WARNINGS') {
			this.getWarningData(payload, this.dataLoadingComplete);
		}
	}

});
<|endoftext|>


<commit_before>var port = typeof( process.env.PORT ) == "undefined" ? 5000 : process.env.PORT;

var fs = require("fs");
var exec = require('child_process').exec;
var wrench = require("./wrench-js/lib/wrench");
var git = require("./GitOperations.js");
var async = require("async");

var zipper = require("node-native-zip");
var folder = require( "./folder" );
var AdmZip = require('adm-zip');
var unzip;

// To be determined later
var baseDir;
var fileName;
var fileData;
var isUpdateOnly = false; // Set when we're just looking to update the server to the most recent state of the repo and zip the directory

var isLocked = false;
var currentUser = null;
var commitMessage = null;

// This will hold the function that we're going to call next. It
// makes our very asynchronous code cleaner.
var nextStep = function() {};

console.log( "Opening socket on port " + port );
var io  = require( 'socket.io' ).listen(port+1);
var dl = require("delivery");

io.sockets.on('connection', function(socket){
	var delivery = dl.listen(socket);

	delivery.on( 'send.error', function( error ) {
		console.log( error );
		console.log( "send error: " + error );
	});

	delivery.on( 'send.start', function( filePackage ) {
		console.log(filePackage.name + " is being sent to the client.");
	});

	delivery.on('send.success', function(file){
		console.log('File successfully sent to client!');
	});

	console.log( "Socket connection" );

	socket.on( "requestTransfer", function( data ) {
		console.log( "transfer requested" );
		console.log( data );
		if( isLocked ) {
			emitError( "Transfer locked: server busy" );
			return;
		} else {
			currentUser = socket.id;
			baseDir = data.baseDir;
			commitMessage = data.commitMessage;

			io.sockets.socket( currentUser ).emit( "transferAccepted" );

			isLocked = true;
		}
	});

	socket.on( "requestHEAD", function( data ) {
		console.log( "update to HEAD requested" );

		var deliveryObj= {
			name: data.fileName,
			path: getOneFolderUp(data.baseDir) + data.fileName
		};

		console.log( deliveryObj );

		if( isLocked ) {
			emitError( "Transfer locked: server busy" );
			return;
		} else {
			console.log( "Checking out" );

			// Run our git operations asynchronously
			async.series([
				function( callback ){
					var undefinedVar;
					git.checkout( undefinedVar, callback );
				},
				function( callback ){
					git.pull( true, callback );
				},
				function( callback ){
					zipDirectory( data.baseDir, function() {
						console.log( "Zipped directory" );
						console.log( deliveryObj );
						try { delivery.send( deliveryObj ); }
						catch(err) { console.log( err ); callback(err); }

						callback( null, "Success" );
					}); // end zip dir
				},
			], function(err, results){
				console.log( err || results );
			});

			/*
			var child = exec('git checkout -- .', function (error, stdout, stderr) {
				console.log('stdout: ' + stdout);
				console.log('stderr: ' + stderr);

				if( error != null ) {
					emitError( error );
				} else {
					console.log( "pulling" );
					var child = exec('git pull', function (error, stdout, stderr) {
						console.log('stdout: ' + stdout);
						console.log('stderr: ' + stderr);

						if( error != null ) {
							emitError( error );
						} else {
							console.log( "Zipping " + data.baseDir );
							zipDirectory( data.baseDir, function() {
								console.log( "Zipped directory" );
								console.log( deliveryObj );
								try { delivery.send( deliveryObj ); }
								catch(err) { console.log( err ); }
							}); // end zip dir
						} // end pull success
					}); // end exec git pull
				} // end checkout success
			});	// end exec git checkout
			*/

		} // end if not locked
	}); // end on request HEAD

	delivery.on('receive.success',function(file){
		var fileNameWithoutPath = getFileNameFromPath( file.name );

		fileName = fileNameWithoutPath;

		// Create our temp directory if it doesn't exist already
		if( !dirExistsSync( "temp" ) ) {
			fs.mkdir( "temp" );
		}

		fs.writeFile( "temp/" + fileNameWithoutPath, file.buffer, function( err ) {
			if( err ) {
				console.log( 'File could not be saved: ' + err );
			} else {
				console.log( 'File ' + file.name + " saved" );

				// Run our git operations asynchronously
				async.series([
					function( callback ){
						var undefinedVar;
						git.checkout( undefinedVar, callback );
					},
					function( callback ){
						git.pull( true, callback );
					},
					function( callback ){
						deleteExistingFiles( callback );
					},
					function( callback ){
						copyIncomingFiles( callback );
					},
					function( callback ){
						git.push( callback );
					},
				], function(err, results){
					console.log( err || results );
				});
			};
		});
	});
}); // end socket on Connection

function startProcess() {
	nextStep = gitCheckout;

	callNextStep();
} // end startProcess()

function processDone() {
	io.sockets.socket(currentUser).emit( "processDone" );
	isLocked = false;
	currentUser = null;
	commitMessage = null;
}

function callNextStep( error ) {
	if( typeof(error) == "undefined" || error == null )
		nextStep();
	else {
		emitError( error );
	}
} // end callNextStep()

function gitCheckout() {
	console.log( "Checking out back to HEAD" );
	nextStep = gitPullRebase;

	var child = exec('git checkout -- .', function (error, stdout, stderr) {
		console.log('stdout: ' + stdout);
		console.log('stderr: ' + stderr);

		if( error != null ) {
			callNextStep( stderr );
		} else {
			callNextStep( null );
		}
	});
} // end gitCheckout()

function gitPullRebase( clearAndPullOnly ) {
	console.log( "Pulling from remote" );
	if( clearAndPullOnly ) {
		nextStep = zipDirectory( baseDir, function() {
			console.log( "Zipped directory" );
		});
	} else {
		nextStep = deleteExistingFiles;
	}

	var child = exec('git pull', function (error, stdout, stderr) {
		console.log('stdout: ' + stdout);
		console.log('stderr: ' + stderr);

		if( error != null ) {
			callNextStep( stderr );
		} else {
			callNextStep( null );
		}
	});
} // end gitPullRebase()

// REMOVE THE DIRECTORY RECURSIVELY (scary, I know)
function deleteExistingFiles( callback ) {
	console.log( "Deleting all files within " + baseDir );
	nextStep = copyIncomingFiles;

	if( baseDir.length < 6 ) {
		console.log( "ALMOST DELETED " + baseDir );
		emitError( "Base directory (" + baseDir + ") is too short, do you really want to delete that :/" );
	}

	var rmDirFilter = function( file ) {
		console.log( file );

		var path;

		if( typeof(file) == "string" ) {
			path = file;
		} else if( typeof(file) == "object" ) {
			path = file.path;
		} else {
			console.log( "Unknown type: " + typeof(file) );
			return false;
		}

		// Only delete things that don't have "/.git/" in them
		if( typeof(path) == "undefined" || path.indexOf("/.git/") != -1 )
			return false;
		else
			return true;
	}

	console.log( "about to remove...hold your breath" );

	// REMOVE THE DIRECTORY RECURSIVELY (scary, I know)
	wrench.rmdirRecursive( baseDir, rmDirFilter, callback );
} // end deleteExistingFiles()

function copyIncomingFiles( callback ) {
	console.log( "Unzipping and copying incoming files into place" );
	nextStep = gitPush;

	try {
		unzip = new AdmZip( "./temp/" + fileName );
	} catch( err ) {
		console.log( "Couldn't open zipped directory: " + err );
	}

	// Extract all files
	unzip.extractAllTo( baseDir, true );

	if( typeof(callback) != "undefined" ) { callNextStep(); }
} // end copyIncomingFiles()

function gitCommit() {
	console.log( "Committing files to git" );

	if( typeof(commitMessage) == "undefined" )
		commitMessage = "Files changed using EasyGit";

	exec('git commit -m "' + commitMessage + '" -- ' + baseDir, function (error, stdout, stderr) {
		console.log('stdout: ' + stdout);
		console.log('stderr: ' + stderr);

		if( error != null ) {
			callNextStep( stderr );
		} else {
			callNextStep( null );
		}
	});
}

function gitPush() {
	console.log( "Pushing changes to git" );
	/*
	exec('git status', function (error, stdout, stderr) {
		console.log('stdout: ' + stdout);
		console.log('stderr: ' + stderr);
		if (error !== null) {
			console.log(error);
		} else {
			console.log( "Success!" );
			processDone();
		}
	});
	*/
	exec('git push origin master', function (error, stdout, stderr) {
		console.log('stdout: ' + stdout);
		console.log('stderr: ' + stderr);
		if (error !== null) {
			emitError(error);
		} else {
			console.log( "Success!" );
			processDone();
		}
	});
} // end gitPush()

function emitError( error ) {
	io.sockets.socket( currentUser ).emit( "transferError", {error: error} );
	console.log( "Error: " + error );

	isLocked = false;
	currentUser = null;
	commitMessage = null;
}

function dirExistsSync( d ) {
	try { fs.statSync( d ).isDirectory() }
	catch( er ) { return false }
} // end dirExistsSync()

function getFileNameFromPath( fullPath ) {
	var lastBackSlash = fullPath.lastIndexOf( "\\" ),
		lastForwardSlash = fullPath.lastIndexOf( "/" );

	var folderStart = lastBackSlash > lastForwardSlash ? lastBackSlash : lastForwardSlash;

	return fullPath.substring( folderStart + 1 );
}

function getBaseDirFromFilePath( filePath ) {
	var lastBackSlash = fullPath.lastIndexOf( "\\" ),
		lastForwardSlash = fullPath.lastIndexOf( "/" );

	var lastfolderStart = lastBackSlash > lastForwardSlash ? lastBackSlash : lastForwardSlash;

	return fullPath.substring( 0, lastfolderStart + 1 );
}

function zipDirectory( dir, callback ) {
	var archive = new zipper();

	console.log( "Starting to zip" );
	console.log( dir );

	// map all files in the approot thru this function
	folder.mapAllFiles(dir, function (path, stats, callback) {
		if( path.indexOf(".git") != -1 ) return callback();

		// Figure out the base directory for all of these files
		var baseDir = getFolderName(dir);

		var afterBaseIndex = path.indexOf(baseDir) /* + baseDir.length + 1*/;

		var callbackParams = {
			//name: path.replace(dir, "").substr(1),
			name: path.substring(afterBaseIndex, path.length),
			path: path
		};

		console.log( callbackParams );

		// prepare for the .addFiles function
		callback( callbackParams );
	}, function (err, data) {
		if (err) return callback(err);

		// add the files to the zip
		archive.addFiles(data, function (err) {
			if (err) return callback(err);

			// write the zip file
			console.log( "writing zip file to " + dir );
			fs.writeFile(dir + ".zip", archive.toBuffer(), function ( err ) {
				if (err) return callback(err);

				callback(null, dir + ".zip");
			});
		});
	});
} // end zipDirectory()

//////////////////////////////////////////////////////////////////////////
// Returns the folder from a full filepath
function getFolderName( fullPath ) {
	var lastBackSlash = fullPath.lastIndexOf( "\\" ),
		lastForwardSlash = fullPath.lastIndexOf( "/" ),
		isForwardSlash;

	// Figure out whether we're working with a forward or backward slash
	if( lastBackSlash > lastForwardSlash ) {
		lastSlash = lastBackSlash;
		isForwardSlash = false;
	} else {
		lastSlash = lastForwardSlash;
		isForwardSlash = true;
	}

	// Pull off any file thats on the end
	if( fullPath.indexOf(".") != -1 ) {
		fullPath= fullPath.substring( 0, lastSlash );
		lastSlash = isForwardSlash ? fullPath.lastIndexOf( "/" ) : fullPath.lastIndexOf( "\\" );
	}

	// Make sure the last slash isn't at the end of the string
	if( lastSlash == fullPath.length - 1 ) {
		fullPath= fullPath.substring( 0, fullPath.length - 1 );
		lastSlash = isForwardSlash ? fullPath.lastIndexOf( "/" ) : fullPath.lastIndexOf( "\\" );
	}

	return fullPath.substring( lastSlash + 1 );
} // end getFolderName()

function getOneFolderUp( folderPath ) {
	var folderName = getFolderName( folderPath );

	return folderPath.substring( 0, folderPath.indexOf(folderName) );
}
<commit_msg>Make sure there are no naming conflicts (although I don't think there would have been)<commit_after>var port = typeof( process.env.PORT ) == "undefined" ? 5000 : process.env.PORT;

var fs = require("fs");
var exec = require('child_process').exec;
var wrench = require("./wrench-js/lib/wrench");
var git = require("./GitOperations.js");
var async = require("async");

var zipper = require("node-native-zip");
var folder = require( "./folder" );
var AdmZip = require('adm-zip');
var unzip;

// To be determined later
var baseDir;
var fileName;
var fileData;
var isUpdateOnly = false; // Set when we're just looking to update the server to the most recent state of the repo and zip the directory

var isLocked = false;
var currentUser = null;
var commitMessage = null;

// This will hold the function that we're going to call next. It
// makes our very asynchronous code cleaner.
var nextStep = function() {};

console.log( "Opening socket on port " + port );
var io  = require( 'socket.io' ).listen(port+1);
var dl = require("delivery");

io.sockets.on('connection', function(socket){
	var delivery = dl.listen(socket);

	delivery.on( 'send.error', function( error ) {
		console.log( error );
		console.log( "send error: " + error );
	});

	delivery.on( 'send.start', function( filePackage ) {
		console.log(filePackage.name + " is being sent to the client.");
	});

	delivery.on('send.success', function(file){
		console.log('File successfully sent to client!');
	});

	console.log( "Socket connection" );

	socket.on( "requestTransfer", function( data ) {
		console.log( "transfer requested" );
		console.log( data );
		if( isLocked ) {
			emitError( "Transfer locked: server busy" );
			return;
		} else {
			currentUser = socket.id;
			baseDir = data.baseDir;
			commitMessage = data.commitMessage;

			io.sockets.socket( currentUser ).emit( "transferAccepted" );

			isLocked = true;
		}
	});

	socket.on( "requestHEAD", function( data ) {
		console.log( "update to HEAD requested" );

		var deliveryObj= {
			name: data.fileName,
			path: getOneFolderUp(data.baseDir) + data.fileName
		};

		console.log( deliveryObj );

		if( isLocked ) {
			emitError( "Transfer locked: server busy" );
			return;
		} else {
			console.log( "Checking out" );

			// Run our git operations asynchronously
			async.series([
				function( callback ){
					var undefinedVar;
					git.checkout( undefinedVar, callback );
				},
				function( callback ){
					git.pull( true, callback );
				},
				function( callback ){
					zipDirectory( data.baseDir, function() {
						console.log( "Zipped directory" );
						console.log( deliveryObj );
						try { delivery.send( deliveryObj ); }
						catch(err) { console.log( err ); callback(err); }

						callback( null, "Success" );
					}); // end zip dir
				},
			], function(err, results){
				console.log( err || results );
			});

			/*
			var child = exec('git checkout -- .', function (error, stdout, stderr) {
				console.log('stdout: ' + stdout);
				console.log('stderr: ' + stderr);

				if( error != null ) {
					emitError( error );
				} else {
					console.log( "pulling" );
					var child = exec('git pull', function (error, stdout, stderr) {
						console.log('stdout: ' + stdout);
						console.log('stderr: ' + stderr);

						if( error != null ) {
							emitError( error );
						} else {
							console.log( "Zipping " + data.baseDir );
							zipDirectory( data.baseDir, function() {
								console.log( "Zipped directory" );
								console.log( deliveryObj );
								try { delivery.send( deliveryObj ); }
								catch(err) { console.log( err ); }
							}); // end zip dir
						} // end pull success
					}); // end exec git pull
				} // end checkout success
			});	// end exec git checkout
			*/

		} // end if not locked
	}); // end on request HEAD

	delivery.on('receive.success',function(file){
		var fileNameWithoutPath = getFileNameFromPath( file.name );

		fileName = fileNameWithoutPath;

		// Create our temp directory if it doesn't exist already
		if( !dirExistsSync( "temp" ) ) {
			fs.mkdir( "temp" );
		}

		fs.writeFile( "temp/" + fileNameWithoutPath, file.buffer, function( err ) {
			if( err ) {
				console.log( 'File could not be saved: ' + err );
			} else {
				console.log( 'File ' + file.name + " saved" );

				// Run our git operations asynchronously
				async.series([
					function( callback ){
						var undefinedVar;
						git.checkout( undefinedVar, callback );
					},
					function( callback ){
						git.pull( true, callback );
					},
					function( callback ){
						deleteExistingFiles( callback );
					},
					function( callback ){
						copyIncomingFiles( callback );
					},
					function( callback ){
						git.push( callback );
					},
				], function(err, results){
					console.log( err || results );
				});
			};
		});
	});
}); // end socket on Connection

function startProcess() {
	nextStep = gitCheckout;

	callNextStep();
} // end startProcess()

function processDone() {
	io.sockets.socket(currentUser).emit( "processDone" );
	isLocked = false;
	currentUser = null;
	commitMessage = null;
}

function callNextStep( error ) {
	if( typeof(error) == "undefined" || error == null )
		nextStep();
	else {
		emitError( error );
	}
} // end callNextStep()

function gitCheckout() {
	console.log( "Checking out back to HEAD" );
	nextStep = gitPullRebase;

	var child = exec('git checkout -- .', function (error, stdout, stderr) {
		console.log('stdout: ' + stdout);
		console.log('stderr: ' + stderr);

		if( error != null ) {
			callNextStep( stderr );
		} else {
			callNextStep( null );
		}
	});
} // end gitCheckout()

function gitPullRebase( clearAndPullOnly ) {
	console.log( "Pulling from remote" );
	if( clearAndPullOnly ) {
		nextStep = zipDirectory( baseDir, function() {
			console.log( "Zipped directory" );
		});
	} else {
		nextStep = deleteExistingFiles;
	}

	var child = exec('git pull', function (error, stdout, stderr) {
		console.log('stdout: ' + stdout);
		console.log('stderr: ' + stderr);

		if( error != null ) {
			callNextStep( stderr );
		} else {
			callNextStep( null );
		}
	});
} // end gitPullRebase()

// REMOVE THE DIRECTORY RECURSIVELY (scary, I know)
function deleteExistingFiles( callback ) {
	console.log( "Deleting all files within " + baseDir );
	nextStep = copyIncomingFiles;

	if( baseDir.length < 6 ) {
		console.log( "ALMOST DELETED " + baseDir );
		emitError( "Base directory (" + baseDir + ") is too short, do you really want to delete that :/" );
	}

	var rmDirFilter = function( file, cb ) {
		console.log( file );

		var path;

		if( typeof(file) == "string" ) {
			path = file;
		} else if( typeof(file) == "object" ) {
			path = file.path;
		} else {
			console.log( "Unknown type: " + typeof(file) );
			return false;
		}

		// Only delete things that don't have "/.git/" in them
		if( typeof(path) == "undefined" || path.indexOf("/.git/") != -1 )
			return false;
		else
			return true;
	}

	console.log( "about to remove...hold your breath" );

	// REMOVE THE DIRECTORY RECURSIVELY (scary, I know)
	wrench.rmdirRecursive( baseDir, rmDirFilter, callback );
} // end deleteExistingFiles()

function copyIncomingFiles( callback ) {
	console.log( "Unzipping and copying incoming files into place" );
	nextStep = gitPush;

	try {
		unzip = new AdmZip( "./temp/" + fileName );
	} catch( err ) {
		console.log( "Couldn't open zipped directory: " + err );
	}

	// Extract all files
	unzip.extractAllTo( baseDir, true );

	if( typeof(callback) != "undefined" ) { callNextStep(); }
} // end copyIncomingFiles()

function gitCommit() {
	console.log( "Committing files to git" );

	if( typeof(commitMessage) == "undefined" )
		commitMessage = "Files changed using EasyGit";

	exec('git commit -m "' + commitMessage + '" -- ' + baseDir, function (error, stdout, stderr) {
		console.log('stdout: ' + stdout);
		console.log('stderr: ' + stderr);

		if( error != null ) {
			callNextStep( stderr );
		} else {
			callNextStep( null );
		}
	});
}

function gitPush() {
	console.log( "Pushing changes to git" );
	/*
	exec('git status', function (error, stdout, stderr) {
		console.log('stdout: ' + stdout);
		console.log('stderr: ' + stderr);
		if (error !== null) {
			console.log(error);
		} else {
			console.log( "Success!" );
			processDone();
		}
	});
	*/
	exec('git push origin master', function (error, stdout, stderr) {
		console.log('stdout: ' + stdout);
		console.log('stderr: ' + stderr);
		if (error !== null) {
			emitError(error);
		} else {
			console.log( "Success!" );
			processDone();
		}
	});
} // end gitPush()

function emitError( error ) {
	io.sockets.socket( currentUser ).emit( "transferError", {error: error} );
	console.log( "Error: " + error );

	isLocked = false;
	currentUser = null;
	commitMessage = null;
}

function dirExistsSync( d ) {
	try { fs.statSync( d ).isDirectory() }
	catch( er ) { return false }
} // end dirExistsSync()

function getFileNameFromPath( fullPath ) {
	var lastBackSlash = fullPath.lastIndexOf( "\\" ),
		lastForwardSlash = fullPath.lastIndexOf( "/" );

	var folderStart = lastBackSlash > lastForwardSlash ? lastBackSlash : lastForwardSlash;

	return fullPath.substring( folderStart + 1 );
}

function getBaseDirFromFilePath( filePath ) {
	var lastBackSlash = fullPath.lastIndexOf( "\\" ),
		lastForwardSlash = fullPath.lastIndexOf( "/" );

	var lastfolderStart = lastBackSlash > lastForwardSlash ? lastBackSlash : lastForwardSlash;

	return fullPath.substring( 0, lastfolderStart + 1 );
}

function zipDirectory( dir, callback ) {
	var archive = new zipper();

	console.log( "Starting to zip" );
	console.log( dir );

	// map all files in the approot thru this function
	folder.mapAllFiles(dir, function (path, stats, callback) {
		if( path.indexOf(".git") != -1 ) return callback();

		// Figure out the base directory for all of these files
		var baseDir = getFolderName(dir);

		var afterBaseIndex = path.indexOf(baseDir) /* + baseDir.length + 1*/;

		var callbackParams = {
			//name: path.replace(dir, "").substr(1),
			name: path.substring(afterBaseIndex, path.length),
			path: path
		};

		console.log( callbackParams );

		// prepare for the .addFiles function
		callback( callbackParams );
	}, function (err, data) {
		if (err) return callback(err);

		// add the files to the zip
		archive.addFiles(data, function (err) {
			if (err) return callback(err);

			// write the zip file
			console.log( "writing zip file to " + dir );
			fs.writeFile(dir + ".zip", archive.toBuffer(), function ( err ) {
				if (err) return callback(err);

				callback(null, dir + ".zip");
			});
		});
	});
} // end zipDirectory()

//////////////////////////////////////////////////////////////////////////
// Returns the folder from a full filepath
function getFolderName( fullPath ) {
	var lastBackSlash = fullPath.lastIndexOf( "\\" ),
		lastForwardSlash = fullPath.lastIndexOf( "/" ),
		isForwardSlash;

	// Figure out whether we're working with a forward or backward slash
	if( lastBackSlash > lastForwardSlash ) {
		lastSlash = lastBackSlash;
		isForwardSlash = false;
	} else {
		lastSlash = lastForwardSlash;
		isForwardSlash = true;
	}

	// Pull off any file thats on the end
	if( fullPath.indexOf(".") != -1 ) {
		fullPath= fullPath.substring( 0, lastSlash );
		lastSlash = isForwardSlash ? fullPath.lastIndexOf( "/" ) : fullPath.lastIndexOf( "\\" );
	}

	// Make sure the last slash isn't at the end of the string
	if( lastSlash == fullPath.length - 1 ) {
		fullPath= fullPath.substring( 0, fullPath.length - 1 );
		lastSlash = isForwardSlash ? fullPath.lastIndexOf( "/" ) : fullPath.lastIndexOf( "\\" );
	}

	return fullPath.substring( lastSlash + 1 );
} // end getFolderName()

function getOneFolderUp( folderPath ) {
	var folderName = getFolderName( folderPath );

	return folderPath.substring( 0, folderPath.indexOf(folderName) );
}
<|endoftext|>


<commit_before>import {
  moduleForComponent,
  test
} from 'ember-qunit';

moduleForComponent('nav-bar', {});

test('it renders', function(assert) {
  assert.expect(2);

  // creates the component instance
  var component = this.subject();
  assert.equal(component._state, 'preRender');

  // renders the component to the page
  this.render();
  assert.equal(component._state, 'inDOM');

});
<commit_msg>Test for links in nav bar component<commit_after>import {
  moduleForComponent,
  test
} from 'ember-qunit';

moduleForComponent('nav-bar', {});

test('it renders', function(assert) {
  assert.expect(3);

  var component = this.subject();
  assert.equal(component._state, 'preRender');

  this.render();
  assert.equal(component._state, 'inDOM');

  assert.equal(this.$().find('a').length, 2);

});
<|endoftext|>


<commit_before>// See http://stackoverflow.com/a/3291856
String.prototype.capitalize = function() {
  return this.charAt(0).toUpperCase() + this.slice(1);
}
// See https://github.com/yagop/node-telegram-bot-api
var TelegramBot = require('node-telegram-bot-api');

// See https://github.com/t3chnoboy/amazon-product-api
var amazon = require('amazon-product-api');

// See https://github.com/vkurchatkin/which-country
var wc = require('which-country');

// See https://github.com/louischatriot/nedb
var Datastore = require('nedb'),
    db = new Datastore({
      filename: 'datastore.db',
      autoload: true
    });

// List of supported Amazon endpoints
var amazonEndpoints = {
  'US' : 'webservices.amazon.com',
  'CA' : 'webservices.amazon.ca',
  'IT' : 'webservices.amazon.it',
  'DE' : 'webservices.amazon.de',
  'UK' : 'webservices.amazon.co.uk',
  'ES' : 'webservices.amazon.es',
  'FR' : 'webservices.amazon.fr'
};

// Telegram API Token
var token = process.env.TELEGRAM_API_TOKEN || '';

// Create the Bot
var bot = new TelegramBot(
  token,
  {
    webHook: {
      port: process.env.PORT || '3000'
    }
  }
);

// Listen on WebHooks
bot
.setWebHook(
  process.env.BASE_URL + '/' + process.env.WEBHOOK_TOKEN
);

// User is asking for help, or is geeting me for the first time
bot.onText(/\/help|\/start/, function (msg, match) {
  var chatId = msg.chat.id,
      resp = `
This Bot will help you to search your favourite Amazon products directly from here.
If you do not pass any {country code} into the inline query, a default assumption will be used.
Default fallback logic: location ( if available ) -> your setting ( if set ) -> US. The first that matches, is the winner.

You can control me by sending these commands:

/set COUNTRY={COUNTRY CODE} [Supported list: {list}]
This option will set your default country amoung all your chats. If you need to change it, just run this command again.
Example: /set COUNTRY=CA
  `;

  bot.sendMessage(chatId, resp);
});

// Save user preferences...
bot.onText(/\/set (.+)/, function (msg, match) {
  var chatId = msg.chat.id,
      userId = msg.from.id,
      option = match[1];

  setUserOption( userId, option, function ( resp ){
    bot.sendMessage(chatId, resp);
  });
});

// Once the user is searching...
bot
.on( 'inline_query', function ( message ){
  getUserOptions( message.from.id, function (options) {
    answerUser( message, options );
  })
});

var answerUser = function ( message, userOptions ) {
  if ( message.query ) {
    // Get the country where to query
    var query = message.query.split('@')[0],
        country = ( message.query.split('@')[1] || '').toUpperCase();

    if ( !country ) {
      // Detect user country if provided
      if ( message.location ) {
        country = wc([
          message.location.latitude,
          message.location.longitude
        ]);
      }

      // Detect if user set a default, update only if not find by the location
      if ( !country && 'country' in userOptions ) {
        country = userOptions.country;
      }

      // Force the Amazon.com search if no country given or detected
      if ( !country ) country = 'US';
    } else
      // Get only the first two letters and convert them to uppercase
      country = country.toUpperCase().substring(0,2)

    // If the country is given, always check if it's in the list
    if ( country in amazonEndpoints ) {

      // Create the Amazon Client
      var client = amazon.createClient({
        awsId: process.env.AMAZON_ACCESS_ID || '',
        awsSecret: process.env.AMAZON_SECRET_ACCESS_KEY || '',
        awsTag: process.env['AMAZON_ASSOCIATE_TAG_' + country] || ''
      });

      client
      .itemSearch(
        {
          keywords: query,
          searchIndex: 'All',
          responseGroup: 'Images,ItemAttributes,OfferSummary',
          domain: amazonEndpoints[ country ]
        },
        function (error, results) {
          if (error) {
            // Log the error
            console.log( error );
          } else {
            var answers = [],
                endpoint = amazonEndpoints[ country ].replace('webservices.','');

            for ( var k in results ) {
              var item = results[k],
                  id = coalesce( item, k, 'ASIN', 0 ),
                  price = coalesce( item, null, 'OfferSummary', 0, 'LowestNewPrice', 0, 'FormattedPrice', 0 ),
                  url = coalesce( item, 'https://' + endpoint, 'DetailPageURL', 0 ),
                  title = coalesce( item, 'No Title', 'ItemAttributes', 0, 'Title', 0 ),
                  imageUrl = coalesce( item, '', 'ImageSets', 0, 'ImageSet', 0, 'LargeImage', 0, 'URL', 0 ),
                  thumbUrl = coalesce( item, amazonEndpoints[ country ].replace('webservices.','https://'), 'ImageSets', 0, 'ImageSet', 0, 'SmallImage', 0, 'URL', 0 ),
                  thumbWidth = parseInt( coalesce( item, 0, 'ImageSets', 0, 'ImageSet', 0, 'SmallImage', 0, 'Width', 0, '_' ) ),
                  thumbHeight = parseInt( coalesce( item, 0, 'ImageSets', 0, 'ImageSet', 0, 'SmallImage', 0, 'Height', 0, '_' ) );

              answers
              .push(
                {
                  type: 'article',
                  id: id,
                  title: ( price ? '[' + price + ']' : '' ) + title,
                  input_message_content: {
                    message_text: title + ( price ? '\n\nLowest Price: ' + price : '' ) + ( imageUrl ? '\n\n' + imageUrl : '' ),
                    parse_mode: 'HTML'
                  },
                  reply_markup: {
                    inline_keyboard: [
                      [{
                        text: 'Open in ' + endpoint.capitalize(),
                        url: url
                      }]
                    ],
                  },
                  url: url,
                  hide_url: false,
                  thumb_url: thumbUrl,
                  thumb_width: thumbWidth,
                  thumb_height: thumbHeight
                }
              );
            }

            bot
            .answerInlineQuery(
              message.id,
              answers
            );
          }
        }
      )
    }
  }
}

var coalesce = function ( arr, def ) {
    var i, max_i, ret = arr;

    for (i = 2, max_i = arguments.length; i < max_i; i++) {
        ret = ret[ arguments[i] ];
        if (ret === undefined) {
            ret = def;
            break;
        }
    }

    return ret;
}

var getUserOptions = function ( uid, cb ) {
  var ret = {};

  db
  .find(
    {
      userid: uid
    },
    function ( err, docs ) {
      if (!err)
        ret = docs[0];

      cb(ret);
    }
  )
}

var setUserOption = function ( uid, option, cb ) {
  var ret = 'Success! Option updated. /help',
      userOptions = {
        userid: uid
      },
      option = ( option ? option.split('=') : [] );

  if ( option.length == 2 ) {
    var key = option[0],
        value = ( option[1] ? option[1] : '' );

    userOptions[ key.toLowerCase() ] = value;

    db
    .update(
      {
        userid: uid,
      },
      userOptions,
      {
        upsert: true,
      },
      function (err, newDoc) {
        if (err)
          ret = 'Something went wrong. Please retry later. /help';

        cb(ret);
      }
    )
  } else {
    ret = 'Fail! Option syntax is not valid. /help';
    cb(ret);
  }
}<commit_msg>Better enhancement for help message<commit_after>// See http://stackoverflow.com/a/3291856
String.prototype.capitalize = function() {
  return this.charAt(0).toUpperCase() + this.slice(1);
}
// See https://github.com/yagop/node-telegram-bot-api
var TelegramBot = require('node-telegram-bot-api');

// See https://github.com/t3chnoboy/amazon-product-api
var amazon = require('amazon-product-api');

// See https://github.com/vkurchatkin/which-country
var wc = require('which-country');

// See https://github.com/louischatriot/nedb
var Datastore = require('nedb'),
    db = new Datastore({
      filename: 'datastore.db',
      autoload: true
    });

// List of supported Amazon endpoints
var amazonEndpoints = {
  'US' : 'webservices.amazon.com',
  'CA' : 'webservices.amazon.ca',
  'IT' : 'webservices.amazon.it',
  'DE' : 'webservices.amazon.de',
  'UK' : 'webservices.amazon.co.uk',
  'ES' : 'webservices.amazon.es',
  'FR' : 'webservices.amazon.fr'
};

// Telegram API Token
var token = process.env.TELEGRAM_API_TOKEN || '';

// Create the Bot
var bot = new TelegramBot(
  token,
  {
    webHook: {
      port: process.env.PORT || '3000'
    }
  }
);

// Listen on WebHooks
bot
.setWebHook(
  process.env.BASE_URL + '/' + process.env.WEBHOOK_TOKEN
);

// User is asking for help, or is geeting me for the first time
bot.onText(/\/help|\/start/, function (msg, match) {
  var chatId = msg.chat.id,
      resp = `
This Bot will help you to search your favourite Amazon products directly from here.
If you do not pass any {country code} into the inline query, a default assumption will be used.
Default fallback logic: location ( if available ) -> your setting ( if set ) -> US. The first that matches, is the winner.

You can control me by sending these commands:

---
/set COUNTRY={COUNTRY CODE} [ Supported list: {cc_list} ]

This option will set your default country amoung all your chats. If you need to change it, just run this command again.

Example: /set COUNTRY=CA
---
  `;

  resp.replace('{cc_list}', Object.keys(amazonEndpoints).join(',') );

  bot.sendMessage(chatId, resp);
});

// Save user preferences...
bot.onText(/\/set (.+)/, function (msg, match) {
  var chatId = msg.chat.id,
      userId = msg.from.id,
      option = match[1];

  setUserOption( userId, option, function ( resp ){
    bot.sendMessage(chatId, resp);
  });
});

// Once the user is searching...
bot
.on( 'inline_query', function ( message ){
  getUserOptions( message.from.id, function (options) {
    answerUser( message, options );
  })
});

var answerUser = function ( message, userOptions ) {
  if ( message.query ) {
    // Get the country where to query
    var query = message.query.split('@')[0],
        country = ( message.query.split('@')[1] || '').toUpperCase();

    if ( !country ) {
      // Detect user country if provided
      if ( message.location ) {
        country = wc([
          message.location.latitude,
          message.location.longitude
        ]);
      }

      // Detect if user set a default, update only if not find by the location
      if ( !country && 'country' in userOptions ) {
        country = userOptions.country;
      }

      // Force the Amazon.com search if no country given or detected
      if ( !country ) country = 'US';
    } else
      // Get only the first two letters and convert them to uppercase
      country = country.toUpperCase().substring(0,2)

    // If the country is given, always check if it's in the list
    if ( country in amazonEndpoints ) {

      // Create the Amazon Client
      var client = amazon.createClient({
        awsId: process.env.AMAZON_ACCESS_ID || '',
        awsSecret: process.env.AMAZON_SECRET_ACCESS_KEY || '',
        awsTag: process.env['AMAZON_ASSOCIATE_TAG_' + country] || ''
      });

      client
      .itemSearch(
        {
          keywords: query,
          searchIndex: 'All',
          responseGroup: 'Images,ItemAttributes,OfferSummary',
          domain: amazonEndpoints[ country ]
        },
        function (error, results) {
          if (error) {
            // Log the error
            console.log( error );
          } else {
            var answers = [],
                endpoint = amazonEndpoints[ country ].replace('webservices.','');

            for ( var k in results ) {
              var item = results[k],
                  id = coalesce( item, k, 'ASIN', 0 ),
                  price = coalesce( item, null, 'OfferSummary', 0, 'LowestNewPrice', 0, 'FormattedPrice', 0 ),
                  url = coalesce( item, 'https://' + endpoint, 'DetailPageURL', 0 ),
                  title = coalesce( item, 'No Title', 'ItemAttributes', 0, 'Title', 0 ),
                  imageUrl = coalesce( item, '', 'ImageSets', 0, 'ImageSet', 0, 'LargeImage', 0, 'URL', 0 ),
                  thumbUrl = coalesce( item, amazonEndpoints[ country ].replace('webservices.','https://'), 'ImageSets', 0, 'ImageSet', 0, 'SmallImage', 0, 'URL', 0 ),
                  thumbWidth = parseInt( coalesce( item, 0, 'ImageSets', 0, 'ImageSet', 0, 'SmallImage', 0, 'Width', 0, '_' ) ),
                  thumbHeight = parseInt( coalesce( item, 0, 'ImageSets', 0, 'ImageSet', 0, 'SmallImage', 0, 'Height', 0, '_' ) );

              answers
              .push(
                {
                  type: 'article',
                  id: id,
                  title: ( price ? '[' + price + ']' : '' ) + title,
                  input_message_content: {
                    message_text: title + ( price ? '\n\nLowest Price: ' + price : '' ) + ( imageUrl ? '\n\n' + imageUrl : '' ),
                    parse_mode: 'HTML'
                  },
                  reply_markup: {
                    inline_keyboard: [
                      [{
                        text: 'Open in ' + endpoint.capitalize(),
                        url: url
                      }]
                    ],
                  },
                  url: url,
                  hide_url: false,
                  thumb_url: thumbUrl,
                  thumb_width: thumbWidth,
                  thumb_height: thumbHeight
                }
              );
            }

            bot
            .answerInlineQuery(
              message.id,
              answers
            );
          }
        }
      )
    }
  }
}

var coalesce = function ( arr, def ) {
    var i, max_i, ret = arr;

    for (i = 2, max_i = arguments.length; i < max_i; i++) {
        ret = ret[ arguments[i] ];
        if (ret === undefined) {
            ret = def;
            break;
        }
    }

    return ret;
}

var getUserOptions = function ( uid, cb ) {
  var ret = {};

  db
  .find(
    {
      userid: uid
    },
    function ( err, docs ) {
      if (!err)
        ret = docs[0];

      cb(ret);
    }
  )
}

var setUserOption = function ( uid, option, cb ) {
  var ret = 'Success! Option updated. /help',
      userOptions = {
        userid: uid
      },
      option = ( option ? option.split('=') : [] );

  if ( option.length == 2 ) {
    var key = option[0],
        value = ( option[1] ? option[1] : '' );

    userOptions[ key.toLowerCase() ] = value;

    db
    .update(
      {
        userid: uid,
      },
      userOptions,
      {
        upsert: true,
      },
      function (err, newDoc) {
        if (err)
          ret = 'Something went wrong. Please retry later. /help';

        cb(ret);
      }
    )
  } else {
    ret = 'Fail! Option syntax is not valid. /help';
    cb(ret);
  }
}<|endoftext|>


<commit_before>var port = typeof( process.env.PORT ) == "undefined" ? 5000 : process.env.PORT;

var fs = require("fs");
var exec = require('child_process').exec
var wrench = require("wrench");

var zipper = require("node-native-zip");
var folder = require( "./folder" );
var AdmZip = require('adm-zip');
var unzip;

// To be determined later
var baseDir;
var fileName;
var fileData;
var isUpdateOnly = false; // Set when we're just looking to update the server to the most recent state of the repo and zip the directory

var isLocked = false;
var currentUser = null;
var commitMessage = null;

// This will hold the function that we're going to call next. It
// makes our very asynchronous code cleaner.
var nextStep = function() {};

console.log( "Opening socket on port " + port );
var io  = require( 'socket.io' ).listen(port+1);
var dl = require("delivery");

io.sockets.on('connection', function(socket){
	var delivery = dl.listen(socket);

	delivery.on( 'send.error', function( error ) {
		console.log( error );
		console.log( "send error: " + error );
	});

	delivery.on( 'send.start', function( filePackage ) {
		console.log(filePackage.name + " is being sent to the client.");
	});

	delivery.on('send.success', function(file){
		console.log('File successfully sent to client!');
	});

	console.log( "Socket connection" );

	socket.on( "requestTransfer", function( data ) {
		console.log( "transfer requested" );
		console.log( data );
		if( isLocked ) {
			emitError( "Transfer locked: server busy" );
			return;
		} else {
			currentUser = socket.id;
			baseDir = data.baseDir;
			commitMessage = data.commitMessage;

			io.sockets.socket( currentUser ).emit( "transferAccepted" );

			isLocked = true;
		}
	});

	socket.on( "requestHEAD", function( data ) {
		console.log( "update to HEAD requested" );

		var deliveryObj= {
			name: data.fileName,
			path: getOneFolderUp(data.baseDir) + data.fileName
		};

		console.log( deliveryObj );

		if( isLocked ) {
			emitError( "Transfer locked: server busy" );
			return;
		} else {
			console.log( "Checking out" );
			var child = exec('git checkout -- .', function (error, stdout, stderr) {
				console.log('stdout: ' + stdout);
				console.log('stderr: ' + stderr);

				if( error != null ) {
					emitError( error );
				} else {
					console.log( "pulling" );
					var child = exec('git pull', function (error, stdout, stderr) {
						console.log('stdout: ' + stdout);
						console.log('stderr: ' + stderr);

						if( error != null ) {
							emitError( error );
						} else {
							console.log( "Zipping " + data.baseDir );
							zipDirectory( data.baseDir, function() {
								console.log( "Zipped directory" );
								console.log( deliveryObj );
								try { delivery.send( deliveryObj ); }
								catch(err) { console.log( err ); }
							}); // end zip dir
						} // end pull success
					}); // end exec git pull
				} // end checkout success
			});	// end exec git checkout
		} // end if not locked
	}); // end on request HEAD

	delivery.on('receive.success',function(file){
		var fileNameWithoutPath = getFileNameFromPath( file.name );

		fileName = fileNameWithoutPath;

		// Create our temp directory if it doesn't exist already
		if( !dirExistsSync( "temp" ) ) {
			fs.mkdir( "temp" );
		}

		fs.writeFile( "temp/" + fileNameWithoutPath, file.buffer, function( err ) {
			if( err ) {
				console.log( 'File could not be saved: ' + err );
			} else {
				console.log( 'File ' + file.name + " saved" );
				startProcess();
			};
		});
	});
}); // end socket on Connection

function startProcess() {
	nextStep = gitCheckout;

	callNextStep();
} // end startProcess()

function processDone() {
	io.sockets.socket(currentUser).emit( "processDone" );
	isLocked = false;
	currentUser = null;
	commitMessage = null;
}

function callNextStep( error ) {
	if( typeof(error) == "undefined" || error == null )
		nextStep();
	else {
		emitError( error );
	}
} // end callNextStep()

function gitCheckout() {
	console.log( "Checking out back to HEAD" );
	nextStep = gitPullRebase;

	var child = exec('git checkout -- .', function (error, stdout, stderr) {
		console.log('stdout: ' + stdout);
		console.log('stderr: ' + stderr);

		if( error != null ) {
			callNextStep( stderr );
		} else {
			callNextStep( null );
		}
	});
} // end gitCheckout()

function gitPullRebase( clearAndPullOnly ) {
	console.log( "Pulling from remote" );
	if( clearAndPullOnly ) {
		nextStep = zipDirectory( baseDir, function() {
			console.log( "Zipped directory" );
		});
	} else {
		nextStep = deleteExistingFiles;
	}

	var child = exec('git pull origin master --rebase', function (error, stdout, stderr) {
		console.log('stdout: ' + stdout);
		console.log('stderr: ' + stderr);

		if( error != null ) {
			callNextStep( stderr );
		} else {
			callNextStep( null );
		}
	});
} // end gitPullRebase()

// REMOVE THE DIRECTORY RECURSIVELY (scary, I know)
function deleteExistingFiles() {
	console.log( "Deleting all files within " + baseDir );
	nextStep = copyIncomingFiles;

	if( baseDir.length < 6 ) {
		console.log( "ALMOST DELETED " + baseDir );
		emitError( "Base directory (" + baseDir + ") is too short, do you really want to delete that :/" );
	}

	// REMOVE THE DIRECTORY RECURSIVELY (scary, I know)
	wrench.rmdirRecursive( baseDir, callNextStep );
} // end deleteExistingFiles()

function copyIncomingFiles() {
	console.log( "Unzipping and copying incoming files into place" );
	nextStep = gitPush;

	try {
		unzip = new AdmZip( "./temp/" + fileName );
	} catch( err ) {
		console.log( "Couldn't open zipped directory: " + err );
	}

	// Extract all files
	unzip.extractAllTo( baseDir, true );

    callNextStep();
} // end copyIncomingFiles()

function gitCommit() {
	console.log( "Committing files to git" );

	if( typeof(commitMessage) == "undefined" )
		commitMessage = "Files changed using EasyGit";

	exec('git commit -m "' + commitMessage + '" -- ' + baseDir, function (error, stdout, stderr) {
		console.log('stdout: ' + stdout);
		console.log('stderr: ' + stderr);

		if( error != null ) {
			callNextStep( stderr );
		} else {
			callNextStep( null );
		}
	});
}

function gitPush() {
	console.log( "Pushing changes to git" );
	/*
	exec('git status', function (error, stdout, stderr) {
		console.log('stdout: ' + stdout);
		console.log('stderr: ' + stderr);
		if (error !== null) {
			console.log(error);
		} else {
			console.log( "Success!" );
			processDone();
		}
	});
	*/
	exec('git push origin master', function (error, stdout, stderr) {
		console.log('stdout: ' + stdout);
		console.log('stderr: ' + stderr);
		if (error !== null) {
			emitError(error);
		} else {
			console.log( "Success!" );
			processDone();
		}
	});
} // end gitPush()

function emitError( error ) {
	io.sockets.socket( currentUser ).emit( "transferError", {error: error} );
	console.log( "Error: " + error );

	isLocked = false;
	currentUser = null;
	commitMessage = null;
}

function dirExistsSync( d ) {
	try { fs.statSync( d ).isDirectory() }
	catch( er ) { return false }
} // end dirExistsSync()

function getFileNameFromPath( fullPath ) {
	var lastBackSlash = fullPath.lastIndexOf( "\\" ),
		lastForwardSlash = fullPath.lastIndexOf( "/" );

	var folderStart = lastBackSlash > lastForwardSlash ? lastBackSlash : lastForwardSlash;

	return fullPath.substring( folderStart + 1 );
}

function getBaseDirFromFilePath( filePath ) {
	var lastBackSlash = fullPath.lastIndexOf( "\\" ),
		lastForwardSlash = fullPath.lastIndexOf( "/" );

	var lastfolderStart = lastBackSlash > lastForwardSlash ? lastBackSlash : lastForwardSlash;

	return fullPath.substring( 0, lastfolderStart + 1 );
}

function zipDirectory( dir, callback ) {
	var archive = new zipper();

	console.log( "Staring to zip" );
	console.log( dir );

	// map all files in the approot thru this function
	folder.mapAllFiles(dir, function (path, stats, callback) {
		if( path.indexOf(".git") != -1 ) return callback();

		// Figure out the base directory for all of these files
		var baseDir = getFolderName(dir);

		var afterBaseIndex = path.indexOf(baseDir) /* + baseDir.length + 1*/;

		var callbackParams = {
			//name: path.replace(dir, "").substr(1),
			name: path.substring(afterBaseIndex, path.length),
			path: path
		};

		console.log( callbackParams );

		// prepare for the .addFiles function
		callback( callbackParams );
	}, function (err, data) {
		if (err) return callback(err);

		// add the files to the zip
		archive.addFiles(data, function (err) {
			if (err) return callback(err);

			// write the zip file
			console.log( "writing zip file to " + dir );
			fs.writeFile(dir + ".zip", archive.toBuffer(), function ( err ) {
				if (err) return callback(err);

				callback(null, dir + ".zip");
			});
		});
	});
} // end zipDirectory()

//////////////////////////////////////////////////////////////////////////
// Returns the folder from a full filepath
function getFolderName( fullPath ) {
	var lastBackSlash = fullPath.lastIndexOf( "\\" ),
		lastForwardSlash = fullPath.lastIndexOf( "/" ),
		isForwardSlash;

	// Figure out whether we're working with a forward or backward slash
	if( lastBackSlash > lastForwardSlash ) {
		lastSlash = lastBackSlash;
		isForwardSlash = false;
	} else {
		lastSlash = lastForwardSlash;
		isForwardSlash = true;
	}

	// Pull off any file thats on the end
	if( fullPath.indexOf(".") != -1 ) {
		fullPath= fullPath.substring( 0, lastSlash );
		lastSlash = isForwardSlash ? fullPath.lastIndexOf( "/" ) : fullPath.lastIndexOf( "\\" );
	}

	// Make sure the last slash isn't at the end of the string
	if( lastSlash == fullPath.length - 1 ) {
		fullPath= fullPath.substring( 0, fullPath.length - 1 );
		lastSlash = isForwardSlash ? fullPath.lastIndexOf( "/" ) : fullPath.lastIndexOf( "\\" );
	}

	return fullPath.substring( lastSlash + 1 );
} // end getFolderName()

function getOneFolderUp( folderPath ) {
	var folderName = getFolderName( folderPath );

	return folderPath.substring( 0, folderPath.indexOf(folderName) );
}<commit_msg>just use a normal git pull for the server<commit_after>var port = typeof( process.env.PORT ) == "undefined" ? 5000 : process.env.PORT;

var fs = require("fs");
var exec = require('child_process').exec
var wrench = require("wrench");

var zipper = require("node-native-zip");
var folder = require( "./folder" );
var AdmZip = require('adm-zip');
var unzip;

// To be determined later
var baseDir;
var fileName;
var fileData;
var isUpdateOnly = false; // Set when we're just looking to update the server to the most recent state of the repo and zip the directory

var isLocked = false;
var currentUser = null;
var commitMessage = null;

// This will hold the function that we're going to call next. It
// makes our very asynchronous code cleaner.
var nextStep = function() {};

console.log( "Opening socket on port " + port );
var io  = require( 'socket.io' ).listen(port+1);
var dl = require("delivery");

io.sockets.on('connection', function(socket){
	var delivery = dl.listen(socket);

	delivery.on( 'send.error', function( error ) {
		console.log( error );
		console.log( "send error: " + error );
	});

	delivery.on( 'send.start', function( filePackage ) {
		console.log(filePackage.name + " is being sent to the client.");
	});

	delivery.on('send.success', function(file){
		console.log('File successfully sent to client!');
	});

	console.log( "Socket connection" );

	socket.on( "requestTransfer", function( data ) {
		console.log( "transfer requested" );
		console.log( data );
		if( isLocked ) {
			emitError( "Transfer locked: server busy" );
			return;
		} else {
			currentUser = socket.id;
			baseDir = data.baseDir;
			commitMessage = data.commitMessage;

			io.sockets.socket( currentUser ).emit( "transferAccepted" );

			isLocked = true;
		}
	});

	socket.on( "requestHEAD", function( data ) {
		console.log( "update to HEAD requested" );

		var deliveryObj= {
			name: data.fileName,
			path: getOneFolderUp(data.baseDir) + data.fileName
		};

		console.log( deliveryObj );

		if( isLocked ) {
			emitError( "Transfer locked: server busy" );
			return;
		} else {
			console.log( "Checking out" );
			var child = exec('git checkout -- .', function (error, stdout, stderr) {
				console.log('stdout: ' + stdout);
				console.log('stderr: ' + stderr);

				if( error != null ) {
					emitError( error );
				} else {
					console.log( "pulling" );
					var child = exec('git pull', function (error, stdout, stderr) {
						console.log('stdout: ' + stdout);
						console.log('stderr: ' + stderr);

						if( error != null ) {
							emitError( error );
						} else {
							console.log( "Zipping " + data.baseDir );
							zipDirectory( data.baseDir, function() {
								console.log( "Zipped directory" );
								console.log( deliveryObj );
								try { delivery.send( deliveryObj ); }
								catch(err) { console.log( err ); }
							}); // end zip dir
						} // end pull success
					}); // end exec git pull
				} // end checkout success
			});	// end exec git checkout
		} // end if not locked
	}); // end on request HEAD

	delivery.on('receive.success',function(file){
		var fileNameWithoutPath = getFileNameFromPath( file.name );

		fileName = fileNameWithoutPath;

		// Create our temp directory if it doesn't exist already
		if( !dirExistsSync( "temp" ) ) {
			fs.mkdir( "temp" );
		}

		fs.writeFile( "temp/" + fileNameWithoutPath, file.buffer, function( err ) {
			if( err ) {
				console.log( 'File could not be saved: ' + err );
			} else {
				console.log( 'File ' + file.name + " saved" );
				startProcess();
			};
		});
	});
}); // end socket on Connection

function startProcess() {
	nextStep = gitCheckout;

	callNextStep();
} // end startProcess()

function processDone() {
	io.sockets.socket(currentUser).emit( "processDone" );
	isLocked = false;
	currentUser = null;
	commitMessage = null;
}

function callNextStep( error ) {
	if( typeof(error) == "undefined" || error == null )
		nextStep();
	else {
		emitError( error );
	}
} // end callNextStep()

function gitCheckout() {
	console.log( "Checking out back to HEAD" );
	nextStep = gitPullRebase;

	var child = exec('git checkout -- .', function (error, stdout, stderr) {
		console.log('stdout: ' + stdout);
		console.log('stderr: ' + stderr);

		if( error != null ) {
			callNextStep( stderr );
		} else {
			callNextStep( null );
		}
	});
} // end gitCheckout()

function gitPullRebase( clearAndPullOnly ) {
	console.log( "Pulling from remote" );
	if( clearAndPullOnly ) {
		nextStep = zipDirectory( baseDir, function() {
			console.log( "Zipped directory" );
		});
	} else {
		nextStep = deleteExistingFiles;
	}

	var child = exec('git pull', function (error, stdout, stderr) {
		console.log('stdout: ' + stdout);
		console.log('stderr: ' + stderr);

		if( error != null ) {
			callNextStep( stderr );
		} else {
			callNextStep( null );
		}
	});
} // end gitPullRebase()

// REMOVE THE DIRECTORY RECURSIVELY (scary, I know)
function deleteExistingFiles() {
	console.log( "Deleting all files within " + baseDir );
	nextStep = copyIncomingFiles;

	if( baseDir.length < 6 ) {
		console.log( "ALMOST DELETED " + baseDir );
		emitError( "Base directory (" + baseDir + ") is too short, do you really want to delete that :/" );
	}

	// REMOVE THE DIRECTORY RECURSIVELY (scary, I know)
	wrench.rmdirRecursive( baseDir, callNextStep );
} // end deleteExistingFiles()

function copyIncomingFiles() {
	console.log( "Unzipping and copying incoming files into place" );
	nextStep = gitPush;

	try {
		unzip = new AdmZip( "./temp/" + fileName );
	} catch( err ) {
		console.log( "Couldn't open zipped directory: " + err );
	}

	// Extract all files
	unzip.extractAllTo( baseDir, true );

    callNextStep();
} // end copyIncomingFiles()

function gitCommit() {
	console.log( "Committing files to git" );

	if( typeof(commitMessage) == "undefined" )
		commitMessage = "Files changed using EasyGit";

	exec('git commit -m "' + commitMessage + '" -- ' + baseDir, function (error, stdout, stderr) {
		console.log('stdout: ' + stdout);
		console.log('stderr: ' + stderr);

		if( error != null ) {
			callNextStep( stderr );
		} else {
			callNextStep( null );
		}
	});
}

function gitPush() {
	console.log( "Pushing changes to git" );
	/*
	exec('git status', function (error, stdout, stderr) {
		console.log('stdout: ' + stdout);
		console.log('stderr: ' + stderr);
		if (error !== null) {
			console.log(error);
		} else {
			console.log( "Success!" );
			processDone();
		}
	});
	*/
	exec('git push origin master', function (error, stdout, stderr) {
		console.log('stdout: ' + stdout);
		console.log('stderr: ' + stderr);
		if (error !== null) {
			emitError(error);
		} else {
			console.log( "Success!" );
			processDone();
		}
	});
} // end gitPush()

function emitError( error ) {
	io.sockets.socket( currentUser ).emit( "transferError", {error: error} );
	console.log( "Error: " + error );

	isLocked = false;
	currentUser = null;
	commitMessage = null;
}

function dirExistsSync( d ) {
	try { fs.statSync( d ).isDirectory() }
	catch( er ) { return false }
} // end dirExistsSync()

function getFileNameFromPath( fullPath ) {
	var lastBackSlash = fullPath.lastIndexOf( "\\" ),
		lastForwardSlash = fullPath.lastIndexOf( "/" );

	var folderStart = lastBackSlash > lastForwardSlash ? lastBackSlash : lastForwardSlash;

	return fullPath.substring( folderStart + 1 );
}

function getBaseDirFromFilePath( filePath ) {
	var lastBackSlash = fullPath.lastIndexOf( "\\" ),
		lastForwardSlash = fullPath.lastIndexOf( "/" );

	var lastfolderStart = lastBackSlash > lastForwardSlash ? lastBackSlash : lastForwardSlash;

	return fullPath.substring( 0, lastfolderStart + 1 );
}

function zipDirectory( dir, callback ) {
	var archive = new zipper();

	console.log( "Staring to zip" );
	console.log( dir );

	// map all files in the approot thru this function
	folder.mapAllFiles(dir, function (path, stats, callback) {
		if( path.indexOf(".git") != -1 ) return callback();

		// Figure out the base directory for all of these files
		var baseDir = getFolderName(dir);

		var afterBaseIndex = path.indexOf(baseDir) /* + baseDir.length + 1*/;

		var callbackParams = {
			//name: path.replace(dir, "").substr(1),
			name: path.substring(afterBaseIndex, path.length),
			path: path
		};

		console.log( callbackParams );

		// prepare for the .addFiles function
		callback( callbackParams );
	}, function (err, data) {
		if (err) return callback(err);

		// add the files to the zip
		archive.addFiles(data, function (err) {
			if (err) return callback(err);

			// write the zip file
			console.log( "writing zip file to " + dir );
			fs.writeFile(dir + ".zip", archive.toBuffer(), function ( err ) {
				if (err) return callback(err);

				callback(null, dir + ".zip");
			});
		});
	});
} // end zipDirectory()

//////////////////////////////////////////////////////////////////////////
// Returns the folder from a full filepath
function getFolderName( fullPath ) {
	var lastBackSlash = fullPath.lastIndexOf( "\\" ),
		lastForwardSlash = fullPath.lastIndexOf( "/" ),
		isForwardSlash;

	// Figure out whether we're working with a forward or backward slash
	if( lastBackSlash > lastForwardSlash ) {
		lastSlash = lastBackSlash;
		isForwardSlash = false;
	} else {
		lastSlash = lastForwardSlash;
		isForwardSlash = true;
	}

	// Pull off any file thats on the end
	if( fullPath.indexOf(".") != -1 ) {
		fullPath= fullPath.substring( 0, lastSlash );
		lastSlash = isForwardSlash ? fullPath.lastIndexOf( "/" ) : fullPath.lastIndexOf( "\\" );
	}

	// Make sure the last slash isn't at the end of the string
	if( lastSlash == fullPath.length - 1 ) {
		fullPath= fullPath.substring( 0, fullPath.length - 1 );
		lastSlash = isForwardSlash ? fullPath.lastIndexOf( "/" ) : fullPath.lastIndexOf( "\\" );
	}

	return fullPath.substring( lastSlash + 1 );
} // end getFolderName()

function getOneFolderUp( folderPath ) {
	var folderName = getFolderName( folderPath );

	return folderPath.substring( 0, folderPath.indexOf(folderName) );
}<|endoftext|>


<commit_before>/*
 * Copyright (c) 2013, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE.txt file for terms.
 */

/*jslint nomen:true, node:true */

"use strict";

var libfs = require('fs'),
    libpath = require('path'),
    HB = require('yui/handlebars').Handlebars,
    description = require('../package.json').description;

function PluginClass(config) {

    config = config || {};
    config.handlebars = config.handlebars || HB;

    this.describe = {
        summary: description,
        extensions: ['hb', 'handlebars', 'hbs'],
        options: config
    };

}

PluginClass.prototype = {

    nameParser: function (source_path) {
        return libpath.basename(source_path, libpath.extname(source_path));
    },

    partialsParser: function (source) {
        var parsed = this.describe.options.handlebars.parse(source),
            partials = [];

        function walk(program) {
            if (program && program.statements) {
                program.statements.forEach(function (st) {
                    if (st.type === 'partial' && st.partialName.name) {
                        partials.push(st.partialName.name);
                    } else if (st.program || st.inverse) {
                        if (st.program){
                            // collecting partials from sub programs
                            walk(st.program);
                        }
                        if (st.inverse){
                            // collecting partials from sub programs in conditional branches
                            walk(st.inverse);
                        }
                    }
                });
            }
        }
        // collecting partials from the parsed program
        walk(parsed);

        return partials;
    },

    fileUpdated: function (evt, api) {
        var self = this,
            bundle = evt.bundle,
            options = this.describe.options,
            handlebars = this.describe.options.handlebars,
            file = evt.file,
            source_path = file.fullPath,
            bundleName = file.bundleName,
            templateName = this.nameParser(source_path),
            moduleName = bundleName + '-template-' + templateName,
            destination_path = moduleName + '.js',
            format = this.describe.options.format;

        return api.promise(function (fulfill, reject) {

            var source = libfs.readFileSync(source_path, 'utf8'),
                precompiled,
                compiled,
                partials;

            try {
                partials = self.partialsParser(source);
                precompiled = handlebars.precompile(source, options);
                compiled = handlebars.compile(source, options);
            } catch (e) {
                throw new Error('Error parsing handlebars template: ' +
                        file.relativePath + '. ' + e);
            }

            // provisioning the template entries for server side use
            // in a form of a compiled function
            bundle.template = bundle.template || {};
            bundle.template[templateName] = function (data) {
                // this is to pipe all available templates in the
                // same bundle in a form of partials
                return compiled.apply(this, [data, {
                    partials: bundle.template
                }]);
            };

            if (format) {
                // trying to write the destination file which will fulfill or reject the initial promise
                api.writeFileInBundle(bundleName, destination_path,
                    require('./formats/' + format)(bundleName, templateName, moduleName, precompiled, partials))
                    .then(fulfill, reject);
            } else {
                fulfill();
            }

        });

    }

};

module.exports = PluginClass;
<commit_msg>Add custom prefix option<commit_after>/*
 * Copyright (c) 2013, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE.txt file for terms.
 */

/*jslint nomen:true, node:true */

"use strict";

var libfs = require('fs'),
    libpath = require('path'),
    HB = require('yui/handlebars').Handlebars,
    description = require('../package.json').description;

function PluginClass(config) {

    config = config || {};
    config.handlebars = config.handlebars || HB;

    this.describe = {
        summary: description,
        extensions: ['hb', 'handlebars', 'hbs'],
        options: config
    };

}

PluginClass.prototype = {

    nameParser: function (source_path) {
        return libpath.basename(source_path, libpath.extname(source_path));
    },

    partialsParser: function (source) {
        var parsed = this.describe.options.handlebars.parse(source),
            partials = [];

        function walk(program) {
            if (program && program.statements) {
                program.statements.forEach(function (st) {
                    if (st.type === 'partial' && st.partialName.name) {
                        partials.push(st.partialName.name);
                    } else if (st.program || st.inverse) {
                        if (st.program){
                            // collecting partials from sub programs
                            walk(st.program);
                        }
                        if (st.inverse){
                            // collecting partials from sub programs in conditional branches
                            walk(st.inverse);
                        }
                    }
                });
            }
        }
        // collecting partials from the parsed program
        walk(parsed);

        return partials;
    },

    fileUpdated: function (evt, api) {
        var self = this,
            bundle = evt.bundle,
            options = this.describe.options,
            handlebars = this.describe.options.handlebars,
            file = evt.file,
            source_path = file.fullPath,
            bundleName = file.bundleName,
            prefix = this.describe.options.prefix || (bundleName + '-template-'),
            templateName = this.nameParser(source_path),
            moduleName = prefix + templateName,
            destination_path = moduleName + '.js',
            format = this.describe.options.format;
        return api.promise(function (fulfill, reject) {

            var source = libfs.readFileSync(source_path, 'utf8'),
                precompiled,
                compiled,
                partials;

            try {
                partials = self.partialsParser(source);
                precompiled = handlebars.precompile(source, options);
                compiled = handlebars.compile(source, options);
            } catch (e) {
                throw new Error('Error parsing handlebars template: ' +
                        file.relativePath + '. ' + e);
            }

            // provisioning the template entries for server side use
            // in a form of a compiled function
            bundle.template = bundle.template || {};
            bundle.template[templateName] = function (data) {
                // this is to pipe all available templates in the
                // same bundle in a form of partials
                return compiled.apply(this, [data, {
                    partials: bundle.template
                }]);
            };

            if (format) {
                // trying to write the destination file which will fulfill or reject the initial promise
                api.writeFileInBundle(bundleName, destination_path,
                    require('./formats/' + format)(bundleName, templateName, moduleName, precompiled, partials))
                    .then(fulfill, reject);
            } else {
                fulfill();
            }

        });

    }

};

module.exports = PluginClass;
<|endoftext|>


<commit_before>/**
 * Web Actions polyfill.
 * Author: Matt Giuca <mgiuca@chromium.org>
 *
 * Implements a (partial) Web Actions API for demonstration purposes. Note: This
 * API, by design, does things that aren't possible in a polyfill, so this will
 * be broken without specific browser hacks. All work-in-progress; don't get too
 * excited about it.
 *
 * Note: The requester needs to set navigator.webActions.polyfillHandlerUrl to a
 * valid handler URL before calling performAction. This is a temporary
 * requirement of the polyfill and won't be part of the final API.
 */
"use strict";

(function() {

// Polyfill Cache.addAll.
// Not necessary in Chrome 45 with --enable-experimental-web-platform-features.
if (Cache.prototype.addAll === undefined) {
  Cache.prototype.addAll = function(urls) {
    return Promise.all(urls.map(url => this.add(url)));
  }
}

// A base class that implements the EventTarget interface.
class CustomEventTarget {
  constructor() {
    // Map from event type to list of listeners.
    this._listeners = {};
  }

  addEventListener(type, listener, useCapture) {
    var listeners = this._listeners;
    var listeners_of_type = listeners[type];
    if (listeners_of_type === undefined) {
      listeners[type] = listeners_of_type = [];
    }

    for (var i = 0; i < listeners_of_type.length; i++) {
      if (listeners_of_type[i] === listener)
        return;
    }

    listeners_of_type.push(listener);
  }

  removeEventListener(type, listener, useCapture) {
    var listeners = this._listeners;
    var listeners_of_type = listeners[type];
    if (listeners_of_type === undefined) {
      listeners[type] = listeners_of_type = [];
    }

    for (var i = 0; i < listeners_of_type.length; i++) {
      if (listeners_of_type[i] === listener) {
        listeners_of_type.splice(i, 1);

        if (listeners_of_type.length == 0)
          delete listeners[type];

        return;
      }
    }
  }

  dispatchEvent(evt) {
    var listeners = this._listeners;
    var listeners_of_type = listeners[evt.type];
    if (listeners_of_type === undefined) {
      listeners[evt.type] = listeners_of_type = [];
    }

    for (var i = 0; i < listeners_of_type.length; i++) {
      var listener = listeners_of_type[i];
      if (listener.handleEvent !== undefined) {
        listener.handleEvent(evt);
      } else {
        listener.call(evt.target, evt);
      }
    }
  }
}

// An Action is an object representing a web action in flight.
class Action extends CustomEventTarget {
  constructor(verb, data) {
    super();
    this.verb = verb;
    this.data = data;
  }
}

// A map from origin strings to CrossOriginServiceWorkerClient objects.
// Allows communication to a client based on the origin.
var clientMap = new Map;

// Polyfill Navigator.webActions.
// The prototype of |navigator| is Navigator in normal pages, WorkerNavigator in
// Web Workers. Support either case.
var navigator_proto =
    (self.WorkerNavigator !== undefined ? WorkerNavigator : Navigator)
        .prototype;
if (navigator_proto.webActions === undefined) {
  var webActions = {};
  navigator_proto.webActions = webActions;

  // The URL of the handler to send requests to. The final API will have the
  // user agent let the user choose a handler from a registered list. For now,
  // we just let the client specify its URL by setting this variable.
  webActions.polyfillHandlerUrl = null;

  // ActionEvent is only available when the global scope is a
  // ServiceWorkerGlobalScope.
  if (self.ExtendableEvent !== undefined) {
    webActions.ActionEvent = class extends ExtendableEvent {
      constructor(action) {
        super('action');
        this.action = action;
        // Note: These seem redundant, but I think in the final API, Action's
        // fields will be opaque, so we'll want to expose these in ActionEvent.
        this.verb = action.verb;
        this.data = action.data;
      }
    };
  }

  webActions.RequesterAction = class extends Action {
    constructor(verb, data, port) {
      super(verb, data);
      this.port = port;
    }
  }

  webActions.HandlerAction = class extends Action {
    // |client| is a CrossOriginServiceWorkerClient that this action belongs to.
    constructor(verb, data, client) {
      super(verb, data);
      this.client = client;
    }
  };

  // Performs an action with a given |verb| and |data|. Returns a
  // Promise<Action> with an action object allowing further interaction with the
  // handler. Fails with AbortError if a connection could not be made.
  webActions.performAction = function(verb, data) {
    // Get the URL of the handler to connect to. For now, this is just a fixed
    // URL set by the client.
    var handlerUrl = webActions.polyfillHandlerUrl;
    if (handlerUrl === null) {
      throw new Error(
          'You need to set navigator.webActions.polyfillHandlerUrl ' +
          '(temporary requirement of the polyfill only).');
    }

    return new Promise((resolve, reject) => {
      // Connect to the handler.
      navigator.services.connect(handlerUrl)
          .then(port => {
            var action = new webActions.RequesterAction(verb, data, port);

            // Send the verb and data payload to the handler.
            var message = {'type': 'action', 'verb': verb, 'data': data};
            port.postMessage(message);

            resolve(action);
          }, err => reject(err))
    });
  };
}

// Called when a message is received (on both the host and client).
// |client| is a CrossOriginServiceWorkerClient on the host; null on the client.
function onMessageReceived(data, client) {
  if (data.type == 'action') {
    if (webActions.ActionEvent === undefined)
      throw new Error('Web Actions requests must go to a service worker.');

    var action = new webActions.HandlerAction(data.verb, data.data, client);

    // Forward the event as an 'action' event to the global object.
    var actionEvent = new webActions.ActionEvent(action);
    self.dispatchEvent(actionEvent);
  } else {
    console.log('Received unknown message:', data);
  }
}

// XXX: The 'connect' event on navigator.services is the currently specified way
// for the host to receive a connection, but in Chrome 45 it receives
// 'crossoriginconnect' instead (see below).
/*
navigator.services.addEventListener('connect', event => {
  console.log('navigator.services: Received connect event for ' +
              event.targetURL + ' from ' + event.origin);
  event.respondWith({accept: true, name: 'the_connecter'})
      .then(port => port.postMessage('You are connected!'));
});
*/

// XXX: The 'message' event on navigator.services is the specified way to
// receive messages on both ends. In Chrome 45, only the client receives
// messages with this event. The host receives 'crossoriginmessage' instead (see
// below).
navigator.services.addEventListener('message', event => {
  onMessageReceived(event.data);
});

// XXX In Chrome 45, the host's global object receives 'crossoriginconnect' and
// 'crossoriginmessage' events, instead of the above. (This is from an older
// version of the spec.)
self.addEventListener('crossoriginconnect', event => {
  console.log('global: Received crossoriginconnection on self:', event);
  event.acceptConnection(true);
  var client = event.client;
  clientMap.set(client.origin, client);
  client.postMessage('You are connected!');
});

self.addEventListener('crossoriginmessage', event => {
  var origin = event.origin;
  if (!clientMap.has(event.origin))
    throw new Error('Received message from unknown origin ' + origin);

  var client = clientMap.get(event.origin);
  onMessageReceived(event.data, client);
});

})();
<commit_msg>HandlerAction: Added update() method.<commit_after>/**
 * Web Actions polyfill.
 * Author: Matt Giuca <mgiuca@chromium.org>
 *
 * Implements a (partial) Web Actions API for demonstration purposes. Note: This
 * API, by design, does things that aren't possible in a polyfill, so this will
 * be broken without specific browser hacks. All work-in-progress; don't get too
 * excited about it.
 *
 * Note: The requester needs to set navigator.webActions.polyfillHandlerUrl to a
 * valid handler URL before calling performAction. This is a temporary
 * requirement of the polyfill and won't be part of the final API.
 */
"use strict";

(function() {

// Polyfill Cache.addAll.
// Not necessary in Chrome 45 with --enable-experimental-web-platform-features.
if (Cache.prototype.addAll === undefined) {
  Cache.prototype.addAll = function(urls) {
    return Promise.all(urls.map(url => this.add(url)));
  }
}

// A base class that implements the EventTarget interface.
class CustomEventTarget {
  constructor() {
    // Map from event type to list of listeners.
    this._listeners = {};
  }

  addEventListener(type, listener, useCapture) {
    var listeners = this._listeners;
    var listeners_of_type = listeners[type];
    if (listeners_of_type === undefined) {
      listeners[type] = listeners_of_type = [];
    }

    for (var i = 0; i < listeners_of_type.length; i++) {
      if (listeners_of_type[i] === listener)
        return;
    }

    listeners_of_type.push(listener);
  }

  removeEventListener(type, listener, useCapture) {
    var listeners = this._listeners;
    var listeners_of_type = listeners[type];
    if (listeners_of_type === undefined) {
      listeners[type] = listeners_of_type = [];
    }

    for (var i = 0; i < listeners_of_type.length; i++) {
      if (listeners_of_type[i] === listener) {
        listeners_of_type.splice(i, 1);

        if (listeners_of_type.length == 0)
          delete listeners[type];

        return;
      }
    }
  }

  dispatchEvent(evt) {
    var listeners = this._listeners;
    var listeners_of_type = listeners[evt.type];
    if (listeners_of_type === undefined) {
      listeners[evt.type] = listeners_of_type = [];
    }

    for (var i = 0; i < listeners_of_type.length; i++) {
      var listener = listeners_of_type[i];
      if (listener.handleEvent !== undefined) {
        listener.handleEvent(evt);
      } else {
        listener.call(evt.target, evt);
      }
    }
  }
}

// An Action is an object representing a web action in flight.
class Action extends CustomEventTarget {
  constructor(verb, data) {
    super();
    this.verb = verb;
    this.data = data;
  }
}

// A map from origin strings to CrossOriginServiceWorkerClient objects.
// Allows communication to a client based on the origin.
var clientMap = new Map;

// Polyfill Navigator.webActions.
// The prototype of |navigator| is Navigator in normal pages, WorkerNavigator in
// Web Workers. Support either case.
var navigator_proto =
    (self.WorkerNavigator !== undefined ? WorkerNavigator : Navigator)
        .prototype;
if (navigator_proto.webActions === undefined) {
  var webActions = {};
  navigator_proto.webActions = webActions;

  // The URL of the handler to send requests to. The final API will have the
  // user agent let the user choose a handler from a registered list. For now,
  // we just let the client specify its URL by setting this variable.
  webActions.polyfillHandlerUrl = null;

  // ActionEvent is only available when the global scope is a
  // ServiceWorkerGlobalScope.
  if (self.ExtendableEvent !== undefined) {
    webActions.ActionEvent = class extends ExtendableEvent {
      constructor(action) {
        super('action');
        this.action = action;
        // Note: These seem redundant, but I think in the final API, Action's
        // fields will be opaque, so we'll want to expose these in ActionEvent.
        this.verb = action.verb;
        this.data = action.data;
      }
    };
  }

  webActions.RequesterAction = class extends Action {
    constructor(verb, data, port) {
      super(verb, data);
      this.port = port;
    }
  }

  webActions.HandlerAction = class extends Action {
    // |client| is a CrossOriginServiceWorkerClient that this action belongs to.
    constructor(verb, data, client) {
      super(verb, data);
      this.client = client;
    }

    // Sends an updated version of the data payload associated with this action
    // back to the requester. This may be called multiple times per action, but
    // should send a complete copy of the data on each call (this is not a
    // stream protocol).
    update(data) {
      var message = {'type': 'update', 'data': data};
      this.client.postMessage(message);
    }
  };

  // Performs an action with a given |verb| and |data|. Returns a
  // Promise<Action> with an action object allowing further interaction with the
  // handler. Fails with AbortError if a connection could not be made.
  webActions.performAction = function(verb, data) {
    // Get the URL of the handler to connect to. For now, this is just a fixed
    // URL set by the client.
    var handlerUrl = webActions.polyfillHandlerUrl;
    if (handlerUrl === null) {
      throw new Error(
          'You need to set navigator.webActions.polyfillHandlerUrl ' +
          '(temporary requirement of the polyfill only).');
    }

    return new Promise((resolve, reject) => {
      // Connect to the handler.
      navigator.services.connect(handlerUrl)
          .then(port => {
            var action = new webActions.RequesterAction(verb, data, port);

            // Send the verb and data payload to the handler.
            var message = {'type': 'action', 'verb': verb, 'data': data};
            port.postMessage(message);

            resolve(action);
          }, err => reject(err))
    });
  };
}

// Called when a message is received (on both the host and client).
// |client| is a CrossOriginServiceWorkerClient on the host; null on the client.
function onMessageReceived(data, client) {
  if (data.type == 'action') {
    if (webActions.ActionEvent === undefined)
      throw new Error('Web Actions requests must go to a service worker.');

    var action = new webActions.HandlerAction(data.verb, data.data, client);

    // Forward the event as an 'action' event to the global object.
    var actionEvent = new webActions.ActionEvent(action);
    self.dispatchEvent(actionEvent);
  } else {
    console.log('Received unknown message:', data);
  }
}

// XXX: The 'connect' event on navigator.services is the currently specified way
// for the host to receive a connection, but in Chrome 45 it receives
// 'crossoriginconnect' instead (see below).
/*
navigator.services.addEventListener('connect', event => {
  console.log('navigator.services: Received connect event for ' +
              event.targetURL + ' from ' + event.origin);
  event.respondWith({accept: true, name: 'the_connecter'})
      .then(port => port.postMessage('You are connected!'));
});
*/

// XXX: The 'message' event on navigator.services is the specified way to
// receive messages on both ends. In Chrome 45, only the client receives
// messages with this event. The host receives 'crossoriginmessage' instead (see
// below).
navigator.services.addEventListener('message', event => {
  onMessageReceived(event.data);
});

// XXX In Chrome 45, the host's global object receives 'crossoriginconnect' and
// 'crossoriginmessage' events, instead of the above. (This is from an older
// version of the spec.)
self.addEventListener('crossoriginconnect', event => {
  console.log('global: Received crossoriginconnection on self:', event);
  event.acceptConnection(true);
  var client = event.client;
  clientMap.set(client.origin, client);
  client.postMessage('You are connected!');
});

self.addEventListener('crossoriginmessage', event => {
  var origin = event.origin;
  if (!clientMap.has(event.origin))
    throw new Error('Received message from unknown origin ' + origin);

  var client = clientMap.get(event.origin);
  onMessageReceived(event.data, client);
});

})();
<|endoftext|>


<commit_before>//librosRUM Web Server

// Import module dependencies
var express = require('express');
var app = express();
var http = require('http');
var path = require('path');
var passport = require('passport');
var TwitterStrategy = require('passport-twitter').Strategy;
var FacebookStrategy = require('passport-facebook').Strategy;
var db = require('./utilities/database');
var RedisStore = require('connect-redis')(express);
var redisClient = require('redis').createClient(process.env.REDIS_PORT, process.env.REDIS_HOST);
  	redisClient.auth(process.env.REDIS_PASSWORD, function(err) {
  		if(err) console.log(err);
    	console.log('Redis client connected');
  	});

// Import configurations data

// Function to serialize users
passport.serializeUser(function(user, done){
	done(null, user.id)
});

passport.deserializeUser(function(id, done){
	db.Users.findOne(id, function(err, user){
		done(err, user);
	});
});

//Twitter Strategy
passport.use(new TwitterStrategy({
	consumerKey: process.env.TWITTER_KEY,
	consumerSecret: process.env.TWITTER_SECRET,
	callbackURL:"/auth/twitter/callback",
	},
	function(token, tokenSecret, profile, done){
		db.Users.findOne({providerID: profile.id}, function(err, user){
			if(user){
				done(null, user);
			}
			else{
				var newUser = new db.Users({
					provider: 'twitter',
					username: profile.username,
					name: profile.displayName,
					providerID: profile.id,
					oauthToken: token,
					created: Date.now(),
					email : "",
					phone: "",
					banned: false
				}).save(function (err, newUser){
					if(err) console.log(err);
					done(null, newUser);
				});
			}
		});
	}
));

//Facebook Passport Strategy
// passport.use(new FacebookStrategy({
// 	clientID: config.facebook.id,
// 	clientSecret: config.facebook.secret,
// 	callbackURL: "/auth/facebook/callback"
// 	},
// 	function(accessToken, refreshToken, profile, done){
// 		db.Users.findOne({customID: 'facebook:' + profile.id}, function(err, user){
// 			console.log(user);
// 			if(user){
// 				done(null,user);
// 			}
// 			else{
// 				var newUser = new db.Users({
// 					provider: 'facebook',
// 					username: profile.username,
// 					name: profile.displayName,
// 					providerID: profile.id,
// 					oauthToken: token,
// 					created: Date.now(),
// 					email : "",
// 					phone: "",
// 					banned: false
// 				}).save(function (err, newUser){
// 					if(err) console.log(err);
// 					done(null, newUser);
// 				});
// 			}
// 		});
// 	}
// ));

//server initialization

//server configuration
app.configure(function(){
	app.set('port', process.env.PORT || 5000);
	app.set('views', __dirname + '/views');
	app.set('view engine', 'jade');
	app.use(express.favicon(__dirname + '/public/img/favicon.ico'));
	app.use(express.logger('dev'));
	app.use(express.bodyParser());
	app.use(express.cookieParser());
	app.use(express.session({ secret: process.env.SECRET, cookie: {maxAge: 12960000000}, store: new RedisStore({client:redisClient})}));
	// app.use(express.session({ secret: config.secret, cookie: {maxAge: 12960000000} }));
	app.use(express.methodOverride());
	app.use(passport.initialize());
	app.use(passport.session());
	app.use(express.static(path.join(__dirname, 'public')));
	app.use('/single_view', express.static(__dirname + '/public'));
	app.use(app.router);
});

app.configure('development', function(){
	app.use(express.errorHandler());
});

//import of routes
require('./utilities/routes.js')(app, express);

//
http.createServer(app).listen(app.get('port'), function(){
	console.log("Express server listening on port " + app.get('port'));
});
<commit_msg>facebook auth<commit_after>//librosRUM Web Server

// Import module dependencies
var express = require('express');
var app = express();
var http = require('http');
var path = require('path');
var passport = require('passport');
var TwitterStrategy = require('passport-twitter').Strategy;
var FacebookStrategy = require('passport-facebook').Strategy;
var db = require('./utilities/database');
var RedisStore = require('connect-redis')(express);
var redisClient = require('redis').createClient(process.env.REDIS_PORT, process.env.REDIS_HOST);
  	redisClient.auth(process.env.REDIS_PASSWORD, function(err) {
  		if(err) console.log(err);
    	console.log('Redis client connected');
  	});

// Import configurations data

// Function to serialize users
passport.serializeUser(function(user, done){
	done(null, user.id)
});

passport.deserializeUser(function(id, done){
	db.Users.findOne(id, function(err, user){
		done(err, user);
	});
});

//Twitter Strategy
passport.use(new TwitterStrategy({
	consumerKey: process.env.TWITTER_KEY,
	consumerSecret: process.env.TWITTER_SECRET,
	callbackURL:"/auth/twitter/callback",
	},
	function(token, tokenSecret, profile, done){
		db.Users.findOne({providerID: profile.id}, function(err, user){
			if(user){
				done(null, user);
			}
			else{
				var newUser = new db.Users({
					provider: 'twitter',
					username: profile.username,
					name: profile.displayName,
					providerID: profile.id,
					oauthToken: token,
					created: Date.now(),
					email : "",
					phone: "",
					banned: false
				}).save(function (err, newUser){
					if(err) console.log(err);
					done(null, newUser);
				});
			}
		});
	}
));

//Facebook Passport Strategy
passport.use(new FacebookStrategy({
	clientID: process.env.FACEBOOK_ID,
	clientSecret: process.env.FACEBOOK_SECRET,
	callbackURL: "/auth/facebook/callback"
	},
	function(accessToken, refreshToken, profile, done){
		db.Users.findOne({customID: 'facebook:' + profile.id}, function(err, user){
			console.log(user);
			if(user){
				done(null,user);
			}
			else{
				var newUser = new db.Users({
					provider: 'facebook',
					username: profile.username,
					name: profile.displayName,
					providerID: profile.id,
					oauthToken: token,
					created: Date.now(),
					email : "",
					phone: "",
					banned: false
				}).save(function (err, newUser){
					if(err) console.log(err);
					done(null, newUser);
				});
			}
		});
	}
));

//server initialization

//server configuration
app.configure(function(){
	app.set('port', process.env.PORT || 5000);
	app.set('views', __dirname + '/views');
	app.set('view engine', 'jade');
	app.use(express.favicon(__dirname + '/public/img/favicon.ico'));
	app.use(express.logger('dev'));
	app.use(express.bodyParser());
	app.use(express.cookieParser());
	app.use(express.session({ secret: process.env.SECRET, cookie: {maxAge: 12960000000}, store: new RedisStore({client:redisClient})}));
	// app.use(express.session({ secret: config.secret, cookie: {maxAge: 12960000000} }));
	app.use(express.methodOverride());
	app.use(passport.initialize());
	app.use(passport.session());
	app.use(express.static(path.join(__dirname, 'public')));
	app.use('/single_view', express.static(__dirname + '/public'));
	app.use(app.router);
});

app.configure('development', function(){
	app.use(express.errorHandler());
});

//import of routes
require('./utilities/routes.js')(app, express);

//
http.createServer(app).listen(app.get('port'), function(){
	console.log("Express server listening on port " + app.get('port'));
});
<|endoftext|>


<commit_before>export default {
  install(Vue, { store }) {
    const { languages } = store.getters

    Vue.prototype.$i18n = {
      /**
       * @param {string}      key  Lookup key for language file
       * @param {object|null} args named arguments for the
       */
      str(key, args = {}) {
        let str
        let data = languages[store.getters.language]
        if (!data || !data[key]) {
          // fallback to English
          data = languages['en']
        }

        // Safeguard to ensure data is present
        if (!data || !data[key]) {
          return key
        }

        // set str
        str = data[key]

        // process vars
        const re = /(\:(\w+)(\=[^\:]+)?\:)/
        let matches
        while ((matches = re.exec(str)) !== null) {
          str = str.replace(matches[0], args[matches[2]] || matches[3] || matches[2])
        }

        // finish
        return str
      },

      /* istanbul ignore next */
      load() {
        return new Promise(resolve => {
          switch (store.getters.language) {
            case 'hb':
              require(['~/lang/en.js', '~/lang/hb.js'], (en, hb) => {
                store.commit('loadLanguage', { key: 'en', data: en })
                store.commit('loadLanguage', { key: 'hb', data: hb })
                resolve()
              })
              break
            case 'de':
              require(['~/lang/en.js', '~/lang/de'], (en, de) => {
                store.commit('loadLanguage', { key: 'en', data: en })
                store.commit('loadLanguage', { key: 'de', data: de })
                resolve()
              })
              break
            default:
              require(['~/lang/en.js'], en => {
                store.commit('loadLanguage', { key: 'en', data: en })
                resolve()
              })
          }
        })
      },
    }
  },
}
<commit_msg>move istanbul line appropriately<commit_after>export default {
  install(Vue, { store }) {
    const { languages } = store.getters

    Vue.prototype.$i18n = {
      /**
       * @param {string}      key  Lookup key for language file
       * @param {object|null} args named arguments for the
       */
      str(key, args = {}) {
        let str
        let data = languages[store.getters.language]
        if (!data || !data[key]) {
          // fallback to English
          data = languages['en']
        }

        // Safeguard to ensure data is present
        if (!data || !data[key]) {
          return key
        }

        // set str
        str = data[key]

        // process vars
        const re = /(\:(\w+)(\=[^\:]+)?\:)/
        let matches
        while ((matches = re.exec(str)) !== null) {
          str = str.replace(matches[0], args[matches[2]] || matches[3] || matches[2])
        }

        // finish
        return str
      },

      load() {
        /* istanbul ignore next */
        return new Promise(resolve => {
          switch (store.getters.language) {
            case 'hb':
              require(['~/lang/en.js', '~/lang/hb.js'], (en, hb) => {
                store.commit('loadLanguage', { key: 'en', data: en })
                store.commit('loadLanguage', { key: 'hb', data: hb })
                resolve()
              })
              break
            case 'de':
              require(['~/lang/en.js', '~/lang/de'], (en, de) => {
                store.commit('loadLanguage', { key: 'en', data: en })
                store.commit('loadLanguage', { key: 'de', data: de })
                resolve()
              })
              break
            default:
              require(['~/lang/en.js'], en => {
                store.commit('loadLanguage', { key: 'en', data: en })
                resolve()
              })
          }
        })
      },
    }
  },
}
<|endoftext|>