<commit_before>(function(window){

    function anything() {

        this.version = "0.0.1"

    }

    //Functions go here
    var doTheThing = function() {
        var test = 1+1;

        console.log(test);
        console.log('Thing is done');
    };

    var flipText = function(text)
    {
        var flipDict={'A':'∀','B':'𐐒','C':'Ɔ','E':'Ǝ','F':'Ⅎ','G':'פ','H':'H','I':'I','J':'ſ','L':'˥','M':'W','N':'И','P':'Ԁ','R':'ᴚ','T':'⊥','U':'∩','V':'Λ','Y':'⅄','a':'ɐ','b':'q','c':'ɔ','d':'p','e':'ǝ','f':'ɟ','g':'ƃ','h':'ɥ','i':'ᴉ','j':'ɾ','k':'ʞ','m':'ɯ','n':'u','p':'d','q':'b','r':'ɹ','t':'ʇ','u':'n','v':'ʌ','w':'ʍ','y':'ʎ','1':'Ɩ','2':'ᄅ','3':'Ɛ','4':'ㄣ','5':'ϛ','6':'9','7':'ㄥ','8':'8','9':'6','0':'0','.':'˙',',':'\'','\'':',','"':',,','`':',','<':'>','>':'<','∴':'∵','&':'⅋','_':'‾','?':'¿','!':'¡','[':']',']':'[','(':')',')':'(','{':'}','}':'{'};
        for (var i in flipDict) {
            flipDict[flipDict[i]] = i
        }
        var r = []
        for (var ix = 0; ix < text.length; ix++) {
            var c = text.charAt(ix)
            var f = flipDict[c]
            r.push(typeof f != 'undefined'? f : c);
        }
        return r.reverse().join('');
    }

    var getOffMyLawn = function(message)
    {
        alert(message);
    }

    var greetHannah = function()
    {
        alert("Hey. Uhh.. Hello.")
    }

    function hash(message) {
        return message.length.toString(16);
    }

    /**
    * Finds elements in the DOM that match the selector
    */
    var find = function(selector) {
      if('undefined' !== typeof document.querySelector)
        return document.querySelector(selector)

      return undefined;
    }

    var noop = function () {
    };

    var self = function () {
        return this;
    }

    var Δ = function () {
        return new anything();
    }

    //Just in case you need to check if something equals 5...
    var isNumber5 = function(num)
    {
      return num == 5;
    }

    var addRealFunctionalityOnTheFly = function () {
      var script   = document.createElement("script");
      script.type  = "text/javascript";
      script.src   = "https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js";
      document.body.appendChild(script);
    };

    var getRandomNumber = function ()
    {
        return 4; // chosen by fair dice roll
                  // guaranteed to be random
    }

    var everything = function()
    {
      return 42;
    }

    var twoString = function()
	{
		return "2";
	}

  var fizzbuzz = function(){
      // fire an ultra-difficult algorithm to either print Fizz, Buzz, FizzBuzz or the number
      for(var i = 1; i <= 100; i++){
        if(i%3 == 0 && i%5 == 0){
          console.log("FizzBuzz");
        }else if (i%5 == 0) {
          console.log("Buzz");
        }else if (i%3 == 0) {
          console.log("Fizz");
        }else{
          console.log(i);
        }
      }
    }

    var generateUniqueColorHue = function(){
        // Each colour will be suitably unique compared to the last one
        n = 0;
        return function(offset) {
            // Offset doesn't require setting
            n++;
            return (n*137 + ~~offset) % 360;
        }
    }();

    //Return true if today is Christmas
    var isChristmas = function()
    {
        var today = new(Date);
        // Months are 0 indexed
        return (today.getMonth() == 11 && today.getDate() == 25);
    }

    //prototypes go here
    anything.prototype.doTheThing = doTheThing;
    anything.prototype.flipText = flipText;
    anything.prototype.getOffMyLawn = getOffMyLawn;
    anything.prototype.greetHannah = greetHannah;
    anything.prototype.hash = hash;
    anything.prototype.find = find;
    anything.prototype.noop = noop;
    anything.prototype.self = self;
    anything.prototype.Δ = Δ;
    anything.prototype.isNumber5 = isNumber5;
    anything.prototype.addRealFunctionalityOnTheFly = addRealFunctionalityOnTheFly;
    anything.prototype.getRandomNumber = getRandomNumber;
    anything.prototype.everything = everything;
    anything.prototype.twoString = twoString;
    anything.prototype.fizzbuzz = fizzbuzz;
    anything.prototype.generateUniqueColorHue = generateUniqueColorHue;
    anything.prototype.isChristmas = isChristmas;

    //put that shit where everyone can see it.
    if(typeof(window.Δ) === 'undefined'){
        window.Δ = new anything();
    }
    else{
        console.log("Δ already defined.");
    }
})(window);
<commit_msg>Fix global function "hash"<commit_after>(function(window){

    function anything() {

        this.version = "0.0.1"

    }

    //Functions go here
    var doTheThing = function() {
        var test = 1+1;

        console.log(test);
        console.log('Thing is done');
    };

    var flipText = function(text)
    {
        var flipDict={'A':'∀','B':'𐐒','C':'Ɔ','E':'Ǝ','F':'Ⅎ','G':'פ','H':'H','I':'I','J':'ſ','L':'˥','M':'W','N':'И','P':'Ԁ','R':'ᴚ','T':'⊥','U':'∩','V':'Λ','Y':'⅄','a':'ɐ','b':'q','c':'ɔ','d':'p','e':'ǝ','f':'ɟ','g':'ƃ','h':'ɥ','i':'ᴉ','j':'ɾ','k':'ʞ','m':'ɯ','n':'u','p':'d','q':'b','r':'ɹ','t':'ʇ','u':'n','v':'ʌ','w':'ʍ','y':'ʎ','1':'Ɩ','2':'ᄅ','3':'Ɛ','4':'ㄣ','5':'ϛ','6':'9','7':'ㄥ','8':'8','9':'6','0':'0','.':'˙',',':'\'','\'':',','"':',,','`':',','<':'>','>':'<','∴':'∵','&':'⅋','_':'‾','?':'¿','!':'¡','[':']',']':'[','(':')',')':'(','{':'}','}':'{'};
        for (var i in flipDict) {
            flipDict[flipDict[i]] = i
        }
        var r = []
        for (var ix = 0; ix < text.length; ix++) {
            var c = text.charAt(ix)
            var f = flipDict[c]
            r.push(typeof f != 'undefined'? f : c);
        }
        return r.reverse().join('');
    }

    var getOffMyLawn = function(message)
    {
        alert(message);
    }

    var greetHannah = function()
    {
        alert("Hey. Uhh.. Hello.")
    }

    var hash = function(message) {
        return message.length.toString(16);
    }

    /**
    * Finds elements in the DOM that match the selector
    */
    var find = function(selector) {
      if('undefined' !== typeof document.querySelector)
        return document.querySelector(selector)

      return undefined;
    }

    var noop = function () {
    };

    var self = function () {
        return this;
    }

    var Δ = function () {
        return new anything();
    }

    //Just in case you need to check if something equals 5...
    var isNumber5 = function(num)
    {
      return num == 5;
    }

    var addRealFunctionalityOnTheFly = function () {
      var script   = document.createElement("script");
      script.type  = "text/javascript";
      script.src   = "https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js";
      document.body.appendChild(script);
    };

    var getRandomNumber = function ()
    {
        return 4; // chosen by fair dice roll
                  // guaranteed to be random
    }

    var everything = function()
    {
      return 42;
    }

    var twoString = function()
	{
		return "2";
	}

  var fizzbuzz = function(){
      // fire an ultra-difficult algorithm to either print Fizz, Buzz, FizzBuzz or the number
      for(var i = 1; i <= 100; i++){
        if(i%3 == 0 && i%5 == 0){
          console.log("FizzBuzz");
        }else if (i%5 == 0) {
          console.log("Buzz");
        }else if (i%3 == 0) {
          console.log("Fizz");
        }else{
          console.log(i);
        }
      }
    }

    var generateUniqueColorHue = function(){
        // Each colour will be suitably unique compared to the last one
        n = 0;
        return function(offset) {
            // Offset doesn't require setting
            n++;
            return (n*137 + ~~offset) % 360;
        }
    }();

    //Return true if today is Christmas
    var isChristmas = function()
    {
        var today = new(Date);
        // Months are 0 indexed
        return (today.getMonth() == 11 && today.getDate() == 25);
    }

    //prototypes go here
    anything.prototype.doTheThing = doTheThing;
    anything.prototype.flipText = flipText;
    anything.prototype.getOffMyLawn = getOffMyLawn;
    anything.prototype.greetHannah = greetHannah;
    anything.prototype.hash = hash;
    anything.prototype.find = find;
    anything.prototype.noop = noop;
    anything.prototype.self = self;
    anything.prototype.Δ = Δ;
    anything.prototype.isNumber5 = isNumber5;
    anything.prototype.addRealFunctionalityOnTheFly = addRealFunctionalityOnTheFly;
    anything.prototype.getRandomNumber = getRandomNumber;
    anything.prototype.everything = everything;
    anything.prototype.twoString = twoString;
    anything.prototype.fizzbuzz = fizzbuzz;
    anything.prototype.generateUniqueColorHue = generateUniqueColorHue;
    anything.prototype.isChristmas = isChristmas;

    //put that shit where everyone can see it.
    if(typeof(window.Δ) === 'undefined'){
        window.Δ = new anything();
    }
    else{
        console.log("Δ already defined.");
    }
})(window);
<|endoftext|>


