<commit_before>/* eslint-disable max-statements */

// Usage:
//   var en = new Entry(rawEntry, entries)

var config = window.tresdb.config;
var locations = require('../../../../stores/locations');

var emitter = require('component-emitter');
var urljoin = require('url-join');
var marked = require('marked');

module.exports = function (rawEntry, entries) {
  // Parameters:
  //   rawEntry
  //     plain content entry object
  //   entries
  //     EntriesModel instance. Work as a parent.

  if (typeof rawEntry !== 'object') {
    throw new Error('Missing or invalid rawEntry object.');
  }

  if (typeof entries !== 'object') {
    throw new Error('Missing or invalid entries model.');
  }

  if (rawEntry.type !== 'location_entry') {
    throw new Error('Wrong entry type for location_entry: ' + rawEntry.type);
  }

  var self = this;
  emitter(self);

  entries.on('location_entry_changed', function (ev) {
    // Skip events of other entries
    if (ev.data.entryId !== rawEntry._id) {
      return;
    }

    rawEntry.data.markdown = ev.data.newMarkdown;
    rawEntry.data.isVisit = ev.data.newIsVisit;
    rawEntry.data.filepath = ev.data.newFilepath;
    rawEntry.data.mimetype = ev.data.newMimetype;
    rawEntry.data.thumbfilepath = ev.data.newThumbfilepath;
    rawEntry.data.thumbmimetype = ev.data.newThumbmimetype;

    // Emit for view to react by rerendering.
    self.emit(ev.type, ev);
  });

  entries.on('location_entry_comment_created', function (ev) {
    // Skip events of other entries
    if (ev.data.entryId !== rawEntry._id) {
      return;
    }

    if (!rawEntry.comments) {
      rawEntry.comments = [];
    }

    rawEntry.comments.push({
      id: ev.data.commentId,
      time: ev.time,
      user: ev.user,
      message: ev.data.message,
    });

    // Emit for the view to react
    self.emit(ev.type, ev);
  });

  entries.on('location_entry_comment_changed', function (ev) {
    // Skip events of other entries
    if (ev.data.entryId !== rawEntry._id) {
      return;
    }

    if (!rawEntry.comments) {
      // Weird state. But let us be sure.
      rawEntry.comments = [];
    }

    // Update a comment.
    rawEntry.comments = rawEntry.comments.map(function (comm) {
      if (ev.data.commentId === comm.id) {
        return Object.assign({}, comm, {
          message: ev.data.newMessage,
        });
      }
      return comm;
    });

    // Emit for the view to react
    self.emit(ev.type, ev);
  });

  entries.on('location_entry_comment_removed', function (ev) {
    // Skip events of other entries
    if (ev.data.entryId !== rawEntry._id) {
      return;
    }

    if (!rawEntry.comments) {
      // No need to update anything
      return;
    }

    // Filter out the removed comment.
    rawEntry.comments = rawEntry.comments.filter(function (comm) {
      return ev.data.commentId !== comm.id;
    });

    // Emit for the view to react
    self.emit(ev.type, ev);
  });

  // Public methods

  self.change = function (form, callback) {
    // Parameters:
    //   form
    //     jQuery instance of edit form

    var lid = rawEntry.locationId;
    var eid = rawEntry._id;
    locations.changeEntry(lid, eid, form, callback);
  };

  self.getId = function () {
    return rawEntry._id;
  };

  self.getType = function () {
    return rawEntry.type;
  };

  self.getTime = function () {
    return rawEntry.time;
  };

  self.getUserName = function () {
    return rawEntry.user;
  };

  self.getLocation = function () {
    // Return Location.Model instance
    return entries.getLocation();
  };

  self.getLocationId = function () {
    return String(rawEntry.locationId);
  };

  self.hasMarkdown = function () {
    return (typeof rawEntry.data.markdown === 'string');
  };

  self.getMarkdown = function () {
    // Null if no markdown
    return rawEntry.data.markdown;
  };

  self.getMarkdownHTML = function () {
    if (!self.hasMarkdown()) {
      return null;
    }

    return marked(rawEntry.data.markdown, { sanitize: true });
  };

  self.isVisit = function () {
    return rawEntry.data.isVisit;
  };

  self.hasFile = function () {
    return (typeof rawEntry.data.filepath === 'string');
  };

  self.hasImage = function () {
    // Return true if attachment is an image
    var HEAD = 6;
    if (self.hasFile()) {
      return (rawEntry.data.mimetype.substr(0, HEAD) === 'image/');
    }
    return false;
  };

  self.getComments = function () {
    if (rawEntry.comments) {
      return rawEntry.comments;
    }
    return [];
  };

  self.getFileName = function () {
    // Get filename part of attachment file path.
    // Null if no file.
    //
    // For example if filepath === '/foo/bar/baz.jpg'
    // then getFileName() === 'baz.jpg'
    var p = rawEntry.data.filepath;

    if (self.hasFile()) {
      return p.substr(p.lastIndexOf('/') + 1);
    }
    return null;
  };

  self.getUrl = function () {
    if (self.hasFile()) {
      return urljoin(config.uploadUrl, rawEntry.data.filepath);
    }
    return null;
  };

  self.getMimeType = function () {
    // Return null if no file
    return rawEntry.data.mimetype;
  };

  self.getThumbUrl = function () {
    if (self.hasFile()) {
      return urljoin(config.uploadUrl, rawEntry.data.thumbfilepath);
    }
    return null;
  };

  self.getThumbMimeType = function () {
    // Return null if no file
    return rawEntry.data.thumbmimetype;
  };

  self.remove = function (callback) {
    // Remove entry from the backend
    var lid = rawEntry.locationId;
    var eid = rawEntry._id;
    locations.removeEntry(lid, eid, callback);
  };

  self.createComment = function (message, callback) {
    var lid = rawEntry.locationId;
    var eid = rawEntry._id;
    locations.createComment(lid, eid, message, callback);
  };
};
<commit_msg>Sanitize entry markdown<commit_after>/* eslint-disable max-statements */

// Usage:
//   var en = new Entry(rawEntry, entries)

var config = window.tresdb.config;
var locations = require('../../../../stores/locations');

var emitter = require('component-emitter');
var urljoin = require('url-join');
var marked = require('marked');
var dompurify = require('dompurify');

module.exports = function (rawEntry, entries) {
  // Parameters:
  //   rawEntry
  //     plain content entry object
  //   entries
  //     EntriesModel instance. Work as a parent.

  if (typeof rawEntry !== 'object') {
    throw new Error('Missing or invalid rawEntry object.');
  }

  if (typeof entries !== 'object') {
    throw new Error('Missing or invalid entries model.');
  }

  if (rawEntry.type !== 'location_entry') {
    throw new Error('Wrong entry type for location_entry: ' + rawEntry.type);
  }

  var self = this;
  emitter(self);

  entries.on('location_entry_changed', function (ev) {
    // Skip events of other entries
    if (ev.data.entryId !== rawEntry._id) {
      return;
    }

    rawEntry.data.markdown = ev.data.newMarkdown;
    rawEntry.data.isVisit = ev.data.newIsVisit;
    rawEntry.data.filepath = ev.data.newFilepath;
    rawEntry.data.mimetype = ev.data.newMimetype;
    rawEntry.data.thumbfilepath = ev.data.newThumbfilepath;
    rawEntry.data.thumbmimetype = ev.data.newThumbmimetype;

    // Emit for view to react by rerendering.
    self.emit(ev.type, ev);
  });

  entries.on('location_entry_comment_created', function (ev) {
    // Skip events of other entries
    if (ev.data.entryId !== rawEntry._id) {
      return;
    }

    if (!rawEntry.comments) {
      rawEntry.comments = [];
    }

    rawEntry.comments.push({
      id: ev.data.commentId,
      time: ev.time,
      user: ev.user,
      message: ev.data.message,
    });

    // Emit for the view to react
    self.emit(ev.type, ev);
  });

  entries.on('location_entry_comment_changed', function (ev) {
    // Skip events of other entries
    if (ev.data.entryId !== rawEntry._id) {
      return;
    }

    if (!rawEntry.comments) {
      // Weird state. But let us be sure.
      rawEntry.comments = [];
    }

    // Update a comment.
    rawEntry.comments = rawEntry.comments.map(function (comm) {
      if (ev.data.commentId === comm.id) {
        return Object.assign({}, comm, {
          message: ev.data.newMessage,
        });
      }
      return comm;
    });

    // Emit for the view to react
    self.emit(ev.type, ev);
  });

  entries.on('location_entry_comment_removed', function (ev) {
    // Skip events of other entries
    if (ev.data.entryId !== rawEntry._id) {
      return;
    }

    if (!rawEntry.comments) {
      // No need to update anything
      return;
    }

    // Filter out the removed comment.
    rawEntry.comments = rawEntry.comments.filter(function (comm) {
      return ev.data.commentId !== comm.id;
    });

    // Emit for the view to react
    self.emit(ev.type, ev);
  });

  // Public methods

  self.change = function (form, callback) {
    // Parameters:
    //   form
    //     jQuery instance of edit form

    var lid = rawEntry.locationId;
    var eid = rawEntry._id;
    locations.changeEntry(lid, eid, form, callback);
  };

  self.getId = function () {
    return rawEntry._id;
  };

  self.getType = function () {
    return rawEntry.type;
  };

  self.getTime = function () {
    return rawEntry.time;
  };

  self.getUserName = function () {
    return rawEntry.user;
  };

  self.getLocation = function () {
    // Return Location.Model instance
    return entries.getLocation();
  };

  self.getLocationId = function () {
    return String(rawEntry.locationId);
  };

  self.hasMarkdown = function () {
    return (typeof rawEntry.data.markdown === 'string');
  };

  self.getMarkdown = function () {
    // Null if no markdown
    return rawEntry.data.markdown;
  };

  self.getMarkdownHTML = function () {
    if (!self.hasMarkdown()) {
      return null;
    }

    var dangerousHTML = marked(rawEntry.data.markdown);
    return dompurify.sanitize(dangerousHTML);
  };

  self.isVisit = function () {
    return rawEntry.data.isVisit;
  };

  self.hasFile = function () {
    return (typeof rawEntry.data.filepath === 'string');
  };

  self.hasImage = function () {
    // Return true if attachment is an image
    var HEAD = 6;
    if (self.hasFile()) {
      return (rawEntry.data.mimetype.substr(0, HEAD) === 'image/');
    }
    return false;
  };

  self.getComments = function () {
    if (rawEntry.comments) {
      return rawEntry.comments;
    }
    return [];
  };

  self.getFileName = function () {
    // Get filename part of attachment file path.
    // Null if no file.
    //
    // For example if filepath === '/foo/bar/baz.jpg'
    // then getFileName() === 'baz.jpg'
    var p = rawEntry.data.filepath;

    if (self.hasFile()) {
      return p.substr(p.lastIndexOf('/') + 1);
    }
    return null;
  };

  self.getUrl = function () {
    if (self.hasFile()) {
      return urljoin(config.uploadUrl, rawEntry.data.filepath);
    }
    return null;
  };

  self.getMimeType = function () {
    // Return null if no file
    return rawEntry.data.mimetype;
  };

  self.getThumbUrl = function () {
    if (self.hasFile()) {
      return urljoin(config.uploadUrl, rawEntry.data.thumbfilepath);
    }
    return null;
  };

  self.getThumbMimeType = function () {
    // Return null if no file
    return rawEntry.data.thumbmimetype;
  };

  self.remove = function (callback) {
    // Remove entry from the backend
    var lid = rawEntry.locationId;
    var eid = rawEntry._id;
    locations.removeEntry(lid, eid, callback);
  };

  self.createComment = function (message, callback) {
    var lid = rawEntry.locationId;
    var eid = rawEntry._id;
    locations.createComment(lid, eid, message, callback);
  };
};
<|endoftext|>


