<commit_before>'use strict';

(function () {

  var app = angular.module('antismash.db.ui.query', [
    'ngResource',
    'antismash.db.ui.queryterm'
  ]);

  app.factory('Downloader', ['$resource', '$q', function ($resource, $q) {

    function handleError(data, status) {
      var decodedString = String.fromCharCode.apply(null, new Uint8Array(data));
      var error = JSON.parse(decodedString);
      return {
        response: error,
        status: status
      }
    }

    var MIME_MAP = {
      csv: 'text/csv',
      fasta: 'application/fasta',
      json: 'application/json'
    }

    function generate_handler(type) {
      var options = {
        method: 'POST',
        headers: {
          accept: MIME_MAP[type]
        },
        responseType: 'arraybuffer',
        cache: true,
        transformResponse: function (data, getter, status) {
          var response;

          if (status != 200) {
            return handleError(data, status);
          }

          if (data) {
            response = new Blob([data], {
              type: MIME_MAP[type]
            });
          }
          return {
            response: response
          };
        }
      };
      return options;
    }

    return $resource('/api/v1.0/export', null, {
      csv: generate_handler('csv'),
      fasta: generate_handler('fasta'),
      fastaa: generate_handler('fasta'),
      json: generate_handler('json')
    });
  }]);

  app.controller('QueryController', ['$http', '$window', '$stateParams', 'Downloader', 'bowser',
    function ($http, $window, $stateParams, Downloader, bowser) {

      var vm = this;

      vm.bowser = bowser;
      vm.search_string = '';
      vm.isValidSearch = isValidSearch;
      vm.search = search;
      vm.simpleSearch = simpleSearch;
      vm.showCluster = showCluster;
      vm.canLoadMore = canLoadMore;
      vm.loadMore = loadMore;
      vm.getNcbiUrl = getNcbiUrl;
      vm.getMibigUrl = getMibigUrl;
      vm.addEntry = addEntry;
      vm.removeEntry = removeEntry;
      vm.loadSimpleExample = loadSimpleExample;
      vm.loadComplexExample = loadComplexExample;
      vm.resetSearch = resetSearch;
      vm.downloadCsv = downloadCsv;
      vm.exportFile = exportFile;
      vm.getExportUrl = getExportUrl;
      vm.showSearch = showSearch;
      vm.graphicalPossible = graphicalPossible;
      vm.search_pending = false;
      vm.download_pending = false;
      vm.search_done = false;
      vm.download_done = false;
      vm.loading_more = false;
      vm.ran_simple_search = false;

      vm.hide_stats = true;
      vm.clusters_by_type_options = {
        title: {display: true, text: 'Clusters by types'},
        scales: {
          xAxes: [{ ticks: { autoSkip: false} }],
          yAxes: [{ ticks: {min: 0} }]
        }
      };
      vm.clusters_by_phylum_options = {
        title: {display: true, text: 'Clusters by phylum'},
        scales: {
          xAxes: [{ ticks: { autoSkip: false} }],
          yAxes: [{ ticks: {min: 0} }]
        }
      };

      vm.query = {
        search: 'cluster',
        return_type: 'json',
        terms: {
          term_type: 'expr',
          category: '',
          term: ''
        }
      };

      vm.results = {};

      if ($stateParams.search_string) {
        vm.search_string = $stateParams.search_string;
        simpleSearch();
      }

      function isValidSearch() {
        if (!vm.query) {
          return false;
        }
        if (!vm.query.terms) {
          return false;
        }
        return isValidTerm(vm.query.terms);
      }

      /* Recursively check if a term is valid
         Terms are considered valid if their category and term are not an
         empty string
       */
      function isValidTerm(term) {
        if (term.term_type == 'expr') {
          if (term.category == '') {
            return false;
          }
          if (term.term == '') {
            return false;
          }
          return true;
        }
        if (term.term_type == 'op') {
          return isValidTerm(term.left) && isValidTerm(term.right);
        }
        return false;
      }

      function search() {
        if (!isValidSearch()){
          return;
        }
        vm.search_pending = true;
        $http.post('/api/v1.0/search', {query: vm.query}).then(
          function(results){
            vm.results = results.data;
            vm.search_pending = false;
            vm.search_done = true;
            vm.ran_simple_search = false;
          }
        );
      };

      function simpleSearch() {
        vm.search_pending = true;
        $http.post('/api/v1.0/search', {search_string: vm.search_string}).then(
          function(results){
            vm.results = results.data;
            vm.search_pending = false;
            vm.search_done = true;
            vm.ran_simple_search = true;
          }
        )
      };

      function canLoadMore() {
        if (vm.results && vm.results.clusters) {
          return vm.results.clusters.length < vm.results.total;
        }
        return false;
      }

      function loadMore() {
        var next_offset = vm.results.offset + vm.results.paginate;
        var search_obj = {
          search_string: vm.search_string,
          offset: next_offset
        };
        vm.loading_more = true;
        $http.post('/api/v1.0/search', search_obj).then(
          function(results){
            vm.loading_more = false;
            var new_clusters = results.data.clusters;
            for (var i = 0; i < new_clusters.length; i++) {
              vm.results.clusters.push(new_clusters[i]);
            }
            vm.results.offset = results.data.offset;
          }
        )
      }

      function showCluster(entry) {
        var cluster_acc = entry.acc + '_c' + entry.cluster_number;
        $window.open('/output/' + entry.acc + '/index.html#cluster-' + entry.cluster_number, '_blank');
      };

      function getNcbiUrl(accession) {
        if (!accession){
          return '';
        }
        return "https://www.ncbi.nlm.nih.gov/genome/?term=" + accession;
      }

      function getMibigUrl(accession) {
        if (!accession) {
          return '';
        }
        var acc = accession.split(/_/)[0];
        return "https://mibig.secondarymetabolites.org/repository/" + acc + "/index.html#cluster-1";
      };

      function addEntry(){
        vm.search_objects.push({category: {val: 'type', desc:'BGC type'}, term: '', operation: 'and'});
      };

      function removeEntry(entry){
        var idx = vm.search_objects.indexOf(entry);
        if (idx > -1) {
          vm.search_objects.splice(idx, 1);
        }
      };

      function loadSimpleExample(entry){
        vm.search_string = 'lantipeptide Streptomyces';
      };

      function loadComplexExample(entry) {
        vm.query = {
          search: 'cluster',
          return_type: 'json',
          terms: {
            term_type: 'op',
            operation: 'and',
            left: {
              term_type: 'expr',
              category: 'type',
              term: 'ripp'
            },
            right: {
              term_type: 'op',
              operation: 'or',
              left: {
                term_type: 'expr',
                category: 'genus',
                term: 'Streptomyces'
              },
              right: {
                term_type: 'expr',
                category: 'genus',
                term: 'Lactococcus'
              }
            }
          }
        };
      }

      function resetSearch(){
        vm.search_done = false;
        vm.search_pending = false;
        vm.download_done = false;
        vm.download_pending = false;
        vm.download_failed = false;
        vm.results = {};
      };

      function showSearch() {
        if (vm.query == {}){
          return true;
        };
        if (graphicalPossible()) {
          if (vm.query.return_type == 'json') {
            return true;
          }
        }
        return false;
      };

      function graphicalPossible() {
        if (vm.query.search == 'cluster') {
          return true;
        }
        return false;
      }

      function downloadCsv(){
        if (vm.query) {
          vm.query.return_type = 'csv';
        }
        exportFile();
      }

      function getExportUrl() {
        var search_string;
        var search_type = 'cluster';
        var return_type = 'csv';
        if (vm.ran_simple_search) {
          search_string = encodeURIComponent(vm.search_string);
        } else {
          search_type = vm.query.search;
          return_type = vm.query.return_type;
          search_string = encodeURIComponent(queryToString(vm.query.terms));
        }
        var search =  '/api/v1.0/export/' + search_type + '/' + return_type + '?search=' + search_string;
        return search;
      };

      function queryToString(term){
        if (term.term_type == 'expr') {
          return '[' + term.category + ']' + term.term;
        }
        if (term.term_type == 'op') {
          return '( ' + queryToString(term.left) + ' '
                      + term.operation.toUpperCase() + ' '
                      + queryToString(term.right) + ' )';
        }
      }

      function exportFile(){
        var search_obj;
        if (vm.ran_simple_search) {
          search_obj = {search_string: vm.search_string};
        } else {
          search_obj = {query: vm.query};
        }
        var format = 'csv';
        if (vm.query && vm.query.return_type) {
          format = vm.query.return_type;
        }
        vm.download_pending = true;
        return Downloader[format](null, search_obj).$promise.then(function (data) {
          var blob = data.response;

          vm.download_pending = false;
          vm.download_done = true;

          $window.saveAs(blob, 'asdb_search_results.' + format);
        }).catch(function(error){
          console.log(error);
          vm.download_pending = false;
          vm.download_done = false;
          vm.download_failed = true;
          if (error.data.response.error) {
            vm.failure_reason = error.data.response.error;
          } else {
            vm.failure_reason = error.statusText;
          }
        });
      };

    }]);

})();
<commit_msg>query: Fix loadMore() to work for the non-simple-search case<commit_after>'use strict';

