<commit_before>(function(scope) {
    'use strict';

    var Scope = scope.window ? window : global;

    if (typeof module === 'object' && module.exports)
        module.exports = new UtilProto();
    else if (!Scope.Util)
        Scope.Util = new UtilProto();

    function UtilProto() {
        var Util = this;

        /*
         * apply arguemnts to constructor
         *
         * @param constructor
         * @param args
         */
        this.applyConstructor   = function(constructor, args) {
            var F = function () {
                return constructor.apply(this, args);
            };

            F.prototype = constructor.prototype;
            return new F();
        };

        /**
         * Функция ищет в имени файла расширение
         * и если находит возвращает true
         * @param name - получает имя файла
         * @param ext - расширение
         */
        this.checkExt           = function(name, ext) {
            var isMatch, str,
                type        = Util.type(ext),
                regStr      = '\\.({{ exts }})$',
                regExp;

            switch(type) {
            case 'string':
                regStr      = Util.render(regStr, {
                    exts: ext
                });

                regExp      = new RegExp(regStr, 'i');
                isMatch     = regExp.test(name);

                break;

            case 'array':
                str         = ext.join('|');
                isMatch     = Util.checkExt(name, str);

                break;
            }

            return isMatch;
        };

        this.check              = new checkProto();

        function checkProto() {
            /**
             * Check is all arguments with names present
             *
             * @param name
             * @param arg
             * @param type
             */
            var check = function check(args, names) {
                var msg         = '',
                    name        = '',
                    template    = '{{ name }} coud not be empty!',

                    indexOf     = Array.prototype.indexOf,

                    lenNames    = names.length,
                    lenArgs     = args.length,
                    lessArgs    = lenArgs < lenNames,
                    emptyIndex  = indexOf.call(args),
                    isEmpty     = ~emptyIndex;

                if (lessArgs || isEmpty) {
                    if (lessArgs)
                        name        = names[lenNames - 1];
                    else
                        name        = names[emptyIndex];

                    msg         = Util.render(template, {
                        name: name
                    });

                    throw(Error(msg));
                }

                return check;
            };

            check.check = check;

            /**
             * Check is type of arg with name is equal to type
             *
             * @param name
             * @param arg
             * @param type
             */
            check.type  = function(name, arg, type) {
                var is = Util.type(arg) === type;

                if (!is)
                    throw(Error(name + ' should be ' + type));

                return check;
            };

            return check;
        }

        /**
         * Copy properties from from to to
         *
         * @param from
         * @param to
         */
        this.copyObj                = function(to, from) {
            if (!from) {
                from    = to;
                to      = {};
            }

            if (to)
                Object.keys(from).forEach(function(name) {
                    to[name]    = from[name];
                });

            return to;
        };

        /**
         * copy objFrom properties to target
         *
         * @target
         * @objFrom
         */
        this.extend                 = function(target, objFrom) {
            var obj,
                keys,
                proto,
                isFunc  = Util.type.function(objFrom),
                isArray = Util.type.array(objFrom),
                isObj   = Util.type.object(target),
                ret     = isObj ? target : {};

            if (isArray)
                objFrom.forEach(function(item) {
                   ret = Util.extend(target, item);
                });

            else if (objFrom) {
                obj     = isFunc ? new objFrom() : objFrom;
                keys    = Object.keys(obj);

                if (!keys.length) {
                    proto = Object.getPrototypeOf(objFrom);
                    keys  = Object.keys(proto);
                }

                keys.forEach(function(name) {
                    ret[name] = obj[name];
                });
            }

            return ret;
        };

        /**
         * extend proto
         *
         * @obj
         */
        this.extendProto           = function(obj) {
            var ret, F      = function() {};
            F.prototype     = Util.extend({}, obj);
            ret             = new F();

            return ret;
        };

        this.json               = new JsonProto();

        function JsonProto() {
            /**
             * @param str
             */
            this.parse      = function(str) {
                var obj;

                Util.exec.try(function() {
                    obj = JSON.parse(str);
                });

                return obj;
            },

            /**
             * @param obj
             */
            this.stringify  = function(obj) {
                var str;

                Util.exec.try(function() {
                    str = JSON.stringify(obj, null, 4);
                });

                return str;
            };
        }

        this.escapeRegExp = function(str) {
            var isStr   = Util.type.string(str);

            if (isStr)
                str = str.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');

            return str;
        };

        /**
         * get regexp from wild card
         */
        this.getRegExp              = function(wildcard) {
            var regExp;

            if (!wildcard)
                wildcard = '*';

            wildcard    = '^' + wildcard /* search from start of line */
                .replace('.', '\\.')
                .replace('*', '.*')
                .replace('?', '.?');

            wildcard    += '$'; /* search to end of line */

            regExp      = new RegExp(wildcard);

            return regExp;
        };

        /**
         * function render template with view and own symbols
         *
         * @param templ
         * @param view
         */
        this.render = function(templ, view) {
            var str, regExp,
                result  = templ;

            Object
                .keys(view)
                .forEach(function(param) {
                    str     = view[param];
                    regExp  = RegExp('{{\\s' + param + '\\s}}', 'g');
                    result  = result.replace(regExp, str);
                });

            if (~result.indexOf('{{'))
                result = result.replace(/{{.*}}/g, '');

            return result;
        };

        this.type                   = new TypeProto();

        function TypeProto() {
            /**
             * get type of variable
             *
             * @param variable
             */
            function type(variable) {
                var regExp      = /\s([a-zA-Z]+)/,
                    str         = {}.toString.call(variable),
                    typeBig     = str.match(regExp)[1],
                    result      = typeBig.toLowerCase();

                return result;
            }

            /**
             * functions check is variable is type of name
             *
             * @param variable
             */
            function typeOf(name, variable) {
                return type(variable) === name;
            }

            function typeOfSimple(name, variable) {
                return typeof variable === name;
            }

            ['null', 'arrayBuffer', 'file', 'array', 'object']
                .forEach(function(name) {
                    type[name] = typeOf.bind(null, name);
                });

            ['string', 'undefined', 'boolean', 'number', 'function']
                .forEach(function(name) {
                    type[name] = typeOfSimple.bind(null, name);
                });

            return type;
        }

        this.exec                       = new ExecProto();

        function ExecProto() {
            /**
             * function do save exec of function
             * @param callback
             * @param arg1
             * ...
             * @param argN
             */
            var exec        = function(callback) {
                var ret,
                    isFunc  = Util.type.function(callback),
                    args    = [].slice.call(arguments, 1);

                if (isFunc)
                    ret     = callback.apply(null, args);

                return ret;
            };

            /*
             * return function that calls callback with arguments
             */

            exec.with           =  function(callback) {
                var result,
                    bind        = Function.bind;

                arguments[0]    = null;
                result          = bind.apply(callback, arguments);

                return result;
            };

             /**
             * return save exec function
             * @param callback
             */
            exec.ret        = function() {
                var result,
                    args        = [].slice.call(arguments);

                args.unshift(exec);
                result          = exec.with.apply(null, args);

                return result;
            };

            /**
             * function do conditional save exec of function
             * @param condition
             * @param callback
             * @param func
             */
            exec.if         = function(condition, callback, func) {
                var ret;

                if (condition)
                    exec(callback);
                else
                    exec(func, callback);

                return ret;
            };

            /**
             * exec function if it exist in object
             *
             * @param obj
             * @param name
             * @param arg
             */
            exec.ifExist                = function(obj, name, arg) {
                var ret,
                    func    = obj && obj[name];

                if (func)
                    func    = func.apply(obj, arg);

                return ret;
            };

            exec.parallel   = function(funcs, callback) {
                var keys        = [],
                    callbackWas = false,
                    arr         = [],
                    obj         = {},
                    count       = 0,
                    countFuncs  = 0,
                    type        = Util.type(funcs);

                Util.check(arguments, ['funcs', 'callback']);

                switch(type) {
                case 'array':
                    countFuncs  = funcs.length;

                    funcs.forEach(function(func, num) {
                        exec(func, function() {
                            checkFunc(num, arguments, arr);
                        });
                    });
                    break;

                case 'object':
                    keys        = Object.keys(funcs);
                    countFuncs  = keys.length;

                    keys.forEach(function(name) {
                        var func    = funcs[name];

                        exec(func, function() {
                            checkFunc(name, arguments, obj);
                        });
                    });
                    break;
                }

                function checkFunc(num, data, all) {
                    var args    = [].slice.call(data, 1),
                        isLast  = false,
                        error   = data[0],
                        length  = args.length;

                    ++count;

                    isLast = count === countFuncs;

                    if (!error)
                        if (length >= 2)
                            all[num] = args;
                        else
                            all[num] = args[0];

                    if (!callbackWas && (error || isLast)) {
                        callbackWas = true;

                        if (type === 'array')
                            callback.apply(null, [error].concat(all));
                        else
                            callback(error, all);
                    }
                }
            };

            /**
             * load functions thrue callbacks one-by-one
             * @param funcs {Array} - array of functions
             */
            exec.series             = function(funcs) {
                var func, callback,
                    isArray     = Util.type.array(funcs);

                if (isArray) {
                    func        = funcs.shift();

                    callback    = function() {
                        return exec.series(funcs);
                    };

                    exec(func, callback);
                }
            };

           /**
             * function execute param function in
             * try...catch block
             *
             * @param callback
             */
            exec.try                = function(callback) {
                var ret;
                try {
                    ret = callback();
                } catch(error) {
                    ret = error;
                }

                return ret;
            };

            return exec;
        }

        /**
         * function gets file extension
         * @param pFileName
         * @return Ext
         */
        this.getExt                     = function(name) {
            var ret     = '',
                dot,
                isStr   = Util.type.string(name);

            if (isStr) {
                dot = name.lastIndexOf('.');

                if (~dot)
                    ret = name.substr(dot);
            }

            return ret;
        };

       /**
         * get values from Object Array name properties
         * or
         * @pObj
         */
        this.getNamesFromObjArray       = function(arr) {
            var ret     = [],
                isArray = Util.type.array(arr);

            if (arr && !isArray)
                arr = arr.data;

            if (arr)
                arr.forEach(function(item) {
                    ret.push(item.name || item);
                });

            return ret;
        };

        /**
         * find object by name in arrray
         *
         * @param array
         * @param name
         */
        this.findObjByNameInArr         = function(array, name) {
            var ret,
                isArray = Util.type.array(array);

            if (isArray) {
                array.some(function(item) {
                    var is = item.name === name,
                        isArray = Util.type.array(item);

                    if (is)
                        ret = item;
                    else if (isArray)
                        item.some(function(item) {
                            is = item.name === name;

                            if (is)
                                ret = item.data;

                            return is;
                        });

                    return is;
                });
            }

            return ret;
        };

        /**
         * Gets current time in format hh:mm:ss
         */
        this.getTime                    = function() {
            var ret,
                date        = new Date(),
                hours       = date.getHours(),
                minutes     = date.getMinutes(),
                seconds     = date.getSeconds();

            minutes         = minutes < 10 ? '0' + minutes : minutes;
            seconds         = seconds < 10 ? '0' + seconds : seconds;

            ret            = hours + ':' + minutes + ':' + seconds;

            return ret;
        };

        /**
         * start timer
         * @param name
         */
        this.time                       = function(name) {
            var console     = Scope.console;

            Util.exec.ifExist(console, 'time', [name]);

            return this;
        };

        /**
         * stop timer
         * @param name
         */
        this.timeEnd                   = function(name) {
            var console    = Scope.console;

            Util.exec.ifExist(console, 'timeEnd', [name]);

            return this;
        };
    }

})(this);
<commit_msg>feature(util) findObjByNameInArr: add arguments check<commit_after>(function(scope) {
    'use strict';

    var Scope = scope.window ? window : global;

    if (typeof module === 'object' && module.exports)
        module.exports = new UtilProto();
    else if (!Scope.Util)
        Scope.Util = new UtilProto();

    function UtilProto() {
        var Util = this;

        /*
         * apply arguemnts to constructor
         *
         * @param constructor
         * @param args
         */
        this.applyConstructor   = function(constructor, args) {
            var F = function () {
                return constructor.apply(this, args);
            };

            F.prototype = constructor.prototype;
            return new F();
        };

        /**
         * Функция ищет в имени файла расширение
         * и если находит возвращает true
         * @param name - получает имя файла
         * @param ext - расширение
         */
        this.checkExt           = function(name, ext) {
            var isMatch, str,
                type        = Util.type(ext),
                regStr      = '\\.({{ exts }})$',
                regExp;

            switch(type) {
            case 'string':
                regStr      = Util.render(regStr, {
                    exts: ext
                });

                regExp      = new RegExp(regStr, 'i');
                isMatch     = regExp.test(name);

                break;

            case 'array':
                str         = ext.join('|');
                isMatch     = Util.checkExt(name, str);

                break;
            }

            return isMatch;
        };

        this.check              = new checkProto();

        function checkProto() {
            /**
             * Check is all arguments with names present
             *
             * @param name
             * @param arg
             * @param type
             */
            var check = function check(args, names) {
                var msg         = '',
                    name        = '',
                    template    = '{{ name }} coud not be empty!',

                    indexOf     = Array.prototype.indexOf,

                    lenNames    = names.length,
                    lenArgs     = args.length,
                    lessArgs    = lenArgs < lenNames,
                    emptyIndex  = indexOf.call(args),
                    isEmpty     = ~emptyIndex;

                if (lessArgs || isEmpty) {
                    if (lessArgs)
                        name        = names[lenNames - 1];
                    else
                        name        = names[emptyIndex];

                    msg         = Util.render(template, {
                        name: name
                    });

                    throw(Error(msg));
                }

                return check;
            };

            check.check = check;

            /**
             * Check is type of arg with name is equal to type
             *
             * @param name
             * @param arg
             * @param type
             */
            check.type  = function(name, arg, type) {
                var is = Util.type(arg) === type;

                if (!is)
                    throw(Error(name + ' should be ' + type));

                return check;
            };

            return check;
        }

        /**
         * Copy properties from from to to
         *
         * @param from
         * @param to
         */
        this.copyObj                = function(to, from) {
            if (!from) {
                from    = to;
                to      = {};
            }

            if (to)
                Object.keys(from).forEach(function(name) {
                    to[name]    = from[name];
                });

            return to;
        };

        /**
         * copy objFrom properties to target
         *
         * @target
         * @objFrom
         */
        this.extend                 = function(target, objFrom) {
            var obj,
                keys,
                proto,
                isFunc  = Util.type.function(objFrom),
                isArray = Util.type.array(objFrom),
                isObj   = Util.type.object(target),
                ret     = isObj ? target : {};

            if (isArray)
                objFrom.forEach(function(item) {
                   ret = Util.extend(target, item);
                });

            else if (objFrom) {
                obj     = isFunc ? new objFrom() : objFrom;
                keys    = Object.keys(obj);

                if (!keys.length) {
                    proto = Object.getPrototypeOf(objFrom);
                    keys  = Object.keys(proto);
                }

                keys.forEach(function(name) {
                    ret[name] = obj[name];
                });
            }

            return ret;
        };

        /**
         * extend proto
         *
         * @obj
         */
        this.extendProto           = function(obj) {
            var ret, F      = function() {};
            F.prototype     = Util.extend({}, obj);
            ret             = new F();

            return ret;
        };

        this.json               = new JsonProto();

        function JsonProto() {
            /**
             * @param str
             */
            this.parse      = function(str) {
                var obj;

                Util.exec.try(function() {
                    obj = JSON.parse(str);
                });

                return obj;
            },

            /**
             * @param obj
             */
            this.stringify  = function(obj) {
                var str;

                Util.exec.try(function() {
                    str = JSON.stringify(obj, null, 4);
                });

                return str;
            };
        }

        this.escapeRegExp = function(str) {
            var isStr   = Util.type.string(str);

            if (isStr)
                str = str.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');

            return str;
        };

        /**
         * get regexp from wild card
         */
        this.getRegExp              = function(wildcard) {
            var regExp;

            if (!wildcard)
                wildcard = '*';

            wildcard    = '^' + wildcard /* search from start of line */
                .replace('.', '\\.')
                .replace('*', '.*')
                .replace('?', '.?');

            wildcard    += '$'; /* search to end of line */

            regExp      = new RegExp(wildcard);

            return regExp;
        };

        /**
         * function render template with view and own symbols
         *
         * @param templ
         * @param view
         */
        this.render = function(templ, view) {
            var str, regExp,
                result  = templ;

            Object
                .keys(view)
                .forEach(function(param) {
                    str     = view[param];
                    regExp  = RegExp('{{\\s' + param + '\\s}}', 'g');
                    result  = result.replace(regExp, str);
                });

            if (~result.indexOf('{{'))
                result = result.replace(/{{.*}}/g, '');

            return result;
        };

        this.type                   = new TypeProto();

        function TypeProto() {
            /**
             * get type of variable
             *
             * @param variable
             */
            function type(variable) {
                var regExp      = /\s([a-zA-Z]+)/,
                    str         = {}.toString.call(variable),
                    typeBig     = str.match(regExp)[1],
                    result      = typeBig.toLowerCase();

                return result;
            }

            /**
             * functions check is variable is type of name
             *
             * @param variable
             */
            function typeOf(name, variable) {
                return type(variable) === name;
            }

            function typeOfSimple(name, variable) {
                return typeof variable === name;
            }

            ['null', 'arrayBuffer', 'file', 'array', 'object']
                .forEach(function(name) {
                    type[name] = typeOf.bind(null, name);
                });

            ['string', 'undefined', 'boolean', 'number', 'function']
                .forEach(function(name) {
                    type[name] = typeOfSimple.bind(null, name);
                });

            return type;
        }

        this.exec                       = new ExecProto();

        function ExecProto() {
            /**
             * function do save exec of function
             * @param callback
             * @param arg1
             * ...
             * @param argN
             */
            var exec        = function(callback) {
                var ret,
                    isFunc  = Util.type.function(callback),
                    args    = [].slice.call(arguments, 1);

                if (isFunc)
                    ret     = callback.apply(null, args);

                return ret;
            };

            /*
             * return function that calls callback with arguments
             */

            exec.with           =  function(callback) {
                var result,
                    bind        = Function.bind;

                arguments[0]    = null;
                result          = bind.apply(callback, arguments);

                return result;
            };

             /**
             * return save exec function
             * @param callback
             */
            exec.ret        = function() {
                var result,
                    args        = [].slice.call(arguments);

                args.unshift(exec);
                result          = exec.with.apply(null, args);

                return result;
            };

            /**
             * function do conditional save exec of function
             * @param condition
             * @param callback
             * @param func
             */
            exec.if         = function(condition, callback, func) {
                var ret;

                if (condition)
                    exec(callback);
                else
                    exec(func, callback);

                return ret;
            };

            /**
             * exec function if it exist in object
             *
             * @param obj
             * @param name
             * @param arg
             */
            exec.ifExist                = function(obj, name, arg) {
                var ret,
                    func    = obj && obj[name];

                if (func)
                    func    = func.apply(obj, arg);

                return ret;
            };

            exec.parallel   = function(funcs, callback) {
                var keys        = [],
                    callbackWas = false,
                    arr         = [],
                    obj         = {},
                    count       = 0,
                    countFuncs  = 0,
                    type        = Util.type(funcs);

                Util.check(arguments, ['funcs', 'callback']);

                switch(type) {
                case 'array':
                    countFuncs  = funcs.length;

                    funcs.forEach(function(func, num) {
                        exec(func, function() {
                            checkFunc(num, arguments, arr);
                        });
                    });
                    break;

                case 'object':
                    keys        = Object.keys(funcs);
                    countFuncs  = keys.length;

                    keys.forEach(function(name) {
                        var func    = funcs[name];

                        exec(func, function() {
                            checkFunc(name, arguments, obj);
                        });
                    });
                    break;
                }

                function checkFunc(num, data, all) {
                    var args    = [].slice.call(data, 1),
                        isLast  = false,
                        error   = data[0],
                        length  = args.length;

                    ++count;

                    isLast = count === countFuncs;

                    if (!error)
                        if (length >= 2)
                            all[num] = args;
                        else
                            all[num] = args[0];

                    if (!callbackWas && (error || isLast)) {
                        callbackWas = true;

                        if (type === 'array')
                            callback.apply(null, [error].concat(all));
                        else
                            callback(error, all);
                    }
                }
            };

            /**
             * load functions thrue callbacks one-by-one
             * @param funcs {Array} - array of functions
             */
            exec.series             = function(funcs) {
                var func, callback,
                    isArray     = Util.type.array(funcs);

                if (isArray) {
                    func        = funcs.shift();

                    callback    = function() {
                        return exec.series(funcs);
                    };

                    exec(func, callback);
                }
            };

           /**
             * function execute param function in
             * try...catch block
             *
             * @param callback
             */
            exec.try                = function(callback) {
                var ret;
                try {
                    ret = callback();
                } catch(error) {
                    ret = error;
                }

                return ret;
            };

            return exec;
        }

        /**
         * function gets file extension
         * @param pFileName
         * @return Ext
         */
        this.getExt                     = function(name) {
            var ret     = '',
                dot,
                isStr   = Util.type.string(name);

            if (isStr) {
                dot = name.lastIndexOf('.');

                if (~dot)
                    ret = name.substr(dot);
            }

            return ret;
        };

       /**
         * get values from Object Array name properties
         * or
         * @pObj
         */
        this.getNamesFromObjArray       = function(arr) {
            var ret     = [],
                isArray = Util.type.array(arr);

            if (arr && !isArray)
                arr = arr.data;

            if (arr)
                arr.forEach(function(item) {
                    ret.push(item.name || item);
                });

            return ret;
        };

        /**
         * find object by name in arrray
         *
         * @param array
         * @param name
         */
        this.findObjByNameInArr         = function(array, name) {
            var ret;

             if (!Array.isArray(array))
                throw(Error('array should be array!'));

            if (typeof name !== 'string')
                throw(Error('name should be string!'));

            array.some(function(item) {
                var is = item.name === name,
                    isArray = Util.type.array(item);

                if (is)
                    ret = item;
                else if (isArray)
                    item.some(function(item) {
                        is = item.name === name;

                        if (is)
                            ret = item.data;

                        return is;
                    });

                return is;
            });

            return ret;
        };

        /**
         * Gets current time in format hh:mm:ss
         */
        this.getTime                    = function() {
            var ret,
                date        = new Date(),
                hours       = date.getHours(),
                minutes     = date.getMinutes(),
                seconds     = date.getSeconds();

            minutes         = minutes < 10 ? '0' + minutes : minutes;
            seconds         = seconds < 10 ? '0' + seconds : seconds;

            ret            = hours + ':' + minutes + ':' + seconds;

            return ret;
        };

        /**
         * start timer
         * @param name
         */
        this.time                       = function(name) {
            var console     = Scope.console;

            Util.exec.ifExist(console, 'time', [name]);

            return this;
        };

        /**
         * stop timer
         * @param name
         */
        this.timeEnd                   = function(name) {
            var console    = Scope.console;

            Util.exec.ifExist(console, 'timeEnd', [name]);

            return this;
        };
    }

})(this);
<|endoftext|>


