<commit_before>import React from 'react'

class Phrase extends React.Component{

  constructor(){
    super();
    this._activePhrase = this._activePhrase.bind(this);
    this._context = this._context.bind(this);
    this._markPhrases = this._markPhrases.bind(this);
    this._markedIndication = this._markedIndication.bind(this);
  }

  _markPhrases(){
    // shortcut for props
    const {details, wrongPhrases} = this.props;

    // create object that gets pushed to state
    const PhraseMarked = {
        pk:details.pk,
        text:details.text
    }
    // check and set
    this.props._selectPhrase(PhraseMarked, details.pk, this.button);
  }

  _context(){
    let keys = Number(this.props.keys);
    let context = this.props.active === keys || this.props.active === keys - 1 || this.props.active === keys + 1;
    if(context) {
      return(
        'context'
      )
    } else {
      return(
        ''
      )
    }
  }

  _markedIndication(){
    console.log(this.props.wrongPhrases);
  }

  _activePhrase(time, start, end){
    const playingPhrase = time <= start || time >= end;
    if(playingPhrase) {
      return(
        'not-active-phrase'
      )
    } else {
      return(
        'active-phrase'
      )
    }
  }

  render(){
    const {details, time, active} = this.props;
    return (

 {this.li = li}} className={this._activePhrase(time, details.start_time, details.end_time)}>
        <button className='play-phrase' onClick={() => this.props._playPhrase(details.start_time)} id={details.start_time}>
          <title>Play Phrase</title>
          <svg className='speaker-icon' viewBox="0 0 200 200">
            <path d="M73.8 19.9c4.7-4.7 8.6-3.1 8.6 3.6v152c0 6.7-3.9 8.3-8.6 3.6l-44.4-44.3H0V64.2h29.4l44.4-44.3zm27.1 121.6c-2.3 0-4.5-.9-6.2-2.6-3.5-3.4-3.5-9 0-12.5 14.9-14.9 14.9-39.1 0-54-3.5-3.4-3.5-9 0-12.5 3.4-3.4 9-3.4 12.5 0 21.8 21.8 21.8 57.2 0 78.9-1.8 1.9-4 2.7-6.3 2.7m31.4 16.6c-2.3 0-4.5-.9-6.2-2.6-3.4-3.4-3.4-9 0-12.5 24.1-24 24.1-63.2 0-87.2-3.4-3.4-3.4-9 0-12.5 3.5-3.4 9-3.4 12.5 0 15 15 23.3 34.9 23.3 56.1 0 21.2-8.3 41.1-23.3 56.1-1.8 1.8-4.1 2.6-6.3 2.6m31.3 16.7c-2.3 0-4.5-.9-6.2-2.6-3.5-3.4-3.5-9 0-12.5 16.1-16.1 25-37.5 25-60.2 0-22.7-8.9-44.1-25-60.2-3.5-3.4-3.5-9 0-12.5 3.4-3.4 9-3.4 12.5 0C189.3 46.2 200 72 200 99.5s-10.7 53.3-30.2 72.7c-1.7 1.7-3.9 2.6-6.2 2.6"/>
          </svg>
        </button>
        <button ref={(button) => {this.button = button}} className='text' onClick={() => this._markPhrases()} id={details.pk}>
          {details.text}
        </button>

    )
  }
}
export default Phrase;<commit_msg>removal of unused _markedIndication function<commit_after>import React from 'react'

class Phrase extends React.Component{

  constructor(){
    super();
    this._activePhrase = this._activePhrase.bind(this);
    this._context = this._context.bind(this);
    this._markPhrases = this._markPhrases.bind(this);
  }

  _markPhrases(){
    // shortcut for props
    const {details, wrongPhrases} = this.props;

    // create object that gets pushed to state
    const PhraseMarked = {
        pk:details.pk,
        text:details.text
    }
    // check and set
    this.props._selectPhrase(PhraseMarked, details.pk, this.button);
  }

  _context(){
    let keys = Number(this.props.keys);
    let context = this.props.active === keys || this.props.active === keys - 1 || this.props.active === keys + 1;
    if(context) {
      return(
        'context'
      )
    } else {
      return(
        ''
      )
    }
  }

  _activePhrase(time, start, end){
    const playingPhrase = time <= start || time >= end;
    if(playingPhrase) {
      return(
        'not-active-phrase'
      )
    } else {
      return(
        'active-phrase'
      )
    }
  }

  render(){
    const {details, time, active} = this.props;
    return (

 {this.li = li}} className={this._activePhrase(time, details.start_time, details.end_time)}>
        <button className='play-phrase' onClick={() => this.props._playPhrase(details.start_time)} id={details.start_time}>
          <title>Play Phrase</title>
          <svg className='speaker-icon' viewBox="0 0 200 200">
            <path d="M73.8 19.9c4.7-4.7 8.6-3.1 8.6 3.6v152c0 6.7-3.9 8.3-8.6 3.6l-44.4-44.3H0V64.2h29.4l44.4-44.3zm27.1 121.6c-2.3 0-4.5-.9-6.2-2.6-3.5-3.4-3.5-9 0-12.5 14.9-14.9 14.9-39.1 0-54-3.5-3.4-3.5-9 0-12.5 3.4-3.4 9-3.4 12.5 0 21.8 21.8 21.8 57.2 0 78.9-1.8 1.9-4 2.7-6.3 2.7m31.4 16.6c-2.3 0-4.5-.9-6.2-2.6-3.4-3.4-3.4-9 0-12.5 24.1-24 24.1-63.2 0-87.2-3.4-3.4-3.4-9 0-12.5 3.5-3.4 9-3.4 12.5 0 15 15 23.3 34.9 23.3 56.1 0 21.2-8.3 41.1-23.3 56.1-1.8 1.8-4.1 2.6-6.3 2.6m31.3 16.7c-2.3 0-4.5-.9-6.2-2.6-3.5-3.4-3.5-9 0-12.5 16.1-16.1 25-37.5 25-60.2 0-22.7-8.9-44.1-25-60.2-3.5-3.4-3.5-9 0-12.5 3.4-3.4 9-3.4 12.5 0C189.3 46.2 200 72 200 99.5s-10.7 53.3-30.2 72.7c-1.7 1.7-3.9 2.6-6.2 2.6"/>
          </svg>
        </button>
        <button ref={(button) => {this.button = button}} className='text' onClick={() => this._markPhrases()} id={details.pk}>
          {details.text}
        </button>

    )
  }
}
export default Phrase;<|endoftext|>


<commit_before>/*----- MISC GLOBALS -----*/
var roverDomain = ''; //Later, if the rover is not hosting the webpage, its address will go here
var roverApiPath = '/api/v1/';

/*----- HELPER FUNCTIONS -----*/
function roverResource(resource) {
	return roverDomain + roverApiPath + (Array.isArray(resource) ? resource.join('/') : resource);
}

/*----- ROVER API FUNCTIONS -----*/
function sendMotorCommand(command, pin, speed) {
	$.post(roverResource('sendcommand'),
		{
			command: command,
			pin: pin,
			speed: Number(speed)
		}, function (response) {
			//writeToConsole(response);
		});
}

function saveDesign() {
	xml = Blockly.Xml.workspaceToDom(workspace);
	xmlString = Blockly.Xml.domToText(xml);
	$.post(roverResource('blockdiagrams'), {bdString: xmlString, designName: designName}, function(response){
	}).error(function(){
			writeToConsole("There was an error saving your design to the rover");
	});
}

function refreshSavedBds() {
	$.get(roverResource('blockdiagrams'), function(json){
		if (!json.result.length){
			$('#savedDesignsArea').text("There are no designs saved on this rover");
		} else {
			$('#savedDesignsArea').empty();
			json.result.forEach(function(entry) {
				$(document.createElement('a')).addClass('button')
					.html(entry)
					.attr('href', '#')
					.css('margin', '10px')
					.appendTo($("#savedDesignsArea"))
					.click(function() {
						return loadDesign(entry);
					});
			});
		}
	}
	);
}

function loadDesign(name) {
	$('#loadModal').foundation('reveal', 'close');
	$.get(roverResource(['blockdiagrams', name]), function(response){
		workspace.clear();

		xmlDom = Blockly.Xml.textToDom(response.getElementsByTagName('bd')[0].childNodes[0].nodeValue);
		Blockly.Xml.domToWorkspace(workspace, xmlDom);
		if (name == 'event_handler_hidden')
			designName = "Unnamed_Design_" + (Math.floor(Math.random()*1000)).toString();
		else
			designName = name;
		$('a#downloadLink').attr("href", "saved-bds/"+designName+".xml");
		$('a#downloadLink').attr("download", designName+".xml");
		$('a#designNameArea').text(designName);

		hideBlockByComment("MAIN EVENT HANDLER LOOP");
		var hiddenBlock;
		var allBlocksHidden = true;
		for (hiddenBlock of blocksToHide) {
			if (!hideBlock(hiddenBlock))
				allBlocksHidden = false;
		}
		if (allBlocksHidden)
			showBlock('always');
	}).error(function(){
			alert("There was an error loading your design from the rover");
	});
	updateCode();
}

function acceptName() {
	designName = $('input[name=designName]').val();

	$.get(roverResource('blockdiagrams'), function(json){
		var duplicate = false;
		for (var i=0; i<json.length; i++){
			if (json[i] == designName)
				duplicate = true;
		}

		if (designName === ''){
			$('#nameErrorArea').text('Please enter a name for your design in the box');
		} else if (duplicate) {
			$('#nameErrorArea').text('This name has already been chosen. Please pick another one.');
		} else {
			saveDesign();
			$('#nameErrorArea').empty();
			$('a#designNameArea').text(designName);
			$('a#downloadLink').attr("href", "saved-bds/"+designName+".xml");
			$('a#downloadLink').attr("download", designName+".xml");
			$('#nameModal').foundation('reveal', 'close');
		}
	});
}
<commit_msg>Simplifies some logic in loading and saving designs<commit_after>/*----- MISC GLOBALS -----*/
var roverDomain = ''; //Later, if the rover is not hosting the webpage, its address will go here
var roverApiPath = '/api/v1/';

/*----- HELPER FUNCTIONS -----*/
function roverResource(resource) {
	return roverDomain + roverApiPath + (Array.isArray(resource) ? resource.join('/') : resource);
}

