<commit_before>import React, { Component } from 'react';
import { Link, withRouter } from 'react-router-dom';
import { compose } from 'recompose';

import { withFirebase } from '../Firebase';
import { withAuthorization } from '../Session';
import * as ROUTES from '../../constants/routes';
import Dashboard from '../Dashboard';

const CreateGamePage = () => (

Create Game

    <CreateGameForm />
    <button type="button"><Link to={ROUTES.DASHBOARD}>Back to dashboard</Link></button>

);

const INITIAL_STATE = {
  gameName: '',
  createdGameId: '',
  error: null,
};

class CreateGameFormBase extends Component {
  constructor(props) {
    super(props);

    this.state = { ...INITIAL_STATE };
  }

  onSubmit = event => {
    const { gameName } = this.state;

    this.props.firebase
      .doCreateGame(gameName)
      .then(gameRef => {
        this.setState({ ...INITIAL_STATE });
        this.setState({ createdGameId: gameRef.id });
      })
      .catch(error => {
        this.setState({ error });
      });

      event.preventDefault();
  };

  onChange = event => {
    this.setState({ [event.target.name]: event.target.value });
  };

  render() {
    const {
      gameName,
      createdGameId,
      error,
    } = this.state;

    const isInvalid = gameName === '';

    return (
      <form onSubmit={this.onSubmit}>
        <input
          name="gameName"
          value={gameName}
          onChange={this.onChange}
          type="text"
          placeholder="Game Name"
        />

        <button disabled={isInvalid} type="submit">Create Game</button>

        {createdGameId !== '' && (

Your game ID is {createdGameId}. Share this with your friends to add them to the game!

        )}

        {error &&
{error.message}
}
      </form>
    );
  }
}

const CreateGameForm = compose(
  withRouter,
  withFirebase,
)(CreateGameFormBase);

const condition = authUser => !!authUser;

export default withAuthorization(condition)(CreateGamePage);

export { CreateGameForm };
<commit_msg>Remove unnecessary import.<commit_after>import React, { Component } from 'react';
import { Link, withRouter } from 'react-router-dom';
import { compose } from 'recompose';

import { withFirebase } from '../Firebase';
import { withAuthorization } from '../Session';
import * as ROUTES from '../../constants/routes';

const CreateGamePage = () => (

Create Game

    <CreateGameForm />
    <button type="button"><Link to={ROUTES.DASHBOARD}>Back to dashboard</Link></button>

);

const INITIAL_STATE = {
  gameName: '',
  createdGameId: '',
  error: null,
};

class CreateGameFormBase extends Component {
  constructor(props) {
    super(props);

    this.state = { ...INITIAL_STATE };
  }

  onSubmit = event => {
    const { gameName } = this.state;

    this.props.firebase
      .doCreateGame(gameName)
      .then(gameRef => {
        this.setState({ ...INITIAL_STATE });
        this.setState({ createdGameId: gameRef.id });
      })
      .catch(error => {
        this.setState({ error });
      });

      event.preventDefault();
  };

  onChange = event => {
    this.setState({ [event.target.name]: event.target.value });
  };

  render() {
    const {
      gameName,
      createdGameId,
      error,
    } = this.state;

    const isInvalid = gameName === '';

    return (
      <form onSubmit={this.onSubmit}>
        <input
          name="gameName"
          value={gameName}
          onChange={this.onChange}
          type="text"
          placeholder="Game Name"
        />

        <button disabled={isInvalid} type="submit">Create Game</button>

        {createdGameId !== '' && (

Your game ID is {createdGameId}. Share this with your friends to add them to the game!

        )}

        {error &&
{error.message}
}
      </form>
    );
  }
}

const CreateGameForm = compose(
  withRouter,
  withFirebase,
)(CreateGameFormBase);

const condition = authUser => !!authUser;

export default withAuthorization(condition)(CreateGamePage);

export { CreateGameForm };
<|endoftext|>


<commit_before>import _ from "lodash";
import fsPath from "path";
import Promise from "bluebird";
import express from "express";
import webpack from "webpack";
import webpackMiddleware from "webpack-dev-middleware";
import webpackHotMiddleware from "webpack-hot-middleware";
import * as config from "../webpack-config";
import * as serverMethods from "./serverMethods";
import bdd from "../shared/bdd";

const parseSpecs = (paths) => {
    bdd.register();
    paths.forEach(path => { require(path); });
    bdd.unregister();
};

/**
 * Starts the UIHarness within a development server.
 * @param {object} options: Configuration settings.
 *                          If a {string/array} is passed, that value is set as the `entry`
 *
 *                          - entry: A string or array of strings to entry points of files
 *                                   to pass to WebPack to build for the client.
 *                          - port: The port to run on (default:8080).
 *                          - env:  The environment to run in ("development" / "production").
 * @param callback: Invokd when the server has started.
 */
export const start = (options = {}, callback) => {
  console.log("Starting...");

  const PORT = options.port || 8080;
  const ENV = options.env || process.env.NODE_ENV || "development"
  const IS_PRODUCTION = ENV === "production";
  const webpackConfig = config.browser({ port: PORT, env: ENV });

  // Prepare the server.
  const app = express();
  const startListening = () => {
      app.listen(PORT, () => {
            console.log("Started.");
            console.log("");
            console.log("UIHarness");
            console.log(" - port:", PORT);
            console.log(" - env: ", ENV);
            console.log("");
            if (_.isFunction(callback)) { callback(); }
      });
    };

  // Setup routing.
  const get = (route, file) => {
      file = fsPath.join(__dirname, `../../public/${ file || route }`);
      app.get(route, (req, res) => { res.sendFile(file); });
  };
  get("/", "index.html");
  get("/normalize.css");
  get("/favicon.ico");
  if (IS_PRODUCTION) {
    get("/public/bundle.js", "bundle.js");
  }

  // Ensure the options is an object.
  if (_.isString(options) || _.isArray(options)) {
    // A string or object was given, convert it to the "entry" option.
    options = { entry: options };
  }

  // Prepare entry paths for the WebPack compiler.
  let entry = options.entry || [];
  if (!_.isArray(entry)) { entry = [entry]; }
  entry = entry.map(path => { return _.startsWith(path, ".") ? fsPath.resolve(path) : path; });
  entry.forEach(path => { webpackConfig.entry.push(path); });

  // Iniitalize the [describe/it] statements.
  parseSpecs(entry);

  // Configure the server methods (REST API).
  // serverMethods.init({ connect:app });

  // Prepare webpack JS.
  if (IS_PRODUCTION) {
    // Compile and minify webpack JS for production.
    webpack(webpackConfig, (err, stats) => {
      if (err) { throw err; }
      startListening();
    });

  } else {
    // Create the WebPack compiler and "hot-reloading" dev server.
    const compiler = webpack(webpackConfig);
    app.use(webpackMiddleware(compiler, config.devServer({ port: PORT })));
    app.use(webpackHotMiddleware(compiler));
    startListening();
  }
};
<commit_msg>console<commit_after>import _ from "lodash";
import fsPath from "path";
import Promise from "bluebird";
import express from "express";
import webpack from "webpack";
import webpackMiddleware from "webpack-dev-middleware";
import webpackHotMiddleware from "webpack-hot-middleware";
import * as config from "../webpack-config";
import * as serverMethods from "./serverMethods";
import bdd from "../shared/bdd";

const parseSpecs = (paths) => {
    bdd.register();
    paths.forEach(path => { require(path); });
    bdd.unregister();
};

/**
 * Starts the UIHarness within a development server.
 * @param {object} options: Configuration settings.
 *                          If a {string/array} is passed, that value is set as the `entry`
 *
 *                          - entry: A string or array of strings to entry points of files
 *                                   to pass to WebPack to build for the client.
 *                          - port: The port to run on (default:8080).
 *                          - env:  The environment to run in ("development" / "production").
 * @param callback: Invokd when the server has started.
 */
export const start = (options = {}, callback) => {
  console.log("Starting...");

  const PORT = options.port || 8080;
  const ENV = options.env || process.env.NODE_ENV || "development"
  const IS_PRODUCTION = ENV === "production";
  const webpackConfig = config.browser({ port: PORT, env: ENV });

  // Prepare the server.
  const app = express();
  const startListening = () => {
      app.listen(PORT, () => {
            console.log("Started.");
            console.log("");
            console.log("UIHarness");
            console.log(" - port:", PORT);
            console.log(" - env: ", ENV);
            console.log("");
            if (_.isFunction(callback)) { callback(); }
      });
    };

  // Setup routing.
  const get = (route, file) => {
      file = fsPath.join(__dirname, `../../public/${ file || route }`);
      app.get(route, (req, res) => { res.sendFile(file); });
  };
  get("/", "index.html");
  get("/normalize.css");
  get("/favicon.ico");
  if (IS_PRODUCTION) {
    get("/public/bundle.js", "bundle.js");
  }

  // Ensure the options is an object.
  if (_.isString(options) || _.isArray(options)) {
    // A string or object was given, convert it to the "entry" option.
    options = { entry: options };
  }

  // Prepare entry paths for the WebPack compiler.
  let entry = options.entry || [];
  if (!_.isArray(entry)) { entry = [entry]; }
  entry = entry.map(path => { return _.startsWith(path, ".") ? fsPath.resolve(path) : path; });
  entry.forEach(path => { webpackConfig.entry.push(path); });

  // Iniitalize the [describe/it] statements.
  parseSpecs(entry);

  // Configure the server methods (REST API).
  // serverMethods.init({ connect:app });

  // Prepare webpack JS.
  if (IS_PRODUCTION) {
    // Compile and minify webpack JS for production.
    console.log("webpack bundling...");
    webpack(webpackConfig, (err, stats) => {
      if (err) { throw err; }
      startListening();
    });

  } else {
    // Create the WebPack compiler and "hot-reloading" dev server.
    const compiler = webpack(webpackConfig);
    app.use(webpackMiddleware(compiler, config.devServer({ port: PORT })));
    app.use(webpackHotMiddleware(compiler));
    startListening();
  }
};
<|endoftext|>


<commit_before>/*
Input Mask plugin for jquery
Copyright (c) 2010 Robin Herbots
Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
Version: 0.0.1

This plugin is based on the masked input plugin written by Josh Bush (digitalbush.com)
*/