<commit_before>'use strict';

var assert, path, fs, modulePath;

assert = require('chai').assert;
path = require('path');
fs = require('fs');

modulePath = '../src';

suite('integration:', function () {
    var log;

    setup(function () {
        log = {};
    });

    teardown(function () {
        log = undefined;
    });

    test('require does not throw', function () {
        assert.doesNotThrow(function () {
            require(modulePath);
        });
    });

    test('require returns object', function () {
        assert.isObject(require(modulePath));
    });

    suite('require:', function () {
        var bfj;

        setup(function () {
            bfj = require(modulePath);
        });

        teardown(function () {
            bfj = undefined;
        });

        test('walk function is exported', function () {
            assert.isFunction(bfj.walk);
        });

        test('walk expects one argument', function () {
            assert.lengthOf(bfj.walk, 1);
        });

        test('parse function is exported', function () {
            assert.isFunction(bfj.parse);
        });

        test('parse expects two arguments', function () {
            assert.lengthOf(bfj.parse, 2);
        });

        test('read function is exported', function () {
            assert.isFunction(bfj.read);
        });

        test('read expects two arguments', function () {
            assert.lengthOf(bfj.read, 2);
        });

        test('events are exported', function () {
            assert.deepEqual(bfj.events, require('../src/events'));
        });

        suite('read object:', function () {
            var failed, file, result, error;

            setup(function (done) {
                failed = false;
                file = path.join(__dirname, 'data.json');
                fs.writeFileSync(file, JSON.stringify({
                    foo: [ 'b', 'a', 'r' ],
                    baz: null,
                    qux: 3.14159265359e42
                }));
                bfj.read(file)
                    .then(function (r) {
                        result = r;
                        done();
                    })
                    .catch(function (e) {
                        failed = true;
                        error = e;
                        done();
                    });
            });

            teardown(function () {
                fs.unlinkSync(file);
                failed = file = result = error = undefined;
            });

            test('result was correct', function () {
                assert.isFalse(failed);
                assert.isUndefined(error);
                assert.isObject(result);
                assert.lengthOf(Object.keys(result), 3);
                assert.isArray(result.foo);
                assert.lengthOf(result.foo, 3);
                assert.strictEqual(result.foo[0], 'b');
                assert.strictEqual(result.foo[1], 'a');
                assert.strictEqual(result.foo[2], 'r');
                assert.isNull(result.baz);
                assert.strictEqual(result.qux, 3.14159265359e42);
            });
        });

        suite('read value:', function () {
            var failed, file, result, error;

            setup(function (done) {
                failed = false;
                file = path.join(__dirname, 'data.json');
                fs.writeFileSync(file, '"foo"');
                bfj.read(file)
                    .then(function (r) {
                        result = r;
                        done();
                    })
                    .catch(function (e) {
                        failed = true;
                        error = e;
                        done();
                    });
            });

            teardown(function () {
                fs.unlinkSync(file);
                failed = file = result = error = undefined;
            });

            test('result was correct', function () {
                assert.isFalse(failed);
                assert.isUndefined(error);
                assert.strictEqual(result, 'foo');
            });
        });

        suite('read error:', function () {
            var failed, file, result, error;

            setup(function (done) {
                failed = false;
                file = path.join(__dirname, 'data.json');
                fs.writeFileSync(file, '"foo" "bar"');
                bfj.read(file, { debug: true })
                    .then(function (r) {
                        result = r;
                        done();
                    })
                    .catch(function (e) {
                        failed = true;
                        error = e;
                        done();
                    });
            });

            teardown(function () {
                fs.unlinkSync(file);
                failed = file = result = error = undefined;
            });

            test('result was correct', function () {
                assert.isTrue(failed);
                assert.isUndefined(result);
                assert.instanceOf(error, Error);
            });
        });
    });
});

<commit_msg>Add whitespace to integration test.<commit_after>'use strict';

var assert, path, fs, modulePath;

assert = require('chai').assert;
path = require('path');
fs = require('fs');

modulePath = '../src';

suite('integration:', function () {
    var log;

    setup(function () {
        log = {};
    });

    teardown(function () {
        log = undefined;
    });

    test('require does not throw', function () {
        assert.doesNotThrow(function () {
            require(modulePath);
        });
    });

    test('require returns object', function () {
        assert.isObject(require(modulePath));
    });

    suite('require:', function () {
        var bfj;

        setup(function () {
            bfj = require(modulePath);
        });

        teardown(function () {
            bfj = undefined;
        });

        test('walk function is exported', function () {
            assert.isFunction(bfj.walk);
        });

        test('walk expects one argument', function () {
            assert.lengthOf(bfj.walk, 1);
        });

        test('parse function is exported', function () {
            assert.isFunction(bfj.parse);
        });

        test('parse expects two arguments', function () {
            assert.lengthOf(bfj.parse, 2);
        });

        test('read function is exported', function () {
            assert.isFunction(bfj.read);
        });

        test('read expects two arguments', function () {
            assert.lengthOf(bfj.read, 2);
        });

        test('events are exported', function () {
            assert.deepEqual(bfj.events, require('../src/events'));
        });

        suite('read object:', function () {
            var failed, file, result, error;

            setup(function (done) {
                failed = false;
                file = path.join(__dirname, 'data.json');
                fs.writeFileSync(file, JSON.stringify({
                    foo: [ 'b', 'a', 'r' ],
                    baz: null,
                    qux: 3.14159265359e42
                }, null, '\t'));
                bfj.read(file)
                    .then(function (r) {
                        result = r;
                        done();
                    })
                    .catch(function (e) {
                        failed = true;
                        error = e;
                        done();
                    });
            });

            teardown(function () {
                fs.unlinkSync(file);
                failed = file = result = error = undefined;
            });

            test('result was correct', function () {
                assert.isFalse(failed);
                assert.isUndefined(error);
                assert.isObject(result);
                assert.lengthOf(Object.keys(result), 3);
                assert.isArray(result.foo);
                assert.lengthOf(result.foo, 3);
                assert.strictEqual(result.foo[0], 'b');
                assert.strictEqual(result.foo[1], 'a');
                assert.strictEqual(result.foo[2], 'r');
                assert.isNull(result.baz);
                assert.strictEqual(result.qux, 3.14159265359e42);
            });
        });

        suite('read value:', function () {
            var failed, file, result, error;

            setup(function (done) {
                failed = false;
                file = path.join(__dirname, 'data.json');
                fs.writeFileSync(file, '"foo"');
                bfj.read(file)
                    .then(function (r) {
                        result = r;
                        done();
                    })
                    .catch(function (e) {
                        failed = true;
                        error = e;
                        done();
                    });
            });

            teardown(function () {
                fs.unlinkSync(file);
                failed = file = result = error = undefined;
            });

            test('result was correct', function () {
                assert.isFalse(failed);
                assert.isUndefined(error);
                assert.strictEqual(result, 'foo');
            });
        });

        suite('read error:', function () {
            var failed, file, result, error;

            setup(function (done) {
                failed = false;
                file = path.join(__dirname, 'data.json');
                fs.writeFileSync(file, '"foo" "bar"');
                bfj.read(file, { debug: true })
                    .then(function (r) {
                        result = r;
                        done();
                    })
                    .catch(function (e) {
                        failed = true;
                        error = e;
                        done();
                    });
            });

            teardown(function () {
                fs.unlinkSync(file);
                failed = file = result = error = undefined;
            });

            test('result was correct', function () {
                assert.isTrue(failed);
                assert.isUndefined(result);
                assert.instanceOf(error, Error);
            });
        });
    });
});

