<commit_before>var REFERER_STORE = [
    [
        [
            'search?q=',
            'xjs/_/js/',
            'images/nav_logo242.png',
            'gen_204?',
            'imghover?',
            'async/irc?',
            'imgrc?',
            'ajax/pi/imgdisc?',
            'imgevent?',
            'url?sa=',
            'client_204?&atyp',
            'complete/search?',
            //'s?sclient' // これはオンにしてはいけない。URLが動的に切り替わってしまう(戒め)
        ],
        'https://www.google.co.jp/'
    ],
];

function lookupReferer(wholePath) {
    for (var i = 0; i < REFERER_STORE.length; i++) {
        var store = REFERER_STORE[i];
        for (var j = 0; j < store[0].length; j++) {
            var partOfPath = store[0][j];
            if (wholePath.indexOf(partOfPath) >= 0) {
                return store[1];
            }
        }
    }

    return null;
}

module.exports = lookupReferer;<commit_msg>facebookのrefererDictionaryを追加<commit_after>var REFERER_STORE = [
    [
        [
            'search?q=',
            'xjs/_/js/',
            'images/nav_logo242.png',
            'gen_204?',
            'imghover?',
            'async/irc?',
            'imgrc?',
            'ajax/pi/imgdisc?',
            'imgevent?',
            'url?sa=',
            'client_204?&atyp',
            'complete/search?',
            //'s?sclient' // これはオンにしてはいけない。URLが動的に切り替わってしまう(戒め)
        ],
        'https://www.google.co.jp/'
    ],
    [
        [
            'intern/common/referer_frame.php'
        ],
        'https://www.facebook.com/'
    ]
];

function lookupReferer(wholePath) {
    for (var i = 0; i < REFERER_STORE.length; i++) {
        var store = REFERER_STORE[i];
        for (var j = 0; j < store[0].length; j++) {
            var partOfPath = store[0][j];
            if (wholePath.indexOf(partOfPath) >= 0) {
                return store[1];
            }
        }
    }

    return null;
}

module.exports = lookupReferer;<|endoftext|>


<commit_before>import React, {PropTypes} from 'react'
import {Flex, Inline} from 'jsxstyle'
import FileDrop from 'react-file-drop'
import ipc from 'electron-safe-ipc/guest'

import SimpleStat from '../simple-stat'
import IconButton from '../icon-button'
import Icon from '../icon'

import 'normalize.css'
import 'css-box-sizing-border-box/index.css'
import '../../../styles/common.css'
import '../../../styles/fonts.css'
import '../../../styles/file-drop.less'

const stopButtonStyles = {
  background: 'none',
  border: 'none',
  position: 'absolute',
  top: '11px',
  right: '0'
}

export default class ProfileScreen extends React.Component {

  static propTypes = {
    peers: PropTypes.number,
    location: PropTypes.string,
    onStopClick: PropTypes.func,
    onConsoleClick: PropTypes.func,
    onBrowserClick: PropTypes.func,
    onSettingsClick: PropTypes.func
  }

  static defaultProps = {
    peers: 0,
    location: '',
    onStopClick () {},
    onConsoleClick () {},
    onBrowserClick () {},
    onSettingsClick () {}
  }

  _onFileDrop = (files, event) => {
    const filesArray = []
    for (let i = 0; i < files.length; i++) {
      filesArray.push(files[i].path)
    }

    ipc.send('drop-files', null, filesArray)
  }

  render () {
    return (
      <Flex
        width='100%'
        height='100%'
        backgroundColor='#19b5fe'
        color='#FFFFFF'
        flexDirection='column'
        alignItems='center'
        >
        <FileDrop
          onDrop={this._onFileDrop}
          />
        <Flex
          height='40px'>
          <Inline
            alignSelf='center'
            flex='1'
            paddingTop='4px'
            >
            IPFS
          </Inline>
          <IconButton
            icon='cross'
            onClick={this.props.onStopClick}
            style={stopButtonStyles}
            iconStyle={{fontSize: '21px'}}
            />
        </Flex>
        <Flex
          flex='1'
          color='#FFFFFF'
          backgroundImage={`url(${require('../../../img/stars.png')})`}
          backgroundSize='100%'
          backgroundPosition='0 0'
          width='100%'
          alignItems='center'
          justifyContent='center'
          flexDirection='column'
          >
          <Icon name='location' style={{padding: '10px 0', fontSize: '32px'}}/>
          <Inline margin='0 auto'>
            {this.props.location}
          </Inline>
        </Flex>
        <Flex
          flex='1'
          backgroundColor='#FFFFFF'
          color='#000000'
          width='100%'
          height='30%'
          justifyContent='space-around'
          >
          <SimpleStat
            name='peers'
            value={this.props.peers}
            color='#50d2c2'
            />
        </Flex>
        <Flex
          height='70px'
          justifyContent='space-around'
          width='100%'
          >
          <IconButton
            name='Console'
            icon='gaming'
            onClick={this.props.onConsoleClick}
            />
          <IconButton
            name='Browser'
            icon='window'
            onClick={this.props.onBrowserClick}
            />
          <IconButton
            name='Settings'
            icon='gear'
            onClick={this.props.onSettingsClick}
            />
        </Flex>
      </Flex>
    )
  }
}
<commit_msg>Do not show settings for now<commit_after>import React, {PropTypes} from 'react'
import {Flex, Inline} from 'jsxstyle'
import FileDrop from 'react-file-drop'
import ipc from 'electron-safe-ipc/guest'

import SimpleStat from '../simple-stat'
import IconButton from '../icon-button'
import Icon from '../icon'

import 'normalize.css'
import 'css-box-sizing-border-box/index.css'
import '../../../styles/common.css'
import '../../../styles/fonts.css'
import '../../../styles/file-drop.less'

const stopButtonStyles = {
  background: 'none',
  border: 'none',
  position: 'absolute',
  top: '11px',
  right: '0'
}

export default class ProfileScreen extends React.Component {

  static propTypes = {
    peers: PropTypes.number,
    location: PropTypes.string,
    onStopClick: PropTypes.func,
    onConsoleClick: PropTypes.func,
    onBrowserClick: PropTypes.func,
    onSettingsClick: PropTypes.func
  }

  static defaultProps = {
    peers: 0,
    location: '',
    onStopClick () {},
    onConsoleClick () {},
    onBrowserClick () {},
    onSettingsClick () {}
  }

  _onFileDrop = (files, event) => {
    const filesArray = []
    for (let i = 0; i < files.length; i++) {
      filesArray.push(files[i].path)
    }

    ipc.send('drop-files', null, filesArray)
  }

  render () {
    return (
      <Flex
        width='100%'
        height='100%'
        backgroundColor='#19b5fe'
        color='#FFFFFF'
        flexDirection='column'
        alignItems='center'
        >
        <FileDrop
          onDrop={this._onFileDrop}
          />
        <Flex
          height='40px'>
          <Inline
            alignSelf='center'
            flex='1'
            paddingTop='4px'
            >
            IPFS
          </Inline>
          <IconButton
            icon='cross'
            onClick={this.props.onStopClick}
            style={stopButtonStyles}
            iconStyle={{fontSize: '21px'}}
            />
        </Flex>
        <Flex
          flex='1'
          color='#FFFFFF'
          backgroundImage={`url(${require('../../../img/stars.png')})`}
          backgroundSize='100%'
          backgroundPosition='0 0'
          width='100%'
          alignItems='center'
          justifyContent='center'
          flexDirection='column'
          >
          <Icon name='location' style={{padding: '10px 0', fontSize: '32px'}}/>
          <Inline margin='0 auto'>
            {this.props.location}
          </Inline>
        </Flex>
        <Flex
          flex='1'
          backgroundColor='#FFFFFF'
          color='#000000'
          width='100%'
          height='30%'
          justifyContent='space-around'
          >
          <SimpleStat
            name='peers'
            value={this.props.peers}
            color='#50d2c2'
            />
        </Flex>
        <Flex
          height='70px'
          justifyContent='space-around'
          width='100%'
          >
          <IconButton
            name='Console'
            icon='gaming'
            onClick={this.props.onConsoleClick}
            />
          <IconButton
            name='Browser'
            icon='window'
            onClick={this.props.onBrowserClick}
            />
        </Flex>
      </Flex>
    )
  }
}
<|endoftext|>


<commit_before>'use strict';

/* Controllers */