(function($) {

    $.fn.inputmask = function(mask, options) {
        var defaults = {
            placeholder: "_",
            onComplete: null,
            definitions: {
                '9': {
                    "validator": "[0-9]",
                    "cardinality": 1,
                    'prevalidator': null
                },
                'a': {
                    "validator": "[A-Za-z]",
                    "cardinality": 1,
                    "prevalidator": null
                },
                '*': {
                    "validator": "[A-Za-z0-9]",
                    "cardinality": 1,
                    "prevalidator": null
                },
                'd': { //day
                    "validator": "0[1-9]|[12][0-9]|3[01]",
                    "cardinality": 2,
                    "prevalidator": [{ "validator": "[0-3]", "cardinality": 1}]
                },
                'm': { //month
                    "validator": "0[1-9]|1[012]",
                    "cardinality": 2,
                    "prevalidator": [{ "validator": "[01]", "cardinality": 1}]
                },
                'y': { //year
                    "validator": "(19|20)\\d\\d",
                    "cardinality": 4,
                    "prevalidator": [
                        { "validator": "[12]", "cardinality": 1 },
                        { "validator": "(19|20)", "cardinality": 2 },
                        { "validator": "(19|20)\\d", "cardinality": 3 }
                        ]
                }
            },
            keyCode: { ALT: 18, BACKSPACE: 8, CAPS_LOCK: 20, COMMA: 188, COMMAND: 91, COMMAND_LEFT: 91, COMMAND_RIGHT: 93, CONTROL: 17, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, INSERT: 45, LEFT: 37, MENU: 93, NUMPAD_ADD: 107, NUMPAD_DECIMAL: 110, NUMPAD_DIVIDE: 111, NUMPAD_ENTER: 108,
                NUMPAD_MULTIPLY: 106, NUMPAD_SUBTRACT: 109, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SHIFT: 16, SPACE: 32, TAB: 9, UP: 38, WINDOWS: 91
            }
        };

        function getMaskTemplate() {
            return $.map(mask.split(""), function(element, index) {
                var outElem = [];
                var maskdef = opts.definitions[element];
                if (maskdef) {
                    for (i = 0; i < maskdef.cardinality; i++) {
                        outElem.push(opts.placeholder);
                    }
                } else outElem.push(element);

                return outElem;
            });
        };

        function getTestingChain() {
            return $.map(mask.split(""), function(element, index) {
                var outElem = [];
                var maskdef = opts.definitions[element];
                if (maskdef) {
                    for (i = 1; i < maskdef.cardinality; i++) {
                        var prevalidator = maskdef.prevalidator[i - 1];
                        outElem.push([new RegExp(prevalidator.validator), prevalidator.cardinality]);
                    }
                    outElem.push([new RegExp(maskdef.validator), maskdef.cardinality]);
                } else outElem.push(null);

                return outElem;
            });
        };

        var opts = $.extend({}, defaults, options);

        //init buffer
        var _buffer = getMaskTemplate();
        var pasteEventName = $.browser.msie ? 'paste' : 'input';
        var iPhone = (window.orientation != undefined);
        var tests = getTestingChain();

        return this.each(function() {
            var input = $(this);
            //init buffer
            var buffer = _buffer.slice();
            var undoBuffer = input.val();
            var ignore = false;  			//Variable for ignoring control keys
            var len = _buffer.length;

            //bind events
            if (!input.attr("readonly")) {
                input.bind("focus", function() {
                    undoBuffer = input.val();
                    var pos = checkVal();
                    writeBuffer();
                    setTimeout(function() {
                        if (pos == _buffer.length)
                            caret(input, 0, pos);
                        else
                            caret(input, pos);
                    }, 0);
                }).bind("mouseenter", function() {
                    if (input.val().length == 0)
                        writeBuffer();
                }).bind("blur", function() {
                    if (input.val() == _buffer.join('')) {
                        input.val('');
                    }
                    checkVal();
                    if (input.val() != undoBuffer)
                        input.change();
                }).bind("mouseleave", function() {
                    if (input.val() == _buffer.join(''))
                        input.val('');
                }).bind("keydown", keydownEvent
				).bind("keypress", keypressEvent
				).bind(pasteEventName, function() {
				    setTimeout(function() { caret(input, checkVal(true)); }, 0);
				});

            }

            checkVal();

            //private functions
            function writeBuffer() { return input.val(buffer.join('')).val(); };
            function clearBuffer(start, end) {
                for (var i = start; i < end && i < len; i++) {
                    buffer[i] = _buffer[i];
                }
            };

            function seekNext(pos) {
                while (++pos <= len && !tests[pos]);
                return pos;
            };

            function shiftL(pos) {
                while (!tests[pos] && --pos >= 0);
                for (var i = pos; i < len; i++) {
                    if (tests[i]) {
                        buffer[i] = opts.placeholder;
                        var j = seekNext(i);
                        if (j < len && isValid(i, buffer[j])) {
                            buffer[i] = buffer[j];
                        } else
                            break;
                    }
                }
                writeBuffer();
                caret(input, pos);
            };

            function shiftR(pos) {
                for (var i = pos, c = opts.placeholder; i < len; i++) {
                    if (tests[i]) {
                        var j = seekNext(i);
                        var t = buffer[i];
                        buffer[i] = c;
                        if (j < len && isValid(j, t))
                            c = t;
                        else
                            break;
                    }
                }
            };

            function caret(input, begin, end) {
                if (input.length == 0) return;
                if (typeof begin == 'number') {
                    end = (typeof end == 'number') ? end : begin;
                    return input.each(function() {
                        if (this.setSelectionRange) {
                            this.focus();
                            this.setSelectionRange(begin, end);
                        } else if (this.createTextRange) {
                            var range = this.createTextRange();
                            range.collapse(true);
                            range.moveEnd('character', end);
                            range.moveStart('character', begin);
                            range.select();
                        }
                    });
                } else {
                    if (input[0].setSelectionRange) {
                        begin = input[0].selectionStart;
                        end = input[0].selectionEnd;
                    } else if (document.selection && document.selection.createRange) {
                        var range = document.selection.createRange();
                        begin = 0 - range.duplicate().moveStart('character', -100000);
                        end = begin + range.text.length;
                    }
                    return { begin: begin, end: end };
                }
            };

            function keydownEvent(e) {
                var pos = caret($(this));
                var k = e.keyCode;
                ignore = (k < 16 || (k > 16 && k < 32) || (k > 32 && k < 41));

                //delete selection before proceeding
                if ((pos.begin - pos.end) != 0 && (!ignore || k == opts.keyCode.BACKSPACE || k == opts.keyCode.DELETE))
                    clearBuffer(pos.begin, pos.end);

                //backspace, delete, and escape get special treatment
                if (k == opts.keyCode.BACKSPACE || k == opts.keyCode.DELETE || (iPhone && k == 127)) {//backspace/delete
                    shiftL(pos.begin + (k == opts.keyCode.DELETE ? 0 : -1));
                    return false;
                } else if (k == opts.keyCode.ESCAPE) {//escape
                    input.val(undoBuffer);
                    caret(input, 0, checkVal());
                    return false;
                }
            }

            function keypressEvent(e) {
                if (ignore) {
                    ignore = false;
                    //Fixes Mac FF bug on backspace
                    return (e.keyCode == 8) ? false : null;
                }
                e = e || window.event;
                var k = e.charCode || e.keyCode || e.which;
                var pos = caret($(this));

                if (e.ctrlKey || e.altKey || e.metaKey) {//Ignore
                    return true;
                } else if ((k >= 32 && k <= 125) || k > 186) {//typeable characters
                    var p = seekNext(pos.begin - 1);
                    if (p < len) {
                        var c = String.fromCharCode(k);
                        if (isValid(p, c)) {
                            shiftR(p);
                            buffer[p] = c;
                            writeBuffer();
                            var next = seekNext(p);
                            caret($(this), next);
                            if (opts.onComplete && next == len)
                                opts.onComplete.call(input);
                        }
                    }
                }
                return false;
            }

            function isValid(pos, c) {
                var inputValue = input.val();

                var loopend = 0;
                if (c) { loopend = 1; ; }

                var chrs = '';
                for (var i = tests[pos][1]; i > loopend; i--) {
                    chrs += inputValue.charAt(pos - (i - 1));
                }

                if (c) { chrs += c; }

                return tests[pos][0].test(chrs);
            }

            function checkVal(clearInvalid) {
                var inputValue = input.val();
                var lastMatch = -1;
                for (var i = 0; i < inputValue.length; i++) {
                    if (tests[i]) {
                        buffer[i] = opts.placeholder;
                        if (isValid(i)) {
                            buffer[i] = inputValue.charAt(i);
                            lastMatch = i;
                        } else break;
                    } else if (buffer[i] == inputValue.charAt(i)) {
                        lastMatch = i;
                    }
                }
                if (clearInvalid) {
                    writeBuffer();
                }
                return lastMatch + 1;
            };

        });
    };

})(jQuery);<commit_msg>copy/paste logic fix<commit_after>/*
Input Mask plugin for jquery
Copyright (c) 2010 Robin Herbots
Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
Version: 0.0.2

This plugin is based on the masked input plugin written by Josh Bush (digitalbush.com)
*/

