<commit_before>/*global require, module */

const config = require('/etc/xray/config.json');
const pg = require('pg');
const logger = require('./logger.js');

const db_cfg = config.scraper.db;
db_cfg.max = 10;
db_cfg.idleTimeoutMillis = 30000;

//this initializes a connection pool
//it will keep idle connections open for 30 seconds
//and set a limit of maximum 10 idle clients
const pool = new pg.Pool(db_cfg);

pool.on('error', function(err) {
    logger.err('idle client error '+ err.message + err.stack);
});

//export the query method for passing queries to the pool
function query(text, values) {
    logger.debug('query:'+ text+ values);
    return pool.query(text, values);
}

// the pool also supports checking out a client for
// multiple operations, such as a transaction
function connect() {
    return pool.connect();
}

async function insertDev(dev) {
    var res = await query('SELECT id FROM developers WHERE $1 = ANY(email)', [dev.email]);
    if (res.length > 0) {
        return res.rows[0].id;
    }

    // maybe dev id needs to be URL encoded?
    let store_site = 'https://play.google.com/store/apps/developer?id=' + dev.id;
    res = await query('INSERT INTO developers(email,name,store_site,site) VALUES ($1, $2, $3, $4) RETURNING id', [
        [dev.email], dev.name, store_site, dev.site
    ]);
    return res.rows[0].id;
}

module.exports = {
    insertPlayApp: async(app, region) => {

        var devId = await insertDev({
            name: app.developer,
            id: app.developerId,
            email: app.developerEmail,
            site: app.developerWebsite
        });

        var appExists = false,
            verExists = false;
        var verId;
        var res = await query('SELECT * FROM apps WHERE id = $1', [app.appId]);

        if (res.length > 0) {
            appExists = true;
            // app exists in database, check if version does as well
            var res1 = await query(
                'SELECT id FROM app_versions WHERE app = $1 AND store = $2 AND region = $3 AND version = $4', [app.appId, 'play', region, app.version]);

            if (res1.length > 0) {
                // app version is also in database
                verExists = true;
                verId = res1.rows[0].id;
            }
        }

        var client = await connect();
        logger.debug('Connected');

        await client.query('BEGIN'); // maybe this should be inside the try?
        try {
            if (!verExists) {
                if (!appExists) {
                    await client.query('INSERT INTO apps VALUES ($1, $2)', [app.appId, []]);
                }

                let res = await client.query(
                    'INSERT INTO app_versions(app, store, region, version,downloaded) VALUES ($1, $2, $3, $4, $5) RETURNING id', [app.appId, 'play', region, app.version, app.isDownloaded]
                );
                verId = res.rows[0].id;

                await client.query('UPDATE apps SET versions=versions || $1 WHERE id = $2', [
                    [verId], app.appId
                ]);

            }

            await client.query(
                'INSERT INTO playstore_apps VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21)', [
                    verId,
                    app.title,
                    app.summary,
                    app.description,
                    app.url,
                    app.price,
                    app.free,
                    app.score,
                    app.reviews,
                    app.genreId,
                    app.familyGenreId,
                    app.minInstalls,
                    app.maxInstalls,
                    devId,
                    app.updated,
                    app.androidVersion,
                    app.contentRating,
                    app.screenshots,
                    app.video,
                    app.recentChanges,
                    new Date().toDateString()
                ]);
            await client.query('COMMIT');
        } catch (e) {
            await client.query('ROLLBACK');
            throw e;
        } finally {
            client.release();
        }
        return verId;
    }
};

if (!module.parent)  {
    query('SELECT * FROM developers');
}<commit_msg>fixed checks for existing db entries<commit_after>/*global require, module */

const config = require('/etc/xray/config.json');
const pg = require('pg');
const logger = require('./logger.js');

const db_cfg = config.scraper.db;
db_cfg.max = 10;
db_cfg.idleTimeoutMillis = 30000;

//this initializes a connection pool
//it will keep idle connections open for 30 seconds
//and set a limit of maximum 10 idle clients
const pool = new pg.Pool(db_cfg);

pool.on('error', function(err) {
    logger.err('idle client error '+ err.message + err.stack);
});

//export the query method for passing queries to the pool
function query(text, values) {
    logger.debug('query:'+ text+ values);
    return pool.query(text, values);
}

// the pool also supports checking out a client for
// multiple operations, such as a transaction
function connect() {
    return pool.connect();
}

async function insertDev(dev) {
    var res = await query('SELECT id FROM developers WHERE $1 = ANY(email)', [dev.email]);
    if (res.rowCount > 0) {
        return res.rows[0].id;
    }

    // maybe dev id needs to be URL encoded?
    let store_site = 'https://play.google.com/store/apps/developer?id=' + dev.id;
    res = await query('INSERT INTO developers(email,name,store_site,site) VALUES ($1, $2, $3, $4) RETURNING id', [
        [dev.email], dev.name, store_site, dev.site
    ]);
    return res.rows[0].id;
}

module.exports = {
    insertPlayApp: async(app, region) => {

        var devId = await insertDev({
            name: app.developer,
            id: app.developerId,
            email: app.developerEmail,
            site: app.developerWebsite
        });

        var appExists = false,
            verExists = false;
        var verId;
        var res = await query('SELECT * FROM apps WHERE id = $1', [app.appId]);

        if (res.rowCount > 0) {
            appExists = true;
            // app exists in database, check if version does as well
            var res1 = await query(
                'SELECT id FROM app_versions WHERE app = $1 AND store = $2 AND region = $3 AND version = $4', [app.appId, 'play', region, app.version]);

            if (res1.rowCount > 0) {
                // app version is also in database
                verExists = true;
                verId = res1.rows[0].id;
            }
        }

        var client = await connect();
        logger.debug('Connected');

        await client.query('BEGIN'); // maybe this should be inside the try?
        try {
            if (!verExists) {
                if (!appExists) {
                    await client.query('INSERT INTO apps VALUES ($1, $2)', [app.appId, []]);
                }

                let res = await client.query(
                    'INSERT INTO app_versions(app, store, region, version, downloaded) VALUES ($1, $2, $3, $4, $5) RETURNING id',
                    [app.appId, 'play', region, app.version, app.isDownloaded]
                );
                verId = res.rows[0].id;

                await client.query('UPDATE apps SET versions=versions || $1 WHERE id = $2', [
                    [verId], app.appId
                ]);

            }

            await client.query(
                'INSERT INTO playstore_apps VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21)', [
                    verId,
                    app.title,
                    app.summary,
                    app.description,
                    app.url,
                    app.price,
                    app.free,
                    app.score,
                    app.reviews,
                    app.genreId,
                    app.familyGenreId,
                    app.minInstalls,
                    app.maxInstalls,
                    devId,
                    app.updated,
                    app.androidVersion,
                    app.contentRating,
                    app.screenshots,
                    app.video,
                    app.recentChanges,
                    new Date().toDateString()
                ]);
            await client.query('COMMIT');
        } catch (e) {
            await client.query('ROLLBACK');
            throw e;
        } finally {
            client.release();
        }
        return verId;
    }
};

if (!module.parent)  {
    query('SELECT * FROM developers');
}
<|endoftext|>


<commit_before>'use strict';

var http = require('http');
var q = require('q');
var request = require('request');

describe('HTTP', function() {

  var callElementor = function(url) {
    var deferred = q.defer();

    request(url, function(error, response, body) {
      if (error) {
        console.log("Got error: " + error);
        return deferred.reject(error);
      }
      deferred.resolve(JSON.parse(body));
    });

    return deferred.promise;
  };

  describe('Popup', function() {
    var callPopup = function(command) {
      var encodedUrl = 'http://localhost:13000/testSelector?popupInput=' +
          encodeURIComponent(command);

      return callElementor(encodedUrl);
    };

    it('should navigate to protractor website', function(done) {
      var url = 'browser.get(\'http://angular.github.io/protractor/#/api\')';

      // Given that you navigate to the protractor website.
      callPopup(url).then(function() {
        // When you get the current URL.
        return callPopup('browser.getCurrentUrl()');
      }).then(function(response) {
        // Then ensure the URL has changed.
        expect(response).toEqual({
          results: {
            'browser.getCurrentUrl()': 'http://angular.github.io/protractor/#/api'
          }
        });
        done();
      });
    });

    it('should transform by input into count expression', function(done) {
      // When you select by css.
      callPopup('by.css(\'#title\')').then(function(response) {
        // Then ensure the input is turned into count expression.
        expect(response).toEqual({
          results: {
            'element.all(by.css(\'#title\')).count()': 1
          }
        });
        done();
      });
    });

    it('should get element text', function(done) {
      // When you get an element's text.
      var command = '$$(\'.navbar li\').first().getText()';
      callPopup(command).then(function(response) {
        // Then ensure there is text.
        expect(response).toEqual({
          results: {
            '$$(\'.navbar li\').first().getText()': 'Home'
          }
        });
        done();
      });
    });
  });

  describe('Devtools', function() {

    var findSuggestions = function(command) {
      var encodedUrl = 'http://localhost:13000/testSelector?locators=' +
          encodeURIComponent(command);

      return callElementor(encodedUrl);
    };

    it('should find suggestions', function(done) {
      var command = JSON.stringify({
        byCss: {
          nodeName: 'label',
          'for': 'searchInput'
        }
      });

      findSuggestions(command).then(function(response) {
        expect(response).toEqual({
          results: {
            'by.css(\'label[for="searchInput"]\')': 1
          }
        });
        done();
      });
    });
  });
});
<commit_msg>Add test for multiple suggestions<commit_after>'use strict';

var http = require('http');
var q = require('q');
var request = require('request');