angular.module('KMCModule').controller('PlayerEditCtrl',
    ['$scope', 'PlayerData', '$routeParams', '$filter', 'menuSvc', 'PlayerService', 'apiService', 'localStorageService', 'userEntries', '$timeout', '$modal', '$location',
        function($scope, PlayerData, $routeParams, $filter, menuSvc, PlayerService, apiService, localStorageService, userEntries, $timeout, $modal, $location) {
            $scope.ks = localStorageService.get('ks');
            $scope.playerId = PlayerData.id;
            $scope.newPlayer = !$routeParams.id;
            $scope.title = ($routeParams.id) ? $filter('i18n')('Edit player') : $filter('i18n')('New  player');
            $scope.data = PlayerData;
            $scope.data.config = angular.fromJson($scope.data.config)
            $scope.debug = $routeParams.debug;
            $scope.getDebugInfo = function(){
                if ($routeParams.debug){
                    return angular.toJson($scope.data.config);
                }
            }
            $scope.masterData = angular.copy($scope.data);
            $scope.userEntriesList = [];
            $scope.userEntries = userEntries;
            $scope.settings = {};
// set tags
            $scope.tags = [];
// all of the next block is just to show how to push into the tags autocomplete/dropdown the list of available tags should be loaded this way instead,
// the model tags of the player are actually set properly from the ng-model of the tags directive and are not needed here
            if (typeof $scope.data.tags != "undefined" && $scope.data.tags) { //can also be null
                var tags = typeof $scope.data.tags == "string" ? $scope.data.tags.split(",") : $scope.data.tags;
                for (var i = 0; i < tags.length; i++)
                    $scope.tags.push({id: tags[i], text: tags[i]});
            }
//registers the tags to be available to the directive
            menuSvc.registerAction('getTags', function() {
                return $scope.tags;
            });
            angular.forEach($scope.userEntries.objects, function(value) {
                $scope.userEntriesList.push({'id': value.id, 'text': value.name});
            });
            menuSvc.registerAction('listEntries', function() { // those should be the first 20...
                return $scope.userEntriesList;
            });
            menuSvc.registerAction('queryEntries', function(query) {
                var data = {results: []};
                console.log(query.term);
                if (query.term) {
// here you should do some AJAX API call with the query term and then()...
                    angular.forEach($scope.userEntriesList, function(item, key) {
                        if (query.term.toUpperCase() === item.text.substring(0, query.term.length).toUpperCase()) {
                            data.results.push(item);
                        }
                    });
                    return query.callback(data);
                }
                else
                    return query.callback({results: $scope.userEntriesList});

            });

            if (parseFloat($scope.data.version) < PlayerService.getRequiredVersion()) {
                menuSvc.registerAction('update', function() {
                    PlayerService.playerUpdate($scope.data);
                });
            }
            $scope.settings.previewEntry = ( PlayerService.getPreviewEntry()) ? PlayerService.getPreviewEntry() : $scope.userEntriesList[0]; //default entry
            $scope.$watch('settings.previewEntry.id', function(newVal, oldVal) {
                if (newVal != oldVal) {
                    PlayerService.setPreviewEntry($scope.settings.previewEntry);
                    PlayerService.renderPlayer();
                }
            });
            $(document).ready(function() {
                $scope.masterData = angular.copy($scope.data);
                // get the preview entry
                PlayerService.setPreviewEntry($scope.settings.previewEntry);
                PlayerService.renderPlayer();
            });
        }
    ]);

angular.module('KMCModule').controller('editPageDataCntrl', ['$scope', 'apiService', '$modal', '$location', 'menuSvc', 'localStorageService', function($scope, apiService, $modal, $location, menuSvc, localStorageService) {
    var filterData = function(data) {
        return $.map([data], function(value, key) {
            if (typeof value == 'object') { // this is a plugin
                if (typeof value['_featureEnabled'] != 'undefined') { // this is a featureMenu/subMenu plugin
                    if (value['_featureEnabled'] === true) { // it is enabled
                        return value;
                    }
                    else
                        return null; // feature is disabled;
                }
                else
                    return value;
            }
            if (key != '_featureEnabled') {
                return value;
            }
            return null;
        });

    };
    $scope.save = function() {
        var data2Save = filterData($scope.data.config)[0];
        var request = {
            'service': 'uiConf',
            'action': 'update',
            'id': $scope.playerId,
            'uiConf:name': $scope.data.name,
            'uiConf:tags': $scope.data.tags,
            'uiConf:description': $scope.data.description ? $scope.data.description : '',
            'uiConf:config': angular.toJson(data2Save)
        };
        apiService.doRequest(request).then(function(result) {
                // cleanup
                menuSvc.menuScope.playerEdit.$setPristine();
                $scope.masterData = angular.copy($scope.data);
                localStorageService.remove('tempPlayerID');
                // if this is a new player - add it to the players list
                if ($scope.newPlayer) {
                    // prevent the list controller from using the cache the next time the list loads
                    apiService.setCache(false);
                }
                // TODO: replace with floating success message that will disappear after few seconds
                $modal.open({ templateUrl: 'template/dialog/message.html',
                    controller: 'ModalInstanceCtrl',
                    resolve: {
                        settings: function() {
                            return {
                                'title': 'Save Player Settings',
                                'message': 'Player Saved Successfully'
                            };
                        }
                    }
                });
            }, function(msg) {
                $modal.open({ templateUrl: 'template/dialog/message.html',
                    controller: 'ModalInstanceCtrl',
                    resolve: {
                        settings: function() {
                            return {
                                'title': 'Player save failure',
                                'message': msg
                            };
                        }
                    }
                });
            }
        );

    };
    $scope.$watch(function() {
        if (typeof menuSvc.menuScope.playerEdit != 'undefined') {
            if (menuSvc.menuScope.playerEdit.$error) {
                return menuSvc.menuScope.playerEdit.$error;

            }
        }
    }, function(obj, oldVal) {
        if (obj != oldVal) {
            $scope.validationObject = obj;
        }

    });
    $scope.cancel = function() {
        if (menuSvc.menuScope.playerEdit.$pristine) {
            $location.url('/list');
        }
        else {
            var modal = $modal.open(
                { templateUrl: 'template/dialog/message.html',
                    controller: 'ModalInstanceCtrl',
                    resolve: {
                        settings: function() {
                            return {
                                'title': 'Navigation confirmation',
                                message: 'You are about to leave this page without saving, are you sure you want to discard the changes?'
                            };
                        }

                    }});
            modal.result.then(function(result) {
                if (result) {
                    $location.url('/list');
                }
            });
        }
    };
    $scope.saveEnabled = function() {
//instead of using the form dirty state we compare to the master copy.
        if (typeof menuSvc.menuScope.playerEdit != 'undefined') {
            if (menuSvc.menuScope.playerEdit.$valid)
                return !angular.equals($scope.data, $scope.masterData);
            else
                return false;
        }
    };

}])
;<commit_msg>#FEC-896<commit_after>'use strict';

/* Controllers */

angular.module('KMCModule').controller('PlayerEditCtrl',
    ['$scope', 'PlayerData', '$routeParams', '$filter', 'menuSvc', 'PlayerService', 'apiService', 'localStorageService', 'userEntries', '$timeout', '$modal', '$location',
        function($scope, PlayerData, $routeParams, $filter, menuSvc, PlayerService, apiService, localStorageService, userEntries, $timeout, $modal, $location) {
            $scope.ks = localStorageService.get('ks');
            $scope.playerId = PlayerData.id;
            $scope.newPlayer = !$routeParams.id;
            $scope.title = ($routeParams.id) ? $filter('i18n')('Edit player') : $filter('i18n')('New  player');
            $scope.data = PlayerData;
            $scope.debug = $routeParams.debug;
            $scope.getDebugInfo = function(){
                if ($routeParams.debug){
                    return angular.toJson($scope.data.config);
                }
            }
            $scope.masterData = angular.copy($scope.data);
            $scope.userEntriesList = [];
            $scope.userEntries = userEntries;
            $scope.settings = {};
// set tags
            $scope.tags = [];
// all of the next block is just to show how to push into the tags autocomplete/dropdown the list of available tags should be loaded this way instead,
// the model tags of the player are actually set properly from the ng-model of the tags directive and are not needed here
            if (typeof $scope.data.tags != "undefined" && $scope.data.tags) { //can also be null
                var tags = typeof $scope.data.tags == "string" ? $scope.data.tags.split(",") : $scope.data.tags;
                for (var i = 0; i < tags.length; i++)
                    $scope.tags.push({id: tags[i], text: tags[i]});
            }
//registers the tags to be available to the directive
            menuSvc.registerAction('getTags', function() {
                return $scope.tags;
            });
            angular.forEach($scope.userEntries.objects, function(value) {
                $scope.userEntriesList.push({'id': value.id, 'text': value.name});
            });
            menuSvc.registerAction('listEntries', function() { // those should be the first 20...
                return $scope.userEntriesList;
            });
            menuSvc.registerAction('queryEntries', function(query) {
                var data = {results: []};
                console.log(query.term);
                if (query.term) {
// here you should do some AJAX API call with the query term and then()...
                    angular.forEach($scope.userEntriesList, function(item, key) {
                        if (query.term.toUpperCase() === item.text.substring(0, query.term.length).toUpperCase()) {
                            data.results.push(item);
                        }
                    });
                    return query.callback(data);
                }
                else
                    return query.callback({results: $scope.userEntriesList});

            });

            if (parseFloat($scope.data.version) < PlayerService.getRequiredVersion()) {
                menuSvc.registerAction('update', function() {
                    PlayerService.playerUpdate($scope.data);
                });
            }
            $scope.settings.previewEntry = ( PlayerService.getPreviewEntry()) ? PlayerService.getPreviewEntry() : $scope.userEntriesList[0]; //default entry
            $scope.$watch('settings.previewEntry.id', function(newVal, oldVal) {
                if (newVal != oldVal) {
                    PlayerService.setPreviewEntry($scope.settings.previewEntry);
                    PlayerService.renderPlayer();
                }
            });
            $(document).ready(function() {
                $scope.masterData = angular.copy($scope.data);
                // get the preview entry
                PlayerService.setPreviewEntry($scope.settings.previewEntry);
                PlayerService.renderPlayer();
            });
        }
    ]);