(function () {

  var app = angular.module('antismash.db.ui.query', [
    'ngResource',
    'antismash.db.ui.queryterm'
  ]);

  app.factory('Downloader', ['$resource', '$q', function ($resource, $q) {

    function handleError(data, status) {
      var decodedString = String.fromCharCode.apply(null, new Uint8Array(data));
      var error = JSON.parse(decodedString);
      return {
        response: error,
        status: status
      }
    }

    var MIME_MAP = {
      csv: 'text/csv',
      fasta: 'application/fasta',
      json: 'application/json'
    }

    function generate_handler(type) {
      var options = {
        method: 'POST',
        headers: {
          accept: MIME_MAP[type]
        },
        responseType: 'arraybuffer',
        cache: true,
        transformResponse: function (data, getter, status) {
          var response;

          if (status != 200) {
            return handleError(data, status);
          }

          if (data) {
            response = new Blob([data], {
              type: MIME_MAP[type]
            });
          }
          return {
            response: response
          };
        }
      };
      return options;
    }

    return $resource('/api/v1.0/export', null, {
      csv: generate_handler('csv'),
      fasta: generate_handler('fasta'),
      fastaa: generate_handler('fasta'),
      json: generate_handler('json')
    });
  }]);

  app.controller('QueryController', ['$http', '$window', '$stateParams', 'Downloader', 'bowser',
    function ($http, $window, $stateParams, Downloader, bowser) {

      var vm = this;

      vm.bowser = bowser;
      vm.search_string = '';
      vm.isValidSearch = isValidSearch;
      vm.search = search;
      vm.simpleSearch = simpleSearch;
      vm.showCluster = showCluster;
      vm.canLoadMore = canLoadMore;
      vm.loadMore = loadMore;
      vm.getNcbiUrl = getNcbiUrl;
      vm.getMibigUrl = getMibigUrl;
      vm.addEntry = addEntry;
      vm.removeEntry = removeEntry;
      vm.loadSimpleExample = loadSimpleExample;
      vm.loadComplexExample = loadComplexExample;
      vm.resetSearch = resetSearch;
      vm.downloadCsv = downloadCsv;
      vm.exportFile = exportFile;
      vm.getExportUrl = getExportUrl;
      vm.showSearch = showSearch;
      vm.graphicalPossible = graphicalPossible;
      vm.search_pending = false;
      vm.download_pending = false;
      vm.search_done = false;
      vm.download_done = false;
      vm.loading_more = false;
      vm.ran_simple_search = false;

      vm.hide_stats = true;
      vm.clusters_by_type_options = {
        title: {display: true, text: 'Clusters by types'},
        scales: {
          xAxes: [{ ticks: { autoSkip: false} }],
          yAxes: [{ ticks: {min: 0} }]
        }
      };
      vm.clusters_by_phylum_options = {
        title: {display: true, text: 'Clusters by phylum'},
        scales: {
          xAxes: [{ ticks: { autoSkip: false} }],
          yAxes: [{ ticks: {min: 0} }]
        }
      };

      vm.query = {
        search: 'cluster',
        return_type: 'json',
        terms: {
          term_type: 'expr',
          category: '',
          term: ''
        }
      };

      vm.results = {};

      if ($stateParams.search_string) {
        vm.search_string = $stateParams.search_string;
        simpleSearch();
      }

      function isValidSearch() {
        if (!vm.query) {
          return false;
        }
        if (!vm.query.terms) {
          return false;
        }
        return isValidTerm(vm.query.terms);
      }

      /* Recursively check if a term is valid
         Terms are considered valid if their category and term are not an
         empty string
       */
      function isValidTerm(term) {
        if (term.term_type == 'expr') {
          if (term.category == '') {
            return false;
          }
          if (term.term == '') {
            return false;
          }
          return true;
        }
        if (term.term_type == 'op') {
          return isValidTerm(term.left) && isValidTerm(term.right);
        }
        return false;
      }

      function search() {
        if (!isValidSearch()){
          return;
        }
        vm.search_pending = true;
        $http.post('/api/v1.0/search', {query: vm.query}).then(
          function(results){
            vm.results = results.data;
            vm.search_pending = false;
            vm.search_done = true;
            vm.ran_simple_search = false;
          }
        );
      };

      function simpleSearch() {
        vm.search_pending = true;
        $http.post('/api/v1.0/search', {search_string: vm.search_string}).then(
          function(results){
            vm.results = results.data;
            vm.search_pending = false;
            vm.search_done = true;
            vm.ran_simple_search = true;
          }
        )
      };

      function canLoadMore() {
        if (vm.results && vm.results.clusters) {
          return vm.results.clusters.length < vm.results.total;
        }
        return false;
      }

      function loadMore() {
        var next_offset = vm.results.offset + vm.results.paginate;
        var search_obj = {
          offset: next_offset
        };

        if (vm.ran_simple_search) {
          search_obj.search_string = vm.search_string;
        } else {
          search_obj.query = vm.query;
        }

        vm.loading_more = true;
        $http.post('/api/v1.0/search', search_obj).then(
          function(results){
            vm.loading_more = false;
            var new_clusters = results.data.clusters;
            for (var i = 0; i < new_clusters.length; i++) {
              vm.results.clusters.push(new_clusters[i]);
            }
            vm.results.offset = results.data.offset;
          }
        )
      }

      function showCluster(entry) {
        var cluster_acc = entry.acc + '_c' + entry.cluster_number;
        $window.open('/output/' + entry.acc + '/index.html#cluster-' + entry.cluster_number, '_blank');
      };

      function getNcbiUrl(accession) {
        if (!accession){
          return '';
        }
        return "https://www.ncbi.nlm.nih.gov/genome/?term=" + accession;
      }

      function getMibigUrl(accession) {
        if (!accession) {
          return '';
        }
        var acc = accession.split(/_/)[0];
        return "https://mibig.secondarymetabolites.org/repository/" + acc + "/index.html#cluster-1";
      };

      function addEntry(){
        vm.search_objects.push({category: {val: 'type', desc:'BGC type'}, term: '', operation: 'and'});
      };

      function removeEntry(entry){
        var idx = vm.search_objects.indexOf(entry);
        if (idx > -1) {
          vm.search_objects.splice(idx, 1);
        }
      };

      function loadSimpleExample(entry){
        vm.search_string = 'lantipeptide Streptomyces';
      };

      function loadComplexExample(entry) {
        vm.query = {
          search: 'cluster',
          return_type: 'json',
          terms: {
            term_type: 'op',
            operation: 'and',
            left: {
              term_type: 'expr',
              category: 'type',
              term: 'ripp'
            },
            right: {
              term_type: 'op',
              operation: 'or',
              left: {
                term_type: 'expr',
                category: 'genus',
                term: 'Streptomyces'
              },
              right: {
                term_type: 'expr',
                category: 'genus',
                term: 'Lactococcus'
              }
            }
          }
        };
      }

      function resetSearch(){
        vm.search_done = false;
        vm.search_pending = false;
        vm.download_done = false;
        vm.download_pending = false;
        vm.download_failed = false;
        vm.results = {};
      };

      function showSearch() {
        if (vm.query == {}){
          return true;
        };
        if (graphicalPossible()) {
          if (vm.query.return_type == 'json') {
            return true;
          }
        }
        return false;
      };

      function graphicalPossible() {
        if (vm.query.search == 'cluster') {
          return true;
        }
        return false;
      }

      function downloadCsv(){
        if (vm.query) {
          vm.query.return_type = 'csv';
        }
        exportFile();
      }

      function getExportUrl() {
        var search_string;
        var search_type = 'cluster';
        var return_type = 'csv';
        if (vm.ran_simple_search) {
          search_string = encodeURIComponent(vm.search_string);
        } else {
          search_type = vm.query.search;
          return_type = vm.query.return_type;
          search_string = encodeURIComponent(queryToString(vm.query.terms));
        }
        var search =  '/api/v1.0/export/' + search_type + '/' + return_type + '?search=' + search_string;
        return search;
      };

      function queryToString(term){
        if (term.term_type == 'expr') {
          return '[' + term.category + ']' + term.term;
        }
        if (term.term_type == 'op') {
          return '( ' + queryToString(term.left) + ' '
                      + term.operation.toUpperCase() + ' '
                      + queryToString(term.right) + ' )';
        }
      }

      function exportFile(){
        var search_obj;
        if (vm.ran_simple_search) {
          search_obj = {search_string: vm.search_string};
        } else {
          search_obj = {query: vm.query};
        }
        var format = 'csv';
        if (vm.query && vm.query.return_type) {
          format = vm.query.return_type;
        }
        vm.download_pending = true;
        return Downloader[format](null, search_obj).$promise.then(function (data) {
          var blob = data.response;

          vm.download_pending = false;
          vm.download_done = true;

          $window.saveAs(blob, 'asdb_search_results.' + format);
        }).catch(function(error){
          console.log(error);
          vm.download_pending = false;
          vm.download_done = false;
          vm.download_failed = true;
          if (error.data.response.error) {
            vm.failure_reason = error.data.response.error;
          } else {
            vm.failure_reason = error.statusText;
          }
        });
      };

    }]);

})();
<|endoftext|>


<commit_before>// Style
require('medium-editor/dist/css/medium-editor.css');
require('medium-editor/dist/css/themes/default.css');
require('./styles/index.styl');

require('./utils/ObjectAssignPolyfill');

window.React = React;
window.ReactDOM = ReactDOM;

import { Provider } from 'react-redux';
import {Router, Route, Link, browserHistory, IndexRoute} from 'react-router';
import { syncReduxAndRouter } from 'redux-simple-router'

// Components
import App from './components/App';
import Home from './components/Home';
import PlaylistEditor from './components/PlaylistEditor';
import ArticleSearch from './components/ArticleSearch';
import ArticlePreview from './components/ArticlePreview';
import ArticleCaption from './components/ArticleCaption';
import ImageSelector from './components/ImageSelector';
import Login from './components/Login';
import StyleGuide from './components/StyleGuide';

import { createHistory } from 'history';
import configureStore from './store/configureStore';

const store = configureStore();
const history = createHistory();

syncReduxAndRouter(history, store)

class PlaylistApp extends React.Component{
  render() {
    return (
      <Provider store={store}>
        <Router history={history}>
          <Route path="/" component={App}>
            <IndexRoute component={Home} />
            <Route path="/playlists" component={PlaylistEditor}>
              <Route path="/playlists/article/images" component={ImageSelector} />
              <Route path="/playlists/article/caption" component={ArticleCaption} />
            </Route>
            <Route path="/playlists/article/search" component={ArticleSearch} />
          </Route>
          <Route path="/styleguide" component={StyleGuide}/>
        </Router>
      </Provider>
    )
  }
}

registerComponent('PlaylistApp', PlaylistApp);

<commit_msg>Remove medium-editor require, since it was removed from package.json in d5fc4b401a3f12f29ded9a76d455d22d03b89426<commit_after>// Style
require('./styles/index.styl');

require('./utils/ObjectAssignPolyfill');

window.React = React;
window.ReactDOM = ReactDOM;

import { Provider } from 'react-redux';
import {Router, Route, Link, browserHistory, IndexRoute} from 'react-router';
import { syncReduxAndRouter } from 'redux-simple-router'

// Components
import App from './components/App';
import Home from './components/Home';
import PlaylistEditor from './components/PlaylistEditor';
import ArticleSearch from './components/ArticleSearch';
import ArticlePreview from './components/ArticlePreview';
import ArticleCaption from './components/ArticleCaption';
import ImageSelector from './components/ImageSelector';
import Login from './components/Login';
import StyleGuide from './components/StyleGuide';

import { createHistory } from 'history';
import configureStore from './store/configureStore';

const store = configureStore();
const history = createHistory();

syncReduxAndRouter(history, store)

class PlaylistApp extends React.Component{
  render() {
    return (
      <Provider store={store}>
        <Router history={history}>
          <Route path="/" component={App}>
            <IndexRoute component={Home} />
            <Route path="/playlists" component={PlaylistEditor}>
              <Route path="/playlists/article/images" component={ImageSelector} />
              <Route path="/playlists/article/caption" component={ArticleCaption} />
            </Route>
            <Route path="/playlists/article/search" component={ArticleSearch} />
          </Route>
          <Route path="/styleguide" component={StyleGuide}/>
        </Router>
      </Provider>
    )
  }
}

registerComponent('PlaylistApp', PlaylistApp);
<|endoftext|>


<commit_before>var express = require('express');
var request = require('request');
var router = express.Router();

var backendsUrl = 'http://exonum.com/backends/timestamping/content';

router.get('/:hash/exists', function(req, res, next) {
    var hash = req.params.hash;

    request.get(backendsUrl + '/' + hash, function(error, response, body) {
        if (!error) {
            if (response.statusCode === 200) {
                res.json({exists: true, redirect: '/f/' + hash});
            } else if (response.statusCode === 409) {
                res.json({exists: false});
            } else {
                res.render('error', {error: error});
            }
        } else {
            res.render('error', {error: error});
        }
    });
});

router.get('/:hash/redirect', function(req, res) {
    var hash = req.params.hash;

    // start pooling until it will be able to get files info with GET request which means file is in a block
    (function pooling() {
        request.get({
            url: req.protocol + '://' + req.headers.host + '/f/' + hash + '/exists',
            json: true
        }, function(error, response, body) {
            if (!error) {
                if (body.exists) {
                    res.redirect(body.redirect);
                } else {
                    setTimeout(function() {
                        pooling(res, hash);
                    }, 128);
                }
            } else {
                res.status(response.statusCode).send(error);
            }
        })
    })();
});

router.post('/proceed', function(req, res) {

    /**
     * req.body
     *
     */

    var hash = 'aaa'; // TODO
    var description = ''; // TODO

    // create file
    request.post({
        url: backendsUrl,
        headers: [{
            name: 'content-type',
            value: 'multipart/form-data'
        }],
        formData: {
            hash: hash,
            description: description
        }
    });
});

router.get('/:hash', function(req, res, next) {
    var hash = req.params.hash;

    request.get(backendsUrl + '/' + hash, function(error, response, body) {
        console.log('>>>>>');
        console.log(error);
        if (!error) {
            var data = JSON.parse(body);

            console.log(response.statusCode);
            console.log(data);

            if (response.statusCode === 200) {
                data['title'] = 'Certificate of proof';
                data['url'] = encodeURIComponent('http://ts.exonum.com/f/' + hash);

                res.render('file', data);
            } else if (response.statusCode === 409) {
                res.render('file-not-found', {title: 'File not found', hash: hash});
            } else {
                res.render('error', {error: error});
            }
        } else {
            res.render('error', {error: error});
        }
    });
});

