<commit_before>/*jshint eqnull:true*/
(function (root) {
    "use strict";

    var GLOBAL_KEY = "fibs";
    var IAC = 255;
    var CLIP_VERSION = "1008";

    var fibs = {};

    function isInteger(o) {
        return o === parseInt(o, 10);
    }

    function isString(o) {
        return Object.prototype.toString.call(o) == '[object String]';
    }

    function ab2int8a(buf) {
        return new Uint8Array(buf);
    }

    function int8a2str(int8a) {
        return String.fromCharCode.apply(null, int8a);
    }

    function str2int16a(str) {
        var buf = new ArrayBuffer(str.length * 2); // 2 bytes for each char
        var bufView = new Uint16Array(buf);
        for (var i = 0, strLen = str.length; i < strLen; i++) {
            bufView[i] = str.charCodeAt(i);
        }
        return bufView;
    }

    function Message(type) {
        this._type = type;
    }

    Object.defineProperty(Message.prototype, "type", {
        get: function() {
            return this._type;
        },
        enumerable: true
    });

    Message.prototype.toJSON = function () {
        var obj = {};

        Object.keys(this).forEach(function (property) {
            if (property.substr(0, 1) != "_") {
                obj[property] = this[property];
            }
        }, this);

        obj.type = this.type;

        return obj;
    };

    function ClipMessage(name, id, text) {

        Message.call(this, "CLIP");

        Object.defineProperties(this, {
            "name": {
                value: name,
                writable: false,
                enumerable: true
            },
            "id": {
                value: id,
                writable: false,
                enumerable: true
            },
            "text": {
                value: text,
                writable: false,
                enumerable: true
            },
            "trueClip": {
                get: function () {
                    var t = this.id;
                    return isInteger(t) && t > 0 && t <= 19;
                },
                enumerable: true
            }
        });
    }

    ClipMessage.prototype = Object.create(Message.prototype);
    ClipMessage.prototype.tokenize = function () {
        if (!this._tokens) {
            this._tokens = this.text.split(/\s+/);
        }

        return this._tokens;
    };

    function IacMessage(iacArray) {
        Message.call(this, "IAC");

        Object.defineProperty(this, "sequence", {
            value: iacArray,
            writable: false,
            enumerable: true
        });
    }

    IacMessage.prototype = Object.create(Message.prototype);

    function NewLineMessage(newLine) {
        Message.call(this, "NEWLINE");

        Object.defineProperty(this, "sequence", {
            value: newLine,
            writable: false,
            enumerable: true
        });
    }

    NewLineMessage.prototype = Object.create(Message.prototype);
    var NEW_LINE_MESSAGE = new NewLineMessage("\r\n");
    Object.freeze(NEW_LINE_MESSAGE);

    function parse(inputData, options) {

        var parseIac = !options || options.parseIac !== false;
        var intArray;

        if (inputData instanceof ArrayBuffer) {
            intArray = ab2int8a(inputData);
        } else if (inputData instanceof Uint8Array) {
            intArray = inputData;
        } else if (isString(inputData)) {
            intArray = str2int16a(inputData);
        } else {
            throw new TypeError("Cannot CLIP-parse data:", inputData);
        }

        var sequences = [];

        if (parseIac) {
            var skip = 0;
            var lastIacSeq = 0;
            for (var index = 0; index < intArray.length; index++) {
                var b = intArray[index];
                if (skip > 0) {
                    skip--;
                }
                else if (b === IAC) {
                    var nonIac = index - lastIacSeq;
                    if (nonIac > 0) {
                        Array.prototype.push.apply(sequences, regularSequence(intArray.subarray(lastIacSeq, index), options, true));
                    }

                    lastIacSeq = Math.min(index + 3, intArray.length);
                    skip = lastIacSeq - index - 1;
                    sequences.push(iacSequence(intArray.subarray(index, lastIacSeq)));
                }
            }

            if (lastIacSeq < intArray.length) {
                Array.prototype.push.apply(sequences, regularSequence(intArray.subarray(lastIacSeq, intArray.length), options));
            }
        } else {
            Array.prototype.push.apply(sequences, regularSequence(intArray, options));
        }

        return sequences;

    }

    function genericTrueClipParser(id, rest, line) {
        return new ClipMessage("CLIP Message", id, line);
    }

    function trueClipParser(id) {
        return trueClipParsers[id] || genericTrueClipParser;
    }

    function fauxClipParse(line) {
        var fwParse = firstWordPtn.exec(line);
        var message;
        if (fwParse) {
            var fw = fwParse[1];
            var parser = fauxClipParsers.byFirstWord[fw];
            if (parser) {
                message = parser.call(null, fw, line);
            }
        }

        if (!message) {
            message = unknownClipMessage(line);
        }

        return message;
    }

    function unknownClipMessage(line) {
        return new ClipMessage("UNRECOGNIZED", fibs.CLIP_UNRECOGNIZED, line);
    }

    var trueClipPtn = /^([1-9]|1[0-9])\s+(.+)$/;
    var firstWordPtn = /^\s*(\S+).*$/;
    var trueClipParsers = {
        generic: genericTrueClipParser,
        1: function (id, rest, line) {
            var m = new ClipMessage("CLIP Welcome", id, line);
            var loginData = rest.split(/\s+/);
            var lastLoginTs = parseInt(parseInt(loginData[1]));
            Object.defineProperties(m, {
                loginName: {
                    value: loginData[0],
                    writable: false,
                    enumerable: true
                },
                lastLogin: {
                    value: lastLoginTs,
                    writable: false,
                    enumerable: true
                },
                lastLoginDate: {
                    value: new Date(lastLoginTs * 1000),
                    writable: false,
                    enumerable: true
                },
                lastHost: {
                    value: loginData[2],
                    writable: false,
                    enumerable: true
                }
            });

            return m;
        },
        2: function (id, rest, line) {
            var m = new ClipMessage("CLIP Own Info", id, line);
            var _settings = rest.split(/\s+/);
            if (_settings.length !== 21) {
                return unknownClipMessage(line);
            }
            var settings = {
                name: _settings[0],
                allowpip: _settings[1] === "1",
                autoboard: _settings[2] === "1",
                autodouble: _settings[3] === "1",
                automove: _settings[4] === "1",
                away: _settings[5] === "1",
                bell: _settings[6] === "1",
                crawford: _settings[7] === "1",
                double: _settings[8] === "1",
                experience: parseInt(_settings[9]),
                greedy: _settings[10] === "1",
                moreboards: _settings[11] === "1",
                moves: _settings[12] === "1",
                notify: _settings[13] === "1",
                rating: parseFloat(_settings[14]),
                ratings: _settings[15] === "1",
                ready: _settings[16] === "1",
                redoubles: _settings[17] === "unlimited" ? _settings[17] : parseInt(_settings[17]),
                report: _settings[18] === "1",
                silent: _settings[19] === "1",
                timezone: _settings[20]

            };
            Object.defineProperty(m, "settings", {
                value: settings,
                writable: false,
                enumerable: true
            });

            return m;
        }
    };
    var fauxClipParsers = {
        generic: unknownClipMessage,
        byFirstWord: {
            "login:": function (firstWord, line) {
                if (firstWord === "login:" && line.length > 6 && line.charCodeAt(6) === 32) {
                    return new ClipMessage("Login Prompt", -1, line);
                }

                return null;
            }
        }
    };

    function regularSequence(data, options, bufferOverride) {
        var msg = [];
        var doBuffer = options && isString(options.buffer);
        var b = doBuffer ? options.buffer : "";
        var str = isString(data) ? b + data : b + int8a2str(data);

        str.split(/\r\n/).forEach(function (line, index, array) {
            console.log("line:", line, line.length);
            if (!bufferOverride && doBuffer && index + 1 === array.length && str.length > 1 &&
                str.substring(str.length - 2, str.length) !== "\r\n" && !isNewLineSpecialCase(line)) {
                options.buffer += line;
            } else {
                try {
                    var result = trueClipPtn.exec(line);
                    if (result) {
                        var id = parseInt(result[1]);
                        var parser = trueClipParser(id);
                        var m = parser.call(null, id, result[2], result.input);
                        msg.push(m);
                    } else if (line.length > 0) {
                        msg.push(fauxClipParse(line));
                    } else {
                        msg.push(NEW_LINE_MESSAGE);
                    }
                } finally {
                    clearBuffer(options);
                }
            }
        });

        return msg;
    }

    function iacSequence(data) {

        var iacMsg = new IacMessage(data);
        Object.freeze(iacMsg);

        return iacMsg;
    }

    function isNewLineSpecialCase(line) {
        return line === "login: ";
    }

    function clearBuffer(options) {
        if (options !== undefined && options.buffer !== undefined) {
            options.buffer = "";
        }
    }

    fibs.CLIP_VERSION = CLIP_VERSION;
    fibs.Message = Message;
    fibs.ClipMessage = ClipMessage;
    fibs.IacMessage = IacMessage;
    fibs.parse = parse;
    fibs.clearBuffer = clearBuffer;
    fibs.trueClipParsers = trueClipParsers;
    fibs.NEW_LINE_MESSAGE = NEW_LINE_MESSAGE;

    // Message ids
    fibs.CLIP_LOGIN_PROMPT = -1;
    fibs.CLIP_WELCOME = 1;
    fibs.CLIP_OWN_INFO = 2;
    fibs.CLIP_UNRECOGNIZED = -99999;

    if (typeof define === "function" && define.amd) {
        define(function () {
            return fibs;
        });
    } else if (typeof module !== "undefined" && typeof require === "function") {
        module.exports = fibs;
    } else {
        (function () {
            var oldGlobal = root[GLOBAL_KEY];
            fibs.noConflict = function () {
                root[GLOBAL_KEY] = oldGlobal;
                return this;
            };
        }());
        root[GLOBAL_KEY] = fibs;
    }
}(this));<commit_msg>int8a<commit_after>/*jshint eqnull:true*/
(function (root) {
    "use strict";

    var GLOBAL_KEY = "fibs";
    var IAC = 255;
    var CLIP_VERSION = "1008";

    var fibs = {};

    function isInteger(o) {
        return o === parseInt(o, 10);
    }

    function isString(o) {
        return Object.prototype.toString.call(o) == '[object String]';
    }

    function ab2int8a(buf) {
        return new Uint8Array(buf);
    }

    function int8a2str(int8a) {
        return String.fromCharCode.apply(null, int8a);
    }

    function str2int16a(str) {
        var buf = new ArrayBuffer(str.length); // 2 bytes for each char
        var bufView = new Uint8Array(buf);
        for (var i = 0, strLen = str.length; i < strLen; i++) {
            bufView[i] = str.charCodeAt(i);
        }
        return bufView;
    }

    function Message(type) {
        this._type = type;
    }

    Object.defineProperty(Message.prototype, "type", {
        get: function() {
            return this._type;
        },
        enumerable: true
    });

    Message.prototype.toJSON = function () {
        var obj = {};

        Object.keys(this).forEach(function (property) {
            if (property.substr(0, 1) != "_") {
                obj[property] = this[property];
            }
        }, this);

        obj.type = this.type;

        return obj;
    };

    function ClipMessage(name, id, text) {

        Message.call(this, "CLIP");

        Object.defineProperties(this, {
            "name": {
                value: name,
                writable: false,
                enumerable: true
            },
            "id": {
                value: id,
                writable: false,
                enumerable: true
            },
            "text": {
                value: text,
                writable: false,
                enumerable: true
            },
            "trueClip": {
                get: function () {
                    var t = this.id;
                    return isInteger(t) && t > 0 && t <= 19;
                },
                enumerable: true
            }
        });
    }

    ClipMessage.prototype = Object.create(Message.prototype);
    ClipMessage.prototype.tokenize = function () {
        if (!this._tokens) {
            this._tokens = this.text.split(/\s+/);
        }

        return this._tokens;
    };

    function IacMessage(iacArray) {
        Message.call(this, "IAC");

        Object.defineProperty(this, "sequence", {
            value: iacArray,
            writable: false,
            enumerable: true
        });
    }

    IacMessage.prototype = Object.create(Message.prototype);

    function NewLineMessage(newLine) {
        Message.call(this, "NEWLINE");

        Object.defineProperty(this, "sequence", {
            value: newLine,
            writable: false,
            enumerable: true
        });
    }

    NewLineMessage.prototype = Object.create(Message.prototype);
    var NEW_LINE_MESSAGE = new NewLineMessage("\r\n");
    Object.freeze(NEW_LINE_MESSAGE);

    function parse(inputData, options) {

        var parseIac = !options || options.parseIac !== false;
        var intArray;

        if (inputData instanceof ArrayBuffer) {
            intArray = ab2int8a(inputData);
        } else if (inputData instanceof Uint8Array) {
            intArray = inputData;
        } else if (isString(inputData)) {
            intArray = str2int16a(inputData);
        } else {
            throw new TypeError("Cannot CLIP-parse data:", inputData);
        }

        var sequences = [];

        if (parseIac) {
            var skip = 0;
            var lastIacSeq = 0;
            for (var index = 0; index < intArray.length; index++) {
                var b = intArray[index];
                if (skip > 0) {
                    skip--;
                }
                else if (b === IAC) {
                    var nonIac = index - lastIacSeq;
                    if (nonIac > 0) {
                        Array.prototype.push.apply(sequences, regularSequence(intArray.subarray(lastIacSeq, index), options, true));
                    }

                    lastIacSeq = Math.min(index + 3, intArray.length);
                    skip = lastIacSeq - index - 1;
                    sequences.push(iacSequence(intArray.subarray(index, lastIacSeq)));
                }
            }

            if (lastIacSeq < intArray.length) {
                Array.prototype.push.apply(sequences, regularSequence(intArray.subarray(lastIacSeq, intArray.length), options));
            }
        } else {
            Array.prototype.push.apply(sequences, regularSequence(intArray, options));
        }

        return sequences;

    }

    function genericTrueClipParser(id, rest, line) {
        return new ClipMessage("CLIP Message", id, line);
    }

    function trueClipParser(id) {
        return trueClipParsers[id] || genericTrueClipParser;
    }

    function fauxClipParse(line) {
        var fwParse = firstWordPtn.exec(line);
        var message;
        if (fwParse) {
            var fw = fwParse[1];
            var parser = fauxClipParsers.byFirstWord[fw];
            if (parser) {
                message = parser.call(null, fw, line);
            }
        }

        if (!message) {
            message = unknownClipMessage(line);
        }

        return message;
    }

    function unknownClipMessage(line) {
        return new ClipMessage("UNRECOGNIZED", fibs.CLIP_UNRECOGNIZED, line);
    }

    var trueClipPtn = /^([1-9]|1[0-9])\s+(.+)$/;
    var firstWordPtn = /^\s*(\S+).*$/;
    var trueClipParsers = {
        generic: genericTrueClipParser,
        1: function (id, rest, line) {
            var m = new ClipMessage("CLIP Welcome", id, line);
            var loginData = rest.split(/\s+/);
            var lastLoginTs = parseInt(parseInt(loginData[1]));
            Object.defineProperties(m, {
                loginName: {
                    value: loginData[0],
                    writable: false,
                    enumerable: true
                },
                lastLogin: {
                    value: lastLoginTs,
                    writable: false,
                    enumerable: true
                },
                lastLoginDate: {
                    value: new Date(lastLoginTs * 1000),
                    writable: false,
                    enumerable: true
                },
                lastHost: {
                    value: loginData[2],
                    writable: false,
                    enumerable: true
                }
            });

            return m;
        },
        2: function (id, rest, line) {
            var m = new ClipMessage("CLIP Own Info", id, line);
            var _settings = rest.split(/\s+/);
            if (_settings.length !== 21) {
                return unknownClipMessage(line);
            }
            var settings = {
                name: _settings[0],
                allowpip: _settings[1] === "1",
                autoboard: _settings[2] === "1",
                autodouble: _settings[3] === "1",
                automove: _settings[4] === "1",
                away: _settings[5] === "1",
                bell: _settings[6] === "1",
                crawford: _settings[7] === "1",
                double: _settings[8] === "1",
                experience: parseInt(_settings[9]),
                greedy: _settings[10] === "1",
                moreboards: _settings[11] === "1",
                moves: _settings[12] === "1",
                notify: _settings[13] === "1",
                rating: parseFloat(_settings[14]),
                ratings: _settings[15] === "1",
                ready: _settings[16] === "1",
                redoubles: _settings[17] === "unlimited" ? _settings[17] : parseInt(_settings[17]),
                report: _settings[18] === "1",
                silent: _settings[19] === "1",
                timezone: _settings[20]

            };
            Object.defineProperty(m, "settings", {
                value: settings,
                writable: false,
                enumerable: true
            });

            return m;
        }
    };
    var fauxClipParsers = {
        generic: unknownClipMessage,
        byFirstWord: {
            "login:": function (firstWord, line) {
                if (firstWord === "login:" && line.length > 6 && line.charCodeAt(6) === 32) {
                    return new ClipMessage("Login Prompt", -1, line);
                }

                return null;
            }
        }
    };

    function regularSequence(data, options, bufferOverride) {
        var msg = [];
        var doBuffer = options && isString(options.buffer);
        var b = doBuffer ? options.buffer : "";
        var str = isString(data) ? b + data : b + int8a2str(data);

        str.split(/\r\n/).forEach(function (line, index, array) {
            console.log("line:", line, line.length);
            if (!bufferOverride && doBuffer && index + 1 === array.length && str.length > 1 &&
                str.substring(str.length - 2, str.length) !== "\r\n" && !isNewLineSpecialCase(line)) {
                options.buffer += line;
            } else {
                try {
                    var result = trueClipPtn.exec(line);
                    if (result) {
                        var id = parseInt(result[1]);
                        var parser = trueClipParser(id);
                        var m = parser.call(null, id, result[2], result.input);
                        msg.push(m);
                    } else if (line.length > 0) {
                        msg.push(fauxClipParse(line));
                    } else {
                        msg.push(NEW_LINE_MESSAGE);
                    }
                } finally {
                    clearBuffer(options);
                }
            }
        });

        return msg;
    }

    function iacSequence(data) {

        var iacMsg = new IacMessage(data);
        Object.freeze(iacMsg);

        return iacMsg;
    }

    function isNewLineSpecialCase(line) {
        return line === "login: ";
    }

    function clearBuffer(options) {
        if (options !== undefined && options.buffer !== undefined) {
            options.buffer = "";
        }
    }

    fibs.CLIP_VERSION = CLIP_VERSION;
    fibs.Message = Message;
    fibs.ClipMessage = ClipMessage;
    fibs.IacMessage = IacMessage;
    fibs.parse = parse;
    fibs.clearBuffer = clearBuffer;
    fibs.trueClipParsers = trueClipParsers;
    fibs.NEW_LINE_MESSAGE = NEW_LINE_MESSAGE;

    // Message ids
    fibs.CLIP_LOGIN_PROMPT = -1;
    fibs.CLIP_WELCOME = 1;
    fibs.CLIP_OWN_INFO = 2;
    fibs.CLIP_UNRECOGNIZED = -99999;

    if (typeof define === "function" && define.amd) {
        define(function () {
            return fibs;
        });
    } else if (typeof module !== "undefined" && typeof require === "function") {
        module.exports = fibs;
    } else {
        (function () {
            var oldGlobal = root[GLOBAL_KEY];
            fibs.noConflict = function () {
                root[GLOBAL_KEY] = oldGlobal;
                return this;
            };
        }());
        root[GLOBAL_KEY] = fibs;
    }
}(this));<|endoftext|>