describe('HTTP', function() {

  var callElementor = function(url) {
    var deferred = q.defer();

    request(url, function(error, response, body) {
      if (error) {
        console.log("Got error: " + error);
        return deferred.reject(error);
      }
      deferred.resolve(JSON.parse(body));
    });

    return deferred.promise;
  };

  describe('Popup', function() {
    var callPopup = function(command) {
      var encodedUrl = 'http://localhost:13000/testSelector?popupInput=' +
          encodeURIComponent(command);

      return callElementor(encodedUrl);
    };

    it('should navigate to protractor website', function(done) {
      var url = 'browser.get(\'http://angular.github.io/protractor/#/api\')';

      // Given that you navigate to the protractor website.
      callPopup(url).then(function() {
        // When you get the current URL.
        return callPopup('browser.getCurrentUrl()');
      }).then(function(response) {
        // Then ensure the URL has changed.
        expect(response).toEqual({
          results: {
            'browser.getCurrentUrl()': 'http://angular.github.io/protractor/#/api'
          }
        });
        done();
      });
    });

    it('should transform by input into count expression', function(done) {
      // When you select by css.
      callPopup('by.css(\'#title\')').then(function(response) {
        // Then ensure the input is turned into count expression.
        expect(response).toEqual({
          results: {
            'element.all(by.css(\'#title\')).count()': 1
          }
        });
        done();
      });
    });

    it('should get element text', function(done) {
      // When you get an element's text.
      var command = '$$(\'.navbar li\').first().getText()';
      callPopup(command).then(function(response) {
        // Then ensure there is text.
        expect(response).toEqual({
          results: {
            '$$(\'.navbar li\').first().getText()': 'Home'
          }
        });
        done();
      });
    });
  });

  describe('Devtools', function() {

    var findSuggestions = function(command) {
      var encodedUrl = 'http://localhost:13000/testSelector?locators=' +
          encodeURIComponent(command);

      return callElementor(encodedUrl);
    };

    it('should find suggestions', function(done) {
      var command = JSON.stringify({
        byCss: {
          nodeName: 'label',
          'for': 'searchInput'
        }
      });

      findSuggestions(command).then(function(response) {
        expect(response).toEqual({
          results: {
            'by.css(\'label[for="searchInput"]\')': 1
          }
        });
        done();
      });
    });

    it('should find multiple suggestions', function(done) {
      var command = JSON.stringify({
        byCss: {
          nodeName: 'input',
          id: 'searchInput',
          class: 'form-control',
          type: 'search',
          placeholder: 'Enter name',
          'ng-model': 'searchTerm'
        },
        byId: 'searchInput',
        byModel: 'searchTerm'
      });

      findSuggestions(command).then(function(response) {
        expect(response).toEqual({
          results: {
            "by.css('#searchInput')": 1,
            "by.css('input.form-control')": 1,
            "by.css('.form-control')": 1,
            "by.css('input[type=\"search\"]')": 1,
            "by.css('input[placeholder=\"Enter name\"]')": 1,
            "by.css('input[ng-model=\"searchTerm\"]')": 1,
            "by.id('searchInput')": 1,
            "by.model('searchTerm')": 1
          }
        });
        done();
      });
    });
  });
});
<|endoftext|>


<commit_before>var ImageToAscii = require("../lib/index");

ImageToAscii(__dirname + "/octocat.png", function(err, converted) {
    console.log(err || converted);
});
<commit_msg>Comments<commit_after>// Dependencies
var ImageToAscii = require("../lib/index");

// Convert to ascii this image
ImageToAscii(__dirname + "/octocat.png", function(err, converted) {
    console.log(err || converted);
});
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
// import moment from 'moment';
import moment from 'moment-timezone';
import { Field } from 'react-final-form';
import { isEmpty } from 'lodash';
import {
  FormattedMessage,
  injectIntl,
} from 'react-intl';

import stripesFinalForm from '@folio/stripes/final-form';

import {
  Button,
  Col,
  Datepicker,
  Label,
  Modal,
  Row,
  ModalFooter,
  MultiSelection,
} from '@folio/stripes/components';

import css from './RefundsReportModal.css';

const validate = ({ startDate, endDate }) => {
  const errors = {};

  if (isEmpty(startDate) && endDate) {
    errors.startDate = <FormattedMessage id="ui-users.reports.refunds.validation.startDate" />;
  }

  if ((!isEmpty(startDate) && !isEmpty(endDate)) && (moment(startDate).isAfter(moment(endDate)))) {
    errors.endDate = <FormattedMessage id="ui-users.reports.refunds.validation.endDate" />;
  }

  return errors;
};

const RefundsReportModal = (props) => {
  const calculateSubmitState = () => {
    let disabled = true;

    const {
      dirty,
      values: {
        startDate,
        endDate,
      },
      valid,
    } = props.form.getState();

    if ((dirty && valid) || (valid && !isEmpty(startDate) && !isEmpty(endDate))) {
      disabled = false;
    }

    return disabled;
  };

  const parseDate = (date) => moment.tz(date, props.timezone).format('YYYY-MM-DD');

  const feeFineOwners = props.owners.map(({ id, owner }) => ({
    value: id,
    label: owner,
  }));

  const footer = (
    <ModalFooter>
      <Button
        data-test-refunds-report-save-btn
        disabled={calculateSubmitState()}
        marginBottom0
        buttonStyle="primary"
        onClick={props.form.submit}
      >
        <FormattedMessage id="ui-users.saveAndClose" />
      </Button>
      <Button
        data-test-refunds-report-cancel-btn
        marginBottom0
        buttonStyle="default"
        onClick={props.onClose}
      >
        <FormattedMessage id="ui-users.cancel" />
      </Button>
    </ModalFooter>
  );

  return (
    <Modal
      id="refunds-report-modal"
      size="small"
      footer={footer}
      dismissible
      open
      label={props.label}
      onClose={props.onClose}
    >
      <form
        className={css.content}
        onSubmit={props.handleSubmit}
      >
        <Label>
          <FormattedMessage id="ui-users.reports.refunds.modal.message" />
        </Label>
        <Row>
          <Col
            data-test-refunds-report-start-date
            xs={6}
          >
            <Field
              label={<FormattedMessage id="ui-users.reports.refunds.modal.startDate" />}
              name="startDate"
              component={Datepicker}
              autoFocus
              parse={parseDate}
            />
          </Col>
          <Col
            data-test-refunds-report-end-date
            xs={6}
          >
            <Field
              label={<FormattedMessage id="ui-users.reports.refunds.modal.endDate" />}
              name="endDate"
              component={Datepicker}
              parse={parseDate}
            />
          </Col>
          <Col
            data-test-refunds-report-owners
            xs={12}
          >
            <Field
              name="owners"
              component={MultiSelection}
              label={<FormattedMessage id="ui-users.reports.refunds.modal.owner" />}
              placeholder={props.intl.formatMessage({ id: 'ui-users.reports.refunds.modal.owner.placeholder' })}
              dataOptions={feeFineOwners}
            />
          </Col>
        </Row>
      </form>
    </Modal>
  );
};

RefundsReportModal.propTypes = {
  form: PropTypes.object.isRequired,
  intl: PropTypes.object.isRequired,
  label: PropTypes.string.isRequired,
  owners: PropTypes.arrayOf(PropTypes.object).isRequired,
  onClose: PropTypes.func.isRequired,
  handleSubmit: PropTypes.func.isRequired,
  timezone: PropTypes.string.isRequired,
};

export default stripesFinalForm({
  validate,
})(injectIntl(RefundsReportModal));
<commit_msg>UIU-2033: Clean up<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import moment from 'moment-timezone';
import { Field } from 'react-final-form';
import { isEmpty } from 'lodash';
import {
  FormattedMessage,
  injectIntl,
} from 'react-intl';

import stripesFinalForm from '@folio/stripes/final-form';

import {
  Button,
  Col,
  Datepicker,
  Label,
  Modal,
  Row,
  ModalFooter,
  MultiSelection,
} from '@folio/stripes/components';

import css from './RefundsReportModal.css';

const validate = ({ startDate, endDate }) => {
  const errors = {};

  if (isEmpty(startDate) && endDate) {
    errors.startDate = <FormattedMessage id="ui-users.reports.refunds.validation.startDate" />;
  }

  if ((!isEmpty(startDate) && !isEmpty(endDate)) && (moment(startDate).isAfter(moment(endDate)))) {
    errors.endDate = <FormattedMessage id="ui-users.reports.refunds.validation.endDate" />;
  }

  return errors;
};

const RefundsReportModal = (props) => {
  const calculateSubmitState = () => {
    let disabled = true;

    const {
      dirty,
      values: {
        startDate,
        endDate,
      },
      valid,
    } = props.form.getState();

    if ((dirty && valid) || (valid && !isEmpty(startDate) && !isEmpty(endDate))) {
      disabled = false;
    }

    return disabled;
  };

  const parseDate = (date) => moment.tz(date, props.timezone).format('YYYY-MM-DD');

  const feeFineOwners = props.owners.map(({ id, owner }) => ({
    value: id,
    label: owner,
  }));

  const footer = (
    <ModalFooter>
      <Button
        data-test-refunds-report-save-btn
        disabled={calculateSubmitState()}
        marginBottom0
        buttonStyle="primary"
        onClick={props.form.submit}
      >
        <FormattedMessage id="ui-users.saveAndClose" />
      </Button>
      <Button
        data-test-refunds-report-cancel-btn
        marginBottom0
        buttonStyle="default"
        onClick={props.onClose}
      >
        <FormattedMessage id="ui-users.cancel" />
      </Button>
    </ModalFooter>
  );

  return (
    <Modal
      id="refunds-report-modal"
      size="small"
      footer={footer}
      dismissible
      open
      label={props.label}
      onClose={props.onClose}
    >
      <form
        className={css.content}
        onSubmit={props.handleSubmit}
      >
        <Label>
          <FormattedMessage id="ui-users.reports.refunds.modal.message" />
        </Label>
        <Row>
          <Col
            data-test-refunds-report-start-date
            xs={6}
          >
            <Field
              label={<FormattedMessage id="ui-users.reports.refunds.modal.startDate" />}
              name="startDate"
              component={Datepicker}
              autoFocus
              parse={parseDate}
            />
          </Col>
          <Col
            data-test-refunds-report-end-date
            xs={6}
          >
            <Field
              label={<FormattedMessage id="ui-users.reports.refunds.modal.endDate" />}
              name="endDate"
              component={Datepicker}
              parse={parseDate}
            />
          </Col>
          <Col
            data-test-refunds-report-owners
            xs={12}
          >
            <Field
              name="owners"
              component={MultiSelection}
              label={<FormattedMessage id="ui-users.reports.refunds.modal.owner" />}
              placeholder={props.intl.formatMessage({ id: 'ui-users.reports.refunds.modal.owner.placeholder' })}
              dataOptions={feeFineOwners}
            />
          </Col>
        </Row>
      </form>
    </Modal>
  );
};

RefundsReportModal.propTypes = {
  form: PropTypes.object.isRequired,
  intl: PropTypes.object.isRequired,
  label: PropTypes.string.isRequired,
  owners: PropTypes.arrayOf(PropTypes.object).isRequired,
  onClose: PropTypes.func.isRequired,
  handleSubmit: PropTypes.func.isRequired,
  timezone: PropTypes.string.isRequired,
};

export default stripesFinalForm({
  validate,
})(injectIntl(RefundsReportModal));
<|endoftext|>


<commit_before>const JlTransform = require('../stream/JlTransform');
const JlTransformsChain = require('../stream/JlTransformsChain');
const JlPassThrough = require('../stream/JlPassThrough');

const JsonStringifier = require('../stream/JsonStringifier');
const LinesJoiner = require('../stream/LinesJoiner');
const ChunkSplitter = require('../stream/ChunkSplitter');

