<commit_before>function classificacao(event) {
    if (!event) {
        return false;
    }
    switch (event.classificacaoEtaria) {
        case 'Livre':
            return 'clivre';

        case '18 anos':
            return 'c18';

        case '16 anos':
            return 'c16';

        case '14 anos':
            return 'c14';

        case '12 anos':
            return 'c12';

        case '10 anos':
            return 'c10';
    }
}
angular.module('mapasculturais.controllers', [])

    .controller('eventsCtrl', [
        '$scope', 'mapas.service.event', 'FavoriteEvents', 'ConfigState', function ($scope, eventApi, FavoriteEvents, config) {
            var api = eventApi(config.dataSource.url);
            var _limit = 25;
            var _page = 1;
            var _endData = false;
            var _lastGroup = null;
            var _now = moment().format('X');

            $scope.groups = [];
            $scope.notFound = false;

            $scope.filters = {};

            $scope.moreDataCanBeLoaded = function () {
                return !_endData;
            }

            $scope.loadMore = function () {
                var events, from;
                var params = {
                    '@limit': _limit,
                    '@page': _page
                };

                if($scope.filters.showPast || ($scope.filters.from && moment($scope.filters.from).toDate() > moment().toDate())){
                    from = $scope.filters.from;
                } else {
                    from = moment().toDate();
                }

                if($scope.filters.keyword){
                    params['@keyword'] = '%' + $scope.filters.keyword + '%';
                }

                if($scope.filters.linguagem){
                    params['term:linguagem'] = $IN($scope.filters.linguagem);
                }

                if($scope.filters.verified){
                    params['isVerified'] = $EQ('true');
                }

                if ($scope.findFunction) {
                    var entityId = $scope.findEntityId;
                    events = api[$scope.findFunction](entityId, from, $scope.filters.to, params);
                } else {
                    events = api.find(from, $scope.filters.to, params);
                }

                _page++;

                events.then(function (rs) {
                    var happening;

                    if (rs.length < _limit) {
                        _endData = true;
                    }

                    if(_page === 2 && rs.length === 0){
                        $scope.notFound = true;
                        return;
                    }

                    rs.forEach(function(event) {
                        event.favorite = FavoriteEvents.isFavorite(event);
                    });

                    // remove os eventos antigos
                    if (!$scope.filters.showPast) {
                        happening = rs.filter(function(r){
                            var end = r.end.format('X');
                            var start = r.start.format('X');

                            if (start < _now && end > _now){
                                return r;
                            }
                        });

                        rs = rs.filter(function(r){
                            var start = r.start.format('X');

                            if(start > _now){
                                return r;
                            }
                        });
                    }

                    var _groups = api.group('YYYY-MM-DD HH:mm', rs);

                    if(happening.length > 0){
                        _groups.unshift({happening: true, events: happening});
                    }
                    _groups.forEach(function (grp) {
                        if (_lastGroup && (_lastGroup.happening && grp.happening || _lastGroup.date && grp.date && _lastGroup.date.format('YYYY-MM-DD HH:mm') === grp.date.format('YYYY-MM-DD HH:mm'))) {
                            grp.events.forEach(function (event) {
                                _lastGroup.events.push(event);
                            });
                        } else {
                            $scope.groups.push(grp);
                        }
                        _lastGroup = grp;
                    });
                    $scope.$broadcast('scroll.infiniteScrollComplete');

                });
            };

            $scope.applyFilters = function($event){
                $scope.$broadcast('scroll.infiniteScrollComplete');
                $scope.groups = [];
                $scope.notFound = false;
                _page = 1;
                _endData = false;

                document.activeElement.blur();
            }

            $scope.dividerText = function (group) {
                var numDays = 6;
                if(group.happening){
                    return "Acontecendo agora";
                } else if(group.date.format('X') < moment().add(numDays, 'days').format('X')) {
                    return group.date.calendar();
                } else {
                    return group.date.format('LLL');
                }
            }

            $scope.classificacao = classificacao;

            $scope.favorite = FavoriteEvents.favorite
        }])

    .controller('eventCtrl', [
        '$scope', '$stateParams', 'mapas.service.event', 'FavoriteEvents', 'ConfigState', function ($scope, $stateParams, eventApi, FavoriteEvents, config) {
            var api = eventApi(config.dataSource.url);
            api.util.applyMe.apply($scope);

            $scope.entity = null;

            api.findOne({id: $EQ($stateParams.entity)}).then(function (entity) {
                $scope.entity = entity;
            });

            $scope.favorite = FavoriteEvents.favorite;

            $scope.classificacao = classificacao;

        }])

    .controller('spacesCtrl', [
        '$scope', 'MenuState', 'mapas.service.space', 'ConfigState', function ($scope, MenuState, spaceApi, config) {
            var api = spaceApi(config.dataSource.url);
            var _limit = 25;
            var _page = 1;
            var _endData = false;

            api.util.applyMe.apply($scope);

            MenuState.activeMenu('spaces');

            $scope.entities = [];

            $scope.filters = {};

            $scope.$watch('filters', function () {
                $scope.entities = [];
                _page = 1;
                _endData = false;
            });

            $scope.moreDataCanBeLoaded = function () {
                return !_endData;
            }

            $scope.loadMore = function(){
                var params = {
                    '@limit': _limit,
                    '@page': _page,
                    '@order': 'name ASC',
                    '@select': api._select + ',endereco'
                };

                if($scope.filters.keyword){
                    params['@keyword'] = '%' + $scope.filters.keyword + '%';
                }

                if($scope.filters.area){
                    params['term:area'] = $IN($scope.filters.area);
                }

                if($scope.filters.type){
                    params['type'] = $IN($scope.filters.type);
                }

                _page++;

                api.find(params).then(function(rs){
                    if (rs.length < _limit) {
                        _endData = true;
                    }

                    if(_page === 2 && rs.length === 0){
                        $scope.notFound = true;
                        return;
                    }

                    rs.forEach(function(entity){
                        $scope.entities.push(entity);
                    });

                    $scope.$broadcast('scroll.infiniteScrollComplete');
                });
            }

            $scope.applyFilters = function($event){
                $scope.$broadcast('scroll.infiniteScrollComplete');
                $scope.entities = [];
                $scope.notFound = false;
                _page = 1;
                _endData = false;

                document.activeElement.blur();
            }
        }])

    .controller('spaceCtrl', [
        '$scope', '$stateParams', 'mapas.service.space', 'mapas.service.event', 'ConfigState', function ($scope, $stateParams, spaceApi, eventApi, config) {
            var api = spaceApi(config.dataSource.url);
            api.util.applyMe.apply($scope);

            $scope.entity = null;

            api.findOne({id: $EQ($stateParams.entity)}).then(function (entity) {
                $scope.entity = entity;
            });
        }])

    .controller('agentCtrl', [
        '$scope', '$stateParams', 'mapas.service.agent', 'mapas.service.event', 'ConfigState', function ($scope, $stateParams, agentApi, eventApi, config) {
            var api = agentApi(config.dataSource.url);
            api.util.applyMe.apply($scope);

            $scope.entity = null;

            api.findOne({id: $EQ($stateParams.entity)}).then(function (entity) {
                $scope.entity = entity;
            });
        }])

    .controller('projectCtrl', [
        '$scope', '$stateParams', 'mapas.service.project', 'mapas.service.event', 'ConfigState', function ($scope, $stateParams, projectApi, eventApi, config) {
            var api = projectApi(config.dataSource.url);
            api.util.applyMe.apply($scope);

            $scope.entity = null;

            api.findOne({id: $EQ($stateParams.entity)}).then(function (entity) {
                $scope.entity = entity;
            });
        }])

    .controller('mapCtrl', ['$scope', '$ionicPlatform', 'MapState', 'mapas.service.space', 'ConfigState', function ($scope, $ionicPlatform, MapState, spaceApi, config) {
        var api = spaceApi(config.dataSource.url);
        var map;
        var from = moment().toDate()
        var to = moment().add(1, 'months').toDate();

        api.util.applyMe.apply($scope);
        $scope.map_state = MapState;

        var _spaces = api.findByEvents(from, to, {'@select': 'id,name,location,endereco,type,terms'});

        $ionicPlatform.ready(function(MapState) {

            var map_wrapper = angular.element(document.querySelector("#map-wrapper"));
            $scope.frameHeight = map_wrapper[0].clientHeight;

            // Getting the map selector in DOM
            var div = document.getElementById("map_canvas");

            // Invoking Map using Google Map SDK v2 by dubcanada
            map = plugin.google.maps.Map.getMap(div, $scope.map_state.options);

            map.setClickable(true);
            // Capturing event when Map load are ready.
            map.addEventListener(plugin.google.maps.event.MAP_READY, function(){
                _spaces.then(function(spaces){
                    console.log(_spaces);
                    spaces.forEach(function(space){
                        var pin = {
                            title: space.name,
                            snippet:
                                "endereço: " + space.endereco + "\n" +
                                "tipo: " + space.type.name + "\n" +
                                "área de atuação: " + space.terms.area.join(', '),
                            visible: true,
                            position: new plugin.google.maps.LatLng(
                                space.location.latitude,
                                space.location.longitude),

                            styles: {
                                maxWidth: "90%"
                            }
                        };

                        map.addMarker(pin, function(marker){
                            space.marker = marker;
                            marker.addEventListener(
                                plugin.google.maps.event.INFO_CLICK,
                                function(){
                                    document.location.hash = '/app/space/' + space.id;
                                });
                        });
                    });
                });
                // Defining markers for demo
                // var markers = [{
                //     position: setPosition(-19.9178713, -43.9603117),
                //     title: "Marker 1"
                // }, {
                //     position: setPosition(-19.8363826, -43.9787167),
                //     title: "Marker 2"
                // }];
                //
                // // Bind markers
                // for (var i = 0; i < markers.length; i++) {
                //     map.addMarker({
                //         'marker': markers[i],
                //         'position': markers[i].position
                //     }, function(marker) {
                //
                //         // Defining event for each marker
                //         marker.on("click", function() {
                //             alert(marker.get('marker').title);
                //         });
                //
                //     });
                // }
            });

            // Function that return a LatLng Object to Map
            // function setPosition(lat, lng) {
            //     return new plugin.google.maps.LatLng(lat, lng);
            // }
      });
    }])

    .controller('aboutCtrl', function ($scope) {

    })

    .controller('configCtrl', function ($scope, FavoriteEvents, ConfigState, $window) {
        $scope.dataSources = ConfigState.dataSources;
        $scope.config = {
            prefix: ConfigState.dataSource.prefix
        };

        $scope.apply = function(){
            ConfigState.defineDataSource($scope.config.prefix);
            $window.location.reload(true)
        };

        $scope.clearFavorites = function () {
            if (confirm('Você está certo de que deseja apagar todos os seus eventos favoritados?'))
                FavoriteEvents.clear();
        };
    })

    .controller('favoritesCtrl', ['$scope', 'MenuState', 'FavoriteEvents', function ($scope, MenuState, FavoriteEvents) {
        $scope.events = FavoriteEvents.favorites;
        $scope.favorite = FavoriteEvents.favorite;
    }])

    .controller('messagesCtrl', function ($scope) {

    })

    .controller('navCtrl', function ($scope, ConfigState, MenuState, $location, $timeout, $ionicLoading, $window) {

        $scope.show_filter_search_menu = true;
        $scope.show_share_buttom = false;

        $scope.openMenuMore = function(){
            $scope.showMenuMore = true;
        };

        $scope.closeMenuMore = function(){
            $scope.showMenuMore = false;
        };

        $scope.toggleMenuMore = function($event){
            $scope.showMenuMore = $scope.showMenuMore ? false : true;
            $event.stopPropagation();
        };

        angular.element($window).on('click', function(e){
            $scope.closeMenuMore();
            $scope.$apply();
        });

        function activeMenu (toState){
            switch(toState.name){
                case 'menu.spaces':
                    MenuState.activeMenu('spaces');
                    break;
                case 'menu.space':
                    MenuState.activeMenu('spaces');
                    break;

                case 'menu.agents':
                    MenuState.activeMenu('agents');
                    break;
                case 'menu.agent':
                    MenuState.activeMenu('agents');
                    break;

                case 'menu.projects':
                    MenuState.activeMenu('projects');
                    break;
                case 'menu.project':
                    MenuState.activeMenu('projects');
                    break;

                case 'menu.events':
                    MenuState.activeMenu('events');
                    break;
                case 'menu.event':
                    MenuState.activeMenu('events');
                    break;

                case 'menu.map':
                    MenuState.activeMenu('map');
                    break;

                case 'menu.favorites':
                    MenuState.activeMenu('favorites');
                    break;

                case 'menu.about':
                    MenuState.activeMenu('about');
                    break;

                case 'menu.config':
                    MenuState.activeMenu('about');
                    break;

            }
        }

        $scope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
            // var new_location_path = newVal.split('#')[1];
            // var old_location_path = oldVal.split('#')[1];

            activeMenu(toState);

            if (toState.name == 'menu.events') {
                $scope.show_filter_search_menu = true;
            } else {
                $scope.show_filter_search_menu = false;
            }
            $ionicLoading.show();
        });

        $scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) {
            activeMenu(toState);
            $ionicLoading.hide();
        });
    })