<commit_before>'use strict';

/*
 * State Declarations: Authorization Pages
 *
 * Set up the states for auth routes, such as the
 * login page, forgot password and other auth states.
 * Uses ui-roter's $stateProvider.
 *
 * Set each state's title (used in the config for the html <title>).
 *
 * Set auth access for each state.
 */

var app = angular.module('app.router.auth', [
    'rcAuth.constants',
    'app.auth'
]);
app.config(['$stateProvider', 'USER_ROLES',
    function ($stateProvider, USER_ROLES) {

        /*  Abstract Auth Route */
        $stateProvider.state('app.auth', {
            url: '',
            abstract: true,
            data: {authorizedRoles: USER_ROLES.guest},
            views: {
                'header@app.auth': {
                    templateUrl: 'app/views/auth/authHeader/authHeader.html',
                    controller: 'AuthHeaderCtrl'
                },
                'layout@': {
                    templateUrl: 'app/views/auth/authLayout/authLayout.html',
                    controller: 'AuthLayoutCtrl'
                },
                'footer@app.auth': {
                    templateUrl: 'app/views/auth/authFooter/authFooter.html',
                    controller: 'AuthFooterCtrl'
                }
            }
        });

        /* Login / Authentication Related States */

        $stateProvider.state('app.auth.signup', {
            bodyClass: 'auth signup',
            title: 'Sign Up',
            url: '/signup',
            views: {
                'content@app.auth': {
                    templateUrl: 'app/views/auth/signup/signup.html',
                    controller: 'AuthSignupCtrl'
                }
            }
        });

        $stateProvider.state('app.auth.signup.invite', {
            bodyClass: 'auth signup',
            title: 'You have been invited!',
            url: '/:token',
            views: {
                'content@app.auth': {
                    templateUrl: 'app/views/auth/playerInvite/playerInvite.html',
                    controller: 'AuthPlayerInviteCtrl'
                },
                'signupform@app.auth.signup.invite': {
                    templateUrl: 'app/views/auth/signup/signupForm.html'
                }
            },
            resolve: {
                $q: '$q',
                ApiRoutesEmails: 'ApiRoutesEmails',
                $stateParams: '$stateParams',
                InvitationData: function($q, $stateParams, ApiRoutesEmails) {
                    return $q(function(resolve, reject) {
                        ApiRoutesEmails.validateInviteToken($stateParams.token).then(function (result) {
                            resolve(result.invite);
                            console.log(result);
                        }, function(error) {
                            console.log(error);
                            resolve(error);
                        });
                    });
                }
            }
        });

        $stateProvider.state('app.auth.signup.confirmEmail', {
            title: 'Please Confirm Your Email',
            url: '/please-confirm-email'
        });

        $stateProvider.state('app.auth.signup.success', {
            title: 'Success! Your Email is Confirmed',
            url: '/success'
        });

        $stateProvider.state('app.auth.login', {
            bodyClass: 'auth login',
            title: 'Login',
            url: '/login',
            views: {
                'content@app.auth': {
                    templateUrl: 'app/views/auth/login/login.html'
                }
            }/*,
            resolve: {
                $q: '$q',
                $rootScope: '$rootScope',
                AUTH_EVENTS: 'AUTH_EVENTS',
                alreadyLoggedIn: function(initUser, $rootScope, AUTH_EVENTS, $q, AuthService) {
                    return $q(function(resolve, reject) {
                        if(AuthService.getUser()) {
                            $rootScope.$broadcast(AUTH_EVENTS.loginSuccess);
                            resolve(true);
                        } else {
                            resolve(false);
                        }
                    });
                }
            }*/
        });

        $stateProvider.state('app.auth.login.locked', {
            title: 'Account Locked',
            url: '/account-locked'
        });

        $stateProvider.state('app.auth.login.forgotPassword', {
            title: 'Forgot Password',
            url: '/forgot-password'
        });

        $stateProvider.state('app.auth.login.forgotPassword.resetEmailSent', {
            title: 'Reset Instructions Have Been Sent',
            url: '/reset-instructions-sent'
        });

        $stateProvider.state('app.auth.login.forgotPassword.changePassword', {
            title: 'Change Your Password',
            url: '/change-password'
        });

        // This should catch incoming requests,
        // Trigger the logout method and then redirect
        // to public.
        $stateProvider.state('app.auth.logout', {
            bodyClass: 'auth logout',
            url: '/logout'
        });

        $stateProvider.state('app.auth.resetPassword', {
            title: 'Reset Password',
            url: '/reset_password/:usertoken',
            views: {
                'content@app.auth': {
                    templateUrl: 'app/views/auth/resetPassword/resetPassword.html',
                    controller: 'ResetPasswordCtrl'
                },
                'signupform@app.auth.resetPassword': {
                    templateUrl: 'app/views/auth/resetPassword/resetPasswordForm.html'
                }
            },
            resolve: {
                $q: '$q',
                $rootScope: '$rootScope',
                $state: '$state'
            }
        });

    }]);<commit_msg>Missed loggin controller.<commit_after>'use strict';

