<commit_before>define(['app', 'underscore', 'providers/extended-route', 'js/support'], function(app, _) { 'use strict';

    app.config(['extendedRouteProvider', '$locationProvider', function($routeProvider, $locationProvider) {

        $locationProvider.html5Mode(true);
        $locationProvider.hashPrefix('!');

        $routeProvider.
            when('/',                                         { templateUrl: '/app/views/index.html',                             resolveController: true,                                 resolveUser: true }).
            when('/database/',                                { templateUrl: '/app/views/database/index.html',                    resolveController: true,                                 resolveUser: true }).
            when('/database/countries/',                      { templateUrl: '/app/views/database/countries.html',                       controller: LEGACY_InnerPageController,           resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['utilities/km-utilities']) } }).
            when('/database/countries/:code',                 { templateUrl: '/app/views/database/country.html',                         controller: LEGACY_InnerPageController,           resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['utilities/km-utilities']) } }).
            when('/database/record',                          { templateUrl: '/app/views/database/record.html',                          controller: LEGACY_InnerPageController,           resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['utilities/km-utilities', 'utilities/km-workflows', 'utilities/km-storage', 'directives/forms/form-controls', 'leaflet-directive']) } }).

            when('/management/',                              { templateUrl: '/app/views/management/register.html',                      controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['utilities/km-utilities', 'utilities/km-workflows', 'utilities/km-storage']) } }).
            when('/management/register',                      { redirectTo:  '/management/' }).
            when('/management/requests',                      { templateUrl: '/app/views/management/index.html',                         controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['utilities/km-utilities', 'utilities/km-workflows', 'utilities/km-storage']) } }).
            when('/management/national-reporting/:schema?',   { templateUrl: '/app/views/management/national-reporting.html',            controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['utilities/km-utilities', 'utilities/km-workflows', 'utilities/km-storage']) } }).
            when('/management/my-records/:schema?',           { templateUrl: '/app/views/management/my-records.html',                    controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['utilities/km-utilities']) } }).
            when('/management/list/:schema?',                 { templateUrl: '/app/views/management/record-list.html',                   controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['utilities/km-utilities']) } }).
            when('/management/my-drafts',                     { templateUrl: '/app/views/management/my-drafts.html',                     controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['utilities/km-utilities']) } }).

            when('/management/tasks',                         { templateUrl: '/app/views/management/tasks/tasks.html',                   controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['utilities/km-utilities']) } }).
            when('/management/tasks/:id',                     { templateUrl: '/app/views/management/tasks/tasks-id.html',                controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['utilities/km-utilities']) } }).
            when('/management/tasks/:id/:activity',           { templateUrl: '/app/views/management/tasks/tasks-id-activity.html',       controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['utilities/km-utilities']) } }).

            when('/management/signin',                        { templateUrl: '/app/views/management/signin.html',                 resolveController: true, resolveUser: true }).

        //  when('/management/meetings',                          { templateUrl: '/app/views/management/meetings/index.html',                 resolveController: true, resolveUser: true }).
        //  when('/management/meetings/:meetingId/documents',     { templateUrl: '/app/views/management/meetings/documents/index.html',       resolveController: true, resolveUser: true }).
        //  when('/management/meetings/:meetingId/documents/:id', { templateUrl: '/app/views/management/meetings/documents/document-id.html', resolveController: true, resolveUser: true }).

            when('/management/edit/aichiTarget',              { templateUrl: '/app/views/management/edit/aichi-target.html',             controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['chm/services/editFormUtility', 'directives/forms/form-controls']) } }).
            when('/management/edit/caseStudy',                { templateUrl: '/app/views/management/edit/case-study.html',               controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['chm/services/editFormUtility', 'directives/forms/form-controls']) } }).
            when('/management/edit/caseStudyHwb',             { templateUrl: '/app/views/management/edit/case-study-hwb.html',           controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['chm/services/editFormUtility', 'directives/forms/form-controls']) } }).
            when('/management/edit/contact',                  { templateUrl: '/app/views/management/edit/contact.html',                  controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['chm/services/editFormUtility', 'directives/forms/form-controls']) } }).
            when('/management/edit/database',                 { templateUrl: '/app/views/management/edit/database.html',                 controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['chm/services/editFormUtility', 'directives/forms/form-controls']) } }).
            when('/management/edit/implementationActivity',   { templateUrl: '/app/views/management/edit/implementationActivity.html',   controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['chm/services/editFormUtility', 'directives/forms/form-controls']) } }).
            when('/management/edit/marineEbsa',               { templateUrl: '/app/views/management/edit/marine-ebsa.html',              controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['chm/services/editFormUtility', 'directives/forms/form-controls', 'leaflet-directive']) } }).
            when('/management/edit/nationalIndicator',        { templateUrl: '/app/views/management/edit/nationalIndicator.html',        controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['chm/services/editFormUtility', 'directives/forms/form-controls']) } }).
            when('/management/edit/nationalReport',           { templateUrl: '/app/views/management/edit/nationalReport.html',           controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['chm/services/editFormUtility', 'directives/forms/form-controls']) } }).
            when('/management/edit/nationalSupportTool',      { templateUrl: '/app/views/management/edit/nationalSupportTool.html',      controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['chm/services/editFormUtility', 'directives/forms/form-controls']) } }).
            when('/management/edit/nationalTarget',           { templateUrl: '/app/views/management/edit/nationalTarget.html',           controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['chm/services/editFormUtility', 'directives/forms/form-controls']) } }).
            when('/management/edit/organization',             { templateUrl: '/app/views/management/edit/organization.html',             controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['chm/services/editFormUtility', 'directives/forms/form-controls']) } }).
            when('/management/edit/progressAssessment',       { templateUrl: '/app/views/management/edit/progressAssessment.html',       controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['chm/services/editFormUtility', 'directives/forms/form-controls']) } }).
            when('/management/edit/resource',                 { templateUrl: '/app/views/management/edit/resource.html',                 controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['chm/services/editFormUtility', 'directives/forms/form-controls']) } }).
            when('/management/edit/resourceMobilisation',     { templateUrl: '/app/views/management/edit/resource-mobilisation.html',    controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['chm/services/editFormUtility', 'directives/forms/form-controls']) } }).
            when('/management/edit/strategicPlanIndicator',   { templateUrl: '/app/views/management/edit/strategic-plan-indicator.html', controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['chm/services/editFormUtility', 'directives/forms/form-controls']) } }).

            when('/about/',                                   { templateUrl: '/app/views/about.html',                                    controller: LEGACY_InnerPageController,           resolveUser: true, resolve : { dependencies : legacyResolver(['utilities/km-utilities']) } }).
            when('/network/',                                 { templateUrl: '/app/views/404.html',                                      controller: LEGACY_InnerPageController,           resolveUser: true, resolve : { dependencies : legacyResolver(['utilities/km-utilities']) } }).
            when('/resources/',                               { templateUrl: '/app/views/404.html',                                      controller: LEGACY_InnerPageController,           resolveUser: true, resolve : { dependencies : legacyResolver(['utilities/km-utilities']) } }).

            when('/help/404',                                 { templateUrl: '/app/views/404.html',                                      controller: LEGACY_InnerPageController,           resolveUser: true, resolve : { dependencies : legacyResolver(['utilities/km-utilities']) } }).
            when('/help/403',                                 { templateUrl: '/app/views/403.html',                                      controller: LEGACY_InnerPageController,           resolveUser: true, resolve : { dependencies : legacyResolver(['utilities/km-utilities']) } }).

            otherwise({ redirectTo: '/help/404' });

    }]);

    //============================================================
    //
    //
    //============================================================
    function securize(roles)
    {
        return ["$location", "authentication", "siteMapUrls", function ($location, authentication, siteMapUrls) {

            return authentication.getUser().then(function (user) {

                if (!user.isAuthenticated) {

                    console.log("securize: force sign in");

                    if (!$location.search().returnUrl)
                        $location.search({ returnUrl: $location.url() });

                    $location.path(siteMapUrls.user.signIn);

                }
                else if (roles && !_.isEmpty(roles) && _.isEmpty(_.intersection(roles, user.roles))) {

                    console.log("securize: not authorized");

                    $location.search({ path: $location.url() });
                    $location.path(siteMapUrls.errors.notAuthorized);
                }

                return user;
            });
        }];
    }

    //============================================================
    //
    //
    //============================================================
    function legacyResolver(deps)
    {
        return ['$q', function($q) {

            var deferred = $q.defer();

            require(deps, function () {
                deferred.resolve();
            });

            return deferred.promise;
        }];
    }

    ////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////

    //============================================================
    //
    //
    //============================================================
    function LEGACY_InnerPageController($rootScope, $scope, $route, $location, user) {

        $rootScope.homePage = false;
        $rootScope.userGovernment = user.government;
        $rootScope.portal = 'database';
        $rootScope.navigation = [
            { url: '/database/', title: 'Search' },
            { url: '/database/countries/', title: 'Parties and Country Profiles' }
        ];

        var subMenu = '';   // use ng-breadcrumbs instead
        switch ($location.path()) {
            case '/database/': {
                subMenu = 'Search';  // use ng-breadcrumbs instead
                break;
            }
            case '/database/countries/': {
                subMenu = 'Parties and Country Profiles';  // use ng-breadcrumbs instead
                break;
            }
            default: subMenu = '';  // use ng-breadcrumbs instead
        }

        $rootScope.navigationTree = {
            mainMenu: 'Finding Information', subMenu: subMenu   // use ng-breadcrumbs instead
        };
    }

    //============================================================
    //
    //
    //============================================================
    function LEGACY_ManagementPageController($rootScope, $scope, $route, $location, siteMapUrls, navigation, user) {

        if ($route.current.originalPath != siteMapUrls.user.signIn)
            navigation.securize();

        $rootScope.homePage = false;
        $rootScope.userGovernment = user.government;
        $rootScope.portal = 'management';
        $rootScope.navigation = [
        { url: '/management/',           title: 'My Dashboard' },
        { url: '/management/register',   title: 'Register a new record' },
        { url: '/management/my-records', title: 'Edit a published record' },
        { url: '/management/my-drafts',  title: 'Edit a draft record' },
        ];

        var subMenu = '';  // use ng-breadcrumbs instead

        switch ($location.path()) {
            case '/management/': {
                subMenu = 'My Dashboard';  // use ng-breadcrumbs instead
                break;
            }
            case '/management/register': {
                subMenu = 'Register a new record';  // use ng-breadcrumbs instead
                break;
            }
            case '/management/my-records': {
                subMenu = 'Edit a published record';  // use ng-breadcrumbs instead
                break;
            }
            case '/management/my-drafts': {
                subMenu = 'Edit a draft record';  // use ng-breadcrumbs instead
                break;
            }
            default: subMenu = '';  // use ng-breadcrumbs instead
        }

        $rootScope.navigationTree = {
            mainMenu: 'Registering Information', subMenu: subMenu  // use ng-breadcrumbs instead
        };
    }
});
<commit_msg>add dependencies<commit_after>define(['app', 'underscore', 'providers/extended-route', 'js/support'], function(app, _) { 'use strict';

    app.config(['extendedRouteProvider', '$locationProvider', function($routeProvider, $locationProvider) {

        $locationProvider.html5Mode(true);
        $locationProvider.hashPrefix('!');

        $routeProvider.
            when('/',                                         { templateUrl: '/app/views/index.html',                             resolveController: true,                                 resolveUser: true }).
            when('/database/',                                { templateUrl: '/app/views/database/index.html',                    resolveController: true,                                 resolveUser: true }).
            when('/database/countries/',                      { templateUrl: '/app/views/database/countries.html',                       controller: LEGACY_InnerPageController,           resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['utilities/km-utilities']) } }).
            when('/database/countries/:code',                 { templateUrl: '/app/views/database/country.html',                         controller: LEGACY_InnerPageController,           resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['utilities/km-utilities']) } }).
            when('/database/record',                          { templateUrl: '/app/views/database/record.html',                          controller: LEGACY_InnerPageController,           resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['utilities/km-utilities', 'utilities/km-workflows', 'utilities/km-storage', 'directives/forms/form-controls', 'leaflet-directive']) } }).

            when('/management/',                              { templateUrl: '/app/views/management/register.html',                      controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['utilities/km-utilities', 'utilities/km-workflows', 'utilities/km-storage']) } }).
            when('/management/register',                      { redirectTo:  '/management/' }).
            when('/management/requests',                      { templateUrl: '/app/views/management/index.html',                         controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['utilities/km-utilities', 'utilities/km-workflows', 'utilities/km-storage']) } }).
            when('/management/national-reporting/:schema?',   { templateUrl: '/app/views/management/national-reporting.html',            controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['utilities/km-utilities', 'utilities/km-workflows', 'utilities/km-storage']) } }).
            when('/management/my-records/:schema?',           { templateUrl: '/app/views/management/my-records.html',                    controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['utilities/km-utilities', 'utilities/km-workflows', 'utilities/km-storage']) } }).
            when('/management/list/:schema?',                 { templateUrl: '/app/views/management/record-list.html',                   controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['utilities/km-utilities', 'utilities/km-workflows', 'utilities/km-storage']) } }).
            when('/management/my-drafts',                     { templateUrl: '/app/views/management/my-drafts.html',                     controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['utilities/km-utilities', 'utilities/km-workflows', 'utilities/km-storage']) } }).

            when('/management/tasks',                         { templateUrl: '/app/views/management/tasks/tasks.html',                   controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['utilities/km-utilities']) } }).
            when('/management/tasks/:id',                     { templateUrl: '/app/views/management/tasks/tasks-id.html',                controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['utilities/km-utilities']) } }).
            when('/management/tasks/:id/:activity',           { templateUrl: '/app/views/management/tasks/tasks-id-activity.html',       controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['utilities/km-utilities']) } }).

            when('/management/signin',                        { templateUrl: '/app/views/management/signin.html',                 resolveController: true, resolveUser: true }).

        //  when('/management/meetings',                          { templateUrl: '/app/views/management/meetings/index.html',                 resolveController: true, resolveUser: true }).
        //  when('/management/meetings/:meetingId/documents',     { templateUrl: '/app/views/management/meetings/documents/index.html',       resolveController: true, resolveUser: true }).
        //  when('/management/meetings/:meetingId/documents/:id', { templateUrl: '/app/views/management/meetings/documents/document-id.html', resolveController: true, resolveUser: true }).

            when('/management/edit/aichiTarget',              { templateUrl: '/app/views/management/edit/aichi-target.html',             controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['chm/services/editFormUtility', 'directives/forms/form-controls']) } }).
            when('/management/edit/caseStudy',                { templateUrl: '/app/views/management/edit/case-study.html',               controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['chm/services/editFormUtility', 'directives/forms/form-controls']) } }).
            when('/management/edit/caseStudyHwb',             { templateUrl: '/app/views/management/edit/case-study-hwb.html',           controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['chm/services/editFormUtility', 'directives/forms/form-controls']) } }).
            when('/management/edit/contact',                  { templateUrl: '/app/views/management/edit/contact.html',                  controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['chm/services/editFormUtility', 'directives/forms/form-controls']) } }).
            when('/management/edit/database',                 { templateUrl: '/app/views/management/edit/database.html',                 controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['chm/services/editFormUtility', 'directives/forms/form-controls']) } }).
            when('/management/edit/implementationActivity',   { templateUrl: '/app/views/management/edit/implementationActivity.html',   controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['chm/services/editFormUtility', 'directives/forms/form-controls']) } }).
            when('/management/edit/marineEbsa',               { templateUrl: '/app/views/management/edit/marine-ebsa.html',              controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['chm/services/editFormUtility', 'directives/forms/form-controls', 'leaflet-directive']) } }).
            when('/management/edit/nationalIndicator',        { templateUrl: '/app/views/management/edit/nationalIndicator.html',        controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['chm/services/editFormUtility', 'directives/forms/form-controls']) } }).
            when('/management/edit/nationalReport',           { templateUrl: '/app/views/management/edit/nationalReport.html',           controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['chm/services/editFormUtility', 'directives/forms/form-controls']) } }).
            when('/management/edit/nationalSupportTool',      { templateUrl: '/app/views/management/edit/nationalSupportTool.html',      controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['chm/services/editFormUtility', 'directives/forms/form-controls']) } }).
            when('/management/edit/nationalTarget',           { templateUrl: '/app/views/management/edit/nationalTarget.html',           controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['chm/services/editFormUtility', 'directives/forms/form-controls']) } }).
            when('/management/edit/organization',             { templateUrl: '/app/views/management/edit/organization.html',             controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['chm/services/editFormUtility', 'directives/forms/form-controls']) } }).
            when('/management/edit/progressAssessment',       { templateUrl: '/app/views/management/edit/progressAssessment.html',       controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['chm/services/editFormUtility', 'directives/forms/form-controls']) } }).
            when('/management/edit/resource',                 { templateUrl: '/app/views/management/edit/resource.html',                 controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['chm/services/editFormUtility', 'directives/forms/form-controls']) } }).
            when('/management/edit/resourceMobilisation',     { templateUrl: '/app/views/management/edit/resource-mobilisation.html',    controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['chm/services/editFormUtility', 'directives/forms/form-controls']) } }).
            when('/management/edit/strategicPlanIndicator',   { templateUrl: '/app/views/management/edit/strategic-plan-indicator.html', controller: LEGACY_ManagementPageController,      resolveUser: true, resolve : { securized : securize(), dependencies : legacyResolver(['chm/services/editFormUtility', 'directives/forms/form-controls']) } }).

            when('/about/',                                   { templateUrl: '/app/views/about.html',                                    controller: LEGACY_InnerPageController,           resolveUser: true, resolve : { dependencies : legacyResolver(['utilities/km-utilities']) } }).
            when('/network/',                                 { templateUrl: '/app/views/404.html',                                      controller: LEGACY_InnerPageController,           resolveUser: true, resolve : { dependencies : legacyResolver(['utilities/km-utilities']) } }).
            when('/resources/',                               { templateUrl: '/app/views/404.html',                                      controller: LEGACY_InnerPageController,           resolveUser: true, resolve : { dependencies : legacyResolver(['utilities/km-utilities']) } }).

            when('/help/404',                                 { templateUrl: '/app/views/404.html',                                      controller: LEGACY_InnerPageController,           resolveUser: true, resolve : { dependencies : legacyResolver(['utilities/km-utilities']) } }).
            when('/help/403',                                 { templateUrl: '/app/views/403.html',                                      controller: LEGACY_InnerPageController,           resolveUser: true, resolve : { dependencies : legacyResolver(['utilities/km-utilities']) } }).

            otherwise({ redirectTo: '/help/404' });

    }]);

    //============================================================
    //
    //
    //============================================================
    function securize(roles)
    {
        return ["$location", "authentication", "siteMapUrls", function ($location, authentication, siteMapUrls) {

            return authentication.getUser().then(function (user) {

                if (!user.isAuthenticated) {

                    console.log("securize: force sign in");

                    if (!$location.search().returnUrl)
                        $location.search({ returnUrl: $location.url() });

                    $location.path(siteMapUrls.user.signIn);

                }
                else if (roles && !_.isEmpty(roles) && _.isEmpty(_.intersection(roles, user.roles))) {

                    console.log("securize: not authorized");

                    $location.search({ path: $location.url() });
                    $location.path(siteMapUrls.errors.notAuthorized);
                }

                return user;
            });
        }];
    }

    //============================================================
    //
    //
    //============================================================
    function legacyResolver(deps)
    {
        return ['$q', function($q) {

            var deferred = $q.defer();

            require(deps, function () {
                deferred.resolve();
            });

            return deferred.promise;
        }];
    }

    ////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////

    //============================================================
    //
    //
    //============================================================
    function LEGACY_InnerPageController($rootScope, $scope, $route, $location, user) {

        $rootScope.homePage = false;
        $rootScope.userGovernment = user.government;
        $rootScope.portal = 'database';
        $rootScope.navigation = [
            { url: '/database/', title: 'Search' },
            { url: '/database/countries/', title: 'Parties and Country Profiles' }
        ];

        var subMenu = '';   // use ng-breadcrumbs instead
        switch ($location.path()) {
            case '/database/': {
                subMenu = 'Search';  // use ng-breadcrumbs instead
                break;
            }
            case '/database/countries/': {
                subMenu = 'Parties and Country Profiles';  // use ng-breadcrumbs instead
                break;
            }
            default: subMenu = '';  // use ng-breadcrumbs instead
        }

        $rootScope.navigationTree = {
            mainMenu: 'Finding Information', subMenu: subMenu   // use ng-breadcrumbs instead
        };
    }

    //============================================================
    //
    //
    //============================================================
    function LEGACY_ManagementPageController($rootScope, $scope, $route, $location, siteMapUrls, navigation, user) {

        if ($route.current.originalPath != siteMapUrls.user.signIn)
            navigation.securize();

        $rootScope.homePage = false;
        $rootScope.userGovernment = user.government;
        $rootScope.portal = 'management';
        $rootScope.navigation = [
        { url: '/management/',           title: 'My Dashboard' },
        { url: '/management/register',   title: 'Register a new record' },
        { url: '/management/my-records', title: 'Edit a published record' },
        { url: '/management/my-drafts',  title: 'Edit a draft record' },
        ];

        var subMenu = '';  // use ng-breadcrumbs instead

        switch ($location.path()) {
            case '/management/': {
                subMenu = 'My Dashboard';  // use ng-breadcrumbs instead
                break;
            }
            case '/management/register': {
                subMenu = 'Register a new record';  // use ng-breadcrumbs instead
                break;
            }
            case '/management/my-records': {
                subMenu = 'Edit a published record';  // use ng-breadcrumbs instead
                break;
            }
            case '/management/my-drafts': {
                subMenu = 'Edit a draft record';  // use ng-breadcrumbs instead
                break;
            }
            default: subMenu = '';  // use ng-breadcrumbs instead
        }

        $rootScope.navigationTree = {
            mainMenu: 'Registering Information', subMenu: subMenu  // use ng-breadcrumbs instead
        };
    }
});
<|endoftext|>


