<commit_before>(function() {
  if (window.GitLab == null) {
    window.GitLab = {};
  }

  GitLab.GfmAutoComplete = {
    dataLoading: false,
    dataLoaded: false,
    cachedData: {},
    dataSource: '',
    Emoji: {
      template: '
${name}
'
    },
    Members: {
      template: '
${username} ${title}
'
    },
    Labels: {
      template: '
 ${title}
'
    },
    Issues: {
      template: '
${id} ${title}
'
    },
    Milestones: {
      template: '
${title}
'
    },
    Loading: {
      template: '
 Loading...
'
    },
    DefaultOptions: {
      sorter: function(query, items, searchKey) {
        if ((items[0].name != null) && items[0].name === 'loading') {
          return items;
        }
        return $.fn.atwho["default"].callbacks.sorter(query, items, searchKey);
      },
      filter: function(query, data, searchKey) {
        if (data[0] === 'loading') {
          return data;
        }
        return $.fn.atwho["default"].callbacks.filter(query, data, searchKey);
      },
      beforeInsert: function(value) {
        if (!GitLab.GfmAutoComplete.dataLoaded) {
          return this.at;
        } else {
          return value;
        }
      }
    },
    setup: function(input) {
      this.input = input || $('.js-gfm-input');
      this.destroyAtWho();
      this.setupAtWho();
      if (this.dataSource) {
        if (!this.dataLoading && !this.cachedData) {
          this.dataLoading = true;
          setTimeout((function(_this) {
            return function() {
              var fetch;
              fetch = _this.fetchData(_this.dataSource);
              return fetch.done(function(data) {
                _this.dataLoading = false;
                return _this.loadData(data);
              });
            };
          })(this), 1000);
        }
        if (this.cachedData != null) {
          return this.loadData(this.cachedData);
        }
      }
    },
    setupAtWho: function() {
      this.input.atwho({
        at: ':',
        displayTpl: (function(_this) {
          return function(value) {
            if (value.path != null) {
              return _this.Emoji.template;
            } else {
              return _this.Loading.template;
            }
          };
        })(this),
        insertTpl: ':${name}:',
        data: ['loading'],
        callbacks: {
          sorter: this.DefaultOptions.sorter,
          filter: this.DefaultOptions.filter,
          beforeInsert: this.DefaultOptions.beforeInsert
        }
      });
      this.input.atwho({
        at: '@',
        displayTpl: (function(_this) {
          return function(value) {
            if (value.username != null) {
              return _this.Members.template;
            } else {
              return _this.Loading.template;
            }
          };
        })(this),
        insertTpl: '${atwho-at}${username}',
        searchKey: 'search',
        data: ['loading'],
        callbacks: {
          sorter: this.DefaultOptions.sorter,
          filter: this.DefaultOptions.filter,
          beforeInsert: this.DefaultOptions.beforeInsert,
          beforeSave: function(members) {
            return $.map(members, function(m) {
              var title;
              if (m.username == null) {
                return m;
              }
              title = m.name;
              if (m.count) {
                title += " (" + m.count + ")";
              }
              return {
                username: m.username,
                title: sanitize(title),
                search: sanitize(m.username + " " + m.name)
              };
            });
          }
        }
      });
      this.input.atwho({
        at: '#',
        alias: 'issues',
        searchKey: 'search',
        displayTpl: (function(_this) {
          return function(value) {
            if (value.title != null) {
              return _this.Issues.template;
            } else {
              return _this.Loading.template;
            }
          };
        })(this),
        data: ['loading'],
        insertTpl: '${atwho-at}${id}',
        callbacks: {
          sorter: this.DefaultOptions.sorter,
          filter: this.DefaultOptions.filter,
          beforeInsert: this.DefaultOptions.beforeInsert,
          beforeSave: function(issues) {
            return $.map(issues, function(i) {
              if (i.title == null) {
                return i;
              }
              return {
                id: i.iid,
                title: sanitize(i.title),
                search: i.iid + " " + i.title
              };
            });
          }
        }
      });
      this.input.atwho({
        at: '%',
        alias: 'milestones',
        searchKey: 'search',
        displayTpl: (function(_this) {
          return function(value) {
            if (value.title != null) {
              return _this.Milestones.template;
            } else {
              return _this.Loading.template;
            }
          };
        })(this),
        insertTpl: '${atwho-at}"${title}"',
        data: ['loading'],
        callbacks: {
          beforeSave: function(milestones) {
            return $.map(milestones, function(m) {
              if (m.title == null) {
                return m;
              }
              return {
                id: m.iid,
                title: sanitize(m.title),
                search: "" + m.title
              };
            });
          }
        }
      });
      this.input.atwho({
        at: '!',
        alias: 'mergerequests',
        searchKey: 'search',
        displayTpl: (function(_this) {
          return function(value) {
            if (value.title != null) {
              return _this.Issues.template;
            } else {
              return _this.Loading.template;
            }
          };
        })(this),
        data: ['loading'],
        insertTpl: '${atwho-at}${id}',
        callbacks: {
          sorter: this.DefaultOptions.sorter,
          filter: this.DefaultOptions.filter,
          beforeInsert: this.DefaultOptions.beforeInsert,
          beforeSave: function(merges) {
            return $.map(merges, function(m) {
              if (m.title == null) {
                return m;
              }
              return {
                id: m.iid,
                title: sanitize(m.title),
                search: m.iid + " " + m.title
              };
            });
          }
        }
      });
      this.input.atwho({
        at: '~',
        alias: 'labels',
        searchKey: 'search',
        displayTpl: this.Labels.template,
        insertTpl: '${atwho-at}${title}',
        callbacks: {
          beforeSave: function(merges) {
            var sanitizeLabelTitle;
            sanitizeLabelTitle = function(title) {
              if (/[\w\?&]+\s+[\w\?&]+/g.test(title)) {
                return "\"" + (sanitize(title)) + "\"";
              } else {
                return sanitize(title);
              }
            };
            return $.map(merges, function(m) {
              return {
                title: sanitizeLabelTitle(m.title),
                color: m.color,
                search: "" + m.title
              };
            });
          }
        }
      });
      // We don't instantiate the slash commands autocomplete for note edit forms
      $("form:not(.edit-note) .js-gfm-input").atwho({
        at: '/',
        alias: 'commands',
        displayTpl: function(value) {
          var tpl = '
/${name}';
          if (value.aliases.length > 0) {
            tpl += ' (or /<%- aliases.join(", /") %>)';
          }
          if (value.params.length > 0) {
            tpl += ' <%- params.join(" ") %>';
          }
          if (value.description !== '') {
            tpl += '<%- description %>';
          }
          tpl += '
';
          return _.template(tpl)(value);
        },
        insertTpl: function(value) {
          var tpl = "\n/${name} ";
          var reference_prefix = null;
          if (value.params.length > 0) {
            reference_prefix = value.params[0][0];
            if (/^[@%~]/.test(reference_prefix)) {
              tpl += '<%- reference_prefix %>';
            }
          }
          return _.template(tpl)({ reference_prefix: reference_prefix });
        },
        suffix: '',
        callbacks: {
          sorter: this.DefaultOptions.sorter,
          filter: this.DefaultOptions.filter,
          beforeInsert: this.DefaultOptions.beforeInsert
        }
      });
      return;
    },
    destroyAtWho: function() {
      return this.input.atwho('destroy');
    },
    fetchData: function(dataSource) {
      return $.getJSON(dataSource);
    },
    loadData: function(data) {
      this.cachedData = data;
      this.dataLoaded = true;
      this.input.atwho('load', '@', data.members);
      this.input.atwho('load', 'issues', data.issues);
      this.input.atwho('load', 'milestones', data.milestones);
      this.input.atwho('load', 'mergerequests', data.mergerequests);
      this.input.atwho('load', ':', data.emojis);
      this.input.atwho('load', '~', data.labels);
      this.input.atwho('load', '/', data.commands);
      return $(':focus').trigger('keyup');
    }
  };

}).call(this);
<commit_msg>Only autocomplete commands at the beginning of a line<commit_after>(function() {
  if (window.GitLab == null) {
    window.GitLab = {};
  }

  GitLab.GfmAutoComplete = {
    dataLoading: false,
    dataLoaded: false,
    cachedData: {},
    dataSource: '',
    Emoji: {
      template: '
${name}
'
    },
    Members: {
      template: '
${username} ${title}
'
    },
    Labels: {
      template: '
 ${title}
'
    },
    Issues: {
      template: '
${id} ${title}
'
    },
    Milestones: {
      template: '
${title}
'
    },
    Loading: {
      template: '
 Loading...
'
    },
    DefaultOptions: {
      sorter: function(query, items, searchKey) {
        if ((items[0].name != null) && items[0].name === 'loading') {
          return items;
        }
        return $.fn.atwho["default"].callbacks.sorter(query, items, searchKey);
      },
      filter: function(query, data, searchKey) {
        if (data[0] === 'loading') {
          return data;
        }
        return $.fn.atwho["default"].callbacks.filter(query, data, searchKey);
      },
      beforeInsert: function(value) {
        if (!GitLab.GfmAutoComplete.dataLoaded) {
          return this.at;
        } else {
          return value;
        }
      }
    },
    setup: function(input) {
      this.input = input || $('.js-gfm-input');
      this.destroyAtWho();
      this.setupAtWho();
      if (this.dataSource) {
        if (!this.dataLoading && !this.cachedData) {
          this.dataLoading = true;
          setTimeout((function(_this) {
            return function() {
              var fetch;
              fetch = _this.fetchData(_this.dataSource);
              return fetch.done(function(data) {
                _this.dataLoading = false;
                return _this.loadData(data);
              });
            };
          })(this), 1000);
        }
        if (this.cachedData != null) {
          return this.loadData(this.cachedData);
        }
      }
    },
    setupAtWho: function() {
      this.input.atwho({
        at: ':',
        displayTpl: (function(_this) {
          return function(value) {
            if (value.path != null) {
              return _this.Emoji.template;
            } else {
              return _this.Loading.template;
            }
          };
        })(this),
        insertTpl: ':${name}:',
        data: ['loading'],
        callbacks: {
          sorter: this.DefaultOptions.sorter,
          filter: this.DefaultOptions.filter,
          beforeInsert: this.DefaultOptions.beforeInsert
        }
      });
      this.input.atwho({
        at: '@',
        displayTpl: (function(_this) {
          return function(value) {
            if (value.username != null) {
              return _this.Members.template;
            } else {
              return _this.Loading.template;
            }
          };
        })(this),
        insertTpl: '${atwho-at}${username}',
        searchKey: 'search',
        data: ['loading'],
        callbacks: {
          sorter: this.DefaultOptions.sorter,
          filter: this.DefaultOptions.filter,
          beforeInsert: this.DefaultOptions.beforeInsert,
          beforeSave: function(members) {
            return $.map(members, function(m) {
              var title;
              if (m.username == null) {
                return m;
              }
              title = m.name;
              if (m.count) {
                title += " (" + m.count + ")";
              }
              return {
                username: m.username,
                title: sanitize(title),
                search: sanitize(m.username + " " + m.name)
              };
            });
          }
        }
      });
      this.input.atwho({
        at: '#',
        alias: 'issues',
        searchKey: 'search',
        displayTpl: (function(_this) {
          return function(value) {
            if (value.title != null) {
              return _this.Issues.template;
            } else {
              return _this.Loading.template;
            }
          };
        })(this),
        data: ['loading'],
        insertTpl: '${atwho-at}${id}',
        callbacks: {
          sorter: this.DefaultOptions.sorter,
          filter: this.DefaultOptions.filter,
          beforeInsert: this.DefaultOptions.beforeInsert,
          beforeSave: function(issues) {
            return $.map(issues, function(i) {
              if (i.title == null) {
                return i;
              }
              return {
                id: i.iid,
                title: sanitize(i.title),
                search: i.iid + " " + i.title
              };
            });
          }
        }
      });
      this.input.atwho({
        at: '%',
        alias: 'milestones',
        searchKey: 'search',
        displayTpl: (function(_this) {
          return function(value) {
            if (value.title != null) {
              return _this.Milestones.template;
            } else {
              return _this.Loading.template;
            }
          };
        })(this),
        insertTpl: '${atwho-at}"${title}"',
        data: ['loading'],
        callbacks: {
          beforeSave: function(milestones) {
            return $.map(milestones, function(m) {
              if (m.title == null) {
                return m;
              }
              return {
                id: m.iid,
                title: sanitize(m.title),
                search: "" + m.title
              };
            });
          }
        }
      });
      this.input.atwho({
        at: '!',
        alias: 'mergerequests',
        searchKey: 'search',
        displayTpl: (function(_this) {
          return function(value) {
            if (value.title != null) {
              return _this.Issues.template;
            } else {
              return _this.Loading.template;
            }
          };
        })(this),
        data: ['loading'],
        insertTpl: '${atwho-at}${id}',
        callbacks: {
          sorter: this.DefaultOptions.sorter,
          filter: this.DefaultOptions.filter,
          beforeInsert: this.DefaultOptions.beforeInsert,
          beforeSave: function(merges) {
            return $.map(merges, function(m) {
              if (m.title == null) {
                return m;
              }
              return {
                id: m.iid,
                title: sanitize(m.title),
                search: m.iid + " " + m.title
              };
            });
          }
        }
      });
      this.input.atwho({
        at: '~',
        alias: 'labels',
        searchKey: 'search',
        displayTpl: this.Labels.template,
        insertTpl: '${atwho-at}${title}',
        callbacks: {
          beforeSave: function(merges) {
            var sanitizeLabelTitle;
            sanitizeLabelTitle = function(title) {
              if (/[\w\?&]+\s+[\w\?&]+/g.test(title)) {
                return "\"" + (sanitize(title)) + "\"";
              } else {
                return sanitize(title);
              }
            };
            return $.map(merges, function(m) {
              return {
                title: sanitizeLabelTitle(m.title),
                color: m.color,
                search: "" + m.title
              };
            });
          }
        }
      });
      // We don't instantiate the slash commands autocomplete for note edit forms
      $("form:not(.edit-note) .js-gfm-input").atwho({
        at: '/',
        alias: 'commands',
        displayTpl: function(value) {
          var tpl = '
/${name}';
          if (value.aliases.length > 0) {
            tpl += ' (or /<%- aliases.join(", /") %>)';
          }
          if (value.params.length > 0) {
            tpl += ' <%- params.join(" ") %>';
          }
          if (value.description !== '') {
            tpl += '<%- description %>';
          }
          tpl += '
';
          return _.template(tpl)(value);
        },
        insertTpl: function(value) {
          var tpl = "/${name} ";
          var reference_prefix = null;
          if (value.params.length > 0) {
            reference_prefix = value.params[0][0];
            if (/^[@%~]/.test(reference_prefix)) {
              tpl += '<%- reference_prefix %>';
            }
          }
          return _.template(tpl)({ reference_prefix: reference_prefix });
        },
        suffix: '',
        callbacks: {
          sorter: this.DefaultOptions.sorter,
          filter: this.DefaultOptions.filter,
          beforeInsert: this.DefaultOptions.beforeInsert,
          matcher: function(flag, subtext, should_startWithSpace, acceptSpaceBar) {
            var regexp = /(?:^|\n)\/([A-Za-z_]*)$/gi
            var match = regexp.exec(subtext);
            if (match) {
              return match[1];
            } else {
              return null;
            }
          }
        }
      });
      return;
    },
    destroyAtWho: function() {
      return this.input.atwho('destroy');
    },
    fetchData: function(dataSource) {
      return $.getJSON(dataSource);
    },
    loadData: function(data) {
      this.cachedData = data;
      this.dataLoaded = true;
      this.input.atwho('load', '@', data.members);
      this.input.atwho('load', 'issues', data.issues);
      this.input.atwho('load', 'milestones', data.milestones);
      this.input.atwho('load', 'mergerequests', data.mergerequests);
      this.input.atwho('load', ':', data.emojis);
      this.input.atwho('load', '~', data.labels);
      this.input.atwho('load', '/', data.commands);
      return $(':focus').trigger('keyup');
    }
  };

}).call(this);
<|endoftext|>


