<commit_before>import { difference, reduce, values } from 'lodash';
import React from 'react';
import PropTypes from 'prop-types';
import { Label, Button } from 'react-bootstrap';
import { Link } from 'react-router';
import { LinkContainer } from 'react-router-bootstrap';
import moment from 'moment';

import ConsortiumResultMeta from './consortium/consortium-result-meta.js';

function getWaitingOnUsers({
  usernames: allUsernames,
  pluginState: {
    'group-step': groupStep,
  },
}) {
  const currentUsernames = Object.keys(groupStep.userStep);
  const currentStep = groupStep.step;

  if (allUsernames.length !== Object.keys(groupStep.userStep).length) {
    return difference(allUsernames, currentUsernames);
  } else if (values(groupStep.userStep).some(step => step !== currentStep)) {
    return reduce(groupStep.userStep, (memo, step, username) => (
      step !== currentStep ? memo.concat(username) : memo
    ), []);
  }

  return [];
}

export default function StatusItem({
  computation,
  consortium,
  remoteResult,
}) {
  let heading;
  let indicator;
  let waitingOn;
  let resultButton = null;

  if (remoteResult.userErrors.length) {
    indicator = Error;
  } else if (remoteResult.complete) {
    indicator = Complete;
    resultButton = (<LinkContainer to={`/consortia/${consortium._id}/${computation._id}`}>
      <Button bsStyle="default" className="pull-right">View Results</Button></LinkContainer>);
  } else {
    indicator = In Progress;
  }

  if (remoteResult && !remoteResult.complete) {
    const waitingOnUsers = getWaitingOnUsers(remoteResult);

    if (waitingOnUsers.length) {
      waitingOn = (

          Waiting on:
          {' '}
          {waitingOnUsers.join(', ')}

      );
    }
  }

  if (remoteResult.endDate) {
    heading = `Ended ${moment(remoteResult.endDate).fromNow()}`;
  } else {
    heading = `Started ${moment(remoteResult.startDate).fromNow()}`;
  }

  return (

          {heading}
          {' '}
          {indicator}

            Consortium:
            {' '}
            <Link to={`/consortia/${consortium._id}`}>{consortium.label}</Link>

          {waitingOn}

        <ConsortiumResultMeta
          computation={computation}
          computationInputs={remoteResult.computationInputs}
          step={remoteResult.pluginState['group-step'].step}
          usernames={remoteResult.usernames}
        />
        {resultButton}

  );
}

StatusItem.propTypes = {
  consortium: PropTypes.shape({
    _id: PropTypes.string.isRequired,
    label: PropTypes.string.isRequired,
  }).isRequired,
  computation: PropTypes.shape({
    name: PropTypes.string.isRequired,
    version: PropTypes.string.isRequired,
  }).isRequired,
  remoteResult: PropTypes.shape({
    computationInputs: PropTypes.arrayOf(PropTypes.array).isRequired,
    endDate: PropTypes.number,
    pipelineState: PropTypes.shape({
      step: PropTypes.number.isRequired,
    }).isRequired,
    pluginState: PropTypes.shape({
      'group-step': PropTypes.object,
    }),
    startDate: PropTypes.number.isRequired,
    usernames: PropTypes.arrayOf(PropTypes.string).isRequired,
  }),
};
<commit_msg>updated existing status-item link<commit_after>import { difference, reduce, values } from 'lodash';
import React from 'react';
import PropTypes from 'prop-types';
import { Label, Button } from 'react-bootstrap';
import { Link } from 'react-router';
import { LinkContainer } from 'react-router-bootstrap';
import moment from 'moment';

import ConsortiumResultMeta from './consortium/consortium-result-meta.js';

function getWaitingOnUsers({
  usernames: allUsernames,
  pluginState: {
    'group-step': groupStep,
  },
}) {
  const currentUsernames = Object.keys(groupStep.userStep);
  const currentStep = groupStep.step;

  if (allUsernames.length !== Object.keys(groupStep.userStep).length) {
    return difference(allUsernames, currentUsernames);
  } else if (values(groupStep.userStep).some(step => step !== currentStep)) {
    return reduce(groupStep.userStep, (memo, step, username) => (
      step !== currentStep ? memo.concat(username) : memo
    ), []);
  }

  return [];
}

export default function StatusItem({
  computation,
  consortium,
  remoteResult,
}) {
  let heading;
  let indicator;
  let waitingOn;
  let resultButton = null;

  if (remoteResult.userErrors.length) {
    indicator = Error;
  } else if (remoteResult.complete) {
    indicator = Complete;
    resultButton = (<LinkContainer to={`/consortia/${consortium._id}/${computation._id}`}>
      <Button bsStyle="default" className="pull-right">View Results</Button></LinkContainer>);
  } else {
    indicator = In Progress;
  }

  if (remoteResult && !remoteResult.complete) {
    const waitingOnUsers = getWaitingOnUsers(remoteResult);

    if (waitingOnUsers.length) {
      waitingOn = (

          Waiting on:
          {' '}
          {waitingOnUsers.join(', ')}

      );
    }
  }

  if (remoteResult.endDate) {
    heading = `Ended ${moment(remoteResult.endDate).fromNow()}`;
  } else {
    heading = `Started ${moment(remoteResult.startDate).fromNow()}`;
  }

  return (

          {heading}
          {' '}
          {indicator}

            Consortium:
            {' '}
            <Link to={`/consortia/${consortium._id}/${computation._id}`}>{consortium.label}</Link>

          {waitingOn}

        <ConsortiumResultMeta
          computation={computation}
          computationInputs={remoteResult.computationInputs}
          step={remoteResult.pluginState['group-step'].step}
          usernames={remoteResult.usernames}
        />
        {resultButton}

  );
}

StatusItem.propTypes = {
  consortium: PropTypes.shape({
    _id: PropTypes.string.isRequired,
    label: PropTypes.string.isRequired,
  }).isRequired,
  computation: PropTypes.shape({
    name: PropTypes.string.isRequired,
    version: PropTypes.string.isRequired,
  }).isRequired,
  remoteResult: PropTypes.shape({
    computationInputs: PropTypes.arrayOf(PropTypes.array).isRequired,
    endDate: PropTypes.number,
    pipelineState: PropTypes.shape({
      step: PropTypes.number.isRequired,
    }).isRequired,
    pluginState: PropTypes.shape({
      'group-step': PropTypes.object,
    }),
    startDate: PropTypes.number.isRequired,
    usernames: PropTypes.arrayOf(PropTypes.string).isRequired,
  }),
};
<|endoftext|>


<commit_before>import DataStore from 'flux/stores/DataStore.js'

class Home extends React.Component {
    render() {
        return (

Home

Initial template project to show how we can fetch data, for now pages and posts from wordpress in a react project.
                    The data will be whatever you add in your wordpress installation. Try it out! :)

        );
    }
}

export default Home;
<commit_msg>Testing jenkins build hook<commit_after>import DataStore from 'flux/stores/DataStore.js'

class Home extends React.Component {
    render() {
        return (

Home

Initial template project to show how we can fetch data, for now pages and posts from wordpress in a react project.
                    The data will be whatever you add in your wordpress installation. Try it out! :)
                    Testing Jenkins

        );
    }
}

export default Home;
<|endoftext|>


<commit_before>/* continue.js -- A very easy and clean async flow controller
 *
 * Copyright (C) 2015 Chizhong Jin
 * All rights reserved.
 *
 * This software may be modified and distributed under the terms
 * of the BSD license.  See the LICENSE file for details.
 */

'use strict';

var func_length_n = function(n, func) {
  switch (n) {
    case 0:  return function() {return func(arguments)};
    case 1:  return function(a) {return func(arguments)};
    case 2:  return function(a, b) {return func(arguments)};
    case 3:  return function(a, b, c) {return func(arguments)};
    case 4:  return function(a, b, c, d) {return func(arguments)};
    case 5:  return function(a, b, c, d, e) {return func(arguments)};
    case 6:  return function(a, b, c, d, e, f) {return func(arguments)};
    case 7:  return function(a, b, c, d, e, f, g) {return func(arguments)};
    case 8:  return function(a, b, c, d, e, f, g, h) {return func(arguments)};
    case 9:  return function(a, b, c, d, e, f, g, h, i) {return func(arguments)};
    case 10: return function(a, b, c, d, e, f, g, h, i, j) {return func(arguments)};
    case 11: return function(a, b, c, d, e, f, g, h, i, j, k) {return func(arguments)};
    case 12: return function(a, b, c, d, e, f, g, h, i, j, k, l) {return func(arguments)};
    case 13: return function(a, b, c, d, e, f, g, h, i, j, k, l, m) {return func(arguments)};
    case 14: return function(a, b, c, d, e, f, g, h, i, j, k, l, m, n) {return func(arguments)};
    case 15: return function(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) {return func(arguments)};
    case 16: return function(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) {return func(arguments)};
    case 17: return function(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q) {return func(arguments)};
    case 18: return function(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r) {return func(arguments)};
    case 19: return function(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s) {return func(arguments)};
    case 20: return function(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t) {return func(arguments)};
    default: return function(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u) {return func(arguments)};
  }
};

var proto_C = {
  __proto__: Function,
  _c_call: function(args) {
    this.args = args;
    this.value = args[0];
    this.err = null;
    this._c_next.go(this);
  },
  _c_err: function(err) {
    this.err = err;
    this.args = {};
    this.value = null;
    this._c_next.go_err(this);
  },
  _c_invoke: function() {
    if (this.err) {
      this._c_next.go_err(this);
    } else {
      this._c_next.go(this);
    }
  },
  assigner: function() {
    var assign_vars = arguments;
    var c = this;
    var func = function(args) {
      c.err = null;
      c.args = args;
      c.value = args[0];
      for (var i = 0; i < assign_vars.length; ++i) {
        if (assign_vars[i] !== null) {
          c[assign_vars[i]] = args[i];
        }
      }
      c._c_invoke();
    };
    return func_length_n(arguments.length, func);
  },
  assigner2: function() {
    var assign_vars = arguments;
    var c = this;
    var func = function(args) {
      c.err = null;
      c.args = args;
      c.value = args[0];
      for (var i = 0; i < assign_vars.length / 2; ++i) {
        if (assign_vars[i * 2] !== null && assign_vars[i * 2 + 1] !== null) {
          assign_vars[i * 2][assign_vars[i * 2 + 1]] = args[i];
        }
      }
      c._c_invoke();
    };
    return func_length_n(arguments.length / 2, func);
  }
};

var C = function() {
  var c = function() {
    c._c_call(arguments);
  };
  c.__proto__ = proto_C;
  c.args = {};
  c.value = c.args[0];
  c.err = null;

  return c;
};