<commit_before>/**
 * Created by nuintun on 2015/4/27.
 */

'use strict';

var is = require('is');
var path = require('path');
var join = path.join;
var extname = path.extname;
var dirname = path.dirname;
var basename = path.basename;
var isAbsolute = path.isAbsolute;
var util = require('util');
var debug = require('debug')('gulp-cmd');
var colors = require('colors/safe');

// the work cwd
var cwd = process.cwd();

// set colors theme
colors.setTheme({
  input: 'magenta',
  verbose: 'cyan',
  prompt: 'grey',
  info: 'green',
  data: 'grey',
  help: 'cyan',
  warn: 'yellow',
  debug: 'blue',
  error: 'red',
  inputBold: ['magenta', 'bold'],
  verboseBold: ['cyan', 'bold'],
  promptBold: ['grey', 'bold'],
  infoBold: ['green', 'bold'],
  dataBold: ['grey', 'bold'],
  helpBold: ['cyan', 'bold'],
  warnBold: ['yellow', 'bold'],
  debugBold: ['blue', 'bold'],
  errorBold: ['red', 'bold']
});

/**
 * parse package form vinyl
 * @param vinyl
 * @param wwwroot
 * @returns {object}
 */
function parsePackage(vinyl, wwwroot){
  var relative = vinyl.relative;

  // vinyl not in base dir, user wwwroot
  if (isRelative(relative)) {
    relative = path.relative(wwwroot, vinyl.path);
    // vinyl not in wwwroot, throw error
    if (isRelative(relative)) {
      throwError('file: %s is out of bound of wwwroot: %s.', normalize(vinyl.path), normalize(wwwroot));
    }

    // reset relative
    relative = path.join('/', relative);
  }

  var dir = normalize(dirname(relative));
  var filename = basename(relative);
  var SPLITRE = /\/((?:\d+\.){2}\d+)(?:\/|$)/;
  var match = dir.split(SPLITRE);

  return {
    name: match[0] || '',
    version: match[1] || '',
    file: match[2] ? match[2] + '/' + filename : filename
  }
}

