<commit_before>const express = require('express');
const User = require('../models').User;
const Errors = require('../lib/errors');

const router = express.Router({ mergeParams: true });

/**
 * @api {get} /users Get all users
 * @apiName GetUsers
 * @apiGroup Users
 * @apiVersion 0.1.0
 */
router.get('/', (req, res, next) => {
  next(new Errors.Generic('Not implemented'));
});

/**
 * @api {get} /users/:userId Get specific user
 * @apiName GetUsersId
 * @apiGroup Users
 * @apiVersion 0.1.0
 */
router.get('/:userId', (req, res, next) => {
  next(new Errors.Generic('Not implemented'));
});

module.exports = router;

<commit_msg>Created basic implementation of user fetch<commit_after>const express = require('express');
const User = require('../models').User;
const Errors = require('../lib/errors');

const router = express.Router({ mergeParams: true });

/**
 * @api {get} /users Get all users
 * @apiName GetUsers
 * @apiGroup Users
 * @apiVersion 0.1.0
 *
 * @apiParam  {String}  name
 * @apiParam  {String}  email
 *
 * @apiSuccess  {Object[]}  users
 * @apiSuccess  {String}    users.name
 * @apiSuccess  {String}    users.email
 * @apiSuccess  {String}    users.googleId
 * @apiSuccess  {String}    users.picture
 *
 * @apiUse UnauthorizedError
 *
 * @apiPermission user
 */
router.get('/', (req, res, next) => {
  if (!req.session.user) {
    next(new Errors.Unauthorized());
  } else {
    const options = {};

    if (req.body.email) {
      options.email = req.body.email;
    }

    if (req.body.name) {
      options.name = req.body.name;
    }

    User.find(options)
      .then((users) => {
        res.body = users;
        next();
      })
      .catch(next);
  }
});

/**
 * @api {get} /users/:userId Get specific user
 * @apiName GetUsersId
 * @apiGroup Users
 * @apiVersion 0.1.0
 *
 * @apiParam  {String}  userId
 *
 * @apiSuccess  {String}  name
 * @apiSuccess  {String}  email
 * @apiSuccess  {String}  googleId
 * @apiSuccess  {String}  picture
 *
 * @apiUse UnauthorizedError
 *
 * @apiPermission user
 */
router.get('/:userId', (req, res, next) => {
  if (!req.session.user) {
    next(new Errors.Unauthorized());
  } else {
    User.findById(req.params.userId)
      .then((user) => {
        res.body = user;
        next();
      })
      .catch(next);
  }
});

module.exports = router;

<|endoftext|>


<commit_before>
sitemaps.add('/reports.xml', function() {
  var out = [], reports = Reports.find({}).fetch();
  _.each(reports, function(report) {
    out.push({
      page: 'rapport/' + report._id + '/' + slugify(report.project.name),
      lastmod: new Date(2014, 6, 20, 0, 0, 0, 0)
    });
  });
  return out;
});

sitemaps.add('sitemap.xml', function() {
  return [
    {page: 'om/', lastmod: new Date(2014, 6, 20, 0, 0, 0, 0) },
    {page: 'kriterier/', lastmod: new Date(2014, 6, 20, 0, 0, 0, 0) },
    {page: 'rapporter/side/1', lastmod: new Date(2014, 6, 20, 0, 0, 0, 0) }
  ];
})
<commit_msg>Typo.<commit_after>
sitemaps.add('/reports.xml', function() {
  var out = [], reports = Reports.find({}).fetch();
  _.each(reports, function(report) {
    out.push({
      page: 'rapport/' + report._id + '/' + slugify(report.project.name),
      lastmod: new Date(2014, 6, 20, 0, 0, 0, 0)
    });
  });
  return out;
});

sitemaps.add('/sitemap.xml', function() {
  return [
    {page: 'om/', lastmod: new Date(2014, 6, 20, 0, 0, 0, 0) },
    {page: 'kriterier/', lastmod: new Date(2014, 6, 20, 0, 0, 0, 0) },
    {page: 'rapporter/side/1', lastmod: new Date(2014, 6, 20, 0, 0, 0, 0) }
  ];
})
<|endoftext|>


<commit_before>var mongoose = require('mongoose');

// New schema for sms messages sent to users
var UserCurrentChoicesSchema = new mongoose.Schema({
  phone: {
    type: String,
    required: true
  },
  1: {
    type: String,
    required: true
  },
  2: {
    type: String,
    required: true
  },
  3: {
    type: String,
    required: true
  }
});

var UserCurrentChoices = mongoose.model('UserCurrentChoices', UserCurrentChoicesSchema);

module.exports = {
  UserCurrentChoices: UserCurrentChoices
}<commit_msg>added missing semi-colon and blank line at end of document.<commit_after>var mongoose = require('mongoose');

// New schema for sms messages sent to users
var UserCurrentChoicesSchema = new mongoose.Schema({
  phone: {
    type: String,
    required: true
  },
  1: {
    type: String,
    required: true
  },
  2: {
    type: String,
    required: true
  },
  3: {
    type: String,
    required: true
  }
});

var UserCurrentChoices = mongoose.model('UserCurrentChoices', UserCurrentChoicesSchema);

module.exports = {
  UserCurrentChoices: UserCurrentChoices
};
<|endoftext|>


<commit_before>exports = module.exports = function (io) {
  // Set socket.io listeners.
  io.on('connection', (socket) => {
    // console.log('a user connected');

    // On conversation entry, join broadcast channel
    socket.on('enter conversation', (conversation) => {
      socket.join(conversation);
      // console.log('joined ' + conversation);
    });

    socket.on('leave conversation', (conversation) => {
      socket.leave(conversation);
      // console.log('left ' + conversation);
    });

    socket.on('new message', (conversation) => {
      io.sockets.in(conversation).emit('refresh messages', conversation);
    });

    socket.on('disconnect', () => {
      // console.log('user disconnected');
    });
  });
};
<commit_msg>Chat Socket Error handle<commit_after>exports = module.exports = function (io) {
  // Set socket.io listeners.
  io.on('connection', (socket) => {
    // console.log('a user connected');

    // On conversation entry, join broadcast channel
    socket.on('enter conversation', (conversation) => {
      socket.join(conversation);
      // console.log('joined ' + conversation);
    });

    socket.on('leave conversation', (conversation) => {
      socket.leave(conversation);
      // console.log('left ' + conversation);
    });

    socket.on('new message', (conversation) => {
      io.sockets.in(conversation).emit('refresh messages', conversation);
    });

    socket.on('disconnect', () => {
      // console.log('user disconnected');
    });
  });
};
<|endoftext|>


<commit_before>const passport = require('passport');
const Strategy = require('passport-twitter').Strategy;
const express = require('express');
const app = express();
const appSecret = process.env.APP_SECRET || 'oh dear oh dear';
const REDIS = require('redis');
const session = require('express-session');
const RedisStore = require('connect-redis')(session);
const denodeify = require('denodeify');
const extend = require('util')._extend;
const redis = (function () {
	if (process.env.REDISTOGO_URL) {
		const rtg = require('url').parse(process.env.REDISTOGO_URL);
		const redis = REDIS.createClient(rtg.port, rtg.hostname);

		redis.auth(rtg.auth.split(':')[1]);
		return redis;
	} else {
	 	return REDIS.createClient();
	}
}());

const redisGet = denodeify(redis.get).bind(redis);
const redisSet = denodeify(redis.set).bind(redis);

function genIdToProfile(profile) {
	return 'v1.0.1_profile_by_number_' + profile.id;
}

function genUserNameToId(profile) {
	return 'v1.0.0_id_by_username_' + profile.username;
}

function getSummary(profile) {
	return {
		id: profile.id,
		username: profile.username,
		displayName: profile.displayName,
		photos: profile.photos[0]
	};
}

passport.use(new Strategy(
	{
		consumerKey: process.env.CONSUMER_KEY,
		consumerSecret: process.env.CONSUMER_SECRET,
		callbackURL: global.serverUrl + '/auth/twitter/return'
	},
	function(token, tokenSecret, profile, cb) {

		redisGet(genIdToProfile(profile))
		.then(data => JSON.parse(data))
		.then(inProfile => {
			if (inProfile) {

				// Old User update profile with new Data
				extend(inProfile, profile);
				redisSet(genIdToProfile(profile), JSON.stringify(inProfile));
				return JSON.parse(inProfile);
			} else {

				//New user
				return profile;
			}
		})
		.then(profile => {

			// Update map of user names to profile ids
			redisSet(genUserNameToId(profile), profile.id);

			// Update profile with new data from auth
			return cb(null, profile);
		});
	}
));

passport.serializeUser(function(user, cb) {
	cb(null, user.id);
});

passport.deserializeUser(function(id, cb) {
	redisGet(genIdToProfile({id}))
	.then(data => JSON.parse(data))
	.catch(e => console.log(e))
	.then(user => {
		cb(null, getSummary(user));
	});
});

// Use application-level middleware for common functionality, including
// logging, parsing, and session handling.
app.use(require('morgan')('combined'));
app.use(require('cookie-parser')());
app.use(require('body-parser').urlencoded({ extended: true }));
app.use(require('express-session')({
	secret: appSecret,
	resave: true,
	saveUninitialized: true,
	store: new RedisStore({
		client : redis
	})
}));

// Initialize Passport and restore authentication state, if any, from the
// session.
app.use(passport.initialize());
app.use(passport.session());

app.get('/auth/twitter', passport.authenticate('twitter'));

app.get('/auth/twitter/return',
	passport.authenticate('twitter', { failureRedirect: '/' }),
	function(req, res) {
		res.redirect('/');
	}
);

app.get('/auth/profile',
	require('connect-ensure-login').ensureLoggedIn('/auth/twitter'),
	function(req, res){
		res.json('profile', { user: req.user });
	}
);

app.get('/auth/logout', function (req, res) {
	req.logout();
	res.redirect('/');
});