var N;
var proto_N = {
  __proto__: Function,
  genNext: function() {
    this.next = N();
    this.next.first = this.first;
    return this.next;
  },
  go: function(c) {
    c._c_next = this.next;
    if (this.kind === 'then') {
      try {
        this.func(c);
      }
      catch (err) {
        c._c_err(err);
      }
    } else if (this.kind === 'err') {
      this.next.go(c);
    } else if (this.kind === 'end') {
      if (this.func) {
        this.func(null, c);
      }
    }
  },
  go_err: function(c) {
    c._c_next = this.next;
    if (this.kind === 'then') {
      this.next.go_err(c);
    } else if (this.kind === 'err') {
      try {
        this.func.length == 2 ? this.func(c.err, c) : this.func(c);
      }
      catch (err2) {
        c._c_err(err2);
      }
    } else if (this.kind === 'end') {
      if (this.func) {
        this.func(c.err, c);
      } else {
        throw c.err;
      }
    }
  },
  then: function(func) {
    this.func = func;
    this.kind = 'then';
    return this.genNext();
  },
  err: function(func) {
    this.func = func;
    this.kind = 'err';
    return this.genNext();
  },
  end: function(func) {
    var c = C();

    this.func = func;
    this.kind = 'end';
    this.first.go(c);
  }
};

// alias
proto_N.done = proto_N.end;

N = function() {
  var n = function(func) {
    return func.length == 2 ? n.err(func) : n.then(func);
  };
  n.__proto__ = proto_N;
  return n;
};

var S = function(func) {
  var n = N();
  n.first = n;
  return n(func);
};

S.then = function(func) {
  var n = N();
  n.first = n;
  return n(func);
};

module.exports = S;

/*
S(function(c) {
  console.log(c.args);
  setTimeout(c, 500);
})(function(c) {
  console.log(c.args);
  c(123);
})(function(c) {
  console.log(c.args);
  throw 'show in next err capture';
})(function(c) {
  console.log('never show');
}).err(function(c) {
  console.log(c.err);
  c.v = 'pass by property';
  c();
})(function(c) {
  console.log(c.v);
  c();
}).end();
*/
<commit_msg>remove useless code<commit_after>/* continue.js -- A very easy and clean async flow controller
 *
 * Copyright (C) 2015 Chizhong Jin
 * All rights reserved.
 *
 * This software may be modified and distributed under the terms
 * of the BSD license.  See the LICENSE file for details.
 */

'use strict';

var func_length_n = function(n, func) {
  switch (n) {
    case 0:  return function() {return func(arguments)};
    case 1:  return function(a) {return func(arguments)};
    case 2:  return function(a, b) {return func(arguments)};
    case 3:  return function(a, b, c) {return func(arguments)};
    case 4:  return function(a, b, c, d) {return func(arguments)};
    case 5:  return function(a, b, c, d, e) {return func(arguments)};
    case 6:  return function(a, b, c, d, e, f) {return func(arguments)};
    case 7:  return function(a, b, c, d, e, f, g) {return func(arguments)};
    case 8:  return function(a, b, c, d, e, f, g, h) {return func(arguments)};
    case 9:  return function(a, b, c, d, e, f, g, h, i) {return func(arguments)};
    case 10: return function(a, b, c, d, e, f, g, h, i, j) {return func(arguments)};
    case 11: return function(a, b, c, d, e, f, g, h, i, j, k) {return func(arguments)};
    case 12: return function(a, b, c, d, e, f, g, h, i, j, k, l) {return func(arguments)};
    case 13: return function(a, b, c, d, e, f, g, h, i, j, k, l, m) {return func(arguments)};
    case 14: return function(a, b, c, d, e, f, g, h, i, j, k, l, m, n) {return func(arguments)};
    case 15: return function(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) {return func(arguments)};
    case 16: return function(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) {return func(arguments)};
    case 17: return function(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q) {return func(arguments)};
    case 18: return function(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r) {return func(arguments)};
    case 19: return function(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s) {return func(arguments)};
    case 20: return function(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t) {return func(arguments)};
    default: return function(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u) {return func(arguments)};
  }
};

var proto_C = {
  __proto__: Function,
  _c_call: function(args) {
    this.args = args;
    this.value = args[0];
    this.err = null;
    this._c_next.go(this);
  },
  _c_err: function(err) {
    this.err = err;
    this.args = {};
    this.value = null;
    this._c_next.go_err(this);
  },
  _c_invoke: function() {
    if (this.err) {
      this._c_next.go_err(this);
    } else {
      this._c_next.go(this);
    }
  },
  assigner: function() {
    var assign_vars = arguments;
    var c = this;
    var func = function(args) {
      c.err = null;
      c.args = args;
      c.value = args[0];
      for (var i = 0; i < assign_vars.length; ++i) {
        if (assign_vars[i] !== null) {
          c[assign_vars[i]] = args[i];
        }
      }
      c._c_invoke();
    };
    return func_length_n(arguments.length, func);
  },
  assigner2: function() {
    var assign_vars = arguments;
    var c = this;
    var func = function(args) {
      c.err = null;
      c.args = args;
      c.value = args[0];
      for (var i = 0; i < assign_vars.length / 2; ++i) {
        if (assign_vars[i * 2] !== null && assign_vars[i * 2 + 1] !== null) {
          assign_vars[i * 2][assign_vars[i * 2 + 1]] = args[i];
        }
      }
      c._c_invoke();
    };
    return func_length_n(arguments.length / 2, func);
  }
};

var C = function() {
  var c = function() {
    c._c_call(arguments);
  };
  c.__proto__ = proto_C;
  c.args = {};
  c.value = c.args[0];
  c.err = null;

  return c;
};

var N;
var proto_N = {
  __proto__: Function,
  genNext: function() {
    this.next = N();
    this.next.first = this.first;
    return this.next;
  },
  go: function(c) {
    c._c_next = this.next;
    if (this.kind === 'then') {
      try {
        this.func(c);
      }
      catch (err) {
        c._c_err(err);
      }
    } else if (this.kind === 'err') {
      this.next.go(c);
    } else if (this.kind === 'end') {
      if (this.func) {
        this.func(null, c);
      }
    }
  },
  go_err: function(c) {
    c._c_next = this.next;
    if (this.kind === 'then') {
      this.next.go_err(c);
    } else if (this.kind === 'err') {
      try {
        this.func.length == 2 ? this.func(c.err, c) : this.func(c);
      }
      catch (err2) {
        c._c_err(err2);
      }
    } else if (this.kind === 'end') {
      if (this.func) {
        this.func(c.err, c);
      } else {
        throw c.err;
      }
    }
  },
  then: function(func) {
    this.func = func;
    this.kind = 'then';
    return this.genNext();
  },
  err: function(func) {
    this.func = func;
    this.kind = 'err';
    return this.genNext();
  },
  end: function(func) {
    var c = C();

    this.func = func;
    this.kind = 'end';
    this.first.go(c);
  }
};

// alias
proto_N.done = proto_N.end;

N = function() {
  var n = function(func) {
    return func.length == 2 ? n.err(func) : n.then(func);
  };
  n.__proto__ = proto_N;
  return n;
};

var S = function(func) {
  var n = N();
  n.first = n;
  return n(func);
};

S.then = function(func) {
  var n = N();
  n.first = n;
  return n(func);
};

module.exports = S;
<|endoftext|>


<commit_before>/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Ajax.org Code Editor (ACE).
 *
 * The Initial Developer of the Original Code is
 * Ajax.org B.V.
 * Portions created by the Initial Developer are Copyright (C) 2010
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *      Fabian Jakobs <fabian AT ajax DOT org>
 *      Julian Viereck <julian.viereck@gmail.com>
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