/**
 * simple template
 * ```
 * var tpl = '{{name}}/{{version}}';
 * util.template(tpl, {name:'base', version: '1.0.0'});
 * ```
 */

function template(format, data){
  if (!is.string(format)) return '';

  return format.replace(/{{([a-z]*)}}/gi, function (all, match){
    return data[match] || '';
  });
}

/**
 * get rename options
 * @param transform
 * @returns {*}
 */

function initRenameOptions(transform){
  if (is.fn(transform)) {
    return transform;
  }

  transform = transform || {};

  if (transform.min) {
    transform.suffix = '-min';
  }

  if (transform.debug) {
    transform.suffix = '-debug';
  }

  return transform;
}

/**
 * set options
 * @param options
 * @returns {object}
 */

function initOptions(options){
  var defaults = {
    vars: {}, // the vars
    paths: {}, // the paths
    alias: {}, // the alias
    cache: true, // use memory file cahe
    ignore: [], // omit the given dependencies when include
    wwwroot: '', // web root
    rename: null, // { debug: boolean, min: boolean }
    prefix: null, // css prefix
    oncsspath: null, // css resource path callback
    include: 'relative', // include model: self, relative, all
    idleading: '{{name}}/{{version}}/{{file}}' // the id prefix template
  };

  extend(true, defaults, options);

  if (defaults.wwwroot && !is.string(defaults.wwwroot)) {
    throwError('options.wwwroot\'s value should be string.');
  }

  // set wwwroot
  defaults.wwwroot = join(cwd, defaults.wwwroot);
  // format ignore
  defaults.ignore = Array.isArray(defaults.ignore) ? defaults.ignore : [];
  // format oncsspath
  defaults.oncsspath = is.fn(defaults.oncsspath) ? defaults.oncsspath : null;
  // format rename
  defaults.rename = initRenameOptions(defaults.rename);

  return defaults;
}