<commit_before>Router.configure({
    layoutTemplate: 'ApplicationLayout'
});

Router.route('/', {
    controller: Meteor.zion.home.controller
});

Router.route('/login', {
    name: 'login',
    controller: Meteor.zion.login.controller
});

Router.route('/television', {
    name: 'television',
    controller: Meteor.zion.television.controller
});

Router.route('/newspaper', {
    name: 'newspaper',
    controller: Meteor.zion.newspaper.controller
});

Router.route('/portal', {
    name: 'portal',
    controller: Meteor.zion.portal.controller
});

Router.route('/boafm', {
    name: 'boafm',
    controller: Meteor.zion.boafm.radio.controller
});
Router.route('/fmmn', {
    name: 'fmmn',
    controller: Meteor.zion.boafm.radio.controller
});<commit_msg>Routers<commit_after><|endoftext|>


<commit_before>import { Table, Modal, Header, Image, Container, Button } from 'semantic-ui-react';
import React from 'react';
import ReplyFormModal from './ReplyFormModal';

const MessagesTable = ({ allMessages, convertTime }) => {
  return (

Subject

Sender

Notes

        {
        allMessages.map(message =>
          <Modal
            key={message.id}
            size="small"
            trigger={

                  {message.title}
                  {`Received about ${convertTime(message.createdAt)}`}

{`${message.sender.firstName} ${message.sender.lastName}`}

None

            }
          >
            <Modal.Header>{message.title}</Modal.Header>
            <Modal.Content image>
              <Image wrapped size="small" src="./client/src/assets/half-raptor.png" />
              <Modal.Description>
                {message.title}

{`From: ${message.user.firstName} ${message.user.lastName}`}

{message.body}

              </Modal.Description>
            </Modal.Content>
            <Modal.Actions>
              <Button>
                <ReplyFormModal />
              </Button>
            </Modal.Actions>
          </Modal>,
          )
        }

  );
};

MessagesTable.propTypes = {
  allMessages: React.PropTypes.array.isRequired,
  convertTime: React.PropTypes.func.isRequired,
};

export default MessagesTable;
<commit_msg>Pass onSubmit and onChange to ReplyFormModal<commit_after>import { Table, Modal, Header, Image, Button } from 'semantic-ui-react';
import React from 'react';
import ReplyFormModal from './ReplyFormModal';

const MessagesTable = ({ allMessages, convertTime, onChange, onSubmit }) =>

Subject

Sender

Notes

      {
      allMessages.map(message =>
        <Modal
          key={message.id}
          size="small"
          trigger={

                {message.title}
                {`Received about ${convertTime(message.createdAt)}`}

{`${message.sender.firstName} ${message.sender.lastName}`}

None

          }
        >
          <Modal.Header>{message.title}</Modal.Header>
          <Modal.Content image>
            <Image wrapped size="small" src="./client/src/assets/half-raptor.png" />
            <Modal.Description>
              {message.title}

{`From: ${message.user.firstName} ${message.user.lastName}`}

{message.body}

            </Modal.Description>
          </Modal.Content>
          <Modal.Actions>
            <Button>
              <ReplyFormModal
                onChange={onChange}
                onSubmit={onSubmit}
                listingId={message.post.id}
                userId={message.user.id}
              />
            </Button>
          </Modal.Actions>
        </Modal>,
        )
      }

;

MessagesTable.propTypes = {
  allMessages: React.PropTypes.array.isRequired,
  convertTime: React.PropTypes.func.isRequired,
  onChange: React.PropTypes.func.isRequired,
  onSubmit: React.PropTypes.func.isRequired,
};

export default MessagesTable;
<|endoftext|>


<commit_before>import { createSelector } from 'reselect';
import micromatch from 'micromatch';
import fuzzy from 'fuzzy';
import _ from 'underscore';

import Utils from '../utils';

const getRequestsAPI = (state) => state.api.requests;
const getUserAPI = (state) => state.api.user;
const getSearchFilter = (state) => state.ui.requestsPage;

function findRequestIds(requests) {
  return _.map(requests, (r) => {
    return _.extend({}, r, {id: r.request ? r.request.id : r.requestId});
  });
}

export const getStarred = (state) => new Set(state.ui.starred);

export const getStarredRequests = createSelector(
  [getStarred, getRequestsAPI],
  (starredData, requestsAPI) => {
    const requests = findRequestIds(requestsAPI.data);
    return requests.filter((r) => starredData.has(r.request.id));
  }
);

export const getUserRequests = createSelector(
  [getUserAPI, getRequestsAPI],
  (userAPI, requestsAPI) => {
    const deployUserTrimmed = Utils.maybe(
      userAPI.data,
      ['user', 'email'],
      ''
    ).split('@')[0];

    const requests = findRequestIds(requestsAPI.data);

    return requests.filter((r) => {
      const activeDeployUser = Utils.maybe(
        r,
        ['requestDeployState', 'activeDeploy', 'user']
      );

      if (activeDeployUser) {
        const activeDeployUserTrimmed = activeDeployUser.split('@')[0];
        if (deployUserTrimmed === activeDeployUserTrimmed) {
          return true;
        }
      }

      const requestOwners = r.owners;
      if (requestOwners === undefined) {
        return false;
      }

      for (const owner of requestOwners) {
        if (deployUserTrimmed === owner.split('@')[0]) {
          return true;
        }
      }

      return false;
    });
  }
);

export const getUserRequestTotals = createSelector(
  [getUserRequests],
  (userRequests) => {
    const userRequestTotals = {
      total: userRequests.length,
      ON_DEMAND: 0,
      SCHEDULED: 0,
      WORKER: 0,
      RUN_ONCE: 0,
      SERVICE: 0
    };

    for (const r of userRequests) {
      userRequestTotals[r.request.requestType] += 1;
    }

    return userRequestTotals;
  }
);

export const getFilteredRequests = createSelector(
  [getSearchFilter, getRequestsAPI],
  (searchFilter, requestsAPI) => {
    let filteredRequests = requestsAPI.data;

    // filter by type
    if (searchFilter.typeFilter !== 'ALL') {
      filteredRequests = filteredRequests.filter((r) => {
        return searchFilter.typeFilter === r.request.requestType;
      });
    }

    // filter by state
    filteredRequests = filteredRequests.filter((r) => {
      return searchFilter.stateFilter.indexOf(r.state) > -1;
    });

    const getUser = (r) => {
      if ('requestDeployState' in r && 'activeDeploy' in r.requestDeployState) {
        return r.requestDeployState.activeDeploy.user || '';
      }
      return null;
    };

    // filter by text
    if (searchFilter.textFilter.length < 3) {
      // Don't start filtering by text until string has some length
      return filteredRequests;
    }
    if (Utils.isGlobFilter(searchFilter.textFilter)) {
      const byId = filteredRequests.filter((r) => {
        return micromatch.any(r.request.id, `${searchFilter.textFilter}*`);
      });
      const byUser = filteredRequests.filter((r) => {
        const user = getUser(r);
        if (user !== null) {
          return micromatch.any(user, `${searchFilter.textFilter}*`);
        }
        return false;
      });
      filteredRequests = _.uniq(_.union(byUser, byId)).reverse();
    } else {
      // somewhere, in the history of Request searching, this was labeled a hack
      // time has passed
      // the comment was lost to refactors
      // this is no longer considered a hack
      // todo: remove hack
      const byId = fuzzy.filter(
        searchFilter.textFilter,
        filteredRequests,
        {
          extract: (r) => r.request.id
        }
      );

      const byUser = fuzzy.filter(
        searchFilter.textFilter,
        filteredRequests,
        {
          extract: (r) => getUser(r) || ''
        }
      );

      filteredRequests = _.uniq(
        _.pluck(
          _.sortBy(
            _.union(byUser, byId),
            (r) => {
              return Utils.fuzzyAdjustScore(searchFilter.textFilter, r);
            }
          ),
          'original'
        ).reverse()
      );
    }

    return filteredRequests;
  }
);
<commit_msg>Fix My paused requests table<commit_after>import { createSelector } from 'reselect';
import micromatch from 'micromatch';
import fuzzy from 'fuzzy';
import _ from 'underscore';

