<commit_before>/** @file This file contains the scripts used when LabelMe starts up. */

/** Main entry point for the annotation tool. */
function StartupLabelMe() {
  console.time('startup');

  // Check browser:
  GetBrowserInfo();
  if(IsNetscape() || (IsMicrosoft() && (bversion>=4.5)) || IsSafari() || IsChrome()) {
    // Write "start up" messages:
    WriteLogMsg('*start_loading');
    console.log('LabelMe: starting up...');

    // Initialize global variables:
    main_handler = new handler();
    main_canvas = new canvas('myCanvas_bg');
    main_media = new image('im');
    // Parse the input URL.  Returns false if the URL does not set the
    // annotation folder or image filename.  If false is returned, the
    // function fetches a new image and sets the URL to reflect the
    // fetched image.
    if(!main_media.GetFileInfo().ParseURL()) return;

    if(video_mode) {
      main_media = new video('videoplayer');
      main_media.GetFileInfo().ParseURL();
      console.log("Video mode...");
      var anno_file = main_media.GetFileInfo().GetFullName();
      main_media.GetNewVideo();
      anno_file = 'VLMAnnotations/' + anno_file + '.xml' + '?' + Math.random();
      ReadXML(anno_file,LoadAnnotationSuccess,LoadAnnotation404);
    }
    else {
      // This function gets run after image is loaded:
      function main_media_onload_helper() {
	// Set the image dimensions:
	main_media.SetImageDimensions();

	// Read the XML annotation file:
	var anno_file = main_media.GetFileInfo().GetFullName();
	anno_file = 'Annotations/' + anno_file.substr(0,anno_file.length-4) + '.xml' + '?' + Math.random();
	ReadXML(anno_file,LoadAnnotationSuccess,LoadAnnotation404);
      };

      // Get the image:
      main_media.GetNewImage(main_media_onload_helper);
    }
  }
  else {
    // Invalid browser, so display error page.
    $('body').remove();
    $('html').append('

Sorry!  This page only works with Mozilla Firefox, Chrome, and Internet Explorer.  We may support other browsers in the future.

Download Mozilla Firefox?
');
  }
}

/** This function gets called if the annotation has been successfully loaded.
  * @param {string} xml - the xml regarding the current file
*/
function LoadAnnotationSuccess(xml) {
  console.time('load success');

  // Set global variable:
  LM_xml = xml;
  if (video_mode){
    FinishStartup();
    return;
  }
  var obj_elts = LM_xml.getElementsByTagName("object");
  var num_obj = obj_elts.length;

  AllAnnotations = Array(num_obj);
  num_orig_anno = num_obj;

  console.time('initialize XML');
  // Initialize any empty tags in the XML file:
  for(var pp = 0; pp < num_obj; pp++) {
    var curr_obj = $(LM_xml).children("annotation").children("object").eq(pp);

    // Initialize object name if empty in the XML file:
    if(curr_obj.children("name").length == 0) curr_obj.append($("<name></name>"));

    // Set object IDs:
    if(curr_obj.children("id").length > 0) curr_obj.children("id").text(""+pp);
    else curr_obj.append($("<id>" + pp + "</id>"));

    /*************************************************************/
    /*************************************************************/
    // Scribble:
    // Initialize username if empty in the XML file. Check first if we
    // have a polygon or a segmentation:
    if(curr_obj.children("polygon").length == 0) { // Segmentation
      if(curr_obj.children("segm").children("username").length == 0) {
        curr_obj.children("segm").append($("<username>anonymous</username>"));
      }
    }
    else if(curr_obj.children("polygon").children("username").length == 0) curr_obj.children("polygon").append($("<username>anonymous</username>"));
    /*************************************************************/
    /*************************************************************/
  }
  console.timeEnd('initialize XML');

  console.time('addPartFields()');
  // Add part fields (this calls a funcion inside object_parts.js)
  addPartFields(); // makes sure all the annotations have all the fields.
  console.timeEnd('addPartFields()');

  console.time('loop annotated');
  // Loop over annotated objects
  for(var pp = 0; pp < num_obj; pp++) {
    AllAnnotations[pp] = new annotation(pp);

    /*************************************************************/
    /*************************************************************/
    // Scribble:
    // If annotation is polygon, insert polygon:
    if(obj_elts[pp].getElementsByTagName("polygon").length > 0){
      var pt_elts = obj_elts[pp].getElementsByTagName("polygon")[0].getElementsByTagName("pt");
      var numpts = pt_elts.length;
      AllAnnotations[pp].CreatePtsX(numpts);
      AllAnnotations[pp].CreatePtsY(numpts);
      for(ii=0; ii < numpts; ii++) {
        AllAnnotations[pp].GetPtsX()[ii] = parseInt(pt_elts[ii].getElementsByTagName("x")[0].firstChild.nodeValue);
        AllAnnotations[pp].GetPtsY()[ii] = parseInt(pt_elts[ii].getElementsByTagName("y")[0].firstChild.nodeValue);
      }
    }
    // Otherwise, insert segmentation:
    else if (scribble_mode){
      AllAnnotations[pp].SetType(1);
      AllAnnotations[pp].SetImName(obj_elts[pp].getElementsByTagName("segm")[0].getElementsByTagName("mask")[0].firstChild.nodeValue);
      AllAnnotations[pp].SetScribbleName(obj_elts[pp].getElementsByTagName("segm")[0].getElementsByTagName("scribbles")[0].getElementsByTagName("scribble_name")[0].firstChild.nodeValue);
      var xc1 = parseInt (obj_elts[pp].getElementsByTagName("segm")[0].getElementsByTagName("scribbles")[0].getElementsByTagName("xmin")[0].firstChild.nodeValue);
      var yc1 = parseInt (obj_elts[pp].getElementsByTagName("segm")[0].getElementsByTagName("scribbles")[0].getElementsByTagName("ymin")[0].firstChild.nodeValue);
      var xc2 = parseInt (obj_elts[pp].getElementsByTagName("segm")[0].getElementsByTagName("scribbles")[0].getElementsByTagName("xmax")[0].firstChild.nodeValue);
      var yc2 = parseInt (obj_elts[pp].getElementsByTagName("segm")[0].getElementsByTagName("scribbles")[0].getElementsByTagName("ymax")[0].firstChild.nodeValue);
      var xc3 = parseInt (obj_elts[pp].getElementsByTagName("segm")[0].getElementsByTagName("box")[0].getElementsByTagName("xmin")[0].firstChild.nodeValue);
      var yc3 = parseInt (obj_elts[pp].getElementsByTagName("segm")[0].getElementsByTagName("box")[0].getElementsByTagName("ymin")[0].firstChild.nodeValue);
      var xc4 = parseInt (obj_elts[pp].getElementsByTagName("segm")[0].getElementsByTagName("box")[0].getElementsByTagName("xmax")[0].firstChild.nodeValue);
      var yc4 = parseInt (obj_elts[pp].getElementsByTagName("segm")[0].getElementsByTagName("box")[0].getElementsByTagName("ymax")[0].firstChild.nodeValue);

      AllAnnotations[pp].SetImageCorners(xc1,yc1,xc2,yc2);
      AllAnnotations[pp].SetCorners(xc3,yc3,xc4,yc4);
    }
    /*************************************************************/
    /*************************************************************/

  }
  console.timeEnd('loop annotated');

  console.time('attach main_canvas');
  // Attach valid annotations to the main_canvas:
  for(var pp = 0; pp < num_obj; pp++) {
    var isDeleted = AllAnnotations[pp].GetDeleted();
    if((view_Existing&&!isDeleted)||(isDeleted&&view_Deleted)) {
      // Attach to main_canvas:
      main_canvas.AttachAnnotation(AllAnnotations[pp]);
    }
  }
  console.timeEnd('attach main_canvas');

  console.time('RenderAnnotations()');
  // Render the annotations:
  main_canvas.RenderAnnotations();
  console.timeEnd('RenderAnnotations()');

  console.timeEnd('load success');

  // Finish the startup scripts:
  FinishStartup();
}

/** Annotation file does not exist, so load template. */
function LoadAnnotation404(jqXHR,textStatus,errorThrown) {
  if(jqXHR.status==404)
    ReadXML(main_media.GetFileInfo().GetTemplatePath(),LoadTemplateSuccess,LoadTemplate404);
  else
    alert(jqXHR.status);
}

/** Annotation template does not exist for this folder, so load default */
function LoadTemplate404(jqXHR,textStatus,errorThrown) {
  if(jqXHR.status==404)
    ReadXML('annotationCache/XMLTemplates/labelme.xml',LoadTemplateSuccess,function(jqXHR) {
	alert(jqXHR.status);
      });
  else
    alert(jqXHR.status);
}

/** Actions after template load success
  * @param {string} xml - the xml regarding the current file
*/
function LoadTemplateSuccess(xml) {
  // Set global variable:
  LM_xml = xml;

  // Set folder and image filename:
  LM_xml.getElementsByTagName("filename")[0].firstChild.nodeValue = '\n'+main_media.GetFileInfo().GetImName()+'\n';
  LM_xml.getElementsByTagName("folder")[0].firstChild.nodeValue = '\n'+main_media.GetFileInfo().GetDirName()+'\n';

  // Set global variable:
  num_orig_anno = 0;

  // Finish the startup scripts:
  FinishStartup();
}

/** Finish the startup process: */
function FinishStartup() {
  // Load the annotation list on the right side of the page:
  if(view_ObjList && !video_mode) RenderObjectList();

  // Add actions:
  console.log('LabelMe: setting actions');
  if($('#img_url')) $('#img_url').attr('onclick','javascript:console.log(\'bobo\');location.href=main_media.GetFileInfo().GetImagePath();');
  $('#changeuser').attr("onclick","javascript:show_enterUserNameDIV(); return false;");
  $('#userEnter').attr("onkeyup","javascript:var c; if(event.keyCode)c=event.keyCode; if(event.which)c=event.which; if(c==13 || c==27) changeAndDisplayUserName(c);");
  $('#xml_url').attr("onclick","javascript:GetXMLFile();");
  $('#nextImage').attr("onclick","javascript:ShowNextImage()");
  $('#zoomin').attr("onclick","javascript:main_media.Zoom(1.15)");
  $('#zoomout').attr("onclick","javascript:main_media.Zoom(1.0/1.15)");
  $('#fit').attr("onclick","javascript:main_media.Zoom('fitted')");
  $('#erase').attr("onclick","javascript:main_handler.EraseSegment()");
  $('#myCanvas_bg_div').attr("onmousedown","javascript:StartDrawEvent(event);return false;");
  $('#myCanvas_bg_div').attr("oncontextmenu","javascript:return false;");
  $('#myCanvas_bg_div').attr("onmouseover","javascript:unselectObjects();");
  $('#select_canvas_div').attr("oncontextmenu","javascript:return false;");
  $('#query_canvas_div').attr("onmousedown","javascript:event.preventDefault();WaitForInput();return false;");
  $('#query_canvas_div').attr("onmouseup","javascript:event.preventDefault();");
  $('#query_canvas_div').attr("oncontextmenu","javascript:return false;");

  // Initialize the username:
  initUserName();

  // Enable scribble mode:
  if(scribble_mode) InitializeScribbleMode('label_buttons_drawing','main_media');

  // Set action when the user presses a key:
  document.onkeyup = main_handler.KeyPress;

  // Collect statistics:
  ref = document.referrer;

  // Write "finished" messages:
  WriteLogMsg('*done_loading_' + main_media.GetFileInfo().GetImagePath());
  console.log('LabelMe: finished loading');

  console.timeEnd('startup');
}
<commit_msg>isolated AllAnnotations() population into separate function<commit_after>/** @file This file contains the scripts used when LabelMe starts up. */

/** Main entry point for the annotation tool. */
function StartupLabelMe() {
  console.time('startup');

  // Check browser:
  GetBrowserInfo();
  if(IsNetscape() || (IsMicrosoft() && (bversion>=4.5)) || IsSafari() || IsChrome()) {
    // Write "start up" messages:
    WriteLogMsg('*start_loading');
    console.log('LabelMe: starting up...');

    // Initialize global variables:
    main_handler = new handler();
    main_canvas = new canvas('myCanvas_bg');
    main_media = new image('im');
    // Parse the input URL.  Returns false if the URL does not set the
    // annotation folder or image filename.  If false is returned, the
    // function fetches a new image and sets the URL to reflect the
    // fetched image.
    if(!main_media.GetFileInfo().ParseURL()) return;

    if(video_mode) {
      main_media = new video('videoplayer');
      main_media.GetFileInfo().ParseURL();
      console.log("Video mode...");
      var anno_file = main_media.GetFileInfo().GetFullName();
      main_media.GetNewVideo();
      anno_file = 'VLMAnnotations/' + anno_file + '.xml' + '?' + Math.random();
      ReadXML(anno_file,LoadAnnotationSuccess,LoadAnnotation404);
    }
    else {
      // This function gets run after image is loaded:
      function main_media_onload_helper() {
	// Set the image dimensions:
	main_media.SetImageDimensions();

	// Read the XML annotation file:
	var anno_file = main_media.GetFileInfo().GetFullName();
	anno_file = 'Annotations/' + anno_file.substr(0,anno_file.length-4) + '.xml' + '?' + Math.random();
	ReadXML(anno_file,LoadAnnotationSuccess,LoadAnnotation404);
      };

      // Get the image:
      main_media.GetNewImage(main_media_onload_helper);
    }
  }
  else {
    // Invalid browser, so display error page.
    $('body').remove();
    $('html').append('

Sorry!  This page only works with Mozilla Firefox, Chrome, and Internet Explorer.  We may support other browsers in the future.

Download Mozilla Firefox?
');
  }
}

/** This function gets called if the annotation has been successfully loaded.
  * @param {string} xml - the xml regarding the current file
*/
function LoadAnnotationSuccess(xml) {
  console.time('load success');

  // Set global variable:
  LM_xml = xml;
  if (video_mode){
    FinishStartup();
    return;
  }

  // Set AllAnnotations array:
  SetAllAnnotationsArray();

  console.time('attach main_canvas');
  // Attach valid annotations to the main_canvas:
  for(var pp = 0; pp < AllAnnotations.length; pp++) {
    var isDeleted = AllAnnotations[pp].GetDeleted();
    if((view_Existing&&!isDeleted)||(isDeleted&&view_Deleted)) {
      // Attach to main_canvas:
      main_canvas.AttachAnnotation(AllAnnotations[pp]);
    }
  }
  console.timeEnd('attach main_canvas');

  console.time('RenderAnnotations()');
  // Render the annotations:
  main_canvas.RenderAnnotations();
  console.timeEnd('RenderAnnotations()');

  console.timeEnd('load success');

  // Finish the startup scripts:
  FinishStartup();
}

/** Sets AllAnnotations array from LM_xml */
function SetAllAnnotationsArray() {
  var obj_elts = LM_xml.getElementsByTagName("object");
  var num_obj = obj_elts.length;

  AllAnnotations = Array(num_obj);
  num_orig_anno = num_obj;

  console.time('initialize XML');
  // Initialize any empty tags in the XML file:
  for(var pp = 0; pp < num_obj; pp++) {
    var curr_obj = $(LM_xml).children("annotation").children("object").eq(pp);

    // Initialize object name if empty in the XML file:
    if(curr_obj.children("name").length == 0) curr_obj.append($("<name></name>"));

    // Set object IDs:
    if(curr_obj.children("id").length > 0) curr_obj.children("id").text(""+pp);
    else curr_obj.append($("<id>" + pp + "</id>"));

    /*************************************************************/
    /*************************************************************/
    // Scribble:
    // Initialize username if empty in the XML file. Check first if we
    // have a polygon or a segmentation:
    if(curr_obj.children("polygon").length == 0) { // Segmentation
      if(curr_obj.children("segm").children("username").length == 0) {
        curr_obj.children("segm").append($("<username>anonymous</username>"));
      }
    }
    else if(curr_obj.children("polygon").children("username").length == 0) curr_obj.children("polygon").append($("<username>anonymous</username>"));
    /*************************************************************/
    /*************************************************************/
  }
  console.timeEnd('initialize XML');

  console.time('addPartFields()');
  // Add part fields (this calls a funcion inside object_parts.js)
  addPartFields(); // makes sure all the annotations have all the fields.
  console.timeEnd('addPartFields()');

  console.time('loop annotated');
  // Loop over annotated objects
  for(var pp = 0; pp < num_obj; pp++) {
    AllAnnotations[pp] = new annotation(pp);

    /*************************************************************/
    /*************************************************************/
    // Scribble:
    // If annotation is polygon, insert polygon:
    if(obj_elts[pp].getElementsByTagName("polygon").length > 0){
      var pt_elts = obj_elts[pp].getElementsByTagName("polygon")[0].getElementsByTagName("pt");
      var numpts = pt_elts.length;
      AllAnnotations[pp].CreatePtsX(numpts);
      AllAnnotations[pp].CreatePtsY(numpts);
      for(ii=0; ii < numpts; ii++) {
        AllAnnotations[pp].GetPtsX()[ii] = parseInt(pt_elts[ii].getElementsByTagName("x")[0].firstChild.nodeValue);
        AllAnnotations[pp].GetPtsY()[ii] = parseInt(pt_elts[ii].getElementsByTagName("y")[0].firstChild.nodeValue);
      }
    }
    // Otherwise, insert segmentation:
    else if (scribble_mode){
      AllAnnotations[pp].SetType(1);
      AllAnnotations[pp].SetImName(obj_elts[pp].getElementsByTagName("segm")[0].getElementsByTagName("mask")[0].firstChild.nodeValue);
      AllAnnotations[pp].SetScribbleName(obj_elts[pp].getElementsByTagName("segm")[0].getElementsByTagName("scribbles")[0].getElementsByTagName("scribble_name")[0].firstChild.nodeValue);
      var xc1 = parseInt (obj_elts[pp].getElementsByTagName("segm")[0].getElementsByTagName("scribbles")[0].getElementsByTagName("xmin")[0].firstChild.nodeValue);
      var yc1 = parseInt (obj_elts[pp].getElementsByTagName("segm")[0].getElementsByTagName("scribbles")[0].getElementsByTagName("ymin")[0].firstChild.nodeValue);
      var xc2 = parseInt (obj_elts[pp].getElementsByTagName("segm")[0].getElementsByTagName("scribbles")[0].getElementsByTagName("xmax")[0].firstChild.nodeValue);
      var yc2 = parseInt (obj_elts[pp].getElementsByTagName("segm")[0].getElementsByTagName("scribbles")[0].getElementsByTagName("ymax")[0].firstChild.nodeValue);
      var xc3 = parseInt (obj_elts[pp].getElementsByTagName("segm")[0].getElementsByTagName("box")[0].getElementsByTagName("xmin")[0].firstChild.nodeValue);
      var yc3 = parseInt (obj_elts[pp].getElementsByTagName("segm")[0].getElementsByTagName("box")[0].getElementsByTagName("ymin")[0].firstChild.nodeValue);
      var xc4 = parseInt (obj_elts[pp].getElementsByTagName("segm")[0].getElementsByTagName("box")[0].getElementsByTagName("xmax")[0].firstChild.nodeValue);
      var yc4 = parseInt (obj_elts[pp].getElementsByTagName("segm")[0].getElementsByTagName("box")[0].getElementsByTagName("ymax")[0].firstChild.nodeValue);

      AllAnnotations[pp].SetImageCorners(xc1,yc1,xc2,yc2);
      AllAnnotations[pp].SetCorners(xc3,yc3,xc4,yc4);
    }
    /*************************************************************/
    /*************************************************************/

  }
  console.timeEnd('loop annotated');
}

/** Annotation file does not exist, so load template. */
function LoadAnnotation404(jqXHR,textStatus,errorThrown) {
  if(jqXHR.status==404)
    ReadXML(main_media.GetFileInfo().GetTemplatePath(),LoadTemplateSuccess,LoadTemplate404);
  else
    alert(jqXHR.status);
}

/** Annotation template does not exist for this folder, so load default */
function LoadTemplate404(jqXHR,textStatus,errorThrown) {
  if(jqXHR.status==404)
    ReadXML('annotationCache/XMLTemplates/labelme.xml',LoadTemplateSuccess,function(jqXHR) {
	alert(jqXHR.status);
      });
  else
    alert(jqXHR.status);
}

/** Actions after template load success
  * @param {string} xml - the xml regarding the current file
*/
function LoadTemplateSuccess(xml) {
  // Set global variable:
  LM_xml = xml;

  // Set folder and image filename:
  LM_xml.getElementsByTagName("filename")[0].firstChild.nodeValue = '\n'+main_media.GetFileInfo().GetImName()+'\n';
  LM_xml.getElementsByTagName("folder")[0].firstChild.nodeValue = '\n'+main_media.GetFileInfo().GetDirName()+'\n';

  // Set global variable:
  num_orig_anno = 0;

  // Finish the startup scripts:
  FinishStartup();
}

/** Finish the startup process: */
function FinishStartup() {
  // Load the annotation list on the right side of the page:
  if(view_ObjList && !video_mode) RenderObjectList();

  // Add actions:
  console.log('LabelMe: setting actions');
  if($('#img_url')) $('#img_url').attr('onclick','javascript:console.log(\'bobo\');location.href=main_media.GetFileInfo().GetImagePath();');
  $('#changeuser').attr("onclick","javascript:show_enterUserNameDIV(); return false;");
  $('#userEnter').attr("onkeyup","javascript:var c; if(event.keyCode)c=event.keyCode; if(event.which)c=event.which; if(c==13 || c==27) changeAndDisplayUserName(c);");
  $('#xml_url').attr("onclick","javascript:GetXMLFile();");
  $('#nextImage').attr("onclick","javascript:ShowNextImage()");
  $('#zoomin').attr("onclick","javascript:main_media.Zoom(1.15)");
  $('#zoomout').attr("onclick","javascript:main_media.Zoom(1.0/1.15)");
  $('#fit').attr("onclick","javascript:main_media.Zoom('fitted')");
  $('#erase').attr("onclick","javascript:main_handler.EraseSegment()");
  $('#myCanvas_bg_div').attr("onmousedown","javascript:StartDrawEvent(event);return false;");
  $('#myCanvas_bg_div').attr("oncontextmenu","javascript:return false;");
  $('#myCanvas_bg_div').attr("onmouseover","javascript:unselectObjects();");
  $('#select_canvas_div').attr("oncontextmenu","javascript:return false;");
  $('#query_canvas_div').attr("onmousedown","javascript:event.preventDefault();WaitForInput();return false;");
  $('#query_canvas_div').attr("onmouseup","javascript:event.preventDefault();");
  $('#query_canvas_div').attr("oncontextmenu","javascript:return false;");

  // Initialize the username:
  initUserName();

  // Enable scribble mode:
  if(scribble_mode) InitializeScribbleMode('label_buttons_drawing','main_media');

  // Set action when the user presses a key:
  document.onkeyup = main_handler.KeyPress;

  // Collect statistics:
  ref = document.referrer;

  // Write "finished" messages:
  WriteLogMsg('*done_loading_' + main_media.GetFileInfo().GetImagePath());
  console.log('LabelMe: finished loading');

  console.timeEnd('startup');
}
<|endoftext|>


<commit_before>var iconv = require('iconv-lite');
var zlib = require('zlib');
var MAX_REQ_SIZE = 128 * 1024;
var MAX_RES_SIZE = 256 * 1024;
var TIMEOUT = 10000;
var MAX_LENGTH = 512;
var count = 0;
var ids = [];
var data = {};
var proxy, binded, timeout, interval, util;

function disable() {
	proxy.removeListener('request', handleRequest);
	ids = [];
	data = {};
	interval && clearInterval(interval);
	interval = null;
	binded = false;
}

/**
 * 如果超过最大缓存数，清理如下请求数据：
 * 1. 已经请求结束且结束时间超过10秒
 * 2. 请求#1前面的未结束且未被ui读取过的请求
 */
function clearCache() {
	if (ids.length <= MAX_LENGTH) {
		return;
	}

	var index = -1; //已经完成，且缓存超过10s的最后一个请求
	var now = Date.now();
	for (var i = ids.length - 1; i >= 0; i--) {
		var curData = data[ids[i]];
		if (curData.endTime && now - curData.endTime > TIMEOUT) {
			index = i;
			break;
		}
	}

	if (index < 0) {
		return;
	}

	var _ids = [];
	++index;
	for (var i = 0; i < index; i++) {
		var id = ids[i];
		var curData = data[id];
		if (curData.read && !curData.endTime) {
			_ids.push(id);
		} else {
			delete data[id];
		}
	}
	if (_ids.length) {
		ids = _ids.concat(ids.slice(index));
	}
}

function passThrough(chunk, encoding, callback) {
	callback(null, chunk);
}

function decode(body) {
	if (body) {
		var _body = body + '';
		if (_body.indexOf('�') != -1) {
			_body = iconv.decode(body, 'gbk');
		}
		body = _body;
	}

	return body;
}

function get() {
	!binded && proxy.on('request', handleRequest);
	binded = true;
	clearTimeout(timeout);
	timeout = setTimeout(disable, TIMEOUT);
	if (!interval) {
		interval = setInterval(clearCache, 3000);
	}
	return [];
}

function handleRequest(req) {
	var dnsTime = req.dnsTime || 0;
	req.dnsTime = Date.now();
	var startTime = startTime - dnsTime;
	var id = startTime + '-' + ++count;
	var reqData = {
			dnsTime: req.dnsTime,
			method: req.method || 'GET',
			httpVersion: req.httpVersion || '1.1',
            host: req.host || '127.0.0.1',
            headers: req.headers
		};
	var resData = {};

	var curData = data[id] = {
			url: req.url,
			startTime: startTime,
			req: reqData,
			res: resData
	};

	ids.push(id);
	req.on('response', handleResponse);
	req.on('error', function(err) {
		reqData.body = err && err.stack;
		curData.endTime = reqData.requestTime = Date.now();
		req.removeListener('response', handleResponse);
		req._transform = passThrough;
		curData.reqError = true;
	});

	var reqBody;

	if (util.hasRequestBody(req)) {
		reqBody = false;
	}
	req._transform = function(chunk, encoding, callback) {

		if (chunk && (reqBody || reqBody === false)) {
			reqBody = reqBody ? Buffer.concat([reqBody, chunk]) : chunk;
		}

		if (reqBody && reqBody.length > MAX_REQ_SIZE) {
			reqBody = null;
		}

		if (!chunk) {
			reqData.requestTime = Date.now();
			curData.reqEnd = true;
			reqData.body = decode(reqBody);
		}

		callback(null, chunk);
	};

	function handleResponse(res) {
		resData.responseTime = Date.now();
		res.on('error', function(err) {
			resData.body = err && err.stack;
			curData.endTime = Date.now();
			res._transform = passThrough;
			curData.resError = true;
		});

		var resBody;
		var contentType = util.getContentType(res.headers);
		if (contentType && contentType != 'IMG' && util.hasBody(res)) {
			resBody = false;
		}

		res._transform = function(chunk, encoding, callback) {
			if (chunk && (resBody || resBody === false)) {
				resBody = resBody ? Buffer.concat([resBody, chunk]) : chunk;
			}

			if (resBody && resBody.length > MAX_RES_SIZE) {
				resBody = null;
			}

			if (!chunk) {
				curData.endTime = Date.now();
				resData.state = 'close';
				curData.resEnd = true;
				if (resBody) {
					var unzip;
					switch (util.toLowerCase(res.headers['content-encoding'])) {
					    case 'gzip':
					    	unzip = zlib.gunzip.bind(zlib);
					      break;
					    case 'deflate':
					    	unzip = zlib.inflate.bind(zlib);
					      break;
					}

					if (unzip) {
						unzip(resBody, function(err, body) {
							if (err) {
								callback(err, chunk);
								return;
							}
							resData.body = decode(body);
							callback(null, chunk);
						});
						return;
					}
				}
				resData.body = decode(resBody);
			}

			callback(null, chunk);
		};
	}

}

module.exports = function init(_proxy) {
	proxy = _proxy;
	util = proxy.util;
	proxy.on('request', handleRequest);
	module.exports = get;
};<commit_msg>clear cache<commit_after>var iconv = require('iconv-lite');
var zlib = require('zlib');
var MAX_REQ_SIZE = 128 * 1024;
var MAX_RES_SIZE = 256 * 1024;
var TIMEOUT = 10000;
var MAX_LENGTH = 512;
var count = 0;
var ids = [];
var data = {};
var proxy, binded, timeout, interval, util;

function disable() {
	proxy.removeListener('request', handleRequest);
	ids = [];
	data = {};
	interval && clearInterval(interval);
	interval = null;
	binded = false;
}

/**
 * 如果超过最大缓存数，清理如下请求数据：
 * 1. 已经请求结束且结束时间超过10秒
 * 2. 请求#1前面的未结束且未被ui读取过的请求
 */
function clearCache() {
	if (ids.length <= MAX_LENGTH) {
		return;
	}

	var index = -1; //已经完成，且缓存超过10s的最后一个请求
	var now = Date.now();
	for (var i = ids.length - 1; i >= 0; i--) {
		var curData = data[ids[i]];
		if (curData.endTime && now - curData.endTime > TIMEOUT) {
			index = i;
			break;
		}
	}

	if (index < 0) {
		return;
	}

	var _ids = [];
	++index;
	for (var i = 0; i < index; i++) {
		var id = ids[i];
		var curData = data[id];
		if (curData.read && !curData.endTime) {
			_ids.push(id);
		} else {
			delete data[id];
		}
	}
	if (_ids.length) {
		ids = _ids.concat(ids.slice(index));
	}
}

function passThrough(chunk, encoding, callback) {
	callback(null, chunk);
}

function decode(body) {
	if (body) {
		var _body = body + '';
		if (_body.indexOf('�') != -1) {
			_body = iconv.decode(body, 'gbk');
		}
		body = _body;
	}

	return body;
}

function get() {
	!binded && proxy.on('request', handleRequest);
	binded = true;
	clearTimeout(timeout);
	timeout = setTimeout(disable, TIMEOUT);
	if (!interval) {
		interval = setInterval(clearCache, 3000);
	}
	return [];
}

function handleRequest(req) {
	var dnsTime = req.dnsTime || 0;
	req.dnsTime = Date.now();
	var startTime = startTime - dnsTime;
	var id = startTime + '-' + ++count;
	var reqData = {
			dnsTime: req.dnsTime,
			method: req.method || 'GET',
			httpVersion: req.httpVersion || '1.1',
            host: req.host || '127.0.0.1',
            headers: req.headers
		};
	var resData = {};

	var curData = data[id] = {
			url: req.url,
			startTime: startTime,
			req: reqData,
			res: resData
	};

	ids.push(id);
	req.on('response', handleResponse);
	req.on('error', function(err) {
		reqData.body = err && err.stack;
		curData.endTime = reqData.requestTime = Date.now();
		req.removeListener('response', handleResponse);
		req._transform = passThrough;
		curData.reqError = true;
	});

	var reqBody;

	if (util.hasRequestBody(req)) {
		reqBody = false;
	}
	req._transform = function(chunk, encoding, callback) {

		if (chunk && (reqBody || reqBody === false)) {
			reqBody = reqBody ? Buffer.concat([reqBody, chunk]) : chunk;
		}

		if (reqBody && reqBody.length > MAX_REQ_SIZE) {
			reqBody = null;
		}

		if (!chunk) {
			reqData.requestTime = Date.now();
			curData.reqEnd = true;
			reqData.body = decode(reqBody);
		}

		callback(null, chunk);
	};

	function handleResponse(res) {
		resData.responseTime = Date.now();
		res.on('error', function(err) {
			resData.body = err && err.stack;
			curData.endTime = Date.now();
			res._transform = passThrough;
			curData.resError = true;
		});

		var resBody;
		var contentType = util.getContentType(res.headers);
		if (contentType && contentType != 'IMG' && util.hasBody(res)) {
			resBody = false;
		}

		res._transform = function(chunk, encoding, callback) {
			if (chunk && (resBody || resBody === false)) {
				resBody = resBody ? Buffer.concat([resBody, chunk]) : chunk;
			}

			if (resBody && resBody.length > MAX_RES_SIZE) {
				resBody = null;
			}

			if (!chunk) {
				curData.endTime = Date.now();
				resData.state = 'close';
				curData.resEnd = true;
				if (resBody) {
					var unzip;
					switch (util.toLowerCase(res.headers['content-encoding'])) {
					    case 'gzip':
					    	unzip = zlib.gunzip.bind(zlib);
					      break;
					    case 'deflate':
					    	unzip = zlib.inflate.bind(zlib);
					      break;
					}

					if (unzip) {
						unzip(resBody, function(err, body) {
							if (err) {
								callback(err, chunk);
								return;
							}
							resData.body = decode(body);
							callback(null, chunk);
						});
						return;
					}
				}
				resData.body = decode(resBody);
			}

			callback(null, chunk);
		};
	}

}

module.exports = function init(_proxy) {
	proxy = _proxy;
	util = proxy.util;
	proxy.on('request', handleRequest);
	binned = true;
	interval = setInterval(clearCache, 3000);
	module.exports = get;
};<|endoftext|>


<commit_before>var Bell = require("bell");
var Config = require("../config");
var Jobs = require("../models/jobs");
var Users = require("../models/users");

module.exports = {

//To serve public files, css, lib, etc
	serveFile: {
		auth: false,
		handler: {
			directory: {
				path: "../public"
			}
		}
	},

	home: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			if(request.auth.isAuthenticated) {
				reply.redirect("/dashboard");
			} else {
				reply.view("home");
			}
		}
	},

	signupIam: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {
			reply.view("signupIam");
		}
	},

	signupPhotographer: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {
			console.log("I am a photographer");
			reply.redirect("/signup/social");
		}
	},

	signupClient: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {
			console.log("I am a client");
			reply.redirect("/signup/social");
		}
	},

	signupSocial: {
			auth: {
				mode: "optional"
			},
		handler: function(request, reply) {
			reply.view("signupSocial");
		}
	},

	facebook: {
		auth: {
			strategy: "facebook"
			},
		handler: function(request, reply) {

			var fb = request.auth.credentials.profile;

			var profile = {
				auth: "Facebook",
				id: fb.id,
				username: fb.username,
				displayName: fb.displayName,
				firstName: fb.name.first,
				lastName: fb.name.last,
				email: fb.email,
				link: fb.raw.link,
				picture: ('https://graph.facebook.com/' + fb.id + '/picture?width=300&height=300'),
				gender: fb.raw.gender
			};

			request.auth.session.set(profile);

			Users.addUser(profile, function(err, data){
				console.log("User added to database");
			});

			reply.redirect("/dashboard");

		}
	},

	google: {
		auth: {
			strategy: "google"
			},
		handler: function(request, reply) {
			var g = request.auth.credentials.profile;

			var profile = {
				auth: "Google",
				id: g.id,
				username: g.username,
				displayName: g.displayName,
				firstName: g.name.first,
				lastName: g.name.last,
				email: g.email,
				link: g.raw.link,
				picture: g.raw.picture,
				gender: g.raw.gender
			};

			request.auth.session.set(profile);

			Users.addUser(profile, function(err, data){
				console.log("User added to database");
			});

			reply.redirect("/dashboard");
		}
	},

	dashboard: {
		auth: {
			mode: "try"
		},
		handler: function(request, reply) {

			var email;

			if(request.auth.isAuthenticated) {

				email = request.auth.credentials.email;

				Jobs.getAllJobs(email, function(err, data) {
					console.log(request.auth.session);
					reply.view("dashboard", {jobs: data});
				});

			} else {

				email = "test@test.com";

				Jobs.getAllJobs(email, function(err, data) {
					console.log(request.auth.session);
					reply.view("dashboard", {jobs: data});
				});
			}
		}
	},

	profile: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			if(request.auth.isAuthenticated) {
				var data = request.auth.credentials;
				reply.view("profile", {data: data});
			} else {
				testdata = {
					auth: "test",
					id: "123",
					username: "test",
					displayName: "test",
					firstName: "test",
					lastName: "test",
					email: "test@test.com",
					link: "test",
					picture: "test",
					gender: "test"
				};
				reply.view("profile", {data: testdata});
			}
		}
	},

	newJobStepOne: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {
			reply.view("newJobOne");
		}
	},

	newJobStepOneP: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			var user_email;

			if(request.auth.isAuthenticated) {

				user_email = request.auth.credentials.email;

			} else {

				user_email = "test@test.com";
			}

			var new_job = {
				user: user_email,
				dateAdded: new Date(),
				postingAs: request.payload.postingAs,
				eventName: request.payload.eventName,
				dateTime: request.payload.dateTime,
				jobDuration: request.payload.jobDuration,
				location: request.payload.location,
				description: request.payload.description,
				useOfPhotos: request.payload.useOfPhotos,
				dateRequired: request.payload.dateRequired,
				noOfPhotographers: request.payload.noOfPhotographers
			};

			Jobs.newjob(new_job, function(err, data) {
				reply.redirect("/dashboard");
			});

		}
	},

	newJobStepTwo: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {
			console.log(request.payload);
			reply.view("newJobTwo");
		}
	},

	newJobStepTwoP: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			var post = request.payload;

			jobs.newjob(request.payload, function (err, data) {
				reply.redirect("/dashboard");
			});
		}
	},

	help: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {
			reply("Help");
		}
	},

	logout: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {
			request.auth.session.clear();
			console.log(request.auth);
			reply.redirect("/");
		}
	}

};<commit_msg>mode optional<commit_after>var Bell = require("bell");
var Config = require("../config");
var Jobs = require("../models/jobs");
var Users = require("../models/users");

