Skip to content
Open
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
45 changes: 45 additions & 0 deletions apps/api/src/app/notifications/notifications.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,17 @@ describe('The NotificationsService class', () => {

beforeEach(() => {
mockPreferencesRepository = mock<Repository<NotificationPreferences>>();
mockPreferencesRepository.findOne.mockResolvedValue({
alert_sound: 'sentry_siren.wav',
telegram_enabled: true,
userId: fakeUserId,
} as NotificationPreferences);
mockPreferencesRepository.create.mockReturnValue({
alert_sound: 'sentry_siren.wav',
telegram_enabled: true,
userId: fakeUserId,
} as NotificationPreferences);
mockPreferencesRepository.save.mockImplementation((pref) => Promise.resolve(pref as NotificationPreferences));
mockPushDeviceTokenRepository = mock<Repository<PushDeviceToken>>();
mockPushDeviceTokenRepository.find.mockResolvedValue([createDevice()]);
fetchMock = jest.fn().mockResolvedValue({
Expand Down Expand Up @@ -278,4 +289,38 @@ describe('The NotificationsService class', () => {
});
});
});

describe('The getPreferences() method', () => {
describe('When preferences exist for the user', () => {
it('should return the alert_sound from preferences', async () => {
mockPreferencesRepository.findOne.mockResolvedValue({
alert_sound: 'tesla_horn.wav',
telegram_enabled: true,
userId: fakeUserId,
} as NotificationPreferences);

const result = await service.getPreferences(fakeUserId);

expect(result.alert_sound).toBe('tesla_horn.wav');
});
});
});

describe('The updatePreferences() method', () => {
describe('When updating the alert sound', () => {
it('should persist the new alert_sound', async () => {
mockPreferencesRepository.findOne.mockResolvedValue({
alert_sound: 'sentry_siren.wav',
telegram_enabled: true,
userId: fakeUserId,
} as NotificationPreferences);

await service.updatePreferences(fakeUserId, { alert_sound: 'cyber_pulse.wav' });

expect(mockPreferencesRepository.save).toHaveBeenCalledWith(
expect.objectContaining({ alert_sound: 'cyber_pulse.wav' })
);
});
});
});
});
36 changes: 29 additions & 7 deletions apps/api/src/app/notifications/notifications.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { NOTIFICATION_REQUEST_TIMEOUT_MS } from '../../config/notification-timeo
import { withTimeout } from '../../common/utils/with-timeout.util';