const PassThrough = require('stream').PassThrough;

const DataStream = require('../DataStream');

const JsonParser = require('../stream/JsonParser');
const LinesSplitter = require('../stream/LinesSplitter');
const ChunkJoiner = require('../stream/ChunkJoiner');

class SelectFrom
{
	constructor(select, inputStream)
	{
		this.select = select;
		this.inputStream = inputStream;
		this.additionalStreams = [];
	}

	toObjectsStream(stream)
	{
		const chain = new JlTransformsChain([
			this.inputStream,
			this.select.select.stream(this.select.dataStreamResolversPool),
			new ChunkSplitter
		]);

		if (stream) {
			return chain.pipe(stream);
		}

		return chain;
	}

	toJsonStream(outputStream)
	{
		const chain = new JlTransformsChain([
			this.inputStream,
			this.select.select.stream(this.select.dataStreamResolversPool),
			new JsonStringifier,
			new LinesJoiner
		]);

		if (outputStream) {
			return chain.pipe(outputStream);
		}

		return chain;
	}

	toArrayOfObjects(cb)
	{
		if (typeof(cb) !== 'function') {
			throw new Error('Function argument expected');
		}

		const output = this.toObjectsStream();
		const objects = [];

		output.on('data', function(object) {
			objects.push(object);
		});

		output.on('end', function() {
			cb(objects);
		});
	}

	addArrayOfObjectsStream(location, array)
	{
		const stream = new JlPassThrough(JlTransform.ARRAYS_OF_OBJECTS, JlTransform.ARRAYS_OF_OBJECTS);

		stream.end(array);

		this.select.dataStreamApiResolver.addDataStream(this._path(location), new DataStream(stream));

		return this;
	}

	addJsonStream(location, stream)
	{
		const chain = stream.pipe(new LinesSplitter).pipe(new JsonParser);

		this.select.dataStreamApiResolver.addDataStream(
			this._path(location),
			new DataStream(chain)
		);

		return this;
	}

	addObjectsStream(location, stream)
	{
		this.select.dataStreamApiResolver.addDataStream(
			this._path(location),
			new DataStream(stream.pipe(new ChunkJoiner))
		);

		return this;
	}

	_path(location) {
		if (typeof(location) === 'string') {
			return [location];
		}

		if (typeof(location) !== 'string') {
			throw new Error('Array or string expected');
		}

		return location;
	}
}

module.exports = SelectFrom;
<commit_msg>Fix: arrays as table location<commit_after>const JlTransform = require('../stream/JlTransform');
const JlTransformsChain = require('../stream/JlTransformsChain');
const JlPassThrough = require('../stream/JlPassThrough');

const JsonStringifier = require('../stream/JsonStringifier');
const LinesJoiner = require('../stream/LinesJoiner');
const ChunkSplitter = require('../stream/ChunkSplitter');

const PassThrough = require('stream').PassThrough;

const DataStream = require('../DataStream');

const JsonParser = require('../stream/JsonParser');
const LinesSplitter = require('../stream/LinesSplitter');
const ChunkJoiner = require('../stream/ChunkJoiner');

class SelectFrom
{
	constructor(select, inputStream)
	{
		this.select = select;
		this.inputStream = inputStream;
		this.additionalStreams = [];
	}

	toObjectsStream(stream)
	{
		const chain = new JlTransformsChain([
			this.inputStream,
			this.select.select.stream(this.select.dataStreamResolversPool),
			new ChunkSplitter
		]);

		if (stream) {
			return chain.pipe(stream);
		}

		return chain;
	}

	toJsonStream(outputStream)
	{
		const chain = new JlTransformsChain([
			this.inputStream,
			this.select.select.stream(this.select.dataStreamResolversPool),
			new JsonStringifier,
			new LinesJoiner
		]);

		if (outputStream) {
			return chain.pipe(outputStream);
		}

		return chain;
	}

	toArrayOfObjects(cb)
	{
		if (typeof(cb) !== 'function') {
			throw new Error('Function argument expected');
		}

		const output = this.toObjectsStream();
		const objects = [];

		output.on('data', function(object) {
			objects.push(object);
		});

		output.on('end', function() {
			cb(objects);
		});
	}

	addArrayOfObjectsStream(location, array)
	{
		const stream = new JlPassThrough(JlTransform.ARRAYS_OF_OBJECTS, JlTransform.ARRAYS_OF_OBJECTS);

		stream.end(array);

		this.select.dataStreamApiResolver.addDataStream(this._path(location), new DataStream(stream));

		return this;
	}

	addJsonStream(location, stream)
	{
		const chain = stream.pipe(new LinesSplitter).pipe(new JsonParser);

		this.select.dataStreamApiResolver.addDataStream(
			this._path(location),
			new DataStream(chain)
		);

		return this;
	}

	addObjectsStream(location, stream)
	{
		this.select.dataStreamApiResolver.addDataStream(
			this._path(location),
			new DataStream(stream.pipe(new ChunkJoiner))
		);

		return this;
	}

	_path(location) {
		if (typeof(location) === 'string') {
			return [location];
		}

		if (!(location instanceof Array)) {
			throw new Error('Array or string expected');
		}

		return location;
	}
}

module.exports = SelectFrom;
<|endoftext|>


<commit_before>var _      = require('lodash')
var router = require('express').Router()
var User   = require('../models/User')

/**
 * GET /
 * Home page
 */
router.get('/', function(req, res) {
  if(!req.user)
    return res.render('landing', {
      title: 'Gamekeller',
      customCss: 'landing'
    })

  User.find({ _id: { $in: req.user.friends } }, 'username avatar rank teamspeakUid teamspeakLinked', function(err, friends) {
    res.render('home', {
      title: 'Gamekeller',
      friends: friends,
      customJs: 'home'
    })
  })
})

/**
 * GET /members
 * Members page
 */
router.get('/members', function(req, res) {
  User.find().sort({ rank: -1, level: -1, createdAt: 1 }).then(function(users) {
    res.render('members', {
      title: 'Mitglieder',
      members: users
    })
  })
})

/**
 * GET /landing
 * Explicitly render landing page
 */
router.get('/landing', function(req, res) {
  res.render('landing', {
    title: 'Gamekeller',
    customCss: 'landing'
  })
})

/**
 * GET /imprint
 * Imprint page
 */
router.get('/imprint', function(req, res) {
  res.render('imprint', {
    title: 'Impressum'
  })
})

/**
 * GET /privacy
 * Privacy policy page
 */
router.get('/privacy', function(req, res) {
  res.render('privacy', {
    title: 'Datenschutz'
  })
})

/**
 * GET /cookies
 * Cookie policy page
 */
router.get('/cookies', function(req, res) {
  res.render('cookies', {
    title: 'Cookies'
  })
})

/**
 * Export the router
 */
module.exports = router<commit_msg>Home/Friends: Sort by 1. online status, 2. username<commit_after>var _      = require('lodash')
var router = require('express').Router()
var User   = require('../models/User')

/**
 * GET /
 * Home page
 */
router.get('/', function(req, res, next) {
  if(!req.user)
    return res.render('landing', {
      title: 'Gamekeller',
      customCss: 'landing'
    })

  User.find({ _id: { $in: req.user.friends } }, 'username avatar teamspeakUid teamspeakLinked').sort({ username: 1 }).then(function(friends) {
    res.render('home', {
      title: 'Gamekeller',
      friends: _.orderBy(friends, 'teamspeakOnline', 'desc'),
      customJs: 'home'
    })
  }).catch(next)
})

/**
 * GET /members
 * Members page
 */
router.get('/members', function(req, res) {
  User.find().sort({ rank: -1, level: -1, createdAt: 1 }).then(function(users) {
    res.render('members', {
      title: 'Mitglieder',
      members: users
    })
  })
})

/**
 * GET /landing
 * Explicitly render landing page
 */
router.get('/landing', function(req, res) {
  res.render('landing', {
    title: 'Gamekeller',
    customCss: 'landing'
  })
})

/**
 * GET /imprint
 * Imprint page
 */
router.get('/imprint', function(req, res) {
  res.render('imprint', {
    title: 'Impressum'
  })
})

/**
 * GET /privacy
 * Privacy policy page
 */
router.get('/privacy', function(req, res) {
  res.render('privacy', {
    title: 'Datenschutz'
  })
})

/**
 * GET /cookies
 * Cookie policy page
 */
router.get('/cookies', function(req, res) {
  res.render('cookies', {
    title: 'Cookies'
  })
})

/**
 * Export the router
 */
module.exports = router<|endoftext|>


<commit_before>import * as ACTIONS from 'constants/action_types';

const reducers = {};

const defaultState = {};