module.exports = {

//To serve public files, css, lib, etc
	serveFile: {
		auth: false,
		handler: {
			directory: {
				path: "../public"
			}
		}
	},

	home: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			if(request.auth.isAuthenticated) {
				reply.redirect("/dashboard");
			} else {
				reply.view("home");
			}
		}
	},

	signupIam: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {
			reply.view("signupIam");
		}
	},

	signupPhotographer: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {
			console.log("I am a photographer");
			reply.redirect("/signup/social");
		}
	},

	signupClient: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {
			console.log("I am a client");
			reply.redirect("/signup/social");
		}
	},

	signupSocial: {
			auth: {
				mode: "optional"
			},
		handler: function(request, reply) {
			reply.view("signupSocial");
		}
	},

	facebook: {
		auth: {
			strategy: "facebook"
			},
		handler: function(request, reply) {

			var fb = request.auth.credentials.profile;

			var profile = {
				auth: "Facebook",
				id: fb.id,
				username: fb.username,
				displayName: fb.displayName,
				firstName: fb.name.first,
				lastName: fb.name.last,
				email: fb.email,
				link: fb.raw.link,
				picture: ('https://graph.facebook.com/' + fb.id + '/picture?width=300&height=300'),
				gender: fb.raw.gender
			};

			request.auth.session.set(profile);

			Users.addUser(profile, function(err, data){
				console.log("User added to database");
			});

			reply.redirect("/dashboard");

		}
	},

	google: {
		auth: {
			strategy: "google"
			},
		handler: function(request, reply) {
			var g = request.auth.credentials.profile;

			var profile = {
				auth: "Google",
				id: g.id,
				username: g.username,
				displayName: g.displayName,
				firstName: g.name.first,
				lastName: g.name.last,
				email: g.email,
				link: g.raw.link,
				picture: g.raw.picture,
				gender: g.raw.gender
			};

			request.auth.session.set(profile);

			Users.addUser(profile, function(err, data){
				console.log("User added to database");
			});

			reply.redirect("/dashboard");
		}
	},

	dashboard: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			var email;

			if(request.auth.isAuthenticated) {

				email = request.auth.credentials.email;

				Jobs.getAllJobs(email, function(err, data) {
					console.log(request.auth.session);
					reply.view("dashboard", {jobs: data});
				});

			} else {

				email = "test@test.com";

				Jobs.getAllJobs(email, function(err, data) {
					console.log(request.auth.session);
					reply.view("dashboard", {jobs: data});
				});
			}
		}
	},

	profile: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			if(request.auth.isAuthenticated) {
				var data = request.auth.credentials;
				reply.view("profile", {data: data});
			} else {
				testdata = {
					auth: "test",
					id: "123",
					username: "test",
					displayName: "test",
					firstName: "test",
					lastName: "test",
					email: "test@test.com",
					link: "test",
					picture: "test",
					gender: "test"
				};
				reply.view("profile", {data: testdata});
			}
		}
	},

	newJobStepOne: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {
			reply.view("newJobOne");
		}
	},

	newJobStepOneP: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			var user_email;

			if(request.auth.isAuthenticated) {

				user_email = request.auth.credentials.email;

			} else {

				user_email = "test@test.com";
			}

			var new_job = {
				user: user_email,
				dateAdded: new Date(),
				postingAs: request.payload.postingAs,
				eventName: request.payload.eventName,
				dateTime: request.payload.dateTime,
				jobDuration: request.payload.jobDuration,
				location: request.payload.location,
				description: request.payload.description,
				useOfPhotos: request.payload.useOfPhotos,
				dateRequired: request.payload.dateRequired,
				noOfPhotographers: request.payload.noOfPhotographers
			};

			Jobs.newjob(new_job, function(err, data) {
				reply.redirect("/dashboard");
			});

		}
	},

	newJobStepTwo: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {
			console.log(request.payload);
			reply.view("newJobTwo");
		}
	},

	newJobStepTwoP: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			var post = request.payload;

			jobs.newjob(request.payload, function (err, data) {
				reply.redirect("/dashboard");
			});
		}
	},

	help: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {
			reply("Help");
		}
	},

	logout: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {
			request.auth.session.clear();
			console.log(request.auth);
			reply.redirect("/");
		}
	}

};<|endoftext|>


