Skip to content

Commit 1305eb2

Browse files
notif: Use Zulip's distinct notification sound on Android
Fixes: #340
1 parent 1f9a5c6 commit 1305eb2

File tree

6 files changed

+283
-4
lines changed

6 files changed

+283
-4
lines changed
8.62 KB
Binary file not shown.
8.28 KB
Binary file not shown.
8.66 KB
Binary file not shown.

android/app/src/main/res/raw/keep.xml

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,5 +12,5 @@
1212
https://github.com/zulip/zulip-flutter/issues/528
1313
-->
1414
<resources xmlns:tools="http://schemas.android.com/tools"
15-
tools:keep="@drawable/zulip_notification"
15+
tools:keep="@drawable/zulip_notification,@raw/chime2,@raw/chime3,@raw/chime4"
1616
/>

lib/notifications/display.dart

+120-2
Original file line numberDiff line numberDiff line change
@@ -23,14 +23,57 @@ import '../widgets/theme.dart';
2323

2424
AndroidNotificationHostApi get _androidHost => ZulipBinding.instance.androidNotificationHost;
2525

26+
/// Generates an Android resource uri for the given resource name and type.
27+
///
28+
/// For example, for a resource `@raw/chime3`, where `raw` would be the
29+
/// resource type and `chime3` would be the resource name it generates the
30+
/// following uri:
31+
/// `android.resource://com.zulip.flutter/raw/chime3`
32+
///
33+
/// Based on: https://stackoverflow.com/a/38340580
34+
Uri resourceUriFromName({
35+
required String resourceTypeName,
36+
required String resourceEntryName,
37+
}) {
38+
const packageName = 'com.zulip.flutter'; // TODO(#407)
39+
40+
// Uri scheme for Android resource url.
41+
// See: https://developer.android.com/reference/android/content/ContentResolver#SCHEME_ANDROID_RESOURCE
42+
const schemeAndroidResource = 'android.resource';
43+
44+
return Uri(
45+
scheme: schemeAndroidResource,
46+
host: packageName,
47+
pathSegments: <String>[resourceTypeName, resourceEntryName],
48+
);
49+
}
50+
51+
enum NotificationSound {
52+
// Any new entry here must appear in `keep.xml` too, see #528.
53+
chime2(resourceName: 'chime2', fileDisplayName: 'Zulip - Low Chime.m4a'),
54+
chime3(resourceName: 'chime3', fileDisplayName: 'Zulip - Chime.m4a'),
55+
chime4(resourceName: 'chime4', fileDisplayName: 'Zulip - High Chime.m4a');
56+
57+
const NotificationSound({
58+
required this.resourceName,
59+
required this.fileDisplayName,
60+
});
61+
final String resourceName;
62+
final String fileDisplayName;
63+
}
64+
2665
/// Service for configuring our Android "notification channel".
2766
class NotificationChannelManager {
2867
/// The channel ID we use for our one notification channel, which we use for
2968
/// all notifications.
3069
// TODO(launch) check this doesn't match zulip-mobile's current or previous
3170
// channel IDs
71+
// Previous values: 'messages-1'
3272
@visibleForTesting
33-
static const kChannelId = 'messages-1';
73+
static const kChannelId = 'messages-2';
74+
75+
@visibleForTesting
76+
static const kDefaultNotificationSound = NotificationSound.chime3;
3477

3578
/// The vibration pattern we set for notifications.
3679
// We try to set a vibration pattern that, with the phone in one's pocket,
@@ -39,6 +82,79 @@ class NotificationChannelManager {
3982
@visibleForTesting
4083
static final kVibrationPattern = Int64List.fromList([0, 125, 100, 450]);
4184

85+
/// Prepare our notification sounds; return a URL for our default sound.
86+
///
87+
/// Where possible, this copies each of our notification sounds into shared storage
88+
/// so that the user can choose between them in the system notification settings.
89+
///
90+
/// Returns a URL for our default notification sound: either in shared storage
91+
/// if we successfully copied it there, or else as our internal resource file.
92+
static Future<String> _ensureInitNotificationSounds() async {
93+
String defaultSoundUrl = resourceUriFromName(
94+
resourceTypeName: 'raw',
95+
resourceEntryName: kDefaultNotificationSound.resourceName).toString();
96+
97+
final shouldUseResourceFile = switch (await ZulipBinding.instance.deviceInfo) {
98+
// Before Android 10 Q, we don't attempt to put the sounds in shared media storage.
99+
// Just use the resource file directly.
100+
// TODO(android-sdk-29): Simplify this away.
101+
AndroidDeviceInfo(:var sdkInt) => sdkInt <= 28,
102+
_ => true,
103+
};
104+
if (shouldUseResourceFile) return defaultSoundUrl;
105+
106+
// First, look to see what notification sounds we've already stored,
107+
// and check against our list of sounds we have.
108+
109+
final soundsToAdd = NotificationSound.values.toList();
110+
final storedSounds = await _androidHost.listStoredSoundsInNotificationsDirectory();
111+
for (final storedSound in storedSounds) {
112+
assert(storedSound != null); // TODO(#942)
113+
114+
// If the file is one we put there, and has the name we give to our
115+
// default sound, then use it as the default sound.
116+
if (storedSound!.fileName == kDefaultNotificationSound.fileDisplayName
117+
&& storedSound.isOwner) {
118+
defaultSoundUrl = storedSound.uri;
119+
}
120+
121+
// If it has the name of any of our sounds, then don't try to add
122+
// that sound. This applies even if we didn't put it there: the
123+
// name is taken, so if we tried adding it anyway it'd get some
124+
// other name (like "Zulip - Chime (1).m4a", with " (1)" added).
125+
// Which means the *next* launch would try to add it again ad infinitum.
126+
// We could avoid this given some other way to uniquely identify the
127+
// file, but haven't found an obvious one.
128+
//
129+
// This does mean it's possible the file isn't the one we would have
130+
// put there... but it probably is, just from a debug vs. release build
131+
// of the app (because those have different package names). And anyway,
132+
// this is a file we're supplying for the user in case they want it, not
133+
// something where the app depends on it having specific content.
134+
soundsToAdd.removeWhere((v) => v.fileDisplayName == storedSound.fileName);
135+
}
136+
137+
// If that leaves any sounds we haven't yet put into shared storage
138+
// (e.g., because this is the first run after install, or after an
139+
// upgrade that added a sound), then store those.
140+
141+
for (final sound in soundsToAdd) {
142+
try {
143+
final url = await _androidHost.copySoundResourceToMediaStore(
144+
targetFileDisplayName: sound.fileDisplayName,
145+
sourceResourceName: sound.resourceName);
146+
147+
if (sound == kDefaultNotificationSound) {
148+
defaultSoundUrl = url;
149+
}
150+
} catch (e, st) {
151+
assert(debugLog("$e\n$st")); // TODO(log)
152+
}
153+
}
154+
155+
return defaultSoundUrl;
156+
}
157+
42158
/// Create our notification channel, if it doesn't already exist.
43159
///
44160
/// Deletes obsolete channels, if present, from old versions of the app.
@@ -80,13 +196,15 @@ class NotificationChannelManager {
80196

81197
// The channel doesn't exist. Create it.
82198

199+
final defaultSoundUrl = await _ensureInitNotificationSounds();
200+
83201
await _androidHost.createNotificationChannel(NotificationChannel(
84202
id: kChannelId,
85203
name: 'Messages', // TODO(i18n)
86204
importance: NotificationImportance.high,
87205
lightsEnabled: true,
206+
soundUri: defaultSoundUrl,
88207
vibrationPattern: kVibrationPattern,
89-
// TODO(#340) sound
90208
));
91209
}
92210
}

test/notifications/display_test.dart

+162-1
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import 'package:http/testing.dart' as http_testing;
1313
import 'package:zulip/api/model/model.dart';
1414
import 'package:zulip/api/notifications.dart';
1515
import 'package:zulip/host/android_notifications.dart';
16+
import 'package:zulip/model/binding.dart';
1617
import 'package:zulip/model/localizations.dart';
1718
import 'package:zulip/model/narrow.dart';
1819
import 'package:zulip/model/store.dart';
@@ -129,7 +130,8 @@ void main() {
129130
..name.equals('Messages')
130131
..importance.equals(NotificationImportance.high)
131132
..lightsEnabled.equals(true)
132-
..soundUri.isNull()
133+
..soundUri.equals(testBinding.androidNotificationHost.fakeStoredNotificationSoundUri(
134+
NotificationChannelManager.kDefaultNotificationSound.resourceName))
133135
..vibrationPattern.isNotNull().deepEquals(
134136
NotificationChannelManager.kVibrationPattern)
135137
;
@@ -209,6 +211,160 @@ void main() {
209211
..vibrationPattern.isNotNull().deepEquals(
210212
NotificationChannelManager.kVibrationPattern);
211213
});
214+
215+
test('on Android 28 (and lower) resource file is used for notification sound', () async {
216+
addTearDown(testBinding.reset);
217+
final androidNotificationHost = testBinding.androidNotificationHost;
218+
219+
// Override android version
220+
testBinding.deviceInfoResult =
221+
const AndroidDeviceInfo(sdkInt: 28, release: '10');
222+
223+
// Ensure that on Android 10, notification sounds aren't being copied to
224+
// the media store, and resource file is used directly.
225+
await NotificationChannelManager.ensureChannel();
226+
check(androidNotificationHost.takeCopySoundResourceToMediaStoreCalls()).length.equals(0);
227+
228+
final defaultSoundResourceName =
229+
NotificationChannelManager.kDefaultNotificationSound.resourceName;
230+
// Android resource uri.
231+
final soundUri =
232+
'android.resource://com.zulip.flutter/raw/$defaultSoundResourceName';
233+
check(androidNotificationHost.takeCreatedChannels()).single
234+
..id.equals(NotificationChannelManager.kChannelId)
235+
..name.equals('Messages')
236+
..importance.equals(NotificationImportance.high)
237+
..lightsEnabled.equals(true)
238+
..soundUri.equals(soundUri)
239+
..vibrationPattern.isNotNull().deepEquals(
240+
NotificationChannelManager.kVibrationPattern);
241+
});
242+
243+
test('notification sound resource files are being copied to the media store', () async {
244+
addTearDown(testBinding.reset);
245+
final androidNotificationHost = testBinding.androidNotificationHost;
246+
247+
await NotificationChannelManager.ensureChannel();
248+
check(androidNotificationHost.takeCopySoundResourceToMediaStoreCalls())
249+
.deepEquals(NotificationSound.values.map((e) => (
250+
sourceResourceName: e.resourceName,
251+
targetFileDisplayName: e.fileDisplayName),
252+
));
253+
254+
// Ensure the default source uri points to a file in the media store,
255+
// rather than a resource file.
256+
final defaultSoundResourceName =
257+
NotificationChannelManager.kDefaultNotificationSound.resourceName;
258+
final soundUri =
259+
androidNotificationHost.fakeStoredNotificationSoundUri(defaultSoundResourceName);
260+
check(androidNotificationHost.takeCreatedChannels()).single
261+
..id.equals(NotificationChannelManager.kChannelId)
262+
..name.equals('Messages')
263+
..importance.equals(NotificationImportance.high)
264+
..lightsEnabled.equals(true)
265+
..soundUri.equals(soundUri)
266+
..vibrationPattern.isNotNull().deepEquals(
267+
NotificationChannelManager.kVibrationPattern);
268+
});
269+
270+
test('notification sounds are not copied again if they were previously copied', () async {
271+
addTearDown(testBinding.reset);
272+
final androidNotificationHost = testBinding.androidNotificationHost;
273+
274+
// Emulate that all notifications sounds are already in the media store.
275+
androidNotificationHost.setupStoredNotificationSounds(
276+
NotificationSound.values.map((e) => StoredNotificationsSound(
277+
fileName: e.fileDisplayName,
278+
isOwner: true,
279+
uri: androidNotificationHost.fakeStoredNotificationSoundUri(e.resourceName)),
280+
).toList(),
281+
);
282+
283+
await NotificationChannelManager.ensureChannel();
284+
check(androidNotificationHost.takeCopySoundResourceToMediaStoreCalls()).length.equals(0);
285+
286+
final defaultSoundResourceName =
287+
NotificationChannelManager.kDefaultNotificationSound.resourceName;
288+
final soundUri =
289+
androidNotificationHost.fakeStoredNotificationSoundUri(defaultSoundResourceName);
290+
check(androidNotificationHost.takeCreatedChannels()).single
291+
..id.equals(NotificationChannelManager.kChannelId)
292+
..name.equals('Messages')
293+
..importance.equals(NotificationImportance.high)
294+
..lightsEnabled.equals(true)
295+
..soundUri.equals(soundUri)
296+
..vibrationPattern.isNotNull().deepEquals(
297+
NotificationChannelManager.kVibrationPattern);
298+
});
299+
300+
test('new notifications sounds are copied to media store', () async {
301+
addTearDown(testBinding.reset);
302+
final androidNotificationHost = testBinding.androidNotificationHost;
303+
304+
// Emulate that except one sound, all other sounds are already in
305+
// media store.
306+
androidNotificationHost.setupStoredNotificationSounds(
307+
NotificationSound.values.map((e) => StoredNotificationsSound(
308+
fileName: e.fileDisplayName,
309+
isOwner: true,
310+
uri: androidNotificationHost.fakeStoredNotificationSoundUri(e.resourceName)),
311+
).skip(1).toList()
312+
);
313+
314+
await NotificationChannelManager.ensureChannel();
315+
final firstSound = NotificationSound.values.first;
316+
check(androidNotificationHost.takeCopySoundResourceToMediaStoreCalls())
317+
.single
318+
..sourceResourceName.equals(firstSound.resourceName)
319+
..targetFileDisplayName.equals(firstSound.fileDisplayName);
320+
321+
final defaultSoundResourceName =
322+
NotificationChannelManager.kDefaultNotificationSound.resourceName;
323+
final soundUri =
324+
androidNotificationHost.fakeStoredNotificationSoundUri(defaultSoundResourceName);
325+
check(androidNotificationHost.takeCreatedChannels()).single
326+
..id.equals(NotificationChannelManager.kChannelId)
327+
..name.equals('Messages')
328+
..importance.equals(NotificationImportance.high)
329+
..lightsEnabled.equals(true)
330+
..soundUri.equals(soundUri)
331+
..vibrationPattern.isNotNull().deepEquals(
332+
NotificationChannelManager.kVibrationPattern);
333+
});
334+
335+
test('no recopying of existing notification sounds in the media store; default sound uri points to resource file', () async {
336+
addTearDown(testBinding.reset);
337+
final androidNotificationHost = testBinding.androidNotificationHost;
338+
339+
androidNotificationHost.setupStoredNotificationSounds(
340+
NotificationSound.values.map((e) => StoredNotificationsSound(
341+
fileName: e.fileDisplayName,
342+
isOwner: false,
343+
uri: androidNotificationHost.fakeStoredNotificationSoundUri(e.resourceName)),
344+
).toList()
345+
);
346+
347+
// Ensure that if a notification sound with the same name already exists
348+
// in the media store, but it wasn't copied by us, no recopying should
349+
// happen. Additionally, the default sound uri should point to the
350+
// resource file, not the version in the media store.
351+
await NotificationChannelManager.ensureChannel();
352+
check(androidNotificationHost.takeCopySoundResourceToMediaStoreCalls()).length.equals(0);
353+
354+
final defaultSoundResourceName =
355+
NotificationChannelManager.kDefaultNotificationSound.resourceName;
356+
// Android resource uri.
357+
final soundUri =
358+
'android.resource://com.zulip.flutter/raw/$defaultSoundResourceName';
359+
check(androidNotificationHost.takeCreatedChannels()).single
360+
..id.equals(NotificationChannelManager.kChannelId)
361+
..name.equals('Messages')
362+
..importance.equals(NotificationImportance.high)
363+
..lightsEnabled.equals(true)
364+
..soundUri.equals(soundUri)
365+
..vibrationPattern.isNotNull().deepEquals(
366+
NotificationChannelManager.kVibrationPattern);
367+
});
212368
});
213369

214370
group('NotificationDisplayManager show', () {
@@ -1182,6 +1338,11 @@ void main() {
11821338
});
11831339
}
11841340

1341+
extension on Subject<CopySoundResourceToMediaStoreCall> {
1342+
Subject<String> get targetFileDisplayName => has((x) => x.targetFileDisplayName, 'targetFileDisplayName');
1343+
Subject<String> get sourceResourceName => has((x) => x.sourceResourceName, 'sourceResourceName');
1344+
}
1345+
11851346
extension NotificationChannelChecks on Subject<NotificationChannel> {
11861347
Subject<String> get id => has((x) => x.id, 'id');
11871348
Subject<int> get importance => has((x) => x.importance, 'importance');

0 commit comments

Comments
 (0)