Skip to content
This repository has been archived by the owner on Sep 11, 2024. It is now read-only.

Custom notification sounds for rooms #2928

Merged
merged 27 commits into from
Jun 3, 2019
Merged
Show file tree
Hide file tree
Changes from 20 commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
f14d96e
Look in room account data for custom notif sounds
Half-Shot Apr 19, 2019
b0bacdb
Simplyify
Half-Shot Apr 19, 2019
cd86471
Support account level custom sounds too
Half-Shot Apr 19, 2019
63ab773
Add a fancy room tab and uploader
Half-Shot Apr 19, 2019
d33df45
Linting
Half-Shot Apr 19, 2019
776210c
Use settings store
Half-Shot Apr 19, 2019
b11050d
Check for sound before logging it
k80w Apr 21, 2019
0f2cd6e
Stick behind a feature flag
Half-Shot Apr 21, 2019
8258e93
Use m.notification.sound
Half-Shot Apr 21, 2019
874b61e
Merge branch 'hs/custom-notif-sounds' of github.com:Half-Shot/matrix-…
Half-Shot Apr 21, 2019
9de8920
Remove trailing space
Half-Shot Apr 22, 2019
020d210
Use uk.half-shot.*
Half-Shot Apr 23, 2019
efc93ab
Merge branch 'develop' into hs/custom-notif-sounds
Half-Shot May 7, 2019
2023b3d
Merge remote-tracking branch 'upstream/develop' into hs/custom-notif-…
Half-Shot May 12, 2019
64a3844
Resolve issues
Half-Shot May 12, 2019
e8c8762
Merge branch 'develop' into hs/custom-notif-sounds
Half-Shot May 13, 2019
626cb46
Cleanup interface buttons
Half-Shot May 14, 2019
46132a2
Merge branch 'hs/custom-notif-sounds' of github.com:Half-Shot/matrix-…
Half-Shot May 14, 2019
277c4ab
Merge branch 'develop' into hs/custom-notif-sounds
Half-Shot May 14, 2019
079bdd4
Update il8n
Half-Shot May 14, 2019
d752de0
Improve UX
Half-Shot May 15, 2019
2994d99
Merge branch 'develop' into hs/custom-notif-sounds
Half-Shot May 15, 2019
9369e96
Merge remote-tracking branch 'upstream/develop' into hs/custom-notif-…
Half-Shot May 31, 2019
96c20ea
Add missing keys to notif sound setting
Half-Shot May 31, 2019
300095f
Remove labs flag for custom notif sounds
Half-Shot Jun 3, 2019
673a8fc
Update src/Notifier.js
Half-Shot Jun 3, 2019
721607b
Remove whitespace
Half-Shot Jun 3, 2019
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
8 changes: 8 additions & 0 deletions res/css/views/settings/_Notifications.scss
Original file line number Diff line number Diff line change
Expand Up @@ -71,3 +71,11 @@ limitations under the License.
.mx_UserNotifSettings_notifTable .mx_Spinner {
position: absolute;
}

.mx_NotificationSound_soundUpload {
display: none;
}

.mx_NotificationSound_resetSound {
margin-left: 5px;
}
53 changes: 49 additions & 4 deletions src/Notifier.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,10 +96,55 @@ const Notifier = {
}
},