<commit_before>define('HUD',

['vent', 'util', 'Sprite'],

function( vent, util ){

    'use strict';

    var init,
        ctx,
        canvas,
        update,
        render,
        bindEvents,
        drawItems,
        score,
        scoreElem,
        draw,
        cooldownTimer,
        activateCooldown,
        resetCooldown,
        checkCooldown,
        pauseCheck,
        activeIcon,
        icons,
        cfg;

    cfg = {
        cooldownTimer: {
            fillStyle: {
                current: '#f1f1f1',
                default: '#f1f1f1',
                water: 'rgba(0, 0, 220, 1)',
                air: '#b8f0f0',
                fire: 'rgba(255, 0, 0, 1)'
            },
            font: '20px Courier',
            textAlign: 'right',
            height: 400,
            currentHeight: 400,
            opts: {
                fg: {
                    lineWidth: 10,
                    lineCap: 'round'
                },
                bg: {
                    lineWidth: 12,
                    lineCap: 'round'
                }
            },
            percent: 0
        }
    };

    drawItems = {
        score: function(  ) {
            scoreElem.innerHTML = 'Score: ' + score;
        },
        cooldownTimer: function( ctx ){
            var c = cfg.cooldownTimer;
            cooldownTimer.elem.innerHTML = cooldownTimer.display || 'Ready';
            util.line(ctx, ctx.canvas.width - 25, ctx.canvas.height - 100,
                ctx.canvas.width - 25, (ctx.canvas.height - 100) - c.height,
                '#333', c.opts.bg
            );
            util.line(ctx, ctx.canvas.width - 25, ctx.canvas.height - 100,
                ctx.canvas.width - 25, (ctx.canvas.height - 100) - c.height * c.percent,
                c.fillStyle.current, c.opts.fg
            );
        }
    };

    init = function(){
        var cvs = util.getById('hud-canvas');
        ctx = cvs.getContext('2d');
        canvas = {
            width: cvs.width,
            height: cvs.height,
            ctx: ctx
        };

        activeIcon = null;
        icons = util.QSA('.ico');

        score = 0;
        scoreElem = util.getById('score');

        cooldownTimer = {
            current: 20,
            lastChecked: new Date().getTime(),
            max: 20,
            timerStarted: null,
            elem: util.getById('cooldown-timer')
        };
        pauseCheck = true;

        vent.on('update', update);
        vent.on('render', render);
        vent.on('deactivate', resetCooldown);
        vent.on('activate', activateCooldown);
        vent.on('elemental-progress', function( percent ){
            cfg.cooldownTimer.percent = percent;
        });
        vent.on('start-game', function(){
            pauseCheck = false;
            cooldownTimer.timerStarted = new Date().getTime();
        });
        vent.on('activate', function( element ){
            for (var i = 0; i < icons.length; i++) {
                icons[i].classList.remove('on');
            }
            activeIcon = util.getById(element);
            activeIcon.classList.add('on');
        });
        vent.on('cooldown-end', function(){
            for (var i = 0; i < icons.length; i++) {
                icons[i].classList.add('on');
            }
        });

    };

    bindEvents = function(){
        vent.on('start', function( obj ){
            init(obj);
        });
        vent.on('enemy-down', function(){
            score += 2;
        });
    };

    activateCooldown = function( element ){
        cooldownTimer.current = 10e3;
        cooldownTimer.lastChecked = new Date().getTime();
        cfg.cooldownTimer.fillStyle.current = cfg.cooldownTimer.fillStyle[element];
        if ( element === 'earth' ) {
            resetCooldown();
        }
    };

    resetCooldown = function(){
        activeIcon.classList.remove('on');
        cooldownTimer.current = 20e3;
        cooldownTimer.display = 20;
        cooldownTimer.lastChecked = new Date().getTime();
        cfg.cooldownTimer.fillStyle.current = cfg.cooldownTimer.fillStyle.default;
        cfg.cooldownTimer.percent = 0;
        cooldownTimer.timerStarted = new Date().getTime();
        pauseCheck = false;
    };

    checkCooldown = function(){
        if ( pauseCheck ) {
            return;
        }
        if ( cooldownTimer.display <= 0 ) {
            vent.emit('cooldown-end');
            cfg.cooldownTimer.fillStyle.current = 'rgba(120, 220, 0, 1)';
            cfg.cooldownTimer.percent = 1;
            pauseCheck = true;
            return;
        }

        var now = new Date().getTime(),
            diff = now - cooldownTimer.timerStarted;

        cooldownTimer.current = diff;
        cooldownTimer.lastChecked = now;
        cfg.cooldownTimer.percent = (now - cooldownTimer.timerStarted) / 20e3;
        cooldownTimer.display = cooldownTimer.max - parseInt(cooldownTimer.current/1000);
    };

    update = function(){
        checkCooldown();
    };

    render = function(){
        ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
        draw('score');
        draw('cooldownTimer');
    };

    draw = function( name ){
        drawItems[name](ctx);
    };

    bindEvents();

});
<commit_msg>practice safe object access<commit_after>define('HUD',

['vent', 'util', 'Sprite'],

function( vent, util ){

    'use strict';

    var init,
        ctx,
        canvas,
        update,
        render,
        bindEvents,
        drawItems,
        score,
        scoreElem,
        draw,
        cooldownTimer,
        activateCooldown,
        resetCooldown,
        checkCooldown,
        pauseCheck,
        activeIcon,
        icons,
        cfg;

    cfg = {
        cooldownTimer: {
            fillStyle: {
                current: '#f1f1f1',
                default: '#f1f1f1',
                water: 'rgba(0, 0, 220, 1)',
                air: '#b8f0f0',
                fire: 'rgba(255, 0, 0, 1)'
            },
            font: '20px Courier',
            textAlign: 'right',
            height: 400,
            currentHeight: 400,
            opts: {
                fg: {
                    lineWidth: 10,
                    lineCap: 'round'
                },
                bg: {
                    lineWidth: 12,
                    lineCap: 'round'
                }
            },
            percent: 0
        }
    };

    drawItems = {
        score: function(  ) {
            scoreElem.innerHTML = 'Score: ' + score;
        },
        cooldownTimer: function( ctx ){
            var c = cfg.cooldownTimer;
            cooldownTimer.elem.innerHTML = cooldownTimer.display || 'Ready';
            util.line(ctx, ctx.canvas.width - 25, ctx.canvas.height - 100,
                ctx.canvas.width - 25, (ctx.canvas.height - 100) - c.height,
                '#333', c.opts.bg
            );
            util.line(ctx, ctx.canvas.width - 25, ctx.canvas.height - 100,
                ctx.canvas.width - 25, (ctx.canvas.height - 100) - c.height * c.percent,
                c.fillStyle.current, c.opts.fg
            );
        }
    };

    init = function(){
        var cvs = util.getById('hud-canvas');
        ctx = cvs.getContext('2d');
        canvas = {
            width: cvs.width,
            height: cvs.height,
            ctx: ctx
        };

        activeIcon = null;
        icons = util.QSA('.ico');

        score = 0;
        scoreElem = util.getById('score');

        cooldownTimer = {
            current: 20,
            lastChecked: new Date().getTime(),
            max: 20,
            timerStarted: null,
            elem: util.getById('cooldown-timer')
        };
        pauseCheck = true;

        vent.on('update', update);
        vent.on('render', render);
        vent.on('deactivate', resetCooldown);
        vent.on('activate', activateCooldown);
        vent.on('elemental-progress', function( percent ){
            cfg.cooldownTimer.percent = percent;
        });
        vent.on('start-game', function(){
            pauseCheck = false;
            cooldownTimer.timerStarted = new Date().getTime();
        });
        vent.on('activate', function( element ){
            for (var i = 0; i < icons.length; i++) {
                icons[i].classList.remove('on');
            }
            activeIcon = util.getById(element);
            activeIcon.classList.add('on');
        });
        vent.on('cooldown-end', function(){
            for (var i = 0; i < icons.length; i++) {
                icons[i].classList.add('on');
            }
        });

    };

    bindEvents = function(){
        vent.on('start', function( obj ){
            init(obj);
        });
        vent.on('enemy-down', function(){
            score += 2;
        });
    };

    activateCooldown = function( element ){
        cooldownTimer.current = 10e3;
        cooldownTimer.lastChecked = new Date().getTime();
        cfg.cooldownTimer.fillStyle.current = cfg.cooldownTimer.fillStyle[element];
        if ( element === 'earth' ) {
            resetCooldown();
        }
    };

    resetCooldown = function(){
        if ( activeIcon ) {
            activeIcon.classList.remove('on');
        }
        cooldownTimer.current = 20e3;
        cooldownTimer.display = 20;
        cooldownTimer.lastChecked = new Date().getTime();
        cfg.cooldownTimer.fillStyle.current = cfg.cooldownTimer.fillStyle.default;
        cfg.cooldownTimer.percent = 0;
        cooldownTimer.timerStarted = new Date().getTime();
        pauseCheck = false;
    };

    checkCooldown = function(){
        if ( pauseCheck ) {
            return;
        }
        if ( cooldownTimer.display <= 0 ) {
            vent.emit('cooldown-end');
            cfg.cooldownTimer.fillStyle.current = 'rgba(120, 220, 0, 1)';
            cfg.cooldownTimer.percent = 1;
            pauseCheck = true;
            return;
        }

        var now = new Date().getTime(),
            diff = now - cooldownTimer.timerStarted;

        cooldownTimer.current = diff;
        cooldownTimer.lastChecked = now;
        cfg.cooldownTimer.percent = (now - cooldownTimer.timerStarted) / 20e3;
        cooldownTimer.display = cooldownTimer.max - parseInt(cooldownTimer.current/1000);
    };

    update = function(){
        checkCooldown();
    };

    render = function(){
        ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
        draw('score');
        draw('cooldownTimer');
    };

    draw = function( name ){
        drawItems[name](ctx);
    };

    bindEvents();

});
<|endoftext|>