/*----- ROVER API FUNCTIONS -----*/
function sendMotorCommand(command, pin, speed) {
	$.post(roverResource('sendcommand'),
		{
			command: command,
			pin: pin,
			speed: Number(speed)
		}, function (response) {
			//writeToConsole(response);
		});
}

function saveDesign() {
	xml = Blockly.Xml.workspaceToDom(workspace);
	xmlString = Blockly.Xml.domToText(xml);
	$.post(roverResource('blockdiagrams'), {bdString: xmlString, designName: designName}, function(response){
	}).error(function(){
			writeToConsole("There was an error saving your design to the rover");
	});
}

function refreshSavedBds() {
	$.get(roverResource('blockdiagrams'), function(json){
		if (!json.result.length){
			$('#savedDesignsArea').text("There are no designs saved on this rover");
		} else {
			$('#savedDesignsArea').empty();
			json.result.forEach(function(entry) {
				$(document.createElement('a')).addClass('button')
					.html(entry)
					.attr('href', '#')
					.css('margin', '10px')
					.appendTo($("#savedDesignsArea"))
					.click(function() {
						return loadDesign(entry);
					});
			});
		}
	}
	);
}

function loadDesign(name) {
	$('#loadModal').foundation('reveal', 'close');
	$.get(roverResource(['blockdiagrams', name]), function(response){
		workspace.clear();

		xmlDom = Blockly.Xml.textToDom(response.getElementsByTagName('bd')[0].childNodes[0].nodeValue);
		Blockly.Xml.domToWorkspace(workspace, xmlDom);
		if (name == 'event_handler_hidden')
			designName = "Unnamed_Design_" + (Math.floor(Math.random()*1000)).toString();
		else
			designName = name;
		$('a#downloadLink').attr("href", "saved-bds/"+designName+".xml");
		$('a#downloadLink').attr("download", designName+".xml");
		$('a#designNameArea').text(designName);

		hideBlockByComment("MAIN EVENT HANDLER LOOP");
		var hiddenBlock;
		var allBlocksHidden = true;
		for (hiddenBlock of blocksToHide) {
			if (!hideBlock(hiddenBlock))
				allBlocksHidden = false;
		}
		if (allBlocksHidden) {
			showBlock('always');
		}
	}).error(function(){
			alert("There was an error loading your design from the rover");
	});
	updateCode();
}

function acceptName() {
	designName = $('input[name=designName]').val();

	if (!designName) {
		$('#nameErrorArea').text('Please enter a name for your design in the box');
	} else {
		$.get(roverResource('blockdiagrams'), function(json){
			var duplicate = json.result.indexOf(designName) > -1;
			if (duplicate) {
				$('#nameErrorArea').text('This name has already been chosen. Please pick another one.');
			} else {
				saveDesign();
				$('#nameErrorArea').empty();
				$('a#designNameArea').text(designName);
				$('a#downloadLink').attr("href", "saved-bds/"+designName+".xml");
				$('a#downloadLink').attr("download", designName+".xml");
				$('#nameModal').foundation('reveal', 'close');
			}
		});
	}

}
<|endoftext|>


<commit_before>Package.describe({
  name: "nova:settings",
  summary: "Telescope settings package – only necessary if you're storing settings in a collection",
  version: "0.27.3-nova",
  git: "https://github.com/TelescopeJS/Telescope.git"
});

Package.onUse(function(api) {

  api.versionsFrom(['METEOR@1.0']);

  api.use([
    'nova:lib@0.27.3-nova',
    'nova:users@0.27.3-nova'
  ]);

  api.addFiles([
    'lib/collection.js',
    'lib/init.js',
    'lib/methods.js',
  ], ['server', 'client']);

  api.addFiles([
    'lib/server/publications.js',
  ], 'server');

});
<commit_msg>get rid of this disallowed insert error client-side<commit_after>Package.describe({
  name: "nova:settings",
  summary: "Telescope settings package – only necessary if you're storing settings in a collection",
  version: "0.27.3-nova",
  git: "https://github.com/TelescopeJS/Telescope.git"
});

Package.onUse(function(api) {

  api.versionsFrom(['METEOR@1.0']);

  api.use([
    'nova:lib@0.27.3-nova',
    'nova:users@0.27.3-nova'
  ]);

  api.addFiles([
    'lib/collection.js',
    'lib/methods.js',
  ], ['server', 'client']);

  api.addFiles([
    'lib/init.js',
    'lib/server/publications.js',
  ], 'server');

});
<|endoftext|>


<commit_before>/*
   Provide the XMLHttpRequest constructor for IE 5.x-6.x:
   Other browsers (including IE 7.x-8.x) do not redefine
   XMLHttpRequest if it already exists.

   This example is based on findings at:
   http://blogs.msdn.com/xmlteam/archive/2006/10/23/using-the-right-version-of-msxml-in-internet-explorer.aspx
*/
if (typeof XMLHttpRequest == "undefined")
  XMLHttpRequest = function () {
    try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); }
      catch (e) {}
    try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
      catch (e) {}
    try { return new ActiveXObject("Msxml2.XMLHTTP"); }
      catch (e) {}
    //Microsoft.XMLHTTP points to Msxml2.XMLHTTP.3.0 and is redundant
    throw new Error("This browser does not support XMLHttpRequest.");
  };

var IDE_clone = function(object) {
  var newObj = (object instanceof Array) ? [] : {};
  for (var i in object) {
    if (i == 'clone') continue;
    if (object[i] && typeof object[i] == "object") {
      newObj[i] = object[i].clone();
    } else newObj[i] = object[i]
  } return newObj;
};

var IDE_auth_token = null
IDE_base = "control.php"

var IDE_async_count = 0;
showElement = hideElement = function(){};

function IDE_authed() {
	return IDE_auth_token != null;
}

function IDE_backend_request(command, arguments, successCallback, errorCallback) {
	var args = IDE_clone(arguments);
	if (IDE_auth_token != null) {
		args["auth-token"] = IDE_auth_token
	}
	var rq = JSON.stringify(args);
	var xhr = new XMLHttpRequest();
	var cb = function() {
		if (xhr.readyState != 4) return;
		IDE_async_count--;
		if( IDE_async_count == 0 ) {
			hideElement('rotating-box');
		}
		if (xhr.status == 200) {
			if (xhr.getResponseHeader("Content-type") == "text/html") {
				// PHP fatal error
				errorCallback(-1, "fatal PHP error", args);
				return;
			}
			var rt = xhr.responseText;
			var rp = JSON.parse(rt);
			if (rp["auth-token"]) {
				IDE_auth_token = rp["auth-token"];
			} else {
				IDE_auth_token = null;
			}
			if (rp.error) {
				errorCallback(rp.error[0], rp.error[1], args);
			} else {
				successCallback(rp, args);
			}
		} else {
			errorCallback(-xhr.status, xhr.statusText, args);
		}
	};
	xhr.open("POST", IDE_base + "/" + command, true);
	xhr.onreadystatechange = cb;
	xhr.setRequestHeader("Content-type", "text/json");
	showElement('rotating-box');
	IDE_async_count++;
	xhr.send(rq);
}

function IDE_path_get_project(path) {
	var split = path.split(/\//);
	return split[1];
}

function IDE_path_get_file(path) {
	var split = path.split(/\//);
	split = split.slice(2);
	return split.join('/');
}

// Test if the user is logged in or not by doing a simple call.
// If they're logged in then we'll get an auth token back.
IDE_backend_request('user/info', {}, function(){ if(user != null) user.load(); }, function(){});
<commit_msg>Make object cloning properly recursive.<commit_after>/*
   Provide the XMLHttpRequest constructor for IE 5.x-6.x:
   Other browsers (including IE 7.x-8.x) do not redefine
   XMLHttpRequest if it already exists.

   This example is based on findings at:
   http://blogs.msdn.com/xmlteam/archive/2006/10/23/using-the-right-version-of-msxml-in-internet-explorer.aspx
*/
if (typeof XMLHttpRequest == "undefined")
  XMLHttpRequest = function () {
    try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); }
      catch (e) {}
    try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
      catch (e) {}
    try { return new ActiveXObject("Msxml2.XMLHTTP"); }
      catch (e) {}
    //Microsoft.XMLHTTP points to Msxml2.XMLHTTP.3.0 and is redundant
    throw new Error("This browser does not support XMLHttpRequest.");
  };

var IDE_clone = function(object) {
  var newObj = (object instanceof Array) ? [] : {};
  for (var i in object) {
    if (i == 'clone') continue;
    if (object[i] && typeof object[i] == "object") {
      newObj[i] = IDE_clone(object[i]);
    } else newObj[i] = object[i]
  } return newObj;
};

var IDE_auth_token = null
IDE_base = "control.php"

var IDE_async_count = 0;
showElement = hideElement = function(){};

function IDE_authed() {
	return IDE_auth_token != null;
}

function IDE_backend_request(command, arguments, successCallback, errorCallback) {
	var args = IDE_clone(arguments);
	if (IDE_auth_token != null) {
		args["auth-token"] = IDE_auth_token
	}
	var rq = JSON.stringify(args);
	var xhr = new XMLHttpRequest();
	var cb = function() {
		if (xhr.readyState != 4) return;
		IDE_async_count--;
		if( IDE_async_count == 0 ) {
			hideElement('rotating-box');
		}
		if (xhr.status == 200) {
			if (xhr.getResponseHeader("Content-type") == "text/html") {
				// PHP fatal error
				errorCallback(-1, "fatal PHP error", args);
				return;
			}
			var rt = xhr.responseText;
			var rp = JSON.parse(rt);
			if (rp["auth-token"]) {
				IDE_auth_token = rp["auth-token"];
			} else {
				IDE_auth_token = null;
			}
			if (rp.error) {
				errorCallback(rp.error[0], rp.error[1], args);
			} else {
				successCallback(rp, args);
			}
		} else {
			errorCallback(-xhr.status, xhr.statusText, args);
		}
	};
	xhr.open("POST", IDE_base + "/" + command, true);
	xhr.onreadystatechange = cb;
	xhr.setRequestHeader("Content-type", "text/json");
	showElement('rotating-box');
	IDE_async_count++;
	xhr.send(rq);
}

