<commit_before>const {i18n, utils, React} = Serverboards
const {Tip, GenericForm, MarkdownPreview} = Serverboards.Components
import {get_source_type, get_destination_type} from '../utils'

const TIMES = [
  "01:00", "01:15", "01:30", "01:45",  "02:00", "02:15", "02:30", "02:45",
  "03:00", "03:15", "03:30", "03:45",  "04:00", "04:15", "04:30", "04:45",
  "05:00", "05:15", "05:30", "05:45",  "06:00", "06:15", "06:30", "06:45",

  "07:00", "07:15", "07:30", "07:45",  "08:00", "08:15", "08:30", "08:45",
  "09:00", "09:15", "09:30", "09:45",  "10:00", "10:15", "10:30", "10:45",
  "11:00", "11:15", "11:30", "11:45",  "12:00", "12:15", "12:30", "12:45",

  "13:00", "13:15", "13:30", "13:45",  "14:00", "14:15", "14:30", "14:45",
  "15:00", "15:15", "15:30", "15:45",  "16:00", "16:15", "16:30", "16:45",
  "17:00", "17:15", "17:30", "17:45",  "18:00", "18:15", "18:30", "18:45",

  "19:00", "19:15", "19:30", "19:45",  "20:00", "20:15", "20:30", "20:45",
  "21:00", "21:15", "21:30", "21:45",  "22:00", "22:15", "22:30", "22:45",
  "23:00", "23:15", "23:30", "23:45",  "00:00", "00:15", "00:30", "00:45",
]

class DayLabel extends React.Component{
  componentDidMount(){
    let self=this
    $(this.refs.toggle).checkbox({
      onChecked(){ self.props.onChange(true) },
      onUnchecked(){ self.props.onChange(false) }
    })
  }
  render(){
    return (

        {this.props.label}

          <input type="checkbox" defaultChecked={this.props.defaultChecked}/>

    )
  }
}

class AddBackup extends React.Component{
  constructor(props){
    super(props)
    this.state = {
      days: [],
      source: props.backup.source.config,
      destination: props.backup.destination.config,
      source_form: undefined,
      destination_form: undefined,
      source_description: undefined,
      destination_description: undefined
    }
  }
  toggleDay(n, on){
    let days = this.state.days
    if (on){
      days=days.concat(n)
    }
    else{
      days=days.filter( d => d!=n )
    }
    this.setState({days})
  }
  componentDidMount(){
    $(this.refs.sources).dropdown()
    $(this.refs.destination).dropdown()
    $(this.refs.time).dropdown()

    if (this.props.backup.source)
      this.handleSetSource(this.props.backup.source.component, this.props.backup.source.config)
    if (this.props.backup.destination)
      this.handleSetDestination(this.props.backup.destination.component, this.props.backup.destination.config)
  }
  prepare_backup(){
    return utils.merge( this.props.backup || {}, {
      name: this.refs.name.value,
      description: this.refs.description.value,
      source: {
        component: this.refs.sources.value,
        config: this.state.source,
      },
      destination: {
        component: this.refs.destination.value,
        config: this.state.destination,
      },
      schedule:{
        days: this.state.days,
        time: this.refs.time.value
      }
    })
  }
  handleAddBackup(){
    const backup = this.prepare_backup()

    console.log("Create backup %o", backup)
    this.props.onAddBackup(backup)
  }
  handleUpdateBackup(){
    const backup = this.prepare_backup()

    console.log("Update backup %o", backup)
    this.props.onUpdateBackup(backup)
  }
  handleSetSource(id, data){
    console.log("Set source %s", id, data)
    get_source_type(id)
      .then( s => {
        this.setState({
            source_form: s.extra.params,
            source_description: s.description
          })
        if (data)
          this.setState({source: data})
      }).catch( () => this.setState({source_form: [], source_description: ""}) )
  }
  handleSetDestination(id, data){
    console.log("Set destination %s", id, data)
    get_destination_type(id)
      .then( s => {
        this.setState({
          destination_form: s.extra.params,
          destination_description: s.description
        })
        if (data)
          this.setState({destination: data})
      }).catch( () => this.setState({destination_form: [], destination_description: ""}) )
  }
  render(){
    const props=this.props
    const backup = props.backup || { schedule: { days: [], time: "03:00"} }
    return (

{i18n("Create a new backup.")}

            {i18n("Name of this backup")}
            <input
              className="ui text input" type="text" ref="name"
              placeholder={i18n("Memorable backup name")}
              defaultValue={backup.name}
              />

            {i18n("Source")}
            <select ref="sources" defaultValue={backup.source.component} onChange={(ev) => this.handleSetSource(ev.target.value)}>
                <option>{i18n("Select a source type")}</option>
              {props.sources.map( s => (
                <option key={s.id} value={s.id}>{s.name}</option>
              ))}
            </select>

          {this.state.source_form && (

                <MarkdownPreview value={this.state.source_description}/>

              <GenericForm
                fields={this.state.source_form}
                data={this.state.source}
                updateForm={(source) => this.setState({source})}
                />

          )}

            {i18n("Destination")}
            <select ref="destination" defaultValue={backup.destination.component} onChange={(ev) => this.handleSetDestination(ev.target.value)}>
              <option>{i18n("Select destination type")}</option>
              {props.destinations.map( s => (
                <option key={s.id} value={s.id}>{s.name}</option>
              ))}
            </select>

          {this.state.destination_form && (

                <MarkdownPreview value={this.state.destination_description}/>

              <GenericForm
                fields={this.state.destination_form}
                data={this.state.destination}
                updateForm={(destination) => this.setState({destination})}
                />

          )}

            {i18n("Schedule")}

              <DayLabel label={i18n("Monday")} defaultChecked={backup.schedule.days.includes(1)} onChange={(onoff) => this.toggleDay(1, onoff)}/>
              <DayLabel label={i18n("Tuesday")} defaultChecked={backup.schedule.days.includes(2)} onChange={(onoff) => this.toggleDay(2, onoff)}/>
              <DayLabel label={i18n("Wednesday")} defaultChecked={backup.schedule.days.includes(3)} onChange={(onoff) => this.toggleDay(3, onoff)}/>
              <DayLabel label={i18n("Thursday")} defaultChecked={backup.schedule.days.includes(4)} onChange={(onoff) => this.toggleDay(4, onoff)}/>
              <DayLabel label={i18n("Friday")} defaultChecked={backup.schedule.days.includes(5)} onChange={(onoff) => this.toggleDay(5, onoff)}/>
              <DayLabel label={i18n("Saturday")} defaultChecked={backup.schedule.days.includes(6)} onChange={(onoff) => this.toggleDay(6, onoff)}/>
              <DayLabel label={i18n("Sunday")} defaultChecked={backup.schedule.days.includes(7)} onChange={(onoff) => this.toggleDay(7, onoff)}/>

            {i18n("Time")}
            <select ref="time" defaultValue={backup.schedule.time || "03:00"}>
              {TIMES.map( t => (
                <option key={t} value={t}>{t}</option>
              ))}
            </select>

            {i18n("Description and comments")}
            <textarea
              ref="description" className="ui text input" type="text"
              placeholder={i18n("Description and random notes about the backup and its history.")}
              defaultValue={backup.description}
              />

            { props.onAddBackup ? (
              <button className="ui button teal" onClick={this.handleAddBackup.bind(this)}>{i18n("Create backup")}</button>
            ) : (
              <button className="ui button teal" onClick={this.handleUpdateBackup.bind(this)}>{i18n("Update backup")}</button>
            )}

    )
  }
}

export default AddBackup
<commit_msg>Can scroll on backup editing<commit_after>const {i18n, utils, React} = Serverboards
const {Tip, GenericForm, MarkdownPreview} = Serverboards.Components
import {get_source_type, get_destination_type} from '../utils'

const TIMES = [
  "01:00", "01:15", "01:30", "01:45",  "02:00", "02:15", "02:30", "02:45",
  "03:00", "03:15", "03:30", "03:45",  "04:00", "04:15", "04:30", "04:45",
  "05:00", "05:15", "05:30", "05:45",  "06:00", "06:15", "06:30", "06:45",

  "07:00", "07:15", "07:30", "07:45",  "08:00", "08:15", "08:30", "08:45",
  "09:00", "09:15", "09:30", "09:45",  "10:00", "10:15", "10:30", "10:45",
  "11:00", "11:15", "11:30", "11:45",  "12:00", "12:15", "12:30", "12:45",

  "13:00", "13:15", "13:30", "13:45",  "14:00", "14:15", "14:30", "14:45",
  "15:00", "15:15", "15:30", "15:45",  "16:00", "16:15", "16:30", "16:45",
  "17:00", "17:15", "17:30", "17:45",  "18:00", "18:15", "18:30", "18:45",

  "19:00", "19:15", "19:30", "19:45",  "20:00", "20:15", "20:30", "20:45",
  "21:00", "21:15", "21:30", "21:45",  "22:00", "22:15", "22:30", "22:45",
  "23:00", "23:15", "23:30", "23:45",  "00:00", "00:15", "00:30", "00:45",
]

class DayLabel extends React.Component{
  componentDidMount(){
    let self=this
    $(this.refs.toggle).checkbox({
      onChecked(){ self.props.onChange(true) },
      onUnchecked(){ self.props.onChange(false) }
    })
  }
  render(){
    return (

        {this.props.label}

          <input type="checkbox" defaultChecked={this.props.defaultChecked}/>

    )
  }
}

