From 32fb3f61e8ce90b30d7ba58c820c9be523e7ff3f Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Sat, 11 Feb 2023 04:02:56 +0300 Subject: HMS notifications --- vnext/server/hms.js | 55 ++++++++++++++++++++++++++++++++++++++++ vnext/server/middleware/event.js | 6 +++++ 2 files changed, 61 insertions(+) create mode 100644 vnext/server/hms.js diff --git a/vnext/server/hms.js b/vnext/server/hms.js new file mode 100644 index 00000000..e9068c58 --- /dev/null +++ b/vnext/server/hms.js @@ -0,0 +1,55 @@ +import axios from 'axios'; +import config from 'config'; +import debug from 'debug'; +var log = debug('hms'); + +const { client_id, client_secret } = config.get('service.hms'); + +const refreshToken = async () => { + 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 { + log(`HMS response: ${JSON.stringify(res.data)}`); + const access = res.data; + log(`HMS access token: ${access.access_token}`); + return access.access_token; + } catch (error) { + log(error); + return ''; + } +}; + +export const send = async (msg, tokenList = []) => { + const adminToken = await refreshToken(); + if (adminToken) { + const response = await axios.post(`https://push-api.cloud.huawei.com/v1/${client_id}/messages:send`, { + headers: { + 'Authorization': adminToken, + 'Content-Type': 'application/json' + }, + body: { + 'validate_only': false, + 'message': { + 'android': { + 'fast_app_target': 2 + }, + 'data': { + 'pushtype': 1, + 'pushbody': { + 'custom': { + 'message': msg + } + } + }, + 'priority': 'high', + 'delayWhileIdle': false, + 'token': tokenList + } + } + }).catch(log); + log(`hcm: ${response.status}`); + } +}; diff --git a/vnext/server/middleware/event.js b/vnext/server/middleware/event.js index 5ea855dd..136ae268 100644 --- a/vnext/server/middleware/event.js +++ b/vnext/server/middleware/event.js @@ -4,6 +4,7 @@ import { sendTelegramNotification } from '../durov'; import { subscribers } from '../http'; import { sendNotification, buildNotification } from '../sender'; import debug from 'debug'; +import { send } from '../hms'; var log = debug('event'); /** @type {number[]} */ @@ -40,6 +41,11 @@ function processMessageEvent(msg) { .filter(t => ['durov'].includes(t.type)) .map(t => t.token); sendTelegramNotification(msg, durovIds); + let hmsIds = (user.tokens || []) + .filter(t => t.type === 'hcm') + .map(t => t.token); + log(`${user.uname}: ${hmsIds}`); + send(msg, hmsIds).then(() => {}).catch(log); }); }).catch(log); } -- cgit v1.2.3