reducers[ACTIONS.RESOLVE_URIS_COMPLETED] = (state, action) => {
  const { resolveInfo } = action.data;
  const byUri = Object.assign({}, state.claimsByUri);
  const byId = Object.assign({}, state.byId);

  Object.entries(resolveInfo).forEach(([uri, { certificate, claim }]) => {
    if (claim) {
      byId[claim.claim_id] = claim;
      byUri[uri] = claim.claim_id;
    } else if (claim === undefined && certificate !== undefined) {
      byId[certificate.claim_id] = certificate;
      // Don't point URI at the channel certificate unless it actually is
      // a channel URI. This is brittle.
      if (!uri.split(certificate.name)[1].match(/\//)) {
        byUri[uri] = certificate.claim_id;
      } else {
        byUri[uri] = null;
      }
    } else {
      byUri[uri] = null;
    }
  });

  return Object.assign({}, state, {
    byId,
    claimsByUri: byUri,
  });
};

reducers[ACTIONS.FETCH_CLAIM_LIST_MINE_STARTED] = state =>
  Object.assign({}, state, {
    isFetchingClaimListMine: true,
  });

reducers[ACTIONS.FETCH_CLAIM_LIST_MINE_COMPLETED] = (state, action) => {
  const { claims } = action.data;
  const byId = Object.assign({}, state.byId);
  const pendingById = Object.assign({}, state.pendingById);

  claims.filter(claim => claim.category && claim.category.match(/claim/)).forEach(claim => {
    byId[claim.claim_id] = claim;

    const pending = Object.values(pendingById).find(
      pendingClaim =>
        pendingClaim.name === claim.name && pendingClaim.channel_name === claim.channel_name
    );

    if (pending) {
      delete pendingById[pending.claim_id];
    }
  });

  // Remove old timed out pending publishes
  Object.values(pendingById)
    .filter(pendingClaim => Date.now() - pendingClaim.time >= 20 * 60 * 1000)
    .forEach(pendingClaim => {
      delete pendingById[pendingClaim.claim_id];
    });

  return Object.assign({}, state, {
    isFetchingClaimListMine: false,
    myClaims: claims,
    byId,
    pendingById,
  });
};

reducers[ACTIONS.FETCH_CHANNEL_LIST_STARTED] = state =>
  Object.assign({}, state, { fetchingMyChannels: true });

reducers[ACTIONS.FETCH_CHANNEL_LIST_COMPLETED] = (state, action) => {
  const { claims } = action.data;
  const myChannelClaims = new Set(state.myChannelClaims);
  const byId = Object.assign({}, state.byId);

  claims.forEach(claim => {
    myChannelClaims.add(claim.claim_id);
    byId[claims.claim_id] = claim;
  });

  return Object.assign({}, state, {
    byId,
    fetchingMyChannels: false,
    myChannelClaims,
  });
};

reducers[ACTIONS.FETCH_CHANNEL_CLAIMS_STARTED] = (state, action) => {
  const { uri, page } = action.data;
  const fetchingChannelClaims = Object.assign({}, state.fetchingChannelClaims);

  fetchingChannelClaims[uri] = page;

  return Object.assign({}, state, {
    fetchingChannelClaims,
  });
};

reducers[ACTIONS.FETCH_CHANNEL_CLAIMS_COMPLETED] = (state, action) => {
  const { uri, claims, page } = action.data;

  const claimsByChannel = Object.assign({}, state.claimsByChannel);
  const byChannel = Object.assign({}, claimsByChannel[uri]);
  const allClaimIds = new Set(byChannel.all);
  const currentPageClaimIds = [];
  const byId = Object.assign({}, state.byId);
  const fetchingChannelClaims = Object.assign({}, state.fetchingChannelClaims);

  if (claims !== undefined) {
    claims.forEach(claim => {
      allClaimIds.add(claim.claim_id);
      currentPageClaimIds.push(claim.claim_id);
      byId[claim.claim_id] = claim;
    });
  }

  byChannel.all = allClaimIds;
  byChannel[page] = currentPageClaimIds;
  claimsByChannel[uri] = byChannel;
  delete fetchingChannelClaims[uri];

  return Object.assign({}, state, {
    claimsByChannel,
    byId,
    fetchingChannelClaims,
  });
};

reducers[ACTIONS.ABANDON_CLAIM_STARTED] = (state, action) => {
  const { claimId } = action.data;
  const abandoningById = Object.assign({}, state.abandoningById);

  abandoningById[claimId] = true;

  return Object.assign({}, state, {
    abandoningById,
  });
};

reducers[ACTIONS.ABANDON_CLAIM_SUCCEEDED] = (state, action) => {
  const { claimId } = action.data;
  const byId = Object.assign({}, state.byId);
  const claimsByUri = Object.assign({}, state.claimsByUri);

  Object.keys(claimsByUri).forEach(uri => {
    if (claimsByUri[uri] === claimId) {
      delete claimsByUri[uri];
    }
  });

  delete byId[claimId];

  return Object.assign({}, state, {
    byId,
    claimsByUri,
  });
};

reducers[ACTIONS.CREATE_CHANNEL_COMPLETED] = (state, action) => {
  const { channelClaim } = action.data;
  const byId = Object.assign({}, state.byId);
  const myChannelClaims = new Set(state.myChannelClaims);

  byId[channelClaim.claim_id] = channelClaim;
  myChannelClaims.add(channelClaim.claim_id);

  return Object.assign({}, state, {
    byId,
    myChannelClaims,
  });
};

export default function reducer(state = defaultState, action) {
  const handler = reducers[action.type];
  if (handler) return handler(state, action);
  return state;
}
<commit_msg>Include updated channels in results<commit_after>import * as ACTIONS from 'constants/action_types';

const reducers = {};

const defaultState = {};

reducers[ACTIONS.RESOLVE_URIS_COMPLETED] = (state, action) => {
  const { resolveInfo } = action.data;
  const byUri = Object.assign({}, state.claimsByUri);
  const byId = Object.assign({}, state.byId);

  Object.entries(resolveInfo).forEach(([uri, { certificate, claim }]) => {
    if (claim) {
      byId[claim.claim_id] = claim;
      byUri[uri] = claim.claim_id;
    } else if (claim === undefined && certificate !== undefined) {
      byId[certificate.claim_id] = certificate;
      // Don't point URI at the channel certificate unless it actually is
      // a channel URI. This is brittle.
      if (!uri.split(certificate.name)[1].match(/\//)) {
        byUri[uri] = certificate.claim_id;
      } else {
        byUri[uri] = null;
      }
    } else {
      byUri[uri] = null;
    }
  });

  return Object.assign({}, state, {
    byId,
    claimsByUri: byUri,
  });
};

reducers[ACTIONS.FETCH_CLAIM_LIST_MINE_STARTED] = state =>
  Object.assign({}, state, {
    isFetchingClaimListMine: true,
  });

reducers[ACTIONS.FETCH_CLAIM_LIST_MINE_COMPLETED] = (state, action) => {
  const { claims } = action.data;
  const byId = Object.assign({}, state.byId);
  const pendingById = Object.assign({}, state.pendingById);

  claims.filter(claim => claim.category && (claim.category.match(/claim/) || claim.category.match(/update/))).forEach(claim => {
    byId[claim.claim_id] = claim;

    const pending = Object.values(pendingById).find(
      pendingClaim =>
        pendingClaim.name === claim.name && pendingClaim.channel_name === claim.channel_name
    );

    if (pending) {
      delete pendingById[pending.claim_id];
    }
  });

  // Remove old timed out pending publishes
  Object.values(pendingById)
    .filter(pendingClaim => Date.now() - pendingClaim.time >= 20 * 60 * 1000)
    .forEach(pendingClaim => {
      delete pendingById[pendingClaim.claim_id];
    });

  return Object.assign({}, state, {
    isFetchingClaimListMine: false,
    myClaims: claims,
    byId,
    pendingById,
  });
};

reducers[ACTIONS.FETCH_CHANNEL_LIST_STARTED] = state =>
  Object.assign({}, state, { fetchingMyChannels: true });

reducers[ACTIONS.FETCH_CHANNEL_LIST_COMPLETED] = (state, action) => {
  const { claims } = action.data;
  const myChannelClaims = new Set(state.myChannelClaims);
  const byId = Object.assign({}, state.byId);

  claims.forEach(claim => {
    myChannelClaims.add(claim.claim_id);
    byId[claims.claim_id] = claim;
  });

  return Object.assign({}, state, {
    byId,
    fetchingMyChannels: false,
    myChannelClaims,
  });
};

reducers[ACTIONS.FETCH_CHANNEL_CLAIMS_STARTED] = (state, action) => {
  const { uri, page } = action.data;
  const fetchingChannelClaims = Object.assign({}, state.fetchingChannelClaims);

  fetchingChannelClaims[uri] = page;

  return Object.assign({}, state, {
    fetchingChannelClaims,
  });
};

reducers[ACTIONS.FETCH_CHANNEL_CLAIMS_COMPLETED] = (state, action) => {
  const { uri, claims, page } = action.data;

  const claimsByChannel = Object.assign({}, state.claimsByChannel);
  const byChannel = Object.assign({}, claimsByChannel[uri]);
  const allClaimIds = new Set(byChannel.all);
  const currentPageClaimIds = [];
  const byId = Object.assign({}, state.byId);
  const fetchingChannelClaims = Object.assign({}, state.fetchingChannelClaims);

  if (claims !== undefined) {
    claims.forEach(claim => {
      allClaimIds.add(claim.claim_id);
      currentPageClaimIds.push(claim.claim_id);
      byId[claim.claim_id] = claim;
    });
  }

  byChannel.all = allClaimIds;
  byChannel[page] = currentPageClaimIds;
  claimsByChannel[uri] = byChannel;
  delete fetchingChannelClaims[uri];

  return Object.assign({}, state, {
    claimsByChannel,
    byId,
    fetchingChannelClaims,
  });
};

reducers[ACTIONS.ABANDON_CLAIM_STARTED] = (state, action) => {
  const { claimId } = action.data;
  const abandoningById = Object.assign({}, state.abandoningById);

  abandoningById[claimId] = true;

  return Object.assign({}, state, {
    abandoningById,
  });
};

reducers[ACTIONS.ABANDON_CLAIM_SUCCEEDED] = (state, action) => {
  const { claimId } = action.data;
  const byId = Object.assign({}, state.byId);
  const claimsByUri = Object.assign({}, state.claimsByUri);

  Object.keys(claimsByUri).forEach(uri => {
    if (claimsByUri[uri] === claimId) {
      delete claimsByUri[uri];
    }
  });

  delete byId[claimId];

  return Object.assign({}, state, {
    byId,
    claimsByUri,
  });
};

reducers[ACTIONS.CREATE_CHANNEL_COMPLETED] = (state, action) => {
  const { channelClaim } = action.data;
  const byId = Object.assign({}, state.byId);
  const myChannelClaims = new Set(state.myChannelClaims);

  byId[channelClaim.claim_id] = channelClaim;
  myChannelClaims.add(channelClaim.claim_id);

  return Object.assign({}, state, {
    byId,
    myChannelClaims,
  });
};

export default function reducer(state = defaultState, action) {
  const handler = reducers[action.type];
  if (handler) return handler(state, action);
  return state;
}
<|endoftext|>


<commit_before>/*
    globals require console
*/
var Express = require('express');
var Http = require('http');
var Https = require('https');
var Fs = require('fs');
var WebSocketServer = require('ws').Server;
var NetfluxSrv = require('./node_modules/chainpad-server/NetfluxWebsocketSrv');
var Package = require('./package.json');
var Path = require("path");
var nThen = require("nthen");

var config = require("./lib/load-config");

var websocketPort = config.websocketPort || config.httpPort;
var useSecureWebsockets = config.useSecureWebsockets || false;

// This is stuff which will become available to replify
const debuggableStore = new WeakMap();
const debuggable = function (name, x) {
    if (name in debuggableStore) {
        try { throw new Error(); } catch (e) {
            console.error('cannot add ' + name + ' more than once [' + e.stack + ']');
        }
    } else {
        debuggableStore[name] = x;
    }
    return x;
};
debuggable('global', global);
debuggable('config', config);

// support multiple storage back ends
var Storage = require(config.storage||'./storage/file');

var app = debuggable('app', Express());

var httpsOpts;

// mode can be FRESH (default), DEV, or PACKAGE

var FRESH_KEY = '';
var FRESH_MODE = true;
var DEV_MODE = false;
if (process.env.PACKAGE) {
// `PACKAGE=1 node server` uses the version string from package.json as the cache string
    console.log("PACKAGE MODE ENABLED");
    FRESH_MODE = false;
    DEV_MODE = false;
} else if (process.env.DEV) {
// `DEV=1 node server` will use a random cache string on every page reload
    console.log("DEV MODE ENABLED");
    FRESH_MODE = false;
    DEV_MODE = true;
} else {
// `FRESH=1 node server` will set a random cache string when the server is launched
// and use it for the process lifetime or until it is reset from the admin panel
    console.log("FRESH MODE ENABLED");
    FRESH_KEY = +new Date();
}

config.flushCache = function () {
    FRESH_KEY = +new Date();
    if (!(DEV_MODE || FRESH_MODE)) { FRESH_MODE = true; }
    if (!config.log) { return; }
    config.log.info("UPDATING_FRESH_KEY", FRESH_KEY);
};

const clone = (x) => (JSON.parse(JSON.stringify(x)));

var setHeaders = (function () {
    if (typeof(config.httpHeaders) !== 'object') { return function () {}; }

    const headers = clone(config.httpHeaders);
    if (config.contentSecurity) {
        headers['Content-Security-Policy'] = clone(config.contentSecurity);
        if (!/;$/.test(headers['Content-Security-Policy'])) { headers['Content-Security-Policy'] += ';' }
        if (headers['Content-Security-Policy'].indexOf('frame-ancestors') === -1) {
            // backward compat for those who do not merge the new version of the config
            // when updating. This prevents endless spinner if someone clicks donate.
            // It also fixes the cross-domain iframe.
            headers['Content-Security-Policy'] += "frame-ancestors *;";
        }
    }
    const padHeaders = clone(headers);
    if (config.padContentSecurity) {
        padHeaders['Content-Security-Policy'] = clone(config.padContentSecurity);
    }
    if (Object.keys(headers).length) {
        return function (req, res) {
            const h = [
                    /^\/pad(2)?\/inner\.html.*/,
                    /^\/sheet\/inner\.html.*/,
                    /^\/common\/onlyoffice\/.*\/index\.html.*/
                ].some((regex) => {
                    return regex.test(req.url)
                }) ? padHeaders : headers;
            for (let header in h) { res.setHeader(header, h[header]); }
        };
    }
    return function () {};
}());

(function () {
if (!config.logFeedback) { return; }

const logFeedback = function (url) {
    url.replace(/\?(.*?)=/, function (all, fb) {
        config.log.feedback(fb, '');
    });
};

app.head(/^\/common\/feedback\.html/, function (req, res, next) {
    logFeedback(req.url);
    next();
});
}());

app.use(function (req, res, next) {
    if (req.method === 'OPTIONS' && /\/blob\//.test(req.url)) {
        res.setHeader('Access-Control-Allow-Origin', '*');
        res.setHeader('Access-Control-Allow-Methods', 'GET, OPTIONS');
        res.setHeader('Access-Control-Allow-Headers', 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range');
        res.setHeader('Access-Control-Max-Age', 1728000);
        res.setHeader('Content-Type', 'application/octet-stream; charset=utf-8');
        res.setHeader('Content-Length', 0);
        res.statusCode = 204;
        return void res.end();
    }

    setHeaders(req, res);
    if (/[\?\&]ver=[^\/]+$/.test(req.url)) { res.setHeader("Cache-Control", "max-age=31536000"); }
    next();
});

app.use(Express.static(__dirname + '/www'));

Fs.exists(__dirname + "/customize", function (e) {
    if (e) { return; }
    console.log("Cryptpad is customizable, see customize.dist/readme.md for details");
});

// FIXME I think this is a regression caused by a recent PR
// correct this hack without breaking the contributor's intended behaviour.

var mainPages = config.mainPages || ['index', 'privacy', 'terms', 'about', 'contact'];
var mainPagePattern = new RegExp('^\/(' + mainPages.join('|') + ').html$');
app.get(mainPagePattern, Express.static(__dirname + '/customize'));
app.get(mainPagePattern, Express.static(__dirname + '/customize.dist'));

app.use("/blob", Express.static(Path.join(__dirname, (config.blobPath || './blob')), {
    maxAge: DEV_MODE? "0d": "365d"
}));
app.use("/datastore", Express.static(Path.join(__dirname, (config.filePath || './datastore')), {
    maxAge: "0d"
}));
app.use("/block", Express.static(Path.join(__dirname, (config.blockPath || '/block')), {
    maxAge: "0d",
}));

app.use("/customize", Express.static(__dirname + '/customize'));
app.use("/customize", Express.static(__dirname + '/customize.dist'));
app.use("/customize.dist", Express.static(__dirname + '/customize.dist'));
app.use(/^\/[^\/]*$/, Express.static('customize'));
app.use(/^\/[^\/]*$/, Express.static('customize.dist'));

if (config.privKeyAndCertFiles) {
    var privKeyAndCerts = '';
    config.privKeyAndCertFiles.forEach(function (file) {
        privKeyAndCerts = privKeyAndCerts + Fs.readFileSync(file);
    });
    var array = privKeyAndCerts.split('\n-----BEGIN ');
    for (var i = 1; i < array.length; i++) { array[i] = '-----BEGIN ' + array[i]; }
    var privKey;
    for (var i = 0; i < array.length; i++) {
        if (array[i].indexOf('PRIVATE KEY-----\n') !== -1) {
            privKey = array[i];
            array.splice(i, 1);
            break;
        }
    }
    if (!privKey) { throw new Error("cannot find private key"); }
    httpsOpts = {
        cert: array.shift(),
        key: privKey,
        ca: array
    };
}

var admins = [];
try {
    admins = (config.adminKeys || []).map(function (k) {
        k = k.replace(/\/+$/, '');
        var s = k.split('/');
        return s[s.length-1].replace(/-/g, '/');
    });
} catch (e) { console.error("Can't parse admin keys"); }

// TODO, cache this /api/config responses instead of re-computing it each time
app.get('/api/config', function(req, res){
    // TODO precompute any data that isn't dynamic to save some CPU time
    var host = req.headers.host.replace(/\:[0-9]+/, '');
    res.setHeader('Content-Type', 'text/javascript');
    res.send('define(function(){\n' + [
        'var obj = ' + JSON.stringify({
            requireConf: {
                waitSeconds: 600,
                urlArgs: 'ver=' + Package.version + (FRESH_KEY? '-' + FRESH_KEY: '') + (DEV_MODE? '-' + (+new Date()): ''),
            },
            removeDonateButton: (config.removeDonateButton === true),
            allowSubscriptions: (config.allowSubscriptions === true),
            websocketPath: config.useExternalWebsocket ? undefined : config.websocketPath,
            // FIXME don't send websocketURL if websocketPath is provided. deprecated.
            websocketURL:'ws' + ((useSecureWebsockets) ? 's' : '') + '://' + host + ':' +
                websocketPort + '/cryptpad_websocket',
            httpUnsafeOrigin: config.httpUnsafeOrigin.replace(/^ /, ''),
            adminEmail: config.adminEmail,
            adminKeys: admins,
            inactiveTime: config.inactiveTime,
            supportMailbox: config.supportMailboxPublicKey
        }, null, '\t'),
        'obj.httpSafeOrigin = ' + (function () {
            if (config.httpSafeOrigin) { return '"' + config.httpSafeOrigin + '"'; }
            if (config.httpSafePort) {
                return "(function () { return window.location.origin.replace(/\:[0-9]+$/, ':" +
                    config.httpSafePort + "'); }())";
            }
            return 'window.location.origin';
        }()),
        'return obj',
        '});'
    ].join(';\n'));
});

var four04_path = Path.resolve(__dirname + '/customize.dist/404.html');
var custom_four04_path = Path.resolve(__dirname + '/customize/404.html');

var send404 = function (res, path) {
    if (!path && path !== four04_path) { path = four04_path; }
    Fs.exists(path, function (exists) {
        res.setHeader('Content-Type', 'text/html; charset=utf-8');
        if (exists) { return Fs.createReadStream(path).pipe(res); }
        send404(res);
    });
};

app.use(function (req, res, next) {
    res.status(404);
    send404(res, custom_four04_path);
});

var httpServer = httpsOpts ? Https.createServer(httpsOpts, app) : Http.createServer(app);

httpServer.listen(config.httpPort,config.httpAddress,function(){
    var host = config.httpAddress;
    var hostName = !host.indexOf(':') ? '[' + host + ']' : host;

    var port = config.httpPort;
    var ps = port === 80? '': ':' + port;

    console.log('[%s] server available http://%s%s', new Date().toISOString(), hostName, ps);
});
if (config.httpSafePort) {
    Http.createServer(app).listen(config.httpSafePort, config.httpAddress);
}

var wsConfig = { server: httpServer };

var rpc;
var historyKeeper;

var log;

// Initialize logging, the the store, then tasks, then rpc, then history keeper and then start the server
var nt = nThen(function (w) {
    // set up logger
    var Logger = require("./lib/log");
    //console.log("Loading logging module");
    Logger.create(config, w(function (_log) {
        log = config.log = _log;
    }));
}).nThen(function (w) {
    if (config.useExternalWebsocket) { return; }
    Storage.create(config, w(function (_store) {
        config.store = _store;
    }));
}).nThen(function (w) {
    var Tasks = require("./storage/tasks");
    Tasks.create(config, w(function (e, tasks) {
        if (e) {
            throw e;
        }
        config.tasks = tasks;
        if (config.disableIntegratedTasks) { return; }
        setInterval(function () {
            tasks.runAll(function (err) {
                if (err) {
                    // either TASK_CONCURRENCY or an error with tasks.list
                    // in either case it is already logged.
                }
            });
        }, 1000 * 60 * 5); // run every five minutes
    }));
}).nThen(function (w) {
    config.rpc = typeof(config.rpc) === 'undefined'? './rpc.js' : config.rpc;
    if (typeof(config.rpc) !== 'string') { return; }
    // load pin store...
    var Rpc = require(config.rpc);
    Rpc.create(config, debuggable, w(function (e, _rpc) {
        if (e) {
            w.abort();
            throw e;
        }
        rpc = _rpc;
    }));
}).nThen(function () {
    if (config.useExternalWebsocket) { return; }
    var HK = require('./historyKeeper.js');
    var hkConfig = {
        tasks: config.tasks,
        rpc: rpc,
        store: config.store,
        log: log,
        retainData: Boolean(config.retainData),
    };
    historyKeeper = HK.create(hkConfig);
}).nThen(function () {
    if (config.useExternalWebsocket) { return; }
    if (websocketPort !== config.httpPort) {
        log.debug("setting up a new websocket server");
        wsConfig = { port: websocketPort};
    }
    var wsSrv = new WebSocketServer(wsConfig);
    NetfluxSrv.run(wsSrv, config, historyKeeper);
});

if (config.debugReplName) {
    require('replify')({ name: config.debugReplName, app: debuggableStore });
}
<commit_msg>trim leading spaces from domains<commit_after>/*
    globals require console
*/
var Express = require('express');
var Http = require('http');
var Https = require('https');
var Fs = require('fs');
var WebSocketServer = require('ws').Server;
var NetfluxSrv = require('./node_modules/chainpad-server/NetfluxWebsocketSrv');
var Package = require('./package.json');
var Path = require("path");
var nThen = require("nthen");

var config = require("./lib/load-config");

var websocketPort = config.websocketPort || config.httpPort;
var useSecureWebsockets = config.useSecureWebsockets || false;

// This is stuff which will become available to replify
const debuggableStore = new WeakMap();
const debuggable = function (name, x) {
    if (name in debuggableStore) {
        try { throw new Error(); } catch (e) {
            console.error('cannot add ' + name + ' more than once [' + e.stack + ']');
        }
    } else {
        debuggableStore[name] = x;
    }
    return x;
};
debuggable('global', global);
debuggable('config', config);

// support multiple storage back ends
var Storage = require(config.storage||'./storage/file');

var app = debuggable('app', Express());

var httpsOpts;

// mode can be FRESH (default), DEV, or PACKAGE

var FRESH_KEY = '';
var FRESH_MODE = true;
var DEV_MODE = false;
if (process.env.PACKAGE) {
// `PACKAGE=1 node server` uses the version string from package.json as the cache string
    console.log("PACKAGE MODE ENABLED");
    FRESH_MODE = false;
    DEV_MODE = false;
} else if (process.env.DEV) {
// `DEV=1 node server` will use a random cache string on every page reload
    console.log("DEV MODE ENABLED");
    FRESH_MODE = false;
    DEV_MODE = true;
} else {
// `FRESH=1 node server` will set a random cache string when the server is launched
// and use it for the process lifetime or until it is reset from the admin panel
    console.log("FRESH MODE ENABLED");
    FRESH_KEY = +new Date();
}

config.flushCache = function () {
    FRESH_KEY = +new Date();
    if (!(DEV_MODE || FRESH_MODE)) { FRESH_MODE = true; }
    if (!config.log) { return; }
    config.log.info("UPDATING_FRESH_KEY", FRESH_KEY);
};

const clone = (x) => (JSON.parse(JSON.stringify(x)));

var setHeaders = (function () {
    if (typeof(config.httpHeaders) !== 'object') { return function () {}; }

    const headers = clone(config.httpHeaders);
    if (config.contentSecurity) {
        headers['Content-Security-Policy'] = clone(config.contentSecurity);
        if (!/;$/.test(headers['Content-Security-Policy'])) { headers['Content-Security-Policy'] += ';' }
        if (headers['Content-Security-Policy'].indexOf('frame-ancestors') === -1) {
            // backward compat for those who do not merge the new version of the config
            // when updating. This prevents endless spinner if someone clicks donate.
            // It also fixes the cross-domain iframe.
            headers['Content-Security-Policy'] += "frame-ancestors *;";
        }
    }
    const padHeaders = clone(headers);
    if (config.padContentSecurity) {
        padHeaders['Content-Security-Policy'] = clone(config.padContentSecurity);
    }
    if (Object.keys(headers).length) {
        return function (req, res) {
            const h = [
                    /^\/pad(2)?\/inner\.html.*/,
                    /^\/sheet\/inner\.html.*/,
                    /^\/common\/onlyoffice\/.*\/index\.html.*/
                ].some((regex) => {
                    return regex.test(req.url)
                }) ? padHeaders : headers;
            for (let header in h) { res.setHeader(header, h[header]); }
        };
    }
    return function () {};
}());

(function () {
if (!config.logFeedback) { return; }

const logFeedback = function (url) {
    url.replace(/\?(.*?)=/, function (all, fb) {
        config.log.feedback(fb, '');
    });
};

app.head(/^\/common\/feedback\.html/, function (req, res, next) {
    logFeedback(req.url);
    next();
});
}());

app.use(function (req, res, next) {
    if (req.method === 'OPTIONS' && /\/blob\//.test(req.url)) {
        res.setHeader('Access-Control-Allow-Origin', '*');
        res.setHeader('Access-Control-Allow-Methods', 'GET, OPTIONS');
        res.setHeader('Access-Control-Allow-Headers', 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range');
        res.setHeader('Access-Control-Max-Age', 1728000);
        res.setHeader('Content-Type', 'application/octet-stream; charset=utf-8');
        res.setHeader('Content-Length', 0);
        res.statusCode = 204;
        return void res.end();
    }

    setHeaders(req, res);
    if (/[\?\&]ver=[^\/]+$/.test(req.url)) { res.setHeader("Cache-Control", "max-age=31536000"); }
    next();
});

app.use(Express.static(__dirname + '/www'));

Fs.exists(__dirname + "/customize", function (e) {
    if (e) { return; }
    console.log("Cryptpad is customizable, see customize.dist/readme.md for details");
});

// FIXME I think this is a regression caused by a recent PR
// correct this hack without breaking the contributor's intended behaviour.

var mainPages = config.mainPages || ['index', 'privacy', 'terms', 'about', 'contact'];
var mainPagePattern = new RegExp('^\/(' + mainPages.join('|') + ').html$');
app.get(mainPagePattern, Express.static(__dirname + '/customize'));
app.get(mainPagePattern, Express.static(__dirname + '/customize.dist'));

app.use("/blob", Express.static(Path.join(__dirname, (config.blobPath || './blob')), {
    maxAge: DEV_MODE? "0d": "365d"
}));
app.use("/datastore", Express.static(Path.join(__dirname, (config.filePath || './datastore')), {
    maxAge: "0d"
}));
app.use("/block", Express.static(Path.join(__dirname, (config.blockPath || '/block')), {
    maxAge: "0d",
}));

app.use("/customize", Express.static(__dirname + '/customize'));
app.use("/customize", Express.static(__dirname + '/customize.dist'));
app.use("/customize.dist", Express.static(__dirname + '/customize.dist'));
app.use(/^\/[^\/]*$/, Express.static('customize'));
app.use(/^\/[^\/]*$/, Express.static('customize.dist'));

if (config.privKeyAndCertFiles) {
    var privKeyAndCerts = '';
    config.privKeyAndCertFiles.forEach(function (file) {
        privKeyAndCerts = privKeyAndCerts + Fs.readFileSync(file);
    });
    var array = privKeyAndCerts.split('\n-----BEGIN ');
    for (var i = 1; i < array.length; i++) { array[i] = '-----BEGIN ' + array[i]; }
    var privKey;
    for (var i = 0; i < array.length; i++) {
        if (array[i].indexOf('PRIVATE KEY-----\n') !== -1) {
            privKey = array[i];
            array.splice(i, 1);
            break;
        }
    }
    if (!privKey) { throw new Error("cannot find private key"); }
    httpsOpts = {
        cert: array.shift(),
        key: privKey,
        ca: array
    };
}

var admins = [];
try {
    admins = (config.adminKeys || []).map(function (k) {
        k = k.replace(/\/+$/, '');
        var s = k.split('/');
        return s[s.length-1].replace(/-/g, '/');
    });
} catch (e) { console.error("Can't parse admin keys"); }

// TODO, cache this /api/config responses instead of re-computing it each time
app.get('/api/config', function(req, res){
    // TODO precompute any data that isn't dynamic to save some CPU time
    var host = req.headers.host.replace(/\:[0-9]+/, '');
    res.setHeader('Content-Type', 'text/javascript');
    res.send('define(function(){\n' + [
        'var obj = ' + JSON.stringify({
            requireConf: {
                waitSeconds: 600,
                urlArgs: 'ver=' + Package.version + (FRESH_KEY? '-' + FRESH_KEY: '') + (DEV_MODE? '-' + (+new Date()): ''),
            },
            removeDonateButton: (config.removeDonateButton === true),
            allowSubscriptions: (config.allowSubscriptions === true),
            websocketPath: config.useExternalWebsocket ? undefined : config.websocketPath,
            // FIXME don't send websocketURL if websocketPath is provided. deprecated.
            websocketURL:'ws' + ((useSecureWebsockets) ? 's' : '') + '://' + host + ':' +
                websocketPort + '/cryptpad_websocket',
            httpUnsafeOrigin: config.httpUnsafeOrigin.replace(/^\s*/, ''),
            adminEmail: config.adminEmail,
            adminKeys: admins,
            inactiveTime: config.inactiveTime,
            supportMailbox: config.supportMailboxPublicKey
        }, null, '\t'),
        'obj.httpSafeOrigin = ' + (function () {
            if (config.httpSafeOrigin) { return '"' + config.httpSafeOrigin + '"'; }
            if (config.httpSafePort) {
                return "(function () { return window.location.origin.replace(/\:[0-9]+$/, ':" +
                    config.httpSafePort + "'); }())";
            }
            return 'window.location.origin';
        }()),
        'return obj',
        '});'
    ].join(';\n'));
});

var four04_path = Path.resolve(__dirname + '/customize.dist/404.html');
var custom_four04_path = Path.resolve(__dirname + '/customize/404.html');

var send404 = function (res, path) {
    if (!path && path !== four04_path) { path = four04_path; }
    Fs.exists(path, function (exists) {
        res.setHeader('Content-Type', 'text/html; charset=utf-8');
        if (exists) { return Fs.createReadStream(path).pipe(res); }
        send404(res);
    });
};

app.use(function (req, res, next) {
    res.status(404);
    send404(res, custom_four04_path);
});

var httpServer = httpsOpts ? Https.createServer(httpsOpts, app) : Http.createServer(app);

httpServer.listen(config.httpPort,config.httpAddress,function(){
    var host = config.httpAddress;
    var hostName = !host.indexOf(':') ? '[' + host + ']' : host;

    var port = config.httpPort;
    var ps = port === 80? '': ':' + port;

    console.log('[%s] server available http://%s%s', new Date().toISOString(), hostName, ps);
});
if (config.httpSafePort) {
    Http.createServer(app).listen(config.httpSafePort, config.httpAddress);
}

var wsConfig = { server: httpServer };

var rpc;
var historyKeeper;

var log;

// Initialize logging, the the store, then tasks, then rpc, then history keeper and then start the server
var nt = nThen(function (w) {
    // set up logger
    var Logger = require("./lib/log");
    //console.log("Loading logging module");
    Logger.create(config, w(function (_log) {
        log = config.log = _log;
    }));
}).nThen(function (w) {
    if (config.useExternalWebsocket) { return; }
    Storage.create(config, w(function (_store) {
        config.store = _store;
    }));
}).nThen(function (w) {
    var Tasks = require("./storage/tasks");
    Tasks.create(config, w(function (e, tasks) {
        if (e) {
            throw e;
        }
        config.tasks = tasks;
        if (config.disableIntegratedTasks) { return; }
        setInterval(function () {
            tasks.runAll(function (err) {
                if (err) {
                    // either TASK_CONCURRENCY or an error with tasks.list
                    // in either case it is already logged.
                }
            });
        }, 1000 * 60 * 5); // run every five minutes
    }));
}).nThen(function (w) {
    config.rpc = typeof(config.rpc) === 'undefined'? './rpc.js' : config.rpc;
    if (typeof(config.rpc) !== 'string') { return; }
    // load pin store...
    var Rpc = require(config.rpc);
    Rpc.create(config, debuggable, w(function (e, _rpc) {
        if (e) {
            w.abort();
            throw e;
        }
        rpc = _rpc;
    }));
}).nThen(function () {
    if (config.useExternalWebsocket) { return; }
    var HK = require('./historyKeeper.js');
    var hkConfig = {
        tasks: config.tasks,
        rpc: rpc,
        store: config.store,
        log: log,
        retainData: Boolean(config.retainData),
    };
    historyKeeper = HK.create(hkConfig);
}).nThen(function () {
    if (config.useExternalWebsocket) { return; }
    if (websocketPort !== config.httpPort) {
        log.debug("setting up a new websocket server");
        wsConfig = { port: websocketPort};
    }
    var wsSrv = new WebSocketServer(wsConfig);
    NetfluxSrv.run(wsSrv, config, historyKeeper);
});

if (config.debugReplName) {
    require('replify')({ name: config.debugReplName, app: debuggableStore });
}
<|endoftext|>


<commit_before>/**
 * @file Tr component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';

import Td from '../_Td';

import SelectMode from '../_statics/SelectMode';
import SelectAllMode from '../_statics/SelectAllMode';
import SortingType from '../_statics/SortingType';

import Util from '../_vendors/Util';
import TableCalculation from '../_vendors/TableCalculation';

class Tr extends Component {

    static SelectMode = SelectMode;
    static SelectAllMode = SelectAllMode;
    static SortingType = SortingType;

    constructor(props, ...restArgs) {
        super(props, ...restArgs);
    }

    handleClick = e => {
        const {data, rowIndex, disabled, onRowClick} = this.props;
        !disabled && onRowClick && onRowClick(data, rowIndex, e);
    };

    render() {

        const {
                className, columns, rowIndex, data, isChecked, disabled,
                onCellClick
            } = this.props,

            columnsWithSpan = TableCalculation.getColumnsWithSpan(columns, rowIndex);

        return (

                {
                    columnsWithSpan && columnsWithSpan.map(({column, span}, colIndex) => column ?

                        :
                        null
                    )
                }

        );

    }
}

Tr.propTypes = {

    rowIndex: PropTypes.number,

    /**
     * Children passed into table header.
     */
    columns: PropTypes.arrayOf(PropTypes.shape({

        /**
         * width of column
         */
        width: PropTypes.number,

        /**
         * minimum width of column
         */
        minWidth: PropTypes.number,

        /**
         * The class name of header.
         */
        headerClassName: PropTypes.string,

        /**
         * Override the styles of header.
         */
        headerStyle: PropTypes.object,

        /**
         * The render content in header.
         * (1) string，example： 'id'
         * (2) callback，example：function (tableData, colIndex) {return colIndex;}
         */
        headerRenderer: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),

        /**
         * The class name of td.
         */
        cellClassName: PropTypes.string,

        /**
         * Override the styles of td.
         */
        cellStyle: PropTypes.object,

        /**
         * The render content in table.
         * (1) data key，example： 'id'
         * (2) data key tamplate，example：'${id} - ${name}'
         * (3) callback，example：function (rowData, rowIndex, colIndex) {return rowData.id;}
         */
        cellRenderer: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),

        /**
         * The class name of footer.
         */
        footerClassName: PropTypes.string,

        /**
         * Override the styles of footer.
         */
        footerStyle: PropTypes.object,

        /**
         * The render content in footer.
         * (1) string，example： 'id'
         * (2) callback，example：function (tableData, colIndex) {return colIndex;}
         */
        footerRenderer: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),

        /**
         * If true,this column can be sorted.
         */
        sortable: PropTypes.bool,

        /**
         * Sort field.
         */
        sortingProp: PropTypes.string,

        defaultSortingType: PropTypes.oneOf(Util.enumerateValue(SortingType)),

        /**
         * Column span callback
         * example: function (colIndex, rowIndex) {return colIndex === 0 ? 2 : null;}
         */
        span: PropTypes.func

    })).isRequired,

    data: PropTypes.object,
    isChecked: PropTypes.bool,
    disabled: PropTypes.bool,
    className: PropTypes.string,

    onRowClick: PropTypes.func,
    onCellClick: PropTypes.func

};