<commit_before>angular.module('ocWebGui.stats', ['ui.router', 'nvd3'])
  .config(function ($stateProvider) {
    $stateProvider
      .state('stats', {
        url: '/stats',
        templateUrl: 'stats/_stats.html',
        controller: 'StatsController',
        controllerAs: 'stats'
      });
  })
  .controller('StatsController', function ($scope, $http, $interval) {
    var vm = this;
    vm.title = 'Tilastot';
  });
<commit_msg>remove unsued injection<commit_after>angular.module('ocWebGui.stats', ['ui.router', 'nvd3'])
  .config(function ($stateProvider) {
    $stateProvider
      .state('stats', {
        url: '/stats',
        templateUrl: 'stats/_stats.html',
        controller: 'StatsController',
        controllerAs: 'stats'
      });
  })
  .controller('StatsController', function ($scope, $http) {
    var vm = this;
    vm.title = 'Tilastot';
  });
<|endoftext|>


<commit_before>'use strict';
import React from 'react';
import ReactCSSTransitionGroup from 'react-addons-css-transition-group';

// Minimum time the loading is visible.
const MIN_TIME = 512;

// Once the component is mounted we store it to be able to access it from
// the outside.
var theGlobalLoading = null;

const GlobalLoading = React.createClass({
  componentAddedBodyClass: false,

  getInitialState: function () {
    return {
      showTimestamp: 0,
      revealed: false
    };
  },

  toggleBodyClass: function (revealed) {
    let bd = document.getElementsByTagName('body')[0];
    if (revealed) {
      this.componentAddedBodyClass = true;
      bd.classList.add('unscrollable-y');
    } else if (this.componentAddedBodyClass) {
      // Only act if the class was added by this component.
      this.componentAddedBodyClass = false;
      bd.classList.remove('unscrollable-y');
    }
  },

  componentDidMount: function () {
    if (theGlobalLoading !== null) {
      throw new Error('<GlobalLoading /> component was already mounted. Only 1 is allowed.');
    }
    theGlobalLoading = this;
    this.toggleBodyClass(this.state.revealed);
  },

  componentDidUpdate: function () {
    this.toggleBodyClass(this.state.revealed);
  },

  componentWillUnmount: function () {
    this.toggleBodyClass(false);
  },

  renderLoading: function () {
    return (

    );
  },

  render: function () {
    return (
      <ReactCSSTransitionGroup
        component='div'
        transitionName='loading-pane'
        transitionEnterTimeout={300}
        transitionLeaveTimeout={300} >

        {this.state.revealed ? this.renderLoading() : null}

      </ReactCSSTransitionGroup>
    );
  }
});

export default GlobalLoading;

export function showGlobalLoading () {
  if (theGlobalLoading === null) {
    throw new Error('<GlobalLoading /> component not mounted');
  }

  theGlobalLoading.setState(Object.assign({}, {
    showTimestamp: Date.now(),
    revealed: true
  }));
}

export function hideGlobalLoading (force = false) {
  if (theGlobalLoading === null) {
    throw new Error('<GlobalLoading /> component not mounted');
  }

  if (force) {
    return theGlobalLoading.setState(Object.assign({}, {
      revealed: false
    }));
  }

  let time = theGlobalLoading.state.showTimestamp;
  let diff = Date.now() - time;
  if (diff >= MIN_TIME) {
    theGlobalLoading.setState(Object.assign({}, {
      revealed: false
    }));
  } else {
    setTimeout(() => {
      theGlobalLoading.setState(Object.assign({}, {
        revealed: false
      }));
    }, MIN_TIME - diff);
  }
}
<commit_msg>Clear timeout when showing loading<commit_after>'use strict';
import React from 'react';
import ReactCSSTransitionGroup from 'react-addons-css-transition-group';

// Minimum time the loading is visible.
const MIN_TIME = 512;
// Since we have a minimum display time we use a timeout to hide it if
// when the hide method is called the time isn't over yet. However, if in
// the mean time the loading is shown again we need to clear the timeout.
var hideTimeout = null;

// Once the component is mounted we store it to be able to access it from
// the outside.
var theGlobalLoading = null;

const GlobalLoading = React.createClass({
  componentAddedBodyClass: false,

  getInitialState: function () {
    return {
      showTimestamp: 0,
      revealed: false
    };
  },

  toggleBodyClass: function (revealed) {
    let bd = document.getElementsByTagName('body')[0];
    if (revealed) {
      this.componentAddedBodyClass = true;
      bd.classList.add('unscrollable-y');
    } else if (this.componentAddedBodyClass) {
      // Only act if the class was added by this component.
      this.componentAddedBodyClass = false;
      bd.classList.remove('unscrollable-y');
    }
  },

  componentDidMount: function () {
    if (theGlobalLoading !== null) {
      throw new Error('<GlobalLoading /> component was already mounted. Only 1 is allowed.');
    }
    theGlobalLoading = this;
    this.toggleBodyClass(this.state.revealed);
  },

  componentDidUpdate: function () {
    this.toggleBodyClass(this.state.revealed);
  },

  componentWillUnmount: function () {
    this.toggleBodyClass(false);
  },

  renderLoading: function () {
    return (

    );
  },

  render: function () {
    return (
      <ReactCSSTransitionGroup
        component='div'
        transitionName='loading-pane'
        transitionEnterTimeout={300}
        transitionLeaveTimeout={300} >

        {this.state.revealed ? this.renderLoading() : null}

      </ReactCSSTransitionGroup>
    );
  }
});

export default GlobalLoading;

export function showGlobalLoading () {
  if (theGlobalLoading === null) {
    throw new Error('<GlobalLoading /> component not mounted');
  }
  if (hideTimeout) {
    clearTimeout(hideTimeout);
  }

  theGlobalLoading.setState(Object.assign({}, {
    showTimestamp: Date.now(),
    revealed: true
  }));
}

export function hideGlobalLoading (force = false) {
  if (theGlobalLoading === null) {
    throw new Error('<GlobalLoading /> component not mounted');
  }

  if (force) {
    return theGlobalLoading.setState(Object.assign({}, {
      revealed: false
    }));
  }

  let time = theGlobalLoading.state.showTimestamp;
  let diff = Date.now() - time;
  if (diff >= MIN_TIME) {
    theGlobalLoading.setState(Object.assign({}, {
      revealed: false
    }));
  } else {
    hideTimeout = setTimeout(() => {
      theGlobalLoading.setState(Object.assign({}, {
        revealed: false
      }));
    }, MIN_TIME - diff);
  }
}
<|endoftext|>


<commit_before>var redis = require('redis-scanstreams')(require('redis')).createClient();
var tredis = require('then-redis').createClient();
var redisChan = require('redis').createClient();
var kue = require('kue');
var queue = require('./queue');
var auth = require('socketio-auth');
var Promise = require('bluebird');
var models = require('./models');

function deviceConnected(deviceId) {
  return new Promise(function(resolve, reject) {
    tredis.exists('musichub.device.' + deviceId + '.connection').then(function(result) {
      resolve(Boolean(parseInt(result)));
    });
  });
}