import Utils from '../utils';

const getRequestsAPI = (state) => state.api.requests;
const getUserAPI = (state) => state.api.user;
const getSearchFilter = (state) => state.ui.requestsPage;

function findRequestIds(requests) {
  return _.map(requests, (r) => {
    return _.extend({}, r, {id: r.request ? r.request.id : r.requestId});
  });
}

export const getStarred = (state) => new Set(state.ui.starred);

export const getStarredRequests = createSelector(
  [getStarred, getRequestsAPI],
  (starredData, requestsAPI) => {
    const requests = findRequestIds(requestsAPI.data);
    return requests.filter((r) => starredData.has(r.request.id));
  }
);

export const getUserRequests = createSelector(
  [getUserAPI, getRequestsAPI],
  (userAPI, requestsAPI) => {
    const deployUserTrimmed = Utils.maybe(
      userAPI.data,
      ['user', 'email'],
      ''
    ).split('@')[0];

    const requests = findRequestIds(requestsAPI.data);

    return requests.filter((r) => {
      const activeDeployUser = Utils.maybe(
        r,
        ['requestDeployState', 'activeDeploy', 'user']
      );

      if (activeDeployUser) {
        const activeDeployUserTrimmed = activeDeployUser.split('@')[0];
        if (deployUserTrimmed === activeDeployUserTrimmed) {
          return true;
        }
      }

      const requestOwners = r.request.owners;
      if (requestOwners === undefined) {
        return false;
      }

      for (const owner of requestOwners) {
        if (deployUserTrimmed === owner.split('@')[0]) {
          return true;
        }
      }

      return false;
    });
  }
);

export const getUserRequestTotals = createSelector(
  [getUserRequests],
  (userRequests) => {
    const userRequestTotals = {
      total: userRequests.length,
      ON_DEMAND: 0,
      SCHEDULED: 0,
      WORKER: 0,
      RUN_ONCE: 0,
      SERVICE: 0
    };

    for (const r of userRequests) {
      userRequestTotals[r.request.requestType] += 1;
    }

    return userRequestTotals;
  }
);

export const getFilteredRequests = createSelector(
  [getSearchFilter, getRequestsAPI],
  (searchFilter, requestsAPI) => {
    let filteredRequests = requestsAPI.data;

    // filter by type
    if (searchFilter.typeFilter !== 'ALL') {
      filteredRequests = filteredRequests.filter((r) => {
        return searchFilter.typeFilter === r.request.requestType;
      });
    }

    // filter by state
    filteredRequests = filteredRequests.filter((r) => {
      return searchFilter.stateFilter.indexOf(r.state) > -1;
    });

    const getUser = (r) => {
      if ('requestDeployState' in r && 'activeDeploy' in r.requestDeployState) {
        return r.requestDeployState.activeDeploy.user || '';
      }
      return null;
    };

    // filter by text
    if (searchFilter.textFilter.length < 3) {
      // Don't start filtering by text until string has some length
      return filteredRequests;
    }
    if (Utils.isGlobFilter(searchFilter.textFilter)) {
      const byId = filteredRequests.filter((r) => {
        return micromatch.any(r.request.id, `${searchFilter.textFilter}*`);
      });
      const byUser = filteredRequests.filter((r) => {
        const user = getUser(r);
        if (user !== null) {
          return micromatch.any(user, `${searchFilter.textFilter}*`);
        }
        return false;
      });
      filteredRequests = _.uniq(_.union(byUser, byId)).reverse();
    } else {
      // somewhere, in the history of Request searching, this was labeled a hack
      // time has passed
      // the comment was lost to refactors
      // this is no longer considered a hack
      // todo: remove hack
      const byId = fuzzy.filter(
        searchFilter.textFilter,
        filteredRequests,
        {
          extract: (r) => r.request.id
        }
      );

      const byUser = fuzzy.filter(
        searchFilter.textFilter,
        filteredRequests,
        {
          extract: (r) => getUser(r) || ''
        }
      );

      filteredRequests = _.uniq(
        _.pluck(
          _.sortBy(
            _.union(byUser, byId),
            (r) => {
              return Utils.fuzzyAdjustScore(searchFilter.textFilter, r);
            }
          ),
          'original'
        ).reverse()
      );
    }

    return filteredRequests;
  }
);
<|endoftext|>


<commit_before><commit_msg>Add blank line to blog.js file<commit_after><|endoftext|>


<commit_before>/**
 * @license
 * The MIT License (MIT)
 * Copyright 2015 Government of Canada
 *
 * @author
 * Ian Boyes
 *
 * @exports IsolateAdd
 */

import React from "react";
import { find, map, get, upperFirst } from "lodash-es";
import { connect } from "react-redux";
import { Row, Col, Modal } from "react-bootstrap";

import { editSequence, hideOTUModal } from "../../actions";
import { clearError } from "../../../errors/actions";
import { Button, InputError } from "../../../base";
import SequenceField from "./SequenceField";

const getInitialState = (props) => {

    if (props.sequenceId) {
        const isolate = {...props.isolate};
        const sequence = find(isolate.sequences, {id: props.sequenceId});

        return {
            definition: sequence.definition,
            host: sequence.host,
            sequence: sequence.sequence,
            segment: sequence.segment,
            autofillPending: false,
            errorDefinition: "",
            errorSequence: "",
            error: props.error
        };
    }

    return {
        definition: "",
        host: "",
        sequence: "",
        segment: "",
        autofillPending: false,
        errorDefinition: "",
        errorSequence: "",
        error: ""
    };
};

class EditSequence extends React.Component {

    constructor (props) {
        super(props);
        this.state = getInitialState(this.props);
    }

    static getDerivedStateFromProps (nextProps, prevState) {
        if (prevState.error !== nextProps.error) {
            return { error: nextProps.error };
        }
        return null;
    }

    handleChange = (e) => {
        const { name, value } = e.target;
        const error = `error${upperFirst(name)}`;

        this.setState({
            [name]: value,
            [error]: ""
        });

        if (this.props.error) {
            this.props.onClearError("EDIT_SEQUENCE_ERROR");
        }
    };

    handleModalEnter = () => {
        this.setState(getInitialState(this.props));
    };

    handleHide = () => {
        this.props.onHide();

        if (this.props.error) {
            this.props.onClearError("EDIT_SEQUENCE_ERROR");
        }
    };

    handleSubmit = (e) => {
        e.preventDefault();

        if (!this.state.definition.length) {
            return this.setState({ errorDefinition: "Minimum length is 1" });
        }

        if (!this.state.sequence.length) {
            return this.setState({ errorSequence: "Minimum length is 1" });
        }

        this.props.onSave(
            this.props.otuId,
            this.props.isolateId,
            this.props.sequenceId,
            this.state.definition,
            this.state.host,
            this.state.sequence,
            this.state.segment
        );
    };

    render () {

        let overlay;

        if (this.state.autofillPending) {
            overlay = (

                        Loading

            );
        }

        const currentOption = this.state.segment
            ? (<option key={this.state.segment} value={this.state.segment}>{this.state.segment}</option>)
            : null;
        const defaultOption = (<option key="" value=""> - None - </option>);
        const segmentNames = map(this.props.schema, (segment) =>
            <option key={segment} value={segment}>
                {segment}
            </option>
        );

        return (
            <Modal show={!!this.props.sequenceId} onEnter={this.handleModalEnter} onHide={this.handleHide}>
                <Modal.Header onHide={this.handleHide} closeButton>
                    Edit Sequence
                </Modal.Header>

                <form onSubmit={this.handleSubmit}>
                    <Modal.Body>
                        {overlay}
                        <Row>
                            <Col xs={12} md={6}>
                                <InputError
                                    label="Accession (ID)"
                                    name="id"
                                    value={this.props.sequenceId}
                                    readOnly
                                />
                            </Col>
                            <Col xs={12} md={6}>
                                <InputError
                                    type="select"
                                    label="Segment"
                                    name="segment"
                                    value={this.state.segment}
                                    onChange={this.handleChange}
                                    error={this.state.error}
                                >
                                    {defaultOption}
                                    {currentOption}
                                    {segmentNames}
                                </InputError>
                            </Col>
                        </Row>
                        <Row>
                            <Col xs={12}>
                                <InputError
                                    label="Host"
                                    name="host"
                                    value={this.state.host}
                                    onChange={this.handleChange}
                                />
                            </Col>
                        </Row>
                        <Row>
                            <Col xs={12}>
                                <InputError
                                    label="Definition"
                                    name="definition"
                                    value={this.state.definition}
                                    onChange={this.handleChange}
                                    error={this.state.errorDefinition}
                                />
                            </Col>
                        </Row>
                        <Row>
                            <Col xs={12}>
                                <SequenceField
                                    name="sequence"
                                    sequence={this.state.sequence}
                                    onChange={this.handleChange}
                                    error={this.state.errorSequence}
                                />
                            </Col>
                        </Row>
                    </Modal.Body>
                    <Modal.Footer>
                        <Button type="submit" bsStyle="primary" icon="save">
                            Save
                        </Button>
                    </Modal.Footer>
                </form>
            </Modal>
        );
    }
}

const mapStateToProps = state => ({
    detail: state.otus.detail,
    isolate: state.otus.activeIsolate,
    sequenceId: state.otus.editSequence,
    otuId: state.otus.detail.id,
    error: get(state, "errors.EDIT_SEQUENCE_ERROR.message", "")
});

const mapDispatchToProps = dispatch => ({

    onHide: () => {
        dispatch(hideOTUModal());
    },

    onSave: (otuId, isolateId, sequenceId, definition, host, sequence, segment) => {
        dispatch(editSequence(otuId, isolateId, sequenceId, definition, host, sequence, segment));
    },

    onClearError: (error) => {
        dispatch(clearError(error));
    }

});

export default connect(mapStateToProps, mapDispatchToProps)(EditSequence);
<commit_msg>Fix invalid input error caused by host null value<commit_after>/**
 * @license
 * The MIT License (MIT)
 * Copyright 2015 Government of Canada
 *
 * @author
 * Ian Boyes
 *
 * @exports IsolateAdd
 */