angular.module('KMCModule').controller('editPageDataCntrl', ['$scope', 'apiService', '$modal', '$location', 'menuSvc', 'localStorageService', function($scope, apiService, $modal, $location, menuSvc, localStorageService) {
    var filterData = function(data) {
        return $.map([data], function(value, key) {
            if (typeof value == 'object') { // this is a plugin
                if (typeof value['_featureEnabled'] != 'undefined') { // this is a featureMenu/subMenu plugin
                    if (value['_featureEnabled'] === true) { // it is enabled
                        return value;
                    }
                    else
                        return null; // feature is disabled;
                }
                else
                    return value;
            }
            if (key != '_featureEnabled') {
                return value;
            }
            return null;
        });

    };
    $scope.save = function() {
        var data2Save = filterData($scope.data.config)[0];
        var request = {
            'service': 'uiConf',
            'action': 'update',
            'id': $scope.playerId,
            'uiConf:name': $scope.data.name,
            'uiConf:tags': $scope.data.tags,
            'uiConf:description': $scope.data.description ? $scope.data.description : '',
            'uiConf:config': angular.toJson(data2Save)
        };
        apiService.doRequest(request).then(function(result) {
                // cleanup
                menuSvc.menuScope.playerEdit.$setPristine();
                $scope.masterData = angular.copy($scope.data);
                localStorageService.remove('tempPlayerID');
                // if this is a new player - add it to the players list
                if ($scope.newPlayer) {
                    // prevent the list controller from using the cache the next time the list loads
                    apiService.setCache(false);
                }
                // TODO: replace with floating success message that will disappear after few seconds
                $modal.open({ templateUrl: 'template/dialog/message.html',
                    controller: 'ModalInstanceCtrl',
                    resolve: {
                        settings: function() {
                            return {
                                'title': 'Save Player Settings',
                                'message': 'Player Saved Successfully'
                            };
                        }
                    }
                });
            }, function(msg) {
                $modal.open({ templateUrl: 'template/dialog/message.html',
                    controller: 'ModalInstanceCtrl',
                    resolve: {
                        settings: function() {
                            return {
                                'title': 'Player save failure',
                                'message': msg
                            };
                        }
                    }
                });
            }
        );

    };
    $scope.$watch(function() {
        if (typeof menuSvc.menuScope.playerEdit != 'undefined') {
            if (menuSvc.menuScope.playerEdit.$error) {
                return menuSvc.menuScope.playerEdit.$error;

            }
        }
    }, function(obj, oldVal) {
        if (obj != oldVal) {
            $scope.validationObject = obj;
        }

    });
    $scope.cancel = function() {
        if (menuSvc.menuScope.playerEdit.$pristine) {
            $location.url('/list');
        }
        else {
            var modal = $modal.open(
                { templateUrl: 'template/dialog/message.html',
                    controller: 'ModalInstanceCtrl',
                    resolve: {
                        settings: function() {
                            return {
                                'title': 'Navigation confirmation',
                                message: 'You are about to leave this page without saving, are you sure you want to discard the changes?'
                            };
                        }

                    }});
            modal.result.then(function(result) {
                if (result) {
                    $location.url('/list');
                }
            });
        }
    };
    $scope.saveEnabled = function() {
//instead of using the form dirty state we compare to the master copy.
        if (typeof menuSvc.menuScope.playerEdit != 'undefined') {
            if (menuSvc.menuScope.playerEdit.$valid)
                return !angular.equals($scope.data, $scope.masterData);
            else
                return false;
        }
    };

}])
;<|endoftext|>


<commit_before>'use strict';

/* Controllers */