<commit_before>// JavaScript Document

// Scripts written by init_author_name @ init_author_company

module.exports = {
    // config task, generate configuration file for uploads & BrowserSync and prompt dev for input
    config(gulp, plugins, requested = "") {
        // generate config.json and start other functions
        const generate_config = (file_name, mode = "ftp") => {
            // store array of config file URIs
            const data_source = {
                bs:    "https://gist.githubusercontent.com/JacobDB/63852a9ad21207ed195aa1fd75bfeeb8/raw/7d011d22bef966f06d0c8b84d50891419738ac8b/.bsconfig",
                ftp:   "https://gist.githubusercontent.com/JacobDB/b41b59c11f10e6b5e4fe5bc4ab40d805/raw/0f408964b8f3c77ed0ae452ab3d2ba2c130e1acd/.ftpconfig",
                sftp:  "https://gist.githubusercontent.com/JacobDB/cad97b5c4e947b40e3b54c6022fec887/raw/4829ebdc5d45cea7dce8cc3109a05501b159f992/.ftpconfig",
                rsync: "https://gist.githubusercontent.com/JacobDB/71f24559e2291c07256edf8a48028ae5/raw/28b31aff5a494daf13f5be679d51c67f7782dc68/.rsyncconfig",
            };

            // check which config URI to use
            const gist_url = typeof file_name !== "undefined" ? (file_name === ".bsconfig" ? data_source.bs : (file_name === ".ftpconfig" ? (mode === "sftp" ? data_source.sftp : data_source.ftp) : (mode === "rsync" ? data_source.rsync : ""))) : "";

            // write the file
            return new Promise((resolve, reject) => {
                // open the file
                plugins.fs.stat(file_name, (err) => {
                    // make sure the file doesn't exist (or otherwise has an error)
                    if (err !== null) {
                        // get the file contents from the gist_url
                        plugins.request.get(gist_url, function (error, response, body) {
                            if (!error && response.statusCode == 200) {
                                // write the file
                                plugins.fs.writeFile(file_name, body, "utf8", () => {
                                    // resolve the promise
                                    resolve();
                                });
                            } else {
                                reject();
                            }
                        });
                    } else {
                        reject();
                    }
                });
            });
        };

        // configue JSON data
        const configure_json = (file_name, namespace, options) => {
            const prompts    = [];
            const configured = plugins.json.readFileSync(file_name).configured;

            // construct the prompts
            Object.keys(options).forEach(option => {
                const properties = options[option];

                // construct the prompt
                const prompt = {
                    name:    option,
                    message: namespace + " " + option + ": ",
                };

                // construct the prompt
                Object.keys(properties).forEach(property => {
                    prompt[property] = properties[property];
                });

                // check if the setting has no value or is explicitly requested
                if ((requested !== "" && requested === namespace && (global.settings[namespace][option] === "" || configured === false)) || gulp.seq.indexOf("config") >= 0 && (requested === "" || requested === namespace) && (global.settings[namespace][option] === "" || plugins.argv[namespace] || configured === false)) {
                    prompts.push(prompt);
                }
            });

            return new Promise ((resolve, reject) => {
                // prompt the user
                gulp.src(file_name)
                    .pipe(plugins.prompt.prompt(prompts, (res) => {
                        // read the file to retrieve the JSON data
                        const json_data = plugins.json.readFileSync(file_name);

                        // update options in JSON data
                        Object.keys(options).forEach(key => {
                            // turn stringy true/false values in to booleans
                            const value = res[key] === "true" ? true : (res[key] === "false" ? false : res[key]);

                            // update the data
                            json_data[key] = value;

                            // store the updated data in the global settings
                            global.settings[namespace][key] = value;
                        });

                        // update file with new JSON data
                        plugins.json.writeFileSync(file_name, json_data);
                    })).on("end", () => {
                        // read the file to retrieve the JSON data
                        const json_data = plugins.json.readFileSync(file_name);

                        // mark as configured
                        json_data["configured"] = true;

                        // update file with new JSON data
                        plugins.json.writeFileSync(file_name, json_data);

                        // resolve the promise
                        resolve();
                    }).on("error", () => {
                        // reject the promise
                        reject();
                    });
            });
        };

        const download_configs = () => {
            // download all config files
            return Promise.all([
                generate_config(".bsconfig", "browsersync"),
                generate_config(".ftpconfig", (plugins.argv["sftp"] ? "sftp" : (plugins.argv["ftps"] ? "ftps" : "ftp"))),
                generate_config(".rsyncconfig", "rsync")
            ]);
        };

        const configure_browsersync = () => {
            // read browsersync settings from .bsconfig
            global.settings.browsersync = plugins.json.readFileSync(".bsconfig");

            // construct the prompts
            const prompts = {
                proxy: {
                    default: global.settings.browsersync.proxy === "" ? "localhost" : global.settings.browsersync.proxy,
                    type:    "input",
                },
                port: {
                    default: global.settings.browsersync.port === "" ? "8080" : global.settings.browsersync.port,
                    type:    "input",
                },
                open: {
                    default: global.settings.browsersync.open === "local" ? 1 : (global.settings.browsersync.open === "external" ? 2 : (global.settings.browsersync.open === "ui" ? 3 : (global.settings.browsersync.open === "ui-external" ? 4 : (global.settings.browsersync.open === "tunnel" ? 5 : (global.settings.browsersync.open === "false" ? 6 : 0))))),
                    type:    "list",
                    choices: ["true", "local", "external", "ui", "ui-external", "tunnel", "false"],
                },
                notify: {
                    default: global.settings.browsersync.notify === true ? 0 : 1,
                    type:    "list",
                    choices: ["true", "false"],
                },
            };

            // configure the JSON
            return configure_json(".bsconfig", "browsersync", prompts);
        };

        const configure_ftp = () => {
            // read ftp settings from .ftpconfig
            global.settings.ftp = plugins.json.readFileSync(".ftpconfig");

            // construct the prompts
            const prompts = {
                protocol: {
                    default: global.settings.ftp.protocol === "ftps" ? 1 : 0,
                    type:    "list",
                    choices: ["ftp", "ftps"],
                },
                host: {
                    default: global.settings.ftp.host === "" ? "" : global.settings.ftp.host,
                    type:    "input",
                },
                port: {
                    default: global.settings.ftp.port === "" ? "" : global.settings.ftp.port,
                    type:    "input",
                },
                user: {
                    default: global.settings.ftp.user === "" ? "" : global.settings.ftp.user,
                    type:    "input",
                },
                pass: {
                    default: global.settings.ftp.pass === "" ? "" : global.settings.ftp.pass,
                    type:    "password",
                },
                remote: {
                    default: global.settings.ftp.remote === "" ? "" : global.settings.ftp.remote,
                    type:    "input",
                },
            };

            // don't prompt for protocol for SFTP
            if (global.settings.ftp.protocol === "sftp") {
                delete prompts.protocol;
            }

            // configure the JSON
            return configure_json(".ftpconfig", "ftp", prompts);
        };

        const configure_rsync = () => {
            // read ftp settings from .ftpconfig
            global.settings.rsync = plugins.json.readFileSync(".rsyncconfig");

            // construct the prompts
            const prompts = {
                root: {
                    default: global.settings.rsync.root === "" ? "dev/" : global.settings.rsync.root,
                    type:    "input",
                },
                hostname: {
                    default: global.settings.rsync.hostname === "" ? "localhost" : global.settings.rsync.hostname,
                    type:    "input",
                },
                username: {
                    default: global.settings.rsync.username === "" ? "root" : global.settings.rsync.username,
                    type:    "input",
                },
                destination: {
                    default: global.settings.rsync.destination === "" ? "/var/www/html" : global.settings.rsync.destination,
                    type:    "input",
                },
                archive: {
                    default: global.settings.rsync.archive === true ? 0 : 1,
                    type:    "list",
                    choices: ["true", "false"],
                },
                silent: {
                    default: global.settings.rsync.silent === true ? 0 : 1,
                    type:    "list",
                    choices: ["true", "false"],
                },
                compress: {
                    default: global.settings.rsync.compress === true ? 0 : 1,
                    type:    "list",
                    choices: ["true", "false"],
                },
            };

            // configure the JSON
            return configure_json(".rsyncconfig", "rsync", prompts);
        };

        // download and configure config files
        return download_configs()
            .then(configure_browsersync)
            .then(configure_ftp)
            .then(configure_rsync);
    }
};
<commit_msg>Set rsync defualt root to current environment<commit_after>// JavaScript Document

