<commit_before>'use strict'

const fs = require('fs-extra')
const xml2json = require('xml2json')
const http = require('http')
const request = require('sync-request')

fs.ensureDirSync(__dirname + '/logs/')

_log_('Start')

let adress = [ // xml-file name, link
  ['dou_ua_online', 'http://dou.ua/calendar/feed/%D0%B2%D1%81%D0%B5%20%D1%82%D0%B5%D0%BC%D1%8B/online'],
  ['dou_ua_kyiv', 'http://dou.ua/calendar/feed/%D0%B2%D1%81%D0%B5%20%D1%82%D0%B5%D0%BC%D1%8B/%D0%9A%D0%B8%D0%B5%D0%B2']
]

for (let adr = 0; adr < adress.length; adr++) {
  // Paths to auxiliary files
  let xml = __dirname + '/xml/' + adress[adr][0] + '.xml'
  let newJSON = __dirname + '/json/new_' + adress[adr][0] + '.json'
  let oldJSON = __dirname + '/json/old_' + adress[adr][0] + '.json'

  // Check for the existence files
  fs.ensureFileSync(xml)
  fs.ensureFileSync(newJSON)
  fs.ensureFileSync(oldJSON)

  // Get xml-data from sources
  let res = request('GET', adress[adr][1])
  fs.writeFileSync(xml, res.getBody())

  // Save old file
  fs.copySync(newJSON, oldJSON)

  // XML to JSON
  let data = fs.readFileSync(xml)
  let result = xml2json.toJson(data, {sanitize: false})
  fs.writeFileSync(newJSON, result)

  data = fs.readFileSync(oldJSON)
  if (data == '') { _log_(adress[adr][0] + ': INIT'); continue } // not rewrite to '==='

  // Add new event
  let newData = fs.readJsonSync(newJSON, {throws: false})
  let oldData = fs.readJsonSync(oldJSON, {throws: false})

  if (newData.rss.channel.item[0].title ===
      oldData.rss.channel.item[0].title) { _log_(adress[adr][0] + ': UP TO DATE'); continue }

  let newI = newData.rss.channel.item
  let oldI = oldData.rss.channel.item

  let num = 0 // # the last new entry
  for (num; num < oldI.length; num++) {
    if (oldI[0].link === newI[num].link) {
      num -= 1
      break
    }
  }

  // RSS to API
  while (num >= 0) {
    let newID = newI[num].description

    function index (foo, bar) {
      return newID.indexOf(foo, bar)
    }

    function substr (foo, bar) {
      return newID.substring(foo, bar)
    }

    let title, agenda, place, registration_url, image_url, only_date, when_start
    switch (newData.rss.channel.link) {
      case 'http://dou.ua/calendar/':
        title = newI[num].title.replace(/(,)\s[0-9]{1,2}(.)+/g, '')

        agenda = 'IMAGE
' + // picture
                  substr(index('p', index('М', 250)) + 4) // other
        agenda = agenda.replace(/(h4>)/g, 'b>')

        place = substr(index('М', 250) + 27, index('p', index('М', 250)) - 2)
        if (place.toLowerCase() === 'online') place = 'Онлайн'

        registration_url = 'http://ITKPI.PP.UA/'
        image_url = ''
        only_date = false

        let month = {
          января: '01',
          февраля: '02',
          марта: '03',
          апреля: '04',
          мая: '05',
          июня: '06',
          июля: '07',
          августа: '08',
          сентября: '09',
          октября: '10',
          ноября: '11',
          декабря: '12'
        }
        let today = new Date()
        let dd = substr(index('Д', 200) + 17, index(' ', index('Д', 200))).replace(' ', '').replace(' ', '')
        let mm_now = today.getMonth() + 1 // January is 0!
        let mm = month[substr(index('Д', 200) + 17, index(' ', index('Д', 200) + 17)).replace(' ', '')] // In 'replace' - non-breaking space
        let yyyy = today.getFullYear()
        if (dd < 10) dd = '0' + dd
        if (mm_now > mm) yyyy += 1

        when_start = yyyy + '-' + mm + '-' + dd
        let time = substr(index('Н', 250) + 17, index('b', index('Н', 250) + 17) - 1)
        if (time.length < 6) {
          when_start += ' ' + time
        } else {
          only_date = true
        }

        break
    }

    // Send event to EventMonkey
    let body = JSON.stringify({
      title: '_T_E_S_T_ ' + adress[adr][0] + ' ' + title,
      agenda: agenda,
      social: '',
      place: place,
      registration_url: registration_url,
      image_url: image_url,
      level: 'NONE',
      when_start: when_start,
      when_end: when_start, // Required field... Need change in API
      only_date: only_date,
      team: 'ITKPI',
      submitter_email: 'vm@itkpi.pp.ua'
    })

    let options = {
      hostname: 'eventsmonkey.itkpi.pp.ua',
      port: 80,
      path: '/api/v1/suggested_events',
      method: 'POST',
      headers: {
        'Content-Type': 'application/json; charset=utf-8',
        'Content-Length': Buffer.byteLength(body)
      }
    }
    let req = http.request(options, (res) => {
      if (res.statusCode !== 201) {
        _log_(`HEADERS: ${JSON.stringify(res.headers)}`)
        res.setEncoding('utf8')
        res.on('data', (chunk) => { _log_(`BODY: ${chunk}`) })
        res.on('end', () => { _log_('No more data in response. \n') })
      }
    })
    req.on('error', (e) => { _log_(`problem with request: ${e.message}`) })

    req.write(body)
    req.end()
    num -= 1
  }
  _log_(adress[adr][0] + ': Done add all events')
}
_log_('Done \n')

var date
function _log_ (log) {
  let d = new Date()
  date = d.getDate()
  fs.appendFile(__dirname + '/logs/' + date + '.txt', d.toTimeString() + ': ' + log + '\n', (err) => {
    if (err) throw err
  })
}

if (date < 10) date += 30

remove()

function remove () {
  fs.remove(__dirname + '/logs/' + (date - 10) + '.txt', (err) => {
    if (err) throw err
  })
}
<commit_msg>Promisification<commit_after>'use strict'

const fs = require('fs-extra')
const xml2json = require('xml2json')
const http = require('http')
const request = require('sync-request')

fs.ensureDirSync(__dirname + '/logs/')
_log_('\n')

let adress = [ // xml-file name, link
  ['dou_ua_online', 'http://dou.ua/calendar/feed/%D0%B2%D1%81%D0%B5%20%D1%82%D0%B5%D0%BC%D1%8B/online'],
  ['dou_ua_kyiv', 'http://dou.ua/calendar/feed/%D0%B2%D1%81%D0%B5%20%D1%82%D0%B5%D0%BC%D1%8B/%D0%9A%D0%B8%D0%B5%D0%B2']
]

for (let adr = 0; adr < adress.length; adr++) {
  // Paths to auxiliary files
  let xml = __dirname + '/xml/' + adress[adr][0] + '.xml'
  let newJSON = __dirname + '/json/new_' + adress[adr][0] + '.json'
  let oldJSON = __dirname + '/json/old_' + adress[adr][0] + '.json'

  let p = new Promise((resolve, reject) => { // Check for the existence files
    fs.ensureFile(xml, (err) => { if (err) throw err })
    fs.ensureFile(newJSON, (err) => { if (err) throw err })
    fs.ensureFile(oldJSON, (err) => { if (err) throw err })
    return resolve()
  })

  p.then(() => { // Get xml-data from sources
    let res = request('GET', adress[adr][1])
    return fs.writeFileSync(xml, res.getBody())
  })

  p.then(() => { // Save old file
    return fs.copy(newJSON, oldJSON, (err) => { if (err) throw err })
  })

  p.then(() => { // XML to JSON
    let data = fs.readFileSync(xml)
    let result = xml2json.toJson(data, {sanitize: false})
    fs.writeFileSync(newJSON, result)

    data = fs.readFileSync(oldJSON)
    if (data == '') { _log_(adress[adr][0] + ': INIT'); /*continue*/ } // not rewrite to '==='
    return Promise.resolve()
  })

  p.then(() => { // Add new event
    let newData = fs.readJsonSync(newJSON, {throws: false})
    let oldData = fs.readJsonSync(oldJSON, {throws: false})

    if (newData.rss.channel.item[0].title ===
        oldData.rss.channel.item[0].title) { _log_(adress[adr][0] + ': UP TO DATE'); /*continue*/ }

    let newI = newData.rss.channel.item
    let oldI = oldData.rss.channel.item

    let num = 0 // # the last new entry
    for (num; num < oldI.length; num++) {
      if (oldI[0].link === newI[num].link) {
        num -= 1
        break
      }
    }

  // RSS to API
    while (num >= 0) {
      let newID = newI[num].description

      function index (foo, bar) {
        return newID.indexOf(foo, bar)
      }

      function substr (foo, bar) {
        return newID.substring(foo, bar)
      }

      let title, agenda, place, registration_url, image_url, only_date, when_start
      switch (newData.rss.channel.link) {
        case 'http://dou.ua/calendar/':
          title = newI[num].title.replace(/(,)\s[0-9]{1,2}(.)+/g, '')

         agenda = 'IMAGE
' + // picture
                   substr(index('p', index('М', 250)) + 4) // other
          agenda = agenda.replace(/(h4>)/g, 'b>')

          place = substr(index('М', 250) + 27, index('p', index('М', 250)) - 2)
          if (place.toLowerCase() === 'online') place = 'Онлайн'

          registration_url = 'http://ITKPI.PP.UA/'
          image_url = ''
          only_date = false

          let month = {
            января: '01',
            февраля: '02',
            марта: '03',
            апреля: '04',
            мая: '05',
            июня: '06',
            июля: '07',
            августа: '08',
            сентября: '09',
            октября: '10',
            ноября: '11',
            декабря: '12'
          }
          let today = new Date()
          let dd = substr(index('Д', 200) + 17, index(' ', index('Д', 200))).replace(' ', '').replace(' ', '')
          let mm_now = today.getMonth() + 1 // January is 0!
          let mm = month[substr(index('Д', 200) + 17, index(' ', index('Д', 200) + 17)).replace(' ', '')] // In 'replace' - non-breaking space
          let yyyy = today.getFullYear()
          if (dd < 10) dd = '0' + dd
          if (mm_now > mm) yyyy += 1

          when_start = yyyy + '-' + mm + '-' + dd
          let time = substr(index('Н', 250) + 17, index('b', index('Н', 250) + 17) - 1)
          if (time.length < 6) {
            when_start += ' ' + time
          } else {
            only_date = true
          }

          break
      }

        // Send event to EventMonkey
        let body = JSON.stringify({
          title: '_T_E_S_T_ ' + adress[adr][0] + ' ' + title,
          agenda: agenda,
          social: '',
          place: place,
          registration_url: registration_url,
          image_url: image_url,
          level: 'NONE',
          when_start: when_start,
          when_end: when_start, // Required field... Need change in API
          only_date: only_date,
          team: 'ITKPI',
          submitter_email: 'vm@itkpi.pp.ua'
        })

        let options = {
          hostname: 'eventsmonkey.itkpi.pp.ua',
          port: 80,
          path: '/api/v1/suggested_events',
          method: 'POST',
          headers: {
            'Content-Type': 'application/json; charset=utf-8',
            'Content-Length': Buffer.byteLength(body)
          }
        }
        let req = http.request(options, (res) => {
          if (res.statusCode !== 201) {
            _log_(`HEADERS: ${JSON.stringify(res.headers)}`)
            res.setEncoding('utf8')
            res.on('data', (chunk) => { _log_(`BODY: ${chunk}`) })
            res.on('end', () => { _log_('No more data in response. \n') })
          }
        })
        req.on('error', (e) => { _log_(`problem with request: ${e.message}`) })

        req.write(body)
        req.end()
        num -= 1
    }
    return Promise.resolve()
  })
  p.then(() => { return _log_(adress[adr][0] + ': Done add all events') })
}