function IDE_path_get_project(path) {
	var split = path.split(/\//);
	return split[1];
}

function IDE_path_get_file(path) {
	var split = path.split(/\//);
	split = split.slice(2);
	return split.join('/');
}

// Test if the user is logged in or not by doing a simple call.
// If they're logged in then we'll get an auth token back.
IDE_backend_request('user/info', {}, function(){ if(user != null) user.load(); }, function(){});
<|endoftext|>


<commit_before>import querystring from 'querystring';
import OH from 'opening_hours';

import config, { PREFERENCES_KEY } from './config';

const api = {};

api.findLoos = async function(lng, lat, { limit, radius } = config.nearest) {
  // Todo: Fix the api to avoid this hard limit
  const qs = querystring.stringify({ limit: 1000, radius });
  const url = `${config.apiEndpoint}/loos/near/${lng}/${lat}?${qs}`;
  const res = await fetch(url, {
    headers: {
      Accept: 'application/json',
    },
  });
  const geojson = await res.json();
  return geojson.features;
};

api.findLooById = async function(id) {
  const url = `${config.apiEndpoint}/loos/${id}`;
  const res = await fetch(url, {
    headers: {
      Accept: 'application/json',
    },
  });
  return await res.json();
};

api.reportLoo = async function(loo, token) {
  // Todo: Handle HTTP 401
  const url = `${config.apiEndpoint}/reports`;
  const res = await fetch(url, {
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
      Authorization: `Bearer ${token}`,
    },
    method: 'post',
    body: JSON.stringify(loo),
  });
  if (res.status !== 201) {
    throw new Error(res.statusText);
  }
  return await res.json();
};

api.removeLoo = async function(looId, reason, token) {
  // Todo: Handle HTTP 401
  const url = `${config.apiEndpoint}/reports/${looId}`;
  const res = await fetch(url, {
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
      Authorization: `Bearer ${token}`,
    },
    method: 'delete',
    body: JSON.stringify({
      removal_reason: reason,
    }),
  });
  if (res.status !== 200) {
    throw new Error(res.statusText);
  }
  return res.status;
};

api.getSettings = function(namespace) {
  return JSON.parse(localStorage.getItem(namespace) || '{}');
};

api.getSetting = function(namespace, key) {
  return this.getSettings(namespace)[key];
};

api.setSetting = function(namespace, key, val) {
  var settings = this.getSettings(namespace);

  settings[key] = val;

  localStorage.setItem(namespace, JSON.stringify(settings));
};

// Compares the user's preferences with properties on the loo to
// determine which preferences, if any, are met.
api.checkPreferences = function(loo) {
  var preferences = this.getSettings(PREFERENCES_KEY);
  var result = {};

  if (!Object.keys(preferences).length) {
    return result;
  }

  // Map preference names to loo properties
  var map = {
    free: 'fee',
    accessible: 'accessibleType',
    open: 'opening',
    male: 'type',
    female: 'type',
    babychanging: 'babyChange',
  };

  Object.keys(preferences).forEach(name => {
    var value = loo.properties[map[name]];

    if (['', undefined, null].indexOf(value) !== -1) {
      return;
    }

    switch (name) {
      case 'free':
        result[name] =
          value === false ||
          value === 'false' ||
          value === 0 ||
          value === '0.00' ||
          value.toLowerCase() === 'free' ||
          value.toLowerCase() === 'none';
        break;

      case 'accessible':
        result[name] =
          value === false ||
          value === 'false' ||
          value.toLowerCase() !== 'none';
        break;

      case 'open':
        if (value !== '') {
          result[name] = new OH(value).getState();
        }
        break;

      case 'male':
        result[name] = /\bmale\b|unisex/.test(value);
        break;

      case 'female':
        result[name] = /\bfemale\b|unisex/.test(value);
        break;

      case 'babychanging':
        result[name] = value === true || value === 'true' || value !== 'false';
        break;

      default:
        break;
    }
  });

  return result;
};

api.humanize = function(val) {
  // Unknown
  if (val === undefined || val === null) {
    return 'Not known';
  }

  // Capitalise
  if (typeof val === 'string') {
    val = val
      .replace(/([A-Z])/g, ' $1')
      .replace(/^./, str => str.toUpperCase())
      .trim();
  }

  // Readable boolean
  if (
    typeof val === 'boolean' ||
    (typeof val === 'string' &&
      ['true', 'false'].indexOf(val.toLowerCase()) !== -1)
  ) {
    val = JSON.parse((val + '').toLowerCase()) ? 'Yes' : 'No';
  }

  // Pricing
  if (val === '0.00') {
    val = 'Free';
  }

  return val;
};

export default api;
<commit_msg>fix: only submit viable properties<commit_after>import querystring from 'querystring';
import _ from 'lodash';
import OH from 'opening_hours';

import config, { PREFERENCES_KEY } from './config';

const api = {};

api.findLoos = async function(lng, lat, { limit, radius } = config.nearest) {
  // Todo: Fix the api to avoid this hard limit
  const qs = querystring.stringify({ limit: 1000, radius });
  const url = `${config.apiEndpoint}/loos/near/${lng}/${lat}?${qs}`;
  const res = await fetch(url, {
    headers: {
      Accept: 'application/json',
    },
  });
  const geojson = await res.json();
  return geojson.features;
};

api.findLooById = async function(id) {
  const url = `${config.apiEndpoint}/loos/${id}`;
  const res = await fetch(url, {
    headers: {
      Accept: 'application/json',
    },
  });
  return await res.json();
};

const submissibleProperties = [
  'access',
  'accesibleType',
  'active',
  'attended',
  'babyChange',
  'fee',
  'name',
  'notes',
  'opening',
  'radar',
  'type',
];
/**
 * Remove non-user editable fields from a loo report before submission
 * also remove empty values
 * @param {Object} loo
 */
function minimizeLooReport(loo) {
  let properties = _.pickBy(loo.properties, (v, k) => {
    return submissibleProperties.includes(k) && !['', undefined].includes(v);
  });
  const report = {
    type: loo.type,
    geometry: loo.geometry,
    properties: properties,
  };
  return report;
}

api.reportLoo = async function(loo, token) {
  const report = minimizeLooReport(loo);
  // Todo: Handle HTTP 401
  const url = `${config.apiEndpoint}/reports`;
  const res = await fetch(url, {
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
      Authorization: `Bearer ${token}`,
    },
    method: 'post',
    body: JSON.stringify(report),
  });
  if (res.status !== 201) {
    throw new Error(res.statusText);
  }
  return await res.json();
};

api.removeLoo = async function(looId, reason, token) {
  // Todo: Handle HTTP 401
  const url = `${config.apiEndpoint}/reports/${looId}`;
  const res = await fetch(url, {
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
      Authorization: `Bearer ${token}`,
    },
    method: 'delete',
    body: JSON.stringify({
      removal_reason: reason,
    }),
  });
  if (res.status !== 200) {
    throw new Error(res.statusText);
  }
  return res.status;
};

api.getSettings = function(namespace) {
  return JSON.parse(localStorage.getItem(namespace) || '{}');
};

api.getSetting = function(namespace, key) {
  return this.getSettings(namespace)[key];
};

api.setSetting = function(namespace, key, val) {
  var settings = this.getSettings(namespace);

  settings[key] = val;

  localStorage.setItem(namespace, JSON.stringify(settings));
};

// Compares the user's preferences with properties on the loo to
// determine which preferences, if any, are met.
api.checkPreferences = function(loo) {
  var preferences = this.getSettings(PREFERENCES_KEY);
  var result = {};

  if (!Object.keys(preferences).length) {
    return result;
  }

  // Map preference names to loo properties
  var map = {
    free: 'fee',
    accessible: 'accessibleType',
    open: 'opening',
    male: 'type',
    female: 'type',
    babychanging: 'babyChange',
  };

  Object.keys(preferences).forEach(name => {
    var value = loo.properties[map[name]];

    if (['', undefined, null].indexOf(value) !== -1) {
      return;
    }

    switch (name) {
      case 'free':
        result[name] =
          value === false ||
          value === 'false' ||
          value === 0 ||
          value === '0.00' ||
          value.toLowerCase() === 'free' ||
          value.toLowerCase() === 'none';
        break;

      case 'accessible':
        result[name] =
          value === false ||
          value === 'false' ||
          value.toLowerCase() !== 'none';
        break;

      case 'open':
        if (value !== '') {
          result[name] = new OH(value).getState();
        }
        break;

      case 'male':
        result[name] = /\bmale\b|unisex/.test(value);
        break;

      case 'female':
        result[name] = /\bfemale\b|unisex/.test(value);
        break;

      case 'babychanging':
        result[name] = value === true || value === 'true' || value !== 'false';
        break;

      default:
        break;
    }
  });

  return result;
};

api.humanize = function(val) {
  // Unknown
  if (val === undefined || val === null) {
    return 'Not known';
  }

  // Capitalise
  if (typeof val === 'string') {
    val = val
      .replace(/([A-Z])/g, ' $1')
      .replace(/^./, str => str.toUpperCase())
      .trim();
  }

  // Readable boolean
  if (
    typeof val === 'boolean' ||
    (typeof val === 'string' &&
      ['true', 'false'].indexOf(val.toLowerCase()) !== -1)
  ) {
    val = JSON.parse((val + '').toLowerCase()) ? 'Yes' : 'No';
  }

  // Pricing
  if (val === '0.00') {
    val = 'Free';
  }

  return val;
};

export default api;
<|endoftext|>


<commit_before><commit_msg>Update routes.js<commit_after><|endoftext|>