import React from "react";
import { find, map, get, upperFirst } from "lodash-es";
import { connect } from "react-redux";
import { Row, Col, Modal } from "react-bootstrap";

import { editSequence, hideOTUModal } from "../../actions";
import { clearError } from "../../../errors/actions";
import { Button, InputError } from "../../../base";
import SequenceField from "./SequenceField";

const getInitialState = (props) => {

    if (props.sequenceId) {
        const isolate = {...props.isolate};
        const sequence = find(isolate.sequences, {id: props.sequenceId});

        return {
            definition: sequence.definition,
            host: sequence.host || "",
            sequence: sequence.sequence,
            segment: sequence.segment,
            autofillPending: false,
            errorDefinition: "",
            errorSequence: "",
            error: props.error
        };
    }

    return {
        definition: "",
        host: "",
        sequence: "",
        segment: "",
        autofillPending: false,
        errorDefinition: "",
        errorSequence: "",
        error: ""
    };
};

class EditSequence extends React.Component {

    constructor (props) {
        super(props);
        this.state = getInitialState(this.props);
    }

    static getDerivedStateFromProps (nextProps, prevState) {
        if (prevState.error !== nextProps.error) {
            return { error: nextProps.error };
        }
        return null;
    }

    handleChange = (e) => {
        const { name, value } = e.target;
        const error = `error${upperFirst(name)}`;

        this.setState({
            [name]: value,
            [error]: ""
        });

        if (this.props.error) {
            this.props.onClearError("EDIT_SEQUENCE_ERROR");
        }
    };

    handleModalEnter = () => {
        this.setState(getInitialState(this.props));
    };

    handleHide = () => {
        this.props.onHide();

        if (this.props.error) {
            this.props.onClearError("EDIT_SEQUENCE_ERROR");
        }
    };

    handleSubmit = (e) => {
        e.preventDefault();

        if (!this.state.definition.length) {
            return this.setState({ errorDefinition: "Minimum length is 1" });
        }

        if (!this.state.sequence.length) {
            return this.setState({ errorSequence: "Minimum length is 1" });
        }

        this.props.onSave(
            this.props.otuId,
            this.props.isolateId,
            this.props.sequenceId,
            this.state.definition,
            this.state.host,
            this.state.sequence,
            this.state.segment
        );
    };

    render () {

        let overlay;

        if (this.state.autofillPending) {
            overlay = (

                        Loading

            );
        }

        const currentOption = this.state.segment
            ? (<option key={this.state.segment} value={this.state.segment}>{this.state.segment}</option>)
            : null;
        const defaultOption = (<option key="" value=""> - None - </option>);
        const segmentNames = map(this.props.schema, (segment) =>
            <option key={segment} value={segment}>
                {segment}
            </option>
        );

        return (
            <Modal show={!!this.props.sequenceId} onEnter={this.handleModalEnter} onHide={this.handleHide}>
                <Modal.Header onHide={this.handleHide} closeButton>
                    Edit Sequence
                </Modal.Header>

                <form onSubmit={this.handleSubmit}>
                    <Modal.Body>
                        {overlay}
                        <Row>
                            <Col xs={12} md={6}>
                                <InputError
                                    label="Accession (ID)"
                                    name="id"
                                    value={this.props.sequenceId}
                                    readOnly
                                />
                            </Col>
                            <Col xs={12} md={6}>
                                <InputError
                                    type="select"
                                    label="Segment"
                                    name="segment"
                                    value={this.state.segment}
                                    onChange={this.handleChange}
                                    error={this.state.error}
                                >
                                    {defaultOption}
                                    {currentOption}
                                    {segmentNames}
                                </InputError>
                            </Col>
                        </Row>
                        <Row>
                            <Col xs={12}>
                                <InputError
                                    label="Host"
                                    name="host"
                                    value={this.state.host}
                                    onChange={this.handleChange}
                                />
                            </Col>
                        </Row>
                        <Row>
                            <Col xs={12}>
                                <InputError
                                    label="Definition"
                                    name="definition"
                                    value={this.state.definition}
                                    onChange={this.handleChange}
                                    error={this.state.errorDefinition}
                                />
                            </Col>
                        </Row>
                        <Row>
                            <Col xs={12}>
                                <SequenceField
                                    name="sequence"
                                    sequence={this.state.sequence}
                                    onChange={this.handleChange}
                                    error={this.state.errorSequence}
                                />
                            </Col>
                        </Row>
                    </Modal.Body>
                    <Modal.Footer>
                        <Button type="submit" bsStyle="primary" icon="save">
                            Save
                        </Button>
                    </Modal.Footer>
                </form>
            </Modal>
        );
    }
}

const mapStateToProps = state => ({
    detail: state.otus.detail,
    isolate: state.otus.activeIsolate,
    sequenceId: state.otus.editSequence,
    otuId: state.otus.detail.id,
    error: get(state, "errors.EDIT_SEQUENCE_ERROR.message", "")
});

const mapDispatchToProps = dispatch => ({

    onHide: () => {
        dispatch(hideOTUModal());
    },

    onSave: (otuId, isolateId, sequenceId, definition, host, sequence, segment) => {
        dispatch(editSequence(otuId, isolateId, sequenceId, definition, host, sequence, segment));
    },

    onClearError: (error) => {
        dispatch(clearError(error));
    }

});

export default connect(mapStateToProps, mapDispatchToProps)(EditSequence);
<|endoftext|>


<commit_before>/**
 * asynchronous audio data analyzer ffmpeg wrapper using node-pcm
 *
 * MIT Licensed, see License.txt
 *
 */

// nodejs http
var http = require('http');

// nodejs filesystem
var fs = require('fs');

// nodejs child_process
var childProcess = require('child_process');

// NODE_ENV can be "development", "staging" or "production"
if (typeof(process.env.NODE_ENV) === 'undefined') {

    console.log('PROCESS ENV NOT FOUND, setting it by default to PRODUCTION', 'red');

    process.env.NODE_ENV = 'production';

}

// get the environment variable
var environment = process.env.NODE_ENV;

var temporaryTracksDirecotry = '/tmp/tracks';
var finalTracksDirecotry = __dirname + '/tracks';

var trackFileName;

var checkIfFileAlreadyExists = false;

/**
 *
 * analyzing track data
 *
 * @returns {undefined}
 */
var analyzeTrack = function() {

    var trackPath = finalTracksDirecotry + '/' + trackFileName;

    console.log('analyzing track data, trackPath: ' + trackPath);

    // https://github.com/HowlingEverett/waveform-util/blob/master/lib/waveform.js

    // ffprobe file data
    var ffprobeSpawn = childProcess.spawn(
       'ffprobe',
       [
           trackPath,
           '-show_streams',
           '-show_format',
           '-print_format',
           'json'
       ]
    );

    var ouput = '';

    //ffprobeSpawn.stdout.setEncoding('utf8');

    ffprobeSpawn.stdout.on('data', function(data) {

        //console.log('data: ' + data);

        ouput += data;

    });

    ffprobeSpawn.stdout.on('end', function(data) {

        console.log('ffprobeSpawn stdout end');

        if (output.length > 0) {

            console.log(output);

            //callback(output, null);

        } else {

            console.log('no output recieved');

        }

    });

    ffprobeSpawn.stderr.setEncoding('utf8');

    ffprobeSpawn.stderr.on('data', function(data) {

        //console.log(data.toString());

    });

    ffprobeSpawn.stderr.on('end', function() {

        console.log('ffprobeSpawn stderr end');

    });

    ffprobeSpawn.on('exit', function(code) {

        console.log('ffprobeSpawn exit, code: ' + code);

    });

    ffprobeSpawn.on('close', function() {

        console.log('ffprobeSpawn close');

    });

    // pcm audio data
    var channels = 1;
    var sampleRate = 44100;

    var ffmpegSpawn = childProcess.spawn(
        'ffmpeg',
        [
            '-i',
            trackPath,
            '-f',
            's16le',
            '-ac',
            channels,
            '-acodec',
            'pcm_s16le',
            '-ar',
            sampleRate,
            '-y',
            'pipe:1'
        ]
    );

    var output = '';

    // TODO: uncomment for ffprobe
    //ffmpegSpawn.stdout.setEncoding('utf8');

    var oddByte = null;
    var channel = 0;

    var outputCounter = 0;

    var maxValue = 0;

    ffmpegSpawn.stdout.on('data', function(data) {

        // http://nodejs.org/api/buffer.html#buffer_buf_readint16le_offset_noassert
        // https://github.com/jhurliman/node-pcm/blob/master/lib/pcm.js

        var value;
        var i;
        var dataLen = data.length;
        var percentageOfMax = 0;

        for (i=0; i < dataLen; i += 2) {

            value = data.readInt16LE(i, true);

            //channel = ++channel % 2;

            //console.log('B: ' + value + ' / ' + channel);

            outputCounter++;

            //if (value > maxValue) maxValue = value;

            // maxValue is 32767

            // (value / maxValue)*100 = percentage of max
            percentageOfMax = (value / 32767)*100;

            //return false;

        }

        //console.log('outputCounter: ' + outputCounter);

        //console.log(maxValue); // 32767

        // get absolute value
        var absolutePercentageOfMaxMath = Math.abs(percentageOfMax);

        console.log(absolutePercentageOfMaxMath);

        var bar = '';

        for (i=0; i < absolutePercentageOfMaxMath/10; i++) {

            bar += '*';

        }

        console.log(bar);

    });

    ffmpegSpawn.stdout.on('end', function(data) {

        console.log('ffmpegSpawn stdout end');

        if (output.length > 0) {

            console.log(output);

            //callback(output, null);

        } else {

            console.log('no output recieved');

        }

    });

    ffmpegSpawn.stderr.setEncoding('utf8');

    ffmpegSpawn.stderr.on('data', function(data) {

        //console.log(data.toString());

    });

    ffmpegSpawn.stderr.on('end', function() {

        console.log('ffmpegSpawn stderr end');

    });

    ffmpegSpawn.on('exit', function(code) {

        console.log('ffmpegSpawn exit, code: ' + code);

    });

    ffmpegSpawn.on('close', function() {

        console.log('ffmpegSpawn close');

    });

};