Tr.defaultProps = {
    rowIndex: 0,
    isChecked: false,
    disabled: false
};

export default Tr;
<commit_msg>update Tr<commit_after>/**
 * @file Tr component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';

import Td from '../_Td';

import HorizontalAlign from '../_statics/HorizontalAlign';
import SelectMode from '../_statics/SelectMode';
import SelectAllMode from '../_statics/SelectAllMode';
import SortingType from '../_statics/SortingType';

import Util from '../_vendors/Util';
import TableCalculation from '../_vendors/TableCalculation';

class Tr extends Component {

    static Align = HorizontalAlign;
    static SelectMode = SelectMode;
    static SelectAllMode = SelectAllMode;
    static SortingType = SortingType;

    constructor(props, ...restArgs) {
        super(props, ...restArgs);
    }

    handleClick = e => {
        const {data, rowIndex, disabled, onRowClick} = this.props;
        !disabled && onRowClick && onRowClick(data, rowIndex, e);
    };

    render() {

        const {
                className, columns, rowIndex, data, isChecked, disabled,
                onCellClick
            } = this.props,

            columnsWithSpan = TableCalculation.getColumnsWithSpan(columns, rowIndex);

        return (

                {
                    columnsWithSpan && columnsWithSpan.map(({column, span}, colIndex) => column ?

                        :
                        null
                    )
                }

        );

    }
}

Tr.propTypes = {

    rowIndex: PropTypes.number,

    /**
     * Children passed into table header.
     */
    columns: PropTypes.arrayOf(PropTypes.shape({

        /**
         * width of column
         */
        width: PropTypes.number,

        /**
         * minimum width of column
         */
        minWidth: PropTypes.number,

        /**
         * The class name of header.
         */
        headClassName: PropTypes.string,

        /**
         * Override the styles of header.
         */
        headStyle: PropTypes.object,

        /**
         * align of table header cell
         */
        headAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * The render content in header.
         * (1) string，example： 'id'
         * (2) callback，example：function (colIndex) {return colIndex;}
         */
        headRenderer: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),

        /**
         * The class name of td.
         */
        bodyClassName: PropTypes.string,

        /**
         * Override the styles of td.
         */
        bodyStyle: PropTypes.object,

        /**
         * The render content in table.
         * (1) data key，example： 'id'
         * (2) data key tamplate，example：'${id} - ${name}'
         * (3) callback，example：function (rowData, rowIndex, colIndex) {return rowData.id;}
         */
        bodyRenderer: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),

        /**
         * align of table body cell
         */
        bodyAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * The class name of footer.
         */
        footClassName: PropTypes.string,

        /**
         * Override the styles of footer.
         */
        footStyle: PropTypes.object,

        /**
         * The render content in footer.
         * (1) string，example： 'id'
         * (2) callback，example：function (colIndex) {return colIndex;}
         */
        footRenderer: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),

        /**
         * align of table footer cell
         */
        footAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * If true,this column can be sorted.
         */
        sortable: PropTypes.bool,

        /**
         * Sorting property.
         */
        sortingProp: PropTypes.string,

        defaultSortingType: PropTypes.oneOf(Util.enumerateValue(SortingType)),

        span: PropTypes.func

    })).isRequired,

    data: PropTypes.object,
    isChecked: PropTypes.bool,
    disabled: PropTypes.bool,
    className: PropTypes.string,

    onRowClick: PropTypes.func,
    onCellClick: PropTypes.func

};

