<commit_before>'use strict';

// LiFx LAN Platform for HomeBridge
//
// Remember to add platform to config.json. Example:
// "platforms": [
//     {
//         "platform": "LifxLan",           // required
//         "name": "LiFx LAN",              // required
//         "timeout": 30,                   // optional: timeout for Discovery (30 sec default)

//         ** optional node-lifx parameters **
//         "lightOfflineTolerance": 3,       // optional: A light is offline if not seen for the given amount of discoveries
//         "messageHandlerTimeout": 45000,   // optional: in ms, if not answer in time an error is provided to get methods
//         "resendPacketDelay": 150,         // optional: delay between packages if light did not receive a packet (for setting methods with callback)
//         "resendMaxTimes": 3,              // optional: resend packages x times if light did not receive a packet (for setting methods with callback)
//         "debug": false                    // optional: logs all messages in console if turned on
//     }
// ],
//

var LifxClient = require('node-lifx').Client;
var LifxLight = require('node-lifx').Light;
var Storage = require('node-persist');

var Client = new LifxClient();
var Characteristic, Kelvin, Service, uuid;

module.exports = function(homebridge) {
    Characteristic = homebridge.hap.Characteristic;
    Service = homebridge.hap.Service;
    uuid = homebridge.hap.uuid;

    Kelvin = function() {
        Characteristic.call(this, 'Kelvin', 'C4E24248-04AC-44AF-ACFF-40164e829DBA')

        this.setProps({
            format: Characteristic.Formats.UINT16,
            unit: 'K',
            maxValue: 9000,
            minValue: 2500,
            minStep: 250,
            perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY]
        });

        this.value = this.getDefaultValue();
    };
    require('util').inherits(Kelvin, Characteristic);

    homebridge.registerPlatform("homebridge-lifx-lan", "LifxLan", LifxLanPlatform);
};

function LifxLanPlatform(log, config) {
    var self = this;

    this.devices = {};
    this.discoveryTimeout = config.timeout || 30;
    this.log = log;

    Client.on('light-offline', function(bulb) {
        var device = self.devices[bulb.id];

        if (device) {
            device.log("Offline: %s [%s]", device.name, device.deviceId);
            device.online = false;
            device.bulb = bulb;
        }
    });

    Client.on('light-online', function(bulb) {
        var device = self.devices[bulb.id];

        if (device) {
            device.log("Online: %s [%s]", device.name, device.deviceId);
            device.online = true;
            device.bulb = bulb;
        }
    });

    Client.init({
        debug:                  config.debug || false,
        lightOfflineTolerance:  config.lightOfflineTolerance || 3,
        messageHandlerTimeout:  config.messageHandlerTimeout || 45000,
        resendMaxTimes:         config.resendMaxTimes || 3,
        resendPacketDelay:      config.resendPacketDelay || 150
    });
}

LifxLanPlatform.prototype = {
    accessories: function(callback) {
        this.log("Starting device discovery...");

        var self = this;
        var discovery = true;
        var foundCount = 0;
        var foundAccessories = [];

        Storage.initSync({dir: this.persistPath()});

        Client.on('light-new', function(bulb) {
            bulb.getState(function(err, state) {
                if (err) {
                    state = {
                        label: bulb.client.label
                    }
                }

                bulb.getHardwareVersion(function(err, data) {
                    if (err) {
                        data = {}
                    }

                    var persist = {id: bulb.id, address: bulb.address, port: bulb.port, label: state.label, vendor: data.vendorName, model: data.productName};
                    Storage.setItemSync(bulb.id, persist);

                    self.log("Found: %s [%s] - %s", state.label, bulb.id, data.productName);

                    if (discovery == true) {
                        var accessory = new LifxBulbAccessory(self.log, bulb, {color: state.color, label: state.label, power: state.power, vendor: data.vendorName, model: data.productName});
                        self.devices[accessory.deviceId] = accessory
                        foundAccessories.push(accessory);
                    }
                });
            });

            foundCount++;
        });

        var timer = setTimeout(
            function () {
                self.log("Stopping device discovery...");
                discovery = false;
                Client.stopDiscovery();

                Storage.forEach(function(key, value) {
                    if (self.devices[key] == undefined) {
                        var bulb = new LifxLight({
                            client: Client,
                            id: value.id,
                            address: value.address,
                            port: value.port,
                            seenOnDiscovery: 0
                        });

                        Client.devices[value.address] = bulb;

                        var accessory = new LifxBulbAccessory(self.log, bulb, {label: value.label, vendor: value.vendor, model: value.model}, false);
                        self.devices[accessory.deviceId] = accessory
                        foundAccessories.push(accessory);
                    }
                });

                callback(foundAccessories);
            },
            this.discoveryTimeout * 1000
        );

        Client.startDiscovery();
    }
}

LifxLanPlatform.prototype.persistPath = function() {
    var path = require('path');

    var home = process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE;
    return path.join(home, ".homebridge-lifx-lan", "persist");
}

function LifxBulbAccessory(log, bulb, data, online) {
    this.bulb = bulb;
    this.deviceId = bulb.id;
    this.log = log;

    this.name = data.label || "LiFx " + bulb.id;
    this.power = data.power || 0;
    this.color = data.color || {hue: 0, saturation: 0, brightness: 50, kelvin: 2500};

    this.online = online || true;
    this.model = data.model || null;
    this.vendor = data.vendor || null;
}

LifxBulbAccessory.prototype = {
    identify: function(callback) {
        this.log("Identify: %s [%s]", this.name, this.deviceId);
        callback();
    },
    get: function (type) {
        var state;

        switch(type) {
            case "brightness":
            case "hue":
            case "kelvin":
            case "saturation":
                this.log("%s - Get %s: %d", this.name, type, this.color[type]);
                state = this.color[type];
                break;
            case "power":
                this.log("%s - Get power: %d", this.name, this.power);
                state = this.power > 0;
                break;
        }

        return state;
    },
    getServices: function() {
        var self = this;
        var services = [];

        this.services = {
            AccessoryInformation: new Service.AccessoryInformation(),
            Lightbulb: new Service.Lightbulb(this.name)
        };

        this.services.AccessoryInformation
            .setCharacteristic(Characteristic.Manufacturer, this.vendor)
            .setCharacteristic(Characteristic.Model, this.model);

        this.services.Lightbulb.getCharacteristic(Characteristic.On)
            .setValue(this.power > 0)
            .on('get', function(callback) {self.getState("power", callback)})
            .on('set', function(value, callback) {self.setPower(value, callback)}
        );

        this.services.Lightbulb.addCharacteristic(Characteristic.Brightness)
            .setValue(this.color.brightness)
            .setProps({minValue: 1})
            .on('get', function(callback) {self.getState("brightness", callback)})
            .on('set', function(value, callback) {self.setColor("brightness", value, callback)}
        );

        this.services.Lightbulb.addCharacteristic(Kelvin)
            .setValue(this.color.kelvin)
            .on('get', function(callback) {self.getState("kelvin", callback)})
            .on('set', function(value, callback) {self.setColor("kelvin", value, callback)}
        );

        if (/[Color|Original]/.test(this.model)) {
            this.services.Lightbulb.addCharacteristic(Characteristic.Hue)
                .setValue(this.color.hue)
                .on('get', function(callback) {self.getState("hue", callback)})
                .on('set', function(value, callback) {self.setColor("hue", value, callback)}
            );

            this.services.Lightbulb.addCharacteristic(Characteristic.Saturation)
                .setValue(this.color.saturation)
                .on('get', function(callback) {self.getState("saturation", callback)})
                .on('set', function(value, callback) {self.setColor("saturation", value, callback)}
            );
        }

        services.push(this.services.Lightbulb);
        services.push(this.services.AccessoryInformation);

        return services;
    },
    getState: function(type, callback){
        var self = this;

        if (this.online === false) {
            callback(null, self.get(type));
            return;
        }

        this.bulb.getState(function(err, data) {
            if (data) {
                self.power = data.power;
                self.color = data.color;
            }

            callback(null, self.get(type));
        });
    },
    setColor: function(type, value, callback){
        var color;

        if (this.online === false) {
            callback(null);
            return;
        }

        this.log("%s - Set %s: %d", this.name, type, value);
        this.color[type] = value;

        this.bulb.color(this.color.hue, this.color.saturation, this.color.brightness, this.color.kelvin, 0, function (err) {
            callback(null);
        });
    },
    setPower: function(state, callback){
        if (this.online === false) {
            callback(null);
            return;
        }

        this.log("%s - Set power: %d", this.name, state);

        this.bulb[state ? "on" : "off"](0, function(err) {
            callback(null);
        });
    }
}
<commit_msg>initial commit on v2 plugin framework<commit_after>'use strict';

