<commit_before>var Util, DOM, CloudFunc, CloudCmd;

(function (Util, DOM, CloudFunc, CloudCmd) {
    'use strict';

     CloudCmd.Listeners = new ListenersProto(Util, DOM, CloudFunc, CloudCmd);

     function ListenersProto(Util, DOM, CloudFunc, CloudCmd) {
        var Info                = DOM.CurrentInfo,
            Storage             = DOM.Storage,
            Events              = DOM.Events,
            EventsFiles         = {
                'mousedown' : Util.exec.with(execIfNotUL, setCurrentFileByEvent),
                'click'     : onClick,
                'dragstart' : Util.exec.with(execIfNotUL, onDragStart),
                'dblclick'  : Util.exec.with(execIfNotUL, onDblClick),
                'touchstart': Util.exec.with(execIfNotUL, onTouch)
            };

        this.init = function () {
            contextMenu();
            dragndrop();
            unload();
            pop();
            resize();
        };

        this.initKeysPanel          = function() {
            var keysElement     = DOM.getById('js-keyspanel');

            if (keysElement)
                Events.addClick(keysElement, function(event) {
                    var element = event.target,
                        id              = element.id,
                        operation       = function(name) {
                            var Operation = CloudCmd.Operation,
                                fn = Operation.show.bind(null, name);

                            return fn;
                        },

                        clickFuncs      = {
                            'f1'        : CloudCmd.Help.show,
                            'f2'        : DOM.renameCurrent,
                            'f3'        : CloudCmd.View.show,
                            'f4'        : CloudCmd.Edit.show,
                            'f5'        : operation('copy'),
                            'f6'        : operation('move'),
                            'f7'        : DOM.promptNewDir,
                            'f8'        : operation('delete'),
                            'f9'        : CloudCmd.Menu.show,
                            'f10'       : CloudCmd.Config.show,
                            '~'         : CloudCmd.Konsole.show,
                            'contact'   : CloudCmd.Contact.show,
                        },

                        func    = clickFuncs[id];

                    if (func)
                        func();
                });
        };

        this.setOnPanel             = function(side) {
            var panel,
                filesElement,
                pathElement;

            if (typeof side === 'string')
                panel       = DOM.getByDataName('js-' + side);
            else
                panel       = side;

            filesElement    = DOM.getByDataName('js-files', panel);
            pathElement     = DOM.getByDataName('js-path', panel);

            /* ставим загрузку гифа на клик*/
            Events.addClick(pathElement, getPathListener(panel));
            Events.add(filesElement, EventsFiles);
        };

        function getPathListener(panel) {
            var fn = onPathElementClick.bind(null, panel);

            return fn;
        }

        function onPathElementClick(panel, event) {
            var link, href, url,
                namePanel,
                nameInfoPanel,
                infoPanel   = Info.panel,
                noCurrent   = false,
                element     = event.target,
                attr        = element.getAttribute('data-name');

            switch (attr) {
            case 'js-clear-storage':
                Storage.clear();
                break;

            case 'js-refresh':
                namePanel           = panel.getAttribute('data-name');

                if (infoPanel)
                    nameInfoPanel   = infoPanel.getAttribute('data-name');

                if (namePanel !== nameInfoPanel)
                    noCurrent = true;

                CloudCmd.refresh(panel, {
                    noCurrent: noCurrent
                });

                event.preventDefault();
                break;

            case 'js-path-link':
                url         = CloudCmd.HOST;
                href        = element.href;
                link        = href.replace(url, '');
                /**
                 * browser doesn't replace % -> %25%
                 * do it for him
                 */
                link        = link.replace('%%', '%25%');
                link        = decodeURI(link);
                link        = link.replace(CloudFunc.FS, '') || '/';

                CloudCmd.loadDir({
                    path        : link,
                    isRefresh   : false
                });

                event.preventDefault();
            }
        }

        function execIfNotUL(callback, event) {
            var element = event.target,
                tag     = element.tagName;

            if (tag !== 'UL')
                callback(event);
        }

        function onClick(event) {
            var ctrl    = event.ctrlKey;

            if (!ctrl)
                event.preventDefault();

            changePanel(event.target);
        }

        function changePanel(element) {
            var panel   = Info.panel,
                files   = DOM.getByDataName('js-files', panel),
                ul      = getULElement(element);

            if (ul !== files)
                DOM.changePanel();
        }

        function onDblClick(event) {
            var current     = getLIElement(event.target),
                isDir       = DOM.isCurrentIsDir(current),
                path        = DOM.getCurrentPath(current);

            if (isDir) {
                CloudCmd.loadDir({
                    path: path + '/'
                });

                event.preventDefault();
            }
        }

        function onTouch(event) {
            var isCurrent,
                current     = getLIElement(event.target),
                isDir       = DOM.isCurrentIsDir(current);

            if (isDir) {
                isCurrent   = DOM.isCurrentFile(current);

                if (isCurrent) {
                    CloudCmd.loadDir({
                        path: DOM.getCurrentPath(current)
                    });

                    event.preventDefault();
                }
            }
        }

         /*
          * download file from browser to desktop
          * in Chrome (HTML5)
          */
        function onDragStart(event) {
            var apiURL      = CloudFunc.apiURL,
                element     = getLIElement(event.target),
                EXT         = '.tar.gz',
                isDir       = Info.isDir,
                link        = DOM.getCurrentLink(element),
                name        = DOM.getCurrentName(element);

            /* if it's directory - adding json extension */
            if (isDir) {
                name            += EXT;
                link            = document.createElement('a');
                link.textContent   = name;
                link.href          = apiURL + '/pack' + Info.path + EXT;
            }

            event.dataTransfer.setData('DownloadURL',
                'application/octet-stream'  + ':' +
                name                        + ':' +
                link);
        }

        function getLIElement(element) {
            if (element)
                while (element.tagName !== 'LI')
                    element = element.parentElement;

            return element;
        }

        function getULElement(element) {
            while (element.tagName !== 'UL')
                element     = element.parentElement;

            return element;
        }

        function setCurrentFileByEvent(event) {
            var element = getLIElement(event.target);
            DOM.setCurrentFile(element);
        }

        function contextMenu() {
            Events.addOnce('contextmenu', DOM.getFM(), function(event) {
                CloudCmd.Menu.show({
                    x: event.clientX,
                    y: event.clientY
                });
            });

            Events.addContextMenu(document, function(event) {
                CloudCmd.Menu.ENABLED || event.preventDefault();
            });
        }

        function dragndrop() {
            var panels          = DOM.getByClassAll('panel'),
                forEach         = Array.prototype.forEach,

                select          = function() {
                    forEach.call(panels, function(panel) {
                        panel.classList.add('selected-panel');
                    });
                },

                unselect        = function() {
                    forEach.call(panels, function(panel) {
                        panel.classList.remove('selected-panel');
                    });
                },
                onDrop          = function(event) {
                    var files   = event.dataTransfer.files,
                        items   = event.dataTransfer.items;

                    event.preventDefault();

                    if (items && items[0].webkitGetAsEntry)
                        DOM.uploadDirectory(items);
                    else
                        DOM.uploadFiles(files);
                },
                /**
                 * In Mac OS Chrome dropEffect = 'none'
                 * so drop do not firing up when try
                 * to upload file from download bar
                 */
                onDragOver      = function(event) {
                    var dataTransfer    = event.dataTransfer,
                        effectAllowed   = dataTransfer.effectAllowed;

                    if (/move|linkMove/.test(effectAllowed))
                        dataTransfer.dropEffect = 'move';
                    else
                        dataTransfer.dropEffect = 'copy';

                    event.preventDefault();
                };

            Events.add('dragenter', select);
            Events.add(['dragleave', 'drop'], unselect);

            forEach.call(panels, function(panel) {
                Events.add('dragover', panel, onDragOver)
                      .add('drop', panel, onDrop);
            });
        }

        function unload() {
            DOM.Events.add(['unload', 'beforeunload'], function (event) {
                var ret,
                    Key     = CloudCmd.Key,
                    isBind  = Key && Key.isBind();

                if (!isBind) {
                    event.preventDefault();
                    ret = 'Please make sure that you saved all work.';
                }

                return ret;
            });
        }

        function pop() {
            Events.add('popstate', function(event) {
                var path    = event.state || '';

                path        = path.replace(CloudFunc.FS, '');

                if (!path)
                    CloudCmd.route(location.hash);
                else
                    CloudCmd.loadDir({
                        path        : path,
                        history     : false
                    });
            });
        }

        function resize() {
            Events.add('resize', function() {
                var name, isLeft,
                    is      = window.innerWidth < CloudCmd.MIN_ONE_PANEL_WIDTH,
                    panel   = Info.panel;

                if (panel) {
                    name    = panel.getAttribute('data-name'),
                    isLeft  = name === 'js-left';
                }

                if (is && !isLeft)
                    DOM.changePanel();
            });
        }

     }

})(Util, DOM, CloudFunc, CloudCmd);
<commit_msg>fix(listeners) onDblClick: add "/"<commit_after>var Util, DOM, CloudFunc, CloudCmd;