define(function(require, exports, module) {

var oop = require("pilot/oop");
var lang = require("pilot/lang");
var EventEmitter = require("pilot/event_emitter").EventEmitter;
var Range = require("ace/range").Range;

/**
 * Keeps cursor position and the text selection of an edit session.
 *
 * The row/columns used in the selection are in document coordinates
 * representing ths coordinates as thez appear in the document
 * before applying soft wrap and folding.
 */
var Selection = function(session) {
    this.session = session;
    this.doc = session.getDocument();

    this.clearSelection();
    this.selectionLead = this.doc.createAnchor(0, 0);
    this.selectionAnchor = this.doc.createAnchor(0, 0);

    var _self = this;
    this.selectionLead.on("change", function(e) {
        _self._dispatchEvent("changeCursor");
        if (!_self.$isEmpty)
            _self._dispatchEvent("changeSelection");
        if (!_self.$preventUpdateDesiredColumnOnChange && e.old.column != e.value.column)
            _self.$updateDesiredColumn();
    });

    this.selectionAnchor.on("change", function() {
        if (!_self.$isEmpty)
            _self._dispatchEvent("changeSelection");
    });
};

(function() {

    oop.implement(this, EventEmitter);

    this.isEmpty = function() {
        return (this.$isEmpty || (
            this.selectionAnchor.row == this.selectionLead.row &&
            this.selectionAnchor.column == this.selectionLead.column
        ));
    };

    this.isMultiLine = function() {
        if (this.isEmpty()) {
            return false;
        }

        return this.getRange().isMultiLine();
    };

    this.getCursor = function() {
        return this.selectionLead.getPosition();
    };

    this.setSelectionAnchor = function(row, column) {
        this.selectionAnchor.setPosition(row, column);

        if (this.$isEmpty) {
            this.$isEmpty = false;
            this._dispatchEvent("changeSelection");
        }
    };

    this.getSelectionAnchor = function() {
        if (this.$isEmpty)
            return this.getSelectionLead()
        else
            return this.selectionAnchor.getPosition();
    };

    this.getSelectionLead = function() {
        return this.selectionLead.getPosition();
    };

    this.shiftSelection = function(columns) {
        if (this.$isEmpty) {
            this.moveCursorTo(this.selectionLead.row, this.selectionLead.column + columns);
            return;
        };

        var anchor = this.getSelectionAnchor();
        var lead = this.getSelectionLead();

        var isBackwards = this.isBackwards();

        if (!isBackwards || anchor.column !== 0)
            this.setSelectionAnchor(anchor.row, anchor.column + columns);

        if (isBackwards || lead.column !== 0) {
            this.$moveSelection(function() {
                this.moveCursorTo(lead.row, lead.column + columns);
            });
        }
    };

    this.isBackwards = function() {
        var anchor = this.selectionAnchor;
        var lead = this.selectionLead;
        return (anchor.row > lead.row || (anchor.row == lead.row && anchor.column > lead.column));
    };

    this.getRange = function() {
        var anchor = this.selectionAnchor;
        var lead = this.selectionLead;

        if (this.isEmpty())
            return Range.fromPoints(lead, lead);

        if (this.isBackwards()) {
            return Range.fromPoints(lead, anchor);
        }
        else {
            return Range.fromPoints(anchor, lead);
        }
    };

    this.clearSelection = function() {
        if (!this.$isEmpty) {
            this.$isEmpty = true;
            this._dispatchEvent("changeSelection");
        }
    };

    this.selectAll = function() {
        var lastRow = this.doc.getLength() - 1;
        this.setSelectionAnchor(lastRow, this.doc.getLine(lastRow).length);
        this.moveCursorTo(0, 0);
    };

    this.setSelectionRange = function(range, reverse) {
        if (reverse) {
            this.setSelectionAnchor(range.end.row, range.end.column);
            this.selectTo(range.start.row, range.start.column);
        } else {
            this.setSelectionAnchor(range.start.row, range.start.column);
            this.selectTo(range.end.row, range.end.column);
        }
        this.$updateDesiredColumn();
    };

    this.$updateDesiredColumn = function() {
        var cursor = this.getCursor();
        this.$desiredColumn = this.session.documentToScreenColumn(cursor.row, cursor.column);
    };

    this.$moveSelection = function(mover) {
        var lead = this.selectionLead;
        if (this.$isEmpty)
            this.setSelectionAnchor(lead.row, lead.column);

        mover.call(this);
    };

    this.selectTo = function(row, column) {
        this.$moveSelection(function() {
            this.moveCursorTo(row, column);
        });
    };

    this.selectToPosition = function(pos) {
        this.$moveSelection(function() {
            this.moveCursorToPosition(pos);
        });
    };

    this.selectUp = function() {
        this.$moveSelection(this.moveCursorUp);
    };

    this.selectDown = function() {
        this.$moveSelection(this.moveCursorDown);
    };

    this.selectRight = function() {
        this.$moveSelection(this.moveCursorRight);
    };

    this.selectLeft = function() {
        this.$moveSelection(this.moveCursorLeft);
    };

    this.selectLineStart = function() {
        this.$moveSelection(this.moveCursorLineStart);
    };

    this.selectLineEnd = function() {
        this.$moveSelection(this.moveCursorLineEnd);
    };

    this.selectFileEnd = function() {
        this.$moveSelection(this.moveCursorFileEnd);
    };

    this.selectFileStart = function() {
        this.$moveSelection(this.moveCursorFileStart);
    };

    this.selectWordRight = function() {
        this.$moveSelection(this.moveCursorWordRight);
    };

    this.selectWordLeft = function() {
        this.$moveSelection(this.moveCursorWordLeft);
    };

    this.selectWord = function() {
        var cursor = this.getCursor();
        var range  = this.session.getWordRange(cursor.row, cursor.column);
        this.setSelectionRange(range);
    };

    this.selectLine = function() {
        var rowStart = this.selectionLead.row;
        var rowEnd;

        var foldLine = this.session.getFoldLine(rowStart);
        if (foldLine) {
            rowStart = foldLine.start.row;
            rowEnd = foldLine.end.row;
        } else {
            rowEnd = rowStart;
        }
        this.setSelectionAnchor(rowStart, 0);
        this.$moveSelection(function() {
            this.moveCursorTo(rowEnd + 1, 0);
        });
    };

    this.moveCursorUp = function() {
        this.moveCursorBy(-1, 0);
    };

    this.moveCursorDown = function() {
        this.moveCursorBy(1, 0);
    };

    this.moveCursorLeft = function() {
        var cursor = this.selectionLead.getPosition(),
            fold;

        if (fold = this.session.getFoldAt(cursor.row, cursor.column, -1)) {
            this.moveCursorTo(fold.start.row, fold.start.column);
        } else if (cursor.column == 0) {
            // cursor is a line (start
            if (cursor.row > 0) {
                this.moveCursorTo(cursor.row - 1, this.doc.getLine(cursor.row - 1).length);
            }
        }
        else {
            var tabSize = this.session.getTabSize();
            if (this.session.isTabStop(cursor) && this.doc.getLine(cursor.row).slice(cursor.column-tabSize, cursor.column).split(" ").length-1 == tabSize)
                this.moveCursorBy(0, -tabSize);
            else
                this.moveCursorBy(0, -1);
        }
    };

    this.moveCursorRight = function() {
        var cursor = this.selectionLead.getPosition(),
            fold;
        if (fold = this.session.getFoldAt(cursor.row, cursor.column, 1)) {
            this.moveCursorTo(fold.end.row, fold.end.column);
        }
        else if (this.selectionLead.column == this.doc.getLine(this.selectionLead.row).length) {
            if (this.selectionLead.row < this.doc.getLength() - 1) {
                this.moveCursorTo(this.selectionLead.row + 1, 0);
            }
        }
        else {
            var tabSize = this.session.getTabSize();
            var cursor = this.selectionLead;
            if (this.session.isTabStop(cursor) && this.doc.getLine(cursor.row).slice(cursor.column, cursor.column+tabSize).split(" ").length-1 == tabSize)
                this.moveCursorBy(0, tabSize);
            else
                this.moveCursorBy(0, 1);
        }
    };

    this.moveCursorLineStart = function() {
        var row = this.selectionLead.row;
        var column = this.selectionLead.column;
        var screenRow = this.session.documentToScreenRow(row, column);

        // Determ the doc-position of the first character at the screen line.
        var firstColumnPosition = this.session.screenToDocumentPosition(screenRow, 0);

        // Determ the line
        var beforeCursor = this.session.getDisplayLine(
            row, null,
            firstColumnPosition.row, firstColumnPosition.column
        );

        var leadingSpace = beforeCursor.match(/^\s*/);
        if (leadingSpace[0].length == column) {
            this.moveCursorTo(
                firstColumnPosition.row, firstColumnPosition.column
            );
        }
        else {
            this.moveCursorTo(
                firstColumnPosition.row,
                firstColumnPosition.column + leadingSpace[0].length
            );
        }
    };

    this.moveCursorLineEnd = function() {
        var lead = this.selectionLead;
        var lastRowColumnPosition =
            this.session.getDocumentLastRowColumnPosition(lead.row, lead.column);
        this.moveCursorTo(
            lastRowColumnPosition.row,
            lastRowColumnPosition.column
        );
    };

    this.moveCursorFileEnd = function() {
        var row = this.doc.getLength() - 1;
        var column = this.doc.getLine(row).length;
        this.moveCursorTo(row, column);
    };

    this.moveCursorFileStart = function() {
        this.moveCursorTo(0, 0);
    };

    this.moveCursorWordRight = function() {
        var row = this.selectionLead.row;
        var column = this.selectionLead.column;
        var line = this.doc.getLine(row);
        var rightOfCursor = line.substring(column);

        var match;
        this.session.nonTokenRe.lastIndex = 0;
        this.session.tokenRe.lastIndex = 0;

        var fold;
        if (fold = this.session.getFoldAt(row, column, 1)) {
            this.moveCursorTo(fold.end.row, fold.end.column);
            return;
        } else if (column == line.length) {
            this.moveCursorRight();
            return;
        }
        else if (match = this.session.nonTokenRe.exec(rightOfCursor)) {
            column += this.session.nonTokenRe.lastIndex;
            this.session.nonTokenRe.lastIndex = 0;
        }
        else if (match = this.session.tokenRe.exec(rightOfCursor)) {
            column += this.session.tokenRe.lastIndex;
            this.session.tokenRe.lastIndex = 0;
        }

        this.moveCursorTo(row, column);
    };

    this.moveCursorWordLeft = function() {
        var row = this.selectionLead.row;
        var column = this.selectionLead.column;

        var fold;
        if (fold = this.session.getFoldAt(row, column, -1)) {
            this.moveCursorTo(fold.start.row, fold.start.column);
            return;
        }

        if (column == 0) {
            this.moveCursorLeft();
            return;
        }

        var str = this.session.getFoldStringAt(row, column, -1);
        if (str == null) {
            str = this.doc.getLine(row).substring(0, column)
        }
        var leftOfCursor = lang.stringReverse(str);

        var match;
        this.session.nonTokenRe.lastIndex = 0;
        this.session.tokenRe.lastIndex = 0;

        if (match = this.session.nonTokenRe.exec(leftOfCursor)) {
            column -= this.session.nonTokenRe.lastIndex;
            this.session.nonTokenRe.lastIndex = 0;
        }
        else if (match = this.session.tokenRe.exec(leftOfCursor)) {
            column -= this.session.tokenRe.lastIndex;
            this.session.tokenRe.lastIndex = 0;
        }

        this.moveCursorTo(row, column);
    };

    this.moveCursorBy = function(rows, chars) {
        var screenPos = this.session.documentToScreenPosition(
            this.selectionLead.row,
            this.selectionLead.column
        );
        var screenCol = (chars == 0 && this.$desiredColumn) || screenPos.column;
        var docPos = this.session.screenToDocumentPosition(screenPos.row + rows, screenCol);
        this.moveCursorTo(docPos.row, docPos.column + chars, chars == 0);
    };

    this.moveCursorToPosition = function(position) {
        this.moveCursorTo(position.row, position.column);
    };

    this.moveCursorTo = function(row, column, preventUpdateDesiredColumn) {
        // Ensure the row/column is not inside of a fold.
        var fold = this.session.getFoldAt(row, column, 1);
        if (fold) {
            row = fold.start.row;
            column = fold.start.column;
        }

        this.$preventUpdateDesiredColumnOnChange = true;
        this.selectionLead.setPosition(row, column);
        this.$preventUpdateDesiredColumnOnChange = false;

        if (!preventUpdateDesiredColumn)
            this.$updateDesiredColumn(this.selectionLead.column);
    };

    this.moveCursorToScreen = function(row, column, preventUpdateDesiredColumn) {
        var pos = this.session.screenToDocumentPosition(row, column);
        row = pos.row;
        column = pos.column;
        this.moveCursorTo(row, column, preventUpdateDesiredColumn);
    };

}).call(Selection.prototype);

exports.Selection = Selection;
});
<commit_msg>Issue 489 Initial<commit_after>/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Ajax.org Code Editor (ACE).
 *
 * The Initial Developer of the Original Code is
 * Ajax.org B.V.
 * Portions created by the Initial Developer are Copyright (C) 2010
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *      Fabian Jakobs <fabian AT ajax DOT org>
 *      Julian Viereck <julian.viereck@gmail.com>
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