module.exports = app;
<commit_msg>wor quirk quirk<commit_after>const passport = require('passport');
const Strategy = require('passport-twitter').Strategy;
const express = require('express');
const app = express();
const appSecret = process.env.APP_SECRET || 'oh dear oh dear';
const REDIS = require('redis');
const session = require('express-session');
const RedisStore = require('connect-redis')(session);
const denodeify = require('denodeify');
const extend = require('util')._extend;
const redis = (function () {
	if (process.env.REDISTOGO_URL) {
		const rtg = require('url').parse(process.env.REDISTOGO_URL);
		const redis = REDIS.createClient(rtg.port, rtg.hostname);

		redis.auth(rtg.auth.split(':')[1]);
		return redis;
	} else {
	 	return REDIS.createClient();
	}
}());

const redisGet = denodeify(redis.get).bind(redis);
const redisSet = denodeify(redis.set).bind(redis);

function genIdToProfile(profile) {
	return 'v1.0.1_profile_by_number_' + profile.id;
}

function genUserNameToId(profile) {
	return 'v1.0.0_id_by_username_' + profile.username;
}

function getSummary(profile) {
	return {
		id: profile.id,
		username: profile.username,
		displayName: profile.displayName,
		photos: profile.photos[0]
	};
}

passport.use(new Strategy(
	{
		consumerKey: process.env.CONSUMER_KEY,
		consumerSecret: process.env.CONSUMER_SECRET,
		callbackURL: global.serverUrl + '/auth/twitter/return'
	},
	function(token, tokenSecret, profile, cb) {

		redisGet(genIdToProfile(profile))
		.then(data => JSON.parse(data))
		.then(inProfile => {
			if (inProfile) {

				// Old User update profile with new Data
				extend(inProfile, profile);
				redisSet(genIdToProfile(profile), JSON.stringify(inProfile));
				return JSON.parse(inProfile);
			} else {

				//New user
				return profile;
			}
		})
		.then(profile => {

			// Update map of user names to profile ids
			redisSet(genUserNameToId(profile), profile.id);

			// Update profile with new data from auth
			return cb(null, profile);
		});
	}
));

passport.serializeUser(function(user, cb) {
	cb(null, user.id);
});

passport.deserializeUser(function(id, cb) {
	redisGet(genIdToProfile({id}))
	.then(data => JSON.parse(data))
	.catch(e => console.log(e))
	.then(user => {
		cb(null, getSummary(user));
	});
});

// Use application-level middleware for common functionality, including
// logging, parsing, and session handling.
app.use(require('morgan')('combined'));
app.use(require('cookie-parser')());
app.use(require('body-parser').urlencoded({ extended: true }));
app.use(require('express-session')({
	secret: appSecret,
	resave: true,
	saveUninitialized: true,
	store: new RedisStore({
		client : redis
	})
}));

// Initialize Passport and restore authentication state, if any, from the
// session.
app.use(passport.initialize());
app.use(passport.session());

app.get('/auth/twitter', passport.authenticate('twitter'));

app.get('/auth/twitter/return',
	passport.authenticate('twitter', { failureRedirect: '/' }),
	function(req, res) {
		res.redirect('/');
	}
);

app.get('/auth/profile',
	require('connect-ensure-login').ensureLoggedIn('/auth/twitter'),
	function(req, res){
		res.json({ user: req.user });
	}
);

app.get('/auth/badend',
	require('connect-ensure-login').ensureLoggedIn('/auth/twitter'),
	function(req, res){
		redisGet(genIdToProfile(req.user.id))
		.then(str => JSON.parse(str))
		.then(profile => {
			res.json(profile);
		});
	}
);

app.get('/auth/logout', function (req, res) {
	req.logout();
	res.redirect('/');
});

module.exports = app;
<|endoftext|>


<commit_before>'use strict';

var S = require('string');
S.extendPrototype();
var n = require('numeral')();
var _ = require('lodash');
var parties = require('uk-political-parties');
var debug = require('debug')('filters');
var d3 = require('d3');

exports.times = function(val, num) {
  return S(val).times(num).s;
};

exports.add = function(val, num) {
  var u = Number(num);
  if (!_.isNumber(u)) return num.toString();
  return n.value(val).add(u);
};

exports.subtract = function(val, num) {
  var u = Number(num);
  if (!_.isNumber(u)) return num.toString();
  return n.value(val).subtract(u);
};

exports.multiply = function(val, num) {
  var u = Number(num);
  if (!_.isNumber(u)) return num.toString();
  return n.value(val).multiply(u);
};

exports.divide = function(val, num) {
  var u = Number(num);
  if (!_.isNumber(u)) return num.toString();
  return n.value(val).divide(u);
};

exports.format = function(val, format) {
  return n.value(val).format(format);
};

exports.unformat = function(val, format) {
  return n.value(val).unformat(format);
};

exports.zeroFormat = function(val) {
  return n.value(val).zeroFormat();
};

exports.isEmpty = function(value) {
  return _.isEmpty(value);
};

exports.objectValues = function(obj) {
  return _.values(obj);
};

exports.mapValues = function(dict, property) {
  return _.mapValues(dict, property);
};

exports.sample = function(collection, x) {
  return _.sample(collection, x);
};

exports.shuffle = function(collection) {
  return _.shuffle(collection);
};

exports.size = function(collection) {
  return _.size(collection);
};

exports.pluck = function(obj, property) {
  return _.pluck(obj, property);
};

exports.sortBy = function(array, property){
  debug(array, property);
  return _.sortBy(array, property);
};

exports.json = function(obj) {
  return JSON.stringify(obj, null, 0);
};

exports.partyAbbreviation = function(str){
  return parties.shortName(str);
};

exports.partyClassName = function(str){
  return parties.className(str);
};

exports.partyFullName = function(str){
  debug('party -- ', str);
  return parties.fullName(str);
};

exports.ftdate = function(date) {
  var format = d3.time.format("%B %e, %Y %I:%M %p");
  return format(date).replace(/(AM|PM)$/, function($1){
    return $1 ? $1.toLowerCase() : '';
  });
};

exports.change = function(value){
  if(value>0) return '+'+value;
  return value;
};
<commit_msg>Add filters<commit_after>'use strict';

var S = require('string');
S.extendPrototype();
var n = require('numeral')();
var _ = require('lodash');
var parties = require('uk-political-parties');
var debug = require('debug')('filters');
var d3 = require('d3');

exports.times = function(val, num) {
  return S(val).times(num).s;
};

exports.add = function(val, num) {
  var u = Number(num);
  if (!_.isNumber(u)) return num.toString();
  return n.value(val).add(u);
};

exports.subtract = function(val, num) {
  var u = Number(num);
  if (!_.isNumber(u)) return num.toString();
  return n.value(val).subtract(u);
};

exports.multiply = function(val, num) {
  var u = Number(num);
  if (!_.isNumber(u)) return num.toString();
  return n.value(val).multiply(u);
};

exports.divide = function(val, num) {
  var u = Number(num);
  if (!_.isNumber(u)) return num.toString();
  return n.value(val).divide(u);
};

exports.format = function(val, format) {
  return n.value(val).format(format);
};

exports.unformat = function(val, format) {
  return n.value(val).unformat(format);
};

exports.zeroFormat = function(val) {
  return n.value(val).zeroFormat();
};

exports.isEmpty = function(value) {
  return _.isEmpty(value);
};

exports.objectValues = function(obj) {
  return _.values(obj);
};

exports.mapValues = function(dict, property) {
  return _.mapValues(dict, property);
};

exports.sample = function(collection, x) {
  return _.sample(collection, x);
};

exports.shuffle = function(collection) {
  return _.shuffle(collection);
};

exports.size = function(collection) {
  return _.size(collection);
};

exports.pluck = function(obj, property) {
  return _.pluck(obj, property);
};

exports.sortBy = function(array, property){
  debug(array, property);
  return _.sortBy(array, property);
};

exports.json = function(obj) {
  return JSON.stringify(obj, null, 0);
};

exports.partyAbbreviation = function(str){
  return parties.shortName(str);
};

exports.partyClassName = function(str){
  return parties.className(str);
};

exports.partyFullName = function(str){
  return parties.fullName(str);
};

exports.partyShortName = function(str){
  return parties.shortName(str);
};

exports.partyColor = function(str){
  return parties.colour(str);
};

exports.ftdate = function(date) {
  var format = d3.time.format("%B %e, %Y %I:%M %p");
  return format(date).replace(/(AM|PM)$/, function($1){
    return $1 ? $1.toLowerCase() : '';
  });
};

exports.change = function(value){
  if(value>0) return '+'+value;
  return value;
};
<|endoftext|>


<commit_before>var fs = require('fs'),
    winston = require('winston');
    dir = __dirname + '/logs';

if (!fs.existsSync(dir)){
    fs.mkdirSync(dir);
}
winston.emitErrs = true;

var logger = new winston.Logger({
    transports: [
        new winston.transports.File({
            level: 'info',
            filename: __dirname + '/logs/logs.log',
            handleExceptions: true,
            json: true,
            maxsize: 5242880, //5MB
            maxFiles: 5,
            colorize: false
        }),
        new winston.transports.Console({
            level: 'debug',
            handleExceptions: true,
            json: false,
            colorize: true
        })
    ],
    exitOnError: false
});

module.exports = logger;
module.exports.stream = {
    write: function(message, encoding){
        logger.info(message);
    }
};
<commit_msg>logger changes<commit_after>var fs = require('fs'),
    winston = require('winston');
    dir = __dirname + '/logs';

if (!fs.existsSync(dir)){
    fs.mkdirSync(dir);
}
winston.emitErrs = true;

var logger = new winston.Logger({
    transports: [
        new winston.transports.File({
            level: 'info',
            filename: __dirname + '/logs/logs.log',
            handleExceptions: true,
            json: true,
            maxsize: 5242880, //5MB
            maxFiles: 5,
            colorize: false
        }),
        new winston.transports.Console({
            level: 'debug',
            handleExceptions: true,
            json: false,
            colorize: true
        })
    ],
    exitOnError: false
});

module.exports = logger;
module.exports.stream = {
    write: function(message, encoding){
        logger.info(message.slice(0, -1));
    }
};
<|endoftext|>


<commit_before>const http = require('http');
const REQUEST_TIMEOUT = 5 * 1000; // 5-seconds

/**
 * @name ServerRequest
 * @summary Class for handling server requests
 */
