<commit_before>/* eslint-disable no-template-curly-in-string */
const path = require('path');
const meta = require('user-meta');
const gitUsername = require('git-username');
const { json, install } = require('mrm-core');

const packages = ['schema-utils', 'loader-utils'];

const devPackages = [
  // Utilities
  'nsp',
  'del',
  'del-cli',
  'cross-env',
  'memory-fs',
  'standard-version',
  '@commitlint/cli',
  '@commitlint/config-angular',
  'conventional-github-releaser',
  'husky',

  // Jest
  'jest',
  'babel-jest',

  // Babel
  'babel-cli',
  'babel-polyfill',
  'babel-preset-env',
  'babel-plugin-transform-object-rest-spread',

  // ESLint
  'eslint',
  'eslint-plugin-import',
  'eslint-plugin-prettier',
  '@webpack-contrib/eslint-config-webpack',
  'lint-staged',
  'pre-commit',
  'prettier',

  // Webpack
  'webpack',
];

module.exports = (config) => {
  const { name } = meta;
  const github = gitUsername();
  const packageName = path.basename(process.cwd());
  const repository = `${github}/${packageName}`;

  const file = json('package.json');
  const existing = file.get();

  json('package.json')
    .set({
      name: `${packageName}`,
      version: existing.version || '1.0.0',
      description: existing.description || '',
      license: existing.license || 'MIT',
      repository: `${repository}`,
      author: existing.author || `${name}`,
      homepage: `https://github.com/${repository}`,
      bugs: `https://github.com/${repository}/issues`,
      main: existing.main || 'dist/cjs.js',
      engines: {
        node: `>= ${config.maintLTS}`,
      },
      scripts: {
        start: 'npm run build -- -w',
        build:
          "cross-env NODE_ENV=production babel src -d dist --ignore 'src/**/*.test.js' --copy-files",
        clean: 'del-cli dist',
        commitlint: 'commitlint',
        commitmsg: 'commitlint -e $GIT_PARAMS',
        lint: 'eslint --cache src test',
        'ci:lint:commits':
          'commitlint --from=${CIRCLE_BRANCH} --to=${CIRCLE_SHA1}',
        'lint-staged': 'lint-staged',
        prebuild: 'npm run clean',
        prepublish: 'npm run build',
        release: 'standard-version',
        'release:ci': 'conventional-github-releaser -p angular',
        'release:validate':
          'commitlint --from=$(git describe --tags --abbrev=0) --to=$(git rev-parse HEAD)',
        security: 'nsp check',
        test: 'jest',
        'test:watch': 'jest --watch',
        'test:coverage': "jest --collectCoverageFrom='src/**/*.js' --coverage",
        'ci:lint': 'npm run lint && npm run security',
        'ci:test': 'npm run test -- --runInBand',
        'ci:coverage': 'npm run test:coverage -- --runInBand',
        defaults: 'webpack-defaults',
      },
      files: existing.files || ['dist/', 'lib/', 'index.js'],
      keywords: existing.keywords || ['webpack'],
      peerDependencies: existing.peerDependencies || { webpack: '^4.3.0' },
      dependencies: existing.dependencies || {},
      devDependencies: existing.devDependencies || {},
      'pre-commit': 'lint-staged',
      'lint-staged': {
        '*.js': ['eslint --fix', 'git add'],
      },
    })
    .save();
  install(packages, { dev: false });
  install(devPackages);
};
<commit_msg>fix(package): Use proper Node engines range<commit_after>/* eslint-disable no-template-curly-in-string */
const path = require('path');
const meta = require('user-meta');
const gitUsername = require('git-username');
const { json, install } = require('mrm-core');

const packages = ['schema-utils', 'loader-utils'];

const devPackages = [
  // Utilities
  'nsp',
  'del',
  'del-cli',
  'cross-env',
  'memory-fs',
  'standard-version',
  '@commitlint/cli',
  '@commitlint/config-angular',
  'conventional-github-releaser',
  'husky',

  // Jest
  'jest',
  'babel-jest',

  // Babel
  'babel-cli',
  'babel-polyfill',
  'babel-preset-env',
  'babel-plugin-transform-object-rest-spread',

  // ESLint
  'eslint',
  'eslint-plugin-import',
  'eslint-plugin-prettier',
  '@webpack-contrib/eslint-config-webpack',
  'lint-staged',
  'pre-commit',
  'prettier',

  // Webpack
  'webpack',
];

module.exports = (config) => {
  const { name } = meta;
  const github = gitUsername();
  const packageName = path.basename(process.cwd());
  const repository = `${github}/${packageName}`;

  const file = json('package.json');
  const existing = file.get();

  json('package.json')
    .set({
      name: `${packageName}`,
      version: existing.version || '1.0.0',
      description: existing.description || '',
      license: existing.license || 'MIT',
      repository: `${repository}`,
      author: existing.author || `${name}`,
      homepage: `https://github.com/${repository}`,
      bugs: `https://github.com/${repository}/issues`,
      main: existing.main || 'dist/cjs.js',
      engines: {
        node: `>= ${config.maintLTS} || >= ${config.activeLTS}`,
      },
      scripts: {
        start: 'npm run build -- -w',
        build:
          "cross-env NODE_ENV=production babel src -d dist --ignore 'src/**/*.test.js' --copy-files",
        clean: 'del-cli dist',
        commitlint: 'commitlint',
        commitmsg: 'commitlint -e $GIT_PARAMS',
        lint: 'eslint --cache src test',
        'ci:lint:commits':
          'commitlint --from=${CIRCLE_BRANCH} --to=${CIRCLE_SHA1}',
        'lint-staged': 'lint-staged',
        prebuild: 'npm run clean',
        prepublish: 'npm run build',
        release: 'standard-version',
        'release:ci': 'conventional-github-releaser -p angular',
        'release:validate':
          'commitlint --from=$(git describe --tags --abbrev=0) --to=$(git rev-parse HEAD)',
        security: 'nsp check',
        test: 'jest',
        'test:watch': 'jest --watch',
        'test:coverage': "jest --collectCoverageFrom='src/**/*.js' --coverage",
        'ci:lint': 'npm run lint && npm run security',
        'ci:test': 'npm run test -- --runInBand',
        'ci:coverage': 'npm run test:coverage -- --runInBand',
        defaults: 'webpack-defaults',
      },
      files: existing.files || ['dist/', 'lib/', 'index.js'],
      keywords: existing.keywords || ['webpack'],
      peerDependencies: existing.peerDependencies || { webpack: '^4.3.0' },
      dependencies: existing.dependencies || {},
      devDependencies: existing.devDependencies || {},
      'pre-commit': 'lint-staged',
      'lint-staged': {
        '*.js': ['eslint --fix', 'git add'],
      },
    })
    .save();
  install(packages, { dev: false });
  install(devPackages);
};
<|endoftext|>


<commit_before>import {SidebarService} from 'sidebarjs';

class SidebarJSCtrl {
  /* @ngInject */
  constructor($scope, $element, SidebarJS) {
    this.$scope = $scope;
    this.SidebarJS = SidebarJS;
    this.elem = $element[0];
  }

  $onInit() {
    this.sidebarjsName = this.sidebarjsName || '';
    this.elem.setAttribute('sidebarjs', this.sidebarjsName);
  }

  $postLink() {
    const container = this.elem.children[0];
    const background = this.elem.children[1];
    const config = {...this.sidebarjsConfig, component: this.elem, container, background};
    this.SidebarJS.create(config);
    this.addTransitionListener(container);
  }

  $onDestroy() {
    this.SidebarJS.destroy(this.sidebarjsName);
  }

  addTransitionListener(container) {
    let wasVisible = false;
    container.addEventListener('transitionend', () => {
      const isVisible = this.SidebarJS.isVisible(this.sidebarjsName);
      if (this.onOpen && isVisible && !wasVisible) {
        wasVisible = true;
        this.onOpen();
      } else if (this.onClose && !isVisible && wasVisible) {
        wasVisible = false;
        this.onClose();
      }
      this.$scope.$applyAsync();
    }, false);
  }
}

function SidebarJSDirective(action) {
  return {
    /* @ngInject */
    controller(SidebarJS) {
      this.SidebarJS = SidebarJS;
    },
    link(scope, elem, attrs, ctrl) {
      if (!ctrl.SidebarJS.elemHasListener(elem[0])) {
        const sidebarName = attrs[`sidebarjs${action.charAt(0).toUpperCase() + action.slice(1)}`];
        elem[0].addEventListener('click', () => ctrl.SidebarJS[action](sidebarName));
        ctrl.SidebarJS.elemHasListener(elem[0], true);
      }
    },
  };
}

angular
  .module('ngSidebarJS', [])
  .service('SidebarJS', SidebarService)
  .component('sidebarjs', {
    template: '

',
    transclude: true,
    controller: SidebarJSCtrl,
    bindings: {
      onOpen: '&?',
      onClose: '&?',
      sidebarjsConfig: '<?',
      sidebarjsName: '@?',
    },
  })
  .directive('sidebarjsOpen', SidebarJSDirective.bind(null, 'open'))
  .directive('sidebarjsClose', SidebarJSDirective.bind(null, 'close'))
  .directive('sidebarjsToggle', SidebarJSDirective.bind(null, 'toggle'));
<commit_msg>refactor(sidebarjs): background > backdrop<commit_after>import {SidebarService} from 'sidebarjs';

