<commit_before>import defaults from '../defaults'

/**
 * Validate primary options of stylelint plugin config.
 *
 * @param {string|string[]} actual - The actual config to validate.
 *
 * @returns {boolean}
 */
function validProperties(actual) {
  return typeof actual === 'string' ||
    (Array.isArray(actual) && actual.every(item => typeof item === 'string'))
}

/**
 * Validate optional secondary options of stylelint plugin config.
 *
 * @param {Object} actual - The actual config to validate.
 * @param {boolean} [actual.ignoreVariables=true] - Whether or not to lint variables.
 * @param {boolean} [actual.ignoreFunctions=true] - Whether or not to lint functions.
 * @param {string|Array|Object} [actual.ignoreKeywords=null] - A keywords config.
 *
 * @returns {boolean}
 */
function validOptions(actual) {
  if (typeof actual !== 'object') return false

  const allowedKeys = Object.keys(defaults)
  if (!Object.keys(actual).every(key => allowedKeys.indexOf(key) > -1)) return false

  if ('ignoreVariables' in actual &&
    typeof actual.ignoreVariables !== 'boolean' &&
    actual.ignoreVariables !== null) return false

  if ('ignoreFunctions' in actual &&
    typeof actual.ignoreFunctions !== 'boolean' &&
    actual.ignoreFunctions !== null) return false

  if ('ignoreKeywords' in actual &&
    !validProperties(actual.ignoreKeywords) &&
    !validHash(actual.ignoreKeywords)) return false

  return true
}

/**
 * Validate optional hash keyword config.
 *
 * @param {string|Array} actual - A keyword config.
 *
 * @returns {boolean}
 */
function validHash(actual) {
  if (typeof actual !== 'object') return false

  return Object.keys(actual).every(key => validProperties(actual[key]))
}

/**
 * Build expected message for stylelint report.
 *
 * @param {Array} types - Either `variable`, `function` and/or `keyword`.
 * @param {string} value - The CSS declaration's value.
 * @param {string} property - The CSS declaration's property.
 * @returns {string}
 */
function expected(types, value, property) {
  if (Array.isArray(types)) {
    const typesLast = types.pop()

    types = types.length ? `${types.join(', ')} or ${typesLast}` : typesLast
  }

  return `Expected ${types} for "${value}" of "${property}"`
}

/**
 * Get configured types for stylelint report message.
 *
 * @param {Object} config - The secondary stylelint-plugin config.
 * @param {string} property - The specific CSS declaration's property of the current iteration.
 * @returns {Array}
 */
function getTypes(config, property) {
  const { ignoreVariables, ignoreFunctions, ignoreKeywords } = config
  const types = []

  if (ignoreVariables) {
    types.push('variable')
  }

  if (ignoreFunctions) {
    types.push('function')
  }

  if (ignoreKeywords && getIgnoredKeywords(ignoreKeywords, property)) {
    types.push('keyword')
  }

  return types
}

/**
 * Get the correct ignored keywords for an specific CSS declaration's property
 * out of a complex ignoreKeywords config hash or array.
 *
 * @param {Object|Array|string} ignoreKeywords - The keyword/-s to ignore.
 * @param {Array} property - The specific CSS declaration's property of the current iteration.
 * @returns {Array}
 */
function getIgnoredKeywords(ignoreKeywords, property) {
  if (!ignoreKeywords) return null

  const keywords = ignoreKeywords[property] || ignoreKeywords[''] || ignoreKeywords

  return Array.isArray(keywords) ? keywords : [keywords]
}

export {
  validProperties,
  validOptions,
  expected,
  getTypes,
  getIgnoredKeywords,
}
<commit_msg>fixed missing hasOwnProperty check<commit_after>import defaults from '../defaults'

/**
 * Validate primary options of stylelint plugin config.
 *
 * @param {string|string[]} actual - The actual config to validate.
 *
 * @returns {boolean}
 */
function validProperties(actual) {
  return typeof actual === 'string' ||
    (Array.isArray(actual) && actual.every(item => typeof item === 'string'))
}

/**
 * Validate optional secondary options of stylelint plugin config.
 *
 * @param {Object} actual - The actual config to validate.
 * @param {boolean} [actual.ignoreVariables=true] - Whether or not to lint variables.
 * @param {boolean} [actual.ignoreFunctions=true] - Whether or not to lint functions.
 * @param {string|Array|Object} [actual.ignoreKeywords=null] - A keywords config.
 *
 * @returns {boolean}
 */
function validOptions(actual) {
  if (typeof actual !== 'object') return false

  const allowedKeys = Object.keys(defaults)
  if (!Object.keys(actual).every(key => allowedKeys.indexOf(key) > -1)) return false

  if ('ignoreVariables' in actual &&
    typeof actual.ignoreVariables !== 'boolean' &&
    actual.ignoreVariables !== null) return false

  if ('ignoreFunctions' in actual &&
    typeof actual.ignoreFunctions !== 'boolean' &&
    actual.ignoreFunctions !== null) return false

  if ('ignoreKeywords' in actual &&
    !validProperties(actual.ignoreKeywords) &&
    !validHash(actual.ignoreKeywords)) return false

  return true
}

/**
 * Validate optional hash keyword config.
 *
 * @param {string|Array} actual - A keyword config.
 *
 * @returns {boolean}
 */
function validHash(actual) {
  if (typeof actual !== 'object') return false

  return Object.keys(actual).every(key => validProperties(actual[key]))
}

/**
 * Build expected message for stylelint report.
 *
 * @param {Array} types - Either `variable`, `function` and/or `keyword`.
 * @param {string} value - The CSS declaration's value.
 * @param {string} property - The CSS declaration's property.
 * @returns {string}
 */
function expected(types, value, property) {
  if (Array.isArray(types)) {
    const typesLast = types.pop()

    types = types.length ? `${types.join(', ')} or ${typesLast}` : typesLast
  }

  return `Expected ${types} for "${value}" of "${property}"`
}

/**
 * Get configured types for stylelint report message.
 *
 * @param {Object} config - The secondary stylelint-plugin config.
 * @param {string} property - The specific CSS declaration's property of the current iteration.
 * @returns {Array}
 */
function getTypes(config, property) {
  const { ignoreVariables, ignoreFunctions, ignoreKeywords } = config
  const types = []

  if (ignoreVariables) {
    types.push('variable')
  }

  if (ignoreFunctions) {
    types.push('function')
  }

  if (ignoreKeywords && getIgnoredKeywords(ignoreKeywords, property)) {
    types.push('keyword')
  }

  return types
}

/**
 * Get the correct ignored keywords for an specific CSS declaration's property
 * out of a complex ignoreKeywords config hash or array.
 *
 * @param {Object|Array|string} ignoreKeywords - The keyword/-s to ignore.
 * @param {Array} property - The specific CSS declaration's property of the current iteration.
 * @returns {Array}
 */
function getIgnoredKeywords(ignoreKeywords, property) {
  if (!ignoreKeywords) return null

  let keywords = ignoreKeywords

  if ({}.hasOwnProperty.call(keywords, property)) {
    keywords = keywords[property]
  } else if ({}.hasOwnProperty.call(keywords, '')) {
    keywords = keywords['']
  }

  return Array.isArray(keywords) ? keywords : [keywords]
}

export {
  validProperties,
  validOptions,
  expected,
  getTypes,
  getIgnoredKeywords,
}
<|endoftext|>


<commit_before>/**
 * Cross-Origin Resource Sharing (CORS) Settings
 * (sails.config.cors)
 *
 * CORS is like a more modern version of JSONP-- it allows your server/API
 * to successfully respond to requests from client-side JavaScript code
 * running on some other domain (e.g. google.com)
 * Unlike JSONP, it works with POST, PUT, and DELETE requests
 *
 * For more information on CORS, check out:
 * http://en.wikipedia.org/wiki/Cross-origin_resource_sharing
 *
 * Note that any of these settings (besides 'allRoutes') can be changed on a per-route basis
 * by adding a "cors" object to the route configuration:
 *
 * '/get foo': {
 *   controller: 'foo',
 *   action: 'bar',
 *   cors: {
 *     origin: 'http://foobar.com,https://owlhoot.com'
 *   }
 *  }
 *
 *  For more information on this configuration file, see:
 *  http://sailsjs.org/#!/documentation/reference/sails.config/sails.config.cors.html
 *
 */

module.exports.cors = {

  /***************************************************************************
  *                                                                          *
  * Allow CORS on all routes by default? If not, you must enable CORS on a   *
  * per-route basis by either adding a "cors" configuration object to the    *
  * route config, or setting "cors:true" in the route config to use the      *
  * default settings below.                                                  *
  *                                                                          *
  ***************************************************************************/

  allRoutes: true,

  /***************************************************************************
  *                                                                          *
  * Which domains which are allowed CORS access? This can be a               *
  * comma-delimited list of hosts (beginning with http:// or https://) or    *
  * "*" to allow all domains CORS access.                                    *
  *                                                                          *
  ***************************************************************************/

  origin: process.env.HOST_URL || process.env.LOCAL_HOST_URL,
  //origin: 'http://localhost',
  //origin: '*',

  /***************************************************************************
  *                                                                          *
  * Allow cookies to be shared for CORS requests?                            *
  *                                                                          *
  ***************************************************************************/

  credentials: true,

  /***************************************************************************
  *                                                                          *
  * Which methods should be allowed for CORS requests? This is only used in  *
  * response to preflight requests (see article linked above for more info)  *
  *                                                                          *
  ***************************************************************************/

  // methods: 'GET, POST, PUT, DELETE, OPTIONS, HEAD',
  methods: 'GET',

  /***************************************************************************
  *                                                                          *
  * Which headers should be allowed for CORS requests? This is only used in  *
  * response to preflight requests.                                          *
  *                                                                          *
  ***************************************************************************/

  headers: 'content-type'

};
<commit_msg>Updated the origin variable.<commit_after>/**
 * Cross-Origin Resource Sharing (CORS) Settings
 * (sails.config.cors)
 *
 * CORS is like a more modern version of JSONP-- it allows your server/API
 * to successfully respond to requests from client-side JavaScript code
 * running on some other domain (e.g. google.com)
 * Unlike JSONP, it works with POST, PUT, and DELETE requests
 *
 * For more information on CORS, check out:
 * http://en.wikipedia.org/wiki/Cross-origin_resource_sharing
 *
 * Note that any of these settings (besides 'allRoutes') can be changed on a per-route basis
 * by adding a "cors" object to the route configuration:
 *
 * '/get foo': {
 *   controller: 'foo',
 *   action: 'bar',
 *   cors: {
 *     origin: 'http://foobar.com,https://owlhoot.com'
 *   }
 *  }
 *
 *  For more information on this configuration file, see:
 *  http://sailsjs.org/#!/documentation/reference/sails.config/sails.config.cors.html
 *
 */