class AddBackup extends React.Component{
  constructor(props){
    super(props)
    this.state = {
      days: [],
      source: props.backup.source.config,
      destination: props.backup.destination.config,
      source_form: undefined,
      destination_form: undefined,
      source_description: undefined,
      destination_description: undefined
    }
  }
  toggleDay(n, on){
    let days = this.state.days
    if (on){
      days=days.concat(n)
    }
    else{
      days=days.filter( d => d!=n )
    }
    this.setState({days})
  }
  componentDidMount(){
    $(this.refs.sources).dropdown()
    $(this.refs.destination).dropdown()
    $(this.refs.time).dropdown()

    if (this.props.backup.source)
      this.handleSetSource(this.props.backup.source.component, this.props.backup.source.config)
    if (this.props.backup.destination)
      this.handleSetDestination(this.props.backup.destination.component, this.props.backup.destination.config)
  }
  prepare_backup(){
    return utils.merge( this.props.backup || {}, {
      name: this.refs.name.value,
      description: this.refs.description.value,
      source: {
        component: this.refs.sources.value,
        config: this.state.source,
      },
      destination: {
        component: this.refs.destination.value,
        config: this.state.destination,
      },
      schedule:{
        days: this.state.days,
        time: this.refs.time.value
      }
    })
  }
  handleAddBackup(){
    const backup = this.prepare_backup()

    console.log("Create backup %o", backup)
    this.props.onAddBackup(backup)
  }
  handleUpdateBackup(){
    const backup = this.prepare_backup()

    console.log("Update backup %o", backup)
    this.props.onUpdateBackup(backup)
  }
  handleSetSource(id, data){
    console.log("Set source %s", id, data)
    get_source_type(id)
      .then( s => {
        this.setState({
            source_form: s.extra.params,
            source_description: s.description
          })
        if (data)
          this.setState({source: data})
      }).catch( () => this.setState({source_form: [], source_description: ""}) )
  }
  handleSetDestination(id, data){
    console.log("Set destination %s", id, data)
    get_destination_type(id)
      .then( s => {
        this.setState({
          destination_form: s.extra.params,
          destination_description: s.description
        })
        if (data)
          this.setState({destination: data})
      }).catch( () => this.setState({destination_form: [], destination_description: ""}) )
  }
  render(){
    const props=this.props
    const backup = props.backup || { schedule: { days: [], time: "03:00"} }
    return (

{i18n("Create a new backup.")}

            {i18n("Name of this backup")}
            <input
              className="ui text input" type="text" ref="name"
              placeholder={i18n("Memorable backup name")}
              defaultValue={backup.name}
              />

            {i18n("Source")}
            <select ref="sources" defaultValue={backup.source.component} onChange={(ev) => this.handleSetSource(ev.target.value)}>
                <option>{i18n("Select a source type")}</option>
              {props.sources.map( s => (
                <option key={s.id} value={s.id}>{s.name}</option>
              ))}
            </select>

          {this.state.source_form && (

                <MarkdownPreview value={this.state.source_description}/>

              <GenericForm
                fields={this.state.source_form}
                data={this.state.source}
                updateForm={(source) => this.setState({source})}
                />

          )}

            {i18n("Destination")}
            <select ref="destination" defaultValue={backup.destination.component} onChange={(ev) => this.handleSetDestination(ev.target.value)}>
              <option>{i18n("Select destination type")}</option>
              {props.destinations.map( s => (
                <option key={s.id} value={s.id}>{s.name}</option>
              ))}
            </select>

          {this.state.destination_form && (

                <MarkdownPreview value={this.state.destination_description}/>

              <GenericForm
                fields={this.state.destination_form}
                data={this.state.destination}
                updateForm={(destination) => this.setState({destination})}
                />

          )}

            {i18n("Schedule")}

              <DayLabel label={i18n("Monday")} defaultChecked={backup.schedule.days.includes(1)} onChange={(onoff) => this.toggleDay(1, onoff)}/>
              <DayLabel label={i18n("Tuesday")} defaultChecked={backup.schedule.days.includes(2)} onChange={(onoff) => this.toggleDay(2, onoff)}/>
              <DayLabel label={i18n("Wednesday")} defaultChecked={backup.schedule.days.includes(3)} onChange={(onoff) => this.toggleDay(3, onoff)}/>
              <DayLabel label={i18n("Thursday")} defaultChecked={backup.schedule.days.includes(4)} onChange={(onoff) => this.toggleDay(4, onoff)}/>
              <DayLabel label={i18n("Friday")} defaultChecked={backup.schedule.days.includes(5)} onChange={(onoff) => this.toggleDay(5, onoff)}/>
              <DayLabel label={i18n("Saturday")} defaultChecked={backup.schedule.days.includes(6)} onChange={(onoff) => this.toggleDay(6, onoff)}/>
              <DayLabel label={i18n("Sunday")} defaultChecked={backup.schedule.days.includes(7)} onChange={(onoff) => this.toggleDay(7, onoff)}/>

            {i18n("Time")}
            <select ref="time" defaultValue={backup.schedule.time || "03:00"}>
              {TIMES.map( t => (
                <option key={t} value={t}>{t}</option>
              ))}
            </select>

            {i18n("Description and comments")}
            <textarea
              ref="description" className="ui text input" type="text"
              placeholder={i18n("Description and random notes about the backup and its history.")}
              defaultValue={backup.description}
              />

            { props.onAddBackup ? (
              <button className="ui button teal" onClick={this.handleAddBackup.bind(this)}>{i18n("Create backup")}</button>
            ) : (
              <button className="ui button teal" onClick={this.handleUpdateBackup.bind(this)}>{i18n("Update backup")}</button>
            )}

    )
  }
}

export default AddBackup
<|endoftext|>


<commit_before>var inSubnet = require('insubnet')
    ,config = require('../config')
    ,log = require('../libs/log')(module);

var requestIp = require('request-ip');

module.exports = function (req, res, next) {
    var ip = getClientIp(req);
    if (ip) {
        ip.replace(/^::ffff:/, '');
    };
    var mode = config.get("uploadAcl:mode");
    var ips =config.get("uploadAcl:ip");

    if (mode === 'allow' && inSubnet.Auto(ip, ips)) {
        req.webitelUser = {
            role: "GOD",
            attr: {}
        };
        next()
    } else {
        log.warn('Unauthorized connection ip: %s', ip);
        res.statusCode = 401;
        return res.end('forbidden');
    }
};

var getClientIp = function(req) {
    return requestIp.getClientIp(req);
};

<commit_msg>fix ACL<commit_after>var inSubnet = require('insubnet')
    ,config = require('../config')
    ,log = require('../libs/log')(module);

var requestIp = require('request-ip');

module.exports = function (req, res, next) {
    var ip = getClientIp(req);
    if (ip) {
        ip = ip.replace(/^::ffff:/, '');
    };
    var mode = config.get("uploadAcl:mode");
    var ips =config.get("uploadAcl:ip");

    if (mode === 'allow' && inSubnet.Auto(ip, ips)) {
        req.webitelUser = {
            role: "GOD",
            attr: {}
        };
        next()
    } else {
        log.warn('Unauthorized connection ip: %s', ip);
        res.statusCode = 401;
        return res.end('forbidden');
    }
};

var getClientIp = function(req) {
    return requestIp.getClientIp(req);
};

<|endoftext|>


<commit_before>// Function that provides map of rules found in ignorefiles for given ignorefile
// type. Additinally it invokes event on changes in map which are results of
// changes in ignorefiles.

'use strict';

var invoke    = require('es5-ext/function/invoke')
  , assign    = require('es5-ext/object/assign')
  , forEach   = require('es5-ext/object/for-each')
  , isCopy    = require('es5-ext/object/is-copy')
  , endsWith  = require('es5-ext/string/#/ends-with')
  , deferred  = require('deferred')
  , path      = require('path')
  , findRoot  = require('./_find-root')
  , readFile  = require('./read-file').readFile

  , dirname = path.dirname, sep = path.sep
  , ConfMap, readRules, readRulesWatcher, paths, getMap, lockId = 0;

paths = function (root, path2) {
	var starter, data;
	starter = [root];
	if (root === path2) {
		return starter;
	}
	if (endsWith.call(root, sep)) {
		data = path2.slice(root.length).split(sep);
		starter.push(root += data.shift());
	} else {
		data = path2.slice(root.length + 1).split(sep);
	}
	return starter.concat(data.map(function (path) {
		return (root += sep + path);
	}));
};

readRules = function (path) {
	return this.readFile(path + sep + this.filename)(function (src) {
		return (src == null) ? src : this.parse(src, path);
	}.bind(this));
};
readRulesWatcher = function (path) {
	var watcher, promise, current;
	watcher = this.readFile(path + sep + this.filename);
	promise = watcher(function (src) {
		return (current = ((src == null) ? src : this.parse(src, path)));
	}.bind(this));
	watcher.on('change', function (data) {
		data = ((data == null) ? data : this.parse(data, path));
		if (!isCopy(current, data, Infinity)) {
			current = promise.value = data;
			promise.emit('change', current, path);
		}
	}.bind(this));
	promise.close = watcher.close;
	return promise;
};

ConfMap = function (path, watch) {
	this.path = path;
	this.watch = watch;
	this.data = { root: null, map: {} };
	assign(this, deferred());
	if (this.watch) {
		this.onRulesChange = this.onRulesChange.bind(this);
		this.rulePromises = {};
		this.promise.close = this.close.bind(this);
	}
};
ConfMap.prototype = {
	init: function (findRoot) {
		this.findRoot = findRoot;
		if (this.watch) {
			findRoot.on('change', this.updateRoot.bind(this));
		}
		findRoot.end(function (root) {
			if (root) {
				this.data.root = root;
				this.addPaths(root, this.path).end(function () {
					this.resolve(this.data);
				}.bind(this), this.resolve);
			} else {
				this.resolve(this.data);
			}
		}.bind(this), this.resolve);
		return this.promise;
	},
	close: function () {
		if (this.rulePromises) {
			this.findRoot.close();
			forEach(this.rulePromises, invoke('close'));
			delete this.rulePromises;
		}
	},
	parse: String,
	readFile: function (path) {
		return readFile(path, { loose: true, watch: this.watch });
	},
	onRulesChange: function (rules, path) {
		if (rules == null) {
			delete this.data.map[path];
		} else {
			this.data.map[path] = rules;
		}
		this.promise.emit('change', this.data);
	},
	addPaths: function (root, path) {
		return deferred.map(paths(root, path), function (path) {
			var rules = this.readRules(path);
			if (this.watch) {
				this.rulePromises[path] = rules;
				rules.on('change', this.onRulesChange);
			}
			return rules.aside(function (rules) {
				if (rules != null) {
					this[path] = rules;
				}
			}.bind(this.data.map))(null, function (err) {
				// Watcher might have been closed in a meantime, if it was we ignore
				// this error as we're not interested in that value anymore
				return this.rulePromises[path] ? err : null;
			}.bind(this));
		}, this);
	},
	removePaths: function (root, path) {
		paths(root, path).forEach(function (path) {
			var promise = this.rulePromises[path];
			delete this.rulePromises[path];
			delete this.data.map[path];
			promise.close();
		}, this);
	},
	updateRoot: function (root) {
		var lock = ++lockId;
		if (!root) {
			this.removePaths(this.data.root, this.path);
			this.data.root = null;
			this.promise.emit('change', this.data);
		} else if (!this.data.root) {
			this.data.root = root;
			this.addPaths(root, this.path).end(function () {
				if (lock === lockId) {
					this.promise.emit('change', this.data);
				}
			}.bind(this));
		} else if (this.data.root < root) {
			this.removePaths(this.data.root, dirname(root));
			this.data.root = root;
			this.promise.emit('change', this.data);
		} else {
			this.addPaths(root, dirname(this.data.root)).end(function () {
				if (lock === lockId) {
					this.promise.emit('change', this.data);
				}
			}.bind(this));
			this.data.root = root;
		}
	}
};

getMap = module.exports = function (path, mode, watch, parse) {
	var map = new ConfMap(path, watch);
	map.filename = mode.filename;
	map.readRules = watch ? readRulesWatcher : readRules;
	if (parse) {
		map.parse = parse;
	}
	return map.init(findRoot(watch ? mode.isRootWatcher : mode.isRoot,
		path, { watch: watch }));
};
getMap.ConfMap = ConfMap;
getMap.readRules = readRules;
getMap.readRulesWatcher = readRulesWatcher;
<commit_msg>Update up to changes in es5-ext<commit_after>// Function that provides map of rules found in ignorefiles for given ignorefile
// type. Additinally it invokes event on changes in map which are results of
// changes in ignorefiles.

'use strict';

var invoke    = require('es5-ext/function/invoke')
  , assign    = require('es5-ext/object/assign')
  , forEach   = require('es5-ext/object/for-each')
  , isCopy    = require('es5-ext/object/is-copy-deep')
  , endsWith  = require('es5-ext/string/#/ends-with')
  , deferred  = require('deferred')
  , path      = require('path')
  , findRoot  = require('./_find-root')
  , readFile  = require('./read-file').readFile

  , dirname = path.dirname, sep = path.sep
  , ConfMap, readRules, readRulesWatcher, paths, getMap, lockId = 0;