// Scripts written by init_author_name @ init_author_company

module.exports = {
    // config task, generate configuration file for uploads & BrowserSync and prompt dev for input
    config(gulp, plugins, requested = "") {
        // generate config.json and start other functions
        const generate_config = (file_name, mode = "ftp") => {
            // store array of config file URIs
            const data_source = {
                bs:    "https://gist.githubusercontent.com/JacobDB/63852a9ad21207ed195aa1fd75bfeeb8/raw/7d011d22bef966f06d0c8b84d50891419738ac8b/.bsconfig",
                ftp:   "https://gist.githubusercontent.com/JacobDB/b41b59c11f10e6b5e4fe5bc4ab40d805/raw/0f408964b8f3c77ed0ae452ab3d2ba2c130e1acd/.ftpconfig",
                sftp:  "https://gist.githubusercontent.com/JacobDB/cad97b5c4e947b40e3b54c6022fec887/raw/4829ebdc5d45cea7dce8cc3109a05501b159f992/.ftpconfig",
                rsync: "https://gist.githubusercontent.com/JacobDB/71f24559e2291c07256edf8a48028ae5/raw/28b31aff5a494daf13f5be679d51c67f7782dc68/.rsyncconfig",
            };

            // check which config URI to use
            const gist_url = typeof file_name !== "undefined" ? (file_name === ".bsconfig" ? data_source.bs : (file_name === ".ftpconfig" ? (mode === "sftp" ? data_source.sftp : data_source.ftp) : (mode === "rsync" ? data_source.rsync : ""))) : "";

            // write the file
            return new Promise((resolve, reject) => {
                // open the file
                plugins.fs.stat(file_name, (err) => {
                    // make sure the file doesn't exist (or otherwise has an error)
                    if (err !== null) {
                        // get the file contents from the gist_url
                        plugins.request.get(gist_url, function (error, response, body) {
                            if (!error && response.statusCode == 200) {
                                // write the file
                                plugins.fs.writeFile(file_name, body, "utf8", () => {
                                    // resolve the promise
                                    resolve();
                                });
                            } else {
                                reject();
                            }
                        });
                    } else {
                        reject();
                    }
                });
            });
        };

        // configue JSON data
        const configure_json = (file_name, namespace, options) => {
            const prompts    = [];
            const configured = plugins.json.readFileSync(file_name).configured;

            // construct the prompts
            Object.keys(options).forEach(option => {
                const properties = options[option];

                // construct the prompt
                const prompt = {
                    name:    option,
                    message: namespace + " " + option + ": ",
                };

                // construct the prompt
                Object.keys(properties).forEach(property => {
                    prompt[property] = properties[property];
                });

                // check if the setting has no value or is explicitly requested
                if ((requested !== "" && requested === namespace && (global.settings[namespace][option] === "" || configured === false)) || gulp.seq.indexOf("config") >= 0 && (requested === "" || requested === namespace) && (global.settings[namespace][option] === "" || plugins.argv[namespace] || configured === false)) {
                    prompts.push(prompt);
                }
            });

            return new Promise ((resolve, reject) => {
                // prompt the user
                gulp.src(file_name)
                    .pipe(plugins.prompt.prompt(prompts, (res) => {
                        // read the file to retrieve the JSON data
                        const json_data = plugins.json.readFileSync(file_name);

                        // update options in JSON data
                        Object.keys(options).forEach(key => {
                            // turn stringy true/false values in to booleans
                            const value = res[key] === "true" ? true : (res[key] === "false" ? false : res[key]);

                            // update the data
                            json_data[key] = value;

                            // store the updated data in the global settings
                            global.settings[namespace][key] = value;
                        });

                        // update file with new JSON data
                        plugins.json.writeFileSync(file_name, json_data);
                    })).on("end", () => {
                        // read the file to retrieve the JSON data
                        const json_data = plugins.json.readFileSync(file_name);

                        // mark as configured
                        json_data["configured"] = true;

                        // update file with new JSON data
                        plugins.json.writeFileSync(file_name, json_data);

                        // resolve the promise
                        resolve();
                    }).on("error", () => {
                        // reject the promise
                        reject();
                    });
            });
        };

        const download_configs = () => {
            // download all config files
            return Promise.all([
                generate_config(".bsconfig", "browsersync"),
                generate_config(".ftpconfig", (plugins.argv["sftp"] ? "sftp" : (plugins.argv["ftps"] ? "ftps" : "ftp"))),
                generate_config(".rsyncconfig", "rsync")
            ]);
        };

        const configure_browsersync = () => {
            // read browsersync settings from .bsconfig
            global.settings.browsersync = plugins.json.readFileSync(".bsconfig");

            // construct the prompts
            const prompts = {
                proxy: {
                    default: global.settings.browsersync.proxy === "" ? "localhost" : global.settings.browsersync.proxy,
                    type:    "input",
                },
                port: {
                    default: global.settings.browsersync.port === "" ? "8080" : global.settings.browsersync.port,
                    type:    "input",
                },
                open: {
                    default: global.settings.browsersync.open === "local" ? 1 : (global.settings.browsersync.open === "external" ? 2 : (global.settings.browsersync.open === "ui" ? 3 : (global.settings.browsersync.open === "ui-external" ? 4 : (global.settings.browsersync.open === "tunnel" ? 5 : (global.settings.browsersync.open === "false" ? 6 : 0))))),
                    type:    "list",
                    choices: ["true", "local", "external", "ui", "ui-external", "tunnel", "false"],
                },
                notify: {
                    default: global.settings.browsersync.notify === true ? 0 : 1,
                    type:    "list",
                    choices: ["true", "false"],
                },
            };

            // configure the JSON
            return configure_json(".bsconfig", "browsersync", prompts);
        };

        const configure_ftp = () => {
            // read ftp settings from .ftpconfig
            global.settings.ftp = plugins.json.readFileSync(".ftpconfig");

            // construct the prompts
            const prompts = {
                protocol: {
                    default: global.settings.ftp.protocol === "ftps" ? 1 : 0,
                    type:    "list",
                    choices: ["ftp", "ftps"],
                },
                host: {
                    default: global.settings.ftp.host === "" ? "" : global.settings.ftp.host,
                    type:    "input",
                },
                port: {
                    default: global.settings.ftp.port === "" ? "" : global.settings.ftp.port,
                    type:    "input",
                },
                user: {
                    default: global.settings.ftp.user === "" ? "" : global.settings.ftp.user,
                    type:    "input",
                },
                pass: {
                    default: global.settings.ftp.pass === "" ? "" : global.settings.ftp.pass,
                    type:    "password",
                },
                remote: {
                    default: global.settings.ftp.remote === "" ? "" : global.settings.ftp.remote,
                    type:    "input",
                },
            };

            // don't prompt for protocol for SFTP
            if (global.settings.ftp.protocol === "sftp") {
                delete prompts.protocol;
            }

            // configure the JSON
            return configure_json(".ftpconfig", "ftp", prompts);
        };

        const configure_rsync = () => {
            // read ftp settings from .ftpconfig
            global.settings.rsync = plugins.json.readFileSync(".rsyncconfig");

            // construct the prompts
            const prompts = {
                root: {
                    default: global.settings.rsync.root === "" ? (plugins.argv.dist ? global.settings.paths.dist : global.settings.paths.dev) : global.settings.rsync.root,
                    type:    "input",
                },
                hostname: {
                    default: global.settings.rsync.hostname === "" ? "localhost" : global.settings.rsync.hostname,
                    type:    "input",
                },
                username: {
                    default: global.settings.rsync.username === "" ? "root" : global.settings.rsync.username,
                    type:    "input",
                },
                destination: {
                    default: global.settings.rsync.destination === "" ? "/var/www/html" : global.settings.rsync.destination,
                    type:    "input",
                },
                archive: {
                    default: global.settings.rsync.archive === true ? 0 : 1,
                    type:    "list",
                    choices: ["true", "false"],
                },
                silent: {
                    default: global.settings.rsync.silent === true ? 0 : 1,
                    type:    "list",
                    choices: ["true", "false"],
                },
                compress: {
                    default: global.settings.rsync.compress === true ? 0 : 1,
                    type:    "list",
                    choices: ["true", "false"],
                },
            };

            // configure the JSON
            return configure_json(".rsyncconfig", "rsync", prompts);
        };

        // download and configure config files
        return download_configs()
            .then(configure_browsersync)
            .then(configure_ftp)
            .then(configure_rsync);
    }
};
<|endoftext|>


