<commit_before>import React from 'react';
import { connect } from 'react-redux';
import TableRow from './TableRow';
import Pagination from './Pagination';
import Button from './Button';
import FilterInput from './FilterInput';
import TableHeaderItem from './TableHeaderItem';

import { selectRow, deleteRow, changePage, setFilter, setSortDef } from './../actions/table';

const UNSELECTED = -1;

class Table extends React.Component {

  constructor(props) {
    super(props);

    this.onAddNewRow = this.onAddNewRow.bind(this);
    this.onDeleteRow = this.onDeleteRow.bind(this);
    this.onEditRow = this.onEditRow.bind(this);
    this.onSelectRow = this.onSelectRow.bind(this);
    this.onChangePageIndex = this.onChangePageIndex.bind(this);
    this.onHandleFilter = this.onHandleFilter.bind(this);
    this.onHandleSortColumn = this.onHandleSortColumn.bind(this);
  }

  onAddNewRow() {
    if (this.props.onAddRow) {
      this.props.onAddRow();
    }
  }

  onDeleteRow(rowId) {
    let { dispatch } = this.props;
    dispatch(deleteRow(rowId));

    if (this.props.onDeleteRow) {
      this.props.onDeleteRow(rowId);
    }
  }

  onEditRow(rowId) {
    if (this.props.onEditRow) {
      this.props.onEditRow(rowId);
    }
  }

  onSelectRow(rowId) {
    let selectedRowId = (this.props.selectedRowId === rowId) ? UNSELECTED : rowId;
    let { dispatch } = this.props;
    dispatch(selectRow(selectedRowId));

    if (this.props.onSelectRow && typeof this.props.onSelectRow === 'function') {
      this.props.onSelectRow(rowId);
    }
  }

  onChangePageIndex(index) {
    if (index < 0) {
      return;
    }

    let { dispatch } = this.props;
    dispatch(changePage(index));
  }

  onHandleFilter(value) {
    let { dispatch } = this.props;
    dispatch(setFilter(value));
  }

  onHandleSortColumn(columnIndex) {
    if (this.props.tools) {
      columnIndex -= 1;
    }

    let sd = this.props.sortDirection;
    if (sd === TableHeaderItem.SORT_NOPE) {
      sd = TableHeaderItem.SORT_ASCENDING;
    }

    let scdv = 1;
    if (this.props.sortColumnIndex === columnIndex) {
      scdv = TableHeaderItem.SORT_CHANGE_DIRECTION;
    }

    let { dispatch } = this.props;
    dispatch(setSortDef(columnIndex, sd * scdv));
  }

  prepRows(records, cp, ps) {
    let rows = [];

    for (let i = 0, cri = cp * ps; cri < records.length && i < ps; i++, cri++) {
      let Row = (
        <TableRow
          data={records[cri]}
          key={`row-${cri}`}
          rowId={cri}
          selected={this.props.selectedRowId === cri}
          tools={this.props.tools}
          onDelete={this.onDeleteRow}
          onEdit={this.onEditRow}
          onSelect={this.onSelectRow}
        />);
      rows.push(Row);
    }

    return rows;
  }

  prepHeader(header, tools) {
    let output = [];

    if (tools && header.length > 0) {
      let th = (<TableHeaderItem key={output.length} colId={output.length} />);
      output.push(th);
    }

    for (let i = 0; i < header.length; i++) {
      let sorted = TableHeaderItem.SORT_NOPE;
      if (i === this.props.sortColumnIndex) {
        sorted = this.props.sortDirection;
      }

      let th = (
        <TableHeaderItem
          sorted={sorted}
          key={output.length}
          colId={output.length}
          title={header[i]}
          onClick={this.onHandleSortColumn}
        />);
      output.push(th);
    }

    return output;
  }

  renderSectionHeader() {
    return (

        <FilterInput onKeyUp={this.onHandleFilter} />

          <Button cn={" btn-primary"} title={"Add new row"} onClick={this.onAddNewRow} />

);
  }

  renderSectionBody(header, rows) {
    return (

              {header}

            {rows}

);
  }

  renderSectionFooter(records, pageCount, pageSize) {
    return (

        {(() => {
          if (records.length > pageSize) {
            return (
              <Pagination
                active={this.props.activePage}
                items={pageCount}
                onChange={this.onChangePageIndex}
              />);
          }
          return '';
        })()}

    );
  }

  render() {
    let pageSize = this.props.pageSize;
    let ap = this.props.activePage;

    let pageCount = Math.ceil(this.props.data.length / pageSize);

    let header = this.prepHeader(this.props.header, this.props.tools);
    let rows = this.prepRows(this.props.data, ap, pageSize);

    return (

        {this.renderSectionHeader()}
        {this.renderSectionBody(header, rows)}
        {this.renderSectionFooter(this.props.data, pageCount, pageSize)}

);
  }
}

Table.defaultProps = {
  activePage: 0,
  pageSize: 10,
  tools: true,
  sortColumnIndex: UNSELECTED,
  sortDirection: TableHeaderItem.SORT_NOPE,
  selectedRowId: UNSELECTED,
  minFilterSize: 3
};

Table.propTypes = {
  activePage: React.PropTypes.number,
  data: React.PropTypes.array.isRequired,
  header: React.PropTypes.arrayOf(React.PropTypes.string),
  tools: React.PropTypes.bool,
  sortDirection: React.PropTypes.number,
  selectedRowId: React.PropTypes.number,
  minFilterSize: React.PropTypes.number,

  onDeleteRow: React.PropTypes.func,
  onAddRow: React.PropTypes.func,
  onEditRow: React.PropTypes.func,
  onSelectRow: React.PropTypes.func
};

function filterRecords(data, filterValue) {
  let records = data;

  if (filterValue !== '') {
    records = data.filter((row) => {
      let value = row.join();
      if (value.indexOf(filterValue) >= 0) {
        return value;
      }

      return false;
    });
  }

  return records;
}

function sortRecords(data, sortColumnIndex, sortDirection) {
  let records = data;
  records.sort((a, b) => {
    let v1 = a[sortColumnIndex];
    let v2 = b[sortColumnIndex];
    return sortDirection * v1.localeCompare(v2);
  });

  return records;
}

function shouldSort(state) {
  return (state.table.sortColumnIndex !== undefined);
}

function shouldFilter(state, ownProps) {
  let filterValue = state.table.filterValue || '';
  let prevFilterValue = state.table.prevFilterValue || '';
  let minFilterSize = ownProps.minFilterSize ?
    ownProps.minFilterSize : Table.defaultProps.minFilterSize;

  return (filterValue.length >= minFilterSize && filterValue !== prevFilterValue);
}

function mapStateToProps(state, ownProps) {
  let records = state.table.data;
  if (shouldFilter(state, ownProps)) {
    records = filterRecords(state.table.data, state.table.filterValue);
  }

  if (shouldSort(state)) {
    records = sortRecords(records, state.table.sortColumnIndex, state.table.sortDirection);
  }

  return {
    selectedRowId: state.table.selectedRowId,
    data: records,
    header: state.table.header,
    activePage: state.table.activePage,
    sortDirection: state.table.sortDirection || TableHeaderItem.SORT_NOPE,
    sortColumnIndex: state.table.sortColumnIndex === undefined ?
      UNSELECTED : state.table.sortColumnIndex
  };
}

export default connect(mapStateToProps)(Table);
<commit_msg>don't render empty header row if no header data available<commit_after>import React from 'react';
import { connect } from 'react-redux';
import TableRow from './TableRow';
import Pagination from './Pagination';
import Button from './Button';
import FilterInput from './FilterInput';
import TableHeaderItem from './TableHeaderItem';

import { selectRow, deleteRow, changePage, setFilter, setSortDef } from './../actions/table';

const UNSELECTED = -1;

class Table extends React.Component {

  constructor(props) {
    super(props);

    this.onAddNewRow = this.onAddNewRow.bind(this);
    this.onDeleteRow = this.onDeleteRow.bind(this);
    this.onEditRow = this.onEditRow.bind(this);
    this.onSelectRow = this.onSelectRow.bind(this);
    this.onChangePageIndex = this.onChangePageIndex.bind(this);
    this.onHandleFilter = this.onHandleFilter.bind(this);
    this.onHandleSortColumn = this.onHandleSortColumn.bind(this);
  }

  onAddNewRow() {
    if (this.props.onAddRow) {
      this.props.onAddRow();
    }
  }

  onDeleteRow(rowId) {
    let { dispatch } = this.props;
    dispatch(deleteRow(rowId));

    if (this.props.onDeleteRow) {
      this.props.onDeleteRow(rowId);
    }
  }

  onEditRow(rowId) {
    if (this.props.onEditRow) {
      this.props.onEditRow(rowId);
    }
  }

  onSelectRow(rowId) {
    let selectedRowId = (this.props.selectedRowId === rowId) ? UNSELECTED : rowId;
    let { dispatch } = this.props;
    dispatch(selectRow(selectedRowId));

    if (this.props.onSelectRow && typeof this.props.onSelectRow === 'function') {
      this.props.onSelectRow(rowId);
    }
  }

  onChangePageIndex(index) {
    if (index < 0) {
      return;
    }

    let { dispatch } = this.props;
    dispatch(changePage(index));
  }

  onHandleFilter(value) {
    let { dispatch } = this.props;
    dispatch(setFilter(value));
  }

  onHandleSortColumn(columnIndex) {
    if (this.props.tools) {
      columnIndex -= 1;
    }

    let sd = this.props.sortDirection;
    if (sd === TableHeaderItem.SORT_NOPE) {
      sd = TableHeaderItem.SORT_ASCENDING;
    }

    let scdv = 1;
    if (this.props.sortColumnIndex === columnIndex) {
      scdv = TableHeaderItem.SORT_CHANGE_DIRECTION;
    }

    let { dispatch } = this.props;
    dispatch(setSortDef(columnIndex, sd * scdv));
  }

  prepRows(records, cp, ps) {
    let rows = [];

    for (let i = 0, cri = cp * ps; cri < records.length && i < ps; i++, cri++) {
      let Row = (
        <TableRow
          data={records[cri]}
          key={`row-${cri}`}
          rowId={cri}
          selected={this.props.selectedRowId === cri}
          tools={this.props.tools}
          onDelete={this.onDeleteRow}
          onEdit={this.onEditRow}
          onSelect={this.onSelectRow}
        />);
      rows.push(Row);
    }

    return rows;
  }

