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

Chore: Convert push endpoints to TS #25347

Merged
merged 3 commits into from
May 5, 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
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,22 @@ import { appTokensCollection } from '../../../push/server';
import { API } from '../api';
import PushNotification from '../../../push-notifications/server/lib/PushNotification';
import { canAccessRoom } from '../../../authorization/server/functions/canAccessRoom';
import { Users, Messages, Rooms } from '../../../models/server';
import { Users, Rooms } from '../../../models/server';
import { Messages } from '../../../models/server/raw';

API.v1.addRoute(
'push.token',
{ authRequired: true },
{
post() {
const { type, value, appName } = this.bodyParams;
let { id } = this.bodyParams;
const { id, type, value, appName } = this.bodyParams;

if (id && typeof id !== 'string') {
throw new Meteor.Error('error-id-param-not-valid', 'The required "id" body param is invalid.');
} else {
id = Random.id();
}

const deviceId = id || Random.id();

if (!type || (type !== 'apn' && type !== 'gcm')) {
throw new Meteor.Error('error-type-param-not-valid', 'The required "type" body param is missing or invalid.');
}
Expand All @@ -34,15 +34,14 @@ API.v1.addRoute(
throw new Meteor.Error('error-appName-param-not-valid', 'The required "appName" body param is missing or invalid.');
}

let result;
Meteor.runAsUser(this.userId, () => {
result = Meteor.call('raix:push-update', {
id,
const result = Meteor.runAsUser(this.userId, () =>
Meteor.call('raix:push-update', {
id: deviceId,
token: { [type]: value },
appName,
userId: this.userId,
});
});
}),
);

return API.v1.success({ result });
},
Expand Down Expand Up @@ -78,7 +77,7 @@ API.v1.addRoute(
'push.get',
{ authRequired: true },
{
get() {
async get() {
const params = this.requestParams();
check(
params,
Expand All @@ -92,7 +91,7 @@ API.v1.addRoute(
throw new Error('error-user-not-found');
}

const message = Messages.findOneById(params.id);
const message = await Messages.findOneById(params.id);
if (!message) {
throw new Error('error-message-not-found');
}
Expand All @@ -106,7 +105,7 @@ API.v1.addRoute(
throw new Error('error-not-allowed');
}

const data = PushNotification.getNotificationForMessageId({ receiver, room, message });
const data = await PushNotification.getNotificationForMessageId({ receiver, room, message });

return API.v1.success({ data });
},
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Meteor } from 'meteor/meteor';
import { IMessage, IPushNotificationConfig, IRoom, IUser } from '@rocket.chat/core-typings';

import { Push } from '../../../push/server';
import { settings } from '../../../settings/server';
Expand All @@ -9,19 +10,62 @@ import { replaceMentionedUsernamesWithFullNames, parseMessageTextPerUser } from
import { callbacks } from '../../../../lib/callbacks';
import { getPushData } from '../../../lib/server/functions/notifications/mobile';

type PushNotificationData = {
rid: string;
uid: string;
mid: string;
roomName: string;
username: string;
message: string;
payload: Record<string, any>;
badge: number;
category: string;
};

type GetNotificationConfigParam = PushNotificationData & {
idOnly: boolean;
};

type NotificationPayload = {
message: IMessage;
notification: IPushNotificationConfig;
};

function hash(str: string): number {
let hash = 0;
let i = str.length;

while (i) {
hash = (hash << 5) - hash + str.charCodeAt(--i);
hash &= hash; // Convert to 32bit integer
}
return hash;
}

export class PushNotification {
getNotificationId(roomId) {
getNotificationId(roomId: string): number {
const serverId = settings.get('uniqueID');
return this.hash(`${serverId}|${roomId}`); // hash
return hash(`${serverId}|${roomId}`); // hash
}

getNotificationConfig({ rid, uid: userId, mid: messageId, roomName, username, message, payload, badge = 1, category, idOnly = false }) {
private getNotificationConfig({
rid,
uid: userId,
mid: messageId,
roomName,
username,
message,
payload,
badge = 1,
category,
idOnly = false,
}: GetNotificationConfigParam): IPushNotificationConfig {
const title = idOnly ? '' : roomName || username;

// message is being redacted already by 'getPushData' if idOnly is true
const text = !idOnly && roomName !== '' ? `${username}: ${message}` : message;

const config = {
const config: IPushNotificationConfig = {
from: 'push',
badge,
sound: 'default',
Expand All @@ -32,7 +76,7 @@ export class PushNotification {
host: Meteor.absoluteUrl(),
messageId,
notificationType: idOnly ? 'message-id-only' : 'message',
...(idOnly || { rid, ...payload }),
...(!idOnly && { rid, ...payload }),
},
userId,
notId: this.getNotificationId(rid),
Expand All @@ -51,19 +95,8 @@ export class PushNotification {
return config;
}

hash(str) {
let hash = 0;
let i = str.length;

while (i) {
hash = (hash << 5) - hash + str.charCodeAt(--i);
hash &= hash; // Convert to 32bit integer
}
return hash;
}

send({ rid, uid, mid, roomName, username, message, payload, badge = 1, category }) {
const idOnly = settings.get('Push_request_content_from_server');
send({ rid, uid, mid, roomName, username, message, payload, badge = 1, category }: PushNotificationData): void {
const idOnly = settings.get<boolean>('Push_request_content_from_server');
const config = this.getNotificationConfig({
rid,
uid,
Expand All @@ -77,34 +110,41 @@ export class PushNotification {
idOnly,
});

// eslint-disable-next-line @typescript-eslint/camelcase
metrics.notificationsSent.inc({ notification_type: 'mobile' });
return Push.send(config);
Push.send(config);
}

getNotificationForMessageId({ receiver, message, room }) {
async getNotificationForMessageId({
receiver,
message,
room,
}: {
receiver: IUser;
message: IMessage;
room: IRoom;
}): Promise<NotificationPayload> {
const sender = Users.findOne(message.u._id, { fields: { username: 1, name: 1 } });
if (!sender) {
throw new Error('Message sender not found');
}

let notificationMessage = callbacks.run('beforeSendMessageNotifications', message.msg);
if (message.mentions?.length > 0 && settings.get('UI_Use_Real_Name')) {
if (message.mentions && Object.keys(message.mentions).length > 0 && settings.get('UI_Use_Real_Name')) {
notificationMessage = replaceMentionedUsernamesWithFullNames(message.msg, message.mentions);
}
notificationMessage = parseMessageTextPerUser(notificationMessage, message, receiver);

const pushData = Promise.await(
getPushData({
room,
message,
userId: receiver._id,
receiver,
senderUsername: sender.username,
senderName: sender.name,
notificationMessage,
shouldOmitMessage: false,
}),
);
const pushData = await getPushData({
room,
message,
userId: receiver._id,
receiver,
senderUsername: sender.username,
senderName: sender.name,
notificationMessage,
shouldOmitMessage: false,
});

return {
message,
Expand Down
18 changes: 18 additions & 0 deletions packages/core-typings/src/IPushNotificationConfig.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
export interface IPushNotificationConfig {
from: string;
badge: number;
sound: string;
priority: number;
title: string;
text: string;
payload: Record<string, any>;
userId: string;
notId: number;
gcm: {
style: string;
image: string;
};
apn?: {
category: string;
};
}
12 changes: 12 additions & 0 deletions packages/core-typings/src/IPushToken.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import type { IRocketChatRecord } from './IRocketChatRecord';

export type IPushTokenTypes = 'gcm' | 'apn';

export interface IPushToken extends IRocketChatRecord {
token: Record<IPushTokenTypes, string>;
appName: string;
userId: string;
enabled: boolean;
createdAt: Date;
updatedAt: Date;
}
2 changes: 2 additions & 0 deletions packages/core-typings/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ export * from './ICustomSound';
export * from './ICloud';
export * from './IServerEvent';
export * from './ICronJobs';
export * from './IPushToken';
export * from './IPushNotificationConfig';

export * from './IUserDataFile';
export * from './IUserSession';
Expand Down
2 changes: 2 additions & 0 deletions packages/rest-typings/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import type { LicensesEndpoints } from './v1/licenses';
import type { MiscEndpoints } from './v1/misc';
import type { OmnichannelEndpoints } from './v1/omnichannel';
import type { PermissionsEndpoints } from './v1/permissions';
import type { PushEndpoints } from './v1/push';
import type { RolesEndpoints } from './v1/roles';
import type { RoomsEndpoints } from './v1/rooms';
import type { SettingsEndpoints } from './v1/settings';
Expand All @@ -47,6 +48,7 @@ export interface Endpoints
ImEndpoints,
LDAPEndpoints,
RoomsEndpoints,
PushEndpoints,
RolesEndpoints,
TeamsEndpoints,
SettingsEndpoints,
Expand Down
16 changes: 16 additions & 0 deletions packages/rest-typings/src/v1/push.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import type { IMessage, IPushNotificationConfig, IPushTokenTypes, IPushToken } from '@rocket.chat/core-typings';

export type PushEndpoints = {
'push.token': {
POST: (payload: { id?: string; type: IPushTokenTypes; value: string; appName: string }) => { result: IPushToken };
DELETE: (payload: { token: string }) => void;
};
'push.get': {
GET: (params: { id: string }) => {
data: {
message: IMessage;
notification: IPushNotificationConfig;
};
};
};
};