<commit_before>// JavaScript Document

// Scripts written by YOURNAME @ YOURCOMPANY

module.exports = {
    // config task, generate configuration file for uploads & BrowserSync and prompt dev for input
    config(gulp, plugins, requested = "") {
        // generate config.json and start other functions
        const generate_config = (file_name, mode = "ftp", callback) => {
            const data_source = {
                bs:   "https://gist.githubusercontent.com/JacobDB/63852a9ad21207ed195aa1fd75bfeeb8/raw/7d011d22bef966f06d0c8b84d50891419738ac8b/.bsconfig",
                ftp:  "https://gist.githubusercontent.com/JacobDB/b41b59c11f10e6b5e4fe5bc4ab40d805/raw/0f408964b8f3c77ed0ae452ab3d2ba2c130e1acd/.ftpconfig",
                sftp: "https://gist.githubusercontent.com/JacobDB/cad97b5c4e947b40e3b54c6022fec887/raw/4829ebdc5d45cea7dce8cc3109a05501b159f992/.ftpconfig",
            };

            if (typeof file_name !== "undefined") {
                return plugins.fs.stat(file_name, (err) => {
                    if (err !== null) {
                        let gist_url  = "";

                        if (file_name === ".bsconfig") {
                            gist_url = data_source.bs;
                        } else if (file_name === ".ftpconfig") {
                            if (mode === "sftp") {
                                gist_url = data_source.sftp;
                            } else {
                                gist_url = data_source.ftp;
                            }
                        }

                        if (gist_url !== "") {
                            plugins.request.get(gist_url, function (error, response, body) {
                                if (!error && response.statusCode == 200) {
                                    plugins.fs.writeFile(file_name, body, "utf8", () => {
                                        if (typeof callback === "function") {
                                            return callback();
                                        }
                                    });
                                } else if (typeof callback === "function") {
                                    return callback();
                                }
                            });
                        } else if (typeof callback === "function") {
                            return callback();
                        }
                    } else if (typeof callback === "function") {
                        return callback();
                    }
                });
            } else if (typeof callback === "function") {
                return callback();
            }
        };

        // configue JSON data
        const configure_json = (file_name, namespace, options, callback) => {
            const prompts    = [];
            const configured = plugins.json.readFileSync(file_name).configured;

            // construct the prompts
            Object.keys(options).forEach(option => {
                const properties = options[option];

                // construct the prompt
                const prompt = {
                    name:    option,
                    message: namespace + " " + option + ": ",
                };

                // construct the prompt
                Object.keys(properties).forEach(property => {
                    prompt[property] = properties[property];
                });

                // check if the setting has no value or is explicitly requested
                if ((requested !== "" && requested === namespace && (global.settings[namespace][option] === "" || configured === false)) || gulp.seq.indexOf("config") >= 0 && (requested === "" || requested === namespace) && (global.settings[namespace][option] === "" || plugins.argv[namespace] || configured === false)) {
                    prompts.push(prompt);
                }
            });

            if (prompts.length > 0) {
                // prompt the user
                gulp.src(file_name)
                    .pipe(plugins.prompt.prompt(prompts, (res) => {
                        // read the file to retrieve the JSON data
                        const json_data = plugins.json.readFileSync(file_name);

                        // update options in JSON data
                        Object.keys(options).forEach(key => {
                            // turn stringy true/false values in to booleans
                            const value = res[key] === "true" ? true : (res[key] === "false" ? false : res[key]);

                            // update the data
                            json_data[key] = value;

                            // store the updated data in the global settings
                            global.settings[namespace][key] = value;
                        });

                        // update file with new JSON data
                        plugins.json.writeFileSync(file_name, json_data);
                    })).on("end", () => {
                        // read the file to retrieve the JSON data
                        const json_data = plugins.json.readFileSync(file_name);

                        // mark as configured
                        json_data["configured"] = true;

                        // update file with new JSON data
                        plugins.json.writeFileSync(file_name, json_data);

                        if (typeof callback === "function") {
                            return callback();
                        }
                    });
            } else if (typeof callback === "function") {
                return callback();
            }
        };

        return new Promise ((resolve) => {
            // generate .bsconfig
            generate_config(".bsconfig", "browsersync", () => {
                const browsersync_config = plugins.json.readFileSync(".bsconfig");

                // read browsersync settings from .bsconfig
                global.settings.browsersync        = {};
                global.settings.browsersync.proxy  = browsersync_config.proxy;
                global.settings.browsersync.port   = browsersync_config.port;
                global.settings.browsersync.open   = browsersync_config.open;
                global.settings.browsersync.notify = browsersync_config.notify;

                const prompts = {
                    proxy: {
                        default: global.settings.browsersync.proxy === "" ? "localhost" : global.settings.browsersync.proxy,
                        type:    "input",
                    },
                    port: {
                        default: global.settings.browsersync.port === "" ? "8080" : global.settings.browsersync.port,
                        type:    "input",
                    },
                    open: {
                        default: global.settings.browsersync.open === "local" ? 1 : (global.settings.browsersync.open === "external" ? 2 : (global.settings.browsersync.open === "ui" ? 3 : (global.settings.browsersync.open === "ui-external" ? 4 : (global.settings.browsersync.open === "tunnel" ? 5 : (global.settings.browsersync.open === "false" ? 6 : 0))))),
                        type:    "list",
                        choices: ["true", "local", "external", "ui", "ui-external", "tunnel", "false"],
                    },
                    notify: {
                        default: global.settings.browsersync.notify === true ? 0 : 1,
                        type:    "list",
                        choices: ["true", "false"],
                    },
                };

                configure_json(".bsconfig", "browsersync", prompts, () => {
                    generate_config(".ftpconfig", (plugins.argv["sftp"] ? "sftp" : (plugins.argv["ftps"] ? "ftps" : "ftp")), () => {
                        const ftp_config = plugins.json.readFileSync(".ftpconfig");

                        // read remote settings from .ftpconfig
                        global.settings.ftp          = {};
                        global.settings.ftp.protocol = ftp_config.protocol !== "sftp" && ftp_config.secure === true ? "ftps" : ftp_config.protocol;
                        global.settings.ftp.host     = ftp_config.host;
                        global.settings.ftp.port     = ftp_config.port;
                        global.settings.ftp.user     = ftp_config.user;
                        global.settings.ftp.pass     = ftp_config.pass;
                        global.settings.ftp.remote   = ftp_config.remote;

                        const prompts = {
                            protocol: {
                                default: global.settings.ftp.protocol === "ftps" ? 1 : 0,
                                type:    "list",
                                choices: ["ftp", "ftps"],
                            },
                            host: {
                                default: global.settings.ftp.host === "" ? "" : global.settings.ftp.host,
                                type:    "input",
                            },
                            port: {
                                default: global.settings.ftp.port === "" ? "" : global.settings.ftp.port,
                                type:    "input",
                            },
                            user: {
                                default: global.settings.ftp.user === "" ? "" : global.settings.ftp.user,
                                type:    "input",
                            },
                            pass: {
                                default: global.settings.ftp.pass === "" ? "" : global.settings.ftp.pass,
                                type:    "password",
                            },
                            remote: {
                                default: global.settings.ftp.remote === "" ? "" : global.settings.ftp.remote,
                                type:    "input",
                            },
                        };

                        // don't prompt for protocol for SFTP
                        if (global.settings.ftp.protocol === "sftp") {
                            delete prompts.protocol;
                        }

                        configure_json(".ftpconfig", "ftp", prompts, () => {
                            // resolve the promise
                            return resolve();
                        });
                    });
                });
            });
        });
    }
};
<commit_msg>Move gist_url in to a ternary to save an if statement<commit_after>// JavaScript Document