  prepHeader(header, tools) {
    let output = [];

    if (!header) return null;

    if (tools && header.length > 0) {
      let th = (<TableHeaderItem key={output.length} colId={output.length} />);
      output.push(th);
    }

    for (let i = 0; i < header.length; i++) {
      let sorted = TableHeaderItem.SORT_NOPE;
      if (i === this.props.sortColumnIndex) {
        sorted = this.props.sortDirection;
      }

      let th = (
        <TableHeaderItem
          sorted={sorted}
          key={output.length}
          colId={output.length}
          title={header[i]}
          onClick={this.onHandleSortColumn}
        />);
      output.push(th);
    }

    return (
{output}
);
  }

  renderSectionHeader() {
    return (

        <FilterInput onKeyUp={this.onHandleFilter} />

          <Button cn={" btn-primary"} title={"Add new row"} onClick={this.onAddNewRow} />

);
  }

  renderSectionBody(header, rows) {
    return (

            {header}

            {rows}

);
  }

  renderSectionFooter(records, pageCount, pageSize) {
    return (

        {(() => {
          if (records.length > pageSize) {
            return (
              <Pagination
                active={this.props.activePage}
                items={pageCount}
                onChange={this.onChangePageIndex}
              />);
          }
          return '';
        })()}

    );
  }

  render() {
    let pageSize = this.props.pageSize;
    let ap = this.props.activePage;

    let pageCount = Math.ceil(this.props.data.length / pageSize);

    let header = this.prepHeader(this.props.header, this.props.tools);
    let rows = this.prepRows(this.props.data, ap, pageSize);

    return (

        {this.renderSectionHeader()}
        {this.renderSectionBody(header, rows)}
        {this.renderSectionFooter(this.props.data, pageCount, pageSize)}

);
  }
}

Table.defaultProps = {
  activePage: 0,
  pageSize: 10,
  tools: true,
  sortColumnIndex: UNSELECTED,
  sortDirection: TableHeaderItem.SORT_NOPE,
  selectedRowId: UNSELECTED,
  minFilterSize: 3
};

Table.propTypes = {
  activePage: React.PropTypes.number,
  data: React.PropTypes.array.isRequired,
  header: React.PropTypes.arrayOf(React.PropTypes.string),
  tools: React.PropTypes.bool,
  sortDirection: React.PropTypes.number,
  selectedRowId: React.PropTypes.number,
  minFilterSize: React.PropTypes.number,

  onDeleteRow: React.PropTypes.func,
  onAddRow: React.PropTypes.func,
  onEditRow: React.PropTypes.func,
  onSelectRow: React.PropTypes.func
};

function filterRecords(data, filterValue) {
  let records = data;

  if (filterValue !== '') {
    records = data.filter((row) => {
      let value = row.join();
      if (value.indexOf(filterValue) >= 0) {
        return value;
      }

      return false;
    });
  }

  return records;
}

function sortRecords(data, sortColumnIndex, sortDirection) {
  let records = data;
  records.sort((a, b) => {
    let v1 = a[sortColumnIndex];
    let v2 = b[sortColumnIndex];
    return sortDirection * v1.localeCompare(v2);
  });

  return records;
}

function shouldSort(state) {
  return (state.table.sortColumnIndex !== undefined);
}

function shouldFilter(state, ownProps) {
  let filterValue = state.table.filterValue || '';
  let prevFilterValue = state.table.prevFilterValue || '';
  let minFilterSize = ownProps.minFilterSize ?
    ownProps.minFilterSize : Table.defaultProps.minFilterSize;

  return (filterValue.length >= minFilterSize && filterValue !== prevFilterValue);
}

function mapStateToProps(state, ownProps) {
  let records = state.table.data;
  if (shouldFilter(state, ownProps)) {
    records = filterRecords(state.table.data, state.table.filterValue);
  }

  if (shouldSort(state)) {
    records = sortRecords(records, state.table.sortColumnIndex, state.table.sortDirection);
  }

  return {
    selectedRowId: state.table.selectedRowId,
    data: records,
    header: state.table.header,
    activePage: state.table.activePage,
    sortDirection: state.table.sortDirection || TableHeaderItem.SORT_NOPE,
    sortColumnIndex: state.table.sortColumnIndex === undefined ?
      UNSELECTED : state.table.sortColumnIndex
  };
}

export default connect(mapStateToProps)(Table);
<|endoftext|>


<commit_before>// -------------------------------------------------------------------
// markItUp!
// -------------------------------------------------------------------
// Copyright (C) 2008 Jay Salvat
// http://markitup.jaysalvat.com/
// -------------------------------------------------------------------
// Textile tags example
// http://en.wikipedia.org/wiki/Textile_(markup_language)
// http://www.textism.com/
// -------------------------------------------------------------------
// Feel free to add more tags
// -------------------------------------------------------------------
myFlexSettings = {
	nameSpace: 'textile',
	previewParserPath:	'', // path to your Textile parser
	onShiftEnter:		{keepDefault:false, replaceWith:'\n\n'},
	markupSet: [
		{name:'Heading 1', key:'1', openWith:'h1(!(([![Class]!]))!). ', placeHolder:'Your title here...' },
		{name:'Heading 2', key:'2', openWith:'h2(!(([![Class]!]))!). ', placeHolder:'Your title here...' },
		{name:'Heading 3', key:'3', openWith:'h3(!(([![Class]!]))!). ', placeHolder:'Your title here...' },
		{name:'Heading 4', key:'4', openWith:'h4(!(([![Class]!]))!). ', placeHolder:'Your title here...' },
		{name:'Heading 5', key:'5', openWith:'h5(!(([![Class]!]))!). ', placeHolder:'Your title here...' },
		{name:'Heading 6', key:'6', openWith:'h6(!(([![Class]!]))!). ', placeHolder:'Your title here...' },
		{name:'Paragraph', key:'P', openWith:'p(!(([![Class]!]))!). '},
		{separator:'---------------' },
		{name:'Bold', key:'B', closeWith:'*', openWith:'*'},
		{name:'Italic', key:'I', closeWith:'_', openWith:'_'},
		{name:'Stroke through', key:'S', closeWith:'-', openWith:'-'},
		{separator:'---------------' },
		{name:'Bulleted list', openWith:'(!(* |!|*)!)'},
		{name:'Numeric list', openWith:'(!(# |!|#)!)'},
		{separator:'---------------' },
		{name:'Picture', replaceWith:'_[Image:[![Index]!]]'},
		{name:'Link', replaceWith:'_[Link:[![Index]!]]'},
		{separator:'---------------' },
		{name:'Quotes', openWith:'bq(!(([![Class]!]))!). '},
		{name:'Code', openWith:'@', closeWith:'@'},
		{separator:'---------------' }
	]
}<commit_msg>Fixed image and link shortcode within markItUp editor.<commit_after>// -------------------------------------------------------------------
// markItUp!
// -------------------------------------------------------------------
// Copyright (C) 2008 Jay Salvat
// http://markitup.jaysalvat.com/
// -------------------------------------------------------------------
// Textile tags example
// http://en.wikipedia.org/wiki/Textile_(markup_language)
// http://www.textism.com/
// -------------------------------------------------------------------
// Feel free to add more tags
// -------------------------------------------------------------------
myFlexSettings = {
	nameSpace: 'textile',
	previewParserPath:	'', // path to your Textile parser
	onShiftEnter:		{keepDefault:false, replaceWith:'\n\n'},
	markupSet: [
		{name:'Heading 1', key:'1', openWith:'h1(!(([![Class]!]))!). ', placeHolder:'Your title here...' },
		{name:'Heading 2', key:'2', openWith:'h2(!(([![Class]!]))!). ', placeHolder:'Your title here...' },
		{name:'Heading 3', key:'3', openWith:'h3(!(([![Class]!]))!). ', placeHolder:'Your title here...' },
		{name:'Heading 4', key:'4', openWith:'h4(!(([![Class]!]))!). ', placeHolder:'Your title here...' },
		{name:'Heading 5', key:'5', openWith:'h5(!(([![Class]!]))!). ', placeHolder:'Your title here...' },
		{name:'Heading 6', key:'6', openWith:'h6(!(([![Class]!]))!). ', placeHolder:'Your title here...' },
		{name:'Paragraph', key:'P', openWith:'p(!(([![Class]!]))!). '},
		{separator:'---------------' },
		{name:'Bold', key:'B', closeWith:'*', openWith:'*'},
		{name:'Italic', key:'I', closeWith:'_', openWith:'_'},
		{name:'Stroke through', key:'S', closeWith:'-', openWith:'-'},
		{separator:'---------------' },
		{name:'Bulleted list', openWith:'(!(* |!|*)!)'},
		{name:'Numeric list', openWith:'(!(# |!|#)!)'},
		{separator:'---------------' },
		{name:'Picture', replaceWith:'.sc(Image:[![Index]!])'},
		{name:'Link', replaceWith:'.sc(Link:[![Index]!])'},
		{separator:'---------------' },
		{name:'Quotes', openWith:'bq(!(([![Class]!]))!). '},
		{name:'Code', openWith:'@', closeWith:'@'},
		{separator:'---------------' }
	]
}<|endoftext|>


<commit_before>var gulp = require("gulp")
  , clean = require("gulp-clean")
  , paths = require("./paths")

module.exports = function(){
  gulp.src(paths.dist.pages + "**/*", {read : false}).pipe(clean())
}
<commit_msg>Fix async gulp clean issue<commit_after>var gulp = require("gulp")
  , clean = require("gulp-clean")
  , paths = require("./paths")

module.exports = function(){
  return gulp.src(paths.dist.pages + "**/*", {read : false})
    .pipe(clean())
}
<|endoftext|>


<commit_before>import { createStore, applyMiddleware, compose } from 'redux';
import flatten from 'flatten';
import invariant from 'invariant';
import window from 'global/window';
import { returnSelf, isArray } from './utils';

export default function ({
  reducers,
  initialState,
  plugin,
  sagaMiddleware,
  promiseMiddleware,
  createOpts: {
    setupMiddlewares = returnSelf,
  },
}) {
  // extra enhancers
  const extraEnhancers = plugin.get('extraEnhancers');
  invariant(
    isArray(extraEnhancers),
    `[app.start] extraEnhancers should be array, but got ${typeof extraEnhancers}`,
  );

  const extraMiddlewares = plugin.get('onAction');
  const middlewares = setupMiddlewares([
    sagaMiddleware,
    promiseMiddleware,
    ...flatten(extraMiddlewares),
  ]);

  let devtools = () => noop => noop;
  if (process.env.NODE_ENV !== 'production' && window.__REDUX_DEVTOOLS_EXTENSION__) {
    devtools = window.__REDUX_DEVTOOLS_EXTENSION__;
  }

  const enhancers = [
    applyMiddleware(...middlewares),
    devtools(window.__REDUX_DEVTOOLS_EXTENSION__OPTIONS),
    ...extraEnhancers,
  ];

  return createStore(reducers, initialState, compose(...enhancers));
}
<commit_msg>fix: redux devtools maybe effect other enhancers.<commit_after>import { createStore, applyMiddleware, compose } from 'redux';
import flatten from 'flatten';
import invariant from 'invariant';
import window from 'global/window';
import { returnSelf, isArray } from './utils';

