Skip to content

Commit

Permalink
chore: move imported Apps to proxy (#32142)
Browse files Browse the repository at this point in the history
  • Loading branch information
ggazzo authored Apr 5, 2024
1 parent 4aba7c8 commit a7823c1
Show file tree
Hide file tree
Showing 37 changed files with 115 additions and 100 deletions.
6 changes: 3 additions & 3 deletions apps/meteor/app/authentication/server/startup/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -350,8 +350,8 @@ const insertUserDocAsync = async function (options, user) {

if (!options.skipAppsEngineEvent) {
// `post` triggered events don't need to wait for the promise to resolve
Apps?.triggerEvent(AppEvents.IPostUserCreated, { user, performedBy: await safeGetMeteorUser() }).catch((e) => {
Apps?.getRocketChatLogger().error('Error while executing post user created event:', e);
Apps.self?.triggerEvent(AppEvents.IPostUserCreated, { user, performedBy: await safeGetMeteorUser() }).catch((e) => {
Apps.self?.getRocketChatLogger().error('Error while executing post user created event:', e);
});
}

Expand Down Expand Up @@ -424,7 +424,7 @@ const validateLoginAttemptAsync = async function (login) {
*/
if (login.type !== 'resume') {
// App IPostUserLoggedIn event hook
await Apps?.triggerEvent(AppEvents.IPostUserLoggedIn, login.user);
await Apps.self?.triggerEvent(AppEvents.IPostUserLoggedIn, login.user);
}

return true;
Expand Down
12 changes: 2 additions & 10 deletions apps/meteor/app/file-upload/server/lib/FileUpload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ export const FileUpload = {

// App IPreFileUpload event hook
try {
await Apps?.triggerEvent(AppEvents.IPreFileUpload, { file, content: content || Buffer.from([]) });
await Apps.self?.triggerEvent(AppEvents.IPreFileUpload, { file, content: content || Buffer.from([]) });
} catch (error: any) {
if (error.name === AppsEngineException.name) {
throw new Meteor.Error('error-app-prevented', error.message);
Expand Down Expand Up @@ -587,15 +587,7 @@ export const FileUpload = {
}

// eslint-disable-next-line prettier/prettier
const headersToProxy = [
'age',
'cache-control',
'content-length',
'content-type',
'date',
'expired',
'last-modified',
];
const headersToProxy = ['age', 'cache-control', 'content-length', 'content-type', 'date', 'expired', 'last-modified'];

headersToProxy.forEach((header) => {
fileRes.headers[header] && res.setHeader(header, String(fileRes.headers[header]));
Expand Down
4 changes: 2 additions & 2 deletions apps/meteor/app/lib/server/functions/addUserToRoom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export const addUserToRoom = async function (
}

try {
await Apps?.triggerEvent(AppEvents.IPreRoomUserJoined, room, userToBeAdded, inviter);
await Apps.self?.triggerEvent(AppEvents.IPreRoomUserJoined, room, userToBeAdded, inviter);
} catch (error: any) {
if (error.name === AppsEngineException.name) {
throw new Meteor.Error('error-app-prevented', error.message);
Expand Down Expand Up @@ -118,7 +118,7 @@ export const addUserToRoom = async function (
// Keep the current event
await callbacks.run('afterJoinRoom', userToBeAdded, room);

void Apps?.triggerEvent(AppEvents.IPostRoomUserJoined, room, userToBeAdded, inviter);
void Apps.self?.triggerEvent(AppEvents.IPostRoomUserJoined, room, userToBeAdded, inviter);
});
}

Expand Down
8 changes: 4 additions & 4 deletions apps/meteor/app/lib/server/functions/createDirectRoom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ export async function createDirectRoom(
_USERNAMES: usernames,
};

const prevent = await Apps?.triggerEvent(AppEvents.IPreRoomCreatePrevent, tmpRoom).catch((error) => {
const prevent = await Apps.self?.triggerEvent(AppEvents.IPreRoomCreatePrevent, tmpRoom).catch((error) => {
if (error.name === AppsEngineException.name) {
throw new Meteor.Error('error-app-prevented', error.message);
}
Expand All @@ -115,9 +115,9 @@ export async function createDirectRoom(
throw new Meteor.Error('error-app-prevented', 'A Rocket.Chat App prevented the room creation.');
}

const result = await Apps?.triggerEvent(
const result = await Apps.self?.triggerEvent(
AppEvents.IPreRoomCreateModify,
await Apps?.triggerEvent(AppEvents.IPreRoomCreateExtend, tmpRoom),
await Apps.self?.triggerEvent(AppEvents.IPreRoomCreateExtend, tmpRoom),
);

if (typeof result === 'object') {
Expand Down Expand Up @@ -172,7 +172,7 @@ export async function createDirectRoom(

await callbacks.run('afterCreateDirectRoom', insertedRoom, { members: roomMembers, creatorId: options?.creator });

void Apps?.triggerEvent(AppEvents.IPostRoomCreate, insertedRoom);
void Apps.self?.triggerEvent(AppEvents.IPostRoomCreate, insertedRoom);
}

return {
Expand Down
6 changes: 3 additions & 3 deletions apps/meteor/app/lib/server/functions/createRoom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ export const createRoom = async <T extends RoomType>(
_USERNAMES: members,
};

const prevent = await Apps?.triggerEvent(AppEvents.IPreRoomCreatePrevent, tmp).catch((error) => {
const prevent = await Apps.self?.triggerEvent(AppEvents.IPreRoomCreatePrevent, tmp).catch((error) => {
if (error.name === AppsEngineException.name) {
throw new Meteor.Error('error-app-prevented', error.message);
}
Expand All @@ -210,7 +210,7 @@ export const createRoom = async <T extends RoomType>(
throw new Meteor.Error('error-app-prevented', 'A Rocket.Chat App prevented the room creation.');
}

const eventResult = await Apps?.triggerEvent(
const eventResult = await Apps.self?.triggerEvent(
AppEvents.IPreRoomCreateModify,
await Apps.triggerEvent(AppEvents.IPreRoomCreateExtend, tmp),
);
Expand Down Expand Up @@ -245,7 +245,7 @@ export const createRoom = async <T extends RoomType>(
callbacks.runAsync('federation.afterCreateFederatedRoom', room, { owner, originalMemberList: members });
}

void Apps?.triggerEvent(AppEvents.IPostRoomCreate, room);
void Apps.self?.triggerEvent(AppEvents.IPostRoomCreate, room);
return {
rid: room._id, // backwards compatible
inserted: true,
Expand Down
2 changes: 1 addition & 1 deletion apps/meteor/app/lib/server/functions/deleteMessage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export async function deleteMessage(message: IMessage, user: IUser): Promise<voi
const isThread = (deletedMsg?.tcount || 0) > 0;
const keepHistory = settings.get('Message_KeepHistory') || isThread;
const showDeletedStatus = settings.get('Message_ShowDeletedStatus') || isThread;
const bridges = Apps?.isLoaded() && Apps.getBridges();
const bridges = Apps.self?.isLoaded() && Apps.getBridges();

if (deletedMsg && bridges) {
const prevent = await bridges.getListenerBridge().messageEvent(AppEvents.IPreMessageDeletePrevent, deletedMsg);
Expand Down
4 changes: 2 additions & 2 deletions apps/meteor/app/lib/server/functions/removeUserFromRoom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export const removeUserFromRoom = async function (
}

try {
await Apps?.triggerEvent(AppEvents.IPreRoomUserLeave, room, user);
await Apps.self?.triggerEvent(AppEvents.IPreRoomUserLeave, room, user);
} catch (error: any) {
if (error.name === AppsEngineException.name) {
throw new Meteor.Error('error-app-prevented', error.message);
Expand Down Expand Up @@ -67,5 +67,5 @@ export const removeUserFromRoom = async function (
// TODO: CACHE: maybe a queue?
await afterLeaveRoomCallback.run(user, room);

await Apps?.triggerEvent(AppEvents.IPostRoomUserLeave, room, user);
await Apps.self?.triggerEvent(AppEvents.IPostRoomUserLeave, room, user);
};
2 changes: 1 addition & 1 deletion apps/meteor/app/lib/server/functions/saveUser.js
Original file line number Diff line number Diff line change
Expand Up @@ -434,7 +434,7 @@ export const saveUser = async function (userId, userData) {
oldUser: oldUserData,
});

await Apps?.triggerEvent(AppEvents.IPostUserUpdated, {
await Apps.self?.triggerEvent(AppEvents.IPostUserUpdated, {
user: userUpdated,
previousUser: oldUserData,
performedBy: await safeGetMeteorUser(),
Expand Down
4 changes: 2 additions & 2 deletions apps/meteor/app/lib/server/functions/sendMessage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ export const sendMessage = async function (user: any, message: any, room: any, u
}

// For the Rocket.Chat Apps :)
if (Apps?.isLoaded()) {
if (Apps.self?.isLoaded()) {
const listenerBridge = Apps.getBridges()?.getListenerBridge();

const prevent = await listenerBridge?.messageEvent('IPreMessageSentPrevent', message);
Expand Down Expand Up @@ -275,7 +275,7 @@ export const sendMessage = async function (user: any, message: any, room: any, u
message._id = insertedId;
}

if (Apps?.isLoaded()) {
if (Apps.self?.isLoaded()) {
// This returns a promise, but it won't mutate anything about the message
// so, we don't really care if it is successful or fails
void Apps.getBridges()?.getListenerBridge().messageEvent('IPostMessageSent', message);
Expand Down
4 changes: 2 additions & 2 deletions apps/meteor/app/lib/server/functions/updateMessage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export const updateMessage = async function (
let messageData: IMessage = Object.assign({}, originalMessage, message);

// For the Rocket.Chat Apps :)
if (message && Apps && Apps.isLoaded()) {
if (message && Apps.self && Apps.isLoaded()) {
const prevent = await Apps.getBridges().getListenerBridge().messageEvent(AppEvents.IPreMessageUpdatedPrevent, messageData);
if (prevent) {
throw new Meteor.Error('error-app-prevented-updating', 'A Rocket.Chat App prevented the message updating.');
Expand Down Expand Up @@ -76,7 +76,7 @@ export const updateMessage = async function (
},
);

if (Apps?.isLoaded()) {
if (Apps.self?.isLoaded()) {
// This returns a promise, but it won't mutate anything about the message
// so, we don't really care if it is successful or fails
void Apps.getBridges()?.getListenerBridge().messageEvent(AppEvents.IPostMessageUpdated, messageData);
Expand Down
2 changes: 1 addition & 1 deletion apps/meteor/app/lib/server/methods/deleteUserOwnAccount.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ Meteor.methods<ServerMethods>({
await deleteUser(uid, confirmRelinquish);

// App IPostUserDeleted event hook
await Apps?.triggerEvent(AppEvents.IPostUserDeleted, { user });
await Apps.self?.triggerEvent(AppEvents.IPostUserDeleted, { user });

return true;
},
Expand Down
6 changes: 3 additions & 3 deletions apps/meteor/app/livechat/server/lib/Helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,7 @@ export const removeAgentFromSubscription = async (rid: string, { _id, username }
await Message.saveSystemMessage('ul', rid, username || '', { _id: user._id, username: user.username, name: user.name });

setImmediate(() => {
void Apps?.triggerEvent(AppEvents.IPostLivechatAgentUnassigned, { room, user });
void Apps.self?.triggerEvent(AppEvents.IPostLivechatAgentUnassigned, { room, user });
});
};

Expand Down Expand Up @@ -452,7 +452,7 @@ export const forwardRoomToAgent = async (room: IOmnichannelRoom, transferData: T
}

setImmediate(() => {
void Apps?.triggerEvent(AppEvents.IPostLivechatRoomTransferred, {
void Apps.self?.triggerEvent(AppEvents.IPostLivechatRoomTransferred, {
type: LivechatTransferEventType.AGENT,
room: rid,
from: oldServedBy?._id,
Expand Down Expand Up @@ -482,7 +482,7 @@ export const updateChatDepartment = async ({
]);

setImmediate(() => {
void Apps?.triggerEvent(AppEvents.IPostLivechatRoomTransferred, {
void Apps.self?.triggerEvent(AppEvents.IPostLivechatRoomTransferred, {
type: LivechatTransferEventType.DEPARTMENT,
room: rid,
from: oldDepartmentId,
Expand Down
8 changes: 4 additions & 4 deletions apps/meteor/app/livechat/server/lib/LivechatTyped.ts
Original file line number Diff line number Diff line change
Expand Up @@ -329,8 +329,8 @@ class LivechatClass {
* @deprecated the `AppEvents.ILivechatRoomClosedHandler` event will be removed
* in the next major version of the Apps-Engine
*/
void Apps?.getBridges()?.getListenerBridge().livechatEvent(AppEvents.ILivechatRoomClosedHandler, newRoom);
void Apps?.getBridges()?.getListenerBridge().livechatEvent(AppEvents.IPostLivechatRoomClosed, newRoom);
void Apps.self?.getBridges()?.getListenerBridge().livechatEvent(AppEvents.ILivechatRoomClosedHandler, newRoom);
void Apps.self?.getBridges()?.getListenerBridge().livechatEvent(AppEvents.IPostLivechatRoomClosed, newRoom);
});
if (process.env.TEST_MODE) {
await callbacks.run('livechat.closeRoom', {
Expand Down Expand Up @@ -1426,7 +1426,7 @@ class LivechatClass {
const ret = await LivechatVisitors.saveGuestById(_id, updateData);

setImmediate(() => {
void Apps?.triggerEvent(AppEvents.IPostLivechatGuestSaved, _id);
void Apps.self?.triggerEvent(AppEvents.IPostLivechatGuestSaved, _id);
});

return ret;
Expand Down Expand Up @@ -1792,7 +1792,7 @@ class LivechatClass {
await LivechatRooms.saveRoomById(roomData);

setImmediate(() => {
void Apps?.triggerEvent(AppEvents.IPostLivechatRoomSaved, roomData._id);
void Apps.self?.triggerEvent(AppEvents.IPostLivechatRoomSaved, roomData._id);
});

if (guestData?.name?.trim().length) {
Expand Down
2 changes: 1 addition & 1 deletion apps/meteor/app/livechat/server/lib/QueueManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ export const QueueManager: queueManager = {
throw new Error('inquiry-not-found');
}

void Apps?.triggerEvent(AppEvents.IPostLivechatRoomStarted, room);
void Apps.self?.triggerEvent(AppEvents.IPostLivechatRoomStarted, room);
await LivechatRooms.updateRoomCount();

await queueInquiry(inquiry, agent);
Expand Down
2 changes: 1 addition & 1 deletion apps/meteor/app/livechat/server/lib/RoutingManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ export const RoutingManager: Routing = {
await dispatchAgentDelegated(rid, agent.agentId);
logger.debug(`Agent ${agent.agentId} assigned to inquriy ${inquiry._id}. Instances notified`);

void Apps?.getBridges()?.getListenerBridge().livechatEvent(AppEvents.IPostLivechatAgentAssigned, { room, user });
void Apps.self?.getBridges()?.getListenerBridge().livechatEvent(AppEvents.IPostLivechatAgentAssigned, { room, user });
return inquiry;
},

Expand Down
2 changes: 1 addition & 1 deletion apps/meteor/app/mailer/server/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ export const sendNoWrap = async ({

const email = { to, from, replyTo, subject, html, text, headers };

const eventResult = await Apps?.triggerEvent(AppEvents.IPreEmailSent, { email });
const eventResult = await Apps.self?.triggerEvent(AppEvents.IPreEmailSent, { email });

setImmediate(() => Email.sendAsync(eventResult || email).catch((e) => console.error(e)));
};
Expand Down
4 changes: 2 additions & 2 deletions apps/meteor/app/message-pin/server/pinMessage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ Meteor.methods<ServerMethods>({
}

// App IPostMessagePinned event hook
await Apps?.triggerEvent(AppEvents.IPostMessagePinned, originalMessage, await Meteor.userAsync(), originalMessage.pinned);
await Apps.self?.triggerEvent(AppEvents.IPostMessagePinned, originalMessage, await Meteor.userAsync(), originalMessage.pinned);

const msgId = await Message.saveSystemMessage('message_pinned', originalMessage.rid, '', me, {
attachments: [
Expand Down Expand Up @@ -216,7 +216,7 @@ Meteor.methods<ServerMethods>({
}

// App IPostMessagePinned event hook
await Apps?.triggerEvent(AppEvents.IPostMessagePinned, originalMessage, await Meteor.userAsync(), originalMessage.pinned);
await Apps.self?.triggerEvent(AppEvents.IPostMessagePinned, originalMessage, await Meteor.userAsync(), originalMessage.pinned);

await Messages.setPinnedByIdAndUserId(originalMessage._id, originalMessage.pinnedBy, originalMessage.pinned);
if (settings.get('Message_Read_Receipt_Store_Users')) {
Expand Down
2 changes: 1 addition & 1 deletion apps/meteor/app/message-star/server/starMessage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ Meteor.methods<ServerMethods>({
await Rooms.updateLastMessageStar(room._id, uid, message.starred);
}

await Apps?.triggerEvent(AppEvents.IPostMessageStarred, message, await Meteor.userAsync(), message.starred);
await Apps.self?.triggerEvent(AppEvents.IPostMessageStarred, message, await Meteor.userAsync(), message.starred);

await Messages.updateUserStarById(message._id, uid, message.starred);

Expand Down
2 changes: 1 addition & 1 deletion apps/meteor/app/reactions/server/setReaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ async function setReaction(room: IRoom, user: IUser, message: IMessage, reaction
isReacted = true;
}

await Apps?.triggerEvent(AppEvents.IPostMessageReacted, message, user, reaction, isReacted);
await Apps.self?.triggerEvent(AppEvents.IPostMessageReacted, message, user, reaction, isReacted);

void broadcastMessageFromData({
id: message._id,
Expand Down
6 changes: 3 additions & 3 deletions apps/meteor/app/statistics/server/lib/getAppsStatistics.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ import { Info } from '../../../utils/rocketchat.info';
export function getAppsStatistics() {
return {
engineVersion: Info.marketplaceApiVersion,
totalInstalled: (Apps?.isInitialized() && Apps.getManager().get().length) ?? 0,
totalActive: (Apps?.isInitialized() && Apps.getManager().get({ enabled: true }).length) ?? 0,
totalInstalled: (Apps.self?.isInitialized() && Apps.getManager().get().length) ?? 0,
totalActive: (Apps.self?.isInitialized() && Apps.getManager().get({ enabled: true }).length) ?? 0,
totalFailed:
(Apps?.isInitialized() &&
(Apps.self?.isInitialized() &&
Apps.getManager()
.get({ disabled: true })
.filter(({ app: { status } }) => status !== AppStatus.MANUALLY_DISABLED).length) ??
Expand Down
2 changes: 1 addition & 1 deletion apps/meteor/app/threads/server/methods/followMessage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ Meteor.methods<ServerMethods>({
const followResult = await follow({ tmid: message.tmid || message._id, uid });

const isFollowed = true;
await Apps?.triggerEvent(AppEvents.IPostMessageFollowed, message, await Meteor.userAsync(), isFollowed);
await Apps.self?.triggerEvent(AppEvents.IPostMessageFollowed, message, await Meteor.userAsync(), isFollowed);

return followResult;
},
Expand Down
2 changes: 1 addition & 1 deletion apps/meteor/app/threads/server/methods/unfollowMessage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ Meteor.methods<ServerMethods>({
const unfollowResult = await unfollow({ rid: message.rid, tmid: message.tmid || message._id, uid });

const isFollowed = false;
await Apps?.triggerEvent(AppEvents.IPostMessageFollowed, message, await Meteor.userAsync(), isFollowed);
await Apps.self?.triggerEvent(AppEvents.IPostMessageFollowed, message, await Meteor.userAsync(), isFollowed);

return unfollowResult;
},
Expand Down
5 changes: 1 addition & 4 deletions apps/meteor/ee/server/apps/communication/rest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -534,10 +534,7 @@ export class AppsRestApi {

try {
const { event, externalComponent } = this.bodyParams;
const result = (Apps?.getBridges()?.getListenerBridge() as Record<string, any>).externalComponentEvent(
event,
externalComponent,
);
const result = (Apps.getBridges()?.getListenerBridge() as Record<string, any>).externalComponentEvent(event, externalComponent);

return API.v1.success({ result });
} catch (e: any) {
Expand Down
1 change: 1 addition & 0 deletions apps/meteor/ee/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,6 @@ import './requestSeatsRoute';
import './configuration/index';
import './local-services/ldap/service';
import './methods/getReadReceipts';
import './apps/startup';

export { registerEEBroker } from './startup';
1 change: 0 additions & 1 deletion apps/meteor/ee/server/startup/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import '../apps/startup';
import '../../app/authorization/server';
import './apps';
import './audit';
Expand Down
2 changes: 1 addition & 1 deletion apps/meteor/server/lib/moderation/reportMessage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export const reportMessage = async (messageId: IMessage['_id'], description: str

await ModerationReports.createWithMessageDescriptionAndUserId(message, description, roomInfo, reportedBy);

await Apps?.triggerEvent(AppEvents.IPostMessageReported, message, user, description);
await Apps.self?.triggerEvent(AppEvents.IPostMessageReported, message, user, description);

return true;
};
2 changes: 1 addition & 1 deletion apps/meteor/server/methods/deleteUser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ Meteor.methods<ServerMethods>({
await deleteUser(userId, confirmRelinquish, uid);

// App IPostUserDeleted event hook
await Apps?.triggerEvent(AppEvents.IPostUserDeleted, { user, performedBy: await Meteor.userAsync() });
await Apps.self?.triggerEvent(AppEvents.IPostUserDeleted, { user, performedBy: await Meteor.userAsync() });

return true;
},
Expand Down
Loading

0 comments on commit a7823c1

Please sign in to comment.