aboutsummaryrefslogtreecommitdiff
path: root/vnext/server/hms.js
blob: 4945fe2ac36512664cc0377d1dd20ae909b994b0 (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
import axios from 'axios'
import config from 'config'
import debug from 'debug'
var log = debug('hms')

const { client_id, client_secret, project_id } = config.has('service.hms') ? config.get('service.hms') : {}

const refreshToken = async () => {
    if (client_id) {
        const params = new URLSearchParams()
        params.append('grant_type', 'client_credentials')
        params.append('client_id', client_id)
        params.append('client_secret', client_secret)
        const res = await axios.post('https://oauth-login.cloud.huawei.com/oauth2/v3/token', params).catch(console.log)
        try {
            const access = res.data
            return access.access_token
        } catch (error) {
            log(error)
            return ''
        }
    }
    return ''
}

export const send = async (msg, tokenList = []) => {
    const adminToken = await refreshToken()
    if (adminToken && tokenList.length > 0) {
        const payload = {
            'message': msg
        }
        const response = await axios.post(`https://push-api.cloud.huawei.com/v2/${project_id}/messages:send`, {
                'validate_only': false,
                'message': {
                    'android': {
                        'fast_app_target': 2
                    },
                    'data': JSON.stringify(payload),
                    'priority': 'high',
                    'delayWhileIdle': false,
                    'token': tokenList
                }
            }, {
            headers: {
                'Authorization': `Bearer ${adminToken}`,
                'Content-Type': 'application/json'
            }
        }).catch(log)
        log(`hcm: ${response.status} ${JSON.stringify(response.data)}`)
    }
}