paths = function (root, path2) {
	var starter, data;
	starter = [root];
	if (root === path2) {
		return starter;
	}
	if (endsWith.call(root, sep)) {
		data = path2.slice(root.length).split(sep);
		starter.push(root += data.shift());
	} else {
		data = path2.slice(root.length + 1).split(sep);
	}
	return starter.concat(data.map(function (path) {
		return (root += sep + path);
	}));
};

readRules = function (path) {
	return this.readFile(path + sep + this.filename)(function (src) {
		return (src == null) ? src : this.parse(src, path);
	}.bind(this));
};
readRulesWatcher = function (path) {
	var watcher, promise, current;
	watcher = this.readFile(path + sep + this.filename);
	promise = watcher(function (src) {
		return (current = ((src == null) ? src : this.parse(src, path)));
	}.bind(this));
	watcher.on('change', function (data) {
		data = ((data == null) ? data : this.parse(data, path));
		if (data === current) return;
		if ((current != null) && (data != null) && (typeof current === 'object')
				&& isCopy(current, data)) {
			return;
		}
		current = promise.value = data;
		promise.emit('change', current, path);
	}.bind(this));
	promise.close = watcher.close;
	return promise;
};

ConfMap = function (path, watch) {
	this.path = path;
	this.watch = watch;
	this.data = { root: null, map: {} };
	assign(this, deferred());
	if (this.watch) {
		this.onRulesChange = this.onRulesChange.bind(this);
		this.rulePromises = {};
		this.promise.close = this.close.bind(this);
	}
};
ConfMap.prototype = {
	init: function (findRoot) {
		this.findRoot = findRoot;
		if (this.watch) {
			findRoot.on('change', this.updateRoot.bind(this));
		}
		findRoot.end(function (root) {
			if (root) {
				this.data.root = root;
				this.addPaths(root, this.path).end(function () {
					this.resolve(this.data);
				}.bind(this), this.resolve);
			} else {
				this.resolve(this.data);
			}
		}.bind(this), this.resolve);
		return this.promise;
	},
	close: function () {
		if (this.rulePromises) {
			this.findRoot.close();
			forEach(this.rulePromises, invoke('close'));
			delete this.rulePromises;
		}
	},
	parse: String,
	readFile: function (path) {
		return readFile(path, { loose: true, watch: this.watch });
	},
	onRulesChange: function (rules, path) {
		if (rules == null) {
			delete this.data.map[path];
		} else {
			this.data.map[path] = rules;
		}
		this.promise.emit('change', this.data);
	},
	addPaths: function (root, path) {
		return deferred.map(paths(root, path), function (path) {
			var rules = this.readRules(path);
			if (this.watch) {
				this.rulePromises[path] = rules;
				rules.on('change', this.onRulesChange);
			}
			return rules.aside(function (rules) {
				if (rules != null) {
					this[path] = rules;
				}
			}.bind(this.data.map))(null, function (err) {
				// Watcher might have been closed in a meantime, if it was we ignore
				// this error as we're not interested in that value anymore
				return this.rulePromises[path] ? err : null;
			}.bind(this));
		}, this);
	},
	removePaths: function (root, path) {
		paths(root, path).forEach(function (path) {
			var promise = this.rulePromises[path];
			delete this.rulePromises[path];
			delete this.data.map[path];
			promise.close();
		}, this);
	},
	updateRoot: function (root) {
		var lock = ++lockId;
		if (!root) {
			this.removePaths(this.data.root, this.path);
			this.data.root = null;
			this.promise.emit('change', this.data);
		} else if (!this.data.root) {
			this.data.root = root;
			this.addPaths(root, this.path).end(function () {
				if (lock === lockId) {
					this.promise.emit('change', this.data);
				}
			}.bind(this));
		} else if (this.data.root < root) {
			this.removePaths(this.data.root, dirname(root));
			this.data.root = root;
			this.promise.emit('change', this.data);
		} else {
			this.addPaths(root, dirname(this.data.root)).end(function () {
				if (lock === lockId) {
					this.promise.emit('change', this.data);
				}
			}.bind(this));
			this.data.root = root;
		}
	}
};

getMap = module.exports = function (path, mode, watch, parse) {
	var map = new ConfMap(path, watch);
	map.filename = mode.filename;
	map.readRules = watch ? readRulesWatcher : readRules;
	if (parse) {
		map.parse = parse;
	}
	return map.init(findRoot(watch ? mode.isRootWatcher : mode.isRoot,
		path, { watch: watch }));
};
getMap.ConfMap = ConfMap;
getMap.readRules = readRules;
getMap.readRulesWatcher = readRulesWatcher;
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var Post = require('../entities/Post');
var auth = require('./auth');
router
  .get('/', (req, res, next) => {
    Post.find(null, 1).then((result) => {
      res.render('index', {
        title: 'AtEOF',
        posts: result
      });
    }).catch(function (err) {
      next(err);
    });
  })
  .get('/posts', (req, res, next) => {
    var keywords = req.query.keywords;
    var page = parseInt(req.query.page) || 1;
    Post.find(keywords, page).then((result) => {
      res.render('posts', {
        title: '文章列表',
        posts: result
      });
    }).catch(function (err) {
      next(err);
    });
  })
  .get('/posts/:id', (req, res, next) => {
    Post.findById(req.params.id).then((result) => {
      res.render('post', {
        title: post.title,
        post: result
      });
    });
  })
  .get('/editor', auth, (req, res, next) => {
    res.render('editor');
  });

module.exports = router;
<commit_msg>增加html标题<commit_after>var express = require('express');
var router = express.Router();
var Post = require('../entities/Post');
var auth = require('./auth');
router
  .get('/', (req, res, next) => {
    Post.find(null, 1).then((result) => {
      res.render('index', {
        title: 'AtEOF',
        posts: result
      });
    }).catch(function (err) {
      next(err);
    });
  })
  .get('/posts', (req, res, next) => {
    var keywords = req.query.keywords;
    var page = parseInt(req.query.page) || 1;
    Post.find(keywords, page).then((result) => {
      res.render('posts', {
        title: '文章列表',
        posts: result
      });
    }).catch(function (err) {
      next(err);
    });
  })
  .get('/posts/:id', (req, res, next) => {
    Post.findById(req.params.id).then((result) => {
      res.render('post', {
        title: result.title,
        post: result
      });
    });
  })
  .get('/editor', auth, (req, res, next) => {
    res.render('editor');
  });

module.exports = router;
<|endoftext|>


<commit_before>var {
  NativeModules
} = require('react-native');

var DeviceUtil = NativeModules.DisplayDeviceUtil;
var Dimensions = require('Dimensions');
var RCTDeviceEventEmitter = require('RCTDeviceEventEmitter');

class Display {

  updateProps(newWidth, newHeight) {
    this.width = newWidth;
    this.height = newHeight;
  }

  constructor() {
    this.width = Dimensions.get("window").width;
    this.height = Dimensions.get("window").height;
    //Enable console messages by changing to true: Display.verbose = true
    this.verbose = false;
  }

  percentage(type, value) {
    if (type == 'width') {
      return value * (this.height / 100);
    } else if (type == 'height') {
      return value * (this.width / 100);
    } else {
      return 'Invalid Type (width / height)';
    }
  }

  isPortrait() {
    if (this.width < this.height) {
      return true;
    } else {
      return false;
    }
  }

  isLandscape() {
    if (this.width > this.height) {
      return true;
    } else {
      return false;
    }
  }

  isTablet() {
    return DeviceUtil.isTablet;
  }

  isPhone() {
    return DeviceUtil.isPhone;
  }

  onOrientationDidChange(handler) {
    var main = this;
    return RCTDeviceEventEmitter.addListener(
      'orientationDidChange',
      function(newDimensions) {
        main.updateProps(newDimensions.width, newDimensions.height);
        var orientation = main.updateOrientation(newDimensions.orientation);
        handler(newDimensions.width, newDimensions.height, orientation);
      }
    );
  }
  updateOrientation(orientation) {
    var o = {};
    switch (orientation) {
      case 1:
        o = {
          current: 'portrait',
          idle: false,
          facing: ''
        };
        break;
      case 2:
        o = {
          current: 'portrait',
          idle: false,
          facing: ''
        };
        break;
      case 3:
        o = {
          current: 'landscape',
          idle: false,
          facing: ''
        };
        break;
      case 4:
        o = {
          current: 'landscape',
          idle: false,
          facing: ''
        };
        break;
      case 5:
        o = {
          current: this.orientation.current,
          idle: true,
          facing: 'up'
        };
        break;
      case 6:
        o = {
          current: this.orientation.current,
          idle: true,
          facing: 'down'
        };
        break;
    }
    if (this.verbose) {
      console.log('Orientation Updated');
      console.log(o);
    }
    this.orientation = o;
    return o;
  }
}

module.exports = new Display();<commit_msg>Compatibility with latest react-native<commit_after>var {
  NativeModules, Dimensions, RCTDeviceEventEmitter
} = require('react-native');

var DeviceUtil = NativeModules.DisplayDeviceUtil;

class Display {

  updateProps(newWidth, newHeight) {
    this.width = newWidth;
    this.height = newHeight;
  }

  constructor() {
    this.width = Dimensions.get("window").width;
    this.height = Dimensions.get("window").height;
    //Enable console messages by changing to true: Display.verbose = true
    this.verbose = false;
  }

  percentage(type, value) {
    if (type == 'width') {
      return value * (this.height / 100);
    } else if (type == 'height') {
      return value * (this.width / 100);
    } else {
      return 'Invalid Type (width / height)';
    }
  }

  isPortrait() {
    if (this.width < this.height) {
      return true;
    } else {
      return false;
    }
  }

  isLandscape() {
    if (this.width > this.height) {
      return true;
    } else {
      return false;
    }
  }

  isTablet() {
    return DeviceUtil.isTablet;
  }

  isPhone() {
    return DeviceUtil.isPhone;
  }

  onOrientationDidChange(handler) {
    var main = this;
    return RCTDeviceEventEmitter.addListener(
      'orientationDidChange',
      function(newDimensions) {
        main.updateProps(newDimensions.width, newDimensions.height);
        var orientation = main.updateOrientation(newDimensions.orientation);
        handler(newDimensions.width, newDimensions.height, orientation);
      }
    );
  }
  updateOrientation(orientation) {
    var o = {};
    switch (orientation) {
      case 1:
        o = {
          current: 'portrait',
          idle: false,
          facing: ''
        };
        break;
      case 2:
        o = {
          current: 'portrait',
          idle: false,
          facing: ''
        };
        break;
      case 3:
        o = {
          current: 'landscape',
          idle: false,
          facing: ''
        };
        break;
      case 4:
        o = {
          current: 'landscape',
          idle: false,
          facing: ''
        };
        break;
      case 5:
        o = {
          current: this.orientation.current,
          idle: true,
          facing: 'up'
        };
        break;
      case 6:
        o = {
          current: this.orientation.current,
          idle: true,
          facing: 'down'
        };
        break;
    }
    if (this.verbose) {
      console.log('Orientation Updated');
      console.log(o);
    }
    this.orientation = o;
    return o;
  }
}