<commit_msg>fix: erro ao filtrar eventos com data inicial e final no passado<commit_after>function classificacao(event) {
    if (!event) {
        return false;
    }
    switch (event.classificacaoEtaria) {
        case 'Livre':
            return 'clivre';

        case '18 anos':
            return 'c18';

        case '16 anos':
            return 'c16';

        case '14 anos':
            return 'c14';

        case '12 anos':
            return 'c12';

        case '10 anos':
            return 'c10';
    }
}
angular.module('mapasculturais.controllers', [])

    .controller('eventsCtrl', [
        '$scope', 'mapas.service.event', 'FavoriteEvents', 'ConfigState', function ($scope, eventApi, FavoriteEvents, config) {
            var api = eventApi(config.dataSource.url);
            var _limit = 25;
            var _page = 1;
            var _endData = false;
            var _lastGroup = null;
            var _now = moment().format('X');

            $scope.groups = [];
            $scope.notFound = false;

            $scope.filters = {};

            $scope.moreDataCanBeLoaded = function () {
                return !_endData;
            }

            $scope.loadMore = function () {
                var events, from;
                var params = {
                    '@limit': _limit,
                    '@page': _page
                };

                if($scope.filters.showPast || ($scope.filters.from && moment($scope.filters.from).toDate() > moment().toDate())){
                    from = $scope.filters.from;
                } else {
                    from = moment().toDate();
                }

                if($scope.filters.keyword){
                    params['@keyword'] = '%' + $scope.filters.keyword + '%';
                }

                if($scope.filters.linguagem){
                    params['term:linguagem'] = $IN($scope.filters.linguagem);
                }

                if($scope.filters.verified){
                    params['isVerified'] = $EQ('true');
                }

                if ($scope.findFunction) {
                    var entityId = $scope.findEntityId;
                    events = api[$scope.findFunction](entityId, from, $scope.filters.to, params);
                } else {
                    events = api.find(from, $scope.filters.to, params);
                }

                _page++;

                events.then(function (rs) {
                    var happening = [];

                    if (rs.length < _limit) {
                        _endData = true;
                    }

                    if(_page === 2 && rs.length === 0){
                        $scope.notFound = true;
                        return;
                    }

                    rs.forEach(function(event) {
                        event.favorite = FavoriteEvents.isFavorite(event);
                    });

                    // remove os eventos antigos
                    if (!$scope.filters.showPast) {
                        happening = rs.filter(function(r){
                            var end = r.end.format('X');
                            var start = r.start.format('X');

                            if (start < _now && end > _now){
                                return r;
                            }
                        });

                        rs = rs.filter(function(r){
                            var start = r.start.format('X');

                            if(start > _now){
                                return r;
                            }
                        });
                    }

                    var _groups = api.group('YYYY-MM-DD HH:mm', rs);

                    if(happening.length > 0){
                        _groups.unshift({happening: true, events: happening});
                    }
                    _groups.forEach(function (grp) {
                        if (_lastGroup && (_lastGroup.happening && grp.happening || _lastGroup.date && grp.date && _lastGroup.date.format('YYYY-MM-DD HH:mm') === grp.date.format('YYYY-MM-DD HH:mm'))) {
                            grp.events.forEach(function (event) {
                                _lastGroup.events.push(event);
                            });
                        } else {
                            $scope.groups.push(grp);
                        }
                        _lastGroup = grp;
                    });
                    $scope.$broadcast('scroll.infiniteScrollComplete');

                });
            };

            $scope.applyFilters = function($event){
                $scope.$broadcast('scroll.infiniteScrollComplete');
                $scope.groups = [];
                $scope.notFound = false;
                _page = 1;
                _endData = false;

                document.activeElement.blur();
            }

            $scope.dividerText = function (group) {
                var numDays = 6;
                if(group.happening){
                    return "Acontecendo agora";
                } else if(group.date.format('X') < moment().add(numDays, 'days').format('X')) {
                    return group.date.calendar();
                } else {
                    return group.date.format('LLL');
                }
            }

            $scope.classificacao = classificacao;

            $scope.favorite = FavoriteEvents.favorite
        }])

    .controller('eventCtrl', [
        '$scope', '$stateParams', 'mapas.service.event', 'FavoriteEvents', 'ConfigState', function ($scope, $stateParams, eventApi, FavoriteEvents, config) {
            var api = eventApi(config.dataSource.url);
            api.util.applyMe.apply($scope);

            $scope.entity = null;

            api.findOne({id: $EQ($stateParams.entity)}).then(function (entity) {
                $scope.entity = entity;
            });

            $scope.favorite = FavoriteEvents.favorite;

            $scope.classificacao = classificacao;

        }])

    .controller('spacesCtrl', [
        '$scope', 'MenuState', 'mapas.service.space', 'ConfigState', function ($scope, MenuState, spaceApi, config) {
            var api = spaceApi(config.dataSource.url);
            var _limit = 25;
            var _page = 1;
            var _endData = false;

            api.util.applyMe.apply($scope);

            MenuState.activeMenu('spaces');

            $scope.entities = [];

            $scope.filters = {};

            $scope.$watch('filters', function () {
                $scope.entities = [];
                _page = 1;
                _endData = false;
            });

            $scope.moreDataCanBeLoaded = function () {
                return !_endData;
            }

            $scope.loadMore = function(){
                var params = {
                    '@limit': _limit,
                    '@page': _page,
                    '@order': 'name ASC',
                    '@select': api._select + ',endereco'
                };

                if($scope.filters.keyword){
                    params['@keyword'] = '%' + $scope.filters.keyword + '%';
                }

                if($scope.filters.area){
                    params['term:area'] = $IN($scope.filters.area);
                }

                if($scope.filters.type){
                    params['type'] = $IN($scope.filters.type);
                }

                _page++;

                api.find(params).then(function(rs){
                    if (rs.length < _limit) {
                        _endData = true;
                    }

                    if(_page === 2 && rs.length === 0){
                        $scope.notFound = true;
                        return;
                    }

                    rs.forEach(function(entity){
                        $scope.entities.push(entity);
                    });

                    $scope.$broadcast('scroll.infiniteScrollComplete');
                });
            }

            $scope.applyFilters = function($event){
                $scope.$broadcast('scroll.infiniteScrollComplete');
                $scope.entities = [];
                $scope.notFound = false;
                _page = 1;
                _endData = false;

                document.activeElement.blur();
            }
        }])

    .controller('spaceCtrl', [
        '$scope', '$stateParams', 'mapas.service.space', 'mapas.service.event', 'ConfigState', function ($scope, $stateParams, spaceApi, eventApi, config) {
            var api = spaceApi(config.dataSource.url);
            api.util.applyMe.apply($scope);

            $scope.entity = null;

            api.findOne({id: $EQ($stateParams.entity)}).then(function (entity) {
                $scope.entity = entity;
            });
        }])

    .controller('agentCtrl', [
        '$scope', '$stateParams', 'mapas.service.agent', 'mapas.service.event', 'ConfigState', function ($scope, $stateParams, agentApi, eventApi, config) {
            var api = agentApi(config.dataSource.url);
            api.util.applyMe.apply($scope);

            $scope.entity = null;

            api.findOne({id: $EQ($stateParams.entity)}).then(function (entity) {
                $scope.entity = entity;
            });
        }])

    .controller('projectCtrl', [
        '$scope', '$stateParams', 'mapas.service.project', 'mapas.service.event', 'ConfigState', function ($scope, $stateParams, projectApi, eventApi, config) {
            var api = projectApi(config.dataSource.url);
            api.util.applyMe.apply($scope);

            $scope.entity = null;

            api.findOne({id: $EQ($stateParams.entity)}).then(function (entity) {
                $scope.entity = entity;
            });
        }])

    .controller('mapCtrl', ['$scope', '$ionicPlatform', 'MapState', 'mapas.service.space', 'ConfigState', function ($scope, $ionicPlatform, MapState, spaceApi, config) {
        var api = spaceApi(config.dataSource.url);
        var map;
        var from = moment().toDate()
        var to = moment().add(1, 'months').toDate();

        api.util.applyMe.apply($scope);
        $scope.map_state = MapState;

        var _spaces = api.findByEvents(from, to, {'@select': 'id,name,location,endereco,type,terms'});

        $ionicPlatform.ready(function(MapState) {

            var map_wrapper = angular.element(document.querySelector("#map-wrapper"));
            $scope.frameHeight = map_wrapper[0].clientHeight;

            // Getting the map selector in DOM
            var div = document.getElementById("map_canvas");

            // Invoking Map using Google Map SDK v2 by dubcanada
            map = plugin.google.maps.Map.getMap(div, $scope.map_state.options);

            map.setClickable(true);
            // Capturing event when Map load are ready.
            map.addEventListener(plugin.google.maps.event.MAP_READY, function(){
                _spaces.then(function(spaces){
                    console.log(_spaces);
                    spaces.forEach(function(space){
                        var pin = {
                            title: space.name,
                            snippet:
                                "endereço: " + space.endereco + "\n" +
                                "tipo: " + space.type.name + "\n" +
                                "área de atuação: " + space.terms.area.join(', '),
                            visible: true,
                            position: new plugin.google.maps.LatLng(
                                space.location.latitude,
                                space.location.longitude),

                            styles: {
                                maxWidth: "90%"
                            }
                        };

                        map.addMarker(pin, function(marker){
                            space.marker = marker;
                            marker.addEventListener(
                                plugin.google.maps.event.INFO_CLICK,
                                function(){
                                    document.location.hash = '/app/space/' + space.id;
                                });
                        });
                    });
                });
                // Defining markers for demo
                // var markers = [{
                //     position: setPosition(-19.9178713, -43.9603117),
                //     title: "Marker 1"
                // }, {
                //     position: setPosition(-19.8363826, -43.9787167),
                //     title: "Marker 2"
                // }];
                //
                // // Bind markers
                // for (var i = 0; i < markers.length; i++) {
                //     map.addMarker({
                //         'marker': markers[i],
                //         'position': markers[i].position
                //     }, function(marker) {
                //
                //         // Defining event for each marker
                //         marker.on("click", function() {
                //             alert(marker.get('marker').title);
                //         });
                //
                //     });
                // }
            });

            // Function that return a LatLng Object to Map
            // function setPosition(lat, lng) {
            //     return new plugin.google.maps.LatLng(lat, lng);
            // }
      });
    }])

    .controller('aboutCtrl', function ($scope) {

    })

    .controller('configCtrl', function ($scope, FavoriteEvents, ConfigState, $window) {
        $scope.dataSources = ConfigState.dataSources;
        $scope.config = {
            prefix: ConfigState.dataSource.prefix
        };

        $scope.apply = function(){
            ConfigState.defineDataSource($scope.config.prefix);
            $window.location.reload(true)
        };

        $scope.clearFavorites = function () {
            if (confirm('Você está certo de que deseja apagar todos os seus eventos favoritados?'))
                FavoriteEvents.clear();
        };
    })

    .controller('favoritesCtrl', ['$scope', 'MenuState', 'FavoriteEvents', function ($scope, MenuState, FavoriteEvents) {
        $scope.events = FavoriteEvents.favorites;
        $scope.favorite = FavoriteEvents.favorite;
    }])

    .controller('messagesCtrl', function ($scope) {

    })

    .controller('navCtrl', function ($scope, ConfigState, MenuState, $location, $timeout, $ionicLoading, $window) {

        $scope.show_filter_search_menu = true;
        $scope.show_share_buttom = false;

        $scope.openMenuMore = function(){
            $scope.showMenuMore = true;
        };

        $scope.closeMenuMore = function(){
            $scope.showMenuMore = false;
        };

        $scope.toggleMenuMore = function($event){
            $scope.showMenuMore = $scope.showMenuMore ? false : true;
            $event.stopPropagation();
        };

        angular.element($window).on('click', function(e){
            $scope.closeMenuMore();
            $scope.$apply();
        });

        function activeMenu (toState){
            switch(toState.name){
                case 'menu.spaces':
                    MenuState.activeMenu('spaces');
                    break;
                case 'menu.space':
                    MenuState.activeMenu('spaces');
                    break;

                case 'menu.agents':
                    MenuState.activeMenu('agents');
                    break;
                case 'menu.agent':
                    MenuState.activeMenu('agents');
                    break;

                case 'menu.projects':
                    MenuState.activeMenu('projects');
                    break;
                case 'menu.project':
                    MenuState.activeMenu('projects');
                    break;

                case 'menu.events':
                    MenuState.activeMenu('events');
                    break;
                case 'menu.event':
                    MenuState.activeMenu('events');
                    break;

                case 'menu.map':
                    MenuState.activeMenu('map');
                    break;

                case 'menu.favorites':
                    MenuState.activeMenu('favorites');
                    break;

                case 'menu.about':
                    MenuState.activeMenu('about');
                    break;

                case 'menu.config':
                    MenuState.activeMenu('about');
                    break;

            }
        }

        $scope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
            // var new_location_path = newVal.split('#')[1];
            // var old_location_path = oldVal.split('#')[1];

            activeMenu(toState);

            if (toState.name == 'menu.events') {
                $scope.show_filter_search_menu = true;
            } else {
                $scope.show_filter_search_menu = false;
            }
            $ionicLoading.show();
        });

        $scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) {
            activeMenu(toState);
            $ionicLoading.hide();
        });
    })