<commit_before>import React from 'react'
import { browserHistory, IndexRoute, Route, Router } from 'react-router'
import Loadable from 'react-loadable'
import App from './App'
import ClearAuthPage from './clear-auth'
import { connectedRouterRedirect } from 'redux-auth-wrapper/history3/redirect'

const Loading = () =>
Loading...

const HomeScreenPage = Loadable({
  loader: () =>
    import(/* webpackChunkName: "HomeScreenPage" */ './HomeScreenPage'),
  loading: Loading,
  delay: 300
})

const ProfilesApp = Loadable({
  loader: () =>
    import(/* webpackChunkName: "ProfilesApp" */ './profiles/ProfilesApp'),
  loading: Loading,
  delay: 300
})

const UpdateStatePage = Loadable({
  loader: () => import(/* webpackChunkName: "UpdateStatePage" */ './update'),
  loading: Loading,
  delay: 300
})
const RegistrationPage = Loadable({
  loader: () =>
    import(/* webpackChunkName: "RegistrationPage" */ './profiles/RegistrationPage'),
  loading: Loading,
  delay: 300
})
const RegistrationSearchView = Loadable({
  loader: () =>
    import(/* webpackChunkName: "RegistrationSearchView" */ './profiles/components/registration/RegistrationSearchView'),
  loading: Loading,
  delay: 300
})