export interface NotificationPreferencesDto {
alert_sound?: string;
critical_alerts_enabled: boolean;
critical_only: boolean;
push_enabled: boolean;
Expand Down Expand Up @@ -103,9 +104,12 @@ export class NotificationsService {
return false;
}

const preferences = await this.findOrCreatePreferences(userId);
const alertSound = preferences.alert_sound || 'sentry_siren.wav';

this.logger.log(`[EXPO_PUSH][${correlationId || 'none'}] Sending push to ${eligibleDevices.length} device(s) for user: ${userId}`);

await this.dispatchPushToDevices(eligibleDevices, severity, type, userId, userLanguage, correlationId);
await this.dispatchPushToDevices(eligibleDevices, severity, type, userId, userLanguage, alertSound, correlationId);

return true;
}
Expand All @@ -121,12 +125,13 @@ export class NotificationsService {
type: AlertEventType,
userId: string,
userLanguage: 'en' | 'fr',
alertSound: string,
correlationId?: string
): Promise<void> {
const { body, title } = this.resolveAlertTexts(type, userLanguage);
const results = await Promise.allSettled(
devices.map((device) =>
this.sendExpoPush(device, title, body, severity, type, device.critical_alerts_enabled, userId, userLanguage, correlationId)
this.sendExpoPush(device, title, body, severity, type, device.critical_alerts_enabled, userId, userLanguage, alertSound, correlationId)
)
);

Expand Down Expand Up @@ -199,6 +204,7 @@ export class NotificationsService {

private pickGlobalPreferenceUpdates(preferences: Partial<NotificationPreferencesDto>): Partial<NotificationPreferences> {
return {
...(preferences.alert_sound !== undefined ? { alert_sound: preferences.alert_sound } : {}),
...(preferences.telegram_enabled !== undefined ? { telegram_enabled: preferences.telegram_enabled } : {}),
};
}
Expand All @@ -213,6 +219,7 @@ export class NotificationsService {

private toDto(preferences: NotificationPreferences, device: PushDeviceToken | null): NotificationPreferencesDto {
return {
alert_sound: preferences.alert_sound ?? 'sentry_siren.wav',
critical_alerts_enabled: device?.critical_alerts_enabled ?? false,
critical_only: device?.critical_only ?? false,
push_enabled: device?.push_enabled ?? false,
Expand All @@ -233,13 +240,14 @@ export class NotificationsService {
criticalAlertsEnabled: boolean,
userId: string,
userLanguage: 'en' | 'fr',
alertSound: string,
correlationId?: string
): Promise<void> {
try {
const pushStart = Date.now();
const response = await withTimeout(
(signal) => fetch('https://exp.host/--/api/v2/push/send', {
body: JSON.stringify(this.buildExpoPushBody(device.token, title, body, severity, type, criticalAlertsEnabled, userId, userLanguage)),
body: JSON.stringify(this.buildExpoPushBody(device.token, title, body, severity, type, criticalAlertsEnabled, userId, userLanguage, alertSound)),
headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
method: 'POST',
signal,
Expand All @@ -266,15 +274,18 @@ export class NotificationsService {
type: AlertEventType,
criticalAlertsEnabled: boolean,
userId: string,
userLanguage: 'en' | 'fr'
userLanguage: 'en' | 'fr',
alertSound: string
): object {
const isPriorityAlert = criticalAlertsEnabled && this.shouldUsePriorityChannel(severity, type);
const channelId = isPriorityAlert ? 'sentryguard-critical-alerts-v5' : 'sentryguard-alerts';
const soundBase = alertSound.replace('.wav', '');
const channelId = isPriorityAlert ? `sentryguard-critical-${soundBase}` : `sentryguard-alerts-${soundBase}`;

return {
const pushMessage: Record<string, unknown> = {
body,
channelId,
data: {
alertSound,
channelId,
criticalAlertsEnabled,
isCriticalAlert: isPriorityAlert,
Expand All @@ -287,10 +298,21 @@ export class NotificationsService {
title,
to: token,
};

const isIosCritical = criticalAlertsEnabled && severity === AlertEventSeverity.Critical;

if (isIosCritical) {
pushMessage.interruptionLevel = 'critical';
pushMessage.sound = { critical: true, name: alertSound, volume: 1.0 };
} else {
pushMessage.sound = alertSound;
}

return pushMessage;
}

private shouldUsePriorityChannel(severity: AlertEventSeverity, type: AlertEventType): boolean {
return severity === AlertEventSeverity.Critical || type === AlertEventType.Sentry;
return severity === AlertEventSeverity.Critical;
}

private buildTeslaRedirectUrl(userId: string, userLanguage: 'en' | 'fr'): string {
Expand Down
3 changes: 3 additions & 0 deletions apps/api/src/entities/notification-preferences.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ export class NotificationPreferences {
@Column({ type: 'boolean', default: true })
telegram_enabled!: boolean;

@Column({ type: 'varchar', length: 64, default: 'sentry_siren.wav' })
alert_sound!: string;

@CreateDateColumn()
created_at!: Date;

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { MigrationInterface, QueryRunner } from 'typeorm';

export class AddAlertSoundToNotificationPreferences1784000000000 implements MigrationInterface {
name = 'AddAlertSoundToNotificationPreferences1784000000000';

public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "notification_preferences" ADD "alert_sound" character varying(64) NOT NULL DEFAULT 'sentry_siren.wav'`
);
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "notification_preferences" DROP COLUMN "alert_sound"`
);
}
}
12 changes: 11 additions & 1 deletion apps/mobile/app.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@
"icon": "./assets/icon.png",
"supportsTablet": true,
"bundleIdentifier": "com.sentryguard.mobile",
"entitlements": {
"com.apple.developer.usernotifications.critical-alerts": true
},
"infoPlist": {
"ITSAppUsesNonExemptEncryption": false
},
Expand Down Expand Up @@ -65,7 +68,14 @@
"expo-notifications",
{
"icon": "./assets/notification-icon.png",
"color": "#dc2626"
"color": "#dc2626",
"sounds": [
"./assets/sounds/sentry_siren.wav",
"./assets/sounds/cyber_pulse.wav",
"./assets/sounds/tesla_horn.wav",
"./assets/sounds/danger_sonar.wav",
"./assets/sounds/klaxon_alarm.wav"
]
}
],
[
Expand Down
Binary file added apps/mobile/assets/sounds/cyber_pulse.wav
Binary file not shown.
Binary file added apps/mobile/assets/sounds/danger_sonar.wav
Binary file not shown.
Binary file added apps/mobile/assets/sounds/klaxon_alarm.wav
Binary file not shown.
Binary file added apps/mobile/assets/sounds/sentry_siren.wav
Binary file not shown.
Binary file added apps/mobile/assets/sounds/tesla_horn.wav
Binary file not shown.
3 changes: 3 additions & 0 deletions apps/mobile/jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ module.exports = {
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json'],
testMatch: ['<rootDir>/src/**/*(*.)@(spec|test).[jt]s?(x)'],
coverageDirectory: 'test-output/jest/coverage',
moduleNameMapper: {
'\\.(wav|mp3|ogg|caf|aiff|png|jpg|jpeg|gif|svg)$': '<rootDir>/src/testing/file-mock.js',
},
transform: {
'^.+\\.[tj]sx?$': ['ts-jest', { isolatedModules: true, tsconfig: { jsx: 'react-jsx' } }],
},
Expand Down
2 changes: 2 additions & 0 deletions apps/mobile/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
"@tanstack/react-query": "^5.100.6",
"enhanced-resolve": "*",
"expo": "~54.0.35",
"expo-asset": "~12.0.13",
"expo-audio": "~1.1.1",
"expo-blur": "~15.0.8",
"expo-constants": "~18.0.13",
"expo-device": "~8.0.10",
Expand Down
68 changes: 68 additions & 0 deletions apps/mobile/src/core/hooks/useSoundPlayer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { AudioPlayer, createAudioPlayer, setAudioModeAsync } from 'expo-audio';
import { useCallback, useEffect, useRef, useState } from 'react';

export interface SoundPlayerRequirements {
isPlaying: (soundId: string) => boolean;
play: (soundId: string, asset: number) => void;
stop: () => void;
}

export function useSoundPlayer(): SoundPlayerRequirements {
const [playingSoundId, setPlayingSoundId] = useState<string | null>(null);
const playerRef = useRef<AudioPlayer | null>(null);

const cleanupCurrentPlayer = useCallback((): void => {
if (!playerRef.current) {
return;
}
try {
playerRef.current.pause();
playerRef.current.remove();
} catch {
playerRef.current = null;
}
playerRef.current = null;
}, []);

const stop = useCallback((): void => {
cleanupCurrentPlayer();
setPlayingSoundId(null);
}, [cleanupCurrentPlayer]);

const attachFinishListener = useCallback(
(player: AudioPlayer): void => {
player.addListener('playbackStatusUpdate', (status) => {
if (status.didJustFinish) {
stop();
}
});
},
[stop]
);

const play = useCallback(
(soundId: string, asset: number): void => {
stop();
try {
void setAudioModeAsync({ playsInSilentMode: true });
const player = createAudioPlayer(asset);
playerRef.current = player;
setPlayingSoundId(soundId);
attachFinishListener(player);
player.play();
} catch {
stop();
}
},
[attachFinishListener, stop]
);

useEffect(() => () => stop(), [stop]);

const isPlaying = useCallback(
(soundId: string): boolean => playingSoundId === soundId,
[playingSoundId]
);

return { isPlaying, play, stop };
}
5 changes: 5 additions & 0 deletions apps/mobile/src/core/ui/Icon.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,11 @@ const ioniconsFallback: Record<string, keyof typeof Ionicons.glyphMap> = {
'link': 'link',
'eye': 'eye-outline',
'eye.slash': 'eye-off-outline',
'play.fill': 'play',
'stop.fill': 'stop',
'speaker.wave.2.fill': 'volume-high',
'checkmark': 'checkmark',
'checkmark.circle.fill': 'checkmark-circle',
};

const useNativeSymbols = Platform.OS === 'ios';
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { ALERT_SOUNDS, DEFAULT_ALERT_SOUND_ID, resolveAlertSound } from './alert-sounds';

describe('The resolveAlertSound() function', () => {
describe('When a valid sound id is provided', () => {
it('should return the matching alert sound', () => {
const sound = resolveAlertSound('tesla_horn.wav');
expect(sound.id).toBe('tesla_horn.wav');
expect(sound.labelKey).toBe('settings.soundTeslaHorn');
});
});

describe('When an unknown sound id is provided', () => {
it('should fallback to the default alert sound', () => {
const sound = resolveAlertSound('unknown.wav');
expect(sound.id).toBe(DEFAULT_ALERT_SOUND_ID);
});
});

describe('When undefined is provided', () => {
it('should fallback to the default alert sound', () => {
const sound = resolveAlertSound(undefined);
expect(sound.id).toBe(DEFAULT_ALERT_SOUND_ID);
});
});

describe('The ALERT_SOUNDS constant', () => {
it('should contain 5 alert sounds', () => {
expect(ALERT_SOUNDS).toHaveLength(5);
});
});
});
40 changes: 40 additions & 0 deletions apps/mobile/src/features/notifications/domain/alert-sounds.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
export interface AlertSoundItem {
id: string;
labelKey: string;
asset: number;
}

export const DEFAULT_ALERT_SOUND_ID = 'sentry_siren.wav';

export const ALERT_SOUNDS: readonly AlertSoundItem[] = [
{
asset: require('../../../../assets/sounds/sentry_siren.wav'),
id: 'sentry_siren.wav',
labelKey: 'settings.soundSentrySiren',
},
{
asset: require('../../../../assets/sounds/cyber_pulse.wav'),
id: 'cyber_pulse.wav',
labelKey: 'settings.soundCyberPulse',
},
{
asset: require('../../../../assets/sounds/tesla_horn.wav'),
id: 'tesla_horn.wav',
labelKey: 'settings.soundTeslaHorn',
},
{
asset: require('../../../../assets/sounds/danger_sonar.wav'),
id: 'danger_sonar.wav',
labelKey: 'settings.soundDangerSonar',
},
{
asset: require('../../../../assets/sounds/klaxon_alarm.wav'),
id: 'klaxon_alarm.wav',
labelKey: 'settings.soundKlaxonAlarm',
},
] as const;

export function resolveAlertSound(id?: string): AlertSoundItem {
const found = ALERT_SOUNDS.find((sound) => sound.id === id);
return found ?? ALERT_SOUNDS[0];
}
Loading
Loading