class SidebarJSCtrl {
  /* @ngInject */
  constructor($scope, $element, SidebarJS) {
    this.$scope = $scope;
    this.SidebarJS = SidebarJS;
    this.elem = $element[0];
  }

  $onInit() {
    this.sidebarjsName = this.sidebarjsName || '';
    this.elem.setAttribute('sidebarjs', this.sidebarjsName);
  }

  $postLink() {
    const container = this.elem.children[0];
    const backdrop = this.elem.children[1];
    const config = {...this.sidebarjsConfig, component: this.elem, container, backdrop};
    this.SidebarJS.create(config);
    this.addTransitionListener(container);
  }

  $onDestroy() {
    this.SidebarJS.destroy(this.sidebarjsName);
  }

  addTransitionListener(container) {
    let wasVisible = false;
    container.addEventListener('transitionend', () => {
      const isVisible = this.SidebarJS.isVisible(this.sidebarjsName);
      if (this.onOpen && isVisible && !wasVisible) {
        wasVisible = true;
        this.onOpen();
      } else if (this.onClose && !isVisible && wasVisible) {
        wasVisible = false;
        this.onClose();
      }
      this.$scope.$applyAsync();
    }, false);
  }
}

function SidebarJSDirective(action) {
  return {
    /* @ngInject */
    controller(SidebarJS) {
      this.SidebarJS = SidebarJS;
    },
    link(scope, elem, attrs, ctrl) {
      if (!ctrl.SidebarJS.elemHasListener(elem[0])) {
        const sidebarName = attrs[`sidebarjs${action.charAt(0).toUpperCase() + action.slice(1)}`];
        elem[0].addEventListener('click', () => ctrl.SidebarJS[action](sidebarName));
        ctrl.SidebarJS.elemHasListener(elem[0], true);
      }
    },
  };
}

angular
  .module('ngSidebarJS', [])
  .service('SidebarJS', SidebarService)
  .component('sidebarjs', {
    template: '

',
    transclude: true,
    controller: SidebarJSCtrl,
    bindings: {
      onOpen: '&?',
      onClose: '&?',
      sidebarjsConfig: '<?',
      sidebarjsName: '@?',
    },
  })
  .directive('sidebarjsOpen', SidebarJSDirective.bind(null, 'open'))
  .directive('sidebarjsClose', SidebarJSDirective.bind(null, 'close'))
  .directive('sidebarjsToggle', SidebarJSDirective.bind(null, 'toggle'));
<|endoftext|>


<commit_before>var orm = require('../../../dbbs');
var Subscriber = orm.model("subscriber");
var request = require('request');
var assert = require('assert');
var fs = require('fs');

orm.setup()

var testEmail = 'oron.hazi@gmail.com';
var token;

describe('Testing registration requests:',function() {
  it('User registered successfully',function(done) {
//    this.timeout(5000);
    request( {
      url: 'http://localhost:3000/api/subscriber/register',
      body: '{ \"email\": \"'+testEmail+'\", \"password\": \"my password\"}',
      headers: {
        'Content-Type': 'application/json'
      },
      method: 'POST'
    }, function (error, response, body) {
      assert(JSON.parse(body)['value'],'Unable to register user');
      console.log('\tResponse received : ', body);
      fs.exists(process.cwd()+'/temp', function (exists) {
        if(exists) {
          fs.readFile(process.cwd()+'/temp','utf8',function (err,data) {
            if (err) console.log('Unable to read token in file for restTest');
            else{ token = data;}
          });
        }
      });
      done();
    });
  });
  it('Email Already in Use',function(done) {
    request( {
      url: 'http://localhost:3000/api/subscriber/register',
      body: '{ \"email\": \"'+testEmail+'\", \"password\": \"my password\", \"ip\": \"192.162.0.8\"}',
      headers: {
        'Content-Type': 'application/json'
      },
      method: 'POST'
    }, function (error, response, body) {
      assert.equal(JSON.parse(body)['error']['type'],'emailInUse');
      console.log('\tResponse received : ', body);
      done();
    });
  });
  it('Bad Password',function(done) {
    request( {
      url: 'http://localhost:3000/api/subscriber/register',
      body: '{ \"email\": \"Something@gmailler.com\", \"password\": \"my\"}',
      headers: {
        'Content-Type': 'application/json'
      },
      method: 'POST'
    }, function (error, response, body) {
      assert.equal(JSON.parse(body)['error']['type'],'badPwd');
      console.log('\tResponse received : ', body);
      done();
    });
  });
  it('Bad email',function(done) {
    request( {
      url: 'http://localhost:3000/api/subscriber/register',
      body: '{ \"email\": \"asdf.com\", \"password\": \"my password\"}',
      headers: {
        'Content-Type': 'application/json'
      },
      method: 'POST'
    }, function (error, response, body) {
      assert.equal(JSON.parse(body)['error']['type'],'badEmail');
      console.log('\tResponse received : ', body);
      done();
    });
  });
  it('Missing Password',function(done) {
    request( {
      url: 'http://localhost:3000/api/subscriber/register',
      body: '{ \"email\": \"'+testEmail+'\", \"password\": \"\"}',
      headers: {
        'Content-Type': 'application/json'
      },
      method: 'POST'
    }, function (error, response, body) {
      assert.equal(JSON.parse(body)['error']['type'],'missingPwd');
      console.log('\tResponse received : ', body);
      done();
    });
  });
  it('Missing Email',function(done) {
    request( {
      url: 'http://localhost:3000/api/subscriber/register',
      body: '{ \"email\": \"\", \"password\": \"my password\"}',
      headers: {
        'Content-Type': 'application/json'
      },
      method: 'POST'
    }, function (error, response, body) {
      assert.equal(JSON.parse(body)['error']['type'],'missingEmail');
      console.log('\tResponse received : ', body);
      done();
    });
  });
});

describe('Testing verification requests:',function() {
  it('User verified successfully',function(done) {
    request( {
      url: 'http://localhost:3000/api/subscriber/verify/',
      body: '{ \"token\": \"'+token+'\"}',
      headers: {
        'Content-Type': 'application/json'
      },
      method: 'POST'
    },
    function (error, response, body) {
      //console.log('\tResponse received : ', body,response);
      console.log(token);
			assert(JSON.parse(body)['value'],'Unable to verify user');
      done();
    });
  });

  it('User already verified',function(done) {
    request( {
      url: 'http://localhost:3000/api/subscriber/verify/',
	body: '{ \"token\": \"'+token+'\"}',
	headers: {
		'Content-Type': 'application/json'
	},
      method: 'POST'
    }, function (error, response, body) {
      assert.equal(JSON.parse(body)['error']['type'],'subscriberAlreadyVerified');
      console.log('\tResponse received : ', body);
      done();
    });
  });

  it('Missing verification token',function(done) {
    request( {
      url: 'http://localhost:3000/api/subscriber/verify/',
	body: '{ \"token\": \"'+''+'\"}',
	headers: {
		'Content-Type': 'application/json'
	},
      method: 'POST'
    }, function (error, response, body) {
      assert.equal(JSON.parse(body)['error']['type'],'missingVerificationToken');
      console.log('\tResponse received : ', body);
      done();
    });
  });

  it('Bad verification token',function(done) {
    request( {
      url: 'http://localhost:3000/api/subscriber/verify/Bad-Token',
	body: '{ \"token\": \"'+'bad_token'+'\"}',
	headers: {
                'Content-Type': 'application/json'
        },
      method: 'POST'
    }, function (error, response, body) {
      assert.equal(JSON.parse(body)['error']['type'],'badVerificationToken');
      console.log('\tResponse received : ', body);
      done();
    });
  });
});
/*
var session;
describe('Testing subscriber login:',function() {
  it('Subscriber logged in successfully',function(done) {
    request( {
      url: 'http://localhost:3000/api/subscriber/login',
      body: '{ \"email\": \"'+testEmail+'\", \"password\": \"my password\"}',
      headers: {
        'Content-Type': 'application/json'
      },
      method: 'POST'
    }, function (error, response, body) {
      assert(JSON.parse(body)['value'],'Unable to login user');
      console.log('\tResponse received : ', body);
      session = JSON.parse(body)['value'];
      done();
    });
  });
  it('Missing Subscriber\'s Email Address',function(done) {
    request( {
      url: 'http://localhost:3000/api/subscriber/login',
      body: '{ \"email\": \"\", \"password\": \"my password\"}',
      headers: {
        'Content-Type': 'application/json'
      },
      method: 'POST'
    }, function (error, response, body) {
      assert.equal(JSON.parse(body)['error']['type'],'missingEmail');
      console.log('\tResponse received : ', body);
      done();
    });
  });
  it('Incorrect Email Address',function(done) {
    request( {
      url: 'http://localhost:3000/api/subscriber/login',
      body: '{ \"email\": \"a-terriblest-email\", \"password\": \"my password\"}',
      headers: {
        'Content-Type': 'application/json'
      },
      method: 'POST'
    }, function (error, response, body) {
      assert.equal(JSON.parse(body)['error']['type'],'badEmail');
      console.log('\tResponse received : ', body);
      done();
    });
  });
  it('Incorrect password',function(done) {
    request( {
      url: 'http://localhost:3000/api/subscriber/login',
      body: '{ \"email\": \"'+testEmail+'\", \"password\": \"\"}',
      headers: {
        'Content-Type': 'application/json'
      },
      method: 'POST'
    }, function (error, response, body) {
      assert.equal(JSON.parse(body)['error']['type'],'incorrectPwd');
      console.log('\tResponse received : ', body);
      done();
    });
  });
});

describe('Testing subscriber logout:',function() {
  it('Subscriber logged out successfully',function(done) {
    request( {
      url: 'http://localhost:3000/api/subscriber/logout',
      body: '{ \"email\": \"'+testEmail+'\", \"password\": \"my password\"}',
      headers: {
        'Content-Type': 'application/json',
        'x-access-token': session
      },
      method: 'POST'
    }, function (error, response, body) {
      //assert(JSON.parse(body)['value'],'Unable to logout user');
      console.log('\tResponse received : ', body);
      done();
    });
  });
});
/*
describe('Testing subscriber forgot password:',function() {
  it('Subscriber password link sent successfully',function(done) {
    request( {
      url: 'http://localhost:3000/api/subscriber/reset',
      body: '{ \"email\": \"'+testEmail+'\"}',
      headers: {
        'Content-Type': 'application/json'
      },
      method: 'POST'
    }, function (error, response, body) {
      //assert(JSON.parse(body)['value'],'Unable to logout user');
      console.log('\tResponse received : ', body);
      done();
    });
  });
});
*/