<commit_before>/*
 * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

var deviceModule;
deviceModule = function () {
    //var log = new Log("modules/device.js");

    var utility = require('/modules/utility.js').utility;
    var constants = require('/modules/constants.js');

    var ArrayList = Packages.java.util.ArrayList;
    var Properties = Packages.java.util.Properties;
    var DeviceIdentifier = Packages.org.wso2.carbon.device.mgt.common.DeviceIdentifier;
    var DeviceManagerUtil = Packages.org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
    var SimpleOperation = Packages.org.wso2.carbon.device.mgt.core.operation.mgt.SimpleOperation;
    var ConfigOperation = Packages.org.wso2.carbon.device.mgt.core.operation.mgt.ConfigOperation;
    var CommandOperation = Packages.org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation;

    var deviceManagementService = utility.getDeviceManagementService();

    var publicMethods = {};
    var privateMethods = {};

    privateMethods.validateAndReturn = function (value) {
        return (value == undefined || value == null) ? constants.UNSPECIFIED : value;
    };

    publicMethods.listDevices = function () {
        var carbonUser = session.get(constants.USER_SESSION_KEY);
        var utility = require('/modules/utility.js').utility;
        if (!carbonUser) {
            log.error("User object was not found in the session");
            throw constants.ERRORS.USER_NOT_FOUND;
        }
        try{
            utility.startTenantFlow(carbonUser);
            var deviceManagementService = utility.getDeviceManagementService();
            var devices = deviceManagementService.getAllDevices();
            var deviceList = [];
            var i, device, propertiesList, deviceObject;
            for (i = 0; i < devices.size(); i++) {
                device = devices.get(i);
                propertiesList = DeviceManagerUtil.convertDevicePropertiesToMap(device.getProperties());

                deviceObject = {};
                deviceObject[constants.DEVICE_IDENTIFIER] =
                    privateMethods.validateAndReturn(device.getDeviceIdentifier());
                deviceObject[constants.DEVICE_NAME] =
                    privateMethods.validateAndReturn(device.getName());
                deviceObject[constants.DEVICE_OWNERSHIP] =
                    privateMethods.validateAndReturn(device.getEnrolmentInfo().getOwnership());
                deviceObject[constants.DEVICE_OWNER] =
                    privateMethods.validateAndReturn(device.getEnrolmentInfo().getOwner());
                deviceObject[constants.DEVICE_TYPE] =
                    privateMethods.validateAndReturn(device.getType());
                deviceObject[constants.DEVICE_PROPERTIES] = {};
                if (device.getType() == constants.PLATFORM_IOS) {
                    deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_MODEL] =
                        privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_PRODUCT));
                    deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_VENDOR] = constants.VENDOR_APPLE;
                } else {
                    deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_MODEL] =
                        privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_MODEL));
                    deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_VENDOR] =
                        privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_VENDOR));
                }
                deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_OS_VERSION] =
                    privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_OS_VERSION));

                deviceList.push(deviceObject);
            }
            return deviceList;
        }catch (e) {
            throw e;
        } finally {
            utility.endTenantFlow();
        }
    };

    publicMethods.listDevicesForUser = function (username) {
        var carbonUser = session.get(constants.USER_SESSION_KEY);
        var utility = require('/modules/utility.js').utility;
        if (!carbonUser) {
            log.error("User object was not found in the session");
            throw constants.ERRORS.USER_NOT_FOUND;
        }
        try{
            utility.startTenantFlow(carbonUser);
            var deviceManagementService = utility.getDeviceManagementService();
            var devices = deviceManagementService.getDeviceListOfUser(username);
            var deviceList = [];
            var i, device, propertiesList, deviceObject;
            for (i = 0; i < devices.size(); i++) {
                device = devices.get(i);
                propertiesList = DeviceManagerUtil.convertDevicePropertiesToMap(device.getProperties());

                deviceObject = {};
                deviceObject[constants.DEVICE_IDENTIFIER] =
                    privateMethods.validateAndReturn(device.getDeviceIdentifier());
                deviceObject[constants.DEVICE_NAME] =
                    privateMethods.validateAndReturn(device.getName());
                deviceObject[constants.DEVICE_OWNERSHIP] =
                    privateMethods.validateAndReturn(device.getEnrolmentInfo().getOwnership());
                deviceObject[constants.DEVICE_OWNER] =
                    privateMethods.validateAndReturn(device.getEnrolmentInfo().getOwner());
                deviceObject[constants.DEVICE_TYPE] =
                    privateMethods.validateAndReturn(device.getType());
                deviceObject[constants.DEVICE_PROPERTIES] = {};
                if (device.getType() == constants.PLATFORM_IOS) {
                    deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_MODEL] =
                        privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_PRODUCT));
                    deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_VENDOR] = constants.VENDOR_APPLE;
                } else {
                    deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_MODEL] =
                        privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_MODEL));
                    deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_VENDOR] =
                        privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_VENDOR));
                }
                deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_OS_VERSION] =
                    privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_OS_VERSION));

                deviceList.push(deviceObject);
            }
            return deviceList;
        }catch (e) {
            throw e;
        } finally {
            utility.endTenantFlow();
        }
    };

    /*
     Get the supported features by the device type
     */
    publicMethods.getFeatures = function (deviceType) {
        var carbonUser = session.get(constants.USER_SESSION_KEY);
        var utility = require('/modules/utility.js').utility;
        if (!carbonUser) {
            log.error("User object was not found in the session");
            throw constants.ERRORS.USER_NOT_FOUND;
        }
        try{
            utility.startTenantFlow(carbonUser);
            var deviceManagementService = utility.getDeviceManagementService();
            var features = deviceManagementService.getFeatureManager(deviceType).getFeatures();
            var featuresConverted = {};
            if (features) {
                var i, feature, featureObject;
                for (i = 0; i < features.size(); i++) {
                    feature = features.get(i);
                    featureObject = {};
                    featureObject[constants.FEATURE_NAME] = feature.getName();
                    featureObject[constants.FEATURE_DESCRIPTION] = feature.getDescription();
                    featuresConverted[feature.getName()] = featureObject;
                }
            }
            return featuresConverted;
        }catch (e) {
            throw e;
        } finally {
            utility.endTenantFlow();
        }
    };

    publicMethods.performOperation = function (devices, operation) {
        var carbonUser = session.get(constants.USER_SESSION_KEY);
        var utility = require('/modules/utility.js').utility;
        if (!carbonUser) {
            log.error("User object was not found in the session");
            throw constants.ERRORS.USER_NOT_FOUND;
        }
        try{
            utility.startTenantFlow(carbonUser);
            var deviceManagementService = utility.getDeviceManagementService();
            var operationInstance;
            if (operation.type == "COMMAND") {
                operationInstance = new CommandOperation();
            } else if (operation.type == "CONFIG") {
                operationInstance = new ConfigOperation();
            } else {
                operationInstance = new SimpleOperation();
            }
            operationInstance.setCode(operation.featureName);
            var props = new Properties();
            var i, object;
            for (i = 0; i < operation.properties.length; i++) {
                object = properties[i];
                props.setProperty(object.key, object.value);
            }
            operationInstance.setProperties(props);
            var deviceList = new ArrayList();
            var j, device, deviceIdentifier;
            for (j = 0; j < devices.length; i++) {
                device = devices[j];
                deviceIdentifier = new DeviceIdentifier();
                deviceIdentifier.setId(device.id);
                deviceIdentifier.setType(device.type);
                deviceList.add(deviceIdentifier);
            }
            deviceManagementService.addOperation(operationInstance, deviceList);
        }catch (e) {
            throw e;
        } finally {
            utility.endTenantFlow();
        }
    };

    privateMethods.getDevice = function (type, deviceId) {
        var carbonUser = session.get(constants.USER_SESSION_KEY);
        var utility = require('/modules/utility.js').utility;
        if (!carbonUser) {
            log.error("User object was not found in the session");
            throw constants.ERRORS.USER_NOT_FOUND;
        }
        try{
            utility.startTenantFlow(carbonUser);
            var deviceManagementService = utility.getDeviceManagementService();
            var deviceIdentifier = new DeviceIdentifier();
            deviceIdentifier.setType(type);
            deviceIdentifier.setId(deviceId);
            return deviceManagementService.getDevice(deviceIdentifier);
        }catch (e) {
            throw e;
        } finally {
            utility.endTenantFlow();
        }
    };

    publicMethods.viewDevice = function (type, deviceId) {
        try{
            var device = privateMethods.getDevice(type, deviceId);
            if (device) {
                var propertiesList = DeviceManagerUtil.convertDevicePropertiesToMap(device.getProperties());
                var entries = propertiesList.entrySet();
                var iterator = entries.iterator();
                var properties = {};
                var entry, key, value;

                while (iterator.hasNext()) {
                    entry = iterator.next();
                    key = entry.getKey();
                    value = entry.getValue();
                    properties[key] = privateMethods.validateAndReturn(value);
                }

                var deviceObject = {};
                deviceObject[constants.DEVICE_IDENTIFIER] = device.getDeviceIdentifier();
                deviceObject[constants.DEVICE_NAME] = privateMethods.validateAndReturn(device.getName());
                deviceObject[constants.DEVICE_OWNERSHIP] = privateMethods.validateAndReturn(device.getEnrolmentInfo().getOwnership());
                deviceObject[constants.DEVICE_OWNER] = device.getEnrolmentInfo().getOwner();
                deviceObject[constants.DEVICE_TYPE] = device.getType();
                if (device.getType() == constants.PLATFORM_IOS) {
                    properties[constants.DEVICE_MODEL] = properties[constants.DEVICE_PRODUCT];
                    delete properties[constants.DEVICE_PRODUCT];
                    properties[constants.DEVICE_VENDOR] = constants.VENDOR_APPLE;
                }
                deviceObject[constants.DEVICE_PROPERTIES] = properties;

                return deviceObject;
            }
        } catch (e) {
            throw e;
        }
    };

    publicMethods.getLicense = function () {
        var carbonUser = session.get(constants.USER_SESSION_KEY);
        var utility = require('/modules/utility.js').utility;
        if (!carbonUser) {
            log.error("User object was not found in the session");
            throw constants.ERRORS.USER_NOT_FOUND;
        }
        try{
            utility.startTenantFlow(carbonUser);
            var deviceManagementService = utility.getDeviceManagementService();
            return deviceManagementService.getLicense(constants.PLATFORM_IOS, constants.LANGUAGE_US);
        }catch (e) {
            throw e;
        } finally {
            utility.endTenantFlow();
        }
    };

    return publicMethods;
}();
<commit_msg>Fixing getLicense<commit_after>/*
 * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

var deviceModule;
deviceModule = function () {
    //var log = new Log("modules/device.js");

    var utility = require('/modules/utility.js').utility;
    var constants = require('/modules/constants.js');

    var ArrayList = Packages.java.util.ArrayList;
    var Properties = Packages.java.util.Properties;
    var DeviceIdentifier = Packages.org.wso2.carbon.device.mgt.common.DeviceIdentifier;
    var DeviceManagerUtil = Packages.org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
    var SimpleOperation = Packages.org.wso2.carbon.device.mgt.core.operation.mgt.SimpleOperation;
    var ConfigOperation = Packages.org.wso2.carbon.device.mgt.core.operation.mgt.ConfigOperation;
    var CommandOperation = Packages.org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation;

    var deviceManagementService = utility.getDeviceManagementService();

    var publicMethods = {};
    var privateMethods = {};

    privateMethods.validateAndReturn = function (value) {
        return (value == undefined || value == null) ? constants.UNSPECIFIED : value;
    };

    publicMethods.listDevices = function () {
        var carbonUser = session.get(constants.USER_SESSION_KEY);
        var utility = require('/modules/utility.js').utility;
        if (!carbonUser) {
            log.error("User object was not found in the session");
            throw constants.ERRORS.USER_NOT_FOUND;
        }
        try{
            utility.startTenantFlow(carbonUser);
            var deviceManagementService = utility.getDeviceManagementService();
            var devices = deviceManagementService.getAllDevices();
            var deviceList = [];
            var i, device, propertiesList, deviceObject;
            for (i = 0; i < devices.size(); i++) {
                device = devices.get(i);
                propertiesList = DeviceManagerUtil.convertDevicePropertiesToMap(device.getProperties());

                deviceObject = {};
                deviceObject[constants.DEVICE_IDENTIFIER] =
                    privateMethods.validateAndReturn(device.getDeviceIdentifier());
                deviceObject[constants.DEVICE_NAME] =
                    privateMethods.validateAndReturn(device.getName());
                deviceObject[constants.DEVICE_OWNERSHIP] =
                    privateMethods.validateAndReturn(device.getEnrolmentInfo().getOwnership());
                deviceObject[constants.DEVICE_OWNER] =
                    privateMethods.validateAndReturn(device.getEnrolmentInfo().getOwner());
                deviceObject[constants.DEVICE_TYPE] =
                    privateMethods.validateAndReturn(device.getType());
                deviceObject[constants.DEVICE_PROPERTIES] = {};
                if (device.getType() == constants.PLATFORM_IOS) {
                    deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_MODEL] =
                        privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_PRODUCT));
                    deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_VENDOR] = constants.VENDOR_APPLE;
                } else {
                    deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_MODEL] =
                        privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_MODEL));
                    deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_VENDOR] =
                        privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_VENDOR));
                }
                deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_OS_VERSION] =
                    privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_OS_VERSION));

                deviceList.push(deviceObject);
            }
            return deviceList;
        }catch (e) {
            throw e;
        } finally {
            utility.endTenantFlow();
        }
    };

    publicMethods.listDevicesForUser = function (username) {
        var carbonUser = session.get(constants.USER_SESSION_KEY);
        var utility = require('/modules/utility.js').utility;
        if (!carbonUser) {
            log.error("User object was not found in the session");
            throw constants.ERRORS.USER_NOT_FOUND;
        }
        try{
            utility.startTenantFlow(carbonUser);
            var deviceManagementService = utility.getDeviceManagementService();
            var devices = deviceManagementService.getDeviceListOfUser(username);
            var deviceList = [];
            var i, device, propertiesList, deviceObject;
            for (i = 0; i < devices.size(); i++) {
                device = devices.get(i);
                propertiesList = DeviceManagerUtil.convertDevicePropertiesToMap(device.getProperties());

                deviceObject = {};
                deviceObject[constants.DEVICE_IDENTIFIER] =
                    privateMethods.validateAndReturn(device.getDeviceIdentifier());
                deviceObject[constants.DEVICE_NAME] =
                    privateMethods.validateAndReturn(device.getName());
                deviceObject[constants.DEVICE_OWNERSHIP] =
                    privateMethods.validateAndReturn(device.getEnrolmentInfo().getOwnership());
                deviceObject[constants.DEVICE_OWNER] =
                    privateMethods.validateAndReturn(device.getEnrolmentInfo().getOwner());
                deviceObject[constants.DEVICE_TYPE] =
                    privateMethods.validateAndReturn(device.getType());
                deviceObject[constants.DEVICE_PROPERTIES] = {};
                if (device.getType() == constants.PLATFORM_IOS) {
                    deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_MODEL] =
                        privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_PRODUCT));
                    deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_VENDOR] = constants.VENDOR_APPLE;
                } else {
                    deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_MODEL] =
                        privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_MODEL));
                    deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_VENDOR] =
                        privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_VENDOR));
                }
                deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_OS_VERSION] =
                    privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_OS_VERSION));

                deviceList.push(deviceObject);
            }
            return deviceList;
        }catch (e) {
            throw e;
        } finally {
            utility.endTenantFlow();
        }
    };

    /*
     Get the supported features by the device type
     */
    publicMethods.getFeatures = function (deviceType) {
        var carbonUser = session.get(constants.USER_SESSION_KEY);
        var utility = require('/modules/utility.js').utility;
        if (!carbonUser) {
            log.error("User object was not found in the session");
            throw constants.ERRORS.USER_NOT_FOUND;
        }
        try{
            utility.startTenantFlow(carbonUser);
            var deviceManagementService = utility.getDeviceManagementService();
            var features = deviceManagementService.getFeatureManager(deviceType).getFeatures();
            var featuresConverted = {};
            if (features) {
                var i, feature, featureObject;
                for (i = 0; i < features.size(); i++) {
                    feature = features.get(i);
                    featureObject = {};
                    featureObject[constants.FEATURE_NAME] = feature.getName();
                    featureObject[constants.FEATURE_DESCRIPTION] = feature.getDescription();
                    featuresConverted[feature.getName()] = featureObject;
                }
            }
            return featuresConverted;
        }catch (e) {
            throw e;
        } finally {
            utility.endTenantFlow();
        }
    };

    publicMethods.performOperation = function (devices, operation) {
        var carbonUser = session.get(constants.USER_SESSION_KEY);
        var utility = require('/modules/utility.js').utility;
        if (!carbonUser) {
            log.error("User object was not found in the session");
            throw constants.ERRORS.USER_NOT_FOUND;
        }
        try{
            utility.startTenantFlow(carbonUser);
            var deviceManagementService = utility.getDeviceManagementService();
            var operationInstance;
            if (operation.type == "COMMAND") {
                operationInstance = new CommandOperation();
            } else if (operation.type == "CONFIG") {
                operationInstance = new ConfigOperation();
            } else {
                operationInstance = new SimpleOperation();
            }
            operationInstance.setCode(operation.featureName);
            var props = new Properties();
            var i, object;
            for (i = 0; i < operation.properties.length; i++) {
                object = properties[i];
                props.setProperty(object.key, object.value);
            }
            operationInstance.setProperties(props);
            var deviceList = new ArrayList();
            var j, device, deviceIdentifier;
            for (j = 0; j < devices.length; i++) {
                device = devices[j];
                deviceIdentifier = new DeviceIdentifier();
                deviceIdentifier.setId(device.id);
                deviceIdentifier.setType(device.type);
                deviceList.add(deviceIdentifier);
            }
            deviceManagementService.addOperation(operationInstance, deviceList);
        }catch (e) {
            throw e;
        } finally {
            utility.endTenantFlow();
        }
    };

    privateMethods.getDevice = function (type, deviceId) {
        var carbonUser = session.get(constants.USER_SESSION_KEY);
        var utility = require('/modules/utility.js').utility;
        if (!carbonUser) {
            log.error("User object was not found in the session");
            throw constants.ERRORS.USER_NOT_FOUND;
        }
        try{
            utility.startTenantFlow(carbonUser);
            var deviceManagementService = utility.getDeviceManagementService();
            var deviceIdentifier = new DeviceIdentifier();
            deviceIdentifier.setType(type);
            deviceIdentifier.setId(deviceId);
            return deviceManagementService.getDevice(deviceIdentifier);
        }catch (e) {
            throw e;
        } finally {
            utility.endTenantFlow();
        }
    };

    publicMethods.viewDevice = function (type, deviceId) {
        try{
            var device = privateMethods.getDevice(type, deviceId);
            if (device) {
                var propertiesList = DeviceManagerUtil.convertDevicePropertiesToMap(device.getProperties());
                var entries = propertiesList.entrySet();
                var iterator = entries.iterator();
                var properties = {};
                var entry, key, value;

                while (iterator.hasNext()) {
                    entry = iterator.next();
                    key = entry.getKey();
                    value = entry.getValue();
                    properties[key] = privateMethods.validateAndReturn(value);
                }

                var deviceObject = {};
                deviceObject[constants.DEVICE_IDENTIFIER] = device.getDeviceIdentifier();
                deviceObject[constants.DEVICE_NAME] = privateMethods.validateAndReturn(device.getName());
                deviceObject[constants.DEVICE_OWNERSHIP] = privateMethods.validateAndReturn(device.getEnrolmentInfo().getOwnership());
                deviceObject[constants.DEVICE_OWNER] = device.getEnrolmentInfo().getOwner();
                deviceObject[constants.DEVICE_TYPE] = device.getType();
                if (device.getType() == constants.PLATFORM_IOS) {
                    properties[constants.DEVICE_MODEL] = properties[constants.DEVICE_PRODUCT];
                    delete properties[constants.DEVICE_PRODUCT];
                    properties[constants.DEVICE_VENDOR] = constants.VENDOR_APPLE;
                }
                deviceObject[constants.DEVICE_PROPERTIES] = properties;

                return deviceObject;
            }
        } catch (e) {
            throw e;
        }
    };

    publicMethods.getLicense = function () {

        var deviceManagementService = utility.getDeviceManagementService();
        return deviceManagementService.getLicense(constants.PLATFORM_IOS, constants.LANGUAGE_US);

    };

    return publicMethods;
}();
<|endoftext|>