// LiFx LAN Platform for HomeBridge
//
// Remember to add platform to config.json. Example:
// "platforms": [
//     {
//         "platform": "LifxLan",           // required
//         "name": "LiFx LAN",              // required

//         ** optional node-lifx parameters **
//         "lightOfflineTolerance": 3,       // optional: A light is offline if not seen for the given amount of discoveries
//         "messageHandlerTimeout": 45000,   // optional: in ms, if not answer in time an error is provided to get methods
//         "resendPacketDelay": 150,         // optional: delay between packages if light did not receive a packet (for setting methods with callback)
//         "resendMaxTimes": 3,              // optional: resend packages x times if light did not receive a packet (for setting methods with callback)
//         "debug": false                    // optional: logs all messages in console if turned on
//     }
// ],
//

var inherits = require('util').inherits;

var LifxClient = require('node-lifx').Client;
var LifxLight = require('node-lifx').Light;

var Client = new LifxClient();
var Characteristic, Kelvin, PlatformAccessory, Service, UUIDGen;

module.exports = function(homebridge) {
    PlatformAccessory = homebridge.platformAccessory;

    Characteristic = homebridge.hap.Characteristic;
    Service = homebridge.hap.Service;
    UUIDGen = homebridge.hap.uuid;

    Kelvin = function() {
        Characteristic.call(this, 'Kelvin', 'C4E24248-04AC-44AF-ACFF-40164e829DBA')

        this.setProps({
            format: Characteristic.Formats.UINT16,
            unit: 'K',
            maxValue: 9000,
            minValue: 2500,
            minStep: 250,
            perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY]
        });

        this.value = this.getDefaultValue();
    };
    inherits(Kelvin, Characteristic);

    homebridge.registerPlatform("homebridge-lifx-lan", "LifxLan", LifxLanPlatform, true);
};

function LifxLanPlatform(log, config, api) {
    config = config || {};

    var self = this;

    this.api = api;
    this.accessories = [];
    this.configured = [];
    this.log = log;

    Client.on('light-offline', function(bulb) {
        var key;
        var uuid = UUIDGen.generate(bulb.id);

        for (var index in self.accessories) {
            if (self.accessories[index].UUID == uuid) {
                key = index;
                break;
            }
        }

        if (key) {
            self.log("Offline: %s [%s]", self.accessories[key].displayName, bulb.id);
            self.accessories[key].updateReachability(false);
            self.accessories[key].bulb = bulb;
        }
    });

    Client.on('light-online', function(bulb) {
        var key;
        var uuid = UUIDGen.generate(bulb.id);

        for (var index in self.accessories) {
            if (self.accessories[index].UUID == uuid) {
                key = index;
                break;
            }
        }

        if (key) {
            self.log("Online: %s [%s]", self.accessories[key].displayName, bulb.id);
            self.accessories[key].updateReachability(false);

            if (self.accessories[key].bulb == undefined) {
                self._initAccessory(self.accessories[key], bulb, {});
            }
            else {
                self.accessories[key].bulb = bulb;
            }
        }
    });

    Client.on('light-new', function(bulb) {
        bulb.getState(function(err, state) {
            if (err) {
                state = {
                    label: bulb.client.label
                }
            }

            if (self.configured.indexOf(UUIDGen.generate(bulb.id)) == -1) {
                self.log("Found: %s [%s]", state.label, bulb.id);
                self.addAccessory(bulb, state);
            }
            else {
                for (var index in self.accessories) {
                    if (self.accessories[index].UUID == UUIDGen.generate(bulb.id)) {
                        self._initAccessory(self.accessories[index], bulb, state);
                        break;
                    }
                }
            }
        });
    });

    this.api.on('didFinishLaunching', function() {
        Client.init({
            debug:                  config.debug || false,
            lightOfflineTolerance:  config.lightOfflineTolerance || 3,
            messageHandlerTimeout:  config.messageHandlerTimeout || 45000,
            resendMaxTimes:         config.resendMaxTimes || 3,
            resendPacketDelay:      config.resendPacketDelay || 150
        });
    }.bind(this));
}

LifxLanPlatform.prototype.addAccessory = function(bulb, data) {
    this.log("Add Accessory");
    var self = this;
    var name = data.label || "LiFx " + bulb.id;
    var accessory = new PlatformAccessory(name, UUIDGen.generate(bulb.id));

    accessory.addService(Service.Lightbulb);
    this._initAccessory(accessory, bulb, data);

    this.accessories.push(accessory);
    this.api.registerPlatformAccessories("homebridge-lifx-lan", "LifxLan", [accessory]);
}

LifxLanPlatform.prototype.configureAccessory = function(accessory) {
    this.log("Cached: %s", accessory.displayName);
    this.configured.push(accessory.UUID);
    this.accessories.push(accessory);
}

LifxLanPlatform.prototype._initAccessory = function(accessory, bulb, data) {
    var self = this;

    accessory.bulb = bulb;
    accessory.power = data.power || 0;
    accessory.color = data.color || {hue: 0, saturation: 0, brightness: 50, kelvin: 2500};

    var service = accessory.getService(Service.Lightbulb);

    service
        .getCharacteristic(Characteristic.On)
        .setValue(accessory.power > 0)
        .on('get', function(callback) {self._getState(accessory, "power", callback)})
        .on('set', function(value, callback) {self._setPower(accessory, value, callback)});

    service.getCharacteristic(Characteristic.Brightness)
        .setValue(accessory.color.brightness)
        .setProps({minValue: 1})
        .on('get', function(callback) {self._getState(accessory, "brightness", callback)})
        .on('set', function(value, callback) {self._setColor(accessory, "brightness", value, callback)});

    /*
    service.getCharacteristic(Kelvin)
        .setValue(accessory.color.kelvin)
        .on('get', function(callback) {self._getState(accessory, "kelvin", callback)})
        .on('set', function(value, callback) {self._setColor(accessory, "kelvin", value, callback)});
    */

    if (/[Color|Original]/.test(this.model)) {
        service.getCharacteristic(Characteristic.Hue)
            .setValue(accessory.color.hue)
            .on('get', function(callback) {self._getState(accessory, "hue", callback)})
            .on('set', function(value, callback) {self._setColor(accessory, "hue", value, callback)}
        );

        service.getCharacteristic(Characteristic.Saturation)
            .setValue(accessory.color.saturation)
            .on('get', function(callback) {self._getState(accessory, "saturation", callback)})
            .on('set', function(value, callback) {self._setColor(accessory, "saturation", value, callback)}
        );
    }

    accessory.updateReachability(true);

    bulb.getHardwareVersion(function(err, data) {
        accessory.getService(Service.AccessoryInformation)
            .setCharacteristic(Characteristic.Manufacturer, data.vendorName)
            .setCharacteristic(Characteristic.Model, data.productName)
            .setCharacteristic(Characteristic.SerialNumber, bulb.id);
    });
}

LifxLanPlatform.prototype._get = function (accessory, type) {
    var state;

    switch(type) {
        case "brightness":
        case "hue":
        case "kelvin":
        case "saturation":
            this.log("%s - Get %s: %d", accessory.displayName, type, accessory.color[type]);
            state = accessory.color[type];
            break;
        case "power":
            this.log("%s - Get power: %d", accessory.displayName, accessory.power);
            state = accessory.reachable && accessory.power > 0;
            break;
    }

    return state;
}

LifxLanPlatform.prototype._getState = function(accessory, type, callback){
    var self = this;

    if (accessory.reachable === false) {
        callback(null, self._get(accessory, type));
        return;
    }

    accessory.bulb.getState(function(err, data) {
        if (data) {
            accessory.power = data.power;
            accessory.color = data.color;
        }

        callback(null, self._get(accessory, type));
    });
}

LifxLanPlatform.prototype._setColor = function(accessory, type, value, callback){
        var color;

        if (accessory.reachable === false) {
            callback(null);
            return;
        }

        this.log("%s - Set %s: %d", accessory.displayName, type, value);
        accessory.color[type] = value;

        accessory.bulb.color(accessory.color.hue, accessory.color.saturation, accessory.color.brightness, accessory.color.kelvin, 0, function (err) {
            callback(null);
        });
    }