<|endoftext|>


<commit_before>'use strict';

import { StatsCollector } from './stats';

export default function(RED) {

  class DeviceStatsNode {
    constructor(n) {
      RED.nodes.createNode(this, n);
      this.name = n.name;
      this.mem = n.mem;
      this.nw = n.nw;
      this.load = n.load;
      this.hostname = n.hostname;
      this.useString = n.useString;
      this.collector = new StatsCollector(this);
      this.status({});

      this.on('input', msg => {
        clearTimeout(this.timeout);
        delete this.timeout;
        this.status({ fill: 'red', shape: 'dot', text: 'device-stats.status.heartbeat' });
        let opts = msg ? msg.payload : null;
        this.collector.collect(opts).then(stats => {
          if (this.useString || opts && opts.useString) {
            stats = JSON.stringify(stats);
          }
          this.send({ payload: stats });
          this.timeout = setTimeout(() => {
            if (this.timeout) {
              this.status({});
            }
          }, 750);
        }).catch(err => {
          RED.log.warn(RED._('device-stats.errors.unknown', { error: err }));
          this.status({});
        });
      });
    }
  }
  RED.nodes.registerType('DeviceStats', DeviceStatsNode);
}
<commit_msg>device stats not working with HTTP<commit_after>'use strict';

import { StatsCollector } from './stats';

export default function(RED) {

  class DeviceStatsNode {
    constructor(n) {
      RED.nodes.createNode(this, n);
      this.name = n.name;
      this.mem = n.mem;
      this.nw = n.nw;
      this.load = n.load;
      this.hostname = n.hostname;
      this.useString = n.useString;
      this.collector = new StatsCollector(this);
      this.status({});

      this.on('input', msg => {
        clearTimeout(this.timeout);
        delete this.timeout;
        this.status({ fill: 'red', shape: 'dot', text: 'device-stats.status.heartbeat' });
        let opts = msg ? msg.payload : null;
        this.collector.collect(opts).then(stats => {
          if (this.useString || opts && opts.useString) {
            stats = JSON.stringify(stats);
          }
          msg.payload = stats;
          this.send(msg);
          this.timeout = setTimeout(() => {
            if (this.timeout) {
              this.status({});
            }
          }, 750);
        }).catch(err => {
          RED.log.warn(RED._('device-stats.errors.unknown', { error: err }));
          this.status({});
        });
      });
    }
  }
  RED.nodes.registerType('DeviceStats', DeviceStatsNode);
}
<|endoftext|>


<commit_before>angular.module('app.controllers', [])

