Skip to content
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
7 changes: 7 additions & 0 deletions .changeset/cute-humans-follow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@rocket.chat/model-typings': patch
'@rocket.chat/models': patch
'@rocket.chat/meteor': patch
---

Fixes auto-translate not activating for users who set their language preference after joining rooms
5 changes: 5 additions & 0 deletions .changeset/short-mice-cover.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@rocket.chat/meteor': patch
---

Fixes rooms failing to open on transient network errors, and prevents a "Room Not Found" flash when opening a room with a local subscription
6 changes: 6 additions & 0 deletions .changeset/true-cooks-lick.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@rocket.chat/apps-engine': minor
'@rocket.chat/meteor': minor
---

Exposes the `isFederated` and `federation` fields for room and user objects in apps
2 changes: 2 additions & 0 deletions apps/meteor/app/apps/server/bridges/rooms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ const rawRoomProjection: FindOptions<ICoreRoom>['projection'] = {
prid: 1,
teamId: 1,
teamMain: 1,
federated: 1,
federation: 1,
livechatData: 1,
waitingResponse: 1,
open: 1,
Expand Down
6 changes: 6 additions & 0 deletions apps/meteor/app/apps/server/converters/rooms.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ export class AppRoomsConverter {
contactId: 'contactId',
departmentId: 'departmentId',
parentRoomId: 'prid',
isFederated: 'federated',
federation: 'federation',
visitor: (data) => {
const { v } = data;
if (!v) {
Expand Down Expand Up @@ -261,6 +263,8 @@ export class AppRoomsConverter {
...(room.lastModifiedAt && { lm: room.lastModifiedAt }),
...(room.customFields && { customFields: room.customFields }),
...(room.livechatData && { livechatData: room.livechatData }),
...(typeof room.isFederated !== 'undefined' && { federated: room.isFederated }),
...(typeof room.federation !== 'undefined' && { federation: room.federation }),
...(typeof room.parentRoom !== 'undefined' && { prid: room.parentRoom.id }),
...(contactId && { contactId }),
...(room._USERNAMES && { _USERNAMES: room._USERNAMES }),
Expand Down Expand Up @@ -304,6 +308,8 @@ export class AppRoomsConverter {
closer: 'closer',
teamId: 'teamId',
isTeamMain: 'teamMain',
isFederated: 'federated',
federation: 'federation',
isDefault: (room) => {
const result = !!room.default;
delete room.default;
Expand Down
4 changes: 4 additions & 0 deletions apps/meteor/app/apps/server/converters/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ export class AppUsersConverter {
lastLoginAt: user.lastLogin,
appId: user.appId,
customFields: user.customFields,
isFederated: user.federated,
federation: user.federation,
sipExtension: user.freeSwitchExtension,
settings: {
preferences: {
Expand Down Expand Up @@ -75,6 +77,8 @@ export class AppUsersConverter {
_updatedAt: user.updatedAt,
lastLogin: user.lastLoginAt,
appId: user.appId,
federated: user.isFederated,
federation: user.federation,
freeSwitchExtension: user.sipExtension,
});
}
Expand Down
17 changes: 16 additions & 1 deletion apps/meteor/client/views/room/hooks/useOpenRoom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,12 @@ export function useOpenRoom({ type, reference }: { type: RoomType; reference: st
try {
roomData = await getRoomByTypeAndName(type, reference);
} catch (error) {
const isDefinitivelyNotFound = error && typeof error === 'object' && 'error' in error && error.error === 'error-invalid-room';

if (!isDefinitivelyNotFound) {
throw error;
}

if (type !== 'd') {
throw new RoomNotFoundError(undefined, { type, reference });
}
Expand Down Expand Up @@ -137,7 +143,16 @@ export function useOpenRoom({ type, reference }: { type: RoomType; reference: st

return { rid: room._id };
},
retry: 0,
retry: (failureCount, error) => {
const unrecoverableErrors = [RoomNotFoundError, OldUrlRoomError, NotAuthorizedError, NotSubscribedToRoomError];

if (unrecoverableErrors.some((e) => error instanceof e)) {
return false;
}

return failureCount < 4;
},
retryDelay: (attempt) => Math.min(1000 * 2 ** attempt, 5000),
});

const queryClient = useQueryClient();
Expand Down
2 changes: 1 addition & 1 deletion apps/meteor/client/views/room/providers/RoomProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ const RoomProvider = ({ rid, children }: RoomProviderProps) => {
}, [rid, subscribed]);

if (!pseudoRoom) {
return !room ? <RoomNotFound /> : <RoomSkeleton />;
return !room && !subscritionFromLocal ? <RoomNotFound /> : <RoomSkeleton />;
}

return (
Expand Down
5 changes: 4 additions & 1 deletion apps/meteor/server/methods/saveUserPreferences.ts
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,10 @@ export const saveUserPreferences = async (settings: Partial<UserPreferences>, us
}

if (language && oldLanguage !== language && rcSettings.get('AutoTranslate_AutoEnableOnJoinRoom')) {
const response = await Subscriptions.updateAllAutoTranslateLanguagesByUserId(user._id, language);
const workspaceLanguage = rcSettings.get('Language');
const targetLanguage = language === 'default' || language === workspaceLanguage ? null : language;

const response = await Subscriptions.setAutoTranslateByUserId(user._id, targetLanguage);
if (response.modifiedCount) {
void notifyOnSubscriptionChangedByAutoTranslateAndUserId(user._id);
}
Expand Down
90 changes: 90 additions & 0 deletions apps/meteor/tests/end-to-end/api/autotranslate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -669,6 +669,96 @@ describe('AutoTranslate', () => {
expect(subscription).to.have.property('autoTranslateLanguage', 'es');
channelsToRemove.push(newChannel);
});

it('should enable autotranslate on existing subscriptions when user changes from workspace language to a different one', async () => {
await setLanguagePref('pt-BR', credA);
const newChannel = await createChannel(undefined, credA);
channelsToRemove.push(newChannel);

const subBefore = await getSub(newChannel._id, credA);
expect(subBefore).to.not.have.property('autoTranslate');
expect(subBefore).to.not.have.property('autoTranslateLanguage');

await setLanguagePref('en', credA);

const subAfter = await getSub(newChannel._id, credA);
expect(subAfter).to.have.property('autoTranslate', true);
expect(subAfter).to.have.property('autoTranslateLanguage', 'en');
});

it("should enable autotranslate on existing subscriptions when user changes from 'default' language to a non-workspace language", async () => {
await setLanguagePref('default', credA);
const newChannel = await createChannel(undefined, credA);
channelsToRemove.push(newChannel);

const subBefore = await getSub(newChannel._id, credA);
expect(subBefore).to.not.have.property('autoTranslate');
expect(subBefore).to.not.have.property('autoTranslateLanguage');

await setLanguagePref('en', credA);

const subAfter = await getSub(newChannel._id, credA);
expect(subAfter).to.have.property('autoTranslate', true);
expect(subAfter).to.have.property('autoTranslateLanguage', 'en');
});

it('should disable autotranslate on existing subscriptions when user changes language to default', async () => {
await setLanguagePref('en', credA);
const newChannel = await createChannel(undefined, credA);
channelsToRemove.push(newChannel);

const subBefore = await getSub(newChannel._id, credA);
expect(subBefore).to.have.property('autoTranslate', true);

await setLanguagePref('default', credA);

const subAfter = await getSub(newChannel._id, credA);
expect(subAfter).to.not.have.property('autoTranslate');
expect(subAfter).to.not.have.property('autoTranslateLanguage');
});

it('should disable autotranslate on existing subscriptions when user changes language to the workspace default', async () => {
await setLanguagePref('en', credA);
const newChannel = await createChannel(undefined, credA);
channelsToRemove.push(newChannel);

const subBefore = await getSub(newChannel._id, credA);
expect(subBefore).to.have.property('autoTranslate', true);

await setLanguagePref('pt-BR', credA);

const subAfter = await getSub(newChannel._id, credA);
expect(subAfter).to.not.have.property('autoTranslate');
expect(subAfter).to.not.have.property('autoTranslateLanguage');
});

it('should not re-enable autotranslate for rooms where the user has explicitly opted out', async () => {
await updatePermission('auto-translate', ['admin', 'user']);

await setLanguagePref('en', credA);
const newChannel = await createChannel(undefined, credA);
channelsToRemove.push(newChannel);

const subEnabled = await getSub(newChannel._id, credA);
expect(subEnabled).to.have.property('autoTranslate', true);

await request
.post(api('autotranslate.saveSettings'))
.set(credA)
.send({ roomId: newChannel._id, field: 'autoTranslate', value: false, defaultLanguage: 'en' })
.expect(200)
.expect((res) => {
expect(res.body).to.have.property('success', true);
});

const subOptedOut = await getSub(newChannel._id, credA);
expect(subOptedOut).to.have.property('autoTranslate', false);

await setLanguagePref('es', credA);

const subAfterLangChange = await getSub(newChannel._id, credA);
expect(subAfterLangChange).to.have.property('autoTranslate', false);
});
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export type FederationLookup = {
version: number;
mrid: string;
origin: string;
};
1 change: 1 addition & 0 deletions packages/apps-engine/src/definition/federation/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export type * from './FederationLookup';
3 changes: 3 additions & 0 deletions packages/apps-engine/src/definition/rooms/IRoom.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { IAbacAttributeDefinition } from '../abac/AbacAttributes';
import type { FederationLookup } from '../federation';
import type { IUser } from '../users';
import type { RoomType } from './RoomType';

Expand Down Expand Up @@ -26,6 +27,8 @@ export interface IRoom {
customFields?: { [key: string]: any };
parentRoom?: IRoom;
livechatData?: { [key: string]: any };
isFederated?: boolean;
federation?: FederationLookup;

abacAttributes?: IAbacAttributeDefinition[];
}
5 changes: 4 additions & 1 deletion packages/apps-engine/src/definition/rooms/IRoomRaw.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import type { IVisitor } from '../livechat';
import type { RoomType } from './RoomType';
import type { FederationLookup } from '../federation';
import type { IOmnichannelSource, IVisitorChannelInfo } from '../livechat/ILivechatRoom';
import type { IUserLookup } from '../users';
import type { RoomType } from './RoomType';

/**
* A lightweight representation of a room without resolving relational data.
Expand Down Expand Up @@ -40,4 +41,6 @@ export interface IRoomRaw {
visitor?: Pick<IVisitor, 'id' | 'token' | 'username' | 'name' | 'status' | 'activity'> & IVisitorChannelInfo;
departmentId?: string;
contactId?: string;
isFederated?: boolean;
federation?: FederationLookup;
}
3 changes: 3 additions & 0 deletions packages/apps-engine/src/definition/users/IUser.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { FederationLookup } from '../federation';
import type { IUserEmail } from './IUserEmail';
import type { IUserSettings } from './IUserSettings';
import type { UserStatusConnection } from './UserStatusConnection';
Expand Down Expand Up @@ -25,5 +26,7 @@ export interface IUser {
settings?: IUserSettings;
appId?: string;
sipExtension?: string;
isFederated?: boolean;
federation?: FederationLookup;
customFields?: { [key: string]: any };
}
2 changes: 1 addition & 1 deletion packages/model-typings/src/models/ISubscriptionsModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ export interface ISubscriptionsModel extends IBaseModel<ISubscription> {
cachedFindByUserId(userId: string, options?: FindOptions<ISubscription>): FindCursor<ISubscription>;
updateAutoTranslateById(_id: string, autoTranslate: boolean): Promise<UpdateResult>;

updateAllAutoTranslateLanguagesByUserId(userId: IUser['_id'], language: string): Promise<UpdateResult | Document>;
setAutoTranslateByUserId(userId: IUser['_id'], language: string | null): Promise<UpdateResult | Document>;
findByAutoTranslateAndUserId(
userId: ISubscription['u']['_id'],
autoTranslate?: ISubscription['autoTranslate'],
Expand Down
30 changes: 16 additions & 14 deletions packages/models/src/models/Subscriptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -707,8 +707,8 @@ export class SubscriptionsRaw extends BaseRaw<ISubscription> implements ISubscri
};
} else {
update = {
$unset: {
autoTranslate: 1,
$set: {
autoTranslate: false,
},
};
}
Expand All @@ -723,19 +723,21 @@ export class SubscriptionsRaw extends BaseRaw<ISubscription> implements ISubscri
return this.findOneAndUpdate(query, update, { returnDocument: 'after' });
}

updateAllAutoTranslateLanguagesByUserId(userId: IUser['_id'], language: string): Promise<UpdateResult | Document> {
const query = {
'u._id': userId,
'autoTranslate': true,
};

const update: UpdateFilter<ISubscription> = {
$set: {
autoTranslateLanguage: language,
},
};
setAutoTranslateByUserId(userId: IUser['_id'], language: string | null): Promise<UpdateResult | Document> {
if (language) {
return Promise.all([
this.updateMany({ 'u._id': userId, 'autoTranslate': true }, { $set: { autoTranslateLanguage: language } }),
this.updateMany(
{ 'u._id': userId, 'autoTranslate': { $exists: false } },
{ $set: { autoTranslate: true, autoTranslateLanguage: language } },
),
]).then(([updateResult, enableResult]) => ({
...updateResult,
modifiedCount: updateResult.modifiedCount + enableResult.modifiedCount,
}));
}

return this.updateMany(query, update);
return this.updateMany({ 'u._id': userId, 'autoTranslate': true }, { $unset: { autoTranslate: 1, autoTranslateLanguage: 1 } });
}

findByAutoTranslateAndUserId(
Expand Down
Loading