angular.module('KMCModule').controller('PlayerListCtrl',
    ['apiService', 'loadINI', '$location', '$rootScope', '$scope', '$filter', '$modal', '$timeout', '$log', "$compile", "$window", 'localStorageService', 'requestNotificationChannel', 'PlayerService',
        function(apiService, loadINI, $location, $rootScope, $scope, $filter, $modal, $timeout, $log, $compile, $window, localStorageService, requestNotificationChannel, PlayerService) {
            requestNotificationChannel.requestStarted('list');
            $rootScope.lang = 'en-US';
            $scope.search = '';
            $scope.searchSelect2Options = {};
            $scope.currentPage = 1;
            $scope.maxSize = 5;
            // get studio UICONF to setup studio configuration
            var config = null;

            try{
                var kmc = window.parent.kmc;
                if (kmc && kmc.vars && kmc.vars.studio.config) {
                    config = kmc.vars.studio.config;
                    $scope.UIConf = angular.fromJson(config);
                }
            }catch(e){
                $log.error('Could not located parent.kmc: ' + e);
            }

            // if we didin't get the uiconf from kmc.vars - load the configuration from base.ini
            if (!config){
                loadINI.getINIConfig().success(function (data) {
                    $scope.UIConf = data;
                });
            }

            // get players list from KMC
            var playersRequest = {
                'filter:tagsMultiLikeOr': 'kdp3,html5studio',
                'filter:orderBy': '-updatedAt',
                'filter:objTypeEqual': '1',
                'filter:objectType': 'KalturaUiConfFilter',
                'filter:creationModeEqual': '2',
                'ignoreNull': '1',
                'page:objectType': 'KalturaFilterPager',
                'pager:pageIndex': '1',
                'pager:pageSize': '999',
                'service': 'uiConf',
                'action': 'list'
            };
            apiService.doRequest(playersRequest).then(function(data) {
                $scope.data = data.objects;
                $scope.calculateTotalItems();
                PlayerService.cachePlayers(data.objects);
            });
            $scope.filtered = $filter('filter')($scope.data, $scope.search) || [];
            $scope.requiredVersion = PlayerService.getRequiredVersion();
            $scope.calculateTotalItems = function() {
                if ($scope.filtered)
                    $scope.totalItems = $scope.filtered.length;
                else if ($scope.data) {
                    $scope.totalItems = $scope.data.length;
                    return $scope.totalItems;
                }
            };

            $scope.checkVersionNeedsUpgrade = function(item) {
                var html5libVersion = item.html5Url.substr(item.html5Url.indexOf('/v') + 2, 1); // get html5 lib version number from its URL
                return (html5libVersion == "1" || item.config === null); // need to upgrade if the version is lower than 2 or the player doesn't have a config object
            };

            $scope.showSubTitle = true;
            $scope.getThumbnail = function(item) {
                if (typeof item.thumbnailUrl != 'undefined')
                    return item.thumbnailUrl; // TODO: prehaps some checking on the URL validity?
                else return $scope.defaultThumbnailUrl;
            };
            $scope.defaultThumbnailUrl = 'img/mockPlayerThumb.png';
            $scope.$watch('search', function(newValue, oldValue) {
                $scope.showSubTitle = newValue;
                if (newValue.length > 0) {
                    $scope.title = $filter('i18n')('search for') + ' "' + newValue + '"';
                }
                else {
                    if (oldValue)
                        $scope.title = $filter('i18n')('Players list');
                }

                $timeout(function() {
                    $scope.calculateTotalItems();
                }, 100);
            });
            $scope.oldVersionEditText = $filter('i18n')('Warning this player is out of date. \n' +
                'Saving changes to this player upgrade, some features and \n' +
                'design may be lost. (read more about upgrading players)');
            $scope.goToEditPage = function(item, $event) {
                $event.preventDefault();
//TODO filter according to what? we don't have "version" field
                if (!$scope.checkVersionNeedsUpgrade(item)) {
                    $location.path('/edit/' + item.id);
                    return false;
                } else {
                    var msgText = $scope.oldVersionEditText;
                    var modal = $modal.open({
                        templateUrl: 'template/dialog/message.html',
                        controller: 'ModalInstanceCtrl',
                        resolve: {
                            settings: function() {
                                return {
                                    'title': 'Edit confirmation',
                                    'message': msgText
                                };
                            }
                        }
                    });
                    modal.result.then(function(result) {
                        if (result) { // here we should move though an upgrade process before reaching the edit.
                            return  $location.url('edit/' + item.id);
                        }

                    }, function() {
                        return $log.info('edit when outdated modal dismissed at: ' + new Date());
                    });
                }

            };
            $scope.newPlayer = function() {
                $location.path('/new');
            };
            $scope.duplicate = function(item) {
                var newclone = PlayerService.clonePlayer(item);
                newclone.then(function(data) {
                    $location.url('edit/' + data[1].id);
                });
//
// $scope.data.splice($scope.data.indexOf(item) + 1, 0, item);
            };
// TODO: preview action...
            $scope.deletePlayer = function(item) {
                var modal = $modal.open({
                    templateUrl: 'template/dialog/message.html',
                    controller: 'ModalInstanceCtrl',
                    resolve: {
                        settings: function() {
                            return {
                                'title': 'Delete confirmation',
                                'message': 'Are you sure you want to delete the player?'
                            };
                        }
                    }
                });
                modal.result.then(function(result) {
                    if (result)
                        PlayerService.deletePlayer(item.id).then(function() {
                            $scope.data.splice($scope.data.indexOf(item), 1);
                        }, function(reason) {
                            $modal.open({ templateUrl: 'template/dialog/message.html',
                                controller: 'ModalInstanceCtrl',
                                resolve: {
                                    settings: function() {
                                        return {
                                            'title': 'Delete failure',
                                            'message': reason
                                        };
                                    }
                                }
                            });
                        });
                }, function() {
                    $log.info('Delete modal dismissed at: ' + new Date());
                });
            };
            $scope.update = function(player) {
                var currentVersion = player.html5Url.split("/v")[1].split("/")[0];
                var text = '' + $filter("i18n")("upgradeMsg") + '

' + $filter("i18n")("upgradeFromVersion") + currentVersion + '
 ' + $filter("i18n")("upgradeToVersion") + $scope.UIConf.html5_version.substr(1) + '';
                var html5lib = player.html5Url.substr(0, player.html5Url.indexOf('/v') + 2) + window.MWEMBED_VERSION + "/mwEmbedLoader.php";
                var modal = $modal.open({
                    templateUrl: 'template/dialog/message.html',
                    controller: 'ModalInstanceCtrl',
                    resolve: {
                        settings: function() {
                            return {
                                'title': 'Update confirmation',
                                'message': text
                            };
                        }
                    }
                });
                modal.result.then(function(result) {
                    if (result)
                        PlayerService.playerUpdate(player, html5lib).then(function(data) {
// update local data (we will not retrieve from the server again)
                            player.config = angular.toJson(data);
                            player.html5Url = html5lib;
                            player.tags = 'html5studio,player';
                        }, function(reason) {
                            $modal.open({ templateUrl: 'template/dialog/message.html',
                                controller: 'ModalInstanceCtrl',
                                resolve: {
                                    settings: function() {
                                        return {
                                            'title': 'Update player failure',
                                            'message': reason
                                        };
                                    }
                                }
                            });
                        });
                }, function() {
                    $log.info('Update player dismissed at: ' + new Date());
                });
            };
        }
    ])
;<commit_msg>removed redundant return statement<commit_after>'use strict';

/* Controllers */

angular.module('KMCModule').controller('PlayerListCtrl',
    ['apiService', 'loadINI', '$location', '$rootScope', '$scope', '$filter', '$modal', '$timeout', '$log', "$compile", "$window", 'localStorageService', 'requestNotificationChannel', 'PlayerService',
        function(apiService, loadINI, $location, $rootScope, $scope, $filter, $modal, $timeout, $log, $compile, $window, localStorageService, requestNotificationChannel, PlayerService) {
            requestNotificationChannel.requestStarted('list');
            $rootScope.lang = 'en-US';
            $scope.search = '';
            $scope.searchSelect2Options = {};
            $scope.currentPage = 1;
            $scope.maxSize = 5;
            // get studio UICONF to setup studio configuration
            var config = null;

            try{
                var kmc = window.parent.kmc;
                if (kmc && kmc.vars && kmc.vars.studio.config) {
                    config = kmc.vars.studio.config;
                    $scope.UIConf = angular.fromJson(config);
                }
            }catch(e){
                $log.error('Could not located parent.kmc: ' + e);
            }

            // if we didin't get the uiconf from kmc.vars - load the configuration from base.ini
            if (!config){
                loadINI.getINIConfig().success(function (data) {
                    $scope.UIConf = data;
                });
            }

            // get players list from KMC
            var playersRequest = {
                'filter:tagsMultiLikeOr': 'kdp3,html5studio',
                'filter:orderBy': '-updatedAt',
                'filter:objTypeEqual': '1',
                'filter:objectType': 'KalturaUiConfFilter',
                'filter:creationModeEqual': '2',
                'ignoreNull': '1',
                'page:objectType': 'KalturaFilterPager',
                'pager:pageIndex': '1',
                'pager:pageSize': '999',
                'service': 'uiConf',
                'action': 'list'
            };
            apiService.doRequest(playersRequest).then(function(data) {
                $scope.data = data.objects;
                $scope.calculateTotalItems();
                PlayerService.cachePlayers(data.objects);
            });
            $scope.filtered = $filter('filter')($scope.data, $scope.search) || [];
            $scope.requiredVersion = PlayerService.getRequiredVersion();
            $scope.calculateTotalItems = function() {
                if ($scope.filtered)
                    $scope.totalItems = $scope.filtered.length;
                else if ($scope.data) {
                    $scope.totalItems = $scope.data.length;
                }
            };

            $scope.checkVersionNeedsUpgrade = function(item) {
                var html5libVersion = item.html5Url.substr(item.html5Url.indexOf('/v') + 2, 1); // get html5 lib version number from its URL
                return (html5libVersion == "1" || item.config === null); // need to upgrade if the version is lower than 2 or the player doesn't have a config object
            };

            $scope.showSubTitle = true;
            $scope.getThumbnail = function(item) {
                if (typeof item.thumbnailUrl != 'undefined')
                    return item.thumbnailUrl; // TODO: prehaps some checking on the URL validity?
                else return $scope.defaultThumbnailUrl;
            };
            $scope.defaultThumbnailUrl = 'img/mockPlayerThumb.png';
            $scope.$watch('search', function(newValue, oldValue) {
                $scope.showSubTitle = newValue;
                if (newValue.length > 0) {
                    $scope.title = $filter('i18n')('search for') + ' "' + newValue + '"';
                }
                else {
                    if (oldValue)
                        $scope.title = $filter('i18n')('Players list');
                }

                $timeout(function() {
                    $scope.calculateTotalItems();
                }, 100);
            });
            $scope.oldVersionEditText = $filter('i18n')('Warning this player is out of date. \n' +
                'Saving changes to this player upgrade, some features and \n' +
                'design may be lost. (read more about upgrading players)');
            $scope.goToEditPage = function(item, $event) {
                $event.preventDefault();
//TODO filter according to what? we don't have "version" field
                if (!$scope.checkVersionNeedsUpgrade(item)) {
                    $location.path('/edit/' + item.id);
                    return false;
                } else {
                    var msgText = $scope.oldVersionEditText;
                    var modal = $modal.open({
                        templateUrl: 'template/dialog/message.html',
                        controller: 'ModalInstanceCtrl',
                        resolve: {
                            settings: function() {
                                return {
                                    'title': 'Edit confirmation',
                                    'message': msgText
                                };
                            }
                        }
                    });
                    modal.result.then(function(result) {
                        if (result) { // here we should move though an upgrade process before reaching the edit.
                            return  $location.url('edit/' + item.id);
                        }

                    }, function() {
                        return $log.info('edit when outdated modal dismissed at: ' + new Date());
                    });
                }

            };
            $scope.newPlayer = function() {
                $location.path('/new');
            };
            $scope.duplicate = function(item) {
                var newclone = PlayerService.clonePlayer(item);
                newclone.then(function(data) {
                    $location.url('edit/' + data[1].id);
                });
//
// $scope.data.splice($scope.data.indexOf(item) + 1, 0, item);
            };
// TODO: preview action...
            $scope.deletePlayer = function(item) {
                var modal = $modal.open({
                    templateUrl: 'template/dialog/message.html',
                    controller: 'ModalInstanceCtrl',
                    resolve: {
                        settings: function() {
                            return {
                                'title': 'Delete confirmation',
                                'message': 'Are you sure you want to delete the player?'
                            };
                        }
                    }
                });
                modal.result.then(function(result) {
                    if (result)
                        PlayerService.deletePlayer(item.id).then(function() {
                            $scope.data.splice($scope.data.indexOf(item), 1);
                        }, function(reason) {
                            $modal.open({ templateUrl: 'template/dialog/message.html',
                                controller: 'ModalInstanceCtrl',
                                resolve: {
                                    settings: function() {
                                        return {
                                            'title': 'Delete failure',
                                            'message': reason
                                        };
                                    }
                                }
                            });
                        });
                }, function() {
                    $log.info('Delete modal dismissed at: ' + new Date());
                });
            };
            $scope.update = function(player) {
                var currentVersion = player.html5Url.split("/v")[1].split("/")[0];
                var text = '' + $filter("i18n")("upgradeMsg") + '

' + $filter("i18n")("upgradeFromVersion") + currentVersion + '
 ' + $filter("i18n")("upgradeToVersion") + $scope.UIConf.html5_version.substr(1) + '';
                var html5lib = player.html5Url.substr(0, player.html5Url.indexOf('/v') + 2) + window.MWEMBED_VERSION + "/mwEmbedLoader.php";
                var modal = $modal.open({
                    templateUrl: 'template/dialog/message.html',
                    controller: 'ModalInstanceCtrl',
                    resolve: {
                        settings: function() {
                            return {
                                'title': 'Update confirmation',
                                'message': text
                            };
                        }
                    }
                });
                modal.result.then(function(result) {
                    if (result)
                        PlayerService.playerUpdate(player, html5lib).then(function(data) {
// update local data (we will not retrieve from the server again)
                            player.config = angular.toJson(data);
                            player.html5Url = html5lib;
                            player.tags = 'html5studio,player';
                        }, function(reason) {
                            $modal.open({ templateUrl: 'template/dialog/message.html',
                                controller: 'ModalInstanceCtrl',
                                resolve: {
                                    settings: function() {
                                        return {
                                            'title': 'Update player failure',
                                            'message': reason
                                        };
                                    }
                                }
                            });
                        });
                }, function() {
                    $log.info('Update player dismissed at: ' + new Date());
                });
            };
        }
    ])