module.exports = router;
<commit_msg>upload file into blockchain on yandex answer<commit_after>var express = require('express');
var request = require('request');
var router = express.Router();

var backendsUrl = 'http://exonum.com/backends/timestamping/content';

router.post('/proceed', function(req, res) {
    var hash = req.body.label;
    var description = '';

    // create file
    request.post({
        url: backendsUrl,
        headers: [{
            name: 'content-type',
            value: 'multipart/form-data'
        }],
        formData: {
            hash: hash,
            description: description
        }
    });

    res.status(200).send();
});

router.get('/:hash/exists', function(req, res, next) {
    var hash = req.params.hash;

    request.get(backendsUrl + '/' + hash, function(error, response, body) {
        if (!error) {
            if (response.statusCode === 200) {
                res.json({exists: true, redirect: '/f/' + hash});
            } else if (response.statusCode === 409) {
                res.json({exists: false});
            } else {
                res.render('error', {error: error});
            }
        } else {
            res.render('error', {error: error});
        }
    });
});

router.get('/:hash/redirect', function(req, res) {
    var hash = req.params.hash;

    // start pooling until it will be able to get files info with GET request which means file is in a block
    (function pooling() {
        request.get({
            url: req.protocol + '://' + req.headers.host + '/f/' + hash + '/exists',
            json: true
        }, function(error, response, body) {
            if (!error) {
                if (body.exists) {
                    res.redirect(body.redirect);
                } else {
                    setTimeout(function() {
                        pooling(res, hash);
                    }, 128);
                }
            } else {
                res.status(response.statusCode).send(error);
            }
        })
    })();
});

router.get('/:hash', function(req, res, next) {
    var hash = req.params.hash;

    request.get(backendsUrl + '/' + hash, function(error, response, body) {
        if (!error) {
            var data = JSON.parse(body);

            if (response.statusCode === 200) {
                data['title'] = 'Certificate of proof';
                data['url'] = encodeURIComponent('http://ts.exonum.com/f/' + hash);

                res.render('file', data);
            } else if (response.statusCode === 409) {
                res.render('file-not-found', {title: 'File not found', hash: hash});
            } else {
                res.render('error', {error: error});
            }
        } else {
            res.render('error', {error: error});
        }
    });
});

module.exports = router;
<|endoftext|>


<commit_before>export default Ember.Route.extend({
  beforeModel: function (transition) {

    var promises = [this.store.find('control-type')];

    promises.push(this.store.find('content-type').then(function (contentTypes) {
      this.set('contentTypes', contentTypes);
    }.bind(this)));

    return Ember.RSVP.all(promises);
  },
  model: function (params) {
    return this.store.getById('content-type', params.id);
  },
  setupController: function (controller, model) {

    controller.set('addedControls', Ember.A([]));
    controller.set('removedControls', Ember.A([]));
    controller.set('changedNameControls', Ember.A([]));
    controller.set('changedRadioControls', Ember.A([]));

    model.get('controls').forEach(function (control) {
      control.set('originalName', control.get('name'));
    });

    controller.set('isEditingTypeId', false);

    controller.set('editingControl', null);
    controller.set('isEditing', false);

    controller.set('controlTypeGroups', this.store.find('control-type-group'));

    if (model.get('oneOff') || model.get('controls').isAny('controlType.widget', 'layout')) {
      this.store.getById('control-type', 'layout').set('isHidden', true);
    } else {
      this.store.getById('control-type', 'layout').set('isHidden', false);
    }

    controller.set('contentTypes', this.get('contentTypes'));

    model.get('controls').setEach('widgetIsValid', true);
    model.get('controls').setEach('value', null);

    model.get('controls').filterBy('controlType.widget', 'checkbox').forEach(function (control) {
      control.get('meta.data.options').setEach('value', undefined);
    });

    model.get('controls').filterBy('controlType.widget', 'radio').forEach(function (control) {
      control.set('originalOptions', control.get('meta.data.options').getEach('value'));
    });

    model.get('controls').filterBy('controlType.widget', 'tabular').forEach(function (control) {

      var value = Ember.A([]);
      var emptyRow = Ember.A([]);
      control.get('meta.data.options').forEach(function () {
        emptyRow.pushObject("");
      });
      value.pushObject(emptyRow);

      control.set('value', value);

    });

    this._super.apply(this, arguments);
  }
});
<commit_msg>hide layouts if not supported by generator<commit_after>export default Ember.Route.extend({
  beforeModel: function (transition) {

    var promises = [this.store.find('control-type')];

    promises.push(this.store.find('content-type').then(function (contentTypes) {
      this.set('contentTypes', contentTypes);
    }.bind(this)));

    return Ember.RSVP.all(promises);
  },
  model: function (params) {
    return this.store.getById('content-type', params.id);
  },
  setupController: function (controller, model) {

    controller.set('addedControls', Ember.A([]));
    controller.set('removedControls', Ember.A([]));
    controller.set('changedNameControls', Ember.A([]));
    controller.set('changedRadioControls', Ember.A([]));

    model.get('controls').forEach(function (control) {
      control.set('originalName', control.get('name'));
    });

    controller.set('isEditingTypeId', false);

    controller.set('editingControl', null);
    controller.set('isEditing', false);

    controller.set('controlTypeGroups', this.store.find('control-type-group'));

    if (this.get('session.supportedMessages.layouts')) {

      if (model.get('oneOff') || model.get('controls').isAny('controlType.widget', 'layout')) {
        this.store.getById('control-type', 'layout').set('isHidden', true);
      } else {
        this.store.getById('control-type', 'layout').set('isHidden', false);
      }

    } else {

      this.store.getById('control-type', 'layout').set('isHidden', true);

    }

    controller.set('contentTypes', this.get('contentTypes'));

    model.get('controls').setEach('widgetIsValid', true);
    model.get('controls').setEach('value', null);

    model.get('controls').filterBy('controlType.widget', 'checkbox').forEach(function (control) {
      control.get('meta.data.options').setEach('value', undefined);
    });

    model.get('controls').filterBy('controlType.widget', 'radio').forEach(function (control) {
      control.set('originalOptions', control.get('meta.data.options').getEach('value'));
    });

    model.get('controls').filterBy('controlType.widget', 'tabular').forEach(function (control) {

      var value = Ember.A([]);
      var emptyRow = Ember.A([]);
      control.get('meta.data.options').forEach(function () {
        emptyRow.pushObject("");
      });
      value.pushObject(emptyRow);

      control.set('value', value);

    });

    this._super.apply(this, arguments);
  }
});
<|endoftext|>


<commit_before>import TravisRoute from 'travis/routes/basic';

