<commit_before>var util = require('util');
var EventEmitter = require('events').EventEmitter;
var Promise = require('bluebird');
var _ = require('lodash');

/**
 * Constructs a new Table instance.
 * @param {Database} db the database that the table belongs to.
 * @param {String} name the name of the table.
 * @constructor
 */
function Table (db, name) {
  this.db = db;
  this.name = name;
  this.columns = [];
  this.primaryKey = [];
  this.uniqueKeys = {};
  this.indexKeys = {};
  // this.foreignKeys = {};
  this.isReady = false;

  // init the EventEmitter
  EventEmitter.call(this);
  this.setMaxListeners(99);
}

// @extends EventEmitter
util.inherits(Table, EventEmitter);

/**
 * Retrieves column metadata from database.
 * @param {Function} [callback] an optional callback function with (err, columns) arguments.
 * @returns {Promise} resolving to Array.<object>
 * @private
 */
Table.prototype._getColumns = function (callback) {
  return Promise.resolve().nodeify(callback);
};

/**
 * Retrieves primary key metadata from database.
 * @param {Function} [callback] an optional callback function with (err, primaryKey) arguments.
 * @returns {Promise} resolving to Array.<string>
 * @private
 */
Table.prototype._getPrimaryKey = function (callback) {
  return Promise.resolve().nodeify(callback);
};

/**
 * Retrieves unique key metadata from database.
 * @param {Function} [callback] an optional callback function with (err, uniqueKeys) arguments.
 * @returns {Promise} resolving to object
 * @private
 */
Table.prototype._getUniqueKeys = function (callback) {
  return Promise.resolve().nodeify(callback);
};

/**
 * Retrieves index key metadata from database.
 * @param {Function} [callback] an optional callback function with (err, indexKeys) arguments.
 * @returns {Promise} resolving to object
 * @private
 */
Table.prototype._getIndexKeys = function (callback) {
  return Promise.resolve().nodeify(callback);
};

/**
 * Retrieves foreign key metadata from database.
 * @param {Function} [callback] an optional callback function with (err, foreignKeys) arguments.
 * @returns {Promise} resolving to object
 * @private
 */
Table.prototype._getForeignKeys = function (callback) {
  return Promise.resolve().nodeify(callback);
};

/**
 * Loads table metadata from database.
 * @param {function} [callback] an optional callback function with (err, foreignKeys) arguments.
 * @returns {Promise}
 * @emits Table#ready
 * @emits Table#error
 */
Table.prototype.loadMeta = function (callback) {
  var _this = this;

  this.db.hasTable(this.name)
    .then(function (hasTable) {
      // make sure table exists
      if (!hasTable) {
        _this.emit('error', new Error('Table "' + _this.name + '" does not exist in database'));
        return;
      }

      // retrieve metadata
      return Promise.props({
        columns: _this.getColumns(),
        primaryKey: _this.getPrimaryKey(),
        uniqueKeys: _this.getUniqueKeys(),
        indexKeys: _this.getIndexKeys(),
        // foreignKeys: _this._getForeignKeys()
      })
        // update table properties + emit @ready
        .then(function(results) {
          _this.columns = results.columns;
          _this.primaryKey = results.primaryKey;
          _this.uniqueKeys = results.uniqueKeys;
          _this.indexKeys = results.indexKeys;
          _this.foreignKeys = results.foreignKeys;
          _this.isReady = true;
          _this.emit('ready');
        });
    })
    .nodeify(callback);
};

/**
 * Indicates whether the specified column exists in table.
 * This method will always return false until database is ready.
 * @param {string} name the name of the column.
 * @returns {boolean}
 * @example
 *
 * table.hasColumn('id');
 */
Table.prototype.hasColumn = function (name) {
  return this.columns.some(function (column) {
    return column.name === name;
  });
};

/**
 * Indicates whether the specified column(s) represent a primary key.
 * Primary keys may be compound, i.e. composed of multiple columns, hence the acceptance of multiple params in this function.
 * This method will always return false until database is ready.
 * @param {...string} columns the name of the columns.
 * @returns {boolean}
 * @example
 *
 * table.isPrimaryKey('id');
 */
Table.prototype.isPrimaryKey = function () {
  var columns = Array.prototype.slice.call(arguments, 0);
  return _.xor(this.primaryKey, columns).length === 0;
};

/**
 * Indicates whether the specified column(s) represent a unique key.
 * Unique keys may be compound, i.e. composed of multiple columns, hence the acceptance of multiple params.
 * This method will always return false until database is ready.
 * @param {...string} columns the name of the columns.
 * @returns {boolean}
 * @example
 *
 * table.isUniqueKey('pid');
 */
Table.prototype.isUniqueKey = function () {
  var columns = Array.prototype.slice.call(arguments, 0);
  return _.some(this.uniqueKeys, function (e) {
    return _.xor(e, columns).length === 0;
  });
};

/**
 * Indicates whether the specified column(s) represent an index key.
 * Index keys may be compound, i.e. composed of multiple columns, hence the acceptance of multiple params.
 * This method will always return false until database is ready.
 * @param {...string} columns the name of the columns.
 * @returns {boolean}
 * @example
 *
 * table.isIndexKey('firstName', 'lastName');
 */
Table.prototype.isIndexKey = function () {
  var columns = Array.prototype.slice.call(arguments, 0);
  return _.some(this.indexKeys, function (e) {
    return _.xor(e, columns).length === 0;
  });
};

/**
 * Indicates whether the specified column is automatically incremented.
 * This method will always return false until database is ready.
 * @param {string} columnName the name of the column.
 * @returns {boolean}
 * @example
 *
 * table.isAutoInc('id');
 */
Table.prototype.isAutoInc = function (columnName) {
  return this.columns.some(function (column) {
    return column.isAutoInc && column.name === columnName;
  });
};

/**
 * Indicates whether the table has a simple automatically incremented primary key.
 * This method will always return false until database is ready.
 * @returns {boolean}
 * @example
 *
 * table.hasAutoIncPrimaryKey();
 */
Table.protype.hasAutoIncPrimaryKey = function () {
  return this.primaryKey.length === 1 && this.isAutoInc(this.primaryKey[0]);
};

/**
 * Enqueues the given resolver function until the Table is ready.
 * Executes the resolver immediately after connection.
 * @param {function} resolver
 * @return {Promise}
 * @private
 */
Table.prototype._enqueue = function (resolver) {
  var _this = this;

  return new Promise(function(resolve, reject) {
    if (_this.isReady) {
      resolver(resolve, reject);
    } else {
      // wait for table to load metadata
      _this.once('ready', function () {
        resolver(resolve, reject);
      });
    }
  });
};

/**
 * Retrieves the designated record(s) from this table.
 * @param {(Boolean|Number|String|Date|Object|Array.<Object>)} [query] a query object.
 * @param {Function} [callback] an optional callback function
 * @returns {Promise} resolving to an Array of records
 */
Table.prototype.get = function (query, callback) {
  return Promise.resolve().nodeify(callback);
};

/**
 * Counts the designated record(s) in this table.
 * @param {(Boolean|Number|String|Date|Object|Array.<Object>)} [query] a query object.
 * @param {Function} [callback] an optional callback function
 * @returns {Promise} resolving to the count of records
 */
Table.prototype.count = function (query, callback) {
  return Promise.resolve().nodeify(callback);
};

/**
 * Deletes the designated record(s) from this table.
 * @param {(Boolean|Number|String|Date|Object|Array.<Object>)} [query] a query object.
 * @param {Function} [callback] an optional callback function
 * @returns {Promise}
 */
Table.prototype.del = function (query, callback) {
  return Promise.resolve().nodeify(callback);
};

/**
 * Creates or updates (if already exists) the specified record(s) in table.
 * @param {(Object|Array.<Object>)} attrs the attributes of the record(s) to create/update
 * @param {Object} options query options
 * @param {Function} [callback] an optional callback function
 * @returns {Promise} resolving to the primary key of the created/updated record(s)
 */
Table.prototype.set = function (attrs, options, callback) {
  return Promise.resolve().nodeify(callback);
};

/**
 * Creates the specified record(s) in table.
 * @param {(Object|Array.<Object>)} attrs the attributes of the record(s) to create
 * @param {Object} options query options
 * @param {Function} [callback] an optional callback function
 * @returns {Promise} resolving to the primary key of the created record(s).
 */
Table.prototype.add = function (attrs, options, callback) {
  return Promise.resolve().nodeify(callback);
};

/**
 * Indicates whether the specified object is Table.
 * @param {*} obj the object to test
 * @returns {boolean}
 */
Table.isTable = function (obj) {
  return obj instanceof Table;
};

module.exports = Table;
<commit_msg>Fix typo in prototype keyword<commit_after>var util = require('util');
var EventEmitter = require('events').EventEmitter;
var Promise = require('bluebird');
var _ = require('lodash');

/**
 * Constructs a new Table instance.
 * @param {Database} db the database that the table belongs to.
 * @param {String} name the name of the table.
 * @constructor
 */
function Table (db, name) {
  this.db = db;
  this.name = name;
  this.columns = [];
  this.primaryKey = [];
  this.uniqueKeys = {};
  this.indexKeys = {};
  // this.foreignKeys = {};
  this.isReady = false;

  // init the EventEmitter
  EventEmitter.call(this);
  this.setMaxListeners(99);
}

// @extends EventEmitter
util.inherits(Table, EventEmitter);

/**
 * Retrieves column metadata from database.
 * @param {Function} [callback] an optional callback function with (err, columns) arguments.
 * @returns {Promise} resolving to Array.<object>
 * @private
 */
Table.prototype._getColumns = function (callback) {
  return Promise.resolve().nodeify(callback);
};

/**
 * Retrieves primary key metadata from database.
 * @param {Function} [callback] an optional callback function with (err, primaryKey) arguments.
 * @returns {Promise} resolving to Array.<string>
 * @private
 */
Table.prototype._getPrimaryKey = function (callback) {
  return Promise.resolve().nodeify(callback);
};

/**
 * Retrieves unique key metadata from database.
 * @param {Function} [callback] an optional callback function with (err, uniqueKeys) arguments.
 * @returns {Promise} resolving to object
 * @private
 */
Table.prototype._getUniqueKeys = function (callback) {
  return Promise.resolve().nodeify(callback);
};

/**
 * Retrieves index key metadata from database.
 * @param {Function} [callback] an optional callback function with (err, indexKeys) arguments.
 * @returns {Promise} resolving to object
 * @private
 */
Table.prototype._getIndexKeys = function (callback) {
  return Promise.resolve().nodeify(callback);
};

/**
 * Retrieves foreign key metadata from database.
 * @param {Function} [callback] an optional callback function with (err, foreignKeys) arguments.
 * @returns {Promise} resolving to object
 * @private
 */
Table.prototype._getForeignKeys = function (callback) {
  return Promise.resolve().nodeify(callback);
};

/**
 * Loads table metadata from database.
 * @param {function} [callback] an optional callback function with (err, foreignKeys) arguments.
 * @returns {Promise}
 * @emits Table#ready
 * @emits Table#error
 */
Table.prototype.loadMeta = function (callback) {
  var _this = this;

  this.db.hasTable(this.name)
    .then(function (hasTable) {
      // make sure table exists
      if (!hasTable) {
        _this.emit('error', new Error('Table "' + _this.name + '" does not exist in database'));
        return;
      }

      // retrieve metadata
      return Promise.props({
        columns: _this.getColumns(),
        primaryKey: _this.getPrimaryKey(),
        uniqueKeys: _this.getUniqueKeys(),
        indexKeys: _this.getIndexKeys(),
        // foreignKeys: _this._getForeignKeys()
      })
        // update table properties + emit @ready
        .then(function(results) {
          _this.columns = results.columns;
          _this.primaryKey = results.primaryKey;
          _this.uniqueKeys = results.uniqueKeys;
          _this.indexKeys = results.indexKeys;
          _this.foreignKeys = results.foreignKeys;
          _this.isReady = true;
          _this.emit('ready');
        });
    })
    .nodeify(callback);
};