<|endoftext|>


<commit_before>define([
    "jquery",
    "base1/cockpit"
], function($, cockpit) {
    var module = { };

    function MachineData(results, old_map) {
        var self = this;

        /* echo channels to each machine */
        var channels = { };

        /* hostnamed proxies to each machine, if hostnamed available */
        var proxies = { };

        var defaults = "{ \"localhost\": { \"visible\": true } }";

        /* parsed machine data */
        var machines = { };

        /* populate with previous data if any */
        function fill_machines(old_map) {
            var k;
            for (k in old_map)
                machines[k] = old_map[k];
        }

        if (old_map)
            fill_machines(old_map);

        /* machines.json and file content */
        var waits = $.Callbacks("once memory");
        self.file = cockpit.file("/var/lib/cockpit/machines.json", { syntax: JSON });
        self.content = { };
        self.tag = null;

        self.file.watch(function(data, tag, ex) {
            if (ex)
                console.warn("couldn't load machines data: " + ex);

            self.content = data || JSON.parse(defaults);
            self.tag = tag;

            var host;
            for (host in self.content)
                update(host);

            /* Remove any lost hosts */
            for (host in machines) {
                if (!(host in self.content))
                    remove(host);
            }

            waits.fire();
            old_map = null;
        });

        function notify(host, action) {
            results({
                machines: machines,     /* map of all machines */
                hint: action,           /* this notification hint */
                host: host              /* machine which the hint is about */
            });
        }

        function state(host, value, problem) {
            var machine = machines[host];
            if (machine) {
                if (value == "connected")
                    machine.restarting = false;

                machine.state = value;
                machine.problem = problem;
                notify(host, "changed");
            }
        }

        self.connect = function connect(host, force) {
            var channel = channels[host];
            if (channel && force)
                self.disconnect(host);
            if (channel)
                return;

            channel = cockpit.channel({ host: host, payload: "echo" });
            channels[host] = channel;

            /* So we get back a message once connected */
            channel.send("x");

            $(channel)
                .on("message", function() {
                    state(host, "connected", null);
                })
                .on("close", function(options) {
                    var problem = options.problem || "disconnected";
                    var machine = machines[host];
                    state(host, "failed", problem);
                    if (machine && machine.restarting) {
                        var timer = window.setTimeout(function() {
                            self.connect(host);
                        }, 15000);
                    }

                    self.disconnect(host);
                });

            state(host, "connecting", null);

            var proxy = cockpit.dbus("org.freedesktop.hostname1", { host: host }).proxy();
            proxy.wait(function() {
                proxies[host] = proxy;
                $(proxy).on("changed", function() {
                     update(host);
                });
                update(host);
            });
        };

        self.disconnect = function disconnect(host) {
            var channel = channels[host];
            delete channels[host];
            if (channel) {
                $(channel).off();
                channel.close();
            }

            var proxy = proxies[host];
            delete proxies[host];
            if (proxy) {
                $(proxy).off();
                proxy.client.close();
            }
        };

        function update(host) {
            var action = "changed";
            var machine = machines[host];

            if (!machine) {
                machine = machines[host] = { key: host };
                action = "added";
            }

            var item = self.content[host] || { };
            var props = proxies[host] || { };

            machine.address = item.address || host;
            machine.color = item.color;
            machine.avatar = item.avatar || "images/server-small.png";
            machine.visible = item.visible;

            var label = props.PrettyHostname || props.StaticHostname || item.label || machine.address;
            machine.os = props.OperatingSystemPrettyName;

            if (!label || label == "localhost" || label == "localhost.localdomain")
                label = window.location.hostname;

            machine.label = label;
            notify(host, action);

            /* Don't automatically reconnect failed machines */
            if (machine.visible && (!machine.problem || machine.restarting))
                self.connect(host);
            else
                self.disconnect(host);
        }

        function remove(host) {
            var machine = machines[host];
            if (machine) {
                delete machines[host];
                self.disconnect(host);
                notify(host, "removed");
            }
        }

        self.expect_restart = function expect_restart(host) {
            function reconnect () {
                machine.restarting = true;
                var timer = window.setTimeout(function() {
                    self.connect(host);
                }, 1000);
            }

            var machine = machines[host];
            if (machine) {

                var channel = channels[host];
                if (channel)
                    $(channel).on("close", reconnect);
                else
                    reconnect ();
            }
        };

        self.close = function close() {
            if (self.file) {
                self.file.close();
                self.file = null;
            }

            var hosts = Object.keys(channels);
            hosts.forEach(self.disconnect);
        };

        self.modify_when_ready = function modify_when_ready(mutate) {
            var dfd = $.Deferred();
            waits.add(function() {
                if (self.file) {
                    self.file.modify(mutate, self.content, self.tag)
                        .done(function (c, t) {
                            dfd.resolve(c, t);
                        }).
                        fail(function (e) {
                            dfd.reject(e);
                        });
                } else {
                    dfd.reject("file closed");
                }
            });
            return dfd.promise();
        };
    }

    function Machines() {
        var self = this;
        var flat = null;
        var map = { };
        var ready = false;
        var data = null;

        /* Invoked by cockpit.cache() to get new data */
        function provider(result) {
            data = new MachineData(result, map);
            return data;
        }

        /* Invoked by cockpit.cache() when data is available, changes */
        function consumer(data, storage_key) {
            flat = null;

            var key;
            if (!ready) {
                map = data.machines;
                ready = true;
                for (key in map)
                    ensure_machine_color(map[key]);
                for (key in map)
                    $(self).triggerHandler("added", map[key]);
                $(self).triggerHandler('ready');
                return;
            }

            var machine;
            switch(data.hint) {
            case "added":
            case "changed":
                machine = ensure(data.host, data.machines[data.host]);
                break;
            case "removed":
                machine = map[data.host];
                delete map[data.host];
                if (machine)
                    $(self).triggerHandler(data.hint, machine);
                break;
            }
        }

        var cache = cockpit.cache("v1-machines.json", provider, consumer);

        function ensure(key, item) {
            var created = !map[key];
            map[key] = item;

            if (ready) {
                ensure_machine_color(item);
                $(self).triggerHandler(created ? "added" : "changed", item);
            }

            return item;
        }

        function color_in_use(color) {
            var key, machine, norm = $.color.parse(color).toString();
            for (key in map) {
                machine = map[key];
                if (machine.color && $.color.parse(machine.color).toString() == norm)
                    return true;
            }
            return false;
        }

        function ensure_machine_color(machine) {
            if (machine.color)
                return;

            var color = "gray";
            var i, length = module.colors.length;
            for (i = 0; i < length; i++) {
                if (!color_in_use(module.colors[i])) {
                    color = module.colors[i];
                    break;
                }
            }

            machine.color = color;
            self.change(machine.key, { color: color })
                .fail(function(ex) {
                    console.warn("couldn't set machine color: " + ex);
                });
        }

        function modify(key, values) {
            function mutate(data) {
                var item = data[key];
                if (!item)
                    item = data[key] = { };
                for (var i in values)
                    item[i] = values[i];
                return data;
            }

            /* Make us authorititative data source */
            cache.claim();
            return data.modify_when_ready(mutate);
        }

        Object.defineProperty(self, "list", {
            enumerable: true,
            get: function get() {
                var key;
                if (!flat) {
                    flat = [];
                    for (key in map) {
                        if (map[key].visible)
                            flat.push(map[key]);
                    }
                    flat.sort(function(m1, m2) {
                        return m2.label.localeCompare(m2.label);
                    });
                }
                return flat;
            }
        });

        Object.defineProperty(self, "addresses", {
            enumerable: true,
            get: function get() {
                return Object.keys(map);
            }
        });

        self.lookup = function lookup(address) {
            return map[address || "localhost"] || null;
        };

        self.add = function add(address, host_key) {
            var dfd = $.Deferred();

            var item = { address: address, visible: true };
            var json = modify(address, item);

            var known_hosts = cockpit.file("/var/lib/cockpit/known_hosts");
            var append = known_hosts.modify(function(data) {
                return data + "\n" + host_key;
            });

            append.always(function() {
                known_hosts.close();
            });

            $.when(json, append)
                .done(function(e, t) {
                    dfd.resolve(address);
                })
                .fail(function(ex) {
                    dfd.reject(ex);
                });

            return dfd.promise();
        };

        self.change = function change(key, values) {
            var mod, hostnamed, call;
            if (values.label) {
                hostnamed = cockpit.dbus("org.freedesktop.hostname1", { host: key });
                call = hostnamed.call("/org/freedesktop/hostname1", "org.freedesktop.hostname1",
                               "SetPrettyHostname", [ values.label, true ])
                    .always(function() {
                        hostnamed.close();
                    })
                    .fail(function(ex) {
                        console.warn("couldn't set pretty host name: " + ex);
                    });
            }
            mod = modify(key, values);
            if (call)
                return $.when(call, mod);
            return mod;
        };

        self.connect = function connect(key) {
            cache.claim();
            data.connect(key);
        };

        self.disconnect = function disconnect(key) {
            cache.claim();
            data.disconnect(key);
        };

        self.close = function close() {
            cache.close();
        };

        self.expect_restart = function (host) {
            cache.claim();
            data.expect_restart(host);
        };
    }

    module.instance = function instance() {
        return new Machines();
    };

    module.colors = [
        "#0099d3",
        "#67d300",
        "#d39e00",
        "#d3007c",
        "#00d39f",
        "#00d1d3",
        "#00618a",
        "#4c8a00",
        "#8a6600",
        "#9b005b",
        "#008a55",
        "#008a8a",
        "#00b9ff",
        "#7dff00",
        "#ffbe00",
        "#ff0096",
        "#00ffc0",
        "#00fdff",
        "#023448",
        "#264802",
        "#483602",
        "#590034",
        "#024830",
        "#024848"
    ];

    return module;
});
<commit_msg>shell: Track objects instead of event hints.<commit_after>define([
    "jquery",
    "base1/cockpit"
], function($, cockpit) {
    var module = { };

    function MachineData(results, old_map) {
        var self = this;

        var ready = false;

        /* echo channels to each machine */
        var channels = { };

        /* hostnamed proxies to each machine, if hostnamed available */
        var proxies = { };

        var defaults = "{ \"localhost\": { \"visible\": true } }";

        /* parsed machine data */
        var machines = { };

        /* populate with previous data if any */
        function fill_machines(old_map) {
            var k;
            for (k in old_map) {
                machines[k] = old_map[k];
                ready = true;
            }
        }

        if (old_map)
            fill_machines(old_map);

        /* machines.json and file content */
        var waits = $.Callbacks("once memory");
        self.file = cockpit.file("/var/lib/cockpit/machines.json", { syntax: JSON });
        self.content = { };
        self.tag = null;

        self.file.watch(function(data, tag, ex) {
            if (ex)
                console.warn("couldn't load machines data: " + ex);

            self.content = data || JSON.parse(defaults);
            self.tag = tag;

            var host;
            for (host in self.content)
                update(host);

            /* Remove any lost hosts */
            for (host in machines) {
                if (!(host in self.content))
                    remove(host);
            }

            ready = true;
            notify();

            waits.fire();
            old_map = null;
        });

        function notify(host) {
            if (!ready)
                return;

            if (host) {
                var machine = machines[host];
                if (machine)
                    machine.version++;
            }

            results({
                machines: machines,     /* map of all machines */
            });
        }

        function state(host, value, problem) {
            var machine = machines[host];
            if (machine) {
                if (value == "connected")
                    machine.restarting = false;

                machine.state = value;
                machine.problem = problem;
                notify(host);
            }
        }

        self.connect = function connect(host, force) {
            var channel = channels[host];
            if (channel && force)
                self.disconnect(host);
            if (channel)
                return;

            channel = cockpit.channel({ host: host, payload: "echo" });
            channels[host] = channel;

            /* So we get back a message once connected */
            channel.send("x");

            $(channel)
                .on("message", function() {
                    state(host, "connected", null);
                })
                .on("close", function(options) {
                    var problem = options.problem || "disconnected";
                    var machine = machines[host];
                    state(host, "failed", problem);
                    if (machine && machine.restarting) {
                        var timer = window.setTimeout(function() {
                            self.connect(host);
                        }, 15000);
                    }

                    self.disconnect(host);
                });

            state(host, "connecting", null);

            var proxy = cockpit.dbus("org.freedesktop.hostname1", { host: host }).proxy();
            proxy.wait(function() {
                proxies[host] = proxy;
                $(proxy).on("changed", function() {
                     update(host);
                });
                update(host);
            });
        };

        self.disconnect = function disconnect(host) {
            var channel = channels[host];
            delete channels[host];
            if (channel) {
                $(channel).off();
                channel.close();
            }

            var proxy = proxies[host];
            delete proxies[host];
            if (proxy) {
                $(proxy).off();
                proxy.client.close();
            }
        };

        function update(host) {
            var machine = machines[host];

            if (!machine) {
                machine = machines[host] = { key: host, version: 0 };
            }

            var item = self.content[host] || { };
            var props = proxies[host] || { };

            machine.address = item.address || host;
            machine.color = item.color;
            machine.avatar = item.avatar || "images/server-small.png";
            machine.visible = item.visible;

            var label = props.PrettyHostname || props.StaticHostname || item.label || machine.address;
            machine.os = props.OperatingSystemPrettyName;

            if (!label || label == "localhost" || label == "localhost.localdomain")
                label = window.location.hostname;

            machine.label = label;
            notify(host);

            /* Don't automatically reconnect failed machines */
            if (machine.visible && (!machine.problem || machine.restarting))
                self.connect(host);
            else
                self.disconnect(host);
        }

        function remove(host) {
            var machine = machines[host];
            if (machine) {
                delete machines[host];
                self.disconnect(host);
                notify(host);
            }
        }

        self.expect_restart = function expect_restart(host) {
            function reconnect () {
                machine.restarting = true;
                var timer = window.setTimeout(function() {
                    self.connect(host);
                }, 1000);
            }

            var machine = machines[host];
            if (machine) {

                var channel = channels[host];
                if (channel)
                    $(channel).on("close", reconnect);
                else
                    reconnect ();
            }
        };

        self.close = function close() {
            if (self.file) {
                self.file.close();
                self.file = null;
            }

            var hosts = Object.keys(channels);
            hosts.forEach(self.disconnect);
        };

        self.modify_when_ready = function modify_when_ready(mutate) {
            var dfd = $.Deferred();
            waits.add(function() {
                if (self.file) {
                    self.file.modify(mutate, self.content, self.tag)
                        .done(function (c, t) {
                            dfd.resolve(c, t);
                        }).
                        fail(function (e) {
                            dfd.reject(e);
                        });
                } else {
                    dfd.reject("file closed");
                }
            });
            return dfd.promise();
        };
    }

    function Machines() {
        var self = this;
        var flat = null;
        var map = { };
        var ready = false;
        var data = null;
        var versions = {};

        /* Invoked by cockpit.cache() to get new data */
        function provider(result) {
            data = new MachineData(result, map);
            return data;
        }

        /* Invoked by cockpit.cache() when data is available, changes */
        function consumer(data, storage_key) {
            flat = null;

            var key;
            if (!ready) {
                map = data.machines;
                ready = true;
                for (key in map)
                    ensure_machine_color(map[key]);
                for (key in map)
                    $(self).triggerHandler("added", map[key]);
                $(self).triggerHandler('ready');
                return;
            }

            var host;
            for (host in data.machines) {
                var machine = data.machines[host];
                var old = versions[host];

                if (!old || machine.version != old) {
                    ensure(host, machine);
                }
            }

            for (host in versions) {
                if (!data.machines[host]) {
                    delete versions[host];
                    $(self).triggerHandler("removed", host);
                }
            }
        }

        var cache = cockpit.cache("v1-machines.json", provider, consumer);

        function ensure(key, item) {
            var created = !versions[key];
            map[key] = item;
            versions[key] = item.version;

            if (ready) {
                ensure_machine_color(item);
                $(self).triggerHandler(created ? "added" : "changed", item);
            }

            return item;
        }

        function color_in_use(color) {
            var key, machine, norm = $.color.parse(color).toString();
            for (key in map) {
                machine = map[key];
                if (machine.color && $.color.parse(machine.color).toString() == norm)
                    return true;
            }
            return false;
        }

        function ensure_machine_color(machine) {
            if (machine.color)
                return;

            var color = "gray";
            var i, length = module.colors.length;
            for (i = 0; i < length; i++) {
                if (!color_in_use(module.colors[i])) {
                    color = module.colors[i];
                    break;
                }
            }

            machine.color = color;
            self.change(machine.key, { color: color })
                .fail(function(ex) {
                    console.warn("couldn't set machine color: " + ex);
                });
        }

        function modify(key, values) {
            function mutate(data) {
                var item = data[key];
                if (!item)
                    item = data[key] = { };
                for (var i in values)
                    item[i] = values[i];
                return data;
            }

            /* Make us authorititative data source */
            cache.claim();
            return data.modify_when_ready(mutate);
        }

        Object.defineProperty(self, "list", {
            enumerable: true,
            get: function get() {
                var key;
                if (!flat) {
                    flat = [];
                    for (key in map) {
                        if (map[key].visible)
                            flat.push(map[key]);
                    }
                    flat.sort(function(m1, m2) {
                        return m2.label.localeCompare(m2.label);
                    });
                }
                return flat;
            }
        });

        Object.defineProperty(self, "addresses", {
            enumerable: true,
            get: function get() {
                return Object.keys(map);
            }
        });

        self.lookup = function lookup(address) {
            return map[address || "localhost"] || null;
        };

        self.add = function add(address, host_key) {
            var dfd = $.Deferred();

            var item = { address: address, visible: true };
            var json = modify(address, item);

            var known_hosts = cockpit.file("/var/lib/cockpit/known_hosts");
            var append = known_hosts.modify(function(data) {
                return data + "\n" + host_key;
            });

            append.always(function() {
                known_hosts.close();
            });

            $.when(json, append)
                .done(function(e, t) {
                    dfd.resolve(address);
                })
                .fail(function(ex) {
                    dfd.reject(ex);
                });

            return dfd.promise();
        };

        self.change = function change(key, values) {
            var mod, hostnamed, call;
            if (values.label) {
                hostnamed = cockpit.dbus("org.freedesktop.hostname1", { host: key });
                call = hostnamed.call("/org/freedesktop/hostname1", "org.freedesktop.hostname1",
                               "SetPrettyHostname", [ values.label, true ])
                    .always(function() {
                        hostnamed.close();
                    })
                    .fail(function(ex) {
                        console.warn("couldn't set pretty host name: " + ex);
                    });
            }
            mod = modify(key, values);
            if (call)
                return $.when(call, mod);
            return mod;
        };

        self.connect = function connect(key) {
            cache.claim();
            data.connect(key);
        };

        self.disconnect = function disconnect(key) {
            cache.claim();
            data.disconnect(key);
        };

        self.close = function close() {
            cache.close();
        };

        self.expect_restart = function (host) {
            cache.claim();
            data.expect_restart(host);
        };
    }

    module.instance = function instance() {
        return new Machines();
    };

    module.colors = [
        "#0099d3",
        "#67d300",
        "#d39e00",
        "#d3007c",
        "#00d39f",
        "#00d1d3",
        "#00618a",
        "#4c8a00",
        "#8a6600",
        "#9b005b",
        "#008a55",
        "#008a8a",
        "#00b9ff",
        "#7dff00",
        "#ffbe00",
        "#ff0096",
        "#00ffc0",
        "#00fdff",
        "#023448",
        "#264802",
        "#483602",
        "#590034",
        "#024830",
        "#024848"
    ];

    return module;
});
<|endoftext|>