export default TravisRoute.extend({
  needsAuth: false,

  model() {
    return [
      {
        name: 'Sven Fuchs',
        title: 'The Original Builder',
        handle: 'svenfuchs',
        nationality: 'germany',
        country: 'germany',
        image: 'sven'
      }, {
        name: 'Josh Kalderimis',
        title: 'Chief Post-It Officer',
        handle: 'j2h',
        nationality: 'newzealand',
        country: 'germany',
        image: 'josh'
      }, {
        name: 'Fritz Thielemann',
        title: 'Admin Adventures',
        handle: 'fritzek',
        nationality: 'germany',
        country: 'germany',
        image: 'fritz'
      }, {
        name: 'Konstantin Haase',
        title: 'Haase of Engineering',
        handle: 'konstantinhaase',
        nationality: 'germany',
        country: 'switzerland',
        image: 'konstantin'
      }, {
        name: 'Mathias Meyer',
        title: 'Director of Bacon Relations',
        handle: 'roidrage',
        nationality: 'germany',
        country: 'germany',
        image: 'mathias'
      }, {
        name: 'Piotr Sarnacki',
        title: 'Code Monkey',
        handle: 'drogus',
        nationality: 'poland',
        country: 'germany',
        image: 'piotr'
      }, {
        name: 'Anika Lindtner',
        title: 'Head Catwoman',
        handle: 'langziehohr',
        nationality: 'germany',
        country: 'germany',
        image: 'anika'
      }, {
        name: 'Henrik Hodne',
        title: 'DevOops Engineer',
        handle: 'henrikhodne',
        nationality: 'norway',
        country: 'norway',
        image: 'henrik'
      }, {
        name: 'Justine Arreche',
        title: 'Lead Clipart Strategist',
        handle: 'saltinejustine',
        nationality: 'usa',
        country: 'usa',
        image: 'justine'
      }, {
        name: 'Hiro Asari',
        title: 'Time Zone Nerd',
        handle: 'hiro_asari',
        nationality: 'japan',
        country: 'usa',
        image: 'hiro'
      }, {
        name: 'Dan Buch',
        title: 'That\'s Numberwang',
        handle: 'meatballhat',
        nationality: 'usa',
        country: 'usa',
        image: 'dan'
      }, {
        name: 'Lisa Passing',
        title: 'Queen of !important',
        nationality: 'germany',
        country: 'germany',
        image: 'lisa'
      }, {
        name: 'Carla Drago',
        title: 'inchworm',
        handle: 'carlad',
        nationality: 'italy',
        country: 'germany',
        image: 'carla'
      }, {
        name: 'Anja Reichmann',
        title: 'Tyranjasaurus Specs',
        handle: '_tyranja_',
        nationality: 'germany',
        country: 'germany',
        image: 'anja'
      }, {
        name: 'Aly Fulton',
        title: 'Resident Linguist',
        handle: 'sinthetix',
        nationality: 'usa',
        country: 'usa',
        image: 'aly'
      }, {
        name: 'Amanda Quaranto',
        title: 'Crafting Extremist',
        handle: 'aquaranto',
        nationality: 'usa',
        country: 'usa',
        image: 'amanda'
      }, {
        name: 'Jen Duke',
        title: 'Gastrognome',
        handle: 'dukeofberlin',
        nationality: 'usa',
        country: 'germany',
        image: 'jen'
      }, {
        name: 'Brandon Burton',
        title: 'Infrastructure Conductor',
        handle: 'solarce',
        nationality: 'usa',
        country: 'usa',
        image: 'brandon'
      }, {
        name: 'Emma Trimble',
        title: 'Lead Pungineer',
        handle: 'emdantrim',
        nationality: 'usa',
        country: 'usa',
        image: 'emma'
      }, {
        name: 'María de Antón',
        title: 'Sous Chef at The Bloge',
        handle: 'amalulla',
        nationality: 'spain',
        country: 'spain',
        image: 'maria'
      }, {
        name: 'Danish Khan',
        title: 'Red Shirt',
        handle: 'danishkhan',
        nationality: 'usa',
        country: 'usa',
        image: 'danish'
      }, {
        name: 'Dominic Jodoin',
        title: 'Humble Tab Hoarder',
        handle: 'cotsog',
        nationality: 'canada',
        country: 'canada',
        image: 'dominic'
      }, {
        name: 'Liz Brisker',
        title: 'Mermaid On Board',
        nationality: 'russia',
        country: 'germany',
        image: 'liz'
      }, {
        name: 'Laura Gaetano',
        title: 'Two Trick Pony',
        handle: 'alicetragedy',
        nationality: 'italy',
        country: 'austria',
        image: 'laura'
      }, {
        name: 'Maren Brechler',
        title: 'Number Juggler',
        nationality: 'germany',
        country: 'germany',
        image: 'maren'
      }, {
        name: 'Ana Rosas',
        title: 'Software Baker',
        handle: 'ana_rosas',
        nationality: 'mexico',
        country: 'mexico',
        image: 'ana'
      }, {
        name: 'Igor Wiedler',
        title: 'webmaster',
        handle: 'igorwhilefalse',
        nationality: 'ukswitzerland',
        country: 'germany',
        image: 'igor'
      }, {
        name: 'Carmen Andoh',
        title: 'SRE- Snazzy Rsync Empress',
        handle: 'caelestisca',
        nationality: 'usa',
        country: 'usa',
        image: 'carmen'
      }, {
        name: 'Buck Doyle',
        title: 'Jorts enthusiast',
        handle: 'buckdoyle',
        nationality: 'none',
        country: 'none',
        image: 'buck'
      }, {
        name: 'Curtis Ekstrom',
        title: 'Fallen for JavaScript',
        handle: 'clekstro',
        nationality: 'usa',
        country: 'germany',
        image: 'curtis'
      }, {
        name: 'Joe Corcoran',
        title: 'Bulldozer',
        handle: 'josephcorcoran',
        nationality: 'uk',
        country: 'germany',
        image: 'joe'
      }, {
        name: 'Aakriti Gupta',
        title: 'Custodian of the Hard Hat',
        handle: 'aakri_tea',
        nationality: 'india',
        country: 'germany',
        image: 'aakriti'
      }, {
        name: 'Renée Hendricksen',
        title: 'Ski Lift Operator',
        handle: 'gigglegirl4e',
        nationality: 'usa',
        country: 'usa',
        image: 'renee'
      }, {
        name: 'Brandon Ferguson',
        title: 'Actual Human Muppet',
        handle: 'bnferguson',
        nationality: 'usa',
        country: 'netherlands',
        image: 'bmoney'
      }, {
        name: 'Anna Nagy',
        title: 'Trainspotter',
        handle: 'acnagy',
        nationality: 'usa',
        country: 'usa',
        image: 'anna'
      }, {
        name: 'Lena Reinhard',
        title: 'Team Lead',
        handle: 'lrnrd',
        nationality: 'germany',
        country: 'germany',
        image: 'lena'
      }, {
        name: 'Sam Wright',
        title: 'Documentarian',
        handle: 'plaindocs',
        nationality: 'none',
        country: 'germany',
        image: 'sam'
      }
    ];
  }
});
<commit_msg>Update Sam’s nationality (#753)<commit_after>import TravisRoute from 'travis/routes/basic';

export default TravisRoute.extend({
  needsAuth: false,

  model() {
    return [
      {
        name: 'Sven Fuchs',
        title: 'The Original Builder',
        handle: 'svenfuchs',
        nationality: 'germany',
        country: 'germany',
        image: 'sven'
      }, {
        name: 'Josh Kalderimis',
        title: 'Chief Post-It Officer',
        handle: 'j2h',
        nationality: 'newzealand',
        country: 'germany',
        image: 'josh'
      }, {
        name: 'Fritz Thielemann',
        title: 'Admin Adventures',
        handle: 'fritzek',
        nationality: 'germany',
        country: 'germany',
        image: 'fritz'
      }, {
        name: 'Konstantin Haase',
        title: 'Haase of Engineering',
        handle: 'konstantinhaase',
        nationality: 'germany',
        country: 'switzerland',
        image: 'konstantin'
      }, {
        name: 'Mathias Meyer',
        title: 'Director of Bacon Relations',
        handle: 'roidrage',
        nationality: 'germany',
        country: 'germany',
        image: 'mathias'
      }, {
        name: 'Piotr Sarnacki',
        title: 'Code Monkey',
        handle: 'drogus',
        nationality: 'poland',
        country: 'germany',
        image: 'piotr'
      }, {
        name: 'Anika Lindtner',
        title: 'Head Catwoman',
        handle: 'langziehohr',
        nationality: 'germany',
        country: 'germany',
        image: 'anika'
      }, {
        name: 'Henrik Hodne',
        title: 'DevOops Engineer',
        handle: 'henrikhodne',
        nationality: 'norway',
        country: 'norway',
        image: 'henrik'
      }, {
        name: 'Justine Arreche',
        title: 'Lead Clipart Strategist',
        handle: 'saltinejustine',
        nationality: 'usa',
        country: 'usa',
        image: 'justine'
      }, {
        name: 'Hiro Asari',
        title: 'Time Zone Nerd',
        handle: 'hiro_asari',
        nationality: 'japan',
        country: 'usa',
        image: 'hiro'
      }, {
        name: 'Dan Buch',
        title: 'That\'s Numberwang',
        handle: 'meatballhat',
        nationality: 'usa',
        country: 'usa',
        image: 'dan'
      }, {
        name: 'Lisa Passing',
        title: 'Queen of !important',
        nationality: 'germany',
        country: 'germany',
        image: 'lisa'
      }, {
        name: 'Carla Drago',
        title: 'inchworm',
        handle: 'carlad',
        nationality: 'italy',
        country: 'germany',
        image: 'carla'
      }, {
        name: 'Anja Reichmann',
        title: 'Tyranjasaurus Specs',
        handle: '_tyranja_',
        nationality: 'germany',
        country: 'germany',
        image: 'anja'
      }, {
        name: 'Aly Fulton',
        title: 'Resident Linguist',
        handle: 'sinthetix',
        nationality: 'usa',
        country: 'usa',
        image: 'aly'
      }, {
        name: 'Amanda Quaranto',
        title: 'Crafting Extremist',
        handle: 'aquaranto',
        nationality: 'usa',
        country: 'usa',
        image: 'amanda'
      }, {
        name: 'Jen Duke',
        title: 'Gastrognome',
        handle: 'dukeofberlin',
        nationality: 'usa',
        country: 'germany',
        image: 'jen'
      }, {
        name: 'Brandon Burton',
        title: 'Infrastructure Conductor',
        handle: 'solarce',
        nationality: 'usa',
        country: 'usa',
        image: 'brandon'
      }, {
        name: 'Emma Trimble',
        title: 'Lead Pungineer',
        handle: 'emdantrim',
        nationality: 'usa',
        country: 'usa',
        image: 'emma'
      }, {
        name: 'María de Antón',
        title: 'Sous Chef at The Bloge',
        handle: 'amalulla',
        nationality: 'spain',
        country: 'spain',
        image: 'maria'
      }, {
        name: 'Danish Khan',
        title: 'Red Shirt',
        handle: 'danishkhan',
        nationality: 'usa',
        country: 'usa',
        image: 'danish'
      }, {
        name: 'Dominic Jodoin',
        title: 'Humble Tab Hoarder',
        handle: 'cotsog',
        nationality: 'canada',
        country: 'canada',
        image: 'dominic'
      }, {
        name: 'Liz Brisker',
        title: 'Mermaid On Board',
        nationality: 'russia',
        country: 'germany',
        image: 'liz'
      }, {
        name: 'Laura Gaetano',
        title: 'Two Trick Pony',
        handle: 'alicetragedy',
        nationality: 'italy',
        country: 'austria',
        image: 'laura'
      }, {
        name: 'Maren Brechler',
        title: 'Number Juggler',
        nationality: 'germany',
        country: 'germany',
        image: 'maren'
      }, {
        name: 'Ana Rosas',
        title: 'Software Baker',
        handle: 'ana_rosas',
        nationality: 'mexico',
        country: 'mexico',
        image: 'ana'
      }, {
        name: 'Igor Wiedler',
        title: 'webmaster',
        handle: 'igorwhilefalse',
        nationality: 'ukswitzerland',
        country: 'germany',
        image: 'igor'
      }, {
        name: 'Carmen Andoh',
        title: 'SRE- Snazzy Rsync Empress',
        handle: 'caelestisca',
        nationality: 'usa',
        country: 'usa',
        image: 'carmen'
      }, {
        name: 'Buck Doyle',
        title: 'Jorts enthusiast',
        handle: 'buckdoyle',
        nationality: 'none',
        country: 'none',
        image: 'buck'
      }, {
        name: 'Curtis Ekstrom',
        title: 'Fallen for JavaScript',
        handle: 'clekstro',
        nationality: 'usa',
        country: 'germany',
        image: 'curtis'
      }, {
        name: 'Joe Corcoran',
        title: 'Bulldozer',
        handle: 'josephcorcoran',
        nationality: 'uk',
        country: 'germany',
        image: 'joe'
      }, {
        name: 'Aakriti Gupta',
        title: 'Custodian of the Hard Hat',
        handle: 'aakri_tea',
        nationality: 'india',
        country: 'germany',
        image: 'aakriti'
      }, {
        name: 'Renée Hendricksen',
        title: 'Ski Lift Operator',
        handle: 'gigglegirl4e',
        nationality: 'usa',
        country: 'usa',
        image: 'renee'
      }, {
        name: 'Brandon Ferguson',
        title: 'Actual Human Muppet',
        handle: 'bnferguson',
        nationality: 'usa',
        country: 'netherlands',
        image: 'bmoney'
      }, {
        name: 'Anna Nagy',
        title: 'Trainspotter',
        handle: 'acnagy',
        nationality: 'usa',
        country: 'usa',
        image: 'anna'
      }, {
        name: 'Lena Reinhard',
        title: 'Team Lead',
        handle: 'lrnrd',
        nationality: 'germany',
        country: 'germany',
        image: 'lena'
      }, {
        name: 'Sam Wright',
        title: 'Documentarian',
        handle: 'plaindocs',
        nationality: 'uk',
        country: 'germany',
        image: 'sam'
      }
    ];
  }
});
<|endoftext|>


<commit_before>import ReactDOM from 'react-dom';

import {
  relToAbsChromPos,
  scalesCenterAndK,
} from './utils';

import {
  setDarkTheme, setTileProxyAuthHeader
} from './services';

import {
  MOUSE_TOOL_MOVE,
  MOUSE_TOOL_SELECT,
} from './configs';

import pubSub, { create } from './services/pub-sub';

import ChromosomeInfo from './ChromosomeInfo';

let stack = {};
let pubSubs = [];

const apiPubSub = create(stack);

export const destroy = () => {
  pubSubs.forEach(subscription => pubSub.unsubscribe(subscription));
  pubSubs = [];
  stack = {};
};

const api = function api(context) {
  const self = context;

  // Public API
  return {
    setAuthHeader(newHeader) {
      setTileProxyAuthHeader(newHeader);

      // we need to re-request all the tiles
      this.reload();
    },

    /**
     * Reload all of the tiles
     */
    reload() {

    },

    destroy() {
      ReactDOM.unmountComponentAtNode(self.topDiv.parentNode);
    },

    setViewConfig(newViewConfig) {
      /**
       * Set a new view config to define the layout and data
       * of this component
       *
       * Parameters
       * ----------
       *  newViewConfig: {}
       *    A JSON object that defines the state of the HiGlassComponent
       *
       * Returns
       * -------
       *  dataLoaded: Promise
       *    A promise that resolves when all of the data for this viewconfig
       *    is loaded
       */
      const viewsByUid = self.processViewConfig(newViewConfig);
      const p = new Promise((resolve) => {
        this.requestsInFlight = 0;

        pubSubs.push(pubSub.subscribe('requestSent', () => {
          this.requestsInFlight += 1;
        }));

        pubSubs.push(pubSub.subscribe('requestReceived', () => {
          this.requestsInFlight -= 1;

          if (this.requestsInFlight === 0) {
            resolve();
          }
        }));

        self.setState({
          viewConfig: newViewConfig,
          views: viewsByUid,
        }, () => {

        });
      });

      return p;
    },

    /**
     * Retrieve a sharable link for the current view config
     *
     * @param {string}  url  Custom URL that should point to a higlass server's
     *   view config endpoint, i.e.,
     *   `http://my-higlass-server.com/api/v1/viewconfs/`.
     * @return  {Object}  Promise resolving to the link ID and URL.
     */
    shareViewConfigAsLink(url) {
      return self.handleExportViewsAsLink(url, true);
    },

    /**
     * Show overlays where this track can be positioned
     *
     * @param {obj} track: { server, tilesetUid, datatype }
     */
    showAvailableTrackPositions(track) {
      self.setState({
        draggingHappening: track,
      });
    },

    /**
     * Hide the overlay showing wher this track can be positioned
     */
    hideAvailableTrackPositions(track) {
      self.setState({
        draggingHappening: null,
      });
    },

    /**
     * Choose a theme.
     */
    setDarkTheme(darkTheme) {
      setDarkTheme(!!darkTheme);
    },

    zoomToDataExtent(viewUid) {
      /**
       * Zoom so that the entire dataset is visible
       *
       * Parameters
       * ----------
       *  viewUid: string
       *    The view uid to zoom to extent to
       *
       * Returns
       * -------
       *  nothing
       */
      self.handleZoomToData(viewUid);
    },

    getDataURI() {
      /**
       * Export the current canvas as a PNG string so that
       * it can be saved
       *
       * Return
       * ------
       *  pngString: string
       *    A data URI
       */
      return self.createDataURI();
    },

    /**
     * Activate a specific mouse tool.
     *
     * @description
     * Mouse tools enable different behaviors which would otherwise clash. For
     *
     * @param {string}  tool  Mouse tool name to be selected.
     */
    activateTool(tool) {
      switch (tool) {
        case 'select':
          self.setMouseTool(MOUSE_TOOL_SELECT);
          break;

        default:
          self.setMouseTool(MOUSE_TOOL_MOVE);
          break;
      }
    },

    /*
     * Get the current view as a Data URI
     *
     * @return {string} A data URI describing the current state of the canvas
     */
    exportAsPng() {
      return self.createDataURI();
    },

    /*
     * Get the current view as an SVG. Relies on all the tracks implementing
     * their respective exportAsSVG methods.
     *
     * @return {string} An SVG string of the current view.
     */
    exportAsSvg() {
      return self.createSVGString();
    },

    /*
     * Export the current view as a Viewconf.
     *
     * @return {string} A stringified version of the current viewconf
    */
    exportAsViewConfString() {
      return self.getViewsAsString();
    },

    /*
     * Get the current range selection
     *
     * @return {???} What is the return type here??
     */
    getRangeSelection() {
      return self.rangeSelection;
    },

    getLocation(viewId) {
      if (typeof viewId === 'undefined') {
        return 'Please provide the view UUID sweetheart 😙';
      }
      return {
        xDomain: self.xScales[viewId].domain(),
        yDomain: self.yScales[viewId].domain()
      };
    },

    zoomTo(
      viewUid,
      start1Abs,
      end1Abs,
      start2Abs,
      end2Abs,
      animateTime = 0,
    ) {
      self.zoomTo(viewUid, start1Abs, end1Abs, start2Abs, end2Abs, animateTime);
    },

    off(event, listenerId, viewId) {
      const callback = typeof listenerId === 'object'
        ? listenerId.callback
        : listenerId;

      switch (event) {
        case 'location':
          self.offLocationChange(viewId, listenerId);
          break;

        case 'mouseMoveZoom':
          apiPubSub.unsubscribe('mouseMoveZoom', callback);
          break;

        case 'rangeSelection':
          apiPubSub.unsubscribe('rangeSelection', callback);
          break;

        case 'viewConfig':
          self.offViewChange(listenerId);
          break;

        default:
          // nothing
          break;
      }
    },

    on(event, callback, viewId, callbackId) {
      switch (event) {
        case 'location':
          // returns a set of scales (xScale, yScale) on every zoom event
          return self.onLocationChange(viewId, callback, callbackId);

        case 'mouseMoveZoom':
          return apiPubSub.subscribe('mouseMoveZoom', callback);

        case 'rangeSelection':
          return apiPubSub.subscribe('rangeSelection', callback);

        case 'viewConfig':
          return self.onViewChange(callback);

        default:
          return undefined;
      }
    },
  };
};

export default api;
export const publish = apiPubSub.publish;
<commit_msg>Remove unused imports<commit_after>import ReactDOM from 'react-dom';

import {
  setDarkTheme, setTileProxyAuthHeader
} from './services';

import {
  MOUSE_TOOL_MOVE,
  MOUSE_TOOL_SELECT,
} from './configs';

import pubSub, { create } from './services/pub-sub';

let stack = {};
let pubSubs = [];

const apiPubSub = create(stack);

export const destroy = () => {
  pubSubs.forEach(subscription => pubSub.unsubscribe(subscription));
  pubSubs = [];
  stack = {};
};

const api = function api(context) {
  const self = context;

  // Public API
  return {
    setAuthHeader(newHeader) {
      setTileProxyAuthHeader(newHeader);

      // we need to re-request all the tiles
      this.reload();
    },

    /**
     * Reload all of the tiles
     */
    reload() {

    },

    destroy() {
      ReactDOM.unmountComponentAtNode(self.topDiv.parentNode);
    },

    setViewConfig(newViewConfig) {
      /**
       * Set a new view config to define the layout and data
       * of this component
       *
       * Parameters
       * ----------
       *  newViewConfig: {}
       *    A JSON object that defines the state of the HiGlassComponent
       *
       * Returns
       * -------
       *  dataLoaded: Promise
       *    A promise that resolves when all of the data for this viewconfig
       *    is loaded
       */
      const viewsByUid = self.processViewConfig(newViewConfig);
      const p = new Promise((resolve) => {
        this.requestsInFlight = 0;

        pubSubs.push(pubSub.subscribe('requestSent', () => {
          this.requestsInFlight += 1;
        }));

        pubSubs.push(pubSub.subscribe('requestReceived', () => {
          this.requestsInFlight -= 1;

          if (this.requestsInFlight === 0) {
            resolve();
          }
        }));

        self.setState({
          viewConfig: newViewConfig,
          views: viewsByUid,
        }, () => {

        });
      });

      return p;
    },

    /**
     * Retrieve a sharable link for the current view config
     *
     * @param {string}  url  Custom URL that should point to a higlass server's
     *   view config endpoint, i.e.,
     *   `http://my-higlass-server.com/api/v1/viewconfs/`.
     * @return  {Object}  Promise resolving to the link ID and URL.
     */
    shareViewConfigAsLink(url) {
      return self.handleExportViewsAsLink(url, true);
    },

    /**
     * Show overlays where this track can be positioned
     *
     * @param {obj} track: { server, tilesetUid, datatype }
     */
    showAvailableTrackPositions(track) {
      self.setState({
        draggingHappening: track,
      });
    },

    /**
     * Hide the overlay showing wher this track can be positioned
     */
    hideAvailableTrackPositions(track) {
      self.setState({
        draggingHappening: null,
      });
    },

    /**
     * Choose a theme.
     */
    setDarkTheme(darkTheme) {
      setDarkTheme(!!darkTheme);
    },

    zoomToDataExtent(viewUid) {
      /**
       * Zoom so that the entire dataset is visible
       *
       * Parameters
       * ----------
       *  viewUid: string
       *    The view uid to zoom to extent to
       *
       * Returns
       * -------
       *  nothing
       */
      self.handleZoomToData(viewUid);
    },

    getDataURI() {
      /**
       * Export the current canvas as a PNG string so that
       * it can be saved
       *
       * Return
       * ------
       *  pngString: string
       *    A data URI
       */
      return self.createDataURI();
    },

    /**
     * Activate a specific mouse tool.
     *
     * @description
     * Mouse tools enable different behaviors which would otherwise clash. For
     *
     * @param {string}  tool  Mouse tool name to be selected.
     */
    activateTool(tool) {
      switch (tool) {
        case 'select':
          self.setMouseTool(MOUSE_TOOL_SELECT);
          break;

        default:
          self.setMouseTool(MOUSE_TOOL_MOVE);
          break;
      }
    },

    /*
     * Get the current view as a Data URI
     *
     * @return {string} A data URI describing the current state of the canvas
     */
    exportAsPng() {
      return self.createDataURI();
    },

    /*
     * Get the current view as an SVG. Relies on all the tracks implementing
     * their respective exportAsSVG methods.
     *
     * @return {string} An SVG string of the current view.
     */
    exportAsSvg() {
      return self.createSVGString();
    },

    /*
     * Export the current view as a Viewconf.
     *
     * @return {string} A stringified version of the current viewconf
    */
    exportAsViewConfString() {
      return self.getViewsAsString();
    },

    /*
     * Get the current range selection
     *
     * @return {???} What is the return type here??
     */
    getRangeSelection() {
      return self.rangeSelection;
    },

    getLocation(viewId) {
      if (typeof viewId === 'undefined') {
        return 'Please provide the view UUID sweetheart 😙';
      }
      return {
        xDomain: self.xScales[viewId].domain(),
        yDomain: self.yScales[viewId].domain()
      };
    },

    zoomTo(
      viewUid,
      start1Abs,
      end1Abs,
      start2Abs,
      end2Abs,
      animateTime = 0,
    ) {
      self.zoomTo(viewUid, start1Abs, end1Abs, start2Abs, end2Abs, animateTime);
    },

    off(event, listenerId, viewId) {
      const callback = typeof listenerId === 'object'
        ? listenerId.callback
        : listenerId;

      switch (event) {
        case 'location':
          self.offLocationChange(viewId, listenerId);
          break;

        case 'mouseMoveZoom':
          apiPubSub.unsubscribe('mouseMoveZoom', callback);
          break;

        case 'rangeSelection':
          apiPubSub.unsubscribe('rangeSelection', callback);
          break;

        case 'viewConfig':
          self.offViewChange(listenerId);
          break;

        default:
          // nothing
          break;
      }
    },

    on(event, callback, viewId, callbackId) {
      switch (event) {
        case 'location':
          // returns a set of scales (xScale, yScale) on every zoom event
          return self.onLocationChange(viewId, callback, callbackId);

        case 'mouseMoveZoom':
          return apiPubSub.subscribe('mouseMoveZoom', callback);

        case 'rangeSelection':
          return apiPubSub.subscribe('rangeSelection', callback);

        case 'viewConfig':
          return self.onViewChange(callback);

        default:
          return undefined;
      }
    },
  };
};

export default api;
export const publish = apiPubSub.publish;
<|endoftext|>


<commit_before>'use strict';

var regexIso8601 =
  /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})\.(\d{1,})(Z|([\-+])(\d{2}):(\d{2}))?$/;