module.exports.cors = {

  /***************************************************************************
  *                                                                          *
  * Allow CORS on all routes by default? If not, you must enable CORS on a   *
  * per-route basis by either adding a "cors" configuration object to the    *
  * route config, or setting "cors:true" in the route config to use the      *
  * default settings below.                                                  *
  *                                                                          *
  ***************************************************************************/

  allRoutes: true,

  /***************************************************************************
  *                                                                          *
  * Which domains which are allowed CORS access? This can be a               *
  * comma-delimited list of hosts (beginning with http:// or https://) or    *
  * "*" to allow all domains CORS access.                                    *
  *                                                                          *
  ***************************************************************************/

  origin: process.env.HOST_URL,
  //origin: 'http://localhost',
  //origin: '*',

  /***************************************************************************
  *                                                                          *
  * Allow cookies to be shared for CORS requests?                            *
  *                                                                          *
  ***************************************************************************/

  credentials: true,

  /***************************************************************************
  *                                                                          *
  * Which methods should be allowed for CORS requests? This is only used in  *
  * response to preflight requests (see article linked above for more info)  *
  *                                                                          *
  ***************************************************************************/

  // methods: 'GET, POST, PUT, DELETE, OPTIONS, HEAD',
  methods: 'GET',

  /***************************************************************************
  *                                                                          *
  * Which headers should be allowed for CORS requests? This is only used in  *
  * response to preflight requests.                                          *
  *                                                                          *
  ***************************************************************************/

  headers: 'content-type'

};
<|endoftext|>


<commit_before>//Importera alla moduler
const path = require('path');
const express = require('express');
const exphbs = require('express-handlebars');
const bodyparser = require('body-parser');
const app = express();
const mysql = require('mysql');
const uuid = require('uuid/v1');
const session = require('client-sessions');

//Säg till appen (express) var den hittar statiska filer, så som javascript-filer och css-filer
app.use(express.static(path.join(__dirname, '/public')));

//Säg till appen vilken view engine vi använder, handlebars, och berätta i vilken mapp våra .hbs-filer
//kommer ligga (dvs handlebars-filer)
app.engine('.hbs', exphbs({
    defaultLayout: 'main',
    extname: '.hbs',
    layoutsDir: path.join(__dirname, 'views/layout'),
    partialsDir: path.join(__dirname, 'views/partials')
}));
app.set('view engine', '.hbs');
app.set('views', path.join(__dirname, 'views'));

//Säg till appen hur vi vill parsa inkommande data som skickas från en sida till en annan (via t ex formulär)
app.use(bodyparser.urlencoded({
    extended: true
}));
app.use(bodyparser.json());

app.use(session({
    cookieName: 'session',
    secret: 'secret',
    duration: 30 * 60 * 1000,
    activeDuration: 5 * 60 * 1000,
}));

//Säg till vilken port appen ska lyssna på.
app.listen(3000);

//APP REQUESTS
app.get('/', function(req, res, next){
    console.log(req.nav);
    if(req.session.username){
        res.render('index', {username: req.session.username});
    } else {
        res.render('index');
    }

});

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

    res.render('login');

});

app.post('/', function(req, res, next){
    console.log(req.body);
});

app.get('/create', function(req, res){
    if(req.session.username){
        res.render('create', {username: req.session.username});
    } else {
        res.render('create');
    }
});

app.get('/logout', function(req, res){
    req.session.reset();
    res.send('index');
})

app.post('/create', function(req, res){
    req.session.username = req.body.username;
    res.redirect('/');
});<commit_msg>Bort med console log.<commit_after>//Importera alla moduler
const path = require('path');
const express = require('express');
const exphbs = require('express-handlebars');
const bodyparser = require('body-parser');
const app = express();
const mysql = require('mysql');
const uuid = require('uuid/v1');
const session = require('client-sessions');

//Säg till appen (express) var den hittar statiska filer, så som javascript-filer och css-filer
app.use(express.static(path.join(__dirname, '/public')));

//Säg till appen vilken view engine vi använder, handlebars, och berätta i vilken mapp våra .hbs-filer
//kommer ligga (dvs handlebars-filer)
app.engine('.hbs', exphbs({
    defaultLayout: 'main',
    extname: '.hbs',
    layoutsDir: path.join(__dirname, 'views/layout'),
    partialsDir: path.join(__dirname, 'views/partials')
}));
app.set('view engine', '.hbs');
app.set('views', path.join(__dirname, 'views'));

//Säg till appen hur vi vill parsa inkommande data som skickas från en sida till en annan (via t ex formulär)
app.use(bodyparser.urlencoded({
    extended: true
}));
app.use(bodyparser.json());

app.use(session({
    cookieName: 'session',
    secret: 'secret',
    duration: 30 * 60 * 1000,
    activeDuration: 5 * 60 * 1000,
}));

//Säg till vilken port appen ska lyssna på.
app.listen(3000);

//APP REQUESTS
app.get('/', function(req, res, next){
    if(req.session.username){
        res.render('index', {username: req.session.username});
    } else {
        res.render('index');
    }

});

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

    res.render('login');

});

app.post('/', function(req, res, next){
    console.log(req.body);
});

app.get('/create', function(req, res){
    if(req.session.username){
        res.render('create', {username: req.session.username});
    } else {
        res.render('create');
    }
});

app.get('/logout', function(req, res){
    req.session.reset();
    res.send('index');
})

app.post('/create', function(req, res){
    req.session.username = req.body.username;
    res.redirect('/');
});<|endoftext|>


<commit_before>"use strict";

const Command = require('cmnd').Command;
const APIResource = require('api-res');
const chalk = require('chalk');
const inquirer = require('inquirer');

const Credentials = require('../../credentials.js');
const tabler = require('../../tabler.js');

const convertPeriodToString = {
  60: 'minute',
  3600: 'hour',
  86400: 'day',
  604800: 'week'
};

class TaskList extends Command {

  constructor() {
    super('tasks', 'list');
  }

  help() {
    return {
      description: 'Lists your scheduled tasks',
      flags: {
        j: 'Return tasks as JSON object'
      },
      vflags: {
        json: 'Return tasks as JSON object'
      }
    };
  }

  run(params, callback) {

    const host = 'api.polybit.com';
    const port = 443;

    let resource = new APIResource(host, port);

    resource.authorize(Credentials.read('ACCESS_TOKEN'));
    resource.request('/v1/scheduled_tasks').index({}, (err, response) => {

      if (err) {
        return callback(err);
      }

      if (params.flags.j || params.vflags.json) {

        return callback(null, response.data);

      }

      return callback(null,
        tabler(
          [
            'Name',
            'Service',
            'Function',
            'Frequency',
            'Period',
            'Last Invoked'
          ],
          response.data.map((scheduledTask) => {
            return {
              'Name': scheduledTask.name,
              'Service': scheduledTask.service.name,
              'Function': scheduledTask.function_name || '__main__',
              'Frequency': `${scheduledTask.frequency} time(s)`,
              'Period': `per ${convertPeriodToString[scheduledTask.period]}`,
              'Last Invoked': scheduledTask.last_invoked_at || 'never'
            };
          })
        )
      );
    });
  }
}

module.exports = TaskList;
<commit_msg>Fixed typo in help message<commit_after>"use strict";

const Command = require('cmnd').Command;
const APIResource = require('api-res');
const chalk = require('chalk');
const inquirer = require('inquirer');

const Credentials = require('../../credentials.js');
const tabler = require('../../tabler.js');

const convertPeriodToString = {
  60: 'minute',
  3600: 'hour',
  86400: 'day',
  604800: 'week'
};

class TaskList extends Command {

  constructor() {
    super('tasks', 'list');
  }

  help() {
    return {
      description: 'Lists your scheduled tasks',
      flags: {
        j: 'Returns tasks as a JSON object'
      },
      vflags: {
        json: 'Returns tasks as a JSON object'
      }
    };
  }

  run(params, callback) {

    const host = 'api.polybit.com';
    const port = 443;

    let resource = new APIResource(host, port);

    resource.authorize(Credentials.read('ACCESS_TOKEN'));
    resource.request('/v1/scheduled_tasks').index({}, (err, response) => {

      if (err) {
        return callback(err);
      }

      if (params.flags.j || params.vflags.json) {

        return callback(null, response.data);

      }

      return callback(null,
        tabler(
          [
            'Name',
            'Service',
            'Function',
            'Frequency',
            'Period',
            'Last Invoked'
          ],
          response.data.map((scheduledTask) => {
            return {
              'Name': scheduledTask.name,
              'Service': scheduledTask.service.name,
              'Function': scheduledTask.function_name || '__main__',
              'Frequency': `${scheduledTask.frequency} time(s)`,
              'Period': `per ${convertPeriodToString[scheduledTask.period]}`,
              'Last Invoked': scheduledTask.last_invoked_at || 'never'
            };
          })
        )
      );
    });
  }
}

module.exports = TaskList;
<|endoftext|>


<commit_before>import bridge from '../common/bridge';
import React from 'react';

export default class ServerForm extends React.Component {
  render() {
    return (
      <form onSubmit={this.connect.bind(this)}>

server: <input type='text' name='server' defaultValue='irc.freenode.net' />

port: <input type='text' name='port' defaultValue='6667' />

encoding: <input type='text' name='encoding' defaultValue='UTF-8' />

nickname: <input type='text' name='nick' defaultValue='noraesae' />

login name: <input type='text' name='loginName' defaultValue='noraesae' />

real name: <input type='text' name='realName' defaultValue='noraesae' />

<button>connect</button>

      </form>
    );
  }

  formToJSON() {
    let form = React.findDOMNode(this);
    let inputs = form.querySelectorAll('input[type="text"]');
    return Array.prototype.reduce.call(inputs, function (obj, input) {
      obj[input.name] = input.value;
      return obj;
    }, {});
  }

  connect(e) {
    e.preventDefault();

    let data = this.formToJSON();
    this.props.connect(data);
    bridge.send('connect', data);
  }
}
<commit_msg>Fix typo in server form.<commit_after>import bridge from '../common/bridge';
import React from 'react';

export default class ServerForm extends React.Component {
  render() {
    return (
      <form onSubmit={this.connect.bind(this)}>

server: <input type='text' name='server' defaultValue='irc.freenode.net' />

port: <input type='text' name='port' defaultValue='6667' />

encoding: <input type='text' name='encoding' defaultValue='UTF-8' />

nickname: <input type='text' name='nick' defaultValue='noraesae' />

user name: <input type='text' name='username' defaultValue='noraesae' />

real name: <input type='text' name='realname' defaultValue='noraesae' />

<button>connect</button>

      </form>
    );
  }

  formToJSON() {
    let form = React.findDOMNode(this);
    let inputs = form.querySelectorAll('input[type="text"]');
    return Array.prototype.reduce.call(inputs, function (obj, input) {
      obj[input.name] = input.value;
      return obj;
    }, {});
  }

  connect(e) {
    e.preventDefault();

    let data = this.formToJSON();
    this.props.connect(data);
    bridge.send('connect', data);
  }
}
<|endoftext|>


<commit_before>/*
 * Copyright 2016 Telefonica Investigación y Desarrollo, S.A.U
 *
 * This file is part of iotagent-ul
 *
 * iotagent-ul is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * iotagent-ul is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with iotagent-ul.
 * If not, seehttp://www.gnu.org/licenses/.
 *
 * For those usages not covered by the GNU Affero General Public License
 * please contact with::[iot_support@tid.es]
 */

const errors = require('./errors');
const constants = require('./constants');
const iotAgentLib = require('iotagent-node-lib');
const _ = require('underscore');

/**
 * Generates a function that parse the given attribute string, adding it to the previous collection, using the
 * provided separator.
 *
 * @param {String} separator           Character used to separate the key from the value
 * @return {Function}                  The key-pair parsing function for the separator.
 */
function addAttribute(separator) {
    return function (collection, newAttr) {
        const fields = newAttr.split(separator);

        if (!fields || fields.length !== 2) {
            throw new errors.ParseError('Extracting attribute:' + newAttr);
        } else {
            collection[fields[0]] = fields[1];
            return collection;
        }
    };
}

/**
 * Extract a key value pair from a length 2 array and add it as an attribute to the given object.
 *
 * @param {Object} collection          Collection of key value pairs
 * @param {Array} pair                 Key value pair as an array of length 2.
 * @return {Object}                    Resulting object.
 */