var date
function _log_ (log) {
  let d = new Date()
  date = d.getDate()
  fs.appendFile(__dirname + '/logs/' + date + '.txt', d.toTimeString() + ': ' + log + '\n', (err) => {
    if (err) throw err
  })
}

if (date < 10) date += 30

remove()

function remove () {
  fs.remove(__dirname + '/logs/' + (date - 10) + '.txt', (err) => {
    if (err) throw err
  })
}
<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');
var book = require('./routes/book');
var adminRouter = require('./routes/admins');
var booksRouter = require('./routes/books');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);
app.use('/book', book);
app.use('/admin/api/v1', adminRouter);
app.use('/api/v1/books', booksRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

module.exports = app;
<commit_msg>modified app.js<commit_after>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');
var book = require('./routes/book');
var adminRouter = require('./routes/admins');
var booksRouter = require('./routes/books');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);
//app.use('/book', book);
app.use('/admin/api/v1', adminRouter);
app.use('/api/v1/books', booksRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

module.exports = app;
<|endoftext|>


<commit_before>//iTop Designer widget for editing properties line by line
$(function()
{
	// the widget definition, where "itop" is the namespace,
	// "property_field" the widget name
	$.widget( "itop.property_field",
	{
		// default options
		options:
		{
			parent_selector: null,
			field_id: '',
			submit_to: 'index.php',
			submit_parameters: {operation: 'async_action'},
			do_apply: null,
			do_cancel: null,
			auto_apply: false

		},

		// the constructor
		_create: function()
		{
			var me = this;

			this.element
				.addClass( "itop-property-field" )
				.bind('apply_changes.itop-property-field', function(){me._do_apply();} );

			this.bModified = false;

			if (this.options.field_id != '')
			{
				$('#'+this.options.field_id).bind('change.itop-property-field', function() { me._on_change(); });
				this.value = this._get_field_value();
			}
			this.element.find(".prop_apply").bind('click.itop-property-field', function() { me._do_apply(); });
			this.element.find(".prop_cancel").bind('click.itop-property-field', function() { me._do_cancel(); });

			this._refresh();
		},

		// called when created, and later when changing options
		_refresh: function()
		{
			if (this.bModified)
			{
				this.element.addClass("itop-property-field-modified");
				this.element.find(".prop_icon span.ui-icon-circle-check").css({visibility: ''});
				this.element.find(".prop_icon span.ui-icon-circle-close").css({visibility: ''});
			}
			else
			{
				this.element.removeClass("itop-property-field-modified");
				this.element.find(".prop_icon span.ui-icon-circle-check").css({visibility: 'hidden'});
				this.element.find(".prop_icon span.ui-icon-circle-close").css({visibility: 'hidden'});
			}
		},

		// events bound via _bind are removed automatically
		// revert other modifications here
		_destroy: function()
		{
			this.element.removeClass( "itop-property-field" );
			this.element.removeClass("itop-property-field-modified");
		},

		// _setOptions is called with a hash of all options that are changing
		// always refresh when changing options
		_setOptions: function()
		{
			// in 1.9 would use _superApply
			this._superApply(arguments);
			this._refresh();
		},

		// _setOption is called for each individual option that is changing
		_setOption: function( key, value )
		{
			// in 1.9 would use _super
			this._superApply(arguments);
		},
		_on_change: function()
		{
			var new_value = this._get_field_value();
			if (new_value != this.value)
			{
				this.bModified = true;
				if (this.options.auto_apply)
				{
					this._do_apply();
				}
			}
			else
			{
				this.bModified = false;
			}
			this._refresh();
		},
		_get_field_value: function()
		{
			var oField = $('#'+this.options.field_id);
			if (oField.attr('type') == 'checkbox')
			{
				return (oField.attr('checked') == 'checked');
			}
			else
			{
				return oField.val();
			}
		},
		_get_committed_value: function()
		{
			return { name: $('#'+this.options.field_id).attr('name'), value: this.value };
		},
		_do_apply: function()
		{
			if (this.options.parent_selector)
			{
				$(this.options.parent_selector).trigger('mark_as_modified');
			}
			if (this.options.do_apply)
			{
				// specific behavior...
				if (this.options.do_apply())
				{
					this.bModified = false;
					this.previous_value = this.value;
					this.value = this._get_field_value();
					this._refresh();
				}
			}
			else
			{
				// Validate the field
				sFormId = this.element.closest('form').attr('id');
				var oField = $('#'+this.options.field_id);
				oField.trigger('validate');
				if ( $.inArray(this.options.field_id, oFormValidation[sFormId]) == -1)
				{
					this.bModified = false;
					this.previous_value = this.value;
					this.value = this._get_field_value();
					this._do_submit();
					this._refresh();
				}
			}
		},
		_do_cancel: function()
		{
			if (this.options.do_cancel)
			{
				// specific behavior...
				this.options.do_cancel();
			}
			else
			{
				this.bModified = false;
				var oField = $('#'+this.options.field_id);
				if (oField.attr('type') == 'checkbox')
				{
					if (this.value)
					{
						oField.attr('checked', true);
					}
					else
					{
						oField.removeAttr('checked');
					}
				}
				else
				{
					oField.val(this.value);
				}
				this._refresh();
				oField.trigger('reverted', {type: 'designer', previous_value: this.value });
				oField.trigger('validate');
			}
		},
		_do_submit: function()
		{
			var oData = {};
			this.element.closest('form').find(':input[type=hidden]').each(function()
			{
				// Hidden form fields
				oData[$(this).attr('name')] = $(this).val();
			});
			this.element.closest('form').find('.itop-property-field').each(function()
			{
				var oWidget = $(this).data('itopProperty_field');
				if (oWidget && oWidget._is_visible())
				{
					var oVal = oWidget._get_committed_value();
					oData[oVal.name] = oVal.value;
				}
			});
			oPostedData = this.options.submit_parameters;
			oPostedData.params = oData;
			oPostedData.params.updated = [ $('#'+this.options.field_id).attr('name') ]; // only one field updated in this case
			oPostedData.params.previous_values = {};
			oPostedData.params.previous_values[oPostedData.params.updated] = this.previous_value; // pass also the previous value(s)
			$.post(this.options.submit_to, oPostedData, function(data)
			{
				$('#prop_submit_result').html(data);
			});
		},
		_is_visible: function()
		{
			return this.element.parent().is(':visible');
		}
	});
});

var oFormValidation = {};

function ValidateWithPattern(sFieldId, bMandatory, sPattern, sFormId, aForbiddenValues, sExplainForbiddenValues)
{
	var currentVal = $('#'+sFieldId).val();
	var bValid = true;
	var sMessage = null;

	if (bMandatory && (currentVal == ''))
	{
		bValid = false;
	}
	if ((sPattern != '') && (currentVal != ''))
	{
		re = new RegExp(sPattern);
		bValid = re.test(currentVal);
	}
	if (aForbiddenValues)
	{
		for(var i = 0; i < aForbiddenValues.length; i++)
		{
			if (aForbiddenValues[i] == currentVal)
			{
				bValid = false;
				sMessage = sExplainForbiddenValues;
				break;
			}
		}
	}

	if (oFormValidation[sFormId] == undefined) oFormValidation[sFormId] = [];
	if (!bValid)
	{
		$('#v_'+sFieldId).addClass('ui-state-error');
		oFormValidation[sFormId].push(sFieldId);
		if (sMessage)
		{
			$('#'+sFieldId).attr('title', sMessage).tooltip();
			if ($('#'+sFieldId).is(":focus"))
			{
				$('#'+sFieldId).tooltip('open');
			}
		}
	}
	else
	{
		$('#v_'+sFieldId).removeClass('ui-state-error');
		if ($('#'+sFieldId).data('uiTooltip'))
		{
			$('#'+sFieldId).tooltip('close');
		}
		$('#'+sFieldId).removeAttr('title');
		// Remove the element from the array
		iFieldIdPos = oFormValidation[sFormId].indexOf(sFieldId);
		oFormValidation[sFormId].splice(iFieldIdPos, 1);
	}
}

function ValidateForm(sFormId, bValidateAll)
{
	oFormValidation[sFormId] = [];
	if (bValidateAll)
	{
		$('#'+sFormId+' :input').trigger('validate');
	}
	else
	{
		// Only the visible fields
		$('#'+sFormId+' :input:visible').each(function() {
			$(this).trigger('validate');
		});
	}
	return oFormValidation[sFormId];
}

function ReadFormParams(sFormId)
{
	var oMap = { };
	$('#'+sFormId+' :input').each( function() {
		if ($(this).parent().is(':visible'))
		{
			var sName = $(this).attr('name');
			if (sName && sName != '')
			{
				if (this.type == 'checkbox')
				{
					oMap[sName] = ($(this).attr('checked') == 'checked');
				}
				else
				{
					oMap[sName] = $(this).val();
				}

			}
		}
	});
	return oMap;
}

function SubmitForm(sFormId, onSubmitResult)
{
	var aErrors = ValidateForm(sFormId, false);
	if (aErrors.length == 0)
	{
		var oMap = ReadFormParams(sFormId);
		oMap.module_name = sCurrentModule;
		$('#'+sFormId+' :input').each( function() {
			if ($(this).parent().is(':visible'))
			{
				var sName = $(this).attr('name');
				if (sName && sName != '')
				{
					if (this.type == 'checkbox')
					{
						oMap[sName] = ($(this).attr('checked') == 'checked');
					}
					else
					{
						oMap[sName] = $(this).val();
					}

				}
			}
		});
		$.post(GetAbsoluteUrlAppRoot()+'designer/module.php', oMap, function(data)
				{
					onSubmitResult(data);
				});
	}
	else
	{
		// TODO: better error reporting !!!
		alert('Please fill all the fields before continuing...');
	}
}
<commit_msg>Forms enhancements: - The current value of a field is automatically excluded from the forbidden values<commit_after>//iTop Designer widget for editing properties line by line
$(function()
{
	// the widget definition, where "itop" is the namespace,
	// "property_field" the widget name
	$.widget( "itop.property_field",
	{
		// default options
		options:
		{
			parent_selector: null,
			field_id: '',
			submit_to: 'index.php',
			submit_parameters: {operation: 'async_action'},
			do_apply: null,
			do_cancel: null,
			auto_apply: false

		},

		// the constructor
		_create: function()
		{
			var me = this;

			this.element
				.addClass( "itop-property-field" )
				.bind('apply_changes.itop-property-field', function(){me._do_apply();} );

			this.bModified = false;

			if (this.options.field_id != '')
			{
				$('#'+this.options.field_id).bind('change.itop-property-field', function() { me._on_change(); });
				this.value = this._get_field_value();
			}
			this.element.find(".prop_apply").bind('click.itop-property-field', function() { me._do_apply(); });
			this.element.find(".prop_cancel").bind('click.itop-property-field', function() { me._do_cancel(); });

			this._refresh();
		},

		// called when created, and later when changing options
		_refresh: function()
		{
			if (this.bModified)
			{
				this.element.addClass("itop-property-field-modified");
				this.element.find(".prop_icon span.ui-icon-circle-check").css({visibility: ''});
				this.element.find(".prop_icon span.ui-icon-circle-close").css({visibility: ''});
			}
			else
			{
				this.element.removeClass("itop-property-field-modified");
				this.element.find(".prop_icon span.ui-icon-circle-check").css({visibility: 'hidden'});
				this.element.find(".prop_icon span.ui-icon-circle-close").css({visibility: 'hidden'});
			}
		},

		// events bound via _bind are removed automatically
		// revert other modifications here
		_destroy: function()
		{
			this.element.removeClass( "itop-property-field" );
			this.element.removeClass("itop-property-field-modified");
		},

		// _setOptions is called with a hash of all options that are changing
		// always refresh when changing options
		_setOptions: function()
		{
			// in 1.9 would use _superApply
			this._superApply(arguments);
			this._refresh();
		},

		// _setOption is called for each individual option that is changing
		_setOption: function( key, value )
		{
			// in 1.9 would use _super
			this._superApply(arguments);
		},
		_on_change: function()
		{
			var new_value = this._get_field_value();
			if (new_value != this.value)
			{
				this.bModified = true;
				if (this.options.auto_apply)
				{
					this._do_apply();
				}
			}
			else
			{
				this.bModified = false;
			}
			this._refresh();
		},
		_get_field_value: function()
		{
			var oField = $('#'+this.options.field_id);
			if (oField.attr('type') == 'checkbox')
			{
				return (oField.attr('checked') == 'checked');
			}
			else
			{
				return oField.val();
			}
		},
		_get_committed_value: function()
		{
			return { name: $('#'+this.options.field_id).attr('name'), value: this.value };
		},
		_do_apply: function()
		{
			if (this.options.parent_selector)
			{
				$(this.options.parent_selector).trigger('mark_as_modified');
			}
			if (this.options.do_apply)
			{
				// specific behavior...
				if (this.options.do_apply())
				{
					this.bModified = false;
					this.previous_value = this.value;
					this.value = this._get_field_value();
					this._refresh();
				}
			}
			else
			{
				// Validate the field
				sFormId = this.element.closest('form').attr('id');
				var oField = $('#'+this.options.field_id);
				oField.trigger('validate');
				if ( $.inArray(this.options.field_id, oFormValidation[sFormId]) == -1)
				{
					this.bModified = false;
					this.previous_value = this.value;
					this.value = this._get_field_value();
					this._do_submit();
					this._refresh();
				}
			}
		},
		_do_cancel: function()
		{
			if (this.options.do_cancel)
			{
				// specific behavior...
				this.options.do_cancel();
			}
			else
			{
				this.bModified = false;
				var oField = $('#'+this.options.field_id);
				if (oField.attr('type') == 'checkbox')
				{
					if (this.value)
					{
						oField.attr('checked', true);
					}
					else
					{
						oField.removeAttr('checked');
					}
				}
				else
				{
					oField.val(this.value);
				}
				this._refresh();
				oField.trigger('reverted', {type: 'designer', previous_value: this.value });
				oField.trigger('validate');
			}
		},
		_do_submit: function()
		{
			var oData = {};
			this.element.closest('form').find(':input[type=hidden]').each(function()
			{
				// Hidden form fields
				oData[$(this).attr('name')] = $(this).val();
			});
			this.element.closest('form').find('.itop-property-field').each(function()
			{
				var oWidget = $(this).data('itopProperty_field');
				if (oWidget && oWidget._is_visible())
				{
					var oVal = oWidget._get_committed_value();
					oData[oVal.name] = oVal.value;
				}
			});
			oPostedData = this.options.submit_parameters;
			oPostedData.params = oData;
			oPostedData.params.updated = [ $('#'+this.options.field_id).attr('name') ]; // only one field updated in this case
			oPostedData.params.previous_values = {};
			oPostedData.params.previous_values[oPostedData.params.updated] = this.previous_value; // pass also the previous value(s)
			$.post(this.options.submit_to, oPostedData, function(data)
			{
				$('#prop_submit_result').html(data);
			});
		},
		_is_visible: function()
		{
			return this.element.parent().is(':visible');
		}
	});
});

var oFormValidation = {};

function ValidateWithPattern(sFieldId, bMandatory, sPattern, sFormId, aForbiddenValues, sExplainForbiddenValues)
{
	var currentVal = $('#'+sFieldId).val();
	var bValid = true;
	var sMessage = null;

	if (bMandatory && (currentVal == ''))
	{
		bValid = false;
	}
	if ((sPattern != '') && (currentVal != ''))
	{
		re = new RegExp(sPattern);
		bValid = re.test(currentVal);
	}
	if (aForbiddenValues)
	{
		for(var i in aForbiddenValues)
		{
			if (aForbiddenValues[i] == currentVal)
			{
				bValid = false;
				sMessage = sExplainForbiddenValues;
				break;
			}
		}
	}

	if (oFormValidation[sFormId] == undefined) oFormValidation[sFormId] = [];
	if (!bValid)
	{
		$('#v_'+sFieldId).addClass('ui-state-error');
		oFormValidation[sFormId].push(sFieldId);
		if (sMessage)
		{
			$('#'+sFieldId).attr('title', sMessage).tooltip();
			if ($('#'+sFieldId).is(":focus"))
			{
				$('#'+sFieldId).tooltip('open');
			}
		}
	}
	else
	{
		$('#v_'+sFieldId).removeClass('ui-state-error');
		if ($('#'+sFieldId).data('uiTooltip'))
		{
			$('#'+sFieldId).tooltip('close');
		}
		$('#'+sFieldId).removeAttr('title');
		// Remove the element from the array
		iFieldIdPos = oFormValidation[sFormId].indexOf(sFieldId);
		oFormValidation[sFormId].splice(iFieldIdPos, 1);
	}
}

function ValidateForm(sFormId, bValidateAll)
{
	oFormValidation[sFormId] = [];
	if (bValidateAll)
	{
		$('#'+sFormId+' :input').trigger('validate');
	}
	else
	{
		// Only the visible fields
		$('#'+sFormId+' :input:visible').each(function() {
			$(this).trigger('validate');
		});
	}
	return oFormValidation[sFormId];
}

function ReadFormParams(sFormId)
{
	var oMap = { };
	$('#'+sFormId+' :input').each( function() {
		if ($(this).parent().is(':visible'))
		{
			var sName = $(this).attr('name');
			if (sName && sName != '')
			{
				if (this.type == 'checkbox')
				{
					oMap[sName] = ($(this).attr('checked') == 'checked');
				}
				else
				{
					oMap[sName] = $(this).val();
				}

			}
		}
	});
	return oMap;
}

function SubmitForm(sFormId, onSubmitResult)
{
	var aErrors = ValidateForm(sFormId, false);
	if (aErrors.length == 0)
	{
		var oMap = ReadFormParams(sFormId);
		oMap.module_name = sCurrentModule;
		$('#'+sFormId+' :input').each( function() {
			if ($(this).parent().is(':visible'))
			{
				var sName = $(this).attr('name');
				if (sName && sName != '')
				{
					if (this.type == 'checkbox')
					{
						oMap[sName] = ($(this).attr('checked') == 'checked');
					}
					else
					{
						oMap[sName] = $(this).val();
					}

				}
			}
		});
		$.post(GetAbsoluteUrlAppRoot()+'designer/module.php', oMap, function(data)
				{
					onSubmitResult(data);
				});
	}
	else
	{
		// TODO: better error reporting !!!
		alert('Please fill all the fields before continuing...');
	}
}
<|endoftext|>


<commit_before>var fs = require('fs');
var express = require('express');
var app = express();
var http = require('http');
var bodyParser = require("body-parser");
var Curl = require( 'node-libcurl' ).Curl;
var Promise = require('promise');

app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());