.controller('createUserCtrl', function($rootScope, $state, $scope, $ionicPopup, SettingsFactory, User) {

	$scope.user = {};

	$scope.register = function () {

		if(SettingsFactory.getCurrentPosition()) {
			$scope.user.lastPosition = {
        type: 'Point',
        coordinates: [
					SettingsFactory.getCurrentPosition().coords.latitude,
					SettingsFactory.getCurrentPosition().coords.longitude
				]
      };
		}

		User
			.register($scope.user)
			.then(function (response) {

				User.setAuthData(response.data)
 			   .then(function (data) {
 				   $state.go("menu.home");
 			   });
			},
			function (err) {
				var alertPopup = $ionicPopup.alert({
	          title: 'Register failed!',
	          template: 'Please check your data!
' + err
	      });
			}
		);
	};

})

.controller('loginCtrl', function($rootScope, $scope, $state, $ionicPopup, User, LocalStorage) {

	$scope.user = {};

	if (LocalStorage.getData('user')) {
		$state.go("menu.home");
	}

	$rootScope.$on('authLoggedIn', function () {
		$state.go("menu.home");
	});

	$scope.login = function () {

		User
		.login($scope.user)
		.then(function (response) {

			 User.setAuthData(response.data)
			   .then(function (data) {
				   $state.go("menu.home");
			   });
		},
		function () {
			var alertPopup = $ionicPopup.alert({
          title: 'Login failed!',
          template: 'Please check your credentials!'
      });
		});
	};

})

.controller('homeCtrl', function($rootScope, $scope, User, LocalStorage) {
	console.log('creating homeCtrl;....');
	$scope.user = LocalStorage.getData('user');
	$scope.donor = LocalStorage.getData('donor');
})

.controller('settingsCtrl', function($scope) {
})

.controller('mapOfDonorsCtrl', function($scope, $ionicPlatform, $state, $cordovaGeolocation, LocalStorage, SettingsFactory, DonorsFactory, GoogleMaps) {

		$scope.loadingMap = true;

		console.log("||||||||||| REQUESTING GOOGLE MAPS INIT ||||||||||||");
		GoogleMaps.init();

		$scope.$on('$GoogleMapsReady', function () {
			$scope.loadingMap = false;
			console.log("||||||||||| RECEIVED GOOGLE MAPS READY ||||||||||||");
			loadDonors();
		});

		$scope.$on('$GoogleMapsError', function () {
			console.log("||||||||||| RECEIVED GOOGLE MAPS ERROR ||||||||||||");

		});

		function loadDonors() {

			DonorsFactory
			.getNear()
			.query({
				donorId: LocalStorage.getData('user').user._id,
				distance: SettingsFactory.getDistance()
			})
			.$promise
			.then(function (donors) {

				var markers = donors.map(function (donor) {

					var donorMarker = new google.maps.Marker({
						position: new google.maps.LatLng(donor.lastPosition.coordinates[0], donor.lastPosition.coordinates[1]),
						title: donor.name,
						label: donor.name,
						image: 'img/7H1FqEQguI8OP5NNHqCQ_10299136_650394668362881_7047276451530079508_n.jpg',
						animation: google.maps.Animation.DROP
					});

					donorMarker.addListener('click', function () {
						// map.setCenter(donorMarker.getPosition());
						$state.go('menu.userDetail', {
							"donorId" : donor._id
						})
					});

					return donorMarker;
				});

				GoogleMaps.addMarkers(markers);

			});

		};
})

.controller('userDetailCtrl', function($scope, donorId, DonorsFactory) {

	DonorsFactory
	.getDonors()
	.get({'donorId': donorId})
	.$promise
	.then(function(donor) {
			$scope.donor = donor;
			$scope.enableToDonate = true;
	});
})

.controller('messagesCtrl', function($scope) {
})
<commit_msg>Removed  event to login and register<commit_after>angular.module('app.controllers', [])

.controller('createUserCtrl', function($rootScope, $state, $scope, $ionicPopup, SettingsFactory, User) {

	$scope.user = {};

	$scope.register = function () {

		if(SettingsFactory.getCurrentPosition()) {
			$scope.user.lastPosition = {
        type: 'Point',
        coordinates: [
					SettingsFactory.getCurrentPosition().coords.latitude,
					SettingsFactory.getCurrentPosition().coords.longitude
				]
      };
		}

		User
			.register($scope.user)
			.then(function (response) {

				User.setAuthData(response.data)
 			   .then(function (data) {
 				   $state.go("menu.home");
 			   });
			},
			function (err) {
				var alertPopup = $ionicPopup.alert({
	          title: 'Register failed!',
	          template: 'Please check your data!
' + err
	      });
			}
		);
	};

})

.controller('loginCtrl', function($rootScope, $scope, $state, $ionicPopup, User, LocalStorage) {

	$scope.user = {};

	if (LocalStorage.getData('user')) {
		$state.go("menu.home");
	}

	$scope.login = function () {

		User
		.login($scope.user)
		.then(function (response) {

			 User.setAuthData(response.data)
			   .then(function (data) {
				   $state.go("menu.home");
			   });
		},
		function () {
			var alertPopup = $ionicPopup.alert({
          title: 'Login failed!',
          template: 'Please check your credentials!'
      });
		});
	};

})

.controller('homeCtrl', function($rootScope, $scope, User, LocalStorage) {
	console.log('creating homeCtrl;....');
	$scope.user = LocalStorage.getData('user');
	$scope.donor = LocalStorage.getData('donor');
})

.controller('settingsCtrl', function($scope) {
})

.controller('mapOfDonorsCtrl', function($scope, $ionicPlatform, $state, $cordovaGeolocation, LocalStorage, SettingsFactory, DonorsFactory, GoogleMaps) {

		$scope.loadingMap = true;

		console.log("||||||||||| REQUESTING GOOGLE MAPS INIT ||||||||||||");
		GoogleMaps.init();

		$scope.$on('$GoogleMapsReady', function () {
			$scope.loadingMap = false;
			console.log("||||||||||| RECEIVED GOOGLE MAPS READY ||||||||||||");
			loadDonors();
		});

		$scope.$on('$GoogleMapsError', function () {
			console.log("||||||||||| RECEIVED GOOGLE MAPS ERROR ||||||||||||");

		});

		function loadDonors() {

			DonorsFactory
			.getNear()
			.query({
				donorId: LocalStorage.getData('user').user._id,
				distance: SettingsFactory.getDistance()
			})
			.$promise
			.then(function (donors) {

				var markers = donors.map(function (donor) {

					var donorMarker = new google.maps.Marker({
						position: new google.maps.LatLng(donor.lastPosition.coordinates[0], donor.lastPosition.coordinates[1]),
						title: donor.name,
						label: donor.name,
						image: 'img/7H1FqEQguI8OP5NNHqCQ_10299136_650394668362881_7047276451530079508_n.jpg',
						animation: google.maps.Animation.DROP
					});

					donorMarker.addListener('click', function () {
						// map.setCenter(donorMarker.getPosition());
						$state.go('menu.userDetail', {
							"donorId" : donor._id
						})
					});

					return donorMarker;
				});

				GoogleMaps.addMarkers(markers);

			});

		};
})

.controller('userDetailCtrl', function($scope, donorId, DonorsFactory) {

	DonorsFactory
	.getDonors()
	.get({'donorId': donorId})
	.$promise
	.then(function(donor) {
			$scope.donor = donor;
			$scope.enableToDonate = true;
	});
})

.controller('messagesCtrl', function($scope) {
})
<|endoftext|>


<commit_before>angular.module('registry.controllers', [])

.controller('MainController', function($scope, $location, Search, API){
    $scope.search = function(){
        if(this.data.search !== ""){
            Search.setValue(this.data.search);
            $location.path("/registry");
        }
    };

    $scope.signin = function(page){
        API.signin(page);
    };
})

.controller('MyStackController', function($scope, $rootScope, API, Search){
    API.getUser().success(function(data, status, headers, config){
         $rootScope.setUser(data.username);
         $scope.user = $rootScope.getUser();
    }).error(function(data, status, headers, config){
        $scope.err = true;
    });

     API.getUserFiles().success(function(data, status, headers, config){
         $scope.files = data;
         $scope.loaded = true;
     }).error(function(data, status, headers, config){
         $scope.err = true;
         $scope.loaded = true;
     });

     $scope.showModal = false;
     $scope.toggleModal = function(){
         $scope.showModal = !$scope.showModal;
     };

     $scope.generateEmbed = function(id){
         API.getFileWithId(id).success(function(data, status, headers, config){
             $scope.embedScript = '' +
                                 '';
         }).error(function(data, status, headers, config){
             $scope.embedScript = 'Unable to generate the embed script. Please try again.';
         });
     };

     $scope.signin = function(page){
         API.signin(page);
     };

    $scope.searchFile = function(){
        var term = this.data.search;
        API.searchFile(term).success(function(data, status, headers, config){
            $scope.results = data;
        }).error(function(data, status, headers, config){
            $scope.err = true;
        });
    };
})

.controller('FavoriteController', function($scope, $rootScope, API, Search){

})