function addAttributePair(collection, pair) {
    if (!pair || pair.length !== 2) {
        throw new errors.ParseError('Extracting attribute:' + JSON.stringify(pair));
    } else {
        collection[pair[0]] = pair[1];
        return collection;
    }
}

/**
 * Divide a list into smaller chunks, of the given size.
 *
 * @param {Array}  list         Array to be divided.
 * @param {Number} size         Size of the chunks.
 * @return {Array}              Array containing the chunks.
 */
function chunk(list, size) {
    const chunks = [];

    while (list.length) {
        chunks.push(list.splice(0, size));
    }

    return chunks;
}

function parseMeasure(group, numberOfBars) {
    let timestamp;
    let returnValue;

    if (numberOfBars && numberOfBars.length % 2 === 0) {
        timestamp = group.substr(0, group.indexOf('|'));
        group = group.substr(group.indexOf('|') + 1);
    }

    const attributes = group.split('|');

    if (
        !attributes ||
        attributes.length === 0 ||
        attributes.length % 2 !== 0 ||
        attributes.filter(_.isEmpty).length > 0
    ) {
        throw new errors.ParseError('Parsing group:' + group);
    } else {
        returnValue = chunk(attributes, 2).reduce(addAttributePair, {});

        if (timestamp) {
            returnValue[constants.TIMESTAMP_ATTRIBUTE] = timestamp;
        }

        return returnValue;
    }
}

/**
 * Parse a command execution payload, returning an object containing information about the command. Throws
 * an error if the syntax is not correct.
 *
 * The returned object contains three attributes:
 * - deviceId: ID of the device executing the command.
 * - command: name of the command to execute.
 * - params: object containing the parameters to the command in map format.
 *
 * @param {String} payload          Ultralight 2.0 command execution payload
 * @return {Object}                Object containing the command information
 */
function command(payload) {
    const fields = payload.split('|');
    const result = {};

    if (fields.length < 1 || fields[0].indexOf('@') < 0) {
        throw new errors.ParseError('Parsing command:' + payload);
    }

    const deviceData = fields[0].split('@');

    result.deviceId = deviceData[0];
    result.command = deviceData[1];

    const dataSection = fields.splice(1);

    if (dataSection.length === 1 && dataSection[0].indexOf('=') < 0) {
        result.value = dataSection[0];
    } else {
        result.params = dataSection.reduce(addAttribute('='), {});
    }

    return result;
}

function parseCommand(group) {
    return command(group);
}

/**
 * Parse a measure group, i.e.: a string of key-value pairs sepparated by the '|' character, returning an object with
 * the same information structured as a map.
 *
 * @param {String} group                String containing a UL2.0 codified group.
 * @return {Object}                    Object representing the information in the group.
 */
function parseGroup(group) {
    if (group[0] === '|') {
        group = group.substr(1);
    }

    const numberOfBars = group.match(/\|/g);

    if (group.indexOf('@') > 0) {
        return parseCommand(group);
    }
    return parseMeasure(group, numberOfBars);
}

/**
 * Parse a measure reporting payload, returning an array with all the measure groups restructured as objects. Throws
 * an error if the syntax is not correct.
 *
 * @param {String} payload          Ultralight 2.0 measure reporting payload
 * @return {Array}                 Array containing an object per measure group
 */
function parse(payload) {
    let groups;
    let result;

    if (!payload) {
        throw new errors.ParseError('Empty payload parsing Ultraligh 2.0');
    }

    try {
        groups = payload.split('#');
        result = groups.map(parseGroup);
    } catch (e) {
        throw new errors.ParseError('Unknown error parsing Ultralight 2.0: %s', e);
    }

    return result;
}

function parseConfigurationRequest(payload) {
    const fields = payload.split('|');

    return {
        type: fields[0],
        attributes: fields.slice(1, fields.lenght)
    };
}

/**
 * Parse a command result payload, returning an object containing information about the command result. Throws
 * an error if the syntax is not correct.
 *
 * The returned object contains three attributes:
 * - deviceId: ID of the device executing the command.
 * - command: name of the command to execute.
 * - result: a string representing the output of the command.
 *
 * @param {String} payload          Ultralight 2.0 command result payload
 * @return {Object}                Object containing the result information
 */
function result(payload) {
    const fields = payload.split('|');

    if (fields.length < 1 || fields[0].indexOf('@') < 0) {
        throw new errors.ParseError('Parsing command:' + payload);
    }

    const deviceData = fields[0].split('@');

    return {
        deviceId: deviceData[0],
        command: deviceData[1],
        result: fields[1]
    };
}

/**
 * Serializes a payload for a command depending on its payloadType if provided
 *
 * @param {String} payload          Payload to serialized
 * @param {Object} command          Command attribute
 * @return {Function}               Returns a serialized payload
 */
function serializedPayloadCommand(payload, command) {
    let serialized;
    if (command && command.payloadType) {
        switch (command.payloadType.toLowerCase()) {
            case 'binaryfromstring':
                serialized = Buffer.from(payload.toString());
                break;
            case 'binaryfromhex':
                serialized = Buffer.from(payload, 'HEX');
                break;
            case 'binaryfromjson':
                serialized = Buffer.from(JSON.stringify(payload));
                break;
            case 'json':
                serialized = JSON.stringify(payload);
                break;
            default:
                // passthrough
                serialized = payload;
        }
    } else {
        serialized = payload;
    }
    return serialized;
}

/**
 * Creates the command payload string, based on the device information and command attributes.
 *
 * @param {Object} device           Object containing all the information about a device.
 * @param {String} command          Name of the command to execute.
 * @param {Object} attributes       Object containing the command parameters as attributes of the object.
 * @return {String}                 String with the codified command.
 */
function createCommandPayload(device, command, attributes) {
    function addAttributes(current, key) {
        let cmd = device && device.commands.find((att) => att.name === key);
        let value = attributes[key];
        if (cmd && cmd.expression) {
            let parser = iotAgentLib.dataPlugins.expressionTransformation;
            // The context for the JEXL expression should be the ID, TYPE, S, SS
            let attrList = [
                { name: 'id', type: 'String', value: device.id },
                { name: 'type', type: 'String', value: device.type },
                { name: 'service', type: 'String', value: device.service },
                { name: 'subservice', type: 'String', value: device.subservice }
            ];
            attrList = device.staticAttributes
                ? attrList.concat(device.staticAttributes).concat({ key: value })
                : attrList.concat({ key: value });
            let ctxt = parser.extractContext(attrList, device);
            let valueRes = null;
            try {
                valueRes = parser.applyExpression(cmd.expression, ctxt, device);
            } catch (e) {
                // nothing to report
            }
            value = valueRes ? valueRes : value;
        }

        return current + '|' + key + '=' + value;
    }

    if (typeof attributes === 'object') {
        return Object.keys(attributes).reduce(addAttributes, device.id + '@' + command);
    }
    let cmd = device && device.commands.find((att) => att.name === command);
    if (cmd && cmd.expression) {
        let parser = iotAgentLib.dataPlugins.expressionTransformation;
        // The context for the JEXL expression should be the ID, TYPE, S, SS
        let attrList = [
            { name: 'id', type: 'String', value: device.id },
            { name: 'type', type: 'String', value: device.type },
            { name: 'service', type: 'String', value: device.service },
            { name: 'subservice', type: 'String', value: device.subservice }
        ];
        attrList = device.staticAttributes
            ? attrList.concat(device.staticAttributes).concat({ command: attributes })
            : attrList.concat({ command: attributes });
        let ctxt = parser.extractContext(attrList, device);
        let valueRes = null;
        try {
            valueRes = parser.applyExpression(cmd.expression, ctxt, device);
        } catch (e) {
            // nothing to report
        }
        attributes = valueRes ? valueRes : attributes;
    }
    let payload = device.id + '@' + command + '|' + attributes;
    return serializedPayloadCommand(payload, cmd);
}

/**
 * Creates the configuration payload string, based on the device information.
 *
 * @param {Object} device           Object containing all the information about a device.
 * @param {Object} attributes       Object containing the command parameters as attributes of the object.
 * @return {String}                 String with the codified command.
 */
function createConfigurationPayload(deviceId, attributes) {
    function addAttributes(current, key) {
        return current + '|' + key + '=' + attributes[key];
    }

    return Object.keys(attributes).reduce(addAttributes, deviceId + '@configuration');
}

exports.parse = parse;
exports.parseConfigurationRequest = parseConfigurationRequest;
exports.command = command;
exports.result = result;
exports.createCommandPayload = createCommandPayload;
exports.createConfigurationPayload = createConfigurationPayload;
<commit_msg>fix no case<commit_after>/*
 * Copyright 2016 Telefonica Investigación y Desarrollo, S.A.U
 *
 * This file is part of iotagent-ul
 *
 * iotagent-ul is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * iotagent-ul is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with iotagent-ul.
 * If not, seehttp://www.gnu.org/licenses/.
 *
 * For those usages not covered by the GNU Affero General Public License
 * please contact with::[iot_support@tid.es]
 */

const errors = require('./errors');
const constants = require('./constants');
const iotAgentLib = require('iotagent-node-lib');
const _ = require('underscore');
const context = {
    op: 'IOTAUL.ulParser'
};
const config = require('./configService');

/**
 * Generates a function that parse the given attribute string, adding it to the previous collection, using the
 * provided separator.
 *
 * @param {String} separator           Character used to separate the key from the value
 * @return {Function}                  The key-pair parsing function for the separator.
 */
function addAttribute(separator) {
    return function (collection, newAttr) {
        const fields = newAttr.split(separator);

        if (!fields || fields.length !== 2) {
            throw new errors.ParseError('Extracting attribute:' + newAttr);
        } else {
            collection[fields[0]] = fields[1];
            return collection;
        }
    };
}

/**
 * Extract a key value pair from a length 2 array and add it as an attribute to the given object.
 *
 * @param {Object} collection          Collection of key value pairs
 * @param {Array} pair                 Key value pair as an array of length 2.
 * @return {Object}                    Resulting object.
 */
function addAttributePair(collection, pair) {
    if (!pair || pair.length !== 2) {
        throw new errors.ParseError('Extracting attribute:' + JSON.stringify(pair));
    } else {
        collection[pair[0]] = pair[1];
        return collection;
    }
}

/**
 * Divide a list into smaller chunks, of the given size.
 *
 * @param {Array}  list         Array to be divided.
 * @param {Number} size         Size of the chunks.
 * @return {Array}              Array containing the chunks.
 */
function chunk(list, size) {
    const chunks = [];

    while (list.length) {
        chunks.push(list.splice(0, size));
    }

    return chunks;
}

function parseMeasure(group, numberOfBars) {
    let timestamp;
    let returnValue;

    if (numberOfBars && numberOfBars.length % 2 === 0) {
        timestamp = group.substr(0, group.indexOf('|'));
        group = group.substr(group.indexOf('|') + 1);
    }

    const attributes = group.split('|');

    if (
        !attributes ||
        attributes.length === 0 ||
        attributes.length % 2 !== 0 ||
        attributes.filter(_.isEmpty).length > 0
    ) {
        throw new errors.ParseError('Parsing group:' + group);
    } else {
        returnValue = chunk(attributes, 2).reduce(addAttributePair, {});

        if (timestamp) {
            returnValue[constants.TIMESTAMP_ATTRIBUTE] = timestamp;
        }

        return returnValue;
    }
}