function createDeviceState(deviceId) {
  return new Promise(function(resolve, reject) {
    Promise.props({
      Connected: tredis.exists('musichub.device.' + deviceId + '.connection'),
      Current: tredis.get('musichub.device.' + deviceId + '.current'),
      Duration: tredis.get('musichub.device.' + deviceId + '.duration'),
      Playing: tredis.get('musichub.device.' + deviceId + '.playing'),
      Paused: tredis.get('musichub.device.' + deviceId + '.paused'),
      Queue: tredis.lrange('musichub.device.' + deviceId + '.queue', 0, -1)
    }).then(function(result) {
      resolve({
        Connected: Boolean(parseInt(result.Connected)),
        Current: parseInt(result.Current),
        Duration: parseInt(result.Duration),
        Playing: Boolean(parseInt(result.Playing)),
        Paused: Boolean(parseInt(result.Paused)),
        Queue: result.Queue.map(function(item) {
          return parseInt(item);
        })
      });
    });
  });
}

function isRegistered(clientId, deviceId) {
  return new Promise(function(resolve, reject) {
    tredis.get('musichub.device.' + deviceId + '.connection').then(function(deviceConnection) {
      if (deviceConnection === clientId) {
        resolve(true);
      }
      else {
        tredis.sismember('musichub.device.' + deviceId + '.clients', clientId).then(function(reply) {
          resolve(Boolean(parseInt(reply)));
        });
      }
    });
  });
}

function checkRegistration(clientId, deviceId, skipDevice) {
  return new Promise(function(resolve, reject) {
    isRegistered(clientId, deviceId).then(function(registered) {
      if (registered) {
        if (skipDevice === true) {
          return resolve();
        }
        tredis.exists('musichub.device.' + deviceId + '.connection').then(function(exists) {
          if (Boolean(parseInt(exists))) {
            resolve();
          }
        })
      }
    });
  });
}

function sendClientState(io, socket, deviceId) {
  return new Promise(function(resolve, reject) {
    createDeviceState(deviceId).then(function(state) {
      io.sockets.to('device.' + deviceId).emit('SetState', state);
      resolve();
    });
  });
}

function updateState(deviceId) {
  return new Promise(function(resolve, reject) {
    Promise.props({
      current: tredis.lpop('musichub.device.' + deviceId + '.queue'),
      currentDeviceTrack: tredis.lpop('musichub.device.' + deviceId + '.queue.device'),
    }).then(function(props) {
      tredis.set('musichub.device.' + deviceId + '.current', props.current).then(function() {
        new models.DeviceTrack({
          DeviceId: deviceId,
          TrackId: props.current
        }).fetch().then(function(dt) {
          tredis.set('musichub.device.' + deviceId + '.duration', dt.get('TrackDuration')).then(function() {
            resolve(props.currentDeviceTrack);
          })
        });
      });
    })
  });
}

function addTrackToQueue(deviceId, trackId) {
  return new Promise(function(resolve, reject) {
    new models.DeviceTrack({
      DeviceId: deviceId,
      TrackId: trackId
    }).fetch().then(function(dt) {
      var deviceTrackId = dt.get('DeviceTrackId');
      Promise.all([
        tredis.rpush('musichub.device.' + deviceId + '.queue', trackId),
        tredis.rpush('musichub.device.' + deviceId + '.queue.device', deviceTrackId)
      ]).then(function() {
        resolve();
      })
    });
  });
}

function requestNext(io, socket, deviceId) {
  tredis.set('musichub.device.' + deviceId + '.playing', 0).then(function() {
    sendClientState(io, socket, deviceId).then(function() {
      tredis.get('musichub.device.' + deviceId + '.connection').then(function(deviceClientId) {
        io.sockets.to(deviceClientId).emit('Stop');
      });
    });
  });
}

function play(io, socket, deviceId) {
  tredis.get('musichub.device.' + deviceId + '.connection').then(function(deviceClientId) {
    tredis.llen('musichub.device.' + deviceId + '.queue').then(function(queueLen) {
      if (parseInt(queueLen) > 0) {
        tredis.set('musichub.device.' + deviceId + '.playing', 1);
        tredis.get('musichub.device.' + deviceId + '.paused').then(function(paused) {
          if (!Boolean(parseInt(paused))) {
            io.sockets.to(deviceClientId).emit('Stop');
            updateState(deviceId).then(function(currentDeviceTrack) {
              io.sockets.to(deviceClientId).emit('SetTrackId', currentDeviceTrack);
              io.sockets.to(deviceClientId).emit('Play');
              sendClientState(io, socket, deviceId);
            });
          }
          else {
            tredis.set('musichub.device.' + deviceId + '.paused', 0).then(function() {
              io.sockets.to(deviceClientId).emit('Play');
              sendClientState(io, socket, deviceId);
            });
          }
        });
      }
    });
  })
}

function onDisconnect(io, socket, clientId) {
  tredis.get('musichub.devices.' + clientId).then(function(deviceId) {
    if (deviceId !== null) {
      Promise.all([
        tredis.del('musichub.device.' + deviceId + '.current'),
        tredis.del('musichub.device.' + deviceId + '.duration'),
        tredis.del('musichub.device.' + deviceId + '.playing'),
        tredis.del('musichub.device.' + deviceId + '.paused'),
        tredis.del('musichub.device.' + deviceId + '.queue'),
        tredis.del('musichub.device.' + deviceId + '.queue.device'),
        tredis.del('musichub.device.' + deviceId + '.clients'),
        tredis.del('musichub.device.' + deviceId + '.connection'),
      ]);
      sendClientState(io, socket, deviceId);
    }
    else {
      tredis.smembers('musichub.client.' + clientId + '.devices').then(function(members) {
        members.forEach(function(member) {
          tredis.srem('musichub.client.' + clientId + '.devices', member);
          tredis.srem('musichub.device.' + member + '.clients', clientId);
        }.bind(this));
      });
    }
  });
}

function reportSubmissionStatus(socket, deviceId) {
  redisChan.on('message', function(channel, message) {
    if (channel === 'submissions.' + deviceId + '.progress') {
      socket.emit('Submission', {
        processing: true,
        progress: parseInt(message)
      });
    }

    if (channel === 'submissions.' + deviceId + '.processing') {
      socket.emit('Submission', {
        processing: Boolean(parseInt(message))
      });
    }
  });
  redisChan.subscribe('submissions.' + deviceId + '.processing');
  redisChan.subscribe('submissions.' + deviceId + '.progress');
}

function hub(io, clientId, socket) {
  socket.on('RegisterDevice', function(deviceId) {
    new models.Device({
      Id: deviceId
    }).fetch().then(function(device) {
      if (device.get('OwnerId') === socket.client.user.id) {
        tredis.set('musichub.devices.' + clientId, deviceId);
        tredis.set('musichub.device.' + deviceId + '.connection', clientId);
        sendClientState(io, socket, deviceId);
      }
    });
  });

  socket.on('RegisterClient', function(data) {
    var deviceId = data.DeviceId;
    new models.Device({
      Id: deviceId
    }).fetch().then(function(device) {
      if (device.get('OwnerId') === socket.client.user.id) {
        Promise.all([
          tredis.sadd('musichub.client.' + clientId + '.devices', deviceId),
          tredis.sadd('musichub.device.' + deviceId + '.clients', clientId),
          socket.join('device.' + deviceId)
        ]).then(function() {
          socket.emit('ClientRegistered');
        });
        reportSubmissionStatus(socket, deviceId);
      }
    });
  });

  socket.on('Queue', function(data) {
    var deviceId = data.DeviceId;
    var trackIds = data.TrackIds;

    checkRegistration(socket.id, deviceId).then(function() {
      Promise.all([
        tredis.del('musichub.device.' + deviceId + '.queue'),
        tredis.del('musichub.device.' + deviceId + '.queue.device')
      ]).then(function() {
        Promise.each(trackIds, function(trackId) {
          return addTrackToQueue(deviceId, trackId);
        }).then(function() {
          sendClientState(io, socket, deviceId).then(function() {
            tredis.get('musichub.device.' + deviceId + '.playing').then(function(playing) {
              if (Boolean(parseInt(playing))) {
                requestNext(io, socket, deviceId);
              }
              else {
                tredis.set('musichub.device.' + deviceId + '.playing', 0).then(function() {
                  play(io, socket, deviceId);
                });
              }
            });
          })
        });
      });
    });
  });

  socket.on('GetState', function(deviceId) {
    checkRegistration(socket.id, deviceId, true).then(function() {
      createDeviceState(deviceId).then(function(state) {
        socket.emit('SetState', state);
      })
    });
  });

  socket.on('Play', function(data) {
    checkRegistration(socket.id, data.DeviceId).then(function() {
      play(io, socket, data.DeviceId);
    });
  });

  socket.on('Pause', function(data) {
    checkRegistration(socket.id, data.DeviceId).then(function() {
      var deviceId = data.DeviceId;
      Promise.all([
        tredis.set('musichub.device.' + deviceId + '.playing', 0),
        tredis.set('musichub.device.' + deviceId + '.paused', 1)
      ]).then(function() {
        sendClientState(io, socket, deviceId);
        tredis.get('musichub.device.' + deviceId + '.connection').then(function(deviceClientId) {
          io.sockets.to(deviceClientId).emit('Pause');
        });
      });
    });
  })

  socket.on('RequestNext', function(data) {
    checkRegistration(socket.id, data.DeviceId).then(function() {
      requestNext(io, socket, data.DeviceId);
    });
  });

  socket.on('Next', function(deviceId) {
    checkRegistration(socket.id, deviceId).then(function() {
      tredis.llen('musichub.device.' + deviceId + '.queue').then(function(queueLen) {
        queueLen = parseInt(queueLen);
        if (queueLen !== 0) {
          play(io, socket, deviceId);
        }
      })
    });
  });
}

function authenticate(token, callback) {
  new models.User({
    Token: token
  }).fetch().then(function(user) {
    return callback(null, true);
  }).catch(function(err) {
    return callback(new Error('Invalid authentication token'));
  });
}

function postAuthenticate(socket, token) {
  new models.User({
    Token: token
  }).fetch().then(function(user) {
    socket.client.user = user;
  }).catch(function(err) {
    return callback(new Error('Invalid authentication token'));
  });
}

module.exports = function(io) {
  auth(io, {
    authenticate: authenticate,
    postAuthenticate: postAuthenticate
  });

  io.on('connection', function(socket) {
    var clientId = socket.id;
    hub(io, clientId, socket);
    socket.on('disconnect', function(socket) {
      onDisconnect(io, socket, clientId);
    })
  })
}
<commit_msg>Don't delete clients authorization on device disconnect<commit_after>var redis = require('redis-scanstreams')(require('redis')).createClient();
var tredis = require('then-redis').createClient();
var redisChan = require('redis').createClient();
var kue = require('kue');
var queue = require('./queue');
var auth = require('socketio-auth');
var Promise = require('bluebird');
var models = require('./models');

function deviceConnected(deviceId) {
  return new Promise(function(resolve, reject) {
    tredis.exists('musichub.device.' + deviceId + '.connection').then(function(result) {
      resolve(Boolean(parseInt(result)));
    });
  });
}

function createDeviceState(deviceId) {
  return new Promise(function(resolve, reject) {
    Promise.props({
      Connected: tredis.exists('musichub.device.' + deviceId + '.connection'),
      Current: tredis.get('musichub.device.' + deviceId + '.current'),
      Duration: tredis.get('musichub.device.' + deviceId + '.duration'),
      Playing: tredis.get('musichub.device.' + deviceId + '.playing'),
      Paused: tredis.get('musichub.device.' + deviceId + '.paused'),
      Queue: tredis.lrange('musichub.device.' + deviceId + '.queue', 0, -1)
    }).then(function(result) {
      resolve({
        Connected: Boolean(parseInt(result.Connected)),
        Current: parseInt(result.Current),
        Duration: parseInt(result.Duration),
        Playing: Boolean(parseInt(result.Playing)),
        Paused: Boolean(parseInt(result.Paused)),
        Queue: result.Queue.map(function(item) {
          return parseInt(item);
        })
      });
    });
  });
}