<commit_msg>update restTest<commit_after>var orm = require('../../../dbbs');
var Subscriber = orm.model("subscriber");
var request = require('request');
var assert = require('assert');
var fs = require('fs');

orm.setup()

var testEmail = 'oron.hazi@gmail.com';
var token;

describe('Testing registration requests:',function() {
  it('User registered successfully',function(done) {
//    this.timeout(5000);
    request( {
      url: 'http://localhost:3000/api/subscriber/register',
      body: '{ \"email\": \"'+testEmail+'\", \"password\": \"my password\"}',
      headers: {
        'Content-Type': 'application/json'
      },
      method: 'POST'
    }, function (error, response, body) {
      assert(JSON.parse(body)['value'],'Unable to register user');
      console.log('\tResponse received : ', body);
      fs.exists(process.cwd()+'/temp', function (exists) {
        if(exists) {
          fs.readFile(process.cwd()+'/temp','utf8',function (err,data) {
            if (err) console.log('Unable to read token in file for restTest');
            else{ token = data;}
          });
        }
      });
      done();
    });
  });
  it('Email Already in Use',function(done) {
    request( {
      url: 'http://localhost:3000/api/subscriber/register',
      body: '{ \"email\": \"'+testEmail+'\", \"password\": \"my password\", \"ip\": \"192.162.0.8\"}',
      headers: {
        'Content-Type': 'application/json'
      },
      method: 'POST'
    }, function (error, response, body) {
      assert.equal(JSON.parse(body)['error']['type'],'emailInUse');
      console.log('\tResponse received : ', body);
      done();
    });
  });
  it('Bad Password',function(done) {
    request( {
      url: 'http://localhost:3000/api/subscriber/register',
      body: '{ \"email\": \"Something@gmailler.com\", \"password\": \"my\"}',
      headers: {
        'Content-Type': 'application/json'
      },
      method: 'POST'
    }, function (error, response, body) {
      assert.equal(JSON.parse(body)['error']['type'],'badPwd');
      console.log('\tResponse received : ', body);
      done();
    });
  });
  it('Bad email',function(done) {
    request( {
      url: 'http://localhost:3000/api/subscriber/register',
      body: '{ \"email\": \"asdf.com\", \"password\": \"my password\"}',
      headers: {
        'Content-Type': 'application/json'
      },
      method: 'POST'
    }, function (error, response, body) {
      assert.equal(JSON.parse(body)['error']['type'],'badEmail');
      console.log('\tResponse received : ', body);
      done();
    });
  });
  it('Missing Password',function(done) {
    request( {
      url: 'http://localhost:3000/api/subscriber/register',
      body: '{ \"email\": \"'+testEmail+'\", \"password\": \"\"}',
      headers: {
        'Content-Type': 'application/json'
      },
      method: 'POST'
    }, function (error, response, body) {
      assert.equal(JSON.parse(body)['error']['type'],'missingPwd');
      console.log('\tResponse received : ', body);
      done();
    });
  });
  it('Missing Email',function(done) {
    request( {
      url: 'http://localhost:3000/api/subscriber/register',
      body: '{ \"email\": \"\", \"password\": \"my password\"}',
      headers: {
        'Content-Type': 'application/json'
      },
      method: 'POST'
    }, function (error, response, body) {
      assert.equal(JSON.parse(body)['error']['type'],'missingEmail');
      console.log('\tResponse received : ', body);
      done();
    });
  });
});

describe('Testing verification requests:',function() {
  it('User verified successfully',function(done) {
    request( {
      url: 'http://localhost:3000/api/subscriber/verify/',
      body: '{ \"token\": \"'+token+'\"}',
      headers: {
        'Content-Type': 'application/json'
      },
      method: 'POST'
    },
    function (error, response, body) {
      //console.log('\tResponse received : ', body,response);
      console.log(token);
			assert(JSON.parse(body)['value'],'Unable to verify user');
      done();
    });
  });

  it('User already verified',function(done) {
    request( {
      url: 'http://localhost:3000/api/subscriber/verify/',
	body: '{ \"token\": \"'+token+'\"}',
	headers: {
		'Content-Type': 'application/json'
	},
      method: 'POST'
    }, function (error, response, body) {
      assert.equal(JSON.parse(body)['error']['type'],'subscriberAlreadyVerified');
      console.log('\tResponse received : ', body);
      done();
    });
  });

  it('Missing verification token',function(done) {
    request( {
      url: 'http://localhost:3000/api/subscriber/verify/',
	body: '{ \"token\": \"'+''+'\"}',
	headers: {
		'Content-Type': 'application/json'
	},
      method: 'POST'
    }, function (error, response, body) {
      assert.equal(JSON.parse(body)['error']['type'],'missingVerificationToken');
      console.log('\tResponse received : ', body);
      done();
    });
  });

  it('Bad verification token',function(done) {
    request( {
      url: 'http://localhost:3000/api/subscriber/verify/Bad-Token',
	body: '{ \"token\": \"'+'bad_token'+'\"}',
	headers: {
                'Content-Type': 'application/json'
        },
      method: 'POST'
    }, function (error, response, body) {
      assert.equal(JSON.parse(body)['error']['type'],'badVerificationToken');
      console.log('\tResponse received : ', body);
      done();
    });
  });
});

var session;
describe('Testing subscriber login:',function() {
  it('Subscriber logged in successfully',function(done) {
    request( {
      url: 'http://localhost:3000/api/subscriber/login',
      body: '{ \"email\": \"'+testEmail+'\", \"password\": \"my password\"}',
      headers: {
        'Content-Type': 'application/json'
      },
      method: 'POST'
    }, function (error, response, body) {
      assert(JSON.parse(body)['value'],'Unable to login user');
      console.log('\tResponse received : ', body);
      session = JSON.parse(body)['value'];
      done();
    });
  });
  it('Missing Subscriber\'s Email Address',function(done) {
    request( {
      url: 'http://localhost:3000/api/subscriber/login',
      body: '{ \"email\": \"\", \"password\": \"my password\"}',
      headers: {
        'Content-Type': 'application/json'
      },
      method: 'POST'
    }, function (error, response, body) {
      assert.equal(JSON.parse(body)['error']['type'],'missingEmail');
      console.log('\tResponse received : ', body);
      done();
    });
  });
  it('Invalid Email Address',function(done) {
    request( {
      url: 'http://localhost:3000/api/subscriber/login',
      body: '{ \"email\": \"a-terriblest-email\", \"password\": \"my password\"}',
      headers: {
        'Content-Type': 'application/json'
      },
      method: 'POST'
    }, function (error, response, body) {
      assert.equal(JSON.parse(body)['error']['type'],'badEmail');
      console.log('\tResponse received : ', body);
      done();
    });
  });
  it('Incorrect password',function(done) {
    request( {
      url: 'http://localhost:3000/api/subscriber/login',
      body: '{ \"email\": \"'+testEmail+'\", \"password\": \"'+'badPassword'+\"}',
      headers: {
        'Content-Type': 'application/json'
      },
      method: 'POST'
    }, function (error, response, body) {
      assert.equal(JSON.parse(body)['error']['type'],'incorrectPwd');
      console.log('\tResponse received : ', body);
      done();
    });
  });
  it('Unregistered user',function(done) {
  });
  it('Unverified sunscriber', function(done) {
	//register a user first, do not verify
	//before hook
	//make registration request before logging in user
	before(function() {
		request( {
     		 url: 'http://localhost:3000/api/subscriber/register',
     		 body: '{ \"email\": \"'+testEmail+'\", \"password\": \"my password\"}',
     		 headers: {
        		'Content-Type': 'application/json'
     		 },
     		 method: 'POST'
   		 }, function (error, response, body) {
     			 assert(JSON.parse(body)['value'],'Unable to register user');
     			 console.log('\tResponse received : ', body);
    		});
	});
  });
  it('Missing password',function(done) {
    request( {
      url: 'http://localhost:3000/api/subscriber/login',
      body: '{ \"email\": \"'+testEmail+'\", \"password\": \"\"}',
      headers: {
        'Content-Type': 'application/json'
      },
      method: 'POST'
    }, function (error, response, body) {
      assert.equal(JSON.parse(body)['error']['type'],'missingPwd');
      console.log('\tResponse received : ', body);
      done();
    });
  });

});
/*
describe('Testing subscriber logout:',function() {
  it('Subscriber logged out successfully',function(done) {
    request( {
      url: 'http://localhost:3000/api/subscriber/logout',
      body: '{ \"email\": \"'+testEmail+'\", \"password\": \"my password\"}',
      headers: {
        'Content-Type': 'application/json',
        'x-access-token': session
      },
      method: 'POST'
    }, function (error, response, body) {
      //assert(JSON.parse(body)['value'],'Unable to logout user');
      console.log('\tResponse received : ', body);
      done();
    });
  });
});
/*
describe('Testing subscriber forgot password:',function() {
  it('Subscriber password link sent successfully',function(done) {
    request( {
      url: 'http://localhost:3000/api/subscriber/reset',
      body: '{ \"email\": \"'+testEmail+'\"}',
      headers: {
        'Content-Type': 'application/json'
      },
      method: 'POST'
    }, function (error, response, body) {
      //assert(JSON.parse(body)['value'],'Unable to logout user');
      console.log('\tResponse received : ', body);
      done();
    });
  });
});
*/