const RegistrationSelectView = Loadable({
  loader: () =>
    import(/* webpackChunkName: "RegistrationSelectView" */ './profiles/components/registration/RegistrationSelectView'),
  loading: Loading,
  delay: 300
})
const RegistrationSubmittedView = Loadable({
  loader: () =>
    import(/* webpackChunkName: "RegistrationSubmittedView" */ './profiles/components/registration/RegistrationSubmittedView'),
  loading: Loading,
  delay: 300
})
const DefaultProfilePage = Loadable({
  loader: () =>
    import(/* webpackChunkName: "DefaultProfilePage" */ './profiles/DefaultProfilePage'),
  loading: Loading,
  delay: 300
})
const AllProfilesPage = Loadable({
  loader: () =>
    import(/* webpackChunkName: "AllProfilesPage" */ './profiles/AllProfilesPage'),
  loading: Loading,
  delay: 300
})
const ViewProfilePage = Loadable({
  loader: () =>
    import(/* webpackChunkName: "ViewProfilePage" */ './profiles/ViewProfilePage'),
  loading: Loading,
  delay: 300
})
const EditProfilePage = Loadable({
  loader: () =>
    import(/* webpackChunkName: "EditProfilePage" */ './profiles/EditProfilePage'),
  loading: Loading,
  delay: 300
})
const RegisterProfilePage = Loadable({
  loader: () =>
    import(/* webpackChunkName: "RegisterProfilePage" */ './profiles/RegisterProfilePage'),
  loading: Loading,
  delay: 300
})
const ImportProfilePage = Loadable({
  loader: () =>
    import(/* webpackChunkName: "ImportProfilePage" */ './profiles/ImportProfilePage'),
  loading: Loading,
  delay: 300
})
const ExportProfilePage = Loadable({
  loader: () =>
    import(/* webpackChunkName: "ExportProfilePage" */ './profiles/ExportProfilePage'),
  loading: Loading,
  delay: 300
})
const SearchProfilesPage = Loadable({
  loader: () =>
    import(/* webpackChunkName: "SearchProfilesPage" */ './profiles/SearchProfilesPage'),
  loading: Loading,
  delay: 300
})
const TransferNamePage = Loadable({
  loader: () =>
    import(/* webpackChunkName: "TransferNamePage" */ './profiles/TransferNamePage'),
  loading: Loading,
  delay: 300
})
const ZoneFilePage = Loadable({
  loader: () =>
    import(/* webpackChunkName: "ZoneFilePage" */ './profiles/ZoneFilePage'),
  loading: Loading,
  delay: 300
})

const AccountApp = Loadable({
  loader: () =>
    import(/* webpackChunkName: "AccountApp" */ './account/AccountApp'),
  loading: Loading,
  delay: 300
})
const AccountMenu = Loadable({
  loader: () =>
    import(/* webpackChunkName: "AccountMenu" */ './account/AccountMenu'),
  loading: Loading,
  delay: 300
})
const DeleteAccountPage = Loadable({
  loader: () =>
    import(/* webpackChunkName: "DeleteAccountPage" */ './account/DeleteAccountPage'),
  loading: Loading,
  delay: 300
})
const BackupAccountPage = Loadable({
  loader: () =>
    import(/* webpackChunkName: "BackupAccountPage" */ './account/BackupAccountPage'),
  loading: Loading,
  delay: 300
})
const ChangePasswordPage = Loadable({
  loader: () =>
    import(/* webpackChunkName: "ChangePasswordPage" */ './account/ChangePasswordPage'),
  loading: Loading,
  delay: 300
})
const CreateAccountPage = Loadable({
  loader: () =>
    import(/* webpackChunkName: "CreateAccountPage" */ './account/CreateAccountPage'),
  loading: Loading,
  delay: 300
})
const ApiSettingsPage = Loadable({
  loader: () =>
    import(/* webpackChunkName: "ApiSettingsPage" */ './account/ApiSettingsPage'),
  loading: Loading,
  delay: 300
})
const StorageProvidersPage = Loadable({
  loader: () =>
    import(/* webpackChunkName: "StorageProvidersPage" */ './account/StorageProvidersPage'),
  loading: Loading,
  delay: 300
})

const WalletApp = Loadable({
  loader: () =>
    import(/* webpackChunkName: "WalletApp" */ './wallet/WalletApp'),
  loading: Loading,
  delay: 300
})
const ReceivePage = Loadable({
  loader: () =>
    import(/* webpackChunkName: "ReceivePage" */ './wallet/ReceivePage'),
  loading: Loading,
  delay: 300
})
const SendPage = Loadable({
  loader: () => import(/* webpackChunkName: "SendPage" */ './wallet/SendPage'),
  loading: Loading,
  delay: 300
})
const SendCorePage = Loadable({
  loader: () =>
    import(/* webpackChunkName: "SendCorePage" */ './wallet/SendCorePage'),
  loading: Loading,
  delay: 300
})

const NewAuthPage = Loadable({
  loader: () => import(/* webpackChunkName: "NewAuthPage" */ './auth/index'),
  loading: Loading,
  delay: 300
})

const SignUpPage = Loadable({
  loader: () => import(/* webpackChunkName: "SignUpPage" */ './sign-up'),
  loading: Loading,
  delay: 300
})
const SeedPage = Loadable({
  loader: () => import(/* webpackChunkName: "SeedPage" */ './seed'),
  loading: Loading,
  delay: 300
})
const SignInPage = Loadable({
  loader: () => import(/* webpackChunkName: "SignInPage" */ './sign-in'),
  loading: Loading,
  delay: 300
})

const NotFoundPage = Loadable({
  loader: () =>
    import(/* webpackChunkName: "NotFoundPage" */ './errors/NotFoundPage'),
  loading: Loading,
  delay: 300
})

const accountCreated = connectedRouterRedirect({
  redirectPath: '/sign-up',
  authenticatedSelector: state => !!state.account.encryptedBackupPhrase,
  wrapperDisplayName: 'AccountCreated'
})

export default (
  <Router history={browserHistory}>
    <Route path="/" component={accountCreated(App)}>
      <IndexRoute component={HomeScreenPage} />
      <Route path="profiles" component={ProfilesApp}>
        <IndexRoute component={DefaultProfilePage} />
        <Route path="i/all" component={AllProfilesPage} />
        <Route path="i/search/:query" component={SearchProfilesPage} />
        <Route path=":name" component={ViewProfilePage} />
        <Route path=":index/local" component={ViewProfilePage} />
        <Route path=":index/edit" component={EditProfilePage} />
        <Route path=":index/transfer-name" component={TransferNamePage} />
        <Route path=":index/zone-file" component={ZoneFilePage} />
        <Route path=":index/export" component={ExportProfilePage} />
        <Route path="i/add-username" component={RegistrationPage}>
          <Route path=":index/search" component={RegistrationSearchView} />
          <Route
            path=":index/select/:name"
            component={RegistrationSelectView}
          />
          <Route
            path=":index/submitted/:name"
            component={RegistrationSubmittedView}
          />
        </Route>
        <Route path="i/register/:index" component={RegisterProfilePage} />
        <Route path="i/import" component={ImportProfilePage} />
      </Route>

      <Route path="account" component={AccountApp}>
        <IndexRoute component={AccountMenu} />
        <Route path="delete" component={DeleteAccountPage} />
        <Route path="backup" component={BackupAccountPage} />
        <Route path="password" component={ChangePasswordPage} />
        <Route path="create" component={CreateAccountPage} />
        <Route path="api" component={ApiSettingsPage} />
        <Route path="storage" component={StorageProvidersPage} />
      </Route>

      <Route path="wallet" component={WalletApp}>
        <Route path="receive" component={ReceivePage} />
        <Route path="send" component={SendPage} />
        <Route path="send-core" component={SendCorePage} />
      </Route>

      <Route path="/auth" component={NewAuthPage} />
    </Route>
    <Route path="/sign-up" component={SignUpPage} />
    <Route path="/sign-up/*" component={SignUpPage} />
    {/**
     * TODO: move /update back up ^^, had to move it out of the 'app' nested route
     * because when we wipe data, it wants to redirect to /sign-up
     */}
    <Route path="/update" component={UpdateStatePage} />
    <Route path="/sign-in" component={SignInPage} />
    <Route path="/sign-in/*" component={SignInPage} />
    <Route path="/seed" component={SeedPage} />
    <Route path="/clear-auth" component={ClearAuthPage} />
    <Route path="/*" component={NotFoundPage} />
  </Router>
)
<commit_msg>try to squeeze some more perf<commit_after>import React from 'react'
import { browserHistory, IndexRoute, Route, Router } from 'react-router'
import Loadable from 'react-loadable'
import App from './App'
import ClearAuthPage from './clear-auth'
import { connectedRouterRedirect } from 'redux-auth-wrapper/history3/redirect'

const Loading = (props) => {
  if (props.error) {
    return
Error! <button onClick={ props.retry }>Retry</button>

  } else if (props.pastDelay) {
    return
Loading...

  }
  return null
}

const HomeScreenPage = Loadable({
  loader: () =>
    import(/* webpackChunkName: "HomeScreenPage" */ './HomeScreenPage'),
  loading: Loading,
  delay: 300
})

const ProfilesApp = Loadable({
  loader: () =>
    import(/* webpackChunkName: "ProfilesApp" */ './profiles/ProfilesApp'),
  loading: Loading,
  delay: 300
})