LifxLanPlatform.prototype._setPower = function(accessory, state, callback){
    if (accessory.reachable === false) {
        callback(null);
        return;
    }

    this.log("%s - Set power: %d", accessory.displayName, state);

    accessory.bulb[state ? "on" : "off"](0, function(err) {
        callback(null);
    });
}
<|endoftext|>


<commit_before>var express = require('express');
var Busboy = require('busboy');
var path = require('path');
var cors = require('cors');
var fs = require('fs');
var streams = require('memory-streams');

var app = express();

app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', req.headers.origin);

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
});

var whitelist = ['http://valor-software.github.io'];

var corsOptionsDelegate = function(req, callback){
  var corsOptions;
  if(whitelist.indexOf(req.header('Origin')) !== -1){
    corsOptions = { origin: true }; // reflect (enable) the requested origin in the CORS response
  }else{
    corsOptions = { origin: false }; // disable CORS for this request
  }
  callback(null, corsOptions); // callback expects two parameters: error and options
};

app.get('/', function (req, res) {
  res.end('Ok!');
});

// cors(corsOptionsDelegate)

app.post('/api', function (req, res) {
  var fstream;
  var files = [];
  var busboy = new Busboy({headers: req.headers});
  busboy.on('file', function (fieldname, file, filename) {
    // fstream = fs.createWriteStream(__dirname + '/uploads/' + filename);
    // stub
    fstream = new streams.WritableStream();
    file.pipe(fstream);
    fstream.on('close', function () {
      console.log('file ' + filename + ' uploaded');
      files.push(filename);
    });
  });

  busboy.on('finish', function () {
    res.redirect('back');
  });
  req.pipe(busboy);
});

app.listen(process.env.PORT || 3000);
<commit_msg>Updated: try #4<commit_after>var express = require('express');
var Busboy = require('busboy');
var path = require('path');
var cors = require('cors');
var fs = require('fs');
var streams = require('memory-streams');

var app = express();

/*app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', req.headers.origin);

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
});*/

var whitelist = ['http://valor-software.github.io'];

var corsOptionsDelegate = function(req, callback){
  var corsOptions;
  if(whitelist.indexOf(req.header('Origin')) !== -1){
    corsOptions = { origin: true }; // reflect (enable) the requested origin in the CORS response
  }else{
    corsOptions = { origin: false }; // disable CORS for this request
  }
  callback(null, corsOptions); // callback expects two parameters: error and options
};

app.get('/', function (req, res) {
  res.end('Ok!');
});

// cors(corsOptionsDelegate)

app.post('/api', function (req, res) {
  var fstream;
  var files = [];
  var busboy = new Busboy({headers: req.headers});
  busboy.on('file', function (fieldname, file, filename) {
    // fstream = fs.createWriteStream(__dirname + '/uploads/' + filename);
    // stub
    fstream = new streams.WritableStream();
    file.pipe(fstream);
    fstream.on('close', function () {
      console.log('file ' + filename + ' uploaded');
      files.push(filename);
    });
  });

  busboy.on('finish', function () {
    // res.redirect('back');
    res.end('ok');
  });
  req.pipe(busboy);
});

app.listen(process.env.PORT || 3000);
<|endoftext|>


<commit_before>var request = require("request");
var wol = require("wake_on_lan");
var Service, Characteristic;

module.exports = function(homebridge) {
    Service = homebridge.hap.Service;
    Characteristic = homebridge.hap.Characteristic;

    homebridge.registerAccessory("homebridge-sonybraviatv", "SonyBraviaTV", SonyBraviaTVAccessory);
}

function SonyBraviaTVAccessory(log, config) {
    this.log = log;

    this.name = config["name"];
    this.psk = config["presharedkey"];
    this.ipaddress = config["ipaddress"];
    this.macaddress = config["macaddress"];

    this.service = new Service.Switch(this.name);

    this.service
        .getCharacteristic(Characteristic.On)
        .on('get', this.getOn.bind(this))
        .on('set', this.setOn.bind(this));

}

SonyBraviaTVAccessory.prototype.getOn = function(callback) {
    this.log("Getting whether Sony TV is on...");

    var postData = JSON.stringify({
        method: 'getPowerStatus',
        params: [],
        id: 1,
        version: '1.0'
    });

    request.post({
        url: "http://" + this.ipaddress + "/sony/system",
        headers: {
            'X-Auth-PSK': this.psk
        },
        form: postData
    }, function(err, response, body) {

        if (!err && response.statusCode == 200) {
            var json = JSON.parse(body);
            var status = json.result[0].status;
            this.log("TV status is %s", status);
            var isOn = status == "active";
            callback(null, isOn); // success
        } else {
            if (response != null) {
                this.log("Error getting TV status (status code %s): %s", response.statusCode, err);
            } else {
                this.log("Error getting TV status: %s", err);
            }
            callback(err);
        }
    }.bind(this));
}

SonyBraviaTVAccessory.prototype.setOn = function(value, callback) {
    value = Boolean(value);
    this.log("Set value to %s", value);

    if (value && this.macaddress) {
        wol.wake(this.macaddress, function(error) {
            if (error) {
                // handle error
                this.log("Error '%s' setting TV power state using WOL.", error);
                callback(error);
            } else {
                // done sending packets
                callback();
            }
        }.bind(this));
    } else {

        var postData = JSON.stringify({
            method: 'setPowerStatus',
            params: [{
                'status': value
            }],
            id: 1,
            version: '1.0'
        });

        request.post({
            url: "http://" + this.ipaddress + "/sony/system",
            headers: {
                'X-Auth-PSK': this.psk
            },
            form: postData
        }, function(err, response, body) {

            if (!err && response.statusCode == 200) {
                callback(); // success
            } else {
                this.log("Error '%s' setting TV power state. Response: %s", err, body);
                callback(err || new Error("Error setting TV power state."));
            }
        }.bind(this));
    }
}

SonyBraviaTVAccessory.prototype.getServices = function() {
    return [this.service];
}
<commit_msg>Report the TV as off we are not able to communicate with it to get it's status. Fixes issue #3<commit_after>var request = require("request");
var wol = require("wake_on_lan");
var Service, Characteristic;

module.exports = function(homebridge) {
    Service = homebridge.hap.Service;
    Characteristic = homebridge.hap.Characteristic;

    homebridge.registerAccessory("homebridge-sonybraviatv", "SonyBraviaTV", SonyBraviaTVAccessory);
}

function SonyBraviaTVAccessory(log, config) {
    this.log = log;

    this.name = config["name"];
    this.psk = config["presharedkey"];
    this.ipaddress = config["ipaddress"];
    this.macaddress = config["macaddress"];

    this.service = new Service.Switch(this.name);

    this.service
        .getCharacteristic(Characteristic.On)
        .on('get', this.getOn.bind(this))
        .on('set', this.setOn.bind(this));

}

SonyBraviaTVAccessory.prototype.getOn = function(callback) {
    this.log("Getting whether Sony TV is on...");

    var postData = JSON.stringify({
        method: 'getPowerStatus',
        params: [],
        id: 1,
        version: '1.0'
    });

    request.post({
        url: "http://" + this.ipaddress + "/sony/system",
        headers: {
            'X-Auth-PSK': this.psk
        },
        form: postData
    }, function(err, response, body) {

        if (!err && response.statusCode == 200) {
            var json = JSON.parse(body);
            var status = json.result[0].status;
            this.log("TV status is %s", status);
            var isOn = status == "active";
            callback(null, isOn); // success
        } else {
            if (response != null) {
                this.log("Error getting TV status (status code %s): %s", response.statusCode, err);
                callback(err);
            } else {
                this.log("Error getting TV status, assuming TV is off: %s.", err);
                callback(null, false);
            }
        }
    }.bind(this));
}

SonyBraviaTVAccessory.prototype.setOn = function(value, callback) {
    value = Boolean(value);
    this.log("Set value to %s", value);

    if (value && this.macaddress) {
        wol.wake(this.macaddress, function(error) {
            if (error) {
                // handle error
                this.log("Error '%s' setting TV power state using WOL.", error);
                callback(error);
            } else {
                // done sending packets
                callback();
            }
        }.bind(this));
    } else {

        var postData = JSON.stringify({
            method: 'setPowerStatus',
            params: [{
                'status': value
            }],
            id: 1,
            version: '1.0'
        });

        request.post({
            url: "http://" + this.ipaddress + "/sony/system",
            headers: {
                'X-Auth-PSK': this.psk
            },
            form: postData
        }, function(err, response, body) {

            if (!err && response.statusCode == 200) {
                callback(); // success
            } else {
                this.log("Error '%s' setting TV power state. Response: %s", err, body);
                callback(err || new Error("Error setting TV power state."));
            }
        }.bind(this));
    }
}