define(function(require, exports, module) {

var oop = require("pilot/oop");
var lang = require("pilot/lang");
var EventEmitter = require("pilot/event_emitter").EventEmitter;
var Range = require("ace/range").Range;

/**
 * Keeps cursor position and the text selection of an edit session.
 *
 * The row/columns used in the selection are in document coordinates
 * representing ths coordinates as thez appear in the document
 * before applying soft wrap and folding.
 */
var Selection = function(session) {
    this.session = session;
    this.doc = session.getDocument();

    this.clearSelection();
    this.selectionLead = this.doc.createAnchor(0, 0);
    this.selectionAnchor = this.doc.createAnchor(0, 0);

    var _self = this;
    this.selectionLead.on("change", function(e) {
        _self._dispatchEvent("changeCursor");
        if (!_self.$isEmpty)
            _self._dispatchEvent("changeSelection");
        if (!_self.$preventUpdateDesiredColumnOnChange && e.old.column != e.value.column)
            _self.$updateDesiredColumn();
    });

    this.selectionAnchor.on("change", function() {
        if (!_self.$isEmpty)
            _self._dispatchEvent("changeSelection");
    });
};

(function() {

    oop.implement(this, EventEmitter);

    this.isEmpty = function() {
        return (this.$isEmpty || (
            this.selectionAnchor.row == this.selectionLead.row &&
            this.selectionAnchor.column == this.selectionLead.column
        ));
    };

    this.isMultiLine = function() {
        if (this.isEmpty()) {
            return false;
        }

        return this.getRange().isMultiLine();
    };

    this.getCursor = function() {
        return this.selectionLead.getPosition();
    };

    this.setSelectionAnchor = function(row, column) {
        this.selectionAnchor.setPosition(row, column);

        if (this.$isEmpty) {
            this.$isEmpty = false;
            this._dispatchEvent("changeSelection");
        }
    };

    this.getSelectionAnchor = function() {
        if (this.$isEmpty)
            return this.getSelectionLead()
        else
            return this.selectionAnchor.getPosition();
    };

    this.getSelectionLead = function() {
        return this.selectionLead.getPosition();
    };

    this.shiftSelection = function(columns) {
        if (this.$isEmpty) {
            this.moveCursorTo(this.selectionLead.row, this.selectionLead.column + columns);
            return;
        };

        var anchor = this.getSelectionAnchor();
        var lead = this.getSelectionLead();

        var isBackwards = this.isBackwards();

        if (!isBackwards || anchor.column !== 0)
            this.setSelectionAnchor(anchor.row, anchor.column + columns);

        if (isBackwards || lead.column !== 0) {
            this.$moveSelection(function() {
                this.moveCursorTo(lead.row, lead.column + columns);
            });
        }
    };

    this.isBackwards = function() {
        var anchor = this.selectionAnchor;
        var lead = this.selectionLead;
        return (anchor.row > lead.row || (anchor.row == lead.row && anchor.column > lead.column));
    };

    this.getRange = function() {
        var anchor = this.selectionAnchor;
        var lead = this.selectionLead;

        if (this.isEmpty())
            return Range.fromPoints(lead, lead);

        if (this.isBackwards()) {
            return Range.fromPoints(lead, anchor);
        }
        else {
            return Range.fromPoints(anchor, lead);
        }
    };

    this.clearSelection = function() {
        if (!this.$isEmpty) {
            this.$isEmpty = true;
            this._dispatchEvent("changeSelection");
        }
    };

    this.selectAll = function() {
        var lastRow = this.doc.getLength() - 1;
        this.setSelectionAnchor(lastRow, this.doc.getLine(lastRow).length);
        this.moveCursorTo(0, 0);
    };

    this.setSelectionRange = function(range, reverse) {
        if (reverse) {
            this.setSelectionAnchor(range.end.row, range.end.column);
            this.selectTo(range.start.row, range.start.column);
        } else {
            this.setSelectionAnchor(range.start.row, range.start.column);
            this.selectTo(range.end.row, range.end.column);
        }
        this.$updateDesiredColumn();
    };

    this.$updateDesiredColumn = function() {
        var cursor = this.getCursor();
        this.$desiredColumn = this.session.documentToScreenColumn(cursor.row, cursor.column);
    };

    this.$moveSelection = function(mover) {
        var lead = this.selectionLead;
        if (this.$isEmpty)
            this.setSelectionAnchor(lead.row, lead.column);

        mover.call(this);
    };

    this.selectTo = function(row, column) {
        this.$moveSelection(function() {
            this.moveCursorTo(row, column);
        });
    };

    this.selectToPosition = function(pos) {
        this.$moveSelection(function() {
            this.moveCursorToPosition(pos);
        });
    };

    this.selectUp = function() {
        this.$moveSelection(this.moveCursorUp);
    };

    this.selectDown = function() {
        this.$moveSelection(this.moveCursorDown);
    };

    this.selectRight = function() {
        this.$moveSelection(this.moveCursorRight);
    };

    this.selectLeft = function() {
        this.$moveSelection(this.moveCursorLeft);
    };

    this.selectLineStart = function() {
        this.$moveSelection(this.moveCursorLineStart);
    };

    this.selectLineEnd = function() {
        this.$moveSelection(this.moveCursorLineEnd);
    };

    this.selectFileEnd = function() {
        this.$moveSelection(this.moveCursorFileEnd);
    };

    this.selectFileStart = function() {
        this.$moveSelection(this.moveCursorFileStart);
    };

    this.selectWordRight = function() {
        this.$moveSelection(this.moveCursorWordRight);
    };

    this.selectWordLeft = function() {
        this.$moveSelection(this.moveCursorWordLeft);
    };

    this.selectWord = function() {
        var cursor = this.getCursor();
        var range  = this.session.getWordRange(cursor.row, cursor.column);
        this.setSelectionRange(range);
    };

    this.selectLine = function() {
        var rowStart = this.selectionLead.row;
        var rowEnd;

        var foldLine = this.session.getFoldLine(rowStart);
        if (foldLine) {
            rowStart = foldLine.start.row;
            rowEnd = foldLine.end.row;
        } else {
            rowEnd = rowStart;
        }
        this.setSelectionAnchor(rowStart, 0);
        this.$moveSelection(function() {
            this.moveCursorTo(rowEnd + 1, 0);
        });
    };

    this.moveCursorUp = function() {
        this.moveCursorBy(-1, 0);
    };

    this.moveCursorDown = function() {
        this.moveCursorBy(1, 0);
    };

    this.moveCursorLeft = function() {
        var cursor = this.selectionLead.getPosition(),
            fold;

        if (fold = this.session.getFoldAt(cursor.row, cursor.column, -1)) {
            this.moveCursorTo(fold.start.row, fold.start.column);
        } else if (cursor.column == 0) {
            // cursor is a line (start
            if (cursor.row > 0) {
                this.moveCursorTo(cursor.row - 1, this.doc.getLine(cursor.row - 1).length);
            }
        }
        else {
            var tabSize = this.session.getTabSize();
            if (this.session.isTabStop(cursor) && this.doc.getLine(cursor.row).slice(cursor.column-tabSize, cursor.column).split(" ").length-1 == tabSize)
                this.moveCursorBy(0, -tabSize);
            else
                this.moveCursorBy(0, -1);
        }
    };

    this.moveCursorRight = function() {
        var cursor = this.selectionLead.getPosition(),
            fold;
        if (fold = this.session.getFoldAt(cursor.row, cursor.column, 1)) {
            this.moveCursorTo(fold.end.row, fold.end.column);
        }
        else if (this.selectionLead.column == this.doc.getLine(this.selectionLead.row).length) {
            if (this.selectionLead.row < this.doc.getLength() - 1) {
                this.moveCursorTo(this.selectionLead.row + 1, 0);
            }
        }
        else {
            var tabSize = this.session.getTabSize();
            var cursor = this.selectionLead;
            if (this.session.isTabStop(cursor) && this.doc.getLine(cursor.row).slice(cursor.column, cursor.column+tabSize).split(" ").length-1 == tabSize)
                this.moveCursorBy(0, tabSize);
            else
                this.moveCursorBy(0, 1);
        }
    };

    this.moveCursorLineStart = function() {
        var row = this.selectionLead.row;
        var column = this.selectionLead.column;
        var screenRow = this.session.documentToScreenRow(row, column);

        // Determ the doc-position of the first character at the screen line.
        var firstColumnPosition = this.session.screenToDocumentPosition(screenRow, 0);

        // Determ the line
        var beforeCursor = this.session.getDisplayLine(
            row, null,
            firstColumnPosition.row, firstColumnPosition.column
        );

        var leadingSpace = beforeCursor.match(/^\s*/);
        if (leadingSpace[0].length == column) {
            this.moveCursorTo(
                firstColumnPosition.row, firstColumnPosition.column
            );
        }
        else {
            this.moveCursorTo(
                firstColumnPosition.row,
                firstColumnPosition.column + leadingSpace[0].length
            );
        }
    };

    this.moveCursorLineEnd = function() {
        var lead = this.selectionLead;
        var lastRowColumnPosition =
            this.session.getDocumentLastRowColumnPosition(lead.row, lead.column);
        this.moveCursorTo(
            lastRowColumnPosition.row,
            lastRowColumnPosition.column
        );
    };

    this.moveCursorFileEnd = function() {
        var row = this.doc.getLength() - 1;
        var column = this.doc.getLine(row).length;
        this.moveCursorTo(row, column);
    };

    this.moveCursorFileStart = function() {
        this.moveCursorTo(0, 0);
    };

    this.moveCursorWordRight = function() {
        var row = this.selectionLead.row;
        var column = this.selectionLead.column;
        var line = this.doc.getLine(row);
        var rightOfCursor = line.substring(column);

        var match;
        this.session.nonTokenRe.lastIndex = 0;
        this.session.tokenRe.lastIndex = 0;

        var fold;
        if (fold = this.session.getFoldAt(row, column, 1)) {
            this.moveCursorTo(fold.end.row, fold.end.column);
            return;
        } else if (column == line.length) {
            this.moveCursorRight();
            return;
        }
        else if (match = this.session.nonTokenRe.exec(rightOfCursor)) {
            column += this.session.nonTokenRe.lastIndex;
            this.session.nonTokenRe.lastIndex = 0;
        }
        else if (match = this.session.tokenRe.exec(rightOfCursor)) {
            column += this.session.tokenRe.lastIndex;
            this.session.tokenRe.lastIndex = 0;
        }

        this.moveCursorTo(row, column);
    };

    this.moveCursorWordLeft = function() {
        var row = this.selectionLead.row;
        var column = this.selectionLead.column;

        var fold;
        if (fold = this.session.getFoldAt(row, column, -1)) {
            this.moveCursorTo(fold.start.row, fold.start.column);
            return;
        }

        if (column == 0) {
            this.moveCursorLeft();
            return;
        }

        var str = this.session.getFoldStringAt(row, column, -1);
        if (str == null) {
            str = this.doc.getLine(row).substring(0, column)
        }
        var leftOfCursor = lang.stringReverse(str);

        var match;
        this.session.nonTokenRe.lastIndex = 0;
        this.session.tokenRe.lastIndex = 0;

        if (match = this.session.nonTokenRe.exec(leftOfCursor)) {
            column -= this.session.nonTokenRe.lastIndex;
            this.session.nonTokenRe.lastIndex = 0;
        }
        else if (match = this.session.tokenRe.exec(leftOfCursor)) {
            column -= this.session.tokenRe.lastIndex;
            this.session.tokenRe.lastIndex = 0;
        }

        this.moveCursorTo(row, column);
    };

    this.moveCursorBy = function(rows, chars) {
        var screenPos = this.session.documentToScreenPosition(
            this.selectionLead.row,
            this.selectionLead.column
        );

        var screenCol = (chars === 0 && this.$desiredColumn) || screenPos.column;

        if (this.$lines[screenPos.row].length === screenPos.column &&
                this.$lines[screenPos.row + rows].match(/^\s*$/)) {
            screenCol = this.$lines[screenPos.row + rows].length;
        }

        var docPos = this.session.screenToDocumentPosition(screenPos.row + rows, screenCol);
        this.moveCursorTo(docPos.row, docPos.column + chars, chars == 0);
    };

    this.moveCursorToPosition = function(position) {
        this.moveCursorTo(position.row, position.column);
    };

    this.moveCursorTo = function(row, column, preventUpdateDesiredColumn) {
        // Ensure the row/column is not inside of a fold.
        var fold = this.session.getFoldAt(row, column, 1);
        if (fold) {
            row = fold.start.row;
            column = fold.start.column;
        }

        this.$preventUpdateDesiredColumnOnChange = true;
        this.selectionLead.setPosition(row, column);
        this.$preventUpdateDesiredColumnOnChange = false;

        if (!preventUpdateDesiredColumn)
            this.$updateDesiredColumn(this.selectionLead.column);
    };

    this.moveCursorToScreen = function(row, column, preventUpdateDesiredColumn) {
        var pos = this.session.screenToDocumentPosition(row, column);
        row = pos.row;
        column = pos.column;
        this.moveCursorTo(row, column, preventUpdateDesiredColumn);
    };

}).call(Selection.prototype);

exports.Selection = Selection;
});
<|endoftext|>


