-
Notifications
You must be signed in to change notification settings - Fork 15
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Add user notification tokens model and service method
- Loading branch information
Showing
5 changed files
with
207 additions
and
16 deletions.
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 |
---|---|---|
@@ -0,0 +1,60 @@ | ||
import { DataTypes, ModelDefined, Sequelize } from 'sequelize'; | ||
|
||
export interface UserNotificationTokenAttributes { | ||
id: string; | ||
userId: string; | ||
token: string; | ||
type: 'macos' | 'android' | 'ios'; | ||
createdAt: Date; | ||
updatedAt: Date; | ||
} | ||
|
||
export type UserNotificationTokenModel = ModelDefined<UserNotificationTokenAttributes, UserNotificationTokenAttributes>; | ||
|
||
export default (database: Sequelize): UserNotificationTokenModel => { | ||
const UserNotificationToken: UserNotificationTokenModel = database.define( | ||
'user_notification_tokens', | ||
{ | ||
id: { | ||
type: DataTypes.UUID, | ||
primaryKey: true, | ||
defaultValue: DataTypes.UUIDV4, | ||
}, | ||
userId: { | ||
type: DataTypes.STRING(36), | ||
allowNull: false, | ||
references: { | ||
model: 'users', | ||
key: 'uuid', | ||
}, | ||
}, | ||
token: { | ||
type: DataTypes.STRING, | ||
allowNull: false, | ||
}, | ||
type: { | ||
type: DataTypes.ENUM('macos', 'android', 'ios'), | ||
allowNull: false, | ||
}, | ||
createdAt: { | ||
field: 'created_at', | ||
type: DataTypes.DATE, | ||
allowNull: false, | ||
defaultValue: DataTypes.NOW, | ||
}, | ||
updatedAt: { | ||
field: 'updated_at', | ||
type: DataTypes.DATE, | ||
allowNull: false, | ||
defaultValue: DataTypes.NOW, | ||
}, | ||
}, | ||
{ | ||
tableName: 'user_notification_tokens', | ||
timestamps: true, | ||
underscored: true, | ||
}, | ||
); | ||
|
||
return UserNotificationToken; | ||
}; |
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 |
---|---|---|
@@ -0,0 +1,113 @@ | ||
import * as http2 from 'http2'; | ||
import jwt, { JwtHeader } from 'jsonwebtoken'; | ||
import Logger from '../../lib/logger'; | ||
|
||
export default class Apn { | ||
private static instance: Apn; | ||
private client: http2.ClientHttp2Session; | ||
private readonly maxReconnectAttempts = 3; | ||
private reconnectAttempts = 0; | ||
private reconnectDelay = 1000; | ||
private readonly bundleId = process.env.APN_BUNDLE_ID; | ||
|
||
private jwt: string | null = null; | ||
private jwtGeneratedAt = 0; | ||
|
||
constructor() { | ||
this.client = this.connectToAPN(); | ||
} | ||
|
||
static getInstance(): Apn { | ||
if (!Apn.instance) { | ||
Apn.instance = new Apn(); | ||
} | ||
return Apn.instance; | ||
} | ||
|
||
private connectToAPN(): http2.ClientHttp2Session { | ||
const apnSecret = process.env.APN_SECRET; | ||
const apnKeyId = process.env.APN_KEY_ID; | ||
const apnTeamId = process.env.APN_TEAM_ID; | ||
|
||
if (!apnSecret || !apnKeyId || !apnTeamId) { | ||
Logger.getInstance().warn('APN env variables must be defined'); | ||
} | ||
|
||
const client = http2.connect(process.env.APN_URL as string, {}); | ||
|
||
client.on('error', (err) => { | ||
Logger.getInstance().error('APN connection error', err); | ||
}); | ||
client.on('close', () => { | ||
Logger.getInstance().warn('APN connection was closed'); | ||
this.handleReconnect(); | ||
}); | ||
client.on('connect', () => { | ||
Logger.getInstance().info('Connected to APN'); | ||
}); | ||
|
||
return client; | ||
} | ||
|
||
private generateJwt(): string { | ||
if (this.jwt && Date.now() - this.jwtGeneratedAt < 3600) { | ||
return this.jwt; | ||
} | ||
|
||
this.jwt = jwt.sign( | ||
{ | ||
iss: process.env.APN_TEAM_ID, | ||
iat: Math.floor(Date.now() / 1000), | ||
}, | ||
process.env.APN_SECRET as string, | ||
{ | ||
algorithm: 'ES256', | ||
header: { | ||
alg: 'ES256', | ||
kid: process.env.APN_KEY_ID, | ||
} as JwtHeader, | ||
}, | ||
); | ||
|
||
this.jwtGeneratedAt = Date.now(); | ||
|
||
return this.jwt; | ||
} | ||
|
||
private handleReconnect() { | ||
if (this.reconnectAttempts < this.maxReconnectAttempts) { | ||
setTimeout(() => { | ||
Logger.getInstance().info(`Attempting to reconnect to APN (#${this.reconnectAttempts + 1})`); | ||
this.connectToAPN(); | ||
this.reconnectAttempts++; | ||
}, this.reconnectDelay * Math.pow(2, this.reconnectAttempts)); | ||
} else { | ||
Logger.getInstance().error('Maximum APN reconnection attempts reached'); | ||
} | ||
} | ||
|
||
public sendNotification(payload: Record<string, any>, topic?: string): void { | ||
const headers = { | ||
'apns-topic': topic ?? `${this.bundleId}.pushkit.fileprovider`, | ||
authorization: `bearer ${this.generateJwt()}`, | ||
}; | ||
|
||
const options = { | ||
':method': 'POST', | ||
':path': `/3/device/${payload.deviceToken}`, | ||
':scheme': 'https', | ||
':authority': 'api.push.apple.com', | ||
'content-type': 'application/json', | ||
}; | ||
|
||
const req = this.client.request({ ...options, ...headers }); | ||
|
||
req.setEncoding('utf8'); | ||
req.write(JSON.stringify(payload)); | ||
req.end(); | ||
|
||
req.on('error', (err) => { | ||
Logger.getInstance().error('APN request error', err); | ||
}); | ||
} | ||
} |