// Scripts written by YOURNAME @ YOURCOMPANY

module.exports = {
    // config task, generate configuration file for uploads & BrowserSync and prompt dev for input
    config(gulp, plugins, requested = "") {
        // generate config.json and start other functions
        const generate_config = (file_name, mode = "ftp", callback) => {
            const data_source = {
                bs:   "https://gist.githubusercontent.com/JacobDB/63852a9ad21207ed195aa1fd75bfeeb8/raw/7d011d22bef966f06d0c8b84d50891419738ac8b/.bsconfig",
                ftp:  "https://gist.githubusercontent.com/JacobDB/b41b59c11f10e6b5e4fe5bc4ab40d805/raw/0f408964b8f3c77ed0ae452ab3d2ba2c130e1acd/.ftpconfig",
                sftp: "https://gist.githubusercontent.com/JacobDB/cad97b5c4e947b40e3b54c6022fec887/raw/4829ebdc5d45cea7dce8cc3109a05501b159f992/.ftpconfig",
            };

            const gist_url = typeof file_name !== "undefined" ? (file_name === ".bsconfig" ? data_source.bs : (file_name === ".ftpconfig" ? (mode === "sftp" ? data_source.sft : data_source.ftp) : "")) : "";

            if (typeof file_name !== "undefined" && gist_url !== "") {
                return plugins.fs.stat(file_name, (err) => {
                    if (err !== null) {
                        plugins.request.get(gist_url, function (error, response, body) {
                            if (!error && response.statusCode == 200) {
                                plugins.fs.writeFile(file_name, body, "utf8", () => {
                                    if (typeof callback === "function") {
                                        return callback();
                                    }
                                });
                            } else if (typeof callback === "function") {
                                return callback();
                            }
                        });
                    } else if (typeof callback === "function") {
                        return callback();
                    }
                });
            } else if (typeof callback === "function") {
                return callback();
            }
        };

        // configue JSON data
        const configure_json = (file_name, namespace, options, callback) => {
            const prompts    = [];
            const configured = plugins.json.readFileSync(file_name).configured;

            // construct the prompts
            Object.keys(options).forEach(option => {
                const properties = options[option];

                // construct the prompt
                const prompt = {
                    name:    option,
                    message: namespace + " " + option + ": ",
                };

                // construct the prompt
                Object.keys(properties).forEach(property => {
                    prompt[property] = properties[property];
                });

                // check if the setting has no value or is explicitly requested
                if ((requested !== "" && requested === namespace && (global.settings[namespace][option] === "" || configured === false)) || gulp.seq.indexOf("config") >= 0 && (requested === "" || requested === namespace) && (global.settings[namespace][option] === "" || plugins.argv[namespace] || configured === false)) {
                    prompts.push(prompt);
                }
            });

            if (prompts.length > 0) {
                // prompt the user
                gulp.src(file_name)
                    .pipe(plugins.prompt.prompt(prompts, (res) => {
                        // read the file to retrieve the JSON data
                        const json_data = plugins.json.readFileSync(file_name);

                        // update options in JSON data
                        Object.keys(options).forEach(key => {
                            // turn stringy true/false values in to booleans
                            const value = res[key] === "true" ? true : (res[key] === "false" ? false : res[key]);

                            // update the data
                            json_data[key] = value;

                            // store the updated data in the global settings
                            global.settings[namespace][key] = value;
                        });

                        // update file with new JSON data
                        plugins.json.writeFileSync(file_name, json_data);
                    })).on("end", () => {
                        // read the file to retrieve the JSON data
                        const json_data = plugins.json.readFileSync(file_name);

                        // mark as configured
                        json_data["configured"] = true;

                        // update file with new JSON data
                        plugins.json.writeFileSync(file_name, json_data);

                        if (typeof callback === "function") {
                            return callback();
                        }
                    });
            } else if (typeof callback === "function") {
                return callback();
            }
        };

        return new Promise ((resolve) => {
            // generate .bsconfig
            generate_config(".bsconfig", "browsersync", () => {
                const browsersync_config = plugins.json.readFileSync(".bsconfig");

                // read browsersync settings from .bsconfig
                global.settings.browsersync        = {};
                global.settings.browsersync.proxy  = browsersync_config.proxy;
                global.settings.browsersync.port   = browsersync_config.port;
                global.settings.browsersync.open   = browsersync_config.open;
                global.settings.browsersync.notify = browsersync_config.notify;

                const prompts = {
                    proxy: {
                        default: global.settings.browsersync.proxy === "" ? "localhost" : global.settings.browsersync.proxy,
                        type:    "input",
                    },
                    port: {
                        default: global.settings.browsersync.port === "" ? "8080" : global.settings.browsersync.port,
                        type:    "input",
                    },
                    open: {
                        default: global.settings.browsersync.open === "local" ? 1 : (global.settings.browsersync.open === "external" ? 2 : (global.settings.browsersync.open === "ui" ? 3 : (global.settings.browsersync.open === "ui-external" ? 4 : (global.settings.browsersync.open === "tunnel" ? 5 : (global.settings.browsersync.open === "false" ? 6 : 0))))),
                        type:    "list",
                        choices: ["true", "local", "external", "ui", "ui-external", "tunnel", "false"],
                    },
                    notify: {
                        default: global.settings.browsersync.notify === true ? 0 : 1,
                        type:    "list",
                        choices: ["true", "false"],
                    },
                };

                configure_json(".bsconfig", "browsersync", prompts, () => {
                    generate_config(".ftpconfig", (plugins.argv["sftp"] ? "sftp" : (plugins.argv["ftps"] ? "ftps" : "ftp")), () => {
                        const ftp_config = plugins.json.readFileSync(".ftpconfig");

                        // read remote settings from .ftpconfig
                        global.settings.ftp          = {};
                        global.settings.ftp.protocol = ftp_config.protocol !== "sftp" && ftp_config.secure === true ? "ftps" : ftp_config.protocol;
                        global.settings.ftp.host     = ftp_config.host;
                        global.settings.ftp.port     = ftp_config.port;
                        global.settings.ftp.user     = ftp_config.user;
                        global.settings.ftp.pass     = ftp_config.pass;
                        global.settings.ftp.remote   = ftp_config.remote;

                        const prompts = {
                            protocol: {
                                default: global.settings.ftp.protocol === "ftps" ? 1 : 0,
                                type:    "list",
                                choices: ["ftp", "ftps"],
                            },
                            host: {
                                default: global.settings.ftp.host === "" ? "" : global.settings.ftp.host,
                                type:    "input",
                            },
                            port: {
                                default: global.settings.ftp.port === "" ? "" : global.settings.ftp.port,
                                type:    "input",
                            },
                            user: {
                                default: global.settings.ftp.user === "" ? "" : global.settings.ftp.user,
                                type:    "input",
                            },
                            pass: {
                                default: global.settings.ftp.pass === "" ? "" : global.settings.ftp.pass,
                                type:    "password",
                            },
                            remote: {
                                default: global.settings.ftp.remote === "" ? "" : global.settings.ftp.remote,
                                type:    "input",
                            },
                        };

                        // don't prompt for protocol for SFTP
                        if (global.settings.ftp.protocol === "sftp") {
                            delete prompts.protocol;
                        }

                        configure_json(".ftpconfig", "ftp", prompts, () => {
                            // resolve the promise
                            return resolve();
                        });
                    });
                });
            });
        });
    }
};
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp'),
    deploy = require('gulp-gh-pages');

gulp.task('deploy', ['clean'], function () {
  gulp.start('build', function () {
   return gulp.src('./dist/**/*')
        .pipe(deploy('https://github.com/dojoapps/saidacerta.com.git'));
  })
});
<commit_msg>fix deploy louco<commit_after>'use strict';

var gulp = require('gulp'),
    deploy = require('gulp-gh-pages');

gulp.task('deploy', ['clean'], function () {
  return gulp.start('build', function () {
   return gulp.src('./dist/**/*')
        .pipe(deploy('https://github.com/dojoapps/saidacerta.com.git'));
  })
});
<|endoftext|>