<commit_before>import { get, set, computed, observer } from '@ember/object';
import { on } from '@ember/object/evented';
import { inject as service } from '@ember/service';
import Resource from '@rancher/ember-api-store/models/resource';
import { hasMany } from '@rancher/ember-api-store/utils/denormalize';
import ResourceUsage from 'shared/mixins/resource-usage';
import Grafana from 'shared/mixins/grafana';
import { equal, alias } from '@ember/object/computed';
import { resolve } from 'rsvp';
import C from 'ui/utils/constants';
import { isEmpty } from '@ember/utils';
import moment from 'moment';

const GRAY_OUT_SCHEDULER_STATUS_PROVIDERS = ['azureaks', 'aliyunkcs'];

export default Resource.extend(Grafana, ResourceUsage, {
  globalStore: service(),
  growl:       service(),
  intl:        service(),
  router:      service(),
  scope:       service(),

  clusterRoleTemplateBindings: hasMany('id', 'clusterRoleTemplateBinding', 'clusterId'),
  etcdbackups:                 hasMany('id', 'etcdbackup', 'clusterId'),
  namespaces:                  hasMany('id', 'namespace', 'clusterId'),
  nodePools:                   hasMany('id', 'nodePool', 'clusterId'),
  nodes:                       hasMany('id', 'node', 'clusterId'),
  projects:                    hasMany('id', 'project', 'clusterId'),
  expiringCerts:               null,
  grafanaDashboardName:        'Cluster',
  isMonitoringReady:           false,
  _cachedConfig:               null,
  machines:                    alias('nodes'),
  roleTemplateBindings:        alias('clusterRoleTemplateBindings'),
  isAKS:                       equal('driver', 'azureKubernetesService'),
  isGKE:                       equal('driver', 'googleKubernetesEngine'),

  conditionsDidChange:        on('init', observer('enableClusterMonitoring', 'conditions.@each.status', function() {
    if ( !get(this, 'enableClusterMonitoring') ) {
      return false;
    }
    const conditions = get(this, 'conditions') || [];

    const ready = conditions.findBy('type', 'MonitoringEnabled');

    const status = ready && get(ready, 'status') === 'True';

    if ( status !== get(this, 'isMonitoringReady') ) {
      set(this, 'isMonitoringReady', status);
    }
  })),

  getAltActionDelete: computed('action.remove', function() { // eslint-disable-line
    return get(this, 'canBulkRemove') ? 'delete' : null;
  }),

  hasSessionToken: computed('annotations', function() {
    const sessionTokenLabel = `${ (get(this, 'annotations') || {})[C.LABEL.EKS_SESSION_TOKEN]  }`;
    let hasSessionToken      = false;

    if (sessionTokenLabel === 'undefined' || sessionTokenLabel === 'false') {
      hasSessionToken = false;
    } else {
      hasSessionToken = true;
    }

    return hasSessionToken;
  }),

  canBulkRemove: computed('action.remove', function() { // eslint-disable-line
    return get(this, 'hasSessionToken') ? false : true;
  }),

  configName: computed(function() {
    const keys = this.allKeys().filter((x) => x.endsWith('Config'));

    for ( let key, i = 0 ; i < keys.length ; i++ ) {
      key = keys[i];
      if ( get(this, key) ) {
        return key;
      }
    }

    return null;
  }),

  isReady: computed('conditions.@each.status', function() {
    return this.hasCondition('Ready');
  }),

  isRKE: computed('configName', function() {
    return get(this, 'configName') === 'rancherKubernetesEngineConfig';
  }),

  provider: computed('configName', 'nodePools.@each.nodeTemplateId', 'driver', function() {
    const pools = get(this, 'nodePools') || [];
    const firstTemplate = get(pools, 'firstObject.nodeTemplate');

    switch ( get(this, 'configName') ) {
    case 'amazonElasticContainerServiceConfig':
      return 'amazoneks';
    case 'azureKubernetesServiceConfig':
      return 'azureaks';
    case 'googleKubernetesEngineConfig':
      return 'googlegke';
    case 'tencentEngineConfig':
      return 'tencenttke';
    case 'aliyunEngineConfig':
      return 'aliyunkcs';
    case 'huaweiEngineConfig':
      return 'huaweicce';
    case 'rancherKubernetesEngineConfig':
      if ( pools.length > 0 ) {
        if ( firstTemplate ) {
          return get(firstTemplate, 'driver');
        } else {
          return 'custom';
        }
      } else {
        return 'custom';
      }
    default:
      if (get(this, 'driver') && get(this, 'configName')) {
        return get(this, 'driver');
      } else {
        return 'import';
      }
    }
  }),

  displayProvider: computed('configName', 'nodePools.@each.displayProvider', 'intl.locale', 'driver', function() {
    const intl = get(this, 'intl');
    const pools = get(this, 'nodePools');
    const firstPool = (pools || []).objectAt(0);

    switch ( get(this, 'configName') ) {
    case 'amazonElasticContainerServiceConfig':
      return intl.t('clusterNew.amazoneks.shortLabel');
    case 'azureKubernetesServiceConfig':
      return intl.t('clusterNew.azureaks.shortLabel');
    case 'googleKubernetesEngineConfig':
      return intl.t('clusterNew.googlegke.shortLabel');
    case 'tencentEngineConfig':
      return intl.t('clusterNew.tencenttke.shortLabel');
    case 'aliyunEngineConfig':
      return intl.t('clusterNew.aliyunkcs.shortLabel');
    case 'huaweiEngineConfig':
      return intl.t('clusterNew.huaweicce.shortLabel');
    case 'rancherKubernetesEngineConfig':
      if ( !!pools ) {
        if ( firstPool ) {
          return get(firstPool, 'displayProvider') ? get(firstPool, 'displayProvider') : intl.t('clusterNew.rke.shortLabel');
        } else {
          return intl.t('clusterNew.rke.shortLabel');
        }
      } else {
        return intl.t('clusterNew.custom.shortLabel');
      }
    default:
      if (get(this, 'driver') && get(this, 'configName')) {
        return get(this, 'driver').capitalize();
      } else {
        return intl.t('clusterNew.import.shortLabel');
      }
    }
  }),

  systemProject: computed('projects.@each.isSystemProject', function() {
    let projects = (get(this, 'projects') || []).filterBy('isSystemProject', true);

    return get(projects, 'firstObject');
  }),

  canSaveMonitor: computed('actionLinks.{editMonitoring,enableMonitoring}', function() {
    const action = get(this, 'enableClusterMonitoring') ?  'editMonitoring' : 'enableMonitoring';

    return !!this.hasAction(action)
  }),

  canDisableMonitor: computed('actionLinks.disableMonitoring', function() {
    return !!this.hasAction('disableMonitoring')
  }),

  defaultProject: computed('projects.@each.{name,clusterOwner}', function() {
    let projects = get(this, 'projects');

    let out = projects.findBy('isDefault');

    if ( out ) {
      return out;
    }

    out = projects.findBy('clusterOwner', true);
    if ( out ) {
      return out;
    }

    out = projects.objectAt(0);

    return out;
  }),

  certsExpiring: computed('certificatesExpiration', function() {
    let { certificatesExpiration = {}, expiringCerts } = this;

    if (!expiringCerts) {
      expiringCerts = [];
    }

    if (!isEmpty(certificatesExpiration)) {
      let expKeys = Object.keys(certificatesExpiration);

      expKeys.forEach((kee) => {
        let certDate  = get(certificatesExpiration[kee], 'expirationDate');
        const expirey = moment(certDate);
        let diff      = expirey.diff(moment());

        if (diff < 2592000000) { // milliseconds in a month
          expiringCerts.pushObject({
            expiringCertName: kee,
            milliUntil:       diff,
            exactDateTime:    certDate
          });
        }
      });

      set(this, 'expiringCerts', expiringCerts);

      return expiringCerts.length > 0;
    }

    return false;
  }),

  availableActions: computed('actionLinks.{rotateCertificates}', function() {
    const a = get(this, 'actionLinks') || {};

    return [
      {
        label:     'action.rotate',
        icon:      'icon icon-history',
        action:    'rotateCertificates',
        enabled:   !!a.rotateCertificates,
      },
      {
        label:     'action.backupEtcd',
        icon:      'icon icon-history',
        action:    'backupEtcd',
        enabled:   !!a.backupEtcd,
      },
      {
        label:     'action.restoreFromEtcdBackup',
        icon:      'icon icon-history',
        action:    'restoreFromEtcdBackup',
        enabled:   !!a.restoreFromEtcdBackup,
      },
    ];
  }),

  isVxlan: computed('rancherKubernetesEngineConfig.network.options.flannel_backend_type', function() {
    const backend = get(this, 'rancherKubernetesEngineConfig.network.options.flannel_backend_type');

    return backend === 'vxlan';
  }),

  isWindows:  computed('windowsPreferedCluster', function() {
    return !!get(this, 'windowsPreferedCluster');
  }),

  unhealthyComponents: computed('componentStatuses.@each.conditions', function() {
    return (get(this, 'componentStatuses') || [])
      .filter((s) => !s.conditions.any((c) => c.status === 'True'));
  }),

  inactiveNodes: computed('nodes.@each.state', function() {
    return get(this, 'nodes').filter( (n) => C.ACTIVEISH_STATES.indexOf(get(n, 'state')) === -1 );
  }),

  displayWarnings: computed('provider', 'inactiveNodes.[]', 'unhealthyComponents.[]', function() {
    const intl = get(this, 'intl');
    const out = [];
    const unhealthyComponents = get(this, 'unhealthyComponents') || [];
    const inactiveNodes = get(this, 'inactiveNodes') || [];
    const provider = get(this, 'provider');

    const grayOut = GRAY_OUT_SCHEDULER_STATUS_PROVIDERS.indexOf(provider) > -1;

    unhealthyComponents.forEach((component) => {
      if ( grayOut && (get(component, 'name') === 'scheduler' || get(component, 'name') === 'controller-manager') ) {
        return;
      }
      out.pushObject(intl.t('clusterDashboard.alert.component', { component: get(component, 'name') }));
    });

    inactiveNodes.forEach((node) => {
      out.pushObject(intl.t('clusterDashboard.alert.node', { node: get(node, 'displayName') }))
    });

    return out;
  }),

  actions: {
    backupEtcd() {
      const getBackupType = () => {
        let services = get(this, 'rancherKubernetesEngineConfig.services.etcd');

        if (get(services, 'cachedConfig')) {
          if (isEmpty(services.cachedConfig.s3BackupConfig)) {
            return 'local';
          } else if (!isEmpty(services.cachedConfig.s3BackupConfig)) {
            return 's3';
          }
        }
      }

      const backupType     = getBackupType();
      const successTitle   = this.intl.t('action.backupEtcdMessage.success.title');
      const successMessage = this.intl.t('action.backupEtcdMessage.success.message', {
        clusterId: this.displayName || this.id,
        backupType
      });

      this.doAction('backupEtcd')
        .then(() => this.growl.success(successTitle, successMessage))
        .catch((err) => this.growl.fromError(err));
    },

    restoreFromEtcdBackup() {
      get(this, 'modalService').toggleModal('modal-restore-backup', { cluster: this, });
    },

    promptDelete() {
      const hasSessionToken = get(this, 'canBulkRemove') ? false : true; // canBulkRemove returns true of the session token is set false

      if (hasSessionToken) {
        set(this, `${ get(this, 'configName') }.accessKey`, null);
        get(this, 'modalService').toggleModal('modal-delete-eks-cluster', { model: this, });
      } else {
        get(this, 'modalService').toggleModal('confirm-delete', {
          escToClose: true,
          resources:  [this]
        });
      }
    },

    edit() {
      let provider = get(this, 'provider') || get(this, 'driver');
      let queryParams = { queryParams: { provider } };

      if (this.clusterTemplateRevisionId) {
        set(queryParams, 'queryParams.clusterTemplateRevision', this.clusterTemplateRevisionId);
      }

      this.router.transitionTo('authenticated.cluster.edit', get(this, 'id'), queryParams);
    },

    scaleDownPool(id) {
      const pool = (get(this, 'nodePools') || []).findBy('id', id);

      if ( pool ) {
        pool.incrementQuantity(-1);
      }
    },

    scaleUpPool(id) {
      const pool = (get(this, 'nodePools') || []).findBy('id', id);

      if ( pool ) {
        pool.incrementQuantity(1);
      }
    },

    rotateCertificates() {
      const model = this;

      get(this, 'modalService').toggleModal('modal-rotate-certificates', {
        model,
        serviceDefaults: get(this, 'globalStore').getById('schema', 'rotatecertificateinput').optionsFor('services'),
      });
    },

  },

  clearConfigFieldsForClusterTemplate() {
    let clearedNull   = ['localClusterAuthEndpoint', 'rancherKubernetesEngineConfig', 'enableNetworkPolicy'];
    let clearedDelete = ['defaultClusterRoleForProjectMembers', 'defaultPodSecurityPolicyTemplateId'];
    let {
      localClusterAuthEndpoint,
      rancherKubernetesEngineConfig,
      enableNetworkPolicy,
      defaultClusterRoleForProjectMembers,
      defaultPodSecurityPolicyTemplateId,
    } = this;

    let cachedConfig = {
      localClusterAuthEndpoint,
      rancherKubernetesEngineConfig,
      enableNetworkPolicy,
      defaultClusterRoleForProjectMembers,
      defaultPodSecurityPolicyTemplateId,
    };

    // set this incase we fail to save the cluster;
    set(this, '_cachedConfig', cachedConfig);

    clearedDelete.forEach((c) => delete this[c]);
    clearedNull.forEach((c) => set(this, c, null));
  },

  clearProvidersExcept(keep) {
    const keys = this.allKeys().filter((x) => x.endsWith('Config'));

    for ( let key, i = 0 ; i < keys.length ; i++ ) {
      key = keys[i];
      if ( key !== keep && get(this, key) ) {
        set(this, key, null);
      }
    }
  },

  delete(/* arguments*/) {
    const promise = this._super.apply(this, arguments);

    return promise.then((/* resp */) => {
      if (get(this, 'scope.currentCluster.id') === get(this, 'id')) {
        get(this, 'router').transitionTo('global-admin.clusters');
      }
    });
  },

  getOrCreateToken() {
    const globalStore = get(this, 'globalStore');
    const id = get(this, 'id');

    return globalStore.findAll('clusterRegistrationToken', { forceReload: true }).then((tokens) => {
      let token = tokens.filterBy('clusterId', id)[0];

      if ( token ) {
        return resolve(token);
      } else {
        token = get(this, 'globalStore').createRecord({
          type:      'clusterRegistrationToken',
          clusterId: id
        });

        return token.save();
      }
    });
  },
});
<commit_msg>revert fix i should not have put in for editing custom cluster<commit_after>import { get, set, computed, observer } from '@ember/object';
import { on } from '@ember/object/evented';
import { inject as service } from '@ember/service';
import Resource from '@rancher/ember-api-store/models/resource';
import { hasMany } from '@rancher/ember-api-store/utils/denormalize';
import ResourceUsage from 'shared/mixins/resource-usage';
import Grafana from 'shared/mixins/grafana';
import { equal, alias } from '@ember/object/computed';
import { resolve } from 'rsvp';
import C from 'ui/utils/constants';
import { isEmpty } from '@ember/utils';
import moment from 'moment';