function isRegistered(clientId, deviceId) {
  return new Promise(function(resolve, reject) {
    tredis.get('musichub.device.' + deviceId + '.connection').then(function(deviceConnection) {
      if (deviceConnection === clientId) {
        resolve(true);
      }
      else {
        tredis.sismember('musichub.device.' + deviceId + '.clients', clientId).then(function(reply) {
          resolve(Boolean(parseInt(reply)));
        });
      }
    });
  });
}

function checkRegistration(clientId, deviceId, skipDevice) {
  return new Promise(function(resolve, reject) {
    isRegistered(clientId, deviceId).then(function(registered) {
      if (registered) {
        if (skipDevice === true) {
          return resolve();
        }
        tredis.exists('musichub.device.' + deviceId + '.connection').then(function(exists) {
          if (Boolean(parseInt(exists))) {
            resolve();
          }
        })
      }
    });
  });
}

function sendClientState(io, socket, deviceId) {
  return new Promise(function(resolve, reject) {
    createDeviceState(deviceId).then(function(state) {
      io.sockets.to('device.' + deviceId).emit('SetState', state);
      resolve();
    });
  });
}

function updateState(deviceId) {
  return new Promise(function(resolve, reject) {
    Promise.props({
      current: tredis.lpop('musichub.device.' + deviceId + '.queue'),
      currentDeviceTrack: tredis.lpop('musichub.device.' + deviceId + '.queue.device'),
    }).then(function(props) {
      tredis.set('musichub.device.' + deviceId + '.current', props.current).then(function() {
        new models.DeviceTrack({
          DeviceId: deviceId,
          TrackId: props.current
        }).fetch().then(function(dt) {
          tredis.set('musichub.device.' + deviceId + '.duration', dt.get('TrackDuration')).then(function() {
            resolve(props.currentDeviceTrack);
          })
        });
      });
    })
  });
}

function addTrackToQueue(deviceId, trackId) {
  return new Promise(function(resolve, reject) {
    new models.DeviceTrack({
      DeviceId: deviceId,
      TrackId: trackId
    }).fetch().then(function(dt) {
      var deviceTrackId = dt.get('DeviceTrackId');
      Promise.all([
        tredis.rpush('musichub.device.' + deviceId + '.queue', trackId),
        tredis.rpush('musichub.device.' + deviceId + '.queue.device', deviceTrackId)
      ]).then(function() {
        resolve();
      })
    });
  });
}

function requestNext(io, socket, deviceId) {
  tredis.set('musichub.device.' + deviceId + '.playing', 0).then(function() {
    sendClientState(io, socket, deviceId).then(function() {
      tredis.get('musichub.device.' + deviceId + '.connection').then(function(deviceClientId) {
        io.sockets.to(deviceClientId).emit('Stop');
      });
    });
  });
}

function play(io, socket, deviceId) {
  tredis.get('musichub.device.' + deviceId + '.connection').then(function(deviceClientId) {
    tredis.llen('musichub.device.' + deviceId + '.queue').then(function(queueLen) {
      if (parseInt(queueLen) > 0) {
        tredis.set('musichub.device.' + deviceId + '.playing', 1);
        tredis.get('musichub.device.' + deviceId + '.paused').then(function(paused) {
          if (!Boolean(parseInt(paused))) {
            io.sockets.to(deviceClientId).emit('Stop');
            updateState(deviceId).then(function(currentDeviceTrack) {
              io.sockets.to(deviceClientId).emit('SetTrackId', currentDeviceTrack);
              io.sockets.to(deviceClientId).emit('Play');
              sendClientState(io, socket, deviceId);
            });
          }
          else {
            tredis.set('musichub.device.' + deviceId + '.paused', 0).then(function() {
              io.sockets.to(deviceClientId).emit('Play');
              sendClientState(io, socket, deviceId);
            });
          }
        });
      }
    });
  })
}

function onDisconnect(io, socket, clientId) {
  tredis.get('musichub.devices.' + clientId).then(function(deviceId) {
    if (deviceId !== null) {
      Promise.all([
        tredis.del('musichub.device.' + deviceId + '.current'),
        tredis.del('musichub.device.' + deviceId + '.duration'),
        tredis.del('musichub.device.' + deviceId + '.playing'),
        tredis.del('musichub.device.' + deviceId + '.paused'),
        tredis.del('musichub.device.' + deviceId + '.queue'),
        tredis.del('musichub.device.' + deviceId + '.queue.device'),
        tredis.del('musichub.device.' + deviceId + '.connection'),
      ]);
      sendClientState(io, socket, deviceId);
    }
    else {
      tredis.smembers('musichub.client.' + clientId + '.devices').then(function(members) {
        members.forEach(function(member) {
          tredis.srem('musichub.client.' + clientId + '.devices', member);
          tredis.srem('musichub.device.' + member + '.clients', clientId);
        }.bind(this));
      });
    }
  });
}

function reportSubmissionStatus(socket, deviceId) {
  redisChan.on('message', function(channel, message) {
    if (channel === 'submissions.' + deviceId + '.progress') {
      socket.emit('Submission', {
        processing: true,
        progress: parseInt(message)
      });
    }

    if (channel === 'submissions.' + deviceId + '.processing') {
      socket.emit('Submission', {
        processing: Boolean(parseInt(message))
      });
    }
  });
  redisChan.subscribe('submissions.' + deviceId + '.processing');
  redisChan.subscribe('submissions.' + deviceId + '.progress');
}

function hub(io, clientId, socket) {
  socket.on('RegisterDevice', function(deviceId) {
    new models.Device({
      Id: deviceId
    }).fetch().then(function(device) {
      if (device.get('OwnerId') === socket.client.user.id) {
        tredis.set('musichub.devices.' + clientId, deviceId);
        tredis.set('musichub.device.' + deviceId + '.connection', clientId);
        sendClientState(io, socket, deviceId);
      }
    });
  });

  socket.on('RegisterClient', function(data) {
    var deviceId = data.DeviceId;
    new models.Device({
      Id: deviceId
    }).fetch().then(function(device) {
      if (device.get('OwnerId') === socket.client.user.id) {
        Promise.all([
          tredis.sadd('musichub.client.' + clientId + '.devices', deviceId),
          tredis.sadd('musichub.device.' + deviceId + '.clients', clientId),
          socket.join('device.' + deviceId)
        ]).then(function() {
          socket.emit('ClientRegistered');
        });
        reportSubmissionStatus(socket, deviceId);
      }
    });
  });

  socket.on('Queue', function(data) {
    var deviceId = data.DeviceId;
    var trackIds = data.TrackIds;

    checkRegistration(socket.id, deviceId).then(function() {
      Promise.all([
        tredis.del('musichub.device.' + deviceId + '.queue'),
        tredis.del('musichub.device.' + deviceId + '.queue.device')
      ]).then(function() {
        Promise.each(trackIds, function(trackId) {
          return addTrackToQueue(deviceId, trackId);
        }).then(function() {
          sendClientState(io, socket, deviceId).then(function() {
            tredis.get('musichub.device.' + deviceId + '.playing').then(function(playing) {
              if (Boolean(parseInt(playing))) {
                requestNext(io, socket, deviceId);
              }
              else {
                tredis.set('musichub.device.' + deviceId + '.playing', 0).then(function() {
                  play(io, socket, deviceId);
                });
              }
            });
          })
        });
      });
    });
  });

  socket.on('GetState', function(deviceId) {
    checkRegistration(socket.id, deviceId, true).then(function() {
      createDeviceState(deviceId).then(function(state) {
        socket.emit('SetState', state);
      })
    });
  });

  socket.on('Play', function(data) {
    checkRegistration(socket.id, data.DeviceId).then(function() {
      play(io, socket, data.DeviceId);
    });
  });

  socket.on('Pause', function(data) {
    checkRegistration(socket.id, data.DeviceId).then(function() {
      var deviceId = data.DeviceId;
      Promise.all([
        tredis.set('musichub.device.' + deviceId + '.playing', 0),
        tredis.set('musichub.device.' + deviceId + '.paused', 1)
      ]).then(function() {
        sendClientState(io, socket, deviceId);
        tredis.get('musichub.device.' + deviceId + '.connection').then(function(deviceClientId) {
          io.sockets.to(deviceClientId).emit('Pause');
        });
      });
    });
  })

  socket.on('RequestNext', function(data) {
    checkRegistration(socket.id, data.DeviceId).then(function() {
      requestNext(io, socket, data.DeviceId);
    });
  });

  socket.on('Next', function(deviceId) {
    checkRegistration(socket.id, deviceId).then(function() {
      tredis.llen('musichub.device.' + deviceId + '.queue').then(function(queueLen) {
        queueLen = parseInt(queueLen);
        if (queueLen !== 0) {
          play(io, socket, deviceId);
        }
      })
    });
  });
}

function authenticate(token, callback) {
  new models.User({
    Token: token
  }).fetch().then(function(user) {
    return callback(null, true);
  }).catch(function(err) {
    return callback(new Error('Invalid authentication token'));
  });
}

function postAuthenticate(socket, token) {
  new models.User({
    Token: token
  }).fetch().then(function(user) {
    socket.client.user = user;
  }).catch(function(err) {
    return callback(new Error('Invalid authentication token'));
  });
}

module.exports = function(io) {
  auth(io, {
    authenticate: authenticate,
    postAuthenticate: postAuthenticate
  });

  io.on('connection', function(socket) {
    var clientId = socket.id;
    hub(io, clientId, socket);
    socket.on('disconnect', function(socket) {
      onDisconnect(io, socket, clientId);
    })
  })
}
<|endoftext|>


<commit_before>var fs = require('fs');
ft = require('file-tail').startTailing('/var/log/secure');
var shell = require('shelljs');
var bufferString;

var listOfIpAddresses = [];
var bannedIPs = [];

var ipRegEx = /\d+\.\d+\.\d+\.\d+/;

var timeToCheck = process.argv[2];
var timeBeforeBan = process.argv[3];
var unbanTime = process.argv[4]

if(!process.argv[2] || !process.argv[3]){
    console.log("Usage: node ips.js timesToCheckBeforeBanning timeBeforeBanInSeconds timeToBanForInSeconds");
    process.exit(1);
}

//check to see if we need to unban everyone every minute
setInterval(function(){
    //check to see if we should unban people
    currentTime = new Date();
    for(var index in bannedIPs){
        var indexTime = bannedIPs[index];
        var difference = currentTime - indexTime;
        //if difference between current time and time
        //someone was banned, then unban them, son
        if(difference > unbanTime){
            console.log("Unbanning " + index + ".");
            shell.exec("iptables -D INPUT -s " + index + " -j DROP");
            delete bannedIPs(index);
        }
    }
}, 60000);