var HOST = process.argv[2] || '127.0.0.1';
console.log('Will start on host: %s', HOST);

var PORT = process.argv[3] || 8080;
console.log('Will start on port: %s', PORT);

app.get('/haproxy', function(req, res){

    function IPs(filePath){

        var curlLog = '';

        var regIP = /^(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[0-9]{2}|[0-9])(\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[0-9]{2}|[0-9])){3}\:[0-9]{1,4}\n?$/;

        var haproxy_origin = fs.readFileSync(filePath, 'utf8');
        var haproxy_splited_rows = haproxy_origin.split('\n');

        //cut and leave only configuration part of haproxy.cfg file
        for(var i = 0; i < haproxy_splited_rows.length; ++i){
            if(haproxy_splited_rows[i] != ''){
                 var temp = haproxy_splited_rows[i].split(' ');
                 if(temp[0] == 'frontend'){
                     haproxy_splited_rows = haproxy_splited_rows.slice(i);
                     break;
                 }
            }
        }

        //delete odd spaces
        for(var i = 0; i < haproxy_splited_rows.length; ++i){
            haproxy_splited_rows[i] = haproxy_splited_rows[i].replace(/^\s*/,'').replace(/\s*$/,'');
        }

        //search for {frontend name : frontend address}
        var frontend_names = {};

        for(var i = 0; i < haproxy_splited_rows.length; ++i){
            var temp = haproxy_splited_rows[i].split(' ');
            for(var j = 0; j < temp.length; ++j){
                if(temp[j] == 'acl'){

                    frontend_names[temp[j+1]] = temp[temp.length - 1];

                }
            }
        }

        //search for {backend name : backend address}
        var backend_part_rows = [];
        for(var i = 0; i < haproxy_splited_rows.length; ++i){
            var temp = haproxy_splited_rows[i].split(' ');
            if(temp[0] == 'backend'){
                backend_part_rows = haproxy_splited_rows.slice(i);
                break;
            }
        }

        var backends_string = '';
        for(var i = 0; i < backend_part_rows.length; ++i){
            backends_string += ' ' + backend_part_rows[i];
        }

        var backend_names = {}; // {backend name : addresses}
        var backends_array_spaces = backends_string.split(' ');
        for(var i = 0; i < backends_array_spaces.length; ++i){

            if(backends_array_spaces[i] == 'backend'){

                backend_names[backends_array_spaces[i + 1]] = '';

                var temp_adr = '';

                for(var j = i; j < backends_array_spaces.length; ++j){

                    if(regIP.test(backends_array_spaces[j])){
                        temp_adr += backends_array_spaces[j] + ' ';
                        backend_names[backends_array_spaces[i + 1]] = temp_adr;
                    }
                    if(backends_array_spaces[j] == 'backend' && j != i){
                        i = j - 1;
                        break;
                    }
                }

            }

        }

        // define pairs front-backend
        var pairs = [];
        for(var i = 0; i < haproxy_splited_rows.length; ++i){
            var temp = haproxy_splited_rows[i].split(' ');
            for(var j = 0; j < temp.length; ++j) {
                if (temp[j] == 'use_backend'){
                    var obj = {};
                    obj.frontend = temp[temp.length - 1];
                    obj.backend = temp[j + 1];
                    pairs.push(obj);
                }
            }
        }

        // build config array [{frontend: 'IP', backend: 'IP', status: ''}, {...}]

        var IPs = [];

        for(var i = 0; i < pairs.length; ++i){
            var obj = {};
            obj.frontend = frontend_names[pairs[i].frontend];
            obj.backend = backend_names[pairs[i].backend];
            obj.status = "Not available";
            IPs.push(obj);
        }

        // preparing for status check
        var tempBackends = [];

        for(var i = 0; i < IPs.length; ++i){
            IPs[i].backend = IPs[i].backend.replace(/^\s*/,'').replace(/\s*$/,'');
            tempBackends[i] = "http://" + IPs[i].backend;
        }

        function getPromise(backend) {
            return new Promise(function(resolve) {

                var curl = new Curl();

                curl.setOpt( 'URL', backend );
                curl.setOpt( 'CONNECTTIMEOUT', 5 );
                curl.setOpt( 'FOLLOWLOCATION', true );

                curl.on( 'end', function(statusCode, body, headers) {
                    console.info(backend + ' is available');

                    curlLog += backend + ' status code ' + statusCode + '\n';
                    curlLog += backend + ' headers ' + headers + '\n';
                    curlLog += backend + ' body ' + body + '\n';

                    resolve("Available");
                    this.close();
                });

                curl.on( 'error', function(statusCode, body, headers){
                    console.info(backend + ' is not available');

                    curlLog += backend + ' status code ' + statusCode + '\n';
                    curlLog += backend + ' headers ' + headers + '\n';
                    curlLog += backend + ' body ' + body + '\n';

                    resolve("Not available");
                    this.close();
                });

                curl.perform();

         });
        }

        Promise.all(tempBackends . map(getPromise)) .
        then(function(stats) {

            for(var i = 0; i < stats.length; ++i)
            {
                IPs[i].status = stats[i];
            }

            var data = { IPs : IPs,
                         log: curlLog};
            res.json(data);
        });

    }
    try{IPs('/etc/haproxy/haproxy.cfg');}
    catch(e){ console.log(e);
    res.end('haproxy.cfg not found');
}

});