SonyBraviaTVAccessory.prototype.getServices = function() {
    return [this.service];
}
<|endoftext|>


<commit_before>'use strict'

var emoji = require('node-emoji')

/**
 * Returns a string surrounded by the poop emoji (poomoji)
 * @param string
 */

module.exports = function pooptimes (string, times) {
  if (times === undefined)
    times = 1
  var string = string.trim()
  var poop = emoji.get('hankey')
  if (times === 0)
    return string
  return pooptimes(poop + ' ' + string + ' ' + poop, times - 1)
}
<commit_msg>chore: minor code style updates<commit_after>'use strict'

const emoji = require('node-emoji')

/**
 * Returns a string surrounded by the poop emoji (poomoji)
 * @param string
 */

module.exports = function pooptimes (string, times) {
  if (times === undefined) {
    times = 1
  }

  const trimmedString = string.trim()
  const poop = emoji.get('hankey')
  if (times === 0) {
    return string
  }

  return pooptimes(poop + ' ' + trimmedString + ' ' + poop, times - 1)
}
<|endoftext|>


<commit_before>var util = require('util')
var isProperty = require('is-property')

var INDENT_START = /[\{\[]/
var INDENT_END = /[\}\]]/

var formats = {
  s: function(s) {
    return '' + s
  },
  d: function(d) {
    return '' + Number(d)
  },
  o: function(o) {
    return JSON.stringify(o)
  }
}

var genfun = function() {
  var lines = []
  var indent = 0
  var vars = {}

  var push = function(str) {
    var spaces = ''
    while (spaces.length < indent*2) spaces += '  '
    lines.push(spaces+str)
  }

  var pushLine = function(line) {
    if (INDENT_END.test(line.trim()[0]) && INDENT_START.test(line[line.length-1])) {
      indent--
      push(line)
      indent++
      return
    }
    if (INDENT_START.test(line[line.length-1])) {
      push(line)
      indent++
      return
    }
    if (INDENT_END.test(line.trim()[0])) {
      indent--
      push(line)
      return
    }

    push(line)
  }

  var line = function(fmt) {
    if (!fmt) return line

    if (arguments.length === 1 && fmt.indexOf('\n') > -1) {
      var lines = fmt.trim().split('\n')
      for (var i = 0; i < lines.length; i++) {
        pushLine(lines[i].trim())
      }
    } else {
      pushLine(util.format.apply(util, arguments))
    }

    return line
  }

  line.scope = {}
  line.formats = formats

  line.sym = function(name) {
    if (!name || !isProperty(name)) name = 'tmp'
    if (!vars[name]) vars[name] = 0
    return name + (vars[name]++ || '')
  }

  line.toString = function() {
    return lines.join('\n')
  }

  line.toFunction = function(scope) {
    if (!scope) scope = {}

    var src = 'return ('+line.toString()+')'

    Object.keys(line.scope).forEach(function (key) {
      if (!scope[key]) scope[key] = line.scope[key]
    })

    var keys = Object.keys(scope).map(function(key) {
      return key
    })

    var vals = keys.map(function(key) {
      return scope[key]
    })

    return Function.apply(null, keys.concat(src)).apply(null, vals)
  }

  if (arguments.length) line.apply(null, arguments)

  return line
}

genfun.formats = formats
module.exports = genfun
<commit_msg>add .property<commit_after>var util = require('util')
var isProperty = require('is-property')

var INDENT_START = /[\{\[]/
var INDENT_END = /[\}\]]/

var formats = {
  s: function(s) {
    return '' + s
  },
  d: function(d) {
    return '' + Number(d)
  },
  o: function(o) {
    return JSON.stringify(o)
  }
}

var genfun = function() {
  var lines = []
  var indent = 0
  var vars = {}

  var push = function(str) {
    var spaces = ''
    while (spaces.length < indent*2) spaces += '  '
    lines.push(spaces+str)
  }

  var pushLine = function(line) {
    if (INDENT_END.test(line.trim()[0]) && INDENT_START.test(line[line.length-1])) {
      indent--
      push(line)
      indent++
      return
    }
    if (INDENT_START.test(line[line.length-1])) {
      push(line)
      indent++
      return
    }
    if (INDENT_END.test(line.trim()[0])) {
      indent--
      push(line)
      return
    }

    push(line)
  }

  var line = function(fmt) {
    if (!fmt) return line

    if (arguments.length === 1 && fmt.indexOf('\n') > -1) {
      var lines = fmt.trim().split('\n')
      for (var i = 0; i < lines.length; i++) {
        pushLine(lines[i].trim())
      }
    } else {
      pushLine(util.format.apply(util, arguments))
    }

    return line
  }

  line.scope = {}
  line.formats = formats

  line.sym = function(name) {
    if (!name || !isProperty(name)) name = 'tmp'
    if (!vars[name]) vars[name] = 0
    return name + (vars[name]++ || '')
  }

  line.property = function(obj, name) {
    if (arguments.length === 1) {
      name = obj
      obj = ''
    }

    name = name + ''

    if (isProperty(name)) return (obj ? obj + '.' + name : name)
    return obj ? obj + '[' + JSON.stringify(name) + ']' : JSON.stringify(name)
  }

  line.toString = function() {
    return lines.join('\n')
  }

  line.toFunction = function(scope) {
    if (!scope) scope = {}

    var src = 'return ('+line.toString()+')'

    Object.keys(line.scope).forEach(function (key) {
      if (!scope[key]) scope[key] = line.scope[key]
    })

    var keys = Object.keys(scope).map(function(key) {
      return key
    })

    var vals = keys.map(function(key) {
      return scope[key]
    })

    return Function.apply(null, keys.concat(src)).apply(null, vals)
  }

  if (arguments.length) line.apply(null, arguments)

  return line
}

genfun.formats = formats
module.exports = genfun
<|endoftext|>


<commit_before>'use strict';

const app = require('app');
const BrowserWindow = require('browser-window');
const Menu = require('menu');
const GlobalShortcut = require('global-shortcut');

require('crash-reporter').start();

// prevent window being GC'd
let win = null;

function toggleWindow() {
	if (win.isVisible() && win.isFocused()) {
		// minimize the window if it is is focused on
		win.minimize();
	}
	else if (win.isVisible() && !win.isFocused()) {
		// brint window in front of others if it is not minized,
		// in behind of the other windows
		win.focus();
	} else if (win.isMinimized()) {
		// restore window from dock
		win.restore();
	}
}

function registerShorcuts() {
	GlobalShortcut.register('CommandOrControl+?', toggleWindow);
}

function unregisterShortcuts() {
	GlobalShortcut.unregisterAll();
}

app.on('window-all-closed', () => {
	if (process.platform !== 'darwin') {
		app.quit();
	}
});

app.on('ready', () => {
	var template = [{
		label: 'Devdocs',
    submenu: [{
		  label: 'Hide Electron',
		  accelerator: 'Esc',
		  selector: 'hide:'
		}]
	}];

	var menu = Menu.buildFromTemplate(template);
  Menu.setApplicationMenu(menu);

	registerShorcuts();

	win = new BrowserWindow({
		width: 800,
		height: 600,
		resizable: true,
		center: true,
		show: true,
		'skip-taskbar': true
	});

	win.loadUrl('http://devdocs.io');

	win.on('closed', () => {
		// deref the window
		// for multiple windows store them in an array
		win = null;

		unregisterShortcuts();
	});

	win.on('restore', () => {
		win.focus();
	});
});
<commit_msg>Add quit option<commit_after>'use strict';

const app = require('app');
const BrowserWindow = require('browser-window');
const Menu = require('menu');
const GlobalShortcut = require('global-shortcut');
const appName = app.getName();

require('crash-reporter').start();

// prevent window being GC'd
let win = null;

function toggleWindow() {
	if (win.isVisible() && win.isFocused()) {
		// minimize the window if it is is focused on
		win.minimize();
	}
	else if (win.isVisible() && !win.isFocused()) {
		// brint window in front of others if it is not minized,
		// in behind of the other windows
		win.focus();
	} else if (win.isMinimized()) {
		// restore window from dock
		win.restore();
	}
}

function registerShorcuts() {
	GlobalShortcut.register('CommandOrControl+?', toggleWindow);
}