/**
 *
 * move the track from temporary folder to its final destination
 *
 * @returns {undefined}
 */
var moveTrack = function() {

    var fromPath = temporaryTracksDirecotry + '/' + trackFileName;
    var toPath = finalTracksDirecotry + '/' + trackFileName;

    var trackSourceReadStream = fs.createReadStream(fromPath);

    trackSourceReadStream.on('open', function() {

        var trackDestinationWriteStream = fs.createWriteStream(toPath);

        trackDestinationWriteStream.on('open', function() {

            trackSourceReadStream.pipe(trackDestinationWriteStream);

        });

        trackDestinationWriteStream.on('close', function() {

            console.log('track got moved from ' + fromPath + ' to final destination ' + toPath);

            analyzeTrack();

        });

        trackDestinationWriteStream.on('error', function(error) {

            console.log('moveTrack trackDestinationWriteStream, error: ' + error);

        });

    });

    trackSourceReadStream.on('close', function(error) {

        console.log('read and write stream are now closed');

    });

    trackSourceReadStream.on('error', function(error) {

        console.log('moveTrack trackSourceReadStream, error: ' + error);

    });

};

/**
 *
 * write the track to temporary folder on disc
 *
 * @returns {undefined}
 */
var writeTrackToDisc = function() {

    var trackPath = temporaryTracksDirecotry + '/' + trackFileName;

    //
    var options = {
        hostname: 'storage-new.newjamendo.com',
        port: 80,
        path: '/download/track/415208/ogg1',
        method: 'GET'
    };

    var writeStream = fs.createWriteStream(trackPath);

    writeStream.on('open', function() {

        var httpRequest = http.request(options, function(httpResponse) {

            console.log('writeTrackToDisc httpRequest STATUS: ' + httpResponse.statusCode);
            console.log('writeTrackToDisc httpRequest HEADERS: ' + JSON.stringify(httpResponse.headers));

            httpResponse.on('data', function(chunk) {

                writeStream.write(chunk);

            });

            httpResponse.on('end', function() {

                console.log('file ' + trackFileName + ' got downloaded into ' + trackPath);

                writeStream.end();

                moveTrack();

            });

        });

        httpRequest.on('error', function(error) {

            console.log('writeTrackToDisc, http request error: ' + error.message);

            writeStream.end();

        });

        httpRequest.end();

    });

    writeStream.on('error', function(error) {

        console.log('writeTrackToDisc writeStream, error: ' + error);

        writeStream.end();

    });

};

/**
 *
 * check if the track already exists
 *
 * @returns {undefined}
 */
var checkIfTrackExists = function() {

    if (checkIfFileAlreadyExists) {

        var toPath = finalTracksDirecotry + '/' + trackFileName;

        // does the file exist
        fs.exists(toPath, function(exists) {

            console.log(toPath + ' exists?: ' + exists);

            if (exists) {

                console.log('this track already exists');

            } else {

                writeTrackToDisc();

            }

        });

    } else {

        writeTrackToDisc();

    }

};

/**
 *
 * check if the final tracks directory exists
 *
 * @returns {undefined}
 */
var checkIfFinalTracksDirectoryExists = function() {

    // does the directory exist
    fs.exists(finalTracksDirecotry, function(exists) {

        console.log('checkIfFinalTracksDirectoryExists exists?: ' + exists);

        if (exists) {

            checkIfTrackExists();

        } else {

            // it does not exist yet so we create it
            fs.mkdir(finalTracksDirecotry, 0666, function(error) {

                if (error) {

                    console.log('checkIfFinalTracksDirectoryExists mkdir error: ' + error);

                } else {

                    checkIfTrackExists();

                }

            });

        }

    });

};

/**
 *
 * check if the temporary tracks directory exists
 *
 * @param {type} fileDirecotry
 * @returns {undefined}
 */
var checkIfTemporaryTracksDirectoryExists = function(fileDirecotry) {

    // does the directory exist
    fs.exists(temporaryTracksDirecotry, function(exists) {

        console.log('checkIfTemporaryTracksDirectoryExists exists?: ' + exists);

        if (exists) {

            checkIfFinalTracksDirectoryExists();

        } else {

            // it does not exist yet so we create it
            fs.mkdir(temporaryTracksDirecotry, 0666, function(error) {

                if (error) {

                    console.log('checkIfTemporaryTracksDirectoryExists mkdir error: ' + error);

                } else {

                    checkIfFinalTracksDirectoryExists();

                }

            });

        }

    });

};

/**
 *
 * get track data
 *
 * @param {type} audio_path
 * @param {type} output_width
 * @param {type} duration
 * @param {type} sample_rate
 * @param {type} channels
 * @param {type} cb
 * @returns {getPeaks.coefficient_to_db}
 */
var getTrackData = function(trackId, trackExtension) {

    trackFileName = trackId + '.' + trackExtension;

    if (arguments.length === 2) {

        var tmpDirecotry = '/tmp';

        // does the directory exist
        fs.exists(tmpDirecotry, function(exists) {

            console.log('getTrackData, tmpDirecotry exists?: ' + exists);

            if (exists) {

                checkIfTemporaryTracksDirectoryExists();

            } else {

                fs.mkdir(tmpDirecotry, 0666, function(error) {

                    if (error) {

                        console.log('getTrackData mkdir error: ' + error);

                    } else {

                        checkIfTemporaryTracksDirectoryExists();

                    }

                });

            }

        });

    } else {

        console.log('getTrackData arguments, error: ' + arguments);

    }

};

var trackId = '415208';
var trackExtension = 'ogg';

getTrackData(trackId, trackExtension);<commit_msg>updated description<commit_after>/**
 * experiment to visualize music
 *
 */

// nodejs http
var http = require('http');

// nodejs filesystem
var fs = require('fs');

// nodejs child_process
var childProcess = require('child_process');

// NODE_ENV can be "development", "staging" or "production"
if (typeof(process.env.NODE_ENV) === 'undefined') {

    console.log('PROCESS ENV NOT FOUND, setting it by default to PRODUCTION', 'red');

    process.env.NODE_ENV = 'production';

}

// get the environment variable
var environment = process.env.NODE_ENV;

var temporaryTracksDirecotry = '/tmp/tracks';
var finalTracksDirecotry = __dirname + '/tracks';

var trackFileName;

var checkIfFileAlreadyExists = false;

/**
 *
 * analyzing track data
 *
 * @returns {undefined}
 */
var analyzeTrack = function() {

    var trackPath = finalTracksDirecotry + '/' + trackFileName;

    console.log('analyzing track data, trackPath: ' + trackPath);

    // https://github.com/HowlingEverett/waveform-util/blob/master/lib/waveform.js

    // ffprobe file data
    var ffprobeSpawn = childProcess.spawn(
       'ffprobe',
       [
           trackPath,
           '-show_streams',
           '-show_format',
           '-print_format',
           'json'
       ]
    );

    var ouput = '';

    //ffprobeSpawn.stdout.setEncoding('utf8');

    ffprobeSpawn.stdout.on('data', function(data) {

        //console.log('data: ' + data);

        ouput += data;

    });

    ffprobeSpawn.stdout.on('end', function(data) {

        console.log('ffprobeSpawn stdout end');

        if (output.length > 0) {

            console.log(output);

            //callback(output, null);

        } else {

            console.log('no output recieved');

        }

    });

    ffprobeSpawn.stderr.setEncoding('utf8');

    ffprobeSpawn.stderr.on('data', function(data) {

        //console.log(data.toString());

    });

    ffprobeSpawn.stderr.on('end', function() {

        console.log('ffprobeSpawn stderr end');

    });

    ffprobeSpawn.on('exit', function(code) {

        console.log('ffprobeSpawn exit, code: ' + code);

    });

    ffprobeSpawn.on('close', function() {

        console.log('ffprobeSpawn close');

    });

    // pcm audio data
    var channels = 1;
    var sampleRate = 44100;

    var ffmpegSpawn = childProcess.spawn(
        'ffmpeg',
        [
            '-i',
            trackPath,
            '-f',
            's16le',
            '-ac',
            channels,
            '-acodec',
            'pcm_s16le',
            '-ar',
            sampleRate,
            '-y',
            'pipe:1'
        ]
    );

    var output = '';

    // TODO: uncomment for ffprobe
    //ffmpegSpawn.stdout.setEncoding('utf8');

    var oddByte = null;
    var channel = 0;

    var outputCounter = 0;

    var maxValue = 0;

    ffmpegSpawn.stdout.on('data', function(data) {

        // http://nodejs.org/api/buffer.html#buffer_buf_readint16le_offset_noassert
        // https://github.com/jhurliman/node-pcm/blob/master/lib/pcm.js

        var value;
        var i;
        var dataLen = data.length;
        var percentageOfMax = 0;

        for (i=0; i < dataLen; i += 2) {

            value = data.readInt16LE(i, true);

            //channel = ++channel % 2;

            //console.log('B: ' + value + ' / ' + channel);

            outputCounter++;

            //if (value > maxValue) maxValue = value;

            // maxValue is 32767

            // (value / maxValue)*100 = percentage of max
            percentageOfMax = (value / 32767)*100;

            //return false;

        }

        //console.log('outputCounter: ' + outputCounter);

        //console.log(maxValue); // 32767

        // get absolute value
        var absolutePercentageOfMaxMath = Math.abs(percentageOfMax);

        console.log(absolutePercentageOfMaxMath);

        var bar = '';

        for (i=0; i < absolutePercentageOfMaxMath/10; i++) {

            bar += '*';

        }

        console.log(bar);

    });

    ffmpegSpawn.stdout.on('end', function(data) {

        console.log('ffmpegSpawn stdout end');

        if (output.length > 0) {

            console.log(output);

            //callback(output, null);

        } else {

            console.log('no output recieved');

        }

    });

    ffmpegSpawn.stderr.setEncoding('utf8');

    ffmpegSpawn.stderr.on('data', function(data) {

        //console.log(data.toString());

    });

    ffmpegSpawn.stderr.on('end', function() {

        console.log('ffmpegSpawn stderr end');

    });

    ffmpegSpawn.on('exit', function(code) {

        console.log('ffmpegSpawn exit, code: ' + code);

    });

    ffmpegSpawn.on('close', function() {

        console.log('ffmpegSpawn close');

    });

};