<|endoftext|>


<commit_before>const generateJWT = require('../utilities/jwt');
const google = require('googleapis');
const moment = require('moment');

export default function list(options) {
  const {
    calendarId,
    timeStart,
    startDT,
    endDT,
    orderBy,
    maxResults,
  } = options;

  return new Promise(async (res, rej) => {
    const jwtClient = await generateJWT();
    const calendar = google.calendar({
      version: 'v3',
      auth: jwtClient,
    });
    const timeMin =
      timeStart || startDT || moment().subtract(1, 'hours').toISOString();
    let finalOptions = {
      calendarId,
      timeMin,
      maxResults: maxResults || 250,
      singleEvents: true,
      orderBy: orderBy || 'startTime',
    };

    if (endDT)
      finalOptions = Object.assign(
        {
          timeMax: endDT,
        },
        finalOptions,
      );

    // console.log(`finalOptions=${JSON.stringify(finalOptions, null, 2)}`);

    calendar.events.list(finalOptions, async (err, response) => {
      if (err) {
        rej(err);
      } else {
        res(response.items);
      }
    });
  });
}
<commit_msg>on a average customer takes 1~2 hrs for an appointment, so i put 3 hours so that i can show last appointment for modification when required<commit_after>const generateJWT = require('../utilities/jwt');
const google = require('googleapis');
const moment = require('moment');

export default function list(options) {
  const {
    calendarId,
    timeStart,
    startDT,
    endDT,
    orderBy,
    maxResults,
  } = options;

  return new Promise(async (res, rej) => {
    const jwtClient = await generateJWT();
    const calendar = google.calendar({
      version: 'v3',
      auth: jwtClient,
    });
    const timeMin =
      timeStart || startDT || moment().subtract(3, 'hours').toISOString();
    let finalOptions = {
      calendarId,
      timeMin,
      maxResults: maxResults || 250,
      singleEvents: true,
      orderBy: orderBy || 'startTime',
    };

    if (endDT)
      finalOptions = Object.assign(
        {
          timeMax: endDT,
        },
        finalOptions,
      );

    // console.log(`finalOptions=${JSON.stringify(finalOptions, null, 2)}`);

    calendar.events.list(finalOptions, async (err, response) => {
      if (err) {
        rej(err);
      } else {
        res(response.items);
      }
    });
  });
}
<|endoftext|>


<commit_before>const moment = require('moment');
const getConfig = require('./configs').get;
const key = require('../keys/google.json');
const google = require('googleapis');

const WORK_EMAIL = getConfig('work_email');

let moduleToken = null;
let jwtClient = null;

function generateJWT(subject = null) {
  if (moduleToken) {
    // console.error('moduleToken', moduleToken);
    if (moduleToken.expiry_date) {
      // console.error('moduleToken.expiry_date', moduleToken.expiry_date);
      if (
        moment(moduleToken.expiry_date)
          .subtract(1, 'minute')
          .isAfter(moment())
      ) {
        return new Promise(res => {
          res(jwtClient);
        });
      }
    }
  }

  return new Promise((res, rej) => {
    const innerJWTClient = new google.auth.JWT(
      key.client_email,
      null,
      key.private_key,
      [
        'https://www.googleapis.com/auth/contacts',
        'https://www.googleapis.com/auth/calendar',
      ], // an array of auth scopes
      subject,
    );
    innerJWTClient.authorize((err, token) => {
      if (err) {
        rej(err);
      } else {
        moduleToken = token;
        jwtClient = innerJWTClient;
        console.error(moduleToken);
        res(innerJWTClient);
      }
    });
  });
}

async function generateCalendarObj() {
  try {
    jwtClient = await generateJWT(WORK_EMAIL);
  } catch (err) {
    console.error('generateCalendarObj', err, WORK_EMAIL);
  }

  return google.calendar({
    version: 'v3',
    auth: jwtClient,
    timeout: 5000, // 5 seconds.
    ontimeout() {
      // Handle timeout.
      console.error(
        'gapi.client create waiting could not load in a timely manner!',
      );
    },
  });
}

async function generatePeopleObj() {
  try {
    jwtClient = await generateJWT(WORK_EMAIL);
  } catch (err) {
    console.error('generateCalendarObj', err, WORK_EMAIL);
  }
  return google.people({
    version: 'v1',
    auth: jwtClient,
    timeout: 5000, // 5 seconds.
    ontimeout() {
      // Handle timeout.
      console.error(
        'gapi.client create waiting could not load in a timely manner!',
      );
    },
  });
}

module.exports = {
  generateJWT,
  generateCalendarObj,
  generatePeopleObj,
};
<commit_msg>comments for cache<commit_after>const moment = require('moment');
const getConfig = require('./configs').get;
const key = require('../keys/google.json');
const google = require('googleapis');

const WORK_EMAIL = getConfig('work_email');

/* specifically for cache */
let moduleToken = null;
let jwtClient = null;

function generateJWT(subject = null) {
  if (moduleToken) {
    // console.error('moduleToken', moduleToken);
    if (moduleToken.expiry_date) {
      // console.error('moduleToken.expiry_date', moduleToken.expiry_date);
      if (
        moment(moduleToken.expiry_date)
          .subtract(1, 'minute')
          .isAfter(moment())
      ) {
        return new Promise(res => {
          res(jwtClient);
        });
      }
    }
  }

  return new Promise((res, rej) => {
    const innerJWTClient = new google.auth.JWT(
      key.client_email,
      null,
      key.private_key,
      [
        'https://www.googleapis.com/auth/contacts',
        'https://www.googleapis.com/auth/calendar',
      ], // an array of auth scopes
      subject,
    );
    innerJWTClient.authorize((err, token) => {
      if (err) {
        rej(err);
      } else {
        moduleToken = token;
        jwtClient = innerJWTClient;
        console.error(moduleToken);
        res(innerJWTClient);
      }
    });
  });
}

async function generateCalendarObj() {
  try {
    jwtClient = await generateJWT(WORK_EMAIL);
  } catch (err) {
    console.error('generateCalendarObj', err, WORK_EMAIL);
  }

  return google.calendar({
    version: 'v3',
    auth: jwtClient,
    timeout: 5000, // 5 seconds.
    ontimeout() {
      // Handle timeout.
      console.error(
        'gapi.client create waiting could not load in a timely manner!',
      );
    },
  });
}

async function generatePeopleObj() {
  try {
    jwtClient = await generateJWT(WORK_EMAIL);
  } catch (err) {
    console.error('generateCalendarObj', err, WORK_EMAIL);
  }
  return google.people({
    version: 'v1',
    auth: jwtClient,
    timeout: 5000, // 5 seconds.
    ontimeout() {
      // Handle timeout.
      console.error(
        'gapi.client create waiting could not load in a timely manner!',
      );
    },
  });
}

module.exports = {
  generateJWT,
  generateCalendarObj,
  generatePeopleObj,
};
<|endoftext|>


<commit_before>/**
 * Created by amo on 14/11/2015.
 */
class CatalogueDataObject{

    /**
     * Creates the Cataloogue Data Object
     * @param guid - Global Unique identifier of the Catalogue Object (e.g. Hyperty descriptor, ProtocolStub descriptor, etc) enabling the same object to be stored and discovered in different Catalogues. That means, guid corresponds to <resource-type-id> per BNF of Resource Path. Couldn't we have problems with too long URL paths?
     * @param type - indicates the type of Catalogue Data Object e.g. Hyperty, ProtocolStub, etc
     * @param objectName - human-understable name of the catalogue object e.g. "My Awesome Hyperty"
     * @param description - desciption of the source package
     * @param language - the programming language used in the SourcePackage.SourceCode
     * @param sourcePackageURL - A string containing the URL from where the source code package of the corresponding catalogue object, e.g. deployable packages containing executable code for Hyperties or ProtoStubs, can be downloaded
     */
    constructor(guid, type, objectName, description, language, sourcePackageURL){
        this.guid = guid;
        this.type = type;
        this.objectName = objectName;
        this.description = description;
        this.language = language;
        this.sourcePackageURL = sourcePackageURL;

        this.signature = null;
        this.sourcePackage = null;
    }

    // Getters
    get guid(){ return this.guid; }

    get type(){ return this.type; }

    get objectName(){return this.objectName; }

    get description(){ return this.descriptiom; }