export default function ({
  reducers,
  initialState,
  plugin,
  sagaMiddleware,
  promiseMiddleware,
  createOpts: {
    setupMiddlewares = returnSelf,
  },
}) {
  // extra enhancers
  const extraEnhancers = plugin.get('extraEnhancers');
  invariant(
    isArray(extraEnhancers),
    `[app.start] extraEnhancers should be array, but got ${typeof extraEnhancers}`,
  );

  const extraMiddlewares = plugin.get('onAction');
  const middlewares = setupMiddlewares([
    sagaMiddleware,
    promiseMiddleware,
    ...flatten(extraMiddlewares),
  ]);

  let devtools = () => noop => noop;
  if (process.env.NODE_ENV !== 'production' && window.__REDUX_DEVTOOLS_EXTENSION__) {
    devtools = window.__REDUX_DEVTOOLS_EXTENSION__;
  }

  const enhancers = [
    applyMiddleware(...middlewares),
    ...extraEnhancers,
    devtools(window.__REDUX_DEVTOOLS_EXTENSION__OPTIONS),
  ];

  return createStore(reducers, initialState, compose(...enhancers));
}
<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');

/**
 * Config object for the app that contains the apiUrl
 * @type {Object}
 */
var config = {};

/**
 * Server Ember application
 */
var clientRoute = function(req, res) {
    return res.render('build', {
        baseURL: config.baseURL,
        apiURL: config.apiURL
    });
};

/**
 * Setup the baseUrl for the Ember app
 * @param  {Object} opts Options
 * @param  {String} opts.baseURL BaseUrl
 */
var setup = function(opts) {
    if (opts.apiURL) {
        config.apiURL = opts.apiURL;
    }

    if (opts.baseURL) {
        config.baseURL = opts.baseURL;
    }
}

// Express app
var app = express();

// Static files
app.set('view engine', 'jade');
app.set('views', __dirname + '/client/dist');

// Static routes
app.get('/', clientRoute);
app.get('/jobs', clientRoute);
app.get('/jobs/type/:type', clientRoute);
app.get('/jobs/state/:state', clientRoute);
app.get('/jobs/:id', clientRoute);
app.get('/jobs/new', clientRoute);

// After to avoid overriding `/`
app.use(express.static( __dirname + '/client/dist' ));

module.exports = {
    app: app,
    setup: setup,
    index: path.resolve(__dirname + '/client/dist/build.jade')
};
<commit_msg>forward slash again<commit_after>var express = require('express');
var path = require('path');

/**
 * Config object for the app that contains the apiUrl
 * @type {Object}
 */
var config = {};

/**
 * Server Ember application
 */
var clientRoute = function(req, res) {
    return res.render('build', {
        baseURL: config.baseURL === '/' ? '' : config.baseURL,
        apiURL: config.apiURL
    });
};

/**
 * Setup the baseUrl for the Ember app
 * @param  {Object} opts Options
 * @param  {String} opts.baseURL BaseUrl
 */
var setup = function(opts) {
    if (opts.apiURL) {
        config.apiURL = opts.apiURL;
    }

    if (opts.baseURL) {
        config.baseURL = opts.baseURL;
    }
}

// Express app
var app = express();

// Static files
app.set('view engine', 'jade');
app.set('views', __dirname + '/client/dist');

// Static routes
app.get('/', clientRoute);
app.get('/jobs', clientRoute);
app.get('/jobs/type/:type', clientRoute);
app.get('/jobs/state/:state', clientRoute);
app.get('/jobs/:id', clientRoute);
app.get('/jobs/new', clientRoute);

// After to avoid overriding `/`
app.use(express.static( __dirname + '/client/dist' ));

module.exports = {
    app: app,
    setup: setup,
    index: path.resolve(__dirname + '/client/dist/build.jade')
};
<|endoftext|>


<commit_before>/*
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

'use strict';

var _ = require('lodash');
var bunyan = require('bunyan');
var path = require('path');
var mkdirp = require('mkdirp');

/**
 * create a kernel instance
 */
module.exports = function(config, cb) {
  var _srv;
  var _auth;
  var _api;
  var logger = config.logger || bunyan.createLogger(_.merge({ name: 'nfd-kernel' }, config.kernel.logger));
  var loadConfig = require('./configLoader')(config);
  var _containers = require('./containers')(loadConfig, logger);
  var stat = false;
  var _servers = {};

  config.logger = logger;

  logger.info('booting');

  if (config.kernel.root) {
    config.kernel.root = path.resolve(process.cwd(), config.kernel.root);
    config.kernel.systemsRoot = path.join(config.kernel.root, 'data', 'systems');
  } else {
    config.kernel.systemsRoot = path.resolve(process.cwd(), config.kernel.systemsRoot);
    config.kernel.root = path.normalize(path.join(config.kernel.systemsRoot, '..', '..'));
  }

  if (!config.kernel.logRoot) {
    config.kernel.logRoot = path.join(config.kernel.root, 'log');
    mkdirp.sync(config.kernel.logRoot);
  }

  if (!config.kernel.timelinesRoot) {
    config.kernel.timelinesRoot = path.join(config.kernel.root, 'timelines');
    mkdirp.sync(config.kernel.timelinesRoot);
  }

  var _sr = require('./sysrev/sysrev')(config.kernel, logger);

  function setDefault(dest, source, key) {
    dest.specific[key] = dest.specific[key] || source.kernel[key];
  }

  function checkRequiredModule(name, cb) {
    var err = 'missing required module - ' + name;

    if (!(config.modules && config.modules[name] && config.modules[name].require)) {
      logger.error(err);
      cb(err);
      return false;
    }
    else {
      return true;
    }
  }

  function validateContainer(containerJson, container, cb) {
    var required = ['deploy', 'start', 'stop', 'link', 'unlink', 'undeploy', 'add', 'remove'];
    var err = 'invalid container: ' + containerJson.require + ' ';
    var stat = true;

    _.each(required, function(req) {
      if (!container[req]) {
        err += ' missing: ' + req;
        stat = false;
      }
    });

    if (!stat) {
      logger.error(err);
      cb(err);
    }

    return stat;
  }

  function start() {
    logger.info('starting operations');
    _srv.start(_api, _auth, logger);
  }

  function stop() {
    logger.info('stopping operations');
    _containers.stopAllServices(function(err) {
      if (err) { logger.error(err); process.exit(1); }
      process.exit(0);
    });
  }

  _sr.boot(function(err) {
    if (err) { logger.error(err); return cb(err); }

    logger.debug('loading protocol module');
    stat = checkRequiredModule('protocol', cb);
    if (stat) {
      _srv = require(config.modules.protocol.require)(config.kernel);
    }

    logger.debug('loading authorization module');
    stat = checkRequiredModule('authorization', cb);
    if (stat) {
      _auth = require(config.modules.authorization.require)(config.modules.authorization.specific);
    }

    _api = require('../lib/api')(
      config,
      loadConfig,
      logger,
      _sr,
      _containers,
      _servers);

    _containers.startAllServices(config, _api, _sr, function(err, servers) {
      if (err) { return cb(err); }

      // needed because we passed the _servers object to API
      Object.keys(servers).forEach(function(key) {
        _servers[key] = servers[key];
      });
      cb();
    });
  });

  return {
    start: start,
    stop: stop
  };
};

<commit_msg>Removing some unused functions.<commit_after>/*
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

'use strict';

var _ = require('lodash');
var bunyan = require('bunyan');
var path = require('path');
var mkdirp = require('mkdirp');

/**
 * create a kernel instance
 */
module.exports = function(config, cb) {
  var _srv;
  var _auth;
  var _api;
  var logger = config.logger || bunyan.createLogger(_.merge({ name: 'nfd-kernel' }, config.kernel.logger));
  var loadConfig = require('./configLoader')(config);
  var _containers = require('./containers')(loadConfig, logger);
  var stat = false;
  var _servers = {};

  config.logger = logger;

  logger.info('booting');

  if (config.kernel.root) {
    config.kernel.root = path.resolve(process.cwd(), config.kernel.root);
    config.kernel.systemsRoot = path.join(config.kernel.root, 'data', 'systems');
  } else {
    config.kernel.systemsRoot = path.resolve(process.cwd(), config.kernel.systemsRoot);
    config.kernel.root = path.normalize(path.join(config.kernel.systemsRoot, '..', '..'));
  }

  if (!config.kernel.logRoot) {
    config.kernel.logRoot = path.join(config.kernel.root, 'log');
    mkdirp.sync(config.kernel.logRoot);
  }

  if (!config.kernel.timelinesRoot) {
    config.kernel.timelinesRoot = path.join(config.kernel.root, 'timelines');
    mkdirp.sync(config.kernel.timelinesRoot);
  }

  var _sr = require('./sysrev/sysrev')(config.kernel, logger);

  function checkRequiredModule(name, cb) {
    var err = 'missing required module - ' + name;

    if (!(config.modules && config.modules[name] && config.modules[name].require)) {
      logger.error(err);
      cb(err);
      return false;
    }
    else {
      return true;
    }
  }

  function start() {
    logger.info('starting operations');
    _srv.start(_api, _auth, logger);
  }

  function stop() {
    logger.info('stopping operations');
    _containers.stopAllServices(function(err) {
      if (err) { logger.error(err); process.exit(1); }
      process.exit(0);
    });
  }

  _sr.boot(function(err) {
    if (err) { logger.error(err); return cb(err); }

    logger.debug('loading protocol module');
    stat = checkRequiredModule('protocol', cb);
    if (stat) {
      _srv = require(config.modules.protocol.require)(config.kernel);
    }

    logger.debug('loading authorization module');
    stat = checkRequiredModule('authorization', cb);
    if (stat) {
      _auth = require(config.modules.authorization.require)(config.modules.authorization.specific);
    }

    _api = require('../lib/api')(
      config,
      loadConfig,
      logger,
      _sr,
      _containers,
      _servers);

    _containers.startAllServices(config, _api, _sr, function(err, servers) {
      if (err) { return cb(err); }

      // needed because we passed the _servers object to API
      Object.keys(servers).forEach(function(key) {
        _servers[key] = servers[key];
      });
      cb();
    });
  });

  return {
    start: start,
    stop: stop
  };
};

