<commit_before>import fetch from 'isomorphic-fetch'

import config from 'src/config'

const chatBaseUrl = config.server.chat.baseURL
const chatUserSecret = config.server.chat.userSecret
const chatWebhookTokenDM = config.server.chat.webhookTokens.DM
if (!chatBaseUrl) {
  throw new Error('Chat base URL must be set in config')
}

export default class ChatClient {
  login() {
    if (!chatUserSecret) {
      throw new Error('Cannot log into chat: invalid user token')
    }
    return this._fetchFromChat('/api/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: `user=echo&password=${<PASSWORD>}`,
    })
    .then(json => json.data)
  }

  sendDirectMessage(userName, msg) {
    return this._loginAndFetchFromChat(`/hooks/${chatWebhookTokenDM}`, {
      method: 'POST',
      body: JSON.stringify({channel: `@${userName}`, msg})
    })
    .then(json => json.result)
  }

  sendChannelMessage(channel, msg) {
    return this._loginAndFetchFromChat(`/api/lg/rooms/${channel}/send`, {
      method: 'POST',
      body: JSON.stringify({msg})
    })
    .then(json => json.result)
  }

  createChannel(channelName, members = ['echo'], topic = '') {
    return this._loginAndFetchFromChat('/api/lg/rooms', {
      method: 'POST',
      body: JSON.stringify({
        name: channelName,
        members,
        topic,
      })
    })
    .then(result => result.room)
  }

  joinChannel(channelName, members = []) {
    return this._loginAndFetchFromChat(`/api/lg/rooms/${channelName}/join`, {
      method: 'POST',
      body: JSON.stringify({
        members: members.concat('echo'),
      }),
    })
    .then(res => res.result)
  }

  deleteChannel(channelName) {
    return this._loginAndFetchFromChat(`/api/lg/rooms/${channelName}`, {
      method: 'DELETE',
    }).then(json => Boolean(json.result)) // return true on success
  }

  _fetchFromChat(path, options) {
    const url = `${chatBaseUrl}${path}`
    return fetch(url, options)
      .then(resp => {
        return resp.json().catch(err => {
          console.error('Chat response parse error:', err)
          return Promise.reject(new Error('There was a problem fetching data from the chat service'))
        })
      })
      .then(json => {
        if (json.status !== 'success') {
          return Promise.reject(json)
        }
        return json
      })
  }

  _loginAndFetchFromChat(path, options) {
    return this.authHeaders()
      .then(authHeaders => {<commit_msg>promise should be rejected with an Error<commit_after>import fetch from 'isomorphic-fetch'

import config from 'src/config'

const chatBaseUrl = config.server.chat.baseURL
const chatUserSecret = config.server.chat.userSecret
const chatWebhookTokenDM = config.server.chat.webhookTokens.DM
if (!chatBaseUrl) {
  throw new Error('Chat base URL must be set in config')
}

export default class ChatClient {
  login() {
    if (!chatUserSecret) {
      throw new Error('Cannot log into chat: invalid user token')
    }
    return this._fetchFromChat('/api/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: `user=echo&password=${chatUserSecret}`,
    })
    .then(json => json.data)
  }

  sendDirectMessage(userName, msg) {
    return this._loginAndFetchFromChat(`/hooks/${chatWebhookTokenDM}`, {
      method: 'POST',
      body: JSON.stringify({channel: `@${userName}`, msg})
    })
    .then(json => json.result)
  }

  sendChannelMessage(channel, msg) {
    return this._loginAndFetchFromChat(`/api/lg/rooms/${channel}/send`, {
      method: 'POST',
      body: JSON.stringify({msg})
    })
    .then(json => json.result)
  }

  createChannel(channelName, members = ['echo'], topic = '') {
    return this._loginAndFetchFromChat('/api/lg/rooms', {
      method: 'POST',
      body: JSON.stringify({
        name: channelName,
        members,
        topic,
      })
    })
    .then(result => result.room)
  }

  joinChannel(channelName, members = []) {
    return this._loginAndFetchFromChat(`/api/lg/rooms/${channelName}/join`, {
      method: 'POST',
      body: JSON.stringify({
        members: members.concat('echo'),
      }),
    })
    .then(res => res.result)
  }

  deleteChannel(channelName) {
    return this._loginAndFetchFromChat(`/api/lg/rooms/${channelName}`, {
      method: 'DELETE',
    }).then(json => Boolean(json.result)) // return true on success
  }

  _fetchFromChat(path, options) {
    const url = `${chatBaseUrl}${path}`
    return fetch(url, options)
      .then(resp => {
        return resp.json().catch(err => {
          console.error('Chat response parse error:', err)
          return Promise.reject(new Error('There was a problem fetching data from the chat service'))
        })
      })
      .then(json => {
        if (json.status !== 'success') {
          return Promise.reject(new Error(json.message))
        }
        return json
      })
  }

  _loginAndFetchFromChat(path, options) {
    return this.authHeaders()
      .then(authHeaders => {
{'fraction_non_alphanumeric': 0.1487229862475442, 'fraction_numerical': 0.0, 'mean_word_length': 2.8249436513899324, 'pattern_counts': {'":': 0, '<': 4, '<?xml version=': 0, '>': 24, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, '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': '95637', 'n_tokens_mistral': 1552, 'n_tokens_neox': 1553, 'n_words': 323}