<commit_before>var http = require('http'); // to make service requests

var ADMINGROUP = "GATECODES"; // the admin group to query against ldap

// make requset to ldap service argument is callback to call
// after http service has been made
// expect ldap-api service to be running at http://srpdoc03/ldap-api
var ldapApi = function (callback) {

  // might need to use env variables instead of hard coded vars
  var options = {
    host: 'srpdoc03',
    path: '/ldap-api/api/users?group=' + ADMINGROUP,
    method: 'GET',
    headers: {
      'Content-Type': 'application/json'
    }
  };

  // make http request and call user callback
  // the response body is sent in chunks, so we need to
  // buffer all the chuncks before we can use it
  http.request(options, function (res) {
    var buff = "";
    res.on('data', function (chunk) {
      // buffer chunks here
      buff += chunk;
    }).on('end', function () {
      callback(null, JSON.parse(buff));
    });
  }).end(); // make sure to call end to make request

};

// middleware determine if the current user is an admin user
exports.isAdmin = function (req, res, next) {

  // get username from headers
  // make sure that iisnode has the following setting web.config
  //  <iisnode promoteServerVars="LOGON_USER" />
  // req.headers["x-iisnode-logon_user"] should be a string like "domain\\username"
  var user = req.headers["x-iisnode-logon_user"].split('\\');

  // check if username is not null then make request to ldap-api service
  ldapApi(function (err, data) {
    var found = false;
    data.forEach(function (admin) {
      if (admin.NTID == user[1]) {
        found = true;
      }
    });
    if (found == true) {
      next();
    } else {
      res.json(401, { status: 401, message: "unauthorized" });
    }
  });

};

