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

[IPCT1-743] - use the graph subscriptions to add notification #320

Merged
merged 2 commits into from
Jul 6, 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
5 changes: 4 additions & 1 deletion packages/core/src/interfaces/app/appNotification.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,10 @@
*/

export enum NotificationType {
STORY_LIKED
STORY_LIKED,
BENEFICIARY_ADDED,
MANAGER_ADDED,
COMMUNITY_CREATED,
}

export interface AppNotification {
Expand Down
2 changes: 2 additions & 0 deletions packages/worker/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
},
"dependencies": {
"@impactmarket/core": "1.0.0",
"apollo-link-ws": "1.0.20",
"@slack/web-api": "6.5.0",
"axios": "0.24.0",
"bignumber.js": "9.0.0",
Expand All @@ -31,6 +32,7 @@
"module-alias": "2.2.2",
"node-schedule": "2.0.0",
"sequelize": "6.10.0",
"subscriptions-transport-ws": "0.11.0",
"ts-node": "10.4.0",
"typescript": "4.5.2"
}
Expand Down
3 changes: 3 additions & 0 deletions packages/worker/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import 'module-alias/register';
import jobsLoader from './jobs';
import { communitySubscription, userActivitySubscription } from './subscription';

jobsLoader();
communitySubscription();
userActivitySubscription();
310 changes: 310 additions & 0 deletions packages/worker/src/subscription.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,310 @@
import {
database,
config,
interfaces,
subgraph,
utils,
} from '@impactmarket/core';
import { execute } from 'apollo-link';
import { WebSocketLink } from 'apollo-link-ws';
import { ethers } from 'ethers';
import gql from 'graphql-tag';
import { Op } from 'sequelize';
import { SubscriptionClient } from 'subscriptions-transport-ws';
import ws from 'ws';

const getWsClient = function (wsurl) {
const client = new SubscriptionClient(wsurl, { reconnect: true }, ws);
return client;
};

const createSubscriptionObservable = (wsurl, query, variables) => {
const link = new WebSocketLink(getWsClient(wsurl));
return execute(link, { query, variables });
};

export const communitySubscription = async () => {
try {
const COMMUNITY_QUERY = gql`
subscription {
communityEntities(
orderBy: startDayId
orderDirection: desc
where: {
startDayId_gte: ${
(new Date().getTime() / 1000 / 86400) | 0
}
}
Comment on lines +33 to +37
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

won't this make users get notified twice if the server is restarted?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

as there is no DateTime field, only the day, just below there is a check to see if there is already a notification created for the community, just to avoid a situation like this of the server restarting and users being notified of the communities opened today

) {
id
startDayId
}
}
`;

const subscriptionClient = createSubscriptionObservable(
config.subgraphUrl, // GraphQL endpoint
COMMUNITY_QUERY, // Subscription query
{} // Query variables
);
subscriptionClient.subscribe(
async (eventData) => {
utils.Logger.info(
`Received event: ${JSON.stringify(eventData, null, 2)}`
);
const communityEntities: [
{
id: string;
startDayId: number;
}
] = eventData.data?.communityEntities;
if (communityEntities && communityEntities.length > 0) {
communityEntities.forEach(async (communityEntitiy) => {
const today = (new Date().getTime() / 1000 / 86400) | 0;

if (communityEntitiy.startDayId === today && !!communityEntitiy.id) {
try {
const community =
await database.models.community.findOne({
attributes: ['id', 'ambassadorAddress'],
where: {
contractAddress:
ethers.utils.getAddress(
communityEntitiy.id
),
},
});

if (community && community.ambassadorAddress) {
const notification =
await database.models.appNotification.findOne(
{
where: {
type: interfaces.app
.appNotification
.NotificationType
.COMMUNITY_CREATED,
params: {
communityId:
community.id,
},
},
}
);

if (!notification) {
const user =
await database.models.appUser.findOne(
{
attributes: ['id'],
where: {
address:
community.ambassadorAddress,
},
}
);

await database.models.appNotification.create(
{
type: interfaces.app
.appNotification
.NotificationType
.COMMUNITY_CREATED,
userId: user!.id,
params: {
communityId: community.id,
},
}
);
}
}
} catch (error) {
utils.Logger.error(
'Add notification error: ',
error
);
}
}
});
}
},
(err) => {
utils.Logger.error('Subscribe Error: ', err);
}
);
} catch (error) {
utils.Logger.error('Error: ', error);
}
};

export const userActivitySubscription = async () => {
try {
const USER_ACTIVITY_QUERY = gql`
subscription {
userActivityEntities(
orderBy: timestamp
orderDirection: desc
where:{
activity: ADDED
timestamp_gt: ${(new Date().getTime() / 1000) | 0}
}
) {
user
community {
id
}
timestamp
}
}
`;

const subscriptionClient = createSubscriptionObservable(
config.subgraphUrl, // GraphQL endpoint
USER_ACTIVITY_QUERY, // Subscription query
{} // Query variables
);
subscriptionClient.subscribe(
async (eventData) => {
utils.Logger.info(
`Received event: ${JSON.stringify(eventData, null, 2)}`
);
const userActivityEntities: [
{
user: string;
community: {
id: string;
};
timestamp: number;
}
] = eventData.data?.userActivityEntities;

if (userActivityEntities && userActivityEntities.length > 0) {
userActivityEntities.forEach(async (userActivity) => {
const date = new Date();
date.setMinutes(date.getMinutes() - 2);

if (userActivity.timestamp * 1000 > date.getTime() && !!userActivity.user) {
try {
const user =
await database.models.appUser.findOne({
attributes: ['id'],
where: {
address: ethers.utils.getAddress(
userActivity.user
),
},
});

const userRole = await getUserRoles(
userActivity.user,
userActivity.timestamp
);
if (user && userRole) {
const notification =
await database.models.appNotification.findOne(
{
where: {
userId: user.id,
type: userRole,
createdAt: {
[Op.gte]: new Date(
userActivity.timestamp *
1000
),
},
},
}
);
if (!notification) {
const community =
await database.models.community.findOne(
{
attributes: ['id'],
where: {
contractAddress:
ethers.utils.getAddress(
userActivity
.community
.id
),
},
}
);
await database.models.appNotification.create(
{
type: userRole,
userId: user.id,
params: {
communityId: community!.id,
},
}
);
}
}
} catch (error) {
utils.Logger.error(
'Add notification error: ',
error
);
}
}
});
}
},
(err) => {
utils.Logger.error('Subscribe error: ', err);
}
);
} catch (error) {
utils.Logger.error('Error: ', error);
}
};

const getUserRoles = async (address: string, timestamp: number) => {
const ENTITIES_QUERY = gql`
{
managerEntities(
where: {
address: "${address}"
since: ${timestamp}
}
){
id
state
address
since
}
beneficiaryEntities(
where: {
address: "${address}"
since: ${timestamp}
}
){
id
state
address
since
}
}
`;

const queryDAOResult = await subgraph.config.clientDAO.query({
query: ENTITIES_QUERY,
fetchPolicy: 'no-cache',
});

if (
queryDAOResult.data?.beneficiaryEntities &&
queryDAOResult.data.beneficiaryEntities.length > 0
) {
return interfaces.app.appNotification.NotificationType
.BENEFICIARY_ADDED;
} else if (
queryDAOResult.data.managerEntities &&
queryDAOResult.data.managerEntities.length > 0
) {
return interfaces.app.appNotification.NotificationType.MANAGER_ADDED;
} else {
return null;
}
};
Loading