var logObject = function(ipAddress, primaryDateTimeOfFirstViolation){
    this.ipAddress = ipAddress;
    this.dateTime = [];
    //this.timeToCheck = process.argv[2];

    this.dateTime[0] = primaryDateTimeOfFirstViolation;

    this.addViolation = function(dateTimeOfViolation){
        //we only want to keep the last 10 failed attempts
        if(this.dateTime.length > 10){
            this.dateTime.shift();
        }
        // we add a violation to the datetime array here
        this.dateTime.push(dateTimeOfViolation);
        this.checkIfBan();
    }

    this.checkIfBan = function(){
        // check last n date Time's that they violated and see if
        // we need to ban them
        if(this.dateTime.length > timeToCheck){
            console.log("More attempts than allowed detected.");
            var lastLog = this.dateTime[this.dateTime.length - 1];
            var firstLog = this.dateTime[this.dateTime.length - 1 - timeToCheck];
            var timeDifference = (lastLog - firstLog) / 1000;
            //if difference between last attempt and first of range we want to check
            //is less than the time allowed for failed attempts set by user
            if(timeDifference <= timeBeforeBan){
                shell.exec("iptables -A INPUT -s " + this.ipAddress + " -j DROP");
                console.log(this.ipAddress + " has been banned");
                //add to banned array
                bannedIPs[this.ipAddress] = new Date();
            }

            //check for slow scan
            var countSlowFails = 0;
            //check for slow scan/patterns
            for(var i = 0; i < timeToCheck; i++){
                var timeOne = this.dateTime[this.dateTime.length - 1 - i]
                var timeTwo = this.dateTime[this.dateTime.length - 1 - (i + 1)]
                var timeDifference = (timeOne - timeTwo) / 1000;
                //if the previous time difference is equal to this time difference
                if(timeDifference >= ((timeBeforeBan / timeToCheck) - 1)){
                    console.log("Incrementing countSlowFails.");
                    countSlowFails++;
                    console.log("countSlowFails currently at: " + countSlowFails);
                }
                if(countSlowFails == timeToCheck){
                    shell.exec("iptables -A INPUT -s " + this.ipAddress + " -j DROP");
                    console.log("Slow scan via periodical attempts detected from IP: " + this.ipAddress);
                    console.log(this.ipAddress + " has been banned");
                    //add to banned array
                    this.bannedIPs[this.ipAddress] = new Date()
                    //iptables -D INPUT -s this.ipAddress -j DROP
                }
                prev = timeDifference;
            }
        }
    }

}

ft.on('line', function(line){
    bufferString += line;
    if(line.indexOf('Failed') > -1){
        var ip = line.match(ipRegEx);

        if(!listOfIpAddresses[ip[0]]){

        var lobj = new logObject(ip[0], new Date());
        listOfIpAddresses[ip[0]] = lobj;
    } else {
        listOfIpAddresses[ip[0]].addViolation(new Date());
    }
}

});
<commit_msg>is this going to work?<commit_after>var fs = require('fs');
ft = require('file-tail').startTailing('/var/log/secure');
var shell = require('shelljs');
var bufferString;

var listOfIpAddresses = [];
var bannedIPs = [];

var ipRegEx = /\d+\.\d+\.\d+\.\d+/;

var timeToCheck = process.argv[2];
var timeBeforeBan = process.argv[3];
var unbanTime = process.argv[4]

if(!process.argv[2] || !process.argv[3]){
    console.log("Usage: node ips.js timesToCheckBeforeBanning timeBeforeBanInSeconds timeToBanForInSeconds");
    process.exit(1);
}

//check to see if we need to unban everyone every minute
setInterval(function(){
    //check to see if we should unban people
    currentTime = new Date();
    for(var index in bannedIPs){
        var indexTime = bannedIPs[index];
        var difference = currentTime - indexTime;
        //if difference between current time and time
        //someone was banned, then unban them, son
        if(difference > unbanTime){
            console.log("Unbanning " + index + ".");
            shell.exec("iptables -D INPUT -s " + index + " -j DROP");
            console.log(bannedIPs);
            bannedIPs.splice(index, 1);
            console.log(bannedIPs);
        }
    }
}, 60000);

var logObject = function(ipAddress, primaryDateTimeOfFirstViolation){
    this.ipAddress = ipAddress;
    this.dateTime = [];
    //this.timeToCheck = process.argv[2];

    this.dateTime[0] = primaryDateTimeOfFirstViolation;

    this.addViolation = function(dateTimeOfViolation){
        //we only want to keep the last 10 failed attempts
        if(this.dateTime.length > 10){
            this.dateTime.shift();
        }
        // we add a violation to the datetime array here
        this.dateTime.push(dateTimeOfViolation);
        this.checkIfBan();
    }

    this.checkIfBan = function(){
        // check last n date Time's that they violated and see if
        // we need to ban them
        if(this.dateTime.length > timeToCheck){
            console.log("More attempts than allowed detected.");
            var lastLog = this.dateTime[this.dateTime.length - 1];
            var firstLog = this.dateTime[this.dateTime.length - 1 - timeToCheck];
            var timeDifference = (lastLog - firstLog) / 1000;
            //if difference between last attempt and first of range we want to check
            //is less than the time allowed for failed attempts set by user
            if(timeDifference <= timeBeforeBan){
                shell.exec("iptables -A INPUT -s " + this.ipAddress + " -j DROP");
                console.log(this.ipAddress + " has been banned");
                //add to banned array
                bannedIPs[this.ipAddress] = new Date();
            }

            //check for slow scan
            var countSlowFails = 0;
            //check for slow scan/patterns
            for(var i = 0; i < timeToCheck; i++){
                var timeOne = this.dateTime[this.dateTime.length - 1 - i]
                var timeTwo = this.dateTime[this.dateTime.length - 1 - (i + 1)]
                var timeDifference = (timeOne - timeTwo) / 1000;
                //if the previous time difference is equal to this time difference
                if(timeDifference >= ((timeBeforeBan / timeToCheck) - 1)){
                    console.log("Incrementing countSlowFails.");
                    countSlowFails++;
                    console.log("countSlowFails currently at: " + countSlowFails);
                }
                if(countSlowFails == timeToCheck){
                    shell.exec("iptables -A INPUT -s " + this.ipAddress + " -j DROP");
                    console.log("Slow scan via periodical attempts detected from IP: " + this.ipAddress);
                    console.log(this.ipAddress + " has been banned");
                    //add to banned array
                    this.bannedIPs[this.ipAddress] = new Date()
                    //iptables -D INPUT -s this.ipAddress -j DROP
                }
                prev = timeDifference;
            }
        }
    }

}

ft.on('line', function(line){
    bufferString += line;
    if(line.indexOf('Failed') > -1){
        var ip = line.match(ipRegEx);

        if(!listOfIpAddresses[ip[0]]){

        var lobj = new logObject(ip[0], new Date());
        listOfIpAddresses[ip[0]] = lobj;
    } else {
        listOfIpAddresses[ip[0]].addViolation(new Date());
    }
}

});
<|endoftext|>


