<commit_before>var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var request = require("request");
var redis = require("redis");

//Setup Redis
client = redis.createClient();
client.on("error", function (err) {
    console.log("Error " + err);
});

//var connectedServers = {}
var serverQueue = []

http.listen(3000, function(){
    console.log('listening on *:3000');
});

//Returns the IP of the next server in the round-robin
function nextServer(){
    var ip = serverQueue.shift();
    serverQueue.push(ip);
    return ip;
}

var cpuUsages = []
var time = 0;
var recordingInterval = 1000 * 10;
var training = true;
var recording = false;
var keyPrefix = training ? "training:" : "testing:";

function startRecordingUsage() {
    var recordUsage = setInterval(function(){
        var count = cpuUsages.length;
        if(count == 0){
            return;
        }

        var sum = 0;
        while(cpuUsages.length > 0){
            sum += cpuUsages.pop();
        }

        var average = sum / count;

        console.log(JSON.stringify({ip: "Average",
        usage: average.toString()}));

        io.emit('cpu-ip', JSON.stringify({ip: "Average",
        usage: average.toString()}));

        time += recordingInterval;

        client.set(keyPrefix + time, average, redis.print);

    }, recordingInterval);
}

io.on('connection', function(socket){
    console.log(socket.request.connection._peername.address);
    var ip = socket.request.connection._peername.address;

    socket.on('cpu-usage', function(msg){
        if(serverQueue.indexOf(ip) === -1){
            serverQueue.push(ip);
        }

        if(recording){
            cpuUsages.push(msg);
        }
    });

    socket.on('disconnect', function(){
        console.log('user disconnected');
        var index = serverQueue.indexOf(ip);
        if(index > -1){
            serverQueue.splice(index, 1);
        }
    });
});

app.get('/', function(req, res){
    if(!recording){
        recording = true;
        startRecordingUsage();
    }

    client.incr(keyPrefix + "requests:" + recordingInterval);

    var server = nextServer();
    request("http://" + server + ":3005" , function(error, response, body) {
        res.write("You were served by " + server + "\n")
        res.end(body);
        client.incr(keyPrefix + "responses:" + server + ":" + recordingInterval);

    });
});
<commit_msg>Added deletion of keys that will be incremented<commit_after>var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var request = require("request");
var redis = require("redis");

//Setup Redis
client = redis.createClient();
client.on("error", function (err) {
    console.log("Error " + err);
});

//var connectedServers = {}
var serverQueue = []

http.listen(3000, function(){
    console.log('listening on *:3000');
});

//Returns the IP of the next server in the round-robin
function nextServer(){
    var ip = serverQueue.shift();
    serverQueue.push(ip);
    return ip;
}

var cpuUsages = []
var time = 0;
var recordingInterval = 1000 * 10;
var training = true;
var recording = false;
var keyPrefix = training ? "training:" : "testing:";