const GRAY_OUT_SCHEDULER_STATUS_PROVIDERS = ['azureaks', 'aliyunkcs'];

export default Resource.extend(Grafana, ResourceUsage, {
  globalStore: service(),
  growl:       service(),
  intl:        service(),
  router:      service(),
  scope:       service(),

  clusterRoleTemplateBindings: hasMany('id', 'clusterRoleTemplateBinding', 'clusterId'),
  etcdbackups:                 hasMany('id', 'etcdbackup', 'clusterId'),
  namespaces:                  hasMany('id', 'namespace', 'clusterId'),
  nodePools:                   hasMany('id', 'nodePool', 'clusterId'),
  nodes:                       hasMany('id', 'node', 'clusterId'),
  projects:                    hasMany('id', 'project', 'clusterId'),
  expiringCerts:               null,
  grafanaDashboardName:        'Cluster',
  isMonitoringReady:           false,
  _cachedConfig:               null,
  machines:                    alias('nodes'),
  roleTemplateBindings:        alias('clusterRoleTemplateBindings'),
  isAKS:                       equal('driver', 'azureKubernetesService'),
  isGKE:                       equal('driver', 'googleKubernetesEngine'),

  conditionsDidChange:        on('init', observer('enableClusterMonitoring', 'conditions.@each.status', function() {
    if ( !get(this, 'enableClusterMonitoring') ) {
      return false;
    }
    const conditions = get(this, 'conditions') || [];

    const ready = conditions.findBy('type', 'MonitoringEnabled');

    const status = ready && get(ready, 'status') === 'True';

    if ( status !== get(this, 'isMonitoringReady') ) {
      set(this, 'isMonitoringReady', status);
    }
  })),

  getAltActionDelete: computed('action.remove', function() { // eslint-disable-line
    return get(this, 'canBulkRemove') ? 'delete' : null;
  }),

  hasSessionToken: computed('annotations', function() {
    const sessionTokenLabel = `${ (get(this, 'annotations') || {})[C.LABEL.EKS_SESSION_TOKEN]  }`;
    let hasSessionToken      = false;

    if (sessionTokenLabel === 'undefined' || sessionTokenLabel === 'false') {
      hasSessionToken = false;
    } else {
      hasSessionToken = true;
    }

    return hasSessionToken;
  }),

  canBulkRemove: computed('action.remove', function() { // eslint-disable-line
    return get(this, 'hasSessionToken') ? false : true;
  }),

  configName: computed(function() {
    const keys = this.allKeys().filter((x) => x.endsWith('Config'));

    for ( let key, i = 0 ; i < keys.length ; i++ ) {
      key = keys[i];
      if ( get(this, key) ) {
        return key;
      }
    }

    return null;
  }),

  isReady: computed('conditions.@each.status', function() {
    return this.hasCondition('Ready');
  }),

  isRKE: computed('configName', function() {
    return get(this, 'configName') === 'rancherKubernetesEngineConfig';
  }),

  provider: computed('configName', 'nodePools.@each.nodeTemplateId', 'driver', function() {
    const pools = get(this, 'nodePools') || [];
    const firstTemplate = get(pools, 'firstObject.nodeTemplate');

    switch ( get(this, 'configName') ) {
    case 'amazonElasticContainerServiceConfig':
      return 'amazoneks';
    case 'azureKubernetesServiceConfig':
      return 'azureaks';
    case 'googleKubernetesEngineConfig':
      return 'googlegke';
    case 'tencentEngineConfig':
      return 'tencenttke';
    case 'aliyunEngineConfig':
      return 'aliyunkcs';
    case 'huaweiEngineConfig':
      return 'huaweicce';
    case 'rancherKubernetesEngineConfig':
      if ( pools.length > 0 ) {
        if ( firstTemplate ) {
          return get(firstTemplate, 'driver');
        } else {
          return null;
        }
      } else {
        return 'custom';
      }
    default:
      if (get(this, 'driver') && get(this, 'configName')) {
        return get(this, 'driver');
      } else {
        return 'import';
      }
    }
  }),

  displayProvider: computed('configName', 'nodePools.@each.displayProvider', 'intl.locale', 'driver', function() {
    const intl = get(this, 'intl');
    const pools = get(this, 'nodePools');
    const firstPool = (pools || []).objectAt(0);

    switch ( get(this, 'configName') ) {
    case 'amazonElasticContainerServiceConfig':
      return intl.t('clusterNew.amazoneks.shortLabel');
    case 'azureKubernetesServiceConfig':
      return intl.t('clusterNew.azureaks.shortLabel');
    case 'googleKubernetesEngineConfig':
      return intl.t('clusterNew.googlegke.shortLabel');
    case 'tencentEngineConfig':
      return intl.t('clusterNew.tencenttke.shortLabel');
    case 'aliyunEngineConfig':
      return intl.t('clusterNew.aliyunkcs.shortLabel');
    case 'huaweiEngineConfig':
      return intl.t('clusterNew.huaweicce.shortLabel');
    case 'rancherKubernetesEngineConfig':
      if ( !!pools ) {
        if ( firstPool ) {
          return get(firstPool, 'displayProvider') ? get(firstPool, 'displayProvider') : intl.t('clusterNew.rke.shortLabel');
        } else {
          return intl.t('clusterNew.rke.shortLabel');
        }
      } else {
        return intl.t('clusterNew.custom.shortLabel');
      }
    default:
      if (get(this, 'driver') && get(this, 'configName')) {
        return get(this, 'driver').capitalize();
      } else {
        return intl.t('clusterNew.import.shortLabel');
      }
    }
  }),

  systemProject: computed('projects.@each.isSystemProject', function() {
    let projects = (get(this, 'projects') || []).filterBy('isSystemProject', true);

    return get(projects, 'firstObject');
  }),

  canSaveMonitor: computed('actionLinks.{editMonitoring,enableMonitoring}', function() {
    const action = get(this, 'enableClusterMonitoring') ?  'editMonitoring' : 'enableMonitoring';

    return !!this.hasAction(action)
  }),

  canDisableMonitor: computed('actionLinks.disableMonitoring', function() {
    return !!this.hasAction('disableMonitoring')
  }),

  defaultProject: computed('projects.@each.{name,clusterOwner}', function() {
    let projects = get(this, 'projects');

    let out = projects.findBy('isDefault');

    if ( out ) {
      return out;
    }

    out = projects.findBy('clusterOwner', true);
    if ( out ) {
      return out;
    }

    out = projects.objectAt(0);

    return out;
  }),

  certsExpiring: computed('certificatesExpiration', function() {
    let { certificatesExpiration = {}, expiringCerts } = this;

    if (!expiringCerts) {
      expiringCerts = [];
    }

    if (!isEmpty(certificatesExpiration)) {
      let expKeys = Object.keys(certificatesExpiration);

      expKeys.forEach((kee) => {
        let certDate  = get(certificatesExpiration[kee], 'expirationDate');
        const expirey = moment(certDate);
        let diff      = expirey.diff(moment());

        if (diff < 2592000000) { // milliseconds in a month
          expiringCerts.pushObject({
            expiringCertName: kee,
            milliUntil:       diff,
            exactDateTime:    certDate
          });
        }
      });

      set(this, 'expiringCerts', expiringCerts);

      return expiringCerts.length > 0;
    }

    return false;
  }),

  availableActions: computed('actionLinks.{rotateCertificates}', function() {
    const a = get(this, 'actionLinks') || {};

    return [
      {
        label:     'action.rotate',
        icon:      'icon icon-history',
        action:    'rotateCertificates',
        enabled:   !!a.rotateCertificates,
      },
      {
        label:     'action.backupEtcd',
        icon:      'icon icon-history',
        action:    'backupEtcd',
        enabled:   !!a.backupEtcd,
      },
      {
        label:     'action.restoreFromEtcdBackup',
        icon:      'icon icon-history',
        action:    'restoreFromEtcdBackup',
        enabled:   !!a.restoreFromEtcdBackup,
      },
    ];
  }),

  isVxlan: computed('rancherKubernetesEngineConfig.network.options.flannel_backend_type', function() {
    const backend = get(this, 'rancherKubernetesEngineConfig.network.options.flannel_backend_type');

    return backend === 'vxlan';
  }),

  isWindows:  computed('windowsPreferedCluster', function() {
    return !!get(this, 'windowsPreferedCluster');
  }),

  unhealthyComponents: computed('componentStatuses.@each.conditions', function() {
    return (get(this, 'componentStatuses') || [])
      .filter((s) => !s.conditions.any((c) => c.status === 'True'));
  }),

  inactiveNodes: computed('nodes.@each.state', function() {
    return get(this, 'nodes').filter( (n) => C.ACTIVEISH_STATES.indexOf(get(n, 'state')) === -1 );
  }),

  displayWarnings: computed('provider', 'inactiveNodes.[]', 'unhealthyComponents.[]', function() {
    const intl = get(this, 'intl');
    const out = [];
    const unhealthyComponents = get(this, 'unhealthyComponents') || [];
    const inactiveNodes = get(this, 'inactiveNodes') || [];
    const provider = get(this, 'provider');

    const grayOut = GRAY_OUT_SCHEDULER_STATUS_PROVIDERS.indexOf(provider) > -1;

    unhealthyComponents.forEach((component) => {
      if ( grayOut && (get(component, 'name') === 'scheduler' || get(component, 'name') === 'controller-manager') ) {
        return;
      }
      out.pushObject(intl.t('clusterDashboard.alert.component', { component: get(component, 'name') }));
    });

    inactiveNodes.forEach((node) => {
      out.pushObject(intl.t('clusterDashboard.alert.node', { node: get(node, 'displayName') }))
    });

    return out;
  }),

  actions: {
    backupEtcd() {
      const getBackupType = () => {
        let services = get(this, 'rancherKubernetesEngineConfig.services.etcd');

        if (get(services, 'cachedConfig')) {
          if (isEmpty(services.cachedConfig.s3BackupConfig)) {
            return 'local';
          } else if (!isEmpty(services.cachedConfig.s3BackupConfig)) {
            return 's3';
          }
        }
      }

      const backupType     = getBackupType();
      const successTitle   = this.intl.t('action.backupEtcdMessage.success.title');
      const successMessage = this.intl.t('action.backupEtcdMessage.success.message', {
        clusterId: this.displayName || this.id,
        backupType
      });

      this.doAction('backupEtcd')
        .then(() => this.growl.success(successTitle, successMessage))
        .catch((err) => this.growl.fromError(err));
    },

    restoreFromEtcdBackup() {
      get(this, 'modalService').toggleModal('modal-restore-backup', { cluster: this, });
    },

    promptDelete() {
      const hasSessionToken = get(this, 'canBulkRemove') ? false : true; // canBulkRemove returns true of the session token is set false

      if (hasSessionToken) {
        set(this, `${ get(this, 'configName') }.accessKey`, null);
        get(this, 'modalService').toggleModal('modal-delete-eks-cluster', { model: this, });
      } else {
        get(this, 'modalService').toggleModal('confirm-delete', {
          escToClose: true,
          resources:  [this]
        });
      }
    },

    edit() {
      let provider = get(this, 'provider') || get(this, 'driver');
      let queryParams = { queryParams: { provider } };

      if (this.clusterTemplateRevisionId) {
        set(queryParams, 'queryParams.clusterTemplateRevision', this.clusterTemplateRevisionId);
      }

      this.router.transitionTo('authenticated.cluster.edit', get(this, 'id'), queryParams);
    },

    scaleDownPool(id) {
      const pool = (get(this, 'nodePools') || []).findBy('id', id);

      if ( pool ) {
        pool.incrementQuantity(-1);
      }
    },

    scaleUpPool(id) {
      const pool = (get(this, 'nodePools') || []).findBy('id', id);

      if ( pool ) {
        pool.incrementQuantity(1);
      }
    },

    rotateCertificates() {
      const model = this;

      get(this, 'modalService').toggleModal('modal-rotate-certificates', {
        model,
        serviceDefaults: get(this, 'globalStore').getById('schema', 'rotatecertificateinput').optionsFor('services'),
      });
    },

  },

  clearConfigFieldsForClusterTemplate() {
    let clearedNull   = ['localClusterAuthEndpoint', 'rancherKubernetesEngineConfig', 'enableNetworkPolicy'];
    let clearedDelete = ['defaultClusterRoleForProjectMembers', 'defaultPodSecurityPolicyTemplateId'];
    let {
      localClusterAuthEndpoint,
      rancherKubernetesEngineConfig,
      enableNetworkPolicy,
      defaultClusterRoleForProjectMembers,
      defaultPodSecurityPolicyTemplateId,
    } = this;

    let cachedConfig = {
      localClusterAuthEndpoint,
      rancherKubernetesEngineConfig,
      enableNetworkPolicy,
      defaultClusterRoleForProjectMembers,
      defaultPodSecurityPolicyTemplateId,
    };

    // set this incase we fail to save the cluster;
    set(this, '_cachedConfig', cachedConfig);

    clearedDelete.forEach((c) => delete this[c]);
    clearedNull.forEach((c) => set(this, c, null));
  },

  clearProvidersExcept(keep) {
    const keys = this.allKeys().filter((x) => x.endsWith('Config'));

    for ( let key, i = 0 ; i < keys.length ; i++ ) {
      key = keys[i];
      if ( key !== keep && get(this, key) ) {
        set(this, key, null);
      }
    }
  },

  delete(/* arguments*/) {
    const promise = this._super.apply(this, arguments);

    return promise.then((/* resp */) => {
      if (get(this, 'scope.currentCluster.id') === get(this, 'id')) {
        get(this, 'router').transitionTo('global-admin.clusters');
      }
    });
  },

  getOrCreateToken() {
    const globalStore = get(this, 'globalStore');
    const id = get(this, 'id');

    return globalStore.findAll('clusterRegistrationToken', { forceReload: true }).then((tokens) => {
      let token = tokens.filterBy('clusterId', id)[0];

      if ( token ) {
        return resolve(token);
      } else {
        token = get(this, 'globalStore').createRecord({
          type:      'clusterRegistrationToken',
          clusterId: id
        });

        return token.save();
      }
    });
  },
});
<|endoftext|>