app.get('/download', function(req, res){

  var file = '/etc/haproxy/haproxy.cfg';
  res.download(file);

});

app.get('/view', function(req, res){
  var file = fs.readFileSync('/etc/haproxy/haproxy.cfg', 'utf8');
  res.end(file);
});

app.post('/certificate', function(req, res){

  var haproxy_origin = fs.readFileSync('/etc/haproxy/haproxy.cfg', 'utf8');
  var haproxy_splited_rows = haproxy_origin.split('\n');

  var certificate = req.body.pem;
  var name = req.body.name;
  var front = req.body.frontend;
  console.log("Add crt to front:   " + front);

  var path = '/etc/pki/tls/private/' + name + '.pem';
  var restartCmd = 'service haproxy restart';

  var exec = require('child_process').exec;

  for(var i = 0; i<haproxy_splited_rows.length; ++i){
      if (haproxy_splited_rows[i].indexOf('bind') >=0 && haproxy_splited_rows[i].indexOf(front + ':') >=0){
          haproxy_splited_rows[i] += ' ssl crt /etc/pki/tls/private/' + name +'.pem';
      }
  }

  var new_haproxy = haproxy_splited_rows.join('\n');

  fs.writeFile(path, certificate, function (err) {
            if (err) {
                return console.log(err);
            }
            console.log('Certificate wroten in ' + path);

                fs.writeFile('/etc/haproxy/haproxy.cfg', new_haproxy, function (err) {
                if (err) {
                    return console.log(err);
                }
                console.log('haproxy.cfg updated');

                    exec(restartCmd, function (error, stdout, stderr) {
                        if (error !== null) {
                            console.log('exec error: ' + error);
                        }
                        console.log('Restarting haproxy');
                    });
            });
 });
});

var server = app.listen(PORT, HOST, function () {
    var host = server.address().address;
    var port = server.address().port;

    console.log('haproxyUI listening at http://%s:%s', host, port);
});
<commit_msg>log clean<commit_after>var fs = require('fs');
var express = require('express');
var app = express();
var http = require('http');
var bodyParser = require("body-parser");
var Curl = require( 'node-libcurl' ).Curl;
var Promise = require('promise');

app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());

var HOST = process.argv[2] || '127.0.0.1';
console.log('Will start on host: %s', HOST);

var PORT = process.argv[3] || 8080;
console.log('Will start on port: %s', PORT);

app.get('/haproxy', function(req, res){

    function IPs(filePath){

        var curlLog = '';

        var regIP = /^(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[0-9]{2}|[0-9])(\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[0-9]{2}|[0-9])){3}\:[0-9]{1,4}\n?$/;

        var haproxy_origin = fs.readFileSync(filePath, 'utf8');
        var haproxy_splited_rows = haproxy_origin.split('\n');

        //cut and leave only configuration part of haproxy.cfg file
        for(var i = 0; i < haproxy_splited_rows.length; ++i){
            if(haproxy_splited_rows[i] != ''){
                 var temp = haproxy_splited_rows[i].split(' ');
                 if(temp[0] == 'frontend'){
                     haproxy_splited_rows = haproxy_splited_rows.slice(i);
                     break;
                 }
            }
        }

        //delete odd spaces
        for(var i = 0; i < haproxy_splited_rows.length; ++i){
            haproxy_splited_rows[i] = haproxy_splited_rows[i].replace(/^\s*/,'').replace(/\s*$/,'');
        }

        //search for {frontend name : frontend address}
        var frontend_names = {};

        for(var i = 0; i < haproxy_splited_rows.length; ++i){
            var temp = haproxy_splited_rows[i].split(' ');
            for(var j = 0; j < temp.length; ++j){
                if(temp[j] == 'acl'){

                    frontend_names[temp[j+1]] = temp[temp.length - 1];

                }
            }
        }

        //search for {backend name : backend address}
        var backend_part_rows = [];
        for(var i = 0; i < haproxy_splited_rows.length; ++i){
            var temp = haproxy_splited_rows[i].split(' ');
            if(temp[0] == 'backend'){
                backend_part_rows = haproxy_splited_rows.slice(i);
                break;
            }
        }

        var backends_string = '';
        for(var i = 0; i < backend_part_rows.length; ++i){
            backends_string += ' ' + backend_part_rows[i];
        }

        var backend_names = {}; // {backend name : addresses}
        var backends_array_spaces = backends_string.split(' ');
        for(var i = 0; i < backends_array_spaces.length; ++i){

            if(backends_array_spaces[i] == 'backend'){

                backend_names[backends_array_spaces[i + 1]] = '';

                var temp_adr = '';

                for(var j = i; j < backends_array_spaces.length; ++j){

                    if(regIP.test(backends_array_spaces[j])){
                        temp_adr += backends_array_spaces[j] + ' ';
                        backend_names[backends_array_spaces[i + 1]] = temp_adr;
                    }
                    if(backends_array_spaces[j] == 'backend' && j != i){
                        i = j - 1;
                        break;
                    }
                }

            }

        }

        // define pairs front-backend
        var pairs = [];
        for(var i = 0; i < haproxy_splited_rows.length; ++i){
            var temp = haproxy_splited_rows[i].split(' ');
            for(var j = 0; j < temp.length; ++j) {
                if (temp[j] == 'use_backend'){
                    var obj = {};
                    obj.frontend = temp[temp.length - 1];
                    obj.backend = temp[j + 1];
                    pairs.push(obj);
                }
            }
        }

        // build config array [{frontend: 'IP', backend: 'IP', status: ''}, {...}]

        var IPs = [];

        for(var i = 0; i < pairs.length; ++i){
            var obj = {};
            obj.frontend = frontend_names[pairs[i].frontend];
            obj.backend = backend_names[pairs[i].backend];
            obj.status = "Not available";
            IPs.push(obj);
        }

        // preparing for status check
        var tempBackends = [];

        for(var i = 0; i < IPs.length; ++i){
            IPs[i].backend = IPs[i].backend.replace(/^\s*/,'').replace(/\s*$/,'');
            tempBackends[i] = "http://" + IPs[i].backend;
        }

        var tempFrontends = [];

        for(var i = 0; i < IPs.length; ++i){
            IPs[i].frontend = IPs[i].frontend.replace(/^\s*/,'').replace(/\s*$/,'');
            tempFrontends[i] = "http://" + IPs[i].frontend;
        }

        var tempIP = [];
        for(var i = 0; i < IPs.length; ++i){
            tempIP[i] = tempFrontends[i] + '|' + tempBackends[i];

        }

        function getPromise(IP) {
            return new Promise(function(resolve) {

                var curl = new Curl();

                var backend = IP.split('|')[1];
                console.log('Backend ' + backend);
                var frontend = IP.split('|')[0]
                console.log('Frontend ' + frontend);

                curl.setOpt( 'URL', backend );
                //curl.setOpt( 'CURLOPT_HTTPHEADER', ['Host:' + frontend]);
                curl.setOpt( 'CONNECTTIMEOUT', 5 );
                curl.setOpt( 'FOLLOWLOCATION', true );
                curl.setOpt( 'NOBODY', true );

                curl.on( 'end', function(statusCode) {
                    console.info(backend + ' is available');

                    curlLog += 'Requesting ' + backend + '\n';
                    curlLog += 'Received status code: ' + statusCode + '\n';

                    resolve("Available");
                    this.close();
                });

                curl.on( 'error', function(statusCode){
                    console.info(backend + ' is not available');

                    curlLog += backend + ' ' + statusCode + '\n';

                    resolve("Not available");
                    this.close();
                });

                curl.perform();

         });
        }

        Promise.all(tempIP . map(getPromise)) .
        then(function(stats) {

            for(var i = 0; i < stats.length; ++i)
            {
                IPs[i].status = stats[i];
            }

            var data = { IPs : IPs,
                         log: curlLog};
            res.json(data);
        });

    }
    try{IPs('/etc/haproxy/haproxy.cfg');}
    catch(e){ console.log(e);
    res.end('haproxy.cfg not found');
}

});

app.get('/download', function(req, res){

  var file = '/etc/haproxy/haproxy.cfg';
  res.download(file);

});

app.get('/view', function(req, res){
  var file = fs.readFileSync('/etc/haproxy/haproxy.cfg', 'utf8');
  res.end(file);
});

app.post('/certificate', function(req, res){

  var haproxy_origin = fs.readFileSync('/etc/haproxy/haproxy.cfg', 'utf8');
  var haproxy_splited_rows = haproxy_origin.split('\n');

  var certificate = req.body.pem;
  var name = req.body.name;
  var front = req.body.frontend;
  console.log("Add crt to front:   " + front);

  var path = '/etc/pki/tls/private/' + name + '.pem';
  var restartCmd = 'service haproxy restart';

  var exec = require('child_process').exec;

  for(var i = 0; i<haproxy_splited_rows.length; ++i){
      if (haproxy_splited_rows[i].indexOf('bind') >=0 && haproxy_splited_rows[i].indexOf(front + ':') >=0){
          haproxy_splited_rows[i] += ' ssl crt /etc/pki/tls/private/' + name +'.pem';
      }
  }

  var new_haproxy = haproxy_splited_rows.join('\n');

  fs.writeFile(path, certificate, function (err) {
            if (err) {
                return console.log(err);
            }
            console.log('Certificate wroten in ' + path);

                fs.writeFile('/etc/haproxy/haproxy.cfg', new_haproxy, function (err) {
                if (err) {
                    return console.log(err);
                }
                console.log('haproxy.cfg updated');

                    exec(restartCmd, function (error, stdout, stderr) {
                        if (error !== null) {
                            console.log('exec error: ' + error);
                        }
                        console.log('Restarting haproxy');
                    });
            });
 });
});

var server = app.listen(PORT, HOST, function () {
    var host = server.address().address;
    var port = server.address().port;

    console.log('haproxyUI listening at http://%s:%s', host, port);
});
<|endoftext|>


<commit_before>import { combineReducers } from "redux";
import { BANDS, WINDOWS } from "../constants";
import {
  CLOSE_WINAMP,
  SET_BALANCE,
  SET_BAND_VALUE,
  SET_FOCUS,
  SET_BAND_FOCUS,
  SET_FOCUSED_WINDOW,
  SET_MEDIA,
  SET_SCRUB_POSITION,
  SET_SKIN_DATA,
  SET_VOLUME,
  START_WORKING,
  STEP_MARQUEE,
  STOP_WORKING,
  TOGGLE_DOUBLESIZE_MODE,
  TOGGLE_EQUALIZER_WINDOW,
  CLOSE_EQUALIZER_WINDOW,
  TOGGLE_PLAYLIST_WINDOW,
  SET_EQ_AUTO,
  SET_EQ_ON,
  SET_EQ_OFF,
  TOGGLE_LLAMA_MODE,
  TOGGLE_REPEAT,
  TOGGLE_SHADE_MODE,
  TOGGLE_EQUALIZER_SHADE_MODE,
  TOGGLE_PLAYLIST_SHADE_MODE,
  TOGGLE_SHUFFLE,
  TOGGLE_TIME_MODE,
  TOGGLE_VISUALIZER_STYLE,
  UNSET_FOCUS,
  UPDATE_TIME_ELAPSED,
  SET_USER_MESSAGE,
  UNSET_USER_MESSAGE,
  SET_PLAYLIST_SCROLL_POSITION,
  PLAYLIST_SIZE_CHANGED,
  SET_AVALIABLE_SKINS,
  ADD_TRACK_FROM_URL,
  CLOSE_GEN_WINDOW,
  OPEN_GEN_WINDOW
} from "../actionTypes";