<commit_before>define(['text!./national-target.html', 'app', 'angular', 'lodash', 'authentication', '../views/national-target', 'authentication', 'services/editFormUtility', 'directives/forms/form-controls', 'utilities/km-utilities', 'utilities/km-workflows', 'utilities/km-storage', 'services/navigation', 'scbd-angularjs-services/locale'], function(template, app, angular, _) { 'use strict';

app.directive("editNationalTarget", ['$filter','$rootScope', "$http", "$q", 'IStorage', "authentication", "editFormUtility", "guid", "$location", "navigation", "$route", "Thesaurus", "locale", function ($filter, $rootScope, $http, $q, storage, authentication, editFormUtility, guid, $location, navigation, $route, Thesaurus, locale) {
    return {
        restrict: 'EA',
        template : template,
        replace: true,
        transclude: false,
        scope: {
				query:'&?',
				closeDialog: '&?'
		},
        link: function ($scope) {
            $scope.status = "";
            $scope.error = null;
            $scope.document = null;
			$scope.tab      = 'general';
            $scope.review = { locale: locale };

			var qs = $route.current.params;
			var openInDialog = false;
			if($scope.query){//when its open in dialog
				qs = $scope.query();
				$scope.container = '.ngdialog-theme-default';
				openInDialog = true;
			}

			$scope.selectedAichi={};
			//==================================
			//
			//==================================
			$scope.$watch('tab', function(tab) {
				if (tab == 'review')
					$scope.validate();
			});

			//==================================
			//
			//==================================
			$scope.init = function() {

				navigation.securize();

				var promise = null;
				var schema  = "nationalTarget";

				if ($scope.document)
					return;

				$scope.status = "loading";

				var identifier = qs.uid;
				var promise = null;

				if(identifier)
					promise = editFormUtility.load(identifier, "nationalTarget");
				else
					promise = $q.when(guid()).then(function(identifier) {

						return storage.drafts.security.canCreate(identifier, schema).then(function(isAllowed) {
							if (!isAllowed)
								throw { data: { error: "Not allowed" }, status: "notAuthorized" };

							return identifier;
						});
					}).then(function(identifier) {

						return{
						header: {
							identifier: guid(),
							schema   : "nationalTarget",
							languages: [locale]
						},
						government: $scope.defaultGovernment() ? { identifier: $scope.defaultGovernment() } : undefined
					}});

				promise.then(function(doc) {

					var aichiTarget = $location.search().aichiTarget;

					if(aichiTarget) {

						doc.aichiTargets = doc.aichiTargets || [];
						doc.aichiTargets.push({ identifier : aichiTarget });
					}

					return doc;

				}).then(function(doc) {

					if(!$scope.options) {

			            $scope.options = {
			                countries:          $http.get("/api/v2013/thesaurus/domains/countries/terms",                            { cache: true }).then(function (o) { return $filter('orderBy')(o.data, 'name'); }),
                            jurisdictions:      $http.get("/api/v2013/thesaurus/domains/50AC1489-92B8-4D99-965A-AAE97A80F38E/terms", { cache: true }).then(function (o) { return o.data; }),
                            aichiTargets:       $http.get("/api/v2013/thesaurus/domains/AICHI-TARGETS-COMPONENTS/terms",			 { cache: true }).then(function (o) { return Thesaurus.buildTree(o.data); }),
                            aichiTargetsFiltered: $http.get("/api/v2013/thesaurus/domains/AICHI-TARGETS-COMPONENTS/terms",			 { cache: true }).then(function (o) {
                                                                 var records =  _.reject(o.data, function(item){return item.broaderTerms.length>0});
                                                                 $scope.cachedAichiTargets = o.data;
                                                                 return records;
                                                            }),
                            aichiSubTargets     : function(){return filterSubAichiTargets();}
			            };

       				    return $q.all(_.values($scope.options)).then(function() {
       				    	return doc;
       				    });
			        }

			        return doc;

				}).then(function(doc) {

					$scope.document = doc;
					$scope.status  = "ready";
                    if($scope.document.isAichiTarget===undefined)
                        $scope.document.isAichiTarget = false;
				}).catch(function(err) {

					$scope.onError(err.data, err.status);
					throw err;

				});
			};

            function filterSubAichiTargets(){
                if(!$scope.cachedAichiTargets || !$scope.selectedAichi.target)
                    return [];

                return _.filter($scope.cachedAichiTargets, function(item){

                            return _.contains(item.broaderTerms,$scope.selectedAichi.target.identifier);
                        });
            }

			//==================================
			//
			//==================================
			$scope.isJurisdictionSubNational = function(document) {

				document = document || $scope.document;

				return !!document && !!document.jurisdiction &&
				(document.jurisdiction.identifier == "528B1187-F1BD-4479-9FB3-ADBD9076D361" || document.jurisdiction.identifier == "DEBB019D-8647-40EC-8AE5-10CA88572F6E");
			};

			//==================================
			//
			//==================================
			$scope.cleanUp = function(document) {

				return $q.when($scope.getCleanDocument(document));
			};

			//==================================
			//
			//==================================
			$scope.getCleanDocument = function(document) {
				document = document || $scope.document;

				if (!document)
					return;

				document = angular.fromJson(angular.toJson(document));

				if (!document)
					return $q.when(true);

				if (!$scope.isJurisdictionSubNational(document))
					document.jurisdictionInfo = undefined;

				if (/^\s*$/g.test(document.notes))
					document.notes = undefined;

                if($scope.selectedAichi.target && document.isAichiTarget){
                    document.aichiTargets = [];
                    document.aichiTargets.push($scope.selectedAichi.target);
                    document.title =  {en:$scope.selectedAichi.target.identifier};

                    document.description = undefined;
                    document.jurisdiction = undefined;
                    document.jurisdictionInfo = undefined;
                    document.relevantInformation = undefined;
                    document.relevantDocuments = undefined;
                }
				if(document.otherAichiTargets && document.otherAichiTargets.length>0){
					document.noOtherAichiTargets = undefined;
					document.noOtherAichiTargetsDescription = undefined;
				}
				return document;
			};

			//==================================
			//
			//==================================
			$scope.loadRecords = function(identifier, schema) {

				if (identifier) { //lookup single record

					return storage.documents.get(identifier, { info: "" })
						.then(function(r) {
							return r.data;
						})
						//otherwise
						.then(null, function(e) {
							if (e.status != 404)
								throw e;

							return storage.drafts.get(identifier, { info: "" })
								.then(function(r) {
									return r.data;
								});
						});
				}
				else { //Load all record of specified schema;

					var sQuery = "type eq '" + encodeURI(schema) + "'";

					return $q.all([storage.documents.query(sQuery, null, { cache: true }),
								   storage.drafts.query(sQuery, null, { cache: true })])
						.then(function(results) {
							var qDocs = results[0].data.Items;
							var qDrafts = results[1].data.Items;
							var qUids = _.pluck(qDocs, "identifier");

							return _.union(qDocs, _.filter(qDrafts, function(draft) {
								return qUids.indexOf(draft.identifier);
							}));
						});
				}
			};

			//======================================================================
			//======================================================================
			//======================================================================
			//======================================================================
			//======================================================================

			//==================================
			//
			//==================================
			$scope.validate = function(clone) {

				$scope.validationReport = null;

				return $scope.cleanUp().then(function(oDocument) {
					return storage.documents.validate(oDocument).then(
						function(success) {
							$scope.validationReport = success.data;
							return !!(success.data && success.data.errors && success.data.errors.length);
						},
						function(error) {
							$scope.onError(error.data);
							return true;
						}
					);
				});
			};

			//==================================
			//
			//==================================
			$scope.isFieldValid = function(field) {
				if (field && $scope.validationReport && $scope.validationReport.errors)
					return !_.findWhere($scope.validationReport.errors, { property: field });

				return true;
			};

			//==================================
            //
            //==================================
            $scope.isLoading = function () {
                return $scope.status == "loading";
            };

			//==================================
			//
			//==================================
			$scope.hasError = function() {
				return !!$scope.error;
			};

			//==================================
			//
			//==================================
			$scope.userGovernment = function() {
				return authentication.user().government;
			};

			//==================================
			//
			//==================================
			$scope.defaultGovernment = function() {

				var qsGovernment = $location.search().government;

				if (qsGovernment)
					qsGovernment = qsGovernment.toLowerCase();

				return $scope.userGovernment() || qsGovernment;
			};

			//==================================
			//
			//==================================
			$scope.onPreSaveDraft = function() {
			};

			//==================================
			//
			//==================================
			$scope.onPrePublish = function() {
				return $scope.validate(false).then(function(hasError) {
					if (hasError)
						$scope.tab = "review";
					return hasError;
				});
			};

			//==================================
			//
			//==================================
			$scope.onPostWorkflow = function() {
                $rootScope.$broadcast("onPostWorkflow", "Publishing request sent successfully.");

				if(!openInDialog)
					gotoManager();
				else{
					$scope.closeDialog();
				}
			};

			//==================================
			//
			//==================================
			$scope.onPostPublish = function() {
				$scope.$root.showAcknowledgement = true;
                $rootScope.$broadcast("onPostPublish", "Record is being published, please note the publishing process could take up to 1 minute before your record appears.");

				if(!openInDialog)
					gotoManager();
				else{
					$scope.closeDialog();
				}
			};

			//==================================
			//
			//==================================
			$scope.onPostSaveDraft = function() {
                $rootScope.$broadcast("onSaveDraft", "Draft record saved.");
			};

			//==================================
			//
			//==================================
			$scope.onPostClose = function() {
                $rootScope.$broadcast("onPostClose", "Record closed.");
				if(!openInDialog)
					gotoManager();
				else{
					$scope.closeDialog();
				}
			};

//==================================
			//
			//==================================
			function gotoManager() {
				$location.url("/submit/online-reporting");
			}

			//==================================
			//
			//==================================
			$scope.onError = function(error, status)
			{
				$scope.status = "error";

				if (status == "notAuthorized") {
					$scope.status = "hidden";
					$scope.error  = "You are not authorized to modify this record";
				}
				else if (status == 404) {
					$scope.status = "hidden";
					$scope.error  = "Record not found.";
				}
				else if (status == "badSchema") {
					$scope.status = "hidden";
					$scope.error  = "Record type is invalid.";
				}
				else if (error.Message)
					$scope.error = error.Message;
				else
					$scope.error = error;
			};

            $scope.$watch('document.aichiTargets', function(value){
                if(value && $scope.document.isAichiTarget)
                    $scope.selectedAichi.target = _.first(value);
            });
            $scope.$watch('selectedAichi.target', function(value){
                if($scope.options)
                    $scope.options.aichiSubTargets = filterSubAichiTargets();
            });

            $scope.init();

        }
    };
}]);
});
<commit_msg>clean noOtherAichiTargets when aichi/other exists<commit_after>define(['text!./national-target.html', 'app', 'angular', 'lodash', 'authentication', '../views/national-target', 'authentication', 'services/editFormUtility', 'directives/forms/form-controls', 'utilities/km-utilities', 'utilities/km-workflows', 'utilities/km-storage', 'services/navigation', 'scbd-angularjs-services/locale'], function(template, app, angular, _) { 'use strict';

app.directive("editNationalTarget", ['$filter','$rootScope', "$http", "$q", 'IStorage', "authentication", "editFormUtility", "guid", "$location", "navigation", "$route", "Thesaurus", "locale", function ($filter, $rootScope, $http, $q, storage, authentication, editFormUtility, guid, $location, navigation, $route, Thesaurus, locale) {
    return {
        restrict: 'EA',
        template : template,
        replace: true,
        transclude: false,
        scope: {
				query:'&?',
				closeDialog: '&?'
		},
        link: function ($scope) {
            $scope.status = "";
            $scope.error = null;
            $scope.document = null;
			$scope.tab      = 'general';
            $scope.review = { locale: locale };

			var qs = $route.current.params;
			var openInDialog = false;
			if($scope.query){//when its open in dialog
				qs = $scope.query();
				$scope.container = '.ngdialog-theme-default';
				openInDialog = true;
			}

			$scope.selectedAichi={};
			//==================================
			//
			//==================================
			$scope.$watch('tab', function(tab) {
				if (tab == 'review')
					$scope.validate();
			});

			//==================================
			//
			//==================================
			$scope.init = function() {

				navigation.securize();

				var promise = null;
				var schema  = "nationalTarget";

				if ($scope.document)
					return;

				$scope.status = "loading";

				var identifier = qs.uid;
				var promise = null;

				if(identifier)
					promise = editFormUtility.load(identifier, "nationalTarget");
				else
					promise = $q.when(guid()).then(function(identifier) {

						return storage.drafts.security.canCreate(identifier, schema).then(function(isAllowed) {
							if (!isAllowed)
								throw { data: { error: "Not allowed" }, status: "notAuthorized" };

							return identifier;
						});
					}).then(function(identifier) {

						return{
						header: {
							identifier: guid(),
							schema   : "nationalTarget",
							languages: [locale]
						},
						government: $scope.defaultGovernment() ? { identifier: $scope.defaultGovernment() } : undefined
					}});

				promise.then(function(doc) {

					var aichiTarget = $location.search().aichiTarget;

					if(aichiTarget) {

						doc.aichiTargets = doc.aichiTargets || [];
						doc.aichiTargets.push({ identifier : aichiTarget });
					}

					return doc;

				}).then(function(doc) {

					if(!$scope.options) {

			            $scope.options = {
			                countries:          $http.get("/api/v2013/thesaurus/domains/countries/terms",                            { cache: true }).then(function (o) { return $filter('orderBy')(o.data, 'name'); }),
                            jurisdictions:      $http.get("/api/v2013/thesaurus/domains/50AC1489-92B8-4D99-965A-AAE97A80F38E/terms", { cache: true }).then(function (o) { return o.data; }),
                            aichiTargets:       $http.get("/api/v2013/thesaurus/domains/AICHI-TARGETS-COMPONENTS/terms",			 { cache: true }).then(function (o) { return Thesaurus.buildTree(o.data); }),
                            aichiTargetsFiltered: $http.get("/api/v2013/thesaurus/domains/AICHI-TARGETS-COMPONENTS/terms",			 { cache: true }).then(function (o) {
                                                                 var records =  _.reject(o.data, function(item){return item.broaderTerms.length>0});
                                                                 $scope.cachedAichiTargets = o.data;
                                                                 return records;
                                                            }),
                            aichiSubTargets     : function(){return filterSubAichiTargets();}
			            };

       				    return $q.all(_.values($scope.options)).then(function() {
       				    	return doc;
       				    });
			        }

			        return doc;

				}).then(function(doc) {

					$scope.document = doc;
					$scope.status  = "ready";
                    if($scope.document.isAichiTarget===undefined)
                        $scope.document.isAichiTarget = false;
				}).catch(function(err) {

					$scope.onError(err.data, err.status);
					throw err;

				});
			};

            function filterSubAichiTargets(){
                if(!$scope.cachedAichiTargets || !$scope.selectedAichi.target)
                    return [];

                return _.filter($scope.cachedAichiTargets, function(item){

                            return _.contains(item.broaderTerms,$scope.selectedAichi.target.identifier);
                        });
            }

			//==================================
			//
			//==================================
			$scope.isJurisdictionSubNational = function(document) {

				document = document || $scope.document;

				return !!document && !!document.jurisdiction &&
				(document.jurisdiction.identifier == "528B1187-F1BD-4479-9FB3-ADBD9076D361" || document.jurisdiction.identifier == "DEBB019D-8647-40EC-8AE5-10CA88572F6E");
			};

			//==================================
			//
			//==================================
			$scope.cleanUp = function(document) {

				return $q.when($scope.getCleanDocument(document));
			};

			//==================================
			//
			//==================================
			$scope.getCleanDocument = function(document) {
				document = document || $scope.document;

				if (!document)
					return;

				document = angular.fromJson(angular.toJson(document));

				if (!document)
					return $q.when(true);

				if (!$scope.isJurisdictionSubNational(document))
					document.jurisdictionInfo = undefined;

				if (/^\s*$/g.test(document.notes))
					document.notes = undefined;

                if($scope.selectedAichi.target && document.isAichiTarget){
                    document.aichiTargets = [];
                    document.aichiTargets.push($scope.selectedAichi.target);
                    document.title =  {en:$scope.selectedAichi.target.identifier};

                    document.description = undefined;
                    document.jurisdiction = undefined;
                    document.jurisdictionInfo = undefined;
                    document.relevantInformation = undefined;
                    document.relevantDocuments = undefined;
                }
				if((document.aichiTargets && document.aichiTargets.length>0) || (document.otherAichiTargets && document.otherAichiTargets.length>0)){
					document.noOtherAichiTargets = undefined;
					document.noOtherAichiTargetsDescription = undefined;
				}
				return document;
			};

			//==================================
			//
			//==================================
			$scope.loadRecords = function(identifier, schema) {

				if (identifier) { //lookup single record

					return storage.documents.get(identifier, { info: "" })
						.then(function(r) {
							return r.data;
						})
						//otherwise
						.then(null, function(e) {
							if (e.status != 404)
								throw e;

							return storage.drafts.get(identifier, { info: "" })
								.then(function(r) {
									return r.data;
								});
						});
				}
				else { //Load all record of specified schema;

					var sQuery = "type eq '" + encodeURI(schema) + "'";

					return $q.all([storage.documents.query(sQuery, null, { cache: true }),
								   storage.drafts.query(sQuery, null, { cache: true })])
						.then(function(results) {
							var qDocs = results[0].data.Items;
							var qDrafts = results[1].data.Items;
							var qUids = _.pluck(qDocs, "identifier");

							return _.union(qDocs, _.filter(qDrafts, function(draft) {
								return qUids.indexOf(draft.identifier);
							}));
						});
				}
			};

			//======================================================================
			//======================================================================
			//======================================================================
			//======================================================================
			//======================================================================

			//==================================
			//
			//==================================
			$scope.validate = function(clone) {

				$scope.validationReport = null;

				return $scope.cleanUp().then(function(oDocument) {
					return storage.documents.validate(oDocument).then(
						function(success) {
							$scope.validationReport = success.data;
							return !!(success.data && success.data.errors && success.data.errors.length);
						},
						function(error) {
							$scope.onError(error.data);
							return true;
						}
					);
				});
			};

			//==================================
			//
			//==================================
			$scope.isFieldValid = function(field) {
				if (field && $scope.validationReport && $scope.validationReport.errors)
					return !_.findWhere($scope.validationReport.errors, { property: field });

				return true;
			};

			//==================================
            //
            //==================================
            $scope.isLoading = function () {
                return $scope.status == "loading";
            };

			//==================================
			//
			//==================================
			$scope.hasError = function() {
				return !!$scope.error;
			};

			//==================================
			//
			//==================================
			$scope.userGovernment = function() {
				return authentication.user().government;
			};

			//==================================
			//
			//==================================
			$scope.defaultGovernment = function() {

				var qsGovernment = $location.search().government;

				if (qsGovernment)
					qsGovernment = qsGovernment.toLowerCase();

				return $scope.userGovernment() || qsGovernment;
			};

			//==================================
			//
			//==================================
			$scope.onPreSaveDraft = function() {
			};

			//==================================
			//
			//==================================
			$scope.onPrePublish = function() {
				return $scope.validate(false).then(function(hasError) {
					if (hasError)
						$scope.tab = "review";
					return hasError;
				});
			};

			//==================================
			//
			//==================================
			$scope.onPostWorkflow = function() {
                $rootScope.$broadcast("onPostWorkflow", "Publishing request sent successfully.");

				if(!openInDialog)
					gotoManager();
				else{
					$scope.closeDialog();
				}
			};

			//==================================
			//
			//==================================
			$scope.onPostPublish = function() {
				$scope.$root.showAcknowledgement = true;
                $rootScope.$broadcast("onPostPublish", "Record is being published, please note the publishing process could take up to 1 minute before your record appears.");

				if(!openInDialog)
					gotoManager();
				else{
					$scope.closeDialog();
				}
			};

			//==================================
			//
			//==================================
			$scope.onPostSaveDraft = function() {
                $rootScope.$broadcast("onSaveDraft", "Draft record saved.");
			};

			//==================================
			//
			//==================================
			$scope.onPostClose = function() {
                $rootScope.$broadcast("onPostClose", "Record closed.");
				if(!openInDialog)
					gotoManager();
				else{
					$scope.closeDialog();
				}
			};

//==================================
			//
			//==================================
			function gotoManager() {
				$location.url("/submit/online-reporting");
			}

			//==================================
			//
			//==================================
			$scope.onError = function(error, status)
			{
				$scope.status = "error";

				if (status == "notAuthorized") {
					$scope.status = "hidden";
					$scope.error  = "You are not authorized to modify this record";
				}
				else if (status == 404) {
					$scope.status = "hidden";
					$scope.error  = "Record not found.";
				}
				else if (status == "badSchema") {
					$scope.status = "hidden";
					$scope.error  = "Record type is invalid.";
				}
				else if (error.Message)
					$scope.error = error.Message;
				else
					$scope.error = error;
			};

            $scope.$watch('document.aichiTargets', function(value){
                if(value && $scope.document.isAichiTarget)
                    $scope.selectedAichi.target = _.first(value);
            });
            $scope.$watch('selectedAichi.target', function(value){
                if($scope.options)
                    $scope.options.aichiSubTargets = filterSubAichiTargets();
            });

            $scope.init();

        }
    };
}]);
});
<|endoftext|>