<commit_before>'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

// Copyright (c) 2017 by Igor Tkachenko <vash.igor@gmail.com>. All Rights Reserved.
// This code is provided under the MIT license.
// You can find the full text in the package you get this file with.

/* eslint-disable import/no-extraneous-dependencies */

/* eslint-enable import/no-extraneous-dependencies */

var _vue = require('vue');

var _vue2 = _interopRequireDefault(_vue);

var _lodash = require('lodash.get');

var _lodash2 = _interopRequireDefault(_lodash);

var _lodash3 = require('lodash.assign');

var _lodash4 = _interopRequireDefault(_lodash3);

var _vueClassComponent = require('vue-class-component');

var _vueClassComponent2 = _interopRequireDefault(_vueClassComponent);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

/**
 * Helper functions.
 */

/**
 * Types that are used in the module.
 */
var metadata = {};
function castMetadata(self, options) {
  /* eslint-disable no-underscore-dangle */
  if (options.metadata) {
    if (!metadata[self._uid]) {
      metadata[self._uid] = _extends({}, options.metadata);
    }

    return { metadata: metadata[self._uid] };
  }
  /* eslint-enable no-underscore-dangle */

  return {};
}

function destroyMetadata(self, options) {
  /* eslint-disable no-underscore-dangle */
  if (options.metadata && metadata[self._uid]) {
    delete metadata[self._uid];
  }
  /* eslint-enable no-underscore-dangle */
}