// Matches YYYY-MM-ddThh:mm:ss.sssZ where .sss is optional

function convertDateStringsToDates(input) {
  // Ignore things that aren't objects.
  if (typeof input !== 'object') {
    return input;
  }

  for (var key in input) {
    if (!input.hasOwnProperty(key)) {
      continue;
    }

    var value = input[key];
    var match;
    // Check for string properties which look like dates.
    if (typeof value === 'string' && (match = value.match(regexIso8601))) {
      var milliseconds = Date.parse(match[0]);
      if (!isNaN(milliseconds)) {
        input[key] = new Date(milliseconds);
      }
    } else if (typeof value === 'object') {
      // Recurse into object
      input[key] = convertDateStringsToDates(value);
    }
  }
  return input;
}
function addExtendedEnumValue(id, labelLong, labelShort, value) {
  return {
    id: id,
    label: {
      long: labelLong,
      short: labelShort
    },
    value: value
  };
}

/* This is a pseudo-function in order to enable gettext-extractor to find the translations that need to be done in the constants.
   As described in https://github.com/rubenv/angular-gettext/issues/67
*/
function gettext(string) {
  return string;
}

/**
 */
angular
  .module('openolitor-kundenportal', [
    'ngAnimate',
    'ngResource',
    'ngRoute',
    'ngSanitize',
    'ngTouch',
    'ngTable',
    'ngFileSaver',
    'ngCookies',
    'ngPasswordStrength',
    'ngMessages',
    'angular.filter',
    'ui.bootstrap',
    'ui.bootstrap.datetimepicker',
    'color.picker',
    'ipCookie',
    'frapontillo.bootstrap-switch',
    'gettext',
    'ngHamburger',
    'angularMoment',
    'ngFileUpload',
    'ngLodash',
    'angular-sortable-view',
    'ngclipboard',
    'mm.iban',
    'piwik'
  ])
  .constant('BUILD_NR', '@@BUILD_NR')
  .constant('LIEFEREINHEIT', {
    STUECK: addExtendedEnumValue('Stueck', gettext('Stück'), gettext('St.')),
    BUND: addExtendedEnumValue('Bund', gettext('Bund'), gettext('Bu.')),
    GRAMM: addExtendedEnumValue('Gramm', gettext('Gramm'), gettext('gr')),
    KILOGRAMM: addExtendedEnumValue('Kilogramm', gettext('Kilogramm'),
      gettext('kg')),
    LITER: addExtendedEnumValue('Liter', gettext('Liter'), gettext('l')),
    PORTION: addExtendedEnumValue('Portion', gettext('Portion'), gettext('Por.'))
  })
  .constant('USER_ROLES', {
    Guest: 'Guest',
    Administrator: 'Administrator',
    Kunde:'Kunde'
  })
  .run(function($rootScope, $location, $anchorScroll) {
    $rootScope.location = $location;
    $anchorScroll.yOffset = 50;

    $rootScope.$on('$routeChangeSuccess', function(newRoute, oldRoute) {
      if($location.hash()) $anchorScroll();
    });
  })
  .constant('WAEHRUNG', {
    CHF: addExtendedEnumValue('CHF', gettext('Schweizer Franken'), gettext(
      'CHF')),
    EUR: addExtendedEnumValue('EUR', gettext('Euro'), gettext('EUR')),
    USD: addExtendedEnumValue('USD', gettext('US Dollar'), gettext('USD')),
    GBP: addExtendedEnumValue('GBP', gettext('Britisches Pfund'), gettext(
      'GBP')),
    CAD: addExtendedEnumValue('CAD', gettext('Kanadischer Dollar'), gettext(
      'CAD'))
  })
  .service('appConfig', function() {
    var loaded = false;
    var configData = {
    };
    configData = getConfig();
    loaded = true;
    return {
      get: function() {
        return configData;
      },
      isLoaded: function() {
        return loaded;
      }
    };
  })
  .run(function(appConfig) {
    appConfig.get();
  })
  .factory('checkSize', ['$rootScope', '$window', function($rootScope, $window) {
    return function() {
      if ($window.innerWidth >= 1200) {
        $rootScope.tgState = true;
      }
    };
  }])
  .factory('convertDateStringsToDatesFct', function() {
    return function(input) {
      return convertDateStringsToDates(input);
    };
  })
  .config(['$provide', function($provide) {
    $provide.decorator('$exceptionHandler', ['$log', '$injector',
      function($log, $injector) {
        return function(exception) {
          // using the injector to retrieve services, otherwise circular dependency
          var alertService = $injector.get('alertService');
          alertService.addAlert('error', exception.message);
          // log error default style
          $log.error.apply($log, arguments);
        };
      }
    ]);
  }])
  .factory('msgBus', [
    '$rootScope',
    function($rootScope) {
      var msgBus = {};
      msgBus.emitMsg = function(msg) {
        $rootScope.$emit(msg.type, msg);
      };
      msgBus.onMsg = function(msg, scope, func) {
        var unbind = $rootScope.$on(msg, func);
        scope.$on('$destroy', unbind);
      };
      return msgBus;
    }
  ])
  .run(['ooClientMessageService', '$timeout', function(clientMessageService, $timeout) {
    $timeout(function() {
      console.log('Start clientMessageService');
      clientMessageService.start();
    }, 1000);
  }])
  .factory('loggedOutInterceptor', function($q, alertService) {
    return {
      responseError: function(rejection) {
        var status = rejection.status;
        if (status === 401) {
          alertService.removeAllAlerts();
          window.location = '#/logout';
          return;
        }
        return $q.reject(rejection);
      }
    };
  })
  .config(['$httpProvider', function($httpProvider) {
    $httpProvider.defaults.transformResponse.push(function(responseData) {
      return convertDateStringsToDates(responseData);
    });
  }])
  .filter('unsafe', [
        '$sce',
        function($sce) {
            return function(value) {
                return $sce.trustAsHtml(value);
            };
        }
    ])

  .filter('dateRange', function(moment) {
    function isMidnight(mom) {
      // The moment at midnight
      var mmtMidnight = mom.clone().startOf('day');

      // Difference in minutes == 0 => midnight
      return mom.diff(mmtMidnight, 'minutes') === 0;
    }

    return function(items, from, to, attribute) {
      if (!angular.isUndefined(items) && items.length > 0) {
        var toPlusOne = to;
        var momTo = moment(to);
        if (isMidnight(momTo)) {
          toPlusOne = momTo.add(1, 'days');
        }
        var result = [];
        for (var i = 0; i < items.length; i++) {
          var itemDate = items[i][attribute];
          if (!angular.isUndefined(attribute)) {
            itemDate = items[i][attribute];
          }
          if (angular.isUndefined(to) && angular.isUndefined(from)) {
            result.push(items[i]);
          } else if (angular.isUndefined(to) && itemDate >= from) {
            result.push(items[i]);
          } else if (angular.isUndefined(from) && itemDate <= toPlusOne) {
            result.push(items[i]);
          } else if (itemDate >= from && itemDate <= toPlusOne) {
            result.push(items[i]);
          }
        }
        return result;
      }
    };
  })
  .filter('fromNow', function(moment) {
    return function(input) {
      return moment(input).fromNow();
    };
  })
  .config(['$httpProvider', function($httpProvider) {
    $httpProvider.interceptors.push('loggedOutInterceptor');
    $httpProvider.interceptors.push('errbitErrorInterceptor');
  }])
  .config(['$locationProvider', function($locationProvider) {
    $locationProvider.hashPrefix('');
  }])
  .config(['$qProvider', function ($qProvider) {
    $qProvider.errorOnUnhandledRejections(false);
  }])
  .filter('notIn', function() {
    return function(items, property, elements) {
      var filtered = [];
      if (!items) {
        return filtered;
      }
      for (var i = 0; i < items.length; i++) {
        var item = items[i];
        var val = item[property];
        if (elements.indexOf(val) < 0) {
          filtered.push(item);
        }
      }
      return filtered;
    };
  })
  .config(function($routeProvider, USER_ROLES) {
    $routeProvider
      .when('/', {
        redirectTo: '/dashboard',
        reloadOnSearch: false,
        access: USER_ROLES.Guest
      })
      .when('/dashboard', {
        templateUrl: 'scripts/dashboard/dashboard.html',
        controller: 'DashboardController',
        name: 'Dashboard',
        reloadOnSearch: false,
        access: [USER_ROLES.Administrator, USER_ROLES.Kunde]
      })
      .when('/open/lastlieferplanungen', {
        templateUrl: 'scripts/open/lastlieferplanungen.html',
        controller: 'LastLieferplanungenController',
        name: 'LastLieferplanungen',
        access: [USER_ROLES.Guest, USER_ROLES.Administrator, USER_ROLES.Kunde]
      })
      .when('/login', {
        templateUrl: 'scripts/login/login.html',
        controller: 'LoginController',
        name: 'Login',
        access: USER_ROLES.Guest
      })
      .when('/passwd', {
        templateUrl: 'scripts/login/change_password.html',
        controller: 'LoginController',
        name: 'Passwortwechsel',
        access: [USER_ROLES.Administrator, USER_ROLES.Kunde]
      })
      .when('/logout', {
        templateUrl: 'scripts/login/logout.html',
        controller: 'LoginController',
        logout: true,
        name: 'Logout',
        access: USER_ROLES.Guest
      })
      .when('/forbidden', {
        templateUrl: 'scripts/login/forbidden.html',
        controller: 'LoginController',
        name: 'Forbidden',
        access: USER_ROLES.Guest
      })
      .when('/zugangaktivieren', {
        templateUrl: 'scripts/login/zugangaktivieren.html',
        controller: 'LoginController',
        name: 'Einladung',
        access: USER_ROLES.Guest
      })
      .when('/passwordreset', {
        templateUrl: 'scripts/login/passwordreset.html',
        controller: 'LoginController',
        name: 'PasswordReset',
        access: USER_ROLES.Guest
      })
      .otherwise({
        templateUrl: 'scripts/not-found.html',
        access: USER_ROLES.Guest
      });
  });