;<|endoftext|>


<commit_before>// use strict
'use strict';

// create eden
var assert  = require ('assert');
var request = require ('supertest');

// describe eden
describe ('EdenJS Event Emitter', () => {
  // test standard event emitter functionality
  it ('should allow event emitter functionality', (done) => {
    // set event function
    global.eden.on ('eefn', (data) => {
      // stop listening
      global.eden.off ('eefn');

      // send done function
      done ();
    });

    // emit event
    global.eden.emit ('eefn');
  });

  // test redis event emitter functionality
  it ('should alow event emitter via redis', (done) => {
    // set event function
    global.eden.on   ('eeredis', (channel, data) => {
      // stop listening
      global.eden.off ('eeredis');

      // send done function
      done ();
    }, true);

    // emit event
    global.eden.emit ('eeredis', true, true);
  });

  // test standard event emitter functionality
  it ('should allow event emitter to pass strings', (done) => {
    // set event function
    global.eden.on   ('eestring', (data) => {
      // stop listening
      global.eden.off ('eestring');

      // send done function
      assert (data === 'true');

      // send done
      done ();
    });

    // emit event
    global.eden.emit ('eestring', 'true');
  });

  // test standard event emitter functionality
  it ('should allow event emitter to pass strings via redis', (done) => {
    // set event function
    global.eden.on   ('eestringredis', (channel, data) => {
      // stop listening
      global.eden.off ('eestringredis');

      // send done function
      assert (data === 'true');

      // send done
      done ();
    }, true);

    // emit event
    global.eden.emit ('eestringredis', 'true', true);
  });

  // test standard event emitter functionality
  it ('should allow event emitter to pass objects', (done) => {
    // set event function
    global.eden.on   ('eeobject', (data) => {
      // stop listening
      global.eden.off ('eeobject');

      // send done function
      assert (data.true && data.true === true);

      // send done
      done ();
    });

    // emit event
    global.eden.emit ('eeobject', {
      'true' : true
    });
  });

  // test standard event emitter functionality
  it ('should allow event emitter to pass objects via redis', (done) => {
    // set event function
    global.eden.on   ('eeobjectredis', (channel, data) => {
      // stop listening
      global.eden.off ('eeobjectredis');

      // send done function
      assert (data.true && data.true === true);

      // send done
      done ();
    }, true);

    // emit event
    global.eden.emit ('eeobjectredis', {
      'true' : true
    }, true);
  });
});
<commit_msg>complete testing edenjs event emitter<commit_after><|endoftext|>


<commit_before>/*
 * Copyright (C) 2004 Baron Schwartz <baron at sequent dot org>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by the
 * Free Software Foundation, version 2.1.
 *
 * 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 Lesser General Public License for more
 * details.
 */

DateFormat = {}

DateFormat.parseFunctions = {count: 0}
DateFormat.parseRegexes = []
DateFormat.formatFunctions = {count: 0}

DateFormat.format = function(dateTime, format, locale) {
  if(DateFormat.formatFunctions[format] == null) {
    DateFormat.createNewFormat(dateTime, format, locale)
  }
  var func = DateFormat.formatFunctions[format]
  return dateTime[func]()
}

DateFormat.shortDateFormat = function(dateTime, locale) {
  return DateFormat.format(dateTime, locale.shortDateFormat, locale)
}

DateFormat.formatRange = function(dateRange, locale) {
  if(dateRange._hasTimes) {
    return  locale.daysLabel(dateRange.days()) + ' ' + locale.hoursLabel(dateRange.hours(), dateRange.minutes())
  } else {
    return DateFormat.shortDateFormat(dateRange.start, locale) + ' - ' + DateFormat.shortDateFormat(dateRange.end, locale)
  }
}

DateFormat.formatDefiningRangeDuration = function(dateRange, locale) {
  var years = parseInt(dateRange.days() / 360, 10)
  if(years > 0) return locale.yearsLabel(years)

  var months = parseInt(dateRange.days() / 30, 10)
  if(months > 0) return locale.monthsLabel(months)

  return locale.daysLabel(dateRange.days())
},

DateFormat.parse = function(input, locale) {
  if(input == 'today') {
    return DateTime.now()
  }
  var date = new Date(input);
  if(isNaN(date.getTime())) {
    throw Error('Could not parse date from "' + input + '"')
  }
  return new DateTime(date, locale)
}

DateFormat.patterns = {
  ISO8601LongPattern: "Y-m-d H:i:s",
  ISO8601ShortPattern: "Y-m-d",
  ShortDatePattern: "n/j/Y",
  FiShortDatePattern: "j.n.Y",
  FiWeekdayDatePattern: "D j.n.Y",
  FiWeekdayDateTimePattern: "D j.n.Y k\\lo G:i",
  LongDatePattern: "l, F d, Y",
  FullDateTimePattern: "l, F d, Y g:i:s A",
  MonthDayPattern: "F d",
  ShortTimePattern: "g:i A",
  LongTimePattern: "g:i:s A",
  SortableDateTimePattern: "Y-m-d\\TH:i:s",
  UniversalSortableDateTimePattern: "Y-m-d H:i:sO",
  YearMonthPattern: "F, Y"
}