<commit_before>var DIRECTIONS = {
  NONE: 0
, DoubleUp: 1
, SingleUp: 2
, FortyFiveUp: 3
, Flat: 4
, FortyFiveDown: 5
, SingleDown: 6
, DoubleDown: 7
, 'NOT COMPUTABLE': 8
, 'RATE OUT OF RANGE': 9
};

var iob = require("./iob")();
var async = require('async');

function directionToTrend (direction) {
  var trend = 8;
  if (direction in DIRECTIONS) {
    trend = DIRECTIONS[direction];
  }
  return trend;
}

function pebble (req, res) {
  var ONE_DAY = 24 * 60 * 60 * 1000
      , uploaderBattery
      , treatmentResults
      , profileResult
      , sgvData = [ ]
      , calData = [ ];

  function scaleBg(bg) {
      if (req.mmol) {
          return (Math.round((bg / 18) * 10) / 10).toFixed(1);
      } else {
          return bg;
      }
  }

  function sendData () {
    var now = Date.now();

    //for compatibility we're keeping battery and iob here, but they would be better somewhere else
    if (sgvData.length > 0) {
        sgvData[0].battery = uploaderBattery ? "" + uploaderBattery : undefined;
        if (req.iob) {
            sgvData[0].iob = iob.calcTotal(treatmentResults.slice(0, 20), profileResult, new Date(now)).display;
        }
    }

    var result = { status: [ {now: now} ], bgs: sgvData, cals: calData };
    res.setHeader('content-type', 'application/json');
    res.write(JSON.stringify(result));
    res.end( );
    // collection.db.close();
  }

    var earliest_data = Date.now() - ONE_DAY;

    async.parallel({
        devicestatus: function (callback) {
            req.devicestatus.last(function (err, value) {
                if (!err && value) {
                    uploaderBattery = value.uploaderBattery;
                } else {
                    console.error("req.devicestatus.tail", err);
                }
                callback();
            });
        }
        , treatments: function(callback) {
            loadTreatments(req, earliest_data, function (err, trs) {
                treatmentResults = trs;
                callback()
            });
        }
        , profile: function(callback) {
            loadProfile(req, function (err, profileResults) {
                profileResults.forEach(function (profile) {
                    if (profile) {
                        if (profile.dia) {
                            profileResult = profile;
                        }
                    }
                });
                callback();
            })
        }
        , cal: function(callback) {
            if (req.rawbg) {
                var cq = { count: req.count, find: {type: 'cal'} };
                req.entries.list(cq, function (err, results) {
                    results.forEach(function (element) {
                        if (element) {
                            calData.push({
                                x: element.date, d: element.dateString, scale: element.scale, intercept: element.intercept, slope: element.slope
                            });
                        }
                    });
                    callback();
                });
            } else {
                callback();
            }
        }
        , entries: function(callback) {
            var q = { count: req.count, find: { "sgv": { $exists: true }} };

            req.entries.list(q, function(err, results) {
                results.forEach(function(element, index) {
                    if (element) {
                        var obj = {};
                        var next = null;
                        var sgvs = results.filter(function(d) {
                            return !!d.sgv;
                        });
                        if (index + 1 < sgvs.length) {
                            next = sgvs[index + 1];
                        }
                        obj.sgv = scaleBg(element.sgv).toString();
                        obj.bgdelta = (next ? (scaleBg(element.sgv) - scaleBg(next.sgv) ) : 0);
                        if (req.mmol) {
                            obj.bgdelta = obj.bgdelta.toFixed(1);
                        }
                        if ('direction' in element) {
                            obj.trend = directionToTrend(element.direction);
                            obj.direction = element.direction;
                        }
                        obj.datetime = element.date;
                        if (req.rawbg) {
                            obj.filtered = element.filtered;
                            obj.unfiltered = element.unfiltered;
                            obj.noise = element.noise;
                            obj.rssi = element.rssi;
                        }
                        // obj.date = element.date.toString( );
                        sgvData.push(obj);
                    }
                });
                callback();
            });
        }
    }, sendData);

}

function loadTreatments(req, earliest_data, fn) {
  if (req.iob) {
    var q = { find: {"created_at": {"$gte": new Date(earliest_data).toISOString()}} };
    req.treatments.list(q, fn);
  } else {
    fn(null, []);
  }
}

function loadProfile(req, fn) {
  if (req.iob) {
    req.profile.list(fn);
  } else {
    fn(null, []);
  }
}

function configure (entries, treatments, profile, devicestatus, env) {
  function middle (req, res, next) {
    req.entries = entries;
    req.treatments = treatments;
    req.profile = profile;
    req.devicestatus = devicestatus;
    req.rawbg = env.enable && env.enable.indexOf('rawbg') > -1;
    req.iob = env.enable && env.enable.indexOf('iob') > -1;
    req.mmol = false;//(req.query.units || env.DISPLAY_UNITS) === 'mmol';
    req.count = parseInt(req.query.count) || 1;

    next( );
  }
  return [middle, pebble];
}

configure.pebble = pebble;
module.exports = configure;
<commit_msg>Update pebble.js<commit_after>var DIRECTIONS = {
  NONE: 0
, DoubleUp: 1
, SingleUp: 2
, FortyFiveUp: 3
, Flat: 4
, FortyFiveDown: 5
, SingleDown: 6
, DoubleDown: 7
, 'NOT COMPUTABLE': 8
, 'RATE OUT OF RANGE': 9
};

var iob = require("./iob")();
var async = require('async');

function directionToTrend (direction) {
  var trend = 8;
  if (direction in DIRECTIONS) {
    trend = DIRECTIONS[direction];
  }
  return trend;
}

function pebble (req, res) {
  var ONE_DAY = 24 * 60 * 60 * 1000
      , uploaderBattery
      , treatmentResults
      , profileResult
      , sgvData = [ ]
      , calData = [ ];

  function scaleBg(bg) {
      if (req.mmol) {
          return (Math.round((bg / 18) * 10) / 10).toFixed(1);
      } else {
          return bg;
      }
  }

  function sendData () {
    var now = Date.now();

    //for compatibility we're keeping battery and iob here, but they would be better somewhere else
    if (sgvData.length > 0) {
        sgvData[0].battery = uploaderBattery ? "" + uploaderBattery : undefined;
        if (req.iob) {
            sgvData[0].iob = iob.calcTotal(treatmentResults.slice(0, 20), profileResult, new Date(now)).display;
        }
    }

    var result = { status: [ {now: now} ], bgs: sgvData, cals: calData };
    res.setHeader('content-type', 'application/json');
    res.write(JSON.stringify(result));
    res.end( );
    // collection.db.close();
  }

    var earliest_data = Date.now() - ONE_DAY;

    async.parallel({
        devicestatus: function (callback) {
            req.devicestatus.last(function (err, value) {
                if (!err && value) {
                    uploaderBattery = value.uploaderBattery;
                } else {
                    console.error("req.devicestatus.tail", err);
                }
                callback();
            });
        }
        , treatments: function(callback) {
            loadTreatments(req, earliest_data, function (err, trs) {
                treatmentResults = trs;
                callback()
            });
        }
        , profile: function(callback) {
            loadProfile(req, function (err, profileResults) {
                profileResults.forEach(function (profile) {
                    if (profile) {
                        if (profile.dia) {
                            profileResult = profile;
                        }
                    }
                });
                callback();
            })
        }
        , cal: function(callback) {
            if (req.rawbg) {
                var cq = { count: req.count, find: {type: 'cal'} };
                req.entries.list(cq, function (err, results) {
                    results.forEach(function (element) {
                        if (element) {
                          var calobj = {};
                          calobj.slope = Math.round(element.slope).toFixed(0);
                          calobj.intercept = Math.round(element.intercept).toFixed(0);
                          calobj.scale = Math.round(element.scale).toFixed(0);
                          calData.push(calobj);
                        }
                    });
                    callback();
                });
            } else {
                callback();
            }
        }
        , entries: function(callback) {
            var q = { count: req.count, find: { "sgv": { $exists: true }} };

            req.entries.list(q, function(err, results) {
                results.forEach(function(element, index) {
                    if (element) {
                        var obj = {};
                        var next = null;
                        var sgvs = results.filter(function(d) {
                            return !!d.sgv;
                        });
                        if (index + 1 < sgvs.length) {
                            next = sgvs[index + 1];
                        }
                        obj.sgv = scaleBg(element.sgv).toString();
                        obj.bgdelta = (next ? (scaleBg(element.sgv) - scaleBg(next.sgv) ) : 0);
                        if (req.mmol) {
                            obj.bgdelta = obj.bgdelta.toFixed(1);
                        }
                        if ('direction' in element) {
                            obj.trend = directionToTrend(element.direction);
                            obj.direction = element.direction;
                        }
                        obj.datetime = element.date;
                        if (req.rawbg) {
                            obj.filtered = element.filtered;
                            obj.unfiltered = element.unfiltered;
                            obj.noise = element.noise;
                            //obj.rssi = element.rssi;
                        }
                        // obj.date = element.date.toString( );
                        sgvData.push(obj);
                    }
                });
                callback();
            });
        }
    }, sendData);

}

function loadTreatments(req, earliest_data, fn) {
  if (req.iob) {
    var q = { find: {"created_at": {"$gte": new Date(earliest_data).toISOString()}} };
    req.treatments.list(q, fn);
  } else {
    fn(null, []);
  }
}