Tr.defaultProps = {
    rowIndex: 0,
    isChecked: false,
    disabled: false
};

export default Tr;
<|endoftext|>


<commit_before>'use strict';

import HashSubscriber from 'javascript/api';
<commit_msg>fixes manual tests<commit_after>'use strict';

import HashSubscriber from 'javascript/api';

window.HashSubscriber = HashSubscriber;
<|endoftext|>


<commit_before>/* @flow */

import { inBrowser } from 'core/util/index'
import { isIE9 } from 'web/util/index'
import { cached, extend } from 'shared/util'
import { mergeVNodeHook } from 'core/vdom/helpers'
import {
  nextFrame,
  addTransitionClass,
  removeTransitionClass,
  whenTransitionEnds
} from '../transition-util'

export function enter (vnode: VNodeWithData) {
  const el: any = vnode.elm

  // call leave callback now
  if (el._leaveCb) {
    el._leaveCb.cancelled = true
    el._leaveCb()
  }

  const data = resolveTransition(vnode.data.transition)
  if (!data) {
    return
  }

  /* istanbul ignore if */
  if (el._enterCb) {
    return
  }

  const {
    css,
    enterClass,
    enterActiveClass,
    appearClass,
    appearActiveClass,
    beforeEnter,
    enter,
    afterEnter,
    enterCancelled,
    beforeAppear,
    appear,
    afterAppear,
    appearCancelled
  } = data

  const isAppear = !vnode.context._isMounted
  if (isAppear && !appear && appear !== '') {
    return
  }

  const startClass = isAppear ? appearClass : enterClass
  const activeClass = isAppear ? appearActiveClass : enterActiveClass
  const beforeEnterHook = isAppear ? (beforeAppear || beforeEnter) : beforeEnter
  const enterHook = isAppear ? (typeof appear === 'function' ? appear : enter) : enter
  const afterEnterHook = isAppear ? (afterAppear || afterEnter) : afterEnter
  const enterCancelledHook = isAppear ? (appearCancelled || enterCancelled) : enterCancelled

  const expectsCSS = css !== false && !isIE9
  const userWantsControl =
    enterHook &&
    // enterHook may be a bound method which exposes
    // the length of original fn as _length
    (enterHook._length || enterHook.length) > 1

  const cb = el._enterCb = once(() => {
    if (expectsCSS) {
      removeTransitionClass(el, activeClass)
    }
    if (cb.cancelled) {
      if (expectsCSS) {
        removeTransitionClass(el, startClass)
      }
      enterCancelledHook && enterCancelledHook(el)
    } else {
      afterEnterHook && afterEnterHook(el)
    }
    el._enterCb = null
  })

  // remove pending leave element on enter by injecting an insert hook
  mergeVNodeHook(vnode.data.hook || (vnode.data.hook = {}), 'insert', () => {
    const parent = el.parentNode
    const pendingNode = parent._pending && parent._pending[vnode.key]
    if (pendingNode && pendingNode.tag === vnode.tag && pendingNode.elm._leaveCb) {
      pendingNode.elm._leaveCb()
    }
    enterHook && enterHook(el, cb)
  })

  // start enter transition
  beforeEnterHook && beforeEnterHook(el)
  if (expectsCSS) {
    addTransitionClass(el, startClass)
    addTransitionClass(el, activeClass)
    nextFrame(() => {
      removeTransitionClass(el, startClass)
      if (!cb.cancelled && !userWantsControl) {
        whenTransitionEnds(el, cb)
      }
    })
  }

  if (!expectsCSS && !userWantsControl) {
    cb()
  }
}