//Clear data from previous runs
client.keys(keyPrefix + "*", function(err, keys){
    keys.forEach(function(key){
        client.del(key);
    });

    console.log("Flushed Keys")
}

function startRecordingUsage() {
    var recordUsage = setInterval(function(){
        var count = cpuUsages.length;
        if(count == 0){
            return;
        }

        var sum = 0;
        while(cpuUsages.length > 0){
            sum += cpuUsages.pop();
        }

        var average = sum / count;

        console.log(JSON.stringify({ip: "Average",
        usage: average.toString()}));

        io.emit('cpu-ip', JSON.stringify({ip: "Average",
        usage: average.toString()}));

        time += recordingInterval;

        client.set(keyPrefix + time, average, redis.print);

    }, recordingInterval);
}

io.on('connection', function(socket){
    console.log(socket.request.connection._peername.address);
    var ip = socket.request.connection._peername.address;

    socket.on('cpu-usage', function(msg){
        if(serverQueue.indexOf(ip) === -1){
            serverQueue.push(ip);
        }

        if(recording){
            cpuUsages.push(msg);
        }
    });

    socket.on('disconnect', function(){
        console.log('user disconnected');
        var index = serverQueue.indexOf(ip);
        if(index > -1){
            serverQueue.splice(index, 1);
        }
    });
});

app.get('/', function(req, res){
    if(!recording){
        recording = true;
        startRecordingUsage();
    }

    client.incr(keyPrefix + "requests:" + recordingInterval);

    var server = nextServer();
    request("http://" + server + ":3005" , function(error, response, body) {
        res.write("You were served by " + server + "\n")
        res.end(body);
        client.incr(keyPrefix + "responses:" + server + ":" + recordingInterval);

    });
});
<|endoftext|>


<commit_before>var events = require('events');
var util = require('util');
var Service = require('./service');

function CdifDevice(spec) {
  this.spec = spec;
  this.deviceID = '';
  this.connected = false;
  this.initServices();

  this.getDeviceSpec = this.getDeviceSpec.bind(this);
  this.connect = this.connect.bind(this);
  this.disconnect = this.disconnect.bind(this);
  this.getHWAddress = this.getHWAddress.bind(this);
  this.deviceControl = this.deviceControl.bind(this);
  this.subscribeDeviceEvent = this.subscribeDeviceEvent.bind(this);
  this.unSubscribeDeviceEvent = this.unSubscribeDeviceEvent.bind(this);
}

util.inherits(CdifDevice, events.EventEmitter);

CdifDevice.prototype.setAction = function(serviceID, actionName, action) {
  var service = this.services[serviceID];
  if (service) {
    service.actions[actionName].invoke = action.bind(this);
  } else {
    console.error('cannot set action: ' + serviceID + ' ' + actionName);
  }
};

CdifDevice.prototype.initServices = function() {
  this.services = {};
  var serviceList = this.spec.device.serviceList;
  for (var i in serviceList) {
    var service_spec = serviceList[i];
    this.services[i] = new Service(i, service_spec);
  }
}

CdifDevice.prototype.getDeviceSpec = function(callback) {
  if (this.connected === false) {
    callback(new Error('device not connected'), null);
    return;
  }
  if (this.spec == null) {
    callback(new Error('cannot get device spec'), null);
  } else {
    console.log('device name: ' + this.spec.device.friendlyName + ' deviceID: ' + this.deviceID);
    callback(null, this.spec);
  }
};

CdifDevice.prototype.getDeviceState = function(serviceID, callback) {
  var service = this.services[serviceID];
  if (service == null) {
    callback(new Error('service not found: ' + serviceID), null);
    return;
  }
  if (this.connected === false) {
    callback(new Error('device not connected'), null);
    return;
  }
  service.getState(callback);
};

CdifDevice.prototype.connect = function(user, pass, callback) {
  var _this = this;
  if (this.connected === true) {
    //TODO: may need to increase connected count?
    if (this.spec.device.userAuth === true) {
      if (this.user === user && this.pass === pass) {
        callback (null);
      } else {
        callback (new Error('user not authenticated'));
      }
      return;
    } else {
      callback(null);
      return;
    }
  }
  if (this._connect) {
    if (this.spec.device.userAuth === true) {
      this._connect(user, pass, function(error) {
        if (!error) {
          _this.user = user;
          _this.pass = pass;
          _this.connected = true;
        }
        callback(error);
      });
    } else {
      this._connect('', '', function(error) {
        if (!error) {
          _this.connected = true;
        }
        callback(error);
      });
    }
  } else {
    if (this.spec.device.userAuth === true) {
      // TODO: may create auth strategy later on
      callback(new Error('cannot authenticate this device'));
    } else {
      this.connected = true;
      callback(null);
    }
  }
};

CdifDevice.prototype.disconnect = function(callback) {
  var _this = this;
  if (this.connected === true) {
    //TODO: may need to decrease connected count?
    if (this._disconnect) {
      this._disconnect(function(error) {
        if (!error) {
          if (_this.spec.device.userAuth === true) {
            _this.user = ''; _this.pass = '';
          }
          _this.connected = false;
        }
        callback(error);
      });
    } else {
      if (this.spec.device.userAuth === true) {
        this.user = ''; this.pass = '';
      }
      this.connected = false;
      callback(null);
    }
  } else {
    callback(new Error('device not connected'));
  }
};

CdifDevice.prototype.getHWAddress = function(callback) {
  if (this._getHWAddress) {
    this._getHWAddress(function(error, data) {
      callback(error, data);
    });
  } else {
    callback(null, null);
  }
};

CdifDevice.prototype.deviceControl = function(serviceID, actionName, args, callback) {
  var service = this.services[serviceID];
  if (service == null) {
    callback(new Error('service not found: ' + serviceID), null);
    return;
  }
  if (this.connected === false) {
    callback(new Error('device not connected'), null);
    return;
  }
  service.invokeAction(actionName, args, function(err, data) {
    callback(err, data);
  });
};

CdifDevice.prototype.updateDeviceSpec = function(newSpec) {
  this.spec = newSpec;
  //rebuild services
  console.log(JSON.stringify(this.spec));
  this.initServices();
};

CdifDevice.prototype.setSubscriber = function(serviceID, subscribeCall, onEvent) {
  var service = this.services[serviceID];
  if (service) {
    service.setSubscriber(subscribeCall.bind(this), onEvent);
  } else {
    console.error('cannot set subscriber: ' + serviceID);
  }
};

CdifDevice.prototype.setUnsubscriber = function(serviceID, unsubscribeCall) {
  var service = this.services[serviceID];
  if (service) {
    service.setUnsubscriber(unsubscribeCall.bind(this));
  } else {
    console.error('cannot set unsubscriber: ' + serviceID);
  }
};

CdifDevice.prototype.subscribeDeviceEvent = function(subscriber, serviceID, callback) {
  var service = this.services[serviceID];
  if (service == null) {
    callback(new Error('cannot subscribe to unknown serviceID: ' + serviceID));
    return;
  }
  if (this.connected === false) {
    callback(new Error('device not connected'), null);
    return;
  }
  service.subscribeEvent(subscriber.onChange, function(err) {
    if (!err) {
      service.addListener('serviceevent', subscriber.publish);
    }
    callback(err);
  });
};

CdifDevice.prototype.unSubscribeDeviceEvent = function(subscriber, serviceID, callback) {
  var service = this.services[serviceID];
  if (service == null) {
    callback(new Error('cannot unsubscribe from unknown serviceID: ' + serviceID));
    return;
  }
  if (this.connected === false) {
    callback(new Error('device not connected'), null);
    return;
  }
  service.removeListener('serviceevent', subscriber.publish);
  if (service.listeners('serviceevent').length === 0) {
    service.unsubscribeEvent(function(err) {
      callback(err);
    });
  }
};

module.exports = CdifDevice;
<commit_msg>minor update<commit_after>var events = require('events');
var util = require('util');
var Service = require('./service');

function CdifDevice(spec) {
  this.spec = spec;
  this.deviceID = '';
  this.connected = false;
  this.initServices();

  this.getDeviceSpec = this.getDeviceSpec.bind(this);
  this.connect = this.connect.bind(this);
  this.disconnect = this.disconnect.bind(this);
  this.getHWAddress = this.getHWAddress.bind(this);
  this.deviceControl = this.deviceControl.bind(this);
  this.subscribeDeviceEvent = this.subscribeDeviceEvent.bind(this);
  this.unSubscribeDeviceEvent = this.unSubscribeDeviceEvent.bind(this);
}

util.inherits(CdifDevice, events.EventEmitter);

CdifDevice.prototype.setAction = function(serviceID, actionName, action) {
  var service = this.services[serviceID];
  if (service) {
    service.actions[actionName].invoke = action.bind(this);
  } else {
    console.error('cannot set action: ' + serviceID + ' ' + actionName);
  }
};

CdifDevice.prototype.initServices = function() {
  this.services = {};
  var serviceList = this.spec.device.serviceList;
  for (var i in serviceList) {
    var service_spec = serviceList[i];
    this.services[i] = new Service(i, service_spec);
  }
}

CdifDevice.prototype.getDeviceSpec = function(callback) {
  if (this.connected === false) {
    callback(new Error('device not connected'), null);
    return;
  }
  if (this.spec == null) {
    callback(new Error('cannot get device spec'), null);
  } else {
    console.log('device name: ' + this.spec.device.friendlyName + ' deviceID: ' + this.deviceID);
    callback(null, this.spec);
  }
};

CdifDevice.prototype.getDeviceState = function(serviceID, callback) {
  var service = this.services[serviceID];
  if (service == null) {
    callback(new Error('service not found: ' + serviceID), null);
    return;
  }
  if (this.connected === false) {
    callback(new Error('device not connected'), null);
    return;
  }
  service.getState(callback);
};

CdifDevice.prototype.connect = function(user, pass, callback) {
  var _this = this;
  //TODO: ref count this call?
  if (this.connected === true) {
    if (this.spec.device.userAuth === true) {
      if (this.user === user && this.pass === pass) {
        callback (null);
      } else {
        callback (new Error('user not authenticated'));
      }
      return;
    } else {
      callback(null);
      return;
    }
  }
  if (this._connect) {
    if (this.spec.device.userAuth === true) {
      this._connect(user, pass, function(error) {
        if (!error) {
          _this.user = user;
          _this.pass = pass;
          _this.connected = true;
        }
        callback(error);
      });
    } else {
      this._connect('', '', function(error) {
        if (!error) {
          _this.connected = true;
        }
        callback(error);
      });
    }
  } else {
    if (this.spec.device.userAuth === true) {
      // TODO: may create auth strategy later on
      callback(new Error('cannot authenticate this device'));
    } else {
      this.connected = true;
      callback(null);
    }
  }
};

CdifDevice.prototype.disconnect = function(callback) {
  var _this = this;
  //TODO: ref count this call?
  if (this.connected === true) {
    if (this._disconnect) {
      this._disconnect(function(error) {
        if (!error) {
          if (_this.spec.device.userAuth === true) {
            _this.user = ''; _this.pass = '';
          }
          _this.connected = false;
        }
        callback(error);
      });
    } else {
      if (this.spec.device.userAuth === true) {
        this.user = ''; this.pass = '';
      }
      this.connected = false;
      callback(null);
    }
  } else {
    callback(new Error('device not connected'));
  }
};

CdifDevice.prototype.getHWAddress = function(callback) {
  if (this._getHWAddress) {
    this._getHWAddress(function(error, data) {
      callback(error, data);
    });
  } else {
    callback(null, null);
  }
};

CdifDevice.prototype.deviceControl = function(serviceID, actionName, args, callback) {
  var service = this.services[serviceID];
  if (service == null) {
    callback(new Error('service not found: ' + serviceID), null);
    return;
  }
  if (this.connected === false) {
    callback(new Error('device not connected'), null);
    return;
  }
  service.invokeAction(actionName, args, function(err, data) {
    callback(err, data);
  });
};

CdifDevice.prototype.updateDeviceSpec = function(newSpec) {
  this.spec = newSpec;
  //rebuild services
  console.log(JSON.stringify(this.spec));
  this.initServices();
};

CdifDevice.prototype.setSubscriber = function(serviceID, subscribeCall, onEvent) {
  var service = this.services[serviceID];
  if (service) {
    service.setSubscriber(subscribeCall.bind(this), onEvent);
  } else {
    console.error('cannot set subscriber: ' + serviceID);
  }
};

CdifDevice.prototype.setUnsubscriber = function(serviceID, unsubscribeCall) {
  var service = this.services[serviceID];
  if (service) {
    service.setUnsubscriber(unsubscribeCall.bind(this));
  } else {
    console.error('cannot set unsubscriber: ' + serviceID);
  }
};

CdifDevice.prototype.subscribeDeviceEvent = function(subscriber, serviceID, callback) {
  var service = this.services[serviceID];
  if (service == null) {
    callback(new Error('cannot subscribe to unknown serviceID: ' + serviceID));
    return;
  }
  if (this.connected === false) {
    callback(new Error('device not connected'), null);
    return;
  }
  service.subscribeEvent(subscriber.onChange, function(err) {
    if (!err) {
      service.addListener('serviceevent', subscriber.publish);
    }
    callback(err);
  });
};

CdifDevice.prototype.unSubscribeDeviceEvent = function(subscriber, serviceID, callback) {
  var service = this.services[serviceID];
  if (service == null) {
    callback(new Error('cannot unsubscribe from unknown serviceID: ' + serviceID));
    return;
  }
  if (this.connected === false) {
    callback(new Error('device not connected'), null);
    return;
  }
  service.removeListener('serviceevent', subscriber.publish);
  if (service.listeners('serviceevent').length === 0) {
    service.unsubscribeEvent(function(err) {
      callback(err);
    });
  }
};

module.exports = CdifDevice;
<|endoftext|>


<commit_before>var socketio = require('socket.io');
var io;
var guestNumber = 1;
var nickNames = {};
var namesUsed = [];
var currentRoom = {};

exports.listen = function(server) {
  io = socketio.listen(server);
  io.set('log level', 1);
  io.sockets.on('connection', function(socket) {
    guestNumber = assignGuestName(socket, guestNumber, nickNames, namesUsed);
    joinRoom(socket, 'Lobby');

    handleMessageBroadcasting(socket, nickNames);
    handleNameChangeAttempts(socket, nickNames, namesUsed);
    handleRoomJoining(socket);

    socket.on('rooms', function() {
      socket.emit('rooms', io.sockets.manager.rooms);
    });

    handleClientDisconnection(socket, nickNames, namesUsed);
  });
};

function assignGuestName(socket, guestNumber, nickNames, namesUsed) {
  var name = 'Guest' + guestNumber;

  nickNames[socket.id] = name;

  socket.emit('nameResult', {
    success: true,
    name: name
  });

  namesUsed.push(name);

  return guestNumber + 1;
}

function joinRoom(socket, room) {
  socket.join(room);

  currentRoom[socket.id] = room;

  socket.emit('joinResult', {room: room});

  socket.broadcast.to(room).emit('message', {
    text: nickNames[socket.io] + 'has joined' + room + '.'
  });

  var usersInRoom = io.sockets.clients(room);
  if (usersInRoom.length > 1) {
    var usersInRoomSummary = 'Users currently in ' + room + ': ';

    for(var index in usersInRoom) {
      var userSocketId = usersInRoom[index].id;
      if (userSocketId != socket.id) {
        if (index > 0) {
          usersInRoomSummary += ', ';
        }
        usersInRoomSummary += nickNames[userSocketId];
      }
    }

    usersInRoomSummary += '.';

    socket.emit('message', {text: usersInRoomSummary});
  }
}

function handleNameChangeAttempts(socket, nickNames, namesUsed) {
  socket.on('nameAttempt', function(name) {
    if (name.indexOf('Guest') == 0) {
      socket.emit('nameResult', {
        success: false,
        message: 'Names cannot begin with "Guest".'
      });

    } else {
      if (namesUsed.indexOf(name) == -1) {
        var previousName = nickNames[socket.id];
        var previousNameIndex = namesUsed.indexOf(previousName);

        namesUsed.push(name);
        nickNames[socket.id] = name;

        delete namesUsed[previousNameIndex];

        socket.emit('nameResult', {
          success: true,
          name: name
        });

        socket.broadcast.to(currentRoom[socket.id]).emit('message', {
          text: previousName + ' is now known as ' + name + '.'
        });

      } else {
        socket.emit('nameResult', {
          success: false,
          message: 'That name is already in use'
        });
      }
    }
  });
}<commit_msg>Add function helper for sending chat messages<commit_after>var socketio = require('socket.io');
var io;
var guestNumber = 1;
var nickNames = {};
var namesUsed = [];
var currentRoom = {};

exports.listen = function(server) {
  io = socketio.listen(server);
  io.set('log level', 1);
  io.sockets.on('connection', function(socket) {
    guestNumber = assignGuestName(socket, guestNumber, nickNames, namesUsed);
    joinRoom(socket, 'Lobby');

    handleMessageBroadcasting(socket, nickNames);
    handleNameChangeAttempts(socket, nickNames, namesUsed);
    handleRoomJoining(socket);

    socket.on('rooms', function() {
      socket.emit('rooms', io.sockets.manager.rooms);
    });

    handleClientDisconnection(socket, nickNames, namesUsed);
  });
};

function assignGuestName(socket, guestNumber, nickNames, namesUsed) {
  var name = 'Guest' + guestNumber;

  nickNames[socket.id] = name;

  socket.emit('nameResult', {
    success: true,
    name: name
  });

  namesUsed.push(name);

  return guestNumber + 1;
}

function joinRoom(socket, room) {
  socket.join(room);

  currentRoom[socket.id] = room;

  socket.emit('joinResult', {room: room});

  socket.broadcast.to(room).emit('message', {
    text: nickNames[socket.io] + 'has joined' + room + '.'
  });

  var usersInRoom = io.sockets.clients(room);
  if (usersInRoom.length > 1) {
    var usersInRoomSummary = 'Users currently in ' + room + ': ';

    for(var index in usersInRoom) {
      var userSocketId = usersInRoom[index].id;
      if (userSocketId != socket.id) {
        if (index > 0) {
          usersInRoomSummary += ', ';
        }
        usersInRoomSummary += nickNames[userSocketId];
      }
    }

    usersInRoomSummary += '.';

    socket.emit('message', {text: usersInRoomSummary});
  }
}

function handleNameChangeAttempts(socket, nickNames, namesUsed) {
  socket.on('nameAttempt', function(name) {
    if (name.indexOf('Guest') == 0) {
      socket.emit('nameResult', {
        success: false,
        message: 'Names cannot begin with "Guest".'
      });

    } else {
      if (namesUsed.indexOf(name) == -1) {
        var previousName = nickNames[socket.id];
        var previousNameIndex = namesUsed.indexOf(previousName);

        namesUsed.push(name);
        nickNames[socket.id] = name;

        delete namesUsed[previousNameIndex];

        socket.emit('nameResult', {
          success: true,
          name: name
        });

        socket.broadcast.to(currentRoom[socket.id]).emit('message', {
          text: previousName + ' is now known as ' + name + '.'
        });

      } else {
        socket.emit('nameResult', {
          success: false,
          message: 'That name is already in use'
        });
      }
    }
  });
}

function handleMessageBroadcasting(socket) {
  socket.on('message', function(message) {
    socket.broadcast.to(message.room).emit('message', {
      text: nickNames[socket.io] + ': ' + message.text
    });
  });
}<|endoftext|>


<commit_before>'use strict';

Application.Directives.directive('widgetSort', ['widgetService',
    function (widgetService) {
        return  {
            'link' : function (scope, element, attrs, ctrl) {
                function updateWidgets() {
                    var widget,
                        position = 1;
                    element.find('.widget').each(function(index, element){
                        widget = angular.element(element).scope().widget;
                        if(scope.isWidgetVisible(widget)) {
                            if(widget.position != position) {
                                widget.position = position;
                                widgetService.put(widget);
                            }
                            position += 1;
                        }
                    });
                }

                scope.$watch('widgets', function () {
                    updateWidgets();
                }, true);

                element.sortable({
                    items : '.widget',
                    cursorAt: { top: 5, left: 5 },
                    tolerance: "pointer",
                    stop : function (event, ui) {
                        updateWidgets();
                    }

                });
            }
        };
    }]);<commit_msg>restricted to attribute<commit_after>'use strict';

Application.Directives.directive('widgetSort', ['widgetService',
    function (widgetService) {
        return  {
            'restrict' : 'A',
            'link' : function (scope, element, attrs, ctrl) {
                function updateWidgets() {
                    var widget,
                        position = 1;
                    element.find('.widget').each(function(index, element){
                        widget = angular.element(element).scope().widget;
                        if(scope.isWidgetVisible(widget)) {
                            if(widget.position != position) {
                                widget.position = position;
                                widgetService.put(widget);
                            }
                            position += 1;
                        }
                    });
                }

                scope.$watch('widgets', function () {
                    updateWidgets();
                }, true);

                element.sortable({
                    items : '.widget',
                    cursorAt: { top: 5, left: 5 },
                    tolerance: "pointer",
                    stop : function (event, ui) {
                        updateWidgets();
                    }

                });
            }
        };
    }]);<|endoftext|>


<commit_before>'use strict';
const CLICommand = require('./cliCommand.js');
const CLIObjects = require('./cliObjects.js');
const messages = require('./messages.js');
const tools = require('../tools.js');
const forge = require('node-forge');
const os = require('os');

/** Command ioBroker cert ... */
module.exports = class CLICert extends CLICommand {

    /** @param {import('./cliCommand.js').CLICommandOptions} options */
    constructor(options) {
        super(options);
    }

    /**
     * Executes a command
     * @param {any[]} args
     */
    execute(args) {
        const { callback, showHelp } = this.options;
        const command = args[0];

        switch (command) {
            case 'renew':
            case 'create':
                return this.create(args);
            default:
                messages.error.unknownCommand('cert', command);
                showHelp();
                return void callback(3);
        }
    }

    /**
     * create new private certificate
     * @param {any[]} [_args]
     */
    create(_args) {

        // If at any time you wish to disable the use of native code, where available, for particular forge features
        // like its secure random number generator, you may set the forge.options.usePureJavaScript flag to true. It
        // is not recommended that you set this flag as native code is typically more performant and may have stronger
        // security properties. It may be useful to set this flag to test certain features that you plan to run in
        // environments that are different from your testing environment.
        forge.options.usePureJavaScript = false;

        const id = 'system.certificates';
        const certPropPath = 'native.certificates';

        // https://github.com/digitalbazaar/forge
        const pki = forge.pki;

        const keys = pki.rsa.generateKeyPair({ bits: 2048, e: 0x10001 });
        const cert = pki.createCertificate();

        cert.publicKey = keys.publicKey;
        cert.serialNumber = '0' + makeid(18);
        cert.validity.notBefore = new Date();
        cert.validity.notAfter = new Date();
        cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + 5);

        const subAttrs = [
            { name: 'commonName', value: tools.getHostName() },
            { name: 'organizationName', value: 'ioBroker GmbH' },
            { shortName: 'OU', value: 'iobroker' }
        ];

        const issAttrs = [
            { name: 'commonName', value: 'iobroker' },
            { name: 'organizationName', value: 'ioBroker GmbH' },
            { shortName: 'OU', value: 'iobroker' }
        ];

        cert.setSubject(subAttrs);
        cert.setIssuer(issAttrs);

        cert.setExtensions([{
            name: 'basicConstraints',
            critical: true,
            cA: false
        },
        {
            name: 'keyUsage',
            critical: true,
            digitalSignature: true,
            contentCommitment: true,
            keyEncipherment: true,
            dataEncipherment: true,
            keyAgreement: true,
            keyCertSign: true,
            cRLSign: true,
            encipherOnly: true,
            decipherOnly: true
        },
        {
            name: 'subjectAltName',
            altNames: [{
                type: 2,
                value: os.hostname()
            }]
        },
        {
            name: 'subjectKeyIdentifier'
        },
        {
            name: 'extKeyUsage',
            serverAuth: true,
            clientAuth: true,
            codeSigning: false,
            emailProtection: false,
            timeStamping: false
        },
        {
            name: 'authorityKeyIdentifier'
        }
        ]);

        cert.sign(keys.privateKey, forge.md.sha256.create());

        const pem_pkey = pki.privateKeyToPem(keys.privateKey);
        const pem_cert = pki.certificateToPem(cert);

        console.log(pem_pkey);
        console.log(pem_cert);

        const certificates = {
            defaultPrivate: pem_pkey,
            defaultPublic: pem_cert
        };

        // use the command `iobroker object set ...` to update the certificate
        const objectsCommandArgs = ['set', id, certPropPath + '=' + JSON.stringify(certificates)];
        const objectsCommand = new CLIObjects(this.options);
        objectsCommand.execute(objectsCommandArgs);
    }

};