import { arrayWith, arrayWithout } from "../utils";
import playlist from "./playlist";

const defaultUserInput = {
  focus: null,
  bandFocused: null,
  scrubPosition: 0,
  userMessage: null
};

export const userInput = (state = defaultUserInput, action) => {
  switch (action.type) {
    case SET_FOCUS:
      return { ...state, focus: action.input, bandFocused: null };
    case SET_BAND_FOCUS:
      return { ...state, focus: action.input, bandFocused: action.bandFocused };
    case UNSET_FOCUS:
      return { ...state, focus: null, bandFocused: null };
    case SET_SCRUB_POSITION:
      return { ...state, scrubPosition: action.position };
    case SET_USER_MESSAGE:
      return { ...state, userMessage: action.message };
    case UNSET_USER_MESSAGE:
      return { ...state, userMessage: null };
    default:
      return state;
  }
};

const defaultWindowsState = {
  focused: WINDOWS.MAIN,
  equalizer: true,
  playlist: true,
  openGenWindows: ["AVS_WINDOW"]
};

const windows = (state = defaultWindowsState, action) => {
  switch (action.type) {
    case SET_FOCUSED_WINDOW:
      return { ...state, focused: action.window };
    case TOGGLE_EQUALIZER_WINDOW:
      return { ...state, equalizer: !state.equalizer };
    case CLOSE_EQUALIZER_WINDOW:
      return { ...state, equalizer: false };
    case TOGGLE_PLAYLIST_WINDOW:
      return { ...state, playlist: !state.playlist };
    case CLOSE_GEN_WINDOW:
      return {
        ...state,
        openGenWindows: arrayWithout(state.openGenWindow, action.windowId)
      };
    case OPEN_GEN_WINDOW:
      return {
        ...state,
        openGenWindows: arrayWith(state.openGenWindow, action.windowId)
      };
    default:
      return state;
  }
};

const defaultDisplayState = {
  doubled: false,
  marqueeStep: 0,
  loading: true,
  llama: false,
  closed: false,
  shade: false,
  equalizerShade: false,
  playlistShade: false,
  working: false,
  skinImages: {},
  skinColors: null,
  skinCursors: null,
  skinPlaylistStyle: {},
  skinRegion: {},
  visualizerStyle: 2,
  playlistScrollPosition: 0,
  playlistSize: [0, 0]
};

const display = (state = defaultDisplayState, action) => {
  switch (action.type) {
    case TOGGLE_DOUBLESIZE_MODE:
      return { ...state, doubled: !state.doubled };
    case TOGGLE_SHADE_MODE:
      return { ...state, shade: !state.shade };
    case TOGGLE_EQUALIZER_SHADE_MODE:
      return { ...state, equalizerShade: !state.equalizerShade };
    case TOGGLE_PLAYLIST_SHADE_MODE:
      return { ...state, playlistShade: !state.playlistShade };
    case TOGGLE_LLAMA_MODE:
      return { ...state, llama: !state.llama };
    case STEP_MARQUEE:
      // TODO: Prevent this from becoming huge
      return { ...state, marqueeStep: state.marqueeStep + 1 };
    case STOP_WORKING:
      return { ...state, working: false };
    case START_WORKING:
      return { ...state, working: true };
    case CLOSE_WINAMP:
      return { ...state, closed: true };
    case SET_SKIN_DATA:
      return {
        ...state,
        loading: false,
        skinImages: action.skinImages,
        skinColors: action.skinColors,
        skinPlaylistStyle: action.skinPlaylistStyle,
        skinCursors: action.skinCursors,
        skinRegion: action.skinRegion,
        skinGenLetterWidths: action.skinGenLetterWidths
      };
    case TOGGLE_VISUALIZER_STYLE:
      return { ...state, visualizerStyle: (state.visualizerStyle + 1) % 3 };
    case SET_PLAYLIST_SCROLL_POSITION:
      return { ...state, playlistScrollPosition: action.position };
    case PLAYLIST_SIZE_CHANGED:
      return { ...state, playlistSize: action.size };
    default:
      return state;
  }
};

const defaultSettingsState = {
  avaliableSkins: []
};

const settings = (state = defaultSettingsState, action) => {
  switch (action.type) {
    case SET_AVALIABLE_SKINS:
      return { ...state, avaliableSkins: action.skins };
    default:
      return state;
  }
};

const equalizer = (state, action) => {
  if (!state) {
    state = {
      on: true,
      auto: false,
      sliders: {
        preamp: 50
      }
    };
    BANDS.forEach(band => {
      state.sliders[band] = 50;
    });
    return state;
  }
  switch (action.type) {
    case SET_BAND_VALUE:
      const newSliders = { ...state.sliders, [action.band]: action.value };
      return { ...state, sliders: newSliders };
    case SET_EQ_ON:
      return { ...state, on: true };
    case SET_EQ_OFF:
      return { ...state, on: false };
    case SET_EQ_AUTO:
      return { ...state, auto: action.value };
    default:
      return state;
  }
};

const media = (state, action) => {
  if (!state) {
    return {
      timeMode: "ELAPSED",
      timeElapsed: 0,
      length: null, // Consider renaming to "duration"
      kbps: null,
      khz: null,
      // The winamp ini file declares the default volume as "200".
      // The UI seems to show a default volume near 78, which would
      // math with the default value being 200 out of 255.
      volume: Math.round(200 / 255 * 100),
      balance: 0,
      channels: null,
      shuffle: false,
      repeat: false,
      // TODO: Enforce possible values
      status: "STOPPED"
    };
  }
  switch (action.type) {
    // TODO: Make these constants
    case "PLAY":
    case "IS_PLAYING":
      return { ...state, status: "PLAYING" };
    case "PAUSE":
      return { ...state, status: "PAUSED" };
    case "STOP":
    case "IS_STOPPED":
      return { ...state, status: "STOPPED" };
    case TOGGLE_TIME_MODE:
      const newMode = state.timeMode === "REMAINING" ? "ELAPSED" : "REMAINING";
      return { ...state, timeMode: newMode };
    case UPDATE_TIME_ELAPSED:
      return { ...state, timeElapsed: action.elapsed };
    case ADD_TRACK_FROM_URL:
      return {
        ...state,
        timeElapsed: 0,
        length: null,
        kbps: null,
        khz: null,
        channels: null
      };
    case SET_MEDIA:
      return {
        ...state,
        length: action.length,
        kbps: action.kbps,
        khz: action.khz,
        channels: action.channels
      };
    case SET_VOLUME:
      return { ...state, volume: action.volume };
    case SET_BALANCE:
      return { ...state, balance: action.balance };
    case TOGGLE_REPEAT:
      return { ...state, repeat: !state.repeat };
    case TOGGLE_SHUFFLE:
      return { ...state, shuffle: !state.shuffle };
    default:
      return state;
  }
};

const reducer = combineReducers({
  userInput,
  windows,
  display,
  settings,
  equalizer,
  playlist,
  media
});

export default reducer;
<commit_msg>Disable AVS<commit_after>import { combineReducers } from "redux";
import { BANDS, WINDOWS } from "../constants";
import {
  CLOSE_WINAMP,
  SET_BALANCE,
  SET_BAND_VALUE,
  SET_FOCUS,
  SET_BAND_FOCUS,
  SET_FOCUSED_WINDOW,
  SET_MEDIA,
  SET_SCRUB_POSITION,
  SET_SKIN_DATA,
  SET_VOLUME,
  START_WORKING,
  STEP_MARQUEE,
  STOP_WORKING,
  TOGGLE_DOUBLESIZE_MODE,
  TOGGLE_EQUALIZER_WINDOW,
  CLOSE_EQUALIZER_WINDOW,
  TOGGLE_PLAYLIST_WINDOW,
  SET_EQ_AUTO,
  SET_EQ_ON,
  SET_EQ_OFF,
  TOGGLE_LLAMA_MODE,
  TOGGLE_REPEAT,
  TOGGLE_SHADE_MODE,
  TOGGLE_EQUALIZER_SHADE_MODE,
  TOGGLE_PLAYLIST_SHADE_MODE,
  TOGGLE_SHUFFLE,
  TOGGLE_TIME_MODE,
  TOGGLE_VISUALIZER_STYLE,
  UNSET_FOCUS,
  UPDATE_TIME_ELAPSED,
  SET_USER_MESSAGE,
  UNSET_USER_MESSAGE,
  SET_PLAYLIST_SCROLL_POSITION,
  PLAYLIST_SIZE_CHANGED,
  SET_AVALIABLE_SKINS,
  ADD_TRACK_FROM_URL,
  CLOSE_GEN_WINDOW,
  OPEN_GEN_WINDOW
} from "../actionTypes";

import { arrayWith, arrayWithout } from "../utils";
import playlist from "./playlist";

const defaultUserInput = {
  focus: null,
  bandFocused: null,
  scrubPosition: 0,
  userMessage: null
};

export const userInput = (state = defaultUserInput, action) => {
  switch (action.type) {
    case SET_FOCUS:
      return { ...state, focus: action.input, bandFocused: null };
    case SET_BAND_FOCUS:
      return { ...state, focus: action.input, bandFocused: action.bandFocused };
    case UNSET_FOCUS:
      return { ...state, focus: null, bandFocused: null };
    case SET_SCRUB_POSITION:
      return { ...state, scrubPosition: action.position };
    case SET_USER_MESSAGE:
      return { ...state, userMessage: action.message };
    case UNSET_USER_MESSAGE:
      return { ...state, userMessage: null };
    default:
      return state;
  }
};

const defaultWindowsState = {
  focused: WINDOWS.MAIN,
  equalizer: true,
  playlist: true,
  // openGenWindows: ["AVS_WINDOW"]
  openGenWindows: []
};

const windows = (state = defaultWindowsState, action) => {
  switch (action.type) {
    case SET_FOCUSED_WINDOW:
      return { ...state, focused: action.window };
    case TOGGLE_EQUALIZER_WINDOW:
      return { ...state, equalizer: !state.equalizer };
    case CLOSE_EQUALIZER_WINDOW:
      return { ...state, equalizer: false };
    case TOGGLE_PLAYLIST_WINDOW:
      return { ...state, playlist: !state.playlist };
    case CLOSE_GEN_WINDOW:
      return {
        ...state,
        openGenWindows: arrayWithout(state.openGenWindow, action.windowId)
      };
    case OPEN_GEN_WINDOW:
      return {
        ...state,
        openGenWindows: arrayWith(state.openGenWindow, action.windowId)
      };
    default:
      return state;
  }
};

const defaultDisplayState = {
  doubled: false,
  marqueeStep: 0,
  loading: true,
  llama: false,
  closed: false,
  shade: false,
  equalizerShade: false,
  playlistShade: false,
  working: false,
  skinImages: {},
  skinColors: null,
  skinCursors: null,
  skinPlaylistStyle: {},
  skinRegion: {},
  visualizerStyle: 2,
  playlistScrollPosition: 0,
  playlistSize: [0, 0]
};