(function (Util, DOM, CloudFunc, CloudCmd) {
    'use strict';

     CloudCmd.Listeners = new ListenersProto(Util, DOM, CloudFunc, CloudCmd);

     function ListenersProto(Util, DOM, CloudFunc, CloudCmd) {
        var Info                = DOM.CurrentInfo,
            Storage             = DOM.Storage,
            Events              = DOM.Events,
            EventsFiles         = {
                'mousedown' : Util.exec.with(execIfNotUL, setCurrentFileByEvent),
                'click'     : onClick,
                'dragstart' : Util.exec.with(execIfNotUL, onDragStart),
                'dblclick'  : Util.exec.with(execIfNotUL, onDblClick),
                'touchstart': Util.exec.with(execIfNotUL, onTouch)
            };

        this.init = function () {
            contextMenu();
            dragndrop();
            unload();
            pop();
            resize();
        };

        this.initKeysPanel          = function() {
            var keysElement     = DOM.getById('js-keyspanel');

            if (keysElement)
                Events.addClick(keysElement, function(event) {
                    var element = event.target,
                        id              = element.id,
                        operation       = function(name) {
                            var Operation = CloudCmd.Operation,
                                fn = Operation.show.bind(null, name);

                            return fn;
                        },

                        clickFuncs      = {
                            'f1'        : CloudCmd.Help.show,
                            'f2'        : DOM.renameCurrent,
                            'f3'        : CloudCmd.View.show,
                            'f4'        : CloudCmd.Edit.show,
                            'f5'        : operation('copy'),
                            'f6'        : operation('move'),
                            'f7'        : DOM.promptNewDir,
                            'f8'        : operation('delete'),
                            'f9'        : CloudCmd.Menu.show,
                            'f10'       : CloudCmd.Config.show,
                            '~'         : CloudCmd.Konsole.show,
                            'contact'   : CloudCmd.Contact.show,
                        },

                        func    = clickFuncs[id];

                    if (func)
                        func();
                });
        };

        this.setOnPanel             = function(side) {
            var panel,
                filesElement,
                pathElement;

            if (typeof side === 'string')
                panel       = DOM.getByDataName('js-' + side);
            else
                panel       = side;

            filesElement    = DOM.getByDataName('js-files', panel);
            pathElement     = DOM.getByDataName('js-path', panel);

            /* ставим загрузку гифа на клик*/
            Events.addClick(pathElement, getPathListener(panel));
            Events.add(filesElement, EventsFiles);
        };

        function getPathListener(panel) {
            var fn = onPathElementClick.bind(null, panel);

            return fn;
        }

        function onPathElementClick(panel, event) {
            var link, href, url,
                namePanel,
                nameInfoPanel,
                infoPanel   = Info.panel,
                noCurrent   = false,
                element     = event.target,
                attr        = element.getAttribute('data-name');

            switch (attr) {
            case 'js-clear-storage':
                Storage.clear();
                break;

            case 'js-refresh':
                namePanel           = panel.getAttribute('data-name');

                if (infoPanel)
                    nameInfoPanel   = infoPanel.getAttribute('data-name');

                if (namePanel !== nameInfoPanel)
                    noCurrent = true;

                CloudCmd.refresh(panel, {
                    noCurrent: noCurrent
                });

                event.preventDefault();
                break;

            case 'js-path-link':
                url         = CloudCmd.HOST;
                href        = element.href;
                link        = href.replace(url, '');
                /**
                 * browser doesn't replace % -> %25%
                 * do it for him
                 */
                link        = link.replace('%%', '%25%');
                link        = decodeURI(link);
                link        = link.replace(CloudFunc.FS, '') || '/';

                CloudCmd.loadDir({
                    path        : link,
                    isRefresh   : false
                });

                event.preventDefault();
            }
        }

        function execIfNotUL(callback, event) {
            var element = event.target,
                tag     = element.tagName;

            if (tag !== 'UL')
                callback(event);
        }

        function onClick(event) {
            var ctrl    = event.ctrlKey;

            if (!ctrl)
                event.preventDefault();

            changePanel(event.target);
        }

        function changePanel(element) {
            var panel   = Info.panel,
                files   = DOM.getByDataName('js-files', panel),
                ul      = getULElement(element);

            if (ul !== files)
                DOM.changePanel();
        }

        function onDblClick(event) {
            var current     = getLIElement(event.target),
                isDir       = DOM.isCurrentIsDir(current),
                path        = DOM.getCurrentPath(current);

            if (isDir) {
                CloudCmd.loadDir({
                    path: path === '/' ? '/' : path + '/'
                });

                event.preventDefault();
            }
        }

        function onTouch(event) {
            var isCurrent,
                current     = getLIElement(event.target),
                isDir       = DOM.isCurrentIsDir(current);

            if (isDir) {
                isCurrent   = DOM.isCurrentFile(current);

                if (isCurrent) {
                    CloudCmd.loadDir({
                        path: DOM.getCurrentPath(current)
                    });

                    event.preventDefault();
                }
            }
        }

         /*
          * download file from browser to desktop
          * in Chrome (HTML5)
          */
        function onDragStart(event) {
            var apiURL      = CloudFunc.apiURL,
                element     = getLIElement(event.target),
                EXT         = '.tar.gz',
                isDir       = Info.isDir,
                link        = DOM.getCurrentLink(element),
                name        = DOM.getCurrentName(element);

            /* if it's directory - adding json extension */
            if (isDir) {
                name            += EXT;
                link            = document.createElement('a');
                link.textContent   = name;
                link.href          = apiURL + '/pack' + Info.path + EXT;
            }

            event.dataTransfer.setData('DownloadURL',
                'application/octet-stream'  + ':' +
                name                        + ':' +
                link);
        }

        function getLIElement(element) {
            if (element)
                while (element.tagName !== 'LI')
                    element = element.parentElement;

            return element;
        }

        function getULElement(element) {
            while (element.tagName !== 'UL')
                element     = element.parentElement;

            return element;
        }

        function setCurrentFileByEvent(event) {
            var element = getLIElement(event.target);
            DOM.setCurrentFile(element);
        }

        function contextMenu() {
            Events.addOnce('contextmenu', DOM.getFM(), function(event) {
                CloudCmd.Menu.show({
                    x: event.clientX,
                    y: event.clientY
                });
            });

            Events.addContextMenu(document, function(event) {
                CloudCmd.Menu.ENABLED || event.preventDefault();
            });
        }

        function dragndrop() {
            var panels          = DOM.getByClassAll('panel'),
                forEach         = Array.prototype.forEach,

                select          = function() {
                    forEach.call(panels, function(panel) {
                        panel.classList.add('selected-panel');
                    });
                },

                unselect        = function() {
                    forEach.call(panels, function(panel) {
                        panel.classList.remove('selected-panel');
                    });
                },
                onDrop          = function(event) {
                    var files   = event.dataTransfer.files,
                        items   = event.dataTransfer.items;

                    event.preventDefault();

                    if (items && items[0].webkitGetAsEntry)
                        DOM.uploadDirectory(items);
                    else
                        DOM.uploadFiles(files);
                },
                /**
                 * In Mac OS Chrome dropEffect = 'none'
                 * so drop do not firing up when try
                 * to upload file from download bar
                 */
                onDragOver      = function(event) {
                    var dataTransfer    = event.dataTransfer,
                        effectAllowed   = dataTransfer.effectAllowed;

                    if (/move|linkMove/.test(effectAllowed))
                        dataTransfer.dropEffect = 'move';
                    else
                        dataTransfer.dropEffect = 'copy';

                    event.preventDefault();
                };

            Events.add('dragenter', select);
            Events.add(['dragleave', 'drop'], unselect);

            forEach.call(panels, function(panel) {
                Events.add('dragover', panel, onDragOver)
                      .add('drop', panel, onDrop);
            });
        }

        function unload() {
            DOM.Events.add(['unload', 'beforeunload'], function (event) {
                var ret,
                    Key     = CloudCmd.Key,
                    isBind  = Key && Key.isBind();

                if (!isBind) {
                    event.preventDefault();
                    ret = 'Please make sure that you saved all work.';
                }

                return ret;
            });
        }

        function pop() {
            Events.add('popstate', function(event) {
                var path    = event.state || '';

                path        = path.replace(CloudFunc.FS, '');

                if (!path)
                    CloudCmd.route(location.hash);
                else
                    CloudCmd.loadDir({
                        path        : path,
                        history     : false
                    });
            });
        }

        function resize() {
            Events.add('resize', function() {
                var name, isLeft,
                    is      = window.innerWidth < CloudCmd.MIN_ONE_PANEL_WIDTH,
                    panel   = Info.panel;

                if (panel) {
                    name    = panel.getAttribute('data-name'),
                    isLeft  = name === 'js-left';
                }

                if (is && !isLeft)
                    DOM.changePanel();
            });
        }

     }

})(Util, DOM, CloudFunc, CloudCmd);
<|endoftext|>


<commit_before>var Util, DOM, CloudCmd;

(function (Util, DOM) {
    'use strict';

     CloudCmd.Listeners = new ListenersProto(CloudCmd, Util, DOM);

     function ListenersProto(CloudCmd, Util, DOM){
        var Cache               = DOM.Cache,
            Events              = DOM.Events;

        this.analytics          = function() {
            CloudCmd.getConfig(function(config) {
                if (config.analytics) {
                    Events.addOneTime('mousemove', function(){
                        var FIVE_SECONDS    = 5000,
                            lUrl            = CloudCmd.LIBDIRCLIENT + 'analytics.js';

                        setTimeout(function(){
                            DOM.jsload(lUrl);
                        }, FIVE_SECONDS);
                    });
                }
            });
        };

        this.init = function () {
            appCache();
            contextMenu();
            dragndrop();
            unload();
            pop();
        };

        this.initKeysPanel          = function() {
            var i, lButton, lEl,
                lKeysPanel = {},

                lFuncs =[
                    null,
                    CloudCmd.Help,              /* f1 */
                    DOM.renameCurrent,          /* f2 */
                    CloudCmd.View,              /* f3 */
                    CloudCmd.Edit,              /* f4 */
                    DOM.copyCurrent,            /* f5 */
                    DOM.moveCurrent,            /* f6 */
                    DOM.promptNewDir,           /* f7 */
                    DOM.promptDeleteSelected,   /* f8 */
                    CloudCmd.Menu,              /* f9 */
                ];

            for (i = 1; i <= 9; i++) {
                lButton             = 'f' + i,
                lEl                 = DOM.getById('f' + i);
                lKeysPanel[lButton] = lEl;

                if (i === 1 || i === 3 || i === 4 || i === 9)
                    Events.addOneTime('click', lFuncs[i], lEl);
                else
                    Events.addClick(lFuncs[i], lEl);
            }

            lButton                 = '~',
            lEl                     = DOM.getById('~');
            lKeysPanel[lButton]     = lEl;
            Events.addOneTime('click', CloudCmd.Console, lEl);

            return lKeysPanel;
        };

        /**
         * функция меняет ссыки на ajax-овые
         * @param pPanelID
         */
        this.changeLinks            = function(pPanelID){
            /* назначаем кнопку очистить кэш и показываем её */
            var lClearcache = DOM.getById('clear-cache');
                Events.addClick(Cache.clear, lClearcache);

            /* меняем ссылки на ajax-запросы */
            var lPanel  = DOM.getById(pPanelID),
                a       = DOM.getByTag('a', lPanel),

                /* right mouse click function varible */
                lOnContextMenu_f = function(pEvent){
                    var lReturn_b   = true,
                        Key         = CloudCmd.Key;

                    Key && Key.unsetBind();

                    /* getting html element
                     * currentTarget - DOM event
                     * target        - jquery event
                     */
                    var lTarget = pEvent.currentTarget || pEvent.target;
                    DOM.setCurrentFile(lTarget);

                    if(Util.isFunction(CloudCmd.Menu) ){
                        CloudCmd.Menu({
                            x: pEvent.clientX,
                            y: pEvent.clientY
                        });

                        /* disabling browsers menu*/
                        lReturn_b = false;
                        DOM.Images.showLoad();
                    }

                    return lReturn_b;
                },

            /* drag and drop function varible
             * download file from browser to descktop
             * in Chrome (HTML5)
             */
                lOnDragStart_f = function(pEvent){
                    var lElement    = pEvent.target,
                        lLink       = lElement.href,
                        lName       = lElement.textContent;

                    /* if it's directory - adding json extension */
                    if( DOM.isCurrentIsDir() ){
                        lName       += '.json';
                        lLink       += '?json';
                    }

                    pEvent.dataTransfer.setData("DownloadURL",
                        'application/octet-stream'  + ':' +
                        lName                       + ':' +
                        lLink);
                },

                lSetCurrentFile_f = function(pEvent){
                    var pElement    = pEvent.target,
                        lTag        = pElement.tagName;

                    if(lTag !== 'LI')
                        do{
                            pElement    = pElement.parentElement;
                            lTag        = pElement.tagName;
                        }while(lTag !== 'LI');

                    DOM.setCurrentFile(pElement);
                },

                lUrl                = CloudCmd.HOST,
                lLoadDirOnce        = CloudCmd.loadDir();

            /* ставим загрузку гифа на клик*/
            Events.addClick( CloudCmd.refresh, a[0].parentElement );

            /* start from 1 cous 0 is a path and it's setted up */
            for(var i = 1, n = a.length; i < n ; i++){
                /* убираем адрес хоста*/
                var ai              = a[i],
                    lLink           = Util.removeStr(ai.href, lUrl),
                    lLoadDir        = CloudCmd.loadDir(lLink),
                    /* устанавливаем обработчики на строку
                     * на двойное нажатие на левую кнопку мышки */
                    lLi = ai.parentElement.parentElement;

                /* if we in path - set click event */
                if (lLi.className === 'path')
                    Events.addClick( lLoadDir, ai );
                else {
                    Events.add({
                        'click'         : DOM.preventDefault,
                        'mousedown'     : lSetCurrentFile_f,
                        'contextmenu'   : lOnContextMenu_f
                        }, lLi);

                    Events.add('dragstart', lOnDragStart_f, ai);

                    /* если ссылка на папку, а не файл */
                    if(ai.target !== '_blank'){
                        Events.add({
                            'dblclick' : lLoadDirOnce,
                            'touchend' : lLoadDirOnce
                            }, lLi);
                    }

                    lLi.id = (ai.title ? ai.title : ai.textContent) +
                        '(' + pPanelID + ')';
                }
            }
        };

        function appCache() {
            if (window.applicationCache)
                Events.add('updateready', function() {
                    var ret = confirm('An update is available. Reload now?');

                    if (ret)
                        location.reload();

                }, applicationCache);
        }

        function contextMenu() {
            Events.addContextMenu(function(pEvent){
                CloudCmd.Menu.ENABLED || DOM.preventDefault(pEvent);
            }, document);
        }

        function dragndrop() {
            var panels          = DOM.getByClass('panel'),
                i               = 0,
                n               = panels.length,
                preventDefault  = function (event) {
                    event.stopPropagation();
                    event.preventDefault();
                },
                toggle          = function () {
                    for (i = 0; i < n; i++)
                        DOM.toggleClass(panels[i], 'selected-panel');
                },
                onDrop          = function (event) {
                    var reader, file, files,
                         dir    = DOM.getCurrentDirPath(),
                         load   = function(file){
                            return function(event) {
                                var path    = dir + file.name,
                                    data    = event.target.result;

                                DOM.RESTfull.save(path, data, CloudCmd.refresh);
                            };
                        };

                    preventDefault(event);
                    toggle();

                    files               = event.dataTransfer.files;

                    if (files.length) {
                        n               = files.length;

                        for (i = 0; i < n; i++) {
                            reader          = new FileReader();
                            file            = files[i];
                            Events.add('load', load(file), reader);
                            reader.readAsArrayBuffer(file);
                        }
                    }
                };

            Events.add(['dragenter', 'dragleave'], toggle);

            for (i = 0; i < n; i++) {
                Events.add('dragover', preventDefault, panels[i]);
                Events.add('drop', onDrop, panels[i]);
            }
        }

        function unload() {
            DOM.Events.add(['unload', 'beforeunload'], function (pEvent) {
                var lRet,
                    Key     = CloudCmd.Key,
                    lIsBind = Key && Key.isBind();

                if(!lIsBind) {
                    DOM.preventDefault(pEvent);
                    lRet = 'Please make sure that you saved all work.';
                }

                return lRet;
            });
        }

        function pop() {
            Events.add("popstate", function(pEvent) {
                var lPath   = pEvent.state + '?json';

                if (pEvent.state) {
                    lPath   = pEvent.state + '?json';
                    ajaxLoad(lPath, {nohistory: true});
                } else
                    route(location.hash);

                return true;
            });
        }

     }

})(Util, DOM);
<commit_msg>feature(listeners) appCache: add getConfig<commit_after>var Util, DOM, CloudCmd;