function unregisterShortcuts() {
	GlobalShortcut.unregisterAll();
}

app.on('window-all-closed', () => {
	app.quit();
});

app.on('ready', () => {
	var template = [{
		label: appName,
    submenu: [{
			label: `About ${appName}`,
			role: 'about'
		}, {
			type: 'separator'
		}, {
		  label: 'Hide',
		  accelerator: 'Esc',
		  selector: 'hide:'
		}, {
			label: 'Quit',
			accelerator: 'Cmd+Q',
			click() {
				app.quit();
			}
		}]
	}];

	var menu = Menu.buildFromTemplate(template);
  Menu.setApplicationMenu(menu);

	registerShorcuts();

	win = new BrowserWindow({
		width: 800,
		height: 600,
		resizable: true,
		center: true,
		show: true,
		'skip-taskbar': true
	});

	win.loadUrl('http://devdocs.io');

	win.on('closed', () => {
		// deref the window
		// for multiple windows store them in an array
		win = null;

		unregisterShortcuts();
	});

	win.on('restore', () => {
		win.focus();
	});
});
<|endoftext|>


<commit_before>"use strict";

module.exports = function(graph) {
  return {
    V: createVertexStream
  };
}

function createVertexStream(startFrom) {
  var VertexStream = require('./lib/vertexStream');
  return new VertexStream(graph, startFrom);
}
<commit_msg>Put vertext stream back where it was<commit_after>"use strict";

module.exports = function(graph) {
  return {
    V: function createVertexStream(startFrom) {
      var VertexStream = require('./lib/vertexStream');
      return new VertexStream(graph, startFrom);
    }
  };
};
<|endoftext|>


<commit_before>var es = require('event-stream');
var fs = require('fs');
var path = require('path');
var child_process = require('child_process');
var async = require('async');
var PluginError = require('gulp-util').PluginError;
var winExt = /^win/.test(process.platform)?".cmd":"";
var console = require('console');

// optimization: cache for phpmetrics binaries directory
var phpmetricsDir = null;

function getPhpmetricsDir() {
	if (phpmetricsDir) {
		return phpmetricsDir;
	}
	var result = require.resolve("phpmetrix");
	if (result) {
		// result is now something like
		phpmetricsDir = path.resolve(path.join(path.dirname(result), "..", ".bin"));
		return phpmetricsDir;
	}
	throw new Error("No phpmetrix installation found.");
}

var phpmetrix = function(options) {
    var child, args;

    options = options || {};
    args = options.args || [];

    console.log(args);

    return es.through(function(config) {
        this.push(config);
    }, function() {
        var stream = this;

        // Pass in the config file
        if (options.configFile) {
            args.unshift(options.configFile);
        }

        phpmetrix = child_process.spawn(path.resolve(getPhpmetricsDir() + '/phpmetrix'+winExt), args, {
            stdio: 'inherit',
            env: process.env
        });

        phpmetrix.stdout.on('data', (data) => {
			console.log(`stdout: ${data}`);
		});

		phpmetrix.stderr.on('data', (data) => {
			console.log(`stderr: ${data}`);
		});

		phpmetrix.on('close', (code) => {
			console.log(`child process exited with code ${code}`);
		});

        phpmetrix.on('exit', function(code) {
            if (child) {
                child.kill();
            }
            if (stream) {
                if (code) {
                    stream.emit('error', new PluginError('gulp-phpmetrix', 'phpmetrix exited with code ' + code));
                }
                else {
                    stream.emit('end');
                }
            }
        });
    });
};

module.exports = {
	getPhpmetricsDir: getPhpmetricsDir,
	phpmetrix: phpmetrix
};
<commit_msg>Updating values for stdio to create the appropriate stdout and stderr output<commit_after>var es = require('event-stream');
var fs = require('fs');
var path = require('path');
var child_process = require('child_process');
var async = require('async');
var PluginError = require('gulp-util').PluginError;
var winExt = /^win/.test(process.platform)?".cmd":"";
var console = require('console');

// optimization: cache for phpmetrics binaries directory
var phpmetricsDir = null;

function getPhpmetricsDir() {
	if (phpmetricsDir) {
		return phpmetricsDir;
	}
	var result = require.resolve("phpmetrix");
	if (result) {
		// result is now something like
		phpmetricsDir = path.resolve(path.join(path.dirname(result), "..", ".bin"));
		return phpmetricsDir;
	}
	throw new Error("No phpmetrix installation found.");
}

var phpmetrix = function(options) {
    var child, args;

    options = options || {};
    args = options.args || [];

    console.log(args);

    return es.through(function(config) {
        this.push(config);
    }, function() {
        var stream = this;

        // Pass in the config file
        if (options.configFile) {
            args.unshift(options.configFile);
        }

        phpmetrix = child_process.spawn(path.resolve(getPhpmetricsDir() + '/phpmetrix'+winExt), args, {
            stdio: [
                0, // Use parents stdin for child
				'pipe', // Pipe child's stdout to parent
    			fs.openSync('err.out', 'w') // Direct child's stderr to a file
    		],
            env: process.env
        });

        phpmetrix.stdout.on('data', (data) => {
			console.log(`stdout: ${data}`);
		});

		phpmetrix.stderr.on('data', (data) => {
			console.log(`stderr: ${data}`);
		});

		phpmetrix.on('close', (code) => {
			console.log(`child process exited with code ${code}`);
		});

        phpmetrix.on('exit', function(code) {
            if (child) {
                child.kill();
            }
            if (stream) {
                if (code) {
                    stream.emit('error', new PluginError('gulp-phpmetrix', 'phpmetrix exited with code ' + code));
                }
                else {
                    stream.emit('end');
                }
            }
        });
    });
};

module.exports = {
	getPhpmetricsDir: getPhpmetricsDir,
	phpmetrix: phpmetrix
};
<|endoftext|>


<commit_before>'use strict';

var path = require('path');
var taskOpts = require('./lib/tasks.js');

module.exports = function(kbox) {

  var events = kbox.core.events;
  var engine = kbox.engine;

  kbox.ifApp(function(app) {

    // Grab the clients
    var Git = require('./lib/git.js');
    var git = new Git(kbox, app);

    // Events
    // Install the util container for our things
    events.on('post-install', function(app, done) {
      var opts = {
        name: 'git',
        srcRoot: path.resolve(__dirname)
      };
      engine.build(opts, done);
    });

    // Tasks
    // git wrapper: kbox git COMMAND
    kbox.tasks.add(function(task) {
      task.path = [app.name, 'git'];
      task.description = 'Run git commands.';
      task.kind = 'delegate';
      task.options.push(taskOpts.gitUsername);
      task.options.push(taskOpts.gitEmail);
      task.func = function(done) {
        // We need to use this faux bin until the resolution of
        // https://github.com/syncthing/syncthing/issues/1056
        git.cmd(this.payload, this.options, done);
      };
    });

  });

};
<commit_msg>Add git command to appAction category<commit_after>'use strict';

var path = require('path');
var taskOpts = require('./lib/tasks.js');

module.exports = function(kbox) {

  var events = kbox.core.events;
  var engine = kbox.engine;

  kbox.ifApp(function(app) {

    // Grab the clients
    var Git = require('./lib/git.js');
    var git = new Git(kbox, app);

    // Events
    // Install the util container for our things
    events.on('post-install', function(app, done) {
      var opts = {
        name: 'git',
        srcRoot: path.resolve(__dirname)
      };
      engine.build(opts, done);
    });

    // Tasks
    // git wrapper: kbox git COMMAND
    kbox.tasks.add(function(task) {
      task.path = [app.name, 'git'];
      task.category = 'appAction';
      task.description = 'Run git commands.';
      task.kind = 'delegate';
      task.options.push(taskOpts.gitUsername);
      task.options.push(taskOpts.gitEmail);
      task.func = function(done) {
        // We need to use this faux bin until the resolution of
        // https://github.com/syncthing/syncthing/issues/1056
        git.cmd(this.payload, this.options, done);
      };
    });

  });

};
<|endoftext|>


<commit_before>var express = require('express');
var app = express();
var path = require('path');
var adaro = require('adaro');

app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));

app.set('views', path.join(__dirname, '/public/dist/views'));

app.engine('dust', adaro.dust());
app.set('view engine', 'dust');

app.get('/hello', function(req, res) {
  var result = '';
  result = '
hulloo wurld
';
  res.send(result);
});