/*
 * State Declarations: Authorization Pages
 *
 * Set up the states for auth routes, such as the
 * login page, forgot password and other auth states.
 * Uses ui-roter's $stateProvider.
 *
 * Set each state's title (used in the config for the html <title>).
 *
 * Set auth access for each state.
 */

var app = angular.module('app.router.auth', [
    'rcAuth.constants',
    'app.auth'
]);
app.config(['$stateProvider', 'USER_ROLES',
    function ($stateProvider, USER_ROLES) {

        /*  Abstract Auth Route */
        $stateProvider.state('app.auth', {
            url: '',
            abstract: true,
            data: {authorizedRoles: USER_ROLES.guest},
            views: {
                'header@app.auth': {
                    templateUrl: 'app/views/auth/authHeader/authHeader.html',
                    controller: 'AuthHeaderCtrl'
                },
                'layout@': {
                    templateUrl: 'app/views/auth/authLayout/authLayout.html',
                    controller: 'AuthLayoutCtrl'
                },
                'footer@app.auth': {
                    templateUrl: 'app/views/auth/authFooter/authFooter.html',
                    controller: 'AuthFooterCtrl'
                }
            }
        });

        /* Login / Authentication Related States */

        $stateProvider.state('app.auth.signup', {
            bodyClass: 'auth signup',
            title: 'Sign Up',
            url: '/signup',
            views: {
                'content@app.auth': {
                    templateUrl: 'app/views/auth/signup/signup.html',
                    controller: 'AuthSignupCtrl'
                }
            }
        });

        $stateProvider.state('app.auth.signup.invite', {
            bodyClass: 'auth signup',
            title: 'You have been invited!',
            url: '/:token',
            views: {
                'content@app.auth': {
                    templateUrl: 'app/views/auth/playerInvite/playerInvite.html',
                    controller: 'AuthPlayerInviteCtrl'
                },
                'signupform@app.auth.signup.invite': {
                    templateUrl: 'app/views/auth/signup/signupForm.html'
                }
            },
            resolve: {
                $q: '$q',
                ApiRoutesEmails: 'ApiRoutesEmails',
                $stateParams: '$stateParams',
                InvitationData: function($q, $stateParams, ApiRoutesEmails) {
                    return $q(function(resolve, reject) {
                        ApiRoutesEmails.validateInviteToken($stateParams.token).then(function (result) {
                            resolve(result.invite);
                            console.log(result);
                        }, function(error) {
                            console.log(error);
                            resolve(error);
                        });
                    });
                }
            }
        });

        $stateProvider.state('app.auth.signup.confirmEmail', {
            title: 'Please Confirm Your Email',
            url: '/please-confirm-email'
        });

        $stateProvider.state('app.auth.signup.success', {
            title: 'Success! Your Email is Confirmed',
            url: '/success'
        });

        $stateProvider.state('app.auth.login', {
            bodyClass: 'auth login',
            title: 'Login',
            url: '/login',
            views: {
                'content@app.auth': {
                    templateUrl: 'app/views/auth/login/login.html',
                    controller: 'AuthLoginCtrl'
                }
            }/*,
            resolve: {
                $q: '$q',
                $rootScope: '$rootScope',
                AUTH_EVENTS: 'AUTH_EVENTS',
                alreadyLoggedIn: function(initUser, $rootScope, AUTH_EVENTS, $q, AuthService) {
                    return $q(function(resolve, reject) {
                        if(AuthService.getUser()) {
                            $rootScope.$broadcast(AUTH_EVENTS.loginSuccess);
                            resolve(true);
                        } else {
                            resolve(false);
                        }
                    });
                }
            }*/
        });

        $stateProvider.state('app.auth.login.locked', {
            title: 'Account Locked',
            url: '/account-locked'
        });

        $stateProvider.state('app.auth.login.forgotPassword', {
            title: 'Forgot Password',
            url: '/forgot-password'
        });

        $stateProvider.state('app.auth.login.forgotPassword.resetEmailSent', {
            title: 'Reset Instructions Have Been Sent',
            url: '/reset-instructions-sent'
        });

        $stateProvider.state('app.auth.login.forgotPassword.changePassword', {
            title: 'Change Your Password',
            url: '/change-password'
        });

        // This should catch incoming requests,
        // Trigger the logout method and then redirect
        // to public.
        $stateProvider.state('app.auth.logout', {
            bodyClass: 'auth logout',
            url: '/logout'
        });

        $stateProvider.state('app.auth.resetPassword', {
            title: 'Reset Password',
            url: '/reset_password/:usertoken',
            views: {
                'content@app.auth': {
                    templateUrl: 'app/views/auth/resetPassword/resetPassword.html',
                    controller: 'ResetPasswordCtrl'
                },
                'signupform@app.auth.resetPassword': {
                    templateUrl: 'app/views/auth/resetPassword/resetPasswordForm.html'
                }
            },
            resolve: {
                $q: '$q',
                $rootScope: '$rootScope',
                $state: '$state'
            }
        });

    }]);<|endoftext|>


<commit_before><commit_msg>include "once" for React.events.mixin functions to be applied within the "events" mixin<commit_after><|endoftext|>


<commit_before>angular.module('starter.controllers')

.controller('profileCtrl', function($scope, $state, $stateParams, $ionicHistory, Profile) {
  /*Dealings of the Ionic to clear navigation history*/
  $ionicHistory.clearHistory();

  /*Profile function to get the user from the service*/
  $scope.user = Profile.getUser();

  /*Function to log out with the Facebook on the app*/
  $scope.fbLogout = function() {
    $scope.user = Profile.setUser(null);
    console.log($scope.user);
    $ionicHistory.clearHistory();
    $ionicHistory.nextViewOptions({
      disableBack: true
    });
    $state.go('menu.home');
  }

  /*Function to open in app an link*/
  $scope.inAppOpenLink = function(url) {
    window.open(url, '_system', 'location=yes');
  }
})<commit_msg>Minor correction<commit_after>angular.module('starter.controllers')

.controller('profileCtrl', function($scope, $state, $stateParams, $ionicHistory, Profile) {
  /*Dealings of the Ionic to clear navigation history*/
  $ionicHistory.clearHistory();

  /*Profile function to get the user from the service*/
  $scope.user = Profile.getUser();

  /*Function to log out with the Facebook on the app*/
  $scope.fbLogout = function() {
    $scope.user = Profile.setUser(null);
    console.log($scope.user);
    $ionicHistory.clearHistory();
    $ionicHistory.nextViewOptions({
      disableBack: true
    });
    $state.go('menu.home');
  }

  /*Function to open in app an link*/
  $scope.inAppOpenLink = function(url) {
    var ref = cordova.InAppBrowser.open(url, '_system', 'location=yes');
    document.addEventListener("deviceready", onDeviceReady, false);
    function onDeviceReady() {
      console.log("window.open works well");
      window.open = cordova.InAppBrowser.open;
      window.open(url, '_system', 'location=yes');
    }
  }
})<|endoftext|>


<commit_before><commit_msg>Cookie low security signing<commit_after><|endoftext|>


<commit_before><commit_msg>keep calling the callback<commit_after><|endoftext|>


<commit_before><commit_msg>Removed old drag n drop code<commit_after><|endoftext|>


<commit_before><commit_msg>Brighten drums<commit_after><|endoftext|>


<commit_before>var QRCoder = QRCoder || {};

QRCoder.showOverlay = function (text) {
  var threwException = false;
  var qrSize = 1;

  do {
    try {
      var qr = qrcode(qrSize, "L");
      qr.addData(text);
      qr.make();
      var imgCode = this.createElementFromHTML(qr.createImgTag(4));
      threwException = false;
    } catch (error) {
      qrSize++;
      threwException = true;
    }
  } while (threwException && qrSize <= 10);

  if (qrSize <= 10) {
    var divShader = document.body.appendChild(document.createElement("div"));
    divShader.style.position = "fixed";
    divShader.style.top = "0";
    divShader.style.left = "0";
    divShader.style.right = "0";
    divShader.style.bottom = "0";
    divShader.style.backgroundColor = "rgba(0, 0, 0, 0.33)";
    divShader.style.backgroundImage = "url('" + imgCode.childNodes[0].src + "')";
    divShader.style.backgroundRepeat = "no-repeat";
    divShader.style.backgroundPosition = "center";
    divShader.style.zIndex = "10000000";
    divShader.addEventListener("click", function (event) {
      divShader.deleteSelf();
    }, false);
  }
};

QRCoder.createElementFromHTML = function (html) {
  var fragment = document.createDocumentFragment();

  var element = document.createElement("div");
  element.innerHTML = html;

  while (element.childNodes[0]) {
    fragment.appendChild(element.childNodes[0]);
  }

  return fragment;
}

Node.prototype.removeAllChilds = function () {
  while (this.firstChild) {
    this.firstChild.removeAllChilds();
    this.removeChild(this.firstChild);
  }

  return this;
};

Node.prototype.deleteSelf = function () {
  this.removeAllChilds().parentNode.removeChild(this);

  return this;
};<commit_msg>Added feedback for the user<commit_after>var QRCoder = QRCoder || {};

QRCoder.showOverlay = function (text) {
  var threwException = false;
  var qrSize = 1;

  do {
    try {
      var qr = qrcode(qrSize, "L");
      qr.addData(text);
      qr.make();
      var imgCode = this.createElementFromHTML(qr.createImgTag(4));
      threwException = false;
    } catch (error) {
      qrSize++;
      threwException = true;
    }
  } while (threwException && qrSize <= 10);

  if (qrSize <= 10) {
    var divShader = document.body.appendChild(document.createElement("div"));
    divShader.style.position = "fixed";
    divShader.style.top = "0";
    divShader.style.left = "0";
    divShader.style.right = "0";
    divShader.style.bottom = "0";
    divShader.style.backgroundColor = "rgba(0, 0, 0, 0.33)";
    divShader.style.backgroundImage = "url('" + imgCode.childNodes[0].src + "')";
    divShader.style.backgroundRepeat = "no-repeat";
    divShader.style.backgroundPosition = "center";
    divShader.style.zIndex = "10000000";
    divShader.addEventListener("click", function (event) {
      divShader.deleteSelf();
    }, false);
  } else {
    window.alert("Too much information for the QR code. Try again with less of it.");
  }
};

QRCoder.createElementFromHTML = function (html) {
  var fragment = document.createDocumentFragment();

  var element = document.createElement("div");
  element.innerHTML = html;

  while (element.childNodes[0]) {
    fragment.appendChild(element.childNodes[0]);
  }

  return fragment;
}

Node.prototype.removeAllChilds = function () {
  while (this.firstChild) {
    this.firstChild.removeAllChilds();
    this.removeChild(this.firstChild);
  }

  return this;
};

Node.prototype.deleteSelf = function () {
  this.removeAllChilds().parentNode.removeChild(this);

  return this;
};<|endoftext|>


<commit_before>"use strict";

let Ci = Components.interfaces;
let Cc = Components.classes;
let Cu = Components.utils;
let Cr = Components.results;

//Cu.import("resource:///modules/errUtils.js");
//Cu.import("resource://emic/stdlib/misc.js");
Cu.import("resource://emic/stdlib/msgHdrUtils.js");

var MailListener = {
    msgAdded: function(aMsgHdr) {
        if( !aMsgHdr.isRead )  {
            emicBackgroundWorkerObj.setInbox(aMsgHdr.folder);
//            alert("Got new mail. Look at aMsgHdr's properties for more details.");
//            alert("aMsgHdr.folder.prettiestName: " + aMsgHdr.folder.prettiestName);
            emicBackgroundWorkerObj.setExpirationDate(aMsgHdr);
        }
    }
};

