<commit_before>/* globals describe, beforeEach, afterEach, $fixture, qq, assert, it, qqtest, helpme, purl, Q */
describe("uploader.basic.api.js", function () {
    "use strict";

    var $uploader, fineuploader;

    beforeEach(function () {
        $fixture.append("

");
        $uploader = $fixture.find("#fine-uploader");
    });

    it("resets multiple buttons to their original states", function () {
        var $btn1 = $fixture.appendTo("

"),
            $btn2 = $fixture.appendTo("

"),
            i, button;

        var fineuploader = new qq.FineUploaderBasic({
            element: $uploader[0],
            extraButtons: [
                {
                    element: $btn1[0],
                    multiple: false,
                    accept: ""
                },
                {
                    element: $btn2[0],
                    multiple: false,
                    accept: ""
                }
            ]
        });

        for (i = 0; i < fineuploader._buttons.length - 1; i++) {
            button = fineuploader._buttons[i];
            button.setMultiple(true);
            button.setAcceptFiles("audio/*");
        }

        fineuploader.reset();

        if (qq.supportedFeatures.ajaxUploading) {
            for (i = 0; i < fineuploader._buttons.length - 1; i++) {
                var input = button.getInput();
                button = fineuploader._buttons[i];
                assert.ok(!input.hasAttribute("multiple"));
                assert.ok(!input.hasAttribute("accept"));
            }
        }
    });

    describe("formatFileName", function () {

        beforeEach(function () {
            fineuploader = new qq.FineUploaderBasic({
                element: $uploader[0]
            });
        });

        it("shortens a long (> 33 chars) filename", function () {
            var filename = "EWDPYZFAMDDOLNQEJXVUEWDPYZFAMDDOLN";
            var filename_fmt = fineuploader._options.formatFileName(filename);
            assert.equal(filename_fmt,
                "EWDPYZFAMDDOLNQEJXV...EWDPYZFAMDDOLN",
                "expect filename to be shortened");
        });

        it("refuses to shorten a short (<= 33 chars) filename", function () {
            var filename = "abcdefg";
            var filename_fmt = fineuploader._options.formatFileName(filename);
            assert.equal(filename_fmt,
                "abcdefg",
                "expect filename to NOT be shortened");
        });
    });

    describe("setParams", function () {

        beforeEach(function () {
            fineuploader = new qq.FineUploaderBasic({
                element: $uploader[0]
            });
        });

        it("resets", function () {
            var params = {"hello": "world"};
            fineuploader.setParams(params, "foo");
            assert.deepEqual(fineuploader._paramsStore.get("foo"), params,
                "the request parameters should be set");
            fineuploader._paramsStore.reset();
            assert.deepEqual(fineuploader._paramsStore.get("foo"), {},
                "the request parameters should be reset");
        });

        it("allows changing parameters for a specific file id", function () {
            var params = {"hello": "world"};
            fineuploader.setParams(params, "foo");
            assert.deepEqual(fineuploader._paramsStore.get("foo"), params,
                "the request parameters should be set");

        });

        it("allows changing paramters for all files", function () {
            var params = {"hello": "world"};
            fineuploader.setParams(params);
            assert.deepEqual(fineuploader._paramsStore.get(), params,
                "the request parameters should be set");
        });

    });

    describe("setEndpoint", function () {
        var defaultEndpoint = "a/b/c";

        beforeEach(function () {

            fineuploader = new qq.FineUploaderBasic({
                element: $uploader[0],
                request: {
                    endpoint: defaultEndpoint
                }
            });
        });

        it("resets", function () {
            var endpoint = "/endpoint";
            fineuploader.setEndpoint(endpoint, 0);
            var ep = fineuploader._endpointStore.get(0);
            assert.deepEqual(ep,
                endpoint,
                "the endpoint should be set");
            fineuploader._endpointStore.reset();
            ep = fineuploader._endpointStore.get(0);
            assert.deepEqual(ep, fineuploader._options.request.endpoint, "the endpoint should be reset");
        });

        it("set a new endpoint", function () {
            var endpoint = "/endpoint";
            fineuploader.setEndpoint(endpoint, 0);
            var ep = fineuploader._endpointStore.get(0);

            assert.deepEqual(ep, endpoint, "the endpoint should be set");

            qq.each(fineuploader._extraButtonSpecs, function(id, spec) {
                assert.equal(spec.endpoint, defaultEndpoint, "endpoint for extra button was changed unexpectedly!");
            });
        });
    });

    describe("_isAllowedExtension", function() {
        beforeEach(function () {
            fineuploader = new qq.FineUploaderBasic();
        });

        it("allows files if no restrictions are in place", function() {
            var allowedExtensions = [];

            assert.ok(fineuploader._isAllowedExtension(allowedExtensions, "foo.bar"));
            assert.ok(fineuploader._isAllowedExtension(allowedExtensions, "foo.bar.bat"));
            assert.ok(fineuploader._isAllowedExtension(allowedExtensions, "foo"));
        });

        it("doesn't choke if allowed extensions are not valid (i.e. not strings)", function() {
            var allowedExtensions = [{}];

            assert.ok(!fineuploader._isAllowedExtension(allowedExtensions, "foo.bar"));
            assert.ok(!fineuploader._isAllowedExtension(allowedExtensions, "foo.bar.bat"));
            assert.ok(!fineuploader._isAllowedExtension(allowedExtensions, "foo"));
        });

        it("only allows valid extensions", function() {
            var allowedExtensions = ["bar", "exe", "png"];

            assert.ok(fineuploader._isAllowedExtension(allowedExtensions, "foo.bar"));
            assert.ok(fineuploader._isAllowedExtension(allowedExtensions, "foo.fee.exe"));
            assert.ok(fineuploader._isAllowedExtension(allowedExtensions, "png.png"));
            assert.ok(!fineuploader._isAllowedExtension(allowedExtensions, "foo.bar.bat"));
            assert.ok(!fineuploader._isAllowedExtension(allowedExtensions, "foo"));
            assert.ok(!fineuploader._isAllowedExtension(allowedExtensions, "png"));
        });
    });

    describe("_handleCheckedCallback", function() {
        beforeEach(function () {
            fineuploader = new qq.FineUploaderBasic();
        });

        it("handles successful non-promissory callbacks (undefined return value)", function() {
            var callback = function() {},
                spec = {
                    callback: callback,
                    onSuccess: function(callbackRetVal) {
                        assert.deepEqual(callbackRetVal, undefined);
                    },
                    onFailure: function() {
                        assert.failure();
                    }
                };

            fineuploader._handleCheckedCallback(spec);
        });

        it("handles successful non-promissory callbacks (defined return value)", function() {
            var callback = function() {
                    return "foobar";
                },
                spec = {
                    callback: callback,
                    onSuccess: function(callbackRetVal) {
                        assert.deepEqual(callbackRetVal, "foobar");
                    }
                };

            assert.deepEqual(fineuploader._handleCheckedCallback(spec), "foobar");
        });

        it("handles failed non-promissory callbacks (defined onFailure)", function(done) {
            var callback = function() {
                    return false;
                },
                spec = {
                    callback: callback,
                    onSuccess: function() {
                        assert.fail();
                        done();
                    },
                    onFailure: function() {
                        done();
                    }
                };

            fineuploader._handleCheckedCallback(spec);
        });

        it("handles failed non-promissory callbacks (undefined onFailure)", function(done) {
            var callback = function() {
                    return false;
                },
                spec = {
                    callback: callback,
                    onSuccess: function() {
                        assert.fail();
                    }
                };

            fineuploader._handleCheckedCallback(spec);
            done();
        });

        describe("handles successful promissory callbacks", function() {
            function runTest(callback, done) {
                var spec = {
                    callback: callback,
                    onSuccess: function(passedVal) {
                        assert.deepEqual(passedVal, "foobar");
                        done();
                    },
                    onFailure: function() {
                        assert.fail();
                        done();
                    }
                };

                fineuploader._handleCheckedCallback(spec);
            }

            it ("qq.Promise", function(done) {
                var callback = function() {
                        var promise = new qq.Promise();

                        setTimeout(function() {
                            promise.success("foobar");
                        }, 100);

                        return promise;
                    };

                runTest(callback, done);
            });

            it ("Q.js", function(done) {
                var callback = function() {
                        return Q.Promise(function(resolve) {
                            setTimeout(function() {
                                resolve("foobar");
                            }, 100);
                        });
                    };

                runTest(callback, done);
            });
        });

        describe("handles failed promissory callbacks", function() {
            function runTest(callback, done) {
                var spec = {
                    callback: callback,
                    onSuccess: function() {
                        assert.fail();
                        done();
                    },
                    onFailure: function() {
                        done();
                    }
                };

                fineuploader._handleCheckedCallback(spec);
            }

            it ("qq.Promise", function(done) {
                var callback = function() {
                        var promise = new qq.Promise();

                        setTimeout(function() {
                            promise.failure();
                        }, 100);

                        return promise;
                    };

                runTest(callback, done);
            });

            it ("Q.js", function(done) {
                var callback = function() {
                    return Q.Promise(function (resolve, reject) {
                        setTimeout(function () {
                            reject();
                        }, 100);
                    });
                };

                runTest(callback, done);
            });
        });

        it("does auto retry if upload is not paused", function() {
            fineuploader = new qq.FineUploaderBasic({
                element: $uploader[0],
                retry: {
                    enableAuto: true
                }
            });

            fineuploader._uploadData = {
                retrieve: function() {
                    return {
                        status: qq.status.UPLOADING
                    };
                }
            };

            assert.ok(fineuploader._shouldAutoRetry(0));
        });

        it("does not auto retry if upload is paused", function() {
            fineuploader = new qq.FineUploaderBasic({
                element: $uploader[0],
                retry: {
                    enableAuto: true
                }
            });

            fineuploader._uploadData = {
                retrieve: function() {
                    return {
                        status: qq.status.PAUSED
                    };
                }
            };

            assert.ok(!fineuploader._shouldAutoRetry(0));
        });
    });

    describe("getRemainingAllowedItems", function() {
        var uploader;

        function setupUploader(allowedItems) {
            uploader = new qq.FineUploaderBasic({
                validation: {
                    itemLimit: allowedItems
                }
            });
        }

        it("reports the correct number of remaining allowed items w/out item limit", function() {
            setupUploader(0);
            uploader._netUploadedOrQueued = 3;

            assert.equal(uploader.getRemainingAllowedItems(), null);
        });

        it("reports the correct number of remaining items w/ an item limit", function() {
            setupUploader(3);
            uploader._netUploadedOrQueued = 2;

            assert.equal(uploader.getRemainingAllowedItems(), 1);
        });

        it("allows the itemLimit to be adjusted via the API", function() {
            setupUploader(3);
            uploader._netUploadedOrQueued = 2;

            uploader.setItemLimit(5);

            assert.equal(uploader.getRemainingAllowedItems(), 3);
        });
    });

    describe("_createStore", function() {
        var uploader = new qq.FineUploaderBasic({});

        it("handles non-object stores properly", function() {
            var initVal = "foo",
                store = uploader._createStore(initVal);

            assert.equal(store.get(100), initVal);
            assert.equal(store.get(), initVal);

            store.set("bar", 2);
            store.set("three", 3);
            assert.equal(store.get(2), "bar");
            assert.equal(store.get(3), "three");
            assert.equal(store.get(100), initVal);
            assert.equal(store.get(), initVal);

            store.remove(3);
            assert.equal(store.get(2), "bar");
            assert.equal(store.get(3), initVal);
            assert.equal(store.get(100), initVal);
            assert.equal(store.get(), initVal);

            store.set("foobar");
            assert.equal(store.get(2), "foobar");
            assert.equal(store.get(3), "foobar");
            assert.equal(store.get(100), "foobar");
            assert.equal(store.get(), "foobar");

            store.reset();
            assert.equal(store.get(2), initVal);
            assert.equal(store.get(3), initVal);
            assert.equal(store.get(100), initVal);
            assert.equal(store.get(), initVal);
        });

        it("handles object stores properly", function() {
            var initVal = {foo: "bar"},
                a = {a: "a"},
                two = {two: "two"},
                three = {three: "three"},
                store = uploader._createStore(initVal);

            assert.deepEqual(store.get(100), initVal);
            assert.deepEqual(store.get(), initVal);

            store.set(two, 2);
            store.set(three, 3);
            assert.deepEqual(store.get(2), two);
            assert.deepEqual(store.get(3), three);
            assert.deepEqual(store.get(100), initVal);
            assert.deepEqual(store.get(), initVal);

            three.test = "123";
            assert.notDeepEqual(store.get(3), three);

            store.remove(3);
            assert.deepEqual(store.get(2), two);
            assert.deepEqual(store.get(3), initVal);
            assert.deepEqual(store.get(100), initVal);
            assert.deepEqual(store.get(), initVal);

            store.set(a);
            assert.deepEqual(store.get(2), a);
            assert.deepEqual(store.get(3), a);
            assert.deepEqual(store.get(100), a);
            assert.deepEqual(store.get(), a);

            a.test = "123";
            assert.notDeepEqual(store.get(2), a);

            store.reset();
            assert.deepEqual(store.get(2), initVal);
            assert.deepEqual(store.get(3), initVal);
            assert.deepEqual(store.get(100), initVal);
            assert.deepEqual(store.get(), initVal);
        });
    });

    describe("_handleNewFile", function() {
        it("ignores size property if passing a file input", function() {
            var uploader = new qq.FineUploaderBasic({}),
                fileInput = document.createElement("input");

            uploader._customNewFileHandler = function(actualFile, name, uuid, size) {
                assert.equal(size, -1);
            };

            fileInput.type = "file";

            uploader._handleNewFile(fileInput, 0, []);
        });
    });
});
<commit_msg>test(ui-updates): remove formatFileName test<commit_after>/* globals describe, beforeEach, afterEach, $fixture, qq, assert, it, qqtest, helpme, purl, Q */
describe("uploader.basic.api.js", function () {
    "use strict";

    var $uploader, fineuploader;

    beforeEach(function () {
        $fixture.append("

");
        $uploader = $fixture.find("#fine-uploader");
    });

    it("resets multiple buttons to their original states", function () {
        var $btn1 = $fixture.appendTo("

"),
            $btn2 = $fixture.appendTo("

"),
            i, button;

        var fineuploader = new qq.FineUploaderBasic({
            element: $uploader[0],
            extraButtons: [
                {
                    element: $btn1[0],
                    multiple: false,
                    accept: ""
                },
                {
                    element: $btn2[0],
                    multiple: false,
                    accept: ""
                }
            ]
        });

        for (i = 0; i < fineuploader._buttons.length - 1; i++) {
            button = fineuploader._buttons[i];
            button.setMultiple(true);
            button.setAcceptFiles("audio/*");
        }

        fineuploader.reset();

        if (qq.supportedFeatures.ajaxUploading) {
            for (i = 0; i < fineuploader._buttons.length - 1; i++) {
                var input = button.getInput();
                button = fineuploader._buttons[i];
                assert.ok(!input.hasAttribute("multiple"));
                assert.ok(!input.hasAttribute("accept"));
            }
        }
    });

    describe("setParams", function () {

        beforeEach(function () {
            fineuploader = new qq.FineUploaderBasic({
                element: $uploader[0]
            });
        });

        it("resets", function () {
            var params = {"hello": "world"};
            fineuploader.setParams(params, "foo");
            assert.deepEqual(fineuploader._paramsStore.get("foo"), params,
                "the request parameters should be set");
            fineuploader._paramsStore.reset();
            assert.deepEqual(fineuploader._paramsStore.get("foo"), {},
                "the request parameters should be reset");
        });

        it("allows changing parameters for a specific file id", function () {
            var params = {"hello": "world"};
            fineuploader.setParams(params, "foo");
            assert.deepEqual(fineuploader._paramsStore.get("foo"), params,
                "the request parameters should be set");

        });

        it("allows changing paramters for all files", function () {
            var params = {"hello": "world"};
            fineuploader.setParams(params);
            assert.deepEqual(fineuploader._paramsStore.get(), params,
                "the request parameters should be set");
        });

    });

    describe("setEndpoint", function () {
        var defaultEndpoint = "a/b/c";

        beforeEach(function () {

            fineuploader = new qq.FineUploaderBasic({
                element: $uploader[0],
                request: {
                    endpoint: defaultEndpoint
                }
            });
        });

        it("resets", function () {
            var endpoint = "/endpoint";
            fineuploader.setEndpoint(endpoint, 0);
            var ep = fineuploader._endpointStore.get(0);
            assert.deepEqual(ep,
                endpoint,
                "the endpoint should be set");
            fineuploader._endpointStore.reset();
            ep = fineuploader._endpointStore.get(0);
            assert.deepEqual(ep, fineuploader._options.request.endpoint, "the endpoint should be reset");
        });

        it("set a new endpoint", function () {
            var endpoint = "/endpoint";
            fineuploader.setEndpoint(endpoint, 0);
            var ep = fineuploader._endpointStore.get(0);

            assert.deepEqual(ep, endpoint, "the endpoint should be set");

            qq.each(fineuploader._extraButtonSpecs, function(id, spec) {
                assert.equal(spec.endpoint, defaultEndpoint, "endpoint for extra button was changed unexpectedly!");
            });
        });
    });

    describe("_isAllowedExtension", function() {
        beforeEach(function () {
            fineuploader = new qq.FineUploaderBasic();
        });

        it("allows files if no restrictions are in place", function() {
            var allowedExtensions = [];

            assert.ok(fineuploader._isAllowedExtension(allowedExtensions, "foo.bar"));
            assert.ok(fineuploader._isAllowedExtension(allowedExtensions, "foo.bar.bat"));
            assert.ok(fineuploader._isAllowedExtension(allowedExtensions, "foo"));
        });

        it("doesn't choke if allowed extensions are not valid (i.e. not strings)", function() {
            var allowedExtensions = [{}];

            assert.ok(!fineuploader._isAllowedExtension(allowedExtensions, "foo.bar"));
            assert.ok(!fineuploader._isAllowedExtension(allowedExtensions, "foo.bar.bat"));
            assert.ok(!fineuploader._isAllowedExtension(allowedExtensions, "foo"));
        });

        it("only allows valid extensions", function() {
            var allowedExtensions = ["bar", "exe", "png"];

            assert.ok(fineuploader._isAllowedExtension(allowedExtensions, "foo.bar"));
            assert.ok(fineuploader._isAllowedExtension(allowedExtensions, "foo.fee.exe"));
            assert.ok(fineuploader._isAllowedExtension(allowedExtensions, "png.png"));
            assert.ok(!fineuploader._isAllowedExtension(allowedExtensions, "foo.bar.bat"));
            assert.ok(!fineuploader._isAllowedExtension(allowedExtensions, "foo"));
            assert.ok(!fineuploader._isAllowedExtension(allowedExtensions, "png"));
        });
    });

    describe("_handleCheckedCallback", function() {
        beforeEach(function () {
            fineuploader = new qq.FineUploaderBasic();
        });

        it("handles successful non-promissory callbacks (undefined return value)", function() {
            var callback = function() {},
                spec = {
                    callback: callback,
                    onSuccess: function(callbackRetVal) {
                        assert.deepEqual(callbackRetVal, undefined);
                    },
                    onFailure: function() {
                        assert.failure();
                    }
                };

            fineuploader._handleCheckedCallback(spec);
        });

        it("handles successful non-promissory callbacks (defined return value)", function() {
            var callback = function() {
                    return "foobar";
                },
                spec = {
                    callback: callback,
                    onSuccess: function(callbackRetVal) {
                        assert.deepEqual(callbackRetVal, "foobar");
                    }
                };

            assert.deepEqual(fineuploader._handleCheckedCallback(spec), "foobar");
        });

        it("handles failed non-promissory callbacks (defined onFailure)", function(done) {
            var callback = function() {
                    return false;
                },
                spec = {
                    callback: callback,
                    onSuccess: function() {
                        assert.fail();
                        done();
                    },
                    onFailure: function() {
                        done();
                    }
                };

            fineuploader._handleCheckedCallback(spec);
        });

        it("handles failed non-promissory callbacks (undefined onFailure)", function(done) {
            var callback = function() {
                    return false;
                },
                spec = {
                    callback: callback,
                    onSuccess: function() {
                        assert.fail();
                    }
                };

            fineuploader._handleCheckedCallback(spec);
            done();
        });

        describe("handles successful promissory callbacks", function() {
            function runTest(callback, done) {
                var spec = {
                    callback: callback,
                    onSuccess: function(passedVal) {
                        assert.deepEqual(passedVal, "foobar");
                        done();
                    },
                    onFailure: function() {
                        assert.fail();
                        done();
                    }
                };

                fineuploader._handleCheckedCallback(spec);
            }

            it ("qq.Promise", function(done) {
                var callback = function() {
                        var promise = new qq.Promise();

                        setTimeout(function() {
                            promise.success("foobar");
                        }, 100);

                        return promise;
                    };

                runTest(callback, done);
            });

            it ("Q.js", function(done) {
                var callback = function() {
                        return Q.Promise(function(resolve) {
                            setTimeout(function() {
                                resolve("foobar");
                            }, 100);
                        });
                    };

                runTest(callback, done);
            });
        });

        describe("handles failed promissory callbacks", function() {
            function runTest(callback, done) {
                var spec = {
                    callback: callback,
                    onSuccess: function() {
                        assert.fail();
                        done();
                    },
                    onFailure: function() {
                        done();
                    }
                };

                fineuploader._handleCheckedCallback(spec);
            }

            it ("qq.Promise", function(done) {
                var callback = function() {
                        var promise = new qq.Promise();

                        setTimeout(function() {
                            promise.failure();
                        }, 100);

                        return promise;
                    };

                runTest(callback, done);
            });

            it ("Q.js", function(done) {
                var callback = function() {
                    return Q.Promise(function (resolve, reject) {
                        setTimeout(function () {
                            reject();
                        }, 100);
                    });
                };

                runTest(callback, done);
            });
        });

        it("does auto retry if upload is not paused", function() {
            fineuploader = new qq.FineUploaderBasic({
                element: $uploader[0],
                retry: {
                    enableAuto: true
                }
            });

            fineuploader._uploadData = {
                retrieve: function() {
                    return {
                        status: qq.status.UPLOADING
                    };
                }
            };

            assert.ok(fineuploader._shouldAutoRetry(0));
        });

        it("does not auto retry if upload is paused", function() {
            fineuploader = new qq.FineUploaderBasic({
                element: $uploader[0],
                retry: {
                    enableAuto: true
                }
            });

            fineuploader._uploadData = {
                retrieve: function() {
                    return {
                        status: qq.status.PAUSED
                    };
                }
            };

            assert.ok(!fineuploader._shouldAutoRetry(0));
        });
    });

    describe("getRemainingAllowedItems", function() {
        var uploader;

        function setupUploader(allowedItems) {
            uploader = new qq.FineUploaderBasic({
                validation: {
                    itemLimit: allowedItems
                }
            });
        }

        it("reports the correct number of remaining allowed items w/out item limit", function() {
            setupUploader(0);
            uploader._netUploadedOrQueued = 3;

            assert.equal(uploader.getRemainingAllowedItems(), null);
        });

        it("reports the correct number of remaining items w/ an item limit", function() {
            setupUploader(3);
            uploader._netUploadedOrQueued = 2;

            assert.equal(uploader.getRemainingAllowedItems(), 1);
        });

        it("allows the itemLimit to be adjusted via the API", function() {
            setupUploader(3);
            uploader._netUploadedOrQueued = 2;

            uploader.setItemLimit(5);

            assert.equal(uploader.getRemainingAllowedItems(), 3);
        });
    });

    describe("_createStore", function() {
        var uploader = new qq.FineUploaderBasic({});

        it("handles non-object stores properly", function() {
            var initVal = "foo",
                store = uploader._createStore(initVal);

            assert.equal(store.get(100), initVal);
            assert.equal(store.get(), initVal);

            store.set("bar", 2);
            store.set("three", 3);
            assert.equal(store.get(2), "bar");
            assert.equal(store.get(3), "three");
            assert.equal(store.get(100), initVal);
            assert.equal(store.get(), initVal);

            store.remove(3);
            assert.equal(store.get(2), "bar");
            assert.equal(store.get(3), initVal);
            assert.equal(store.get(100), initVal);
            assert.equal(store.get(), initVal);

            store.set("foobar");
            assert.equal(store.get(2), "foobar");
            assert.equal(store.get(3), "foobar");
            assert.equal(store.get(100), "foobar");
            assert.equal(store.get(), "foobar");

            store.reset();
            assert.equal(store.get(2), initVal);
            assert.equal(store.get(3), initVal);
            assert.equal(store.get(100), initVal);
            assert.equal(store.get(), initVal);
        });

        it("handles object stores properly", function() {
            var initVal = {foo: "bar"},
                a = {a: "a"},
                two = {two: "two"},
                three = {three: "three"},
                store = uploader._createStore(initVal);

            assert.deepEqual(store.get(100), initVal);
            assert.deepEqual(store.get(), initVal);

            store.set(two, 2);
            store.set(three, 3);
            assert.deepEqual(store.get(2), two);
            assert.deepEqual(store.get(3), three);
            assert.deepEqual(store.get(100), initVal);
            assert.deepEqual(store.get(), initVal);

            three.test = "123";
            assert.notDeepEqual(store.get(3), three);

            store.remove(3);
            assert.deepEqual(store.get(2), two);
            assert.deepEqual(store.get(3), initVal);
            assert.deepEqual(store.get(100), initVal);
            assert.deepEqual(store.get(), initVal);

            store.set(a);
            assert.deepEqual(store.get(2), a);
            assert.deepEqual(store.get(3), a);
            assert.deepEqual(store.get(100), a);
            assert.deepEqual(store.get(), a);

            a.test = "123";
            assert.notDeepEqual(store.get(2), a);

            store.reset();
            assert.deepEqual(store.get(2), initVal);
            assert.deepEqual(store.get(3), initVal);
            assert.deepEqual(store.get(100), initVal);
            assert.deepEqual(store.get(), initVal);
        });
    });

    describe("_handleNewFile", function() {
        it("ignores size property if passing a file input", function() {
            var uploader = new qq.FineUploaderBasic({}),
                fileInput = document.createElement("input");

            uploader._customNewFileHandler = function(actualFile, name, uuid, size) {
                assert.equal(size, -1);
            };

            fileInput.type = "file";

            uploader._handleNewFile(fileInput, 0, []);
        });
    });
});
<|endoftext|>


<commit_before>var helpers = require('../helpers');
var importData = require('./import_data');
var importPoints = require('./import_points_gz');
var importPolygonEgyptZip = require('./egypt_polygon_200_geojson');
var twoZippedShapesZipError = require('./two_zipped_geojson.error.zip');
var shapefileMissingPrjZip = require('./shapefile_missing_prj_zip');
var rasterEcwZip = require('./raster_ecw_200_zip');
var geom_zPointsShapeFileZip = require('./raster_ecw_200_zip');

describe.only('Upload data', function () {

    before(function(done) { helpers.create_user(done); });
    after(function(done) { helpers.delete_user(done); });

    importData();
    importPoints();
    importPolygonEgyptZip();
    twoZippedShapesZipError();
    shapefileMissingPrjZip();
    rasterEcwZip();
    geom_zPointsShapeFileZip();
});
<commit_msg>clean core test file<commit_after>var helpers = require('../helpers');
var importData = require('./import_data');
var importPolygonEgyptZip = require('./egypt_polygon_200_geojson');
var twoZippedShapesZipError = require('./two_zipped_geojson.error.zip');
var shapefileMissingPrjZip = require('./shapefile_missing_prj_zip');
var rasterEcwZip = require('./raster_ecw_200_zip');
var geom_zPointsShapeFileZip = require('./raster_ecw_200_zip');

describe.only('Upload data', function () {

    before(function(done) { helpers.create_user(done); });
    after(function(done) { helpers.delete_user(done); });

    importData();
    importPolygonEgyptZip();
    twoZippedShapesZipError();
    shapefileMissingPrjZip();
    rasterEcwZip();
    geom_zPointsShapeFileZip();
});
<|endoftext|>


<commit_before>
exports.seed = function(knex, Promise) {
  // Deletes ALL existing entries
  return knex('blogs').del()
    .then(function () {
      return Promise.all([
        // Inserts seed entries
        knex('blogs').insert({
          id: 99999,
          category: 'EDA culture',
          title: 'C1 - First Reflections',
          content: {
            "title": "I'm taking the opportunity, on this fine, sunny Friday morning to stay inside and write this, my first ever blog post. These are just a few thoughts I have about EDA so far at the start of phase-0, with the lovely Nikau cohort.",
            "questions": ["What's your take on the DBC/EDA (Dev Bootcamp/Enspiral Dev Academy) experience?", "What are your impressions?"],
            "answers": ["To sum it up very simply, it seems to be a very community-centric type of system, not unlike a good (non-toxic) gaming community. Everyone will have their own skills and experiences to bring to the table and their own goals and motivations to work towards. However, I get the sense that, at least from what I got from my own cohort so far, we're all in it for the same reason at the end of the day. We're here to learn and we can lean on each other when it comes down to building our skills.", "I'm in love with the system already. It actually hits very close to home, I think. As a gamer, having been part of several gaming communities, I've drawn a few comparisons between EDA and the communities I've experienced. While the goal in gaming is mainly to have fun (unless you're that type of person... XD), part of the experience is learning the rules of a game, testing out new things and developing skills that are useful within the game world. EDA, I feel, seems to build a community where fun, experimentation and skill development are simply applied to the real world, rather than a virtual one."]
          }
        }),
        knex('blogs').insert({
          id: 99998,
          category: 'EDA culture',
          title: 'C1 - Time and Habits',
          content: {
            "title": "Here's my second post. Hope this looks okay. @.@",
            "questions": ["Which timebox and habits techniques did you try?"],
            "answers": ["I've managed to stumble into the Growth Mindset on accident (or maybe not?). I've had success jumping into phase-0 with this in mind and have been playing around with resources and tools ever since I applied. (it's really just treating study like play time) I'm also planning out the future in increments.  The Toggl timer in conjunction with the Pomodoro technique was another one of those techniques that I tried out."]
          }
        }),
        knex('blogs').insert({
          id: 99997,
          category: 'EDA culture',
          title: 'C2 - Emotional Intelligence',
          content: {
            "title": "EQ > IQ? It's not really news to me now.",
            "questions": ["What learnings did you take from the chapter?"],
            "answers": ["That we really need to rethink how we define intelligence to be inclusive of factors beyond intellect and that the world seems to be getting less monochrome, so to speak.
There's also a lot to be said about the value of taking time away from task and objective oriented thinking to just focusing on awareness. To knowing all the intimate little details that your brain can process that normally get filtered out when we work just to accomplish a goal."]
          }
        }),
        knex('blogs').insert({
          id: 99996,
          category: 'EDA culture',
          title: 'C3 - The Process of Meditation',
          content: {
            "title": "Here's one about meditation",
            "questions": ["How did the 'process over product' concept affect the way you tackled the site redesign and rebuild?"],
            "answers": ["My site looks like a butt at the moment. :/ If I wasn't focusing my attention on the actual process of making the site work, I think I'd get a lot more caught up on random little things; Like the colour doesn't look so great, or that post isn't quite centered. I could have wasted a lot of time that could be spent building the site."]
          }
        })
      ])
    })
}
<commit_msg>rewrote blogs table<commit_after>
exports.seed = function(knex, Promise) {
  // Deletes ALL existing entries
  return knex('blogs').del()
    .then(function () {
      return Promise.all([
        // Inserts seed entries
        knex('blogs').insert({
          id: 99999,
          category: 'EDA culture',
          title: 'C1 - First Reflections',
          sub-title: "I'm taking the opportunity, on this fine, sunny Friday morning to stay inside and write this, my first ever blog post. These are just a few thoughts I have about EDA so far at the start of phase-0, with the lovely Nikau cohort."
        }),
        knex('blogs').insert({
          id: 99998,
          category: 'EDA culture',
          title: 'C1 - Time and Habits',
          sub-title: "Here's my second post. Hope this looks okay. @.@"
        }),
        knex('blogs').insert({
          id: 99997,
          category: 'EDA culture',
          title: 'C2 - Emotional Intelligence',
          sub-title: "EQ > IQ? It's not really news to me now."
        }),
        knex('blogs').insert({
          id: 99996,
          category: 'EDA culture',
          title: 'C3 - The Process of Meditation',
          sub-title: "Here's one about meditation"
        })
      ])
    })
}
<|endoftext|>


<commit_before>// modules =================================================
var express        = require('express');
var app            = express();
var bodyParser     = require('body-parser');
var methodOverride = require('method-override');
var mongoose = require('mongoose');
var User = require('./app/models/user');
var passport = require('passport');
var authenticate = require('./app/authenticate');
// configuration ===========================================

// config files
var config = require('./config/node');
// set our port
var path = require('path');
global.appRoot = path.resolve(__dirname) + config.staticDir;

app.start = function() {
    console.log("starting");
    // connect to our mongoDB database
    // (uncomment after you enter in your own credentials in config/db.js)
    mongoose.connect(config.mongoUrl + "?authMechanism=SCRAM-SHA-1", function(err, res) {
        if(err) {
            console.log('ERROR connecting to: ' + config.mongoUrl + '. ' + err);
        } else {
            console.log('Succeeded connecting to: ' + config.mongoUrl);
        }
    });

    // get all data/stuff of the body (POST) parameters
    // parse application/json
    app.use(bodyParser.json());
    // parse application/vnd.api+json as json
    app.use(bodyParser.json({ type: 'application/vnd.api+json' }));

    // parse application/x-www-form-urlencoded
    app.use(bodyParser.urlencoded({ extended: true }));

    app.use(express.static(__dirname + '/dist', { maxAge: 365 }));
    console.log('loaded bodyParser');

    // override with the X-HTTP-Method-Override header in the request. simulate DELETE/PUT
    app.use(methodOverride('X-HTTP-Method-Override'));
    console.log('methodOverride started');
    app.use(passport.initialize());
    // set the static files location /public/img will be /img for users
    app.use(express.static('.'));
    console.log("express static loaded");
    // routes ==================================================
    require('./app/routes')(app, config.staticDir); // configure our routes
    console.log('app routes');
    // start app ===============================================
    // startup our app at http://localhost:8080
    app.listen(config.port);
    // shoutout to the user
    console.log('Magic happens on port ' + config.port);
}

app.stop = function() {
    app.close();
}
// expose app
exports = module.exports = app;    <commit_msg>fix size limits<commit_after>// modules =================================================
var express        = require('express');
var app            = express();
var bodyParser     = require('body-parser');
var methodOverride = require('method-override');
var mongoose = require('mongoose');
var User = require('./app/models/user');
var passport = require('passport');
var authenticate = require('./app/authenticate');
// configuration ===========================================

// config files
var config = require('./config/node');
// set our port
var path = require('path');
global.appRoot = path.resolve(__dirname) + config.staticDir;

app.start = function() {
    console.log("starting");
    // connect to our mongoDB database
    // (uncomment after you enter in your own credentials in config/db.js)
    mongoose.connect(config.mongoUrl + "?authMechanism=SCRAM-SHA-1", function(err, res) {
        if(err) {
            console.log('ERROR connecting to: ' + config.mongoUrl + '. ' + err);
        } else {
            console.log('Succeeded connecting to: ' + config.mongoUrl);
        }
    });

    // get all data/stuff of the body (POST) parameters
    // parse application/json
    app.use(bodyParser.json({limit: '50mb'}));
    // parse application/vnd.api+json as json
    app.use(bodyParser.json({ type: 'application/vnd.api+json' }));

    // parse application/x-www-form-urlencoded
    app.use(bodyParser.urlencoded({ extended: true }));

    app.use(express.static(__dirname + '/dist', { maxAge: 365 }));
    console.log('loaded bodyParser');

    // override with the X-HTTP-Method-Override header in the request. simulate DELETE/PUT
    app.use(methodOverride('X-HTTP-Method-Override'));
    console.log('methodOverride started');
    app.use(passport.initialize());
    // set the static files location /public/img will be /img for users
    app.use(express.static('.'));
    console.log("express static loaded");
    // routes ==================================================
    require('./app/routes')(app, config.staticDir); // configure our routes
    console.log('app routes');
    // start app ===============================================
    // startup our app at http://localhost:8080
    app.listen(config.port);
    // shoutout to the user
    console.log('Magic happens on port ' + config.port);
}

app.stop = function() {
    app.close();
}
// expose app
exports = module.exports = app;    <|endoftext|>


<commit_before>var suite = {
	name: "All thenable 2",
	initialize: function(Constructor) {
    var array = [];

    function resolver(resolve) { resolve(1); }

    for (var i = 0; i < 2; i++) {
      array.push(new Constructor(resolver));
    }

		return array;
	},
	test: function(Constructor, testInstance, array) {
    Constructor.all(array).then(function() {
      testInstance.end();
    });
	},
	options: {
		defer: true
	}
};

export suite;
<commit_msg>retab<commit_after>var suite = {
  name: "All thenable 2",
  initialize: function(Constructor) {
    var array = [];

    function resolver(resolve) { resolve(1); }

    for (var i = 0; i < 2; i++) {
      array.push(new Constructor(resolver));
    }

    return array;
  },
  test: function(Constructor, testInstance, array) {
    Constructor.all(array).then(function() {
      testInstance.end();
    });
  },
  options: {
    defer: true
  }
};

export suite;
<|endoftext|>


<commit_before>const Promise = require('bluebird')
const request = Promise.promisifyAll(require('request'))
const fs = Promise.promisifyAll(require('fs'))
const path = require('path')
const logger = require('loggy')
const cache = require('./cache')

const dataDir = path.join(__dirname, '..', 'schedules')

/**
 * Make sure people aren't trying anything funny
 * with weird source characters
 *
 * @param  {string} source Source string
 * @return {boolean} Returns true if source is valid
 */
const validateSource = function (source) {
  return source.match(/^[a-zA-Z0-9\-]+$/)
}

const getLocalData = async function (source, file) {
  if (!validateSource(source)) { throw new Error('Source contains invalid characters') }
  const data = await fs.readFileAsync(path.join(dataDir, source, file))
  return data.toString()
}

const getWebData = async function (source, file, url) {
  if (!validateSource(source)) { throw new Error('Source contains invalid characters') }
  const response = await request.getAsync(`${url}/api/data/${source}/${file.split('.')[0]}`)
  return response.body
}

const fetch = async function (source, file) {
  const sourceData = await getSource(source)
  switch (sourceData.location) {
    case 'local':
      return getLocalData(source, file)
    case 'web':
      try {
        return (await getWebData(source, file, sourceData.url))
      } catch (e) {
        logger.warn(`Connection to ${sourceData.url} failed`)
        return getLocalData(source, file)
      }
  }
}
const getCorrection = cache(async function (source) {
  return fetch(source, 'correction.txt')
})
const getSchedules = cache(async function (source) {
  return fetch(source, 'schedules.bell')
})
const getCalendar = cache(async function (source) {
  return fetch(source, 'calendar.bell')
})
const getMeta = cache(async function (source) {
  try {
    const meta = await fetch(source, 'meta.json')
    return JSON.parse(meta)
  } catch (e) {
    return JSON.parse(await getLocalData(source, 'meta.json'))
  }
})
const getSource = cache(async function (source) {
  source = await getLocalData(source, 'source.json')
  return JSON.parse(source.toString())
})
const getMessage = cache(async function (source) {
  try {
    return JSON.parse(await fetch(source, 'message.json'))
  } catch (e) {
    return JSON.parse(await fs.readFileAsync(path.join(dataDir, 'message.json')))
  }
})
const getVersion = cache(async function () {
  const version = await fs.readFileAsync(path.join(__dirname, '..', 'package.json'))
  return JSON.parse(version.toString()).version
})

module.exports = {
  getCorrection,
  getSchedules,
  getCalendar,
  getMeta,
  getSource,
  getMessage,
  getVersion
}
<commit_msg>Fix style<commit_after>const Promise = require('bluebird')
const request = Promise.promisifyAll(require('request'))
const fs = Promise.promisifyAll(require('fs'))
const path = require('path')
const logger = require('loggy')
const cache = require('./cache')

const dataDir = path.join(__dirname, '..', 'schedules')

/**
 * Make sure people aren't trying anything funny
 * with weird source characters
 *
 * @param  {string} source Source string
 * @return {boolean} Returns true if source is valid
 */
const validateSource = function (source) {
  return source.match(/^[a-zA-Z0-9-]+$/)
}

const getLocalData = async function (source, file) {
  if (!validateSource(source)) { throw new Error('Source contains invalid characters') }
  const data = await fs.readFileAsync(path.join(dataDir, source, file))
  return data.toString()
}

const getWebData = async function (source, file, url) {
  if (!validateSource(source)) { throw new Error('Source contains invalid characters') }
  const response = await request.getAsync(`${url}/api/data/${source}/${file.split('.')[0]}`)
  return response.body
}

const fetch = async function (source, file) {
  const sourceData = await getSource(source)
  switch (sourceData.location) {
    case 'local':
      return getLocalData(source, file)
    case 'web':
      try {
        return (await getWebData(source, file, sourceData.url))
      } catch (e) {
        logger.warn(`Connection to ${sourceData.url} failed`)
        return getLocalData(source, file)
      }
  }
}
const getCorrection = cache(async function (source) {
  return fetch(source, 'correction.txt')
})
const getSchedules = cache(async function (source) {
  return fetch(source, 'schedules.bell')
})
const getCalendar = cache(async function (source) {
  return fetch(source, 'calendar.bell')
})
const getMeta = cache(async function (source) {
  try {
    const meta = await fetch(source, 'meta.json')
    return JSON.parse(meta)
  } catch (e) {
    return JSON.parse(await getLocalData(source, 'meta.json'))
  }
})
const getSource = cache(async function (source) {
  source = await getLocalData(source, 'source.json')
  return JSON.parse(source.toString())
})
const getMessage = cache(async function (source) {
  try {
    return JSON.parse(await fetch(source, 'message.json'))
  } catch (e) {
    return JSON.parse(await fs.readFileAsync(path.join(dataDir, 'message.json')))
  }
})
const getVersion = cache(async function () {
  const version = await fs.readFileAsync(path.join(__dirname, '..', 'package.json'))
  return JSON.parse(version.toString()).version
})

module.exports = {
  getCorrection,
  getSchedules,
  getCalendar,
  getMeta,
  getSource,
  getMessage,
  getVersion
}
<|endoftext|>


<commit_before>/*global web3*/
const namehash = require('eth-ens-namehash');

function registerSubDomain(ens, registrar, resolver, defaultAccount, subdomain, rootDomain, reverseNode, address, logger, secureSend, callback) {
  const subnode = namehash.hash(subdomain);
  const rootNode = namehash.hash(rootDomain);
  const node = namehash.hash(`${subdomain}.${rootDomain}`);
  // FIXME Registrar calls a function in ENS and in privatenet it doesn't work for soem reason
  // const toSend = registrar.methods.register(subnode, defaultAccount);
  const toSend = ens.methods.setSubnodeOwner(rootNode, subnode, defaultAccount);
  let transaction;

  secureSend(web3, toSend, {from: defaultAccount}, false)
    // Set resolver for the node
    .then(transac => {
      if (transac.status !== "0x1" && transac.status !== "0x01" && transac.status !== true) {
        logger.warn('Failed transaction', transac);
        return callback('Failed to register. Check gas cost.');
      }
      transaction = transac;
      return secureSend(web3, ens.methods.setResolver(node, resolver.options.address), {from: defaultAccount}, false);
    })
    // Set address for node
    .then(_result => {
      return secureSend(web3, resolver.methods.setAddr(node, address), {from: defaultAccount}, false);
    })
    // Set resolver for the reverse node
    .then(_result => {
      return secureSend(web3, ens.methods.setResolver(reverseNode, resolver.options.address), {from: defaultAccount}, false);
    })
    // Set name for reverse node
    .then(_result => {
      return secureSend(web3, resolver.methods.setName(reverseNode, `${subdomain}.${rootDomain}`), {from: defaultAccount}, false);
    })
    .then(_result => {
      callback(null, transaction);
    })
    .catch(err => {
      logger.error(err.message);
      callback('Failed to register with error: ' + (err.message || err));
    });
}

if (typeof module !== 'undefined' && module.exports) {
  module.exports = registerSubDomain;
}
<commit_msg>Update error with or<commit_after>/*global web3*/
const namehash = require('eth-ens-namehash');

function registerSubDomain(ens, registrar, resolver, defaultAccount, subdomain, rootDomain, reverseNode, address, logger, secureSend, callback) {
  const subnode = namehash.hash(subdomain);
  const rootNode = namehash.hash(rootDomain);
  const node = namehash.hash(`${subdomain}.${rootDomain}`);
  // FIXME Registrar calls a function in ENS and in privatenet it doesn't work for soem reason
  // const toSend = registrar.methods.register(subnode, defaultAccount);
  const toSend = ens.methods.setSubnodeOwner(rootNode, subnode, defaultAccount);
  let transaction;

  secureSend(web3, toSend, {from: defaultAccount}, false)
    // Set resolver for the node
    .then(transac => {
      if (transac.status !== "0x1" && transac.status !== "0x01" && transac.status !== true) {
        logger.warn('Failed transaction', transac);
        return callback('Failed to register. Check gas cost.');
      }
      transaction = transac;
      return secureSend(web3, ens.methods.setResolver(node, resolver.options.address), {from: defaultAccount}, false);
    })
    // Set address for node
    .then(_result => {
      return secureSend(web3, resolver.methods.setAddr(node, address), {from: defaultAccount}, false);
    })
    // Set resolver for the reverse node
    .then(_result => {
      return secureSend(web3, ens.methods.setResolver(reverseNode, resolver.options.address), {from: defaultAccount}, false);
    })
    // Set name for reverse node
    .then(_result => {
      return secureSend(web3, resolver.methods.setName(reverseNode, `${subdomain}.${rootDomain}`), {from: defaultAccount}, false);
    })
    .then(_result => {
      callback(null, transaction);
    })
    .catch(err => {
      logger.error(err.message || err);
      callback('Failed to register with error: ' + (err.message || err));
    });
}

if (typeof module !== 'undefined' && module.exports) {
  module.exports = registerSubDomain;
}
<|endoftext|>


<commit_before>SearchSource.defineSource('hymns', function(searchText, options) {
  var options = {sort: {"number": 1}, limit: 20};

  if(searchText) {
    var regExp = buildRegExp(searchText);
    var selector = {$or: [
      {"name": regExp},
      {"numberText": regExp}
    ]};

    return hymnCollection.find(selector, options).fetch();
  } else {
    return hymnCollection.find({}, options).fetch();
  }
});

function buildRegExp(searchText) {
  // this is a dumb implementation
  var parts = searchText.trim().split(/[ \-\:]+/);
  return new RegExp("(" + parts.join('|') + ")", "ig");
}
<commit_msg>Update hymn.js<commit_after>SearchSource.defineSource('hymns', function(searchText, options) {
  var options = {sort: {"number": 1}, limit: 20};

  if(searchText) {
    var regExp = buildRegExp(searchText);
    var selector = {$or: [
      {"name": regExp},
      {"numberText": regExp}
    ]};

    return hymnCollection.find(selector, options).fetch();
  } else {
    return hymnCollection.find({}, options).fetch();
  }
});

function buildRegExp(searchText) {
  // this is a dumb implementation
  var parts = searchText.trim().split(/[ \-\:]+/);
  return new RegExp("(" + parts.join('|') + ")", "ig");
}
<|endoftext|>


<commit_before>var utils = require('../utils'),
	env = require('../env'),
	openTags = require('../parsers/open-tags'),
	strictTags = /span|script|meta/,
	Context = require('../context'),
	Template = require('../template');

// String Output Descriptor
function SOD() {
	this.attributes = '';
	this.classes = '';
	this.children = '';
	this.style = '';
}

function tagOutput(descriptor, innerDescriptor, name) {
	var out = '<' + name + innerDescriptor.attributes;
	if (innerDescriptor.style)
		out += ' style="' + innerDescriptor.style + '"';
	if (innerDescriptor.classes)
		out += ' class="' + innerDescriptor.classes + '"';
	if (innerDescriptor.children)
		descriptor.children += out + '>' + innerDescriptor.children + '</' + name + '>';
	else if (openTags.test(name))
		descriptor.children += out + '>';
	else if (strictTags.test(name))
		descriptor.children += out + '></' + name + '>';
	else
		descriptor.children += out + '/>';
}
utils.tagOutput = tagOutput;

var methods = {
	SOD: SOD,
	//_________________________________ local context management
	context: function(context, descriptor, args) {
		var value = args[0],
			parentPath = args[1];
		descriptor.context = new Context(parentPath ? null : value, context, parentPath ? parentPath : null)
	},
	//_________________________________________ EACH
	each: function(context, descriptor, args) {
		var path = args[0],
			values = (typeof path === 'string') ? context.get(path) : path;
		if (values) {
			var template = args[1];
			for (var i = 0, len = values.length; i < len; ++i)
				template.toHTMLString(new Context(values[i], context), descriptor);
		}
	},
	// ____________________________________ WITH
	with: function(context, descriptor, args) {
		var path = args[0],
			template = args[1];
		var ctx = new Context(typeof path === 'string' ? context.get(path) : path, context, path);
		template.toHTMLString(ctx, descriptor, container);
	},
	//______________________________________________
	rendered: function(context, descriptor, args) {
		var ok, condition = args[0];
		if (condition && condition.__interpolable__)
			ok = condition.output(context);
		else if (type === 'function')
			ok = condition.call(this, context);
		if (ok)
		; // render to string
	},
	//________________________________ TAGS
	tag: function(context, descriptor, originalArgs) {
		var name = originalArgs[0],
			template = originalArgs[1];
		var newDescriptor = new SOD();
		template.toHTMLString(context, newDescriptor);
		tagOutput(descriptor, newDescriptor, name);
	},
	text: function(context, descriptor, args) {
		var value = args[0];
		descriptor.children += value.__interpolable__ ? value.output(context) : value;
	},
	br: function(context, descriptor) {
		descriptor.children += '
';
	},
	//______________________________________________ ATTRIBUTES
	attr: function(context, descriptor, args) {
		var name = args[0],
			value = args[1];
		descriptor.attributes += ' ' + name;
		if (value)
			descriptor.attributes += '="' + (value.__interpolable__ ? value.output(context) : value) + '"';
	},
	disabled: function(context, descriptor, args) {
		var value = args[0];
		if (value === undefined || context.get(value))
			descriptor.attributes += ' disabled';
	},
	val: function(context, descriptor, args) {
		var path = args[0],
			value = args[1];
		descriptor.attributes += ' value="' + (value.__interpolable__ ? value.output(context) : value) + '"';
	},
	setClass: function(context, descriptor, args) {
		var name = args[0],
			flag = args[1];
		if ((flag.__interpolable__ && flag.output(context)) || flag)
			descriptor.classes += ' ' + (name.__interpolable__ ? name.output(context) : name);
	},
	css: function(context, descriptor, args) {
		var prop = args[0],
			value = args[1];
		descriptor.style += prop + ':' + (value.__interpolable__ ? value.output(context) : value);
	},
	visible: function(context, descriptor, args) {
		var flag = args[0],
			val = flag.__interpolable__ ? flag.output(context) : flag;
		if (!val)
			descriptor.style += 'display:none;';
	},
	//_________________________________ EVENTS
	on: function() {},
	off: function() {},
	//_________________________________ CLIENT/SERVER
	client: function(context, descriptor, args) {
		if (env.isServer)
			return;
		args[0].toHTMLString(context, descriptor);
	},
	server: function(context, descriptor, args) {
		if (!env.isServer)
			return;
		args[0].toHTMLString(context, descriptor);
	}
};

Template.prototype.toHTMLString = function(context, descriptor) {
	context = context || new Context();
	descriptor = descriptor ||  new SOD();
	var handler = this._queue[0],
		nextIndex = 0,
		f;
	while (handler) {
		if (handler.engineBlock)
			f = handler.engineBlock.string;
		else
			f = handler.func || methods[handler.name];
		if (!f)
			throw new Error('string output : no template output method found with ' + JSON.stringify(handler));
		f(descriptor.context || context, descriptor, handler.args);
		handler = this._queue[++nextIndex];
	}
	return descriptor.children;
};

module.exports = methods;
<commit_msg>finalise string.each with emptyTempl<commit_after>var utils = require('../utils'),
	env = require('../env'),
	openTags = require('../parsers/open-tags'),
	strictTags = /span|script|meta/,
	Context = require('../context'),
	Template = require('../template');

// String Output Descriptor
function SOD() {
	this.attributes = '';
	this.classes = '';
	this.children = '';
	this.style = '';
}

function tagOutput(descriptor, innerDescriptor, name) {
	var out = '<' + name + innerDescriptor.attributes;
	if (innerDescriptor.style)
		out += ' style="' + innerDescriptor.style + '"';
	if (innerDescriptor.classes)
		out += ' class="' + innerDescriptor.classes + '"';
	if (innerDescriptor.children)
		descriptor.children += out + '>' + innerDescriptor.children + '</' + name + '>';
	else if (openTags.test(name))
		descriptor.children += out + '>';
	else if (strictTags.test(name))
		descriptor.children += out + '></' + name + '>';
	else
		descriptor.children += out + '/>';
}
utils.tagOutput = tagOutput;

var methods = {
	SOD: SOD,
	//_________________________________ local context management
	context: function(context, descriptor, args) {
		var value = args[0],
			parentPath = args[1];
		descriptor.context = new Context(parentPath ? null : value, context, parentPath ? parentPath : null)
	},
	//_________________________________________ EACH
	each: function(context, descriptor, args) {
		var path = args[0],
			values = (typeof path === 'string') ? context.get(path) : path;
		if (values && values.length) {
			var template = args[1];
			for (var i = 0, len = values.length; i < len; ++i)
				template.toHTMLString(new Context(values[i], context), descriptor);
		} else if (args[2])
			args[2].toHTMLString(context, descriptor);
	},
	// ____________________________________ WITH
	with: function(context, descriptor, args) {
		var path = args[0],
			template = args[1];
		var ctx = new Context(typeof path === 'string' ? context.get(path) : path, context, path);
		template.toHTMLString(ctx, descriptor, container);
	},
	//______________________________________________
	rendered: function(context, descriptor, args) {
		var ok, condition = args[0];
		if (condition && condition.__interpolable__)
			ok = condition.output(context);
		else if (type === 'function')
			ok = condition.call(this, context);
		if (ok)
		; // render to string
	},
	//________________________________ TAGS
	tag: function(context, descriptor, originalArgs) {
		var name = originalArgs[0],
			template = originalArgs[1];
		var newDescriptor = new SOD();
		template.toHTMLString(context, newDescriptor);
		tagOutput(descriptor, newDescriptor, name);
	},
	text: function(context, descriptor, args) {
		var value = args[0];
		descriptor.children += value.__interpolable__ ? value.output(context) : value;
	},
	br: function(context, descriptor) {
		descriptor.children += '
';
	},
	//______________________________________________ ATTRIBUTES
	attr: function(context, descriptor, args) {
		var name = args[0],
			value = args[1];
		descriptor.attributes += ' ' + name;
		if (value)
			descriptor.attributes += '="' + (value.__interpolable__ ? value.output(context) : value) + '"';
	},
	disabled: function(context, descriptor, args) {
		var value = args[0];
		if (value === undefined || context.get(value))
			descriptor.attributes += ' disabled';
	},
	val: function(context, descriptor, args) {
		var path = args[0],
			value = args[1];
		descriptor.attributes += ' value="' + (value.__interpolable__ ? value.output(context) : value) + '"';
	},
	setClass: function(context, descriptor, args) {
		var name = args[0],
			flag = args[1];
		if ((flag.__interpolable__ && flag.output(context)) || flag)
			descriptor.classes += ' ' + (name.__interpolable__ ? name.output(context) : name);
	},
	css: function(context, descriptor, args) {
		var prop = args[0],
			value = args[1];
		descriptor.style += prop + ':' + (value.__interpolable__ ? value.output(context) : value);
	},
	visible: function(context, descriptor, args) {
		var flag = args[0],
			val = flag.__interpolable__ ? flag.output(context) : flag;
		if (!val)
			descriptor.style += 'display:none;';
	},
	//_________________________________ EVENTS
	on: function() {},
	off: function() {},
	//_________________________________ CLIENT/SERVER
	client: function(context, descriptor, args) {
		if (env.isServer)
			return;
		args[0].toHTMLString(context, descriptor);
	},
	server: function(context, descriptor, args) {
		if (!env.isServer)
			return;
		args[0].toHTMLString(context, descriptor);
	}
};

Template.prototype.toHTMLString = function(context, descriptor) {
	context = context || new Context();
	descriptor = descriptor ||  new SOD();
	var handler = this._queue[0],
		nextIndex = 0,
		f;
	while (handler) {
		if (handler.engineBlock)
			f = handler.engineBlock.string;
		else
			f = handler.func || methods[handler.name];
		if (!f)
			throw new Error('string output : no template output method found with ' + JSON.stringify(handler));
		f(descriptor.context || context, descriptor, handler.args);
		handler = this._queue[++nextIndex];
	}
	return descriptor.children;
};

module.exports = methods;
<|endoftext|>


<commit_before>/*
 * Parser for the CCDA results (labs) section
 */

Parsers.CCDA.results = function (ccda) {

  var parseDate = Documents.parseDate;
  var parseName = Documents.parseName;
  var parseAddress = Documents.parseAddress;
  var data = [], el;

  var results = ccda.section('results');

  results.entries().each(function(entry) {

    // panel
    el = entry.tag('code');
    var panel_name = el.attr('displayName'),
        panel_code = el.attr('code'),
        panel_code_system = el.attr('codeSystem'),
        panel_code_system_name = el.attr('codeSystemName');

    var observation;
    var tests = entry.elsByTag('component');
    var tests_data = [];

    for (var i = 0; i < tests.length; i++) {
      observation = tests[i];

      var date = parseDate(observation.tag('effectiveTime').attr('value'));

      el = observation.tag('code');
      var name = el.attr('displayName'),
          code = el.attr('code'),
          code_system = el.attr('codeSystem'),
          code_system_name = el.attr('codeSystemName');

      el = observation.tag('value');
      var value = parseFloat(el.attr('value')),
          unit = el.attr('unit');

      el = observation.tag('referenceRange');
      var reference_range_text = Core.stripWhitespace(el.tag('observationRange').tag('text').val()),
          reference_range_low_unit = el.tag('observationRange').tag('low').attr('unit'),
          reference_range_low_value = el.tag('observationRange').tag('low').attr('value'),
          reference_range_high_unit = el.tag('observationRange').tag('high').attr('unit'),
          reference_range_high_value = el.tag('observationRange').tag('high').attr('value');

      tests_data.push({
        date: date,
        name: name,
        value: value,
        unit: unit,
        code: code,
        code_system: code_system,
        code_system_name: code_system_name,
        reference_range: {
          text: reference_range_text,
          low_unit: reference_range_low_unit,
          low_value: reference_range_low_value,
          high_unit: reference_range_high_unit,
          high_value: reference_range_high_value,
        }
      });
    }

    data.push({
      name: panel_name,
      code: panel_code,
      code_system: panel_code_system,
      code_system_name: panel_code_system_name,
      tests: tests_data
    });
  });

  return data;
};
<commit_msg>Fixed High/Low parsing in labs<commit_after>/*
 * Parser for the CCDA results (labs) section
 */

Parsers.CCDA.results = function (ccda) {

  var parseDate = Documents.parseDate;
  var parseName = Documents.parseName;
  var parseAddress = Documents.parseAddress;
  var data = [], el;

  var results = ccda.section('results');

  results.entries().each(function(entry) {

    // panel
    el = entry.tag('code');
    var panel_name = el.attr('displayName'),
        panel_code = el.attr('code'),
        panel_code_system = el.attr('codeSystem'),
        panel_code_system_name = el.attr('codeSystemName');

    var observation;
    var low = "";
    var high = "";
    var tests = entry.elsByTag('component');
    var tests_data = [];

    for (var i = 0; i < tests.length; i++) {
      observation = tests[i];

      var date = parseDate(observation.tag('effectiveTime').attr('value'));
      if (date === null) {
        try {
            low = parseDate(observation.tag('effectiveTime').tag('low').attr('value'));
            high = parseDate(observation.tag('effectiveTime').tag('high').attr('value'));

            if (low > high) throw "Invalid date range";

            if (low !== null && low.toString() === high.toString()) {
                date = low;
            } else if (low !== null && high !== null) {
                date = { "start": low, "end": high };
            } else if (low === null && high !== null) {
                date = high;
            } else if (low !== null && high === null) {
                date = low;
            } else {
                date = null;
            }
        }catch (ex) {
            //ignore - date remains null
            date = null;
            low = null;
            high = null;
        }
      }

      el = observation.tag('code');
      var name = el.attr('displayName'),
          code = el.attr('code'),
          code_system = el.attr('codeSystem'),
          code_system_name = el.attr('codeSystemName');

      el = observation.tag('value');
      var value = parseFloat(el.attr('value')),
          unit = el.attr('unit');

      el = observation.tag('referenceRange');
      var reference_range_text = Core.stripWhitespace(el.tag('observationRange').tag('text').val()),
          reference_range_low_unit = el.tag('observationRange').tag('low').attr('unit'),
          reference_range_low_value = el.tag('observationRange').tag('low').attr('value'),
          reference_range_high_unit = el.tag('observationRange').tag('high').attr('unit'),
          reference_range_high_value = el.tag('observationRange').tag('high').attr('value');

      var testObj = {
        name: name,
        value: value,
        unit: unit,
        code: code,
        code_system: code_system,
        code_system_name: code_system_name,
        reference_range: {
          text: reference_range_text,
          low_unit: reference_range_low_unit,
          low_value: reference_range_low_value,
          high_unit: reference_range_high_unit,
          high_value: reference_range_high_value,
        }
      }
      testObj["date" + ((typeof(date.start) !== 'undefined') ? "_range" : "")] = date;
      tests_data.push(testObj);
    }

    data.push({
      name: panel_name,
      code: panel_code,
      code_system: panel_code_system,
      code_system_name: panel_code_system_name,
      tests: tests_data
    });
  });

  return data;
};
<|endoftext|>


<commit_before>'use strict'
var Player = require('../')
var cases = require('../../cases/')
var playExec = Player.prototype.play.exec
const SCRIPT_ID = 'bitdash-script'
var instance
var setTime
var hasBuiltinAd

module.exports = {
  define: {
    getTime () {
      if (this.ready.val) {
        let player = instance
        let current = setTime || player.getCurrentTime()
        let duration = this.duration.val || (this.duration.origin.val = player.getDuration())
        return current / duration
      } else {
        return this.time.val
      }
    },
    getBuffer () {
      if (!this.ready.val) {
        return 0
      }
      var player = instance
      var current = setTime || player.getCurrentTime()
      var duration = player.getDuration()
      var bufferLength = player.getVideoBufferLength()
      if (current === duration) {
        return 1
      }
      return (current + bufferLength) / duration
    },
    dispose () {
      var scriptEl = document.getElementById(SCRIPT_ID)
      if (scriptEl) {
        scriptEl.remove()
      }
      initialized = false
      setTime = null
      hasBuiltinAd = false
      if (instance) {
        instance.unload()
        instance.destroy()
        instance = null
        // if (ad) {
        //   if (adPlayer) {
        //     adPlayer.remove()
        //     adPlayer = null
        //   }
        // }
      }
    }
  },
  properties: {
    bitdashInstance: true
  },
  src: {
    define: {
      plain () {
        var val = this.val
        if (val) {
          var obj = {}
          if (typeof val === 'string') {
            obj.hls = val.replace(/{type}/g, 'm3u8')
            obj.mpd = val.replace(/{type}/g, 'mpd')
          } else {
            this.each(function (prop, key) {
              obj[key] = prop.val
            })
          }
          for (var i in obj) {
            return obj
          }
        }
      }
    },
    render (node, event, player) {
      var src = this.plain()
      if (src) {
        if (!instance) {
          init(player, node)
        } else {
          player.ready.origin.val = false
          instance
            .load(this.plain())
            .catch((err) => {
              player.play.origin.val = false
              handleError.call(this, err)
            })
        }
      } else {
        player.play.origin.val = false
        player.ready.origin.val = false
        if (instance) {
          instance.unload()
        }
      }
    }
  },
  play: {
    exec (node, event, player) {
      playExec.apply(this, arguments)
      if (this.val) {
        instance.play()
      } else {
        instance.pause()
      }
    }
  },
  volume: {
    exec (node, event, player) {
      instance.setVolume && instance.setVolume(this.val * 100)
    }
  },
  time: {
    exec (node, event, player) {
      if (player.isProgress(event)) {
        return
      }
      // // let isPaused = !player.play.val
      // // if (isPaused) {
      // //   player.play.origin.val = true
      // // }
      setTime = (player.duration.val || instance.getDuration()) * this.val
      // var seekAmount = (player.duration.val || instance.getDuration()) * this.val
      // setTimeout(() => {
      //   instance.seek(seekAmount)
      // })

      // if (isPaused) {
      //   player.timeout('time', function (player) {
      //     player.play.origin.val = false
      //   }, 10)
      // }
    }
  }
  // mute: {
  //   on: {
  //     data: {
  //       handle () {
  //         var parent = this.parent
  //         var player = parent.bitdashInstance
  //         if (!player || !parent.rendered || !hasSource.call(this)) {
  //           return
  //         }
  //         if (this.val) {
  //           player.mute()
  //         } else {
  //           player.unmute()
  //         }
  //       }
  //     }
  //   }
  // },
  // fullscreen: {
  //   exec (node, event, player) {

  //   }
  //   on: {
  //     data: {
  //       handle () {
  //         var parent = this.parent
  //         var player = parent.bitdashInstance
  //         if (!player || !parent.rendered || !hasSource.call(this)) {
  //           return
  //         }
  //         if (this.val) {
  //           player.enterFullscreen()
  //         } else {
  //           player.exitFullscreen()
  //         }
  //       }
  //     }
  //   }
  // }
}

var initialized = false
function init (player, node) {
  if (initialized) {
    return
  }
  initialized = true
  var opts = player.options
  var bitdashScript = document.createElement('script')
  var store = player.storeContext()
  bitdashScript.type = 'text/javascript'
  bitdashScript.src = opts && opts.bitdashScriptUrl
  bitdashScript.id = SCRIPT_ID
  bitdashScript.onload = () => {
    player.applyContext(store)
    config(player, node)
  }
  document.getElementsByTagName('head')[0].appendChild(bitdashScript)
}

function config (player, node) {
  if (!node.id) {
    node.setAttribute('id', 'dash-player')
  }

  let store = player.storeContext()
  let opts = player.options
  /* global bitdash */
  let config = {
    key: opts.key,
    playback: {
      autoplay: false
    },
    tweaks: {
      file_protocol: true,
      app_id: 'io.vigour.app'
    },
    skin: {},
    style: {
      ux: false,
      width: opts.width || '100%'
    },
    events: {
      onPlaybackFinished () {
        player.applyContext(store)
        player.play.origin.val = false
      },
      onFullscreenEnter () {
        player.applyContext(store)
        player.fullscreen.origin.val = true
      },
      onFullscreenExit () {
        player.applyContext(store)
        player.fullscreen.origin.val = false
      },
      onMute () {
        player.applyContext(store)
        player.mute.origin.val = true
      },
      onUnmute () {
        player.applyContext(store)
        player.mute.origin.val = false
      },
      onError (reason) {
        player.applyContext(store)
        handleError.call(player, reason)
      },
      onTimeChanged () {
        if (setTime) {
          player.timeout('seeking', function () {
            instance.seek(setTime)
            setTime = null
          }, 1)
        }
      }
    }
  }
  if (opts.advertising) {
    config.advertising = opts.advertising
    hasBuiltinAd = true
  }

  config.source = player.src.plain()
  var id = node.id
  var bitplayer = bitdash(id)

  player.applyContext(store)

  bitplayer.setup(config).then(function (value) {
    if (value && value.addEventHandler) {
      instance = global.bitdashInstance = value
      var videos = document.getElementsByTagName('video')
      for (let i = 0; i < videos.length; i++) {
        let video = videos[i]
        if (video.id.indexOf(node.id) === -1) {
          continue
        }
        video.setAttribute('webkit-playsinline', true)
        if (cases.$android.val) {
          video.setAttribute('autoplay', true)
        }
      }

      player.applyContext(store)

      player.ready.origin.val = true
      player.play.origin.val = true
      player.volume.origin.val = 1

      instance.addEventHandler('onReady', () => {
        player.applyContext(store)
        // player.ready.origin.val = true
        // player.play.origin.val = true
        // player.volume.origin.val = 1

        var videos = document.getElementsByTagName('video')
        for (let i = 0; i < videos.length; i++) {
          let video = videos[i]
          if (video.id.indexOf(node.id) === -1) {
            continue
          }
          video.setAttribute('webkit-playsinline', true)
        }
      })

      if (hasBuiltinAd) {
        let maxTries = 5
        let tryPlayAdVideo = function () {
          maxTries--
          player.timeout('builtinAds', function () {
            let id = `bitdash-ad-video-${node.id}`
            let adPlayer = document.getElementById(id)
            if (adPlayer) {
              adPlayer.setAttribute('webkit-playsinline', true)
              adPlayer.setAttribute('autoplay', true)
            } else {
              if (maxTries > 0) {
                tryPlayAdVideo()
              }
            }
          }, 50)
        }
        tryPlayAdVideo()
      }
    }
  }, function (err) {
    // player.play.origin.val = false
    handleError(err)
  })
}

function handleError () {
  console.error('Something went wrong with the player', arguments[0])
  // var reason = arguments.length === 1 && typeof arguments[0] === 'object' && arguments[0]
  // var obs = this
  // var playerConfig = instance && instance.getConfig()

  // if (reason) {
  //   //console.error('Error on instance', reason)
  // }
  // if (instance && instance.isSetup()) {
  //   if (obs.play.val === true && !instance.isPlaying()) {
  //     // play is true but it's not player = player errored and stopped it
  //     // check if it's related to ad
  //     if (playerConfig.source && (playerConfig.source.hls || playerConfig.source.progressive || playerConfig.source.dash)) {
  //       if (obs.ad.play.val === true) {
  //         obs.ad.skip.origin.val = true
  //       }
  //     }
  //   }
  // }
}
<commit_msg>play after load<commit_after>'use strict'
var Player = require('../')
var cases = require('../../cases/')
var playExec = Player.prototype.play.exec
const SCRIPT_ID = 'bitdash-script'
var instance
var setTime
var hasBuiltinAd

module.exports = {
  define: {
    getTime () {
      if (this.ready.val) {
        let player = instance
        let current = setTime || player.getCurrentTime()
        let duration = this.duration.val || (this.duration.origin.val = player.getDuration())
        return current / duration
      } else {
        return this.time.val
      }
    },
    getBuffer () {
      if (!this.ready.val) {
        return 0
      }
      var player = instance
      var current = setTime || player.getCurrentTime()
      var duration = player.getDuration()
      var bufferLength = player.getVideoBufferLength()
      if (current === duration) {
        return 1
      }
      return (current + bufferLength) / duration
    },
    dispose () {
      var scriptEl = document.getElementById(SCRIPT_ID)
      if (scriptEl) {
        scriptEl.remove()
      }
      initialized = false
      setTime = null
      hasBuiltinAd = false
      if (instance) {
        instance.unload()
        instance.destroy()
        instance = null
        // if (ad) {
        //   if (adPlayer) {
        //     adPlayer.remove()
        //     adPlayer = null
        //   }
        // }
      }
    }
  },
  properties: {
    bitdashInstance: true
  },
  src: {
    define: {
      plain () {
        var val = this.val
        if (val) {
          var obj = {}
          if (typeof val === 'string') {
            obj.hls = val.replace(/{type}/g, 'm3u8')
            obj.mpd = val.replace(/{type}/g, 'mpd')
          } else {
            this.each(function (prop, key) {
              obj[key] = prop.val
            })
          }
          for (var i in obj) {
            return obj
          }
        }
      }
    },
    render (node, event, player) {
      var src = this.plain()
      if (src) {
        if (!instance) {
          init(player, node)
        } else {
          player.ready.origin.val = false
          instance
            .load(this.plain())
            .catch((err) => {
              player.play.origin.val = false
              handleError.call(this, err)
            })
        }
      } else {
        player.play.origin.val = false
        player.ready.origin.val = false
        if (instance) {
          instance.unload()
        }
      }
    }
  },
  play: {
    exec (node, event, player) {
      playExec.apply(this, arguments)
      if (this.val) {
        instance.play()
      } else {
        instance.pause()
      }
    }
  },
  volume: {
    exec (node, event, player) {
      instance.setVolume && instance.setVolume(this.val * 100)
    }
  },
  time: {
    exec (node, event, player) {
      if (player.isProgress(event)) {
        return
      }
      // // let isPaused = !player.play.val
      // // if (isPaused) {
      // //   player.play.origin.val = true
      // // }
      setTime = (player.duration.val || instance.getDuration()) * this.val
      // var seekAmount = (player.duration.val || instance.getDuration()) * this.val
      // setTimeout(() => {
      //   instance.seek(seekAmount)
      // })

      // if (isPaused) {
      //   player.timeout('time', function (player) {
      //     player.play.origin.val = false
      //   }, 10)
      // }
    }
  }
  // mute: {
  //   on: {
  //     data: {
  //       handle () {
  //         var parent = this.parent
  //         var player = parent.bitdashInstance
  //         if (!player || !parent.rendered || !hasSource.call(this)) {
  //           return
  //         }
  //         if (this.val) {
  //           player.mute()
  //         } else {
  //           player.unmute()
  //         }
  //       }
  //     }
  //   }
  // },
  // fullscreen: {
  //   exec (node, event, player) {

  //   }
  //   on: {
  //     data: {
  //       handle () {
  //         var parent = this.parent
  //         var player = parent.bitdashInstance
  //         if (!player || !parent.rendered || !hasSource.call(this)) {
  //           return
  //         }
  //         if (this.val) {
  //           player.enterFullscreen()
  //         } else {
  //           player.exitFullscreen()
  //         }
  //       }
  //     }
  //   }
  // }
}

var initialized = false
function init (player, node) {
  if (initialized) {
    return
  }
  initialized = true
  var opts = player.options
  var bitdashScript = document.createElement('script')
  var store = player.storeContext()
  bitdashScript.type = 'text/javascript'
  bitdashScript.src = opts && opts.bitdashScriptUrl
  bitdashScript.id = SCRIPT_ID
  bitdashScript.onload = () => {
    player.applyContext(store)
    config(player, node)
  }
  document.getElementsByTagName('head')[0].appendChild(bitdashScript)
}

function config (player, node) {
  if (!node.id) {
    node.setAttribute('id', 'dash-player')
  }

  let store = player.storeContext()
  let opts = player.options
  /* global bitdash */
  let config = {
    key: opts.key,
    playback: {
      autoplay: false
    },
    tweaks: {
      file_protocol: true,
      app_id: 'io.vigour.app'
    },
    skin: {},
    style: {
      ux: false,
      width: opts.width || '100%'
    },
    events: {
      onPlaybackFinished () {
        player.applyContext(store)
        player.play.origin.val = false
      },
      onFullscreenEnter () {
        player.applyContext(store)
        player.fullscreen.origin.val = true
      },
      onFullscreenExit () {
        player.applyContext(store)
        player.fullscreen.origin.val = false
      },
      onMute () {
        player.applyContext(store)
        player.mute.origin.val = true
      },
      onUnmute () {
        player.applyContext(store)
        player.mute.origin.val = false
      },
      onError (reason) {
        player.applyContext(store)
        handleError.call(player, reason)
      },
      onTimeChanged () {
        if (setTime) {
          player.timeout('seeking', function () {
            instance.seek(setTime)
            setTime = null
          }, 1)
        }
      }
    }
  }
  if (opts.advertising) {
    config.advertising = opts.advertising
    hasBuiltinAd = true
  }

  config.source = player.src.plain()
  var id = node.id
  var bitplayer = bitdash(id)

  player.applyContext(store)

  bitplayer.setup(config).then(function (value) {
    if (value && value.addEventHandler) {
      instance = global.bitdashInstance = value
      var videos = document.getElementsByTagName('video')
      for (let i = 0; i < videos.length; i++) {
        let video = videos[i]
        if (video.id.indexOf(node.id) === -1) {
          continue
        }
        video.setAttribute('webkit-playsinline', true)
        if (cases.$android.val) {
          video.setAttribute('autoplay', true)
        }
      }

      player.applyContext(store)

      player.ready.origin.val = true
      player.play.origin.val = true
      player.volume.origin.val = 1

      instance.addEventHandler('onReady', () => {
        player.applyContext(store)
        player.ready.origin.val = true
        player.play.origin.val = true
        player.volume.origin.val = 1

        var videos = document.getElementsByTagName('video')
        for (let i = 0; i < videos.length; i++) {
          let video = videos[i]
          if (video.id.indexOf(node.id) === -1) {
            continue
          }
          video.setAttribute('webkit-playsinline', true)
        }
      })

      if (hasBuiltinAd) {
        let maxTries = 5
        let tryPlayAdVideo = function () {
          maxTries--
          player.timeout('builtinAds', function () {
            let id = `bitdash-ad-video-${node.id}`
            let adPlayer = document.getElementById(id)
            if (adPlayer) {
              adPlayer.setAttribute('webkit-playsinline', true)
              adPlayer.setAttribute('autoplay', true)
            } else {
              if (maxTries > 0) {
                tryPlayAdVideo()
              }
            }
          }, 50)
        }
        tryPlayAdVideo()
      }
    }
  }, function (err) {
    // player.play.origin.val = false
    handleError(err)
  })
}

function handleError () {
  console.error('Something went wrong with the player', arguments[0])
  // var reason = arguments.length === 1 && typeof arguments[0] === 'object' && arguments[0]
  // var obs = this
  // var playerConfig = instance && instance.getConfig()

  // if (reason) {
  //   //console.error('Error on instance', reason)
  // }
  // if (instance && instance.isSetup()) {
  //   if (obs.play.val === true && !instance.isPlaying()) {
  //     // play is true but it's not player = player errored and stopped it
  //     // check if it's related to ad
  //     if (playerConfig.source && (playerConfig.source.hls || playerConfig.source.progressive || playerConfig.source.dash)) {
  //       if (obs.ad.play.val === true) {
  //         obs.ad.skip.origin.val = true
  //       }
  //     }
  //   }
  // }
}
<|endoftext|>


<commit_before>"use strict";

const Item = require('./item');
const Handler = require('./handler');
const Plugin = require('../plugin');
const url = require('url');
const {coroutine: co} = require('bluebird');

class Router extends Plugin {
  constructor(engine) {
    super(engine);
    engine.registry.http.incoming.set({id: 'http', incoming: (...args) => this.incoming(...args)});
    this.router = new Item();
    return this;
  }

  incoming(context) {
    if (context.request.url == '/favicon.ico') {return Promise.resolve();}
    let handlers = Item.sortHandlers(this.router.collectHandlers(context.request._parsedUrl.pathname));
    return co(function*() {
      for (let handler of handlers) {
        if (context.status == undefined) {
          yield (new handler()).init(context);
        }
      }
    })();
  }
}

module.exports = Router;
<commit_msg>Router checking wrong variable for httpResponse<commit_after>"use strict";

const Item = require('./item');
const Handler = require('./handler');
const Plugin = require('../plugin');
const url = require('url');
const {coroutine: co} = require('bluebird');

class Router extends Plugin {
  constructor(engine) {
    super(engine);
    engine.registry.http.incoming.set({id: 'http', incoming: (...args) => this.incoming(...args)});
    this.router = new Item();
    return this;
  }

  incoming(context) {
    // TODO: Proper favicon.ico handling.
    if (context.request.url == '/favicon.ico') {return Promise.resolve();}
    let handlers = Item.sortHandlers(this.router.collectHandlers(context.request._parsedUrl.pathname));
    return co(function*() {
      for (let handler of handlers) {
        if (context.httpResponse == undefined) {
          yield (new handler()).init(context);
        }
      }
    })();
  }
}

module.exports = Router;
<|endoftext|>


<commit_before>'use strict'
/*
 * See the NOTICE.txt file distributed with this work for additional information
 * regarding copyright ownership.
 * Sematext licenses logagent-js to you under
 * the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
var consoleLogger = require('../../util/logger.js')
var Syslogd = require('syslogd')

var SEVERITY = [
  'emerg',
  'alert',
  'crit',
  'err',
  'warning',
  'notice',
  'info',
  'debug'
]
var FACILITY = [
  'kern',
  'user',
  'mail',
  'daemon',
  'auth',
  'syslog',
  'lpr',
  'news',
  'uucp',
  'cron',
  'authpriv',
  'ftp',
  'ntp',
  'logaudit',
  'logalert',
  'clock',
  'local0',
  'local1',
  'local2',
  'local3',
  'local4',
  'local5',
  'local6',
  'local7'
]

function InputSyslog (config, eventEmitter) {
  this.config = config
  this.eventEmitter = eventEmitter
}

InputSyslog.prototype.start = function () {
  if (this.config.udp) {
    try {
      var port = this.config.udp
      var eventEmitter = this.eventEmitter
      var syslogd = Syslogd(function (sysLogMsg) {
        // consoleLogger.log (JSON.stringify(sysLogMsg))
        var context = {
          sourceName: sysLogMsg.tag || 'syslog',
          enrichEvent: {
            // note there is a bug in syslogd so facility and severty are mixed up
            severity: SEVERITY[sysLogMsg.facility] || SEVERITY[6],
            facility: FACILITY[sysLogMsg.severity] || FACILITY[16],
            'syslog-tag': sysLogMsg.tag,
            syslogClient: sysLogMsg.address
          },
          syslogClient: sysLogMsg.address,
          port: port
        }
        eventEmitter.emit('data.raw', sysLogMsg.msg, context)
      }, {address: '0.0.0.0.'})
      syslogd.listen(this.config.udp, function (err) {
        consoleLogger.log('start syslog server ' + syslogd.server.address().address + ':' + this.config.udp + ' ' + (err || ''))
      }.bind(this))
    } catch (err) {
      console.log(err)
    }
  }
}

InputSyslog.prototype.stop = function (cb) {
  cb()
}
module.exports = InputSyslog
<commit_msg>fix bind address<commit_after>'use strict'
/*
 * See the NOTICE.txt file distributed with this work for additional information
 * regarding copyright ownership.
 * Sematext licenses logagent-js to you under
 * the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
var consoleLogger = require('../../util/logger.js')
var Syslogd = require('syslogd')

var SEVERITY = [
  'emerg',
  'alert',
  'crit',
  'err',
  'warning',
  'notice',
  'info',
  'debug'
]
var FACILITY = [
  'kern',
  'user',
  'mail',
  'daemon',
  'auth',
  'syslog',
  'lpr',
  'news',
  'uucp',
  'cron',
  'authpriv',
  'ftp',
  'ntp',
  'logaudit',
  'logalert',
  'clock',
  'local0',
  'local1',
  'local2',
  'local3',
  'local4',
  'local5',
  'local6',
  'local7'
]

function InputSyslog (config, eventEmitter) {
  this.config = config
  this.eventEmitter = eventEmitter
}

InputSyslog.prototype.start = function () {
  if (this.config.udp) {
    try {
      var port = this.config.udp
      var eventEmitter = this.eventEmitter
      var syslogd = Syslogd(function (sysLogMsg) {
        // consoleLogger.log (JSON.stringify(sysLogMsg))
        var context = {
          sourceName: sysLogMsg.tag || 'syslog',
          enrichEvent: {
            // note there is a bug in syslogd so facility and severty are mixed up
            severity: SEVERITY[sysLogMsg.facility] || SEVERITY[6],
            facility: FACILITY[sysLogMsg.severity] || FACILITY[16],
            'syslog-tag': sysLogMsg.tag,
            syslogClient: sysLogMsg.address
          },
          syslogClient: sysLogMsg.address,
          port: port
        }
        eventEmitter.emit('data.raw', sysLogMsg.msg, context)
      }, {address: '0.0.0.0'})
      syslogd.listen(this.config.udp, function (err) {
        consoleLogger.log('start syslog server ' + syslogd.server.address().address + ':' + this.config.udp + ' ' + (err || ''))
      }.bind(this))
    } catch (err) {
      console.log(err)
    }
  }
}

InputSyslog.prototype.stop = function (cb) {
  cb()
}
module.exports = InputSyslog
<|endoftext|>