(function (Util, DOM) {
    'use strict';

     CloudCmd.Listeners = new ListenersProto(CloudCmd, Util, DOM);

     function ListenersProto(CloudCmd, Util, DOM){
        var Cache               = DOM.Cache,
            Events              = DOM.Events,
            getConfig           = CloudCmd.getConfig;

        this.analytics          = function() {
            getConfig(function(config) {
                if (config.analytics) {
                    Events.addOneTime('mousemove', function(){
                        var FIVE_SECONDS    = 5000,
                            lUrl            = CloudCmd.LIBDIRCLIENT + 'analytics.js';

                        setTimeout(function(){
                            DOM.jsload(lUrl);
                        }, FIVE_SECONDS);
                    });
                }
            });
        };

        this.init = function () {
            appCache();
            contextMenu();
            dragndrop();
            unload();
            pop();
        };

        this.initKeysPanel          = function() {
            var i, lButton, lEl,
                lKeysPanel = {},

                lFuncs =[
                    null,
                    CloudCmd.Help,              /* f1 */
                    DOM.renameCurrent,          /* f2 */
                    CloudCmd.View,              /* f3 */
                    CloudCmd.Edit,              /* f4 */
                    DOM.copyCurrent,            /* f5 */
                    DOM.moveCurrent,            /* f6 */
                    DOM.promptNewDir,           /* f7 */
                    DOM.promptDeleteSelected,   /* f8 */
                    CloudCmd.Menu,              /* f9 */
                ];

            for (i = 1; i <= 9; i++) {
                lButton             = 'f' + i,
                lEl                 = DOM.getById('f' + i);
                lKeysPanel[lButton] = lEl;

                if (i === 1 || i === 3 || i === 4 || i === 9)
                    Events.addOneTime('click', lFuncs[i], lEl);
                else
                    Events.addClick(lFuncs[i], lEl);
            }

            lButton                 = '~',
            lEl                     = DOM.getById('~');
            lKeysPanel[lButton]     = lEl;
            Events.addOneTime('click', CloudCmd.Console, lEl);

            return lKeysPanel;
        };

        /**
         * функция меняет ссыки на ajax-овые
         * @param pPanelID
         */
        this.changeLinks            = function(pPanelID){
            /* назначаем кнопку очистить кэш и показываем её */
            var lClearcache = DOM.getById('clear-cache');
                Events.addClick(Cache.clear, lClearcache);

            /* меняем ссылки на ajax-запросы */
            var lPanel  = DOM.getById(pPanelID),
                a       = DOM.getByTag('a', lPanel),

                /* right mouse click function varible */
                lOnContextMenu_f = function(pEvent){
                    var lReturn_b   = true,
                        Key         = CloudCmd.Key;

                    Key && Key.unsetBind();

                    /* getting html element
                     * currentTarget - DOM event
                     * target        - jquery event
                     */
                    var lTarget = pEvent.currentTarget || pEvent.target;
                    DOM.setCurrentFile(lTarget);

                    if(Util.isFunction(CloudCmd.Menu) ){
                        CloudCmd.Menu({
                            x: pEvent.clientX,
                            y: pEvent.clientY
                        });

                        /* disabling browsers menu*/
                        lReturn_b = false;
                        DOM.Images.showLoad();
                    }

                    return lReturn_b;
                },

            /* drag and drop function varible
             * download file from browser to descktop
             * in Chrome (HTML5)
             */
                lOnDragStart_f = function(pEvent){
                    var lElement    = pEvent.target,
                        lLink       = lElement.href,
                        lName       = lElement.textContent;

                    /* if it's directory - adding json extension */
                    if( DOM.isCurrentIsDir() ){
                        lName       += '.json';
                        lLink       += '?json';
                    }

                    pEvent.dataTransfer.setData("DownloadURL",
                        'application/octet-stream'  + ':' +
                        lName                       + ':' +
                        lLink);
                },

                lSetCurrentFile_f = function(pEvent){
                    var pElement    = pEvent.target,
                        lTag        = pElement.tagName;

                    if(lTag !== 'LI')
                        do{
                            pElement    = pElement.parentElement;
                            lTag        = pElement.tagName;
                        }while(lTag !== 'LI');

                    DOM.setCurrentFile(pElement);
                },

                lUrl                = CloudCmd.HOST,
                lLoadDirOnce        = CloudCmd.loadDir();

            /* ставим загрузку гифа на клик*/
            Events.addClick( CloudCmd.refresh, a[0].parentElement );

            /* start from 1 cous 0 is a path and it's setted up */
            for(var i = 1, n = a.length; i < n ; i++){
                /* убираем адрес хоста*/
                var ai              = a[i],
                    lLink           = Util.removeStr(ai.href, lUrl),
                    lLoadDir        = CloudCmd.loadDir(lLink),
                    /* устанавливаем обработчики на строку
                     * на двойное нажатие на левую кнопку мышки */
                    lLi = ai.parentElement.parentElement;

                /* if we in path - set click event */
                if (lLi.className === 'path')
                    Events.addClick( lLoadDir, ai );
                else {
                    Events.add({
                        'click'         : DOM.preventDefault,
                        'mousedown'     : lSetCurrentFile_f,
                        'contextmenu'   : lOnContextMenu_f
                        }, lLi);

                    Events.add('dragstart', lOnDragStart_f, ai);

                    /* если ссылка на папку, а не файл */
                    if(ai.target !== '_blank'){
                        Events.add({
                            'dblclick' : lLoadDirOnce,
                            'touchend' : lLoadDirOnce
                            }, lLi);
                    }

                    lLi.id = (ai.title ? ai.title : ai.textContent) +
                        '(' + pPanelID + ')';
                }
            }
        };

        function appCache() {
            getConfig(function(config) {
                var isAppCache  = config.appcache,
                    appCache    = window.applicationCache;

                if (isAppCache && appCache)
                    Events.add('updateready', function() {
                        var ret = confirm('An update is available. Reload now?');

                        if (ret)
                            location.reload();

                    }, appCache);
                });
        }

        function contextMenu() {
            Events.addContextMenu(function(pEvent){
                CloudCmd.Menu.ENABLED || DOM.preventDefault(pEvent);
            }, document);
        }

        function dragndrop() {
            var panels          = DOM.getByClass('panel'),
                i               = 0,
                n               = panels.length,
                preventDefault  = function (event) {
                    event.stopPropagation();
                    event.preventDefault();
                },
                toggle          = function () {
                    for (i = 0; i < n; i++)
                        DOM.toggleClass(panels[i], 'selected-panel');
                },
                onDrop          = function (event) {
                    var reader, file, files,
                         dir    = DOM.getCurrentDirPath(),
                         load   = function(file){
                            return function(event) {
                                var path    = dir + file.name,
                                    data    = event.target.result;

                                DOM.RESTfull.save(path, data, CloudCmd.refresh);
                            };
                        };

                    preventDefault(event);
                    toggle();

                    files               = event.dataTransfer.files;

                    if (files.length) {
                        n               = files.length;

                        for (i = 0; i < n; i++) {
                            reader          = new FileReader();
                            file            = files[i];
                            Events.add('load', load(file), reader);
                            reader.readAsArrayBuffer(file);
                        }
                    }
                };

            Events.add(['dragenter', 'dragleave'], toggle);

            for (i = 0; i < n; i++) {
                Events.add('dragover', preventDefault, panels[i]);
                Events.add('drop', onDrop, panels[i]);
            }
        }

        function unload() {
            DOM.Events.add(['unload', 'beforeunload'], function (pEvent) {
                var lRet,
                    Key     = CloudCmd.Key,
                    lIsBind = Key && Key.isBind();

                if(!lIsBind) {
                    DOM.preventDefault(pEvent);
                    lRet = 'Please make sure that you saved all work.';
                }

                return lRet;
            });
        }

        function pop() {
            Events.add("popstate", function(pEvent) {
                var lPath   = pEvent.state + '?json';

                if (pEvent.state) {
                    lPath   = pEvent.state + '?json';
                    ajaxLoad(lPath, {nohistory: true});
                } else
                    route(location.hash);

                return true;
            });
        }

     }

})(Util, DOM);
<|endoftext|>


