<commit_before>// Description:
//   A Hubot script to add Toggl integration to your company's chat
//
// Commands:
//   hubot toggl setup - Sets-up an user's account with Toggl
//   hubot toggl start <description> - Starts a time-entry
//   hubot toggl stop - Stops the current time-entry
//   hubot toggl current - Prints the current time-entry
//   hubot toggl whoami - Prints the current authenticated Toggl user
//   hubot toggl projects - Prints the 5 most recently modified projects
//
// Author:
//   yamadapc
'use strict';
var buffer = require('buffer');
var Promise = require('bluebird');
var _ = require('lodash');
var moment = require('moment');

var Buffer = buffer.Buffer;
var NO_ACCOUNT_ERROR = 'No Toggl Account set-up. Add your account with: *toggl setup <token>*';

function hubotToggl(robot) {
  robot.logger.info("hubot-toggl: Starting the Toggl robot");

  function assertStatus(status, httpRes) {
    if(httpRes.statusCode !== status) {
      throw new Error(
        'Request failed with the Toggl API (HTTP ' + httpRes.statusCode + ')'
      );
    }
  }

  function errorHandler(res) {
    return function(err) {
      res.send('*Error:* ' + err.message);
    };
  }

  function http(res, method, url, body) {
    var token;
    var authorization;
    var req = robot.http(url);

    if(res) {
      var user = robot.brain.userForName(res.envelope.user.name);
      token = user && user.toggl && user.toggl.me && user.toggl.me.data.api_token;

      if(!token) {
        return Promise.reject(new Error(NO_ACCOUNT_ERROR));
      }

      var base64Token = new Buffer(token + ':api_token').toString('base64');
      authorization = 'Basic ' + base64Token;
      req = req.header('Authorization', authorization);
    }

    if(method !== 'get') {
      body = JSON.stringify(body);
    }
    req = req.header('Content-Type', 'application/json');

    return new Promise(function(fulfill, reject) {
      req[method](body)
        (function(err, res, body) {
          if(err) reject(err);
          else fulfill([res, body]);
        });
    });
  }

  robot.respond(/toggl setup( (.*))?/, function(res) {
    var token = res.match[2];

    var isPrivateMessage = res.envelope.room === res.envelope.user.name;

    if(!isPrivateMessage) {
      res.reply('I can only authenticate you with a Private Message');
      robot.send({room: res.envelope.user.name}, 'Send me *toggl setup <token>*');
      return;
    }

    var username = res.envelope.user.name;

    if(!token) {
      res.send('Missing token. Send me *toggl setup <token>*.');
      return;
    }

    var user = robot.brain.userForName(username);
    res.send('Validating your token');
    http(false, 'get', 'https://toggl.com/api/v8/me')
      .spread(function(httpRes, body) {
        assertStatus(200, httpRes);
        body = JSON.parse(body);
        res.send(
          'Authenticated as: *' + body.data.fullname + '*\n' +
          'User ID: *' + body.data.id + '*\n' +
          'Default Workspace ID: *' + body.data.default_wid + '*'
        );
        user.toggl = {
          me: body,
        };
        robot.brain.save();
      })
      .catch(errorHandler(res));
  });

  robot.respond(/toggl whoami/, function(res) {
    var username = res.envelope.user.name;
    var user = robot.brain.userForName(username);

    if(!user || !user.toggl || !user.toggl.me) {
      res.send(NO_ACCOUNT_ERROR);
      return;
    }

    var me = user.toggl.me;
    res.send(
      'Authenticated as: *' + me.data.fullname + '*\n' +
      'User ID: *' + me.data.id + '*\n' +
      'Default Workspace ID: *' + me.data.default_wid + '*'<commit_msg>Fix `toggl setup` (closes #1)<commit_after>// Description:
//   A Hubot script to add Toggl integration to your company's chat
//
// Commands:
//   hubot toggl setup - Sets-up an user's account with Toggl
//   hubot toggl start <description> - Starts a time-entry
//   hubot toggl stop - Stops the current time-entry
//   hubot toggl current - Prints the current time-entry
//   hubot toggl whoami - Prints the current authenticated Toggl user
//   hubot toggl projects - Prints the 5 most recently modified projects
//
// Author:
//   yamadapc
'use strict';
var buffer = require('buffer');
var Promise = require('bluebird');
var _ = require('lodash');
var moment = require('moment');

var Buffer = buffer.Buffer;
var NO_ACCOUNT_ERROR = 'No Toggl Account set-up. Add your account with: *toggl setup <token>*';

function hubotToggl(robot) {
  robot.logger.info("hubot-toggl: Starting the Toggl robot");

  function assertStatus(status, httpRes) {
    if(httpRes.statusCode !== status) {
      throw new Error(
        'Request failed with the Toggl API (HTTP ' + httpRes.statusCode + ')'
      );
    }
  }

  function errorHandler(res) {
    return function(err) {
      res.send('*Error:* ' + err.message);
    };
  }

  function http(res, method, url, body) {
    var token;
    var authorization;
    var req = robot.http(url);

    if(res) {
      if(_.isString(res)) {
        token = res;
      } else {
        var user = robot.brain.userForName(res.envelope.user.name);
        token = user && user.toggl && user.toggl.me && user.toggl.me.data.api_token;
      }

      if(!token) {
        return Promise.reject(new Error(NO_ACCOUNT_ERROR));
      }

      var base64Token = new Buffer(token + ':api_token').toString('base64');
      authorization = 'Basic ' + base64Token;
      req = req.header('Authorization', authorization);
    }

    if(method !== 'get') {
      body = JSON.stringify(body);
    }
    req = req.header('Content-Type', 'application/json');

    return new Promise(function(fulfill, reject) {
      req[method](body)
        (function(err, res, body) {
          if(err) reject(err);
          else fulfill([res, body]);
        });
    });
  }

  robot.respond(/toggl setup( (.*))?/, function(res) {
    var token = res.match[2];

    var isPrivateMessage = res.envelope.room === res.envelope.user.name;

    if(!isPrivateMessage) {
      res.reply('I can only authenticate you with a Private Message');
      robot.send({room: res.envelope.user.name}, 'Send me *toggl setup <token>*');
      return;
    }

    var username = res.envelope.user.name;

    if(!token) {
      res.send('Missing token. Send me *toggl setup <token>*.');
      return;
    }

    var user = robot.brain.userForName(username);
    res.send('Validating your token');
    http(token, 'get', 'https://toggl.com/api/v8/me')
      .spread(function(httpRes, body) {
        assertStatus(200, httpRes);
        body = JSON.parse(body);
        res.send(
          'Authenticated as: *' + body.data.fullname + '*\n' +
          'User ID: *' + body.data.id + '*\n' +
          'Default Workspace ID: *' + body.data.default_wid + '*'
        );
        user.toggl = {
          me: body,
        };
        robot.brain.save();
      })
      .catch(errorHandler(res));
  });

  robot.respond(/toggl whoami/, function(res) {
    var username = res.envelope.user.name;
    var user = robot.brain.userForName(username);

    if(!user || !user.toggl || !user.toggl.me) {
      res.send(NO_ACCOUNT_ERROR);
      return;
    }

    var me = user.toggl.me;
    res.send(
      'Authenticated as: *' + me.data.fullname + '*\n' +
      'User ID: *' + me.data.id + '*\n' +
      'Default Workspace ID: *' + me.data.default_wid + '*'
{'fraction_non_alphanumeric': 0.15179542981501631, 'fraction_numerical': 0.003400435255712731, 'mean_word_length': 2.567685589519651, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5952710', 'n_tokens_mistral': 2494, 'n_tokens_neox': 2440, 'n_words': 572}