function makeid(length) {
    var result           = '';
    var characters       = 'abcdef0123456789';
    var charactersLength = characters.length;
    for ( var i = 0; i < length; i++ ) {
       result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }
    return result;
 }
<commit_msg>Update cliCert.js<commit_after>'use strict';
const CLICommand = require('./cliCommand.js');
const CLIObjects = require('./cliObjects.js');
const messages = require('./messages.js');
const tools = require('../tools.js');
const forge = require('node-forge');
const os = require('os');

/** Command ioBroker cert ... */
module.exports = class CLICert extends CLICommand {

    /** @param {import('./cliCommand.js').CLICommandOptions} options */
    constructor(options) {
        super(options);
    }

    /**
     * Executes a command
     * @param {any[]} args
     */
    execute(args) {
        const { callback, showHelp } = this.options;
        const command = args[0];

        switch (command) {
            case 'renew':
            case 'create':
                return this.create(args);
            default:
                messages.error.unknownCommand('cert', command);
                showHelp();
                return void callback(3);
        }
    }

    /**
     * create new private certificate
     * @param {any[]} [_args]
     */
    create(_args) {

        // If at any time you wish to disable the use of native code, where available, for particular forge features
        // like its secure random number generator, you may set the forge.options.usePureJavaScript flag to true. It
        // is not recommended that you set this flag as native code is typically more performant and may have stronger
        // security properties. It may be useful to set this flag to test certain features that you plan to run in
        // environments that are different from your testing environment.
        forge.options.usePureJavaScript = false;

        const id = 'system.certificates';
        const certPropPath = 'native.certificates';

        // https://github.com/digitalbazaar/forge
        const pki = forge.pki;

        const keys = pki.rsa.generateKeyPair({ bits: 2048, e: 0x10001 });
        const cert = pki.createCertificate();

        cert.publicKey = keys.publicKey;
        cert.serialNumber = '0' + makeid(17);
        cert.validity.notBefore = new Date();
        cert.validity.notAfter = new Date();
        cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + 5);

        const subAttrs = [
            { name: 'commonName', value: tools.getHostName() },
            { name: 'organizationName', value: 'ioBroker GmbH' },
            { shortName: 'OU', value: 'iobroker' }
        ];

        const issAttrs = [
            { name: 'commonName', value: 'iobroker' },
            { name: 'organizationName', value: 'ioBroker GmbH' },
            { shortName: 'OU', value: 'iobroker' }
        ];

        cert.setSubject(subAttrs);
        cert.setIssuer(issAttrs);

        cert.setExtensions([{
            name: 'basicConstraints',
            critical: true,
            cA: false
        },
        {
            name: 'keyUsage',
            critical: true,
            digitalSignature: true,
            contentCommitment: true,
            keyEncipherment: true,
            dataEncipherment: true,
            keyAgreement: true,
            keyCertSign: true,
            cRLSign: true,
            encipherOnly: true,
            decipherOnly: true
        },
        {
            name: 'subjectAltName',
            altNames: [{
                type: 2,
                value: os.hostname()
            }]
        },
        {
            name: 'subjectKeyIdentifier'
        },
        {
            name: 'extKeyUsage',
            serverAuth: true,
            clientAuth: true,
            codeSigning: false,
            emailProtection: false,
            timeStamping: false
        },
        {
            name: 'authorityKeyIdentifier'
        }
        ]);

        cert.sign(keys.privateKey, forge.md.sha256.create());

        const pem_pkey = pki.privateKeyToPem(keys.privateKey);
        const pem_cert = pki.certificateToPem(cert);

        console.log(pem_pkey);
        console.log(pem_cert);

        const certificates = {
            defaultPrivate: pem_pkey,
            defaultPublic: pem_cert
        };

        // use the command `iobroker object set ...` to update the certificate
        const objectsCommandArgs = ['set', id, certPropPath + '=' + JSON.stringify(certificates)];
        const objectsCommand = new CLIObjects(this.options);
        objectsCommand.execute(objectsCommandArgs);
    }

};

function makeid(length) {
    var result           = '';
    var characters       = 'abcdef0123456789';
    var charactersLength = characters.length;
    for ( var i = 0; i < length; i++ ) {
       result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }
    return result;
 }
<|endoftext|>


<commit_before>import path from 'path';
import fs from 'fs';
import { sync as spawnSync } from 'cross-spawn';
import hasYarn from './has_yarn';
import latestVersion from './latest_version';
import { commandLog } from './helpers';

const logger = console;
export const storybookAddonScope = '@storybook/addon-';

const isAddon = async (name, npmOptions) => {
  try {
    await latestVersion(npmOptions, name);
    return true;
  } catch (e) {
    return false;
  }
};

