<commit_before>(function(global){

  var WORKER_PATH = 'js/recorderWorker.js';
  var encoderWorker;
  try {
    encoderWorker = new Worker('js/mp3Worker.js');
  } catch (e) {
    console.warn("Web workers are not defined, recording will not work.", e);
  }
  var audio_context, source;

  var __log = function(e, data) {
    log.innerHTML += "\n" + e + " " + (data || '');
  };

  var Recorder = function(cfg){
    var config = cfg || {};
    var bufferLen = config.bufferLen || 4096;
    var self = this;
    var btnPlay = document.createElement('button');
    var btnRecord = document.createElement('button');
    var btnStop = document.createElement('button');
    var btnSave = document.createElement('button');
    if (!config.element) {
      __log('No element specified.  Cannot initialise recorder.');
      return;
    }
    this.vumeter = null;
    this.outputFormat = config.format || config.element.getAttribute('data-format') || 'wav';
    this.callback = config.callback || config.element.getAttribute('data-callback') || 'console.log';
    this.audioData = null;
    this.context = source.context;
    this.node = (this.context.createScriptProcessor ||
           this.context.createJavaScriptNode).call(this.context,
                               bufferLen, 2, 2);
    this.analyser = this.context.createAnalyser();
    this.analyser.smoothingTimeConstant = 0.3;
    this.analyser.fftSize = 1024;
    this.audio = null;
    this.playing = false;
    var worker = new Worker(config.workerPath || WORKER_PATH);
    worker.postMessage({
      command: 'init',
      config: {
      sampleRate: this.context.sampleRate
      }
    });
    var recording = false,
      currCallback;

    this.node.onaudioprocess = function(e){
      if (!recording) return;

      worker.postMessage({
        command: 'record',
        buffer: [
          e.inputBuffer.getChannelData(0)
        ]
      });

      // VU Meter.
      var array =  new Uint8Array(self.analyser.frequencyBinCount);
      self.analyser.getByteFrequencyData(array);
      var values = 0;

      var length = array.length;
      for (var i = 0; i < length; i++) {
          values += array[i];
      }

      var average = values / length;
      self.vumeter.style.width = Math.min(parseInt(average*2),100)+'%';
    };

    this.configure = function(cfg){
      for (var prop in cfg){
        if (cfg.hasOwnProperty(prop)){
          config[prop] = cfg[prop];
        }
      }
    };

    this.toggleRecording = function() {
      if (recording) {
        return self.stop();
      }
      self.record();
      btnStop.disabled = false;
      btnPlay.disabled = true;
      config.element.className += ' recording';
      self.audio = null;
      __log('Recording...');
    };

    this.record = function(){
      recording = true;
    };

    this.stop = function() {
      if (self.playing) {
        self.audio.pause();
        self.audio.currentTime = 0;
        self.playing = false;
        btnPlay.className = 'btn-play';
        btnPlay.innerHTML = '';
      } else {
        self.stopRecording();
        removeClass(config.element, 'recording');
        __log('Stopped recording.');

        // create WAV download link using audio data blob
        self.exportWAV();

        self.clear();
      }
      btnStop.disabled = true;
      btnRecord.disabled = false;
      btnSave.disabled = false;
    };

    this.stopRecording = function(){
      recording = false;
    };

    this.play = function() {
      if (self.playing) {
        self.audio.pause();
        self.playing = false;
        btnStop.disabled = true;
        btnRecord.disabled = false;
        btnPlay.className = 'btn-play';
        btnPlay.innerHTML = '';
      } else {
        if (self.audio === null) {
          var reader = new FileReader();
          reader.onload = function(event) {
            self.audio = new Audio(event.target.result);
            self.play();
          };
            reader.readAsDataURL(self.audioData);
        } else {
          self.audio.play();
          self.playing = true;
          btnStop.disabled = false;
          btnRecord.disabled = true;
          btnPlay.className = 'btn-pause';
          btnPlay.innerHTML = '';
        }
      }
    };

    this.save = function(){
      btnPlay.disabled = true;
      btnStop.disabled = true;
      btnRecord.disabled = true;
      btnSave.disabled = true;
      config.element.className += ' processing';
      if (self.outputFormat === 'mp3') {
        self.convertToMP3();
      } else {
        // Assume WAV.
        global[self.callback](self, self.audioData);
      }
    };

    this.clear = function(){
      worker.postMessage({ command: 'clear' });
      initButtons();
      removeClass(config.element, 'recording');
      removeClass(config.element, 'processing');
    };

    this.getBuffer = function(cb) {
      currCallback = cb || config.callback;
      worker.postMessage({ command: 'getBuffer' });
    };

    this.exportWAV = function(type){
      type = type || config.type || 'audio/wav';
      worker.postMessage({
      command: 'exportWAV',
      type: type
      });
    };

    worker.onmessage = function(e){
      var blob = e.data;
      self.audioData = blob;
      btnPlay.disabled = false;
    };

    this.convertToMP3 = function() {
      var arrayBuffer;
      var fileReader = new FileReader();

      fileReader.onload = function(){
        arrayBuffer = this.result;
        var buffer = new Uint8Array(arrayBuffer),
        data = parseWav(buffer);

        __log("Converting to Mp3");

        encoderWorker.postMessage({ cmd: 'init', config:{
          mode : 3,
          channels:1,
          samplerate: data.sampleRate,
          bitrate: data.bitsPerSample
        }});

        encoderWorker.postMessage({ cmd: 'encode', buf: Uint8ArrayToFloat32Array(data.samples) });
        encoderWorker.postMessage({ cmd: 'finish'});
        encoderWorker.onmessage = function(e) {
          if (e.data.cmd == 'data') {

            __log("Done converting to Mp3");

            var mp3Blob = new Blob([new Uint8Array(e.data.buf)], {type: 'audio/mp3'});
            global[self.callback](self, mp3Blob);

          }
        };
      };

      fileReader.readAsArrayBuffer(this.audioData);
    };

    var encode64 = function(buffer) {
      var binary = '',
        bytes = new Uint8Array( buffer ),
        len = bytes.byteLength;

      for (var i = 0; i < len; i++) {
        binary += String.fromCharCode( bytes[ i ] );
      }
      return global.btoa( binary );
    };

    var parseWav = function(wav) {
      var readInt= function(i, bytes) {
        var ret = 0,
          shft = 0;

        while (bytes) {
          ret += wav[i] << shft;
          shft += 8;
          i++;
          bytes--;
        }
        return ret;
      };
      if (readInt(20, 2) != 1) throw 'Invalid compression code, not PCM';
      if (readInt(22, 2) != 1) throw 'Invalid number of channels, not 1';
      return {
        sampleRate: readInt(24, 4),
        bitsPerSample: readInt(34, 2),
        samples: wav.subarray(44)
      };
    };

    var Uint8ArrayToFloat32Array= function(u8a){
      var f32Buffer = new Float32Array(u8a.length);
      for (var i = 0; i < u8a.length; i++) {
        var value = u8a[i<<1] + (u8a[(i<<1)+1]<<8);
        if (value >= 0x8000) value |= ~0x7FFF;
        f32Buffer[i] = value / 0x8000;
      }
      return f32Buffer;
    };

    var removeClass= function(el, name) {
      el.className = el.className.replace(' '+name, '');
    };

    var buildInterface = function() {
      __log('Building interface...');
      initButtons();
      config.element.appendChild(btnPlay);
      config.element.appendChild(btnRecord);
      config.element.appendChild(btnStop);
      config.element.appendChild(btnSave);
      self.vumeter = config.element.querySelector('.btn-record .vumeter');
      __log('Interface built.');
    };
    var initButtons =function() {
      btnRecord.onclick = self.toggleRecording;
      btnRecord.className = 'btn-record';
      btnRecord.innerHTML = '';
      btnRecord.disabled = false;
      btnStop.onclick = self.stop;
      btnStop.className = 'btn-stop';
      btnStop.innerHTML = '';
      btnStop.disabled = true;
      btnPlay.onclick = self.play;
      btnPlay.className = 'btn-play';
      btnPlay.innerHTML = '';
      btnPlay.disabled = true;
      btnSave.onclick = self.save;
      btnSave.className = 'btn-save';
      btnSave.innerHTML = '';
      btnSave.disabled = true;
    };

    source.connect(this.analyser);
    this.analyser.connect(this.node);
    this.node.connect(this.context.destination);

    buildInterface();

    return this;
    // __log('Recorder initialised.');
  };

  global.Recorder = Recorder;

  var initRecorder = function() {
    try {
      // webkit shim
      global.AudioContext = global.AudioContext || global.webkitAudioContext;
      navigator.getUserMedia = ( navigator.getUserMedia ||
          navigator.webkitGetUserMedia ||
          navigator.mozGetUserMedia ||
          navigator.msGetUserMedia);
      global.URL = global.URL || global.webkitURL;

      audio_context = new AudioContext();
      __log('Audio context set up.');
      __log('navigator.getUserMedia ' + (navigator.getUserMedia ? 'available.' : 'not present!'));
    } catch (e) {
      alert('No web audio support in this browser!');
    }

    navigator.getUserMedia({audio: true}, startUserMedia, function(e) {
      __log('No live audio input: ' + e);
    });
  };

  var startUserMedia = function(stream) {
    var recorders = document.querySelectorAll('.RecordMP3js-recorder');
    source = audio_context.createMediaStreamSource(stream);
    __log('Media stream created.' );
    __log("input sample rate " +source.context.sampleRate);

    for(var i=0; i<recorders.length; i++) {
      recorders[i].recorder = new Recorder({element: recorders[i]});
    }
  };

  if (global.addEventListener) {
    global.addEventListener('load', initRecorder, false);
  } else if (global.attachEvent) {
    global.attachEvent('onload', initRecorder);
  }

})(exports || window);
<commit_msg>formatting<commit_after>(function(global) {

  var WORKER_PATH = 'js/recorderWorker.js';
  var encoderWorker;
  try {
    encoderWorker = new Worker('js/mp3Worker.js');
  } catch (e) {
    console.warn("Web workers are not defined, recording will not work.", e);
  }
  var audio_context, source;

  var __log = function(e, data) {
    log.innerHTML += "\n" + e + " " + (data || '');
  };

  var Recorder = function(cfg) {
    var config = cfg || {};
    var bufferLen = config.bufferLen || 4096;
    var self = this;
    var btnPlay = document.createElement('button');
    var btnRecord = document.createElement('button');
    var btnStop = document.createElement('button');
    var btnSave = document.createElement('button');
    if (!config.element) {
      __log('No element specified.  Cannot initialise recorder.');
      return;
    }
    this.vumeter = null;
    this.outputFormat = config.format || config.element.getAttribute('data-format') || 'wav';
    this.callback = config.callback || config.element.getAttribute('data-callback') || 'console.log';
    this.audioData = null;
    this.context = source.context;
    this.node = (this.context.createScriptProcessor ||
      this.context.createJavaScriptNode).call(this.context,
      bufferLen, 2, 2);
    this.analyser = this.context.createAnalyser();
    this.analyser.smoothingTimeConstant = 0.3;
    this.analyser.fftSize = 1024;
    this.audio = null;
    this.playing = false;
    var worker = new Worker(config.workerPath || WORKER_PATH);
    worker.postMessage({
      command: 'init',
      config: {
        sampleRate: this.context.sampleRate
      }
    });
    var recording = false,
      currCallback;

    this.node.onaudioprocess = function(e) {
      if (!recording) return;

      worker.postMessage({
        command: 'record',
        buffer: [
          e.inputBuffer.getChannelData(0)
        ]
      });

      // VU Meter.
      var array = new Uint8Array(self.analyser.frequencyBinCount);
      self.analyser.getByteFrequencyData(array);
      var values = 0;

      var length = array.length;
      for (var i = 0; i < length; i++) {
        values += array[i];
      }

      var average = values / length;
      self.vumeter.style.width = Math.min(parseInt(average * 2), 100) + '%';
    };

    this.configure = function(cfg) {
      for (var prop in cfg) {
        if (cfg.hasOwnProperty(prop)) {
          config[prop] = cfg[prop];
        }
      }
    };

    this.toggleRecording = function() {
      if (recording) {
        return self.stop();
      }
      self.record();
      btnStop.disabled = false;
      btnPlay.disabled = true;
      config.element.className += ' recording';
      self.audio = null;
      __log('Recording...');
    };

    this.record = function() {
      recording = true;
    };

    this.stop = function() {
      if (self.playing) {
        self.audio.pause();
        self.audio.currentTime = 0;
        self.playing = false;
        btnPlay.className = 'btn-play';
        btnPlay.innerHTML = '';
      } else {
        self.stopRecording();
        removeClass(config.element, 'recording');
        __log('Stopped recording.');

        // create WAV download link using audio data blob
        self.exportWAV();

        self.clear();
      }
      btnStop.disabled = true;
      btnRecord.disabled = false;
      btnSave.disabled = false;
    };

    this.stopRecording = function() {
      recording = false;
    };

    this.play = function() {
      if (self.playing) {
        self.audio.pause();
        self.playing = false;
        btnStop.disabled = true;
        btnRecord.disabled = false;
        btnPlay.className = 'btn-play';
        btnPlay.innerHTML = '';
      } else {
        if (self.audio === null) {
          var reader = new FileReader();
          reader.onload = function(event) {
            self.audio = new Audio(event.target.result);
            self.play();
          };
          reader.readAsDataURL(self.audioData);
        } else {
          self.audio.play();
          self.playing = true;
          btnStop.disabled = false;
          btnRecord.disabled = true;
          btnPlay.className = 'btn-pause';
          btnPlay.innerHTML = '';
        }
      }
    };

    this.save = function() {
      btnPlay.disabled = true;
      btnStop.disabled = true;
      btnRecord.disabled = true;
      btnSave.disabled = true;
      config.element.className += ' processing';
      if (self.outputFormat === 'mp3') {
        self.convertToMP3();
      } else {
        // Assume WAV.
        global[self.callback](self, self.audioData);
      }
    };

    this.clear = function() {
      worker.postMessage({
        command: 'clear'
      });
      initButtons();
      removeClass(config.element, 'recording');
      removeClass(config.element, 'processing');
    };

    this.getBuffer = function(cb) {
      currCallback = cb || config.callback;
      worker.postMessage({
        command: 'getBuffer'
      });
    };

    this.exportWAV = function(type) {
      type = type || config.type || 'audio/wav';
      worker.postMessage({
        command: 'exportWAV',
        type: type
      });
    };

    worker.onmessage = function(e) {
      var blob = e.data;
      self.audioData = blob;
      btnPlay.disabled = false;
    };

    this.convertToMP3 = function() {
      var arrayBuffer;
      var fileReader = new FileReader();

      fileReader.onload = function() {
        arrayBuffer = this.result;
        var buffer = new Uint8Array(arrayBuffer),
          data = parseWav(buffer);

        __log("Converting to Mp3");

        encoderWorker.postMessage({
          cmd: 'init',
          config: {
            mode: 3,
            channels: 1,
            samplerate: data.sampleRate,
            bitrate: data.bitsPerSample
          }
        });

        encoderWorker.postMessage({
          cmd: 'encode',
          buf: Uint8ArrayToFloat32Array(data.samples)
        });
        encoderWorker.postMessage({
          cmd: 'finish'
        });
        encoderWorker.onmessage = function(e) {
          if (e.data.cmd == 'data') {

            __log("Done converting to Mp3");

            var mp3Blob = new Blob([new Uint8Array(e.data.buf)], {
              type: 'audio/mp3'
            });
            global[self.callback](self, mp3Blob);

          }
        };
      };

      fileReader.readAsArrayBuffer(this.audioData);
    };

    var encode64 = function(buffer) {
      var binary = '',
        bytes = new Uint8Array(buffer),
        len = bytes.byteLength;

      for (var i = 0; i < len; i++) {
        binary += String.fromCharCode(bytes[i]);
      }
      return global.btoa(binary);
    };

    var parseWav = function(wav) {
      var readInt = function(i, bytes) {
        var ret = 0,
          shft = 0;

        while (bytes) {
          ret += wav[i] << shft;
          shft += 8;
          i++;
          bytes--;
        }
        return ret;
      };
      if (readInt(20, 2) != 1) throw 'Invalid compression code, not PCM';
      if (readInt(22, 2) != 1) throw 'Invalid number of channels, not 1';
      return {
        sampleRate: readInt(24, 4),
        bitsPerSample: readInt(34, 2),
        samples: wav.subarray(44)
      };
    };

    var Uint8ArrayToFloat32Array = function(u8a) {
      var f32Buffer = new Float32Array(u8a.length);
      for (var i = 0; i < u8a.length; i++) {
        var value = u8a[i << 1] + (u8a[(i << 1) + 1] << 8);
        if (value >= 0x8000) value |= ~0x7FFF;
        f32Buffer[i] = value / 0x8000;
      }
      return f32Buffer;
    };

    var removeClass = function(el, name) {
      el.className = el.className.replace(' ' + name, '');
    };

    var buildInterface = function() {
      __log('Building interface...');
      initButtons();
      config.element.appendChild(btnPlay);
      config.element.appendChild(btnRecord);
      config.element.appendChild(btnStop);
      config.element.appendChild(btnSave);
      self.vumeter = config.element.querySelector('.btn-record .vumeter');
      __log('Interface built.');
    };
    var initButtons = function() {
      btnRecord.onclick = self.toggleRecording;
      btnRecord.className = 'btn-record';
      btnRecord.innerHTML = '';
      btnRecord.disabled = false;
      btnStop.onclick = self.stop;
      btnStop.className = 'btn-stop';
      btnStop.innerHTML = '';
      btnStop.disabled = true;
      btnPlay.onclick = self.play;
      btnPlay.className = 'btn-play';
      btnPlay.innerHTML = '';
      btnPlay.disabled = true;
      btnSave.onclick = self.save;
      btnSave.className = 'btn-save';
      btnSave.innerHTML = '';
      btnSave.disabled = true;
    };

    source.connect(this.analyser);
    this.analyser.connect(this.node);
    this.node.connect(this.context.destination);

    buildInterface();

    return this;
    // __log('Recorder initialised.');
  };

  global.Recorder = Recorder;

  var initRecorder = function() {
    try {
      // webkit shim
      global.AudioContext = global.AudioContext || global.webkitAudioContext;
      navigator.getUserMedia = (navigator.getUserMedia ||
        navigator.webkitGetUserMedia ||
        navigator.mozGetUserMedia ||
        navigator.msGetUserMedia);
      global.URL = global.URL || global.webkitURL;

      audio_context = new AudioContext();
      __log('Audio context set up.');
      __log('navigator.getUserMedia ' + (navigator.getUserMedia ? 'available.' : 'not present!'));
    } catch (e) {
      alert('No web audio support in this browser!');
    }

    navigator.getUserMedia({
      audio: true
    }, startUserMedia, function(e) {
      __log('No live audio input: ' + e);
    });
  };

  var startUserMedia = function(stream) {
    var recorders = document.querySelectorAll('.RecordMP3js-recorder');
    source = audio_context.createMediaStreamSource(stream);
    __log('Media stream created.');
    __log("input sample rate " + source.context.sampleRate);

    for (var i = 0; i < recorders.length; i++) {
      recorders[i].recorder = new Recorder({
        element: recorders[i]
      });
    }
  };

  if (global.addEventListener) {
    global.addEventListener('load', initRecorder, false);
  } else if (global.attachEvent) {
    global.attachEvent('onload', initRecorder);
  }

})(exports || window);
<|endoftext|>