<|endoftext|>


<commit_before>const async = require( 'async' );
const fs = require('fs');
const data_file = "./scripts/concurrent_users/inst.json"
// --------------------------------------------------------------------------------------
var exp = {}
// --------------------------------------------------------------------------------------
// perform mac address counting
// --------------------------------------------------------------------------------------
exp.process_old_data = function (database, callback) {
  // find the lowest date in database and go from that date to present
  var data = JSON.parse(fs.readFileSync(data_file, 'utf8'));
  var date;
  var current = new Date();
  var curr_min = new Date(current.getFullYear(), current.getMonth(), current.getUTCDate(), 0, 0, 0, 0);   // current day hh:mm:ss:ms set to 00:00:00:000

  // find all, sort by timestamp, display only timestamp, display one document only
  database.logs.find({}).sort({"timestamp" : 1}).limit(1).select({"timestamp" : 1, "_id" : 0}).exec(
  function(err, doc) {
    var date = doc;

    date = String(date[0]["timestamp"]);    // get only string representation of date

    var fields = date.split(" ");
    var months = {      // months dict for date constructor
      "Jan" : 0,
      "Feb" : 1,
      "Mar" : 2,
      "Apr" : 3,
      "May" : 4,
      "Jun" : 5,
      "Jul" : 6,
      "Aug" : 7,
      "Sep" : 8,
      "Oct" : 9,
      "Nov" : 10,
      "Dec" : 11
    }

    var min = new Date(fields[3], months[fields[1]], fields[2], 0, 0, 0, 0);        // hh:mm:ss:ms set to 0
    var max = new Date(fields[3], months[fields[1]], Number(fields[2]) + 1, 0, 0, 0, 0);    // next day, hh:mm:ss:ms set to 0
                                                                                // search uses lower than max condition !
    // this date handling should guarantee correct interval for all processed records

    async.whilst(function () {
      return min < curr_min;
    },
    function(next) {
      async.series([
        function(done) {
          search(database, data, min, max, done);     // calls done when finished
        },
        function(done) {
          min.setDate(min.getDate() + 1);  // continue
          max.setDate(max.getDate() + 1);  // continue
          done(null);                      // done
        }
        ],
        function(err, results) {
          next();   // next whilst iteration
      });
    },
    function(err) {
      if(err)
        console.error(err);
      else
        console.log("cron task concurrent_users finished processing old data");
      callback(null, null);
    });
  });
};
// --------------------------------------------------------------------------------------
// perform mac address counting
// --------------------------------------------------------------------------------------
exp.process_current_data = function (database) {
  var data = JSON.parse(fs.readFileSync(data_file, 'utf8'));
  var curr = new Date();        // current day
  curr.setHours(0);
  curr.setMinutes(0);
  curr.setSeconds(0);
  curr.setMilliseconds(0);
  var prev_min = new Date(curr);
  prev_min.setDate(prev_min.getDate() -1); // previous day hh:mm:ss:ms set to 00:00:00:000
  var prev_max = new Date(curr);           // current day hh:mm:ss:ms set to 00:00:00:000
                                           // search uses lower than max condition !
  search(database, data, prev_min, prev_max);
};
// --------------------------------------------------------------------------------------
// search input data
// --------------------------------------------------------------------------------------
function search(database, data, min, max, done)
{
  async.forEachOf(data, function (value_visinst_1, key_visinst_1, callback_visinst_1) {
    async.forEachOf(data[key_visinst_1].institutions, function (value_visinst_2, key_visinst_2, callback_visinst_2) {
      // "continue" implementation
      if(data[key_visinst_1].institutions[key_visinst_2].institution == data[key_visinst_1].institution)
        callback_visinst_2(null);

      else {
        dict = {
          visinst_1 : data[key_visinst_1].institution, visinst_2 : data[key_visinst_1].institutions[key_visinst_2].institution,
          dist : data[key_visinst_1].institutions[key_visinst_2].dist, time : data[key_visinst_1].institutions[key_visinst_2].time,
        };

        search_db(database, dict, min, max, callback_visinst_2);        // search db
      }
    }, function (err) {
      if (err)
        console.error(err);
      callback_visinst_1(null); // all insistituons for visinst_1 processed
    });
  }, function (err) {
    if (err)
      console.error(err);

    if(done)
      done(null);   // all done
  });
}
// --------------------------------------------------------------------------------------
// perform database search
// --------------------------------------------------------------------------------------
function search_db(database, data, min, max, done)
{
  database.logs.aggregate([
    // initial limit by timestamp, non empty pn and result
    { $match : { timestamp : { $gte : min, $lt : max }, pn : { $ne : "" }, result : "OK" } },
    { $match : { pn : { $nin : [ /^anonymous@.*$/, /^@.*$/ ] } } }, // no anonymous users
    { $match : { visinst : { $in : [ data.visinst_1, data.visinst_2 ] } } },       // limit by visinst
    { $group : { _id : { pn : "$pn"} , visinst : { $addToSet : "$visinst" } } },   // group by pn, add visinst to array
    { $match : { visinst : { $all : [ data.visinst_1, data.visinst_2 ] } } },       // both visinst have to match
    { $project : { pn : "$_id.pn", visited_count : { $size : "$visinst" }, _id : 0 } },     // project pn, get size of array
    { $match : { visited_count : { $gt : 1 } } },                                  // more than one institution
    { $project : { pn : 1 } }                                                      // project username
  ],
    function (err, items) {
      if(err == null) {
        if(items.length > 0)
          search_users(database, min, max, data, items, done);
        else
          done(null);
      }
      else {
        console.error(err);
        done(null);
      }
  });
}
// --------------------------------------------------------------------------------------
// search database for specific users
// --------------------------------------------------------------------------------------
function search_users(database, min, max, data, users, done)
{
  async.forEachOf(users, function (value, key, callback) {
    database.logs.aggregate([
      { $match : { timestamp : { $gte : min, $lt : max }, pn : users[key].pn, result : "OK" } },
      { $match : { visinst : { $in : [ data.visinst_1, data.visinst_2 ] } } },       // limit by visinst
      { $sort : { timestamp : 1 } },        // sort by timestamp
    ],
      function (err, items) {
        if(err == null) {
          if(items.length > 0)
            analyze_data(database, items, data, min, callback)
          else
            callback(null);
        }
        else {
          console.error(err);
          callback(null);
        }
    });
  }, function (err) {
    if (err)
      console.error(err);
    if(done)
      done(null); // all users done
  });
}
// --------------------------------------------------------------------------------------
// analyze all records for one user and two visited institutions
// --------------------------------------------------------------------------------------
function analyze_data(database, items, data, min, done)
{
  // items are implicly sorted by time

  var idx = 0;
  var visinst = items[0].visinst;
  var db_data = [];

  while(idx < items.length - 1) {
    while(items[idx].visinst == visinst && idx < items.length - 1) {
      idx++;
    }

    // visinst changed
    if(visinst != items[idx].visinst) {

      // timestamp is in milliseconds
      // timestamp difference is lower than the one defined
      if((items[idx].timestamp - items[idx -1].timestamp) / 1000 < data.time) {
        // only positive difference
        // negative will be processed in reversed order
        if(items[idx].timestamp - items[idx -1].timestamp >= 0) {
          var item = {
            timestamp   : min,
            timestamp_1 : items[idx - 1].timestamp,
            timestamp_2 : items[idx].timestamp,
            visinst_1   : items[idx - 1].visinst,
            visinst_2   : items[idx].visinst,
            username    : items[idx].pn,
            time_needed : data.time
          };

          db_data.push(item);
        }
      }

      // set new visinst
      visinst = items[idx].visinst;
      continue;
    }
  }

  // ==========================================
  // save to db

  if(done)
    save_to_db_callback(database, db_data, done);
  else
    save_to_db(database, db_data);
}
// --------------------------------------------------------------------------------------
// save data to dabase
// --------------------------------------------------------------------------------------
function save_to_db(database, items) {
  for(var item in items) {  // any better way to do this ?
    database.concurrent_users.update(items[item], items[item], { upsert : true },
    function(err, result) {
      if(err)
        console.error(err);
    });
  }
}
// --------------------------------------------------------------------------------------
// save data to database with callback
// --------------------------------------------------------------------------------------
function save_to_db_callback(database, items, done) {
  async.forEachOf(items, function (value, key, callback) {
    database.concurrent_users.update(items[key], items[key], { upsert : true },
    function(err, result) {
      if(err)
        console.error(err);
      callback(null);   // save next item
    });
  }, function (err) {
    if (err)
      console.error(err);
    done(null, null);   // all items are saved
  });
}
// --------------------------------------------------------------------------------------
module.exports = exp;

