<commit_before>/* global XMLHttpRequest FormData */
import Credentials from '../constants/Credentials'
import * as types from '../constants/ActionTypes'
import generateId from '../utils/generateId'
import getCookie from '../utils/getCookie'

export const startUpload = (id, file) => ({
  type: types.UPLOAD_STARTED,
  payload: { id, file }
})

export const uploadFinished = (id, finishedUpload) => ({
  type: types.UPLOAD_SUCCESS,
  payload: { id, finishedUpload }
})

export const uploadError = (id, error) => ({
  type: types.UPLOAD_ERROR,
  payload: { id, error },
  error: true
})

export const uploadProgress = (id, progress) => ({
  type: types.UPLOAD_PROGRESS,
  payload: { progress, id }
})

export const uploadFile = file => (dispatch, getState) => {
  const id = generateId()
  dispatch(startUpload(id, file.name))
  const url = `/api/v1/file/${Credentials.USER && Credentials.API_KEY
    ? `?username=${Credentials.USER}&api_key=${Credentials.API_KEY}`
    : ''}`

  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()
    const checkAborted = setInterval(() => {
      if (
        getState().uploads.find(upload => upload.id === id).status ===
        'Aborting'
      ) {
        xhr.abort()
      }
    })
    let nextTenthOfSecond = 0
    xhr.upload.onprogress = event => {
      if (new Date().getMilliseconds() / 10 < nextTenthOfSecond) return
      nextTenthOfSecond = new Date().getSeconds() / 10 + 10
      dispatch(
        uploadProgress(id, Math.floor(event.loaded / event.total * 1000) / 10)
      )
    }
    xhr.onload = () => {
      if (xhr.readyState === XMLHttpRequest.DONE) {
        dispatch(uploadProgress(id, 100))
        clearInterval(checkAborted)
        if (xhr.status === 201) {
          setTimeout(() => resolve(JSON.parse(xhr.response)), 1000)
        } else {
          reject(Error('Something went wrong uploading'))
        }
      } else {
        clearInterval(checkAborted)
        reject(Error(xhr.statusText))
      }
    }
    xhr.onabort = () => {
      clearInterval(checkAborted)
      dispatch(uploadAborted(id))
    }
    xhr.onerror = () => {
      clearInterval(checkAborted)
      reject(Error('Network error'))
    }
    xhr.open('post', url, true)
    xhr.setRequestHeader('accept', '*/*')
    xhr.setRequestHeader('X-CSRFToken', getCookie('csrftoken'))
    const formData = new FormData()
    formData.append('file', file)
    xhr.send(formData)
  })
    .then(response => dispatch(uploadFinished(id, response)))
    .catch(error => dispatch(uploadError(id, error)))
}

export const requestDeleteUpload = id => ({
  type: types.REQUEST_DELETE_UPLOAD,
  payload: {
    id
  }
})

export const uploadDeleted = id => ({
  type: types.UPLOAD_DELETED,
  payload: {
    id
  }
})

export const deleteUploadError = (id, error) => ({
  type: types.DELETE_UPLOAD_ERROR,
  payload: { id, error },
  error: true
})

export const deleteUpload = id => dispatch => {
  dispatch(requestDeleteUpload(id))
  const url = `/api/v1/file/${id}/${Credentials.USER && Credentials.API_KEY
    ? `?username=${Credentials.USER}&api_key=${Credentials.API_KEY}`
    : ''}`

  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()

    xhr.onload = () => {
      if (xhr.readyState === XMLHttpRequest.DONE) {
        resolve()
      } else {
        reject(Error(xhr.statusText))
      }
    }
    xhr.onerror = () => {
      reject(Error('Network error'))
    }
    xhr.open('delete', url, true)
    xhr.setRequestHeader('accept', '*/*')
    xhr.send()
  })
    .then(() => dispatch(uploadDeleted(id)))
    .catch(error => dispatch(deleteUploadError(id, error)))<commit_msg>Add xsrf-token to delete as well<commit_after>/* global XMLHttpRequest FormData */
import Credentials from '../constants/Credentials'
import * as types from '../constants/ActionTypes'
import generateId from '../utils/generateId'
import getCookie from '../utils/getCookie'