<commit_before>/**
 * IRC Class
 *
 * @author		Michael Owens
 * @website		http://www.michaelowens.nl
 * @copyright	Michael Owens 2011
 */

var sys = require( 'sys' ),
	net = require( 'net' ),
	fs = require( 'fs' ),
	channel = require( './channel' );

Server = exports.Server = function( config ) {

	this.initialize( config );

};

sys.inherits( Server, process.EventEmitter );

Server.prototype.initialize = function( config ) {

	this.host = config.host || '127.0.0.1';
	this.port = config.port || 6667;
	this.nick = config.nick || 'MikeBot';
	this.username = config.username || 'MikeBot';
	this.realname = config.realname || 'Powered by MikeBot';
	this.command = config.command || '.';
        this.userchannels = config.channels || [];
	this.channels = [];
	this.hooks = [];
	this.triggers = [];
	this.replies = [];

	this.connection = null;
	this.buffer = "";
	this.encoding = "utf8";
	this.timeout = 60*60*1000;

	this.debug = config.debug || false;

	/*
	 * Boot Plugins
	 */
	this.plugins = [];

	for( i = 0, z = config.plugins.length; i < z; i++ ) {

		var p = config.plugins[ i ];
		this.loadPlugin( p );

	}

};

Server.prototype.connect = function( ) {

	var c = this.connection = net.createConnection( this.port, this.host );
    c.setEncoding( this.encoding );
    c.setTimeout( this.timeout );

	this.addListener( 'connect', this.onConnect );
    this.addListener( 'data', this.onReceive );
    this.addListener( 'eof', this.onEOF );
    this.addListener( 'timeout', this.onTimeout );
    this.addListener( 'close', this.onClose );

};

Server.prototype.disconnect = function( reason ) {

    if( this.connection.readyState !== 'closed' ) {

        this.connection.close( );
        sys.puts( 'disconnected (' + reason + ')' );

    }

};

Server.prototype.onConnect = function( ) {

	sys.puts( 'connected' );

    this.raw( 'NICK', this.nick );
    this.raw( 'USER', this.username, '0', '*', ':' + this.realname );

    this.emit( 'connect' );

};

Server.prototype.onReceive = function( chunk ) {

	this.buffer += chunk;

    while( this.buffer ) {

        var offset = this.buffer.indexOf( "\r\n" );
        if( offset < 0 ) {
            return;
        }

        var msg = this.buffer.slice( 0, offset );
        this.buffer = this.buffer.slice( offset + 2 );

        if( this.debug ) sys.puts( "< " + msg );

        msg = this.parse( msg );

        this.onMessage( msg );

    }

};

Server.prototype.onMessage = function( msg ) {

	if( this.debug ) {
		sys.puts( '++ command: ' + msg.command );
		sys.puts( '++ arguments: ' + msg.arguments );
		sys.puts( '++ prefix: ' + msg.prefix );
		sys.puts( '++ lastarg: ' + msg.lastarg );
	}

	var c, // channel
		u, // user
		m; // message
	switch( msg.command ){
		case 'PING':
			this.raw( 'PONG', msg.arguments );
			break;

		case 'PRIVMSG':
			// Look for triggers
			m = msg.arguments[ 1 ];
			if( m.substring( 0, 1 ) == this.command ) {

				var trigger = m.split( ' ' )[ 0 ].substring( 1, m.length );
				if( typeof this.triggers[ trigger ] != 'undefined' ) {

					var trig = this.triggers[ trigger ];
					trig.callback.apply( this.plugins[ trig.plugin ], arguments );

				}

			}
			this.emit( 'message', msg );
			break;

		case 'JOIN':
			this.emit( 'join', msg );
			break;

		case 'PART':
			this.emit( 'part', msg );
			break;

		case 'QUIT':
			this.emit( 'quit', msg );
			break;

		case 'NICK':
			this.emit( 'nick', msg );
			break;
	}

	this.emit( msg.command, msg );
	this.emit( 'data', msg );

};

Server.prototype.user = function( mask ){

	var match = mask.match( /([^!]+)![^@]+@.+/ );
	if( !match ) throw new TypeError( "Erroneus (incomplete?) mask: " + mask );
	match = match[ 1 ];
	return match;

}

Server.prototype.parse = function( text ) {

	if ( typeof( text ) != "string" )
		return false;

	var tmp = text.split(" ");

	if ( tmp.length < 2 )
		return false;

	var prefix    = null;
	var command   = null;
	var lastarg   = null;
	var arguments = [];

	for ( var i = 0, j = tmp.length; i < j; i++ ) {

		if ( i == 0 && tmp[ i ].indexOf( ":" ) == 0 )
			prefix = tmp[ 0 ].substr( 1 );

		else if ( tmp[ i ] == "" )
			continue;

		else if ( !command && tmp[ i ].indexOf(":") != 0 )
			command = tmp[ i ].toUpperCase();

		else if ( tmp[ i ].indexOf( ":" ) == 0 ) {

			tmp[ i ] = tmp[ i ].substr(1);
			tmp.splice( 0, i );
			arguments.push( tmp.join( " " ) );
			lastarg = arguments.length - 1;
			break;

		} else
			arguments.push( tmp[ i ] );

	}

	return {
		prefix: prefix,
		command: command,
		arguments: arguments,
		lastarg: lastarg,
		orig: text
	};

};

Server.prototype.onEOF = function( ) {
    this.disconnect( 'EOF' );
};

Server.prototype.onTimeout = function( ) {
    this.disconnect( 'timeout' );
};

Server.prototype.onClose = function( ) {
    this.disconnect( 'close' );
};

Server.prototype.raw = function( cmd ) {

    if( this.connection.readyState !== "open" ) {
        return this.disconnect( "cannot send with readyState " + this.connection.readyState );
    }

    var msg = Array.prototype.slice.call( arguments, 1 ).join( ' ' ) + "\r\n";

    if( this.debug ) sys.puts( '>' + cmd + ' ' + msg );

    this.connection.write( cmd + " " + msg, this.encoding );

};

Server.prototype.addListener = function( ev, f ) {

	var that = this;
	return this.connection.addListener( ev, ( function( ) {

		return function( ) {
			f.apply( that, arguments )
		};

	} )() );

};

Server.prototype.addPluginListener = function( plugin, ev, f ) {

	if( typeof this.hooks[ plugin ] == 'undefined' ) this.hooks[ plugin ] = [];

	var callback = ( function( ) {

		return function( ) {
			f.apply( that, arguments )
		};

	} )();

	this.hooks[ plugin ].push( { event: ev, callback: callback } );

	var that = this.plugins[ plugin ];
	return this.on( ev, callback );

};

Server.prototype.unloadPlugin = function( name ) {

	if( typeof this.plugins[ name ] != 'undefined' ) {

		delete this.plugins[ name ];

		if( typeof this.hooks[ name ] != 'undefined' ) {

			for( var hook in this.hooks[ name ] ) {

				this.removeListener( this.hooks[ name ][ hook ].event, this.hooks[ name ][ hook ].callback );

			}

		}

		if( typeof this.replies[ name ] != 'undefined' ) {

			for( var reply in this.replies[ name ] ) {

				this.removeListener( this.replies[ name ][ reply ].event, this.replies[ name ][ reply ].callback );

			}

		}

		for( var trig in this.triggers ) {

			if( this.triggers[ trig ].plugin == name ) {

				delete this.triggers[ trig ];

			}

		}

	}

};