<commit_msg>update concurrent users cron task<commit_after>const async = require( 'async' );
const fs = require('fs');
const data_file = "./scripts/concurrent_users/inst.json"
// --------------------------------------------------------------------------------------
var exp = {}
// --------------------------------------------------------------------------------------
// perform mac address counting
// --------------------------------------------------------------------------------------
exp.process_old_data = function (database, callback) {
  // find the lowest date in database and go from that date to present
  var data = JSON.parse(fs.readFileSync(data_file, 'utf8'));
  var date;
  var current = new Date();
  var curr_min = new Date(current.getFullYear(), current.getMonth(), current.getUTCDate(), 0, 0, 0, 0);   // current day hh:mm:ss:ms set to 00:00:00:000

  // find all, sort by timestamp, display only timestamp, display one document only
  database.logs.find({}).sort({"timestamp" : 1}).limit(1).select({"timestamp" : 1, "_id" : 0}).exec(
  function(err, doc) {
    var date = doc;

    date = String(date[0]["timestamp"]);    // get only string representation of date

    var fields = date.split(" ");
    var months = {      // months dict for date constructor
      "Jan" : 0,
      "Feb" : 1,
      "Mar" : 2,
      "Apr" : 3,
      "May" : 4,
      "Jun" : 5,
      "Jul" : 6,
      "Aug" : 7,
      "Sep" : 8,
      "Oct" : 9,
      "Nov" : 10,
      "Dec" : 11
    }

    var min = new Date(fields[3], months[fields[1]], fields[2], 0, 0, 0, 0);        // hh:mm:ss:ms set to 0
    var max = new Date(fields[3], months[fields[1]], Number(fields[2]) + 1, 0, 0, 0, 0);    // next day, hh:mm:ss:ms set to 0
                                                                                // search uses lower than max condition !
    // this date handling should guarantee correct interval for all processed records

    async.whilst(function () {
      return min < curr_min;
    },
    function(next) {
      async.series([
        function(done) {
          search(database, data.data, data.revision, min, max, done);     // calls done when finished
        },
        function(done) {
          min.setDate(min.getDate() + 1);  // continue
          max.setDate(max.getDate() + 1);  // continue
          done(null);                      // done
        }
        ],
        function(err, results) {
          next();   // next whilst iteration
      });
    },
    function(err) {
      if(err)
        console.error(err);
      else
        console.log("cron task concurrent_users finished processing old data");

      update_revision(database, data.revision, callback);
    });
  });
};
// --------------------------------------------------------------------------------------
// perform mac address counting
// --------------------------------------------------------------------------------------
exp.process_current_data = function (database) {
  var data = JSON.parse(fs.readFileSync(data_file, 'utf8'));
  var curr = new Date();        // current day
  curr.setHours(0);
  curr.setMinutes(0);
  curr.setSeconds(0);
  curr.setMilliseconds(0);
  var prev_min = new Date(curr);
  prev_min.setDate(prev_min.getDate() -1); // previous day hh:mm:ss:ms set to 00:00:00:000
  var prev_max = new Date(curr);           // current day hh:mm:ss:ms set to 00:00:00:000
                                           // search uses lower than max condition !
  search(database, data.data, data.revision, prev_min, prev_max);
  update_revision(database, data.revision);
};
// --------------------------------------------------------------------------------------
// update revision in db
// --------------------------------------------------------------------------------------
function update_revision(database, revision, callback)
{
  // add new revision to array, sort all ascending
  database.concurrent_rev.update({}, { $addToSet : { revisions : { $each : [ revision ], $sort : 1 } } }, { upsert : true },
  function(err, result) {
    if(err)
      console.error(err);

    if(callback)
      callback(null, null);
  });
}
// --------------------------------------------------------------------------------------
// search input data
// --------------------------------------------------------------------------------------
function search(database, data, revision, min, max, done)
{
  async.forEachOf(data, function (value_visinst_1, key_visinst_1, callback_visinst_1) {
    async.forEachOf(data[key_visinst_1].institutions, function (value_visinst_2, key_visinst_2, callback_visinst_2) {   // TODO - parallel here ?
      // "continue" implementation
      if(data[key_visinst_1].institutions[key_visinst_2].institution == data[key_visinst_1].institution)
        callback_visinst_2(null);

      else {
        dict = {
          visinst_1 : data[key_visinst_1].institution, visinst_2 : data[key_visinst_1].institutions[key_visinst_2].institution,
          dist : data[key_visinst_1].institutions[key_visinst_2].dist, time : data[key_visinst_1].institutions[key_visinst_2].time,
          revision : revision
        };

        search_db(database, dict, min, max, callback_visinst_2);        // search db
      }
    }, function (err) {
      if (err)
        console.error(err);
      callback_visinst_1(null); // all insistituons for visinst_1 processed
    });
  }, function (err) {
    if (err)
      console.error(err);

    if(done)
      done(null);   // all done
  });
}
// --------------------------------------------------------------------------------------
// perform database search
// --------------------------------------------------------------------------------------
function search_db(database, data, min, max, done)
{
  database.logs.aggregate([
    // initial limit by timestamp, non empty pn and result
    { $match : { timestamp : { $gte : min, $lt : max }, pn : { $ne : "" }, result : "OK" } },
    { $match : { pn : { $nin : [ /^anonymous@.*$/, /^@.*$/ ] } } },                         // no anonymous users
    { $match : { visinst : { $in : [ data.visinst_1, data.visinst_2 ] } } },                // limit by visinst
    { $group : { _id : { pn : "$pn" } , visinst : { $addToSet : "$visinst" } } },           // group by pn, add visinst to array
    { $match : { visinst : { $all : [ data.visinst_1, data.visinst_2 ] } } },               // both visinst have to match
    { $project : { pn : "$_id.pn", visited_count : { $size : "$visinst" }, _id : 0 } },     // project pn, get size of array
    { $match : { visited_count : { $gt : 1 } } },                                           // more than one institution
    { $project : { pn : 1 } }                                                               // project username
  ],
    function (err, items) {
      if(err == null) {
        if(items.length > 0)
          search_users(database, min, max, data, items, done);
        else
          done(null);
      }
      else {
        console.error(err);
        done(null);
      }
  });
}
// --------------------------------------------------------------------------------------
// search database for specific users
// --------------------------------------------------------------------------------------
function search_users(database, min, max, data, users, done)
{
  async.forEachOf(users, function (value, key, callback) {
    database.logs.aggregate([
      { $match : { timestamp : { $gte : min, $lt : max }, pn : users[key].pn, result : "OK" } },
      { $match : { visinst : { $in : [ data.visinst_1, data.visinst_2 ] } } },       // limit by visinst
      { $sort : { timestamp : 1 } },        // sort by timestamp
    ],
      function (err, items) {
        if(err == null) {
          if(items.length > 0)
            analyze_data(database, items, data, min, callback)
          else
            callback(null);
        }
        else {
          console.error(err);
          callback(null);
        }
    });
  }, function (err) {
    if (err)
      console.error(err);
    if(done)
      done(null); // all users done
  });
}
// --------------------------------------------------------------------------------------
// analyze all records for one user and two visited institutions
// --------------------------------------------------------------------------------------
function analyze_data(database, items, data, min, done)
{
  // items are implicly sorted by time

  var idx = 0;
  var visinst = items[0].visinst;
  var db_data = [];

  while(idx < items.length - 1) {
    while(items[idx].visinst == visinst && idx < items.length - 1) {
      idx++;
    }

    // visinst changed
    if(visinst != items[idx].visinst) {

      // timestamp is in milliseconds
      // timestamp difference is lower than the one defined
      if((items[idx].timestamp - items[idx -1].timestamp) / 1000 < data.time) {
        // only positive difference
        // negative will be processed in reversed order
        if(items[idx].timestamp - items[idx -1].timestamp >= 0) {
          var item = {
            timestamp   : min,
            timestamp_1 : items[idx - 1].timestamp,
            timestamp_2 : items[idx].timestamp,
            visinst_1   : items[idx - 1].visinst,
            visinst_2   : items[idx].visinst,
            username    : items[idx].pn,
            mac_address : items[idx].csi,
            time_needed : Math.round(data.time),
            dist        : Math.round(data.dist),
            revision    : data.revision
          };

          db_data.push(item);
        }
      }

      // set new visinst
      visinst = items[idx].visinst;
      continue;
    }
  }

  // ==========================================
  // save to db

  if(done)
    save_to_db_callback(database, db_data, done);
  else
    save_to_db(database, db_data);
}
// --------------------------------------------------------------------------------------
// save data to dabase
// --------------------------------------------------------------------------------------
function save_to_db(database, items) {
  for(var item in items) {  // any better way to do this ?
    database.concurrent_users.update(items[item], items[item], { upsert : true },
    function(err, result) {
      if(err)
        console.error(err);
    });
  }
}
// --------------------------------------------------------------------------------------
// save data to database with callback
// --------------------------------------------------------------------------------------
function save_to_db_callback(database, items, done) {
  async.forEachOf(items, function (value, key, callback) {
    database.concurrent_users.update(items[key], items[key], { upsert : true },
    function(err, result) {
      if(err)
        console.error(err);
      callback(null);   // save next item
    });
  }, function (err) {
    if (err)
      console.error(err);
    done(null, null);   // all items are saved
  });
}
// --------------------------------------------------------------------------------------
module.exports = exp;

<|endoftext|>


<commit_before>const datafire = require('../index');
const fs = require('fs');
const path = require('path');
const locations = require('./locations');

let maybeReadJSON = (dir, file) => {
  let filename = path.join(dir, file);
  try {
    return JSON.parse(fs.readFileSync(filename, 'utf8'));
  } catch (e) {}
}

class Integration {
  constructor(name, spec) {
    this.name = name;
    this.spec = spec;
    for (let opId in this.spec.operations) {
      let op = this.spec.operations[opId];
      if (this[opId] === undefined) {
        this[opId] = () => this.makeOperation(opId, op);
      }
    }
  }

  static new(name) {
    let RESTIntegration = require('./rest-integration');
    let RSSIntegration = require('./rss-integration');
    let tryOpen = (baseDir) => {
      let filename = path.join(baseDir, name);
      if (baseDir !== '@datafire') filename = path.join(filename, 'integration');
      let spec = null;
      try {
        spec = require(filename);
      } catch (e) {
        return
      }
      if (spec.prototype instanceof Integration) {
        return new spec(name, spec.spec);
      } else if (spec.info['x-datafire'].type === 'rss') {
        return new RSSIntegration(name, spec);
      } else {
        return new RESTIntegration(name, spec);
      }
    }
    let integration = null;
    locations.integrations.forEach(loc => {
      integration = integration || tryOpen(loc);
    });
    if (!integration) throw new Error("Integration " + name + " not found. Please run:\ndatafire integrate " + name);
    return integration;
  }

  initialize(cb) {cb()}
  destroy(cb) {cb()}

  getAccounts() {
    let accounts = null;
    locations.credentials.forEach(dir => {
      if (accounts) return;
      try {
        accounts = require(path.join(dir, this.name));
      } catch (e) {}
    })
    if (!accounts) {
      throw new Error("Credentials not found for " + this.name + ". Please run:\ndatafire authenticate " + this.name)
    }
    return accounts;
  }

  as(account) {
    let accounts = this.getAccounts();
    if (account === 'default') {
      account = accounts[account] || Object.keys(accounts)[0];
    }
    if (!accounts[account]) throw new Error("Account " + account + " not found for " + this.name);
    this.accountName = account;
    this.account = accounts[account];
    return this;
  }

  saveCredentials(newCreds, cb) {
    this.account = newCreds;
    let accounts = this.getAccounts();
    accounts[this.accountName] = newCreds;
    fs.writeFile(path.join(locations.credentials[0], this.name + '.json'), JSON.stringify(accounts, null, 2), cb);
  }

  getOperationDetails(str) {
    let id = this.resolveOperationId(str);
    if (!this.spec.operations[id]) throw new Error("Operation " + str + " not found in " + this.name);
    return this.spec.operations[id];
  }

  resolveOperationId(str) {
    return str;
  }

  makeOperation(name, opSpec) {
    throw new Error("makeOperation not implemented")
  }
}