const UpdateStatePage = Loadable({
  loader: () => import(/* webpackChunkName: "UpdateStatePage" */ './update'),
  loading: Loading,
  delay: 300
})
const RegistrationPage = Loadable({
  loader: () =>
    import(/* webpackChunkName: "RegistrationPage" */ './profiles/RegistrationPage'),
  loading: Loading,
  delay: 300
})
const RegistrationSearchView = Loadable({
  loader: () =>
    import(/* webpackChunkName: "RegistrationSearchView" */ './profiles/components/registration/RegistrationSearchView'),
  loading: Loading,
  delay: 300
})

const RegistrationSelectView = Loadable({
  loader: () =>
    import(/* webpackChunkName: "RegistrationSelectView" */ './profiles/components/registration/RegistrationSelectView'),
  loading: Loading,
  delay: 300
})
const RegistrationSubmittedView = Loadable({
  loader: () =>
    import(/* webpackChunkName: "RegistrationSubmittedView" */ './profiles/components/registration/RegistrationSubmittedView'),
  loading: Loading,
  delay: 300
})
const DefaultProfilePage = Loadable({
  loader: () =>
    import(/* webpackChunkName: "DefaultProfilePage" */ './profiles/DefaultProfilePage'),
  loading: Loading,
  delay: 300
})
const AllProfilesPage = Loadable({
  loader: () =>
    import(/* webpackChunkName: "AllProfilesPage" */ './profiles/AllProfilesPage'),
  loading: Loading,
  delay: 300
})
const ViewProfilePage = Loadable({
  loader: () =>
    import(/* webpackChunkName: "ViewProfilePage" */ './profiles/ViewProfilePage'),
  loading: Loading,
  delay: 300
})
const EditProfilePage = Loadable({
  loader: () =>
    import(/* webpackChunkName: "EditProfilePage" */ './profiles/EditProfilePage'),
  loading: Loading,
  delay: 300
})
const RegisterProfilePage = Loadable({
  loader: () =>
    import(/* webpackChunkName: "RegisterProfilePage" */ './profiles/RegisterProfilePage'),
  loading: Loading,
  delay: 300
})
const ImportProfilePage = Loadable({
  loader: () =>
    import(/* webpackChunkName: "ImportProfilePage" */ './profiles/ImportProfilePage'),
  loading: Loading,
  delay: 300
})
const ExportProfilePage = Loadable({
  loader: () =>
    import(/* webpackChunkName: "ExportProfilePage" */ './profiles/ExportProfilePage'),
  loading: Loading,
  delay: 300
})
const SearchProfilesPage = Loadable({
  loader: () =>
    import(/* webpackChunkName: "SearchProfilesPage" */ './profiles/SearchProfilesPage'),
  loading: Loading,
  delay: 300
})
const TransferNamePage = Loadable({
  loader: () =>
    import(/* webpackChunkName: "TransferNamePage" */ './profiles/TransferNamePage'),
  loading: Loading,
  delay: 300
})
const ZoneFilePage = Loadable({
  loader: () =>
    import(/* webpackChunkName: "ZoneFilePage" */ './profiles/ZoneFilePage'),
  loading: Loading,
  delay: 300
})

const AccountApp = Loadable({
  loader: () =>
    import(/* webpackChunkName: "AccountApp" */ './account/AccountApp'),
  loading: Loading,
  delay: 300
})
const AccountMenu = Loadable({
  loader: () =>
    import(/* webpackChunkName: "AccountMenu" */ './account/AccountMenu'),
  loading: Loading,
  delay: 300
})
const DeleteAccountPage = Loadable({
  loader: () =>
    import(/* webpackChunkName: "DeleteAccountPage" */ './account/DeleteAccountPage'),
  loading: Loading,
  delay: 300
})
const BackupAccountPage = Loadable({
  loader: () =>
    import(/* webpackChunkName: "BackupAccountPage" */ './account/BackupAccountPage'),
  loading: Loading,
  delay: 300
})
const ChangePasswordPage = Loadable({
  loader: () =>
    import(/* webpackChunkName: "ChangePasswordPage" */ './account/ChangePasswordPage'),
  loading: Loading,
  delay: 300
})
const CreateAccountPage = Loadable({
  loader: () =>
    import(/* webpackChunkName: "CreateAccountPage" */ './account/CreateAccountPage'),
  loading: Loading,
  delay: 300
})
const ApiSettingsPage = Loadable({
  loader: () =>
    import(/* webpackChunkName: "ApiSettingsPage" */ './account/ApiSettingsPage'),
  loading: Loading,
  delay: 300
})
const StorageProvidersPage = Loadable({
  loader: () =>
    import(/* webpackChunkName: "StorageProvidersPage" */ './account/StorageProvidersPage'),
  loading: Loading,
  delay: 300
})

const WalletApp = Loadable({
  loader: () =>
    import(/* webpackChunkName: "WalletApp" */ './wallet/WalletApp'),
  loading: Loading,
  delay: 300
})
const ReceivePage = Loadable({
  loader: () =>
    import(/* webpackChunkName: "ReceivePage" */ './wallet/ReceivePage'),
  loading: Loading,
  delay: 300
})
const SendPage = Loadable({
  loader: () => import(/* webpackChunkName: "SendPage" */ './wallet/SendPage'),
  loading: Loading,
  delay: 300
})
const SendCorePage = Loadable({
  loader: () =>
    import(/* webpackChunkName: "SendCorePage" */ './wallet/SendCorePage'),
  loading: Loading,
  delay: 300
})

const NewAuthPage = Loadable({
  loader: () => import(/* webpackChunkName: "NewAuthPage" */ './auth/index'),
  loading: Loading,
  delay: 300
})

const SignUpPage = Loadable({
  loader: () => import(/* webpackChunkName: "SignUpPage" */ './sign-up'),
  loading: Loading,
  delay: 300
})
const SeedPage = Loadable({
  loader: () => import(/* webpackChunkName: "SeedPage" */ './seed'),
  loading: Loading,
  delay: 300
})
const SignInPage = Loadable({
  loader: () => import(/* webpackChunkName: "SignInPage" */ './sign-in'),
  loading: Loading,
  delay: 300
})

const NotFoundPage = Loadable({
  loader: () =>
    import(/* webpackChunkName: "NotFoundPage" */ './errors/NotFoundPage'),
  loading: Loading,
  delay: 300
})

const accountCreated = connectedRouterRedirect({
  redirectPath: '/sign-up',
  authenticatedSelector: state => !!state.account.encryptedBackupPhrase,
  wrapperDisplayName: 'AccountCreated'
})

export default (
  <Router history={ browserHistory }>
    <Route path="/" component={ accountCreated(App) }>
      <IndexRoute component={ HomeScreenPage }/>
      <Route path="profiles" component={ ProfilesApp }>
        <IndexRoute component={ DefaultProfilePage }/>
        <Route path="i/all" component={ AllProfilesPage }/>
        <Route path="i/search/:query" component={ SearchProfilesPage }/>
        <Route path=":name" component={ ViewProfilePage }/>
        <Route path=":index/local" component={ ViewProfilePage }/>
        <Route path=":index/edit" component={ EditProfilePage }/>
        <Route path=":index/transfer-name" component={ TransferNamePage }/>
        <Route path=":index/zone-file" component={ ZoneFilePage }/>
        <Route path=":index/export" component={ ExportProfilePage }/>
        <Route path="i/add-username" component={ RegistrationPage }>
          <Route path=":index/search" component={ RegistrationSearchView }/>
          <Route
            path=":index/select/:name"
            component={ RegistrationSelectView }
          />
          <Route
            path=":index/submitted/:name"
            component={ RegistrationSubmittedView }
          />
        </Route>
        <Route path="i/register/:index" component={ RegisterProfilePage }/>
        <Route path="i/import" component={ ImportProfilePage }/>
      </Route>

      <Route path="account" component={ AccountApp }>
        <IndexRoute component={ AccountMenu }/>
        <Route path="delete" component={ DeleteAccountPage }/>
        <Route path="backup" component={ BackupAccountPage }/>
        <Route path="password" component={ ChangePasswordPage }/>
        <Route path="create" component={ CreateAccountPage }/>
        <Route path="api" component={ ApiSettingsPage }/>
        <Route path="storage" component={ StorageProvidersPage }/>
      </Route>

      <Route path="wallet" component={ WalletApp }>
        <Route path="receive" component={ ReceivePage }/>
        <Route path="send" component={ SendPage }/>
        <Route path="send-core" component={ SendCorePage }/>
      </Route>

      <Route path="/auth" component={ NewAuthPage }/>
    </Route>
    <Route path="/sign-up" component={ SignUpPage }/>
    <Route path="/sign-up/*" component={ SignUpPage }/>
    { /**
     * TODO: move /update back up ^^, had to move it out of the 'app' nested route
     * because when we wipe data, it wants to redirect to /sign-up
     */ }
    <Route path="/update" component={ UpdateStatePage }/>
    <Route path="/sign-in" component={ SignInPage }/>
    <Route path="/sign-in/*" component={ SignInPage }/>
    <Route path="/seed" component={ SeedPage }/>
    <Route path="/clear-auth" component={ ClearAuthPage }/>
    <Route path="/*" component={ NotFoundPage }/>
  </Router>
)
<|endoftext|>


<commit_before>"use strict";
let dos2unix = require('./dos2unix');
let constants = require('./constants');