class ServerRequest {
  /**
  * @name constructor
  * @summary Class constructor
  * @return {undefined}
  */
  constructor() {
  }

  /**
  * @name send
  * @summary sends an HTTP Request
  * @param {object} options - request options
  * @return {object} promise
  */
  send(options) {
    return new Promise((resolve, reject) => {
      if (options.method === 'POST' || options.method === 'PUT') {
        options.headers['content-length'] = options.body.length;
      } else {
        delete options.body;
      }

      let req = http.request(options, (res) => {
        let response = [];
        res.on('data', (data) => {
          response.push(data);
        });
        res.on('end', () => {
          let buffer = Buffer.concat(response);
          let data = {
            statusCode: res.statusCode,
            headers: res.headers
          };
          data.headers['content-length'] = Buffer.byteLength(buffer);
          data.payLoad = buffer;
          resolve(data);
        });
        res.on('error', (err) => {
          reject(err);
        });
      });

      req.on('socket', (socket) => {
        socket.setNoDelay(true);
        socket.setTimeout(options.timeout * 1000 || REQUEST_TIMEOUT, () => {
          req.abort();
        });
      });

      req.on('error', (err) => {
        reject(err);
      });

      if (options.body) {
        req.write(options.body);
      }
      req.end();
    });
  }
}

