-
Notifications
You must be signed in to change notification settings - Fork 16
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
Migrated notifications to Firebase #37
Closed
eswarasai
wants to merge
4
commits into
snapshot-labs:master
from
eswarasai:feature/firebase-notifications
Closed
Changes from all commits
Commits
Show all changes
4 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
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -4,7 +4,6 @@ dist | |
build | ||
.env | ||
|
||
|
||
# Remove some common IDE working directories | ||
.idea | ||
.vscode |
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 @@ | ||
v16.17.0 | ||
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
This file was deleted.
Oops, something went wrong.
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,142 @@ | ||
import snapshot from '@snapshot-labs/snapshot.js'; | ||
import { initializeApp, cert, ServiceAccount } from 'firebase-admin/app'; | ||
import { getMessaging } from 'firebase-admin/messaging'; | ||
|
||
import db from './mysql'; | ||
import { getProposal } from './proposal'; | ||
|
||
const { FIREBASE_PROJECT_ID, FIREBASE_CLIENT_EMAIL, FIREBASE_PRIVATE_KEY, HUB_URL } = process.env; | ||
|
||
const firebaseApp = initializeApp({ | ||
credential: cert({ | ||
projectId: FIREBASE_PROJECT_ID, | ||
clientEmail: FIREBASE_CLIENT_EMAIL, | ||
privateKey: (FIREBASE_PRIVATE_KEY || '').replace(/\\n/g, '\n') | ||
} as ServiceAccount) | ||
}); | ||
const messaging = getMessaging(firebaseApp); | ||
const hubURL = HUB_URL || 'https://hub.snapshot.org'; | ||
|
||
async function getUserSpaces(user: string) { | ||
let userSpaces: { [key: string]: any } = []; | ||
const query = { | ||
follows: { | ||
__args: { | ||
where: { follower: user } | ||
}, | ||
space: { id: true } | ||
} | ||
}; | ||
try { | ||
const result = await snapshot.utils.subgraphRequest(`${hubURL}/graphql`, query); | ||
userSpaces = result.follows || []; | ||
} catch (error) { | ||
console.log('[notifications] Snapshot hub error:', error); | ||
} | ||
return userSpaces.map(follow => follow.space.id); | ||
} | ||
|
||
async function toggleTopicSubscription( | ||
token: string, | ||
owner: string, | ||
space: string, | ||
unsubscribe: boolean | ||
) { | ||
try { | ||
if (unsubscribe) { | ||
await messaging.unsubscribeFromTopic(token, space); | ||
} else { | ||
await messaging.subscribeToTopic(token, space); | ||
} | ||
|
||
console.log( | ||
`[notifications] Successfully ${ | ||
unsubscribe ? 'un' : '' | ||
}subscribed user: ${owner} to space: ${space}` | ||
); | ||
} catch (e) { | ||
console.error( | ||
`[notifications] Error ${unsubscribe ? 'un' : ''}subscribing user ${owner} to space ${space}`, | ||
e | ||
); | ||
} | ||
} | ||
|
||
export async function isTokenValid(token: string, owner: string) { | ||
// TODO: Check token validity in Firebase | ||
const device = await db.queryAsync( | ||
'SELECT * FROM device_tokens WHERE token = ? AND owner = ? LIMIT 1', | ||
[token, owner] | ||
); | ||
return Boolean(device.length); | ||
} | ||
|
||
export async function sendPushNotification(event) { | ||
const proposal = await getProposal(event.id.replace('proposal/', '')); | ||
if (!proposal) { | ||
console.log('[notifications] Proposal not found', event.id); | ||
return; | ||
} | ||
|
||
messaging | ||
.sendToTopic(event.space, { | ||
notification: { | ||
title: event.space, | ||
body: proposal.title, | ||
clickAction: `${process.env.SNAPSHOT_URI}/#/${event.space}/${event.id}` | ||
} | ||
}) | ||
.then(response => { | ||
console.log('Notification sent successfully!', response.messageId); | ||
}) | ||
.catch(error => console.error(error.errorInfo.code)); | ||
} | ||
|
||
export async function subscribeUser(token: string, owner: string) { | ||
try { | ||
const ts = parseInt((Date.now() / 1e3).toFixed()); | ||
await db.queryAsync( | ||
`INSERT INTO device_tokens (token, owner, created, updated) VALUES (?, ?, ?, ?)`, | ||
[token, owner, ts, ts] | ||
); | ||
|
||
const userSpaces = await getUserSpaces(owner); | ||
userSpaces.map(async space => toggleTopicSubscription(token, owner, space, false)); | ||
} catch (e) { | ||
console.error('[notifications] subscribeUser:', e); | ||
} | ||
} | ||
|
||
export async function unsubscribeUser(token: string, owner: string) { | ||
try { | ||
await db.queryAsync('DELETE FROM device_tokens WHERE token = ? AND owner = ? LIMIT 1', [ | ||
token, | ||
owner | ||
]); | ||
|
||
const userSpaces = await getUserSpaces(owner); | ||
userSpaces.map(async space => toggleTopicSubscription(token, owner, space, true)); | ||
} catch (e) { | ||
console.error('[notifications] unsubscribeUser:', e); | ||
} | ||
} | ||
|
||
export async function toggleSpaceNotification( | ||
owner: string, | ||
spaceId: string, | ||
unsubscribe: boolean | ||
) { | ||
try { | ||
const deviceTokens = await db.queryAsync(`SELECT token FROM device_tokens WHERE owner = ?`, [ | ||
owner | ||
]); | ||
|
||
if (deviceTokens.length !== 0) { | ||
deviceTokens.map(async deviceToken => | ||
toggleTopicSubscription(deviceToken.token, owner, spaceId, unsubscribe) | ||
); | ||
} | ||
} catch (e) { | ||
console.error('[notifications] toggleSpaceNotification:', e); | ||
} | ||
} |
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
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.
Any reason to force v16 here?
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.
Just to keep dev env consistent across the repos. Updated the same for Snapshot UI repo as well.