const display = (state = defaultDisplayState, action) => {
  switch (action.type) {
    case TOGGLE_DOUBLESIZE_MODE:
      return { ...state, doubled: !state.doubled };
    case TOGGLE_SHADE_MODE:
      return { ...state, shade: !state.shade };
    case TOGGLE_EQUALIZER_SHADE_MODE:
      return { ...state, equalizerShade: !state.equalizerShade };
    case TOGGLE_PLAYLIST_SHADE_MODE:
      return { ...state, playlistShade: !state.playlistShade };
    case TOGGLE_LLAMA_MODE:
      return { ...state, llama: !state.llama };
    case STEP_MARQUEE:
      // TODO: Prevent this from becoming huge
      return { ...state, marqueeStep: state.marqueeStep + 1 };
    case STOP_WORKING:
      return { ...state, working: false };
    case START_WORKING:
      return { ...state, working: true };
    case CLOSE_WINAMP:
      return { ...state, closed: true };
    case SET_SKIN_DATA:
      return {
        ...state,
        loading: false,
        skinImages: action.skinImages,
        skinColors: action.skinColors,
        skinPlaylistStyle: action.skinPlaylistStyle,
        skinCursors: action.skinCursors,
        skinRegion: action.skinRegion,
        skinGenLetterWidths: action.skinGenLetterWidths
      };
    case TOGGLE_VISUALIZER_STYLE:
      return { ...state, visualizerStyle: (state.visualizerStyle + 1) % 3 };
    case SET_PLAYLIST_SCROLL_POSITION:
      return { ...state, playlistScrollPosition: action.position };
    case PLAYLIST_SIZE_CHANGED:
      return { ...state, playlistSize: action.size };
    default:
      return state;
  }
};

const defaultSettingsState = {
  avaliableSkins: []
};

const settings = (state = defaultSettingsState, action) => {
  switch (action.type) {
    case SET_AVALIABLE_SKINS:
      return { ...state, avaliableSkins: action.skins };
    default:
      return state;
  }
};

const equalizer = (state, action) => {
  if (!state) {
    state = {
      on: true,
      auto: false,
      sliders: {
        preamp: 50
      }
    };
    BANDS.forEach(band => {
      state.sliders[band] = 50;
    });
    return state;
  }
  switch (action.type) {
    case SET_BAND_VALUE:
      const newSliders = { ...state.sliders, [action.band]: action.value };
      return { ...state, sliders: newSliders };
    case SET_EQ_ON:
      return { ...state, on: true };
    case SET_EQ_OFF:
      return { ...state, on: false };
    case SET_EQ_AUTO:
      return { ...state, auto: action.value };
    default:
      return state;
  }
};

const media = (state, action) => {
  if (!state) {
    return {
      timeMode: "ELAPSED",
      timeElapsed: 0,
      length: null, // Consider renaming to "duration"
      kbps: null,
      khz: null,
      // The winamp ini file declares the default volume as "200".
      // The UI seems to show a default volume near 78, which would
      // math with the default value being 200 out of 255.
      volume: Math.round(200 / 255 * 100),
      balance: 0,
      channels: null,
      shuffle: false,
      repeat: false,
      // TODO: Enforce possible values
      status: "STOPPED"
    };
  }
  switch (action.type) {
    // TODO: Make these constants
    case "PLAY":
    case "IS_PLAYING":
      return { ...state, status: "PLAYING" };
    case "PAUSE":
      return { ...state, status: "PAUSED" };
    case "STOP":
    case "IS_STOPPED":
      return { ...state, status: "STOPPED" };
    case TOGGLE_TIME_MODE:
      const newMode = state.timeMode === "REMAINING" ? "ELAPSED" : "REMAINING";
      return { ...state, timeMode: newMode };
    case UPDATE_TIME_ELAPSED:
      return { ...state, timeElapsed: action.elapsed };
    case ADD_TRACK_FROM_URL:
      return {
        ...state,
        timeElapsed: 0,
        length: null,
        kbps: null,
        khz: null,
        channels: null
      };
    case SET_MEDIA:
      return {
        ...state,
        length: action.length,
        kbps: action.kbps,
        khz: action.khz,
        channels: action.channels
      };
    case SET_VOLUME:
      return { ...state, volume: action.volume };
    case SET_BALANCE:
      return { ...state, balance: action.balance };
    case TOGGLE_REPEAT:
      return { ...state, repeat: !state.repeat };
    case TOGGLE_SHUFFLE:
      return { ...state, shuffle: !state.shuffle };
    default:
      return state;
  }
};

const reducer = combineReducers({
  userInput,
  windows,
  display,
  settings,
  equalizer,
  playlist,
  media
});

export default reducer;
<|endoftext|>


<commit_before>
var express = require('express');
var app = express();
var port = 1337;
var cameras = require('./cameras.json');
var cameraManager = require('./IPCameraManager')(cameras);

var compression = require('compression');
app.use(compression({ filter : () => {true} }));

var cookieParser = require('cookie-parser');
app.use(cookieParser());

const zlib = require('zlib');

const gzip = zlib.createGzip();

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

var Mustache = require('mustache');
var fs = require('fs');

process.on('uncaughtException', function (err) {
    console.log('uncaught error ',err);
});

app.get('/', function (req, res) {

    var query = req.query;
    if(query && query.username && query.password){
        res.cookie('username', query.username);
        res.cookie('password', query.password);
    }

    console.log('got root page!');
    var template;
    var indexPage;

        template = fs.readFileSync('./public/cameras.mustache', 'utf8');
        indexPage = Mustache.render(template, {
            cameras : cameras
        });

        res.send(indexPage);

});

app.get('/single', function (req, res) {
    console.log('got camera page!');
    var template = fs.readFileSync('./public/camera.mustache', 'utf8');
    cameraManager.getCamera(req.query, (err, camera) => {
        //console.log('err', err, 'camera', camera);
        var indexPage = Mustache.render(template, {
            camera : camera
        });

        res.send(indexPage);
    });
});

//this may be the shittiest auth ever, but its only temporary
function auth(req, next, unauth){
    //req.socket.setTimeout(2147483647);

    if(config.users[req.cookies.username] && config.users[req.cookies.username].password === req.cookies.password) {
        next();
    }
    else {
        unauth({ message : 'unauthorized'});
    }
}

app.get('/camera', function (req, res) {
    auth(req,function() {
        console.log('params', req.query);
        cameraManager.getCamera(req.query, (err, camera) => {
            if (err) {
                return res.json({
                    code: 'Nope',
                    message: err
                });
            }

            process.nextTick(() => {
                //res.setHeader('connection', 'keep-alive');
                var cameraStream = cameraManager.proxyVideo(camera);
                cameraStream.on('error', () => {
                    //console.log('err', err);
                    //res.json({
                    //    err: err
                    //});
                });
                res.on('close', function(){
                   console.log('switched cameras?');
                });
                res.setHeader('Content-Encoding','gzip');

                cameraStream.pipe(gzip).pipe(res);//.pipe(res);

            });
        });
    },res.json);
});

app.get('/ptz', function(req, res){

    cameraManager.getCamera(req.query, (err, camera) => {
        //console.log('err', err, 'camera', camera);

        cameraManager.ptz(camera, req.query.action);

        res.send(null);
    });

});

app.get('/snapshot', function (req, res) {
    auth(req,function() {
        console.log('params', req.query);
        cameraManager.getCamera(req.query, (err, camera) => {
            if (err) {
                return res.json({
                    code: 'Nope',
                    message: err
                });
            }

            process.nextTick(() => {
                res.setHeader('connection', 'keep-alive');
                var cameraStream = cameraManager.proxySnapshot(camera);
                cameraStream.on('error', (err) => {
                    res.json({
                        err: err
                    });
                });
                cameraStream.pipe(res);//.pipe(res);
            });
        });
    },res.json);
});

app.listen(port, function () {
    console.log(`Example app listening on port ${port}!`);
});
<commit_msg>nvm you can't gzip it like that<commit_after>
var express = require('express');
var app = express();
var port = 1337;
var cameras = require('./cameras.json');
var cameraManager = require('./IPCameraManager')(cameras);

var compression = require('compression');
app.use(compression({ filter : () => {true} }));

var cookieParser = require('cookie-parser');
app.use(cookieParser());

//const zlib = require('zlib');
//
//const gzip = zlib.createGzip();

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

var Mustache = require('mustache');
var fs = require('fs');

process.on('uncaughtException', function (err) {
    console.log('uncaught error ',err);
});

app.get('/', function (req, res) {

    var query = req.query;
    if(query && query.username && query.password){
        res.cookie('username', query.username);
        res.cookie('password', query.password);
    }

    console.log('got root page!');
    var template;
    var indexPage;

        template = fs.readFileSync('./public/cameras.mustache', 'utf8');
        indexPage = Mustache.render(template, {
            cameras : cameras
        });

        res.send(indexPage);

});

app.get('/single', function (req, res) {
    console.log('got camera page!');
    var template = fs.readFileSync('./public/camera.mustache', 'utf8');
    cameraManager.getCamera(req.query, (err, camera) => {
        //console.log('err', err, 'camera', camera);
        var indexPage = Mustache.render(template, {
            camera : camera
        });

        res.send(indexPage);
    });
});

//this may be the shittiest auth ever, but its only temporary
function auth(req, next, unauth){
    //req.socket.setTimeout(2147483647);

    if(config.users[req.cookies.username] && config.users[req.cookies.username].password === req.cookies.password) {
        next();
    }
    else {
        unauth({ message : 'unauthorized'});
    }
}

app.get('/camera', function (req, res) {
    auth(req,function() {
        console.log('params', req.query);
        cameraManager.getCamera(req.query, (err, camera) => {
            if (err) {
                return res.json({
                    code: 'Nope',
                    message: err
                });
            }

            process.nextTick(() => {
                //res.setHeader('connection', 'keep-alive');
                var cameraStream = cameraManager.proxyVideo(camera);
                cameraStream.on('error', () => {
                    //console.log('err', err);
                    //res.json({
                    //    err: err
                    //});
                });
                res.on('close', function(){
                   console.log('switched cameras?');
                });
                //res.setHeader('Content-Encoding','gzip');

                cameraStream.pipe(res);//.pipe(res);

            });
        });
    },res.json);
});

app.get('/ptz', function(req, res){

    cameraManager.getCamera(req.query, (err, camera) => {
        //console.log('err', err, 'camera', camera);

        cameraManager.ptz(camera, req.query.action);

        res.send(null);
    });

});

app.get('/snapshot', function (req, res) {
    auth(req,function() {
        console.log('params', req.query);
        cameraManager.getCamera(req.query, (err, camera) => {
            if (err) {
                return res.json({
                    code: 'Nope',
                    message: err
                });
            }

            process.nextTick(() => {
                res.setHeader('connection', 'keep-alive');
                var cameraStream = cameraManager.proxySnapshot(camera);
                cameraStream.on('error', (err) => {
                    res.json({
                        err: err
                    });
                });
                cameraStream.pipe(res);//.pipe(res);
            });
        });
    },res.json);
});

app.listen(port, function () {
    console.log(`Example app listening on port ${port}!`);
});
<|endoftext|>


<commit_before>$(document).ready(function() {
	$('.tooltip').tooltipster({
		contentAsHTML : true,
		maxWidth: 700
	});
	$("#jquery-ui-dialog").dialog({
		buttons : [{text:"OK",click:function(){$(this).dialog("close")}}],
		autoOpen: false,
		maxWidth:800,
		width:800,
		modal: true,
		position: {my:"center",at : "top", of: window}
	});
	$("#input-tabs").tabs().removeClass("ui-widget ui-widget-content");
	loadExample();
	//$("#rdf").rdf();
	fileSelected();
	if (debug) {
		console.log("DEBUG!!!");
		$("#input-area").val("Berlin is the capital of Germany in the European Union.\n\nThere is another line of text here.");
		//$("#input-informat").val("text/plain");
		fwm.addEService("e-entity").doEnrichment();
		/*fwm.addEService("e-translation");
		$("#target-lang-2").val("nl")*/
	}
});