<commit_before>/*
 Extensions Compatibility Library

 Usage:
     var extensions = window['piro.sakura.ne.jp'].extensions;
     extensions.isAvailable('my.extension.id@example.com', {
       ok : function() { extensions.goToOptions('my.extension.id@example.com'); },
       ng : function() { alert('NOT INSTALLED'); }
     });
     extensions.isInstalled('my.extension.id@example.com', {
       ok : function(aDir) {
         var dir = aDir; // nsILocalFile
       }
     });

 license: The MIT License, Copyright (c) 2009-2016 YUKI "Piro" Hiroshi
 original:
   http://github.com/piroor/fxaddonlib-extensions
*/

/* To work as a JS Code Module */
if (typeof window == 'undefined' ||
	(window && typeof window.constructor == 'function')) {
	this.EXPORTED_SYMBOLS = ['extensions'];

	// If namespace.jsm is available, export symbols to the shared namespace.
	// See: http://github.com/piroor/fxaddonlibs/blob/master/namespace.jsm
	try {
		let ns = {};
		Components.utils.import('resource://my-modules/namespace.jsm', ns);
		/* var */ window = ns.getNamespaceFor('piro.sakura.ne.jp');
	}
	catch(e) {
		window = {};
	}
}

(function() {
	const currentRevision = 13;

	if (!('piro.sakura.ne.jp' in window)) window['piro.sakura.ne.jp'] = {};

	var loadedRevision = 'extensions' in window['piro.sakura.ne.jp'] ?
			window['piro.sakura.ne.jp'].extensions.revision :
			0 ;
	if (loadedRevision && loadedRevision > currentRevision) {
		return;
	}

	const Cc = Components.classes;
	const Ci = Components.interfaces;

	// Firefox 3.7 or later
	var AM = {};
	if ('@mozilla.org/addons/integration;1' in Cc)
		Components.utils.import('resource://gre/modules/AddonManager.jsm', AM);

	window['piro.sakura.ne.jp'].extensions = {
		revision : currentRevision,

		_formatCallbacks : function(aOKCallback, aNGCallback)
		{
			var callbacks = {
					ok : aOKCallback,
					ng : aNGCallback
				};
			if (typeof aOKCallback != 'function')
				callbacks = aOKCallback;

			if (!('ok' in callbacks) || typeof callbacks.ok != 'function')
				callbacks.ok = function() {};
			if (!('ng' in callbacks) || typeof callbacks.ng != 'function')
				callbacks.ng = function() {};

			return callbacks;
		},

		isAvailable : function(aId, aOKCallback, aNGCallback)
		{
			return this.isEnabled(aId, aOKCallback, aNGCallback);
		},

		isInstalled : function(aId, aOKCallback, aNGCallback)
		{
			var callbacks = this._formatCallbacks(aOKCallback, aNGCallback);
				AM.AddonManager.getAddonByID(aId, function(aAddon) {
					callbacks[aAddon ? 'ok' : 'ng']();
				});
		},

		isEnabled : function(aId, aOKCallback, aNGCallback)
		{
			var callbacks = this._formatCallbacks(aOKCallback, aNGCallback);
				AM.AddonManager.getAddonByID(aId, function(aAddon) {
					callbacks[aAddon && aAddon.isActive ? 'ok' : 'ng']();
				});
		},

		getInstalledLocation : function(aId, aCallback)
		{
				AM.AddonManager.getAddonByID(aId, function(aAddon) {
					var location = null;
					if (aAddon)
						location = aAddon.getResourceURI('/').QueryInterface(Ci.nsIFileURL).file.clone();
					aCallback(location);
				});
		},

		getVersion : function(aId, aCallback)
		{
				AM.AddonManager.getAddonByID(aId, function(aAddon) {
					aCallback(aAddon ? aAddon.version : null );
				});
		},

		goToOptions : function(aId, aOwnerWindow)
		{
			var self = this;
			var callback = function(aURI) {
					self.goToOptionsInternal(aURI, aOwnerWindow);
				};
				AM.AddonManager.getAddonByID(aId, function(aAddon) {
					callback(aAddon && aAddon.isActive ? aAddon.optionsURL : null );
				});
		},
		goToOptionsInternal : function(aURI, aOwnerWindow)
		{
			if (!aURI) return;

			var windows = this._WindowMediator.getEnumerator(null);
			while (windows.hasMoreElements())
			{
				let win = windows.getNext();
				if (win.location.href == aURI) {
					win.focus();
					return;
				}
			}
			var instantApply = false;
			try {
				instantApply = this._Prefs.getBoolPref('browser.preferences.instantApply');
			}
			catch(e) {
			}
			(aOwnerWindow || window).openDialog(
				aURI,
				'',
				'chrome,titlebar,toolbar,centerscreen,' + (instantApply ? 'dialog=no' : 'modal' )
			);
		}
	};
})();