/**
 *
 * move the track from temporary folder to its final destination
 *
 * @returns {undefined}
 */
var moveTrack = function() {

    var fromPath = temporaryTracksDirecotry + '/' + trackFileName;
    var toPath = finalTracksDirecotry + '/' + trackFileName;

    var trackSourceReadStream = fs.createReadStream(fromPath);

    trackSourceReadStream.on('open', function() {

        var trackDestinationWriteStream = fs.createWriteStream(toPath);

        trackDestinationWriteStream.on('open', function() {

            trackSourceReadStream.pipe(trackDestinationWriteStream);

        });

        trackDestinationWriteStream.on('close', function() {

            console.log('track got moved from ' + fromPath + ' to final destination ' + toPath);

            analyzeTrack();

        });

        trackDestinationWriteStream.on('error', function(error) {

            console.log('moveTrack trackDestinationWriteStream, error: ' + error);

        });

    });

    trackSourceReadStream.on('close', function(error) {

        console.log('read and write stream are now closed');

    });

    trackSourceReadStream.on('error', function(error) {

        console.log('moveTrack trackSourceReadStream, error: ' + error);

    });

};

/**
 *
 * write the track to temporary folder on disc
 *
 * @returns {undefined}
 */
var writeTrackToDisc = function() {

    var trackPath = temporaryTracksDirecotry + '/' + trackFileName;

    //
    var options = {
        hostname: 'storage-new.newjamendo.com',
        port: 80,
        path: '/download/track/415208/ogg1',
        method: 'GET'
    };

    var writeStream = fs.createWriteStream(trackPath);

    writeStream.on('open', function() {

        var httpRequest = http.request(options, function(httpResponse) {

            console.log('writeTrackToDisc httpRequest STATUS: ' + httpResponse.statusCode);
            console.log('writeTrackToDisc httpRequest HEADERS: ' + JSON.stringify(httpResponse.headers));

            httpResponse.on('data', function(chunk) {

                writeStream.write(chunk);

            });

            httpResponse.on('end', function() {

                console.log('file ' + trackFileName + ' got downloaded into ' + trackPath);

                writeStream.end();

                moveTrack();

            });

        });

        httpRequest.on('error', function(error) {

            console.log('writeTrackToDisc, http request error: ' + error.message);

            writeStream.end();

        });

        httpRequest.end();

    });

    writeStream.on('error', function(error) {

        console.log('writeTrackToDisc writeStream, error: ' + error);

        writeStream.end();

    });

};

/**
 *
 * check if the track already exists
 *
 * @returns {undefined}
 */
var checkIfTrackExists = function() {

    if (checkIfFileAlreadyExists) {

        var toPath = finalTracksDirecotry + '/' + trackFileName;

        // does the file exist
        fs.exists(toPath, function(exists) {

            console.log(toPath + ' exists?: ' + exists);

            if (exists) {

                console.log('this track already exists');

            } else {

                writeTrackToDisc();

            }

        });

    } else {

        writeTrackToDisc();

    }

};

/**
 *
 * check if the final tracks directory exists
 *
 * @returns {undefined}
 */
var checkIfFinalTracksDirectoryExists = function() {

    // does the directory exist
    fs.exists(finalTracksDirecotry, function(exists) {

        console.log('checkIfFinalTracksDirectoryExists exists?: ' + exists);

        if (exists) {

            checkIfTrackExists();

        } else {

            // it does not exist yet so we create it
            fs.mkdir(finalTracksDirecotry, 0666, function(error) {

                if (error) {

                    console.log('checkIfFinalTracksDirectoryExists mkdir error: ' + error);

                } else {

                    checkIfTrackExists();

                }

            });

        }

    });

};

/**
 *
 * check if the temporary tracks directory exists
 *
 * @param {type} fileDirecotry
 * @returns {undefined}
 */
var checkIfTemporaryTracksDirectoryExists = function(fileDirecotry) {

    // does the directory exist
    fs.exists(temporaryTracksDirecotry, function(exists) {

        console.log('checkIfTemporaryTracksDirectoryExists exists?: ' + exists);

        if (exists) {

            checkIfFinalTracksDirectoryExists();

        } else {

            // it does not exist yet so we create it
            fs.mkdir(temporaryTracksDirecotry, 0666, function(error) {

                if (error) {

                    console.log('checkIfTemporaryTracksDirectoryExists mkdir error: ' + error);

                } else {

                    checkIfFinalTracksDirectoryExists();

                }

            });

        }

    });

};

/**
 *
 * get track data
 *
 * @param {type} audio_path
 * @param {type} output_width
 * @param {type} duration
 * @param {type} sample_rate
 * @param {type} channels
 * @param {type} cb
 * @returns {getPeaks.coefficient_to_db}
 */
var getTrackData = function(trackId, trackExtension) {

    trackFileName = trackId + '.' + trackExtension;

    if (arguments.length === 2) {

        var tmpDirecotry = '/tmp';

        // does the directory exist
        fs.exists(tmpDirecotry, function(exists) {

            console.log('getTrackData, tmpDirecotry exists?: ' + exists);

            if (exists) {

                checkIfTemporaryTracksDirectoryExists();

            } else {

                fs.mkdir(tmpDirecotry, 0666, function(error) {

                    if (error) {

                        console.log('getTrackData mkdir error: ' + error);

                    } else {

                        checkIfTemporaryTracksDirectoryExists();

                    }

                });

            }

        });

    } else {

        console.log('getTrackData arguments, error: ' + arguments);

    }

};

var trackId = '415208';
var trackExtension = 'ogg';

getTrackData(trackId, trackExtension);<|endoftext|>


<commit_before>import React from "react";
import { connect } from "react-redux";
import { Switch, Route, Redirect } from "react-router-dom";
import { push } from "connected-react-router";
import { get } from "lodash-es";
import { LinkContainer } from "react-router-bootstrap";
import { Badge, Nav, NavItem, Dropdown, MenuItem } from "react-bootstrap";
import { LoadingPlaceholder, Icon, ViewHeader, Flex, FlexItem, RelativeTime, NotFound } from "../../../base";
import IndexDetail from "../../../indexes/components/Detail";
import OTUDetail from "../../../otus/components/Detail/Detail";
import { checkRefRight, followDownload } from "../../../utils/utils";
import { getReference } from "../../actions";
import OTUList from "../../../otus/components/List";
import Indexes from "../../../indexes/components/Indexes";
import SourceTypes from "../SourceTypes";
import InternalControl from "./InternalControl";
import ReferenceMembers from "./Members";
import ReferenceManage from "./Manage";
import EditReference from "./Edit";

class CustomToggle extends React.Component {
    // Bootstrap Dropdown requires custom dropdown components to be class components
    // in order to use refs.
    render() {
        return (
            <Icon
                name="ellipsis-v"
                tip="Options"
                onClick={this.props.onClick}
                style={{ fontSize: "65%", paddingLeft: "5px" }}
            />
        );
    }
}

const ReferenceSettings = ({ isRemote }) => (

        {isRemote ? null : <SourceTypes />}
        <ReferenceMembers noun="users" />
        <ReferenceMembers noun="groups" />

);

class ReferenceDetail extends React.Component {
    constructor(props) {
        super(props);
        this.props.onGetReference(this.props.match.params.refId);
    }

    handleSelect = key => {
        followDownload(`/download/refs/${this.props.match.params.refId}?scope=${key}`);
    };

    render = () => {
        if (this.props.error) {
            return <NotFound />;
        }

        if (this.props.detail === null || this.props.detail.id !== this.props.match.params.refId) {
            return <LoadingPlaceholder />;
        }

        const { name, id, remotes_from, created_at, user } = this.props.detail;

        let headerIcon;
        let exportButton;

        if (this.props.pathname === `/refs/${id}/manage`) {
            headerIcon = remotes_from ? (
                <Icon bsStyle="default" name="lock" pullRight style={{ fontSize: "65%" }} />
            ) : null;

            headerIcon =
                this.props.canModify && !remotes_from ? (
                    <Icon
                        bsStyle="warning"
                        name="pencil-alt"
                        tip="Edit"
                        onClick={this.props.onEdit}
                        pullRight
                        style={{ fontSize: "65%" }}
                    />
                ) : (
                    headerIcon
                );

            exportButton = (
                <Dropdown id="dropdown-export-reference" className="dropdown-export-reference">
                    <CustomToggle bsRole="toggle" />
                    <Dropdown.Menu className="export-ref-dropdown-menu">
                        <MenuItem header>Export</MenuItem>
                        <MenuItem eventKey="built" onSelect={this.handleSelect}>
                            Built
                        </MenuItem>
                        <MenuItem eventKey="unbuilt" onSelect={this.handleSelect}>
                            Unbuilt
                        </MenuItem>
                        <MenuItem eventKey="unverified" onSelect={this.handleSelect}>
                            Unverified
                        </MenuItem>
                    </Dropdown.Menu>
                </Dropdown>
            );
        }

        const referenceHeader = (
            <ViewHeader title={`${name} - References`}>
                <Flex alignItems="flex-end">
                    <FlexItem grow={1}>
                        <Flex>
                            {name}
                        </Flex>
                    </FlexItem>
                    {headerIcon}
                    {exportButton}
                </Flex>

                    Created <RelativeTime time={created_at} /> by {user.id}

            </ViewHeader>
        );

        return (

                <Switch>
                    <Route path="/refs/:refId/otus/:otuId" component={OTUDetail} />
                    <Route path="/refs/:refId/indexes/:indexId" component={IndexDetail} />
                    <Route
                        path="/refs"
                        render={() => (

                                {referenceHeader}

                                    <LinkContainer to={`/refs/${id}/manage`}>
                                        <NavItem>Manage</NavItem>
                                    </LinkContainer>
                                    <LinkContainer to={`/refs/${id}/otus`}>
                                        <NavItem>
                                            OTUs <Badge>{this.props.detail.otu_count}</Badge>
                                        </NavItem>
                                    </LinkContainer>
                                    <LinkContainer to={`/refs/${id}/indexes`}>
                                        <NavItem>Indexes</NavItem>
                                    </LinkContainer>
                                    <LinkContainer to={`/refs/${id}/settings`}>
                                        <NavItem>Settings</NavItem>
                                    </LinkContainer>

                                <Switch>
                                    <Redirect from="/refs/:refId" to={`/refs/${id}/manage`} exact />
                                    <Route path="/refs/:refId/manage" component={ReferenceManage} />
                                    <Route path="/refs/:refId/otus" component={OTUList} />
                                    <Route path="/refs/:refId/indexes" component={Indexes} />
                                    <Route
                                        path="/refs/:refId/settings"
                                        render={() => <ReferenceSettings isRemote={remotes_from} />}
                                    />
                                </Switch>

                                <EditReference />

                        )}
                    />
                </Switch>

        );
    };
}