/**
 * Indicates whether the specified column exists in table.
 * This method will always return false until database is ready.
 * @param {string} name the name of the column.
 * @returns {boolean}
 * @example
 *
 * table.hasColumn('id');
 */
Table.prototype.hasColumn = function (name) {
  return this.columns.some(function (column) {
    return column.name === name;
  });
};

/**
 * Indicates whether the specified column(s) represent a primary key.
 * Primary keys may be compound, i.e. composed of multiple columns, hence the acceptance of multiple params in this function.
 * This method will always return false until database is ready.
 * @param {...string} columns the name of the columns.
 * @returns {boolean}
 * @example
 *
 * table.isPrimaryKey('id');
 */
Table.prototype.isPrimaryKey = function () {
  var columns = Array.prototype.slice.call(arguments, 0);
  return _.xor(this.primaryKey, columns).length === 0;
};

/**
 * Indicates whether the specified column(s) represent a unique key.
 * Unique keys may be compound, i.e. composed of multiple columns, hence the acceptance of multiple params.
 * This method will always return false until database is ready.
 * @param {...string} columns the name of the columns.
 * @returns {boolean}
 * @example
 *
 * table.isUniqueKey('pid');
 */
Table.prototype.isUniqueKey = function () {
  var columns = Array.prototype.slice.call(arguments, 0);
  return _.some(this.uniqueKeys, function (e) {
    return _.xor(e, columns).length === 0;
  });
};

/**
 * Indicates whether the specified column(s) represent an index key.
 * Index keys may be compound, i.e. composed of multiple columns, hence the acceptance of multiple params.
 * This method will always return false until database is ready.
 * @param {...string} columns the name of the columns.
 * @returns {boolean}
 * @example
 *
 * table.isIndexKey('firstName', 'lastName');
 */
Table.prototype.isIndexKey = function () {
  var columns = Array.prototype.slice.call(arguments, 0);
  return _.some(this.indexKeys, function (e) {
    return _.xor(e, columns).length === 0;
  });
};

/**
 * Indicates whether the specified column is automatically incremented.
 * This method will always return false until database is ready.
 * @param {string} columnName the name of the column.
 * @returns {boolean}
 * @example
 *
 * table.isAutoInc('id');
 */
Table.prototype.isAutoInc = function (columnName) {
  return this.columns.some(function (column) {
    return column.isAutoInc && column.name === columnName;
  });
};

/**
 * Indicates whether the table has a simple automatically incremented primary key.
 * This method will always return false until database is ready.
 * @returns {boolean}
 * @example
 *
 * table.hasAutoIncPrimaryKey();
 */
Table.prototype.hasAutoIncPrimaryKey = function () {
  return this.primaryKey.length === 1 && this.isAutoInc(this.primaryKey[0]);
};

/**
 * Enqueues the given resolver function until the Table is ready.
 * Executes the resolver immediately after connection.
 * @param {function} resolver
 * @return {Promise}
 * @private
 */
Table.prototype._enqueue = function (resolver) {
  var _this = this;

  return new Promise(function(resolve, reject) {
    if (_this.isReady) {
      resolver(resolve, reject);
    } else {
      // wait for table to load metadata
      _this.once('ready', function () {
        resolver(resolve, reject);
      });
    }
  });
};

/**
 * Retrieves the designated record(s) from this table.
 * @param {(Boolean|Number|String|Date|Object|Array.<Object>)} [query] a query object.
 * @param {Function} [callback] an optional callback function
 * @returns {Promise} resolving to an Array of records
 */
Table.prototype.get = function (query, callback) {
  return Promise.resolve().nodeify(callback);
};

/**
 * Counts the designated record(s) in this table.
 * @param {(Boolean|Number|String|Date|Object|Array.<Object>)} [query] a query object.
 * @param {Function} [callback] an optional callback function
 * @returns {Promise} resolving to the count of records
 */
Table.prototype.count = function (query, callback) {
  return Promise.resolve().nodeify(callback);
};

/**
 * Deletes the designated record(s) from this table.
 * @param {(Boolean|Number|String|Date|Object|Array.<Object>)} [query] a query object.
 * @param {Function} [callback] an optional callback function
 * @returns {Promise}
 */
Table.prototype.del = function (query, callback) {
  return Promise.resolve().nodeify(callback);
};

/**
 * Creates or updates (if already exists) the specified record(s) in table.
 * @param {(Object|Array.<Object>)} attrs the attributes of the record(s) to create/update
 * @param {Object} options query options
 * @param {Function} [callback] an optional callback function
 * @returns {Promise} resolving to the primary key of the created/updated record(s)
 */
Table.prototype.set = function (attrs, options, callback) {
  return Promise.resolve().nodeify(callback);
};

/**
 * Creates the specified record(s) in table.
 * @param {(Object|Array.<Object>)} attrs the attributes of the record(s) to create
 * @param {Object} options query options
 * @param {Function} [callback] an optional callback function
 * @returns {Promise} resolving to the primary key of the created record(s).
 */
Table.prototype.add = function (attrs, options, callback) {
  return Promise.resolve().nodeify(callback);
};

/**
 * Indicates whether the specified object is Table.
 * @param {*} obj the object to test
 * @returns {boolean}
 */
Table.isTable = function (obj) {
  return obj instanceof Table;
};

module.exports = Table;
<|endoftext|>


<commit_before>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow
 */
import React, { Component } from 'react';
import { Platform, StyleSheet, Text, View, Image, TextInput, Button, Alert } from 'react-native';

export default class App extends Component {
    _onPressButton() {
        Alert.alert('You tapped the button!')
    }

    render() {
        return (
            <View style={styles.container}>
                <View style={styles.buttonContainer}>
                    <Button
                        onPress={this._onPressButton}
                        title="Press Me"
                    />
                </View>
                <View style={styles.buttonContainer}>
                    <Button
                        onPress={this._onPressButton}
                        title="Press Me"
                        color="#841584"
                    />
                </View>
                <View style={styles.alternativeLayoutButtonContainer}>
                    <Button
                        onPress={this._onPressButton}
                        title="This looks great!"
                    />
                    <Button
                        onPress={this._onPressButton}
                        title="OK!"
                        color="#841584"
                    />
                </View>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
    },
    buttonContainer: {
        margin: 20
    },
    alternativeLayoutButtonContainer: {
        margin: 20,
        flexDirection: 'row',
        justifyContent: 'space-between'
    }
});
<commit_msg>Add fetch sample<commit_after>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow
 */
import React from 'react';
import { FlatList, ActivityIndicator, Text, View  } from 'react-native';

export default class App extends React.Component {

  constructor(props){
    super(props);
    this.state ={ isLoading: true}
  }

  componentDidMount(){
    return fetch('https://facebook.github.io/react-native/movies.json')
      .then((response) => response.json())
      .then((responseJson) => {

        this.setState({
          isLoading: false,
          dataSource: responseJson.movies,
        }, function(){

        });

      })
      .catch((error) =>{
        console.error(error);
      });
  }

  render(){

    if(this.state.isLoading){
      return(
        <View style={{flex: 1, padding: 20}}>
          <ActivityIndicator/>
        </View>
      )
    }

    return(
      <View style={{flex: 1, paddingTop:20}}>
        <FlatList
          data={this.state.dataSource}
          renderItem={({item}) => <Text>{item.title}, {item.releaseYear}</Text>}
          keyExtractor={({id}, index) => id}
        />
      </View>
    );
  }
}
<|endoftext|>


<commit_before>/* global process, __dirname */

// Ensure running a compatible version of Node before getting too far...
var semver = require('semver')
var packageJson = require('../package.json')
if (packageJson.engines &&
    packageJson.engines.node &&
    !semver.satisfies(process.versions.node, packageJson.engines.node)) {
    console.error('Incompatible version of node - running [%s] but require [%s]',
            process.versions.node, packageJson.engines.node)
    process.exit(1)
}

/**
 * Configuration dependencies
 */

var cwd = process.cwd()
var path = require('path')
var settings = require('./settings')
var setup = require('./setup')
var client = require('./redis').getClient()
var logger = require('./logger')(settings.logger)
require('./mailer').getMailer()
require('./database')()
var authenticator = require('../lib/authenticator')
var express = require('express')
var cons = require('consolidate')
var cookieParser = require('cookie-parser')
var bodyParser = require('body-parser')
var session = require('express-session')
var RedisStore = require('connect-redis')(session)
var connectFlash = require('connect-flash')
var cors = require('cors')
var sessionStore = new RedisStore({ client: client })

/**
 * Read setup token if the server is in out-of-box mode
 */

setup.isOOB(function (err, oob) {
  if (err) { return console.log(err) }
  if (oob) {
    setup.readSetupToken(function (err, token) {
      if (err) { return console.log(err) }
      settings.setupToken = token
    })
  }
})

/**
 * Exports
 */

module.exports = function (server) {
  /**
   * Disable default header
   */

  server.disable('x-powered-by')

  /**
   * Views configuration
   */

  var engine = settings.view_engine || 'jade'
  server.engine(engine, cons[engine])
  server.set('view engine', engine)

  // First, look for views in the project directory.
  // If absent, look in the package views directory.
  server.set('views', [
    path.join(cwd, 'views'),
    path.join(__dirname, '..', 'views')
  ])

  /**
   * Settings
   */

  Object.keys(settings).forEach(function (key) {
    server.set(key, settings[key])
  })

  /**
   * Request Parsing
   */

  server.use(cookieParser(settings.cookie_secret))
  server.use(bodyParser.urlencoded({ extended: false }))
  server.use(bodyParser.json())

  /**
   * Express Session
   */

  if (process.env.NODE_ENV === 'production') {
    server.use(session({
      store: sessionStore,
      resave: false,
      saveUninitialized: false,
      secret: settings.session_secret,
      proxy: true,
      cookie: {
        secure: true
      }
    }))
  } else {
    server.use(session({
      store: sessionStore,
      resave: false,
      saveUninitialized: false,
      secret: settings.session_secret
    }))
  }

  /**
   * Flash messaging
   */

  server.use(connectFlash())

  /**
   * Set user on request
   */

  server.use(authenticator.setUserOnRequest)

  /**
   * Cross-Origin Support
   */

  server.use(cors())

  /**
   * Logging
   */

  server.use(logger.middleware())

  /**
   * Serve Static Files
   *
   * First, look for files in the project `public` directory.
   * If absent, look in the package `public` directory.
   */

  server.use(express.static(path.join(cwd, 'public')))
  server.use(express.static(path.join(__dirname, '..', 'public')))

  /**
   * OpenID Provider Metadata Properties
   */

  var parameters = [
    'issuer',
    'authorization_endpoint',
    'token_endpoint',
    'userinfo_endpoint',
    'jwks_uri',
    'registration_endpoint',
    'scopes_supported',
    'response_types_supported',
    'response_modes_supported',
    'grant_types_supported',
    'acr_values_supported',
    'subject_types_supported',
    'id_token_signing_alg_values_supported',
    'id_token_encryption_alg_values_supported',
    'id_token_encryption_enc_values_supported',
    'userinfo_signing_alg_values_supported',
    'userinfo_encryption_alg_values_supported',
    'userinfo_encryption_enc_values_supported',
    'request_object_signing_alg_values_supported',
    'request_object_encryption_alg_values_supported',
    'request_object_encryption_enc_values_supported',
    'token_endpoint_auth_methods_supported',
    'token_endpoint_auth_signing_alg_values_supported',
    'display_values_supported',
    'claim_types_supported',
    'claims_supported',
    'service_documentation',
    'claims_locales_supported',
    'ui_locales_supported',
    'claims_parameter_supported',
    'request_parameter_supported',
    'request_uri_parameter_supported',
    'require_request_uri_registration',
    'op_policy_uri',
    'op_tos_uri',
    'check_session_iframe',
    'end_session_endpoint'
  ]

  /**
   * Build Provider Configuration Info from Metadata
   */

  server.OpenIDConfiguration = parameters.reduce(function (config, param) {
    var value = settings[param]
    if (value) { config[param] = value }
    return config
  }, {})
}
<commit_msg>style: Conform to JS Standard Style<commit_after>/* global process, __dirname */