module.exports = new Display();
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

module.exports = router;

var mongoose = require('mongoose');
var Comics = mongoose.model('Comics');

router.get('/comics', function(req, res, next) {
	Comics.find(function(err, comics) {
		if(err){ return next(err);}
		res.json(comics);
	});
});<commit_msg>Add post function for comics<commit_after>var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

module.exports = router;

var mongoose = require('mongoose');
var Comics = mongoose.model('Comics');

router.get('/comics', function(req, res, next) {
	Comics.find(function(err, comics) {
		if(err){ return next(err);}
		res.json(comics);
	});
});

router.post('/comics', function(req, res, next) {
	var comic = new Comics(req.body);
	comic.save(function(err, comic){
		if(err){ return next(err); }

		res.json(comic);
	});
});<|endoftext|>


<commit_before>
var createDisplay = function(options) {

    options = options || {};
    var self = {};

    var canvasId = options.id || "display";

    var cols = options.cols || 80;
    var rows = options.rows || 40;

    var font = options.font || "monospace";
    var fontSize = options.fontSize || 8;
    var charWidth = options.charWidth || fontSize;
    var charHeight = options.charHeight || fontSize;
    var baselineOffset = options.baselineOffset || 0;
    var scale = options.scale || 1;

    var displayWidth = charWidth * cols * scale;
    var displayHeight = charHeight * rows * scale;

    var keyHandled = false;
    var keyTime = 0;
    var keyPressed = false;
    var frameTimer = null;

    var canvas = document.getElementById(canvasId);
    var g = canvas.getContext("2d");

    canvas.width = displayWidth;
    canvas.height = displayHeight;
    canvas.style.width = displayWidth + "px";
    canvas.style.height = displayHeight + "px";

    self.buffer = [];
    self.x = options.x || 0;
    self.y = options.y || 0;
    self.capsLock = options.capsLock || false;
    self.bgColor = options.bgColor || "#444";
    self.fgColor = options.fgColor || "#ccc";
    self.border = options.border || 0;
    self.borderColor = options.borderColor || "#000";
    self.borderRadius = options.borderRadius || 0;

    self.print = function(text) {
        for (var i = 0; i < text.length; i++) {
            charout(text[i]);
        }
        return self;
    };

    self.println = function(text) {
        if (!text) {
            text = "";
        }
        self.print(text + "\n");
        return self;
    };

    self.cprintln = function(text) {
        self.x = (cols / 2) - Math.floor(text.length / 2);
        if (self.x < 0) {
            self.x = 0;
        }
        self.println(text);
        return self;
    };

    self.rprint = function(text) {
        self.x = cols - text.length;
        self.print(text);
        return self;
    };

    self.color = function(fgColor, bgColor) {
        self.fgColor = fgColor;
        if (bgColor) {
            self.bgColor = bgColor;
        }
        return this;
    };

    self.backspace = function() {
        self.left();
        self.buffer[self.x][self.y].text = " ";
    };

    self.scroll = function() {
        for (var x = 0; x < cols; x++) {
            self.buffer[x].shift();
            self.buffer[x][height - 1] = {
                text: " ",
                fgColor: self.fgColor,
                bgColor: self.bgColor
            }
        }
        return self;
    };

    self.clear = function() {
        for (var x = 0; x < cols; x++) {
            self.buffer[x] = [];
            for (var y = 0; y < rows; y++) {
                self.buffer[x][y] = {
                    text: " ",
                    fgColor: self.fgColor,
                    bgColor: self.bgColor
                }
            }
        }
        return self;
    };

    self.reset = function() {
        self.clear();
        self.x = 0;
        self.y = 0;
    };

    var renderCell = function(x, y, cell) {
        var sx = x * charWidth * scale;
        var sy1 = y * charHeight * scale;
        var sy2 = (y + 1) * charHeight * scale;

        g.fillStyle = cell.bgColor;
        g.fillRect(sx, sy1, charWidth * scale, charHeight * scale);

        g.fillStyle = cell.fgColor;
        g.fillText(cell.text, sx, sy2 - (baselineOffset * scale));
    };

    var renderCursor = function(time) {
        if (keyPressed) {
            keyPressed = false;
            keyTime = time;
        }

        var checkTime = time - keyTime;
        if (checkTime % 1000 > 500) {
            return;
        }
        var cell = self.buffer[self.x][self.y];
        renderCell(self.x, self.y, {
            text: cell.text,
            fgColor: cell.bgColor,
            bgColor: cell.fgColor
        });
    };

    var render = function(time) {
        var previousBorder = window.getComputedStyle(canvas, null);
        var currentBorder = "0px none rgb(0, 0, 0)";
        if (self.border > 0) {
            currentBorder = self.border + "px solid " + self.borderColor;
        }
        if (currentBorder !== previousBorder) {
            canvas.style.border = currentBorder;
            canvas.style.borderRadius = self.borderRadius + "px";
        }
        var scaledFontSize = fontSize * scale;
        g.font = scaledFontSize + "px " + font;
        for (var x = 0; x < cols; x++) {
            for (var y = 0; y < rows; y++) {
                renderCell(x, y, self.buffer[x][y]);
            }
        }
        frameTimer = window.requestAnimationFrame(render);
        renderCursor(time);
    };

    var nextLine = function() {
        self.x = 0;
        if (self.y < cols - 1) {
            self.y += 1;
            if (self.y >= rows) {
                self.y = rows - 1;
            }
        }
    };

    var advance = function() {
        self.x += 1;
        if (self.x >= cols) {
            nextLine();
        }
    };

    self.left = function() {
        self.x -= 1;
        if (self.x < 0) {
            self.x = 0;
        }
    };

    self.right = function() {
        self.x += 1;
        if (self.x >= cols) {
            self.x = cols - 1;
        }
    };

    self.up = function() {
        self.y -= 1;
        if (self.y < 0) {
            self.y = 0;
        }
    };

    self.down = function() {
        self.y += 1;
        if (self.y >= rows) {
            self.y = rows - 1;
        }
    };

    var charout = function(char) {
        if (self.capsLock) {
            char = char.toUpperCase();
        }
        if (char === "\n") {
            nextLine();
        } else {
            self.buffer[self.x][self.y] = {
                text: char,
                bgColor: self.bgColor,
                fgColor: self.fgColor
            };
            advance();
        }
    };

    // Use down for repeat events
    var keydown = function(event) {
        keyPressed = true;
        keyHandled = true;
        if (event.keyCode === 38) {
            self.up();
        } else if (event.keyCode === 40) {
            self.down();
        } else if (event.keyCode === 37) {
            self.left();
        } else if (event.keyCode === 39) {
            self.right();
        } else if (event.keyCode === 8) {
            self.backspace();
            event.preventDefault();
        } else if (event.keyCode === 13) {
            self.println();
        } else {
            keyHandled = false;
        }
    };

    var keypress = function(event) {
        if (keyHandled) {
            keyHandled = false;
            return;
        }
        self.print(event.key);
    };

    self.stop = function() {
        window.cancelAnimationFrame(frameTimer);
        window.removeEventListener("keydown", keydown);
        window.removeEventListener("keypress", keypress);
    };

    self.start = function() {
        self.stop();
        frameTimer = window.requestAnimationFrame(render);
        window.addEventListener("keydown", keydown);
        window.addEventListener("keypress", keypress);
    };

    self.clear();
    self.start();

    return self;
};

<commit_msg>scroll at the bottom of the screen<commit_after>
var createDisplay = function(options) {

    options = options || {};
    var self = {};

    var canvasId = options.id || "display";

    var cols = options.cols || 80;
    var rows = options.rows || 40;

    var font = options.font || "monospace";
    var fontSize = options.fontSize || 8;
    var charWidth = options.charWidth || fontSize;
    var charHeight = options.charHeight || fontSize;
    var baselineOffset = options.baselineOffset || 0;
    var scale = options.scale || 1;

    var displayWidth = charWidth * cols * scale;
    var displayHeight = charHeight * rows * scale;

    var keyHandled = false;
    var keyTime = 0;
    var keyPressed = false;
    var frameTimer = null;

    var canvas = document.getElementById(canvasId);
    var g = canvas.getContext("2d");

    canvas.width = displayWidth;
    canvas.height = displayHeight;
    canvas.style.width = displayWidth + "px";
    canvas.style.height = displayHeight + "px";

    self.buffer = [];
    self.x = options.x || 0;
    self.y = options.y || 0;
    self.capsLock = options.capsLock || false;
    self.bgColor = options.bgColor || "#444";
    self.fgColor = options.fgColor || "#ccc";
    self.border = options.border || 0;
    self.borderColor = options.borderColor || "#000";
    self.borderRadius = options.borderRadius || 0;

    self.print = function(text) {
        for (var i = 0; i < text.length; i++) {
            charout(text[i]);
        }
        return self;
    };

    self.println = function(text) {
        if (!text) {
            text = "";
        }
        self.print(text + "\n");
        return self;
    };

    self.cprintln = function(text) {
        self.x = (cols / 2) - Math.floor(text.length / 2);
        if (self.x < 0) {
            self.x = 0;
        }
        self.println(text);
        return self;
    };

    self.rprint = function(text) {
        self.x = cols - text.length;
        self.print(text);
        return self;
    };

    self.color = function(fgColor, bgColor) {
        self.fgColor = fgColor;
        if (bgColor) {
            self.bgColor = bgColor;
        }
        return this;
    };

    self.backspace = function() {
        self.left();
        self.buffer[self.x][self.y].text = " ";
    };

    self.scroll = function() {
        for (var x = 0; x < cols; x++) {
            self.buffer[x].shift();
            self.buffer[x][rows - 1] = {
                text: " ",
                fgColor: self.fgColor,
                bgColor: self.bgColor
            }
        }
        return self;
    };

    self.clear = function() {
        for (var x = 0; x < cols; x++) {
            self.buffer[x] = [];
            for (var y = 0; y < rows; y++) {
                self.buffer[x][y] = {
                    text: " ",
                    fgColor: self.fgColor,
                    bgColor: self.bgColor
                }
            }
        }
        return self;
    };

    self.reset = function() {
        self.clear();
        self.x = 0;
        self.y = 0;
    };

    var renderCell = function(x, y, cell) {
        var sx = x * charWidth * scale;
        var sy1 = y * charHeight * scale;
        var sy2 = (y + 1) * charHeight * scale;

        g.fillStyle = cell.bgColor;
        g.fillRect(sx, sy1, charWidth * scale, charHeight * scale);

        g.fillStyle = cell.fgColor;
        g.fillText(cell.text, sx, sy2 - (baselineOffset * scale));
    };

    var renderCursor = function(time) {
        if (keyPressed) {
            keyPressed = false;
            keyTime = time;
        }

        var checkTime = time - keyTime;
        if (checkTime % 1000 > 500) {
            return;
        }
        var cell = self.buffer[self.x][self.y];
        renderCell(self.x, self.y, {
            text: cell.text,
            fgColor: cell.bgColor,
            bgColor: cell.fgColor
        });
    };

    var render = function(time) {
        var previousBorder = window.getComputedStyle(canvas, null);
        var currentBorder = "0px none rgb(0, 0, 0)";
        if (self.border > 0) {
            currentBorder = self.border + "px solid " + self.borderColor;
        }
        if (currentBorder !== previousBorder) {
            canvas.style.border = currentBorder;
            canvas.style.borderRadius = self.borderRadius + "px";
        }
        var scaledFontSize = fontSize * scale;
        g.font = scaledFontSize + "px " + font;
        for (var x = 0; x < cols; x++) {
            for (var y = 0; y < rows; y++) {
                renderCell(x, y, self.buffer[x][y]);
            }
        }
        frameTimer = window.requestAnimationFrame(render);
        renderCursor(time);
    };

    var nextLine = function() {
        self.x = 0;
        if (self.y < rows - 1) {
            self.y += 1;
        } else {
            self.scroll();
        }
    };

    var advance = function() {
        self.x += 1;
        if (self.x >= cols) {
            nextLine();
        }
    };

    self.left = function() {
        self.x -= 1;
        if (self.x < 0) {
            self.x = 0;
        }
    };

    self.right = function() {
        self.x += 1;
        if (self.x >= cols) {
            self.x = cols - 1;
        }
    };

    self.up = function() {
        self.y -= 1;
        if (self.y < 0) {
            self.y = 0;
        }
    };

    self.down = function() {
        self.y += 1;
        if (self.y >= rows) {
            self.y = rows - 1;
        }
    };

    var charout = function(char) {
        if (self.capsLock) {
            char = char.toUpperCase();
        }
        if (char === "\n") {
            nextLine();
        } else {
            self.buffer[self.x][self.y] = {
                text: char,
                bgColor: self.bgColor,
                fgColor: self.fgColor
            };
            advance();
        }
    };

    // Use down for repeat events
    var keydown = function(event) {
        keyPressed = true;
        keyHandled = true;
        if (event.keyCode === 38) {
            self.up();
        } else if (event.keyCode === 40) {
            self.down();
        } else if (event.keyCode === 37) {
            self.left();
        } else if (event.keyCode === 39) {
            self.right();
        } else if (event.keyCode === 8) {
            self.backspace();
            event.preventDefault();
        } else if (event.keyCode === 13) {
            self.println();
        } else {
            keyHandled = false;
        }
    };

    var keypress = function(event) {
        if (keyHandled) {
            keyHandled = false;
            return;
        }
        self.print(event.key);
    };

    self.stop = function() {
        window.cancelAnimationFrame(frameTimer);
        window.removeEventListener("keydown", keydown);
        window.removeEventListener("keypress", keypress);
    };

    self.start = function() {
        self.stop();
        frameTimer = window.requestAnimationFrame(render);
        window.addEventListener("keydown", keydown);
        window.addEventListener("keypress", keypress);
    };

    self.clear();
    self.start();

    return self;
};