module.exports = ServerRequest;
<commit_msg>Correct request body length (#129)<commit_after>const http = require('http');
const REQUEST_TIMEOUT = 5 * 1000; // 5-seconds

/**
 * @name ServerRequest
 * @summary Class for handling server requests
 */
class ServerRequest {
  /**
  * @name constructor
  * @summary Class constructor
  * @return {undefined}
  */
  constructor() {
  }

  /**
  * @name send
  * @summary sends an HTTP Request
  * @param {object} options - request options
  * @return {object} promise
  */
  send(options) {
    return new Promise((resolve, reject) => {
      if (options.method === 'POST' || options.method === 'PUT') {
        options.headers['content-length'] = Buffer.byteLength(options.body, 'utf8');
      } else {
        delete options.body;
      }

      let req = http.request(options, (res) => {
        let response = [];
        res.on('data', (data) => {
          response.push(data);
        });
        res.on('end', () => {
          let buffer = Buffer.concat(response);
          let data = {
            statusCode: res.statusCode,
            headers: res.headers
          };
          data.headers['content-length'] = Buffer.byteLength(buffer);
          data.payLoad = buffer;
          resolve(data);
        });
        res.on('error', (err) => {
          reject(err);
        });
      });

      req.on('socket', (socket) => {
        socket.setNoDelay(true);
        socket.setTimeout(options.timeout * 1000 || REQUEST_TIMEOUT, () => {
          req.abort();
        });
      });

      req.on('error', (err) => {
        reject(err);
      });

      if (options.body) {
        req.write(options.body);
      }
      req.end();
    });
  }
}

module.exports = ServerRequest;
<|endoftext|>


<commit_before>(function() {
    'use strict';

    var spawnify        = require('spawnify'),
        io              = require('socket.io'),
        debug           = require('debug'),
        logConsole      = debug('console'),
        logClients      = debug('console:clients'),

        CWD             = process.cwd(),
        Socket,
        Clients         = [],
        ConNum          = -1;

    module.exports = function(options) {
        var o       = options || {},
            prefix  = o.prefix || '/console';

        if (o.socket)
            Socket = o.socket;
        else if (o.server)
            Socket = io.listen(o.server);
        else
            throw(Error('server or socket should be passed in options!'));

        Socket
            .of(prefix)
            .on('connection', onConnection.bind(null, options));
    };

    function onConnection(options, socket) {
        var msg, onDisconnect, onMessage,
            indexEmpty  = Clients.indexOf(null),
            ERROR_MSG   = 'could not be empty!';

        if (!socket)
            throw(Error('socket ' + ERROR_MSG));

        logClients('add before:', Clients);

        if (indexEmpty >= 0)
            ConNum = indexEmpty;
        else
            ConNum = Clients.length;

        msg = log(ConNum + 1, 'console connected\n');

        socket.emit('data', msg);

        socket.emit('path', options.prompt || CWD);
        socket.emit('prompt');

        Clients[ConNum] = {
            cwd : CWD
        };

        logClients('add after:', Clients);

        onMessage                   = processing.bind(null, socket, ConNum, options),

        onDisconnect                = function(conNum) {
            logClients('remove before:', Clients);

            if (Clients.length !== conNum + 1) {
                Clients[conNum] = null;
            } else {
                Clients.pop();
                --ConNum;
            }

            logClients('remove after:', Clients);

            log(conNum, 'console disconnected');

            socket.removeListener('command', onMessage);
            socket.removeListener('disconnect', onDisconnect);
        }.bind(null, ConNum);

        socket.on('command', onMessage);
        socket.on('disconnect', onDisconnect);
    }

    function processing(socket, conNum, options, command) {
        var func    = options.execute || execute,
            cwd     = function(path) {
                var dir;

                if (path)
                    Clients[conNum].cwd = path;
                else
                    dir = Clients[conNum].cwd;

                return  dir;
            };

        log(conNum, command);

        func(socket, command, cwd);
    }

    function execute(socket, command, cwd) {
        var isDone,
            spawn   = spawnify(command, {
                cwd: cwd()
            }),

            kill    = function() {
                spawn.kill();
            },

            write   = function(data) {
                spawn.write(data);
            };

        socket.on('kill', kill);
        socket.on('write', write);

        spawn.on('error', function(error) {
            isDone = true;

            socket.emit('err', error.message);
        });

        spawn.on('data', function(data) {
            isDone = true;

            socket.emit('data', data);
        });

        spawn.on('path', function(path) {
            isDone = true;

            socket.emit('path', path);
            cwd(path);
        });

        spawn.on('close', function() {
            socket.removeListener('kill', kill);
            socket.removeListener('write', write);

            socket.emit('prompt');

            if (!isDone);
                socket.emit('data', '');
        });
    }

    function log(connNum, str, typeParam) {
        var ret,
            type       = ' ';

        if (str) {

            if (typeParam)
                type  += typeParam + ':';

            ret        = 'client #' + connNum + type + str;
        }

        logConsole(ret);

        return ret;
    }
})();
<commit_msg>feature(console) execute: rm isDone<commit_after>(function() {
    'use strict';

    var spawnify        = require('spawnify'),
        io              = require('socket.io'),
        debug           = require('debug'),
        logConsole      = debug('console'),
        logClients      = debug('console:clients'),

        CWD             = process.cwd(),
        Socket,
        Clients         = [],
        ConNum          = -1;

    module.exports = function(options) {
        var o       = options || {},
            prefix  = o.prefix || '/console';

        if (o.socket)
            Socket = o.socket;
        else if (o.server)
            Socket = io.listen(o.server);
        else
            throw(Error('server or socket should be passed in options!'));

        Socket
            .of(prefix)
            .on('connection', onConnection.bind(null, options));
    };

    function onConnection(options, socket) {
        var msg, onDisconnect, onMessage,
            indexEmpty  = Clients.indexOf(null),
            ERROR_MSG   = 'could not be empty!';

        if (!socket)
            throw(Error('socket ' + ERROR_MSG));

        logClients('add before:', Clients);

        if (indexEmpty >= 0)
            ConNum = indexEmpty;
        else
            ConNum = Clients.length;

        msg = log(ConNum + 1, 'console connected\n');

        socket.emit('data', msg);

        socket.emit('path', options.prompt || CWD);
        socket.emit('prompt');

        Clients[ConNum] = {
            cwd : CWD
        };

        logClients('add after:', Clients);

        onMessage                   = processing.bind(null, socket, ConNum, options),

        onDisconnect                = function(conNum) {
            logClients('remove before:', Clients);

            if (Clients.length !== conNum + 1) {
                Clients[conNum] = null;
            } else {
                Clients.pop();
                --ConNum;
            }

            logClients('remove after:', Clients);

            log(conNum, 'console disconnected');

            socket.removeListener('command', onMessage);
            socket.removeListener('disconnect', onDisconnect);
        }.bind(null, ConNum);

        socket.on('command', onMessage);
        socket.on('disconnect', onDisconnect);
    }

    function processing(socket, conNum, options, command) {
        var func    = options.execute || execute,
            cwd     = function(path) {
                var dir;

                if (path)
                    Clients[conNum].cwd = path;
                else
                    dir = Clients[conNum].cwd;

                return  dir;
            };

        log(conNum, command);

        func(socket, command, cwd);
    }

    function execute(socket, command, cwd) {
        var spawn   = spawnify(command, {
                cwd: cwd()
            }),

            kill    = function() {
                spawn.kill();
            },

            write   = function(data) {
                spawn.write(data);
            };

        socket.on('kill', kill);
        socket.on('write', write);

        spawn.on('error', function(error) {
            socket.emit('err', error.message);
        });

        spawn.on('data', function(data) {
            socket.emit('data', data);
        });

        spawn.on('path', function(path) {
            socket.emit('path', path);
            cwd(path);
        });

        spawn.on('close', function() {
            socket.removeListener('kill', kill);
            socket.removeListener('write', write);

            socket.emit('prompt');
        });
    }

    function log(connNum, str, typeParam) {
        var ret,
            type       = ' ';

        if (str) {

            if (typeParam)
                type  += typeParam + ':';

            ret        = 'client #' + connNum + type + str;
        }

        logConsole(ret);

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


<commit_before>(function() {
    'use strict';

    var DIR             = '../',
        DIR_ROOT        = DIR + '../',
        DIR_SERVER      = './',

        path            = require('path'),
        child_process   = require('child_process'),
        exec            = child_process.exec,
        spawn           = child_process.spawn,

        Util            = require(DIR           + 'util'),
        CloudFunc       = require(DIR           + 'cloudfunc'),

        win             = require(DIR_SERVER    + 'win'),
        update          = require(DIR_SERVER    + 'update'),
        socket          = require(DIR_SERVER    + 'socket'),

        mainpackage     = require(DIR_ROOT      + 'package'),
        CLOUDCMD        = mainpackage.name,

        equalPart       = Util.isContainStrAtBegin,

        ClientFuncs     = [],
        ClientDirs      = [],
        Clients         = [],
        WIN             = process.platform === 'win32',

        addNewLine      = CloudFunc.addNewLine,
        rmNewLine       = CloudFunc.rmNewLine,

        ConNum          = 0,

        CHANNEL         = CloudFunc.CHANNEL_CONSOLE,

        HELP            = {
            stdout  : CLOUDCMD + ' exit     \n' +
                      CLOUDCMD + ' update   \n',
        };

    /**
     * function listen on servers port
     * @pServer {Object} started server object
     */
    exports.init = function() {
        var ret;

        ret = socket.on('connection', function(clientSocket) {
            onConnection(clientSocket, function(json) {
                socket.emit(CHANNEL, json, clientSocket);
            });
        });

        return ret;
    };

    function onConnection(clientSocket, callback) {
        var msg, onDisconnect, onMessage;

        ++ConNum;

        if (!Clients[ConNum]) {
            msg = log(ConNum, 'console connected');

            callback({
                stdout  : addNewLine(msg),
                path    : process.cwd()
            });

            Clients[ConNum]             = true;

            onMessage                   = Util.exec.with(getOnMessage, ConNum, callback);
            onDisconnect                = function(conNum) {
                Clients[conNum]         =
                ClientFuncs[conNum]     = null;

                log(conNum, 'console disconnected');

                socket.removeListener(CHANNEL, onMessage, clientSocket);
                socket.removeListener('disconnect', onDisconnect, clientSocket);
            }.bind(null, ConNum);

            socket.on(CHANNEL, onMessage, clientSocket);
            socket.on('disconnect', onDisconnect, clientSocket);
        } else {
            msg = log(ConNum, ' in use. Reconnecting...\n');

            Util.exec(callback, {
                stdout: msg
            });

            socket.disconnect();
        }
    }

    /**
     * function gets onMessage function
     * that execute needed command
     *
     * @param pConnNum
     * @param callback
     */
    function getOnMessage(connNum, callback, command) {
        var funcExec, firstChar,
            connName, ret,

            isVolume    = win.isChangeVolume(command),
            isCD        = command.match(new RegExp('^cd ')),
            isCDWin     = command.match(new RegExp('^cd ', 'i')),

            symbolsExec = ['*', '&', '{', '}', '|', '\'', '"'],
            isSymbol    = Util.isContainStr(command, symbolsExec),

            CWD         = process.cwd(),
            dir         = ClientDirs[connNum],
            options     = {
                cwd:    dir || CWD
            };

        if (!dir)
            dir = ClientDirs[connNum] = CWD;

        connName = '#' + connNum + ': ';
        Util.log(connName + command);

        if (equalPart(command, CLOUDCMD))
            ret = onCloudCmd(command, callback);
        else if (isCD || isCDWin && WIN || isVolume) {
            ret = true;

            onCD(command, dir, function(error, json) {
                var path  = '';

                if (!error) {
                    path                = json.path;
                    ClientDirs[connNum] = path;
                }

                callback(json);
            });
        }

        if (!ret) {
            if (WIN)
                command    = 'cmd /C ' + command;

            if (!ClientFuncs[connNum])
                ClientFuncs[connNum] = Util.exec.with(setExec, function(json, error, stderr) {
                    log(connNum, error, 'error');
                    log(connNum, stderr, 'stderror');

                    Util.exec(callback, json);
                });

            funcExec        = ClientFuncs[connNum];
            firstChar       = command[0];

            if (firstChar === '#') {
                command     = command.slice(1);
                command     = connName + command;
                command     = addNewLine(command);

                Util.exec(callback, {
                    stdout: command
                }, true);
            } else if (WIN || firstChar === ' ' || isSymbol)
                exec(command, options, funcExec);
            else
                setSpawn(command, options, callback);
        }
    }

    /**
     * function send result of command to client
     * @param callback
     */
    function setExec(callback, error, stdout, stderr) {
        var json,
            errorStr    = '';

        if (stderr)
            errorStr    = stderr;
        else if (error)
            errorStr    = error.message;

        json            = {
            stdout : stdout,
            stderr : errorStr
        };

        Util.exec(callback, json, error, stderr);
    }

    function setSpawn(сommand, options, callback) {
        var cmd, error,
            isSended    = false,
            args        = сommand.split(' '),
            send        = function(error, data) {
                isSended = true;

                callback({
                    stderr: error,
                    stdout: data
                });
            },
            sendError     = function(error) {
                isSended = true;

                send(error, null);
            };

        сommand    = args.shift();

        error       = Util.exec.tryLog(function() {
            cmd = spawn(сommand, args, options);
        });

        if (error) {
            sendError(error);
        } else {
            cmd.stderr.setEncoding('utf8');
            cmd.stdout.setEncoding('utf8');

            cmd.stdout.on('data', function(data) {
                send(null, data);
            });

            cmd.stderr.on('data', function(error) {
                sendError(error);
            });

            cmd.on('error', function(error) {
                var errorStr    = addNewLine(error + '');

                Util.log(error);
                sendError(errorStr);
            });

            cmd.on('close', function () {
                cmd = null;

                if (!isSended)
                    send(null, null);
            });
        }
    }

    function onCloudCmd(command, callback) {
        var is;

        command = Util.rmStr(command, CLOUDCMD);
        is      = !equalPart(command, ' ');

        if (is) {
            Util.exec(callback, HELP);
        } else {
            command = Util.rmStr(command, ' ');
            is  = update && equalPart(command, 'update');

            if (is) {
                update.get();

                Util.exec(callback, {
                    stdout: addNewLine('update: ok')
                });
            }

            is = Util.strCmp(command, 'exit');

            if (is)
                process.exit();
        }

        return is;
    }

     function onCD(command, currDir, callback) {
        var isChangeVolume  = win.isChangeVolume(command),
            isVolume        = win.isVolume(command),
            paramDir        = Util.rmStr(command, 'cd '),
            isRootOrHome    = equalPart(paramDir, ['/', '~']),
            getDir          = WIN ? 'chdir' : 'pwd';

        if (!isRootOrHome && !isChangeVolume || isVolume)
            command     = 'cd ' + path.join(currDir, paramDir);

        exec(command + ' && ' + getDir, {cwd : currDir}, function (error, stdout, stderr) {
            var errorStr    = '';

            if (stderr)
                errorStr    = stderr;
            else if (error)
                errorStr    = error.message;

            callback(error || stderr, {
                stderr  : addNewLine(errorStr),
                path    : rmNewLine(stdout)
            });
        });
    }

    function log(connNum, str, typeParam) {
        var ret,
            type       = ' ';

        if (str) {

            if (typeParam)
                type  += typeParam + ':';

            ret        = 'client #' + connNum + type + str;

            Util.log(ret);
        }

        return ret;
    }
})();
<commit_msg>fix(console) change dir if current dir removed<commit_after>(function() {
    'use strict';

    var DIR             = '../',
        DIR_ROOT        = DIR + '../',
        DIR_SERVER      = './',

        path            = require('path'),
        child_process   = require('child_process'),
        exec            = child_process.exec,
        spawn           = child_process.spawn,

        Util            = require(DIR           + 'util'),
        CloudFunc       = require(DIR           + 'cloudfunc'),

        win             = require(DIR_SERVER    + 'win'),
        update          = require(DIR_SERVER    + 'update'),
        socket          = require(DIR_SERVER    + 'socket'),

        mainpackage     = require(DIR_ROOT      + 'package'),
        CLOUDCMD        = mainpackage.name,

        equalPart       = Util.isContainStrAtBegin,

        ClientFuncs     = [],
        ClientDirs      = [],
        Clients         = [],
        WIN             = process.platform === 'win32',

        addNewLine      = CloudFunc.addNewLine,
        rmNewLine       = CloudFunc.rmNewLine,

        ConNum          = 0,

        CHANNEL         = CloudFunc.CHANNEL_CONSOLE,

        HELP            = {
            stdout  : CLOUDCMD + ' exit     \n' +
                      CLOUDCMD + ' update   \n',
        };

    /**
     * function listen on servers port
     * @pServer {Object} started server object
     */
    exports.init = function() {
        var ret;

        ret = socket.on('connection', function(clientSocket) {
            onConnection(clientSocket, function(json) {
                socket.emit(CHANNEL, json, clientSocket);
            });
        });

        return ret;
    };

    function onConnection(clientSocket, callback) {
        var msg, onDisconnect, onMessage;

        ++ConNum;

        if (!Clients[ConNum]) {
            msg = log(ConNum, 'console connected');

            callback({
                stdout  : addNewLine(msg),
                path    : process.cwd()
            });

            Clients[ConNum]             = true;

            onMessage                   = Util.exec.with(getOnMessage, ConNum, callback);
            onDisconnect                = function(conNum) {
                Clients[conNum]         =
                ClientFuncs[conNum]     = null;

                log(conNum, 'console disconnected');

                socket.removeListener(CHANNEL, onMessage, clientSocket);
                socket.removeListener('disconnect', onDisconnect, clientSocket);
            }.bind(null, ConNum);

            socket.on(CHANNEL, onMessage, clientSocket);
            socket.on('disconnect', onDisconnect, clientSocket);
        } else {
            msg = log(ConNum, ' in use. Reconnecting...\n');

            Util.exec(callback, {
                stdout: msg
            });

            socket.disconnect();
        }
    }

    /**
     * function gets onMessage function
     * that execute needed command
     *
     * @param pConnNum
     * @param callback
     */
    function getOnMessage(connNum, callback, command) {
        var funcExec, firstChar,
            connName, ret,

            isVolume    = win.isChangeVolume(command),
            isCD        = command.match(new RegExp('^cd ')),
            isCDWin     = command.match(new RegExp('^cd ', 'i')),

            symbolsExec = ['*', '&', '{', '}', '|', '\'', '"'],
            isSymbol    = Util.isContainStr(command, symbolsExec),

            CWD         = process.cwd(),
            dir         = ClientDirs[connNum],
            options     = {
                cwd:    dir || CWD
            };

        if (!dir)
            dir = ClientDirs[connNum] = CWD;

        connName = '#' + connNum + ': ';
        Util.log(connName + command);

        if (equalPart(command, CLOUDCMD))
            ret = onCloudCmd(command, callback);
        else if (isCD || isCDWin && WIN || isVolume) {
            ret = true;

            onCD(command, dir, function(error, json) {
                var path  = '';

                if (!error) {
                    path                = json.path;
                    ClientDirs[connNum] = path;
                }

                callback(json);
            });
        }

        if (!ret) {
            if (WIN)
                command    = 'cmd /C ' + command;

            if (!ClientFuncs[connNum])
                ClientFuncs[connNum] = Util.exec.with(setExec, function(json, error, stderr) {
                    log(connNum, error, 'error');
                    log(connNum, stderr, 'stderror');

                    Util.exec(callback, json);
                });

            funcExec        = ClientFuncs[connNum];
            firstChar       = command[0];

            if (firstChar === '#') {
                command     = command.slice(1);
                command     = connName + command;
                command     = addNewLine(command);

                Util.exec(callback, {
                    stdout: command
                }, true);
            } else if (WIN || firstChar === ' ' || isSymbol)
                exec(command, options, funcExec);
            else
                setSpawn(command, options, callback);
        }
    }

    /**
     * function send result of command to client
     * @param callback
     */
    function setExec(callback, error, stdout, stderr) {
        var json,
            errorStr    = '';

        if (stderr)
            errorStr    = stderr;
        else if (error)
            errorStr    = error.message;

        json            = {
            stdout : stdout,
            stderr : errorStr
        };

        Util.exec(callback, json, error, stderr);
    }

    function setSpawn(сommand, options, callback) {
        var cmd, error,
            isSended    = false,
            args        = сommand.split(' '),
            send        = function(error, data) {
                isSended = true;

                callback({
                    stderr: error,
                    stdout: data
                });
            },
            sendError     = function(error) {
                isSended = true;

                send(error, null);
            };

        сommand    = args.shift();

        error       = Util.exec.tryLog(function() {
            cmd = spawn(сommand, args, options);
        });

        if (error) {
            sendError(error);
        } else {
            cmd.stderr.setEncoding('utf8');
            cmd.stdout.setEncoding('utf8');

            cmd.stdout.on('data', function(data) {
                send(null, data);
            });

            cmd.stderr.on('data', function(error) {
                sendError(error);
            });

            cmd.on('error', function(error) {
                var errorStr    = addNewLine(error + '');

                Util.log(error);
                sendError(errorStr);
            });

            cmd.on('close', function () {
                cmd = null;

                if (!isSended)
                    send(null, null);
            });
        }
    }

    function onCloudCmd(command, callback) {
        var is;

        command = Util.rmStr(command, CLOUDCMD);
        is      = !equalPart(command, ' ');

        if (is) {
            Util.exec(callback, HELP);
        } else {
            command = Util.rmStr(command, ' ');
            is  = update && equalPart(command, 'update');

            if (is) {
                update.get();

                Util.exec(callback, {
                    stdout: addNewLine('update: ok')
                });
            }

            is = Util.strCmp(command, 'exit');

            if (is)
                process.exit();
        }

        return is;
    }

     function onCD(command, currDir, callback) {
        var isChangeVolume  = win.isChangeVolume(command),
            isVolume        = win.isVolume(command),
            paramDir        = Util.rmStr(command, 'cd '),
            isRootOrHome    = equalPart(paramDir, ['/', '~']),
            getDir          = WIN ? 'chdir' : 'pwd';

        if (!isRootOrHome && !isChangeVolume || isVolume) {
            paramDir    =  path.join(currDir, paramDir);
            command     = 'cd ' + paramDir;
        }

        exec(command + ' && ' + getDir, {cwd : paramDir}, function (error, stdout, stderr) {
            var errorStr    = '';

            if (stderr)
                errorStr    = stderr;
            else if (error)
                errorStr    = error.message;

            callback(error || stderr, {
                stderr  : addNewLine(errorStr),
                path    : rmNewLine(stdout)
            });
        });
    }

    function log(connNum, str, typeParam) {
        var ret,
            type       = ' ';

        if (str) {

            if (typeParam)
                type  += typeParam + ':';

            ret        = 'client #' + connNum + type + str;

            Util.log(ret);
        }

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


<commit_before>var SECOND = 1000;

exports.register = function User (service, options, next) {

  var userMethods = require('./methods/user')(options, service);

  service.method('user.loginUser', userMethods.login);
  service.method('user.logoutUser', userMethods.logout);

  service.method('user.getUser', require('./methods/getUser'), {
    cache: { expiresIn: 60 * SECOND, segment: '##user' }
  });

  service.method('user.lookupUserByEmail', require('./methods/emailLookup'));

  service.method('user.signupUser', require('./methods/signupUser'));

  service.method('user.saveProfile', require('./methods/saveProfile'));

  service.method('user.changePass', require('./methods/changePass'));

  service.method('user.changeEmail', require('./methods/changeEmail'));

  var sessionMethods = require('./methods/sessions');

  service.method('user.setSession', sessionMethods.set);
  service.method('user.delSession', sessionMethods.del);

  next();
};

exports.register.attributes = {
  pkg: require('./package.json')
};<commit_msg>change profile cache ttl to five minutes<commit_after>var SECOND = 1000;

exports.register = function User (service, options, next) {

  var userMethods = require('./methods/user')(options, service);

  service.method('user.loginUser', userMethods.login);
  service.method('user.logoutUser', userMethods.logout);

  service.method('user.getUser', require('./methods/getUser'), {
    cache: { expiresIn: 5 * 60 * SECOND, segment: '##user' }
  });

  service.method('user.lookupUserByEmail', require('./methods/emailLookup'));

  service.method('user.signupUser', require('./methods/signupUser'));

  service.method('user.saveProfile', require('./methods/saveProfile'));

  service.method('user.changePass', require('./methods/changePass'));

  service.method('user.changeEmail', require('./methods/changeEmail'));

  var sessionMethods = require('./methods/sessions');

  service.method('user.setSession', sessionMethods.set);
  service.method('user.delSession', sessionMethods.del);

  next();
};

exports.register.attributes = {
  pkg: require('./package.json')
};
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');

////////////////////////////////////////////////////////////////////////////////

/**
 *  new Store(options)
 *  - options (Object): Store configuration options. See below.
 *
 *  Creates new store instance.
 *
 *
 *  ##### Options
 *
 *  - `get(keys, params, options, callback(err, results))` (Function):
 *    *REQUIRED* A getter backend
 *  - `set(settings, params, callback(err))` (Function):
 *    *REQUIRED* A setter backend
 **/
function Store(options) {
  options = options || {};

  if (!_.isFunction(options.set) || 3 !== options.set.length) {
    throw "Store set backend is required to be a function with 3 arguments";
  }

  if (!_.isFunction(options.get) || 4 !== options.get.length) {
    throw "Store get backend is required to be a function with 4 arguments";
  }

  this.__set__  = options.set;
  this.__get__  = options.get;
  this.__keys__ = {};
}

/**
 *  Settings.Store#get(keys, params[, options], callback(err, values)) -> Void
 *  - keys (String|Array): Setting key(s)
 *  - params (Object): Params used to get value of a key
 *  - options (Object): Extra options for fine tuning, see below.
 *  - callback (Function): Executed once, everything is done.
 *
 *  Each value is an instance of [[Value]].
 *
 *  ##### Options
 *
 *  - *skipCache* (Boolean): Skip cache and get value from database. Default: false
 *  - *cache* (Object): Cache data, that can be used instead of hitting database.
 *    Ignored if `skipCache` is true.
 **/
Store.prototype.get = function get(keys, params, options, callback) {
  var single = !_.isArray(keys);

  if (!callback) {
    callback = options;
    options  = {};
  }

  this.__get__.call(this, single ? [keys] : keys, params, options, function (err, data) {
    callback(err, single ? data[keys] : data);
  });
};

/**
 *  Settings.Store#set(values, params, callback(err)) -> Void
 *  - values (Object): Key-Value hash of settings
 *  - params (Object): Params used to get value of a key
 *  - value (Mixed): New value for the `key`
 *  - callback (Function): Executed once, everything is done.
 *
 *  Sets new settings values.
 **/
Store.prototype.set = function set(values, params, callback) {
  var err, settings = {};

  _.forEach(values, function (setting, key) {
    if (!_.has(this.__keys__, key)) {
      return; // Skip unregistered setting.
    }

    if (!_.isObject(setting) && !_.isNull(setting)) {
      err = new Error('Setting must be an object or null.');
      return false;
    }

    if (null === setting) {
      settings[key] = null; // i.e. remove setting.
      return; // Continue.
    }

    switch (this.__keys__[key].type) {
    case 'boolean':
      if (!_.isBoolean(setting.value)) {
        err = new Error('Value of ' + key + ' setting must be a boolean.');
        return false;
      }
      break;

    case 'number':
      if (!_.isNumber(setting.value)) {
        err = new Error('Value of ' + key + ' setting must be a number.');
        return false;
      }
      break;

    case 'combobox':
      if (!_.isArray(setting.value)) {
        err = new Error('Value of ' + key + ' setting must be an array.');
        return false;
      }
      break;

    // Except string type otherwise.
    default:
      if (!_.isString(setting.value)) {
        err = new Error('Value of ' + key + ' setting must be a string.');
        return false;
      }
      break;
    }

    settings[key] = { value: setting.value, force: Boolean(setting.force) };
  }, this);

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

  this.__set__.call(this, settings, params, callback);
};

/**
 *  Settings.Store#keys -> Array
 *
 *  List of registered setting keys.
 *
 *
 *  ##### See Also
 *
 *  - [[Settings.Store#addKnownKey]]
 *  - [[Settings.Store#getDefaultValue]]
 **/
Object.defineProperty(Store.prototype, 'keys', {
  get: function () {
    return Object.keys(this.__keys__);
  }
});

/**
 *  Store#addKnownKey(key, type, value) -> Void
 *  - key (String): Setting key
 *  - type (String): Value type used for typecasting upon [[Store#set]]
 *  - value (Mixed): Default setting value
 *
 *  Adds `key` with `type` and its default `value` to be served by the store.
 **/
Store.prototype.addKnownKey = function addKnownKey(key, type, value) {
  this.__keys__[key] = { type: type, value: value };
};

/**
 *  Store#getDefaultValue(key) -> Mixed
 *  - key (String): Setting key
 *
 *  Returns default value for the setting.
 **/
Store.prototype.getDefaultValue = function getDefaultValue(key) {
  return (this.__keys__[key] || {}).value;
};

////////////////////////////////////////////////////////////////////////////////

module.exports = Store;
<commit_msg>Implement `Store#validate` and `Store#validateSetting` methods.<commit_after>'use strict';

var _ = require('lodash');

// Used as default `validate` option for Store constructor. (see below)
//
var defaultSettingsValidator = function (settings) {
  _.forEach(settings, function (setting, key) {
    if (!_.isObject(setting) && !_.isNull(setting)) {
      throw 'Setting must be Object or Null.';
    }

    if (_.isNull(setting)) {
      return; // Ok - nothing more to check here. Check next one.
    }

    if (!_.has(setting, 'value')) {
      throw 'Setting must contain `value` property.';
    }

    if (!_.has(setting, 'force')) {
      throw 'Setting must contain `force` property.';
    }

    if (!_.isBoolean(setting.force)) {
      throw "Setting's `force` property must be Boolean.";
    }

    var err = this.validateSetting(key, setting.value);

    if (null !== err) {
      throw err;
    }
  }, this);
};

/**
 *  new Store(options)
 *  - options (Object): Store configuration options. See below.
 *
 *  Creates new store instance.
 *
 *
 *  ##### Options
 *
 *  - `get(keys, params, options, callback(err, results))` (Function):
 *    *REQUIRED* A getter backend
 *
 *  - `set(settings, params, callback(err))` (Function):
 *    *REQUIRED* A setter backend
 *
 *  - `validate(settings)`:
 *    (optional) Custom settings validator called from `set` method.
 *    It should just throw if input settings are not good.
 **/
function Store(options) {
  options = options || {};

  if (!_.isFunction(options.set) || 3 !== options.set.length) {
    throw "Store set backend is required to be a function with 3 arguments";
  }

  if (!_.isFunction(options.get) || 4 !== options.get.length) {
    throw "Store get backend is required to be a function with 4 arguments";
  }

  this.__set__      = options.set;
  this.__get__      = options.get;
  this.__validate__ = options.validate || defaultSettingsValidator;
  this.__keys__     = {};
}

/**
 *  Settings.Store#validateSetting(key, value) -> Null|String
 *  - key (String): Name of setting to check.
 *  - value (Mixed): Value to check using that setting's schema.
 *
 *  Returns null if `value` is good for setting by `key`.
 *  Otherwise returns string with error description.
 **/
Store.prototype.validateSetting = function validateSetting(key, value) {
  if (!_.has(this.__keys__, key)) {
    return 'Unknown setting: ' + key;
  }

  switch (this.__keys__[key].type) {
  case 'boolean':
    if (!_.isBoolean(value)) {
      return 'Value of ' + key + ' setting must be a boolean.';
    }
    break;

  case 'number':
    if (!_.isNumber(value)) {
      return 'Value of ' + key + ' setting must be a number.';
    }
    break;

  case 'combobox':
    if (!_.isArray(value)) {
      return 'Value of ' + key + ' setting must be an array.';
    }
    break;

  // Except string type otherwise.
  default:
    if (!_.isString(value)) {
      return 'Value of ' + key + ' setting must be a string.';
    }
    break;
  }

  return null;
};

/**
 *  Settings.Store#validate(settings) -> Null|String
 *  - settings (Object): Key-Value hash of settings
 *
 *  Returns null if `settings` are good to save.
 *  Otherwise returns string with error description.
 **/
Store.prototype.validate = function validate(settings) {
  try {
    this.__validate__.call(this, settings);
  } catch (err) {
    return err;
  }

  return null;
};

/**
 *  Settings.Store#get(keys, params[, options], callback(err, values)) -> Void
 *  - keys (String|Array): Setting key(s)
 *  - params (Object): Params used to get value of a key
 *  - options (Object): Extra options for fine tuning, see below.
 *  - callback (Function): Executed once, everything is done.
 *
 *  Each value is an instance of [[Value]].
 *
 *  ##### Options
 *
 *  - *skipCache* (Boolean): Skip cache and get value from database. Default: false
 *  - *cache* (Object): Cache data, that can be used instead of hitting database.
 *    Ignored if `skipCache` is true.
 **/
Store.prototype.get = function get(keys, params, options, callback) {
  var single = !_.isArray(keys);

  if (!callback) {
    callback = options;
    options  = {};
  }

  this.__get__.call(this, single ? [keys] : keys, params, options, function (err, data) {
    callback(err, single ? data[keys] : data);
  });
};

/**
 *  Settings.Store#set(settings, params, callback(err)) -> Void
 *  - settings (Object): Key-Value hash of settings
 *  - params (Object): Params used to get value of a key
 *  - value (Mixed): New value for the `key`
 *  - callback (Function): Executed once, everything is done.
 *
 *  Sets new settings values.
 **/
Store.prototype.set = function set(settings, params, callback) {
  var err = this.validate(settings);

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

  this.__set__.call(this, settings, params, callback);
};

/**
 *  Settings.Store#keys -> Array
 *
 *  List of registered setting keys.
 *
 *
 *  ##### See Also
 *
 *  - [[Settings.Store#addKnownKey]]
 *  - [[Settings.Store#getDefaultValue]]
 **/
Object.defineProperty(Store.prototype, 'keys', {
  get: function () {
    return Object.keys(this.__keys__);
  }
});

/**
 *  Store#addKnownKey(key, type, value) -> Void
 *  - key (String): Setting key
 *  - type (String): Value type used for typecasting upon [[Store#set]]
 *  - value (Mixed): Default setting value
 *
 *  Adds `key` with `type` and its default `value` to be served by the store.
 **/
Store.prototype.addKnownKey = function addKnownKey(key, type, value) {
  this.__keys__[key] = { type: type, value: value };
};

/**
 *  Store#getDefaultValue(key) -> Mixed
 *  - key (String): Setting key
 *
 *  Returns default value for the setting.
 **/
Store.prototype.getDefaultValue = function getDefaultValue(key) {
  return (this.__keys__[key] || {}).value;
};

module.exports = Store;
<|endoftext|>


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

define(([],function (){
    var FileMenu = {
        id: "file",
        label: "File",
        items: [
            {
                id: "new",
                label: "New",
                command: {
                    id: "create-new-tab",
                    shortcuts: {
                        mac: {
                            key: "command+option+n",
                            label: "\u2318\u2325N"
                        },
                        other: {
                            key: "ctrl+alt+n",
                            label: "Ctrl+Alt+N"
                        }
                    }
                },
                disabled: false
            },
            {
                id: "open",
                label: "Open File",
                command: {
                    id: "open-file-open-dialog",
                    shortcuts: {
                        mac: {
                            key: "command+o",
                            label: "\u2318O"
                        },
                        other: {
                            key: "ctrl+o",
                            label: "Ctrl+O"
                        }
                    }
                },
                disabled: false
            },
            {
                id: "openSample",
                label: "Open Sample",
                command: {
                    id: "open-sample-file-open-dialog",
                    shortcuts: {
                        mac: {
                            key: "command+o+s",
                            label: "\u2318OS"
                        },
                        other: {
                            key: "ctrl+o+s",
                            label: "Ctrl+O+S"
                        }
                    }
                },
                disabled: false
            },
            {
                id: "save",
                label: "Save",
                command: {
                    id: "save",
                    shortcuts: {
                        mac: {
                            key: "command+s",
                            label: "\u2318S"
                        },
                        other: {
                            key: "ctrl+s",
                            label: "Ctrl+S"
                        }
                    }
                },
                disabled: false
            },
            {
                id: "saveAs",
                label: "Save As",
                command: {
                    id: "open-file-save-dialog",
                    shortcuts: {
                        mac: {
                            key: "command+shift+s",
                            label: "\u2318\u21E7S"
                        },
                        other: {
                            key: "ctrl+shift+s",
                            label: "Ctrl+Shift+S"
                        }
                    }
                },
                disabled: false
            },
            {
                id: "import",
                label: "Import File",
                command: {
                    id: "import-file-import-dialog",
                    shortcuts: {
                        mac: {
                            key: "command+i",
                            label: "\u2318I"
                        },
                        other: {
                            key: "ctrl+i",
                            label: "Ctrl+I"
                        }
                    }
                },
                disabled: false
            },
            {
                id: "export",
                label: "Export File",
                command: {
                    id: "export",
                    shortcuts: {
                        mac: {
                            key: "command+e",
                            label: "\u2318E"
                        },
                        other: {
                            key: "ctrl+e",
                            label: "Ctrl+E"
                        }
                    }
                },
                disabled: false
            },
            {
                id: "close",
                label: "Close File",
                command: {
                    id: "close",
                    shortcuts: {
                        mac: {
                            key: "command+w",
                            label: "\u2318W"
                        },
                        other: {
                            key: "ctrl+w",
                            label: "Ctrl+W"
                        }
                    }
                },
                disabled: false
            },
            {
                id: "closeAll",
                label: "Close All Files",
                command: {
                    id: "close-all",
                    shortcuts: {
                        mac: {
                            key: "command+alt+x",
                            label: "\u2318\u2303X"
                        },
                        other: {
                            key: "ctrl+alt+x",
                            label: "Ctrl+Alt+X"
                        }
                    }
                },
                disabled: false
            },
            {
                id: "delete",
                label: "Delete File",
                command: {
                    id: "delete-file-delete-dialog",
                    shortcuts: {
                        mac: {
                            key: "command+d",
                            label: "\u2318D"
                        },
                        other: {
                            key: "ctrl+d",
                            label: "Ctrl+D"
                        }
                    }
                },
                disabled: false
            },
            {
                id: "settings",
                label: "Settings",
                command: {
                    id: "open-settings-dialog",
                    shortcuts: {
                        mac: {
                            key: "command+option+e",
                            label: "\u2318\u2325E"
                        },
                        other: {
                            key: "ctrl+alt+e",
                            label: "Ctrl+Alt+E"
                        }
                    }
                },
                disabled: false
            }

            ]

    };

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

define(([],function (){
    var FileMenu = {
        id: "file",
        label: "File",
        items: [
            {
                id: "new",
                label: "New",
                command: {
                    id: "create-new-tab",
                    shortcuts: {
                        mac: {
                            key: "command+option+n",
                            label: "\u2318\u2325N"
                        },
                        other: {
                            key: "ctrl+alt+n",
                            label: "Ctrl+Alt+N"
                        }
                    }
                },
                disabled: false
            },
            {
                id: "open",
                label: "Open File",
                command: {
                    id: "open-file-open-dialog",
                    shortcuts: {
                        mac: {
                            key: "command+o",
                            label: "\u2318O"
                        },
                        other: {
                            key: "ctrl+o",
                            label: "Ctrl+O"
                        }
                    }
                },
                disabled: false
            },
            {
                id: "openSample",
                label: "Open Sample",
                command: {
                    id: "open-sample-file-open-dialog",
                    shortcuts: {
                        mac: {
                            key: "command+shift+o",
                            label: "\u2318\u21E7O"
                        },
                        other: {
                            key: "ctrl+shift+o",
                            label: "Ctrl+Shift+O"
                        }
                    }
                },
                disabled: false
            },
            {
                id: "save",
                label: "Save",
                command: {
                    id: "save",
                    shortcuts: {
                        mac: {
                            key: "command+s",
                            label: "\u2318S"
                        },
                        other: {
                            key: "ctrl+s",
                            label: "Ctrl+S"
                        }
                    }
                },
                disabled: false
            },
            {
                id: "saveAs",
                label: "Save As",
                command: {
                    id: "open-file-save-dialog",
                    shortcuts: {
                        mac: {
                            key: "command+shift+s",
                            label: "\u2318\u21E7S"
                        },
                        other: {
                            key: "ctrl+shift+s",
                            label: "Ctrl+Shift+S"
                        }
                    }
                },
                disabled: false
            },
            {
                id: "import",
                label: "Import File",
                command: {
                    id: "import-file-import-dialog",
                    shortcuts: {
                        mac: {
                            key: "command+i",
                            label: "\u2318I"
                        },
                        other: {
                            key: "ctrl+i",
                            label: "Ctrl+I"
                        }
                    }
                },
                disabled: false
            },
            {
                id: "export",
                label: "Export File",
                command: {
                    id: "export",
                    shortcuts: {
                        mac: {
                            key: "command+e",
                            label: "\u2318E"
                        },
                        other: {
                            key: "ctrl+e",
                            label: "Ctrl+E"
                        }
                    }
                },
                disabled: false
            },
            {
                id: "close",
                label: "Close File",
                command: {
                    id: "close",
                    shortcuts: {
                        mac: {
                            key: "command+w",
                            label: "\u2318W"
                        },
                        other: {
                            key: "ctrl+w",
                            label: "Ctrl+W"
                        }
                    }
                },
                disabled: false
            },
            {
                id: "closeAll",
                label: "Close All Files",
                command: {
                    id: "close-all",
                    shortcuts: {
                        mac: {
                            key: "command+alt+x",
                            label: "\u2318\u2303X"
                        },
                        other: {
                            key: "ctrl+alt+x",
                            label: "Ctrl+Alt+X"
                        }
                    }
                },
                disabled: false
            },
            {
                id: "delete",
                label: "Delete File",
                command: {
                    id: "delete-file-delete-dialog",
                    shortcuts: {
                        mac: {
                            key: "command+d",
                            label: "\u2318D"
                        },
                        other: {
                            key: "ctrl+d",
                            label: "Ctrl+D"
                        }
                    }
                },
                disabled: false
            },
            {
                id: "settings",
                label: "Settings",
                command: {
                    id: "open-settings-dialog",
                    shortcuts: {
                        mac: {
                            key: "command+option+e",
                            label: "\u2318\u2325E"
                        },
                        other: {
                            key: "ctrl+alt+e",
                            label: "Ctrl+Alt+E"
                        }
                    }
                },
                disabled: false
            }

            ]

    };

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


<commit_before>import 'native-promise-only'
import 'whatwg-fetch'
import React from 'react'
import {render} from 'react-dom'
import {Router, Route, browserHistory, IndexRoute} from 'react-router'
import config from 'lib/config'
import urlBuilder from 'lib/url-builder'
import user from 'lib/site/user/user'

import Layout from 'lib/site/layout/component'
import TopicLayout from 'lib/site/topic-layout/component'
import HomeForum from 'lib/site/home-forum/component'
import HomeMultiForum from 'lib/site/home-multiforum/component'
import SignIn from 'lib/site/sign-in/component'
import SignUp from 'lib/site/sign-up/component'
import Resend from 'lib/site/resend/component'
import Forgot from 'lib/site/forgot/component'
import Reset from 'lib/site/reset/component'
import Help from 'lib/site/help/component'
import Notifications from 'lib/site/notifications/component'
import NotFound from 'lib/site/error-pages/not-found/component'
import NotAllowed from 'lib/site/error-pages/not-allowed/component'

import 'lib/analytics/analytics'
import 'lib/translations/translations'

/**
 * Enable client-side debug messages
 */

import 'lib/debug'

/*
 * Register routes aliases
 */

import 'lib/boot/routes'

/*
 * Setup Moment.js
 */

import './moment'

/*
 * Compose react app
 */

render((
  <Router history={browserHistory} onUpdate={track}>
    <Route path='/' component={Layout}>
      <Route path='404' component={NotFound} />
      <Route path='401' component={NotAllowed} />

      <Route path='signin' component={SignIn} onEnter={restrictLoggedin} />

      <Route path='signup' onEnter={restrictLoggedin}>
        <IndexRoute component={SignUp} />
        <Route
          path='resend-validation-email'
          component={Resend} />
        <Route
          path='validate/:token'
          component={Resend} />
        <Route
          path=':reference'
          component={SignUp} />
      </Route>

      <Route path='forgot'>
        <IndexRoute component={Forgot} />
        <Route path=':token' component={Reset} />
      </Route>

      <Route path={urlBuilder.for('site.help')} component={Help} />
      <Route path={urlBuilder.for('site.help.article')} component={Help} />

      <Route path='notifications' component={Notifications} />

      <Route path='settings/*' component={reload} />
      <Route path='help/*' component={reload} />

      <Route path={urlBuilder.for('site.topic')} component={TopicLayout} />
      {config.multiForum && (
        <Route
          path={urlBuilder.for('site.forum')}
          component={HomeForum} onEnter={setForumParam} />
      )}
      <IndexRoute
        component={config.multiForum ? HomeMultiForum : HomeForum} />

      <Route path='*' component={reload} />
    </Route>
  </Router>
), document.getElementById('root'))

function track () {
  window.analytics.page(window.location.pathname)
}

function reload () {
  window.location.reload(false)
  return null
}

function setForumParam (nextState) {
  if (!config.multiForum) {
    nextState.params.forum = config.defaultForum
  }
}

function restrictLoggedin (nextState, replace, next) {
  user.fetch().then(() => {
    if (user.state.rejected) return next()
    replace('/')
  })
}
<commit_msg>fix password reset token verification url<commit_after>import 'native-promise-only'
import 'whatwg-fetch'
import React from 'react'
import {render} from 'react-dom'
import {Router, Route, browserHistory, IndexRoute} from 'react-router'
import config from 'lib/config'
import urlBuilder from 'lib/url-builder'
import user from 'lib/site/user/user'

import Layout from 'lib/site/layout/component'
import TopicLayout from 'lib/site/topic-layout/component'
import HomeForum from 'lib/site/home-forum/component'
import HomeMultiForum from 'lib/site/home-multiforum/component'
import SignIn from 'lib/site/sign-in/component'
import SignUp from 'lib/site/sign-up/component'
import Resend from 'lib/site/resend/component'
import Forgot from 'lib/site/forgot/component'
import Reset from 'lib/site/reset/component'
import Help from 'lib/site/help/component'
import Notifications from 'lib/site/notifications/component'
import NotFound from 'lib/site/error-pages/not-found/component'
import NotAllowed from 'lib/site/error-pages/not-allowed/component'

import 'lib/analytics/analytics'
import 'lib/translations/translations'

/**
 * Enable client-side debug messages
 */

import 'lib/debug'

/*
 * Register routes aliases
 */

import 'lib/boot/routes'

/*
 * Setup Moment.js
 */

import './moment'

/*
 * Compose react app
 */

render((
  <Router history={browserHistory} onUpdate={track}>
    <Route path='/' component={Layout}>
      <Route path='404' component={NotFound} />
      <Route path='401' component={NotAllowed} />

      <Route path='signin' component={SignIn} onEnter={restrictLoggedin} />

      <Route path='signup' onEnter={restrictLoggedin}>
        <IndexRoute component={SignUp} />
        <Route
          path='resend-validation-email'
          component={Resend} />
        <Route
          path='validate/:token'
          component={Resend} />
        <Route
          path=':reference'
          component={SignUp} />
      </Route>

      <Route path='forgot'>
        <IndexRoute component={Forgot} />
        <Route path='reset/:token' component={Reset} />
      </Route>

      <Route path={urlBuilder.for('site.help')} component={Help} />
      <Route path={urlBuilder.for('site.help.article')} component={Help} />

      <Route path='notifications' component={Notifications} />

      <Route path='settings/*' component={reload} />
      <Route path='help/*' component={reload} />

      <Route path={urlBuilder.for('site.topic')} component={TopicLayout} />
      {config.multiForum && (
        <Route
          path={urlBuilder.for('site.forum')}
          component={HomeForum} onEnter={setForumParam} />
      )}
      <IndexRoute
        component={config.multiForum ? HomeMultiForum : HomeForum} />

      <Route path='*' component={reload} />
    </Route>
  </Router>
), document.getElementById('root'))

function track () {
  window.analytics.page(window.location.pathname)
}

function reload () {
  window.location.reload(false)
  return null
}

function setForumParam (nextState) {
  if (!config.multiForum) {
    nextState.params.forum = config.defaultForum
  }
}

function restrictLoggedin (nextState, replace, next) {
  user.fetch().then(() => {
    if (user.state.rejected) return next()
    replace('/')
  })
}
<|endoftext|>


<commit_before>ngDefine('cockpit.plugin.base.views', function(module) {

  var Controller = function ($scope, $http, $location, Uri) {

    // input: processInstanceId, selection, processInstance

    var pages = $scope.pages = { size: 50, total: 0 };

    var activityInstanceIds = null;
    var alreadyUpdated = false;

    $scope.$watch(function() { return $location.search().page; }, function(newValue) {
      pages.current = parseInt(newValue) || 1;
    });

    $scope.$watch('pages.current', function(newValue) {
      var currentPage = newValue || 1;
      var search = $location.search().page;

      if (search || currentPage !== 1) {
        $location.search('page', currentPage);
        updateView(currentPage);
      }

    });

    $scope.$watch('selection.treeDiagramMapping.activityInstances', function (newValue) {
      var instances = newValue || [];
      activityInstanceIds = [];
      // collect the instance ids
      angular.forEach(instances, function (instance) {
        var instanceId = instance.id;
        activityInstanceIds.push(instanceId);
      });

      // always reset the current page to null
      $location.search('page', null);
      if ($scope.processInstance.instanceIdToInstanceMap) {
        alreadyUpdated = true;
        updateView(1);
      }

    });

    // This $watch on 'processInstance.instanceIdToInstance' is necessary due to race
    // conditions. It can happen, that the view will be updated before the the properpty
    // instanceIdToInstanceMap of the variable processInstance has been set.
    $scope.$watch('processInstance.instanceIdToInstanceMap', function (newValue) {
      if (newValue && activityInstanceIds && !alreadyUpdated) {
        updateView(1);
      }

    });

    function updateView(page) {
      var count = pages.size;
      var firstResult = (page - 1) * count;

      // get the 'count' of variables
      $http.post(Uri.appUri("engine://engine/:engine/variable-instance/count"), {
        processInstanceIdIn : [ $scope.processInstanceId ],
        activityInstanceIdIn :  activityInstanceIds
      })
      .success(function(data) {
        pages.total = Math.ceil(data.count / pages.size);
      });

      // get the variables
      $http.post(Uri.appUri("engine://engine/:engine/variable-instance/"), {
        processInstanceIdIn : [ $scope.processInstanceId ],
        activityInstanceIdIn :  activityInstanceIds
      }, {
        params: {firstResult: firstResult, maxResults: count}
      })
      .success(function(data) {
        var instanceIdToInstanceMap = $scope.processInstance.instanceIdToInstanceMap;
        angular.forEach(data, function(currentVariable) {
          var instance = instanceIdToInstanceMap[currentVariable.activityInstanceId];
          currentVariable.instance = instance;
        });
        $scope.variables = data;
      });
    };

    $scope.selectActivityInstance = function (variable) {
      $scope.selection.treeDiagramMapping = {activityInstances: [ variable.instance ], scrollTo: variable.instance};
    }
  };

  Controller.$inject = [ '$scope', '$http', '$location', 'Uri' ];

  var Configuration = function PluginConfiguration(ViewsProvider) {

    ViewsProvider.registerDefaultView('cockpit.processInstance.instanceDetails', {
      id: 'variables-tab',
      label: 'Variables',
      url: 'plugin://base/static/app/views/processInstance/variables-tab.html',
      controller: Controller
    });
  };

  Configuration.$inject = ['ViewsProvider'];

  module.config(Configuration);
});
<commit_msg>chore(variables): Reset variables to null<commit_after>ngDefine('cockpit.plugin.base.views', function(module) {

  var Controller = function ($scope, $http, $location, Uri) {

    // input: processInstanceId, selection, processInstance

    var pages = $scope.pages = { size: 50, total: 0 };

    var activityInstanceIds = null;
    var alreadyUpdated = false;

    $scope.$watch(function() { return $location.search().page; }, function(newValue) {
      pages.current = parseInt(newValue) || 1;
    });

    $scope.$watch('pages.current', function(newValue) {
      var currentPage = newValue || 1;
      var search = $location.search().page;

      if (search || currentPage !== 1) {
        $location.search('page', currentPage);
        updateView(currentPage);
      }

    });

    $scope.$watch('selection.treeDiagramMapping.activityInstances', function (newValue) {
      var instances = newValue || [];
      activityInstanceIds = [];
      // collect the instance ids
      angular.forEach(instances, function (instance) {
        var instanceId = instance.id;
        activityInstanceIds.push(instanceId);
      });

      // always reset the current page to null
      $location.search('page', null);
      if ($scope.processInstance.instanceIdToInstanceMap) {
        alreadyUpdated = true;
        updateView(1);
      }

    });

    // This $watch on 'processInstance.instanceIdToInstance' is necessary due to race
    // conditions. It can happen, that the view will be updated before the the properpty
    // instanceIdToInstanceMap of the variable processInstance has been set.
    $scope.$watch('processInstance.instanceIdToInstanceMap', function (newValue) {
      if (newValue && activityInstanceIds && !alreadyUpdated) {
        updateView(1);
      }

    });

    function updateView(page) {
      $scope.variables = null;

      var count = pages.size;
      var firstResult = (page - 1) * count;

      // get the 'count' of variables
      $http.post(Uri.appUri("engine://engine/:engine/variable-instance/count"), {
        processInstanceIdIn : [ $scope.processInstanceId ],
        activityInstanceIdIn :  activityInstanceIds
      })
      .success(function(data) {
        pages.total = Math.ceil(data.count / pages.size);
      });

      // get the variables
      $http.post(Uri.appUri("engine://engine/:engine/variable-instance/"), {
        processInstanceIdIn : [ $scope.processInstanceId ],
        activityInstanceIdIn :  activityInstanceIds
      }, {
        params: {firstResult: firstResult, maxResults: count}
      })
      .success(function(data) {
        var instanceIdToInstanceMap = $scope.processInstance.instanceIdToInstanceMap;
        angular.forEach(data, function(currentVariable) {
          var instance = instanceIdToInstanceMap[currentVariable.activityInstanceId];
          currentVariable.instance = instance;
        });
        $scope.variables = data;
      });
    };

    $scope.selectActivityInstance = function (variable) {
      $scope.selection.treeDiagramMapping = {activityInstances: [ variable.instance ], scrollTo: variable.instance};
    }
  };

  Controller.$inject = [ '$scope', '$http', '$location', 'Uri' ];

  var Configuration = function PluginConfiguration(ViewsProvider) {

    ViewsProvider.registerDefaultView('cockpit.processInstance.instanceDetails', {
      id: 'variables-tab',
      label: 'Variables',
      url: 'plugin://base/static/app/views/processInstance/variables-tab.html',
      controller: Controller
    });
  };

  Configuration.$inject = ['ViewsProvider'];

  module.config(Configuration);
});
<|endoftext|>


<commit_before>#!/usr/bin/env node

'use strict';

var fs = require('fs');
var path = require('path');
var qs = require('querystring');
var http = require('http');
var url = require('url');
var execFileSync = require('child_process').execFileSync;

var PORT = 9191;

function handleRequest(req, res){
    function updateRepo(pathname) {
        var gitPull = execFileSync('bash', ['./update-repo.sh', pathname]);
        res.end(gitPull);
    }
    function cloneRepo(url, pathname) {
        var gitClone = execFileSync('bash', ['./clone-repo.sh', url, pathname]);
        res.end(gitClone);
    }

    try {
        var urlInfo = url.parse(req.url);
        var query = qs.parse(urlInfo.query);
        if (query && query.repo && query.name) {
            var pathname = path.join(process.cwd(), 'repo/' + query.name);
console.log(query.repo, query.name, pathname, new Date());
            var stat;
            try {
                stat = fs.statSync(pathname);
                if (stat.isDirectory()) {
console.log('directory exists, update');
                    updateRepo(pathname);
                } else {
console.log('not a directory, clone');
                    cloneRepo(query.repo, pathname);
                }
            } catch (err) {
console.log('directory not found, clone');
                cloneRepo(query.repo, pathname);
            }
        } else {
            res.end('repo not found. url: ' + req.url);
        }
    } catch (e) {
        res.end('error: ' + e);
    }
}

var server = http.createServer(handleRequest);

server.listen(PORT, function(){
    console.log("Server listening on: http://localhost:%s", PORT);
});
<commit_msg>update hook scripts<commit_after>#!/usr/bin/env node

'use strict';

var fs = require('fs');
var path = require('path');
var qs = require('querystring');
var http = require('http');
var url = require('url');
var execFileSync = require('child_process').execFileSync;

var PORT = 9191;

function handleRequest(req, res){
    function updateRepo(pathname) {
        var gitPull = execFileSync('bash', [
            path.join(__dirname, 'update-repo.sh'),
            pathname
        ]);
        res.end(gitPull);
    }
    function cloneRepo(url, pathname) {
        var gitClone = execFileSync('bash', [
            path.join(__dirname, 'clone-repo.sh'),
            url,
            pathname
        ]);
        res.end(gitClone);
    }

    try {
        var urlInfo = url.parse(req.url);
        var query = qs.parse(urlInfo.query);
        if (query && query.repo && query.name) {
            var pathname = path.join(process.cwd(), 'repo/' + query.name);
console.log(query.repo, query.name, pathname, new Date());
            var stat;
            try {
                stat = fs.statSync(pathname);
                if (stat.isDirectory()) {
console.log('directory exists, update');
                    updateRepo(pathname);
                } else {
console.log('not a directory, clone');
                    cloneRepo(query.repo, pathname);
                }
            } catch (err) {
console.log('directory not found, clone');
                cloneRepo(query.repo, pathname);
            }
        } else {
            res.end('repo not found. url: ' + req.url);
        }
    } catch (e) {
        res.end('error: ' + e);
    }
}

var server = http.createServer(handleRequest);

server.listen(PORT, function(){
    console.log("Server listening on: http://localhost:%s", PORT);
});
<|endoftext|>