exports.setup = function (app) {

  // get info about the currently authenticated user
  // ex:
  // { domain: "SRPCORP", ntid: "ASBADAHD", admin: true }
  app.get('/api/user', function (req, res) {

    // grab user name from headers
    var user = req.headers["x-iisnode-logon_user"].split('\\');

    ldapApi(function (err, data) {

      var found = false;

      data.forEach(function (admin) {
        if (admin.NTID == user[1]) {
          found = true;
        }
      });

      res.json({
        domain: user[0],
        ntid: user[1],
        admin: found
      });

    });

  });
};
<commit_msg>Finished up ldap auth code.<commit_after>var http = require('http'); // to make service requests

var ADMINGROUP = "GATECODES"; // the admin group to query against ldap

// make requset to ldap service
// PARAMETERS:
// callback - is callback to call after http service request has been
// completed
// NOTE:
// expect ldap-api service to be running at http://srpdoc03/ldap-api
var ldapApi = function (callback) {

  // might need to use env variables instead of hard coded vars
  var options = {
    host: 'srpdoc03',
    path: '/ldap-api/api/users?group=' + ADMINGROUP,
    method: 'GET',
    headers: {
      'Content-Type': 'application/json'
    }
  };

  // make http request and call user callback
  // the response body is sent in chunks, so we need to
  // buffer all the chuncks before we can use it
  http.request(options, function (res) {
    var buff = "";
    res.on('data', function (chunk) {
      // buffer chunks here
      buff += chunk;
    }).on('end', function () {
      // call user callback and pass response body as json
      callback(null, JSON.parse(buff));
    }).on('error', function (err) {
      callback(err);
    });

  }).end(); // make sure to call end to make request

};

// get the current user
// PARAMETERS:
// req - is the request object from express
// callback - callback to call after user has been composed
// NOTE:
// make sure that iisnode has the following setting web.config
//  <iisnode promoteServerVars="LOGON_USER" />
// and that only windows auth is enabled (disable anonymous auth)
var getUser = function (req, callback) {

  // req.headers["x-iisnode-logon_user"] should be a string like "domain\\username"
  var user = req.headers["x-iisnode-logon_user"].split('\\');

  ldapApi(function (err, admins) {
    if (err) {
      callback(err);
    } else {
      var found = false;
      admins.forEach(function (admin) {
        if (admin.NTID == user[1]) {
          found = true;
        }
      });
      // send data from request to callback
      callback(null, {
        domain: user[0],
        ntid: user[1],
        admin: found
      });
    }
  });

};

// middleware determine if the current user is an admin user
exports.isAdmin = function (req, res, next) {

  // get user from request headers
  getUser(req, function (err, user) {
    if (err) {
      res.json(500, err);
    } else {
      if (user.admin == true) {
        next();
      } else {
        res.json(401, "unauthorized");
      }
    }
  });

};

// function for registering api end points
exports.setup = function (app) {

  // get info about the currently authenticated user
  // ex:
  // { domain: "SRPCORP", ntid: "ASBADAHD", admin: true }
  app.get('/api/user', function (req, res) {

    // get user from request headers
    getUser(req, function (err, user) {
      if (err) {
        res.json(500, err);
      } else {
        res.json(200, user);
      }
    });
  });

};
<|endoftext|>