// Ensure running a compatible version of Node before getting too far...
var semver = require('semver')
var packageJson = require('../package.json')
if (packageJson.engines &&
  packageJson.engines.node &&
  !semver.satisfies(process.versions.node, packageJson.engines.node)) {
  console.error('Incompatible version of node - running [%s] but require [%s]',
    process.versions.node, packageJson.engines.node)
  process.exit(1)
}

/**
 * Configuration dependencies
 */

var cwd = process.cwd()
var path = require('path')
var settings = require('./settings')
var setup = require('./setup')
var client = require('./redis').getClient()
var logger = require('./logger')(settings.logger)
require('./mailer').getMailer()
require('./database')()
var authenticator = require('../lib/authenticator')
var express = require('express')
var cons = require('consolidate')
var cookieParser = require('cookie-parser')
var bodyParser = require('body-parser')
var session = require('express-session')
var RedisStore = require('connect-redis')(session)
var connectFlash = require('connect-flash')
var cors = require('cors')
var sessionStore = new RedisStore({ client: client })

/**
 * Read setup token if the server is in out-of-box mode
 */

setup.isOOB(function (err, oob) {
  if (err) { return console.log(err) }
  if (oob) {
    setup.readSetupToken(function (err, token) {
      if (err) { return console.log(err) }
      settings.setupToken = token
    })
  }
})

/**
 * Exports
 */

module.exports = function (server) {
  /**
   * Disable default header
   */

  server.disable('x-powered-by')

  /**
   * Views configuration
   */

  var engine = settings.view_engine || 'jade'
  server.engine(engine, cons[engine])
  server.set('view engine', engine)

  // First, look for views in the project directory.
  // If absent, look in the package views directory.
  server.set('views', [
    path.join(cwd, 'views'),
    path.join(__dirname, '..', 'views')
  ])

  /**
   * Settings
   */

  Object.keys(settings).forEach(function (key) {
    server.set(key, settings[key])
  })

  /**
   * Request Parsing
   */

  server.use(cookieParser(settings.cookie_secret))
  server.use(bodyParser.urlencoded({ extended: false }))
  server.use(bodyParser.json())

  /**
   * Express Session
   */

  if (process.env.NODE_ENV === 'production') {
    server.use(session({
      store: sessionStore,
      resave: false,
      saveUninitialized: false,
      secret: settings.session_secret,
      proxy: true,
      cookie: {
        secure: true
      }
    }))
  } else {
    server.use(session({
      store: sessionStore,
      resave: false,
      saveUninitialized: false,
      secret: settings.session_secret
    }))
  }

  /**
   * Flash messaging
   */

  server.use(connectFlash())

  /**
   * Set user on request
   */

  server.use(authenticator.setUserOnRequest)

  /**
   * Cross-Origin Support
   */

  server.use(cors())

  /**
   * Logging
   */

  server.use(logger.middleware())

  /**
   * Serve Static Files
   *
   * First, look for files in the project `public` directory.
   * If absent, look in the package `public` directory.
   */

  server.use(express.static(path.join(cwd, 'public')))
  server.use(express.static(path.join(__dirname, '..', 'public')))

  /**
   * OpenID Provider Metadata Properties
   */

  var parameters = [
    'issuer',
    'authorization_endpoint',
    'token_endpoint',
    'userinfo_endpoint',
    'jwks_uri',
    'registration_endpoint',
    'scopes_supported',
    'response_types_supported',
    'response_modes_supported',
    'grant_types_supported',
    'acr_values_supported',
    'subject_types_supported',
    'id_token_signing_alg_values_supported',
    'id_token_encryption_alg_values_supported',
    'id_token_encryption_enc_values_supported',
    'userinfo_signing_alg_values_supported',
    'userinfo_encryption_alg_values_supported',
    'userinfo_encryption_enc_values_supported',
    'request_object_signing_alg_values_supported',
    'request_object_encryption_alg_values_supported',
    'request_object_encryption_enc_values_supported',
    'token_endpoint_auth_methods_supported',
    'token_endpoint_auth_signing_alg_values_supported',
    'display_values_supported',
    'claim_types_supported',
    'claims_supported',
    'service_documentation',
    'claims_locales_supported',
    'ui_locales_supported',
    'claims_parameter_supported',
    'request_parameter_supported',
    'request_uri_parameter_supported',
    'require_request_uri_registration',
    'op_policy_uri',
    'op_tos_uri',
    'check_session_iframe',
    'end_session_endpoint'
  ]

  /**
   * Build Provider Configuration Info from Metadata
   */

  server.OpenIDConfiguration = parameters.reduce(function (config, param) {
    var value = settings[param]
    if (value) { config[param] = value }
    return config
  }, {})
}
<|endoftext|>


<commit_before>/* global AFRAME, THREE */
const inherit = AFRAME.utils.extendDeep
const buttonsCore = require('./prototypes/buttons-proto.js')
const networkedCore = require('./prototypes/networked-proto.js')
// new object with all core modules
const base = inherit({}, buttonsCore, networkedCore)
AFRAME.registerComponent('stretchable', inherit(base, {
  schema: {
    usePhysics: {default: 'ifavailable'},
    invert: {default: false},
    physicsUpdateRate: {default: 100},
    useWorldPosition: {type: 'bool', default: false}
  },
  init: function () {
    this.STRETCHED_STATE = 'stretched'
    this.STRETCH_EVENT = 'stretch-start'
    this.UNSTRETCH_EVENT = 'stretch-end'
    this.stretched = false
    this.stretchers = []

    this.scale = new THREE.Vector3()
    this.handPos = new THREE.Vector3()
    this.otherHandPos = new THREE.Vector3()

    this.start = this.start.bind(this)
    this.end = this.end.bind(this)

    this.el.addEventListener(this.STRETCH_EVENT, this.start)
    this.el.addEventListener(this.UNSTRETCH_EVENT, this.end)
  },
  update: function (oldDat) {
    this.updateBodies = AFRAME.utils.throttleTick(
      this._updateBodies,
      this.data.physicsUpdateRate,
      this
    )
  },
  tick: function (time, timeDelta) {
    if (!this.stretched) { return }
    this.scale.copy(this.el.getAttribute('scale'))
    if (this.data.useWorldPosition) {
      this.stretchers[0].object3D.getWorldPosition(this.handPos)
      this.stretchers[1].object3D.getWorldPosition(this.otherHandPos)
    } else {
      this.handPos.copy(this.stretchers[0].getAttribute('position'))
      this.otherHandPos.copy(this.stretchers[1].getAttribute('position'))
    }
    const currentStretch = this.handPos.distanceTo(this.otherHandPos)
    let deltaStretch = 1
    if (this.previousStretch !== null && currentStretch !== 0) {
      deltaStretch = Math.pow(
          currentStretch / this.previousStretch,
          (this.data.invert)
            ? -1
            : 1
      )
    }
    this.previousStretch = currentStretch
    if (this.previousPhysicsStretch == null) {
      // establish correct baseline even if throttled function isn't called
      this.previousPhysicsStretch = currentStretch
    }
    this.scale.multiplyScalar(deltaStretch)
    this.el.setAttribute('scale', this.scale)
    // scale update for all nested physics bodies (throttled)
    this.updateBodies(time, timeDelta)
  },
  remove: function () {
    this.el.removeEventListener(this.STRETCH_EVENT, this.start)
    this.el.removeEventListener(this.UNSTRETCH_EVENT, this.end)
  },
  start: function (evt) {
    if (this.stretched || this.stretchers.includes(evt.detail.hand) ||
        !this.startButtonOk(evt) || evt.defaultPrevented ||
        !this.networkedOk()) {
      return
    } // already stretched or already captured this hand or wrong button
    this.stretchers.push(evt.detail.hand)
    if (this.stretchers.length === 2) {
      this.stretched = true
      this.previousStretch = null
      this.previousPhysicsStretch = null
      this.el.addState(this.STRETCHED_STATE)
    }
    if (evt.preventDefault) { evt.preventDefault() } // gesture accepted
  },
  end: function (evt) {
    var stretcherIndex = this.stretchers.indexOf(evt.detail.hand)
    if (evt.defaultPrevented || !this.endButtonOk(evt)) { return }
    if (stretcherIndex !== -1) {
      this.stretchers.splice(stretcherIndex, 1)
      this.stretched = false
      this.el.removeState(this.STRETCHED_STATE)
      // override throttle to push last stretch to physics bodies
      this._updateBodies()
    }
    if (evt.preventDefault) { evt.preventDefault() }
  },
  _updateBodies: function () {
    if (!this.el.body || this.data.usePhysics === 'never') { return }
    const currentStretch = this.previousStretch // last visible geometry stretch
    let deltaStretch = 1
    if (this.previousPhysicsStretch !== null && currentStretch > 0) {
      deltaStretch = Math.pow(
          currentStretch / this.previousPhysicsStretch,
          (this.data.invert)
            ? -1
            : 1
      )
    }
    this.previousPhysicsStretch = currentStretch
    if (deltaStretch === 1) { return }
    for (let c of this.el.children) { this.stretchBody(c, deltaStretch) }
    this.stretchBody(this.el, deltaStretch)
  },
  stretchBody: function (el, deltaStretch) {
    if (!el.body) { return }
    let physicsShape
    let offset
    for (let i = 0; i < el.body.shapes.length; i++) {
      physicsShape = el.body.shapes[i]
      if (physicsShape.halfExtents) {
        physicsShape.halfExtents
            .scale(deltaStretch, physicsShape.halfExtents)
        physicsShape.updateConvexPolyhedronRepresentation()
      } else if (physicsShape.radius) {
        physicsShape.radius *= deltaStretch
        physicsShape.updateBoundingSphereRadius()
      } else if (!this.shapeWarned) {
        console.warn('Unable to stretch physics body: unsupported shape')
        this.shapeWarned = true
      }
      // also move offset to match scale change
      offset = el.body.shapeOffsets[i]
      offset.scale(deltaStretch, offset)
    }
    el.body.updateBoundingRadius()
  }
}))
<commit_msg>just use default<commit_after>/* global AFRAME, THREE */
const inherit = AFRAME.utils.extendDeep
const buttonsCore = require('./prototypes/buttons-proto.js')
const networkedCore = require('./prototypes/networked-proto.js')
// new object with all core modules
const base = inherit({}, buttonsCore, networkedCore)
AFRAME.registerComponent('stretchable', inherit(base, {
  schema: {
    usePhysics: {default: 'ifavailable'},
    invert: {default: false},
    physicsUpdateRate: {default: 100},
    useWorldPosition: {default: false}
  },
  init: function () {
    this.STRETCHED_STATE = 'stretched'
    this.STRETCH_EVENT = 'stretch-start'
    this.UNSTRETCH_EVENT = 'stretch-end'
    this.stretched = false
    this.stretchers = []

    this.scale = new THREE.Vector3()
    this.handPos = new THREE.Vector3()
    this.otherHandPos = new THREE.Vector3()

    this.start = this.start.bind(this)
    this.end = this.end.bind(this)

    this.el.addEventListener(this.STRETCH_EVENT, this.start)
    this.el.addEventListener(this.UNSTRETCH_EVENT, this.end)
  },
  update: function (oldDat) {
    this.updateBodies = AFRAME.utils.throttleTick(
      this._updateBodies,
      this.data.physicsUpdateRate,
      this
    )
  },
  tick: function (time, timeDelta) {
    if (!this.stretched) { return }
    this.scale.copy(this.el.getAttribute('scale'))
    if (this.data.useWorldPosition) {
      this.stretchers[0].object3D.getWorldPosition(this.handPos)
      this.stretchers[1].object3D.getWorldPosition(this.otherHandPos)
    } else {
      this.handPos.copy(this.stretchers[0].getAttribute('position'))
      this.otherHandPos.copy(this.stretchers[1].getAttribute('position'))
    }
    const currentStretch = this.handPos.distanceTo(this.otherHandPos)
    let deltaStretch = 1
    if (this.previousStretch !== null && currentStretch !== 0) {
      deltaStretch = Math.pow(
          currentStretch / this.previousStretch,
          (this.data.invert)
            ? -1
            : 1
      )
    }
    this.previousStretch = currentStretch
    if (this.previousPhysicsStretch == null) {
      // establish correct baseline even if throttled function isn't called
      this.previousPhysicsStretch = currentStretch
    }
    this.scale.multiplyScalar(deltaStretch)
    this.el.setAttribute('scale', this.scale)
    // scale update for all nested physics bodies (throttled)
    this.updateBodies(time, timeDelta)
  },
  remove: function () {
    this.el.removeEventListener(this.STRETCH_EVENT, this.start)
    this.el.removeEventListener(this.UNSTRETCH_EVENT, this.end)
  },
  start: function (evt) {
    if (this.stretched || this.stretchers.includes(evt.detail.hand) ||
        !this.startButtonOk(evt) || evt.defaultPrevented ||
        !this.networkedOk()) {
      return
    } // already stretched or already captured this hand or wrong button
    this.stretchers.push(evt.detail.hand)
    if (this.stretchers.length === 2) {
      this.stretched = true
      this.previousStretch = null
      this.previousPhysicsStretch = null
      this.el.addState(this.STRETCHED_STATE)
    }
    if (evt.preventDefault) { evt.preventDefault() } // gesture accepted
  },
  end: function (evt) {
    var stretcherIndex = this.stretchers.indexOf(evt.detail.hand)
    if (evt.defaultPrevented || !this.endButtonOk(evt)) { return }
    if (stretcherIndex !== -1) {
      this.stretchers.splice(stretcherIndex, 1)
      this.stretched = false
      this.el.removeState(this.STRETCHED_STATE)
      // override throttle to push last stretch to physics bodies
      this._updateBodies()
    }
    if (evt.preventDefault) { evt.preventDefault() }
  },
  _updateBodies: function () {
    if (!this.el.body || this.data.usePhysics === 'never') { return }
    const currentStretch = this.previousStretch // last visible geometry stretch
    let deltaStretch = 1
    if (this.previousPhysicsStretch !== null && currentStretch > 0) {
      deltaStretch = Math.pow(
          currentStretch / this.previousPhysicsStretch,
          (this.data.invert)
            ? -1
            : 1
      )
    }
    this.previousPhysicsStretch = currentStretch
    if (deltaStretch === 1) { return }
    for (let c of this.el.children) { this.stretchBody(c, deltaStretch) }
    this.stretchBody(this.el, deltaStretch)
  },
  stretchBody: function (el, deltaStretch) {
    if (!el.body) { return }
    let physicsShape
    let offset
    for (let i = 0; i < el.body.shapes.length; i++) {
      physicsShape = el.body.shapes[i]
      if (physicsShape.halfExtents) {
        physicsShape.halfExtents
            .scale(deltaStretch, physicsShape.halfExtents)
        physicsShape.updateConvexPolyhedronRepresentation()
      } else if (physicsShape.radius) {
        physicsShape.radius *= deltaStretch
        physicsShape.updateBoundingSphereRadius()
      } else if (!this.shapeWarned) {
        console.warn('Unable to stretch physics body: unsupported shape')
        this.shapeWarned = true
      }
      // also move offset to match scale change
      offset = el.body.shapeOffsets[i]
      offset.scale(deltaStretch, offset)
    }
    el.body.updateBoundingRadius()
  }
}))
<|endoftext|>