module.exports = new function() {

  let that = this;

  this.getOfficialIdentity = function (json) {
    let raw = "";
    raw += "Version: " + (json.version || constants.DOCUMENTS_VERSION) + "\n";
    raw += "Type: Identity\n";
    raw += "Currency: " + json.currency + "\n";
    raw += "Issuer: " + (json.issuer || json.pubkey) + "\n";
    raw += "UniqueID: " + json.uid + '\n';
    raw += "Timestamp: " + json.buid + '\n';
    if (json.sig) {
      raw += json.sig + '\n';
    }
    return dos2unix(raw);
  };

  this.getOfficialCertification = function (json) {
    let raw = getNormalHeader('Certification', json);
    raw += "IdtyIssuer: " + json.idty_issuer + '\n';
    raw += "IdtyUniqueID: " + json.idty_uid + '\n';
    raw += "IdtyTimestamp: " + json.idty_buid + '\n';
    raw += "IdtySignature: " + json.idty_sig + '\n';
    raw += "CertTimestamp: " + json.buid + '\n';
    if (json.sig) {
      raw += json.sig + '\n';
    }
    return dos2unix(raw);
  };

  this.getOfficialRevocation = function (json) {
    let raw = getNormalHeader('Revocation', json);
    raw += "IdtyUniqueID: " + json.uid + '\n';
    raw += "IdtyTimestamp: " + json.buid + '\n';
    raw += "IdtySignature: " + json.sig + '\n';
    raw += json.revocation + '\n';
    return dos2unix(raw);
  };

  this.getPeerWithoutSignature = function (json) {
    let raw = "";
    raw += "Version: " + (json.version || constants.DOCUMENTS_VERSION) + "\n";
    raw += "Type: Peer\n";
    raw += "Currency: " + json.currency + "\n";
    raw += "PublicKey: " + json.pubkey + "\n";
    raw += "Block: " + json.block + "\n";
    raw += "Endpoints:" + "\n";
    (json.endpoints || []).forEach(function(ep){
      raw += ep + "\n";
    });
    return dos2unix(raw);
  };

  this.getPeer = function (json) {
    return dos2unix(signed(that.getPeerWithoutSignature(json), json));
  };

  this.getMembershipWithoutSignature = function (json) {
    let raw = getNormalHeader('Membership', json);
    raw += "Block: " + json.block + "\n";
    raw += "Membership: " + json.membership + "\n";
    if (json.userid)
      raw += "UserID: " + json.userid + "\n";
    if (json.certts)
      raw += "CertTS: " + json.certts + "\n";
    return dos2unix(raw);
  };

  this.getMembership = function (json) {
    return dos2unix(signed(that.getMembershipWithoutSignature(json), json));
  };

  this.getBlockInnerPart = function (json) {
    let raw = "";
    raw += "Version: " + (json.version || constants.DOCUMENTS_VERSION) + "\n";
    raw += "Type: Block\n";
    raw += "Currency: " + json.currency + "\n";
    raw += "Number: " + json.number + "\n";
    raw += "PoWMin: " + json.powMin + "\n";
    raw += "Time: " + json.time + "\n";
    raw += "MedianTime: " + json.medianTime + "\n";
    if (json.dividend)
      raw += "UniversalDividend: " + json.dividend + "\n";
    if (json.dividend)
      raw += "UnitBase: " + json.unitbase + "\n";
    raw += "Issuer: " + json.issuer + "\n";
    if(json.previousHash)
      raw += "PreviousHash: " + json.previousHash + "\n";
    if(json.previousIssuer)
      raw += "PreviousIssuer: " + json.previousIssuer + "\n";
    if(json.parameters)
      raw += "Parameters: " + json.parameters + "\n";
    raw += "MembersCount: " + json.membersCount + "\n";
    raw += "Identities:\n";
    for(let i = 0; i < json.identities.length; i++){
      raw += json.identities[i] + "\n";
    }
    raw += "Joiners:\n";
    for(let i = 0; i < json.joiners.length; i++){
      raw += json.joiners[i] + "\n";
    }
    raw += "Actives:\n";
    for(let i = 0; i < json.actives.length; i++){
      raw += json.actives[i] + "\n";
    }
    raw += "Leavers:\n";
    for(let i = 0; i < json.leavers.length; i++){
      raw += json.leavers[i] + "\n";
    }
    raw += "Revoked:\n";
    for(let i = 0; i < json.revoked.length; i++){
      raw += json.revoked[i] + "\n";
    }
    raw += "Excluded:\n";
    for(let i = 0; i < json.excluded.length; i++){
      raw += json.excluded[i] + "\n";
    }
    raw += "Certifications:\n";
    for(let i = 0; i < json.certifications.length; i++){
      raw += json.certifications[i] + "\n";
    }
    raw += "Transactions:\n";
    for(let i = 0; i < json.transactions.length; i++){
      raw += json.transactions[i].raw || that.getCompactTransaction(json.transactions[i]);
    }
    return dos2unix(raw);
  };

  this.getBlockWithInnerHashAndNonce = function (json) {
    let raw = that.getBlockInnerPart(json);
    raw += "InnerHash: " + json.inner_hash + "\n";
    raw += "Nonce: " + json.nonce + "\n";
    return dos2unix(raw);
  };

  this.getBlockInnerHashAndNonce = function (json) {
    let raw = "" +
      "InnerHash: " + json.inner_hash + "\n" +
      "Nonce: " + json.nonce + "\n";
    return dos2unix(raw);
  };

  this.getBlockInnerHashAndNonceWithSignature = function (json) {
    let raw = "" +
      "InnerHash: " + json.inner_hash + "\n" +
      "Nonce: " + json.nonce + "\n";
    return dos2unix(signed(raw, json));
  };

  this.getBlock = function (json) {
    return dos2unix(signed(that.getBlockWithInnerHashAndNonce(json), json));
  };

  this.getTransaction = function (json) {
    let raw = "";
    raw += "Version: " + (json.version || constants.DOCUMENTS_VERSION) + "\n";
    raw += "Type: Transaction\n";
    raw += "Currency: " + json.currency + "\n";
    raw += "Locktime: " + json.locktime + "\n";
    raw += "Issuers:\n";
    (json.issuers || []).forEach(function (issuer) {
      raw += issuer + '\n';
    });
    raw += "Inputs:\n";
    (json.inputs || []).forEach(function (input) {
      raw += input + '\n';
    });
    raw += "Unlocks:\n";
    (json.unlocks || []).forEach(function (input) {
      raw += input + '\n';
    });
    raw += "Outputs:\n";
    (json.outputs || []).forEach(function (output) {
      raw += output + '\n';
    });
    raw += "Comment: " + (json.comment || "") + "\n";
    (json.signatures || []).forEach(function (signature) {
      raw += signature + '\n';
    });
    return dos2unix(raw);
  };

  this.getCompactTransaction = function (json) {
    let issuers = (json.issuers || json.signatories);
    let raw = ["TX", 1, issuers.length, json.inputs.length, json.unlocks.length, json.outputs.length, json.comment ? 1 : 0, json.locktime || 0].join(':') + '\n';
    (issuers || []).forEach(function (issuer) {
      raw += issuer + '\n';
    });
    (json.inputs || []).forEach(function (input) {
      raw += input + '\n';
    });
    (json.unlocks || []).forEach(function (input) {
      raw += input + '\n';
    });
    (json.outputs || []).forEach(function (output) {
      raw += output + '\n';
    });
    if (json.comment)
      raw += json.comment + '\n';
    (json.signatures || []).forEach(function (signature) {
      raw += signature + '\n';
    });
    return dos2unix(raw);
  };

  function getNormalHeader(doctype, json) {
    let raw = "";
    raw += "Version: " + (json.version || constants.DOCUMENTS_VERSION) + "\n";
    raw += "Type: " + doctype + "\n";
    raw += "Currency: " + json.currency + "\n";
    raw += "Issuer: " + json.issuer + "\n";
    return raw;
  }

  function signed (raw, json) {
    raw += json.signature + '\n';
    return raw;
  }
};
<commit_msg>Fix handling of line endings in revocations docs<commit_after>"use strict";
let dos2unix = require('./dos2unix');
let constants = require('./constants');

module.exports = new function() {

  let that = this;

  this.getOfficialIdentity = function (json) {
    let raw = "";
    raw += "Version: " + (json.version || constants.DOCUMENTS_VERSION) + "\n";
    raw += "Type: Identity\n";
    raw += "Currency: " + json.currency + "\n";
    raw += "Issuer: " + (json.issuer || json.pubkey) + "\n";
    raw += "UniqueID: " + json.uid + '\n';
    raw += "Timestamp: " + json.buid + '\n';
    if (json.sig) {
      raw += json.sig + '\n';
    }
    return dos2unix(raw);
  };

  this.getOfficialCertification = function (json) {
    let raw = getNormalHeader('Certification', json);
    raw += "IdtyIssuer: " + json.idty_issuer + '\n';
    raw += "IdtyUniqueID: " + json.idty_uid + '\n';
    raw += "IdtyTimestamp: " + json.idty_buid + '\n';
    raw += "IdtySignature: " + json.idty_sig + '\n';
    raw += "CertTimestamp: " + json.buid + '\n';
    if (json.sig) {
      raw += json.sig + '\n';
    }
    return dos2unix(raw);
  };

  this.getOfficialRevocation = function (json) {
    let raw = getNormalHeader('Revocation', json);
    raw += "IdtyUniqueID: " + json.uid + '\n';
    raw += "IdtyTimestamp: " + json.buid + '\n';
    raw += "IdtySignature: " + json.sig + '\n';
    if (json.revocation) {
      raw += json.revocation + '\n';
    }
    return dos2unix(raw);
  };

  this.getPeerWithoutSignature = function (json) {
    let raw = "";
    raw += "Version: " + (json.version || constants.DOCUMENTS_VERSION) + "\n";
    raw += "Type: Peer\n";
    raw += "Currency: " + json.currency + "\n";
    raw += "PublicKey: " + json.pubkey + "\n";
    raw += "Block: " + json.block + "\n";
    raw += "Endpoints:" + "\n";
    (json.endpoints || []).forEach(function(ep){
      raw += ep + "\n";
    });
    return dos2unix(raw);
  };

  this.getPeer = function (json) {
    return dos2unix(signed(that.getPeerWithoutSignature(json), json));
  };

  this.getMembershipWithoutSignature = function (json) {
    let raw = getNormalHeader('Membership', json);
    raw += "Block: " + json.block + "\n";
    raw += "Membership: " + json.membership + "\n";
    if (json.userid)
      raw += "UserID: " + json.userid + "\n";
    if (json.certts)
      raw += "CertTS: " + json.certts + "\n";
    return dos2unix(raw);
  };

  this.getMembership = function (json) {
    return dos2unix(signed(that.getMembershipWithoutSignature(json), json));
  };

  this.getBlockInnerPart = function (json) {
    let raw = "";
    raw += "Version: " + (json.version || constants.DOCUMENTS_VERSION) + "\n";
    raw += "Type: Block\n";
    raw += "Currency: " + json.currency + "\n";
    raw += "Number: " + json.number + "\n";
    raw += "PoWMin: " + json.powMin + "\n";
    raw += "Time: " + json.time + "\n";
    raw += "MedianTime: " + json.medianTime + "\n";
    if (json.dividend)
      raw += "UniversalDividend: " + json.dividend + "\n";
    if (json.dividend)
      raw += "UnitBase: " + json.unitbase + "\n";
    raw += "Issuer: " + json.issuer + "\n";
    if(json.previousHash)
      raw += "PreviousHash: " + json.previousHash + "\n";
    if(json.previousIssuer)
      raw += "PreviousIssuer: " + json.previousIssuer + "\n";
    if(json.parameters)
      raw += "Parameters: " + json.parameters + "\n";
    raw += "MembersCount: " + json.membersCount + "\n";
    raw += "Identities:\n";
    for(let i = 0; i < json.identities.length; i++){
      raw += json.identities[i] + "\n";
    }
    raw += "Joiners:\n";
    for(let i = 0; i < json.joiners.length; i++){
      raw += json.joiners[i] + "\n";
    }
    raw += "Actives:\n";
    for(let i = 0; i < json.actives.length; i++){
      raw += json.actives[i] + "\n";
    }
    raw += "Leavers:\n";
    for(let i = 0; i < json.leavers.length; i++){
      raw += json.leavers[i] + "\n";
    }
    raw += "Revoked:\n";
    for(let i = 0; i < json.revoked.length; i++){
      raw += json.revoked[i] + "\n";
    }
    raw += "Excluded:\n";
    for(let i = 0; i < json.excluded.length; i++){
      raw += json.excluded[i] + "\n";
    }
    raw += "Certifications:\n";
    for(let i = 0; i < json.certifications.length; i++){
      raw += json.certifications[i] + "\n";
    }
    raw += "Transactions:\n";
    for(let i = 0; i < json.transactions.length; i++){
      raw += json.transactions[i].raw || that.getCompactTransaction(json.transactions[i]);
    }
    return dos2unix(raw);
  };

  this.getBlockWithInnerHashAndNonce = function (json) {
    let raw = that.getBlockInnerPart(json);
    raw += "InnerHash: " + json.inner_hash + "\n";
    raw += "Nonce: " + json.nonce + "\n";
    return dos2unix(raw);
  };

  this.getBlockInnerHashAndNonce = function (json) {
    let raw = "" +
      "InnerHash: " + json.inner_hash + "\n" +
      "Nonce: " + json.nonce + "\n";
    return dos2unix(raw);
  };

  this.getBlockInnerHashAndNonceWithSignature = function (json) {
    let raw = "" +
      "InnerHash: " + json.inner_hash + "\n" +
      "Nonce: " + json.nonce + "\n";
    return dos2unix(signed(raw, json));
  };

  this.getBlock = function (json) {
    return dos2unix(signed(that.getBlockWithInnerHashAndNonce(json), json));
  };

  this.getTransaction = function (json) {
    let raw = "";
    raw += "Version: " + (json.version || constants.DOCUMENTS_VERSION) + "\n";
    raw += "Type: Transaction\n";
    raw += "Currency: " + json.currency + "\n";
    raw += "Locktime: " + json.locktime + "\n";
    raw += "Issuers:\n";
    (json.issuers || []).forEach(function (issuer) {
      raw += issuer + '\n';
    });
    raw += "Inputs:\n";
    (json.inputs || []).forEach(function (input) {
      raw += input + '\n';
    });
    raw += "Unlocks:\n";
    (json.unlocks || []).forEach(function (input) {
      raw += input + '\n';
    });
    raw += "Outputs:\n";
    (json.outputs || []).forEach(function (output) {
      raw += output + '\n';
    });
    raw += "Comment: " + (json.comment || "") + "\n";
    (json.signatures || []).forEach(function (signature) {
      raw += signature + '\n';
    });
    return dos2unix(raw);
  };

  this.getCompactTransaction = function (json) {
    let issuers = (json.issuers || json.signatories);
    let raw = ["TX", 1, issuers.length, json.inputs.length, json.unlocks.length, json.outputs.length, json.comment ? 1 : 0, json.locktime || 0].join(':') + '\n';
    (issuers || []).forEach(function (issuer) {
      raw += issuer + '\n';
    });
    (json.inputs || []).forEach(function (input) {
      raw += input + '\n';
    });
    (json.unlocks || []).forEach(function (input) {
      raw += input + '\n';
    });
    (json.outputs || []).forEach(function (output) {
      raw += output + '\n';
    });
    if (json.comment)
      raw += json.comment + '\n';
    (json.signatures || []).forEach(function (signature) {
      raw += signature + '\n';
    });
    return dos2unix(raw);
  };

  function getNormalHeader(doctype, json) {
    let raw = "";
    raw += "Version: " + (json.version || constants.DOCUMENTS_VERSION) + "\n";
    raw += "Type: " + doctype + "\n";
    raw += "Currency: " + json.currency + "\n";
    raw += "Issuer: " + json.issuer + "\n";
    return raw;
  }

  function signed (raw, json) {
    raw += json.signature + '\n';
    return raw;
  }
};
<|endoftext|>