/**
 * Parse a command execution payload, returning an object containing information about the command. Throws
 * an error if the syntax is not correct.
 *
 * The returned object contains three attributes:
 * - deviceId: ID of the device executing the command.
 * - command: name of the command to execute.
 * - params: object containing the parameters to the command in map format.
 *
 * @param {String} payload          Ultralight 2.0 command execution payload
 * @return {Object}                Object containing the command information
 */
function command(payload) {
    const fields = payload.split('|');
    const result = {};

    if (fields.length < 1 || fields[0].indexOf('@') < 0) {
        throw new errors.ParseError('Parsing command:' + payload);
    }

    const deviceData = fields[0].split('@');

    result.deviceId = deviceData[0];
    result.command = deviceData[1];

    const dataSection = fields.splice(1);

    if (dataSection.length === 1 && dataSection[0].indexOf('=') < 0) {
        result.value = dataSection[0];
    } else {
        result.params = dataSection.reduce(addAttribute('='), {});
    }

    return result;
}

function parseCommand(group) {
    return command(group);
}

/**
 * Parse a measure group, i.e.: a string of key-value pairs sepparated by the '|' character, returning an object with
 * the same information structured as a map.
 *
 * @param {String} group                String containing a UL2.0 codified group.
 * @return {Object}                    Object representing the information in the group.
 */
function parseGroup(group) {
    if (group[0] === '|') {
        group = group.substr(1);
    }

    const numberOfBars = group.match(/\|/g);

    if (group.indexOf('@') > 0) {
        return parseCommand(group);
    }
    return parseMeasure(group, numberOfBars);
}

/**
 * Parse a measure reporting payload, returning an array with all the measure groups restructured as objects. Throws
 * an error if the syntax is not correct.
 *
 * @param {String} payload          Ultralight 2.0 measure reporting payload
 * @return {Array}                 Array containing an object per measure group
 */
function parse(payload) {
    let groups;
    let result;

    if (!payload) {
        throw new errors.ParseError('Empty payload parsing Ultraligh 2.0');
    }

    try {
        groups = payload.split('#');
        result = groups.map(parseGroup);
    } catch (e) {
        throw new errors.ParseError('Unknown error parsing Ultralight 2.0: %s', e);
    }

    return result;
}

function parseConfigurationRequest(payload) {
    const fields = payload.split('|');

    return {
        type: fields[0],
        attributes: fields.slice(1, fields.lenght)
    };
}

/**
 * Parse a command result payload, returning an object containing information about the command result. Throws
 * an error if the syntax is not correct.
 *
 * The returned object contains three attributes:
 * - deviceId: ID of the device executing the command.
 * - command: name of the command to execute.
 * - result: a string representing the output of the command.
 *
 * @param {String} payload          Ultralight 2.0 command result payload
 * @return {Object}                Object containing the result information
 */
function result(payload) {
    const fields = payload.split('|');

    if (fields.length < 1 || fields[0].indexOf('@') < 0) {
        throw new errors.ParseError('Parsing command:' + payload);
    }

    const deviceData = fields[0].split('@');

    return {
        deviceId: deviceData[0],
        command: deviceData[1],
        result: fields[1]
    };
}

/**
 * Serializes a payload for a command depending on its payloadType if provided
 *
 * @param {String} payload          Payload to serialized
 * @param {Object} command          Command attribute
 * @return {Function}               Returns a serialized payload
 */
function serializedPayloadCommand(payload, command) {
    let serialized;
    if (command && command.payloadType) {
        switch (command.payloadType.toLowerCase()) {
            case 'binaryfromstring':
                serialized = Buffer.from(payload.toString());
                break;
            case 'binaryfromhex':
                serialized = Buffer.from(payload, 'HEX');
                break;
            case 'binaryfromjson':
                serialized = Buffer.from(JSON.stringify(payload));
                break;
            case 'json':
                serialized = JSON.stringify(payload);
                break;
            default:
                // passthrough
                serialized = payload;
        }
    } else {
        serialized = payload;
    }
    return serialized;
}

/**
 * Creates the command payload string, based on the device information and command attributes.
 *
 * @param {Object} device           Object containing all the information about a device.
 * @param {String} command          Name of the command to execute.
 * @param {Object} attributes       Object containing the command parameters as attributes of the object.
 * @return {String}                 String with the codified command.
 */
function createCommandPayload(device, command, attributes) {
    function addAttributes(current, key) {
        let cmd = device && device.commands.find((att) => att.name === key);
        let value = attributes[key];
        if (cmd && cmd.expression) {
            let parser = iotAgentLib.dataPlugins.expressionTransformation;
            // The context for the JEXL expression should be the ID, TYPE, S, SS
            let attrList = [
                { name: 'id', type: 'String', value: device.id },
                { name: 'type', type: 'String', value: device.type },
                { name: 'service', type: 'String', value: device.service },
                { name: 'subservice', type: 'String', value: device.subservice }
            ];
            attrList = device.staticAttributes
                ? attrList.concat(device.staticAttributes).concat({ key: value })
                : attrList.concat({ key: value });
            config.getLogger().debug(context, 'attrList [%j] for device %j', attrList, device);
            let ctxt = parser.extractContext(attrList, device);
            let valueRes = null;
            try {
                valueRes = parser.applyExpression(cmd.expression, ctxt, device);
            } catch (e) {
                // nothing to report
            }
            value = valueRes ? valueRes : cmd.expression;
        }

        return current + '|' + key + '=' + value;
    }

    if (typeof attributes === 'object') {
        return Object.keys(attributes).reduce(addAttributes, device.id + '@' + command);
    }
    let cmd = device && device.commands.find((att) => att.name === command);
    if (cmd && cmd.expression) {
        let parser = iotAgentLib.dataPlugins.expressionTransformation;
        // The context for the JEXL expression should be the ID, TYPE, S, SS
        let attrList = [
            { name: 'id', type: 'String', value: device.id },
            { name: 'type', type: 'String', value: device.type },
            { name: 'service', type: 'String', value: device.service },
            { name: 'subservice', type: 'String', value: device.subservice }
        ];
        attrList = device.staticAttributes
            ? attrList.concat(device.staticAttributes).concat({ command: attributes })
            : attrList.concat({ command: attributes });
        config.getLogger().debug(context, 'attrList [%j] for device %j', attrList, device);
        let ctxt = parser.extractContext(attrList, device);
        let valueRes = null;
        try {
            valueRes = parser.applyExpression(cmd.expression, ctxt, device);
        } catch (e) {
            // nothing to report
        }
        attributes = valueRes ? valueRes : cmd.expression;
    }
    let payload = device.id + '@' + command + '|' + attributes;
    return serializedPayloadCommand(payload, cmd);
}

/**
 * Creates the configuration payload string, based on the device information.
 *
 * @param {Object} device           Object containing all the information about a device.
 * @param {Object} attributes       Object containing the command parameters as attributes of the object.
 * @return {String}                 String with the codified command.
 */
function createConfigurationPayload(deviceId, attributes) {
    function addAttributes(current, key) {
        return current + '|' + key + '=' + attributes[key];
    }

    return Object.keys(attributes).reduce(addAttributes, deviceId + '@configuration');
}

exports.parse = parse;
exports.parseConfigurationRequest = parseConfigurationRequest;
exports.command = command;
exports.result = result;
exports.createCommandPayload = createCommandPayload;
exports.createConfigurationPayload = createConfigurationPayload;
<|endoftext|>


<commit_before>module.exports = {
  "parser": "typescript-eslint-parser",
  "parserOptions": {
    "ecmaVersion": 2018,
    "sourceType": "module",
    "ecmaFeatures": {
      "experimentalObjectRestSpread": true,
      "modules": true
    },
  },
  "env": {
    "node": true,
    "es6": true
  },
  "extends": [
    "airbnb-base",
    "plugin:promise/recommended"
  ],
  "plugins": [
    "promise",
    "typescript"
  ],
  "rules": {
    "import/no-unresolved": "off",
    "no-console": "off",
    "no-undef": "off",
    "no-underscore-dangle": ["error", { "allowAfterThis": true, "allowAfterSuper": true }]
  }
};
<commit_msg>Eslint rules changed.<commit_after>module.exports = {
  "parser": "typescript-eslint-parser",
  "parserOptions": {
    "ecmaVersion": 2018,
    "sourceType": "module",
    "ecmaFeatures": {
      "experimentalObjectRestSpread": true,
      "modules": true
    },
  },
  "env": {
    "node": true,
    "es6": true
  },
  "extends": [
    "airbnb-base",
    "plugin:promise/recommended"
  ],
  "plugins": [
    "promise",
    "typescript"
  ],
  "rules": {
    "import/no-unresolved": "off",
    "no-console": "off",
    "no-undef": "off",
    "no-underscore-dangle": ["error", { "allowAfterThis": true, "allowAfterSuper": true }],
    "typescript/no-unused-vars": ["error"]
  }
};
<|endoftext|>


<commit_before>'use strict';
// modules
var spawn = require('open'),
    express = require('express'),
    http = require('http'),
    path = require('path'),
    dgram = require('dgram'),
    socketIO = require('socket.io');
// server
var app = express(),
    httpServer = http.Server(app),
    io = socketIO(httpServer),
    udpServer = dgram.createSocket('udp4');
// config
var config = require('./config.json');

// configure static files
app.use(express.static(path.join(__dirname, 'public')));

// Start the http server
httpServer.listen(config.webPort, function(){
	console.log('HTTP Server listening on port ' + config.webPort);
    spawn('http://127.0.0.1:'+config.webPort);
});

udpServer.on('listening', function () {
	console.log('UDP Server listening on port ' + udpServer.address().port);
});

// converting the outgauge packages to JSON transmitted via Socket.IO
udpServer.on('message', function (message) {
	var buff = new Buffer(message);
	var outgaugeData = {
		time: buff.readInt32LE(0),
		car: buff.toString('ascii',4,7),
		flags: buff.readUInt16LE(8),
		plid: buff.readUInt8(9),
		gear: buff.readUInt8(10),
		speed: buff.readFloatLE(12),
		rpm: buff.readFloatLE(16),
		turbo: buff.readFloatLE(20),
		engtemp: buff.readFloatLE(24),
		fuel: buff.readFloatLE(28),
		oilpressure: buff.readFloatLE(32),
		oiltemp: buff.readFloatLE(36),
		dashlights: buff.readInt32LE(40),
		showlights: buff.readInt32LE(44),
		throttle: buff.readFloatLE(48),
		brake: buff.readFloatLE(52),
		clutch: buff.readFloatLE(56),
        // TODO: Those aren't completly right
		display: [
			buff.toString('ascii', 60, 75),
			buff.toString('ascii', 76, 92)
		]
	};
	io.emit('outgauge',outgaugeData);
});

// start the udp server
udpServer.bind(config.outgaugePort);<commit_msg>more fixes of the outgauge struct<commit_after>'use strict';
// modules
var spawn = require('open'),
    express = require('express'),
    http = require('http'),
    path = require('path'),
    dgram = require('dgram'),
    socketIO = require('socket.io');
// server
var app = express(),
    httpServer = http.Server(app),
    io = socketIO(httpServer),
    udpServer = dgram.createSocket('udp4');
// config
var config = require('./config.json');

// configure static files
app.use(express.static(path.join(__dirname, 'public')));

// Start the http server
httpServer.listen(config.webPort, function(){
	console.log('HTTP Server listening on port ' + config.webPort);
    spawn('http://127.0.0.1:'+config.webPort);
});

udpServer.on('listening', function () {
	console.log('UDP Server listening on port ' + udpServer.address().port);
});