<commit_before>import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import store from './store/store'
import App from './App'

import './style/reset.scss'

render(
    <Provider store={store}>
        <App />
    </Provider>,
    document.getElementById('app')
)
<commit_msg>conf index<commit_after>import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import store from './store/store'
import App from './App'

import './style/reset.scss'
import './style/common.scss'

render(
    <Provider store={store}>
        <App />
    </Provider>,
    document.getElementById('app')
)
<|endoftext|>


<commit_before>
/**
 * Server used to run unit tests
 *
 * @class Tests
 * @constructor
 *
 * @param config {Object}
 * @param [config.server] {Object} config for {{#crossLink "Server"}}{{/crossLink}}
 * @param [config.remote] {Object} config for {{#crossLink "Remote"}}{{/crossLink}}
 * @param [config.node] {Object} config for {{#crossLink "NodeTests"}}{{/crossLink}}
 * @param [config.coverage] {Object} config for {{#crossLink "Coverage"}}{{/crossLink}}
 * @param [config.manualStop] {Boolean} If true, server is not stopped automatically and coverage repport is delayed.
 *                            You need to manually call the stop method to end the tests.
 *
 */
var Tests = function(config) {
	this.config = config;

	var actions = this.actions = {};
	actions.runServer = !!this.config.server;
	actions.runNodeTests = !!(this.config.node && (!this.config.coverage || !this.config.coverage.coverageOnly));
	actions.runNodeCoverage = !!(this.config.coverage && this.config.node);
	actions.prepareCoverage = !!this.config.coverage;
	actions.runRemote = !!this.config.remote;
	//actions.runRemoteCoverage = !!(this.config.remote && this.config.coverage && this.config.remote.urlCoverage);
	actions.coverageReport = !!(this.config.coverage && this.config.server);

	var needStop = !!this.config.server;
	actions.autoStop = needStop && !this.config.manualStop;
	actions.manualStop = needStop && !!this.config.manualStop;
};

Tests.prototype.run = function(cb) {
	var actions = [];

	if (this.actions.runServer) actions.push(this.startServer.bind(this));
	if (this.actions.runNodeTests) actions.push(this.runTests.bind(this, 'standard'));
	if (this.actions.prepareCoverage) actions.push(this.prepareCoverage.bind(this));
	if (this.actions.runNodeCoverage) actions.push(this.runTests.bind(this, 'coverage'));
	if (this.actions.runRemote) actions.push(this.runRemote.bind(this));
	if (this.actions.autoStop) actions.push(this.stop.bind(this));

	require('async').series(actions, function(err) {
		if (cb) {
			// Small delay so that all messages get time to be written to console before returning to caller
			setTimeout(function() {
				cb(err);
			}, 100);
		}

	}.bind(this));

	if (this.actions.manualStop) {
		return {
			stop: this.stop.bind(this)
		};
	}
};

Tests.prototype.stop = function(cb) {
	if (this.actions.coverageReport) {
		this.coverage.report();
	}
	if (this.server) {
		this.stopServer(cb);
	}
};

/**
 * Start the webserver
 *
 * @method startServer
 * @private
 */
Tests.prototype.startServer = function(cb) {
	if (!this.server) {
		var Server = require('./Server');

		this.server = new Server(this.config.server);
		this.server.start(function(err, address) {
			if (this.config.remote && this.config.remote.url) {
				var url = require('url');
				var u = url.parse(this.config.remote.url);
				if (u.port === '0') {
					delete u.host;
					u.port = address.port;
					this.config.remote.url = url.format(u);
				}
			}
			cb();
		}.bind(this));
	}
};

/**
 * Stop the webserver
 *
 * @method stopServer
 * @private
 */
Tests.prototype.stopServer = function(cb) {
	this.server.stop(function() {
		delete this.server;
		console.log('server stoped');
		if (cb) cb();
	}.bind(this));
};

Tests.prototype.runTests = function(type, cb) {
	var NodeTests = require('./NodeTests');
	var coverage = (type === 'coverage') ? this.coverage : null;
	new NodeTests(this.config.node).run(coverage, cb);
};

Tests.prototype.prepareCoverage = function(cb) {
	var Coverage = require('./Coverage');
	this.coverage = new Coverage(this.config.coverage);
	this.coverage.prepare();
	if (this.server) this.server.setCoverage(this.coverage);
	cb();
};

Tests.prototype.runRemote = function(cb) {
	var Remote = require('./Remote');
	new Remote(this.config.remote).run(!!this.coverage, cb);
};

module.exports = Tests;
<commit_msg>Allays stop the web server and publish coverage<commit_after>
/**
 * Server used to run unit tests
 *
 * @class Tests
 * @constructor
 *
 * @param config {Object}
 * @param [config.server] {Object} config for {{#crossLink "Server"}}{{/crossLink}}
 * @param [config.remote] {Object} config for {{#crossLink "Remote"}}{{/crossLink}}
 * @param [config.node] {Object} config for {{#crossLink "NodeTests"}}{{/crossLink}}
 * @param [config.coverage] {Object} config for {{#crossLink "Coverage"}}{{/crossLink}}
 * @param [config.manualStop] {Boolean} If true, server is not stopped automatically and coverage repport is delayed.
 *                            You need to manually call the stop method to end the tests.
 *
 */
var Tests = function(config) {
	this.config = config;

	var actions = this.actions = {};
	actions.runServer = !!this.config.server;
	actions.runNodeTests = !!(this.config.node && (!this.config.coverage || !this.config.coverage.coverageOnly));
	actions.runNodeCoverage = !!(this.config.coverage && this.config.node);
	actions.prepareCoverage = !!this.config.coverage;
	actions.runRemote = !!this.config.remote;
	//actions.runRemoteCoverage = !!(this.config.remote && this.config.coverage && this.config.remote.urlCoverage);
	actions.coverageReport = !!(this.config.coverage && this.config.server);

	var needStop = !!this.config.server;
	actions.autoStop = needStop && !this.config.manualStop;
	actions.manualStop = needStop && !!this.config.manualStop;
};

Tests.prototype.run = function(cb) {
	var actions = [];

	if (this.actions.runServer) actions.push(this.startServer.bind(this));
	if (this.actions.runNodeTests) actions.push(this.runTests.bind(this, 'standard'));
	if (this.actions.prepareCoverage) actions.push(this.prepareCoverage.bind(this));
	if (this.actions.runNodeCoverage) actions.push(this.runTests.bind(this, 'coverage'));
	if (this.actions.runRemote) actions.push(this.runRemote.bind(this));

	require('async').series(actions, function(err) {
		if (this.actions.autoStop) {
			this.stop(function() {
				if (cb) {
					// Small delay so that all messages get time to be written to console before returning to caller
					setTimeout(function() {
						cb(err);
					}, 100);
				}
			}.bind(this));
		}
	}.bind(this));

	if (this.actions.manualStop) {
		return {
			stop: this.stop.bind(this)
		};
	}
};

Tests.prototype.stop = function(cb) {
	if (this.actions.coverageReport) {
		this.coverage.report();
	}
	if (this.server) {
		this.stopServer(cb);
	}
};

/**
 * Start the webserver
 *
 * @method startServer
 * @private
 */
Tests.prototype.startServer = function(cb) {
	if (!this.server) {
		var Server = require('./Server');

		this.server = new Server(this.config.server);
		this.server.start(function(err, address) {
			if (this.config.remote && this.config.remote.url) {
				var url = require('url');
				var u = url.parse(this.config.remote.url);
				if (u.port === '0') {
					delete u.host;
					u.port = address.port;
					this.config.remote.url = url.format(u);
				}
			}
			cb();
		}.bind(this));
	}
};

/**
 * Stop the webserver
 *
 * @method stopServer
 * @private
 */
Tests.prototype.stopServer = function(cb) {
	this.server.stop(function() {
		delete this.server;
		console.log('server stoped');
		if (cb) cb();
	}.bind(this));
};

Tests.prototype.runTests = function(type, cb) {
	var NodeTests = require('./NodeTests');
	var coverage = (type === 'coverage') ? this.coverage : null;
	new NodeTests(this.config.node).run(coverage, cb);
};