.controller('RegistryController', function($scope, $rootScope, $window, API, Search){
    $scope.favoriteList = [];

    API.getUser().success(function(data, status, headers, config){
         $rootScope.setUser(data.username);
         $scope.user = $rootScope.getUser();

         API.checkFav().success(function(data, status, header, config){
            $scope.favoriteList = data;
        }).error(function(data, status, headers, config){
            console.log(data);
        });

    }).error(function(data, status, headers, config){
        $scope.err = true;
    });

    $scope.showModal = false;
    $scope.toggleModal = function(){
        $scope.showModal = !$scope.showModal;
    };

    $scope.generateEmbed = function(id){
        API.getFileWithId(id).success(function(data, status, headers, config){
            $scope.embedScript = '' +
                                '';
        }).error(function(data, status, headers, config){
            $scope.embedScript = 'Unable to generate the embed script. Please try again.';
        });
    };

    $scope.signin = function(page){
        API.signin(page);
    };

    $scope.deploy = function(id){
        window.location.href = ('/api/v1/deploy/'+id);
    };

    API.getFiles().success(function(data, status, headers, config){
        $scope.files = data;
        $scope.loaded = true;
    }).error(function(data, status, headers, config){
        $scope.err = true;
    });

    $scope.searchFile = function(){
        var term = this.data.search;
        API.searchFile(term).success(function(data, status, headers, config){
            $scope.results = data;
        }).error(function(data, status, headers, config){
            $scope.err = true;
        });
    };

    $scope.checkSearch = function(){
        if(Search.getValue().search !== null){
            $scope.data = Search.getValue();
            $scope.searchFile(Search.getValue());
        }
    };

    $scope.toggleStatus = function(file) {
        $scope.favoriteList.push(file._id);
        API.favFile(file._id).success(function(data, status, headers, config){

        }).error(function(data, status, headers, config){
            $scope.err = true;
        });
    };
    $scope.isSelected = function(file) {
        return $scope.favoriteList.indexOf(file._id) > -1;
    };
})

.controller('RegistryDetailsController', function($scope, $rootScope, $window, $routeParams, API){

    $scope.favoriteList = [];
    $scope.user = $rootScope.getUser();

    API.getFileWithId($routeParams.registryId).success(function(data, status, headers, config){
        $scope.data = data;
        API.getYAMLFile(data._id, data.projectName, data.path).success(function(yamlData, status, headers, config){
            $scope.composeFile = yamlData;
            $scope.loaded = true;
        }).error(function(data, status, headers, config){
            $scope.composeFile = "Unable to fetch tutum.yml from Github repository. Please select a repository that contains a tutum.yml or a docker-compose.yml file";
            $scope.loaded = true;
        });
        API.checkFav().success(function(data, status, header, config){
           $scope.favoriteList = data;
        }).error(function(data, status, headers, config){

        });
    }).error(function(data, status, headers, config){
        window.location.href = ("/404");
    });

    $scope.showModal = false;
    $scope.toggleModal = function(){
        $scope.showModal = !$scope.showModal;
    };

    $scope.generateEmbed = function(id){
        API.getFileWithId(id).success(function(data, status, headers, config){
            $scope.embedScript = '

' +
                                '';
        }).error(function(data, status, headers, config){
            $scope.embedScript = 'Unable to generate the embed script. Please try again.';
        });
    };

    $scope.signin = function(page){
        API.signin(page);
    };

    $scope.deploy = function(id){
        window.location.href = ('/api/v1/deploy/'+id);
    };

    $scope.toggleStatus = function(file) {
        $scope.favoriteList.push(file._id);
        API.favFile(file._id).success(function(data, status, headers, config){

        }).error(function(data, status, headers, config){
            $scope.err = true;
        });
    };
    $scope.isSelected = function(file) {
        return $scope.favoriteList.indexOf(file._id) > -1;
    };

    $scope.deleteStackfile = function(id){
        API.deleteStackfile(id).success(function(data, status, headers, config){
            $window.location.href = ("/registry");
        }).error(function(data, status, headers, config){
            $scope.err = true;
        });
    };

})

.controller('CreateController', function($scope, $rootScope, $window, API){

    var orgs = [];

    API.getUser().success(function(data, status, headers, config){
         $rootScope.setUser(data.username);
         $scope.user = $rootScope.getUser();
    }).error(function(data, status, headers, config){
        $scope.err = true;
    });

    $scope.signin = function(page){
        API.signin(page);
    };

    $scope.getRepos = function(){
        var repos = [];
        $scope.repos = [];
        var branches = [];
        $scope.branches = [];
        $scope.data.path = "";
        $scope.data.composefile = "";

        API.getUserRepos($scope.data.orgname).success(function(data, status, headers, config){
            angular.forEach(data, function(value, key){
                repos.push(value.name);
            });
            $scope.repos=repos;
        }).error(function(data, status, headers, config){
            $scope.err = true;
        });
    };

    $scope.getOrgs = function(){
        API.getUserOrgs().success(function(data, status, headers, config){
            angular.forEach(data, function(value, key){
                orgs.push(value.login);
            });
            orgs.push($rootScope.getUser());
            $scope.orgs=orgs;
        }).error(function(data, status, headers, config){
            $scope.err = true;
        });
    };

    $scope.getBranches = function(){
        var branches = [];
        $scope.branches = [];
        $scope.data.path = "";
        $scope.data.composefile = "";
        API.getRepoBranches($scope.data.orgname, $scope.data.reponame).success(function(data, status, headers, config){
            angular.forEach(data, function(value, key){
                branches.push(value);
            });
            $scope.branches=branches;
        }).error(function(data, status, headers, config){
            $scope.err = true;
        });
    };

    $scope.getComposeFile = function(orgname, name, branch, path){
        $scope.stackfile = "";
        API.getUserReposInfo(orgname, name, branch, path).success(function(data, status, headers, config){
            if(data === "File not found"){
                $scope.stackfile = "Unable to fetch tutum.yml from Github repository. Please select a repository that contains a tutum.yml or a docker-compose.yml file";
            } else {
                $scope.stackfile = data;
            }
        }).error(function(data, status, headers, config){
            console.log(data);
            $scope.err = true;
        });
    };

    $scope.createNew = function(){
        var title = this.data.title;
        var stackfile = jsyaml.load($scope.stackfile);
        var branch = this.data.branch;
        var path = this.data.path;
        var projectName = this.data.reponame;
        var organizationName = this.data.orgname;

        var form = {
            title: title.replace(/\(\(/g,'{{').replace(/\)\)/, '}}').replace(/'/g,'\''),
            stackfile: stackfile,
            branch: branch,
            path: path,
            name: projectName,
            orgname: organizationName
        };

        API.saveFile(form).success(function(data, status, headers, config){
            $window.location.href = ('/registry');
        }).error(function(data, status, header, config){
            window.location.href = ("/404");
        });
    };
});
<commit_msg>new embed script<commit_after>angular.module('registry.controllers', [])

.controller('MainController', function($scope, $location, Search, API){
    $scope.search = function(){
        if(this.data.search !== ""){
            Search.setValue(this.data.search);
            $location.path("/registry");
        }
    };

    $scope.signin = function(page){
        API.signin(page);
    };
})

.controller('MyStackController', function($scope, $rootScope, API, Search){
    API.getUser().success(function(data, status, headers, config){
         $rootScope.setUser(data.username);
         $scope.user = $rootScope.getUser();
    }).error(function(data, status, headers, config){
        $scope.err = true;
    });

     API.getUserFiles().success(function(data, status, headers, config){
         $scope.files = data;
         $scope.loaded = true;
     }).error(function(data, status, headers, config){
         $scope.err = true;
         $scope.loaded = true;
     });

     $scope.showModal = false;
     $scope.toggleModal = function(){
         $scope.showModal = !$scope.showModal;
     };

     $scope.generateEmbed = function(id){
         API.getFileWithId(id).success(function(data, status, headers, config){
             $scope.embedScript = '

';
         }).error(function(data, status, headers, config){
             $scope.embedScript = 'Unable to generate the embed script. Please try again.';
         });
     };

     $scope.signin = function(page){
         API.signin(page);
     };

    $scope.searchFile = function(){
        var term = this.data.search;
        API.searchFile(term).success(function(data, status, headers, config){
            $scope.results = data;
        }).error(function(data, status, headers, config){
            $scope.err = true;
        });
    };
})

.controller('FavoriteController', function($scope, $rootScope, API, Search){

})

.controller('RegistryController', function($scope, $rootScope, $window, API, Search){
    $scope.favoriteList = [];

    API.getUser().success(function(data, status, headers, config){
         $rootScope.setUser(data.username);
         $scope.user = $rootScope.getUser();

         API.checkFav().success(function(data, status, header, config){
            $scope.favoriteList = data;
        }).error(function(data, status, headers, config){
            console.log(data);
        });

    }).error(function(data, status, headers, config){
        $scope.err = true;
    });

    $scope.showModal = false;
    $scope.toggleModal = function(){
        $scope.showModal = !$scope.showModal;
    };

    $scope.generateEmbed = function(id){
        API.getFileWithId(id).success(function(data, status, headers, config){
            $scope.embedScript = '

';
        }).error(function(data, status, headers, config){
            $scope.embedScript = 'Unable to generate the embed script. Please try again.';
        });
    };

    $scope.signin = function(page){
        API.signin(page);
    };

    $scope.deploy = function(id){
        window.location.href = ('/api/v1/deploy/'+id);
    };

    API.getFiles().success(function(data, status, headers, config){
        $scope.files = data;
        $scope.loaded = true;
    }).error(function(data, status, headers, config){
        $scope.err = true;
    });

    $scope.searchFile = function(){
        var term = this.data.search;
        API.searchFile(term).success(function(data, status, headers, config){
            $scope.results = data;
        }).error(function(data, status, headers, config){
            $scope.err = true;
        });
    };

    $scope.checkSearch = function(){
        if(Search.getValue().search !== null){
            $scope.data = Search.getValue();
            $scope.searchFile(Search.getValue());
        }
    };

    $scope.toggleStatus = function(file) {
        $scope.favoriteList.push(file._id);
        API.favFile(file._id).success(function(data, status, headers, config){

        }).error(function(data, status, headers, config){
            $scope.err = true;
        });
    };
    $scope.isSelected = function(file) {
        return $scope.favoriteList.indexOf(file._id) > -1;
    };
})