/**
 * Module export.
 * Wrap function that simplifies HOC creation for VueJs.
 * It can be used to transform a render function in a fullscale component.
 */

exports.default = function () {
  var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  return function (com) {
    // We can transform some function to component instead of wrapping one.

    var mixins = options.options && options.options.mixins ? options.options.mixins : [];
    if (!(com.name || com.options)) {
      return (0, _vueClassComponent2.default)(_extends({}, (0, _lodash2.default)(options, 'options', {}), {
        name: 'great-func-com',
        props: options.props ? options.props : {},
        mixins: [].concat(_toConsumableArray(mixins), [{
          destroyed: function destroyed() {
            destroyMetadata(this, options);
          }
        }])
      }))(function (_Vue) {
        _inherits(_class, _Vue);

        function _class() {
          _classCallCheck(this, _class);

          return _possibleConstructorReturn(this, (_class.__proto__ || Object.getPrototypeOf(_class)).apply(this, arguments));
        }

        _createClass(_class, [{
          key: 'render',
          value: function render(h) {
            return com(h, _extends({
              props: this.$props,
              children: this.$children,
              self: this
            }, castMetadata(this, options)));
          }
        }]);

        return _class;
      }(_vue2.default));
    }

    // This is a dangerous dirty hack - we change props option of the decorated component.
    com.options.props = com.options.props || {};
    (0, _lodash4.default)(com.options.props, (0, _lodash2.default)(options, 'props', {}));

    return _vue2.default.extend(_extends({}, (0, _lodash2.default)(options, 'options', {}), {

      name: 'great-hoc',

      props: com.options.props,

      mixins: [].concat(_toConsumableArray(mixins), [{
        created: function created() {
          this.$hocMetadata = castMetadata(this, options).metadata;
        },
        destroyed: function destroyed() {
          destroyMetadata(this, options);
        }
      }]),

      render: function render(h) {
        var metadata = castMetadata(this, options).metadata || {};

        // Generete prop value
        var props = options.injectProps ? options.injectProps(this.$props, this, options, metadata) : this.$props;

        // Prepare component render data
        var prepare = options.prepareData || options.preapreData;
        var others = prepare ? prepare(this, options) : {};

        var payload = {
          com: com,
          props: props,
          children: this.$children,
          self: this,
          others: others,
          metadata: metadata
        };
        if (options.render) {
          return options.render(h, payload);
        }

        return h(com, _extends({ props: props }, others), this.$children);
      }
    }));
  };
};
<commit_msg>Added forgotten build<commit_after>'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

// Copyright (c) 2017 by Igor Tkachenko <vash.igor@gmail.com>. All Rights Reserved.
// This code is provided under the MIT license.
// You can find the full text in the package you get this file with.

/* eslint-disable import/no-extraneous-dependencies */

/* eslint-enable import/no-extraneous-dependencies */

var _vue = require('vue');

var _vue2 = _interopRequireDefault(_vue);

var _lodash = require('lodash.get');

var _lodash2 = _interopRequireDefault(_lodash);

var _lodash3 = require('lodash.assign');

var _lodash4 = _interopRequireDefault(_lodash3);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

/**
 * Helper functions.
 */

/**
 * Types that are used in the module.
 */
var metadata = {};
function castMetadata(self, options) {
  /* eslint-disable no-underscore-dangle */
  if (options.metadata) {
    if (!metadata[self._uid]) {
      metadata[self._uid] = _extends({}, options.metadata);
    }

    return { metadata: metadata[self._uid] };
  }
  /* eslint-enable no-underscore-dangle */

  return {};
}

function destroyMetadata(self, options) {
  /* eslint-disable no-underscore-dangle */
  if (options.metadata && metadata[self._uid]) {
    delete metadata[self._uid];
  }
  /* eslint-enable no-underscore-dangle */
}

/**
 * Module export.
 * Wrap function that simplifies HOC creation for VueJs.
 * It can be used to transform a render function in a fullscale component.
 */

exports.default = function () {
  var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  return function (com) {
    var mixins = options.options && options.options.mixins ? options.options.mixins : [];

    // We can transform some function to component instead of wrapping one.
    if (!(com.name || com.options)) {
      return _vue2.default.extend(_extends({}, (0, _lodash2.default)(options, 'options', {}), {

        name: 'great-func-com',

        props: options.props ? options.props : {},

        mixins: [].concat(_toConsumableArray(mixins), [{
          destroyed: function destroyed() {
            destroyMetadata(this, options);
          }
        }]),

        render: function render(h) {
          return com(h, _extends({
            props: this.$props,
            children: this.$children,
            self: this
          }, castMetadata(this, options)));
        }
      }));
    }

    // This is a dangerous dirty hack - we change props option of the decorated component.
    com.options.props = com.options.props || {};
    (0, _lodash4.default)(com.options.props, (0, _lodash2.default)(options, 'props', {}));

    return _vue2.default.extend(_extends({}, (0, _lodash2.default)(options, 'options', {}), {

      name: 'great-hoc',

      props: com.options.props,

      mixins: [].concat(_toConsumableArray(mixins), [{
        created: function created() {
          this.$hocMetadata = castMetadata(this, options).metadata;
        },
        destroyed: function destroyed() {
          destroyMetadata(this, options);
        }
      }]),

      render: function render(h) {
        var metadata = castMetadata(this, options).metadata || {};

        // Generete prop value
        var props = options.injectProps ? options.injectProps(this.$props, this, options, metadata) : this.$props;

        // Prepare component render data
        var prepare = options.prepareData || options.preapreData;
        var others = prepare ? prepare(this, options) : {};

        var payload = {
          com: com,
          props: props,
          children: this.$children,
          self: this,
          others: others,
          metadata: metadata
        };
        if (options.render) {
          return options.render(h, payload);
        }

        return h(com, _extends({ props: props }, others), this.$children);
      }
    }));
  };
};
<|endoftext|>


<commit_before>// vim: noexpandtab
function Log(file, project) {
	//class properties
	this.tab = null;		//holds reference to tab in tabbar
	this.selectedRevision = -1;	//Selected revision, -1 indicates no revision set
	this.team = team;		//team number TODO: get this from elsewhere
	this.project = project;    //holds the current project name
	this.user = null;		//holds author name
	this.userList = new Array();	//List of  users attributed to file(s)
	this.history = new Array();	//array of log entries returned by server
	this.file = file;		//the file/directory for which we are interested
	this.offset = 0;		//which results page we want to retrieve from the server
	this.overflow = 0;		//stores  total number of results pages (retrieved from server)

	//do this only once: add a new tab to the tabbar and link it to this log page
	this.tab = new Tab("Log: "+this.file.toString());
	connect(this.tab, 'onfocus', bind(this._onfocus, this));
	connect(this.tab, 'onblur', bind(this._onblur, this));
	connect(this.tab, 'onclickclose', bind(this.close, this));
	tabbar.add_tab(this.tab);
	tabbar.switch_to(this.tab);
	//start initialisation
	this._init();

/*
	selectedRevision [int]	holds revision number to revert to
	userList [string[]]	Array of users who have made revisions to the selected  file(s)
	history			the array of dictionaries returned by the server
	file			the file(s) for which the logs are for
	user			holds the name of the user who's revisions have been selected
	overflow		holds the total number of page of results for  the latest query
	offset			holds the page offset for the next query

	_init()			Initialize function - clears variables and re-retrieves data from server
	_receiveHistory(rev)	Callback function for loadJSONDoc success
	_errorReceiveHistory()	Callback function for loadJSONDoc fail
	_retrieveHistory()	Instigates call to server to retrieve logs for given file(s) & users
	_populateList()		Takes history and updates list of logs on page, it also adds event handlers to log-menu buttons
	_update()		Event handler for when a new user is selected
	_revert(bool)		event handler for when user clicks 'revert' - if arg is false, confirmation is  requested from user
	_nextview(int)		event handler for when user clicks on 'older'/'newer' buttons,
				if int > 0 an older page of  results is retrieved, if int <0 a later page of results is retrieved
	_onfocus()		event handler for tab click
	_onblur()		event handler for tab looses focus
	close()			completely close the tab and log page
*/
}

Log.prototype._init = function() {
	logDebug("Initializing Log...");
	//clear data from previous query
	this.history = new Array();
	this.userList = new Array();
	//do new query
	this._retrieveHistory();
}

Log.prototype._receiveHistory = function(opt, revisions) {
	logDebug("Log history received ok");
	//extract data from query response
	update(this.history, revisions.log);
	update(this.userList, revisions.authors);
	this.overflow = 0;
	if(opt == null || opt != 'quiet')
		status_msg("File history loaded successfully", LEVEL_OK);
	//present data
	this._populateList();
}

Log.prototype._errorReceiveHistory = function() {
	//handle failed request
	logDebug("Log history retrieval failed");
	this.history = new Array();
	status_button("Error retrieving history", LEVEL_WARN, "Retry", bind(this._receiveHistory, this));
}

Log.prototype._retrieveHistory = function(opt) {
	IDE_backend_request('file/log',
		{ team : team,
		  project: IDE_path_get_project(this.file),
		  path : IDE_path_get_file(this.file),
		  //this key is to filter by author
		  user : this.user,
		  offset : this.offset,
		  number : 4096
		},
		bind(this._receiveHistory, this, opt),
		bind(this._errorReceiveHistory, this)
	);
}

Log.prototype._histDate = function(which) {
	var stamp = this.history[which].time;
	var d = new Date(stamp*1000);
	return d.toDateString();
}

