-
Notifications
You must be signed in to change notification settings - Fork 0
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
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} | ||
} | ||
) { | ||
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; | ||
} | ||
}; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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