.controller('RegistryDetailsController', function($scope, $rootScope, $window, $routeParams, API){

    $scope.favoriteList = [];
    $scope.user = $rootScope.getUser();

    API.getFileWithId($routeParams.registryId).success(function(data, status, headers, config){
        $scope.data = data;
        API.getYAMLFile(data._id, data.projectName, data.path).success(function(yamlData, status, headers, config){
            $scope.composeFile = yamlData;
            $scope.loaded = true;
        }).error(function(data, status, headers, config){
            $scope.composeFile = "Unable to fetch tutum.yml from Github repository. Please select a repository that contains a tutum.yml or a docker-compose.yml file";
            $scope.loaded = true;
        });
        API.checkFav().success(function(data, status, header, config){
           $scope.favoriteList = data;
        }).error(function(data, status, headers, config){

        });
    }).error(function(data, status, headers, config){
        window.location.href = ("/404");
    });

    $scope.showModal = false;
    $scope.toggleModal = function(){
        $scope.showModal = !$scope.showModal;
    };

    $scope.generateEmbed = function(id){
        API.getFileWithId(id).success(function(data, status, headers, config){
            $scope.embedScript = '

';
        }).error(function(data, status, headers, config){
            $scope.embedScript = 'Unable to generate the embed script. Please try again.';
        });
    };

    $scope.signin = function(page){
        API.signin(page);
    };

    $scope.deploy = function(id){
        window.location.href = ('/api/v1/deploy/'+id);
    };

    $scope.toggleStatus = function(file) {
        $scope.favoriteList.push(file._id);
        API.favFile(file._id).success(function(data, status, headers, config){

        }).error(function(data, status, headers, config){
            $scope.err = true;
        });
    };
    $scope.isSelected = function(file) {
        return $scope.favoriteList.indexOf(file._id) > -1;
    };

    $scope.deleteStackfile = function(id){
        API.deleteStackfile(id).success(function(data, status, headers, config){
            $window.location.href = ("/registry");
        }).error(function(data, status, headers, config){
            $scope.err = true;
        });
    };

})

.controller('CreateController', function($scope, $rootScope, $window, API){

    var orgs = [];

    API.getUser().success(function(data, status, headers, config){
         $rootScope.setUser(data.username);
         $scope.user = $rootScope.getUser();
    }).error(function(data, status, headers, config){
        $scope.err = true;
    });

    $scope.signin = function(page){
        API.signin(page);
    };

    $scope.getRepos = function(){
        var repos = [];
        $scope.repos = [];
        var branches = [];
        $scope.branches = [];
        $scope.data.path = "";
        $scope.data.composefile = "";

        API.getUserRepos($scope.data.orgname).success(function(data, status, headers, config){
            angular.forEach(data, function(value, key){
                repos.push(value.name);
            });
            $scope.repos=repos;
        }).error(function(data, status, headers, config){
            $scope.err = true;
        });
    };

    $scope.getOrgs = function(){
        API.getUserOrgs().success(function(data, status, headers, config){
            angular.forEach(data, function(value, key){
                orgs.push(value.login);
            });
            orgs.push($rootScope.getUser());
            $scope.orgs=orgs;
        }).error(function(data, status, headers, config){
            $scope.err = true;
        });
    };

    $scope.getBranches = function(){
        var branches = [];
        $scope.branches = [];
        $scope.data.path = "";
        $scope.data.composefile = "";
        API.getRepoBranches($scope.data.orgname, $scope.data.reponame).success(function(data, status, headers, config){
            angular.forEach(data, function(value, key){
                branches.push(value);
            });
            $scope.branches=branches;
        }).error(function(data, status, headers, config){
            $scope.err = true;
        });
    };

    $scope.getComposeFile = function(orgname, name, branch, path){
        $scope.stackfile = "";
        API.getUserReposInfo(orgname, name, branch, path).success(function(data, status, headers, config){
            if(data === "File not found"){
                $scope.stackfile = "Unable to fetch tutum.yml from Github repository. Please select a repository that contains a tutum.yml or a docker-compose.yml file";
            } else {
                $scope.stackfile = data;
            }
        }).error(function(data, status, headers, config){
            console.log(data);
            $scope.err = true;
        });
    };

    $scope.createNew = function(){
        var title = this.data.title;
        var stackfile = jsyaml.load($scope.stackfile);
        var branch = this.data.branch;
        var path = this.data.path;
        var projectName = this.data.reponame;
        var organizationName = this.data.orgname;

        var form = {
            title: title.replace(/\(\(/g,'{{').replace(/\)\)/, '}}').replace(/'/g,'\''),
            stackfile: stackfile,
            branch: branch,
            path: path,
            name: projectName,
            orgname: organizationName
        };

        API.saveFile(form).success(function(data, status, headers, config){
            $window.location.href = ('/registry');
        }).error(function(data, status, header, config){
            window.location.href = ("/404");
        });
    };
});
<|endoftext|>


<commit_before>/*
 * This function probes Okapi to discover what versions of what
 * interfaces are supported by the services that it is proxying
 * for. This information can be used to configure the UI at run-time
 * (e.g. not attempting to fetch loan information for a
 * non-circulating library that doesn't provide the circ interface)
 */
import 'isomorphic-fetch';

function discoverInterfaces(okapiUrl, store, entry) {
  fetch(`${okapiUrl}/_/proxy/modules/${entry.id}`)
    .catch((reason) => {
      store.dispatch({ type: 'DISCOVERY_FAILURE', message: reason });
    }).then((response) => {
      if (response.status >= 400) {
        store.dispatch({ type: 'DISCOVERY_FAILURE', code: response.status });
      } else {
        response.json().then((json) => {
          store.dispatch({ type: 'DISCOVERY_INTERFACES', data: json });
        });
      }
    });
}

export function discoverServices(okapiUrl, store) {
  fetch(`${okapiUrl}/_/version`)
    .catch((reason) => {
      store.dispatch({ type: 'DISCOVERY_FAILURE', message: reason });
    }).then((response) => {
      if (response.status >= 400) {
        store.dispatch({ type: 'DISCOVERY_FAILURE', code: response.status });
      } else {
        response.text().then((text) => {
          store.dispatch({ type: 'DISCOVERY_OKAPI', version: text });
        });
      }
    });

  fetch(`${okapiUrl}/_/proxy/modules`)
    .catch((reason) => {
      store.dispatch({ type: 'DISCOVERY_FAILURE', message: reason });
    }).then((response) => {
      if (response.status >= 400) {
        store.dispatch({ type: 'DISCOVERY_FAILURE', code: response.status });
      } else {
        response.json().then((json) => {
          store.dispatch({ type: 'DISCOVERY_SUCCESS', data: json });
          for (const entry of json) {
            discoverInterfaces(okapiUrl, store, entry);
          }
        });
      }
    });
}

export function discoveryReducer(state = {}, action) {
  switch (action.type) {
    case 'DISCOVERY_OKAPI':
      return Object.assign({}, state, { okapi: action.version });
    case 'DISCOVERY_FAILURE':
      return Object.assign({}, state, { failure: action });
    case 'DISCOVERY_SUCCESS': {
      const modules = {};
      for (const entry of action.data) {
        modules[entry.id] = entry.name;
      }
      return Object.assign({}, state, { modules });
    }
    case 'DISCOVERY_INTERFACES': {
      const interfaces = {};
      for (const entry of action.data.provides) {
        interfaces[entry.id] = entry.version;
      }
      return Object.assign({}, state, {
        interfaces: Object.assign(state.interfaces || {}, interfaces),
      });
    }
    default:
      return state;
  }
}

export function isVersionCompatible(got, wanted) {
  const [gmajor, gminor] = got.split('.');
  const [wmajor, wminor] = wanted.split('.');
  return wmajor === gmajor && parseInt(wminor, 10) >= parseInt(gminor, 10);
}
<commit_msg>Avoid error when from no "provides" section in descrptor<commit_after>/*
 * This function probes Okapi to discover what versions of what
 * interfaces are supported by the services that it is proxying
 * for. This information can be used to configure the UI at run-time
 * (e.g. not attempting to fetch loan information for a
 * non-circulating library that doesn't provide the circ interface)
 */
import 'isomorphic-fetch';

function discoverInterfaces(okapiUrl, store, entry) {
  fetch(`${okapiUrl}/_/proxy/modules/${entry.id}`)
    .catch((reason) => {
      store.dispatch({ type: 'DISCOVERY_FAILURE', message: reason });
    }).then((response) => {
      if (response.status >= 400) {
        store.dispatch({ type: 'DISCOVERY_FAILURE', code: response.status });
      } else {
        response.json().then((json) => {
          store.dispatch({ type: 'DISCOVERY_INTERFACES', data: json });
        });
      }
    });
}

export function discoverServices(okapiUrl, store) {
  fetch(`${okapiUrl}/_/version`)
    .catch((reason) => {
      store.dispatch({ type: 'DISCOVERY_FAILURE', message: reason });
    }).then((response) => {
      if (response.status >= 400) {
        store.dispatch({ type: 'DISCOVERY_FAILURE', code: response.status });
      } else {
        response.text().then((text) => {
          store.dispatch({ type: 'DISCOVERY_OKAPI', version: text });
        });
      }
    });

  fetch(`${okapiUrl}/_/proxy/modules`)
    .catch((reason) => {
      store.dispatch({ type: 'DISCOVERY_FAILURE', message: reason });
    }).then((response) => {
      if (response.status >= 400) {
        store.dispatch({ type: 'DISCOVERY_FAILURE', code: response.status });
      } else {
        response.json().then((json) => {
          store.dispatch({ type: 'DISCOVERY_SUCCESS', data: json });
          for (const entry of json) {
            discoverInterfaces(okapiUrl, store, entry);
          }
        });
      }
    });
}