<commit_before>var window = typeof window === "undefined" ? this : window;

(function (logEnhancer, angular, sprintf, moment) {
	'use strict';

	angular.module('logger', []).
	provider('logEnhancer', function() {
		var provider = this;

        this.datetimePattern = 'LLL'; 	// default datetime stamp pattern, overwrite in config phase
        this.datetimeLocale = window.navigator.userLanguage || window.navigator.language || 'en';
        this.loggingPattern = '%s::[%s]> '; 		// default logging pattern, overwrite in config phase
        this.LEVEL = logEnhancer.LEVEL;             // with these configure loglevels in config fase
        this.logLevels = {'*': this.LEVEL.TRACE}; 	// everything by everyone should be visible by default

		this.$get = function() {
			return {

                // Actually modifies $log. Without calling this in the run phase, $log remains untouched
				enhanceAngularLog : function($log) {
					$log.LEVEL = provider.LEVEL; // assign to $log, so the user can change them after config phase
					$log.logLevels = provider.logLevels; // assign to $log, so the user can change them after config phase

					$log.getInstance = function(context) {
						return {
							trace	: logEnhancer.enhanceLogging($log.debug, $log.LEVEL.TRACE, context, $log, provider.datetimePattern, provider.datetimeLocale, provider.loggingPattern),
							debug	: logEnhancer.enhanceLogging($log.debug, $log.LEVEL.DEBUG, context, $log, provider.datetimePattern, provider.datetimeLocale, provider.loggingPattern),
							log		: logEnhancer.enhanceLogging($log.log,   $log.LEVEL.INFO,  context, $log, provider.datetimePattern, provider.datetimeLocale, provider.loggingPattern),
							info	: logEnhancer.enhanceLogging($log.info,  $log.LEVEL.INFO,  context, $log, provider.datetimePattern, provider.datetimeLocale, provider.loggingPattern),
							warn	: logEnhancer.enhanceLogging($log.warn,  $log.LEVEL.WARN,  context, $log, provider.datetimePattern, provider.datetimeLocale, provider.loggingPattern),
							error	: logEnhancer.enhanceLogging($log.error, $log.LEVEL.ERROR, context, $log, provider.datetimePattern, provider.datetimeLocale, provider.loggingPattern)
						};
					};
				}
			};
		};
	}).
	/*
		Default config and example config as well.
		Overrides default logging pattern and global logLevel
	*/
    config(['logEnhancerProvider',
        function (logEnhancerProvider) {
            // logEnhancerProvider.datetimePattern = 'LLL';
            // logEnhancerProvider.datetimeLocale = window.navigator.userLanguage || window.navigator.language || 'en';
            // logEnhancerProvider.loggingPattern = '%s::[%s]> ';
            // logEnhancerProvider.logLevels = {'*': logEnhancerProvider.LEVEL.TRACE};
            /*
                // example structure:
                logEnhancerProvider.logLevels = {
                    'a.b.c': logEnhancerProvider.LEVEL.TRACE, // trace + debug + info + warn + error
                    'a.b.d': logEnhancerProvider.LEVEL.ERROR, // error
                    'a.b': logEnhancerProvider.LEVEL.DEBUG, // debug + info + warn + error
                    'a': logEnhancerProvider.LEVEL.WARN, // warn + error
                    '*': logEnhancerProvider.LEVEL.INFO // info + warn + error
                };
            */
        }
    ]).
    run(['$log', 'logEnhancer',
        function ($log, logEnhancer) {
            if (!sprintf) {
                $log.warn("sprintf.js not found: https://github.com/alexei/sprintf.js, using fixed layout pattern '%s::[%s]> '");
            }
            if (!moment) {
                $log.warn("moment.js not found: http://momentjs.com, using simple Date format");
            }
            logEnhancer.enhanceAngularLog($log);
			$log.info('logging enhancer initiated');
        }
    ]);
}(window.loggingEnhancer, window.angular, window.sprintf, window.moment));<commit_msg>resolve Code Climate warning<commit_after>var window = typeof window === "undefined" ? this : window;

(function (logEnhancer, angular, sprintf, moment) {
	'use strict';

	angular.module('logger', []).
	provider('logEnhancer', function() {
		var provider = this;

        this.datetimePattern = 'LLL'; 	// default datetime stamp pattern, overwrite in config phase
        this.datetimeLocale = window.navigator.userLanguage || window.navigator.language || 'en';
        this.loggingPattern = '%s::[%s]> '; 		// default logging pattern, overwrite in config phase
        this.LEVEL = logEnhancer.LEVEL;             // with these configure loglevels in config fase
        this.logLevels = {'*': this.LEVEL.TRACE}; 	// everything by everyone should be visible by default

		this.$get = function() {
			return {

                // Actually modifies $log. Without calling this in the run phase, $log remains untouched
				enhanceAngularLog : function($log) {
					$log.LEVEL = provider.LEVEL; // assign to $log, so the user can change them after config phase
					$log.logLevels = provider.logLevels; // assign to $log, so the user can change them after config phase

					$log.getInstance = function(context) {
						return {
							trace	: logEnhancer.enhanceLogging($log.debug, $log.LEVEL.TRACE, context, $log, provider.datetimePattern, provider.datetimeLocale, provider.loggingPattern),
							debug	: logEnhancer.enhanceLogging($log.debug, $log.LEVEL.DEBUG, context, $log, provider.datetimePattern, provider.datetimeLocale, provider.loggingPattern),
							log		: logEnhancer.enhanceLogging($log.log,   $log.LEVEL.INFO,  context, $log, provider.datetimePattern, provider.datetimeLocale, provider.loggingPattern),
							info	: logEnhancer.enhanceLogging($log.info,  $log.LEVEL.INFO,  context, $log, provider.datetimePattern, provider.datetimeLocale, provider.loggingPattern),
							warn	: logEnhancer.enhanceLogging($log.warn,  $log.LEVEL.WARN,  context, $log, provider.datetimePattern, provider.datetimeLocale, provider.loggingPattern),
							error	: logEnhancer.enhanceLogging($log.error, $log.LEVEL.ERROR, context, $log, provider.datetimePattern, provider.datetimeLocale, provider.loggingPattern)
						};
					};
				}
			};
		};
	}).

	/*jshint unused:false */

	/*
		Default config and example config as well.
		Overrides default logging pattern and global logLevel
	*/
    config(['logEnhancerProvider', function (logEnhancerProvider) {
        // logEnhancerProvider.datetimePattern = 'LLL';
        // logEnhancerProvider.datetimeLocale = window.navigator.userLanguage || window.navigator.language || 'en';
        // logEnhancerProvider.loggingPattern = '%s::[%s]> ';
        // logEnhancerProvider.logLevels = {'*': logEnhancerProvider.LEVEL.TRACE};
        /*
            // example structure:
            logEnhancerProvider.logLevels = {
                'a.b.c': logEnhancerProvider.LEVEL.TRACE, // trace + debug + info + warn + error
                'a.b.d': logEnhancerProvider.LEVEL.ERROR, // error
                'a.b': logEnhancerProvider.LEVEL.DEBUG, // debug + info + warn + error
                'a': logEnhancerProvider.LEVEL.WARN, // warn + error
                '*': logEnhancerProvider.LEVEL.INFO // info + warn + error
            };
        */
    }]).

	/*jshint unused:true */

    run(['$log', 'logEnhancer', function ($log, logEnhancer) {
        if (!sprintf) {
            $log.warn("sprintf.js not found: https://github.com/alexei/sprintf.js, using fixed layout pattern '%s::[%s]> '");
        }
        if (!moment) {
            $log.warn("moment.js not found: http://momentjs.com, using simple Date format");
        }
        logEnhancer.enhanceAngularLog($log);
		$log.info('logging enhancer initiated');
    }]);
}(window.loggingEnhancer, window.angular, window.sprintf, window.moment));<|endoftext|>