if (window != this) { // work as a JS Code Module
	this.extensions = window['piro.sakura.ne.jp'].extensions;
}
<commit_msg>Fix indent<commit_after>/*
 Extensions Compatibility Library

 Usage:
     var extensions = window['piro.sakura.ne.jp'].extensions;
     extensions.isAvailable('my.extension.id@example.com', {
       ok : function() { extensions.goToOptions('my.extension.id@example.com'); },
       ng : function() { alert('NOT INSTALLED'); }
     });
     extensions.isInstalled('my.extension.id@example.com', {
       ok : function(aDir) {
         var dir = aDir; // nsILocalFile
       }
     });

 license: The MIT License, Copyright (c) 2009-2016 YUKI "Piro" Hiroshi
 original:
   http://github.com/piroor/fxaddonlib-extensions
*/

/* To work as a JS Code Module */
if (typeof window == 'undefined' ||
	(window && typeof window.constructor == 'function')) {
	this.EXPORTED_SYMBOLS = ['extensions'];

	// If namespace.jsm is available, export symbols to the shared namespace.
	// See: http://github.com/piroor/fxaddonlibs/blob/master/namespace.jsm
	try {
		let ns = {};
		Components.utils.import('resource://my-modules/namespace.jsm', ns);
		/* var */ window = ns.getNamespaceFor('piro.sakura.ne.jp');
	}
	catch(e) {
		window = {};
	}
}

(function() {
	const currentRevision = 13;

	if (!('piro.sakura.ne.jp' in window)) window['piro.sakura.ne.jp'] = {};

	var loadedRevision = 'extensions' in window['piro.sakura.ne.jp'] ?
			window['piro.sakura.ne.jp'].extensions.revision :
			0 ;
	if (loadedRevision && loadedRevision > currentRevision) {
		return;
	}

	const Cc = Components.classes;
	const Ci = Components.interfaces;

	// Firefox 3.7 or later
	var AM = {};
	if ('@mozilla.org/addons/integration;1' in Cc)
		Components.utils.import('resource://gre/modules/AddonManager.jsm', AM);

	window['piro.sakura.ne.jp'].extensions = {
		revision : currentRevision,

		_formatCallbacks : function(aOKCallback, aNGCallback)
		{
			var callbacks = {
					ok : aOKCallback,
					ng : aNGCallback
				};
			if (typeof aOKCallback != 'function')
				callbacks = aOKCallback;

			if (!('ok' in callbacks) || typeof callbacks.ok != 'function')
				callbacks.ok = function() {};
			if (!('ng' in callbacks) || typeof callbacks.ng != 'function')
				callbacks.ng = function() {};

			return callbacks;
		},

		isAvailable : function(aId, aOKCallback, aNGCallback)
		{
			return this.isEnabled(aId, aOKCallback, aNGCallback);
		},

		isInstalled : function(aId, aOKCallback, aNGCallback)
		{
			var callbacks = this._formatCallbacks(aOKCallback, aNGCallback);
			AM.AddonManager.getAddonByID(aId, function(aAddon) {
				callbacks[aAddon ? 'ok' : 'ng']();
			});
		},

		isEnabled : function(aId, aOKCallback, aNGCallback)
		{
			var callbacks = this._formatCallbacks(aOKCallback, aNGCallback);
			AM.AddonManager.getAddonByID(aId, function(aAddon) {
				callbacks[aAddon && aAddon.isActive ? 'ok' : 'ng']();
			});
		},

		getInstalledLocation : function(aId, aCallback)
		{
			AM.AddonManager.getAddonByID(aId, function(aAddon) {
				var location = null;
				if (aAddon)
					location = aAddon.getResourceURI('/').QueryInterface(Ci.nsIFileURL).file.clone();
				aCallback(location);
			});
		},

		getVersion : function(aId, aCallback)
		{
			AM.AddonManager.getAddonByID(aId, function(aAddon) {
				aCallback(aAddon ? aAddon.version : null );
			});
		},

		goToOptions : function(aId, aOwnerWindow)
		{
			var self = this;
			var callback = function(aURI) {
					self.goToOptionsInternal(aURI, aOwnerWindow);
				};
			AM.AddonManager.getAddonByID(aId, function(aAddon) {
				callback(aAddon && aAddon.isActive ? aAddon.optionsURL : null );
			});
		},
		goToOptionsInternal : function(aURI, aOwnerWindow)
		{
			if (!aURI) return;

			var windows = this._WindowMediator.getEnumerator(null);
			while (windows.hasMoreElements())
			{
				let win = windows.getNext();
				if (win.location.href == aURI) {
					win.focus();
					return;
				}
			}
			var instantApply = false;
			try {
				instantApply = this._Prefs.getBoolPref('browser.preferences.instantApply');
			}
			catch(e) {
			}
			(aOwnerWindow || window).openDialog(
				aURI,
				'',
				'chrome,titlebar,toolbar,centerscreen,' + (instantApply ? 'dialog=no' : 'modal' )
			);
		}
	};
})();

if (window != this) { // work as a JS Code Module
	this.extensions = window['piro.sakura.ne.jp'].extensions;
}
<|endoftext|>


<commit_before>import { isArray } from '../../utility/kit';
import { Node } from '../../node/node';

export class SelectionState {
	constructor(model, service) {
		this.model = model;
		this.service = service;
	}

	select(item, state = true, key) {
		key = key || this.keyFactory();
		if (isArray(item)) {
			item.forEach(item => this.select(item, state, key));
			return;
		}

		if (item instanceof Node) {
			const { rows } = this.model.data();
			if (rows.length) {
				item.rows.forEach(index => this.select(rows[index], state, key));
				return;
			}
		}

		this.selectCore(item, state, key);
	}

	canSelect(item) {
		return this.canSelectCore(item);
	}

	toggle(item) {
		const state = this.state(item);
		return this.select(item, state === null || !state);
	}

	state(item, key) {
		key = key || this.keyFactory();
		if (isArray(item)) {
			const all = item.every(item => this.state(item, key));
			return all ? true : item.some(item => this.state(item, key)) ? null : false;
		}

		if (item instanceof Node) {
			const { rows } = this.model.data();
			if (rows.length) {
				const all = item.rows.length && item.rows.every(index => this.state(rows[index], key));
				return all ? true : item.rows.some(index => this.state(rows[index], key)) ? null : false;
			}
		}

		return this.stateCore(item, key);
	}

	stateAll(items) {
		const entries = this.entries();
		if (items.length === entries.length) {
			return true;
		}

		return entries.length > 0 ? null : false;
	}

	keyFactory() {
		return this.service.hashFactory();
	}

	clear() {
		this.clearCore();
	}

	entries() {
		return [];
	}

	selectCore() {
	}

	clearCore() {
	}

	stateCore() {
		return false;
	}

	canSelectCore() {
		return true;
	}
}<commit_msg>fix select all state<commit_after>import { isArray } from '../../utility/kit';
import { Node } from '../../node/node';

export class SelectionState {
	constructor(model, service) {
		this.model = model;
		this.service = service;
	}

	select(item, state = true, key) {
		key = key || this.keyFactory();
		if (isArray(item)) {
			item.forEach(item => this.select(item, state, key));
			return;
		}

		if (item instanceof Node) {
			const { rows } = this.model.data();
			if (rows.length) {
				item.rows.forEach(index => this.select(rows[index], state, key));
				return;
			}
		}

		this.selectCore(item, state, key);
	}

	canSelect(item) {
		return this.canSelectCore(item);
	}

	toggle(item) {
		const state = this.state(item);
		return this.select(item, state === null || !state);
	}

	state(item, key) {
		key = key || this.keyFactory();
		if (isArray(item)) {
			const all = item.every(item => this.state(item, key));
			return all ? true : item.some(item => this.state(item, key)) ? null : false;
		}

		if (item instanceof Node) {
			const { rows } = this.model.data();
			if (rows.length) {
				const all = item.rows.length && item.rows.every(index => this.state(rows[index], key));
				return all ? true : item.rows.some(index => this.state(rows[index], key)) ? null : false;
			}
		}

		return this.stateCore(item, key);
	}