    get language() {return this.language; }

    get signature() { return this.signature; }

    get sourcePackage(){ return this.sourcePackage; }

    get sourcePackageURL(){ return this.sourcePackageURL; }

    // Setters
    set guid(guid){
        if(guid)
            this.guid = guid;
    }

    set type(catalogueType){
        if(catalogueType)
            this.type = catalogueType;
    }

    set objectName(oName){
        if(oName)
            this.objectName = oName;
    }
    set description(desc){
        if(desc)
            this.description = desc;
    }
    set language(lang){
        if(lang)
            this.language = lang;
    }

    set signature(signature){
        if(signature)
            this.signature = signature;
    }

    set sourcePackage(srcPackage){
        if(srcPackage)
            this.sourcePackage = srcPackage;
    }

    set sourcePackageURL(srcPackageUrl){
        if(srcPackageUrl)
            this.sourcePackageURL = srcPackageUrl;
    }

}
export class SourcePackage{
    constructor(encoding, sourceCodeClassname, sourceCode, signature){
        "use strict";
        this.encoding = encoding;
        this.sourceCodeClassname = sourceCodeClassname;
        this.sourceCode = sourceCode;
        this.signature = signature;
    }

}

export var CatalogueObjectType = { HYPERTY: 'hyperty', PROTOSTUB: 'protostub', HYPERTY_RUNTIME: 'hyperty_runtime', HYPERTY_INSPECTOR: 'hyperty_inspector', HYPERTY_DATA_OBJECT: 'hyperty_data_object'};
export var DataObjectSourceLanguage = {JAVASCRIPT_ECMA6: 'javascript_ecma6', JAVASCRIPT_ECMA5: 'javascript_ecma5', JSON_SCHEMA_V4: 'json_schema_v4', PYTHON: 'python', TYPESCRIPT: 'typescript'};
export default CatalogueDataObject;<commit_msg>Fixed typos, code formatting<commit_after>/**
 * Created by amo on 14/11/2015.
 */
class CatalogueDataObject {
    /**
     * Creates the Catalogue Data Object
     * @param guid - Global Unique identifier of the Catalogue Object (e.g. Hyperty descriptor, ProtocolStub descriptor,
     * etc) enabling the same object to be stored and discovered in different Catalogues. That means, guid corresponds to
     * <resource-type-id> per BNF of Resource Path. Couldn't we have problems with too long URL paths?
     * @param type - indicates the type of Catalogue Data Object e.g. Hyperty, ProtocolStub, etc
     * @param objectName - human-understandable name of the catalogue object e.g. "My Awesome Hyperty"
     * @param description - description of the source package
     * @param language - the programming language used in the SourcePackage.SourceCode
     * @param sourcePackageURL - A string containing the URL from where the source code package of the corresponding
     * catalogue object, e.g. deployable packages containing executable code for Hyperties or ProtoStubs, can be downloaded
     */
    constructor(guid, type, objectName, description, language, sourcePackageURL) {
        this._guid = guid;
        this._type = type;
        this._objectName = objectName;
        this._description = description;
        this._language = language;
        this._sourcePackageURL = sourcePackageURL;

        this._signature = null;
        this._sourcePackage = null;
    }

    // Getters
    get guid() {
        return this._guid;
    }

    get type() {
        return this._type;
    }

    get objectName() {
        return this._objectName;
    }

    get description() {
        return this._description;
    }

    get language() {
        return this._language;
    }

    get signature() {
        return this._signature;
    }

    get sourcePackage() {
        return this._sourcePackage;
    }

    // Setters
    /**
     * Set the signature to enables integrity and authenticity verification
     * @param signature
     */
    set signature(signature) {
        if (signature)
            this._signature = signature;

    }

    set sourcePackage(srcPackage) {
        if (srcPackage)
            this._sourcePackage = srcPackage;

    }
}

export var CatalogueObjectType = {
    HYPERTY: 'hyperty', PROTOSTUB: 'protostub', HYPERTY_RUNTIME: 'hyperty_runtime',
    HYPERTY_INSPECTOR: 'hyperty_inspector', HYPERTY_DATA_OBJECT: 'hyperty_data_object'
};
export var DataObjectSourceLanguage = {
    JAVASCRIPT_ECMA6: 'javascript_ecma6', JAVASCRIPT_ECMA5: 'javascript_ecma5',
    JSON_SCHEMA_V4: 'json_schema_v4', PYTHON: 'python', TYPESCRIPT: 'typescript'
};
export default CatalogueDataObject;<|endoftext|>


<commit_before>'use strict';
/**
 * @file
 * Currently the main entrypoint served on /work.
 * Provides the work view for the enduser.
 */
import React from 'react';
import Reflux from 'reflux';

import {isEmpty, values} from 'lodash';

import workAction from '../../actions/Work.action.js';
import WorkStore from '../../stores/Work.store.js';
import {CoverImage, OrderButton} from 'dbc-react-components';
import {rewriteCoverImageUrl} from '../../../utils/CoverImage.util.js';
import LikeContainer from '../LikeDislike/LikeContainer.component.js';
import DislikeContainer from '../LikeDislike/DislikeContainer.component.js';
import ProfileStore from '../../stores/Profile.store.js';

const Work = React.createClass({
  displayName: 'Work.component',

  propTypes: {
    id: React.PropTypes.string,
    work: React.PropTypes.object
  },

  mixins: [
    Reflux.connect(WorkStore, 'work'),
    Reflux.connect(ProfileStore, 'profile')
  ],

  getInitialState() {
    if (typeof window === 'undefined') {
      this.getWork();
    }
  },

  componentDidMount() {
    this.getWork();
  },

  getWork() {
    if (this.props.work) {
      workAction.updated([this.props.work]);
    }
    workAction({id: this.props.id});
  },

  getLikeDislikeContainers(id) {
    return (

          <LikeContainer objectId={id} />

          <DislikeContainer objectId={id} />

    );
  },

  render() {
    const profile = this.state.profile;
    const work = this.props.work ? this.props.work : this.state.work;
    const id = this.props.id;

    // No result found!
    if (work.info.hits === '0') {
      return (
Værket blev ikke fundet
);
    }

    // Result is pending, waiting for serviceprovider
    if (isEmpty(work.result) && isEmpty(work.info)) {
      return (

      );
    }

    // Empty result (Should perhaps be an error report)
    if (isEmpty(work.result)) {
      return (
);
    }

    // Data was found, begin rendering
    const likeContainers = this.state.profile.userIsLoggedIn ? this.getLikeDislikeContainers(id) : ' ';
    let editions = [];
    let specifics_object = {};

    work.result.editions.forEach((element, index) => {
      let edition = (

{element.type}

{element.edition + (element.edition !== '' ? ', ' : '')} {element.date}

{element.extent}

            {element.isbns.length > 0 ? 'ISBN: ' : ''}
            {element.isbns.join(', ')}

            {element.link.map((link, idx) => {
              return (
                Find online);
            })}

      );

      editions.push(edition);

      const elementKey = element.accessType + '_' + element.type;

      if (!specifics_object.hasOwnProperty(elementKey)) {
        specifics_object[elementKey] = {
          accessType: element.accessType,
          creator: element.creator,
          dates: [],
          identifiers: [],
          links: [],
          order: '',
          title: element.title,
          type: element.type,
          workType: element.workType
        };
      }

      element.link.forEach((link) => {
        specifics_object[elementKey].links.push(link);
      });
      specifics_object[elementKey].dates.push(element.date);
      specifics_object[elementKey].identifiers.push(element.identifier);
      specifics_object[elementKey].order = '/order?ids=' + specifics_object[elementKey].identifiers.join(',') +
        '&creator=' + specifics_object[elementKey].creator +
        '&title=' + encodeURIComponent(specifics_object[elementKey].title) +
        '&type=' + specifics_object[elementKey].type;
    });

    let specifics = values(specifics_object);

    return (

          <CoverImage noCoverUrl='/covers/no-cover-image-book.png' pids={[id, work.result.pid]} prefSize='detail_500' rewritwImgUrl={rewriteCoverImageUrl} />

          <OrderButton manifestations={specifics} profile={profile} relations={work.result.relations} />

          {likeContainers}

{work.result.title}

                {work.result.creator}

{work.result.abstract}

              {work.result.isbns.length > 0 ? 'ISBN: ' + work.result.isbns[0] : ''}

{work.result.extent}

                {work.result.actors.length > 0 ? 'Medvirkende: ' : ''}
                {work.result.actors.map((actor, index) => {
                  return (

                        {actor}

                    );
                })}

              {work.result.series}

              {work.result.subjects.length > 0 ? 'Emner: ' : ''}
              {work.result.subjects.map((subject, index, array) => {
                const notLast = (array.length - 1) !== index;
                return (

                     {notLast ? subject + ', ' : subject}

                );
              })}

              {work.result.dk5s.length > 0 ? 'Opstilling: ' : ''}
              {work.result.dk5s.map((dk5, index) => {
                return (

                    {dk5.text}

                );
              })}

{work.result.audience.age.join(', ')}

{work.result.audience.pegi}

{work.result.audience.medieraad}

              {work.result.tracks.length > 0 ? 'Trackliste: ' : ''}
              {work.result.tracks.map((track, index) => {
                return (

{track}
);
              })}

              {work.result.languages.length > 0 ? 'Sprog: ' : ''}
              {work.result.languages.join(', ')}

            {specifics.map((specific, index) => {
              return (
                {specific.type} ({specific.dates.join('; ')})
              );
            })}

            {editions.length > 0 ? 'Udgaver:' : ''}
            {editions}

    );
  }
});