Tests.prototype.prepareCoverage = function(cb) {
	var Coverage = require('./Coverage');
	this.coverage = new Coverage(this.config.coverage);
	this.coverage.prepare();
	if (this.server) this.server.setCoverage(this.coverage);
	cb();
};

Tests.prototype.runRemote = function(cb) {
	var Remote = require('./Remote');
	new Remote(this.config.remote).run(!!this.coverage, cb);
};

module.exports = Tests;
<|endoftext|>


<commit_before>Router.configure({
  layoutTemplate: 'MasterLayout',
  loadingTemplate: 'Loading',
  notFoundTemplate: 'NotFound',
  yieldTemplates: {
    'header': { to: 'header' },
    'footer': { to: 'footer' }
  }
});

// enable hooks
if (Meteor.isClient) {
  Router.onBeforeAction('dataNotFound');
  Router.onBeforeAction('loading');
}

// global configuration
Router.waitOn(function() {
  return [Meteor.subscribe('allplaylists'),
          Meteor.subscribe('allusers')];
});

// route specific configuration

Router.map(function() {
  this.route('home', {path: '/'});

  this.route('playlists', {
    data: {
      playlists: function() {
        return Playlists.find({privacy:{$ne:'private'}},{sort: {createdAt: -1}, limit: 5});
      }
    }
  });

  this.route('allplaylists', {
    data: {
      playlists: function() {
        return Playlists.find({privacy:{$ne:'private'}},{sort: {createdAt: -1}});
      }
    }
  });

  this.route('playlist', {
    path: '/playlist/:_id',
    onBeforeAction: function() {
      console.log("subscribe to playlist", this.params._id);
      this.subscribe('playlist', this.params._id);
      var playlist = this.data();
      if (!playlist) {
        console.warn("no playlist");
        return;
      }
      var songs = playlist.songs || [];
      songs = _.pluck(songs, 'songId');
      //add another subscription to waiting list
      this.subscribe('songs', songs);
    },
    loadingTemplate: 'playlist',
    notFoundTemplate: 'playlistNotFound',
    data: function() {
      //return all current client side playlists (just one ;)
      return Playlists.findOne(this.params._id);
    },
  });

  this.route('loved', {
    onBeforeAction: function() {
      var user = Meteor.user();
      if (!user)
        return;
      var songs = user.profile.lovedSongs;
      this.subscribe('songs', songs);
    },
    data: {
      lovedSongs: function() {
        var user = Meteor.user();
        //find song info in the cache for each song
        return Songs.find({_id: {$in: user.profile.lovedSongs} });
      }
    }
  });

  this.route('userProfile', {
    path:'/profile/:_id',
    waitOn: function() {
      return Meteor.subscribe('playlistsByUser', this.params._id);
    },
    data: function () {
      var user = Meteor.users.findOne(this.params._id);

      var playlists = Playlists.find( {owner: this.params._id});
      user.userPlaylists = playlists;
      return user;
    },
  });
});
<commit_msg>fix broken stand-alone profile pages<commit_after>Router.configure({
  layoutTemplate: 'MasterLayout',
  loadingTemplate: 'Loading',
  notFoundTemplate: 'NotFound',
  yieldTemplates: {
    'header': { to: 'header' },
    'footer': { to: 'footer' }
  }
});

// enable hooks
if (Meteor.isClient) {
  Router.onBeforeAction('dataNotFound');
  Router.onBeforeAction('loading');
}

// global configuration
Router.waitOn(function() {
  return [Meteor.subscribe('allplaylists'),
          Meteor.subscribe('allusers')];
});

// route specific configuration

Router.map(function() {
  this.route('home', {path: '/'});

  this.route('playlists', {
    data: {
      playlists: function() {
        return Playlists.find({privacy:{$ne:'private'}},{sort: {createdAt: -1}, limit: 5});
      }
    }
  });

  this.route('allplaylists', {
    data: {
      playlists: function() {
        return Playlists.find({privacy:{$ne:'private'}},{sort: {createdAt: -1}});
      }
    }
  });

  this.route('playlist', {
    path: '/playlist/:_id',
    onBeforeAction: function() {
      console.log("subscribe to playlist", this.params._id);
      this.subscribe('playlist', this.params._id);
      var playlist = this.data();
      if (!playlist) {
        console.warn("no playlist");
        return;
      }
      var songs = playlist.songs || [];
      songs = _.pluck(songs, 'songId');
      //add another subscription to waiting list
      this.subscribe('songs', songs);
    },
    loadingTemplate: 'playlist',
    notFoundTemplate: 'playlistNotFound',
    data: function() {
      //return all current client side playlists (just one ;)
      return Playlists.findOne(this.params._id);
    },
  });

  this.route('loved', {
    onBeforeAction: function() {
      var user = Meteor.user();
      if (!user)
        return;
      var songs = user.profile.lovedSongs;
      this.subscribe('songs', songs);
    },
    data: {
      lovedSongs: function() {
        var user = Meteor.user();
        //find song info in the cache for each song
        return Songs.find({_id: {$in: user.profile.lovedSongs} });
      }
    }
  });

  this.route('userProfile', {
    path:'/profile/:_id',
    waitOn: function() {
      return Meteor.subscribe('playlistsByUser', this.params._id);
    },
    data: function () {
      var user = Meteor.users.findOne(this.params._id);
      if (!user)
        return;

      var playlists = Playlists.find( {owner: this.params._id});
      user.userPlaylists = playlists;
      return user;
    },
  });
});
<|endoftext|>


<commit_before>
var https = require('https');
var token;

exports.init = function(_socket, _rooms, _config) {
    console.log("Search init");
    token=_config.token;
};

exports.shutdown = function(socket, cb) {
    console.log("Shutdown search");
    cb();
};

exports.onmessage = function(socket, mdata) {
    // Handle 'standard' @bots command and respond with usage
    if (mdata.m == "@bots") {
        socket.emit('chatm', JSON.stringify({"t": token, "room": mdata.room, "m": " @s [your-search] - Search duckduckgo answers API", "dur":"1m"}));
        return;
    }

    if (mdata.m.indexOf("@s ")==0) {
        var s = mdata.m.substring(3).replace(/\W+/g, ' ').replace(/[ ]/g, '+');
        console.log("@s:", s);

        var results = "";
        var m="";

        https.get('https://api.duckduckgo.com/?t=chatassistsearch&format=json&q='+s, function(res) {
            if (res.statusCode !== 200) {
                socket.emit('chatm', JSON.stringify({"t": token, "room": mdata.room, "m": "Search server error.", "dur":"1m"}));
            } else {
                res.setEncoding('utf8');

                res.on('data', function(chunk) {
                    results += chunk;
                });

                res.on('end', function() {
                    try {
                        var data = JSON.parse(results);

                        if (data.Image!='') {
                            m+=data.Image+"#iconsmall\n";
                        }

                        if (data.AnswerType!='') {
                            m+=data.Answer;
                        } else if (data.DefinitionSource!='') {
                            m+=data.Definition+" [ "+data.DefinitionURL+" ]";
                        } else if (data.AbstractSource!='') {
                            m+=data.Abstract+" [ "+data.AbstractURL+" ]";
                        }

                        if (m=="")
                            m = "No quick results found. Try https://www.duckduckgo.com/?q="+s;
                        else
                            m += " (via DuckDuckGo: https://www.duckduckgo.com/?q="+s+")";

                        socket.emit('chatm', JSON.stringify({"t": token, "room": mdata.room, "m": m, "dur":"1h"}));
                    } catch (e) {
                        console.log(e.message);
                        socket.emit('chatm', JSON.stringify({"t": token, "room": mdata.room, "m": "Search server error.", "dur":"1m"}));
                    }
                });
            }
        });
    }
};

exports.onroomjoin = function(socket, name, room) {
    console.log("Room ID", room, name);
};
<commit_msg>search wikipedia if no ddg result<commit_after>
var https = require('https');
var token;

exports.init = function(_socket, _rooms, _config) {
    console.log("Search init");
    token=_config.token;
};

exports.shutdown = function(socket, cb) {
    console.log("Shutdown search");
    cb();
};

exports.onmessage = function(socket, mdata) {
    // Handle 'standard' @bots command and respond with usage
    if (mdata.m == "@bots") {
        socket.emit('chatm', JSON.stringify({"t": token, "room": mdata.room, "m": " @s [your-search] - Search duckduckgo answers API", "dur":"1m"}));
        return;
    }

    if (mdata.m.indexOf("@s ")==0) {
        var s = mdata.m.substring(3).replace(/\W+/g, ' ').replace(/[ ]/g, '+');
        console.log("@s:", s);

        var results = "";
        var m="";

        _gethttps('https://api.duckduckgo.com/?t=chatassistsearch&format=json&q='+s, function(results, status) {
            if (status !== 200) {
                console.log("Duckduckgo search error");
                tryWikipedia(socket, mdata, s);
            } else {
                try {
                    var data = JSON.parse(results);

                    if (data.Image!='') {
                        m+=data.Image+"#iconsmall\n";
                    }

                    if (data.AnswerType!='' && data.Answer!='') {
                        m+=data.Answer;
                    } else if (data.DefinitionSource!='') {
                        m+=data.Definition+" [ "+data.DefinitionURL+" ]";
                    } else if (data.AbstractSource!='' && data.Abstract!='') {
                        m+=data.Abstract+" [ "+data.AbstractURL+" ]";
                    } else {
                        tryWikipedia(socket, mdata, s);
                    }

                    if (m!="") {
                        m += " (via DuckDuckGo: https://www.duckduckgo.com/?q="+s+")";
                    }

                    socket.emit('chatm', JSON.stringify({"t": token, "room": mdata.room, "m": m, "dur":"1h"}));
                } catch (e) {
                    console.log("Duckduckgo search error",e.message);
                    tryWikipedia(socket, mdata, s);
                }
            }
        });
    }
};

exports.onroomjoin = function(socket, name, room) {
    console.log("Room ID", room, name);
};

function tryWikipedia(socket, mdata, s) {
    var requrl="https://en.wikipedia.org/w/api.php?action=query&format=json&list=search&utf8=1&srsearch="+s+"&srlimit=1&srprop=&srenablerewrites=1";
    var m="", results="";
    _gethttps(requrl, function(results, status) {
        if (status !== 200) {
            socket.emit('chatm', JSON.stringify({"t": token, "room": mdata.room, "m": "Wikipedia search server error.", "dur":"1m"}));
        } else {
            try {
                var data = JSON.parse(results);
                if (data.query.search.length==0) {
                    m = "No quick results found. Try https://www.duckduckgo.com/?q="+s;
                    socket.emit('chatm', JSON.stringify({"t": token, "room": mdata.room, "m": m, "dur":"1m"}));
                } else {
                    getWikipediaArticle(socket, mdata, data.query.search[0].title, s);
                }
            } catch (e) {
                console.log(e.message);
                socket.emit('chatm', JSON.stringify({"t": token, "room": mdata.room, "m": "Wikipedia search json error.", "dur":"1m"}));
            }
        }
    });
}

function getWikipediaArticle(socket, mdata, title, s) {
    var requrl = "https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exlimit=max&explaintext&exintro&titles="+title+"&redirects=";
    var m="";
    _gethttps(requrl, function(results, status){
        if (status!=200) {
            socket.emit('chatm', JSON.stringify({"t": token, "room": mdata.room, "m": "Wikipedia search server error.", "dur":"1m"}));
        } else {
            try {
                var data = JSON.parse(results);
                for (var p in data.query.pages) {
                    m=data.query.pages[p].extract;
                    break;
                }

                if (m!="") {
                    m += " (via Wikipedia: https://en.wikipedia.org/wiki/"+escape(title.replace(/ /g,'_'))+")";
                    socket.emit('chatm', JSON.stringify({"t": token, "room": mdata.room, "m": m, "dur":"1h"}));
                } else {
                    m = "No quick results found. Try https://www.duckduckgo.com/?q="+s;
                    socket.emit('chatm', JSON.stringify({"t": token, "room": mdata.room, "m": m, "dur":"1m"}));
                }

            } catch (e) {
                console.log(e.message);
                socket.emit('chatm', JSON.stringify({"t": token, "room": mdata.room, "m": "Wikipedia search json error.", "dur":"1m"}));
            }
        }
    });
}