export function leave (vnode: VNodeWithData, rm: Function) {
  const el: any = vnode.elm

  // call enter callback now
  if (el._enterCb) {
    el._enterCb.cancelled = true
    el._enterCb()
  }

  const data = resolveTransition(vnode.data.transition)
  if (!data) {
    return rm()
  }

  /* istanbul ignore if */
  if (el._leaveCb) {
    return
  }

  const {
    css,
    leaveClass,
    leaveActiveClass,
    beforeLeave,
    leave,
    afterLeave,
    leaveCancelled,
    delayLeave
  } = data

  const expectsCSS = css !== false && !isIE9
  const userWantsControl =
    leave &&
    // leave hook may be a bound method which exposes
    // the length of original fn as _length
    (leave._length || leave.length) > 1

  const cb = el._leaveCb = once(() => {
    if (el.parentNode && el.parentNode._pending) {
      el.parentNode._pending[vnode.key] = null
    }
    if (expectsCSS) {
      removeTransitionClass(el, leaveActiveClass)
    }
    if (cb.cancelled) {
      if (expectsCSS) {
        removeTransitionClass(el, leaveClass)
      }
      leaveCancelled && leaveCancelled(el)
    } else {
      rm()
      afterLeave && afterLeave(el)
    }
    el._leaveCb = null
  })

  if (delayLeave) {
    delayLeave(performLeave)
  } else {
    performLeave()
  }

  function performLeave () {
    // the delayed leave may have already been cancelled
    if (cb.cancelled) {
      return
    }
    // record leaving element
    if (!vnode.data.show) {
      (el.parentNode._pending || (el.parentNode._pending = {}))[vnode.key] = vnode
    }
    beforeLeave && beforeLeave(el)
    if (expectsCSS) {
      addTransitionClass(el, leaveClass)
      addTransitionClass(el, leaveActiveClass)
      nextFrame(() => {
        removeTransitionClass(el, leaveClass)
        if (!cb.cancelled && !userWantsControl) {
          whenTransitionEnds(el, cb)
        }
      })
    }
    leave && leave(el, cb)
    if (!expectsCSS && !userWantsControl) {
      cb()
    }
  }
}