app.get('/', function(req, res) {
  res.render('index', {
      title: "dan",
      job: "fe dev",
      "techs": [
          {"tech": "Node"},
          {"tech": "Express"},
          {"tech": "Dust"},
          {"tech": "Webpack"},
          {"tech": "Ongoing setup of tooling and boilerplate"}
      ]
  });
});

app.listen(app.get('port'), function() {
  console.log('Running on port', app.get('port'));
  console.log('process.env.NODE_ENV: ',app.get('process.env.NODE_ENV'));
});
<commit_msg>typo boilerplate<commit_after>var express = require('express');
var app = express();
var path = require('path');
var adaro = require('adaro');

app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));

app.set('views', path.join(__dirname, '/public/dist/views'));

app.engine('dust', adaro.dust());
app.set('view engine', 'dust');

app.get('/hello', function(req, res) {
  var result = '';
  result = '
hulloo wurld
';
  res.send(result);
});

app.get('/', function(req, res) {
  res.render('index', {
      title: "dan",
      job: "fe dev",
      "techs": [
          {"tech": "Node"},
          {"tech": "Express"},
          {"tech": "Dust"},
          {"tech": "Webpack"},
          {"tech": "Tooling and boilerplate"}
      ]
  });
});

app.listen(app.get('port'), function() {
  console.log('Running on port', app.get('port'));
  console.log('process.env.NODE_ENV: ',app.get('process.env.NODE_ENV'));
});
<|endoftext|>


<commit_before>module.exports = require('./lib/getter.js');

var x = require('./lib/getter.js');

x.get('http://www.brandontruong.com', function(data){
	console.log(data);
});<commit_msg>took out random test<commit_after>module.exports = require('./lib/getter.js');<|endoftext|>


<commit_before>/*
 Copyright 2013 Daniel Wirtz <dcode@dcode.io>

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
var path = require("path"),
    ByteBufferNB = require(path.join(__dirname, "dist", "ByteBufferNB.js")),
    ByteBufferAB = require(path.join(__dirname, "dist", "ByteBufferAB.js"));

module.exports = ByteBufferNB;
module.exports.ByteBufferNB = ByteBufferNB; // node Buffer backed
module.exports.ByteBufferAB = ByteBufferAB; // ArrayBuffer backed
<commit_msg>Simplify require<commit_after>/*
 Copyright 2013 Daniel Wirtz <dcode@dcode.io>

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
var ByteBufferNB = require("./dist/ByteBufferNB.js")),
    ByteBufferAB = require("./dist/ByteBufferAB.js"));

module.exports = ByteBufferNB;
module.exports.ByteBufferNB = ByteBufferNB; // node Buffer backed
module.exports.ByteBufferAB = ByteBufferAB; // ArrayBuffer backed
<|endoftext|>


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

var fs = require('fs');
var path = require('path');
var glob = require('glob');
var Q = require('q');
var express = require('express');
var Readable = require('stream').Readable;
var MimeMultipartStream = require('mime-multipart-stream');
var hogan = require('hogan.js');

/*
 * Cloud-Init Module
 */
function Module(options) {
  var name = options.name;
  var templates = {};

  // build lookup table
  options.templates.forEach(function(template) {
    templates[template.name] = template;
  });

  // todo: determine interface
  return {
    name: function() {
      return name;
    },

    hasTemplate: function(name) {
      return !!templates[name];
    },

    get: function(templateName) {
      return templates[templateName];
    },

    each: function(fn) {
      Object.keys(templates).forEach(function(name) {
        fn(templates[name]);
      });
    }
  }
}

Module.init = function(options) {
  var name = options.name;
  var basePath = options.basePath;
  var modulePath = path.join(basePath, name);
  var manifestFile = path.join(modulePath, 'cloudinit.json');

  function parseManifest() {
    return readFile(manifestFile).then(JSON.parse.bind(JSON));
  }

  function compileTemplates(manifest) {
    var compiledTemplates = [];

    Object.keys(manifest).forEach(function(mime) {
      manifest[mime].forEach(function(templateFile) {
        compiledTemplates.push(
          compileTemplate(mime, templateFile)
        );
      });
    });

    return Q.all(compiledTemplates);
  }

  function compileTemplate(mime, templateFile) {
    return readFile(path.join(modulePath, templateFile))
      .then(function(templateStr) {
        return hogan.compile(templateStr);
      })
      .then(function(template) {
        return { name: templateFile, template: template, mime: mime };
      });
  }

  return parseManifest()
    .then(compileTemplates)
    .then(function(templates) {
      return new Module({
        name: name,
        templates: templates
      });
    });
};

/*
 * Module Registry
 */
function Registry(modules) {
  var registry = {};

  // build lookup table
  modules.forEach(function(mod) {
    registry[mod.name()] = mod;
  });

  return {
    get: function(moduleName) {
      return registry[moduleName];
    }
  };
}

Registry.init = function(basePath) {
  var pattern = path.join(basePath, '**', 'cloudinit.json');

  console.log('Loading modules from: ' + path.resolve(basePath));

  return Q.nfcall(glob, pattern, { nodir: true })
    .then(function (files) {
      return Q.all(files.map(function(file) {
        console.log('[module]', file);
        return Module.init({
          basePath: basePath,
          name: path.dirname(path.relative(basePath, file))
        });
      }));
    })
    .then(function(modules) {
      console.log('Loaded ' + modules.length + ' module(s).');
      return new Registry(modules);
    });
}

/*
 * Cloud-Init Server
 */
function Server(registry) {
  var app = express();

  function serveTemplate(req, res) {
    var module = registry.get(req.params.moduleName);
    var template = module && module.get(req.params.templateName);

    if (!template) {
      res.status(404).send('Not Found!');
      return;
    }

    res
      .status(200)
      .set('Content-Type', template.mime)
      .send(
        template.template.render(req.query)
      );
  }

  function serveModule(req, res) {
    var module = registry.get(req.params.moduleName);

    if (!module) {
      res.status(404).send('Not Found!');
      return;
    }

    var mimeStream = MimeMultipartStream({
      boundary: genMimeBoundry(),
      type: 'mixed'
    });

    module.each(function(template) {
      var fileStream = new Readable();
      fileStream._read = function noop() {};

      mimeStream.add({
        type: template.mime + '; charset=UTF-8',
        // transferEncoding: 'base64',
        headers: {
          'Content-Disposition': 'attachment; filename="' + template.name + '"'
        },
        body: fileStream
      });

      var body = template.template.render(req.query);

      fileStream.push(body);
      fileStream.push(null);
    });

    res.status(200);
    mimeStream.pipe(res);
  }

  // Start server on port `port` and returns a promise.
  // The server is ready to handle connections when
  // the returned promise is resolved.
  function start(port) {
    console.log('Starting Server on port: ' + port);
    return Q.ninvoke(app, 'listen', port);
  }

  // Stops a running server.
  // It must be call after the server is ready for
  // connections. Otherwise it will return error.
  function stop() {
    app.close();
  }

  // configure app server
  app.get('/:moduleName/:templateName', serveTemplate);
  app.get('/:moduleName', serveModule);

  // expose public interface.
  return {
    start: start,
    stop: stop
  };
}

/*
 *  Helpers
 */
function genMimeBoundry() {
  var numbers = new Array(10);
  for (var i = 0; i < numbers.length; i++) {
    numbers[i] = Math.floor(Math.random() * 10);
  }

  return numbers.join('');
}

function readFile(file) {
  return Q.ninvoke(fs, 'readFile', file, 'utf8');
}

/*
 * Startup
 */
var port = process.env.PORT || 8888;
var modulesPath = process.argv[2] || '.';
var server;

Registry.init(modulesPath)
  .then(function (registry) {
    server = new Server(registry);
    return server.start(port);
  })
  .done(function() {
    console.log('Server started!');
  });
<commit_msg>better logging<commit_after>#!/usr/bin/env node

var fs = require('fs');
var path = require('path');
var glob = require('glob');
var Q = require('q');
var express = require('express');
var Readable = require('stream').Readable;
var MimeMultipartStream = require('mime-multipart-stream');
var hogan = require('hogan.js');

/*
 * Cloud-Init Module
 */
function Module(options) {
  var name = options.name;
  var templates = {};

  // build lookup table
  options.templates.forEach(function(template) {
    templates[template.name] = template;
  });

  // todo: determine interface
  return {
    name: function() {
      return name;
    },

    hasTemplate: function(name) {
      return !!templates[name];
    },

    get: function(templateName) {
      return templates[templateName];
    },

    each: function(fn) {
      Object.keys(templates).forEach(function(name) {
        fn(templates[name]);
      });
    }
  }
}