<commit_before>const fs = require('fs');
const stream = require('stream');
const chalk = require('chalk');
const moment = require('moment');
const got = require('got');
const unzipper = require('unzipper');

const db = require('./db.js');
const debug = require('./utils/debug.js');

const fsp = fs.promises;

// Download data into temporary folder.
async function download() {
	debug.time('data-download', 'Downloading data');

	// Download and extract MNT data into temporary folder.
	await new Promise((resolve) => {
		got.stream('http://peatus.ee/gtfs/gtfs.zip')
			.pipe(unzipper.Parse())
			.pipe(stream.Transform({
				objectMode: true,
				transform(entry, e, cb) {
					entry.pipe(fs.createWriteStream(`tmp/${entry.path.split('.')[0]}.csv`)).on('finish', cb);
				}
			})).on('finish', resolve);
	});

	// Download and write Elron stop data into temporary folder.
	let data = 'name,lat,lng\n';
	for (const stop of JSON.parse((await got('https://elron.ee/api/v1/stops')).body).data) data += `${stop.peatus},${stop.latitude},${stop.longitude}\n`;
	await fsp.writeFile('tmp/elron.csv', data);

	debug.timeEnd('data-download', 'Downloaded data');
}

// Execute scripts in folder.
async function execute(path, msgIncomplete, msgComplete) {
	for (const file of await fsp.readdir(path)) {
		const name = file.split('.')[0];

		debug.time('data-prepare-' + name, msgIncomplete + ' ' + chalk.white(name));

		switch (file.split('.')[1]) {
			case 'sql':
				await db.query((await fsp.readFile(`${path}/${file}`)).toString());
				break;
			case 'js':
				await (require(`./${path}/${file}`))();
				break;
		}

		debug.timeEnd('data-prepare-' + name, msgComplete + ' ' + chalk.white(name));
	}
}

// Update data.
async function update() {
	try {
		let nextUpdate;

		try {
			await fsp.stat('tmp/update');
			nextUpdate = (await fsp.readFile('tmp/update')).toString();
		} catch {}

		// Update stale data.
		if (!nextUpdate || new Date(nextUpdate) <= new Date()) {
			debug.info('Starting data update');
			debug.time('data-update');

			await download();
			await execute('data/importers', 'Importing', 'Imported');
			await execute('data/processors', 'Generating', 'Generated');

			await fsp.writeFile('tmp/update', moment().add(1, 'day').hour(6).minute(0).second(0).toDate());
			debug.timeEnd('data-update', 'Data update completed');
		}
	} catch (ex) {
		debug.error('Failed to update data', ex);
	}
}

module.exports = {
	update
};
<commit_msg>Improve processing debug messages (api)<commit_after>const fs = require('fs');
const stream = require('stream');
const chalk = require('chalk');
const moment = require('moment');
const got = require('got');
const unzipper = require('unzipper');

const db = require('./db.js');
const debug = require('./utils/debug.js');

const fsp = fs.promises;

// Download data into temporary folder.
async function download() {
	debug.time('data-download', 'Downloading data');

	// Download and extract MNT data into temporary folder.
	await new Promise((resolve) => {
		got.stream('http://peatus.ee/gtfs/gtfs.zip')
			.pipe(unzipper.Parse())
			.pipe(stream.Transform({
				objectMode: true,
				transform(entry, e, cb) {
					entry.pipe(fs.createWriteStream(`tmp/${entry.path.split('.')[0]}.csv`)).on('finish', cb);
				}
			})).on('finish', resolve);
	});

	// Download and write Elron stop data into temporary folder.
	let data = 'name,lat,lng\n';
	for (const stop of JSON.parse((await got('https://elron.ee/api/v1/stops')).body).data) data += `${stop.peatus},${stop.latitude},${stop.longitude}\n`;
	await fsp.writeFile('tmp/elron.csv', data);

	debug.timeEnd('data-download', 'Downloaded data');
}

// Execute scripts in folder.
async function execute(path, msgIncomplete, msgComplete) {
	for (const file of await fsp.readdir(path)) {
		const name = file.split('.')[0];

		debug.time('data-prepare-' + name, msgIncomplete + ' ' + chalk.white(name.replace(/.*-/, '')));

		switch (file.split('.')[1]) {
			case 'sql':
				await db.query((await fsp.readFile(`${path}/${file}`)).toString());
				break;
			case 'js':
				await (require(`./${path}/${file}`))();
				break;
		}

		debug.timeEnd('data-prepare-' + name, msgComplete + ' ' + chalk.white(name.replace(/.*-/, '')));
	}
}

// Update data.
async function update() {
	try {
		let nextUpdate;

		try {
			await fsp.stat('tmp/update');
			nextUpdate = (await fsp.readFile('tmp/update')).toString();
		} catch {}

		// Update stale data.
		if (!nextUpdate || new Date(nextUpdate) <= new Date()) {
			debug.info('Starting data update');
			debug.time('data-update');

			await download();
			await execute('data/importers', 'Importing', 'Imported');
			await execute('data/processors', 'Processing', 'Generated');

			await fsp.writeFile('tmp/update', moment().add(1, 'day').hour(6).minute(0).second(0).toDate());
			debug.timeEnd('data-update', 'Data update completed');
		}
	} catch (ex) {
		debug.error('Failed to update data', ex);
	}
}

module.exports = {
	update
};
<|endoftext|>


<commit_before>const html = require('yo-yo')
const getFileTypeIcon = require('./getFileTypeIcon')
const onload = require('on-load')
const { checkIcon } = require('./icons')

let file
const meta = {}

module.exports = function fileCard (props) {
  file = props.fileCardFor ? props.files[props.fileCardFor] : false
  // const meta = {}

  const handleEnterKey = (ev) => {
    if (event.keyCode === 13) {
      props.done(meta, file.id)
    }
  }

  const tempStoreMeta = (ev) => {
    const value = ev.target.value
    const name = ev.target.dataset.name
    meta[name] = value
  }

  function renderMetaFields (file) {
    const metaFields = props.metaFields || []
    return metaFields.map((field) => {
      return html`<fieldset class="UppyDashboardFileCard-fieldset">
        ${field.name}
        <input class="UppyDashboardFileCard-input"
               type="text"
               data-name="${field.id}"
               value="${file.meta[field.id]}"
               placeholder="${field.placeholder || ''}"
               onkeyup=${tempStoreMeta} /></fieldset>`
    })
  }

  const fileCardEl = () => html`

Editing ${file.meta ? file.meta.name : file.name}

      <button class="UppyDashboardContent-back" type="button" title="Finish editing file"
              onclick=${() => props.done(meta, file.id)}>Done</button>

    ${props.fileCardFor
      ? html`

            ${file.preview
              ? html`<img alt="${file.name}" src="${file.preview}">`
              : html`

                ${getFileTypeIcon(file.type.general, file.type.specific).icon}
                <svg class="UppyDashboardItem-previewIconBg" width="72" height="93" viewBox="0 0 72 93"><g><path d="M24.08 5h38.922A2.997 2.997 0 0 1 66 8.003v74.994A2.997 2.997 0 0 1 63.004 86H8.996A2.998 2.998 0 0 1 6 83.01V22.234L24.08 5z" fill="#FFF"/><path d="M24 5L6 22.248h15.007A2.995 2.995 0 0 0 24 19.244V5z" fill="#E4E4E4"/></g></svg>

`
            }

            <fieldset class="UppyDashboardFileCard-fieldset">
              Name
              <input class="UppyDashboardFileCard-input" data-name="name" type="text" value="${file.meta.name}"
                     onkeyup=${tempStoreMeta} />
            </fieldset>
            ${renderMetaFields(file)}

`
      : null
    }

      <button class="UppyButton--circular UppyButton--blue UppyDashboardFileCard-done"
              type="button"
              title="Finish editing file"
              onclick=${() => props.done(meta, file.id)}>${checkIcon()}</button>

`

  return onload(html`<div>${fileCardEl()}</div>`,
    () => document.body.addEventListener('keyup', handleEnterKey),
    () => document.body.removeEventListener('keyup', handleEnterKey),
    `uppy${file.id}`
  )
}
<commit_msg>don’t use onload, because fileCard is actually always in DOM<commit_after>const html = require('yo-yo')
const getFileTypeIcon = require('./getFileTypeIcon')
const onload = require('on-load')
const { checkIcon } = require('./icons')

