<commit_before>/*
   Custom, Unoptimized Audiocodes Log to SIP/HEP3 Parser w/ reassembly of rows
   (C) 2020 QXIP BV
*/

var base_filter = require('@pastash/pastash').base_filter,
  util = require('util'),
  logger = require('@pastash/pastash').logger;

var moment = require('moment');
var LRU = require("lru-cache")
  , sidcache = new LRU(1000)
  , expire = 10000 * 60 * 60

function FilterAppAudiocodes() {
  base_filter.BaseFilter.call(this);
  this.mergeConfig({
    name: 'AppAudiocodes',
    optional_params: ['correlation_hdr','bypass', 'debug', 'logs', 'localip', 'localport', 'correlation_contact', 'qos', 'autolocal', 'version'],
    default_values: {
      'correlation_contact': false,
      'correlation_hdr': false,
      'debug': false,
      'bypass': false,
      'logs': false,
      'qos': true,
      'autolocal': false,
      'localip': '127.0.0.1',
      'localport': 5060,
      'version': '7.20A.260.012'
    },
    start_hook: this.start,
  });
}

util.inherits(FilterAppAudiocodes, base_filter.BaseFilter);

FilterAppAudiocodes.prototype.start = function(callback) {
logger.info('Initialized App Audiocodes SysLog to SIP/HEP parser');
  this.postProcess = function(ipcache,last,type){
	 if(!last||!ipcache) return;
   	 last = last.replace(/#012/g, '\r\n').trim() + "\r\n\r\n";
         var rcinfo = {
              type: 'HEP',
              version: 3,
              payload_type: type ? 'LOG' :'SIP',
              ip_family: 2,
              protocol: 17,
              proto_type: type || 1,
              correlation_id: ipcache.callId || '',
              srcIp: ipcache.srcIp || this.localip,
              srcPort: ipcache.srcPort || 0,
              dstIp: ipcache.dstIp || this.localip,
              dstPort: ipcache.dstPort || 0,
              time_sec: ipcache.ts || parseInt(new Date().getTime() / 1000),
              time_usec: ipcache.usec || new Date().getMilliseconds()
            };

	 // EXTRACT CORRELATION HEADER, IF ANY
	  if (this.correlation_hdr && rcinfo.proto_type == 1 && last.startsWith('INVITE')) {
          	var xcid = last.match(this.correlation_hdr+":\s?(.*)\r\n\r\n");
               	if (xcid && xcid[1]) rcinfo.correlation_id = xcid[1].trim();
                        if (this.debug) logger.info('auto correlation pick', rcinfo.correlation_id);
         }

	 if (this.correlation_contact && rcinfo.proto_type == 1 && last.startsWith('INVITE')) {
		var extract = /x-c=(.*?)\//.exec(last);
		if (extract[1]) {
			rcinfo.correlation_id = extract[1];
			if (this.debug) logger.info('auto correlation pick', rcinfo.correlation_id);
		}
	 }

	 if (last.indexOf('2.0/TCP') !== -1 || last.indexOf('2.0/TLS') !== -1 ){
		rcinfo.protocol = 6;
		if (this.autolocal) rcinfo.dstPort = 5061;
         }

         if (last && rcinfo) {
           var data = { payload: last, rcinfo: rcinfo };
	   return data;
         }
  }
  callback();
};

var last = '';
var ipcache = {};
var alias = {};

var hold;
var cache;
var seq;

FilterAppAudiocodes.prototype.process = function(data) {

   var line = data.message.toString();
   var ipcache = {};
   if (this.debug) console.info('DEBUG', line);
   var message = /^.*?\[S=([0-9]+)\].*?\[SID=.*?\]\s?(.*)\[Time:.*\]$/
   var test = message.exec(line.replace(/\n/g, '#012'));
   if(hold && line) {
        if (this.debug) logger.error('Next packet number', test[1]);
        if (parseInt(test[1]) == seq + 1) {
	  line = cache + ( test ? test[2] : '');
	  hold = false;
	  cache = '';
	  if (this.debug) console.info('reassembled line', line);
        }
   }

   line = line.replace(/\n/g, '#012');

   var ids = /\[SID=(?<mac>.*?):(?<seq>.*?):(?<sid>.*?)\]/.exec(line) || [];
   if (this.debug) logger.error('SESSION SID',ids[3]);

   if (line.indexOf('Incoming SIP Message') !== -1) {
      try {
	   // var regex = /(.*)---- Incoming SIP Message from (.*) to SIPInterface #[0-99] \((.*)\) (.*) TO.*--- #012(.*)#012 #012 #012(.*) \[Time:(.*)-(.*)@(.*)\]/g;
           var regex;
	   if (this.version == '7.20A.260.012') {
                regex = /(.*)---- Incoming SIP Message from (.*) to SIPInterface #[0-99] \((.*)\) (.*) TO.*--- #012(.*)#012 #012(.*)/g; //7.20A.260.012
	   } else if (this.version == '7.20A.256.511') {
                regex = /(.*)---- Incoming SIP Message from (.*) to SIPInterface #[0-99] \((.*)\) (.*) TO.*---  (.*)(.*)/g; //7.20A.256.511
	   }
	   var ip = regex.exec(line);
	   if (!ip) {
		cache = line.replace(/\[Time.*\]$/,'');
		hold = true;
                var regpackid = /.*\[S=([0-9]+)\].*/.exec(line);
                seq = parseInt(regpackid[1]);
                if (this.debug) logger.error('Cashed packet number', seq);
		logger.error('failed parsing Incoming SIP. Cache on!');
		if (this.bypass) return data;
	   } else {
		   if (ip[3]) {
			/* convert alias to IP:port */
			   ipcache.dstIp = alias[0] || this.localip;
			   ipcache.dstPort = alias[1] || this.localport;
		   }
		   ipcache.srcIp = ip[2].split(':')[0];
		   ipcache.srcPort = ip[2].split(':')[1];
		   last = ip[5];
	   	   last += '#012 #012';
		   var callid = last.match(/call-id:\s?(.*?)\s?#012/i) || [];
		   ipcache.callId = callid[1] || ids[3] || '';
		   // Cache SID to Call-ID correlation
		   sidcache.set(ids[3], ipcache.callid, expire);
		   // Seek final fragment
		   if(ip[6].includes(' SIP Message ')){
			hold = true;
			cache = line.replace(/\[Time.*\]$/,'');
		   }
		   return this.postProcess(ipcache,last);
	   }
     } catch(e) { logger.error(e, line); }

   } else if (line.indexOf('Outgoing SIP Message') !== -1) {
      try {
           var regex;
           if (this.version == '7.20A.260.012') {
                regex = /(.*)---- Outgoing SIP Message to (.*) from SIPInterface #[0-99] \((.*)\) (.*) TO.*--- #012(.*)#012 #012 (.*)/g; //7.20A.260.012
           } else if (this.version == '7.20A.256.511') {
	        regex = /(.*)---- Outgoing SIP Message to (.*) from SIPInterface #[0-99] \((.*)\) (.*) TO.*---  (.*)(.*)/g; //7.20A.256.511
           }
	   var ip = regex.exec(line);
	   if (!ip) {
		cache = line.replace(/\[Time.*\]$/,'');
		hold = true;
                var regpackid = /.*\[S=([0-9]+)\].*/.exec(line);
                seq = parseInt(regpackid[1]);
                if (this.debug) logger.error('Cashed packet number', seq);
		logger.error('failed parsing Outgoing SIP. Cache on!');
		if (this.bypass) return data;
	   } else {
		   if (ip[3]) {
			/* convert alias to IP:port */
			   ipcache.srcIp = alias[0] || this.localip;
			   ipcache.srcPort = alias[1] || this.localport;
		   }
		   ipcache.dstIp = ip[2].split(':')[0];
		   ipcache.dstPort = ip[2].split(':')[1];
		   last = ip[5];
	   	   last += '#012 #012';
		   var callid = last.match(/call-id:\s?(.*?)\s?#012/i) || [];
		   ipcache.callId = callid[1] || ids[3] || '';
		   // Cache SID to Call-ID correlation
		   sidcache.set(ids[3], ipcache.callid, expire);
		   // Seek final fragment
		   if(ip[6].includes(' SIP Message ')){
			hold = true;
			cache = line.replace(/\[Time.*\]$/,'');
		   }
		   return this.postProcess(ipcache,last);
	   }
     } catch(e) { logger.error(e, line); }

   } else if (this.autolocal && line.indexOf('Local IP Address =') !== -1) {
	var local = line.match(/Local IP Address = (.*?):(.*?),/) || [];
	if(local[1]) this.localip   = local[1];
	if(local[2]) this.localport = local[2];
   } else if (line.indexOf('CALL_END ') !== -1 && this.logs) {
	// Parser TBD page 352 @ https://www.audiocodes.com/media/10312/ltrt-41548-mediant-software-sbc-users-manual-ver-66.pdf
	var cdr = line.split(/(\s+\|)/).filter( function(e) { return e.trim().length > 1; } )
	ipcache.callId = cdr[3] || '';
	if (this.debug) logger.info('CALL_END', cdr, ipcache);
	if (this.logs) return this.postProcess(ipcache,JSON.stringify(cdr),100);

   } else if (line.indexOf('MEDIA_END ') !== -1 && this.qos) {
	// Parsed TBD page 353 @ https://www.audiocodes.com/media/10312/ltrt-41548-mediant-software-sbc-users-manual-ver-66.pdf
	var qos = line.split(/(\s+\|)/).filter( function(e) { return e.trim().length > 1; } )
	if (qos.length == 25){
		qos.splice(15, 1);
		qos.splice(5, 1);
	}
	logger.info('!!!!!!!!!!!!!! DEBUG MEDIA', qos, qos.length);
	if(qos && qos[2] && qos[21]){
		ipcache.callId = qos[2] || '';
		var response = [];
		// A-LEG
		ipcache.srcIp = qos[7];
		ipcache.srcPort = parseInt(qos[8]);
		ipcache.dstIp = qos[9];
		ipcache.dstPort = parseInt(qos[10]);
		var local_report = {
			"CORRELATION_ID": qos[2],
			"RTP_SIP_CALL_ID": qos[2],
			"MOS": 4.5 * parseInt(qos[17]) / 127,
			"TOTAL_PK": parseInt(qos[11]),
			"CODEC_NAME": qos[5],
			"DIR":0,
			"REPORT_NAME": qos[4] + "_" + qos[7] + ":" + qos[8],
			"PARTY":0,
			"TYPE":"HANGUP"
		};
		response.push(this.postProcess(ipcache,JSON.stringify(local_report),35));
		// B-LEG
		ipcache.srcIp = qos[9];
		ipcache.srcPort = parseInt(qos[10]);
		ipcache.dstIp = qos[7];
		ipcache.dstPort = parseInt(qos[8]);
		var remote_report = {
			"CORRELATION_ID": qos[2],
			"RTP_SIP_CALL_ID": qos[2],
			"MOS": 4.5 * parseInt(qos[18]) / 127,
			"TOTAL_PK": parseInt(qos[12]),
			"CODEC_NAME": qos[5],
			"DIR":1,
			"REPORT_NAME": qos[4] + "_" + qos[9] + ":" + qos[10],
			"PARTY":1,
			"TYPE":"HANGUP"
		};
		response.push(this.postProcess(ipcache,JSON.stringify(remote_report),35));
		if (this.debug) logger.info('MEDIA_END', response);
		if (this.qos) return response;
	} else {
		logger.error('missing media parameters', qos);
	}

   } else if (ids[3] && !hold && this.logs) {
	if (this.bypass) return data;
	// Prepare SIP LOG
	if (this.logs) {
		ipcache.callId = sidcache.get(ids[3]) || ids[3] || '';
		ipcache.srcIp = this.localip || '127.0.0.1';
		ipcache.srcPort = 514
		ipcache.dstIp = this.localip || '127.0.0.1';
		ipcache.dstPort = 514
		return this.postProcess(ipcache,line,100);
	}
   } else {
	// Discard
	if (this.bypass) return data;
   }
};

exports.create = function() {
  return new FilterAppAudiocodes();
};
<commit_msg>fix the carriage return for latest SBC version (#92)<commit_after>/*
   Custom, Unoptimized Audiocodes Log to SIP/HEP3 Parser w/ reassembly of rows
   (C) 2020 QXIP BV
*/

var base_filter = require('@pastash/pastash').base_filter,
  util = require('util'),
  logger = require('@pastash/pastash').logger;

var moment = require('moment');
var LRU = require("lru-cache")
  , sidcache = new LRU(1000)
  , expire = 10000 * 60 * 60

function FilterAppAudiocodes() {
  base_filter.BaseFilter.call(this);
  this.mergeConfig({
    name: 'AppAudiocodes',
    optional_params: ['correlation_hdr','bypass', 'debug', 'logs', 'localip', 'localport', 'correlation_contact', 'qos', 'autolocal', 'version'],
    default_values: {
      'correlation_contact': false,
      'correlation_hdr': false,
      'debug': false,
      'bypass': false,
      'logs': false,
      'qos': true,
      'autolocal': false,
      'localip': '127.0.0.1',
      'localport': 5060,
      'version': '7.20A.260.012'
    },
    start_hook: this.start,
  });
}

util.inherits(FilterAppAudiocodes, base_filter.BaseFilter);

FilterAppAudiocodes.prototype.start = function(callback) {
logger.info('Initialized App Audiocodes SysLog to SIP/HEP parser');
  this.postProcess = function(ipcache,last,type){
	 if(!last||!ipcache) return;
   	 last = last.replace(/#012/g, '\r\n').trim() + "\r\n\r\n";
         var rcinfo = {
              type: 'HEP',
              version: 3,
              payload_type: type ? 'LOG' :'SIP',
              ip_family: 2,
              protocol: 17,
              proto_type: type || 1,
              correlation_id: ipcache.callId || '',
              srcIp: ipcache.srcIp || this.localip,
              srcPort: ipcache.srcPort || 0,
              dstIp: ipcache.dstIp || this.localip,
              dstPort: ipcache.dstPort || 0,
              time_sec: ipcache.ts || parseInt(new Date().getTime() / 1000),
              time_usec: ipcache.usec || new Date().getMilliseconds()
            };

	 // EXTRACT CORRELATION HEADER, IF ANY
	  if (this.correlation_hdr && rcinfo.proto_type == 1 && last.startsWith('INVITE')) {
          	var xcid = last.match(this.correlation_hdr+":\s?(.*)\r\n\r\n");
               	if (xcid && xcid[1]) rcinfo.correlation_id = xcid[1].trim();
                        if (this.debug) logger.info('auto correlation pick', rcinfo.correlation_id);
         }

	 if (this.correlation_contact && rcinfo.proto_type == 1 && last.startsWith('INVITE')) {
		var extract = /x-c=(.*?)\//.exec(last);
		if (extract[1]) {
			rcinfo.correlation_id = extract[1];
			if (this.debug) logger.info('auto correlation pick', rcinfo.correlation_id);
		}
	 }

	 if (last.indexOf('2.0/TCP') !== -1 || last.indexOf('2.0/TLS') !== -1 ){
		rcinfo.protocol = 6;
		if (this.autolocal) rcinfo.dstPort = 5061;
         }

         if (last && rcinfo) {
           var data = { payload: last, rcinfo: rcinfo };
	   return data;
         }
  }
  callback();
};

var last = '';
var ipcache = {};
var alias = {};

var hold;
var cache;
var seq;

FilterAppAudiocodes.prototype.process = function(data) {

   var line = data.message.toString();
   var ipcache = {};
   if (this.debug) console.info('DEBUG', line);
   var message = /^.*?\[S=([0-9]+)\].*?\[SID=.*?\]\s?(.*)\[Time:.*\]$/
   var test = message.exec(line.replace(/\r\n/g, '#012'));
   if(hold && line) {
        if (this.debug) logger.error('Next packet number', test[1]);
        if (parseInt(test[1]) == seq + 1) {
	  line = cache + ( test ? test[2] : '');
	  hold = false;
	  cache = '';
	  if (this.debug) console.info('reassembled line', line);
        }
   }

   line = line.replace(/\r\n/g, '#012');

   var ids = /\[SID=(?<mac>.*?):(?<seq>.*?):(?<sid>.*?)\]/.exec(line) || [];
   if (this.debug) logger.error('SESSION SID',ids[3]);

   if (line.indexOf('Incoming SIP Message') !== -1) {
      try {
	   // var regex = /(.*)---- Incoming SIP Message from (.*) to SIPInterface #[0-99] \((.*)\) (.*) TO.*--- #012(.*)#012 #012 #012(.*) \[Time:(.*)-(.*)@(.*)\]/g;
           var regex;
	   if (this.version == '7.20A.260.012') {
                regex = /(.*)---- Incoming SIP Message from (.*) to SIPInterface #[0-99] \((.*)\) (.*) TO.*--- #012(.*)#012 #012(.*)/g; //7.20A.260.012
	   } else if (this.version == '7.20A.256.511') {
                regex = /(.*)---- Incoming SIP Message from (.*) to SIPInterface #[0-99] \((.*)\) (.*) TO.*---  (.*)(.*)/g; //7.20A.256.511
	   }
	   var ip = regex.exec(line);
	   if (!ip) {
		cache = line.replace(/\[Time.*\]$/,'');
		hold = true;
                var regpackid = /.*\[S=([0-9]+)\].*/.exec(line);
                seq = parseInt(regpackid[1]);
                if (this.debug) logger.error('Cashed packet number', seq);
		logger.error('failed parsing Incoming SIP. Cache on!');
		if (this.bypass) return data;
	   } else {
		   if (ip[3]) {
			/* convert alias to IP:port */
			   ipcache.dstIp = alias[0] || this.localip;
			   ipcache.dstPort = alias[1] || this.localport;
		   }
		   ipcache.srcIp = ip[2].split(':')[0];
		   ipcache.srcPort = ip[2].split(':')[1];
		   last = ip[5];
	   	   last += '#012 #012';
		   var callid = last.match(/call-id:\s?(.*?)\s?#012/i) || [];
		   ipcache.callId = callid[1] || ids[3] || '';
		   // Cache SID to Call-ID correlation
		   sidcache.set(ids[3], ipcache.callid, expire);
		   // Seek final fragment
		   if(ip[6].includes(' SIP Message ')){
			hold = true;
			cache = line.replace(/\[Time.*\]$/,'');
		   }
		   return this.postProcess(ipcache,last);
	   }
     } catch(e) { logger.error(e, line); }

   } else if (line.indexOf('Outgoing SIP Message') !== -1) {
      try {
           var regex;
           if (this.version == '7.20A.260.012') {
                regex = /(.*)---- Outgoing SIP Message to (.*) from SIPInterface #[0-99] \((.*)\) (.*) TO.*--- #012(.*)#012 #012 (.*)/g; //7.20A.260.012
           } else if (this.version == '7.20A.256.511') {
	        regex = /(.*)---- Outgoing SIP Message to (.*) from SIPInterface #[0-99] \((.*)\) (.*) TO.*---  (.*)(.*)/g; //7.20A.256.511
           }
	   var ip = regex.exec(line);
	   if (!ip) {
		cache = line.replace(/\[Time.*\]$/,'');
		hold = true;
                var regpackid = /.*\[S=([0-9]+)\].*/.exec(line);
                seq = parseInt(regpackid[1]);
                if (this.debug) logger.error('Cashed packet number', seq);
		logger.error('failed parsing Outgoing SIP. Cache on!');
		if (this.bypass) return data;
	   } else {
		   if (ip[3]) {
			/* convert alias to IP:port */
			   ipcache.srcIp = alias[0] || this.localip;
			   ipcache.srcPort = alias[1] || this.localport;
		   }
		   ipcache.dstIp = ip[2].split(':')[0];
		   ipcache.dstPort = ip[2].split(':')[1];
		   last = ip[5];
	   	   last += '#012 #012';
		   var callid = last.match(/call-id:\s?(.*?)\s?#012/i) || [];
		   ipcache.callId = callid[1] || ids[3] || '';
		   // Cache SID to Call-ID correlation
		   sidcache.set(ids[3], ipcache.callid, expire);
		   // Seek final fragment
		   if(ip[6].includes(' SIP Message ')){
			hold = true;
			cache = line.replace(/\[Time.*\]$/,'');
		   }
		   return this.postProcess(ipcache,last);
	   }
     } catch(e) { logger.error(e, line); }

   } else if (this.autolocal && line.indexOf('Local IP Address =') !== -1) {
	var local = line.match(/Local IP Address = (.*?):(.*?),/) || [];
	if(local[1]) this.localip   = local[1];
	if(local[2]) this.localport = local[2];
   } else if (line.indexOf('CALL_END ') !== -1 && this.logs) {
	// Parser TBD page 352 @ https://www.audiocodes.com/media/10312/ltrt-41548-mediant-software-sbc-users-manual-ver-66.pdf
	var cdr = line.split(/(\s+\|)/).filter( function(e) { return e.trim().length > 1; } )
	ipcache.callId = cdr[3] || '';
	if (this.debug) logger.info('CALL_END', cdr, ipcache);
	if (this.logs) return this.postProcess(ipcache,JSON.stringify(cdr),100);

   } else if (line.indexOf('MEDIA_END ') !== -1 && this.qos) {
	// Parsed TBD page 353 @ https://www.audiocodes.com/media/10312/ltrt-41548-mediant-software-sbc-users-manual-ver-66.pdf
	var qos = line.split(/(\s+\|)/).filter( function(e) { return e.trim().length > 1; } )
	if (qos.length == 25){
		qos.splice(15, 1);
		qos.splice(5, 1);
	}
	logger.info('!!!!!!!!!!!!!! DEBUG MEDIA', qos, qos.length);
	if(qos && qos[2] && qos[21]){
		ipcache.callId = qos[2] || '';
		var response = [];
		// A-LEG
		ipcache.srcIp = qos[7];
		ipcache.srcPort = parseInt(qos[8]);
		ipcache.dstIp = qos[9];
		ipcache.dstPort = parseInt(qos[10]);
		var local_report = {
			"CORRELATION_ID": qos[2],
			"RTP_SIP_CALL_ID": qos[2],
			"MOS": 4.5 * parseInt(qos[17]) / 127,
			"TOTAL_PK": parseInt(qos[11]),
			"CODEC_NAME": qos[5],
			"DIR":0,
			"REPORT_NAME": qos[4] + "_" + qos[7] + ":" + qos[8],
			"PARTY":0,
			"TYPE":"HANGUP"
		};
		response.push(this.postProcess(ipcache,JSON.stringify(local_report),35));
		// B-LEG
		ipcache.srcIp = qos[9];
		ipcache.srcPort = parseInt(qos[10]);
		ipcache.dstIp = qos[7];
		ipcache.dstPort = parseInt(qos[8]);
		var remote_report = {
			"CORRELATION_ID": qos[2],
			"RTP_SIP_CALL_ID": qos[2],
			"MOS": 4.5 * parseInt(qos[18]) / 127,
			"TOTAL_PK": parseInt(qos[12]),
			"CODEC_NAME": qos[5],
			"DIR":1,
			"REPORT_NAME": qos[4] + "_" + qos[9] + ":" + qos[10],
			"PARTY":1,
			"TYPE":"HANGUP"
		};
		response.push(this.postProcess(ipcache,JSON.stringify(remote_report),35));
		if (this.debug) logger.info('MEDIA_END', response);
		if (this.qos) return response;
	} else {
		logger.error('missing media parameters', qos);
	}

   } else if (ids[3] && !hold && this.logs) {
	if (this.bypass) return data;
	// Prepare SIP LOG
	if (this.logs) {
		ipcache.callId = sidcache.get(ids[3]) || ids[3] || '';
		ipcache.srcIp = this.localip || '127.0.0.1';
		ipcache.srcPort = 514
		ipcache.dstIp = this.localip || '127.0.0.1';
		ipcache.dstPort = 514
		return this.postProcess(ipcache,line,100);
	}
   } else {
	// Discard
	if (this.bypass) return data;
   }
};

exports.create = function() {
  return new FilterAppAudiocodes();
};
<|endoftext|>


<commit_before>var width = 640, height=580;
var fib = [0,1,1];
var n = 15;
var index = 2;
var r = 1;

var midX = width/2+130;
var midY = height/2-80;

var moveX = 0;
var moveY = 0;

var last_mouse_z = mouse_z;

function draw()
{
	moveX = 0;
	moveY = 0;
	for(var i =1; i<n; i++){
		if(i%4 == 1){
			moveX -= (fib[i]-fib[i-1]);
			rect (canvas, midX + moveX*r, midY + moveY*r, fib[i]*r, fib[i]*r, makecol(0,0,0), 1);
			arc(canvas, midX + moveX*r, midY + moveY*r, DEG(PI*(i-1)/2), DEG(PI*i/2), fib[i]*r, makecol(0,0,0), 2);

		}else if(i%4 == 2){
			moveY -= (fib[i]-fib[i-1]);
			rect (canvas, midX + moveX*r-fib[i]*r, midY + moveY*r, fib[i]*r, fib[i]*r, makecol(0,0,0), 1);
			arc(canvas, midX + moveX*r, midY + moveY*r, DEG(PI*(i-1)/2), DEG(PI*i/2), fib[i]*r, makecol(0,0,0), 2);

		}else if(i%4 == 3){
			moveX += (fib[i]-fib[i-1]);
			rect (canvas, midX + moveX*r - fib[i]*r, midY + moveY*r - fib[i]*r, fib[i]*r, fib[i]*r, makecol(0,0,0), 1);
			arc (canvas, midX + moveX*r, midY + moveY*r, DEG(PI*(i-1)/2), DEG(PI*i/2), fib[i]*r, makecol(0,0,0), 2);

		}else if(i%4 == 0){
			moveY += (fib[i]-fib[i-1]);
			rect (canvas, midX + moveX*r, midY + moveY*r - fib[i]*r, fib[i]*r, fib[i]*r, makecol(0,0,0), 1);
			arc (canvas, midX + moveX*r, midY + moveY*r, DEG(PI*(i-1)/2), DEG(PI*i/2), fib[i]*r, makecol(0,0,0), 2);
		}
	}
}

function update()
{
	if(last_mouse_z != mouse_z){
		r += sgn(last_mouse_z - mouse_z);
		r<1?r=1:r;
		last_mouse_z = mouse_z;
	}
}

function main()
{
    enable_debug('debug');
    allegro_init_all("game_canvas", width, height);
	load_elements();
	font = load_font("../antilles.ttf");
	fibon();
	ready(function(){
        loop(function(){
            clear_to_color(canvas,makecol(255,255,255));
            update();
            draw();
			//fib_step();
        },BPS_TO_TIMER(60));
    });
    return 0;
}
END_OF_MAIN();

function load_elements()
{

}

function fibon(){

	for(var i = 2; i<n; i++){
		fib[i] = fib[i-1]+fib[i-2];
	}
}
<commit_msg>one small fix<commit_after>var width = 640, height=580;
var fib = [0,1,1];
var n = 15;
var index = 2;
var r = 1;

var midX = width/2+130;
var midY = height/2-80;

var moveX = 0;
var moveY = 0;

var last_mouse_z = mouse_z;

function draw()
{
	moveX = 0;
	moveY = 0;
	for(var i =1; i<n; i++){
		if(i%4 == 1){
			moveX -= (fib[i]-fib[i-1]);
			rect (canvas, midX + moveX*r, midY + moveY*r, fib[i]*r, fib[i]*r, makecol(0,0,0), 1);
		}else if(i%4 == 2){
			moveY -= (fib[i]-fib[i-1]);
			rect (canvas, midX + moveX*r-fib[i]*r, midY + moveY*r, fib[i]*r, fib[i]*r, makecol(0,0,0), 1);
		}else if(i%4 == 3){
			moveX += (fib[i]-fib[i-1]);
			rect (canvas, midX + moveX*r - fib[i]*r, midY + moveY*r - fib[i]*r, fib[i]*r, fib[i]*r, makecol(0,0,0), 1);
		}else if(i%4 == 0){
			moveY += (fib[i]-fib[i-1]);
			rect (canvas, midX + moveX*r, midY + moveY*r - fib[i]*r, fib[i]*r, fib[i]*r, makecol(0,0,0), 1);
		}

		arc(canvas, midX + moveX*r, midY + moveY*r, DEG(PI*(i-1)/2), DEG(PI*i/2), fib[i]*r, makecol(0,0,0), 2);
	}
}

function update()
{
	if(last_mouse_z != mouse_z){
		r += sgn(last_mouse_z - mouse_z);
		r<1?r=1:r;
		last_mouse_z = mouse_z;
	}
}

function main()
{
    enable_debug('debug');
    allegro_init_all("game_canvas", width, height);
	load_elements();
	font = load_font("../antilles.ttf");
	fibon();
	ready(function(){
        loop(function(){
            clear_to_color(canvas,makecol(255,255,255));
            update();
            draw();
			//fib_step();
        },BPS_TO_TIMER(60));
    });
    return 0;
}
END_OF_MAIN();

function load_elements()
{

}

function fibon(){

	for(var i = 2; i<n; i++){
		fib[i] = fib[i-1]+fib[i-2];
	}
}
<|endoftext|>


<commit_before>// jscs:disable
/* globals define */
String.prototype.toSnakeCase = function() {
  return this.replace(/([A-Z])/g, function(string) {
    return '_' + string.toLowerCase();
  });
};

(function() {
  'use strict';
  var _elev = window._elev = {};

  function _setup(config) {
    if (!config.enabled) {
      return;
    }

    var i, e;
    i = document.createElement("script"), i.type = 'text/javascript';
    i.async = 1, i.src = "https://static.elev.io/js/v3.js", e =
      document.getElementsByTagName("script")[0], e.parentNode.insertBefore(i, e);

    if (!config.accountId) {
      throw new Error('ENV.elevio.accountId must be defined in config/environment.js');
    }

    // elevio uses snake case for all their keys.
    // All the config for this addon uses camelCase
    for (var key in config) {
      if (config.hasOwnProperty(key)) {
        _elev[key.toSnakeCase()] = config[key];
      }
    }
  }

  function generateModule(name, values) {
    define(name, [], function() {
      'use strict';

      Object.defineProperty(values, '__esModule', {
        value: true
      });

      return values;
    });
  }

  generateModule('elevio', {
    default: _elev,
    _setup: _setup
  });
})();
<commit_msg>Fix enabled flag not working when the user doesnt explicity set enabled to true in config<commit_after>// jscs:disable
/* globals define */
String.prototype.toSnakeCase = function() {
  return this.replace(/([A-Z])/g, function(string) {
    return '_' + string.toLowerCase();
  });
};

(function() {
  'use strict';
  var _elev = window._elev = {};

  function _setup(config) {
    if (config.enabled === false) {
      return;
    }

    var i, e;
    i = document.createElement("script"), i.type = 'text/javascript';
    i.async = 1, i.src = "https://static.elev.io/js/v3.js", e =
      document.getElementsByTagName("script")[0], e.parentNode.insertBefore(i, e);

    if (!config.accountId) {
      throw new Error('ENV.elevio.accountId must be defined in config/environment.js');
    }

    // elevio uses snake case for all their keys.
    // All the config for this addon uses camelCase
    for (var key in config) {
      if (config.hasOwnProperty(key)) {
        _elev[key.toSnakeCase()] = config[key];
      }
    }
  }

  function generateModule(name, values) {
    define(name, [], function() {
      'use strict';

      Object.defineProperty(values, '__esModule', {
        value: true
      });

      return values;
    });
  }

  generateModule('elevio', {
    default: _elev,
    _setup: _setup
  });
})();
<|endoftext|>


<commit_before>/* @flow */
import {EditorState} from 'draft-js';
import stateToHTML from './stateToHTML';
import stateFromHTML from './stateFromHTML';
import stateToMarkdown from './stateToMarkdown';
import stateFromMarkdown from './stateFromMarkdown';

type StringMap = {[key: string]: string};

export default class EditorValue {
  _editorState: ?EditorState;
  _cache: StringMap;

  constructor(editorState: ?EditorState) {
    this._editorState = editorState;
    this._cache = {};
  }

  getEditorState(): EditorState {
    return this._editorState || EditorState.createEmpty();
  }

  setEditorState(editorState: EditorState): EditorValue {
    if (this._editorState === editorState) {
      return this;
    }
    return new EditorValue(editorState);
  }

  toString(format: string): string {
    let fromCache = this._cache[format];
    if (fromCache != null) {
      return fromCache;
    }
    return (this._cache[format] = toString(this.getEditorState(), format));
  }

  static createEmpty(): EditorValue {
    return new EditorValue();
  }

  static createFromString(source: string, format: string): EditorValue {
    let editorState = fromString(source, format);
    return new EditorValue(editorState);
  }

  static createFromState(editorState: EditorState): EditorValue {
    return new EditorValue(editorState);
  }
}

function toString(editorState, format) {
  let contentState = editorState.getCurrentContent();
  switch (format) {
    case 'html': {
      return stateToHTML(contentState);
    }
    case 'markdown': {
      return stateToMarkdown(contentState);
    }
    default: {
      throw new Error('Format not supported: ' + format);
    }
  }
}

function fromString(source, format) {
  switch (format) {
    case 'html': {
      return stateFromHTML(source);
    }
    case 'markdown': {
      return stateFromMarkdown(source);
    }
    default: {
      throw new Error('Format not supported: ' + format);
    }
  }
}
<commit_msg>after setting editorState from source don't re-generate source upon next toString<commit_after>/* @flow */
import {EditorState} from 'draft-js';
import stateToHTML from './stateToHTML';
import stateFromHTML from './stateFromHTML';
import stateToMarkdown from './stateToMarkdown';
import stateFromMarkdown from './stateFromMarkdown';

type StringMap = {[key: string]: string};

export default class EditorValue {
  _editorState: ?EditorState;
  _cache: StringMap;

  constructor(editorState: ?EditorState) {
    this._editorState = editorState;
    this._cache = {};
  }

  getEditorState(): EditorState {
    return this._editorState || EditorState.createEmpty();
  }

  setEditorState(editorState: EditorState): EditorValue {
    if (this._editorState === editorState) {
      return this;
    }
    return new EditorValue(editorState);
  }

  toString(format: string): string {
    let fromCache = this._cache[format];
    if (fromCache != null) {
      return fromCache;
    }
    return (this._cache[format] = toString(this.getEditorState(), format));
  }

  static createEmpty(): EditorValue {
    return new EditorValue();
  }

  static createFromString(source: string, format: string): EditorValue {
    let editorState = fromString(source, format);
    let value = new EditorValue(editorState);
    value._cache[format] = source;
    return value;
  }

  static createFromState(editorState: EditorState): EditorValue {
    return new EditorValue(editorState);
  }
}

function toString(editorState, format) {
  let contentState = editorState.getCurrentContent();
  switch (format) {
    case 'html': {
      return stateToHTML(contentState);
    }
    case 'markdown': {
      return stateToMarkdown(contentState);
    }
    default: {
      throw new Error('Format not supported: ' + format);
    }
  }
}

function fromString(source, format) {
  switch (format) {
    case 'html': {
      return stateFromHTML(source);
    }
    case 'markdown': {
      return stateFromMarkdown(source);
    }
    default: {
      throw new Error('Format not supported: ' + format);
    }
  }
}
<|endoftext|>


<commit_before>var BotKit = require('botkit');

module.exports = Ears;

var Bot = BotKit.slackbot({
  debug: false,
  storage: undefined
});

function Ears(token) {
  this.scopes = [
    'direct_mention',
    'direct_message',
    'mention'
  ];
  this.token = token;
}

Ears.prototype.listen = function() {
  console.log('TOKEN: ' + this.token);
  this.bot = Bot.spawn({
    token: this.token
  }).startRTM();

    // @ https://api.slack.com/methods/users.list
    bot.api.users.list({}, function (err, response) {
        if (response.hasOwnProperty('members') && response.ok) {
            var total = response.members.length;
            for (var i = 0; i < total; i++) {
                var member = response.members[i];
                var id = db.saveSync({name: member.name, id: member.id});
                //fullTeamList.push({name: member.name, id: member.id});
            }
        }
    });
  return this;
}

Ears.prototype.hear = function(pattern, callback) {
  Bot.hears(pattern, this.scopes, callback);
  return this;
};
<commit_msg>Update ears.js<commit_after>var BotKit = require('botkit');

module.exports = Ears;

var Bot = BotKit.slackbot({
  debug: false,
  storage: undefined
});

function Ears(token) {
  this.scopes = [
    'direct_mention',
    'direct_message',
    'mention'
  ];
  this.token = token;
}

Ears.prototype.listen = function() {
  console.log('TOKEN: ' + this.token);
  this.bot = Bot.spawn({
    token: this.token
  }).startRTM();

    // @ https://api.slack.com/methods/users.list
    this.bot.api.users.list({}, function (err, response) {
        if (response.hasOwnProperty('members') && response.ok) {
            var total = response.members.length;
            for (var i = 0; i < total; i++) {
                var member = response.members[i];
                var id = db.saveSync({name: member.name, id: member.id});
                //fullTeamList.push({name: member.name, id: member.id});
            }
        }
    });
  return this;
}

Ears.prototype.hear = function(pattern, callback) {
  Bot.hears(pattern, this.scopes, callback);
  return this;
};
<|endoftext|>


<commit_before>/*
 * run.js: Titanium iOS CLI run hook
 *
 * Copyright (c) 2012, Appcelerator, Inc.  All Rights Reserved.
 * See the LICENSE file for more information.
 */

var appc = require('node-appc'),
	i18n = appc.i18n(__dirname),
	__ = i18n.__,
	__n = i18n.__n,
	afs = appc.fs,
	fs = require('fs'),
	path = require('path'),
	parallel = require('async').parallel,
	cp = require('child_process'),
	exec = cp.exec,
	spawn = cp.spawn;

exports.cliVersion = '>=3.X';

exports.init = function (logger, config, cli) {

	cli.addHook('build.post.compile', {
		priority: 10000,
		post: function (build, finished) {
			if (cli.argv.target != 'simulator') return finished();

			if (cli.argv['build-only']) {
				logger.info(__('Performed build only, skipping running of the application'));
				return finished();
			}

			logger.info(__('Running application in iOS Simulator'));

			var simulatorDir = afs.resolvePath('~/Library/Application Support/iPhone Simulator/' + build.iosSimVersion + '/Applications'),
				logFile = build.tiapp.guid + '.log';

			parallel([
				function (next) {
					logger.debug(__('Terminating all iOS simulators'));
					exec('/usr/bin/killall ios-sim', next);
				},

				function (next) {
					exec('/usr/bin/killall "iPhone Simulator"', next);
				},

				function (next) {
					setTimeout(next, 2000);
				},

				function (next) {
					// sometimes the simulator doesn't remove old log files in which case we get
					// our logging jacked - we need to remove them before running the simulator
					afs.exists(simulatorDir) && fs.readdirSync(simulatorDir).forEach(function (guid) {
						var file = path.join(simulatorDir, guid, 'Documents', logFile);
						if (afs.exists(file)) {
							logger.debug(__('Removing old log file: %s', file.cyan));
							fs.unlinkSync(file);
						}
					});

					next();
				}
			], function () {
				var cmd = [
						'"' + path.join(build.titaniumIosSdkPath, 'ios-sim') + '"',
						'launch',
						'"' + build.xcodeAppDir + '"',
						'--sdk',
						build.iosSimVersion,
						'--family',
						build.iosSimType
					],
					findLogTimer,
					simActivateTimer = setTimeout(function () {
						exec([
							'osascript',
							'"' + path.join(build.titaniumIosSdkPath, 'iphone_sim_activate.scpt') + '"',
							'"' + path.join(build.xcodeEnv.path, 'Platforms', 'iPhoneSimulator.platform', 'Developer', 'Applications', 'iPhone Simulator.app') + '"'
						].join(' '), function (err, stdout, stderr) {
							if (err) {
								logger.error(__('Failed to activate the iPhone Simulator window'));
								logger.error(stderr);
							}
						})
					}, 500),
					simProcess,
					simErr = [],
					stripLogLevelRE = new RegExp('[(?:' + logger.getLevels().join('|') + ')] '),
					logProcess;

				cli.argv.retina && cmd.push('--retina');
				cmd = cmd.join(' ');

				logger.info(__('Launching application in iOS Simulator'));
				logger.debug(__('Simulator command: %s', cmd.cyan));

				simProcess = spawn('/bin/sh', ['-c', cmd], {
					cwd: build.titaniumIosSdkPath,
					env: {
						DYLD_FRAMEWORK_PATH: path.join(build.xcodeEnv.path, 'Platforms', 'iPhoneSimulator.platform', 'Developer', 'Library', 'PrivateFrameworks') +
							':' + afs.resolvePath(build.xcodeEnv.path, '..', 'OtherFrameworks')
					}
				});

				simProcess.stderr.on('data', function (data) {
					data.toString().split('\n').forEach(function (line) {
						line.length && simErr.push(line.replace(stripLogLevelRE, ''));
					}, this);
				}.bind(this));

				simProcess.on('exit', function (code, signal) {
					clearTimeout(simActivateTimer);
					clearTimeout(findLogTimer);
					logProcess && logProcess.kill();

					if (code) {
						finished(new appc.exception(__('An error occurred running the iOS Simulator'), simErr));
					} else {
						logger.info(__('Application has exited from iOS Simulator'));
						finished();
					}
				}.bind(this));

				function findLogFile() {
					var files = fs.readdirSync(simulatorDir),
						file,
						i = 0,
						l = files.length,
						logLevelRE = new RegExp('(\u001b\\[\\d+m)?\\[?(' + logger.getLevels().join('|') + ')\\]?\s*(\u001b\\[\\d+m)?(.*)', 'i');

					for (; i < l; i++) {
						file = path.join(simulatorDir, files[i], 'Documents', logFile);
						if (afs.exists(file)) {
							logger.debug(__('Found iPhone Simulator log file: %s', file.cyan));
							logger.info(__('iPhone Simulator log:'));

							var stat = fs.lstatSync(file),
								prevSize = stat.size,
								queue = [{
									start: 0,
									end: prevSize
								}],
								buffer = '';

							function pump(callback) {
								if (queue.length >= 1) {
									var block = queue[0];
									if (block.end > block.start) {
										var stream = fs.createReadStream(file, {
											start: block.start,
											end: block.end - 1,
											encoding: 'utf-8',
											bufferSize: 64
										});

										stream.on('error', function(error) {
											console.log('Tail error: ' + error);
										});

										stream.on('end', function() {
											queue.shift();
											if (queue.length >= 1) {
												pump();
											} else {
												callback && callback();
											}
										});

										stream.on('data', function (data) {
											buffer += data;
											var lines = buffer.split('\n');
											buffer = lines.pop(); // keep the last line because it could be incomplete
											lines.forEach(function (line) {
												if (line) {
													var m = line.match(logLevelRE);
													if (m) {
														logger[m[2].toLowerCase()](m[4].trim());
													} else {
														logger.debug(line);
													}
												}
											});
										});
									}
								}
							}

							pump(function () {
								fs.watch(file, { persistent: false }, function () {
									var currentSize = fs.lstatSync(file).size;
									if (currentSize > prevSize) {
										queue.push({
											start: prevSize,
											end: currentSize
										});
										if (queue.length == 1) {
											pump();
										}
									}
								});
							});

							// we found the log file, no need to keep searching for it
							return;
						}
					}

					// didn't find any log files, try again in 250ms
					findLogTimer = setTimeout(findLogFile, 250);
				}

				afs.exists(simulatorDir) && findLogFile();
			});
		}
	});

};
<commit_msg>[TIMOB-12280] Fixed iOS Simulator log tailing so it's not repeating any more and also simplified the code.<commit_after>/*
 * run.js: Titanium iOS CLI run hook
 *
 * Copyright (c) 2012, Appcelerator, Inc.  All Rights Reserved.
 * See the LICENSE file for more information.
 */

var appc = require('node-appc'),
	i18n = appc.i18n(__dirname),
	__ = i18n.__,
	__n = i18n.__n,
	afs = appc.fs,
	fs = require('fs'),
	path = require('path'),
	parallel = require('async').parallel,
	cp = require('child_process'),
	exec = cp.exec,
	spawn = cp.spawn;

exports.cliVersion = '>=3.X';

exports.init = function (logger, config, cli) {

	cli.addHook('build.post.compile', {
		priority: 10000,
		post: function (build, finished) {
			if (cli.argv.target != 'simulator') return finished();

			if (cli.argv['build-only']) {
				logger.info(__('Performed build only, skipping running of the application'));
				return finished();
			}

			logger.info(__('Running application in iOS Simulator'));

			var simulatorDir = afs.resolvePath('~/Library/Application Support/iPhone Simulator/' + build.iosSimVersion + '/Applications'),
				logFile = build.tiapp.guid + '.log';

			parallel([
				function (next) {
					logger.debug(__('Terminating all iOS simulators'));
					exec('/usr/bin/killall ios-sim', next);
				},

				function (next) {
					exec('/usr/bin/killall "iPhone Simulator"', next);
				},

				function (next) {
					setTimeout(next, 2000);
				},

				function (next) {
					// sometimes the simulator doesn't remove old log files in which case we get
					// our logging jacked - we need to remove them before running the simulator
					afs.exists(simulatorDir) && fs.readdirSync(simulatorDir).forEach(function (guid) {
						var file = path.join(simulatorDir, guid, 'Documents', logFile);
						if (afs.exists(file)) {
							logger.debug(__('Removing old log file: %s', file.cyan));
							fs.unlinkSync(file);
						}
					});

					next();
				}
			], function () {
				var cmd = [
						'"' + path.join(build.titaniumIosSdkPath, 'ios-sim') + '"',
						'launch',
						'"' + build.xcodeAppDir + '"',
						'--sdk',
						build.iosSimVersion,
						'--family',
						build.iosSimType
					],
					findLogTimer,
					simActivateTimer = setTimeout(function () {
						exec([
							'osascript',
							'"' + path.join(build.titaniumIosSdkPath, 'iphone_sim_activate.scpt') + '"',
							'"' + path.join(build.xcodeEnv.path, 'Platforms', 'iPhoneSimulator.platform', 'Developer', 'Applications', 'iPhone Simulator.app') + '"'
						].join(' '), function (err, stdout, stderr) {
							if (err) {
								logger.error(__('Failed to activate the iPhone Simulator window'));
								logger.error(stderr);
							}
						})
					}, 500),
					simProcess,
					simErr = [],
					stripLogLevelRE = new RegExp('[(?:' + logger.getLevels().join('|') + ')] '),
					logProcess;

				cli.argv.retina && cmd.push('--retina');
				cmd = cmd.join(' ');

				logger.info(__('Launching application in iOS Simulator'));
				logger.debug(__('Simulator command: %s', cmd.cyan));

				simProcess = spawn('/bin/sh', ['-c', cmd], {
					cwd: build.titaniumIosSdkPath,
					env: {
						DYLD_FRAMEWORK_PATH: path.join(build.xcodeEnv.path, 'Platforms', 'iPhoneSimulator.platform', 'Developer', 'Library', 'PrivateFrameworks') +
							':' + afs.resolvePath(build.xcodeEnv.path, '..', 'OtherFrameworks')
					}
				});

				simProcess.stderr.on('data', function (data) {
					data.toString().split('\n').forEach(function (line) {
						line.length && simErr.push(line.replace(stripLogLevelRE, ''));
					}, this);
				}.bind(this));

				simProcess.on('exit', function (code, signal) {
					clearTimeout(simActivateTimer);
					clearTimeout(findLogTimer);
					logProcess && logProcess.kill();

					if (code) {
						finished(new appc.exception(__('An error occurred running the iOS Simulator'), simErr));
					} else {
						logger.info(__('Application has exited from iOS Simulator'));
						finished();
					}
				}.bind(this));

				function findLogFile() {
					var files = fs.readdirSync(simulatorDir),
						file,
						i = 0,
						l = files.length,
						logLevelRE = new RegExp('(\u001b\\[\\d+m)?\\[?(' + logger.getLevels().join('|') + ')\\]?\s*(\u001b\\[\\d+m)?(.*)', 'i');

					for (; i < l; i++) {
						file = path.join(simulatorDir, files[i], 'Documents', logFile);
						if (afs.exists(file)) {
							logger.debug(__('Found iPhone Simulator log file: %s', file.cyan));
							logger.info(__('iPhone Simulator log:'));

							var stat = fs.lstatSync(file),
								bytesRead = 0,
								queue = [ stat.size ],
								buffer = '';

							function pump(callback) {
								if (queue.length >= 1) {
									var readTo = queue[0];

									var stream = fs.createReadStream(file, {
										start: bytesRead,
										end: readTo - 1,
										encoding: 'utf-8',
										bufferSize: 16
									});

									stream.on('error', function(error) {
										console.log('Tail error: ' + error);
									});

									stream.on('end', function() {
										bytesRead = readTo;
										queue.shift();
										if (queue.length >= 1) {
											pump();
										} else {
											callback && callback();
										}
									});

									stream.on('data', function (data) {
										buffer += data;
										var lines = buffer.split('\n');
										buffer = lines.pop(); // keep the last line because it could be incomplete
										lines.forEach(function (line) {
											if (line) {
												var m = line.match(logLevelRE);
												if (m) {
													logger[m[2].toLowerCase()](m[4].trim());
												} else {
													logger.debug(line);
												}
											}
										});
									});
								}
							}

							pump(function () {
								fs.watch(file, { persistent: false }, function () {
									queue.push(fs.lstatSync(file).size);
									if (queue.length == 1) {
										pump();
									}
								});
							});

							// we found the log file, no need to keep searching for it
							return;
						}
					}

					// didn't find any log files, try again in 250ms
					findLogTimer = setTimeout(findLogFile, 250);
				}

				afs.exists(simulatorDir) && findLogFile();
			});
		}
	});

};
<|endoftext|>


<commit_before>var fs = require('fs'),
    fileQueue = require('./file_queue'),
    path = require('path');

var File = function () {
  this.constructor.prototype.initialize.apply(this, arguments);
};

File.prototype = new function () {

  this.initialize = function(options) {
    var key, name;

    for(key in options) {
      this[key] = options[key];
    }

    // Check for extname
    this.extname = path.extname(this.path);

    // Create name
    name = this.path.split('/');
    this.fullName = name = name[name.length - 1]; // full name
    name = name.replace(this.extname, '');

    // Store the name
    this.name = name;

    // Build url path
    var pack = this.package;

    if (pack && this.isScript()) {
      // remove path
      this.url = this.path.replace(pack.path + "/" + pack.scripts, '');
      // remove extension
      this.url = this.url.replace(this.extname, '');
      // add package name
      this.url = pack.name + this.url;
    }
  };

  this.isStylesheet = function() {
    return /^\.(css|less|scss|styl)$/.test(this.extname);
  };

  this.isScript = function() {
    return this.extname === '.js' && !/tests\//.test(this.path);
  };

  this.isTest = function() {
    return this.extname() === '.js' && /tests\//.test(this.path);
  };

  this.isTemplate = function() {
    return /^\.(hbs|handlebars)$/.test(this.extname);
  };

  this.isStatic = function() {
    return /^\.(html|html)$/.test(this.extname);
  };

  this.readFile = function(callback) {
    var self = this;

    fileQueue.readFile(this.path, function(err, data) {
      if (err) {
        console.log(err);
        return callback("Error loading file: " + this.path);
      }
      self.content = data;
      callback(null, data);
    });
  };

}();

File.prototype.constructor = File;

module.exports = File;<commit_msg>Implemented the file.templateName(templatesLocation) method which will generate the template name, taking subfolders into account.<commit_after>var fs = require('fs'),
    fileQueue = require('./file_queue'),
    path = require('path');

var File = function () {
  this.constructor.prototype.initialize.apply(this, arguments);
};

File.prototype = new function () {

  this.initialize = function(options) {
    var key, name;

    for(key in options) {
      this[key] = options[key];
    }

    // Check for extname
    this.extname = path.extname(this.path);

    // Create name
    name = this.path.split('/');
    this.fullName = name = name[name.length - 1]; // full name
    name = name.replace(this.extname, '');

    // Store the name
    this.name = name;

    // Build url path
    var pack = this.package;

    if (pack && this.isScript()) {
      // remove path
      this.url = this.path.replace(pack.path + "/" + pack.scripts, '');
      // remove extension
      this.url = this.url.replace(this.extname, '');
      // add package name
      this.url = pack.name + this.url;
    }
  };

  this.isStylesheet = function() {
    return /^\.(css|less|scss|styl)$/.test(this.extname);
  };

  this.isScript = function() {
    return this.extname === '.js' && !/tests\//.test(this.path);
  };

  this.isTest = function() {
    return this.extname() === '.js' && /tests\//.test(this.path);
  };

  this.isTemplate = function() {
    return /^\.(hbs|handlebars)$/.test(this.extname);
  };

  this.isStatic = function() {
    return /^\.(html|html)$/.test(this.extname);
  };

  this.readFile = function(callback) {
    var self = this;

    fileQueue.readFile(this.path, function(err, data) {
      if (err) {
        console.log(err);
        return callback("Error loading file: " + this.path);
      }
      self.content = data;
      callback(null, data);
    });
  };

  // `templateName( templatesLocation )` returns the fully computed name of the template, taking into
  //  account any nested subfolders.
  //
  //   * `templatesLocation` is expected to be the value of the configured templates location
  //
  // `return` The fully computed name of the template
  this.templateName = function(templatesLocation) {
    var templateName = null;

    if (this.isTemplate()) {
      var pathComponents = this.path.split('/');

      // Drop the extension on the final component...
      pathComponents[pathComponents.length - 1] = pathComponents[pathComponents.length - 1].replace(this.extname, '');

      for (i = pathComponents.length - 1; i >= 0; i--){
        if (pathComponents[i] === templatesLocation) {

          for (j = i + 1; j < pathComponents.length; j++) {
            if (templateName === null) {
              templateName = pathComponents[j];
            } else {
              templateName = templateName + '/' + pathComponents[j];
            }
          }

          break;
        }
      }
    }

    return templateName;
  };

}();

File.prototype.constructor = File;

module.exports = File;<|endoftext|>


<commit_before>define
([
    'jquery', 'jquery/superdesk', 'dust/core', 'utils/sha512', 'jquery/tmpl', 'jquery/rest', 'bootstrap',
    'tmpl!auth',
],
function($, superdesk, dust, jsSHA)
{
<<<<<<< HEAD
    var AuthLogin = function(username, password, logintoken){
=======
    var AuthDetails = function(username){
		var authDetails = new $.rest('Superdesk/User');
		authDetails.resetData().xfilter('Name,Id,EMail').select({ name: username }).done(function(users){
			var user = users.UserList[0];
			localStorage.setItem('superdesk.login.id', user.Id);
			localStorage.setItem('superdesk.login.name', user.Name);
			localStorage.setItem('superdesk.login.email', user.EMail);
		});
		return $(authDetails);
	},
	AuthLogin = function(username, password, logintoken){
>>>>>>> 718d8c014dc7f1c47606de731769286a6bcebb81
		var shaObj = new jsSHA(logintoken, "ASCII"),shaPassword = new jsSHA(password, "ASCII"),
			authLogin = new $.rest('Authentication');
			authLogin.resetData().insert({
			UserName: username,
			LoginToken: logintoken,
			HashedLoginToken: shaObj.getHMAC(username+shaPassword.getHash("SHA-512", "HEX"), "ASCII", "SHA-512", "HEX")
		}).done(function(user){
			localStorage.setItem('superdesk.login.session', user.Session);
			localStorage.setItem('superdesk.login.id', user.Id);
			localStorage.setItem('superdesk.login.name', user.UserName);
			localStorage.setItem('superdesk.login.email', user.EMail);
			$(authLogin).trigger('success');
		});
		return $(authLogin);
	},
	AuthToken = function(username, password) {
		var authToken = new $.rest('Authentication');
		authToken.resetData().select({ userName: username }).done(
			function(data){
				authLogin = AuthLogin(username, password, data.Token);
				authLogin.on('failed', function(){
					$(authToken).trigger('failed', 'authToken');
				}).on('success', function(){
					$(authToken).trigger('success');
				});
			}
		);
		return $(authToken);
	},
	AuthApp =
    {
        success: $.noop,
        require: function()
        {
			if(this.showed) return;
            var self = this; // rest
			self.showed = true;
            $.tmpl('auth', null, function(e, o)
            {
                var dialog = $(o).eq(0).dialog
                ({
                    draggable: false,
                    resizable: false,
                    modal: true,
                    width: "40.1709%",
                    buttons:
                    [
                         { text: "Login", click: function(){ $(form).trigger('submit'); }, class: "btn btn-primary"},
                         { text: "Close", click: function(){ $(this).dialog('close'); }, class: "btn"}
                    ]
                }),
                    form = dialog.find('form');
                form.off('submit.superdesk')//
                .on('submit.superdesk', function(event)
                {
                    var username = $(this).find('#username'), password=$(this).find('#password');
					AuthToken(username.val(), password.val()).on('failed',function(evt, type){
						username.val('');
						password.val('')
					}).on('success', function(){
                        AuthApp.success && AuthApp.success.apply();
						$(dialog).dialog('close');
						self.showed = false;
					});
                    event.preventDefault();

                });
            });
        }
    };
    return AuthApp;
});<commit_msg>NR-226: Create login functionality in Ally framework<commit_after>define
([
    'jquery', 'jquery/superdesk', 'dust/core', 'utils/sha512', 'jquery/tmpl', 'jquery/rest', 'bootstrap',
    'tmpl!auth',
],
function($, superdesk, dust, jsSHA)
{
    var AuthLogin = function(username, password, logintoken){
		var shaObj = new jsSHA(logintoken, "ASCII"),shaPassword = new jsSHA(password, "ASCII"),
			authLogin = new $.rest('Authentication');
			authLogin.resetData().insert({
			UserName: username,
			LoginToken: logintoken,
			HashedLoginToken: shaObj.getHMAC(username+shaPassword.getHash("SHA-512", "HEX"), "ASCII", "SHA-512", "HEX")
		}).done(function(user){
			localStorage.setItem('superdesk.login.session', user.Session);
			localStorage.setItem('superdesk.login.id', user.Id);
			localStorage.setItem('superdesk.login.name', user.UserName);
			localStorage.setItem('superdesk.login.email', user.EMail);
			$(authLogin).trigger('success');
		});
		return $(authLogin);
	},
	AuthToken = function(username, password) {
		var authToken = new $.rest('Authentication');
		authToken.resetData().select({ userName: username }).done(
			function(data){
				authLogin = AuthLogin(username, password, data.Token);
				authLogin.on('failed', function(){
					$(authToken).trigger('failed', 'authToken');
				}).on('success', function(){
					$(authToken).trigger('success');
				});
			}
		);
		return $(authToken);
	},
	AuthApp =
    {
        success: $.noop,
        require: function()
        {
			if(this.showed) return;
            var self = this; // rest
			self.showed = true;
            $.tmpl('auth', null, function(e, o)
            {
                var dialog = $(o).eq(0).dialog
                ({
                    draggable: false,
                    resizable: false,
                    modal: true,
                    width: "40.1709%",
                    buttons:
                    [
                         { text: "Login", click: function(){ $(form).trigger('submit'); }, class: "btn btn-primary"},
                         { text: "Close", click: function(){ $(this).dialog('close'); }, class: "btn"}
                    ]
                }),
                    form = dialog.find('form');
                form.off('submit.superdesk')//
                .on('submit.superdesk', function(event)
                {
                    var username = $(this).find('#username'), password=$(this).find('#password');
					AuthToken(username.val(), password.val()).on('failed',function(evt, type){
						username.val('');
						password.val('')
					}).on('success', function(){
                        AuthApp.success && AuthApp.success.apply();
						$(dialog).dialog('close');
						self.showed = false;
					});
                    event.preventDefault();

                });
            });
        }
    };
    return AuthApp;
});<|endoftext|>


<commit_before>OC.Tags= {
	edit:function(type, cb) {
		if(!type && !this.type) {
			throw { name: 'MissingParameter', message: t('core', 'The object type is not specified.') };
		}
		type = type ? type : this.type;
		var self = this;
		$.when(this._getTemplate()).then(function($tmpl) {
			if(self.$dialog) {
				self.$dialog.ocdialog('close');
			}
			self.$dialog = $tmpl.octemplate({
				addText: t('core', 'Enter new')
			});
			$('body').append(self.$dialog);

			self.$dialog.ready(function() {
				self.$taglist = self.$dialog.find('.taglist');
				self.$taginput = self.$dialog.find('.addinput');
				self.$taglist.on('change', 'input:checkbox', function(event) {
					self._handleChanges(self.$taglist, self.$taginput);
				});
				self.$taginput.on('input', function(event) {
					self._handleChanges(self.$taglist, self.$taginput);
				});
				self.deleteButton = {
					text: t('core', 'Delete'),
					click: function() {self._deleteTags(self, type, self._selectedIds())},
				};
				self.addButton = {
					text: t('core', 'Add'),
					click: function() {self._addTag(self, type, self.$taginput.val())},
				};

				self._fillTagList(type, self.$taglist);
			});

			self.$dialog.ocdialog({
				title: t('core', 'Edit tags'),
				closeOnEscape: true,
				width: 250,
				height: 'auto',
				modal: true,
				//buttons: buttonlist,
				close: function(event, ui) {
					try {
						$(this).ocdialog('destroy').remove();
					} catch(e) {console.warn(e);}
					self.$dialog = null;
				}
			});
		})
		.fail(function(status, error) {
			// If the method is called while navigating away
			// from the page, it is probably not needed ;)
			if(status !== 0) {
				alert(t('core', 'Error loading dialog template: {error}', {error: error}));
			}
		});
	},
	/**
	 * @param string type
	 * @return jQuery.Promise which resolves with an array of ids
	 */
	getIdsForTag:function(type, tag) {
		if(!type && !this.type) {
			throw new Error('The object type is not specified.');
		}
		type = type ? type : this.type;
		var defer = $.Deferred(),
			self = this,
			url = OC.Router.generate('core_tags_ids_for_tag', {type: type});
		$.getJSON(url, {tag: tag}, function(response) {
			if(response.status === 'success') {
				defer.resolve(response.ids);
			} else {
				defer.reject(response);
			}
		});
		return defer.promise();
	},
	/**
	 * @param string type
	 * @return jQuery.Promise which resolves with an array of ids
	 */
	getFavorites:function(type) {
		if(!type && !this.type) {
			throw new Error('The object type is not specified.');
		}
		type = type ? type : this.type;
		var defer = $.Deferred(),
			self = this,
			url = OC.Router.generate('core_tags_favorites', {type: type});
		$.getJSON(url, function(response) {
			if(response.status === 'success') {
				defer.resolve(response.ids);
			} else {
				defer.reject(response);
			}
		});
		return defer.promise();
	},
	/**
	 * @param string type
	 * @return jQuery.Promise which resolves with an array of id/name objects
	 */
	getTags:function(type) {
		if(!type && !this.type) {
			throw new Error('The object type is not specified.');
		}
		type = type ? type : this.type;
		var defer = $.Deferred(),
			self = this,
			url = OC.Router.generate('core_tags_tags', {type: type});
		$.getJSON(url, function(response) {
			if(response.status === 'success') {
				defer.resolve(response.tags);
			} else {
				defer.reject(response);
			}
		});
		return defer.promise();
	},
	/**
	 * @param int id
	 * @param string type
	 * @return jQuery.Promise
	 */
	tagAs:function(id, tag, type) {
		if(!type && !this.type) {
			throw new Error('The object type is not specified.');
		}
		type = type ? type : this.type;
		var defer = $.Deferred(),
			self = this,
			url = OC.Router.generate('core_tags_tag', {type: type, id: id});
		$.post(url, {tag: tag}, function(response) {
			if(response.result === 'success') {
				defer.resolve(response);
			} else {
				defer.reject(response);
			}
		}).fail(function(jqXHR, textStatus, errorThrown) {
			defer.reject(jqXHR.status, errorThrown);
		});
		return defer.promise();
	},
	/**
	 * @param int id
	 * @param string type
	 * @return jQuery.Promise
	 */
	unTag:function(id, tag, type) {
		if(!type && !this.type) {
			throw new Error('The object type is not specified.');
		}
		type = type ? type : this.type;
		var defer = $.Deferred(),
			self = this,
			url = OC.Router.generate('core_tags_untag', {type: type, id: id});
		$.post(url, {tag: tag}, function(response) {
			if(response.result === 'success') {
				defer.resolve(response);
			} else {
				defer.reject(response);
			}
		}).fail(function(jqXHR, textStatus, errorThrown) {
			defer.reject(jqXHR.status, errorThrown);
		});
		return defer.promise();
	},
	/**
	 * @param int id
	 * @param string type
	 * @return jQuery.Promise
	 */
	addToFavorites:function(id, type) {
		if(!type && !this.type) {
			throw new Error('The object type is not specified.');
		}
		type = type ? type : this.type;
		var defer = $.Deferred(),
			self = this,
			url = OC.Router.generate('core_tags_favorite', {type: type, id: id});
		$.post(url, function(response) {
			if(response.result === 'success') {
				defer.resolve(response);
			} else {
				defer.reject(response);
			}
		}).fail(function(jqXHR, textStatus, errorThrown) {
			defer.reject(jqXHR.status, errorThrown);
		});
		return defer.promise();
	},
	/**
	 * @param int id
	 * @param string type
	 * @return jQuery.Promise
	 */
	removeFromFavorites:function(id, type) {
		if(!type && !this.type) {
			throw new Error('The object type is not specified.');
		}
		type = type ? type : this.type;
		var defer = $.Deferred(),
			self = this,
			url = OC.Router.generate('core_tags_unfavorite', {type: type, id: id});
		$.post(url, function(response) {
			if(response.result === 'success') {
				defer.resolve();
			} else {
				defer.reject(response);
			}
		}).fail(function(jqXHR, textStatus, errorThrown) {
			defer.reject(jqXHR.status, errorThrown);
		});
		return defer.promise();
	},
	/**
	 * @param string tag
	 * @param string type
	 * @return jQuery.Promise which resolves with an object with the name and the new id
	 */
	addTag:function(tag, type) {
		if(!type && !this.type) {
			throw new Error('The object type is not specified.');
		}
		type = type ? type : this.type;
		var defer = $.Deferred(),
			self = this,
			url = OC.Router.generate('core_tags_add', {type: type});
		$.post(url,{tag:tag}, function(response) {
			if(typeof cb == 'function') {
				cb(response);
			}
			if(response.status === 'success') {
				defer.resolve({id:response.id, name: tag});
			} else {
				defer.reject(response);
			}
		}).fail(function(jqXHR, textStatus, errorThrown) {
			defer.reject(jqXHR.status, errorThrown);
		});
		return defer.promise();
	},
	/**
	 * @param array tags
	 * @param string type
	 * @return jQuery.Promise
	 */
	deleteTags:function(tags, type) {
		if(!type && !this.type) {
			throw new Error('The object type is not specified.');
		}
		type = type ? type : this.type;
		var defer = $.Deferred(),
			self = this,
			url = OC.Router.generate('core_tags_delete', {type: type});
		if(!tags || !tags.length) {
			throw new Error(t('core', 'No tags selected for deletion.'));
		}
		var self = this;
		$.post(url, {tags:tags}, function(response) {
			if(response.status === 'success') {
				defer.resolve(response.tags);
			} else {
				defer.reject(response);
			}
		}).fail(function(jqXHR, textStatus, errorThrown) {
			defer.reject(jqXHR.status, errorThrown);
		});
		return defer.promise();
	},
	_update:function(tags, type) {
		if(!this.$dialog) {
			return;
		}
		var $taglist = this.$dialog.find('.taglist'),
			self = this;
		$taglist.empty();
		$.each(tags, function(idx, tag) {
			var $item = self.$listTmpl.octemplate({id: tag.id, name: tag.name});
			$item.appendTo($taglist);
		});
		$(this).trigger('change', {type: type, tags: tags});
		if(typeof this.changed === 'function') {
			this.changed(tags);
		}
	},
	_getTemplate: function() {
		var defer = $.Deferred();
		if(!this.$template) {
			var self = this;
			$.get(OC.filePath('core', 'templates', 'tags.html'), function(tmpl) {
				self.$template = $(tmpl);
				self.$listTmpl = self.$template.find('.taglist li:first-child').detach();
				defer.resolve(self.$template);
			})
			.fail(function(jqXHR, textStatus, errorThrown) {
				defer.reject(jqXHR.status, errorThrown);
			});
		} else {
			defer.resolve(this.$template);
		}
		return defer.promise();
	},
	_fillTagList: function(type) {
		var self = this;
		$.when(this.getTags(type))
		.then(function(tags) {
			self._update(tags, type);
		})
		.fail(function(response) {
			console.warn(response);
		});
	},
	_selectedIds: function() {
		return $.map(this.$taglist.find('input:checked'), function(b) {return $(b).val();});
	},
	_handleChanges: function($list, $input) {
		var ids = this._selectedIds();
		var buttons = [];
		if($input.val().length) {
			buttons.push(this.addButton);
		}
		if(ids.length) {
			buttons.push(this.deleteButton);
		}
		this.$dialog.ocdialog('option', 'buttons', buttons);
	},
	_deleteTags: function(self, type, ids) {
		$.when(self.deleteTags(ids, type))
		.then(function() {
			self._fillTagList(type);
			self.$dialog.ocdialog('option', 'buttons', []);
		})
		.fail(function(response) {
			console.warn(response);
		});
	},
	_addTag: function(self, type, tag) {
		$.when(self.addTag(tag, type))
		.then(function(tag) {
			self._fillTagList(type);
			self.$taginput.val('').trigger('input');
		})
		.fail(function(response) {
			console.warn(response);
		});
	}
}

<commit_msg>It's 'status', not 'result'!<commit_after>OC.Tags= {
	edit:function(type, cb) {
		if(!type && !this.type) {
			throw { name: 'MissingParameter', message: t('core', 'The object type is not specified.') };
		}
		type = type ? type : this.type;
		var self = this;
		$.when(this._getTemplate()).then(function($tmpl) {
			if(self.$dialog) {
				self.$dialog.ocdialog('close');
			}
			self.$dialog = $tmpl.octemplate({
				addText: t('core', 'Enter new')
			});
			$('body').append(self.$dialog);

			self.$dialog.ready(function() {
				self.$taglist = self.$dialog.find('.taglist');
				self.$taginput = self.$dialog.find('.addinput');
				self.$taglist.on('change', 'input:checkbox', function(event) {
					self._handleChanges(self.$taglist, self.$taginput);
				});
				self.$taginput.on('input', function(event) {
					self._handleChanges(self.$taglist, self.$taginput);
				});
				self.deleteButton = {
					text: t('core', 'Delete'),
					click: function() {self._deleteTags(self, type, self._selectedIds())},
				};
				self.addButton = {
					text: t('core', 'Add'),
					click: function() {self._addTag(self, type, self.$taginput.val())},
				};

				self._fillTagList(type, self.$taglist);
			});

			self.$dialog.ocdialog({
				title: t('core', 'Edit tags'),
				closeOnEscape: true,
				width: 250,
				height: 'auto',
				modal: true,
				//buttons: buttonlist,
				close: function(event, ui) {
					try {
						$(this).ocdialog('destroy').remove();
					} catch(e) {console.warn(e);}
					self.$dialog = null;
				}
			});
		})
		.fail(function(status, error) {
			// If the method is called while navigating away
			// from the page, it is probably not needed ;)
			if(status !== 0) {
				alert(t('core', 'Error loading dialog template: {error}', {error: error}));
			}
		});
	},
	/**
	 * @param string type
	 * @return jQuery.Promise which resolves with an array of ids
	 */
	getIdsForTag:function(type, tag) {
		if(!type && !this.type) {
			throw new Error('The object type is not specified.');
		}
		type = type ? type : this.type;
		var defer = $.Deferred(),
			self = this,
			url = OC.Router.generate('core_tags_ids_for_tag', {type: type});
		$.getJSON(url, {tag: tag}, function(response) {
			if(response.status === 'success') {
				defer.resolve(response.ids);
			} else {
				defer.reject(response);
			}
		});
		return defer.promise();
	},
	/**
	 * @param string type
	 * @return jQuery.Promise which resolves with an array of ids
	 */
	getFavorites:function(type) {
		if(!type && !this.type) {
			throw new Error('The object type is not specified.');
		}
		type = type ? type : this.type;
		var defer = $.Deferred(),
			self = this,
			url = OC.Router.generate('core_tags_favorites', {type: type});
		$.getJSON(url, function(response) {
			if(response.status === 'success') {
				defer.resolve(response.ids);
			} else {
				defer.reject(response);
			}
		});
		return defer.promise();
	},
	/**
	 * @param string type
	 * @return jQuery.Promise which resolves with an array of id/name objects
	 */
	getTags:function(type) {
		if(!type && !this.type) {
			throw new Error('The object type is not specified.');
		}
		type = type ? type : this.type;
		var defer = $.Deferred(),
			self = this,
			url = OC.Router.generate('core_tags_tags', {type: type});
		$.getJSON(url, function(response) {
			if(response.status === 'success') {
				defer.resolve(response.tags);
			} else {
				defer.reject(response);
			}
		});
		return defer.promise();
	},
	/**
	 * @param int id
	 * @param string type
	 * @return jQuery.Promise
	 */
	tagAs:function(id, tag, type) {
		if(!type && !this.type) {
			throw new Error('The object type is not specified.');
		}
		type = type ? type : this.type;
		var defer = $.Deferred(),
			self = this,
			url = OC.Router.generate('core_tags_tag', {type: type, id: id});
		$.post(url, {tag: tag}, function(response) {
			if(response.status === 'success') {
				defer.resolve(response);
			} else {
				defer.reject(response);
			}
		}).fail(function(jqXHR, textStatus, errorThrown) {
			defer.reject(jqXHR.status, errorThrown);
		});
		return defer.promise();
	},
	/**
	 * @param int id
	 * @param string type
	 * @return jQuery.Promise
	 */
	unTag:function(id, tag, type) {
		if(!type && !this.type) {
			throw new Error('The object type is not specified.');
		}
		type = type ? type : this.type;
		var defer = $.Deferred(),
			self = this,
			url = OC.Router.generate('core_tags_untag', {type: type, id: id});
		$.post(url, {tag: tag}, function(response) {
			if(response.status === 'success') {
				defer.resolve(response);
			} else {
				defer.reject(response);
			}
		}).fail(function(jqXHR, textStatus, errorThrown) {
			defer.reject(jqXHR.status, errorThrown);
		});
		return defer.promise();
	},
	/**
	 * @param int id
	 * @param string type
	 * @return jQuery.Promise
	 */
	addToFavorites:function(id, type) {
		if(!type && !this.type) {
			throw new Error('The object type is not specified.');
		}
		type = type ? type : this.type;
		var defer = $.Deferred(),
			self = this,
			url = OC.Router.generate('core_tags_favorite', {type: type, id: id});
		$.post(url, function(response) {
			if(response.status === 'success') {
				defer.resolve(response);
			} else {
				defer.reject(response);
			}
		}).fail(function(jqXHR, textStatus, errorThrown) {
			defer.reject(jqXHR.status, errorThrown);
		});
		return defer.promise();
	},
	/**
	 * @param int id
	 * @param string type
	 * @return jQuery.Promise
	 */
	removeFromFavorites:function(id, type) {
		if(!type && !this.type) {
			throw new Error('The object type is not specified.');
		}
		type = type ? type : this.type;
		var defer = $.Deferred(),
			self = this,
			url = OC.Router.generate('core_tags_unfavorite', {type: type, id: id});
		$.post(url, function(response) {
			if(response.status === 'success') {
				defer.resolve();
			} else {
				defer.reject(response);
			}
		}).fail(function(jqXHR, textStatus, errorThrown) {
			defer.reject(jqXHR.status, errorThrown);
		});
		return defer.promise();
	},
	/**
	 * @param string tag
	 * @param string type
	 * @return jQuery.Promise which resolves with an object with the name and the new id
	 */
	addTag:function(tag, type) {
		if(!type && !this.type) {
			throw new Error('The object type is not specified.');
		}
		type = type ? type : this.type;
		var defer = $.Deferred(),
			self = this,
			url = OC.Router.generate('core_tags_add', {type: type});
		$.post(url,{tag:tag}, function(response) {
			if(typeof cb == 'function') {
				cb(response);
			}
			if(response.status === 'success') {
				defer.resolve({id:response.id, name: tag});
			} else {
				defer.reject(response);
			}
		}).fail(function(jqXHR, textStatus, errorThrown) {
			defer.reject(jqXHR.status, errorThrown);
		});
		return defer.promise();
	},
	/**
	 * @param array tags
	 * @param string type
	 * @return jQuery.Promise
	 */
	deleteTags:function(tags, type) {
		if(!type && !this.type) {
			throw new Error('The object type is not specified.');
		}
		type = type ? type : this.type;
		var defer = $.Deferred(),
			self = this,
			url = OC.Router.generate('core_tags_delete', {type: type});
		if(!tags || !tags.length) {
			throw new Error(t('core', 'No tags selected for deletion.'));
		}
		var self = this;
		$.post(url, {tags:tags}, function(response) {
			if(response.status === 'success') {
				defer.resolve(response.tags);
			} else {
				defer.reject(response);
			}
		}).fail(function(jqXHR, textStatus, errorThrown) {
			defer.reject(jqXHR.status, errorThrown);
		});
		return defer.promise();
	},
	_update:function(tags, type) {
		if(!this.$dialog) {
			return;
		}
		var $taglist = this.$dialog.find('.taglist'),
			self = this;
		$taglist.empty();
		$.each(tags, function(idx, tag) {
			var $item = self.$listTmpl.octemplate({id: tag.id, name: tag.name});
			$item.appendTo($taglist);
		});
		$(this).trigger('change', {type: type, tags: tags});
		if(typeof this.changed === 'function') {
			this.changed(tags);
		}
	},
	_getTemplate: function() {
		var defer = $.Deferred();
		if(!this.$template) {
			var self = this;
			$.get(OC.filePath('core', 'templates', 'tags.html'), function(tmpl) {
				self.$template = $(tmpl);
				self.$listTmpl = self.$template.find('.taglist li:first-child').detach();
				defer.resolve(self.$template);
			})
			.fail(function(jqXHR, textStatus, errorThrown) {
				defer.reject(jqXHR.status, errorThrown);
			});
		} else {
			defer.resolve(this.$template);
		}
		return defer.promise();
	},
	_fillTagList: function(type) {
		var self = this;
		$.when(this.getTags(type))
		.then(function(tags) {
			self._update(tags, type);
		})
		.fail(function(response) {
			console.warn(response);
		});
	},
	_selectedIds: function() {
		return $.map(this.$taglist.find('input:checked'), function(b) {return $(b).val();});
	},
	_handleChanges: function($list, $input) {
		var ids = this._selectedIds();
		var buttons = [];
		if($input.val().length) {
			buttons.push(this.addButton);
		}
		if(ids.length) {
			buttons.push(this.deleteButton);
		}
		this.$dialog.ocdialog('option', 'buttons', buttons);
	},
	_deleteTags: function(self, type, ids) {
		$.when(self.deleteTags(ids, type))
		.then(function() {
			self._fillTagList(type);
			self.$dialog.ocdialog('option', 'buttons', []);
		})
		.fail(function(response) {
			console.warn(response);
		});
	},
	_addTag: function(self, type, tag) {
		$.when(self.addTag(tag, type))
		.then(function(tag) {
			self._fillTagList(type);
			self.$taginput.val('').trigger('input');
		})
		.fail(function(response) {
			console.warn(response);
		});
	}
}

<|endoftext|>


<commit_before>// @flow

import type { $Application, $Request, $Response } from 'express';
import type Controller from './controllers/Controller';

const getFunctionArgumentNames = (func: Function): Array<string> => {
  // First match everything inside the function argument parens.
  const args = func.toString().match(/function\s.*?\(([^)]*)\)/)[1];

  // Split the arguments string into an array comma delimited.
  return args.split(',').map((argument: string): string =>
    // Ensure no inline comments are parsed and trim the whitespace.
    argument.replace(/\/\*.*\*\//, '').trim(),
  ).filter((argument: string): boolean => !!argument);
};

export default (app: $Application, controllers: Array<Controller>) => {
  controllers.forEach((controller: Controller) => {
    Object.getOwnPropertyNames(
      Object.getPrototypeOf(controller),
    ).forEach((functionName: string) => {
      const mappedFunction = controller[functionName];
      const { httpVerb, route } = mappedFunction;
      if (!httpVerb) {
        return;
      }

      const argumentNames = getFunctionArgumentNames(mappedFunction);

      app[httpVerb](route, (request: $Request, response: $Response) => {
        const values = argumentNames
          .map((argument: string): string => request.params[argument])
          .filter((value: ?Object): boolean => value !== undefined);

        const result = mappedFunction.call(
          controller,
          ...values,
          request.body,
        );

        response.status(result.status).json(result.data);
      });
    });
  });
};
<commit_msg>fix async response in  RouteConfig<commit_after>// @flow

import type { $Application, $Request, $Response } from 'express';
import type Controller from './controllers/Controller';

const getFunctionArgumentNames = (func: Function): Array<string> => {
  // First match everything inside the function argument parens.
  const args = func.toString().match(/function\s.*?\(([^)]*)\)/)[1];

  // Split the arguments string into an array comma delimited.
  return args.split(',').map((argument: string): string =>
    // Ensure no inline comments are parsed and trim the whitespace.
    argument.replace(/\/\*.*\*\//, '').trim(),
  ).filter((argument: string): boolean => !!argument);
};

export default (app: $Application, controllers: Array<Controller>) => {
  controllers.forEach((controller: Controller) => {
    Object.getOwnPropertyNames(
      Object.getPrototypeOf(controller),
    ).forEach((functionName: string) => {
      const mappedFunction = controller[functionName];
      const { httpVerb, route } = mappedFunction;
      if (!httpVerb) {
        return;
      }

      const argumentNames = getFunctionArgumentNames(mappedFunction);

      app[httpVerb](route, async (request: $Request, response: $Response) => {
        const values = argumentNames
          .map((argument: string): string => request.params[argument])
          .filter((value: ?Object): boolean => value !== undefined);

        const result = await mappedFunction.call(
          controller,
          ...values,
          request.body,
        );

        response.status(result.status).json(result.data);
      });
    });
  });
};
<|endoftext|>


<commit_before>/**
 * @fileoverview DTMF
 */

/**
 * @class DTMF
 * @param {SIP.Session} session
 */
(function(SIP) {

var DTMF,
  C = {
    MIN_DURATION:            70,
    MAX_DURATION:            6000,
    DEFAULT_DURATION:        100,
    MIN_INTER_TONE_GAP:      50,
    DEFAULT_INTER_TONE_GAP:  500
  };

DTMF = function(session) {
  var events = [
  'succeeded',
  'failed'
  ];

  this.logger = session.ua.getLogger('sip.invitecontext.dtmf', session.id);
  this.owner = session;
  this.direction = null;
  this.tone = null;
  this.duration = null;

  this.initEvents(events);
};
DTMF.prototype = new SIP.EventEmitter();

DTMF.prototype.send = function(tone, options) {
  var event, eventHandlers, extraHeaders, body;

  if (tone === undefined) {
    throw new TypeError('Not enough arguments');
  }

  this.direction = 'outgoing';

  // Check RTCSession Status
  if (this.owner.status !== SIP.Session.C.STATUS_CONFIRMED &&
    this.owner.status !== SIP.Session.C.STATUS_WAITING_FOR_ACK) {
    throw new SIP.Exceptions.InvalidStateError(this.owner.status);
  }

  // Get DTMF options
  options = options || {};
  extraHeaders = options.extraHeaders ? options.extraHeaders.slice() : [];
  eventHandlers = options.eventHandlers || {};

  // Check tone type
  if (typeof tone === 'string' ) {
    tone = tone.toUpperCase();
  } else if (typeof tone === 'number') {
    tone = tone.toString();
  } else {
    throw new TypeError('Invalid tone: '+ tone);
  }

  // Check tone value
  if (!tone.match(/^[0-9A-D#*]$/)) {
    throw new TypeError('Invalid tone: '+ tone);
  } else {
    this.tone = tone;
  }

  // Duration is checked/corrected in RTCSession
  this.duration = options.duration;

  // Set event handlers
  for (event in eventHandlers) {
    this.on(event, eventHandlers[event]);
  }

  extraHeaders.push('Content-Type: application/dtmf-relay');

  body = "Signal= " + this.tone + "\r\n";
  body += "Duration= " + this.duration;

  this.owner.emit('dtmf', {
    originator: 'local',
    dtmf: this,
    request: this.request
  });

  this.owner.dialog.sendRequest(this, SIP.C.INFO, {
    extraHeaders: extraHeaders,
    body: body
  });
};

/**
 * @private
 */
DTMF.prototype.receiveResponse = function(response) {
  var cause;

  switch(true) {
    case /^1[0-9]{2}$/.test(response.status_code):
      // Ignore provisional responses.
      break;

    case /^2[0-9]{2}$/.test(response.status_code):
      this.emit('succeeded', {
        originator: 'remote',
        response: response
      });
      break;

    default:
      cause = SIP.Utils.sipErrorCause(response.status_code);
      this.emit('failed', {
        originator: 'remote',
        response: response,
        cause: cause
      });
      break;
  }
};

/**
 * @private
 */
DTMF.prototype.onRequestTimeout = function() {
  this.emit('failed', {
    originator: 'system',
    cause: SIP.C.causes.REQUEST_TIMEOUT
  });
  this.owner.onRequestTimeout();
};

/**
 * @private
 */
DTMF.prototype.onTransportError = function() {
  this.emit('failed', {
    originator: 'system',
    cause: SIP.C.causes.CONNECTION_ERROR
  });
  this.owner.onTransportError();
};

/**
 * @private
 */
DTMF.prototype.onDialogError = function(response) {
  this.emit('failed', {
    originator: 'remote',
    response: response,
    cause: SIP.C.causes.DIALOG_ERROR
  });
  this.owner.onDialogError(response);
};

/**
 * @private
 */
DTMF.prototype.init_incoming = function(request) {
  var body,
    reg_tone = /^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/,
    reg_duration = /^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/;

  this.direction = 'incoming';
  this.request = request;

  request.reply(200);

  if (request.body) {
    body = request.body.split('\r\n');
    if (body.length === 2) {
      if (reg_tone.test(body[0])) {
        this.tone = body[0].replace(reg_tone,"$2");
      }
      if (reg_duration.test(body[1])) {
        this.duration = parseInt(body[1].replace(reg_duration,"$2"), 10);
      }
    }
  }

  if (!this.tone || !this.duration) {
    this.logger.warn('invalid INFO DTMF received, discarded');
  } else {
    this.owner.emit('dtmf', {
      originator: 'remote',
      dtmf: this,
      request: request
    });
  }
};

DTMF.C = C;
return DTMF;
}(SIP));
<commit_msg>Session.DTMF methods match 'failed' event API<commit_after>/**
 * @fileoverview DTMF
 */

/**
 * @class DTMF
 * @param {SIP.Session} session
 */
(function(SIP) {

var DTMF,
  C = {
    MIN_DURATION:            70,
    MAX_DURATION:            6000,
    DEFAULT_DURATION:        100,
    MIN_INTER_TONE_GAP:      50,
    DEFAULT_INTER_TONE_GAP:  500
  };

DTMF = function(session) {
  var events = [
  'succeeded',
  'failed'
  ];

  this.logger = session.ua.getLogger('sip.invitecontext.dtmf', session.id);
  this.owner = session;
  this.direction = null;
  this.tone = null;
  this.duration = null;

  this.initEvents(events);
};
DTMF.prototype = new SIP.EventEmitter();

DTMF.prototype.send = function(tone, options) {
  var event, eventHandlers, extraHeaders, body;

  if (tone === undefined) {
    throw new TypeError('Not enough arguments');
  }

  this.direction = 'outgoing';

  // Check RTCSession Status
  if (this.owner.status !== SIP.Session.C.STATUS_CONFIRMED &&
    this.owner.status !== SIP.Session.C.STATUS_WAITING_FOR_ACK) {
    throw new SIP.Exceptions.InvalidStateError(this.owner.status);
  }

  // Get DTMF options
  options = options || {};
  extraHeaders = options.extraHeaders ? options.extraHeaders.slice() : [];
  eventHandlers = options.eventHandlers || {};

  // Check tone type
  if (typeof tone === 'string' ) {
    tone = tone.toUpperCase();
  } else if (typeof tone === 'number') {
    tone = tone.toString();
  } else {
    throw new TypeError('Invalid tone: '+ tone);
  }

  // Check tone value
  if (!tone.match(/^[0-9A-D#*]$/)) {
    throw new TypeError('Invalid tone: '+ tone);
  } else {
    this.tone = tone;
  }

  // Duration is checked/corrected in RTCSession
  this.duration = options.duration;

  // Set event handlers
  for (event in eventHandlers) {
    this.on(event, eventHandlers[event]);
  }

  extraHeaders.push('Content-Type: application/dtmf-relay');

  body = "Signal= " + this.tone + "\r\n";
  body += "Duration= " + this.duration;

  this.owner.emit('dtmf', {
    originator: 'local',
    dtmf: this,
    request: this.request
  });

  this.owner.dialog.sendRequest(this, SIP.C.INFO, {
    extraHeaders: extraHeaders,
    body: body
  });
};

/**
 * @private
 */
DTMF.prototype.receiveResponse = function(response) {
  var cause;

  switch(true) {
    case /^1[0-9]{2}$/.test(response.status_code):
      // Ignore provisional responses.
      break;

    case /^2[0-9]{2}$/.test(response.status_code):
      this.emit('succeeded', {
        originator: 'remote',
        response: response
      });
      break;

    default:
      cause = SIP.Utils.sipErrorCause(response.status_code);
      this.emit('failed', response, cause);
      break;
  }
};

/**
 * @private
 */
DTMF.prototype.onRequestTimeout = function() {
  this.emit('failed', null, SIP.C.causes.REQUEST_TIMEOUT);
  this.owner.onRequestTimeout();
};

/**
 * @private
 */
DTMF.prototype.onTransportError = function() {
  this.emit('failed', null, SIP.C.causes.CONNECTION_ERROR);
  this.owner.onTransportError();
};

/**
 * @private
 */
DTMF.prototype.onDialogError = function(response) {
  this.emit('failed', response, SIP.C.causes.DIALOG_ERROR);
  this.owner.onDialogError(response);
};

/**
 * @private
 */
DTMF.prototype.init_incoming = function(request) {
  var body,
    reg_tone = /^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/,
    reg_duration = /^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/;

  this.direction = 'incoming';
  this.request = request;

  request.reply(200);

  if (request.body) {
    body = request.body.split('\r\n');
    if (body.length === 2) {
      if (reg_tone.test(body[0])) {
        this.tone = body[0].replace(reg_tone,"$2");
      }
      if (reg_duration.test(body[1])) {
        this.duration = parseInt(body[1].replace(reg_duration,"$2"), 10);
      }
    }
  }

  if (!this.tone || !this.duration) {
    this.logger.warn('invalid INFO DTMF received, discarded');
  } else {
    this.owner.emit('dtmf', {
      originator: 'remote',
      dtmf: this,
      request: request
    });
  }
};

DTMF.C = C;
return DTMF;
}(SIP));
<|endoftext|>


<commit_before>/**
 * Created by Wayne on 16/2/22.
 */

var config = require('./config/config');
var setup = require('./config/setup')();
var express = require('./config/express');

new express().listen(config.port);
console.log('process.env.NODE_ENV', process.env.NODE_ENV);

exports.index = function () {

}

exports.index1 = function () {

}

<commit_msg>Add index3<commit_after>/**
 * Created by Wayne on 16/2/22.
 */

var config = require('./config/config');
var setup = require('./config/setup')();
var express = require('./config/express');

new express().listen(config.port);
console.log('process.env.NODE_ENV', process.env.NODE_ENV);

exports.index = function () {

}

exports.index1 = function () {

}

exports.index3 = function () {

}
<|endoftext|>


<commit_before>"use strict";

const config = require("config");
const moment = require('moment');
const fs = require('fs');
const fse = require('fs-extra');

const log = require("./helpers/logger");

let format = process.env.FORMAT || (config.has('app.format') ? config.get('app.format').toLowerCase() : "json");
let writeConfig = process.env.FORMAT|| (config.has('app.write_to_file') ? config.get('app.write_to_file') : "false");

const supportedFormats = ["json", "csv"];
const ts = moment().format("YYYY-MM-DD-HH.mm.ss");
const dir = "./output/" + process.env.NODE_ENV + "-" + ts;

function fileExists(){
    try{
        fs.accessSync('./tableau-templates/' + process.env.NODE_ENV + '.twb');
        return true;
    }catch(e){
        return false;
    }
}

if(fileExists() === true && writeConfig === true){

    if (!fs.existsSync(dir)){
        fs.mkdirSync(dir);
    }

    let destFile = dir + '/' + process.env.NODE_ENV + '.twb';

    fse.copy('./tableau-templates/' + process.env.NODE_ENV + '.twb', destFile, function (err) {
        if (err) {
            log.error("Unable to copy Tableau source file.");
        }

        fs.readFile(destFile, 'utf8', function (readErr, data) {
            if (readErr) {
                log.error("Unable to read Tableau source file");
            } else {
                //replace workbook name
                let out = data.replace(/ directory=''/g, " directory='.//'");
                fs.writeFile(destFile, out, 'utf8', function (writeErr) {
                    if (writeErr) {
                        log.error("Unable to write to Tableau destFile file.");
                    }
                });
            }
        });

    });
}

/**
 * write - files to disk
 * @param fileName - string
 * @param content - string
 * @returns {promise}
 */
const write = function write(fileName, content) {
    return new Promise(function(resolve, reject){

        if(supportedFormats.indexOf(format) === -1){
            log.warn("Invalid config: app.format. Defaulting to json");
            format = "json";
        }

        if(writeConfig === false){
            log.trace("Write to disk disabled");
            return resolve(content);
        }

        log.trace("Writing file to disk using format: " + format);

        // pretty print json
        if(format === "json"){
            content = JSON.stringify(content, null, 4);
        }

        if (!fs.existsSync(dir)){
            try {
                log.trace("Creating dir: " + dir);
                fs.mkdirSync(dir);
            } catch(e) {
                log.error("Error creating directory: " + e);
                reject(e);
            }
        }

        fs.writeFile(dir + "/" + fileName + "." + format, content, "utf8", function (err) {
            if (err) {
                reject(err);
            } else {
                resolve(content);
            }
        });
    });
};

exports.write = write;<commit_msg>Fix so that Tableau file path names are correctly rewritten with each export. #39<commit_after>"use strict";

const config = require("config");
const moment = require('moment');
const fs = require('fs');
const fse = require('fs-extra');

const log = require("./helpers/logger");

let format = process.env.FORMAT || (config.has('app.format') ? config.get('app.format').toLowerCase() : "json");
let writeConfig = process.env.FORMAT|| (config.has('app.write_to_file') ? config.get('app.write_to_file') : "false");

const supportedFormats = ["json", "csv"];
const ts = moment().format("YYYY-MM-DD-HH.mm.ss");
const dir = "./output/" + process.env.NODE_ENV + "-" + ts;

function fileExists(){
    try{
        fs.accessSync('./tableau-templates/' + process.env.NODE_ENV + '.twb');
        return true;
    }catch(e){
        return false;
    }
}

if(fileExists() === true && writeConfig === true){

    if (!fs.existsSync(dir)){
        fs.mkdirSync(dir);
    }

    let destFile = dir + '/' + process.env.NODE_ENV + '.twb';

    fse.copy('./tableau-templates/' + process.env.NODE_ENV + '.twb', destFile, function (err) {
        if (err) {
            log.error("Unable to copy Tableau source file.");
        }

        fs.readFile(destFile, 'utf8', function (readErr, data) {
            if (readErr) {
                log.error("Unable to read Tableau source file");
            } else {
                //replace workbook name
                let out = data.replace(/ directory='.*'/g, " directory='.//'");
                fs.writeFile(destFile, out, 'utf8', function (writeErr) {
                    if (writeErr) {
                        log.error("Unable to write to Tableau destFile file.");
                    }
                });
            }
        });

    });
}

/**
 * write - files to disk
 * @param fileName - string
 * @param content - string
 * @returns {promise}
 */
const write = function write(fileName, content) {
    return new Promise(function(resolve, reject){

        if(supportedFormats.indexOf(format) === -1){
            log.warn("Invalid config: app.format. Defaulting to json");
            format = "json";
        }

        if(writeConfig === false){
            log.trace("Write to disk disabled");
            return resolve(content);
        }

        log.trace("Writing file to disk using format: " + format);

        // pretty print json
        if(format === "json"){
            content = JSON.stringify(content, null, 4);
        }

        if (!fs.existsSync(dir)){
            try {
                log.trace("Creating dir: " + dir);
                fs.mkdirSync(dir);
            } catch(e) {
                log.error("Error creating directory: " + e);
                reject(e);
            }
        }

        fs.writeFile(dir + "/" + fileName + "." + format, content, "utf8", function (err) {
            if (err) {
                reject(err);
            } else {
                resolve(content);
            }
        });
    });
};

exports.write = write;<|endoftext|>