Module.init = function(options) {
  var name = options.name;
  var basePath = options.basePath;
  var modulePath = path.join(basePath, name);
  var manifestFile = path.join(modulePath, 'cloudinit.json');

  function parseManifest() {
    return readFile(manifestFile).then(JSON.parse.bind(JSON));
  }

  function compileTemplates(manifest) {
    var compiledTemplates = [];

    Object.keys(manifest).forEach(function(mime) {
      manifest[mime].forEach(function(templateFile) {
        compiledTemplates.push(
          compileTemplate(mime, templateFile)
        );
      });
    });

    return Q.all(compiledTemplates);
  }

  function compileTemplate(mime, templateFile) {
    return readFile(path.join(modulePath, templateFile))
      .then(function(templateStr) {
        return hogan.compile(templateStr);
      })
      .then(function(template) {
        return { name: templateFile, template: template, mime: mime };
      });
  }

  return parseManifest()
    .then(compileTemplates)
    .then(function(templates) {
      return new Module({
        name: name,
        templates: templates
      });
    });
};

/*
 * Module Registry
 */
function Registry(modules) {
  var registry = {};

  // build lookup table
  modules.forEach(function(mod) {
    registry[mod.name()] = mod;
  });

  return {
    get: function(moduleName) {
      return registry[moduleName];
    }
  };
}

Registry.init = function(basePath) {
  var pattern = path.join(basePath, '**', 'cloudinit.json');

  console.log('Loading modules from: ' + path.resolve(basePath));

  return Q.nfcall(glob, pattern, { nodir: true })
    .then(function (files) {
      return Q.all(files.map(function(file) {
        var moduleName = path.dirname(path.relative(basePath, file));
        console.log('[' + moduleName + '] Loading...');
        return Module.init({
          basePath: basePath,
          name: moduleName
        });
      }));
    })
    .then(function(modules) {
      console.log('Loaded ' + modules.length + ' module(s).');
      return new Registry(modules);
    });
}

/*
 * Cloud-Init Server
 */
function Server(registry) {
  var app = express();

  function serveTemplate(req, res) {
    var module = registry.get(req.params.moduleName);
    var template = module && module.get(req.params.templateName);

    if (!template) {
      res.status(404).send('Not Found!');
      return;
    }

    res
      .status(200)
      .set('Content-Type', template.mime)
      .send(
        template.template.render(req.query)
      );
  }

  function serveModule(req, res) {
    var module = registry.get(req.params.moduleName);

    if (!module) {
      res.status(404).send('Not Found!');
      return;
    }

    var mimeStream = MimeMultipartStream({
      boundary: genMimeBoundry(),
      type: 'mixed'
    });

    module.each(function(template) {
      var fileStream = new Readable();
      fileStream._read = function noop() {};

      mimeStream.add({
        type: template.mime + '; charset=UTF-8',
        // transferEncoding: 'base64',
        headers: {
          'Content-Disposition': 'attachment; filename="' + template.name + '"'
        },
        body: fileStream
      });

      var body = template.template.render(req.query);

      fileStream.push(body);
      fileStream.push(null);
    });

    res.status(200);
    mimeStream.pipe(res);
  }

  // Start server on port `port` and returns a promise.
  // The server is ready to handle connections when
  // the returned promise is resolved.
  function start(port) {
    console.log('Starting Server on port: ' + port);
    return Q.ninvoke(app, 'listen', port);
  }

  // Stops a running server.
  // It must be call after the server is ready for
  // connections. Otherwise it will return error.
  function stop() {
    app.close();
  }

  // configure app server
  app.get('/:moduleName/:templateName', serveTemplate);
  app.get('/:moduleName', serveModule);

  // expose public interface.
  return {
    start: start,
    stop: stop
  };
}

/*
 *  Helpers
 */
function genMimeBoundry() {
  var numbers = new Array(10);
  for (var i = 0; i < numbers.length; i++) {
    numbers[i] = Math.floor(Math.random() * 10);
  }

  return numbers.join('');
}

function readFile(file) {
  return Q.ninvoke(fs, 'readFile', file, 'utf8');
}

/*
 * Startup
 */
var port = process.env.PORT || 8888;
var modulesPath = process.argv[2] || '.';
var server;

Registry.init(modulesPath)
  .then(function (registry) {
    server = new Server(registry);
    return server.start(port);
  })
  .done(function() {
    console.log('Server started!');
  });
<|endoftext|>


<commit_before>// Inizializziamo i componenti dell'applicazione
var express = require('express');
var bodyParser = require('body-parser');
var request = require('request');
var app = express();
var mongodb = require('mongodb');

// Wit
var Wit = require('node-wit').Wit;
var log = require('node-wit').log;
var WIT_ACCESS_TOKEN = process.env.WIT_ACCESS_TOKEN;

// Connettiamoci a MongoDB.
var MongoClient = mongodb.MongoClient;

// URL precedentemente salvato dal plugin mlab.
var url = process.env.MONGODB_URI;

// Connessione al server
MongoClient.connect(url, function (err, db) {
  if (err) {
    console.log('Impossibile connettersi. Errore:', err);
  } else {
    // Siamo connessi! :)
    console.log('Connessione stabilita con: ', url);

    // Qui eseguiremo il nostro codice...

    db.close();
  }
});

// La cartella per i file statici
app.use(express.static('public'));

// Impostiamo bodyparser che ci permetterà di interpretare messaggi e confezionare payload
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());

// L'applicazione sarà in ascolto sulla porta 3000 o su una porta predefinita dal server
app.listen((process.env.PORT || 3000));