<commit_before>$(document).ready(function() {

	$('#parameters').click(function() {
		initParametersUI();
		changeContent("lang");
	});

	//Internationalize content
	$("#lang-label").text(window.i18n.msgStore['facetlanguage']);
	$("#alert-label").text(window.i18n.msgStore['alerts']);
	$("#savedsearch-label").text(window.i18n.msgStore['savedsearch']);
	$("#param-label").text(window.i18n.msgStore['param']);

	var param = retrieveParamValue();

	changeContent(param);

	$("#lang-link").click(function() {changeContent("lang")});
	$("#alert-link").click(function() {changeContent("alert")});
	$("#savedsearch-link").click(function() {changeContent("savedsearch")});

});
	var d;
	var alertsTable;
	var searchesTable;

	function initParametersUI() {
		$("#parametersUi").show();
		$("#results_div").hide();
		$("#search_information").hide();
		$("#sortMode").hide();
		$("#advancedSearch").hide();
		$("#favoritesUi").hide();
		$("#searchBar").show();
		clearActiveLinks();
		$("#parameters").addClass("active");
	}

	function clearActiveLinks() {
		$("#loginDatafariLinks").find(".active").removeClass("active");
	}

	function retrieveParamValue() {
		var query = window.location.search.substring(1);
		var vars = query.split("&");
		for (var i=0;i<vars.length;i++) {
			var pair = vars[i].split("=");
			if(pair[0] == "param") {
				return pair[1];
				break;
			}
		}
	}

	function changeContent(param) {
		clear();
		if(param == "lang") {
			$("#param-content-title").text(window.i18n.msgStore['param-lang']);
			$("#lang-link .link-icon").addClass("selected");
			$("#lang-link .link-label").addClass("selected");
			createLangContent();
		} else if(param == "alert") {
			$("#param-content-title").text(window.i18n.msgStore['param-alert']);
			$("#alert-link .link-icon").addClass("selected");
			$("#alert-link .link-label").addClass("selected");
			createAlertContent();
		}
	}

	function clear() {
		$("#lang-link .link-icon").removeClass("selected");
		$("#alert-link .link-icon").removeClass("selected");
		$("#lang-link .link-label").removeClass("selected");
		$("#alert-link .link-label").removeClass("selected");
	}

	function createLangContent() {
		var languages = ['en', 'fr', 'it', 'pt_br', 'de'];

		$("#param-content").html("
" + window.i18n.msgStore['lang-choice'] + "
");
		var inputs = $("

")
		$.each(languages, function( index, value ) {
			inputs.append("<input type='radio' name='lang' id='" + value + "' value='" + value + "'> " + window.i18n.msgStore[value+'_locale'] + "
");
		});

		$("#param-content").append(inputs);

		// Select the language for languageSelectorWidget, based on the window.i18n language detected from the browser/system
		inputs.find('input[value="'+ window.i18n.language + '"]').prop('checked', true);
		inputs.find('input').show();

		$("#param-content").append("

<input type='button' name='validate-lang' id='validate-lang' value='" + window.i18n.msgStore['validate'] + "'/>
");
		$("#validate-lang").click(function() {
			var selectedLang = $('input[name=lang]:checked').val();

			// Save user language in the 'lang' table of Cassandra
			$.post('./applyLang',{"lang":selectedLang}, function() {
				// Function executed every time the user changes the language of
				// Datafari
				window.i18n.userSelected(selectedLang);
			});
		});
	}

	function createAlertContent() {
		var dataString = "keyword=";
		$("#param-content").html("
<button onclick='javascript:addAlert();' id='addAlertButton'>"+window.i18n.msgStore['addAlert']+"</button>
");
		$("#param-content").append("

");
		$.ajax({			//Ajax request to the doGet of the Alerts servlet
	        type: "GET",
	        url: "./admin/Alerts",
	        data: dataString,
	    	beforeSend: function(jqXHR, settings){
	    		$("#alertsListDiv").html("

");
	    	},
	        //if received a response from the server
	        success: function( data, textStatus, jqXHR) {
	        	if(data.toString().indexOf("Error code : ")!==-1){
	        		console.log(data);
	        	} else if(data.alerts!=undefined){
	        		$("#alertsListDiv").html("

"+window.i18n.msgStore['search']+"	"+window.i18n.msgStore['subject']+"	"+window.i18n.msgStore['mail']+"	"+window.i18n.msgStore['send-frequency']+"	"+window.i18n.msgStore['delete']+"

");
	        		//get the data in a global var so it can be used in edit() or remove()
	        		d=data;
	        		var numb = data.alerts.length;
	        		var i = 0;
					while (i<numb){	//While they are still alerts to print
						var doc = data.alerts[i];
						//Print the alert with an href of the keyword towards edit()
						$("#alerts_table tbody").append("
"+doc.keyword+"	"+doc.subject+"	"+doc.mail+"	"+window.i18n.msgStore[doc.frequency]+" <button onclick='javascript: modify("+i+")'>"+window.i18n.msgStore['modify']+"</button>	x
");
						//Print a button with an href towards remove()
						i++;
					}
					alertsTable = $("#alerts_table").DataTable(
	        				{
	        					"info":false,
	        					"lengthChange":false,
	        					"searching":false,
	        					"columns": [
	        						null,
	        						null,
	        						null,
	        						null,
	        						{ "orderable": false }
	        					]
	        				}
	        		);
	        	}else{
	        		$("#alertsListDiv").html("
"+window.i18n.msgStore['noAlerts']+"
");
	        	}
	        },

	        //If there was no response from the server
	        error: function(jqXHR, textStatus, errorThrown){
	            if(jqXHR.responseText==="error connecting to the database"){
	            	console.log(window.i18n.msgStore['dbError'])
	          	}else {
	                console.log("Something really bad happened " + textStatus);
	          	}
	        }
	    });
	}

	function addAlert() {
		$("#addAlertDiv").html("");
		$("#addAlertDiv").append("<form id=\"add\" role=\"form\">");
		$("#add").append("

");
		var tr = $("
");
		tr.append(""+window.i18n.msgStore['keyword']+"	");
		tr.append("<input required type=\"text\" id=\"keyword\" name=\"keyword\" placeholder="+window.i18n.msgStore['keyword']+"/>	");
		$("#addAlertTable").append(tr);
		tr = $("
");
		tr.append(""+window.i18n.msgStore['subject']+"	");
		tr.append("<input required type=\"text\" id=\"subject\" name=\"subject\" placeholder="+window.i18n.msgStore['subject']+"/>	");
		$("#addAlertTable").append(tr);
		tr = $("
");
		tr.append(""+window.i18n.msgStore['mail']+"	");
		tr.append("<input required type=\"text\" id=\"mail\" name=\"mail\" placeholder="+window.i18n.msgStore['mail']+"/>	");
		$("#addAlertTable").append(tr);
		tr = $("
");
		tr.append(""+window.i18n.msgStore['core']+"	");
		tr.append("<input required type=\"text\" id=\"core\" name=\"core\" placeholder=\"Core\" value=\"FileShare\"/>	");
		$("#addAlertTable").append(tr);
		tr = $("
");
		tr.append(""+window.i18n.msgStore['frequency']+"	");
		tr.append("<select required id=\"frequency\" name=\"frequency\" class=\"col-sm-4\">	<OPTION value='hourly'>"+window.i18n.msgStore['hourly']+"</OPTION><OPTION value='daily'>"+window.i18n.msgStore['daily']+"</OPTION><OPTION value='weekly'>"+window.i18n.msgStore['weekly']+"</OPTION></select>	");
		$("#addAlertTable").append(tr);
		tr = $("
");
		tr.append("<input type=\"Submit\" id=\"newAlerts\" name=\"AddAlert\" value=\""+window.i18n.msgStore['confirm']+"\"/><button id='addAlertCancel'>"+window.i18n.msgStore['cancel']+"</button>	");
		$("#addAlertTable").append(tr);
		$("#addAlertDiv").append("</form>");
		$("#addAlertDiv").append("

");

		$("#addAlertCancel").click(function() {initCreateAlertButton();});

		$("#add").submit(function(e){
	        e.preventDefault();
	 	});

		$("#add").submit(function(e){
			 var datastring = $("#add").serialize();
		 		$.ajax({ 				//Ajax request to the doPost of the Alerts servlet
		       		type: "POST",
		        	url: "./admin/Alerts",
		       	 	data: datastring,
		        	//if received a response from the server
		        	success: function(data, textStatus, jqXHR) {
		        		if(data.toString().indexOf("Error code : ")!==-1){
		        			$("#addAlertMessage").addClass("fail");
		    				$("#addAlertMessage").html(data);
		            	}else{
		            		$("#addAlertMessage").addClass("success");
		            		$("#addAlertMessage").html(window.i18n.msgStore['success']);
		            		$("#addAlertMessage").fadeOut(1500,function(){
		            			destroyAlertsTable();
		            			createAlertContent();});
		            	}
		        	},
		        	error: function(jqXHR, textStatus, errorThrown){
		        		 if(jqXHR.responseText==="error connecting to the database"){
		               		$("#addAlertsForm").append(window.i18n.msgStore['dbError'])
		               	}else {
		                     console.log("Something really bad happened " + textStatus);
		                     $("#addAlertsForm").html(jqXHR.responseText);
		               	}
		        	},
		        	//capture the request before it was sent to server
		        	beforeSend: function(jqXHR, settings){
		            	//disable the button until we get the response
		            	$('#newAlerts').attr("disabled", true);
		        	},
		        	//called after the response or error functions are finsihed
		        	complete: function(jqXHR, textStatus){
		            	//enable the button
		            	$('#add').attr("disabled", false);
		        	}
		 		});
		 });
	}

	function initCreateAlertButton() {
		$("#addAlertDiv").html("<button onclick='javascript:addAlert();' id='addAlertButton'>"+window.i18n.msgStore['addAlert']+"</button>");
	}

	function modify(i) {
		$("#frequency-"+i).html("<select required id=\"select-frequency-" + i + "\" name=\"frequency\" class=\"col-sm-4\">	<OPTION value='hourly'>"+window.i18n.msgStore['hourly']+"</OPTION><OPTION value='daily'>"+window.i18n.msgStore['daily']+"</OPTION><OPTION value='weekly'>"+window.i18n.msgStore['weekly']+"</OPTION></select> <button onclick='javascript: validate("+i+")' >"+window.i18n.msgStore['validate']+"</button>")
		$("#select-frequency-" + i).val(d.alerts[i].frequency);
	}

	function validate(i) {
		var id = "_id="+d.alerts[i]._id;
		var datastring = "";
		for (var key in d.alerts[i]) {
		    if (datastring != "") {
		    	datastring += "&";
		    }
		    var value = "";
		    if(key==="frequency") {
		    	value = $("#select-frequency-" + i).val();
		    } else {
		    	value = d.alerts[i][key];
		    }
		    datastring += key + "=" + value;
		}
		$.ajax({			 	//Ajax request to the doPost of the Alerts servlet
	        type: "POST",
	        url: "./admin/Alerts",
	        data: datastring,
	        //if received a response from the server
	        success: function(data, textStatus, jqXHR) {
	        	if(data.toString().indexOf("Error code : ")!==-1){
	        		console.log(data);
	        	}else{
	        		d.alerts[i].frequency = $("#select-frequency-" + i).val();
	        		d.alerts[i]._id = JSON.parse(data).uuid;
	        		alertsTable.cell("#frequency-"+i).data(window.i18n.msgStore[d.alerts[i].frequency]+" <button onclick='javascript: modify("+i+")'>"+window.i18n.msgStore['modify']+"</button>").draw();
	        	}
	        },
	        error: function(jqXHR, textStatus, errorThrown){
	             console.log("Something really bad happened " + textStatus);
	        }
		});
	}

	function remove(i){
		// get the id of the alert to remove and serialize it
		var id = "_id="+d.alerts[i]._id;
		$.ajax({		//Ajax request to the doPost of the Alerts servlet
	        type: "POST",
	        url: "./admin/Alerts",
	        data: id,
	        //if received a response from the server
	        success: function(data, textStatus, jqXHR) {
	        	if(data.toString().indexOf("Error code : ")!==-1){
	        		console.log(data);
	        	}else{
	        		//Suppress the row of the tab that was show the now removed alert
//	        		var row = document.getElementById(i);
//	            	row.parentNode.removeChild(row);
	            	alertsTable
	                .row( "#alert-" + i)
	                .remove()
	                .draw();

	            	var nbData = alertsTable.column(0).data().length
					if(nbData < 1 ) {
						$("#alertsListDiv").html("
"+window.i18n.msgStore['noAlerts']+"
");
						destroyAlertsTable();
					}
	        	}
	        },
	        //If there was no resonse from the server
	        error: function(jqXHR, textStatus, errorThrown){
	             console.log("Something really bad happened " + textStatus);
	        }
		});
	}

	function destroyDatatables() {
		destroyAlertsTable();
	}

	function destroyAlertsTable() {
		if(alertsTable !== undefined) {
			alertsTable.clear();
			alertsTable.destroy(true);
			alertsTable = undefined;
		}
	}
<commit_msg>Bug Fix DATAFARI-220 : Russian language not visible in the Datafari UI<commit_after>$(document).ready(function() {

	$('#parameters').click(function() {
		initParametersUI();
		changeContent("lang");
	});

	//Internationalize content
	$("#lang-label").text(window.i18n.msgStore['facetlanguage']);
	$("#alert-label").text(window.i18n.msgStore['alerts']);
	$("#savedsearch-label").text(window.i18n.msgStore['savedsearch']);
	$("#param-label").text(window.i18n.msgStore['param']);

	var param = retrieveParamValue();

	changeContent(param);

	$("#lang-link").click(function() {changeContent("lang")});
	$("#alert-link").click(function() {changeContent("alert")});
	$("#savedsearch-link").click(function() {changeContent("savedsearch")});

});
	var d;
	var alertsTable;
	var searchesTable;

	function initParametersUI() {
		$("#parametersUi").show();
		$("#results_div").hide();
		$("#search_information").hide();
		$("#sortMode").hide();
		$("#advancedSearch").hide();
		$("#favoritesUi").hide();
		$("#searchBar").show();
		clearActiveLinks();
		$("#parameters").addClass("active");
	}

	function clearActiveLinks() {
		$("#loginDatafariLinks").find(".active").removeClass("active");
	}

	function retrieveParamValue() {
		var query = window.location.search.substring(1);
		var vars = query.split("&");
		for (var i=0;i<vars.length;i++) {
			var pair = vars[i].split("=");
			if(pair[0] == "param") {
				return pair[1];
				break;
			}
		}
	}

	function changeContent(param) {
		clear();
		if(param == "lang") {
			$("#param-content-title").text(window.i18n.msgStore['param-lang']);
			$("#lang-link .link-icon").addClass("selected");
			$("#lang-link .link-label").addClass("selected");
			createLangContent();
		} else if(param == "alert") {
			$("#param-content-title").text(window.i18n.msgStore['param-alert']);
			$("#alert-link .link-icon").addClass("selected");
			$("#alert-link .link-label").addClass("selected");
			createAlertContent();
		}
	}

	function clear() {
		$("#lang-link .link-icon").removeClass("selected");
		$("#alert-link .link-icon").removeClass("selected");
		$("#lang-link .link-label").removeClass("selected");
		$("#alert-link .link-label").removeClass("selected");
	}

	function createLangContent() {
		var languages = ['en', 'fr', 'it', 'pt_br', 'de', 'ru'];

		$("#param-content").html("
" + window.i18n.msgStore['lang-choice'] + "
");
		var inputs = $("

")
		$.each(languages, function( index, value ) {
			inputs.append("<input type='radio' name='lang' id='" + value + "' value='" + value + "'> " + window.i18n.msgStore[value+'_locale'] + "
");
		});

		$("#param-content").append(inputs);

		// Select the language for languageSelectorWidget, based on the window.i18n language detected from the browser/system
		inputs.find('input[value="'+ window.i18n.language + '"]').prop('checked', true);
		inputs.find('input').show();

		$("#param-content").append("

<input type='button' name='validate-lang' id='validate-lang' value='" + window.i18n.msgStore['validate'] + "'/>
");
		$("#validate-lang").click(function() {
			var selectedLang = $('input[name=lang]:checked').val();

			// Save user language in the 'lang' table of Cassandra
			$.post('./applyLang',{"lang":selectedLang}, function() {
				// Function executed every time the user changes the language of
				// Datafari
				window.i18n.userSelected(selectedLang);
			});
		});
	}

	function createAlertContent() {
		var dataString = "keyword=";
		$("#param-content").html("
<button onclick='javascript:addAlert();' id='addAlertButton'>"+window.i18n.msgStore['addAlert']+"</button>
");
		$("#param-content").append("

");
		$.ajax({			//Ajax request to the doGet of the Alerts servlet
	        type: "GET",
	        url: "./admin/Alerts",
	        data: dataString,
	    	beforeSend: function(jqXHR, settings){
	    		$("#alertsListDiv").html("

");
	    	},
	        //if received a response from the server
	        success: function( data, textStatus, jqXHR) {
	        	if(data.toString().indexOf("Error code : ")!==-1){
	        		console.log(data);
	        	} else if(data.alerts!=undefined){
	        		$("#alertsListDiv").html("

"+window.i18n.msgStore['search']+"	"+window.i18n.msgStore['subject']+"	"+window.i18n.msgStore['mail']+"	"+window.i18n.msgStore['send-frequency']+"	"+window.i18n.msgStore['delete']+"

");
	        		//get the data in a global var so it can be used in edit() or remove()
	        		d=data;
	        		var numb = data.alerts.length;
	        		var i = 0;
					while (i<numb){	//While they are still alerts to print
						var doc = data.alerts[i];
						//Print the alert with an href of the keyword towards edit()
						$("#alerts_table tbody").append("
"+doc.keyword+"	"+doc.subject+"	"+doc.mail+"	"+window.i18n.msgStore[doc.frequency]+" <button onclick='javascript: modify("+i+")'>"+window.i18n.msgStore['modify']+"</button>	x
");
						//Print a button with an href towards remove()
						i++;
					}
					alertsTable = $("#alerts_table").DataTable(
	        				{
	        					"info":false,
	        					"lengthChange":false,
	        					"searching":false,
	        					"columns": [
	        						null,
	        						null,
	        						null,
	        						null,
	        						{ "orderable": false }
	        					]
	        				}
	        		);
	        	}else{
	        		$("#alertsListDiv").html("
"+window.i18n.msgStore['noAlerts']+"
");
	        	}
	        },

	        //If there was no response from the server
	        error: function(jqXHR, textStatus, errorThrown){
	            if(jqXHR.responseText==="error connecting to the database"){
	            	console.log(window.i18n.msgStore['dbError'])
	          	}else {
	                console.log("Something really bad happened " + textStatus);
	          	}
	        }
	    });
	}

	function addAlert() {
		$("#addAlertDiv").html("");
		$("#addAlertDiv").append("<form id=\"add\" role=\"form\">");
		$("#add").append("

");
		var tr = $("
");
		tr.append(""+window.i18n.msgStore['keyword']+"	");
		tr.append("<input required type=\"text\" id=\"keyword\" name=\"keyword\" placeholder="+window.i18n.msgStore['keyword']+"/>	");
		$("#addAlertTable").append(tr);
		tr = $("
");
		tr.append(""+window.i18n.msgStore['subject']+"	");
		tr.append("<input required type=\"text\" id=\"subject\" name=\"subject\" placeholder="+window.i18n.msgStore['subject']+"/>	");
		$("#addAlertTable").append(tr);
		tr = $("
");
		tr.append(""+window.i18n.msgStore['mail']+"	");
		tr.append("<input required type=\"text\" id=\"mail\" name=\"mail\" placeholder="+window.i18n.msgStore['mail']+"/>	");
		$("#addAlertTable").append(tr);
		tr = $("
");
		tr.append(""+window.i18n.msgStore['core']+"	");
		tr.append("<input required type=\"text\" id=\"core\" name=\"core\" placeholder=\"Core\" value=\"FileShare\"/>	");
		$("#addAlertTable").append(tr);
		tr = $("
");
		tr.append(""+window.i18n.msgStore['frequency']+"	");
		tr.append("<select required id=\"frequency\" name=\"frequency\" class=\"col-sm-4\">	<OPTION value='hourly'>"+window.i18n.msgStore['hourly']+"</OPTION><OPTION value='daily'>"+window.i18n.msgStore['daily']+"</OPTION><OPTION value='weekly'>"+window.i18n.msgStore['weekly']+"</OPTION></select>	");
		$("#addAlertTable").append(tr);
		tr = $("
");
		tr.append("<input type=\"Submit\" id=\"newAlerts\" name=\"AddAlert\" value=\""+window.i18n.msgStore['confirm']+"\"/><button id='addAlertCancel'>"+window.i18n.msgStore['cancel']+"</button>	");
		$("#addAlertTable").append(tr);
		$("#addAlertDiv").append("</form>");
		$("#addAlertDiv").append("

");

		$("#addAlertCancel").click(function() {initCreateAlertButton();});

		$("#add").submit(function(e){
	        e.preventDefault();
	 	});

		$("#add").submit(function(e){
			 var datastring = $("#add").serialize();
		 		$.ajax({ 				//Ajax request to the doPost of the Alerts servlet
		       		type: "POST",
		        	url: "./admin/Alerts",
		       	 	data: datastring,
		        	//if received a response from the server
		        	success: function(data, textStatus, jqXHR) {
		        		if(data.toString().indexOf("Error code : ")!==-1){
		        			$("#addAlertMessage").addClass("fail");
		    				$("#addAlertMessage").html(data);
		            	}else{
		            		$("#addAlertMessage").addClass("success");
		            		$("#addAlertMessage").html(window.i18n.msgStore['success']);
		            		$("#addAlertMessage").fadeOut(1500,function(){
		            			destroyAlertsTable();
		            			createAlertContent();});
		            	}
		        	},
		        	error: function(jqXHR, textStatus, errorThrown){
		        		 if(jqXHR.responseText==="error connecting to the database"){
		               		$("#addAlertsForm").append(window.i18n.msgStore['dbError'])
		               	}else {
		                     console.log("Something really bad happened " + textStatus);
		                     $("#addAlertsForm").html(jqXHR.responseText);
		               	}
		        	},
		        	//capture the request before it was sent to server
		        	beforeSend: function(jqXHR, settings){
		            	//disable the button until we get the response
		            	$('#newAlerts').attr("disabled", true);
		        	},
		        	//called after the response or error functions are finsihed
		        	complete: function(jqXHR, textStatus){
		            	//enable the button
		            	$('#add').attr("disabled", false);
		        	}
		 		});
		 });
	}

	function initCreateAlertButton() {
		$("#addAlertDiv").html("<button onclick='javascript:addAlert();' id='addAlertButton'>"+window.i18n.msgStore['addAlert']+"</button>");
	}

	function modify(i) {
		$("#frequency-"+i).html("<select required id=\"select-frequency-" + i + "\" name=\"frequency\" class=\"col-sm-4\">	<OPTION value='hourly'>"+window.i18n.msgStore['hourly']+"</OPTION><OPTION value='daily'>"+window.i18n.msgStore['daily']+"</OPTION><OPTION value='weekly'>"+window.i18n.msgStore['weekly']+"</OPTION></select> <button onclick='javascript: validate("+i+")' >"+window.i18n.msgStore['validate']+"</button>")
		$("#select-frequency-" + i).val(d.alerts[i].frequency);
	}

	function validate(i) {
		var id = "_id="+d.alerts[i]._id;
		var datastring = "";
		for (var key in d.alerts[i]) {
		    if (datastring != "") {
		    	datastring += "&";
		    }
		    var value = "";
		    if(key==="frequency") {
		    	value = $("#select-frequency-" + i).val();
		    } else {
		    	value = d.alerts[i][key];
		    }
		    datastring += key + "=" + value;
		}
		$.ajax({			 	//Ajax request to the doPost of the Alerts servlet
	        type: "POST",
	        url: "./admin/Alerts",
	        data: datastring,
	        //if received a response from the server
	        success: function(data, textStatus, jqXHR) {
	        	if(data.toString().indexOf("Error code : ")!==-1){
	        		console.log(data);
	        	}else{
	        		d.alerts[i].frequency = $("#select-frequency-" + i).val();
	        		d.alerts[i]._id = JSON.parse(data).uuid;
	        		alertsTable.cell("#frequency-"+i).data(window.i18n.msgStore[d.alerts[i].frequency]+" <button onclick='javascript: modify("+i+")'>"+window.i18n.msgStore['modify']+"</button>").draw();
	        	}
	        },
	        error: function(jqXHR, textStatus, errorThrown){
	             console.log("Something really bad happened " + textStatus);
	        }
		});
	}

	function remove(i){
		// get the id of the alert to remove and serialize it
		var id = "_id="+d.alerts[i]._id;
		$.ajax({		//Ajax request to the doPost of the Alerts servlet
	        type: "POST",
	        url: "./admin/Alerts",
	        data: id,
	        //if received a response from the server
	        success: function(data, textStatus, jqXHR) {
	        	if(data.toString().indexOf("Error code : ")!==-1){
	        		console.log(data);
	        	}else{
	        		//Suppress the row of the tab that was show the now removed alert
//	        		var row = document.getElementById(i);
//	            	row.parentNode.removeChild(row);
	            	alertsTable
	                .row( "#alert-" + i)
	                .remove()
	                .draw();

	            	var nbData = alertsTable.column(0).data().length
					if(nbData < 1 ) {
						$("#alertsListDiv").html("
"+window.i18n.msgStore['noAlerts']+"
");
						destroyAlertsTable();
					}
	        	}
	        },
	        //If there was no resonse from the server
	        error: function(jqXHR, textStatus, errorThrown){
	             console.log("Something really bad happened " + textStatus);
	        }
		});
	}

	function destroyDatatables() {
		destroyAlertsTable();
	}

	function destroyAlertsTable() {
		if(alertsTable !== undefined) {
			alertsTable.clear();
			alertsTable.destroy(true);
			alertsTable = undefined;
		}
	}
<|endoftext|>


<commit_before>'use strict';

var Q = require('q');
var expand = require('glob-expand');

var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var $28 = new (require('28').$28)('http://portal.28.io/api');
var VFS = require('28').VFS;
var _ = require('lodash');

var Config = require('./config');

var credentials;

var Options = {
    OVERWRITE_ALWAYS: 0,
    OVERWRITE_NEVER: 1,
    OVERWRITE_ASK: 2,
    OVERWRITE_IF_NEWER: 3
};

var castToJson = function(obj){
    var result = obj;
    if(_.isString(obj)){
        try {
            result = JSON.parse(obj);
        } catch (e) {

        }
    }
    return result;
};

var throwError = function (error) {
    var message = JSON.stringify(error);
    if(error.stack || error.filename){
        message = error.toString();
        $.util.log(error.stack);
        $.util.log(error.filename);
    } else if(_.isString(error.message)){
        message = error.message;
    }
    if(error.body){
        var body = castToJson(error.body);
        message = _.isObject(body) ? JSON.stringify(body, null, '\t') : body;
        if((_.isObject(body) && body.context) || (_.isArray(body) && body[0].context)){
            $.util.log(message);
            message = 'Compilation error';
        }
    }

    // truncate error message if too long
    if(message.length > 500){
        message = message.substring(0, 500) + ' ... (truncated)';
    }
    throw new $.util.PluginError(__filename, message);
};

var summarizeTestError = function(error){
    var hasError = false;
    if(error.body) {
        var body = castToJson(error.body);
        if (_.isObject(body) && _.isArray(body.items) && body.items.length > 0) {
            body = castToJson(body.items[0]);
        }
        if (_.isObject(body) && body.content) {
            body = castToJson(body.content);
        }
        /*jshint camelcase:false */
        if (_.isObject(body) && !body.request_id) {
            _.each(body, function(testResult, testName){
                if (_.isObject(testResult) && testResult.url) {
                    hasError = true;
                    $.util.log(testName.red + ': ' + testResult.url);
                    if (_.isObject(testResult.expectedFactTable) && testResult.expectedFactTable.error === true) {
                        // http error (e.g. 404)
                        $.util.log(testName.red + ': ' + JSON.stringify(testResult.expectedFactTable, null, '\t'));
                    }
                    _.each(testResult.factTableDiff, function(diff){
                        if (diff.expectedNumberOfFacts) {
                            $.util.log(testName.red + ': ' + JSON.stringify(diff, null, '\t'));
                        }
                    });
                }
            });
        }
        if (hasError) {
            return new Error('some test queries failed');
        }
    }
    return error;
};

var login = function(email, password){
    $.util.log('Logging in as ' + email);
    return $28.login(email, password).then(function(response){
        $.util.log('Logged in.');
        credentials = response.body;
        return credentials;
    });
};

var removeProject = function(projectName, isIdempotent){
    /*jshint camelcase:false */
    var defered = Q.defer();
    if(!Config.isOnProduction) {
        var token = credentials.access_token;
        $.util.log('Deleting project ' + projectName);
        $28.deleteProject(projectName, token).then(function () {
            $.util.log('Project deleted.');
            defered.resolve(credentials);
        }).catch(function (error) {
            if (!isIdempotent) {
                defered.reject(error);
            } else {
                defered.resolve(credentials);
            }
        });
    } else {
        $.util.log('Skipping project deletion for production: ' + projectName);
        defered.resolve(credentials);
    }
    return defered.promise;
};

var createProject = function(projectName){
    /*jshint camelcase:false */
    var defered = Q.defer();
    if(!Config.isOnProduction) {
        var token = credentials.access_token;
        $.util.log('Creating project ' + projectName);
        $28.createProject(projectName, token).then(function (response) {
            $.util.log('Project  ' + projectName + ' created.');
            /*jshint camelcase:false */
            credentials.project_tokens['project_' + projectName] = response.body.projectToken;
            defered.resolve(credentials);
        }).catch(function (error) {
            $.util.log('Project creation failed: ' + error);
            defered.reject(error);
        });
    } else {
        $.util.log('Skipping project creation on production: ' + projectName);
        defered.resolve(credentials);
    }
    return defered.promise;
};

var ignoreQueriesFunction = function(list){
    return list;
};

var upload = function(projectName){
    /*jshint camelcase:false */
    var projectToken = credentials.project_tokens['project_' + projectName];
    if(!projectToken) {
        throw new Error('project not found ' + projectName);
    }
    var projectPath = Config.paths.queries;
    var overwrite = Options.OVERWRITE_ALWAYS;
    var deleteOrphaned = true;
    var simulate = false;
    $.util.log('Uploading queries.');
    return $28.upload(projectName, projectToken, projectPath, overwrite, deleteOrphaned, simulate, ignoreQueriesFunction).then(function(){
        $.util.log('Queries uploaded.');
        return credentials;
    });
};

var runQueriesInParallel = function(projectName, queriesToRun) {
    var promises = [];
    var QueriesAPI = $28.api.Queries(projectName);
    /*jshint camelcase:false */
    var projectToken = credentials.project_tokens['project_' + projectName];
    _.each(queriesToRun, function(nextQuery){
        promises.push(
            QueriesAPI.executeQuery({
                accept: 'application/28.io+json',
                queryPath: nextQuery,
                format: '',
                token: projectToken
            }).then(function (data) {
                $.util.log($.util.colors.green('✓ ') + nextQuery + ' returned with status code: ' + data.response.statusCode);
                return credentials;
            }).catch(function (error) {
                var requestUri = error.response.request.uri;
                var isTestQuery = (requestUri.pathname.lastIndexOf('/v1/_queries/public/test', 0) === 0);
                var href = isTestQuery ? requestUri.host + requestUri.pathname.substring('/v1/_queries/public'.length) : requestUri.host + requestUri.pathname;
                $.util.log($.util.colors.red('✗ ') + href + ' returned with status code: ' + $.util.colors.red(error.response.statusCode));
                error = isTestQuery ? summarizeTestError(error) : error;
                throw error;
            })
        );
    });
    return Q.all(promises);
};

var runQueries = function(projectName, sequenceOfQueriesToRun) {
    return _.chain(sequenceOfQueriesToRun)
        .map(function(queriesToRun) {
            // create chunks of queries to be executed in parallel
            if (_.isString(queriesToRun)) {
                return expand(queriesToRun);
            } else if (_.isArray(queriesToRun)){
                return _.chain(queriesToRun)
                    .map(function(queriesGlob){
                        return expand(queriesGlob);
                    })
                    .flatten()
                    .value();
            }
        })
        .map(function(queriesToRunArray){
            // substring to relative query path
            return _.map(queriesToRunArray, function(query) {
                return query.substring(Config.paths.queries.length + 1);
            });
        })
        .reduce(function(previousPromise, nextQueriesArray){
            // execute them in chunks
            return previousPromise.then(function() {
                return runQueriesInParallel(projectName, nextQueriesArray);
            });
        }, Q.resolve())
        .value();
};

var createDatasource = function(projectName, datasource){
    var defered = Q.defer();
    if(!Config.isOnProduction) {
        $.util.log('Creating datasource ' + datasource.name);
        var difault = datasource.default ? datasource.default : false;
        /*jshint camelcase:false */
        var projectToken = credentials.project_tokens['project_' + projectName];
        $28.createDatasource(projectName, datasource.category, datasource.name, projectToken, difault, JSON.stringify(datasource.credentials))
            .then(function(){
                $.util.log(datasource.name + ' created');
                defered.resolve(credentials);
            })
            .catch(function (error) {
                $.util.log('datasource creation failed: ' + datasource.name);
                defered.reject(error);
            });
    } else {
        $.util.log('Skipping data source creation on production: ' + datasource.name);
        defered.resolve(credentials);
    }
    return defered.promise;
};

gulp.task('28:login', [ 'load-config' ], function(){
    return login(Config.credentials['28'].email, Config.credentials['28'].password).catch(throwError);
});

gulp.task('28:create-project', [ 'load-config' ], function(){
    return createProject(Config.projectName, true).catch(throwError);
});

gulp.task('28:remove-project', [ 'load-config' ], function(){
    return removeProject(Config.projectName, true).catch(throwError);
});

gulp.task('28:upload', [ 'load-config' ], function(){
    return upload(Config.projectName).catch(throwError);
});

gulp.task('28:setup-datasource', [ 'load-config' ], function(){
    var promises = [];
    Config.credentials['28'].datasources.forEach(function(datasource){
        promises.push(createDatasource(Config.projectName, datasource).catch(throwError));
    });
    return Q.all(promises);
});

gulp.task('28:init', [ 'load-config' ], function(){
    return runQueries(Config.projectName, Config.paths.initQueries).catch(throwError);
});

gulp.task('28:test', [ 'load-config' ], function(){
    return runQueries(Config.projectName, Config.paths.apiTestQueries).catch(throwError);
});

module.exports = {
    watchJSONiqQueries: function(){
        //Initialize the VFS
        /*jshint camelcase:false */
        var projectName = Config.projectName;
        var projectToken = credentials.project_tokens['project_' + projectName];
        var upath = require('upath');
        var projectPath = upath.resolve(Config.paths.queries);
        var vfs = new VFS($28.api, projectName, projectToken, projectPath);

        //Do the Watch
        gulp.watch(Config.paths.jsoniq, {}, function(event){
            //Get relative query path
            var query = event.path.substring(projectPath.length + 1);
            query = upath.normalize(query);
            $.util.log(query + ' has ' + event.type);

            //Upload
            if(event.type === 'added' || event.type === 'changed') {
                $.util.log($.util.colors.grey('Uploading ' + query));
                vfs.writeRemoteQuery(query, true).then(function(result){
                    //Show compilation errors
                    if(result && result.message) {
                        $.util.log($.util.colors.red(result.message));
                    }
                    $.util.log($.util.colors.green(query + ' uploaded'));
                }).catch(function(error){
                    throwError(error);
                });

            //Delete
            } else if(event.type === 'deleted') {
                $.util.log($.util.colors.grey('Removing ' + query));
                vfs.deleteRemoteQuery(query).then(function(){
                    $.util.log($.util.colors.green(query + ' removed'));
                }).catch(function(error){
                    throwError(error);
                });
            }
        });
    }
};
<commit_msg>:new: Add gulp trace<commit_after>'use strict';

var Q = require('q');
var expand = require('glob-expand');

var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var $28 = new (require('28').$28)('http://portal.28.io/api');
var VFS = require('28').VFS;
var _ = require('lodash');
var minimist = require('minimist');

var Config = require('./config');

var credentials;

var Options = {
    OVERWRITE_ALWAYS: 0,
    OVERWRITE_NEVER: 1,
    OVERWRITE_ASK: 2,
    OVERWRITE_IF_NEWER: 3
};

var castToJson = function(obj){
    var result = obj;
    if(_.isString(obj)){
        try {
            result = JSON.parse(obj);
        } catch (e) {

        }
    }
    return result;
};

var throwError = function (error) {
    var message = JSON.stringify(error);
    if(error.stack || error.filename){
        message = error.toString();
        $.util.log(error.stack);
        $.util.log(error.filename);
    } else if(_.isString(error.message)){
        message = error.message;
    }
    if(error.body){
        var body = castToJson(error.body);
        message = _.isObject(body) ? JSON.stringify(body, null, '\t') : body;
        if((_.isObject(body) && body.context) || (_.isArray(body) && body[0].context)){
            $.util.log(message);
            message = 'Compilation error';
        }
    }

    // truncate error message if too long
    if(message.length > 500){
        message = message.substring(0, 500) + ' ... (truncated)';
    }
    throw new $.util.PluginError(__filename, message);
};

var summarizeTestError = function(error){
    var hasError = false;
    if(error.body) {
        var body = castToJson(error.body);
        if (_.isObject(body) && _.isArray(body.items) && body.items.length > 0) {
            body = castToJson(body.items[0]);
        }
        if (_.isObject(body) && body.content) {
            body = castToJson(body.content);
        }
        /*jshint camelcase:false */
        if (_.isObject(body) && !body.request_id) {
            _.each(body, function(testResult, testName){
                if (_.isObject(testResult) && testResult.url) {
                    hasError = true;
                    $.util.log(testName.red + ': ' + testResult.url);
                    if (_.isObject(testResult.expectedFactTable) && testResult.expectedFactTable.error === true) {
                        // http error (e.g. 404)
                        $.util.log(testName.red + ': ' + JSON.stringify(testResult.expectedFactTable, null, '\t'));
                    }
                    _.each(testResult.factTableDiff, function(diff){
                        if (diff.expectedNumberOfFacts) {
                            $.util.log(testName.red + ': ' + JSON.stringify(diff, null, '\t'));
                        }
                    });
                }
            });
        }
        if (hasError) {
            return new Error('some test queries failed');
        }
    }
    return error;
};

var login = function(email, password){
    $.util.log('Logging in as ' + email);
    return $28.login(email, password).then(function(response){
        $.util.log('Logged in.');
        credentials = response.body;
        return credentials;
    });
};

var removeProject = function(projectName, isIdempotent){
    /*jshint camelcase:false */
    var defered = Q.defer();
    if(!Config.isOnProduction) {
        var token = credentials.access_token;
        $.util.log('Deleting project ' + projectName);
        $28.deleteProject(projectName, token).then(function () {
            $.util.log('Project deleted.');
            defered.resolve(credentials);
        }).catch(function (error) {
            if (!isIdempotent) {
                defered.reject(error);
            } else {
                defered.resolve(credentials);
            }
        });
    } else {
        $.util.log('Skipping project deletion for production: ' + projectName);
        defered.resolve(credentials);
    }
    return defered.promise;
};

var createProject = function(projectName){
    /*jshint camelcase:false */
    var defered = Q.defer();
    if(!Config.isOnProduction) {
        var token = credentials.access_token;
        $.util.log('Creating project ' + projectName);
        $28.createProject(projectName, token).then(function (response) {
            $.util.log('Project  ' + projectName + ' created.');
            /*jshint camelcase:false */
            credentials.project_tokens['project_' + projectName] = response.body.projectToken;
            defered.resolve(credentials);
        }).catch(function (error) {
            $.util.log('Project creation failed: ' + error);
            defered.reject(error);
        });
    } else {
        $.util.log('Skipping project creation on production: ' + projectName);
        defered.resolve(credentials);
    }
    return defered.promise;
};

var ignoreQueriesFunction = function(list){
    return list;
};

var upload = function(projectName){
    /*jshint camelcase:false */
    var projectToken = credentials.project_tokens['project_' + projectName];
    if(!projectToken) {
        throw new Error('project not found ' + projectName);
    }
    var projectPath = Config.paths.queries;
    var overwrite = Options.OVERWRITE_ALWAYS;
    var deleteOrphaned = true;
    var simulate = false;
    $.util.log('Uploading queries.');
    return $28.upload(projectName, projectToken, projectPath, overwrite, deleteOrphaned, simulate, ignoreQueriesFunction).then(function(){
        $.util.log('Queries uploaded.');
        return credentials;
    });
};

var runQueriesInParallel = function(projectName, queriesToRun) {
    var promises = [];
    var QueriesAPI = $28.api.Queries(projectName);
    /*jshint camelcase:false */
    var projectToken = credentials.project_tokens['project_' + projectName];
    _.each(queriesToRun, function(nextQuery){
        promises.push(
            QueriesAPI.executeQuery({
                accept: 'application/28.io+json',
                queryPath: nextQuery,
                format: '',
                token: projectToken
            }).then(function (data) {
                $.util.log($.util.colors.green('✓ ') + nextQuery + ' returned with status code: ' + data.response.statusCode);
                return credentials;
            }).catch(function (error) {
                var requestUri = error.response.request.uri;
                var isTestQuery = (requestUri.pathname.lastIndexOf('/v1/_queries/public/test', 0) === 0);
                var href = isTestQuery ? requestUri.host + requestUri.pathname.substring('/v1/_queries/public'.length) : requestUri.host + requestUri.pathname;
                $.util.log($.util.colors.red('✗ ') + href + ' returned with status code: ' + $.util.colors.red(error.response.statusCode));
                error = isTestQuery ? summarizeTestError(error) : error;
                throw error;
            })
        );
    });
    return Q.all(promises);
};

var runQueries = function(projectName, sequenceOfQueriesToRun) {
    return _.chain(sequenceOfQueriesToRun)
        .map(function(queriesToRun) {
            // create chunks of queries to be executed in parallel
            if (_.isString(queriesToRun)) {
                return expand(queriesToRun);
            } else if (_.isArray(queriesToRun)){
                return _.chain(queriesToRun)
                    .map(function(queriesGlob){
                        return expand(queriesGlob);
                    })
                    .flatten()
                    .value();
            }
        })
        .map(function(queriesToRunArray){
            // substring to relative query path
            return _.map(queriesToRunArray, function(query) {
                return query.substring(Config.paths.queries.length + 1);
            });
        })
        .reduce(function(previousPromise, nextQueriesArray){
            // execute them in chunks
            return previousPromise.then(function() {
                return runQueriesInParallel(projectName, nextQueriesArray);
            });
        }, Q.resolve())
        .value();
};

var createDatasource = function(projectName, datasource){
    var defered = Q.defer();
    if(!Config.isOnProduction) {
        $.util.log('Creating datasource ' + datasource.name);
        var difault = datasource.default ? datasource.default : false;
        /*jshint camelcase:false */
        var projectToken = credentials.project_tokens['project_' + projectName];
        $28.createDatasource(projectName, datasource.category, datasource.name, projectToken, difault, JSON.stringify(datasource.credentials))
            .then(function(){
                $.util.log(datasource.name + ' created');
                defered.resolve(credentials);
            })
            .catch(function (error) {
                $.util.log('datasource creation failed: ' + datasource.name);
                defered.reject(error);
            });
    } else {
        $.util.log('Skipping data source creation on production: ' + datasource.name);
        defered.resolve(credentials);
    }
    return defered.promise;
};

gulp.task('28:login', [ 'load-config' ], function(){
    return login(Config.credentials['28'].email, Config.credentials['28'].password).catch(throwError);
});

gulp.task('28:create-project', [ 'load-config' ], function(){
    return createProject(Config.projectName, true).catch(throwError);
});

gulp.task('28:remove-project', [ 'load-config' ], function(){
    return removeProject(Config.projectName, true).catch(throwError);
});

gulp.task('28:upload', [ 'load-config' ], function(){
    return upload(Config.projectName).catch(throwError);
});

gulp.task('28:setup-datasource', [ 'load-config' ], function(){
    var promises = [];
    Config.credentials['28'].datasources.forEach(function(datasource){
        promises.push(createDatasource(Config.projectName, datasource).catch(throwError));
    });
    return Q.all(promises);
});

gulp.task('28:init', [ 'load-config' ], function(){
    return runQueries(Config.projectName, Config.paths.initQueries).catch(throwError);
});

gulp.task('28:test', [ 'load-config' ], function(){
    return runQueries(Config.projectName, Config.paths.apiTestQueries).catch(throwError);
});

gulp.task('trace', ['28:login'], function(done){
    var knownOptions = {
        string: [ 'path' ]
    };
    var args = minimist(process.argv.slice(2), knownOptions);
    var path = args.path;
    if(!path) {
        throw new $.util.PluginError(__filename, 'Specify --path option.');
    }
    var projectName = Config.projectName;
    /*jshint camelcase:false */
    var projectToken = credentials.project_tokens['project_' + projectName];
    var url = 'http://' + projectName + '.28.io' + '/v1/_queries';
    var request = require('request');
    path = path.indexOf('?') === -1 ? (path + '?') : path;
    url += path + '&trace&_token=' + encodeURIComponent(projectToken);
    request({
        uri: url,
        method: 'POST'
    }, function(error, response, body){
        if(error) {
            console.error(error);
            return;
        }
        console.log(body.grey);
        var traceFile = response.headers['x-28msec-trace'];
        setTimeout(function(){
            request({
                uri: traceFile,
                method: 'GET'
            }, function(error, response, body){
                if(body) {
                    console.log(body.green);
                } else {
                    console.log('No trace.'.green);
                }
                done();
            });
        }, 1000);
    });
});

module.exports = {
    watchJSONiqQueries: function(){
        //Initialize the VFS
        /*jshint camelcase:false */
        var projectName = Config.projectName;
        var projectToken = credentials.project_tokens['project_' + projectName];
        var upath = require('upath');
        var projectPath = upath.resolve(Config.paths.queries);
        var vfs = new VFS($28.api, projectName, projectToken, projectPath);

        //Do the Watch
        gulp.watch(Config.paths.jsoniq, {}, function(event){
            //Get relative query path
            var query = event.path.substring(projectPath.length + 1);
            query = upath.normalize(query);
            $.util.log(query + ' has ' + event.type);

            //Upload
            if(event.type === 'added' || event.type === 'changed') {
                $.util.log($.util.colors.grey('Uploading ' + query));
                vfs.writeRemoteQuery(query, true).then(function(result){
                    //Show compilation errors
                    if(result && result.message) {
                        $.util.log($.util.colors.red(result.message));
                    }
                    $.util.log($.util.colors.green(query + ' uploaded'));
                }).catch(function(error){
                    throwError(error);
                });

            //Delete
            } else if(event.type === 'deleted') {
                $.util.log($.util.colors.grey('Removing ' + query));
                vfs.deleteRemoteQuery(query).then(function(){
                    $.util.log($.util.colors.green(query + ' removed'));
                }).catch(function(error){
                    throwError(error);
                });
            }
        });
    }
};
<|endoftext|>


<commit_before>"use strict";

var debug = require('debug')('app:routes:gradients' + process.pid),
    _ = require("lodash"),
    util = require('util'),
    path = require('path'),
    async = require('async'),
    Router = require("express").Router,
    tokenUtils = require(path.join(__dirname, '..', '..', 'utils', 'tokenUtils')),
    gradientUtils = require(path.join(__dirname, '..', '..', 'utils', 'gradientUtils')),
    srs = require('secure-random-string'),
    UnauthorizedAccessError = require(path.join(__dirname, '..', '..', 'errors', 'UnauthorizedAccessError'));

module.exports = function (Models) {

  var User = Models.User;
  var UserProfile = Models.UserProfile;
  var Gradient = Models.Gradient;
  var Comment = Models.Comment;
  var Heart = Models.Heart;

  var router = new Router();

  router.route('/').get(function(req, res, next) {
    Gradient.findAll({
      include: [
        {
          model: User, attributes: ['id', 'username', 'email', 'is_admin', 'createdAt', 'updatedAt'],
            include: [{ model: UserProfile }]
        },
        {
          model: Comment,
            include: [{ model: User, attributes: ['id', 'username', 'email', 'is_admin', 'createdAt', 'updatedAt'],
              include: [{ model: UserProfile }]
            }]
        },{
          model: Heart
        }]
      }).then(function(gradients) {

      if (gradients.length == 0) {
        res.status(404).json({ success: false, message: 'No gradients found.' });
      } else {
        res.status(200).json({
          success: true,
          message: (gradients.length > 1) ? gradients.length + ' gradients found.' : '1 gradient found.',
          gradientsFound: gradients
        });
      }

    }).catch(function(err){
      console.log(err);
      return next(err);
    });
  });

  router.route('/:permalink').get(function(req, res, next) {
    Gradient.findOne({
      where: { permalink: req.params.permalink },
      include: [
        {
          model: User, attributes: ['id', 'username', 'email', 'is_admin', 'createdAt', 'updatedAt'],
          include: [{ model: UserProfile }]
        },
        {
          model: Comment,
          include: [{ model: User, attributes: ['id', 'username', 'email', 'is_admin', 'createdAt', 'updatedAt'],
            include: [{ model: UserProfile }]
          }]
        },{
          model: Heart
        }]
      }).then(function(gradient) {

      if (!gradient) {
        return res.status(404).json({ success: false, message: 'No gradients found with a permalink of ' + req.params.permalink + '.' });
      } else {

        gradient.User.dataValues = _.omit(gradient.User.dataValues, ['password', 'email_verified', 'email_verification_uuid', 'password_reset_uuid']);

        res.status(200).json({
          success: true,
          message: '1 gradient found.',
          gradientFound: gradient
        });
      }

    }).catch(function(err) {
      console.log(err);
      return next(err);
    });
  });

  router.route('/:permalink/heart').post(tokenUtils.middleware(), function(req, res, next){
    Gradient.findOne({
      where: { permalink: req.params.permalink },
        include: [
          {
            model: User, attributes: ['id', 'username', 'email', 'is_admin', 'createdAt', 'updatedAt'],
            include: [{ model: UserProfile }]
          },
          {
            model: Comment,
            include: [{ model: User, attributes: ['id', 'username', 'email', 'is_admin', 'createdAt', 'updatedAt'],
              include: [{ model: UserProfile }]
            }]
          },{
            model: Heart
          }]
    }).then(function(gradient){

      if (!gradient) {
        return res.status(404).json({ success: false, message: 'No gradients found with a permalink of ' + req.params.permalink + '.' });
      } else {

        gradient.getHearts({
          where: { UserId: req.user.id, GradientId: gradient.id }
        }).then(function(hearts){

          if (!hearts || hearts.length == 0) {

            User.findOne({ where: { id: req.user.id } }).then(function(user){

              Heart.create().then(function(newHeart){

                gradient.addHeart(newHeart).then(function(newlyAssignedGradient){

                  newHeart.setUser(user).then(function(assignedGradientHeart){

                    newlyAssignedGradient.getHearts().then(function(finalGradientHearts){

                      var finalGradient = newlyAssignedGradient.dataValues;

                      finalGradient.Hearts = finalGradientHearts;

                      res.status(200).json({
                        success: true,
                        message: '1 gradient found.',
                        gradientFound: finalGradient
                      });

                    }).catch(function(err){
                      console.log(err);
                      return next(err);
                    });;

                  }).catch(function(err){
                    console.log(err);
                    return next(err);
                  });;

                }).catch(function(err){
                  console.log(err);
                  return next(err);
                });;

              }).catch(function(err){
                console.log(err);
                return next(err);
              });;

            }).catch(function(err){
              console.log(err);
              return next(err);
            });;

          } else {
            return res.status(304);
          }

        });

      }

    }).catch(function(err){
      console.log(err);
      return next(err);
    });
  });

router.route('/by/:username').get(function(req, res, next) {
  User.findOne({
    where: { username: req.params.username },
    include: [
      {
        model: Gradient,
          include: [{
            model: User,
              include: [{ model: UserProfile }]
          },{
            model: Comment,
              include: [{ model: User, attributes: ['id', 'username', 'email', 'is_admin', 'createdAt', 'updatedAt'],
                include: [{ model: UserProfile }]
          },{
            model: Heart
          }]
        }]
      }]
    }).then(function(user) {

    if (user.length == 0) {
      res.status(404).json({ success: false, message: 'No gradients by ' + req.params.username + ' found.' });
    } else {
      console.log(user);
      res.status(200).json({
        success: true,
        message: (user.Gradients.length > 1) ? user.Gradients.length + ' gradients found by ' + req.params.username + '.' : '1 gradient found by ' + req.params.username + '.',
        gradientsFound: user.Gradients
      });
    }

  }).catch(function(err){
    console.log(err);
    return next(err);
  });
});

  router.route('/:permalink/comment').post(tokenUtils.middleware(), function(req, res, next) {
    Gradient.findOne({ where: { permalink: req.params.permalink },
      include: [{
        model: User, attributes: ['id', 'username', 'email', 'is_admin', 'createdAt', 'updatedAt']
      }, {
        model: Comment,
          include: [{ model: User, attributes: ['id', 'username', 'email', 'is_admin', 'createdAt', 'updatedAt'],
            include: [{ model: UserProfile }]
      }]
    }] }).then(function(gradient) {

      if (!gradient) {
        res.status(404).json({ success: false, message: 'No gradients found with a permalink of ' + req.params.permalink + '.' });
      } else {

        User.findOne({ where: { id: req.user.id } }).then(function(author){

          if (!author){

            return next(new UnauthorizedAccessError("invalid_token", {
              success: false,
              message: 'You must be logged in to comment.'
            }));

          } else {

            Comment.create(req.body).then(function(comment){

              comment.setUser(author).then(function(authoredComment){

                gradient.addComment(authoredComment).then(function(savedGradientWithComment){

                  author.getUserProfile().then(function(completeUser){

                    author.dataValues.UserProfile = completeUser;
                    authoredComment.dataValues.User = author;

                    res.status(200).json({
                      success: true,
                      message: 'Comment created.',
                      commentCreated: authoredComment
                    });

                  }).catch(function(err){
                    console.log(err);
                    return next(err);
                  });

                }).catch(function(err){
                  console.log(err);
                  return next(err);
                });

              }).catch(function(err){
                console.log(err);
                return next(err);
              });

            }).catch(function(err){
              console.log(err);
              return next(err);
            });

          } // end if/else block checking for author

        }).catch(function(err){
          console.log(err);
          return next(err);
        });

      }

    }).catch(function(err) {
      console.log(err);
      return next(err);
    });
  });

  function generateSrs(length, callback) {
    srs({ length: length }, function(err, sr){
      if (err) {
        callback(err);
      } else {
        callback(null, sr);
      }
    });
  }

  function assignGradientPermalink(callback) {
    generateSrs(8, function(err, srs){
      if (err) return next(err);

      //Make sure permalink value does not contain underscores and hyphens.
      if (srs.indexOf('-') != -1 || srs.indexOf('_') != -1) {
        return assignGradientPermalink(callback);
      }

      Gradient.findOne({ where: { permalink: srs } }).then(function(existingGradientWithPermalink){
        if (existingGradientWithPermalink) {
          assignGradientPermalink(callback);
        } else {
          callback(null, srs);
        }
      }).catch(function(err){
        console.log(err);
        callback(err);
      });

    });
  }

  router.route('/').post(tokenUtils.middleware(), function(req, res, next) {

    var gradientObject = req.body;

    assignGradientPermalink(function(err, srs){
      if (err) return next(err);

      gradientObject.permalink = srs;

      gradientUtils.autoprefixCss(gradientObject.body, function(err, autoprefixedCss){
        gradientObject.body_autoprefixed = autoprefixedCss;

        User.findOne({ where: { id: req.user.id } }).then(function(author){

          if (!author){

            return next(new UnauthorizedAccessError("invalid_token", {
              success: false,
              message: 'You must be logged in to save a new gradient.'
            }));

          } else {

            Gradient.create(gradientObject).then(function(gradient){

              gradient.setUser(author).then(function(authoredGradient){

                res.status(200).json({
                  success: true,
                  message: 'Gradient created.',
                  gradientCreated: authoredGradient
                });

              }).catch(function(err){
                console.log(err);
                return next(err);
              });

            }).catch(function(err){
              console.log(err);
              return next(err);
            });

          } // end if/else block checking for author

        }).catch(function(err){
          console.log(err);
          return next(err);
        });

      });

    });

  });

  router.unless = require("express-unless");

  return router;
};

debug("Loaded");<commit_msg>Adding views counter for gradients<commit_after>"use strict";

var debug = require('debug')('app:routes:gradients' + process.pid),
    _ = require("lodash"),
    util = require('util'),
    path = require('path'),
    async = require('async'),
    Router = require("express").Router,
    tokenUtils = require(path.join(__dirname, '..', '..', 'utils', 'tokenUtils')),
    gradientUtils = require(path.join(__dirname, '..', '..', 'utils', 'gradientUtils')),
    srs = require('secure-random-string'),
    UnauthorizedAccessError = require(path.join(__dirname, '..', '..', 'errors', 'UnauthorizedAccessError'));

module.exports = function (Models) {

  var User = Models.User;
  var UserProfile = Models.UserProfile;
  var Gradient = Models.Gradient;
  var Comment = Models.Comment;
  var Heart = Models.Heart;

  var router = new Router();

  router.route('/').get(function(req, res, next) {
    Gradient.findAll({
      include: [
        {
          model: User, attributes: ['id', 'username', 'email', 'is_admin', 'createdAt', 'updatedAt'],
            include: [{ model: UserProfile }]
        },
        {
          model: Comment,
            include: [{ model: User, attributes: ['id', 'username', 'email', 'is_admin', 'createdAt', 'updatedAt'],
              include: [{ model: UserProfile }]
            }]
        },{
          model: Heart
        }]
      }).then(function(gradients) {

      if (gradients.length == 0) {
        res.status(404).json({ success: false, message: 'No gradients found.' });
      } else {
        res.status(200).json({
          success: true,
          message: (gradients.length > 1) ? gradients.length + ' gradients found.' : '1 gradient found.',
          gradientsFound: gradients
        });
      }

    }).catch(function(err){
      console.log(err);
      return next(err);
    });
  });

  router.route('/:permalink').get(function(req, res, next) {
    Gradient.findOne({
      where: { permalink: req.params.permalink },
      include: [
        {
          model: User, attributes: ['id', 'username', 'email', 'is_admin', 'createdAt', 'updatedAt'],
          include: [{ model: UserProfile }]
        },
        {
          model: Comment,
          include: [{ model: User, attributes: ['id', 'username', 'email', 'is_admin', 'createdAt', 'updatedAt'],
            include: [{ model: UserProfile }]
          }]
        },{
          model: Heart
        }]
      }).then(function(gradient){

        gradient.increment({ views: 1 }).then(function(incrementedGradient) {

        if (!incrementedGradient) {
          return res.status(404).json({ success: false, message: 'No gradients found with a permalink of ' + req.params.permalink + '.' });
        } else {

          incrementedGradient.User.dataValues = _.omit(incrementedGradient.User.dataValues, ['password', 'email_verified', 'email_verification_uuid', 'password_reset_uuid']);

          res.status(200).json({
            success: true,
            message: '1 gradient found.',
            gradientFound: incrementedGradient
          });
        }

      }).catch(function(err){
        console.log(err);
        return next(err);
      });

    }).catch(function(err) {
      console.log(err);
      return next(err);
    });
  });

  router.route('/:permalink/heart').post(tokenUtils.middleware(), function(req, res, next){
    Gradient.findOne({
      where: { permalink: req.params.permalink },
        include: [
          {
            model: User, attributes: ['id', 'username', 'email', 'is_admin', 'createdAt', 'updatedAt'],
            include: [{ model: UserProfile }]
          },
          {
            model: Comment,
            include: [{ model: User, attributes: ['id', 'username', 'email', 'is_admin', 'createdAt', 'updatedAt'],
              include: [{ model: UserProfile }]
            }]
          },{
            model: Heart
          }]
    }).then(function(gradient){

      if (!gradient) {
        return res.status(404).json({ success: false, message: 'No gradients found with a permalink of ' + req.params.permalink + '.' });
      } else {

        gradient.getHearts({
          where: { UserId: req.user.id, GradientId: gradient.id }
        }).then(function(hearts){

          if (!hearts || hearts.length == 0) {

            User.findOne({ where: { id: req.user.id } }).then(function(user){

              Heart.create().then(function(newHeart){

                gradient.addHeart(newHeart).then(function(newlyAssignedGradient){

                  newHeart.setUser(user).then(function(assignedGradientHeart){

                    newlyAssignedGradient.getHearts().then(function(finalGradientHearts){

                      var finalGradient = newlyAssignedGradient.dataValues;

                      finalGradient.Hearts = finalGradientHearts;

                      res.status(200).json({
                        success: true,
                        message: '1 gradient found.',
                        gradientFound: finalGradient
                      });

                    }).catch(function(err){
                      console.log(err);
                      return next(err);
                    });;

                  }).catch(function(err){
                    console.log(err);
                    return next(err);
                  });;

                }).catch(function(err){
                  console.log(err);
                  return next(err);
                });;

              }).catch(function(err){
                console.log(err);
                return next(err);
              });;

            }).catch(function(err){
              console.log(err);
              return next(err);
            });;

          } else {
            return res.status(304);
          }

        });

      }

    }).catch(function(err){
      console.log(err);
      return next(err);
    });
  });

router.route('/by/:username').get(function(req, res, next) {
  User.findOne({
    where: { username: req.params.username },
    include: [
      {
        model: Gradient,
          include: [{
            model: User,
              include: [{ model: UserProfile }]
          },{
            model: Comment,
              include: [{ model: User, attributes: ['id', 'username', 'email', 'is_admin', 'createdAt', 'updatedAt'],
                include: [{ model: UserProfile }]
          },{
            model: Heart
          }]
        }]
      }]
    }).then(function(user) {

    if (user.length == 0) {
      res.status(404).json({ success: false, message: 'No gradients by ' + req.params.username + ' found.' });
    } else {
      console.log(user);
      res.status(200).json({
        success: true,
        message: (user.Gradients.length > 1) ? user.Gradients.length + ' gradients found by ' + req.params.username + '.' : '1 gradient found by ' + req.params.username + '.',
        gradientsFound: user.Gradients
      });
    }

  }).catch(function(err){
    console.log(err);
    return next(err);
  });
});

  router.route('/:permalink/comment').post(tokenUtils.middleware(), function(req, res, next) {
    Gradient.findOne({ where: { permalink: req.params.permalink },
      include: [{
        model: User, attributes: ['id', 'username', 'email', 'is_admin', 'createdAt', 'updatedAt']
      }, {
        model: Comment,
          include: [{ model: User, attributes: ['id', 'username', 'email', 'is_admin', 'createdAt', 'updatedAt'],
            include: [{ model: UserProfile }]
      }]
    }] }).then(function(gradient) {

      if (!gradient) {
        res.status(404).json({ success: false, message: 'No gradients found with a permalink of ' + req.params.permalink + '.' });
      } else {

        User.findOne({ where: { id: req.user.id } }).then(function(author){

          if (!author){

            return next(new UnauthorizedAccessError("invalid_token", {
              success: false,
              message: 'You must be logged in to comment.'
            }));

          } else {

            Comment.create(req.body).then(function(comment){

              comment.setUser(author).then(function(authoredComment){

                gradient.addComment(authoredComment).then(function(savedGradientWithComment){

                  author.getUserProfile().then(function(completeUser){

                    author.dataValues.UserProfile = completeUser;
                    authoredComment.dataValues.User = author;

                    res.status(200).json({
                      success: true,
                      message: 'Comment created.',
                      commentCreated: authoredComment
                    });

                  }).catch(function(err){
                    console.log(err);
                    return next(err);
                  });

                }).catch(function(err){
                  console.log(err);
                  return next(err);
                });

              }).catch(function(err){
                console.log(err);
                return next(err);
              });

            }).catch(function(err){
              console.log(err);
              return next(err);
            });

          } // end if/else block checking for author

        }).catch(function(err){
          console.log(err);
          return next(err);
        });

      }

    }).catch(function(err) {
      console.log(err);
      return next(err);
    });
  });

  function generateSrs(length, callback) {
    srs({ length: length }, function(err, sr){
      if (err) {
        callback(err);
      } else {
        callback(null, sr);
      }
    });
  }

  function assignGradientPermalink(callback) {
    generateSrs(8, function(err, srs){
      if (err) return next(err);

      //Make sure permalink value does not contain underscores and hyphens.
      if (srs.indexOf('-') != -1 || srs.indexOf('_') != -1) {
        return assignGradientPermalink(callback);
      }

      Gradient.findOne({ where: { permalink: srs } }).then(function(existingGradientWithPermalink){
        if (existingGradientWithPermalink) {
          assignGradientPermalink(callback);
        } else {
          callback(null, srs);
        }
      }).catch(function(err){
        console.log(err);
        callback(err);
      });

    });
  }

  router.route('/').post(tokenUtils.middleware(), function(req, res, next) {

    var gradientObject = req.body;

    assignGradientPermalink(function(err, srs){
      if (err) return next(err);

      gradientObject.permalink = srs;

      gradientUtils.autoprefixCss(gradientObject.body, function(err, autoprefixedCss){
        gradientObject.body_autoprefixed = autoprefixedCss;

        User.findOne({ where: { id: req.user.id } }).then(function(author){

          if (!author){

            return next(new UnauthorizedAccessError("invalid_token", {
              success: false,
              message: 'You must be logged in to save a new gradient.'
            }));

          } else {

            Gradient.create(gradientObject).then(function(gradient){

              gradient.setUser(author).then(function(authoredGradient){

                res.status(200).json({
                  success: true,
                  message: 'Gradient created.',
                  gradientCreated: authoredGradient
                });

              }).catch(function(err){
                console.log(err);
                return next(err);
              });

            }).catch(function(err){
              console.log(err);
              return next(err);
            });

          } // end if/else block checking for author

        }).catch(function(err){
          console.log(err);
          return next(err);
        });

      });

    });

  });

  router.unless = require("express-unless");

  return router;
};

debug("Loaded");<|endoftext|>