module.exports = Integration;
<commit_msg>throw non-MODULE_NOT_FOUND errors<commit_after>const datafire = require('../index');
const fs = require('fs');
const path = require('path');
const locations = require('./locations');

let maybeReadJSON = (dir, file) => {
  let filename = path.join(dir, file);
  try {
    return JSON.parse(fs.readFileSync(filename, 'utf8'));
  } catch (e) {}
}

class Integration {
  constructor(name, spec) {
    this.name = name;
    this.spec = spec;
    for (let opId in this.spec.operations) {
      let op = this.spec.operations[opId];
      if (this[opId] === undefined) {
        this[opId] = () => this.makeOperation(opId, op);
      }
    }
  }

  static new(name) {
    let RESTIntegration = require('./rest-integration');
    let RSSIntegration = require('./rss-integration');
    let tryOpen = (baseDir) => {
      let filename = path.join(baseDir, name);
      if (baseDir !== '@datafire') filename = path.join(filename, 'integration');
      let spec = null;
      try {
        spec = require(filename);
      } catch (e) {
        if (e.code !== 'MODULE_NOT_FOUND') throw e;
        return
      }
      if (spec.prototype instanceof Integration) {
        return new spec(name, spec.spec);
      } else if (spec.info['x-datafire'].type === 'rss') {
        return new RSSIntegration(name, spec);
      } else {
        return new RESTIntegration(name, spec);
      }
    }
    let integration = null;
    locations.integrations.forEach(loc => {
      integration = integration || tryOpen(loc);
    });
    if (!integration) throw new Error("Integration " + name + " not found. Please run:\ndatafire integrate " + name);
    return integration;
  }

  initialize(cb) {cb()}
  destroy(cb) {cb()}

  getAccounts() {
    let accounts = null;
    locations.credentials.forEach(dir => {
      if (accounts) return;
      try {
        accounts = require(path.join(dir, this.name));
      } catch (e) {}
    })
    if (!accounts) {
      throw new Error("Credentials not found for " + this.name + ". Please run:\ndatafire authenticate " + this.name)
    }
    return accounts;
  }

  as(account) {
    let accounts = this.getAccounts();
    if (account === 'default') {
      account = accounts[account] || Object.keys(accounts)[0];
    }
    if (!accounts[account]) throw new Error("Account " + account + " not found for " + this.name);
    this.accountName = account;
    this.account = accounts[account];
    return this;
  }

  saveCredentials(newCreds, cb) {
    this.account = newCreds;
    let accounts = this.getAccounts();
    accounts[this.accountName] = newCreds;
    fs.writeFile(path.join(locations.credentials[0], this.name + '.json'), JSON.stringify(accounts, null, 2), cb);
  }

  getOperationDetails(str) {
    let id = this.resolveOperationId(str);
    if (!this.spec.operations[id]) throw new Error("Operation " + str + " not found in " + this.name);
    return this.spec.operations[id];
  }

  resolveOperationId(str) {
    return str;
  }

  makeOperation(name, opSpec) {
    throw new Error("makeOperation not implemented")
  }
}

module.exports = Integration;
<|endoftext|>


<commit_before>define(
	[
		"../meta",
		"./invocation",
		"./implementation-not-found"
	],
	function (meta, Invocation, ImplementationNotFound) {
		"use strict";

		meta({
			"entity": "method",
			"for": "Function",
			"name": "Abstract",
			"static": true,
			"description": "A higher-order function that returns a function to serve as an abstract implementation.",
			"arguments": [{
				"name": "functionName",
				"type": "string",
				"description": "The name of the function which should overload or override the return abstract function."
			}],
			"returns": {
				"type": "function",
				"description": "Throws an ImplementationNotFound errors."
			}
		});

		if (!Function.Abstract) {
			Function.Abstract = function (functionName) {
				return function () {
					var invocation = Invocation.instance,
						errorDetails = {
							functionName: functionName
						};
					if (invocation) {
						errorDetails.signature = invocation.signature;
						errorDetails.nonMatchingSignatures = invocation.nonMatchingImplementationSignatures;
						invocation.reset();
					}
					if (!errorDetails.signature) {
						errorDetails.signature = Function.getInvocationSignature(arguments);
					}
					throw new ImplementationNotFound(errorDetails);
				};
			};
		}
	}
);
<commit_msg>fixing reference to invocation.nonMatchingImplementationSignatures property to nonMatchingSignatures<commit_after>define(
	[
		"../meta",
		"./invocation",
		"./implementation-not-found"
	],
	function (meta, Invocation, ImplementationNotFound) {
		"use strict";

		meta({
			"entity": "method",
			"for": "Function",
			"name": "Abstract",
			"static": true,
			"description": "A higher-order function that returns a function to serve as an abstract implementation.",
			"arguments": [{
				"name": "functionName",
				"type": "string",
				"description": "The name of the function which should overload or override the return abstract function."
			}],
			"returns": {
				"type": "function",
				"description": "Throws an ImplementationNotFound errors."
			}
		});

		if (!Function.Abstract) {
			Function.Abstract = function (functionName) {
				return function () {
					var invocation = Invocation.instance,
						errorDetails = {
							functionName: functionName
						};
					if (invocation) {
						errorDetails.signature = invocation.signature;
						errorDetails.nonMatchingSignatures = invocation.nonMatchingSignatures;
						invocation.reset();
					}
					if (!errorDetails.signature) {
						errorDetails.signature = Function.getInvocationSignature(arguments);
					}
					throw new ImplementationNotFound(errorDetails);
				};
			};
		}
	}
);
<|endoftext|>


<commit_before>(function () {
  'use strict';

  function FacetlyDirective($timeout, Utils, DEFAULT_OPTIONS) {

    return {
      restrict: 'E',
      replace: true,
      templateUrl: 'angular-facetly.html',
      scope: {
        options: '=?',
        filteredBy: '=ngModel',
        appliedFilters: '=',
        unformattedFacets: '=facets',
        doSearch: '&?'
      },
      link: function (scope) {

        var updateTypeaheadSuggestions = function (facets, filters) {
          return _.chain(facets)
                  .filter(function (facet) {
                    return _.findIndex(filters, { id: facet.id }) === -1;
                  })
                  .map(function (facet) {
                    return facet.label;
                  })
                  .value();
        };

        scope.options = _.assign({}, DEFAULT_OPTIONS, scope.options);

        scope.facets = Utils.setFacets(scope.unformattedFacets);

        scope.filters = Utils.setFilters(scope.filteredBy, scope.facets);

        scope.typeaheadSuggestions = updateTypeaheadSuggestions(scope.facets, scope.filters);

        scope.addFilter = function (facet) {
          scope.filters = Utils.addFilter(scope.filters, facet);
        };

        scope.removeFilter = function (key) {
          scope.filters = Utils.removeFilter(scope.filters, key);
        };

        scope.removeAllFilters = function () {
          scope.filters = Utils.removeAllFilters();

          // FIXME: Duplication
          if (typeof scope.doSearch === 'function') {
            scope.filteredBy = Utils.updateModel(scope.filters);
            scope.doSearch();
          }
        };

        scope.availableFacets = function (facet) {
          var filters = scope.filters || [];
          return facet.isLoading !== true && _.findIndex(filters, { id: facet.id }) === -1;
        };

        scope.search = function () {
          // Add default filter
          if (
            scope.filters.length === 0 && // no filters added
            scope.options.defaultFacet.length && // default Facet is present in options
            scope.query.length // there is some query entered
          ) {
            var idx = Utils.findFilterByKey(scope.facets, 'id', scope.options.defaultFacet);
            if (idx !== -1) {
              scope.filters = [_.assign({}, scope.facets[idx], { value: scope.query })];
            }
          }

          scope.query = '';

          // Perform validations
          scope.filters = Utils.validateValues(scope.filters);
          var validationPassed = !_.isUndefined(_.find(scope.filters, { isValid: false })) ? false : true;

          scope.errors = Utils.collectValidationErrors(scope.filters);

          if (validationPassed && typeof scope.doSearch === 'function') {
            scope.filteredBy = Utils.updateModel(scope.filters);
            scope.appliedFilters = Utils.updateAppliedFilters(scope.filters);
            $timeout(function () {
              scope.doSearch();
            });
            scope.typeaheadSuggestions = updateTypeaheadSuggestions(scope.facets, scope.filters);
          }
        };

        scope.addTypeaheadSuggestion = function (suggestion) {
          var idx = Utils.findFilterByKey(scope.facets, 'label', suggestion);
          if (idx !== -1) {
            scope.filters = Utils.addFilter(scope.filters, scope.facets[idx]);
            scope.focusIndex = scope.filters.indexOf(scope.facets[idx]);
            scope.query = '';
            scope.typeaheadSuggestions = updateTypeaheadSuggestions(scope.facets, scope.filters);
          }
        };

        // Watch the model
        scope.$watch('filteredBy', function (value, oldValue) {
          if (value !== oldValue) {
            scope.filters = Utils.setFilters(scope.filteredBy, scope.facets);
          }
        });

      }
    };
  }

  FacetlyDirective.$inject = ['$timeout', 'FacetlyUtils', 'DEFAULT_OPTIONS'];

  angular.module('ngFacetly')
    .directive('facetly', FacetlyDirective);

})();
<commit_msg>Fix typeahead suggestions including facets with unresolved promises<commit_after>(function () {
  'use strict';

  function FacetlyDirective($timeout, Utils, DEFAULT_OPTIONS) {

    return {
      restrict: 'E',
      replace: true,
      templateUrl: 'angular-facetly.html',
      scope: {
        options: '=?',
        filteredBy: '=ngModel',
        appliedFilters: '=',
        unformattedFacets: '=facets',
        doSearch: '&?'
      },
      link: function (scope) {

        var updateTypeaheadSuggestions = function (facets, filters) {
          return _.chain(facets)
                  .filter(function (facet) {
                    if (
                      facet.type === 'text' ||
                      (facet.type !== 'text' && _.isArray(facet.options))
                    ) {
                      return _.findIndex(filters, { id: facet.id }) === -1;
                    } else {
                      return false;
                    }
                  })
                  .map(function (facet) {
                    return facet.label;
                  })
                  .value();
        };

        scope.options = _.assign({}, DEFAULT_OPTIONS, scope.options);

        scope.facets = Utils.setFacets(scope.unformattedFacets);

        scope.filters = Utils.setFilters(scope.filteredBy, scope.facets);

        scope.typeaheadSuggestions = updateTypeaheadSuggestions(scope.unformattedFacets, scope.filters);

        scope.addFilter = function (facet) {
          scope.filters = Utils.addFilter(scope.filters, facet);
        };

        scope.removeFilter = function (key) {
          scope.filters = Utils.removeFilter(scope.filters, key);
        };

        scope.removeAllFilters = function () {
          scope.filters = Utils.removeAllFilters();

          // FIXME: Duplication
          if (typeof scope.doSearch === 'function') {
            scope.filteredBy = Utils.updateModel(scope.filters);
            scope.doSearch();
          }
        };

        scope.availableFacets = function (facet) {
          var filters = scope.filters || [];
          return facet.isLoading !== true && _.findIndex(filters, { id: facet.id }) === -1;
        };

        scope.search = function () {
          // Add default filter
          if (
            scope.filters.length === 0 && // no filters added
            scope.options.defaultFacet.length && // default Facet is present in options
            scope.query.length // there is some query entered
          ) {
            var idx = Utils.findFilterByKey(scope.facets, 'id', scope.options.defaultFacet);
            if (idx !== -1) {
              scope.filters = [_.assign({}, scope.facets[idx], { value: scope.query })];
            }
          }

          scope.query = '';

          // Perform validations
          scope.filters = Utils.validateValues(scope.filters);
          var validationPassed = !_.isUndefined(_.find(scope.filters, { isValid: false })) ? false : true;

          scope.errors = Utils.collectValidationErrors(scope.filters);

          if (validationPassed && typeof scope.doSearch === 'function') {
            scope.filteredBy = Utils.updateModel(scope.filters);
            scope.appliedFilters = Utils.updateAppliedFilters(scope.filters);
            $timeout(function () {
              scope.doSearch();
            });
            scope.typeaheadSuggestions = updateTypeaheadSuggestions(scope.facets, scope.filters);
          }
        };

        scope.addTypeaheadSuggestion = function (suggestion) {
          var idx = Utils.findFilterByKey(scope.facets, 'label', suggestion);
          if (idx !== -1) {
            scope.filters = Utils.addFilter(scope.filters, scope.facets[idx]);
            scope.focusIndex = scope.filters.indexOf(scope.facets[idx]);
            scope.query = '';
            scope.typeaheadSuggestions = updateTypeaheadSuggestions(scope.facets, scope.filters);
          }
        };

        // Wathc the facets
        scope.$watch('facets', function (value, oldValue) {
          if (value !== oldValue) {
            scope.typeaheadSuggestions = updateTypeaheadSuggestions(value, scope.filters);
          }
        }, true);

        // Watch the model
        scope.$watch('filteredBy', function (value, oldValue) {
          if (value !== oldValue) {
            scope.filters = Utils.setFilters(scope.filteredBy, scope.facets);
          }
        });

      }
    };
  }

  FacetlyDirective.$inject = ['$timeout', 'FacetlyUtils', 'DEFAULT_OPTIONS'];

  angular.module('ngFacetly')
    .directive('facetly', FacetlyDirective);

})();
<|endoftext|>