// converting the outgauge packages to JSON transmitted via Socket.IO
udpServer.on('message', function (message) {
	var buff = new Buffer(message);
	var outgaugeData = {
		time: buff.readInt32LE(0),
		car: buff.toString('ascii',4,7),
		flags: buff.readUInt16LE(7),
		plid: buff.readUInt8(9),
		gear: buff.readUInt8(10),
		speed: buff.readFloatLE(12),
		rpm: buff.readFloatLE(16),
		turbo: buff.readFloatLE(20),
		engtemp: buff.readFloatLE(24),
		fuel: buff.readFloatLE(28),
		oilpressure: buff.readFloatLE(32),
		oiltemp: buff.readFloatLE(36),
		dashlights: buff.readInt32LE(40),
		showlights: buff.readInt32LE(44),
		throttle: buff.readFloatLE(48),
		brake: buff.readFloatLE(52),
		clutch: buff.readFloatLE(56),
        // TODO: Those aren't completly right
		display: [
			buff.toString('ascii', 60, 76),
			buff.toString('ascii', 76, 92)
		]
	};
	io.emit('outgauge',outgaugeData);
});

// start the udp server
udpServer.bind(config.outgaugePort);<|endoftext|>


<commit_before>exports.config = {
  shaIn : '00000000000000000000000000000000000000000',
  shaOut : '00000000000000000000000000000000000000000',
  shaType : 'sha1',
  pspId : 'pspid',
  testMode : true,
  accounts : {
    'legalisation-post' : {
      pspId : (process.env["epdq_legalisation_pspid"] || 'pspid'),
      shaType : 'sha1',
      shaIn : (process.env["epdq_legalisation_post_shaIn"] || "00000000000000000000000000000000000000000"),
      shaOut : (process.env["epdq_legalisation_post_shaOut"] || "00000000000000000000000000000000000000000"),
      testMode : true
    },
    'legalisation-drop-off' : {
      pspId : (process.env["epdq_pspid"] || 'pspid'),
      shaType : 'sha1',
      shaIn : (process.env["epdq_legalisation_dropoff_shaIn"] || "00000000000000000000000000000000000000000"),
      shaOut : (process.env["epdq_legalisation_dropoff_shaOut"] || "00000000000000000000000000000000000000000"),
      testMode : true
    },
    'birth-death-marriage' : {
      pspId : (process.env["epdq_birth_pspid"] || 'pspid'),
      shaType : 'sha1',
      shaIn : (process.env["epdq_birth_shaIn"] || "00000000000000000000000000000000000000000"),
      shaOut : (process.env["epdq_birth_shaOut"] || "00000000000000000000000000000000000000000"),
      testMode : true
    }
  }
};
<commit_msg>Make env variable names consistent<commit_after>exports.config = {
  shaIn : '00000000000000000000000000000000000000000',
  shaOut : '00000000000000000000000000000000000000000',
  shaType : 'sha1',
  pspId : 'pspid',
  testMode : true,
  accounts : {
    'legalisation-post' : {
      pspId : (process.env["epdq_legalisation_post_pspid"] || 'pspid'),
      shaType : 'sha1',
      shaIn : (process.env["epdq_legalisation_post_shaIn"] || "00000000000000000000000000000000000000000"),
      shaOut : (process.env["epdq_legalisation_post_shaOut"] || "00000000000000000000000000000000000000000"),
      testMode : true
    },
    'legalisation-drop-off' : {
      pspId : (process.env["epdq_legalisation_dropoff_pspid"] || 'pspid'),
      shaType : 'sha1',
      shaIn : (process.env["epdq_legalisation_dropoff_shaIn"] || "00000000000000000000000000000000000000000"),
      shaOut : (process.env["epdq_legalisation_dropoff_shaOut"] || "00000000000000000000000000000000000000000"),
      testMode : true
    },
    'birth-death-marriage' : {
      pspId : (process.env["epdq_birth_pspid"] || 'pspid'),
      shaType : 'sha1',
      shaIn : (process.env["epdq_birth_shaIn"] || "00000000000000000000000000000000000000000"),
      shaOut : (process.env["epdq_birth_shaOut"] || "00000000000000000000000000000000000000000"),
      testMode : true
    }
  }
};
<|endoftext|>


<commit_before>/**
 * ku 0.3.0-dev <http://github.com/L8D/ku/>
 * @license MIT
 * @copyright (c) 2014 Tenor Biel
 */
/* global define, exports, module */
/* istanbul ignore next */
(function(root, factory) {
  'use strict';

  if (typeof define === 'function' && define.amd) {
    define('ku', factory);
  } else if (typeof exports === 'object') {
    module.exports = factory();
  } else {
    root.ku = factory();
  }
})(this, function() {
  'use strict';

  /**
   * @exampleHelpers
   * function add(x, y) { return x + y; }
   */

  /** @exports ku */
  var ku = {
    /**
     * Creates an array of values by apply the function to each element in the
     * collection.
     *
     * @example
     * ku.map(function(num) { return num * 3}, [1, 2, 3]);
     * // => [3, 6, 9]
     * @param {function} fn - The function to iterate with
     * @param {array} data - The data to iterate over
     * @returns {array}
     */
    map: function(fn, data) {
      var index = data.length;
      var res = new Array(index);

      while (index--) {
        res[index] = fn(data[index], index);
      }

      return res;
    },

    /**
     * Creates an array of all values that the function returns a truthy value
     * for.
     *
     * @example
     * ku.filter(function(num) { return num % 2 === 0; }, [1, 2, 3, 4, 5, 6]);
     * // => [2, 4, 6]
     * @param {function} fn - The function to iterate with
     * @param {array} data - The data to iterate over
     * @returns {array}
     */
    filter: function(fn, data) {
      var index = -1;
      var length = data.length;
      var res = [];
      var rindex = -1;

      while (++index < length) {
        var value = data[index];

        if (fn(value, index)) {
          res[++rindex] = value;
        }
      }

      return res;
    },

    /**
     * Aggregates over a collection starting with a value and returning the
     * resulting value.
     *
     * @example
     * ku.reduce(add, '', ['foo', 'bar', 'baz']);
     * // => (('' + 'foo') + 'bar') + 'baz'
     * // => 'foobarbaz'
     * @example
     * ku.reduce(add, 'some value', []);
     * // => 'some value'
     * @param {function} fn - The function to aggregate with
     * @param {*} value - The initial accumulator value
     * @param {array} data - The data to aggregate over
     * @returns {*}
     */
    reduce: function(fn, value, data) {
      var index = -1;
      var length = data.length;

      while (++index < length) {
        value = fn(value, data[index]);
      }

      return value;
    },

    /**
     * Aggregates over a collection and returns an array of each intermittent
     * accumulation.
     *
     * @example
     * ku.scan(add, 0, [1, 2, 3]);
     * // => [0, 1, 3, 6]
     * @example
     * ku.scan(add, 0, []);
     * // => [0]
     * @param {function} fn - The function to aggregate with
     * @param {*} value - The initial accumulator value
     * @param {array} data - The data to aggregate over
     * @returns {array}
     */
    scan: function(fn, value, data) {
      var index = -1;
      var length = data.length;
      var res = new Array(length + 1);
      var rindex = 0;

      res[0] = value;

      while (++index < length) {
        value = res[++rindex] = fn(value, data[index]);
      }

      return res;
    },

    /**
     * Maps over an array and concatenates the result.
     *
     * @example
     * ku.chain(function(x) { return [x, x + 1, x + 2]; }, [1, 2, 3]);
     * // => [1, 2, 3, 2, 3, 4, 3, 4, 5]
     * @example
     * ku.chain(function(x) { return [[x]]; }, [1, 2, 3]);
     * // => [[1], [2], [3]]
     * @param {function} fn - The function to iterate with
     * @param {array} data - The data to iterate over
     * @returns {array}
     */
    chain: function(fn, data) {
      var index = -1;
      var length = data.length;
      var res = [];
      var rindex = -1;

      while (++index < length) {
        var values = fn(data[index]);

        var index2 = -1;
        var length2 = values.length;

        while (++index2 < length2) {
          res[++rindex] = values[index2];
        }
      }

      return res;
    },

    /**
     * Takes the first `count` elements from an array.
     *
     * @example
     * ku.take(5, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
     * //=> [1, 2, 3, 4, 5]
     * @param {number} count
     * @param {array} data
     * @returns {array}
     */
    take: function(count, data) {
      var length = data.length;
      var index = Math.min(length, count);
      var res = new Array(length - index);

      while (index--) {
        res[index] = data[index];
      }

      return res;
    },

    /**
     * Drops the first `count` elements from an array.
     *
     * @example
     * (function() {
     *   return ku.drop(0, arguments);
     * })(1, 2, 3, 4);
     * //=> [1, 2, 3, 4]
     * @param {number} count
     * @param {array} data
     * @returns {array}
     */
    drop: function(count, data) {
      var length = data.length;
      var index = Math.min(length, count);
      var res = new Array(length - index);
      index--;

      while (++index < length) {
        res[index - count] = data[index];
      }

      return res;
    },

    /**
     * Slices an array at indecies `x` and `y`.
     *
     * @example
     * ku.slice(2, 5, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
     * // => [3, 4, 5]
     * @example
     * ku.slice(2, 5, []);
     * // => []
     * @param {number} x
     * @param {number} y
     * @param {array} data
     * @returns {array}
     */
    slice: function(x, y, data) {
      var length = data.length;
      var index = Math.min(x, length);
      y = Math.min(y, length);
      var res = new Array(y - index);
      index--;

      while (++index < y) {
        res[index - x] = data[index];
      }

      return res;
    },

    /**
     * Uses `fn` to zip two arrays into one new array.
     *
     * Due to performance implications and idiomaticism, zip is actually
     * zipWith because JavaScript doesn't have a standard for tuple-like
     * data structures.
     *
     * @example
     * ku.zip(add, [1, 2, 3], [4, 5, 6]);
     * // => [1 + 4, 2 + 5, 3 + 6]
     * @example
     * ku.zip(add, [], [1, 2, 3, 4]); // => []
     * ku.zip(add, [1, 2, 3, 4], []); // => []
     * @param {function} fn
     * @param {array} left
     * @param {array} right
     * @returns {array}
     */
    zip: function(fn, left, right) {
      var index = Math.min(left.length, right.length);
      var res = new Array(index);

      while (index--) {
        res[index] = fn(left[index], right[index]);
      }

      return res;
    }
  };

  return ku;
});
<commit_msg>add reduceRight<commit_after>/**
 * ku 0.3.0-dev <http://github.com/L8D/ku/>
 * @license MIT
 * @copyright (c) 2014 Tenor Biel
 */