var copyListener = {
    OnStartCopy: function() {
        document.getElementById("emic-progress").value = 0;
        document.getElementById("emic-statusbarpanel").hidden = false;
//        alert("OnStartCopy()");
    },
    OnProgress: function(aProgress, aProgressMax) {
        document.getElementById("emic-progress").value = 100*aProgress/aProgressMax;
//        alert("OnProgress("+aProgress+", "+aProgressMax+")");
    },
    SetMessageKey: function(aKey) {
        //alert("SetMessageKey("+aKey+")");
    },
    SetMessageId: function(aMessageId) {
        //alert("SetMessageId("+aMessageId+")");
    },
    OnStopCopy: function(aStatus) {
        // Check: message successfully copied.
        //alert("OnStopCopy("+aStatus+")");
//        if(status == Cr.NS_OK)
//            alert("End OK");
//        else
//            alert("End Error");
        document.getElementById("emic-progress").value = 100;
        document.getElementById("emic-statusbarpanel").hidden = true;
    }
};

var gLocalIncomingServer = MailServices.accounts.localFoldersServer;
var gLocalMsgAccount = MailServices.accounts.defaultAccount; //FindAccountForServer(gLocalIncomingServer);

var gLocalRootFolder = gLocalIncomingServer.rootMsgFolder.rootFolder; //.QueryInterface(Ci.nsIMsgLocalMailFolder);

var gLocalInboxFolder = gLocalRootFolder.getFoldersWithFlags(Ci.nsMsgFolderFlags.Inbox);

var emicBackgroundWorkerObj = {

    consoleService: Cc["@mozilla.org/consoleservice;1"].getService(Ci.nsIConsoleService),
    notificationService: Cc["@mozilla.org/messenger/msgnotificationservice;1"].getService(Ci.nsIMsgFolderNotificationService),
    tagService: Cc["@mozilla.org/messenger/tagservice;1"].getService(Ci.nsIMsgTagService),
    copyService: Cc["@mozilla.org/messenger/messagecopyservice;1"].getService(Ci.nsIMsgCopyService),
    prefs: Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService).getBranch("extensions.emic."),
    global_strBundle: null,
    backgroundworker_strBundle: null,

    srcFolder: gLocalInboxFolder,
    destFolderName: null,

    setExpirationDate: function(msgHdr) {
        this.consoleService.logStringMessage("emicBackgroundWorkerObj.setExpirationDate() called");

        var stringpropertyidentifier = this.global_strBundle.getString("global.identifier.expirationdate.stringproperty");
//        this.consoleService.logStringMessage("stringpropertyidentifier: " + stringpropertyidentifier);

        if(msgHdr.getStringProperty(stringpropertyidentifier).length <= 0) {
        // extract expiration-date from Mime-Hdr:
            msgHdrGetHeaders(msgHdr, function (aHeaders) {
//                    emicBackgroundWorkerObj.consoleService.logStringMessage("   msgHdrGetHeaders called for Subject: '" + aHeaders.get("subject") + "'");
                var hasgetidentifier = emicBackgroundWorkerObj.global_strBundle.getString("global.identifier.expirationdate.mailheader.hasget");
                var stringpropertyidentifier = emicBackgroundWorkerObj.global_strBundle.getString("global.identifier.expirationdate.stringproperty");
//                    emicBackgroundWorkerObj.consoleService.logStringMessage("hasgetidentifier: " + hasgetidentifier);
//                    emicBackgroundWorkerObj.consoleService.logStringMessage("stringpropertyidentifier: " + stringpropertyidentifier);

                if(aHeaders.has(hasgetidentifier)) {
//                        emicBackgroundWorkerObj.consoleService.logStringMessage("   ^ has expiration date, set it to: " + aHeaders.get(hasgetidentifier));
                    msgHdr.setStringProperty(
                        stringpropertyidentifier,
                        aHeaders.get(hasgetidentifier)
                    );
                }
                else {
//                        emicBackgroundWorkerObj.consoleService.logStringMessage("   ^ has no expiration date; set it to never");
                    msgHdr.setStringProperty(
                        stringpropertyidentifier,
                        emicBackgroundWorkerObj.global_strBundle.getString("global.identifier.never")
                    );
                }

            });
        }
    },

    processExpiredMails: function() {
        this.consoleService.logStringMessage("emicBackgroundWorkerObj.processExpiredMails() called");
//        this.consoleService.logStringMessage("this.destFolderName: " + this.destFolderName);

        if(!this.srcFolder)
            return null;

        var now = new Date();
        var msgArray = this.srcFolder.messages;
        var expired_mails = Cc["@mozilla.org/array;1"].createInstance(Ci.nsIMutableArray);

        while( msgArray.hasMoreElements() ) {
            var msgHdr = msgArray.getNext().QueryInterface(Ci.nsIMsgDBHdr);
            var expdatestr = msgHdr.getStringProperty(this.global_strBundle.getString("global.identifier.expirationdate.stringproperty"));

            if(expdatestr != 0 && expdatestr.length > 0 && !(expdatestr == this.global_strBundle.getString("global.identifier.never"))) {
                var expiration_date = new Date(expdatestr);
                //search for expired mails:
                if(expiration_date < now) {
                    expired_mails.appendElement(msgHdr, false);
                }
            }
        }

        if(expired_mails.length > 0) {
            //add keywords to messages:
            if(this.prefs.getBoolPref("expiredmails.addtag")) {
                this.consoleService.logStringMessage(" Try to tag " + expired_mails.length + " mails.");
                this.srcFolder.addKeywordsToMessages(expired_mails, this.global_strBundle.getString("global.tag.expired.key"));
            }

            //move expired mails to folder:
            if(this.prefs.getBoolPref("expiredmails.move")) {
                var destfolder = null;

                try {
                    destfolder = gLocalRootFolder.getChildNamed(this.destFolderName);
                }
                catch(e) {
                    this.consoleService.logStringMessage(" Destination folder not exists, try to create it (" + e + ").");
                    if(!destfolder) {
                        var msgWindow = Cc["@mozilla.org/messenger/msgwindow;1"].createInstance().QueryInterface(Ci.nsIMsgWindow);
                        gLocalRootFolder.createSubfolder(this.destFolderName,msgWindow);
                        destfolder = gLocalRootFolder.getChildNamed(this.destFolderName);
                    }
                }
                this.consoleService.logStringMessage(" Try to move " + expired_mails.length + " mails from Src: " + this.srcFolder.prettiestName + " --> Dest: " + destfolder.prettiestName + ".");
                if(this.srcFolder && destfolder)
                    this.copyService.CopyMessages(this.srcFolder, expired_mails, destfolder, true, copyListener, null, false);
            }
        }
    },

    selectChanged: function(e) {
//        this.consoleService.logStringMessage("emicBackgroundWorkerObj.selectChanged() called");
        var folder = gFolderDisplay.selectedMessage.folder;
        this.setInbox(folder);
    },

    setInbox: function(inboxfolder) {
//        this.consoleService.logStringMessage("emicBackgroundWorkerObj.setInbox() called");
//        this.consoleService.logStringMessage("inboxfolder.prettiestName: " + inboxfolder.prettiestName);
        if(inboxfolder.flags & Ci.nsMsgFolderFlags.Inbox) {
//            this.consoleService.logStringMessage("emicBackgroundWorkerObj.setInbox(): " + inboxfolder.prettiestName + " is of type inbox");
            this.srcFolder = inboxfolder;
        }
    },

    setDestFolder: function(destfoldername) {
//        this.consoleService.logStringMessage("emicBackgroundWorkerObj.setDestFolder() called");
        this.destFolderName = destfoldername;
    },

    shutdown: function() {
//        this.consoleService.logStringMessage("emicBackgroundWorkerObj.shutdown() called");
        this.prefs.removeObserver("", this);
    },

    observe: function(aSubject, aTopic, aData) {
    // aSubject is the nsIPrefBranch we're observing (after appropriate QI)
    // aData is the name of the pref that's been changed (relative to aSubject)
//        this.consoleService.logStringMessage("emicBackgroundWorkerObj.observe() called");
        if (aTopic != "nsPref:changed")
            return;

        switch(aData) {
        case "expiredmails.move.destfoldername":
            this.setDestFolder(this.prefs.getCharPref("expiredmails.move.destfoldername"));
            break;
        case "expiredmails.addtag.colorcode":
            this.tagService.setColorForKey(this.global_strBundle.getString("global.tag.expired.key"), this.prefs.getCharPref("expiredmails.addtag.colorcode"));
            break;
        }
    },

    init: function() {
        this.consoleService.logStringMessage("emicBackgroundWorkerObj.init() called");
        this.global_strBundle           = document.getElementById("emic-strings-global");
        this.backgroundworker_strBundle = document.getElementById("emic-strings-backgroundworker");

        this.prefs.QueryInterface(Ci.nsIPrefBranch);
        this.prefs.addObserver("", this, false);
        this.setDestFolder(this.prefs.getCharPref("expiredmails.move.destfoldername"));

        this.notificationService.addListener(MailListener, this.notificationService.msgAdded);

        //set up a Tag
        if(!this.tagService.isValidKey(this.global_strBundle.getString("global.tag.expired.key"))) {
            this.tagService.addTagForKey(this.global_strBundle.getString("global.tag.expired.key"), this.backgroundworker_strBundle.getString("backgroundworker.tag.expired.label"), this.prefs.getCharPref("expiredmails.addtag.colorcode"), "");
        }

        var statBar = document.getElementById("status-bar");
	    var statPanel = document.getElementById("emic-statusbarpanel");
        statBar.insertBefore(statPanel, null);

        this.processExpiredMails();
    }
}

window.addEventListener("load", function() {emicBackgroundWorkerObj.init()}, false);
window.setInterval(function(){emicBackgroundWorkerObj.processExpiredMails();}, 60000); //update every minute
document.getElementById('threadTree').addEventListener('select', function(e){emicBackgroundWorkerObj.selectChanged(e);}, false);
window.addEventListener("unload", function(e) { emicBackgroundWorkerObj.shutdown(); }, false);<commit_msg>V0.1.3.09<commit_after>"use strict";

let Ci = Components.interfaces;
let Cc = Components.classes;
let Cu = Components.utils;
let Cr = Components.results;

//Cu.import("resource:///modules/errUtils.js");
//Cu.import("resource://emic/stdlib/misc.js");
Cu.import("resource://emic/stdlib/msgHdrUtils.js");

var MailListener = {
    msgAdded: function(aMsgHdr) {
        if( !aMsgHdr.isRead )  {
//            emicBackgroundWorkerObj.setInbox(aMsgHdr.folder);
//            alert("Got new mail. Look at aMsgHdr's properties for more details.");
//            alert("aMsgHdr.folder.prettiestName: " + aMsgHdr.folder.prettiestName);
            emicBackgroundWorkerObj.setExpirationDate(aMsgHdr);
        }
    }
};

var copyListener = {
    OnStartCopy: function() {
        document.getElementById("emic-progress").value = 0;
        document.getElementById("emic-statusbarpanel").hidden = false;
//        alert("OnStartCopy()");
    },
    OnProgress: function(aProgress, aProgressMax) {
        document.getElementById("emic-progress").value = 100*aProgress/aProgressMax;
//        alert("OnProgress("+aProgress+", "+aProgressMax+")");
    },
    SetMessageKey: function(aKey) {
        //alert("SetMessageKey("+aKey+")");
    },
    SetMessageId: function(aMessageId) {
        //alert("SetMessageId("+aMessageId+")");
    },
    OnStopCopy: function(aStatus) {
        // Check: message successfully copied.
        //alert("OnStopCopy("+aStatus+")");
//        if(status == Cr.NS_OK)
//            alert("End OK");
//        else
//            alert("End Error");
        document.getElementById("emic-progress").value = 100;
        document.getElementById("emic-statusbarpanel").hidden = true;
    }
};

