Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

348 - endpoint to send push notification #366

Merged
merged 1 commit into from
Aug 4, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions packages/api/src/controllers/v2/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,17 @@ class UserController {
standardResponse(res, 400, false, '', { error: e.message })
);
};

public sendPushNotifications = (req: Request, res: Response) => {
const { country, communities, title, body, data } = req.body;

this.userService
.sendPushNotifications(title, body, country, communities, data)
.then((r) => standardResponse(res, 200, true, r))
.catch((e) =>
standardResponse(res, 400, false, '', { error: e.message })
);
};
}

export default UserController;
9 changes: 8 additions & 1 deletion packages/api/src/routes/v2/user.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Router } from 'express';

import UserController from '../../controllers/v2/user';
import { authenticateToken } from '../../middlewares';
import { authenticateToken, adminAuthentication } from '../../middlewares';
import userValidators from '../../validators/user';

export default (app: Router): void => {
Expand Down Expand Up @@ -495,4 +495,11 @@ export default (app: Router): void => {
* - "write:modify":
*/
route.get('/:address', authenticateToken, userController.findBy);

route.post(
'/push-notifications',
adminAuthentication,
userValidators.sendPushNotifications,
userController.sendPushNotifications
);
};
11 changes: 11 additions & 0 deletions packages/api/src/validators/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,16 @@ const readNotifications = celebrate({
}),
});

const sendPushNotifications = celebrate({
body: defaultSchema.object({
country: Joi.string().optional(),
communities: Joi.array().items(Joi.number().required()).optional(),
title: Joi.string().required(),
body: Joi.string().required(),
data: Joi.object().optional(),
}),
});

//

const reportv1 = celebrate({
Expand Down Expand Up @@ -207,4 +217,5 @@ export default {
subscribeNewsletter,
saveSurvey,
readNotifications,
sendPushNotifications,
};
89 changes: 87 additions & 2 deletions packages/core/src/services/app/user/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Op, WhereOptions } from 'sequelize';
import { ethers } from 'ethers';
import { Op } from 'sequelize';

import config from '../../../config';
import { models, sequelize } from '../../../database';
Expand All @@ -11,10 +12,12 @@ import {
AppUser,
} from '../../../interfaces/app/appUser';
import { ProfileContentStorage } from '../../../services/storage';
import { getAllBeneficiaries } from '../../../subgraph/queries/beneficiary';
import { getUserRoles } from '../../../subgraph/queries/user';
import { BaseError } from '../../../utils/baseError';
import { generateAccessToken } from '../../../utils/jwt';
import { Logger } from '../../../utils/logger';
import { sendPushNotification } from '../../../utils/util';
import UserLogService from './log';

export default class UserService {
Expand Down Expand Up @@ -402,7 +405,10 @@ export default class UserService {
}
);
if (updated[0] === 0) {
throw new Error('notifications were not updated!');
throw new BaseError(
'UPDATE_FAILED',
'notifications were not updated!'
);
}
return true;
}
Expand All @@ -416,6 +422,85 @@ export default class UserService {
});
}

public async sendPushNotifications(
title: string,
body: string,
country?: string,
communitiesIds?: number[],
data?: any
) {
if (country) {
const users = await models.appUser.findAll({
attributes: ['pushNotificationToken'],
where: {
country,
pushNotificationToken: {
[Op.not]: null,
},
},
});
users.forEach((user) => {
sendPushNotification(
user.address,
title,
body,
data,
user.pushNotificationToken
);
});
} else if (communitiesIds && communitiesIds.length) {
const communities = await models.community.findAll({
attributes: ['contractAddress'],
where: {
id: {
[Op.in]: communitiesIds,
},
contractAddress: {
[Op.not]: null,
},
},
});
const beneficiaryAddress: string[] = [];

// get beneficiaries
for (let index = 0; index < communities.length; index++) {
const community = communities[index];
const beneficiaries = await getAllBeneficiaries(
community.contractAddress!
);
beneficiaries.forEach((beneficiary) => {
beneficiaryAddress.push(
ethers.utils.getAddress(beneficiary.address)
);
});
}
// get users
const users = await models.appUser.findAll({
attributes: ['pushNotificationToken'],
where: {
address: {
[Op.in]: beneficiaryAddress,
},
pushNotificationToken: {
[Op.not]: null,
},
},
});

users.forEach((user) => {
sendPushNotification(
user.address,
title,
body,
data,
user.pushNotificationToken
);
});
} else {
throw new BaseError('INVALID_OPTION', 'invalid option');
}
}

private async _overwriteUser(user: AppUserCreationAttributes) {
try {
const usersToInactive = await models.appUser.findAll({
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/subgraph/queries/beneficiary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export const getAllBeneficiaries = async (
lastClaimAt_gte: ${aMonthAgo.getTime() / 1000}
}
) {
address
lastClaimAt
preLastClaimAt
claims
Expand Down
17 changes: 9 additions & 8 deletions packages/core/src/utils/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -182,16 +182,17 @@ export async function sendPushNotification(
userAddress: string,
title: string,
body: string,
data: any
data: any,
pushNotificationToken?: string | null
): Promise<boolean> {
const user = await UserService.get(userAddress);
if (
user !== null &&
user.pushNotificationToken !== null &&
user.pushNotificationToken.length > 0
) {
if (!pushNotificationToken) {
const user = await UserService.get(userAddress);
if (!user) return false;
pushNotificationToken = user.pushNotificationToken;
}
if (pushNotificationToken !== null && pushNotificationToken.length > 0) {
const message = {
to: user.pushNotificationToken,
to: pushNotificationToken,
sound: 'default',
title,
body,
Expand Down