summaryrefslogtreecommitdiff
path: root/client/faceAnalysis/faceAnalysis.actions.js
blob: 860d32926f3b005c761e9ec684c977dec64110b8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// import fetchJsonp from 'fetch-jsonp'
import * as types from '../types'
// import { hashPath } from '../util'
import { store } from '../store'
import { get, post } from '../util'
// import querystring from 'query-string'

// urls

const url = {
  upload: () => process.env.API_HOST + '/task/upload/blur',
}
export const publicUrl = {
}

// standard loading events

const loading = (tag, offset) => ({
  type: types.faceAnalysis.loading,
  tag,
  offset
})
const loaded = (tag, data, offset = 0) => ({
  type: types.faceAnalysis.loaded,
  tag,
  data,
  offset
})
const polled = (data, offset = 0) => ({
  type: types.faceAnalysis.poll,
  data,
  offset
})
const error = (tag, err) => ({
  type: types.faceAnalysis.error,
  tag,
  err
})

// search UI functions

export const updateOptions = opt => dispatch => {
  dispatch({ type: types.faceAnalysis.update_options, opt })
}

// API functions

// task polling

const POLL_DELAY = 500
let pollTimeout = null

export const poll = (payload, taskURL) => dispatch => {
  clearTimeout(pollTimeout)
  console.log('polling...')
  get(taskURL)
    .then(data => {
      console.log('poll', data)
      dispatch(polled(data))
      if (data.state !== 'error' && data.state !== 'complete') {
        pollTimeout = setTimeout(() => poll(payload, taskURL), POLL_DELAY)
      }
    })
    .catch(err => dispatch(error('result', err)))
}

export const upload = (payload, file) => dispatch => {
  const tag = 'task'
  const fd = new FormData()
  fd.append('query_img', file)
  dispatch(loading(tag))
  post(url.upload(), fd)
    .then(data => {
      console.log('loaded!', tag, data)
      dispatch(loaded(tag, data))
      const { result, taskURL } = data
      if (result && taskURL) {
        poll(payload, taskURL)(dispatch)
      }
    })
    .catch(err => dispatch(error(tag, err)))
}