var emicBackgroundWorkerObj = {

    consoleService: Cc["@mozilla.org/consoleservice;1"].getService(Ci.nsIConsoleService),
    notificationService: Cc["@mozilla.org/messenger/msgnotificationservice;1"].getService(Ci.nsIMsgFolderNotificationService),
    tagService: Cc["@mozilla.org/messenger/tagservice;1"].getService(Ci.nsIMsgTagService),
    copyService: Cc["@mozilla.org/messenger/messagecopyservice;1"].getService(Ci.nsIMsgCopyService),
    prefs: Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService).getBranch("extensions.emic."),
    accountManager: Cc["@mozilla.org/messenger/account-manager;1"].getService(Ci.nsIMsgAccountManager),
    global_strBundle: null,
    backgroundworker_strBundle: null,

    destFolderName: null,

    setExpirationDate: function(msgHdr) {
        this.consoleService.logStringMessage("emicBackgroundWorkerObj.setExpirationDate() called");

        var stringpropertyidentifier = this.global_strBundle.getString("global.identifier.expirationdate.stringproperty");
//        this.consoleService.logStringMessage("stringpropertyidentifier: " + stringpropertyidentifier);

        if(msgHdr.getStringProperty(stringpropertyidentifier).length <= 0) {
        // extract expiration-date from Mime-Hdr:
            msgHdrGetHeaders(msgHdr, function (aHeaders) {
//                    emicBackgroundWorkerObj.consoleService.logStringMessage("   msgHdrGetHeaders called for Subject: '" + aHeaders.get("subject") + "'");
                var hasgetidentifier = emicBackgroundWorkerObj.global_strBundle.getString("global.identifier.expirationdate.mailheader.hasget");
                var stringpropertyidentifier = emicBackgroundWorkerObj.global_strBundle.getString("global.identifier.expirationdate.stringproperty");
//                    emicBackgroundWorkerObj.consoleService.logStringMessage("hasgetidentifier: " + hasgetidentifier);
//                    emicBackgroundWorkerObj.consoleService.logStringMessage("stringpropertyidentifier: " + stringpropertyidentifier);

                if(aHeaders.has(hasgetidentifier)) {
//                        emicBackgroundWorkerObj.consoleService.logStringMessage("   ^ has expiration date, set it to: " + aHeaders.get(hasgetidentifier));
                    msgHdr.setStringProperty(
                        stringpropertyidentifier,
                        aHeaders.get(hasgetidentifier)
                    );
                }
                else {
//                        emicBackgroundWorkerObj.consoleService.logStringMessage("   ^ has no expiration date; set it to never");
                    msgHdr.setStringProperty(
                        stringpropertyidentifier,
                        emicBackgroundWorkerObj.global_strBundle.getString("global.identifier.never")
                    );
                }

            });
        }
    },

    processExpiredMails: function() {
        this.consoleService.logStringMessage("emicBackgroundWorkerObj.processExpiredMails() called");

        var srcFolders = new Array;
        var servers = this.accountManager.allServers;
        for(var i=0; i<servers.length; ++i) {
            var folders = servers.queryElementAt(i, Ci.nsIMsgIncomingServer).rootFolder.getFoldersWithFlags(Ci.nsMsgFolderFlags.Inbox);
            for (var j=0; j<folders.length; ++j) {
                srcFolders.push(folders.queryElementAt(j, Ci.nsIMsgFolder));
            }
        }

        for(var i=0; i<srcFolders.length; ++i) {
            var srcFolder = srcFolders[i];
            this.consoleService.logStringMessage("srcFolder: " + srcFolder.prettiestName);

            var now = new Date();
            var msgArray = srcFolder.messages;
            var expired_mails = Cc["@mozilla.org/array;1"].createInstance(Ci.nsIMutableArray);

            while( msgArray.hasMoreElements() ) {
                var msgHdr = msgArray.getNext().QueryInterface(Ci.nsIMsgDBHdr);
                var expdatestr = msgHdr.getStringProperty(this.global_strBundle.getString("global.identifier.expirationdate.stringproperty"));

                if(expdatestr != 0 && expdatestr.length > 0 && !(expdatestr == this.global_strBundle.getString("global.identifier.never"))) {
                    var expiration_date = new Date(expdatestr);
                    //search for expired mails:
                    if(expiration_date < now) {
                        expired_mails.appendElement(msgHdr, false);
                    }
                }
            }

            if(expired_mails.length > 0) {
                //add keywords to messages:
                if(this.prefs.getBoolPref("expiredmails.addtag")) {
                    this.consoleService.logStringMessage(" Try to tag " + expired_mails.length + " mails.");
                    srcFolder.addKeywordsToMessages(expired_mails, this.global_strBundle.getString("global.tag.expired.key"));
                }

                //move expired mails to folder:
                if(this.prefs.getBoolPref("expiredmails.move")) {
                    var gLocalIncomingServer = MailServices.accounts.localFoldersServer;
                    var gLocalRootFolder = gLocalIncomingServer.rootFolder;
                    var destfolder = null;

                    try {
                        destfolder = gLocalRootFolder.getChildNamed(this.destFolderName);
                    }
                    catch(e) {
                        this.consoleService.logStringMessage(" Destination folder not exists, try to create it (" + e + ").");
                        if(!destfolder) {
                            var msgWindow = Cc["@mozilla.org/messenger/msgwindow;1"].createInstance().QueryInterface(Ci.nsIMsgWindow);
                            gLocalRootFolder.createSubfolder(this.destFolderName,msgWindow);
                            destfolder = gLocalRootFolder.getChildNamed(this.destFolderName);
                        }
                    }
                    this.consoleService.logStringMessage(" Try to move " + expired_mails.length + " mails from Src: " + srcFolder.prettiestName + " --> Dest: " + destfolder.prettiestName + ".");
                    if(srcFolder && destfolder)
                        this.copyService.CopyMessages(srcFolder, expired_mails, destfolder, true, copyListener, null, false);
                }
            }
        }
    },

//    selectChanged: function(e) {
////        this.consoleService.logStringMessage("emicBackgroundWorkerObj.selectChanged() called");
//        var folder = gFolderDisplay.selectedMessage.folder;
//        this.setInbox(folder);
//    },

//    setInbox: function(inboxfolder) {
////        this.consoleService.logStringMessage("emicBackgroundWorkerObj.setInbox() called");
////        this.consoleService.logStringMessage("inboxfolder.prettiestName: " + inboxfolder.prettiestName);
//        if(inboxfolder.flags & Ci.nsMsgFolderFlags.Inbox) {
////            this.consoleService.logStringMessage("emicBackgroundWorkerObj.setInbox(): " + inboxfolder.prettiestName + " is of type inbox");
//            srcFolder = inboxfolder;
//        }
//    },

    setDestFolder: function(destfoldername) {
//        this.consoleService.logStringMessage("emicBackgroundWorkerObj.setDestFolder() called");
        this.destFolderName = destfoldername;
    },

    shutdown: function() {
//        this.consoleService.logStringMessage("emicBackgroundWorkerObj.shutdown() called");
        this.prefs.removeObserver("", this);
    },

    observe: function(aSubject, aTopic, aData) {
    // aSubject is the nsIPrefBranch we're observing (after appropriate QI)
    // aData is the name of the pref that's been changed (relative to aSubject)
//        this.consoleService.logStringMessage("emicBackgroundWorkerObj.observe() called");
        if (aTopic != "nsPref:changed")
            return;

        switch(aData) {
        case "expiredmails.move.destfoldername":
            this.setDestFolder(this.prefs.getCharPref("expiredmails.move.destfoldername"));
            break;
        case "expiredmails.addtag.colorcode":
            this.tagService.setColorForKey(this.global_strBundle.getString("global.tag.expired.key"), this.prefs.getCharPref("expiredmails.addtag.colorcode"));
            break;
        }
    },

    init: function() {
        this.consoleService.logStringMessage("emicBackgroundWorkerObj.init() called");
        this.global_strBundle           = document.getElementById("emic-strings-global");
        this.backgroundworker_strBundle = document.getElementById("emic-strings-backgroundworker");

        this.prefs.QueryInterface(Ci.nsIPrefBranch);
        this.prefs.addObserver("", this, false);
        this.setDestFolder(this.prefs.getCharPref("expiredmails.move.destfoldername"));

        this.notificationService.addListener(MailListener, this.notificationService.msgAdded);

        //set up a Tag:
        if(!this.tagService.isValidKey(this.global_strBundle.getString("global.tag.expired.key"))) {
            this.tagService.addTagForKey(this.global_strBundle.getString("global.tag.expired.key"), this.backgroundworker_strBundle.getString("backgroundworker.tag.expired.label"), this.prefs.getCharPref("expiredmails.addtag.colorcode"), "");
        }

        //set up status-bar:
        var statBar = document.getElementById("status-bar");
	    var statPanel = document.getElementById("emic-statusbarpanel");
        statBar.insertBefore(statPanel, null);

        this.processExpiredMails();
    }
}

window.addEventListener("load", function() {emicBackgroundWorkerObj.init()}, false);
window.setInterval(function(){emicBackgroundWorkerObj.processExpiredMails();}, 60000); //update every minute
//document.getElementById('threadTree').addEventListener('select', function(e){emicBackgroundWorkerObj.selectChanged(e);}, false);
window.addEventListener("unload", function(e) { emicBackgroundWorkerObj.shutdown(); }, false);<|endoftext|>


<commit_before>/*
	bigEval.js v0.1
	by Avi Aryan
*/

var bigEval_add = function(a, b){
	return Number(a)+Number(b);
};

var bigEval_mult = function(a, b){
	return Number(a)*Number(b);
};

var bigEval_div = function(a, b){
	return Number(a)/Number(b);
};

// so on

function bigEval(){
	this.err = 0;
	this.errMsg = "";
	this.errBR = "IMPROPER_BRACKETS";
	this.errMS = "MISSING_OPERATOR_AT_";
	this.errMN = "MISSING_OPERAND_AT_";
	this.errIC = "INVALID_CHAR_AT_";

	this.fChrRegex = /[a-z0-9\.\+\-\(]/i;
}

bigEval.prototype.exec = function(s){
	this.err = 0;
	this.errMsg = "";
	this.str = s;

	// validate brackets
	this.validate();
	if (this.err)
		return this.errMsg;

	// validate missing operator
	var misOperator = /[a-z0-9]([ \t]+[a-z0-9\.]|[ \t]*\()/ig, p;
	if (misOperator.exec(s)){
		this.err = 1;
		return this.errMsg = this.errMS + misOperator.lastIndex;
	}

	// validate missing operand
	var misOperands = /[\+\-\\\/\*\^][ \t]*([\+\-\\\/\*\^\!\)]|$)/g;
	if (misOperands.exec(s)){
		this.err = 1;
		return this.errMsg = this.errMN + misOperands.lastIndex;
	}

	s = s.replace(/[ \t]/g, '');

	return this.solve(s);
};

bigEval.prototype.solve = function(s){

	// validate first char
	var fc = s.charAt(0);
	if (!fc.match(this.fChrRegex)){
		this.err = 1;
		return this.errMsg = this.errIC;
	}

	var ans = 0, pop;

	if (fc == '+' || fc == '-'){
		s = s.slice(1);
	}

	return ans;
};

bigEval.prototype.validate = function(){
	// checks expression for errors
	var stack = [], err = 0;

	for ( var i = 0; i < this.str.length; i++ ){
		if ( this.str[i] == '(' )
			stack.push(0);
		else if ( this.str[i] == ')' ){
			if (stack.length > 0)
				stack.pop();
			else {
				this.makeError(this.errBS);
				break;
			}
		}
	}

	if (this.err == 0)
		if (stack.length != 0)
			this.makeError(this.errBS);
};

bigEval.prototype.makeError = function(msg){
	this.err = 1;
	this.errMsg += msg + " ";
};<commit_msg>first working version :-)<commit_after>/*
	bigEval.js v0.1
	by Avi Aryan
*/

function bigEval(){
	this.err = 0;
	this.errMsg = "";
	this.errBR = "IMPROPER_BRACKETS";
	this.errMS = "MISSING_OPERATOR_AT_";
	this.errMN = "MISSING_OPERAND_AT_";
	this.errIC = "INVALID_CHAR_AT_";

	this.order = "!^\\/*+-";
}

bigEval.prototype.exec = function(s){
	this.err = 0;
	this.errMsg = "";
	this.str = s;

	// validate brackets
	this.validate();
	if (this.err)
		return this.errMsg;

	// validate missing operator
	var misOperator = /[a-z0-9]([ \t]+[a-z0-9\.]|[ \t]*\()/ig, p;
	if (misOperator.exec(s)){
		this.err = 1;
		return this.errMsg = this.errMS + misOperator.lastIndex;
	}

	// validate missing operand
	var misOperands = /[\+\-\\\/\*\^][ \t]*([\+\-\\\/\*\^\!\)]|$)/g;
	if (misOperands.exec(s)){
		this.err = 1;
		return this.errMsg = this.errMN + misOperands.lastIndex;
	}

	s = s.replace(/[ \t]/g, '');

	return this.solve(s);
};