/* global define, exports, module */
/* istanbul ignore next */
(function(root, factory) {
  'use strict';

  if (typeof define === 'function' && define.amd) {
    define('ku', factory);
  } else if (typeof exports === 'object') {
    module.exports = factory();
  } else {
    root.ku = factory();
  }
})(this, function() {
  'use strict';

  /**
   * @exampleHelpers
   * function add(x, y) { return x + y; }
   */

  /** @exports ku */
  var ku = {
    /**
     * Creates an array of values by apply the function to each element in the
     * collection.
     *
     * @example
     * ku.map(function(num) { return num * 3}, [1, 2, 3]);
     * // => [3, 6, 9]
     * @param {function} fn - The function to iterate with
     * @param {array} data - The data to iterate over
     * @returns {array}
     */
    map: function(fn, data) {
      var index = data.length;
      var res = new Array(index);

      while (index--) {
        res[index] = fn(data[index], index);
      }

      return res;
    },

    /**
     * Creates an array of all values that the function returns a truthy value
     * for.
     *
     * @example
     * ku.filter(function(num) { return num % 2 === 0; }, [1, 2, 3, 4, 5, 6]);
     * // => [2, 4, 6]
     * @param {function} fn - The function to iterate with
     * @param {array} data - The data to iterate over
     * @returns {array}
     */
    filter: function(fn, data) {
      var index = -1;
      var length = data.length;
      var res = [];
      var rindex = -1;

      while (++index < length) {
        var value = data[index];

        if (fn(value, index)) {
          res[++rindex] = value;
        }
      }

      return res;
    },

    /**
     * Aggregates over a collection starting with a value and returning the
     * resulting value.
     *
     * @example
     * ku.reduce(add, '', ['foo', 'bar', 'baz']);
     * // => (('' + 'foo') + 'bar') + 'baz'
     * // => 'foobarbaz'
     * @example
     * ku.reduce(add, 'some value', []);
     * // => 'some value'
     * @param {function} fn - The function to aggregate with
     * @param {*} value - The initial accumulator value
     * @param {array} data - The data to aggregate over
     * @returns {*}
     */
    reduce: function(fn, value, data) {
      var index = -1;
      var length = data.length;

      while (++index < length) {
        value = fn(value, data[index]);
      }

      return value;
    },

    /**
     * Aggregates over a collection and returns an array of each intermittent
     * accumulation.
     *
     * @example
     * ku.scan(add, 0, [1, 2, 3]);
     * // => [0, 1, 3, 6]
     * @example
     * ku.scan(add, 0, []);
     * // => [0]
     * @param {function} fn - The function to aggregate with
     * @param {*} value - The initial accumulator value
     * @param {array} data - The data to aggregate over
     * @returns {array}
     */
    scan: function(fn, value, data) {
      var index = -1;
      var length = data.length;
      var res = new Array(length + 1);
      var rindex = 0;

      res[0] = value;

      while (++index < length) {
        value = res[++rindex] = fn(value, data[index]);
      }

      return res;
    },

    /**
     * Maps over an array and concatenates the result.
     *
     * @example
     * ku.chain(function(x) { return [x, x + 1, x + 2]; }, [1, 2, 3]);
     * // => [1, 2, 3, 2, 3, 4, 3, 4, 5]
     * @example
     * ku.chain(function(x) { return [[x]]; }, [1, 2, 3]);
     * // => [[1], [2], [3]]
     * @param {function} fn - The function to iterate with
     * @param {array} data - The data to iterate over
     * @returns {array}
     */
    chain: function(fn, data) {
      var index = -1;
      var length = data.length;
      var res = [];
      var rindex = -1;

      while (++index < length) {
        var values = fn(data[index]);

        var index2 = -1;
        var length2 = values.length;

        while (++index2 < length2) {
          res[++rindex] = values[index2];
        }
      }

      return res;
    },

    /**
     * Takes the first `count` elements from an array.
     *
     * @example
     * ku.take(5, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
     * //=> [1, 2, 3, 4, 5]
     * @param {number} count
     * @param {array} data
     * @returns {array}
     */
    take: function(count, data) {
      var length = data.length;
      var index = Math.min(length, count);
      var res = new Array(length - index);

      while (index--) {
        res[index] = data[index];
      }

      return res;
    },

    /**
     * Drops the first `count` elements from an array.
     *
     * @example
     * (function() {
     *   return ku.drop(0, arguments);
     * })(1, 2, 3, 4);
     * //=> [1, 2, 3, 4]
     * @param {number} count
     * @param {array} data
     * @returns {array}
     */
    drop: function(count, data) {
      var length = data.length;
      var index = Math.min(length, count);
      var res = new Array(length - index);
      index--;

      while (++index < length) {
        res[index - count] = data[index];
      }

      return res;
    },

    /**
     * Slices an array at indecies `x` and `y`.
     *
     * @example
     * ku.slice(2, 5, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
     * // => [3, 4, 5]
     * @example
     * ku.slice(2, 5, []);
     * // => []
     * @param {number} x
     * @param {number} y
     * @param {array} data
     * @returns {array}
     */
    slice: function(x, y, data) {
      var length = data.length;
      var index = Math.min(x, length);
      y = Math.min(y, length);
      var res = new Array(y - index);
      index--;

      while (++index < y) {
        res[index - x] = data[index];
      }

      return res;
    },

    /**
     * Uses `fn` to zip two arrays into one new array.
     *
     * Due to performance implications and idiomaticism, zip is actually
     * zipWith because JavaScript doesn't have a standard for tuple-like
     * data structures.
     *
     * @example
     * ku.zip(add, [1, 2, 3], [4, 5, 6]);
     * // => [1 + 4, 2 + 5, 3 + 6]
     * @example
     * ku.zip(add, [], [1, 2, 3, 4]); // => []
     * ku.zip(add, [1, 2, 3, 4], []); // => []
     * @param {function} fn
     * @param {array} left
     * @param {array} right
     * @returns {array}
     */
    zip: function(fn, left, right) {
      var index = Math.min(left.length, right.length);
      var res = new Array(index);

      while (index--) {
        res[index] = fn(left[index], right[index]);
      }

      return res;
    },

    /**
     * Aggregates over a collection from right to left starting with a value
     * and returning the resulting value.
     *
     * @example
     * ku.reduceRight(add, '', ['foo', 'bar', 'baz']);
     * // => (('' + 'baz') + 'bar') + 'foo'
     * // => 'bazbarfoo'
     * @example
     * ku.reduceRight(add, 'some value', []);
     * // => 'some value'
     * @param {function} fn - The function to aggregate with
     * @param {*} value - The initial accumulator value
     * @param {array} data - The data to aggregate over
     * @returns {*}
     */
    reduceRight: function(fn, value, data) {
      var index = data.length;

      while (index--) {
        value = fn(value, data[index]);
      }

      return value;
    },
  };

  return ku;
});
<|endoftext|>


<commit_before>/**
 * @type {String}
 *
 * @properties={typeid:35,uuid:"04fde543-69cc-4de9-af47-7f7c22221f26"}
 */
var _license_dsa_mosaic_WEB_cms = 'Module: _dsa_mosaic_WEB_cms \
									Copyright (C) 2011-2013 Data Mosaic \
									MIT Licensed';

/**
 * @type {Boolean}
 *
 * @properties={typeid:35,uuid:"1637C97D-08E7-4019-813B-FF8A07B35AB6",variableType:-4}
 */
var _skipSelect = false;

/**
 *
 * @properties={typeid:24,uuid:"022C11EE-D472-44B4-88EA-873A195E7136"}
 */
function REC_delete() {
	var input = globals.DIALOGS.showWarningDialog(
						'Delete',
						'Do you really want to delete this record?',
						'Yes',
						'No'
					)

	if (input == 'Yes') {
		//delete all assets when not a group
		if (asset_type != 3) {
			//grab directory name
			var directory = web_asset_to_asset_instance__initial.asset_directory
			var baseDirectory = forms.WEB_0F_install.ACTION_get_install() +
					'/application_server/server/webapps/ROOT/sutraCMS/sites/' +
					forms.WEB_0F_site.directory
			var deleteThis		= {}
			deleteThis.directory	 	= baseDirectory + '/' + directory

			for (var i = 1; i <= web_asset_to_asset_instance.getSize(); i++) {
				forms.WEB_0F_asset_1F_2L_asset_instance.REC_delete(null,true,forms.WEB_0F_asset_1F_2L_asset_instance.foundset.getRecord(i))
			}

		//delete directory
			// developer version (use local file system method since headless client plugin bugged)
			if ( application.isInDeveloper() ) {
				forms.WEB_0C__file_stream.ASSET_delete(deleteThis)
			}
			// file streaming version when on a service
			else {
				var jsclient = plugins.headlessclient.createClient("_dsa_mosaic_WEB_cms", null, null, null)
				jsclient.queueMethod("WEB_0C__file_stream", "ASSET_delete", [deleteThis], null)
			}
		}

		controller.deleteRecord()

		//dim out the lights
		if (!utils.hasRecords(foundset)) {
			FORM_on_show()
		}
	}
}

/**
 * Perform the element default action.
 *
 * @param {JSEvent} event the event that triggered the action
 *
 * @properties={typeid:24,uuid:"0DFCEC6C-DF14-4E2B-BE6A-A5F986F8375C"}
 */
function TAG_add(event) {
	if (utils.hasRecords(foundset)) {
		//turn autosave off
		databaseManager.setAutoSave(false)

		forms.WEB_P_tag__add._callingForm = controller.getName()

		globals.CODE_form_in_dialog(
					forms.WEB_P_tag__add,
					400,-1,-1,-1,
					'Tags',
					true,
					false,
					'tagAdd'
				)
	}
	else {
		globals.DIALOGS.showErrorDialog(
						'Error',
						'There is no record to add tags to'
					)
	}
}

/**
 * Perform the element default action.
 *
 * @param {JSEvent} event the event that triggered the action
 *
 * @properties={typeid:24,uuid:"8372B4E8-DA55-4B6A-8F4F-4B7C787F286C"}
 */
function TAG_delete(event) {
	if (utils.hasRecords(foundset)) {
		//turn autosave off
		databaseManager.setAutoSave(false)

		forms.WEB_P_tag__remove._callingForm = controller.getName()

		globals.CODE_form_in_dialog(
					forms.WEB_P_tag__remove,
					400,-1,-1,-1,
					'Tags',
					true,
					false,
					'tagDelete'
				)
	}
	else {
		globals.DIALOGS.showErrorDialog(
						'Error',
						'There is no record to remove tags from'
					)
	}

}

/**
 *
 * @properties={typeid:24,uuid:"FF5AF14C-E836-4D15-897E-FC174AA6C371"}
 */
function REC_new(assetType) {
	var input = globals.DIALOGS.showSelectDialog(
					"Asset",
					"Select asset type",
					"Image",
					"File",
					"Group"
				)

	//something selected, do the right kind of import
	switch ( input  ) {
		case 'Image':
			forms.WEB_0C__file_stream.IMAGE_import("images")
			break
		case 'File':
			forms.WEB_0C__file_stream.FILE_import("files")
			break
		case 'Group':
			// create asset record
			var fsAsset = foundset
			//disable on select method
			_skipSelect = true

			var assetRec = fsAsset.getRecord(fsAsset.newRecord(true,true))
			assetRec.id_site = forms.WEB_0F_site.id_site
			assetRec.asset_type = 3

			//enable on select method
			_skipSelect = false
			REC_on_select()
			break
	}
}

/**
 * Callback method when form is (re)loaded.
 *
 * @param {JSEvent} event the event that triggered the action
 *
 * @properties={typeid:24,uuid:"CFCBF7B5-C038-4D04-AFF3-41AEA18ED580"}
 * @AllowToRunInFind
 */
function FILTER_records(event) {
	//find stuff for the selected site
	if (utils.hasRecords(forms.WEB_0F_site.foundset)) {
		foundset.find()
		foundset.id_site = forms.WEB_0F_site.id_site
		var results = foundset.search()
	}
	else {
		foundset.clear()
	}
}

/**
 * Callback method for when form is shown.
 *
 * @param {Boolean} firstShow form is shown first time after load
 * @param {JSEvent} event the event that triggered the action
 *
 * @properties={typeid:24,uuid:"16C7820E-528E-495C-A409-E0EA923E2429"}
 */
