<commit_before>var deepEqual = require('deep-equal');
var defined = require('defined');
var path = require('path');
var inherits = require('inherits');
var EventEmitter = require('events').EventEmitter;
var has = require('has');
var trim = require('string.prototype.trim');
var bind = require('function-bind');
var forEach = require('for-each');
var isEnumerable = bind.call(Function.call, Object.prototype.propertyIsEnumerable);

module.exports = Test;

var nextTick = typeof setImmediate !== 'undefined'
    ? setImmediate
    : process.nextTick
;
var safeSetTimeout = setTimeout;
var safeClearTimeout = clearTimeout;

inherits(Test, EventEmitter);

var getTestArgs = function (name_, opts_, cb_) {
    var name = '(anonymous)';
    var opts = {};
    var cb;

    for (var i = 0; i < arguments.length; i++) {
        var arg = arguments[i];
        var t = typeof arg;
        if (t === 'string') {
            name = arg;
        } else if (t === 'object') {
            opts = arg || opts;
        } else if (t === 'function') {
            cb = arg;
        }
    }
    return { name: name, opts: opts, cb: cb };
};

function Test (name_, opts_, cb_) {
    if (! (this instanceof Test)) {
        return new Test(name_, opts_, cb_);
    }

    var args = getTestArgs(name_, opts_, cb_);

    this.readable = true;
    this.name = args.name || '(anonymous)';
    this.assertCount = 0;
    this.pendingCount = 0;
    this._skip = args.opts.skip || false;
    this._timeout = args.opts.timeout;
    this._objectPrintDepth = args.opts.objectPrintDepth || 5;
    this._plan = undefined;
    this._cb = args.cb;
    this._progeny = [];
    this._ok = true;

    for (var prop in this) {
        this[prop] = (function bind(self, val) {
            if (typeof val === 'function') {
                return function bound() {
                    return val.apply(self, arguments);
                };
            }
            return val;
        })(this, this[prop]);
    }
}

Test.prototype.run = function () {
    if (this._skip) {
        this.comment('SKIP ' + this.name);
    }
    if (!this._cb || this._skip) {
        return this._end();
    }
    if (this._timeout != null) {
        this.timeoutAfter(this._timeout);
    }
    this.emit('prerun');
    this._cb(this);
    this.emit('run');
};

Test.prototype.test = function (name, opts, cb) {
    var self = this;
    var t = new Test(name, opts, cb);
    this._progeny.push(t);
    this.pendingCount++;
    this.emit('test', t);
    t.on('prerun', function () {
        self.assertCount++;
    })

    if (!self._pendingAsserts()) {
        nextTick(function () {
            self._end();
        });
    }

    nextTick(function() {
        if (!self._plan && self.pendingCount == self._progeny.length) {
            self._end();
        }
    });
};