<commit_before>TileMill = {};

/**
 * Generate the URL of the current project .mml file.
 *
 * @param bool timestamp
 *   Optionally append a timestamp parameter to the URL to avoid
 *   TileLive caching.
 */
TileMill.mmlURL = function(timestamp) {
  var url = window.server + 'projects/mml?id=' + window.project_id;
  if (timestamp) {
    url = url + '&c=' + (new Date().getTime());
  }
  return url;
};

TileMill.addLayer = function(options) {
  var layerName = '';
  if (options.id) {
    layerName = '#' + options.id + ' ';
  }
  if (options.classes.length) {
    layerName += '.' + options.classes.join(', .');
  }
  var checkbox = $('<input class="checkbox" type="checkbox" />');
  var li = $('
')
    .append($('

'))
    .append(checkbox)
    .append($('Delete').click(function() {
      if (confirm('Are you sure you want to delete this layer?')) {
        $(this).parents('li').hide('fast', function() {
          $(this).remove();
        });
      }
      return false;
    }))
    .append($('Inspect').click(function() {
      if (!$(this).parents('li').data('tilemill')['id']) {
        alert('You need to add an id to a field and save to inspect it.');
        return;
      }
      $('#inspector .sidebar-header h2').html('Layers » ' + $(this).parents('li').find('label').text());
      TileMill.inspect($(this).parents('li').data('tilemill').id);
      return false;
    }))
    .append($('Edit').click(function() {
      var options = $(this).parents('li').data('tilemill');
      $('#popup, #popup-layer, #popup-backdrop, #popup-header').show().removeClass('new');
      var layer = $('#popup-layer').find('input.submit').val('Save').data('li', $(this).parents('li')).end();

      options.classes = options.classes.join(' ');
      for (option in options) {
        layer.find('#' + option).val(options[option]).end();
      }

      $('#popup-header h2').text('Edit layer');
      $('#popup-info').hide();
      return false;
    }))
    .append($('' + layerName + ''));
  if (options.status == 'true') {
    checkbox[0].checked = true;
  }
  $('#layers ul.sidebar-content').prepend(li.data('tilemill', options));
};

TileMill.initMap = function() {
  if (!$('#map-preview').is('.inited')) {
    $('#map-preview').addClass('inited');
    var options = {
      projection: new OpenLayers.Projection("EPSG:900913"),
      displayProjection: new OpenLayers.Projection("EPSG:4326"),
      units: "m",
      numZoomLevels: 12,
      maxResolution: 156543.0339,
      maxExtent: new OpenLayers.Bounds(
        -20037500,
        -20037500,
        20037500,
        20037500
      ),
      controls: []
    };
    TileMill.map = new OpenLayers.Map('map-preview', options);
    TileMill.layer = new OpenLayers.Layer.XYZ("Preview", window.tilelive + 'tile/' + Base64.encode(TileMill.mmlURL()) + '/${z}/${x}/${y}.png');
    TileMill.map.addLayers([ TileMill.layer ]);

    // Set the map's initial center point
    TileMill.map.setCenter(new OpenLayers.LonLat(0, 0), 2);

    // Add control
    var control = new OpenLayers.Control.Navigation({ 'zoomWheelEnabled': true });
    TileMill.map.addControl(control);
    control.activate();
  }
  // Update map.
  else {
    url = window.server + 'projects/mml?id=' + window.project_id + '&c=' + (new Date().getTime());
    encode = Base64.encode(url);
    layer = new OpenLayers.Layer.XYZ("Preview " + TileMill.counter, window.tilelive + 'tile/' + encode + '/${z}/${x}/${y}.png');
    TileMill.map.removeLayer(TileMill.layer);
    TileMill.map.addLayers([layer]);
    TileMill.layer = layer;
  }
};

TileMill.initColors = function() {
  TileMill.farbtastic = $.farbtastic($('#farbtastic'), {callback:'input#color', width:200, height:200});
  $('#color-picker a.color-picker').click(function() {
    $('#farbtastic').toggle('fast');
  });
};

TileMill.initCodeEditor = function(file) {
  $.get('/projects/mss', {'id': project_id, 'filename': file}, function(data) {
    $('textarea#code').val(data);
    TileMill.reloadColors(data);
    TileMill.mirror = CodeMirror.fromTextArea('code', {
      height: "auto",
      parserfile: "parsecss.js",
      stylesheet: static_path + "css/code.css",
      path: static_path + "js/codemirror/js/"
    });
    TileMill.mirror.setCode(data);
    setInterval(function() {
      TileMill.reloadColors(TileMill.mirror.getCode());
    }, 5000);
  });
};

TileMill.save = function(map) {
  var mml = TileMill.mml();
  $.post('/projects/mml', {
    'id': window.project_id,
    'data': mml,
  });
  TileMill.mssSave(project_id);
  TileMill.loadInspection();
  if (map == undefined || !!map) {
    TileMill.initMap();
  }
}

TileMill.mml = function() {
  var output = ['<' + '?xml version="1.0" encoding="utf-8"?>',
  '<!DOCTYPE Map[',
  '  <!ENTITY srs900913 "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs">',
  '  <!ENTITY srsWGS84 "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs">',
  ']>',
  '<Map srs="&srs900913;">'];
  output.push('


<commit_before>/**
 * Created by sokolski adrien on 17/03/2017.
 */
let instance = null;

class Spiderman{
  constructor(){
    if (!instance){
      instance = this;
      this.poneyFarm = [];

      setInterval(()=>{
        this.onPoney();
      },4000);
    }
    return instance;
  }
  onPoney(){
    const i = Math.floor(Math.random()* this.poneyFarm.length);
    this.poneyFarm[i].ridingPoney()
      .then(()=> console.log('Spiderman est avec un poney'))
      .catch(()=> console.log('spiderman nest plus sur un poney'));
  }
}

module.export = {Spiderman};<commit_msg>Delete spiderman.js<commit_after><|endoftext|>


<commit_before>// NOTE: The contents of this file will only be executed if
// you uncomment its entry in "web/static/js/app.js".

// To use Phoenix channels, the first step is to import Socket
// and connect at the socket path in "lib/my_app/endpoint.ex":
import {Socket} from "phoenix"

let socket = new Socket("/socket", {params: {token: window.userToken}})

// When you connect, you'll often need to authenticate the client.
// For example, imagine you have an authentication plug, `MyAuth`,
// which authenticates the session and assigns a `:current_user`.
// If the current user exists you can assign the user's token in
// the connection for use in the layout.
//
// In your "web/router.ex":
//
//     pipeline :browser do
//       ...
//       plug MyAuth
//       plug :put_user_token
//     end
//
//     defp put_user_token(conn, _) do
//       if current_user = conn.assigns[:current_user] do
//         token = Phoenix.Token.sign(conn, "user socket", current_user.id)
//         assign(conn, :user_token, token)
//       else
//         conn
//       end
//     end
//
// Now you need to pass this token to JavaScript. You can do so
// inside a script tag in "web/templates/layout/app.html.eex":
//
//     <script>window.userToken = "<%= assigns[:user_token] %>";</script>
//
// You will need to verify the user token in the "connect/2" function
// in "web/channels/user_socket.ex":
//
//     def connect(%{"token" => token}, socket) do
//       # max_age: 1209600 is equivalent to two weeks in seconds
//       case Phoenix.Token.verify(socket, "user socket", token, max_age: 1209600) do
//         {:ok, user_id} ->
//           {:ok, assign(socket, :user, user_id)}
//         {:error, reason} ->
//           :error
//       end
//     end
//
// Finally, pass the token on connect as below. Or remove it
// from connect if you don't care about authentication.

socket.connect()

// Now that you are connected, you can join channels with a topic:
let channel = socket.channel("person", {})
channel.join()
  .receive("ok", resp => { console.log("Joined successfully", resp) })
  .receive("error", resp => { console.log("Unable to join", resp) })

channel.on("change", person => {
      console.log("New user created:", person);
    })
export default socket
<commit_msg>[Added] Channel v1<commit_after>// NOTE: The contents of this file will only be executed if
// you uncomment its entry in "web/static/js/app.js".

// To use Phoenix channels, the first step is to import Socket
// and connect at the socket path in "lib/my_app/endpoint.ex":
import {Socket} from "phoenix"

// let socket = new Socket("/socket", {params: {token: window.userToken}})
let socket = new Socket("http://otherpoolapi.herokuapp.com/", {params: {token: window.userToken}})
// When you connect, you'll often need to authenticate the client.
// For example, imagine you have an authentication plug, `MyAuth`,
// which authenticates the session and assigns a `:current_user`.
// If the current user exists you can assign the user's token in
// the connection for use in the layout.
//
// In your "web/router.ex":
//
//     pipeline :browser do
//       ...
//       plug MyAuth
//       plug :put_user_token
//     end
//
//     defp put_user_token(conn, _) do
//       if current_user = conn.assigns[:current_user] do
//         token = Phoenix.Token.sign(conn, "user socket", current_user.id)
//         assign(conn, :user_token, token)
//       else
//         conn
//       end
//     end
//
// Now you need to pass this token to JavaScript. You can do so
// inside a script tag in "web/templates/layout/app.html.eex":
//
//     <script>window.userToken = "<%= assigns[:user_token] %>";</script>
//
// You will need to verify the user token in the "connect/2" function
// in "web/channels/user_socket.ex":
//
//     def connect(%{"token" => token}, socket) do
//       # max_age: 1209600 is equivalent to two weeks in seconds
//       case Phoenix.Token.verify(socket, "user socket", token, max_age: 1209600) do
//         {:ok, user_id} ->
//           {:ok, assign(socket, :user, user_id)}
//         {:error, reason} ->
//           :error
//       end
//     end
//
// Finally, pass the token on connect as below. Or remove it
// from connect if you don't care about authentication.

socket.connect()

// Now that you are connected, you can join channels with a topic:
let channel = socket.channel("person", {})
channel.join()
  .receive("ok", resp => { console.log("Joined successfully", resp) })
  .receive("error", resp => { console.log("Unable to join", resp) })

channel.on("change", person => {
      console.log("New user created:", person);
    })
export default socket
<|endoftext|>


<commit_before>var api = require('./api')
var manifest = api.manifest
var goodbye = require('pull-goodbye')
var Serializer = require('pull-serializer')
var JSONH = require('json-human-buffer')
var pull = require('pull-stream')
var many = require('pull-many')

function serialize (stream) {
  return Serializer(stream, JSONH, {split: '\n\n'})
}

function id (e) {
  return e
}

module.exports = function (ssb, opts, cb) {
  opts = opts || {}
  var rpc = api.peer(ssb, {}, id)
  var progress = opts.progress || function () {}

  var latestStream = opts.latest
    ? pull(
        opts.latest(),
        ssb.createLatestLookupStream()
      )
    : ssb.latest()

  var sources = many()
  var sent = 0
  pull(
    latestStream,
    pull.drain(function (upto) {
      sources.add(rpc.createHistoryStream(upto.id, upto.sequence + 1))
    }, function () {
      sources.cap()
    })
  )

  var rpcStream = rpc.createStream()

  pull(
    sources,
    pull.through(function (data) {
      sent ++
      console.log(sent)
      console.log(data)
    }),
    ssb.createWriteStream(function (err) {
      rpcStream.close(function (err2) {
        cb(err || err2, sent)
      })
    })
  )

  return serialize(goodbye(rpcStream))

}
<commit_msg>remove logging<commit_after>var api = require('./api')
var manifest = api.manifest
var goodbye = require('pull-goodbye')
var Serializer = require('pull-serializer')
var JSONH = require('json-human-buffer')
var pull = require('pull-stream')
var many = require('pull-many')

function serialize (stream) {
  return Serializer(stream, JSONH, {split: '\n\n'})
}

function id (e) {
  return e
}

module.exports = function (ssb, opts, cb) {
  opts = opts || {}
  var rpc = api.peer(ssb, {}, id)
  var progress = opts.progress || function () {}

  var latestStream = opts.latest
    ? pull(
        opts.latest(),
        ssb.createLatestLookupStream()
      )
    : ssb.latest()

  var sources = many()
  var sent = 0
  pull(
    latestStream,
    pull.drain(function (upto) {
      sources.add(rpc.createHistoryStream(upto.id, upto.sequence + 1))
    }, function () {
      sources.cap()
    })
  )

  var rpcStream = rpc.createStream()

  pull(
    sources,
    ssb.createWriteStream(function (err) {
      rpcStream.close(function (err2) {
        cb(err || err2)
      })
    })
  )

  return serialize(goodbye(rpcStream))

}
<|endoftext|>


<commit_before>const { httpSocketsByGuildId, httpsSocketsByGuildId, guildIdsByHttpSockets, guildIdsByHttpsSockets } = require('./util/directory.js')
const dbOpsFailedLinks = require('../../util/db/failedLinks.js')
const log = require('../../util/logger.js')

module.exports = (io, isHttps) => {
  const socketFunctions = socket => {
    if (!socket.handshake.session.auth) return
    return {
      identify: async guildId => {
        if (!guildId) return log.web.warning('Invalid identify socket event', guildId)
        const socketId = socket.id
        // const session = socket.handshake.session
        const guildIdsBySockets = isHttps ? guildIdsByHttpsSockets : guildIdsByHttpSockets
        if (!Array.isArray(guildIdsBySockets[socketId])) {
          guildIdsBySockets[socketId] = [ guildId ]
        } else if (!guildIdsBySockets[socketId].includes(guildId)) {
          guildIdsBySockets[socketId].push(guildId)
        }

        const socketsByGuildId = isHttps ? httpsSocketsByGuildId : httpSocketsByGuildId
        if (!Array.isArray(socketsByGuildId[guildId])) {
          socketsByGuildId[guildId] = [ socketId ]
        } else if (!socketsByGuildId[guildId].includes(socketId)) {
          socketsByGuildId[guildId].push(socketId)
        }
      },
      getLinkStatus: async link => {
        try {
          let status
          const doc = await dbOpsFailedLinks.get(link)
          if (!doc) status = 0 // OK
          else if (doc.failed) status = doc.failed // FAILED
          else status = doc.count // OK so far
          socket.emit('linkStatus', JSON.stringify({ link, status }))
        } catch (err) {
          log.web.err('Failed to get link status after websocket request', err)
        }
      }
    }
  }

  io.on('connection', socket => {
    const functions = socketFunctions(socket)
    if (!functions) return
    for (const eventName in functions) {
      socket.on(eventName, functions[eventName])
    }

    socket.once('disconnect', () => {
      for (const eventName in functions) {
        socket.removeListener(eventName, functions[eventName])
      }
      const socketGuilds = isHttps ? guildIdsByHttpsSockets[socket.id] : guildIdsByHttpSockets[socket.id]
      if (!socketGuilds) return
      for (const guildId of socketGuilds) {
        const guildSockets = isHttps ? httpsSocketsByGuildId[guildId] : httpSocketsByGuildId[guildId]
        if (!guildSockets) continue
        // log.web.info(`[WEBSOCKETS] ${socket.id} deregistered for guild ${guildId}`)
        guildSockets.splice(guildSockets.indexOf(socket.id), 1)
      }
      delete (isHttps ? guildIdsByHttpsSockets[socket.id] : guildIdsByHttpSockets[socket.id])
    })
  })
}
<commit_msg>Fix func name<commit_after>const { httpSocketsByGuildId, httpsSocketsByGuildId, guildIdsByHttpSockets, guildIdsByHttpsSockets } = require('./util/directory.js')
const dbOpsFailedLinks = require('../../util/db/failedLinks.js')
const log = require('../../util/logger.js')

module.exports = (io, isHttps) => {
  const socketFunctions = socket => {
    if (!socket.handshake.session.auth) return
    return {
      identify: async guildId => {
        if (!guildId) return log.web.warning('Invalid identify socket event', guildId)
        const socketId = socket.id
        // const session = socket.handshake.session
        const guildIdsBySockets = isHttps ? guildIdsByHttpsSockets : guildIdsByHttpSockets
        if (!Array.isArray(guildIdsBySockets[socketId])) {
          guildIdsBySockets[socketId] = [ guildId ]
        } else if (!guildIdsBySockets[socketId].includes(guildId)) {
          guildIdsBySockets[socketId].push(guildId)
        }

        const socketsByGuildId = isHttps ? httpsSocketsByGuildId : httpSocketsByGuildId
        if (!Array.isArray(socketsByGuildId[guildId])) {
          socketsByGuildId[guildId] = [ socketId ]
        } else if (!socketsByGuildId[guildId].includes(socketId)) {
          socketsByGuildId[guildId].push(socketId)
        }
      },
      getLinkStatus: async link => {
        try {
          let status
          const doc = await dbOpsFailedLinks.get(link)
          if (!doc) status = 0 // OK
          else if (doc.failed) status = doc.failed // FAILED
          else status = doc.count // OK so far
          socket.emit('linkStatus', JSON.stringify({ link, status }))
        } catch (err) {
          log.web.error('Failed to get link status after websocket request', err)
        }
      }
    }
  }

  io.on('connection', socket => {
    const functions = socketFunctions(socket)
    if (!functions) return
    for (const eventName in functions) {
      socket.on(eventName, functions[eventName])
    }

    socket.once('disconnect', () => {
      for (const eventName in functions) {
        socket.removeListener(eventName, functions[eventName])
      }
      const socketGuilds = isHttps ? guildIdsByHttpsSockets[socket.id] : guildIdsByHttpSockets[socket.id]
      if (!socketGuilds) return
      for (const guildId of socketGuilds) {
        const guildSockets = isHttps ? httpsSocketsByGuildId[guildId] : httpSocketsByGuildId[guildId]
        if (!guildSockets) continue
        // log.web.info(`[WEBSOCKETS] ${socket.id} deregistered for guild ${guildId}`)
        guildSockets.splice(guildSockets.indexOf(socket.id), 1)
      }
      delete (isHttps ? guildIdsByHttpsSockets[socket.id] : guildIdsByHttpSockets[socket.id])
    })
  })
}
<|endoftext|>


<commit_before>$(function () {
    minerva.events.trigger('g:appload.before');
    minerva.mainApp = new minerva.App({
        el: 'body',
        parentView: null
    });
    minerva.events.trigger('g:appload.after');
});
<commit_msg>Trigger app ready event from main<commit_after>$(function () {
    minerva.events.trigger('g:appload.before');
    minerva.mainApp = new minerva.App({
        el: 'body',
        parentView: null
    });
    minerva.mainApp.start().then(function () {
        minerva.events.trigger('g:appload.ready');
    });
    minerva.events.trigger('g:appload.after');
});
<|endoftext|>


<commit_before>'use strict';

var Command     = require('../models/command');
var SilentError = require('silent-error');
var chalk       = require('chalk');

module.exports = Command.extend({
  printBasicHelp: function() {
    this.ui.writeLine(chalk.red('No help entry for \'' + this.commandName + '\''));
  },

  validateAndRun: function() {
    throw new SilentError('The specified command ' + this.commandName +
                          ' is invalid. For available options, see' +
                          ' `ember help`.');
  }
});
<commit_msg>Removing unknown command from `ember help`.<commit_after>'use strict';

var Command     = require('../models/command');
var SilentError = require('silent-error');
var chalk       = require('chalk');

module.exports = Command.extend({
  skipHelp: true,

  printBasicHelp: function() {
    this.ui.writeLine(chalk.red('No help entry for \'' + this.commandName + '\''));
  },

  validateAndRun: function() {
    throw new SilentError('The specified command ' + this.commandName +
                          ' is invalid. For available options, see' +
                          ' `ember help`.');
  }
});
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2011 Bruno Jouhier <bruno.jouhier@sage.com>
 * MIT License
 */
var __g = {}; // streamline's globals
global.__streamline = __g; // standalone modules need to share our global!
exports = module.exports = function(filename){
	var __srcName = filename.replace(/\.js$/, '_.js')
	function __func(_, __this, __arguments, fn, index, frame, body){
		if (!_) {
			return __future.call(__this, fn, __arguments, index);
		}
		frame.file = __srcName;
		frame.prev = __g.frame;
		__g.frame = frame;
		try {
			body();
		}
		catch (e) {
			__setEF(e, frame.prev);
			__propagate(_, e);
		}
		finally {
			__g.frame = frame.prev;
		}
	}

	return {
		__g: __g,
		__srcName: __srcName,
		__func: __func,
		__cb: __cb,
		__future: __future,
		__propagate: __propagate,
		__trap: __trap,
		__tryCatch: __tryCatch,
		__forIn: __forIn,
		__apply: __apply,
		__setEF: __setEF
	};
}

function __cb(_, frame, offset, col, fn){
	frame.offset = offset;
	frame.col = col;
	var ctx = __g.context;
	return function ___(err, result){
		var oldFrame = __g.frame;
		__g.frame = frame;
		__g.context = ctx;
		try {
			if (err) {
				__setEF(err, frame);
				return _(err);
			}
			return fn(null, result);
		}
		catch (ex) {
			__setEF(ex, frame);
			return __propagate(_, ex);
		}
		finally {
			__g.frame = oldFrame;
		}
	}
}

// unfortunately callee is gone. So we need to pass a function
function __future(fn, args, i){
	var err, result, done, q = [];
	var args = Array.prototype.slice.call(args);
	args[i] = function(e, r){
		err = e, result = r, done = true;
		q && q.forEach(function(f){
			try {
				f(e, r);
			}
			catch (ex) {
				__trap(ex);
			}
		});
		q = null;
	};
	fn.apply(this, args);
	return function ___(_){
		if (done)
			_(err, result);
		else
			q.push(_)
	}
}

function __propagate(_, err){
	try {
		_(err);
	}
	catch (ex) {
		__trap(ex);
	}
}

function __trap(err){
	if (err) {
		if (__g.context && __g.context.errorHandler)
			__g.context.errorHandler(err);
		else
			console.error("UNCAUGHT EXCEPTION: " + err.message + "\\n" + err.stack);
	}
}

__tryCatch: function __tryCatch(_, fn){
	try {
		fn();
	}
	catch (e) {
		try {
			_(e);
		}
		catch (ex) {
			__trap(ex);
		}
	}
}

function __forIn(object){
	var array = [];
	for (var obj in object) {
		array.push(obj);
	}
	return array;
}

function __apply(cb, fn, thisObj, args, index){
	if (cb == null)
		return __future(__apply, arguments, 0);
	args[index != null ? index : args.length] = cb;
	return fn.apply(thisObj, args);
}

function __setEF(e, f){
	function formatStack(e, raw){
		var s = raw, f, skip, skipFunc = 0;
		if (s) {
			var ff;
			s = s.split('\n').map(function(l){
				// try to map firefox format to V8 format
				// ffOffset takes care of lines difference introduced by require.js script.
				var ffOffset = __streamline.ffOffset || 0;
				var m = /(^[^(]+)\([^@]*\@(.*)\:(\d+)$/.exec(l);
				l = m ? "    at " + m[1] + " (" + m[2] + ":" + (parseInt(m[3]) - ffOffset) + ":0)" : l;
				ff = ff || (m != null);
				var i = l.indexOf('__$');
				if (i >= 0 && !skip) {
					skip = true;
					return l.substring(0, i) + l.substring(i + 3) + '\n';
				}
				return skip ? '' : l + '\n';
			}).join('');
			if (ff) // firefox does not include message
				s = "Error: " + e.message + '\n' + s;
			for (var f = e.__frame; f; f = f.prev) {
				if (f.offset >= 0)
					s += "    at " + f.name + " (" + f.file + ":" + (f.line + f.offset) + ":" + f.col + ")\n"
			}
		}
		return s;
	};
	e.__frame = e.__frame || f;
	if (exports.stackTraceEnabled && e.__lookupGetter__("rawStack") == null) {
		var getter = e.__lookupGetter__("stack");
		if (!getter) { // FF case
			var raw = e.stack;
			getter = function(){
				return raw;
			}
		}
		e.__defineGetter__("rawStack", getter);
		e.__defineGetter__("stack", function(){
			return formatStack(e, getter());
		});
	}
}

/// * `runtime.stackTraceEnabled = true/false;`
///   If true, `err.stack` returns the reconstructed _sync_ stack trace.
///   Otherwise, it returns the _raw_ stack trace.
///   The default is true, but you must require the flows module
///   at least once to enable sync stack traces.
module.exports.stackTraceEnabled = true;
<commit_msg>fixed bug in __future<commit_after>/**
 * Copyright (c) 2011 Bruno Jouhier <bruno.jouhier@sage.com>
 * MIT License
 */
var __g = {}; // streamline's globals
global.__streamline = __g; // standalone modules need to share our global!
exports = module.exports = function(filename){
	var __srcName = filename.replace(/\.js$/, '_.js')
	function __func(_, __this, __arguments, fn, index, frame, body){
		if (!_) {
			return __future.call(__this, fn, __arguments, index);
		}
		frame.file = __srcName;
		frame.prev = __g.frame;
		__g.frame = frame;
		try {
			body();
		}
		catch (e) {
			__setEF(e, frame.prev);
			__propagate(_, e);
		}
		finally {
			__g.frame = frame.prev;
		}
	}

	return {
		__g: __g,
		__srcName: __srcName,
		__func: __func,
		__cb: __cb,
		__future: __future,
		__propagate: __propagate,
		__trap: __trap,
		__tryCatch: __tryCatch,
		__forIn: __forIn,
		__apply: __apply,
		__setEF: __setEF
	};
}

function __cb(_, frame, offset, col, fn){
	frame.offset = offset;
	frame.col = col;
	var ctx = __g.context;
	return function ___(err, result){
		var oldFrame = __g.frame;
		__g.frame = frame;
		__g.context = ctx;
		try {
			if (err) {
				__setEF(err, frame);
				return _(err);
			}
			return fn(null, result);
		}
		catch (ex) {
			__setEF(ex, frame);
			return __propagate(_, ex);
		}
		finally {
			__g.frame = oldFrame;
		}
	}
}

// unfortunately callee is gone. So we need to pass a function
function __future(fn, args, i){
	var err, result, done, q = [];
	args = Array.prototype.slice.call(args);
	args[i] = function(e, r){
		err = e, result = r, done = true;
		q && q.forEach(function(f){
			try {
				f(e, r);
			}
			catch (ex) {
				__trap(ex);
			}
		});
		q = null;
	};
	fn.apply(this, args);
	return function ___(_){
		if (done)
			_(err, result);
		else
			q.push(_)
	}
}

function __propagate(_, err){
	try {
		_(err);
	}
	catch (ex) {
		__trap(ex);
	}
}

function __trap(err){
	if (err) {
		if (__g.context && __g.context.errorHandler)
			__g.context.errorHandler(err);
		else
			console.error("UNCAUGHT EXCEPTION: " + err.message + "\\n" + err.stack);
	}
}

__tryCatch: function __tryCatch(_, fn){
	try {
		fn();
	}
	catch (e) {
		try {
			_(e);
		}
		catch (ex) {
			__trap(ex);
		}
	}
}

function __forIn(object){
	var array = [];
	for (var obj in object) {
		array.push(obj);
	}
	return array;
}

function __apply(cb, fn, thisObj, args, index){
	if (cb == null)
		return __future(__apply, arguments, 0);
	args[index != null ? index : args.length] = cb;
	return fn.apply(thisObj, args);
}

function __setEF(e, f){
	function formatStack(e, raw){
		var s = raw, f, skip, skipFunc = 0;
		if (s) {
			var ff;
			s = s.split('\n').map(function(l){
				// try to map firefox format to V8 format
				// ffOffset takes care of lines difference introduced by require.js script.
				var ffOffset = __streamline.ffOffset || 0;
				var m = /(^[^(]+)\([^@]*\@(.*)\:(\d+)$/.exec(l);
				l = m ? "    at " + m[1] + " (" + m[2] + ":" + (parseInt(m[3]) - ffOffset) + ":0)" : l;
				ff = ff || (m != null);
				var i = l.indexOf('__$');
				if (i >= 0 && !skip) {
					skip = true;
					return l.substring(0, i) + l.substring(i + 3) + '\n';
				}
				return skip ? '' : l + '\n';
			}).join('');
			if (ff) // firefox does not include message
				s = "Error: " + e.message + '\n' + s;
			for (var f = e.__frame; f; f = f.prev) {
				if (f.offset >= 0)
					s += "    at " + f.name + " (" + f.file + ":" + (f.line + f.offset) + ":" + f.col + ")\n"
			}
		}
		return s;
	};
	e.__frame = e.__frame || f;
	if (exports.stackTraceEnabled && e.__lookupGetter__("rawStack") == null) {
		var getter = e.__lookupGetter__("stack");
		if (!getter) { // FF case
			var raw = e.stack;
			getter = function(){
				return raw;
			}
		}
		e.__defineGetter__("rawStack", getter);
		e.__defineGetter__("stack", function(){
			return formatStack(e, getter());
		});
	}
}

/// * `runtime.stackTraceEnabled = true/false;`
///   If true, `err.stack` returns the reconstructed _sync_ stack trace.
///   Otherwise, it returns the _raw_ stack trace.
///   The default is true, but you must require the flows module
///   at least once to enable sync stack traces.
module.exports.stackTraceEnabled = true;
<|endoftext|>


<commit_before><commit_msg>Compress GOV.UK Template assets<commit_after><|endoftext|>


<commit_before>'use strict'

var debug = require('debug')('rascal:config:configure')
var format = require('util').format
var url = require('url')
var _ = require('lodash').runInContext().mixin({ 'defaultsDeep': require('merge-defaults') })
var uuid = require('node-uuid').v4
var emptyConfig = require('./empty')
var fqn = require('./fqn')
var XRegExp = require('xregexp').XRegExp
var freeze = require('deep-freeze')

module.exports = _.curry(function(rascalConfig, next) {
    rascalConfig = _.defaultsDeep(rascalConfig, emptyConfig, { publications: {}, subscriptions: {} })
    try {
        configureVhosts(rascalConfig.vhosts)
        configurePublications(rascalConfig.publications)
        configureSubscriptions(rascalConfig.subscriptions)
        configureShovels(rascalConfig.shovels)
        configureCounters(rascalConfig.redeliveries.counters)
        return next(null, freeze(rascalConfig))
    } catch(err) {
        return next(err)
    }

    function configureVhosts(vhosts) {
        _.each(rascalConfig.vhosts, function(vhostConfig, name) {
            configureVhost(name, vhostConfig)
            configureExchanges(vhostConfig)
            configureQueues(vhostConfig)
            configureBindings(vhostConfig)
            configureVhostPublications(vhostConfig)
            configureVhostSubscriptions(vhostConfig)
        })
    }

    function configureVhost(name, vhostConfig) {
        debug('Configuring vhost: %s', name)
        rascalConfig.vhosts[name] = _.defaultsDeep(vhostConfig, { name: name, namespace: rascalConfig.defaults.vhosts.namespace }, { defaults: rascalConfig.defaults.vhosts })
        rascalConfig.vhosts[name].namespace = vhostConfig.namespace === true ? uuid() : vhostConfig.namespace
        configureConnections(vhostConfig, name)
    }

    function configureConnections(vhostConfig, vhostName) {
        vhostConfig.connections = _.chain([]).concat(vhostConfig.connections, vhostConfig.connection).compact().unique().value()
        if (vhostConfig.connections.length === 0) vhostConfig.connections.push({})
        _.each(vhostConfig.connections, function(connection) {
            configureConnection(vhostConfig, vhostName, connection)
        })
        delete vhostConfig.connection
    }

    function configureConnection(vhostConfig, vhostName, connection) {
        _.defaultsDeep(connection, vhostConfig.defaults.connection)
        connection.vhost = connection.vhost !== undefined ? connection.vhost : vhostName,
        connection.auth = connection.user + ':' + connection.password
        connection.pathname = connection.vhost === '/' ? '' : connection.vhost
        connection.query = connection.options
        connection.url = connection.url || url.format(connection)
        connection.loggableUrl = connection.url.replace(/:[^:]*?@/, ':***@')
    }

    function configureVhostPublications(vhostConfig) {
        _.each(vhostConfig.publications, function(publicationConfig, name) {
            publicationConfig.vhost = vhostConfig.name
            configurePublication(publicationConfig, name)
        })
        delete vhostConfig.publications
    }

    function configurePublications(publications) {
        _.each(publications, configurePublication)
    }

    function configurePublication(publicationConfig, name) {
        debug('Configuring publication: %s', name)
        if (rascalConfig.publications[name] && rascalConfig.publications[name].vhost !== publicationConfig.vhost) throw new Error(format('Duplicate publication: %s', name))
        rascalConfig.publications[name] = _.defaultsDeep(publicationConfig, { name: name }, rascalConfig.defaults.publications)
        if (!rascalConfig.vhosts[publicationConfig.vhost]) return
        var destination = publicationConfig.exchange ? rascalConfig.vhosts[publicationConfig.vhost].exchanges[publicationConfig.exchange]
                                                     : rascalConfig.vhosts[publicationConfig.vhost].queues[publicationConfig.queue]
        rascalConfig.publications[name].destination = destination.fullyQualifiedName
    }

    function configureVhostSubscriptions(vhostConfig) {
        _.each(vhostConfig.subscriptions, function(subscriptionConfig, name) {
            subscriptionConfig.vhost = vhostConfig.name
            configureSubscription(subscriptionConfig, name)
        })
        delete vhostConfig.subscriptions
    }

    function configureSubscriptions(subscriptions) {
        _.each(subscriptions, configureSubscription)
    }

    function configureSubscription(subscriptionConfig, name) {
        debug('Configuring subscription: %s', name)
        if (rascalConfig.subscriptions[name] && rascalConfig.subscriptions[name].vhost !== subscriptionConfig.vhost) throw new Error(format('Duplicate subscription: %s', name))
        rascalConfig.subscriptions[name] = _.defaultsDeep(subscriptionConfig, { name: name }, rascalConfig.defaults.subscriptions)
        if (!rascalConfig.vhosts[subscriptionConfig.vhost]) return
        subscriptionConfig.source = rascalConfig.vhosts[subscriptionConfig.vhost].queues[subscriptionConfig.queue].fullyQualifiedName
    }

    function configureShovels(shovels) {
        rascalConfig.shovels = ensureKeyedCollection(shovels)
        _.each(rascalConfig.shovels, configureShovel)
    }

    function configureShovel(shovelConfig, name) {
        debug('Configuring shovel: %s', name)
        var parsedConfig = parseShovelName(name)
        rascalConfig.shovels[name] = _.defaultsDeep(shovelConfig, { name: name }, parsedConfig, rascalConfig.defaults.shovels)
    }

    function parseShovelName(name) {
        var pattern = XRegExp('(?<subscription>[\\w:]+)\\s*->\\s*(?<publication>[\\w:]+)')
        var match = XRegExp.exec(name, pattern)
        return match ? { name: name, subscription: match.subscription, publication: match.publication } : { name: name }
    }

    function configureCounters(counters) {
        rascalConfig.counters = ensureKeyedCollection(counters)
        _.each(rascalConfig.counters, configureCounter)
    }

    function configureCounter(counterConfig, name) {
        debug('Configuring counter: %s', name)
        rascalConfig.counters[name] = _.defaultsDeep(counterConfig, { name: name, type: name }, rascalConfig.defaults.counters)
    }
})

function configureExchanges(config) {
    config.exchanges = ensureKeyedCollection(config.exchanges)
    _.each(config.exchanges, function(exchangeConfig, name) {
        debug('Configuring exchange: %s', name)
        config.exchanges[name] = _.defaultsDeep(exchangeConfig, { name: name, fullyQualifiedName: fqn.qualify(name, config.namespace) }, config.defaults.exchanges)
    })
}

function configureQueues(config) {
    config.queues = ensureKeyedCollection(config.queues)
    _.each(config.queues, function(queueConfig, name) {
        debug('Configuring queue: %s', name)
        queueConfig.replyTo = queueConfig.replyTo === true ? uuid() : queueConfig.replyTo
        qualifyArguments(config.namespace, queueConfig.options && queueConfig.options.arguments)
        config.queues[name] = _.defaultsDeep(queueConfig, { name: name, fullyQualifiedName: fqn.qualify(name, config.namespace, queueConfig.replyTo) }, config.defaults.queues)
    })
}

function configureBindings(config) {

    config.bindings = expandBindings(ensureKeyedCollection(config.bindings))

    _.each(config.bindings, function(bindingConfig, name) {
        debug('Configuring binding: %s', name)

        config.bindings[name] = _.defaultsDeep(bindingConfig, config.defaults.bindings)

        if (bindingConfig.qualifyBindingKeys) {
            config.bindings[name].bindingKey = fqn.qualify(bindingConfig.bindingKey, config.namespace)
        }
        if (bindingConfig.destinationType === 'queue') {
            var queue = config.queues[bindingConfig.destination]
            config.bindings[name].bindingKey = fqn.prefix(queue && queue.replyTo, bindingConfig.bindingKey, '.')
        }
    })
}

function parseBindingName(name) {
    var pattern = XRegExp('(?<source>[\\w:]+)\\s*(?:\\[\\s*(?<keys>.*)\\s*\\])?\\s*->\\s*(?<destination>[\\w:]+)')
    var match = XRegExp.exec(name, pattern)
    return match ? { name: name, source: match.source, destination: match.destination, bindingKeys: splitBindingKeys(match.keys) } : { name: name }
}

function splitBindingKeys(keys) {
    return keys ? _.compact(keys.split(/[,\s]+/)) : undefined
}

function expandBindings(definitions) {
    var result = {}
    _.each(definitions, function(bindingConfig, name) {
        var parsedConfig = parseBindingName(name)
        var bindingKeys = _.chain([]).concat(bindingConfig.bindingKeys, bindingConfig.bindingKey, parsedConfig.bindingKeys).compact().unique().value()
        if (bindingKeys.length <= 1) {
            result[name] = _({ bindingKey: bindingKeys[0] }).defaults(bindingConfig, parsedConfig).omit('bindingKeys').value()
            return result[name]
        }
        _.each(bindingKeys, function(bindingKey) {
            result[format('%s:%s', name, bindingKey)] = _({ bindingKey: bindingKey }).defaults(bindingConfig, parsedConfig).omit('bindingKeys').value()
        })
    })
    return result
}

function qualifyArguments(namespace, args) {
    if (!args) return
    _.each(['x-dead-letter-exchange'], function(name) {
        args[name] = args[name] !== undefined ? fqn.qualify(args[name], namespace) : args[name]
    })
}

function ensureKeyedCollection(collection) {
    if (!_.isArray(collection)) return collection
    return _.chain(collection).map(function(item) {
        return _.isString(item) ? { name: item } : _.defaults(item, { name: 'unnamed-' + uuid() })
    }).indexBy('name').value()
}
<commit_msg>Defaulting stub config<commit_after>'use strict'

var debug = require('debug')('rascal:config:configure')
var format = require('util').format
var url = require('url')
var _ = require('lodash').runInContext().mixin({ 'defaultsDeep': require('merge-defaults') })
var uuid = require('node-uuid').v4
var emptyConfig = require('./empty')
var fqn = require('./fqn')
var XRegExp = require('xregexp').XRegExp
var freeze = require('deep-freeze')

module.exports = _.curry(function(rascalConfig, next) {
    rascalConfig = _.defaultsDeep(rascalConfig, emptyConfig, { publications: {}, subscriptions: {}, redeliveries: { counters: { stub: {} }}})
    try {
        configureVhosts(rascalConfig.vhosts)
        configurePublications(rascalConfig.publications)
        configureSubscriptions(rascalConfig.subscriptions)
        configureShovels(rascalConfig.shovels)
        configureCounters(rascalConfig.redeliveries.counters)
        return next(null, freeze(rascalConfig))
    } catch(err) {
        return next(err)
    }

    function configureVhosts(vhosts) {
        _.each(rascalConfig.vhosts, function(vhostConfig, name) {
            configureVhost(name, vhostConfig)
            configureExchanges(vhostConfig)
            configureQueues(vhostConfig)
            configureBindings(vhostConfig)
            configureVhostPublications(vhostConfig)
            configureVhostSubscriptions(vhostConfig)
        })
    }

    function configureVhost(name, vhostConfig) {
        debug('Configuring vhost: %s', name)
        rascalConfig.vhosts[name] = _.defaultsDeep(vhostConfig, { name: name, namespace: rascalConfig.defaults.vhosts.namespace }, { defaults: rascalConfig.defaults.vhosts })
        rascalConfig.vhosts[name].namespace = vhostConfig.namespace === true ? uuid() : vhostConfig.namespace
        configureConnections(vhostConfig, name)
    }

    function configureConnections(vhostConfig, vhostName) {
        vhostConfig.connections = _.chain([]).concat(vhostConfig.connections, vhostConfig.connection).compact().unique().value()
        if (vhostConfig.connections.length === 0) vhostConfig.connections.push({})
        _.each(vhostConfig.connections, function(connection) {
            configureConnection(vhostConfig, vhostName, connection)
        })
        delete vhostConfig.connection
    }

    function configureConnection(vhostConfig, vhostName, connection) {
        _.defaultsDeep(connection, vhostConfig.defaults.connection)
        connection.vhost = connection.vhost !== undefined ? connection.vhost : vhostName,
        connection.auth = connection.user + ':' + connection.password
        connection.pathname = connection.vhost === '/' ? '' : connection.vhost
        connection.query = connection.options
        connection.url = connection.url || url.format(connection)
        connection.loggableUrl = connection.url.replace(/:[^:]*?@/, ':***@')
    }

    function configureVhostPublications(vhostConfig) {
        _.each(vhostConfig.publications, function(publicationConfig, name) {
            publicationConfig.vhost = vhostConfig.name
            configurePublication(publicationConfig, name)
        })
        delete vhostConfig.publications
    }

    function configurePublications(publications) {
        _.each(publications, configurePublication)
    }

    function configurePublication(publicationConfig, name) {
        debug('Configuring publication: %s', name)
        if (rascalConfig.publications[name] && rascalConfig.publications[name].vhost !== publicationConfig.vhost) throw new Error(format('Duplicate publication: %s', name))
        rascalConfig.publications[name] = _.defaultsDeep(publicationConfig, { name: name }, rascalConfig.defaults.publications)
        if (!rascalConfig.vhosts[publicationConfig.vhost]) return
        var destination = publicationConfig.exchange ? rascalConfig.vhosts[publicationConfig.vhost].exchanges[publicationConfig.exchange]
                                                     : rascalConfig.vhosts[publicationConfig.vhost].queues[publicationConfig.queue]
        rascalConfig.publications[name].destination = destination.fullyQualifiedName
    }

    function configureVhostSubscriptions(vhostConfig) {
        _.each(vhostConfig.subscriptions, function(subscriptionConfig, name) {
            subscriptionConfig.vhost = vhostConfig.name
            configureSubscription(subscriptionConfig, name)
        })
        delete vhostConfig.subscriptions
    }

    function configureSubscriptions(subscriptions) {
        _.each(subscriptions, configureSubscription)
    }

    function configureSubscription(subscriptionConfig, name) {
        debug('Configuring subscription: %s', name)
        if (rascalConfig.subscriptions[name] && rascalConfig.subscriptions[name].vhost !== subscriptionConfig.vhost) throw new Error(format('Duplicate subscription: %s', name))
        rascalConfig.subscriptions[name] = _.defaultsDeep(subscriptionConfig, { name: name }, rascalConfig.defaults.subscriptions)
        if (!rascalConfig.vhosts[subscriptionConfig.vhost]) return
        subscriptionConfig.source = rascalConfig.vhosts[subscriptionConfig.vhost].queues[subscriptionConfig.queue].fullyQualifiedName
    }

    function configureShovels(shovels) {
        rascalConfig.shovels = ensureKeyedCollection(shovels)
        _.each(rascalConfig.shovels, configureShovel)
    }

    function configureShovel(shovelConfig, name) {
        debug('Configuring shovel: %s', name)
        var parsedConfig = parseShovelName(name)
        rascalConfig.shovels[name] = _.defaultsDeep(shovelConfig, { name: name }, parsedConfig, rascalConfig.defaults.shovels)
    }

    function parseShovelName(name) {
        var pattern = XRegExp('(?<subscription>[\\w:]+)\\s*->\\s*(?<publication>[\\w:]+)')
        var match = XRegExp.exec(name, pattern)
        return match ? { name: name, subscription: match.subscription, publication: match.publication } : { name: name }
    }

    function configureCounters(counters) {
        rascalConfig.counters = ensureKeyedCollection(counters)
        _.each(rascalConfig.counters, configureCounter)
    }

    function configureCounter(counterConfig, name) {
        debug('Configuring counter: %s', name)
        rascalConfig.counters[name] = _.defaultsDeep(counterConfig, { name: name, type: name }, rascalConfig.defaults.counters)
    }
})

function configureExchanges(config) {
    config.exchanges = ensureKeyedCollection(config.exchanges)
    _.each(config.exchanges, function(exchangeConfig, name) {
        debug('Configuring exchange: %s', name)
        config.exchanges[name] = _.defaultsDeep(exchangeConfig, { name: name, fullyQualifiedName: fqn.qualify(name, config.namespace) }, config.defaults.exchanges)
    })
}

function configureQueues(config) {
    config.queues = ensureKeyedCollection(config.queues)
    _.each(config.queues, function(queueConfig, name) {
        debug('Configuring queue: %s', name)
        queueConfig.replyTo = queueConfig.replyTo === true ? uuid() : queueConfig.replyTo
        qualifyArguments(config.namespace, queueConfig.options && queueConfig.options.arguments)
        config.queues[name] = _.defaultsDeep(queueConfig, { name: name, fullyQualifiedName: fqn.qualify(name, config.namespace, queueConfig.replyTo) }, config.defaults.queues)
    })
}

function configureBindings(config) {

    config.bindings = expandBindings(ensureKeyedCollection(config.bindings))

    _.each(config.bindings, function(bindingConfig, name) {
        debug('Configuring binding: %s', name)

        config.bindings[name] = _.defaultsDeep(bindingConfig, config.defaults.bindings)

        if (bindingConfig.qualifyBindingKeys) {
            config.bindings[name].bindingKey = fqn.qualify(bindingConfig.bindingKey, config.namespace)
        }
        if (bindingConfig.destinationType === 'queue') {
            var queue = config.queues[bindingConfig.destination]
            config.bindings[name].bindingKey = fqn.prefix(queue && queue.replyTo, bindingConfig.bindingKey, '.')
        }
    })
}

function parseBindingName(name) {
    var pattern = XRegExp('(?<source>[\\w:]+)\\s*(?:\\[\\s*(?<keys>.*)\\s*\\])?\\s*->\\s*(?<destination>[\\w:]+)')
    var match = XRegExp.exec(name, pattern)
    return match ? { name: name, source: match.source, destination: match.destination, bindingKeys: splitBindingKeys(match.keys) } : { name: name }
}

function splitBindingKeys(keys) {
    return keys ? _.compact(keys.split(/[,\s]+/)) : undefined
}

function expandBindings(definitions) {
    var result = {}
    _.each(definitions, function(bindingConfig, name) {
        var parsedConfig = parseBindingName(name)
        var bindingKeys = _.chain([]).concat(bindingConfig.bindingKeys, bindingConfig.bindingKey, parsedConfig.bindingKeys).compact().unique().value()
        if (bindingKeys.length <= 1) {
            result[name] = _({ bindingKey: bindingKeys[0] }).defaults(bindingConfig, parsedConfig).omit('bindingKeys').value()
            return result[name]
        }
        _.each(bindingKeys, function(bindingKey) {
            result[format('%s:%s', name, bindingKey)] = _({ bindingKey: bindingKey }).defaults(bindingConfig, parsedConfig).omit('bindingKeys').value()
        })
    })
    return result
}

function qualifyArguments(namespace, args) {
    if (!args) return
    _.each(['x-dead-letter-exchange'], function(name) {
        args[name] = args[name] !== undefined ? fqn.qualify(args[name], namespace) : args[name]
    })
}

function ensureKeyedCollection(collection) {
    if (!_.isArray(collection)) return collection
    return _.chain(collection).map(function(item) {
        return _.isString(item) ? { name: item } : _.defaults(item, { name: 'unnamed-' + uuid() })
    }).indexBy('name').value()
}
<|endoftext|>


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

var util = require('util');

var async = require('async');

var agentManagers = require('cast-agent/managers');
var jobs = require('jobs');
var instances = require('deployment/instances');

function getInstanceManager() {
  return agentManagers.getManager('InstanceManager');
}

/**
 * A Job that executes a service action.
 * @extends {jobs.Job}
 * @param {String} name The name of the Instance to execute the action against.
 * @param {String} action The name of the service action to execute.
 */
function ServiceActionJob(name, action) {
  jobs.Job.call(this, [action]);
  this.options = jobs.JobOptions.UPDATE;
  this.resourceName = name;
  this.resourceType = instances.Instance;
}

util.inherits(ServiceActionJob, jobs.Job);

/**
 * Execute a service action.
 * @param {deployment.instances.Instance} instance The Instance to act on.
 * @param {String} action The name of the action to run.
 * @param {Function} callback A callback fired with (err).
 */
ServiceActionJob.prototype.run = function(instance, action, callback) {
  instance.serviceAction(action, callback);
};

function getService(name, callback) {
  getInstanceManager().get(name, function(err, instance) {
    if (err) {
      callback(err);
    } else {
      callback(null, instance.service);
    }
  });
}

function listServices(callback) {
  var services;

  getInstanceManager().list(function(err, instances) {
    if (err) {
      callback(err);
    } else {
      services = instances.map(function(instance) {
        return instance.service;
      });
      callback(null, services);
    }
  });
}

function enableService(name, callback) {
  var j = new ServiceActionJob(name, 'enable');
  agentManagers.getJobManager().run(j);
  return j;
}

function disableService(name, callback) {
  var j = new ServiceActionJob(name, 'disable');
  agentManagers.getJobManager().run(j);
  return j;
}

function startService(name, callback) {
  var j = new ServiceActionJob(name, 'start');
  agentManagers.getJobManager().run(j);
  return j;
}

function stopService(name, callback) {
  var j = new ServiceActionJob(name, 'stop');
  agentManagers.getJobManager().run(j);
  return j;
}

function restartService(name, callback) {
  var j = new ServiceActionJob(name, 'restart');
  agentManagers.getJobManager().run(j);
  return j;
}

function tailServiceLog(name, bytes, follow, callback) {
  var services;

  getInstanceManager().getLive(name, function(err, instance) {
    if (err) {
      callback(err);
    } else {
      instance.tailServiceLog(bytes, follow, callback);
    }
  });
}

exports.getService = getService;
exports.listServices = listServices;
exports.enableService = enableService;
exports.disableService = disableService;
exports.startService = startService;
exports.stopService = stopService;
exports.restartService = restartService;
exports.tailServiceLog = tailServiceLog;
<commit_msg>fix leaked Instance<commit_after>/*
 * Licensed to Cloudkick, Inc ('Cloudkick') under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * Cloudkick licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var util = require('util');

var async = require('async');

var agentManagers = require('cast-agent/managers');
var jobs = require('jobs');
var instances = require('deployment/instances');

function getInstanceManager() {
  return agentManagers.getManager('InstanceManager');
}

/**
 * A Job that executes a service action.
 * @extends {jobs.Job}
 * @param {String} name The name of the Instance to execute the action against.
 * @param {String} action The name of the service action to execute.
 */
function ServiceActionJob(name, action) {
  jobs.Job.call(this, [action]);
  this.options = jobs.JobOptions.UPDATE;
  this.resourceName = name;
  this.resourceType = instances.Instance;
}

util.inherits(ServiceActionJob, jobs.Job);

/**
 * Execute a service action.
 * @param {deployment.instances.Instance} instance The Instance to act on.
 * @param {String} action The name of the action to run.
 * @param {Function} callback A callback fired with (err).
 */
ServiceActionJob.prototype.run = function(instance, action, callback) {
  instance.serviceAction(action, callback);
};

function getService(name, callback) {
  getInstanceManager().get(name, function(err, instance) {
    if (err) {
      callback(err);
    } else {
      callback(null, instance.service);
    }
  });
}

function listServices(callback) {
  var services;

  getInstanceManager().list(function(err, instances) {
    if (err) {
      callback(err);
    } else {
      services = instances.map(function(instance) {
        return instance.service;
      });
      callback(null, services);
    }
  });
}

function enableService(name, callback) {
  var j = new ServiceActionJob(name, 'enable');
  agentManagers.getJobManager().run(j);
  return j;
}

function disableService(name, callback) {
  var j = new ServiceActionJob(name, 'disable');
  agentManagers.getJobManager().run(j);
  return j;
}

function startService(name, callback) {
  var j = new ServiceActionJob(name, 'start');
  agentManagers.getJobManager().run(j);
  return j;
}

function stopService(name, callback) {
  var j = new ServiceActionJob(name, 'stop');
  agentManagers.getJobManager().run(j);
  return j;
}

function restartService(name, callback) {
  var j = new ServiceActionJob(name, 'restart');
  agentManagers.getJobManager().run(j);
  return j;
}

function tailServiceLog(name, bytes, follow, callback) {
  var services;

  getInstanceManager().getLive(name, function(err, instance) {
    if (err) {
      callback(err);
    } else {
      instance.tailServiceLog(bytes, follow, callback);
      instance.deref();
    }
  });
}

exports.getService = getService;
exports.listServices = listServices;
exports.enableService = enableService;
exports.disableService = disableService;
exports.startService = startService;
exports.stopService = stopService;
exports.restartService = restartService;
exports.tailServiceLog = tailServiceLog;
<|endoftext|>