//processess log data and formats into list. connects up related event handlers,
//deals with multile results pages
Log.prototype._populateList = function() {
	logDebug("Processing log list...");

	//print summary information
	var entries = this.history.length;
	if(entries <= 0) {
		$("log-summary").innerHTML = "There are no revisions available for file(s): "+this.file;
	} else {
		$("log-summary").innerHTML = "Displaying "+entries+" revision(s) between "+this._histDate(this.history.length-1)+" & "+this._histDate(0)+" Page "+(this.offset+1)+" of "+(this.overflow+1);
	}

	//fill drop down box with authors attributed to file(s)
	//clear list:
	replaceChildNodes('repo-users', opt);

	//first item in list is: 'Filter by user'
	var opt = OPTION({"value":-1}, "Filter by user");
	appendChildNodes('repo-users', opt);

	//second item in the list is: 'all' meaning, show logs from all users
	var opt = OPTION({"value":-1}, "Show all");
	appendChildNodes('repo-users', opt);

	//now add all attributed authors
	for(var i=0; i < this.userList.length; i++) {
		var opt = OPTION({"value":i}, this.userList[i]);
		appendChildNodes('repo-users', opt);
	}
    //remove event handler for when user applies filter to results
	disconnectAll('repo-users');

	//clear log list
	replaceChildNodes($("log-list"), null);
	//now populate log list
	for(var x=0; x <this.history.length; x++) {
		var logtxt = SPAN(this.history[x].hash+" | "+this.history[x].author+" | "+this._histDate(x));
		var radio = INPUT({'type' : 'radio', 'name' : 'log', 'class' : 'log-radio', 'value' : this.history[x].hash });
		var label = LABEL( null, radio, logtxt );
		var commitMsg = DIV({'class' : 'commit-msg'}, this.history[x].message);
		appendChildNodes($("log-list"), LI(null, label, commitMsg));
	}
	//make selected user selected in drop down box (visual clue that filter is applied)
	if(this.user != null) {
		$('repo-users').value = findValue(this.userList, this.user);
	}

	//connect event handler for when user applies filter to results
	connect('repo-users', 'onchange', bind(this._update, this));

	//disconnect the older/newer buttons
	disconnectAll($("older"));
	disconnectAll($("newer"));

	//if older results are available, enable the 'older' button and hook it up
	if(this.offset < (this.overflow-1)) {
		$("older").disabled = false;
		connect($("older"), 'onclick', bind(this._nextview, this, +1));
	} else
		$("older").disabled = true;

	//if newer results are available, enable the 'newer' button and hook it up
	if(this.offset > 0) {
		$("newer").disabled = false;
		connect($("newer"), 'onclick', bind(this._nextview, this, -1));
	} else
		$("newer").disabled = true;

	//connect up the 'Revert' button to event handler
	disconnectAll($("revert"));
	connect($("revert"), 'onclick', bind(this._revert, this, false));

	//connect up the 'Diff' button to event handler
	disconnectAll('log-diff');
	connect('log-diff', 'onclick', bind(this._diff, this, false));

	//connect up the close button on log menu
	disconnectAll($("log-close"));
	connect($("log-close"), 'onclick', bind(this.close, this));
}
//get older (updown > 0) or newer (updown < 0) results
Log.prototype._nextview = function(updown) {
	this.offset = this.offset+updown;
	//get new results page
	this._init();
}
//called when user applies author filter
Log.prototype._update = function() {
	//find out which author was selected  using select value as key to userList array
	var index = $('repo-users').value;
	//if user clicks 'All' (-1) clear user variable
	if(index > -1) {
		this.user = this.userList[index];
	} else {
		this.user = null;
	}
	logDebug("Filter logs by user: "+this.user);
	//reset offset
	this.offset = 0;
	this._init();
}

Log.prototype._receiveRevert = function(nodes,args) {
    nodes = args["nodes"]
	if(nodes.commit != "")
		status_msg("Successfully reverted to version "+this.selectedRevision+" (New Revision: "+nodes.commit+")", LEVEL_OK);
	else
		status_msg("Failed to revert: "+nodes.success, LEVEL_ERROR);
	//in either case update the history
	this._retrieveHistory('quiet');
	//refresh open files. yes that's right, I'm abusing the scope chain massively to
	//get the file contents here, but I don't care. Whoever wrote the edit module needs
	//their head examined
	for (var key in editpage._open_files) {
		var fileHandle = editpage._open_files[key];
		fileHandle._load_contents()
		fileHandle._update_contents()
	}
}

Log.prototype._errorReceiveRevision = function(commitMsg) {
	status_button("Unable to contact server to revert file", LEVEL_ERROR, "retry", bind(this._do_revert, this, commitMsg));
}
Log.prototype._do_revert = function(commitMsg) {
    IDE_backend_request("file/co",
                        {
                            team:team,
                            project:IDE_path_get_project(this.file),
                            files:[IDE_path_get_file(this.file)],
                            revision:this.selectedRevision
                        },
                        bind(
                            function(nodes) {
                                IDE_backend_request("proj/commit",
                                                    {
                                                        team:team,
                                                        project:IDE_path_get_project(this.file),
                                                        paths:[IDE_path_get_file(this.file)],
                                                        message:commitMsg,
                                                        nodes:nodes
                                                    },
                                                    bind(this._receiveRevert,this),
                                                    bind(this._errorReceiveRevision,this,commitMsg)
                                                   )
                            }, this
                        ),
                        bind(
                            this._errorReceiveRevision,this,commitMsg
                        )
                       )
}

//revert to selected revision. override = true to skip user confirmation
Log.prototype._revert = function(override) {
	this._find_selected();

	if(this.selectedRevision < 0) {
		//no revision selected
		status_msg("No revision selected !", LEVEL_WARN);
	} else if(override) {
		//user has confirmed revert, proceed
		status_msg("Reverting to revision: "+this.selectedRevision+"...", LEVEL_INFO);
		var b = new Browser(bind(this._do_revert, this), {'type' : 'isCommit'});
	} else {
		//user has not confirmed revert, seek confirmation
		status_button("Are you sure you want to revert selected file(s)?", LEVEL_WARN, "Yes", bind(this._revert, this, true));
	}

}

//find out which radio button is checked
Log.prototype._find_selected = function() {
	var radios = getElementsByTagAndClassName("input", "log-radio");
	for(var x=0; x < radios.length; x++) {
		if(radios[x].checked == true) {
			this.selectedRevision = radios[x].value;
			break;
		}
	}
}

//view the diff applied by a selected revision.
Log.prototype._diff = function() {
	this._find_selected();

	if(this.selectedRevision < 0) {
		//no revision selected
		status_msg("No revision selected !", LEVEL_WARN);
	} else {
		diffpage.diff(this.file, this.selectedRevision);
	}
}

//tab gets focus
Log.prototype._onfocus = function() {
	if(getStyle($("log-mode"), "display") != "block") {
		setStyle($("log-mode"), {"display" : "block"});
	}
	//don't waste time doing query again, just process results in buffer
	this._populateList();
}

//tab loses focus
Log.prototype._onblur = function() {
	setStyle($("log-mode"), {"display" : "none"});
}
//tab is closed
Log.prototype.close = function() {
	this.tab.close();
	logDebug("Closing log tab");
}
<commit_msg>show the new revision instead of undefined on revert<commit_after>// vim: noexpandtab
function Log(file, project) {
	//class properties
	this.tab = null;		//holds reference to tab in tabbar
	this.selectedRevision = -1;	//Selected revision, -1 indicates no revision set
	this.team = team;		//team number TODO: get this from elsewhere
	this.project = project;    //holds the current project name
	this.user = null;		//holds author name
	this.userList = new Array();	//List of  users attributed to file(s)
	this.history = new Array();	//array of log entries returned by server
	this.file = file;		//the file/directory for which we are interested
	this.offset = 0;		//which results page we want to retrieve from the server
	this.overflow = 0;		//stores  total number of results pages (retrieved from server)

	//do this only once: add a new tab to the tabbar and link it to this log page
	this.tab = new Tab("Log: "+this.file.toString());
	connect(this.tab, 'onfocus', bind(this._onfocus, this));
	connect(this.tab, 'onblur', bind(this._onblur, this));
	connect(this.tab, 'onclickclose', bind(this.close, this));
	tabbar.add_tab(this.tab);
	tabbar.switch_to(this.tab);
	//start initialisation
	this._init();

/*
	selectedRevision [int]	holds revision number to revert to
	userList [string[]]	Array of users who have made revisions to the selected  file(s)
	history			the array of dictionaries returned by the server
	file			the file(s) for which the logs are for
	user			holds the name of the user who's revisions have been selected
	overflow		holds the total number of page of results for  the latest query
	offset			holds the page offset for the next query

	_init()			Initialize function - clears variables and re-retrieves data from server
	_receiveHistory(rev)	Callback function for loadJSONDoc success
	_errorReceiveHistory()	Callback function for loadJSONDoc fail
	_retrieveHistory()	Instigates call to server to retrieve logs for given file(s) & users
	_populateList()		Takes history and updates list of logs on page, it also adds event handlers to log-menu buttons
	_update()		Event handler for when a new user is selected
	_revert(bool)		event handler for when user clicks 'revert' - if arg is false, confirmation is  requested from user
	_nextview(int)		event handler for when user clicks on 'older'/'newer' buttons,
				if int > 0 an older page of  results is retrieved, if int <0 a later page of results is retrieved
	_onfocus()		event handler for tab click
	_onblur()		event handler for tab looses focus
	close()			completely close the tab and log page
*/
}

Log.prototype._init = function() {
	logDebug("Initializing Log...");
	//clear data from previous query
	this.history = new Array();
	this.userList = new Array();
	//do new query
	this._retrieveHistory();
}

Log.prototype._receiveHistory = function(opt, revisions) {
	logDebug("Log history received ok");
	//extract data from query response
	update(this.history, revisions.log);
	update(this.userList, revisions.authors);
	this.overflow = 0;
	if(opt == null || opt != 'quiet')
		status_msg("File history loaded successfully", LEVEL_OK);
	//present data
	this._populateList();
}

Log.prototype._errorReceiveHistory = function() {
	//handle failed request
	logDebug("Log history retrieval failed");
	this.history = new Array();
	status_button("Error retrieving history", LEVEL_WARN, "Retry", bind(this._receiveHistory, this));
}

Log.prototype._retrieveHistory = function(opt) {
	IDE_backend_request('file/log',
		{ team : team,
		  project: IDE_path_get_project(this.file),
		  path : IDE_path_get_file(this.file),
		  //this key is to filter by author
		  user : this.user,
		  offset : this.offset,
		  number : 4096
		},
		bind(this._receiveHistory, this, opt),
		bind(this._errorReceiveHistory, this)
	);
}