bigEval.prototype.solve = function(s){

	// validate first char
	var fc = s.charAt(0);
	if (!fc.match(/[a-z0-9\.\+\-\(]/i)){
		this.err = 1;
		return this.errMsg = this.errIC;
	}

	var ob = s.indexOf('('), cb;

	// if bracket present, work on them
	if (ob != -1){
		var obct = 1;
		for (var i = ob+1; i < s.length; i++){
			if (s[i] == '(')
				obct++;
			else if (s[i] == ')'){
				obct--;
				if (obct == 0){
					cb = i;
					break;
				}
			}
		}
		s = s.slice(0, ob) + this.solve( s.slice(ob+1, cb) ) + s.slice(cb+1);
		if (this.err)
			return this.errMsg;
	}

	// solve expression (no brackets exist)
	var p, bp, ap, seg, c;
	for (var i = 0; i < this.order.length; i++){
		p = s.indexOf(c = this.order[i]);
		while (p > 0){ // the first is sign, no need to take that
			bp = s.slice(0,p).match(/[-]?[a-z0-9\.]+$/i);
			ap = s.slice(p+1).match(/[\-\+]?[a-z0-9\.]+/i);

			if (c == '!'){

			} else {
				if (c == '/' || c == '\\')
					seg = this.div( bp[0] , ap[0] );
				else if (c == '*')
					seg = this.mul( bp[0] , ap[0] );
				else if (c == '+')
					seg = this.add( bp[0] , ap[0] );
				else if (c == '-')
					seg = this.add( bp[0] , '-' + ap[0] );

				s = s.slice(0, p-bp[0].length) + seg + s.slice(p+ap[0].length+1);
			}
			p = s.indexOf(c);
		}
	}

	return s;
};

bigEval.prototype.validate = function(){
	// checks expression for errors
	var stack = [], err = 0;

	for ( var i = 0; i < this.str.length; i++ ){
		if ( this.str[i] == '(' )
			stack.push(0);
		else if ( this.str[i] == ')' ){
			if (stack.length > 0)
				stack.pop();
			else {
				this.makeError(this.errBS);
				break;
			}
		}
	}

	if (this.err == 0)
		if (stack.length != 0)
			this.makeError(this.errBS);
};

bigEval.prototype.makeError = function(msg){
	this.err = 1;
	this.errMsg += msg + " ";
};

/******************
*
* FUNCTIONS BENEATH
*
*******************/

bigEval.prototype.add = function(a, b){
	return Number(a)+Number(b);
};

bigEval.prototype.mul = function(a, b){
	return Number(a)*Number(b);
};

bigEval.prototype.div = function(a, b){
	return Number(a)/Number(b);
};<|endoftext|>


<commit_before>Components.utils.import("resource:///modules/gloda/log4moz.js");

function enhancedPriorityDisplayIcons() {
    var oldColumnHandler;
    var logger = Log4Moz
	.getConfiguredLogger("extensions.EnhancedPriorityDisplay",
			     Log4Moz.Level.Trace,
			     Log4Moz.Level.Info,
			     Log4Moz.Level.Debug);
    var prefService = Components.classes["@mozilla.org/preferences-service;1"]
        .getService(Components.interfaces.nsIPrefBranch);

    function gCP(pref) {
	return prefService.getCharPref("extensions.EnhancedPriorityDisplay." +
				       pref);
    };

    function priorityIconsOnLoad() {
	var ObserverService = Components.classes["@mozilla.org/observer-service;1"]
	    .getService(Components.interfaces.nsIObserverService);
	ObserverService.addObserver(createDbObserver, "MsgCreateDBView", false);
    };

    function createGenericHandler(colId, oldHandler) {
	if (gDBView) {
	    var columnHandler = {
		old: oldHandler,

		getCellText: function(row, col) {
		    if (columnHandler.old)
			return columnHandler.old.getCellText(row, col);
		    return gDBView.cellTextForColumn(row, colId);
		},

		getSortStringForRow: function(hdr) {
		    if (columnHandler.old)
			return columnHandler.old.getSortStringForRow(hdr);
		    return null;
		},

		isString: function() {
		    return true;
		},

		getExtensionProperties: function(row, props) {
		    var hdr = gDBView.getMsgHdrAt(row);
		    var priority = hdr.getStringProperty("priority");
		    var property;
		    switch (priority) {
		    case "6":
			property = "enhanced-priority-display-highest";
			break;
		    case "5":
			property = "enhanced-priority-display-high";
			break;
		    case "3":
			property = "enhanced-priority-display-low";
			break;
		    case "2":
			property = "enhanced-priority-display-lowest";
			break;
		    }
		    if (property) {
			var aserv=Components
			    .classes["@mozilla.org/atom-service;1"].
			    getService(Components.interfaces.nsIAtomService);
			props.AppendElement(aserv.getAtom(property));
		    }
		},

		getCellProperties: function(row, col, props) {
		    columnHandler.getExtensionProperties(row, props);
		    if (columnHandler.old)
			columnHandler.old.getCellProperties(row, col, props);
		},

		getRowProperties: function(row, props) {
		    columnHandler.getExtensionProperties(row, props);
		    if (columnHandler.old)
			columnHandler.old.getRowProperties(row, props);
		},

		getImageSrc: function(row, col) {
		    if (columnHandler.old)
			return columnHandler.old.getImageSrc(row, col);
		    return null;
		},

		getSortLongForRow: function(hdr) {
		    if (columnHandler.old)
			return columnHandler.old.getSortLongForRow(hdr);
		    return null;
		}
	    };

	    gDBView.addColumnHandler(colId, columnHandler);
	}
    };

    var createDbObserver = {
	// Components.interfaces.nsIObserver
	observe: function(aMsgFolder, aTopic, aData) {
	    if (gDBView) {
		var columnHandler = {
		    getCellText: function(row, col) {
			return "";
		    },

		    getSortStringForRow: function(hdr) {
			if (columnHandler.old)
			    return columnHandler.old.getSortStringForRow(hdr);
			return null;
		    },

		    isString: function() {
			return false;
		    },

		    getExtensionProperties: function(row, props) {
			var hdr = gDBView.getMsgHdrAt(row);
			var priority = hdr.getStringProperty("priority");
			var property;
			switch (priority) {
			case "6":
			    property = "enhanced-priority-display-highest";
			    break;
			case "5":
			    property = "enhanced-priority-display-high";
			    break;
			case "3":
			    property = "enhanced-priority-display-low";
			    break;
			case "2":
			    property = "enhanced-priority-display-lowest";
			    break;
			}
			if (property) {
			    var aserv=Components
				.classes["@mozilla.org/atom-service;1"].
				getService(Components.interfaces.nsIAtomService);
			    props.AppendElement(aserv.getAtom(property));
			}
		    },

		    getCellProperties: function(row, col, props) {
			columnHandler.getExtensionProperties(row, props);
			if (columnHandler.old)
			    columnHandler.old.getCellProperties(row, props);
		    },

		    getRowProperties: function(row, props) {
			columnHandler.getExtensionProperties(row, props);
			if (columnHandler.old)
			    columnHandler.old.getRowProperties(row, props);
		    },

		    getImageSrc: function(row, col) {
			var hdr = gDBView.getMsgHdrAt(row);
			var priority = hdr.getStringProperty("priority");
			switch (priority) {
			case "6":
			    return gCP("HighestIcon");
			case "5":
			    return gCP("HighIcon");
			case "3":
			    return gCP("LowIcon");
			case "2":
			    return gCP("LowestIcon");
			default:
			    if (columnHandler.old)
				return columnHandler.old.getImageSrc(row, col);
			    return null;
			}
		    },

		    getSortLongForRow: function(hdr) {
			if (columnHandler.old)
			    return columnHandler.old.getSortLongForRow(hdr);
			return null;
		    }
		};

		try {
		    columnHandler.old = gDBView.getColumnHandler("priorityCol");
		}
		catch (ex) {}
		gDBView.addColumnHandler("priorityCol", columnHandler);
		var threadCols = document.getElementById("threadCols");
		if (! threadCols)
		    return;
		var columns = threadCols.getElementsByTagName("treecol");
		if (! columns)
		    return;
		for (var column in columns) {
		    var id = columns[column].id;
		    if (! id)
			continue;
		    var handler;
		    try { handler = gDBView.getColumnHandler(id); }
		    catch (ex) {}
		    if (handler && ! handler.isString())
			continue;
		    if (handler && handler.cycleCell)
			continue;
		    if (! handler && ! id.match(/^(subject|sender|recipient|received|date|size|tags|account|unread|total|location|status)Col$/))
			continue;
		    createGenericHandler(id, handler);
		}
	    }
	}
    };

    window.addEventListener("load", priorityIconsOnLoad, false);
    // window.addEventListener("unload", priorityIconsOnUnload, false);
};

enhancedPriorityDisplayIcons.apply();
<commit_msg>Use preferences to control how we modify the UI.<commit_after>Components.utils.import("resource:///modules/gloda/log4moz.js");

function enhancedPriorityDisplayIcons() {
    var oldColumnHandler;
    var logger = Log4Moz
	.getConfiguredLogger("extensions.EnhancedPriorityDisplay",
			     Log4Moz.Level.Trace,
			     Log4Moz.Level.Info,
			     Log4Moz.Level.Debug);
    var prefService = Components.classes["@mozilla.org/preferences-service;1"]
        .getService(Components.interfaces.nsIPrefBranch);

    function gCP(pref) {
	return prefService.getCharPref("extensions.EnhancedPriorityDisplay." +
				       pref);
    };

    function gBP(pref) {
	return prefService.getBoolPref("extensions.EnhancedPriorityDisplay." +
				       pref);
    };

    function priorityIconsOnLoad() {
	var ObserverService = Components.classes["@mozilla.org/observer-service;1"]
	    .getService(Components.interfaces.nsIObserverService);
	ObserverService.addObserver(createDbObserver, "MsgCreateDBView", false);
    };

    function createGenericHandler(colId, oldHandler) {
	if (gDBView) {
	    var columnHandler = {
		old: oldHandler,

		getCellText: function(row, col) {
		    if (columnHandler.old)
			return columnHandler.old.getCellText(row, col);
		    return gDBView.cellTextForColumn(row, colId);
		},

		getSortStringForRow: function(hdr) {
		    if (columnHandler.old)
			return columnHandler.old.getSortStringForRow(hdr);
		    return null;
		},

		isString: function() {
		    return true;
		},

		getExtensionProperties: function(row, props, which) {
		    var hdr = gDBView.getMsgHdrAt(row);
		    var priority = hdr.getStringProperty("priority");
		    var doHigh = gBP(which + "High");
		    var doLow = gBP(which + "Low");
		    var property;
		    switch (priority) {
		    case "6":
			if (doHigh)
			    property = "enhanced-priority-display-highest";
			break;
		    case "5":
			if (doHigh)
			    property = "enhanced-priority-display-high";
			break;
		    case "3":
			if (doLow)
			    property = "enhanced-priority-display-low";
			break;
		    case "2":
			if (doLow)
			    property = "enhanced-priority-display-lowest";
			break;
		    }
		    if (property) {
			var aserv=Components
			    .classes["@mozilla.org/atom-service;1"].
			    getService(Components.interfaces.nsIAtomService);
			props.AppendElement(aserv.getAtom(property));
		    }
		},

		getCellProperties: function(row, col, props) {
		    columnHandler.getExtensionProperties(row, props, "Style");
		    if (columnHandler.old)
			columnHandler.old.getCellProperties(row, col, props);
		},

		getRowProperties: function(row, props) {
		    columnHandler.getExtensionProperties(row, props, "Shade");
		    if (columnHandler.old)
			columnHandler.old.getRowProperties(row, props);
		},

		getImageSrc: function(row, col) {
		    if (columnHandler.old)
			return columnHandler.old.getImageSrc(row, col);
		    return null;
		},

		getSortLongForRow: function(hdr) {
		    if (columnHandler.old)
			return columnHandler.old.getSortLongForRow(hdr);
		    return null;
		}
	    };

	    gDBView.addColumnHandler(colId, columnHandler);
	}
    };

    var createDbObserver = {
	// Components.interfaces.nsIObserver
	observe: function(aMsgFolder, aTopic, aData) {
	    if (gDBView) {
		var columnHandler = {
		    getCellText: function(row, col) {
			if (gBP("Iconify"))
			    return "";
			return gDBView.cellTextForColumn(row, "priorityCol");
		    },

		    getSortStringForRow: function(hdr) {
			if (columnHandler.old)
			    return columnHandler.old.getSortStringForRow(hdr);
			return null;
		    },

		    isString: function() {
			return ! gBP("Iconify");
		    },

		    getExtensionProperties: function(row, props, which) {
			var hdr = gDBView.getMsgHdrAt(row);
			var priority = hdr.getStringProperty("priority");
			var doHigh = gBP(which + "High");
			var doLow = gBP(which + "Low");
			var property;
			switch (priority) {
			case "6":
			    if (doHigh)
				property = "enhanced-priority-display-highest";
			    break;
			case "5":
			    if (doHigh)
				property = "enhanced-priority-display-high";
			    break;
			case "3":
			    if (doLow)
				property = "enhanced-priority-display-low";
			    break;
			case "2":
			    if (doLow)
				property = "enhanced-priority-display-lowest";
			    break;
			}
			if (property) {
			    var aserv = Components
				.classes["@mozilla.org/atom-service;1"]
				.getService(Components.interfaces.nsIAtomService);
			    props.AppendElement(aserv.getAtom(property));
			}
		    },

		    getCellProperties: function(row, col, props) {
			columnHandler .getExtensionProperties(row, props,
							      "Style");
			if (columnHandler.old)
			    columnHandler.old.getCellProperties(row, props);
		    },

		    getRowProperties: function(row, props) {
			columnHandler.getExtensionProperties(row, props,
							     "Shade");
			if (columnHandler.old)
			    columnHandler.old.getRowProperties(row, props);
		    },

		    getImageSrc: function(row, col) {
			if (! gBP("Iconify"))
			    return null;
			var hdr = gDBView.getMsgHdrAt(row);
			var priority = hdr.getStringProperty("priority");
			switch (priority) {
			case "6":
			    return gCP("HighestIcon");
			case "5":
			    return gCP("HighIcon");
			case "3":
			    return gCP("LowIcon");
			case "2":
			    return gCP("LowestIcon");
			default:
			    if (columnHandler.old)
				return columnHandler.old.getImageSrc(row, col);
			    return null;
			}
		    },

		    getSortLongForRow: function(hdr) {
			if (columnHandler.old)
			    return columnHandler.old.getSortLongForRow(hdr);
			return null;
		    }
		};

		try {
		    columnHandler.old = gDBView.getColumnHandler("priorityCol");
		}
		catch (ex) {}
		gDBView.addColumnHandler("priorityCol", columnHandler);
		var threadCols = document.getElementById("threadCols");
		if (! threadCols)
		    return;
		var columns = threadCols.getElementsByTagName("treecol");
		if (! columns)
		    return;
		for (var column in columns) {
		    var id = columns[column].id;
		    if (! id)
			continue;
		    var handler;
		    try { handler = gDBView.getColumnHandler(id); }
		    catch (ex) {}
		    if (handler && ! handler.isString())
			continue;
		    if (handler && handler.cycleCell)
			continue;
		    if (! handler && ! id.match(/^(subject|sender|recipient|received|date|size|tags|account|unread|total|location|status)Col$/))
			continue;
		    createGenericHandler(id, handler);
		}
	    }
	}
    };

    window.addEventListener("load", priorityIconsOnLoad, false);
    // window.addEventListener("unload", priorityIconsOnUnload, false);
};

enhancedPriorityDisplayIcons.apply();
<|endoftext|>


<commit_before>// This anonymous function exists to isolate generic names inside it to its
// private scope.
var GM_ScriptDownloader;
(function() {

GM_ScriptDownloader = function(win, uri, bundle) {
  this.win_ = win;
  this.uri_ = uri;
  this.bundle_ = bundle;
  this.req_ = null;
  this.script = null;
  this.depQueue_ = [];
  this.dependenciesLoaded_ = false;
  this.installOnCompletion_ = false;
  this.tempFiles_ = [];
  this.updateScript = false;
}

GM_ScriptDownloader.prototype.startInstall = function() {
  this.installing_ = true;
  this.startDownload();
};

GM_ScriptDownloader.prototype.startViewScript = function(uri) {
  this.installing_ = false;
  this.startDownload();
};

GM_ScriptDownloader.prototype.startDownload = function() {
  this.win_.GM_BrowserUI.statusImage.src =
      "chrome://greasemonkey/content/third-party/throbber.gif";
  this.win_.GM_BrowserUI.statusImage.style.opacity = "0.5";
  this.win_.GM_BrowserUI.statusImage.tooltipText =
      this.bundle_.getString("tooltip.loading");

  this.win_.GM_BrowserUI.showStatus("Fetching user script", false);

  Components.classes["@greasemonkey.mozdev.org/greasemonkey-service;1"]
    .getService().wrappedJSObject
    .ignoreNextScript();

  this.req_ = new XMLHttpRequest();
  this.req_.overrideMimeType("text/plain");
  this.req_.open("GET", this.uri_.spec, true);
  this.req_.onload = GM_hitch(this, "handleScriptDownloadComplete");
  this.req_.send(null);
};

GM_ScriptDownloader.prototype.handleScriptDownloadComplete = function() {
  this.win_.GM_BrowserUI.refreshStatus();
  this.win_.GM_BrowserUI.hideStatusImmediately();

  try {
    // If loading from file, status might be zero on success
    if (this.req_.status != 200 && this.req_.status != 0) {
      // NOTE: Unlocalized string
      alert("Error loading user script:\n" +
      this.req_.status + ": " +
      this.req_.statusText);
      return;
    }

    var source = this.req_.responseText;

    this.script = GM_getConfig().parse(source, this.uri_);

    var file = Components.classes["@mozilla.org/file/directory_service;1"]
                         .getService(Components.interfaces.nsIProperties)
                         .get("TmpD", Components.interfaces.nsILocalFile);

    var base = this.script.name.replace(/[^A-Z0-9_]/gi, "").toLowerCase();
    file.append(base + ".user.js");
    file.createUnique(
      Components.interfaces.nsILocalFile.NORMAL_FILE_TYPE,
      0640
    );
    this.tempFiles_.push(file);

    var converter =
      Components.classes["@mozilla.org/intl/scriptableunicodeconverter"]
        .createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
    converter.charset = "UTF-8";
    source = converter.ConvertFromUnicode(source);

    var ws = GM_getWriteStream(file);
    ws.write(source, source.length);
    ws.close();

    this.script.setDownloadedFile(file);

    window.setTimeout(GM_hitch(this, "fetchDependencies"), 0);

    if(this.installing_){
      this.showInstallDialog();
    }else{
      this.showScriptView();
    }
  } catch (e) {
    // NOTE: unlocalized string
    alert("Script could not be installed " + e);
    throw e;
  }
};

GM_ScriptDownloader.prototype.fetchDependencies = function(){
  GM_log("Fetching Dependencies");
  var deps = this.script.requires.concat(this.script.resources);
  for (var i = 0; i < deps.length; i++) {
    var dep = deps[i];
    if (this.checkDependencyURL(dep.urlToDownload)) {
      this.depQueue_.push(dep);
    } else {
      this.errorInstallDependency(this.script, dep,
        "SecurityException: Request to local and chrome url's is forbidden");
      return;
    }
  }
  this.downloadNextDependency();
};

GM_ScriptDownloader.prototype.downloadNextDependency = function(){
  if (this.depQueue_.length > 0) {
    var dep = this.depQueue_.pop();
    try {
      var persist = Components.classes[
        "@mozilla.org/embedding/browser/nsWebBrowserPersist;1"]
        .createInstance(Components.interfaces.nsIWebBrowserPersist);
      persist.persistFlags =
        persist.PERSIST_FLAGS_BYPASS_CACHE |
        persist.PERSIST_FLAGS_REPLACE_EXISTING_FILES; //doesn't work?
      var ioservice =
        Components.classes["@mozilla.org/network/io-service;1"]
        .getService(Components.interfaces.nsIIOService);
      var sourceUri = GM_uriFromUrl(dep.urlToDownload);
      var sourceChannel = ioservice.newChannelFromURI(sourceUri);
      sourceChannel.notificationCallbacks = new NotificationCallbacks();

      var file = GM_getTempFile();
      this.tempFiles_.push(file);

      var progressListener = new PersistProgressListener(persist);
      progressListener.onFinish = GM_hitch(this,
        "handleDependencyDownloadComplete", dep, file, sourceChannel);
      persist.progressListener = progressListener;

      persist.saveChannel(sourceChannel,  file);
    } catch(e) {
      GM_log("Download exception " + e);
      this.errorInstallDependency(this.script, dep, e);
    }
  } else {
    this.dependenciesLoaded_ = true;
    this.finishInstall();
  }
};

GM_ScriptDownloader.prototype.handleDependencyDownloadComplete =
function(dep, file, channel) {
  GM_log("Dependency Download complete " + dep.urlToDownload);
  try {
    var httpChannel =
      channel.QueryInterface(Components.interfaces.nsIHttpChannel);
  } catch(e) {
    var httpChannel = false;
  }

  if (httpChannel) {
    if (httpChannel.requestSucceeded) {
      if (this.updateScript) {
        dep._script = this.script;
        dep.updateScript = true;
      }
      dep.setDownloadedFile(file, channel.contentType, channel.contentCharset ? channel.contentCharset : null);
      this.downloadNextDependency();
    } else {
      this.errorInstallDependency(this.script, dep,
        "Error! Server Returned : " + httpChannel.responseStatus + ": " +
        httpChannel.responseStatusText);
    }
  } else {
    dep.setDownloadedFile(file);
    this.downloadNextDependency();
  }
};

GM_ScriptDownloader.prototype.checkDependencyURL = function(url) {
  var ioService = Components.classes["@mozilla.org/network/io-service;1"]
                            .getService(Components.interfaces.nsIIOService);
  var scheme = ioService.extractScheme(url);

  switch (scheme) {
    case "http":
    case "https":
    case "ftp":
        return true;
    case "file":
        var scriptScheme = ioService.extractScheme(this.uri_.spec);
        return (scriptScheme == "file")
    default:
      return false;
  }
};

GM_ScriptDownloader.prototype.finishInstall = function() {
  if (this.updateScript) {
    // Inject the script now that we have the new dependencies
    GM_getConfig().injectScript(this.script);
    this.script.delayInjection = false;

    // Save new values to config.xml
    GM_getConfig()._save();
  } else if (this.installOnCompletion_) {
    this.installScript();
  }
};

GM_ScriptDownloader.prototype.errorInstallDependency = function(script, dep, msg){
  GM_log("Error loading dependency " + dep.urlToDownload + "\n" + msg);
  if (this.installOnCompletion_) {
    alert("Error loading dependency " + dep.urlToDownload + "\n" + msg);
  } else {
    this.dependencyError = "Error loading dependency " + dep.urlToDownload + "\n" + msg;
  }
};

GM_ScriptDownloader.prototype.installScript = function(){
  if (this.dependencyError) {
    alert(this.dependencyError);
  } else if(this.dependenciesLoaded_) {
    this.win_.GM_BrowserUI.installScript(this.script)
  } else {
    this.installOnCompletion_ = true;
  }
};

GM_ScriptDownloader.prototype.cleanupTempFiles = function() {
  for (var i = 0, file = null; file = this.tempFiles_[i]; i++) {
    file.remove(false);
  }
};

GM_ScriptDownloader.prototype.showInstallDialog = function(timer) {
  if (!timer) {
    // otherwise, the status bar stays in the loading state.
    this.win_.setTimeout(GM_hitch(this, "showInstallDialog", true), 0);
    return;
  }
  this.win_.openDialog("chrome://greasemonkey/content/install.xul", "",
                       "chrome,centerscreen,modal,dialog,titlebar,resizable",
                       this);
};

GM_ScriptDownloader.prototype.showScriptView = function() {
  this.win_.GM_BrowserUI.showScriptView(this);
};

function NotificationCallbacks() {}

NotificationCallbacks.prototype.QueryInterface = function(aIID) {
  if (aIID.equals(Components.interfaces.nsIInterfaceRequestor)) {
    return this;
  }
  throw Components.results.NS_NOINTERFACE;
};

NotificationCallbacks.prototype.getInterface = function(aIID) {
  if (aIID.equals(Components.interfaces.nsIAuthPrompt )) {
     var winWat = Components.classes["@mozilla.org/embedcomp/window-watcher;1"]
                            .getService(Components.interfaces.nsIWindowWatcher);
     return winWat.getNewAuthPrompter(winWat.activeWindow);
  }
  return undefined;
};

function PersistProgressListener(persist) {
  this.persist = persist;
  this.onFinish = function(){};
  this.persiststate = "";
}

PersistProgressListener.prototype.QueryInterface = function(aIID) {
 if (aIID.equals(Components.interfaces.nsIWebProgressListener)) {
   return this;
 }
 throw Components.results.NS_NOINTERFACE;
};

// nsIWebProgressListener
PersistProgressListener.prototype.onProgressChange =
  PersistProgressListener.prototype.onLocationChange =
    PersistProgressListener.prototype.onStatusChange =
      PersistProgressListener.prototype.onSecurityChange = function(){};

PersistProgressListener.prototype.onStateChange =
  function(aWebProgress, aRequest, aStateFlags, aStatus) {
    if (this.persist.currentState == this.persist.PERSIST_STATE_FINISHED) {
      GM_log("Persister: Download complete " + aRequest.status);
      this.onFinish();
    }
  };

})();
<commit_msg>Now that we're using GM_scriptMatchesUrlAndRuns for late injection, script.delayInjection must be set to false before late injection can occur.<commit_after>// This anonymous function exists to isolate generic names inside it to its
// private scope.
var GM_ScriptDownloader;
(function() {

GM_ScriptDownloader = function(win, uri, bundle) {
  this.win_ = win;
  this.uri_ = uri;
  this.bundle_ = bundle;
  this.req_ = null;
  this.script = null;
  this.depQueue_ = [];
  this.dependenciesLoaded_ = false;
  this.installOnCompletion_ = false;
  this.tempFiles_ = [];
  this.updateScript = false;
}

GM_ScriptDownloader.prototype.startInstall = function() {
  this.installing_ = true;
  this.startDownload();
};

GM_ScriptDownloader.prototype.startViewScript = function(uri) {
  this.installing_ = false;
  this.startDownload();
};

GM_ScriptDownloader.prototype.startDownload = function() {
  this.win_.GM_BrowserUI.statusImage.src =
      "chrome://greasemonkey/content/third-party/throbber.gif";
  this.win_.GM_BrowserUI.statusImage.style.opacity = "0.5";
  this.win_.GM_BrowserUI.statusImage.tooltipText =
      this.bundle_.getString("tooltip.loading");

  this.win_.GM_BrowserUI.showStatus("Fetching user script", false);

  Components.classes["@greasemonkey.mozdev.org/greasemonkey-service;1"]
    .getService().wrappedJSObject
    .ignoreNextScript();

  this.req_ = new XMLHttpRequest();
  this.req_.overrideMimeType("text/plain");
  this.req_.open("GET", this.uri_.spec, true);
  this.req_.onload = GM_hitch(this, "handleScriptDownloadComplete");
  this.req_.send(null);
};

GM_ScriptDownloader.prototype.handleScriptDownloadComplete = function() {
  this.win_.GM_BrowserUI.refreshStatus();
  this.win_.GM_BrowserUI.hideStatusImmediately();

  try {
    // If loading from file, status might be zero on success
    if (this.req_.status != 200 && this.req_.status != 0) {
      // NOTE: Unlocalized string
      alert("Error loading user script:\n" +
      this.req_.status + ": " +
      this.req_.statusText);
      return;
    }

    var source = this.req_.responseText;

    this.script = GM_getConfig().parse(source, this.uri_);

    var file = Components.classes["@mozilla.org/file/directory_service;1"]
                         .getService(Components.interfaces.nsIProperties)
                         .get("TmpD", Components.interfaces.nsILocalFile);

    var base = this.script.name.replace(/[^A-Z0-9_]/gi, "").toLowerCase();
    file.append(base + ".user.js");
    file.createUnique(
      Components.interfaces.nsILocalFile.NORMAL_FILE_TYPE,
      0640
    );
    this.tempFiles_.push(file);

    var converter =
      Components.classes["@mozilla.org/intl/scriptableunicodeconverter"]
        .createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
    converter.charset = "UTF-8";
    source = converter.ConvertFromUnicode(source);

    var ws = GM_getWriteStream(file);
    ws.write(source, source.length);
    ws.close();

    this.script.setDownloadedFile(file);

    window.setTimeout(GM_hitch(this, "fetchDependencies"), 0);

    if(this.installing_){
      this.showInstallDialog();
    }else{
      this.showScriptView();
    }
  } catch (e) {
    // NOTE: unlocalized string
    alert("Script could not be installed " + e);
    throw e;
  }
};

GM_ScriptDownloader.prototype.fetchDependencies = function(){
  GM_log("Fetching Dependencies");
  var deps = this.script.requires.concat(this.script.resources);
  for (var i = 0; i < deps.length; i++) {
    var dep = deps[i];
    if (this.checkDependencyURL(dep.urlToDownload)) {
      this.depQueue_.push(dep);
    } else {
      this.errorInstallDependency(this.script, dep,
        "SecurityException: Request to local and chrome url's is forbidden");
      return;
    }
  }
  this.downloadNextDependency();
};

GM_ScriptDownloader.prototype.downloadNextDependency = function(){
  if (this.depQueue_.length > 0) {
    var dep = this.depQueue_.pop();
    try {
      var persist = Components.classes[
        "@mozilla.org/embedding/browser/nsWebBrowserPersist;1"]
        .createInstance(Components.interfaces.nsIWebBrowserPersist);
      persist.persistFlags =
        persist.PERSIST_FLAGS_BYPASS_CACHE |
        persist.PERSIST_FLAGS_REPLACE_EXISTING_FILES; //doesn't work?
      var ioservice =
        Components.classes["@mozilla.org/network/io-service;1"]
        .getService(Components.interfaces.nsIIOService);
      var sourceUri = GM_uriFromUrl(dep.urlToDownload);
      var sourceChannel = ioservice.newChannelFromURI(sourceUri);
      sourceChannel.notificationCallbacks = new NotificationCallbacks();

      var file = GM_getTempFile();
      this.tempFiles_.push(file);

      var progressListener = new PersistProgressListener(persist);
      progressListener.onFinish = GM_hitch(this,
        "handleDependencyDownloadComplete", dep, file, sourceChannel);
      persist.progressListener = progressListener;

      persist.saveChannel(sourceChannel,  file);
    } catch(e) {
      GM_log("Download exception " + e);
      this.errorInstallDependency(this.script, dep, e);
    }
  } else {
    this.dependenciesLoaded_ = true;
    this.finishInstall();
  }
};

GM_ScriptDownloader.prototype.handleDependencyDownloadComplete =
function(dep, file, channel) {
  GM_log("Dependency Download complete " + dep.urlToDownload);
  try {
    var httpChannel =
      channel.QueryInterface(Components.interfaces.nsIHttpChannel);
  } catch(e) {
    var httpChannel = false;
  }

  if (httpChannel) {
    if (httpChannel.requestSucceeded) {
      if (this.updateScript) {
        dep._script = this.script;
        dep.updateScript = true;
      }
      dep.setDownloadedFile(file, channel.contentType, channel.contentCharset ? channel.contentCharset : null);
      this.downloadNextDependency();
    } else {
      this.errorInstallDependency(this.script, dep,
        "Error! Server Returned : " + httpChannel.responseStatus + ": " +
        httpChannel.responseStatusText);
    }
  } else {
    dep.setDownloadedFile(file);
    this.downloadNextDependency();
  }
};

GM_ScriptDownloader.prototype.checkDependencyURL = function(url) {
  var ioService = Components.classes["@mozilla.org/network/io-service;1"]
                            .getService(Components.interfaces.nsIIOService);
  var scheme = ioService.extractScheme(url);

  switch (scheme) {
    case "http":
    case "https":
    case "ftp":
        return true;
    case "file":
        var scriptScheme = ioService.extractScheme(this.uri_.spec);
        return (scriptScheme == "file")
    default:
      return false;
  }
};

GM_ScriptDownloader.prototype.finishInstall = function() {
  if (this.updateScript) {
    // Inject the script now that we have the new dependencies
    this.script.delayInjection = false;
    GM_getConfig().injectScript(this.script);

    // Save new values to config.xml
    GM_getConfig()._save();
  } else if (this.installOnCompletion_) {
    this.installScript();
  }
};

GM_ScriptDownloader.prototype.errorInstallDependency = function(script, dep, msg){
  GM_log("Error loading dependency " + dep.urlToDownload + "\n" + msg);
  if (this.installOnCompletion_) {
    alert("Error loading dependency " + dep.urlToDownload + "\n" + msg);
  } else {
    this.dependencyError = "Error loading dependency " + dep.urlToDownload + "\n" + msg;
  }
};

GM_ScriptDownloader.prototype.installScript = function(){
  if (this.dependencyError) {
    alert(this.dependencyError);
  } else if(this.dependenciesLoaded_) {
    this.win_.GM_BrowserUI.installScript(this.script)
  } else {
    this.installOnCompletion_ = true;
  }
};

GM_ScriptDownloader.prototype.cleanupTempFiles = function() {
  for (var i = 0, file = null; file = this.tempFiles_[i]; i++) {
    file.remove(false);
  }
};

GM_ScriptDownloader.prototype.showInstallDialog = function(timer) {
  if (!timer) {
    // otherwise, the status bar stays in the loading state.
    this.win_.setTimeout(GM_hitch(this, "showInstallDialog", true), 0);
    return;
  }
  this.win_.openDialog("chrome://greasemonkey/content/install.xul", "",
                       "chrome,centerscreen,modal,dialog,titlebar,resizable",
                       this);
};

GM_ScriptDownloader.prototype.showScriptView = function() {
  this.win_.GM_BrowserUI.showScriptView(this);
};

function NotificationCallbacks() {}

NotificationCallbacks.prototype.QueryInterface = function(aIID) {
  if (aIID.equals(Components.interfaces.nsIInterfaceRequestor)) {
    return this;
  }
  throw Components.results.NS_NOINTERFACE;
};

NotificationCallbacks.prototype.getInterface = function(aIID) {
  if (aIID.equals(Components.interfaces.nsIAuthPrompt )) {
     var winWat = Components.classes["@mozilla.org/embedcomp/window-watcher;1"]
                            .getService(Components.interfaces.nsIWindowWatcher);
     return winWat.getNewAuthPrompter(winWat.activeWindow);
  }
  return undefined;
};

function PersistProgressListener(persist) {
  this.persist = persist;
  this.onFinish = function(){};
  this.persiststate = "";
}

PersistProgressListener.prototype.QueryInterface = function(aIID) {
 if (aIID.equals(Components.interfaces.nsIWebProgressListener)) {
   return this;
 }
 throw Components.results.NS_NOINTERFACE;
};

// nsIWebProgressListener
PersistProgressListener.prototype.onProgressChange =
  PersistProgressListener.prototype.onLocationChange =
    PersistProgressListener.prototype.onStatusChange =
      PersistProgressListener.prototype.onSecurityChange = function(){};

PersistProgressListener.prototype.onStateChange =
  function(aWebProgress, aRequest, aStateFlags, aStatus) {
    if (this.persist.currentState == this.persist.PERSIST_STATE_FINISHED) {
      GM_log("Persister: Download complete " + aRequest.status);
      this.onFinish();
    }
  };

})();
<|endoftext|>