<|endoftext|>


<commit_before>
var express        = require('express');
var router         = express.Router();
var userRoutes     = require('./user');
var sessionRoutes  = require('./session');
var homeRoutes     = require('./home');
var fashionRoutes  = require('./fashion');
var categoryRoutes = require('./category');
var roleRoutes     = require('./role');
var sizeRoutes     = require('./size');
var cartRoutes     = require('./cart');
var payRoutes      = require('./pay');
var ordersRoutes   = require('./orders');

var multer = require('multer');
var upload = multer({dest:'uploads/'});

function isLoggedIn(req, res, next) {
  if(req.isAuthenticated()){
    return next();
  }
  req.session.returnTo = req.path;
  res.redirect('/login');
}

function isAdmin(req, res, next) {
  if(req.isAuthenticated()){
    if(req.user.role == 'admin'){
      return next();
    }
  }
  req.session.returnTo = req.path;
  res.redirect('/login');
}

router.get('/', homeRoutes.index);
router.get('/category/:category', homeRoutes.categories);

/*
 * @user routes
*/
router.get('/register',           userRoutes.new);
router.post('/signup',            userRoutes.create);

/*
 * @session routes
*/
router.get('/login',           sessionRoutes.new);
router.post('/login',          sessionRoutes.create);
router.get('/logout',          sessionRoutes.delete);

/*
 * @fashion routes
*/
router.get('/admin/fashions',              fashionRoutes.index);
router.get('/admin/fashion/item/:id',      fashionRoutes.single);
router.get('/fashion/item/:id',            fashionRoutes.item);
router.get('/admin/fashion/create',        fashionRoutes.new);
router.post('/admin/fashion/add',          upload.single('upload'),  fashionRoutes.add);
router.get('/admin/fashion/edit/:id',      fashionRoutes.edit);
router.post('/admin/fashion/update',       fashionRoutes.update);
router.post('/admin/fashion/image/update', upload.single('upload'),  fashionRoutes.updateimage);
router.get('/admin/fashion/delete/:id',    fashionRoutes.delete);
//router.get('/fashion/cart',          fashionRoutes.cart);

/*
 * @cart routes
 */
router.get('/fashion/checkout',                 cartRoutes.new);
router.get('/add-to-cart/:fashion_id/:size_id', cartRoutes.addtocart);
router.get('/remove-from-cart/:size_id',        cartRoutes.removeonefromcart);
router.get('/add-qty-to-cart/:size_id',         cartRoutes.addqtytocart);
router.get('/remove-object/:size_id',           cartRoutes.removecartobject);
router.get('/session/cart/delete',              cartRoutes.deletecart);

/*
 * @category Routes
 */
router.get('/admin/category/index',      categoryRoutes.index);
router.get('/admin/category/create',     categoryRoutes.new);
router.get('/admin/categories',          categoryRoutes.get);
router.post('/admin/category/add',       categoryRoutes.add);
router.get('/admin/category/delete/:id', categoryRoutes.delete);

/*
 * @size Routes
 */
router.get('/admin/size/index',          sizeRoutes.index);
router.get('/admin/size/create/:id',     sizeRoutes.new);
router.get('/admin/sizes',               sizeRoutes.get);
router.post('/admin/size/add',           sizeRoutes.add);
router.get('/admin/size/edit/:id',       sizeRoutes.edit);
router.post('/admin/size/update',        sizeRoutes.update);

router.get('/fashion/cart/create/:id',   cartRoutes.new);
router.post('/fashion/cart/add',         cartRoutes.add);
router.get('/fashion/cart/:id',          cartRoutes.item);
router.get('/fashion/pay/:id',           cartRoutes.pay);

/*
 * @Paypal routes
 */
router.get('/payment/:id', payRoutes.payment);
router.get('/paypal/:id',  payRoutes.paypal);
router.post('/paynow/:id', payRoutes.paypal);
router.get('/success/:id', payRoutes.success);
router.get('/cancel/:id',  payRoutes.cancel);

/*
 * @order routes
 */
router.get('/pay/:id',       ordersRoutes.order);
router.post('/billing',      ordersRoutes.billing);
router.get('/new',           ordersRoutes.index);
router.get('/sold',          ordersRoutes.sold);
router.get('/awaiting',      ordersRoutes.awaiting);
router.get('/admin/product', ordersRoutes.product);
router.get('/orders/post',   ordersRoutes.postorder);

/*
 * @Role routes
 */
router.get('/admin/assign/:username/:role', roleRoutes.assign);
router.get('/admin/role/:role',             roleRoutes.create);

module.exports=router;
<commit_msg>route contact us and blog pages<commit_after>
var express        = require('express');
var router         = express.Router();
var userRoutes     = require('./user');
var sessionRoutes  = require('./session');
var homeRoutes     = require('./home');
var fashionRoutes  = require('./fashion');
var categoryRoutes = require('./category');
var roleRoutes     = require('./role');
var sizeRoutes     = require('./size');
var cartRoutes     = require('./cart');
var payRoutes      = require('./pay');
var ordersRoutes   = require('./orders');

var multer = require('multer');
var upload = multer({dest:'uploads/'});

function isLoggedIn(req, res, next) {
  if(req.isAuthenticated()){
    return next();
  }
  req.session.returnTo = req.path;
  res.redirect('/login');
}

function isAdmin(req, res, next) {
  if(req.isAuthenticated()){
    if(req.user.role == 'admin'){
      return next();
    }
  }
  req.session.returnTo = req.path;
  res.redirect('/login');
}

router.get('/', homeRoutes.index);
router.get('/contact', homeRoutes.contact);
router.get('/blog', homeRoutes.blog);
router.get('/blog_single', homeRoutes.blog_single);
router.get('/category/:category', homeRoutes.categories);

/*
 * @user routes
*/
router.get('/register',           userRoutes.new);
router.post('/signup',            userRoutes.create);

/*
 * @session routes
*/
router.get('/login',           sessionRoutes.new);
router.post('/login',          sessionRoutes.create);
router.get('/logout',          sessionRoutes.delete);

/*
 * @fashion routes
*/
router.get('/admin/fashions',              fashionRoutes.index);
router.get('/admin/fashion/item/:id',      fashionRoutes.single);
router.get('/fashion/item/:id',            fashionRoutes.item);
router.get('/admin/fashion/create',        fashionRoutes.new);
router.post('/admin/fashion/add',          upload.single('upload'),  fashionRoutes.add);
router.get('/admin/fashion/edit/:id',      fashionRoutes.edit);
router.post('/admin/fashion/update',       fashionRoutes.update);
router.post('/admin/fashion/image/update', upload.single('upload'),  fashionRoutes.updateimage);
router.get('/admin/fashion/delete/:id',    fashionRoutes.delete);
//router.get('/fashion/cart',          fashionRoutes.cart);

/*
 * @cart routes
 */
router.get('/fashion/checkout',                 cartRoutes.new);
router.get('/add-to-cart/:fashion_id/:size_id', cartRoutes.addtocart);
router.get('/remove-from-cart/:size_id',        cartRoutes.removeonefromcart);
router.get('/add-qty-to-cart/:size_id',         cartRoutes.addqtytocart);
router.get('/remove-object/:size_id',           cartRoutes.removecartobject);
router.get('/session/cart/delete',              cartRoutes.deletecart);

/*
 * @category Routes
 */
router.get('/admin/category/index',      categoryRoutes.index);
router.get('/admin/category/create',     categoryRoutes.new);
router.get('/admin/categories',          categoryRoutes.get);
router.post('/admin/category/add',       categoryRoutes.add);
router.get('/admin/category/delete/:id', categoryRoutes.delete);

/*
 * @size Routes
 */
router.get('/admin/size/index',          sizeRoutes.index);
router.get('/admin/size/create/:id',     sizeRoutes.new);
router.get('/admin/sizes',               sizeRoutes.get);
router.post('/admin/size/add',           sizeRoutes.add);
router.get('/admin/size/edit/:id',       sizeRoutes.edit);
router.post('/admin/size/update',        sizeRoutes.update);

router.get('/fashion/cart/create/:id',   cartRoutes.new);
router.post('/fashion/cart/add',         cartRoutes.add);
router.get('/fashion/cart/:id',          cartRoutes.item);
router.get('/fashion/pay/:id',           cartRoutes.pay);

/*
 * @Paypal routes
 */
router.get('/payment/:id', payRoutes.payment);
router.get('/paypal/:id',  payRoutes.paypal);
router.post('/paynow/:id', payRoutes.paypal);
router.get('/success/:id', payRoutes.success);
router.get('/cancel/:id',  payRoutes.cancel);