export function discoveryReducer(state = {}, action) {
  switch (action.type) {
    case 'DISCOVERY_OKAPI':
      return Object.assign({}, state, { okapi: action.version });
    case 'DISCOVERY_FAILURE':
      return Object.assign({}, state, { failure: action });
    case 'DISCOVERY_SUCCESS': {
      const modules = {};
      for (const entry of action.data) {
        modules[entry.id] = entry.name;
      }
      return Object.assign({}, state, { modules });
    }
    case 'DISCOVERY_INTERFACES': {
      const interfaces = {};
      for (const entry of action.data.provides || []) {
        interfaces[entry.id] = entry.version;
      }
      return Object.assign({}, state, {
        interfaces: Object.assign(state.interfaces || {}, interfaces),
      });
    }
    default:
      return state;
  }
}

export function isVersionCompatible(got, wanted) {
  const [gmajor, gminor] = got.split('.');
  const [wmajor, wminor] = wanted.split('.');
  return wmajor === gmajor && parseInt(wminor, 10) >= parseInt(gminor, 10);
}
<|endoftext|>


<commit_before>var util = require("util");

var shlog = require(global.gBaseDir + "/src/shlog.js");
var ShObject = require(global.gBaseDir + "/src/do/shobject.js");

function MessageBank() {
  ShObject.call(this);

  this._keyType = "kMessageBank";
  this._keyFormat = "mb:%s";
  this._data = {
    bank: []
  };
  this._max = 10;
}

util.inherits(MessageBank, ShObject);
module.exports = MessageBank;

MessageBank.prototype.add = function (msg) {
  shlog.info("add message:", msg.from, msg.message);

  this._data.bank.push(msg);
  if (this._data.bank.length > this._max) {
    this._data.bank.shift();
  }
};<commit_msg>always lock the messagebank objects;<commit_after>var util = require("util");

var shlog = require(global.gBaseDir + "/src/shlog.js");
var ShObject = require(global.gBaseDir + "/src/do/shobject.js");

function MessageBank() {
  ShObject.call(this);

  this._keyType = "kMessageBank";
  this._keyFormat = "mb:%s";
  this._data = {
    bank: []
  };
  this._max = 10;
  this.alwaysLock = true;
}

util.inherits(MessageBank, ShObject);
module.exports = MessageBank;

MessageBank.prototype.add = function (msg) {
  shlog.info("add message:", msg.from, msg.message);

  this._data.bank.push(msg);
  if (this._data.bank.length > this._max) {
    this._data.bank.shift();
  }
};<|endoftext|>


<commit_before>import jsan from 'jsan';
import throttle from 'lodash/throttle';
import seralizeImmutable from 'remotedev-serialize/immutable/serialize';
import { getLocalFilter, isFiltered } from './filters';
import importState from './importState';
import generateId from './generateInstanceId';

const listeners = {};
export const source = '@devtools-page';

function tryCatchStringify(obj) {
  try {
    return JSON.stringify(obj);
  } catch (err) {
    /* eslint-disable no-console */
    if (process.env.NODE_ENV !== 'production') console.log('Failed to stringify', err);
    /* eslint-enable no-console */
    return jsan.stringify(obj, null, null, { circular: '[CIRCULAR]' });
  }
}

function stringify(obj, serialize) {
  if (typeof serialize === 'undefined') {
    return tryCatchStringify(obj);
  }
  return jsan.stringify(obj, serialize.replacer, null, serialize.options);
}

export function getSeralizeParameter(config, param) {
  const serialize = config.serialize;
  if (serialize) {
    if (serialize === true) return { options: true };
    if (serialize.immutable) {
      return {
        replacer: seralizeImmutable(serialize.immutable, serialize.refs).replacer,
        options: serialize.options || true
      };
    }
    if (!serialize.replacer) return { options: serialize.options };
    return { replacer: serialize.replacer, options: serialize.options || true };
  }

  const value = config[param];
  if (typeof value === 'undefined') return undefined;
  console.warn(`\`${param}\` parameter for Redux DevTools Extension is deprecated. Use \`serialize\` parameter instead: https://github.com/zalmoxisus/redux-devtools-extension/releases/tag/v2.12.1`); // eslint-disable-line

  if (typeof serializeState === 'boolean') return { options: value };
  if (typeof serializeState === 'function') return { replacer: value };
  return value;
}

function post(message) {
  window.postMessage(message, '*');
}

function amendActionType(action) {
  if (typeof action === 'string') return { action: { type: action }, timestamp: Date.now() };
  if (!action.type) return { action: { type: 'update' }, timestamp: Date.now() };
  if (action.action) return action;
  return { action, timestamp: Date.now() };
}

export function toContentScript(message, serializeState, serializeAction) {
  if (message.type === 'ACTION') {
    message.action = stringify(message.action, serializeAction);
    message.payload = stringify(message.payload, serializeState);
  } else if (message.type === 'STATE' || message.type === 'PARTIAL_STATE') {
    const { actionsById, computedStates, committedState, ...rest } = message.payload;
    message.payload = rest;
    message.actionsById = stringify(actionsById, serializeAction);
    message.computedStates = stringify(computedStates, serializeState);
    message.committedState = typeof committedState !== 'undefined';
  } else if (message.type === 'EXPORT') {
    message.payload = stringify(message.payload, serializeAction);
    if (typeof message.committedState !== 'undefined') {
      message.committedState = stringify(message.committedState, serializeState);
    }
  }
  post(message);
}

export function sendMessage(action, state, config, instanceId, name) {
  let amendedAction = action;
  if (typeof config !== 'object') {
    // Legacy: sending actions not from connected part
    config = {}; // eslint-disable-line no-param-reassign
    if (action) amendedAction = amendActionType(action);
  }
  const message = {
    type: action ? 'ACTION' : 'STATE',
    action: amendedAction,
    payload: state,
    maxAge: config.maxAge,
    source,
    name: config.name || name,
    instanceId: config.instanceId || instanceId || 1
  };
  toContentScript(message, config.serialize, config.serialize);
}

function handleMessages(event) {
  if (process.env.BABEL_ENV !== 'test' && (!event || event.source !== window)) return;
  const message = event.data;
  if (!message || message.source !== '@devtools-extension') return;
  Object.keys(listeners).forEach(id => {
    if (message.id && id !== message.id) return;
    if (typeof listeners[id] === 'function') listeners[id](message);
    else listeners[id].forEach(fn => { fn(message); });
  });
}

export function setListener(onMessage, instanceId) {
  listeners[instanceId] = onMessage;
  window.addEventListener('message', handleMessages, false);
}

const liftListener = (listener, config) => message => {
  let data = {};
  if (message.type === 'IMPORT') {
    data.type = 'DISPATCH';
    data.payload = {
      type: 'IMPORT_STATE',
      ...importState(message.state, config)
    };
  } else {
    data = message;
  }
  listener(data);
};

export function disconnect() {
  window.removeEventListener('message', handleMessages);
  post({ type: 'DISCONNECT', source });
}

export function connect(preConfig) {
  const config = preConfig || {};
  const id = generateId(config.instanceId);
  if (!config.instanceId) config.instanceId = id;
  if (!config.name) config.name = document.title && id === 1 ? document.title : `Instance ${id}`;
  if (config.serialize) config.serialize = getSeralizeParameter(config);
  const latency = config.latency;
  const predicate = config.predicate;
  const localFilter = getLocalFilter(config);
  const autoPause = config.autoPause;
  let isPaused = autoPause;
  let delayedActions = [];
  let delayedStates = [];

  const rootListiner = action => {
    if (autoPause) {
      if (action.type === 'START') isPaused = false;
      else if (action.type === 'STOP') isPaused = true;
    }
    if (action.type === 'DISPATCH') {
      const payload = action.payload;
      if (payload.type === 'PAUSE_RECORDING') {
        isPaused = payload.status;
        toContentScript({
          type: 'LIFTED',
          liftedState: { isPaused },
          instanceId: id,
          source
        });
      }
    }
  };

  listeners[id] = [rootListiner];

  const subscribe = (listener) => {
    if (!listener) return undefined;
    const liftedListener = liftListener(listener, config);
    listeners[id].push(liftedListener);

    return function unsubscribe() {
      const index = listeners[id].indexOf(liftedListener);
      listeners[id].splice(index, 1);
    };
  };

  const unsubscribe = () => {
    delete listeners[id];
  };

  const sendDelayed = throttle(() => {
    sendMessage(delayedActions, delayedStates, config);
    delayedActions = [];
    delayedStates = [];
  }, latency);

  const send = (action, state) => {
    if (isPaused || isFiltered(action, localFilter) || predicate && !predicate(state, action)) {
      return;
    }

    let amendedAction = action;
    const amendedState = config.stateSanitizer ? config.stateSanitizer(state) : state;
    if (action) {
      if (config.getActionType) {
        amendedAction = config.getActionType(action);
        if (typeof amendedAction !== 'object') {
          amendedAction = { action: { type: amendedAction }, timestamp: Date.now() };
        }
      }
      else if (config.actionSanitizer) amendedAction = config.actionSanitizer(action);
      amendedAction = amendActionType(amendedAction);
      if (latency) {
        delayedActions.push(amendedAction);
        delayedStates.push(amendedState);
        sendDelayed();
        return;
      }
    }
    sendMessage(amendedAction, amendedState, config);
  };

  const init = (state, liftedData) => {
    const message = {
      type: 'INIT',
      payload: stringify(state, config),
      instanceId: id,
      source
    };
    if (liftedData && Array.isArray(liftedData)) { // Legacy
      message.action = stringify(liftedData);
      message.name = config.name;
    } else {
      if (liftedData) {
        message.liftedState = liftedData;
        if (liftedData.isPaused) isPaused = true;
      }
      message.libConfig = {
        name: config.name || document.title,
        features: config.features,
        serialize: !!config.serialize,
        type: config.type
      };
      // TODO: add actionCreators
    }
    post(message);
  };

  const error = (payload) => {
    post({ type: 'ERROR', payload, id, source });
  };

  window.addEventListener('message', handleMessages, false);

  post({ type: 'INIT_INSTANCE', instanceId: id, source });

  return {
    init,
    subscribe,
    unsubscribe,
    send,
    error
  };
}