<commit_before>

/*    Copyright 2016 Firewalla LLC
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
'use strict';
let log = require('../net2/logger.js')(__filename);

const TimeSeries = require('redis-timeseries')

const redis = require("redis");
const rclient = redis.createClient();

const timeSeries = new TimeSeries(rclient, "timedTraffic")
timeSeries.granularities = {
  '1minute'  : { ttl: timeSeries.hours(1)  , duration: timeSeries.minutes(1) },
  '5minutes' : { ttl: timeSeries.days(1)   , duration: timeSeries.minutes(5) },
  '10minutes': { ttl: timeSeries.days(1)   , duration: timeSeries.minutes(10) },
  '1hour'    : { ttl: timeSeries.days(1)   , duration: timeSeries.hours(1) },
  '1day'     : { ttl: timeSeries.days(30) , duration: timeSeries.days(1) },
  '1month'     : { ttl: timeSeries.months(24) , duration: timeSeries.months(1) }
}

module.exports = {
  getTimeSeries: function() {return timeSeries}
}<commit_msg>revert<commit_after>

/*    Copyright 2016 Firewalla LLC
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
'use strict';
let log = require('../net2/logger.js')(__filename);

const TimeSeries = require('redis-timeseries')

const redis = require("redis");
const rclient = redis.createClient();

const timeSeries = new TimeSeries(rclient, "timedTraffic")
timeSeries.granularities = {
  '1minute'  : { ttl: timeSeries.hours(1)  , duration: timeSeries.minutes(1) },
  '5minutes' : { ttl: timeSeries.days(1)   , duration: timeSeries.minutes(5) },
  '10minutes': { ttl: timeSeries.days(1)   , duration: timeSeries.minutes(10) },
  '1hour'    : { ttl: timeSeries.days(7)   , duration: timeSeries.hours(1) },
  '1day'     : { ttl: timeSeries.weeks(52) , duration: timeSeries.days(1) },
  '1month'     : { ttl: timeSeries.months(24) , duration: timeSeries.months(1) }
}

module.exports = {
  getTimeSeries: function() {return timeSeries}
}<|endoftext|>


<commit_before>/**
 * AngularJSReact
 *
 * Easily consume React components in an Angular app.
 * Three types of attributes are available, input prop attributes, callback prop attributes, and
 * ref attributes.
 *
 * Input Attributes
 * prefix: re-in-
 * value: an angular expression that is watched (deeply) and the value is passed to
 * the react component.
 *
 * Callback Attributes
 * prefix: re-cb-
 * value: an angular expression that is evaluated when the callback is called.
 *        An `args` variable is available to the expression which will contain an array of the
 *        arguments from the react callback.
 *
 * Ref Attribute
 * name: re-ref
 * value: an angular expression that is evaluated when the ref callback is called by react.
 *        the reference will be available as `ref` when the expression is evaluated.
 *
 * Regular HTML attributes as well as many angular directives can still be used in conjunction
 * with the above attributes.
 *
 * @example
 *
 * JS
 * import directify from 'angularjs-react.umd.js';
 * import MyComponent = from 'myComponent.jsx';
 * angular.module('app').directive('myComponent', directify(MyComponent));
 *
 * HTML
 * <my-component
 *   re-in-value="data.value"
 *   re-cb-on-open="handleOpenEvent(args[0])"
 *   re-ref="controller.reactRef = ref"
 *   ng-class="{stylish: true}"
 *   id="my-component-123">
 *     {{someAngularExpression}}
 * </my-component>
 */

import React from 'react';
import ReactDOM from 'react-dom';
import angular from 'angular';

import _ from './lodashReplacement';

const INPUT_PREFIX = 'reIn';
const INPUT_PREFIX_REGEXP = new RegExp(`^${INPUT_PREFIX}[A-Z]`);
const INPUT_ATTR_PREFIX = 're-in-';
const INPUT_ATTR_PREFIX_REGEXP = new RegExp(`^${INPUT_ATTR_PREFIX}`);
const CALLBACK_PREFIX = 'reCb';
const CALLBACK_PREFIX_REGEXP = new RegExp(`^${CALLBACK_PREFIX}[A-Z]`);
const REF_ATTR = 'reRef';
const REF_ATTR_REGEXP = new RegExp(`^${REF_ATTR}$`);

class AngularjsReact {

  constructor(component, $compile, $timeout) {
    this.acceptsChildren = !component.propTypes || !!component.propTypes.children;
    this.component = React.createFactory(component);
    this.$compile = $compile;
    this.$timeout = $timeout;
  }

  restrict = 'E';
  scope = true;

  compile = (element) => {
    const definition = {};
    definition.hasChildren = this.acceptsChildren && !!element.html().trim();
    if (definition.hasChildren) {
      definition.innerHtml = element.html();
      definition.contents = element.contents();
      definition.contents.splice(0).forEach((e) => {
        angular.element(e).detach();
      });
    }
    return this.link(definition);
  };

  link = (definition) => ($scope, $elem, $attrs) => {
    const replace = $attrs.reReplace || $attrs.reReplace === "";
    const elem = $elem[0];
    const index = elem.parentNode && [...elem.parentNode.childNodes].indexOf(elem);
    const reactParent = replace ? elem.cloneNode(false) : elem;

    let angularParent;
    if (definition.hasChildren) {
      let content;
      try {
        content = this.$compile(definition.innerHtml)($scope);
      } catch(e) {
        content = definition.contents;
      }
      angularParent = angular.element(elem.cloneNode(false));
      angularParent.append(content);
    }

    const props = {};
    let refCallbacks;
    let renderPending = false;

    const transclude = (ref, content) => {
      if (renderPending) {
        /* eslint-disable react/no-find-dom-node */
        const node = ReactDOM.findDOMNode(ref);
        /* eslint-disable no-undef */
        angular.element(node).replaceWith(content);
      }
    };

    const getChildren = (parent) => {
      if ([].slice.call(parent[0].attributes || []).filter(a => a.name === 're-react').length) {
        const result = parent.contents().splice(0)
          .filter(e => e.tagName)
          .map(e => {
          const el = angular.element(e);
          const inputAttrs = [].slice.call(e.attributes || [])
            .filter(a => a.name.match(INPUT_ATTR_PREFIX_REGEXP));
          const inputProps = _(inputAttrs)
            .keyBy(a => a.name.substr(INPUT_ATTR_PREFIX.length, 1).toLowerCase()
              + a.name.substr(INPUT_ATTR_PREFIX.length + 1)).value();
          Object.keys(inputProps)
            .forEach(prop => { inputProps[prop] = el.scope().$eval(inputProps[prop].value); });
          return React.createElement(e.tagName, inputProps, getChildren(el));
        });
        if (result.length > 0) {
          return result.length > 1 ? result : result[0];
        }
      }
      return React.createElement('outlet', { ref: ref => transclude(ref, parent.contents()) });
    };

    const render = () => {
      const component = this.component(props);
      const children = definition.hasChildren ? getChildren(angularParent) : undefined;
      ReactDOM.render(React.createElement(
        component.type,
        angular.extend({},
          { ...component.props },
          { ref: ref => {
            if (replace) {
              angular.element(elem.parentNode.childNodes[index]).replaceWith(angular.element(reactParent).contents());
            }
            refCallbacks.forEach(cb => cb(ref));
          } }),
        children), reactParent);
      renderPending = false;
    };

    const scheduleRender = () => {
      if (!renderPending) {
        this.$timeout(render);
        renderPending = true;
      }
    };

    const inputAttrs = Object.keys($attrs).filter((key) => key.match(INPUT_PREFIX_REGEXP));
    const inputProps = inputAttrs.map((key) => key.substr(INPUT_PREFIX.length, 1).toLowerCase()
      + key.substr(INPUT_PREFIX.length + 1));
    inputAttrs.forEach((key, i) => {
      $scope.$watch($attrs[key], (value) => {
        props[inputProps[i]] = value;
        scheduleRender();
      }, true);
      $scope.$watch($attrs[key], (value) => {
        props[inputProps[i]] = value;
        scheduleRender();
      });
    });

    const callbackAttrs = Object.keys($attrs).filter((key) => key.match(CALLBACK_PREFIX_REGEXP));
    const callbackProps = callbackAttrs
      .map((key) => key.substr(CALLBACK_PREFIX.length, 1).toLowerCase()
        + key.substr(CALLBACK_PREFIX.length + 1));
    callbackAttrs.forEach((key, i) => {
      props[callbackProps[i]] = (...args) => {
        this.$timeout(() => $scope.$eval($attrs[key], { args }));
      };
    });

    refCallbacks = Object.keys($attrs).filter((key) => key.match(REF_ATTR_REGEXP))
      .map((key) => (ref) => $scope.$eval($attrs[key], { ref }));

    $scope.$on('$destroy', () => {
      ReactDOM.unmountComponentAtNode(reactParent);
    });

    scheduleRender();
  };

}

export default (component) => {
  const factory = ($compile, $timeout) => new AngularjsReact(component, $compile, $timeout);
  factory.$inject = ['$compile', '$timeout'];
  return factory;
};
<commit_msg>Refactored main logic into Instance class.<commit_after>/**
 * AngularJSReact
 *
 * Easily consume React components in an Angular app.
 * Three types of attributes are available, input prop attributes, callback prop attributes, and
 * ref attributes.
 *
 * Input Attributes
 * prefix: re-in-
 * value: an angular expression that is watched (deeply) and the value is passed to
 * the react component.
 *
 * Callback Attributes
 * prefix: re-cb-
 * value: an angular expression that is evaluated when the callback is called.
 *        An `args` variable is available to the expression which will contain an array of the
 *        arguments from the react callback.
 *
 * Ref Attribute
 * name: re-ref
 * value: an angular expression that is evaluated when the ref callback is called by react.
 *        the reference will be available as `ref` when the expression is evaluated.
 *
 * Regular HTML attributes as well as many angular directives can still be used in conjunction
 * with the above attributes.
 *
 * @example
 *
 * JS
 * import directify from 'angularjs-react.umd.js';
 * import MyComponent = from 'myComponent.jsx';
 * angular.module('app').directive('myComponent', directify(MyComponent));
 *
 * HTML
 * <my-component
 *   re-in-value="data.value"
 *   re-cb-on-open="handleOpenEvent(args[0])"
 *   re-ref="controller.reactRef = ref"
 *   ng-class="{stylish: true}"
 *   id="my-component-123">
 *     {{someAngularExpression}}
 * </my-component>
 */

import React from 'react';
import ReactDOM from 'react-dom';
import angular from 'angular';

import _ from './lodashReplacement';

