Merge branch 'develop' into katex

This commit is contained in:
Aleks Kissinger 2020-10-10 19:31:46 +01:00
commit aafaf34233
157 changed files with 6534 additions and 4828 deletions

View file

@ -30,6 +30,7 @@ import {Notifier} from "../Notifier";
import type {Renderer} from "react-dom";
import RightPanelStore from "../stores/RightPanelStore";
import WidgetStore from "../stores/WidgetStore";
import CallHandler from "../CallHandler";
declare global {
interface Window {
@ -53,6 +54,7 @@ declare global {
mxNotifier: typeof Notifier;
mxRightPanelStore: RightPanelStore;
mxWidgetStore: WidgetStore;
mxCallHandler: CallHandler;
}
interface Document {
@ -62,6 +64,9 @@ declare global {
interface Navigator {
userLanguage?: string;
// https://github.com/Microsoft/TypeScript/issues/19473
// https://developer.mozilla.org/en-US/docs/Web/API/MediaSession
mediaSession: any;
}
interface StorageEstimate {

View file

@ -0,0 +1,23 @@
/*
Copyright 2020 The Matrix.org Foundation C.I.C.
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 sanitizeHtml from 'sanitize-html';
export interface IExtendedSanitizeOptions extends sanitizeHtml.IOptions {
// This option only exists in 2.x RCs so far, so not yet present in the
// separate type definition module.
nestingLimit?: number;
}

View file

@ -82,6 +82,7 @@ function urlForColor(color) {
const colorToDataURLCache = new Map();
export function defaultAvatarUrlForString(s) {
if (!s) return ""; // XXX: should never happen but empirically does by evidence of a rageshake
const defaultColors = ['#0DBD8B', '#368bd6', '#ac3ba8'];
let total = 0;
for (let i = 0; i < s.length; ++i) {

View file

@ -1,526 +0,0 @@
/*
Copyright 2015, 2016 OpenMarket Ltd
Copyright 2017, 2018 New Vector Ltd
Copyright 2019, 2020 The Matrix.org Foundation C.I.C.
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.
*/
/*
* Manages a list of all the currently active calls.
*
* This handler dispatches when voip calls are added/updated/removed from this list:
* {
* action: 'call_state'
* room_id: <room ID of the call>
* }
*
* To know the state of the call, this handler exposes a getter to
* obtain the call for a room:
* var call = CallHandler.getCall(roomId)
* var state = call.call_state; // ringing|ringback|connected|ended|busy|stop_ringback|stop_ringing
*
* This handler listens for and handles the following actions:
* {
* action: 'place_call',
* type: 'voice|video',
* room_id: <room that the place call button was pressed in>
* }
*
* {
* action: 'incoming_call'
* call: MatrixCall
* }
*
* {
* action: 'hangup'
* room_id: <room that the hangup button was pressed in>
* }
*
* {
* action: 'answer'
* room_id: <room that the answer button was pressed in>
* }
*/
import {MatrixClientPeg} from './MatrixClientPeg';
import PlatformPeg from './PlatformPeg';
import Modal from './Modal';
import { _t } from './languageHandler';
import Matrix from 'matrix-js-sdk';
import dis from './dispatcher/dispatcher';
import WidgetUtils from './utils/WidgetUtils';
import WidgetEchoStore from './stores/WidgetEchoStore';
import SettingsStore from './settings/SettingsStore';
import {generateHumanReadableId} from "./utils/NamingUtils";
import {Jitsi} from "./widgets/Jitsi";
import {WidgetType} from "./widgets/WidgetType";
import {SettingLevel} from "./settings/SettingLevel";
import {base32} from "rfc4648";
import QuestionDialog from "./components/views/dialogs/QuestionDialog";
import ErrorDialog from "./components/views/dialogs/ErrorDialog";
global.mxCalls = {
//room_id: MatrixCall
};
const calls = global.mxCalls;
let ConferenceHandler = null;
const audioPromises = {};
function play(audioId) {
// TODO: Attach an invisible element for this instead
// which listens?
const audio = document.getElementById(audioId);
if (audio) {
const playAudio = async () => {
try {
// This still causes the chrome debugger to break on promise rejection if
// the promise is rejected, even though we're catching the exception.
await audio.play();
} catch (e) {
// This is usually because the user hasn't interacted with the document,
// or chrome doesn't think so and is denying the request. Not sure what
// we can really do here...
// https://github.com/vector-im/element-web/issues/7657
console.log("Unable to play audio clip", e);
}
};
if (audioPromises[audioId]) {
audioPromises[audioId] = audioPromises[audioId].then(()=>{
audio.load();
return playAudio();
});
} else {
audioPromises[audioId] = playAudio();
}
}
}
function pause(audioId) {
// TODO: Attach an invisible element for this instead
// which listens?
const audio = document.getElementById(audioId);
if (audio) {
if (audioPromises[audioId]) {
audioPromises[audioId] = audioPromises[audioId].then(()=>audio.pause());
} else {
// pause doesn't actually return a promise, but might as well do this for symmetry with play();
audioPromises[audioId] = audio.pause();
}
}
}
function _setCallListeners(call) {
call.on("error", function(err) {
console.error("Call error:", err);
if (
MatrixClientPeg.get().getTurnServers().length === 0 &&
SettingsStore.getValue("fallbackICEServerAllowed") === null
) {
_showICEFallbackPrompt();
return;
}
Modal.createTrackedDialog('Call Failed', '', ErrorDialog, {
title: _t('Call Failed'),
description: err.message,
});
});
call.on("hangup", function() {
_setCallState(undefined, call.roomId, "ended");
});
// map web rtc states to dummy UI state
// ringing|ringback|connected|ended|busy|stop_ringback|stop_ringing
call.on("state", function(newState, oldState) {
if (newState === "ringing") {
_setCallState(call, call.roomId, "ringing");
pause("ringbackAudio");
} else if (newState === "invite_sent") {
_setCallState(call, call.roomId, "ringback");
play("ringbackAudio");
} else if (newState === "ended" && oldState === "connected") {
_setCallState(undefined, call.roomId, "ended");
pause("ringbackAudio");
play("callendAudio");
} else if (newState === "ended" && oldState === "invite_sent" &&
(call.hangupParty === "remote" ||
(call.hangupParty === "local" && call.hangupReason === "invite_timeout")
)) {
_setCallState(call, call.roomId, "busy");
pause("ringbackAudio");
play("busyAudio");
Modal.createTrackedDialog('Call Handler', 'Call Timeout', ErrorDialog, {
title: _t('Call Timeout'),
description: _t('The remote side failed to pick up') + '.',
});
} else if (oldState === "invite_sent") {
_setCallState(call, call.roomId, "stop_ringback");
pause("ringbackAudio");
} else if (oldState === "ringing") {
_setCallState(call, call.roomId, "stop_ringing");
pause("ringbackAudio");
} else if (newState === "connected") {
_setCallState(call, call.roomId, "connected");
pause("ringbackAudio");
}
});
}
function _setCallState(call, roomId, status) {
console.log(
`Call state in ${roomId} changed to ${status} (${call ? call.call_state : "-"})`,
);
calls[roomId] = call;
if (status === "ringing") {
play("ringAudio");
} else if (call && call.call_state === "ringing") {
pause("ringAudio");
}
if (call) {
call.call_state = status;
}
dis.dispatch({
action: 'call_state',
room_id: roomId,
state: status,
});
}
function _showICEFallbackPrompt() {
const cli = MatrixClientPeg.get();
const code = sub => <code>{sub}</code>;
Modal.createTrackedDialog('No TURN servers', '', QuestionDialog, {
title: _t("Call failed due to misconfigured server"),
description: <div>
<p>{_t(
"Please ask the administrator of your homeserver " +
"(<code>%(homeserverDomain)s</code>) to configure a TURN server in " +
"order for calls to work reliably.",
{ homeserverDomain: cli.getDomain() }, { code },
)}</p>
<p>{_t(
"Alternatively, you can try to use the public server at " +
"<code>turn.matrix.org</code>, but this will not be as reliable, and " +
"it will share your IP address with that server. You can also manage " +
"this in Settings.",
null, { code },
)}</p>
</div>,
button: _t('Try using turn.matrix.org'),
cancelButton: _t('OK'),
onFinished: (allow) => {
SettingsStore.setValue("fallbackICEServerAllowed", null, SettingLevel.DEVICE, allow);
cli.setFallbackICEServerAllowed(allow);
},
}, null, true);
}
function _onAction(payload) {
function placeCall(newCall) {
_setCallListeners(newCall);
if (payload.type === 'voice') {
newCall.placeVoiceCall();
} else if (payload.type === 'video') {
newCall.placeVideoCall(
payload.remote_element,
payload.local_element,
);
} else if (payload.type === 'screensharing') {
const screenCapErrorString = PlatformPeg.get().screenCaptureErrorString();
if (screenCapErrorString) {
_setCallState(undefined, newCall.roomId, "ended");
console.log("Can't capture screen: " + screenCapErrorString);
Modal.createTrackedDialog('Call Handler', 'Unable to capture screen', ErrorDialog, {
title: _t('Unable to capture screen'),
description: screenCapErrorString,
});
return;
}
newCall.placeScreenSharingCall(
payload.remote_element,
payload.local_element,
);
} else {
console.error("Unknown conf call type: %s", payload.type);
}
}
switch (payload.action) {
case 'place_call':
{
if (callHandler.getAnyActiveCall()) {
Modal.createTrackedDialog('Call Handler', 'Existing Call', ErrorDialog, {
title: _t('Existing Call'),
description: _t('You are already in a call.'),
});
return; // don't allow >1 call to be placed.
}
// if the runtime env doesn't do VoIP, whine.
if (!MatrixClientPeg.get().supportsVoip()) {
Modal.createTrackedDialog('Call Handler', 'VoIP is unsupported', ErrorDialog, {
title: _t('VoIP is unsupported'),
description: _t('You cannot place VoIP calls in this browser.'),
});
return;
}
const room = MatrixClientPeg.get().getRoom(payload.room_id);
if (!room) {
console.error("Room %s does not exist.", payload.room_id);
return;
}
const members = room.getJoinedMembers();
if (members.length <= 1) {
Modal.createTrackedDialog('Call Handler', 'Cannot place call with self', ErrorDialog, {
description: _t('You cannot place a call with yourself.'),
});
return;
} else if (members.length === 2) {
console.info("Place %s call in %s", payload.type, payload.room_id);
const call = Matrix.createNewMatrixCall(MatrixClientPeg.get(), payload.room_id);
placeCall(call);
} else { // > 2
dis.dispatch({
action: "place_conference_call",
room_id: payload.room_id,
type: payload.type,
remote_element: payload.remote_element,
local_element: payload.local_element,
});
}
}
break;
case 'place_conference_call':
console.info("Place conference call in %s", payload.room_id);
_startCallApp(payload.room_id, payload.type);
break;
case 'incoming_call':
{
if (callHandler.getAnyActiveCall()) {
// ignore multiple incoming calls. in future, we may want a line-1/line-2 setup.
// we avoid rejecting with "busy" in case the user wants to answer it on a different device.
// in future we could signal a "local busy" as a warning to the caller.
// see https://github.com/vector-im/vector-web/issues/1964
return;
}
// if the runtime env doesn't do VoIP, stop here.
if (!MatrixClientPeg.get().supportsVoip()) {
return;
}
const call = payload.call;
_setCallListeners(call);
_setCallState(call, call.roomId, "ringing");
}
break;
case 'hangup':
if (!calls[payload.room_id]) {
return; // no call to hangup
}
calls[payload.room_id].hangup();
_setCallState(null, payload.room_id, "ended");
break;
case 'answer':
if (!calls[payload.room_id]) {
return; // no call to answer
}
calls[payload.room_id].answer();
_setCallState(calls[payload.room_id], payload.room_id, "connected");
dis.dispatch({
action: "view_room",
room_id: payload.room_id,
});
break;
}
}
async function _startCallApp(roomId, type) {
dis.dispatch({
action: 'appsDrawer',
show: true,
});
const room = MatrixClientPeg.get().getRoom(roomId);
const currentJitsiWidgets = WidgetUtils.getRoomWidgetsOfType(room, WidgetType.JITSI);
if (WidgetEchoStore.roomHasPendingWidgetsOfType(roomId, currentJitsiWidgets, WidgetType.JITSI)) {
Modal.createTrackedDialog('Call already in progress', '', ErrorDialog, {
title: _t('Call in Progress'),
description: _t('A call is currently being placed!'),
});
return;
}
if (currentJitsiWidgets.length > 0) {
console.warn(
"Refusing to start conference call widget in " + roomId +
" a conference call widget is already present",
);
if (WidgetUtils.canUserModifyWidgets(roomId)) {
Modal.createTrackedDialog('Already have Jitsi Widget', '', QuestionDialog, {
title: _t('End Call'),
description: _t('Remove the group call from the room?'),
button: _t('End Call'),
cancelButton: _t('Cancel'),
onFinished: (endCall) => {
if (endCall) {
WidgetUtils.setRoomWidget(roomId, currentJitsiWidgets[0].getContent()['id']);
}
},
});
} else {
Modal.createTrackedDialog('Already have Jitsi Widget', '', ErrorDialog, {
title: _t('Call in Progress'),
description: _t("You don't have permission to remove the call from the room"),
});
}
return;
}
const jitsiDomain = Jitsi.getInstance().preferredDomain;
const jitsiAuth = await Jitsi.getInstance().getJitsiAuth();
let confId;
if (jitsiAuth === 'openidtoken-jwt') {
// Create conference ID from room ID
// For compatibility with Jitsi, use base32 without padding.
// More details here:
// https://github.com/matrix-org/prosody-mod-auth-matrix-user-verification
confId = base32.stringify(Buffer.from(roomId), { pad: false });
} else {
// Create a random human readable conference ID
confId = `JitsiConference${generateHumanReadableId()}`;
}
let widgetUrl = WidgetUtils.getLocalJitsiWrapperUrl({auth: jitsiAuth});
// TODO: Remove URL hacks when the mobile clients eventually support v2 widgets
const parsedUrl = new URL(widgetUrl);
parsedUrl.search = ''; // set to empty string to make the URL class use searchParams instead
parsedUrl.searchParams.set('confId', confId);
widgetUrl = parsedUrl.toString();
const widgetData = {
conferenceId: confId,
isAudioOnly: type === 'voice',
domain: jitsiDomain,
auth: jitsiAuth,
};
const widgetId = (
'jitsi_' +
MatrixClientPeg.get().credentials.userId +
'_' +
Date.now()
);
WidgetUtils.setRoomWidget(roomId, widgetId, WidgetType.JITSI, widgetUrl, 'Jitsi', widgetData).then(() => {
console.log('Jitsi widget added');
}).catch((e) => {
if (e.errcode === 'M_FORBIDDEN') {
Modal.createTrackedDialog('Call Failed', '', ErrorDialog, {
title: _t('Permission Required'),
description: _t("You do not have permission to start a conference call in this room"),
});
}
console.error(e);
});
}
// FIXME: Nasty way of making sure we only register
// with the dispatcher once
if (!global.mxCallHandler) {
dis.register(_onAction);
// add empty handlers for media actions, otherwise the media keys
// end up causing the audio elements with our ring/ringback etc
// audio clips in to play.
if (navigator.mediaSession) {
navigator.mediaSession.setActionHandler('play', function() {});
navigator.mediaSession.setActionHandler('pause', function() {});
navigator.mediaSession.setActionHandler('seekbackward', function() {});
navigator.mediaSession.setActionHandler('seekforward', function() {});
navigator.mediaSession.setActionHandler('previoustrack', function() {});
navigator.mediaSession.setActionHandler('nexttrack', function() {});
}
}
const callHandler = {
getCallForRoom: function(roomId) {
let call = callHandler.getCall(roomId);
if (call) return call;
if (ConferenceHandler) {
call = ConferenceHandler.getConferenceCallForRoom(roomId);
}
if (call) return call;
return null;
},
getCall: function(roomId) {
return calls[roomId] || null;
},
getAnyActiveCall: function() {
const roomsWithCalls = Object.keys(calls);
for (let i = 0; i < roomsWithCalls.length; i++) {
if (calls[roomsWithCalls[i]] &&
calls[roomsWithCalls[i]].call_state !== "ended") {
return calls[roomsWithCalls[i]];
}
}
return null;
},
/**
* The conference handler is a module that deals with implementation-specific
* multi-party calling implementations. Element passes in its own which creates
* a one-to-one call with a freeswitch conference bridge. As of July 2018,
* the de-facto way of conference calling is a Jitsi widget, so this is
* deprecated. It reamins here for two reasons:
* 1. So Element still supports joining existing freeswitch conference calls
* (but doesn't support creating them). After a transition period, we can
* remove support for joining them too.
* 2. To hide the one-to-one rooms that old-style conferencing creates. This
* is much harder to remove: probably either we make Element leave & forget these
* rooms after we remove support for joining freeswitch conferences, or we
* accept that random rooms with cryptic users will suddently appear for
* anyone who's ever used conference calling, or we are stuck with this
* code forever.
*
* @param {object} confHandler The conference handler object
*/
setConferenceHandler: function(confHandler) {
ConferenceHandler = confHandler;
},
getConferenceHandler: function() {
return ConferenceHandler;
},
};
// Only things in here which actually need to be global are the
// calls list (done separately) and making sure we only register
// with the dispatcher once (which uses this mechanism but checks
// separately). This could be tidied up.
if (global.mxCallHandler === undefined) {
global.mxCallHandler = callHandler;
}
export default global.mxCallHandler;

513
src/CallHandler.tsx Normal file
View file

@ -0,0 +1,513 @@
/*
Copyright 2015, 2016 OpenMarket Ltd
Copyright 2017, 2018 New Vector Ltd
Copyright 2019, 2020 The Matrix.org Foundation C.I.C.
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.
*/
/*
* Manages a list of all the currently active calls.
*
* This handler dispatches when voip calls are added/updated/removed from this list:
* {
* action: 'call_state'
* room_id: <room ID of the call>
* }
*
* To know the state of the call, this handler exposes a getter to
* obtain the call for a room:
* var call = CallHandler.getCall(roomId)
* var state = call.call_state; // ringing|ringback|connected|ended|busy|stop_ringback|stop_ringing
*
* This handler listens for and handles the following actions:
* {
* action: 'place_call',
* type: 'voice|video',
* room_id: <room that the place call button was pressed in>
* }
*
* {
* action: 'incoming_call'
* call: MatrixCall
* }
*
* {
* action: 'hangup'
* room_id: <room that the hangup button was pressed in>
* }
*
* {
* action: 'answer'
* room_id: <room that the answer button was pressed in>
* }
*/
import React from 'react';
import {MatrixClientPeg} from './MatrixClientPeg';
import PlatformPeg from './PlatformPeg';
import Modal from './Modal';
import { _t } from './languageHandler';
// @ts-ignore - XXX: tsc doesn't like this: our js-sdk imports are complex so this isn't surprising
import Matrix from 'matrix-js-sdk';
import dis from './dispatcher/dispatcher';
import WidgetUtils from './utils/WidgetUtils';
import WidgetEchoStore from './stores/WidgetEchoStore';
import SettingsStore from './settings/SettingsStore';
import {generateHumanReadableId} from "./utils/NamingUtils";
import {Jitsi} from "./widgets/Jitsi";
import {WidgetType} from "./widgets/WidgetType";
import {SettingLevel} from "./settings/SettingLevel";
import { ActionPayload } from "./dispatcher/payloads";
import {base32} from "rfc4648";
import QuestionDialog from "./components/views/dialogs/QuestionDialog";
import ErrorDialog from "./components/views/dialogs/ErrorDialog";
import WidgetStore from "./stores/WidgetStore";
import { WidgetMessagingStore } from "./stores/widgets/WidgetMessagingStore";
import { ElementWidgetActions } from "./stores/widgets/ElementWidgetActions";
// until we ts-ify the js-sdk voip code
type Call = any;
export default class CallHandler {
private calls = new Map<string, Call>();
private audioPromises = new Map<string, Promise<void>>();
static sharedInstance() {
if (!window.mxCallHandler) {
window.mxCallHandler = new CallHandler()
}
return window.mxCallHandler;
}
constructor() {
dis.register(this.onAction);
// add empty handlers for media actions, otherwise the media keys
// end up causing the audio elements with our ring/ringback etc
// audio clips in to play.
if (navigator.mediaSession) {
navigator.mediaSession.setActionHandler('play', function() {});
navigator.mediaSession.setActionHandler('pause', function() {});
navigator.mediaSession.setActionHandler('seekbackward', function() {});
navigator.mediaSession.setActionHandler('seekforward', function() {});
navigator.mediaSession.setActionHandler('previoustrack', function() {});
navigator.mediaSession.setActionHandler('nexttrack', function() {});
}
}
getCallForRoom(roomId: string): Call {
return this.calls.get(roomId) || null;
}
getAnyActiveCall() {
for (const call of this.calls.values()) {
if (call.state !== "ended") {
return call;
}
}
return null;
}
play(audioId: string) {
// TODO: Attach an invisible element for this instead
// which listens?
const audio = document.getElementById(audioId) as HTMLMediaElement;
if (audio) {
const playAudio = async () => {
try {
// This still causes the chrome debugger to break on promise rejection if
// the promise is rejected, even though we're catching the exception.
await audio.play();
} catch (e) {
// This is usually because the user hasn't interacted with the document,
// or chrome doesn't think so and is denying the request. Not sure what
// we can really do here...
// https://github.com/vector-im/element-web/issues/7657
console.log("Unable to play audio clip", e);
}
};
if (this.audioPromises.has(audioId)) {
this.audioPromises.set(audioId, this.audioPromises.get(audioId).then(() => {
audio.load();
return playAudio();
}));
} else {
this.audioPromises.set(audioId, playAudio());
}
}
}
pause(audioId: string) {
// TODO: Attach an invisible element for this instead
// which listens?
const audio = document.getElementById(audioId) as HTMLMediaElement;
if (audio) {
if (this.audioPromises.has(audioId)) {
this.audioPromises.set(audioId, this.audioPromises.get(audioId).then(() => audio.pause()));
} else {
// pause doesn't return a promise, so just do it
audio.pause();
}
}
}
private setCallListeners(call: Call) {
call.on("error", (err) => {
console.error("Call error:", err);
if (
MatrixClientPeg.get().getTurnServers().length === 0 &&
SettingsStore.getValue("fallbackICEServerAllowed") === null
) {
this.showICEFallbackPrompt();
return;
}
Modal.createTrackedDialog('Call Failed', '', ErrorDialog, {
title: _t('Call Failed'),
description: err.message,
});
});
call.on("hangup", () => {
this.removeCallForRoom(call.roomId);
});
// map web rtc states to dummy UI state
// ringing|ringback|connected|ended|busy|stop_ringback|stop_ringing
call.on("state", (newState, oldState) => {
if (newState === "ringing") {
this.setCallState(call, call.roomId, "ringing");
this.pause("ringbackAudio");
} else if (newState === "invite_sent") {
this.setCallState(call, call.roomId, "ringback");
this.play("ringbackAudio");
} else if (newState === "ended" && oldState === "connected") {
this.removeCallForRoom(call.roomId);
this.pause("ringbackAudio");
this.play("callendAudio");
} else if (newState === "ended" && oldState === "invite_sent" &&
(call.hangupParty === "remote" ||
(call.hangupParty === "local" && call.hangupReason === "invite_timeout")
)) {
this.setCallState(call, call.roomId, "busy");
this.pause("ringbackAudio");
this.play("busyAudio");
Modal.createTrackedDialog('Call Handler', 'Call Timeout', ErrorDialog, {
title: _t('Call Timeout'),
description: _t('The remote side failed to pick up') + '.',
});
} else if (oldState === "invite_sent") {
this.setCallState(call, call.roomId, "stop_ringback");
this.pause("ringbackAudio");
} else if (oldState === "ringing") {
this.setCallState(call, call.roomId, "stop_ringing");
this.pause("ringbackAudio");
} else if (newState === "connected") {
this.setCallState(call, call.roomId, "connected");
this.pause("ringbackAudio");
}
});
}
private setCallState(call: Call, roomId: string, status: string) {
console.log(
`Call state in ${roomId} changed to ${status} (${call ? call.call_state : "-"})`,
);
if (call) {
this.calls.set(roomId, call);
} else {
this.calls.delete(roomId);
}
if (status === "ringing") {
this.play("ringAudio");
} else if (call && call.call_state === "ringing") {
this.pause("ringAudio");
}
if (call) {
call.call_state = status;
}
dis.dispatch({
action: 'call_state',
room_id: roomId,
state: status,
});
}
private removeCallForRoom(roomId: string) {
this.setCallState(null, roomId, null);
}
private showICEFallbackPrompt() {
const cli = MatrixClientPeg.get();
const code = sub => <code>{sub}</code>;
Modal.createTrackedDialog('No TURN servers', '', QuestionDialog, {
title: _t("Call failed due to misconfigured server"),
description: <div>
<p>{_t(
"Please ask the administrator of your homeserver " +
"(<code>%(homeserverDomain)s</code>) to configure a TURN server in " +
"order for calls to work reliably.",
{ homeserverDomain: cli.getDomain() }, { code },
)}</p>
<p>{_t(
"Alternatively, you can try to use the public server at " +
"<code>turn.matrix.org</code>, but this will not be as reliable, and " +
"it will share your IP address with that server. You can also manage " +
"this in Settings.",
null, { code },
)}</p>
</div>,
button: _t('Try using turn.matrix.org'),
cancelButton: _t('OK'),
onFinished: (allow) => {
SettingsStore.setValue("fallbackICEServerAllowed", null, SettingLevel.DEVICE, allow);
cli.setFallbackICEServerAllowed(allow);
},
}, null, true);
}
private onAction = (payload: ActionPayload) => {
const placeCall = (newCall) => {
this.setCallListeners(newCall);
if (payload.type === 'voice') {
newCall.placeVoiceCall();
} else if (payload.type === 'video') {
newCall.placeVideoCall(
payload.remote_element,
payload.local_element,
);
} else if (payload.type === 'screensharing') {
const screenCapErrorString = PlatformPeg.get().screenCaptureErrorString();
if (screenCapErrorString) {
this.removeCallForRoom(newCall.roomId);
console.log("Can't capture screen: " + screenCapErrorString);
Modal.createTrackedDialog('Call Handler', 'Unable to capture screen', ErrorDialog, {
title: _t('Unable to capture screen'),
description: screenCapErrorString,
});
return;
}
newCall.placeScreenSharingCall(
payload.remote_element,
payload.local_element,
);
} else {
console.error("Unknown conf call type: %s", payload.type);
}
}
switch (payload.action) {
case 'place_call':
{
if (this.getAnyActiveCall()) {
Modal.createTrackedDialog('Call Handler', 'Existing Call', ErrorDialog, {
title: _t('Existing Call'),
description: _t('You are already in a call.'),
});
return; // don't allow >1 call to be placed.
}
// if the runtime env doesn't do VoIP, whine.
if (!MatrixClientPeg.get().supportsVoip()) {
Modal.createTrackedDialog('Call Handler', 'VoIP is unsupported', ErrorDialog, {
title: _t('VoIP is unsupported'),
description: _t('You cannot place VoIP calls in this browser.'),
});
return;
}
const room = MatrixClientPeg.get().getRoom(payload.room_id);
if (!room) {
console.error("Room %s does not exist.", payload.room_id);
return;
}
const members = room.getJoinedMembers();
if (members.length <= 1) {
Modal.createTrackedDialog('Call Handler', 'Cannot place call with self', ErrorDialog, {
description: _t('You cannot place a call with yourself.'),
});
return;
} else if (members.length === 2) {
console.info("Place %s call in %s", payload.type, payload.room_id);
const call = Matrix.createNewMatrixCall(MatrixClientPeg.get(), payload.room_id);
placeCall(call);
} else { // > 2
dis.dispatch({
action: "place_conference_call",
room_id: payload.room_id,
type: payload.type,
remote_element: payload.remote_element,
local_element: payload.local_element,
});
}
}
break;
case 'place_conference_call':
console.info("Place conference call in %s", payload.room_id);
this.startCallApp(payload.room_id, payload.type);
break;
case 'end_conference':
console.info("Terminating conference call in %s", payload.room_id);
this.terminateCallApp(payload.room_id);
break;
case 'hangup_conference':
console.info("Leaving conference call in %s", payload.room_id);
this.hangupCallApp(payload.room_id);
break;
case 'incoming_call':
{
if (this.getAnyActiveCall()) {
// ignore multiple incoming calls. in future, we may want a line-1/line-2 setup.
// we avoid rejecting with "busy" in case the user wants to answer it on a different device.
// in future we could signal a "local busy" as a warning to the caller.
// see https://github.com/vector-im/vector-web/issues/1964
return;
}
// if the runtime env doesn't do VoIP, stop here.
if (!MatrixClientPeg.get().supportsVoip()) {
return;
}
const call = payload.call;
this.setCallListeners(call);
this.setCallState(call, call.roomId, "ringing");
}
break;
case 'hangup':
if (!this.calls.get(payload.room_id)) {
return; // no call to hangup
}
this.calls.get(payload.room_id).hangup();
this.removeCallForRoom(payload.room_id);
break;
case 'answer':
if (!this.calls.get(payload.room_id)) {
return; // no call to answer
}
this.calls.get(payload.room_id).answer();
this.setCallState(this.calls.get(payload.room_id), payload.room_id, "connected");
dis.dispatch({
action: "view_room",
room_id: payload.room_id,
});
break;
}
}
private async startCallApp(roomId: string, type: string) {
dis.dispatch({
action: 'appsDrawer',
show: true,
});
// prevent double clicking the call button
const room = MatrixClientPeg.get().getRoom(roomId);
const currentJitsiWidgets = WidgetUtils.getRoomWidgetsOfType(room, WidgetType.JITSI);
const hasJitsi = currentJitsiWidgets.length > 0
|| WidgetEchoStore.roomHasPendingWidgetsOfType(roomId, currentJitsiWidgets, WidgetType.JITSI);
if (hasJitsi) {
Modal.createTrackedDialog('Call already in progress', '', ErrorDialog, {
title: _t('Call in Progress'),
description: _t('A call is currently being placed!'),
});
return;
}
const jitsiDomain = Jitsi.getInstance().preferredDomain;
const jitsiAuth = await Jitsi.getInstance().getJitsiAuth();
let confId;
if (jitsiAuth === 'openidtoken-jwt') {
// Create conference ID from room ID
// For compatibility with Jitsi, use base32 without padding.
// More details here:
// https://github.com/matrix-org/prosody-mod-auth-matrix-user-verification
confId = base32.stringify(Buffer.from(roomId), { pad: false });
} else {
// Create a random human readable conference ID
confId = `JitsiConference${generateHumanReadableId()}`;
}
let widgetUrl = WidgetUtils.getLocalJitsiWrapperUrl({auth: jitsiAuth});
// TODO: Remove URL hacks when the mobile clients eventually support v2 widgets
const parsedUrl = new URL(widgetUrl);
parsedUrl.search = ''; // set to empty string to make the URL class use searchParams instead
parsedUrl.searchParams.set('confId', confId);
widgetUrl = parsedUrl.toString();
const widgetData = {
conferenceId: confId,
isAudioOnly: type === 'voice',
domain: jitsiDomain,
auth: jitsiAuth,
};
const widgetId = (
'jitsi_' +
MatrixClientPeg.get().credentials.userId +
'_' +
Date.now()
);
WidgetUtils.setRoomWidget(roomId, widgetId, WidgetType.JITSI, widgetUrl, 'Jitsi', widgetData).then(() => {
console.log('Jitsi widget added');
}).catch((e) => {
if (e.errcode === 'M_FORBIDDEN') {
Modal.createTrackedDialog('Call Failed', '', ErrorDialog, {
title: _t('Permission Required'),
description: _t("You do not have permission to start a conference call in this room"),
});
}
console.error(e);
});
}
private terminateCallApp(roomId: string) {
Modal.createTrackedDialog('Confirm Jitsi Terminate', '', QuestionDialog, {
hasCancelButton: true,
title: _t("End conference"),
description: _t("This will end the conference for everyone. Continue?"),
button: _t("End conference"),
onFinished: (proceed) => {
if (!proceed) return;
// We'll just obliterate them all. There should only ever be one, but might as well
// be safe.
const roomInfo = WidgetStore.instance.getRoom(roomId);
const jitsiWidgets = roomInfo.widgets.filter(w => WidgetType.JITSI.matches(w.type));
jitsiWidgets.forEach(w => {
// setting invalid content removes it
WidgetUtils.setRoomWidget(roomId, w.id);
});
},
});
}
private hangupCallApp(roomId: string) {
const roomInfo = WidgetStore.instance.getRoom(roomId);
if (!roomInfo) return; // "should never happen" clauses go here
const jitsiWidgets = roomInfo.widgets.filter(w => WidgetType.JITSI.matches(w.type));
jitsiWidgets.forEach(w => {
const messaging = WidgetMessagingStore.instance.getMessagingForId(w.id);
if (!messaging) return; // more "should never happen" words
messaging.transport.send(ElementWidgetActions.HangupCall, {});
});
}
}

View file

@ -1,275 +0,0 @@
/*
Copyright 2018 New Vector Ltd
Copyright 2019 Travis Ralston
Copyright 2019 The Matrix.org Foundation C.I.C.
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 URL from 'url';
import dis from './dispatcher/dispatcher';
import WidgetMessagingEndpoint from './WidgetMessagingEndpoint';
import ActiveWidgetStore from './stores/ActiveWidgetStore';
import {MatrixClientPeg} from "./MatrixClientPeg";
import RoomViewStore from "./stores/RoomViewStore";
import {IntegrationManagers} from "./integrations/IntegrationManagers";
import SettingsStore from "./settings/SettingsStore";
import {Capability} from "./widgets/WidgetApi";
import {objectClone} from "./utils/objects";
const WIDGET_API_VERSION = '0.0.2'; // Current API version
const SUPPORTED_WIDGET_API_VERSIONS = [
'0.0.1',
'0.0.2',
];
const INBOUND_API_NAME = 'fromWidget';
// Listen for and handle incoming requests using the 'fromWidget' postMessage
// API and initiate responses
export default class FromWidgetPostMessageApi {
constructor() {
this.widgetMessagingEndpoints = [];
this.widgetListeners = {}; // {action: func[]}
this.start = this.start.bind(this);
this.stop = this.stop.bind(this);
this.onPostMessage = this.onPostMessage.bind(this);
}
start() {
window.addEventListener('message', this.onPostMessage);
}
stop() {
window.removeEventListener('message', this.onPostMessage);
}
/**
* Adds a listener for a given action
* @param {string} action The action to listen for.
* @param {Function} callbackFn A callback function to be called when the action is
* encountered. Called with two parameters: the interesting request information and
* the raw event received from the postMessage API. The raw event is meant to be used
* for sendResponse and similar functions.
*/
addListener(action, callbackFn) {
if (!this.widgetListeners[action]) this.widgetListeners[action] = [];
this.widgetListeners[action].push(callbackFn);
}
/**
* Removes a listener for a given action.
* @param {string} action The action that was subscribed to.
* @param {Function} callbackFn The original callback function that was used to subscribe
* to updates.
*/
removeListener(action, callbackFn) {
if (!this.widgetListeners[action]) return;
const idx = this.widgetListeners[action].indexOf(callbackFn);
if (idx !== -1) this.widgetListeners[action].splice(idx, 1);
}
/**
* Register a widget endpoint for trusted postMessage communication
* @param {string} widgetId Unique widget identifier
* @param {string} endpointUrl Widget wurl origin (protocol + (optional port) + host)
*/
addEndpoint(widgetId, endpointUrl) {
const u = URL.parse(endpointUrl);
if (!u || !u.protocol || !u.host) {
console.warn('Add FromWidgetPostMessageApi endpoint - Invalid origin:', endpointUrl);
return;
}
const origin = u.protocol + '//' + u.host;
const endpoint = new WidgetMessagingEndpoint(widgetId, origin);
if (this.widgetMessagingEndpoints.some(function(ep) {
return (ep.widgetId === widgetId && ep.endpointUrl === endpointUrl);
})) {
// Message endpoint already registered
console.warn('Add FromWidgetPostMessageApi - Endpoint already registered');
return;
} else {
console.log(`Adding fromWidget messaging endpoint for ${widgetId}`, endpoint);
this.widgetMessagingEndpoints.push(endpoint);
}
}
/**
* De-register a widget endpoint from trusted communication sources
* @param {string} widgetId Unique widget identifier
* @param {string} endpointUrl Widget wurl origin (protocol + (optional port) + host)
* @return {boolean} True if endpoint was successfully removed
*/
removeEndpoint(widgetId, endpointUrl) {
const u = URL.parse(endpointUrl);
if (!u || !u.protocol || !u.host) {
console.warn('Remove widget messaging endpoint - Invalid origin');
return;
}
const origin = u.protocol + '//' + u.host;
if (this.widgetMessagingEndpoints && this.widgetMessagingEndpoints.length > 0) {
const length = this.widgetMessagingEndpoints.length;
this.widgetMessagingEndpoints = this.widgetMessagingEndpoints
.filter((endpoint) => endpoint.widgetId !== widgetId || endpoint.endpointUrl !== origin);
return (length > this.widgetMessagingEndpoints.length);
}
return false;
}
/**
* Handle widget postMessage events
* Messages are only handled where a valid, registered messaging endpoints
* @param {Event} event Event to handle
* @return {undefined}
*/
onPostMessage(event) {
if (!event.origin) { // Handle chrome
event.origin = event.originalEvent.origin;
}
// Event origin is empty string if undefined
if (
event.origin.length === 0 ||
!this.trustedEndpoint(event.origin) ||
event.data.api !== INBOUND_API_NAME ||
!event.data.widgetId
) {
return; // don't log this - debugging APIs like to spam postMessage which floods the log otherwise
}
// Call any listeners we have registered
if (this.widgetListeners[event.data.action]) {
for (const fn of this.widgetListeners[event.data.action]) {
fn(event.data, event);
}
}
// Although the requestId is required, we don't use it. We'll be nice and process the message
// if the property is missing, but with a warning for widget developers.
if (!event.data.requestId) {
console.warn("fromWidget action '" + event.data.action + "' does not have a requestId");
}
const action = event.data.action;
const widgetId = event.data.widgetId;
if (action === 'content_loaded') {
console.log('Widget reported content loaded for', widgetId);
dis.dispatch({
action: 'widget_content_loaded',
widgetId: widgetId,
});
this.sendResponse(event, {success: true});
} else if (action === 'supported_api_versions') {
this.sendResponse(event, {
api: INBOUND_API_NAME,
supported_versions: SUPPORTED_WIDGET_API_VERSIONS,
});
} else if (action === 'api_version') {
this.sendResponse(event, {
api: INBOUND_API_NAME,
version: WIDGET_API_VERSION,
});
} else if (action === 'm.sticker') {
// console.warn('Got sticker message from widget', widgetId);
// NOTE -- The widgetData field is deprecated (in favour of the 'data' field) and will be removed eventually
const data = event.data.data || event.data.widgetData;
dis.dispatch({action: 'm.sticker', data: data, widgetId: event.data.widgetId});
} else if (action === 'integration_manager_open') {
// Close the stickerpicker
dis.dispatch({action: 'stickerpicker_close'});
// Open the integration manager
// NOTE -- The widgetData field is deprecated (in favour of the 'data' field) and will be removed eventually
const data = event.data.data || event.data.widgetData;
const integType = (data && data.integType) ? data.integType : null;
const integId = (data && data.integId) ? data.integId : null;
// TODO: Open the right integration manager for the widget
if (SettingsStore.getValue("feature_many_integration_managers")) {
IntegrationManagers.sharedInstance().openAll(
MatrixClientPeg.get().getRoom(RoomViewStore.getRoomId()),
`type_${integType}`,
integId,
);
} else {
IntegrationManagers.sharedInstance().getPrimaryManager().open(
MatrixClientPeg.get().getRoom(RoomViewStore.getRoomId()),
`type_${integType}`,
integId,
);
}
} else if (action === 'set_always_on_screen') {
// This is a new message: there is no reason to support the deprecated widgetData here
const data = event.data.data;
const val = data.value;
if (ActiveWidgetStore.widgetHasCapability(widgetId, Capability.AlwaysOnScreen)) {
ActiveWidgetStore.setWidgetPersistence(widgetId, val);
}
} else if (action === 'get_openid') {
// Handled by caller
} else {
console.warn('Widget postMessage event unhandled');
this.sendError(event, {message: 'The postMessage was unhandled'});
}
}
/**
* Check if message origin is registered as trusted
* @param {string} origin PostMessage origin to check
* @return {boolean} True if trusted
*/
trustedEndpoint(origin) {
if (!origin) {
return false;
}
return this.widgetMessagingEndpoints.some((endpoint) => {
// TODO / FIXME -- Should this also check the widgetId?
return endpoint.endpointUrl === origin;
});
}
/**
* Send a postmessage response to a postMessage request
* @param {Event} event The original postMessage request event
* @param {Object} res Response data
*/
sendResponse(event, res) {
const data = objectClone(event.data);
data.response = res;
event.source.postMessage(data, event.origin);
}
/**
* Send an error response to a postMessage request
* @param {Event} event The original postMessage request event
* @param {string} msg Error message
* @param {Error} nestedError Nested error event (optional)
*/
sendError(event, msg, nestedError) {
console.error('Action:' + event.data.action + ' failed with message: ' + msg);
const data = objectClone(event.data);
data.response = {
error: {
message: msg,
},
};
if (nestedError) {
data.response.error._error = nestedError;
}
event.source.postMessage(data, event.origin);
}
}

View file

@ -19,6 +19,7 @@ limitations under the License.
import React from 'react';
import sanitizeHtml from 'sanitize-html';
import { IExtendedSanitizeOptions } from './@types/sanitize-html';
import * as linkify from 'linkifyjs';
import linkifyMatrix from './linkify-matrix';
import _linkifyElement from 'linkifyjs/element';
@ -55,7 +56,7 @@ const BIGEMOJI_REGEX = new RegExp(`^(${EMOJIBASE_REGEX.source})+$`, 'i');
const COLOR_REGEX = /^#[0-9a-fA-F]{6}$/;
const PERMITTED_URL_SCHEMES = ['http', 'https', 'ftp', 'mailto', 'magnet'];
export const PERMITTED_URL_SCHEMES = ['http', 'https', 'ftp', 'mailto', 'magnet'];
/*
* Return true if the given string contains emoji
@ -154,7 +155,7 @@ export function isUrlPermitted(inputUrl: string) {
}
}
const transformTags: sanitizeHtml.IOptions["transformTags"] = { // custom to matrix
const transformTags: IExtendedSanitizeOptions["transformTags"] = { // custom to matrix
// add blank targets to all hyperlinks except vector URLs
'a': function(tagName: string, attribs: sanitizeHtml.Attributes) {
if (attribs.href) {
@ -227,7 +228,7 @@ const transformTags: sanitizeHtml.IOptions["transformTags"] = { // custom to mat
},
};
const sanitizeHtmlParams: sanitizeHtml.IOptions = {
const sanitizeHtmlParams: IExtendedSanitizeOptions = {
allowedTags: [
'font', // custom to matrix for IRC-style font coloring
'del', // for markdown
@ -249,13 +250,14 @@ const sanitizeHtmlParams: sanitizeHtml.IOptions = {
selfClosing: ['img', 'br', 'hr', 'area', 'base', 'basefont', 'input', 'link', 'meta'],
// URL schemes we permit
allowedSchemes: PERMITTED_URL_SCHEMES,
allowProtocolRelative: false,
transformTags,
// 50 levels deep "should be enough for anyone"
nestingLimit: 50,
};
// this is the same as the above except with less rewriting
const composerSanitizeHtmlParams: sanitizeHtml.IOptions = {
const composerSanitizeHtmlParams: IExtendedSanitizeOptions = {
...sanitizeHtmlParams,
transformTags: {
'code': transformTags['code'],

View file

@ -17,9 +17,12 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
// @ts-ignore - XXX: tsc doesn't like this: our js-sdk imports are complex so this isn't surprising
import Matrix from 'matrix-js-sdk';
import { InvalidStoreError } from "matrix-js-sdk/src/errors";
import { MatrixClient } from "matrix-js-sdk/src/client";
import {MatrixClientPeg} from './MatrixClientPeg';
import {IMatrixClientCreds, MatrixClientPeg} from './MatrixClientPeg';
import EventIndexPeg from './indexing/EventIndexPeg';
import createMatrixClient from './utils/createMatrixClient';
import Analytics from './Analytics';
@ -47,44 +50,46 @@ import ThreepidInviteStore from "./stores/ThreepidInviteStore";
const HOMESERVER_URL_KEY = "mx_hs_url";
const ID_SERVER_URL_KEY = "mx_is_url";
interface ILoadSessionOpts {
enableGuest?: boolean;
guestHsUrl?: string;
guestIsUrl?: string;
ignoreGuest?: boolean;
defaultDeviceDisplayName?: string;
fragmentQueryParams?: Record<string, string>;
}
/**
* Called at startup, to attempt to build a logged-in Matrix session. It tries
* a number of things:
*
*
* 1. if we have a guest access token in the fragment query params, it uses
* that.
*
* 2. if an access token is stored in local storage (from a previous session),
* it uses that.
*
* 3. it attempts to auto-register as a guest user.
*
* If any of steps 1-4 are successful, it will call {_doSetLoggedIn}, which in
* turn will raise on_logged_in and will_start_client events.
*
* @param {object} opts
*
* @param {object} opts.fragmentQueryParams: string->string map of the
* @param {object} [opts]
* @param {object} [opts.fragmentQueryParams]: string->string map of the
* query-parameters extracted from the #-fragment of the starting URI.
*
* @param {boolean} opts.enableGuest: set to true to enable guest access tokens
* and auto-guest registrations.
*
* @params {string} opts.guestHsUrl: homeserver URL. Only used if enableGuest is
* true; defines the HS to register against.
*
* @params {string} opts.guestIsUrl: homeserver URL. Only used if enableGuest is
* true; defines the IS to use.
*
* @params {bool} opts.ignoreGuest: If the stored session is a guest account, ignore
* it and don't load it.
*
* @param {boolean} [opts.enableGuest]: set to true to enable guest access
* tokens and auto-guest registrations.
* @param {string} [opts.guestHsUrl]: homeserver URL. Only used if enableGuest
* is true; defines the HS to register against.
* @param {string} [opts.guestIsUrl]: homeserver URL. Only used if enableGuest
* is true; defines the IS to use.
* @param {bool} [opts.ignoreGuest]: If the stored session is a guest account,
* ignore it and don't load it.
* @param {string} [opts.defaultDeviceDisplayName]: Default display name to use
* when registering as a guest.
* @returns {Promise} a promise which resolves when the above process completes.
* Resolves to `true` if we ended up starting a session, or `false` if we
* failed.
*/
export async function loadSession(opts) {
export async function loadSession(opts: ILoadSessionOpts = {}): Promise<boolean> {
try {
let enableGuest = opts.enableGuest || false;
const guestHsUrl = opts.guestHsUrl;
@ -97,12 +102,13 @@ export async function loadSession(opts) {
enableGuest = false;
}
if (enableGuest &&
if (
enableGuest &&
fragmentQueryParams.guest_user_id &&
fragmentQueryParams.guest_access_token
) {
) {
console.log("Using guest access credentials");
return _doSetLoggedIn({
return doSetLoggedIn({
userId: fragmentQueryParams.guest_user_id,
accessToken: fragmentQueryParams.guest_access_token,
homeserverUrl: guestHsUrl,
@ -110,7 +116,7 @@ export async function loadSession(opts) {
guest: true,
}, true).then(() => true);
}
const success = await _restoreFromLocalStorage({
const success = await restoreFromLocalStorage({
ignoreGuest: Boolean(opts.ignoreGuest),
});
if (success) {
@ -118,7 +124,7 @@ export async function loadSession(opts) {
}
if (enableGuest) {
return _registerAsGuest(guestHsUrl, guestIsUrl, defaultDeviceDisplayName);
return registerAsGuest(guestHsUrl, guestIsUrl, defaultDeviceDisplayName);
}
// fall back to welcome screen
@ -129,7 +135,7 @@ export async function loadSession(opts) {
// need to show the general failure dialog. Instead, just go back to welcome.
return false;
}
return _handleLoadSessionFailure(e);
return handleLoadSessionFailure(e);
}
}
@ -139,7 +145,7 @@ export async function loadSession(opts) {
* is associated with them. The session is not loaded.
* @returns {String} The persisted session's owner, if an owner exists. Null otherwise.
*/
export function getStoredSessionOwner() {
export function getStoredSessionOwner(): string {
const {hsUrl, userId, accessToken} = getLocalStorageSessionVars();
return hsUrl && userId && accessToken ? userId : null;
}
@ -148,7 +154,7 @@ export function getStoredSessionOwner() {
* @returns {bool} True if the stored session is for a guest user or false if it is
* for a real user. If there is no stored session, return null.
*/
export function getStoredSessionIsGuest() {
export function getStoredSessionIsGuest(): boolean {
const sessVars = getLocalStorageSessionVars();
return sessVars.hsUrl && sessVars.userId && sessVars.accessToken ? sessVars.isGuest : null;
}
@ -163,7 +169,10 @@ export function getStoredSessionIsGuest() {
* @returns {Promise} promise which resolves to true if we completed the token
* login, else false
*/
export function attemptTokenLogin(queryParams, defaultDeviceDisplayName) {
export function attemptTokenLogin(
queryParams: Record<string, string>,
defaultDeviceDisplayName?: string,
): Promise<boolean> {
if (!queryParams.loginToken) {
return Promise.resolve(false);
}
@ -184,8 +193,10 @@ export function attemptTokenLogin(queryParams, defaultDeviceDisplayName) {
},
).then(function(creds) {
console.log("Logged in with token");
return _clearStorage().then(() => {
_persistCredentialsToLocalStorage(creds);
return clearStorage().then(() => {
persistCredentialsToLocalStorage(creds);
// remember that we just logged in
sessionStorage.setItem("mx_fresh_login", String(true));
return true;
});
}).catch((err) => {
@ -195,8 +206,8 @@ export function attemptTokenLogin(queryParams, defaultDeviceDisplayName) {
});
}
export function handleInvalidStoreError(e) {
if (e.reason === Matrix.InvalidStoreError.TOGGLED_LAZY_LOADING) {
export function handleInvalidStoreError(e: InvalidStoreError): Promise<void> {
if (e.reason === InvalidStoreError.TOGGLED_LAZY_LOADING) {
return Promise.resolve().then(() => {
const lazyLoadEnabled = e.value;
if (lazyLoadEnabled) {
@ -229,7 +240,11 @@ export function handleInvalidStoreError(e) {
}
}
function _registerAsGuest(hsUrl, isUrl, defaultDeviceDisplayName) {
function registerAsGuest(
hsUrl: string,
isUrl: string,
defaultDeviceDisplayName: string,
): Promise<boolean> {
console.log(`Doing guest login on ${hsUrl}`);
// create a temporary MatrixClient to do the login
@ -243,7 +258,7 @@ function _registerAsGuest(hsUrl, isUrl, defaultDeviceDisplayName) {
},
}).then((creds) => {
console.log(`Registered as guest: ${creds.user_id}`);
return _doSetLoggedIn({
return doSetLoggedIn({
userId: creds.user_id,
deviceId: creds.device_id,
accessToken: creds.access_token,
@ -257,12 +272,21 @@ function _registerAsGuest(hsUrl, isUrl, defaultDeviceDisplayName) {
});
}
export interface ILocalStorageSession {
hsUrl: string;
isUrl: string;
accessToken: string;
userId: string;
deviceId: string;
isGuest: boolean;
}
/**
* Retrieves information about the stored session in localstorage. The session
* may not be valid, as it is not tested for consistency here.
* @returns {Object} Information about the session - see implementation for variables.
*/
export function getLocalStorageSessionVars() {
export function getLocalStorageSessionVars(): ILocalStorageSession {
const hsUrl = localStorage.getItem(HOMESERVER_URL_KEY);
const isUrl = localStorage.getItem(ID_SERVER_URL_KEY);
const accessToken = localStorage.getItem("mx_access_token");
@ -290,8 +314,8 @@ export function getLocalStorageSessionVars() {
// The plan is to gradually move the localStorage access done here into
// SessionStore to avoid bugs where the view becomes out-of-sync with
// localStorage (e.g. isGuest etc.)
async function _restoreFromLocalStorage(opts) {
const ignoreGuest = opts.ignoreGuest;
async function restoreFromLocalStorage(opts?: { ignoreGuest?: boolean }): Promise<boolean> {
const ignoreGuest = opts?.ignoreGuest;
if (!localStorage) {
return false;
@ -312,8 +336,11 @@ async function _restoreFromLocalStorage(opts) {
console.log("No pickle key available");
}
const freshLogin = sessionStorage.getItem("mx_fresh_login") === "true";
sessionStorage.removeItem("mx_fresh_login");
console.log(`Restoring session for ${userId}`);
await _doSetLoggedIn({
await doSetLoggedIn({
userId: userId,
deviceId: deviceId,
accessToken: accessToken,
@ -321,6 +348,7 @@ async function _restoreFromLocalStorage(opts) {
identityServerUrl: isUrl,
guest: isGuest,
pickleKey: pickleKey,
freshLogin: freshLogin,
}, false);
return true;
} else {
@ -329,7 +357,7 @@ async function _restoreFromLocalStorage(opts) {
}
}
async function _handleLoadSessionFailure(e) {
async function handleLoadSessionFailure(e: Error): Promise<boolean> {
console.error("Unable to load session", e);
const SessionRestoreErrorDialog =
@ -342,7 +370,7 @@ async function _handleLoadSessionFailure(e) {
const [success] = await modal.finished;
if (success) {
// user clicked continue.
await _clearStorage();
await clearStorage();
return false;
}
@ -363,11 +391,12 @@ async function _handleLoadSessionFailure(e) {
*
* @returns {Promise} promise which resolves to the new MatrixClient once it has been started
*/
export async function setLoggedIn(credentials) {
export async function setLoggedIn(credentials: IMatrixClientCreds): Promise<MatrixClient> {
credentials.freshLogin = true;
stopMatrixClient();
const pickleKey = credentials.userId && credentials.deviceId
? await PlatformPeg.get().createPickleKey(credentials.userId, credentials.deviceId)
: null;
? await PlatformPeg.get().createPickleKey(credentials.userId, credentials.deviceId)
: null;
if (pickleKey) {
console.log("Created pickle key");
@ -375,7 +404,7 @@ export async function setLoggedIn(credentials) {
console.log("Pickle key not created");
}
return _doSetLoggedIn(Object.assign({}, credentials, {pickleKey}), true);
return doSetLoggedIn(Object.assign({}, credentials, {pickleKey}), true);
}
/**
@ -393,7 +422,7 @@ export async function setLoggedIn(credentials) {
*
* @returns {Promise} promise which resolves to the new MatrixClient once it has been started
*/
export function hydrateSession(credentials) {
export function hydrateSession(credentials: IMatrixClientCreds): Promise<MatrixClient> {
const oldUserId = MatrixClientPeg.get().getUserId();
const oldDeviceId = MatrixClientPeg.get().getDeviceId();
@ -406,7 +435,7 @@ export function hydrateSession(credentials) {
console.warn("Clearing all data: Old session belongs to a different user/session");
}
return _doSetLoggedIn(credentials, overwrite);
return doSetLoggedIn(credentials, overwrite);
}
/**
@ -418,7 +447,10 @@ export function hydrateSession(credentials) {
*
* @returns {Promise} promise which resolves to the new MatrixClient once it has been started
*/
async function _doSetLoggedIn(credentials, clearStorage) {
async function doSetLoggedIn(
credentials: IMatrixClientCreds,
clearStorageEnabled: boolean,
): Promise<MatrixClient> {
credentials.guest = Boolean(credentials.guest);
const softLogout = isSoftLogout();
@ -429,6 +461,7 @@ async function _doSetLoggedIn(credentials, clearStorage) {
" guest: " + credentials.guest +
" hs: " + credentials.homeserverUrl +
" softLogout: " + softLogout,
" freshLogin: " + credentials.freshLogin,
);
// This is dispatched to indicate that the user is still in the process of logging in
@ -440,8 +473,8 @@ async function _doSetLoggedIn(credentials, clearStorage) {
// (dis.dispatch uses `setTimeout`, which does not guarantee ordering.)
dis.dispatch({action: 'on_logging_in'}, true);
if (clearStorage) {
await _clearStorage();
if (clearStorageEnabled) {
await clearStorage();
}
const results = await StorageManager.checkConsistency();
@ -449,9 +482,9 @@ async function _doSetLoggedIn(credentials, clearStorage) {
// crypto store, we'll be generally confused when handling encrypted data.
// Show a modal recommending a full reset of storage.
if (results.dataInLocalStorage && results.cryptoInited && !results.dataInCryptoStore) {
const signOut = await _showStorageEvictedDialog();
const signOut = await showStorageEvictedDialog();
if (signOut) {
await _clearStorage();
await clearStorage();
// This error feels a bit clunky, but we want to make sure we don't go any
// further and instead head back to sign in.
throw new AbortLoginAndRebuildStorage(
@ -462,19 +495,26 @@ async function _doSetLoggedIn(credentials, clearStorage) {
Analytics.setLoggedIn(credentials.guest, credentials.homeserverUrl);
MatrixClientPeg.replaceUsingCreds(credentials);
const client = MatrixClientPeg.get();
if (credentials.freshLogin && SettingsStore.getValue("feature_dehydration")) {
// If we just logged in, try to rehydrate a device instead of using a
// new device. If it succeeds, we'll get a new device ID, so make sure
// we persist that ID to localStorage
const newDeviceId = await client.rehydrateDevice();
if (newDeviceId) {
credentials.deviceId = newDeviceId;
}
delete credentials.freshLogin;
}
if (localStorage) {
try {
_persistCredentialsToLocalStorage(credentials);
// The user registered as a PWLU (PassWord-Less User), the generated password
// is cached here such that the user can change it at a later time.
if (credentials.password) {
// Update SessionStore
dis.dispatch({
action: 'cached_password',
cachedPassword: credentials.password,
});
}
persistCredentialsToLocalStorage(credentials);
// make sure we don't think that it's a fresh login any more
sessionStorage.removeItem("mx_fresh_login");
} catch (e) {
console.warn("Error using local storage: can't persist session!", e);
}
@ -482,15 +522,13 @@ async function _doSetLoggedIn(credentials, clearStorage) {
console.warn("No local storage available: can't persist session!");
}
MatrixClientPeg.replaceUsingCreds(credentials);
dis.dispatch({ action: 'on_logged_in' });
await startMatrixClient(/*startSyncing=*/!softLogout);
return MatrixClientPeg.get();
return client;
}
function _showStorageEvictedDialog() {
function showStorageEvictedDialog(): Promise<boolean> {
const StorageEvictedDialog = sdk.getComponent('views.dialogs.StorageEvictedDialog');
return new Promise(resolve => {
Modal.createTrackedDialog('Storage evicted', '', StorageEvictedDialog, {
@ -503,7 +541,7 @@ function _showStorageEvictedDialog() {
// `instanceof`. Babel 7 supports this natively in their class handling.
class AbortLoginAndRebuildStorage extends Error { }
function _persistCredentialsToLocalStorage(credentials) {
function persistCredentialsToLocalStorage(credentials: IMatrixClientCreds): void {
localStorage.setItem(HOMESERVER_URL_KEY, credentials.homeserverUrl);
if (credentials.identityServerUrl) {
localStorage.setItem(ID_SERVER_URL_KEY, credentials.identityServerUrl);
@ -513,7 +551,7 @@ function _persistCredentialsToLocalStorage(credentials) {
localStorage.setItem("mx_is_guest", JSON.stringify(credentials.guest));
if (credentials.pickleKey) {
localStorage.setItem("mx_has_pickle_key", true);
localStorage.setItem("mx_has_pickle_key", String(true));
} else {
if (localStorage.getItem("mx_has_pickle_key")) {
console.error("Expected a pickle key, but none provided. Encryption may not work.");
@ -537,7 +575,7 @@ let _isLoggingOut = false;
/**
* Logs the current session out and transitions to the logged-out state
*/
export function logout() {
export function logout(): void {
if (!MatrixClientPeg.get()) return;
if (MatrixClientPeg.get().isGuest()) {
@ -566,7 +604,7 @@ export function logout() {
);
}
export function softLogout() {
export function softLogout(): void {
if (!MatrixClientPeg.get()) return;
// Track that we've detected and trapped a soft logout. This helps prevent other
@ -587,11 +625,11 @@ export function softLogout() {
// DO NOT CALL LOGOUT. A soft logout preserves data, logout does not.
}
export function isSoftLogout() {
export function isSoftLogout(): boolean {
return localStorage.getItem("mx_soft_logout") === "true";
}
export function isLoggingOut() {
export function isLoggingOut(): boolean {
return _isLoggingOut;
}
@ -601,7 +639,7 @@ export function isLoggingOut() {
* @param {boolean} startSyncing True (default) to actually start
* syncing the client.
*/
async function startMatrixClient(startSyncing=true) {
async function startMatrixClient(startSyncing = true): Promise<void> {
console.log(`Lifecycle: Starting MatrixClient`);
// dispatch this before starting the matrix client: it's used
@ -660,21 +698,21 @@ async function startMatrixClient(startSyncing=true) {
* Stops a running client and all related services, and clears persistent
* storage. Used after a session has been logged out.
*/
export async function onLoggedOut() {
export async function onLoggedOut(): Promise<void> {
_isLoggingOut = false;
// Ensure that we dispatch a view change **before** stopping the client so
// so that React components unmount first. This avoids React soft crashes
// that can occur when components try to use a null client.
dis.dispatch({action: 'on_logged_out'}, true);
stopMatrixClient();
await _clearStorage({deleteEverything: true});
await clearStorage({deleteEverything: true});
}
/**
* @param {object} opts Options for how to clear storage.
* @returns {Promise} promise which resolves once the stores have been cleared
*/
async function _clearStorage(opts: {deleteEverything: boolean}) {
async function clearStorage(opts?: { deleteEverything?: boolean }): Promise<void> {
Analytics.disable();
if (window.localStorage) {
@ -712,7 +750,7 @@ async function _clearStorage(opts: {deleteEverything: boolean}) {
* @param {boolean} unsetClient True (default) to abandon the client
* on MatrixClientPeg after stopping.
*/
export function stopMatrixClient(unsetClient=true) {
export function stopMatrixClient(unsetClient = true): void {
Notifier.stop();
UserActivity.sharedInstance().stop();
TypingStore.sharedInstance().reset();

View file

@ -18,35 +18,72 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
// @ts-ignore - XXX: tsc doesn't like this: our js-sdk imports are complex so this isn't surprising
import Matrix from "matrix-js-sdk";
import { MatrixClient } from "matrix-js-sdk/src/client";
import { IMatrixClientCreds } from "./MatrixClientPeg";
interface ILoginOptions {
defaultDeviceDisplayName?: string;
}
// TODO: Move this to JS SDK
interface ILoginFlow {
type: string;
}
// TODO: Move this to JS SDK
/* eslint-disable camelcase */
interface ILoginParams {
identifier?: string;
password?: string;
token?: string;
device_id?: string;
initial_device_display_name?: string;
}
/* eslint-enable camelcase */
export default class Login {
constructor(hsUrl, isUrl, fallbackHsUrl, opts) {
this._hsUrl = hsUrl;
this._isUrl = isUrl;
this._fallbackHsUrl = fallbackHsUrl;
this._currentFlowIndex = 0;
this._flows = [];
this._defaultDeviceDisplayName = opts.defaultDeviceDisplayName;
this._tempClient = null; // memoize
private hsUrl: string;
private isUrl: string;
private fallbackHsUrl: string;
private currentFlowIndex: number;
// TODO: Flows need a type in JS SDK
private flows: Array<ILoginFlow>;
private defaultDeviceDisplayName: string;
private tempClient: MatrixClient;
constructor(
hsUrl: string,
isUrl: string,
fallbackHsUrl?: string,
opts?: ILoginOptions,
) {
this.hsUrl = hsUrl;
this.isUrl = isUrl;
this.fallbackHsUrl = fallbackHsUrl;
this.currentFlowIndex = 0;
this.flows = [];
this.defaultDeviceDisplayName = opts.defaultDeviceDisplayName;
this.tempClient = null; // memoize
}
getHomeserverUrl() {
return this._hsUrl;
public getHomeserverUrl(): string {
return this.hsUrl;
}
getIdentityServerUrl() {
return this._isUrl;
public getIdentityServerUrl(): string {
return this.isUrl;
}
setHomeserverUrl(hsUrl) {
this._tempClient = null; // clear memoization
this._hsUrl = hsUrl;
public setHomeserverUrl(hsUrl: string): void {
this.tempClient = null; // clear memoization
this.hsUrl = hsUrl;
}
setIdentityServerUrl(isUrl) {
this._tempClient = null; // clear memoization
this._isUrl = isUrl;
public setIdentityServerUrl(isUrl: string): void {
this.tempClient = null; // clear memoization
this.isUrl = isUrl;
}
/**
@ -54,40 +91,41 @@ export default class Login {
* requests.
* @returns {MatrixClient}
*/
createTemporaryClient() {
if (this._tempClient) return this._tempClient; // use memoization
return this._tempClient = Matrix.createClient({
baseUrl: this._hsUrl,
idBaseUrl: this._isUrl,
public createTemporaryClient(): MatrixClient {
if (this.tempClient) return this.tempClient; // use memoization
return this.tempClient = Matrix.createClient({
baseUrl: this.hsUrl,
idBaseUrl: this.isUrl,
});
}
getFlows() {
const self = this;
public async getFlows(): Promise<Array<ILoginFlow>> {
const client = this.createTemporaryClient();
return client.loginFlows().then(function(result) {
self._flows = result.flows;
self._currentFlowIndex = 0;
// technically the UI should display options for all flows for the
// user to then choose one, so return all the flows here.
return self._flows;
});
const { flows } = await client.loginFlows();
this.flows = flows;
this.currentFlowIndex = 0;
// technically the UI should display options for all flows for the
// user to then choose one, so return all the flows here.
return this.flows;
}
chooseFlow(flowIndex) {
this._currentFlowIndex = flowIndex;
public chooseFlow(flowIndex): void {
this.currentFlowIndex = flowIndex;
}
getCurrentFlowStep() {
public getCurrentFlowStep(): string {
// technically the flow can have multiple steps, but no one does this
// for login so we can ignore it.
const flowStep = this._flows[this._currentFlowIndex];
const flowStep = this.flows[this.currentFlowIndex];
return flowStep ? flowStep.type : null;
}
loginViaPassword(username, phoneCountry, phoneNumber, pass) {
const self = this;
public loginViaPassword(
username: string,
phoneCountry: string,
phoneNumber: string,
password: string,
): Promise<IMatrixClientCreds> {
const isEmail = username.indexOf("@") > 0;
let identifier;
@ -113,14 +151,14 @@ export default class Login {
}
const loginParams = {
password: pass,
identifier: identifier,
initial_device_display_name: this._defaultDeviceDisplayName,
password,
identifier,
initial_device_display_name: this.defaultDeviceDisplayName,
};
const tryFallbackHs = (originalError) => {
return sendLoginRequest(
self._fallbackHsUrl, this._isUrl, 'm.login.password', loginParams,
this.fallbackHsUrl, this.isUrl, 'm.login.password', loginParams,
).catch((fallbackError) => {
console.log("fallback HS login failed", fallbackError);
// throw the original error
@ -130,11 +168,11 @@ export default class Login {
let originalLoginError = null;
return sendLoginRequest(
self._hsUrl, self._isUrl, 'm.login.password', loginParams,
this.hsUrl, this.isUrl, 'm.login.password', loginParams,
).catch((error) => {
originalLoginError = error;
if (error.httpStatus === 403) {
if (self._fallbackHsUrl) {
if (this.fallbackHsUrl) {
return tryFallbackHs(originalLoginError);
}
}
@ -154,11 +192,16 @@ export default class Login {
* @param {string} hsUrl the base url of the Homeserver used to log in.
* @param {string} isUrl the base url of the default identity server
* @param {string} loginType the type of login to do
* @param {object} loginParams the parameters for the login
* @param {ILoginParams} loginParams the parameters for the login
*
* @returns {MatrixClientCreds}
*/
export async function sendLoginRequest(hsUrl, isUrl, loginType, loginParams) {
export async function sendLoginRequest(
hsUrl: string,
isUrl: string,
loginType: string,
loginParams: ILoginParams,
): Promise<IMatrixClientCreds> {
const client = Matrix.createClient({
baseUrl: hsUrl,
idBaseUrl: isUrl,

View file

@ -31,17 +31,18 @@ import {verificationMethods} from 'matrix-js-sdk/src/crypto';
import MatrixClientBackedSettingsHandler from "./settings/handlers/MatrixClientBackedSettingsHandler";
import * as StorageManager from './utils/StorageManager';
import IdentityAuthClient from './IdentityAuthClient';
import { crossSigningCallbacks } from './SecurityManager';
import { crossSigningCallbacks, tryToUnlockSecretStorageWithDehydrationKey } from './SecurityManager';
import {SHOW_QR_CODE_METHOD} from "matrix-js-sdk/src/crypto/verification/QRCode";
export interface IMatrixClientCreds {
homeserverUrl: string;
identityServerUrl: string;
userId: string;
deviceId: string;
deviceId?: string;
accessToken: string;
guest: boolean;
guest?: boolean;
pickleKey?: string;
freshLogin?: boolean;
}
// TODO: Move this to the js-sdk
@ -192,6 +193,7 @@ class _MatrixClientPeg implements IMatrixClientPeg {
this.matrixClient.setCryptoTrustCrossSignedDevices(
!SettingsStore.getValue('e2ee.manuallyVerifyAllSessions'),
);
await tryToUnlockSecretStorageWithDehydrationKey(this.matrixClient);
StorageManager.setCryptoInitialised(true);
}
} catch (e) {

View file

@ -24,7 +24,6 @@ import dis from './dispatcher/dispatcher';
import * as sdk from './index';
import Modal from './Modal';
import { _t } from './languageHandler';
// import {MatrixClientPeg} from './MatrixClientPeg';
// Regex for what a "safe" or "Matrix-looking" localpart would be.
// TODO: Update as needed for https://github.com/matrix-org/matrix-doc/issues/1514
@ -44,70 +43,27 @@ export const SAFE_LOCALPART_REGEX = /^[a-z0-9=_\-./]+$/;
*/
export async function startAnyRegistrationFlow(options) {
if (options === undefined) options = {};
// look for an ILAG compatible flow. We define this as one
// which has only dummy or recaptcha flows. In practice it
// would support any stage InteractiveAuth supports, just not
// ones like email & msisdn which require the user to supply
// the relevant details in advance. We err on the side of
// caution though.
// XXX: ILAG is disabled for now,
// see https://github.com/vector-im/element-web/issues/8222
// const flows = await _getRegistrationFlows();
// const hasIlagFlow = flows.some((flow) => {
// return flow.stages.every((stage) => {
// return ['m.login.dummy', 'm.login.recaptcha', 'm.login.terms'].includes(stage);
// });
// });
// if (hasIlagFlow) {
// dis.dispatch({
// action: 'view_set_mxid',
// go_home_on_cancel: options.go_home_on_cancel,
// });
//} else {
const QuestionDialog = sdk.getComponent("dialogs.QuestionDialog");
const modal = Modal.createTrackedDialog('Registration required', '', QuestionDialog, {
hasCancelButton: true,
quitOnly: true,
title: _t("Sign In or Create Account"),
description: _t("Use your account or create a new one to continue."),
button: _t("Create Account"),
extraButtons: [
<button key="start_login" onClick={() => {
modal.close();
dis.dispatch({action: 'start_login', screenAfterLogin: options.screen_after});
}}>{ _t('Sign In') }</button>,
],
onFinished: (proceed) => {
if (proceed) {
dis.dispatch({action: 'start_registration', screenAfterLogin: options.screen_after});
} else if (options.go_home_on_cancel) {
dis.dispatch({action: 'view_home_page'});
} else if (options.go_welcome_on_cancel) {
dis.dispatch({action: 'view_welcome_page'});
}
},
});
//}
const QuestionDialog = sdk.getComponent("dialogs.QuestionDialog");
const modal = Modal.createTrackedDialog('Registration required', '', QuestionDialog, {
hasCancelButton: true,
quitOnly: true,
title: _t("Sign In or Create Account"),
description: _t("Use your account or create a new one to continue."),
button: _t("Create Account"),
extraButtons: [
<button key="start_login" onClick={() => {
modal.close();
dis.dispatch({action: 'start_login', screenAfterLogin: options.screen_after});
}}>{ _t('Sign In') }</button>,
],
onFinished: (proceed) => {
if (proceed) {
dis.dispatch({action: 'start_registration', screenAfterLogin: options.screen_after});
} else if (options.go_home_on_cancel) {
dis.dispatch({action: 'view_home_page'});
} else if (options.go_welcome_on_cancel) {
dis.dispatch({action: 'view_welcome_page'});
}
},
});
}
// async function _getRegistrationFlows() {
// try {
// await MatrixClientPeg.get().register(
// null,
// null,
// undefined,
// {},
// {},
// );
// console.log("Register request succeeded when it should have returned 401!");
// } catch (e) {
// if (e.httpStatus === 401) {
// return e.data.flows;
// }
// throw e;
// }
// throw new Error("Register request succeeded when it should have returned 401!");
// }

View file

@ -26,58 +26,6 @@ export function getDisplayAliasForRoom(room) {
return room.getCanonicalAlias() || room.getAltAliases()[0];
}
/**
* If the room contains only two members including the logged-in user,
* return the other one. Otherwise, return null.
*/
export function getOnlyOtherMember(room, myUserId) {
if (room.currentState.getJoinedMemberCount() === 2) {
return room.getJoinedMembers().filter(function(m) {
return m.userId !== myUserId;
})[0];
}
return null;
}
function _isConfCallRoom(room, myUserId, conferenceHandler) {
if (!conferenceHandler) return false;
const myMembership = room.getMyMembership();
if (myMembership != "join") {
return false;
}
const otherMember = getOnlyOtherMember(room, myUserId);
if (!otherMember) {
return false;
}
if (conferenceHandler.isConferenceUser(otherMember.userId)) {
return true;
}
return false;
}
// Cache whether a room is a conference call. Assumes that rooms will always
// either will or will not be a conference call room.
const isConfCallRoomCache = {
// $roomId: bool
};
export function isConfCallRoom(room, myUserId, conferenceHandler) {
if (isConfCallRoomCache[room.roomId] !== undefined) {
return isConfCallRoomCache[room.roomId];
}
const result = _isConfCallRoom(room, myUserId, conferenceHandler);
isConfCallRoomCache[room.roomId] = result;
return result;
}
export function looksLikeDirectMessageRoom(room, myUserId) {
const myMembership = room.getMyMembership();
const me = room.getMember(myUserId);

View file

@ -33,6 +33,11 @@ export const DEFAULTS: ConfigOptions = {
// Default conference domain
preferredDomain: "jitsi.riot.im",
},
desktopBuilds: {
available: true,
logo: require("../res/img/element-desktop-logo.svg"),
url: "https://element.io/get-started",
},
};
export default class SdkConfig {

View file

@ -24,6 +24,7 @@ import {encodeBase64} from "matrix-js-sdk/src/crypto/olmlib";
import { isSecureBackupRequired } from './utils/WellKnownUtils';
import AccessSecretStorageDialog from './components/views/dialogs/security/AccessSecretStorageDialog';
import RestoreKeyBackupDialog from './components/views/dialogs/security/RestoreKeyBackupDialog';
import SettingsStore from "./settings/SettingsStore";
// This stores the secret storage private keys in memory for the JS SDK. This is
// only meant to act as a cache to avoid prompting the user multiple times
@ -31,8 +32,13 @@ import RestoreKeyBackupDialog from './components/views/dialogs/security/RestoreK
// single secret storage operation, as it will clear the cached keys once the
// operation ends.
let secretStorageKeys = {};
let secretStorageKeyInfo = {};
let secretStorageBeingAccessed = false;
let nonInteractive = false;
let dehydrationCache = {};
function isCachingAllowed() {
return secretStorageBeingAccessed;
}
@ -66,6 +72,20 @@ async function confirmToDismiss() {
return !sure;
}
function makeInputToKey(keyInfo) {
return async ({ passphrase, recoveryKey }) => {
if (passphrase) {
return deriveKey(
passphrase,
keyInfo.passphrase.salt,
keyInfo.passphrase.iterations,
);
} else {
return decodeRecoveryKey(recoveryKey);
}
};
}
async function getSecretStorageKey({ keys: keyInfos }, ssssItemName) {
const keyInfoEntries = Object.entries(keyInfos);
if (keyInfoEntries.length > 1) {
@ -78,17 +98,18 @@ async function getSecretStorageKey({ keys: keyInfos }, ssssItemName) {
return [keyId, secretStorageKeys[keyId]];
}
const inputToKey = async ({ passphrase, recoveryKey }) => {
if (passphrase) {
return deriveKey(
passphrase,
keyInfo.passphrase.salt,
keyInfo.passphrase.iterations,
);
} else {
return decodeRecoveryKey(recoveryKey);
if (dehydrationCache.key) {
if (await MatrixClientPeg.get().checkSecretStorageKey(dehydrationCache.key, keyInfo)) {
cacheSecretStorageKey(keyId, dehydrationCache.key, keyInfo);
return [keyId, dehydrationCache.key];
}
};
}
if (nonInteractive) {
throw new Error("Could not unlock non-interactively");
}
const inputToKey = makeInputToKey(keyInfo);
const { finished } = Modal.createTrackedDialog("Access Secret Storage dialog", "",
AccessSecretStorageDialog,
/* props= */
@ -118,14 +139,56 @@ async function getSecretStorageKey({ keys: keyInfos }, ssssItemName) {
const key = await inputToKey(input);
// Save to cache to avoid future prompts in the current session
cacheSecretStorageKey(keyId, key);
cacheSecretStorageKey(keyId, key, keyInfo);
return [keyId, key];
}
function cacheSecretStorageKey(keyId, key) {
export async function getDehydrationKey(keyInfo, checkFunc) {
const inputToKey = makeInputToKey(keyInfo);
const { finished } = Modal.createTrackedDialog("Access Secret Storage dialog", "",
AccessSecretStorageDialog,
/* props= */
{
keyInfo,
checkPrivateKey: async (input) => {
const key = await inputToKey(input);
try {
checkFunc(key);
return true;
} catch (e) {
return false;
}
},
},
/* className= */ null,
/* isPriorityModal= */ false,
/* isStaticModal= */ false,
/* options= */ {
onBeforeClose: async (reason) => {
if (reason === "backgroundClick") {
return confirmToDismiss();
}
return true;
},
},
);
const [input] = await finished;
if (!input) {
throw new AccessCancelledError();
}
const key = await inputToKey(input);
// need to copy the key because rehydration (unpickling) will clobber it
dehydrationCache = {key: new Uint8Array(key), keyInfo};
return key;
}
function cacheSecretStorageKey(keyId, key, keyInfo) {
if (isCachingAllowed()) {
secretStorageKeys[keyId] = key;
secretStorageKeyInfo[keyId] = keyInfo;
}
}
@ -176,6 +239,7 @@ export const crossSigningCallbacks = {
getSecretStorageKey,
cacheSecretStorageKey,
onSecretRequested,
getDehydrationKey,
};
export async function promptForBackupPassphrase() {
@ -262,6 +326,18 @@ export async function accessSecretStorage(func = async () => { }, forceReset = f
await cli.bootstrapSecretStorage({
getKeyBackupPassphrase: promptForBackupPassphrase,
});
const keyId = Object.keys(secretStorageKeys)[0];
if (keyId && SettingsStore.getValue("feature_dehydration")) {
const dehydrationKeyInfo =
secretStorageKeyInfo[keyId] && secretStorageKeyInfo[keyId].passphrase
? {passphrase: secretStorageKeyInfo[keyId].passphrase}
: {};
console.log("Setting dehydration key");
await cli.setDehydrationKey(secretStorageKeys[keyId], dehydrationKeyInfo, "Backup device");
} else {
console.log("Not setting dehydration key: no SSSS key found");
}
}
// `return await` needed here to ensure `finally` block runs after the
@ -272,6 +348,57 @@ export async function accessSecretStorage(func = async () => { }, forceReset = f
secretStorageBeingAccessed = false;
if (!isCachingAllowed()) {
secretStorageKeys = {};
secretStorageKeyInfo = {};
}
}
}
// FIXME: this function name is a bit of a mouthful
export async function tryToUnlockSecretStorageWithDehydrationKey(client) {
const key = dehydrationCache.key;
let restoringBackup = false;
if (key && await client.isSecretStorageReady()) {
console.log("Trying to set up cross-signing using dehydration key");
secretStorageBeingAccessed = true;
nonInteractive = true;
try {
await client.checkOwnCrossSigningTrust();
// we also need to set a new dehydrated device to replace the
// device we rehydrated
const dehydrationKeyInfo =
dehydrationCache.keyInfo && dehydrationCache.keyInfo.passphrase
? {passphrase: dehydrationCache.keyInfo.passphrase}
: {};
await client.setDehydrationKey(key, dehydrationKeyInfo, "Backup device");
// and restore from backup
const backupInfo = await client.getKeyBackupVersion();
if (backupInfo) {
restoringBackup = true;
// don't await, because this can take a long time
client.restoreKeyBackupWithSecretStorage(backupInfo)
.finally(() => {
secretStorageBeingAccessed = false;
nonInteractive = false;
if (!isCachingAllowed()) {
secretStorageKeys = {};
secretStorageKeyInfo = {};
}
});
}
} finally {
dehydrationCache = {};
// the secret storage cache is needed for restoring from backup, so
// don't clear it yet if we're restoring from backup
if (!restoringBackup) {
secretStorageBeingAccessed = false;
nonInteractive = false;
if (!isCachingAllowed()) {
secretStorageKeys = {};
secretStorageKeyInfo = {};
}
}
}
}
}

View file

@ -16,12 +16,21 @@ limitations under the License.
*/
import {clamp} from "lodash";
import {MatrixEvent} from "matrix-js-sdk/src/models/event";
import {SerializedPart} from "./editor/parts";
import EditorModel from "./editor/model";
interface IHistoryItem {
parts: SerializedPart[];
replyEventId?: string;
}
export default class SendHistoryManager {
history: Array<HistoryItem> = [];
history: Array<IHistoryItem> = [];
prefix: string;
lastIndex: number = 0; // used for indexing the storage
currentIndex: number = 0; // used for indexing the loaded validated history Array
lastIndex = 0; // used for indexing the storage
currentIndex = 0; // used for indexing the loaded validated history Array
constructor(roomId: string, prefix: string) {
this.prefix = prefix + roomId;
@ -32,8 +41,7 @@ export default class SendHistoryManager {
while (itemJSON = sessionStorage.getItem(`${this.prefix}[${index}]`)) {
try {
const serializedParts = JSON.parse(itemJSON);
this.history.push(serializedParts);
this.history.push(JSON.parse(itemJSON));
} catch (e) {
console.warn("Throwing away unserialisable history", e);
break;
@ -45,15 +53,22 @@ export default class SendHistoryManager {
this.currentIndex = this.lastIndex + 1;
}
save(editorModel: Object) {
const serializedParts = editorModel.serializeParts();
this.history.push(serializedParts);
this.currentIndex = this.history.length;
this.lastIndex += 1;
sessionStorage.setItem(`${this.prefix}[${this.lastIndex}]`, JSON.stringify(serializedParts));
static createItem(model: EditorModel, replyEvent?: MatrixEvent): IHistoryItem {
return {
parts: model.serializeParts(),
replyEventId: replyEvent ? replyEvent.getId() : undefined,
};
}
getItem(offset: number): ?HistoryItem {
save(editorModel: EditorModel, replyEvent?: MatrixEvent) {
const item = SendHistoryManager.createItem(editorModel, replyEvent);
this.history.push(item);
this.currentIndex = this.history.length;
this.lastIndex += 1;
sessionStorage.setItem(`${this.prefix}[${this.lastIndex}]`, JSON.stringify(item));
}
getItem(offset: number): IHistoryItem {
this.currentIndex = clamp(this.currentIndex + offset, 0, this.history.length - 1);
return this.history[this.currentIndex];
}

View file

@ -14,12 +14,10 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import {MatrixClientPeg} from './MatrixClientPeg';
import CallHandler from './CallHandler';
import { _t } from './languageHandler';
import * as Roles from './Roles';
import {isValid3pidInvite} from "./RoomInvite";
import SettingsStore from "./settings/SettingsStore";
import {WidgetType} from "./widgets/WidgetType";
import {ALL_RULE_TYPES, ROOM_RULE_TYPES, SERVER_RULE_TYPES, USER_RULE_TYPES} from "./mjolnir/BanList";
function textForMemberEvent(ev) {
@ -29,7 +27,6 @@ function textForMemberEvent(ev) {
const prevContent = ev.getPrevContent();
const content = ev.getContent();
const ConferenceHandler = CallHandler.getConferenceHandler();
const reason = content.reason ? (_t('Reason') + ': ' + content.reason) : '';
switch (content.membership) {
case 'invite': {
@ -44,11 +41,7 @@ function textForMemberEvent(ev) {
return _t('%(targetName)s accepted an invitation.', {targetName});
}
} else {
if (ConferenceHandler && ConferenceHandler.isConferenceUser(ev.getStateKey())) {
return _t('%(senderName)s requested a VoIP conference.', {senderName});
} else {
return _t('%(senderName)s invited %(targetName)s.', {senderName, targetName});
}
return _t('%(senderName)s invited %(targetName)s.', {senderName, targetName});
}
}
case 'ban':
@ -85,17 +78,11 @@ function textForMemberEvent(ev) {
}
} else {
if (!ev.target) console.warn("Join message has no target! -- " + ev.getContent().state_key);
if (ConferenceHandler && ConferenceHandler.isConferenceUser(ev.getStateKey())) {
return _t('VoIP conference started.');
} else {
return _t('%(targetName)s joined the room.', {targetName});
}
return _t('%(targetName)s joined the room.', {targetName});
}
case 'leave':
if (ev.getSender() === ev.getStateKey()) {
if (ConferenceHandler && ConferenceHandler.isConferenceUser(ev.getStateKey())) {
return _t('VoIP conference finished.');
} else if (prevContent.membership === "invite") {
if (prevContent.membership === "invite") {
return _t('%(targetName)s rejected the invitation.', {targetName});
} else {
return _t('%(targetName)s left the room.', {targetName});
@ -476,10 +463,6 @@ function textForWidgetEvent(event) {
const {name: prevName, type: prevType, url: prevUrl} = event.getPrevContent();
const {name, type, url} = event.getContent() || {};
if (WidgetType.JITSI.matches(type) || WidgetType.JITSI.matches(prevType)) {
return textForJitsiWidgetEvent(event, senderName, url, prevUrl);
}
let widgetName = name || prevName || type || prevType || '';
// Apply sentence case to widget name
if (widgetName && widgetName.length > 0) {
@ -505,24 +488,6 @@ function textForWidgetEvent(event) {
}
}
function textForJitsiWidgetEvent(event, senderName, url, prevUrl) {
if (url) {
if (prevUrl) {
return _t('Group call modified by %(senderName)s', {
senderName,
});
} else {
return _t('Group call started by %(senderName)s', {
senderName,
});
}
} else {
return _t('Group call ended by %(senderName)s', {
senderName,
});
}
}
function textForMjolnirEvent(event) {
const senderName = event.getSender();
const {entity: prevEntity} = event.getPrevContent();

View file

@ -1,84 +0,0 @@
/*
Copyright 2018 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.
*/
// const OUTBOUND_API_NAME = 'toWidget';
// Initiate requests using the "toWidget" postMessage API and handle responses
// NOTE: ToWidgetPostMessageApi only handles message events with a data payload with a
// response field
export default class ToWidgetPostMessageApi {
constructor(timeoutMs) {
this._timeoutMs = timeoutMs || 5000; // default to 5s timer
this._counter = 0;
this._requestMap = {
// $ID: {resolve, reject}
};
this.start = this.start.bind(this);
this.stop = this.stop.bind(this);
this.onPostMessage = this.onPostMessage.bind(this);
}
start() {
window.addEventListener('message', this.onPostMessage);
}
stop() {
window.removeEventListener('message', this.onPostMessage);
}
onPostMessage(ev) {
// THIS IS ALL UNSAFE EXECUTION.
// We do not verify who the sender of `ev` is!
const payload = ev.data;
// NOTE: Workaround for running in a mobile WebView where a
// postMessage immediately triggers this callback even though it is
// not the response.
if (payload.response === undefined) {
return;
}
const promise = this._requestMap[payload.requestId];
if (!promise) {
return;
}
delete this._requestMap[payload.requestId];
promise.resolve(payload);
}
// Initiate outbound requests (toWidget)
exec(action, targetWindow, targetOrigin) {
targetWindow = targetWindow || window.parent; // default to parent window
targetOrigin = targetOrigin || "*";
this._counter += 1;
action.requestId = Date.now() + "-" + Math.random().toString(36) + "-" + this._counter;
return new Promise((resolve, reject) => {
this._requestMap[action.requestId] = {resolve, reject};
targetWindow.postMessage(action, targetOrigin);
if (this._timeoutMs > 0) {
setTimeout(() => {
if (!this._requestMap[action.requestId]) {
return;
}
console.error("postMessage request timed out. Sent object: " + JSON.stringify(action),
this._requestMap);
this._requestMap[action.requestId].reject(new Error("Timed out"));
delete this._requestMap[action.requestId];
}, this._timeoutMs);
}
});
}
}

View file

@ -1,135 +0,0 @@
/*
Copyright 2015, 2016 OpenMarket Ltd
Copyright 2019 The Matrix.org Foundation C.I.C.
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 {createNewMatrixCall as jsCreateNewMatrixCall, Room} from "matrix-js-sdk";
import CallHandler from './CallHandler';
import {MatrixClientPeg} from "./MatrixClientPeg";
// FIXME: this is Element specific code, but will be removed shortly when we
// switch over to Jitsi entirely for video conferencing.
// FIXME: This currently forces Element to try to hit the matrix.org AS for
// conferencing. This is bad because it prevents people running their own ASes
// from being used. This isn't permanent and will be customisable in the future:
// see the proposal at docs/conferencing.md for more info.
const USER_PREFIX = "fs_";
const DOMAIN = "matrix.org";
export function ConferenceCall(matrixClient, groupChatRoomId) {
this.client = matrixClient;
this.groupRoomId = groupChatRoomId;
this.confUserId = getConferenceUserIdForRoom(this.groupRoomId);
}
ConferenceCall.prototype.setup = function() {
const self = this;
return this._joinConferenceUser().then(function() {
return self._getConferenceUserRoom();
}).then(function(room) {
// return a call for *this* room to be placed. We also tack on
// confUserId to speed up lookups (else we'd need to loop every room
// looking for a 1:1 room with this conf user ID!)
const call = jsCreateNewMatrixCall(self.client, room.roomId);
call.confUserId = self.confUserId;
call.groupRoomId = self.groupRoomId;
return call;
});
};
ConferenceCall.prototype._joinConferenceUser = function() {
// Make sure the conference user is in the group chat room
const groupRoom = this.client.getRoom(this.groupRoomId);
if (!groupRoom) {
return Promise.reject("Bad group room ID");
}
const member = groupRoom.getMember(this.confUserId);
if (member && member.membership === "join") {
return Promise.resolve();
}
return this.client.invite(this.groupRoomId, this.confUserId);
};
ConferenceCall.prototype._getConferenceUserRoom = function() {
// Use an existing 1:1 with the conference user; else make one
const rooms = this.client.getRooms();
let confRoom = null;
for (let i = 0; i < rooms.length; i++) {
const confUser = rooms[i].getMember(this.confUserId);
if (confUser && confUser.membership === "join" &&
rooms[i].getJoinedMemberCount() === 2) {
confRoom = rooms[i];
break;
}
}
if (confRoom) {
return Promise.resolve(confRoom);
}
return this.client.createRoom({
preset: "private_chat",
invite: [this.confUserId],
}).then(function(res) {
return new Room(res.room_id, null, MatrixClientPeg.get().getUserId());
});
};
/**
* Check if this user ID is in fact a conference bot.
* @param {string} userId The user ID to check.
* @return {boolean} True if it is a conference bot.
*/
export function isConferenceUser(userId) {
if (userId.indexOf("@" + USER_PREFIX) !== 0) {
return false;
}
const base64part = userId.split(":")[0].substring(1 + USER_PREFIX.length);
if (base64part) {
const decoded = new Buffer(base64part, "base64").toString();
// ! $STUFF : $STUFF
return /^!.+:.+/.test(decoded);
}
return false;
}
export function getConferenceUserIdForRoom(roomId) {
// abuse browserify's core node Buffer support (strip padding ='s)
const base64RoomId = new Buffer(roomId).toString("base64").replace(/=/g, "");
return "@" + USER_PREFIX + base64RoomId + ":" + DOMAIN;
}
export function createNewMatrixCall(client, roomId) {
const confCall = new ConferenceCall(
client, roomId,
);
return confCall.setup();
}
export function getConferenceCallForRoom(roomId) {
// search for a conference 1:1 call for this group chat room ID
const activeCall = CallHandler.getAnyActiveCall();
if (activeCall && activeCall.confUserId) {
const thisRoomConfUserId = getConferenceUserIdForRoom(
roomId,
);
if (thisRoomConfUserId === activeCall.confUserId) {
return activeCall;
}
}
return null;
}
// TODO: Document this.
export const slot = 'conference';

View file

@ -1,212 +0,0 @@
/*
Copyright 2017 New Vector Ltd
Copyright 2019 Travis Ralston
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.
*/
/*
* See - https://docs.google.com/document/d/1uPF7XWY_dXTKVKV7jZQ2KmsI19wn9-kFRgQ1tFQP7wQ/edit?usp=sharing for
* spec. details / documentation.
*/
import FromWidgetPostMessageApi from './FromWidgetPostMessageApi';
import ToWidgetPostMessageApi from './ToWidgetPostMessageApi';
import Modal from "./Modal";
import {MatrixClientPeg} from "./MatrixClientPeg";
import SettingsStore from "./settings/SettingsStore";
import WidgetOpenIDPermissionsDialog from "./components/views/dialogs/WidgetOpenIDPermissionsDialog";
import WidgetUtils from "./utils/WidgetUtils";
import {KnownWidgetActions} from "./widgets/WidgetApi";
if (!global.mxFromWidgetMessaging) {
global.mxFromWidgetMessaging = new FromWidgetPostMessageApi();
global.mxFromWidgetMessaging.start();
}
if (!global.mxToWidgetMessaging) {
global.mxToWidgetMessaging = new ToWidgetPostMessageApi();
global.mxToWidgetMessaging.start();
}
const OUTBOUND_API_NAME = 'toWidget';
export default class WidgetMessaging {
/**
* @param {string} widgetId The widget's ID
* @param {string} wurl The raw URL of the widget as in the event (the 'wURL')
* @param {string} renderedUrl The url used in the widget's iframe (either similar to the wURL
* or a different URL of the clients choosing if it is using its own impl).
* @param {bool} isUserWidget If true, the widget is a user widget, otherwise it's a room widget
* @param {object} target Where widget messages should be sent (eg. the iframe object)
*/
constructor(widgetId, wurl, renderedUrl, isUserWidget, target) {
this.widgetId = widgetId;
this.wurl = wurl;
this.renderedUrl = renderedUrl;
this.isUserWidget = isUserWidget;
this.target = target;
this.fromWidget = global.mxFromWidgetMessaging;
this.toWidget = global.mxToWidgetMessaging;
this._onOpenIdRequest = this._onOpenIdRequest.bind(this);
this.start();
}
messageToWidget(action) {
action.widgetId = this.widgetId; // Required to be sent for all outbound requests
return this.toWidget.exec(action, this.target).then((data) => {
// Check for errors and reject if found
if (data.response === undefined) { // null is valid
throw new Error("Missing 'response' field");
}
if (data.response && data.response.error) {
const err = data.response.error;
const msg = String(err.message ? err.message : "An error was returned");
if (err._error) {
console.error(err._error);
}
// Potential XSS attack if 'msg' is not appropriately sanitized,
// as it is untrusted input by our parent window (which we assume is Element).
// We can't aggressively sanitize [A-z0-9] since it might be a translation.
throw new Error(msg);
}
// Return the response field for the request
return data.response;
});
}
/**
* Tells the widget that the client is ready to handle further widget requests.
* @returns {Promise<*>} Resolves after the widget has acknowledged the ready message.
*/
flagReadyToContinue() {
return this.messageToWidget({
api: OUTBOUND_API_NAME,
action: KnownWidgetActions.ClientReady,
});
}
/**
* Tells the widget that it should terminate now.
* @returns {Promise<*>} Resolves when widget has acknowledged the message.
*/
terminate() {
return this.messageToWidget({
api: OUTBOUND_API_NAME,
action: KnownWidgetActions.Terminate,
});
}
/**
* Request a screenshot from a widget
* @return {Promise} To be resolved with screenshot data when it has been generated
*/
getScreenshot() {
console.log('Requesting screenshot for', this.widgetId);
return this.messageToWidget({
api: OUTBOUND_API_NAME,
action: "screenshot",
})
.catch((error) => new Error("Failed to get screenshot: " + error.message))
.then((response) => response.screenshot);
}
/**
* Request capabilities required by the widget
* @return {Promise} To be resolved with an array of requested widget capabilities
*/
getCapabilities() {
console.log('Requesting capabilities for', this.widgetId);
return this.messageToWidget({
api: OUTBOUND_API_NAME,
action: "capabilities",
}).then((response) => {
console.log('Got capabilities for', this.widgetId, response.capabilities);
return response.capabilities;
});
}
sendVisibility(visible) {
return this.messageToWidget({
api: OUTBOUND_API_NAME,
action: "visibility",
visible,
})
.catch((error) => {
console.error("Failed to send visibility: ", error);
});
}
start() {
this.fromWidget.addEndpoint(this.widgetId, this.renderedUrl);
this.fromWidget.addListener("get_openid", this._onOpenIdRequest);
}
stop() {
this.fromWidget.removeEndpoint(this.widgetId, this.renderedUrl);
this.fromWidget.removeListener("get_openid", this._onOpenIdRequest);
}
async _onOpenIdRequest(ev, rawEv) {
if (ev.widgetId !== this.widgetId) return; // not interesting
const widgetSecurityKey = WidgetUtils.getWidgetSecurityKey(this.widgetId, this.wurl, this.isUserWidget);
const settings = SettingsStore.getValue("widgetOpenIDPermissions");
if (settings.deny && settings.deny.includes(widgetSecurityKey)) {
this.fromWidget.sendResponse(rawEv, {state: "blocked"});
return;
}
if (settings.allow && settings.allow.includes(widgetSecurityKey)) {
const responseBody = {state: "allowed"};
const credentials = await MatrixClientPeg.get().getOpenIdToken();
Object.assign(responseBody, credentials);
this.fromWidget.sendResponse(rawEv, responseBody);
return;
}
// Confirm that we received the request
this.fromWidget.sendResponse(rawEv, {state: "request"});
// Actually ask for permission to send the user's data
Modal.createTrackedDialog("OpenID widget permissions", '',
WidgetOpenIDPermissionsDialog, {
widgetUrl: this.wurl,
widgetId: this.widgetId,
isUserWidget: this.isUserWidget,
onFinished: async (confirm) => {
const responseBody = {
// Legacy (early draft) fields
success: confirm,
// New style MSC1960 fields
state: confirm ? "allowed" : "blocked",
original_request_id: ev.requestId, // eslint-disable-line camelcase
};
if (confirm) {
const credentials = await MatrixClientPeg.get().getOpenIdToken();
Object.assign(responseBody, credentials);
}
this.messageToWidget({
api: OUTBOUND_API_NAME,
action: "openid_credentials",
data: responseBody,
}).catch((error) => {
console.error("Failed to send OpenID credentials: ", error);
});
},
},
);
}
}

View file

@ -1,37 +0,0 @@
/*
Copyright 2018 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.
*/
/**
* Represents mapping of widget instance to URLs for trusted postMessage communication.
*/
export default class WidgetMessageEndpoint {
/**
* Mapping of widget instance to URL for trusted postMessage communication.
* @param {string} widgetId Unique widget identifier
* @param {string} endpointUrl Widget wurl origin.
*/
constructor(widgetId, endpointUrl) {
if (!widgetId) {
throw new Error("No widgetId specified in widgetMessageEndpoint constructor");
}
if (!endpointUrl) {
throw new Error("No endpoint specified in widgetMessageEndpoint constructor");
}
this.widgetId = widgetId;
this.endpointUrl = endpointUrl;
}
}

View file

@ -166,7 +166,8 @@ export const RovingTabIndexProvider: React.FC<IProps> = ({children, handleHomeEn
const onKeyDownHandler = useCallback((ev) => {
let handled = false;
if (handleHomeEnd) {
// Don't interfere with input default keydown behaviour
if (handleHomeEnd && ev.target.tagName !== "INPUT") {
// check if we actually have any items
switch (ev.key) {
case Key.HOME:

View file

@ -28,6 +28,9 @@ interface IProps extends Omit<React.HTMLProps<HTMLDivElement>, "onKeyDown"> {
const Toolbar: React.FC<IProps> = ({children, ...props}) => {
const onKeyDown = (ev: React.KeyboardEvent, state: IState) => {
const target = ev.target as HTMLElement;
// Don't interfere with input default keydown behaviour
if (target.tagName === "INPUT") return;
let handled = true;
// HOME and END are handled by RovingTabIndexProvider

View file

@ -31,7 +31,7 @@ import AccessibleButton from "../../../../components/views/elements/AccessibleBu
import DialogButtons from "../../../../components/views/elements/DialogButtons";
import InlineSpinner from "../../../../components/views/elements/InlineSpinner";
import RestoreKeyBackupDialog from "../../../../components/views/dialogs/security/RestoreKeyBackupDialog";
import { isSecureBackupRequired } from '../../../../utils/WellKnownUtils';
import { getSecureBackupSetupMethods, isSecureBackupRequired } from '../../../../utils/WellKnownUtils';
const PHASE_LOADING = 0;
const PHASE_LOADERROR = 1;
@ -87,10 +87,16 @@ export default class CreateSecretStorageDialog extends React.PureComponent {
canUploadKeysWithPasswordOnly: null,
accountPassword: props.accountPassword || "",
accountPasswordCorrect: null,
passPhraseKeySelected: CREATE_STORAGE_OPTION_KEY,
canSkip: !isSecureBackupRequired(),
};
const setupMethods = getSecureBackupSetupMethods();
if (setupMethods.includes("key")) {
this.state.passPhraseKeySelected = CREATE_STORAGE_OPTION_KEY;
} else {
this.state.passPhraseKeySelected = CREATE_STORAGE_OPTION_PASSPHRASE;
}
this._passphraseField = createRef();
this._fetchBackupInfo();
@ -441,39 +447,55 @@ export default class CreateSecretStorageDialog extends React.PureComponent {
});
}
_renderOptionKey() {
return (
<StyledRadioButton
key={CREATE_STORAGE_OPTION_KEY}
value={CREATE_STORAGE_OPTION_KEY}
name="keyPassphrase"
checked={this.state.passPhraseKeySelected === CREATE_STORAGE_OPTION_KEY}
outlined
>
<div className="mx_CreateSecretStorageDialog_optionTitle">
<span className="mx_CreateSecretStorageDialog_optionIcon mx_CreateSecretStorageDialog_optionIcon_secureBackup"></span>
{_t("Generate a Security Key")}
</div>
<div>{_t("Well generate a Security Key for you to store somewhere safe, like a password manager or a safe.")}</div>
</StyledRadioButton>
);
}
_renderOptionPassphrase() {
return (
<StyledRadioButton
key={CREATE_STORAGE_OPTION_PASSPHRASE}
value={CREATE_STORAGE_OPTION_PASSPHRASE}
name="keyPassphrase"
checked={this.state.passPhraseKeySelected === CREATE_STORAGE_OPTION_PASSPHRASE}
outlined
>
<div className="mx_CreateSecretStorageDialog_optionTitle">
<span className="mx_CreateSecretStorageDialog_optionIcon mx_CreateSecretStorageDialog_optionIcon_securePhrase"></span>
{_t("Enter a Security Phrase")}
</div>
<div>{_t("Use a secret phrase only you know, and optionally save a Security Key to use for backup.")}</div>
</StyledRadioButton>
);
}
_renderPhaseChooseKeyPassphrase() {
const setupMethods = getSecureBackupSetupMethods();
const optionKey = setupMethods.includes("key") ? this._renderOptionKey() : null;
const optionPassphrase = setupMethods.includes("passphrase") ? this._renderOptionPassphrase() : null;
return <form onSubmit={this._onChooseKeyPassphraseFormSubmit}>
<p className="mx_CreateSecretStorageDialog_centeredBody">{_t(
"Safeguard against losing access to encrypted messages & data by " +
"backing up encryption keys on your server.",
)}</p>
<div className="mx_CreateSecretStorageDialog_primaryContainer" role="radiogroup" onChange={this._onKeyPassphraseChange}>
<StyledRadioButton
key={CREATE_STORAGE_OPTION_KEY}
value={CREATE_STORAGE_OPTION_KEY}
name="keyPassphrase"
checked={this.state.passPhraseKeySelected === CREATE_STORAGE_OPTION_KEY}
outlined
>
<div className="mx_CreateSecretStorageDialog_optionTitle">
<span className="mx_CreateSecretStorageDialog_optionIcon mx_CreateSecretStorageDialog_optionIcon_secureBackup"></span>
{_t("Generate a Security Key")}
</div>
<div>{_t("Well generate a Security Key for you to store somewhere safe, like a password manager or a safe.")}</div>
</StyledRadioButton>
<StyledRadioButton
key={CREATE_STORAGE_OPTION_PASSPHRASE}
value={CREATE_STORAGE_OPTION_PASSPHRASE}
name="keyPassphrase"
checked={this.state.passPhraseKeySelected === CREATE_STORAGE_OPTION_PASSPHRASE}
outlined
>
<div className="mx_CreateSecretStorageDialog_optionTitle">
<span className="mx_CreateSecretStorageDialog_optionIcon mx_CreateSecretStorageDialog_optionIcon_securePhrase"></span>
{_t("Enter a Security Phrase")}
</div>
<div>{_t("Use a secret phrase only you know, and optionally save a Security Key to use for backup.")}</div>
</StyledRadioButton>
{optionKey}
{optionPassphrase}
</div>
<DialogButtons
primaryButton={_t("Continue")}

View file

@ -25,6 +25,7 @@ import EventIndexPeg from "../../indexing/EventIndexPeg";
import { _t } from '../../languageHandler';
import BaseCard from "../views/right_panel/BaseCard";
import {RightPanelPhases} from "../../stores/RightPanelStorePhases";
import DesktopBuildsNotice, {WarningKind} from "../views/elements/DesktopBuildsNotice";
/*
* Component which shows the filtered file using a TimelinePanel
@ -222,6 +223,8 @@ class FilePanel extends React.Component {
<p>{_t('Attach files from chat or just drag and drop them anywhere in a room.')}</p>
</div>);
const isRoomEncrypted = this.noRoom ? false : MatrixClientPeg.get().isRoomEncrypted(this.props.roomId);
if (this.state.timelineSet) {
// console.log("rendering TimelinePanel for timelineSet " + this.state.timelineSet.room.roomId + " " +
// "(" + this.state.timelineSet._timelines.join(", ") + ")" + " with key " + this.props.roomId);
@ -232,6 +235,7 @@ class FilePanel extends React.Component {
previousPhase={RightPanelPhases.RoomSummary}
withoutScrollContainer
>
<DesktopBuildsNotice isRoomEncrypted={isRoomEncrypted} kind={WarningKind.Files} />
<TimelinePanel
manageReadReceipts={false}
manageReadMarkers={false}

View file

@ -27,7 +27,6 @@ import CallMediaHandler from '../../CallMediaHandler';
import { fixupColorFonts } from '../../utils/FontManager';
import * as sdk from '../../index';
import dis from '../../dispatcher/dispatcher';
import sessionStore from '../../stores/SessionStore';
import {MatrixClientPeg, IMatrixClientCreds} from '../../MatrixClientPeg';
import SettingsStore from "../../settings/SettingsStore";
@ -41,10 +40,6 @@ import HomePage from "./HomePage";
import ResizeNotifier from "../../utils/ResizeNotifier";
import PlatformPeg from "../../PlatformPeg";
import { DefaultTagID } from "../../stores/room-list/models";
import {
showToast as showSetPasswordToast,
hideToast as hideSetPasswordToast,
} from "../../toasts/SetPasswordToast";
import {
showToast as showServerLimitToast,
hideToast as hideServerLimitToast,
@ -85,7 +80,6 @@ interface IProps {
threepidInvite?: IThreepidInvite;
roomOobData?: object;
currentRoomId: string;
ConferenceHandler?: object;
collapseLhs: boolean;
config: {
piwik: {
@ -150,8 +144,6 @@ class LoggedInView extends React.Component<IProps, IState> {
protected readonly _matrixClient: MatrixClient;
protected readonly _roomView: React.RefObject<any>;
protected readonly _resizeContainer: React.RefObject<ResizeHandle>;
protected readonly _sessionStore: sessionStore;
protected readonly _sessionStoreToken: { remove: () => void };
protected readonly _compactLayoutWatcherRef: string;
protected resizer: Resizer;
@ -172,12 +164,6 @@ class LoggedInView extends React.Component<IProps, IState> {
document.addEventListener('keydown', this._onNativeKeyDown, false);
this._sessionStore = sessionStore;
this._sessionStoreToken = this._sessionStore.addListener(
this._setStateFromSessionStore,
);
this._setStateFromSessionStore();
this._updateServerNoticeEvents();
this._matrixClient.on("accountData", this.onAccountData);
@ -206,9 +192,6 @@ class LoggedInView extends React.Component<IProps, IState> {
this._matrixClient.removeListener("sync", this.onSync);
this._matrixClient.removeListener("RoomState.events", this.onRoomStateEvents);
SettingsStore.unwatchSetting(this._compactLayoutWatcherRef);
if (this._sessionStoreToken) {
this._sessionStoreToken.remove();
}
this.resizer.detach();
}
@ -229,14 +212,6 @@ class LoggedInView extends React.Component<IProps, IState> {
return this._roomView.current.canResetTimeline();
};
_setStateFromSessionStore = () => {
if (this._sessionStore.getCachedPassword()) {
showSetPasswordToast();
} else {
hideSetPasswordToast();
}
};
_createResizer() {
const classNames = {
handle: "mx_ResizeHandle",
@ -637,7 +612,6 @@ class LoggedInView extends React.Component<IProps, IState> {
viaServers={this.props.viaServers}
key={this.props.currentRoomId || 'roomview'}
disabled={this.props.middleDisabled}
ConferenceHandler={this.props.ConferenceHandler}
resizeNotifier={this.props.resizeNotifier}
/>;
break;

View file

@ -30,7 +30,7 @@ import 'what-input';
import Analytics from "../../Analytics";
import { DecryptionFailureTracker } from "../../DecryptionFailureTracker";
import { MatrixClientPeg } from "../../MatrixClientPeg";
import { MatrixClientPeg, IMatrixClientCreds } from "../../MatrixClientPeg";
import PlatformPeg from "../../PlatformPeg";
import SdkConfig from "../../SdkConfig";
import * as RoomListSorter from "../../RoomListSorter";
@ -80,6 +80,7 @@ import { leaveRoomBehaviour } from "../../utils/membership";
import CreateCommunityPrototypeDialog from "../views/dialogs/CreateCommunityPrototypeDialog";
import ThreepidInviteStore, { IThreepidInvite, IThreepidInviteWireFormat } from "../../stores/ThreepidInviteStore";
import {UIFeature} from "../../settings/UIFeature";
import { CommunityPrototypeStore } from "../../stores/CommunityPrototypeStore";
/** constants for MatrixChat.state.view */
export enum Views {
@ -148,7 +149,6 @@ interface IRoomInfo {
interface IProps { // TODO type things better
config: Record<string, any>;
serverConfig?: ValidatedServerConfig;
ConferenceHandler?: any;
onNewScreen: (screen: string, replaceLast: boolean) => void;
enableGuest?: boolean;
// the queryParams extracted from the [real] query-string of the URI
@ -290,7 +290,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
// When the session loads it'll be detected as soft logged out and a dispatch
// will be sent out to say that, triggering this MatrixChat to show the soft
// logout page.
Lifecycle.loadSession({});
Lifecycle.loadSession();
}
this.accountPassword = null;
@ -670,9 +670,6 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
case 'view_home_page':
this.viewHome();
break;
case 'view_set_mxid':
this.setMxId(payload);
break;
case 'view_start_chat_or_reuse':
this.chatCreateOrReuse(payload.user_id);
break;
@ -985,37 +982,19 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
});
}
private setMxId(payload) {
const SetMxIdDialog = sdk.getComponent('views.dialogs.SetMxIdDialog');
const close = Modal.createTrackedDialog('Set MXID', '', SetMxIdDialog, {
homeserverUrl: MatrixClientPeg.get().getHomeserverUrl(),
onFinished: (submitted, credentials) => {
if (!submitted) {
dis.dispatch({
action: 'cancel_after_sync_prepared',
});
if (payload.go_home_on_cancel) {
dis.dispatch({
action: 'view_home_page',
});
}
return;
}
MatrixClientPeg.setJustRegisteredUserId(credentials.user_id);
this.onRegistered(credentials);
},
onDifferentServerClicked: (ev) => {
dis.dispatch({action: 'start_registration'});
close();
},
onLoginClick: (ev) => {
dis.dispatch({action: 'start_login'});
close();
},
}).close;
}
private async createRoom(defaultPublic = false) {
const communityId = CommunityPrototypeStore.instance.getSelectedCommunityId();
if (communityId) {
// double check the user will have permission to associate this room with the community
if (!CommunityPrototypeStore.instance.isAdminOf(communityId)) {
Modal.createTrackedDialog('Pre-failure to create room', '', ErrorDialog, {
title: _t("Cannot create rooms in this community"),
description: _t("You do not have permission to create rooms in this community."),
});
return;
}
}
const CreateRoomDialog = sdk.getComponent('dialogs.CreateRoomDialog');
const modal = Modal.createTrackedDialog('Create Room', '', CreateRoomDialog, { defaultPublic });
@ -1802,12 +1781,12 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
this.showScreen("forgot_password");
};
onRegisterFlowComplete = (credentials: object, password: string) => {
onRegisterFlowComplete = (credentials: IMatrixClientCreds, password: string) => {
return this.onUserCompletedLoginFlow(credentials, password);
};
// returns a promise which resolves to the new MatrixClient
onRegistered(credentials: object) {
onRegistered(credentials: IMatrixClientCreds) {
return Lifecycle.setLoggedIn(credentials);
}
@ -1843,7 +1822,12 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
} else {
subtitle = `${this.subTitleStatus} ${subtitle}`;
}
document.title = `${SdkConfig.get().brand} ${subtitle}`;
const title = `${SdkConfig.get().brand} ${subtitle}`;
if (document.title !== title) {
document.title = title;
}
}
updateStatusIndicator(state: string, prevState: string) {
@ -1888,7 +1872,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
* Note: SSO users (and any others using token login) currently do not pass through
* this, as they instead jump straight into the app after `attemptTokenLogin`.
*/
onUserCompletedLoginFlow = async (credentials: object, password: string) => {
onUserCompletedLoginFlow = async (credentials: IMatrixClientCreds, password: string) => {
this.accountPassword = password;
// self-destruct the password after 5mins
if (this.accountPasswordTimer !== null) clearTimeout(this.accountPasswordTimer);

View file

@ -1,9 +1,6 @@
/*
Copyright 2015, 2016 OpenMarket Ltd
Copyright 2017 Vector Creations Ltd
Copyright 2017, 2018 New Vector Ltd
Copyright 2019 Michael Telatynski <7t3chguy@gmail.com>
Copyright 2019 The Matrix.org Foundation C.I.C.
Copyright 2015 - 2020 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@ -162,7 +159,7 @@ export default class RightPanel extends React.Component {
}
onRoomStateMember(ev, state, member) {
if (member.roomId !== this.props.room.roomId) {
if (!this.props.room || member.roomId !== this.props.room.roomId) {
return;
}
// redraw the badge on the membership list
@ -202,13 +199,19 @@ export default class RightPanel extends React.Component {
dis.dispatch({
action: "view_home_page",
});
} else if (this.state.phase === RightPanelPhases.EncryptionPanel &&
this.state.verificationRequest && this.state.verificationRequest.pending
) {
// When the user clicks close on the encryption panel cancel the pending request first if any
this.state.verificationRequest.cancel();
} else {
// Otherwise we have got our user from RoomViewStore which means we're being shown
// within a room/group, so go back to the member panel if we were in the encryption panel,
// or the member list if we were in the member panel... phew.
const isEncryptionPhase = this.state.phase === RightPanelPhases.EncryptionPanel;
dis.dispatch({
action: Action.ViewUser,
member: this.state.phase === RightPanelPhases.EncryptionPanel ? this.state.member : null,
member: isEncryptionPhase ? this.state.member : null,
});
}
};

View file

@ -35,7 +35,7 @@ import GroupStore from "../../stores/GroupStore";
import FlairStore from "../../stores/FlairStore";
const MAX_NAME_LENGTH = 80;
const MAX_TOPIC_LENGTH = 160;
const MAX_TOPIC_LENGTH = 800;
function track(action) {
Analytics.trackEvent('RoomDirectory', action);
@ -497,6 +497,9 @@ export default class RoomDirectory extends React.Component {
}
let topic = room.topic || '';
// Additional truncation based on line numbers is done via CSS,
// but to ensure that the DOM is not polluted with a huge string
// we give it a hard limit before rendering.
if (topic.length > MAX_TOPIC_LENGTH) {
topic = `${topic.substring(0, MAX_TOPIC_LENGTH)}...`;
}

View file

@ -69,7 +69,6 @@ import PinnedEventsPanel from "../views/rooms/PinnedEventsPanel";
import AuxPanel from "../views/rooms/AuxPanel";
import RoomHeader from "../views/rooms/RoomHeader";
import TintableSvg from "../views/elements/TintableSvg";
import type * as ConferenceHandler from '../../VectorConferenceHandler';
import {XOR} from "../../@types/common";
import { IThreepidInvite } from "../../stores/ThreepidInviteStore";
@ -84,8 +83,6 @@ if (DEBUG) {
}
interface IProps {
ConferenceHandler?: ConferenceHandler;
threepidInvite: IThreepidInvite,
// Any data about the room that would normally come from the homeserver
@ -181,7 +178,6 @@ export interface IState {
matrixClientIsReady: boolean;
showUrlPreview?: boolean;
e2eStatus?: E2EStatus;
displayConfCallNotification?: boolean;
rejecting?: boolean;
rejectError?: Error;
}
@ -488,8 +484,6 @@ export default class RoomView extends React.Component<IProps, IState> {
callState: callState,
});
this.updateConfCallNotification();
window.addEventListener('beforeunload', this.onPageUnload);
if (this.props.resizeNotifier) {
this.props.resizeNotifier.on("middlePanelResized", this.onResize);
@ -724,10 +718,6 @@ export default class RoomView extends React.Component<IProps, IState> {
callState = call.call_state;
}
// possibly remove the conf call notification if we're now in
// the conf
this.updateConfCallNotification();
this.setState({
callState: callState,
});
@ -1018,9 +1008,6 @@ export default class RoomView extends React.Component<IProps, IState> {
// rate limited because a power level change will emit an event for every member in the room.
private updateRoomMembers = rateLimitedFunc((dueToMember) => {
// a member state changed in this room
// refresh the conf call notification state
this.updateConfCallNotification();
this.updateDMState();
let memberCountInfluence = 0;
@ -1049,30 +1036,6 @@ export default class RoomView extends React.Component<IProps, IState> {
this.setState({isAlone: joinedOrInvitedMemberCount === 1});
}
private updateConfCallNotification() {
const room = this.state.room;
if (!room || !this.props.ConferenceHandler) {
return;
}
const confMember = room.getMember(
this.props.ConferenceHandler.getConferenceUserIdForRoom(room.roomId),
);
if (!confMember) {
return;
}
const confCall = this.props.ConferenceHandler.getConferenceCallForRoom(confMember.roomId);
// A conf call notification should be displayed if there is an ongoing
// conf call but this cilent isn't a part of it.
this.setState({
displayConfCallNotification: (
(!confCall || confCall.call_state === "ended") &&
confMember.membership === "join"
),
});
}
private updateDMState() {
const room = this.state.room;
if (room.getMyMembership() != "join") {
@ -1127,42 +1090,7 @@ export default class RoomView extends React.Component<IProps, IState> {
room_id: this.getRoomId(),
},
});
// Don't peek whilst registering otherwise getPendingEventList complains
// Do this by indicating our intention to join
// XXX: ILAG is disabled for now,
// see https://github.com/vector-im/element-web/issues/8222
dis.dispatch({action: 'require_registration'});
// dis.dispatch({
// action: 'will_join',
// });
// const SetMxIdDialog = sdk.getComponent('views.dialogs.SetMxIdDialog');
// const close = Modal.createTrackedDialog('Set MXID', '', SetMxIdDialog, {
// homeserverUrl: cli.getHomeserverUrl(),
// onFinished: (submitted, credentials) => {
// if (submitted) {
// this.props.onRegistered(credentials);
// } else {
// dis.dispatch({
// action: 'cancel_after_sync_prepared',
// });
// dis.dispatch({
// action: 'cancel_join',
// });
// }
// },
// onDifferentServerClicked: (ev) => {
// dis.dispatch({action: 'start_registration'});
// close();
// },
// onLoginClick: (ev) => {
// dis.dispatch({action: 'start_login'});
// close();
// },
// }).close;
// return;
} else {
Promise.resolve().then(() => {
const signUrl = this.props.threepidInvite?.signUrl;
@ -1681,7 +1609,7 @@ export default class RoomView extends React.Component<IProps, IState> {
if (!this.state.room) {
return null;
}
return CallHandler.getCallForRoom(this.state.room.roomId);
return CallHandler.sharedInstance().getCallForRoom(this.state.room.roomId);
}
// this has to be a proper method rather than an unnamed function,
@ -1857,7 +1785,6 @@ export default class RoomView extends React.Component<IProps, IState> {
let aux = null;
let previewBar;
let hideCancel = false;
let forceHideRightPanel = false;
if (this.state.forwardingEvent) {
aux = <ForwardMessage onCancelClick={this.onCancelClick} />;
} else if (this.state.searching) {
@ -1866,6 +1793,7 @@ export default class RoomView extends React.Component<IProps, IState> {
searchInProgress={this.state.searchInProgress}
onCancelClick={this.onCancelSearchClick}
onSearch={this.onSearch}
isRoomEncrypted={this.context.isRoomEncrypted(this.state.room.roomId)}
/>;
} else if (showRoomUpgradeBar) {
aux = <RoomUpgradeWarningBar room={this.state.room} recommendation={roomVersionRecommendation} />;
@ -1901,8 +1829,6 @@ export default class RoomView extends React.Component<IProps, IState> {
{ previewBar }
</div>
);
} else {
forceHideRightPanel = true;
}
} else if (hiddenHighlightCount > 0) {
aux = (
@ -1924,9 +1850,7 @@ export default class RoomView extends React.Component<IProps, IState> {
room={this.state.room}
fullHeight={false}
userId={this.context.credentials.userId}
conferenceHandler={this.props.ConferenceHandler}
draggingFile={this.state.draggingFile}
displayConfCallNotification={this.state.displayConfCallNotification}
maxHeight={this.state.auxPanelMaxHeight}
showApps={this.state.showApps}
hideAppsDrawer={false}
@ -2107,7 +2031,7 @@ export default class RoomView extends React.Component<IProps, IState> {
"mx_fadable_faded": this.props.disabled,
});
const showRightPanel = !forceHideRightPanel && this.state.room && this.state.showRightPanel;
const showRightPanel = this.state.room && this.state.showRightPanel;
const rightPanel = showRightPanel
? <RightPanel room={this.state.room} resizeNotifier={this.props.resizeNotifier} />
: null;

View file

@ -343,6 +343,7 @@ export default class UserMenu extends React.Component<IProps, IState> {
let secondarySection = null;
if (prototypeCommunityName) {
const communityId = CommunityPrototypeStore.instance.getSelectedCommunityId();
primaryHeader = (
<div className="mx_UserMenu_contextMenu_name">
<span className="mx_UserMenu_contextMenu_displayName">
@ -350,24 +351,36 @@ export default class UserMenu extends React.Component<IProps, IState> {
</span>
</div>
);
primaryOptionList = (
<IconizedContextMenuOptionList>
let settingsOption;
let inviteOption;
if (CommunityPrototypeStore.instance.canInviteTo(communityId)) {
inviteOption = (
<IconizedContextMenuOption
iconClassName="mx_UserMenu_iconInvite"
label={_t("Invite")}
onClick={this.onCommunityInviteClick}
/>
);
}
if (CommunityPrototypeStore.instance.isAdminOf(communityId)) {
settingsOption = (
<IconizedContextMenuOption
iconClassName="mx_UserMenu_iconSettings"
label={_t("Settings")}
aria-label={_t("Community settings")}
onClick={this.onCommunitySettingsClick}
/>
);
}
primaryOptionList = (
<IconizedContextMenuOptionList>
{settingsOption}
<IconizedContextMenuOption
iconClassName="mx_UserMenu_iconMembers"
label={_t("Members")}
onClick={this.onCommunityMembersClick}
/>
<IconizedContextMenuOption
iconClassName="mx_UserMenu_iconInvite"
label={_t("Invite")}
onClick={this.onCommunityInviteClick}
/>
{inviteOption}
</IconizedContextMenuOptionList>
);
secondarySection = (

View file

@ -40,11 +40,7 @@ interface IProps {
onValidate(result: IValidationResult);
}
interface IState {
complexity: zxcvbn.ZXCVBNResult;
}
class PassphraseField extends PureComponent<IProps, IState> {
class PassphraseField extends PureComponent<IProps> {
static defaultProps = {
label: _td("Password"),
labelEnterPassword: _td("Enter password"),
@ -52,14 +48,16 @@ class PassphraseField extends PureComponent<IProps, IState> {
labelAllowedButUnsafe: _td("Password is allowed, but unsafe"),
};
state = { complexity: null };
public readonly validate = withValidation<this>({
description: function() {
const complexity = this.state.complexity;
public readonly validate = withValidation<this, zxcvbn.ZXCVBNResult>({
description: function(complexity) {
const score = complexity ? complexity.score : 0;
return <progress className="mx_PassphraseField_progress" max={4} value={score} />;
},
deriveData: async ({ value }) => {
if (!value) return null;
const { scorePassword } = await import('../../../utils/PasswordScorer');
return scorePassword(value);
},
rules: [
{
key: "required",
@ -68,28 +66,24 @@ class PassphraseField extends PureComponent<IProps, IState> {
},
{
key: "complexity",
test: async function({ value }) {
test: async function({ value }, complexity) {
if (!value) {
return false;
}
const { scorePassword } = await import('../../../utils/PasswordScorer');
const complexity = scorePassword(value);
this.setState({ complexity });
const safe = complexity.score >= this.props.minScore;
const allowUnsafe = SdkConfig.get()["dangerously_allow_unsafe_and_insecure_passwords"];
return allowUnsafe || safe;
},
valid: function() {
valid: function(complexity) {
// Unsafe passwords that are valid are only possible through a
// configuration flag. We'll print some helper text to signal
// to the user that their password is allowed, but unsafe.
if (this.state.complexity.score >= this.props.minScore) {
if (complexity.score >= this.props.minScore) {
return _t(this.props.labelStrongPassword);
}
return _t(this.props.labelAllowedButUnsafe);
},
invalid: function() {
const complexity = this.state.complexity;
invalid: function(complexity) {
if (!complexity) {
return null;
}

View file

@ -23,7 +23,7 @@ import {Action} from "../../../dispatcher/actions";
import {MatrixClientPeg} from "../../../MatrixClientPeg";
import BaseAvatar from "./BaseAvatar";
interface IProps {
interface IProps extends Omit<React.ComponentProps<typeof BaseAvatar>, "name" | "idName" | "url"> {
member: RoomMember;
fallbackUserId?: string;
width: number;

View file

@ -1,304 +0,0 @@
/*
Copyright 2016 OpenMarket Ltd
Copyright 2017 Vector Creations 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, {createRef} from 'react';
import PropTypes from 'prop-types';
import * as sdk from '../../../index';
import {MatrixClientPeg} from '../../../MatrixClientPeg';
import classnames from 'classnames';
import { Key } from '../../../Keyboard';
import { _t } from '../../../languageHandler';
import { SAFE_LOCALPART_REGEX } from '../../../Registration';
// The amount of time to wait for further changes to the input username before
// sending a request to the server
const USERNAME_CHECK_DEBOUNCE_MS = 250;
/*
* Prompt the user to set a display name.
*
* On success, `onFinished(true, newDisplayName)` is called.
*/
export default class SetMxIdDialog extends React.Component {
static propTypes = {
onFinished: PropTypes.func.isRequired,
// Called when the user requests to register with a different homeserver
onDifferentServerClicked: PropTypes.func.isRequired,
// Called if the user wants to switch to login instead
onLoginClick: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
this._input_value = createRef();
this._uiAuth = createRef();
this.state = {
// The entered username
username: '',
// Indicate ongoing work on the username
usernameBusy: false,
// Indicate error with username
usernameError: '',
// Assume the homeserver supports username checking until "M_UNRECOGNIZED"
usernameCheckSupport: true,
// Whether the auth UI is currently being used
doingUIAuth: false,
// Indicate error with auth
authError: '',
};
}
componentDidMount() {
this._input_value.current.select();
this._matrixClient = MatrixClientPeg.get();
}
onValueChange = ev => {
this.setState({
username: ev.target.value,
usernameBusy: true,
usernameError: '',
}, () => {
if (!this.state.username || !this.state.usernameCheckSupport) {
this.setState({
usernameBusy: false,
});
return;
}
// Debounce the username check to limit number of requests sent
if (this._usernameCheckTimeout) {
clearTimeout(this._usernameCheckTimeout);
}
this._usernameCheckTimeout = setTimeout(() => {
this._doUsernameCheck().finally(() => {
this.setState({
usernameBusy: false,
});
});
}, USERNAME_CHECK_DEBOUNCE_MS);
});
};
onKeyUp = ev => {
if (ev.key === Key.ENTER) {
this.onSubmit();
}
};
onSubmit = ev => {
if (this._uiAuth.current) {
this._uiAuth.current.tryContinue();
}
this.setState({
doingUIAuth: true,
});
};
_doUsernameCheck() {
// We do a quick check ahead of the username availability API to ensure the
// user ID roughly looks okay from a Matrix perspective.
if (!SAFE_LOCALPART_REGEX.test(this.state.username)) {
this.setState({
usernameError: _t("A username can only contain lower case letters, numbers and '=_-./'"),
});
return Promise.reject();
}
// Check if username is available
return this._matrixClient.isUsernameAvailable(this.state.username).then(
(isAvailable) => {
if (isAvailable) {
this.setState({usernameError: ''});
}
},
(err) => {
// Indicate whether the homeserver supports username checking
const newState = {
usernameCheckSupport: err.errcode !== "M_UNRECOGNIZED",
};
console.error('Error whilst checking username availability: ', err);
switch (err.errcode) {
case "M_USER_IN_USE":
newState.usernameError = _t('Username not available');
break;
case "M_INVALID_USERNAME":
newState.usernameError = _t(
'Username invalid: %(errMessage)s',
{ errMessage: err.message},
);
break;
case "M_UNRECOGNIZED":
// This homeserver doesn't support username checking, assume it's
// fine and rely on the error appearing in registration step.
newState.usernameError = '';
break;
case undefined:
newState.usernameError = _t('Something went wrong!');
break;
default:
newState.usernameError = _t(
'An error occurred: %(error_string)s',
{ error_string: err.message },
);
break;
}
this.setState(newState);
},
);
}
_generatePassword() {
return Math.random().toString(36).slice(2);
}
_makeRegisterRequest = auth => {
// Not upgrading - changing mxids
const guestAccessToken = null;
if (!this._generatedPassword) {
this._generatedPassword = this._generatePassword();
}
return this._matrixClient.register(
this.state.username,
this._generatedPassword,
undefined, // session id: included in the auth dict already
auth,
{},
guestAccessToken,
);
};
_onUIAuthFinished = (success, response) => {
this.setState({
doingUIAuth: false,
});
if (!success) {
this.setState({ authError: response.message });
return;
}
this.props.onFinished(true, {
userId: response.user_id,
deviceId: response.device_id,
homeserverUrl: this._matrixClient.getHomeserverUrl(),
identityServerUrl: this._matrixClient.getIdentityServerUrl(),
accessToken: response.access_token,
password: this._generatedPassword,
});
};
render() {
const BaseDialog = sdk.getComponent('views.dialogs.BaseDialog');
const InteractiveAuth = sdk.getComponent('structures.InteractiveAuth');
let auth;
if (this.state.doingUIAuth) {
auth = <InteractiveAuth
matrixClient={this._matrixClient}
makeRequest={this._makeRegisterRequest}
onAuthFinished={this._onUIAuthFinished}
inputs={{}}
poll={true}
ref={this._uiAuth}
continueIsManaged={true}
/>;
}
const inputClasses = classnames({
"mx_SetMxIdDialog_input": true,
"error": Boolean(this.state.usernameError),
});
let usernameIndicator = null;
if (this.state.usernameBusy) {
usernameIndicator = <div>{_t("Checking...")}</div>;
} else {
const usernameAvailable = this.state.username &&
this.state.usernameCheckSupport && !this.state.usernameError;
const usernameIndicatorClasses = classnames({
"error": Boolean(this.state.usernameError),
"success": usernameAvailable,
});
usernameIndicator = <div className={usernameIndicatorClasses} role="alert">
{ usernameAvailable ? _t('Username available') : this.state.usernameError }
</div>;
}
let authErrorIndicator = null;
if (this.state.authError) {
authErrorIndicator = <div className="error" role="alert">
{ this.state.authError }
</div>;
}
const canContinue = this.state.username &&
!this.state.usernameError &&
!this.state.usernameBusy;
return (
<BaseDialog className="mx_SetMxIdDialog"
onFinished={this.props.onFinished}
title={_t('To get started, please pick a username!')}
contentId='mx_Dialog_content'
>
<div className="mx_Dialog_content" id='mx_Dialog_content'>
<div className="mx_SetMxIdDialog_input_group">
<input type="text" ref={this._input_value} value={this.state.username}
autoFocus={true}
onChange={this.onValueChange}
onKeyUp={this.onKeyUp}
size="30"
className={inputClasses}
/>
</div>
{ usernameIndicator }
<p>
{ _t(
'This will be your account name on the <span></span> ' +
'homeserver, or you can pick a <a>different server</a>.',
{},
{
'span': <span>{ this.props.homeserverUrl }</span>,
'a': (sub) => <a href="#" onClick={this.props.onDifferentServerClicked}>{ sub }</a>,
},
) }
</p>
<p>
{ _t(
'If you already have a Matrix account you can <a>log in</a> instead.',
{},
{ 'a': (sub) => <a href="#" onClick={this.props.onLoginClick}>{ sub }</a> },
) }
</p>
{ auth }
{ authErrorIndicator }
</div>
<div className="mx_Dialog_buttons">
<input className="mx_Dialog_primary"
type="submit"
value={_t("Continue")}
onClick={this.onSubmit}
disabled={!canContinue}
/>
</div>
</BaseDialog>
);
}
}

View file

@ -1,128 +0,0 @@
/*
Copyright 2017 Vector Creations Ltd
Copyright 2018 New Vector Ltd
Copyright 2019 Michael Telatynski <7t3chguy@gmail.com>
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 * as sdk from '../../../index';
import { _t } from '../../../languageHandler';
import Modal from '../../../Modal';
const WarmFuzzy = function(props) {
const BaseDialog = sdk.getComponent('views.dialogs.BaseDialog');
let title = _t('You have successfully set a password!');
if (props.didSetEmail) {
title = _t('You have successfully set a password and an email address!');
}
const advice = _t('You can now return to your account after signing out, and sign in on other devices.');
let extraAdvice = null;
if (!props.didSetEmail) {
extraAdvice = _t('Remember, you can always set an email address in user settings if you change your mind.');
}
return <BaseDialog className="mx_SetPasswordDialog"
onFinished={props.onFinished}
title={ title }
>
<div className="mx_Dialog_content">
<p>
{ advice }
</p>
<p>
{ extraAdvice }
</p>
</div>
<div className="mx_Dialog_buttons">
<button
className="mx_Dialog_primary"
autoFocus={true}
onClick={props.onFinished}>
{ _t('Continue') }
</button>
</div>
</BaseDialog>;
};
/**
* Prompt the user to set a password
*
* On success, `onFinished()` when finished
*/
export default class SetPasswordDialog extends React.Component {
static propTypes = {
onFinished: PropTypes.func.isRequired,
};
state = {
error: null,
};
_onPasswordChanged = res => {
Modal.createDialog(WarmFuzzy, {
didSetEmail: res.didSetEmail,
onFinished: () => {
this.props.onFinished();
},
});
};
_onPasswordChangeError = err => {
let errMsg = err.error || "";
if (err.httpStatus === 403) {
errMsg = _t('Failed to change password. Is your password correct?');
} else if (err.httpStatus) {
errMsg += ' ' + _t(
'(HTTP status %(httpStatus)s)',
{ httpStatus: err.httpStatus },
);
}
this.setState({
error: errMsg,
});
};
render() {
const BaseDialog = sdk.getComponent('views.dialogs.BaseDialog');
const ChangePassword = sdk.getComponent('views.settings.ChangePassword');
return (
<BaseDialog className="mx_SetPasswordDialog"
onFinished={this.props.onFinished}
title={ _t('Please set a password!') }
>
<div className="mx_Dialog_content">
<p>
{ _t('This will allow you to return to your account after signing out, and sign in on other sessions.') }
</p>
<ChangePassword
className="mx_SetPasswordDialog_change_password"
rowClassName=""
buttonClassNames="mx_Dialog_primary mx_SetPasswordDialog_change_password_button"
buttonKind="primary"
confirm={false}
autoFocusNewPasswordInput={true}
shouldAskForEmail={true}
onError={this._onPasswordChangeError}
onFinished={this._onPasswordChanged} />
<div className="error">
{ this.state.error }
</div>
</div>
</BaseDialog>
);
}
}

View file

@ -289,7 +289,12 @@ export default class AccessSecretStorageDialog extends React.PureComponent {
content = <div>
<p>{_t("Use your Security Key to continue.")}</p>
<form className="mx_AccessSecretStorageDialog_primaryContainer" onSubmit={this._onRecoveryKeyNext} spellCheck={false}>
<form
className="mx_AccessSecretStorageDialog_primaryContainer"
onSubmit={this._onRecoveryKeyNext}
spellCheck={false}
autoComplete="off"
>
<div className="mx_AccessSecretStorageDialog_recoveryKeyEntry">
<div className="mx_AccessSecretStorageDialog_recoveryKeyEntry_textInput">
<Field
@ -298,6 +303,7 @@ export default class AccessSecretStorageDialog extends React.PureComponent {
value={this.state.recoveryKey}
onChange={this._onRecoveryKeyChange}
forceValidity={this.state.recoveryKeyCorrect}
autoComplete="off"
/>
</div>
<span className="mx_AccessSecretStorageDialog_recoveryKeyEntry_entryControlSeparatorText">

View file

@ -62,7 +62,8 @@ export default class AccessibleTooltipButton extends React.PureComponent<IToolti
};
render() {
const {title, tooltip, children, tooltipClassName, ...props} = this.props;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const {title, tooltip, children, tooltipClassName, forceHide, ...props} = this.props;
const tip = this.state.hover ? <Tooltip
className="mx_AccessibleTooltipButton_container"

View file

@ -18,11 +18,9 @@ limitations under the License.
*/
import url from 'url';
import qs from 'qs';
import React, {createRef} from 'react';
import PropTypes from 'prop-types';
import {MatrixClientPeg} from '../../../MatrixClientPeg';
import WidgetMessaging from '../../../WidgetMessaging';
import AccessibleButton from './AccessibleButton';
import Modal from '../../../Modal';
import { _t } from '../../../languageHandler';
@ -34,37 +32,16 @@ import WidgetUtils from '../../../utils/WidgetUtils';
import dis from '../../../dispatcher/dispatcher';
import ActiveWidgetStore from '../../../stores/ActiveWidgetStore';
import classNames from 'classnames';
import {IntegrationManagers} from "../../../integrations/IntegrationManagers";
import SettingsStore from "../../../settings/SettingsStore";
import {aboveLeftOf, ContextMenu, ContextMenuButton} from "../../structures/ContextMenu";
import PersistedElement from "./PersistedElement";
import {WidgetType} from "../../../widgets/WidgetType";
import {Capability} from "../../../widgets/WidgetApi";
import {sleep} from "../../../utils/promise";
import {SettingLevel} from "../../../settings/SettingLevel";
import WidgetStore from "../../../stores/WidgetStore";
import {Action} from "../../../dispatcher/actions";
const ALLOWED_APP_URL_SCHEMES = ['https:', 'http:'];
const ENABLE_REACT_PERF = false;
/**
* Does template substitution on a URL (or any string). Variables will be
* passed through encodeURIComponent.
* @param {string} uriTemplate The path with template variables e.g. '/foo/$bar'.
* @param {Object} variables The key/value pairs to replace the template
* variables with. E.g. { '$bar': 'baz' }.
* @return {string} The result of replacing all template variables e.g. '/foo/baz'.
*/
function uriFromTemplate(uriTemplate, variables) {
let out = uriTemplate;
for (const [key, val] of Object.entries(variables)) {
out = out.replace(
'$' + key, encodeURIComponent(val),
);
}
return out;
}
import {StopGapWidget} from "../../../stores/widgets/StopGapWidget";
import {ElementWidgetActions} from "../../../stores/widgets/ElementWidgetActions";
import {MatrixCapabilities} from "matrix-widget-api";
export default class AppTile extends React.Component {
constructor(props) {
@ -72,11 +49,14 @@ export default class AppTile extends React.Component {
// The key used for PersistedElement
this._persistKey = 'widget_' + this.props.app.id;
this._sgWidget = new StopGapWidget(this.props);
this._sgWidget.on("preparing", this._onWidgetPrepared);
this._sgWidget.on("ready", this._onWidgetReady);
this.iframe = null; // ref to the iframe (callback style)
this.state = this._getNewState(props);
this._onAction = this._onAction.bind(this);
this._onLoaded = this._onLoaded.bind(this);
this._onEditClick = this._onEditClick.bind(this);
this._onDeleteClick = this._onDeleteClick.bind(this);
this._onRevokeClicked = this._onRevokeClicked.bind(this);
@ -89,7 +69,6 @@ export default class AppTile extends React.Component {
this._onReloadWidgetClick = this._onReloadWidgetClick.bind(this);
this._contextMenuButton = createRef();
this._appFrame = createRef();
this._menu_bar = createRef();
}
@ -108,12 +87,10 @@ export default class AppTile extends React.Component {
return !!currentlyAllowedWidgets[newProps.app.eventId];
};
const PersistedElement = sdk.getComponent("elements.PersistedElement");
return {
initialising: true, // True while we are mangling the widget URL
// True while the iframe content is loading
loading: this.props.waitForIframeLoad && !PersistedElement.isMounted(this._persistKey),
widgetUrl: this._addWurlParams(newProps.app.url),
// Assume that widget has permission to load if we are the user who
// added it to the room, or if explicitly granted by the user
hasPermissionToLoad: newProps.userId === newProps.creatorUserId || hasPermissionToLoad(),
@ -124,43 +101,6 @@ export default class AppTile extends React.Component {
};
}
/**
* Does the widget support a given capability
* @param {string} capability Capability to check for
* @return {Boolean} True if capability supported
*/
_hasCapability(capability) {
return ActiveWidgetStore.widgetHasCapability(this.props.app.id, capability);
}
/**
* Add widget instance specific parameters to pass in wUrl
* Properties passed to widget instance:
* - widgetId
* - origin / parent URL
* @param {string} urlString Url string to modify
* @return {string}
* Url string with parameters appended.
* If url can not be parsed, it is returned unmodified.
*/
_addWurlParams(urlString) {
try {
const parsed = new URL(urlString);
// TODO: Replace these with proper widget params
// See https://github.com/matrix-org/matrix-doc/pull/1958/files#r405714833
parsed.searchParams.set('widgetId', this.props.app.id);
parsed.searchParams.set('parentUrl', window.location.href.split('#', 2)[0]);
// Replace the encoded dollar signs back to dollar signs. They have no special meaning
// in HTTP, but URL parsers encode them anyways.
return parsed.toString().replace(/%24/g, '$');
} catch (e) {
console.error("Failed to add widget URL params:", e);
return urlString;
}
}
isMixedContent() {
const parentContentProtocol = window.location.protocol;
const u = url.parse(this.props.app.url);
@ -176,7 +116,7 @@ export default class AppTile extends React.Component {
componentDidMount() {
// Only fetch IM token on mount if we're showing and have permission to load
if (this.props.show && this.state.hasPermissionToLoad) {
this.setScalarToken();
this._startWidget();
}
// Widget action listeners
@ -190,93 +130,45 @@ export default class AppTile extends React.Component {
// if it's not remaining on screen, get rid of the PersistedElement container
if (!ActiveWidgetStore.getWidgetPersistence(this.props.app.id)) {
ActiveWidgetStore.destroyPersistentWidget(this.props.app.id);
const PersistedElement = sdk.getComponent("elements.PersistedElement");
PersistedElement.destroyElement(this._persistKey);
}
if (this._sgWidget) {
this._sgWidget.stop();
}
}
// TODO: Generify the name of this function. It's not just scalar tokens.
/**
* Adds a scalar token to the widget URL, if required
* Component initialisation is only complete when this function has resolved
*/
setScalarToken() {
if (!WidgetUtils.isScalarUrl(this.props.app.url)) {
console.warn('Widget does not match integration manager, refusing to set auth token', url);
this.setState({
error: null,
widgetUrl: this._addWurlParams(this.props.app.url),
initialising: false,
});
return;
_resetWidget(newProps) {
if (this._sgWidget) {
this._sgWidget.stop();
}
this._sgWidget = new StopGapWidget(newProps);
this._sgWidget.on("preparing", this._onWidgetPrepared);
this._sgWidget.on("ready", this._onWidgetReady);
this._startWidget();
}
const managers = IntegrationManagers.sharedInstance();
if (!managers.hasManager()) {
console.warn("No integration manager - not setting scalar token", url);
this.setState({
error: null,
widgetUrl: this._addWurlParams(this.props.app.url),
initialising: false,
});
return;
}
// TODO: Pick the right manager for the widget
const defaultManager = managers.getPrimaryManager();
if (!WidgetUtils.isScalarUrl(defaultManager.apiUrl)) {
console.warn('Unknown integration manager, refusing to set auth token', url);
this.setState({
error: null,
widgetUrl: this._addWurlParams(this.props.app.url),
initialising: false,
});
return;
}
// Fetch the token before loading the iframe as we need it to mangle the URL
if (!this._scalarClient) {
this._scalarClient = defaultManager.getScalarClient();
}
this._scalarClient.getScalarToken().then((token) => {
// Append scalar_token as a query param if not already present
this._scalarClient.scalarToken = token;
const u = url.parse(this._addWurlParams(this.props.app.url));
const params = qs.parse(u.query);
if (!params.scalar_token) {
params.scalar_token = encodeURIComponent(token);
// u.search must be set to undefined, so that u.format() uses query parameters - https://nodejs.org/docs/latest/api/url.html#url_url_format_url_options
u.search = undefined;
u.query = params;
}
this.setState({
error: null,
widgetUrl: u.format(),
initialising: false,
});
// Fetch page title from remote content if not already set
if (!this.state.widgetPageTitle && params.url) {
this._fetchWidgetTitle(params.url);
}
}, (err) => {
console.error("Failed to get scalar_token", err);
this.setState({
error: err.message,
initialising: false,
});
_startWidget() {
this._sgWidget.prepare().then(() => {
this.setState({initialising: false});
});
}
_iframeRefChange = (ref) => {
this.iframe = ref;
if (ref) {
this._sgWidget.start(ref);
} else {
this._resetWidget(this.props);
}
};
// TODO: [REACT-WARNING] Replace with appropriate lifecycle event
UNSAFE_componentWillReceiveProps(nextProps) { // eslint-disable-line camelcase
if (nextProps.app.url !== this.props.app.url) {
this._getNewState(nextProps);
// Fetch IM token for new URL if we're showing and have permission to load
if (this.props.show && this.state.hasPermissionToLoad) {
this.setScalarToken();
this._resetWidget(nextProps);
}
}
@ -287,9 +179,9 @@ export default class AppTile extends React.Component {
loading: true,
});
}
// Fetch IM token now that we're showing if we already have permission to load
// Start the widget now that we're showing if we already have permission to load
if (this.state.hasPermissionToLoad) {
this.setScalarToken();
this._startWidget();
}
}
@ -319,7 +211,14 @@ export default class AppTile extends React.Component {
}
_onSnapshotClick() {
WidgetUtils.snapshotWidget(this.props.app);
this._sgWidget.widgetApi.takeScreenshot().then(data => {
dis.dispatch({
action: 'picture_snapshot',
file: data.screenshot,
});
}).catch(err => {
console.error("Failed to take screenshot: ", err);
});
}
/**
@ -327,35 +226,24 @@ export default class AppTile extends React.Component {
* @private
* @returns {Promise<*>} Resolves when the widget is terminated, or timeout passed.
*/
_endWidgetActions() {
let terminationPromise;
if (this._hasCapability(Capability.ReceiveTerminate)) {
// Wait for widget to terminate within a timeout
const timeout = 2000;
const messaging = ActiveWidgetStore.getWidgetMessaging(this.props.app.id);
terminationPromise = Promise.race([messaging.terminate(), sleep(timeout)]);
} else {
terminationPromise = Promise.resolve();
async _endWidgetActions() { // widget migration dev note: async to maintain signature
// HACK: This is a really dirty way to ensure that Jitsi cleans up
// its hold on the webcam. Without this, the widget holds a media
// stream open, even after death. See https://github.com/vector-im/element-web/issues/7351
if (this.iframe) {
// In practice we could just do `+= ''` to trick the browser
// into thinking the URL changed, however I can foresee this
// being optimized out by a browser. Instead, we'll just point
// the iframe at a page that is reasonably safe to use in the
// event the iframe doesn't wink away.
// This is relative to where the Element instance is located.
this.iframe.src = 'about:blank';
}
return terminationPromise.finally(() => {
// HACK: This is a really dirty way to ensure that Jitsi cleans up
// its hold on the webcam. Without this, the widget holds a media
// stream open, even after death. See https://github.com/vector-im/element-web/issues/7351
if (this._appFrame.current) {
// In practice we could just do `+= ''` to trick the browser
// into thinking the URL changed, however I can foresee this
// being optimized out by a browser. Instead, we'll just point
// the iframe at a page that is reasonably safe to use in the
// event the iframe doesn't wink away.
// This is relative to where the Element instance is located.
this._appFrame.current.src = 'about:blank';
}
// Delete the widget from the persisted store for good measure.
PersistedElement.destroyElement(this._persistKey);
// Delete the widget from the persisted store for good measure.
PersistedElement.destroyElement(this._persistKey);
});
this._sgWidget.stop();
}
/* If user has permission to modify widgets, delete the widget,
@ -409,73 +297,21 @@ export default class AppTile extends React.Component {
this._revokeWidgetPermission();
}
/**
* Called when widget iframe has finished loading
*/
_onLoaded() {
// Destroy the old widget messaging before starting it back up again. Some widgets
// have startup routines that run when they are loaded, so we just need to reinitialize
// the messaging for them.
ActiveWidgetStore.delWidgetMessaging(this.props.app.id);
this._setupWidgetMessaging();
ActiveWidgetStore.setRoomId(this.props.app.id, this.props.room.roomId);
_onWidgetPrepared = () => {
this.setState({loading: false});
}
};
_setupWidgetMessaging() {
// FIXME: There's probably no reason to do this here: it should probably be done entirely
// in ActiveWidgetStore.
const widgetMessaging = new WidgetMessaging(
this.props.app.id,
this.props.app.url,
this._getRenderedUrl(),
this.props.userWidget,
this._appFrame.current.contentWindow,
);
ActiveWidgetStore.setWidgetMessaging(this.props.app.id, widgetMessaging);
widgetMessaging.getCapabilities().then((requestedCapabilities) => {
console.log(`Widget ${this.props.app.id} requested capabilities: ` + requestedCapabilities);
requestedCapabilities = requestedCapabilities || [];
// Allow whitelisted capabilities
let requestedWhitelistCapabilies = [];
if (this.props.whitelistCapabilities && this.props.whitelistCapabilities.length > 0) {
requestedWhitelistCapabilies = requestedCapabilities.filter(function(e) {
return this.indexOf(e)>=0;
}, this.props.whitelistCapabilities);
if (requestedWhitelistCapabilies.length > 0 ) {
console.log(`Widget ${this.props.app.id} allowing requested, whitelisted properties: ` +
requestedWhitelistCapabilies,
);
}
}
// TODO -- Add UI to warn about and optionally allow requested capabilities
ActiveWidgetStore.setWidgetCapabilities(this.props.app.id, requestedWhitelistCapabilies);
if (this.props.onCapabilityRequest) {
this.props.onCapabilityRequest(requestedCapabilities);
}
// We only tell Jitsi widgets that we're ready because they're realistically the only ones
// using this custom extension to the widget API.
if (WidgetType.JITSI.matches(this.props.app.type)) {
widgetMessaging.flagReadyToContinue();
}
}).catch((err) => {
console.log(`Failed to get capabilities for widget type ${this.props.app.type}`, this.props.app.id, err);
});
}
_onWidgetReady = () => {
if (WidgetType.JITSI.matches(this.props.app.type)) {
this._sgWidget.widgetApi.transport.send(ElementWidgetActions.ClientReady, {});
}
};
_onAction(payload) {
if (payload.widgetId === this.props.app.id) {
switch (payload.action) {
case 'm.sticker':
if (this._hasCapability('m.sticker')) {
if (this._sgWidget.widgetApi.hasCapability(MatrixCapabilities.StickerSending)) {
dis.dispatch({action: 'post_sticker_message', data: payload.data});
} else {
console.warn('Ignoring sticker message. Invalid capability');
@ -493,20 +329,6 @@ export default class AppTile extends React.Component {
}
}
/**
* Set remote content title on AppTile
* @param {string} url Url to check for title
*/
_fetchWidgetTitle(url) {
this._scalarClient.getScalarPageTitle(url).then((widgetPageTitle) => {
if (widgetPageTitle) {
this.setState({widgetPageTitle: widgetPageTitle});
}
}, (err) =>{
console.error("Failed to get page title", err);
});
}
_grantWidgetPermission() {
const roomId = this.props.room.roomId;
console.info("Granting permission for widget to load: " + this.props.app.eventId);
@ -516,7 +338,7 @@ export default class AppTile extends React.Component {
this.setState({hasPermissionToLoad: true});
// Fetch a token for the integration manager, now that we're allowed to
this.setScalarToken();
this._startWidget();
}).catch(err => {
console.error(err);
// We don't really need to do anything about this - the user will just hit the button again.
@ -535,6 +357,7 @@ export default class AppTile extends React.Component {
ActiveWidgetStore.destroyPersistentWidget(this.props.app.id);
const PersistedElement = sdk.getComponent("elements.PersistedElement");
PersistedElement.destroyElement(this._persistKey);
this._sgWidget.stop();
}).catch(err => {
console.error(err);
// We don't really need to do anything about this - the user will just hit the button again.
@ -572,40 +395,6 @@ export default class AppTile extends React.Component {
}
}
/**
* Replace the widget template variables in a url with their values
*
* @param {string} u The URL with template variables
* @param {string} widgetType The widget's type
*
* @returns {string} url with temlate variables replaced
*/
_templatedUrl(u, widgetType: string) {
const targetData = {};
if (WidgetType.JITSI.matches(widgetType)) {
targetData['domain'] = 'jitsi.riot.im'; // v1 jitsi widgets have this hardcoded
}
const myUserId = MatrixClientPeg.get().credentials.userId;
const myUser = MatrixClientPeg.get().getUser(myUserId);
const vars = Object.assign(targetData, this.props.app.data, {
'matrix_user_id': myUserId,
'matrix_room_id': this.props.room.roomId,
'matrix_display_name': myUser ? myUser.displayName : myUserId,
'matrix_avatar_url': myUser ? MatrixClientPeg.get().mxcUrlToHttp(myUser.avatarUrl) : '',
// TODO: Namespace themes through some standard
'theme': SettingsStore.getValue("theme"),
});
if (vars.conferenceId === undefined) {
// we'll need to parse the conference ID out of the URL for v1 Jitsi widgets
const parsedUrl = new URL(this.props.app.url);
vars.conferenceId = parsedUrl.searchParams.get("confId");
}
return uriFromTemplate(u, vars);
}
/**
* Whether we're using a local version of the widget rather than loading the
* actual widget URL
@ -615,67 +404,11 @@ export default class AppTile extends React.Component {
return WidgetType.JITSI.matches(this.props.app.type);
}
/**
* Get the URL used in the iframe
* In cases where we supply our own UI for a widget, this is an internal
* URL different to the one used if the widget is popped out to a separate
* tab / browser
*
* @returns {string} url
*/
_getRenderedUrl() {
let url;
if (WidgetType.JITSI.matches(this.props.app.type)) {
console.log("Replacing Jitsi widget URL with local wrapper");
url = WidgetUtils.getLocalJitsiWrapperUrl({
forLocalRender: true,
auth: this.props.app.data ? this.props.app.data.auth : null,
});
url = this._addWurlParams(url);
} else {
url = this._getSafeUrl(this.state.widgetUrl);
}
return this._templatedUrl(url, this.props.app.type);
}
_getPopoutUrl() {
if (WidgetType.JITSI.matches(this.props.app.type)) {
return this._templatedUrl(
WidgetUtils.getLocalJitsiWrapperUrl({
forLocalRender: false,
auth: this.props.app.data ? this.props.app.data.auth : null,
}),
this.props.app.type,
);
} else {
// use app.url, not state.widgetUrl, because we want the one without
// the wURL params for the popped-out version.
return this._templatedUrl(this._getSafeUrl(this.props.app.url), this.props.app.type);
}
}
_getSafeUrl(u) {
const parsedWidgetUrl = url.parse(u, true);
if (ENABLE_REACT_PERF) {
parsedWidgetUrl.search = null;
parsedWidgetUrl.query.react_perf = true;
}
let safeWidgetUrl = '';
if (ALLOWED_APP_URL_SCHEMES.includes(parsedWidgetUrl.protocol)) {
safeWidgetUrl = url.format(parsedWidgetUrl);
}
// Replace all the dollar signs back to dollar signs as they don't affect HTTP at all.
// We also need the dollar signs in-tact for variable substitution.
return safeWidgetUrl.replace(/%24/g, '$');
}
_getTileTitle() {
const name = this.formatAppTileName();
const titleSpacer = <span>&nbsp;-&nbsp;</span>;
let title = '';
if (this.state.widgetPageTitle && this.state.widgetPageTitle != this.formatAppTileName()) {
if (this.state.widgetPageTitle && this.state.widgetPageTitle !== this.formatAppTileName()) {
title = this.state.widgetPageTitle;
}
@ -698,9 +431,9 @@ export default class AppTile extends React.Component {
// twice from the same computer, which Jitsi can have problems with (audio echo/gain-loop).
if (WidgetType.JITSI.matches(this.props.app.type) && this.props.show) {
this._endWidgetActions().then(() => {
if (this._appFrame.current) {
if (this.iframe) {
// Reload iframe
this._appFrame.current.src = this._getRenderedUrl();
this.iframe.src = this._sgWidget.embedUrl;
this.setState({});
}
});
@ -708,13 +441,13 @@ export default class AppTile extends React.Component {
// Using Object.assign workaround as the following opens in a new window instead of a new tab.
// window.open(this._getPopoutUrl(), '_blank', 'noopener=yes');
Object.assign(document.createElement('a'),
{ target: '_blank', href: this._getPopoutUrl(), rel: 'noreferrer noopener'}).click();
{ target: '_blank', href: this._sgWidget.popoutUrl, rel: 'noreferrer noopener'}).click();
}
_onReloadWidgetClick() {
// Reload iframe in this way to avoid cross-origin restrictions
// eslint-disable-next-line no-self-assign
this._appFrame.current.src = this._appFrame.current.src;
this.iframe.src = this.iframe.src;
}
_onContextMenuClick = () => {
@ -760,7 +493,7 @@ export default class AppTile extends React.Component {
<AppPermission
roomId={this.props.room.roomId}
creatorUserId={this.props.creatorUserId}
url={this.state.widgetUrl}
url={this._sgWidget.embedUrl}
isRoomEncrypted={isEncrypted}
onPermissionGranted={this._grantWidgetPermission}
/>
@ -785,11 +518,11 @@ export default class AppTile extends React.Component {
{ this.state.loading && loadingElement }
<iframe
allow={iframeFeatures}
ref={this._appFrame}
src={this._getRenderedUrl()}
ref={this._iframeRefChange}
src={this._sgWidget.embedUrl}
allowFullScreen={true}
sandbox={sandboxFlags}
onLoad={this._onLoaded} />
/>
</div>
);
// if the widget would be allowed to remain on screen, we must put it in
@ -833,9 +566,10 @@ export default class AppTile extends React.Component {
const elementRect = this._contextMenuButton.current.getBoundingClientRect();
const canUserModify = this._canUserModify();
const showEditButton = Boolean(this._scalarClient && canUserModify);
const showEditButton = Boolean(this._sgWidget.isManagedByManager && canUserModify);
const showDeleteButton = (this.props.showDelete === undefined || this.props.showDelete) && canUserModify;
const showPictureSnapshotButton = this._hasCapability('m.capability.screenshot') && this.props.show;
const showPictureSnapshotButton = this.props.show && this._sgWidget.widgetApi &&
this._sgWidget.widgetApi.hasCapability(MatrixCapabilities.Screenshots);
const WidgetContextMenu = sdk.getComponent('views.context_menus.WidgetContextMenu');
contextMenu = (
@ -943,9 +677,6 @@ AppTile.propTypes = {
// NOTE -- Use with caution. This is intended to aid better integration / UX
// basic widget capabilities, e.g. injecting sticker message events.
whitelistCapabilities: PropTypes.array,
// Optional function to be called on widget capability request
// Called with an array of the requested capabilities
onCapabilityRequest: PropTypes.func,
// Is this an instance of a user widget
userWidget: PropTypes.bool,
};

View file

@ -0,0 +1,77 @@
/*
Copyright 2020 The Matrix.org Foundation C.I.C.
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 EventIndexPeg from "../../../indexing/EventIndexPeg";
import { _t } from "../../../languageHandler";
import SdkConfig from "../../../SdkConfig";
import React from "react";
export enum WarningKind {
Files,
Search,
}
interface IProps {
isRoomEncrypted: boolean;
kind: WarningKind;
}
export default function DesktopBuildsNotice({isRoomEncrypted, kind}: IProps) {
if (!isRoomEncrypted) return null;
if (EventIndexPeg.get()) return null;
const {desktopBuilds, brand} = SdkConfig.get();
let text = null;
let logo = null;
if (desktopBuilds.available) {
logo = <img src={desktopBuilds.logo} />;
switch (kind) {
case WarningKind.Files:
text = _t("Use the <a>Desktop app</a> to see all encrypted files", {}, {
a: sub => (<a href={desktopBuilds.url} target="_blank" rel="noreferrer noopener">{sub}</a>),
});
break;
case WarningKind.Search:
text = _t("Use the <a>Desktop app</a> to search encrypted messages", {}, {
a: sub => (<a href={desktopBuilds.url} target="_blank" rel="noreferrer noopener">{sub}</a>),
});
break;
}
} else {
switch (kind) {
case WarningKind.Files:
text = _t("This version of %(brand)s does not support viewing some encrypted files", {brand});
break;
case WarningKind.Search:
text = _t("This version of %(brand)s does not support searching encrypted messages", {brand});
break;
}
}
// for safety
if (!text) {
console.warn("Unknown desktop builds warning kind: ", kind);
return null;
}
return (
<div className="mx_DesktopBuildsNotice">
{logo}
<span>{text}</span>
</div>
);
}

View file

@ -1,5 +1,5 @@
/*
Copyright 2019 The Matrix.org Foundation C.I.C.
Copyright 2019, 2020 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@ -14,15 +14,41 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import React, {useEffect} from 'react';
import PropTypes from 'prop-types';
import React, {ReactChildren, useEffect} from 'react';
import {MatrixEvent} from "matrix-js-sdk/src/models/event";
import {RoomMember} from "matrix-js-sdk/src/models/room-member";
import MemberAvatar from '../avatars/MemberAvatar';
import { _t } from '../../../languageHandler';
import {MatrixEvent, RoomMember} from "matrix-js-sdk";
import {useStateToggle} from "../../../hooks/useStateToggle";
import AccessibleButton from "./AccessibleButton";
const EventListSummary = ({events, children, threshold=3, onToggle, startExpanded, summaryMembers=[], summaryText}) => {
interface IProps {
// An array of member events to summarise
events: MatrixEvent[];
// The minimum number of events needed to trigger summarisation
threshold?: number;
// Whether or not to begin with state.expanded=true
startExpanded?: boolean,
// The list of room members for which to show avatars next to the summary
summaryMembers?: RoomMember[],
// The text to show as the summary of this event list
summaryText?: string,
// An array of EventTiles to render when expanded
children: ReactChildren,
// Called when the event list expansion is toggled
onToggle?(): void;
}
const EventListSummary: React.FC<IProps> = ({
events,
children,
threshold = 3,
onToggle,
startExpanded,
summaryMembers = [],
summaryText,
}) => {
const [expanded, toggleExpanded] = useStateToggle(startExpanded);
// Whenever expanded changes call onToggle
@ -75,22 +101,4 @@ const EventListSummary = ({events, children, threshold=3, onToggle, startExpande
);
};
EventListSummary.propTypes = {
// An array of member events to summarise
events: PropTypes.arrayOf(PropTypes.instanceOf(MatrixEvent)).isRequired,
// An array of EventTiles to render when expanded
children: PropTypes.arrayOf(PropTypes.element).isRequired,
// The minimum number of events needed to trigger summarisation
threshold: PropTypes.number,
// Called when the event list expansion is toggled
onToggle: PropTypes.func,
// Whether or not to begin with state.expanded=true
startExpanded: PropTypes.bool,
// The list of room members for which to show avatars next to the summary
summaryMembers: PropTypes.arrayOf(PropTypes.instanceOf(RoomMember)),
// The text to show as the summary of this event list
summaryText: PropTypes.string,
};
export default EventListSummary;

View file

@ -80,27 +80,30 @@ export default class EventTilePreview extends React.Component<IProps, IState> {
private fakeEvent({userId, displayname, avatar_url: avatarUrl}: IState) {
// Fake it till we make it
const event = new MatrixEvent(JSON.parse(`{
"type": "m.room.message",
"sender": "${userId}",
"content": {
"m.new_content": {
"msgtype": "m.text",
"body": "${this.props.message}",
"displayname": "${displayname}",
"avatar_url": "${avatarUrl}"
},
"msgtype": "m.text",
"body": "${this.props.message}",
"displayname": "${displayname}",
"avatar_url": "${avatarUrl}"
/* eslint-disable quote-props */
const rawEvent = {
type: "m.room.message",
sender: userId,
content: {
"m.new_content": {
msgtype: "m.text",
body: this.props.message,
displayname: displayname,
avatar_url: avatarUrl,
},
"unsigned": {
"age": 97
},
"event_id": "$9999999999999999999999999999999999999999999",
"room_id": "!999999999999999999:matrix.org"
}`));
msgtype: "m.text",
body: this.props.message,
displayname: displayname,
avatar_url: avatarUrl,
},
unsigned: {
age: 97,
},
event_id: "$9999999999999999999999999999999999999999999",
room_id: "!999999999999999999:example.org",
};
const event = new MatrixEvent(rawEvent);
/* eslint-enable quote-props */
// Fake it more
event.sender = {

View file

@ -16,32 +16,60 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import React from 'react';
import PropTypes from 'prop-types';
import React, { ReactChildren } from 'react';
import { MatrixEvent } from "matrix-js-sdk/src/models/event";
import { RoomMember } from "matrix-js-sdk/src/models/room-member";
import { _t } from '../../../languageHandler';
import { formatCommaSeparatedList } from '../../../utils/FormattingUtils';
import * as sdk from "../../../index";
import {MatrixEvent} from "matrix-js-sdk";
import {isValid3pidInvite} from "../../../RoomInvite";
import { isValid3pidInvite } from "../../../RoomInvite";
import EventListSummary from "./EventListSummary";
export default class MemberEventListSummary extends React.Component {
static propTypes = {
// An array of member events to summarise
events: PropTypes.arrayOf(PropTypes.instanceOf(MatrixEvent)).isRequired,
// An array of EventTiles to render when expanded
children: PropTypes.array.isRequired,
// The maximum number of names to show in either each summary e.g. 2 would result "A, B and 234 others left"
summaryLength: PropTypes.number,
// The maximum number of avatars to display in the summary
avatarsMaxLength: PropTypes.number,
// The minimum number of events needed to trigger summarisation
threshold: PropTypes.number,
// Called when the MELS expansion is toggled
onToggle: PropTypes.func,
// Whether or not to begin with state.expanded=true
startExpanded: PropTypes.bool,
};
interface IProps {
// An array of member events to summarise
events: MatrixEvent[];
// The maximum number of names to show in either each summary e.g. 2 would result "A, B and 234 others left"
summaryLength?: number;
// The maximum number of avatars to display in the summary
avatarsMaxLength?: number;
// The minimum number of events needed to trigger summarisation
threshold?: number,
// Whether or not to begin with state.expanded=true
startExpanded?: boolean,
// An array of EventTiles to render when expanded
children: ReactChildren;
// Called when the MELS expansion is toggled
onToggle?(): void,
}
interface IUserEvents {
// The original event
mxEvent: MatrixEvent;
// The display name of the user (if not, then user ID)
displayName: string;
// The original index of the event in this.props.events
index: number;
}
enum TransitionType {
Joined = "joined",
Left = "left",
JoinedAndLeft = "joined_and_left",
LeftAndJoined = "left_and_joined",
InviteReject = "invite_reject",
InviteWithdrawal = "invite_withdrawal",
Invited = "invited",
Banned = "banned",
Unbanned = "unbanned",
Kicked = "kicked",
ChangedName = "changed_name",
ChangedAvatar = "changed_avatar",
NoChange = "no_change",
}
const SEP = ",";
export default class MemberEventListSummary extends React.Component<IProps> {
static defaultProps = {
summaryLength: 1,
threshold: 3,
@ -62,30 +90,28 @@ export default class MemberEventListSummary extends React.Component {
/**
* Generate the text for users aggregated by their transition sequences (`eventAggregates`) where
* the sequences are ordered by `orderedTransitionSequences`.
* @param {object[]} eventAggregates a map of transition sequence to array of user display names
* @param {object} eventAggregates a map of transition sequence to array of user display names
* or user IDs.
* @param {string[]} orderedTransitionSequences an array which is some ordering of
* `Object.keys(eventAggregates)`.
* @returns {string} the textual summary of the aggregated events that occurred.
*/
_generateSummary(eventAggregates, orderedTransitionSequences) {
private generateSummary(eventAggregates: Record<string, string[]>, orderedTransitionSequences: string[]) {
const summaries = orderedTransitionSequences.map((transitions) => {
const userNames = eventAggregates[transitions];
const nameList = this._renderNameList(userNames);
const nameList = this.renderNameList(userNames);
const splitTransitions = transitions.split(',');
const splitTransitions = transitions.split(SEP) as TransitionType[];
// Some neighbouring transitions are common, so canonicalise some into "pair"
// transitions
const canonicalTransitions = this._getCanonicalTransitions(splitTransitions);
const canonicalTransitions = MemberEventListSummary.getCanonicalTransitions(splitTransitions);
// Transform into consecutive repetitions of the same transition (like 5
// consecutive 'joined_and_left's)
const coalescedTransitions = this._coalesceRepeatedTransitions(
canonicalTransitions,
);
const coalescedTransitions = MemberEventListSummary.coalesceRepeatedTransitions(canonicalTransitions);
const descs = coalescedTransitions.map((t) => {
return this._getDescriptionForTransition(
return MemberEventListSummary.getDescriptionForTransition(
t.transitionType, userNames.length, t.repeats,
);
});
@ -108,7 +134,7 @@ export default class MemberEventListSummary extends React.Component {
* more items in `users` than `this.props.summaryLength`, which is the number of names
* included before "and [n] others".
*/
_renderNameList(users) {
private renderNameList(users: string[]) {
return formatCommaSeparatedList(users, this.props.summaryLength);
}
@ -119,22 +145,22 @@ export default class MemberEventListSummary extends React.Component {
* @param {string[]} transitions an array of transitions.
* @returns {string[]} an array of transitions.
*/
_getCanonicalTransitions(transitions) {
private static getCanonicalTransitions(transitions: TransitionType[]): TransitionType[] {
const modMap = {
'joined': {
'after': 'left',
'newTransition': 'joined_and_left',
[TransitionType.Joined]: {
after: TransitionType.Left,
newTransition: TransitionType.JoinedAndLeft,
},
'left': {
'after': 'joined',
'newTransition': 'left_and_joined',
[TransitionType.Left]: {
after: TransitionType.Joined,
newTransition: TransitionType.LeftAndJoined,
},
// $currentTransition : {
// 'after' : $nextTransition,
// 'newTransition' : 'new_transition_type',
// },
};
const res = [];
const res: TransitionType[] = [];
for (let i = 0; i < transitions.length; i++) {
const t = transitions[i];
@ -166,8 +192,12 @@ export default class MemberEventListSummary extends React.Component {
* @param {string[]} transitions the array of transitions to transform.
* @returns {object[]} an array of coalesced transitions.
*/
_coalesceRepeatedTransitions(transitions) {
const res = [];
private static coalesceRepeatedTransitions(transitions: TransitionType[]) {
const res: {
transitionType: TransitionType;
repeats: number;
}[] = [];
for (let i = 0; i < transitions.length; i++) {
if (res.length > 0 && res[res.length - 1].transitionType === transitions[i]) {
res[res.length - 1].repeats += 1;
@ -189,7 +219,7 @@ export default class MemberEventListSummary extends React.Component {
* @param {number} repeats the number of times the transition was repeated in a row.
* @returns {string} the written Human Readable equivalent of the transition.
*/
_getDescriptionForTransition(t, userCount, repeats) {
private static getDescriptionForTransition(t: TransitionType, userCount: number, repeats: number) {
// The empty interpolations 'severalUsers' and 'oneUser'
// are there only to show translators to non-English languages
// that the verb is conjugated to plural or singular Subject.
@ -217,12 +247,18 @@ export default class MemberEventListSummary extends React.Component {
break;
case "invite_reject":
res = (userCount > 1)
? _t("%(severalUsers)srejected their invitations %(count)s times", { severalUsers: "", count: repeats })
? _t("%(severalUsers)srejected their invitations %(count)s times", {
severalUsers: "",
count: repeats,
})
: _t("%(oneUser)srejected their invitation %(count)s times", { oneUser: "", count: repeats });
break;
case "invite_withdrawal":
res = (userCount > 1)
? _t("%(severalUsers)shad their invitations withdrawn %(count)s times", { severalUsers: "", count: repeats })
? _t("%(severalUsers)shad their invitations withdrawn %(count)s times", {
severalUsers: "",
count: repeats,
})
: _t("%(oneUser)shad their invitation withdrawn %(count)s times", { oneUser: "", count: repeats });
break;
case "invited":
@ -265,8 +301,8 @@ export default class MemberEventListSummary extends React.Component {
return res;
}
_getTransitionSequence(events) {
return events.map(this._getTransition);
private static getTransitionSequence(events: MatrixEvent[]) {
return events.map(MemberEventListSummary.getTransition);
}
/**
@ -277,60 +313,60 @@ export default class MemberEventListSummary extends React.Component {
* @returns {string?} the transition type given to this event. This defaults to `null`
* if a transition is not recognised.
*/
_getTransition(e) {
private static getTransition(e: MatrixEvent): TransitionType {
if (e.mxEvent.getType() === 'm.room.third_party_invite') {
// Handle 3pid invites the same as invites so they get bundled together
if (!isValid3pidInvite(e.mxEvent)) {
return 'invite_withdrawal';
return TransitionType.InviteWithdrawal;
}
return 'invited';
return TransitionType.Invited;
}
switch (e.mxEvent.getContent().membership) {
case 'invite': return 'invited';
case 'ban': return 'banned';
case 'invite': return TransitionType.Invited;
case 'ban': return TransitionType.Banned;
case 'join':
if (e.mxEvent.getPrevContent().membership === 'join') {
if (e.mxEvent.getContent().displayname !==
e.mxEvent.getPrevContent().displayname) {
return 'changed_name';
return TransitionType.ChangedName;
} else if (e.mxEvent.getContent().avatar_url !==
e.mxEvent.getPrevContent().avatar_url) {
return 'changed_avatar';
return TransitionType.ChangedAvatar;
}
// console.log("MELS ignoring duplicate membership join event");
return 'no_change';
return TransitionType.NoChange;
} else {
return 'joined';
return TransitionType.Joined;
}
case 'leave':
if (e.mxEvent.getSender() === e.mxEvent.getStateKey()) {
switch (e.mxEvent.getPrevContent().membership) {
case 'invite': return 'invite_reject';
default: return 'left';
case 'invite': return TransitionType.InviteReject;
default: return TransitionType.Left;
}
}
switch (e.mxEvent.getPrevContent().membership) {
case 'invite': return 'invite_withdrawal';
case 'ban': return 'unbanned';
case 'invite': return TransitionType.InviteWithdrawal;
case 'ban': return TransitionType.Unbanned;
// sender is not target and made the target leave, if not from invite/ban then this is a kick
default: return 'kicked';
default: return TransitionType.Kicked;
}
default: return null;
}
}
_getAggregate(userEvents) {
getAggregate(userEvents: Record<string, IUserEvents[]>) {
// A map of aggregate type to arrays of display names. Each aggregate type
// is a comma-delimited string of transitions, e.g. "joined,left,kicked".
// The array of display names is the array of users who went through that
// sequence during eventsToRender.
const aggregate = {
const aggregate: Record<string, string[]> = {
// $aggregateType : []:string
};
// A map of aggregate types to the indices that order them (the index of
// the first event for a given transition sequence)
const aggregateIndices = {
const aggregateIndices: Record<string, number> = {
// $aggregateType : int
};
@ -340,7 +376,7 @@ export default class MemberEventListSummary extends React.Component {
const firstEvent = userEvents[userId][0];
const displayName = firstEvent.displayName;
const seq = this._getTransitionSequence(userEvents[userId]);
const seq = MemberEventListSummary.getTransitionSequence(userEvents[userId]).join(SEP);
if (!aggregate[seq]) {
aggregate[seq] = [];
aggregateIndices[seq] = -1;
@ -349,8 +385,9 @@ export default class MemberEventListSummary extends React.Component {
aggregate[seq].push(displayName);
if (aggregateIndices[seq] === -1 ||
firstEvent.index < aggregateIndices[seq]) {
aggregateIndices[seq] = firstEvent.index;
firstEvent.index < aggregateIndices[seq]
) {
aggregateIndices[seq] = firstEvent.index;
}
},
);
@ -364,25 +401,21 @@ export default class MemberEventListSummary extends React.Component {
render() {
const eventsToRender = this.props.events;
// Map user IDs to an array of objects:
const userEvents = {
// $userId : [{
// // The original event
// mxEvent: e,
// // The display name of the user (if not, then user ID)
// displayName: e.target.name || userId,
// // The original index of the event in this.props.events
// index: index,
// }]
};
// Map user IDs to latest Avatar Member. ES6 Maps are ordered by when the key was created,
// so this works perfectly for us to match event order whilst storing the latest Avatar Member
const latestUserAvatarMember = new Map<string, RoomMember>();
const avatarMembers = [];
// Object mapping user IDs to an array of IUserEvents
const userEvents: Record<string, IUserEvents[]> = {};
eventsToRender.forEach((e, index) => {
const userId = e.getStateKey();
// Initialise a user's events
if (!userEvents[userId]) {
userEvents[userId] = [];
if (e.target) avatarMembers.push(e.target);
}
if (e.target) {
latestUserAvatarMember.set(userId, e.target);
}
let displayName = userId;
@ -399,21 +432,20 @@ export default class MemberEventListSummary extends React.Component {
});
});
const aggregate = this._getAggregate(userEvents);
const aggregate = this.getAggregate(userEvents);
// Sort types by order of lowest event index within sequence
const orderedTransitionSequences = Object.keys(aggregate.names).sort(
(seq1, seq2) => aggregate.indices[seq1] > aggregate.indices[seq2],
(seq1, seq2) => aggregate.indices[seq1] - aggregate.indices[seq2],
);
const EventListSummary = sdk.getComponent("views.elements.EventListSummary");
return <EventListSummary
events={this.props.events}
threshold={this.props.threshold}
onToggle={this.props.onToggle}
startExpanded={this.props.startExpanded}
children={this.props.children}
summaryMembers={avatarMembers}
summaryText={this._generateSummary(aggregate.names, orderedTransitionSequences)} />;
summaryMembers={[...latestUserAvatarMember.values()]}
summaryText={this.generateSummary(aggregate.names, orderedTransitionSequences)} />;
}
}

View file

@ -82,6 +82,7 @@ export default class PersistentApp extends React.Component {
showDelete={false}
showMinimise={false}
miniMode={true}
showMenubar={false}
/>;
}
}

View file

@ -29,6 +29,7 @@ import MatrixClientContext from "../../../contexts/MatrixClientContext";
import {Action} from "../../../dispatcher/actions";
import sanitizeHtml from "sanitize-html";
import {UIFeature} from "../../../settings/UIFeature";
import {PERMITTED_URL_SCHEMES} from "../../../HtmlUtils";
// This component does no cycle detection, simply because the only way to make such a cycle would be to
// craft event_id's, using a homeserver that generates predictable event IDs; even then the impact would
@ -62,6 +63,12 @@ export default class ReplyThread extends React.Component {
err: false,
};
this.unmounted = false;
this.context.on("Event.replaced", this.onEventReplaced);
this.room = this.context.getRoom(this.props.parentEv.getRoomId());
this.room.on("Room.redaction", this.onRoomRedaction);
this.room.on("Room.redactionCancelled", this.onRoomRedaction);
this.onQuoteClick = this.onQuoteClick.bind(this);
this.canCollapse = this.canCollapse.bind(this);
this.collapse = this.collapse.bind(this);
@ -106,6 +113,9 @@ export default class ReplyThread extends React.Component {
{
allowedTags: false, // false means allow everything
allowedAttributes: false,
// we somehow can't allow all schemes, so we allow all that we
// know of and mxc (for img tags)
allowedSchemes: [...PERMITTED_URL_SCHEMES, 'mxc'],
exclusiveFilter: (frame) => frame.tag === "mx-reply",
},
);
@ -213,11 +223,6 @@ export default class ReplyThread extends React.Component {
}
componentDidMount() {
this.unmounted = false;
this.room = this.context.getRoom(this.props.parentEv.getRoomId());
this.room.on("Room.redaction", this.onRoomRedaction);
// same event handler as Room.redaction as for both we just do forceUpdate
this.room.on("Room.redactionCancelled", this.onRoomRedaction);
this.initialize();
}
@ -227,21 +232,36 @@ export default class ReplyThread extends React.Component {
componentWillUnmount() {
this.unmounted = true;
this.context.removeListener("Event.replaced", this.onEventReplaced);
if (this.room) {
this.room.removeListener("Room.redaction", this.onRoomRedaction);
this.room.removeListener("Room.redactionCancelled", this.onRoomRedaction);
}
}
onRoomRedaction = (ev, room) => {
if (this.unmounted) return;
// If one of the events we are rendering gets redacted, force a re-render
if (this.state.events.some(event => event.getId() === ev.getId())) {
updateForEventId = (eventId) => {
if (this.state.events.some(event => event.getId() === eventId)) {
this.forceUpdate();
}
};
onEventReplaced = (ev) => {
if (this.unmounted) return;
// If one of the events we are rendering gets replaced, force a re-render
this.updateForEventId(ev.getId());
};
onRoomRedaction = (ev) => {
if (this.unmounted) return;
const eventId = ev.getAssociatedId();
if (!eventId) return;
// If one of the events we are rendering gets redacted, force a re-render
this.updateForEventId(eventId);
};
async initialize() {
const {parentEv} = this.props;
// at time of making this component we checked that props.parentEv has a parentEventId
@ -368,6 +388,7 @@ export default class ReplyThread extends React.Component {
isTwelveHour={SettingsStore.getValue("showTwelveHourTimestamps")}
useIRCLayout={this.props.useIRCLayout}
enableFlair={SettingsStore.getValue(UIFeature.Flair)}
replacingEventId={ev.replacingEventId()}
/>
</blockquote>;
});

View file

@ -21,18 +21,19 @@ import classNames from "classnames";
type Data = Pick<IFieldState, "value" | "allowEmpty">;
interface IRule<T> {
interface IRule<T, D = void> {
key: string;
final?: boolean;
skip?(this: T, data: Data): boolean;
test(this: T, data: Data): boolean | Promise<boolean>;
valid?(this: T): string;
invalid?(this: T): string;
skip?(this: T, data: Data, derivedData: D): boolean;
test(this: T, data: Data, derivedData: D): boolean | Promise<boolean>;
valid?(this: T, derivedData: D): string;
invalid?(this: T, derivedData: D): string;
}
interface IArgs<T> {
rules: IRule<T>[];
description(this: T): React.ReactChild;
interface IArgs<T, D = void> {
rules: IRule<T, D>[];
description(this: T, derivedData: D): React.ReactChild;
deriveData?(data: Data): Promise<D>;
}
export interface IFieldState {
@ -53,6 +54,10 @@ export interface IValidationResult {
* @param {Function} description
* Function that returns a string summary of the kind of value that will
* meet the validation rules. Shown at the top of the validation feedback.
* @param {Function} deriveData
* Optional function that returns a Promise to an object of generic type D.
* The result of this Promise is passed to rule methods `skip`, `test`, `valid`, and `invalid`.
* Useful for doing calculations per-value update once rather than in each of the above rule methods.
* @param {Object} rules
* An array of rules describing how to check to input value. Each rule in an object
* and may have the following properties:
@ -66,7 +71,7 @@ export interface IValidationResult {
* A validation function that takes in the current input value and returns
* the overall validity and a feedback UI that can be rendered for more detail.
*/
export default function withValidation<T = undefined>({ description, rules }: IArgs<T>) {
export default function withValidation<T = undefined, D = void>({ description, deriveData, rules }: IArgs<T, D>) {
return async function onValidate({ value, focused, allowEmpty = true }: IFieldState): Promise<IValidationResult> {
if (!value && allowEmpty) {
return {
@ -75,6 +80,9 @@ export default function withValidation<T = undefined>({ description, rules }: IA
};
}
const data = { value, allowEmpty };
const derivedData = deriveData ? await deriveData(data) : undefined;
const results = [];
let valid = true;
if (rules && rules.length) {
@ -87,20 +95,18 @@ export default function withValidation<T = undefined>({ description, rules }: IA
continue;
}
const data = { value, allowEmpty };
if (rule.skip && rule.skip.call(this, data)) {
if (rule.skip && rule.skip.call(this, data, derivedData)) {
continue;
}
// We're setting `this` to whichever component holds the validation
// function. That allows rules to access the state of the component.
const ruleValid = await rule.test.call(this, data);
const ruleValid = await rule.test.call(this, data, derivedData);
valid = valid && ruleValid;
if (ruleValid && rule.valid) {
// If the rule's result is valid and has text to show for
// the valid state, show it.
const text = rule.valid.call(this);
const text = rule.valid.call(this, derivedData);
if (!text) {
continue;
}
@ -112,7 +118,7 @@ export default function withValidation<T = undefined>({ description, rules }: IA
} else if (!ruleValid && rule.invalid) {
// If the rule's result is invalid and has text to show for
// the invalid state, show it.
const text = rule.invalid.call(this);
const text = rule.invalid.call(this, derivedData);
if (!text) {
continue;
}
@ -153,7 +159,7 @@ export default function withValidation<T = undefined>({ description, rules }: IA
if (description) {
// We're setting `this` to whichever component holds the validation
// function. That allows rules to access the state of the component.
const content = description.call(this);
const content = description.call(this, derivedData);
summary = <div className="mx_Validation_description">{content}</div>;
}

View file

@ -1,5 +1,6 @@
/*
Copyright 2019 Tulir Asokan <tulir@maunium.net>
Copyright 2020 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@ -14,32 +15,53 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import React from 'react';
import PropTypes from 'prop-types';
import React, {RefObject} from 'react';
import { CATEGORY_HEADER_HEIGHT, EMOJI_HEIGHT, EMOJIS_PER_ROW } from "./EmojiPicker";
import * as sdk from '../../../index';
import LazyRenderList from "../elements/LazyRenderList";
import {DATA_BY_CATEGORY, IEmoji} from "../../../emoji";
import Emoji from './Emoji';
const OVERFLOW_ROWS = 3;
class Category extends React.PureComponent {
static propTypes = {
emojis: PropTypes.arrayOf(PropTypes.object).isRequired,
name: PropTypes.string.isRequired,
id: PropTypes.string.isRequired,
onMouseEnter: PropTypes.func.isRequired,
onMouseLeave: PropTypes.func.isRequired,
onClick: PropTypes.func.isRequired,
selectedEmojis: PropTypes.instanceOf(Set),
};
export type CategoryKey = (keyof typeof DATA_BY_CATEGORY) | "recent";
_renderEmojiRow = (rowIndex) => {
export interface ICategory {
id: CategoryKey;
name: string;
enabled: boolean;
visible: boolean;
ref: RefObject<HTMLButtonElement>;
}
interface IProps {
id: string;
name: string;
emojis: IEmoji[];
selectedEmojis: Set<string>;
heightBefore: number;
viewportHeight: number;
scrollTop: number;
onClick(emoji: IEmoji): void;
onMouseEnter(emoji: IEmoji): void;
onMouseLeave(emoji: IEmoji): void;
}
class Category extends React.PureComponent<IProps> {
private renderEmojiRow = (rowIndex: number) => {
const { onClick, onMouseEnter, onMouseLeave, selectedEmojis, emojis } = this.props;
const emojisForRow = emojis.slice(rowIndex * 8, (rowIndex + 1) * 8);
const Emoji = sdk.getComponent("emojipicker.Emoji");
return (<div key={rowIndex}>{
emojisForRow.map(emoji =>
<Emoji key={emoji.hexcode} emoji={emoji} selectedEmojis={selectedEmojis}
onClick={onClick} onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave} />)
emojisForRow.map(emoji => ((
<Emoji
key={emoji.hexcode}
emoji={emoji}
selectedEmojis={selectedEmojis}
onClick={onClick}
onMouseEnter={onMouseEnter}
onMouseLeave={onMouseLeave}
/>
)))
}</div>);
};
@ -52,7 +74,6 @@ class Category extends React.PureComponent {
for (let counter = 0; counter < rows.length; ++counter) {
rows[counter] = counter;
}
const LazyRenderList = sdk.getComponent('elements.LazyRenderList');
const viewportTop = scrollTop;
const viewportBottom = viewportTop + viewportHeight;
@ -84,7 +105,7 @@ class Category extends React.PureComponent {
height={localHeight}
overflowItems={OVERFLOW_ROWS}
overflowMargin={0}
renderItem={this._renderEmojiRow}>
renderItem={this.renderEmojiRow}>
</LazyRenderList>
</section>
);

View file

@ -1,5 +1,6 @@
/*
Copyright 2019 Tulir Asokan <tulir@maunium.net>
Copyright 2020 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@ -15,18 +16,19 @@ limitations under the License.
*/
import React from 'react';
import PropTypes from 'prop-types';
import {MenuItem} from "../../structures/ContextMenu";
import {IEmoji} from "../../../emoji";
class Emoji extends React.PureComponent {
static propTypes = {
onClick: PropTypes.func,
onMouseEnter: PropTypes.func,
onMouseLeave: PropTypes.func,
emoji: PropTypes.object.isRequired,
selectedEmojis: PropTypes.instanceOf(Set),
};
interface IProps {
emoji: IEmoji;
selectedEmojis?: Set<string>;
onClick(emoji: IEmoji): void;
onMouseEnter(emoji: IEmoji): void;
onMouseLeave(emoji: IEmoji): void;
}
class Emoji extends React.PureComponent<IProps> {
render() {
const { onClick, onMouseEnter, onMouseLeave, emoji, selectedEmojis } = this.props;
const isSelected = selectedEmojis && selectedEmojis.has(emoji.unicode);

View file

@ -1,5 +1,6 @@
/*
Copyright 2019 Tulir Asokan <tulir@maunium.net>
Copyright 2020 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@ -15,25 +16,43 @@ limitations under the License.
*/
import React from 'react';
import PropTypes from 'prop-types';
import * as sdk from '../../../index';
import { _t } from '../../../languageHandler';
import * as recent from '../../../emojipicker/recent';
import {DATA_BY_CATEGORY, getEmojiFromUnicode} from "../../../emoji";
import {DATA_BY_CATEGORY, getEmojiFromUnicode, IEmoji} from "../../../emoji";
import AutoHideScrollbar from "../../structures/AutoHideScrollbar";
import Header from "./Header";
import Search from "./Search";
import Preview from "./Preview";
import QuickReactions from "./QuickReactions";
import Category, {ICategory, CategoryKey} from "./Category";
export const CATEGORY_HEADER_HEIGHT = 22;
export const EMOJI_HEIGHT = 37;
export const EMOJIS_PER_ROW = 8;
class EmojiPicker extends React.Component {
static propTypes = {
onChoose: PropTypes.func.isRequired,
selectedEmojis: PropTypes.instanceOf(Set),
showQuickReactions: PropTypes.bool,
};
interface IProps {
selectedEmojis: Set<string>;
showQuickReactions?: boolean;
onChoose(unicode: string): boolean;
}
interface IState {
filter: string;
previewEmoji?: IEmoji;
scrollTop: number;
// initial estimation of height, dialog is hardcoded to 450px height.
// should be enough to never have blank rows of emojis as
// 3 rows of overflow are also rendered. The actual value is updated on scroll.
viewportHeight: number;
}
class EmojiPicker extends React.Component<IProps, IState> {
private readonly recentlyUsed: IEmoji[];
private readonly memoizedDataByCategory: Record<CategoryKey, IEmoji[]>;
private readonly categories: ICategory[];
private bodyRef = React.createRef<HTMLDivElement>();
constructor(props) {
super(props);
@ -42,9 +61,6 @@ class EmojiPicker extends React.Component {
filter: "",
previewEmoji: null,
scrollTop: 0,
// initial estimation of height, dialog is hardcoded to 450px height.
// should be enough to never have blank rows of emojis as
// 3 rows of overflow are also rendered. The actual value is updated on scroll.
viewportHeight: 280,
};
@ -110,18 +126,9 @@ class EmojiPicker extends React.Component {
visible: false,
ref: React.createRef(),
}];
this.bodyRef = React.createRef();
this.onChangeFilter = this.onChangeFilter.bind(this);
this.onHoverEmoji = this.onHoverEmoji.bind(this);
this.onHoverEmojiEnd = this.onHoverEmojiEnd.bind(this);
this.onClickEmoji = this.onClickEmoji.bind(this);
this.scrollToCategory = this.scrollToCategory.bind(this);
this.updateVisibility = this.updateVisibility.bind(this);
}
onScroll = () => {
private onScroll = () => {
const body = this.bodyRef.current;
this.setState({
scrollTop: body.scrollTop,
@ -130,7 +137,7 @@ class EmojiPicker extends React.Component {
this.updateVisibility();
};
updateVisibility() {
private updateVisibility = () => {
const body = this.bodyRef.current;
const rect = body.getBoundingClientRect();
for (const cat of this.categories) {
@ -147,21 +154,21 @@ class EmojiPicker extends React.Component {
// We update this here instead of through React to avoid re-render on scroll.
if (cat.visible) {
cat.ref.current.classList.add("mx_EmojiPicker_anchor_visible");
cat.ref.current.setAttribute("aria-selected", true);
cat.ref.current.setAttribute("tabindex", 0);
cat.ref.current.setAttribute("aria-selected", "true");
cat.ref.current.setAttribute("tabindex", "0");
} else {
cat.ref.current.classList.remove("mx_EmojiPicker_anchor_visible");
cat.ref.current.setAttribute("aria-selected", false);
cat.ref.current.setAttribute("tabindex", -1);
cat.ref.current.setAttribute("aria-selected", "false");
cat.ref.current.setAttribute("tabindex", "-1");
}
}
}
};
scrollToCategory(category) {
private scrollToCategory = (category: string) => {
this.bodyRef.current.querySelector(`[data-category-id="${category}"]`).scrollIntoView();
}
};
onChangeFilter(filter) {
private onChangeFilter = (filter: string) => {
filter = filter.toLowerCase(); // filter is case insensitive stored lower-case
for (const cat of this.categories) {
let emojis;
@ -181,27 +188,34 @@ class EmojiPicker extends React.Component {
// Header underlines need to be updated, but updating requires knowing
// where the categories are, so we wait for a tick.
setTimeout(this.updateVisibility, 0);
}
};
onHoverEmoji(emoji) {
private onEnterFilter = () => {
const btn = this.bodyRef.current.querySelector<HTMLButtonElement>(".mx_EmojiPicker_item");
if (btn) {
btn.click();
}
};
private onHoverEmoji = (emoji: IEmoji) => {
this.setState({
previewEmoji: emoji,
});
}
};
onHoverEmojiEnd(emoji) {
private onHoverEmojiEnd = (emoji: IEmoji) => {
this.setState({
previewEmoji: null,
});
}
};
onClickEmoji(emoji) {
private onClickEmoji = (emoji: IEmoji) => {
if (this.props.onChoose(emoji.unicode) !== false) {
recent.add(emoji.unicode);
}
}
};
_categoryHeightForEmojiCount(count) {
private static categoryHeightForEmojiCount(count: number) {
if (count === 0) {
return 0;
}
@ -209,25 +223,37 @@ class EmojiPicker extends React.Component {
}
render() {
const Header = sdk.getComponent("emojipicker.Header");
const Search = sdk.getComponent("emojipicker.Search");
const Category = sdk.getComponent("emojipicker.Category");
const Preview = sdk.getComponent("emojipicker.Preview");
const QuickReactions = sdk.getComponent("emojipicker.QuickReactions");
let heightBefore = 0;
return (
<div className="mx_EmojiPicker">
<Header categories={this.categories} defaultCategory="recent" onAnchorClick={this.scrollToCategory} />
<Search query={this.state.filter} onChange={this.onChangeFilter} />
<AutoHideScrollbar className="mx_EmojiPicker_body" wrappedRef={e => this.bodyRef.current = e} onScroll={this.onScroll}>
<Header categories={this.categories} onAnchorClick={this.scrollToCategory} />
<Search query={this.state.filter} onChange={this.onChangeFilter} onEnter={this.onEnterFilter} />
<AutoHideScrollbar
className="mx_EmojiPicker_body"
wrappedRef={ref => {
// @ts-ignore - AutoHideScrollbar should accept a RefObject or fall back to its own instead
this.bodyRef.current = ref
}}
onScroll={this.onScroll}
>
{this.categories.map(category => {
const emojis = this.memoizedDataByCategory[category.id];
const categoryElement = (<Category key={category.id} id={category.id} name={category.name}
heightBefore={heightBefore} viewportHeight={this.state.viewportHeight}
scrollTop={this.state.scrollTop} emojis={emojis} onClick={this.onClickEmoji}
onMouseEnter={this.onHoverEmoji} onMouseLeave={this.onHoverEmojiEnd}
selectedEmojis={this.props.selectedEmojis} />);
const height = this._categoryHeightForEmojiCount(emojis.length);
const categoryElement = ((
<Category
key={category.id}
id={category.id}
name={category.name}
heightBefore={heightBefore}
viewportHeight={this.state.viewportHeight}
scrollTop={this.state.scrollTop}
emojis={emojis}
onClick={this.onClickEmoji}
onMouseEnter={this.onHoverEmoji}
onMouseLeave={this.onHoverEmojiEnd}
selectedEmojis={this.props.selectedEmojis}
/>
));
const height = EmojiPicker.categoryHeightForEmojiCount(emojis.length);
heightBefore += height;
return categoryElement;
})}

View file

@ -1,5 +1,6 @@
/*
Copyright 2019 Tulir Asokan <tulir@maunium.net>
Copyright 2020 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@ -15,19 +16,19 @@ limitations under the License.
*/
import React from 'react';
import PropTypes from 'prop-types';
import classNames from "classnames";
import {_t} from "../../../languageHandler";
import {Key} from "../../../Keyboard";
import {CategoryKey, ICategory} from "./Category";
class Header extends React.PureComponent {
static propTypes = {
categories: PropTypes.arrayOf(PropTypes.object).isRequired,
onAnchorClick: PropTypes.func.isRequired,
};
interface IProps {
categories: ICategory[];
onAnchorClick(id: CategoryKey): void
}
findNearestEnabled(index, delta) {
class Header extends React.PureComponent<IProps> {
private findNearestEnabled(index: number, delta: number) {
index += this.props.categories.length;
const cats = [...this.props.categories, ...this.props.categories, ...this.props.categories];
@ -37,12 +38,12 @@ class Header extends React.PureComponent {
}
}
changeCategoryRelative(delta) {
private changeCategoryRelative(delta: number) {
const current = this.props.categories.findIndex(c => c.visible);
this.changeCategoryAbsolute(current + delta, delta);
}
changeCategoryAbsolute(index, delta=1) {
private changeCategoryAbsolute(index: number, delta=1) {
const category = this.props.categories[this.findNearestEnabled(index, delta)];
if (category) {
this.props.onAnchorClick(category.id);
@ -52,7 +53,7 @@ class Header extends React.PureComponent {
// Implements ARIA Tabs with Automatic Activation pattern
// https://www.w3.org/TR/wai-aria-practices/examples/tabs/tabs-1/tabs.html
onKeyDown = (ev) => {
private onKeyDown = (ev: React.KeyboardEvent) => {
let handled = true;
switch (ev.key) {
case Key.ARROW_LEFT:
@ -80,7 +81,12 @@ class Header extends React.PureComponent {
render() {
return (
<nav className="mx_EmojiPicker_header" role="tablist" aria-label={_t("Categories")} onKeyDown={this.onKeyDown}>
<nav
className="mx_EmojiPicker_header"
role="tablist"
aria-label={_t("Categories")}
onKeyDown={this.onKeyDown}
>
{this.props.categories.map(category => {
const classes = classNames(`mx_EmojiPicker_anchor mx_EmojiPicker_anchor_${category.id}`, {
mx_EmojiPicker_anchor_visible: category.visible,

View file

@ -1,5 +1,6 @@
/*
Copyright 2019 Tulir Asokan <tulir@maunium.net>
Copyright 2020 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@ -15,19 +16,21 @@ limitations under the License.
*/
import React from 'react';
import PropTypes from 'prop-types';
class Preview extends React.PureComponent {
static propTypes = {
emoji: PropTypes.object,
};
import {IEmoji} from "../../../emoji";
interface IProps {
emoji: IEmoji;
}
class Preview extends React.PureComponent<IProps> {
render() {
const {
unicode = "",
annotation = "",
shortcodes: [shortcode = ""],
} = this.props.emoji || {};
return (
<div className="mx_EmojiPicker_footer mx_EmojiPicker_preview">
<div className="mx_EmojiPicker_preview_emoji">

View file

@ -1,5 +1,6 @@
/*
Copyright 2019 Tulir Asokan <tulir@maunium.net>
Copyright 2020 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@ -15,11 +16,10 @@ limitations under the License.
*/
import React from 'react';
import PropTypes from 'prop-types';
import * as sdk from '../../../index';
import { _t } from '../../../languageHandler';
import {getEmojiFromUnicode} from "../../../emoji";
import {getEmojiFromUnicode, IEmoji} from "../../../emoji";
import Emoji from "./Emoji";
// We use the variation-selector Heart in Quick Reactions for some reason
const QUICK_REACTIONS = ["👍", "👎", "😄", "🎉", "😕", "❤️", "🚀", "👀"].map(emoji => {
@ -30,36 +30,36 @@ const QUICK_REACTIONS = ["👍", "👎", "😄", "🎉", "😕", "❤️", "🚀
return data;
});
class QuickReactions extends React.Component {
static propTypes = {
onClick: PropTypes.func.isRequired,
selectedEmojis: PropTypes.instanceOf(Set),
};
interface IProps {
selectedEmojis?: Set<string>;
onClick(emoji: IEmoji): void;
}
interface IState {
hover?: IEmoji;
}
class QuickReactions extends React.Component<IProps, IState> {
constructor(props) {
super(props);
this.state = {
hover: null,
};
this.onMouseEnter = this.onMouseEnter.bind(this);
this.onMouseLeave = this.onMouseLeave.bind(this);
}
onMouseEnter(emoji) {
private onMouseEnter = (emoji: IEmoji) => {
this.setState({
hover: emoji,
});
}
};
onMouseLeave() {
private onMouseLeave = () => {
this.setState({
hover: null,
});
}
};
render() {
const Emoji = sdk.getComponent("emojipicker.Emoji");
return (
<section className="mx_EmojiPicker_footer mx_EmojiPicker_quick mx_EmojiPicker_category">
<h2 className="mx_EmojiPicker_quick_header mx_EmojiPicker_category_label">
@ -72,10 +72,16 @@ class QuickReactions extends React.Component {
}
</h2>
<ul className="mx_EmojiPicker_list" aria-label={_t("Quick Reactions")}>
{QUICK_REACTIONS.map(emoji => <Emoji
key={emoji.hexcode} emoji={emoji} onClick={this.props.onClick}
onMouseEnter={this.onMouseEnter} onMouseLeave={this.onMouseLeave}
selectedEmojis={this.props.selectedEmojis} />)}
{QUICK_REACTIONS.map(emoji => ((
<Emoji
key={emoji.hexcode}
emoji={emoji}
onClick={this.props.onClick}
onMouseEnter={this.onMouseEnter}
onMouseLeave={this.onMouseLeave}
selectedEmojis={this.props.selectedEmojis}
/>
)))}
</ul>
</section>
);

View file

@ -1,5 +1,6 @@
/*
Copyright 2019 Tulir Asokan <tulir@maunium.net>
Copyright 2020 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@ -15,26 +16,29 @@ limitations under the License.
*/
import React from 'react';
import PropTypes from "prop-types";
import {MatrixEvent} from "matrix-js-sdk/src/models/event";
import EmojiPicker from "./EmojiPicker";
import {MatrixClientPeg} from "../../../MatrixClientPeg";
import dis from "../../../dispatcher/dispatcher";
class ReactionPicker extends React.Component {
static propTypes = {
mxEvent: PropTypes.object.isRequired,
onFinished: PropTypes.func.isRequired,
reactions: PropTypes.object,
};
interface IProps {
mxEvent: MatrixEvent;
reactions: any; // TODO type this once js-sdk is more typescripted
onFinished(): void;
}
interface IState {
selectedEmojis: Set<string>;
}
class ReactionPicker extends React.Component<IProps, IState> {
constructor(props) {
super(props);
this.state = {
selectedEmojis: new Set(Object.keys(this.getReactions())),
};
this.onChoose = this.onChoose.bind(this);
this.onReactionsChange = this.onReactionsChange.bind(this);
this.addListeners();
}
@ -45,7 +49,7 @@ class ReactionPicker extends React.Component {
}
}
addListeners() {
private addListeners() {
if (this.props.reactions) {
this.props.reactions.on("Relations.add", this.onReactionsChange);
this.props.reactions.on("Relations.remove", this.onReactionsChange);
@ -55,22 +59,13 @@ class ReactionPicker extends React.Component {
componentWillUnmount() {
if (this.props.reactions) {
this.props.reactions.removeListener(
"Relations.add",
this.onReactionsChange,
);
this.props.reactions.removeListener(
"Relations.remove",
this.onReactionsChange,
);
this.props.reactions.removeListener(
"Relations.redaction",
this.onReactionsChange,
);
this.props.reactions.removeListener("Relations.add", this.onReactionsChange);
this.props.reactions.removeListener("Relations.remove", this.onReactionsChange);
this.props.reactions.removeListener("Relations.redaction", this.onReactionsChange);
}
}
getReactions() {
private getReactions() {
if (!this.props.reactions) {
return {};
}
@ -81,13 +76,13 @@ class ReactionPicker extends React.Component {
.map(event => [event.getRelation().key, event.getId()]));
}
onReactionsChange() {
private onReactionsChange = () => {
this.setState({
selectedEmojis: new Set(Object.keys(this.getReactions())),
});
}
};
onChoose(reaction) {
onChoose = (reaction: string) => {
this.componentWillUnmount();
this.props.onFinished();
const myReactions = this.getReactions();
@ -109,7 +104,7 @@ class ReactionPicker extends React.Component {
dis.dispatch({action: "message_sent"});
return true;
}
}
};
render() {
return <EmojiPicker

View file

@ -1,5 +1,6 @@
/*
Copyright 2019 Tulir Asokan <tulir@maunium.net>
Copyright 2020 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@ -15,32 +16,41 @@ limitations under the License.
*/
import React from 'react';
import PropTypes from 'prop-types';
import { _t } from '../../../languageHandler';
import {Key} from "../../../Keyboard";
class Search extends React.PureComponent {
static propTypes = {
query: PropTypes.string.isRequired,
onChange: PropTypes.func.isRequired,
};
interface IProps {
query: string;
onChange(value: string): void;
onEnter(): void;
}
constructor(props) {
super(props);
this.inputRef = React.createRef();
}
class Search extends React.PureComponent<IProps> {
private inputRef = React.createRef<HTMLInputElement>();
componentDidMount() {
// For some reason, neither the autoFocus nor just calling focus() here worked, so here's a setTimeout
setTimeout(() => this.inputRef.current.focus(), 0);
}
private onKeyDown = (ev: React.KeyboardEvent) => {
if (ev.key === Key.ENTER) {
this.props.onEnter();
ev.stopPropagation();
ev.preventDefault();
}
};
render() {
let rightButton;
if (this.props.query) {
rightButton = (
<button onClick={() => this.props.onChange("")}
className="mx_EmojiPicker_search_icon mx_EmojiPicker_search_clear"
title={_t("Cancel search")} />
<button
onClick={() => this.props.onChange("")}
className="mx_EmojiPicker_search_icon mx_EmojiPicker_search_clear"
title={_t("Cancel search")}
/>
);
} else {
rightButton = <span className="mx_EmojiPicker_search_icon" />;
@ -48,8 +58,15 @@ class Search extends React.PureComponent {
return (
<div className="mx_EmojiPicker_search">
<input autoFocus type="text" placeholder="Search" value={this.props.query}
onChange={ev => this.props.onChange(ev.target.value)} ref={this.inputRef} />
<input
autoFocus
type="text"
placeholder="Search"
value={this.props.query}
onChange={ev => this.props.onChange(ev.target.value)}
onKeyDown={this.onKeyDown}
ref={this.inputRef}
/>
{rightButton}
</div>
);

View file

@ -25,10 +25,8 @@ export default class EncryptionEvent extends React.Component {
let body;
let classes = "mx_EventTile_bubble mx_cryptoEvent mx_cryptoEvent_icon";
if (
mxEvent.getContent().algorithm === 'm.megolm.v1.aes-sha2' &&
MatrixClientPeg.get().isRoomEncrypted(mxEvent.getRoomId())
) {
const isRoomEncrypted = MatrixClientPeg.get().isRoomEncrypted(mxEvent.getRoomId());
if (mxEvent.getContent().algorithm === 'm.megolm.v1.aes-sha2' && isRoomEncrypted) {
body = <div>
<div className="mx_cryptoEvent_title">{_t("Encryption enabled")}</div>
<div className="mx_cryptoEvent_subtitle">
@ -38,6 +36,13 @@ export default class EncryptionEvent extends React.Component {
)}
</div>
</div>;
} else if (isRoomEncrypted) {
body = <div>
<div className="mx_cryptoEvent_title">{_t("Encryption enabled")}</div>
<div className="mx_cryptoEvent_subtitle">
{_t("Ignored attempt to disable encryption")}
</div>
</div>;
} else {
body = <div>
<div className="mx_cryptoEvent_title">{_t("Encryption not enabled")}</div>

View file

@ -0,0 +1,76 @@
/*
Copyright 2020 The Matrix.org Foundation C.I.C.
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 { MatrixEvent } from "matrix-js-sdk/src/models/event";
import { _t } from "../../../languageHandler";
import WidgetStore from "../../../stores/WidgetStore";
interface IProps {
mxEvent: MatrixEvent;
}
export default class MJitsiWidgetEvent extends React.PureComponent<IProps> {
constructor(props) {
super(props);
}
render() {
const url = this.props.mxEvent.getContent()['url'];
const prevUrl = this.props.mxEvent.getPrevContent()['url'];
const senderName = this.props.mxEvent.sender?.name || this.props.mxEvent.getSender();
let joinCopy = _t('Join the conference at the top of this room');
if (!WidgetStore.instance.isPinned(this.props.mxEvent.getStateKey())) {
joinCopy = _t('Join the conference from the room information card on the right');
}
if (!url) {
// removed
return (
<div className='mx_EventTile_bubble mx_MJitsiWidgetEvent'>
<div className='mx_MJitsiWidgetEvent_title'>
{_t('Video conference ended by %(senderName)s', {senderName})}
</div>
</div>
);
} else if (prevUrl) {
// modified
return (
<div className='mx_EventTile_bubble mx_MJitsiWidgetEvent'>
<div className='mx_MJitsiWidgetEvent_title'>
{_t('Video conference updated by %(senderName)s', {senderName})}
</div>
<div className='mx_MJitsiWidgetEvent_subtitle'>
{joinCopy}
</div>
</div>
);
} else {
// assume added
return (
<div className='mx_EventTile_bubble mx_MJitsiWidgetEvent'>
<div className='mx_MJitsiWidgetEvent_title'>
{_t("Video conference started by %(senderName)s", {senderName})}
</div>
<div className='mx_MJitsiWidgetEvent_subtitle'>
{joinCopy}
</div>
</div>
);
}
}
}

View file

@ -401,7 +401,8 @@ export default class TextualBody extends React.Component {
const mxEvent = this.props.mxEvent;
const content = mxEvent.getContent();
const stripReply = ReplyThread.getParentEventId(mxEvent);
// only strip reply if this is the original replying event, edits thereafter do not have the fallback
const stripReply = !mxEvent.replacingEvent() && ReplyThread.getParentEventId(mxEvent);
let body = HtmlUtils.bodyToHtml(content, this.props.highlights, {
disableBigEmoji: content.msgtype === "m.emote" || !SettingsStore.getValue('TextualBody.enableBigEmoji'),
// Part of Replies fallback support

View file

@ -31,6 +31,7 @@ interface IProps {
className?: string;
withoutScrollContainer?: boolean;
previousPhase?: RightPanelPhases;
closeLabel?: string;
onClose?(): void;
}
@ -47,6 +48,7 @@ export const Group: React.FC<IGroupProps> = ({ className, title, children }) =>
};
const BaseCard: React.FC<IProps> = ({
closeLabel,
onClose,
className,
header,
@ -68,7 +70,11 @@ const BaseCard: React.FC<IProps> = ({
let closeButton;
if (onClose) {
closeButton = <AccessibleButton className="mx_BaseCard_close" onClick={onClose} title={_t("Close")} />;
closeButton = <AccessibleButton
className="mx_BaseCard_close"
onClick={onClose}
title={closeLabel || _t("Close")}
/>;
}
if (!withoutScrollContainer) {

View file

@ -27,6 +27,9 @@ import * as sdk from "../../../index";
import {_t} from "../../../languageHandler";
import {VerificationRequest} from "matrix-js-sdk/src/crypto/verification/request/VerificationRequest";
import {RoomMember} from "matrix-js-sdk/src/models/room-member";
import dis from "../../../dispatcher/dispatcher";
import {Action} from "../../../dispatcher/actions";
import {RightPanelPhases} from "../../../stores/RightPanelStorePhases";
// cancellation codes which constitute a key mismatch
const MISMATCHES = ["m.key_mismatch", "m.user_error", "m.mismatched_sas"];
@ -42,7 +45,14 @@ interface IProps {
}
const EncryptionPanel: React.FC<IProps> = (props: IProps) => {
const {verificationRequest, verificationRequestPromise, member, onClose, layout, isRoomEncrypted} = props;
const {
verificationRequest,
verificationRequestPromise,
member,
onClose,
layout,
isRoomEncrypted,
} = props;
const [request, setRequest] = useState(verificationRequest);
// state to show a spinner immediately after clicking "start verification",
// before we have a request
@ -95,22 +105,6 @@ const EncryptionPanel: React.FC<IProps> = (props: IProps) => {
}, [onClose, request]);
useEventEmitter(request, "change", changeHandler);
const onCancel = useCallback(function() {
if (request) {
request.cancel();
}
}, [request]);
let cancelButton: JSX.Element;
if (layout !== "dialog" && request && request.pending) {
const AccessibleButton = sdk.getComponent("elements.AccessibleButton");
cancelButton = (<AccessibleButton
className="mx_EncryptionPanel_cancel"
onClick={onCancel}
title={_t('Cancel')}
></AccessibleButton>);
}
const onStartVerification = useCallback(async () => {
setRequesting(true);
const cli = MatrixClientPeg.get();
@ -118,7 +112,13 @@ const EncryptionPanel: React.FC<IProps> = (props: IProps) => {
const verificationRequest_ = await cli.requestVerificationDM(member.userId, roomId);
setRequest(verificationRequest_);
setPhase(verificationRequest_.phase);
}, [member.userId]);
// Notify the RightPanelStore about this
dis.dispatch({
action: Action.SetRightPanelPhase,
phase: RightPanelPhases.EncryptionPanel,
refireParams: { member, verificationRequest: verificationRequest_ },
});
}, [member]);
const requested =
(!request && isRequesting) ||
@ -128,8 +128,7 @@ const EncryptionPanel: React.FC<IProps> = (props: IProps) => {
member.userId === MatrixClientPeg.get().getUserId();
if (!request || requested) {
const initiatedByMe = (!request && isRequesting) || (request && request.initiatedByMe);
return (<React.Fragment>
{cancelButton}
return (
<EncryptionInfo
isRoomEncrypted={isRoomEncrypted}
onStartVerification={onStartVerification}
@ -138,10 +137,9 @@ const EncryptionPanel: React.FC<IProps> = (props: IProps) => {
waitingForOtherParty={requested && initiatedByMe}
waitingForNetwork={requested && !initiatedByMe}
inDialog={layout === "dialog"} />
</React.Fragment>);
);
} else {
return (<React.Fragment>
{cancelButton}
return (
<VerificationPanel
isRoomEncrypted={isRoomEncrypted}
layout={layout}
@ -152,7 +150,7 @@ const EncryptionPanel: React.FC<IProps> = (props: IProps) => {
inDialog={layout === "dialog"}
phase={phase}
/>
</React.Fragment>);
);
}
};

View file

@ -17,20 +17,22 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import React, {useCallback, useMemo, useState, useEffect, useContext} from 'react';
import PropTypes from 'prop-types';
import React, {useCallback, useContext, useEffect, useMemo, useState} from 'react';
import classNames from 'classnames';
import {Group, RoomMember, User, Room} from 'matrix-js-sdk';
import {MatrixClient} from 'matrix-js-sdk/src/client';
import {RoomMember} from 'matrix-js-sdk/src/models/room-member';
import {User} from 'matrix-js-sdk/src/models/user';
import {Room} from 'matrix-js-sdk/src/models/room';
import {EventTimeline} from 'matrix-js-sdk/src/models/event-timeline';
import dis from '../../../dispatcher/dispatcher';
import Modal from '../../../Modal';
import * as sdk from '../../../index';
import { _t } from '../../../languageHandler';
import {_t} from '../../../languageHandler';
import createRoom, {privateShouldBeEncrypted} from '../../../createRoom';
import DMRoomMap from '../../../utils/DMRoomMap';
import AccessibleButton from '../elements/AccessibleButton';
import SdkConfig from '../../../SdkConfig';
import SettingsStore from "../../../settings/SettingsStore";
import {EventTimeline} from "matrix-js-sdk";
import RoomViewStore from "../../../stores/RoomViewStore";
import MultiInviter from "../../../utils/MultiInviter";
import GroupStore from "../../../stores/GroupStore";
@ -41,13 +43,31 @@ import {textualPowerLevel} from '../../../Roles';
import MatrixClientContext from "../../../contexts/MatrixClientContext";
import {RightPanelPhases} from "../../../stores/RightPanelStorePhases";
import EncryptionPanel from "./EncryptionPanel";
import { useAsyncMemo } from '../../../hooks/useAsyncMemo';
import { verifyUser, legacyVerifyUser, verifyDevice } from '../../../verification';
import {useAsyncMemo} from '../../../hooks/useAsyncMemo';
import {legacyVerifyUser, verifyDevice, verifyUser} from '../../../verification';
import {Action} from "../../../dispatcher/actions";
import {useIsEncrypted} from "../../../hooks/useIsEncrypted";
import BaseCard from "./BaseCard";
import {E2EStatus} from "../../../utils/ShieldUtils";
import ImageView from "../elements/ImageView";
import Spinner from "../elements/Spinner";
import IconButton from "../elements/IconButton";
import PowerSelector from "../elements/PowerSelector";
import MemberAvatar from "../avatars/MemberAvatar";
import PresenceLabel from "../rooms/PresenceLabel";
import ShareDialog from "../dialogs/ShareDialog";
import ErrorDialog from "../dialogs/ErrorDialog";
import QuestionDialog from "../dialogs/QuestionDialog";
import ConfirmUserActionDialog from "../dialogs/ConfirmUserActionDialog";
import InfoDialog from "../dialogs/InfoDialog";
const _disambiguateDevices = (devices) => {
interface IDevice {
deviceId: string;
ambiguous?: boolean;
getDisplayName(): string;
}
const disambiguateDevices = (devices: IDevice[]) => {
const names = Object.create(null);
for (let i = 0; i < devices.length; i++) {
const name = devices[i].getDisplayName();
@ -64,11 +84,11 @@ const _disambiguateDevices = (devices) => {
}
};
export const getE2EStatus = (cli, userId, devices) => {
export const getE2EStatus = (cli: MatrixClient, userId: string, devices: IDevice[]): E2EStatus => {
const isMe = userId === cli.getUserId();
const userTrust = cli.checkUserTrust(userId);
if (!userTrust.isCrossSigningVerified()) {
return userTrust.wasCrossSigningVerified() ? "warning" : "normal";
return userTrust.wasCrossSigningVerified() ? E2EStatus.Warning : E2EStatus.Normal;
}
const anyDeviceUnverified = devices.some(device => {
@ -81,10 +101,10 @@ export const getE2EStatus = (cli, userId, devices) => {
const deviceTrust = cli.checkDeviceTrust(userId, deviceId);
return isMe ? !deviceTrust.isCrossSigningVerified() : !deviceTrust.isVerified();
});
return anyDeviceUnverified ? "warning" : "verified";
return anyDeviceUnverified ? E2EStatus.Warning : E2EStatus.Verified;
};
async function openDMForUser(matrixClient, userId) {
async function openDMForUser(matrixClient: MatrixClient, userId: string) {
const dmRooms = DMRoomMap.shared().getDMRoomsForUserId(userId);
const lastActiveRoom = dmRooms.reduce((lastActiveRoom, roomId) => {
const room = matrixClient.getRoom(roomId);
@ -107,6 +127,7 @@ async function openDMForUser(matrixClient, userId) {
const createRoomOptions = {
dmUserId: userId,
encryption: undefined,
};
if (privateShouldBeEncrypted()) {
@ -122,10 +143,12 @@ async function openDMForUser(matrixClient, userId) {
}
}
createRoom(createRoomOptions);
return createRoom(createRoomOptions);
}
function useHasCrossSigningKeys(cli, member, canVerify, setUpdating) {
type SetUpdating = (updating: boolean) => void;
function useHasCrossSigningKeys(cli: MatrixClient, member: RoomMember, canVerify: boolean, setUpdating: SetUpdating) {
return useAsyncMemo(async () => {
if (!canVerify) {
return undefined;
@ -142,7 +165,7 @@ function useHasCrossSigningKeys(cli, member, canVerify, setUpdating) {
}, [cli, member, canVerify], undefined);
}
function DeviceItem({userId, device}) {
function DeviceItem({userId, device}: {userId: string, device: IDevice}) {
const cli = useContext(MatrixClientContext);
const isMe = userId === cli.getUserId();
const deviceTrust = cli.checkDeviceTrust(userId, device.deviceId);
@ -169,8 +192,8 @@ function DeviceItem({userId, device}) {
};
const deviceName = device.ambiguous ?
(device.getDisplayName() ? device.getDisplayName() : "") + " (" + device.deviceId + ")" :
device.getDisplayName();
(device.getDisplayName() ? device.getDisplayName() : "") + " (" + device.deviceId + ")" :
device.getDisplayName();
let trustedLabel = null;
if (userTrust.isVerified()) trustedLabel = isVerified ? _t("Trusted") : _t("Not trusted");
@ -198,8 +221,7 @@ function DeviceItem({userId, device}) {
}
}
function DevicesSection({devices, userId, loading}) {
const Spinner = sdk.getComponent("elements.Spinner");
function DevicesSection({devices, userId, loading}: {devices: IDevice[], userId: string, loading: boolean}) {
const cli = useContext(MatrixClientContext);
const userTrust = cli.checkUserTrust(userId);
@ -210,7 +232,7 @@ function DevicesSection({devices, userId, loading}) {
return <Spinner />;
}
if (devices === null) {
return _t("Unable to load session list");
return <>{_t("Unable to load session list")}</>;
}
const isMe = userId === cli.getUserId();
const deviceTrusts = devices.map(d => cli.checkDeviceTrust(userId, d.deviceId));
@ -285,7 +307,11 @@ function DevicesSection({devices, userId, loading}) {
);
}
const UserOptionsSection = ({member, isIgnored, canInvite, devices}) => {
const UserOptionsSection: React.FC<{
member: RoomMember;
isIgnored: boolean;
canInvite: boolean;
}> = ({member, isIgnored, canInvite}) => {
const cli = useContext(MatrixClientContext);
let ignoreButton = null;
@ -296,7 +322,6 @@ const UserOptionsSection = ({member, isIgnored, canInvite, devices}) => {
const isMe = member.userId === cli.getUserId();
const onShareUserClick = () => {
const ShareDialog = sdk.getComponent("dialogs.ShareDialog");
Modal.createTrackedDialog('share room member dialog', '', ShareDialog, {
target: member,
});
@ -318,7 +343,10 @@ const UserOptionsSection = ({member, isIgnored, canInvite, devices}) => {
};
ignoreButton = (
<AccessibleButton onClick={onIgnoreToggle} className={classNames("mx_UserInfo_field", {mx_UserInfo_destructive: !isIgnored})}>
<AccessibleButton
onClick={onIgnoreToggle}
className={classNames("mx_UserInfo_field", {mx_UserInfo_destructive: !isIgnored})}
>
{ isIgnored ? _t("Unignore") : _t("Ignore") }
</AccessibleButton>
);
@ -341,11 +369,14 @@ const UserOptionsSection = ({member, isIgnored, canInvite, devices}) => {
});
};
readReceiptButton = (
<AccessibleButton onClick={onReadReceiptButton} className="mx_UserInfo_field">
{ _t('Jump to read receipt') }
</AccessibleButton>
);
const room = cli.getRoom(member.roomId);
if (room?.getEventReadUpTo(member.userId)) {
readReceiptButton = (
<AccessibleButton onClick={onReadReceiptButton} className="mx_UserInfo_field">
{ _t('Jump to read receipt') }
</AccessibleButton>
);
}
insertPillButton = (
<AccessibleButton onClick={onInsertPillButton} className={"mx_UserInfo_field"}>
@ -367,7 +398,6 @@ const UserOptionsSection = ({member, isIgnored, canInvite, devices}) => {
}
});
} catch (err) {
const ErrorDialog = sdk.getComponent('dialogs.ErrorDialog');
Modal.createTrackedDialog('Failed to invite', '', ErrorDialog, {
title: _t('Failed to invite'),
description: ((err && err.message) ? err.message : _t("Operation failed")),
@ -413,8 +443,7 @@ const UserOptionsSection = ({member, isIgnored, canInvite, devices}) => {
);
};
const _warnSelfDemote = async () => {
const QuestionDialog = sdk.getComponent("dialogs.QuestionDialog");
const warnSelfDemote = async () => {
const {finished} = Modal.createTrackedDialog('Demoting Self', '', QuestionDialog, {
title: _t("Demote yourself?"),
description:
@ -430,7 +459,7 @@ const _warnSelfDemote = async () => {
return confirmed;
};
const GenericAdminToolsContainer = ({children}) => {
const GenericAdminToolsContainer: React.FC<{}> = ({children}) => {
return (
<div className="mx_UserInfo_container">
<h3>{ _t("Admin Tools") }</h3>
@ -441,7 +470,20 @@ const GenericAdminToolsContainer = ({children}) => {
);
};
const _isMuted = (member, powerLevelContent) => {
interface IPowerLevelsContent {
events?: Record<string, number>;
// eslint-disable-next-line camelcase
users_default?: number;
// eslint-disable-next-line camelcase
events_default?: number;
// eslint-disable-next-line camelcase
state_default?: number;
ban?: number;
kick?: number;
redact?: number;
}
const isMuted = (member: RoomMember, powerLevelContent: IPowerLevelsContent) => {
if (!powerLevelContent || !member) return false;
const levelToSend = (
@ -451,8 +493,8 @@ const _isMuted = (member, powerLevelContent) => {
return member.powerLevel < levelToSend;
};
export const useRoomPowerLevels = (cli, room) => {
const [powerLevels, setPowerLevels] = useState({});
export const useRoomPowerLevels = (cli: MatrixClient, room: Room) => {
const [powerLevels, setPowerLevels] = useState<IPowerLevelsContent>({});
const update = useCallback(() => {
if (!room) {
@ -479,14 +521,19 @@ export const useRoomPowerLevels = (cli, room) => {
return powerLevels;
};
const RoomKickButton = ({member, startUpdating, stopUpdating}) => {
interface IBaseProps {
member: RoomMember;
startUpdating(): void;
stopUpdating(): void;
}
const RoomKickButton: React.FC<IBaseProps> = ({member, startUpdating, stopUpdating}) => {
const cli = useContext(MatrixClientContext);
// check if user can be kicked/disinvited
if (member.membership !== "invite" && member.membership !== "join") return null;
const onKick = async () => {
const ConfirmUserActionDialog = sdk.getComponent("dialogs.ConfirmUserActionDialog");
const {finished} = Modal.createTrackedDialog(
'Confirm User Action Dialog',
'onKick',
@ -509,7 +556,6 @@ const RoomKickButton = ({member, startUpdating, stopUpdating}) => {
// get out of sync if we force setState here!
console.log("Kick success");
}, function(err) {
const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog");
console.error("Kick error: " + err);
Modal.createTrackedDialog('Failed to kick', '', ErrorDialog, {
title: _t("Failed to kick"),
@ -526,7 +572,7 @@ const RoomKickButton = ({member, startUpdating, stopUpdating}) => {
</AccessibleButton>;
};
const RedactMessagesButton = ({member}) => {
const RedactMessagesButton: React.FC<IBaseProps> = ({member}) => {
const cli = useContext(MatrixClientContext);
const onRedactAllMessages = async () => {
@ -554,7 +600,6 @@ const RedactMessagesButton = ({member}) => {
const user = member.name;
if (count === 0) {
const InfoDialog = sdk.getComponent("dialogs.InfoDialog");
Modal.createTrackedDialog('No user messages found to remove', '', InfoDialog, {
title: _t("No recent messages by %(user)s found", {user}),
description:
@ -563,14 +608,14 @@ const RedactMessagesButton = ({member}) => {
</div>,
});
} else {
const QuestionDialog = sdk.getComponent("dialogs.QuestionDialog");
const {finished} = Modal.createTrackedDialog('Remove recent messages by user', '', QuestionDialog, {
title: _t("Remove recent messages by %(user)s", {user}),
description:
<div>
<p>{ _t("You are about to remove %(count)s messages by %(user)s. This cannot be undone. Do you wish to continue?", {count, user}) }</p>
<p>{ _t("For a large amount of messages, this might take some time. Please don't refresh your client in the meantime.") }</p>
<p>{ _t("You are about to remove %(count)s messages by %(user)s. " +
"This cannot be undone. Do you wish to continue?", {count, user}) }</p>
<p>{ _t("For a large amount of messages, this might take some time. " +
"Please don't refresh your client in the meantime.") }</p>
</div>,
button: _t("Remove %(count)s messages", {count}),
});
@ -603,11 +648,10 @@ const RedactMessagesButton = ({member}) => {
</AccessibleButton>;
};
const BanToggleButton = ({member, startUpdating, stopUpdating}) => {
const BanToggleButton: React.FC<IBaseProps> = ({member, startUpdating, stopUpdating}) => {
const cli = useContext(MatrixClientContext);
const onBanOrUnban = async () => {
const ConfirmUserActionDialog = sdk.getComponent("dialogs.ConfirmUserActionDialog");
const {finished} = Modal.createTrackedDialog(
'Confirm User Action Dialog',
'onBanOrUnban',
@ -636,7 +680,6 @@ const BanToggleButton = ({member, startUpdating, stopUpdating}) => {
// get out of sync if we force setState here!
console.log("Ban success");
}, function(err) {
const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog");
console.error("Ban error: " + err);
Modal.createTrackedDialog('Failed to ban user', '', ErrorDialog, {
title: _t("Error"),
@ -661,22 +704,26 @@ const BanToggleButton = ({member, startUpdating, stopUpdating}) => {
</AccessibleButton>;
};
const MuteToggleButton = ({member, room, powerLevels, startUpdating, stopUpdating}) => {
interface IBaseRoomProps extends IBaseProps {
room: Room;
powerLevels: IPowerLevelsContent;
}
const MuteToggleButton: React.FC<IBaseRoomProps> = ({member, room, powerLevels, startUpdating, stopUpdating}) => {
const cli = useContext(MatrixClientContext);
// Don't show the mute/unmute option if the user is not in the room
if (member.membership !== "join") return null;
const isMuted = _isMuted(member, powerLevels);
const muted = isMuted(member, powerLevels);
const onMuteToggle = async () => {
const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog");
const roomId = member.roomId;
const target = member.userId;
// if muting self, warn as it may be irreversible
if (target === cli.getUserId()) {
try {
if (!(await _warnSelfDemote())) return;
if (!(await warnSelfDemote())) return;
} catch (e) {
console.error("Failed to warn about self demotion: ", e);
return;
@ -692,7 +739,7 @@ const MuteToggleButton = ({member, room, powerLevels, startUpdating, stopUpdatin
powerLevels.events_default
);
let level;
if (isMuted) { // unmute
if (muted) { // unmute
level = levelToSend;
} else { // mute
level = levelToSend - 1;
@ -718,16 +765,23 @@ const MuteToggleButton = ({member, room, powerLevels, startUpdating, stopUpdatin
};
const classes = classNames("mx_UserInfo_field", {
mx_UserInfo_destructive: !isMuted,
mx_UserInfo_destructive: !muted,
});
const muteLabel = isMuted ? _t("Unmute") : _t("Mute");
const muteLabel = muted ? _t("Unmute") : _t("Mute");
return <AccessibleButton className={classes} onClick={onMuteToggle}>
{ muteLabel }
</AccessibleButton>;
};
const RoomAdminToolsContainer = ({room, children, member, startUpdating, stopUpdating, powerLevels}) => {
const RoomAdminToolsContainer: React.FC<IBaseRoomProps> = ({
room,
children,
member,
startUpdating,
stopUpdating,
powerLevels,
}) => {
const cli = useContext(MatrixClientContext);
let kickButton;
let banButton;
@ -786,7 +840,18 @@ const RoomAdminToolsContainer = ({room, children, member, startUpdating, stopUpd
return <div />;
};
const GroupAdminToolsSection = ({children, groupId, groupMember, startUpdating, stopUpdating}) => {
interface GroupMember {
userId: string;
displayname?: string; // XXX: GroupMember objects are inconsistent :((
avatarUrl?: string;
}
const GroupAdminToolsSection: React.FC<{
groupId: string;
groupMember: GroupMember;
startUpdating(): void;
stopUpdating(): void;
}> = ({children, groupId, groupMember, startUpdating, stopUpdating}) => {
const cli = useContext(MatrixClientContext);
const [isPrivileged, setIsPrivileged] = useState(false);
@ -814,8 +879,7 @@ const GroupAdminToolsSection = ({children, groupId, groupMember, startUpdating,
}, [groupId, groupMember.userId]);
if (isPrivileged) {
const _onKick = async () => {
const ConfirmUserActionDialog = sdk.getComponent("dialogs.ConfirmUserActionDialog");
const onKick = async () => {
const {finished} = Modal.createDialog(ConfirmUserActionDialog, {
matrixClient: cli,
groupMember,
@ -836,7 +900,6 @@ const GroupAdminToolsSection = ({children, groupId, groupMember, startUpdating,
member: null,
});
}).catch((e) => {
const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog");
Modal.createTrackedDialog('Failed to remove user from group', '', ErrorDialog, {
title: _t('Error'),
description: isInvited ?
@ -850,7 +913,7 @@ const GroupAdminToolsSection = ({children, groupId, groupMember, startUpdating,
};
const kickButton = (
<AccessibleButton className="mx_UserInfo_field mx_UserInfo_destructive" onClick={_onKick}>
<AccessibleButton className="mx_UserInfo_field mx_UserInfo_destructive" onClick={onKick}>
{ isInvited ? _t('Disinvite') : _t('Remove from community') }
</AccessibleButton>
);
@ -870,13 +933,7 @@ const GroupAdminToolsSection = ({children, groupId, groupMember, startUpdating,
return <div />;
};
const GroupMember = PropTypes.shape({
userId: PropTypes.string.isRequired,
displayname: PropTypes.string, // XXX: GroupMember objects are inconsistent :((
avatarUrl: PropTypes.string,
});
const useIsSynapseAdmin = (cli) => {
const useIsSynapseAdmin = (cli: MatrixClient) => {
const [isAdmin, setIsAdmin] = useState(false);
useEffect(() => {
cli.isSynapseAdministrator().then((isAdmin) => {
@ -888,14 +945,20 @@ const useIsSynapseAdmin = (cli) => {
return isAdmin;
};
const useHomeserverSupportsCrossSigning = (cli) => {
return useAsyncMemo(async () => {
const useHomeserverSupportsCrossSigning = (cli: MatrixClient) => {
return useAsyncMemo<boolean>(async () => {
return cli.doesServerSupportUnstableFeature("org.matrix.e2e_cross_signing");
}, [cli], false);
};
function useRoomPermissions(cli, room, user) {
const [roomPermissions, setRoomPermissions] = useState({
interface IRoomPermissions {
modifyLevelMax: number;
canEdit: boolean;
canInvite: boolean;
}
function useRoomPermissions(cli: MatrixClient, room: Room, user: User): IRoomPermissions {
const [roomPermissions, setRoomPermissions] = useState<IRoomPermissions>({
// modifyLevelMax is the max PL we can set this user to, typically min(their PL, our PL) && canSetPL
modifyLevelMax: -1,
canEdit: false,
@ -940,7 +1003,7 @@ function useRoomPermissions(cli, room, user) {
updateRoomPermissions();
return () => {
setRoomPermissions({
maximalPowerLevel: -1,
modifyLevelMax: -1,
canEdit: false,
canInvite: false,
});
@ -950,14 +1013,18 @@ function useRoomPermissions(cli, room, user) {
return roomPermissions;
}
const PowerLevelSection = ({user, room, roomPermissions, powerLevels}) => {
const PowerLevelSection: React.FC<{
user: User;
room: Room;
roomPermissions: IRoomPermissions;
powerLevels: IPowerLevelsContent;
}> = ({user, room, roomPermissions, powerLevels}) => {
const [isEditing, setEditing] = useState(false);
if (isEditing) {
return (<PowerLevelEditor
user={user} room={room} roomPermissions={roomPermissions}
onFinished={() => setEditing(false)} />);
} else {
const IconButton = sdk.getComponent('elements.IconButton');
const powerLevelUsersDefault = powerLevels.users_default || 0;
const powerLevel = parseInt(user.powerLevel, 10);
const modifyButton = roomPermissions.canEdit ?
@ -975,7 +1042,12 @@ const PowerLevelSection = ({user, room, roomPermissions, powerLevels}) => {
}
};
const PowerLevelEditor = ({user, room, roomPermissions, onFinished}) => {
const PowerLevelEditor: React.FC<{
user: User;
room: Room;
roomPermissions: IRoomPermissions;
onFinished(): void;
}> = ({user, room, roomPermissions, onFinished}) => {
const cli = useContext(MatrixClientContext);
const [isUpdating, setIsUpdating] = useState(false);
@ -994,7 +1066,6 @@ const PowerLevelEditor = ({user, room, roomPermissions, onFinished}) => {
// get out of sync if we force setState here!
console.log("Power change success");
}, function(err) {
const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog");
console.error("Failed to change power level " + err);
Modal.createTrackedDialog('Failed to change power level', '', ErrorDialog, {
title: _t("Error"),
@ -1025,12 +1096,10 @@ const PowerLevelEditor = ({user, room, roomPermissions, onFinished}) => {
}
const myUserId = cli.getUserId();
const QuestionDialog = sdk.getComponent("dialogs.QuestionDialog");
// If we are changing our own PL it can only ever be decreasing, which we cannot reverse.
if (myUserId === target) {
try {
if (!(await _warnSelfDemote())) return;
if (!(await warnSelfDemote())) return;
} catch (e) {
console.error("Failed to warn about self demotion: ", e);
}
@ -1039,7 +1108,7 @@ const PowerLevelEditor = ({user, room, roomPermissions, onFinished}) => {
}
const myPower = powerLevelEvent.getContent().users[myUserId];
if (parseInt(myPower) === parseInt(powerLevel)) {
if (parseInt(myPower) === powerLevel) {
const {finished} = Modal.createTrackedDialog('Promote to PL100 Warning', '', QuestionDialog, {
title: _t("Warning!"),
description:
@ -1062,12 +1131,9 @@ const PowerLevelEditor = ({user, room, roomPermissions, onFinished}) => {
const powerLevelEvent = room.currentState.getStateEvents("m.room.power_levels", "");
const powerLevelUsersDefault = powerLevelEvent ? powerLevelEvent.getContent().users_default : 0;
const IconButton = sdk.getComponent('elements.IconButton');
const Spinner = sdk.getComponent("elements.Spinner");
const buttonOrSpinner = isUpdating ? <Spinner w={16} h={16} /> :
<IconButton icon="check" onClick={changePowerLevel} />;
const PowerSelector = sdk.getComponent('elements.PowerSelector');
return (
<div className="mx_UserInfo_profileField">
<PowerSelector
@ -1083,7 +1149,7 @@ const PowerLevelEditor = ({user, room, roomPermissions, onFinished}) => {
);
};
export const useDevices = (userId) => {
export const useDevices = (userId: string) => {
const cli = useContext(MatrixClientContext);
// undefined means yet to be loaded, null means failed to load, otherwise list of devices
@ -1094,7 +1160,7 @@ export const useDevices = (userId) => {
let cancelled = false;
async function _downloadDeviceList() {
async function downloadDeviceList() {
try {
await cli.downloadKeys([userId], true);
const devices = cli.getStoredDevicesForUser(userId);
@ -1104,13 +1170,13 @@ export const useDevices = (userId) => {
return;
}
_disambiguateDevices(devices);
disambiguateDevices(devices);
setDevices(devices);
} catch (err) {
setDevices(null);
}
}
_downloadDeviceList();
downloadDeviceList();
// Handle being unmounted
return () => {
@ -1153,7 +1219,13 @@ export const useDevices = (userId) => {
return devices;
};
const BasicUserInfo = ({room, member, groupId, devices, isRoomEncrypted}) => {
const BasicUserInfo: React.FC<{
room: Room;
member: User | RoomMember;
groupId: string;
devices: IDevice[];
isRoomEncrypted: boolean;
}> = ({room, member, groupId, devices, isRoomEncrypted}) => {
const cli = useContext(MatrixClientContext);
const powerLevels = useRoomPowerLevels(cli, room);
@ -1186,7 +1258,6 @@ const BasicUserInfo = ({room, member, groupId, devices, isRoomEncrypted}) => {
const roomPermissions = useRoomPermissions(cli, room, member);
const onSynapseDeactivate = useCallback(async () => {
const QuestionDialog = sdk.getComponent('views.dialogs.QuestionDialog');
const {finished} = Modal.createTrackedDialog('Synapse User Deactivation', '', QuestionDialog, {
title: _t("Deactivate user?"),
description:
@ -1207,7 +1278,6 @@ const BasicUserInfo = ({room, member, groupId, devices, isRoomEncrypted}) => {
console.error("Failed to deactivate user");
console.error(err);
const ErrorDialog = sdk.getComponent('dialogs.ErrorDialog');
Modal.createTrackedDialog('Failed to deactivate Synapse user', '', ErrorDialog, {
title: _t('Failed to deactivate user'),
description: ((err && err.message) ? err.message : _t("Operation failed")),
@ -1260,8 +1330,7 @@ const BasicUserInfo = ({room, member, groupId, devices, isRoomEncrypted}) => {
}
if (pendingUpdateCount > 0) {
const Loader = sdk.getComponent("elements.Spinner");
spinner = <Loader imgClassName="mx_ContextualMenu_spinner" />;
spinner = <Spinner imgClassName="mx_ContextualMenu_spinner" />;
}
let memberDetails;
@ -1296,7 +1365,8 @@ const BasicUserInfo = ({room, member, groupId, devices, isRoomEncrypted}) => {
const userTrust = cryptoEnabled && cli.checkUserTrust(member.userId);
const userVerified = cryptoEnabled && userTrust.isCrossSigningVerified();
const isMe = member.userId === cli.getUserId();
const canVerify = cryptoEnabled && homeserverSupportsCrossSigning && !userVerified && !isMe;
const canVerify = cryptoEnabled && homeserverSupportsCrossSigning && !userVerified && !isMe &&
devices && devices.length > 0;
const setUpdating = (updating) => {
setPendingUpdateCount(count => count + (updating ? 1 : -1));
@ -1323,7 +1393,6 @@ const BasicUserInfo = ({room, member, groupId, devices, isRoomEncrypted}) => {
// HACK: only show a spinner if the device section spinner is not shown,
// to avoid showing a double spinner
// We should ask for a design that includes all the different loading states here
const Spinner = sdk.getComponent('elements.Spinner');
verifyButton = <Spinner />;
}
}
@ -1350,7 +1419,6 @@ const BasicUserInfo = ({room, member, groupId, devices, isRoomEncrypted}) => {
{ securitySection }
<UserOptionsSection
devices={devices}
canInvite={roomPermissions.canInvite}
isIgnored={isIgnored}
member={member} />
@ -1361,7 +1429,12 @@ const BasicUserInfo = ({room, member, groupId, devices, isRoomEncrypted}) => {
</React.Fragment>;
};
const UserInfoHeader = ({member, e2eStatus}) => {
type Member = User | RoomMember | GroupMember;
const UserInfoHeader: React.FC<{
member: Member;
e2eStatus: E2EStatus;
}> = ({member, e2eStatus}) => {
const cli = useContext(MatrixClientContext);
const onMemberAvatarClick = useCallback(() => {
@ -1369,7 +1442,6 @@ const UserInfoHeader = ({member, e2eStatus}) => {
if (!avatarUrl) return;
const httpUrl = cli.mxcUrlToHttp(avatarUrl);
const ImageView = sdk.getComponent("elements.ImageView");
const params = {
src: httpUrl,
name: member.name,
@ -1378,7 +1450,6 @@ const UserInfoHeader = ({member, e2eStatus}) => {
Modal.createDialog(ImageView, params, "mx_Dialog_lightbox");
}, [cli, member]);
const MemberAvatar = sdk.getComponent('avatars.MemberAvatar');
const avatarElement = (
<div className="mx_UserInfo_avatar">
<div>
@ -1420,10 +1491,13 @@ const UserInfoHeader = ({member, e2eStatus}) => {
let presenceLabel = null;
if (showPresence) {
const PresenceLabel = sdk.getComponent('rooms.PresenceLabel');
presenceLabel = <PresenceLabel activeAgo={presenceLastActiveAgo}
currentlyActive={presenceCurrentlyActive}
presenceState={presenceState} />;
presenceLabel = (
<PresenceLabel
activeAgo={presenceLastActiveAgo}
currentlyActive={presenceCurrentlyActive}
presenceState={presenceState}
/>
);
}
let statusLabel = null;
@ -1460,7 +1534,32 @@ const UserInfoHeader = ({member, e2eStatus}) => {
</React.Fragment>;
};
const UserInfo = ({user, groupId, room, onClose, phase=RightPanelPhases.RoomMemberInfo, ...props}) => {
interface IProps {
user: Member;
groupId?: string;
room?: Room;
phase: RightPanelPhases.RoomMemberInfo | RightPanelPhases.GroupMemberInfo;
onClose(): void;
}
interface IPropsWithEncryptionPanel extends React.ComponentProps<typeof EncryptionPanel> {
user: Member;
groupId: void;
room: Room;
phase: RightPanelPhases.EncryptionPanel;
onClose(): void;
}
type Props = IProps | IPropsWithEncryptionPanel;
const UserInfo: React.FC<Props> = ({
user,
groupId,
room,
onClose,
phase = RightPanelPhases.RoomMemberInfo,
...props
}) => {
const cli = useContext(MatrixClientContext);
// fetch latest room member if we have a room, so we don't show historical information, falling back to user
@ -1484,7 +1583,7 @@ const UserInfo = ({user, groupId, room, onClose, phase=RightPanelPhases.RoomMemb
<BasicUserInfo
room={room}
member={member}
groupId={groupId}
groupId={groupId as string}
devices={devices}
isRoomEncrypted={isRoomEncrypted} />
);
@ -1492,7 +1591,12 @@ const UserInfo = ({user, groupId, room, onClose, phase=RightPanelPhases.RoomMemb
case RightPanelPhases.EncryptionPanel:
classes.push("mx_UserInfo_smallAvatar");
content = (
<EncryptionPanel {...props} member={member} onClose={onClose} isRoomEncrypted={isRoomEncrypted} />
<EncryptionPanel
{...props as React.ComponentProps<typeof EncryptionPanel>}
member={member}
onClose={onClose}
isRoomEncrypted={isRoomEncrypted}
/>
);
break;
}
@ -1503,23 +1607,24 @@ const UserInfo = ({user, groupId, room, onClose, phase=RightPanelPhases.RoomMemb
previousPhase = RightPanelPhases.RoomMemberList;
}
const header = <UserInfoHeader member={member} e2eStatus={e2eStatus} onClose={onClose} />;
return <BaseCard className={classes.join(" ")} header={header} onClose={onClose} previousPhase={previousPhase}>
let closeLabel = undefined;
if (phase === RightPanelPhases.EncryptionPanel) {
const verificationRequest = (props as React.ComponentProps<typeof EncryptionPanel>).verificationRequest;
if (verificationRequest && verificationRequest.pending) {
closeLabel = _t("Cancel");
}
}
const header = <UserInfoHeader member={member} e2eStatus={e2eStatus} />;
return <BaseCard
className={classes.join(" ")}
header={header}
onClose={onClose}
closeLabel={closeLabel}
previousPhase={previousPhase}
>
{ content }
</BaseCard>;
};
UserInfo.propTypes = {
user: PropTypes.oneOfType([
PropTypes.instanceOf(User),
PropTypes.instanceOf(RoomMember),
GroupMember,
]).isRequired,
group: PropTypes.instanceOf(Group),
groupId: PropTypes.string,
room: PropTypes.instanceOf(Room),
onClose: PropTypes.func,
};
export default UserInfo;

View file

@ -29,16 +29,17 @@ import defaultDispatcher from "../../../dispatcher/dispatcher";
import {SetRightPanelPhasePayload} from "../../../dispatcher/payloads/SetRightPanelPhasePayload";
import {Action} from "../../../dispatcher/actions";
import WidgetStore from "../../../stores/WidgetStore";
import ActiveWidgetStore from "../../../stores/ActiveWidgetStore";
import {ChevronFace, ContextMenuButton, useContextMenu} from "../../structures/ContextMenu";
import IconizedContextMenu, {
IconizedContextMenuOption,
IconizedContextMenuOptionList,
} from "../context_menus/IconizedContextMenu";
import {AppTileActionPayload} from "../../../dispatcher/payloads/AppTileActionPayload";
import {Capability} from "../../../widgets/WidgetApi";
import AccessibleTooltipButton from "../elements/AccessibleTooltipButton";
import classNames from "classnames";
import dis from "../../../dispatcher/dispatcher";
import { WidgetMessagingStore } from "../../../stores/widgets/WidgetMessagingStore";
import { MatrixCapabilities } from "matrix-widget-api";
interface IProps {
room: Room;
@ -77,9 +78,17 @@ const WidgetCard: React.FC<IProps> = ({ room, widgetId, onClose }) => {
let contextMenu;
if (menuDisplayed) {
let snapshotButton;
if (ActiveWidgetStore.widgetHasCapability(app.id, Capability.Screenshot)) {
const widgetMessaging = WidgetMessagingStore.instance.getMessagingForId(app.id);
if (widgetMessaging?.hasCapability(MatrixCapabilities.Screenshots)) {
const onSnapshotClick = () => {
WidgetUtils.snapshotWidget(app);
widgetMessaging.takeScreenshot().then(data => {
dis.dispatch({
action: 'picture_snapshot',
file: data.screenshot,
});
}).catch(err => {
console.error("Failed to take screenshot: ", err);
});
closeMenu();
};

View file

@ -75,6 +75,15 @@ export default class RoomProfileSettings extends React.Component {
});
};
_clearProfile = async (e) => {
e.stopPropagation();
e.preventDefault();
if (!this.state.enableProfileSave) return;
this._removeAvatar();
this.setState({enableProfileSave: false, displayName: this.state.originalDisplayName});
};
_saveProfile = async (e) => {
e.stopPropagation();
e.preventDefault();
@ -150,7 +159,12 @@ export default class RoomProfileSettings extends React.Component {
const AccessibleButton = sdk.getComponent('elements.AccessibleButton');
const AvatarSetting = sdk.getComponent('settings.AvatarSetting');
return (
<form onSubmit={this._saveProfile} autoComplete="off" noValidate={true}>
<form
onSubmit={this._saveProfile}
autoComplete="off"
noValidate={true}
className="mx_ProfileSettings_profileForm"
>
<input type="file" ref={this._avatarUpload} className="mx_ProfileSettings_avatarUpload"
onChange={this._onAvatarChanged} accept="image/*" />
<div className="mx_ProfileSettings_profile">
@ -169,10 +183,22 @@ export default class RoomProfileSettings extends React.Component {
uploadAvatar={this.state.canSetAvatar ? this._uploadAvatar : undefined}
removeAvatar={this.state.canSetAvatar ? this._removeAvatar : undefined} />
</div>
<AccessibleButton onClick={this._saveProfile} kind="primary"
disabled={!this.state.enableProfileSave}>
{_t("Save")}
</AccessibleButton>
<div className="mx_ProfileSettings_buttons">
<AccessibleButton
onClick={this._clearProfile}
kind="link"
disabled={!this.state.enableProfileSave}
>
{_t("Cancel")}
</AccessibleButton>
<AccessibleButton
onClick={this._saveProfile}
kind="primary"
disabled={!this.state.enableProfileSave}
>
{_t("Save")}
</AccessibleButton>
</div>
</form>
);
}

View file

@ -39,15 +39,9 @@ export default class AuxPanel extends React.Component {
showApps: PropTypes.bool, // Render apps
hideAppsDrawer: PropTypes.bool, // Do not display apps drawer and content (may still be rendered)
// Conference Handler implementation
conferenceHandler: PropTypes.object,
// set to true to show the file drop target
draggingFile: PropTypes.bool,
// set to true to show the 'active conf call' banner
displayConfCallNotification: PropTypes.bool,
// maxHeight attribute for the aux panel and the video
// therein
maxHeight: PropTypes.number,
@ -161,39 +155,9 @@ export default class AuxPanel extends React.Component {
);
}
let conferenceCallNotification = null;
if (this.props.displayConfCallNotification) {
let supportedText = '';
let joinNode;
if (!MatrixClientPeg.get().supportsVoip()) {
supportedText = _t(" (unsupported)");
} else {
joinNode = (<span>
{ _t(
"Join as <voiceText>voice</voiceText> or <videoText>video</videoText>.",
{},
{
'voiceText': (sub) => <a onClick={(event)=>{ this.onConferenceNotificationClick(event, 'voice');}} href="#">{ sub }</a>,
'videoText': (sub) => <a onClick={(event)=>{ this.onConferenceNotificationClick(event, 'video');}} href="#">{ sub }</a>,
},
) }
</span>);
}
// XXX: the translation here isn't great: appending ' (unsupported)' is likely to not make sense in many languages,
// but there are translations for this in the languages we do have so I'm leaving it for now.
conferenceCallNotification = (
<div className="mx_RoomView_ongoingConfCallNotification">
{ _t("Ongoing conference call%(supportedText)s.", {supportedText: supportedText}) }
&nbsp;
{ joinNode }
</div>
);
}
const callView = (
<CallView
room={this.props.room}
ConferenceHandler={this.props.conferenceHandler}
onResize={this.props.onResize}
maxVideoHeight={this.props.maxHeight}
/>
@ -276,7 +240,6 @@ export default class AuxPanel extends React.Component {
{ appsDrawer }
{ fileDropTarget }
{ callView }
{ conferenceCallNotification }
{ this.props.children }
</AutoHideScrollbar>
);

View file

@ -92,7 +92,7 @@ interface IProps {
label?: string;
initialCaret?: DocumentOffset;
onChange();
onChange?();
onPaste?(event: ClipboardEvent<HTMLDivElement>, model: EditorModel): boolean;
}
@ -619,13 +619,14 @@ export default class BasicMessageEditor extends React.Component<IProps, IState>
}
private onFormatAction = (action: Formatting) => {
const range = getRangeForSelection(
this.editorRef.current,
this.props.model,
document.getSelection());
const range = getRangeForSelection(this.editorRef.current, this.props.model, document.getSelection());
// trim the range as we want it to exclude leading/trailing spaces
range.trim();
if (range.length === 0) {
return;
}
this.historyManager.ensureLastChangesPushed(this.props.model);
this.modifiedFlag = true;
switch (action) {

View file

@ -34,6 +34,7 @@ import * as ObjectUtils from "../../../ObjectUtils";
import MatrixClientContext from "../../../contexts/MatrixClientContext";
import {E2E_STATE} from "./E2EIcon";
import {toRem} from "../../../utils/units";
import {WidgetType} from "../../../widgets/WidgetType";
import RoomAvatar from "../avatars/RoomAvatar";
const eventTileTypes = {
@ -111,6 +112,19 @@ export function getHandlerTile(ev) {
}
}
// TODO: Enable support for m.widget event type (https://github.com/vector-im/element-web/issues/13111)
if (type === "im.vector.modular.widgets") {
let type = ev.getContent()['type'];
if (!type) {
// deleted/invalid widget - try the past widget type
type = ev.getPrevContent()['type'];
}
if (WidgetType.JITSI.matches(type)) {
return "messages.MJitsiWidgetEvent";
}
}
return ev.isState() ? stateEventTileTypes[type] : eventTileTypes[type];
}
@ -627,16 +641,18 @@ export default class EventTile extends React.Component {
const msgtype = content.msgtype;
const eventType = this.props.mxEvent.getType();
let tileHandler = getHandlerTile(this.props.mxEvent);
// Info messages are basically information about commands processed on a room
const isBubbleMessage = eventType.startsWith("m.key.verification") ||
(eventType === "m.room.message" && msgtype && msgtype.startsWith("m.key.verification")) ||
(eventType === "m.room.encryption");
(eventType === "m.room.encryption") ||
(tileHandler === "messages.MJitsiWidgetEvent");
let isInfoMessage = (
!isBubbleMessage && eventType !== 'm.room.message' &&
eventType !== 'm.sticker' && eventType !== 'm.room.create'
);
let tileHandler = getHandlerTile(this.props.mxEvent);
// If we're showing hidden events in the timeline, we should use the
// source tile when there's no regular tile for an event and also for
// replace relations (which otherwise would display as a confusing
@ -902,6 +918,7 @@ export default class EventTile extends React.Component {
highlights={this.props.highlights}
highlightLink={this.props.highlightLink}
onHeightChanged={this.props.onHeightChanged}
replacingEventId={this.props.replacingEventId}
showUrlPreview={false} />
</div>
</div>

View file

@ -24,7 +24,6 @@ import {isValid3pidInvite} from "../../../RoomInvite";
import rate_limited_func from "../../../ratelimitedfunc";
import {MatrixClientPeg} from "../../../MatrixClientPeg";
import * as sdk from "../../../index";
import CallHandler from "../../../CallHandler";
import {CommunityPrototypeStore} from "../../../stores/CommunityPrototypeStore";
import BaseCard from "../right_panel/BaseCard";
import {RightPanelPhases} from "../../../stores/RightPanelStorePhases";
@ -122,8 +121,8 @@ export default class MemberList extends React.Component {
this.setState(this._getMembersState(this.roomMembers()));
this._listenForMembersChanges();
}
} else if (membership === "invite") {
// show the members we've got when invited
} else {
// show the members we already have loaded
this.setState(this._getMembersState(this.roomMembers()));
}
}
@ -233,15 +232,10 @@ export default class MemberList extends React.Component {
}
roomMembers() {
const ConferenceHandler = CallHandler.getConferenceHandler();
const allMembers = this.getMembersWithUser();
const filteredAndSortedMembers = allMembers.filter((m) => {
return (
m.membership === 'join' || m.membership === 'invite'
) && (
!ConferenceHandler ||
(ConferenceHandler && !ConferenceHandler.isConferenceUser(m.userId))
);
});
filteredAndSortedMembers.sort(this.memberSort);

View file

@ -1,6 +1,7 @@
/*
Copyright 2015, 2016 OpenMarket Ltd
Copyright 2017, 2018 New Vector Ltd
Copyright 2020 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@ -32,6 +33,10 @@ import {aboveLeftOf, ContextMenu, ContextMenuTooltipButton, useContextMenu} from
import AccessibleTooltipButton from "../elements/AccessibleTooltipButton";
import ReplyPreview from "./ReplyPreview";
import {UIFeature} from "../../../settings/UIFeature";
import WidgetStore from "../../../stores/WidgetStore";
import WidgetUtils from "../../../utils/WidgetUtils";
import {UPDATE_EVENT} from "../../../stores/AsyncStore";
import ActiveWidgetStore from "../../../stores/ActiveWidgetStore";
function ComposerAvatar(props) {
const MemberStatusMessageAvatar = sdk.getComponent('avatars.MemberStatusMessageAvatar');
@ -85,9 +90,16 @@ VideoCallButton.propTypes = {
};
function HangupButton(props) {
const AccessibleButton = sdk.getComponent('elements.AccessibleButton');
const onHangupClick = () => {
const call = CallHandler.getCallForRoom(props.roomId);
if (props.isConference) {
dis.dispatch({
action: props.canEndConference ? 'end_conference' : 'hangup_conference',
room_id: props.roomId,
});
return;
}
const call = CallHandler.sharedInstance().getCallForRoom(props.roomId);
if (!call) {
return;
}
@ -98,14 +110,28 @@ function HangupButton(props) {
room_id: call.roomId,
});
};
return (<AccessibleButton className="mx_MessageComposer_button mx_MessageComposer_hangup"
let tooltip = _t("Hangup");
if (props.isConference && props.canEndConference) {
tooltip = _t("End conference");
}
const canLeaveConference = !props.isConference ? true : props.isInConference;
return (
<AccessibleTooltipButton
className="mx_MessageComposer_button mx_MessageComposer_hangup"
onClick={onHangupClick}
title={_t('Hangup')}
/>);
title={tooltip}
disabled={!canLeaveConference}
/>
);
}
HangupButton.propTypes = {
roomId: PropTypes.string.isRequired,
isConference: PropTypes.bool.isRequired,
canEndConference: PropTypes.bool,
isInConference: PropTypes.bool,
};
const EmojiButton = ({addEmoji}) => {
@ -226,12 +252,17 @@ export default class MessageComposer extends React.Component {
this._onRoomViewStoreUpdate = this._onRoomViewStoreUpdate.bind(this);
this._onTombstoneClick = this._onTombstoneClick.bind(this);
this.renderPlaceholderText = this.renderPlaceholderText.bind(this);
WidgetStore.instance.on(UPDATE_EVENT, this._onWidgetUpdate);
ActiveWidgetStore.on('update', this._onActiveWidgetUpdate);
this._dispatcherRef = null;
this.state = {
isQuoting: Boolean(RoomViewStore.getQuotingEvent()),
replyToEvent: RoomViewStore.getQuotingEvent(),
tombstone: this._getRoomTombstone(),
canSendMessages: this.props.room.maySendMessage(),
showCallButtons: SettingsStore.getValue("showCallButtonsInComposer"),
hasConference: WidgetStore.instance.doesRoomHaveConference(this.props.room),
joinedConference: WidgetStore.instance.isJoinedToConferenceIn(this.props.room),
};
}
@ -247,6 +278,14 @@ export default class MessageComposer extends React.Component {
}
};
_onWidgetUpdate = () => {
this.setState({hasConference: WidgetStore.instance.doesRoomHaveConference(this.props.room)});
};
_onActiveWidgetUpdate = () => {
this.setState({joinedConference: WidgetStore.instance.isJoinedToConferenceIn(this.props.room)});
};
componentDidMount() {
this.dispatcherRef = dis.register(this.onAction);
MatrixClientPeg.get().on("RoomState.events", this._onRoomStateEvents);
@ -277,6 +316,8 @@ export default class MessageComposer extends React.Component {
if (this._roomStoreToken) {
this._roomStoreToken.remove();
}
WidgetStore.instance.removeListener(UPDATE_EVENT, this._onWidgetUpdate);
ActiveWidgetStore.removeListener('update', this._onActiveWidgetUpdate);
dis.unregister(this.dispatcherRef);
}
@ -296,9 +337,9 @@ export default class MessageComposer extends React.Component {
}
_onRoomViewStoreUpdate() {
const isQuoting = Boolean(RoomViewStore.getQuotingEvent());
if (this.state.isQuoting === isQuoting) return;
this.setState({ isQuoting });
const replyToEvent = RoomViewStore.getQuotingEvent();
if (this.state.replyToEvent === replyToEvent) return;
this.setState({ replyToEvent });
}
onInputStateChanged(inputState) {
@ -337,7 +378,7 @@ export default class MessageComposer extends React.Component {
}
renderPlaceholderText() {
if (this.state.isQuoting) {
if (this.state.replyToEvent) {
if (this.props.e2eStatus) {
return _t('Send an encrypted reply…');
} else {
@ -382,7 +423,9 @@ export default class MessageComposer extends React.Component {
room={this.props.room}
placeholder={this.renderPlaceholderText()}
resizeNotifier={this.props.resizeNotifier}
permalinkCreator={this.props.permalinkCreator} />,
permalinkCreator={this.props.permalinkCreator}
replyToEvent={this.state.replyToEvent}
/>,
<UploadButton key="controls_upload" roomId={this.props.room.roomId} />,
<EmojiButton key="emoji_button" addEmoji={this.addEmoji} />,
);
@ -392,9 +435,20 @@ export default class MessageComposer extends React.Component {
}
if (this.state.showCallButtons) {
if (callInProgress) {
if (this.state.hasConference) {
const canEndConf = WidgetUtils.canUserModifyWidgets(this.props.room.roomId);
controls.push(
<HangupButton key="controls_hangup" roomId={this.props.room.roomId} />,
<HangupButton
key="controls_hangup"
roomId={this.props.room.roomId}
isConference={true}
canEndConference={canEndConf}
isInConference={this.state.joinedConference}
/>,
);
} else if (callInProgress) {
controls.push(
<HangupButton key="controls_hangup" roomId={this.props.room.roomId} isConference={false} />,
);
} else {
controls.push(

View file

@ -1,5 +1,5 @@
/*
Copyright 2018 New Vector Ltd
Copyright 2018-2020 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.
@ -28,6 +28,11 @@ export default class RoomUpgradeWarningBar extends React.Component {
recommendation: PropTypes.object.isRequired,
};
constructor(props) {
super(props);
this.state = {};
}
componentDidMount() {
const tombstone = this.props.room.currentState.getStateEvents("m.room.tombstone", "");
this.setState({upgraded: tombstone && tombstone.getContent().replacement_room});
@ -35,6 +40,13 @@ export default class RoomUpgradeWarningBar extends React.Component {
MatrixClientPeg.get().on("RoomState.events", this._onStateEvents);
}
componentWillUnmount() {
const cli = MatrixClientPeg.get();
if (cli) {
cli.removeListener("RoomState.events", this._onStateEvents);
}
}
_onStateEvents = (event, state) => {
if (!this.props.room || event.getRoomId() !== this.props.room.roomId) {
return;

View file

@ -1,5 +1,6 @@
/*
Copyright 2015, 2016 OpenMarket Ltd
Copyright 2020 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@ -19,6 +20,7 @@ import AccessibleButton from "../elements/AccessibleButton";
import classNames from "classnames";
import { _t } from '../../../languageHandler';
import {Key} from "../../../Keyboard";
import DesktopBuildsNotice, {WarningKind} from "../elements/DesktopBuildsNotice";
export default class SearchBar extends React.Component {
constructor(props) {
@ -72,21 +74,24 @@ export default class SearchBar extends React.Component {
});
return (
<div className="mx_SearchBar">
<div className="mx_SearchBar_buttons" role="radiogroup">
<AccessibleButton className={ thisRoomClasses } onClick={this.onThisRoomClick} aria-checked={this.state.scope === 'Room'} role="radio">
{_t("This Room")}
</AccessibleButton>
<AccessibleButton className={ allRoomsClasses } onClick={this.onAllRoomsClick} aria-checked={this.state.scope === 'All'} role="radio">
{_t("All Rooms")}
</AccessibleButton>
<>
<div className="mx_SearchBar">
<div className="mx_SearchBar_buttons" role="radiogroup">
<AccessibleButton className={ thisRoomClasses } onClick={this.onThisRoomClick} aria-checked={this.state.scope === 'Room'} role="radio">
{_t("This Room")}
</AccessibleButton>
<AccessibleButton className={ allRoomsClasses } onClick={this.onAllRoomsClick} aria-checked={this.state.scope === 'All'} role="radio">
{_t("All Rooms")}
</AccessibleButton>
</div>
<div className="mx_SearchBar_input mx_textinput">
<input ref={this._search_term} type="text" autoFocus={true} placeholder={_t("Search…")} onKeyDown={this.onSearchChange} />
<AccessibleButton className={ searchButtonClasses } onClick={this.onSearch} />
</div>
<AccessibleButton className="mx_SearchBar_cancel" onClick={this.props.onCancelClick} />
</div>
<div className="mx_SearchBar_input mx_textinput">
<input ref={this._search_term} type="text" autoFocus={true} placeholder={_t("Search…")} onKeyDown={this.onSearchChange} />
<AccessibleButton className={ searchButtonClasses } onClick={this.onSearch} />
</div>
<AccessibleButton className="mx_SearchBar_cancel" onClick={this.props.onCancelClick} />
</div>
<DesktopBuildsNotice isRoomEncrypted={this.props.isRoomEncrypted} kind={WarningKind.Search} />
</>
);
}
}

View file

@ -29,7 +29,6 @@ import {
} from '../../../editor/serialize';
import {CommandPartCreator} from '../../../editor/parts';
import BasicMessageComposer from "./BasicMessageComposer";
import RoomViewStore from '../../../stores/RoomViewStore';
import ReplyThread from "../elements/ReplyThread";
import {parseEvent} from '../../../editor/deserialize';
import {findEditableEvent} from '../../../utils/EventUtils';
@ -41,7 +40,6 @@ import {_t, _td} from '../../../languageHandler';
import ContentMessages from '../../../ContentMessages';
import {Key} from "../../../Keyboard";
import MatrixClientContext from "../../../contexts/MatrixClientContext";
import {MatrixClientPeg} from "../../../MatrixClientPeg";
import RateLimitedFunc from '../../../ratelimitedfunc';
import {Action} from "../../../dispatcher/actions";
@ -61,7 +59,7 @@ function addReplyToMessageContent(content, repliedToEvent, permalinkCreator) {
}
// exported for tests
export function createMessageContent(model, permalinkCreator) {
export function createMessageContent(model, permalinkCreator, replyToEvent) {
const isEmote = containsEmote(model);
if (isEmote) {
model = stripEmoteCommand(model);
@ -70,21 +68,20 @@ export function createMessageContent(model, permalinkCreator) {
model = stripPrefix(model, "/");
}
model = unescapeMessage(model);
const repliedToEvent = RoomViewStore.getQuotingEvent();
const body = textSerialize(model);
const content = {
msgtype: isEmote ? "m.emote" : "m.text",
body: body,
};
const formattedBody = htmlSerializeIfNeeded(model, {forceHTML: !!repliedToEvent});
const formattedBody = htmlSerializeIfNeeded(model, {forceHTML: !!replyToEvent});
if (formattedBody) {
content.format = "org.matrix.custom.html";
content.formatted_body = formattedBody;
}
if (repliedToEvent) {
addReplyToMessageContent(content, repliedToEvent, permalinkCreator);
if (replyToEvent) {
addReplyToMessageContent(content, replyToEvent, permalinkCreator);
}
return content;
@ -95,6 +92,7 @@ export default class SendMessageComposer extends React.Component {
room: PropTypes.object.isRequired,
placeholder: PropTypes.string,
permalinkCreator: PropTypes.object.isRequired,
replyToEvent: PropTypes.object,
};
static contextType = MatrixClientContext;
@ -104,12 +102,13 @@ export default class SendMessageComposer extends React.Component {
this.model = null;
this._editorRef = null;
this.currentlyComposedEditorState = null;
const cli = MatrixClientPeg.get();
if (cli.isCryptoEnabled() && cli.isRoomEncrypted(this.props.room.roomId)) {
if (this.context.isCryptoEnabled() && this.context.isRoomEncrypted(this.props.room.roomId)) {
this._prepareToEncrypt = new RateLimitedFunc(() => {
cli.prepareToEncrypt(this.props.room);
this.context.prepareToEncrypt(this.props.room);
}, 60000);
}
window.addEventListener("beforeunload", this._saveStoredEditorState);
}
_setEditorRef = ref => {
@ -145,7 +144,7 @@ export default class SendMessageComposer extends React.Component {
if (e.shiftKey || e.metaKey) return;
const shouldSelectHistory = e.altKey && e.ctrlKey;
const shouldEditLastMessage = !e.altKey && !e.ctrlKey && up && !RoomViewStore.getQuotingEvent();
const shouldEditLastMessage = !e.altKey && !e.ctrlKey && up && !this.props.replyToEvent;
if (shouldSelectHistory) {
// Try select composer history
@ -187,9 +186,13 @@ export default class SendMessageComposer extends React.Component {
this.sendHistoryManager.currentIndex = this.sendHistoryManager.history.length;
return;
}
const serializedParts = this.sendHistoryManager.getItem(delta);
if (serializedParts) {
this.model.reset(serializedParts);
const {parts, replyEventId} = this.sendHistoryManager.getItem(delta);
dis.dispatch({
action: 'reply_to_event',
event: replyEventId ? this.props.room.findEventById(replyEventId) : null,
});
if (parts) {
this.model.reset(parts);
this._editorRef.focus();
}
}
@ -299,12 +302,12 @@ export default class SendMessageComposer extends React.Component {
}
}
const replyToEvent = this.props.replyToEvent;
if (shouldSend) {
const isReply = !!RoomViewStore.getQuotingEvent();
const {roomId} = this.props.room;
const content = createMessageContent(this.model, this.props.permalinkCreator);
const content = createMessageContent(this.model, this.props.permalinkCreator, replyToEvent);
this.context.sendMessage(roomId, content);
if (isReply) {
if (replyToEvent) {
// Clear reply_to_event as we put the message into the queue
// if the send fails, retry will handle resending.
dis.dispatch({
@ -315,7 +318,7 @@ export default class SendMessageComposer extends React.Component {
dis.dispatch({action: "message_sent"});
}
this.sendHistoryManager.save(this.model);
this.sendHistoryManager.save(this.model, replyToEvent);
// clear composer
this.model.reset([]);
this._editorRef.clearUndoHistory();
@ -325,6 +328,8 @@ export default class SendMessageComposer extends React.Component {
componentWillUnmount() {
dis.unregister(this.dispatcherRef);
window.removeEventListener("beforeunload", this._saveStoredEditorState);
this._saveStoredEditorState();
}
// TODO: [REACT-WARNING] Move this to constructor
@ -333,11 +338,11 @@ export default class SendMessageComposer extends React.Component {
const parts = this._restoreStoredEditorState(partCreator) || [];
this.model = new EditorModel(parts, partCreator);
this.dispatcherRef = dis.register(this.onAction);
this.sendHistoryManager = new SendHistoryManager(this.props.room.roomId, 'mx_cider_composer_history_');
this.sendHistoryManager = new SendHistoryManager(this.props.room.roomId, 'mx_cider_history_');
}
get _editorStateKey() {
return `cider_editor_state_${this.props.room.roomId}`;
return `mx_cider_state_${this.props.room.roomId}`;
}
_clearStoredEditorState() {
@ -347,9 +352,19 @@ export default class SendMessageComposer extends React.Component {
_restoreStoredEditorState(partCreator) {
const json = localStorage.getItem(this._editorStateKey);
if (json) {
const serializedParts = JSON.parse(json);
const parts = serializedParts.map(p => partCreator.deserializePart(p));
return parts;
try {
const {parts: serializedParts, replyEventId} = JSON.parse(json);
const parts = serializedParts.map(p => partCreator.deserializePart(p));
if (replyEventId) {
dis.dispatch({
action: 'reply_to_event',
event: this.props.room.findEventById(replyEventId),
});
}
return parts;
} catch (e) {
console.error(e);
}
}
}
@ -357,7 +372,8 @@ export default class SendMessageComposer extends React.Component {
if (this.model.isEmpty) {
this._clearStoredEditorState();
} else {
localStorage.setItem(this._editorStateKey, JSON.stringify(this.model.serializeParts()));
const item = SendHistoryManager.createItem(this.model, this.props.replyToEvent);
localStorage.setItem(this._editorStateKey, JSON.stringify(item));
}
}
@ -449,7 +465,6 @@ export default class SendMessageComposer extends React.Component {
room={this.props.room}
label={this.props.placeholder}
placeholder={this.props.placeholder}
onChange={this._saveStoredEditorState}
onPaste={this._onPaste}
/>
</div>

View file

@ -22,7 +22,6 @@ import * as sdk from '../../../index';
import dis from '../../../dispatcher/dispatcher';
import AccessibleButton from '../elements/AccessibleButton';
import WidgetUtils from '../../../utils/WidgetUtils';
import ActiveWidgetStore from '../../../stores/ActiveWidgetStore';
import PersistedElement from "../elements/PersistedElement";
import {IntegrationManagers} from "../../../integrations/IntegrationManagers";
import SettingsStore from "../../../settings/SettingsStore";
@ -30,6 +29,7 @@ import {ContextMenu} from "../../structures/ContextMenu";
import {WidgetType} from "../../../widgets/WidgetType";
import AccessibleTooltipButton from "../elements/AccessibleTooltipButton";
import {Action} from "../../../dispatcher/actions";
import {WidgetMessagingStore} from "../../../stores/widgets/WidgetMessagingStore";
// This should be below the dialog level (4000), but above the rest of the UI (1000-2000).
// We sit in a context menu, so this should be given to the context menu.
@ -212,9 +212,11 @@ export default class Stickerpicker extends React.Component {
_sendVisibilityToWidget(visible) {
if (!this.state.stickerpickerWidget) return;
const widgetMessaging = ActiveWidgetStore.getWidgetMessaging(this.state.stickerpickerWidget.id);
if (widgetMessaging && visible !== this._prevSentVisibility) {
widgetMessaging.sendVisibility(visible);
const messaging = WidgetMessagingStore.instance.getMessagingForId(this.state.stickerpickerWidget.id);
if (messaging && visible !== this._prevSentVisibility) {
messaging.updateVisibility(visible).catch(err => {
console.error("Error updating widget visibility: ", err);
});
this._prevSentVisibility = visible;
}
}

View file

@ -14,25 +14,25 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import React, {useCallback} from "react";
import React, {useState} from "react";
import PropTypes from "prop-types";
import * as sdk from "../../../index";
import {_t} from "../../../languageHandler";
import Modal from "../../../Modal";
import AccessibleButton from "../elements/AccessibleButton";
import classNames from "classnames";
const AvatarSetting = ({avatarUrl, avatarAltText, avatarName, uploadAvatar, removeAvatar}) => {
const AccessibleButton = sdk.getComponent('elements.AccessibleButton');
const [isHovering, setIsHovering] = useState(false);
const hoveringProps = {
onMouseEnter: () => setIsHovering(true),
onMouseLeave: () => setIsHovering(false),
};
const openImageView = useCallback(() => {
const ImageView = sdk.getComponent("elements.ImageView");
Modal.createDialog(ImageView, {
src: avatarUrl,
name: avatarName,
}, "mx_Dialog_lightbox");
}, [avatarUrl, avatarName]);
let avatarElement = <div className="mx_AvatarSetting_avatarPlaceholder" />;
let avatarElement = <AccessibleButton
element="div"
onClick={uploadAvatar}
className="mx_AvatarSetting_avatarPlaceholder"
{...hoveringProps}
/>;
if (avatarUrl) {
avatarElement = (
<AccessibleButton
@ -40,16 +40,20 @@ const AvatarSetting = ({avatarUrl, avatarAltText, avatarName, uploadAvatar, remo
src={avatarUrl}
alt={avatarAltText}
aria-label={avatarAltText}
onClick={openImageView} />
onClick={uploadAvatar}
{...hoveringProps}
/>
);
}
let uploadAvatarBtn;
if (uploadAvatar) {
// insert an empty div to be the host for a css mask containing the upload.svg
uploadAvatarBtn = <AccessibleButton onClick={uploadAvatar} kind="primary">
{_t("Upload")}
</AccessibleButton>;
uploadAvatarBtn = <AccessibleButton
onClick={uploadAvatar}
className='mx_AvatarSetting_uploadButton'
{...hoveringProps}
/>;
}
let removeAvatarBtn;
@ -59,10 +63,18 @@ const AvatarSetting = ({avatarUrl, avatarAltText, avatarName, uploadAvatar, remo
</AccessibleButton>;
}
return <div className="mx_AvatarSetting_avatar">
{ avatarElement }
{ uploadAvatarBtn }
{ removeAvatarBtn }
const avatarClasses = classNames({
"mx_AvatarSetting_avatar": true,
"mx_AvatarSetting_avatar_hovering": isHovering,
});
return <div className={avatarClasses}>
{avatarElement}
<div className="mx_AvatarSetting_hover">
<div className="mx_AvatarSetting_hoverBg" />
<span>{_t("Upload")}</span>
</div>
{uploadAvatarBtn}
{removeAvatarBtn}
</div>;
};

View file

@ -19,14 +19,12 @@ import Field from "../elements/Field";
import React from 'react';
import PropTypes from 'prop-types';
import {MatrixClientPeg} from "../../../MatrixClientPeg";
import dis from "../../../dispatcher/dispatcher";
import AccessibleButton from '../elements/AccessibleButton';
import Spinner from '../elements/Spinner';
import { _t } from '../../../languageHandler';
import * as sdk from "../../../index";
import Modal from "../../../Modal";
import sessionStore from '../../../stores/SessionStore';
export default class ChangePassword extends React.Component {
static propTypes = {
onFinished: PropTypes.func,
@ -35,6 +33,7 @@ export default class ChangePassword extends React.Component {
rowClassName: PropTypes.string,
buttonClassName: PropTypes.string,
buttonKind: PropTypes.string,
buttonLabel: PropTypes.string,
confirm: PropTypes.bool,
// Whether to autoFocus the new password input
autoFocusNewPasswordInput: PropTypes.bool,
@ -65,33 +64,11 @@ export default class ChangePassword extends React.Component {
state = {
phase: ChangePassword.Phases.Edit,
cachedPassword: null,
oldPassword: "",
newPassword: "",
newPasswordConfirm: "",
};
componentDidMount() {
this._sessionStore = sessionStore;
this._sessionStoreToken = this._sessionStore.addListener(
this._setStateFromSessionStore,
);
this._setStateFromSessionStore();
}
componentWillUnmount() {
if (this._sessionStoreToken) {
this._sessionStoreToken.remove();
}
}
_setStateFromSessionStore = () => {
this.setState({
cachedPassword: this._sessionStore.getCachedPassword(),
});
};
changePassword(oldPassword, newPassword) {
const cli = MatrixClientPeg.get();
@ -118,8 +95,11 @@ export default class ChangePassword extends React.Component {
</div>,
button: _t("Continue"),
extraButtons: [
<button className="mx_Dialog_primary"
onClick={this._onExportE2eKeysClicked}>
<button
key="exportRoomKeys"
className="mx_Dialog_primary"
onClick={this._onExportE2eKeysClicked}
>
{ _t('Export E2E room keys') }
</button>,
],
@ -149,9 +129,6 @@ export default class ChangePassword extends React.Component {
});
cli.setPassword(authDict, newPassword).then(() => {
// Notify SessionStore that the user's password was changed
dis.dispatch({action: 'password_changed'});
if (this.props.shouldAskForEmail) {
return this._optionallySetEmail().then((confirmed) => {
this.props.onFinished({
@ -211,7 +188,7 @@ export default class ChangePassword extends React.Component {
onClickChange = (ev) => {
ev.preventDefault();
const oldPassword = this.state.cachedPassword || this.state.oldPassword;
const oldPassword = this.state.oldPassword;
const newPassword = this.state.newPassword;
const confirmPassword = this.state.newPasswordConfirm;
const err = this.props.onCheckPassword(
@ -230,31 +207,22 @@ export default class ChangePassword extends React.Component {
const rowClassName = this.props.rowClassName;
const buttonClassName = this.props.buttonClassName;
let currentPassword = null;
if (!this.state.cachedPassword) {
currentPassword = (
<div className={rowClassName}>
<Field
type="password"
label={_t('Current password')}
value={this.state.oldPassword}
onChange={this.onChangeOldPassword}
/>
</div>
);
}
switch (this.state.phase) {
case ChangePassword.Phases.Edit:
const passwordLabel = this.state.cachedPassword ?
_t('Password') : _t('New Password');
return (
<form className={this.props.className} onSubmit={this.onClickChange}>
{ currentPassword }
<div className={rowClassName}>
<Field
type="password"
label={passwordLabel}
label={_t('Current password')}
value={this.state.oldPassword}
onChange={this.onChangeOldPassword}
/>
</div>
<div className={rowClassName}>
<Field
type="password"
label={_t('New Password')}
value={this.state.newPassword}
autoFocus={this.props.autoFocusNewPasswordInput}
onChange={this.onChangeNewPassword}
@ -271,15 +239,14 @@ export default class ChangePassword extends React.Component {
/>
</div>
<AccessibleButton className={buttonClassName} kind={this.props.buttonKind} onClick={this.onClickChange}>
{ _t('Change Password') }
{ this.props.buttonLabel || _t('Change Password') }
</AccessibleButton>
</form>
);
case ChangePassword.Phases.Uploading:
var Loader = sdk.getComponent("elements.Spinner");
return (
<div className="mx_Dialog_content">
<Loader />
<Spinner />
</div>
);
}

View file

@ -18,30 +18,23 @@ import React, {createRef} from 'react';
import {_t} from "../../../languageHandler";
import {MatrixClientPeg} from "../../../MatrixClientPeg";
import Field from "../elements/Field";
import {User} from "matrix-js-sdk";
import { getHostingLink } from '../../../utils/HostingLink';
import * as sdk from "../../../index";
import {OwnProfileStore} from "../../../stores/OwnProfileStore";
import Modal from "../../../Modal";
import ErrorDialog from "../dialogs/ErrorDialog";
export default class ProfileSettings extends React.Component {
constructor() {
super();
const client = MatrixClientPeg.get();
let user = client.getUser(client.getUserId());
if (!user) {
// XXX: We shouldn't have to do this.
// There seems to be a condition where the User object won't exist until a room
// exists on the account. To work around this, we'll just create a temporary User
// and use that.
console.warn("User object not found - creating one for ProfileSettings");
user = new User(client.getUserId());
}
let avatarUrl = user.avatarUrl;
let avatarUrl = OwnProfileStore.instance.avatarMxc;
if (avatarUrl) avatarUrl = client.mxcUrlToHttp(avatarUrl, 96, 96, 'crop', false);
this.state = {
userId: user.userId,
originalDisplayName: user.rawDisplayName,
displayName: user.rawDisplayName,
userId: client.getUserId(),
originalDisplayName: OwnProfileStore.instance.displayName,
displayName: OwnProfileStore.instance.displayName,
originalAvatarUrl: avatarUrl,
avatarUrl: avatarUrl,
avatarFile: null,
@ -65,6 +58,15 @@ export default class ProfileSettings extends React.Component {
});
};
_clearProfile = async (e) => {
e.stopPropagation();
e.preventDefault();
if (!this.state.enableProfileSave) return;
this._removeAvatar();
this.setState({enableProfileSave: false, displayName: this.state.originalDisplayName});
};
_saveProfile = async (e) => {
e.stopPropagation();
e.preventDefault();
@ -75,21 +77,26 @@ export default class ProfileSettings extends React.Component {
const client = MatrixClientPeg.get();
const newState = {};
// TODO: What do we do about errors?
try {
if (this.state.originalDisplayName !== this.state.displayName) {
await client.setDisplayName(this.state.displayName);
newState.originalDisplayName = this.state.displayName;
}
if (this.state.originalDisplayName !== this.state.displayName) {
await client.setDisplayName(this.state.displayName);
newState.originalDisplayName = this.state.displayName;
}
if (this.state.avatarFile) {
const uri = await client.uploadContent(this.state.avatarFile);
await client.setAvatarUrl(uri);
newState.avatarUrl = client.mxcUrlToHttp(uri, 96, 96, 'crop', false);
newState.originalAvatarUrl = newState.avatarUrl;
newState.avatarFile = null;
} else if (this.state.originalAvatarUrl !== this.state.avatarUrl) {
await client.setAvatarUrl(""); // use empty string as Synapse 500s on undefined
if (this.state.avatarFile) {
const uri = await client.uploadContent(this.state.avatarFile);
await client.setAvatarUrl(uri);
newState.avatarUrl = client.mxcUrlToHttp(uri, 96, 96, 'crop', false);
newState.originalAvatarUrl = newState.avatarUrl;
newState.avatarFile = null;
} else if (this.state.originalAvatarUrl !== this.state.avatarUrl) {
await client.setAvatarUrl(""); // use empty string as Synapse 500s on undefined
}
} catch (err) {
Modal.createTrackedDialog('Failed to save profile', '', ErrorDialog, {
title: _t("Failed to save your profile"),
description: ((err && err.message) ? err.message : _t("The operation could not be completed")),
});
}
this.setState(newState);
@ -144,18 +151,27 @@ export default class ProfileSettings extends React.Component {
const AccessibleButton = sdk.getComponent('elements.AccessibleButton');
const AvatarSetting = sdk.getComponent('settings.AvatarSetting');
return (
<form onSubmit={this._saveProfile} autoComplete="off" noValidate={true}>
<form
onSubmit={this._saveProfile}
autoComplete="off"
noValidate={true}
className="mx_ProfileSettings_profileForm"
>
<input type="file" ref={this._avatarUpload} className="mx_ProfileSettings_avatarUpload"
onChange={this._onAvatarChanged} accept="image/*" />
<div className="mx_ProfileSettings_profile">
<div className="mx_ProfileSettings_controls">
<span className="mx_SettingsTab_subheading">{_t("Profile")}</span>
<Field
label={_t("Display Name")}
type="text" value={this.state.displayName}
autoComplete="off"
onChange={this._onDisplayNameChanged}
/>
<p>
{this.state.userId}
{hostingSignup}
</p>
<Field label={_t("Display Name")}
type="text" value={this.state.displayName} autoComplete="off"
onChange={this._onDisplayNameChanged} />
</div>
<AvatarSetting
avatarUrl={this.state.avatarUrl}
@ -164,10 +180,22 @@ export default class ProfileSettings extends React.Component {
uploadAvatar={this._uploadAvatar}
removeAvatar={this._removeAvatar} />
</div>
<AccessibleButton onClick={this._saveProfile} kind="primary"
disabled={!this.state.enableProfileSave}>
{_t("Save")}
</AccessibleButton>
<div className="mx_ProfileSettings_buttons">
<AccessibleButton
onClick={this._clearProfile}
kind="link"
disabled={!this.state.enableProfileSave}
>
{_t("Cancel")}
</AccessibleButton>
<AccessibleButton
onClick={this._saveProfile}
kind="primary"
disabled={!this.state.enableProfileSave}
>
{_t("Save")}
</AccessibleButton>
</div>
</form>
);
}

View file

@ -239,7 +239,7 @@ export default class RolesRoomSettingsTab extends React.Component {
defaultValue: 50,
},
"redact": {
desc: _t('Remove messages'),
desc: _t('Remove messages sent by others'),
defaultValue: 50,
},
"notifications.room": {

View file

@ -221,7 +221,6 @@ export default class GeneralUserSettingsTab extends React.Component {
_renderProfileSection() {
return (
<div className="mx_SettingsTab_section">
<span className="mx_SettingsTab_subheading">{_t("Profile")}</span>
<ProfileSettings />
</div>
);

View file

@ -17,7 +17,6 @@ limitations under the License.
import React from 'react';
import IncomingCallBox from './IncomingCallBox';
import CallPreview from './CallPreview';
import * as VectorConferenceHandler from '../../../VectorConferenceHandler';
interface IProps {
@ -31,7 +30,7 @@ export default class CallContainer extends React.PureComponent<IProps, IState> {
public render() {
return <div className="mx_CallContainer">
<IncomingCallBox />
<CallPreview ConferenceHandler={VectorConferenceHandler} />
<CallPreview />
</div>;
}
}

View file

@ -26,10 +26,6 @@ import PersistentApp from "../elements/PersistentApp";
import SettingsStore from "../../../settings/SettingsStore";
interface IProps {
// A Conference Handler implementation
// Must have a function signature:
// getConferenceCallForRoom(roomId: string): MatrixCall
ConferenceHandler: any;
}
interface IState {
@ -47,7 +43,7 @@ export default class CallPreview extends React.Component<IProps, IState> {
this.state = {
roomId: RoomViewStore.getRoomId(),
activeCall: CallHandler.getAnyActiveCall(),
activeCall: CallHandler.sharedInstance().getAnyActiveCall(),
};
}
@ -77,14 +73,14 @@ export default class CallPreview extends React.Component<IProps, IState> {
// may hide the global CallView if the call it is tracking is dead
case 'call_state':
this.setState({
activeCall: CallHandler.getAnyActiveCall(),
activeCall: CallHandler.sharedInstance().getAnyActiveCall(),
});
break;
}
};
private onCallViewClick = () => {
const call = CallHandler.getAnyActiveCall();
const call = CallHandler.sharedInstance().getAnyActiveCall();
if (call) {
dis.dispatch({
action: 'view_room',
@ -94,7 +90,7 @@ export default class CallPreview extends React.Component<IProps, IState> {
};
public render() {
const callForRoom = CallHandler.getCallForRoom(this.state.roomId);
const callForRoom = CallHandler.sharedInstance().getCallForRoom(this.state.roomId);
const showCall = (
this.state.activeCall &&
this.state.activeCall.call_state === 'connected' &&
@ -106,7 +102,6 @@ export default class CallPreview extends React.Component<IProps, IState> {
<CallView
className="mx_CallPreview"
onClick={this.onCallViewClick}
ConferenceHandler={this.props.ConferenceHandler}
showHangup={true}
/>
);

View file

@ -31,11 +31,6 @@ interface IProps {
// room; if not, we will show any active call.
room?: Room;
// A Conference Handler implementation
// Must have a function signature:
// getConferenceCallForRoom(roomId: string): MatrixCall
ConferenceHandler?: any;
// maxHeight style attribute for the video panel
maxVideoHeight?: number;
@ -96,14 +91,13 @@ export default class CallView extends React.Component<IProps, IState> {
if (this.props.room) {
const roomId = this.props.room.roomId;
call = CallHandler.getCallForRoom(roomId) ||
(this.props.ConferenceHandler ? this.props.ConferenceHandler.getConferenceCallForRoom(roomId) : null);
call = CallHandler.sharedInstance().getCallForRoom(roomId);
if (this.call) {
this.setState({ call: call });
}
} else {
call = CallHandler.getAnyActiveCall();
call = CallHandler.sharedInstance().getAnyActiveCall();
// Ignore calls if we can't get the room associated with them.
// I think the underlying problem is that the js-sdk sends events
// for calls before it has made the rooms available in the store,
@ -115,20 +109,19 @@ export default class CallView extends React.Component<IProps, IState> {
}
if (call) {
call.setLocalVideoElement(this.getVideoView().getLocalVideoElement());
call.setRemoteVideoElement(this.getVideoView().getRemoteVideoElement());
// always use a separate element for audio stream playback.
// this is to let us move CallView around the DOM without interrupting remote audio
// during playback, by having the audio rendered by a top-level <audio/> element.
// rather than being rendered by the main remoteVideo <video/> element.
call.setRemoteAudioElement(this.getVideoView().getRemoteAudioElement());
if (this.getVideoView()) {
call.setLocalVideoElement(this.getVideoView().getLocalVideoElement());
call.setRemoteVideoElement(this.getVideoView().getRemoteVideoElement());
// always use a separate element for audio stream playback.
// this is to let us move CallView around the DOM without interrupting remote audio
// during playback, by having the audio rendered by a top-level <audio/> element.
// rather than being rendered by the main remoteVideo <video/> element.
call.setRemoteAudioElement(this.getVideoView().getRemoteAudioElement());
}
}
if (call && call.type === "video" && call.call_state !== "ended" && call.call_state !== "ringing") {
// if this call is a conf call, don't display local video as the
// conference will have us in it
this.getVideoView().getLocalVideoElement().style.display = (
call.confUserId ? "none" : "block"
);
this.getVideoView().getLocalVideoElement().style.display = "block";
this.getVideoView().getRemoteVideoElement().style.display = "block";
} else {
this.getVideoView().getLocalVideoElement().style.display = "none";

View file

@ -52,7 +52,7 @@ export default class IncomingCallBox extends React.Component<IProps, IState> {
private onAction = (payload: ActionPayload) => {
switch (payload.action) {
case 'call_state': {
const call = CallHandler.getCall(payload.room_id);
const call = CallHandler.sharedInstance().getCallForRoom(payload.room_id);
if (call && call.call_state === 'ringing') {
this.setState({
incomingCall: call,

View file

@ -275,12 +275,17 @@ export async function _waitForMember(client: MatrixClient, roomId: string, userI
* can encrypt to.
*/
export async function canEncryptToAllUsers(client: MatrixClient, userIds: string[]) {
const usersDeviceMap = await client.downloadKeys(userIds);
// { "@user:host": { "DEVICE": {...}, ... }, ... }
return Object.values(usersDeviceMap).every((userDevices) =>
// { "DEVICE": {...}, ... }
Object.keys(userDevices).length > 0,
);
try {
const usersDeviceMap = await client.downloadKeys(userIds);
// { "@user:host": { "DEVICE": {...}, ... }, ... }
return Object.values(usersDeviceMap).every((userDevices) =>
// { "DEVICE": {...}, ... }
Object.keys(userDevices).length > 0,
);
} catch (e) {
console.error("Error determining if it's possible to encrypt to all users: ", e);
return false; // assume not
}
}
export async function ensureDMExists(client: MatrixClient, userId: string): Promise<string> {
@ -289,9 +294,9 @@ export async function ensureDMExists(client: MatrixClient, userId: string): Prom
if (existingDMRoom) {
roomId = existingDMRoom.roomId;
} else {
let encryption;
let encryption: boolean = undefined;
if (privateShouldBeEncrypted()) {
encryption = canEncryptToAllUsers(client, [userId]);
encryption = await canEncryptToAllUsers(client, [userId]);
}
roomId = await createRoom({encryption, dmUserId: userId, spinner: false, andView: false});
await _waitForMember(client, roomId, userId);

View file

@ -18,6 +18,10 @@ import EditorModel from "./model";
import DocumentPosition, {Predicate} from "./position";
import {Part} from "./parts";
const whitespacePredicate: Predicate = (index, offset, part) => {
return part.text[offset].trim() === "";
};
export default class Range {
private _start: DocumentPosition;
private _end: DocumentPosition;
@ -35,6 +39,11 @@ export default class Range {
});
}
trim() {
this._start = this._start.forwardsWhile(this.model, whitespacePredicate);
this._end = this._end.backwardsWhile(this.model, whitespacePredicate);
}
expandBackwardsWhile(predicate: Predicate) {
this._start = this._start.backwardsWhile(this.model, predicate);
}

View file

@ -18,8 +18,8 @@ import {useState, useEffect, DependencyList} from 'react';
type Fn<T> = () => Promise<T>;
export const useAsyncMemo = <T>(fn: Fn<T>, deps: DependencyList, initialValue?: T) => {
const [value, setValue] = useState(initialValue);
export const useAsyncMemo = <T>(fn: Fn<T>, deps: DependencyList, initialValue?: T): T => {
const [value, setValue] = useState<T>(initialValue);
useEffect(() => {
fn().then(setValue);
}, deps); // eslint-disable-line react-hooks/exhaustive-deps

View file

@ -14,11 +14,11 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import {useState} from "react";
import {Dispatch, SetStateAction, useState} from "react";
// Hook to simplify toggling of a boolean state value
// Returns value, method to toggle boolean value and method to set the boolean value
export const useStateToggle = (initialValue: boolean) => {
export const useStateToggle = (initialValue: boolean): [boolean, () => void, Dispatch<SetStateAction<boolean>>] => {
const [value, setValue] = useState(initialValue);
const toggleValue = () => {
setValue(!value);

View file

@ -1,5 +1,5 @@
{
"Continue": "إستمر",
"Continue": "واصِل",
"Username available": "اسم المستخدم متاح",
"Username not available": "الإسم المستخدم غير موجود",
"Something went wrong!": "هناك خطأ ما!",
@ -7,18 +7,18 @@
"Close": "إغلاق",
"Create new room": "إنشاء غرفة جديدة",
"Custom Server Options": "الإعدادات الشخصية للخادوم",
"Dismiss": "تجاهل",
"Dismiss": "أهمِل",
"Failed to change password. Is your password correct?": "فشلت عملية تعديل الكلمة السرية. هل كلمتك السرية صحيحة ؟",
"Warning": "تنبيه",
"Error": "خطأ",
"Error": "عُطل",
"Remove": "حذف",
"Send": "إرسال",
"Edit": "تعديل",
"This email address is already in use": "عنوان البريد هذا مستخدم بالفعل",
"This phone number is already in use": "رقم الهاتف هذا مستخدم بالفعل",
"Failed to verify email address: make sure you clicked the link in the email": "فشل تأكيد عنوان البريد الإلكتروني: تحقق من نقر الرابط في البريد",
"Failed to verify email address: make sure you clicked the link in the email": "فشل التثبّت من عنوان البريد الإلكتروني: تأكّد من نقر الرابط في البريد المُرسل",
"The version of %(brand)s": "إصدارة %(brand)s",
"Whether or not you're using the Richtext mode of the Rich Text Editor": "فيما إذا كنت تستخدم وضع النص الغني لمحرر النصوص الغني أم لا",
"Whether or not you're using the Richtext mode of the Rich Text Editor": "فيما إذا كنت تستعمل وضع النص الغني في محرّر النصوص الغنية",
"Your homeserver's URL": "عنوان خادوم المنزل",
"Analytics": "التحاليل",
"The information being sent to us to help make %(brand)s better includes:": "تحتوي المعلومات التي تُرسل إلينا للمساعدة بتحسين جودة %(brand)s الآتي:",
@ -59,120 +59,120 @@
"Checking for an update...": "البحث عن تحديث …",
"powered by Matrix": "مشغل بواسطة Matrix",
"The platform you're on": "المنصة الحالية",
"Your language of choice": "اللغة المختارة",
"e.g. %(exampleValue)s": "مثال %(exampleValue)s",
"Use Single Sign On to continue": "استخدم تسجيل الدخول الموحد للاستمرار",
"Confirm adding this email address by using Single Sign On to prove your identity.": "اكد اضافة بريدك الالكتروني عن طريق الدخول الموحد (SSO) لتثبت هويتك.",
"Single Sign On": "تسجيل الدخول الموحد",
"Confirm adding email": "تأكيد اضافة بريدك الالكتروني",
"Click the button below to confirm adding this email address.": "انقر على الزر ادناه لتأكد اضافة هذا البريد الالكتروني.",
"Confirm": "تأكيد",
"Add Email Address": "اضافة بريد الكتروني",
"Confirm adding this phone number by using Single Sign On to prove your identity.": "قم بتأكيد اضافة رقم الهاتف هذا باستخدام تقنية الدخول الموحد لتثبت هويتك.",
"Confirm adding phone number": "قم بتأكيد اضافة رقم الهاتف",
"Click the button below to confirm adding this phone number.": "انقر الزر ادناه لتأكيد اضافة رقم الهاتف.",
"Add Phone Number": "اضافة رقم هاتف",
"Which officially provided instance you are using, if any": "التي تقدم البيئة التي تستخدمها بشكل رسمي، اذا كان هناك",
"Whether you're using %(brand)s on a device where touch is the primary input mechanism": "عندما تستخدم %(brand)s على جهاز تكون شاشة اللمس هي طريقة الادخال الرئيسية",
"Whether or not you're using the 'breadcrumbs' feature (avatars above the room list)": "اذا كنت تستخدم او لا تستخدم ميزة 'breadcrumbs' (الافاتار فوق قائمة الغرف)",
"Whether you're using %(brand)s as an installed Progressive Web App": "اذا كنت تستخدم %(brand)s كتطبيق ويب",
"Your user agent": "وكيل المستخدم الخاص بك",
"Unable to load! Check your network connectivity and try again.": "غير قادر على التحميل! قم فحص اتصالك الشبكي وحاول مرة اخرى.",
"Call Timeout": "مهلة الاتصال",
"Call failed due to misconfigured server": "فشل الاتصال بسبب إعداد السيرفر بشكل خاطئ",
"Please ask the administrator of your homeserver (<code>%(homeserverDomain)s</code>) to configure a TURN server in order for calls to work reliably.": "يرجى مطالبة مسئول سيرفرك (<code>%(homeserverDomain)s</code>) بإعداد سيرفر TURN لكي تعمل المكالمات بشكل صحيح.",
"Alternatively, you can try to use the public server at <code>turn.matrix.org</code>, but this will not be as reliable, and it will share your IP address with that server. You can also manage this in Settings.": "بدلاً من ذلك، يمكنك محاولة استخدام السيرفر العام على <code>turn.matrix.org</code>، ولكن هذا لن يكون موثوقًا به، وسيشارك عنوان IP الخاص بك مع هذا السيرفر. يمكنك أيضًا تعديل ذلك في الإعدادات.",
"Try using turn.matrix.org": "جرب استخدام turn.matrix.org",
"OK": "حسنا",
"Unable to capture screen": "غير قادر على التقاط الشاشة",
"Call Failed": ل الاتصال",
"You are already in a call.": "أنت بالفعل في مكالمة.",
"Your language of choice": "اللغة التي تريد",
"e.g. %(exampleValue)s": "مثال: %(exampleValue)s",
"Use Single Sign On to continue": "استعمل الولوج الموحّد للمواصلة",
"Confirm adding this email address by using Single Sign On to prove your identity.": "أكّد إضافتك لعنوان البريد هذا باستعمال الولوج الموحّد لإثبات هويّتك.",
"Single Sign On": "الولوج الموحّد",
"Confirm adding email": "أكّد إضافة البريد الإلكتروني",
"Click the button below to confirm adding this email address.": "انقر الزر أسفله لتأكيد إضافة عنوان البريد الإلكتروني هذا.",
"Confirm": "أكّد",
"Add Email Address": "أضِف بريدًا إلكترونيًا",
"Confirm adding this phone number by using Single Sign On to prove your identity.": "أكّد إضافتك لرقم الهاتف هذا باستعمال الولوج الموحّد لإثبات هويّتك.",
"Confirm adding phone number": "أكّد إضافة رقم الهاتف",
"Click the button below to confirm adding this phone number.": "انقر الزر أسفله لتأكيد إضافة رقم الهاتف هذا",
"Add Phone Number": "أضِف رقم الهاتف",
"Which officially provided instance you are using, if any": "السيرورة المقدّمة رسميًا التي تستعملها، لو وُجدت",
"Whether you're using %(brand)s on a device where touch is the primary input mechanism": "فيما إذا كنت تستعمل %(brand)s على جهاز اللمس فيه هو طريقة الإدخال الرئيسة",
"Whether or not you're using the 'breadcrumbs' feature (avatars above the room list)": "",
"Whether you're using %(brand)s as an installed Progressive Web App": "فيما إذا كنت تستعمل %(brand)s كتطبيق وِب تدرّجي",
"Your user agent": "وكيل المستخدم الذي تستعمله",
"Unable to load! Check your network connectivity and try again.": "تعذر التحميل! افحص اتصالك بالشبكة وأعِد المحاولة.",
"Call Timeout": "انتهت مهلة الاتصال",
"Call failed due to misconfigured server": "فشل الاتصال بسبب سوء ضبط الخادوم",
"Please ask the administrator of your homeserver (<code>%(homeserverDomain)s</code>) to configure a TURN server in order for calls to work reliably.": "من فضلك اطلب من مسؤول الخادوم المنزل الذي تستعمله (<code>%(homeserverDomain)s</code>) أن يضبط خادوم TURN كي تعمل الاتصالات بنحوٍ يكون محط ثقة.",
"Alternatively, you can try to use the public server at <code>turn.matrix.org</code>, but this will not be as reliable, and it will share your IP address with that server. You can also manage this in Settings.": "أو يمكنك محاولة الخادوم العمومي <code>turn.matrix.org</code> إلا أنه لن يكون محطّ ثقة إذ سيُشارك عنوان IP لديك بذاك الخادوم. يمكنك أيضًا إدارة هذا من الإعدادات.",
"Try using turn.matrix.org": "جرّب استعمال turn.matrix.org",
"OK": "حسنًا",
"Unable to capture screen": "تعذر التقاط الشاشة",
"Call Failed": شل الاتصال",
"You are already in a call.": "تُجري مكالمة الآن.",
"VoIP is unsupported": "تقنية VoIP غير مدعومة",
"You cannot place VoIP calls in this browser.": "لايمكنك اجراء مكالمات VoIP عبر هذا المتصفح.",
"A call is currently being placed!": تم حاليًا إجراء مكالمة!",
"A call is already in progress!": "المكالمة جارية بالفعل!",
"Permission Required": "مطلوب صلاحية",
"You do not have permission to start a conference call in this room": "ليس لديك صلاحية لبدء مكالمة جماعية في هذه الغرفة",
"Replying With Files": "الرد مع الملفات",
"At this time it is not possible to reply with a file. Would you like to upload this file without replying?": "في الوقت الحالي ، لا يمكن الرد مع ملف. هل تريد تحميل هذا الملف بدون رد؟",
"The file '%(fileName)s' failed to upload.": "فشل في رفع الملف '%(fileName)s'.",
"The file '%(fileName)s' exceeds this homeserver's size limit for uploads": "إن حجم الملف '%(fileName)s' يتجاوز الحد المسموح به للرفع في السيرفر",
"You cannot place VoIP calls in this browser.": "لا يمكنك إجراء مكالمات VoIP عبر هذا المتصفح.",
"A call is currently being placed!": جري إجراء المكالمة!",
"A call is already in progress!": "تُجري مكالمة الآن فعلًا!",
"Permission Required": "التصريح مطلوب",
"You do not have permission to start a conference call in this room": "ينقصك تصريح بدء مكالمة جماعية في هذه الغرفة",
"Replying With Files": "الرد مع ملفات",
"At this time it is not possible to reply with a file. Would you like to upload this file without replying?": "لا يمكنك حاليًا إرسال رد مع ملف. أتريد رفع الملف دون الرد؟",
"The file '%(fileName)s' failed to upload.": "فشل رفع الملف ”%(fileName)s“.",
"The file '%(fileName)s' exceeds this homeserver's size limit for uploads": "حجم الملف ”%(fileName)s“ يتجاوز الحجم الأقصى الذي يسمح به الخادوم المنزل",
"Upload Failed": "فشل الرفع",
"Server may be unavailable, overloaded, or you hit a bug.": "قد يكون السيرفر غير متوفر، او محملا بشكل زائد او انك طلبت ميزة بها مشكلة.",
"The server does not support the room version specified.": "السيرفر لا يدعم إصدار الغرفة المحدد.",
"Failure to create room": "فشل في انشاء الغرفة",
"Server may be unavailable, overloaded, or you hit a bug.": "قد لا يكون الخادوم متاحًا، أو أن عليه ضغط، أو أنك واجهت علة.",
"The server does not support the room version specified.": "لا يدعم الخادوم إصدارة الغرفة المحدّدة.",
"Failure to create room": "فشل إنشاء الغرفة",
"Cancel entering passphrase?": "هل تريد إلغاء إدخال عبارة المرور؟",
"Are you sure you want to cancel entering passphrase?": "هل أنت متأكد من أنك تريد إلغاء إدخال عبارة المرور؟",
"Go Back": "الرجوع للخلف",
"Setting up keys": "إعداد المفاتيح",
"Sun": "احد",
"Mon": "اثنين",
"Tue": "ثلاثاء",
"Wed": "اربعاء",
"Thu": "خميس",
"Fri": "جمعة",
"Sat": "سبت",
"Sun": "الأحد",
"Mon": "الإثنين",
"Tue": "الثلاثاء",
"Wed": "الأربعاء",
"Thu": "الخميس",
"Fri": "الجمعة",
"Sat": "السبت",
"Jan": "يناير",
"Feb": "فبراير",
"Mar": "مارس",
"Apr": "ابريل",
"Apr": "أبريل",
"May": "مايو",
"Jun": "يونيو",
"Jul": "يوليو",
"Aug": "اغسطس",
"Aug": "أغسطس",
"Sep": "سبتمبر",
"Oct": "اكتوبر",
"Oct": "أكتوبر",
"Nov": "نوفمبر",
"Dec": "ديسمبر",
"PM": ساء",
"AM": باحا",
"%(weekDayName)s %(time)s": "%(weekDayName)s %(time)s",
"%(weekDayName)s, %(monthName)s %(day)s %(time)s": "%(weekDayName)s, %(monthName)s %(day)s %(time)s",
"PM": ",
"AM": ",
"%(weekDayName)s %(time)s": "%(weekDayName)s %(time)s",
"%(weekDayName)s, %(monthName)s %(day)s %(time)s": "",
"%(weekDayName)s, %(monthName)s %(day)s %(fullYear)s": "%(weekDayName)s, %(monthName)s %(day)s %(fullYear)s",
"%(weekDayName)s, %(monthName)s %(day)s %(fullYear)s %(time)s": "%(weekDayName)s, %(monthName)s %(day)s %(fullYear)s %(time)s",
"Who would you like to add to this community?": "هل ترغب في اضافة هذا المجتمع؟",
"Warning: any person you add to a community will be publicly visible to anyone who knows the community ID": "تحذير: أي شخص تضيفه إلى مجتمع سيكون مرئيًا للعامة لأي شخص يعرف معرف المجتمع",
"Invite new community members": "دعوى اعضاء جدد للمجتمع",
"Name or Matrix ID": "الاسم او معرف Matrix",
"Invite to Community": "دعوة الى المجتمع",
"Which rooms would you like to add to this community?": "ما هي الغرف التي ترغب في إضافتها إلى هذا المجتمع؟",
"Show these rooms to non-members on the community page and room list?": "هل تريد إظهار هذه الغرف لغير الأعضاء في صفحة المجتمع وقائمة الغرف؟",
"Add rooms to the community": "اضافة غرف الى المجتمع",
"Room name or address": "اسم او عنوان الغرفة",
"Add to community": "اضافة لمجتمع",
"Failed to invite the following users to %(groupId)s:": "فشل في اضافة المستخدمين التاليين الى %(groupId)s:",
"Failed to invite users to community": "فشل دعوة المستخدمين إلى المجتمع",
"Failed to invite users to %(groupId)s": "فشل في دعوة المستخدمين الى %(groupId)s",
"Failed to add the following rooms to %(groupId)s:": "فشل في اضافة الغرف التالية الى %(groupId)s:",
"Who would you like to add to this community?": "مَن تريد إضافته إلى هذا المجتمع؟",
"Warning: any person you add to a community will be publicly visible to anyone who knows the community ID": "تحذير: كلّ من تُضيفه إلى أحد المجتمعات سيكون ظاهرًا لكل من يعرف معرّف المجتمع",
"Invite new community members": "ادعُ أعضاء جدد إلى المجتمع",
"Name or Matrix ID": "الاسم أو معرّف «ماترِكس",
"Invite to Community": "ادعُ إلى المجتمع",
"Which rooms would you like to add to this community?": "ما الغرف التي تُريد إضافتها إلى هذا المجتمع؟",
"Show these rooms to non-members on the community page and room list?": "أتريد عرض هذه الغرف على غير المسجلين كأعضاء في صفحة المجتمع وقائمة الغُرف؟",
"Add rooms to the community": "أضِف غرف إلى المجتمع",
"Room name or address": "اسم الغرفة أو العنوان",
"Add to community": "أضِف إلى المجتمع",
"Failed to invite the following users to %(groupId)s:": "فشلت دعوة المستخدمين الآتية أسمائهم إلى %(groupId)s:",
"Failed to invite users to community": "فشلت دعوة المستخدمين إلى المجتمع",
"Failed to invite users to %(groupId)s": "فشلت دعوة المستخدمين إلى %(groupId)s",
"Failed to add the following rooms to %(groupId)s:": "فشلت إضافة الغرف الآتية إلى %(groupId)s:",
"Unnamed Room": "غرفة بدون اسم",
"Identity server has no terms of service": "سيرفر الهوية ليس لديه شروط للخدمة",
"This action requires accessing the default identity server <server /> to validate an email address or phone number, but the server does not have any terms of service.": "هذا الحدث يتطلب الوصول الى السيرفر الافتراضي للهوية <server /> للتحقق من البريد الالكتروني او رقم الهاتف، ولكن هذا السيرفر ليس لديه اي شروط للخدمة.",
"Only continue if you trust the owner of the server.": "لا تستمر إلا إذا كنت تثق في مالك السيرفر.",
"Trust": "ثِق",
"%(name)s is requesting verification": "%(name)s يطلب التحقق",
"%(brand)s does not have permission to send you notifications - please check your browser settings": "%(brand)s ليس لديه الصلاحية لارسال التنبيهات - يرجى فحص اعدادات متصفحك",
"%(brand)s was not given permission to send notifications - please try again": "لم تعطى الصلاحية ل %(brand)s لارسال التنبيهات - يرجى المحاولة ثانية",
"Unable to enable Notifications": "غير قادر على تفعيل التنبيهات",
"This email address was not found": "لم يتم العثور على البريد الالكتروني هذا",
"Your email address does not appear to be associated with a Matrix ID on this Homeserver.": "يبدو ان بريدك الالكتروني غير مرتبط بمعرف Matrix على هذا السيرفر.",
"Identity server has no terms of service": "ليس لخادوم الهويّة أيّ شروط خدمة",
"This action requires accessing the default identity server <server /> to validate an email address or phone number, but the server does not have any terms of service.": "يطلب هذا الإجراء الوصول إلى خادوم الهويّات المبدئي<server />للتثبّت من عنوان البريد الإلكتروني أو رقم الهاتف، ولكن ليس للخادوم أيّ شروط خدمة.",
"Only continue if you trust the owner of the server.": "لا تُواصل لو لم تكن تثق بمالك الخادوم.",
"Trust": "أثق به",
"%(name)s is requesting verification": "يطلب %(name)s التثبّت",
"%(brand)s does not have permission to send you notifications - please check your browser settings": "لا يملك %(brand)s التصريح لإرسال التنبيهات. من فضلك تحقّق من إعدادات المتصفح",
"%(brand)s was not given permission to send notifications - please try again": "لم تقدّم التصريح اللازم كي يُرسل %(brand)s التنبيهات. من فضلك أعِد المحاولة",
"Unable to enable Notifications": "تعذر تفعيل التنبيهات",
"This email address was not found": "لم يوجد عنوان البريد الإلكتروني هذا",
"Your email address does not appear to be associated with a Matrix ID on this Homeserver.": "لا يظهر بأن عنوان بريدك مرتبط بمعرّف «ماترِكس» على الخادوم المنزل هذا.",
"Use your account to sign in to the latest version": "استخدم حسابك للدخول الى الاصدار الاخير",
"Were excited to announce Riot is now Element": "نحن سعيدون باعلان ان Riot اصبح الان Element",
"Riot is now Element!": "Riot اصبح الان Element!",
"Learn More": "تعلم المزيد",
"Sign In or Create Account": "قم بتسجيل الدخول او انشاء حساب جديد",
"Use your account or create a new one to continue.": "استخدم حسابك او قم بانشاء حساب اخر للاستمرار.",
"Create Account": "انشاء حساب",
"Sign In": "الدخول",
"Default": "افتراضي",
"Sign In or Create Account": "لِج أو أنشِئ حسابًا",
"Use your account or create a new one to continue.": "استعمل حسابك أو أنشِئ واحدًا جديدًا للمواصلة.",
"Create Account": "أنشِئ حسابًا",
"Sign In": "لِج",
"Default": "المبدئي",
"Restricted": "مقيد",
"Moderator": "مشرف",
"Admin": "مدير",
"Custom (%(level)s)": "(%(level)s) مخصص",
"Failed to invite": "فشل في الدعوة",
"Failed to invite": "فشلت الدعوة",
"Operation failed": "فشلت العملية",
"Failed to invite users to the room:": "فشل في دعوة المستخدمين للغرفة:",
"Failed to invite the following users to the %(roomName)s room:": "فشل في دعوة المستخدمين التالية اسمائهم الى الغرفة %(roomName)s:",
"You need to be logged in.": "تحتاج إلى تسجيل الدخول.",
"Failed to invite users to the room:": "فشلت دعوة المستخدمين إلى الغرفة:",
"Failed to invite the following users to the %(roomName)s room:": "فشلت دعوة المستخدمين الآتية أسمائهم إلى غرفة %(roomName)s:",
"You need to be logged in.": "عليك الولوج.",
"You need to be able to invite users to do that.": "يجب أن تكون قادرًا على دعوة المستخدمين للقيام بذلك.",
"Unable to create widget.": "غير قادر على إنشاء Widget.",
"Missing roomId.": "معرف الغرفة مفقود.",
@ -320,15 +320,15 @@
"%(widgetName)s widget modified by %(senderName)s": "الودجت %(widgetName)s تعدلت بواسطة %(senderName)s",
"%(widgetName)s widget added by %(senderName)s": "الودجت %(widgetName)s اضيفت بواسطة %(senderName)s",
"%(widgetName)s widget removed by %(senderName)s": "الودجت %(widgetName)s حذفت بواسطة %(senderName)s",
"Whether or not you're logged in (we don't record your username)": "سواءً كنت مسجلا دخولك أم لا (لا نحتفظ باسم المستخدم)",
"Every page you use in the app": "كل صفحة تستخدمها في التطبيق",
"e.g. <CurrentPageURL>": "مثلا <رابط الصفحة الحالية>",
"Your device resolution": "دقة شاشة جهازك",
"Where this page includes identifiable information, such as a room, user or group ID, that data is removed before being sent to the server.": "على الرغم من كون هذه الصفحة تحوي معلومات تمكن تحديد الهوية، مثل معرف الغرفة والمستخدم والمجموعة، فهذه البيانات يتم حذفها قبل أن ترسل للسيرفر.",
"The remote side failed to pick up": "الطرف الآخر لم يتمكن من الرد",
"Existing Call": "مكالمة موجودة",
"Whether or not you're logged in (we don't record your username)": "سواءً كنت والجًا أم لا (لا نحتفظ باسم المستخدم)",
"Every page you use in the app": "كل صفحة تستعملها في التطبيق",
"e.g. <CurrentPageURL>": "مثال: <عنوان_الصفحة_الحالية>",
"Your device resolution": "ميز الجهاز لديك",
"Where this page includes identifiable information, such as a room, user or group ID, that data is removed before being sent to the server.": "على الرغم من احتواء هذه الصفحة على معلومات تُحدّد الهويّة (مثل معرّف الغرفة والمستخدم والمجموعة) إلّا أن هذه البيانات تُحذف قبل إرسالها إلى الخادوم.",
"The remote side failed to pick up": "لم يردّ الطرف الآخر",
"Existing Call": "مكالمة جارية",
"You cannot place a call with yourself.": "لا يمكنك الاتصال بنفسك.",
"Call in Progress": "المكالمة قيد التحضير",
"Call in Progress": "إجراء المكالمة جارٍ",
"Please install <chromeLink>Chrome</chromeLink>, <firefoxLink>Firefox</firefoxLink>, or <safariLink>Safari</safariLink> for the best experience.": "يرجى تثبيت <chromeLink>Chrome</chromeLink>, <firefoxLink>Firefox</firefoxLink>, or <safariLink>Safari</safariLink> for the best experience.",
"%(senderName)s removed the rule banning users matching %(glob)s": "%(اسم المرسل)S إزالة القاعدة التي تحظر المستخدمين المتطابقين %(عام)s",
"%(senderName)s removed the rule banning rooms matching %(glob)s": "%(اسم المرسل)s إزالة القاعدة التي تحظر الغرف المتطابقة %(عام)s",

View file

@ -1 +1,6 @@
{}
{
"Dismiss": "Odbaci",
"Create Account": "Otvori račun",
"Sign In": "Prijavite se",
"Explore rooms": "Istražite sobe"
}

View file

@ -32,7 +32,7 @@
"Continue": "Fortfahren",
"Create Room": "Raum erstellen",
"Cryptography": "Verschlüsselung",
"Deactivate Account": "Benutzerkonto schließen",
"Deactivate Account": "Benutzerkonto deaktivieren",
"Failed to send email": "Fehler beim Senden der E-Mail",
"Account": "Benutzerkonto",
"Click here to fix": "Zum reparieren hier klicken",
@ -801,7 +801,7 @@
"Muted Users": "Stummgeschaltete Benutzer",
"This will make your account permanently unusable. You will not be able to log in, and no one will be able to re-register the same user ID. This will cause your account to leave all rooms it is participating in, and it will remove your account details from your identity server. <b>This action is irreversible.</b>": "Dies wird deinen Account permanent unbenutzbar machen. Du wirst nicht in der Lage sein, dich anzumelden und keiner wird dieselbe Benutzer-ID erneut registrieren können. Alle Räume, in denen der Account ist, werden verlassen und deine Account-Daten werden vom Identitätsserver gelöscht. <b>Diese Aktion ist unumkehrbar.</b>",
"Deactivating your account <b>does not by default cause us to forget messages you have sent.</b> If you would like us to forget your messages, please tick the box below.": "Standardmäßig werden <b>die von dir gesendeten Nachrichten beim Deaktiveren nicht gelöscht</b>. Wenn du dies von uns möchtest, aktivere das Auswalfeld unten.",
"Message visibility in Matrix is similar to email. Our forgetting your messages means that messages you have sent will not be shared with any new or unregistered users, but registered users who already have access to these messages will still have access to their copy.": "Sie Sichtbarkeit der Nachrichten in Matrix ist vergleichbar mit E-Mails: Wenn wir deine Nachrichten vergessen heißt das, dass diese nicht mit neuen oder nicht registrierten Nutzern teilen werden, aber registrierte Nutzer, die bereits zugriff haben, werden Zugriff auf ihre Kopie behalten.",
"Message visibility in Matrix is similar to email. Our forgetting your messages means that messages you have sent will not be shared with any new or unregistered users, but registered users who already have access to these messages will still have access to their copy.": "Die Sichtbarkeit der Nachrichten in Matrix ist vergleichbar mit E-Mails: Wenn wir deine Nachrichten vergessen heißt das, dass diese nicht mit neuen oder nicht registrierten Nutzern teilen werden, aber registrierte Nutzer, die bereits zugriff haben, werden Zugriff auf ihre Kopie behalten.",
"Please forget all messages I have sent when my account is deactivated (<b>Warning:</b> this will cause future users to see an incomplete view of conversations)": "Bitte vergesst alle Nachrichten, die ich gesendet habe, wenn mein Account deaktiviert wird. (<b>Warnung:</b> Zukünftige Nutzer werden eine unvollständige Konversation sehen)",
"To continue, please enter your password:": "Um fortzufahren, bitte Passwort eingeben:",
"Can't leave Server Notices room": "Du kannst den Raum für Server-Notizen nicht verlassen",
@ -818,7 +818,7 @@
"Share Room Message": "Teile Raumnachricht",
"Link to selected message": "Link zur ausgewählten Nachricht",
"COPY": "KOPIEREN",
"Share Message": "Teile Nachricht",
"Share Message": "Nachricht teilen",
"No Audio Outputs detected": "Keine Ton-Ausgabe erkannt",
"Audio Output": "Ton-Ausgabe",
"In encrypted rooms, like this one, URL previews are disabled by default to ensure that your homeserver (where the previews are generated) cannot gather information about links you see in this room.": "In verschlüsselten Räumen, wie diesem, ist die Link-Vorschau standardmäßig deaktiviert damit dein Heimserver (auf dem die Vorschau erzeugt wird) keine Informationen über Links in diesem Raum bekommt.",
@ -880,7 +880,7 @@
"Delete Backup": "Sicherung löschen",
"Backup version: ": "Sicherungsversion: ",
"Algorithm: ": "Algorithmus: ",
"To avoid losing your chat history, you must export your room keys before logging out. You will need to go back to the newer version of %(brand)s to do this": "Um zu vermeiden, dass Ihr Chat-Verlauf verloren geht, müssen Sie Ihre Raum-Schlüssel exportieren, bevor Sie sich abmelden. Dazu müssen Sie auf die neuere Version von %(brand)s zurückgehen",
"To avoid losing your chat history, you must export your room keys before logging out. You will need to go back to the newer version of %(brand)s to do this": "Um zu vermeiden, dass dein Chat-Verlauf verloren geht, musst du deine Raum-Schlüssel exportieren, bevor du dich abmeldest. Dazu musst du auf die neuere Version von %(brand)s zurückgehen",
"Incompatible Database": "Inkompatible Datenbanken",
"Continue With Encryption Disabled": "Mit deaktivierter Verschlüsselung fortfahren",
"Next": "Weiter",
@ -937,16 +937,16 @@
"Unable to load key backup status": "Konnte Status der Schlüsselsicherung nicht laden",
"Don't ask again": "Nicht erneut fragen",
"Set up": "Einrichten",
"Please review and accept all of the homeserver's policies": "Bitte prüfen und akzeptieren Sie alle Richtlinien des Heimservers",
"Please review and accept all of the homeserver's policies": "Bitte prüfe und akzeptiere alle Richtlinien des Heimservers",
"Failed to load group members": "Konnte Gruppenmitglieder nicht laden",
"That doesn't look like a valid email address": "Sieht nicht nach einer validen E-Mail-Adresse aus",
"That doesn't look like a valid email address": "Sieht nicht nach einer gültigen E-Mail-Adresse aus",
"Unable to load commit detail: %(msg)s": "Konnte Commit-Details nicht laden: %(msg)s",
"Checking...": "Überprüfe...",
"Unable to load backup status": "Konnte Sicherungsstatus nicht laden",
"Failed to decrypt %(failedCount)s sessions!": "Konnte %(failedCount)s Sitzungen nicht entschlüsseln!",
"Access your secure message history and set up secure messaging by entering your recovery passphrase.": "Greifen Sie auf Ihre sichere Nachrichtenhistorie zu und richten Sie einen sicheren Nachrichtenversand ein, indem Sie Ihre Wiederherstellungspassphrase eingeben.",
"Access your secure message history and set up secure messaging by entering your recovery passphrase.": "Greife auf deine gesicherten Chatverlauf zu und richten einen sicheren Nachrichtenversand ein, indem du deine Wiederherstellungspassphrase eingibst.",
"If you've forgotten your recovery passphrase you can <button1>use your recovery key</button1> or <button2>set up new recovery options</button2>": "Wenn du deinen Wiederherstellungspassphrase vergessen hast, kannst du <button1>deinen Wiederherstellungsschlüssel benutzen</button1> oder <button2>neue Wiederherstellungsoptionen einrichten</button2>",
"Access your secure message history and set up secure messaging by entering your recovery key.": "Greifen Sie auf Ihren sicheren Nachrichtenverlauf zu und richten Sie durch Eingabe Ihres Wiederherstellungsschlüssels einen sicheren Nachrichtenversand ein.",
"Access your secure message history and set up secure messaging by entering your recovery key.": "Greife auf deinen gesicherten Chatverlauf zu und richten durch Eingabe deines Wiederherstellungsschlüssels einen sicheren Nachrichtenversand ein.",
"Set a new status...": "Setze einen neuen Status...",
"Clear status": "Status löschen",
"Invalid homeserver discovery response": "Ungültige Antwort beim Aufspüren des Heimservers",
@ -957,10 +957,10 @@
"Without setting up Secure Message Recovery, you'll lose your secure message history when you log out.": "Ohne Sichere Nachrichten-Wiederherstellung einzurichten, wirst du deine sichere Nachrichtenhistorie verlieren, wenn du dich abmeldest.",
"If you don't want to set this up now, you can later in Settings.": "Wenn du dies jetzt nicht einrichten willst, kannst du dies später in den Einstellungen tun.",
"New Recovery Method": "Neue Wiederherstellungsmethode",
"If you didn't set the new recovery method, an attacker may be trying to access your account. Change your account password and set a new recovery method immediately in Settings.": "Wenn Sie die neue Wiederherstellungsmethode nicht festgelegt haben, versucht ein Angreifer möglicherweise, auf Ihr Konto zuzugreifen. Ändern Sie Ihr Kontopasswort und legen Sie sofort eine neue Wiederherstellungsmethode in den Einstellungen fest.",
"If you didn't set the new recovery method, an attacker may be trying to access your account. Change your account password and set a new recovery method immediately in Settings.": "Wenn du die neue Wiederherstellungsmethode nicht festgelegt hast, versucht ein/e Angreifer!n möglicherweise, auf dein Konto zuzugreifen. Ändere dein Kontopasswort und lege sofort eine neue Wiederherstellungsmethode in den Einstellungen fest.",
"Set up Secure Messages": "Richte sichere Nachrichten ein",
"Go to Settings": "Gehe zu Einstellungen",
"Sign in with single sign-on": "Melden Sie sich mit Single Sign-On an",
"Sign in with single sign-on": "Melde dich mit „Single Sign-On“ an",
"Unrecognised address": "Nicht erkannte Adresse",
"User %(user_id)s may or may not exist": "Existenz der Benutzer %(user_id)s unsicher",
"Prompt before sending invites to potentially invalid matrix IDs": "Nachfragen bevor Einladungen zu möglichen ungültigen Matrix IDs gesendet werden",
@ -1141,11 +1141,11 @@
"Are you sure you want to sign out?": "Bist du sicher, dass du dich abmelden möchtest?",
"Manually export keys": "Manueller Schlüssel Export",
"Composer": "Nachrichteneingabefeld",
"Verify this user to mark them as trusted. Trusting users gives you extra peace of mind when using end-to-end encrypted messages.": "Überprüfen Sie diesen Benutzer, um ihn als vertrauenswürdig zu kennzeichnen. Benutzern zu vertrauen gibt Ihnen zusätzliche Sicherheit bei der Verwendung von Ende-zu-Ende-verschlüsselten Nachrichten.",
"Verify this user to mark them as trusted. Trusting users gives you extra peace of mind when using end-to-end encrypted messages.": "Überprüfe diesen Benutzer, um ihn als vertrauenswürdig zu kennzeichnen. Benutzern zu vertrauen gibt dir zusätzliche Sicherheit bei der Verwendung von Ende-zu-Ende-verschlüsselten Nachrichten.",
"I don't want my encrypted messages": "Ich möchte meine verschlüsselten Nachrichten nicht",
"You'll lose access to your encrypted messages": "Du wirst den Zugang zu deinen verschlüsselten Nachrichten verlieren",
"If you run into any bugs or have feedback you'd like to share, please let us know on GitHub.": "Wenn du Fehler bemerkst oder eine Rückmeldung geben möchtest, teile dies uns auf GitHub mit.",
"To help avoid duplicate issues, please <existingIssuesLink>view existing issues</existingIssuesLink> first (and add a +1) or <newIssueLink>create a new issue</newIssueLink> if you can't find it.": "Um doppelte Issues zu vermeiden, <existingIssuesLink>schauen Sie bitte zuerst die existierenden Issues an</existingIssuesLink> (und fügen Sie ein \"+1\" hinzu), oder <newIssueLink>erstellen Sie ein neues Issue</newIssueLink>, wenn Sie keines finden können.",
"To help avoid duplicate issues, please <existingIssuesLink>view existing issues</existingIssuesLink> first (and add a +1) or <newIssueLink>create a new issue</newIssueLink> if you can't find it.": "Um doppelte Issues zu vermeiden, <existingIssuesLink>schaue bitte zuerst die existierenden Issues an</existingIssuesLink> (und füge ein \"+1\" hinzu), oder <newIssueLink>erstelle ein neues Issue</newIssueLink>, wenn du kein passendes findest.",
"Report bugs & give feedback": "Melde Fehler & gib Rückmeldungen",
"Update status": "Aktualisiere Status",
"Set status": "Setze Status",
@ -1188,7 +1188,7 @@
"Enter the location of your Modular homeserver. It may use your own domain name or be a subdomain of <a>modular.im</a>.": "Gib die Adresse deines Modular-Heimservers an. Es kann deine eigene Domain oder eine Subdomain von <a>modular.im</a> sein.",
"Unable to query for supported registration methods.": "Konnte unterstützte Registrierungsmethoden nicht abrufen.",
"Bulk options": "Sammeloptionen",
"Join millions for free on the largest public server": "Schließen Sie sich auf dem größten öffentlichen Server kostenlos Millionen von Menschen an",
"Join millions for free on the largest public server": "Schließe dich kostenlos auf dem größten öffentlichen Server Millionen von Menschen an",
"Prepends ¯\\_(ツ)_/¯ to a plain-text message": "Fügt ¯\\_(ツ)_/¯ vor einer Klartextnachricht ein",
"Changes your display nickname in the current room only": "Ändert den Anzeigenamen ausschließlich für den aktuellen Raum",
"%(senderDisplayName)s enabled flair for %(groups)s in this room.": "%(senderDisplayName)s aktivierte Abzeichen der Gruppen %(groups)s für diesen Raum.",
@ -1322,7 +1322,7 @@
"Add Email Address": "E-Mail-Adresse hinzufügen",
"Add Phone Number": "Telefonnummer hinzufügen",
"Changes the avatar of the current room": "Ändert den Avatar für diesen Raum",
"Deactivate account": "Benutzerkonto schließen",
"Deactivate account": "Benutzerkonto deaktivieren",
"Show previews/thumbnails for images": "Zeige Vorschauen/Thumbnails für Bilder",
"View": "Vorschau",
"Find a room…": "Suche einen Raum…",
@ -1330,7 +1330,7 @@
"If you can't find the room you're looking for, ask for an invite or <a>Create a new room</a>.": "Wenn du den gesuchten Raum nicht finden kannst, frage nach einer Einladung für den Raum oder <a>Erstelle einen neuen Raum</a>.",
"Alternatively, you can try to use the public server at <code>turn.matrix.org</code>, but this will not be as reliable, and it will share your IP address with that server. You can also manage this in Settings.": "Alternativ kannst du versuchen, den öffentlichen Server unter <code>turn.matrix.org</code> zu verwenden. Allerdings wird dieser nicht so zuverlässig sein, und deine IP-Adresse mit diesem Server teilen. Du kannst dies auch in den Einstellungen konfigurieren.",
"This action requires accessing the default identity server <server /> to validate an email address or phone number, but the server does not have any terms of service.": "Diese Handlung erfordert es, auf den Standard-Identitätsserver <server /> zuzugreifen, um eine E-Mail Adresse oder Telefonnummer zu validieren, aber der Server hat keine Nutzungsbedingungen.",
"Only continue if you trust the owner of the server.": "Fahre nur fort, wenn du den Inhaber*innen des Servers vertraust.",
"Only continue if you trust the owner of the server.": "Fahre nur fort, wenn du dem/r Besitzer*in des Servers vertraust.",
"Trust": "Vertrauen",
"Custom (%(level)s)": "Benutzerdefinierte (%(level)s)",
"Sends a message as plain text, without interpreting it as markdown": "Verschickt eine Nachricht in reinem Textformat, ohne sie in Markdown zu formatieren",
@ -1417,7 +1417,7 @@
"You are currently subscribed to:": "Du abonnierst momentan:",
"⚠ These settings are meant for advanced users.": "⚠ Diese Einstellungen sind für fortgeschrittene Nutzer gedacht.",
"Whether you're using %(brand)s on a device where touch is the primary input mechanism": "Ob du %(brand)s auf einem Gerät verwendest, bei dem Berührung der primäre Eingabemechanismus ist",
"Whether you're using %(brand)s as an installed Progressive Web App": "Ob Sie %(brand)s als installierte progressive Web-App verwenden",
"Whether you're using %(brand)s as an installed Progressive Web App": "Ob du %(brand)s als installierte progressive Web-App verwendest",
"Your user agent": "Dein User-Agent",
"If you cancel now, you won't complete verifying the other user.": "Wenn Sie jetzt abbrechen, werden Sie die Verifizierung des anderen Nutzers nicht beenden können.",
"If you cancel now, you won't complete verifying your other session.": "Wenn Sie jetzt abbrechen, werden Sie die Verifizierung der anderen Sitzung nicht beenden können.",
@ -1434,32 +1434,32 @@
"Changing password will currently reset any end-to-end encryption keys on all sessions, making encrypted chat history unreadable, unless you first export your room keys and re-import them afterwards. In future this will be improved.": "Durch die Änderung des Passworts werden derzeit alle Ende-zu-Ende-Verschlüsselungsschlüssel in allen Sitzungen zurückgesetzt, sodass der verschlüsselte Chat-Verlauf nicht mehr lesbar ist, es sei denn, du exportierst zuerst deine Raumschlüssel und importierst sie anschließend wieder. In Zukunft wird dies verbessert werden.",
"Delete %(count)s sessions|other": "Lösche %(count)s Sitzungen",
"Backup is not signed by any of your sessions": "Die Sicherung wurde von keiner deiner Sitzungen unterzeichnet",
"Your password was successfully changed. You will not receive push notifications on other sessions until you log back in to them": "Ihr Passwort wurde erfolgreich geändert. Sie erhalten keine Push-Benachrichtigungen zu anderen Sitzungen, bis Sie sich wieder bei diesen anmelden",
"Your password was successfully changed. You will not receive push notifications on other sessions until you log back in to them": "Dein Passwort wurde erfolgreich geändert. Du erhälst keine Push-Benachrichtigungen zu anderen Sitzungen, bis du dich wieder bei diesen anmeldst",
"Notification sound": "Benachrichtigungston",
"Set a new custom sound": "Setze einen neuen benutzerdefinierten Ton",
"Browse": "Durchsuche",
"Direct Messages": "Direktnachrichten",
"You can use <code>/help</code> to list available commands. Did you mean to send this as a message?": "Sie können <code>/help</code> benutzen, um verfügbare Befehle aufzulisten. Wollten Sie dies als Nachricht senden?",
"You can use <code>/help</code> to list available commands. Did you mean to send this as a message?": "Du kannst <code>/help</code> benutzen, um verfügbare Befehle aufzulisten. Willst du dies als Nachricht senden?",
"Direct message": "Direktnachricht",
"Suggestions": "Vorschläge",
"Recently Direct Messaged": "Kürzlich direkt verschickt",
"Go": "Los",
"Command Help": "Befehl Hilfe",
"To help us prevent this in future, please <a>send us logs</a>.": "Um uns zu helfen, dies in Zukunft zu vermeiden, <a>senden Sie uns bitte Logs</a>.",
"To help us prevent this in future, please <a>send us logs</a>.": "Um uns zu helfen, dies in Zukunft zu vermeiden, <a>sende uns bitte Logs</a>.",
"Notification settings": "Benachrichtigungseinstellungen",
"Help": "Hilf uns",
"Filter": "Filtern",
"Filter rooms…": "Räume filtern…",
"You have %(count)s unread notifications in a prior version of this room.|one": "Sie haben %(count)s ungelesene Benachrichtigungen in einer früheren Version dieses Raumes.",
"You have %(count)s unread notifications in a prior version of this room.|one": "Du hast %(count)s ungelesene Benachrichtigungen in einer früheren Version dieses Raumes.",
"Go Back": "Gehe zurück",
"Notification Autocomplete": "Benachrichtigung Autovervollständigen",
"If disabled, messages from encrypted rooms won't appear in search results.": "Wenn deaktiviert, werden Nachrichten von verschlüsselten Räumen nicht in den Ergebnissen auftauchen.",
"This user has not verified all of their sessions.": "Dieser Benutzer hat nicht alle seine Sitzungen verifiziert.",
"You have verified this user. This user has verified all of their sessions.": "Sie haben diesen Benutzer verifiziert. Dieser Benutzer hat alle seine Sitzungen verifiziert.",
"Your key share request has been sent - please check your other sessions for key share requests.": "Ihre Anfrage zur Schlüssel-Teilung wurde gesendet - bitte überprüfen Sie Ihre anderen Sitzungen auf Anfragen zur Schlüssel-Teilung.",
"Key share requests are sent to your other sessions automatically. If you rejected or dismissed the key share request on your other sessions, click here to request the keys for this session again.": "Anfragen zum Teilen von Schlüsseln werden automatisch an Ihre anderen Sitzungen gesendet. Wenn Sie die Anfragen zum Teilen von Schlüsseln in Ihren anderen Sitzungen abgelehnt oder abgewiesen haben, klicken Sie hier, um die Schlüssel für diese Sitzung erneut anzufordern.",
"If your other sessions do not have the key for this message you will not be able to decrypt them.": "Wenn Ihre anderen Sitzungen nicht über den Schlüssel für diese Nachricht verfügen, können Sie sie nicht entschlüsseln.",
"<requestLink>Re-request encryption keys</requestLink> from your other sessions.": "<requestLink>Fordern Sie Verschlüsselungsschlüssel aus Ihren anderen Sitzungen erneut an</requestLink>.",
"You have verified this user. This user has verified all of their sessions.": "Du hast diese/n Nutzer!n verifiziert. Er/Sie hat alle seine/ihre Sitzungen verifiziert.",
"Your key share request has been sent - please check your other sessions for key share requests.": "Deine Schlüsselanfrage wurde gesendet - sieh in deinen anderen Sitzungen nach der Schlüsselanfrage.",
"Key share requests are sent to your other sessions automatically. If you rejected or dismissed the key share request on your other sessions, click here to request the keys for this session again.": "Schlüsselanfragen werden automatisch an deine anderen Sitzungen gesendet. Wenn du sie abgelehnt oder ignoriert hast klicke hier, um die Schlüssel erneut anzufordern.",
"If your other sessions do not have the key for this message you will not be able to decrypt them.": "Wenn deine anderen Sitzungen nicht über den Schlüssel für diese Nachricht verfügen, kannst du die Nachricht nicht entschlüsseln.",
"<requestLink>Re-request encryption keys</requestLink> from your other sessions.": "<requestLink>Fordere die Verschlüsselungsschlüssel aus deinen anderen Sitzungen erneut an</requestLink>.",
"Room %(name)s": "Raum %(name)s",
"Upgrading this room will shut down the current instance of the room and create an upgraded room with the same name.": "Ein Upgrade dieses Raums schaltet die aktuelle Instanz des Raums ab und erstellt einen aktualisierten Raum mit demselben Namen.",
"%(name)s (%(userId)s) signed in to a new session without verifying it:": "%(name)s (%(userId)s) hat sich zu einer neuen Sitzung angemeldet, ohne sie zu verifizieren:",
@ -1468,29 +1468,29 @@
"%(count)s sessions|other": "%(count)s Sitzungen",
"Hide sessions": "Sitzungen ausblenden",
"Encryption enabled": "Verschlüsselung aktiviert",
"Messages in this room are end-to-end encrypted. Learn more & verify this user in their user profile.": "Nachrichten in diesem Raum sind Ende-zu-Ende verschlüsselt. Erfahren Sie mehr & überprüfen Sie diesen Benutzer in seinem Benutzerprofil.",
"Messages in this room are end-to-end encrypted. Learn more & verify this user in their user profile.": "Nachrichten in diesem Raum sind Ende-zu-Ende verschlüsselt. Erfahre mehr & überprüfe diesen Benutzer in seinem Benutzerprofil.",
"Encryption not enabled": "Verschlüsselung nicht aktiviert",
"You verified %(name)s": "Du hast %(name)s verifiziert",
"You cancelled verifying %(name)s": "Sie haben die Verifizierung von %(name)s abgebrochen",
"You cancelled verifying %(name)s": "Du hast die Verifizierung von %(name)s abgebrochen",
"%(name)s cancelled verifying": "%(name)s hat die Verifizierung abgebrochen",
"%(name)s accepted": "%(name)s hat akzeptiert",
"%(name)s declined": "%(name)s hat abgelehnt",
"%(name)s cancelled": "%(name)s hat abgebrochen",
"%(name)s wants to verify": "%(name)s will eine Verifizierung",
"Your display name": "Ihr Anzeigename",
"Please enter a name for the room": "Bitte geben Sie einen Namen für den Raum ein",
"Your display name": "Dein Anzeigename",
"Please enter a name for the room": "Bitte gib einen Namen für den Raum ein",
"This room is private, and can only be joined by invitation.": "Dieser Raum ist privat und kann nur auf Einladung betreten werden.",
"Create a private room": "Erstelle einen privaten Raum",
"Topic (optional)": "Thema (optional)",
"Make this room public": "Machen Sie diesen Raum öffentlich",
"Make this room public": "Mache diesen Raum öffentlich",
"Hide advanced": "Weitere Einstellungen ausblenden",
"Block users on other matrix homeservers from joining this room (This setting cannot be changed later!)": "Hindere Benutzer auf anderen Matrix-Homeservern daran, diesem Raum beizutreten (Diese Einstellung kann später nicht geändert werden!)",
"Session name": "Name der Sitzung",
"This will allow you to return to your account after signing out, and sign in on other sessions.": "So können Sie nach der Abmeldung zu Ihrem Konto zurückkehren und sich bei anderen Sitzungen anmelden.",
"This will allow you to return to your account after signing out, and sign in on other sessions.": "So kannst du nach der Abmeldung zu deinem Konto zurückkehren und dich bei anderen Sitzungen anmelden.",
"Use bots, bridges, widgets and sticker packs": "Benutze Bots, Bridges, Widgets und Sticker-Packs",
"Changing your password will reset any end-to-end encryption keys on all of your sessions, making encrypted chat history unreadable. Set up Key Backup or export your room keys from another session before resetting your password.": "Wenn Sie Ihr Passwort ändern, werden alle End-to-End-Verschlüsselungsschlüssel für alle Ihre Sitzungen zurückgesetzt, sodass der verschlüsselte Chat-Verlauf nicht mehr lesbar ist. Richten Sie ein Schlüssel-Backup ein oder exportieren Sie Ihre Raumschlüssel aus einer anderen Sitzung, bevor Sie Ihr Passwort zurücksetzen.",
"You have been logged out of all sessions and will no longer receive push notifications. To re-enable notifications, sign in again on each device.": "Sie wurden von allen Sitzungen abgemeldet und erhalten keine Push-Benachrichtigungen mehr. Um die Benachrichtigungen wieder zu aktivieren, melden Sie sich auf jedem Gerät erneut an.",
"Upgrade this session to allow it to verify other sessions, granting them access to encrypted messages and marking them as trusted for other users.": "Aktualisieren Sie diese Sitzung, damit sie andere Sitzungen verifizieren kann, indem sie ihnen Zugang zu verschlüsselten Nachrichten gewährt und sie für andere Benutzer als vertrauenswürdig markiert.",
"Changing your password will reset any end-to-end encryption keys on all of your sessions, making encrypted chat history unreadable. Set up Key Backup or export your room keys from another session before resetting your password.": "Wenn du dein Passwort änderst, werden alle Ende-zu-Ende-Verschlüsselungsschlüssel für alle deine Sitzungen zurückgesetzt, sodass der verschlüsselte Chat-Verlauf nicht mehr lesbar ist. Richte ein Schlüssel-Backup ein oder exportiere deine Raumschlüssel aus einer anderen Sitzung, bevor du dein Passwort zurücksetzst.",
"You have been logged out of all sessions and will no longer receive push notifications. To re-enable notifications, sign in again on each device.": "Du wurdest von allen Sitzungen abgemeldet und erhälst keine Push-Benachrichtigungen mehr. Um die Benachrichtigungen wieder zu aktivieren, melde dich auf jedem Gerät erneut an.",
"Upgrade this session to allow it to verify other sessions, granting them access to encrypted messages and marking them as trusted for other users.": "Aktualisiere diese Sitzung, damit sie andere Sitzungen verifizieren kann, indem sie dir Zugang zu verschlüsselten Nachrichten gewährt und sie für andere Benutzer als vertrauenswürdig markiert.",
"Sign out and remove encryption keys?": "Abmelden und Verschlüsselungsschlüssel entfernen?",
"Sign in to your Matrix account on <underlinedServerName />": "Melde dich bei deinem Matrix-Konto auf <underlinedServerName /> an",
"Enter your password to sign in and regain access to your account.": "Gib dein Passwort ein, um dich anzumelden und wieder Zugang zu deinem Konto zu erhalten.",
@ -1633,7 +1633,7 @@
"Sends a message as html, without interpreting it as markdown": "Verschickt eine Nachricht im html-Format, ohne sie in Markdown zu formatieren",
"Show rooms with unread notifications first": "Räume mit ungelesenen Benachrichtigungen zuerst zeigen",
"Show shortcuts to recently viewed rooms above the room list": "Kurzbefehle zu den kürzlich gesichteten Räumen über der Raumliste anzeigen",
"Use Single Sign On to continue": "Verwende Single Sign on um fortzufahren",
"Use Single Sign On to continue": "Benutze Single Sign-On um fortzufahren",
"Confirm adding this email address by using Single Sign On to prove your identity.": "Bestätige die hinzugefügte E-Mail-Adresse mit Single Sign-On, um deine Identität nachzuweisen.",
"Single Sign On": "Single Sign-On",
"Confirm adding email": "Bestätige hinzugefügte E-Mail-Addresse",
@ -1836,7 +1836,7 @@
"Mark all as read": "Alle als gelesen markieren",
"Local address": "Lokale Adresse",
"Published Addresses": "Öffentliche Adresse",
"Published addresses can be used by anyone on any server to join your room. To publish an address, it needs to be set as a local address first.": "Öffentliche Adressen können von jedem verwendet werden um den Raum zu betreten. Um eine Adresse zu veröffentlichen musst du zunächst eine lokale Adresse anlegen.",
"Published addresses can be used by anyone on any server to join your room. To publish an address, it needs to be set as a local address first.": "Öffentliche Adressen können von jedem/r verwendet werden, um den Raum zu betreten. Um eine Adresse zu veröffentlichen musst du zunächst eine lokale Adresse anlegen.",
"Other published addresses:": "Andere öffentliche Adressen:",
"No other published addresses yet, add one below": "Keine anderen öffentlichen Adressen vorhanden, füge unten eine hinzu",
"New published address (e.g. #alias:server)": "Neue öffentliche Adresse (z.B. #alias:server)",
@ -2262,7 +2262,7 @@
"Message layout": "Nachrichtenlayout",
"Compact": "Kompakt",
"Modern": "Modern",
"Use a system font": "Verwende die System-Schriftart",
"Use a system font": "Verwende eine System-Schriftart",
"System font name": "System-Schriftart",
"Customise your appearance": "Verändere das Erscheinungsbild",
"Appearance Settings only affect this %(brand)s session.": "Einstellungen zum Erscheinungsbild wirken sich nur auf diese %(brand)s Sitzung aus.",
@ -2410,7 +2410,7 @@
"You can also set up Secure Backup & manage your keys in Settings.": "Du kannst auch in den Einstellungen eine Sicherung erstellen & deine Schlüssel verwalten.",
"Set up Secure backup": "Sicheres Backup einrichten",
"Show message previews for reactions in DMs": "Anzeigen einer Nachrichtenvorschau für Reaktionen in DMs",
"Show message previews for reactions in all rooms": "Zeigen Sie eine Nachrichtenvorschau für Reaktionen in allen Räumen an",
"Show message previews for reactions in all rooms": "Zeige eine Nachrichtenvorschau für Reaktionen in allen Räumen an",
"Uploading logs": "Protokolle werden hochgeladen",
"Downloading logs": "Protokolle werden heruntergeladen",
"Explore public rooms": "Erkunde öffentliche Räume",
@ -2457,5 +2457,67 @@
"Community settings": "Community-Einstellungen",
"User settings": "Nutzer-Einstellungen",
"Community and user menu": "Community- und Nutzer-Menü",
"Prepends ( ͡° ͜ʖ ͡°) to a plain-text message": "Stellt ( ͡° ͜ʖ ͡°) einer Klartextnachricht voran"
"Prepends ( ͡° ͜ʖ ͡°) to a plain-text message": "Stellt ( ͡° ͜ʖ ͡°) einer Klartextnachricht voran",
"Unknown App": "Unbekannte App",
"%(count)s results|one": "%(count)s Ergebnis",
"Room Info": "Raum-Info",
"Apps": "Apps",
"Unpin app": "App nicht mehr anheften",
"Edit apps, bridges & bots": "Apps, Bridges & Bots bearbeiten",
"Add apps, bridges & bots": "Apps, Bridges & Bots hinzufügen",
"Not encrypted": "Nicht verschlüsselt",
"About": "Über",
"%(count)s people|other": "%(count)s Personen",
"%(count)s people|one": "%(count)s Person",
"Show files": "Dateien anzeigen",
"Room settings": "Raum-Einstellungen",
"Take a picture": "Foto aufnehmen",
"Pin to room": "An Raum anheften",
"You can only pin 2 apps at a time": "Du kannst nur 2 Apps gleichzeitig anheften",
"Unpin": "Nicht mehr anheften",
"Group call modified by %(senderName)s": "Gruppenanruf wurde von %(senderName)s verändert",
"Group call started by %(senderName)s": "Gruppenanruf von %(senderName)s gestartet",
"Group call ended by %(senderName)s": "Gruppenanruf wurde von %(senderName)s beendet",
"Cross-signing is ready for use.": "Cross-Signing ist bereit zur Anwendung.",
"Cross-signing is not set up.": "Cross-Signing wurde nicht eingerichtet.",
"Backup version:": "Backup-Version:",
"Algorithm:": "Algorithmus:",
"Back up your encryption keys with your account data in case you lose access to your sessions. Your keys will be secured with a unique Recovery Key.": "Sichere deine Verschlüsselungsschlüssel mit deinen Kontodaten, falls du den Zugriff auf deine Sitzungen verlierst. Deine Schlüssel werden mit einem eindeutigen Wiederherstellungsschlüssel gesichert.",
"Backup key stored:": "Sicherungsschlüssel gespeichert:",
"Backup key cached:": "Sicherungsschlüssel zwischengespeichert:",
"Secret storage:": "Sicherer Speicher:",
"ready": "bereit",
"not ready": "nicht bereit",
"Secure Backup": "Sicheres Backup",
"End Call": "Anruf beenden",
"Remove the group call from the room?": "Konferenzgespräch aus diesem Raum entfernen?",
"You don't have permission to remove the call from the room": "Du hast keine Berechtigung um den Konferenzanruf aus dem Raum zu entfernen",
"Safeguard against losing access to encrypted messages & data": "Schütze dich vor dem Verlust des Zugriffs auf verschlüsselte Nachrichten und Daten",
"not found in storage": "nicht im Speicher gefunden",
"Widgets": "Widgets",
"Edit widgets, bridges & bots": "Widgets, Bridges & Bots bearbeiten",
"Add widgets, bridges & bots": "Widgets, Bridges & Bots hinzufügen",
"You can only pin 2 widgets at a time": "Du kannst jeweils nur 2 Widgets anheften",
"Minimize widget": "Widget minimieren",
"Maximize widget": "Widget maximieren",
"Your server requires encryption to be enabled in private rooms.": "Für deinen Server muss die Verschlüsselung in privaten Räumen aktiviert sein.",
"Start a conversation with someone using their name or username (like <userId/>).": "Starte ein Gespräch unter Verwendung des Namen oder Benutzernamens des Gegenübers (z. B. <userId/>).",
"This won't invite them to %(communityName)s. To invite someone to %(communityName)s, click <a>here</a>": "Das wird sie nicht zu %(communityName)s einladen. Um jemand zu %(communityName)s einzuladen, klicke <a>hier</a>",
"Invite someone using their name, username (like <userId/>) or <a>share this room</a>.": "Lade jemand mittels seinem/ihrem Namen oder Benutzernamen (z.B. <userId/>) ein, oder <a>teile diesem Raum</a>.",
"Unable to set up keys": "Schlüssel können nicht eingerichtet werden",
"Use the <a>Desktop app</a> to see all encrypted files": "Nutze die <a>Desktop-App</a> um alle verschlüsselten Dateien zu sehen",
"Use the <a>Desktop app</a> to search encrypted messages": "Nutze die <a>Desktop-App</a> um verschlüsselte Nachrichten zu suchen",
"This version of %(brand)s does not support viewing some encrypted files": "Diese Version von %(brand)s unterstützt nicht alle verschlüsselten Dateien anzuzeigen",
"This version of %(brand)s does not support searching encrypted messages": "Diese Version von %(brand)s unterstützt nicht verschlüsselte Nachrichten zu durchsuchen",
"Cannot create rooms in this community": "Räume können in dieser Community nicht erstellt werden",
"You do not have permission to create rooms in this community.": "Du bist nicht berechtigt Räume in dieser Community zu erstellen.",
"End conference": "Konferenzgespräch beenden",
"This will end the conference for everyone. Continue?": "Dies wird das Konferenzgespräch für alle beenden. Fortfahren?",
"Join the conference at the top of this room": "Konferenzgespräch oben in diesem Raum beitreten",
"Join the conference from the room information card on the right": "Konferenzgespräch in den Rauminformationen rechts beitreten",
"Video conference ended by %(senderName)s": "Videokonferenz von %(senderName)s beendet",
"Video conference updated by %(senderName)s": "Videokonferenz wurde von %(senderName)s aktualisiert",
"Video conference started by %(senderName)s": "Videokonferenz wurde von %(senderName)s gestartet",
"Ignored attempt to disable encryption": "Versuch, die Verschlüsselung zu deaktivieren, wurde ignoriert",
"Failed to save your profile": "Profil speichern fehlgeschlagen"
}

View file

@ -50,12 +50,10 @@
"You cannot place a call with yourself.": "You cannot place a call with yourself.",
"Call in Progress": "Call in Progress",
"A call is currently being placed!": "A call is currently being placed!",
"End Call": "End Call",
"Remove the group call from the room?": "Remove the group call from the room?",
"Cancel": "Cancel",
"You don't have permission to remove the call from the room": "You don't have permission to remove the call from the room",
"Permission Required": "Permission Required",
"You do not have permission to start a conference call in this room": "You do not have permission to start a conference call in this room",
"End conference": "End conference",
"This will end the conference for everyone. Continue?": "This will end the conference for everyone. Continue?",
"Replying With Files": "Replying With Files",
"At this time it is not possible to reply with a file. Would you like to upload this file without replying?": "At this time it is not possible to reply with a file. Would you like to upload this file without replying?",
"Continue": "Continue",
@ -143,6 +141,7 @@
"Cancel entering passphrase?": "Cancel entering passphrase?",
"Are you sure you want to cancel entering passphrase?": "Are you sure you want to cancel entering passphrase?",
"Go Back": "Go Back",
"Cancel": "Cancel",
"Setting up keys": "Setting up keys",
"Messages": "Messages",
"Actions": "Actions",
@ -214,7 +213,6 @@
"Reason": "Reason",
"%(targetName)s accepted the invitation for %(displayName)s.": "%(targetName)s accepted the invitation for %(displayName)s.",
"%(targetName)s accepted an invitation.": "%(targetName)s accepted an invitation.",
"%(senderName)s requested a VoIP conference.": "%(senderName)s requested a VoIP conference.",
"%(senderName)s invited %(targetName)s.": "%(senderName)s invited %(targetName)s.",
"%(senderName)s banned %(targetName)s.": "%(senderName)s banned %(targetName)s.",
"%(oldDisplayName)s changed their display name to %(displayName)s.": "%(oldDisplayName)s changed their display name to %(displayName)s.",
@ -224,9 +222,7 @@
"%(senderName)s changed their profile picture.": "%(senderName)s changed their profile picture.",
"%(senderName)s set a profile picture.": "%(senderName)s set a profile picture.",
"%(senderName)s made no change.": "%(senderName)s made no change.",
"VoIP conference started.": "VoIP conference started.",
"%(targetName)s joined the room.": "%(targetName)s joined the room.",
"VoIP conference finished.": "VoIP conference finished.",
"%(targetName)s rejected the invitation.": "%(targetName)s rejected the invitation.",
"%(targetName)s left the room.": "%(targetName)s left the room.",
"%(senderName)s unbanned %(targetName)s.": "%(senderName)s unbanned %(targetName)s.",
@ -280,9 +276,6 @@
"%(widgetName)s widget modified by %(senderName)s": "%(widgetName)s widget modified by %(senderName)s",
"%(widgetName)s widget added by %(senderName)s": "%(widgetName)s widget added by %(senderName)s",
"%(widgetName)s widget removed by %(senderName)s": "%(widgetName)s widget removed by %(senderName)s",
"Group call modified by %(senderName)s": "Group call modified by %(senderName)s",
"Group call started by %(senderName)s": "Group call started by %(senderName)s",
"Group call ended by %(senderName)s": "Group call ended by %(senderName)s",
"%(senderName)s removed the rule banning users matching %(glob)s": "%(senderName)s removed the rule banning users matching %(glob)s",
"%(senderName)s removed the rule banning rooms matching %(glob)s": "%(senderName)s removed the rule banning rooms matching %(glob)s",
"%(senderName)s removed the rule banning servers matching %(glob)s": "%(senderName)s removed the rule banning servers matching %(glob)s",
@ -408,9 +401,6 @@
"Contact your <a>server admin</a>.": "Contact your <a>server admin</a>.",
"Warning": "Warning",
"Ok": "Ok",
"Set password": "Set password",
"To return to your account in future you need to set a password": "To return to your account in future you need to set a password",
"Set Password": "Set Password",
"Set up Secure Backup": "Set up Secure Backup",
"Encryption upgrade available": "Encryption upgrade available",
"Verify this session": "Verify this session",
@ -459,6 +449,7 @@
"Support adding custom themes": "Support adding custom themes",
"Show message previews for reactions in DMs": "Show message previews for reactions in DMs",
"Show message previews for reactions in all rooms": "Show message previews for reactions in all rooms",
"Offline encrypted messaging using dehydrated devices": "Offline encrypted messaging using dehydrated devices",
"Enable advanced debugging for the room list": "Enable advanced debugging for the room list",
"Show info about bridges in room settings": "Show info about bridges in room settings",
"Font size": "Font size",
@ -624,8 +615,8 @@
"From %(deviceName)s (%(deviceId)s)": "From %(deviceName)s (%(deviceId)s)",
"Decline (%(counter)s)": "Decline (%(counter)s)",
"Accept <policyLink /> to continue:": "Accept <policyLink /> to continue:",
"Upload": "Upload",
"Remove": "Remove",
"Upload": "Upload",
"This bridge was provisioned by <user />.": "This bridge was provisioned by <user />.",
"This bridge is managed by <user />.": "This bridge is managed by <user />.",
"Workspace: %(networkName)s": "Workspace: %(networkName)s",
@ -642,7 +633,6 @@
"Export E2E room keys": "Export E2E room keys",
"Do you want to set an email address?": "Do you want to set an email address?",
"Current password": "Current password",
"Password": "Password",
"New Password": "New Password",
"Confirm password": "Confirm password",
"Change Password": "Change Password",
@ -721,7 +711,10 @@
"Off": "Off",
"On": "On",
"Noisy": "Noisy",
"Failed to save your profile": "Failed to save your profile",
"The operation could not be completed": "The operation could not be completed",
"<a>Upgrade</a> to your own domain": "<a>Upgrade</a> to your own domain",
"Profile": "Profile",
"Display Name": "Display Name",
"Profile picture": "Profile picture",
"Save": "Save",
@ -822,7 +815,6 @@
"Failed to change password. Is your password correct?": "Failed to change password. Is your password correct?",
"Success": "Success",
"Your password was successfully changed. You will not receive push notifications on other sessions until you log back in to them": "Your password was successfully changed. You will not receive push notifications on other sessions until you log back in to them",
"Profile": "Profile",
"Email addresses": "Email addresses",
"Phone numbers": "Phone numbers",
"Set a new account password...": "Set a new account password...",
@ -975,7 +967,7 @@
"Change settings": "Change settings",
"Kick users": "Kick users",
"Ban users": "Ban users",
"Remove messages": "Remove messages",
"Remove messages sent by others": "Remove messages sent by others",
"Notify everyone": "Notify everyone",
"No users have specific privileges in this room": "No users have specific privileges in this room",
"Privileged Users": "Privileged Users",
@ -1034,9 +1026,6 @@
"Add a widget": "Add a widget",
"Drop File Here": "Drop File Here",
"Drop file here to upload": "Drop file here to upload",
" (unsupported)": " (unsupported)",
"Join as <voiceText>voice</voiceText> or <videoText>video</videoText>.": "Join as <voiceText>voice</voiceText> or <videoText>video</videoText>.",
"Ongoing conference call%(supportedText)s.": "Ongoing conference call%(supportedText)s.",
"This user has not verified all of their sessions.": "This user has not verified all of their sessions.",
"You have not verified this user.": "You have not verified this user.",
"You have verified this user. This user has verified all of their sessions.": "You have verified this user. This user has verified all of their sessions.",
@ -1387,6 +1376,7 @@
"View Source": "View Source",
"Encryption enabled": "Encryption enabled",
"Messages in this room are end-to-end encrypted. Learn more & verify this user in their user profile.": "Messages in this room are end-to-end encrypted. Learn more & verify this user in their user profile.",
"Ignored attempt to disable encryption": "Ignored attempt to disable encryption",
"Encryption not enabled": "Encryption not enabled",
"The encryption used by this room isn't supported.": "The encryption used by this room isn't supported.",
"Error decrypting audio": "Error decrypting audio",
@ -1400,6 +1390,11 @@
"Invalid file%(extra)s": "Invalid file%(extra)s",
"Error decrypting image": "Error decrypting image",
"Show image": "Show image",
"Join the conference at the top of this room": "Join the conference at the top of this room",
"Join the conference from the room information card on the right": "Join the conference from the room information card on the right",
"Video conference ended by %(senderName)s": "Video conference ended by %(senderName)s",
"Video conference updated by %(senderName)s": "Video conference updated by %(senderName)s",
"Video conference started by %(senderName)s": "Video conference started by %(senderName)s",
"You have ignored this user, so their message is hidden. <a>Show anyways.</a>": "You have ignored this user, so their message is hidden. <a>Show anyways.</a>",
"You verified %(name)s": "You verified %(name)s",
"You cancelled verifying %(name)s": "You cancelled verifying %(name)s",
@ -1488,6 +1483,10 @@
"Maximize widget": "Maximize widget",
"Popout widget": "Popout widget",
"More options": "More options",
"Use the <a>Desktop app</a> to see all encrypted files": "Use the <a>Desktop app</a> to see all encrypted files",
"Use the <a>Desktop app</a> to search encrypted messages": "Use the <a>Desktop app</a> to search encrypted messages",
"This version of %(brand)s does not support viewing some encrypted files": "This version of %(brand)s does not support viewing some encrypted files",
"This version of %(brand)s does not support searching encrypted messages": "This version of %(brand)s does not support searching encrypted messages",
"Join": "Join",
"No results": "No results",
"Please <newIssueLink>create a new issue</newIssueLink> on GitHub so that we can investigate this bug.": "Please <newIssueLink>create a new issue</newIssueLink> on GitHub so that we can investigate this bug.",
@ -1817,22 +1816,6 @@
"Verification Pending": "Verification Pending",
"Please check your email and click on the link it contains. Once this is done, click continue.": "Please check your email and click on the link it contains. Once this is done, click continue.",
"This will allow you to reset your password and receive notifications.": "This will allow you to reset your password and receive notifications.",
"A username can only contain lower case letters, numbers and '=_-./'": "A username can only contain lower case letters, numbers and '=_-./'",
"Username not available": "Username not available",
"Username invalid: %(errMessage)s": "Username invalid: %(errMessage)s",
"An error occurred: %(error_string)s": "An error occurred: %(error_string)s",
"Checking...": "Checking...",
"Username available": "Username available",
"To get started, please pick a username!": "To get started, please pick a username!",
"This will be your account name on the <span></span> homeserver, or you can pick a <a>different server</a>.": "This will be your account name on the <span></span> homeserver, or you can pick a <a>different server</a>.",
"If you already have a Matrix account you can <a>log in</a> instead.": "If you already have a Matrix account you can <a>log in</a> instead.",
"You have successfully set a password!": "You have successfully set a password!",
"You have successfully set a password and an email address!": "You have successfully set a password and an email address!",
"You can now return to your account after signing out, and sign in on other devices.": "You can now return to your account after signing out, and sign in on other devices.",
"Remember, you can always set an email address in user settings if you change your mind.": "Remember, you can always set an email address in user settings if you change your mind.",
"(HTTP status %(httpStatus)s)": "(HTTP status %(httpStatus)s)",
"Please set a password!": "Please set a password!",
"This will allow you to return to your account after signing out, and sign in on other sessions.": "This will allow you to return to your account after signing out, and sign in on other sessions.",
"Share Room": "Share Room",
"Link to most recent message": "Link to most recent message",
"Share User": "Share User",
@ -1944,6 +1927,7 @@
"Custom Server Options": "Custom Server Options",
"You can use the custom server options to sign into other Matrix servers by specifying a different homeserver URL. This allows you to use %(brand)s with an existing Matrix account on a different homeserver.": "You can use the custom server options to sign into other Matrix servers by specifying a different homeserver URL. This allows you to use %(brand)s with an existing Matrix account on a different homeserver.",
"Confirm your identity by entering your account password below.": "Confirm your identity by entering your account password below.",
"Password": "Password",
"Missing captcha public key in homeserver configuration. Please report this to your homeserver administrator.": "Missing captcha public key in homeserver configuration. Please report this to your homeserver administrator.",
"Please review and accept all of the homeserver's policies": "Please review and accept all of the homeserver's policies",
"Please review and accept the policies of this homeserver:": "Please review and accept the policies of this homeserver:",
@ -2058,6 +2042,8 @@
"Create a Group Chat": "Create a Group Chat",
"Explore rooms": "Explore rooms",
"Failed to reject invitation": "Failed to reject invitation",
"Cannot create rooms in this community": "Cannot create rooms in this community",
"You do not have permission to create rooms in this community.": "You do not have permission to create rooms in this community.",
"This room is not public. You will not be able to rejoin without an invite.": "This room is not public. You will not be able to rejoin without an invite.",
"Are you sure you want to leave the room '%(roomName)s'?": "Are you sure you want to leave the room '%(roomName)s'?",
"Failed to forget room %(errCode)s": "Failed to forget room %(errCode)s",
@ -2267,11 +2253,11 @@
"Success!": "Success!",
"Create key backup": "Create key backup",
"Unable to create key backup": "Unable to create key backup",
"Safeguard against losing access to encrypted messages & data by backing up encryption keys on your server.": "Safeguard against losing access to encrypted messages & data by backing up encryption keys on your server.",
"Generate a Security Key": "Generate a Security Key",
"Well generate a Security Key for you to store somewhere safe, like a password manager or a safe.": "Well generate a Security Key for you to store somewhere safe, like a password manager or a safe.",
"Enter a Security Phrase": "Enter a Security Phrase",
"Use a secret phrase only you know, and optionally save a Security Key to use for backup.": "Use a secret phrase only you know, and optionally save a Security Key to use for backup.",
"Safeguard against losing access to encrypted messages & data by backing up encryption keys on your server.": "Safeguard against losing access to encrypted messages & data by backing up encryption keys on your server.",
"Enter your account password to confirm the upgrade:": "Enter your account password to confirm the upgrade:",
"Restore your key backup to upgrade your encryption": "Restore your key backup to upgrade your encryption",
"Restore": "Restore",

View file

@ -2135,5 +2135,317 @@
"Explore public rooms": "Buscar salas publicas",
"Can't see what youre looking for?": "¿No encuentras nada de lo que buscas?",
"Explore all public rooms": "Buscar todas las salas publicas",
"%(count)s results|other": "%(count)s resultados"
"%(count)s results|other": "%(count)s resultados",
"Prepends ( ͡° ͜ʖ ͡°) to a plain-text message": "Antepone ( ͡° ͜ʖ ͡°) a un mensaje de texto sin formato",
"Group call modified by %(senderName)s": "Llamada grupal modificada por %(senderName)s",
"Group call started by %(senderName)s": "Llamada grupal iniciada por %(senderName)s",
"Group call ended by %(senderName)s": "Llamada de grupo finalizada por %(senderName)s",
"Unknown App": "Aplicación desconocida",
"New spinner design": "Nuevo diseño de ruleta",
"Show message previews for reactions in DMs": "Mostrar vistas previas de mensajes para reacciones en DM",
"Show message previews for reactions in all rooms": "Mostrar vistas previas de mensajes para reacciones en todas las salas",
"Enable advanced debugging for the room list": "Habilite la depuración avanzada para la lista de salas",
"IRC display name width": "Ancho del nombre de visualización de IRC",
"Unknown caller": "Llamador desconocido",
"Cross-signing is ready for use.": "La firma cruzada está lista para su uso.",
"Cross-signing is not set up.": "La firma cruzada no está configurada.",
"Master private key:": "Clave privada maestra:",
"%(brand)s can't securely cache encrypted messages locally while running in a web browser. Use <desktopLink>%(brand)s Desktop</desktopLink> for encrypted messages to appear in search results.": "%(brand)s no puede almacenar en caché de forma segura mensajes cifrados localmente mientras se ejecuta en un navegador web. Utilizar <desktopLink> %(brand)s Escritorio</desktopLink> para que los mensajes cifrados aparezcan en los resultados de búsqueda.",
"Backup version:": "Versión de respaldo:",
"Algorithm:": "Algoritmo:",
"Back up your encryption keys with your account data in case you lose access to your sessions. Your keys will be secured with a unique Recovery Key.": "Haga una copia de seguridad de sus claves de cifrado con los datos de su cuenta en caso de que pierda el acceso a sus sesiones. Sus claves estarán protegidas con una clave de recuperación única.",
"Backup key stored:": "Clave de respaldo almacenada:",
"Backup key cached:": "Clave de respaldo almacenada en caché:",
"Secret storage:": "Almacenamiento secreto:",
"ready": "Listo",
"not ready": "no está listo",
"Room ID or address of ban list": "ID de habitación o dirección de la lista de prohibición",
"Secure Backup": "Copia de seguridad segura",
"Privacy": "Intimidad",
"Emoji picker": "Selector de emoji",
"Explore community rooms": "Explore las salas comunitarias",
"Custom Tag": "Etiqueta personalizada",
"%(count)s results|one": "%(count)s resultado",
"Appearance": "Apariencia",
"Show rooms with unread messages first": "Mostrar primero las salas con mensajes no leídos",
"Show previews of messages": "Mostrar vistas previas de mensajes",
"Sort by": "Ordenar por",
"Activity": "Actividad",
"A-Z": "A-Z",
"List options": "Opciones de lista",
"Show %(count)s more|other": "Mostrar %(count)s más",
"Show %(count)s more|one": "Mostrar %(count)s más",
"Use default": "Uso por defecto",
"Mentions & Keywords": "Menciones y palabras clave",
"Notification options": "Opciones de notificación",
"Forget Room": "Olvidar habitación",
"Favourited": "Favorecido",
"Leave Room": "Dejar la habitación",
"Room options": "Opciones de habitación",
"Error creating address": "Error al crear la dirección",
"There was an error creating that address. It may not be allowed by the server or a temporary failure occurred.": "Hubo un error al crear esa dirección. Es posible que el servidor no lo permita o que haya ocurrido una falla temporal.",
"You don't have permission to delete the address.": "No tienes permiso para borrar la dirección.",
"There was an error removing that address. It may no longer exist or a temporary error occurred.": "Se produjo un error al eliminar esa dirección. Puede que ya no exista o se haya producido un error temporal.",
"Error removing address": "Error al eliminar la dirección",
"Room Info": "Información de la habitación",
"Apps": "Aplicaciones",
"Unpin app": "Desanclar aplicación",
"Edit apps, bridges & bots": "Edite aplicaciones, puentes y bots",
"Add apps, bridges & bots": "Agregar aplicaciones, puentes y bots",
"Not encrypted": "No encriptado",
"About": "Acerca de",
"%(count)s people|other": "%(count)s personas",
"%(count)s people|one": "%(count)s persona",
"Show files": "Mostrar archivos",
"Room settings": "Configuración de la habitación",
"You've successfully verified your device!": "¡Ha verificado correctamente su dispositivo!",
"Take a picture": "Toma una foto",
"Pin to room": "Anclar a la habitación",
"You can only pin 2 apps at a time": "Solo puedes anclar 2 aplicaciones a la vez",
"Message deleted on %(date)s": "Mensaje eliminado el %(date)s",
"Edited at %(date)s": "Editado el %(date)s",
"Click to view edits": "Haga clic para ver las ediciones",
"Categories": "Categorías",
"Information": "Información",
"QR Code": "Código QR",
"Room address": "Dirección de la habitación",
"Please provide a room address": "Proporcione una dirección de habitación",
"This address is available to use": "Esta dirección está disponible para usar",
"This address is already in use": "Esta dirección ya está en uso",
"Preparing to download logs": "Preparándose para descargar registros",
"Download logs": "Descargar registros",
"Add another email": "Agregar otro correo electrónico",
"People you know on %(brand)s": "Gente que conoces %(brand)s",
"Show": "Mostrar",
"Send %(count)s invites|other": "Enviar %(count)s invitaciones",
"Send %(count)s invites|one": "Enviar invitación a %(count)s",
"Invite people to join %(communityName)s": "Invita a personas a unirse %(communityName)s",
"There was an error creating your community. The name may be taken or the server is unable to process your request.": "Hubo un error al crear tu comunidad. El nombre puede ser tomado o el servidor no puede procesar su solicitud.",
"Community ID: +<localpart />:%(domain)s": "ID de comunidad: +<localpart />:%(domain)s",
"Use this when referencing your community to others. The community ID cannot be changed.": "Use esto cuando haga referencia a su comunidad con otras. La identificación de la comunidad no se puede cambiar.",
"You can change this later if needed.": "Puede cambiar esto más tarde si es necesario.",
"What's the name of your community or team?": "¿Cuál es el nombre de tu comunidad o equipo?",
"Enter name": "Ingrese su nombre",
"Add image (optional)": "Agregar imagen (opcional)",
"An image will help people identify your community.": "Una imagen ayudará a las personas a identificar su comunidad.",
"Private rooms can be found and joined by invitation only. Public rooms can be found and joined by anyone.": "Las salas privadas se pueden encontrar y unirse solo con invitación. Cualquier persona puede encontrar y unirse a las salas públicas.",
"Private rooms can be found and joined by invitation only. Public rooms can be found and joined by anyone in this community.": "Las salas privadas se pueden encontrar y unirse solo con invitación. Cualquier persona de esta comunidad puede encontrar salas públicas y unirse a ellas.",
"You might enable this if the room will only be used for collaborating with internal teams on your homeserver. This cannot be changed later.": "Puede habilitar esto si la sala solo se usará para colaborar con equipos internos en su servidor doméstico. Esto no se puede cambiar después.",
"You might disable this if the room will be used for collaborating with external teams who have their own homeserver. This cannot be changed later.": "Puede desactivar esto si la sala se utilizará para colaborar con equipos externos que tengan su propio servidor doméstico. Esto no se puede cambiar después.",
"Create a room in %(communityName)s": "Crea una habitación en %(communityName)s",
"Block anyone not part of %(serverName)s from ever joining this room.": "Bloquea a cualquier persona que no sea parte de %(serverName)s para que no se una a esta sala.",
"You've previously used a newer version of %(brand)s with this session. To use this version again with end to end encryption, you will need to sign out and back in again.": "Anteriormente usaste una versión más nueva de %(brand)s con esta sesión. Para volver a utilizar esta versión con cifrado de extremo a extremo, deberá cerrar sesión y volver a iniciar sesión.",
"There was an error updating your community. The server is unable to process your request.": "Hubo un error al actualizar tu comunidad. El servidor no puede procesar su solicitud.",
"Update community": "Actualizar comunidad",
"To continue, use Single Sign On to prove your identity.": "Para continuar, utilice el inicio de sesión único para demostrar su identidad.",
"Confirm to continue": "Confirmar para continuar",
"Click the button below to confirm your identity.": "Haga clic en el botón de abajo para confirmar su identidad.",
"May include members not in %(communityName)s": "Puede incluir miembros que no están en %(communityName)s",
"Start a conversation with someone using their name, username (like <userId/>) or email address. This won't invite them to %(communityName)s. To invite someone to %(communityName)s, click <a>here</a>.": "Inicie una conversación con alguien usando su nombre, nombre de usuario (como<userId/>) o dirección de correo electrónico. Esto no los invitará a %(communityName)s Para invitar a alguien a %(communityName)s, haga clic <a>aquí</a>.",
"You're all caught up.": "Estás al día.",
"Server isn't responding": "El servidor no responde",
"Your server isn't responding to some of your requests. Below are some of the most likely reasons.": "Su servidor no responde a algunas de sus solicitudes. A continuación se presentan algunas de las razones más probables.",
"The server (%(serverName)s) took too long to respond.": "El servidor (%(serverName)s) tardó demasiado en responder.",
"Your firewall or anti-virus is blocking the request.": "Su firewall o antivirus está bloqueando la solicitud.",
"A browser extension is preventing the request.": "Una extensión del navegador impide la solicitud.",
"The server is offline.": "El servidor está desconectado.",
"The server has denied your request.": "El servidor ha denegado su solicitud.",
"Your area is experiencing difficulties connecting to the internet.": "Su área está experimentando dificultades para conectarse a Internet.",
"A connection error occurred while trying to contact the server.": "Se produjo un error de conexión al intentar contactar con el servidor.",
"The server is not configured to indicate what the problem is (CORS).": "El servidor no está configurado para indicar cuál es el problema (CORS).",
"Recent changes that have not yet been received": "Cambios recientes que aún no se han recibido",
"Copy": "Copiar",
"Wrong file type": "Tipo de archivo incorrecto",
"Looks good!": "¡Se ve bien!",
"Wrong Recovery Key": "Clave de recuperación incorrecta",
"Invalid Recovery Key": "Clave de recuperación no válida",
"Security Phrase": "Frase de seguridad",
"Enter your Security Phrase or <button>Use your Security Key</button> to continue.": "Ingrese su Frase de seguridad o <button>Usa tu llave de seguridad</button> para continuar.",
"Security Key": "Clave de seguridad",
"Use your Security Key to continue.": "Usa tu llave de seguridad para continuar.",
"Unpin": "Desprender",
"This room is public": "Esta sala es pública",
"Away": "Lejos",
"You can use the custom server options to sign into other Matrix servers by specifying a different homeserver URL. This allows you to use %(brand)s with an existing Matrix account on a different homeserver.": "Puede utilizar las opciones del servidor personalizado para iniciar sesión en otros servidores Matrix especificando una URL de servidor principal diferente. Esto le permite utilizar %(brand)s con una cuenta Matrix existente en un servidor doméstico diferente.",
"Enter the location of your Element Matrix Services homeserver. It may use your own domain name or be a subdomain of <a>element.io</a>.": "Ingrese la ubicación de su servidor doméstico de Element Matrix Services. Puede usar su propio nombre de dominio o ser un subdominio de <a>element.io</a>.",
"No files visible in this room": "No hay archivos visibles en esta sala",
"Attach files from chat or just drag and drop them anywhere in a room.": "Adjunte archivos desde el chat o simplemente arrástrelos y suéltelos en cualquier lugar de una sala.",
"Youre all caught up": "Estás al día",
"You have no visible notifications in this room.": "No tienes notificaciones visibles en esta sala.",
"Delete the room address %(alias)s and remove %(name)s from the directory?": "¿Eliminar la dirección de la sala %(alias)s y eliminar %(name)s del directorio?",
"delete the address.": "eliminar la dirección.",
"Explore rooms in %(communityName)s": "Explora habitaciones en %(communityName)s",
"Search rooms": "Buscar salas",
"Create community": "Crear comunidad",
"Failed to find the general chat for this community": "No se pudo encontrar el chat general de esta comunidad",
"Security & privacy": "Seguridad y Privacidad",
"All settings": "Todos los ajustes",
"Feedback": "Realimentación",
"Community settings": "Configuración de la comunidad",
"User settings": "Ajustes de usuario",
"Switch to light mode": "Cambiar al modo de luz",
"Switch to dark mode": "Cambiar al modo oscuro",
"Switch theme": "Cambiar tema",
"User menu": "Menú del Usuario",
"Community and user menu": "Menú de comunidad y usuario",
"Failed to perform homeserver discovery": "No se pudo realizar el descubrimiento del servidor doméstico",
"Syncing...": "Sincronizando ...",
"Signing In...": "Iniciando sesión...",
"If you've joined lots of rooms, this might take a while": "Si se ha unido a muchas salas, esto puede llevar un tiempo",
"Create account": "Crear una cuenta",
"Unable to query for supported registration methods.": "No se pueden consultar los métodos de registro admitidos.",
"Registration has been disabled on this homeserver.": "El registro ha sido deshabilitado en este servidor doméstico.",
"Your new account (%(newAccountId)s) is registered, but you're already logged into a different account (%(loggedInUserId)s).": "Su nueva cuenta (%(newAccountId)s) está registrada, pero ya inició sesión en una cuenta diferente (%(loggedInUserId)s).",
"Continue with previous account": "Continuar con la cuenta anterior",
"<a>Log in</a> to your new account.": "<a>Inicie sesión</a> en su nueva cuenta.",
"You can now close this window or <a>log in</a> to your new account.": "Ahora puede cerrar esta ventana o <a>iniciar sesión</a> en su nueva cuenta.",
"Registration Successful": "Registro exitoso",
"Create your account": "Crea tu cuenta",
"Use Recovery Key or Passphrase": "Usar clave de recuperación o frase de contraseña",
"Use Recovery Key": "Usar clave de recuperación",
"Confirm your identity by verifying this login from one of your other sessions, granting it access to encrypted messages.": "Confirme su identidad verificando este inicio de sesión de una de sus otras sesiones, otorgándole acceso a los mensajes cifrados.",
"This requires the latest %(brand)s on your other devices:": "Esto requiere la última %(brand)s en sus otros dispositivos:",
"%(brand)s Web": "%(brand)s Web",
"%(brand)s Desktop": "%(brand)s Escritorio",
"%(brand)s iOS": "%(brand)s iOS",
"%(brand)s Android": "%(brand)s Android",
"or another cross-signing capable Matrix client": "u otro cliente Matrix con capacidad de firma cruzada",
"Without completing security on this session, it wont have access to encrypted messages.": "Sin completar la seguridad en esta sesión, no tendrá acceso a los mensajes cifrados.",
"Failed to re-authenticate due to a homeserver problem": "No se pudo volver a autenticar debido a un problema con el servidor doméstico",
"Failed to re-authenticate": "No se pudo volver a autenticar",
"Regain access to your account and recover encryption keys stored in this session. Without them, you wont be able to read all of your secure messages in any session.": "Recupere el acceso a su cuenta y recupere las claves de cifrado almacenadas en esta sesión. Sin ellos, no podrá leer todos sus mensajes seguros en ninguna sesión.",
"Enter your password to sign in and regain access to your account.": "Ingrese su contraseña para iniciar sesión y recuperar el acceso a su cuenta.",
"Forgotten your password?": "¿Olvidaste tu contraseña?",
"Sign in and regain access to your account.": "Inicie sesión y recupere el acceso a su cuenta.",
"You cannot sign in to your account. Please contact your homeserver admin for more information.": "No puede iniciar sesión en su cuenta. Comuníquese con el administrador de su servidor doméstico para obtener más información.",
"You're signed out": "Estás desconectado",
"Clear personal data": "Borrar datos personales",
"Warning: Your personal data (including encryption keys) is still stored in this session. Clear it if you're finished using this session, or want to sign in to another account.": "Advertencia: sus datos personales (incluidas las claves de cifrado) todavía se almacenan en esta sesión. Bórrelo si terminó de usar esta sesión o si desea iniciar sesión en otra cuenta.",
"Command Autocomplete": "Comando Autocompletar",
"Community Autocomplete": "Autocompletar de la comunidad",
"DuckDuckGo Results": "Resultados de DuckDuckGo",
"Emoji Autocomplete": "Autocompletar Emoji",
"Notification Autocomplete": "Autocompletar notificación",
"Room Autocomplete": "Autocompletar habitación",
"User Autocomplete": "Autocompletar de usuario",
"Confirm encryption setup": "Confirmar la configuración de cifrado",
"Click the button below to confirm setting up encryption.": "Haga clic en el botón de abajo para confirmar la configuración del cifrado.",
"Safeguard against losing access to encrypted messages & data by backing up encryption keys on your server.": "Protéjase contra la pérdida de acceso a los mensajes y datos cifrados haciendo una copia de seguridad de las claves de cifrado en su servidor.",
"Generate a Security Key": "Generar una llave de seguridad",
"Well generate a Security Key for you to store somewhere safe, like a password manager or a safe.": "Generaremos una llave de seguridad para que la guardes en un lugar seguro, como un administrador de contraseñas o una caja fuerte.",
"Enter a Security Phrase": "Ingrese una frase de seguridad",
"Use a secret phrase only you know, and optionally save a Security Key to use for backup.": "Use una frase secreta que solo usted conozca y, opcionalmente, guarde una clave de seguridad para usarla como respaldo.",
"Enter your account password to confirm the upgrade:": "Ingrese la contraseña de su cuenta para confirmar la actualización:",
"Restore your key backup to upgrade your encryption": "Restaure la copia de seguridad de su clave para actualizar su cifrado",
"Restore": "Restaurar",
"You'll need to authenticate with the server to confirm the upgrade.": "Deberá autenticarse con el servidor para confirmar la actualización.",
"Upgrade this session to allow it to verify other sessions, granting them access to encrypted messages and marking them as trusted for other users.": "Actualice esta sesión para permitirle verificar otras sesiones, otorgándoles acceso a mensajes cifrados y marcándolos como confiables para otros usuarios.",
"Enter a security phrase only you know, as its used to safeguard your data. To be secure, you shouldnt re-use your account password.": "Ingrese una frase de seguridad que solo usted conozca, ya que se usa para proteger sus datos. Para estar seguro, no debe volver a utilizar la contraseña de su cuenta.",
"Enter a recovery passphrase": "Ingrese una frase de contraseña de recuperación",
"Great! This recovery passphrase looks strong enough.": "¡Excelente! Esta frase de contraseña de recuperación parece lo suficientemente sólida.",
"That matches!": "¡Eso combina!",
"Use a different passphrase?": "¿Utiliza una frase de contraseña diferente?",
"That doesn't match.": "Eso no coincide.",
"Go back to set it again.": "Regrese para configurarlo nuevamente.",
"Enter your recovery passphrase a second time to confirm it.": "Ingrese su contraseña de recuperación por segunda vez para confirmarla.",
"Confirm your recovery passphrase": "Confirma tu contraseña de recuperación",
"Store your Security Key somewhere safe, like a password manager or a safe, as its used to safeguard your encrypted data.": "Guarde su llave de seguridad en un lugar seguro, como un administrador de contraseñas o una caja fuerte, ya que se usa para proteger sus datos cifrados.",
"Download": "Descargar",
"Unable to query secret storage status": "No se puede consultar el estado del almacenamiento secreto",
"Retry": "Reintentar",
"If you cancel now, you may lose encrypted messages & data if you lose access to your logins.": "Si cancela ahora, puede perder mensajes y datos cifrados si pierde el acceso a sus inicios de sesión.",
"You can also set up Secure Backup & manage your keys in Settings.": "También puede configurar la Copia de seguridad segura y administrar sus claves en Configuración.",
"Set up Secure Backup": "Configurar copia de seguridad segura",
"Upgrade your encryption": "Actualice su cifrado",
"Set a Security Phrase": "Establecer una frase de seguridad",
"Confirm Security Phrase": "Confirmar la frase de seguridad",
"Save your Security Key": "Guarde su llave de seguridad",
"Unable to set up secret storage": "No se puede configurar el almacenamiento secreto",
"We'll store an encrypted copy of your keys on our server. Secure your backup with a recovery passphrase.": "Almacenaremos una copia encriptada de sus claves en nuestro servidor. Asegure su copia de seguridad con una contraseña de recuperación.",
"For maximum security, this should be different from your account password.": "Para mayor seguridad, esta debe ser diferente a la contraseña de su cuenta.",
"Set up with a recovery key": "Configurar con una clave de recuperación",
"Please enter your recovery passphrase a second time to confirm.": "Ingrese su contraseña de recuperación por segunda vez para confirmar.",
"Repeat your recovery passphrase...": "Repite tu contraseña de recuperación ...",
"Your recovery key is a safety net - you can use it to restore access to your encrypted messages if you forget your recovery passphrase.": "Su clave de recuperación es una red de seguridad; puede usarla para restaurar el acceso a sus mensajes cifrados si olvida su contraseña de recuperación.",
"Keep a copy of it somewhere secure, like a password manager or even a safe.": "Guarde una copia en un lugar seguro, como un administrador de contraseñas o incluso una caja fuerte.",
"Your recovery key": "Tu clave de recuperación",
"Your recovery key has been <b>copied to your clipboard</b>, paste it to:": "Tu clave de recuperación se ha <b>copiado en tu portapapeles</b>, pégala en:",
"Your recovery key is in your <b>Downloads</b> folder.": "Tu clave de recuperación está en tu carpeta <b>Descargas</b>.",
"<b>Print it</b> and store it somewhere safe": "<b>Imprímelo</b> y guárdalo en un lugar seguro",
"<b>Save it</b> on a USB key or backup drive": "<b>Guárdelo</b> en una llave USB o unidad de respaldo",
"<b>Copy it</b> to your personal cloud storage": "<b>Cópielo</b> a su almacenamiento personal en la nube",
"Your keys are being backed up (the first backup could take a few minutes).": "Se está realizando una copia de seguridad de sus claves (la primera copia de seguridad puede tardar unos minutos).",
"Without setting up Secure Message Recovery, you won't be able to restore your encrypted message history if you log out or use another session.": "Sin configurar Secure Message Recovery, no podrá restaurar su historial de mensajes encriptados si cierra sesión o usa otra sesión.",
"Set up Secure Message Recovery": "Configurar la recuperación segura de mensajes",
"Secure your backup with a recovery passphrase": "Asegure su copia de seguridad con una frase de contraseña de recuperación",
"Make a copy of your recovery key": "Haz una copia de tu clave de recuperación",
"Starting backup...": "Iniciando copia de seguridad ...",
"Success!": "¡Éxito!",
"Create key backup": "Crear copia de seguridad de claves",
"Unable to create key backup": "No se puede crear una copia de seguridad de la clave",
"Without setting up Secure Message Recovery, you'll lose your secure message history when you log out.": "Sin configurar Secure Message Recovery, perderá su historial de mensajes seguros cuando cierre la sesión.",
"If you don't want to set this up now, you can later in Settings.": "Si no desea configurar esto ahora, puede hacerlo más tarde en Configuración.",
"Don't ask again": "No vuelvas a preguntar",
"New Recovery Method": "Nuevo método de recuperación",
"A new recovery passphrase and key for Secure Messages have been detected.": "Se han detectado una nueva contraseña y clave de recuperación para mensajes seguros.",
"If you didn't set the new recovery method, an attacker may be trying to access your account. Change your account password and set a new recovery method immediately in Settings.": "Si no configuró el nuevo método de recuperación, es posible que un atacante esté intentando acceder a su cuenta. Cambie la contraseña de su cuenta y configure un nuevo método de recuperación inmediatamente en Configuración.",
"Go to Settings": "Ir a la configuración",
"Set up Secure Messages": "Configurar mensajes seguros",
"Recovery Method Removed": "Método de recuperación eliminado",
"This session has detected that your recovery passphrase and key for Secure Messages have been removed.": "Esta sesión ha detectado que se han eliminado su contraseña de recuperación y la clave para Mensajes seguros.",
"If you did this accidentally, you can setup Secure Messages on this session which will re-encrypt this session's message history with a new recovery method.": "Si hizo esto accidentalmente, puede configurar Mensajes seguros en esta sesión que volverá a cifrar el historial de mensajes de esta sesión con un nuevo método de recuperación.",
"If you didn't remove the recovery method, an attacker may be trying to access your account. Change your account password and set a new recovery method immediately in Settings.": "Si no eliminó el método de recuperación, es posible que un atacante esté intentando acceder a su cuenta. Cambie la contraseña de su cuenta y configure un nuevo método de recuperación inmediatamente en Configuración.",
"If disabled, messages from encrypted rooms won't appear in search results.": "Si está desactivado, los mensajes de las salas cifradas no aparecerán en los resultados de búsqueda.",
"Disable": "Inhabilitar",
"Not currently indexing messages for any room.": "Actualmente no indexa mensajes para ninguna sala.",
"Currently indexing: %(currentRoom)s": "Actualmente indexando: %(currentRoom)s",
"%(brand)s is securely caching encrypted messages locally for them to appear in search results:": "%(brand)s está almacenando en caché de forma segura los mensajes cifrados localmente para que aparezcan en los resultados de búsqueda:",
"Space used:": "Espacio usado:",
"Indexed messages:": "Mensajes indexados:",
"Indexed rooms:": "Salas indexadas:",
"%(doneRooms)s out of %(totalRooms)s": "%(doneRooms)s fuera de %(totalRooms)s",
"Message downloading sleep time(ms)": "Tiempo de suspensión de descarga de mensajes(ms)",
"Navigation": "Navegación",
"Calls": "Llamadas",
"Room List": "Lista de habitaciones",
"Autocomplete": "Autocompletar",
"Alt": "Alt",
"Alt Gr": "Alt Gr",
"Shift": "Shift",
"Super": "Super",
"Ctrl": "Ctrl",
"Toggle Bold": "Alternar negrita",
"Toggle Italics": "Alternar cursiva",
"Toggle Quote": "Alternar Entrecomillar",
"New line": "Nueva línea",
"Navigate recent messages to edit": "Navegar por mensajes recientes para editar",
"Jump to start/end of the composer": "Saltar al inicio / final del compositor",
"Navigate composer history": "Navegar por el historial del compositor",
"Cancel replying to a message": "Cancelar la respuesta a un mensaje",
"Toggle microphone mute": "Alternar silencio del micrófono",
"Toggle video on/off": "Activar/desactivar video",
"Scroll up/down in the timeline": "Desplazarse hacia arriba o hacia abajo en la línea de tiempo",
"Dismiss read marker and jump to bottom": "Descartar el marcador de lectura y saltar al final",
"Jump to oldest unread message": "Ir al mensaje no leído más antiguo",
"Upload a file": "Cargar un archivo",
"Jump to room search": "Ir a la búsqueda de Salas",
"Navigate up/down in the room list": "Navegar hacia arriba/abajo en la lista de salas",
"Select room from the room list": "Seleccionar sala de la lista de salas",
"Collapse room list section": "Contraer la sección de lista de salas",
"Expand room list section": "Expandir la sección de la lista de salas",
"Clear room list filter field": "Borrar campo de filtro de lista de salas",
"Previous/next unread room or DM": "Sala o DM anterior/siguiente sin leer",
"Previous/next room or DM": "Sala anterior/siguiente o DM",
"Toggle the top left menu": "Alternar el menú superior izquierdo",
"Close dialog or context menu": "Cerrar cuadro de diálogo o menú contextual",
"Activate selected button": "Activar botón seleccionado",
"Toggle right panel": "Alternar panel derecho",
"Toggle this dialog": "Alternar este diálogo",
"Move autocomplete selection up/down": "Mover la selección de autocompletar hacia arriba/abajo",
"Cancel autocomplete": "Cancelar autocompletar",
"Page Up": "Página arriba",
"Page Down": "Página abajo",
"Esc": "Esc",
"Enter": "Enter",
"Space": "Espacio"
}

View file

@ -618,7 +618,7 @@
"%(senderDisplayName)s removed the room name.": "%(senderDisplayName)s eemaldas jututoa nime.",
"%(senderDisplayName)s changed the room name from %(oldRoomName)s to %(newRoomName)s.": "%(senderDisplayName)s muutis jututoa vana nime %(oldRoomName)s uueks nimeks %(newRoomName)s.",
"%(senderDisplayName)s changed the room name to %(roomName)s.": "%(senderDisplayName)s muutis jututoa nimeks %(roomName)s.",
"Show info about bridges in room settings": "Näita jututoa seadistustes teavet võrgusildade kohta",
"Show info about bridges in room settings": "Näita jututoa seadistustes teavet sõnumisildade kohta",
"Upload": "Lae üles",
"Save": "Salvesta",
"General": "Üldist",
@ -1578,7 +1578,7 @@
"You have successfully set a password and an email address!": "Salasõna loomine ja e-posti aadressi salvestamine õnnestus!",
"You can now return to your account after signing out, and sign in on other devices.": "Nüüd sa saad peale väljalogimist pöörduda tagasi oma konto juurde või logida sisse muudest seadmetest.",
"Remember, you can always set an email address in user settings if you change your mind.": "Jäta meelde, et sa saad alati hiljem määrata kasutajaseadetest oma e-posti aadressi.",
"Use bots, bridges, widgets and sticker packs": "Kasuta roboteid, võrgusildu, vidinaid või kleepsupakke",
"Use bots, bridges, widgets and sticker packs": "Kasuta roboteid, sõnumisildu, vidinaid või kleepsupakke",
"Upload all": "Lae kõik üles",
"This file is <b>too large</b> to upload. The file size limit is %(limit)s but this file is %(sizeOfThisFile)s.": "See fail on üleslaadimiseks <b>liiga suur</b>. Üleslaetavate failide mahupiir on %(limit)s, kuid selle faili suurus on %(sizeOfThisFile)s.",
"Appearance": "Välimus",
@ -1930,7 +1930,7 @@
"'%(groupId)s' is not a valid community ID": "'%(groupId)s' ei ole korrektne kogukonna tunnus",
"Direct message": "Otsevestlus",
"Demote yourself?": "Kas vähendad enda õigusi?",
"You will not be able to undo this change as you are demoting yourself, if you are the last privileged user in the room it will be impossible to regain privileges.": "Kuna sa vähendad enda õigusi, siis sul ei pruugi enam olla võimalik seda muutust tagasi pöörata. Kui sa juhtumisi oled viimane haldusõigustega kasutaja jututoas, siis hiljem on võimatu samu õigusi tagasi saada.",
"You will not be able to undo this change as you are demoting yourself, if you are the last privileged user in the room it will be impossible to regain privileges.": "Kuna sa vähendad enda õigusi, siis sul ei pruugi hiljem olla võimalik seda muutust tagasi pöörata. Kui sa juhtumisi oled viimane haldusõigustega kasutaja jututoas, siis hiljem on võimatu samu õigusi tagasi saada.",
"Demote": "Vähenda enda õigusi",
"Ban": "Keela ligipääs",
"Unban this user?": "Kas taastame selle kasutaja ligipääsu?",
@ -2459,5 +2459,70 @@
"User settings": "Kasutaja seadistused",
"Community and user menu": "Kogukonna ja kasutaja menüü",
"Privacy": "Privaatsus",
"Prepends ( ͡° ͜ʖ ͡°) to a plain-text message": "Lisa ( ͡° ͜ʖ ͡°) smaili vormindamata sõnumi algusesse"
"Prepends ( ͡° ͜ʖ ͡°) to a plain-text message": "Lisa ( ͡° ͜ʖ ͡°) smaili vormindamata sõnumi algusesse",
"Unknown App": "Tundmatu rakendus",
"%(count)s results|one": "%(count)s tulemus",
"Room Info": "Jututoa teave",
"Apps": "Rakendused",
"Unpin app": "Eemalda rakenduse klammerdus",
"Edit apps, bridges & bots": "Muuda rakendusi, sõnumisildu ja roboteid",
"Add apps, bridges & bots": "Lisa rakendusi, sõnumisildu ja roboteid",
"Not encrypted": "Krüptimata",
"About": "Rakenduse teave",
"%(count)s people|other": "%(count)s inimest",
"%(count)s people|one": "%(count)s isik",
"Show files": "Näita faile",
"Room settings": "Jututoa seadistused",
"Take a picture": "Tee foto",
"Pin to room": "Klammerda jututoa külge",
"You can only pin 2 apps at a time": "Sul võib korraga olla vaid kaks klammerdatud rakendust",
"Unpin": "Eemalda klammerdus",
"Group call modified by %(senderName)s": "%(senderName)s muutis rühmakõnet",
"Group call started by %(senderName)s": "%(senderName)s algatas rühmakõne",
"Group call ended by %(senderName)s": "%(senderName)s lõpetas rühmakõne",
"Cross-signing is ready for use.": "Risttunnustamine on kasutamiseks valmis.",
"Cross-signing is not set up.": "Risttunnustamine on seadistamata.",
"Backup version:": "Varukoopia versioon:",
"Algorithm:": "Algoritm:",
"Back up your encryption keys with your account data in case you lose access to your sessions. Your keys will be secured with a unique Recovery Key.": "Selleks puhuks, kui sa kaotad ligipääsu kõikidele oma sessioonidele, tee varukoopia oma krüptovõtmetest ja kasutajakonto seadistustest. Unikaalse taastevõtmega tagad selle, et sinu varukoopia on turvaline.",
"Backup key stored:": "Varukoopia võti on salvestatud:",
"Backup key cached:": "Varukoopia võti on puhverdatud:",
"Secret storage:": "Turvahoidla:",
"ready": "valmis",
"not ready": "ei ole valmis",
"Secure Backup": "Turvaline varundus",
"End Call": "Lõpeta kõne",
"Remove the group call from the room?": "Kas eemaldame jututoast rühmakõne?",
"You don't have permission to remove the call from the room": "Sinul pole õigusi rühmakõne eemaldamiseks sellest jututoast",
"Start a conversation with someone using their name or username (like <userId/>).": "Alusta vestlust kasutades teise osapoole nime või kasutajanime (näiteks <userId/>).",
"This won't invite them to %(communityName)s. To invite someone to %(communityName)s, click <a>here</a>": "Sellega ei kutsu sa teda %(communityName)s kogukonna liikmeks. %(communityName)s kogukonna kutse saatmiseks klõpsi <a>siin</a>",
"Invite someone using their name, username (like <userId/>) or <a>share this room</a>.": "Kutsu kedagi tema nime, kasutajanime (nagu <userId/>) alusel või <a>jaga seda jututuba</a>.",
"Safeguard against losing access to encrypted messages & data": "Hoia ära, et kaotad ligipääsu krüptitud sõnumitele ja andmetele",
"not found in storage": "ei leidunud turvahoidlas",
"Widgets": "Vidinad",
"Edit widgets, bridges & bots": "Muuda vidinaid, võrgusildu ja roboteid",
"Add widgets, bridges & bots": "Lisa vidinaid, võrgusildu ja roboteid",
"You can only pin 2 widgets at a time": "Korraga saavad kinniklammerdatud olla vaid 2 vidinat",
"Minimize widget": "Vähenda vidinat",
"Maximize widget": "Suurenda vidinat",
"Your server requires encryption to be enabled in private rooms.": "Sinu koduserveri seadistused eeldavad, et mitteavalikud jututoad asutavad läbivat krüptimist.",
"Unable to set up keys": "Krüptovõtmete kasutuselevõtmine ei õnnestu",
"Use the <a>Desktop app</a> to see all encrypted files": "Kõikide krüptitud failide vaatamiseks kasuta <a>Element Desktop</a> rakendust",
"Use the <a>Desktop app</a> to search encrypted messages": "Otsinguks krüptitud sõnumite hulgast kasuta <a>Element Desktop</a> rakendust",
"This version of %(brand)s does not support viewing some encrypted files": "See %(brand)s versioon ei toeta mõnede krüptitud failide vaatatamist",
"This version of %(brand)s does not support searching encrypted messages": "See %(brand)s versioon ei toeta otsingut krüptitud sõnumite seast",
"Cannot create rooms in this community": "Siia kogukonda ei saa jututubasid luua",
"You do not have permission to create rooms in this community.": "Sul pole õigusi luua siin kogukonnas uusi jututubasid.",
"Join the conference at the top of this room": "Liitu konverentsiga selle jututoa ülaosas",
"Join the conference from the room information card on the right": "Liitu konverentsiga selle jututoa infolehelt paremal",
"Video conference ended by %(senderName)s": "%(senderName)s lõpetas video rühmakõne",
"Video conference updated by %(senderName)s": "%(senderName)s uuendas video rühmakõne",
"Video conference started by %(senderName)s": "%(senderName)s alustas video rühmakõne",
"End conference": "Lõpeta videokonverents",
"This will end the conference for everyone. Continue?": "Sellega lõpetame kõikide osalejate jaoks videokonverentsi. Nõus?",
"Ignored attempt to disable encryption": "Eirasin katset lõpetada krüptimise kasutamine",
"Offline encrypted messaging using dehydrated devices": "Võrguühenduseta kasutamiseks mõeldud krüptitud sõnumid dehydrated teenuse abil",
"Remove messages sent by others": "Kustuta teiste saadetud sõnumid",
"Failed to save your profile": "Sinu profiili salvestamine ei õnnestunud",
"The operation could not be completed": "Toimingut ei õnnestunud lõpetada"
}

View file

@ -2458,5 +2458,70 @@
"Failed to find the general chat for this community": "Non se atopou o chat xenérico para esta comunidade",
"Community settings": "Axustes da comunidade",
"User settings": "Axustes de usuaria",
"Community and user menu": "Menú de usuaria e comunidade"
"Community and user menu": "Menú de usuaria e comunidade",
"Prepends ( ͡° ͜ʖ ͡°) to a plain-text message": "Engade ( ͡° ͜ʖ ͡°) a unha mensaxe de texto-plano",
"Unknown App": "App descoñecida",
"%(count)s results|one": "%(count)s resultado",
"Room Info": "Info da sala",
"Apps": "Apps",
"Unpin app": "Desafixar app",
"Edit apps, bridges & bots": "Editar apps, pontes e bots",
"Add apps, bridges & bots": "Engadir apps, pontes e bots",
"Not encrypted": "Sen cifrar",
"About": "Acerca de",
"%(count)s people|other": "%(count)s persoas",
"%(count)s people|one": "%(count)s persoa",
"Show files": "Mostrar ficheiros",
"Room settings": "Axustes da sala",
"Take a picture": "Tomar unha foto",
"Pin to room": "Fixar a sala",
"You can only pin 2 apps at a time": "Só podes fixar 2 apps ó tempo",
"Unpin": "Desafixar",
"Group call modified by %(senderName)s": "Chamada en grupo modificada por %(senderName)s",
"Group call started by %(senderName)s": "Chamada en grupo iniciada por %(senderName)s",
"Group call ended by %(senderName)s": "Chamada en grupo rematada por %(senderName)s",
"Cross-signing is ready for use.": "A Sinatura-Cruzada está lista para usar.",
"Cross-signing is not set up.": "Non está configurada a Sinatura-Cruzada.",
"Backup version:": "Versión da copia:",
"Algorithm:": "Algoritmo:",
"Back up your encryption keys with your account data in case you lose access to your sessions. Your keys will be secured with a unique Recovery Key.": "Fai copia de apoio das chaves de cifrado para a continxencia de perder o acceso a todas as sesións. As chaves quedarán aseguradas cunha Chave de Recuperación única.",
"Backup key stored:": "Chave da copia gardada:",
"Backup key cached:": "Chave da copia na caché:",
"Secret storage:": "Almacenaxe segreda:",
"ready": "lista",
"not ready": "non lista",
"Secure Backup": "Copia Segura",
"End Call": "Finalizar chamada",
"Remove the group call from the room?": "Eliminar a chamada en grupo da sala?",
"You don't have permission to remove the call from the room": "Non tes permiso para eliminar a chamada da sala",
"Safeguard against losing access to encrypted messages & data": "Protéxete de perder o acceso a mensaxes e datos cifrados",
"not found in storage": "non atopado no almacenaxe",
"Start a conversation with someone using their name or username (like <userId/>).": "Inicia unha conversa con alguén usando o seu nome ou nome de usuaria (como <userId/>).",
"This won't invite them to %(communityName)s. To invite someone to %(communityName)s, click <a>here</a>": "Esto non as convidará a %(communityName)s. Para convidar alguén a %(communityName)s, preme <a>aquí</a>",
"Invite someone using their name, username (like <userId/>) or <a>share this room</a>.": "Convida a alguén usando o seu nome, nome de usuaria (como <userId/>) ou <a>comparte esta sala</a>.",
"Unable to set up keys": "Non se puideron configurar as chaves",
"Widgets": "Widgets",
"Edit widgets, bridges & bots": "Editar widgets, pontes e bots",
"Add widgets, bridges & bots": "Engade widgets, pontes e bots",
"You can only pin 2 widgets at a time": "Só podes fixar 2 widgets ó mesmo tempo",
"Minimize widget": "Minimizar widget",
"Maximize widget": "Maximizar widget",
"Your server requires encryption to be enabled in private rooms.": "O servidor require que actives o cifrado nas salas privadas.",
"Use the <a>Desktop app</a> to see all encrypted files": "Usa a <a>app de Escritorio</a> para ver todos os ficheiros cifrados",
"Use the <a>Desktop app</a> to search encrypted messages": "Usa a <a>app de Escritorio</a> para buscar mensaxes cifradas",
"This version of %(brand)s does not support viewing some encrypted files": "Esta versión de %(brand)s non soporta o visionado dalgúns ficheiros cifrados",
"This version of %(brand)s does not support searching encrypted messages": "Esta versión de %(brand)s non soporta a busca de mensaxes cifradas",
"Cannot create rooms in this community": "Non se poden crear salas nesta comunidade",
"You do not have permission to create rooms in this community.": "Non tes permiso para crear salas nesta comunidade.",
"Join the conference at the top of this room": "Únete á conferencia na ligazón arriba nesta sala",
"Join the conference from the room information card on the right": "Únete á conferencia desde a tarxeta con información da sala á dereita",
"Video conference ended by %(senderName)s": "Video conferencia rematada por %(senderName)s",
"Video conference updated by %(senderName)s": "Video conferencia actualizada por %(senderName)s",
"Video conference started by %(senderName)s": "Video conferencia iniciada por %(senderName)s",
"End conference": "Rematar conferencia",
"This will end the conference for everyone. Continue?": "Así finalizarás a conferencia para todas. ¿Adiante?",
"Ignored attempt to disable encryption": "Intento ignorado de desactivar o cifrado",
"Failed to save your profile": "Non se gardaron os cambios",
"The operation could not be completed": "Non se puido realizar a acción",
"Remove messages sent by others": "Eliminar mensaxes enviadas por outras"
}

View file

@ -31,7 +31,7 @@
"Default Device": "Alapértelmezett eszköz",
"Microphone": "Mikrofon",
"Camera": "Kamera",
"Advanced": "Speciális",
"Advanced": "Haladó",
"Always show message timestamps": "Üzenet időbélyeg folyamatos megjelenítése",
"Authentication": "Azonosítás",
"Failed to change password. Is your password correct?": "Nem sikerült megváltoztatni a jelszót. Helyesen írtad be a jelszavadat?",
@ -1070,7 +1070,7 @@
"Identity Server URL": "Azonosítási Szerver URL",
"Free": "Szabad",
"Join millions for free on the largest public server": "Milliók kapcsolódnak ingyen a legnagyobb nyilvános szerveren",
"Premium": "Pérmium",
"Premium": "Prémium",
"Premium hosting for organisations <a>Learn more</a>": "Prémium üzemeltetés szervezetek részére <a>Tudj meg többet</a>",
"Other": "Más",
"Find other public servers or use a custom server": "Találj más nyilvános szervereket vagy használj egyedi szervert",
@ -2457,5 +2457,72 @@
"Failed to find the general chat for this community": "Ehhez a közösséghez nem található általános csevegés",
"Community settings": "Közösségi beállítások",
"User settings": "Felhasználói beállítások",
"Community and user menu": "Közösségi és felhasználói menü"
"Community and user menu": "Közösségi és felhasználói menü",
"Prepends ( ͡° ͜ʖ ͡°) to a plain-text message": "( ͡° ͜ʖ ͡°) -t tesz a szöveg elejére",
"Unknown App": "Ismeretlen alkalmazás",
"Privacy": "Adatvédelem",
"%(count)s results|one": "%(count)s találat",
"Room Info": "Szoba információ",
"Apps": "Alkalmazások",
"Unpin app": "Alkalmazás kitűzésének megszüntetése",
"Edit apps, bridges & bots": "Alkalmazások, hidak és botok szerkesztése",
"Add apps, bridges & bots": "Alkalmazások, hidak és botok hozzáadása",
"Not encrypted": "Nem titkosított",
"About": "Névjegy",
"%(count)s people|other": "%(count)s személy",
"%(count)s people|one": "%(count)s személy",
"Show files": "Fájlok megjelenítése",
"Room settings": "Szoba beállítások",
"Take a picture": "Fénykép készítése",
"Pin to room": "A szobába kitűz",
"You can only pin 2 apps at a time": "Csak 2 alkalmazást tűzhetsz ki egyszerre",
"Unpin": "Leszed",
"Group call modified by %(senderName)s": "A konferenciahívást módosította: %(senderName)s",
"Group call started by %(senderName)s": "A konferenciahívást elindította: %(senderName)s",
"Group call ended by %(senderName)s": "A konferenciahívást befejezte: %(senderName)s",
"Cross-signing is ready for use.": "Eszközök közötti hitelesítés kész a használatra.",
"Cross-signing is not set up.": "Eszközök közötti hitelesítés nincs beállítva.",
"Backup version:": "Mentés verzió:",
"Algorithm:": "Algoritmus:",
"Back up your encryption keys with your account data in case you lose access to your sessions. Your keys will be secured with a unique Recovery Key.": "Ments el a titkosítási kulcsaidat a fiókadatokkal arra az esetre ha levesztenéd a hozzáférést a munkameneteidhez. A kulcsok egy egyedi visszaállítási kulccsal lesznek védve.",
"Backup key stored:": "Mentési kulcs tár:",
"Backup key cached:": "Mentési kulcs gyorsítótár:",
"Secret storage:": "Biztonsági tároló:",
"ready": "kész",
"not ready": "nem kész",
"Secure Backup": "Biztonsági Mentés",
"End Call": "Hívás befejezése",
"Remove the group call from the room?": "Törlöd a konferenciahívást a szobából?",
"You don't have permission to remove the call from the room": "A konferencia hívás törléséhez nincs jogosultságod",
"Start a conversation with someone using their name or username (like <userId/>).": "Indíts beszélgetést valakivel és használd hozzá a nevét vagy a felhasználói nevét (mint <userId/>).",
"This won't invite them to %(communityName)s. To invite someone to %(communityName)s, click <a>here</a>": "Ez nem hívja meg őket ebbe a közösségbe: %(communityName)s. Hogy meghívj valakit ebbe a közösségbe: %(communityName)s kattints <a>ide</a>",
"Invite someone using their name, username (like <userId/>) or <a>share this room</a>.": "Hívj meg valakit a nevével, felhasználói nevével (pl. <userId/>) vagy <a>oszd meg ezt a szobát</a>.",
"Add widgets, bridges & bots": "Widget-ek, hidak, és botok hozzáadása",
"You can only pin 2 widgets at a time": "Egyszerre csak 2 widget-et lehet kitűzni",
"Minimize widget": "Widget minimalizálása",
"Maximize widget": "Widget maximalizálása",
"Your server requires encryption to be enabled in private rooms.": "A szervered megköveteli, hogy a titkosítás be legyen kapcsolva a privát szobákban.",
"Unable to set up keys": "Nem sikerült a kulcsok beállítása",
"Safeguard against losing access to encrypted messages & data": "Biztosítás a titkosított üzenetek és adatokhoz való hozzáférés elvesztése ellen",
"not found in storage": "a tárban nem található",
"Widgets": "Kisalkalmazások",
"Edit widgets, bridges & bots": "Kisalkalmazások, hidak és botok szerkesztése",
"Use the <a>Desktop app</a> to see all encrypted files": "Minden titkosított fájl eléréséhez használd az <a>Asztali alkalmazást</a>",
"Use the <a>Desktop app</a> to search encrypted messages": "A titkosított üzenetek kereséséhez használd az <a>Asztali alkalmazást</a>",
"This version of %(brand)s does not support viewing some encrypted files": "%(brand)s ezen verziója nem minden titkosított fájl megjelenítését támogatja",
"This version of %(brand)s does not support searching encrypted messages": "%(brand)s ezen verziója nem támogatja a keresést a titkosított üzenetekben",
"Cannot create rooms in this community": "A közösségben nem lehet szobát készíteni",
"You do not have permission to create rooms in this community.": "A közösségben szoba létrehozásához nincs jogosultságod.",
"End conference": "Konferenciahívás befejezése",
"This will end the conference for everyone. Continue?": "Mindenki számára befejeződik a konferencia. Folytatod?",
"Offline encrypted messaging using dehydrated devices": "Kapcsolat nélküli titkosított üzenetküldés tartósított eszközökkel",
"Ignored attempt to disable encryption": "A titkosítás kikapcsolására tett kísérlet figyelmen kívül lett hagyva",
"Join the conference at the top of this room": "Csatlakozz a konferenciához a szoba tetején",
"Join the conference from the room information card on the right": "Csatlakozz a konferenciához a jobb oldali szoba információs panel segítségével",
"Video conference ended by %(senderName)s": "A videókonferenciát befejezte: %(senderName)s",
"Video conference updated by %(senderName)s": "A videókonferenciát frissítette: %(senderName)s",
"Video conference started by %(senderName)s": "A videókonferenciát elindította: %(senderName)s",
"Failed to save your profile": "A profilodat nem sikerült elmenteni",
"The operation could not be completed": "A műveletet nem lehetett befejezni",
"Remove messages sent by others": "Mások által küldött üzenetek törlése"
}

View file

@ -2452,5 +2452,76 @@
"Private rooms can be found and joined by invitation only. Public rooms can be found and joined by anyone in this community.": "Le stanze private possono essere trovate e visitate solo con invito. Le stanze pubbliche invece sono aperte a tutti i membri di questa comunità.",
"You might enable this if the room will only be used for collaborating with internal teams on your homeserver. This cannot be changed later.": "Dovresti attivarlo se questa stanza verrà usata solo per collaborazioni tra squadre interne nel tuo homeserver. Non può essere cambiato in seguito.",
"You might disable this if the room will be used for collaborating with external teams who have their own homeserver. This cannot be changed later.": "Dovresti disattivarlo se questa stanza verrà usata per collaborazioni con squadre esterne che hanno il loro homeserver. Non può essere cambiato in seguito.",
"Block anyone not part of %(serverName)s from ever joining this room.": "Blocca l'accesso alla stanza per chiunque non faccia parte di %(serverName)s."
"Block anyone not part of %(serverName)s from ever joining this room.": "Blocca l'accesso alla stanza per chiunque non faccia parte di %(serverName)s.",
"Prepends ( ͡° ͜ʖ ͡°) to a plain-text message": "Antepone ( ͡° ͜ʖ ͡°) ad un messaggio di testo",
"Group call modified by %(senderName)s": "Chiamata di gruppo modificata da %(senderName)s",
"Group call started by %(senderName)s": "Chiamata di gruppo iniziata da %(senderName)s",
"Group call ended by %(senderName)s": "Chiamata di gruppo terminata da %(senderName)s",
"Unknown App": "App sconosciuta",
"Cross-signing is ready for use.": "La firma incrociata è pronta all'uso.",
"Cross-signing is not set up.": "La firma incrociata non è impostata.",
"Backup version:": "Versione backup:",
"Algorithm:": "Algoritmo:",
"Back up your encryption keys with your account data in case you lose access to your sessions. Your keys will be secured with a unique Recovery Key.": "Fai il backup delle tue chiavi di crittografia con i dati del tuo account in caso perdessi l'accesso alle sessioni. Le tue chiavi saranno protette con una chiave di recupero univoca.",
"Backup key stored:": "Chiave di backup salvata:",
"Backup key cached:": "Chiave di backup in cache:",
"Secret storage:": "Archivio segreto:",
"ready": "pronto",
"not ready": "non pronto",
"Secure Backup": "Backup Sicuro",
"Privacy": "Privacy",
"%(count)s results|one": "%(count)s risultato",
"Room Info": "Info stanza",
"Apps": "App",
"Unpin app": "Sblocca app",
"Edit apps, bridges & bots": "Modifica app, bridge e bot",
"Add apps, bridges & bots": "Aggiungi app, bridge e bot",
"Not encrypted": "Non cifrato",
"About": "Al riguardo",
"%(count)s people|other": "%(count)s persone",
"%(count)s people|one": "%(count)s persona",
"Show files": "Mostra file",
"Room settings": "Impostazioni stanza",
"Take a picture": "Scatta una foto",
"Pin to room": "Fissa nella stanza",
"You can only pin 2 apps at a time": "Puoi fissare solo 2 app alla volta",
"There was an error updating your community. The server is unable to process your request.": "Si è verificato un errore nell'aggiornamento della comunità. Il server non riesce ad elaborare la richiesta.",
"Update community": "Aggiorna comunità",
"May include members not in %(communityName)s": "Può includere membri non in %(communityName)s",
"Start a conversation with someone using their name, username (like <userId/>) or email address. This won't invite them to %(communityName)s. To invite someone to %(communityName)s, click <a>here</a>.": "Inizia una conversazione con qualcuno usando il suo nome, nome utente (come <userId/>) o indirizzo email. Ciò non lo inviterà in %(communityName)s. Per invitare qualcuno in %(communityName)s, clicca <a>qui</a>.",
"Unpin": "Sblocca",
"Failed to find the general chat for this community": "Impossibile trovare la chat generale di questa comunità",
"Community settings": "Impostazioni comunità",
"User settings": "Impostazioni utente",
"Community and user menu": "Menu comunità e utente",
"End Call": "Chiudi chiamata",
"Remove the group call from the room?": "Rimuovere la chiamata di gruppo dalla stanza?",
"You don't have permission to remove the call from the room": "Non hai l'autorizzazione per rimuovere la chiamata dalla stanza",
"Safeguard against losing access to encrypted messages & data": "Proteggiti dalla perdita dei messaggi e dati crittografati",
"not found in storage": "non trovato nell'archivio",
"Widgets": "Widget",
"Edit widgets, bridges & bots": "Modifica widget, bridge e bot",
"Add widgets, bridges & bots": "Aggiungi widget, bridge e bot",
"You can only pin 2 widgets at a time": "Puoi fissare solo 2 widget alla volta",
"Minimize widget": "Riduci widget",
"Maximize widget": "Espandi widget",
"Your server requires encryption to be enabled in private rooms.": "Il tuo server richiede la crittografia attiva nelle stanze private.",
"Start a conversation with someone using their name or username (like <userId/>).": "Inizia una conversazione con qualcuno usando il suo nome o il nome utente (come <userId/>).",
"This won't invite them to %(communityName)s. To invite someone to %(communityName)s, click <a>here</a>": "Ciò non lo inviterà in %(communityName)s. Per invitare qualcuno in %(communityName)s, clicca <a>qui</a>",
"Invite someone using their name, username (like <userId/>) or <a>share this room</a>.": "Invita qualcuno usando il suo nome, nome utente (come <userId/>) o <a>condividi questa stanza</a>.",
"Unable to set up keys": "Impossibile impostare le chiavi",
"Use the <a>Desktop app</a> to see all encrypted files": "Usa <a>l'app desktop</a> per vedere tutti i file cifrati",
"Use the <a>Desktop app</a> to search encrypted messages": "Usa <a>l'app desktop</a> per cercare i messaggi cifrati",
"This version of %(brand)s does not support viewing some encrypted files": "Questa versione di %(brand)s non supporta la visualizzazione di alcuni file cifrati",
"This version of %(brand)s does not support searching encrypted messages": "Questa versione di %(brand)s non supporta la ricerca di messaggi cifrati",
"Cannot create rooms in this community": "Impossibile creare stanze in questa comunità",
"You do not have permission to create rooms in this community.": "Non hai i permessi per creare stanze in questa comunità.",
"Join the conference at the top of this room": "Entra nella conferenza in cima alla stanza",
"Join the conference from the room information card on the right": "Entra nella conferenza dalla scheda di informazione della stanza a destra",
"Video conference ended by %(senderName)s": "Conferenza video terminata da %(senderName)s",
"Video conference updated by %(senderName)s": "Conferenza video aggiornata da %(senderName)s",
"Video conference started by %(senderName)s": "Conferenza video iniziata da %(senderName)s",
"End conference": "Termina conferenza",
"This will end the conference for everyone. Continue?": "Verrà terminata la conferenza per tutti. Continuare?",
"Ignored attempt to disable encryption": "Tentativo di disattivare la crittografia ignorato"
}

View file

@ -126,7 +126,7 @@
"You are not receiving desktop notifications": "デスクトップ通知を受け取っていません",
"Update": "アップデート",
"Unable to fetch notification target list": "通知先リストを取得できませんでした",
"Uploaded on %(date)s by %(user)s": "%(date)s に %(user)s によりアップロードされました",
"Uploaded on %(date)s by %(user)s": "このファイルは %(date)s に %(user)s によりアップロードされました",
"Send Custom Event": "カスタムイベントを送信する",
"All notifications are currently disabled for all targets.": "現在すべての対象についての全通知が無効です。",
"Failed to send logs: ": "ログの送信に失敗しました: ",
@ -341,7 +341,7 @@
"Unable to connect to Homeserver. Retrying...": "ホームサーバーに接続できません。 再試行中...",
"Your browser does not support the required cryptography extensions": "お使いのブラウザは、必要な暗号化拡張機能をサポートしていません",
"Not a valid %(brand)s keyfile": "有効な%(brand)sキーファイルではありません",
"Authentication check failed: incorrect password?": "認証チェックに失敗しました: パスワードの間違い?",
"Authentication check failed: incorrect password?": "認証に失敗しました: パスワードの間違っている可能性があります。",
"Sorry, your homeserver is too old to participate in this room.": "申し訳ありませんが、あなたのホームサーバーはこの部屋に参加するには古すぎます。",
"Please contact your homeserver administrator.": "ホームサーバー管理者に連絡してください。",
"Failed to join room": "部屋に参加できませんでした",
@ -454,7 +454,7 @@
"(~%(count)s results)|one": "(~%(count)s 結果)",
"Join Room": "部屋に入る",
"Forget room": "部屋を忘れる",
"Share room": "部屋を共有する",
"Share room": "部屋を共有",
"Community Invites": "コミュニティへの招待",
"Invites": "招待",
"Unban": "ブロック解除",
@ -508,10 +508,10 @@
"When someone puts a URL in their message, a URL preview can be shown to give more information about that link such as the title, description, and an image from the website.": "メッセージにURLを入力すると、URLプレビューが表示され、タイトル、説明、ウェブサイトからの画像など、そのリンクに関する詳細情報が表示されます。",
"Error decrypting audio": "オーディオの復号化エラー",
"Error decrypting attachment": "添付ファイルの復号化エラー",
"Decrypt %(text)s": "%(text)s を解読する",
"Decrypt %(text)s": "%(text)s を復号",
"Download %(text)s": "%(text)s をダウンロード",
"Invalid file%(extra)s": "無効なファイル %(extra)s",
"Error decrypting image": "イメージの復号化エラー",
"Error decrypting image": "画像の復号中にエラーが発生しました",
"Error decrypting video": "動画の復号エラー",
"%(senderDisplayName)s changed the avatar for %(roomName)s": "%(senderDisplayName)s が %(roomName)s のアバターを変更しました",
"%(senderDisplayName)s removed the room avatar.": "%(senderDisplayName)s がルームアバターを削除しました。",
@ -783,7 +783,7 @@
"Connectivity to the server has been lost.": "サーバーへの接続が失われました。",
"Sent messages will be stored until your connection has returned.": "送信されたメッセージは、接続が復旧するまで保存されます。",
"Active call": "アクティブコール",
"There's no one else here! Would you like to <inviteText>invite others</inviteText> or <nowarnText>stop warning about the empty room</nowarnText>?": "他に誰もいません! <inviteText>他のユーザーを招待</inviteText>または<nowarnText>空の部屋に関する警告を停止しますか</nowarnText>?",
"There's no one else here! Would you like to <inviteText>invite others</inviteText> or <nowarnText>stop warning about the empty room</nowarnText>?": "この部屋には他に誰もいません!:<inviteText>他のユーザーを招待</inviteText>・<nowarnText>この警告を停止</nowarnText>",
"You seem to be uploading files, are you sure you want to quit?": "ファイルをアップロードしているようですが、中止しますか?",
"You seem to be in a call, are you sure you want to quit?": "通話中のようですが、本当にやめたいですか?",
"Search failed": "検索に失敗しました",
@ -1319,7 +1319,7 @@
"Set addresses for this room so users can find this room through your homeserver (%(localDomain)s)": "他のユーザーがあなたのホームサーバー (%(localDomain)s) を通じてこの部屋を見つけられるよう、アドレスを設定しましょう",
"Enter recovery key": "リカバリキーを入力",
"Verify this login": "このログインを承認",
"Signing In...": "サインインしています...",
"Signing In...": "サインイン...",
"If you've joined lots of rooms, this might take a while": "たくさんの部屋に参加している場合は、時間がかかる可能性があります",
"Confirm your identity by verifying this login from one of your other sessions, granting it access to encrypted messages.": "このログインを他のセッションで承認し、あなたの認証情報を確認すれば、暗号化されたメッセージへアクセスできるようになります。",
"This requires the latest %(brand)s on your other devices:": "最新版の %(brand)s が他のあなたのデバイスで実行されている必要があります:",
@ -1387,5 +1387,41 @@
"Your server": "あなたのサーバー",
"Matrix": "Matrix",
"Add a new server": "新しいサーバーを追加",
"Server name": "サーバー名"
"Server name": "サーバー名",
"Privacy": "プライバシー",
"Syncing...": "同期中...",
"<a>Log in</a> to your new account.": "新しいアカウントで<a>ログイン</a>する。",
"Use Recovery Key or Passphrase": "リカバリーキーまたはパスフレーズを使う",
"Use Recovery Key": "リカバリーキーを使う",
"%(brand)s Web": "%(brand)s ウェブ",
"%(brand)s Desktop": "%(brand)s デスクトップ",
"%(brand)s iOS": "%(brand)s iOS",
"%(brand)s Android": "%(brand)s Android",
"Your recovery key": "あなたのリカバリーキー",
"a few seconds ago": "数秒前",
"about a minute ago": "約1分前",
"about an hour ago": "約1時間前",
"about a day ago": "約1日前",
"a few seconds from now": "今から数秒前",
"about a minute from now": "今から約1分前",
"%(num)s minutes from now": "今から %(num)s 分前",
"about an hour from now": "今から約1時間前",
"%(num)s hours from now": "今から %(num)s 時間前",
"about a day from now": "今から約1日前",
"%(num)s days from now": "今から %(num)s 日前",
"%(name)s (%(userId)s)": "%(name)s (%(userId)s)",
"User %(user_id)s may or may not exist": "ユーザー %(user_id)s は存在しないとは限りません",
"Unknown App": "未知のアプリ",
"Room Info": "部屋の情報",
"About": "概要",
"%(count)s people|other": "%(count)s 人の参加者",
"%(count)s people|one": "%(count)s 人の参加者",
"Show files": "ファイルを表示",
"Room settings": "部屋の設定",
"Show image": "画像を表示",
"Upload files (%(current)s of %(total)s)": "ファイルのアップロード (%(current)s/%(total)s)",
"Upload files": "ファイルのアップロード",
"Upload all": "全てアップロード",
"No files visible in this room": "この部屋にファイルはありません",
"Attach files from chat or just drag and drop them anywhere in a room.": "チャットでファイルを添付するか、部屋のどこかにドラッグ&ドロップするとファイルを追加できます。"
}

View file

@ -2410,5 +2410,33 @@
"Can't connect to homeserver - please check your connectivity, ensure your <a>homeserver's SSL certificate</a> is trusted, and that a browser extension is not blocking requests.": "Yegguma ad yeqqen ɣer uqeddac agejdan - ttxil-k·m senqed tuqqna-inek·inem, tḍemneḍ belli <a>aselken n SSL n uqeddac agejdan</a> yettwattkal, rnu aseɣzan n yiminig-nni ur issewḥal ara isutar.",
"Your new account (%(newAccountId)s) is registered, but you're already logged into a different account (%(loggedInUserId)s).": "Amiḍan-ik·im amaynut (%(newAccountId)s) yettwaseklas, maca teqqneḍ yakan ɣer umiḍan wayeḍ (%(loggedInUserId)s).",
"Your recovery key is a safety net - you can use it to restore access to your encrypted messages if you forget your recovery passphrase.": "Tasarut-ik·im n tririt d azeṭṭa aɣelsan - tzemreḍ ad tt-tesqedceḍ i wakken ad d-terreḍ anekcum ɣer yiznan-ik·im yettwawgelhen ma yella tettuḍ tafyirt-ik·im tuffirt n tririt.",
"Trophy": "Arraz"
"Trophy": "Arraz",
"Prepends ( ͡° ͜ʖ ͡°) to a plain-text message": "Irennu ( ͡° ͜ʖ ͡°) ɣer yizen s uḍris arewway",
"Group call modified by %(senderName)s": "Asiwel n ugraw yettwabeddel sɣur %(senderName)s",
"Group call started by %(senderName)s": "Asiwel n ugraw yebda-t-id %(senderName)s",
"Group call ended by %(senderName)s": "Asiwel n ugraw yekfa-t %(senderName)s",
"Unknown App": "Asnas arussin",
"Cross-signing is ready for use.": "Azmul anmidag yewjed i useqdec.",
"Cross-signing is not set up.": "Azmul anmidag ur yettwasebded ara.",
"Backup version:": "Lqem n uklas:",
"Algorithm:": "Alguritm:",
"Back up your encryption keys with your account data in case you lose access to your sessions. Your keys will be secured with a unique Recovery Key.": "Kkes tisura-k•m n uwgelhen s yisefka n umiḍan-ik•im ma ur tezmireḍ ara ad tkecmeḍ ɣer tɣimiyin-ik•im. Tisura-k•m ad ttwaɣellsent s yiwet n tsarut n tiririt.",
"Backup key stored:": "Tasarut n uklas tettwaḥrez:",
"ready": "yewjed",
"not ready": "ur yewjid ara",
"Secure Backup": "Aklas aɣellsan",
"Privacy": "Tabaḍnit",
"Room Info": "Talɣut ɣef texxamt",
"Apps": "Isnasen",
"Not encrypted": "Ur yettwawgelhen ara",
"About": "Ɣef",
"%(count)s people|other": "%(count)s n yimdanen",
"%(count)s people|one": "%(count)s n umdan",
"Show files": "Sken ifuyla",
"Room settings": "Iɣewwaṛen n texxamt",
"Take a picture": "Ṭṭef tawlaft",
"There was an error updating your community. The server is unable to process your request.": "Tella-d tuccḍa deg uleqqem n temɣiwent-ik•im. Aqeddac ur izmir ara ad isesfer asuter.",
"Update community": "Leqqem tamɣiwent",
"May include members not in %(communityName)s": "Yezmer ad d-isseddu iɛeggalen ur nelli deg %(communityName)s",
"Start a conversation with someone using their name, username (like <userId/>) or email address. This won't invite them to %(communityName)s. To invite someone to %(communityName)s, click <a>here</a>.": "Bdu adiwenni akked ḥedd s useqdec n yisem-is, isem uffir (am <userId/>) neɣ tansa imayl. Aya ur ten-iecced ara ɣer %(communityName)s. Akked ad d-tnecdeḍ yiwen ɣer %(communityName)s sit ɣef <a>da</a>."
}

View file

@ -2027,5 +2027,6 @@
"To return to your account in future you need to set a password": "Zonder wachtwoord kunt u later niet tot uw account terugkeren",
"Restart": "Herstarten",
"People": "Tweegesprekken",
"Set a room address to easily share your room with other people.": "Geef het gesprek een adres om het gemakkelijk met anderen te kunnen delen."
"Set a room address to easily share your room with other people.": "Geef het gesprek een adres om het gemakkelijk met anderen te kunnen delen.",
"Invite people to join %(communityName)s": "Stuur uitnodigingen voor %(communityName)s"
}

View file

@ -167,7 +167,7 @@
"This email address was not found": "Este endereço de e-mail não foi encontrado",
"The remote side failed to pick up": "A pessoa não atendeu a chamada",
"This room is not recognised.": "Esta sala não é reconhecida.",
"This phone number is already in use": "Este número de telefone já está sendo usado",
"This phone number is already in use": "Este número de telefone já está em uso",
"To use it, just wait for autocomplete results to load and tab through them.": "Para usar este recurso, aguarde o carregamento dos resultados de autocompletar e então escolha entre as opções.",
"%(senderName)s unbanned %(targetName)s.": "%(senderName)s removeu o banimento de %(targetName)s.",
"Unable to capture screen": "Não foi possível capturar a imagem da tela",
@ -866,7 +866,7 @@
"Submit debug logs": "Submeter registros de depuração",
"Debug logs contain application usage data including your username, the IDs or aliases of the rooms or groups you have visited and the usernames of other users. They do not contain messages.": "Os registros de depuração contêm dados de uso do aplicativo, incluindo seu nome de usuário, os IDs ou aliases das salas ou comunidades que você visitou e os nomes de usuários de outros usuários. Eles não contêm mensagens.",
"Before submitting logs, you must <a>create a GitHub issue</a> to describe your problem.": "Antes de enviar os registros, você deve <a>criar um bilhete de erro no GitHub</a> para descrever seu problema.",
"Unable to load commit detail: %(msg)s": "Não é possível carregar os detalhes do commit: %(msg)s",
"Unable to load commit detail: %(msg)s": "Não foi possível carregar os detalhes do envio: %(msg)s",
"To avoid losing your chat history, you must export your room keys before logging out. You will need to go back to the newer version of %(brand)s to do this": "Para evitar perder seu histórico de bate-papo, você precisa exportar as chaves da sua sala antes de se desconectar. Quando entrar novamente, você precisará usar a versão mais atual do %(brand)s",
"Incompatible Database": "Banco de dados incompatível",
"Continue With Encryption Disabled": "Continuar com criptografia desativada",
@ -2295,5 +2295,39 @@
"Send %(count)s invites|other": "Enviar %(count)s convites",
"Send %(count)s invites|one": "Enviar %(count)s convite",
"Community ID: +<localpart />:%(domain)s": "ID da comunidade: +<localpart />:%(domain)s",
"Enter name": "Digitar nome"
"Enter name": "Digitar nome",
"End Call": "Encerrar chamada",
"Remove the group call from the room?": "Remover esta chamada em grupo da sala?",
"You don't have permission to remove the call from the room": "Você não tem permissão para remover a chamada da sala",
"Group call modified by %(senderName)s": "Chamada em grupo modificada por %(senderName)s",
"Group call started by %(senderName)s": "Chamada em grupo iniciada por %(senderName)s",
"Group call ended by %(senderName)s": "Chamada em grupo encerrada por %(senderName)s",
"Unknown App": "App desconhecido",
"eg: @bot:* or example.org": "por exemplo: @bot:* ou exemplo.org",
"Privacy": "Privacidade",
"Room Info": "Informações da sala",
"Widgets": "Widgets",
"Unpin app": "Desafixar app",
"Edit widgets, bridges & bots": "Editar widgets, pontes & bots",
"Add widgets, bridges & bots": "Adicionar widgets, pontes & bots",
"%(count)s people|other": "%(count)s pessoas",
"%(count)s people|one": "%(count)s pessoa",
"Show files": "Mostrar arquivos",
"Room settings": "Configurações da sala",
"Almost there! Is your other session showing the same shield?": "Quase lá! A sua outra sessão está mostrando o mesmo escudo?",
"Take a picture": "Tirar uma foto",
"Minimize widget": "Minimizar widget",
"Maximize widget": "Maximizar widget",
"Use the <a>Desktop app</a> to see all encrypted files": "Use o <a>app para Computador</a> para ver todos os arquivos criptografados",
"Use the <a>Desktop app</a> to search encrypted messages": "Use o <a>app para Computador</a> para buscar mensagens criptografadas",
"This version of %(brand)s does not support viewing some encrypted files": "Esta versão do %(brand)s não permite visualizar alguns arquivos criptografados",
"This version of %(brand)s does not support searching encrypted messages": "Esta versão do %(brand)s não permite buscar mensagens criptografadas",
"Information": "Informação",
"Add another email": "Adicionar outro e-mail",
"Invite people to join %(communityName)s": "Convidar pessoas para entrarem em %(communityName)s",
"There was an error creating your community. The name may be taken or the server is unable to process your request.": "Houve um erro ao criar sua comunidade. Ou o nome dela pode já estar em uso, ou o servidor não foi capaz de processar a sua solicitação.",
"What's the name of your community or team?": "Qual é o nome da sua comunidade ou equipe?",
"Add image (optional)": "Adicionar foto (opcional)",
"An image will help people identify your community.": "Uma foto ajudará as pessoas identificarem a sua comunidade.",
"Preview": "Visualizar"
}

View file

@ -1325,7 +1325,7 @@
"Invalid homeserver discovery response": "Неверный ответ при попытке обнаружения домашнего сервера",
"Failed to get autodiscovery configuration from server": "Не удалось получить конфигурацию автообнаружения с сервера",
"Invalid base_url for m.homeserver": "Неверный base_url для m.homeserver",
"Homeserver URL does not appear to be a valid Matrix homeserver": "URL-адрес сервера не является действительным URL-адресом сервера Матрица",
"Homeserver URL does not appear to be a valid Matrix homeserver": "URL-адрес домашнего сервера не является допустимым домашним сервером Matrix",
"Invalid identity server discovery response": "Неверный ответ на запрос идентификации сервера",
"Invalid base_url for m.identity_server": "Неверный base_url для m.identity_server",
"Identity server URL does not appear to be a valid identity server": "URL-адрес сервера идентификации не является действительным сервером идентификации",
@ -2411,7 +2411,7 @@
"Explore public rooms": "Просмотреть публичные комнаты",
"Uploading logs": "Загрузка журналов",
"Downloading logs": "Скачивание журналов",
"Can't see what youre looking for?": "Не видите то, что ищете?",
"Can't see what youre looking for?": "Не нашли, что искали?",
"Explore all public rooms": "Просмотреть все публичные комнаты",
"%(count)s results|other": "%(count)s результатов",
"Preparing to download logs": "Подготовка к загрузке журналов",
@ -2455,5 +2455,67 @@
"User settings": "Пользовательские настройки",
"Community and user menu": "Сообщество и меню пользователя",
"Privacy": "Конфиденциальность",
"Prepends ( ͡° ͜ʖ ͡°) to a plain-text message": "Добавляет ( ͡° ͜ʖ ͡°) к текстовому сообщению"
"Prepends ( ͡° ͜ʖ ͡°) to a plain-text message": "Добавляет ( ͡° ͜ʖ ͡°) к текстовому сообщению",
"Unknown App": "Неизвестное приложение",
"%(count)s results|one": "%(count)s результат",
"Room Info": "Информация о комнате",
"Apps": "Приложения",
"Unpin app": "Открепить приложение",
"Edit apps, bridges & bots": "Редактировать приложения, мосты и ботов",
"Add apps, bridges & bots": "Добавить приложения, мосты и ботов",
"Not encrypted": "Не зашифровано",
"About": "О приложение",
"%(count)s people|other": "%(count)s человек",
"%(count)s people|one": "%(count)s человек",
"Show files": "Показать файлы",
"Room settings": "Настройки комнаты",
"Take a picture": "Сделать снимок",
"Pin to room": "Закрепить в комнате",
"You can only pin 2 apps at a time": "Вы можете закрепить только 2 приложения за раз",
"Unpin": "Открепить",
"Cross-signing is ready for use.": "Кросс-подпись готова к использованию.",
"Cross-signing is not set up.": "Кросс-подпись не настроена.",
"Backup version:": "Версия резервной копии:",
"Algorithm:": "Алгоритм:",
"Back up your encryption keys with your account data in case you lose access to your sessions. Your keys will be secured with a unique Recovery Key.": "Сделайте резервную копию ключей шифрования с данными вашей учетной записи на случай, если вы потеряете доступ к своим сеансам. Ваши ключи будут защищены уникальным ключом восстановления.",
"Backup key stored:": "Резервный ключ сохранён:",
"Backup key cached:": "Резервный ключ кэширован:",
"Secret storage:": "Секретное хранилище:",
"ready": "готов",
"not ready": "не готов",
"Secure Backup": "Безопасное резервное копирование",
"Group call modified by %(senderName)s": "%(senderName)s изменил(а) групповой вызов",
"Group call started by %(senderName)s": "Групповой вызов начат %(senderName)s",
"Group call ended by %(senderName)s": "%(senderName)s завершил(а) групповой вызов",
"End Call": "Завершить звонок",
"Remove the group call from the room?": "Удалить групповой вызов из комнаты?",
"You don't have permission to remove the call from the room": "У вас нет разрешения на удаление звонка из комнаты",
"Safeguard against losing access to encrypted messages & data": "Защита от потери доступа к зашифрованным сообщениям и данным",
"not found in storage": "не найдено в хранилище",
"Widgets": "Виджеты",
"Edit widgets, bridges & bots": "Редактировать виджеты, мосты и ботов",
"Add widgets, bridges & bots": "Добавить виджеты, мосты и ботов",
"You can only pin 2 widgets at a time": "Вы можете закрепить только 2 виджета за раз",
"Minimize widget": "Свернуть виджет",
"Maximize widget": "Развернуть виджет",
"Your server requires encryption to be enabled in private rooms.": "Вашему серверу необходимо включить шифрование в приватных комнатах.",
"Start a conversation with someone using their name or username (like <userId/>).": "Начните разговор с кем-нибудь, используя его имя или имя пользователя (например, <userId/>).",
"This won't invite them to %(communityName)s. To invite someone to %(communityName)s, click <a>here</a>": "Это не пригласит их в %(communityName)s. Чтобы пригласить кого-нибудь в %(communityName)s, нажмите <a>здесь</a>",
"Invite someone using their name, username (like <userId/>) or <a>share this room</a>.": "Пригласите кого-нибудь, используя его имя, имя пользователя (например, <userId/>) или <a>поделитесь этой комнатой</a>.",
"Unable to set up keys": "Невозможно настроить ключи",
"Use the <a>Desktop app</a> to see all encrypted files": "Используйте <a>настольное приложение</a>, чтобы просмотреть все зашифрованные файлы",
"Use the <a>Desktop app</a> to search encrypted messages": "Используйте <a>настольное приложение</a> для поиска зашифрованных сообщений",
"This version of %(brand)s does not support viewing some encrypted files": "Эта версия %(brand)s не поддерживает просмотр некоторых зашифрованных файлов",
"This version of %(brand)s does not support searching encrypted messages": "Эта версия %(brand)s не поддерживает поиск зашифрованных сообщений",
"Cannot create rooms in this community": "Невозможно создать комнаты в этом сообществе",
"You do not have permission to create rooms in this community.": "У вас нет разрешения на создание комнат в этом сообществе.",
"Join the conference at the top of this room": "Присоединяйтесь к конференции в верхней части этой комнаты",
"Join the conference from the room information card on the right": "Присоединяйтесь к конференции, используя информационную карточку комнаты справа",
"Video conference ended by %(senderName)s": "%(senderName)s завершил(а) видеоконференцию",
"Video conference updated by %(senderName)s": "%(senderName)s обновил(а) видеоконференцию",
"Video conference started by %(senderName)s": "%(senderName)s начал(а) видеоконференцию",
"End conference": "Завершить конференцию",
"This will end the conference for everyone. Continue?": "Это завершит конференцию для всех. Продолжить?",
"Failed to save your profile": "Не удалось сохранить ваш профиль",
"The operation could not be completed": "Операция не может быть выполнена"
}

View file

@ -295,7 +295,7 @@
"A text message has been sent to %(msisdn)s": "Na číslo %(msisdn)s bola odoslaná textová správa",
"Please enter the code it contains:": "Prosím, zadajte kód z tejto správy:",
"Start authentication": "Spustiť overenie",
"powered by Matrix": "Poháňa Matrix",
"powered by Matrix": "používa protokol Matrix",
"Sign in with": "Na prihlásenie sa použije",
"Email address": "Emailová adresa",
"Sign in": "Prihlásiť sa",

View file

@ -11,5 +11,14 @@
"Custom Server Options": "Možnosti strežnika po meri",
"Your language of choice": "Vaš jezik po izbiri",
"Use Single Sign On to continue": "Uporabi Single Sign On za prijavo",
"Confirm adding this email address by using Single Sign On to prove your identity.": ""
"Confirm adding this email address by using Single Sign On to prove your identity.": "Potrdite dodajanje tega e-poštnega naslova z enkratno prijavo, da dokažete svojo identiteto.",
"Single Sign On": "Enkratna prijava",
"Confirm adding email": "Potrdi dodajanje e-poštnega naslova",
"Click the button below to confirm adding this email address.": "Kliknite gumb spodaj za potrditev dodajanja tega elektronskega naslova.",
"Confirm": "Potrdi",
"Add Email Address": "Dodaj e-poštni naslov",
"Confirm adding this phone number by using Single Sign On to prove your identity.": "Potrdite dodajanje te telefonske številke z enkratno prijavo, da dokažete svojo identiteto.",
"Confirm adding phone number": "Potrdi dodajanje telefonske številke",
"Click the button below to confirm adding this phone number.": "Pritisnite gumb spodaj da potrdite dodajanje te telefonske številke.",
"Add Phone Number": "Dodaj telefonsko številko"
}

View file

@ -2422,5 +2422,101 @@
"Error leaving room": "Gabim në dalje nga dhoma",
"Communities v2 prototypes. Requires compatible homeserver. Highly experimental - use with caution.": "Prototipe bashkësie v2. Lyp shërbyes Home të përputhshëm. Tejet eksperimentale - përdoreni me kujdes.",
"Explore rooms in %(communityName)s": "Eksploroni dhoma në %(communityName)s",
"Set up Secure Backup": "Ujdisni Kopjeruajtje të Sigurt"
"Set up Secure Backup": "Ujdisni Kopjeruajtje të Sigurt",
"Prepends ( ͡° ͜ʖ ͡°) to a plain-text message": "Një mesazhi tekst të thjeshtë vëri përpara ( ͡° ͜ʖ ͡°)",
"Unknown App": "Aplikacion i Panjohur",
"Cross-signing is ready for use, but secret storage is currently not being used to backup your keys.": "<em>Cross-signing</em> është gati për përdorim, por depozita e fshehtë sështë duke u përdorur për kopjeruajtje të kyçeve tuaj.",
"Privacy": "Privatësi",
"Explore community rooms": "Eksploroni dhoma bashkësie",
"%(count)s results|one": "%(count)s përfundim",
"Room Info": "Të dhëna Dhome",
"Apps": "Aplikacione",
"Unpin app": "Shfiksoje aplikacionin",
"Edit apps, bridges & bots": "Përpunoni aplikacione, ura & robotë",
"Add apps, bridges & bots": "Shtoni aplikacione, ura & robotë",
"Not encrypted": "Jo e fshehtëzuar",
"About": "Mbi",
"%(count)s people|other": "%(count)s vetë",
"%(count)s people|one": "%(count)s person",
"Show files": "Shfaq kartela",
"Room settings": "Rregullime dhome",
"Take a picture": "Bëni një foto",
"Pin to room": "Fiksoje te dhoma",
"You can only pin 2 apps at a time": "Mund të fiksoni vetëm 2 aplikacione në herë",
"Information": "Informacion",
"Add another email": "Shtoni email tjetër",
"People you know on %(brand)s": "Persona që njihni në %(brand)s",
"Send %(count)s invites|other": "Dërgo %(count)s ftesa",
"Send %(count)s invites|one": "Dërgo %(count)s ftesë",
"Invite people to join %(communityName)s": "Ftoni njerëz të marrin pjesë në %(communityName)s",
"There was an error creating your community. The name may be taken or the server is unable to process your request.": "Pati një gabim teksa krijohej bashkësia juaj. Emri mund të jetë i zënë ose shërbyesi sarrin të merret me kërkesën tuaj.",
"Community ID: +<localpart />:%(domain)s": "ID Bashkësie: +<localpart />:%(domain)s",
"Use this when referencing your community to others. The community ID cannot be changed.": "Përdoreni këtë kur ia referoheni bashkësinë tuaj të tjerëve. ID-ja e bashkësisë smund të ndryshohet.",
"You can change this later if needed.": "Këtë mund ta ndryshoni më vonë, nëse ju duhet.",
"What's the name of your community or team?": "Cili është emri i bashkësisë apo ekipit tuaj?",
"Enter name": "Jepni emër",
"Add image (optional)": "Shtoni figurë (në daçi)",
"An image will help people identify your community.": "Një figurë do ti ndihmojë njerëzit të identifikojnë bashkësinë tuaj.",
"Private rooms can be found and joined by invitation only. Public rooms can be found and joined by anyone.": "Dhoma private mund të gjenden dhe në to të hyhet vetëm me ftesë. Dhomat publike mund të gjenden dhe në to të hyhet nga kushdo.",
"Private rooms can be found and joined by invitation only. Public rooms can be found and joined by anyone in this community.": "Dhoma private mund të gjenden dhe në to të hyhet vetëm me ftesë. Dhomat publike mund të gjenden dhe në to të hyhet nga kushdo në këtë bashkësi.",
"You might enable this if the room will only be used for collaborating with internal teams on your homeserver. This cannot be changed later.": "Këtë mund ta aktivizonit, nëse kjo dhomë do të përdoret vetëm për bashkëpunim me ekipe të brendshëm në shërbyesin tuaj Home. Kjo smund të ndryshohet më vonë.",
"You might disable this if the room will be used for collaborating with external teams who have their own homeserver. This cannot be changed later.": "Këtë mund të çaktivizonit, nëse dhoma do të përdoret për bashkëpunim me ekipe të jashtëm që kanë shërbyesin e tyre Home. Kjo smund të ndryshohet më vonë.",
"Create a room in %(communityName)s": "Krijo një dhomë te %(communityName)s",
"Block anyone not part of %(serverName)s from ever joining this room.": "Bllokoji cilitdo që sështë pjesë e %(serverName)s marrjen pjesë në këtë dhomë.",
"There was an error updating your community. The server is unable to process your request.": "Pati një gabim teksa përditësohej bashkësia juaj. Shërbyesi sështë në gjendje të merret me kërkesën tuaj.",
"Update community": "Përditësoni bashkësinë",
"May include members not in %(communityName)s": "Mund të përfshijë anëtarë jo në %(communityName)s",
"Start a conversation with someone using their name, username (like <userId/>) or email address. This won't invite them to %(communityName)s. To invite someone to %(communityName)s, click <a>here</a>.": "Filloni një bisedë me dikë duke përdorur emrin e tij, emrin e përdoruesit (bie fjala, <userId/>) ose adresën e tij email. Kjo sdo të përbëjë ftesë për ta për tu bërë pjesë e %(communityName)s. Për të ftuar dikë te %(communityName)s, klikoni <a>këtu</a>.",
"Unpin": "Shfiksoje",
"Create community": "Krijoni bashkësi",
"Failed to find the general chat for this community": "Su arrit të gjendej fjalosja e përgjithshme për këtë bashkësi",
"Community settings": "Rregullime bashkësie",
"User settings": "Rregullime përdoruesi",
"Community and user menu": "Menu bashkësie dhe përdoruesish",
"End Call": "Përfundoje Thirrjen",
"Remove the group call from the room?": "Të hiqet nga dhoma thirrja e grupit?",
"You don't have permission to remove the call from the room": "Skeni leje të hiqni thirrjen nga dhoma",
"Group call modified by %(senderName)s": "Thirrja e grupit u modifikua nga %(senderName)s",
"Group call started by %(senderName)s": "Thirrje grupi e nisur nga %(senderName)s",
"Group call ended by %(senderName)s": "Thirrje grupi e përfunduar nga %(senderName)s",
"Safeguard against losing access to encrypted messages & data": "Mbrohuni nga humbja e hyrjes te mesazhe & të dhëna të fshehtëzuara",
"not found in storage": "su gjet në depozitë",
"Backup version:": "Version kopjeruajtjeje:",
"Algorithm:": "Algoritëm:",
"Back up your encryption keys with your account data in case you lose access to your sessions. Your keys will be secured with a unique Recovery Key.": "Kopjeruani kyçet tuaj të fshehtëzimit me të dhënat e llogarisë tuaj, për rastin kur humbni hyrje te sesionet tuaj. Kyçet tuaj do të sigurohen me një Kyç unik Rimarrjesh.",
"Backup key stored:": "Kyç kopjeruajtjesh i depozituar:",
"Backup key cached:": "Kyç kopjeruajtjesh i ruajtur në fshehtinë:",
"Secret storage:": "Depozitë e fshehtë:",
"ready": "gati",
"not ready": "jo gati",
"Secure Backup": "Kopjeruajtje e Sigurt",
"Widgets": "Widget-e",
"Edit widgets, bridges & bots": "Përpunoni widget-e, ura & robotë",
"Add widgets, bridges & bots": "Shtoni widget-e, ura & robotë",
"You can only pin 2 widgets at a time": "Mundeni të fiksoni vetëm 2 widget-e në herë",
"Minimize widget": "Minimizoje widget-in",
"Maximize widget": "Maksimizoj widget-in",
"Your server requires encryption to be enabled in private rooms.": "Shërbyesi juaj lyp që fshehtëzimi të jetë i aktivizuar në dhoma private.",
"Start a conversation with someone using their name or username (like <userId/>).": "Nisni një bisedë me dikë duke përdorur emrin e tij ose emrin e tij të përdoruesit (bie fjala, <userId/>).",
"This won't invite them to %(communityName)s. To invite someone to %(communityName)s, click <a>here</a>": "Kjo sdo ta ftojë te %(communityName)s. Që të ftoni dikë te %(communityName)s, klikoni <a>këtu</a>",
"Invite someone using their name, username (like <userId/>) or <a>share this room</a>.": "Ftoni dikë duke përdorur emrin e tij, emrin e tij të përdoruesit (bie fjala, <userId/>) ose <a>ndani me të këtë dhomë</a>.",
"Unable to set up keys": "Sarrihet të ujdisen kyçe",
"End conference": "Përfundoje konferencën",
"This will end the conference for everyone. Continue?": "Kjo do të mbyllë konferencën për këdo. Të vazhdohet?",
"Offline encrypted messaging using dehydrated devices": "Shkëmbim jashtë linje mesazhesh të fshehtëzuar duke përdorur pajisje të dehidratuara",
"Cross-signing is ready for use.": "“Cross-signing” është gati për përdorim.",
"Cross-signing is not set up.": "“Cross-signing” sështë ujdisur.",
"Remove messages sent by others": "Hiqi mesazhet e dërguar nga të tjerët",
"Ignored attempt to disable encryption": "U shpërfill përpjekje për të çaktivizuar fshehtëzimin",
"Join the conference at the top of this room": "Merrni pjesë në konferencë, në krye të kësaj dhome",
"Join the conference from the room information card on the right": "Merrni pjesë në konferencë që prej kartës së informacionit mbi dhomën, në të djathtë",
"Video conference ended by %(senderName)s": "Konferenca video u përfundua nga %(senderName)s",
"Video conference updated by %(senderName)s": "Konferenca video u përditësua nga %(senderName)s",
"Video conference started by %(senderName)s": "Konferenca video u fillua nga %(senderName)s",
"Use the <a>Desktop app</a> to see all encrypted files": "Që të shihni krejt kartelat e fshehtëzuara, përdorni <a>aplikacionin për Desktop</a>",
"Use the <a>Desktop app</a> to search encrypted messages": "Që të kërkoni te mesazhe të fshehtëzuar, përdorni <a>aplikacionin për Desktop</a>",
"This version of %(brand)s does not support viewing some encrypted files": "Ky version i %(brand)s nuk mbulon parjen për disa kartela të fshehtëzuara",
"This version of %(brand)s does not support searching encrypted messages": "Ky version i %(brand)s nuk mbulon kërkimin në mesazhe të fshehtëzuar",
"Cannot create rooms in this community": "Smund të krijohen dhoma në këtë bashkësi",
"You do not have permission to create rooms in this community.": "Skeni leje të krijoni dhoma në këtë bashkësi."
}

View file

@ -801,7 +801,7 @@
"Unpin Message": "Ta bort fastnålning",
"No pinned messages.": "Inga fastnålade meddelanden.",
"Pinned Messages": "Fastnålade meddelanden",
"Pin Message": "Nåla fast meddelande",
"Pin Message": "st meddelande",
"The exported file will allow anyone who can read it to decrypt any encrypted messages that you can see, so you should be careful to keep it secure. To help with this, you should enter a passphrase below, which will be used to encrypt the exported data. It will only be possible to import the data by using the same passphrase.": "Den exporterade filen kommer att låta de som kan läsa den att dekryptera alla krypterade meddelanden som du kan se, så du bör vara noga med att hålla den säker. För att hjälpa till med detta, bör du ange en lösenfras nedan, som kommer att användas för att kryptera exporterad data. Det kommer bara vara möjligt att importera data genom att använda samma lösenfras.",
"This process allows you to import encryption keys that you had previously exported from another Matrix client. You will then be able to decrypt any messages that the other client could decrypt.": "Denna process möjliggör import av krypteringsnycklar som tidigare exporterats från en annan Matrix-klient. Du kommer då kunna avkryptera alla meddelanden som den andra klienten kunde avkryptera.",
"The export file will be protected with a passphrase. You should enter the passphrase here, to decrypt the file.": "Den exporterade filen kommer vara skyddad med en lösenfras. Du måste ange lösenfrasen här, för att avkryptera filen.",
@ -2392,5 +2392,70 @@
"Toggle this dialog": "Växla den här dialogrutan",
"Move autocomplete selection up/down": "Flytta autokompletteringssektionen upp/ner",
"Cancel autocomplete": "Stäng autokomplettering",
"Prepends ( ͡° ͜ʖ ͡°) to a plain-text message": "Lägger till ( ͡° ͜ʖ ͡°) i början på ett textmeddelande"
"Prepends ( ͡° ͜ʖ ͡°) to a plain-text message": "Lägger till ( ͡° ͜ʖ ͡°) i början på ett textmeddelande",
"Unknown App": "Okänd app",
"%(count)s results|one": "%(count)s resultat",
"Room Info": "Rumsinfo",
"Apps": "Appar",
"Unpin app": "Avfäst app",
"Edit apps, bridges & bots": "Redigera appar, bryggor och bottar",
"Add apps, bridges & bots": "Lägg till appar, bryggor och bottar",
"Not encrypted": "Inte krypterad",
"About": "Om",
"%(count)s people|other": "%(count)s personer",
"%(count)s people|one": "%(count)s person",
"Show files": "Visa filer",
"Room settings": "Rumsinställningar",
"Take a picture": "Ta en bild",
"Pin to room": "Fäst i rum",
"You can only pin 2 apps at a time": "Du kan bara fästa två appar på en gång",
"Unpin": "Avfäst",
"Group call modified by %(senderName)s": "Gruppsamtal ändrat av %(senderName)s",
"Group call started by %(senderName)s": "Gruppsamtal startat av %(senderName)s",
"Group call ended by %(senderName)s": "Gruppsamtal avslutat av %(senderName)s",
"Cross-signing is ready for use.": "Korssignering är klart att användas.",
"Cross-signing is not set up.": "Korssignering är inte inställt.",
"Backup version:": "Version av säkerhetskopia:",
"Algorithm:": "Algoritm:",
"Back up your encryption keys with your account data in case you lose access to your sessions. Your keys will be secured with a unique Recovery Key.": "Säkerhetskopiera dina krypteringsnycklar med dina kontodata ifall du förlorar åtkomst till dina sessioner. Dina nycklar skyddas med en unik återställningsnyckel.",
"Backup key stored:": "Lagrad säkerhetskopieringsnyckel:",
"Backup key cached:": "Cachad säkerhetskopieringsnyckel:",
"Secret storage:": "Hemlig lagring:",
"ready": "klart",
"not ready": "inte klart",
"Secure Backup": "Säker säkerhetskopiering",
"End Call": "Avsluta samtal",
"Remove the group call from the room?": "Ta bort gruppsamtalet från rummet?",
"You don't have permission to remove the call from the room": "Du har inte behörighet från att ta bort samtalet från rummet",
"Safeguard against losing access to encrypted messages & data": "Skydda mot att förlora åtkomst till krypterade meddelanden och data",
"not found in storage": "hittades inte i lagring",
"Widgets": "Widgets",
"Edit widgets, bridges & bots": "Redigera widgets, bryggor och bottar",
"Add widgets, bridges & bots": "Lägg till widgets, bryggor och bottar",
"You can only pin 2 widgets at a time": "Du kan bara fästa 2 widgets i taget",
"Minimize widget": "Minimera widget",
"Maximize widget": "Maximera widget",
"Your server requires encryption to be enabled in private rooms.": "Din server kräver att kryptering ska användas i privata rum.",
"Start a conversation with someone using their name or username (like <userId/>).": "Starta en konversation med någon med deras namn eller användarnamn (som <userId/>).",
"This won't invite them to %(communityName)s. To invite someone to %(communityName)s, click <a>here</a>": "Detta kommer inte att bjuda in dem till %(communityName)s. För att bjuda in någon till %(communityName)s, klicka <a>här</a>",
"Invite someone using their name, username (like <userId/>) or <a>share this room</a>.": "Bjud in någon med deras namn eller användarnamn (som <userId/>) eller <a>dela det här rummet</a>.",
"Unable to set up keys": "Kunde inte ställa in nycklar",
"End conference": "Avsluta gruppsamtal",
"This will end the conference for everyone. Continue?": "Detta kommer att avsluta gruppsamtalet för alla. Fortsätt?",
"Offline encrypted messaging using dehydrated devices": "Krypterad meddelandehantering offline med hjälp av frystorkade enheter",
"Failed to save your profile": "Misslyckades att spara din profil",
"The operation could not be completed": "Operationen kunde inte slutföras",
"Remove messages sent by others": "Ta bort meddelanden skickade av andra",
"Ignored attempt to disable encryption": "Ignorerade försök att inaktivera kryptering",
"Join the conference at the top of this room": "Gå med i gruppsamtalet på toppen av det här rummet",
"Join the conference from the room information card on the right": "Gå med i gruppsamtalet ifrån informationskortet till höger",
"Video conference ended by %(senderName)s": "Videogruppsamtal avslutat av %(senderName)s",
"Video conference updated by %(senderName)s": "Videogruppsamtal uppdaterat av %(senderName)s",
"Video conference started by %(senderName)s": "Videogruppsamtal startat av %(senderName)s",
"Use the <a>Desktop app</a> to see all encrypted files": "Använd <a>skrivbordsappen</a> för att se alla krypterade filer",
"Use the <a>Desktop app</a> to search encrypted messages": "Använd <a>skrivbordsappen</a> söka bland krypterade meddelanden",
"This version of %(brand)s does not support viewing some encrypted files": "Den här versionen av %(brand)s stöder inte visning av vissa krypterade filer",
"This version of %(brand)s does not support searching encrypted messages": "Den här versionen av %(brand)s stöder inte sökning bland krypterade meddelanden",
"Cannot create rooms in this community": "Kan inte skapa rum i den här gemenskapen",
"You do not have permission to create rooms in this community.": "Du har inte behörighet att skapa rum i den här gemenskapen."
}

Some files were not shown because too many files have changed in this diff Show more