function _gethttps(url, finish_callback) {
    var results="";
    https.get(url, function(res) {
        if (res.statusCode !== 200) {
            finish_callback(null, res.statusCode);
        } else {
            res.setEncoding('utf8');

            res.on('data', function(chunk) {
                results += chunk;
            });

            res.on('end', function() {
                finish_callback(results, res.statusCode);
            });
        }
    }).on('error', function(e) {
        console.log(e.message);
        finish_callback(null, 0);
    });
}<|endoftext|>


<commit_before>var GearmanConnection = require("./gearman-connection"),
    EventEmitter = require('events').EventEmitter,
    utillib = require("util");

function Gearman(){
    EventEmitter.call(this);

    this.server_names = [];
    this.servers = {};

    this.function_names = [];
    this.functions = {};
}
utillib.inherits(Gearman, EventEmitter);

Gearman.prototype.addServer = function(server_name, server_port){
    server_name = (server_name || "127.0.0.1").toLowerCase().trim();
    server_port = server_port || 4730;

    if(this.servers[server_name]){
        return;
    }

    this.server_names.push(server_name);
    this.servers[server_name] = {
        name: server_name,
        port: server_port,
        connection: new GearmanConnection(server_name, server_port),
        functions: []
    };

    this.servers[server_name].connection.on("error", function(err){
        console.log("Error with "+server_name);
        //console.log(err.message);
        console.log(err.stack);
    });

    this.servers[server_name].connection.on("job", this.runJob.bind(this, server_name));

    this.servers[server_name].connection.on("created", (function(handle, options){
        if(options && options.job){
            options.job.emit("created", handle);
        }
    }).bind(this));

    this.servers[server_name].connection.on("complete", (function(handle, response, options){
        if(options && options.job){
            options.job.emit("complete", response);
        }
    }).bind(this));

    this.servers[server_name].connection.on("exception", (function(handle, error, options){
        if(options && options.job){
            options.job.emit("exception", error);
        }
    }).bind(this));

    this.servers[server_name].connection.on("warning", (function(handle, error, options){
        if(options && options.job){
            options.job.emit("warning", error);
        }
    }).bind(this));

    this.servers[server_name].connection.on("data", (function(handle, error, options){
        if(options && options.job){
            options.job.emit("data", error);
        }
    }).bind(this));

    this.servers[server_name].connection.on("fail", (function(handle, options){
        if(options && options.job){
            options.job.emit("fail");
        }
    }).bind(this));

    this.update(server_name);
}

Gearman.prototype.runJob = function(server_name, handle, func_name, payload, uid){
    uid = uid || null;
    if(this.functions[func_name]){
        this.functions[func_name](payload, (function(err, response, type){
            if(err){
                this.servers[server_name].connection.jobError(handle, err.message || err);
                return;
            }
            switch(type){
                case "warning":
                    this.servers[server_name].connection.jobWarning(handle, response);
                    break;
                case "data":
                    this.servers[server_name].connection.jobData(handle, response);
                    break;
                case "normal":
                default:
                    this.servers[server_name].connection.jobComplete(handle, response);
            }

        }).bind(this));
    }else{
        this.servers[server_name].connection.jobError(handle, "Function "+func_name+" not found");
    }
}

Gearman.prototype.removeServer = function(server_name){
    var connection, pos;

    server_name = (server_name || "127.0.0.1").toLowerCase().trim();

    if(!this.servers[server_name]){
        return false;
    }

    connection = this.servers[server_name].connection;
    connection.closeConnection();

    if((pos = this.server_names.indexOf(server_name))>=0){
        this.server_names.splice(pos, 1);
    }

    delete this.servers[server_name];

    return true;
}

Gearman.prototype.update = function(server_name){
    if(!server_name){
        return;
    }

    this.function_names.forEach((function(func_name){
        this.register(func_name, server_name);
    }).bind(this));
}

Gearman.prototype.register = function(func_name, server_name){
    if(this.servers[server_name]){
        if(this.servers[server_name].functions.indexOf(func_name)<0){
            this.servers[server_name].connection.addFunction(func_name);
            this.servers[server_name].functions.push(func_name);
        }
    }else{
        this.server_names.forEach((function(server_name){
            if(server_name){
                this.register(func_name, server_name);
            }
        }).bind(this))
    }
}

Gearman.prototype.unregister = function(func_name, server_name){
    var pos;
    if(this.servers[server_name]){
        if((pos = this.servers[server_name].functions.indexOf(func_name))>=0){
            this.servers[server_name].connection.removeFunction(func_name);
            this.servers[server_name].functions.splice(pos, 1);
        }
    }else{
        this.server_names.forEach((function(server_name){
            if(server_name){
                this.unregister(func_name, server_name);
            }
        }).bind(this))
    }
}

Gearman.prototype.getExceptions = function(server_name, callback){
    var pos;
    if(this.servers[server_name]){

            this.servers[server_name].connection.getExceptions((function(err, success){
                if(callback){
                    return callback(err, success);
                }
                if(err){
                    console.log("Server "+server_name+" responded with error: "+(err.message || err));
                }else{
                    console.log("Exceptions are followed from "+server_name);
                }
            }).bind(this));

    }else{
        this.server_names.forEach((function(server_name){
            if(server_name){
                this.getExceptions(server_name, callback);
            }
        }).bind(this))
    }
}

Gearman.prototype.addFunction = function(name, func){
    if(!name){
        return false;
    }

    if(!(name in this.functions)){
        this.functions[name] = func;
        this.function_names.push(name);
        this.register(name);
    }else{
        this.functions[name] = func;
        this.function_names.push(name);
    }

}

Gearman.prototype.removeFunction = function(name){
    var pos;

    if(!name){
        return false;
    }

    if((pos = this.function_names.indexOf(name))>=0){
        delete this.functions[name];
        this.function_names.splice(pos, 1);
        this.unregister(name);
    }
}

Gearman.prototype.end = function(){
    for(var i=this.server_names.length-1; i>=0; i--){
        this.removeServer(this.server_names[i]);
    }
}

Gearman.prototype.submitJob = function(func_name, payload, options){
    if(!func_name){
        return false;
    }

    var server = this.servers[this.server_names[this.server_names.length-1]];

    return new Gearman.GearmanJob(func_name, payload, options, server);
}

Gearman.GearmanJob = function(func_name, payload, options, server){
    EventEmitter.call(this);

    options = options || {};
    options.job = this;

    server.connection.submitJob(func_name, payload, options);
}
utillib.inherits(Gearman.GearmanJob, EventEmitter);

module.exports = Gearman;

<commit_msg>update<commit_after>var GearmanConnection = require("./gearman-connection"),
    EventEmitter = require('events').EventEmitter,
    utillib = require("util");

function Gearman(){
    EventEmitter.call(this);

    this.server_names = [];
    this.servers = {};

    this.function_names = [];
    this.functions = {};
}
utillib.inherits(Gearman, EventEmitter);

Gearman.prototype.addServer = function(server_name, server_port){
    server_name = (server_name || "127.0.0.1").toLowerCase().trim();
    server_port = server_port || 4730;

    if(this.servers[server_name]){
        return;
    }

    this.server_names.push(server_name);
    this.servers[server_name] = {
        name: server_name,
        port: server_port,
        connection: new GearmanConnection(server_name, server_port),
        functions: []
    };

    this.servers[server_name].connection.on("error", function(err){
        console.log("Error with "+server_name);
        //console.log(err.message);
        console.log(err.stack);
    });

    this.servers[server_name].connection.on("job", this.runJob.bind(this, server_name));

    this.servers[server_name].connection.on("created", (function(handle, options){
        if(options && options.job){
            options.job.emit("created", handle);
        }
    }).bind(this));

    this.servers[server_name].connection.on("complete", (function(handle, response, options){
        if(options && options.job){
            options.job.emit("complete", response);
        }
    }).bind(this));

    this.servers[server_name].connection.on("exception", (function(handle, error, options){
        if(options && options.job){
            options.job.emit("exception", error);
        }
    }).bind(this));

    this.servers[server_name].connection.on("warning", (function(handle, error, options){
        if(options && options.job){
            options.job.emit("warning", error);
        }
    }).bind(this));

    this.servers[server_name].connection.on("data", (function(handle, error, options){
        if(options && options.job){
            options.job.emit("data", error);
        }
    }).bind(this));

    this.servers[server_name].connection.on("fail", (function(handle, options){
        if(options && options.job){
            options.job.emit("fail");
        }
    }).bind(this));

    this.update(server_name);
}

Gearman.prototype.runJob = function(server_name, handle, func_name, payload, uid){
    uid = uid || null;
    if(this.functions[func_name]){
        this.functions[func_name](payload, (function(err, response, type){
            if(err){
                this.servers[server_name].connection.jobError(handle, err.message || err);
                return;
            }
            switch(type){
                case "warning":
                    this.servers[server_name].connection.jobWarning(handle, response);
                    break;
                case "data":
                    this.servers[server_name].connection.jobData(handle, response);
                    break;
                case "normal":
                default:
                    this.servers[server_name].connection.jobComplete(handle, response);
            }

        }).bind(this));
    }else{
        this.servers[server_name].connection.jobError(handle, "Function "+func_name+" not found");
    }
}

Gearman.prototype.removeServer = function(server_name){
    var connection, pos;

    server_name = (server_name || "127.0.0.1").toLowerCase().trim();

    if(!this.servers[server_name]){
        return false;
    }

    connection = this.servers[server_name].connection;
    connection.closeConnection();

    if((pos = this.server_names.indexOf(server_name))>=0){
        this.server_names.splice(pos, 1);
    }

    delete this.servers[server_name];

    return true;
}

Gearman.prototype.update = function(server_name){
    if(!server_name){
        return;
    }

    this.function_names.forEach((function(func_name){
        this.register(func_name, server_name);
    }).bind(this));
}

Gearman.prototype.register = function(func_name, server_name){
    if(this.servers[server_name]){
        if(this.servers[server_name].functions.indexOf(func_name)<0){
            this.servers[server_name].connection.addFunction(func_name);
            this.servers[server_name].functions.push(func_name);
        }
    }else{
        this.server_names.forEach((function(server_name){
            if(server_name){
                this.register(func_name, server_name);
            }
        }).bind(this))
    }
}

Gearman.prototype.unregister = function(func_name, server_name){
    var pos;
    if(this.servers[server_name]){
        if((pos = this.servers[server_name].functions.indexOf(func_name))>=0){
            this.servers[server_name].connection.removeFunction(func_name);
            this.servers[server_name].functions.splice(pos, 1);
        }
    }else{
        this.server_names.forEach((function(server_name){
            if(server_name){
                this.unregister(func_name, server_name);
            }
        }).bind(this))
    }
}

Gearman.prototype.getExceptions = function(server_name, callback){
    var pos;

    if(!callback && typeof server_name =="function"){
        callback = server_name;
        server_name = null;
    }

    if(server_name){
        if(this.servers[server_name]){

            this.servers[server_name].connection.getExceptions((function(err, success){
                if(callback){
                    return callback(err, success);
                }
                if(err){
                    console.log("Server "+server_name+" responded with error: "+(err.message || err));
                }else{
                    console.log("Exceptions are followed from "+server_name);
                }
            }).bind(this));
        }
    }else{
        this.server_names.forEach((function(server_name){
            if(server_name){
                this.getExceptions(server_name, callback);
            }
        }).bind(this))
    }
}

Gearman.prototype.addFunction = function(name, func){
    if(!name){
        return false;
    }

    if(!(name in this.functions)){
        this.functions[name] = func;
        this.function_names.push(name);
        this.register(name);
    }else{
        this.functions[name] = func;
        this.function_names.push(name);
    }

}