export const startUpload = (id, file) => ({
  type: types.UPLOAD_STARTED,
  payload: { id, file }
})

export const uploadFinished = (id, finishedUpload) => ({
  type: types.UPLOAD_SUCCESS,
  payload: { id, finishedUpload }
})

export const uploadError = (id, error) => ({
  type: types.UPLOAD_ERROR,
  payload: { id, error },
  error: true
})

export const uploadProgress = (id, progress) => ({
  type: types.UPLOAD_PROGRESS,
  payload: { progress, id }
})

export const uploadFile = file => (dispatch, getState) => {
  const id = generateId()
  dispatch(startUpload(id, file.name))
  const url = `/api/v1/file/${Credentials.USER && Credentials.API_KEY
    ? `?username=${Credentials.USER}&api_key=${Credentials.API_KEY}`
    : ''}`

  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()
    const checkAborted = setInterval(() => {
      if (
        getState().uploads.find(upload => upload.id === id).status ===
        'Aborting'
      ) {
        xhr.abort()
      }
    })
    let nextTenthOfSecond = 0
    xhr.upload.onprogress = event => {
      if (new Date().getMilliseconds() / 10 < nextTenthOfSecond) return
      nextTenthOfSecond = new Date().getSeconds() / 10 + 10
      dispatch(
        uploadProgress(id, Math.floor(event.loaded / event.total * 1000) / 10)
      )
    }
    xhr.onload = () => {
      if (xhr.readyState === XMLHttpRequest.DONE) {
        dispatch(uploadProgress(id, 100))
        clearInterval(checkAborted)
        if (xhr.status === 201) {
          setTimeout(() => resolve(JSON.parse(xhr.response)), 1000)
        } else {
          reject(Error('Something went wrong uploading'))
        }
      } else {
        clearInterval(checkAborted)
        reject(Error(xhr.statusText))
      }
    }
    xhr.onabort = () => {
      clearInterval(checkAborted)
      dispatch(uploadAborted(id))
    }
    xhr.onerror = () => {
      clearInterval(checkAborted)
      reject(Error('Network error'))
    }
    xhr.open('post', url, true)
    xhr.setRequestHeader('accept', '*/*')
    xhr.setRequestHeader('X-CSRFToken', getCookie('csrftoken'))
    const formData = new FormData()
    formData.append('file', file)
    xhr.send(formData)
  })
    .then(response => dispatch(uploadFinished(id, response)))
    .catch(error => dispatch(uploadError(id, error)))
}

export const requestDeleteUpload = id => ({
  type: types.REQUEST_DELETE_UPLOAD,
  payload: {
    id
  }
})

export const uploadDeleted = id => ({
  type: types.UPLOAD_DELETED,
  payload: {
    id
  }
})

export const deleteUploadError = (id, error) => ({
  type: types.DELETE_UPLOAD_ERROR,
  payload: { id, error },
  error: true
})

export const deleteUpload = id => dispatch => {
  dispatch(requestDeleteUpload(id))
  const url = `/api/v1/file/${id}/${Credentials.USER && Credentials.API_KEY
    ? `?username=${Credentials.USER}&api_key=${Credentials.API_KEY}`
    : ''}`

  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()

    xhr.onload = () => {
      if (xhr.readyState === XMLHttpRequest.DONE) {
        resolve()
      } else {
        reject(Error(xhr.statusText))
      }
    }
    xhr.onerror = () => {
      reject(Error('Network error'))
    }
    xhr.open('delete', url, true)
    xhr.setRequestHeader('accept', '*/*')
    xhr.setRequestHeader('X-CSRFToken', getCookie('csrftoken'))
    xhr.send()
  })
    .then(() => dispatch(uploadDeleted(id)))
    .catch(error => dispatch(deleteUploadError(id, error)))
{'fraction_non_alphanumeric': 0.15687862832455785, 'fraction_numerical': 0.006750371270419873, 'mean_word_length': 3.0547345374931583, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 55, 'https://': 0, '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': '4220325', 'n_tokens_mistral': 2411, 'n_tokens_neox': 2413, 'n_words': 470}