function resolveTransition (def?: string | Object): ?Object {
  if (!def) {
    return
  }
  /* istanbul ignore else */
  if (typeof def === 'object') {
    const res = {}
    if (def.css !== false) {
      extend(res, autoCssTransition(def.name || 'v'))
    }
    extend(res, def)
    return res
  } else if (typeof def === 'string') {
    return autoCssTransition(def)
  }
}

const autoCssTransition: (name: string) => Object = cached(name => {
  return {
    enterClass: `${name}-enter`,
    leaveClass: `${name}-leave`,
    appearClass: `${name}-enter`,
    enterActiveClass: `${name}-enter-active`,
    leaveActiveClass: `${name}-leave-active`,
    appearActiveClass: `${name}-enter-active`
  }
})

function once (fn: Function): Function {
  let called = false
  return () => {
    if (!called) {
      called = true
      fn()
    }
  }
}

export default inBrowser ? {
  create (_: any, vnode: VNodeWithData) {
    if (!vnode.data.show) {
      enter(vnode)
    }
  },
  remove (vnode: VNode, rm: Function) {
    /* istanbul ignore else */
    if (!vnode.data.show) {
      leave(vnode, rm)
    } else {
      rm()
    }
  }
} : {}
<commit_msg>fix transition appear check (again)<commit_after>/* @flow */

import { inBrowser } from 'core/util/index'
import { isIE9 } from 'web/util/index'
import { cached, extend } from 'shared/util'
import { mergeVNodeHook } from 'core/vdom/helpers'
import {
  nextFrame,
  addTransitionClass,
  removeTransitionClass,
  whenTransitionEnds
} from '../transition-util'

export function enter (vnode: VNodeWithData) {
  const el: any = vnode.elm

  // call leave callback now
  if (el._leaveCb) {
    el._leaveCb.cancelled = true
    el._leaveCb()
  }

  const data = resolveTransition(vnode.data.transition)
  if (!data) {
    return
  }

  /* istanbul ignore if */
  if (el._enterCb) {
    return
  }

  const {
    css,
    enterClass,
    enterActiveClass,
    appearClass,
    appearActiveClass,
    beforeEnter,
    enter,
    afterEnter,
    enterCancelled,
    beforeAppear,
    appear,
    afterAppear,
    appearCancelled
  } = data

  const context = vnode.context.$parent || vnode.context
  const isAppear = !context._isMounted
  if (isAppear && !appear && appear !== '') {
    return
  }

  const startClass = isAppear ? appearClass : enterClass
  const activeClass = isAppear ? appearActiveClass : enterActiveClass
  const beforeEnterHook = isAppear ? (beforeAppear || beforeEnter) : beforeEnter
  const enterHook = isAppear ? (typeof appear === 'function' ? appear : enter) : enter
  const afterEnterHook = isAppear ? (afterAppear || afterEnter) : afterEnter
  const enterCancelledHook = isAppear ? (appearCancelled || enterCancelled) : enterCancelled

  const expectsCSS = css !== false && !isIE9
  const userWantsControl =
    enterHook &&
    // enterHook may be a bound method which exposes
    // the length of original fn as _length
    (enterHook._length || enterHook.length) > 1

  const cb = el._enterCb = once(() => {
    if (expectsCSS) {
      removeTransitionClass(el, activeClass)
    }
    if (cb.cancelled) {
      if (expectsCSS) {
        removeTransitionClass(el, startClass)
      }
      enterCancelledHook && enterCancelledHook(el)
    } else {
      afterEnterHook && afterEnterHook(el)
    }
    el._enterCb = null
  })

  // remove pending leave element on enter by injecting an insert hook
  mergeVNodeHook(vnode.data.hook || (vnode.data.hook = {}), 'insert', () => {
    const parent = el.parentNode
    const pendingNode = parent._pending && parent._pending[vnode.key]
    if (pendingNode && pendingNode.tag === vnode.tag && pendingNode.elm._leaveCb) {
      pendingNode.elm._leaveCb()
    }
    enterHook && enterHook(el, cb)
  })

  // start enter transition
  beforeEnterHook && beforeEnterHook(el)
  if (expectsCSS) {
    addTransitionClass(el, startClass)
    addTransitionClass(el, activeClass)
    nextFrame(() => {
      removeTransitionClass(el, startClass)
      if (!cb.cancelled && !userWantsControl) {
        whenTransitionEnds(el, cb)
      }
    })
  }

  if (!expectsCSS && !userWantsControl) {
    cb()
  }
}

export function leave (vnode: VNodeWithData, rm: Function) {
  const el: any = vnode.elm

  // call enter callback now
  if (el._enterCb) {
    el._enterCb.cancelled = true
    el._enterCb()
  }

  const data = resolveTransition(vnode.data.transition)
  if (!data) {
    return rm()
  }

  /* istanbul ignore if */
  if (el._leaveCb) {
    return
  }

  const {
    css,
    leaveClass,
    leaveActiveClass,
    beforeLeave,
    leave,
    afterLeave,
    leaveCancelled,
    delayLeave
  } = data

  const expectsCSS = css !== false && !isIE9
  const userWantsControl =
    leave &&
    // leave hook may be a bound method which exposes
    // the length of original fn as _length
    (leave._length || leave.length) > 1

  const cb = el._leaveCb = once(() => {
    if (el.parentNode && el.parentNode._pending) {
      el.parentNode._pending[vnode.key] = null
    }
    if (expectsCSS) {
      removeTransitionClass(el, leaveActiveClass)
    }
    if (cb.cancelled) {
      if (expectsCSS) {
        removeTransitionClass(el, leaveClass)
      }
      leaveCancelled && leaveCancelled(el)
    } else {
      rm()
      afterLeave && afterLeave(el)
    }
    el._leaveCb = null
  })

  if (delayLeave) {
    delayLeave(performLeave)
  } else {
    performLeave()
  }

  function performLeave () {
    // the delayed leave may have already been cancelled
    if (cb.cancelled) {
      return
    }
    // record leaving element
    if (!vnode.data.show) {
      (el.parentNode._pending || (el.parentNode._pending = {}))[vnode.key] = vnode
    }
    beforeLeave && beforeLeave(el)
    if (expectsCSS) {
      addTransitionClass(el, leaveClass)
      addTransitionClass(el, leaveActiveClass)
      nextFrame(() => {
        removeTransitionClass(el, leaveClass)
        if (!cb.cancelled && !userWantsControl) {
          whenTransitionEnds(el, cb)
        }
      })
    }
    leave && leave(el, cb)
    if (!expectsCSS && !userWantsControl) {
      cb()
    }
  }
}

function resolveTransition (def?: string | Object): ?Object {
  if (!def) {
    return
  }
  /* istanbul ignore else */
  if (typeof def === 'object') {
    const res = {}
    if (def.css !== false) {
      extend(res, autoCssTransition(def.name || 'v'))
    }
    extend(res, def)
    return res
  } else if (typeof def === 'string') {
    return autoCssTransition(def)
  }
}

const autoCssTransition: (name: string) => Object = cached(name => {
  return {
    enterClass: `${name}-enter`,
    leaveClass: `${name}-leave`,
    appearClass: `${name}-enter`,
    enterActiveClass: `${name}-enter-active`,
    leaveActiveClass: `${name}-leave-active`,
    appearActiveClass: `${name}-enter-active`
  }
})

function once (fn: Function): Function {
  let called = false
  return () => {
    if (!called) {
      called = true
      fn()
    }
  }
}

export default inBrowser ? {
  create (_: any, vnode: VNodeWithData) {
    if (!vnode.data.show) {
      enter(vnode)
    }
  },
  remove (vnode: VNode, rm: Function) {
    /* istanbul ignore else */
    if (!vnode.data.show) {
      leave(vnode, rm)
    } else {
      rm()
    }
  }
} : {}
<|endoftext|>