Gearman.prototype.removeFunction = function(name){
    var pos;

    if(!name){
        return false;
    }

    if((pos = this.function_names.indexOf(name))>=0){
        delete this.functions[name];
        this.function_names.splice(pos, 1);
        this.unregister(name);
    }
}

Gearman.prototype.end = function(){
    for(var i=this.server_names.length-1; i>=0; i--){
        this.removeServer(this.server_names[i]);
    }
}

Gearman.prototype.submitJob = function(func_name, payload, options){
    if(!func_name){
        return false;
    }

    var server = this.servers[this.server_names[this.server_names.length-1]];

    return new Gearman.GearmanJob(func_name, payload, options, server);
}

Gearman.GearmanJob = function(func_name, payload, options, server){
    EventEmitter.call(this);

    options = options || {};
    options.job = this;

    server.connection.submitJob(func_name, payload, options);
}
utillib.inherits(Gearman.GearmanJob, EventEmitter);

module.exports = Gearman;

<|endoftext|>


<commit_before>var localStream;
var localPeerConnection;
var remotePeerConnection;
var users = [];
var candidates = {};
var descriptions = {};
var me = null;
var localVideo = document.getElementById('localVideo');
var remoteVideo = document.getElementById('remoteVideo');

localVideo.addEventListener('loadedmetadata', function() {
  trace('Local video currentSrc: ' + this.currentSrc +
    ', videoWidth: ' + this.videoWidth +
    'px,  videoHeight: ' + this.videoHeight + 'px');
});

remoteVideo.addEventListener('loadedmetadata', function() {
  trace('Remote video currentSrc: ' + this.currentSrc +
    ', videoWidth: ' + this.videoWidth +
    'px,  videoHeight: ' + this.videoHeight + 'px');
});

var startButton = document.getElementById('startButton');
var callButton = document.getElementById('callButton');
var hangupButton = document.getElementById('hangupButton');
var stopButton = document.getElementById('stopButton');
startButton.disabled = true;
stopButton.disabled = true;
callButton.disabled = true;
hangupButton.disabled = true;
startButton.onclick = start;
callButton.onclick = call;
hangupButton.onclick = hangup;
stopButton.onclick = stop;

function gotStream(stream) {
  trace('Received local stream');
  localVideo.src = URL.createObjectURL(stream);
  localStream = stream;
  callButton.disabled = false;
}

function start() {
  trace('Requesting local stream');
  startButton.disabled = true;
  stopButton.disabled = false;
  navigator.getUserMedia({
      video: true,
      audio: true
    }, gotStream,
    function(error) {
      trace('navigator.getUserMedia error: ', error);
    });
}

function stop() {

  startButton.disabled = false;
  stopButton.disabled = true;

  localStream.getVideoTracks()[0].stop()
  localStream.getAudioTracks()[0].stop()

}

function call() {
  callButton.disabled = true;
  hangupButton.disabled = false;
  trace('Starting call');

  if (localStream.getVideoTracks().length > 0) {
    trace('Using video device: ' + localStream.getVideoTracks()[0].label);
  }
  if (localStream.getAudioTracks().length > 0) {
    trace('Using audio device: ' + localStream.getAudioTracks()[0].label);
  }

  var servers = {
    "iceServers": [
      {
        url: 'stun:stun.iptel.org'
      }, {
        url: 'stun:stun.rixtelecom.se'
      }, {
        url: 'stun:stun.schlund.de'
      }, {
        url: 'stun:stun.l.google.com:19302'
      }, {
        url: 'stun:stun1.l.google.com:19302'
      }, {
        url: 'stun:stun2.l.google.com:19302'
      }, {
        url: 'stun:stun3.l.google.com:19302'
      }, {
        url: 'stun:stun4.l.google.com:19302'
      }, {
        url: 'stun:stunserver.org'
      }, {
        url: 'stun:stun.voxgratia.org'
      }, {
        url: 'turn:numb.viagenie.ca',
        credential: 'muazkh',
        username: 'webrtc@live.com'
      }
    ]
  };

  localPeerConnection =
    new RTCPeerConnection(servers); // eslint-disable-line new-cap
  trace('Created local peer connection object localPeerConnection');
  localPeerConnection.onicecandidate = gotLocalIceCandidate;

  remotePeerConnection =
    new RTCPeerConnection(servers); // eslint-disable-line new-cap
  trace('Created remote peer connection object remotePeerConnection');
  remotePeerConnection.onicecandidate = gotRemoteIceCandidate;
  remotePeerConnection.onaddstream = gotRemoteStream;

  localPeerConnection.addStream(localStream);
  trace('Added localStream to localPeerConnection');
  localPeerConnection.createOffer(gotLocalDescription);
}

function gotLocalDescription(description) {
  localPeerConnection.setLocalDescription(description);
  trace('Offer from localPeerConnection: \n' + description.sdp);
  if (wave != null) {
    descriptions[me] = description
    wave.getState().submitDelta({
      'descriptions': descriptions
    });
  }
}

function gotRemoteDescription(description) {
  remotePeerConnection.setLocalDescription(description);
  trace('Answer from remotePeerConnection: \n' + description.sdp);
  localPeerConnection.setRemoteDescription(description);
}

function hangup() {
  trace('Ending call');
  hangupButton.disabled = true;
  callButton.disabled = false;
  remotePeerConnection.close();
  localPeerConnection.close();
  //  remotePeerConnection.close();
  localPeerConnection = null;
  remotePeerConnection = null;
  remoteVideo.src = null;
}

function gotRemoteStream(event) {
  remoteVideo.src = URL.createObjectURL(event.stream);
  trace('Received remote stream');
}

function gotLocalIceCandidate(event) {
  if (event.candidate) {
    if (wave != null) {
      candidates[me] = event.candidate
      wave.getState().submitDelta({
        'candidates': candidates
      });
    }
    //remotePeerConnection.addIceCandidate(new RTCIceCandidate(event.candidate));
    trace('Local ICE candidate: \n' + event.candidate.candidate);
  }
}

function gotRemoteIceCandidate(event) {
  if (event.candidate) {
    localPeerConnection.addIceCandidate(new RTCIceCandidate(event.candidate));
    trace('Remote ICE candidate: \n ' + event.candidate.candidate);
  }
}

// Renders the gadget
function stateChangeHandler() {
  // Get state
  if (!wave.getState() || !wave.getViewer()) {
    return;
  }
  startButton.disabled = false;
  me = wave.getViewer().getId();
  if (me && users.indexOf(me) < 0) {
    users.push(me);
    wave.getState().submitDelta({
      'users': users
    });
  }
  var state = wave.getState();
  users = state.get('users', users);
  candidates = state.get('candidates', candidates)
  descriptions = state.get('descriptions', candidates)

  //only if changed
  if (candidates != candidates) {
    for (var property in candidates) {
      if (candidates.hasOwnProperty(property) && property != me) {
        remotePeerConnection.addIceCandidate(new RTCIceCandidate(candidates[property]));
        break; // No conference
      }
    }
  }
  if (descriptions != descriptions) {
    for (var property in descriptions) {
      if (descriptions.hasOwnProperty(property) && property != me) {
        remotePeerConnection.setRemoteDescription(descriptions[property]);
        remotePeerConnection.createAnswer(gotRemoteDescription);
        break; // No conference
      }
    }
  }
  console.log(" state users: ", users)
  console.log(" state candidates: ", candidates)
  console.log(" state descriptions: ", descriptions)
}

function init() {
  if (wave && wave.isInWaveContainer()) {
    // Loads the gadget's initial state and the subsequent changes to it
    wave.setStateCallback(stateChangeHandler);
    // Loads participants and any changes to them
    wave.setParticipantCallback(stateChangeHandler);
    console.log("wave state loaded")
  }

  // resetStatus();
  // openChannel('AHRlWrqvgCpvbd9B-Gl5vZ2F1BlpwFv0xBUwRgLF/* ...*/');
  // doGetUserMedia();

}
// Initializes gadget after receiving a notification that the page is loaded and the DOM is ready.
gadgets.util.registerOnLoadHandler(init);

/*
card = document.getElementById("card");
localVideo = document.getElementById("localVideo");
miniVideo = document.getElementById("miniVideo");
remoteVideo = document.getElementById("remoteVideo");
var pc = new webkitRTCPeerConnection(servers, {
  optional: [{
    RtpDataChannels: true
  }]
});

pc.ondatachannel = function(event) {
  receiveChannel = event.channel;
  receiveChannel.onmessage = function(event) {
    document.querySelector("div#receive").innerHTML = event.data;
  };
};

sendChannel = pc.createDataChannel("sendDataChannel", {
  reliable: false
});

document.querySelector("button#send").onclick = function() {
  var data = document.querySelector("textarea#send").value;
  sendChannel.send(data);
};

function onUserMediaSuccess(stream) {
  console.log("User has granted access to local media.");
  // Call the polyfill wrapper to attach the media stream to this element.
  attachMediaStream(localVideo, stream);
  localVideo.style.opacity = 1;
  localStream = stream;
  // Caller creates PeerConnection.
  if (initiator) maybeStart();
}

function maybeStart() {
  if (!started && localStream && channelReady) {
    // ...
    createPeerConnection();
    // ...
    pc.addStream(localStream);
    started = true;
    // Caller initiates offer to peer.
    if (initiator)
      doCall();
  }
}

function createPeerConnection() {
  var pc_config = {
    "iceServers": [{
      "url": "stun:stun.l.google.com:19302"
    }]
  };
  try {
    // Create an RTCPeerConnection via the polyfill (adapter.js).
    pc = new RTCPeerConnection(pc_config);
    pc.onicecandidate = onIceCandidate;
    console.log("Created RTCPeerConnnection with config:\n" + "  \"" +
      JSON.stringify(pc_config) + "\".");
  } catch (e) {
    console.log("Failed to create PeerConnection, exception: " + e.message);
    alert("Cannot create RTCPeerConnection object; WebRTC is not supported by this browser.");
    return;
  }

  pc.onconnecting = onSessionConnecting;
  pc.onopen = onSessionOpened;
  pc.onaddstream = onRemoteStreamAdded;
  pc.onremovestream = onRemoteStreamRemoved;
}

function onRemoteStreamAdded(event) {
  // ...
  miniVideo.src = localVideo.src;
  attachMediaStream(remoteVideo, event.stream);
  remoteStream = event.stream;
  waitForRemoteVideo();
}

function doCall() {
  console.log("Sending offer to peer.");
  pc.createOffer(setLocalAndSendMessage, null, mediaConstraints);
}

function setLocalAndSendMessage(sessionDescription) {
  // Set Opus as the preferred codec in SDP if Opus is present.
  sessionDescription.sdp = preferOpus(sessionDescription.sdp);
  pc.setLocalDescription(sessionDescription);
  sendMessage(sessionDescription);
}

function onIceCandidate(event) {
  if (event.candidate) {
    sendMessage({
      type: 'candidate',
      label: event.candidate.sdpMLineIndex,
      id: event.candidate.sdpMid,
      candidate: event.candidate.candidate
    });
  } else {
    console.log("End of candidates.");
  }
}

function sendMessage(message) {
  var msgString = JSON.stringify(message);
  console.log('C->S: ' + msgString);
  wave.getState().submitDelta(message);
  // path = '/message?r=99688636' + '&u=92246248';
  // var xhr = new XMLHttpRequest();
  // xhr.open('POST', path, true);
  // xhr.send(msgString);
}

function processSignalingMessage(message) {
  var msg = JSON.parse(message);

  if (msg.type === 'offer') {
    // Callee creates PeerConnection
    if (!initiator && !started)
      maybeStart();

    pc.setRemoteDescription(new RTCSessionDescription(msg));
    doAnswer();
  } else if (msg.type === 'answer' && started) {
    pc.setRemoteDescription(new RTCSessionDescription(msg));
  } else if (msg.type === 'candidate' && started) {
    var candidate = new RTCIceCandidate({
      sdpMLineIndex: msg.label,
      candidate: msg.candidate
    });
    pc.addIceCandidate(candidate);
  } else if (msg.type === 'bye' && started) {
    onRemoteHangup();
  }
}

function doAnswer() {
  console.log("Sending answer to peer.");
  pc.createAnswer(setLocalAndSendMessage, null, mediaConstraints);
}
*/
<commit_msg>Add logging<commit_after>var localStream;
var localPeerConnection;
var remotePeerConnection;
var users = [];
var candidates = {};
var descriptions = {};
var me = null;
var localVideo = document.getElementById('localVideo');
var remoteVideo = document.getElementById('remoteVideo');