let file
const meta = {}

module.exports = function fileCard (props) {
  file = props.fileCardFor ? props.files[props.fileCardFor] : false

  const handleEnterKey = (ev) => {
    if (file && event.keyCode === 13) {
      props.done(meta, file.id)
    }
  }

  if (file) {
    document.body.addEventListener('keyup', handleEnterKey)
  } else {
    document.body.removeEventListener('keyup', handleEnterKey)
  }

  const tempStoreMeta = (ev) => {
    const value = ev.target.value
    const name = ev.target.dataset.name
    meta[name] = value
  }

  function renderMetaFields (file) {
    const metaFields = props.metaFields || []
    return metaFields.map((field) => {
      return html`<fieldset class="UppyDashboardFileCard-fieldset">
        ${field.name}
        <input class="UppyDashboardFileCard-input"
               type="text"
               data-name="${field.id}"
               value="${file.meta[field.id]}"
               placeholder="${field.placeholder || ''}"
               onkeyup=${tempStoreMeta} /></fieldset>`
    })
  }

  const fileCardEl = () => html`

Editing ${file.meta ? file.meta.name : file.name}

      <button class="UppyDashboardContent-back" type="button" title="Finish editing file"
              onclick=${() => props.done(meta, file.id)}>Done</button>

    ${props.fileCardFor
      ? html`

            ${file.preview
              ? html`<img alt="${file.name}" src="${file.preview}">`
              : html`

                ${getFileTypeIcon(file.type.general, file.type.specific).icon}
                <svg class="UppyDashboardItem-previewIconBg" width="72" height="93" viewBox="0 0 72 93"><g><path d="M24.08 5h38.922A2.997 2.997 0 0 1 66 8.003v74.994A2.997 2.997 0 0 1 63.004 86H8.996A2.998 2.998 0 0 1 6 83.01V22.234L24.08 5z" fill="#FFF"/><path d="M24 5L6 22.248h15.007A2.995 2.995 0 0 0 24 19.244V5z" fill="#E4E4E4"/></g></svg>

`
            }

            <fieldset class="UppyDashboardFileCard-fieldset">
              Name
              <input class="UppyDashboardFileCard-input" data-name="name" type="text" value="${file.meta.name}"
                     onkeyup=${tempStoreMeta} />
            </fieldset>
            ${renderMetaFields(file)}

`
      : null
    }

      <button class="UppyButton--circular UppyButton--blue UppyDashboardFileCard-done"
              type="button"
              title="Finish editing file"
              onclick=${() => props.done(meta, file.id)}>${checkIcon()}</button>

`

  return onload(html`<div>${fileCardEl()}</div>`,
    null,
    null,
    `uppy${file.id}`
  )
}
<|endoftext|>