const isStorybookAddon = async (name, npmOptions) =>
  isAddon(`${storybookAddonScope}${name}`, npmOptions);

const installAddon = (addonName, npmOptions) => {
  const prepareDone = commandLog(`Preparing to install the ${addonName} Storybook addon`);
  prepareDone();
  logger.log();

  let result;
  if (npmOptions.useYarn) {
    result = spawnSync('yarn', ['add', `${storybookAddonScope}${addonName}`, '--dev'], {
      stdio: 'inherit',
    });
  } else {
    result = spawnSync('npm', ['install', `${storybookAddonScope}${addonName}`, '--save-dev'], {
      stdio: 'inherit',
    });
  }

  logger.log();
  const installDone = commandLog(`Installing the ${addonName} Storybook addon`);
  if (result.status !== 0) {
    installDone(`Something went wrong installing the addon: "${storybookAddonScope}${addonName}"`);
    logger.log();
    process.exit(1);
  }
  installDone();
};

export const addStorybookAddonToFile = (addonName, addonsFile) => {
  const addonNameNoTag = addonName.split('@')[0];
  const alreadyRegistered = addonsFile.find(line => line.includes(`${addonNameNoTag}/register`));

  if (alreadyRegistered) {
    return addonsFile;
  }

  const latestImportIndex = addonsFile.reduce(
    (prev, curr, currIndex) =>
      curr.startsWith('import') && curr.includes('register') ? currIndex : prev,
    -1
  );

  return [
    ...addonsFile.slice(0, latestImportIndex + 1),
    `import '${storybookAddonScope}${addonNameNoTag}/register';`,
    ...addonsFile.slice(latestImportIndex + 1),
  ];
};

const registerAddon = addonName => {
  const registerDone = commandLog(`Registering the ${addonName} Storybook addon`);
  const addonsFilePath = path.resolve('.storybook/addons.js');
  const addonsFile = fs
    .readFileSync(addonsFilePath)
    .toString()
    .split('\n');
  fs.writeFileSync(addonsFilePath, addStorybookAddonToFile(addonName, addonsFile).join('\n'));
  registerDone();
};

export default async function add(addonName, options) {
  const useYarn = Boolean(options.useNpm !== true) && hasYarn();
  const npmOptions = {
    useYarn,
  };
  const addonCheckDone = commandLog(`Verifying that ${addonName} is an addon`);
  if (await isStorybookAddon(addonName, npmOptions)) {
    addonCheckDone();
    installAddon(addonName, npmOptions);
    registerAddon(addonName);
  } else {
    addonCheckDone(`The provided package was not a Storybook addon: ${addonName}.`);
  }
}
<commit_msg>Make it possible to install any addon<commit_after>import path from 'path';
import fs from 'fs';
import { sync as spawnSync } from 'cross-spawn';
import hasYarn from './has_yarn';
import latestVersion from './latest_version';
import { commandLog } from './helpers';

const logger = console;
export const storybookAddonScope = '@storybook/addon-';

const isAddon = async (name, npmOptions) => {
  try {
    await latestVersion(npmOptions, name);
    return true;
  } catch (e) {
    return false;
  }
};

const isStorybookAddon = async (name, npmOptions) =>
  isAddon(`${storybookAddonScope}${name}`, npmOptions);

const installAddon = (addonName, npmOptions, isAStorybookAddon) => {
  const prepareDone = commandLog(`Preparing to install the ${addonName} Storybook addon`);
  prepareDone();
  logger.log();

  let result;
  const packageName = isAStorybookAddon ? `${storybookAddonScope}${addonName}` : addonName;
  if (npmOptions.useYarn) {
    result = spawnSync('yarn', ['add', packageName, '--dev'], {
      stdio: 'inherit',
    });
  } else {
    result = spawnSync('npm', ['install', packageName, '--save-dev'], {
      stdio: 'inherit',
    });
  }

  logger.log();
  const installDone = commandLog(`Installing the ${addonName} Storybook addon`);
  if (result.status !== 0) {
    installDone(`Something went wrong installing the addon: "${packageName}"`);
    logger.log();
    process.exit(1);
  }
  installDone();
};

export const addStorybookAddonToFile = (addonName, addonsFile) => {
  const addonNameNoTag = addonName.split('@')[0];
  const alreadyRegistered = addonsFile.find(line => line.includes(`${addonNameNoTag}/register`));

  if (alreadyRegistered) {
    return addonsFile;
  }

  const latestImportIndex = addonsFile.reduce(
    (prev, curr, currIndex) =>
      curr.startsWith('import') && curr.includes('register') ? currIndex : prev,
    -1
  );

  return [
    ...addonsFile.slice(0, latestImportIndex + 1),
    `import '${storybookAddonScope}${addonNameNoTag}/register';`,
    ...addonsFile.slice(latestImportIndex + 1),
  ];
};

const registerAddon = addonName => {
  const registerDone = commandLog(`Registering the ${addonName} Storybook addon`);
  const addonsFilePath = path.resolve('.storybook/addons.js');
  const addonsFile = fs
    .readFileSync(addonsFilePath)
    .toString()
    .split('\n');
  fs.writeFileSync(addonsFilePath, addStorybookAddonToFile(addonName, addonsFile).join('\n'));
  registerDone();
};

export default async function add(addonName, options) {
  const useYarn = Boolean(options.useNpm !== true) && hasYarn();
  const npmOptions = {
    useYarn,
  };
  const addonCheckDone = commandLog(`Verifying that ${addonName} is an addon`);
  const isAStorybookAddon = await isStorybookAddon(addonName, npmOptions);
  if (isAStorybookAddon) {
    addonCheckDone();
    installAddon(addonName, npmOptions, isAStorybookAddon);
    registerAddon(addonName);
  } else {
    addonCheckDone(`The provided package was not a Storybook addon: ${addonName}.`);
  }
}
<|endoftext|>


<commit_before>/*eslint indent:0*/
var
  _ = require('lodash'),
  util = require('util'),
  moment = require('moment'),
  path = require('path'),

  log = require('fedtools-logs'),
  config = require('fedtools-config'),

  common = require('../common'),

  EnvtoolsBase = require('./base'),
  EnvtoolsVersion;

// -- C O N S T R U C T O R

EnvtoolsVersion = function () {
  EnvtoolsBase.call(this);
};

// -- I N H E R I T A N C E

util.inherits(EnvtoolsVersion, EnvtoolsBase);
EnvtoolsVersion.prototype.name = 'EnvtoolsVersion';

// -- E X T E N D E D  M E T H O D S

EnvtoolsVersion.prototype._initialize = function () {
  var
    rcInfo,
    canCheck = false,
    needToCheck = false;

  EnvtoolsBase.prototype._initialize.call(this);

  // check for current version
  this.currentVersion = this.packageJson.version;

  // checking if the version was already benn checked recently
  rcInfo = this._getConfiguration();
  if (rcInfo && rcInfo[common.ENVTOOLS.CFG_AUTOCHECK] === common.ON) {
    canCheck = true;
  }
  if (canCheck && rcInfo && rcInfo.expiration) {
    // all the keys are here, let's check the expiration
    if (moment().isAfter(rcInfo.expiration)) {
      // time's out, need to check if there is a new version
      // Spawn a detached process that will update the key 'version'
      // from the .fedtoolsrc file with the following sub-keys:
      // version: {
      //   expiration: Now + 1d
      //   latest: x.y.z
      // }
      // It's non-blocking so the next time envtools run, just
      // checking the .fedtoolsrc file is enough.
      needToCheck = true;
    }
  } else {
    needToCheck = canCheck;
  }

  if (needToCheck) {
    require('child_process')
      .spawn(process.execPath, [path.join(__dirname, '..', '..', 'bin', 'check.js')], {
        detached: true,
        stdio: 'ignore'
      }).unref();
  }
};

// -- P R I V A T E  M E T H O D S
EnvtoolsVersion.prototype._getConfiguration = function () {
  return config.getKey('envtoolsversion');
};

// -- P U B L I C  M E T H O D S

EnvtoolsVersion.prototype.setAutoCheck = function (flag) {
  var
    o = {};
  o[common.ENVTOOLS.CFG_AUTOCHECK] = flag;
  config.setKey('envtoolsversion', _.extend(this._getConfiguration(), o), true, true);
};

EnvtoolsVersion.prototype.getAutoCheck = function () {
  var
    cfg = this._getConfiguration();

  if (cfg) {
    return (cfg[common.ENVTOOLS.CFG_AUTOCHECK]) ? cfg[common.ENVTOOLS.CFG_AUTOCHECK] : common.OFF;
  } else {
    return common.OFF;
  }
};

/**
 * This method will read the .fedtoolrc configuration file.
 * It will then display the 'update available' box if the one of
 * the following is true:
 * 1) cfg.alreadyDisplayed is falsy and cfg.latest is truthy
 * 2) force is true and cfg.latest is truthy
 * If it does, it will also update the configuration file to mark
 * that the message has been displayed to the user. (no need to
 * display it again. This flag will be removed automatically after
 * one day).
 *
 * @method printUpgradeIfAny
 * @param  {Boolean} force If true, ignore the 'alreadyDisplayed' key
 */
EnvtoolsVersion.prototype.printUpgradeIfAny = function (force) {
  var
    self = this,
    msg = [],
    lightGrey = 245,
    rcInfo = this._getConfiguration() || {},
    LATEST_IS_INSTALLED = 'You are up-to-date!',
    NO_DATA_AVAILABLE = 'There is no data available at this time.\nPlease check again later...',
    AUTOCHECK_DISABLED = 'Automatically check for update is disabled.\nYou can enable this option by typing ' +
    log.strToColor(lightGrey, 'envtools config') +
    '\nand following the instructions at the prompt.';

  function printCustomMessage(msgs, boxColor) {
    log.echo();
    log.printMessagesInBox(msgs, (boxColor) ? boxColor : 'yellow');
    log.echo();
    return true;
  }

  if (force && !rcInfo) {
    return printCustomMessage([NO_DATA_AVAILABLE]);
  }

  if (force && rcInfo[common.ENVTOOLS.CFG_AUTOCHECK] !== common.ON) {
    return printCustomMessage([AUTOCHECK_DISABLED]);
  }

  if (rcInfo.latest) {
    if (require('semver').gt(rcInfo.latest, self.currentVersion)) {
      msg.push('');
      msg.push('A new version of Envtools has been published!');
      msg.push('Envtools ' +
        log.strToColor('green', rcInfo.latest) +
        ' is now available - you have ' +
        log.strToColor(lightGrey, self.currentVersion));
      msg.push('Type ' +
        log.strToColor(lightGrey, 'npm i -g envtools') +
        ' to upgrade.');
      msg.push('');
    } else {
      msg.push('');
      msg.push(LATEST_IS_INSTALLED);
      msg.push('');
    }
  }

  if (msg.length && (!rcInfo.alreadyDisplayed || force)) {
    // need to mark version as displayed so that it won't
    // be shown to the user again (until the expiration date)
    config.setKey('envtoolsversion', _.extend(rcInfo, {
      alreadyDisplayed: true
    }), true, true);

    return printCustomMessage(msg, 'green');
  }
};