localVideo.addEventListener('loadedmetadata', function() {
  trace('Local video currentSrc: ' + this.currentSrc +
    ', videoWidth: ' + this.videoWidth +
    'px,  videoHeight: ' + this.videoHeight + 'px');
});

remoteVideo.addEventListener('loadedmetadata', function() {
  trace('Remote video currentSrc: ' + this.currentSrc +
    ', videoWidth: ' + this.videoWidth +
    'px,  videoHeight: ' + this.videoHeight + 'px');
});

var startButton = document.getElementById('startButton');
var callButton = document.getElementById('callButton');
var hangupButton = document.getElementById('hangupButton');
var stopButton = document.getElementById('stopButton');
startButton.disabled = true;
stopButton.disabled = true;
callButton.disabled = true;
hangupButton.disabled = true;
startButton.onclick = start;
callButton.onclick = call;
hangupButton.onclick = hangup;
stopButton.onclick = stop;

function gotStream(stream) {
  trace('Received local stream');
  localVideo.src = URL.createObjectURL(stream);
  localStream = stream;
  callButton.disabled = false;
}

function start() {
  trace('Requesting local stream');
  startButton.disabled = true;
  stopButton.disabled = false;
  navigator.getUserMedia({
      video: true,
      audio: true
    }, gotStream,
    function(error) {
      trace('navigator.getUserMedia error: ', error);
    });
}

function stop() {

  startButton.disabled = false;
  stopButton.disabled = true;

  localStream.getVideoTracks()[0].stop()
  localStream.getAudioTracks()[0].stop()

}

function call() {
  callButton.disabled = true;
  hangupButton.disabled = false;
  trace('Starting call');

  if (localStream.getVideoTracks().length > 0) {
    trace('Using video device: ' + localStream.getVideoTracks()[0].label);
  }
  if (localStream.getAudioTracks().length > 0) {
    trace('Using audio device: ' + localStream.getAudioTracks()[0].label);
  }

  var servers = {
    "iceServers": [{
      url: 'stun:stun.iptel.org'
    }, {
      url: 'stun:stun.rixtelecom.se'
    }, {
      url: 'stun:stun.schlund.de'
    }, {
      url: 'stun:stun.l.google.com:19302'
    }, {
      url: 'stun:stun1.l.google.com:19302'
    }, {
      url: 'stun:stun2.l.google.com:19302'
    }, {
      url: 'stun:stun3.l.google.com:19302'
    }, {
      url: 'stun:stun4.l.google.com:19302'
    }, {
      url: 'stun:stunserver.org'
    }, {
      url: 'stun:stun.voxgratia.org'
    }, {
      url: 'turn:numb.viagenie.ca',
      credential: 'muazkh',
      username: 'webrtc@live.com'
    }]
  };

  localPeerConnection =
    new RTCPeerConnection(servers); // eslint-disable-line new-cap
  trace('Created local peer connection object localPeerConnection');
  localPeerConnection.onicecandidate = gotLocalIceCandidate;

  remotePeerConnection =
    new RTCPeerConnection(servers); // eslint-disable-line new-cap
  trace('Created remote peer connection object remotePeerConnection');
  remotePeerConnection.onicecandidate = gotRemoteIceCandidate;
  remotePeerConnection.onaddstream = gotRemoteStream;

  localPeerConnection.addStream(localStream);
  trace('Added localStream to localPeerConnection');
  localPeerConnection.createOffer(gotLocalDescription);
}

function gotLocalDescription(description) {
  localPeerConnection.setLocalDescription(description);
  trace('Offer from localPeerConnection: \n' + description.sdp);
  if (wave != null) {
    descriptions[me] = description
    wave.getState().submitDelta({
      'descriptions': descriptions
    });
  }
}

function gotRemoteDescription(description) {
  remotePeerConnection.setLocalDescription(description);
  trace('Answer from remotePeerConnection: \n' + description.sdp);
  localPeerConnection.setRemoteDescription(description);
}

function hangup() {
  trace('Ending call');
  hangupButton.disabled = true;
  callButton.disabled = false;
  remotePeerConnection.close();
  localPeerConnection.close();
  //  remotePeerConnection.close();
  localPeerConnection = null;
  remotePeerConnection = null;
  remoteVideo.src = null;
}

function gotRemoteStream(event) {
  remoteVideo.src = URL.createObjectURL(event.stream);
  trace('Received remote stream');
}

function gotLocalIceCandidate(event) {
  if (event.candidate) {
    if (wave != null) {
      candidates[me] = event.candidate
      wave.getState().submitDelta({
        'candidates': candidates
      });
    }
    //remotePeerConnection.addIceCandidate(new RTCIceCandidate(event.candidate));
    trace('Local ICE candidate: \n' + event.candidate.candidate);
  }
}

function gotRemoteIceCandidate(event) {
  if (event.candidate) {
    localPeerConnection.addIceCandidate(new RTCIceCandidate(event.candidate));
    trace('Remote ICE candidate: \n ' + event.candidate.candidate);
  }
}

// Renders the gadget
function stateChangeHandler() {
  // Get state
  if (!wave.getState() || !wave.getViewer()) {
    return;
  }
  startButton.disabled = false;
  me = wave.getViewer().getId();
  if (me && users.indexOf(me) < 0) {
    users.push(me);
    wave.getState().submitDelta({
      'users': users
    });
  }
  var state = wave.getState();
  users = state.get('users', users);
  candidates = state.get('candidates', candidates)
  descriptions = state.get('descriptions', candidates)

  //only if changed
  if (candidates != candidates) {
    for (var property in candidates) {
      if (candidates.hasOwnProperty(property) && property != me) {
        remotePeerConnection.addIceCandidate(new RTCIceCandidate(candidates[property]));
        console.log("Setting remote candidate", candidates[property])
        break; // No conference
      }
    }
  }
  if (descriptions != descriptions) {
    for (var property in descriptions) {
      if (descriptions.hasOwnProperty(property) && property != me) {
        remotePeerConnection.setRemoteDescription(descriptions[property]);
        remotePeerConnection.createAnswer(gotRemoteDescription);
        console.log("Setting remote description", descriptions[property])
        break; // No conference
      }
    }
  }
  console.log(" state users: ", users)
  console.log(" state candidates: ", candidates)
  console.log(" state descriptions: ", descriptions)
}

function init() {
  if (wave && wave.isInWaveContainer()) {
    // Loads the gadget's initial state and the subsequent changes to it
    wave.setStateCallback(stateChangeHandler);
    // Loads participants and any changes to them
    wave.setParticipantCallback(stateChangeHandler);
    console.log("wave state loaded")
  }

  // resetStatus();
  // openChannel('AHRlWrqvgCpvbd9B-Gl5vZ2F1BlpwFv0xBUwRgLF/* ...*/');
  // doGetUserMedia();

}
// Initializes gadget after receiving a notification that the page is loaded and the DOM is ready.
gadgets.util.registerOnLoadHandler(init);

/*
card = document.getElementById("card");
localVideo = document.getElementById("localVideo");
miniVideo = document.getElementById("miniVideo");
remoteVideo = document.getElementById("remoteVideo");
var pc = new webkitRTCPeerConnection(servers, {
  optional: [{
    RtpDataChannels: true
  }]
});

pc.ondatachannel = function(event) {
  receiveChannel = event.channel;
  receiveChannel.onmessage = function(event) {
    document.querySelector("div#receive").innerHTML = event.data;
  };
};

sendChannel = pc.createDataChannel("sendDataChannel", {
  reliable: false
});

document.querySelector("button#send").onclick = function() {
  var data = document.querySelector("textarea#send").value;
  sendChannel.send(data);
};

function onUserMediaSuccess(stream) {
  console.log("User has granted access to local media.");
  // Call the polyfill wrapper to attach the media stream to this element.
  attachMediaStream(localVideo, stream);
  localVideo.style.opacity = 1;
  localStream = stream;
  // Caller creates PeerConnection.
  if (initiator) maybeStart();
}

function maybeStart() {
  if (!started && localStream && channelReady) {
    // ...
    createPeerConnection();
    // ...
    pc.addStream(localStream);
    started = true;
    // Caller initiates offer to peer.
    if (initiator)
      doCall();
  }
}

function createPeerConnection() {
  var pc_config = {
    "iceServers": [{
      "url": "stun:stun.l.google.com:19302"
    }]
  };
  try {
    // Create an RTCPeerConnection via the polyfill (adapter.js).
    pc = new RTCPeerConnection(pc_config);
    pc.onicecandidate = onIceCandidate;
    console.log("Created RTCPeerConnnection with config:\n" + "  \"" +
      JSON.stringify(pc_config) + "\".");
  } catch (e) {
    console.log("Failed to create PeerConnection, exception: " + e.message);
    alert("Cannot create RTCPeerConnection object; WebRTC is not supported by this browser.");
    return;
  }

  pc.onconnecting = onSessionConnecting;
  pc.onopen = onSessionOpened;
  pc.onaddstream = onRemoteStreamAdded;
  pc.onremovestream = onRemoteStreamRemoved;
}

function onRemoteStreamAdded(event) {
  // ...
  miniVideo.src = localVideo.src;
  attachMediaStream(remoteVideo, event.stream);
  remoteStream = event.stream;
  waitForRemoteVideo();
}

function doCall() {
  console.log("Sending offer to peer.");
  pc.createOffer(setLocalAndSendMessage, null, mediaConstraints);
}

function setLocalAndSendMessage(sessionDescription) {
  // Set Opus as the preferred codec in SDP if Opus is present.
  sessionDescription.sdp = preferOpus(sessionDescription.sdp);
  pc.setLocalDescription(sessionDescription);
  sendMessage(sessionDescription);
}

function onIceCandidate(event) {
  if (event.candidate) {
    sendMessage({
      type: 'candidate',
      label: event.candidate.sdpMLineIndex,
      id: event.candidate.sdpMid,
      candidate: event.candidate.candidate
    });
  } else {
    console.log("End of candidates.");
  }
}

function sendMessage(message) {
  var msgString = JSON.stringify(message);
  console.log('C->S: ' + msgString);
  wave.getState().submitDelta(message);
  // path = '/message?r=99688636' + '&u=92246248';
  // var xhr = new XMLHttpRequest();
  // xhr.open('POST', path, true);
  // xhr.send(msgString);
}

function processSignalingMessage(message) {
  var msg = JSON.parse(message);

  if (msg.type === 'offer') {
    // Callee creates PeerConnection
    if (!initiator && !started)
      maybeStart();

    pc.setRemoteDescription(new RTCSessionDescription(msg));
    doAnswer();
  } else if (msg.type === 'answer' && started) {
    pc.setRemoteDescription(new RTCSessionDescription(msg));
  } else if (msg.type === 'candidate' && started) {
    var candidate = new RTCIceCandidate({
      sdpMLineIndex: msg.label,
      candidate: msg.candidate
    });
    pc.addIceCandidate(candidate);
  } else if (msg.type === 'bye' && started) {
    onRemoteHangup();
  }
}

function doAnswer() {
  console.log("Sending answer to peer.");
  pc.createAnswer(setLocalAndSendMessage, null, mediaConstraints);
}
*/
<|endoftext|>