export default Work;
<commit_msg>Accumulated commit of the following from branch 'origin/ready/remove_links':<commit_after>'use strict';
/**
 * @file
 * Currently the main entrypoint served on /work.
 * Provides the work view for the enduser.
 */
import React from 'react';
import Reflux from 'reflux';

import {isEmpty, values} from 'lodash';

import workAction from '../../actions/Work.action.js';
import WorkStore from '../../stores/Work.store.js';
import {CoverImage, OrderButton} from 'dbc-react-components';
import {rewriteCoverImageUrl} from '../../../utils/CoverImage.util.js';
import LikeContainer from '../LikeDislike/LikeContainer.component.js';
import DislikeContainer from '../LikeDislike/DislikeContainer.component.js';
import ProfileStore from '../../stores/Profile.store.js';

const Work = React.createClass({
  displayName: 'Work.component',

  propTypes: {
    id: React.PropTypes.string,
    work: React.PropTypes.object
  },

  mixins: [
    Reflux.connect(WorkStore, 'work'),
    Reflux.connect(ProfileStore, 'profile')
  ],

  getInitialState() {
    if (typeof window === 'undefined') {
      this.getWork();
    }
  },

  componentDidMount() {
    this.getWork();
  },

  getWork() {
    if (this.props.work) {
      workAction.updated([this.props.work]);
    }
    workAction({id: this.props.id});
  },

  getLikeDislikeContainers(id) {
    return (

          <LikeContainer objectId={id} />

          <DislikeContainer objectId={id} />

    );
  },

  render() {
    const profile = this.state.profile;
    const work = this.props.work ? this.props.work : this.state.work;
    const id = this.props.id;

    // No result found!
    if (work.info.hits === '0') {
      return (
Værket blev ikke fundet
);
    }

    // Result is pending, waiting for serviceprovider
    if (isEmpty(work.result) && isEmpty(work.info)) {
      return (

      );
    }

    // Empty result (Should perhaps be an error report)
    if (isEmpty(work.result)) {
      return (
);
    }

    // Data was found, begin rendering
    const likeContainers = this.state.profile.userIsLoggedIn ? this.getLikeDislikeContainers(id) : ' ';
    let editions = [];
    let specifics_object = {};

    work.result.editions.forEach((element, index) => {
      let edition = (

{element.type}

{element.edition + (element.edition !== '' ? ', ' : '')} {element.date}

{element.extent}

            {element.isbns.length > 0 ? 'ISBN: ' : ''}
            {element.isbns.join(', ')}

      );

      editions.push(edition);

      const elementKey = element.accessType + '_' + element.type;

      if (!specifics_object.hasOwnProperty(elementKey)) {
        specifics_object[elementKey] = {
          accessType: element.accessType,
          creator: element.creator,
          dates: [],
          identifiers: [],
          order: '',
          title: element.title,
          type: element.type,
          workType: element.workType
        };
      }

      specifics_object[elementKey].dates.push(element.date);
      specifics_object[elementKey].identifiers.push(element.identifier);
      specifics_object[elementKey].order = '/order?ids=' + specifics_object[elementKey].identifiers.join(',') +
        '&creator=' + specifics_object[elementKey].creator +
        '&title=' + encodeURIComponent(specifics_object[elementKey].title) +
        '&type=' + specifics_object[elementKey].type;
    });

    let specifics = values(specifics_object);

    return (

          <CoverImage noCoverUrl='/covers/no-cover-image-book.png' pids={[id, work.result.pid]} prefSize='detail_500' rewritwImgUrl={rewriteCoverImageUrl} />

          <OrderButton manifestations={specifics} profile={profile} relations={work.result.relations} />

          {likeContainers}

{work.result.title}

                {work.result.creator}

{work.result.abstract}

              {work.result.isbns.length > 0 ? 'ISBN: ' + work.result.isbns[0] : ''}

{work.result.extent}

                {work.result.actors.length > 0 ? 'Medvirkende: ' : ''}
                {work.result.actors.map((actor, index) => {
                  return (

                        {actor}

                    );
                })}

              {work.result.series}

              {work.result.subjects.length > 0 ? 'Emner: ' : ''}
              {work.result.subjects.map((subject, index, array) => {
                const notLast = (array.length - 1) !== index;
                return (

                     {notLast ? subject + ', ' : subject}

                );
              })}

              {work.result.dk5s.length > 0 ? 'Opstilling: ' : ''}
              {work.result.dk5s.map((dk5, index) => {
                return (

                    {dk5.text}

                );
              })}

{work.result.audience.age.join(', ')}

{work.result.audience.pegi}

{work.result.audience.medieraad}

              {work.result.tracks.length > 0 ? 'Trackliste: ' : ''}
              {work.result.tracks.map((track, index) => {
                return (

{track}
);
              })}

              {work.result.languages.length > 0 ? 'Sprog: ' : ''}
              {work.result.languages.join(', ')}

            {specifics.map((specific, index) => {
              return (
                {specific.type} ({specific.dates.join('; ')})
              );
            })}

            {editions.length > 0 ? 'Udgaver:' : ''}
            {editions}

    );
  }
});

export default Work;
<|endoftext|>


<commit_before>'use strict';
/**
 * @file
 * Currently the main entrypoint served on /work.
 * Provides the work view for the enduser.
 */
import React from 'react';
import Reflux from 'reflux';

import {isEmpty, values} from 'lodash';

import workAction from '../../actions/Work.action.js';
import WorkStore from '../../stores/Work.store.js';
import {CoverImage, OrderButton} from 'dbc-react-components';
import {rewriteCoverImageUrl} from '../../../utils/CoverImage.util.js';
import LikeContainer from '../LikeDislike/LikeContainer.component.js';
import DislikeContainer from '../LikeDislike/DislikeContainer.component.js';
import ProfileStore from '../../stores/Profile.store.js';

const Work = React.createClass({
  displayName: 'Work.component',

  propTypes: {
    id: React.PropTypes.string,
    work: React.PropTypes.object
  },

  mixins: [
    Reflux.connect(WorkStore, 'work'),
    Reflux.connect(ProfileStore, 'profile')
  ],

  getInitialState() {
    if (typeof window === 'undefined') {
      this.getWork();
    }
  },

  componentDidMount() {
    this.getWork();
  },

  getWork() {
    if (this.props.work) {
      workAction.updated([this.props.work]);
    }
    workAction({id: this.props.id});
  },

  getLikeDislikeContainers(id) {
    return (

          <LikeContainer objectId={id} />

          <DislikeContainer objectId={id} />

    );
  },

  render() {
    const profile = this.state.profile;
    const work = this.props.work ? this.props.work : this.state.work;
    const id = this.props.id;

    // No result found!
    if (work.info.hits === '0') {
      return (
Værket blev ikke fundet
);
    }

    // Result is pending, waiting for serviceprovider
    if (isEmpty(work.result) && isEmpty(work.info)) {
      return (

      );
    }

    // Empty result (Should perhaps be an error report)
    if (isEmpty(work.result)) {
      return (
);
    }

    // Data was found, begin rendering
    const likeContainers = this.state.profile.userIsLoggedIn ? this.getLikeDislikeContainers(id) : ' ';
    let editions = [];
    let specifics_object = {};

    work.result.editions.forEach((element, index) => {
      let edition = (

{element.type}

{element.edition + (element.edition !== '' ? ', ' : '')} {element.date}

{element.extent}

            {element.isbns.length > 0 ? 'ISBN: ' : ''}
            {element.isbns.join(', ')}

            {element.link.map((link, idx) => {
              return (Find online);
            })}

      );

      editions.push(edition);

      const elementKey = element.accessType + '_' + element.type;

      if (!specifics_object.hasOwnProperty(elementKey)) {
        specifics_object[elementKey] = {
          accessType: element.accessType,
          creator: element.creator,
          dates: [],
          identifiers: [],
          links: [],
          order: '',
          title: element.title,
          type: element.type
        };
      }

      element.link.forEach((link) => {
        specifics_object[elementKey].links.push(link);
      });
      specifics_object[elementKey].dates.push(element.date);
      specifics_object[elementKey].identifiers.push(element.identifier);
      specifics_object[elementKey].order = '/order?ids=' + specifics_object[elementKey].identifiers.join(',') +
        '&creator=' + specifics_object[elementKey].creator +
        '&title=' + encodeURIComponent(specifics_object[elementKey].title) +
        '&type=' + specifics_object[elementKey].type;
    });

    let specifics = values(specifics_object);

    return (

          <CoverImage pids={[id, work.result.pid]} prefSize='detail_500' rewritwImgUrl={rewriteCoverImageUrl} />

          <OrderButton manifestations={specifics} profile={profile} relations={work.result.relations} />

          {likeContainers}

{work.result.title}

                {work.result.creator}

{work.result.abstract}

              {work.result.isbns.length > 0 ? 'ISBN: '+ work.result.isbns[0] : ''}

{work.result.extent}

                {work.result.actors.length > 0 ? 'Medvirkende: ' : ''}
                {work.result.actors.map((actor, index) => {
                  return (

                        {actor}

                    );
                })}

              {work.result.series}

              {work.result.subjects.length > 0 ? 'Emner: ' : ''}
              {work.result.subjects.map((subject, index, array) => {
                const notLast = (array.length - 1) !== index;
                return (

                     {notLast ? subject + ', ' : subject}

                );
              })}

              {work.result.dk5s.length > 0 ? 'Opstilling: ' : ''}
              {work.result.dk5s.map((dk5, index) => {
                return (

                    {dk5.text}

                );
              })}

{work.result.audience.age.join(', ')}

{work.result.audience.pegi}

{work.result.audience.medieraad}

              {work.result.tracks.length > 0 ? 'Trackliste: ' : ''}
              {work.result.tracks.map((track, index) => {
                return (
{track}
);
              })}

              {work.result.languages.length > 0 ? 'Sprog: ' : ''}
              {work.result.languages.join(', ')}

            {specifics.map((specific, index) => {
              return (
                {specific.type} ({specific.dates.join('; ')})
              );
            })}

            {editions.length > 0 ? 'Udgaver:' : ''}
            {editions}

    );
  }
});