DateFormat.parseTime = function(timeStr) {
  var splittedTime = splitTime(timeStr.replace(/:|,/i, '.'))
  var time = [parseInt(splittedTime[0], 10), parseInt(splittedTime[1], 10)]
  return (isHour(time[0]) && isMinute(time[1])) ? time : null

  function splitTime(timeStr) {
    if(timeStr.indexOf('.') != -1) {
      return  timeStr.split('.')
    }
    switch(timeStr.length) {
      case 4:
        return [timeStr.slice(0, 2) , timeStr.slice(2, 4)]
      case 3:
        return [timeStr.slice(0, 1) , timeStr.slice(1, 3)]
      case 2:
        return [timeStr, 0]
      default:
        return [-1, -1]
    }
  }

  function isMinute(minutes) { return !isNaN(minutes) && minutes >= 0 && minutes <= 59 }

  function isHour(hours) { return !isNaN(hours) && hours >= 0 && hours <= 23 }
}

DateFormat.createNewFormat = function(dateTime, format, locale) {
  var funcName = "format" + DateFormat.formatFunctions.count++
  DateFormat.formatFunctions[format] = funcName
  var code = "DateTime.prototype." + funcName + " = function(){return "
  var special = false
  var ch = ''
  for(var i = 0; i < format.length; ++i) {
    ch = format.charAt(i)
    if(!special && ch == "\\") {
      special = true
    } else {
      if(special) {
        special = false
        code += "'" + String.escape(ch) + "' + "
      } else {
        code += DateFormat.getFormatCode(ch, locale)
      }
    }
  }
  eval(code.substring(0, code.length - 3) + ";}")
}

DateFormat.getFormatCode = function(character, locale) {
  switch(character) {
    case "d":
      return "String.leftPad(this.getDate(), 2, '0') + "
    case "D":
      return "locale.dayNames[this.getDay()].substring(0, 3) + "
    case "j":
      return "this.getDate() + "
    case "l":
      return "locale.dayNames[this.getDay()] + "
    case "S":
      return "this.getSuffix() + "
    case "w":
      return "this.getDay() + "
    case "z":
      return "this.getDayOfYear() + "
    case "W":
      return "this.getWeekOfYear() + "
    case "F":
      return "locale.monthNames[this.getMonth()] + "
    case "m":
      return "String.leftPad(this.getMonth() + 1, 2, '0') + "
    case "M":
      return "locale.monthNames[this.getMonth()].substring(0, 3) + "
    case "n":
      return "(this.getMonth() + 1) + "
    case "t":
      return "this.getDaysInMonth() + "
    case "L":
      return "(this.isLeapYear() ? 1 : 0) + "
    case "Y":
      return "this.getFullYear() + "
    case "y":
      return "('' + this.getFullYear()).substring(2, 4) + "
    case "a":
      return "(this.getHours() < 12 ? 'am' : 'pm') + "
    case "A":
      return "(this.getHours() < 12 ? 'AM' : 'PM') + "
    case "g":
      return "((this.getHours() %12) ? this.getHours() % 12 : 12) + "
    case "G":
      return "this.getHours() + "
    case "h":
      return "String.leftPad((this.getHours() %12) ? this.getHours() % 12 : 12, 2, '0') + "
    case "H":
      return "String.leftPad(this.getHours(), 2, '0') + "
    case "i":
      return "String.leftPad(this.getMinutes(), 2, '0') + "
    case "s":
      return "String.leftPad(this.getSeconds(), 2, '0') + "
    case "O":
      return "this.getGMTOffset() + "
    case "T":
      return "this.getTimezone() + "
    case "Z":
      return "(this.getTimezoneOffset() * -60) + "
    default:
      return "'" + String.escape(character) + "' + "
  }
}
<commit_msg>Have default format for shortDateFormat<commit_after>/*
 * Copyright (C) 2004 Baron Schwartz <baron at sequent dot org>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by the
 * Free Software Foundation, version 2.1.
 *
 * 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 Lesser General Public License for more
 * details.
 */

DateFormat = {}

DateFormat.parseFunctions = {count: 0}
DateFormat.parseRegexes = []
DateFormat.formatFunctions = {count: 0}

DateFormat.format = function(dateTime, format, locale) {
  if(DateFormat.formatFunctions[format] == null) {
    DateFormat.createNewFormat(dateTime, format, locale)
  }
  var func = DateFormat.formatFunctions[format]
  return dateTime[func]()
}

DateFormat.shortDateFormat = function(dateTime, locale) {
  return DateFormat.format(dateTime, locale ? locale.shortDateFormat : 'n/j/Y' , locale)
}

DateFormat.formatRange = function(dateRange, locale) {
  if(dateRange._hasTimes) {
    return  locale.daysLabel(dateRange.days()) + ' ' + locale.hoursLabel(dateRange.hours(), dateRange.minutes())
  } else {
    return DateFormat.shortDateFormat(dateRange.start, locale) + ' - ' + DateFormat.shortDateFormat(dateRange.end, locale)
  }
}

DateFormat.formatDefiningRangeDuration = function(dateRange, locale) {
  var years = parseInt(dateRange.days() / 360, 10)
  if(years > 0) return locale.yearsLabel(years)

  var months = parseInt(dateRange.days() / 30, 10)
  if(months > 0) return locale.monthsLabel(months)

  return locale.daysLabel(dateRange.days())
},

DateFormat.parse = function(input, locale) {
  if(input == 'today') {
    return DateTime.now()
  }
  var date = new Date(input);
  if(isNaN(date.getTime())) {
    throw Error('Could not parse date from "' + input + '"')
  }
  return new DateTime(date, locale)
}

DateFormat.patterns = {
  ISO8601LongPattern: "Y-m-d H:i:s",
  ISO8601ShortPattern: "Y-m-d",
  ShortDatePattern: "n/j/Y",
  FiShortDatePattern: "j.n.Y",
  FiWeekdayDatePattern: "D j.n.Y",
  FiWeekdayDateTimePattern: "D j.n.Y k\\lo G:i",
  LongDatePattern: "l, F d, Y",
  FullDateTimePattern: "l, F d, Y g:i:s A",
  MonthDayPattern: "F d",
  ShortTimePattern: "g:i A",
  LongTimePattern: "g:i:s A",
  SortableDateTimePattern: "Y-m-d\\TH:i:s",
  UniversalSortableDateTimePattern: "Y-m-d H:i:sO",
  YearMonthPattern: "F, Y"
}

DateFormat.parseTime = function(timeStr) {
  var splittedTime = splitTime(timeStr.replace(/:|,/i, '.'))
  var time = [parseInt(splittedTime[0], 10), parseInt(splittedTime[1], 10)]
  return (isHour(time[0]) && isMinute(time[1])) ? time : null

  function splitTime(timeStr) {
    if(timeStr.indexOf('.') != -1) {
      return  timeStr.split('.')
    }
    switch(timeStr.length) {
      case 4:
        return [timeStr.slice(0, 2) , timeStr.slice(2, 4)]
      case 3:
        return [timeStr.slice(0, 1) , timeStr.slice(1, 3)]
      case 2:
        return [timeStr, 0]
      default:
        return [-1, -1]
    }
  }

  function isMinute(minutes) { return !isNaN(minutes) && minutes >= 0 && minutes <= 59 }

  function isHour(hours) { return !isNaN(hours) && hours >= 0 && hours <= 23 }
}

DateFormat.createNewFormat = function(dateTime, format, locale) {
  var funcName = "format" + DateFormat.formatFunctions.count++
  DateFormat.formatFunctions[format] = funcName
  var code = "DateTime.prototype." + funcName + " = function(){return "
  var special = false
  var ch = ''
  for(var i = 0; i < format.length; ++i) {
    ch = format.charAt(i)
    if(!special && ch == "\\") {
      special = true
    } else {
      if(special) {
        special = false
        code += "'" + String.escape(ch) + "' + "
      } else {
        code += DateFormat.getFormatCode(ch, locale)
      }
    }
  }
  eval(code.substring(0, code.length - 3) + ";}")
}