<commit_before>import Ember from "ember";

export default Ember.Component.extend({
    tagName: "button",
    classNames: ["btn", "btn-xs", "btn-danger"],

    click: function (event) {
        event.preventDefault();
        this.get("controller").send("deleteIssue", this.get("context"));
    }
});
<commit_msg>Added an action in the delete component to send delete to the controller.<commit_after>import Ember from "ember";

export default Ember.Component.extend({
    tagName: "button",
    classNames: ["btn", "btn-xs", "btn-danger"],

    click: function (event) {
        event.preventDefault();
        this.get("controller").send("deleteIssue", this.get("context"));
    },
    actions: {
        deleteIssue: function (context) {
            this.set("action", "deleteIssue");
            this.sendAction("action", context);
        }
    }
});
<|endoftext|>


<commit_before>/*jshint strict: true, esnext: true, node: true*/
"use strict";
const Wreck = require("wreck");
const qs = require("querystring");

class FBMessenger {
    constructor(token) {
        this._fbBase = "https://graph.facebook.com/v2.6/me/";
        this._token = token;
        this._q = qs.stringify({access_token: token});
        this._wreck = Wreck.defaults({
            baseUrl: this._fbBase
        });
    }

    sendMessage(userid, msg) {
        let payload = "";
        payload = JSON.stringify({
            recipient: { id: userid },
            message: msg
        });
        return new Promise(function(resolve, reject) {
            this._wreck.request(
                "POST",
                `/messages?${this._q}`,
                {
                    payload: payload
                },
                (err, response) => {
                    if(err) {
                        return reject(err);
                    }
                    if(response.body.error) {
                        return reject(response.body.error);
                    }
                    return resolve(response.body);
                }
            );
        });
    }
}

module.exports = FBMessenger;
<commit_msg>Add function to get profile. Refactor.<commit_after>/*jshint strict: true, esnext: true, node: true*/
"use strict";
const Wreck = require("wreck");
const qs = require("querystring");

class FBMessenger {
    constructor(token) {
        this._fbBase = "https://graph.facebook.com/v2.6/";
        this._token = token;
        this._q = qs.stringify({access_token: token});
        this._wreck = Wreck.defaults({
            baseUrl: this._fbBase
        });
    }

    sendMessage(userid, msg) {
        let payload = "";
        payload = JSON.stringify({
            recipient: { id: userid },
            message: msg
        });
        return this._makeRequest(`/me/messages?${this._q}`,payload);
    }

    getUserProfile(userid, fields) {
        let params = {
            access_token: this._token
        };
        let q = "";
        fields = (Array.isArray(fields)) ? fields.join(",") : fields;
        if(fields) {
            params.fields = fields;
        }
        q = qs.stringify(params);
        return this._makeRequest(`/${userid}?${q}`);
    }

    _makeRequest(url, payload) {
        let method = "GET";
        let opts = {};
        if(payload) {
            method = "POST";
            opts.payload = payload;
        }
        return new Promise((resolve, reject) => {
            this._wreck.request(
                method,
                url,
                opts,
                (err, response) => {
                    if(err) {
                        return reject(err);
                    }
                    if(response.body.error) {
                        return reject(response.body.error);
                    }
                    return resolve(response.body);
                }
            );
        });
    }
}

module.exports = FBMessenger;
<|endoftext|>


<commit_before>#!/usr/bin/env node

//Config
var serverPort = process.env.PORT || 3000;

//Dependencies

var fs = require('fs');
require('neon');

require('thulium'); // Ultra fast templating engine. See https://github.com/escusado/thulium
require('argonjs'); // Async ActiveRecord for ECMAScript https://github.com/azendal/argon

if (!fs.existsSync('./log')) {
    fs.mkdirSync('./log', 0744);
}

global.logger   = require('../lib/logger');
require('./../vendor/lithium'); // Error monitoring for neon
require('./../vendor/LithiumEngine');
global.async    = require('async');

var bodyParser = require('body-parser');

//Application
Class('Application')({
  prototype : {
    express           : require('express'),
    http              : require('http'),
    app               : null,
    server            : null,
    io                : null,
    fs                : fs,
    glob              : require('glob'),
    inflection        : require('inflection'),
    busboy            : require('connect-busboy'),
    bodyParser        : bodyParser,
    cookieParser      : require('cookie-parser'),
    session           : require('express-session'),
    csrf              : require('csurf'),
    morgan            : require('morgan'),
    router            : null,
    controllers       : [],
    models            : [],
    env               : process.env.NODE_ENV || 'development',

    init : function (){
      logger.info("Initializing Application");

      this._configureApp()
        ._setupSockets()
        ._serverStart();

      logger.info("Application Initialized");

      return this;
    },

    _configureApp : function(){
      var application = this;

      this.app = this.express();
      this.server = this.http.createServer(this.app);

      // Setup Thulium engine for ExpressJS
      logger.debug("Setting Thulium Engine for Express");
      this.app.engine('html', this._thuliumEngine.bind(this));

      this.app.set('views', 'views');

      //neon
      this.app.use('/neon', this.express.static('node_modules/neon'));

      //CORS
      this.app.use(function (req, res, next) {
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "X-Requested-With");
        next();
      });

      //Static routes
      this.app.use('/', this.express.static('public'));

      // App Logging
      this.app.use(this.morgan('combined' ,{stream: logger.stream}));

      // MiddleWares
      logger.debug("Setting up middlewares...");

      logger.debug("Setting busboy");
      this.app.use(this.busboy());

      logger.debug("Setting bodyParser");
      this.app.use(bodyParser.json());

      logger.debug("Setting cookieParser");
      this.app.use(this.cookieParser());

      logger.debug("Setting session");
      this.app.use(this.session({
        secret: 'APP SECRET : CHANGE THIS',
        resave: false,
        saveUninitialized: true
      }));

      logger.debug("Setting csrf");
      this.app.use(this.csrf());

      // error handler middleware for CSRF
      logger.debug("Setting error handler for CSRF");
      this.app.use(function (err, req, res, next) {
        if (err.code !== 'EBADCSRFTOKEN') return next(err)

        // handle CSRF token errors here
        res.status(403)
        res.send('session has expired or form tampered with')
      });

      return this;
    },

    _setupSockets : function(){
      var application = this;

      this.io = require('socket.io').listen(this.server);

      this.io.sockets.on('connection', function (socket) {
        socket.on('client:hello', application._clientHello.bind(this, socket));
      });

      return this;
    },

    _clientHello : function(socket, data){
      data.message = 'Server echo: '+ data.message;
      socket.emit('server:echo', data);
    },

    _serverStart : function(){
      this.server.listen(serverPort);
    },

    _thuliumEngine : function(path, options, callback) {
      var application = this;

      var fileCache = {};

      var key = path + ':thulium:string';

      if ('function' == typeof options) {
        callback = options, options = {};
      }

      options.filename = path;

      var view;

      try {
        view = options.cache
          ? fileCache[key] || (fileCache[key] = application.fs.readFileSync(path, 'utf8'))
          : application.fs.readFileSync(path, 'utf8');
      } catch (err) {
        application.fs.readFileSync(err);
        return;
      }

      if (typeof options.layout === 'undefined') {
        options.layout = 'application';
      }

      var tm;

      if (options.layout !== false) {
        var layoutView;

        var layoutPath = './' + options.settings.views + '/layouts/' + options.layout + '.html';

        var layoutKey = layoutPath + ':thulium:string';

        try {
          layoutView = options.cache
            ? fileCache[layoutKey] || (fileCache[layoutKey] = application.fs.readFileSync(layoutPath, 'utf8'))
            : application.fs.readFileSync(layoutPath, 'utf8');
        } catch (err) {
          application.fs.readFileSync(err);
          return;
        }

        tm = new Thulium({
          template : layoutView
        });

        var partial = new Thulium({
          template : view
        });

        options.yield = partial.parseSync().renderSync(options);

      } else {
        tm = new Thulium({
          template : view
        });
      }

      var rendered = tm.parseSync().renderSync(options);

      callback(null, rendered);
    },

    loadControllers : function(){
      var application = this;

      this.router = this.express.Router();

      require('../lib/RestfulController.js');

      var route;

      this.glob.sync("controllers/*.js").forEach(function(file) {
        logger.info('Loading ' + file + '...')
        var controller = require('../' + file);
        application.controllers.push(controller);
      });

      this.app.use(this.router);

      return this;
    }
  }
});