(function($) {

    $.fn.inputmask = function(fn, options) {
        //options default
        var defaults = {
            placeholder: "_",
            mask: null,
            onComplete: null,
            definitions: {
                '9': {
                    "validator": "[0-9]",
                    "cardinality": 1,
                    'prevalidator': null
                },
                'a': {
                    "validator": "[A-Za-z]",
                    "cardinality": 1,
                    "prevalidator": null
                },
                '*': {
                    "validator": "[A-Za-z0-9]",
                    "cardinality": 1,
                    "prevalidator": null
                },
                'd': { //day
                    "validator": "0[1-9]|[12][0-9]|3[01]",
                    "cardinality": 2,
                    "prevalidator": [{ "validator": "[0-3]", "cardinality": 1}]
                },
                'm': { //month
                    "validator": "0[1-9]|1[012]",
                    "cardinality": 2,
                    "prevalidator": [{ "validator": "[01]", "cardinality": 1}]
                },
                'y': { //year
                    "validator": "(19|20)\\d\\d",
                    "cardinality": 4,
                    "prevalidator": [
                        { "validator": "[12]", "cardinality": 1 },
                        { "validator": "(19|20)", "cardinality": 2 },
                        { "validator": "(19|20)\\d", "cardinality": 3 }
                        ]
                }
            },
            keyCode: { ALT: 18, BACKSPACE: 8, CAPS_LOCK: 20, COMMA: 188, COMMAND: 91, COMMAND_LEFT: 91, COMMAND_RIGHT: 93, CONTROL: 17, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, INSERT: 45, LEFT: 37, MENU: 93, NUMPAD_ADD: 107, NUMPAD_DECIMAL: 110, NUMPAD_DIVIDE: 111, NUMPAD_ENTER: 108,
                NUMPAD_MULTIPLY: 106, NUMPAD_SUBTRACT: 109, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SHIFT: 16, SPACE: 32, TAB: 9, UP: 38, WINDOWS: 91
            }
        };

        var opts = $.extend({}, defaults, options);

        if (typeof fn == "string") {
            if (fn == 'mask') {
                //init buffer
                var _buffer = getMaskTemplate();
                var pasteEventName = $.browser.msie ? 'paste' : 'input';
                var iPhone = (window.orientation != undefined);
                var tests = getTestingChain();

                return this.each(function() {
                    mask($(this));
                });
            } else if (fn == 'unmaskedvalue') {
                return unmaskedvalue($(this));
            } else { //maybe fn is a mask so we try
            	//set mask
            	opts.mask = fn;

            	//init buffer
                var _buffer = getMaskTemplate();
                var pasteEventName = $.browser.msie ? 'paste' : 'input';
                var iPhone = (window.orientation != undefined);
                var tests = getTestingChain();

                return this.each(function() {
                    mask($(this));
                });
            }
        }

        //functions
        function getMaskTemplate() {
            return $.map(opts.mask.split(""), function(element, index) {
                var outElem = [];
                var maskdef = opts.definitions[element];
                if (maskdef) {
                    for (i = 0; i < maskdef.cardinality; i++) {
                        outElem.push(opts.placeholder);
                    }
                } else outElem.push(element);

                return outElem;
            });
        };

        function getTestingChain() {
            return $.map(opts.mask.split(""), function(element, index) {
                var outElem = [];
                var maskdef = opts.definitions[element];
                if (maskdef) {
                    for (i = 1; i < maskdef.cardinality; i++) {
                        var prevalidator = maskdef.prevalidator[i - 1];
                        outElem.push([new RegExp(prevalidator.validator), prevalidator.cardinality]);
                    }
                    outElem.push([new RegExp(maskdef.validator), maskdef.cardinality]);
                } else outElem.push(null);

                return outElem;
            });
        };

        function unmaskedvalue(el) {
            var tests = el.data('tests');
            if (tests) {
                return $.map(el.val().split(""), function(element, index) {
                    return tests[index] ? element : null;
                }).join('');
            }
            else {
                return el.val();
            }
        }

        function mask(el) {
            var input = $(el);
            //store tests in the input element - used to get the unmasked value
            input.data('tests', tests);

            //init buffer
            var buffer = _buffer.slice();
            var undoBuffer = input.val();
            var ignore = false;              //Variable for ignoring control keys
            var len = _buffer.length;

            //bind events
            if (!input.attr("readonly")) {
                input.bind("focus", function() {
                    undoBuffer = input.val();
                    var pos = checkVal();
                    writeBuffer();
                    setTimeout(function() {
                        if (pos == _buffer.length)
                            caret(input, 0, pos);
                        else
                            caret(input, pos);
                    }, 0);
                }).bind("mouseenter", function() {
                    if (input.val().length == 0)
                        writeBuffer();
                }).bind("blur", function() {
                    if (input.val() == _buffer.join('')) {
                        input.val('');
                    } else {
                        checkVal();
                        if (input.val() != undoBuffer)
                            input.change();
                    }
                }).bind("mouseleave", function() {
                    if (input.val() == _buffer.join(''))
                        input.val('');
                }).bind("keydown", keydownEvent
                ).bind("keypress", keypressEvent
                ).bind(pasteEventName, function() {
                    setTimeout(function() { caret(input, checkVal(true)); }, 0);
                });

            }

            checkVal();

            //private functions
            function writeBuffer() { return input.val(buffer.join('')).val(); };
            function clearBuffer(start, end) {
                for (var i = start; i < end && i < len; i++) {
                    buffer[i] = _buffer[i];
                }
            };

            function seekNext(pos) {
                while (++pos <= len && !isMask(pos));
                return pos;
            };

            function shiftL(pos) {
                while (!isMask(pos) && --pos >= 0);
                for (var i = pos; i < len; i++) {
                    if (isMask(i)) {
                        buffer[i] = opts.placeholder;
                        var j = seekNext(i);
                        if (j < len && isValid(i, buffer[j])) {
                            buffer[i] = buffer[j];
                        } else
                            break;
                    }
                }
                writeBuffer();
                caret(input, pos);
            };

            function shiftR(pos) {
                for (var i = pos, c = opts.placeholder; i < len; i++) {
                    if (isMask(i)) {
                        var j = seekNext(i);
                        var t = buffer[i];
                        buffer[i] = c;
                        if (j < len && isValid(j, t))
                            c = t;
                        else
                            break;
                    }
                }
            };

            function caret(input, begin, end) {
                if (input.length == 0) return;
                if (typeof begin == 'number') {
                    end = (typeof end == 'number') ? end : begin;
                    return input.each(function() {
                        if (this.setSelectionRange) {
                            this.focus();
                            this.setSelectionRange(begin, end);
                        } else if (this.createTextRange) {
                            var range = this.createTextRange();
                            range.collapse(true);
                            range.moveEnd('character', end);
                            range.moveStart('character', begin);
                            range.select();
                        }
                    });
                } else {
                    if (input[0].setSelectionRange) {
                        begin = input[0].selectionStart;
                        end = input[0].selectionEnd;
                    } else if (document.selection && document.selection.createRange) {
                        var range = document.selection.createRange();
                        begin = 0 - range.duplicate().moveStart('character', -100000);
                        end = begin + range.text.length;
                    }
                    return { begin: begin, end: end };
                }
            };

            function keydownEvent(e) {
                var pos = caret($(this));
                var k = e.keyCode;
                ignore = (k < 16 || (k > 16 && k < 32) || (k > 32 && k < 41));

                //delete selection before proceeding
                if ((pos.begin - pos.end) != 0 && (!ignore || k == opts.keyCode.BACKSPACE || k == opts.keyCode.DELETE))
                    clearBuffer(pos.begin, pos.end);

                //backspace, delete, and escape get special treatment
                if (k == opts.keyCode.BACKSPACE || k == opts.keyCode.DELETE || (iPhone && k == 127)) {//backspace/delete
                    shiftL(pos.begin + (k == opts.keyCode.DELETE ? 0 : -1));
                    return false;
                } else if (k == opts.keyCode.ESCAPE) {//escape
                    input.val(undoBuffer);
                    caret(input, 0, checkVal());
                    return false;
                }
            }

            function keypressEvent(e) {
                if (ignore) {
                    ignore = false;
                    //Fixes Mac FF bug on backspace
                    return (e.keyCode == 8) ? false : null;
                }
                e = e || window.event;
                var k = e.charCode || e.keyCode || e.which;
                var pos = caret($(this));

                if (e.ctrlKey || e.altKey || e.metaKey) {//Ignore
                    return true;
                } else if ((k >= 32 && k <= 125) || k > 186) {//typeable characters
                    var p = seekNext(pos.begin - 1);
                    if (p < len) {
                        var c = String.fromCharCode(k);
                        if (isValid(p, c)) {
                            shiftR(p);
                            buffer[p] = c;
                            writeBuffer();
                            var next = seekNext(p);
                            caret($(this), next);
                            if (opts.onComplete && next == len)
                                opts.onComplete.call(input);
                        }
                    }
                }
                return false;
            }

            function isValid(pos, c) {
                var inputValue = input.val();

                var loopend = 0;
                if (c) { loopend = 1; ; }

                var chrs = '';
                for (var i = tests[pos][1]; i > loopend; i--) {
                    chrs += buffer[pos - (i - 1)];
                }

                if (c) { chrs += c; }

                return tests[pos][0].test(chrs);
            }

            function isMask(pos) {
                return tests[pos];
            }

            function checkVal(clearInvalid) {
                var inputValue = input.val();
                var lastMatch = -1;
                for (var i = 0; i < inputValue.length; i++) {
                    for (var pos = lastMatch+1; pos < len; pos++) {
                    	if(isMask(pos)){
                        	buffer[pos] = opts.placeholder;
                        	if (isValid(pos, inputValue.charAt(i))) {
                           		buffer[pos] = inputValue.charAt(i);
                           		lastMatch = pos;
                        	}
                        	break;
                        }else {   //nonmask
                           lastMatch++;
                        }
                    }
                }
                if (clearInvalid) {
                    writeBuffer();
                }
                return seekNext(lastMatch);
            };
        }
    };

})(jQuery);<|endoftext|>


<commit_before>const PropertyViewFactoryComplex = require('./factory/property_view_factory_complex');
const ButtonViewInterface        = require('./interface/button_view_interface');
const FolderViewInterface        = require('./interface/folder_view_interface');
const PropertyViewInterface      = require('./interface/property_view_interface');
const ClassName                  = require('./misc/class_name');
const Errors                     = require('./misc/errors');
const EventEmitter               = require('./misc/event_emitter');
const Style                      = require('./misc/style');
const ViewUtil                   = require('./misc/view_util');
const Model                      = require('./model/model');
const ButtonView                 = require('./view/button_view');
const FolderView                 = require('./view/folder_view');
const PropertyView               = require('./view/property_view');
const SeparatorView              = require('./view/separator_view');
const RootFolderView             = require('./view/root_folder_view');
const RootView                   = require('./view/root_view');

class Core {
	constructor(opt_options) {
		this.rootView_ = new RootView();

		const options = (opt_options !== undefined) ?
			opt_options :
			{};

		const containerElem = (options.container !== undefined) ?
			options.container :
			this.createDefaultContainer_();
		if (containerElem) {
			containerElem.appendChild(this.rootView_.getElement());
		}

		this.emitter_ = new EventEmitter();

		Style.injectDefault();

		const foldable = (options.foldable !== undefined) ?
			options.foldable :
			true;
		if (foldable) {
			this.rootView_.getFooterView().addSubview(
				new RootFolderView()
			);
		}
	}

	createDefaultContainer_() {
		const containerElem = document.createElement('div');
		containerElem.classList.add(ClassName.get('DefaultContainer'));
		document.body.appendChild(containerElem);
		return containerElem;
	}

	getElement() {
		return this.rootView_.getElement();
	}

	getEmitter() {
		return this.emitter_;
	}

	addProperty_(target, propName, options) {
		const propView = PropertyViewFactoryComplex.create(
			target, propName, options
		);

		this.rootView_.getMainView().addSubview(propView);

		const prop = propView.getProperty();
		const model = prop.getModel();
		model.getEmitter().on(
			Model.EVENT_CHANGE,
			() => {
				this.onPropertyModelChange_(prop);
			},
			this
		);

		return propView;
	}

	getProperties_() {
		const views = ViewUtil.getAllSubviews(this.rootView_);
		const propViews = views.filter((view) => {
			return view instanceof PropertyView;
		});
		return propViews.map((propView) => {
			return propView.getProperty();
		});
	}