export default Work;
<commit_msg>adding workType to order button props<commit_after>'use strict';
/**
 * @file
 * Currently the main entrypoint served on /work.
 * Provides the work view for the enduser.
 */
import React from 'react';
import Reflux from 'reflux';

import {isEmpty, values} from 'lodash';

import workAction from '../../actions/Work.action.js';
import WorkStore from '../../stores/Work.store.js';
import {CoverImage, OrderButton} from 'dbc-react-components';
import {rewriteCoverImageUrl} from '../../../utils/CoverImage.util.js';
import LikeContainer from '../LikeDislike/LikeContainer.component.js';
import DislikeContainer from '../LikeDislike/DislikeContainer.component.js';
import ProfileStore from '../../stores/Profile.store.js';

const Work = React.createClass({
  displayName: 'Work.component',

  propTypes: {
    id: React.PropTypes.string,
    work: React.PropTypes.object
  },

  mixins: [
    Reflux.connect(WorkStore, 'work'),
    Reflux.connect(ProfileStore, 'profile')
  ],

  getInitialState() {
    if (typeof window === 'undefined') {
      this.getWork();
    }
  },

  componentDidMount() {
    this.getWork();
  },

  getWork() {
    if (this.props.work) {
      workAction.updated([this.props.work]);
    }
    workAction({id: this.props.id});
  },

  getLikeDislikeContainers(id) {
    return (

          <LikeContainer objectId={id} />

          <DislikeContainer objectId={id} />

    );
  },

  render() {
    const profile = this.state.profile;
    const work = this.props.work ? this.props.work : this.state.work;
    const id = this.props.id;

    // No result found!
    if (work.info.hits === '0') {
      return (
Værket blev ikke fundet
);
    }

    // Result is pending, waiting for serviceprovider
    if (isEmpty(work.result) && isEmpty(work.info)) {
      return (

      );
    }

    // Empty result (Should perhaps be an error report)
    if (isEmpty(work.result)) {
      return (
);
    }

    // Data was found, begin rendering
    const likeContainers = this.state.profile.userIsLoggedIn ? this.getLikeDislikeContainers(id) : ' ';
    let editions = [];
    let specifics_object = {};

    work.result.editions.forEach((element, index) => {
      let edition = (

{element.type}

{element.edition + (element.edition !== '' ? ', ' : '')} {element.date}

{element.extent}

            {element.isbns.length > 0 ? 'ISBN: ' : ''}
            {element.isbns.join(', ')}

            {element.link.map((link, idx) => {
              return (Find online);
            })}

      );

      editions.push(edition);

      const elementKey = element.accessType + '_' + element.type;

      if (!specifics_object.hasOwnProperty(elementKey)) {
        specifics_object[elementKey] = {
          accessType: element.accessType,
          creator: element.creator,
          dates: [],
          identifiers: [],
          links: [],
          order: '',
          title: element.title,
          type: element.type,
          workType: element.workType
        };
      }

      element.link.forEach((link) => {
        specifics_object[elementKey].links.push(link);
      });
      specifics_object[elementKey].dates.push(element.date);
      specifics_object[elementKey].identifiers.push(element.identifier);
      specifics_object[elementKey].order = '/order?ids=' + specifics_object[elementKey].identifiers.join(',') +
        '&creator=' + specifics_object[elementKey].creator +
        '&title=' + encodeURIComponent(specifics_object[elementKey].title) +
        '&type=' + specifics_object[elementKey].type;
    });

    let specifics = values(specifics_object);

    return (

          <CoverImage pids={[id, work.result.pid]} prefSize='detail_500' rewritwImgUrl={rewriteCoverImageUrl} />

          <OrderButton manifestations={specifics} profile={profile} relations={work.result.relations} />

          {likeContainers}

{work.result.title}

                {work.result.creator}

{work.result.abstract}

              {work.result.isbns.length > 0 ? 'ISBN: '+ work.result.isbns[0] : ''}

{work.result.extent}

                {work.result.actors.length > 0 ? 'Medvirkende: ' : ''}
                {work.result.actors.map((actor, index) => {
                  return (

                        {actor}

                    );
                })}

              {work.result.series}

              {work.result.subjects.length > 0 ? 'Emner: ' : ''}
              {work.result.subjects.map((subject, index, array) => {
                const notLast = (array.length - 1) !== index;
                return (

                     {notLast ? subject + ', ' : subject}

                );
              })}

              {work.result.dk5s.length > 0 ? 'Opstilling: ' : ''}
              {work.result.dk5s.map((dk5, index) => {
                return (

                    {dk5.text}

                );
              })}

{work.result.audience.age.join(', ')}

{work.result.audience.pegi}

{work.result.audience.medieraad}

              {work.result.tracks.length > 0 ? 'Trackliste: ' : ''}
              {work.result.tracks.map((track, index) => {
                return (
{track}
);
              })}

              {work.result.languages.length > 0 ? 'Sprog: ' : ''}
              {work.result.languages.join(', ')}

            {specifics.map((specific, index) => {
              return (
                {specific.type} ({specific.dates.join('; ')})
              );
            })}

            {editions.length > 0 ? 'Udgaver:' : ''}
            {editions}

    );
  }
});

export default Work;
<|endoftext|>


<commit_before>var conditionalHTML = require('./conditional-input-card.html');
var InputCard = require('./card-input.js');

/**
 * This Card extends the functionality of InputCard. It gives the ability of disabling the InputCard.
 * This is useful in situations where you don't want the Card to be required.
 *
 * @param {jquery} appendTo The div to append this Card to.
 * @param {Object} options The object that describes the Card functionality. See the parent object InputCard for details.
 * @param {boolean} enabled The default state of the checkbox.
 */
var ConditionalInputCard = function(appendTo, options) {
  InputCard.call(this, appendTo, options);

  // Private variables
  var self = this;
  var innerBase = $(conditionalHTML);
  var checkbox = innerBase.find('[data-id="checkbox"]');
  var cbLabel = innerBase.find('[data-id="checkbox-label"]');

  //***** Private Methods *****//

  this.init_ = function(appendTo, options) {
    this.append(innerBase);

    checkbox.on('change', setCardState);

    componentHandler.upgradeAllRegistered();

    if (options.enabled !== undefined) {
      if (options.enabled) {
        checkbox.attr('checked');
      }
    }
    if (options.checkboxText !== undefined) {
      cbLabel.text(options.checkboxText);
    }
  };

  var setCardState = function(e) {
    // NOTE MDL doesn't change the class until after this event is fired. That revereses our logic here.
    if (!self.isEnabled()) {
      enableCard();
    }
    else {
      disableCard();
    }
  };

  var disableCard = function() {
    self.disableInput();
  };

  var enableCard = function() {
    self.enableInput();
  };

  var oldGetValue = this.getValue;

  //***** Public Functions *****//

  /**
   * Checks whether this Card is enabled.
   *
   * @returns {boolean} True if the Card is enabled. False if it isn't.
   */
  this.isEnabled = function() {
    return innerBase.hasClass('is-checked');
  };

  this.check = function() {
    innerBase[0].MaterialCheckbox.check();
  };

  this.uncheck = function() {
    innerBase[0].MaterialCheckbox.uncheck();
  };

  this.getValue = function() {
    if (self.isEnabled()) {
      return oldGetValue();
    }
    return;
  }

  this.init_(appendTo, options);
};

/** */
ConditionalInputCard.prototype.constructor = ConditionalInputCard;
ConditionalInputCard.prototype = Object.create(ConditionalInputCard.prototype);

/** */
module.exports = ConditionalInputCard;
<commit_msg>Fixed an issue with toggling states for ConditionalInputs.<commit_after>var conditionalHTML = require('./conditional-input-card.html');
var InputCard = require('./card-input.js');

/**
 * This Card extends the functionality of InputCard. It gives the ability of disabling the InputCard.
 * This is useful in situations where you don't want the Card to be required.
 *
 * @param {jquery} appendTo The div to append this Card to.
 * @param {Object} options The object that describes the Card functionality. See the parent object InputCard for details.
 * @param {boolean} enabled The default state of the checkbox.
 */