/*
 * @order routes
 */
router.get('/pay/:id',       ordersRoutes.order);
router.post('/billing',      ordersRoutes.billing);
router.get('/new',           ordersRoutes.index);
router.get('/sold',          ordersRoutes.sold);
router.get('/awaiting',      ordersRoutes.awaiting);
router.get('/admin/product', ordersRoutes.product);
router.get('/orders/post',   ordersRoutes.postorder);

/*
 * @Role routes
 */
router.get('/admin/assign/:username/:role', roleRoutes.assign);
router.get('/admin/role/:role',             roleRoutes.create);

module.exports=router;
<|endoftext|>


<commit_before>'use strict';

const tools = require('../tools.js');
const dgram = require('dgram');
const adapterName = 'kecontact';
var txSocket = null;
var rxSocket = null;
const DEFAULT_UDP_PORT = 7090;
const BROADCAST_UDP_PORT = 7092;
const DETECT_MESSAGE = "i";
const KEBA_TIMEOUT = 500;
var timeout = null;

function addInstance(ip, device, options, native) {
    let instance = tools.findInstance (options, adapterName, obj => true);
    if (!instance) {
        instance = {
            _id: tools.getNextInstanceID(adapterName, options),
            common: {
                name: adapterName,
                title: 'Keba KeContact P30 (' + ip + ')'
            },
            native: {
                host: ip
            },
            comment: {
                add: [ip]
            }
        };
        options.newInstances.push(instance);
        return true;
    }
    return false;
}

function detect(ip, device, options, callback) {
    options.log.info('Detecting Keba KeContact wallbox on ' + ip + '...');

    timeout = setTimeout(() => {
        timeout = null;
        cleanup(ip, callback, false);
        callback = null;
    }, KEBA_TIMEOUT);

    rxSocket = dgram.createSocket('udp4');
    rxSocket.on('error', (err) => {
        if (err.message.includes('EADDRINUSE')) {
            options.log.info('Keba adapter already running');
        } else {
            options.log.error(`Keba rxSocket error:${err.stack}`);
        }
        cleanup(ip, callback, false);
        callback = null;
    });

    rxSocket.on('listening', function () {
        //rxSocket.setBroadcast(true);
        //rxSocket.setMulticastLoopback(true);
        var address = rxSocket.address();
        options.log.debug('Keba UDP server listening on ' + address.address + ":" + address.port);
        // send connect request
        txSocket = dgram.createSocket('udp4');
        txSocket.send(DETECT_MESSAGE, 0, DETECT_MESSAGE.length, DEFAULT_UDP_PORT, '192.168.97.47', (err, bytes) => err && options.log.warn('Error from KeContact: ' + err));
    });
    rxSocket.on('message', (message, remote) => {
        options.log.debug('UDP datagram from ' + remote.address + ':' + remote.port + ': "' + message + '"');
        if (timeout) {
            clearTimeout(timeout);
            timeout = null;
        }
        if (message.length > 0) {
            // no defined response needed regarding Keba docs
            cleanup(ip, callback, addInstance(ip, device, options, {ip}));
            callback = null;
        } else {
            cleanup(ip, callback, false);
            callback = null;
        }

    });
    rxSocket.bind(BROADCAST_UDP_PORT);
}

function cleanup(ip, callback, callbackResult) {
    if (txSocket) {
        txSocket.close();
        txSocket = null;
    }
    if (rxSocket) {
        rxSocket.close(() => {
            if (callback) {
                callback(null, callbackResult, ip);
            }
        });
        rxSocket = null;
    }
}

exports.detect = detect;
exports.type = ['udp'];
exports.timeout = KEBA_TIMEOUT;<commit_msg>change rx port<commit_after>'use strict';

const tools = require('../tools.js');
const dgram = require('dgram');
const adapterName = 'kecontact';
var txSocket = null;
var rxSocket = null;
const DEFAULT_UDP_PORT = 7090;
const BROADCAST_UDP_PORT = 7092;
const DETECT_MESSAGE = "i";
const KEBA_TIMEOUT = 500;
var timeout = null;

function addInstance(ip, device, options, native) {
    let instance = tools.findInstance (options, adapterName, obj => true);
    if (!instance) {
        instance = {
            _id: tools.getNextInstanceID(adapterName, options),
            common: {
                name: adapterName,
                title: 'Keba KeContact P30 (' + ip + ')'
            },
            native: {
                host: ip
            },
            comment: {
                add: [ip]
            }
        };
        options.newInstances.push(instance);
        return true;
    }
    return false;
}

function detect(ip, device, options, callback) {
    options.log.info('Detecting Keba KeContact wallbox on ' + ip + '...');

    timeout = setTimeout(() => {
        timeout = null;
        cleanup(ip, callback, false);
        callback = null;
    }, KEBA_TIMEOUT);

    rxSocket = dgram.createSocket('udp4');
    rxSocket.on('error', (err) => {
        if (err.message.includes('EADDRINUSE')) {
            options.log.info('Keba adapter already running');
        } else {
            options.log.error(`Keba rxSocket error:${err.stack}`);
        }
        cleanup(ip, callback, false);
        callback = null;
    });

    rxSocket.on('listening', function () {
        //rxSocket.setBroadcast(true);
        //rxSocket.setMulticastLoopback(true);
        var address = rxSocket.address();
        options.log.debug('Keba UDP server listening on ' + address.address + ":" + address.port);
        // send connect request
        txSocket = dgram.createSocket('udp4');
        txSocket.send(DETECT_MESSAGE, 0, DETECT_MESSAGE.length, DEFAULT_UDP_PORT, '192.168.97.47', (err, bytes) => err && options.log.warn('Error from KeContact: ' + err));
    });
    rxSocket.on('message', (message, remote) => {
        options.log.debug('UDP datagram from ' + remote.address + ':' + remote.port + ': "' + message + '"');
        if (timeout) {
            clearTimeout(timeout);
            timeout = null;
        }
        if (message.length > 0) {
            // no defined response needed regarding Keba docs
            cleanup(ip, callback, addInstance(ip, device, options, {ip}));
            callback = null;
        } else {
            cleanup(ip, callback, false);
            callback = null;
        }

    });
    rxSocket.bind(DEFAULT_UDP_PORT);
}

function cleanup(ip, callback, callbackResult) {
    if (txSocket) {
        txSocket.close();
        txSocket = null;
    }
    if (rxSocket) {
        rxSocket.close(() => {
            if (callback) {
                callback(null, callbackResult, ip);
            }
        });
        rxSocket = null;
    }
}

exports.detect = detect;
exports.type = ['udp'];
exports.timeout = KEBA_TIMEOUT;<|endoftext|>


<commit_before>'use strict';

var express = require('express');
var braintree = require('braintree');
var router = express.Router(); // eslint-disable-line new-cap
var gateway = require('../lib/gateway');

  var SUBSCRIPTION_SUCCESS_STATUSES = [
    braintree.Subscription.Status.Active,
    braintree.Subscription.Status.Canceled,
    braintree.Subscription.Status.Expired,
    braintree.Subscription.Status.PastDue,
    braintree.Subscription.Status.Pending
   ];

function formatErrors(errors) {
  var formattedErrors = '';

  for (var i in errors) { // eslint-disable-line no-inner-declarations, vars-on-top
    if (errors.hasOwnProperty(i)) {
      formattedErrors += 'Error: ' + errors[i].code + ': ' + errors[i].message + '\n';
    }
  }
  return formattedErrors;
}

function createResultObject(subscription) {
  var result;
  var status = subscription.status;

  if (SUBSCRIPTION_SUCCESS_STATUSES.indexOf(status) !== -1) {
    result = {
      header: 'Welcome to Coder Kids!',
      icon: 'success',
      message: 'Your membership enrollment is now complete. Please review membership details and contact us at hello@coder-kids.com with any questions. Once you have reviewed your membership details, click the button below to schedule your CoderKid.'
    };
  } else {
    result = {
      header: 'Transaction Failed',
      icon: 'fail',
      message: 'There is an issue with this transaction. Please contact us at hello@coder-kids.com.'
    };
  }

  return result;
}

router.get('/', function (req, res) {
  res.redirect('/checkouts/new');
});

router.get('/checkouts/new', function (req, res) {
  gateway.clientToken.generate({}, function (err, response) {
    res.render('checkouts/new', {clientToken: response.clientToken, messages: req.flash('error')});
  });
});

router.get('/checkouts/:id', function (req, res) {
  var result;
  var subscriptionId = req.params.id;
  gateway.subscription.find(subscriptionId, function (err, subscription) {
    result = createResultObject(subscription);
    res.render('checkouts/show', {subscription: subscription, result: result});
  });
});

router.post('/checkouts', function (req, res) {
  var transactionErrors;
  var plan = req.body.selectedPlan;
  var firstName = req.body.firstName;
  var lastName = req.body.lastName;
  var email = req.body.email;
  var phoneNumber = req.body.phone;
  var referralName = req.body.referralName;
  var childFirstName = req.body.childfirstname;
  var childLastName = req.body.childlastname;
  var childAge = req.body.childage;
  var initialCourse = req.body.initialcourse;
  var nonce = req.body.payment_method_nonce;
  var startDate = new Date(Date.UTC(2016, 8, 6, 0, 0, 0));

  gateway.customer.create({
  paymentMethodNonce: nonce,
  firstName: firstName,
  lastName: lastName,
  email: email,
  phone: phoneNumber
  customFields: {
    initialcourse: initialCourse,
    childage: childAge,
    childlastname: childLastName,
    childfirstname: childFirstName,
    referralname: referralName
  }
  }, function (err, result) {
      if (result.success) {
        var token = result.customer.paymentMethods[0].token;
        gateway.subscription.create({
          paymentMethodToken: token,
          planId: plan,
          firstBillingDate: startDate
        }, function (err, result) {
            if (result.success || result.subscription) {
              res.redirect('checkouts/' + result.subscription.id);
          } else {
              var transactionErrors = result.errors.deepErrors();
              req.flash('error', {msg: formatErrors(transactionErrors)});
              res.redirect('checkouts/new');
            }
          });
  } else {
      res.redirect('/');
    }
  });

  // gateway.transaction.sale({
  //   amount: amount,
  //   paymentMethodNonce: nonce
  // }, function (err, result) {
  //   if (result.success || result.transaction) {
  //     res.redirect('checkouts/' + result.transaction.id);
  //   } else {
  //     transactionErrors = result.errors.deepErrors();
  //     req.flash('error', {msg: formatErrors(transactionErrors)});
  //     res.redirect('checkouts/new');
  //   }
  // });
});

module.exports = router;
<commit_msg>Update index.js<commit_after>'use strict';

var express = require('express');
var braintree = require('braintree');
var router = express.Router(); // eslint-disable-line new-cap
var gateway = require('../lib/gateway');

  var SUBSCRIPTION_SUCCESS_STATUSES = [
    braintree.Subscription.Status.Active,
    braintree.Subscription.Status.Canceled,
    braintree.Subscription.Status.Expired,
    braintree.Subscription.Status.PastDue,
    braintree.Subscription.Status.Pending
   ];