<commit_msg>Remove errbit reference<commit_after>'use strict';

var regexIso8601 =
  /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})\.(\d{1,})(Z|([\-+])(\d{2}):(\d{2}))?$/;
// Matches YYYY-MM-ddThh:mm:ss.sssZ where .sss is optional

function convertDateStringsToDates(input) {
  // Ignore things that aren't objects.
  if (typeof input !== 'object') {
    return input;
  }

  for (var key in input) {
    if (!input.hasOwnProperty(key)) {
      continue;
    }

    var value = input[key];
    var match;
    // Check for string properties which look like dates.
    if (typeof value === 'string' && (match = value.match(regexIso8601))) {
      var milliseconds = Date.parse(match[0]);
      if (!isNaN(milliseconds)) {
        input[key] = new Date(milliseconds);
      }
    } else if (typeof value === 'object') {
      // Recurse into object
      input[key] = convertDateStringsToDates(value);
    }
  }
  return input;
}
function addExtendedEnumValue(id, labelLong, labelShort, value) {
  return {
    id: id,
    label: {
      long: labelLong,
      short: labelShort
    },
    value: value
  };
}

/* This is a pseudo-function in order to enable gettext-extractor to find the translations that need to be done in the constants.
   As described in https://github.com/rubenv/angular-gettext/issues/67
*/
function gettext(string) {
  return string;
}

/**
 */