var ConditionalInputCard = function(appendTo, options) {
  InputCard.call(this, appendTo, options);

  // Private variables
  var self = this;
  var innerBase = $(conditionalHTML);
  var checkbox = innerBase.find('[data-id="checkbox"]');
  var cbLabel = innerBase.find('[data-id="checkbox-label"]');

  //***** Private Methods *****//

  this.init_ = function(appendTo, options) {
    this.append(innerBase);

    checkbox.on('change', setCardState);

    componentHandler.upgradeAllRegistered();

    if (options.enabled !== undefined) {
      if (options.enabled) {
        checkbox.attr('checked');
      }
    }
    if (options.checkboxText !== undefined) {
      cbLabel.text(options.checkboxText);
    }
  };

  var setCardState = function(e) {
    // NOTE MDL doesn't change the class until after this event is fired. That revereses our logic here.
    if (!self.isEnabled()) {
      enableCard();
    }
    else {
      disableCard();
    }
  };

  var disableCard = function() {
    self.disableInput();
  };

  var enableCard = function() {
    self.enableInput();
  };

  var oldGetValue = this.getValue;

  //***** Public Functions *****//

  /**
   * Checks whether this Card is enabled.
   *
   * @returns {boolean} True if the Card is enabled. False if it isn't.
   */
  this.isEnabled = function() {
    return innerBase.hasClass('is-checked');
  };

  this.check = function() {
    innerBase[0].MaterialCheckbox.check();
    enableCard();
  };

  this.uncheck = function() {
    innerBase[0].MaterialCheckbox.uncheck();
    disableCard();
  };

  this.getValue = function() {
    if (self.isEnabled()) {
      return oldGetValue();
    }
    return;
  }

  this.init_(appendTo, options);
};

/** */
ConditionalInputCard.prototype.constructor = ConditionalInputCard;
ConditionalInputCard.prototype = Object.create(ConditionalInputCard.prototype);

/** */
module.exports = ConditionalInputCard;
<|endoftext|>


<commit_before>/* global Drawer: false, ImageLoader: false, NProgress: false, Prism: false */
(function ($, window, document, undefined) {

  'use strict';

  $(function () {

    // Cache a couple of useful elements
    // =================
    var $window   = $(window),
        $document = $(document),
        $html     = $(document.documentElement),
        $body     = $(document.body),
        $surface  = $('.surface-container', $body);

    // Drawer bindings
    // =================
    Drawer.init();

    // PrismJS handler
    // =================
    Prism.languages.html = Prism.languages.markup;

    var _prismHandler = function() {
      $('code').not('[class*="language-"]').addClass(function() {
        var _lang = $(this).attr('class');
        return 'language-' + (_lang ? _lang : 'markup');
      });

      Prism.highlightAll();
    };

    _prismHandler();

    // PJax bindings
    // =================
    if ($.support.pjax) {
      $document.on('pjax:start', function() {
        NProgress.start();

        $surface.animate({
          scrollTop: 0
        }, 500);

        if(Drawer.isOpen())
          Drawer.close();
      });
      $document.on('pjax:end', function() {
        if(ga !== undefined) {
          ga('set', 'location', window.location.href);
          ga('send', 'pageview');
        }

        _prismHandler();
        NProgress.done();
      });

      var pjaxHandler = function(e) {
        $.pjax.click(e, {
          container: '[data-pjax-container]',
          fragment: '[data-pjax-container]',
          replace: true
        });
      };

      $document.on('click', 'a[data-pjax]', pjaxHandler);
      $document.on('submit', 'form[data-pjax]', pjaxHandler);
    }

    // Data API bindings
    // =================
    $document.on('click', '[data-action]', function(e) {
      var _self = $(this),
         action = _self.data('action');

      var _openWindow = function(url, h, w) {
        var dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : screen.left,
            dualScreenTop = window.screenTop !== undefined ? window.screenTop : screen.top,
            left = ((screen.width / 2) - (w / 2)) + dualScreenLeft,
            top = ((screen.height / 2) - (h / 2)) + dualScreenTop;

        var newWindow = window.open(url, '',
          'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,copyhistory=no' +
          ', width=' + w +
          ', height=' + h +
          ', top=' + top +
          ', left=' + left);

        // Puts focus on the newWindow
        if (window.focus) {
            newWindow.focus();
        }
        return newWindow;
      };

      e.preventDefault();

      switch(action) {
        case 'open-drawer':
          Drawer.open();
          break;
        case 'close-drawer':
          Drawer.close();
          break;
        case 'share-gplus':
          _openWindow(
            'https://plus.google.com/share?url=' + encodeURIComponent(location.href),
            600, 600);
          break;
        case 'share-facebook':
          _openWindow(
            'https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(location.href),
            436, 626);
          break;
        case 'share-twitter':
          _openWindow(
            'https://twitter.com/share?url=' + encodeURIComponent(location.href) + '&text=' + encodeURIComponent(document.title),
            440, 550);
          break;
      }

      return false;
    });

    // Async load images
    $('[data-load-image]', $body).each(function() {
      ImageLoader.load($(this));
    });

    // Hide drawer button on scroll for best readability
    // =================
    $surface.on('scroll', function() {
      var offset = $surface.scrollTop(),
          btn = $('#drawer-button');
      if(offset === 0) {
        btn.removeClass('drawer-button-hidden');
      } else if(!btn.hasClass('drawer-button-hidden')) {
        btn.addClass('drawer-button-hidden');
      }
    });

    // Smooth scrolling for same page anchors
    // =================
    $document.on('click', 'a[href*=#]:not([href=#])', function(e) {
      e.preventDefault();

      if (location.pathname.replace(/^\//,'') === this.pathname.replace(/^\//,'') && location.hostname === this.hostname) {
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
        if (target.length) {
          $surface.animate({
            scrollTop: target.offset().top
          }, 500);
          location.hash = this.hash;
          return false;
        }
      }
    });

  });

})(jQuery, window, document);
<commit_msg>fix(pjax): Fix back/foward #1<commit_after>/* global Drawer: false, ImageLoader: false, NProgress: false, Prism: false */
(function ($, window, document, undefined) {

  'use strict';

  $(function () {

    // Cache a couple of useful elements
    // =================
    var $window   = $(window),
        $document = $(document),
        $html     = $(document.documentElement),
        $body     = $(document.body),
        $surface  = $('.surface-container', $body);

    // Drawer bindings
    // =================
    Drawer.init();

    // PrismJS handler
    // =================
    Prism.languages.html = Prism.languages.markup;

    var _prismHandler = function() {
      $('code').not('[class*="language-"]').addClass(function() {
        var _lang = $(this).attr('class');
        return 'language-' + (_lang ? _lang : 'markup');
      });

      Prism.highlightAll();
    };

    _prismHandler();

    // PJax bindings
    // =================
    if ($.support.pjax) {
      $document.on('pjax:start', function() {
        NProgress.start();

        $surface.animate({
          scrollTop: 0
        }, 500);

        if(Drawer.isOpen())
          Drawer.close();
      });

      $document.on('pjax:end', function() {
        if(ga !== undefined) {
          ga('set', 'location', window.location.href);
          ga('send', 'pageview');
        }

        _prismHandler();
        NProgress.done();
      });

      $document.pjax('a[data-pjax]', '[data-pjax-container]');

      $document.on('submit', 'form[data-pjax]', function(e) {
        $.pjax.submit(e, '[data-pjax-container]')
      })
    }

    // Data API bindings
    // =================
    $document.on('click', '[data-action]', function(e) {
      var _self = $(this),
         action = _self.data('action');

      var _openWindow = function(url, h, w) {
        var dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : screen.left,
            dualScreenTop = window.screenTop !== undefined ? window.screenTop : screen.top,
            left = ((screen.width / 2) - (w / 2)) + dualScreenLeft,
            top = ((screen.height / 2) - (h / 2)) + dualScreenTop;

        var newWindow = window.open(url, '',
          'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,copyhistory=no' +
          ', width=' + w +
          ', height=' + h +
          ', top=' + top +
          ', left=' + left);

        // Puts focus on the newWindow
        if (window.focus) {
            newWindow.focus();
        }
        return newWindow;
      };

      e.preventDefault();

      switch(action) {
        case 'open-drawer':
          Drawer.open();
          break;
        case 'close-drawer':
          Drawer.close();
          break;
        case 'share-gplus':
          _openWindow(
            'https://plus.google.com/share?url=' + encodeURIComponent(location.href),
            600, 600);
          break;
        case 'share-facebook':
          _openWindow(
            'https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(location.href),
            436, 626);
          break;
        case 'share-twitter':
          _openWindow(
            'https://twitter.com/share?url=' + encodeURIComponent(location.href) + '&text=' + encodeURIComponent(document.title),
            440, 550);
          break;
      }

      return false;
    });

    // Async load images
    $('[data-load-image]', $body).each(function() {
      ImageLoader.load($(this));
    });

    // Hide drawer button on scroll for best readability
    // =================
    $surface.on('scroll', function() {
      var offset = $surface.scrollTop(),
          btn = $('#drawer-button');
      if(offset === 0) {
        btn.removeClass('drawer-button-hidden');
      } else if(!btn.hasClass('drawer-button-hidden')) {
        btn.addClass('drawer-button-hidden');
      }
    });

    // Smooth scrolling for same page anchors
    // =================
    $document.on('click', 'a[href*=#]:not([href=#])', function(e) {
      e.preventDefault();

      if (location.pathname.replace(/^\//,'') === this.pathname.replace(/^\//,'') && location.hostname === this.hostname) {
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
        if (target.length) {
          $surface.animate({
            scrollTop: target.offset().top
          }, 500);
          location.hash = this.hash;
          return false;
        }
      }
    });

  });

})(jQuery, window, document);
<|endoftext|>