var PATHS_RE = /^([^/:]+)(\/.+)$/;
var VARS_RE = /{([^{]+)}/g;

/**
 * parse alias
 * @param id
 * @param alias
 * @returns {*}
 */

function parseAlias(id, alias){
  alias = alias || {};

  return alias && is.string(alias[id]) ? alias[id] : id;
}

/**
 * parse paths
 * @param id
 * @param paths
 * @returns {*}
 */

function parsePaths(id, paths){
  var match;

  paths = paths || {};

  if (paths && (match = id.match(PATHS_RE)) && is.string(paths[match[1]])) {
    id = paths[match[1]] + match[2];
  }

  return id;
}

/**
 * parse vars
 * @param id
 * @param vars
 * @returns {*}
 */

function parseVars(id, vars){
  vars = vars || {};

  if (vars && id.indexOf('{') > -1) {
    id = id.replace(VARS_RE, function (match, key){
      return is.string(vars[key]) ? vars[key] : match;
    });
  }

  return id;
}

/**
 * normalize path
 * @param path
 * @returns {string}
 */

function normalize(path){
  path = path.replace(/\\+/g, '/');
  path = path.replace(/([^:/])\/+\//g, '$1/');
  path = path.replace(/^\/{2,}|(:)\/{2,}/, '//');

  return path;
}

/**
 * resolve a `relative` path base on `base` path
 * @param relative
 * @param vinyl
 * @param wwwroot
 * @returns {string}
 */

function resolve(relative, vinyl, wwwroot){
  var base;
  var absolute;

  // debug
  debug('resolve path: %s', colors.dataBold(normalize(relative)));

  // resolve
  if (isRelative(relative)) {
    base = dirname(vinyl.path);
    absolute = join(base, relative);

    // out of base, use wwwroot
    if (isRelative(absolute)) {
      base = wwwroot;
      absolute = join(base, relative);

      // out of wwwroot
      if (isRelative(absolute)) {
        throwError('file: %s is out of bound of wwwroot: %s.', normalize(absolute), normalize(base));
      }
    }
  } else if (isAbsolute(relative)) {
    base = wwwroot;
    absolute = join(base, relative.substring(1));
  } else {
    base = join(vinyl.cwd, vinyl.base);
    absolute = join(base, relative);
  }

  // debug
  debug('of base path: %s', colors.dataBold(relativeCwd(base)));
  debug('to: %s', colors.dataBold(relativeCwd(absolute)));

  return absolute;
}

/**
 * hide .js if exists
 * @param filepath
 * @returns {*}
 */

function hideExt(filepath){
  return extname(filepath) === '.js' ? filepath.replace(/\.js$/, '') : filepath;
}

/**
 * add .js if not exists
 * @param filepath
 * @returns {*}
 */

function addExt(filepath){
  return extname(filepath) === '.js' ? filepath : (filepath + '.js');
}

/**
 * test filepath is relative path or not
 * @param filepath
 * @returns {boolean}
 */

function isRelative(filepath){
  return /^\.{1,2}[\\/]/.test(filepath);
}

/**
 * test filepath is local path or not
 * @param filepath
 * @returns {boolean}
 */

function isLocal(filepath){
  return !/^https?:\/\/|^\/\//.test(filepath) && !/^data:/.test(filepath);
}

/**
 * get relative path from cwd
 * @param filepath
 * @returns {string}
 */

function relativeCwd(filepath){
  return normalize(path.relative(cwd, filepath));
}

/**
 * Plugin error
 */

function throwError(){
  var slice = [].slice;
  var message = util.format
    .apply(null, slice.call(arguments));

  throw new Error(message);
}

/**
 * node.extend
 * Copyright 2011, John Resig
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * @fileoverview
 * Port of jQuery.extend that actually works on node.js
 */

function extend(){
  var target = arguments[0] || {};
  var i = 1;
  var length = arguments.length;
  var deep = false;
  var options, name, src, copy, copy_is_array, clone;

  // handle a deep copy situation
  if (typeof target === 'boolean') {
    deep = target;
    target = arguments[1] || {};
    // skip the boolean and the target
    i = 2;
  }

  // handle case when target is a string or something (possible in deep copy)
  if (typeof target !== 'object' && !is.fn(target)) {
    target = {};
  }

  for (; i < length; i++) {
    // only deal with non-null/undefined values
    options = arguments[i];

    if (options !== null) {
      if (typeof options === 'string') {
        options = options.split('');
      }

      // extend the base object
      for (name in options) {
        if (options.hasOwnProperty(name)) {
          src = target[name];
          copy = options[name];

          // prevent never-ending loop
          if (target === copy) {
            continue;
          }

          // recurse if we're merging plain objects or arrays
          if (deep && copy && (is.hash(copy) || (copy_is_array = Array.isArray(copy)))) {
            if (copy_is_array) {
              copy_is_array = false;
              clone = src && Array.isArray(src) ? src : [];
            } else {
              clone = src && is.hash(src) ? src : {};
            }

            // never move original objects, clone them
            target[name] = extend(deep, clone, copy);

            // don't bring in undefined values
          } else if (typeof copy !== 'undefined') {
            target[name] = copy;
          }
        }
      }
    }
  }

  // return the modified object
  return target;
}

/**
 * transform array to string
 * @param arr
 * @returns {string}
 */

function arr2str(arr){
  return arr.map(function (item){
    return '"' + item + '"';
  }).join(', ');
}

/**
 * wrap module
 * @param id
 * @param deps
 * @param code
 * @returns {string}
 */

function wrapModule(id, deps, code){
  deps = arr2str(deps);

  // header and footer template string
  var headerTpl = 'define("{{id}}", [{{deps}}], function(require, exports, module){';
  var footerTpl = '});\n\n';

  if (Buffer.isBuffer(code)) code = code.toString();

  // debug
  debug('compile module: %s', colors.dataBold(id));

  return template(headerTpl, { id: id, deps: deps })
    + '\n' + code + '\n' + footerTpl;
}

/**
 * Exports module.
 */

exports.cwd = cwd;
exports.template = template;
exports.parsePackage = parsePackage;
exports.initOptions = initOptions;
exports.normalize = normalize;
exports.parseAlias = parseAlias;
exports.parsePaths = parsePaths;
exports.parseVars = parseVars;
exports.hideExt = hideExt;
exports.addExt = addExt;
exports.isRelative = isRelative;
exports.isAbsolute = isAbsolute;
exports.isLocal = isLocal;
exports.resolve = resolve;
exports.relativeCwd = relativeCwd;
exports.throwError = throwError;
exports.extend = extend;
exports.colors = colors;
exports.debug = debug;
exports.wrapModule = wrapModule;
<commit_msg>add source files<commit_after>/**
 * Created by nuintun on 2015/4/27.
 */

'use strict';

var is = require('is');
var path = require('path');
var join = path.join;
var extname = path.extname;
var dirname = path.dirname;
var basename = path.basename;
var isAbsolute = path.isAbsolute;
var util = require('util');
var debug = require('debug')('gulp-cmd');
var colors = require('colors/safe');

// the work cwd
var cwd = process.cwd();

// set colors theme
colors.setTheme({
  input: 'magenta',
  verbose: 'cyan',
  prompt: 'gray',
  info: 'green',
  data: 'grey',
  help: 'cyan',
  warn: 'yellow',
  debug: 'blue',
  error: 'red',
  inputBold: ['magenta', 'bold'],
  verboseBold: ['cyan', 'bold'],
  promptBold: ['gray', 'bold'],
  infoBold: ['green', 'bold'],
  dataBold: ['grey', 'bold'],
  helpBold: ['cyan', 'bold'],
  warnBold: ['yellow', 'bold'],
  debugBold: ['blue', 'bold'],
  errorBold: ['red', 'bold']
});

/**
 * parse package form vinyl
 * @param vinyl
 * @param wwwroot
 * @returns {object}
 */
function parsePackage(vinyl, wwwroot){
  var relative = vinyl.relative;

  // vinyl not in base dir, user wwwroot
  if (isRelative(relative)) {
    relative = path.relative(wwwroot, vinyl.path);
    // vinyl not in wwwroot, throw error
    if (isRelative(relative)) {
      throwError('file: %s is out of bound of wwwroot: %s.', normalize(vinyl.path), normalize(wwwroot));
    }

    // reset relative
    relative = path.join('/', relative);
  }

  var dir = normalize(dirname(relative));
  var filename = basename(relative);
  var SPLITRE = /\/((?:\d+\.){2}\d+)(?:\/|$)/;
  var match = dir.split(SPLITRE);

  return {
    name: match[0] || '',
    version: match[1] || '',
    file: match[2] ? match[2] + '/' + filename : filename
  }
}

/**
 * simple template
 * ```
 * var tpl = '{{name}}/{{version}}';
 * util.template(tpl, {name:'base', version: '1.0.0'});
 * ```
 */

function template(format, data){
  if (!is.string(format)) return '';

  return format.replace(/{{([a-z]*)}}/gi, function (all, match){
    return data[match] || '';
  });
}

/**
 * get rename options
 * @param transform
 * @returns {*}
 */

function initRenameOptions(transform){
  if (is.fn(transform)) {
    return transform;
  }

  transform = transform || {};

  if (transform.min) {
    transform.suffix = '-min';
  }

  if (transform.debug) {
    transform.suffix = '-debug';
  }

  return transform;
}

/**
 * set options
 * @param options
 * @returns {object}
 */

function initOptions(options){
  var defaults = {
    vars: {}, // the vars
    paths: {}, // the paths
    alias: {}, // the alias
    cache: true, // use memory file cahe
    ignore: [], // omit the given dependencies when include
    wwwroot: '', // web root
    rename: null, // { debug: boolean, min: boolean }
    prefix: null, // css prefix
    oncsspath: null, // css resource path callback
    include: 'relative', // include model: self, relative, all
    idleading: '{{name}}/{{version}}/{{file}}' // the id prefix template
  };

  extend(true, defaults, options);

  if (defaults.wwwroot && !is.string(defaults.wwwroot)) {
    throwError('options.wwwroot\'s value should be string.');
  }

  // set wwwroot
  defaults.wwwroot = join(cwd, defaults.wwwroot);
  // format ignore
  defaults.ignore = Array.isArray(defaults.ignore) ? defaults.ignore : [];
  // format oncsspath
  defaults.oncsspath = is.fn(defaults.oncsspath) ? defaults.oncsspath : null;
  // format rename
  defaults.rename = initRenameOptions(defaults.rename);

  return defaults;
}

var PATHS_RE = /^([^/:]+)(\/.+)$/;
var VARS_RE = /{([^{]+)}/g;

/**
 * parse alias
 * @param id
 * @param alias
 * @returns {*}
 */

function parseAlias(id, alias){
  alias = alias || {};

  return alias && is.string(alias[id]) ? alias[id] : id;
}

/**
 * parse paths
 * @param id
 * @param paths
 * @returns {*}
 */

function parsePaths(id, paths){
  var match;

  paths = paths || {};

  if (paths && (match = id.match(PATHS_RE)) && is.string(paths[match[1]])) {
    id = paths[match[1]] + match[2];
  }

  return id;
}

/**
 * parse vars
 * @param id
 * @param vars
 * @returns {*}
 */

function parseVars(id, vars){
  vars = vars || {};

  if (vars && id.indexOf('{') > -1) {
    id = id.replace(VARS_RE, function (match, key){
      return is.string(vars[key]) ? vars[key] : match;
    });
  }

  return id;
}

/**
 * normalize path
 * @param path
 * @returns {string}
 */

function normalize(path){
  path = path.replace(/\\+/g, '/');
  path = path.replace(/([^:/])\/+\//g, '$1/');
  path = path.replace(/^\/{2,}|(:)\/{2,}/, '//');

  return path;
}

/**
 * resolve a `relative` path base on `base` path
 * @param relative
 * @param vinyl
 * @param wwwroot
 * @returns {string}
 */

function resolve(relative, vinyl, wwwroot){
  var base;
  var absolute;

  // debug
  debug('resolve path: %s', colors.dataBold(normalize(relative)));

  // resolve
  if (isRelative(relative)) {
    base = dirname(vinyl.path);
    absolute = join(base, relative);

    // out of base, use wwwroot
    if (isRelative(absolute)) {
      base = wwwroot;
      absolute = join(base, relative);

      // out of wwwroot
      if (isRelative(absolute)) {
        throwError('file: %s is out of bound of wwwroot: %s.', normalize(absolute), normalize(base));
      }
    }
  } else if (isAbsolute(relative)) {
    base = wwwroot;
    absolute = join(base, relative.substring(1));
  } else {
    base = join(vinyl.cwd, vinyl.base);
    absolute = join(base, relative);
  }

  // debug
  debug('of base path: %s', colors.dataBold(relativeCwd(base)));
  debug('to: %s', colors.dataBold(relativeCwd(absolute)));

  return absolute;
}

/**
 * hide .js if exists
 * @param filepath
 * @returns {*}
 */

function hideExt(filepath){
  return extname(filepath) === '.js' ? filepath.replace(/\.js$/, '') : filepath;
}

/**
 * add .js if not exists
 * @param filepath
 * @returns {*}
 */

function addExt(filepath){
  return extname(filepath) === '.js' ? filepath : (filepath + '.js');
}

/**
 * test filepath is relative path or not
 * @param filepath
 * @returns {boolean}
 */

function isRelative(filepath){
  return /^\.{1,2}[\\/]/.test(filepath);
}

/**
 * test filepath is local path or not
 * @param filepath
 * @returns {boolean}
 */

function isLocal(filepath){
  return !/^https?:\/\/|^\/\//.test(filepath) && !/^data:/.test(filepath);
}

/**
 * get relative path from cwd
 * @param filepath
 * @returns {string}
 */

function relativeCwd(filepath){
  return normalize(path.relative(cwd, filepath));
}

/**
 * Plugin error
 */

function throwError(){
  var slice = [].slice;
  var message = util.format
    .apply(null, slice.call(arguments));

  throw new Error(message);
}

/**
 * node.extend
 * Copyright 2011, John Resig
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * @fileoverview
 * Port of jQuery.extend that actually works on node.js
 */

function extend(){
  var target = arguments[0] || {};
  var i = 1;
  var length = arguments.length;
  var deep = false;
  var options, name, src, copy, copy_is_array, clone;

  // handle a deep copy situation
  if (typeof target === 'boolean') {
    deep = target;
    target = arguments[1] || {};
    // skip the boolean and the target
    i = 2;
  }

  // handle case when target is a string or something (possible in deep copy)
  if (typeof target !== 'object' && !is.fn(target)) {
    target = {};
  }

  for (; i < length; i++) {
    // only deal with non-null/undefined values
    options = arguments[i];

    if (options !== null) {
      if (typeof options === 'string') {
        options = options.split('');
      }

      // extend the base object
      for (name in options) {
        if (options.hasOwnProperty(name)) {
          src = target[name];
          copy = options[name];

          // prevent never-ending loop
          if (target === copy) {
            continue;
          }

          // recurse if we're merging plain objects or arrays
          if (deep && copy && (is.hash(copy) || (copy_is_array = Array.isArray(copy)))) {
            if (copy_is_array) {
              copy_is_array = false;
              clone = src && Array.isArray(src) ? src : [];
            } else {
              clone = src && is.hash(src) ? src : {};
            }

            // never move original objects, clone them
            target[name] = extend(deep, clone, copy);

            // don't bring in undefined values
          } else if (typeof copy !== 'undefined') {
            target[name] = copy;
          }
        }
      }
    }
  }

  // return the modified object
  return target;
}

/**
 * transform array to string
 * @param arr
 * @returns {string}
 */

function arr2str(arr){
  return arr.map(function (item){
    return '"' + item + '"';
  }).join(', ');
}

/**
 * wrap module
 * @param id
 * @param deps
 * @param code
 * @returns {string}
 */

function wrapModule(id, deps, code){
  deps = arr2str(deps);

  // header and footer template string
  var headerTpl = 'define("{{id}}", [{{deps}}], function(require, exports, module){';
  var footerTpl = '});\n\n';

  if (Buffer.isBuffer(code)) code = code.toString();

  // debug
  debug('compile module: %s', colors.dataBold(id));

  return template(headerTpl, { id: id, deps: deps })
    + '\n' + code + '\n' + footerTpl;
}

/**
 * Exports module.
 */

exports.cwd = cwd;
exports.template = template;
exports.parsePackage = parsePackage;
exports.initOptions = initOptions;
exports.normalize = normalize;
exports.parseAlias = parseAlias;
exports.parsePaths = parsePaths;
exports.parseVars = parseVars;
exports.hideExt = hideExt;
exports.addExt = addExt;
exports.isRelative = isRelative;
exports.isAbsolute = isAbsolute;
exports.isLocal = isLocal;
exports.resolve = resolve;
exports.relativeCwd = relativeCwd;
exports.throwError = throwError;
exports.extend = extend;
exports.colors = colors;
exports.debug = debug;
exports.wrapModule = wrapModule;
<|endoftext|>


<commit_before>exports.generate = function (length, radix) {
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
    var uuid = [], rnd = Math.random;
    length = length || 8;
    radix = radix || chars.length;
    for (var i = 0; i < length; i++) {
        uuid[i] = chars[0 | rnd()*radix];
    }
    return uuid.join('');
};<commit_msg>chars is now called uuid_chars.<commit_after>var uuid_chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
exports.generate = function (length, radix) {
    var uuid = '', rnd = Math.random;
    length = length || 8;
    radix = radix || uuid_chars.length;
    for (var i = 0; i < length; i++) {
        uuid += uuid_chars[0 | rnd()*radix];
    }
    return uuid;
};<|endoftext|>


<commit_before>import NProgress from 'nprogress'

login = function() {
	if(getCookie("auth") !== undefined){
		console.log("Logged - Do not clear cookies");
		if(getLocal("auth") === null) {
			setLocalFromCookie("auth", "auth");
		}
		return getCookie("auth");
	}else{
		if(getLocal("auth") !== null){
			console.log("Logged - Do not clear LS");
			return getLocal("auth");
		}else{
			console.log("Logging in ..");
			return setLocal("auth");
		}
	}
}

getPaste = function(params) {
	Meteor.call('getPaste', params.pasteName, function(err,response){
		if (err) {console.log(err); return 1;}
		if (response === 1) {
			Session.set('pasteText', "No paste found");}
		else {
			Session.set('pasteText', response.text);
			Session.set('pasteTitle', response.title);
			Session.set('pasteLang', response.language);
			Session.set('isPasteEncrypted', response.isEncry);
			Session.set('isForked', response.isFork);
			Session.set('isBookmarked', response.isBookmark);
			Session.set('pasteId', response._id);
			Session.set('numbersOfViews', response.numbersOfViews);
			editor.getSession().setMode("ace/mode/" + checkFramework(Session.get("pasteLang")));
			if(Session.get("pasteKey") !== undefined) {
				Session.set("pasteText",  sjcl.decrypt( Session.get("pasteKey"), Session.get("pasteText") ));
			}else if(Session.get("isPasteEncrypted") && Session.get("pasteKey") === undefined ){
				Session.set("pasteText", "Add the key to the URL");
				Session.set("pasteLang","You need a key to view this paste");
			}
			initEditor();
			startReadWriteTracker();
		}
	});
}

getBasicPaste = function(params) {
	Meteor.call('getPaste', params.pasteName, function(err,response){
		if (err) {console.log(err); return 1;}
		if (response === 1) {
			Session.set('pasteText', "No paste found");
		} else if (response.isEncry) {
			Session.set('pasteText', "This paste is encrypted");
		} else {
			Session.set("pasteName", params.pasteName);
			Session.set('pasteText', response.text);
			Session.set('pasteTitle', response.title);
			Session.set('pasteLang', response.language);
			Session.set('isPasteEncrypted', response.isEncry);
			Session.set('isForked', response.isFork);
			Session.set('isBookmarked', response.isBookmark);
			Session.set('numbersOfViews', response.numbersOfViews);
			editor.getSession().setMode("ace/mode/" + checkFramework(Session.get("pasteLang")));
			editor.setValue(Session.get("pasteText"));
			currentLines = editor.session.getLength();
			editor.setOptions({
			    maxLines: currentLines < 37 ? currentLines : 37
			});
			editor.moveCursorTo(0,0);
		}
	});
}

uploadBlob = function(action) {
	//action-> 0 : new paste
	//action-> 1 : new bookmark from other paste
	var blob = editor.getValue();
	var titlePaste;
	var langPaste;
	var key = "";
	if(!action){ //new paste
		Session.set("isBookmark", false);
		titlePaste = document.getElementById('pasteName').value;
		langPaste = document.getElementById('selectLanguage');
		langPaste = langPaste.options[langPaste.selectedIndex].value;
	}else{ //new save form other paste
		Session.set("isBookmark", true);
		titlePaste = document.getElementById('pasteName').childNodes[4].nextSibling.data;
		langPaste = document.getElementById('pasteLang').textContent;
		langPaste = langPaste.slice(1, -1);
	}
	// Check that text field is not blank before adding paste
	if (blob !== '' && titlePaste !== '') {
		if(Session.get("isPasteEncrypted") === true){
			var s = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
			key = Array(17).join().split(',').map(function() { return s.charAt(Math.floor(Math.random() * s.length)); }).join('');
			blob = sjcl.encrypt(key, blob);
		}
		Meteor.call("addPaste", blob, titlePaste, langPaste, Session.get("auth"),
								Session.get("isPasteEncrypted"), Session.get("isFork"),
								Session.get("pasteName"), Session.get("isBookmark"),
								Session.get("isPasteHided"), function (err, response) {
			if (err) {console.log(err);}
			document.getElementById("tools").classList.add("hideSlow");
			//document.getElementById('submitPaste').classList.add("ready");
			NProgress.configure({ easing: 'ease', speed: 500 });
			NProgress.start();
			NProgress.inc();
			setTimeout(function(){
				NProgress.done();
				localStorage.setItem(response[0], key); //store key for easy access
				takeMeToPaste(response[0], key); //redirect user
			},1000);
		}); //call server-side method addPaste
	} else {
		Notify.startToast(2000, "Either title or paste is empty", "OPS...");
	}
};

updateBlob = function() {
	var blob = editor.getValue();
	//var titlePaste = document.getElementById('pasteName').childNodes[0].nextSibling.data;
	Meteor.call("updatePaste", blob, Session.get("pasteTitle"), Session.get("pasteId"), Session.get("auth"), function(err, response){
		if(err) {alert(err);}
	});
};

bookmarkPaste = function() {
	if(!Session.get("isBookmarked")){
		Meteor.call("addBookmark", Session.get("pasteName"), Session.get("pasteTitle"), Session.get("auth"), function (err, response){
			if(err) {console.log(err);}
		});
	}
};

deletePaste = function(pasteId) {
	Meteor.call("deletePaste", pasteId, Session.get("auth"), function(err,response){
		if(err) {console.log(err);}
		else {Notify.startToast(2000, "This paste has been deleted", "Deleted");}
		loadUserPastes();
		if(Session.get("pasteId") === pasteId) {document.location.reload(false);}
	});
};

deleteBookmark = function(bookmarkId) {
	Meteor.call("deleteBookmark", bookmarkId, Session.get("auth"), function(err,response){
		if(err) {console.log(err);}
		else {Notify.startToast(2000, "This bookmark has been deleted", "Deleted");}
	});
};

loadUserPastes = function() {
	Meteor.call("getUserPastes", Session.get("auth"), function (err, response){
		if(err) {console.log(err);}
		if(response === 1) {
			console.log("A server error has occurred");
		}else{
			Session.set("userPastesLoaded", true);
			Session.set("userPastes", response);
			var userPastesIds = [];
			for (var i = response.userPastes.length - 1; i >= 0; i--) {
				userPastesIds.push(response.userPastes[i]._id);
			}
			Session.set("userPastesIds", userPastesIds);
		}
	});
};

loadLangs = function() {
	HTTP.get(Meteor.absoluteUrl("languages.json"), function(e, data) {
		Session.set("langList", data.data);
		Session.set("lastLang", localStorage.getItem("lastLang"))
		Session.set("langListReady", true);
		if(Session.get("isHome")){
			var lang = checkFramework(Session.get("lastLang"));
			editor.getSession().setMode("ace/mode/" + lang);
		}
	});
};

downloadBlob = function(filename, text) {
	var element = document.createElement('a');
	element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
	element.setAttribute('download', filename);
	element.style.display = 'none';
	document.body.appendChild(element);
	element.click();
	document.body.removeChild(element);
};

takeMeToPaste = function (pasteName, key) {
	window.onbeforeunload = null
	if (key === ""){
		FlowRouter.go("/pastes/" + pasteName);
	}else {
		FlowRouter.go("/pastes/" + pasteName + "/" + key);
	}
};

getCookie = function(name) {
  var value = "; " + document.cookie;
  var parts = value.split("; " + name + "=");
  if (parts.length === 2) {return parts.pop().split(";").shift();}
};

getLocal = function(name) {
	return localStorage.getItem(name);
}

setLocal = function(name) {
	var s = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789£$&^";
	var userName = Array(9).join().split(',').map(function() { return s.charAt(Math.floor(Math.random() * s.length)); }).join('');
	localStorage.setItem(name, userName);
	return userName;
}

setLocalLang = function(lang) {
	localStorage.setItem("lastLang", lang);
}

setLocalFromCookie = function(name, cookieValue) {
	localStorage.setItem(name, getCookie(cookieValue));
}

setCookie = function (argument) {
	var s = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789£$&^";
	var userName = Array(9).join().split(',').map(function() { return s.charAt(Math.floor(Math.random() * s.length)); }).join('');
	document.cookie ='auth=' + userName + '; expires=Fri, 3 Aug 2100 20:47:11 UTC; path=/';
};

KeyPress = function (e) {
	var evtobj = window.event? event : e;
	if (evtobj.ctrlKey && evtobj.keyCode === 37) {slideout.open();}
	if (evtobj.ctrlKey && evtobj.keyCode === 39) {slideout.close();}
	if (evtobj.ctrlKey && evtobj.keyCode === 40) {downloadBlob(Session.get("pasteTitle"), Session.get("pasteText"));}
	if (evtobj.ctrlKey && evtobj.keyCode === 38) {try{uploadBlob(0);}catch(e){}}
};

savePaste = function () {
	if( Session.get("userPastesIds").indexOf(Session.get("pasteId")) > -1 ) {
		if( Session.get("pasteText") !== editor.getValue() ) {//need to update paste
			if( !Session.get("isFork") ){ //if i'm not forking one of my projects
				updateBlob();
			}
		}
	}
};

initEditor = function () {
	console.log("init");
	editor.setValue(Session.get("pasteText"));
	var lastURL = Session.get("lastHref");
	Session.set("lastHref", FlowRouter.current().context.path);
	var range;
	editor.getSession().setUseWrapMode(true);
	var hashRow = FlowRouter.current().context.hash;
	if(hashRow){
			var lineNumber = +hashRow.slice(1);
			editor.gotoLine(lineNumber,0);
			editor.selection.selectLineEnd();
	} else {
		console.log("no hash")
		editor.navigateTo(0,0);
	}
	editor.setShowPrintMargin(false);
	Session.set('cursorPosition', editor.getSession().selection.getCursor());
	//editor.focus();
	Session.set('length', editor.getSession().getLength());
	editor.commands.addCommand({
	    name: 'selectNext',
	    bindKey: {win: 'Ctrl-D',  mac: 'Command-D'},
	    exec: function(editor) {
	        editor.selectMore(1, false);
	    }
	});
	editor.on("change", function(e){
		Session.set('length', editor.getSession().getLength());
	});
	editor.getSession().selection.on('changeCursor', function(e) {
		Session.set('cursorPosition', editor.getSession().selection.getCursor());
	});
	editor.getSession().selection.on('changeSelection', function(e) {
		range = editor.getSession().selection.getRange();
		Session.set("selectionRowRange", range.end.row - range.start.row);
		Session.set("rangeLength", editor.getSelectedText().length);
	});
	if(Session.get("isPaste")){
		editor.on("guttermousedown", function(e){
			console.log(e)
			window.location.hash = "L" + (e.getDocumentPosition().row + 1);
		})
	}
};

startReadWriteTracker = function () {
	Tracker.autorun(function () {
		if(Session.get("userPastesIds").indexOf(Session.get("pasteId"))>-1 || Session.get("isFork")){
			editor.setReadOnly(0);
		}else {editor.setReadOnly(1);}
	});
};

openMegaSlideout = function () {
	slideout.close();
	setTimeout(function(){megaSlideout.open();},600);
};

const jsFrameworks = ["angularjs","atom","backbone","d3js","grunt","gulp","jquery","meteor","nodejs","react", "kraken"]
const phpFrameworks = ["laravel"]
const android = ["android"]
const git = ["git"]

checkFramework = function(lang) {
	if(jsFrameworks.indexOf(lang) > -1){return "javascript";}
	if(phpFrameworks.indexOf(lang) > -1){return "php";}
	if(android.indexOf(lang) > -1){return "java";}
	if(git.indexOf(lang) > -1){return "gitignore";}
	return lang;
}

showEmbedDialog = function() {
	document.getElementById("bodyContainer").classList.add("blurred");
	document.getElementsByClassName("embedDialogContainer")[0].classList.remove("dialogClose");
	document.getElementsByClassName("embedDialogContainer")[0].classList.add("dialogOpen");
}

hideEmbedDialog = function() {
	document.getElementById("bodyContainer").classList.remove("blurred");
	document.getElementsByClassName("embedDialogContainer")[0].classList.remove("dialogOpen");
	document.getElementsByClassName("embedDialogContainer")[0].classList.add("dialogClose");
	document.getElementsByClassName("embedDialogContainer")[0].addEventListener('animationend', function(){
			document.getElementsByClassName("embedDialogContainer")[0].classList.remove("dialogClose");
		}, false);
}<commit_msg>multi gutterline<commit_after>import NProgress from 'nprogress'

login = function() {
	if(getCookie("auth") !== undefined){
		console.log("Logged - Do not clear cookies");
		if(getLocal("auth") === null) {
			setLocalFromCookie("auth", "auth");
		}
		return getCookie("auth");
	}else{
		if(getLocal("auth") !== null){
			console.log("Logged - Do not clear LS");
			return getLocal("auth");
		}else{
			console.log("Logging in ..");
			return setLocal("auth");
		}
	}
}

getPaste = function(params) {
	Meteor.call('getPaste', params.pasteName, function(err,response){
		if (err) {console.log(err); return 1;}
		if (response === 1) {
			Session.set('pasteText', "No paste found");}
		else {
			Session.set('pasteText', response.text);
			Session.set('pasteTitle', response.title);
			Session.set('pasteLang', response.language);
			Session.set('isPasteEncrypted', response.isEncry);
			Session.set('isForked', response.isFork);
			Session.set('isBookmarked', response.isBookmark);
			Session.set('pasteId', response._id);
			Session.set('numbersOfViews', response.numbersOfViews);
			editor.getSession().setMode("ace/mode/" + checkFramework(Session.get("pasteLang")));
			if(Session.get("pasteKey") !== undefined) {
				Session.set("pasteText",  sjcl.decrypt( Session.get("pasteKey"), Session.get("pasteText") ));
			}else if(Session.get("isPasteEncrypted") && Session.get("pasteKey") === undefined ){
				Session.set("pasteText", "Add the key to the URL");
				Session.set("pasteLang","You need a key to view this paste");
			}
			initEditor();
			startReadWriteTracker();
		}
	});
}

getBasicPaste = function(params) {
	Meteor.call('getPaste', params.pasteName, function(err,response){
		if (err) {console.log(err); return 1;}
		if (response === 1) {
			Session.set('pasteText', "No paste found");
		} else if (response.isEncry) {
			Session.set('pasteText', "This paste is encrypted");
		} else {
			Session.set("pasteName", params.pasteName);
			Session.set('pasteText', response.text);
			Session.set('pasteTitle', response.title);
			Session.set('pasteLang', response.language);
			Session.set('isPasteEncrypted', response.isEncry);
			Session.set('isForked', response.isFork);
			Session.set('isBookmarked', response.isBookmark);
			Session.set('numbersOfViews', response.numbersOfViews);
			editor.getSession().setMode("ace/mode/" + checkFramework(Session.get("pasteLang")));
			editor.setValue(Session.get("pasteText"));
			currentLines = editor.session.getLength();
			editor.setOptions({
			    maxLines: currentLines < 37 ? currentLines : 37
			});
			editor.moveCursorTo(0,0);
		}
	});
}

uploadBlob = function(action) {
	//action-> 0 : new paste
	//action-> 1 : new bookmark from other paste
	var blob = editor.getValue();
	var titlePaste;
	var langPaste;
	var key = "";
	if(!action){ //new paste
		Session.set("isBookmark", false);
		titlePaste = document.getElementById('pasteName').value;
		langPaste = document.getElementById('selectLanguage');
		langPaste = langPaste.options[langPaste.selectedIndex].value;
	}else{ //new save form other paste
		Session.set("isBookmark", true);
		titlePaste = document.getElementById('pasteName').childNodes[4].nextSibling.data;
		langPaste = document.getElementById('pasteLang').textContent;
		langPaste = langPaste.slice(1, -1);
	}
	// Check that text field is not blank before adding paste
	if (blob !== '' && titlePaste !== '') {
		if(Session.get("isPasteEncrypted") === true){
			var s = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
			key = Array(17).join().split(',').map(function() { return s.charAt(Math.floor(Math.random() * s.length)); }).join('');
			blob = sjcl.encrypt(key, blob);
		}
		Meteor.call("addPaste", blob, titlePaste, langPaste, Session.get("auth"),
								Session.get("isPasteEncrypted"), Session.get("isFork"),
								Session.get("pasteName"), Session.get("isBookmark"),
								Session.get("isPasteHided"), function (err, response) {
			if (err) {console.log(err);}
			document.getElementById("tools").classList.add("hideSlow");
			//document.getElementById('submitPaste').classList.add("ready");
			NProgress.configure({ easing: 'ease', speed: 500 });
			NProgress.start();
			NProgress.inc();
			setTimeout(function(){
				NProgress.done();
				localStorage.setItem(response[0], key); //store key for easy access
				takeMeToPaste(response[0], key); //redirect user
			},1000);
		}); //call server-side method addPaste
	} else {
		Notify.startToast(2000, "Either title or paste is empty", "OPS...");
	}
};

updateBlob = function() {
	var blob = editor.getValue();
	//var titlePaste = document.getElementById('pasteName').childNodes[0].nextSibling.data;
	Meteor.call("updatePaste", blob, Session.get("pasteTitle"), Session.get("pasteId"), Session.get("auth"), function(err, response){
		if(err) {alert(err);}
	});
};

bookmarkPaste = function() {
	if(!Session.get("isBookmarked")){
		Meteor.call("addBookmark", Session.get("pasteName"), Session.get("pasteTitle"), Session.get("auth"), function (err, response){
			if(err) {console.log(err);}
		});
	}
};

deletePaste = function(pasteId) {
	Meteor.call("deletePaste", pasteId, Session.get("auth"), function(err,response){
		if(err) {console.log(err);}
		else {Notify.startToast(2000, "This paste has been deleted", "Deleted");}
		loadUserPastes();
		if(Session.get("pasteId") === pasteId) {document.location.reload(false);}
	});
};

deleteBookmark = function(bookmarkId) {
	Meteor.call("deleteBookmark", bookmarkId, Session.get("auth"), function(err,response){
		if(err) {console.log(err);}
		else {Notify.startToast(2000, "This bookmark has been deleted", "Deleted");}
	});
};

loadUserPastes = function() {
	Meteor.call("getUserPastes", Session.get("auth"), function (err, response){
		if(err) {console.log(err);}
		if(response === 1) {
			console.log("A server error has occurred");
		}else{
			Session.set("userPastesLoaded", true);
			Session.set("userPastes", response);
			var userPastesIds = [];
			for (var i = response.userPastes.length - 1; i >= 0; i--) {
				userPastesIds.push(response.userPastes[i]._id);
			}
			Session.set("userPastesIds", userPastesIds);
		}
	});
};

loadLangs = function() {
	HTTP.get(Meteor.absoluteUrl("languages.json"), function(e, data) {
		Session.set("langList", data.data);
		Session.set("lastLang", localStorage.getItem("lastLang"))
		Session.set("langListReady", true);
		if(Session.get("isHome")){
			var lang = checkFramework(Session.get("lastLang"));
			editor.getSession().setMode("ace/mode/" + lang);
		}
	});
};

downloadBlob = function(filename, text) {
	var element = document.createElement('a');
	element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
	element.setAttribute('download', filename);
	element.style.display = 'none';
	document.body.appendChild(element);
	element.click();
	document.body.removeChild(element);
};

takeMeToPaste = function (pasteName, key) {
	window.onbeforeunload = null
	if (key === ""){
		FlowRouter.go("/pastes/" + pasteName);
	}else {
		FlowRouter.go("/pastes/" + pasteName + "/" + key);
	}
};

getCookie = function(name) {
  var value = "; " + document.cookie;
  var parts = value.split("; " + name + "=");
  if (parts.length === 2) {return parts.pop().split(";").shift();}
};

getLocal = function(name) {
	return localStorage.getItem(name);
}

setLocal = function(name) {
	var s = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789£$&^";
	var userName = Array(9).join().split(',').map(function() { return s.charAt(Math.floor(Math.random() * s.length)); }).join('');
	localStorage.setItem(name, userName);
	return userName;
}

setLocalLang = function(lang) {
	localStorage.setItem("lastLang", lang);
}

setLocalFromCookie = function(name, cookieValue) {
	localStorage.setItem(name, getCookie(cookieValue));
}

setCookie = function (argument) {
	var s = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789£$&^";
	var userName = Array(9).join().split(',').map(function() { return s.charAt(Math.floor(Math.random() * s.length)); }).join('');
	document.cookie ='auth=' + userName + '; expires=Fri, 3 Aug 2100 20:47:11 UTC; path=/';
};

KeyPress = function (e) {
	var evtobj = window.event? event : e;
	if (evtobj.ctrlKey && evtobj.keyCode === 37) {slideout.open();}
	if (evtobj.ctrlKey && evtobj.keyCode === 39) {slideout.close();}
	if (evtobj.ctrlKey && evtobj.keyCode === 40) {downloadBlob(Session.get("pasteTitle"), Session.get("pasteText"));}
	if (evtobj.ctrlKey && evtobj.keyCode === 38) {try{uploadBlob(0);}catch(e){}}
};

savePaste = function () {
	if( Session.get("userPastesIds").indexOf(Session.get("pasteId")) > -1 ) {
		if( Session.get("pasteText") !== editor.getValue() ) {//need to update paste
			if( !Session.get("isFork") ){ //if i'm not forking one of my projects
				updateBlob();
			}
		}
	}
};

initEditor = function () {
	console.log("init");
	editor.setValue(Session.get("pasteText"));
	var lastURL = Session.get("lastHref");
	Session.set("lastHref", FlowRouter.current().context.path);
	var range;
	editor.getSession().setUseWrapMode(true);
	var hash = FlowRouter.current().context.hash;
	if(hash){
		if(hash.indexOf("-")<0){
			var lineNumber = +hash.slice(1);
			editor.gotoLine(lineNumber,0);
			editor.selection.selectLineEnd();
		}else {
			fromToRegex = /L(\d+)\-L(\d+)/g;
			fromToLines = fromToRegex.exec(hash);
			var Range = ace.require('ace/range').Range;
			editor.gotoLine(+fromToLines[1],0);
			editor.selection.setSelectionRange(
				new Range((+fromToLines[1])-1, 0, (+fromToLines[2])-1, 0), false
			);
		}
	} else {
		console.log("no hash")
		editor.navigateTo(0,0);
	}
	editor.setShowPrintMargin(false);
	Session.set('cursorPosition', editor.getSession().selection.getCursor());
	//editor.focus();
	Session.set('length', editor.getSession().getLength());
	editor.commands.addCommand({
	    name: 'selectNext',
	    bindKey: {win: 'Ctrl-D',  mac: 'Command-D'},
	    exec: function(editor) {
	        editor.selectMore(1, false);
	    }
	});
	editor.on("change", function(e){
		Session.set('length', editor.getSession().getLength());
	});
	editor.getSession().selection.on('changeCursor', function(e) {
		Session.set('cursorPosition', editor.getSession().selection.getCursor());
	});
	editor.getSession().selection.on('changeSelection', function(e) {
		range = editor.getSession().selection.getRange();
		Session.set("selectionRowRange", range.end.row - range.start.row);
		Session.set("rangeLength", editor.getSelectedText().length);
	});
	if(Session.get("isPaste")){
		editor.on("guttermousedown", function(e){
			var line = e.getDocumentPosition().row + 1;
			if(!e.domEvent.shiftKey){
				Session.set("gutterLine", line);
				window.location.hash = "L" + line;
			} else if (e.domEvent.shiftKey && Session.get("gutterLine") === undefined){
				Session.set("gutterLine", line);
				window.location.hash = "L" + line;
			} else {
				Session.set("gutterLineTill", line);
				if(Session.get("gutterLineTill") < Session.get("gutterLine")){
					window.location.hash = "L" + Session.get("gutterLineTill") + "-L" + Session.get("gutterLine");
				}else {
					window.location.hash = "L" + Session.get("gutterLine") + "-L" + Session.get("gutterLineTill");
				}
			}

		})
	}
};

startReadWriteTracker = function () {
	Tracker.autorun(function () {
		if(Session.get("userPastesIds").indexOf(Session.get("pasteId"))>-1 || Session.get("isFork")){
			editor.setReadOnly(0);
		}else {editor.setReadOnly(1);}
	});
};

openMegaSlideout = function () {
	slideout.close();
	setTimeout(function(){megaSlideout.open();},600);
};

const jsFrameworks = ["angularjs","atom","backbone","d3js","grunt","gulp","jquery","meteor","nodejs","react", "kraken"]
const phpFrameworks = ["laravel"]
const android = ["android"]
const git = ["git"]

checkFramework = function(lang) {
	if(jsFrameworks.indexOf(lang) > -1){return "javascript";}
	if(phpFrameworks.indexOf(lang) > -1){return "php";}
	if(android.indexOf(lang) > -1){return "java";}
	if(git.indexOf(lang) > -1){return "gitignore";}
	return lang;
}

showEmbedDialog = function() {
	document.getElementById("bodyContainer").classList.add("blurred");
	document.getElementsByClassName("embedDialogContainer")[0].classList.remove("dialogClose");
	document.getElementsByClassName("embedDialogContainer")[0].classList.add("dialogOpen");
}

hideEmbedDialog = function() {
	document.getElementById("bodyContainer").classList.remove("blurred");
	document.getElementsByClassName("embedDialogContainer")[0].classList.remove("dialogOpen");
	document.getElementsByClassName("embedDialogContainer")[0].classList.add("dialogClose");
	document.getElementsByClassName("embedDialogContainer")[0].addEventListener('animationend', function(){
			document.getElementsByClassName("embedDialogContainer")[0].classList.remove("dialogClose");
		}, false);
}<|endoftext|>


<commit_before>/*
 * Wifi Support
 *
 * Copyright(c) 2012 Fred Chien <fred@mandice.com>
 *
 */

module.exports = function(connman) {
	var self = this;
	var dbus = connman.dbus;
	var updaterID = null;

	this.service = null;
	this.serviceChangedCallback = null;
	this._internalServiceChangedCallback = null;
	this._enableServiceChanged = function() {
		if (self.service) {
			self.service.PropertyChanged.onemit = _serviceChangedCallback;
			self.service.PropertyChanged.enabled = true;
		}

		/* Timer for pulling strength */
		if (!updaterID) {
			updaterID = setInterval(function() {
				if (self.service) {

					var serviceProp = self.service.GetProperties();

					_serviceChangedCallback('Strength', serviceProp.Strength);
				}
			}, 30000);
		}
	};

	this._disableServiceChanged = function() {
		/* ServiceChanged signal is being using */
		if (self.serviceChangedCallback)
			return;

		if (self.service) {
			self.service.ServiceChanged.onemit = null;
			self.service.ServiceChanged.enabled = false;
		}

		if (updaterID)
			clearInterval(updaterID);
	};

	var _serviceChangedCallback = function() {
		if (self._internalServiceChangedCallback)
			self._internalServiceChangedCallback.apply(self, Array.prototype.slice.call(arguments));

		if (self.serviceChangedCallback)
			self.serviceChangedCallback.apply(self, Array.prototype.slice.call(arguments));
	};

	/* Create connection for Wifi Technology */
	this.technology = connman.Technology.Find('wifi');

	this.ListAPs = function(callback) {
		process.nextTick(function() {
			var origList = connman.manager.GetServices();
			var list = [];

			/* We only get services of wifi */
			for (var index in origList) {
				if (origList[index][1].Type != 'wifi')
					continue;

				origList[index][1].dbusObject = origList[index][0];

				list.push(origList[index][1]);
			}

			delete origList;

			callback(list);
		});
	};

	this.Scan = function(callback) {
		if (self.technology) {
			process.nextTick(function() {
				self.technology.Scan['finish'] = function() {
					callback();
				};
				self.technology.Scan['timeout'] = 30000;
				self.technology.Scan();
			});
		}
	};

	this.FindAccessPoint = function(ssid, callback) {
		process.nextTick(function() {
			var List = connman.manager.GetServices();
			var ap;

			for (var index in List) {
				ap = List[index];
				if (ap[1].Name == ssid) {
					callback(null, ap);

					delete List;

					return;
				}
			}

			delete List;

			callback(new Error('Cannot find such access point'));
		});
	};

	this.Connect = function(ssid, passphrase, security) {
		if (self.technology) {
			self.FindAccessPoint(ssid, function(err, ap) {
				if (err)
					return;

				/* Get service interface */
				self.service = dbus.get_interface(connman.systemBus, 'net.connman', ap[0], 'net.connman.Service');

				/* Connect to Agent to make connection with access point */
				self.service.Connect();
			});
		}
	};

	this.GetStatus = function(callback) {
		process.nextTick(function() {
			var List = connman.manager.GetServices();
			var service;

			for (var index in List) {
				service = List[index];
				if (service[1].Type == 'wifi' && service[1].State == 'online') {

					/* Get service interface */
					self.service = dbus.get_interface(connman.systemBus, 'net.connman', service[0], 'net.connman.Service');

					callback(null, service);

					return;
				}
			}

			callback(new Error('Cannot get Wifi status'));
		});
	};

	/* Signal */
	this.onPropertyChanged = function(callback) {
		self.technology.PropertyChanged.onemit = callback;
		self.technology.PropertyChanged.enabled = true;
	};

	this.onServiceChanged = function(callback) {
		self.serviceChangedCallback = callback;

		self._enableServiceChanged();
	};

	/* Properties */
	this.__defineGetter__('Connected', function() {
		return self.technology.GetProperties().Connected;
	});

	this.__defineGetter__('Powered', function() {
		return self.technology.GetProperties().Powered;
	});

	this.__defineSetter__('Powered', function(value) {
		self.technology.SetProperty('Powered', value);
	});

	this.__defineGetter__('Tethering', function() {
		return self.technology.GetProperties().Tethering;
	});

	this.__defineSetter__('Tethering', function(value) {
		self.technology.SetProperty('Tethering', value);
	});
};
<commit_msg>make it can accept 'ready' state<commit_after>/*
 * Wifi Support
 *
 * Copyright(c) 2012 Fred Chien <fred@mandice.com>
 *
 */

module.exports = function(connman) {
	var self = this;
	var dbus = connman.dbus;
	var updaterID = null;

	this.service = null;
	this.serviceChangedCallback = null;
	this._internalServiceChangedCallback = null;
	this._enableServiceChanged = function() {
		if (self.service) {
			self.service.PropertyChanged.onemit = _serviceChangedCallback;
			self.service.PropertyChanged.enabled = true;
		}

		/* Timer for pulling strength */
		if (!updaterID) {
			updaterID = setInterval(function() {
				if (self.service) {

					var serviceProp = self.service.GetProperties();

					_serviceChangedCallback('Strength', serviceProp.Strength);
				}
			}, 30000);
		}
	};

	this._disableServiceChanged = function() {
		/* ServiceChanged signal is being using */
		if (self.serviceChangedCallback)
			return;

		if (self.service) {
			self.service.ServiceChanged.onemit = null;
			self.service.ServiceChanged.enabled = false;
		}

		if (updaterID)
			clearInterval(updaterID);
	};

	var _serviceChangedCallback = function() {
		if (self._internalServiceChangedCallback)
			self._internalServiceChangedCallback.apply(self, Array.prototype.slice.call(arguments));

		if (self.serviceChangedCallback)
			self.serviceChangedCallback.apply(self, Array.prototype.slice.call(arguments));
	};

	/* Create connection for Wifi Technology */
	this.technology = connman.Technology.Find('wifi');

	this.ListAPs = function(callback) {
		process.nextTick(function() {
			var origList = connman.manager.GetServices();
			var list = [];

			/* We only get services of wifi */
			for (var index in origList) {
				if (origList[index][1].Type != 'wifi')
					continue;

				origList[index][1].dbusObject = origList[index][0];

				list.push(origList[index][1]);
			}

			delete origList;

			callback(list);
		});
	};

	this.Scan = function(callback) {
		if (self.technology) {
			process.nextTick(function() {
				self.technology.Scan['finish'] = function() {
					callback();
				};
				self.technology.Scan['timeout'] = 30000;
				self.technology.Scan();
			});
		}
	};

	this.FindAccessPoint = function(ssid, callback) {
		process.nextTick(function() {
			var List = connman.manager.GetServices();
			var ap;

			for (var index in List) {
				ap = List[index];
				if (ap[1].Name == ssid) {
					callback(null, ap);

					delete List;

					return;
				}
			}

			delete List;

			callback(new Error('Cannot find such access point'));
		});
	};

	this.Connect = function(ssid, passphrase, security) {
		if (self.technology) {
			self.FindAccessPoint(ssid, function(err, ap) {
				if (err)
					return;

				/* Get service interface */
				self.service = dbus.get_interface(connman.systemBus, 'net.connman', ap[0], 'net.connman.Service');

				/* Connect to Agent to make connection with access point */
				self.service.Connect();
			});
		}
	};

	this.GetStatus = function(callback) {
		process.nextTick(function() {
			var List = connman.manager.GetServices();
			var service;

			for (var index in List) {
				service = List[index];
				if (service[1].Type == 'wifi' && (service[1].State == 'online' || service[1].State == 'ready')) {

					/* Get service interface */
					self.service = dbus.get_interface(connman.systemBus, 'net.connman', service[0], 'net.connman.Service');

					callback(null, service);

					return;
				}
			}

			callback(new Error('Cannot get Wifi status'));
		});
	};

	/* Signal */
	this.onPropertyChanged = function(callback) {
		self.technology.PropertyChanged.onemit = callback;
		self.technology.PropertyChanged.enabled = true;
	};

	this.onServiceChanged = function(callback) {
		self.serviceChangedCallback = callback;

		self._enableServiceChanged();
	};

	/* Properties */
	this.__defineGetter__('Connected', function() {
		return self.technology.GetProperties().Connected;
	});

	this.__defineGetter__('Powered', function() {
		return self.technology.GetProperties().Powered;
	});

	this.__defineSetter__('Powered', function(value) {
		self.technology.SetProperty('Powered', value);
	});

	this.__defineGetter__('Tethering', function() {
		return self.technology.GetProperties().Tethering;
	});

	this.__defineSetter__('Tethering', function(value) {
		self.technology.SetProperty('Tethering', value);
	});
};
<|endoftext|>