function formatErrors(errors) {
  var formattedErrors = '';

  for (var i in errors) { // eslint-disable-line no-inner-declarations, vars-on-top
    if (errors.hasOwnProperty(i)) {
      formattedErrors += 'Error: ' + errors[i].code + ': ' + errors[i].message + '\n';
    }
  }
  return formattedErrors;
}

function createResultObject(subscription) {
  var result;
  var status = subscription.status;

  if (SUBSCRIPTION_SUCCESS_STATUSES.indexOf(status) !== -1) {
    result = {
      header: 'Welcome to Coder Kids!',
      icon: 'success',
      message: 'Your membership enrollment is now complete. Please review membership details and contact us at hello@coder-kids.com with any questions. Once you have reviewed your membership details, click the button below to schedule your CoderKid.'
    };
  } else {
    result = {
      header: 'Transaction Failed',
      icon: 'fail',
      message: 'There is an issue with this transaction. Please contact us at hello@coder-kids.com.'
    };
  }

  return result;
}

router.get('/', function (req, res) {
  res.redirect('/checkouts/new');
});

router.get('/checkouts/new', function (req, res) {
  gateway.clientToken.generate({}, function (err, response) {
    res.render('checkouts/new', {clientToken: response.clientToken, messages: req.flash('error')});
  });
});

router.get('/checkouts/:id', function (req, res) {
  var result;
  var subscriptionId = req.params.id;
  gateway.subscription.find(subscriptionId, function (err, subscription) {
    result = createResultObject(subscription);
    res.render('checkouts/show', {subscription: subscription, result: result});
  });
});

router.post('/checkouts', function (req, res) {
  var transactionErrors;
  var plan = req.body.selectedPlan;
  var firstName = req.body.firstName;
  var lastName = req.body.lastName;
  var email = req.body.email;
  var phoneNumber = req.body.phone;
  var referralName = req.body.referralName;
  var childFirstName = req.body.childfirstname;
  var childLastName = req.body.childlastname;
  var childAge = req.body.childage;
  var initialCourse = req.body.initialcourse;
  var nonce = req.body.payment_method_nonce;
  var startDate = new Date(Date.UTC(2016, 10, 6, 0, 0, 0));

  gateway.customer.create({
  paymentMethodNonce: nonce,
  firstName: firstName,
  lastName: lastName,
  email: email,
  phone: phoneNumber
  customFields: {
    initialcourse: initialCourse,
    childage: childAge,
    childlastname: childLastName,
    childfirstname: childFirstName,
    referralname: referralName
  }
  }, function (err, result) {
      if (result.success) {
        var token = result.customer.paymentMethods[0].token;
        gateway.subscription.create({
          paymentMethodToken: token,
          planId: plan,
          firstBillingDate: startDate
        }, function (err, result) {
            if (result.success || result.subscription) {
              res.redirect('checkouts/' + result.subscription.id);
          } else {
              var transactionErrors = result.errors.deepErrors();
              req.flash('error', {msg: formatErrors(transactionErrors)});
              res.redirect('checkouts/new');
            }
          });
  } else {
      res.redirect('/');
    }
  });

  // gateway.transaction.sale({
  //   amount: amount,
  //   paymentMethodNonce: nonce
  // }, function (err, result) {
  //   if (result.success || result.transaction) {
  //     res.redirect('checkouts/' + result.transaction.id);
  //   } else {
  //     transactionErrors = result.errors.deepErrors();
  //     req.flash('error', {msg: formatErrors(transactionErrors)});
  //     res.redirect('checkouts/new');
  //   }
  // });
});

module.exports = router;
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

module.exports = router;
<commit_msg>adidng routes for the login<commit_after>var express = require('express');
var passport = require('passport');
var router = express.Router();

router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

router.get('/login', function(req, res, next) {
  res.render('login', { title: 'Express' });
});

router.post('/login', passport.authenticate('login', {
  successRedirect: '/user',
  faulureRedirect: '/login',
  failureFlash: true
}));

module.exports = router;
<|endoftext|>


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

/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

// // Goal
// //
// // Map https://{user}-components.appmaker.mozillalabs.com/{component-name}/(.*)
// // to proxy for
// // http://{user}.github.io/{component-name}/{(.*)}

// Couldn't get this working with node-http-proxy library, so went with simpler
// http://www.catonmat.net/http-proxy-in-nodejs/

var http = require('http');
var httpProxy = require('http-proxy');
var url = require('url');
var cors = require('cors');

var proxy = new httpProxy.RoutingProxy();

module.exports = {
  gitHubComponent: function(request, response) {
    var urlObj = url.parse(request.url);
    var user = request.headers.host.match(/^(.*)-components\/*/)[1]
    var path = urlObj.pathname.split('/');
    var componentName = path[0];
    var fileName = path.slice(1).join('/');
    var target = 'http://' + user + '.github.io/' + componentName + fileName;
    console.log('proxying %s to %s', request.url, target);
    var proxy_request = http.request(target);
    proxy_request.headers = request.headers;
    proxy_request.addListener('response', function (proxy_response) {
      proxy_response.addListener('data', function(chunk) {
        response.write(chunk, 'binary');
      });
      proxy_response.addListener('end', function() {
        response.end();
      });
      response.writeHead(proxy_response.statusCode, proxy_response.headers);
    });
    request.addListener('data', function(chunk) {
      proxy_request.write(chunk, 'binary');
    });
    request.addListener('end', function() {
      proxy_request.end();
    });
  },

  cors: function(req, resp){
    //TODO: So much error handling.

    // Host pulled from url mapping in app.js
    var host = req.params.host.split(":");
    var port = 80;

    if (host[1]){
      port = parseInt(host[1]);
    }

    host = host[0];

    //This is the first and only wildcard match
    req.url = "/" + req.params[0];

    req.headers.host = host;
    proxy.proxyRequest(req, resp, {

      host: host,
      port: port
    });
  }

};
<commit_msg>unused dependency<commit_after>#!/usr/bin/env node

/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

// // Goal
// //
// // Map https://{user}-components.appmaker.mozillalabs.com/{component-name}/(.*)
// // to proxy for
// // http://{user}.github.io/{component-name}/{(.*)}

// Couldn't get this working with node-http-proxy library, so went with simpler
// http://www.catonmat.net/http-proxy-in-nodejs/

var http = require('http');
var httpProxy = require('http-proxy');
var url = require('url');

var proxy = new httpProxy.RoutingProxy();

module.exports = {
  gitHubComponent: function(request, response) {
    var urlObj = url.parse(request.url);
    var user = request.headers.host.match(/^(.*)-components\/*/)[1]
    var path = urlObj.pathname.split('/');
    var componentName = path[0];
    var fileName = path.slice(1).join('/');
    var target = 'http://' + user + '.github.io/' + componentName + fileName;
    console.log('proxying %s to %s', request.url, target);
    var proxy_request = http.request(target);
    proxy_request.headers = request.headers;
    proxy_request.addListener('response', function (proxy_response) {
      proxy_response.addListener('data', function(chunk) {
        response.write(chunk, 'binary');
      });
      proxy_response.addListener('end', function() {
        response.end();
      });
      response.writeHead(proxy_response.statusCode, proxy_response.headers);
    });
    request.addListener('data', function(chunk) {
      proxy_request.write(chunk, 'binary');
    });
    request.addListener('end', function() {
      proxy_request.end();
    });
  },

  cors: function(req, resp){
    //TODO: So much error handling.

    // Host pulled from url mapping in app.js
    var host = req.params.host.split(":");
    var port = 80;

    if (host[1]){
      port = parseInt(host[1]);
    }

    host = host[0];

    //This is the first and only wildcard match
    req.url = "/" + req.params[0];

    req.headers.host = host;
    proxy.proxyRequest(req, resp, {

      host: host,
      port: port
    });
  }

};
<|endoftext|>