function loadProfile(req, fn) {
  if (req.iob) {
    req.profile.list(fn);
  } else {
    fn(null, []);
  }
}

function configure (entries, treatments, profile, devicestatus, env) {
  function middle (req, res, next) {
    req.entries = entries;
    req.treatments = treatments;
    req.profile = profile;
    req.devicestatus = devicestatus;
    req.rawbg = env.enable && env.enable.indexOf('rawbg') > -1;
    req.iob = env.enable && env.enable.indexOf('iob') > -1;
    req.mmol = false;//(req.query.units || env.DISPLAY_UNITS) === 'mmol';
    req.count = parseInt(req.query.count) || 1;

    next( );
  }
  return [middle, pebble];
}

configure.pebble = pebble;
module.exports = configure;
<|endoftext|>


<commit_before>/*
 * debugger.io: An interactive web scripting sandbox
 */

define([
  'module', 'path', 'config', 'utils', 'underscore', 'q',
  'marked', 'jade', 'less', 'node-sass',
  'coffee-script', 'typestring', 'gorillascript'
],
function(
  module, path, config, utils, _, Q,
  marked, jade, less, sass, cs, ts, gs
) {
  'use strict';

  var __dirname = path.dirname(module.uri);
  var compilers = {};

  /**
   * All compilers should return a promise, and always resolve, either to
   * a compiled result, or the original input
   */
  var compilers_map = (function() {

    marked.setOptions({ gfm: true });

    return {

      // MARKUP
      'jade': function(str) {
        var d = Q.defer();

        try {
          var html = jade.render(str, { compileDebug: false };
          d.resolve(html);
        } catch(err) {
          d.resolve(str);
        }

        return d.promise;
      },

      'gfm': function(str) {
        var d = Q.defer();

        try { var html = marked(str); d.resolve(html); }
        catch(err) { d.resolve(str); }

        return d.promise;
      },

      // STYLE
      'less': function(str) {
        var d = Q.defer();

        try { less.render(str, function(e, css) { d.resolve(css); }); }
        catch(err) { d.resolve(str); }

        return d.promise;
      },

      'scss': function(str) {
        var d = Q.defer();

        try {
          sass.render({
            data: str,
            success: function(css) { d.resolve(css); },
            error: function(err) { d.resolve(str); },
          });
        } catch(err) {
          d.resolve(str);
        }

        return d.promise;
      },

      // SCRIPT
      'coffeescript': function(str) {
        var d = Q.defer();

        try {
          var js = cs.compile(str);
          d.resolve(js);
        } catch(err) {
          d.resolve(str);
        }

        return d.promise;
      },

      'typescript': function(str) {
        var d = Q.defer();

        try {
          var js = ts.compile(str);
          d.resolve(js);
        } catch(err) {
          d.resolve(str);
        }

        return d.promise;
      },

      'gorillascript': function(str) {
        var d = Q.defer();

        try {
          gs.compile(str).then(function(result) {
            d.resolve(result.code);
          }, function(err) {
            d.resolve(str);
          });
        } catch(err) {
          d.resolve(str);
        }

        return d.promise;
      }

    };
  })();

  /**
   * Compile an input string, return a promise with the output
   *
   * @param {String} type: which compiler to use (eg. 'typescript')
   * @param {String} str: the input string of type `type`
   */
  compilers.compile = function(type, str) {
    type = utils.ensure_string(type);
    str = utils.ensure_string(str);

    // each compiler_fn should return a promise
    var compiler_fn = compilers_map[type];
    return _.isFunction(compiler_fn) ? compiler_fn(str) : Q(str);
  };

  return compilers;
});
<commit_msg>Fix a missing closing paren<commit_after>/*
 * debugger.io: An interactive web scripting sandbox
 */

define([
  'module', 'path', 'config', 'utils', 'underscore', 'q',
  'marked', 'jade', 'less', 'node-sass',
  'coffee-script', 'typestring', 'gorillascript'
],
function(
  module, path, config, utils, _, Q,
  marked, jade, less, sass, cs, ts, gs
) {
  'use strict';

  var __dirname = path.dirname(module.uri);
  var compilers = {};

  /**
   * All compilers should return a promise, and always resolve, either to
   * a compiled result, or the original input
   */
  var compilers_map = (function() {

    marked.setOptions({ gfm: true });

    return {

      // MARKUP
      'jade': function(str) {
        var d = Q.defer();

        try {
          var html = jade.render(str, { compileDebug: false });
          d.resolve(html);
        } catch(err) {
          d.resolve(str);
        }

        return d.promise;
      },

      'gfm': function(str) {
        var d = Q.defer();

        try { var html = marked(str); d.resolve(html); }
        catch(err) { d.resolve(str); }

        return d.promise;
      },

      // STYLE
      'less': function(str) {
        var d = Q.defer();

        try { less.render(str, function(e, css) { d.resolve(css); }); }
        catch(err) { d.resolve(str); }

        return d.promise;
      },

      'scss': function(str) {
        var d = Q.defer();

        try {
          sass.render({
            data: str,
            success: function(css) { d.resolve(css); },
            error: function(err) { d.resolve(str); },
          });
        } catch(err) {
          d.resolve(str);
        }

        return d.promise;
      },

      // SCRIPT
      'coffeescript': function(str) {
        var d = Q.defer();

        try {
          var js = cs.compile(str);
          d.resolve(js);
        } catch(err) {
          d.resolve(str);
        }

        return d.promise;
      },

      'typescript': function(str) {
        var d = Q.defer();

        try {
          var js = ts.compile(str);
          d.resolve(js);
        } catch(err) {
          d.resolve(str);
        }

        return d.promise;
      },

      'gorillascript': function(str) {
        var d = Q.defer();

        try {
          gs.compile(str).then(function(result) {
            d.resolve(result.code);
          }, function(err) {
            d.resolve(str);
          });
        } catch(err) {
          d.resolve(str);
        }

        return d.promise;
      }

    };
  })();

  /**
   * Compile an input string, return a promise with the output
   *
   * @param {String} type: which compiler to use (eg. 'typescript')
   * @param {String} str: the input string of type `type`
   */
  compilers.compile = function(type, str) {
    type = utils.ensure_string(type);
    str = utils.ensure_string(str);

    // each compiler_fn should return a promise
    var compiler_fn = compilers_map[type];
    return _.isFunction(compiler_fn) ? compiler_fn(str) : Q(str);
  };

  return compilers;
});
<|endoftext|>


<commit_before>export default class ComponentUtils {
  /**
   * Initializes the registry used for managing component utils.
   *
   * @param {ObjectContainer} oc The application's dependency injector - the
   *        object container.
   */
  constructor(oc) {
    /**
     * The application's dependency injector - the object container.
     *
     * @type {ObjectContainer}
     */
    this._oc = oc;

    /**
     * Map of registered utilities.
     *
     * @type {Object<string, function(new: T, ...*)|function(...*): T>}
     */
    this._utilityClasses = {};

    /**
     * Map of instantiated utilities
     *
     * @type {Object<string, Object>}
     */
    this._utilities = null;
  }

  /**
   * Registers single utility class or multiple classes in alias->class mapping.
   *
   * @param {string|Object<string, function(new: T, ...*)|function(...*): T>} name
   * @param {function(new: T, ...*)|function(...*): T} componentUtilityClass
   */
  register(name, componentUtilityClass) {
    if (typeof componentUtilityClass === 'function') {
      const alias = String(name);
      this._utilityClasses[alias] = componentUtilityClass;

      if (this._utilities) {
        this._createUtilityInstance(alias, componentUtilityClass);
      }
    } else if (typeof name === 'object') {
      const utilityClasses = name;

      for (const alias of Object.keys(utilityClasses)) {
        if (!utilityClasses.hasOwnProperty(alias)) {
          continue;
        }

        this._utilityClasses[alias] = utilityClasses[alias];

        if (this._utilities) {
          this._createUtilityInstance(alias, utilityClasses[alias]);
        }
      }
    }
  }

  /**
   * Returns object containing all registered utilities
   *
   * @returns {Object<string, Object>}
   */
  getUtils() {
    if (this._utilities) {
      return this._utilities;
    }

    this._utilities = {};

    // create instance of each utility class
    for (const alias of Object.keys(this._utilityClasses)) {
      this._createUtilityInstance(alias, this._utilityClasses[alias]);
    }

    if (this._oc.has('$Utils')) {
      // fallback for backward compatibility
      Object.assign(this._utilities, this._oc.get('$Utils'));
    }

    return this._utilities;
  }

  /**
   * @template T
   * @param {string} alias
   * @param {function(new: T, ...*)|function(...*): T} utilityClass
   * @return {T}
   */
  _createUtilityInstance(alias, utilityClass) {
    return (this._utilities[alias] = this._oc.get(utilityClass));
  }
}
<commit_msg>fix(component-utils): better check for object type<commit_after>export default class ComponentUtils {
  /**
   * Initializes the registry used for managing component utils.
   *
   * @param {ObjectContainer} oc The application's dependency injector - the
   *        object container.
   */
  constructor(oc) {
    /**
     * The application's dependency injector - the object container.
     *
     * @type {ObjectContainer}
     */
    this._oc = oc;

    /**
     * Map of registered utilities.
     *
     * @type {Object<string, function(new: T, ...*)|function(...*): T>}
     */
    this._utilityClasses = {};

    /**
     * Map of instantiated utilities
     *
     * @type {Object<string, Object>}
     */
    this._utilities = null;
  }

  /**
   * Registers single utility class or multiple classes in alias->class mapping.
   *
   * @param {string|Object<string, function(new: T, ...*)|function(...*): T>} name
   * @param {function(new: T, ...*)|function(...*): T} componentUtilityClass
   */
  register(name, componentUtilityClass) {
    if (typeof componentUtilityClass === 'function') {
      const alias = String(name);
      this._utilityClasses[alias] = componentUtilityClass;

      if (this._utilities) {
        this._createUtilityInstance(alias, componentUtilityClass);
      }
    } else if (
      name &&
      typeof name === 'object' &&
      name.constructor === Object
    ) {
      const utilityClasses = name;

      for (const alias of Object.keys(utilityClasses)) {
        if (!utilityClasses.hasOwnProperty(alias)) {
          continue;
        }

        this._utilityClasses[alias] = utilityClasses[alias];

        if (this._utilities) {
          this._createUtilityInstance(alias, utilityClasses[alias]);
        }
      }
    }
  }

  /**
   * Returns object containing all registered utilities
   *
   * @returns {Object<string, Object>}
   */
  getUtils() {
    if (this._utilities) {
      return this._utilities;
    }

    this._utilities = {};

    // create instance of each utility class
    for (const alias of Object.keys(this._utilityClasses)) {
      this._createUtilityInstance(alias, this._utilityClasses[alias]);
    }

    if (this._oc.has('$Utils')) {
      // fallback for backward compatibility
      Object.assign(this._utilities, this._oc.get('$Utils'));
    }

    return this._utilities;
  }

  /**
   * @template T
   * @param {string} alias
   * @param {function(new: T, ...*)|function(...*): T} utilityClass
   * @return {T}
   */
  _createUtilityInstance(alias, utilityClass) {
    return (this._utilities[alias] = this._oc.get(utilityClass));
  }
}
<|endoftext|>


<commit_before>const crypto = require(`crypto`)
const axios = require(`axios`)
const _ = require(`lodash`)
const { createRemoteFileNode } = require(`gatsby-source-filesystem`)

const SCREENSHOT_ENDPOINT = `https://h7iqvn4842.execute-api.us-east-2.amazonaws.com/prod/screenshot`

const createContentDigest = obj =>
  crypto
    .createHash(`md5`)
    .update(JSON.stringify(obj))
    .digest(`hex`)

exports.onPreBootstrap = (
  { store, cache, boundActionCreators },
  pluginOptions
) => {
  const { createNode, touchNode } = boundActionCreators

  // Check for updated screenshots
  // and prevent Gatsby from garbage collecting remote file nodes
  return Promise.all(
    _.values(store.getState().nodes)
      .filter(n => n.internal.type === `Screenshot`)
      .map(async n => {
        if (n.expires && new Date() >= new Date(n.expires)) {
          // Screenshot expired, re-run Lambda
          await createScreenshotNode({
            url: n.url,
            parent: n.parent,
            store,
            cache,
            createNode,
          })
        } else {
          // Screenshot hasn't yet expired, touch the image node
          // to prevent garbage collection
          touchNode(n.screenshotFile___NODE)
        }
      })
  )
}

exports.onCreateNode = async ({ node, boundActionCreators, store, cache }) => {
  const { createNode, createParentChildLink } = boundActionCreators

  // We only care about parsed sites.yaml files
  if (node.internal.type !== `SitesYaml`) {
    return
  }

  const screenshotNode = await createScreenshotNode({
    url: node.url,
    parent: node.id,
    store,
    cache,
    createNode,
  })

  createParentChildLink({
    parent: node,
    child: screenshotNode,
  })
}

const createScreenshotNode = async ({
  url,
  parent,
  store,
  cache,
  createNode,
}) => {
  const screenshotResponse = await axios.post(SCREENSHOT_ENDPOINT, { url })

  const fileNode = await createRemoteFileNode({
    url: screenshotResponse.data.url,
    store,
    cache,
    createNode,
  })

  const screenshotNode = {
    id: `${parent} >>> Screenshot`,
    url,
    expires: screenshotResponse.data.expires,
    parent,
    children: [],
    internal: {
      type: `Screenshot`,
    },
    screenshotFile___NODE: fileNode.id,
  }

  screenshotNode.internal.contentDigest = createContentDigest(screenshotNode)

  createNode(screenshotNode)

  return screenshotNode
}
<commit_msg>Ignore nodes with no URL field (#4930)<commit_after>const crypto = require(`crypto`)
const axios = require(`axios`)
const _ = require(`lodash`)
const { createRemoteFileNode } = require(`gatsby-source-filesystem`)

const SCREENSHOT_ENDPOINT = `https://h7iqvn4842.execute-api.us-east-2.amazonaws.com/prod/screenshot`

const createContentDigest = obj =>
  crypto
    .createHash(`md5`)
    .update(JSON.stringify(obj))
    .digest(`hex`)

exports.onPreBootstrap = (
  { store, cache, boundActionCreators },
  pluginOptions
) => {
  const { createNode, touchNode } = boundActionCreators

  // Check for updated screenshots
  // and prevent Gatsby from garbage collecting remote file nodes
  return Promise.all(
    _.values(store.getState().nodes)
      .filter(n => n.internal.type === `Screenshot`)
      .map(async n => {
        if (n.expires && new Date() >= new Date(n.expires)) {
          // Screenshot expired, re-run Lambda
          await createScreenshotNode({
            url: n.url,
            parent: n.parent,
            store,
            cache,
            createNode,
          })
        } else {
          // Screenshot hasn't yet expired, touch the image node
          // to prevent garbage collection
          touchNode(n.screenshotFile___NODE)
        }
      })
  )
}

exports.onCreateNode = async ({ node, boundActionCreators, store, cache }) => {
  const { createNode, createParentChildLink } = boundActionCreators

  // We only care about parsed sites.yaml files with a url field
  if (node.internal.type !== `SitesYaml` || !node.url) {
    return
  }

  const screenshotNode = await createScreenshotNode({
    url: node.url,
    parent: node.id,
    store,
    cache,
    createNode,
  })

  createParentChildLink({
    parent: node,
    child: screenshotNode,
  })
}

const createScreenshotNode = async ({
  url,
  parent,
  store,
  cache,
  createNode,
}) => {
  const screenshotResponse = await axios.post(SCREENSHOT_ENDPOINT, { url })

  const fileNode = await createRemoteFileNode({
    url: screenshotResponse.data.url,
    store,
    cache,
    createNode,
  })

  const screenshotNode = {
    id: `${parent} >>> Screenshot`,
    url,
    expires: screenshotResponse.data.expires,
    parent,
    children: [],
    internal: {
      type: `Screenshot`,
    },
    screenshotFile___NODE: fileNode.id,
  }

  screenshotNode.internal.contentDigest = createContentDigest(screenshotNode)

  createNode(screenshotNode)

  return screenshotNode
}
<|endoftext|>


<commit_before>const accountsConfig = {
	forbidClientAccountCreation: true,
	loginExpirationInDays: RocketChat.settings.get('Accounts_LoginExpiration')
};

Accounts.config(accountsConfig);

Accounts.emailTemplates.siteName = RocketChat.settings.get('Site_Name');

Accounts.emailTemplates.from = `${ RocketChat.settings.get('Site_Name') } <${ RocketChat.settings.get('From_Email') }>`;

Accounts.emailTemplates.notifyAdmin = {};

const verifyEmailHtml = Accounts.emailTemplates.verifyEmail.text;

Accounts.emailTemplates.verifyEmail.html = function(user, url) {
	url = url.replace(Meteor.absoluteUrl(), `${ Meteor.absoluteUrl() }login/`);
	return verifyEmailHtml(user, url);
};

const resetPasswordHtml = Accounts.emailTemplates.resetPassword.text;

Accounts.emailTemplates.resetPassword.html = function(user, url) {
	url = url.replace(/\/#\//, '/');
	return resetPasswordHtml(user, url);
};

Accounts.emailTemplates.enrollAccount.subject = function(user = {}) {
	let subject;
	if (RocketChat.settings.get('Accounts_Enrollment_Customized')) {
		subject = RocketChat.settings.get('Accounts_Enrollment_Email_Subject');
	} else {
		subject = TAPi18n.__('Accounts_Enrollment_Email_Subject_Default', {
			lng: user.language || RocketChat.settings.get('language') || 'en'
		});
	}
	return RocketChat.placeholders.replace(subject);
};

Accounts.emailTemplates.enrollAccount.html = function(user = {}/*, url*/) {
	let html;
	if (RocketChat.settings.get('Accounts_Enrollment_Customized')) {
		html = RocketChat.settings.get('Accounts_Enrollment_Email');
	} else {
		html = TAPi18n.__('Accounts_Enrollment_Email_Default', {
			lng: user.language || RocketChat.settings.get('language') || 'en'
		});
	}

	const header = RocketChat.placeholders.replace(RocketChat.settings.get('Email_Header') || '');
	const footer = RocketChat.placeholders.replace(RocketChat.settings.get('Email_Footer') || '');

	html = RocketChat.placeholders.replace(html, {
		name: user.name,
		email: user.emails && user.emails[0] && user.emails[0].address
	});

	return header + html + footer;
};

Accounts.emailTemplates.notifyAdmin.subject = function() {
	const subject = TAPi18n.__('Accounts_Admin_Email_Approval_Needed_Subject_Default');
	const siteName = RocketChat.settings.get('Site_Name');

	return `[${ siteName }] ${ subject }`;
};

Accounts.emailTemplates.notifyAdmin.html = function(user = {}) {

	let html;

	html = TAPi18n.__('Accounts_Admin_Email_Approval_Needed_Default');

	const header = RocketChat.placeholders.replace(RocketChat.settings.get('Email_Header') || '');
	const footer = RocketChat.placeholders.replace(RocketChat.settings.get('Email_Footer') || '');

	html = RocketChat.placeholders.replace(html, {
		email: user.emails[0].address
	});

	return header + html + footer;
};

Accounts.onCreateUser(function(options, user = {}) {
	RocketChat.callbacks.run('beforeCreateUser', options, user);

	user.status = 'offline';
	user.active = !RocketChat.settings.get('Accounts_ManuallyApproveNewUsers');

	if (!user.name) {
		if (options.profile) {
			if (options.profile.name) {
				user.name = options.profile.name;
			} else if (options.profile.firstName && options.profile.lastName) {
				// LinkedIn format
				user.name = `${ options.profile.firstName } ${ options.profile.lastName }`;
			} else if (options.profile.firstName) {
				// LinkedIn format
				user.name = options.profile.firstName;
			}
		}
	}

	if (user.services) {
		for (const service of Object.values(user.services)) {
			if (!user.name) {
				user.name = service.name || service.username;
			}

			if (!user.emails && service.email) {
				user.emails = [{
					address: service.email,
					verified: true
				}];
			}
		}
	}

	if (!user.active) {
		user.emails.some((email) => {
			RocketChat.models.Roles.findUsersInRole('admin').forEach(function(adminUser) {
				email = {
					to: adminUser.emails[0].address,
					from: RocketChat.settings.get('From_Email'),
					subject: Accounts.emailTemplates.notifyAdmin.subject(),
					html: Accounts.emailTemplates.notifyAdmin.html(user)
				};

				Meteor.defer(() => {
					Email.send(email);
				});
			});
		});
	}

	return user;
});

Accounts.insertUserDoc = _.wrap(Accounts.insertUserDoc, function(insertUserDoc, options, user) {
	let roles = [];

	if (Match.test(user.globalRoles, [String]) && user.globalRoles.length > 0) {
		roles = roles.concat(user.globalRoles);
	}

	delete user.globalRoles;

	if (user.services && !user.services.password) {
		const defaultAuthServiceRoles = String(RocketChat.settings.get('Accounts_Registration_AuthenticationServices_Default_Roles')).split(',');
		if (defaultAuthServiceRoles.length > 0) {
			roles = roles.concat(defaultAuthServiceRoles.map(s => s.trim()));
		}
	}

	if (!user.type) {
		user.type = 'user';
	}

	const _id = insertUserDoc.call(Accounts, options, user);

	user = Meteor.users.findOne({
		_id
	});

	if (user.username && options.joinDefaultChannels !== false && user.joinDefaultChannels !== false) {
		Meteor.runAsUser(_id, function() {
			return Meteor.call('joinDefaultChannels', options.joinDefaultChannelsSilenced);
		});
	}

	if (roles.length === 0) {
		const hasAdmin = RocketChat.models.Users.findOne({
			roles: 'admin',
			type: 'user'
		}, {
			fields: {
				_id: 1
			}
		});

		if (hasAdmin) {
			roles.push('user');
		} else {
			roles.push('admin');
		}
	}

	RocketChat.authz.addUserRoles(_id, roles);

	return _id;
});

Accounts.validateLoginAttempt(function(login) {
	login = RocketChat.callbacks.run('beforeValidateLogin', login);

	if (login.allowed !== true) {
		return login.allowed;
	}

	if (login.user.type === 'visitor') {
		return true;
	}

	if (!!login.user.active !== true) {
		throw new Meteor.Error('error-user-is-not-activated', 'User is not activated', {
			'function': 'Accounts.validateLoginAttempt'
		});
	}

	if (login.user.roles.includes('admin') === false && login.type === 'password' && RocketChat.settings.get('Accounts_EmailVerification') === true) {
		const validEmail = login.user.emails.filter(email => email.verified === true);
		if (validEmail.length === 0) {
			throw new Meteor.Error('error-invalid-email', 'Invalid email __email__');
		}
	}

	login = RocketChat.callbacks.run('onValidateLogin', login);

	RocketChat.models.Users.updateLastLoginById(login.user._id);
	Meteor.defer(function() {
		return RocketChat.callbacks.run('afterValidateLogin', login);
	});

	return true;
});

Accounts.validateNewUser(function(user) {
	if (user.type === 'visitor') {
		return true;
	}

	if (RocketChat.settings.get('Accounts_Registration_AuthenticationServices_Enabled') === false && RocketChat.settings.get('LDAP_Enable') === false && !(user.services && user.services.password)) {
		throw new Meteor.Error('registration-disabled-authentication-services', 'User registration is disabled for authentication services');
	}

	return true;
});

Accounts.validateNewUser(function(user) {
	if (user.type === 'visitor') {
		return true;
	}

	let domainWhiteList = RocketChat.settings.get('Accounts_AllowedDomainsList');
	if (_.isEmpty(s.trim(domainWhiteList))) {
		return true;
	}

	domainWhiteList = domainWhiteList.split(',').map(domain => domain.trim());

	if (user.emails && user.emails.length > 0) {
		const email = user.emails[0].address;
		const inWhiteList = domainWhiteList.some(domain => email.match(`@${ RegExp.escape(domain) }$`));

		if (inWhiteList === false) {
			throw new Meteor.Error('error-invalid-domain');
		}
	}

	return true;
});
<commit_msg>Modified to change email to all admins at once<commit_after>const accountsConfig = {
	forbidClientAccountCreation: true,
	loginExpirationInDays: RocketChat.settings.get('Accounts_LoginExpiration')
};

Accounts.config(accountsConfig);

Accounts.emailTemplates.siteName = RocketChat.settings.get('Site_Name');

Accounts.emailTemplates.from = `${ RocketChat.settings.get('Site_Name') } <${ RocketChat.settings.get('From_Email') }>`;

Accounts.emailTemplates.notifyAdmin = {};

const verifyEmailHtml = Accounts.emailTemplates.verifyEmail.text;

Accounts.emailTemplates.verifyEmail.html = function(user, url) {
	url = url.replace(Meteor.absoluteUrl(), `${ Meteor.absoluteUrl() }login/`);
	return verifyEmailHtml(user, url);
};

const resetPasswordHtml = Accounts.emailTemplates.resetPassword.text;

Accounts.emailTemplates.resetPassword.html = function(user, url) {
	url = url.replace(/\/#\//, '/');
	return resetPasswordHtml(user, url);
};

Accounts.emailTemplates.enrollAccount.subject = function(user = {}) {
	let subject;
	if (RocketChat.settings.get('Accounts_Enrollment_Customized')) {
		subject = RocketChat.settings.get('Accounts_Enrollment_Email_Subject');
	} else {
		subject = TAPi18n.__('Accounts_Enrollment_Email_Subject_Default', {
			lng: user.language || RocketChat.settings.get('language') || 'en'
		});
	}
	return RocketChat.placeholders.replace(subject);
};

Accounts.emailTemplates.enrollAccount.html = function(user = {}/*, url*/) {
	let html;
	if (RocketChat.settings.get('Accounts_Enrollment_Customized')) {
		html = RocketChat.settings.get('Accounts_Enrollment_Email');
	} else {
		html = TAPi18n.__('Accounts_Enrollment_Email_Default', {
			lng: user.language || RocketChat.settings.get('language') || 'en'
		});
	}

	const header = RocketChat.placeholders.replace(RocketChat.settings.get('Email_Header') || '');
	const footer = RocketChat.placeholders.replace(RocketChat.settings.get('Email_Footer') || '');

	html = RocketChat.placeholders.replace(html, {
		name: user.name,
		email: user.emails && user.emails[0] && user.emails[0].address
	});

	return header + html + footer;
};

Accounts.emailTemplates.notifyAdmin.subject = function() {
	const subject = TAPi18n.__('Accounts_Admin_Email_Approval_Needed_Subject_Default');
	const siteName = RocketChat.settings.get('Site_Name');

	return `[${ siteName }] ${ subject }`;
};

Accounts.emailTemplates.notifyAdmin.html = function(user = {}) {

	let html;

	html = TAPi18n.__('Accounts_Admin_Email_Approval_Needed_Default');

	const header = RocketChat.placeholders.replace(RocketChat.settings.get('Email_Header') || '');
	const footer = RocketChat.placeholders.replace(RocketChat.settings.get('Email_Footer') || '');

	html = RocketChat.placeholders.replace(html, {
		email: user.emails[0].address
	});

	return header + html + footer;
};

Accounts.onCreateUser(function(options, user = {}) {
	RocketChat.callbacks.run('beforeCreateUser', options, user);

	user.status = 'offline';
	user.active = !RocketChat.settings.get('Accounts_ManuallyApproveNewUsers');

	if (!user.name) {
		if (options.profile) {
			if (options.profile.name) {
				user.name = options.profile.name;
			} else if (options.profile.firstName && options.profile.lastName) {
				// LinkedIn format
				user.name = `${ options.profile.firstName } ${ options.profile.lastName }`;
			} else if (options.profile.firstName) {
				// LinkedIn format
				user.name = options.profile.firstName;
			}
		}
	}

	if (user.services) {
		for (const service of Object.values(user.services)) {
			if (!user.name) {
				user.name = service.name || service.username;
			}

			if (!user.emails && service.email) {
				user.emails = [{
					address: service.email,
					verified: true
				}];
			}
		}
	}

	if (!user.active) {
		user.emails.some((email) => {
			const destinations = [];

			RocketChat.models.Roles.findUsersInRole('admin').forEach(function(adminUser) {
				destinations.push(`${ adminUser.name }<${ adminUser.emails[0].address }>`);
			});

			email = {
				to: destinations,
				from: RocketChat.settings.get('From_Email'),
				subject: Accounts.emailTemplates.notifyAdmin.subject(),
				html: Accounts.emailTemplates.notifyAdmin.html(user)
			};

			Meteor.defer(() => {
				Email.send(email);
			});
		});
	}

	return user;
});

Accounts.insertUserDoc = _.wrap(Accounts.insertUserDoc, function(insertUserDoc, options, user) {
	let roles = [];

	if (Match.test(user.globalRoles, [String]) && user.globalRoles.length > 0) {
		roles = roles.concat(user.globalRoles);
	}

	delete user.globalRoles;

	if (user.services && !user.services.password) {
		const defaultAuthServiceRoles = String(RocketChat.settings.get('Accounts_Registration_AuthenticationServices_Default_Roles')).split(',');
		if (defaultAuthServiceRoles.length > 0) {
			roles = roles.concat(defaultAuthServiceRoles.map(s => s.trim()));
		}
	}

	if (!user.type) {
		user.type = 'user';
	}

	const _id = insertUserDoc.call(Accounts, options, user);

	user = Meteor.users.findOne({
		_id
	});

	if (user.username && options.joinDefaultChannels !== false && user.joinDefaultChannels !== false) {
		Meteor.runAsUser(_id, function() {
			return Meteor.call('joinDefaultChannels', options.joinDefaultChannelsSilenced);
		});
	}

	if (roles.length === 0) {
		const hasAdmin = RocketChat.models.Users.findOne({
			roles: 'admin',
			type: 'user'
		}, {
			fields: {
				_id: 1
			}
		});

		if (hasAdmin) {
			roles.push('user');
		} else {
			roles.push('admin');
		}
	}

	RocketChat.authz.addUserRoles(_id, roles);

	return _id;
});

Accounts.validateLoginAttempt(function(login) {
	login = RocketChat.callbacks.run('beforeValidateLogin', login);

	if (login.allowed !== true) {
		return login.allowed;
	}

	if (login.user.type === 'visitor') {
		return true;
	}

	if (!!login.user.active !== true) {
		throw new Meteor.Error('error-user-is-not-activated', 'User is not activated', {
			'function': 'Accounts.validateLoginAttempt'
		});
	}

	if (login.user.roles.includes('admin') === false && login.type === 'password' && RocketChat.settings.get('Accounts_EmailVerification') === true) {
		const validEmail = login.user.emails.filter(email => email.verified === true);
		if (validEmail.length === 0) {
			throw new Meteor.Error('error-invalid-email', 'Invalid email __email__');
		}
	}

	login = RocketChat.callbacks.run('onValidateLogin', login);

	RocketChat.models.Users.updateLastLoginById(login.user._id);
	Meteor.defer(function() {
		return RocketChat.callbacks.run('afterValidateLogin', login);
	});

	return true;
});

Accounts.validateNewUser(function(user) {
	if (user.type === 'visitor') {
		return true;
	}

	if (RocketChat.settings.get('Accounts_Registration_AuthenticationServices_Enabled') === false && RocketChat.settings.get('LDAP_Enable') === false && !(user.services && user.services.password)) {
		throw new Meteor.Error('registration-disabled-authentication-services', 'User registration is disabled for authentication services');
	}

	return true;
});

Accounts.validateNewUser(function(user) {
	if (user.type === 'visitor') {
		return true;
	}

	let domainWhiteList = RocketChat.settings.get('Accounts_AllowedDomainsList');
	if (_.isEmpty(s.trim(domainWhiteList))) {
		return true;
	}

	domainWhiteList = domainWhiteList.split(',').map(domain => domain.trim());

	if (user.emails && user.emails.length > 0) {
		const email = user.emails[0].address;
		const inWhiteList = domainWhiteList.some(domain => email.match(`@${ RegExp.escape(domain) }$`));

		if (inWhiteList === false) {
			throw new Meteor.Error('error-invalid-domain');
		}
	}

	return true;
});
<|endoftext|>