	getPropertiesForJson_() {
		const props = this.getProperties_().filter((prop) => {
			return !prop.isForMonitor();
		});
		const result = {};
		props.forEach((prop) => {
			const propId = prop.getId();
			if (result[propId] !== undefined) {
				throw Errors.duplicatedPropertyId(propId);
			}
			result[propId] = prop;
		});
		return result;
	}

	add(target, propName, opt_options) {
		const options = (opt_options !== undefined) ?
			opt_options :
			{};
		options.forMonitor = false;

		const propView = this.addProperty_(
			target, propName, options
		);
		return new PropertyViewInterface(propView);
	}

	monitor(target, propName, opt_options) {
		const options = (opt_options !== undefined) ?
			opt_options :
			{};
		options.forMonitor = true;

		const propView = this.addProperty_(
			target, propName, options
		);
		return new PropertyViewInterface(propView);
	}

	refresh() {
		this.getProperties_().forEach((prop) => {
			prop.applySourceValue();
		});
	}

	getJson() {
		const props = this.getPropertiesForJson_();
		return Object.keys(props).reduce((result, propId) => {
			const prop = props[propId];
			result[propId] = prop.getValue();
			return result;
		}, {});
	}

	setJson(json) {
		const props = this.getPropertiesForJson_();
		Object.keys(json).forEach((propId) => {
			const prop = props[propId];
			if (prop === undefined) {
				return;
			}

			prop.setValue(json[propId]);
		});
	}

	/**
	 * Adds a folder.
	 * @param {string} title A title
	 * @return {FolderViewInterface}
	*/
	addFolder(title) {
		const folderView = new FolderView(title);
		const parentView = this.rootView_.getMainView();
		parentView.addSubview(folderView);
		return new FolderViewInterface(folderView);
	}

	/**
	 * Adds a button.
	 * @param {string} title A title
	 * @return {ButtonViewInterface}
	 */
	addButton(title) {
		const buttonView = new ButtonView(title);
		const parentView = this.rootView_.getMainView();
		parentView.addSubview(buttonView);
		return new ButtonViewInterface(buttonView);
	}

	/**
	 * Adds a separator.
	 */
	addSeparator() {
		const separatorView = new SeparatorView();
		const parentView = this.rootView_.getMainView();
		parentView.addSubview(separatorView);
	}

	on(eventName, handler, opt_scope) {
		this.emitter_.on(eventName, handler, opt_scope);
		return this;
	}

	off(eventName, handler, opt_scope) {
		this.emitter_.off(eventName, handler, opt_scope);
		return this;
	}

	onPropertyModelChange_(prop) {
		this.emitter_.notifyObservers(
			Core.EVENT_CHANGE,
			[prop.getModel().getValue(), prop]
		);
	}
}

Core.EVENT_CHANGE = 'change';

module.exports = Core;
<commit_msg>Remove unused method<commit_after>const PropertyViewFactoryComplex = require('./factory/property_view_factory_complex');
const ButtonViewInterface        = require('./interface/button_view_interface');
const FolderViewInterface        = require('./interface/folder_view_interface');
const PropertyViewInterface      = require('./interface/property_view_interface');
const ClassName                  = require('./misc/class_name');
const Errors                     = require('./misc/errors');
const EventEmitter               = require('./misc/event_emitter');
const Style                      = require('./misc/style');
const ViewUtil                   = require('./misc/view_util');
const Model                      = require('./model/model');
const ButtonView                 = require('./view/button_view');
const FolderView                 = require('./view/folder_view');
const PropertyView               = require('./view/property_view');
const SeparatorView              = require('./view/separator_view');
const RootFolderView             = require('./view/root_folder_view');
const RootView                   = require('./view/root_view');

class Core {
	constructor(opt_options) {
		this.rootView_ = new RootView();

		const options = (opt_options !== undefined) ?
			opt_options :
			{};

		const containerElem = (options.container !== undefined) ?
			options.container :
			this.createDefaultContainer_();
		if (containerElem) {
			containerElem.appendChild(this.rootView_.getElement());
		}

		this.emitter_ = new EventEmitter();

		Style.injectDefault();

		const foldable = (options.foldable !== undefined) ?
			options.foldable :
			true;
		if (foldable) {
			this.rootView_.getFooterView().addSubview(
				new RootFolderView()
			);
		}
	}

	createDefaultContainer_() {
		const containerElem = document.createElement('div');
		containerElem.classList.add(ClassName.get('DefaultContainer'));
		document.body.appendChild(containerElem);
		return containerElem;
	}

	getElement() {
		return this.rootView_.getElement();
	}

	addProperty_(target, propName, options) {
		const propView = PropertyViewFactoryComplex.create(
			target, propName, options
		);

		this.rootView_.getMainView().addSubview(propView);

		const prop = propView.getProperty();
		const model = prop.getModel();
		model.getEmitter().on(
			Model.EVENT_CHANGE,
			() => {
				this.onPropertyModelChange_(prop);
			},
			this
		);

		return propView;
	}

	getProperties_() {
		const views = ViewUtil.getAllSubviews(this.rootView_);
		const propViews = views.filter((view) => {
			return view instanceof PropertyView;
		});
		return propViews.map((propView) => {
			return propView.getProperty();
		});
	}

	getPropertiesForJson_() {
		const props = this.getProperties_().filter((prop) => {
			return !prop.isForMonitor();
		});
		const result = {};
		props.forEach((prop) => {
			const propId = prop.getId();
			if (result[propId] !== undefined) {
				throw Errors.duplicatedPropertyId(propId);
			}
			result[propId] = prop;
		});
		return result;
	}

	add(target, propName, opt_options) {
		const options = (opt_options !== undefined) ?
			opt_options :
			{};
		options.forMonitor = false;

		const propView = this.addProperty_(
			target, propName, options
		);
		return new PropertyViewInterface(propView);
	}

	monitor(target, propName, opt_options) {
		const options = (opt_options !== undefined) ?
			opt_options :
			{};
		options.forMonitor = true;

		const propView = this.addProperty_(
			target, propName, options
		);
		return new PropertyViewInterface(propView);
	}

	refresh() {
		this.getProperties_().forEach((prop) => {
			prop.applySourceValue();
		});
	}

	getJson() {
		const props = this.getPropertiesForJson_();
		return Object.keys(props).reduce((result, propId) => {
			const prop = props[propId];
			result[propId] = prop.getValue();
			return result;
		}, {});
	}

	setJson(json) {
		const props = this.getPropertiesForJson_();
		Object.keys(json).forEach((propId) => {
			const prop = props[propId];
			if (prop === undefined) {
				return;
			}

			prop.setValue(json[propId]);
		});
	}

	/**
	 * Adds a folder.
	 * @param {string} title A title
	 * @return {FolderViewInterface}
	*/
	addFolder(title) {
		const folderView = new FolderView(title);
		const parentView = this.rootView_.getMainView();
		parentView.addSubview(folderView);
		return new FolderViewInterface(folderView);
	}

	/**
	 * Adds a button.
	 * @param {string} title A title
	 * @return {ButtonViewInterface}
	 */
	addButton(title) {
		const buttonView = new ButtonView(title);
		const parentView = this.rootView_.getMainView();
		parentView.addSubview(buttonView);
		return new ButtonViewInterface(buttonView);
	}

	/**
	 * Adds a separator.
	 */
	addSeparator() {
		const separatorView = new SeparatorView();
		const parentView = this.rootView_.getMainView();
		parentView.addSubview(separatorView);
	}

	on(eventName, handler, opt_scope) {
		this.emitter_.on(eventName, handler, opt_scope);
		return this;
	}

	off(eventName, handler, opt_scope) {
		this.emitter_.off(eventName, handler, opt_scope);
		return this;
	}

	onPropertyModelChange_(prop) {
		this.emitter_.notifyObservers(
			Core.EVENT_CHANGE,
			[prop.getModel().getValue(), prop]
		);
	}
}

Core.EVENT_CHANGE = 'change';

module.exports = Core;
<|endoftext|>


<commit_before>AutoForm.hooks({
    'events-form': {
        onSuccess: function (operation, result, template) {
            slidePanel.closePanel();
            Materialize.toast('Event submitted successfully!', 4000);
            if (operation === "insert") {
                Session.set("selected", result);
                $('#congratsModal').openModal({
                   dismissible: true
                 });
                GAnalytics.event("Events","create");
            } else {
                GAnalytics.event("Events","edit");
            }
        },
        onError: function(formType, error) {
            GAnalytics.event("Events","form_error");
            console.error(error);
        }
    }
});

// Fix for geocodeDataSource (It doesen't have access to Template.instance())
var templateInstance = null;
//

Template.eventsForm.onCreated(function() {
    this.debounce = null;
    templateInstance = Template.instance();
    console.log('hear');
    this.subscribe('categories');
    this.setCoordinates = function (lat, lng) {
        var instance = Template.instance();
        instance.$('input[name="coordinates.lat"]').val(lat);
        instance.$('input[name="coordinates.lng"]').val(lng);
    };

});

Template.eventsForm.helpers({
    categories: function(){
        return Categories.find({});
    },
    geocodeDataSource: function(query, sync, asyncCallback, template) {
        var instance = templateInstance;
        if (instance.debounce) {
            Meteor.clearTimeout(instance.debounce);
        }
        const debounceDelay = 500; //wait half a second before triggering search
        instance.debounce = Meteor.setTimeout(function() {
            Meteor.call('getCoords', query, function (error, result) {
                console.info("Query: " + query);
                var mapResultToDisplay = function () {
                    var isCity = function(element, index) {
                        return element.city!=null
                    };
                    return result.filter(isCity).map(function (v) {
                            console.info("Response: " + JSON.stringify(v));
                            var streetName = _.isNull(v.streetName) ? '' : v.streetName + ' ';
                            var streetNumber = _.isNull(v.streetNumber) ? _.isEmpty(streetName) ? '' : ', ' : +v.streetNumber + ', ';
                            var city  = _.isNull(v.city) ? '' : v.city + ', ';
                            var state  = _.isNull(v.state) ? '' : v.state + ', ';
                            return {
                                value: streetName + streetNumber + city + state + v.country,
                                lat: v.latitude,
                                lng: v.longitude
                            };
                        }
                    );
                };

                if (error != undefined) {
                    console.error(error);
                    Events.simpleSchema().namedContext("events-form").addInvalidKeys([{
                        name: "address",
                        type: "offline"
                    }]);
                } else {
                    asyncCallback(mapResultToDisplay());
                }
            });
        }, debounceDelay);
    },
    selectedHandler: function (event, suggestion, datasetName) {
        var coordsDefined = !_.isUndefined(suggestion.lat) && !_.isUndefined(suggestion.lng);
        if (coordsDefined) {
            Template.instance().setCoordinates(suggestion.lat,suggestion.lng);
            AutoForm.validateField('events-form', 'coordinates', false); //remove potential validation error
        } else {
            throw Meteor.Error('cords-undefined', 'Coordinates are empty for the selected location');
        }

    },
    selectedEventDoc: function() { return Events.findOne(Session.get('selected'));},
    isEdit: function() { return Session.get('isEdit') }
});