/**
 * This method is supposed to be called explicitely by the user (for
 * example, envtools -v). In that case, we assume that we can present
 * the current version, but also the 'update available' message.
 *
 * @method printCurrentVersion
 */
EnvtoolsVersion.prototype.printCurrentVersion = function (boring, done) {
  if (!this.printUpgradeIfAny()) {
    log.echo();
    log.printMessagesInBox([
      this.i18n.t('version.installed') + log.strToColor('green', this.currentVersion)
    ]);
    log.echo();
  }
  done();
};

// -- E X P O R T S
module.exports = (function () {
  return EnvtoolsVersion._instance || new EnvtoolsVersion();
})();
<commit_msg>No need to be cheap on the actual words<commit_after>/*eslint indent:0*/
var
  _ = require('lodash'),
  util = require('util'),
  moment = require('moment'),
  path = require('path'),

  log = require('fedtools-logs'),
  config = require('fedtools-config'),

  common = require('../common'),

  EnvtoolsBase = require('./base'),
  EnvtoolsVersion;

// -- C O N S T R U C T O R

EnvtoolsVersion = function () {
  EnvtoolsBase.call(this);
};

// -- I N H E R I T A N C E

util.inherits(EnvtoolsVersion, EnvtoolsBase);
EnvtoolsVersion.prototype.name = 'EnvtoolsVersion';

// -- E X T E N D E D  M E T H O D S

EnvtoolsVersion.prototype._initialize = function () {
  var
    rcInfo,
    canCheck = false,
    needToCheck = false;

  EnvtoolsBase.prototype._initialize.call(this);

  // check for current version
  this.currentVersion = this.packageJson.version;

  // checking if the version was already benn checked recently
  rcInfo = this._getConfiguration();
  if (rcInfo && rcInfo[common.ENVTOOLS.CFG_AUTOCHECK] === common.ON) {
    canCheck = true;
  }
  if (canCheck && rcInfo && rcInfo.expiration) {
    // all the keys are here, let's check the expiration
    if (moment().isAfter(rcInfo.expiration)) {
      // time's out, need to check if there is a new version
      // Spawn a detached process that will update the key 'version'
      // from the .fedtoolsrc file with the following sub-keys:
      // version: {
      //   expiration: Now + 1d
      //   latest: x.y.z
      // }
      // It's non-blocking so the next time envtools run, just
      // checking the .fedtoolsrc file is enough.
      needToCheck = true;
    }
  } else {
    needToCheck = canCheck;
  }

  if (needToCheck) {
    require('child_process')
      .spawn(process.execPath, [path.join(__dirname, '..', '..', 'bin', 'check.js')], {
        detached: true,
        stdio: 'ignore'
      }).unref();
  }
};

// -- P R I V A T E  M E T H O D S
EnvtoolsVersion.prototype._getConfiguration = function () {
  return config.getKey('envtoolsversion');
};

// -- P U B L I C  M E T H O D S

EnvtoolsVersion.prototype.setAutoCheck = function (flag) {
  var
    o = {};
  o[common.ENVTOOLS.CFG_AUTOCHECK] = flag;
  config.setKey('envtoolsversion', _.extend(this._getConfiguration(), o), true, true);
};

EnvtoolsVersion.prototype.getAutoCheck = function () {
  var
    cfg = this._getConfiguration();

  if (cfg) {
    return (cfg[common.ENVTOOLS.CFG_AUTOCHECK]) ? cfg[common.ENVTOOLS.CFG_AUTOCHECK] : common.OFF;
  } else {
    return common.OFF;
  }
};

/**
 * This method will read the .fedtoolrc configuration file.
 * It will then display the 'update available' box if the one of
 * the following is true:
 * 1) cfg.alreadyDisplayed is falsy and cfg.latest is truthy
 * 2) force is true and cfg.latest is truthy
 * If it does, it will also update the configuration file to mark
 * that the message has been displayed to the user. (no need to
 * display it again. This flag will be removed automatically after
 * one day).
 *
 * @method printUpgradeIfAny
 * @param  {Boolean} force If true, ignore the 'alreadyDisplayed' key
 */
EnvtoolsVersion.prototype.printUpgradeIfAny = function (force) {
  var
    self = this,
    msg = [],
    lightGrey = 245,
    rcInfo = this._getConfiguration() || {},
    LATEST_IS_INSTALLED = 'You are up-to-date!',
    NO_DATA_AVAILABLE = 'There is no data available at this time.\nPlease check again later...',
    AUTOCHECK_DISABLED = 'Automatically check for update is disabled.\nYou can enable this option by typing ' +
    log.strToColor(lightGrey, 'envtools config') +
    '\nand following the instructions at the prompt.';

  function printCustomMessage(msgs, boxColor) {
    log.echo();
    log.printMessagesInBox(msgs, (boxColor) ? boxColor : 'yellow');
    log.echo();
    return true;
  }

  if (force && !rcInfo) {
    return printCustomMessage([NO_DATA_AVAILABLE]);
  }

  if (force && rcInfo[common.ENVTOOLS.CFG_AUTOCHECK] !== common.ON) {
    return printCustomMessage([AUTOCHECK_DISABLED]);
  }

  if (rcInfo.latest) {
    if (require('semver').gt(rcInfo.latest, self.currentVersion)) {
      msg.push('');
      msg.push('A new version of Envtools has been published!');
      msg.push('Envtools ' +
        log.strToColor('green', rcInfo.latest) +
        ' is now available - you have ' +
        log.strToColor(lightGrey, self.currentVersion));
      msg.push('Type ' +
        log.strToColor(lightGrey, 'npm install -g envtools') +
        ' to upgrade.');
      msg.push('');
    } else {
      msg.push('');
      msg.push(LATEST_IS_INSTALLED);
      msg.push('');
    }
  }

  if (msg.length && (!rcInfo.alreadyDisplayed || force)) {
    // need to mark version as displayed so that it won't
    // be shown to the user again (until the expiration date)
    config.setKey('envtoolsversion', _.extend(rcInfo, {
      alreadyDisplayed: true
    }), true, true);

    return printCustomMessage(msg, 'green');
  }
};

/**
 * This method is supposed to be called explicitely by the user (for
 * example, envtools -v). In that case, we assume that we can present
 * the current version, but also the 'update available' message.
 *
 * @method printCurrentVersion
 */
EnvtoolsVersion.prototype.printCurrentVersion = function (boring, done) {
  if (!this.printUpgradeIfAny()) {
    log.echo();
    log.printMessagesInBox([
      this.i18n.t('version.installed') + log.strToColor('green', this.currentVersion)
    ]);
    log.echo();
  }
  done();
};

// -- E X P O R T S
module.exports = (function () {
  return EnvtoolsVersion._instance || new EnvtoolsVersion();
})();
<|endoftext|>


