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

refactor: Do not rely on amplify for sound notifications #16408

Merged
merged 5 commits into from
Dec 21, 2023
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 @@ -29,62 +29,54 @@ describe('AudioRepository', () => {
const audioRepository = new AudioRepository();

describe('init', () => {
it('inits all the sounds without preload', () => {
spyOn(window, 'Audio').and.callFake(function () {
this.load = () => {};
spyOn(this, 'load');
});
audioRepository.init();

expect(window.Audio).toHaveBeenCalledTimes(Object.keys(AudioType).length);
Object.values(audioRepository.audioElements).forEach(audioElement => {
expect(audioElement.load).not.toHaveBeenCalled();
});
});

it('inits all the sounds with preload', () => {
spyOn(window, 'Audio').and.callFake(function () {
this.load = () => {};
spyOn(this, 'load');
});
audioRepository.init(true);
jest.spyOn(window, 'Audio').mockImplementation(
() =>
({
load: jest.fn(),
}) as unknown as HTMLAudioElement,
);

audioRepository.init();

expect(window.Audio).toHaveBeenCalledTimes(Object.keys(AudioType).length);

Object.values(audioRepository.audioElements).forEach(audioElement => {
Object.values(audioRepository['audioElements']).forEach(audioElement => {
expect(audioElement.load).toHaveBeenCalledTimes(1);
});
});
});

describe('play', () => {
beforeEach(() => {
spyOn(window, 'Audio').and.callFake(function () {
this.load = () => {};
this.play = () => {};
this.paused = true;
spyOn(this, 'play');
});
jest.spyOn(window, 'Audio').mockImplementation(
() =>
({
load: jest.fn(),
play: jest.fn(),
paused: true,
}) as unknown as HTMLAudioElement,
);
audioRepository.init();
audioRepository.setMutedState(NOTIFICATION_HANDLING_STATE.WEB_SOCKET);
});

it('only plays muted allowed sounds when in muted state', () => {
audioRepository.setAudioPreference(AudioPreference.NONE);
audioRepository.setMutedState('whatever');
audioRepository.setMutedState(NOTIFICATION_HANDLING_STATE.RECOVERY);
const forcedSounds = AudioPlayingType.MUTED;

const forcedPromises = forcedSounds.map(audioId => {
return audioRepository.play(audioId).then(() => {
expect(audioRepository.audioElements[audioId].play).toHaveBeenCalledTimes(1);
expect(audioRepository['audioElements'][audioId].play).toHaveBeenCalledTimes(1);
});
});

const ignoredSounds = difference(Object.values(AudioType), AudioPlayingType.MUTED);

const ignoredPromises = ignoredSounds.map(audioId => {
return audioRepository.play(audioId).then(() => {
expect(audioRepository.audioElements[audioId].play).not.toHaveBeenCalledTimes(1);
expect(audioRepository['audioElements'][audioId].play).not.toHaveBeenCalledTimes(1);
});
});

Expand All @@ -97,15 +89,15 @@ describe('AudioRepository', () => {

const allowedPromises = allowedSounds.map(audioId => {
return audioRepository.play(audioId).then(() => {
expect(audioRepository.audioElements[audioId].play).toHaveBeenCalledTimes(1);
expect(audioRepository['audioElements'][audioId].play).toHaveBeenCalledTimes(1);
});
});

const ignoredSounds = difference(Object.values(AudioType), AudioPlayingType.SOME);

const ignoredPromises = ignoredSounds.map(audioId => {
return audioRepository.play(audioId).then(() => {
expect(audioRepository.audioElements[audioId].play).not.toHaveBeenCalledTimes(1);
expect(audioRepository['audioElements'][audioId].play).not.toHaveBeenCalledTimes(1);
});
});

Expand All @@ -118,7 +110,7 @@ describe('AudioRepository', () => {

const testPromises = sounds.map(audioId => {
return audioRepository.play(audioId).then(() => {
expect(audioRepository.audioElements[audioId].play).not.toHaveBeenCalled();
expect(audioRepository['audioElements'][audioId].play).not.toHaveBeenCalled();
});
});

Expand Down
48 changes: 19 additions & 29 deletions src/script/audio/AudioRepository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,13 @@

import {AudioPreference, WebappProperties} from '@wireapp/api-client/lib/user/data/';
import {amplify} from 'amplify';
import {container} from 'tsyringe';
import ko from 'knockout';

import {WebAppEvents} from '@wireapp/webapp-events';

import {Logger, getLogger} from 'Util/Logger';

import {AudioPlayingType} from './AudioPlayingType';
import {AudioState} from './AudioState';
import {AudioType} from './AudioType';

import {NOTIFICATION_HANDLING_STATE} from '../event/NotificationHandlingState';
Expand All @@ -42,14 +41,12 @@ enum AUDIO_PLAY_PERMISSION {
export class AudioRepository {
private readonly logger: Logger;
private readonly audioElements: Record<string, HTMLAudioElement>;
private readonly audioPreference = ko.observable(AudioPreference.ALL);
private muted: boolean;

constructor(
private readonly devicesHandler: MediaDevicesHandler,
private readonly audioState = container.resolve(AudioState),
) {
constructor(private readonly devicesHandler?: MediaDevicesHandler) {
this.logger = getLogger('AudioRepository');
this.audioState.audioPreference.subscribe(audioPreference => {
this.audioPreference.subscribe(audioPreference => {
if (audioPreference === AudioPreference.NONE) {
this.stopAll();
}
Expand All @@ -64,25 +61,24 @@ export class AudioRepository {
return AUDIO_PLAY_PERMISSION.DISALLOWED_BY_MUTE_STATE;
}

const preferenceIsNone = this.audioState.audioPreference() === AudioPreference.NONE;
const preferenceIsNone = this.audioPreference() === AudioPreference.NONE;
if (preferenceIsNone && !AudioPlayingType.NONE.includes(audioId)) {
return AUDIO_PLAY_PERMISSION.DISALLOWED_BY_PREFERENCES;
}

const preferenceIsSome = this.audioState.audioPreference() === AudioPreference.SOME;
const preferenceIsSome = this.audioPreference() === AudioPreference.SOME;
if (preferenceIsSome && !AudioPlayingType.SOME.includes(audioId)) {
return AUDIO_PLAY_PERMISSION.DISALLOWED_BY_PREFERENCES;
}

return AUDIO_PLAY_PERMISSION.ALLOWED;
}

private createAudioElement(sourcePath: string, preload: boolean): HTMLAudioElement {
private createAudioElement(sourcePath: string): HTMLAudioElement {
const audioElement = new Audio();
audioElement.preload = preload ? 'auto' : 'none';
if (preload) {
audioElement.load();
}
audioElement.preload = 'auto';
// preload element
audioElement.load();
audioElement.src = sourcePath;
return audioElement;
}
Expand All @@ -103,21 +99,16 @@ export class AudioRepository {
return this.audioElements[audioId];
}

private initSounds(preload: boolean): void {
private initSounds(): void {
Object.values(AudioType).forEach(audioId => {
this.audioElements[audioId] = this.createAudioElement(`./audio/${audioId}.mp3`, preload);
this.audioElements[audioId] = this.createAudioElement(`./audio/${audioId}.mp3`);
});
}

private stopAll(): void {
Object.keys(this.audioElements).forEach((audioId: AudioType) => this.stop(audioId));
}

private subscribeToAudioEvents(): void {
amplify.subscribe(WebAppEvents.AUDIO.PLAY, this.play);
amplify.subscribe(WebAppEvents.AUDIO.STOP, this.stop);
}

private subscribeToEvents(): void {
amplify.subscribe(WebAppEvents.EVENT.NOTIFICATION_HANDLING_STATE, this.setMutedState);
amplify.subscribe(WebAppEvents.PROPERTIES.UPDATED, this.updatedProperties);
Expand All @@ -130,10 +121,9 @@ export class AudioRepository {
}
}

init(preload: boolean = false): void {
this.initSounds(preload);
init(): void {
this.initSounds();
this.updateSinkIds();
this.subscribeToAudioEvents();
}

loop(audioId: AudioType): Promise<void> {
Expand All @@ -155,7 +145,7 @@ export class AudioRepository {
return audioElement.play();
}

play = async (audioId: AudioType, playInLoop: boolean = false): Promise<void> => {
async play(audioId: AudioType, playInLoop: boolean = false): Promise<void> {
this.updateSinkIds();
const audioElement = this.getSoundById(audioId);
if (!audioElement) {
Expand All @@ -181,10 +171,10 @@ export class AudioRepository {
this.logger.debug(`Playing '${audioId}' was disallowed because of user's preferences`);
break;
}
};
}

readonly setAudioPreference = (audioPreference: AudioPreference): void => {
this.audioState.audioPreference(audioPreference);
this.audioPreference(audioPreference);
};

readonly setMutedState = (handlingNotifications: NOTIFICATION_HANDLING_STATE): void => {
Expand All @@ -197,15 +187,15 @@ export class AudioRepository {
}
};

readonly stop = (audioId: AudioType): void => {
stop(audioId: AudioType): void {
const audioElement = this.getSoundById(audioId);
if (!audioElement?.paused) {
// This log is used by QA
this.logger.log(`Stopping sound '${audioId}'`);
audioElement.pause();
audioElement.load();
}
};
}

readonly updatedProperties = (properties: WebappProperties): void => {
this.setAudioPreference(properties.settings.sound.alerts);
Expand Down
31 changes: 0 additions & 31 deletions src/script/audio/AudioState.ts

This file was deleted.

2 changes: 2 additions & 0 deletions src/script/conversation/MessageRepository.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import {ConversationRepository} from './ConversationRepository';
import {ConversationState} from './ConversationState';

import {AssetRepository} from '../assets/AssetRepository';
import {AudioRepository} from '../audio/AudioRepository';
import {ClientEntity} from '../client/ClientEntity';
import {ClientState} from '../client/ClientState';
import {CryptographyRepository} from '../cryptography/CryptographyRepository';
Expand Down Expand Up @@ -99,6 +100,7 @@ async function buildMessageRepository(): Promise<[MessageRepository, MessageRepo
assignAllClients: jest.fn().mockResolvedValue(true),
} as unknown as UserRepository,
assetRepository: {} as AssetRepository,
audioRepository: new AudioRepository(),
userState,
clientState,
conversationState,
Expand Down
4 changes: 3 additions & 1 deletion src/script/conversation/MessageRepository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ import {getLinkPreviewFromString} from './linkPreviews';
import {buildMetadata, ImageMetadata, isAudio, isImage, isVideo} from '../assets/AssetMetaDataBuilder';
import {AssetRepository} from '../assets/AssetRepository';
import {AssetTransferState} from '../assets/AssetTransferState';
import {AudioRepository} from '../audio/AudioRepository';
import {AudioType} from '../audio/AudioType';
import {ClientState} from '../client/ClientState';
import {PrimaryModal} from '../components/Modals/PrimaryModal';
Expand Down Expand Up @@ -165,6 +166,7 @@ export class MessageRepository {
private readonly serverTimeHandler: ServerTimeHandler,
private readonly userRepository: UserRepository,
private readonly assetRepository: AssetRepository,
private readonly audioRepository: AudioRepository,
private readonly userState = container.resolve(UserState),
private readonly clientState = container.resolve(ClientState),
private readonly conversationState = container.resolve(ConversationState),
Expand Down Expand Up @@ -240,7 +242,7 @@ export class MessageRepository {
legalHoldStatus: conversation.legalHoldStatus(),
});

amplify.publish(WebAppEvents.AUDIO.PLAY, AudioType.OUTGOING_PING);
void this.audioRepository.play(AudioType.OUTGOING_PING);
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We now have direct calls to the audio repo (rather than implicit global events)

return this.sendAndInjectMessage(ping, conversation, {enableEphemeral: true});
}

Expand Down
9 changes: 7 additions & 2 deletions src/script/main/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,7 @@ export class App {
serverTimeHandler,
repositories.user,
repositories.asset,
repositories.audio,
);

repositories.calling = new CallingRepository(
Expand Down Expand Up @@ -280,7 +281,11 @@ export class App {
repositories.team,
);
repositories.permission = new PermissionRepository();
repositories.notification = new NotificationRepository(repositories.conversation, repositories.permission);
repositories.notification = new NotificationRepository(
repositories.conversation,
repositories.permission,
repositories.audio,
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's not explicit that the notification repo will trigger sound

);
repositories.preferenceNotification = new PreferenceNotificationRepository(repositories.user['userState'].self);

return repositories;
Expand Down Expand Up @@ -503,7 +508,7 @@ export class App {
// start regularly polling the server to check if there is a new version of Wire
startNewVersionPolling(Environment.version(false), this.update);
}
audioRepository.init(true);
audioRepository.init();
await conversationRepository.cleanupEphemeralMessages();
callingRepository.setReady();
telemetry.timeStep(AppInitTimingsStep.APP_LOADED);
Expand Down
2 changes: 2 additions & 0 deletions src/script/notification/NotificationRepository.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ import {createUuid} from 'Util/uuid';

import {NotificationRepository} from './NotificationRepository';

import {AudioRepository} from '../audio/AudioRepository';
import {CallState} from '../calling/CallState';
import {ConnectionEntity} from '../connection/ConnectionEntity';
import {ConversationState} from '../conversation/ConversationState';
Expand All @@ -72,6 +73,7 @@ function buildNotificationRepository() {
const notificationRepository = new NotificationRepository(
{} as any,
new PermissionRepository(),
new AudioRepository(),
userState,
container.resolve(ConversationState),
container.resolve(CallState),
Expand Down
Loading
Loading