Server.prototype.loadPlugin = function( name ) {

        this.unloadPlugin( name );

	var that = this;
	fs.readFile( './plugins/' + name + '.js', 'utf8', function( err, data ) {

		if( err ) {

			sys.puts( err );

		} else {

			eval( data );

			that.plugins[ name ] = new Plugin( that );

			/*
			 * Hooks
			 */
			if( typeof that.plugins[ name ].onConnect == 'function' ) that.addPluginListener( name, 'connect', that.plugins[ name ].onConnect );
			if( typeof that.plugins[ name ].onData == 'function' ) that.addPluginListener( name, 'data', that.plugins[ name ].onData );
			if( typeof that.plugins[ name ].onMessage == 'function' ) that.addPluginListener( name, 'message', that.plugins[ name ].onMessage );
			if( typeof that.plugins[ name ].onJoin == 'function' ) that.addPluginListener( name, 'join', that.plugins[ name ].onJoin );
			if( typeof that.plugins[ name ].onPart == 'function' ) that.addPluginListener( name, 'part', that.plugins[ name ].onPart );
			if( typeof that.plugins[ name ].onQuit == 'function' ) that.addPluginListener( name, 'quit', that.plugins[ name ].onQuit );
			if( typeof that.plugins[ name ].onNick == 'function' ) that.addPluginListener( name, 'nick', that.plugins[ name ].onNick );

		}

	} );

};

Server.prototype.addTrigger = function( plugin, trigger, callback ) {

	if( typeof this.triggers[ trigger ] == 'undefined' ) {

		this.triggers[ trigger ] = { plugin: plugin.name, callback: callback };

	}

};

Server.prototype.onReply = function( plugin, ev, f ) {

	if( typeof this.replies[ plugin ] == 'undefined' ) this.replies[ plugin ] = [];

	var callback = ( function( ) {

		return function( ) {
			f.apply( that, arguments )
		};

	} )();

	this.replies[ plugin ].push( { event: ev, callback: callback } );

	var that = this.plugins[ plugin ];
	return this.on( ev, callback );

};
<commit_msg>added private message hook<commit_after>/**
 * IRC Class
 *
 * @author		Michael Owens
 * @website		http://www.michaelowens.nl
 * @copyright	Michael Owens 2011
 */

var sys = require( 'sys' ),
	net = require( 'net' ),
	fs = require( 'fs' ),
	channel = require( './channel' );

Server = exports.Server = function( config ) {

	this.initialize( config );

};

sys.inherits( Server, process.EventEmitter );

Server.prototype.initialize = function( config ) {

	this.host = config.host || '127.0.0.1';
	this.port = config.port || 6667;
	this.nick = config.nick || 'MikeBot';
	this.username = config.username || 'MikeBot';
	this.realname = config.realname || 'Powered by MikeBot';
	this.command = config.command || '.';
        this.userchannels = config.channels || [];
	this.channels = [];
	this.hooks = [];
	this.triggers = [];
	this.replies = [];

	this.connection = null;
	this.buffer = "";
	this.encoding = "utf8";
	this.timeout = 60*60*1000;

	this.debug = config.debug || false;

	/*
	 * Boot Plugins
	 */
	this.plugins = [];

	for( i = 0, z = config.plugins.length; i < z; i++ ) {

		var p = config.plugins[ i ];
		this.loadPlugin( p );

	}

};

Server.prototype.connect = function( ) {

	var c = this.connection = net.createConnection( this.port, this.host );
    c.setEncoding( this.encoding );
    c.setTimeout( this.timeout );

	this.addListener( 'connect', this.onConnect );
    this.addListener( 'data', this.onReceive );
    this.addListener( 'eof', this.onEOF );
    this.addListener( 'timeout', this.onTimeout );
    this.addListener( 'close', this.onClose );

};

Server.prototype.disconnect = function( reason ) {

    if( this.connection.readyState !== 'closed' ) {

        this.connection.close( );
        sys.puts( 'disconnected (' + reason + ')' );

    }

};

Server.prototype.onConnect = function( ) {

	sys.puts( 'connected' );

    this.raw( 'NICK', this.nick );
    this.raw( 'USER', this.username, '0', '*', ':' + this.realname );

    this.emit( 'connect' );

};

Server.prototype.onReceive = function( chunk ) {

	this.buffer += chunk;

    while( this.buffer ) {

        var offset = this.buffer.indexOf( "\r\n" );
        if( offset < 0 ) {
            return;
        }

        var msg = this.buffer.slice( 0, offset );
        this.buffer = this.buffer.slice( offset + 2 );

        if( this.debug ) sys.puts( "< " + msg );

        msg = this.parse( msg );

        this.onMessage( msg );

    }

};

Server.prototype.onMessage = function( msg ) {

	if( this.debug ) {
		sys.puts( '++ command: ' + msg.command );
		sys.puts( '++ arguments: ' + msg.arguments );
		sys.puts( '++ prefix: ' + msg.prefix );
		sys.puts( '++ lastarg: ' + msg.lastarg );
	}

	var c, // channel
		u, // user
		m; // message
	switch( msg.command ){
		case 'PING':
			this.raw( 'PONG', msg.arguments );
			break;

		case 'PRIVMSG':
			// Look for triggers
			m = msg.arguments[ 1 ];
			if( m.substring( 0, 1 ) == this.command ) {

				var trigger = m.split( ' ' )[ 0 ].substring( 1, m.length );
				if( typeof this.triggers[ trigger ] != 'undefined' ) {

					var trig = this.triggers[ trigger ];
					trig.callback.apply( this.plugins[ trig.plugin ], arguments );

				}

			}

	                if( msg.arguments[ 0 ] == this.nick ) {

			    this.emit( 'private_message', msg );

			} else {

			    this.emit( 'message', msg );

			}

			break;

		case 'JOIN':
			this.emit( 'join', msg );
			break;

		case 'PART':
			this.emit( 'part', msg );
			break;

		case 'QUIT':
			this.emit( 'quit', msg );
			break;

		case 'NICK':
			this.emit( 'nick', msg );
			break;
	}

	this.emit( msg.command, msg );
	this.emit( 'data', msg );

};

Server.prototype.user = function( mask ){

	var match = mask.match( /([^!]+)![^@]+@.+/ );
	if( !match ) throw new TypeError( "Erroneus (incomplete?) mask: " + mask );
	match = match[ 1 ];
	return match;

}

Server.prototype.parse = function( text ) {

	if ( typeof( text ) != "string" )
		return false;

	var tmp = text.split(" ");

	if ( tmp.length < 2 )
		return false;

	var prefix    = null;
	var command   = null;
	var lastarg   = null;
	var arguments = [];

	for ( var i = 0, j = tmp.length; i < j; i++ ) {

		if ( i == 0 && tmp[ i ].indexOf( ":" ) == 0 )
			prefix = tmp[ 0 ].substr( 1 );

		else if ( tmp[ i ] == "" )
			continue;

		else if ( !command && tmp[ i ].indexOf(":") != 0 )
			command = tmp[ i ].toUpperCase();

		else if ( tmp[ i ].indexOf( ":" ) == 0 ) {

			tmp[ i ] = tmp[ i ].substr(1);
			tmp.splice( 0, i );
			arguments.push( tmp.join( " " ) );
			lastarg = arguments.length - 1;
			break;

		} else
			arguments.push( tmp[ i ] );

	}

	return {
		prefix: prefix,
		command: command,
		arguments: arguments,
		lastarg: lastarg,
		orig: text
	};

};

Server.prototype.onEOF = function( ) {
    this.disconnect( 'EOF' );
};

Server.prototype.onTimeout = function( ) {
    this.disconnect( 'timeout' );
};

Server.prototype.onClose = function( ) {
    this.disconnect( 'close' );
};

Server.prototype.raw = function( cmd ) {

    if( this.connection.readyState !== "open" ) {
        return this.disconnect( "cannot send with readyState " + this.connection.readyState );
    }

    var msg = Array.prototype.slice.call( arguments, 1 ).join( ' ' ) + "\r\n";

    if( this.debug ) sys.puts( '>' + cmd + ' ' + msg );

    this.connection.write( cmd + " " + msg, this.encoding );

};

Server.prototype.addListener = function( ev, f ) {

	var that = this;
	return this.connection.addListener( ev, ( function( ) {

		return function( ) {
			f.apply( that, arguments )
		};

	} )() );

};

Server.prototype.addPluginListener = function( plugin, ev, f ) {

	if( typeof this.hooks[ plugin ] == 'undefined' ) this.hooks[ plugin ] = [];

	var callback = ( function( ) {

		return function( ) {
			f.apply( that, arguments )
		};

	} )();

	this.hooks[ plugin ].push( { event: ev, callback: callback } );

	var that = this.plugins[ plugin ];
	return this.on( ev, callback );

};

Server.prototype.unloadPlugin = function( name ) {

	if( typeof this.plugins[ name ] != 'undefined' ) {

		delete this.plugins[ name ];

		if( typeof this.hooks[ name ] != 'undefined' ) {

			for( var hook in this.hooks[ name ] ) {

				this.removeListener( this.hooks[ name ][ hook ].event, this.hooks[ name ][ hook ].callback );

			}

		}

		if( typeof this.replies[ name ] != 'undefined' ) {

			for( var reply in this.replies[ name ] ) {

				this.removeListener( this.replies[ name ][ reply ].event, this.replies[ name ][ reply ].callback );

			}

		}

		for( var trig in this.triggers ) {

			if( this.triggers[ trig ].plugin == name ) {

				delete this.triggers[ trig ];

			}

		}

	}

};

Server.prototype.loadPlugin = function( name ) {

        this.unloadPlugin( name );

	var that = this;
	fs.readFile( './plugins/' + name + '.js', 'utf8', function( err, data ) {

		if( err ) {

			sys.puts( err );

		} else {

			eval( data );

			that.plugins[ name ] = new Plugin( that );

			/*
			 * Hooks
			 */
			if( typeof that.plugins[ name ].onConnect == 'function' ) that.addPluginListener( name, 'connect', that.plugins[ name ].onConnect );
			if( typeof that.plugins[ name ].onData == 'function' ) that.addPluginListener( name, 'data', that.plugins[ name ].onData );
			if( typeof that.plugins[ name ].onMessage == 'function' ) that.addPluginListener( name, 'message', that.plugins[ name ].onMessage );
			if( typeof that.plugins[ name ].onJoin == 'function' ) that.addPluginListener( name, 'join', that.plugins[ name ].onJoin );
			if( typeof that.plugins[ name ].onPart == 'function' ) that.addPluginListener( name, 'part', that.plugins[ name ].onPart );
			if( typeof that.plugins[ name ].onQuit == 'function' ) that.addPluginListener( name, 'quit', that.plugins[ name ].onQuit );
			if( typeof that.plugins[ name ].onNick == 'function' ) that.addPluginListener( name, 'nick', that.plugins[ name ].onNick );
		        if( typeof that.plugins[ name ].onPrivateMessage == 'function' ) that.addPluginListener( name, 'private_message', that.plugins[ name ].onPrivateMessage );

		}

	} );

};

Server.prototype.addTrigger = function( plugin, trigger, callback ) {

	if( typeof this.triggers[ trigger ] == 'undefined' ) {

		this.triggers[ trigger ] = { plugin: plugin.name, callback: callback };

	}

};

Server.prototype.onReply = function( plugin, ev, f ) {

	if( typeof this.replies[ plugin ] == 'undefined' ) this.replies[ plugin ] = [];

	var callback = ( function( ) {

		return function( ) {
			f.apply( that, arguments )
		};

	} )();

	this.replies[ plugin ].push( { event: ev, callback: callback } );

	var that = this.plugins[ plugin ];
	return this.on( ev, callback );

};
<|endoftext|>