	stateAll(items) {
		if (!items.length) {
			return false;
		}

		const key = this.keyFactory();

		const notSelected = items.findIndex(item => this.state(item, key) === false);
		if (notSelected < 0) {
			return true;
		}

		return notSelected === 0
			? items.every(item => this.state(item, key) === false)
				? false
				: null
			: null;
	}

	keyFactory() {
		return this.service.hashFactory();
	}

	clear() {
		this.clearCore();
	}

	entries() {
		return [];
	}

	selectCore() {
	}

	clearCore() {
	}

	stateCore() {
		return false;
	}

	canSelectCore() {
		return true;
	}
}<|endoftext|>


<commit_before>/*
 * NTwitBot - process.test.js
 * Copyright (C) 2016-2017 Jordan Sne
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

const Process = require('../lib/process.js');
const Util    = require('../lib/util.js');
const processor = new Process(new Util());

describe('Process', () => {
    it('should filter mentions and links from words', () => {
        const words = ["good", "@bad", "http://bad.ca", "good2"];
        const filtered = processor.filterWords(words);

        expect(filtered).toMatchObject(["good", "good2"]);
    });

    it('should convert words to lowercase', () => {
        const words = ["Test", "sentENCE."];
        processor.converToLowercase(words);

        expect(words).toMatchObject(["test", "sentence."]);
    });

    it('should capitalize sentences', () => {
        const words = ["test", "one.", "test", "two!", "test", "three?", "final"];
        processor.capitalizeSentences(words);

        expect(words).toMatchObject(["Test", "one.", "Test", "two!", "Test", "three?", "Final"]);
    });

    it('should append periods to the end of tweets', () => {
        const words = ["Test", "sentence"];
        processor.appendPeriod(words);

        expect(words).toMatchObject(["Test", "sentence."]);
    });

    it('should add new keys in a data object', () => {
        // Use a mock utils object to mock the getTime function that is used by the processor
        const timeMock = jest.fn().mockReturnValue(201710302350);
        const processorMocked = new Process({ getTime: timeMock });
        const data = {};
        const words = ["Test", "sentence", "one."];

        processorMocked.appendData(data, words);

        expect(data).toHaveProperty(
            "Test sentence", [{
                word: "one.",
                time: 201710302350
            }]
        );
    });

    it('should append to existing keys in a data object', () => {
        // Use a mock utils object to mock the getTime function that is used by the processor
        const timeMock = jest.fn().mockReturnValue(201710302351);
        const processorMocked = new Process({ getTime: timeMock });
        const data = {
            "Test sentence": [{
                word: "one.",
                time: 201710302350
            }]
        };
        const words = ["Test", "sentence", "two."];

        processorMocked.appendData(data, words);

        expect(data).toHaveProperty(
            "Test sentence", [{
                word: "one.",
                time: 201710302350
            }, {
                word: "two.",
                time: 201710302351
            }]
        );
    });

    it('should convert raw tweets into a data object', () => {
        const utilsMock = new Util();
        const processorMocked = new Process(utilsMock);

        // Override getTime in utils
        utilsMock.getTime = () => 201710302350;

        const tweets = [
            { text: "test sentence one. tEst sentence two"},
            { text: "Another sentence one." }
        ];
        const data = processorMocked.processTweets(tweets);

        expect(data).toMatchObject({
            "Test sentence": [{
                word: "one.",
                time: 201710302350
            }, {
                word: "two.",
                time: 201710302350
            }],
            "sentence one.": [{
                word: "Test",
                time: 201710302350
            }],
            "one. Test": [{
                word: "sentence",
                time: 201710302350
            }],
            "Another sentence": [{
                word: "one.",
                time: 201710302350
            }]
        });
    });
});
<commit_msg>Mock util's time methods for all of process.test.js<commit_after>/*
 * NTwitBot - process.test.js
 * Copyright (C) 2016-2017 Jordan Sne
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

const Process = require('../lib/process.js');
const Util    = require('../lib/util.js');
let processor;

const MOCK_TIME           = 201710302350;
const MOCK_TIME_FORMATTED = "10/30/2017 23:50:15";

describe('Process', () => {
    beforeAll(() => {
        // Override time methods with time constants above
        const utilsMock = new Util();
        utilsMock.getTime = jest.fn(() => MOCK_TIME);
        utilsMock.getFormattedTime = jest.fn(() => MOCK_TIME_FORMATTED);

        processor = new Process(utilsMock);
    });

    it('should filter mentions and links from words', () => {
        const words = ["good", "@bad", "http://bad.ca", "good2"];
        const filtered = processor.filterWords(words);

        expect(filtered).toMatchObject(["good", "good2"]);
    });

    it('should convert words to lowercase', () => {
        const words = ["Test", "sentENCE."];
        processor.converToLowercase(words);

        expect(words).toMatchObject(["test", "sentence."]);
    });

    it('should capitalize sentences', () => {
        const words = ["test", "one.", "test", "two!", "test", "three?", "final"];
        processor.capitalizeSentences(words);

        expect(words).toMatchObject(["Test", "one.", "Test", "two!", "Test", "three?", "Final"]);
    });

    it('should append periods to the end of tweets', () => {
        const words = ["Test", "sentence"];
        processor.appendPeriod(words);

        expect(words).toMatchObject(["Test", "sentence."]);
    });

    it('should add new keys in a data object', () => {
        const data = {};
        const words = ["Test", "sentence", "one."];

        processor.appendData(data, words);

        expect(data).toHaveProperty(
            "Test sentence", [{
                word: "one.",
                time: MOCK_TIME
            }]
        );
    });

    it('should append to existing keys in a data object', () => {
        const data = {
            "Test sentence": [{
                word: "one.",
                time: MOCK_TIME
            }]
        };
        const words = ["Test", "sentence", "two."];

        processor.appendData(data, words);

        expect(data).toHaveProperty(
            "Test sentence", [{
                word: "one.",
                time: MOCK_TIME
            }, {
                word: "two.",
                time: MOCK_TIME
            }]
        );
    });

    it('should convert raw tweets into a data object', () => {
        const tweets = [
            { text: "test sentence one. tEst sentence two"},
            { text: "Another sentence one." }
        ];
        const data = processor.processTweets(tweets);

        expect(data).toMatchObject({
            "Test sentence": [{
                word: "one.",
                time: MOCK_TIME
            }, {
                word: "two.",
                time: MOCK_TIME
            }],
            "sentence one.": [{
                word: "Test",
                time: MOCK_TIME
            }],
            "one. Test": [{
                word: "sentence",
                time: MOCK_TIME
            }],
            "Another sentence": [{
                word: "one.",
                time: MOCK_TIME
            }]
        });
    });
});
<|endoftext|>


<commit_before>var chai = require('chai')
  , expect = require('chai').expect
  , acdc = require('../../lib/exchange/jwt-acdc');

describe('exchange.jwt-acdc', function() {

  it('should be unnamed', function() {
    expect(acdc(function(){}).name).to.equal('');
  });

  describe('issuing an access token', function() {
    var response, err;

    before(function(done) {
      function issue(client, assertion, done) {
        if (client.id !== '1') { return done(new Error('incorrect client argument')); }
        if (assertion !== 'eyJ') { return done(new Error('incorrect code argument')); }

        return done(null, 's3cr1t');
      }

      chai.connect.use(acdc(issue))
        .req(function(req) {
          req.user = { id: '1', name: 'OAuth Client' };
          req.body = { assertion: 'eyJ', code_verifier: 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk' };
        })
        .end(function(res) {
          response = res;
          done();
        })
        .dispatch();
    });

    it('should respond with headers', function() {
      expect(response.getHeader('Content-Type')).to.equal('application/json');
      expect(response.getHeader('Cache-Control')).to.equal('no-store');
      expect(response.getHeader('Pragma')).to.equal('no-cache');
    });

    it('should respond with body', function() {
      expect(response.body).to.equal('{"access_token":"s3cr1t","token_type":"Bearer"}');
    });
  });

  describe('issuing an access token and refresh token', function() {
    var response, err;

    before(function(done) {
      function issue(client, assertion, done) {
        if (client.id !== '1') { return done(new Error('incorrect client argument')); }
        if (assertion !== 'eyJ') { return done(new Error('incorrect code argument')); }

        return done(null, 's3cr1t', 'getANotehr');
      }

      chai.connect.use(acdc(issue))
        .req(function(req) {
          req.user = { id: '1', name: 'OAuth Client' };
          req.body = { assertion: 'eyJ', code_verifier: 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk' };
        })
        .end(function(res) {
          response = res;
          done();
        })
        .dispatch();
    });

    it('should respond with headers', function() {
      expect(response.getHeader('Content-Type')).to.equal('application/json');
      expect(response.getHeader('Cache-Control')).to.equal('no-store');
      expect(response.getHeader('Pragma')).to.equal('no-cache');
    });

    it('should respond with body', function() {
      expect(response.body).to.equal('{"access_token":"s3cr1t","refresh_token":"getANotehr","token_type":"Bearer"}');
    });
  });

  describe('issuing an access token and params', function() {
    var response, err;

    before(function(done) {
      function issue(client, assertion, done) {
        if (client.id !== '1') { return done(new Error('incorrect client argument')); }
        if (assertion !== 'eyJ') { return done(new Error('incorrect code argument')); }

        return done(null, 's3cr1t', { 'expires_in': 3600 });
      }

      chai.connect.use(acdc(issue))
        .req(function(req) {
          req.user = { id: '1', name: 'OAuth Client' };
          req.body = { assertion: 'eyJ', code_verifier: 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk' };
        })
        .end(function(res) {
          response = res;
          done();
        })
        .dispatch();
    });

    it('should respond with headers', function() {
      expect(response.getHeader('Content-Type')).to.equal('application/json');
      expect(response.getHeader('Cache-Control')).to.equal('no-store');
      expect(response.getHeader('Pragma')).to.equal('no-cache');
    });

    it('should respond with body', function() {
      expect(response.body).to.equal('{"access_token":"s3cr1t","expires_in":3600,"token_type":"Bearer"}');
    });
  });

  describe('issuing an access token, null refresh token, and params', function() {
    var response, err;

    before(function(done) {
      function issue(client, assertion, done) {
        if (client.id !== '1') { return done(new Error('incorrect client argument')); }
        if (assertion !== 'eyJ') { return done(new Error('incorrect code argument')); }

        return done(null, 's3cr1t', null, { 'expires_in': 3600 });
      }

      chai.connect.use(acdc(issue))
        .req(function(req) {
          req.user = { id: '1', name: 'OAuth Client' };
          req.body = { assertion: 'eyJ', code_verifier: 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk' };
        })
        .end(function(res) {
          response = res;
          done();
        })
        .dispatch();
    });

    it('should respond with headers', function() {
      expect(response.getHeader('Content-Type')).to.equal('application/json');
      expect(response.getHeader('Cache-Control')).to.equal('no-store');
      expect(response.getHeader('Pragma')).to.equal('no-cache');
    });

    it('should respond with body', function() {
      expect(response.body).to.equal('{"access_token":"s3cr1t","expires_in":3600,"token_type":"Bearer"}');
    });
  });

  describe('issuing an access token, refresh token, and params with token_type', function() {
    var response, err;

    before(function(done) {
      function issue(client, assertion, done) {
        if (client.id !== '1') { return done(new Error('incorrect client argument')); }
        if (assertion !== 'eyJ') { return done(new Error('incorrect code argument')); }

        return done(null, 's3cr1t', 'blahblag', { 'token_type': 'foo', 'expires_in': 3600 });
      }

      chai.connect.use(acdc(issue))
        .req(function(req) {
          req.user = { id: '1', name: 'OAuth Client' };
          req.body = { assertion: 'eyJ', code_verifier: 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk' };
        })
        .end(function(res) {
          response = res;
          done();
        })
        .dispatch();
    });

    it('should respond with headers', function() {
      expect(response.getHeader('Content-Type')).to.equal('application/json');
      expect(response.getHeader('Cache-Control')).to.equal('no-store');
      expect(response.getHeader('Pragma')).to.equal('no-cache');
    });

    it('should respond with body', function() {
      expect(response.body).to.equal('{"access_token":"s3cr1t","refresh_token":"blahblag","token_type":"foo","expires_in":3600}');
    });
  });

});
<commit_msg>More test cases.<commit_after>var chai = require('chai')
  , expect = require('chai').expect
  , acdc = require('../../lib/exchange/jwt-acdc');

describe('exchange.jwt-acdc', function() {

  it('should be unnamed', function() {
    expect(acdc(function(){}).name).to.equal('');
  });

  describe('issuing an access token', function() {
    var response, err;

    before(function(done) {
      function issue(client, assertion, done) {
        if (client.id !== '1') { return done(new Error('incorrect client argument')); }
        if (assertion !== 'eyJ') { return done(new Error('incorrect code argument')); }

        return done(null, 's3cr1t');
      }

      chai.connect.use(acdc(issue))
        .req(function(req) {
          req.user = { id: '1', name: 'OAuth Client' };
          req.body = { assertion: 'eyJ', code_verifier: 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk' };
        })
        .end(function(res) {
          response = res;
          done();
        })
        .dispatch();
    });

    it('should respond with headers', function() {
      expect(response.getHeader('Content-Type')).to.equal('application/json');
      expect(response.getHeader('Cache-Control')).to.equal('no-store');
      expect(response.getHeader('Pragma')).to.equal('no-cache');
    });

    it('should respond with body', function() {
      expect(response.body).to.equal('{"access_token":"s3cr1t","token_type":"Bearer"}');
    });
  });

  describe('issuing an access token and refresh token', function() {
    var response, err;

    before(function(done) {
      function issue(client, assertion, done) {
        if (client.id !== '1') { return done(new Error('incorrect client argument')); }
        if (assertion !== 'eyJ') { return done(new Error('incorrect code argument')); }

        return done(null, 's3cr1t', 'getANotehr');
      }

      chai.connect.use(acdc(issue))
        .req(function(req) {
          req.user = { id: '1', name: 'OAuth Client' };
          req.body = { assertion: 'eyJ', code_verifier: 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk' };
        })
        .end(function(res) {
          response = res;
          done();
        })
        .dispatch();
    });

    it('should respond with headers', function() {
      expect(response.getHeader('Content-Type')).to.equal('application/json');
      expect(response.getHeader('Cache-Control')).to.equal('no-store');
      expect(response.getHeader('Pragma')).to.equal('no-cache');
    });

    it('should respond with body', function() {
      expect(response.body).to.equal('{"access_token":"s3cr1t","refresh_token":"getANotehr","token_type":"Bearer"}');
    });
  });

  describe('issuing an access token and params', function() {
    var response, err;

    before(function(done) {
      function issue(client, assertion, done) {
        if (client.id !== '1') { return done(new Error('incorrect client argument')); }
        if (assertion !== 'eyJ') { return done(new Error('incorrect code argument')); }

        return done(null, 's3cr1t', { 'expires_in': 3600 });
      }

      chai.connect.use(acdc(issue))
        .req(function(req) {
          req.user = { id: '1', name: 'OAuth Client' };
          req.body = { assertion: 'eyJ', code_verifier: 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk' };
        })
        .end(function(res) {
          response = res;
          done();
        })
        .dispatch();
    });

    it('should respond with headers', function() {
      expect(response.getHeader('Content-Type')).to.equal('application/json');
      expect(response.getHeader('Cache-Control')).to.equal('no-store');
      expect(response.getHeader('Pragma')).to.equal('no-cache');
    });

    it('should respond with body', function() {
      expect(response.body).to.equal('{"access_token":"s3cr1t","expires_in":3600,"token_type":"Bearer"}');
    });
  });

  describe('issuing an access token, null refresh token, and params', function() {
    var response, err;

    before(function(done) {
      function issue(client, assertion, done) {
        if (client.id !== '1') { return done(new Error('incorrect client argument')); }
        if (assertion !== 'eyJ') { return done(new Error('incorrect code argument')); }

        return done(null, 's3cr1t', null, { 'expires_in': 3600 });
      }

      chai.connect.use(acdc(issue))
        .req(function(req) {
          req.user = { id: '1', name: 'OAuth Client' };
          req.body = { assertion: 'eyJ', code_verifier: 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk' };
        })
        .end(function(res) {
          response = res;
          done();
        })
        .dispatch();
    });

    it('should respond with headers', function() {
      expect(response.getHeader('Content-Type')).to.equal('application/json');
      expect(response.getHeader('Cache-Control')).to.equal('no-store');
      expect(response.getHeader('Pragma')).to.equal('no-cache');
    });

    it('should respond with body', function() {
      expect(response.body).to.equal('{"access_token":"s3cr1t","expires_in":3600,"token_type":"Bearer"}');
    });
  });

  describe('issuing an access token, refresh token, and params with token_type', function() {
    var response, err;

    before(function(done) {
      function issue(client, assertion, done) {
        if (client.id !== '1') { return done(new Error('incorrect client argument')); }
        if (assertion !== 'eyJ') { return done(new Error('incorrect code argument')); }

        return done(null, 's3cr1t', 'blahblag', { 'token_type': 'foo', 'expires_in': 3600 });
      }

      chai.connect.use(acdc(issue))
        .req(function(req) {
          req.user = { id: '1', name: 'OAuth Client' };
          req.body = { assertion: 'eyJ', code_verifier: 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk' };
        })
        .end(function(res) {
          response = res;
          done();
        })
        .dispatch();
    });

    it('should respond with headers', function() {
      expect(response.getHeader('Content-Type')).to.equal('application/json');
      expect(response.getHeader('Cache-Control')).to.equal('no-store');
      expect(response.getHeader('Pragma')).to.equal('no-cache');
    });

    it('should respond with body', function() {
      expect(response.body).to.equal('{"access_token":"s3cr1t","refresh_token":"blahblag","token_type":"foo","expires_in":3600}');
    });
  });

  describe('issuing an access token based on verifier', function() {
    var response, err;

    before(function(done) {
      function issue(client, assertion, verifier, done) {
        if (client.id !== '1') { return done(new Error('incorrect client argument')); }
        if (assertion !== 'eyJ') { return done(new Error('incorrect code argument')); }
        if (verifier !== 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk') { return done(new Error('incorrect code argument')); }

        return done(null, 's3cr1t');
      }

      chai.connect.use(acdc(issue))
        .req(function(req) {
          req.user = { id: '1', name: 'OAuth Client' };
          req.body = { assertion: 'eyJ', code_verifier: 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk' };
        })
        .end(function(res) {
          response = res;
          done();
        })
        .dispatch();
    });

    it('should respond with headers', function() {
      expect(response.getHeader('Content-Type')).to.equal('application/json');
      expect(response.getHeader('Cache-Control')).to.equal('no-store');
      expect(response.getHeader('Pragma')).to.equal('no-cache');
    });

    it('should respond with body', function() {
      expect(response.body).to.equal('{"access_token":"s3cr1t","token_type":"Bearer"}');
    });
  });

  describe('issuing an access token based on misspelled verifier', function() {
    var response, err;

    before(function(done) {
      function issue(client, assertion, verifier, done) {
        if (client.id !== '1') { return done(new Error('incorrect client argument')); }
        if (assertion !== 'eyJ') { return done(new Error('incorrect code argument')); }
        if (verifier !== 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk') { return done(new Error('incorrect code argument')); }

        return done(null, 's3cr1t');
      }

      chai.connect.use(acdc(issue))
        .req(function(req) {
          req.user = { id: '1', name: 'OAuth Client' };
          req.body = { assertion: 'eyJ', code_verifyer: 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk' };
        })
        .end(function(res) {
          response = res;
          done();
        })
        .dispatch();
    });

    it('should respond with headers', function() {
      expect(response.getHeader('Content-Type')).to.equal('application/json');
      expect(response.getHeader('Cache-Control')).to.equal('no-store');
      expect(response.getHeader('Pragma')).to.equal('no-cache');
    });

    it('should respond with body', function() {
      expect(response.body).to.equal('{"access_token":"s3cr1t","token_type":"Bearer"}');
    });
  });

});
<|endoftext|>


<commit_before>//Default replacements
var default_replacements = [
    ['keyboard', 'leopard'],
    ['keyboards', 'leopards'],
    ['force', 'horse'],
    ['forces', 'horses'],
    ['witness', 'this dude I know'],
    ['witnesses', 'these dudes I know'],
    ['allegedly', 'kinda probably'],
    ['new study', 'tumblr post'],
    ['rebuild', 'avenge'],
    ['space', 'spaaaaaace'],
    ['google glass', 'virtual boy'],
    ['smartphone', 'pok\u00E9dex'],
    ['senator', 'elf-lord'],
    ['senators', 'elf-lords'],
    ['electric', 'atomic'],
    ['car', 'cat'],
    ['cars', 'cats'],
    ['election', 'eating contest'],
    ['elections', 'eating contests'],
    ['congressional leaders', 'river spirits'],
    ['homeland security', 'homestar runner'],
    ['could not be reached for comment', 'is guilty and everyone knows it'],
];
//Default Blacklist
var default_blacklisted_sites = ["docs.google.com",
    "gmail.com",
    "mail.google.com",
    "mail.yahoo.com",
    "outlook.com",
]

debug = false;

function checkBlackList(url, blacklist) {
    url = url.toLowerCase() || "";
    blacklist = blacklist || [];
    for (var i = blacklist.length - 1; i >= 0; i--) {
        if (url.indexOf(blacklist[i]) > -1) {
            return false;
        }
    };
    return true;
}

function injectionScript(tabId, info, tab) {
    if (debug) console.log("injection fire");
    chrome.storage.sync.get(null, function(result) {
        if (result["status"] === "enabled" && checkBlackList(tab.url, result['blacklist'])) {
            chrome.tabs.executeScript(tabId, {
                file: "js/substitutions.js",
                runAt: "document_end"
            });
        }
    });
}

function addMessage(request, sender, sendResponse) {
    if (debug) console.log("message fire");
    chrome.storage.sync.get(null, function(result) {
        if (request === "config" && result["replacements"]) {
            sendResponse(result["replacements"]);
        }
    });
    return true;
}

function fixDataCorruption() {
    if (debug) console.log("updateStore");
    chrome.storage.sync.get(null, function(result) {
        if (!result["status"]) {
            chrome.storage.sync.set({
                "status": "enabled"
            });
        }
        if (!result["replacements"]) {
            chrome.storage.sync.set({
                "replacements": default_replacements
            });
        }
        if (!result["replacements"]) {
            chrome.storage.sync.set({
                "blacklist": default_blacklisted_sites
            });
        }
    });
}

function toggleActive() {
        if (debug) console.log("clickfire");
    chrome.storage.sync.get("status", function(result) {
        if (result["status"] === null) {
            status = "enabled";
        } else {
            status = result["status"];
        }
        if (status === "enabled") {
            icon = {
                "path": "images/disabled.png"
            };
            message = {
                "title": "click to enable xkcd substitutions"
            };
            status = "disabled";
        } else if (status === "disabled") {
            icon = {
                "path": "images/enabled.png"
            };
            message = {
                "title": "click to disabled xkcd substitutions"
            };
            status = "enabled";
        }
        chrome.browserAction.setIcon(icon);
        chrome.browserAction.setTitle(message);
        chrome.storage.sync.set({
            "status": status
        });
    });
}

chrome.browserAction.onClicked.addListener(toggleActive);
chrome.runtime.onMessage.addListener(addMessage);
chrome.tabs.onUpdated.addListener(injectionScript);
chrome.runtime.onInstalled.addListener(fixDataCorruption);
chrome.runtime.onStartup.addListener(fixDataCorruption);<commit_msg>added a man dressed like a bat joke<commit_after>//Default replacements
var default_replacements = [
    ['keyboard', 'leopard'],
    ['keyboards', 'leopards'],
    ['force', 'horse'],
    ['forces', 'horses'],
    ['witness', 'this dude I know'],
    ['witnesses', 'these dudes I know'],
    ['allegedly', 'kinda probably'],
    ['new study', 'tumblr post'],
    ['rebuild', 'avenge'],
    ['space', 'spaaaaaace'],
    ['google glass', 'virtual boy'],
    ['smartphone', 'pok\u00E9dex'],
    ['senator', 'elf-lord'],
    ['senators', 'elf-lords'],
    ['electric', 'atomic'],
    ['car', 'cat'],
    ['cars', 'cats'],
    ['election', 'eating contest'],
    ['elections', 'eating contests'],
    ['congressional leaders', 'river spirits'],
    ['homeland security', 'homestar runner'],
    ['could not be reached for comment', 'is guilty and everyone knows it'],
    ['batman', 'a man dressed like a bat'],
];
//Default Blacklist
var default_blacklisted_sites = ["docs.google.com",
    "gmail.com",
    "mail.google.com",
    "mail.yahoo.com",
    "outlook.com",
]

debug = false;

function checkBlackList(url, blacklist) {
    url = url.toLowerCase() || "";
    blacklist = blacklist || [];
    for (var i = blacklist.length - 1; i >= 0; i--) {
        if (url.indexOf(blacklist[i]) > -1) {
            return false;
        }
    };
    return true;
}

function injectionScript(tabId, info, tab) {
    if (debug) console.log("injection fire");
    chrome.storage.sync.get(null, function(result) {
        if (result["status"] === "enabled" && checkBlackList(tab.url, result['blacklist'])) {
            chrome.tabs.executeScript(tabId, {
                file: "js/substitutions.js",
                runAt: "document_end"
            });
        }
    });
}

function addMessage(request, sender, sendResponse) {
    if (debug) console.log("message fire");
    chrome.storage.sync.get(null, function(result) {
        if (request === "config" && result["replacements"]) {
            sendResponse(result["replacements"]);
        }
    });
    return true;
}

function fixDataCorruption() {
    if (debug) console.log("updateStore");
    chrome.storage.sync.get(null, function(result) {
        if (!result["status"]) {
            chrome.storage.sync.set({
                "status": "enabled"
            });
        }
        if (!result["replacements"]) {
            chrome.storage.sync.set({
                "replacements": default_replacements
            });
        }
        if (!result["replacements"]) {
            chrome.storage.sync.set({
                "blacklist": default_blacklisted_sites
            });
        }
    });
}

function toggleActive() {
    if (debug) console.log("clickfire");
    chrome.storage.sync.get("status", function(result) {
        if (result["status"] === null) {
            status = "enabled";
        } else {
            status = result["status"];
        }
        if (status === "enabled") {
            icon = {
                "path": "images/disabled.png"
            };
            message = {
                "title": "click to enable xkcd substitutions"
            };
            status = "disabled";
        } else if (status === "disabled") {
            icon = {
                "path": "images/enabled.png"
            };
            message = {
                "title": "click to disabled xkcd substitutions"
            };
            status = "enabled";
        }
        chrome.browserAction.setIcon(icon);
        chrome.browserAction.setTitle(message);
        chrome.storage.sync.set({
            "status": status
        });
    });
}

chrome.browserAction.onClicked.addListener(toggleActive);
chrome.runtime.onMessage.addListener(addMessage);
chrome.tabs.onUpdated.addListener(injectionScript);
chrome.runtime.onInstalled.addListener(fixDataCorruption);
chrome.runtime.onStartup.addListener(fixDataCorruption);<|endoftext|>


<commit_before>dojo.require("dojox.cometd");

dojo.addOnLoad(function()
{
    var cometd = dojox.cometd;

    // Idempotent function called every time the connection
    // with the Bayeux server is (re-)established
    var _subscription;
    function _connectionSucceeded()
    {
        dojo.byId('body').innerHTML = '
Cometd Connection Succeeded
';

        cometd.batch(function()
        {
            if (_subscription)
            {
                cometd.unsubscribe(_subscription);
            }
            _subscription = cometd.subscribe('/semispace/reply/readOrTake/1', function(message)
            {
                dojo.byId('body').innerHTML += '
Server Says:
' + message.data.result+ '

';
            });
            //// Publish on a service channel since the message is for the server only
            //cometd.publish('/service/hello', { name: 'World' });
            // Waiting an hour, if need be
            cometd.publish('/semispace/call/readOrTake/1', {duration: '600000', searchMap: {class: 'org.semispace.comet.demo.FieldHolder'}, shallTake: 'false'});
        });//
    }

    function _connectionBroken()
    {
        dojo.byId('body').innerHTML = 'Cometd Connection Broken';
    }

    // Function that manages the connection status with the Bayeux server
    var _connected = false;
    function _metaConnect(message)
    {
        var wasConnected = _connected;
        _connected = message.successful === true;
        if (!wasConnected && _connected)
        {
            _connectionSucceeded();
        }
        else if (wasConnected && !_connected)
        {
            _connectionBroken();
        }
    }

    // Disconnect when the page unloads
    dojo.addOnUnload(function()
    {
        cometd.disconnect();
    });

    var cometURL = location.protocol + "//" + location.host + config.contextPath + "/cometd";
    cometd.configure({
        url: cometURL,
        logLevel: 'debug'
    });

    cometd.addListener('/meta/connect', _metaConnect);

    cometd.handshake();
});
<commit_msg>Correcting demo app.<commit_after>dojo.require("dojox.cometd");

dojo.addOnLoad(function()
{
    var cometd = dojox.cometd;

    // Idempotent function called every time the connection
    // with the Bayeux server is (re-)established
    var _subscription;
    function _connectionSucceeded()
    {
        dojo.byId('body').innerHTML = '
Cometd Connection Succeeded
';

        cometd.batch(function()
        {
            if (_subscription)
            {
                cometd.unsubscribe(_subscription);
            }
            _subscription = cometd.subscribe('/semispace/reply/read/1', function(message)
            {
                dojo.byId('body').innerHTML += '
Server Says:
' + message.data.result+ '

';
            });
            //// Publish on a service channel since the message is for the server only
            //cometd.publish('/service/hello', { name: 'World' });
            // Waiting an hour, if need be
            cometd.publish('/semispace/call/read/1', {duration: '600000', searchMap: {semispaceObjectTypeKey: 'org.semispace.comet.demo.FieldHolder'}});
        });//
    }

    function _connectionBroken()
    {
        dojo.byId('body').innerHTML = 'Cometd Connection Broken';
    }

    // Function that manages the connection status with the Bayeux server
    var _connected = false;
    function _metaConnect(message)
    {
        var wasConnected = _connected;
        _connected = message.successful === true;
        if (!wasConnected && _connected)
        {
            _connectionSucceeded();
        }
        else if (wasConnected && !_connected)
        {
            _connectionBroken();
        }
    }

    // Disconnect when the page unloads
    dojo.addOnUnload(function()
    {
        cometd.disconnect();
    });

    var cometURL = location.protocol + "//" + location.host + config.contextPath + "/cometd";
    cometd.configure({
        url: cometURL,
        logLevel: 'debug'
    });

    cometd.addListener('/meta/connect', _metaConnect);

    cometd.handshake();
});
<|endoftext|>


<commit_before>import focusScope from 'a11y-focus-scope';
import focusStore from 'a11y-focus-store';
import BpkHeading from 'bpk-component-heading';
import { BpkButtonLink } from 'bpk-component-link';
import React, { PropTypes, Component } from 'react';
import BpkCloseButton from 'bpk-component-close-button';
import { TransitionInitialMount } from 'bpk-react-utils';

import './bpk-modal.scss';
import { lockScroll, unlockScroll, storeScroll, restoreScroll } from './scroll-utils';

const stopPropagation = (e) => {
  e.stopPropagation();
};

class BpkModalDialog extends Component {
  constructor() {
    super();

    this.onClose = this.onClose.bind(this);
    this.getDialogRef = this.getDialogRef.bind(this);
  }

  componentDidMount() {
    const { isIphone, getApplicationElement } = this.props;
    const applicationElement = getApplicationElement();

    if (isIphone && applicationElement) {
      storeScroll();
      applicationElement.style.display = 'none';
    } else if (applicationElement) {
      lockScroll();
      applicationElement.setAttribute('aria-hidden', 'true');
    } else {
      lockScroll();
    }

    focusStore.storeFocus();
    if (this.dialogElement) {
      focusScope.scopeFocus(this.dialogElement);
    }
  }

  componentWillUnmount() {
    const { isIphone, getApplicationElement } = this.props;
    const applicationElement = getApplicationElement();

    if (isIphone && applicationElement) {
      applicationElement.style.display = '';
      restoreScroll();
    } else if (applicationElement) {
      unlockScroll();
      applicationElement.removeAttribute('aria-hidden');
    } else {
      unlockScroll();
    }

    focusScope.unscopeFocus();
    focusStore.restoreFocus();
  }

  onClose(e) {
    stopPropagation(e);
    this.props.onClose();
  }

  getDialogRef(ref) {
    this.dialogElement = ref;
  }

  renderDialog() {
    const dialogClassName = 'bpk-modal__dialog';
    const dialogClassNames = [dialogClassName];

    if (this.props.wide) { dialogClassNames.push('bpk-modal__dialog--wide'); }
    if (this.props.isIphone) { dialogClassNames.push('bpk-modal__dialog--iphone-fix'); }

    const headingId = `bpk-modal-heading-${this.props.id}`;

    /* eslint-disable jsx-a11y/no-static-element-interactions */
    return (
      <TransitionInitialMount classNamePrefix={dialogClassName} transitionTimeout={300}>

            <BpkHeading id={headingId} level="h4" bottomMargin={false}>
              {this.props.title}
            </BpkHeading>

            {this.props.closeText
              ? <BpkButtonLink onClick={this.onClose}>{this.props.closeText}</BpkButtonLink>
              : <BpkCloseButton
                className="bpk-modal__dialog-close-button"
                label={this.props.closeLabel}
                onClick={this.onClose}
              />
            }

            {this.props.children}

      </TransitionInitialMount>
    );
    /* eslint-enable */
  }

  render() {
    const classNames = ['bpk-modal'];

    if (this.props.isIphone) { classNames.push('bpk-modal--iphone-fix'); }

    /* eslint-disable jsx-a11y/no-static-element-interactions */
    return (

        {this.renderDialog()}

    );
    /* eslint-enable */
  }
}