const mapStateToProps = state => ({
    error: get(state, "errors.GET_REFERENCE_ERROR", null),
    detail: state.references.detail,
    pathname: state.router.location.pathname,
    canModify: checkRefRight(state, "modify")
});

const mapDispatchToProps = dispatch => ({
    onGetReference: refId => {
        dispatch(getReference(refId));
    },

    onEdit: () => {
        dispatch(push({ ...window.location, state: { editReference: true } }));
    }
});

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(ReferenceDetail);
<commit_msg>Improve ref export interface<commit_after>import React from "react";
import { connect } from "react-redux";
import { Switch, Route, Redirect } from "react-router-dom";
import { push } from "connected-react-router";
import { get } from "lodash-es";
import { LinkContainer } from "react-router-bootstrap";
import { Badge, Nav, NavItem, Dropdown, MenuItem } from "react-bootstrap";
import { LoadingPlaceholder, Icon, ViewHeader, Flex, FlexItem, RelativeTime, NotFound } from "../../../base";
import IndexDetail from "../../../indexes/components/Detail";
import OTUDetail from "../../../otus/components/Detail/Detail";
import { checkRefRight, followDownload } from "../../../utils/utils";
import { getReference } from "../../actions";
import OTUList from "../../../otus/components/List";
import Indexes from "../../../indexes/components/Indexes";
import SourceTypes from "../SourceTypes";
import InternalControl from "./InternalControl";
import ReferenceMembers from "./Members";
import ReferenceManage from "./Manage";
import EditReference from "./Edit";

class CustomToggle extends React.Component {
    // Bootstrap Dropdown requires custom dropdown components to be class components
    // in order to use refs.
    render() {
        return (
            <Icon
                name="download"
                tip="Options"
                onClick={this.props.onClick}
                style={{ fontSize: "65%", paddingLeft: "5px" }}
            />
        );
    }
}

const ReferenceSettings = ({ isRemote }) => (

        {isRemote ? null : <SourceTypes />}
        <ReferenceMembers noun="users" />
        <ReferenceMembers noun="groups" />

);

class ReferenceDetail extends React.Component {
    constructor(props) {
        super(props);
        this.props.onGetReference(this.props.match.params.refId);
    }

    handleSelect = key => {
        followDownload(`/download/refs/${this.props.match.params.refId}?scope=${key}`);
    };

    render = () => {
        if (this.props.error) {
            return <NotFound />;
        }

        if (this.props.detail === null || this.props.detail.id !== this.props.match.params.refId) {
            return <LoadingPlaceholder />;
        }

        const { name, id, cloned_from, remotes_from, created_at, user } = this.props.detail;

        let headerIcon;
        let exportButton;

        if (this.props.pathname === `/refs/${id}/manage`) {
            headerIcon = remotes_from ? (
                <Icon bsStyle="default" name="lock" pullRight style={{ fontSize: "65%" }} />
            ) : null;

            headerIcon =
                this.props.canModify && !remotes_from ? (
                    <Icon
                        bsStyle="warning"
                        name="pencil-alt"
                        tip="Edit"
                        onClick={this.props.onEdit}
                        pullRight
                        style={{ fontSize: "65%" }}
                    />
                ) : (
                    headerIcon
                );

            if (!remotes_from) {
                let remoteExport;
                if (cloned_from) {
                    remoteExport = (
                        <MenuItem eventKey="remote" onSelect={this.handleSelect}>

Remote

                                Export the reference using the OTU IDs from the source reference for this clone.

                        </MenuItem>
                    );
                }

                exportButton = (
                    <Dropdown id="dropdown-export-reference" className="dropdown-export-reference">
                        <CustomToggle bsRole="toggle" />
                        <Dropdown.Menu className="export-ref-dropdown-menu">
                            <MenuItem eventKey="built" onSelect={this.handleSelect}>

Normal

                                Export the reference with the local OTU IDs.
                            </MenuItem>
                            {remoteExport}
                        </Dropdown.Menu>
                    </Dropdown>
                );
            }
        }

        const referenceHeader = (
            <ViewHeader title={`${name} - References`}>
                <Flex alignItems="flex-end">
                    <FlexItem grow={1}>
                        <Flex>
                            {name}
                        </Flex>
                    </FlexItem>
                    {headerIcon}
                    {exportButton}
                </Flex>

                    Created <RelativeTime time={created_at} /> by {user.id}

            </ViewHeader>
        );

        return (

                <Switch>
                    <Route path="/refs/:refId/otus/:otuId" component={OTUDetail} />
                    <Route path="/refs/:refId/indexes/:indexId" component={IndexDetail} />
                    <Route
                        path="/refs"
                        render={() => (

                                {referenceHeader}

                                    <LinkContainer to={`/refs/${id}/manage`}>
                                        <NavItem>Manage</NavItem>
                                    </LinkContainer>
                                    <LinkContainer to={`/refs/${id}/otus`}>
                                        <NavItem>
                                            OTUs <Badge>{this.props.detail.otu_count}</Badge>
                                        </NavItem>
                                    </LinkContainer>
                                    <LinkContainer to={`/refs/${id}/indexes`}>
                                        <NavItem>Indexes</NavItem>
                                    </LinkContainer>
                                    <LinkContainer to={`/refs/${id}/settings`}>
                                        <NavItem>Settings</NavItem>
                                    </LinkContainer>

                                <Switch>
                                    <Redirect from="/refs/:refId" to={`/refs/${id}/manage`} exact />
                                    <Route path="/refs/:refId/manage" component={ReferenceManage} />
                                    <Route path="/refs/:refId/otus" component={OTUList} />
                                    <Route path="/refs/:refId/indexes" component={Indexes} />
                                    <Route
                                        path="/refs/:refId/settings"
                                        render={() => <ReferenceSettings isRemote={remotes_from} />}
                                    />
                                </Switch>

                                <EditReference />

                        )}
                    />
                </Switch>

        );
    };
}

const mapStateToProps = state => ({
    error: get(state, "errors.GET_REFERENCE_ERROR", null),
    detail: state.references.detail,
    pathname: state.router.location.pathname,
    canModify: checkRefRight(state, "modify")
});

const mapDispatchToProps = dispatch => ({
    onGetReference: refId => {
        dispatch(getReference(refId));
    },

    onEdit: () => {
        dispatch(push({ ...window.location, state: { editReference: true } }));
    }
});

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(ReferenceDetail);
<|endoftext|>


<commit_before>import React from 'react';
import { subscribe } from 'horizon-react';
import wedding from '../../../../../config/wedding.js';
import variables from '../../../../../config/variables.js';
import glob from 'styles/app';
import local from './_styles';
import { Row, Col, Button } from 'react-bootstrap';
import PageHeader from '../../_partials/page-header';
import prettyAddress from '../../_partials/pretty-address';
import Map from '../../_partials/map/map';
import { showGuideMapInfo } from '../../../actions/actionCreators';
import greetings from '../../../../../static/images/greetings.png';
import Scroll from 'react-scroll';

/**
  *
  * The City Guide page
  *
  * @param  none
  *
  * @return {ReactComponent}
  */

const Events = Scroll.Events;
const scroll = Scroll.animateScroll;
const scrollSpy = Scroll.scrollSpy;

const images = process.env.NODE_ENV === 'production' ? 'images' : `http://127.0.0.1:9095/static/images`;

const mapStateToProps = (state) => ({
  guideMap: state.guideMap
});

class CityGuide extends React.Component {
  handlePlaceNameClick(e){
    e.preventDefault();
    const element = document.getElementById('map')
    const alignWithTop = true;
    element.scrollIntoView(alignWithTop);
    const placeParts = e.target.id.split('-');
    const list = placeParts[0];
    const index = parseInt(placeParts[1]);
    const markers = this.props.guideMap.markers.map(
      (marker, i) => {
        let show = false;
        if (marker.pin === list && marker.idx === index) {
          show = true
        }
        return {
          ...marker,
          showInfo: show,
        };
      }
    );
    this.props.dispatch(showGuideMapInfo(markers));
  }

  componentDidMount () {
    scrollSpy.update();
    scroll.scrollToTop();
  }

  componentWillUnmount() {
    Events.scrollEvent.remove('begin');
    Events.scrollEvent.remove('end');
  }