var debug = false;
var fwm = {

	eServices : [],
	idCounter : 0,
	fremeApi : "http://api-dev.freme-project.eu/current",

	addEService : function(type) {

		var newEService = null;

		if (type == "e-entity") {
			newEService = Object.create(eEntity);
		}
		else if (type == "e-link") {
			newEService = Object.create(eLink);
		} else if (type == "e-translation") {
			newEService = Object.create(eTranslation);
		} else if (type == "e-terminology") {
			newEService = Object.create(eTerminology);
		}

		$.extend(newEService, eService);
		newEService.createId();

		newEService.createHtml();
		this.eServices.push({type: type, service: newEService});

		return newEService;
	},

	removeEService: function(id) {
		this.eServices[parseInt(id)]={type : "deleted", service: null};
		$("#step"+id).remove();
	}

};

var inputArea = {

	getInput : function() {

		var tab=$("#input-tabs").tabs("option","active");
		return {
			informat : $("#input-informat").val(),
			input :  tab==0 ? $("#input-area").val() : inputArea.uploadedText
		};
	}
};

var eService = {

	// id to identify this eService
	id : 0,

	// initialize unique id
	createId : function() {

		if (typeof eService.idCounter == "undefined") {
			eService.idCounter = 0;
		}

		this.id = eService.idCounter++;
	},

	// stores the nif of the enrichment when enrichment has been performed. NIF
	// is stored as javascript JSON object
	nif : null,

	// load assets/step.html and assets/e-entity.html and insert the variables
	loadStep : function(url, data) {

		var stepHtml = "";
		jQuery.ajax({
			url : "assets/html/step.html",
			success : function(result) {
				stepHtml = result
			},
			async : false
		});

		var entityHtml = "";

		jQuery.ajax({
			url : url,
			success : function(result) {
				entityHtml = result;

			},
			async : false
		});

		var html = stepHtml.replace(/\$controls\$/g, entityHtml);

		$.each(data, function(key, value) {
			var regex = new RegExp(key, "g");
			html = html.replace(regex, value);
		});
		$("#enrichment-modules").append(html);

	},

	// retrieve input - either from input area or from previous step
	getInput : function() {
		if (this.id==0) {
			return inputArea.getInput();
		}
		var i=0;
		while(fwm.eServices[this.id-1-i].type=="deleted"){
			i+=1;
			if (this.id-i==0) {
				return inputArea.getInput();
			}
		}
		return { informat : "application/rdf+xml", input: fwm.eServices[this.id-1-i].nif}
	}
};

var re =  function(name){
	return new RegExp("http://.*#"+name);
};

var xmlToString = function(xmlData) {
	//https://stackoverflow.com/questions/6507293/convert-xml-to-string-with-jquery#6507766
	var xmlString;
	//IE
	if (window.ActiveXObject){
		xmlString = xmlData.xml;
	}
	// code for Mozilla, Firefox, Opera, etc.
	else{
		xmlString = (new XMLSerializer()).serializeToString(xmlData);
	}
	return xmlString;
};

/*var stringToXml = function(str) {
	var xmlFields = $(str);
	return xmlFields[0].outerHTML;
}*/