BpkModalDialog.propTypes = {
  id: PropTypes.string.isRequired,
  onClose: PropTypes.func.isRequired,
  title: PropTypes.string.isRequired,
  children: PropTypes.node.isRequired,
  getApplicationElement: PropTypes.func.isRequired,
  closeLabel: PropTypes.string,
  closeText: PropTypes.string,
  isIphone: PropTypes.bool,
  wide: PropTypes.bool,
};

BpkModalDialog.defaultProps = {
  closeLabel: null,
  closeText: null,
  isIphone: /iPhone/i.test(typeof window !== 'undefined' ? window.navigator.platform : ''),
  wide: false,
};

export default BpkModalDialog;
<commit_msg>Forward className to Modal component<commit_after>import focusScope from 'a11y-focus-scope';
import focusStore from 'a11y-focus-store';
import BpkHeading from 'bpk-component-heading';
import { BpkButtonLink } from 'bpk-component-link';
import React, { PropTypes, Component } from 'react';
import BpkCloseButton from 'bpk-component-close-button';
import { TransitionInitialMount } from 'bpk-react-utils';

import './bpk-modal.scss';
import { lockScroll, unlockScroll, storeScroll, restoreScroll } from './scroll-utils';

const stopPropagation = (e) => {
  e.stopPropagation();
};