<commit_before>var CloudCmd, Util, DOM, CloudFunc, ace, DiffProto, diff_match_patch, Zip;
(function(CloudCmd, Util, DOM, CloudFunc) {
    'use strict';

    CloudCmd.Edit = EditProto;

    function EditProto() {
        var Name        = 'Edit',
            Loading     = false,
            DIR         = CloudCmd.LIBDIRCLIENT + 'edit/',
            LIBDIR      = CloudCmd.LIBDIR,
            Info        = DOM.CurrentInfo,
            Value,
            Edit        = this,
            Diff,
            Emmet,
            Ace,
            Session,
            Modelist,
            Msg,
            Events      = DOM.Events,
            Dialog      = DOM.Dialog,
            Images      = DOM.Images,
            Element, JSHintConfig;

       function init() {
            Loading   = true;
            Util.loadOnLoad([
                CloudCmd.View,
                load,
                Edit.show
            ]);
        }

        this.show                       = function(value) {
            var mode, htmlMode, jsMode, isHTML, isJS, modesByName,
                isStr       = Util.isString(value),
                name        = Info.name,
                isDir       = Info.isDir,
                focus       = function() {
                    Ace.focus();
                    Ace.clearSelection();
                    Ace.moveCursorTo(0, 0);
                };

            if (!Loading) {
                Images.showLoad();

                if (!Element) {
                    Element         = DOM.anyload({
                        name        : 'div',
                        style   :
                            'width      : 100%;'    +
                            'height     : 100%;'    +
                            'font       : 16px "Droid Sans Mono";' +
                            'position   : absolute;',
                        not_append : true
                    });

                  initAce();

                  Events.add({
                      drop      : onDrop,
                      dragover  : function(event) {
                          event.preventDefault();
                      }
                  }, Element);
                }

                modesByName = Modelist.modesByName;

                if (isDir)
                    mode    = modesByName.json.mode;
                else
                    mode    = Modelist.getModeForPath(name).mode;

                htmlMode    = modesByName.html.mode;
                jsMode      = modesByName.javascript.mode;

                isHTML      = mode === htmlMode;
                isJS        = mode === jsMode;

                Session.setMode(mode);

                Util.ifExec(Emmet, function() {
                    if (Emmet)
                        Ace.setOption('enableEmmet', isHTML);
                }, function(callback) {
                    var url;

                    if (!isHTML)
                        Util.exec(callback);
                    else {
                        url = CloudFunc.getJoinURL([
                            DIR + 'emmet.js',
                            DIR + 'ext-emmet.js'
                        ]);

                        DOM.jsload(url, function() {
                            Emmet = ace.require('ace/ext/emmet');
                            Emmet.setCore(window.emmet);
                            Util.exec(callback);
                        });
                    }
                });

                Util.ifExec(isStr, function() {
                    var UndoManager = ace.require("ace/undomanager").UndoManager;

                    Ace.setValue(Value);
                    CloudCmd.View.show(Element, focus);

                    Session.setUndoManager(new UndoManager());
                }, function(callback) {
                    Info.getData(function(data) {
                        Value = data;

                        if (isJS && Session.getUseWorker())
                            setJsHintConfig();

                        callback();
                    });
                });
            }
        };

        this.hide                       =  function() {
            CloudCmd.View.hide();
        };

        this.goToLine                   = function() {
            var msg     = 'Enter line number:',
                cursor  = Ace.selection.getCursor(),
                number  = cursor.row + 1,
                line    = Dialog.prompt(msg, number);

            number      = line - 0;

            if (number)
                Ace.gotoLine(number);
        };

        function initAce() {
            Ace     = ace.edit(Element);
            Session = Ace.getSession();

            Ace.setTheme('ace/theme/tomorrow_night_blue');

            Ace.setShowPrintMargin(false);
            Ace.setShowInvisibles(true);
            Session.setUseSoftTabs(true);

            Ace.commands.addCommand({
                name    : 'hide',
                bindKey : { win: 'Esc',  mac: 'Esc' },
                exec    : function () {
                    Edit.hide();
                }
            });

            Ace.commands.addCommand({
                name    : 'goToLine',
                bindKey : { win: 'Ctrl-G',  mac: 'Command-G' },
                exec    : function () {
                    Edit.goToLine();
                }
            });

            Ace.commands.addCommand({
                name    : 'save',
                bindKey : { win: 'Ctrl-S',  mac: 'Command-S' },
                exec    : save
            });

            Ace.commands.addCommand({
                name    : 'saveMC',
                bindKey : { win: 'F2',  mac: 'F2' },
                exec    : save
            });

            ace.require('ace/ext/language_tools');
            Modelist = ace.require('ace/ext/modelist');

            Ace.setOptions({
                enableBasicAutocompletion   : true,
                enableSnippets              : true
            });
        }

        function save () {
            var path    = Info.path,
                value   = Ace.getValue();

            CloudCmd.getConfig(function(config) {
                var isDiff      = config.diff,
                    isZip       = config.zip;

                Util.ifExec(!isDiff, function(patch) {
                    var query           = '',
                        MAX_SIZE        = CloudFunc.MAX_FILE_SIZE,
                        patchLength     = patch.length,
                        length          = Value.length,
                        isLessMaxLength = length < MAX_SIZE,
                        isLessLength    = isLessMaxLength && patchLength < length,
                        isStr           = Util.isString(patch);

                    Value               = value;

                    if (isStr && patch && isLessLength)
                        query           = '?patch';
                    else
                        patch           = false;

                    Util.ifExec(!isZip || query, function(equal, data) {
                        var result  = data || patch || Value,
                            url     = path + query;

                        DOM.RESTful.write(url, result , onSave);
                    }, function(func) {
                        zip(value, function(error, data) {
                            if (error)
                                Util.log(error);

                            query = '?unzip';
                            func(null, data);
                        });
                    });

                }, Util.bind(doDiff, path));
            });
        }

        function doDiff(path, callback) {
            var value = Ace.getValue();

            diff(value, function(patch) {
                var isAllowed = DOM.Storage.isAllowed();

                Util.ifExec(!isAllowed, callback, function(func) {
                        DOM.checkStorageHash(path, function(error, equal) {
                            if (!equal)
                                patch = '';

                            func(patch);
                        });
                });
            });
        }

        function diff(newValue, callback) {
            var libs            = [
                    LIBDIR + 'diff/diff-match-patch.js',
                    LIBDIR + 'diff.js'
                ],
                url             = CloudFunc.getJoinURL(libs);

            DOM.jsload(url, function() {
                var patch,
                    isAllowed   = DOM.Storage.isAllowed();

                if (!Diff)
                    Diff        = new DiffProto(diff_match_patch);

                Util.ifExec(!isAllowed, function() {
                    patch       = Diff.createPatch(Value, newValue);
                    Util.exec(callback, patch);
                }, function(func) {
                    var path = Info.path;

                    DOM.getDataFromStorage(path, function(data) {
                        if (data)
                            Value   = data;

                        func();
                    });
                });
            });
        }

        function zip(value, callback) {
            var dir             = CloudCmd.LIBDIRCLIENT,
                libs            = [
                    dir + 'zip/dist/pako.js',
                    dir + 'zip.js'
                ],
                url             = CloudFunc.getJoinURL(libs);

            DOM.jsload(url, function() {
                Zip.pack(value, callback);
            });
        }

        function setJsHintConfig(callback) {
            var JSHINT_PATH = '/.jshintrc',
                func        = function() {
                    var worker  = Session.$worker;

                    if (worker)
                        worker.send('changeOptions', [JSHintConfig]);

                    Util.exec(callback);
                };

            Util.ifExec(JSHintConfig, func, function() {
                DOM.ajax({
                    url     :  JSHINT_PATH,
                    success : function(data) {
                        JSHintConfig = Util.parseJSON(data);
                        func();
                    }
                });
            });
        }

        function load(callback) {
            var files  = [
                    DIR + 'theme-tomorrow_night_blue.js',
                    DIR + 'ext-language_tools.js',
                    DIR + 'ext-searchbox.js',
                    DIR + 'ext-modelist.js'
                ],

                ace     = DIR + 'ace.js',
                url     = CloudFunc.getJoinURL(files);

            Util.time(Name + ' load');

            DOM.anyLoadOnLoad([ace, url], function() {
                Util.timeEnd(Name + ' load');
                Loading = false;
                Util.exec(callback);
            });
        }

        function onSave(text) {
            var ret,
                isError = Util.isContainStrAtBegin(text, 'error'),
                path    = Info.path,
                msg     = '\nShould I save file anyway?';

            if (!isError) {
                Edit.showMessage(text);
                DOM.saveDataToStorage(path, Value);
                DOM.setCurrentSize(Value.length);
            } else {
                ret     = Dialog.confirm(text + msg);

                if (ret)
                    DOM.RESTful.write(path, Value, onSave);
            }
        }

         function onDrop(event) {
            var reader, i, n, file, files,
                onLoad   =  function(event) {
                    var data    = event.target.result;

                    Ace.setValue(data);
                };

            event.preventDefault();

            files               = event.dataTransfer.files;

            if (files.length) {
                n               = files.length;

                for (i = 0; i < n; i++) {
                    reader          = new FileReader();
                    file            = files[i];

                    DOM.Events.add('load', onLoad, reader);
                    reader.readAsBinaryString(file);
                }
            }
        }

        this.showMessage    = function(text) {
            var parent,
                HIDE_TIME = 2000;

            if (!Msg) {
                DOM.cssSet({
                    id      : 'msg-css',
                    inner   : '#view .msg {'        +
                                'z-index'           + ': 1;'                    +
                                'background-color'  + ': #7285B7;'              +
                                'color'             + ': #D1F1A9;'              +
                                'position'          + ': fixed;'                +
                                'left'              + ': 40%;'                  +
                                'top'               + ': 25px;'                 +
                                'padding'           + ': 5px;'                  +
                                'opacity'           + ': 0.9;'                  +
                                'transition'        + ': ease 0.5s;'            +
                            '}'
                });
                parent  = Element;

                Msg     = DOM.anyload({
                    name        : 'div',
                    className   : 'msg',
                    parent      : parent
                });
            }

            Msg.innerHTML = text;
            DOM.show(Msg);
            setTimeout(Util.retExec(DOM.hide, Msg), HIDE_TIME);
        };

        init();
    }

})(CloudCmd, Util, DOM, CloudFunc);
<commit_msg>chore(edit) fix quotes<commit_after>var CloudCmd, Util, DOM, CloudFunc, ace, DiffProto, diff_match_patch, Zip;
(function(CloudCmd, Util, DOM, CloudFunc) {
    'use strict';

    CloudCmd.Edit = EditProto;

    function EditProto() {
        var Name        = 'Edit',
            Loading     = false,
            DIR         = CloudCmd.LIBDIRCLIENT + 'edit/',
            LIBDIR      = CloudCmd.LIBDIR,
            Info        = DOM.CurrentInfo,
            Value,
            Edit        = this,
            Diff,
            Emmet,
            Ace,
            Session,
            Modelist,
            Msg,
            Events      = DOM.Events,
            Dialog      = DOM.Dialog,
            Images      = DOM.Images,
            Element, JSHintConfig;

       function init() {
            Loading   = true;
            Util.loadOnLoad([
                CloudCmd.View,
                load,
                Edit.show
            ]);
        }

        this.show                       = function(value) {
            var mode, htmlMode, jsMode, isHTML, isJS, modesByName,
                isStr       = Util.isString(value),
                name        = Info.name,
                isDir       = Info.isDir,
                focus       = function() {
                    Ace.focus();
                    Ace.clearSelection();
                    Ace.moveCursorTo(0, 0);
                };

            if (!Loading) {
                Images.showLoad();

                if (!Element) {
                    Element         = DOM.anyload({
                        name        : 'div',
                        style   :
                            'width      : 100%;'    +
                            'height     : 100%;'    +
                            'font       : 16px "Droid Sans Mono";' +
                            'position   : absolute;',
                        not_append : true
                    });

                  initAce();

                  Events.add({
                      drop      : onDrop,
                      dragover  : function(event) {
                          event.preventDefault();
                      }
                  }, Element);
                }

                modesByName = Modelist.modesByName;

                if (isDir)
                    mode    = modesByName.json.mode;
                else
                    mode    = Modelist.getModeForPath(name).mode;

                htmlMode    = modesByName.html.mode;
                jsMode      = modesByName.javascript.mode;

                isHTML      = mode === htmlMode;
                isJS        = mode === jsMode;

                Session.setMode(mode);

                Util.ifExec(Emmet, function() {
                    if (Emmet)
                        Ace.setOption('enableEmmet', isHTML);
                }, function(callback) {
                    var url;

                    if (!isHTML)
                        Util.exec(callback);
                    else {
                        url = CloudFunc.getJoinURL([
                            DIR + 'emmet.js',
                            DIR + 'ext-emmet.js'
                        ]);

                        DOM.jsload(url, function() {
                            Emmet = ace.require('ace/ext/emmet');
                            Emmet.setCore(window.emmet);
                            Util.exec(callback);
                        });
                    }
                });

                Util.ifExec(isStr, function() {
                    var UndoManager = ace.require('ace/undomanager').UndoManager;

                    Ace.setValue(Value);
                    CloudCmd.View.show(Element, focus);

                    Session.setUndoManager(new UndoManager());
                }, function(callback) {
                    Info.getData(function(data) {
                        Value = data;

                        if (isJS && Session.getUseWorker())
                            setJsHintConfig();

                        callback();
                    });
                });
            }
        };

        this.hide                       =  function() {
            CloudCmd.View.hide();
        };

        this.goToLine                   = function() {
            var msg     = 'Enter line number:',
                cursor  = Ace.selection.getCursor(),
                number  = cursor.row + 1,
                line    = Dialog.prompt(msg, number);

            number      = line - 0;

            if (number)
                Ace.gotoLine(number);
        };

        function initAce() {
            Ace     = ace.edit(Element);
            Session = Ace.getSession();

            Ace.setTheme('ace/theme/tomorrow_night_blue');

            Ace.setShowPrintMargin(false);
            Ace.setShowInvisibles(true);
            Session.setUseSoftTabs(true);

            Ace.commands.addCommand({
                name    : 'hide',
                bindKey : { win: 'Esc',  mac: 'Esc' },
                exec    : function () {
                    Edit.hide();
                }
            });

            Ace.commands.addCommand({
                name    : 'goToLine',
                bindKey : { win: 'Ctrl-G',  mac: 'Command-G' },
                exec    : function () {
                    Edit.goToLine();
                }
            });

            Ace.commands.addCommand({
                name    : 'save',
                bindKey : { win: 'Ctrl-S',  mac: 'Command-S' },
                exec    : save
            });

            Ace.commands.addCommand({
                name    : 'saveMC',
                bindKey : { win: 'F2',  mac: 'F2' },
                exec    : save
            });

            ace.require('ace/ext/language_tools');
            Modelist = ace.require('ace/ext/modelist');

            Ace.setOptions({
                enableBasicAutocompletion   : true,
                enableSnippets              : true
            });
        }

        function save () {
            var path    = Info.path,
                value   = Ace.getValue();

            CloudCmd.getConfig(function(config) {
                var isDiff      = config.diff,
                    isZip       = config.zip;

                Util.ifExec(!isDiff, function(patch) {
                    var query           = '',
                        MAX_SIZE        = CloudFunc.MAX_FILE_SIZE,
                        patchLength     = patch.length,
                        length          = Value.length,
                        isLessMaxLength = length < MAX_SIZE,
                        isLessLength    = isLessMaxLength && patchLength < length,
                        isStr           = Util.isString(patch);

                    Value               = value;

                    if (isStr && patch && isLessLength)
                        query           = '?patch';
                    else
                        patch           = false;

                    Util.ifExec(!isZip || query, function(equal, data) {
                        var result  = data || patch || Value,
                            url     = path + query;

                        DOM.RESTful.write(url, result , onSave);
                    }, function(func) {
                        zip(value, function(error, data) {
                            if (error)
                                Util.log(error);

                            query = '?unzip';
                            func(null, data);
                        });
                    });

                }, Util.bind(doDiff, path));
            });
        }

        function doDiff(path, callback) {
            var value = Ace.getValue();

            diff(value, function(patch) {
                var isAllowed = DOM.Storage.isAllowed();

                Util.ifExec(!isAllowed, callback, function(func) {
                        DOM.checkStorageHash(path, function(error, equal) {
                            if (!equal)
                                patch = '';

                            func(patch);
                        });
                });
            });
        }

        function diff(newValue, callback) {
            var libs            = [
                    LIBDIR + 'diff/diff-match-patch.js',
                    LIBDIR + 'diff.js'
                ],
                url             = CloudFunc.getJoinURL(libs);

            DOM.jsload(url, function() {
                var patch,
                    isAllowed   = DOM.Storage.isAllowed();

                if (!Diff)
                    Diff        = new DiffProto(diff_match_patch);

                Util.ifExec(!isAllowed, function() {
                    patch       = Diff.createPatch(Value, newValue);
                    Util.exec(callback, patch);
                }, function(func) {
                    var path = Info.path;

                    DOM.getDataFromStorage(path, function(data) {
                        if (data)
                            Value   = data;

                        func();
                    });
                });
            });
        }

        function zip(value, callback) {
            var dir             = CloudCmd.LIBDIRCLIENT,
                libs            = [
                    dir + 'zip/dist/pako.js',
                    dir + 'zip.js'
                ],
                url             = CloudFunc.getJoinURL(libs);

            DOM.jsload(url, function() {
                Zip.pack(value, callback);
            });
        }

        function setJsHintConfig(callback) {
            var JSHINT_PATH = '/.jshintrc',
                func        = function() {
                    var worker  = Session.$worker;

                    if (worker)
                        worker.send('changeOptions', [JSHintConfig]);

                    Util.exec(callback);
                };

            Util.ifExec(JSHintConfig, func, function() {
                DOM.ajax({
                    url     :  JSHINT_PATH,
                    success : function(data) {
                        JSHintConfig = Util.parseJSON(data);
                        func();
                    }
                });
            });
        }

        function load(callback) {
            var files  = [
                    DIR + 'theme-tomorrow_night_blue.js',
                    DIR + 'ext-language_tools.js',
                    DIR + 'ext-searchbox.js',
                    DIR + 'ext-modelist.js'
                ],

                ace     = DIR + 'ace.js',
                url     = CloudFunc.getJoinURL(files);

            Util.time(Name + ' load');

            DOM.anyLoadOnLoad([ace, url], function() {
                Util.timeEnd(Name + ' load');
                Loading = false;
                Util.exec(callback);
            });
        }

        function onSave(text) {
            var ret,
                isError = Util.isContainStrAtBegin(text, 'error'),
                path    = Info.path,
                msg     = '\nShould I save file anyway?';

            if (!isError) {
                Edit.showMessage(text);
                DOM.saveDataToStorage(path, Value);
                DOM.setCurrentSize(Value.length);
            } else {
                ret     = Dialog.confirm(text + msg);

                if (ret)
                    DOM.RESTful.write(path, Value, onSave);
            }
        }

         function onDrop(event) {
            var reader, i, n, file, files,
                onLoad   =  function(event) {
                    var data    = event.target.result;

                    Ace.setValue(data);
                };

            event.preventDefault();

            files               = event.dataTransfer.files;

            if (files.length) {
                n               = files.length;

                for (i = 0; i < n; i++) {
                    reader          = new FileReader();
                    file            = files[i];

                    DOM.Events.add('load', onLoad, reader);
                    reader.readAsBinaryString(file);
                }
            }
        }

        this.showMessage    = function(text) {
            var parent,
                HIDE_TIME = 2000;

            if (!Msg) {
                DOM.cssSet({
                    id      : 'msg-css',
                    inner   : '#view .msg {'        +
                                'z-index'           + ': 1;'                    +
                                'background-color'  + ': #7285B7;'              +
                                'color'             + ': #D1F1A9;'              +
                                'position'          + ': fixed;'                +
                                'left'              + ': 40%;'                  +
                                'top'               + ': 25px;'                 +
                                'padding'           + ': 5px;'                  +
                                'opacity'           + ': 0.9;'                  +
                                'transition'        + ': ease 0.5s;'            +
                            '}'
                });
                parent  = Element;

                Msg     = DOM.anyload({
                    name        : 'div',
                    className   : 'msg',
                    parent      : parent
                });
            }

            Msg.innerHTML = text;
            DOM.show(Msg);
            setTimeout(Util.retExec(DOM.hide, Msg), HIDE_TIME);
        };

        init();
    }

})(CloudCmd, Util, DOM, CloudFunc);
<|endoftext|>