function FORM_on_show(firstShow, event) {
	//only do this when not running in data sutra
	if (!application.__parent__.solutionPrefs) {
		FILTER_records(event)
	}
	//don't run in headless or web client (they use whatever solution is activated as context)
	else if ((application.getApplicationType() == APPLICATION_TYPES.SMART_CLIENT || application.getApplicationType() == APPLICATION_TYPES.RUNTIME_CLIENT) &&
		//don't run if in a preload
		!(application.__parent__.solutionPrefs && solutionPrefs.config.prefs.formPreloading)) {

		if (!utils.hasRecords(foundset)) {
			//make sure that doesn't lock us out of left-side lists
			if (solutionPrefs.config.activeSpace == 'workflow') {
				solutionPrefs.config.activeSpace = 'standard'
			}

			globals.WEB_lock_workflow(true)

			//there are records in the pages used on list, clear
			if (utils.hasRecords(forms.WEB_0F_asset_1L_page.foundset)) {
				forms.WEB_0F_asset_1L_page.foundset.clear()
			}
		}
	}
}

/**
 * Handle hide window.
 *
 * @param {JSEvent} event the event that triggered the action
 *
 * @returns {Boolean}
 *
 * @properties={typeid:24,uuid:"6F9735E5-4802-4370-9526-80C07653820B"}
 */
function FORM_on_hide(event) {
	if (application.__parent__.solutionPrefs && solutionPrefs.design.statusLockWorkflow && !solutionPrefs.config.prefs.formPreloading) {
		globals.WEB_lock_workflow(false)
	}

	return true
}

/**
 * @param	{Integer}	assetType What type of asset are we working with
 *
 * @properties={typeid:24,uuid:"69916907-339D-4989-A21B-A53DD115E194"}
 */
function MAP_asset(assetType) {
	switch (assetType) {
		case 1:	//images
			return forms.WEB_0F_asset__image.INIT_asset()
			break
		case 2:	//files
			return forms.WEB_0F_asset__file.INIT_asset()
			break
	}
}

/**
 * Perform the element default action.
 *
 * @param {JSEvent} event the event that triggered the action
 *
 * @properties={typeid:24,uuid:"750A29D4-2647-475B-BA2F-B86562F6C9B2"}
 */
function TAB_change(event) {
	globals.TAB_change_grid(null,null,'tab_list','tab_l')

	elements.btn_tag_add.visible = elements.tab_list.tabIndex == 2
	elements.btn_tag_delete.visible = elements.tab_list.tabIndex == 2
}

/**
 * Handle record selected.
 *
 * @param {JSEvent} event the event that triggered the action
 *
 * @properties={typeid:24,uuid:"49E7AA78-EDBA-4820-BD16-BDB92BD63793"}
 */
function REC_on_select(event) {
	//disable select method when new asset created
	if (!_skipSelect) {
		//show appropriate buttons on asset instance list
		forms.WEB_0F_asset_1F.TOGGLE_elements(asset_type == 3)

		var fsPages = forms.WEB_0F_asset_1L_page.foundset

		//there is something to do on this page
		if (utils.hasRecords(foundset) && utils.hasRecords(web_asset_to_asset_instance)) {
			globals.CODE_cursor_busy(true)
			var args = [1,'id_asset_instance']

			var query =
	"SELECT DISTINCT c.id_page FROM web_platform a, web_version b, web_page c WHERE b.id_version IN ( \
		SELECT DISTINCT c.id_version from web_block a, web_scope b, web_area c, web_block_version d, web_block_data e WHERE \
		c.id_area = b.id_area AND \
		b.id_block = a.id_block AND \
		d.id_block = a.id_block AND \
		e.id_block_version = d.id_block_version AND \
		d.flag_active = ? AND \
		e.data_key = ? AND \
		e.data_value IN ("
			for (var i = 1; i <= web_asset_to_asset_instance.getSize(); i++) {
				var record = web_asset_to_asset_instance.getRecord(i)
				//build up query
				query += '?'
				if (i < web_asset_to_asset_instance.getSize()) {
					query += ','
				}
				//tack on to arguments
				args.push(record.id_asset_instance.toString())
			}
	query += ") \
	) AND \
		a.id_platform = b.id_platform AND \
		a.id_page = c.id_page"

			var dataset = databaseManager.getDataSetByQuery(
						'sutra_cms',
						query,
						args,
						-1
					)

			//load correct pages that this is used on
			fsPages.loadRecords(dataset)

			globals.CODE_cursor_busy(false)
		}
		//clear out the related pages link
		else {
			fsPages.clear()
		}
	}
}
<commit_msg>error check for when deleting asset record and no asset instances remaining<commit_after>/**
 * @type {String}
 *
 * @properties={typeid:35,uuid:"04fde543-69cc-4de9-af47-7f7c22221f26"}
 */
var _license_dsa_mosaic_WEB_cms = 'Module: _dsa_mosaic_WEB_cms \
									Copyright (C) 2011-2013 Data Mosaic \
									MIT Licensed';

/**
 * @type {Boolean}
 *
 * @properties={typeid:35,uuid:"1637C97D-08E7-4019-813B-FF8A07B35AB6",variableType:-4}
 */
var _skipSelect = false;

/**
 *
 * @properties={typeid:24,uuid:"022C11EE-D472-44B4-88EA-873A195E7136"}
 */
function REC_delete() {
	var input = globals.DIALOGS.showWarningDialog(
						'Delete',
						'Do you really want to delete this record?',
						'Yes',
						'No'
					)

	if (input == 'Yes') {
		//delete all assets when not a group
		if (asset_type != 3 && utils.hasRecords(web_asset_to_asset_instance)) {
			//grab directory name
			var directory = web_asset_to_asset_instance__initial.asset_directory
			var baseDirectory = forms.WEB_0F_install.ACTION_get_install() +
					'/application_server/server/webapps/ROOT/sutraCMS/sites/' +
					forms.WEB_0F_site.directory
			var deleteThis		= {}
			deleteThis.directory	 	= baseDirectory + '/' + directory

			for (var i = 1; i <= web_asset_to_asset_instance.getSize(); i++) {
				forms.WEB_0F_asset_1F_2L_asset_instance.REC_delete(null,true,forms.WEB_0F_asset_1F_2L_asset_instance.foundset.getRecord(i))
			}

		//delete directory
			// developer version (use local file system method since headless client plugin bugged)
			if ( application.isInDeveloper() ) {
				forms.WEB_0C__file_stream.ASSET_delete(deleteThis)
			}
			// file streaming version when on a service
			else {
				var jsclient = plugins.headlessclient.createClient("_dsa_mosaic_WEB_cms", null, null, null)
				jsclient.queueMethod("WEB_0C__file_stream", "ASSET_delete", [deleteThis], null)
			}
		}

		controller.deleteRecord()

		//dim out the lights
		if (!utils.hasRecords(foundset)) {
			FORM_on_show()
		}
	}
}

/**
 * Perform the element default action.
 *
 * @param {JSEvent} event the event that triggered the action
 *
 * @properties={typeid:24,uuid:"0DFCEC6C-DF14-4E2B-BE6A-A5F986F8375C"}
 */
function TAG_add(event) {
	if (utils.hasRecords(foundset)) {
		//turn autosave off
		databaseManager.setAutoSave(false)

		forms.WEB_P_tag__add._callingForm = controller.getName()

		globals.CODE_form_in_dialog(
					forms.WEB_P_tag__add,
					400,-1,-1,-1,
					'Tags',
					true,
					false,
					'tagAdd'
				)
	}
	else {
		globals.DIALOGS.showErrorDialog(
						'Error',
						'There is no record to add tags to'
					)
	}
}

/**
 * Perform the element default action.
 *
 * @param {JSEvent} event the event that triggered the action
 *
 * @properties={typeid:24,uuid:"8372B4E8-DA55-4B6A-8F4F-4B7C787F286C"}
 */
function TAG_delete(event) {
	if (utils.hasRecords(foundset)) {
		//turn autosave off
		databaseManager.setAutoSave(false)

		forms.WEB_P_tag__remove._callingForm = controller.getName()

		globals.CODE_form_in_dialog(
					forms.WEB_P_tag__remove,
					400,-1,-1,-1,
					'Tags',
					true,
					false,
					'tagDelete'
				)
	}
	else {
		globals.DIALOGS.showErrorDialog(
						'Error',
						'There is no record to remove tags from'
					)
	}

}

/**
 *
 * @properties={typeid:24,uuid:"FF5AF14C-E836-4D15-897E-FC174AA6C371"}
 */
function REC_new(assetType) {
	var input = globals.DIALOGS.showSelectDialog(
					"Asset",
					"Select asset type",
					"Image",
					"File",
					"Group"
				)

	//something selected, do the right kind of import
	switch ( input  ) {
		case 'Image':
			forms.WEB_0C__file_stream.IMAGE_import("images")
			break
		case 'File':
			forms.WEB_0C__file_stream.FILE_import("files")
			break
		case 'Group':
			// create asset record
			var fsAsset = foundset
			//disable on select method
			_skipSelect = true

			var assetRec = fsAsset.getRecord(fsAsset.newRecord(true,true))
			assetRec.id_site = forms.WEB_0F_site.id_site
			assetRec.asset_type = 3

			//enable on select method
			_skipSelect = false
			REC_on_select()
			break
	}
}

/**
 * Callback method when form is (re)loaded.
 *
 * @param {JSEvent} event the event that triggered the action
 *
 * @properties={typeid:24,uuid:"CFCBF7B5-C038-4D04-AFF3-41AEA18ED580"}
 * @AllowToRunInFind
 */
function FILTER_records(event) {
	//find stuff for the selected site
	if (utils.hasRecords(forms.WEB_0F_site.foundset)) {
		foundset.find()
		foundset.id_site = forms.WEB_0F_site.id_site
		var results = foundset.search()
	}
	else {
		foundset.clear()
	}
}

/**
 * Callback method for when form is shown.
 *
 * @param {Boolean} firstShow form is shown first time after load
 * @param {JSEvent} event the event that triggered the action
 *
 * @properties={typeid:24,uuid:"16C7820E-528E-495C-A409-E0EA923E2429"}
 */
function FORM_on_show(firstShow, event) {
	//only do this when not running in data sutra
	if (!application.__parent__.solutionPrefs) {
		FILTER_records(event)
	}
	//don't run in headless or web client (they use whatever solution is activated as context)
	else if ((application.getApplicationType() == APPLICATION_TYPES.SMART_CLIENT || application.getApplicationType() == APPLICATION_TYPES.RUNTIME_CLIENT) &&
		//don't run if in a preload
		!(application.__parent__.solutionPrefs && solutionPrefs.config.prefs.formPreloading)) {

		if (!utils.hasRecords(foundset)) {
			//make sure that doesn't lock us out of left-side lists
			if (solutionPrefs.config.activeSpace == 'workflow') {
				solutionPrefs.config.activeSpace = 'standard'
			}

			globals.WEB_lock_workflow(true)

			//there are records in the pages used on list, clear
			if (utils.hasRecords(forms.WEB_0F_asset_1L_page.foundset)) {
				forms.WEB_0F_asset_1L_page.foundset.clear()
			}
		}
	}
}

/**
 * Handle hide window.
 *
 * @param {JSEvent} event the event that triggered the action
 *
 * @returns {Boolean}
 *
 * @properties={typeid:24,uuid:"6F9735E5-4802-4370-9526-80C07653820B"}
 */
function FORM_on_hide(event) {
	if (application.__parent__.solutionPrefs && solutionPrefs.design.statusLockWorkflow && !solutionPrefs.config.prefs.formPreloading) {
		globals.WEB_lock_workflow(false)
	}

	return true
}