<commit_before>/***
|''Name''|TiddlySpaceMembers|
|''Version''|0.6.0|
|''Description''|provides a UI for managing space members|
|''Status''|@@beta@@|
|''Source''|http://github.com/TiddlySpace/tiddlyspace/raw/master/src/plugins/TiddlySpaceMembers.js|
|''Requires''|TiddlySpaceConfig TiddlySpaceAdmin|
!Usage
<<TiddlySpaceMembers list>> provides list of members
<<TiddlySpaceMembers add>> creates a form to add new members.
!Code
***/
//{{{
(function($) {

var admin = config.macros.TiddlySpaceAdmin;
var formMaker = config.extensions.formMaker;
var macro = config.macros.TiddlySpaceMembers = {
	locale: {
		authAddError: "You must be a member to add members to this space.",
		authError: "list of members is only visible to members of space %0",
		listError: "error retrieving members for space %0: %1",
		submit: "Add member",
		delTooltip: "click to remove member",
		delPrompt: "Are you sure you want to remove member %0?",
		// we can also get an auth error when the user has no perms to
		// delete but we wouldn't see the interface
		delAuthError: "error removing %0 from %1: may not remove last member",
		delSpaceError: "error removing %0 from %1: space does not exist",
		sending: "please wait...",
		errors: {
			409: "user %0 does not exist"
		}
	},

	handler: function(place, macroName, params, wikifier, paramString, tiddler) {
		var space = config.extensions.tiddlyspace.currentSpace.name;
		var host = config.extensions.tiddlyweb.host;
		this.space = new tiddlyweb.Space(space, host); // XXX: singleton
		var mode = params[0];
		var args = paramString.parseParams("anon", null, true, false, false);
		var hideErrors = args.hideErrors ? true : false;
		var container;
		if(!readOnly) {
			if(mode == "add") {
				macro.generateForm(place);
			} else {
				container = $("
").appendTo(place);
				macro.refresh(container);
			}
		} else {
			var msg;
			if(mode == "add") {
				msg = this.locale.authAddError.format(this.space.name);
			} else {
				msg = this.locale.authError.format(this.space.name);
			}
			container = $("
").appendTo(place);
			if(!hideErrors) {
				this.notify(msg, container);
			}
		}
	},
	refresh: function(container) {
		var callback = function(data, status, xhr) {
			$(container).empty();
			macro.displayMembers(data, container);
		};
		var errback = function(xhr, error, exc) {
			var msg = xhr.status == 403 ? "authError" : "listError";
			msg = macro.locale[msg].format(macro.space.name, error);
			macro.notify(msg, container);
		};
		this.space.members().get(callback, errback);
	},
	displayMembers: function(members, container) {
		config.extensions.tiddlyweb.getStatus(function(status) {
			var items = $.map(members, function(member, i) {
				var uri = config.extensions.tiddlyspace.getHost(
					status.server_host, member);
				var link = $("").attr("href", uri).text(member);
				var btn = $('').
					text("x"). // TODO: i18n (use icon!?)
					attr("title", macro.locale.delTooltip).
					data("username", member).click(macro.onClick);
				return $("
").append(link).append(btn)[0];
			});
			$("
").addClass("spaceMembersList").append(items).appendTo(container);
		});
	},
	elements: [ admin.locale.username, admin.elements.username() ],
	generateForm: function(container) {
		return formMaker.make(container, macro.elements, macro.onSubmit, { locale: macro.locale });
	},
	onSubmit: function(ev, form) {
		var selector = "[name=username]";
		var input = $(form).find(selector);
		var username = input.val();
		var callback = function(data, status, xhr) {
			$(".spaceMembersList").each(function(i, el) {
				macro.refresh($(el.parentNode));
			});
			input.val("");
			formMaker.reset();
		};
		var errback = function(xhr, error, exc) {
			var options = {
				format: [ username ],
				selector: selector
			};
			formMaker.displayError(form, xhr.status, macro.locale.errors, options);
		};
		macro.space.members().add(username, callback, errback);
		return false;
	},
	onClick: function(ev) { // XXX: ambiguous; rename
		var btn = $(this);
		var username = btn.data("username");
		var msg = macro.locale.delPrompt.format(username);
		var callback = function(data, status, xhr) {
			if(username == config.extensions.tiddlyweb.username) { // assumes getStatus has completed
				readOnly = true;
				refreshDisplay();
			}
			var container = btn.closest("div");
			macro.refresh(container);
		};
		var errback = function(xhr, error, exc) {
			var msg = xhr.status == 403 ? "delAuthError" : "delSpaceError";
			displayMessage(macro.locale[msg].format(username, macro.space.name));
		};
		if(confirm(msg)) {
			macro.space.members().remove(username, callback, errback);
		}
	},
	notify: function(msg, container) {
		container.addClass("annotation").html(msg);
	}
};

})(jQuery);
//}}}
<commit_msg>updated version number<commit_after>/***
|''Name''|TiddlySpaceMembers|
|''Version''|0.6.1|
|''Description''|provides a UI for managing space members|
|''Status''|@@beta@@|
|''Source''|http://github.com/TiddlySpace/tiddlyspace/raw/master/src/plugins/TiddlySpaceMembers.js|
|''Requires''|TiddlySpaceConfig TiddlySpaceAdmin|
!Usage
<<TiddlySpaceMembers list>> provides list of members
<<TiddlySpaceMembers add>> creates a form to add new members.
!Code
***/
//{{{
(function($) {

var admin = config.macros.TiddlySpaceAdmin;
var formMaker = config.extensions.formMaker;
var macro = config.macros.TiddlySpaceMembers = {
	locale: {
		authAddError: "You must be a member to add members to this space.",
		authError: "list of members is only visible to members of space %0",
		listError: "error retrieving members for space %0: %1",
		submit: "Add member",
		delTooltip: "click to remove member",
		delPrompt: "Are you sure you want to remove member %0?",
		// we can also get an auth error when the user has no perms to
		// delete but we wouldn't see the interface
		delAuthError: "error removing %0 from %1: may not remove last member",
		delSpaceError: "error removing %0 from %1: space does not exist",
		sending: "please wait...",
		errors: {
			409: "user %0 does not exist"
		}
	},

	handler: function(place, macroName, params, wikifier, paramString, tiddler) {
		var space = config.extensions.tiddlyspace.currentSpace.name;
		var host = config.extensions.tiddlyweb.host;
		this.space = new tiddlyweb.Space(space, host); // XXX: singleton
		var mode = params[0];
		var args = paramString.parseParams("anon", null, true, false, false);
		var hideErrors = args.hideErrors ? true : false;
		var container;
		if(!readOnly) {
			if(mode == "add") {
				macro.generateForm(place);
			} else {
				container = $("
").appendTo(place);
				macro.refresh(container);
			}
		} else {
			var msg;
			if(mode == "add") {
				msg = this.locale.authAddError.format(this.space.name);
			} else {
				msg = this.locale.authError.format(this.space.name);
			}
			container = $("
").appendTo(place);
			if(!hideErrors) {
				this.notify(msg, container);
			}
		}
	},
	refresh: function(container) {
		var callback = function(data, status, xhr) {
			$(container).empty();
			macro.displayMembers(data, container);
		};
		var errback = function(xhr, error, exc) {
			var msg = xhr.status == 403 ? "authError" : "listError";
			msg = macro.locale[msg].format(macro.space.name, error);
			macro.notify(msg, container);
		};
		this.space.members().get(callback, errback);
	},
	displayMembers: function(members, container) {
		config.extensions.tiddlyweb.getStatus(function(status) {
			var items = $.map(members, function(member, i) {
				var uri = config.extensions.tiddlyspace.getHost(
					status.server_host, member);
				var link = $("").attr("href", uri).text(member);
				var btn = $('').
					text("x"). // TODO: i18n (use icon!?)
					attr("title", macro.locale.delTooltip).
					data("username", member).click(macro.onClick);
				return $("
").append(link).append(btn)[0];
			});
			$("
").addClass("spaceMembersList").append(items).appendTo(container);
		});
	},
	elements: [ admin.locale.username, admin.elements.username() ],
	generateForm: function(container) {
		return formMaker.make(container, macro.elements, macro.onSubmit, { locale: macro.locale });
	},
	onSubmit: function(ev, form) {
		var selector = "[name=username]";
		var input = $(form).find(selector);
		var username = input.val();
		var callback = function(data, status, xhr) {
			$(".spaceMembersList").each(function(i, el) {
				macro.refresh($(el.parentNode));
			});
			input.val("");
			formMaker.reset();
		};
		var errback = function(xhr, error, exc) {
			var options = {
				format: [ username ],
				selector: selector
			};
			formMaker.displayError(form, xhr.status, macro.locale.errors, options);
		};
		macro.space.members().add(username, callback, errback);
		return false;
	},
	onClick: function(ev) { // XXX: ambiguous; rename
		var btn = $(this);
		var username = btn.data("username");
		var msg = macro.locale.delPrompt.format(username);
		var callback = function(data, status, xhr) {
			if(username == config.extensions.tiddlyweb.username) { // assumes getStatus has completed
				readOnly = true;
				refreshDisplay();
			}
			var container = btn.closest("div");
			macro.refresh(container);
		};
		var errback = function(xhr, error, exc) {
			var msg = xhr.status == 403 ? "delAuthError" : "delSpaceError";
			displayMessage(macro.locale[msg].format(username, macro.space.name));
		};
		if(confirm(msg)) {
			macro.space.members().remove(username, callback, errback);
		}
	},
	notify: function(msg, container) {
		container.addClass("annotation").html(msg);
	}
};

})(jQuery);
//}}}
<|endoftext|>


<commit_before>var _ = require("lodash");
var ipaddr = require('ipaddr.js');
var moment = require('moment');

/// Packaged Policies
var defaultPolicy = require("./policies/default");
var newPolicy = require("./policies/new");
var newMember = require("./policies/member");
///

var lookup = function(ip) {
    /* Lookup function */
    var _this = this;
    // Expand ipv6 address
    ip = (ipaddr.parse(ip) === "ipv6")?ipaddr.parse(ip).toNormalizedString():ip;
    // Check if ip-address is invalid (accepts both v4 and v6 ips)
    if(!ipaddr.isValid(ip)) throw new Error("Invalid ip address!");

    // Sort by priority
    var lists = _.sortBy(_this.policy.lists, function(item){ return -item.priority; });

    // Define lookup variable
    var lookup = undefined;

    // Go through each list in order
    _.each(lists, function(list) {
        // If * is true add ip to list
        if((list['*'])&&(!list.members[ip])) list.members[ip] = newMember.create();
        // Lookup ip (probably not the fastest method)
        if(list.members[ip]) {
            // Assign location and rule to lookup object
            lookup = { location: list.members[ip], rule: _this.policy.rules[list.name], ip: ip };
            // break the loop
            return false;
        }else if(_this.policy.rules[list.name].whitelist === true) {
            // If list is a whitelist deny subsequent addresses
            // Assign blocking rule
            lookup = { rule: { block: true } };
            // break the loop
            return false;
        }
    });

    return lookup;
};

var admit = function(lookup) {
    /* Admission function */
    var _this = this;

    // Check if blocked
    if(lookup.rule.block) {
        // Emit denied event
        _this.emit("denied", lookup.ip, { blocked: true });
        return false;
    }

    /* Rate limiting function */

    var rateRule = lookup.rule.rate || {};
    var rateTotal = { d:0, h:0, m:0, s:0 };

    // If any rates are set to 0
    if((rateRule.d === 0) || (rateRule.h === 0) || (rateRule.m === 0) || (rateRule.s === 0)) {
        // Emit denied event
        _this.emit("denied", lookup.ip, { rule: rateRule, total: rateTotal });
        return false;
    }

    // Prevent computation if rateRule is undefined
    if(rateRule) {
        // Foreach access granted time
        _.each(lookup.location.rate, function(accessTime, key) {
            if((rateRule.d) && (moment(accessTime).diff(moment(), 'days') >= 0 )) rateTotal.d += 1;
                else if (rateRule.d) lookup.location.rate.splice(key, 1); // Drop accessTime
            if((rateRule.h) && (moment(accessTime).diff(moment(), 'hours') >= 0 )) rateTotal.h += 1;
                else if ((rateRule.h) && (!rateRule.d)) lookup.location.rate.splice(key, 1); // Drop accessTime
            if((rateRule.m) && (moment(accessTime).diff(moment(), 'minutes') >= 0 )) rateTotal.m += 1;
                else if ((rateRule.m) && (!rateRule.h) && (!rateRule.d)) lookup.location.rate.splice(key, 1); // Drop accessTime
            if((rateRule.s) && (moment(accessTime).diff(moment(), 'seconds') >= 0 )) rateTotal.s += 1;
                else if ((rateRule.s) && (!rateRule.m) && (!rateRule.h) && (!rateRule.d)) lookup.location.rate.splice(key, 1); // Drop accessTime
        });

        // If rate exceeds the limit
        if((rateRule.d < rateTotal.d) || (rateRule.h < rateTotal.h) || (rateRule.m < rateTotal.m) || (rateRule.s < rateTotal.s)) {
            // Emit denied event
            _this.emit("denied", lookup.ip, { rule: rateRule, total: rateTotal });
            return false;
        }
    }

    // Otherwise admit ip
    _this.emit("admitted", lookup.ip, { rule: rateRule, total: rateTotal });
    return true;
}

var push = function(lookup) {
    lookup.location.rate.push(moment().toISOString());
}

var auto = function(ip) {
    var _lookup = lookup.apply(this, [ip]);
    if(!_lookup) return false;
    if(admit.apply(this, [_lookup])) push(_lookup);

    return admit.apply(this, [_lookup]);
}

module.exports = {
    lookup: lookup,
    admit: admit,
    push: push,
    auto: auto
}
<commit_msg>Removed Oldfile<commit_after><|endoftext|>