From 98fc529e92bcaf0a63bf0c60a581772d70d4dc8f Mon Sep 17 00:00:00 2001 From: david Date: Thu, 7 Nov 2019 18:24:29 +0100 Subject: [PATCH 01/14] Notificaciones push --- helpers/composes.helper.js | 4 +- .../notification/notification.controller.js | 140 ++++++++++++------ modules/notification/notification.model.js | 4 + modules/notification/notification.routes.js | 8 +- modules/notification/notification.service.js | 30 ++-- .../notification/notification.validations.js | 13 +- 6 files changed, 126 insertions(+), 73 deletions(-) diff --git a/helpers/composes.helper.js b/helpers/composes.helper.js index e8fcff4..9c04b46 100644 --- a/helpers/composes.helper.js +++ b/helpers/composes.helper.js @@ -258,9 +258,7 @@ const usersIdsComposer = (inscriptions) => { let usersId = [] if (inscriptions) { inscriptions.map((inscription) => { - usersId.push({ - userId: inscription.userId, - }); + usersId.push(inscription.userId); }); }; return usersId; diff --git a/modules/notification/notification.controller.js b/modules/notification/notification.controller.js index cf84b86..a40d5c1 100644 --- a/modules/notification/notification.controller.js +++ b/modules/notification/notification.controller.js @@ -19,29 +19,7 @@ const extraControllers = { sendNotificationEvent: async (req, res, next) => { - /** - * notificationSample = { - * "tittle": "título de la notificación", - * "message": "cuerpo de la notificación", - * "recipients": { - * "eventId": "xxx-xxx-xxx-xxx", - * "segment": "ALL" | "ALL_VALIDATED" | "ALL_NOT_VALIDATED" | - * "PARTNERS_ALL" | "PARTNERS_VALIDATED" | "PARTNERS_NOT_VALIDATED" | - * "COLLEGE_ALL" | "COLLEGE_VALIDATED" | "COLLEGE_NOT_VALIDATED" - * }, - * "data": { - * "type": "message", - * "title": "Título del mensaje", - * "message": "Cuerpo del mensaje", - * "button": { - * "caption": "Etiqueta del boton", - * "url": "https://www.site.es", - * "screen": "", - * "paramId": "23", - * } - * } - *} - */ + let usersIds = null; const params = req.body; const eventId = params.recipients.eventId; @@ -88,6 +66,31 @@ const extraControllers = { }, sendNotification: (config) => { + + /** + * notificationSample = { + * "tittle": "título de la notificación", + * "message": "cuerpo de la notificación", + * "recipients": { + * "eventId": "xxx-xxx-xxx-xxx", + * "segment": "ALL" | "ALL_VALIDATED" | "ALL_NOT_VALIDATED" | + * "PARTNERS_ALL" | "PARTNERS_VALIDATED" | "PARTNERS_NOT_VALIDATED" | + * "COLLEGE_ALL" | "COLLEGE_VALIDATED" | "COLLEGE_NOT_VALIDATED" + * }, + * "data": { + * "type": "message", + * "title": "Título del mensaje", + * "message": "Cuerpo del mensaje", + * "button": { + * "caption": "Etiqueta del boton", + * "url": "https://www.site.es", + * "screen": "", + * "paramId": "23", + * } + * } + *} + */ + return async (req, res, next) => { config = config || { scopes: [], @@ -97,24 +100,35 @@ const extraControllers = { const context = buildContext(req, config); let params = extractParamsFromRequest(req, res); - let userIds = req.body.userIds; - if (!userIds) { - return handleErrorResponse(controllerOptions.MODULE_NAME, 'sendNotification', new Error('Missing user Ids'), res) - } + let userIds = undefined; + let eventId = undefined; + let segment = undefined; + const { body } = req; - if (!req.body.title) { + if (!body.title) { return handleErrorResponse(controllerOptions.MODULE_NAME, 'sendNotification', new Error('Missing message title'), res) } - if (!req.body.message) { + if (!body.message) { return handleErrorResponse(controllerOptions.MODULE_NAME, 'sendNotification', new Error('Missing message content'), res) } + // Evento? + if (body.recipients.eventId) { + eventId = body.recipients.eventId; + segment = body.recipients.segment; + } else if (body.recipients.userIds) { + userIds = body.recipients.userIds; + } else { + return handleErrorResponse(controllerOptions.MODULE_NAME, 'sendNotification', new Error('Missing user Ids or event Ids'), res) + } + + try { let getUserDevicesPromise = (userId) => userDeviceService.fetchAll({ params: { userId: userId }}, context).then(function(result) { return new Promise(function(resolve) { resolve(result.rows) }); }); - let saveNotificationPromise = (notification) => notificationService.create(notification, context); + let saveNotificationPromise = (notification) => notificationService.createNotification(notification); let sendNotificationsPromise = (messages) => notificationService.sendNotification(messages); let disableUserDevicePromise = (token) => userDeviceService.update({ params: { token: token, @@ -149,12 +163,13 @@ const extraControllers = { let saveResponseStatusPromise = (messages, tickets) => notificationDetailService.saveNotificationDetails(messages, tickets); const notificationRecord = { - date: moment(), - title: req.body.title, - body: req.body.message, - ttl: req.body.ttl || undefined, - priority: req.body.priority || 'default', - data: req.body.data || { userIds: req.body.userIds }, + date: body.date, + title: body.title, + body: body.message, + ttl: body.ttl, + priority: body.priority, + recipients: body.recipients, + data: body.data, userId: context.user.id, }; @@ -181,15 +196,56 @@ const extraControllers = { }); }; - let getUserDevicesList = []; - userIds.forEach(function (userId) { - getUserDevicesList.push(getUserDevicesPromise(userId)); - }); + let getUserIds = async () => { + if (userIds) { + return new Promise(function(resolve) { resolve(userIds) } ); + } else if (eventId && segment) { + switch (segment) { + //Todos los inscritos tanto invitados como libres + case 'ALL_VALIDATED': + userIds = await eventInscriptionService._getInscriptionByEventAndValidated(eventId, true); + break; + //Todos los de lista de espera tanto invitados como libres (Actualmente en invitados no hay lista de espera) + case 'ALL_NOT_VALIDATED': + userIds = await eventInscriptionService._getInscriptionByEventAndValidated(eventId, false); + break; - saveNotificationPromise(notificationRecord) - .then(function(notification) { + //Solo invitados como actualmente no se usa codigo de reserva para los coles, vale con filtrar por aquellos que tengan codigo de reserva + case 'PARTNERS_ALL': + userIds = await eventInscriptionService._getInscriptionByEventFromPartner(eventId); + break; + + //Todos los inscritos al evento, tanto validados como en lista de espera + default: //ALL + userIds = await eventInscriptionService._getInscriptionByEvent(eventId); + break; + } + + return new Promise(function (resolve) { resolve(usersIdsComposer(userIds)); }); + + } else { + return handleErrorResponse(controllerOptions.MODULE_NAME, 'sendNotification', new Error('Missing event and segment'), res) + } + } + + let getUserDevicesList = []; + + Promise.all([ + saveNotificationPromise(notificationRecord), + getUserIds() + ]) + .then(function(result) { + let notification = result[0]; notificationRecord.id = notification.id; + + userIds = result[1]; + + userIds.forEach(function (userId) { + console.log(userId); + getUserDevicesList.push(getUserDevicesPromise(userId)); + }); + return Promise.all(getUserDevicesList) }).then(function (userDeviceList) { return new Promise(function(resolve) { resolve(userDeviceList[0]); }); diff --git a/modules/notification/notification.model.js b/modules/notification/notification.model.js index 469ec2f..76fdbd5 100644 --- a/modules/notification/notification.model.js +++ b/modules/notification/notification.model.js @@ -26,6 +26,10 @@ module.exports = function (sequelize, DataTypes) { allowNull: false, default: 'default', }, + recipients: { + type: DataTypes.JSON, + allowNull: true, + }, data: { type: DataTypes.JSON, allowNull: true, diff --git a/modules/notification/notification.routes.js b/modules/notification/notification.routes.js index 41eb88a..c22f692 100644 --- a/modules/notification/notification.routes.js +++ b/modules/notification/notification.routes.js @@ -6,7 +6,7 @@ const PaginateMiddleware = require('../../middlewares/paginate'); const FieldMiddleware = require('../../middlewares/fields'); const SortMiddleware = require('../../middlewares/sort'); const notificationController = require('./notification.controller'); -const { pushSendEvent, deviceTokenInputType, notificationSendType } = require('./notification.validations'); +const { pushSendEvent, deviceTokenInputType } = require('./notification.validations'); const generalInvalidFields = [ 'createdAt', 'updatedAt', @@ -36,17 +36,17 @@ routes.get('/admin/notifications/:id', routes.post('/admin/notifications', isAdministratorUser, - SchemaValidator(notificationSendType, true), + SchemaValidator(pushSendEvent, true), notificationController.sendNotification({ scopes: ['defaultScope'] }) ); -routes.post('/admin/notifications/event', +/*routes.post('/admin/notifications/event', isAdministratorUser, SchemaValidator(pushSendEvent, true), notificationController.sendNotificationEvent -); +);*/ /* Borrar cuando ya no aparezca la versión 1.0.10 */ routes.post('/notifications/register', diff --git a/modules/notification/notification.service.js b/modules/notification/notification.service.js index ef93031..40b0497 100644 --- a/modules/notification/notification.service.js +++ b/modules/notification/notification.service.js @@ -1,3 +1,4 @@ +const moment = require('moment'); const { Expo } = require('expo-server-sdk'); const { generateService, parseParamsToFindOptions } = require('../../helpers/service.helper'); const models = require('../../core/models'); @@ -7,26 +8,19 @@ const expo = new Expo(); const extraMethods = { - createNotification: (date, title, body, ttl, priority, data, userId) => { + createNotification: ({ date, title, body, ttl, priority, recipients, data, userId }) => { console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>< Date: Thu, 7 Nov 2019 18:37:53 +0100 Subject: [PATCH 02/14] . --- modules/notification/notification.controller.js | 1 + 1 file changed, 1 insertion(+) diff --git a/modules/notification/notification.controller.js b/modules/notification/notification.controller.js index a40d5c1..3e8cc45 100644 --- a/modules/notification/notification.controller.js +++ b/modules/notification/notification.controller.js @@ -248,6 +248,7 @@ const extraControllers = { return Promise.all(getUserDevicesList) }).then(function (userDeviceList) { + console.log(userDeviceList); return new Promise(function(resolve) { resolve(userDeviceList[0]); }); }) .then(disableInvalidUserDevicesPromise) From 32fe3d7e7954f6867cc2602a5937bc6de75d6ec5 Mon Sep 17 00:00:00 2001 From: david Date: Thu, 7 Nov 2019 18:45:50 +0100 Subject: [PATCH 03/14] . --- modules/notification/notification.controller.js | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/modules/notification/notification.controller.js b/modules/notification/notification.controller.js index 3e8cc45..bb36fe8 100644 --- a/modules/notification/notification.controller.js +++ b/modules/notification/notification.controller.js @@ -138,6 +138,7 @@ const extraControllers = { return new Promise(function (resolve) { let _userDevices = []; userDevices.forEach(async function (userDevice) { + console.log(userDevice); if (!userDeviceService.isValidPushToken(userDevice.token)) { await disableUserDevicePromise(userDevice.token); } else { @@ -236,9 +237,7 @@ const extraControllers = { getUserIds() ]) .then(function(result) { - let notification = result[0]; - notificationRecord.id = notification.id; - + notificationRecord = result[0]; userIds = result[1]; userIds.forEach(function (userId) { @@ -249,7 +248,7 @@ const extraControllers = { return Promise.all(getUserDevicesList) }).then(function (userDeviceList) { console.log(userDeviceList); - return new Promise(function(resolve) { resolve(userDeviceList[0]); }); + return new Promise(function(resolve) { resolve(userDeviceList); }); }) .then(disableInvalidUserDevicesPromise) .then(buildMessagesPromise) From a4bb28d909117562e5954ea0c4f74bf86835d93d Mon Sep 17 00:00:00 2001 From: david Date: Thu, 7 Nov 2019 18:47:35 +0100 Subject: [PATCH 04/14] . --- modules/notification/notification.controller.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/notification/notification.controller.js b/modules/notification/notification.controller.js index bb36fe8..d93e20b 100644 --- a/modules/notification/notification.controller.js +++ b/modules/notification/notification.controller.js @@ -163,7 +163,7 @@ const extraControllers = { let saveResponseStatusPromise = (messages, tickets) => notificationDetailService.saveNotificationDetails(messages, tickets); - const notificationRecord = { + let notificationRecord = { date: body.date, title: body.title, body: body.message, From 7f4cbfa588f8daccae9898904cae06e0bcddc7ba Mon Sep 17 00:00:00 2001 From: david Date: Thu, 7 Nov 2019 19:02:35 +0100 Subject: [PATCH 05/14] . --- modules/notification/notification.controller.js | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/modules/notification/notification.controller.js b/modules/notification/notification.controller.js index d93e20b..45cfbd7 100644 --- a/modules/notification/notification.controller.js +++ b/modules/notification/notification.controller.js @@ -248,7 +248,13 @@ const extraControllers = { return Promise.all(getUserDevicesList) }).then(function (userDeviceList) { console.log(userDeviceList); - return new Promise(function(resolve) { resolve(userDeviceList); }); + let result = []; + userDeviceList.forEach(function (elements) { + elements.forEach(function (item) { + result.push(item) + }) + }); + return new Promise(function (resolve) { resolve(result); }); }) .then(disableInvalidUserDevicesPromise) .then(buildMessagesPromise) From a2d2d7fb5812a321d8005b74c8584515eb19609c Mon Sep 17 00:00:00 2001 From: david Date: Thu, 7 Nov 2019 19:06:45 +0100 Subject: [PATCH 06/14] . --- modules/notification/notification.service.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/notification/notification.service.js b/modules/notification/notification.service.js index 40b0497..4b44c80 100644 --- a/modules/notification/notification.service.js +++ b/modules/notification/notification.service.js @@ -17,8 +17,8 @@ const extraMethods = { title: title, body: body, userId: userId, - ttl: ttl || undefined, - priority: priority || 'default', + ttl: ttl ? ttl : undefined, + priority: priority ? priority : 'default', recipients: recipients, data: data, }); From 664c8e52718d38cc242f1be1ea99f4b60a27629e Mon Sep 17 00:00:00 2001 From: david Date: Thu, 7 Nov 2019 19:11:14 +0100 Subject: [PATCH 07/14] . --- .../notification/notification.controller.js | 50 +------------------ .../notification/notification.validations.js | 2 + 2 files changed, 4 insertions(+), 48 deletions(-) diff --git a/modules/notification/notification.controller.js b/modules/notification/notification.controller.js index 45cfbd7..e8110e2 100644 --- a/modules/notification/notification.controller.js +++ b/modules/notification/notification.controller.js @@ -17,54 +17,6 @@ const controllerOptions = { MODULE_NAME }; const extraControllers = { - sendNotificationEvent: async (req, res, next) => { - - - let usersIds = null; - const params = req.body; - const eventId = params.recipients.eventId; - const segment = params.recipients.segment; - console.log('prueba de llamada>>>>> ', params); - - try { - notificationService.createNotification(params.date, params.title, params.message, undefined, 'default', params.data, req.user.id); - switch (segment) { - //Todos los inscritos al evento tanto en validos como en lista de espera - case 'ALL': - usersIds = await eventInscriptionService._getInscriptionByEvent(eventId); - break; - //Todos los inscritos tanto invitados como libres - case 'ALL_VALIDATED': - usersIds = await eventInscriptionService._getInscriptionByEventAndValidated(eventId, true); - break; - //Todos los de lista de espera tanto invitados como libres (Actualmente en invitados no hay lista de espera) - case 'ALL_NOT_VALIDATED': - usersIds = await eventInscriptionService._getInscriptionByEventAndValidated(eventId, false); - break; - - //Solo invitados como actualmente no se usa codigo de reserva para los coles, vale con filtrar por aquellos que tengan codigo de reserva - case 'PARTNERS_ALL': - usersIds = await eventInscriptionService._getInscriptionByEventFromPartner(eventId); - - break; - - //Todos los inscritos al evento, tanto validados como en lista de espera - default: //ALL - break; - } - - usersIds = usersIdsComposer(usersIds); - console.log('usuarios inscritos>>>>> ', usersIds); - - } catch(error) { - return handleErrorResponse(MODULE_NAME, 'sendNotificationEvent', error, res); - } - - - - return handleResultResponse("sendNotificationEvent", null, params, res, httpStatus.OK); - }, - sendNotification: (config) => { /** @@ -173,6 +125,8 @@ const extraControllers = { data: body.data, userId: context.user.id, }; + console.log('--------------------'); + console.log(notificationRecord); let buildMessagesPromise = (userDevices) => { return new Promise(function (resolve) { diff --git a/modules/notification/notification.validations.js b/modules/notification/notification.validations.js index fed4961..aa5e274 100644 --- a/modules/notification/notification.validations.js +++ b/modules/notification/notification.validations.js @@ -20,6 +20,8 @@ const pushSendEvent = Joi.object().keys({ eventId: Joi.string().optional(), segment: Joi.string().optional(), }), + priority: Joi.string().optional(), + ttl: Joi.string().optional(), data: Joi.object().keys({ type: Joi.string().required(), title: Joi.string().required(), From 37419b8a2a4296069e9b8e516bb0148f627e9bbd Mon Sep 17 00:00:00 2001 From: david Date: Mon, 11 Nov 2019 17:43:08 +0100 Subject: [PATCH 08/14] . --- helpers/message.helper.js | 11 + helpers/messages.json | 16 ++ helpers/notification.helpers.js | 48 ++++ helpers/push.helper.js | 133 +++++++++++ modules/events/event.controller.js | 65 ++++-- .../notification/notification.controller.js | 124 +--------- modules/notification/notification.service.js | 214 +++++++++--------- .../notification_detail.service.js | 1 + package.json | 1 + 9 files changed, 374 insertions(+), 239 deletions(-) create mode 100644 helpers/notification.helpers.js create mode 100644 helpers/push.helper.js diff --git a/helpers/message.helper.js b/helpers/message.helper.js index d8a718a..4fb0a84 100644 --- a/helpers/message.helper.js +++ b/helpers/message.helper.js @@ -1,5 +1,7 @@ 'use strict'; +const tinytim = require('tinytim').tim; + //////////////////////////////////////////////////////////////////////////////// // CONSTANTS //////////////////////////////////////////////////////////////////////////////// @@ -29,7 +31,16 @@ function buildMessage(text) { return buildGenericMessage(TITLE_MESSAGE, text) } +function tinytom(literal, data) { + if (typeof literal === 'object' && literal !== null) { + return JSON.parse(tinytim(JSON.stringify(literal), data)); + } else { + return tinytim(literal, data); + } +} + module.exports = { + tinytom, buildErrorMessage, buildMessage, //For testing diff --git a/helpers/messages.json b/helpers/messages.json index 7f7b020..a95822e 100644 --- a/helpers/messages.json +++ b/helpers/messages.json @@ -21,5 +21,21 @@ "html": "¡Hola!,

Solicitaste cambiar la contraseña, hemos creado una nueva.

Entra en la app con tu dirección de email y esta clave: {{password}}

Fundación Lo Que De Verdad Importa." } } + }, + "push": { + "confirmInvitation": { + "title": "{{ congress }}", + "message": "Tu inscripción al congreso de {{ congress }} está confirmada.", + "data": { + "type": "message", + "title": "{{ congress }}", + "message": "Tu inscripción al congreso de {{ congress }} está confirmada.\nPor favor, si no puedes asistir al congreso, elimina tu inscripción para que otra persona pueda asistir.\n", + "button": { + "caption": "Ver mi entrada", + "screen": "Ticket", + "paramId": "{{ ticketId }}" + } + } + } } } \ No newline at end of file diff --git a/helpers/notification.helpers.js b/helpers/notification.helpers.js new file mode 100644 index 0000000..663c763 --- /dev/null +++ b/helpers/notification.helpers.js @@ -0,0 +1,48 @@ +const moment = require('moment'); +const { tinytom } = require('./message.helper'); +const messages = require('./messages.json'); + + +const createNotification = (data) => { + return { + date: data.date, + title: data.title, + body: data.message, + ttl: data.ttl, + priority: data.priority ? data.priority : 'high', + recipients: data.recipients, + data: data.data, + userId: data.userId, + _displayInForeground: true, + sound: 'default', + } +} + +createNotificationValidatedInscription = (inscription) => { + let jsonMessage = messages.push.confirmInvitation; + + const jsonNotification = tinytom(jsonMessage, { + congress: inscription.event.name, + ticketId: inscription.id, + }); + + return { + ...jsonNotification, + date: moment(), + priority: "high", + _displayInForeground: true, + sound: 'default', + recipients: { + "userIds": [ + inscription.user.id, + ] + }, + } +} + + +module.exports = { + createNotificationValidatedInscription, + createNotification, + //createMessageNotification +} diff --git a/helpers/push.helper.js b/helpers/push.helper.js new file mode 100644 index 0000000..6a4fb8b --- /dev/null +++ b/helpers/push.helper.js @@ -0,0 +1,133 @@ +const { Expo } = require('expo-server-sdk'); + +// Create a new Expo SDK client +const expo = new Expo(); + +const createPushMessage = (data) => { + console.log('---------------------------------'); + console.log(data); + console.log('---------------------------------'); + return { + title: data.title, + body: data.body, + ttl: data.ttl, + priority: data.priority, + userId: data.userId, + to: data.to, + notificationId: data.id, + data: data.data, + _displayInForeground: true, + sound: 'default', + } +}; + + + + + +const sendPushMessage = async (messages) => { + + // The Expo push notification service accepts batches of notifications so + // that you don't need to send 1000 requests to send 1000 notifications. We + // recommend you batch your notifications to reduce the number of requests + // and to compress them (notifications with similar content will get + // compressed). + + /** + * There is a limit on the number of push notifications (100) you can send at once.Use + * `chunkPushNotifications` to divide an array of push notification messages into appropriately + * sized chunks + */ + + // Later, after the Expo push notification service has delivered the + // notifications to Apple or Google (usually quickly, but allow the the service + // up to 30 minutes when under load), a "receipt" for each notification is + // created. The receipts will be available for at least a day; stale receipts + // are deleted. + // + // The ID of each receipt is sent back in the response "ticket" for each + // notification. In summary, sending a notification produces a ticket, which + // contains a receipt ID you later use to get the receipt. + // + // The receipts may contain error codes to which you must respond. In + // particular, Apple or Google may block apps that continue to send + // notifications to devices that have blocked notifications or have uninstalled + // your app. Expo does not control this policy and sends back the feedback from + // Apple and Google so you can handle it appropriately. + + let chunks = expo.chunkPushNotifications(messages); + return { + messages, + tickets: await _sendPushNotificationsAsync(chunks) + }; +}; + +module.exports = { + sendPushMessage, + createPushMessage, +} + + +const _sendPushNotificationsAsync = async function (chunks) { + return new Promise(async function (resolve) { + let tickets = []; + // Send the chunks to the Expo push notification service. There are + // different strategies you could use. A simple one is to send one chunk at a + // time, which nicely spreads the load out over time: + for (let chunk of chunks) { + try { + let ticketChunk = await expo.sendPushNotificationsAsync(chunk); + tickets.push(...ticketChunk); + + // NOTE: If a ticket contains an error code in ticket.details.error, you + // must handle it appropriately. The error codes are listed in the Expo + // documentation: + // https://docs.expo.io/versions/latest/guides/push-notifications#response-format + + } catch (error) { + console.error(error); + } + } + + resolve(tickets); + }); +}; + +const _getPushNotificationsResultAsync = async function (receiptIdChunks) { + return new Promise(async function (resolve) { + // Like sending notifications, there are different strategies you could use + // to retrieve batches of receipts from the Expo service. + + let result = []; + + console.log(receiptIdChunks); + + for (let chunk of receiptIdChunks) { + try { + let receipts = await expo.getPushNotificationReceiptsAsync(chunk); + console.log('hola', receipts); + + // The receipts specify whether Apple or Google successfully received the + // notification and information about an error, if one occurred. + for (let key in receipts) { + if (receipts[key].status === 'ok') { + result.push[receipts[key]]; + continue; + } else if (receipts[key].status === 'error') { + console.error(`There was an error sending a notification: ${receipts[key].message}`); + if (receipts[key].details && receipts[key].details.error) { + // The error codes are listed in the Expo documentation: + // https://docs.expo.io/versions/latest/guides/push-notifications#response-format + // You must handle the errors appropriately. + console.error(`The error code is ${receipts[key].details.error}`); + } + } + } + } catch (error) { + console.error(error); + } + } + + resolve(result); + }); +} diff --git a/modules/events/event.controller.js b/modules/events/event.controller.js index cc11e0e..fc6a6f2 100644 --- a/modules/events/event.controller.js +++ b/modules/events/event.controller.js @@ -4,11 +4,14 @@ const httpStatus = require('http-status'); const generateControllers = require('../../core/controllers'); const QRHelper = require('../../helpers/qr.helper'); const emailHelper = require('../../helpers/mail.helper'); +const notificationHelper = require('../../helpers/notification.helpers'); const path = require("path"); const messages = require('../../helpers/messages.json'); const eventService = require('./event.service'); const eventReservationService = require('./events_reservations.service'); const eventInscriptionService = require('./events_inscriptions.service'); +const notificationController = require('../notification/notification.controller'); + const { extractParamsFromRequest, handleErrorResponse, handleResultResponse } = require('../../helpers/controller.helper'); //PRUEBA @@ -26,25 +29,25 @@ function generateMemberInscription (user, inscription, reservation) { let memberInscription = null; if (user && inscription) { memberInscription = { - marketing_memberId: null, - email: user.email, - name: user.name, - surname: user.surname, - source: inscription.source, - event_name: (inscription.event) ? inscription.event.name : 'N/A', - event_date: (inscription.event) ? inscription.event.init_date : 'N/A', - reservation_code: (reservation) ? reservation.reservation_code : null, - date_inscription: inscription.date, - code_ticket: inscription.code_ticket, - validated: inscription.validated, - color: (reservation) ? reservation.color : null, - description: ((reservation) ? reservation.description : 'Entrada').toUpperCase(), - entity: (reservation) ? reservation.Entity.name : user.entityId, - userId: user.id, - qrConfig: null, - qrCode: null, + marketing_memberId: null, + email: user.email, + name: user.name, + surname: user.surname, + source: inscription.source, + event_name: (inscription.event) ? inscription.event.name : 'N/A', + event_date: (inscription.event) ? inscription.event.init_date : 'N/A', + reservation_code: (reservation) ? reservation.reservation_code : null, + date_inscription: inscription.date, + code_ticket: inscription.code_ticket, + validated: inscription.validated, + color: (reservation) ? reservation.color : null, + description: ((reservation) ? reservation.description : 'Entrada').toUpperCase(), + entity: (reservation) ? reservation.Entity.name : user.entityId, + userId: user.id, + qrConfig: null, + qrCode: null, - } + } } return memberInscription; @@ -264,19 +267,31 @@ console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ', member); - //Mandar correo de confirmacion de desinscripcion + + //Mandar correo de confirmacion de inscripcion try { + + var member = generateMemberInscription(inscription.user, inscription, inscription.reservation); + member.marketing_memberId = await eventInscriptionService._addMember(marketingListIdEvent, member); + eventInscriptionService._updateMarketingMemberOfInscription(inscription.id, member.marketing_memberId); + member.qrConfig = generateQRConfig(member); + member.qrCode = await QRHelper.getInscriptionQRCode(member.qrConfig); + console.log('mandar correo>>>>>>>>>>>>>>>>>>>>> ', member); emailHelper.sendTicket(generateHeaderMail(member), generateBodyMail(member)) } catch (error) { console.log('No se ha podido mandar email con entrada'); }; + + + try { + let notification = notificationHelper.createNotificationValidatedInscription(inscription); + notificationController.sendNotification(notification); + + console.log(result); + } catch (error) { + console.log('No se ha podido mandar email con entrada'); + }; }; return handleResultResponse("Inscripción validada", null, params, res, httpStatus.OK); diff --git a/modules/notification/notification.controller.js b/modules/notification/notification.controller.js index e8110e2..500d329 100644 --- a/modules/notification/notification.controller.js +++ b/modules/notification/notification.controller.js @@ -8,6 +8,8 @@ const notificationDetailService = require('./notification_detail.service'); const userDeviceService = require('./user_device.service'); const eventInscriptionService = require('../events/events_inscriptions.service'); const { usersIdsComposer } = require('../../helpers/composes.helper'); +const pushHelper = require('../../helpers/push.helper'); +const notificationHelper = require('../../helpers/notification.helpers'); const { extractParamsFromRequest, handleErrorResponse, handleResultResponse } = require('../../helpers/controller.helper'); @@ -76,85 +78,17 @@ const extraControllers = { } - try { - let getUserDevicesPromise = (userId) => userDeviceService.fetchAll({ params: { userId: userId }}, context).then(function(result) { - return new Promise(function(resolve) { resolve(result.rows) }); + try { + let notification = notificationHelper.createNotification ({ + ...body, + userId: context.user.id }); - let saveNotificationPromise = (notification) => notificationService.createNotification(notification); - let sendNotificationsPromise = (messages) => notificationService.sendNotification(messages); - let disableUserDevicePromise = (token) => userDeviceService.update({ params: { - token: token, - }}, { valid: 0, invalidated: moment() }, context); - - let disableInvalidUserDevicesPromise = (userDevices) => { - return new Promise(function (resolve) { - let _userDevices = []; - userDevices.forEach(async function (userDevice) { - console.log(userDevice); - if (!userDeviceService.isValidPushToken(userDevice.token)) { - await disableUserDevicePromise(userDevice.token); - } else { - _userDevices.push(userDevice); - } - }); - - resolve(_userDevices) - }); - }; - - let disableUserDevicesWithErrorStatus = (messages, tickets) => { - return new Promise(function (resolve) { - tickets.forEach(async function (ticket, index) { - if ((ticket.status === 'error') && (ticket.details.error === 'DeviceNotRegistered')) { - await disableUserDevicePromise(messages[index].to) - } - }); - resolve(true); - }); - } - - let saveResponseStatusPromise = (messages, tickets) => notificationDetailService.saveNotificationDetails(messages, tickets); - - let notificationRecord = { - date: body.date, - title: body.title, - body: body.message, - ttl: body.ttl, - priority: body.priority, - recipients: body.recipients, - data: body.data, - userId: context.user.id, - }; console.log('--------------------'); - console.log(notificationRecord); + console.log(notification); - let buildMessagesPromise = (userDevices) => { - return new Promise(function (resolve) { - let messages = []; - - userDevices.forEach(async function (userDevice) { - messages.push({ - title: notificationRecord.title, - body: notificationRecord.body, - ttl: notificationRecord.ttl, - priority: notificationRecord.priority, - userId: userDevice.userId, - to: userDevice.token, - notificationId: notificationRecord.id, - data: notificationRecord.data, - _displayInForeground: true, - sound: 'default', - }); - }); - - resolve(messages) - }); - }; - - let getUserIds = async () => { if (userIds) { - return new Promise(function(resolve) { resolve(userIds) } ); + return new Promise(function(resolve) { resolve(userIds) } ); } else if (eventId && segment) { switch (segment) { //Todos los inscritos tanto invitados como libres @@ -182,46 +116,10 @@ const extraControllers = { } else { return handleErrorResponse(controllerOptions.MODULE_NAME, 'sendNotification', new Error('Missing event and segment'), res) } - } - - let getUserDevicesList = []; + } + + receipt = notificationService.sendNotification(notification, await getUserIds()); - Promise.all([ - saveNotificationPromise(notificationRecord), - getUserIds() - ]) - .then(function(result) { - notificationRecord = result[0]; - userIds = result[1]; - - userIds.forEach(function (userId) { - console.log(userId); - getUserDevicesList.push(getUserDevicesPromise(userId)); - }); - - return Promise.all(getUserDevicesList) - }).then(function (userDeviceList) { - console.log(userDeviceList); - let result = []; - userDeviceList.forEach(function (elements) { - elements.forEach(function (item) { - result.push(item) - }) - }); - return new Promise(function (resolve) { resolve(result); }); - }) - .then(disableInvalidUserDevicesPromise) - .then(buildMessagesPromise) - .then(sendNotificationsPromise) - .then(function({ messages, tickets }) { - let _saveStatus = saveResponseStatusPromise(messages, tickets); - let _disableDevices = disableUserDevicesWithErrorStatus(messages, tickets); - - return Promise.all([_saveStatus, _disableDevices]); - }) - .then(function (details) { - console.log(details); - }); } catch (error) { console.error(error); return handleErrorResponse(controllerOptions.MODULE_NAME, 'sendNotification', error, res) diff --git a/modules/notification/notification.service.js b/modules/notification/notification.service.js index 4b44c80..872f25c 100644 --- a/modules/notification/notification.service.js +++ b/modules/notification/notification.service.js @@ -1,14 +1,27 @@ const moment = require('moment'); -const { Expo } = require('expo-server-sdk'); -const { generateService, parseParamsToFindOptions } = require('../../helpers/service.helper'); -const models = require('../../core/models'); -// Create a new Expo SDK client -const expo = new Expo(); +const { generateService, parseParamsToFindOptions } = require('../../helpers/service.helper'); +const userDeviceService = require('./user_device.service'); +const notificationDetailService = require('./notification_detail.service'); +const pushHelper = require('../../helpers/push.helper'); +const models = require('../../core/models'); const extraMethods = { - createNotification: ({ date, title, body, ttl, priority, recipients, data, userId }) => { + createNotification: (data) => { + return { + date: data.date, + title: data.title, + body: data.message, + ttl: data.ttl, + priority: data.priority, + recipients: data.recipients, + data: data.data, + userId: data.userId, + } + }, + + saveNotification: ({ date, title, body, ttl, priority, recipients, data, userId }) => { console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>< { + sendNotification: (notification, userIds) => { - // The Expo push notification service accepts batches of notifications so - // that you don't need to send 1000 requests to send 1000 notifications. We - // recommend you batch your notifications to reduce the number of requests - // and to compress them (notifications with similar content will get - // compressed). + console.log('sendNofitication -----------------------------------------------'); + console.log(notification, userIds); - /** - * There is a limit on the number of push notifications (100) you can send at once.Use - * `chunkPushNotifications` to divide an array of push notification messages into appropriately - * sized chunks - */ + let getUserDevicesPromise = (userId) => userDeviceService.fetchAll({ params: { userId: userId } }, {}).then(function (result) { + return new Promise(function (resolve) { resolve(result.rows) }); + }); + let saveNotificationPromise = (notification) => extraMethods.saveNotification(notification); + let sendNotificationsPromise = (messages) => pushHelper.sendPushMessage(messages); + let disableUserDevicePromise = (token) => userDeviceService.update({ + params: { + token: token, + } + }, { valid: 0, invalidated: moment() }, {}); - // Later, after the Expo push notification service has delivered the - // notifications to Apple or Google (usually quickly, but allow the the service - // up to 30 minutes when under load), a "receipt" for each notification is - // created. The receipts will be available for at least a day; stale receipts - // are deleted. - // - // The ID of each receipt is sent back in the response "ticket" for each - // notification. In summary, sending a notification produces a ticket, which - // contains a receipt ID you later use to get the receipt. - // - // The receipts may contain error codes to which you must respond. In - // particular, Apple or Google may block apps that continue to send - // notifications to devices that have blocked notifications or have uninstalled - // your app. Expo does not control this policy and sends back the feedback from - // Apple and Google so you can handle it appropriately. + let disableInvalidUserDevicesPromise = (userDevices) => { + return new Promise(function (resolve) { + let _userDevices = []; + userDevices.forEach(async function (userDevice) { + console.log(userDevice); + if (!userDeviceService.isValidPushToken(userDevice.token)) { + await disableUserDevicePromise(userDevice.token); + } else { + _userDevices.push(userDevice); + } + }); - let chunks = expo.chunkPushNotifications(messages); - return { - messages, - tickets: await _sendPushNotificationsAsync(chunks) + resolve(_userDevices) + }); }; + + let disableUserDevicesWithErrorStatus = (messages, tickets) => { + return new Promise(function (resolve) { + tickets.forEach(async function (ticket, index) { + if ((ticket.status === 'error') && (ticket.details.error === 'DeviceNotRegistered')) { + await disableUserDevicePromise(messages[index].to) + } + }); + resolve(true); + }); + } + + let saveResponseStatusPromise = (messages, tickets) => notificationDetailService.saveNotificationDetails(messages, tickets); + + + let buildMessagesPromise = (userDevices) => { + return new Promise(function (resolve) { + let messages = []; + + userDevices.forEach(async function (userDevice) { + messages.push(pushHelper.createPushMessage({ + ...notification, + userId: userDevice.userId, + to: userDevice.token, + })); + }); + resolve(messages) + }); + }; + + + let getUserDevicesList = []; + + saveNotificationPromise(notification) + .then(function (notificationRecord) { + notification = notificationRecord.toJSON(); + userIds.forEach(function (userId) { + console.log(userId); + getUserDevicesList.push(getUserDevicesPromise(userId)); + }); + + return Promise.all(getUserDevicesList) + }).then(function (userDeviceList) { + console.log(userDeviceList); + let result = []; + userDeviceList.forEach(function (elements) { + elements.forEach(function (item) { + result.push(item) + }) + }); + return new Promise(function (resolve) { resolve(result); }); + }) + .then(disableInvalidUserDevicesPromise) + .then(buildMessagesPromise) + .then(sendNotificationsPromise) + .then(function ({ messages, tickets }) { + let _saveStatus = saveResponseStatusPromise(messages, tickets); + let _disableDevices = disableUserDevicesWithErrorStatus(messages, tickets); + + return Promise.all([_saveStatus, _disableDevices]); + }) + .then(function (details) { + console.log(details); + return details; + }); }, + + getNotificationsWithoutReceipt: async() => { }, @@ -78,67 +153,4 @@ const extraMethods = { module.exports = generateService(models.Notification, extraMethods); -const _sendPushNotificationsAsync = async function (chunks) { - return new Promise(async function (resolve) { - let tickets = []; - // Send the chunks to the Expo push notification service. There are - // different strategies you could use. A simple one is to send one chunk at a - // time, which nicely spreads the load out over time: - for (let chunk of chunks) { - try { - let ticketChunk = await expo.sendPushNotificationsAsync(chunk); - tickets.push(...ticketChunk); - - // NOTE: If a ticket contains an error code in ticket.details.error, you - // must handle it appropriately. The error codes are listed in the Expo - // documentation: - // https://docs.expo.io/versions/latest/guides/push-notifications#response-format - - } catch (error) { - console.error(error); - } - } - - resolve(tickets); - }); -}; - -const _getPushNotificationsResultAsync = async function (receiptIdChunks) { - return new Promise(async function (resolve) { - // Like sending notifications, there are different strategies you could use - // to retrieve batches of receipts from the Expo service. - - let result = []; - - console.log(receiptIdChunks); - - for (let chunk of receiptIdChunks) { - try { - let receipts = await expo.getPushNotificationReceiptsAsync(chunk); - console.log('hola', receipts); - - // The receipts specify whether Apple or Google successfully received the - // notification and information about an error, if one occurred. - for (let key in receipts) { - if (receipts[key].status === 'ok') { - result.push[receipts[key]]; - continue; - } else if (receipts[key].status === 'error') { - console.error(`There was an error sending a notification: ${receipts[key].message}`); - if (receipts[key].details && receipts[key].details.error) { - // The error codes are listed in the Expo documentation: - // https://docs.expo.io/versions/latest/guides/push-notifications#response-format - // You must handle the errors appropriately. - console.error(`The error code is ${receipts[key].details.error}`); - } - } - } - } catch (error) { - console.error(error); - } - } - - resolve(result); - }); -} diff --git a/modules/notification/notification_detail.service.js b/modules/notification/notification_detail.service.js index 3606f99..e53d4bb 100644 --- a/modules/notification/notification_detail.service.js +++ b/modules/notification/notification_detail.service.js @@ -7,6 +7,7 @@ const extraMethods = { saveNotificationDetails: async function (messages, tickets) { return new Promise(function (resolve) { messages.forEach(async function (message, index) { + console.log(message); let notification = models.NotificationDetail.build({ ...message, token: message.to, diff --git a/package.json b/package.json index 07a4980..20b61fe 100644 --- a/package.json +++ b/package.json @@ -66,6 +66,7 @@ "sanitize-filename": "^1.6.2", "sequelize": "^5.16.0", "sharp": "^0.23.0", + "tinytim": "^0.1.1", "unique-file-name": "^1.0.0", "vimeo": "^2.1.1", "vm": "^0.1.0", From ed86025b5fa876d0672cf08aa320d951142628bf Mon Sep 17 00:00:00 2001 From: david Date: Mon, 11 Nov 2019 18:20:59 +0100 Subject: [PATCH 09/14] . --- helpers/messages.json | 2 +- helpers/notification.helpers.js | 2 +- helpers/push.helper.js | 3 --- modules/events/event.controller.js | 8 +++++--- modules/notification/notification.controller.js | 8 +++----- modules/notification/notification.service.js | 8 +------- modules/notification/notification.validations.js | 2 +- modules/notification/notification_detail.service.js | 1 - 8 files changed, 12 insertions(+), 22 deletions(-) diff --git a/helpers/messages.json b/helpers/messages.json index a95822e..e7482c1 100644 --- a/helpers/messages.json +++ b/helpers/messages.json @@ -25,7 +25,7 @@ "push": { "confirmInvitation": { "title": "{{ congress }}", - "message": "Tu inscripción al congreso de {{ congress }} está confirmada.", + "body": "Tu inscripción al congreso de {{ congress }} está confirmada.", "data": { "type": "message", "title": "{{ congress }}", diff --git a/helpers/notification.helpers.js b/helpers/notification.helpers.js index 663c763..d62d646 100644 --- a/helpers/notification.helpers.js +++ b/helpers/notification.helpers.js @@ -7,7 +7,7 @@ const createNotification = (data) => { return { date: data.date, title: data.title, - body: data.message, + body: data.body, ttl: data.ttl, priority: data.priority ? data.priority : 'high', recipients: data.recipients, diff --git a/helpers/push.helper.js b/helpers/push.helper.js index 6a4fb8b..0d4e71d 100644 --- a/helpers/push.helper.js +++ b/helpers/push.helper.js @@ -4,9 +4,6 @@ const { Expo } = require('expo-server-sdk'); const expo = new Expo(); const createPushMessage = (data) => { - console.log('---------------------------------'); - console.log(data); - console.log('---------------------------------'); return { title: data.title, body: data.body, diff --git a/modules/events/event.controller.js b/modules/events/event.controller.js index fc6a6f2..ebf5cf1 100644 --- a/modules/events/event.controller.js +++ b/modules/events/event.controller.js @@ -10,7 +10,7 @@ const messages = require('../../helpers/messages.json'); const eventService = require('./event.service'); const eventReservationService = require('./events_reservations.service'); const eventInscriptionService = require('./events_inscriptions.service'); -const notificationController = require('../notification/notification.controller'); +const notificationService = require('../notification/notification.service'); const { extractParamsFromRequest, handleErrorResponse, handleResultResponse } = require('../../helpers/controller.helper'); @@ -286,11 +286,12 @@ console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>> { if (userIds) { diff --git a/modules/notification/notification.service.js b/modules/notification/notification.service.js index 872f25c..bdd6106 100644 --- a/modules/notification/notification.service.js +++ b/modules/notification/notification.service.js @@ -12,7 +12,7 @@ const extraMethods = { return { date: data.date, title: data.title, - body: data.message, + body: data.body, ttl: data.ttl, priority: data.priority, recipients: data.recipients, @@ -22,9 +22,6 @@ const extraMethods = { }, saveNotification: ({ date, title, body, ttl, priority, recipients, data, userId }) => { - console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>< Date: Mon, 11 Nov 2019 19:10:34 +0100 Subject: [PATCH 10/14] . --- helpers/notification.helpers.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/helpers/notification.helpers.js b/helpers/notification.helpers.js index d62d646..fd6110a 100644 --- a/helpers/notification.helpers.js +++ b/helpers/notification.helpers.js @@ -15,6 +15,9 @@ const createNotification = (data) => { userId: data.userId, _displayInForeground: true, sound: 'default', + android: { + channelId: 'lqdvi-messages' + } } } From 454e5ec749e8657eb2372b68d01d0d4a8266ec46 Mon Sep 17 00:00:00 2001 From: david Date: Wed, 13 Nov 2019 12:01:50 +0100 Subject: [PATCH 11/14] . --- core/passport.js | 9 +++------ modules/auth/user.model.js | 2 +- modules/auth/user.service.js | 15 +++++++-------- 3 files changed, 11 insertions(+), 15 deletions(-) diff --git a/core/passport.js b/core/passport.js index a80c5c5..8a247e8 100644 --- a/core/passport.js +++ b/core/passport.js @@ -116,12 +116,9 @@ passport.use('jwt', new CustomStrategy(async (req, done) => { let user = await authService.extraMethods.findUser({ id: result.id }); if (user) { user = user.toJSON(); - if (appVersion) { - if (user.app_version != appVersion){ - const result = userService._updateLastLoginAndVersionUser(user.id, appVersion); - user.app_version = appVersion; - } - } + const result = userService._updateLastLoginAndVersionUser(user.id, appVersion); + user.app_version = appVersion; + delete user.password; console.log('Logged in Successfully'); return done(null, user, { message: 'Logged in Successfully' }); diff --git a/modules/auth/user.model.js b/modules/auth/user.model.js index 1da9242..0af072e 100644 --- a/modules/auth/user.model.js +++ b/modules/auth/user.model.js @@ -77,7 +77,7 @@ module.exports = function (sequelize, DataTypes) { User.Comments = User.hasMany(models.Comment, { foreignKey: 'userId' }); User.EventsReservations = User.hasMany(models.EventReservation, { foreignKey: 'userId' }); User.EventsInscriptions = User.hasMany(models.EventInscription, { foreignKey: 'userId' }); - User.Questions = User.hasMany(models.EventQuestion, { foreignKey: 'userId', as: "questions", required: false, }); + User.Questions = User.hasMany(models.EventQuestion, { foreignKey: 'userId', as: "questions", required: false }); // User.InscriptionsValidate = User.hasMany(models.EventIncription, { foreignkey: 'validateUserId'}) //User.Reactions = User.hasMany(models.UserReaction, { foreignKey: 'UserId' }); diff --git a/modules/auth/user.service.js b/modules/auth/user.service.js index ea39c22..59823a5 100644 --- a/modules/auth/user.service.js +++ b/modules/auth/user.service.js @@ -26,14 +26,13 @@ const extraMethods = { }) }, - _updateLastLoginAndVersionUser: async (Id, appVersion) => { - return models.User.update ( - { app_version : appVersion, - lastlogin: moment().utc() }, - { - where: { id: Id} - }, - ); + _updateLastLoginAndVersionUser: async (id, appVersion) => { + return models.User.update ({ + app_version : appVersion, + lastlogin: moment().utc() + }, { + where: { id: id } + }); }, _getOrCreateUser: async (dataUser) => { From db26c250c6d824e382bca3acb7825888df1eb000 Mon Sep 17 00:00:00 2001 From: david Date: Wed, 13 Nov 2019 12:14:45 +0100 Subject: [PATCH 12/14] . --- helpers/notification.helpers.js | 5 ----- helpers/push.helper.js | 3 +++ 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/helpers/notification.helpers.js b/helpers/notification.helpers.js index fd6110a..8fde4a1 100644 --- a/helpers/notification.helpers.js +++ b/helpers/notification.helpers.js @@ -13,11 +13,6 @@ const createNotification = (data) => { recipients: data.recipients, data: data.data, userId: data.userId, - _displayInForeground: true, - sound: 'default', - android: { - channelId: 'lqdvi-messages' - } } } diff --git a/helpers/push.helper.js b/helpers/push.helper.js index 0d4e71d..a4e201b 100644 --- a/helpers/push.helper.js +++ b/helpers/push.helper.js @@ -15,6 +15,9 @@ const createPushMessage = (data) => { data: data.data, _displayInForeground: true, sound: 'default', + android: { + channelId: 'lqdvi-messages' + } } }; From 39a449e894dbe1f55bcdf40dd552c5b63d6a5862 Mon Sep 17 00:00:00 2001 From: david Date: Wed, 13 Nov 2019 12:21:10 +0100 Subject: [PATCH 13/14] . --- helpers/notification.helpers.js | 2 -- helpers/push.helper.js | 6 ++++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/helpers/notification.helpers.js b/helpers/notification.helpers.js index 8fde4a1..c61abc7 100644 --- a/helpers/notification.helpers.js +++ b/helpers/notification.helpers.js @@ -28,8 +28,6 @@ createNotificationValidatedInscription = (inscription) => { ...jsonNotification, date: moment(), priority: "high", - _displayInForeground: true, - sound: 'default', recipients: { "userIds": [ inscription.user.id, diff --git a/helpers/push.helper.js b/helpers/push.helper.js index a4e201b..557900b 100644 --- a/helpers/push.helper.js +++ b/helpers/push.helper.js @@ -4,7 +4,7 @@ const { Expo } = require('expo-server-sdk'); const expo = new Expo(); const createPushMessage = (data) => { - return { + const pushMessage = { title: data.title, body: data.body, ttl: data.ttl, @@ -18,7 +18,9 @@ const createPushMessage = (data) => { android: { channelId: 'lqdvi-messages' } - } + }; + console.log(pushMessage); + return pushMessage; }; From 392f66b5749a23e093919edc9d9d2d99e0d97d97 Mon Sep 17 00:00:00 2001 From: david Date: Wed, 13 Nov 2019 12:23:55 +0100 Subject: [PATCH 14/14] . --- helpers/push.helper.js | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/helpers/push.helper.js b/helpers/push.helper.js index 557900b..f992ac1 100644 --- a/helpers/push.helper.js +++ b/helpers/push.helper.js @@ -15,9 +15,7 @@ const createPushMessage = (data) => { data: data.data, _displayInForeground: true, sound: 'default', - android: { - channelId: 'lqdvi-messages' - } + channelId: 'lqdvi-messages' }; console.log(pushMessage); return pushMessage;