DateFormat.getFormatCode = function(character, locale) {
  switch(character) {
    case "d":
      return "String.leftPad(this.getDate(), 2, '0') + "
    case "D":
      return "locale.dayNames[this.getDay()].substring(0, 3) + "
    case "j":
      return "this.getDate() + "
    case "l":
      return "locale.dayNames[this.getDay()] + "
    case "S":
      return "this.getSuffix() + "
    case "w":
      return "this.getDay() + "
    case "z":
      return "this.getDayOfYear() + "
    case "W":
      return "this.getWeekOfYear() + "
    case "F":
      return "locale.monthNames[this.getMonth()] + "
    case "m":
      return "String.leftPad(this.getMonth() + 1, 2, '0') + "
    case "M":
      return "locale.monthNames[this.getMonth()].substring(0, 3) + "
    case "n":
      return "(this.getMonth() + 1) + "
    case "t":
      return "this.getDaysInMonth() + "
    case "L":
      return "(this.isLeapYear() ? 1 : 0) + "
    case "Y":
      return "this.getFullYear() + "
    case "y":
      return "('' + this.getFullYear()).substring(2, 4) + "
    case "a":
      return "(this.getHours() < 12 ? 'am' : 'pm') + "
    case "A":
      return "(this.getHours() < 12 ? 'AM' : 'PM') + "
    case "g":
      return "((this.getHours() %12) ? this.getHours() % 12 : 12) + "
    case "G":
      return "this.getHours() + "
    case "h":
      return "String.leftPad((this.getHours() %12) ? this.getHours() % 12 : 12, 2, '0') + "
    case "H":
      return "String.leftPad(this.getHours(), 2, '0') + "
    case "i":
      return "String.leftPad(this.getMinutes(), 2, '0') + "
    case "s":
      return "String.leftPad(this.getSeconds(), 2, '0') + "
    case "O":
      return "this.getGMTOffset() + "
    case "T":
      return "this.getTimezone() + "
    case "Z":
      return "(this.getTimezoneOffset() * -60) + "
    default:
      return "'" + String.escape(character) + "' + "
  }
}
<|endoftext|>


<commit_before>/*eslint-env node, jasmine*//*global module, inject*/
/*eslint-disable max-statements, max-params*/
import angular from 'angular';
import 'angular-mocks';
import 'luxyflux/ng-luxyflux';

import {
  Store,
  FilterableStore,
  FilterableStoreBehavior,
  TransformableCollection,
  Transformer,
  Annotations
} from 'anglue/anglue';

describe('FilterableStore', () => {
  // Clear the AnnotationCache for unit tests to ensure we create new annotations for each class.
  beforeEach(() => {
    Annotations.clear();
  });

  describe('FilterableStoreBehavior', () => {
    let mockInstance, behavior, refreshSpy, addSpy, removeSpy;
    beforeEach(() => {
      refreshSpy = jasmine.createSpy('refresh');
      addSpy = jasmine.createSpy('addSpy');
      removeSpy = jasmine.createSpy('removeSpy');

      module(angular.module('test', []).name);
      inject(_$filter_ => {
        mockInstance = {
          $filter: _$filter_,
          transformables: {items: {
            refresh: refreshSpy,
            addTransformer: addSpy,
            removeTransformer: removeSpy,
            transformers: []
          }}
        };

        behavior = new FilterableStoreBehavior(mockInstance);
      });
    });

    it('should set default values for its config', () => {
      expect(behavior.collection).toEqual('items');
    });

    it('should read the passed config', () => {
      behavior = new FilterableStoreBehavior(mockInstance, {
        collection: 'foo'
      });
      expect(behavior.collection).toEqual('foo');
    });

    describe('#transformer', () => {
      it('should define a Transformer instance as the transformers property', () => {
        expect(behavior.transformer).toEqual(jasmine.any(Transformer));
      });

      it('should name the transformer filterableStore', () => {
        expect(behavior.transformer.name).toEqual('filterableStore');
      });

      it('should have a noop fn on the transformer', () => {
        const items = ['foo'];
        expect(behavior.transformer.exec(items)).toEqual(items);
      });
    });

    describe('onFilterChange()', () => {
      it('Should be able to filter on property values', () => {
        behavior.onFilterChange('nameFilter', {
          name: 'Optimus'
        });
        const filtered = behavior.transformer.exec([{name: 'Optimus'}, {name: 'Bumblebee'}]);
        expect(filtered).toEqual([{name: 'Optimus'}]);
      });

      it('Should be able to invert filter with !', () => {
        behavior.onFilterChange('nameFilter', {
          name: '!Optimus'
        });
        const filtered = behavior.transformer.exec([{name: 'Optimus'}, {name: 'Bumblebee'}]);
        expect(filtered).toEqual([{name: 'Bumblebee'}]);
      });

      it('should just refresh if there is an active filter transformer', () => {
        behavior.transformableCollection.transformers.push(behavior.transformer);
        behavior.onFilterChange('name');
        expect(addSpy).not.toHaveBeenCalled();
        expect(refreshSpy).toHaveBeenCalled();
      });
    });

    describe('onFilterClear', () => {
      it('When clearing a filter items should return to original state', () => {
        behavior.onFilterChange('nameFilter', {
          property: 'name',
          value: 'Optimus',
          exclude: true
        });
        behavior.onFilterClear('nameFilter');
        const filtered = behavior.transformer.exec([{name: 'Optimus'}, {name: 'Bumblebee'}]);
        expect(filtered).toEqual([{name: 'Optimus'}, {name: 'Bumblebee'}]);
      });
    });

    describe('onSearchChange()', () => {
      it('Should be able to search on property value', () => {
        behavior.onSearchChange('Optimus');
        const filtered = behavior.transformer.exec([{name: 'Optimus'}, {name: 'Bumblebee'}]);

        expect(filtered).toEqual([{name: 'Optimus'}]);
        expect(filtered.length).toEqual(1);
      });
    });

    describe('onSearchClear()', () => {
      it('When clearing the search items should return to original state', () => {
        behavior.onSearchChange('Optimus');
        behavior.onSearchClear();
        const filtered = behavior.transformer.exec([{name: 'Optimus'}, {name: 'Bumblebee'}]);
        expect(filtered).toEqual([{name: 'Optimus'}, {name: 'Bumblebee'}]);
      });
    });

    describe('combine filter and search()', () => {
      it('Applying both a filter and search should work', () => {
        behavior.onSearchChange('Optimus');
        behavior.onFilterChange('nameFilter', {
          name: '!Bumblebee'
        });

        const filtered = behavior.transformer.exec([{name: 'Optimus'}, {name: 'Bumblebee'}, {name: 'Foobar'}]);
        expect(filtered).toEqual([{name: 'Optimus'}]);
      });
    });
  });

  describe('@FilterableStore() decorator', () => {
    @Store() @FilterableStore() class TestStore {}
    @Store() @FilterableStore({entity: 'custom'}) class CustomFilterableStore {}
    @Store() @FilterableStore('custom') class CustomFilterableStringStore {}
    @Store() @FilterableStore({collection: 'foo'}) class CollectionStore {}

    let store, customFilterableStore, customFilterableStringStore, collectionStore, $filter;
    beforeEach(() => {
      angular.module('test', [
        'luxyflux',
        TestStore.annotation.module.name,
        CustomFilterableStore.annotation.module.name,
        CustomFilterableStringStore.annotation.module.name,
        CollectionStore.annotation.module.name
      ]).service('ApplicationDispatcher', () => {
        return {
          register() {},
          dispatch() {}
        };
      });

      module('test');
      inject((
        _TestStore_,
        _CustomFilterableStore_,
        _CustomFilterableStringStore_,
        _CollectionStore_,
        _$filter_
      ) => {
        store = _TestStore_;
        customFilterableStore = _CustomFilterableStore_;
        customFilterableStringStore = _CustomFilterableStringStore_;
        collectionStore = _CollectionStore_;
        $filter = _$filter_;
      });
    });

    it('should define the EntityStore API methods on the store', () => {
      [
        'filterableStore',
        'onTestFilterChange',
        'onTestFilterClear'
      ].forEach(api => expect(store[api]).toBeDefined());
    });

    it('should inject $filter on the store', () => {
      expect(store.$filter).toBe($filter);
    });

    it('should make the collection transformable', () => {
      expect(store.transformables.items).toEqual(jasmine.any(TransformableCollection));
    });

    it('should have an instance of FilterableStoreBehavior as the behavior property', () => {
      expect(store.filterableStore).toEqual(jasmine.any(FilterableStoreBehavior));
    });

    it('should use the class name to determine the crud entity by default', () => {
      expect(store.filterableStore.config.entity).toEqual('Test');
    });

    it('should be possible to configure the entity to manage', () => {
      expect(customFilterableStore.filterableStore.config.entity).toEqual('Custom');
    });

    it('should be possible to pass the entity property as a string', () => {
      expect(customFilterableStringStore.filterableStore.config.entity).toEqual('Custom');
    });

    it('should create properly named handlers when configuring the entity', () => {
      expect(customFilterableStore.onCustomFilterChange).toBeDefined();
      expect(customFilterableStore.onCustomFilterClear).toBeDefined();
    });

    it('should use the item property as the collection by default', () => {
      expect(store.filterableStore.collection).toEqual('items');
    });

    it('should be possible to configure the collection property the entities are stored in', () => {
      expect(collectionStore.filterableStore.collection).toEqual('foo');
    });

    it('should add handlers for actions', () => {
      expect(TestStore.handlers)
        .toEqual(jasmine.objectContaining({
          TEST_FILTER_CHANGE: 'onTestFilterChange',
          TEST_FILTER_CLEAR: 'onTestFilterClear',
          TEST_SEARCH_CHANGE: 'onTestSearchChange',
          TEST_SEARCH_CLEAR: 'onTestSearchClear'
        }));
    });
  });
});
<commit_msg>Added checks<commit_after>/*eslint-env node, jasmine*//*global module, inject*/
/*eslint-disable max-statements, max-params*/
import angular from 'angular';
import 'angular-mocks';
import 'luxyflux/ng-luxyflux';