  render(){
    const accommodationsAddress = prettyAddress(wedding.accommodations.hotel.address);

    const makeList = (listType) => {
      let prettyListType = listType;
      if(listType === 'bar'){
        prettyListType = Drink
<i className={`material-icons ${local.icon}`}>local_bar;
      } else if(listType === 'music'){
        prettyListType = Music
<i className={`material-icons ${local.icon}`}>music_note;
      } else if(listType === 'food'){
        prettyListType = Eat
<i className={`material-icons ${local.icon}`}>restaurant;
      } else if(listType === 'fun'){
        prettyListType = Misc
<i className={`material-icons ${local.icon}`}>directions_bike;
      } else if(listType === 'shop'){
        prettyListType = Shop
<i className={`material-icons ${local.icon}`}>shopping_basket;
      }
      return (
        <ul className={`${local.todoListCol}`}>
          <li
            className={`${glob.card} ${local.todoListHeader}`}
            style={{backgroundColor: variables.$map.colors[listType]}}
          >

              {prettyListType}

          {wedding.guide[listType].list.map(
            (place, idx) => {
              return (
                <li className={`${glob.card} ${local.listItem}`} key={idx}>

                    {place.name}

{place.description}

{place.address.street}

                    <a className={local.guideLink} href="#" style={{ color: variables.$map.colors[listType]}} onClick={this.handlePlaceNameClick.bind(this)} id={`${listType}-${idx}`}>
                      map

                      arrow_forward

              );
            }
          )}

      )
    }

    const barList = makeList('bar');
    const musicList = makeList('music');
    const foodList = makeList('food');
    const funList = makeList('fun');
    const shopList = makeList('shop');

    const fullList = (

{musicList}

{funList}

{foodList}

{barList}

{shopList}

    );

    return (

        <PageHeader page="City Guide" />

        <div className={`${glob.section}`} style={{ paddingBottom: '0px' }}>

Welcome to

{wedding.city.name}

        <div className={`${glob.section} ${glob.sectionBlue}`} style={{  }}>
          <Row>
            <Col xs={11} sm={5} md={4} className={glob.verticalCol}>

            </Col>
          </Row>

        <div className={`${glob.section}`}>
          <h2 className={`${glob.headerLines} ${glob.black}`}>Accommodations

          <Row>
            <Col xs={10} sm={6} className={glob.verticalCol}>
                <div className={`${glob.card} ${local.hotel}`}>

                      {wedding.accommodations.hotel.name}

                      {wedding.accommodations.hotel.location}

{accommodationsAddress}

                      Book Hotel at {wedding.accommodations.hotel.discountAmt}% OFF

            </Col>
            <Col xs={8} sm={6} className={`${glob.verticalCol} ${local.hotelAbout}`}>

hotel

{wedding.accommodations.hotel.highlight}

{wedding.accommodations.hotel.message}

            </Col>
          </Row>

        <div className={`${glob.section} ${glob.sectionWhiteMed}`}>
          <Row>
            <Col xs={12}>
              <h2 className={`${glob.headerLines}`}>Transportation

              <ul className={`${local.transportation}`}>

                    <Button className={`${glob.button}`} href={wedding.guide.transportation.bus.how.website} target="_BLANK">
                      directions_bus

                      {wedding.guide.transportation.bus.how.name}
                    </Button>

                    <Button className={`${glob.button}`} href={wedding.guide.transportation.rideshare.how.website}  target="_BLANK">
                      directions_car

                      {wedding.guide.transportation.rideshare.how.name}
                    </Button>

                    <Button className={`${glob.button}`} href={wedding.guide.transportation.taxi.how.website} target="_BLANK">
                      local_taxi

                      {wedding.guide.transportation.taxi.how.name}
                    </Button>

            </Col>
          </Row>

        <div  className={`${glob.section}`}>
          <h2 className={`${glob.headerLines} ${glob.black}`}>Things to Do

          <Row id="map">
            <Col xs={10} xsOffset={1} lg={6} lgOffset={3}>
              <Map type="guide" />
            </Col>
          </Row>
          <Row>
            <Col xs={10} xsOffset={1} lg={6} lgOffset={3}>
              {fullList}
            </Col>
          </Row>

    );
  }
};

export default subscribe({
  mapStateToProps
})(CityGuide);
<commit_msg>Guide image<commit_after>import React from 'react';
import { subscribe } from 'horizon-react';
import wedding from '../../../../../config/wedding.js';
import variables from '../../../../../config/variables.js';
import glob from 'styles/app';
import local from './_styles';
import { Row, Col, Button } from 'react-bootstrap';
import PageHeader from '../../_partials/page-header';
import prettyAddress from '../../_partials/pretty-address';
import Map from '../../_partials/map/map';
import { showGuideMapInfo } from '../../../actions/actionCreators';
import greetings from '../../../../../static/images/greetings.png';
import Scroll from 'react-scroll';

/**
  *
  * The City Guide page
  *
  * @param  none
  *
  * @return {ReactComponent}
  */

const Events = Scroll.Events;
const scroll = Scroll.animateScroll;
const scrollSpy = Scroll.scrollSpy;

const images = process.env.NODE_ENV === 'production' ? 'images' : `http://127.0.0.1:9095/static/images`;

const mapStateToProps = (state) => ({
  guideMap: state.guideMap
});

class CityGuide extends React.Component {
  handlePlaceNameClick(e){
    e.preventDefault();
    const element = document.getElementById('map')
    const alignWithTop = true;
    element.scrollIntoView(alignWithTop);
    const placeParts = e.target.id.split('-');
    const list = placeParts[0];
    const index = parseInt(placeParts[1]);
    const markers = this.props.guideMap.markers.map(
      (marker, i) => {
        let show = false;
        if (marker.pin === list && marker.idx === index) {
          show = true
        }
        return {
          ...marker,
          showInfo: show,
        };
      }
    );
    this.props.dispatch(showGuideMapInfo(markers));
  }

  componentDidMount () {
    scrollSpy.update();
    scroll.scrollToTop();
  }

  componentWillUnmount() {
    Events.scrollEvent.remove('begin');
    Events.scrollEvent.remove('end');
  }

  render(){
    const accommodationsAddress = prettyAddress(wedding.accommodations.hotel.address);

    const makeList = (listType) => {
      let prettyListType = listType;
      if(listType === 'bar'){
        prettyListType = Drink
<i className={`material-icons ${local.icon}`}>local_bar;
      } else if(listType === 'music'){
        prettyListType = Music
<i className={`material-icons ${local.icon}`}>music_note;
      } else if(listType === 'food'){
        prettyListType = Eat
<i className={`material-icons ${local.icon}`}>restaurant;
      } else if(listType === 'fun'){
        prettyListType = Misc
<i className={`material-icons ${local.icon}`}>directions_bike;
      } else if(listType === 'shop'){
        prettyListType = Shop
<i className={`material-icons ${local.icon}`}>shopping_basket;
      }
      return (
        <ul className={`${local.todoListCol}`}>
          <li
            className={`${glob.card} ${local.todoListHeader}`}
            style={{backgroundColor: variables.$map.colors[listType]}}
          >

              {prettyListType}

          {wedding.guide[listType].list.map(
            (place, idx) => {
              return (
                <li className={`${glob.card} ${local.listItem}`} key={idx}>

                    {place.name}

{place.description}

{place.address.street}

                    <a className={local.guideLink} href="#" style={{ color: variables.$map.colors[listType]}} onClick={this.handlePlaceNameClick.bind(this)} id={`${listType}-${idx}`}>
                      map

                      arrow_forward

              );
            }
          )}

      )
    }

    const barList = makeList('bar');
    const musicList = makeList('music');
    const foodList = makeList('food');
    const funList = makeList('fun');
    const shopList = makeList('shop');

    const fullList = (

{musicList}

{funList}

{foodList}

{barList}

{shopList}

    );

    return (

        <PageHeader page="City Guide" />

        <div className={`${glob.section}`} style={{ paddingBottom: '0px' }}>

Welcome to

{wedding.city.name}

        <div className={`${glob.section} ${glob.sectionBlue}`} style={{  }}>
          <Row>
            <Col xs={11} sm={6} md={4} className={glob.verticalCol}>

            </Col>
          </Row>

        <div className={`${glob.section}`}>
          <h2 className={`${glob.headerLines} ${glob.black}`}>Accommodations

          <Row>
            <Col xs={10} sm={6} className={glob.verticalCol}>
                <div className={`${glob.card} ${local.hotel}`}>

                      {wedding.accommodations.hotel.name}

                      {wedding.accommodations.hotel.location}

{accommodationsAddress}

                      Book Hotel at {wedding.accommodations.hotel.discountAmt}% OFF

            </Col>
            <Col xs={8} sm={6} className={`${glob.verticalCol} ${local.hotelAbout}`}>

hotel

{wedding.accommodations.hotel.highlight}

{wedding.accommodations.hotel.message}

            </Col>
          </Row>

        <div className={`${glob.section} ${glob.sectionWhiteMed}`}>
          <Row>
            <Col xs={12}>
              <h2 className={`${glob.headerLines}`}>Transportation

              <ul className={`${local.transportation}`}>

                    <Button className={`${glob.button}`} href={wedding.guide.transportation.bus.how.website} target="_BLANK">
                      directions_bus

                      {wedding.guide.transportation.bus.how.name}
                    </Button>

                    <Button className={`${glob.button}`} href={wedding.guide.transportation.rideshare.how.website}  target="_BLANK">
                      directions_car

                      {wedding.guide.transportation.rideshare.how.name}
                    </Button>

                    <Button className={`${glob.button}`} href={wedding.guide.transportation.taxi.how.website} target="_BLANK">
                      local_taxi

                      {wedding.guide.transportation.taxi.how.name}
                    </Button>

            </Col>
          </Row>

        <div  className={`${glob.section}`}>
          <h2 className={`${glob.headerLines} ${glob.black}`}>Things to Do

          <Row id="map">
            <Col xs={10} xsOffset={1} lg={6} lgOffset={3}>
              <Map type="guide" />
            </Col>
          </Row>
          <Row>
            <Col xs={10} xsOffset={1} lg={6} lgOffset={3}>
              {fullList}
            </Col>
          </Row>

    );
  }
};

export default subscribe({
  mapStateToProps
})(CityGuide);
<|endoftext|>