<commit_before>Werld.Models.Base.Creature = Backbone.Model.extend({
  defaults: {
    lastAttackAt: Number.NEGATIVE_INFINITY
  },
  initialize: function() {
    var stats = this.get('stats');
    var coordinates = _.clone(this.get('coordinates'));
    var fixedCoordinates;

    if (this.get('fixed')) {
      fixedCoordinates = coordinates;
    }

    this.set({
      status: 'alive',
      hitPoints: stats.strength,
      maxHitPoints: stats.strength,
      mana: stats.intelligence,
      maxMana: stats.intelligence,
      stamina: stats.dexterity,
      maxStamina: stats.dexterity,
      destination: coordinates,
      messages: [],
      fixedCoordinates: fixedCoordinates
    });

    this.messagesSweeperIntervalId = setInterval(
      _.bind(this.messagesSweeper, this),
      Werld.Config.MESSAGE_SWEEPER_POLLING_INTERVAL
    );

    this.movementHandlerIntervalId = setInterval(
      _.bind(this.movementHandler, this), Werld.Config.FRAME_RATE()
    );

    this.hitPointsObserverIntervalId = setInterval(
      _.bind(this.hitPointsObserver, this), Werld.Config.FRAME_RATE()
    );
  },
  say: function(message) {
    var now = new Date();
    var messages = this.get('messages');

    messages.unshift({
      type: 'speech', content: message, created_at: now.getTime()
    });
    this.set({ messages: messages });
  },
  move: function(destinationTile) {
    var mapDestinationTile;

    this.follow(null);

    if (this.get('fixed')) {
      var fixedCoordinates = this.get('fixedCoordinates');
      var coordinates = this.get('coordinates');

      var tileOffset = [
        destinationTile[0] - Werld.util.pixelToTile(fixedCoordinates[0]),
        destinationTile[1] - Werld.util.pixelToTile(fixedCoordinates[1])
      ];

      mapDestinationTile = [
        Werld.util.pixelToTile(coordinates[0]) + tileOffset[0],
        Werld.util.pixelToTile(coordinates[1]) + tileOffset[1]
      ];

    } else {
      mapDestinationTile = destinationTile;
    }

    if (mapDestinationTile[0] < 0) {
      mapDestinationTile[0] = 0;
    } else if (mapDestinationTile[0] >= Werld.Config.WORLD_MAP_DIMENSIONS[0]) {
      mapDestinationTile[0] = Werld.Config.WORLD_MAP_DIMENSIONS[1] - 1;
    }

    if (mapDestinationTile[1] < 0) {
      mapDestinationTile[1] = 0;
    } else if (mapDestinationTile[1] >= Werld.Config.WORLD_MAP_DIMENSIONS[0]) {
      mapDestinationTile[1] = Werld.Config.WORLD_MAP_DIMENSIONS[1] - 1;
    }

    this.set({
      destination: _(mapDestinationTile).map(function(column) {
        return(Werld.util.tileToPixel(column));
      })
    });
  },
  movementHandler: function() {
    if (this.get('following')) {
      this.set({ destination: _.clone(this.get('following').get('coordinates')) });
    }

    var coordinates = this.get('coordinates');
    var destination = this.get('destination');
    var movementSpeed = this.get('MOVEMENT_SPEED');

    if (coordinates[0] > destination[0]) {
      coordinates[0] -= movementSpeed;
    } else if (coordinates[0] < destination[0]) {
      coordinates[0] += movementSpeed;
    }

    if (coordinates[1] > destination[1]) {
      coordinates[1] -= movementSpeed;
    } else if (coordinates[1] < destination[1]) {
      coordinates[1] += movementSpeed;
    }

    this.set({ coordinates: coordinates });
    /* TODO: figure out why set() isn't triggering the change event and remove
     *       this hack. */
    this.trigger('change:coordinates');
  },
  follow: function(creature) {
    this.set({ following: creature });
  },
  damage: function() {
    var stats = this.get('stats');
    var boundaries = this.get('BOUNDARIES');
    var criticalHitChance = (stats.dexterity *
                               boundaries.MAX_CRITICAL_HIT_CHANCE /
                               boundaries.MAX_DEXTERITY) / 100;
    var critical = Math.random() < criticalHitChance;
    var damage = stats.strength / 10;
    return(critical ? damage * 2 : damage);
  },
  attackSpeed: function() {
    return(((-4 * this.get('stats').dexterity / 125) + 5) * 1000);
  },
  attack: function(creature) {
    this.battleHandlerIntervalId = setInterval(
      _.bind(this.battleHandler, this), Werld.Config.FRAME_RATE()
    );
    this.follow(creature);
    this.set({ attacking: creature });
    creature.acknowledgeAttack(this);
  },
  acknowledgeAttack: function(attacker) {
    if (this.get('attacker') !== attacker) {
      this.set({ attacker: attacker });
      this.attack(attacker);
    }
  },
  stopAttacking: function(creature) {
    clearInterval(this.battleHandlerIntervalId);
    this.set({ attacking: null });
    this.follow(null);
    creature.acknowledgeAttackStop(this);
  },
  acknowledgeAttackStop: function(attacker) {
    this.set({ attacker: null });
  },
  hit: function(creature) {
    creature.receiveHit(this.damage());
  },
  receiveHit: function(damage) {
    var now = new Date();
    var messages = this.get('messages');

    this.set({ hitPoints: this.get('hitPoints') - damage });
    messages.unshift({
      type: 'hit', content: damage, created_at: now.getTime()
    });
    this.set({ messages: messages });
  },
  battleHandler: function() {
    var attackedCreature = this.get('attacking');

    if (attackedCreature) {
      if (attackedCreature.alive()) {
        var coordinates = this.get('coordinates');
        var attackedCreatureCoordinates = attackedCreature.get('coordinates');
        var distance =
          Werld.util.pixelDistance(coordinates, attackedCreatureCoordinates);
        var lastAttackAt = this.get('lastAttackAt');
        var now = new Date();

        if (distance <= Werld.Config.PIXELS_PER_TILE &&
              (now.getTime() - lastAttackAt) >= this.attackSpeed()) {
          this.set({ lastAttackAt: now.getTime() });
          this.hit(attackedCreature);
        }
      } else {
        this.stopAttacking(attackedCreature);
      }
    }
  },
  alive: function() {
    return(this.get('status') === 'alive');
  },
  dead: function() {
    return(this.get('status') === 'dead');
  },
  die: function() {
    if (this.get('attacking')) {
      this.stopAttacking(this.get('attacking'));
    } else {
      this.follow(null);
    }
    this.set({
      status: 'dead',
      hitPoints: 0,
      mana: 0,
      stamina: 0,
      messages: []
    });
  },
  resurrect: function() {
    this.set({
      status: 'alive',
      hitPoints: 1
    });
  },
  hitPointsObserver: function() {
    if (this.dead()) {
      if (this.get('hitPoints') > 0) {
        this.resurrect();
      }
    } else {
      if (this.get('hitPoints') <= 0) {
        this.die();
      }
    }
  },
  loot: function() {
  },
  messagesSweeper: function() {
    var now = new Date();
    var self = this;
    _(this.get('messages')).each(function(message) {
      if ((now.getTime() - message.created_at) > Werld.Config.MESSAGE_LIFE_CYCLE) {
        var messages = self.get('messages');
        messages.pop();
        self.set({ messages: messages });
      }
    });
  }
});
<commit_msg>Only set HP to 1 if it was <= 0.<commit_after>Werld.Models.Base.Creature = Backbone.Model.extend({
  defaults: {
    lastAttackAt: Number.NEGATIVE_INFINITY
  },
  initialize: function() {
    var stats = this.get('stats');
    var coordinates = _.clone(this.get('coordinates'));
    var fixedCoordinates;

    if (this.get('fixed')) {
      fixedCoordinates = coordinates;
    }

    this.set({
      status: 'alive',
      hitPoints: stats.strength,
      maxHitPoints: stats.strength,
      mana: stats.intelligence,
      maxMana: stats.intelligence,
      stamina: stats.dexterity,
      maxStamina: stats.dexterity,
      destination: coordinates,
      messages: [],
      fixedCoordinates: fixedCoordinates
    });

    this.messagesSweeperIntervalId = setInterval(
      _.bind(this.messagesSweeper, this),
      Werld.Config.MESSAGE_SWEEPER_POLLING_INTERVAL
    );

    this.movementHandlerIntervalId = setInterval(
      _.bind(this.movementHandler, this), Werld.Config.FRAME_RATE()
    );

    this.hitPointsObserverIntervalId = setInterval(
      _.bind(this.hitPointsObserver, this), Werld.Config.FRAME_RATE()
    );
  },
  say: function(message) {
    var now = new Date();
    var messages = this.get('messages');

    messages.unshift({
      type: 'speech', content: message, created_at: now.getTime()
    });
    this.set({ messages: messages });
  },
  move: function(destinationTile) {
    var mapDestinationTile;

    this.follow(null);

    if (this.get('fixed')) {
      var fixedCoordinates = this.get('fixedCoordinates');
      var coordinates = this.get('coordinates');

      var tileOffset = [
        destinationTile[0] - Werld.util.pixelToTile(fixedCoordinates[0]),
        destinationTile[1] - Werld.util.pixelToTile(fixedCoordinates[1])
      ];

      mapDestinationTile = [
        Werld.util.pixelToTile(coordinates[0]) + tileOffset[0],
        Werld.util.pixelToTile(coordinates[1]) + tileOffset[1]
      ];

    } else {
      mapDestinationTile = destinationTile;
    }

    if (mapDestinationTile[0] < 0) {
      mapDestinationTile[0] = 0;
    } else if (mapDestinationTile[0] >= Werld.Config.WORLD_MAP_DIMENSIONS[0]) {
      mapDestinationTile[0] = Werld.Config.WORLD_MAP_DIMENSIONS[1] - 1;
    }

    if (mapDestinationTile[1] < 0) {
      mapDestinationTile[1] = 0;
    } else if (mapDestinationTile[1] >= Werld.Config.WORLD_MAP_DIMENSIONS[0]) {
      mapDestinationTile[1] = Werld.Config.WORLD_MAP_DIMENSIONS[1] - 1;
    }

    this.set({
      destination: _(mapDestinationTile).map(function(column) {
        return(Werld.util.tileToPixel(column));
      })
    });
  },
  movementHandler: function() {
    if (this.get('following')) {
      this.set({ destination: _.clone(this.get('following').get('coordinates')) });
    }

    var coordinates = this.get('coordinates');
    var destination = this.get('destination');
    var movementSpeed = this.get('MOVEMENT_SPEED');

    if (coordinates[0] > destination[0]) {
      coordinates[0] -= movementSpeed;
    } else if (coordinates[0] < destination[0]) {
      coordinates[0] += movementSpeed;
    }

    if (coordinates[1] > destination[1]) {
      coordinates[1] -= movementSpeed;
    } else if (coordinates[1] < destination[1]) {
      coordinates[1] += movementSpeed;
    }

    this.set({ coordinates: coordinates });
    /* TODO: figure out why set() isn't triggering the change event and remove
     *       this hack. */
    this.trigger('change:coordinates');
  },
  follow: function(creature) {
    this.set({ following: creature });
  },
  damage: function() {
    var stats = this.get('stats');
    var boundaries = this.get('BOUNDARIES');
    var criticalHitChance = (stats.dexterity *
                               boundaries.MAX_CRITICAL_HIT_CHANCE /
                               boundaries.MAX_DEXTERITY) / 100;
    var critical = Math.random() < criticalHitChance;
    var damage = stats.strength / 10;
    return(critical ? damage * 2 : damage);
  },
  attackSpeed: function() {
    return(((-4 * this.get('stats').dexterity / 125) + 5) * 1000);
  },
  attack: function(creature) {
    this.battleHandlerIntervalId = setInterval(
      _.bind(this.battleHandler, this), Werld.Config.FRAME_RATE()
    );
    this.follow(creature);
    this.set({ attacking: creature });
    creature.acknowledgeAttack(this);
  },
  acknowledgeAttack: function(attacker) {
    if (this.get('attacker') !== attacker) {
      this.set({ attacker: attacker });
      this.attack(attacker);
    }
  },
  stopAttacking: function(creature) {
    clearInterval(this.battleHandlerIntervalId);
    this.set({ attacking: null });
    this.follow(null);
    creature.acknowledgeAttackStop(this);
  },
  acknowledgeAttackStop: function(attacker) {
    this.set({ attacker: null });
  },
  hit: function(creature) {
    creature.receiveHit(this.damage());
  },
  receiveHit: function(damage) {
    var now = new Date();
    var messages = this.get('messages');

    this.set({ hitPoints: this.get('hitPoints') - damage });
    messages.unshift({
      type: 'hit', content: damage, created_at: now.getTime()
    });
    this.set({ messages: messages });
  },
  battleHandler: function() {
    var attackedCreature = this.get('attacking');

    if (attackedCreature) {
      if (attackedCreature.alive()) {
        var coordinates = this.get('coordinates');
        var attackedCreatureCoordinates = attackedCreature.get('coordinates');
        var distance =
          Werld.util.pixelDistance(coordinates, attackedCreatureCoordinates);
        var lastAttackAt = this.get('lastAttackAt');
        var now = new Date();

        if (distance <= Werld.Config.PIXELS_PER_TILE &&
              (now.getTime() - lastAttackAt) >= this.attackSpeed()) {
          this.set({ lastAttackAt: now.getTime() });
          this.hit(attackedCreature);
        }
      } else {
        this.stopAttacking(attackedCreature);
      }
    }
  },
  alive: function() {
    return(this.get('status') === 'alive');
  },
  dead: function() {
    return(this.get('status') === 'dead');
  },
  die: function() {
    if (this.get('attacking')) {
      this.stopAttacking(this.get('attacking'));
    } else {
      this.follow(null);
    }
    this.set({
      status: 'dead',
      hitPoints: 0,
      mana: 0,
      stamina: 0,
      messages: []
    });
  },
  resurrect: function() {
    this.set({ status: 'alive' });
    if (this.get('hitPoints') <= 0) {
      this.set({ hitPoints: 1 });
    }
  },
  hitPointsObserver: function() {
    if (this.dead()) {
      if (this.get('hitPoints') > 0) {
        this.resurrect();
      }
    } else {
      if (this.get('hitPoints') <= 0) {
        this.die();
      }
    }
  },
  loot: function() {
  },
  messagesSweeper: function() {
    var now = new Date();
    var self = this;
    _(this.get('messages')).each(function(message) {
      if ((now.getTime() - message.created_at) > Werld.Config.MESSAGE_LIFE_CYCLE) {
        var messages = self.get('messages');
        messages.pop();
        self.set({ messages: messages });
      }
    });
  }
});
<|endoftext|>