Template.eventsForm.onRendered(function () {
    Meteor.typeahead.inject();

    this.$('input[name=address]').detach().insertBefore('.twitter-typeahead');
    this.$('.twitter-typeahead').find('input[type=text]').remove();
    var copyCoordsFromSelectedEvent = function () {
        if (Session.get('isEdit')) {
            var selectedEvent = Events.findOne(Session.get('selected'));
            if (selectedEvent != null) {
                Template.instance().setCoordinates(selectedEvent.coordinates.lat, selectedEvent.coordinates.lng);
            }
        }
    };
    copyCoordsFromSelectedEvent();
    var fixMaterializeActiveClassTrigger = function() {
        $('input[name=address]').detach().insertBefore('.twitter-typeahead');
        $('.twitter-typeahead').find('input[type=text]').remove();
    };
    //this is a hack, because Typeahead duplicates input and inserts it inside of a new span item which breaks Materialize
    fixMaterializeActiveClassTrigger();
});

Template.eventsForm.onDestroyed(function () {
    var $typeahead = $('.typeahead');
    $typeahead.unbind();
    AutoForm.resetForm('events-form');
    $typeahead.typeahead('destroy');
});
<commit_msg>Fixed init issue with typeahead<commit_after>AutoForm.hooks({
    'events-form': {
        onSuccess: function (operation, result, template) {
            slidePanel.closePanel();
            Materialize.toast('Event submitted successfully!', 4000);
            if (operation === "insert") {
                Session.set("selected", result);
                $('#congratsModal').openModal({
                   dismissible: true
                 });
                GAnalytics.event("Events","create");
            } else {
                GAnalytics.event("Events","edit");
            }
        },
        onError: function(formType, error) {
            GAnalytics.event("Events","form_error");
            console.error(error);
        }
    }
});

// Fix for geocodeDataSource (It doesen't have access to Template.instance())
var templateInstance = null;
//

Template.eventsForm.onCreated(function() {
    this.debounce = null;
    templateInstance = Template.instance();
    console.log('hear');
    this.subscribe('categories');
    this.setCoordinates = function (lat, lng) {
        var instance = Template.instance();
        instance.$('input[name="coordinates.lat"]').val(lat);
        instance.$('input[name="coordinates.lng"]').val(lng);
    };

});

Template.eventsForm.helpers({
    categories: function(){
        return Categories.find({});
    },
    geocodeDataSource: function(query, sync, asyncCallback) {
        var instance = templateInstance;
        if (instance.debounce) {
            Meteor.clearTimeout(instance.debounce);
        }
        const debounceDelay = 500; //wait half a second before triggering search
        instance.debounce = Meteor.setTimeout(function() {
            Meteor.call('getCoords', query, function (error, result) {
                console.info("Query: " + query);
                var mapResultToDisplay = function () {
                    var isCity = function(element, index) {
                        return element.city!=null
                    };
                    return result.filter(isCity).map(function (v) {
                            console.info("Response: " + JSON.stringify(v));
                            var streetName = _.isNull(v.streetName) ? '' : v.streetName + ' ';
                            var streetNumber = _.isNull(v.streetNumber) ? _.isEmpty(streetName) ? '' : ', ' : +v.streetNumber + ', ';
                            var city  = _.isNull(v.city) ? '' : v.city + ', ';
                            var state  = _.isNull(v.state) ? '' : v.state + ', ';
                            return {
                                value: streetName + streetNumber + city + state + v.country,
                                lat: v.latitude,
                                lng: v.longitude
                            };
                        }
                    );
                };

                if (error != undefined) {
                    console.error(error);
                    Events.simpleSchema().namedContext("events-form").addInvalidKeys([{
                        name: "address",
                        type: "offline"
                    }]);
                } else {
                    asyncCallback(mapResultToDisplay());
                }
            });
        }, debounceDelay);
    },
    selectedHandler: function (event, suggestion, datasetName) {
        var coordsDefined = !_.isUndefined(suggestion.lat) && !_.isUndefined(suggestion.lng);
        if (coordsDefined) {
            Template.instance().setCoordinates(suggestion.lat,suggestion.lng);
            AutoForm.validateField('events-form', 'coordinates', false); //remove potential validation error
        } else {
            throw Meteor.Error('cords-undefined', 'Coordinates are empty for the selected location');
        }

    },
    selectedEventDoc: function() { return Events.findOne(Session.get('selected'));},
    isEdit: function() { return Session.get('isEdit') }
});

Template.autoForm.onRendered(function () {
    Meteor.typeahead.inject();

    this.$('input[name=address]').detach().insertBefore('.twitter-typeahead');
    this.$('.twitter-typeahead').find('input[type=text]').remove();
    var copyCoordsFromSelectedEvent = function () {
        if (Session.get('isEdit')) {
            var selectedEvent = Events.findOne(Session.get('selected'));
            if (selectedEvent != null) {
                Template.instance().setCoordinates(selectedEvent.coordinates.lat, selectedEvent.coordinates.lng);
            }
        }
    };
    copyCoordsFromSelectedEvent();
    var fixMaterializeActiveClassTrigger = function() {
        $('input[name=address]').detach().insertBefore('.twitter-typeahead');
        $('.twitter-typeahead').find('input[type=text]').remove();
    };
    //this is a hack, because Typeahead duplicates input and inserts it inside of a new span item which breaks Materialize
    fixMaterializeActiveClassTrigger();
});

Template.eventsForm.onDestroyed(function () {
    var $typeahead = $('.typeahead');
    $typeahead.unbind();
    AutoForm.resetForm('events-form');
    $typeahead.typeahead('destroy');
});
<|endoftext|>