/**
 * @param	{Integer}	assetType What type of asset are we working with
 *
 * @properties={typeid:24,uuid:"69916907-339D-4989-A21B-A53DD115E194"}
 */
function MAP_asset(assetType) {
	switch (assetType) {
		case 1:	//images
			return forms.WEB_0F_asset__image.INIT_asset()
			break
		case 2:	//files
			return forms.WEB_0F_asset__file.INIT_asset()
			break
	}
}

/**
 * Perform the element default action.
 *
 * @param {JSEvent} event the event that triggered the action
 *
 * @properties={typeid:24,uuid:"750A29D4-2647-475B-BA2F-B86562F6C9B2"}
 */
function TAB_change(event) {
	globals.TAB_change_grid(null,null,'tab_list','tab_l')

	elements.btn_tag_add.visible = elements.tab_list.tabIndex == 2
	elements.btn_tag_delete.visible = elements.tab_list.tabIndex == 2
}

/**
 * Handle record selected.
 *
 * @param {JSEvent} event the event that triggered the action
 *
 * @properties={typeid:24,uuid:"49E7AA78-EDBA-4820-BD16-BDB92BD63793"}
 */
function REC_on_select(event) {
	//disable select method when new asset created
	if (!_skipSelect) {
		//show appropriate buttons on asset instance list
		forms.WEB_0F_asset_1F.TOGGLE_elements(asset_type == 3)

		var fsPages = forms.WEB_0F_asset_1L_page.foundset

		//there is something to do on this page
		if (utils.hasRecords(foundset) && utils.hasRecords(web_asset_to_asset_instance)) {
			globals.CODE_cursor_busy(true)
			var args = [1,'id_asset_instance']

			var query =
	"SELECT DISTINCT c.id_page FROM web_platform a, web_version b, web_page c WHERE b.id_version IN ( \
		SELECT DISTINCT c.id_version from web_block a, web_scope b, web_area c, web_block_version d, web_block_data e WHERE \
		c.id_area = b.id_area AND \
		b.id_block = a.id_block AND \
		d.id_block = a.id_block AND \
		e.id_block_version = d.id_block_version AND \
		d.flag_active = ? AND \
		e.data_key = ? AND \
		e.data_value IN ("
			for (var i = 1; i <= web_asset_to_asset_instance.getSize(); i++) {
				var record = web_asset_to_asset_instance.getRecord(i)
				//build up query
				query += '?'
				if (i < web_asset_to_asset_instance.getSize()) {
					query += ','
				}
				//tack on to arguments
				args.push(record.id_asset_instance.toString())
			}
	query += ") \
	) AND \
		a.id_platform = b.id_platform AND \
		a.id_page = c.id_page"

			var dataset = databaseManager.getDataSetByQuery(
						'sutra_cms',
						query,
						args,
						-1
					)

			//load correct pages that this is used on
			fsPages.loadRecords(dataset)

			globals.CODE_cursor_busy(false)
		}
		//clear out the related pages link
		else {
			fsPages.clear()
		}
	}
}
<|endoftext|>


<commit_before>var fs = require( 'fs' );
var readline = require( 'readline' );
var path = require( 'path' );
var Emitter = require( 'events' ).EventEmitter;

var FTPClient = require( 'ftp' );
var appUtil = require( './util' );

var ftpClient = new FTPClient();
var emitter = new Emitter();

var defaultConnConfig = {
    port : 21
};

var uploader = {

    init : function ( config, setting ) {

        this.config = config || {};
        this.setting = setting || {};
    },

    ftpUpload : function ( fileNames ) {

        if ( !Array.isArray( fileNames ) ) {
            fileNames = [ fileNames ];
        }

        fileNames = fileNames.map( function ( fileName ) {

            return fileName.replace( this.config.build_dir, '' ).replace( /^\//, '' );

        }.bind( this ) );

        fileNames = appUtil.unique( fileNames );

        //最后上传字典文件
        fileNames.sort( function ( f1, f2 ) {

            if ( appUtil.isMatch( f1, this.setting.mapFiles ) &&
                    !appUtil.isMatch( f2, this.setting.mapFiles ) ) {

                return 1;
            } else {
                return -1;
            }
        }.bind( this ) );

        var uploadedN = 0;

        var connConfig = appUtil.applyIf( this.config.uploader.ftp || {}, defaultConnConfig );

        ftpClient.connect( connConfig );

        ftpClient.on( 'ready', function () {

            console.log( 'ftp连接成功...' );

            var i = 1, len = fileNames.length;
            var fileName = fileNames[ 0 ];

            emitter.on( 'success', function () {

                if ( i < len ) {

                    fileName = fileNames[ i++ ];
                    this.ftpUploadOne( fileName );

                } else {
                    ftpClient.end();

                    console.log( 'ftp断开连接成功...' );

                    emitter.emit( 'done' );
                }
            }.bind( this ) );

            this.ftpUploadOne( fileName );

        }.bind( this ) );
    },

    tFtpUpload : function ( fileNames ) {

        if ( !Array.isArray( fileNames ) ) {
            fileNames = [ fileNames ];
        }

        fileNames = fileNames.map( function ( fileName ) {

            return fileName.replace( this.config.build_dir, '' ).replace( /^\//, '' );

        }.bind( this ) );

        fileNames = appUtil.unique( fileNames );

        //最后上传字典文件
        fileNames.sort( function ( f1, f2 ) {

            if ( appUtil.isMatch( f1, this.setting.mapFiles ) &&
                    !appUtil.isMatch( f2, this.setting.mapFiles ) ) {

                return 1;
            } else {
                return -1;
            }
        }.bind( this ) );

        var uploadedN = 0;

        var connConfig = appUtil.applyIf( this.config.uploader.tFtp || {}, defaultConnConfig );

        ftpClient.connect( connConfig );

        ftpClient.on( 'ready', function () {

            console.log( 'ftp连接成功...' );

            ftpClient.cwd( connConfig.cwd, function () {

                var i = 1, len = fileNames.length;
                var fileName = fileNames[ 0 ];

                emitter.on( 'success', function () {

                    if ( i < len ) {

                        fileName = fileNames[ i++ ];
                        this.ftpUploadOne( fileName );

                    } else {
                        ftpClient.end();
                        console.log( 'ftp断开连接成功...' );
                        emitter.emit( 'done' );
                    }
                }.bind( this ) );

                this.ftpUploadOne( fileName );

            }.bind( this ) );

        }.bind( this ) );
    },

    ftpUploadOne : function ( fileName ) {

        var realeseFileName = path.resolve( this.config.build_dir, fileName );
        var dir = path.dirname( fileName );

        dir = path.join( dir, '/' );

        ftpClient.mkdir( dir, true, function ( err ) {

            if ( err ) {
                console.log( err );
                ftpClient.end();
                process.exit( 1 );
            }

            //ftpClient.put( fs.readFileSync( realeseFileName ), fileName, function ( err ) {
            ftpClient.put( fs.createReadStream( realeseFileName ), fileName, function ( err ) {

                if ( err ) {
                    console.log( err );
                    ftpClient.end();
                    process.exit( 1 );
                }
                console.log( fileName + ' 上传成功' );
                emitter.emit( 'success' );
            } );
        } );
    }
};

module.exports = uploader;
<commit_msg>add log<commit_after>var fs = require( 'fs' );
var readline = require( 'readline' );
var path = require( 'path' );
var Emitter = require( 'events' ).EventEmitter;

var FTPClient = require( 'ftp' );
var appUtil = require( './util' );

var ftpClient = new FTPClient();
var emitter = new Emitter();

var defaultConnConfig = {
    port : 21
};

var uploader = {

    init : function ( config, setting ) {

        this.config = config || {};
        this.setting = setting || {};
    },

    ftpUpload : function ( fileNames ) {

        if ( !Array.isArray( fileNames ) ) {
            fileNames = [ fileNames ];
        }

        fileNames = fileNames.map( function ( fileName ) {

            return fileName.replace( this.config.build_dir, '' ).replace( /^\//, '' );

        }.bind( this ) );

        fileNames = appUtil.unique( fileNames );

        //最后上传字典文件
        fileNames.sort( function ( f1, f2 ) {

            if ( appUtil.isMatch( f1, this.setting.mapFiles ) &&
                    !appUtil.isMatch( f2, this.setting.mapFiles ) ) {

                return 1;
            } else {
                return -1;
            }
        }.bind( this ) );

        var uploadedN = 0;

        var connConfig = appUtil.applyIf( this.config.uploader.ftp || {}, defaultConnConfig );

        ftpClient.connect( connConfig );

        ftpClient.on( 'ready', function () {

            console.log( 'ftp连接成功(' + connConfig.host + ')... ' );

            var i = 1, len = fileNames.length;
            var fileName = fileNames[ 0 ];

            emitter.on( 'success', function () {

                if ( i < len ) {

                    fileName = fileNames[ i++ ];
                    this.ftpUploadOne( fileName );

                } else {
                    ftpClient.end();

                    console.log( 'ftp断开连接成功...' );

                    emitter.emit( 'done' );
                }
            }.bind( this ) );

            this.ftpUploadOne( fileName );

        }.bind( this ) );
    },

    tFtpUpload : function ( fileNames ) {

        if ( !Array.isArray( fileNames ) ) {
            fileNames = [ fileNames ];
        }

        fileNames = fileNames.map( function ( fileName ) {

            return fileName.replace( this.config.build_dir, '' ).replace( /^\//, '' );

        }.bind( this ) );

        fileNames = appUtil.unique( fileNames );

        //最后上传字典文件
        fileNames.sort( function ( f1, f2 ) {

            if ( appUtil.isMatch( f1, this.setting.mapFiles ) &&
                    !appUtil.isMatch( f2, this.setting.mapFiles ) ) {

                return 1;
            } else {
                return -1;
            }
        }.bind( this ) );

        var uploadedN = 0;

        var connConfig = appUtil.applyIf( this.config.uploader.tFtp || {}, defaultConnConfig );

        ftpClient.connect( connConfig );

        ftpClient.on( 'ready', function () {

            console.log( 'ftp连接成功(' + connConfig.host + ')... ' );

            ftpClient.cwd( connConfig.cwd, function () {

                var i = 1, len = fileNames.length;
                var fileName = fileNames[ 0 ];

                emitter.on( 'success', function () {

                    if ( i < len ) {

                        fileName = fileNames[ i++ ];
                        this.ftpUploadOne( fileName );

                    } else {
                        ftpClient.end();
                        console.log( 'ftp断开连接成功...' );
                        emitter.emit( 'done' );
                    }
                }.bind( this ) );

                this.ftpUploadOne( fileName );

            }.bind( this ) );

        }.bind( this ) );
    },

    ftpUploadOne : function ( fileName ) {

        var realeseFileName = path.resolve( this.config.build_dir, fileName );
        var dir = path.dirname( fileName );

        dir = path.join( dir, '/' );

        ftpClient.mkdir( dir, true, function ( err ) {

            if ( err ) {
                console.log( err );
                ftpClient.end();
                process.exit( 1 );
            }

            console.log( fileName + '正在上传...' );
            //ftpClient.put( fs.readFileSync( realeseFileName ), fileName, function ( err ) {
            ftpClient.put( fs.createReadStream( realeseFileName ), fileName, function ( err ) {

                if ( err ) {
                    console.log( err );
                    ftpClient.end();
                    process.exit( 1 );
                }
                console.log( fileName + ' 上传成功' );
                emitter.emit( 'success' );
            } );
        } );
    }
};

module.exports = uploader;
<|endoftext|>