import {
  Store,
  FilterableStore,
  FilterableStoreBehavior,
  TransformableCollection,
  Transformer,
  Annotations
} from 'anglue/anglue';

describe('FilterableStore', () => {
  // Clear the AnnotationCache for unit tests to ensure we create new annotations for each class.
  beforeEach(() => {
    Annotations.clear();
  });

  describe('FilterableStoreBehavior', () => {
    let mockInstance, behavior, refreshSpy, addSpy, removeSpy;
    beforeEach(() => {
      refreshSpy = jasmine.createSpy('refresh');
      addSpy = jasmine.createSpy('addSpy');
      removeSpy = jasmine.createSpy('removeSpy');

      module(angular.module('test', []).name);
      inject(_$filter_ => {
        mockInstance = {
          $filter: _$filter_,
          transformables: {items: {
            refresh: refreshSpy,
            addTransformer: addSpy,
            removeTransformer: removeSpy,
            transformers: []
          }}
        };

        behavior = new FilterableStoreBehavior(mockInstance);
      });
    });

    it('should set default values for its config', () => {
      expect(behavior.collection).toEqual('items');
    });

    it('should read the passed config', () => {
      behavior = new FilterableStoreBehavior(mockInstance, {
        collection: 'foo'
      });
      expect(behavior.collection).toEqual('foo');
    });

    describe('#transformer', () => {
      it('should define a Transformer instance as the transformers property', () => {
        expect(behavior.transformer).toEqual(jasmine.any(Transformer));
      });

      it('should name the transformer filterableStore', () => {
        expect(behavior.transformer.name).toEqual('filterableStore');
      });

      it('should have a noop fn on the transformer', () => {
        const items = ['foo'];
        expect(behavior.transformer.exec(items)).toEqual(items);
      });
    });

    describe('onFilterChange()', () => {
      it('Should be able to filter on property values', () => {
        behavior.onFilterChange('nameFilter', {
          name: 'Optimus'
        });
        const filtered = behavior.transformer.exec([{name: 'Optimus'}, {name: 'Bumblebee'}]);
        expect(filtered).toEqual([{name: 'Optimus'}]);
      });

      it('Should be able to invert filter with !', () => {
        behavior.onFilterChange('nameFilter', {
          name: '!Optimus'
        });
        const filtered = behavior.transformer.exec([{name: 'Optimus'}, {name: 'Bumblebee'}]);
        expect(filtered).toEqual([{name: 'Bumblebee'}]);
      });

      it('should just refresh if there is an active filter transformer', () => {
        behavior.transformableCollection.transformers.push(behavior.transformer);
        behavior.onFilterChange('name');
        expect(addSpy).not.toHaveBeenCalled();
        expect(refreshSpy).toHaveBeenCalled();
      });
    });

    describe('onFilterClear', () => {
      it('When clearing a filter items should return to original state', () => {
        behavior.onFilterChange('nameFilter', {
          name: 'Optimus'
        });
        behavior.onFilterClear('nameFilter');
        const filtered = behavior.transformer.exec([{name: 'Optimus'}, {name: 'Bumblebee'}]);
        expect(filtered).toEqual([{name: 'Optimus'}, {name: 'Bumblebee'}]);
      });
    });

    describe('onSearchChange()', () => {
      it('Should be able to search on property value', () => {
        behavior.onSearchChange('Optimus');
        const filtered = behavior.transformer.exec([{name: 'Optimus'}, {name: 'Bumblebee'}]);

        expect(filtered).toEqual([{name: 'Optimus'}]);
        expect(filtered.length).toEqual(1);
      });
    });

    describe('onSearchClear()', () => {
      it('When clearing the search items should return to original state', () => {
        behavior.onSearchChange('Optimus');
        behavior.onSearchClear();
        const filtered = behavior.transformer.exec([{name: 'Optimus'}, {name: 'Bumblebee'}]);
        expect(filtered).toEqual([{name: 'Optimus'}, {name: 'Bumblebee'}]);
      });
    });

    describe('combine filter and search()', () => {
      it('Applying both a filter and search should work', () => {
        behavior.onSearchChange('Optimus');
        behavior.onFilterChange('nameFilter', {
          name: '!Bumblebee'
        });

        const filtered = behavior.transformer.exec([{name: 'Optimus'}, {name: 'Bumblebee'}, {name: 'Foobar'}]);
        expect(filtered).toEqual([{name: 'Optimus'}]);
      });
    });
  });

  describe('@FilterableStore() decorator', () => {
    @Store() @FilterableStore() class TestStore {}
    @Store() @FilterableStore({entity: 'custom'}) class CustomFilterableStore {}
    @Store() @FilterableStore('custom') class CustomFilterableStringStore {}
    @Store() @FilterableStore({collection: 'foo'}) class CollectionStore {}

    let store, customFilterableStore, customFilterableStringStore, collectionStore, $filter;
    beforeEach(() => {
      angular.module('test', [
        'luxyflux',
        TestStore.annotation.module.name,
        CustomFilterableStore.annotation.module.name,
        CustomFilterableStringStore.annotation.module.name,
        CollectionStore.annotation.module.name
      ]).service('ApplicationDispatcher', () => {
        return {
          register() {},
          dispatch() {}
        };
      });

      module('test');
      inject((
        _TestStore_,
        _CustomFilterableStore_,
        _CustomFilterableStringStore_,
        _CollectionStore_,
        _$filter_
      ) => {
        store = _TestStore_;
        customFilterableStore = _CustomFilterableStore_;
        customFilterableStringStore = _CustomFilterableStringStore_;
        collectionStore = _CollectionStore_;
        $filter = _$filter_;
      });
    });

    it('should define the FilterableStore API methods on the store', () => {
      [
        'filterableStore',
        'onTestFilterChange',
        'onTestFilterClear',
        'onTestSearchChange',
        'onTestSearchClear'
      ].forEach(api => expect(store[api]).toBeDefined());
    });

    it('should inject $filter on the store', () => {
      expect(store.$filter).toBe($filter);
    });

    it('should make the collection transformable', () => {
      expect(store.transformables.items).toEqual(jasmine.any(TransformableCollection));
    });

    it('should have an instance of FilterableStoreBehavior as the behavior property', () => {
      expect(store.filterableStore).toEqual(jasmine.any(FilterableStoreBehavior));
    });

    it('should use the class name to determine the crud entity by default', () => {
      expect(store.filterableStore.config.entity).toEqual('Test');
    });

    it('should be possible to configure the entity to manage', () => {
      expect(customFilterableStore.filterableStore.config.entity).toEqual('Custom');
    });

    it('should be possible to pass the entity property as a string', () => {
      expect(customFilterableStringStore.filterableStore.config.entity).toEqual('Custom');
    });

    it('should create properly named handlers when configuring the entity', () => {
      expect(customFilterableStore.onCustomFilterChange).toBeDefined();
      expect(customFilterableStore.onCustomFilterClear).toBeDefined();
    });

    it('should use the item property as the collection by default', () => {
      expect(store.filterableStore.collection).toEqual('items');
    });

    it('should be possible to configure the collection property the entities are stored in', () => {
      expect(collectionStore.filterableStore.collection).toEqual('foo');
    });

    it('should add handlers for actions', () => {
      expect(TestStore.handlers)
        .toEqual(jasmine.objectContaining({
          TEST_FILTER_CHANGE: 'onTestFilterChange',
          TEST_FILTER_CLEAR: 'onTestFilterClear',
          TEST_SEARCH_CHANGE: 'onTestSearchChange',
          TEST_SEARCH_CLEAR: 'onTestSearchClear'
        }));
    });
  });
});
<|endoftext|>