function stringToXml(oString) {
	//code for IE
	if (window.ActiveXObject) {
		var oXML = new ActiveXObject("Microsoft.XMLDOM"); oXML.loadXML(oString);
		return oXML;
	}
	// code for Chrome, Safari, Firefox, Opera, etc.
	else {
		return (new DOMParser()).parseFromString(oString, "text/xml");
	}
}
var responseToDialog = function(data) {
	exceptionToDialog(data.responseText)
};
var exceptionToDialog = function(data){
	if (typeof(data)=="object") {
		data= JSON.stringify(data);
	}

	$("#jquery-ui-dialog").html(data.replace(/\\\"/g,"''").replace(/\"/g," ").replace(/{/g,"").replace(/}/g,"").replace(/,/g,"
"))
	.dialog("open");
};

var stringToDialog = function(str) {
	$("#jquery-ui-dialog").html("
"+escapeHtml(str)+"
")
		.dialog("open");
};

var processRdfResponse = function(data, id, rdf) {
	var service = fwm.eServices[id];
	service.nif = xmlToString(data);
	$("#nif-"+id).html("
"+escapeHtml(service.nif)+"
");
	service.annotations=createAnnotations(rdf);
	var text = matchAnnotationsToString(service.annotations);
	$("#output-"+id).html(text.replace(/\n/g,"
"));
	$(".tooltip").tooltipster({contentAsHTML:true,multiple:true,maxWidth:700});
};

var processXmlResponse = function(data, id) {
	return processRdfResponse(data,id,xmlToRdf(data))
};

var toggleNif = function(id) {
	var nifdiv = $("#nif-"+id);
	var togglediv = $("#toggle-"+id);
	if (togglediv.text()=="[Show NIF]") {
		nifdiv.show();
		togglediv.text("[Hide NIF]")
	} else if (togglediv.text()=="[Hide NIF]") {
        nifdiv.hide();
		togglediv.text("[Show NIF]")
	}
};

var entityMap = {
	"&": "&",
	"<": "<",
	">": ">",
	'"': '"',
	"'": ''',
	"/": '/'
};

function escapeHtml(string) {
	return String(string).replace(/[&<>"'\/]/g, function (s) {
		return entityMap[s];
	});
}

function jsonToTable(json) {
	/*
	 * Used in Postprocessing / Filter
	 * It felt more natural to use json instead of csv in javascript
	 * Creates HTML Table out of Table-like JSON
	 */
	var li="

";
	var cols=json.head.vars.length;
	var val;
	for (var i=0; i<cols;i++) {
		li+=""+json.head.vars[i]+"	"
	}
	li+="
";

	for(i=0; i<json.results.bindings.length;i++) {
		li+="
";
		for (var k=0; k<cols;k++) {
			val = json.results.bindings[i][json.head.vars[k]];
			if (val) {
				li += "" + val.value + "	";

			}
		}
		li+="
";
	}

	return li+"

";
}

var fileSelected = function() {
	/* Based on http://www.matlus.com/html5-file-upload-with-progress/
	 *
	 *
	 */
	var file = document.getElementById('input-upload').files[0];

	if (file) {
		var fileSize = 0;
		if (file.size > 1024 * 1024) {
			fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
		} else {
			fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';
		}
		document.getElementById('input-fileName').innerHTML = 'Name: ' + file.name;
		document.getElementById('input-fileSize').innerHTML = 'Size: ' + fileSize;
//		document.getElementById('input-fileType').innerHTML = 'Type: ' + file.type;

		var f = new FileReader();
		f.onload = function(abc) {
			inputArea.uploadedText = f.result;
		};
		f.readAsText(file);
	}
};<commit_msg>update api url to https<commit_after>$(document).ready(function() {
	$('.tooltip').tooltipster({
		contentAsHTML : true,
		maxWidth: 700
	});
	$("#jquery-ui-dialog").dialog({
		buttons : [{text:"OK",click:function(){$(this).dialog("close")}}],
		autoOpen: false,
		maxWidth:800,
		width:800,
		modal: true,
		position: {my:"center",at : "top", of: window}
	});
	$("#input-tabs").tabs().removeClass("ui-widget ui-widget-content");
	loadExample();
	//$("#rdf").rdf();
	fileSelected();
	if (debug) {
		console.log("DEBUG!!!");
		$("#input-area").val("Berlin is the capital of Germany in the European Union.\n\nThere is another line of text here.");
		//$("#input-informat").val("text/plain");
		fwm.addEService("e-entity").doEnrichment();
		/*fwm.addEService("e-translation");
		$("#target-lang-2").val("nl")*/
	}
});

var debug = false;
var fwm = {

	eServices : [],
	idCounter : 0,
	fremeApi : "https://api.freme-project.eu/current",

	addEService : function(type) {

		var newEService = null;

		if (type == "e-entity") {
			newEService = Object.create(eEntity);
		}
		else if (type == "e-link") {
			newEService = Object.create(eLink);
		} else if (type == "e-translation") {
			newEService = Object.create(eTranslation);
		} else if (type == "e-terminology") {
			newEService = Object.create(eTerminology);
		}

		$.extend(newEService, eService);
		newEService.createId();

		newEService.createHtml();
		this.eServices.push({type: type, service: newEService});

		return newEService;
	},

	removeEService: function(id) {
		this.eServices[parseInt(id)]={type : "deleted", service: null};
		$("#step"+id).remove();
	}

};

var inputArea = {

	getInput : function() {

		var tab=$("#input-tabs").tabs("option","active");
		return {
			informat : $("#input-informat").val(),
			input :  tab==0 ? $("#input-area").val() : inputArea.uploadedText
		};
	}
};

var eService = {

	// id to identify this eService
	id : 0,

	// initialize unique id
	createId : function() {

		if (typeof eService.idCounter == "undefined") {
			eService.idCounter = 0;
		}

		this.id = eService.idCounter++;
	},

	// stores the nif of the enrichment when enrichment has been performed. NIF
	// is stored as javascript JSON object
	nif : null,

	// load assets/step.html and assets/e-entity.html and insert the variables
	loadStep : function(url, data) {

		var stepHtml = "";
		jQuery.ajax({
			url : "assets/html/step.html",
			success : function(result) {
				stepHtml = result
			},
			async : false
		});

		var entityHtml = "";

		jQuery.ajax({
			url : url,
			success : function(result) {
				entityHtml = result;

			},
			async : false
		});

		var html = stepHtml.replace(/\$controls\$/g, entityHtml);

		$.each(data, function(key, value) {
			var regex = new RegExp(key, "g");
			html = html.replace(regex, value);
		});
		$("#enrichment-modules").append(html);

	},

	// retrieve input - either from input area or from previous step
	getInput : function() {
		if (this.id==0) {
			return inputArea.getInput();
		}
		var i=0;
		while(fwm.eServices[this.id-1-i].type=="deleted"){
			i+=1;
			if (this.id-i==0) {
				return inputArea.getInput();
			}
		}
		return { informat : "application/rdf+xml", input: fwm.eServices[this.id-1-i].nif}
	}
};

var re =  function(name){
	return new RegExp("http://.*#"+name);
};

var xmlToString = function(xmlData) {
	//https://stackoverflow.com/questions/6507293/convert-xml-to-string-with-jquery#6507766
	var xmlString;
	//IE
	if (window.ActiveXObject){
		xmlString = xmlData.xml;
	}
	// code for Mozilla, Firefox, Opera, etc.
	else{
		xmlString = (new XMLSerializer()).serializeToString(xmlData);
	}
	return xmlString;
};

/*var stringToXml = function(str) {
	var xmlFields = $(str);
	return xmlFields[0].outerHTML;
}*/

function stringToXml(oString) {
	//code for IE
	if (window.ActiveXObject) {
		var oXML = new ActiveXObject("Microsoft.XMLDOM"); oXML.loadXML(oString);
		return oXML;
	}
	// code for Chrome, Safari, Firefox, Opera, etc.
	else {
		return (new DOMParser()).parseFromString(oString, "text/xml");
	}
}
var responseToDialog = function(data) {
	exceptionToDialog(data.responseText)
};
var exceptionToDialog = function(data){
	if (typeof(data)=="object") {
		data= JSON.stringify(data);
	}

	$("#jquery-ui-dialog").html(data.replace(/\\\"/g,"''").replace(/\"/g," ").replace(/{/g,"").replace(/}/g,"").replace(/,/g,"
"))
	.dialog("open");
};

var stringToDialog = function(str) {
	$("#jquery-ui-dialog").html("
"+escapeHtml(str)+"
")
		.dialog("open");
};

var processRdfResponse = function(data, id, rdf) {
	var service = fwm.eServices[id];
	service.nif = xmlToString(data);
	$("#nif-"+id).html("
"+escapeHtml(service.nif)+"
");
	service.annotations=createAnnotations(rdf);
	var text = matchAnnotationsToString(service.annotations);
	$("#output-"+id).html(text.replace(/\n/g,"
"));
	$(".tooltip").tooltipster({contentAsHTML:true,multiple:true,maxWidth:700});
};

var processXmlResponse = function(data, id) {
	return processRdfResponse(data,id,xmlToRdf(data))
};

var toggleNif = function(id) {
	var nifdiv = $("#nif-"+id);
	var togglediv = $("#toggle-"+id);
	if (togglediv.text()=="[Show NIF]") {
		nifdiv.show();
		togglediv.text("[Hide NIF]")
	} else if (togglediv.text()=="[Hide NIF]") {
        nifdiv.hide();
		togglediv.text("[Show NIF]")
	}
};

var entityMap = {
	"&": "&",
	"<": "<",
	">": ">",
	'"': '"',
	"'": ''',
	"/": '/'
};

function escapeHtml(string) {
	return String(string).replace(/[&<>"'\/]/g, function (s) {
		return entityMap[s];
	});
}

function jsonToTable(json) {
	/*
	 * Used in Postprocessing / Filter
	 * It felt more natural to use json instead of csv in javascript
	 * Creates HTML Table out of Table-like JSON
	 */
	var li="

";
	var cols=json.head.vars.length;
	var val;
	for (var i=0; i<cols;i++) {
		li+=""+json.head.vars[i]+"	"
	}
	li+="
";

	for(i=0; i<json.results.bindings.length;i++) {
		li+="
";
		for (var k=0; k<cols;k++) {
			val = json.results.bindings[i][json.head.vars[k]];
			if (val) {
				li += "" + val.value + "	";

			}
		}
		li+="
";
	}

	return li+"

";
}

var fileSelected = function() {
	/* Based on http://www.matlus.com/html5-file-upload-with-progress/
	 *
	 *
	 */
	var file = document.getElementById('input-upload').files[0];

	if (file) {
		var fileSize = 0;
		if (file.size > 1024 * 1024) {
			fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
		} else {
			fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';
		}
		document.getElementById('input-fileName').innerHTML = 'Name: ' + file.name;
		document.getElementById('input-fileSize').innerHTML = 'Size: ' + fileSize;
//		document.getElementById('input-fileType').innerHTML = 'Type: ' + file.type;

		var f = new FileReader();
		f.onload = function(abc) {
			inputArea.uploadedText = f.result;
		};
		f.readAsText(file);
	}
};<|endoftext|>


<commit_before>'use strict';

const helper = require('../helper');

/**
 * Default arguments for the `--ignore` option.
 * @type {string[]}
 */
const DEFAULT_IGNORE = ['node_modules'];

/**
 * Schema for the `upload-sourcemaps` command.
 * @type {OptionsSchema}
 */
const SOURCEMAPS_SCHEMA = require('./options/uploadSourcemaps');

/**
 * Manages releases and release artifacts on Sentry.
 * @namespace SentryReleases
 */
class Releases {
  /**
   * Creates a new `Releases` instance.
   *
   * @param {Object} [options] More options to pass to the CLI
   */
  constructor(options) {
    this.options = options || {};
  }

  /**
   * Registers a new release with sentry.
   *
   * The given release name should be unique and deterministic. It can later be used to
   * upload artifacts, such as source maps.
   *
   * @param {string} release Unique name of the new release.
   * @returns {Promise} A promise that resolves when the release has been created.
   * @memberof SentryReleases
   */
  new(release) {
    return helper.execute(['releases', 'new', release], null, this.options.silent);
  }

  /**
   * Marks this release as complete. This should be called once all artifacts has been
   * uploaded.
   *
   * @param {string} release Unique name of the release.
   * @returns {Promise} A promise that resolves when the release has been finalized.
   * @memberof SentryReleases
   */
  finalize(release) {
    return helper.execute(['releases', 'finalize', release], null, this.options.silent);
  }

  /**
   * Creates a unique, deterministic version identifier based on the project type and
   * source files. This identifier can be used as release name.
   *
   * @returns {Promise.<string>} A promise that resolves to the version string.
   * @memberof SentryReleases
   */
  proposeVersion() {
    return helper
      .execute(['releases', 'propose-version'], null, this.options.silent)
      .then(version => version && version.trim());
  }

  /**
   * Scans the given include folders for JavaScript source maps and uploads them to the
   * specified release for processing.
   *
   * The options require an `include` array, which is a list of directories to scan.
   * Additionally, it supports to ignore certain files, validate and preprocess source
   * maps and define a URL prefix.
   *
   * @example
   * await cli.releases.uploadSourceMaps(cli.releases.proposeVersion(), {
   *   // required options:
   *   include: ['build'],
   *
   *   // default options:
   *   ignore: ['node_modules'],  // globs for files to ignore
   *   ignoreFile: null,          // path to a file with ignore rules
   *   rewrite: false,            // preprocess sourcemaps before uploading
   *   sourceMapReference: true,  // add a source map reference to source files
   *   stripPrefix: [],           // remove certain prefices from filenames
   *   stripCommonPrefix: false,  // guess common prefices to remove from filenames
   *   validate: false,           // validate source maps and cancel the upload on error
   *   urlPrefix: '',             // add a prefix source map urls after stripping them
   *   urlSuffix: '',             // add a suffix source map urls after stripping them
   *   ext: ['js', 'map', 'jsbundle', 'bundle'],  // override file extensions to scan for
   * });
   *
   * @param {string} release Unique name of the release.
   * @param {object} options Options to configure the source map upload.
   * @returns {Promise} A promise that resolves when the upload has completed successfully.
   * @memberof SentryReleases
   */
  uploadSourceMaps(release, options) {
    if (!options || !options.include) {
      throw new Error('options.include must be a vaild path(s)');
    }

    const uploads = options.include.map(sourcemapPath => {
      const newOptions = Object.assign({}, options);
      if (!newOptions.ignoreFile && !newOptions.ignore) {
        newOptions.ignore = DEFAULT_IGNORE;
      }

      const args = ['releases', 'files', release, 'upload-sourcemaps', sourcemapPath];
      return helper.execute(
        helper.prepareCommand(args, SOURCEMAPS_SCHEMA, newOptions),
        true,
        this.options.silent
      );
    });

    return Promise.all(uploads);
  }
}

module.exports = Releases;
<commit_msg>feat(js): Allow setting commits on a release (#580)<commit_after>'use strict';

const helper = require('../helper');

/**
 * Default arguments for the `--ignore` option.
 * @type {string[]}
 */
const DEFAULT_IGNORE = ['node_modules'];

/**
 * Schema for the `upload-sourcemaps` command.
 * @type {OptionsSchema}
 */
const SOURCEMAPS_SCHEMA = require('./options/uploadSourcemaps');

/**
 * Manages releases and release artifacts on Sentry.
 * @namespace SentryReleases
 */
class Releases {
  /**
   * Creates a new `Releases` instance.
   *
   * @param {Object} [options] More options to pass to the CLI
   */
  constructor(options) {
    this.options = options || {};
  }

  /**
   * Registers a new release with sentry.
   *
   * The given release name should be unique and deterministic. It can later be used to
   * upload artifacts, such as source maps.
   *
   * @param {string} release Unique name of the new release.
   * @returns {Promise} A promise that resolves when the release has been created.
   * @memberof SentryReleases
   */
  new(release) {
    return helper.execute(['releases', 'new', release], null, this.options.silent);
  }

  /**
   * Specifies the set of commits covered in this release.
   *
   * @param {string} release Unique name of the release
   * @param {object} options A set of options to configure the commits to include
   * @param {string} options.repo The full repo name as defined in Sentry
   * @param {boolean} options.auto Automatically choose the associated commit (uses
   * the current commit). Overrides other options.
   * @param {string} options.commit The current (last) commit in the release.
   * @param {string} options.previousCommit The commit before the beginning of this
   * release (in other words, the last commit of the previous release). If omitted,
   * this will default to the last commit of the previous release in Sentry. If there
   * was no previous release, the last 10 commits will be used.
   * @returns {Promise} A promise that resolves when the commits have been associated
   * @memberof SentryReleases
   */
  setCommits(release, options) {
    if (!options || !options.repo || (!options.auto && !options.commit)) {
      throw new Error(
        'options.repo, and either options.commit or options.auto must be specified'
      );
    }

    let commitFlags = [];

    if (options.auto) {
      commitFlags = ['--auto'];
    } else if (options.previousCommit) {
      commitFlags = [
        '--commit',
        `${options.repo}@${options.previousCommit}..${options.commit}`,
      ];
    } else {
      commitFlags = ['--commit', `${options.repo}@${options.commit}`];
    }

    return helper.execute(['releases', 'set-commits', release].concat(commitFlags));
  },

  /**
   * Marks this release as complete. This should be called once all artifacts has been
   * uploaded.
   *
   * @param {string} release Unique name of the release.
   * @returns {Promise} A promise that resolves when the release has been finalized.
   * @memberof SentryReleases
   */
  finalize(release) {
    return helper.execute(['releases', 'finalize', release], null, this.options.silent);
  }

  /**
   * Creates a unique, deterministic version identifier based on the project type and
   * source files. This identifier can be used as release name.
   *
   * @returns {Promise.<string>} A promise that resolves to the version string.
   * @memberof SentryReleases
   */
  proposeVersion() {
    return helper
      .execute(['releases', 'propose-version'], null, this.options.silent)
      .then(version => version && version.trim());
  }

  /**
   * Scans the given include folders for JavaScript source maps and uploads them to the
   * specified release for processing.
   *
   * The options require an `include` array, which is a list of directories to scan.
   * Additionally, it supports to ignore certain files, validate and preprocess source
   * maps and define a URL prefix.
   *
   * @example
   * await cli.releases.uploadSourceMaps(cli.releases.proposeVersion(), {
   *   // required options:
   *   include: ['build'],
   *
   *   // default options:
   *   ignore: ['node_modules'],  // globs for files to ignore
   *   ignoreFile: null,          // path to a file with ignore rules
   *   rewrite: false,            // preprocess sourcemaps before uploading
   *   sourceMapReference: true,  // add a source map reference to source files
   *   stripPrefix: [],           // remove certain prefices from filenames
   *   stripCommonPrefix: false,  // guess common prefices to remove from filenames
   *   validate: false,           // validate source maps and cancel the upload on error
   *   urlPrefix: '',             // add a prefix source map urls after stripping them
   *   urlSuffix: '',             // add a suffix source map urls after stripping them
   *   ext: ['js', 'map', 'jsbundle', 'bundle'],  // override file extensions to scan for
   * });
   *
   * @param {string} release Unique name of the release.
   * @param {object} options Options to configure the source map upload.
   * @returns {Promise} A promise that resolves when the upload has completed successfully.
   * @memberof SentryReleases
   */
  uploadSourceMaps(release, options) {
    if (!options || !options.include) {
      throw new Error('options.include must be a vaild path(s)');
    }

    const uploads = options.include.map(sourcemapPath => {
      const newOptions = Object.assign({}, options);
      if (!newOptions.ignoreFile && !newOptions.ignore) {
        newOptions.ignore = DEFAULT_IGNORE;
      }

      const args = ['releases', 'files', release, 'upload-sourcemaps', sourcemapPath];
      return helper.execute(
        helper.prepareCommand(args, SOURCEMAPS_SCHEMA, newOptions),
        true,
        this.options.silent
      );
    });

    return Promise.all(uploads);
  }
}

module.exports = Releases;
<|endoftext|>