angular
  .module('openolitor-kundenportal', [
    'ngAnimate',
    'ngResource',
    'ngRoute',
    'ngSanitize',
    'ngTouch',
    'ngTable',
    'ngFileSaver',
    'ngCookies',
    'ngPasswordStrength',
    'ngMessages',
    'angular.filter',
    'ui.bootstrap',
    'ui.bootstrap.datetimepicker',
    'color.picker',
    'ipCookie',
    'frapontillo.bootstrap-switch',
    'gettext',
    'ngHamburger',
    'angularMoment',
    'ngFileUpload',
    'ngLodash',
    'angular-sortable-view',
    'ngclipboard',
    'mm.iban',
    'piwik'
  ])
  .constant('BUILD_NR', '@@BUILD_NR')
  .constant('LIEFEREINHEIT', {
    STUECK: addExtendedEnumValue('Stueck', gettext('Stück'), gettext('St.')),
    BUND: addExtendedEnumValue('Bund', gettext('Bund'), gettext('Bu.')),
    GRAMM: addExtendedEnumValue('Gramm', gettext('Gramm'), gettext('gr')),
    KILOGRAMM: addExtendedEnumValue('Kilogramm', gettext('Kilogramm'),
      gettext('kg')),
    LITER: addExtendedEnumValue('Liter', gettext('Liter'), gettext('l')),
    PORTION: addExtendedEnumValue('Portion', gettext('Portion'), gettext('Por.'))
  })
  .constant('USER_ROLES', {
    Guest: 'Guest',
    Administrator: 'Administrator',
    Kunde:'Kunde'
  })
  .run(function($rootScope, $location, $anchorScroll) {
    $rootScope.location = $location;
    $anchorScroll.yOffset = 50;

    $rootScope.$on('$routeChangeSuccess', function(newRoute, oldRoute) {
      if($location.hash()) $anchorScroll();
    });
  })
  .constant('WAEHRUNG', {
    CHF: addExtendedEnumValue('CHF', gettext('Schweizer Franken'), gettext(
      'CHF')),
    EUR: addExtendedEnumValue('EUR', gettext('Euro'), gettext('EUR')),
    USD: addExtendedEnumValue('USD', gettext('US Dollar'), gettext('USD')),
    GBP: addExtendedEnumValue('GBP', gettext('Britisches Pfund'), gettext(
      'GBP')),
    CAD: addExtendedEnumValue('CAD', gettext('Kanadischer Dollar'), gettext(
      'CAD'))
  })
  .service('appConfig', function() {
    var loaded = false;
    var configData = {
    };
    configData = getConfig();
    loaded = true;
    return {
      get: function() {
        return configData;
      },
      isLoaded: function() {
        return loaded;
      }
    };
  })
  .run(function(appConfig) {
    appConfig.get();
  })
  .factory('checkSize', ['$rootScope', '$window', function($rootScope, $window) {
    return function() {
      if ($window.innerWidth >= 1200) {
        $rootScope.tgState = true;
      }
    };
  }])
  .factory('convertDateStringsToDatesFct', function() {
    return function(input) {
      return convertDateStringsToDates(input);
    };
  })
  .config(['$provide', function($provide) {
    $provide.decorator('$exceptionHandler', ['$log', '$injector',
      function($log, $injector) {
        return function(exception) {
          // using the injector to retrieve services, otherwise circular dependency
          var alertService = $injector.get('alertService');
          alertService.addAlert('error', exception.message);
          // log error default style
          $log.error.apply($log, arguments);
        };
      }
    ]);
  }])
  .factory('msgBus', [
    '$rootScope',
    function($rootScope) {
      var msgBus = {};
      msgBus.emitMsg = function(msg) {
        $rootScope.$emit(msg.type, msg);
      };
      msgBus.onMsg = function(msg, scope, func) {
        var unbind = $rootScope.$on(msg, func);
        scope.$on('$destroy', unbind);
      };
      return msgBus;
    }
  ])
  .run(['ooClientMessageService', '$timeout', function(clientMessageService, $timeout) {
    $timeout(function() {
      console.log('Start clientMessageService');
      clientMessageService.start();
    }, 1000);
  }])
  .factory('loggedOutInterceptor', function($q, alertService) {
    return {
      responseError: function(rejection) {
        var status = rejection.status;
        if (status === 401) {
          alertService.removeAllAlerts();
          window.location = '#/logout';
          return;
        }
        return $q.reject(rejection);
      }
    };
  })
  .config(['$httpProvider', function($httpProvider) {
    $httpProvider.defaults.transformResponse.push(function(responseData) {
      return convertDateStringsToDates(responseData);
    });
  }])
  .filter('unsafe', [
        '$sce',
        function($sce) {
            return function(value) {
                return $sce.trustAsHtml(value);
            };
        }
    ])

  .filter('dateRange', function(moment) {
    function isMidnight(mom) {
      // The moment at midnight
      var mmtMidnight = mom.clone().startOf('day');

      // Difference in minutes == 0 => midnight
      return mom.diff(mmtMidnight, 'minutes') === 0;
    }

    return function(items, from, to, attribute) {
      if (!angular.isUndefined(items) && items.length > 0) {
        var toPlusOne = to;
        var momTo = moment(to);
        if (isMidnight(momTo)) {
          toPlusOne = momTo.add(1, 'days');
        }
        var result = [];
        for (var i = 0; i < items.length; i++) {
          var itemDate = items[i][attribute];
          if (!angular.isUndefined(attribute)) {
            itemDate = items[i][attribute];
          }
          if (angular.isUndefined(to) && angular.isUndefined(from)) {
            result.push(items[i]);
          } else if (angular.isUndefined(to) && itemDate >= from) {
            result.push(items[i]);
          } else if (angular.isUndefined(from) && itemDate <= toPlusOne) {
            result.push(items[i]);
          } else if (itemDate >= from && itemDate <= toPlusOne) {
            result.push(items[i]);
          }
        }
        return result;
      }
    };
  })
  .filter('fromNow', function(moment) {
    return function(input) {
      return moment(input).fromNow();
    };
  })
  .config(['$httpProvider', function($httpProvider) {
    $httpProvider.interceptors.push('loggedOutInterceptor');
  }])
  .config(['$locationProvider', function($locationProvider) {
    $locationProvider.hashPrefix('');
  }])
  .config(['$qProvider', function ($qProvider) {
    $qProvider.errorOnUnhandledRejections(false);
  }])
  .filter('notIn', function() {
    return function(items, property, elements) {
      var filtered = [];
      if (!items) {
        return filtered;
      }
      for (var i = 0; i < items.length; i++) {
        var item = items[i];
        var val = item[property];
        if (elements.indexOf(val) < 0) {
          filtered.push(item);
        }
      }
      return filtered;
    };
  })
  .config(function($routeProvider, USER_ROLES) {
    $routeProvider
      .when('/', {
        redirectTo: '/dashboard',
        reloadOnSearch: false,
        access: USER_ROLES.Guest
      })
      .when('/dashboard', {
        templateUrl: 'scripts/dashboard/dashboard.html',
        controller: 'DashboardController',
        name: 'Dashboard',
        reloadOnSearch: false,
        access: [USER_ROLES.Administrator, USER_ROLES.Kunde]
      })
      .when('/open/lastlieferplanungen', {
        templateUrl: 'scripts/open/lastlieferplanungen.html',
        controller: 'LastLieferplanungenController',
        name: 'LastLieferplanungen',
        access: [USER_ROLES.Guest, USER_ROLES.Administrator, USER_ROLES.Kunde]
      })
      .when('/login', {
        templateUrl: 'scripts/login/login.html',
        controller: 'LoginController',
        name: 'Login',
        access: USER_ROLES.Guest
      })
      .when('/passwd', {
        templateUrl: 'scripts/login/change_password.html',
        controller: 'LoginController',
        name: 'Passwortwechsel',
        access: [USER_ROLES.Administrator, USER_ROLES.Kunde]
      })
      .when('/logout', {
        templateUrl: 'scripts/login/logout.html',
        controller: 'LoginController',
        logout: true,
        name: 'Logout',
        access: USER_ROLES.Guest
      })
      .when('/forbidden', {
        templateUrl: 'scripts/login/forbidden.html',
        controller: 'LoginController',
        name: 'Forbidden',
        access: USER_ROLES.Guest
      })
      .when('/zugangaktivieren', {
        templateUrl: 'scripts/login/zugangaktivieren.html',
        controller: 'LoginController',
        name: 'Einladung',
        access: USER_ROLES.Guest
      })
      .when('/passwordreset', {
        templateUrl: 'scripts/login/passwordreset.html',
        controller: 'LoginController',
        name: 'PasswordReset',
        access: USER_ROLES.Guest
      })
      .otherwise({
        templateUrl: 'scripts/not-found.html',
        access: USER_ROLES.Guest
      });
  });
<|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc overview
 * @name grafterizerApp
 * @description
 * # Grafterizer
 *
 * This file contains the declaration of the application dependencies,
 * and the modules settings.
 *
 * The theme is defined here, as well as the routing (using a state machine).
 */
angular
  .module('grafterizerApp', [
    'ui.router',
    'ngMaterial',
    'ngAnimate',
    'ngCookies',
    'ngResource',
    'ngRoute',
    'ngSanitize',
    'ngTouch',
    'ngFileUpload',
    'ui.grid',
    'ui.grid.autoResize',
    'angular-loading-bar',
    'ncy-angular-breadcrumb',
    'angularMoment',
    'as.sortable',
    'ui.codemirror',
    'ui.grid.selection',
    'ui.grid.edit',
    'ui.grid.resizeColumns',
    'ui.grid.exporter',
    'ngMessages',
    'RecursionHelper',
    'vAccordion'
])
  .config(function(
    ontotextAPIProvider,
    PipeServiceProvider,
    $mdThemingProvider,
    $stateProvider,
    $urlRouterProvider,
    $urlMatcherFactoryProvider,
    cfpLoadingBarProvider,
    $breadcrumbProvider,
    $locationProvider,
    $provide) {

    var developmentMode = window.location.origin === 'http://localhost:9000';

    if (typeof Raven !== 'undefined') {

      Raven.config('https://cdec3ae0110344cabdd5a242d2247d07@grafterizer.datagraft.net/5', {}).install();

      $provide.decorator('$exceptionHandler', ['$delegate', function($delegate) {
        return function(exception, cause) {
          $delegate(exception, cause);
          if (typeof Raven !== 'undefined') {
            Raven.captureException(exception, { cause: cause });
          }
        };
      }]);

    } else {
      window.Raven = {
        captureEvents: console.log,
        captureMessage: console.log
      };
    }

    ontotextAPIProvider.setEndpoint('https://api.datagraft.net');

    PipeServiceProvider.setEndpoint(
      developmentMode ?
      'https://grafterizer.datagraft.net/backend'
      : '/backend');

    var urlBase = $urlRouterProvider.otherwise('/transformations/new');

    sessionStorage.localClassAndProperty = JSON.stringify([]);
    sessionStorage.localVocabulary = JSON.stringify([]);

    if (!window.navigator.device && !developmentMode) {
      $locationProvider.html5Mode(true);
    }

    // Workaround for https://github.com/angular-ui/ui-router/issues/1119
    var valToString = function(val) {
      return val !== null ? val.toString() : val;
    };

    $urlMatcherFactoryProvider.type('nonURIEncoded', {
      encode: valToString,
      decode: valToString,
      is: function() {
        return true;
      }
    });

    $stateProvider
      .state('about', {
        url: '/about',
        views: {
          main: {
            templateUrl: 'views/about.html'
          }
        },
        ncyBreadcrumb: {
          label: 'About'
        }
      })
      .state('transformations', {
        url: '/transformations',
        views: {
          main: {
            templateUrl: 'views/transformations.html',
            controller: 'TransformationsCtrl'
          }
        },
        ncyBreadcrumb: {
          label: 'Data transformations'
        }
      })
      .state('transformations.new', {
        url: '/new',
        views: {
          'main@': {
            controller: 'TransformationNewCtrl',
            templateUrl: 'views/transformation.html'
          },
          'actions@': {
            templateUrl: 'views/actions.html',
            controller: 'ActionsCtrl'
          }
        },
        ncyBreadcrumb: {
          label: '{{document.title || "New transformation"}}'
        }
      })
      .state('transformations.transformation', {
        url: '/{id:nonURIEncoded}',
        views: {
          'main@': {
            templateUrl: 'views/transformation.html',
            controller: 'TransformationCtrl'
          },
          'actions@': {
            templateUrl: 'views/actions.html',
            controller: 'ActionsCtrl'
          }
        },
        ncyBreadcrumb: {
          label: '{{document.title || "File "+id}}'
        }
      })
      .state('transformations.transformation.preview', {
        url: '^/transform/{id:nonURIEncoded}',
        params: {
          distribution: null
        },
        views: {
          preview: {
            templateUrl: 'views/preview.html',
            controller: 'PreviewCtrl'
          }
        },
        ncyBreadcrumb: {
          label: '{{(selectedDistribution || "Preview")|beautifyUri}}'
        }
      })
      .state('datasets', {
        url: '/datasets',
        views: {
          'main@': {
            templateUrl: 'views/datasets.html',
            controller: 'DatasetsCtrl'
          }
        },
        ncyBreadcrumb: {
          label: 'Datasets'
        }
      })
      .state('datasets.dataset', {
        url: '/datasets/{id:nonURIEncoded}',
        views: {
          'main@': {
            templateUrl: 'views/dataset.html',
            controller: 'DatasetCtrl'
          }
        },
        ncyBreadcrumb: {
          label: '{{document.title || id}}'
        }
      })
      .state('distribution', {
        url: '/distribution/{id:nonURIEncoded}',
        views: {
          'main@': {
            templateUrl: 'views/distribution.html',
            controller: 'DistributionCtrl'
          }
        },
        ncyBreadcrumb: {
          label: '{{document.title || id}}'
        }
      })
      .state('embedded', {
        url: '/embedded',
        views: {
          main: true
        },
        ncyBreadcrumb: {
          label: 'Loading'
        }
      })
      .state('apikey', {
        url: '/apiKey',
        views: {
          main: {
            templateUrl: 'views/apikey.html',
            controller: 'ApikeyCtrl'
          }
        },
        ncyBreadcrumb: {
          label: 'API Key'
        }
      })
      .state('help', {
        url: '/help',
        views: {
          main: {
            templateUrl: 'views/help.html',
            controller: 'HelpCtrl'
          }
        },
        ncyBreadcrumb: {
          label: 'Help'
        }
      });

    // The spinner is a bit too much
    cfpLoadingBarProvider.includeSpinner = false;

    // Breadcrumb settings using material-style
    $breadcrumbProvider.setOptions({
      template: '
' +
        '
' +
        '{{step.ncyBreadcrumbLabel}}' +
        '{{step.ncyBreadcrumbLabel}}' +
        '
' +
        '
'
    });

    // Theme settings

    $mdThemingProvider.definePalette('customPrimary', {
      50: '#a9b2d7',
      100: '#97a2cf',
      200: '#8693c6',
      300: '#7583be',
      400: '#6374b6',
      500: '#5264AE',
      600: '#495a9d',
      700: '#41508c',
      800: '#39467a',
      900: '#313c69',
      A100: '#bac1df',
      A200: '#ccd1e7',
      A400: '#dde0ef',
      A700: '#293258',
      contrastDefaultColor: 'light'
    });

    $mdThemingProvider.definePalette('customAccent', {
      50: '#333333',
      100: '#333333',
      200: '#333333',
      300: '#f7fcfc',
      400: '#e4f4f5',
      500: '#EEEEEE',
      600: '#bfe6e7',
      700: '#addee0',
      800: '#9ad7d9',
      900: '#88cfd2',
      A100: '#EEEEEE',
      A200: '#EEEEEE',
      A400: '#EEEEEE',
      A700: '#75c8cb',
      contrastDefaultColor: 'dark'
    });

    $mdThemingProvider.definePalette('dapaasPrimary', {
      50: '#67ffa0',
      100: '#4eff90',
      200: '#34ff80',
      300: '#1bff70',
      400: '#01ff60',
      500: '#00E756',
      600: '#00cd4c',
      700: '#00b443',
      800: '#009a3a',
      900: '#008130',
      A100: '#81ffb0',
      A200: '#9affc0',
      A400: '#b4ffd0',
      A700: '#006727',
      contrastDefaultColor: 'dark'
    });

    $mdThemingProvider.theme('default')
      .primaryPalette('customPrimary')
      .accentPalette('blue');

    // .primaryPalette('dapaasPrimary')
    // .accentPalette('customAccent');

    // JSEDN is too restrictive by default on valid symbols
    jsedn.Symbol.prototype.validRegex = new RegExp(/.*/);
  }).run(function(datagraftPostMessage, apiKeyService, $state, $rootScope) {
    datagraftPostMessage.setup();

    // Mobile detection (as Leaflet 1.0 does)
    var ua = navigator.userAgent.toLowerCase();
    $rootScope.isMobile = typeof orientation !== 'undefined' || ua.indexOf('mobile') !== -1;

    if (!apiKeyService.hasKeyPass()) {
      window.setTimeout(function() {
        if (!apiKeyService.hasKeyPass()) {
          $state.go('apikey');
        }
      }, 2000);
    }
  });