<commit_before>;(function() {

  var localStream;
  var pc;
  var remoteStream;
  var turnReady;

  var xpush;
  var channel;
  var channelNm;
  var userId;

  var localVideo;
  var remoteVideo;

  var CONFIG = {};
  var STATUS = {
    READY: false,
    INIT: false,
    STARTED: false
  };

  var _initProcess = function (type, data){
    console.log('EVENT', type, data);

    if(data.event == 'CONNECTION' && userId == data.U){

      if(!channel){
        channel = xpush.getChannel(channelNm);
      }

      // channel 연결 후!
      if(data.count == 1){ // created
        STATUS.INIT = true;
      }else if(data.count == 2){ // joined

        STATUS.READY = true;
        channel.send('message', 'JOIN');

      }else if(data.count == 0 || data.count > 2){
        console.error('FULL!! & something is wrong.. (_ _); ');

      }

      getUserMedia(CONFIG.constraints, handleUserMedia, handleUserMediaError);

    }

  };

  var XWebRTC = function(_host, _app, _channelName, _userId, _localVideo, _remoteVideo){
    var self = this;

    CONFIG.constraints    = {video: true};
    CONFIG.pc             = {'iceServers': [{'url': 'stun:stun.l.google.com:19302'}]};
    CONFIG.pcConstraints  = {'optional': [{'DtlsSrtpKeyAgreement': true}]};
    CONFIG.sdpConstraints = {'mandatory': {'OfferToReceiveAudio':true,'OfferToReceiveVideo':true }};

    channelNm   = _channelName;
    localVideo  = _localVideo;
    remoteVideo = _remoteVideo;
    userId      = _userId.U;

    xpush = new XPush(_host, _app, _initProcess);

    xpush.createSimpleChannel(_channelName, _userId, function(err, data){
      if(err){
        console.error("CHANNEL CREATE" ,err);
      }
    });

    xpush.on('message',function(ch, name, message){

      console.log('    ---------------- ', ch, name, message);

      if (message === 'MEDIA') {
  	     maybeStart();

      }else if (message === 'JOIN') {
         STATUS.READY = true;

      } else if (message.type === 'offer') {

        console.warn(STATUS);

        if (!STATUS.INIT && !STATUS.STARTED) {
          maybeStart();
        }
        pc.setRemoteDescription(new RTCSessionDescription(message));
        doAnswer();

      } else if (message.type === 'answer' && STATUS.STARTED) {
        pc.setRemoteDescription(new RTCSessionDescription(message));

      } else if (message.type === 'candidate' && STATUS.STARTED) {
        var candidate = new RTCIceCandidate({
          sdpMLineIndex: message.label,
          candidate: message.candidate
        });
        pc.addIceCandidate(candidate);
      }

    });

  };

  var handleUserMedia = function(stream) {
    console.log('Adding local stream.');
    localVideo.src = window.URL.createObjectURL(stream);
    localStream = stream;
    channel.send('message', 'MEDIA');
    if (STATUS.INIT) {
      maybeStart();
    }
  };

  var handleUserMediaError = function(error){
    console.log('getUserMedia error: ', error);
  };

  var maybeStart = function () {
    console.warn(STATUS);
    console.log(!STATUS.STARTED, localStream, STATUS.READY);
    if (!STATUS.STARTED && typeof localStream != 'undefined' && STATUS.READY) {
      createPeerConnection();
      pc.addStream(localStream);
      STATUS.STARTED = true;
      console.log('isInitiator', STATUS.INIT);
      if (STATUS.INIT) {
        doCall();
      }
    }
  };

  window.onbeforeunload = function(e){
  	//sendMessage('bye');
  };

  // ********** P2P Connections *********

  var createPeerConnection = function () {
    try {
      pc = new RTCPeerConnection(null);
      pc.onicecandidate = handleIceCandidate;
      pc.onaddstream    = handleRemoteStreamAdded;
      pc.onremovestream = handleRemoteStreamRemoved;
      console.log('Created RTCPeerConnnection');
    } catch (e) {
      console.log('Failed to create PeerConnection, exception: ' + e.message);
      alert('Cannot create RTCPeerConnection object.');
      return;
    }
  };

  var handleIceCandidate = function (event) {
    console.log('handleIceCandidate event: ', event);
    if (event.candidate) {
      channel.send('message', {
        type:     'candidate',
        label:     event.candidate.sdpMLineIndex,
        id:        event.candidate.sdpMid,
        candidate: event.candidate.candidate});
    } else {
      console.log('End of candidates.');
    }
  };

  var handleRemoteStreamAdded = function (event) {
    console.log('Remote stream added.');
    remoteVideo.src = window.URL.createObjectURL(event.stream);
    remoteStream = event.stream;
  };

  var handleRemoteStreamRemoved = function (event) {
    console.log('Remote stream removed. Event: ', event);
  };

  var handleCreateOfferError = function (event){
    console.log('createOffer() error: ', e);
  };

  var doCall = function () {
    console.log('Sending offer to peer');
    pc.createOffer(setLocalAndSendMessage, handleCreateOfferError);
  };

  var doAnswer = function () {
    console.log('Sending answer to peer.');
    pc.createAnswer(setLocalAndSendMessage, null, CONFIG.sdpConstraints);
  };

  var setLocalAndSendMessage = function (sessionDescription) {
    // Set Opus as the preferred codec in SDP if Opus is present.
    sessionDescription.sdp = preferOpus(sessionDescription.sdp);
    pc.setLocalDescription(sessionDescription);
    console.log('setLocalAndSendMessage sending message' , sessionDescription);
    channel.send('message', sessionDescription);
  };

  ///////////////////////////////////////////

  // Set Opus as the default audio codec if it's present.
  function preferOpus(sdp) {
    var sdpLines = sdp.split('\r\n');
    var mLineIndex;
    // Search for m line.
    for (var i = 0; i < sdpLines.length; i++) {
        if (sdpLines[i].search('m=audio') !== -1) {
          mLineIndex = i;
          break;
        }
    }
    if (mLineIndex === null) {
      return sdp;
    }

    // If Opus is available, set it as the default in m line.
    for (i = 0; i < sdpLines.length; i++) {
      if (sdpLines[i].search('opus/48000') !== -1) {
        var opusPayload = extractSdp(sdpLines[i], /:(\d+) opus\/48000/i);
        if (opusPayload) {
          sdpLines[mLineIndex] = setDefaultCodec(sdpLines[mLineIndex], opusPayload);
        }
        break;
      }
    }

    // Remove CN in m line and sdp.
    sdpLines = removeCN(sdpLines, mLineIndex);

    sdp = sdpLines.join('\r\n');
    return sdp;
  }

  function extractSdp(sdpLine, pattern) {
    var result = sdpLine.match(pattern);
    return result && result.length === 2 ? result[1] : null;
  }

  // Set the selected codec to the first in m line.
  function setDefaultCodec(mLine, payload) {
    var elements = mLine.split(' ');
    var newLine = [];
    var index = 0;
    for (var i = 0; i < elements.length; i++) {
      if (index === 3) { // Format of media starts from the fourth.
        newLine[index++] = payload; // Put target payload to the first.
      }
      if (elements[i] !== payload) {
        newLine[index++] = elements[i];
      }
    }
    return newLine.join(' ');
  }

  // Strip CN from sdp before CN constraints is ready.
  function removeCN(sdpLines, mLineIndex) {
    var mLineElements = sdpLines[mLineIndex].split(' ');
    // Scan from end for the convenience of removing an item.
    for (var i = sdpLines.length-1; i >= 0; i--) {
      var payload = extractSdp(sdpLines[i], /a=rtpmap:(\d+) CN\/\d+/i);
      if (payload) {
        var cnPos = mLineElements.indexOf(payload);
        if (cnPos !== -1) {
          // Remove CN payload from m line.
          mLineElements.splice(cnPos, 1);
        }
        // Remove CN line in sdp
        sdpLines.splice(i, 1);
      }
    }

    sdpLines[mLineIndex] = mLineElements.join(' ');
    return sdpLines;
  }

  XWebRTC.prototype.debug = function(){
    console.log('STATUS', STATUS);
    console.log('CONFIG', CONFIG);
    console.log(xpush);
    console.log(channel);
    console.log(channelNm);
  };

  window.XWebRTC = XWebRTC;

})();
<commit_msg>add audio constraint webrtc<commit_after>;(function() {

  var localStream;
  var pc;
  var remoteStream;
  var turnReady;

  var xpush;
  var channel;
  var channelNm;
  var userId;

  var localVideo;
  var remoteVideo;

  var CONFIG = {};
  var STATUS = {
    READY: false,
    INIT: false,
    STARTED: false
  };

  var _initProcess = function (type, data){
    console.log('EVENT', type, data);

    if(data.event == 'CONNECTION' && userId == data.U){

      if(!channel){
        channel = xpush.getChannel(channelNm);
      }

      // channel 연결 후!
      if(data.count == 1){ // created
        STATUS.INIT = true;
      }else if(data.count == 2){ // joined

        STATUS.READY = true;
        channel.send('message', 'JOIN');

      }else if(data.count == 0 || data.count > 2){
        console.error('FULL!! & something is wrong.. (_ _); ');

      }

      getUserMedia(CONFIG.constraints, handleUserMedia, handleUserMediaError);

    }

  };

  var XWebRTC = function(_host, _app, _channelName, _userId, _localVideo, _remoteVideo){
    var self = this;

    CONFIG.constraints    = {'audio': true, 'video': true};
    CONFIG.pc             = {'iceServers': [{'url': 'stun:stun.l.google.com:19302'}]};
    CONFIG.pcConstraints  = {'optional': [{'DtlsSrtpKeyAgreement': true}]};
    CONFIG.sdpConstraints = {'mandatory': {'OfferToReceiveAudio':true,'OfferToReceiveVideo':true }};

    channelNm   = _channelName;
    localVideo  = _localVideo;
    remoteVideo = _remoteVideo;
    userId      = _userId.U;

    xpush = new XPush(_host, _app, _initProcess);

    xpush.createSimpleChannel(_channelName, _userId, function(err, data){
      if(err){
        console.error("CHANNEL CREATE" ,err);
      }
    });

    xpush.on('message',function(ch, name, message){

      console.log('    ---------------- ', ch, name, message);

      if (message === 'MEDIA') {
  	     maybeStart();

      }else if (message === 'JOIN') {
         STATUS.READY = true;

      } else if (message.type === 'offer') {

        console.warn(STATUS);

        if (!STATUS.INIT && !STATUS.STARTED) {
          maybeStart();
        }
        pc.setRemoteDescription(new RTCSessionDescription(message));
        doAnswer();

      } else if (message.type === 'answer' && STATUS.STARTED) {
        pc.setRemoteDescription(new RTCSessionDescription(message));

      } else if (message.type === 'candidate' && STATUS.STARTED) {
        var candidate = new RTCIceCandidate({
          sdpMLineIndex: message.label,
          candidate: message.candidate
        });
        pc.addIceCandidate(candidate);
      }

    });

  };

  var handleUserMedia = function(stream) {
    console.log('Adding local stream.');
    localVideo.src = window.URL.createObjectURL(stream);
    localStream = stream;
    channel.send('message', 'MEDIA');
    if (STATUS.INIT) {
      maybeStart();
    }
  };

  var handleUserMediaError = function(error){
    console.log('getUserMedia error: ', error);
  };

  var maybeStart = function () {
    console.warn(STATUS);
    console.log(!STATUS.STARTED, localStream, STATUS.READY);
    if (!STATUS.STARTED && typeof localStream != 'undefined' && STATUS.READY) {
      createPeerConnection();
      pc.addStream(localStream);
      STATUS.STARTED = true;
      console.log('isInitiator', STATUS.INIT);
      if (STATUS.INIT) {
        doCall();
      }
    }
  };

  window.onbeforeunload = function(e){
  	//sendMessage('bye');
  };

  // ********** P2P Connections *********

  var createPeerConnection = function () {
    try {
      pc = new RTCPeerConnection(null);
      pc.onicecandidate = handleIceCandidate;
      pc.onaddstream    = handleRemoteStreamAdded;
      pc.onremovestream = handleRemoteStreamRemoved;
      console.log('Created RTCPeerConnnection');
    } catch (e) {
      console.log('Failed to create PeerConnection, exception: ' + e.message);
      alert('Cannot create RTCPeerConnection object.');
      return;
    }
  };

  var handleIceCandidate = function (event) {
    console.log('handleIceCandidate event: ', event);
    if (event.candidate) {
      channel.send('message', {
        type:     'candidate',
        label:     event.candidate.sdpMLineIndex,
        id:        event.candidate.sdpMid,
        candidate: event.candidate.candidate});
    } else {
      console.log('End of candidates.');
    }
  };

  var handleRemoteStreamAdded = function (event) {
    console.log('Remote stream added.');
    remoteVideo.src = window.URL.createObjectURL(event.stream);
    remoteStream = event.stream;
  };

  var handleRemoteStreamRemoved = function (event) {
    console.log('Remote stream removed. Event: ', event);
  };

  var handleCreateOfferError = function (event){
    console.log('createOffer() error: ', e);
  };

  var doCall = function () {
    console.log('Sending offer to peer');
    pc.createOffer(setLocalAndSendMessage, handleCreateOfferError);
  };

  var doAnswer = function () {
    console.log('Sending answer to peer.');
    pc.createAnswer(setLocalAndSendMessage, null, CONFIG.sdpConstraints);
  };

  var setLocalAndSendMessage = function (sessionDescription) {
    // Set Opus as the preferred codec in SDP if Opus is present.
    sessionDescription.sdp = preferOpus(sessionDescription.sdp);
    pc.setLocalDescription(sessionDescription);
    console.log('setLocalAndSendMessage sending message' , sessionDescription);
    channel.send('message', sessionDescription);
  };

  ///////////////////////////////////////////

  // Set Opus as the default audio codec if it's present.
  function preferOpus(sdp) {
    var sdpLines = sdp.split('\r\n');
    var mLineIndex;
    // Search for m line.
    for (var i = 0; i < sdpLines.length; i++) {
        if (sdpLines[i].search('m=audio') !== -1) {
          mLineIndex = i;
          break;
        }
    }
    if (mLineIndex === null) {
      return sdp;
    }

    // If Opus is available, set it as the default in m line.
    for (i = 0; i < sdpLines.length; i++) {
      if (sdpLines[i].search('opus/48000') !== -1) {
        var opusPayload = extractSdp(sdpLines[i], /:(\d+) opus\/48000/i);
        if (opusPayload) {
          sdpLines[mLineIndex] = setDefaultCodec(sdpLines[mLineIndex], opusPayload);
        }
        break;
      }
    }

    // Remove CN in m line and sdp.
    sdpLines = removeCN(sdpLines, mLineIndex);

    sdp = sdpLines.join('\r\n');
    return sdp;
  }

  function extractSdp(sdpLine, pattern) {
    var result = sdpLine.match(pattern);
    return result && result.length === 2 ? result[1] : null;
  }

  // Set the selected codec to the first in m line.
  function setDefaultCodec(mLine, payload) {
    var elements = mLine.split(' ');
    var newLine = [];
    var index = 0;
    for (var i = 0; i < elements.length; i++) {
      if (index === 3) { // Format of media starts from the fourth.
        newLine[index++] = payload; // Put target payload to the first.
      }
      if (elements[i] !== payload) {
        newLine[index++] = elements[i];
      }
    }
    return newLine.join(' ');
  }

  // Strip CN from sdp before CN constraints is ready.
  function removeCN(sdpLines, mLineIndex) {
    var mLineElements = sdpLines[mLineIndex].split(' ');
    // Scan from end for the convenience of removing an item.
    for (var i = sdpLines.length-1; i >= 0; i--) {
      var payload = extractSdp(sdpLines[i], /a=rtpmap:(\d+) CN\/\d+/i);
      if (payload) {
        var cnPos = mLineElements.indexOf(payload);
        if (cnPos !== -1) {
          // Remove CN payload from m line.
          mLineElements.splice(cnPos, 1);
        }
        // Remove CN line in sdp
        sdpLines.splice(i, 1);
      }
    }

    sdpLines[mLineIndex] = mLineElements.join(' ');
    return sdpLines;
  }

  XWebRTC.prototype.debug = function(){
    console.log('STATUS', STATUS);
    console.log('CONFIG', CONFIG);
    console.log(xpush);
    console.log(channel);
    console.log(channelNm);
  };

  window.XWebRTC = XWebRTC;

})();
<|endoftext|>