Log.prototype._histDate = function(which) {
	var stamp = this.history[which].time;
	var d = new Date(stamp*1000);
	return d.toDateString();
}

//processess log data and formats into list. connects up related event handlers,
//deals with multile results pages
Log.prototype._populateList = function() {
	logDebug("Processing log list...");

	//print summary information
	var entries = this.history.length;
	if(entries <= 0) {
		$("log-summary").innerHTML = "There are no revisions available for file(s): "+this.file;
	} else {
		$("log-summary").innerHTML = "Displaying "+entries+" revision(s) between "+this._histDate(this.history.length-1)+" & "+this._histDate(0)+" Page "+(this.offset+1)+" of "+(this.overflow+1);
	}

	//fill drop down box with authors attributed to file(s)
	//clear list:
	replaceChildNodes('repo-users', opt);

	//first item in list is: 'Filter by user'
	var opt = OPTION({"value":-1}, "Filter by user");
	appendChildNodes('repo-users', opt);

	//second item in the list is: 'all' meaning, show logs from all users
	var opt = OPTION({"value":-1}, "Show all");
	appendChildNodes('repo-users', opt);

	//now add all attributed authors
	for(var i=0; i < this.userList.length; i++) {
		var opt = OPTION({"value":i}, this.userList[i]);
		appendChildNodes('repo-users', opt);
	}
    //remove event handler for when user applies filter to results
	disconnectAll('repo-users');

	//clear log list
	replaceChildNodes($("log-list"), null);
	//now populate log list
	for(var x=0; x <this.history.length; x++) {
		var logtxt = SPAN(this.history[x].hash+" | "+this.history[x].author+" | "+this._histDate(x));
		var radio = INPUT({'type' : 'radio', 'name' : 'log', 'class' : 'log-radio', 'value' : this.history[x].hash });
		var label = LABEL( null, radio, logtxt );
		var commitMsg = DIV({'class' : 'commit-msg'}, this.history[x].message);
		appendChildNodes($("log-list"), LI(null, label, commitMsg));
	}
	//make selected user selected in drop down box (visual clue that filter is applied)
	if(this.user != null) {
		$('repo-users').value = findValue(this.userList, this.user);
	}

	//connect event handler for when user applies filter to results
	connect('repo-users', 'onchange', bind(this._update, this));

	//disconnect the older/newer buttons
	disconnectAll($("older"));
	disconnectAll($("newer"));

	//if older results are available, enable the 'older' button and hook it up
	if(this.offset < (this.overflow-1)) {
		$("older").disabled = false;
		connect($("older"), 'onclick', bind(this._nextview, this, +1));
	} else
		$("older").disabled = true;

	//if newer results are available, enable the 'newer' button and hook it up
	if(this.offset > 0) {
		$("newer").disabled = false;
		connect($("newer"), 'onclick', bind(this._nextview, this, -1));
	} else
		$("newer").disabled = true;

	//connect up the 'Revert' button to event handler
	disconnectAll($("revert"));
	connect($("revert"), 'onclick', bind(this._revert, this, false));

	//connect up the 'Diff' button to event handler
	disconnectAll('log-diff');
	connect('log-diff', 'onclick', bind(this._diff, this, false));

	//connect up the close button on log menu
	disconnectAll($("log-close"));
	connect($("log-close"), 'onclick', bind(this.close, this));
}
//get older (updown > 0) or newer (updown < 0) results
Log.prototype._nextview = function(updown) {
	this.offset = this.offset+updown;
	//get new results page
	this._init();
}
//called when user applies author filter
Log.prototype._update = function() {
	//find out which author was selected  using select value as key to userList array
	var index = $('repo-users').value;
	//if user clicks 'All' (-1) clear user variable
	if(index > -1) {
		this.user = this.userList[index];
	} else {
		this.user = null;
	}
	logDebug("Filter logs by user: "+this.user);
	//reset offset
	this.offset = 0;
	this._init();
}

Log.prototype._receiveRevert = function(nodes,args) {
    arg_nodes = args["nodes"]
	if(nodes.commit != "")
		status_msg("Successfully reverted to version "+this.selectedRevision+" (New Revision: "+nodes.commit+")", LEVEL_OK);
	else
		status_msg("Failed to revert: "+nodes.success, LEVEL_ERROR);
	//in either case update the history
	this._retrieveHistory('quiet');
	//refresh open files. yes that's right, I'm abusing the scope chain massively to
	//get the file contents here, but I don't care. Whoever wrote the edit module needs
	//their head examined
	for (var key in editpage._open_files) {
		var fileHandle = editpage._open_files[key];
		fileHandle._load_contents()
		fileHandle._update_contents()
	}
}

Log.prototype._errorReceiveRevision = function(commitMsg) {
	status_button("Unable to contact server to revert file", LEVEL_ERROR, "retry", bind(this._do_revert, this, commitMsg));
}
Log.prototype._do_revert = function(commitMsg) {
    IDE_backend_request("file/co",
                        {
                            team:team,
                            project:IDE_path_get_project(this.file),
                            files:[IDE_path_get_file(this.file)],
                            revision:this.selectedRevision
                        },
                        bind(
                            function(nodes) {
                                IDE_backend_request("proj/commit",
                                                    {
                                                        team:team,
                                                        project:IDE_path_get_project(this.file),
                                                        paths:[IDE_path_get_file(this.file)],
                                                        message:commitMsg,
                                                        nodes:nodes
                                                    },
                                                    bind(this._receiveRevert,this),
                                                    bind(this._errorReceiveRevision,this,commitMsg)
                                                   )
                            }, this
                        ),
                        bind(
                            this._errorReceiveRevision,this,commitMsg
                        )
                       )
}

//revert to selected revision. override = true to skip user confirmation
Log.prototype._revert = function(override) {
	this._find_selected();

	if(this.selectedRevision < 0) {
		//no revision selected
		status_msg("No revision selected !", LEVEL_WARN);
	} else if(override) {
		//user has confirmed revert, proceed
		status_msg("Reverting to revision: "+this.selectedRevision+"...", LEVEL_INFO);
		var b = new Browser(bind(this._do_revert, this), {'type' : 'isCommit'});
	} else {
		//user has not confirmed revert, seek confirmation
		status_button("Are you sure you want to revert selected file(s)?", LEVEL_WARN, "Yes", bind(this._revert, this, true));
	}

}

//find out which radio button is checked
Log.prototype._find_selected = function() {
	var radios = getElementsByTagAndClassName("input", "log-radio");
	for(var x=0; x < radios.length; x++) {
		if(radios[x].checked == true) {
			this.selectedRevision = radios[x].value;
			break;
		}
	}
}

//view the diff applied by a selected revision.
Log.prototype._diff = function() {
	this._find_selected();

	if(this.selectedRevision < 0) {
		//no revision selected
		status_msg("No revision selected !", LEVEL_WARN);
	} else {
		diffpage.diff(this.file, this.selectedRevision);
	}
}

//tab gets focus
Log.prototype._onfocus = function() {
	if(getStyle($("log-mode"), "display") != "block") {
		setStyle($("log-mode"), {"display" : "block"});
	}
	//don't waste time doing query again, just process results in buffer
	this._populateList();
}

//tab loses focus
Log.prototype._onblur = function() {
	setStyle($("log-mode"), {"display" : "none"});
}
//tab is closed
Log.prototype.close = function() {
	this.tab.close();
	logDebug("Closing log tab");
}
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2005-2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 *  WSO2 Inc. licenses this file to you under the Apache License,
 *  Version 2.0 (the "License"); you may not use this file except
 *  in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an
 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *  KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations
 *  under the License.
 *
 */
app.dependencies=['store_common'];

app.server=function(ctx){

	return{
		endpoints:{
			pages:[
				{
					title:'WSO2 GREG Top Assets',
					url:'top-assets',
					path:'top_assets.jag'
				}
			]

		}

	}

};<commit_msg>Added extension ignore property<commit_after>/*
 *  Copyright (c) 2005-2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 *  WSO2 Inc. licenses this file to you under the Apache License,
 *  Version 2.0 (the "License"); you may not use this file except
 *  in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an
 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *  KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations
 *  under the License.
 *
 */
app.dependencies=['store_common'];
app.ignoreExtension=true;

app.server=function(ctx){

	return{
		endpoints:{
			pages:[
				{
					title:'WSO2 GREG Top Assets',
					url:'top-assets',
					path:'top_assets.jag'
				}
			]

		}

	}

};<|endoftext|>


<commit_before>function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }

const { getParamsAndQuery } = require('../utils');

const METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'];

const methodFn = method => (path, handler) => {
  if (!path) throw new Error('You need to set a valid path');
  if (!handler) throw new Error('You need to set a valid handler');

  return (req, res) => {
    const { params, query } = getParamsAndQuery(path, req.url);

    if (params && req.method === method) {
      return handler(Object.assign(req, { params, query }), res);
    }
  };
};

exports.router = (...funcs) => (() => {
  var _ref = _asyncToGenerator(function* (req, res) {
    for (const fn of funcs) {
      const result = yield fn(req, res);
      if (result || res.headersSent) return result;
    }
  });

  return function (_x, _x2) {
    return _ref.apply(this, arguments);
  };
})();

METHODS.forEach(method => {
  exports[method === 'DELETE' ? 'del' : method.toLowerCase()] = methodFn(method);
});<commit_msg>chore: add updated dist<commit_after>function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }

const UrlPattern = require('url-pattern');
const { send } = require('micro');
const { getParamsAndQuery } = require('../utils');

const METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'];

const methodFn = method => (path, handler) => {
  if (!path) throw new Error('You need to set a valid path');
  if (!handler) throw new Error('You need to set a valid handler');

  const route = new UrlPattern(path);

  return (req, res) => {
    const { params, query } = getParamsAndQuery(route, req.url);

    if (params && req.method === method) {
      return handler(Object.assign(req, { params, query }), res);
    }
  };
};

exports.router = (...funcs) => (() => {
  var _ref = _asyncToGenerator(function* (req, res) {
    for (const fn of funcs) {
      const result = yield fn(req, res);
      if (result || res.headersSent) return result;
    }

    send(res, 404, `Cannot ${req.method} ${req.url}`);
  });

  return function (_x, _x2) {
    return _ref.apply(this, arguments);
  };
})();

METHODS.forEach(method => {
  exports[method === 'DELETE' ? 'del' : method.toLowerCase()] = methodFn(method);
});<|endoftext|>