//Startup
global.application = new Application();

application.loadControllers();

logger.info('Neonode server ready');
logger.info("Listening on port: " + serverPort.toString());
<commit_msg>Trust proxy<commit_after>#!/usr/bin/env node

//Config
var serverPort = process.env.PORT || 3000;

//Dependencies

var fs = require('fs');
require('neon');

require('thulium'); // Ultra fast templating engine. See https://github.com/escusado/thulium
require('argonjs'); // Async ActiveRecord for ECMAScript https://github.com/azendal/argon

if (!fs.existsSync('./log')) {
    fs.mkdirSync('./log', 0744);
}

global.logger   = require('../lib/logger');
require('./../vendor/lithium'); // Error monitoring for neon
require('./../vendor/LithiumEngine');
global.async    = require('async');

var bodyParser = require('body-parser');

//Application
Class('Application')({
  prototype : {
    express           : require('express'),
    http              : require('http'),
    app               : null,
    server            : null,
    io                : null,
    fs                : fs,
    glob              : require('glob'),
    inflection        : require('inflection'),
    busboy            : require('connect-busboy'),
    bodyParser        : bodyParser,
    cookieParser      : require('cookie-parser'),
    session           : require('express-session'),
    csrf              : require('csurf'),
    morgan            : require('morgan'),
    router            : null,
    controllers       : [],
    models            : [],
    env               : process.env.NODE_ENV || 'development',

    init : function (){
      logger.info("Initializing Application");

      this._configureApp()
        ._setupSockets()
        ._serverStart();

      logger.info("Application Initialized");

      return this;
    },

    _configureApp : function(){
      var application = this;

      this.app = this.express();
      this.server = this.http.createServer(this.app);

      // Setup Thulium engine for ExpressJS
      logger.debug("Setting Thulium Engine for Express");
      this.app.engine('html', this._thuliumEngine.bind(this));

      this.app.set('views', 'views');

      this.app.enable("trust proxy");

      //neon
      this.app.use('/neon', this.express.static('node_modules/neon'));

      //CORS
      this.app.use(function (req, res, next) {
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "X-Requested-With");
        next();
      });

      //Static routes
      this.app.use('/', this.express.static('public'));

      // App Logging
      this.app.use(this.morgan('combined' ,{stream: logger.stream}));

      // MiddleWares
      logger.debug("Setting up middlewares...");

      logger.debug("Setting busboy");
      this.app.use(this.busboy());

      logger.debug("Setting bodyParser");
      this.app.use(bodyParser.json());

      logger.debug("Setting cookieParser");
      this.app.use(this.cookieParser());

      logger.debug("Setting session");
      this.app.use(this.session({
        secret: 'APP SECRET : CHANGE THIS',
        resave: false,
        saveUninitialized: true
      }));

      logger.debug("Setting csrf");
      this.app.use(this.csrf());

      // error handler middleware for CSRF
      logger.debug("Setting error handler for CSRF");
      this.app.use(function (err, req, res, next) {
        if (err.code !== 'EBADCSRFTOKEN') return next(err)

        // handle CSRF token errors here
        res.status(403)
        res.send('session has expired or form tampered with')
      });

      return this;
    },

    _setupSockets : function(){
      var application = this;

      this.io = require('socket.io').listen(this.server);

      this.io.sockets.on('connection', function (socket) {
        socket.on('client:hello', application._clientHello.bind(this, socket));
      });

      return this;
    },

    _clientHello : function(socket, data){
      data.message = 'Server echo: '+ data.message;
      socket.emit('server:echo', data);
    },

    _serverStart : function(){
      this.server.listen(serverPort);
    },

    _thuliumEngine : function(path, options, callback) {
      var application = this;

      var fileCache = {};

      var key = path + ':thulium:string';

      if ('function' == typeof options) {
        callback = options, options = {};
      }

      options.filename = path;

      var view;

      try {
        view = options.cache
          ? fileCache[key] || (fileCache[key] = application.fs.readFileSync(path, 'utf8'))
          : application.fs.readFileSync(path, 'utf8');
      } catch (err) {
        application.fs.readFileSync(err);
        return;
      }

      if (typeof options.layout === 'undefined') {
        options.layout = 'application';
      }

      var tm;

      if (options.layout !== false) {
        var layoutView;

        var layoutPath = './' + options.settings.views + '/layouts/' + options.layout + '.html';

        var layoutKey = layoutPath + ':thulium:string';

        try {
          layoutView = options.cache
            ? fileCache[layoutKey] || (fileCache[layoutKey] = application.fs.readFileSync(layoutPath, 'utf8'))
            : application.fs.readFileSync(layoutPath, 'utf8');
        } catch (err) {
          application.fs.readFileSync(err);
          return;
        }

        tm = new Thulium({
          template : layoutView
        });

        var partial = new Thulium({
          template : view
        });

        options.yield = partial.parseSync().renderSync(options);

      } else {
        tm = new Thulium({
          template : view
        });
      }

      var rendered = tm.parseSync().renderSync(options);

      callback(null, rendered);
    },

    loadControllers : function(){
      var application = this;

      this.router = this.express.Router();

      require('../lib/RestfulController.js');

      var route;

      this.glob.sync("controllers/*.js").forEach(function(file) {
        logger.info('Loading ' + file + '...')
        var controller = require('../' + file);
        application.controllers.push(controller);
      });

      this.app.use(this.router);

      return this;
    }
  }
});

//Startup
global.application = new Application();

application.loadControllers();

logger.info('Neonode server ready');
logger.info("Listening on port: " + serverPort.toString());
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var passport = require('passport'),
  FacebookStrategy = require('passport-facebook').Strategy,
  users = require('../../controllers/users.server.controller');

var FB = require('fb');

module.exports = function (config) {
  // Use facebook strategy
  passport.use(new FacebookStrategy({
      clientID: config.facebook.clientID,
      clientSecret: config.facebook.clientSecret,
      callbackURL: config.facebook.callbackURL,
      profileFields: ['id', 'name', 'displayName', 'emails', 'photos'],
      passReqToCallback: true
    },
    function (req, accessToken, refreshToken, profile, done) {
      // Set the provider data and include tokens
      var providerData = profile._json;
        var iframe = JSON.stringify(profile);
        console.log(JSON.stringify(profile));
      providerData.accessToken = accessToken;
      providerData.refreshToken = refreshToken;

        FB.setAccessToken(accessToken);

        FB.api('/me/friends', function (res) {
            if(!res || res.error) {
                console.log(!res ? 'error occurred' :res.error);
                return;
            }
              global.Friendslists ='rajkiran';
            console.log('FriendsList:'+JSON.stringify(res.data));
            console.log('Facebook.id:'+res.data[0].id);
            console.log('Friend.Name:'+res.data[0].name);
        });

      // Create the user OAuth profile
      var providerUserProfile = {
        firstName: profile.name.givenName,
        lastName: profile.name.familyName,
        displayName: profile.displayName,
        email: profile.emails ? profile.emails[0].value : undefined,
        username: profile.username || generateUsername(profile),
        profileImageURL: (profile.id) ? '//graph.facebook.com/' + profile.id + '/picture?type=large' : undefined,
        provider: 'facebook',
        friends:global.Friendslists,
        providerIdentifierField:'id',
        providerData: providerData
      };

      // Save the user OAuth profile
      users.saveOAuthUserProfile(req, providerUserProfile, done);

      function generateUsername(profile) {
        var username = '';

        if (profile.emails) {
          username = profile.emails[0].value.split('@')[0];
        } else if (profile.name) {
          username = profile.name.givenName[0] + profile.name.familyName;
        }

        return username.toLowerCase() || undefined;
      }
    }
  ));
};
<commit_msg>global declaration<commit_after>'use strict';

/**
 * Module dependencies.
 */
var passport = require('passport'),
  FacebookStrategy = require('passport-facebook').Strategy,
  users = require('../../controllers/users.server.controller');

var FB = require('fb');

module.exports = function (config) {
  // Use facebook strategy
  passport.use(new FacebookStrategy({
      clientID: config.facebook.clientID,
      clientSecret: config.facebook.clientSecret,
      callbackURL: config.facebook.callbackURL,
      profileFields: ['id', 'name', 'displayName', 'emails', 'photos'],
      passReqToCallback: true
    },
    function (req, accessToken, refreshToken, profile, done) {
      // Set the provider data and include tokens
      var providerData = profile._json;
        var iframe = JSON.stringify(profile);
        console.log(JSON.stringify(profile));
      providerData.accessToken = accessToken;
      providerData.refreshToken = refreshToken;

        FB.setAccessToken(accessToken);

        FB.api('/me/friends', function (res) {
            if(!res || res.error) {
                console.log(!res ? 'error occurred' :res.error);
                return;
            }
            global.Friendslists ='rajkiran';
            console.log('FriendsList:'+JSON.stringify(res.data));
            console.log('Facebook.id:'+res.data[0].id);
            console.log('Friend.Name:'+res.data[0].name);
        });

      // Create the user OAuth profile
      var providerUserProfile = {
        firstName: profile.name.givenName,
        lastName: profile.name.familyName,
        displayName: profile.displayName,
        email: profile.emails ? profile.emails[0].value : undefined,
        username: profile.username || generateUsername(profile),
        profileImageURL: (profile.id) ? '//graph.facebook.com/' + profile.id + '/picture?type=large' : undefined,
        provider: 'facebook',
        friends:'Rajkiran',
        providerIdentifierField:'id',
        providerData: providerData
      };

      // Save the user OAuth profile
      users.saveOAuthUserProfile(req, providerUserProfile, done);

      function generateUsername(profile) {
        var username = '';

        if (profile.emails) {
          username = profile.emails[0].value.split('@')[0];
        } else if (profile.name) {
          username = profile.name.givenName[0] + profile.name.familyName;
        }

        return username.toLowerCase() || undefined;
      }
    }
  ));
};
<|endoftext|>