<commit_msg>Report the development errors in a separate Sentry project<commit_after>'use strict';

/**
 * @ngdoc overview
 * @name grafterizerApp
 * @description
 * # Grafterizer
 *
 * This file contains the declaration of the application dependencies,
 * and the modules settings.
 *
 * The theme is defined here, as well as the routing (using a state machine).
 */
angular
  .module('grafterizerApp', [
    'ui.router',
    'ngMaterial',
    'ngAnimate',
    'ngCookies',
    'ngResource',
    'ngRoute',
    'ngSanitize',
    'ngTouch',
    'ngFileUpload',
    'ui.grid',
    'ui.grid.autoResize',
    'angular-loading-bar',
    'ncy-angular-breadcrumb',
    'angularMoment',
    'as.sortable',
    'ui.codemirror',
    'ui.grid.selection',
    'ui.grid.edit',
    'ui.grid.resizeColumns',
    'ui.grid.exporter',
    'ngMessages',
    'RecursionHelper',
    'vAccordion'
])
  .config(function(
    ontotextAPIProvider,
    PipeServiceProvider,
    $mdThemingProvider,
    $stateProvider,
    $urlRouterProvider,
    $urlMatcherFactoryProvider,
    cfpLoadingBarProvider,
    $breadcrumbProvider,
    $locationProvider,
    $provide) {

    var developmentMode = window.location.origin === 'http://localhost:9000';

    if (typeof Raven !== 'undefined') {

      var sentryPath = developmentMode ?
        'http://76c7f69b67a649619dbf7a9f679efb96@sentry.datagraft.net/6'
        : 'https://cdec3ae0110344cabdd5a242d2247d07@grafterizer.datagraft.net/5';

      Raven.config(sentryPath, {}).install();

      $provide.decorator('$exceptionHandler', ['$delegate', function($delegate) {
        return function(exception, cause) {
          $delegate(exception, cause);
          if (typeof Raven !== 'undefined') {
            Raven.captureException(exception, { cause: cause });
          }
        };
      }]);

    } else {
      window.Raven = {
        captureEvents: console.log,
        captureMessage: console.log
      };
    }

    ontotextAPIProvider.setEndpoint('https://api.datagraft.net');

    PipeServiceProvider.setEndpoint(
      developmentMode ?
      'https://grafterizer.datagraft.net/backend'
      : '/backend');

    var urlBase = $urlRouterProvider.otherwise('/transformations/new');

    sessionStorage.localClassAndProperty = JSON.stringify([]);
    sessionStorage.localVocabulary = JSON.stringify([]);

    if (!window.navigator.device && !developmentMode) {
      $locationProvider.html5Mode(true);
    }

    // Workaround for https://github.com/angular-ui/ui-router/issues/1119
    var valToString = function(val) {
      return val !== null ? val.toString() : val;
    };

    $urlMatcherFactoryProvider.type('nonURIEncoded', {
      encode: valToString,
      decode: valToString,
      is: function() {
        return true;
      }
    });

    $stateProvider
      .state('about', {
        url: '/about',
        views: {
          main: {
            templateUrl: 'views/about.html'
          }
        },
        ncyBreadcrumb: {
          label: 'About'
        }
      })
      .state('transformations', {
        url: '/transformations',
        views: {
          main: {
            templateUrl: 'views/transformations.html',
            controller: 'TransformationsCtrl'
          }
        },
        ncyBreadcrumb: {
          label: 'Data transformations'
        }
      })
      .state('transformations.new', {
        url: '/new',
        views: {
          'main@': {
            controller: 'TransformationNewCtrl',
            templateUrl: 'views/transformation.html'
          },
          'actions@': {
            templateUrl: 'views/actions.html',
            controller: 'ActionsCtrl'
          }
        },
        ncyBreadcrumb: {
          label: '{{document.title || "New transformation"}}'
        }
      })
      .state('transformations.transformation', {
        url: '/{id:nonURIEncoded}',
        views: {
          'main@': {
            templateUrl: 'views/transformation.html',
            controller: 'TransformationCtrl'
          },
          'actions@': {
            templateUrl: 'views/actions.html',
            controller: 'ActionsCtrl'
          }
        },
        ncyBreadcrumb: {
          label: '{{document.title || "File "+id}}'
        }
      })
      .state('transformations.transformation.preview', {
        url: '^/transform/{id:nonURIEncoded}',
        params: {
          distribution: null
        },
        views: {
          preview: {
            templateUrl: 'views/preview.html',
            controller: 'PreviewCtrl'
          }
        },
        ncyBreadcrumb: {
          label: '{{(selectedDistribution || "Preview")|beautifyUri}}'
        }
      })
      .state('datasets', {
        url: '/datasets',
        views: {
          'main@': {
            templateUrl: 'views/datasets.html',
            controller: 'DatasetsCtrl'
          }
        },
        ncyBreadcrumb: {
          label: 'Datasets'
        }
      })
      .state('datasets.dataset', {
        url: '/datasets/{id:nonURIEncoded}',
        views: {
          'main@': {
            templateUrl: 'views/dataset.html',
            controller: 'DatasetCtrl'
          }
        },
        ncyBreadcrumb: {
          label: '{{document.title || id}}'
        }
      })
      .state('distribution', {
        url: '/distribution/{id:nonURIEncoded}',
        views: {
          'main@': {
            templateUrl: 'views/distribution.html',
            controller: 'DistributionCtrl'
          }
        },
        ncyBreadcrumb: {
          label: '{{document.title || id}}'
        }
      })
      .state('embedded', {
        url: '/embedded',
        views: {
          main: true
        },
        ncyBreadcrumb: {
          label: 'Loading'
        }
      })
      .state('apikey', {
        url: '/apiKey',
        views: {
          main: {
            templateUrl: 'views/apikey.html',
            controller: 'ApikeyCtrl'
          }
        },
        ncyBreadcrumb: {
          label: 'API Key'
        }
      })
      .state('help', {
        url: '/help',
        views: {
          main: {
            templateUrl: 'views/help.html',
            controller: 'HelpCtrl'
          }
        },
        ncyBreadcrumb: {
          label: 'Help'
        }
      });

    // The spinner is a bit too much
    cfpLoadingBarProvider.includeSpinner = false;

    // Breadcrumb settings using material-style
    $breadcrumbProvider.setOptions({
      template: '
' +
        '
' +
        '{{step.ncyBreadcrumbLabel}}' +
        '{{step.ncyBreadcrumbLabel}}' +
        '
' +
        '
'
    });

    // Theme settings

    $mdThemingProvider.definePalette('customPrimary', {
      50: '#a9b2d7',
      100: '#97a2cf',
      200: '#8693c6',
      300: '#7583be',
      400: '#6374b6',
      500: '#5264AE',
      600: '#495a9d',
      700: '#41508c',
      800: '#39467a',
      900: '#313c69',
      A100: '#bac1df',
      A200: '#ccd1e7',
      A400: '#dde0ef',
      A700: '#293258',
      contrastDefaultColor: 'light'
    });

    $mdThemingProvider.definePalette('customAccent', {
      50: '#333333',
      100: '#333333',
      200: '#333333',
      300: '#f7fcfc',
      400: '#e4f4f5',
      500: '#EEEEEE',
      600: '#bfe6e7',
      700: '#addee0',
      800: '#9ad7d9',
      900: '#88cfd2',
      A100: '#EEEEEE',
      A200: '#EEEEEE',
      A400: '#EEEEEE',
      A700: '#75c8cb',
      contrastDefaultColor: 'dark'
    });

    $mdThemingProvider.definePalette('dapaasPrimary', {
      50: '#67ffa0',
      100: '#4eff90',
      200: '#34ff80',
      300: '#1bff70',
      400: '#01ff60',
      500: '#00E756',
      600: '#00cd4c',
      700: '#00b443',
      800: '#009a3a',
      900: '#008130',
      A100: '#81ffb0',
      A200: '#9affc0',
      A400: '#b4ffd0',
      A700: '#006727',
      contrastDefaultColor: 'dark'
    });

    $mdThemingProvider.theme('default')
      .primaryPalette('customPrimary')
      .accentPalette('blue');

    // .primaryPalette('dapaasPrimary')
    // .accentPalette('customAccent');

    // JSEDN is too restrictive by default on valid symbols
    jsedn.Symbol.prototype.validRegex = new RegExp(/.*/);
  }).run(function(datagraftPostMessage, apiKeyService, $state, $rootScope) {
    datagraftPostMessage.setup();

    // Mobile detection (as Leaflet 1.0 does)
    var ua = navigator.userAgent.toLowerCase();
    $rootScope.isMobile = typeof orientation !== 'undefined' || ua.indexOf('mobile') !== -1;

    if (!apiKeyService.hasKeyPass()) {
      window.setTimeout(function() {
        if (!apiKeyService.hasKeyPass()) {
          $state.go('apikey');
        }
      }, 2000);
    }
  });
<|endoftext|>