<commit_before>var Client = module.exports

var Promise = require("bluebird")
//var request = require("request")
var routes = require("../routes")
var axios = require("axios")

var d = require("debug")("raptorjs:client:http")

Client.create = function (container) {

    var emit = function() {
        container.emit.apply(container, arguments)
    }

    var opts = container.config

    var addDefaultHeaders = function(opts, token) {
        if(!opts.headers) {
            opts.headers = {
                "Content-Type": "application/json"
            }
        }
        if(token) {
            opts.headers.Authorization = `Bearer ${token}`
        }
    }

    var defaultsOptions = {
        baseUrl: opts.url
        //json: true,
        //debug: opts.debug
    }

    addDefaultHeaders(defaultsOptions)

    //var client = request.defaults(defaultsOptions)
    console.log('using axios')
    var client = axios.defaults(defaultsOptions)

    d("Created new client %s", defaultsOptions.baseUrl)

    var instance = {}

    instance.baseRequest = (options) => {
        return new Promise(function (resolve, reject) {

            options.headers = Object.assign({}, defaultsOptions.headers || {}, options.headers || {})

            d("Performing request %j", options)
            //client(options, function (err, res, body) {
            axios(options).then((res) {

                var json
                try {
                    json = JSON.parse(res.data)
                } catch(e) {
                    json = res.data
                }

                if(res.status >= 400 || res.status < 200) {

                    if (res.status === 0) {
                        res.statusMessage = "Cannot perform request"
                    }

                    let error = {
                        code: json ? json.code : res.status,
                        message: json ? json.message : res.statusText,
                    }

                    if (res.data) {
                        d("Error body: \n %j", res.data)
                    }

                    d("Request error %s %s", error.code, error.message)

                    emit("request.error", error)
                    emit("request.complete", false)

                    const err = new Error(error.message)
                    err.code = error.code

                    return reject(err)
                }

                d("Request response: %j", json)

                emit("request.complete", json)
                resolve(json)
            }).catch(function (error) {
                console.error(error)
                return reject(error)
            })

        })
    }

    instance.request = function (options) {

        // do not try to login if requesting login / get user
        var userReq =  (
            options.url === routes.LOGIN ||
                options.url === routes.USER_GET_ME ||
                    options.url === routes.REFRESH_TOKEN
        ) ?
            Promise.resolve() : container.Auth().loadUser()

        emit("request.start", options)

        return userReq.then(function () {

            if(container.Auth().getToken()) {
                addDefaultHeaders(options, container.Auth().getToken())
            }

            return instance.baseRequest(options)
        })

    }

    instance.get = function (url) {
        return instance.request({
            method: "GET",
            url: url
        })
    }

    instance.delete = function (url) {
        return instance.request({
            method: "DELETE",
            url: url
        })
    }

    instance.put = function (url, data) {
        return instance.request({
            method: "PUT",
            url: url,
            data: data
        })
    }

    instance.post = function (url, data) {
        return instance.request({
            method: "POST",
            url: url,
            data: data
        })
    }

    instance.client = client

    return instance
}
<commit_msg>fix client http<commit_after>var Client = module.exports

var Promise = require("bluebird")
//var request = require("request")
var routes = require("../routes")
var axios = require("axios")

var d = require("debug")("raptorjs:client:http")

Client.create = function (container) {

    var emit = function() {
        container.emit.apply(container, arguments)
    }

    var opts = container.config

    var addDefaultHeaders = function(opts, token) {
        if(!opts.headers) {
            opts.headers = { "Content-Type": "application/json" }
        }
        if(token) {
            opts.headers.Authorization = `Bearer ${token}`
        }
    }

    var defaultsOptions = {
        baseURL: opts.url
        //json: true,
        //debug: opts.debug
    }

    addDefaultHeaders(defaultsOptions)

    //var client = request.defaults(defaultsOptions)
    console.log('using axios')
    var client = axios.create(defaultsOptions)

    d("Created new client %s", defaultsOptions.baseURL)

    var instance = {}

    instance.baseRequest = (options) => {
        return new Promise(function (resolve, reject) {

            options.headers = Object.assign({}, defaultsOptions.headers || {}, options.headers || {})

            d("Performing request %j", options)
            client(options).then((res) => {

                var json
                try {
                    json = JSON.parse(res.data)
                } catch(e) {
                    json = res.data
                }

                if(res.status >= 400 || res.status < 200) {

                    if (res.status === 0) {
                        res.statusMessage = "Cannot perform request"
                    }

                    let error = {
                        code: json ? json.code : res.status,
                        message: json ? json.message : res.statusText
                    }

                    if (res.data) {
                        d("Error body: \n %j", res.data)
                    }

                    d("Request error %s %s", error.code, error.message)

                    emit("request.error", error)
                    emit("request.complete", false)

                    const err = new Error(error.message)
                    err.code = error.code

                    return reject(err)
                }

                d("Request response: %j", json)

                emit("request.complete", json)
                resolve(json)
            }).catch(function (error) {
                console.error(error.code)
                return reject(error)
            })

        })
    }

    instance.request = function (options) {

        // do not try to login if requesting login / get user
        var userReq =  (
            options.url === routes.LOGIN ||
                options.url === routes.USER_GET_ME ||
                    options.url === routes.REFRESH_TOKEN
        ) ?
            Promise.resolve() : container.Auth().loadUser()

        emit("request.start", options)

        return userReq.then(function () {

            if(container.Auth().getToken()) {
                addDefaultHeaders(options, container.Auth().getToken())
            }

            return instance.baseRequest(options)
        })

    }

    instance.get = function (url) {
        return instance.request({
            method: "GET",
            url: url
        })
    }

    instance.delete = function (url) {
        return instance.request({
            method: "DELETE",
            url: url
        })
    }

    instance.put = function (url, data) {
        return instance.request({
            method: "PUT",
            url: url,
            data: data
        })
    }

    instance.post = function (url, data) {
        return instance.request({
            method: "POST",
            url: url,
            data: data
        })
    }

    instance.client = client

    return instance
}
<|endoftext|>


