aboutsummaryrefslogtreecommitdiffstats
path: root/ui/app/components/modals/qr-scanner/qr-scanner.component.js
blob: cb8d07d83831d073ee07d99fae7aa9e5827a0cd3 (plain) (blame)
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { BrowserQRCodeReader } from '@zxing/library'
import adapter from 'webrtc-adapter' // eslint-disable-line import/no-nodejs-modules, no-unused-vars
import Spinner from '../../spinner'
import WebcamUtils from '../../../../lib/webcam-utils'
import PageContainerFooter from '../../page-container/page-container-footer/page-container-footer.component'

export default class QrScanner extends Component {
  static propTypes = {
    hideModal: PropTypes.func.isRequired,
    qrCodeDetected: PropTypes.func,
    scanQrCode: PropTypes.func,
    error: PropTypes.bool,
    errorType: PropTypes.string,
  }

  static contextTypes = {
    t: PropTypes.func,
  }

  constructor (props, context) {
    super(props)

    this.state = {
      ready: false,
      msg: context.t('accessingYourCamera'),
    }
    this.codeReader = null
    this.permissionChecker = null
    this.needsToReinit = false

    // Clear pre-existing qr code data before scanning
    this.props.qrCodeDetected(null)
  }

  componentDidMount () {
    this.initCamera()
  }

  async checkPermisisions () {
    const { permissions } = await WebcamUtils.checkStatus()
    if (permissions) {
      clearTimeout(this.permissionChecker)
      // Let the video stream load first...
      setTimeout(_ => {
        this.setState({
          ready: true,
          msg: this.context.t('scanInstructions'),
        })
        if (this.needsToReinit) {
          this.initCamera()
          this.needsToReinit = false
        }
      }, 2000)
    } else {
      // Keep checking for permissions
      this.permissionChecker = setTimeout(_ => {
        this.checkPermisisions()
      }, 1000)
    }
  }

  componentWillUnmount () {
    clearTimeout(this.permissionChecker)
    if (this.codeReader) {
      this.codeReader.reset()
    }
  }

  initCamera () {
    this.codeReader = new BrowserQRCodeReader()
    this.codeReader.getVideoInputDevices()
      .then(videoInputDevices => {
        clearTimeout(this.permissionChecker)
        this.checkPermisisions()
        this.codeReader.decodeFromInputVideoDevice(undefined, 'video')
        .then(content => {
          const result = this.parseContent(content.text)
          if (result.type !== 'unknown') {
            this.props.qrCodeDetected(result)
            this.stopAndClose()
          } else {
            this.setState({msg: this.context.t('unknownQrCode')})
          }
        })
        .catch(err => {
          if (err && err.name === 'NotAllowedError') {
            this.setState({msg: this.context.t('youNeedToAllowCameraAccess')})
            clearTimeout(this.permissionChecker)
            this.needsToReinit = true
            this.checkPermisisions()
          }
        })
      }).catch(err => {
        console.error('[QR-SCANNER]: getVideoInputDevices threw an exception: ', err)
      })
  }

  parseContent (content) {
    let type = 'unknown'
    let values = {}

    // Here we could add more cases
    // To parse other type of links
    // For ex. EIP-681 (https://eips.ethereum.org/EIPS/eip-681)


    // Ethereum address links - fox ex. ethereum:0x.....1111
    if (content.split('ethereum:').length > 1) {

      type = 'address'
      values = {'address': content.split('ethereum:')[1] }

    // Regular ethereum addresses - fox ex. 0x.....1111
    } else if (content.substring(0, 2).toLowerCase() === '0x') {

      type = 'address'
      values = {'address': content }

    }
    return {type, values}
  }


  stopAndClose = () => {
    if (this.codeReader) {
      this.codeReader.reset()
    }
    this.setState({ ready: false })
    this.props.hideModal()
  }

  tryAgain = () => {
    // close the modal
    this.stopAndClose()
    // wait for the animation and try again
    setTimeout(_ => {
      this.props.scanQrCode()
    }, 1000)
  }

  renderVideo () {
    return (
      <div className={'qr-scanner__content__video-wrapper'}>
        <video
          id="video"
          style={{
            display: this.state.ready ? 'block' : 'none',
          }}
        />
        { !this.state.ready ? <Spinner color={'#F7C06C'} /> : null}
      </div>
    )
  }

  renderErrorModal () {
    let title, msg

    if (this.props.error) {
      if (this.props.errorType === 'NO_WEBCAM_FOUND') {
        title = this.context.t('noWebcamFoundTitle')
        msg = this.context.t('noWebcamFound')
      } else {
        title = this.context.t('unknownCameraErrorTitle')
        msg = this.context.t('unknownCameraError')
      }
    }

    return (
      <div className="qr-scanner">
        <div className="qr-scanner__close" onClick={this.stopAndClose}></div>

        <div className="qr-scanner__image">
          <img src={'images/webcam.svg'} width={70} height={70} />
        </div>
        <div className="qr-scanner__title">
          { title }
        </div>
        <div className={'qr-scanner__error'}>
          {msg}
        </div>
        <PageContainerFooter
          onCancel={this.stopAndClose}
          onSubmit={this.tryAgain}
          cancelText={this.context.t('cancel')}
          submitText={this.context.t('tryAgain')}
          submitButtonType="confirm"
        />
      </div>
    )
  }

  render () {
    const { t } = this.context

    if (this.props.error) {
      return this.renderErrorModal()
    }

    return (
      <div className="qr-scanner">
        <div className="qr-scanner__close" onClick={this.stopAndClose}></div>
        <div className="qr-scanner__title">
          { `${t('scanQrCode')}` }
        </div>
        <div className="qr-scanner__content">
          { this.renderVideo() }
        </div>
        <div className={'qr-scanner__status'}>
          {this.state.msg}
        </div>
      </div>
    )
  }
}