export function updateStore(stores) {
  return function(newStore, instanceId) {
    /* eslint-disable no-console */
    console.warn('`devToolsExtension.updateStore` is deprecated, remove it and just use ' +
      '`__REDUX_DEVTOOLS_EXTENSION_COMPOSE__` instead of the extension\'s store enhancer: ' +
      'https://github.com/zalmoxisus/redux-devtools-extension#12-advanced-store-setup');
    /* eslint-enable no-console */
    const store = stores[instanceId || Object.keys(stores)[0]];
    // Mutate the store in order to keep the reference
    store.liftedStore = newStore.liftedStore;
    store.getState = newStore.getState;
    store.dispatch = newStore.dispatch;
  };
}

export function isInIframe() {
  try {
    return window.self !== window.top;
  } catch (e) {
    return true;
  }
}
<commit_msg>Attempt to fix `toISOString is not a function`<commit_after>import jsan from 'jsan';
import throttle from 'lodash/throttle';
import seralizeImmutable from 'remotedev-serialize/immutable/serialize';
import { getLocalFilter, isFiltered } from './filters';
import importState from './importState';
import generateId from './generateInstanceId';

const listeners = {};
export const source = '@devtools-page';

function tryCatchStringify(obj) {
  try {
    return JSON.stringify(obj);
  } catch (err) {
    /* eslint-disable no-console */
    if (process.env.NODE_ENV !== 'production') console.log('Failed to stringify', err);
    /* eslint-enable no-console */
    return jsan.stringify(obj, null, null, { circular: '[CIRCULAR]', date: true });
  }
}

function stringify(obj, serialize) {
  if (typeof serialize === 'undefined') {
    return tryCatchStringify(obj);
  }
  return jsan.stringify(obj, serialize.replacer, null, serialize.options);
}

export function getSeralizeParameter(config, param) {
  const serialize = config.serialize;
  if (serialize) {
    if (serialize === true) return { options: true };
    if (serialize.immutable) {
      return {
        replacer: seralizeImmutable(serialize.immutable, serialize.refs).replacer,
        options: serialize.options || true
      };
    }
    if (!serialize.replacer) return { options: serialize.options };
    return { replacer: serialize.replacer, options: serialize.options || true };
  }

  const value = config[param];
  if (typeof value === 'undefined') return undefined;
  console.warn(`\`${param}\` parameter for Redux DevTools Extension is deprecated. Use \`serialize\` parameter instead: https://github.com/zalmoxisus/redux-devtools-extension/releases/tag/v2.12.1`); // eslint-disable-line

  if (typeof serializeState === 'boolean') return { options: value };
  if (typeof serializeState === 'function') return { replacer: value };
  return value;
}

function post(message) {
  window.postMessage(message, '*');
}

function amendActionType(action) {
  if (typeof action === 'string') return { action: { type: action }, timestamp: Date.now() };
  if (!action.type) return { action: { type: 'update' }, timestamp: Date.now() };
  if (action.action) return action;
  return { action, timestamp: Date.now() };
}

export function toContentScript(message, serializeState, serializeAction) {
  if (message.type === 'ACTION') {
    message.action = stringify(message.action, serializeAction);
    message.payload = stringify(message.payload, serializeState);
  } else if (message.type === 'STATE' || message.type === 'PARTIAL_STATE') {
    const { actionsById, computedStates, committedState, ...rest } = message.payload;
    message.payload = rest;
    message.actionsById = stringify(actionsById, serializeAction);
    message.computedStates = stringify(computedStates, serializeState);
    message.committedState = typeof committedState !== 'undefined';
  } else if (message.type === 'EXPORT') {
    message.payload = stringify(message.payload, serializeAction);
    if (typeof message.committedState !== 'undefined') {
      message.committedState = stringify(message.committedState, serializeState);
    }
  }
  post(message);
}

export function sendMessage(action, state, config, instanceId, name) {
  let amendedAction = action;
  if (typeof config !== 'object') {
    // Legacy: sending actions not from connected part
    config = {}; // eslint-disable-line no-param-reassign
    if (action) amendedAction = amendActionType(action);
  }
  const message = {
    type: action ? 'ACTION' : 'STATE',
    action: amendedAction,
    payload: state,
    maxAge: config.maxAge,
    source,
    name: config.name || name,
    instanceId: config.instanceId || instanceId || 1
  };
  toContentScript(message, config.serialize, config.serialize);
}

function handleMessages(event) {
  if (process.env.BABEL_ENV !== 'test' && (!event || event.source !== window)) return;
  const message = event.data;
  if (!message || message.source !== '@devtools-extension') return;
  Object.keys(listeners).forEach(id => {
    if (message.id && id !== message.id) return;
    if (typeof listeners[id] === 'function') listeners[id](message);
    else listeners[id].forEach(fn => { fn(message); });
  });
}

export function setListener(onMessage, instanceId) {
  listeners[instanceId] = onMessage;
  window.addEventListener('message', handleMessages, false);
}

const liftListener = (listener, config) => message => {
  let data = {};
  if (message.type === 'IMPORT') {
    data.type = 'DISPATCH';
    data.payload = {
      type: 'IMPORT_STATE',
      ...importState(message.state, config)
    };
  } else {
    data = message;
  }
  listener(data);
};

export function disconnect() {
  window.removeEventListener('message', handleMessages);
  post({ type: 'DISCONNECT', source });
}

export function connect(preConfig) {
  const config = preConfig || {};
  const id = generateId(config.instanceId);
  if (!config.instanceId) config.instanceId = id;
  if (!config.name) config.name = document.title && id === 1 ? document.title : `Instance ${id}`;
  if (config.serialize) config.serialize = getSeralizeParameter(config);
  const latency = config.latency;
  const predicate = config.predicate;
  const localFilter = getLocalFilter(config);
  const autoPause = config.autoPause;
  let isPaused = autoPause;
  let delayedActions = [];
  let delayedStates = [];

  const rootListiner = action => {
    if (autoPause) {
      if (action.type === 'START') isPaused = false;
      else if (action.type === 'STOP') isPaused = true;
    }
    if (action.type === 'DISPATCH') {
      const payload = action.payload;
      if (payload.type === 'PAUSE_RECORDING') {
        isPaused = payload.status;
        toContentScript({
          type: 'LIFTED',
          liftedState: { isPaused },
          instanceId: id,
          source
        });
      }
    }
  };

  listeners[id] = [rootListiner];

  const subscribe = (listener) => {
    if (!listener) return undefined;
    const liftedListener = liftListener(listener, config);
    listeners[id].push(liftedListener);

    return function unsubscribe() {
      const index = listeners[id].indexOf(liftedListener);
      listeners[id].splice(index, 1);
    };
  };

  const unsubscribe = () => {
    delete listeners[id];
  };

  const sendDelayed = throttle(() => {
    sendMessage(delayedActions, delayedStates, config);
    delayedActions = [];
    delayedStates = [];
  }, latency);

  const send = (action, state) => {
    if (isPaused || isFiltered(action, localFilter) || predicate && !predicate(state, action)) {
      return;
    }

    let amendedAction = action;
    const amendedState = config.stateSanitizer ? config.stateSanitizer(state) : state;
    if (action) {
      if (config.getActionType) {
        amendedAction = config.getActionType(action);
        if (typeof amendedAction !== 'object') {
          amendedAction = { action: { type: amendedAction }, timestamp: Date.now() };
        }
      }
      else if (config.actionSanitizer) amendedAction = config.actionSanitizer(action);
      amendedAction = amendActionType(amendedAction);
      if (latency) {
        delayedActions.push(amendedAction);
        delayedStates.push(amendedState);
        sendDelayed();
        return;
      }
    }
    sendMessage(amendedAction, amendedState, config);
  };

  const init = (state, liftedData) => {
    const message = {
      type: 'INIT',
      payload: stringify(state, config),
      instanceId: id,
      source
    };
    if (liftedData && Array.isArray(liftedData)) { // Legacy
      message.action = stringify(liftedData);
      message.name = config.name;
    } else {
      if (liftedData) {
        message.liftedState = liftedData;
        if (liftedData.isPaused) isPaused = true;
      }
      message.libConfig = {
        name: config.name || document.title,
        features: config.features,
        serialize: !!config.serialize,
        type: config.type
      };
      // TODO: add actionCreators
    }
    post(message);
  };

  const error = (payload) => {
    post({ type: 'ERROR', payload, id, source });
  };

  window.addEventListener('message', handleMessages, false);

  post({ type: 'INIT_INSTANCE', instanceId: id, source });

  return {
    init,
    subscribe,
    unsubscribe,
    send,
    error
  };
}

export function updateStore(stores) {
  return function(newStore, instanceId) {
    /* eslint-disable no-console */
    console.warn('`devToolsExtension.updateStore` is deprecated, remove it and just use ' +
      '`__REDUX_DEVTOOLS_EXTENSION_COMPOSE__` instead of the extension\'s store enhancer: ' +
      'https://github.com/zalmoxisus/redux-devtools-extension#12-advanced-store-setup');
    /* eslint-enable no-console */
    const store = stores[instanceId || Object.keys(stores)[0]];
    // Mutate the store in order to keep the reference
    store.liftedStore = newStore.liftedStore;
    store.getState = newStore.getState;
    store.dispatch = newStore.dispatch;
  };
}

export function isInIframe() {
  try {
    return window.self !== window.top;
  } catch (e) {
    return true;
  }
}
<|endoftext|>