class BpkModalDialog extends Component {
  constructor() {
    super();

    this.onClose = this.onClose.bind(this);
    this.getDialogRef = this.getDialogRef.bind(this);
  }

  componentDidMount() {
    const { isIphone, getApplicationElement } = this.props;
    const applicationElement = getApplicationElement();

    if (isIphone && applicationElement) {
      storeScroll();
      applicationElement.style.display = 'none';
    } else if (applicationElement) {
      lockScroll();
      applicationElement.setAttribute('aria-hidden', 'true');
    } else {
      lockScroll();
    }

    focusStore.storeFocus();
    if (this.dialogElement) {
      focusScope.scopeFocus(this.dialogElement);
    }
  }

  componentWillUnmount() {
    const { isIphone, getApplicationElement } = this.props;
    const applicationElement = getApplicationElement();

    if (isIphone && applicationElement) {
      applicationElement.style.display = '';
      restoreScroll();
    } else if (applicationElement) {
      unlockScroll();
      applicationElement.removeAttribute('aria-hidden');
    } else {
      unlockScroll();
    }

    focusScope.unscopeFocus();
    focusStore.restoreFocus();
  }

  onClose(e) {
    stopPropagation(e);
    this.props.onClose();
  }

  getDialogRef(ref) {
    this.dialogElement = ref;
  }