Test.prototype.comment = function (msg) {
    var that = this;
    forEach(trim(msg).split('\n'), function (aMsg) {
        that.emit('result', trim(aMsg).replace(/^#\s*/, ''));
    });
};

Test.prototype.plan = function (n) {
    this._plan = n;
    this.emit('plan', n);
};

Test.prototype.timeoutAfter = function(ms) {
    if (!ms) throw new Error('timeoutAfter requires a timespan');
    var self = this;
    var timeout = safeSetTimeout(function() {
        self.fail('test timed out after ' + ms + 'ms');
        self.end();
    }, ms);
    this.once('end', function() {
        safeClearTimeout(timeout);
    });
}

Test.prototype.end = function (err) {
    var self = this;
    if (arguments.length >= 1 && !!err) {
        this.ifError(err);
    }

    if (this.calledEnd) {
        this.fail('.end() called twice');
    }
    this.calledEnd = true;
    this._end();
};

Test.prototype._end = function (err) {
    var self = this;
    if (this._progeny.length) {
        var t = this._progeny.shift();
        t.on('end', function () { self._end() });
        t.run();
        return;
    }

    if (!this.ended) this.emit('end');
    var pendingAsserts = this._pendingAsserts();
    if (!this._planError && this._plan !== undefined && pendingAsserts) {
        this._planError = true;
        this.fail('plan != count', {
            expected : this._plan,
            actual : this.assertCount
        });
    }
    this.ended = true;
};

Test.prototype._exit = function () {
    if (this._plan !== undefined &&
        !this._planError && this.assertCount !== this._plan) {
        this._planError = true;
        this.fail('plan != count', {
            expected : this._plan,
            actual : this.assertCount,
            exiting : true
        });
    } else if (!this.ended) {
        this.fail('test exited without ending', {
            exiting: true
        });
    }
};

Test.prototype._pendingAsserts = function () {
    if (this._plan === undefined) {
        return 1;
    }
    return this._plan - (this._progeny.length + this.assertCount);
};

Test.prototype._assert = function assert (ok, opts) {
    var self = this;
    var extra = opts.extra || {};

    var res = {
        id : self.assertCount ++,
        ok : Boolean(ok),
        skip : defined(extra.skip, opts.skip),
        name : defined(extra.message, opts.message, '(unnamed assert)'),
        operator : defined(extra.operator, opts.operator),
        objectPrintDepth : self._objectPrintDepth
    };
    if (has(opts, 'actual') || has(extra, 'actual')) {
        res.actual = defined(extra.actual, opts.actual);
    }
    if (has(opts, 'expected') || has(extra, 'expected')) {
        res.expected = defined(extra.expected, opts.expected);
    }
    this._ok = Boolean(this._ok && ok);

    if (!ok) {
        res.error = defined(extra.error, opts.error, new Error(res.name));
    }

    if (!ok) {
        var e = new Error('exception');
        var err = (e.stack || '').split('\n');
        var dir = __dirname + path.sep;

        for (var i = 0; i < err.length; i++) {
            var m = /^[^\s]*\s*\bat\s+(.+)/.exec(err[i]);
            if (!m) {
                continue;
            }

            var s = m[1].split(/\s+/);
            var filem = /((?:\/|[A-Z]:\\)[^:\s]+:(\d+)(?::(\d+))?)/.exec(s[1]);
            if (!filem) {
                filem = /((?:\/|[A-Z]:\\)[^:\s]+:(\d+)(?::(\d+))?)/.exec(s[2]);

                if (!filem) {
                    filem = /((?:\/|[A-Z]:\\)[^:\s]+:(\d+)(?::(\d+))?)/.exec(s[3]);

                    if (!filem) {
                        continue;
                    }
                }
            }

            if (filem[1].slice(0, dir.length) === dir) {
                continue;
            }

            res.functionName = s[0];
            res.file = filem[1];
            res.line = Number(filem[2]);
            if (filem[3]) res.column = filem[3];

            res.at = m[1];
            break;
        }
    }

    self.emit('result', res);

    var pendingAsserts = self._pendingAsserts();
    if (!pendingAsserts) {
        if (extra.exiting) {
            self._end();
        } else {
            nextTick(function () {
                self._end();
            });
        }
    }

    if (!self._planError && pendingAsserts < 0) {
        self._planError = true;
        self.fail('plan != count', {
            expected : self._plan,
            actual : self._plan - pendingAsserts
        });
    }
};

Test.prototype.fail = function (msg, extra) {
    this._assert(false, {
        message : msg,
        operator : 'fail',
        extra : extra
    });
};

Test.prototype.pass = function (msg, extra) {
    this._assert(true, {
        message : msg,
        operator : 'pass',
        extra : extra
    });
};

Test.prototype.skip = function (msg, extra) {
    this._assert(true, {
        message : msg,
        operator : 'skip',
        skip : true,
        extra : extra
    });
};

Test.prototype.ok
= Test.prototype['true']
= Test.prototype.assert
= function (value, msg, extra) {
    this._assert(value, {
        message : defined(msg, 'should be truthy'),
        operator : 'ok',
        expected : true,
        actual : value,
        extra : extra
    });
};

Test.prototype.notOk
= Test.prototype['false']
= Test.prototype.notok
= function (value, msg, extra) {
    this._assert(!value, {
        message : defined(msg, 'should be falsy'),
        operator : 'notOk',
        expected : false,
        actual : value,
        extra : extra
    });
};

Test.prototype.error
= Test.prototype.ifError
= Test.prototype.ifErr
= Test.prototype.iferror
= function (err, msg, extra) {
    this._assert(!err, {
        message : defined(msg, String(err)),
        operator : 'error',
        actual : err,
        extra : extra
    });
};

Test.prototype.equal
= Test.prototype.equals
= Test.prototype.isEqual
= Test.prototype.is
= Test.prototype.strictEqual
= Test.prototype.strictEquals
= function (a, b, msg, extra) {
    this._assert(a === b, {
        message : defined(msg, 'should be equal'),
        operator : 'equal',
        actual : a,
        expected : b,
        extra : extra
    });
};

Test.prototype.notEqual
= Test.prototype.notEquals
= Test.prototype.notStrictEqual
= Test.prototype.notStrictEquals
= Test.prototype.isNotEqual
= Test.prototype.isNot
= Test.prototype.not
= Test.prototype.doesNotEqual
= Test.prototype.isInequal
= function (a, b, msg, extra) {
    this._assert(a !== b, {
        message : defined(msg, 'should not be equal'),
        operator : 'notEqual',
        actual : a,
        notExpected : b,
        extra : extra
    });
};

Test.prototype.deepEqual
= Test.prototype.deepEquals
= Test.prototype.isEquivalent
= Test.prototype.same
= function (a, b, msg, extra) {
    this._assert(deepEqual(a, b, { strict: true }), {
        message : defined(msg, 'should be equivalent'),
        operator : 'deepEqual',
        actual : a,
        expected : b,
        extra : extra
    });
};

Test.prototype.deepLooseEqual
= Test.prototype.looseEqual
= Test.prototype.looseEquals
= function (a, b, msg, extra) {
    this._assert(deepEqual(a, b), {
        message : defined(msg, 'should be equivalent'),
        operator : 'deepLooseEqual',
        actual : a,
        expected : b,
        extra : extra
    });
};

Test.prototype.notDeepEqual
= Test.prototype.notEquivalent
= Test.prototype.notDeeply
= Test.prototype.notSame
= Test.prototype.isNotDeepEqual
= Test.prototype.isNotDeeply
= Test.prototype.isNotEquivalent
= Test.prototype.isInequivalent
= function (a, b, msg, extra) {
    this._assert(!deepEqual(a, b, { strict: true }), {
        message : defined(msg, 'should not be equivalent'),
        operator : 'notDeepEqual',
        actual : a,
        notExpected : b,
        extra : extra
    });
};

Test.prototype.notDeepLooseEqual
= Test.prototype.notLooseEqual
= Test.prototype.notLooseEquals
= function (a, b, msg, extra) {
    this._assert(!deepEqual(a, b), {
        message : defined(msg, 'should be equivalent'),
        operator : 'notDeepLooseEqual',
        actual : a,
        expected : b,
        extra : extra
    });
};

Test.prototype['throws'] = function (fn, expected, msg, extra) {
    if (typeof expected === 'string') {
        msg = expected;
        expected = undefined;
    }

    var caught = undefined;

    try {
        fn();
    } catch (err) {
        caught = { error : err };
        if ((err != null) && (!isEnumerable(err, 'message') || !has(err, 'message'))) {
            var message = err.message;
            delete err.message;
            err.message = message;
        }
    }

    var passed = caught;

    if (expected instanceof RegExp) {
        passed = expected.test(caught && caught.error);
        expected = String(expected);
    }

    if (typeof expected === 'function' && caught) {
        passed = caught.error instanceof expected;
        caught.error = caught.error.constructor;
    }

    this._assert(typeof fn === 'function' && passed, {
        message : defined(msg, 'should throw'),
        operator : 'throws',
        actual : caught && caught.error,
        expected : expected,
        error: !passed && caught && caught.error,
        extra : extra
    });
};

Test.prototype.doesNotThrow = function (fn, expected, msg, extra) {
    if (typeof expected === 'string') {
        msg = expected;
        expected = undefined;
    }
    var caught = undefined;
    try {
        fn();
    }
    catch (err) {
        caught = { error : err };
    }
    this._assert(!caught, {
        message : defined(msg, 'should not throw'),
        operator : 'throws',
        actual : caught && caught.error,
        expected : expected,
        error : caught && caught.error,
        extra : extra
    });
};

Test.skip = function (name_, _opts, _cb) {
    var args = getTestArgs.apply(null, arguments);
    args.opts.skip = true;
    return Test(args.name, args.opts, args.cb);
};

// vim: set softtabstop=4 shiftwidth=4:

<commit_msg>Check added stack trace parts for filename match<commit_after>var deepEqual = require('deep-equal');
var defined = require('defined');
var path = require('path');
var inherits = require('inherits');
var EventEmitter = require('events').EventEmitter;
var has = require('has');
var trim = require('string.prototype.trim');
var bind = require('function-bind');
var forEach = require('for-each');
var isEnumerable = bind.call(Function.call, Object.prototype.propertyIsEnumerable);

module.exports = Test;

var nextTick = typeof setImmediate !== 'undefined'
    ? setImmediate
    : process.nextTick
;
var safeSetTimeout = setTimeout;
var safeClearTimeout = clearTimeout;

inherits(Test, EventEmitter);

var getTestArgs = function (name_, opts_, cb_) {
    var name = '(anonymous)';
    var opts = {};
    var cb;

    for (var i = 0; i < arguments.length; i++) {
        var arg = arguments[i];
        var t = typeof arg;
        if (t === 'string') {
            name = arg;
        } else if (t === 'object') {
            opts = arg || opts;
        } else if (t === 'function') {
            cb = arg;
        }
    }
    return { name: name, opts: opts, cb: cb };
};

function Test (name_, opts_, cb_) {
    if (! (this instanceof Test)) {
        return new Test(name_, opts_, cb_);
    }

    var args = getTestArgs(name_, opts_, cb_);

    this.readable = true;
    this.name = args.name || '(anonymous)';
    this.assertCount = 0;
    this.pendingCount = 0;
    this._skip = args.opts.skip || false;
    this._timeout = args.opts.timeout;
    this._objectPrintDepth = args.opts.objectPrintDepth || 5;
    this._plan = undefined;
    this._cb = args.cb;
    this._progeny = [];
    this._ok = true;

    for (var prop in this) {
        this[prop] = (function bind(self, val) {
            if (typeof val === 'function') {
                return function bound() {
                    return val.apply(self, arguments);
                };
            }
            return val;
        })(this, this[prop]);
    }
}

Test.prototype.run = function () {
    if (this._skip) {
        this.comment('SKIP ' + this.name);
    }
    if (!this._cb || this._skip) {
        return this._end();
    }
    if (this._timeout != null) {
        this.timeoutAfter(this._timeout);
    }
    this.emit('prerun');
    this._cb(this);
    this.emit('run');
};

Test.prototype.test = function (name, opts, cb) {
    var self = this;
    var t = new Test(name, opts, cb);
    this._progeny.push(t);
    this.pendingCount++;
    this.emit('test', t);
    t.on('prerun', function () {
        self.assertCount++;
    })

    if (!self._pendingAsserts()) {
        nextTick(function () {
            self._end();
        });
    }

    nextTick(function() {
        if (!self._plan && self.pendingCount == self._progeny.length) {
            self._end();
        }
    });
};

Test.prototype.comment = function (msg) {
    var that = this;
    forEach(trim(msg).split('\n'), function (aMsg) {
        that.emit('result', trim(aMsg).replace(/^#\s*/, ''));
    });
};

Test.prototype.plan = function (n) {
    this._plan = n;
    this.emit('plan', n);
};

Test.prototype.timeoutAfter = function(ms) {
    if (!ms) throw new Error('timeoutAfter requires a timespan');
    var self = this;
    var timeout = safeSetTimeout(function() {
        self.fail('test timed out after ' + ms + 'ms');
        self.end();
    }, ms);
    this.once('end', function() {
        safeClearTimeout(timeout);
    });
}

Test.prototype.end = function (err) {
    var self = this;
    if (arguments.length >= 1 && !!err) {
        this.ifError(err);
    }

    if (this.calledEnd) {
        this.fail('.end() called twice');
    }
    this.calledEnd = true;
    this._end();
};

Test.prototype._end = function (err) {
    var self = this;
    if (this._progeny.length) {
        var t = this._progeny.shift();
        t.on('end', function () { self._end() });
        t.run();
        return;
    }

    if (!this.ended) this.emit('end');
    var pendingAsserts = this._pendingAsserts();
    if (!this._planError && this._plan !== undefined && pendingAsserts) {
        this._planError = true;
        this.fail('plan != count', {
            expected : this._plan,
            actual : this.assertCount
        });
    }
    this.ended = true;
};

Test.prototype._exit = function () {
    if (this._plan !== undefined &&
        !this._planError && this.assertCount !== this._plan) {
        this._planError = true;
        this.fail('plan != count', {
            expected : this._plan,
            actual : this.assertCount,
            exiting : true
        });
    } else if (!this.ended) {
        this.fail('test exited without ending', {
            exiting: true
        });
    }
};

Test.prototype._pendingAsserts = function () {
    if (this._plan === undefined) {
        return 1;
    }
    return this._plan - (this._progeny.length + this.assertCount);
};

Test.prototype._assert = function assert (ok, opts) {
    var self = this;
    var extra = opts.extra || {};

    var res = {
        id : self.assertCount ++,
        ok : Boolean(ok),
        skip : defined(extra.skip, opts.skip),
        name : defined(extra.message, opts.message, '(unnamed assert)'),
        operator : defined(extra.operator, opts.operator),
        objectPrintDepth : self._objectPrintDepth
    };
    if (has(opts, 'actual') || has(extra, 'actual')) {
        res.actual = defined(extra.actual, opts.actual);
    }
    if (has(opts, 'expected') || has(extra, 'expected')) {
        res.expected = defined(extra.expected, opts.expected);
    }
    this._ok = Boolean(this._ok && ok);

    if (!ok) {
        res.error = defined(extra.error, opts.error, new Error(res.name));
    }

    if (!ok) {
        var e = new Error('exception');
        var err = (e.stack || '').split('\n');
        var dir = __dirname + path.sep;

        for (var i = 0; i < err.length; i++) {
            var m = /^[^\s]*\s*\bat\s+(.+)/.exec(err[i]);
            if (!m) {
                continue;
            }

            var s = m[1].split(/\s+/);
            var filemRe = /((?:\/|[A-Z]:\\)[^:\s]+:(\d+)(?::(\d+))?)/;
            var filem;
            var sIndex;
            for (sIndex in s.slice(0, 4)) {
                filem = filemRe.exec(s[sIndex]);
                if (filem) break;
            }
            if (! filem) continue;

            if (filem[1].slice(0, dir.length) === dir) {
                continue;
            }

            res.functionName = s[0];
            res.file = filem[1];
            res.line = Number(filem[2]);
            if (filem[3]) res.column = filem[3];

            res.at = m[1];
            break;
        }
    }

    self.emit('result', res);

    var pendingAsserts = self._pendingAsserts();
    if (!pendingAsserts) {
        if (extra.exiting) {
            self._end();
        } else {
            nextTick(function () {
                self._end();
            });
        }
    }

    if (!self._planError && pendingAsserts < 0) {
        self._planError = true;
        self.fail('plan != count', {
            expected : self._plan,
            actual : self._plan - pendingAsserts
        });
    }
};

Test.prototype.fail = function (msg, extra) {
    this._assert(false, {
        message : msg,
        operator : 'fail',
        extra : extra
    });
};

Test.prototype.pass = function (msg, extra) {
    this._assert(true, {
        message : msg,
        operator : 'pass',
        extra : extra
    });
};

Test.prototype.skip = function (msg, extra) {
    this._assert(true, {
        message : msg,
        operator : 'skip',
        skip : true,
        extra : extra
    });
};

Test.prototype.ok
= Test.prototype['true']
= Test.prototype.assert
= function (value, msg, extra) {
    this._assert(value, {
        message : defined(msg, 'should be truthy'),
        operator : 'ok',
        expected : true,
        actual : value,
        extra : extra
    });
};

Test.prototype.notOk
= Test.prototype['false']
= Test.prototype.notok
= function (value, msg, extra) {
    this._assert(!value, {
        message : defined(msg, 'should be falsy'),
        operator : 'notOk',
        expected : false,
        actual : value,
        extra : extra
    });
};

Test.prototype.error
= Test.prototype.ifError
= Test.prototype.ifErr
= Test.prototype.iferror
= function (err, msg, extra) {
    this._assert(!err, {
        message : defined(msg, String(err)),
        operator : 'error',
        actual : err,
        extra : extra
    });
};

Test.prototype.equal
= Test.prototype.equals
= Test.prototype.isEqual
= Test.prototype.is
= Test.prototype.strictEqual
= Test.prototype.strictEquals
= function (a, b, msg, extra) {
    this._assert(a === b, {
        message : defined(msg, 'should be equal'),
        operator : 'equal',
        actual : a,
        expected : b,
        extra : extra
    });
};

Test.prototype.notEqual
= Test.prototype.notEquals
= Test.prototype.notStrictEqual
= Test.prototype.notStrictEquals
= Test.prototype.isNotEqual
= Test.prototype.isNot
= Test.prototype.not
= Test.prototype.doesNotEqual
= Test.prototype.isInequal
= function (a, b, msg, extra) {
    this._assert(a !== b, {
        message : defined(msg, 'should not be equal'),
        operator : 'notEqual',
        actual : a,
        notExpected : b,
        extra : extra
    });
};

Test.prototype.deepEqual
= Test.prototype.deepEquals
= Test.prototype.isEquivalent
= Test.prototype.same
= function (a, b, msg, extra) {
    this._assert(deepEqual(a, b, { strict: true }), {
        message : defined(msg, 'should be equivalent'),
        operator : 'deepEqual',
        actual : a,
        expected : b,
        extra : extra
    });
};

Test.prototype.deepLooseEqual
= Test.prototype.looseEqual
= Test.prototype.looseEquals
= function (a, b, msg, extra) {
    this._assert(deepEqual(a, b), {
        message : defined(msg, 'should be equivalent'),
        operator : 'deepLooseEqual',
        actual : a,
        expected : b,
        extra : extra
    });
};

Test.prototype.notDeepEqual
= Test.prototype.notEquivalent
= Test.prototype.notDeeply
= Test.prototype.notSame
= Test.prototype.isNotDeepEqual
= Test.prototype.isNotDeeply
= Test.prototype.isNotEquivalent
= Test.prototype.isInequivalent
= function (a, b, msg, extra) {
    this._assert(!deepEqual(a, b, { strict: true }), {
        message : defined(msg, 'should not be equivalent'),
        operator : 'notDeepEqual',
        actual : a,
        notExpected : b,
        extra : extra
    });
};

Test.prototype.notDeepLooseEqual
= Test.prototype.notLooseEqual
= Test.prototype.notLooseEquals
= function (a, b, msg, extra) {
    this._assert(!deepEqual(a, b), {
        message : defined(msg, 'should be equivalent'),
        operator : 'notDeepLooseEqual',
        actual : a,
        expected : b,
        extra : extra
    });
};

Test.prototype['throws'] = function (fn, expected, msg, extra) {
    if (typeof expected === 'string') {
        msg = expected;
        expected = undefined;
    }

    var caught = undefined;

    try {
        fn();
    } catch (err) {
        caught = { error : err };
        if ((err != null) && (!isEnumerable(err, 'message') || !has(err, 'message'))) {
            var message = err.message;
            delete err.message;
            err.message = message;
        }
    }

    var passed = caught;

    if (expected instanceof RegExp) {
        passed = expected.test(caught && caught.error);
        expected = String(expected);
    }

    if (typeof expected === 'function' && caught) {
        passed = caught.error instanceof expected;
        caught.error = caught.error.constructor;
    }

    this._assert(typeof fn === 'function' && passed, {
        message : defined(msg, 'should throw'),
        operator : 'throws',
        actual : caught && caught.error,
        expected : expected,
        error: !passed && caught && caught.error,
        extra : extra
    });
};

Test.prototype.doesNotThrow = function (fn, expected, msg, extra) {
    if (typeof expected === 'string') {
        msg = expected;
        expected = undefined;
    }
    var caught = undefined;
    try {
        fn();
    }
    catch (err) {
        caught = { error : err };
    }
    this._assert(!caught, {
        message : defined(msg, 'should not throw'),
        operator : 'throws',
        actual : caught && caught.error,
        expected : expected,
        error : caught && caught.error,
        extra : extra
    });
};

Test.skip = function (name_, _opts, _cb) {
    var args = getTestArgs.apply(null, arguments);
    args.opts.skip = true;
    return Test(args.name, args.opts, args.cb);
};

// vim: set softtabstop=4 shiftwidth=4:

<|endoftext|>


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

    var _ = require('underscore'),
        angular = require('angular'),
        appController = require('js/app-controller'),
        IScroll = require('iscroll'),
        emailDao;

    var MailListCtrl = function($scope) {
        var offset = 0,
            num = 100,
            firstSelect = true;

        emailDao = appController._emailDao;

        //
        // scope functions
        //

        $scope.$parent.select = $scope.select = function(email) {
            if (!email) {
                return;
            }
            // split text only emails into parts for easier rendering
            if (!email.html && typeof email.body === 'string') {
                email.bodyDisplayParts = email.body.split('\n');
            }
            $scope.selected = email;
            // set selected in parent scope ro it can be displayed in the read view
            $scope.$parent.selected = $scope.selected;

            // mark selected message as 'read'
            markAsRead(email);
        };

        $scope.$parent.synchronize = $scope.synchronize = function() {
            updateStatus('Syncing ...');
            // sync from imap to local db
            syncImapFolder({
                folder: getFolder().path,
                offset: -num,
                num: offset
            }, function() {
                // list again from local db after syncing
                listLocalMessages({
                    folder: getFolder().path,
                    offset: offset,
                    num: num
                }, function() {
                    updateStatus('Last update: ', new Date());
                });
            });
        };

        $scope.$watch('currentFolder', function() {
            if (!getFolder()) {
                return;
            }

            // production... in chrome packaged app
            if (window.chrome && chrome.identity) {
                initList();
                return;
            }

            // development... display dummy mail objects
            updateStatus('Last update: ', new Date());
            $scope.$parent.emails = $scope.emails = createDummyMails();
            $scope.select($scope.emails[0]);
        });

        //
        // helper functions
        //

        function initList() {
            updateStatus('Read cache ...');

            // list messaged from local db
            listLocalMessages({
                folder: getFolder().path,
                offset: offset,
                num: num
            }, function sync() {
                updateStatus('Syncing ...');
                $scope.$apply();

                // sync imap folder to local db
                $scope.synchronize();
            });
        }

        function syncImapFolder(options, callback) {
            emailDao.unreadMessages(getFolder().path, function(err, unreadCount) {
                if (err) {
                    console.log(err);
                    updateStatus('Error on sync!');
                    $scope.$apply();
                    return;
                }
                // set unread count in folder model
                getFolder().count = unreadCount;
                $scope.$apply();

                emailDao.imapSync(options, function(err) {
                    if (err) {
                        console.log(err);
                        updateStatus('Error on sync!');
                        $scope.$apply();
                        return;
                    }

                    callback();
                });
            });
        }

        function listLocalMessages(options, callback) {
            firstSelect = true;
            emailDao.listMessages(options, function(err, emails) {
                if (err) {
                    console.log(err);
                    updateStatus('Error listing cache!');
                    $scope.$apply();
                    return;
                }

                callback(emails);
                displayEmails(emails);
            });
        }

        function updateStatus(lbl, time) {
            $scope.lastUpdateLbl = lbl;
            $scope.lastUpdate = (time) ? time : '';
            $scope.$parent.lastUpdateLbl = $scope.lastUpdateLbl;
            $scope.$parent.lastUpdate = $scope.lastUpdate;
        }

        function displayEmails(emails) {
            if (!emails || emails.length < 1) {
                $scope.emails = [];
                $scope.select();
                $scope.$apply();
                return;
            }

            // sort by uid
            emails = _.sortBy(emails, function(e) {
                return -e.uid;
            });

            $scope.$parent.emails = $scope.emails = emails;
            $scope.select($scope.emails[0]);
            $scope.$apply();
        }

        function getFolder() {
            return $scope.$parent.currentFolder;
        }

        function markAsRead(email) {
            // don't mark top selected email automatically
            if (firstSelect) {
                firstSelect = false;
                return;
            }

            email.unread = false;
            emailDao.imapMarkMessageRead({
                folder: getFolder().path,
                uid: email.uid
            }, function(err) {
                if (err) {
                    console.log(err);
                    updateStatus('Error marking read!');
                    $scope.$apply();
                    return;
                }
            });
        }
    };

    function createDummyMails() {
        var Email = function(unread, attachments, answered, html) {
            this.uid = '1';
            this.from = [{
                name: 'Whiteout Support',
                address: 'support@whiteout.io'
            }]; // sender address
            this.to = [{
                address: 'max.musterman@gmail.com'
            }]; // list of receivers
            this.attachments = (attachments) ? [true] : undefined;
            this.unread = unread;
            this.answered = answered;
            this.html = html;
            this.sentDate = new Date('Thu Sep 19 2013 20:41:23 GMT+0200 (CEST)');
            this.subject = "Welcome Max"; // Subject line
            this.body = "Hi Max,\n\n" +
                "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.\n\n" +
                "Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet.\n\n" +
                "Best regards\nYour whiteout team"; // plaintext body
        };

        var dummys = [new Email(true, true), new Email(true, false, false, true), new Email(false, true, true), new Email(false), new Email(false), new Email(false), new Email(false), new Email(false), new Email(false), new Email(false), new Email(false), new Email(false), new Email(false), new Email(false), new Email(false), new Email(false), new Email(false), new Email(false)];

        return dummys;
    }

    //
    // Directives
    //

    var ngModule = angular.module('mail-list', []);
    ngModule.directive('ngIscroll', function($timeout) {
        return {
            link: function(scope, elm) {
                $timeout(function() {
                    var myScroll;
                    // activate iscroll
                    myScroll = new IScroll(elm[0], {
                        mouseWheel: true
                    });
                });

            }
        };
    });

    return MailListCtrl;
});<commit_msg>[WO-29] omit unnecessary flag update<commit_after>define(function(require) {
    'use strict';

    var _ = require('underscore'),
        angular = require('angular'),
        appController = require('js/app-controller'),
        IScroll = require('iscroll'),
        emailDao;

    var MailListCtrl = function($scope) {
        var offset = 0,
            num = 100,
            firstSelect = true;

        emailDao = appController._emailDao;

        //
        // scope functions
        //

        $scope.$parent.select = $scope.select = function(email) {
            if (!email) {
                return;
            }
            // split text only emails into parts for easier rendering
            if (!email.html && typeof email.body === 'string') {
                email.bodyDisplayParts = email.body.split('\n');
            }
            $scope.selected = email;
            // set selected in parent scope ro it can be displayed in the read view
            $scope.$parent.selected = $scope.selected;

            // mark selected message as 'read'
            markAsRead(email);
        };

        $scope.$parent.synchronize = $scope.synchronize = function() {
            updateStatus('Syncing ...');
            // sync from imap to local db
            syncImapFolder({
                folder: getFolder().path,
                offset: -num,
                num: offset
            }, function() {
                // list again from local db after syncing
                listLocalMessages({
                    folder: getFolder().path,
                    offset: offset,
                    num: num
                }, function() {
                    updateStatus('Last update: ', new Date());
                });
            });
        };

        $scope.$watch('currentFolder', function() {
            if (!getFolder()) {
                return;
            }

            // production... in chrome packaged app
            if (window.chrome && chrome.identity) {
                initList();
                return;
            }

            // development... display dummy mail objects
            updateStatus('Last update: ', new Date());
            $scope.$parent.emails = $scope.emails = createDummyMails();
            $scope.select($scope.emails[0]);
        });

        //
        // helper functions
        //

        function initList() {
            updateStatus('Read cache ...');

            // list messaged from local db
            listLocalMessages({
                folder: getFolder().path,
                offset: offset,
                num: num
            }, function sync() {
                updateStatus('Syncing ...');
                $scope.$apply();

                // sync imap folder to local db
                $scope.synchronize();
            });
        }

        function syncImapFolder(options, callback) {
            emailDao.unreadMessages(getFolder().path, function(err, unreadCount) {
                if (err) {
                    console.log(err);
                    updateStatus('Error on sync!');
                    $scope.$apply();
                    return;
                }
                // set unread count in folder model
                getFolder().count = unreadCount;
                $scope.$apply();

                emailDao.imapSync(options, function(err) {
                    if (err) {
                        console.log(err);
                        updateStatus('Error on sync!');
                        $scope.$apply();
                        return;
                    }

                    callback();
                });
            });
        }

        function listLocalMessages(options, callback) {
            firstSelect = true;
            emailDao.listMessages(options, function(err, emails) {
                if (err) {
                    console.log(err);
                    updateStatus('Error listing cache!');
                    $scope.$apply();
                    return;
                }

                callback(emails);
                displayEmails(emails);
            });
        }

        function updateStatus(lbl, time) {
            $scope.lastUpdateLbl = lbl;
            $scope.lastUpdate = (time) ? time : '';
            $scope.$parent.lastUpdateLbl = $scope.lastUpdateLbl;
            $scope.$parent.lastUpdate = $scope.lastUpdate;
        }

        function displayEmails(emails) {
            if (!emails || emails.length < 1) {
                $scope.emails = [];
                $scope.select();
                $scope.$apply();
                return;
            }

            // sort by uid
            emails = _.sortBy(emails, function(e) {
                return -e.uid;
            });

            $scope.$parent.emails = $scope.emails = emails;
            $scope.select($scope.emails[0]);
            $scope.$apply();
        }

        function getFolder() {
            return $scope.$parent.currentFolder;
        }

        function markAsRead(email) {
            // don't mark top selected email automatically
            if (firstSelect) {
                firstSelect = false;
                return;
            }

            if (!email.unread) {
                return;
            }

            email.unread = false;
            emailDao.imapMarkMessageRead({
                folder: getFolder().path,
                uid: email.uid
            }, function(err) {
                if (err) {
                    console.log(err);
                    updateStatus('Error marking read!');
                    $scope.$apply();
                    return;
                }
            });
        }
    };

    function createDummyMails() {
        var Email = function(unread, attachments, answered, html) {
            this.uid = '1';
            this.from = [{
                name: 'Whiteout Support',
                address: 'support@whiteout.io'
            }]; // sender address
            this.to = [{
                address: 'max.musterman@gmail.com'
            }]; // list of receivers
            this.attachments = (attachments) ? [true] : undefined;
            this.unread = unread;
            this.answered = answered;
            this.html = html;
            this.sentDate = new Date('Thu Sep 19 2013 20:41:23 GMT+0200 (CEST)');
            this.subject = "Welcome Max"; // Subject line
            this.body = "Hi Max,\n\n" +
                "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.\n\n" +
                "Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet.\n\n" +
                "Best regards\nYour whiteout team"; // plaintext body
        };

        var dummys = [new Email(true, true), new Email(true, false, false, true), new Email(false, true, true), new Email(false), new Email(false), new Email(false), new Email(false), new Email(false), new Email(false), new Email(false), new Email(false), new Email(false), new Email(false), new Email(false), new Email(false), new Email(false), new Email(false), new Email(false)];

        return dummys;
    }

    //
    // Directives
    //

    var ngModule = angular.module('mail-list', []);
    ngModule.directive('ngIscroll', function($timeout) {
        return {
            link: function(scope, elm) {
                $timeout(function() {
                    var myScroll;
                    // activate iscroll
                    myScroll = new IScroll(elm[0], {
                        mouseWheel: true
                    });
                });

            }
        };
    });

    return MailListCtrl;
});<|endoftext|>


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

(function(){

	// private variables, global for all instances of the functions within this closure
	var max_loaded_id = 0;
	var loaded_elements = [];

	// add our constructor function to the global scope.
	window.Script_loader = function(){

		// private functions
		function isNumber(n) {
			// returns true if n is a number
			return !isNaN(parseFloat(n)) && isFinite(n);
		}
		function isset( argument ){
			// returns true if argument has a value
			if( typeof(argument) !== 'undefined' ){
				if( isNumber(argument) ){
					return true;
				}
				if( argument !== null && argument !== "" ){
					return true;
				}
			}
			return false;
		}
		function add_to_element_list( url, ref ){
			// function stores a reference to the inserted element in the loaded_elements array

			max_loaded_id++;
			loaded_elements[ max_loaded_id ] = {
				"id" : max_loaded_id,
				"ref" : ref,
				"src" : url
			};
			return max_loaded_id;
		}
		function remove_from_element_list( obj ){
			// function removes a reference to an element from the loaded_elements array

			if( isset(obj) ){
				var index = loaded_elements.indexOf(obj);
				loaded_elements[ index ] = undefined;

				return true;
			}
			return false;
		}
		function get_element_list(){
			// return the loaded_elements array

			return loaded_elements;
		}
		function get_loaded_ids(){
			// return an array of all ids of the reference objects in the loaded_elements array

			var id_array = [];
			for( i = 0; i <= max_loaded_id; i++ ){
				if( isset(loaded_elements[i]) && isset( loaded_elements[i].id ) ){
					id_array.push( loaded_elements[i].id );
				}
			}
			return id_array;
		}

		// public object
		return {
			"loaded_elements" : function(){
				return get_element_list();
			},
			"get_ids" : function(){
				return get_loaded_ids();
			},
			"load" : function( url, callback ){
				// add the script / stylesheet 'url' to the <head>

				if( !isset(url) ){
					throw new Error("function expects argument 1 to be an url.");
				}

				// determine type
				var type_info = url.split(".");
				var type = type_info[type_info.length - 1];

				// functions inserted after the loading element can not be called by it, so we always insert the scripts before it.
				var scripts = document.getElementsByTagName('head')[0].getElementsByTagName("script");
				var loading_element = scripts[ scripts.length - 1 ];

				// append to head
				switch(type){
					case "js":
						var script = document.createElement("script");
						script.src = url;
						script.type = "text/javascript";
						script.onreadystatechange = function () {		// IE compatibility mode
							if (this.readyState == 'complete'){
								if( isset(callback) && typeof(callback) == "function" ){
									callback();
								}
							}
						}
						script.onload = callback;
						var ref = document.getElementsByTagName('head')[0].insertBefore(script, loading_element);
					 break;
					case "css":
						var css = document.createElement("link");
						css.href = url;
						css.type = "text/css";
						var ref = document.getElementsByTagName('head')[0].insertBefore(css, loading_element);
					 break;
					default:
						throw new Error("Unknown type: " + type + ".");
					break;
				}
				return add_to_element_list( url, ref );
			},
			"unload" : function( identifier ){
				// remove the element that corresponds the to id given in the array loaded_elements

				if( !isset(identifier) ){
					throw new Error("function expects argument 1 to be an id or url.");
				}

				var ids = get_loaded_ids();
				var element_list = get_element_list();

				if( isNumber(identifier) ){
					// delete based on id

					if( isset(element_list[identifier]) ){
						document.getElementsByTagName('head')[0].removeChild( element_list[identifier].ref );
					}

					remove_from_element_list( element_list[identifier] );

				} else {
					// delete based on url

					ids.forEach( function( id ){
						if( isset(element_list[id]) && isset(element_list[id].src) ){
							if( element_list[id].src == identifier ){

								document.getElementsByTagName('head')[0].removeChild( element_list[id].ref );
								remove_from_element_list( element_list[id] );
							}
						}
					});
				}
			}
		};
	}
})();
<commit_msg>fix css not working for some browsers<commit_after>/*
 * Copyright 07-04-2015 Bl00dsoul
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

(function(){

	// private variables, global for all instances of the functions within this closure
	var max_loaded_id = 0;
	var loaded_elements = [];

	// add our constructor function to the global scope.
	window.Script_loader = function(){

		// private functions
		function isNumber(n) {
			// returns true if n is a number
			return !isNaN(parseFloat(n)) && isFinite(n);
		}
		function isset( argument ){
			// returns true if argument has a value
			if( typeof(argument) !== 'undefined' ){
				if( isNumber(argument) ){
					return true;
				}
				if( argument !== null && argument !== "" ){
					return true;
				}
			}
			return false;
		}
		function add_to_element_list( url, ref ){
			// function stores a reference to the inserted element in the loaded_elements array

			max_loaded_id++;
			loaded_elements[ max_loaded_id ] = {
				"id" : max_loaded_id,
				"ref" : ref,
				"src" : url
			};
			return max_loaded_id;
		}
		function remove_from_element_list( obj ){
			// function removes a reference to an element from the loaded_elements array

			if( isset(obj) ){
				var index = loaded_elements.indexOf(obj);
				loaded_elements[ index ] = undefined;

				return true;
			}
			return false;
		}
		function get_element_list(){
			// return the loaded_elements array

			return loaded_elements;
		}
		function get_loaded_ids(){
			// return an array of all ids of the reference objects in the loaded_elements array

			var id_array = [];
			for( i = 0; i <= max_loaded_id; i++ ){
				if( isset(loaded_elements[i]) && isset( loaded_elements[i].id ) ){
					id_array.push( loaded_elements[i].id );
				}
			}
			return id_array;
		}

		// public object
		return {
			"loaded_elements" : function(){
				return get_element_list();
			},
			"get_ids" : function(){
				return get_loaded_ids();
			},
			"load" : function( url, callback ){
				// add the script / stylesheet 'url' to the <head>

				if( !isset(url) ){
					throw new Error("function expects argument 1 to be an url.");
				}

				// determine type
				var type_info = url.split(".");
				var type = type_info[type_info.length - 1];

				// functions inserted after the loading element can not be called by it, so we always insert the scripts before it.
				var scripts = document.getElementsByTagName('head')[0].getElementsByTagName("script");
				var loading_element = scripts[ scripts.length - 1 ];

				// append to head
				switch(type){
					case "js":
						var script = document.createElement("script");
						script.src = url;
						script.type = "text/javascript";
						script.onreadystatechange = function () {		// IE compatibility mode
							if (this.readyState == 'complete'){
								if( isset(callback) && typeof(callback) == "function" ){
									callback();
								}
							}
						}
						script.onload = callback;
						var ref = document.getElementsByTagName('head')[0].insertBefore(script, loading_element);
					 break;
					case "css":
						var css = document.createElement("link");
						css.href = url;
						css.type = "text/css";
						css.rel  = 'stylesheet';
						var ref = document.getElementsByTagName('head')[0].insertBefore(css, loading_element);
					 break;
					default:
						throw new Error("Unknown type: " + type + ".");
					break;
				}
				return add_to_element_list( url, ref );
			},
			"unload" : function( identifier ){
				// remove the element that corresponds the to id given in the array loaded_elements

				if( !isset(identifier) ){
					throw new Error("function expects argument 1 to be an id or url.");
				}

				var ids = get_loaded_ids();
				var element_list = get_element_list();

				if( isNumber(identifier) ){
					// delete based on id

					if( isset(element_list[identifier]) ){
						document.getElementsByTagName('head')[0].removeChild( element_list[identifier].ref );
					}

					remove_from_element_list( element_list[identifier] );

				} else {
					// delete based on url

					ids.forEach( function( id ){
						if( isset(element_list[id]) && isset(element_list[id].src) ){
							if( element_list[id].src == identifier ){

								document.getElementsByTagName('head')[0].removeChild( element_list[id].ref );
								remove_from_element_list( element_list[id] );
							}
						}
					});
				}
			}
		};
	}
})();
<|endoftext|>


<commit_before>angular.module('MinecraftlyAppControllers')
        .controller('AppCtrl', function ($scope, $rootScope, API, $localStorage, Intercom, $mdDialog, $mdMedia, $mdSidenav) {
            $scope.$storage = $localStorage;
            $scope.openMenu = function () {
                $mdSidenav("leftNav").toggle();
            };
            $scope.logout = function () {
                $localStorage.loggedIn = 0;
                $localStorage.user = {};
            };
            $localStorage.loading = 0;
            $scope.showLogin = function (ev) {
                $mdSidenav("leftNav").close();
                var useFullScreen = ($mdMedia('sm') || $mdMedia('xs')) && $scope.customFullscreen;
                $mdDialog.show({
                    controller: function ($scope, $localStorage, $rootScope, $mdDialog) {
                        $scope.user = {};
                        $scope.cancel = function () {
                            $mdDialog.cancel();
                        }
                        $scope.login = function () {
                            $localStorage.loading = 1;
                            API.login($scope.user.email, $scope.user.password).then(function (resp) {
                                $localStorage.loading = 0;
                                if (resp.data.availableProfiles.length > 0) {
                                    $localStorage.loggedIn = 1;
                                    $localStorage.user = {};
                                    $localStorage.user.uuid = resp.data.availableProfiles[0].id;
                                    $localStorage.user.name = resp.data.availableProfiles[0].name;
                                    $localStorage.user.email = $scope.user.email;
                                    $mdDialog.cancel();
                                    Intercom.boot({
                                        name: $localStorage.user.name,
                                        email: $localStorage.user.email,
                                        user_id: $localStorage.user.uuid,
                                        created_at: Date.now()
                                    });
                                } else {
                                    $mdDialog.show(
                                            $mdDialog.alert()
                                            .parent(angular.element(document.querySelector('body')))
                                            .clickOutsideToClose(true)
                                            .title('Login failed!')
                                            .textContent('Incorrect username and/or password.')
                                            .ariaLabel('Login failed!')
                                            .ok('OK')
                                            .targetEvent(ev)
                                            );
                                }

                            }, function (j, t, a) {
                                $localStorage.loading = 0;

                                $mdDialog.show(
                                        $mdDialog.alert()
                                        .parent(angular.element(document.querySelector('body')))
                                        .clickOutsideToClose(true)
                                        .title('Login failed!')
                                        .textContent('Incorrect username and/or password.')
                                        .ariaLabel('Login failed!')
                                        .ok('OK')
                                        .targetEvent(ev)
                                        );
                            });

                        };
                    },
                    templateUrl: 'templates/login.html',
                    parent: angular.element(document.body),
                    targetEvent: ev,
                    clickOutsideToClose: true,
                    fullscreen: useFullScreen
                })
                        .then(function (answer) {
                        }, function () {
                        });
                $scope.$watch(function () {
                    return $mdMedia('xs') || $mdMedia('sm');
                }, function (wantsFullScreen) {
                    $scope.customFullscreen = (wantsFullScreen === true);
                });
            };
            if ($localStorage.loggedIn == 1) {
                Intercom.boot({
                    name: $localStorage.user.name,
                    email: $localStorage.user.email,
                    created_at: Date.now()
                });
            } else {
                Intercom.boot();
            }
        })
        .controller('mainController', function ($scope) {

        });
<commit_msg>fix_logged_in<commit_after>angular.module('MinecraftlyAppControllers')
        .controller('AppCtrl', function ($scope, $rootScope, API, $localStorage, Intercom, $mdDialog, $mdMedia, $mdSidenav) {
            $scope.$storage = $localStorage;
            $scope.openMenu = function () {
                $mdSidenav("leftNav").toggle();
            };
            $scope.logout = function () {
                $localStorage.loggedIn = 0;
                $localStorage.user = {};
            };
            $localStorage.loading = 0;
            $scope.showLogin = function (ev) {
                $mdSidenav("leftNav").close();
                var useFullScreen = ($mdMedia('sm') || $mdMedia('xs')) && $scope.customFullscreen;
                $mdDialog.show({
                    controller: function ($scope, $localStorage, $rootScope, $mdDialog) {
                        $scope.user = {};
                        $scope.cancel = function () {
                            $mdDialog.cancel();
                        }
                        $scope.login = function () {
                            $localStorage.loading = 1;
                            API.login($scope.user.email, $scope.user.password).then(function (resp) {
                                $localStorage.loading = 0;
                                if (resp.data.availableProfiles.length > 0) {
                                    $localStorage.loggedIn = 1;
                                    $localStorage.user = {};
                                    $localStorage.user.uuid = resp.data.availableProfiles[0].id;
                                    $localStorage.user.name = resp.data.availableProfiles[0].name;
                                    $localStorage.user.email = $scope.user.email;
                                    $mdDialog.cancel();
                                    Intercom.boot({
                                        name: $localStorage.user.name,
                                        email: $localStorage.user.email,
                                        user_id: $localStorage.user.uuid,
                                        created_at: Date.now()
                                    });
                                } else {
                                    $mdDialog.show(
                                            $mdDialog.alert()
                                            .parent(angular.element(document.querySelector('body')))
                                            .clickOutsideToClose(true)
                                            .title('Login failed!')
                                            .textContent('Incorrect username and/or password.')
                                            .ariaLabel('Login failed!')
                                            .ok('OK')
                                            .targetEvent(ev)
                                            );
                                }

                            }, function (j, t, a) {
                                $localStorage.loading = 0;

                                $mdDialog.show(
                                        $mdDialog.alert()
                                        .parent(angular.element(document.querySelector('body')))
                                        .clickOutsideToClose(true)
                                        .title('Login failed!')
                                        .textContent('Incorrect username and/or password.')
                                        .ariaLabel('Login failed!')
                                        .ok('OK')
                                        .targetEvent(ev)
                                        );
                            });

                        };
                    },
                    templateUrl: 'templates/login.html',
                    parent: angular.element(document.body),
                    targetEvent: ev,
                    clickOutsideToClose: true,
                    fullscreen: useFullScreen
                })
                        .then(function (answer) {
                        }, function () {
                        });
                $scope.$watch(function () {
                    return $mdMedia('xs') || $mdMedia('sm');
                }, function (wantsFullScreen) {
                    $scope.customFullscreen = (wantsFullScreen === true);
                });
            };
            if ($localStorage.loggedIn == 1 && $localStorage.user && $localStorage.user.name &&$localStorage.user.email && $localStorage.user.uuid) {
                Intercom.boot({
                    name: $localStorage.user.name,
                    email: $localStorage.user.email,
					user_id: $localStorage.user.uuid,
                    created_at: Date.now()
                });
            } else {
                Intercom.boot();
            }
        })
        .controller('mainController', function ($scope) {

        });
<|endoftext|>


<commit_before>var http = require('http'),
  net = require('net'),
  https = require('https'),
  fs = require('fs'),
  os = require('os'),
  request = require('request'),
  url = require('url'),
  EventEmitter = require('events').EventEmitter,
  util = require('util');

var Logger = require('./logger');

function Mitm(opts) {
  this.opts = opts || {};

  // socket path for system mitm https server
  this.socket = os.tmpdir() + '/node-thin.' + process.pid + '.sock';
  this.interceptors = [];

  this.log = new Logger(false);
}

util.inherits(Mitm, EventEmitter);

Mitm.prototype.listen = function(port, host, cb) {
  var self = this;

  // make sure there's no previously created socket
  if (fs.existsSync(this.socket))
    fs.unlinkSync(this.socket);

  var options = {
    key: fs.readFileSync(__dirname + '/../cert/dummy.key', 'utf8'),
    cert: fs.readFileSync(__dirname + '/../cert/dummy.crt', 'utf8')
  };
  // fake https server, MITM if you want
  this.httpsServer = https.createServer(options, this._handler.bind(this)).listen(this.socket);

  // start HTTP server with custom request handler callback function
  this.httpServer = http.createServer(this._handler.bind(this)).listen(port, host, function(err) {
    if (err)
      self.log.error('Cannot start proxy', err);
    // else
    //   this.log.info('Listening on %s:%s [%d]', this.opts.host, this.opts.port, process.pid);
    cb(err);
  });

  // add handler for HTTPS (which issues a CONNECT to the proxy)
  this.httpServer.addListener('connect', this._httpsHandler.bind(this));
};

Mitm.prototype.close = function(cb) {
  var self = this;
  self.httpServer.close(function(err) {
    if (err)
      return cb(err);
    self.httpsServer.close(cb);
  });
};

Mitm.prototype._handler = function(req, res) {

  var interceptors = this.interceptors.concat([this.direct.bind(this)]);
  var layer = 0;

  (function runner() {
    var interceptor = interceptors[layer++];
    interceptor(req, res, function(err) {
      if (err) return res.end('Proxy error: ' + err.toString());
      runner();
    });
  })();
};

Mitm.prototype._httpsHandler = function(request, socketRequest, bodyhead) {
  var self = this;
  var log = this.log,
    url = request['url'],
    httpVersion = request['httpVersion'];

  log.info('  = will connect to socket "%s"', this.socket);

  // set up TCP connection
  var proxySocket = new net.Socket();
  proxySocket.connect(this.socket, function() {
    log.info('< connected to socket "%s"', self.socket);
    log.info('> writing head of length %d', bodyhead.length);

    proxySocket.write(bodyhead);

    // tell the caller the connection was successfully established
    socketRequest.write('HTTP/' + httpVersion + ' 200 Connection established\r\n\r\n');
  });

  proxySocket.on('data', function(chunk) {
    log.info('< data length = %d', chunk.length);
    socketRequest.write(chunk);
  });

  proxySocket.on('end', function() {
    log.info('< end');
    socketRequest.end();
  });

  socketRequest.on('data', function(chunk) {
    log.info('> data length = %d', chunk.length);
    proxySocket.write(chunk);
  });

  socketRequest.on('end', function() {
    log.info('> end');
    proxySocket.end();
  });

  proxySocket.on('error', function(err) {
    socketRequest.write('HTTP/' + httpVersion + ' 500 Connection error\r\n\r\n');
    log.error('< ERR: %s', err);
    socketRequest.end();
  });

  socketRequest.on('error', function(err) {
    log.error('> ERR: %s', err);
    proxySocket.end();
  });
};

Mitm.prototype.use = function(fn) {
  this.interceptors.push(fn);
};

Mitm.prototype.removeInterceptors = function() {
  this.interceptors.length = 0;
};

Mitm.prototype.direct = function(req, res) {
  var log = this.log,
    self = this,
    path = url.parse(req.url).path,
    schema = Boolean(req.client.pair) ? 'https' : 'http',
    dest = schema + '://' + req.headers['host'] + path;

  var params = {
    url: dest,
    strictSSL: this.opts.strictSSL,
    method: req.method,
    proxy: this.opts.proxy,
    headers: {}
  };

  // Set original headers except proxy system's headers
  var exclude = ['proxy-connection'];
  for (var hname in req.headers)
    if (!~exclude.indexOf(hname))
      params.headers[hname] = req.headers[hname];

  var buffer = '';
  req.on('data', function(chunk) {
    buffer += chunk;
  });

  req.on('end', function() {
    params.body = buffer;
    var r = request(params, function(err, response) {
      if (err) {
          self.emit('error', err);
          res.end();
      }
    });

    r.pipe(res);
  });

};

module.exports = Mitm;
<commit_msg>Allow rejectUnauthorized to be passed as an option.<commit_after>var http = require('http'),
  net = require('net'),
  https = require('https'),
  fs = require('fs'),
  os = require('os'),
  request = require('request'),
  url = require('url'),
  EventEmitter = require('events').EventEmitter,
  util = require('util');

var Logger = require('./logger');

function Mitm(opts) {
  this.opts = opts || {};

  // socket path for system mitm https server
  this.socket = os.tmpdir() + '/node-thin.' + process.pid + '.sock';
  this.interceptors = [];

  this.log = new Logger(false);
}

util.inherits(Mitm, EventEmitter);

Mitm.prototype.listen = function(port, host, cb) {
  var self = this;

  // make sure there's no previously created socket
  if (fs.existsSync(this.socket))
    fs.unlinkSync(this.socket);

  var options = {
    key: fs.readFileSync(__dirname + '/../cert/dummy.key', 'utf8'),
    cert: fs.readFileSync(__dirname + '/../cert/dummy.crt', 'utf8')
  };
  // fake https server, MITM if you want
  this.httpsServer = https.createServer(options, this._handler.bind(this)).listen(this.socket);

  // start HTTP server with custom request handler callback function
  this.httpServer = http.createServer(this._handler.bind(this)).listen(port, host, function(err) {
    if (err)
      self.log.error('Cannot start proxy', err);
    // else
    //   this.log.info('Listening on %s:%s [%d]', this.opts.host, this.opts.port, process.pid);
    cb(err);
  });

  // add handler for HTTPS (which issues a CONNECT to the proxy)
  this.httpServer.addListener('connect', this._httpsHandler.bind(this));
};

Mitm.prototype.close = function(cb) {
  var self = this;
  self.httpServer.close(function(err) {
    if (err)
      return cb(err);
    self.httpsServer.close(cb);
  });
};

Mitm.prototype._handler = function(req, res) {

  var interceptors = this.interceptors.concat([this.direct.bind(this)]);
  var layer = 0;

  (function runner() {
    var interceptor = interceptors[layer++];
    interceptor(req, res, function(err) {
      if (err) return res.end('Proxy error: ' + err.toString());
      runner();
    });
  })();
};

Mitm.prototype._httpsHandler = function(request, socketRequest, bodyhead) {
  var self = this;
  var log = this.log,
    url = request['url'],
    httpVersion = request['httpVersion'];

  log.info('  = will connect to socket "%s"', this.socket);

  // set up TCP connection
  var proxySocket = new net.Socket();
  proxySocket.connect(this.socket, function() {
    log.info('< connected to socket "%s"', self.socket);
    log.info('> writing head of length %d', bodyhead.length);

    proxySocket.write(bodyhead);

    // tell the caller the connection was successfully established
    socketRequest.write('HTTP/' + httpVersion + ' 200 Connection established\r\n\r\n');
  });

  proxySocket.on('data', function(chunk) {
    log.info('< data length = %d', chunk.length);
    socketRequest.write(chunk);
  });

  proxySocket.on('end', function() {
    log.info('< end');
    socketRequest.end();
  });

  socketRequest.on('data', function(chunk) {
    log.info('> data length = %d', chunk.length);
    proxySocket.write(chunk);
  });

  socketRequest.on('end', function() {
    log.info('> end');
    proxySocket.end();
  });

  proxySocket.on('error', function(err) {
    socketRequest.write('HTTP/' + httpVersion + ' 500 Connection error\r\n\r\n');
    log.error('< ERR: %s', err);
    socketRequest.end();
  });

  socketRequest.on('error', function(err) {
    log.error('> ERR: %s', err);
    proxySocket.end();
  });
};

Mitm.prototype.use = function(fn) {
  this.interceptors.push(fn);
};

Mitm.prototype.removeInterceptors = function() {
  this.interceptors.length = 0;
};

Mitm.prototype.direct = function(req, res) {
  var log = this.log,
    self = this,
    path = url.parse(req.url).path,
    schema = Boolean(req.client.pair) ? 'https' : 'http',
    dest = schema + '://' + req.headers['host'] + path;

  var params = {
    url: dest,
    strictSSL: this.opts.strictSSL,
    rejectUnauthorized: this.opts.rejectUnauthorized,
    method: req.method,
    proxy: this.opts.proxy,
    headers: {}
  };

  // Set original headers except proxy system's headers
  var exclude = ['proxy-connection'];
  for (var hname in req.headers)
    if (!~exclude.indexOf(hname))
      params.headers[hname] = req.headers[hname];

  var buffer = '';
  req.on('data', function(chunk) {
    buffer += chunk;
  });

  req.on('end', function() {
    params.body = buffer;
    var r = request(params, function(err, response) {
      if (err) {
          self.emit('error', err);
          res.end();
      }
    });

    r.pipe(res);
  });

};

module.exports = Mitm;
<|endoftext|>


<commit_before>import Q from 'q';
import Request from './sessionSuperagent';

import StoreSingleton from '../redux/storeSingleton';

import { kGlobalConstants } from '../GlobalConstants';
import * as uploadActions from '../redux/actions/uploadActions';

const prepareFilesNewSub = (fileDict) => {
    const deferred = Q.defer();

    Request.post(kGlobalConstants.API + 'submit_files/')
        .attach('appropriations', fileDict.appropriations)
        .attach('program_activity', fileDict.program_activity)
        .attach('award_financial', fileDict.award_financial)
        .field('cgac_code', fileDict.cgac_code)
        .field('frec_code', fileDict.frec_code)
        .field('reporting_period_start_date', fileDict.reporting_period_start_date)
        .field('reporting_period_end_date', fileDict.reporting_period_end_date)
        .field('is_quarter', fileDict.is_quarter)
        .end((err, res) => {
            if (err) {
                const response = Object.assign({}, res.body);
                response.httpStatus = res.status;
                deferred.reject(response);
            }
            else {
                deferred.resolve(res);
            }
        });

    return deferred.promise;
};

const prepareFilesExistingSub = (fileDict) => {
    const deferred = Q.defer();

    Request.post(kGlobalConstants.API + 'submit_files/')
        .attach('appropriations', fileDict.appropriations)
        .attach('program_activity', fileDict.program_activity)
        .attach('award_financial', fileDict.award_financial)
        .field('existing_submission_id', fileDict.existing_submission_id)
        .end((err, res) => {
            if (err) {
                const response = Object.assign({}, res.body);
                response.httpStatus = res.status;
                deferred.reject(response);
            }
            else {
                deferred.resolve(res);
            }
        });

    return deferred.promise;
};

const prepareMetadata = (metadata, request) => {
    const tmpRequest = Object.assign({}, request);
    // add the metadata to the request
    tmpRequest.cgac_code = metadata.codeType === 'cgac_code' ? metadata.agency : null;
    tmpRequest.frec_code = metadata.codeType === 'frec_code' ? metadata.agency : null;
    tmpRequest.reporting_period_start_date = metadata.startDate;
    tmpRequest.reporting_period_end_date = metadata.endDate;
    tmpRequest.is_quarter = false;
    if (metadata.dateType === "quarter") {
        tmpRequest.is_quarter = true;
    }

    return tmpRequest;
};

export const submitFabs = (submissionId) => {
    const deferred = Q.defer();

    Request.post(kGlobalConstants.API + 'submit_detached_file/')
        .send(submissionId)
        .end((err, res) => {
            if (err) {
                const response = Object.assign({}, res.body);
                response.httpStatus = res.status;
                deferred.reject(response);
            }
            else {
                deferred.resolve(res);
            }
        });

    return deferred.promise;
};

const prepareFabsFile = (fileDict) => {
    const deferred = Q.defer();

    let fieldType = '';

    if (fileDict.hasOwnProperty('agency_code')) {
        fieldType = 'agency_code';
    }
    else if (fileDict.hasOwnProperty('existing_submission_id')) {
        fieldType = 'existing_submission_id';
    }

    Request.post(kGlobalConstants.API + 'upload_detached_file/')
        .attach('fabs', fileDict.fabs)
        .field(fieldType, fileDict[fieldType])
        .end((err, res) => {
            if (err) {
                const response = Object.assign({}, res.body);
                response.httpStatus = res.status;
                deferred.reject(response);
            }
            else {
                deferred.resolve(res);
            }
        });

    return deferred.promise;
};

export const performRemoteUpload = (submission) => {
    const deferred = Q.defer();

    const store = new StoreSingleton().store;
    store.dispatch(uploadActions.setSubmissionState('uploading'));

    let request = {};

    for (const fileType in submission.files) {
        if (submission.files.hasOwnProperty(fileType)) {
            request[fileType] = submission.files[fileType].file;
        }
    }

    request = prepareMetadata(submission.meta, request);

    prepareFilesNewSub(request)
        .then((res) => {
            store.dispatch(uploadActions.setSubmissionState('prepare'));
            deferred.resolve(res.body.submission_id);
        })
        .catch((err) => {
            store.dispatch(uploadActions.setSubmissionState('failed'));
            deferred.reject(err);
        });

    return deferred.promise;
};

export const performRemoteCorrectedUpload = (submission) => {
    const deferred = Q.defer();

    const store = new StoreSingleton().store;
    store.dispatch(uploadActions.setSubmissionState('uploading'));

    const request = {
        existing_submission_id: submission.id
    };
    for (const fileType in submission.files) {
        if (submission.files.hasOwnProperty(fileType)) {
            request[fileType] = submission.files[fileType].file;
        }
    }

    prepareFilesExistingSub(request)
        .then(() => {
            store.dispatch(uploadActions.setSubmissionState('prepare'));
            deferred.resolve(submission.id);
        })
        .catch((err) => {
            store.dispatch(uploadActions.setSubmissionState('failed'));
            deferred.reject(err);
        });

    return deferred.promise;
};

export const performLocalUpload = (submission) => {
    const deferred = Q.defer();

    let request = {};

    const store = new StoreSingleton().store;
    store.dispatch(uploadActions.setSubmissionState('uploading'));

    request = prepareMetadata(submission.meta, request);

    for (const fileType in submission.files) {
        if (submission.files.hasOwnProperty(fileType)) {
            request[fileType] = submission.files[fileType].file;
        }
    }

    prepareFilesNewSub(request)
        .then((res) => {
            store.dispatch(uploadActions.setSubmissionState('prepare'));
            deferred.resolve(res.body.submission_id);
        })
        .catch(() => {
            store.dispatch(uploadActions.setSubmissionState('failed'));
            deferred.reject();
        });

    return deferred.promise;
};

export const performLocalCorrectedUpload = (submission) => {
    const deferred = Q.defer();

    const store = new StoreSingleton().store;
    store.dispatch(uploadActions.setSubmissionState('uploading'));

    const request = {
        existing_submission_id: submission.id
    };

    for (const fileType in submission.files) {
        if (submission.files.hasOwnProperty(fileType)) {
            request[fileType] = submission.files[fileType].file;
        }
    }

    prepareFilesExistingSub(request)
        .then(() => {
            store.dispatch(uploadActions.setSubmissionState('prepare'));
            deferred.resolve(submission.id);
        })
        .catch(() => {
            store.dispatch(uploadActions.setSubmissionState('failed'));
            deferred.reject();
        });

    return deferred.promise;
};

export const performFabsFileUpload = (submission) => {
    const deferred = Q.defer();

    const store = new StoreSingleton().store;
    store.dispatch(uploadActions.setSubmissionState('uploading'));

    const request = {
        agency_code: submission.meta.subTierAgency
    };

    if (submission.files.hasOwnProperty('fabs')) {
        request.fabs = submission.files.fabs.file;
    }

    prepareFabsFile(request)
        .then((res) => {
            store.dispatch(uploadActions.setSubmissionState('prepare'));
            deferred.resolve(res.body.submission_id);
        })
        .catch((err) => {
            store.dispatch(uploadActions.setSubmissionState('failed'));
            deferred.reject(err);
        });

    return deferred.promise;
};

export const performFabsFileCorrectedUpload = (submission) => {
    const deferred = Q.defer();

    const store = new StoreSingleton().store;
    store.dispatch(uploadActions.setSubmissionState('uploading'));

    const request = {
        existing_submission_id: submission.id
    };

    if (submission.files.hasOwnProperty('fabs')) {
        request.fabs = submission.files.fabs.file;
    }

    prepareFabsFile(request)
        .then((res) => {
            store.dispatch(uploadActions.setSubmissionState('prepare'));
            deferred.resolve(res.body.submission_id);
        })
        .catch((err) => {
            store.dispatch(uploadActions.setSubmissionState('failed'));
            deferred.reject(err);
        });

    return deferred.promise;
};

export const performFabsLocalUpload = (submission) => {
    const deferred = Q.defer();

    const request = {
        agency_code: submission.meta.subTierAgency
    };

    const store = new StoreSingleton().store;
    store.dispatch(uploadActions.setSubmissionState('uploading'));

    if (submission.files.hasOwnProperty('fabs')) {
        request.fabs = submission.files.fabs.file;
    }

    prepareFabsFile(request)
        .then((res) => {
            store.dispatch(uploadActions.setSubmissionState('prepare'));
            deferred.resolve(res.body.submission_id);
        })
        .catch((err) => {
            store.dispatch(uploadActions.setSubmissionState('failed'));
            deferred.reject(err);
        });

    return deferred.promise;
};

export const performFabsLocalCorrectedUpload = (submission) => {
    const deferred = Q.defer();

    const request = {
        existing_submission_id: submission.id
    };

    const store = new StoreSingleton().store;
    store.dispatch(uploadActions.setSubmissionState('uploading'));

    if (submission.files.hasOwnProperty('fabs')) {
        request.fabs = submission.files.fabs.file;
    }

    prepareFabsFile(request)
        .then((res) => {
            store.dispatch(uploadActions.setSubmissionState('prepare'));
            deferred.resolve(res.body.submission_id);
        })
        .catch((err) => {
            store.dispatch(uploadActions.setSubmissionState('failed'));
            deferred.reject(err);
        });

    return deferred.promise;
};
<commit_msg>Renaming submit_files to upload_dabs_files<commit_after>import Q from 'q';
import Request from './sessionSuperagent';

import StoreSingleton from '../redux/storeSingleton';

import { kGlobalConstants } from '../GlobalConstants';
import * as uploadActions from '../redux/actions/uploadActions';

const prepareFilesNewSub = (fileDict) => {
    const deferred = Q.defer();

    Request.post(kGlobalConstants.API + 'upload_dabs_files/')
        .attach('appropriations', fileDict.appropriations)
        .attach('program_activity', fileDict.program_activity)
        .attach('award_financial', fileDict.award_financial)
        .field('cgac_code', fileDict.cgac_code)
        .field('frec_code', fileDict.frec_code)
        .field('reporting_period_start_date', fileDict.reporting_period_start_date)
        .field('reporting_period_end_date', fileDict.reporting_period_end_date)
        .field('is_quarter', fileDict.is_quarter)
        .end((err, res) => {
            if (err) {
                const response = Object.assign({}, res.body);
                response.httpStatus = res.status;
                deferred.reject(response);
            }
            else {
                deferred.resolve(res);
            }
        });

    return deferred.promise;
};

const prepareFilesExistingSub = (fileDict) => {
    const deferred = Q.defer();

    Request.post(kGlobalConstants.API + 'upload_dabs_files/')
        .attach('appropriations', fileDict.appropriations)
        .attach('program_activity', fileDict.program_activity)
        .attach('award_financial', fileDict.award_financial)
        .field('existing_submission_id', fileDict.existing_submission_id)
        .end((err, res) => {
            if (err) {
                const response = Object.assign({}, res.body);
                response.httpStatus = res.status;
                deferred.reject(response);
            }
            else {
                deferred.resolve(res);
            }
        });

    return deferred.promise;
};

const prepareMetadata = (metadata, request) => {
    const tmpRequest = Object.assign({}, request);
    // add the metadata to the request
    tmpRequest.cgac_code = metadata.codeType === 'cgac_code' ? metadata.agency : null;
    tmpRequest.frec_code = metadata.codeType === 'frec_code' ? metadata.agency : null;
    tmpRequest.reporting_period_start_date = metadata.startDate;
    tmpRequest.reporting_period_end_date = metadata.endDate;
    tmpRequest.is_quarter = false;
    if (metadata.dateType === "quarter") {
        tmpRequest.is_quarter = true;
    }

    return tmpRequest;
};

export const submitFabs = (submissionId) => {
    const deferred = Q.defer();

    Request.post(kGlobalConstants.API + 'submit_detached_file/')
        .send(submissionId)
        .end((err, res) => {
            if (err) {
                const response = Object.assign({}, res.body);
                response.httpStatus = res.status;
                deferred.reject(response);
            }
            else {
                deferred.resolve(res);
            }
        });

    return deferred.promise;
};

const prepareFabsFile = (fileDict) => {
    const deferred = Q.defer();

    let fieldType = '';

    if (fileDict.hasOwnProperty('agency_code')) {
        fieldType = 'agency_code';
    }
    else if (fileDict.hasOwnProperty('existing_submission_id')) {
        fieldType = 'existing_submission_id';
    }

    Request.post(kGlobalConstants.API + 'upload_detached_file/')
        .attach('fabs', fileDict.fabs)
        .field(fieldType, fileDict[fieldType])
        .end((err, res) => {
            if (err) {
                const response = Object.assign({}, res.body);
                response.httpStatus = res.status;
                deferred.reject(response);
            }
            else {
                deferred.resolve(res);
            }
        });

    return deferred.promise;
};

export const performRemoteUpload = (submission) => {
    const deferred = Q.defer();

    const store = new StoreSingleton().store;
    store.dispatch(uploadActions.setSubmissionState('uploading'));

    let request = {};

    for (const fileType in submission.files) {
        if (submission.files.hasOwnProperty(fileType)) {
            request[fileType] = submission.files[fileType].file;
        }
    }

    request = prepareMetadata(submission.meta, request);

    prepareFilesNewSub(request)
        .then((res) => {
            store.dispatch(uploadActions.setSubmissionState('prepare'));
            deferred.resolve(res.body.submission_id);
        })
        .catch((err) => {
            store.dispatch(uploadActions.setSubmissionState('failed'));
            deferred.reject(err);
        });

    return deferred.promise;
};

export const performRemoteCorrectedUpload = (submission) => {
    const deferred = Q.defer();

    const store = new StoreSingleton().store;
    store.dispatch(uploadActions.setSubmissionState('uploading'));

    const request = {
        existing_submission_id: submission.id
    };
    for (const fileType in submission.files) {
        if (submission.files.hasOwnProperty(fileType)) {
            request[fileType] = submission.files[fileType].file;
        }
    }

    prepareFilesExistingSub(request)
        .then(() => {
            store.dispatch(uploadActions.setSubmissionState('prepare'));
            deferred.resolve(submission.id);
        })
        .catch((err) => {
            store.dispatch(uploadActions.setSubmissionState('failed'));
            deferred.reject(err);
        });

    return deferred.promise;
};

export const performLocalUpload = (submission) => {
    const deferred = Q.defer();

    let request = {};

    const store = new StoreSingleton().store;
    store.dispatch(uploadActions.setSubmissionState('uploading'));

    request = prepareMetadata(submission.meta, request);

    for (const fileType in submission.files) {
        if (submission.files.hasOwnProperty(fileType)) {
            request[fileType] = submission.files[fileType].file;
        }
    }

    prepareFilesNewSub(request)
        .then((res) => {
            store.dispatch(uploadActions.setSubmissionState('prepare'));
            deferred.resolve(res.body.submission_id);
        })
        .catch(() => {
            store.dispatch(uploadActions.setSubmissionState('failed'));
            deferred.reject();
        });

    return deferred.promise;
};

export const performLocalCorrectedUpload = (submission) => {
    const deferred = Q.defer();

    const store = new StoreSingleton().store;
    store.dispatch(uploadActions.setSubmissionState('uploading'));

    const request = {
        existing_submission_id: submission.id
    };

    for (const fileType in submission.files) {
        if (submission.files.hasOwnProperty(fileType)) {
            request[fileType] = submission.files[fileType].file;
        }
    }

    prepareFilesExistingSub(request)
        .then(() => {
            store.dispatch(uploadActions.setSubmissionState('prepare'));
            deferred.resolve(submission.id);
        })
        .catch(() => {
            store.dispatch(uploadActions.setSubmissionState('failed'));
            deferred.reject();
        });

    return deferred.promise;
};

export const performFabsFileUpload = (submission) => {
    const deferred = Q.defer();

    const store = new StoreSingleton().store;
    store.dispatch(uploadActions.setSubmissionState('uploading'));

    const request = {
        agency_code: submission.meta.subTierAgency
    };

    if (submission.files.hasOwnProperty('fabs')) {
        request.fabs = submission.files.fabs.file;
    }

    prepareFabsFile(request)
        .then((res) => {
            store.dispatch(uploadActions.setSubmissionState('prepare'));
            deferred.resolve(res.body.submission_id);
        })
        .catch((err) => {
            store.dispatch(uploadActions.setSubmissionState('failed'));
            deferred.reject(err);
        });

    return deferred.promise;
};

export const performFabsFileCorrectedUpload = (submission) => {
    const deferred = Q.defer();

    const store = new StoreSingleton().store;
    store.dispatch(uploadActions.setSubmissionState('uploading'));

    const request = {
        existing_submission_id: submission.id
    };

    if (submission.files.hasOwnProperty('fabs')) {
        request.fabs = submission.files.fabs.file;
    }

    prepareFabsFile(request)
        .then((res) => {
            store.dispatch(uploadActions.setSubmissionState('prepare'));
            deferred.resolve(res.body.submission_id);
        })
        .catch((err) => {
            store.dispatch(uploadActions.setSubmissionState('failed'));
            deferred.reject(err);
        });

    return deferred.promise;
};

export const performFabsLocalUpload = (submission) => {
    const deferred = Q.defer();

    const request = {
        agency_code: submission.meta.subTierAgency
    };

    const store = new StoreSingleton().store;
    store.dispatch(uploadActions.setSubmissionState('uploading'));

    if (submission.files.hasOwnProperty('fabs')) {
        request.fabs = submission.files.fabs.file;
    }

    prepareFabsFile(request)
        .then((res) => {
            store.dispatch(uploadActions.setSubmissionState('prepare'));
            deferred.resolve(res.body.submission_id);
        })
        .catch((err) => {
            store.dispatch(uploadActions.setSubmissionState('failed'));
            deferred.reject(err);
        });

    return deferred.promise;
};

export const performFabsLocalCorrectedUpload = (submission) => {
    const deferred = Q.defer();

    const request = {
        existing_submission_id: submission.id
    };

    const store = new StoreSingleton().store;
    store.dispatch(uploadActions.setSubmissionState('uploading'));

    if (submission.files.hasOwnProperty('fabs')) {
        request.fabs = submission.files.fabs.file;
    }

    prepareFabsFile(request)
        .then((res) => {
            store.dispatch(uploadActions.setSubmissionState('prepare'));
            deferred.resolve(res.body.submission_id);
        })
        .catch((err) => {
            store.dispatch(uploadActions.setSubmissionState('failed'));
            deferred.reject(err);
        });

    return deferred.promise;
};
<|endoftext|>