<commit_before>var registerShader = require('../core/shader').registerShader;

/**
 * Multi-channel signed distance field.
 * Used by text component.
 */
module.exports.Shader = registerShader('msdf', {
  schema: {
    alphaTest: {type: 'number', is: 'uniform', default: 0.5},
    color: {type: 'color', is: 'uniform', default: 'white'},
    map: {type: 'map', is: 'uniform'},
    negate: {type: 'boolean', is: 'uniform', default: true},
    opacity: {type: 'number', is: 'uniform', default: 1.0}
  },

  raw: true,

  vertexShader: [
    'attribute vec2 uv;',
    'attribute vec3 position;',
    'uniform mat4 projectionMatrix;',
    'uniform mat4 modelViewMatrix;',
    'varying vec2 vUV;',
    'void main(void) {',
    '  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
    '  vUV = uv;',
    '}'
  ].join('\n'),

  fragmentShader: [
    '#ifdef GL_OES_standard_derivatives',
    '#extension GL_OES_standard_derivatives: enable',
    '#endif',

    'precision highp float;',
    'uniform bool negate;',
    'uniform float alphaTest;',
    'uniform float opacity;',
    'uniform sampler2D map;',
    'uniform vec3 color;',
    'varying vec2 vUV;',

    'float median(float r, float g, float b) {',
    '  return max(min(r, g), min(max(r, g), b));',
    '}',

    // FIXME: Experimentally determined constants.
    '#define BIG_ENOUGH 0.001',
    '#define MODIFIED_ALPHATEST (0.02 * isBigEnough / BIG_ENOUGH)',

    'void main() {',
    '  vec3 sample = texture2D(map, vUV).rgb;',
    '  if (negate) { sample = 1.0 - sample; }',

    '  float sigDist = median(sample.r, sample.g, sample.b) - 0.5;',
    '  float alpha = clamp(sigDist / fwidth(sigDist) + 0.5, 0.0, 1.0);',
    '  float dscale = 0.353505;',
    '  vec2 duv = dscale * (dFdx(vUV) + dFdy(vUV));',
    '  float isBigEnough = max(abs(duv.x), abs(duv.y));',

    // When texel is too small, blend raw alpha value rather than supersampling.
    // FIXME: Experimentally determined constant.
    '  // Do modified alpha test.',
    '  if (isBigEnough > BIG_ENOUGH) {',
    '    float ratio = BIG_ENOUGH / isBigEnough;',
    '    alpha = ratio * alpha + (1.0 - ratio) * (sigDist + 0.5);',
    '  }',

    '  // Do modified alpha test.',
    '  if (alpha < alphaTest * MODIFIED_ALPHATEST) { discard; return; }',
    '  gl_FragColor = vec4(color.xyz, alpha * opacity);',
    '}'
  ].join('\n')
});
<commit_msg>fix for webgl2 sample is a reserved word (#4511)<commit_after>var registerShader = require('../core/shader').registerShader;

/**
 * Multi-channel signed distance field.
 * Used by text component.
 */
module.exports.Shader = registerShader('msdf', {
  schema: {
    alphaTest: {type: 'number', is: 'uniform', default: 0.5},
    color: {type: 'color', is: 'uniform', default: 'white'},
    map: {type: 'map', is: 'uniform'},
    negate: {type: 'boolean', is: 'uniform', default: true},
    opacity: {type: 'number', is: 'uniform', default: 1.0}
  },

  raw: true,

  vertexShader: [
    'attribute vec2 uv;',
    'attribute vec3 position;',
    'uniform mat4 projectionMatrix;',
    'uniform mat4 modelViewMatrix;',
    'varying vec2 vUV;',
    'void main(void) {',
    '  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
    '  vUV = uv;',
    '}'
  ].join('\n'),

  fragmentShader: [
    '#ifdef GL_OES_standard_derivatives',
    '#extension GL_OES_standard_derivatives: enable',
    '#endif',

    'precision highp float;',
    'uniform bool negate;',
    'uniform float alphaTest;',
    'uniform float opacity;',
    'uniform sampler2D map;',
    'uniform vec3 color;',
    'varying vec2 vUV;',

    'float median(float r, float g, float b) {',
    '  return max(min(r, g), min(max(r, g), b));',
    '}',

    // FIXME: Experimentally determined constants.
    '#define BIG_ENOUGH 0.001',
    '#define MODIFIED_ALPHATEST (0.02 * isBigEnough / BIG_ENOUGH)',

    'void main() {',
    '  vec3 sampleColor = texture2D(map, vUV).rgb;',
    '  if (negate) { sampleColor = 1.0 - sampleColor; }',

    '  float sigDist = median(sampleColor.r, sampleColor.g, sampleColor.b) - 0.5;',
    '  float alpha = clamp(sigDist / fwidth(sigDist) + 0.5, 0.0, 1.0);',
    '  float dscale = 0.353505;',
    '  vec2 duv = dscale * (dFdx(vUV) + dFdy(vUV));',
    '  float isBigEnough = max(abs(duv.x), abs(duv.y));',

    // When texel is too small, blend raw alpha value rather than supersampling.
    // FIXME: Experimentally determined constant.
    '  // Do modified alpha test.',
    '  if (isBigEnough > BIG_ENOUGH) {',
    '    float ratio = BIG_ENOUGH / isBigEnough;',
    '    alpha = ratio * alpha + (1.0 - ratio) * (sigDist + 0.5);',
    '  }',

    '  // Do modified alpha test.',
    '  if (alpha < alphaTest * MODIFIED_ALPHATEST) { discard; return; }',
    '  gl_FragColor = vec4(color.xyz, alpha * opacity);',
    '}'
  ].join('\n')
});
<|endoftext|>


<commit_before>/* Copyright (c) 2012-2013 The TagSpaces Authors. All rights reserved.
 * Use of this source code is governed by a AGPL3 license that
 * can be found in the LICENSE file. */
define(function(require, exports, module) {
"use strict";

	// Activating browser specific exports modul
	console.log("Loading web.js..");

    var TSCORE = require("tscore");
	var TSPOSTIO = require("tspostioapi");

    require("webdavlib");

    var davClient;

	function connectDav() {
        console.log("Connecting webdav...");
        davClient = new nl.sara.webdav.Client("127.0.0.1");
	}

	window.setTimeout(connectDav(), 2000);

    function listDirectory(dirPath) {
        console.log("Listing directory: "+dirPath);

        dirPath = dirPath + "/";

        davClient.propfind(
            dirPath,
            function( status, data ) {
                console.log("Dirlist Status:  "+status);
                console.log("Dirlist Content: "+JSON.stringify(data._responses));
                var anotatedDirList = [],
                    dirList = data._responses,
                    fileName,
                    isDir,
                    filesize,
                    lmdt;

                for (var entry in dirList) {
                    var path = dirList[entry].href;
                    if(dirPath !== path) {
                        isDir = false,
                        filesize = undefined;
                        lmdt = undefined;
                        //console.log(dirList[entry]._namespaces["DAV:"]);
                        if (typeof dirList[entry]._namespaces["DAV:"].getcontentlength === 'undefined') {
                            isDir = true;
                        } else {
                            filesize = dirList[entry]._namespaces["DAV:"].getcontentlength;
                            lmdt = data._responses[entry]._namespaces["DAV:"].getlastmodified._xmlvalue[0].data;
                        }
                        fileName = getNameForPath(path);
                        anotatedDirList.push({
                            "name": fileName,
                            "isFile": !isDir,
                            "size": filesize,
                            "lmdt": lmdt,
                            "path": decodeURI(path)
                        });
                    }
                }
                TSPOSTIO.listDirectory(anotatedDirList);
            },
            1 //1 , davClient.INFINITY
        );
    }

    function getNameForPath(path) {
        if(path.lastIndexOf("/") == path.length-1) {
            path = path.substring(0,path.lastIndexOf("/"));
        }
        var encodedName = path.substring(path.lastIndexOf("/")+1, path.length);
        return decodeURI(encodedName);
    }

    function isDirectory(path) {
        return path.lastIndexOf("/") == path.length-1;
    }

    var createDirectoryIndex = function(dirPath) {
        console.log("Creating index for directory: "+dirPath);
        TSCORE.showLoadingAnimation();

        var directoryIndex = [];
        TSPOSTIO.createDirectoryIndex(directoryIndex);
    };

    var createDirectoryTree = function(dirPath) {
        console.log("Creating directory index for: "+dirPath);
        TSCORE.showLoadingAnimation();

        var directoyTree = [];
        //console.log(JSON.stringify(directoyTree));
        TSPOSTIO.createDirectoryTree(directoyTree);
    };

	var createDirectory = function(dirPath) {
	    console.log("Creating directory: "+dirPath);
        davClient.mkcol(
            dirPath,
            function( status, data, headers ) {
                console.log("Directory Creation Status/Content/Headers:  "+status+" / "+data+" / "+headers);
                TSPOSTIO.createDirectory(dirPath);
            }
        );
	};

    var renameFile = function(filePath, newFilePath) {
        console.log("Renaming file: "+filePath+" to "+newFilePath);
        davClient.move(
            filePath,
            function( status, data, headers ) {
                console.log("Rename File Status/Content/Headers:  "+status+" / "+data+" / "+headers);
                TSPOSTIO.renameFile(filePath, newFilePath);
            },
            newFilePath,
            davClient.FAIL_ON_OVERWRITE
            //,customHeaders
        );
    };

	var loadTextFile = function(filePath) {
		console.log("Loading file: "+filePath);
        davClient.get(
            filePath,
            function( status, data, headers ) {
                console.log("Loading File Status/Content/Headers:  "+status+" / "+data+" / "+headers);
                TSPOSTIO.loadTextFile(data);
            }
            //,customHeaders
        );
        //TODO Perform file locking and unlocking
	};

	var saveTextFile = function(filePath,content,overWrite) {
		console.log("Saving file: "+filePath+" content: "+content);

        var isNewFile; // = !pathUtils.existsSync(filePath);
        davClient.put(
            filePath,
            function( status, data, headers ) {
                console.log("Creating File Status/Content/Headers:  "+status+" / "+data+" / "+headers);
            },
            content
        );
        TSPOSTIO.saveTextFile(filePath, isNewFile);
	};

	var deleteElement = function(path) {
		console.log("Deleting: "+path);
        davClient.remove(
            path,
            function( status, data, headers ) {
                console.log("Directory/File Deletion Status/Content/Headers:  "+status+" / "+data+" / "+headers);
                TSPOSTIO.deleteElement(path);
            }
        );
	};

    var checkAccessFileURLAllowed = function() {
        console.log("checkAccessFileURLAllowed function not relevant for webdav..");
    };

    var checkNewVersion = function() {
        console.log("Checking for new version not relevant fot the webdav version");
    };

    var selectDirectory = function() {
        console.log("selectDirectory function not relevant for webdav..");
    };

    var openDirectory = function(dirPath) {
        console.log("openDirectory function not relevant for webdav..");
    };

    var openFile = function(filePath) {
        console.log("openFile function not relevant for webdav..");
    };

    var selectFile = function() {
        console.log("selectFile function not relevant for webdav..");
    };

    var openExtensionsDirectory = function() {
        console.log("openExtensionsDirectory function not relevant for webdav..");
    };

    var getFileProperties = function(filePath) {
        davClient.propfind( filePath, function( status, data ) {
                console.log("Properties Status / Content: "+status+" / "+JSON.stringify(data._responses));
                var fileProperties = {};
                for (var entry in data._responses) {
                    fileProperties.path = filePath;
                    fileProperties.size = data._responses[entry]._namespaces["DAV:"].getcontentlength;
                    fileProperties.lmdt = data._responses[entry]._namespaces["DAV:"].getlastmodified._xmlvalue[0].data;
                }
                TSPOSTIO.getFileProperties(fileProperties);
            },1
        );
    };

	exports.createDirectory 			= createDirectory;
	exports.renameFile 					= renameFile;
	exports.loadTextFile 				= loadTextFile;
	exports.saveTextFile 				= saveTextFile;
	exports.listDirectory 				= listDirectory;
	exports.deleteElement 				= deleteElement;
    exports.createDirectoryIndex 		= createDirectoryIndex;
    exports.createDirectoryTree 		= createDirectoryTree;
	exports.selectDirectory 			= selectDirectory;
	exports.openDirectory				= openDirectory;
    exports.openFile                    = openFile;
	exports.selectFile 					= selectFile;
	exports.openExtensionsDirectory 	= openExtensionsDirectory;
	exports.checkAccessFileURLAllowed 	= checkAccessFileURLAllowed;
	exports.checkNewVersion 			= checkNewVersion;
    exports.getFileProperties           = getFileProperties;
});<commit_msg>removing hardcoded ip<commit_after>/* Copyright (c) 2012-2013 The TagSpaces Authors. All rights reserved.
 * Use of this source code is governed by a AGPL3 license that
 * can be found in the LICENSE file. */
define(function(require, exports, module) {
"use strict";

	// Activating browser specific exports modul
	console.log("Loading web.js..");

    var TSCORE = require("tscore");
	var TSPOSTIO = require("tspostioapi");

    require("webdavlib");

    var davClient;

	function connectDav() {
        console.log("Connecting webdav...");
        // TODO handle port and https
        davClient = new nl.sara.webdav.Client(location.host);
	}

	window.setTimeout(connectDav(), 2000);

    function listDirectory(dirPath) {
        console.log("Listing directory: "+dirPath);

        dirPath = dirPath + "/";

        davClient.propfind(
            dirPath,
            function( status, data ) {
                console.log("Dirlist Status:  "+status);
                console.log("Dirlist Content: "+JSON.stringify(data._responses));
                var anotatedDirList = [],
                    dirList = data._responses,
                    fileName,
                    isDir,
                    filesize,
                    lmdt;

                for (var entry in dirList) {
                    var path = dirList[entry].href;
                    if(dirPath !== path) {
                        isDir = false,
                        filesize = undefined;
                        lmdt = undefined;
                        //console.log(dirList[entry]._namespaces["DAV:"]);
                        if (typeof dirList[entry]._namespaces["DAV:"].getcontentlength === 'undefined') {
                            isDir = true;
                        } else {
                            filesize = dirList[entry]._namespaces["DAV:"].getcontentlength;
                            lmdt = data._responses[entry]._namespaces["DAV:"].getlastmodified._xmlvalue[0].data;
                        }
                        fileName = getNameForPath(path);
                        anotatedDirList.push({
                            "name": fileName,
                            "isFile": !isDir,
                            "size": filesize,
                            "lmdt": lmdt,
                            "path": decodeURI(path)
                        });
                    }
                }
                TSPOSTIO.listDirectory(anotatedDirList);
            },
            1 //1 , davClient.INFINITY
        );
    }

    function getNameForPath(path) {
        if(path.lastIndexOf("/") == path.length-1) {
            path = path.substring(0,path.lastIndexOf("/"));
        }
        var encodedName = path.substring(path.lastIndexOf("/")+1, path.length);
        return decodeURI(encodedName);
    }

    function isDirectory(path) {
        return path.lastIndexOf("/") == path.length-1;
    }

    var createDirectoryIndex = function(dirPath) {
        console.log("Creating index for directory: "+dirPath);
        TSCORE.showLoadingAnimation();

        var directoryIndex = [];
        TSPOSTIO.createDirectoryIndex(directoryIndex);
    };

    var createDirectoryTree = function(dirPath) {
        console.log("Creating directory index for: "+dirPath);
        TSCORE.showLoadingAnimation();

        var directoyTree = [];
        //console.log(JSON.stringify(directoyTree));
        TSPOSTIO.createDirectoryTree(directoyTree);
    };

	var createDirectory = function(dirPath) {
	    console.log("Creating directory: "+dirPath);
        davClient.mkcol(
            dirPath,
            function( status, data, headers ) {
                console.log("Directory Creation Status/Content/Headers:  "+status+" / "+data+" / "+headers);
                TSPOSTIO.createDirectory(dirPath);
            }
        );
	};

    var renameFile = function(filePath, newFilePath) {
        console.log("Renaming file: "+filePath+" to "+newFilePath);
        davClient.move(
            filePath,
            function( status, data, headers ) {
                console.log("Rename File Status/Content/Headers:  "+status+" / "+data+" / "+headers);
                TSPOSTIO.renameFile(filePath, newFilePath);
            },
            newFilePath,
            davClient.FAIL_ON_OVERWRITE
            //,customHeaders
        );
    };

	var loadTextFile = function(filePath) {
		console.log("Loading file: "+filePath);
        davClient.get(
            filePath,
            function( status, data, headers ) {
                console.log("Loading File Status/Content/Headers:  "+status+" / "+data+" / "+headers);
                TSPOSTIO.loadTextFile(data);
            }
            //,customHeaders
        );
        //TODO Perform file locking and unlocking
	};

	var saveTextFile = function(filePath,content,overWrite) {
		console.log("Saving file: "+filePath+" content: "+content);

        var isNewFile; // = !pathUtils.existsSync(filePath);
        davClient.put(
            filePath,
            function( status, data, headers ) {
                console.log("Creating File Status/Content/Headers:  "+status+" / "+data+" / "+headers);
            },
            content
        );
        TSPOSTIO.saveTextFile(filePath, isNewFile);
	};

	var deleteElement = function(path) {
		console.log("Deleting: "+path);
        davClient.remove(
            path,
            function( status, data, headers ) {
                console.log("Directory/File Deletion Status/Content/Headers:  "+status+" / "+data+" / "+headers);
                TSPOSTIO.deleteElement(path);
            }
        );
	};

    var checkAccessFileURLAllowed = function() {
        console.log("checkAccessFileURLAllowed function not relevant for webdav..");
    };

    var checkNewVersion = function() {
        console.log("Checking for new version not relevant fot the webdav version");
    };

    var selectDirectory = function() {
        console.log("selectDirectory function not relevant for webdav..");
    };

    var openDirectory = function(dirPath) {
        console.log("openDirectory function not relevant for webdav..");
    };

    var openFile = function(filePath) {
        console.log("openFile function not relevant for webdav..");
    };

    var selectFile = function() {
        console.log("selectFile function not relevant for webdav..");
    };

    var openExtensionsDirectory = function() {
        console.log("openExtensionsDirectory function not relevant for webdav..");
    };

    var getFileProperties = function(filePath) {
        davClient.propfind( filePath, function( status, data ) {
                console.log("Properties Status / Content: "+status+" / "+JSON.stringify(data._responses));
                var fileProperties = {};
                for (var entry in data._responses) {
                    fileProperties.path = filePath;
                    fileProperties.size = data._responses[entry]._namespaces["DAV:"].getcontentlength;
                    fileProperties.lmdt = data._responses[entry]._namespaces["DAV:"].getlastmodified._xmlvalue[0].data;
                }
                TSPOSTIO.getFileProperties(fileProperties);
            },1
        );
    };

	exports.createDirectory 			= createDirectory;
	exports.renameFile 					= renameFile;
	exports.loadTextFile 				= loadTextFile;
	exports.saveTextFile 				= saveTextFile;
	exports.listDirectory 				= listDirectory;
	exports.deleteElement 				= deleteElement;
    exports.createDirectoryIndex 		= createDirectoryIndex;
    exports.createDirectoryTree 		= createDirectoryTree;
	exports.selectDirectory 			= selectDirectory;
	exports.openDirectory				= openDirectory;
    exports.openFile                    = openFile;
	exports.selectFile 					= selectFile;
	exports.openExtensionsDirectory 	= openExtensionsDirectory;
	exports.checkAccessFileURLAllowed 	= checkAccessFileURLAllowed;
	exports.checkNewVersion 			= checkNewVersion;
    exports.getFileProperties           = getFileProperties;
});<|endoftext|>