// Homepage
app.get('/', function (req, res) {
    res.send('
Questo è hotelbot
');
});

// Facebook Webhook
app.get('/webhook', function (req, res) {
    if (req.query['hub.verify_token'] === 'ciao_io_programmo_sono_hotelbot') {
        res.send(req.query['hub.challenge']);
    } else {
        res.send('Token non valido');
    }
});

// Gestione degli eventi
app.post('/webhook', function (req, res) {
    var events = req.body.entry[0].messaging;
    for (i = 0; i < events.length; i++) {
        var event = events[i];
        if (event.message && event.message.text) {
            sendMessageToWit(event.sender.id, event);
            //evaluateCommand(event.sender.id, event.message.text);
        } else if (event.postback) {
            // Abbiamo ricevuto una postback
        } else if (event.message && event.message.attachments) {
            // Gestione degli allegati
            sendTextMessage(event.sender.id, "Mi spiace, non posso gestire allegati!");
        }
    }
    res.sendStatus(200);
});

// Invia un messaggio di testo
function sendTextMessage(recipientId, text) {
    var msg = {
        "text": text
    };
    sendMessage(recipientId, msg)
}

// Invia messaggio multimediale
function sendMultimediaMessage(recipientId, type, url) {
    var msg = {
        "attachment": {
            "type": type,
            "payload": {
                "url": url
            }
        }
    };

    sendMessage(recipientId, msg);
}

// Invia un messaggio generico
function sendMessage(recipientId, message) {
    request({
        url: 'https://graph.facebook.com/v2.7/me/messages',
        qs: {access_token: process.env.PAGE_ACCESS_TOKEN},
        method: 'POST',
        json: {
            recipient: {id: recipientId},
            message: message,
        }
    }, function(error, response, body) {
        if (error) {
            console.log('Errore nella spedizione del messaggio: ', error);
        } else if (response.body.error) {
            console.log('Errore: ', response.body.error);
        }
    });
};

// Gestione dei comandi
function evaluateCommand(recipientId, text) {
    command = text.toLowerCase();
    console.log("Comando ricevuto: " + command);
}

// Codice per wit.ai
function sendMessageToWit(recipientId, event) {

  const sessionId = findOrCreateSession(recipientId);
  const {
      text,
      attachments
  } = event.message;

  // Inviamo i messaggi a Wit.ai
  // Eseguiamo le azioni fino a quando non abbiamo più niente da eseguire
  wit.runActions(
      sessionId, // sessione utente
      text, // messaggio
      sessions[sessionId].context // context sessione utente
  ).then((context) => {
        console.log('Azioni...');
        // Ok, abbiamo fatto tutto.
        // Aspettiamo nuovi messaggi.
        console.log('Aspettiamo nuovi messaggi...');

        // Updating the user's current session state
        sessions[sessionId].context = context;
      })
      .catch((err) => {
        var reply = "Mi spiace, non riesco a capirti... :-(";
        sendTextMessage(recipientId, reply);
        console.error('Oops! C\'è stato un problema! ', err.stack || err);
      })

}

const sessions = {};

const findOrCreateSession = (fbid) => {
    let sessionId;
    // Controlliamo se abbiamo una sessione utente
    Object.keys(sessions).forEach(k => {
        if (sessions[k].fbid === fbid) {
        // Eccolo
        sessionId = k;
    }
});
if (!sessionId) {
    // Sessione non trovata, ne creiamo una nuova
    sessionId = new Date().toISOString();
    sessions[sessionId] = {
        fbid: fbid,
        context: {}
    };
}
return sessionId;
};

// Le azioni del nostro bot
const actions = {
    send({
        sessionId
    }, {
        text
    }) {
    // Il nostro bot ha qualcosa da dire!
    // Recuperiamo l'id utente dalla sessione
    const recipientId = sessions[sessionId].fbid;
    if (recipientId) {
        // Utente trovato, inviamo il messaggio all'utente dopo l'esecuzione delle azioni
        return new Promise(function(resolve, reject) {
            sendTextMessage(recipientId, text);
            return resolve();
        });
    } else {
        console.error('Oops! Non ho trovato:', sessionId);
        // Giving the wheel back to our bot
        return Promise.resolve()
    }
},
// Salutiamo, perché il bot è educato
getHello({
    context,
    entities
}) {
    return new Promise(function(resolve, reject) {

        var saluto = firstEntityValue(entities, 'saluti');

        if(saluto) {
            context.greetings = "Ciao, come posso aiutarti?";
        } else {
            delete context.greetings;
        }

        return resolve(context);
    });
}
};

// Setup del bot
const wit = new Wit({
    accessToken: WIT_ACCESS_TOKEN,
    actions,
    logger: new log.Logger(log.INFO)
});

// Controllo entità
const firstEntityValue = (entities, entity) => {
  const val = entities && entities[entity] &&
    Array.isArray(entities[entity]) &&
    entities[entity].length > 0 &&
    entities[entity][0].value
  ;
  if (!val) {
    return null;
  }
  return typeof val === 'object' ? val.value : val;
};

<commit_msg>logging<commit_after>// Inizializziamo i componenti dell'applicazione
var express = require('express');
var bodyParser = require('body-parser');
var request = require('request');
var app = express();
var mongodb = require('mongodb');

// Wit
var Wit = require('node-wit').Wit;
var log = require('node-wit').log;
var WIT_ACCESS_TOKEN = process.env.WIT_ACCESS_TOKEN;

// Connettiamoci a MongoDB.
var MongoClient = mongodb.MongoClient;

// URL precedentemente salvato dal plugin mlab.
var url = process.env.MONGODB_URI;

// Connessione al server
MongoClient.connect(url, function (err, db) {
  if (err) {
    console.log('Impossibile connettersi. Errore:', err);
  } else {
    // Siamo connessi! :)
    console.log('Connessione stabilita con: ', url);

    // Qui eseguiremo il nostro codice...

    db.close();
  }
});

// La cartella per i file statici
app.use(express.static('public'));

// Impostiamo bodyparser che ci permetterà di interpretare messaggi e confezionare payload
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());

// L'applicazione sarà in ascolto sulla porta 3000 o su una porta predefinita dal server
app.listen((process.env.PORT || 3000));

// Homepage
app.get('/', function (req, res) {
    res.send('
Questo è hotelbot
');
});

// Facebook Webhook
app.get('/webhook', function (req, res) {
    if (req.query['hub.verify_token'] === 'ciao_io_programmo_sono_hotelbot') {
        res.send(req.query['hub.challenge']);
    } else {
        res.send('Token non valido');
    }
});

// Gestione degli eventi
app.post('/webhook', function (req, res) {
    var events = req.body.entry[0].messaging;
    for (i = 0; i < events.length; i++) {
        var event = events[i];
        if (event.message && event.message.text) {
            sendMessageToWit(event.sender.id, event);
            //evaluateCommand(event.sender.id, event.message.text);
        } else if (event.postback) {
            // Abbiamo ricevuto una postback
        } else if (event.message && event.message.attachments) {
            // Gestione degli allegati
            sendTextMessage(event.sender.id, "Mi spiace, non posso gestire allegati!");
        }
    }
    res.sendStatus(200);
});

// Invia un messaggio di testo
function sendTextMessage(recipientId, text) {
    var msg = {
        "text": text
    };
    sendMessage(recipientId, msg)
}

// Invia messaggio multimediale
function sendMultimediaMessage(recipientId, type, url) {
    var msg = {
        "attachment": {
            "type": type,
            "payload": {
                "url": url
            }
        }
    };

    sendMessage(recipientId, msg);
}

// Invia un messaggio generico
function sendMessage(recipientId, message) {
    request({
        url: 'https://graph.facebook.com/v2.7/me/messages',
        qs: {access_token: process.env.PAGE_ACCESS_TOKEN},
        method: 'POST',
        json: {
            recipient: {id: recipientId},
            message: message,
        }
    }, function(error, response, body) {
        if (error) {
            console.log('Errore nella spedizione del messaggio: ', error);
        } else if (response.body.error) {
            console.log('Errore: ', response.body.error);
        }
    });
};

// Gestione dei comandi
function evaluateCommand(recipientId, text) {
    command = text.toLowerCase();
    console.log("Comando ricevuto: " + command);
}

// Codice per wit.ai
function sendMessageToWit(recipientId, event) {

  const sessionId = findOrCreateSession(recipientId);
  const {
      text,
      attachments
  } = event.message;

  // Inviamo i messaggi a Wit.ai
  // Eseguiamo le azioni fino a quando non abbiamo più niente da eseguire
  wit.runActions(
      sessionId, // sessione utente
      text, // messaggio
      sessions[sessionId].context // context sessione utente
  ).then((context) => {
        console.log('Azioni...');
        // Ok, abbiamo fatto tutto.
        // Aspettiamo nuovi messaggi.
        console.log('Aspettiamo nuovi messaggi...');

        // Updating the user's current session state
        sessions[sessionId].context = context;
      })
      .catch((err) => {
        var reply = "Mi spiace, non riesco a capirti... :-(";
        sendTextMessage(recipientId, reply);
        console.error('Oops! C\'è stato un problema! ', err.stack || err);
      })

}

const sessions = {};

const findOrCreateSession = (fbid) => {
    let sessionId;
    // Controlliamo se abbiamo una sessione utente
    Object.keys(sessions).forEach(k => {
        if (sessions[k].fbid === fbid) {
        // Eccolo
        sessionId = k;
    }
});
if (!sessionId) {
    // Sessione non trovata, ne creiamo una nuova
    sessionId = new Date().toISOString();
    sessions[sessionId] = {
        fbid: fbid,
        context: {}
    };
}
return sessionId;
};

// Le azioni del nostro bot
const actions = {
    send({
        sessionId
    }, {
        text
    }) {
    // Il nostro bot ha qualcosa da dire!
    // Recuperiamo l'id utente dalla sessione
    const recipientId = sessions[sessionId].fbid;
    if (recipientId) {
        // Utente trovato, inviamo il messaggio all'utente dopo l'esecuzione delle azioni
        return new Promise(function(resolve, reject) {
            sendTextMessage(recipientId, text);
            return resolve();
        });
    } else {
        console.error('Oops! Non ho trovato:', sessionId);
        // Giving the wheel back to our bot
        return Promise.resolve()
    }
},
// Salutiamo, perché il bot è educato
getHello({
    context,
    entities
}) {
    return new Promise(function(resolve, reject) {

        var saluto = firstEntityValue(entities, 'saluti');

        if(saluto) {
            context.greetings = "Ciao, come posso aiutarti?";
        } else {
            delete context.greetings;
        }

        console.log("CONTEXT " + context);
        return resolve(context);
    });
}
};

// Setup del bot
const wit = new Wit({
    accessToken: WIT_ACCESS_TOKEN,
    actions,
    logger: new log.Logger(log.INFO)
});

// Controllo entità
const firstEntityValue = (entities, entity) => {
  const val = entities && entities[entity] &&
    Array.isArray(entities[entity]) &&
    entities[entity].length > 0 &&
    entities[entity][0].value
  ;
  if (!val) {
    return null;
  }
  return typeof val === 'object' ? val.value : val;
};

<|endoftext|>