_playAudioNotification: function(ev, room) {
const e = document.getElementById("messageAudio");
if (e) {
e.play();
getSoundForRoom: async function(roomId) {
// We do no caching here because the SDK caches setting
// and the browser will cache the sound.
let content = SettingsStore.getValue("notificationSound", roomId);
if (!content) {
return null;
}

if (!content.url) {
console.warn(`${roomId} has custom notification sound event, but no url key`);
return null;
}

if (!content.url.startsWith("mxc://")) {
console.warn(`${roomId} has custom notification sound event, but url is not a mxc url`);
return null;
}

// Ideally in here we could use MSC1310 to detect the type of file, and reject it.

return {
url: MatrixClientPeg.get().mxcUrlToHttp(content.url),
name: content.name,
type: content.type,
size: content.size,
};
},

_playAudioNotification: async function(ev, room) {
const sound = SettingsStore.isFeatureEnabled("feature_notification_sounds") ? await this.getSoundForRoom(room.roomId) : null;
console.log(`Got sound ${sound && sound.name || "default"} for ${room.roomId}`);

try {
const selector = document.querySelector(sound ? `audio[src='${sound.url}']` : "#messageAudio");
let audioElement = selector;
if (!selector) {
if (!sound) {
console.error("Tried to play alert sound but missing #messageAudio");
Half-Shot marked this conversation as resolved.
Show resolved Hide resolved
return;
}
audioElement = new Audio(sound.url);
if (sound.type) {
audioElement.type = sound.type;
}
document.body.appendChild(audioElement);
}
audioElement.play();
} catch (ex) {
console.warn("Caught error when trying to fetch room notification sound:", ex);
}
},

Expand Down
11 changes: 11 additions & 0 deletions src/components/views/dialogs/RoomSettingsDialog.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,10 @@ import AdvancedRoomSettingsTab from "../settings/tabs/room/AdvancedRoomSettingsT
import RolesRoomSettingsTab from "../settings/tabs/room/RolesRoomSettingsTab";
import GeneralRoomSettingsTab from "../settings/tabs/room/GeneralRoomSettingsTab";
import SecurityRoomSettingsTab from "../settings/tabs/room/SecurityRoomSettingsTab";
import NotificationSettingsTab from "../settings/tabs/room/NotificationSettingsTab";
import sdk from "../../../index";
import MatrixClientPeg from "../../../MatrixClientPeg";
import SettingsStore from '../../../settings/SettingsStore';
import dis from "../../../dispatcher";

export default class RoomSettingsDialog extends React.Component {
Expand Down Expand Up @@ -67,6 +69,15 @@ export default class RoomSettingsDialog extends React.Component {
"mx_RoomSettingsDialog_rolesIcon",
<RolesRoomSettingsTab roomId={this.props.roomId} />,
));

Half-Shot marked this conversation as resolved.
Show resolved Hide resolved
if (SettingsStore.isFeatureEnabled("feature_notification_sounds")) {
tabs.push(new Tab(
_td("Notifications"),
"mx_RoomSettingsDialog_rolesIcon",
<NotificationSettingsTab roomId={this.props.roomId} />,
));
}

tabs.push(new Tab(
_td("Advanced"),
"mx_RoomSettingsDialog_warningIcon",
Expand Down
158 changes: 158 additions & 0 deletions src/components/views/settings/tabs/room/NotificationSettingsTab.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
/*
Copyright 2019 New Vector Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import React from 'react';
import PropTypes from 'prop-types';
import {_t} from "../../../../../languageHandler";
import MatrixClientPeg from "../../../../../MatrixClientPeg";
import AccessibleButton from "../../../elements/AccessibleButton";
import Notifier from "../../../../../Notifier";
import SettingsStore from '../../../../../settings/SettingsStore';
import { SettingLevel } from '../../../../../settings/SettingsStore';

export default class NotificationsSettingsTab extends React.Component {
static propTypes = {
roomId: PropTypes.string.isRequired,
};

constructor() {
super();

this.state = {
currentSound: "default",
uploadedFile: null,
};
}

componentWillMount() {
Notifier.getSoundForRoom(this.props.roomId).then((soundData) => {
if (!soundData) {
return;
}
this.setState({currentSound: soundData.name || soundData.url});
});
}

async _triggerUploader(e) {
e.stopPropagation();
e.preventDefault();

this.refs.soundUpload.click();
}

async _onSoundUploadChanged(e) {
if (!e.target.files || !e.target.files.length) {
this.setState({
uploadedFile: null,
});
return;
}

const file = e.target.files[0];
this.setState({
uploadedFile: file,
});

try {
await this._saveSound();
} catch (ex) {
console.error(
`Unable to save notification sound for ${this.props.roomId}`,
ex,
);
}
}

async _saveSound() {
if (!this.state.uploadedFile) {
return;
}
let type = this.state.uploadedFile.type;
if (type === "video/ogg") {
// XXX: I've observed browsers allowing users to pick a audio/ogg files,
// and then calling it a video/ogg. This is a lame hack, but man browsers
// suck at detecting mimetypes.
type = "audio/ogg";
}
const url = await MatrixClientPeg.get().uploadContent(
this.state.uploadedFile, {
type,
},
);

await SettingsStore.setValue(
"notificationSound",
this.props.roomId,
SettingsStore.
SettingLevel.ROOM_ACCOUNT,
{
name: this.state.uploadedFile.name,
type: type,
size: this.state.uploadedFile.size,
url,
},
);

this.setState({
uploadedFile: null,
uploadedFileUrl: null,
currentSound: this.state.uploadedFile.name,
});
}

_clearSound(e) {
e.stopPropagation();
e.preventDefault();
SettingsStore.setValue(
"notificationSound",
this.props.roomId,
SettingLevel.ROOM_ACCOUNT,
null,
);

this.setState({
currentSound: "default",
});
}

render() {
return (
<div className="mx_SettingsTab">
<div className="mx_SettingsTab_heading">{_t("Notifications")}</div>
<div className='mx_SettingsTab_section mx_SettingsTab_subsectionText'>
<span className='mx_SettingsTab_subheading'>{_t("Sounds")}</span>
<div>
<span>{_t("Custom Notification Sounds")}: <code>{this.state.currentSound}</code></span>
</div>
<div>
<h3>{_t("Set a new custom sound")}</h3>
<form autoComplete={false} noValidate={true}>
<input ref="soundUpload" className="mx_NotificationSound_soundUpload" type="file" onChange={this._onSoundUploadChanged.bind(this)} accept="audio/*" />
</form>

<AccessibleButton onClick={this._triggerUploader.bind(this)} kind="primary">
{_t("Browse")}
</AccessibleButton>

<AccessibleButton className="mx_NotificationSound_resetSound" onClick={this._clearSound.bind(this)} kind="primary">
{_t("Reset")}
</AccessibleButton>
</div>
</div>
</div>
);
}
}
5 changes: 5 additions & 0 deletions src/i18n/strings/en_EN.json
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,7 @@
"Show recent room avatars above the room list": "Show recent room avatars above the room list",
"Group & filter rooms by custom tags (refresh to apply changes)": "Group & filter rooms by custom tags (refresh to apply changes)",
"Render simple counters in room header": "Render simple counters in room header",
"Custom Notification Sounds": "Custom Notification Sounds",
"React to messages with emoji (refresh to apply changes)": "React to messages with emoji (refresh to apply changes)",
"Enable Emoji suggestions while typing": "Enable Emoji suggestions while typing",
"Use compact timeline layout": "Use compact timeline layout",
Expand Down Expand Up @@ -616,6 +617,10 @@
"Room Addresses": "Room Addresses",
"Publish this room to the public in %(domain)s's room directory?": "Publish this room to the public in %(domain)s's room directory?",
"URL Previews": "URL Previews",
"Sounds": "Sounds",
"Set a new custom sound": "Set a new custom sound",
"Browse": "Browse",
"Reset": "Reset",
"Change room avatar": "Change room avatar",
"Change room name": "Change room name",
"Change main address for the room": "Change main address for the room",
Expand Down
9 changes: 9 additions & 0 deletions src/settings/Settings.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import ThemeController from './controllers/ThemeController';

// These are just a bunch of helper arrays to avoid copy/pasting a bunch of times
const LEVELS_ROOM_SETTINGS = ['device', 'room-device', 'room-account', 'account', 'config'];
const LEVELS_ROOM_OR_ACCOUNT = ['room-account', 'account'];
const LEVELS_ROOM_SETTINGS_WITH_ROOM = ['device', 'room-device', 'room-account', 'account', 'config', 'room'];
const LEVELS_ACCOUNT_SETTINGS = ['device', 'account', 'config'];
const LEVELS_FEATURE = ['device', 'config'];
Expand Down Expand Up @@ -118,6 +119,10 @@ export const SETTINGS = {
supportedLevels: LEVELS_FEATURE,
default: false,
},
"feature_notification_sounds": {
isFeature: true,
displayName: _td("Custom Notification Sounds"),
Half-Shot marked this conversation as resolved.
Show resolved Hide resolved
},
"feature_reactions": {
isFeature: true,
displayName: _td("React to messages with emoji (refresh to apply changes)"),
Expand Down Expand Up @@ -321,6 +326,10 @@ export const SETTINGS = {
default: false,
controller: new NotificationsEnabledController(),
},
"notificationSound": {
supportedLevels: LEVELS_ROOM_OR_ACCOUNT,
default: false,
},
"notificationBodyEnabled": {
supportedLevels: LEVELS_DEVICE_ONLY_SETTINGS,
default: true,
Expand Down
4 changes: 4 additions & 0 deletions src/settings/handlers/AccountSettingsHandler.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,10 @@ export default class AccountSettingsHandler extends MatrixClientBackedSettingsHa
return !content['disable'];
}

if (settingName === "notificationSound") {
return this._getSettings("uk.half-shot.notification.sound");
}

// Special case for breadcrumbs
if (settingName === "breadcrumb_rooms") {
const content = this._getSettings(BREADCRUMBS_EVENT_TYPE) || {};
Expand Down
4 changes: 4 additions & 0 deletions src/settings/handlers/RoomSettingsHandler.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,10 @@ export default class RoomSettingsHandler extends MatrixClientBackedSettingsHandl
return !content['disable'];
}

if (settingName === "notificationSound") {
return this._getSettings(roomId, "uk.half-shot.notification.sound");
}

const settings = this._getSettings(roomId) || {};
return settings[settingName];
}
Expand Down