  renderDialog() {
    const dialogClassName = 'bpk-modal__dialog';
    const dialogClassNames = [dialogClassName];

    if (this.props.wide) { dialogClassNames.push('bpk-modal__dialog--wide'); }
    if (this.props.isIphone) { dialogClassNames.push('bpk-modal__dialog--iphone-fix'); }
    if (this.props.className !== null) { dialogClassNames.push(this.props.className); }

    const headingId = `bpk-modal-heading-${this.props.id}`;

    /* eslint-disable jsx-a11y/no-static-element-interactions */
    return (
      <TransitionInitialMount classNamePrefix={dialogClassName} transitionTimeout={300}>

            <BpkHeading id={headingId} level="h4" bottomMargin={false}>
              {this.props.title}
            </BpkHeading>

            {this.props.closeText
              ? <BpkButtonLink onClick={this.onClose}>{this.props.closeText}</BpkButtonLink>
              : <BpkCloseButton
                className="bpk-modal__dialog-close-button"
                label={this.props.closeLabel}
                onClick={this.onClose}
              />
            }

            {this.props.children}

      </TransitionInitialMount>
    );
    /* eslint-enable */
  }

  render() {
    const classNames = ['bpk-modal'];

    if (this.props.isIphone) { classNames.push('bpk-modal--iphone-fix'); }

    /* eslint-disable jsx-a11y/no-static-element-interactions */
    return (

        {this.renderDialog()}

    );
    /* eslint-enable */
  }
}

BpkModalDialog.propTypes = {
  id: PropTypes.string.isRequired,
  className: PropTypes.string,
  onClose: PropTypes.func.isRequired,
  title: PropTypes.string.isRequired,
  children: PropTypes.node.isRequired,
  getApplicationElement: PropTypes.func.isRequired,
  closeLabel: PropTypes.string,
  closeText: PropTypes.string,
  isIphone: PropTypes.bool,
  wide: PropTypes.bool,
};

BpkModalDialog.defaultProps = {
  className: null,
  closeLabel: null,
  closeText: null,
  isIphone: /iPhone/i.test(typeof window !== 'undefined' ? window.navigator.platform : ''),
  wide: false,
};

export default BpkModalDialog;
<|endoftext|>


<commit_before>/**
 * Pimcore
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.pimcore.org/license
 *
 * @copyright  Copyright (c) 2009-2013 pimcore GmbH (http://www.pimcore.org)
 * @license    http://www.pimcore.org/license     New BSD License
 */

pimcore.registerNS("pimcore.document.tags.input");
pimcore.document.tags.input = Class.create(pimcore.document.tag, {

    initialize: function(id, name, options, data, inherited) {
        this.id = id;
        this.name = name;
        this.setupWrapper();
        options = this.parseOptions(options);

        if (!data) {
            data = "";
        }

        if(!options.width) {
            options.width = Ext.get(id).getWidth()-2;
        }

        options.value = data;
        options.name = id + "_editable";
        this.element = new Ext.form.TextField(options);
        this.element.render(id);

        if(options["autoStyle"] !== false) {
            var styles = Ext.get(id).parent().getStyles("font-size","font-family","font-style","font-weight",
                                "font-stretch","font-variant","color","line-height","text-shadow","text-align",
                                "text-decoration","text-transform","direction","white-space","word-spacing");
            styles["background"] = "none";
            if(!options["height"]) {
                styles["height"] = "auto";
            }
            this.element.getEl().applyStyles(styles);

            // necessary for IE9
            window.setTimeout(function () {
                this.element.getEl().repaint();
            }.bind(this), 300);
        }
    },

    getValue: function () {
        return this.element.getValue();
    },

    getType: function () {
        return "input";
    }
});
<commit_msg>document input tag bugfix<commit_after>/**
 * Pimcore
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.pimcore.org/license
 *
 * @copyright  Copyright (c) 2009-2013 pimcore GmbH (http://www.pimcore.org)
 * @license    http://www.pimcore.org/license     New BSD License
 */

pimcore.registerNS("pimcore.document.tags.input");
pimcore.document.tags.input = Class.create(pimcore.document.tag, {

    initialize: function(id, name, options, data, inherited) {
        this.id = id;
        this.name = name;
        this.setupWrapper();
        options = this.parseOptions(options);

        if (!data) {
            data = "";
        }

        if(!options.width) {
            options.width = Ext.get(id).getWidth()-2;
        }

        options.value = data;
        options.name = id + "_editable";
        this.element = new Ext.form.TextField(options);
        this.element.render(id);

        if(options["autoStyle"] !== false) {
            var styles = Ext.get(id).parent().getStyles("font-size","font-family","font-style","font-weight",
                                "font-stretch","font-variant","color","line-height","text-shadow","text-align",
                                "text-decoration","text-transform","direction","white-space","word-spacing");
            styles["background"] = "none";
            if(!options["height"]) {
                styles["height"] = "auto";
            }
            if(styles["font-size"] == "0px") {
                delete styles["font-size"];
            }

            this.element.getEl().applyStyles(styles);

            // necessary for IE9
            window.setTimeout(function () {
                this.element.getEl().repaint();
            }.bind(this), 300);
        }
    },

    getValue: function () {
        return this.element.getValue();
    },

    getType: function () {
        return "input";
    }
});
<|endoftext|>