const INPUT_PREFIX = 'reIn';
const INPUT_PREFIX_REGEXP = new RegExp(`^${INPUT_PREFIX}[A-Z]`);
const INPUT_ATTR_PREFIX = 're-in-';
const INPUT_ATTR_PREFIX_REGEXP = new RegExp(`^${INPUT_ATTR_PREFIX}`);
const CALLBACK_PREFIX = 'reCb';
const CALLBACK_PREFIX_REGEXP = new RegExp(`^${CALLBACK_PREFIX}[A-Z]`);
const REF_ATTR = 'reRef';
const REF_ATTR_REGEXP = new RegExp(`^${REF_ATTR}$`);

class AngularjsReact {

  constructor(component, $compile, $timeout) {
    this.acceptsChildren = !component.propTypes || !!component.propTypes.children;
    this.component = React.createFactory(component);
    this.$compile = $compile;
    this.$timeout = $timeout;
  }

  restrict = 'E';
  scope = true;

  compile = (element) => {
    const markup = {};
    markup.hasChildren = this.acceptsChildren && !!element.html().trim();
    if (markup.hasChildren) {
      markup.innerHtml = element.html();
      markup.contents = element.contents();
      markup.contents.splice(0).forEach((e) => {
        angular.element(e).detach();
      });
    }
    return this.getLinker(markup);
  };

  getLinker = (markup) => ($scope, $elem, $attrs) => {
    let instance = new Instance(this, markup);
    instance.link($scope, $elem, $attrs);
  }

}

class Instance {

  constructor(Directive, markup) {
    this.component = Directive.component;
    this.$compile = Directive.$compile;
    this.$timeout = Directive.$timeout;
    this.markup = markup;
    this.renderPending = false;
    this.props = {};
  }

  link = ($scope, $elem, $attrs) => {
    this.$scope = $scope;
    this.elem = $elem[0];
    this.$attrs = $attrs;

    this.replace = this.$attrs.reReplace || this.$attrs.reReplace === "";
    this.nodeIndex = this.elem.parentNode && [...this.elem.parentNode.childNodes].indexOf(this.elem);
    this.reactParent = this.replace ? this.elem.cloneNode(false) : this.elem;

    if (this.markup.hasChildren) {
      let content;
      try {
        content = this.$compile(this.markup.innerHtml)(this.$scope);
      } catch(e) {
        content = this.markup.contents;
      }
      this.angularParent = angular.element(this.elem.cloneNode(false));
      this.angularParent.append(content);
    }

    this.setupInputs();
    this.setupCallbacks();
    this.setupRefCallbacks();

    this.$scope.$on('$destroy', () => {
      ReactDOM.unmountComponentAtNode(this.reactParent);
    });

    this.scheduleRender();
  };

  transclude = (ref, content) => {
    if (this.renderPending) {
      const node = ReactDOM.findDOMNode(ref);
      angular.element(node).replaceWith(content);
    }
  };

  getChildren = (parent) => {
    if ([].slice.call(parent[0].attributes || []).filter(a => a.name === 're-react').length) {
      const result = parent.contents().splice(0)
        .filter(e => e.tagName)
        .map(e => {
          const el = angular.element(e);
          const inputAttrs = [].slice.call(e.attributes || [])
            .filter(a => a.name.match(INPUT_ATTR_PREFIX_REGEXP));
          const inputProps = _(inputAttrs)
            .keyBy(a => a.name.substr(INPUT_ATTR_PREFIX.length, 1).toLowerCase()
              + a.name.substr(INPUT_ATTR_PREFIX.length + 1)).value();
          Object.keys(inputProps)
            .forEach(prop => { inputProps[prop] = el.scope().$eval(inputProps[prop].value); });
          return React.createElement(e.tagName, inputProps, this.getChildren(el));
        });
      if (result.length > 0) {
        return result.length > 1 ? result : result[0];
      }
    }
    return React.createElement('outlet', { ref: ref => this.transclude(ref, parent.contents()) });
  };

  render = () => {
    const component = this.component(this.props);
    const children = this.markup.hasChildren ? this.getChildren(this.angularParent) : undefined;
    ReactDOM.render(React.createElement(
      component.type,
      angular.extend({},
        { ...component.props },
        { ref: ref => {
          if (this.replace) {
            angular.element(this.elem.parentNode.childNodes[this.nodeIndex]).replaceWith(angular.element(this.reactParent).contents());
          }
          this.refCallbacks.forEach(cb => cb(ref));
        } }),
      children), this.reactParent);
    this.renderPending = false;
  };

  scheduleRender = () => {
    if (!this.renderPending) {
      this.$timeout(this.render);
      this.renderPending = true;
    }
  };

  setupInputs = () => {
    let inputAttrs = Object.keys(this.$attrs).filter((key) => key.match(INPUT_PREFIX_REGEXP));
    let inputProps = inputAttrs.map((key) => key.substr(INPUT_PREFIX.length, 1).toLowerCase()
      + key.substr(INPUT_PREFIX.length + 1));
    inputAttrs.forEach((key, i) => {
      this.$scope.$watch(this.$attrs[key], (value) => {
        this.props[inputProps[i]] = value;
        this.scheduleRender();
      }, true);
      this.$scope.$watch(this.$attrs[key], (value) => {
        this.props[inputProps[i]] = value;
        this.scheduleRender();
      });
    });
  };

  setupCallbacks = () => {
    let callbackAttrs = Object.keys(this.$attrs).filter((key) => key.match(CALLBACK_PREFIX_REGEXP));
    let callbackProps = callbackAttrs
      .map((key) => key.substr(CALLBACK_PREFIX.length, 1).toLowerCase()
        + key.substr(CALLBACK_PREFIX.length + 1));
    callbackAttrs.forEach((key, i) => {
      this.props[callbackProps[i]] = (...args) => {
        this.$timeout(() => this.$scope.$eval(this.$attrs[key], { args }));
      };
    });
  };

  setupRefCallbacks = () => {
    this.refCallbacks = Object.keys(this.$attrs).filter((key) => key.match(REF_ATTR_REGEXP))
      .map((key) => (ref) => this.$scope.$eval(this.$attrs[key], { ref }));
  };

}

export default (component) => {
  const factory = ($compile, $timeout) => new AngularjsReact(component, $compile, $timeout);
  factory.$inject = ['$compile', '$timeout'];
  return factory;
};
<|endoftext|>


<commit_before>/**
 * Created by k186 on 2016/12/28.
 */
class urlMapping {
    constructor () {
        this.isLocal = window.location.hostname.toUpperCase() === 'LOCALHOST';
    }

    Mapping (url) {
        let urls = {
            /*获取搜索历史记录*/
            'GET_SEARCH_HISTORY': (this.isLocal ? '' : this.hostname) + '../../static/mokData/musicPlayer/history' + (this.isLocal ? '.json' : '.json'),
            /*搜索结构*/
            'GET_SEARCH_RESULT': (this.isLocal ? '' : this.hostname) + '../../static/mokData/musicPlayer/searchResult' + (this.isLocal ? '.json' : '.json'),
            /*个性电台*/
            'GET_PERSONAL_RADIO': (this.isLocal ? '' : this.hostname) + '../../static/mokData/musicPlayer/personalRadio' + (this.isLocal ? '.json' : '.json'),
            /*个性电台初始化*/
            'GET_PERSONAL_RADIO_INIT': (this.isLocal ? '' : this.hostname) + '../../static/mokData/musicPlayer/radioInit' + (this.isLocal ? '.json' : '.json'),
            /*更新收藏列表*/
            'GET_UPDATE_FAVOURITE': (this.isLocal ? '' : this.hostname) + '../../static/mokData/musicPlayer/updatefavourite' + (this.isLocal ? '.json' : '.json'),
            /*初始化用户信息*/
            'GET_INIT_USER_DATA': (this.isLocal ? '' : this.hostname) + '../../static/mokData/musicPlayer/userdata' + (this.isLocal ? '.json' : '.json'),
        };
        return urls[url]
    }

    ajaxGetData (options) {
        let that=this;
        let url=that.Mapping(options.url);
        if(!url){
            return  options.callback({success: false,message:'路由错误'});
        }
        $.ajax({
            url: url,
            type: options.type || 'get',
            data: options.data,
            cache: false,
            async: true,
            contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
            success: function(data) {
                if(data.constructor == String) {
                    try{
                        data = JSON.parse(data);
                    } catch(e){
                        if(data == '') {
                            data = {success: false,message:'请求错误'};
                        }
                    }
                }
                options.callback(data);
            },
            error: function() {
                options.callback({success: false,message:'请求错误'});
            }
        });
    }
}
export default urlMapping<commit_msg>todo cdn<commit_after>/**
 * Created by k186 on 2016/12/28.
 */
class urlMapping {
    constructor () {
        this.isLocal = window.location.hostname.toUpperCase() === 'LOCALHOST';
    }

    Mapping (url) {
        let urls = {
            /*获取搜索历史记录*/
            'GET_SEARCH_HISTORY': (this.isLocal ? '' : 'http://olpmg8rkp.bkt.clouddn.com') + '/static/mokData/musicPlayer/history' + (this.isLocal ? '.json' : '.json'),
            /*搜索结构*/
            'GET_SEARCH_RESULT': (this.isLocal ? '' : 'http://olpmg8rkp.bkt.clouddn.com') + '/static/mokData/musicPlayer/searchResult' + (this.isLocal ? '.json' : '.json'),
            /*个性电台*/
            'GET_PERSONAL_RADIO': (this.isLocal ? '' : 'http://olpmg8rkp.bkt.clouddn.com') + '/static/mokData/musicPlayer/personalRadio' + (this.isLocal ? '.json' : '.json'),
            /*个性电台初始化*/
            'GET_PERSONAL_RADIO_INIT': (this.isLocal ? '' : 'http://olpmg8rkp.bkt.clouddn.com') + '/static/mokData/musicPlayer/radioInit' + (this.isLocal ? '.json' : '.json'),
            /*更新收藏列表*/
            'GET_UPDATE_FAVOURITE': (this.isLocal ? '' : 'http://olpmg8rkp.bkt.clouddn.com') + '/static/mokData/musicPlayer/updatefavourite' + (this.isLocal ? '.json' : '.json'),
            /*初始化用户信息*/
            'GET_INIT_USER_DATA': (this.isLocal ? '' : 'http://olpmg8rkp.bkt.clouddn.com') + '/static/mokData/musicPlayer/userdata' + (this.isLocal ? '.json' : '.json'),
        };
        return urls[url]
    }

    ajaxGetData (options) {
        let that=this;
        let url=that.Mapping(options.url);
        if(!url){
            return  options.callback({success: false,message:'路由错误'});
        }
        $.ajax({
            url: url,
            type: options.type || 'get',
            data: options.data,
            cache: false,
            async: true,
            contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
            success: function(data) {
                if(data.constructor == String) {
                    try{
                        data = JSON.parse(data);
                    } catch(e){
                        if(data == '') {
                            data = {success: false,message:'请求错误'};
                        }
                    }
                }
                options.callback(data);
            },
            error: function() {
                options.callback({success: false,message:'请求错误'});
            }
        });
    }
}
export default urlMapping<|endoftext|>