<commit_before>
var async = require('async')

var SBOLDocument = require('sboljs')

const getRdfSerializeAttribs = require('./getRdfSerializeAttribs')

function collateSBOL(documents, res) {

    res.header('content-type', 'application/rdf+xml')

    if(documents.length === 0) {

        /* no results?
         */

        return res.status(404).send('No results to collate')
    }

    //if(documents.length === 1) {

        /* only one result; no collation required
         */

        //return res.send(documents[0].body)
    //}

    var collatedSBOL = new SBOLDocument()

    console.log(documents.length)
    console.log(documents[0])

    async.eachSeries(documents, (document, next) => {

        var done = false

        collatedSBOL.loadRDF(document.body, (err) => {

            if(!done) {
                next(err)
                done = true
            }

        })

    }, (err) => {

        const xml = collatedSBOL.serializeXML(getRdfSerializeAttribs())

        console.log(xml)
        res.send(xml)
    })

}

module.exports = collateSBOL

<commit_msg>Removed debug<commit_after>
var async = require('async')

var SBOLDocument = require('sboljs')

const getRdfSerializeAttribs = require('./getRdfSerializeAttribs')

function collateSBOL(documents, res) {

    res.header('content-type', 'application/rdf+xml')

    if(documents.length === 0) {

        /* no results?
         */

        return res.status(404).send('No results to collate')
    }

    //if(documents.length === 1) {

        /* only one result; no collation required
         */

        //return res.send(documents[0].body)
    //}

    var collatedSBOL = new SBOLDocument()

    console.log(documents.length)
    //console.log(documents[0])

    async.eachSeries(documents, (document, next) => {

        var done = false

        collatedSBOL.loadRDF(document.body, (err) => {

            if(!done) {
                next(err)
                done = true
            }

        })

    }, (err) => {

        const xml = collatedSBOL.serializeXML(getRdfSerializeAttribs())

        console.log(xml)
        res.send(xml)
    })

}

module.exports = collateSBOL

<|endoftext|>


<commit_before>'use strict';

var log = require('db-migrate-shared').log;
var assert = require('assert');

function executeDB (internals, config, callback) {
  var index = require('../../connect');

  if (internals.argv._.length > 0) {
    internals.argv.dbname = internals.argv._.shift().toString();
  } else {
    log.info('Error: You must enter a database name!');
    return;
  }

  index.driver(config.getCurrent().settings, function (err, db) {
    assert.ifError(err);

    if (internals.mode === 'create') {
      db.createDatabase(
        internals.argv.dbname,
        {
          ifNotExists: true
        },
        function (err) {
          if (err) {
            if (err.error) err = err.error;
            log.info('Error: Failed to create database!', err);
          } else {
            log.info('Created database "' + internals.argv.dbname + '"');
          }

          db.close();
          if (typeof callback === 'function') callback();
        }
      );
    } else if (internals.mode === 'drop') {
      db.dropDatabase(
        internals.argv.dbname,
        {
          ifExists: true
        },
        function (err) {
          if (err) {
            if (err.error) err = err.error;
            log.info('Error: Failed to drop database!', err);
          } else {
            log.info('Deleted database "' + internals.argv.dbname + '"');
          }

          db.close();
          if (typeof callback === 'function') callback();
        }
      );
    }
  });
}

module.exports = executeDB;
<commit_msg>fix(exitCode): wrong exit code on db methods<commit_after>'use strict';

var log = require('db-migrate-shared').log;
var assert = require('assert');

function executeDB (internals, config, callback) {
  var index = require('../../connect');

  if (internals.argv._.length > 0) {
    internals.argv.dbname = internals.argv._.shift().toString();
  } else {
    log.info('Error: You must enter a database name!');
    return;
  }

  index.driver(config.getCurrent().settings, function (err, db) {
    assert.ifError(err);

    if (internals.mode === 'create') {
      db.createDatabase(
        internals.argv.dbname,
        {
          ifNotExists: true
        },
        function (err) {
          if (err) {
            if (err.error) err = err.error;
            log.error('Error: Failed to create database!', err);
          } else {
            log.info('Created database "' + internals.argv.dbname + '"');
          }

          db.close();
          if (typeof callback === 'function') callback(err);
          else process.exit(1);
        }
      );
    } else if (internals.mode === 'drop') {
      db.dropDatabase(
        internals.argv.dbname,
        {
          ifExists: true
        },
        function (err) {
          if (err) {
            if (err.error) err = err.error;
            log.error('Error: Failed to drop database!', err);
          } else {
            log.info('Deleted database "' + internals.argv.dbname + '"');
          }

          db.close();
          if (typeof callback === 'function') callback(err);
          process.exit(1);
        }
      );
    }
  });
}

module.exports = executeDB;
<|endoftext|>


<commit_before>var strip = require('strip-loader');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var path = require('path');
var webpack = require('webpack');

var filenameWithoutExt = require('./filenameWithoutExt.js');
var WEBPACK_URL = '/';

module.exports = function(spec) {
  var entry = {};

  if (spec.in) {
    entry[filenameWithoutExt(spec.in)] = spec.in;
  }

  return {

    entry: entry,

    output: {
      path: path.resolve(__dirname, spec.out || 'public/'),
      filename: '[name].js',
      publicPath: WEBPACK_URL,
    },

    /**
     * Note: css-lader is passed the no-restructuring param b/c it can sometimes
     * cause issues where selectors will be reordered and no longer get applied.
     */
    module: {
      loaders: [
        // See .babelrc for Babel config. Also note that all calls to console.log
        // and debug will be stripped from the code
        { test: /\.js?$/, loaders: [strip.loader('debug', 'console.log'), 'babel'], exclude: /node_modules/ },

        { test: /\.styl$/, loader: ExtractTextPlugin.extract('style', 'css?modules&importLoaders=2!autoprefixer!stylus') },
        { test: /\.(png|jpg|gif)$/, loaders: ['file?name=[name].[ext]'] },
        { test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loaders: ['url?limit=10000&minetype=application/font-woff'] },
        { test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loaders: ['file'] },
      ],
    },

    plugins: [
      new ExtractTextPlugin('[name].css', { allChunks: true }),

      // Minify
      new webpack.optimize.UglifyJsPlugin({
        sourceMap: false,

        // This matches nothing and thus removes all comments
        comments: /.^/,
        screw_ie8: true,

        // Options: http://lisperator.net/uglifyjs/compress
        compress: { warnings: false },
      }),

      // Dedupe
      new webpack.optimize.DedupePlugin(),

      // Don't reload on errors
      new webpack.NoErrorsPlugin(),

      // Define magic globals
      new webpack.DefinePlugin({ __DEV__: false }),
    ],

  };
};
<commit_msg>Add clean plugin<commit_after>var strip = require('strip-loader');
var Clean = require('clean-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var path = require('path');
var webpack = require('webpack');

var filenameWithoutExt = require('./filenameWithoutExt.js');
var WEBPACK_URL = '/';

module.exports = function(spec) {
  var entry = {};

  if (spec.in) {
    entry[filenameWithoutExt(spec.in)] = spec.in;
  }

  return {

    entry: entry,

    output: {
      path: path.resolve(__dirname, spec.out || 'public/'),
      filename: '[name].js',
      publicPath: WEBPACK_URL,
    },

    /**
     * Note: css-lader is passed the no-restructuring param b/c it can sometimes
     * cause issues where selectors will be reordered and no longer get applied.
     */
    module: {
      loaders: [
        // See .babelrc for Babel config. Also note that all calls to console.log
        // and debug will be stripped from the code
        { test: /\.js?$/, loaders: [strip.loader('debug', 'console.log'), 'babel'], exclude: /node_modules/ },

        { test: /\.styl$/, loader: ExtractTextPlugin.extract('style', 'css?modules&importLoaders=2!autoprefixer!stylus') },
        { test: /\.(png|jpg|gif)$/, loaders: ['file?name=[name].[ext]'] },
        { test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loaders: ['url?limit=10000&minetype=application/font-woff'] },
        { test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loaders: ['file'] },
      ],
    },

    plugins: [
      // Clean before build
      new Clean(['public']),

      // Extract all CSS to appropriately named css files
      new ExtractTextPlugin('[name].css', { allChunks: true }),

      // Minify
      new webpack.optimize.UglifyJsPlugin({
        sourceMap: false,

        // This matches nothing and thus removes all comments
        comments: /.^/,
        screw_ie8: true,

        // Options: http://lisperator.net/uglifyjs/compress
        compress: { warnings: false },
      }),

      // Dedupe
      new webpack.optimize.DedupePlugin(),

      // Don't reload on errors
      new webpack.NoErrorsPlugin(),

      // Define magic globals
      new webpack.DefinePlugin({ __DEV__: false }),
    ],

  };
};
<|endoftext|>


<commit_before>'use strict';
var Posts = module.parent.parent.require('./posts');
var Controllers = {};

Controllers.getPost = function(req, res, next){
	if(req.headers.host == "localhost:4567"){
		Posts.getPostData(req.params.pid,function(err,result){
			res.send(result);
		});
	}
	return;
};

module.exports = Controllers;
<commit_msg>add next call<commit_after>'use strict';
var Posts = module.parent.parent.require('./posts');
var Controllers = {};

Controllers.getPost = function(req, res, next){
	if(req.headers.host == "localhost:4567"){
		Posts.getPostData(req.params.pid,function(err,result){
			res.send(result);
		});
	}else{
		next();
	}
};

module.exports = Controllers;
<|endoftext|>