Compare commits

...
Author SHA1 Message Date
David Baker b44ab47a1a Report more errors to sentry
Mostly from ErrorView
2023-07-21 11:58:21 +01:00
Robin 0d89f497aa Merge pull request #1264 from robintown/settings-tab-order
Put the settings tabs back in the right order
2023-07-21 00:40:26 -04:00
Robin Townsend 8903930d56 Respond to review feedback 2023-07-21 00:00:04 -04:00
Robin Townsend 922d66d66b Merge branch 'livekit' into settings-tab-order 2023-07-20 23:54:47 -04:00
David Baker e4f2d86fcc Merge pull request #1182 from vector-im/dbkr/docker-use-container
Use docker container for docker compose file
2023-07-20 18:33:46 +01:00
David BakerandRobin 9200fac28e Fix URL
Co-authored-by: Robin <robin@robin.town>
2023-07-20 18:30:20 +01:00
David Baker a311c6ea3d Merge pull request #1272 from vector-im/dbkr/debug_logs
Enable debug logging
2023-07-19 14:04:58 +01:00
David Baker 50ba23b7ea Revert unintentional change 2023-07-18 16:59:51 +01:00
Timo b7f5069e98 set video enabled even if tracks are not yet initialized (#1273)
This could fix "muted on join issues" but could introduce issues where the buttons show unmuted even if no device is available.

Signed-off-by: Timo K <toger5@hotmail.de>
2023-07-18 17:41:54 +02:00
David Baker b6c6a6215e Merge pull request #1271 from vector-im/dbkr/fix_embedded
Fix embedded mode
2023-07-18 13:25:24 +01:00
David Baker 4eb9326bd2 Enable debug logging
Fixes https://github.com/vector-im/element-call/issues/1267
2023-07-17 19:33:29 +01:00
David Baker c15b2a62d5 Fix jsdoc 2023-07-17 19:22:22 +01:00
David Baker f28cf0ce69 Fix embedded mode
This was trying to get the room alias, which causes the config to be
read. We don't need the room alias here though, so pass the flag to
not return it.
2023-07-17 19:16:28 +01:00
David Baker d612c6a14c Remove redundant server url from readme example 2023-07-17 12:41:46 +01:00
David Baker 05505a6177 Merge pull request #1263 from vector-im/dbkr/jwt-service-more-logging
Add more logs to JWT service code
2023-07-17 10:14:32 +01:00
Robin b2be3575f2 Merge pull request #1265 from robintown/avatar-setting
Fix avatar field in profile settings being hidden
2023-07-15 20:43:40 -04:00
Robin 04d4d9af75 Merge pull request #1261 from robintown/fix-registration
Fix registration not logging you into the new account
2023-07-15 20:42:54 -04:00
Šimon Brandner 5d3eed033d Merge pull request #1177 from vector-im/SimonBrandner/feat/friendly-url 2023-07-15 09:51:54 +02:00
Šimon Brandner 723819b3d6 Merge remote-tracking branch 'upstream/livekit' into SimonBrandner/feat/friendly-url
Signed-off-by: Šimon Brandner <simon.bra.ag@gmail.com>
2023-07-15 09:48:08 +02:00
Robin Townsend 2d3d58cdc7 Fix avatar field in profile settings being hidden
It was being hidden when you didn't yet have an avatar set, which made it impossible to ever set one.
2023-07-14 14:48:50 -04:00
Robin Townsend 72eca769a4 Put the settings tabs back in the right order 2023-07-14 14:08:42 -04:00
David Baker be340ca4e4 Add more logs to JWT service code 2023-07-14 18:42:31 +01:00
Robin Townsend 3c30a5812b Fix registration not logging you into the new account 2023-07-14 12:41:21 -04:00
Robin 8cee8c8779 Merge pull request #1252 from RiotTranslateBot/weblate-element-call-element-call
Translations update from Weblate
2023-07-13 11:11:47 -04:00
Jozef Gaal 606a4e4bfc Translated using Weblate (Slovak)
Currently translated at 100.0% (118 of 118 strings)

Translation: Element Call/element-call
Translate-URL: https://translate.element.io/projects/element-call/element-call/sk/
2023-07-13 14:16:27 +00:00
Jeff Huang 69426176aa Translated using Weblate (Chinese (Traditional))
Currently translated at 100.0% (118 of 118 strings)

Translation: Element Call/element-call
Translate-URL: https://translate.element.io/projects/element-call/element-call/zh_Hant/
2023-07-13 14:16:27 +00:00
Avery 5f23c3b9c6 Translated using Weblate (Spanish)
Currently translated at 100.0% (118 of 118 strings)

Translation: Element Call/element-call
Translate-URL: https://translate.element.io/projects/element-call/element-call/es/
2023-07-13 14:16:27 +00:00
Priit Jõerüüt ed3c11da5a Translated using Weblate (Estonian)
Currently translated at 100.0% (118 of 118 strings)

Translation: Element Call/element-call
Translate-URL: https://translate.element.io/projects/element-call/element-call/et/
2023-07-13 14:16:27 +00:00
Ihor Hordiichuk 873d852609 Translated using Weblate (Ukrainian)
Currently translated at 100.0% (118 of 118 strings)

Translation: Element Call/element-call
Translate-URL: https://translate.element.io/projects/element-call/element-call/uk/
2023-07-13 14:16:27 +00:00
Glandos 285ae01b1f Translated using Weblate (French)
Currently translated at 100.0% (118 of 118 strings)

Translation: Element Call/element-call
Translate-URL: https://translate.element.io/projects/element-call/element-call/fr/
2023-07-13 14:16:27 +00:00
Linerly e36839f1ce Translated using Weblate (Indonesian)
Currently translated at 100.0% (118 of 118 strings)

Translation: Element Call/element-call
Translate-URL: https://translate.element.io/projects/element-call/element-call/id/
2023-07-13 14:16:27 +00:00
Vri 64becad7ed Translated using Weblate (German)
Currently translated at 100.0% (118 of 118 strings)

Translation: Element Call/element-call
Translate-URL: https://translate.element.io/projects/element-call/element-call/de/
2023-07-13 14:16:27 +00:00
Timo cac06f9852 Remove unecassary state for lobby device initialization (#1238)
* remove unecassary state

Signed-off-by: Timo K <toger5@hotmail.de>

* hotfix

Signed-off-by: Timo K <toger5@hotmail.de>

* remove video/audioAvailableAndEnabled
this is not required anymore since we disable the button.

Signed-off-by: Timo K <toger5@hotmail.de>

---------

Signed-off-by: Timo K <toger5@hotmail.de>
2023-07-13 11:20:24 +02:00
David Baker c99a400dd1 Prettier 2023-07-13 09:58:56 +01:00
David Baker 4a4c66caf2 Update README with new dev backend instructions. 2023-07-13 09:55:33 +01:00
David Baker a3ce8384db Merge pull request #1250 from vector-im/dbkr/merge_hotfixes
Merge v0.4.2 hotfixes
2023-07-12 18:11:48 +01:00
David Baker e264a71d1e Merge v0.4.2 hotfixes 2023-07-12 17:57:54 +01:00
Robin 89c326f0bb Merge pull request #1240 from RiotTranslateBot/weblate-element-call-element-call
Translations update from Weblate
2023-07-12 11:51:14 -04:00
Daniel Abramov eab2bc8ab5 Merge pull request #1173 from vector-im/lint-fixes
Enable stricter lints
2023-07-12 17:18:33 +02:00
Daniel Abramov 9820773136 A hack to fix problems with Matrix JS SDK
See https://github.com/matrix-org/matrix-js-sdk/pull/3593#issuecomment-1632725177
for more context on why it was necessary.
2023-07-12 16:11:01 +01:00
David Baker e4a96c8c0b Merge pull request #1246 from vector-im/dbkr/jwt_url
Update JWT service URL
2023-07-12 15:16:06 +01:00
Šimon Brandner bb2b60951e Merge pull request #1243 from vector-im/SimonBrandner/other/basic-ssl 2023-07-12 16:08:59 +02:00
David Baker d081dc0013 Update JWT service URL 2023-07-12 15:01:16 +01:00
Šimon Brandner 62d4084dcf Add support for accessing the web server from other devices
Signed-off-by: Šimon Brandner <simon.bra.ag@gmail.com>
2023-07-12 13:55:21 +02:00
Weblate 439fb23470 Update translation files
Updated by "Cleanup translation files" hook in Weblate.

Translation: Element Call/element-call
Translate-URL: https://translate.element.io/projects/element-call/element-call/
2023-07-11 23:00:16 +00:00
David Baker e8404d3514 Merge pull request #1239 from vector-im/dbkr/sfo
Spell SFU correctly
2023-07-11 18:19:21 +01:00
Daniel Abramov c87e06244e Update matrix-js-sdk to fix crypto issues 2023-07-11 17:46:17 +01:00
David Baker 8754651f5c Spell SFU correctly 2023-07-11 16:49:29 +01:00
Daniel Abramov 6bbd92a2bf Fix missing i18n 2023-07-11 16:02:58 +01:00
Daniel Abramov f3de341a4b Remove unnecessary usage of a roomIdOrAlias
In most cases the `roomId` was used despite the name of the variable.
2023-07-11 16:02:58 +01:00
Daniel Abramov 7f9157bae1 Fix lint errors that originate from JS SDK 2023-07-11 16:02:58 +01:00
Daniel Abramov 6d6e88c234 Fix unit tests after the lints 2023-07-11 16:02:58 +01:00
Daniel Abramov 91352fd08d Disable a lint for any for now in UserMenu 2023-07-11 16:02:58 +01:00
Daniel Abramov c9edfd9df4 Fix the CI pipeline command used for linting 2023-07-11 16:02:58 +01:00
Daniel Abramov 5c559bdca6 Re-generate i18 2023-07-11 16:02:58 +01:00
Daniel Abramov aaa9b7761c Use widget with ! instead of ?
It cannot be `null` in the mentioned contexts as discussed with Robin.
2023-07-11 16:02:58 +01:00
Daniel Abramov 259ef27bd0 Properly model the state of a group call load 2023-07-11 16:02:58 +01:00
Daniel Abramov 647599a39e Use useMemo in a proper way in ClientContext 2023-07-11 16:02:58 +01:00
Daniel Abramov 6998555ad9 Show UserMenu even if no avatar available 2023-07-11 16:02:58 +01:00
Daniel Abramov b68cd54049 Properly use sizeToClassName for a LinkButton 2023-07-11 16:02:58 +01:00
Daniel Abramov 2293cbf1f0 Use memoized callbacks when passing to components 2023-07-11 16:02:58 +01:00
Daniel Abramov caa3a7e8d0 Make useProfile() use of undefined explicit 2023-07-11 16:02:58 +01:00
Daniel Abramov 333b7cc041 Use more concise syntax for optional function call 2023-07-11 16:02:58 +01:00
Daniel Abramov e6047f8583 Remove redundant code when resolving an avatar 2023-07-11 16:02:58 +01:00
Daniel Abramov 0105162ffa Enable strict lints
An attempt to fix https://github.com/vector-im/element-call/issues/1132
2023-07-11 16:02:58 +01:00
Šimon Brandner 607e1b7b43 Fix getRoomUrl()
Signed-off-by: Šimon Brandner <simon.bra.ag@gmail.com>
2023-07-06 12:02:39 +02:00
Šimon Brandner c7258776c3 Merge remote-tracking branch 'upstream/livekit' into SimonBrandner/feat/friendly-url 2023-07-06 11:59:13 +02:00
David Baker 6117b42a4e Merge remote-tracking branch 'origin/livekit' into dbkr/docker-use-container 2023-07-04 19:06:40 +01:00
David Baker 6c8b96ed3d Use prebuilt image for docker compose 2023-07-04 18:57:35 +01:00
Šimon Brandner 8fbcc06cd8 Don't use the whole Location
Signed-off-by: Šimon Brandner <simon.bra.ag@gmail.com>
2023-07-03 20:05:08 +02:00
Šimon Brandner 0bba620451 Further id vs alias
Signed-off-by: Šimon Brandner <simon.bra.ag@gmail.com>
2023-07-03 19:32:25 +02:00
Šimon Brandner b08044c06d More fixes of id vs alias
Signed-off-by: Šimon Brandner <simon.bra.ag@gmail.com>
2023-07-03 19:30:38 +02:00
Šimon Brandner e1ef18093f Fix alias vs id + participants bug
Signed-off-by: Šimon Brandner <simon.bra.ag@gmail.com>
2023-07-03 19:23:26 +02:00
Šimon Brandner fdc41aaa50 Use friendly URLs
Signed-off-by: Šimon Brandner <simon.bra.ag@gmail.com>
2023-07-03 16:20:19 +02:00
Šimon Brandner 11785fc243 Avoid redirects
Signed-off-by: Šimon Brandner <simon.bra.ag@gmail.com>
2023-07-03 15:40:06 +02:00
Šimon Brandner f0c9a26242 Add jest-mock
Signed-off-by: Šimon Brandner <simon.bra.ag@gmail.com>
2023-07-03 14:03:29 +02:00
96 changed files with 1461 additions and 1223 deletions
+11 -1
View File
@@ -1,6 +1,16 @@
module.exports = { module.exports = {
plugins: ["matrix-org"], plugins: ["matrix-org"],
extends: ["plugin:matrix-org/react", "plugin:matrix-org/a11y", "prettier"], extends: [
"prettier",
"plugin:matrix-org/react",
"plugin:matrix-org/a11y",
"plugin:matrix-org/typescript",
],
parserOptions: {
ecmaVersion: 2018,
sourceType: "module",
project: ["./tsconfig.json"],
},
env: { env: {
browser: true, browser: true,
node: true, node: true,
+1 -1
View File
@@ -19,6 +19,6 @@ jobs:
- name: i18n - name: i18n
run: "yarn run i18n:check" run: "yarn run i18n:check"
- name: ESLint - name: ESLint
run: "yarn run lint:js" run: "yarn run lint:eslint"
- name: Type check - name: Type check
run: "yarn run lint:types" run: "yarn run lint:types"
+6 -10
View File
@@ -88,20 +88,16 @@ yarn dev
### Backend ### Backend
Add in you `.env` in root dir with: A docker compose file is provided to start a LiveKit server and auth
service for development. These use a test 'secret' published in this
repository, so this must be used only for local development and
**_never be exposed to the public Internet._**
```yaml To use it, add SFU parameter in your local config `./public/config.yml`:
# Develop backend settings:
LIVEKIT_KEY="devkey"
LIVEKIT_SECRET="secret"
```
Add SFU parameter in your local config `./public/config.yml`:
```yaml ```yaml
"livekit": { "livekit": {
"server_url": "ws://localhost:7880", "jwt_service_url": "http://localhost:8881"
"jwt_service_url": "http:/localhost:8881"
}, },
``` ```
+4 -7
View File
@@ -1,5 +1,3 @@
# LiveKit requires host networking, which is only available on Linux
# This compose will not function correctly on Mac or Windows
version: "3.9" version: "3.9"
networks: networks:
@@ -7,15 +5,14 @@ networks:
services: services:
auth-service: auth-service:
build: image: ghcr.io/vector-im/lk-jwt-service:latest-ci
context: ./backend/auth
container_name: auth-server
hostname: auth-server hostname: auth-server
ports: ports:
- 8881:8080 - 8881:8080
environment: environment:
- LIVEKIT_KEY=${LIVEKIT_KEY} - LIVEKIT_URL=ws://localhost:7880
- LIVEKIT_SECRET=${LIVEKIT_SECRET} - LIVEKIT_KEY=devkey
- LIVEKIT_SECRET=secret
deploy: deploy:
restart_policy: restart_policy:
condition: on-failure condition: on-failure
-15
View File
@@ -1,15 +0,0 @@
FROM golang:1.20-alpine
WORKDIR /app
COPY go.mod ./
COPY go.sum ./
RUN go mod download
COPY *.go ./
RUN go build -o /auth-server
EXPOSE 8080
CMD [ "/auth-server" ]
-20
View File
@@ -1,20 +0,0 @@
module vector-auth-server
go 1.20
require github.com/livekit/protocol v1.5.7
require (
github.com/go-jose/go-jose/v3 v3.0.0 // indirect
github.com/golang/protobuf v1.5.3 // indirect
github.com/twitchtv/twirp v8.1.3+incompatible // indirect
golang.org/x/crypto v0.9.0 // indirect
golang.org/x/exp v0.0.0-20230515195305-f3d0a9c9a5cc // indirect
golang.org/x/net v0.10.0 // indirect
golang.org/x/sys v0.8.0 // indirect
golang.org/x/text v0.9.0 // indirect
google.golang.org/genproto v0.0.0-20230403163135-c38d8f061ccd // indirect
google.golang.org/grpc v1.55.0 // indirect
google.golang.org/protobuf v1.30.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
-94
View File
@@ -1,94 +0,0 @@
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
github.com/eapache/channels v1.1.0 h1:F1taHcn7/F0i8DYqKXJnyhJcVpp2kgFcNePxXtnyu4k=
github.com/eapache/queue v1.1.0 h1:YOEu7KNc61ntiQlcEeUIoDTJ2o8mQznoNvUhiigpIqc=
github.com/frostbyte73/core v0.0.9 h1:AmE9GjgGpPsWk9ZkmY3HsYUs2hf2tZt+/W6r49URBQI=
github.com/gammazero/deque v0.2.1 h1:qSdsbG6pgp6nL7A0+K/B7s12mcCY/5l5SIUpMOl+dC0=
github.com/go-jose/go-jose/v3 v3.0.0 h1:s6rrhirfEP/CGIoc6p+PZAeogN2SxKav6Wp7+dyMWVo=
github.com/go-jose/go-jose/v3 v3.0.0/go.mod h1:RNkWWRld676jZEYoV3+XK8L2ZnNSvIsxFMht0mSX+u8=
github.com/go-logr/logr v1.2.4 h1:g01GSCwiDw2xSZfjJ2/T9M+S6pFdcNtFYsp+Y43HYDQ=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg=
github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
github.com/jxskiss/base62 v1.1.0 h1:A5zbF8v8WXx2xixnAKD2w+abC+sIzYJX+nxmhA6HWFw=
github.com/lithammer/shortuuid/v4 v4.0.0 h1:QRbbVkfgNippHOS8PXDkti4NaWeyYfcBTHtw7k08o4c=
github.com/livekit/mageutil v0.0.0-20230125210925-54e8a70427c1 h1:jm09419p0lqTkDaKb5iXdynYrzB84ErPPO4LbRASk58=
github.com/livekit/protocol v1.5.7 h1:jZeFQEmLuIhFblXDGPRCBbfjVJHb+YU7AsO+SMoXF70=
github.com/livekit/protocol v1.5.7/go.mod h1:ZaOnsvP+JS4s7vI1UO+JVdBagvvLp/lBXDAl2hkDS0I=
github.com/livekit/psrpc v0.3.0 h1:giBZsfM3CWA0oIYXofsMITbVQtyW7u/ES9sQmVspHPM=
github.com/mackerelio/go-osstat v0.2.4 h1:qxGbdPkFo65PXOb/F/nhDKpF2nGmGaCFDLXoZjJTtUs=
github.com/matttproud/golang_protobuf_extensions v1.0.4 h1:mmDVorXM7PCGKw94cs5zkfA9PSy5pEvNWRP0ET0TIVo=
github.com/nats-io/nats.go v1.25.0 h1:t5/wCPGciR7X3Mu8QOi4jiJaXaWM8qtkLu4lzGZvYHE=
github.com/nats-io/nkeys v0.4.4 h1:xvBJ8d69TznjcQl9t6//Q5xXuVhyYiSos6RPtvQNTwA=
github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw=
github.com/pion/datachannel v1.5.5 h1:10ef4kwdjije+M9d7Xm9im2Y3O6A6ccQb0zcqZcJew8=
github.com/pion/dtls/v2 v2.2.6 h1:yXMxKr0Skd+Ub6A8UqXTRLSywskx93ooMRHsQUtd+Z4=
github.com/pion/ice/v2 v2.3.4 h1:tjYjTLpWyZzUjpDnzk6T1y3oQyhyY2DiM2t095iDhyQ=
github.com/pion/interceptor v0.1.16 h1:0GDZrfNO+BmVNWymS31fMlVtPO2IJVBzy2Qq5XCYMIg=
github.com/pion/logging v0.2.2 h1:M9+AIj/+pxNsDfAT64+MAVgJO0rsyLnoJKCqf//DoeY=
github.com/pion/mdns v0.0.7 h1:P0UB4Sr6xDWEox0kTVxF0LmQihtCbSAdW0H2nEgkA3U=
github.com/pion/randutil v0.1.0 h1:CFG1UdESneORglEsnimhUjf33Rwjubwj6xfiOXBa3mA=
github.com/pion/rtcp v1.2.10 h1:nkr3uj+8Sp97zyItdN60tE/S6vk4al5CPRR6Gejsdjc=
github.com/pion/rtp v1.7.13 h1:qcHwlmtiI50t1XivvoawdCGTP4Uiypzfrsap+bijcoA=
github.com/pion/sctp v1.8.7 h1:JnABvFakZueGAn4KU/4PSKg+GWbF6QWbKTWZOSGJjXw=
github.com/pion/sdp/v3 v3.0.6 h1:WuDLhtuFUUVpTfus9ILC4HRyHsW6TdugjEX/QY9OiUw=
github.com/pion/srtp/v2 v2.0.14 h1:Glt0MqEvINrDxL+aanmK4DiFjvs+uN2iYc6XD/iKpoY=
github.com/pion/stun v0.5.2 h1:J/8glQnDV91dfk2+ZnGN0o9bUJgABhTNljwfQWByoXE=
github.com/pion/transport/v2 v2.2.0 h1:u5lFqFHkXLMXMzai8tixZDfVjb8eOjH35yCunhPeb1c=
github.com/pion/turn/v2 v2.1.0 h1:5wGHSgGhJhP/RpabkUb/T9PdsAjkGLS6toYz5HNzoSI=
github.com/pion/udp/v2 v2.0.1 h1:xP0z6WNux1zWEjhC7onRA3EwwSliXqu1ElUZAQhUP54=
github.com/pion/webrtc/v3 v3.2.4 h1:gWSx4dqQb77051qBT9ipDrOyP6/sGYcAQP3UPjM8pU8=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/prometheus/client_golang v1.15.1 h1:8tXpTmJbyH5lydzFPoxSIJ0J46jdh3tylbvM1xCv0LI=
github.com/prometheus/client_model v0.3.0 h1:UBgGFHqYdG/TPFD1B1ogZywDqEkwp3fBMvqdiQ7Xew4=
github.com/prometheus/common v0.42.0 h1:EKsfXEYo4JpWMHH5cg+KOUWeuJSov1Id8zGR8eeI1YM=
github.com/prometheus/procfs v0.9.0 h1:wzCHvIvM5SxWqYvwgVL7yJY8Lz3PKn49KQtpgMYJfhI=
github.com/redis/go-redis/v9 v9.0.4 h1:FC82T+CHJ/Q/PdyLW++GeCO+Ol59Y4T7R4jbgjvktgc=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.3 h1:RP3t2pwF7cMEbC1dqtB6poj3niw/9gnV4Cjg5oW5gtY=
github.com/twitchtv/twirp v8.1.3+incompatible h1:+F4TdErPgSUbMZMwp13Q/KgDVuI7HJXP61mNV3/7iuU=
github.com/twitchtv/twirp v8.1.3+incompatible/go.mod h1:RRJoFSAmTEh2weEqWtpPE3vFK5YBhA6bqp2l1kfCC5A=
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
go.uber.org/multierr v1.6.0 h1:y6IPFStTAIT5Ytl7/XYmHvzXQ7S3g/IeZW9hyZ5thw4=
go.uber.org/zap v1.24.0 h1:FiJd5l1UOLj0wCgbSE0rwwXHzEdAZS6hiiSnxJN/D60=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190911031432-227b76d455e7/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.9.0 h1:LF6fAI+IutBocDJ2OT0Q1g8plpYljMZ4+lty+dsqw3g=
golang.org/x/crypto v0.9.0/go.mod h1:yrmDGqONDYtNj3tH8X9dzUun2m2lzPa9ngI6/RUPGR0=
golang.org/x/exp v0.0.0-20230515195305-f3d0a9c9a5cc h1:mCRnTeVUjcrhlRmO0VK8a6k6Rrf6TF9htwo2pJVSjIU=
golang.org/x/exp v0.0.0-20230515195305-f3d0a9c9a5cc/go.mod h1:V1LtkGg67GoY2N1AnLN78QLrzxkLyJw7RJb1gzOOz9w=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.10.0 h1:X2//UzNDwYmtCLn7To6G58Wr6f5ahEAQgKNzv9Y951M=
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.8.0 h1:EBmGv8NaZBZTWvrbjNoL6HVt+IVy3QDQpJs7VRIw3tU=
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE=
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/genproto v0.0.0-20230403163135-c38d8f061ccd h1:sLpv7bNL1AsX3fdnWh9WVh7ejIzXdOc1RRHGeAmeStU=
google.golang.org/genproto v0.0.0-20230403163135-c38d8f061ccd/go.mod h1:UUQDJDOlWu4KYeJZffbWgBkS1YFobzKbLVfK69pe0Ak=
google.golang.org/grpc v1.55.0 h1:3Oj82/tFSCeUrRTg/5E/7d/W5A1tj6Ky1ABAuZuv5ag=
google.golang.org/grpc v1.55.0/go.mod h1:iYEXKGkEBhg1PjZQvoYEVPTDkHo1/bjTnfwTeGONTY8=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
google.golang.org/protobuf v1.30.0 h1:kPPoIgf3TsEvrm0PFe15JQ+570QVxYzEvvHqChK+cng=
google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
-98
View File
@@ -1,98 +0,0 @@
package main
import (
"encoding/json"
"log"
"net/http"
"os"
"time"
"github.com/livekit/protocol/auth"
)
type Handler struct {
key, secret string
}
func (h *Handler) handle(w http.ResponseWriter, r *http.Request) {
log.Printf("Request from %s", r.RemoteAddr)
// Set the CORS headers
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
// Handle preflight request (CORS)
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
roomName := r.URL.Query().Get("roomName")
name := r.URL.Query().Get("name")
identity := r.URL.Query().Get("identity")
log.Printf("roomName: %s, name: %s, identity: %s", roomName, name, identity)
if roomName == "" || name == "" || identity == "" {
w.WriteHeader(http.StatusBadRequest)
return
}
token, err := getJoinToken(h.key, h.secret, roomName, identity, name)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
res := Response{token}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(res)
}
func main() {
key := os.Getenv("LIVEKIT_KEY")
secret := os.Getenv("LIVEKIT_SECRET")
// Check if the key and secret are empty.
if key == "" || secret == "" {
log.Fatal("LIVEKIT_KEY and LIVEKIT_SECRET environment variables must be set")
}
log.Printf("LIVEKIT_KEY: %s and LIVEKIT_SECRET %s", key, secret)
handler := &Handler{
key: key,
secret: secret,
}
http.HandleFunc("/token", handler.handle)
log.Fatal(http.ListenAndServe(":8080", nil))
}
type Response struct {
Token string `json:"accessToken"`
}
func getJoinToken(apiKey, apiSecret, room, identity, name string) (string, error) {
at := auth.NewAccessToken(apiKey, apiSecret)
canPublish := true
canSubscribe := true
grant := &auth.VideoGrant{
RoomJoin: true,
RoomCreate: true,
CanPublish: &canPublish,
CanSubscribe: &canSubscribe,
Room: room,
}
at.AddGrant(grant).
SetIdentity(identity).
SetValidFor(time.Hour).
SetName(name)
return at.ToJWT()
}
+1 -1
View File
@@ -6,7 +6,7 @@
} }
}, },
"livekit": { "livekit": {
"livekit_service_url": "https://livekit.element.dev" "livekit_service_url": "https://livekit-jwt.call.element.dev"
}, },
"posthog": { "posthog": {
"api_key": "phc_rXGHx9vDmyEvyRxPziYtdVIv0ahEv8A9uLWFcCi1WcU", "api_key": "phc_rXGHx9vDmyEvyRxPziYtdVIv0ahEv8A9uLWFcCi1WcU",
+11 -5
View File
@@ -9,8 +9,9 @@
"build-storybook": "build-storybook", "build-storybook": "build-storybook",
"prettier:check": "prettier -c .", "prettier:check": "prettier -c .",
"prettier:format": "prettier -w .", "prettier:format": "prettier -w .",
"lint": "yarn lint:types && yarn lint:js", "lint": "yarn lint:types && yarn lint:eslint",
"lint:js": "eslint --max-warnings 0 src", "lint:eslint": "eslint --max-warnings 0 src",
"lint:eslint-fix": "eslint --max-warnings 0 src --fix",
"lint:types": "tsc", "lint:types": "tsc",
"i18n": "node_modules/i18next-parser/bin/cli.js", "i18n": "node_modules/i18next-parser/bin/cli.js",
"i18n:check": "node_modules/i18next-parser/bin/cli.js --fail-on-warnings --fail-on-update", "i18n:check": "node_modules/i18next-parser/bin/cli.js --fail-on-warnings --fail-on-update",
@@ -46,8 +47,10 @@
"@sentry/react": "^6.13.3", "@sentry/react": "^6.13.3",
"@sentry/tracing": "^6.13.3", "@sentry/tracing": "^6.13.3",
"@types/grecaptcha": "^3.0.4", "@types/grecaptcha": "^3.0.4",
"@types/react-router-dom": "^5.3.3",
"@types/sdp-transform": "^2.4.5", "@types/sdp-transform": "^2.4.5",
"@use-gesture/react": "^10.2.11", "@use-gesture/react": "^10.2.11",
"@vitejs/plugin-basic-ssl": "^1.0.1",
"@vitejs/plugin-react": "^4.0.1", "@vitejs/plugin-react": "^4.0.1",
"classnames": "^2.3.1", "classnames": "^2.3.1",
"color-hash": "^2.0.1", "color-hash": "^2.0.1",
@@ -57,7 +60,7 @@
"i18next-http-backend": "^1.4.4", "i18next-http-backend": "^1.4.4",
"livekit-client": "1.12.0", "livekit-client": "1.12.0",
"lodash": "^4.17.21", "lodash": "^4.17.21",
"matrix-js-sdk": "github:matrix-org/matrix-js-sdk#9ba44b96202e36d8bd6fbcff3222b7c70fc371d7", "matrix-js-sdk": "github:matrix-org/matrix-js-sdk#b698217445318f453e0b1086364a33113eaa85d9",
"matrix-widget-api": "^1.3.1", "matrix-widget-api": "^1.3.1",
"mermaid": "^8.13.8", "mermaid": "^8.13.8",
"normalize.css": "^8.0.1", "normalize.css": "^8.0.1",
@@ -69,13 +72,15 @@
"react-dom": "18", "react-dom": "18",
"react-i18next": "^11.18.6", "react-i18next": "^11.18.6",
"react-json-view": "^1.21.3", "react-json-view": "^1.21.3",
"react-router": "6",
"react-router-dom": "^5.2.0", "react-router-dom": "^5.2.0",
"react-use-clipboard": "^1.0.7", "react-use-clipboard": "^1.0.7",
"react-use-measure": "^2.1.1", "react-use-measure": "^2.1.1",
"sdp-transform": "^2.14.1", "sdp-transform": "^2.14.1",
"tinyqueue": "^2.0.3", "tinyqueue": "^2.0.3",
"unique-names-generator": "^4.6.0" "unique-names-generator": "^4.6.0",
"uuid": "9",
"@types/uuid": "9",
"@types/content-type": "^1.1.5"
}, },
"devDependencies": { "devDependencies": {
"@babel/core": "^7.16.5", "@babel/core": "^7.16.5",
@@ -101,6 +106,7 @@
"identity-obj-proxy": "^3.0.0", "identity-obj-proxy": "^3.0.0",
"jest": "^29.2.2", "jest": "^29.2.2",
"jest-environment-jsdom": "^29.3.1", "jest-environment-jsdom": "^29.3.1",
"jest-mock": "^29.5.0",
"prettier": "^2.6.2", "prettier": "^2.6.2",
"sass": "^1.42.1", "sass": "^1.42.1",
"storybook-builder-vite": "^0.1.12", "storybook-builder-vite": "^0.1.12",
+2 -2
View File
@@ -115,6 +115,6 @@
"Show connection stats": "Verbindungsstatistiken zeigen", "Show connection stats": "Verbindungsstatistiken zeigen",
"By clicking \"Join call now\", you agree to our <2>End User Licensing Agreement (EULA)</2>": "Mit einem Klick auf „Anruf beitreten“ akzeptierst du unseren <2>Endbenutzer-Lizenzvertrag (EULA)</2>", "By clicking \"Join call now\", you agree to our <2>End User Licensing Agreement (EULA)</2>": "Mit einem Klick auf „Anruf beitreten“ akzeptierst du unseren <2>Endbenutzer-Lizenzvertrag (EULA)</2>",
"By clicking \"Go\", you agree to our <2>End User Licensing Agreement (EULA)</2>": "Mit einem Klick auf „Los geht’s“ akzeptierst du unseren <2>Endbenutzer-Lizenzvertrag (EULA)</2>", "By clicking \"Go\", you agree to our <2>End User Licensing Agreement (EULA)</2>": "Mit einem Klick auf „Los geht’s“ akzeptierst du unseren <2>Endbenutzer-Lizenzvertrag (EULA)</2>",
"Element Call is temporarily not encrypted while we test scalability.": "Element Call ist temporär nicht verschlüsselt, während wir die Skalierbarkeit testen.", "This site is protected by ReCAPTCHA and the Google <2>Privacy Policy</2> and <6>Terms of Service</6> apply.<9></9>By clicking \"Register\", you agree to our <12>End User Licensing Agreement (EULA)</12>": "Diese Seite wird durch reCAPTCHA geschützt und es gelten Googles <2>Datenschutzerklärung</2> und <6>Nutzungsbedingungen</6>. <9></9>Mit einem Klick auf „Registrieren“ akzeptierst du unseren <2>Endbenutzer-Lizenzvertrag (EULA)</2>",
"This site is protected by ReCAPTCHA and the Google <2>Privacy Policy</2> and <6>Terms of Service</6> apply.<9></9>By clicking \"Register\", you agree to our <12>End User Licensing Agreement (EULA)</12>": "Diese Seite wird durch reCAPTCHA geschützt und es gelten Googles <2>Datenschutzerklärung</2> und <6>Nutzungsbedingungen</6>. <9></9>Mit einem Klick auf „Registrieren“ akzeptierst du unseren <2>Endbenutzer-Lizenzvertrag (EULA)</2>" "Element Call is temporarily not end-to-end encrypted while we test scalability.": "Element Call ist temporär nicht Ende-zu-Ende-verschlüsselt, während wir die Skalierbarkeit testen."
} }
+19 -1
View File
@@ -98,5 +98,23 @@
"Expose developer settings in the settings window.": "Muestra los ajustes de desarrollador en la ventana de ajustes.", "Expose developer settings in the settings window.": "Muestra los ajustes de desarrollador en la ventana de ajustes.",
"Developer Settings": "Ajustes de desarrollador", "Developer Settings": "Ajustes de desarrollador",
"By participating in this beta, you consent to the collection of anonymous data, which we use to improve the product. You can find more information about which data we track in our <2>Privacy Policy</2> and our <5>Cookie Policy</5>.": "Al participar en esta beta, consientes a la recogida de datos anónimos, los cuales usaremos para mejorar el producto. Puedes encontrar más información sobre que datos recogemos en nuestra <2>Política de privacidad</2> y en nuestra <5>Política sobre Cookies</5>.", "By participating in this beta, you consent to the collection of anonymous data, which we use to improve the product. You can find more information about which data we track in our <2>Privacy Policy</2> and our <5>Cookie Policy</5>.": "Al participar en esta beta, consientes a la recogida de datos anónimos, los cuales usaremos para mejorar el producto. Puedes encontrar más información sobre que datos recogemos en nuestra <2>Política de privacidad</2> y en nuestra <5>Política sobre Cookies</5>.",
"<0></0><1></1>You may withdraw consent by unchecking this box. If you are currently in a call, this setting will take effect at the end of the call.": "<0></0><1></1>Puedes retirar tu consentimiento desmarcando esta casilla. Si estás en una llamada, este ajuste se aplicará al final de esta." "<0></0><1></1>You may withdraw consent by unchecking this box. If you are currently in a call, this setting will take effect at the end of the call.": "<0></0><1></1>Puedes retirar tu consentimiento desmarcando esta casilla. Si estás en una llamada, este ajuste se aplicará al final de esta.",
"{{displayName}} is presenting": "{{displayName}} está presentando",
"<0>Thanks for your feedback!</0>": "<0>¡Gracias por tus comentarios!</0>",
"How did it go?": "¿Cómo ha ido?",
"This site is protected by ReCAPTCHA and the Google <2>Privacy Policy</2> and <6>Terms of Service</6> apply.<9></9>By clicking \"Register\", you agree to our <12>End User Licensing Agreement (EULA)</12>": "Este sitio está protegido por ReCAPTCHA y se aplican la <2>Política de Privacidad</2> y los <6>Términos de Servicio de Google.<9></9>Al hacer clic en \"Registrar\", aceptas nuestro <12>Contrato de Licencia de Usuario Final (CLUF)</12>",
"Show connection stats": "Mostrar estadísticas de conexión",
"Element Call is temporarily not end-to-end encrypted while we test scalability.": "Element Call no está encriptado de extremo a extremo de manera temporal mientras probamos la escalabilidad del servicio.",
"By clicking \"Go\", you agree to our <2>End User Licensing Agreement (EULA)</2>": "Al hacer clic en \"Comenzar\", aceptas nuestro <2>Contrato de Licencia de Usuario Final (CLUF)</2>",
"Thanks, we received your feedback!": "¡Gracias, hemos recibido tus comentarios!",
"If you are experiencing issues or simply would like to provide some feedback, please send us a short description below.": "Si tienes algún problema o simplemente quieres darnos tu opinión, por favor envíanos una breve descripción.",
"By clicking \"Join call now\", you agree to our <2>End User Licensing Agreement (EULA)</2>": "Al hacer clic en \"Unirse a la llamada ahora\", aceptas nuestro <2>Contrato de Licencia de Usuario Final (CLUF)</2>",
"<0>We'd love to hear your feedback so we can improve your experience.</0>": "<0>Nos encantaría conocer tu opinión para que podamos mejorar tu experiencia</0>",
"Feedback": "Danos tu opinión",
"Submit": "Enviar",
"{{count}} stars|one": "{{count}} estrella",
"{{count}} stars|other": "{{count}} estrellas",
"{{displayName}}, your call has ended.": "{{displayName}}, tu llamada ha finalizado.",
"Submitting…": "Enviando…",
"Your feedback": "Tus comentarios"
} }
+2 -2
View File
@@ -115,6 +115,6 @@
"{{displayName}} is presenting": "{{displayName}} on esitlemas", "{{displayName}} is presenting": "{{displayName}} on esitlemas",
"By clicking \"Go\", you agree to our <2>End User Licensing Agreement (EULA)</2>": "Klõpsides „Jätka“, nõustud sa meie <2>Lõppkasutaja litsentsilepinguga (EULA)</2>", "By clicking \"Go\", you agree to our <2>End User Licensing Agreement (EULA)</2>": "Klõpsides „Jätka“, nõustud sa meie <2>Lõppkasutaja litsentsilepinguga (EULA)</2>",
"By clicking \"Join call now\", you agree to our <2>End User Licensing Agreement (EULA)</2>": "Klõpsides „Liitu kõnega kohe“, nõustud sa meie <2>Lõppkasutaja litsentsilepinguga (EULA)</2>", "By clicking \"Join call now\", you agree to our <2>End User Licensing Agreement (EULA)</2>": "Klõpsides „Liitu kõnega kohe“, nõustud sa meie <2>Lõppkasutaja litsentsilepinguga (EULA)</2>",
"Element Call is temporarily not encrypted while we test scalability.": "Seni kuni me testime skaleeritavust, siis Element Call ajutiselt pole krüptitud.", "This site is protected by ReCAPTCHA and the Google <2>Privacy Policy</2> and <6>Terms of Service</6> apply.<9></9>By clicking \"Register\", you agree to our <12>End User Licensing Agreement (EULA)</12>": "Selles saidis on kasutusel ReCAPTCHA ja kehtivad Google'i <2>Privaatsuspoliitika</2> ning <6>Teenusetingimused</6>.<9></9>Klõpsides „Registreeru“, sa nõustud meie <12>Lõppkasutaja litsentsilepingu (EULA) tingimustega</12>",
"This site is protected by ReCAPTCHA and the Google <2>Privacy Policy</2> and <6>Terms of Service</6> apply.<9></9>By clicking \"Register\", you agree to our <12>End User Licensing Agreement (EULA)</12>": "Selles saidis on kasutusel ReCAPTCHA ja kehtivad Google'i <2>Privaatsuspoliitika</2> ning <6>Teenusetingimused</6>.<9></9>Klõpsides „Registreeru“, sa nõustud meie <12>Lõppkasutaja litsentsilepingu (EULA) tingimustega</12>" "Element Call is temporarily not end-to-end encrypted while we test scalability.": "Seni kuni me testime skaleeritavust, siis Element Call ajutiselt pole läbivalt krüptitud."
} }
+2 -1
View File
@@ -115,5 +115,6 @@
"Show connection stats": "Afficher les statistiques de la connexion", "Show connection stats": "Afficher les statistiques de la connexion",
"By clicking \"Join call now\", you agree to our <2>End User Licensing Agreement (EULA)</2>": "En cliquant sur « Rejoindre l’appel maintenant », vous acceptez notre <2>Contrat de Licence Utilisateur Final (CLUF)</2>", "By clicking \"Join call now\", you agree to our <2>End User Licensing Agreement (EULA)</2>": "En cliquant sur « Rejoindre l’appel maintenant », vous acceptez notre <2>Contrat de Licence Utilisateur Final (CLUF)</2>",
"By clicking \"Go\", you agree to our <2>End User Licensing Agreement (EULA)</2>": "En cliquant sur « Commencer », vous acceptez notre <2>Contrat de Licence Utilisateur Final (CLUF)</2>", "By clicking \"Go\", you agree to our <2>End User Licensing Agreement (EULA)</2>": "En cliquant sur « Commencer », vous acceptez notre <2>Contrat de Licence Utilisateur Final (CLUF)</2>",
"This site is protected by ReCAPTCHA and the Google <2>Privacy Policy</2> and <6>Terms of Service</6> apply.<9></9>By clicking \"Register\", you agree to our <12>End User Licensing Agreement (EULA)</12>": "Ce site est protégé par ReCAPTCHA, la <2>politique de confidentialité</2> et les <6>conditions d’utilisation</6> de Google s’appliquent.<9></9>En cliquant sur « S’enregistrer » vous acceptez également notre <12>Contrat de Licence Utilisateur Final (CLUF)</12>" "This site is protected by ReCAPTCHA and the Google <2>Privacy Policy</2> and <6>Terms of Service</6> apply.<9></9>By clicking \"Register\", you agree to our <12>End User Licensing Agreement (EULA)</12>": "Ce site est protégé par ReCAPTCHA, la <2>politique de confidentialité</2> et les <6>conditions d’utilisation</6> de Google s’appliquent.<9></9>En cliquant sur « S’enregistrer » vous acceptez également notre <12>Contrat de Licence Utilisateur Final (CLUF)</12>",
"Element Call is temporarily not end-to-end encrypted while we test scalability.": "Element Call n’est temporairement plus chiffré de bout en bout le temps de tester l’extensibilité."
} }
+1 -1
View File
@@ -116,5 +116,5 @@
"By clicking \"Go\", you agree to our <2>End User Licensing Agreement (EULA)</2>": "Dengan mengeklik \"Bergabung\", Anda menyetujui <2>Perjanjian Lisensi Pengguna Akhir (EULA)</2>", "By clicking \"Go\", you agree to our <2>End User Licensing Agreement (EULA)</2>": "Dengan mengeklik \"Bergabung\", Anda menyetujui <2>Perjanjian Lisensi Pengguna Akhir (EULA)</2>",
"This site is protected by ReCAPTCHA and the Google <2>Privacy Policy</2> and <6>Terms of Service</6> apply.<9></9>By clicking \"Register\", you agree to our <12>End User Licensing Agreement (EULA)</12>": "Situs ini dilindungi oleh reCAPTCHA dan <2>Kebijakan Privasi</2> dan <6>Ketentuan Layanan</6> Google berlaku.<9></9>Dengan mengeklik \"Daftar\", Anda menyetujui <12>Perjanjian Lisensi Pengguna Akhir (EULA)</12> kami", "This site is protected by ReCAPTCHA and the Google <2>Privacy Policy</2> and <6>Terms of Service</6> apply.<9></9>By clicking \"Register\", you agree to our <12>End User Licensing Agreement (EULA)</12>": "Situs ini dilindungi oleh reCAPTCHA dan <2>Kebijakan Privasi</2> dan <6>Ketentuan Layanan</6> Google berlaku.<9></9>Dengan mengeklik \"Daftar\", Anda menyetujui <12>Perjanjian Lisensi Pengguna Akhir (EULA)</12> kami",
"By clicking \"Join call now\", you agree to our <2>End User Licensing Agreement (EULA)</2>": "Dengan mengeklik \"Bergabung ke panggilan sekarang\", Anda menyetujui <2>Perjanjian Lisensi Pengguna Akhir (EULA)</2> kami", "By clicking \"Join call now\", you agree to our <2>End User Licensing Agreement (EULA)</2>": "Dengan mengeklik \"Bergabung ke panggilan sekarang\", Anda menyetujui <2>Perjanjian Lisensi Pengguna Akhir (EULA)</2> kami",
"Element Call is temporarily not encrypted while we test scalability.": "Element Call sementara tidak dienkripsi selagi kami menguji skalabilitas." "Element Call is temporarily not end-to-end encrypted while we test scalability.": "Element Call sementara tidak dienkripsi secara ujung ke ujung selagi kami menguji skalabilitas."
} }
+1 -1
View File
@@ -116,5 +116,5 @@
"By clicking \"Join call now\", you agree to our <2>End User Licensing Agreement (EULA)</2>": "Kliknutím na \"Pripojiť sa k hovoru teraz\" súhlasíte s našou <2>Licenčnou zmluvou s koncovým používateľom (EULA)</2>", "By clicking \"Join call now\", you agree to our <2>End User Licensing Agreement (EULA)</2>": "Kliknutím na \"Pripojiť sa k hovoru teraz\" súhlasíte s našou <2>Licenčnou zmluvou s koncovým používateľom (EULA)</2>",
"By clicking \"Go\", you agree to our <2>End User Licensing Agreement (EULA)</2>": "Kliknutím na tlačidlo \"Prejsť\" vyjadrujete súhlas s našou <2>Licenčnou zmluvou s koncovým používateľom (EULA)</2>", "By clicking \"Go\", you agree to our <2>End User Licensing Agreement (EULA)</2>": "Kliknutím na tlačidlo \"Prejsť\" vyjadrujete súhlas s našou <2>Licenčnou zmluvou s koncovým používateľom (EULA)</2>",
"This site is protected by ReCAPTCHA and the Google <2>Privacy Policy</2> and <6>Terms of Service</6> apply.<9></9>By clicking \"Register\", you agree to our <12>End User Licensing Agreement (EULA)</12>": "Táto stránka je chránená systémom ReCAPTCHA a platia na ňu <2>Pravidlá ochrany osobných údajov spoločnosti Google</2> a <6>Podmienky poskytovania služieb</6>.<9></9>Kliknutím na tlačidlo \"Registrovať sa\" súhlasíte s našou <12>Licenčnou zmluvou s koncovým používateľom (EULA)</12>", "This site is protected by ReCAPTCHA and the Google <2>Privacy Policy</2> and <6>Terms of Service</6> apply.<9></9>By clicking \"Register\", you agree to our <12>End User Licensing Agreement (EULA)</12>": "Táto stránka je chránená systémom ReCAPTCHA a platia na ňu <2>Pravidlá ochrany osobných údajov spoločnosti Google</2> a <6>Podmienky poskytovania služieb</6>.<9></9>Kliknutím na tlačidlo \"Registrovať sa\" súhlasíte s našou <12>Licenčnou zmluvou s koncovým používateľom (EULA)</12>",
"Element Call is temporarily not encrypted while we test scalability.": "Element Call nie je dočasne šifrovaný, kým testujeme škálovateľnosť." "Element Call is temporarily not end-to-end encrypted while we test scalability.": "Element Call nie je dočasne šifrovaný, kým testujeme škálovateľnosť."
} }
+1 -1
View File
@@ -116,5 +116,5 @@
"By clicking \"Go\", you agree to our <2>End User Licensing Agreement (EULA)</2>": "Натискаючи \"Далі\", ви погоджуєтеся з нашою <2>Ліцензійною угодою з кінцевим користувачем (EULA)</2>", "By clicking \"Go\", you agree to our <2>End User Licensing Agreement (EULA)</2>": "Натискаючи \"Далі\", ви погоджуєтеся з нашою <2>Ліцензійною угодою з кінцевим користувачем (EULA)</2>",
"By clicking \"Join call now\", you agree to our <2>End User Licensing Agreement (EULA)</2>": "Натискаючи \"Приєднатися до виклику зараз\", ви погоджуєтеся з нашою <2>Ліцензійною угодою з кінцевим користувачем (EULA)</2>", "By clicking \"Join call now\", you agree to our <2>End User Licensing Agreement (EULA)</2>": "Натискаючи \"Приєднатися до виклику зараз\", ви погоджуєтеся з нашою <2>Ліцензійною угодою з кінцевим користувачем (EULA)</2>",
"This site is protected by ReCAPTCHA and the Google <2>Privacy Policy</2> and <6>Terms of Service</6> apply.<9></9>By clicking \"Register\", you agree to our <12>End User Licensing Agreement (EULA)</12>": "Цей сайт захищений ReCAPTCHA і до нього застосовується <2>Політика приватності</2> і <6>Умови надання послуг</6> Google.<9></9>Натискаючи \"Зареєструватися\", ви погоджуєтеся з нашою <12>Ліцензійною угодою з кінцевим користувачем (EULA)</12>", "This site is protected by ReCAPTCHA and the Google <2>Privacy Policy</2> and <6>Terms of Service</6> apply.<9></9>By clicking \"Register\", you agree to our <12>End User Licensing Agreement (EULA)</12>": "Цей сайт захищений ReCAPTCHA і до нього застосовується <2>Політика приватності</2> і <6>Умови надання послуг</6> Google.<9></9>Натискаючи \"Зареєструватися\", ви погоджуєтеся з нашою <12>Ліцензійною угодою з кінцевим користувачем (EULA)</12>",
"Element Call is temporarily not encrypted while we test scalability.": "Element Call тимчасово не шифрується, поки ми тестуємо масштабованість." "Element Call is temporarily not end-to-end encrypted while we test scalability.": "Виклики Element тимчасово не захищаються наскрізним шифруванням, поки ми тестуємо масштабованість."
} }
+1 -1
View File
@@ -116,5 +116,5 @@
"By clicking \"Go\", you agree to our <2>End User Licensing Agreement (EULA)</2>": "點擊「前往」即表示您同意我們的<2>終端使用者授權協議 (EULA)</2>", "By clicking \"Go\", you agree to our <2>End User Licensing Agreement (EULA)</2>": "點擊「前往」即表示您同意我們的<2>終端使用者授權協議 (EULA)</2>",
"By clicking \"Join call now\", you agree to our <2>End User Licensing Agreement (EULA)</2>": "點擊「立刻加入通話」即表示您同意我們的<2>終端使用者授權協議 (EULA)</2>", "By clicking \"Join call now\", you agree to our <2>End User Licensing Agreement (EULA)</2>": "點擊「立刻加入通話」即表示您同意我們的<2>終端使用者授權協議 (EULA)</2>",
"This site is protected by ReCAPTCHA and the Google <2>Privacy Policy</2> and <6>Terms of Service</6> apply.<9></9>By clicking \"Register\", you agree to our <12>End User Licensing Agreement (EULA)</12>": "此網站被 ReCAPTCHA 保護,並適用 Google 的<2>隱私權政策</2>與<6>服務條款</6>。<9></9>點擊「註冊」即表示您同意我們的<12>終端使用者授權協議 (EULA)</12>", "This site is protected by ReCAPTCHA and the Google <2>Privacy Policy</2> and <6>Terms of Service</6> apply.<9></9>By clicking \"Register\", you agree to our <12>End User Licensing Agreement (EULA)</12>": "此網站被 ReCAPTCHA 保護,並適用 Google 的<2>隱私權政策</2>與<6>服務條款</6>。<9></9>點擊「註冊」即表示您同意我們的<12>終端使用者授權協議 (EULA)</12>",
"Element Call is temporarily not encrypted while we test scalability.": "在我們測試可擴展性時,Element Call 暫時未加密。" "Element Call is temporarily not end-to-end encrypted while we test scalability.": "在我們測試可擴展性時,Element Call 暫時未進行端到端加密。"
} }
+4 -5
View File
@@ -18,12 +18,12 @@ import { Suspense, useEffect, useState } from "react";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom"; import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import * as Sentry from "@sentry/react"; import * as Sentry from "@sentry/react";
import { OverlayProvider } from "@react-aria/overlays"; import { OverlayProvider } from "@react-aria/overlays";
import { History } from "history";
import { HomePage } from "./home/HomePage"; import { HomePage } from "./home/HomePage";
import { LoginPage } from "./auth/LoginPage"; import { LoginPage } from "./auth/LoginPage";
import { RegisterPage } from "./auth/RegisterPage"; import { RegisterPage } from "./auth/RegisterPage";
import { RoomPage } from "./room/RoomPage"; import { RoomPage } from "./room/RoomPage";
import { RoomRedirect } from "./room/RoomRedirect";
import { ClientProvider } from "./ClientContext"; import { ClientProvider } from "./ClientContext";
import { usePageFocusStyle } from "./usePageFocusStyle"; import { usePageFocusStyle } from "./usePageFocusStyle";
import { SequenceDiagramViewerPage } from "./SequenceDiagramViewerPage"; import { SequenceDiagramViewerPage } from "./SequenceDiagramViewerPage";
@@ -51,6 +51,8 @@ export default function App({ history }: AppProps) {
const errorPage = <CrashView />; const errorPage = <CrashView />;
return ( return (
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
<Router history={history}> <Router history={history}>
{loaded ? ( {loaded ? (
<Suspense fallback={null}> <Suspense fallback={null}>
@@ -68,14 +70,11 @@ export default function App({ history }: AppProps) {
<SentryRoute exact path="/register"> <SentryRoute exact path="/register">
<RegisterPage /> <RegisterPage />
</SentryRoute> </SentryRoute>
<SentryRoute path="/room/:roomId?">
<RoomPage />
</SentryRoute>
<SentryRoute path="/inspector"> <SentryRoute path="/inspector">
<SequenceDiagramViewerPage /> <SequenceDiagramViewerPage />
</SentryRoute> </SentryRoute>
<SentryRoute path="*"> <SentryRoute path="*">
<RoomRedirect /> <RoomPage />
</SentryRoute> </SentryRoute>
</Switch> </Switch>
</OverlayProvider> </OverlayProvider>
+4 -8
View File
@@ -16,7 +16,6 @@ limitations under the License.
import { useMemo, CSSProperties, HTMLAttributes, FC } from "react"; import { useMemo, CSSProperties, HTMLAttributes, FC } from "react";
import classNames from "classnames"; import classNames from "classnames";
import { MatrixClient } from "matrix-js-sdk/src/client";
import { getAvatarUrl } from "./matrix-utils"; import { getAvatarUrl } from "./matrix-utils";
import { useClient } from "./ClientContext"; import { useClient } from "./ClientContext";
@@ -59,9 +58,6 @@ function hashStringToArrIndex(str: string, arrLength: number) {
return sum % arrLength; return sum % arrLength;
} }
const resolveAvatarSrc = (client: MatrixClient, src: string, size: number) =>
src?.startsWith("mxc://") ? client && getAvatarUrl(client, src, size) : src;
interface Props extends HTMLAttributes<HTMLDivElement> { interface Props extends HTMLAttributes<HTMLDivElement> {
bgKey?: string; bgKey?: string;
src?: string; src?: string;
@@ -99,10 +95,10 @@ export const Avatar: FC<Props> = ({
[size] [size]
); );
const resolvedSrc = useMemo( const resolvedSrc = useMemo(() => {
() => resolveAvatarSrc(client, src, sizePx), if (!client || !src || !sizePx) return undefined;
[client, src, sizePx] return src.startsWith("mxc://") ? getAvatarUrl(client, src, sizePx) : src;
); }, [client, src, sizePx]);
const backgroundColor = useMemo(() => { const backgroundColor = useMemo(() => {
const index = hashStringToArrIndex( const index = hashStringToArrIndex(
+278 -259
View File
@@ -20,9 +20,9 @@ import {
useEffect, useEffect,
useState, useState,
createContext, createContext,
useMemo,
useContext, useContext,
useRef, useRef,
useMemo,
} from "react"; } from "react";
import { useHistory } from "react-router-dom"; import { useHistory } from "react-router-dom";
import { MatrixClient } from "matrix-js-sdk/src/client"; import { MatrixClient } from "matrix-js-sdk/src/client";
@@ -31,9 +31,9 @@ import { useTranslation } from "react-i18next";
import { ErrorView } from "./FullScreenView"; import { ErrorView } from "./FullScreenView";
import { import {
initClient,
CryptoStoreIntegrityError, CryptoStoreIntegrityError,
fallbackICEServerAllowed, fallbackICEServerAllowed,
initClient,
} from "./matrix-utils"; } from "./matrix-utils";
import { widget } from "./widget"; import { widget } from "./widget";
import { import {
@@ -47,140 +47,313 @@ import { Config } from "./config/Config";
declare global { declare global {
interface Window { interface Window {
matrixclient: MatrixClient; matrixclient: MatrixClient;
isPasswordlessUser: boolean; passwordlessUser: boolean;
} }
} }
export interface Session { export type ClientState = ValidClientState | ErrorState;
user_id: string;
device_id: string; export type ValidClientState = {
access_token: string; state: "valid";
authenticated?: AuthenticatedClient;
setClient: (params?: SetClientParams) => void;
};
export type AuthenticatedClient = {
client: MatrixClient;
isPasswordlessUser: boolean;
changePassword: (password: string) => Promise<void>;
logout: () => void;
};
export type ErrorState = {
state: "error";
error: Error;
};
export type SetClientParams = {
client: MatrixClient;
session: Session;
};
const ClientContext = createContext<ClientState | undefined>(undefined);
export const useClientState = () => useContext(ClientContext);
export function useClient(): {
client?: MatrixClient;
setClient?: (params?: SetClientParams) => void;
} {
let client;
let setClient;
const clientState = useClientState();
if (clientState?.state === "valid") {
client = clientState.authenticated?.client;
setClient = clientState.setClient;
}
return { client, setClient };
}
// Plain representation of the `ClientContext` as a helper for old components that expected an object with multiple fields.
export function useClientLegacy(): {
client?: MatrixClient;
setClient?: (params?: SetClientParams) => void;
passwordlessUser: boolean; passwordlessUser: boolean;
tempPassword?: string; loading: boolean;
authenticated: boolean;
logout?: () => void;
error?: Error;
} {
const clientState = useClientState();
let client;
let setClient;
let passwordlessUser = false;
let loading = true;
let error;
let authenticated = false;
let logout;
if (clientState?.state === "valid") {
client = clientState.authenticated?.client;
setClient = clientState.setClient;
passwordlessUser = clientState.authenticated?.isPasswordlessUser ?? false;
loading = false;
authenticated = client !== undefined;
logout = clientState.authenticated?.logout;
} else if (clientState?.state === "error") {
error = clientState.error;
loading = false;
}
return {
client,
setClient,
passwordlessUser,
loading,
authenticated,
logout,
error,
};
} }
const loadChannel = const loadChannel =
"BroadcastChannel" in window ? new BroadcastChannel("load") : null; "BroadcastChannel" in window ? new BroadcastChannel("load") : null;
const loadSession = (): Session => {
const data = localStorage.getItem("matrix-auth-store");
if (data) return JSON.parse(data);
return null;
};
const saveSession = (session: Session) =>
localStorage.setItem("matrix-auth-store", JSON.stringify(session));
const clearSession = () => localStorage.removeItem("matrix-auth-store");
interface ClientState {
loading: boolean;
isAuthenticated: boolean;
isPasswordlessUser: boolean;
client: MatrixClient;
userName: string;
changePassword: (password: string) => Promise<void>;
logout: () => void;
setClient: (client: MatrixClient, session: Session) => void;
error?: Error;
}
const ClientContext = createContext<ClientState>(null);
type ClientProviderState = Omit<
ClientState,
"changePassword" | "logout" | "setClient"
> & { error?: Error };
interface Props { interface Props {
children: JSX.Element; children: JSX.Element;
} }
export const ClientProvider: FC<Props> = ({ children }) => { export const ClientProvider: FC<Props> = ({ children }) => {
const history = useHistory(); const history = useHistory();
const initializing = useRef(false);
const [
{ loading, isAuthenticated, isPasswordlessUser, client, userName, error },
setState,
] = useState<ClientProviderState>({
loading: true,
isAuthenticated: false,
isPasswordlessUser: false,
client: undefined,
userName: null,
error: undefined,
});
const [initClientState, setInitClientState] = useState<
InitResult | undefined
>(undefined);
const initializing = useRef(false);
useEffect(() => { useEffect(() => {
// In case the component is mounted, unmounted, and remounted quickly (as // In case the component is mounted, unmounted, and remounted quickly (as
// React does in strict mode), we need to make sure not to doubly initialize // React does in strict mode), we need to make sure not to doubly initialize
// the client // the client.
if (initializing.current) return; if (initializing.current) return;
initializing.current = true; initializing.current = true;
const init = async (): Promise< loadClient()
Pick<ClientProviderState, "client" | "isPasswordlessUser"> .then((maybeClient) => {
> => { if (!maybeClient) {
logger.error("Failed to initialize client");
return;
}
setInitClientState(maybeClient);
})
.catch((err) => logger.error(err))
.finally(() => (initializing.current = false));
}, []);
const changePassword = useCallback(
async (password: string) => {
const session = loadSession();
if (!initClientState?.client || !session) {
return;
}
await initClientState.client.setPassword(
{
type: "m.login.password",
identifier: {
type: "m.id.user",
user: session.user_id,
},
user: session.user_id,
password: session.tempPassword,
},
password
);
saveSession({ ...session, passwordlessUser: false });
setInitClientState({
client: initClientState.client,
passwordlessUser: false,
});
},
[initClientState?.client]
);
const setClient = useCallback(
(clientParams?: SetClientParams) => {
const oldClient = initClientState?.client;
const newClient = clientParams?.client;
if (oldClient && oldClient !== newClient) {
oldClient.stopClient();
}
if (clientParams) {
saveSession(clientParams.session);
setInitClientState({
client: clientParams.client,
passwordlessUser: clientParams.session.passwordlessUser,
});
} else {
clearSession();
setInitClientState(undefined);
}
},
[initClientState?.client]
);
const logout = useCallback(async () => {
const client = initClientState?.client;
if (!client) {
return;
}
await client.logout(true);
await client.clearStores();
clearSession();
setInitClientState(undefined);
history.push("/");
PosthogAnalytics.instance.setRegistrationType(RegistrationType.Guest);
}, [history, initClientState?.client]);
const { t } = useTranslation();
// To protect against multiple sessions writing to the same storage
// simultaneously, we send a broadcast message that shuts down all other
// running instances of the app. This isn't necessary if the app is running in
// a widget though, since then it'll be mostly stateless.
useEffect(() => {
if (!widget) loadChannel?.postMessage({});
}, []);
const [alreadyOpenedErr, setAlreadyOpenedErr] = useState<Error | undefined>(
undefined
);
useEventTarget(
loadChannel,
"message",
useCallback(() => {
initClientState?.client.stopClient();
setAlreadyOpenedErr(
translatedError("This application has been opened in another tab.", t)
);
}, [initClientState?.client, setAlreadyOpenedErr, t])
);
const state: ClientState = useMemo(() => {
if (alreadyOpenedErr) {
return { state: "error", error: alreadyOpenedErr };
}
let authenticated = undefined;
if (initClientState) {
authenticated = {
client: initClientState.client,
isPasswordlessUser: initClientState.passwordlessUser,
changePassword,
logout,
};
}
return { state: "valid", authenticated, setClient };
}, [alreadyOpenedErr, changePassword, initClientState, logout, setClient]);
useEffect(() => {
if (!initClientState) {
return;
}
window.matrixclient = initClientState.client;
window.passwordlessUser = initClientState.passwordlessUser;
if (PosthogAnalytics.hasInstance())
PosthogAnalytics.instance.onLoginStatusChanged();
}, [initClientState]);
if (alreadyOpenedErr) {
return <ErrorView error={alreadyOpenedErr} />;
}
return (
<ClientContext.Provider value={state}>{children}</ClientContext.Provider>
);
};
type InitResult = {
client: MatrixClient;
passwordlessUser: boolean;
};
async function loadClient(): Promise<InitResult> {
if (widget) { if (widget) {
// We're inside a widget, so let's engage *matryoshka mode* // We're inside a widget, so let's engage *matryoshka mode*
logger.log("Using a matryoshka client"); logger.log("Using a matryoshka client");
const client = await widget.client;
return { return {
client: await widget.client, client,
isPasswordlessUser: false, passwordlessUser: false,
}; };
} else { } else {
// We're running as a standalone application // We're running as a standalone application
try { try {
const session = loadSession(); const session = loadSession();
if (!session) return { client: undefined, isPasswordlessUser: false }; if (!session) {
throw new Error("No session stored");
}
logger.log("Using a standalone client"); logger.log("Using a standalone client");
/* eslint-disable camelcase */ /* eslint-disable camelcase */
const { user_id, device_id, access_token, passwordlessUser } = const { user_id, device_id, access_token, passwordlessUser } = session;
session; const initClientParams = {
baseUrl: Config.defaultHomeserverUrl()!,
const livekit = Config.get().livekit;
const foci = livekit
? [
{
livekitServiceUrl: livekit.livekit_service_url,
},
]
: undefined;
try {
return {
client: await initClient(
{
baseUrl: Config.defaultHomeserverUrl(),
accessToken: access_token, accessToken: access_token,
userId: user_id, userId: user_id,
deviceId: device_id, deviceId: device_id,
fallbackICEServerAllowed: fallbackICEServerAllowed, fallbackICEServerAllowed: fallbackICEServerAllowed,
foci, livekitServiceURL: Config.get().livekit!.livekit_service_url,
}, };
true
), try {
isPasswordlessUser: passwordlessUser, const client = await initClient(initClientParams, true);
return {
client,
passwordlessUser,
}; };
} catch (err) { } catch (err) {
if (err instanceof CryptoStoreIntegrityError) { if (err instanceof CryptoStoreIntegrityError) {
// We can't use this session anymore, so let's log it out // We can't use this session anymore, so let's log it out
try { try {
const client = await initClient( const client = await initClient(initClientParams, false); // Don't need the crypto store just to log out)
{
baseUrl: Config.defaultHomeserverUrl(),
accessToken: access_token,
userId: user_id,
deviceId: device_id,
fallbackICEServerAllowed: fallbackICEServerAllowed,
foci,
},
false // Don't need the crypto store just to log out
);
await client.logout(true); await client.logout(true);
} catch (err_) { } catch (err) {
logger.warn( logger.warn(
"The previous session was lost, and we couldn't log it out, " + "The previous session was lost, and we couldn't log it out, " +
err +
"either" "either"
); );
} }
@@ -193,178 +366,24 @@ export const ClientProvider: FC<Props> = ({ children }) => {
throw err; throw err;
} }
} }
}; }
init() export interface Session {
.then(({ client, isPasswordlessUser }) => { user_id: string;
setState({ device_id: string;
client, access_token: string;
loading: false, passwordlessUser: boolean;
isAuthenticated: Boolean(client), tempPassword?: string;
isPasswordlessUser, }
userName: client?.getUserIdLocalpart(),
error: undefined,
});
})
.catch((err) => {
logger.error(err);
setState({
client: undefined,
loading: false,
isAuthenticated: false,
isPasswordlessUser: false,
userName: null,
error: undefined,
});
})
.finally(() => (initializing.current = false));
}, []);
const changePassword = useCallback( const clearSession = () => localStorage.removeItem("matrix-auth-store");
async (password: string) => { const saveSession = (s: Session) =>
const { tempPassword, ...session } = loadSession(); localStorage.setItem("matrix-auth-store", JSON.stringify(s));
const loadSession = (): Session | undefined => {
await client.setPassword( const data = localStorage.getItem("matrix-auth-store");
{ if (!data) {
type: "m.login.password", return undefined;
identifier: {
type: "m.id.user",
user: session.user_id,
},
user: session.user_id,
password: tempPassword,
},
password
);
saveSession({ ...session, passwordlessUser: false });
setState({
client,
loading: false,
isAuthenticated: true,
isPasswordlessUser: false,
userName: client.getUserIdLocalpart(),
error: undefined,
});
},
[client]
);
const setClient = useCallback(
(newClient: MatrixClient, session: Session) => {
if (client && client !== newClient) {
client.stopClient();
} }
if (newClient) { return JSON.parse(data);
saveSession(session);
setState({
client: newClient,
loading: false,
isAuthenticated: true,
isPasswordlessUser: session.passwordlessUser,
userName: newClient.getUserIdLocalpart(),
error: undefined,
});
} else {
clearSession();
setState({
client: undefined,
loading: false,
isAuthenticated: false,
isPasswordlessUser: false,
userName: null,
error: undefined,
});
}
},
[client]
);
const logout = useCallback(async () => {
await client.logout(true);
await client.clearStores();
clearSession();
setState({
client: undefined,
loading: false,
isAuthenticated: false,
isPasswordlessUser: true,
userName: "",
error: undefined,
});
history.push("/");
PosthogAnalytics.instance.setRegistrationType(RegistrationType.Guest);
}, [history, client]);
const { t } = useTranslation();
// To protect against multiple sessions writing to the same storage
// simultaneously, we send a broadcast message that shuts down all other
// running instances of the app. This isn't necessary if the app is running in
// a widget though, since then it'll be mostly stateless.
useEffect(() => {
if (!widget) loadChannel?.postMessage({});
}, []);
useEventTarget(
loadChannel,
"message",
useCallback(() => {
client?.stopClient();
setState((prev) => ({
...prev,
error: translatedError(
"This application has been opened in another tab.",
t
),
}));
}, [client, setState, t])
);
const context = useMemo<ClientState>(
() => ({
loading,
isAuthenticated,
isPasswordlessUser,
client,
changePassword,
logout,
userName,
setClient,
error: undefined,
}),
[
loading,
isAuthenticated,
isPasswordlessUser,
client,
changePassword,
logout,
userName,
setClient,
]
);
useEffect(() => {
window.matrixclient = client;
window.isPasswordlessUser = isPasswordlessUser;
if (PosthogAnalytics.hasInstance())
PosthogAnalytics.instance.onLoginStatusChanged();
}, [client, isPasswordlessUser]);
if (error) {
return <ErrorView error={error} />;
}
return (
<ClientContext.Provider value={context}>{children}</ClientContext.Provider>
);
}; };
export const useClient = () => useContext(ClientContext);
+2 -2
View File
@@ -47,8 +47,8 @@ export function Facepile({
}: Props) { }: Props) {
const { t } = useTranslation(); const { t } = useTranslation();
const _size = sizes.get(size); const _size = sizes.get(size)!;
const _overlap = overlapMap[size]; const _overlap = overlapMap[size]!;
const title = useMemo(() => { const title = useMemo(() => {
return members.reduce<string | null>( return members.reduce<string | null>(
+2
View File
@@ -18,6 +18,7 @@ import { ReactNode, useCallback, useEffect } from "react";
import { useLocation } from "react-router-dom"; import { useLocation } from "react-router-dom";
import classNames from "classnames"; import classNames from "classnames";
import { Trans, useTranslation } from "react-i18next"; import { Trans, useTranslation } from "react-i18next";
import * as Sentry from "@sentry/react";
import { Header, HeaderLogo, LeftNav, RightNav } from "./Header"; import { Header, HeaderLogo, LeftNav, RightNav } from "./Header";
import { LinkButton, Button } from "./button"; import { LinkButton, Button } from "./button";
@@ -58,6 +59,7 @@ export function ErrorView({ error }: ErrorViewProps) {
useEffect(() => { useEffect(() => {
console.error(error); console.error(error);
Sentry.captureException(error);
}, [error]); }, [error]);
const onReload = useCallback(() => { const onReload = useCallback(() => {
+10 -5
View File
@@ -36,15 +36,16 @@ export function ListBox<T>({
listBoxRef, listBoxRef,
...rest ...rest
}: ListBoxProps<T>) { }: ListBoxProps<T>) {
const ref = useRef<HTMLUListElement>(); const ref = useRef<HTMLUListElement>(null);
if (!listBoxRef) listBoxRef = ref;
const { listBoxProps } = useListBox(rest, state, listBoxRef); const listRef = listBoxRef ?? ref;
const { listBoxProps } = useListBox(rest, state, listRef);
return ( return (
<ul <ul
{...listBoxProps} {...listBoxProps}
ref={listBoxRef} ref={listRef}
className={classNames(styles.listBox, className)} className={classNames(styles.listBox, className)}
> >
{[...state.collection].map((item) => ( {[...state.collection].map((item) => (
@@ -66,7 +67,7 @@ interface OptionProps<T> {
} }
function Option<T>({ item, state, className }: OptionProps<T>) { function Option<T>({ item, state, className }: OptionProps<T>) {
const ref = useRef(); const ref = useRef(null);
const { optionProps, isSelected, isFocused, isDisabled } = useOption( const { optionProps, isSelected, isFocused, isDisabled } = useOption(
{ key: item.key }, { key: item.key },
state, state,
@@ -83,7 +84,11 @@ function Option<T>({ item, state, className }: OptionProps<T>) {
const origPointerUp = optionProps.onPointerUp; const origPointerUp = optionProps.onPointerUp;
delete optionProps.onPointerUp; delete optionProps.onPointerUp;
optionProps.onClick = useCallback( optionProps.onClick = useCallback(
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
(e) => { (e) => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
origPointerUp(e as unknown as PointerEvent<HTMLElement>); origPointerUp(e as unknown as PointerEvent<HTMLElement>);
}, },
[origPointerUp] [origPointerUp]
+3 -3
View File
@@ -26,7 +26,7 @@ import styles from "./Menu.module.css";
interface MenuProps<T> extends AriaMenuOptions<T> { interface MenuProps<T> extends AriaMenuOptions<T> {
className?: String; className?: String;
onClose?: () => void; onClose: () => void;
onAction: (value: Key) => void; onAction: (value: Key) => void;
label?: string; label?: string;
} }
@@ -39,7 +39,7 @@ export function Menu<T extends object>({
...rest ...rest
}: MenuProps<T>) { }: MenuProps<T>) {
const state = useTreeState<T>({ ...rest, selectionMode: "none" }); const state = useTreeState<T>({ ...rest, selectionMode: "none" });
const menuRef = useRef(); const menuRef = useRef(null);
const { menuProps } = useMenu<T>(rest, state, menuRef); const { menuProps } = useMenu<T>(rest, state, menuRef);
return ( return (
@@ -69,7 +69,7 @@ interface MenuItemProps<T> {
} }
function MenuItem<T>({ item, state, onAction, onClose }: MenuItemProps<T>) { function MenuItem<T>({ item, state, onAction, onClose }: MenuItemProps<T>) {
const ref = useRef(); const ref = useRef(null);
const { menuItemProps } = useMenuItem( const { menuItemProps } = useMenuItem(
{ {
key: item.key, key: item.key,
+2 -2
View File
@@ -55,7 +55,7 @@ export function Modal({
...rest ...rest
}: ModalProps) { }: ModalProps) {
const { t } = useTranslation(); const { t } = useTranslation();
const modalRef = useRef(); const modalRef = useRef(null);
const { overlayProps, underlayProps } = useOverlay( const { overlayProps, underlayProps } = useOverlay(
{ ...rest, onClose }, { ...rest, onClose },
modalRef modalRef
@@ -63,7 +63,7 @@ export function Modal({
usePreventScroll(); usePreventScroll();
const { modalProps } = useModal(); const { modalProps } = useModal();
const { dialogProps, titleProps } = useDialog(rest, modalRef); const { dialogProps, titleProps } = useDialog(rest, modalRef);
const closeButtonRef = useRef(); const closeButtonRef = useRef(null);
const { buttonProps: closeButtonProps } = useButton( const { buttonProps: closeButtonProps } = useButton(
{ {
onPress: () => onClose(), onPress: () => onClose(),
+4 -1
View File
@@ -36,6 +36,9 @@ export function SequenceDiagramViewerPage() {
const [debugLog, setDebugLog] = useState<DebugLog>(); const [debugLog, setDebugLog] = useState<DebugLog>();
const [selectedUserId, setSelectedUserId] = useState<string>(); const [selectedUserId, setSelectedUserId] = useState<string>();
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const onChangeDebugLog = useCallback((e) => { const onChangeDebugLog = useCallback((e) => {
if (e.target.files && e.target.files.length > 0) { if (e.target.files && e.target.files.length > 0) {
e.target.files[0].text().then((text: string) => { e.target.files[0].text().then((text: string) => {
@@ -55,7 +58,7 @@ export function SequenceDiagramViewerPage() {
onChange={onChangeDebugLog} onChange={onChangeDebugLog}
/> />
</FieldRow> </FieldRow>
{debugLog && ( {debugLog && selectedUserId && (
<SequenceDiagramViewer <SequenceDiagramViewer
localUserId={debugLog.localUserId} localUserId={debugLog.localUserId}
selectedUserId={selectedUserId} selectedUserId={selectedUserId}
+1 -1
View File
@@ -74,7 +74,7 @@ export const TooltipTrigger = forwardRef<HTMLElement, TooltipTriggerProps>(
const tooltipTriggerProps = { delay: 250, ...rest }; const tooltipTriggerProps = { delay: 250, ...rest };
const tooltipState = useTooltipTriggerState(tooltipTriggerProps); const tooltipState = useTooltipTriggerState(tooltipTriggerProps);
const triggerRef = useObjectRef<HTMLElement>(ref); const triggerRef = useObjectRef<HTMLElement>(ref);
const overlayRef = useRef(); const overlayRef = useRef<HTMLDivElement>(null);
const { triggerProps, tooltipProps } = useTooltipTrigger( const { triggerProps, tooltipProps } = useTooltipTrigger(
tooltipTriggerProps, tooltipTriggerProps,
tooltipState, tooltipState,
+43 -17
View File
@@ -1,5 +1,5 @@
/* /*
Copyright 2022 New Vector Ltd Copyright 2022 - 2023 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License"); Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.
@@ -17,6 +17,8 @@ limitations under the License.
import { useMemo } from "react"; import { useMemo } from "react";
import { useLocation } from "react-router-dom"; import { useLocation } from "react-router-dom";
import { Config } from "./config/Config";
interface UrlParams { interface UrlParams {
roomAlias: string | null; roomAlias: string | null;
roomId: string | null; roomId: string | null;
@@ -88,19 +90,46 @@ interface UrlParams {
/** /**
* Gets the app parameters for the current URL. * Gets the app parameters for the current URL.
* @param query The URL query string * @param ignoreRoomAlias If true, does not try to parse a room alias from the URL
* @param fragment The URL fragment string * @param search The URL search string
* @param pathname The URL path name
* @param hash The URL hash
* @returns The app parameters encoded in the URL * @returns The app parameters encoded in the URL
*/ */
export const getUrlParams = ( export const getUrlParams = (
query: string = window.location.search, ignoreRoomAlias?: boolean,
fragment: string = window.location.hash search = window.location.search,
pathname = window.location.pathname,
hash = window.location.hash
): UrlParams => { ): UrlParams => {
const fragmentQueryStart = fragment.indexOf("?"); let roomAlias: string | undefined;
if (!ignoreRoomAlias) {
if (hash === "") {
roomAlias = pathname.substring(1); // Strip the "/"
// Delete "/room/" and "?", if present
if (roomAlias.startsWith("room/")) {
roomAlias = roomAlias.substring("room/".length);
}
// Add "#", if not present
if (!roomAlias.startsWith("#")) {
roomAlias = `#${roomAlias}`;
}
} else {
roomAlias = hash;
}
// Add server part, if not present
if (!roomAlias.includes(":")) {
roomAlias = `${roomAlias}:${Config.defaultServerName()}`;
}
}
const fragmentQueryStart = hash.indexOf("?");
const fragmentParams = new URLSearchParams( const fragmentParams = new URLSearchParams(
fragmentQueryStart === -1 ? "" : fragment.substring(fragmentQueryStart) fragmentQueryStart === -1 ? "" : hash.substring(fragmentQueryStart)
); );
const queryParams = new URLSearchParams(query); const queryParams = new URLSearchParams(search);
// Normally, URL params should be encoded in the fragment so as to avoid // Normally, URL params should be encoded in the fragment so as to avoid
// leaking them to the server. However, we also check the normal query // leaking them to the server. However, we also check the normal query
@@ -114,16 +143,10 @@ export const getUrlParams = (
...queryParams.getAll(name), ...queryParams.getAll(name),
]; ];
// The part of the fragment before the ?
const fragmentRoute =
fragmentQueryStart === -1
? fragment
: fragment.substring(0, fragmentQueryStart);
const fontScale = parseFloat(getParam("fontScale") ?? ""); const fontScale = parseFloat(getParam("fontScale") ?? "");
return { return {
roomAlias: fragmentRoute.length > 1 ? fragmentRoute : null, roomAlias: !roomAlias || roomAlias.includes("!") ? null : roomAlias,
roomId: getParam("roomId"), roomId: getParam("roomId"),
viaServers: getAllParams("via"), viaServers: getAllParams("via"),
isEmbedded: hasParam("embed"), isEmbedded: hasParam("embed"),
@@ -149,6 +172,9 @@ export const getUrlParams = (
* @returns The app parameters for the current URL * @returns The app parameters for the current URL
*/ */
export const useUrlParams = (): UrlParams => { export const useUrlParams = (): UrlParams => {
const { hash, search } = useLocation(); const { search, pathname, hash } = useLocation();
return useMemo(() => getUrlParams(search, hash), [search, hash]); return useMemo(
() => getUrlParams(false, search, pathname, hash),
[search, pathname, hash]
);
}; };
+6 -3
View File
@@ -36,7 +36,7 @@ interface UserMenuProps {
isAuthenticated: boolean; isAuthenticated: boolean;
isPasswordlessUser: boolean; isPasswordlessUser: boolean;
displayName: string; displayName: string;
avatarUrl: string; avatarUrl?: string;
onAction: (value: string) => void; onAction: (value: string) => void;
} }
@@ -119,7 +119,9 @@ export function UserMenu({
)} )}
</Button> </Button>
</TooltipTrigger> </TooltipTrigger>
{(props) => ( {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(props: any) => (
<Menu {...props} label={t("User menu")} onAction={onAction}> <Menu {...props} label={t("User menu")} onAction={onAction}>
{items.map(({ key, icon: Icon, label, dataTestid }) => ( {items.map(({ key, icon: Icon, label, dataTestid }) => (
<Item key={key} textValue={label}> <Item key={key} textValue={label}>
@@ -133,7 +135,8 @@ export function UserMenu({
</Item> </Item>
))} ))}
</Menu> </Menu>
)} )
}
</PopoverMenuTrigger> </PopoverMenuTrigger>
); );
} }
+8 -10
View File
@@ -17,7 +17,7 @@ limitations under the License.
import { useCallback, useState } from "react"; import { useCallback, useState } from "react";
import { useHistory, useLocation } from "react-router-dom"; import { useHistory, useLocation } from "react-router-dom";
import { useClient } from "./ClientContext"; import { useClientLegacy } from "./ClientContext";
import { useProfile } from "./profile/useProfile"; import { useProfile } from "./profile/useProfile";
import { useModalTriggerState } from "./Modal"; import { useModalTriggerState } from "./Modal";
import { SettingsModal } from "./settings/SettingsModal"; import { SettingsModal } from "./settings/SettingsModal";
@@ -30,8 +30,7 @@ interface Props {
export function UserMenuContainer({ preventNavigation = false }: Props) { export function UserMenuContainer({ preventNavigation = false }: Props) {
const location = useLocation(); const location = useLocation();
const history = useHistory(); const history = useHistory();
const { isAuthenticated, isPasswordlessUser, logout, userName, client } = const { client, logout, authenticated, passwordlessUser } = useClientLegacy();
useClient();
const { displayName, avatarUrl } = useProfile(client); const { displayName, avatarUrl } = useProfile(client);
const { modalState, modalProps } = useModalTriggerState(); const { modalState, modalProps } = useModalTriggerState();
@@ -49,7 +48,7 @@ export function UserMenuContainer({ preventNavigation = false }: Props) {
modalState.open(); modalState.open();
break; break;
case "logout": case "logout":
logout(); logout?.();
break; break;
case "login": case "login":
history.push("/login", { state: { from: location } }); history.push("/login", { state: { from: location } });
@@ -59,19 +58,18 @@ export function UserMenuContainer({ preventNavigation = false }: Props) {
[history, location, logout, modalState] [history, location, logout, modalState]
); );
const userName = client?.getUserIdLocalpart() ?? "";
return ( return (
<> <>
<UserMenu <UserMenu
preventNavigation={preventNavigation} preventNavigation={preventNavigation}
isAuthenticated={isAuthenticated} isAuthenticated={authenticated}
isPasswordlessUser={isPasswordlessUser} isPasswordlessUser={passwordlessUser}
avatarUrl={avatarUrl} avatarUrl={avatarUrl}
onAction={onAction} onAction={onAction}
displayName={ displayName={displayName || (userName ? userName.replace("@", "") : "")}
displayName || (userName ? userName.replace("@", "") : undefined)
}
/> />
{modalState.isOpen && ( {modalState.isOpen && client && (
<SettingsModal <SettingsModal
client={client} client={client}
defaultTab={defaultSettingsTab} defaultTab={defaultSettingsTab}
+5 -3
View File
@@ -98,7 +98,7 @@ export class PosthogAnalytics {
// set true during the constructor if posthog config is present, otherwise false // set true during the constructor if posthog config is present, otherwise false
private static internalInstance: PosthogAnalytics | null = null; private static internalInstance: PosthogAnalytics | null = null;
private identificationPromise: Promise<void>; private identificationPromise?: Promise<void>;
private readonly enabled: boolean = false; private readonly enabled: boolean = false;
private anonymity = Anonymity.Disabled; private anonymity = Anonymity.Disabled;
private platformSuperProperties = {}; private platformSuperProperties = {};
@@ -255,7 +255,9 @@ export class PosthogAnalytics {
} catch (e) { } catch (e) {
// The above could fail due to network requests, but not essential to starting the application, // The above could fail due to network requests, but not essential to starting the application,
// so swallow it. // so swallow it.
logger.log("Unable to identify user for tracking" + e.toString()); logger.log(
"Unable to identify user for tracking" + (e as Error)?.toString()
);
} }
if (analyticsID) { if (analyticsID) {
this.posthog.identify(analyticsID); this.posthog.identify(analyticsID);
@@ -366,7 +368,7 @@ export class PosthogAnalytics {
if (anonymity === Anonymity.Pseudonymous) { if (anonymity === Anonymity.Pseudonymous) {
this.setRegistrationType( this.setRegistrationType(
window.matrixclient.isGuest() || window.isPasswordlessUser window.matrixclient.isGuest() || window.passwordlessUser
? RegistrationType.Guest ? RegistrationType.Guest
: RegistrationType.Registered : RegistrationType.Registered
); );
+20 -5
View File
@@ -35,8 +35,8 @@ export const LoginPage: FC = () => {
const { setClient } = useClient(); const { setClient } = useClient();
const login = useInteractiveLogin(); const login = useInteractiveLogin();
const homeserver = Config.defaultHomeserverUrl(); // TODO: Make this configurable const homeserver = Config.defaultHomeserverUrl(); // TODO: Make this configurable
const usernameRef = useRef<HTMLInputElement>(); const usernameRef = useRef<HTMLInputElement>(null);
const passwordRef = useRef<HTMLInputElement>(); const passwordRef = useRef<HTMLInputElement>(null);
const history = useHistory(); const history = useHistory();
const location = useLocation(); const location = useLocation();
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
@@ -49,12 +49,27 @@ export const LoginPage: FC = () => {
e.preventDefault(); e.preventDefault();
setLoading(true); setLoading(true);
if (!homeserver || !usernameRef.current || !passwordRef.current) {
setError(Error("Login parameters are undefined"));
setLoading(false);
return;
}
login(homeserver, usernameRef.current.value, passwordRef.current.value) login(homeserver, usernameRef.current.value, passwordRef.current.value)
.then(([client, session]) => { .then(([client, session]) => {
setClient(client, session); if (!setClient) {
return;
}
if (location.state && location.state.from) { setClient({ client, session });
history.push(location.state.from);
const locationState = location.state;
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
if (locationState && locationState.from) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
history.push(locationState.from);
} else { } else {
history.push("/"); history.push("/");
} }
+20 -10
View File
@@ -30,7 +30,7 @@ import { Trans, useTranslation } from "react-i18next";
import { FieldRow, InputField, ErrorMessage } from "../input/Input"; import { FieldRow, InputField, ErrorMessage } from "../input/Input";
import { Button } from "../button"; import { Button } from "../button";
import { useClient } from "../ClientContext"; import { useClientLegacy } from "../ClientContext";
import { useInteractiveRegistration } from "./useInteractiveRegistration"; import { useInteractiveRegistration } from "./useInteractiveRegistration";
import styles from "./LoginPage.module.css"; import styles from "./LoginPage.module.css";
import { ReactComponent as Logo } from "../icons/LogoLarge.svg"; import { ReactComponent as Logo } from "../icons/LogoLarge.svg";
@@ -45,9 +45,10 @@ export const RegisterPage: FC = () => {
const { t } = useTranslation(); const { t } = useTranslation();
usePageTitle(t("Register")); usePageTitle(t("Register"));
const { loading, isAuthenticated, isPasswordlessUser, client, setClient } = const { loading, authenticated, passwordlessUser, client, setClient } =
useClient(); useClientLegacy();
const confirmPasswordRef = useRef<HTMLInputElement>();
const confirmPasswordRef = useRef<HTMLInputElement>(null);
const history = useHistory(); const history = useHistory();
const location = useLocation(); const location = useLocation();
const [registering, setRegistering] = useState(false); const [registering, setRegistering] = useState(false);
@@ -75,10 +76,11 @@ export const RegisterPage: FC = () => {
userName, userName,
password, password,
userName, userName,
recaptchaResponse recaptchaResponse,
passwordlessUser
); );
if (client && isPasswordlessUser) { if (client && client?.groupCallEventHandler && passwordlessUser) {
// Migrate the user's rooms // Migrate the user's rooms
for (const groupCall of client.groupCallEventHandler.groupCalls.values()) { for (const groupCall of client.groupCallEventHandler.groupCalls.values()) {
const roomId = groupCall.room.roomId; const roomId = groupCall.room.roomId;
@@ -86,7 +88,11 @@ export const RegisterPage: FC = () => {
try { try {
await newClient.joinRoom(roomId); await newClient.joinRoom(roomId);
} catch (error) { } catch (error) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
if (error.errcode === "M_LIMIT_EXCEEDED") { if (error.errcode === "M_LIMIT_EXCEEDED") {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
await sleep(error.data.retry_after_ms); await sleep(error.data.retry_after_ms);
await newClient.joinRoom(roomId); await newClient.joinRoom(roomId);
} else { } else {
@@ -97,13 +103,17 @@ export const RegisterPage: FC = () => {
} }
} }
setClient(newClient, session); setClient?.({ client: newClient, session });
PosthogAnalytics.instance.eventSignup.cacheSignupEnd(new Date()); PosthogAnalytics.instance.eventSignup.cacheSignupEnd(new Date());
}; };
submit() submit()
.then(() => { .then(() => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
if (location.state?.from) { if (location.state?.from) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
history.push(location.state?.from); history.push(location.state?.from);
} else { } else {
history.push("/"); history.push("/");
@@ -119,7 +129,7 @@ export const RegisterPage: FC = () => {
register, register,
location, location,
history, history,
isPasswordlessUser, passwordlessUser,
reset, reset,
execute, execute,
client, client,
@@ -136,10 +146,10 @@ export const RegisterPage: FC = () => {
}, [password, passwordConfirmation, t]); }, [password, passwordConfirmation, t]);
useEffect(() => { useEffect(() => {
if (!loading && isAuthenticated && !isPasswordlessUser && !registering) { if (!loading && authenticated && !passwordlessUser && !registering) {
history.push("/"); history.push("/");
} }
}, [loading, history, isAuthenticated, isPasswordlessUser, registering]); }, [loading, history, authenticated, passwordlessUser, registering]);
if (loading) { if (loading) {
return <LoadingView />; return <LoadingView />;
+4 -2
View File
@@ -41,8 +41,10 @@ export const useInteractiveLogin = () =>
}, },
password, password,
}), }),
stateUpdated: null, stateUpdated: (...args) => {},
requestEmailToken: null, requestEmailToken: (...args): Promise<{ sid: string }> => {
return Promise.resolve({ sid: "" });
},
}); });
// XXX: This claims to return an IAuthData which contains none of these // XXX: This claims to return an IAuthData which contains none of these
+19 -13
View File
@@ -23,28 +23,32 @@ import { Session } from "../ClientContext";
import { Config } from "../config/Config"; import { Config } from "../config/Config";
export const useInteractiveRegistration = (): { export const useInteractiveRegistration = (): {
privacyPolicyUrl: string; privacyPolicyUrl?: string;
recaptchaKey: string; recaptchaKey?: string;
register: ( register: (
username: string, username: string,
password: string, password: string,
displayName: string, displayName: string,
recaptchaResponse: string, recaptchaResponse: string,
passwordlessUser?: boolean passwordlessUser: boolean
) => Promise<[MatrixClient, Session]>; ) => Promise<[MatrixClient, Session]>;
} => { } => {
const [privacyPolicyUrl, setPrivacyPolicyUrl] = useState<string>(); const [privacyPolicyUrl, setPrivacyPolicyUrl] = useState<string | undefined>(
const [recaptchaKey, setRecaptchaKey] = useState<string>(); undefined
);
const [recaptchaKey, setRecaptchaKey] = useState<string | undefined>(
undefined
);
const authClient = useRef<MatrixClient>(); const authClient = useRef<MatrixClient>();
if (!authClient.current) { if (!authClient.current) {
authClient.current = createClient({ authClient.current = createClient({
baseUrl: Config.defaultHomeserverUrl(), baseUrl: Config.defaultHomeserverUrl()!,
}); });
} }
useEffect(() => { useEffect(() => {
authClient.current.registerRequest({}).catch((error) => { authClient.current!.registerRequest({}).catch((error) => {
setPrivacyPolicyUrl( setPrivacyPolicyUrl(
error.data?.params["m.login.terms"]?.policies?.privacy_policy?.en?.url error.data?.params["m.login.terms"]?.policies?.privacy_policy?.en?.url
); );
@@ -58,12 +62,12 @@ export const useInteractiveRegistration = (): {
password: string, password: string,
displayName: string, displayName: string,
recaptchaResponse: string, recaptchaResponse: string,
passwordlessUser?: boolean passwordlessUser: boolean
): Promise<[MatrixClient, Session]> => { ): Promise<[MatrixClient, Session]> => {
const interactiveAuth = new InteractiveAuth({ const interactiveAuth = new InteractiveAuth({
matrixClient: authClient.current, matrixClient: authClient.current!,
doRequest: (auth) => doRequest: (auth) =>
authClient.current.registerRequest({ authClient.current!.registerRequest({
username, username,
password, password,
auth: auth || undefined, auth: auth || undefined,
@@ -84,7 +88,9 @@ export const useInteractiveRegistration = (): {
}); });
} }
}, },
requestEmailToken: null, requestEmailToken: (...args) => {
return Promise.resolve({ sid: "dummy" });
},
}); });
// XXX: This claims to return an IAuthData which contains none of these // XXX: This claims to return an IAuthData which contains none of these
@@ -95,7 +101,7 @@ export const useInteractiveRegistration = (): {
const client = await initClient( const client = await initClient(
{ {
baseUrl: Config.defaultHomeserverUrl(), baseUrl: Config.defaultHomeserverUrl()!,
accessToken: access_token, accessToken: access_token,
userId: user_id, userId: user_id,
deviceId: device_id, deviceId: device_id,
@@ -117,7 +123,7 @@ export const useInteractiveRegistration = (): {
session.tempPassword = password; session.tempPassword = password;
} }
const user = client.getUser(client.getUserId()); const user = client.getUser(client.getUserId()!)!;
user.setRawDisplayName(displayName); user.setRawDisplayName(displayName);
user.setDisplayName(displayName); user.setDisplayName(displayName);
+3 -3
View File
@@ -34,7 +34,7 @@ interface RecaptchaPromiseRef {
reject: (error: Error) => void; reject: (error: Error) => void;
} }
export const useRecaptcha = (sitekey: string) => { export const useRecaptcha = (sitekey?: string) => {
const { t } = useTranslation(); const { t } = useTranslation();
const [recaptchaId] = useState(() => randomString(16)); const [recaptchaId] = useState(() => randomString(16));
const promiseRef = useRef<RecaptchaPromiseRef>(); const promiseRef = useRef<RecaptchaPromiseRef>();
@@ -68,9 +68,9 @@ export const useRecaptcha = (sitekey: string) => {
} }
}, [recaptchaId, sitekey]); }, [recaptchaId, sitekey]);
const execute = useCallback(() => { const execute = useCallback((): Promise<string> => {
if (!sitekey) { if (!sitekey) {
return Promise.resolve(null); return Promise.resolve("");
} }
if (!window.grecaptcha) { if (!window.grecaptcha) {
+7 -3
View File
@@ -23,9 +23,9 @@ import { generateRandomName } from "../auth/generateRandomName";
import { useRecaptcha } from "../auth/useRecaptcha"; import { useRecaptcha } from "../auth/useRecaptcha";
interface UseRegisterPasswordlessUserType { interface UseRegisterPasswordlessUserType {
privacyPolicyUrl: string; privacyPolicyUrl?: string;
registerPasswordlessUser: (displayName: string) => Promise<void>; registerPasswordlessUser: (displayName: string) => Promise<void>;
recaptchaId: string; recaptchaId?: string;
} }
export function useRegisterPasswordlessUser(): UseRegisterPasswordlessUserType { export function useRegisterPasswordlessUser(): UseRegisterPasswordlessUserType {
@@ -36,6 +36,10 @@ export function useRegisterPasswordlessUser(): UseRegisterPasswordlessUserType {
const registerPasswordlessUser = useCallback( const registerPasswordlessUser = useCallback(
async (displayName: string) => { async (displayName: string) => {
if (!setClient) {
throw new Error("No client context");
}
try { try {
const recaptchaResponse = await execute(); const recaptchaResponse = await execute();
const userName = generateRandomName(); const userName = generateRandomName();
@@ -46,7 +50,7 @@ export function useRegisterPasswordlessUser(): UseRegisterPasswordlessUserType {
recaptchaResponse, recaptchaResponse,
true true
); );
setClient(client, session); setClient({ client, session });
} catch (e) { } catch (e) {
reset(); reset();
throw e; throw e;
+1 -1
View File
@@ -46,7 +46,7 @@ export function LinkButton({
<Link <Link
className={classNames( className={classNames(
variantToClassName[variant || "secondary"], variantToClassName[variant || "secondary"],
sizeToClassName[size], size ? sizeToClassName[size] : [],
className className
)} )}
to={to} to={to}
+2 -2
View File
@@ -45,11 +45,11 @@ export class Config {
// Convenience accessors // Convenience accessors
public static defaultHomeserverUrl(): string | undefined { public static defaultHomeserverUrl(): string | undefined {
return Config.get().default_server_config["m.homeserver"].base_url; return Config.get().default_server_config?.["m.homeserver"].base_url;
} }
public static defaultServerName(): string | undefined { public static defaultServerName(): string | undefined {
return Config.get().default_server_config["m.homeserver"].server_name; return Config.get().default_server_config?.["m.homeserver"].server_name;
} }
public config?: ResolvedConfigOptions; public config?: ResolvedConfigOptions;
+11 -8
View File
@@ -35,13 +35,13 @@ export function CallList({ rooms, client, disableFacepile }: CallListProps) {
return ( return (
<> <>
<div className={styles.callList}> <div className={styles.callList}>
{rooms.map(({ roomId, roomName, avatarUrl, participants }) => ( {rooms.map(({ roomAlias, roomName, avatarUrl, participants }) => (
<CallTile <CallTile
key={roomId} key={roomAlias}
client={client} client={client}
name={roomName} name={roomName}
avatarUrl={avatarUrl} avatarUrl={avatarUrl}
roomId={roomId} roomAlias={roomAlias}
participants={participants} participants={participants}
disableFacepile={disableFacepile} disableFacepile={disableFacepile}
/> />
@@ -59,7 +59,7 @@ export function CallList({ rooms, client, disableFacepile }: CallListProps) {
interface CallTileProps { interface CallTileProps {
name: string; name: string;
avatarUrl: string; avatarUrl: string;
roomId: string; roomAlias: string;
participants: RoomMember[]; participants: RoomMember[];
client: MatrixClient; client: MatrixClient;
disableFacepile?: boolean; disableFacepile?: boolean;
@@ -67,14 +67,17 @@ interface CallTileProps {
function CallTile({ function CallTile({
name, name,
avatarUrl, avatarUrl,
roomId, roomAlias,
participants, participants,
client, client,
disableFacepile, disableFacepile,
}: CallTileProps) { }: CallTileProps) {
return ( return (
<div className={styles.callTile}> <div className={styles.callTile}>
<Link to={`/room/${roomId}`} className={styles.callTileLink}> <Link
to={`/${roomAlias.substring(1).split(":")[0]}`}
className={styles.callTileLink}
>
<Avatar <Avatar
size={Size.LG} size={Size.LG}
bgKey={name} bgKey={name}
@@ -86,7 +89,7 @@ function CallTile({
<Body overflowEllipsis fontWeight="semiBold"> <Body overflowEllipsis fontWeight="semiBold">
{name} {name}
</Body> </Body>
<Caption overflowEllipsis>{getRoomUrl(roomId)}</Caption> <Caption overflowEllipsis>{getRoomUrl(roomAlias)}</Caption>
{participants && !disableFacepile && ( {participants && !disableFacepile && (
<Facepile <Facepile
className={styles.facePile} className={styles.facePile}
@@ -100,7 +103,7 @@ function CallTile({
<CopyButton <CopyButton
className={styles.copyButton} className={styles.copyButton}
variant="icon" variant="icon"
value={getRoomUrl(roomId)} value={getRoomUrl(roomAlias)}
/> />
</div> </div>
); );
+12 -1
View File
@@ -42,6 +42,12 @@ interface Props {
export const CallTypeDropdown: FC<Props> = ({ callType, setCallType }) => { export const CallTypeDropdown: FC<Props> = ({ callType, setCallType }) => {
const { t } = useTranslation(); const { t } = useTranslation();
const onAction = (key: React.Key) => {
setCallType(key.toString() as CallType);
};
const onClose = () => {};
return ( return (
<PopoverMenuTrigger placement="bottom"> <PopoverMenuTrigger placement="bottom">
<Button variant="dropdown" className={commonStyles.headline}> <Button variant="dropdown" className={commonStyles.headline}>
@@ -52,7 +58,12 @@ export const CallTypeDropdown: FC<Props> = ({ callType, setCallType }) => {
</Headline> </Headline>
</Button> </Button>
{(props: JSX.IntrinsicAttributes) => ( {(props: JSX.IntrinsicAttributes) => (
<Menu {...props} label={t("Call type menu")} onAction={setCallType}> <Menu
{...props}
label={t("Call type menu")}
onAction={onAction}
onClose={onClose}
>
<Item key={CallType.Video} textValue={t("Video call")}> <Item key={CallType.Video} textValue={t("Video call")}>
<VideoIcon /> <VideoIcon />
<span>{t("Video call")}</span> <span>{t("Video call")}</span>
+10 -8
View File
@@ -16,7 +16,7 @@ limitations under the License.
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { useClient } from "../ClientContext"; import { useClientState } from "../ClientContext";
import { ErrorView, LoadingView } from "../FullScreenView"; import { ErrorView, LoadingView } from "../FullScreenView";
import { UnauthenticatedView } from "./UnauthenticatedView"; import { UnauthenticatedView } from "./UnauthenticatedView";
import { RegisteredView } from "./RegisteredView"; import { RegisteredView } from "./RegisteredView";
@@ -26,16 +26,18 @@ export function HomePage() {
const { t } = useTranslation(); const { t } = useTranslation();
usePageTitle(t("Home")); usePageTitle(t("Home"));
const { isAuthenticated, isPasswordlessUser, loading, error, client } = const clientState = useClientState();
useClient();
if (loading) { if (!clientState) {
return <LoadingView />; return <LoadingView />;
} else if (error) { } else if (clientState.state === "error") {
return <ErrorView error={error} />; return <ErrorView error={clientState.error} />;
} else { } else {
return isAuthenticated ? ( return clientState.authenticated ? (
<RegisteredView isPasswordlessUser={isPasswordlessUser} client={client} /> <RegisteredView
isPasswordlessUser={clientState.authenticated.isPasswordlessUser}
client={clientState.authenticated.client}
/>
) : ( ) : (
<UnauthenticatedView /> <UnauthenticatedView />
); );
+3 -3
View File
@@ -70,10 +70,10 @@ export function RegisteredView({ client, isPasswordlessUser }: Props) {
setError(undefined); setError(undefined);
setLoading(true); setLoading(true);
const [roomIdOrAlias] = await createRoom(client, roomName, ptt); const [roomAlias] = await createRoom(client, roomName, ptt);
if (roomIdOrAlias) { if (roomAlias) {
history.push(`/room/${roomIdOrAlias}`); history.push(`/${roomAlias.substring(1).split(":")[0]}`);
} }
} }
+17 -8
View File
@@ -79,16 +79,21 @@ export const UnauthenticatedView: FC = () => {
true true
); );
let roomIdOrAlias: string; let roomAlias: string;
try { try {
[roomIdOrAlias] = await createRoom(client, roomName, ptt); [roomAlias] = await createRoom(client, roomName, ptt);
} catch (error) { } catch (error) {
if (!setClient) {
throw error;
}
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
if (error.errcode === "M_ROOM_IN_USE") { if (error.errcode === "M_ROOM_IN_USE") {
setOnFinished(() => { setOnFinished(() => {
setClient(client, session); setClient({ client, session });
const aliasLocalpart = roomAliasLocalpartFromRoomName(roomName); const aliasLocalpart = roomAliasLocalpartFromRoomName(roomName);
const [, serverName] = client.getUserId().split(":"); history.push(`/${aliasLocalpart}`);
history.push(`/room/#${aliasLocalpart}:${serverName}`);
}); });
setLoading(false); setLoading(false);
@@ -100,8 +105,12 @@ export const UnauthenticatedView: FC = () => {
} }
// Only consider the registration successful if we managed to create the room, too // Only consider the registration successful if we managed to create the room, too
setClient(client, session); if (!setClient) {
history.push(`/room/${roomIdOrAlias}`); throw new Error("setClient is undefined");
}
setClient({ client, session });
history.push(`/${roomAlias.substring(1).split(":")[0]}`);
} }
submit().catch((error) => { submit().catch((error) => {
@@ -204,7 +213,7 @@ export const UnauthenticatedView: FC = () => {
</Body> </Body>
</footer> </footer>
</div> </div>
{modalState.isOpen && ( {modalState.isOpen && onFinished && (
<JoinExistingCallModal onJoin={onFinished} {...modalProps} /> <JoinExistingCallModal onJoin={onFinished} {...modalProps} />
)} )}
</> </>
+15 -9
View File
@@ -22,7 +22,7 @@ import { GroupCallEventHandlerEvent } from "matrix-js-sdk/src/webrtc/groupCallEv
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
export interface GroupCallRoom { export interface GroupCallRoom {
roomId: string; roomAlias: string;
roomName: string; roomName: string;
avatarUrl: string; avatarUrl: string;
room: Room; room: Room;
@@ -42,7 +42,7 @@ function getLastTs(client: MatrixClient, r: Room) {
return ts; return ts;
} }
const myUserId = client.getUserId(); const myUserId = client.getUserId()!;
if (r.getMyMembership() !== "join") { if (r.getMyMembership() !== "join") {
const membershipEvent = r.currentState.getStateEvents( const membershipEvent = r.currentState.getStateEvents(
@@ -79,26 +79,32 @@ function sortRooms(client: MatrixClient, rooms: Room[]): Room[] {
} }
export function useGroupCallRooms(client: MatrixClient): GroupCallRoom[] { export function useGroupCallRooms(client: MatrixClient): GroupCallRoom[] {
const [rooms, setRooms] = useState([]); const [rooms, setRooms] = useState<GroupCallRoom[]>([]);
useEffect(() => { useEffect(() => {
function updateRooms() { function updateRooms() {
if (!client.groupCallEventHandler) {
return;
}
const groupCalls = client.groupCallEventHandler.groupCalls.values(); const groupCalls = client.groupCallEventHandler.groupCalls.values();
const rooms = Array.from(groupCalls).map((groupCall) => groupCall.room); const rooms = Array.from(groupCalls).map((groupCall) => groupCall.room);
const sortedRooms = sortRooms(client, rooms); const filteredRooms = rooms.filter((r) => r.getCanonicalAlias()); // We don't display rooms without an alias
const sortedRooms = sortRooms(client, filteredRooms);
const items = sortedRooms.map((room) => { const items = sortedRooms.map((room) => {
const groupCall = client.getGroupCallForRoom(room.roomId); const groupCall = client.getGroupCallForRoom(room.roomId)!;
return { return {
roomId: room.getCanonicalAlias() || room.roomId, roomAlias: room.getCanonicalAlias(),
roomName: room.name, roomName: room.name,
avatarUrl: room.getMxcAvatarUrl(), avatarUrl: room.getMxcAvatarUrl()!,
room, room,
groupCall, groupCall,
participants: [...groupCall.participants], participants: [...groupCall!.participants.keys()],
}; };
}); });
setRooms(items);
setRooms(items as GroupCallRoom[]);
} }
updateRooms(); updateRooms();
+4 -3
View File
@@ -55,7 +55,7 @@ export class Initializer {
languageDetector.addDetector({ languageDetector.addDetector({
name: "urlFragment", name: "urlFragment",
// Look for a language code in the URL's fragment // Look for a language code in the URL's fragment
lookup: () => getUrlParams().lang ?? undefined, lookup: () => getUrlParams(true).lang ?? undefined,
}); });
i18n i18n
@@ -140,7 +140,7 @@ export class Initializer {
} }
// Custom fonts // Custom fonts
const { fonts, fontScale } = getUrlParams(); const { fonts, fontScale } = getUrlParams(true);
if (fontScale !== null) { if (fontScale !== null) {
document.documentElement.style.setProperty( document.documentElement.style.setProperty(
"--font-scale", "--font-scale",
@@ -229,5 +229,6 @@ export class Initializer {
resolve(); resolve();
} }
} }
private initPromise: Promise<void> | null;
private initPromise?: Promise<void>;
} }
+13 -9
View File
@@ -15,10 +15,14 @@ limitations under the License.
*/ */
import { useObjectRef } from "@react-aria/utils"; import { useObjectRef } from "@react-aria/utils";
import { AllHTMLAttributes, ChangeEvent, useEffect } from "react"; import {
import { useCallback } from "react"; AllHTMLAttributes,
import { useState } from "react"; useEffect,
import { forwardRef } from "react"; useCallback,
useState,
forwardRef,
ChangeEvent,
} from "react";
import classNames from "classnames"; import classNames from "classnames";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
@@ -30,7 +34,7 @@ import styles from "./AvatarInputField.module.css";
interface Props extends AllHTMLAttributes<HTMLInputElement> { interface Props extends AllHTMLAttributes<HTMLInputElement> {
id: string; id: string;
label: string; label: string;
avatarUrl: string; avatarUrl: string | undefined;
displayName: string; displayName: string;
onRemoveAvatar: () => void; onRemoveAvatar: () => void;
} }
@@ -43,7 +47,7 @@ export const AvatarInputField = forwardRef<HTMLInputElement, Props>(
const { t } = useTranslation(); const { t } = useTranslation();
const [removed, setRemoved] = useState(false); const [removed, setRemoved] = useState(false);
const [objUrl, setObjUrl] = useState<string>(null); const [objUrl, setObjUrl] = useState<string | undefined>(undefined);
const fileInputRef = useObjectRef(ref); const fileInputRef = useObjectRef(ref);
@@ -52,11 +56,11 @@ export const AvatarInputField = forwardRef<HTMLInputElement, Props>(
const onChange = (e: Event) => { const onChange = (e: Event) => {
const inputEvent = e as unknown as ChangeEvent<HTMLInputElement>; const inputEvent = e as unknown as ChangeEvent<HTMLInputElement>;
if (inputEvent.target.files.length > 0) { if (inputEvent.target.files && inputEvent.target.files.length > 0) {
setObjUrl(URL.createObjectURL(inputEvent.target.files[0])); setObjUrl(URL.createObjectURL(inputEvent.target.files[0]));
setRemoved(false); setRemoved(false);
} else { } else {
setObjUrl(null); setObjUrl(undefined);
} }
}; };
@@ -77,7 +81,7 @@ export const AvatarInputField = forwardRef<HTMLInputElement, Props>(
<div className={styles.avatarContainer}> <div className={styles.avatarContainer}>
<Avatar <Avatar
size={Size.XL} size={Size.XL}
src={removed ? null : objUrl || avatarUrl} src={removed ? undefined : objUrl || avatarUrl}
fallback={displayName.slice(0, 1).toUpperCase()} fallback={displayName.slice(0, 1).toUpperCase()}
/> />
<input <input
+3 -1
View File
@@ -82,7 +82,7 @@ interface InputFieldProps {
defaultValue?: string; defaultValue?: string;
placeholder?: string; placeholder?: string;
defaultChecked?: boolean; defaultChecked?: boolean;
onChange?: (event: ChangeEvent) => void; onChange?: (event: ChangeEvent<HTMLInputElement>) => void;
} }
export const InputField = forwardRef< export const InputField = forwardRef<
@@ -119,6 +119,8 @@ export const InputField = forwardRef<
> >
{prefix && <span>{prefix}</span>} {prefix && <span>{prefix}</span>}
{type === "textarea" ? ( {type === "textarea" ? (
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
<textarea <textarea
id={id} id={id}
ref={ref as ForwardedRef<HTMLTextAreaElement>} ref={ref as ForwardedRef<HTMLTextAreaElement>}
+1 -1
View File
@@ -34,7 +34,7 @@ export function SelectInput(props: Props): JSX.Element {
const { t } = useTranslation(); const { t } = useTranslation();
const state = useSelectState(props); const state = useSelectState(props);
const ref = useRef(); const ref = useRef(null);
const { labelProps, triggerProps, valueProps, menuProps } = useSelect( const { labelProps, triggerProps, valueProps, menuProps } = useSelect(
props, props,
state, state,
+7 -11
View File
@@ -22,6 +22,7 @@ import {
useState, useState,
} from "react"; } from "react";
import { logger } from "matrix-js-sdk/src/logger"; import { logger } from "matrix-js-sdk/src/logger";
import { GroupCall } from "matrix-js-sdk";
import { import {
OpenIDClientParts, OpenIDClientParts,
@@ -32,21 +33,16 @@ import { ErrorView, LoadingView } from "../FullScreenView";
interface Props { interface Props {
client: OpenIDClientParts; client: OpenIDClientParts;
livekitServiceURL: string; groupCall: GroupCall;
roomName: string; roomName: string;
children: ReactNode; children: ReactNode;
} }
const SFUConfigContext = createContext<SFUConfig>(undefined); const SFUConfigContext = createContext<SFUConfig | undefined>(undefined);
export const useSFUConfig = () => useContext(SFUConfigContext); export const useSFUConfig = () => useContext(SFUConfigContext);
export function OpenIDLoader({ export function OpenIDLoader({ client, groupCall, roomName, children }: Props) {
client,
livekitServiceURL,
roomName,
children,
}: Props) {
const [state, setState] = useState< const [state, setState] = useState<
SFUConfigLoading | SFUConfigLoaded | SFUConfigFailed SFUConfigLoading | SFUConfigLoaded | SFUConfigFailed
>({ kind: "loading" }); >({ kind: "loading" });
@@ -56,16 +52,16 @@ export function OpenIDLoader({
try { try {
const result = await getSFUConfigWithOpenID( const result = await getSFUConfigWithOpenID(
client, client,
livekitServiceURL, groupCall,
roomName roomName
); );
setState({ kind: "loaded", sfuConfig: result }); setState({ kind: "loaded", sfuConfig: result });
} catch (e) { } catch (e) {
logger.error("Failed to fetch SFU config: ", e); logger.error("Failed to fetch SFU config: ", e);
setState({ kind: "failed", error: e }); setState({ kind: "failed", error: e as Error });
} }
})(); })();
}, [client, livekitServiceURL, roomName]); }, [client, groupCall, roomName]);
switch (state.kind) { switch (state.kind) {
case "loading": case "loading":
+71 -4
View File
@@ -14,9 +14,11 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
import { MatrixClient } from "matrix-js-sdk"; import { GroupCall, IOpenIDToken, MatrixClient } from "matrix-js-sdk";
import { logger } from "matrix-js-sdk/src/logger"; import { logger } from "matrix-js-sdk/src/logger";
import { Config } from "../config/Config";
export interface SFUConfig { export interface SFUConfig {
url: string; url: string;
jwt: string; jwt: string;
@@ -30,12 +32,74 @@ export type OpenIDClientParts = Pick<
export async function getSFUConfigWithOpenID( export async function getSFUConfigWithOpenID(
client: OpenIDClientParts, client: OpenIDClientParts,
livekitServiceURL: string, groupCall: GroupCall,
roomName: string roomName: string
): Promise<SFUConfig> { ): Promise<SFUConfig> {
const openIdToken = await client.getOpenIdToken(); const openIdToken = await client.getOpenIdToken();
logger.debug("Got openID token", openIdToken); logger.debug("Got openID token", openIdToken);
// if the call has a livekit service URL, try it.
if (groupCall.livekitServiceURL) {
try {
logger.info(
`Trying to get JWT from call's configured URL of ${groupCall.livekitServiceURL}...`
);
const sfuConfig = await getLiveKitJWT(
client,
groupCall.livekitServiceURL,
roomName,
openIdToken
);
logger.info(`Got JWT from call state event URL.`);
return sfuConfig;
} catch (e) {
logger.warn(
`Failed to get JWT from group call's configured URL of ${groupCall.livekitServiceURL}.`,
e
);
}
}
// otherwise, try our configured one and, if it works, update the call's service URL in the state event
// NB. This wuill update it for everyone so we may end up with multiple clients updating this when they
// join at similar times, but we don't have a huge number of options here.
const urlFromConf = Config.get().livekit!.livekit_service_url;
logger.info(`Trying livekit service URL from our config: ${urlFromConf}...`);
try {
const sfuConfig = await getLiveKitJWT(
client,
urlFromConf,
roomName,
openIdToken
);
logger.info(
`Got JWT, updating call livekit service URL with: ${urlFromConf}...`
);
try {
await groupCall.updateLivekitServiceURL(urlFromConf);
logger.info(`Call livekit service URL updated.`);
} catch (e) {
logger.warn(
`Failed to update call livekit service URL: continuing anyway.`
);
}
return sfuConfig;
} catch (e) {
logger.error("Failed to get JWT from URL defined in Config.", e);
throw e;
}
}
async function getLiveKitJWT(
client: OpenIDClientParts,
livekitServiceURL: string,
roomName: string,
openIDToken: IOpenIDToken
): Promise<SFUConfig> {
try {
const res = await fetch(livekitServiceURL + "/sfu/get", { const res = await fetch(livekitServiceURL + "/sfu/get", {
method: "POST", method: "POST",
headers: { headers: {
@@ -43,12 +107,15 @@ export async function getSFUConfigWithOpenID(
}, },
body: JSON.stringify({ body: JSON.stringify({
room: roomName, room: roomName,
openid_token: openIdToken, openid_token: openIDToken,
device_id: client.getDeviceId(), device_id: client.getDeviceId(),
}), }),
}); });
if (!res.ok) { if (!res.ok) {
throw new Error("SFO Config fetch failed with status code " + res.status); throw new Error("SFU Config fetch failed with status code " + res.status);
} }
return await res.json(); return await res.json();
} catch (e) {
throw new Error("SFU Config fetch failed with exception " + e);
}
} }
+6 -4
View File
@@ -1,4 +1,4 @@
import { Room, RoomOptions } from "livekit-client"; import { Room, RoomOptions, setLogLevel } from "livekit-client";
import { useLiveKitRoom } from "@livekit/components-react"; import { useLiveKitRoom } from "@livekit/components-react";
import { useMemo } from "react"; import { useMemo } from "react";
@@ -15,9 +15,11 @@ export type DeviceChoices = {
enabled: boolean; enabled: boolean;
}; };
setLogLevel("debug");
export function useLiveKit( export function useLiveKit(
userChoices: UserChoices, userChoices: UserChoices,
sfuConfig: SFUConfig sfuConfig?: SFUConfig
): Room | undefined { ): Room | undefined {
const roomOptions = useMemo((): RoomOptions => { const roomOptions = useMemo((): RoomOptions => {
const options = defaultLiveKitOptions; const options = defaultLiveKitOptions;
@@ -33,8 +35,8 @@ export function useLiveKit(
}, [userChoices.video, userChoices.audio]); }, [userChoices.video, userChoices.audio]);
const { room } = useLiveKitRoom({ const { room } = useLiveKitRoom({
token: sfuConfig.jwt, token: sfuConfig?.jwt,
serverUrl: sfuConfig.url, serverUrl: sfuConfig?.url,
audio: userChoices.audio?.enabled ?? false, audio: userChoices.audio?.enabled ?? false,
video: userChoices.video?.enabled ?? false, video: userChoices.video?.enabled ?? false,
options: roomOptions, options: roomOptions,
+11 -16
View File
@@ -19,8 +19,7 @@ import { MemoryStore } from "matrix-js-sdk/src/store/memory";
import { IndexedDBCryptoStore } from "matrix-js-sdk/src/crypto/store/indexeddb-crypto-store"; import { IndexedDBCryptoStore } from "matrix-js-sdk/src/crypto/store/indexeddb-crypto-store";
import { LocalStorageCryptoStore } from "matrix-js-sdk/src/crypto/store/localStorage-crypto-store"; import { LocalStorageCryptoStore } from "matrix-js-sdk/src/crypto/store/localStorage-crypto-store";
import { MemoryCryptoStore } from "matrix-js-sdk/src/crypto/store/memory-crypto-store"; import { MemoryCryptoStore } from "matrix-js-sdk/src/crypto/store/memory-crypto-store";
import { createClient } from "matrix-js-sdk/src/matrix"; import { createClient, ICreateClientOpts } from "matrix-js-sdk/src/matrix";
import { ICreateClientOpts } from "matrix-js-sdk/src/matrix";
import { ClientEvent } from "matrix-js-sdk/src/client"; import { ClientEvent } from "matrix-js-sdk/src/client";
import { Visibility, Preset } from "matrix-js-sdk/src/@types/partials"; import { Visibility, Preset } from "matrix-js-sdk/src/@types/partials";
import { ISyncStateData, SyncState } from "matrix-js-sdk/src/sync"; import { ISyncStateData, SyncState } from "matrix-js-sdk/src/sync";
@@ -57,8 +56,8 @@ function waitForSync(client: MatrixClient) {
return new Promise<void>((resolve, reject) => { return new Promise<void>((resolve, reject) => {
const onSync = ( const onSync = (
state: SyncState, state: SyncState,
_old: SyncState, _old: SyncState | null,
data: ISyncStateData data?: ISyncStateData
) => { ) => {
if (state === "PREPARED") { if (state === "PREPARED") {
resolve(); resolve();
@@ -87,7 +86,7 @@ export async function initClient(
): Promise<MatrixClient> { ): Promise<MatrixClient> {
await loadOlm(); await loadOlm();
let indexedDB: IDBFactory; let indexedDB: IDBFactory | undefined;
try { try {
indexedDB = window.indexedDB; indexedDB = window.indexedDB;
} catch (e) {} } catch (e) {}
@@ -247,7 +246,7 @@ export function sanitiseRoomNameInput(input: string): string {
*/ */
export function roomNameFromRoomId(roomId: string): string { export function roomNameFromRoomId(roomId: string): string {
return roomId return roomId
.match(/([^:]+):.*$/)[1] .match(/([^:]+):.*$/)![1]
.substring(1) .substring(1)
.split("-") .split("-")
.map((part) => .map((part) =>
@@ -262,7 +261,7 @@ export function isLocalRoomId(roomId: string, client: MatrixClient): boolean {
return false; return false;
} }
const parts = roomId.match(/[^:]+:(.*)$/); const parts = roomId.match(/[^:]+:(.*)$/)!;
if (parts.length < 2) { if (parts.length < 2) {
return false; return false;
@@ -302,7 +301,7 @@ export async function createRoom(
"org.matrix.msc3401.call.member": 0, "org.matrix.msc3401.call.member": 0,
}, },
users: { users: {
[client.getUserId()]: 100, [client.getUserId()!]: 100,
}, },
}, },
}); });
@@ -346,15 +345,11 @@ export async function createRoom(
// Returns a URL to that will load Element Call with the given room // Returns a URL to that will load Element Call with the given room
export function getRoomUrl(roomIdOrAlias: string): string { export function getRoomUrl(roomIdOrAlias: string): string {
if (roomIdOrAlias.startsWith("#")) { if (roomIdOrAlias.startsWith("#")) {
const [localPart, host] = roomIdOrAlias.replace("#", "").split(":"); return `${window.location.protocol}//${window.location.host}/${
roomIdOrAlias.substring(1).split(":")[0]
if (host !== Config.defaultServerName()) { }`;
return `${window.location.protocol}//${window.location.host}/room/${roomIdOrAlias}`;
} else { } else {
return `${window.location.protocol}//${window.location.host}/${localPart}`; return `${window.location.protocol}//${window.location.host}/room?roomId=${roomIdOrAlias}`;
}
} else {
return `${window.location.protocol}//${window.location.host}/room/#?roomId=${roomIdOrAlias}`;
} }
} }
+14 -14
View File
@@ -61,46 +61,46 @@ export class OTelCall {
} }
public dispose() { public dispose() {
this.call.peerConn.removeEventListener( this.call.peerConn?.removeEventListener(
"connectionstatechange", "connectionstatechange",
this.onCallConnectionStateChanged this.onCallConnectionStateChanged
); );
this.call.peerConn.removeEventListener( this.call.peerConn?.removeEventListener(
"signalingstatechange", "signalingstatechange",
this.onCallSignalingStateChanged this.onCallSignalingStateChanged
); );
this.call.peerConn.removeEventListener( this.call.peerConn?.removeEventListener(
"iceconnectionstatechange", "iceconnectionstatechange",
this.onIceConnectionStateChanged this.onIceConnectionStateChanged
); );
this.call.peerConn.removeEventListener( this.call.peerConn?.removeEventListener(
"icegatheringstatechange", "icegatheringstatechange",
this.onIceGatheringStateChanged this.onIceGatheringStateChanged
); );
this.call.peerConn.removeEventListener( this.call.peerConn?.removeEventListener(
"icecandidateerror", "icecandidateerror",
this.onIceCandidateError this.onIceCandidateError
); );
} }
private addCallPeerConnListeners = (): void => { private addCallPeerConnListeners = (): void => {
this.call.peerConn.addEventListener( this.call.peerConn?.addEventListener(
"connectionstatechange", "connectionstatechange",
this.onCallConnectionStateChanged this.onCallConnectionStateChanged
); );
this.call.peerConn.addEventListener( this.call.peerConn?.addEventListener(
"signalingstatechange", "signalingstatechange",
this.onCallSignalingStateChanged this.onCallSignalingStateChanged
); );
this.call.peerConn.addEventListener( this.call.peerConn?.addEventListener(
"iceconnectionstatechange", "iceconnectionstatechange",
this.onIceConnectionStateChanged this.onIceConnectionStateChanged
); );
this.call.peerConn.addEventListener( this.call.peerConn?.addEventListener(
"icegatheringstatechange", "icegatheringstatechange",
this.onIceGatheringStateChanged this.onIceGatheringStateChanged
); );
this.call.peerConn.addEventListener( this.call.peerConn?.addEventListener(
"icecandidateerror", "icecandidateerror",
this.onIceCandidateError this.onIceCandidateError
); );
@@ -108,25 +108,25 @@ export class OTelCall {
public onCallConnectionStateChanged = (): void => { public onCallConnectionStateChanged = (): void => {
this.span.addEvent("matrix.call.callConnectionStateChange", { this.span.addEvent("matrix.call.callConnectionStateChange", {
callConnectionState: this.call.peerConn.connectionState, callConnectionState: this.call.peerConn?.connectionState,
}); });
}; };
public onCallSignalingStateChanged = (): void => { public onCallSignalingStateChanged = (): void => {
this.span.addEvent("matrix.call.callSignalingStateChange", { this.span.addEvent("matrix.call.callSignalingStateChange", {
callSignalingState: this.call.peerConn.signalingState, callSignalingState: this.call.peerConn?.signalingState,
}); });
}; };
public onIceConnectionStateChanged = (): void => { public onIceConnectionStateChanged = (): void => {
this.span.addEvent("matrix.call.iceConnectionStateChange", { this.span.addEvent("matrix.call.iceConnectionStateChange", {
iceConnectionState: this.call.peerConn.iceConnectionState, iceConnectionState: this.call.peerConn?.iceConnectionState,
}); });
}; };
public onIceGatheringStateChanged = (): void => { public onIceGatheringStateChanged = (): void => {
this.span.addEvent("matrix.call.iceGatheringStateChange", { this.span.addEvent("matrix.call.iceGatheringStateChange", {
iceGatheringState: this.call.peerConn.iceGatheringState, iceGatheringState: this.call.peerConn?.iceGatheringState,
}); });
}; };
+2 -2
View File
@@ -172,7 +172,7 @@ export class OTelGroupCallMembership {
if ( if (
!userCalls || !userCalls ||
!userCalls.has(callTrackingInfo.deviceId) || !userCalls.has(callTrackingInfo.deviceId) ||
userCalls.get(callTrackingInfo.deviceId).callId !== userCalls.get(callTrackingInfo.deviceId)?.callId !==
callTrackingInfo.call.callId callTrackingInfo.call.callId
) { ) {
callTrackingInfo.end(); callTrackingInfo.end();
@@ -420,7 +420,7 @@ export class OTelGroupCallMembership {
ctx ctx
); );
span.setAttribute("matrix.callId", callId); span.setAttribute("matrix.callId", callId ?? "unknown");
span.setAttribute( span.setAttribute(
"matrix.opponentMemberId", "matrix.opponentMemberId",
report.opponentMemberId ? report.opponentMemberId : "unknown" report.opponentMemberId ? report.opponentMemberId : "unknown"
+2 -8
View File
@@ -23,7 +23,6 @@ import { SemanticResourceAttributes } from "@opentelemetry/semantic-conventions"
import { logger } from "matrix-js-sdk/src/logger"; import { logger } from "matrix-js-sdk/src/logger";
import { PosthogSpanProcessor } from "../analytics/PosthogSpanProcessor"; import { PosthogSpanProcessor } from "../analytics/PosthogSpanProcessor";
import { Anonymity } from "../analytics/PosthogAnalytics";
import { Config } from "../config/Config"; import { Config } from "../config/Config";
import { RageshakeSpanProcessor } from "../analytics/RageshakeSpanProcessor"; import { RageshakeSpanProcessor } from "../analytics/RageshakeSpanProcessor";
@@ -34,8 +33,7 @@ let sharedInstance: ElementCallOpenTelemetry;
export class ElementCallOpenTelemetry { export class ElementCallOpenTelemetry {
private _provider: WebTracerProvider; private _provider: WebTracerProvider;
private _tracer: Tracer; private _tracer: Tracer;
private _anonymity: Anonymity; private otlpExporter?: OTLPTraceExporter;
private otlpExporter: OTLPTraceExporter;
public readonly rageshakeProcessor?: RageshakeSpanProcessor; public readonly rageshakeProcessor?: RageshakeSpanProcessor;
static globalInit(): void { static globalInit(): void {
@@ -100,7 +98,7 @@ export class ElementCallOpenTelemetry {
} }
public dispose(): void { public dispose(): void {
opentelemetry.trace.setGlobalTracerProvider(null); opentelemetry.trace.disable();
this._provider?.shutdown(); this._provider?.shutdown();
} }
@@ -115,8 +113,4 @@ export class ElementCallOpenTelemetry {
public get provider(): WebTracerProvider { public get provider(): WebTracerProvider {
return this._provider; return this._provider;
} }
public get anonymity(): Anonymity {
return this._anonymity;
}
} }
+1 -1
View File
@@ -46,7 +46,7 @@ export const PopoverMenuTrigger = forwardRef<
buttonRef buttonRef
); );
const popoverRef = useRef(); const popoverRef = useRef(null);
const { overlayProps } = useOverlayPosition({ const { overlayProps } = useOverlayPosition({
targetRef: buttonRef, targetRef: buttonRef,
+21 -17
View File
@@ -21,10 +21,10 @@ import { FileType } from "matrix-js-sdk/src/http-api";
import { useState, useCallback, useEffect } from "react"; import { useState, useCallback, useEffect } from "react";
interface ProfileLoadState { interface ProfileLoadState {
success?: boolean; success: boolean;
loading?: boolean; loading: boolean;
displayName: string; displayName?: string;
avatarUrl: string; avatarUrl?: string;
error?: Error; error?: Error;
} }
@@ -38,23 +38,26 @@ type ProfileSaveCallback = ({
removeAvatar: boolean; removeAvatar: boolean;
}) => Promise<void>; }) => Promise<void>;
export function useProfile(client: MatrixClient) { export function useProfile(client: MatrixClient | undefined) {
const [{ loading, displayName, avatarUrl, error, success }, setState] = const [{ success, loading, displayName, avatarUrl, error }, setState] =
useState<ProfileLoadState>(() => { useState<ProfileLoadState>(() => {
const user = client?.getUser(client.getUserId()); let user: User | undefined = undefined;
if (client) {
user = client.getUser(client.getUserId()!) ?? undefined;
}
return { return {
success: false, success: false,
loading: false, loading: false,
displayName: user?.rawDisplayName, displayName: user?.rawDisplayName,
avatarUrl: user?.avatarUrl, avatarUrl: user?.avatarUrl,
error: null, error: undefined,
}; };
}); });
useEffect(() => { useEffect(() => {
const onChangeUser = ( const onChangeUser = (
_event: MatrixEvent, _event: MatrixEvent | undefined,
{ displayName, avatarUrl }: User { displayName, avatarUrl }: User
) => { ) => {
setState({ setState({
@@ -62,17 +65,16 @@ export function useProfile(client: MatrixClient) {
loading: false, loading: false,
displayName, displayName,
avatarUrl, avatarUrl,
error: null, error: undefined,
}); });
}; };
let user: User; let user: User | null;
if (client) { if (client) {
const userId = client.getUserId(); const userId = client.getUserId()!;
user = client.getUser(userId); user = client.getUser(userId);
user.on(UserEvent.DisplayName, onChangeUser); user?.on(UserEvent.DisplayName, onChangeUser);
user.on(UserEvent.AvatarUrl, onChangeUser); user?.on(UserEvent.AvatarUrl, onChangeUser);
} }
return () => { return () => {
@@ -89,7 +91,7 @@ export function useProfile(client: MatrixClient) {
setState((prev) => ({ setState((prev) => ({
...prev, ...prev,
loading: true, loading: true,
error: null, error: undefined,
success: false, success: false,
})); }));
@@ -110,7 +112,9 @@ export function useProfile(client: MatrixClient) {
setState((prev) => ({ setState((prev) => ({
...prev, ...prev,
displayName, displayName,
avatarUrl: removeAvatar ? null : mxcAvatarUrl ?? prev.avatarUrl, avatarUrl: removeAvatar
? undefined
: mxcAvatarUrl ?? prev.avatarUrl,
loading: false, loading: false,
success: true, success: true,
})); }));
+15 -1
View File
@@ -38,6 +38,15 @@ export function GridLayoutMenu({ layout, setLayout }: Props) {
const { t } = useTranslation(); const { t } = useTranslation();
const tooltip = useCallback(() => t("Change layout"), [t]); const tooltip = useCallback(() => t("Change layout"), [t]);
const onAction = useCallback(
(key: React.Key) => {
setLayout(key.toString() as Layout);
},
[setLayout]
);
const onClose = useCallback(() => {}, []);
return ( return (
<PopoverMenuTrigger placement="bottom right"> <PopoverMenuTrigger placement="bottom right">
<TooltipTrigger tooltip={tooltip}> <TooltipTrigger tooltip={tooltip}>
@@ -46,7 +55,12 @@ export function GridLayoutMenu({ layout, setLayout }: Props) {
</Button> </Button>
</TooltipTrigger> </TooltipTrigger>
{(props: JSX.IntrinsicAttributes) => ( {(props: JSX.IntrinsicAttributes) => (
<Menu {...props} label={t("Grid layout menu")} onAction={setLayout}> <Menu
{...props}
label={t("Grid layout menu")}
onAction={onAction}
onClose={onClose}
>
<Item key="freedom" textValue={t("Freedom")}> <Item key="freedom" textValue={t("Freedom")}>
<FreedomIcon /> <FreedomIcon />
<span>Freedom</span> <span>Freedom</span>
+13 -5
View File
@@ -1,3 +1,6 @@
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-nocheck
/* /*
Copyright 2022 New Vector Ltd Copyright 2022 New Vector Ltd
@@ -70,7 +73,7 @@ const defaultCollapsedFields = [
]; ];
function shouldCollapse({ name }: CollapsedFieldProps) { function shouldCollapse({ name }: CollapsedFieldProps) {
return defaultCollapsedFields.includes(name); return name ? defaultCollapsedFields.includes(name) : false;
} }
function getUserName(userId: string) { function getUserName(userId: string) {
@@ -196,7 +199,7 @@ export function SequenceDiagramViewer({
onSelectUserId, onSelectUserId,
events, events,
}: SequenceDiagramViewerProps) { }: SequenceDiagramViewerProps) {
const mermaidElRef = useRef<HTMLDivElement>(); const mermaidElRef = useRef<HTMLDivElement>(null);
useEffect(() => { useEffect(() => {
mermaid.initialize({ mermaid.initialize({
@@ -217,6 +220,7 @@ export function SequenceDiagramViewer({
`; `;
mermaid.mermaidAPI.render("mermaid", graphDefinition, (svgCode: string) => { mermaid.mermaidAPI.render("mermaid", graphDefinition, (svgCode: string) => {
if (!mermaidElRef.current) return;
mermaidElRef.current.innerHTML = svgCode; mermaidElRef.current.innerHTML = svgCode;
}); });
}, [events, localUserId, selectedUserId]); }, [events, localUserId, selectedUserId]);
@@ -228,7 +232,7 @@ export function SequenceDiagramViewer({
className={styles.selectInput} className={styles.selectInput}
label="Remote User" label="Remote User"
selectedKey={selectedUserId} selectedKey={selectedUserId}
onSelectionChange={onSelectUserId} onSelectionChange={(key) => onSelectUserId(key.toString())}
> >
{remoteUserIds.map((userId) => ( {remoteUserIds.map((userId) => (
<Item key={userId}>{userId}</Item> <Item key={userId}>{userId}</Item>
@@ -498,7 +502,7 @@ export function GroupCallInspector({
return ( return (
<Resizable <Resizable
enable={{ top: true }} enable={{ top: true }}
defaultSize={{ height: 200, width: undefined }} defaultSize={{ height: 200, width: 0 }}
className={styles.inspector} className={styles.inspector}
> >
<div className={styles.toolbar}> <div className={styles.toolbar}>
@@ -507,7 +511,11 @@ export function GroupCallInspector({
</button> </button>
<button onClick={() => setCurrentTab("inspector")}>Inspector</button> <button onClick={() => setCurrentTab("inspector")}>Inspector</button>
</div> </div>
{currentTab === "sequence-diagrams" && ( {currentTab === "sequence-diagrams" &&
state.localUserId &&
selectedUserId &&
state.eventsByUserId &&
state.remoteUserIds && (
<SequenceDiagramViewer <SequenceDiagramViewer
localUserId={state.localUserId} localUserId={state.localUserId}
selectedUserId={selectedUserId} selectedUserId={selectedUserId}
+7 -11
View File
@@ -21,7 +21,6 @@ import { useTranslation } from "react-i18next";
import { useLoadGroupCall } from "./useLoadGroupCall"; import { useLoadGroupCall } from "./useLoadGroupCall";
import { ErrorView, FullScreenView } from "../FullScreenView"; import { ErrorView, FullScreenView } from "../FullScreenView";
import { usePageTitle } from "../usePageTitle";
interface Props { interface Props {
client: MatrixClient; client: MatrixClient;
@@ -39,26 +38,23 @@ export function GroupCallLoader({
createPtt, createPtt,
}: Props): JSX.Element { }: Props): JSX.Element {
const { t } = useTranslation(); const { t } = useTranslation();
const { loading, error, groupCall } = useLoadGroupCall( const groupCallState = useLoadGroupCall(
client, client,
roomIdOrAlias, roomIdOrAlias,
viaServers, viaServers,
createPtt createPtt
); );
usePageTitle(groupCall ? groupCall.room.name : t("Loading…")); switch (groupCallState.kind) {
case "loading":
if (loading) {
return ( return (
<FullScreenView> <FullScreenView>
<h1>{t("Loading…")}</h1> <h1>{t("Loading…")}</h1>
</FullScreenView> </FullScreenView>
); );
case "loaded":
return <>{children(groupCallState.groupCall)}</>;
case "failed":
return <ErrorView error={groupCallState.error} />;
} }
if (error) {
return <ErrorView error={error} />;
}
return <>{children(groupCall)}</>;
} }
+14 -24
View File
@@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
import { useCallback, useEffect, useState } from "react"; import { useCallback, useEffect, useMemo, useState } from "react";
import { useHistory } from "react-router-dom"; import { useHistory } from "react-router-dom";
import { GroupCall, GroupCallState } from "matrix-js-sdk/src/webrtc/groupCall"; import { GroupCall, GroupCallState } from "matrix-js-sdk/src/webrtc/groupCall";
import { MatrixClient } from "matrix-js-sdk/src/client"; import { MatrixClient } from "matrix-js-sdk/src/client";
@@ -36,7 +36,6 @@ import { UserChoices } from "../livekit/useLiveKit";
import { findDeviceByName } from "../media-utils"; import { findDeviceByName } from "../media-utils";
import { OpenIDLoader } from "../livekit/OpenIDLoader"; import { OpenIDLoader } from "../livekit/OpenIDLoader";
import { ActiveCall } from "./InCallView"; import { ActiveCall } from "./InCallView";
import { Config } from "../config/Config";
declare global { declare global {
interface Window { interface Window {
@@ -50,7 +49,6 @@ interface Props {
isEmbedded: boolean; isEmbedded: boolean;
preload: boolean; preload: boolean;
hideHeader: boolean; hideHeader: boolean;
roomIdOrAlias: string;
groupCall: GroupCall; groupCall: GroupCall;
} }
@@ -60,7 +58,6 @@ export function GroupCallView({
isEmbedded, isEmbedded,
preload, preload,
hideHeader, hideHeader,
roomIdOrAlias,
groupCall, groupCall,
}: Props) { }: Props) {
const { const {
@@ -83,13 +80,14 @@ export function GroupCallView({
}, [groupCall]); }, [groupCall]);
const { displayName, avatarUrl } = useProfile(client); const { displayName, avatarUrl } = useProfile(client);
const matrixInfo = useMemo((): MatrixInfo => {
const matrixInfo: MatrixInfo = { return {
displayName, displayName: displayName!,
avatarUrl, avatarUrl: avatarUrl!,
roomId: groupCall.room.roomId,
roomName: groupCall.room.name, roomName: groupCall.room.name,
roomIdOrAlias,
}; };
}, [displayName, avatarUrl, groupCall]);
useEffect(() => { useEffect(() => {
if (widget && preload) { if (widget && preload) {
@@ -140,14 +138,14 @@ export function GroupCallView({
PosthogAnalytics.instance.eventCallStarted.track(groupCall.groupCallId); PosthogAnalytics.instance.eventCallStarted.track(groupCall.groupCallId);
await Promise.all([ await Promise.all([
widget.api.setAlwaysOnScreen(true), widget!.api.setAlwaysOnScreen(true),
widget.api.transport.reply(ev.detail, {}), widget!.api.transport.reply(ev.detail, {}),
]); ]);
}; };
widget.lazyActions.on(ElementWidgetActions.JoinCall, onJoin); widget.lazyActions.on(ElementWidgetActions.JoinCall, onJoin);
return () => { return () => {
widget.lazyActions.off(ElementWidgetActions.JoinCall, onJoin); widget!.lazyActions.off(ElementWidgetActions.JoinCall, onJoin);
}; };
} }
}, [groupCall, preload, enter]); }, [groupCall, preload, enter]);
@@ -206,12 +204,12 @@ export function GroupCallView({
if (widget && state === GroupCallState.Entered) { if (widget && state === GroupCallState.Entered) {
const onHangup = async (ev: CustomEvent<IWidgetApiRequest>) => { const onHangup = async (ev: CustomEvent<IWidgetApiRequest>) => {
leave(); leave();
await widget.api.transport.reply(ev.detail, {}); await widget!.api.transport.reply(ev.detail, {});
widget.api.setAlwaysOnScreen(false); widget!.api.setAlwaysOnScreen(false);
}; };
widget.lazyActions.once(ElementWidgetActions.HangupCall, onHangup); widget.lazyActions.once(ElementWidgetActions.HangupCall, onHangup);
return () => { return () => {
widget.lazyActions.off(ElementWidgetActions.HangupCall, onHangup); widget!.lazyActions.off(ElementWidgetActions.HangupCall, onHangup);
}; };
} }
}, [groupCall, state, leave]); }, [groupCall, state, leave]);
@@ -220,20 +218,13 @@ export function GroupCallView({
undefined undefined
); );
const livekitServiceURL =
groupCall.foci[0]?.livekitServiceUrl ??
Config.get().livekit.livekit_service_url;
if (!livekitServiceURL) {
return <ErrorView error={new Error("No livekit_service_url defined")} />;
}
if (error) { if (error) {
return <ErrorView error={error} />; return <ErrorView error={error} />;
} else if (state === GroupCallState.Entered && userChoices) { } else if (state === GroupCallState.Entered && userChoices) {
return ( return (
<OpenIDLoader <OpenIDLoader
client={client} client={client}
livekitServiceURL={livekitServiceURL} groupCall={groupCall}
roomName={`${groupCall.room.roomId}-${groupCall.groupCallId}`} roomName={`${groupCall.room.roomId}-${groupCall.groupCallId}`}
> >
<ActiveCall <ActiveCall
@@ -243,7 +234,6 @@ export function GroupCallView({
onLeave={onLeave} onLeave={onLeave}
unencryptedEventsFromUsers={unencryptedEventsFromUsers} unencryptedEventsFromUsers={unencryptedEventsFromUsers}
hideHeader={hideHeader} hideHeader={hideHeader}
matrixInfo={matrixInfo}
userChoices={userChoices} userChoices={userChoices}
otelGroupCallMembership={otelGroupCallMembership} otelGroupCallMembership={otelGroupCallMembership}
/> />
+15 -18
View File
@@ -68,17 +68,15 @@ import { ElementWidgetActions, widget } from "../widget";
import { GridLayoutMenu } from "./GridLayoutMenu"; import { GridLayoutMenu } from "./GridLayoutMenu";
import { GroupCallInspector } from "./GroupCallInspector"; import { GroupCallInspector } from "./GroupCallInspector";
import styles from "./InCallView.module.css"; import styles from "./InCallView.module.css";
import { MatrixInfo } from "./VideoPreview";
import { useJoinRule } from "./useJoinRule"; import { useJoinRule } from "./useJoinRule";
import { ParticipantInfo } from "./useGroupCall"; import { ParticipantInfo } from "./useGroupCall";
import { ItemData, TileContent } from "../video-grid/VideoTile"; import { ItemData, TileContent, VideoTile } from "../video-grid/VideoTile";
import { NewVideoGrid } from "../video-grid/NewVideoGrid"; import { NewVideoGrid } from "../video-grid/NewVideoGrid";
import { OTelGroupCallMembership } from "../otel/OTelGroupCallMembership"; import { OTelGroupCallMembership } from "../otel/OTelGroupCallMembership";
import { SettingsModal } from "../settings/SettingsModal"; import { SettingsModal } from "../settings/SettingsModal";
import { InviteModal } from "./InviteModal"; import { InviteModal } from "./InviteModal";
import { useRageshakeRequestModal } from "../settings/submit-rageshake"; import { useRageshakeRequestModal } from "../settings/submit-rageshake";
import { RageshakeRequestModal } from "./RageshakeRequestModal"; import { RageshakeRequestModal } from "./RageshakeRequestModal";
import { VideoTile } from "../video-grid/VideoTile";
import { UserChoices, useLiveKit } from "../livekit/useLiveKit"; import { UserChoices, useLiveKit } from "../livekit/useLiveKit";
import { useMediaDevicesSwitcher } from "../livekit/useMediaDevicesSwitcher"; import { useMediaDevicesSwitcher } from "../livekit/useMediaDevicesSwitcher";
import { useFullscreen } from "./useFullscreen"; import { useFullscreen } from "./useFullscreen";
@@ -100,12 +98,14 @@ export function ActiveCall(props: ActiveCallProps) {
const sfuConfig = useSFUConfig(); const sfuConfig = useSFUConfig();
const livekitRoom = useLiveKit(props.userChoices, sfuConfig); const livekitRoom = useLiveKit(props.userChoices, sfuConfig);
if (!livekitRoom) {
return null;
}
return ( return (
livekitRoom && (
<RoomContext.Provider value={livekitRoom}> <RoomContext.Provider value={livekitRoom}>
<InCallView {...props} livekitRoom={livekitRoom} /> <InCallView {...props} livekitRoom={livekitRoom} />
</RoomContext.Provider> </RoomContext.Provider>
)
); );
} }
@@ -117,8 +117,7 @@ export interface InCallViewProps {
onLeave: () => void; onLeave: () => void;
unencryptedEventsFromUsers: Set<string>; unencryptedEventsFromUsers: Set<string>;
hideHeader: boolean; hideHeader: boolean;
matrixInfo: MatrixInfo; otelGroupCallMembership?: OTelGroupCallMembership;
otelGroupCallMembership: OTelGroupCallMembership;
} }
export function InCallView({ export function InCallView({
@@ -129,7 +128,6 @@ export function InCallView({
onLeave, onLeave,
unencryptedEventsFromUsers, unencryptedEventsFromUsers,
hideHeader, hideHeader,
matrixInfo,
otelGroupCallMembership, otelGroupCallMembership,
}: InCallViewProps) { }: InCallViewProps) {
const { t } = useTranslation(); const { t } = useTranslation();
@@ -203,11 +201,11 @@ export function InCallView({
if (widget) { if (widget) {
const onTileLayout = async (ev: CustomEvent<IWidgetApiRequest>) => { const onTileLayout = async (ev: CustomEvent<IWidgetApiRequest>) => {
setLayout("freedom"); setLayout("freedom");
await widget.api.transport.reply(ev.detail, {}); await widget!.api.transport.reply(ev.detail, {});
}; };
const onSpotlightLayout = async (ev: CustomEvent<IWidgetApiRequest>) => { const onSpotlightLayout = async (ev: CustomEvent<IWidgetApiRequest>) => {
setLayout("spotlight"); setLayout("spotlight");
await widget.api.transport.reply(ev.detail, {}); await widget!.api.transport.reply(ev.detail, {});
}; };
widget.lazyActions.on(ElementWidgetActions.TileLayout, onTileLayout); widget.lazyActions.on(ElementWidgetActions.TileLayout, onTileLayout);
@@ -217,8 +215,8 @@ export function InCallView({
); );
return () => { return () => {
widget.lazyActions.off(ElementWidgetActions.TileLayout, onTileLayout); widget!.lazyActions.off(ElementWidgetActions.TileLayout, onTileLayout);
widget.lazyActions.off( widget!.lazyActions.off(
ElementWidgetActions.SpotlightLayout, ElementWidgetActions.SpotlightLayout,
onSpotlightLayout onSpotlightLayout
); );
@@ -396,7 +394,7 @@ export function InCallView({
{!hideHeader && maximisedParticipant === null && ( {!hideHeader && maximisedParticipant === null && (
<Header> <Header>
<LeftNav> <LeftNav>
<RoomHeaderInfo roomName={matrixInfo.roomName} /> <RoomHeaderInfo roomName={groupCall.room.name} />
<VersionMismatchWarning <VersionMismatchWarning
users={unencryptedEventsFromUsers} users={unencryptedEventsFromUsers}
room={groupCall.room} room={groupCall.room}
@@ -416,16 +414,18 @@ export function InCallView({
{renderContent()} {renderContent()}
{footer} {footer}
</div> </div>
{otelGroupCallMembership && (
<GroupCallInspector <GroupCallInspector
client={client} client={client}
groupCall={groupCall} groupCall={groupCall}
otelGroupCallMembership={otelGroupCallMembership} otelGroupCallMembership={otelGroupCallMembership}
show={showInspector} show={showInspector}
/> />
)}
{rageshakeRequestModalState.isOpen && !noControls && ( {rageshakeRequestModalState.isOpen && !noControls && (
<RageshakeRequestModal <RageshakeRequestModal
{...rageshakeRequestModalProps} {...rageshakeRequestModalProps}
roomIdOrAlias={matrixInfo.roomIdOrAlias} roomId={groupCall.room.roomId}
/> />
)} )}
{settingsModalState.isOpen && ( {settingsModalState.isOpen && (
@@ -437,10 +437,7 @@ export function InCallView({
/> />
)} )}
{inviteModalState.isOpen && ( {inviteModalState.isOpen && (
<InviteModal <InviteModal roomId={groupCall.room.roomId} {...inviteModalProps} />
roomIdOrAlias={matrixInfo.roomIdOrAlias}
{...inviteModalProps}
/>
)} )}
</div> </div>
); );
+3 -3
View File
@@ -23,10 +23,10 @@ import { getRoomUrl } from "../matrix-utils";
import styles from "./InviteModal.module.css"; import styles from "./InviteModal.module.css";
interface Props extends Omit<ModalProps, "title" | "children"> { interface Props extends Omit<ModalProps, "title" | "children"> {
roomIdOrAlias: string; roomId: string;
} }
export const InviteModal: FC<Props> = ({ roomIdOrAlias, ...rest }) => { export const InviteModal: FC<Props> = ({ roomId, ...rest }) => {
const { t } = useTranslation(); const { t } = useTranslation();
return ( return (
@@ -40,7 +40,7 @@ export const InviteModal: FC<Props> = ({ roomIdOrAlias, ...rest }) => {
<p>{t("Copy and share this call link")}</p> <p>{t("Copy and share this call link")}</p>
<CopyButton <CopyButton
className={styles.copyButton} className={styles.copyButton}
value={getRoomUrl(roomIdOrAlias)} value={getRoomUrl(roomId)}
data-testid="modal_inviteLink" data-testid="modal_inviteLink"
/> />
</ModalContent> </ModalContent>
+2 -2
View File
@@ -39,7 +39,7 @@ export function LobbyView(props: Props) {
const { t } = useTranslation(); const { t } = useTranslation();
useLocationNavigation(); useLocationNavigation();
const joinCallButtonRef = useRef<HTMLButtonElement>(); const joinCallButtonRef = useRef<HTMLButtonElement>(null);
useEffect(() => { useEffect(() => {
if (joinCallButtonRef.current) { if (joinCallButtonRef.current) {
joinCallButtonRef.current.focus(); joinCallButtonRef.current.focus();
@@ -81,7 +81,7 @@ export function LobbyView(props: Props) {
<Body>Or</Body> <Body>Or</Body>
<CopyButton <CopyButton
variant="secondaryCopy" variant="secondaryCopy"
value={getRoomUrl(props.matrixInfo.roomName)} value={getRoomUrl(props.matrixInfo.roomId)}
className={styles.copyButton} className={styles.copyButton}
copiedMessage={t("Call link copied")} copiedMessage={t("Call link copied")}
data-testid="lobby_inviteLink" data-testid="lobby_inviteLink"
+3 -3
View File
@@ -25,13 +25,13 @@ import { Body } from "../typography/Typography";
interface Props extends Omit<ModalProps, "title" | "children"> { interface Props extends Omit<ModalProps, "title" | "children"> {
rageshakeRequestId: string; rageshakeRequestId: string;
roomIdOrAlias: string; roomId: string;
onClose: () => void; onClose: () => void;
} }
export const RageshakeRequestModal: FC<Props> = ({ export const RageshakeRequestModal: FC<Props> = ({
rageshakeRequestId, rageshakeRequestId,
roomIdOrAlias, roomId,
...rest ...rest
}) => { }) => {
const { t } = useTranslation(); const { t } = useTranslation();
@@ -57,7 +57,7 @@ export const RageshakeRequestModal: FC<Props> = ({
submitRageshake({ submitRageshake({
sendLogs: true, sendLogs: true,
rageshakeRequestId, rageshakeRequestId,
roomId: roomIdOrAlias, // Possibly not a room ID, but oh well roomId,
}) })
} }
disabled={sending} disabled={sending}
+2
View File
@@ -36,6 +36,8 @@ export function RoomAuthView() {
useRegisterPasswordlessUser(); useRegisterPasswordlessUser();
const onSubmit = useCallback( const onSubmit = useCallback(
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
(e) => { (e) => {
e.preventDefault(); e.preventDefault();
const data = new FormData(e.target); const data = new FormData(e.target);
+12 -12
View File
@@ -18,7 +18,7 @@ import { FC, useEffect, useState, useCallback } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import type { GroupCall } from "matrix-js-sdk/src/webrtc/groupCall"; import type { GroupCall } from "matrix-js-sdk/src/webrtc/groupCall";
import { useClient } from "../ClientContext"; import { useClientLegacy } from "../ClientContext";
import { ErrorView, LoadingView } from "../FullScreenView"; import { ErrorView, LoadingView } from "../FullScreenView";
import { RoomAuthView } from "./RoomAuthView"; import { RoomAuthView } from "./RoomAuthView";
import { GroupCallLoader } from "./GroupCallLoader"; import { GroupCallLoader } from "./GroupCallLoader";
@@ -30,8 +30,6 @@ import { useOptInAnalytics } from "../settings/useSetting";
export const RoomPage: FC = () => { export const RoomPage: FC = () => {
const { t } = useTranslation(); const { t } = useTranslation();
const { loading, isAuthenticated, error, client, isPasswordlessUser } =
useClient();
const { const {
roomAlias, roomAlias,
@@ -52,39 +50,41 @@ export const RoomPage: FC = () => {
useEffect(() => { useEffect(() => {
// During the beta, opt into analytics by default // During the beta, opt into analytics by default
if (optInAnalytics === null) setOptInAnalytics(true); if (optInAnalytics === null && setOptInAnalytics) setOptInAnalytics(true);
}, [optInAnalytics, setOptInAnalytics]); }, [optInAnalytics, setOptInAnalytics]);
const { loading, authenticated, client, error, passwordlessUser } =
useClientLegacy();
useEffect(() => { useEffect(() => {
// If we've finished loading, are not already authed and we've been given a display name as // If we've finished loading, are not already authed and we've been given a display name as
// a URL param, automatically register a passwordless user // a URL param, automatically register a passwordless user
if (!loading && !isAuthenticated && displayName) { if (!loading && !authenticated && displayName) {
setIsRegistering(true); setIsRegistering(true);
registerPasswordlessUser(displayName).finally(() => { registerPasswordlessUser(displayName).finally(() => {
setIsRegistering(false); setIsRegistering(false);
}); });
} }
}, [ }, [
isAuthenticated, loading,
authenticated,
displayName, displayName,
setIsRegistering, setIsRegistering,
registerPasswordlessUser, registerPasswordlessUser,
loading,
]); ]);
const groupCallView = useCallback( const groupCallView = useCallback(
(groupCall: GroupCall) => ( (groupCall: GroupCall) => (
<GroupCallView <GroupCallView
client={client} client={client!}
roomIdOrAlias={roomIdOrAlias}
groupCall={groupCall} groupCall={groupCall}
isPasswordlessUser={isPasswordlessUser} isPasswordlessUser={passwordlessUser}
isEmbedded={isEmbedded} isEmbedded={isEmbedded}
preload={preload} preload={preload}
hideHeader={hideHeader} hideHeader={hideHeader}
/> />
), ),
[client, roomIdOrAlias, isPasswordlessUser, isEmbedded, preload, hideHeader] [client, passwordlessUser, isEmbedded, preload, hideHeader]
); );
if (loading || isRegistering) { if (loading || isRegistering) {
@@ -95,7 +95,7 @@ export const RoomPage: FC = () => {
return <ErrorView error={error} />; return <ErrorView error={error} />;
} }
if (!isAuthenticated) { if (!client) {
return <RoomAuthView />; return <RoomAuthView />;
} }
-44
View File
@@ -1,44 +0,0 @@
/*
Copyright 2022 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import { useEffect } from "react";
import { useLocation, useHistory } from "react-router-dom";
import { Config } from "../config/Config";
import { LoadingView } from "../FullScreenView";
// A component that, when loaded, redirects the client to a full room URL
// based on the current URL being an abbreviated room URL
export function RoomRedirect() {
const { pathname } = useLocation();
const history = useHistory();
useEffect(() => {
let roomId = pathname;
if (pathname.startsWith("/")) {
roomId = roomId.substring(1, roomId.length);
}
if (!roomId.startsWith("#") && !roomId.startsWith("!")) {
roomId = `#${roomId}:${Config.defaultServerName()}`;
}
history.replace(`/room/${roomId.toLowerCase()}`);
}, [pathname, history]);
return <LoadingView />;
}
+11 -31
View File
@@ -34,8 +34,8 @@ import { useDefaultDevices } from "../settings/useSetting";
export type MatrixInfo = { export type MatrixInfo = {
displayName: string; displayName: string;
avatarUrl: string; avatarUrl: string;
roomId: string;
roomName: string; roomName: string;
roomIdOrAlias: string;
}; };
interface Props { interface Props {
@@ -66,11 +66,6 @@ export function VideoPreview({ matrixInfo, onUserChoicesChanged }: Props) {
const [videoEnabled, setVideoEnabled] = useState<boolean>(true); const [videoEnabled, setVideoEnabled] = useState<boolean>(true);
const [audioEnabled, setAudioEnabled] = useState<boolean>(true); const [audioEnabled, setAudioEnabled] = useState<boolean>(true);
// we store if the tracks are currently initializing to not show them as muted.
// showing them as muted while they are not yet available makes the buttons flicker undesirable during startup.
const [initializingVideo, setInitializingVideo] = useState<boolean>(true);
const [initializingAudio, setInitializingAudio] = useState<boolean>(true);
// The settings are updated as soon as the device changes. We wrap the settings value in a ref to store their initial value. // The settings are updated as soon as the device changes. We wrap the settings value in a ref to store their initial value.
// Not changing the device options prohibits the usePreviewTracks hook to recreate the tracks. // Not changing the device options prohibits the usePreviewTracks hook to recreate the tracks.
const initialDefaultDevices = useRef(useDefaultDevices()[0]); const initialDefaultDevices = useRef(useDefaultDevices()[0]);
@@ -99,32 +94,23 @@ export function VideoPreview({ matrixInfo, onUserChoicesChanged }: Props) {
const requestPermissions = !!audioTrack && !!videoTrack; const requestPermissions = !!audioTrack && !!videoTrack;
const mediaSwitcher = useMediaDevicesSwitcher( const mediaSwitcher = useMediaDevicesSwitcher(
undefined, undefined,
{ { videoTrack, audioTrack },
videoTrack,
audioTrack,
},
requestPermissions requestPermissions
); );
const { videoIn, audioIn } = mediaSwitcher; const { videoIn, audioIn } = mediaSwitcher;
const videoEl = React.useRef(null); const videoEl = React.useRef(null);
// pretend the video is available until the initialization is over
const videoAvailableAndEnabled =
videoEnabled && (!!videoTrack || initializingVideo);
const audioAvailableAndEnabled =
audioEnabled && (!!videoTrack || initializingAudio);
useEffect(() => { useEffect(() => {
// Effect to update the settings // Effect to update the settings
onUserChoicesChanged({ onUserChoicesChanged({
video: { video: {
selectedId: videoIn.selectedId, selectedId: videoIn.selectedId,
enabled: videoAvailableAndEnabled, enabled: videoEnabled,
}, },
audio: { audio: {
selectedId: audioIn.selectedId, selectedId: audioIn.selectedId,
enabled: audioAvailableAndEnabled, enabled: audioEnabled,
}, },
}); });
}, [ }, [
@@ -133,24 +119,18 @@ export function VideoPreview({ matrixInfo, onUserChoicesChanged }: Props) {
videoEnabled, videoEnabled,
audioIn.selectedId, audioIn.selectedId,
audioEnabled, audioEnabled,
videoAvailableAndEnabled, videoTrack,
audioAvailableAndEnabled, audioTrack,
]); ]);
useEffect(() => { useEffect(() => {
// Effect to update the initial device selection for the ui elements based on the current preview track. // Effect to update the initial device selection for the ui elements based on the current preview track.
if (!videoIn.selectedId || videoIn.selectedId == "") { if (!videoIn.selectedId || videoIn.selectedId == "") {
if (videoTrack) {
setInitializingVideo(false);
}
videoTrack?.getDeviceId().then((videoId) => { videoTrack?.getDeviceId().then((videoId) => {
videoIn.setSelected(videoId ?? "default"); videoIn.setSelected(videoId ?? "default");
}); });
} }
if (!audioIn.selectedId || audioIn.selectedId == "") { if (!audioIn.selectedId || audioIn.selectedId == "") {
if (audioTrack) {
setInitializingAudio(false);
}
audioTrack?.getDeviceId().then((audioId) => { audioTrack?.getDeviceId().then((audioId) => {
// getDeviceId() can return undefined for audio devices. This happens if // getDeviceId() can return undefined for audio devices. This happens if
// the devices list uses "default" as the device id for the current // the devices list uses "default" as the device id for the current
@@ -197,19 +177,19 @@ export function VideoPreview({ matrixInfo, onUserChoicesChanged }: Props) {
)} )}
<div className={styles.previewButtons}> <div className={styles.previewButtons}>
<MicButton <MicButton
muted={!audioAvailableAndEnabled} muted={!audioEnabled}
onPress={() => setAudioEnabled(!audioAvailableAndEnabled)} onPress={() => setAudioEnabled(!audioEnabled)}
disabled={!audioTrack} disabled={!audioTrack}
/> />
<VideoButton <VideoButton
muted={!videoAvailableAndEnabled} muted={!videoEnabled}
onPress={() => setVideoEnabled(!videoAvailableAndEnabled)} onPress={() => setVideoEnabled(!videoEnabled)}
disabled={!videoTrack} disabled={!videoTrack}
/> />
<SettingsButton onPress={openSettings} /> <SettingsButton onPress={openSettings} />
</div> </div>
</> </>
{settingsModalState.isOpen && ( {settingsModalState.isOpen && client && (
<SettingsModal <SettingsModal
client={client} client={client}
mediaDevicesSwitcher={mediaSwitcher} mediaDevicesSwitcher={mediaSwitcher}
+21 -30
View File
@@ -15,6 +15,7 @@ limitations under the License.
*/ */
import { useCallback, useEffect, useReducer, useState } from "react"; import { useCallback, useEffect, useReducer, useState } from "react";
import * as Sentry from "@sentry/react";
import { import {
GroupCallEvent, GroupCallEvent,
GroupCallState, GroupCallState,
@@ -58,12 +59,12 @@ export interface ParticipantInfo {
interface UseGroupCallReturnType { interface UseGroupCallReturnType {
state: GroupCallState; state: GroupCallState;
localCallFeed: CallFeed; localCallFeed?: CallFeed;
activeSpeaker: CallFeed | null; activeSpeaker?: CallFeed;
userMediaFeeds: CallFeed[]; userMediaFeeds: CallFeed[];
microphoneMuted: boolean; microphoneMuted: boolean;
localVideoMuted: boolean; localVideoMuted: boolean;
error: TranslatedError | null; error?: TranslatedError;
initLocalCallFeed: () => void; initLocalCallFeed: () => void;
enter: () => Promise<void>; enter: () => Promise<void>;
leave: () => void; leave: () => void;
@@ -74,23 +75,21 @@ interface UseGroupCallReturnType {
requestingScreenshare: boolean; requestingScreenshare: boolean;
isScreensharing: boolean; isScreensharing: boolean;
screenshareFeeds: CallFeed[]; screenshareFeeds: CallFeed[];
localDesktopCapturerSourceId: string; // XXX: This looks unused?
participants: Map<RoomMember, Map<string, ParticipantInfo>>; participants: Map<RoomMember, Map<string, ParticipantInfo>>;
hasLocalParticipant: boolean; hasLocalParticipant: boolean;
unencryptedEventsFromUsers: Set<string>; unencryptedEventsFromUsers: Set<string>;
otelGroupCallMembership: OTelGroupCallMembership; otelGroupCallMembership?: OTelGroupCallMembership;
} }
interface State { interface State {
state: GroupCallState; state: GroupCallState;
localCallFeed: CallFeed; localCallFeed?: CallFeed;
activeSpeaker: CallFeed | null; activeSpeaker?: CallFeed;
userMediaFeeds: CallFeed[]; userMediaFeeds: CallFeed[];
error: TranslatedError | null; error?: TranslatedError;
microphoneMuted: boolean; microphoneMuted: boolean;
localVideoMuted: boolean; localVideoMuted: boolean;
screenshareFeeds: CallFeed[]; screenshareFeeds: CallFeed[];
localDesktopCapturerSourceId: string;
isScreensharing: boolean; isScreensharing: boolean;
requestingScreenshare: boolean; requestingScreenshare: boolean;
participants: Map<RoomMember, Map<string, ParticipantInfo>>; participants: Map<RoomMember, Map<string, ParticipantInfo>>;
@@ -101,7 +100,7 @@ interface State {
// level so that it doesn't pop in & out of existence as react mounts & unmounts // level so that it doesn't pop in & out of existence as react mounts & unmounts
// components. The right solution is probably for this to live in the js-sdk and have // components. The right solution is probably for this to live in the js-sdk and have
// the same lifetime as groupcalls themselves. // the same lifetime as groupcalls themselves.
let groupCallOTelMembership: OTelGroupCallMembership; let groupCallOTelMembership: OTelGroupCallMembership | undefined;
let groupCallOTelMembershipGroupCallId: string; let groupCallOTelMembershipGroupCallId: string;
function getParticipants( function getParticipants(
@@ -159,7 +158,6 @@ export function useGroupCall(
localVideoMuted, localVideoMuted,
isScreensharing, isScreensharing,
screenshareFeeds, screenshareFeeds,
localDesktopCapturerSourceId,
participants, participants,
hasLocalParticipant, hasLocalParticipant,
requestingScreenshare, requestingScreenshare,
@@ -167,15 +165,11 @@ export function useGroupCall(
setState, setState,
] = useState<State>({ ] = useState<State>({
state: GroupCallState.LocalCallFeedUninitialized, state: GroupCallState.LocalCallFeedUninitialized,
localCallFeed: null,
activeSpeaker: null,
userMediaFeeds: [], userMediaFeeds: [],
error: null,
microphoneMuted: false, microphoneMuted: false,
localVideoMuted: false, localVideoMuted: false,
isScreensharing: false, isScreensharing: false,
screenshareFeeds: [], screenshareFeeds: [],
localDesktopCapturerSourceId: null,
requestingScreenshare: false, requestingScreenshare: false,
participants: new Map(), participants: new Map(),
hasLocalParticipant: false, hasLocalParticipant: false,
@@ -248,12 +242,11 @@ export function useGroupCall(
updateState({ updateState({
state: groupCall.state, state: groupCall.state,
localCallFeed: groupCall.localCallFeed, localCallFeed: groupCall.localCallFeed,
activeSpeaker: groupCall.activeSpeaker ?? null, activeSpeaker: groupCall.activeSpeaker,
userMediaFeeds: [...groupCall.userMediaFeeds], userMediaFeeds: [...groupCall.userMediaFeeds],
microphoneMuted: groupCall.isMicrophoneMuted(), microphoneMuted: groupCall.isMicrophoneMuted(),
localVideoMuted: groupCall.isLocalVideoMuted(), localVideoMuted: groupCall.isLocalVideoMuted(),
isScreensharing: groupCall.isScreensharing(), isScreensharing: groupCall.isScreensharing(),
localDesktopCapturerSourceId: groupCall.localDesktopCapturerSourceId,
screenshareFeeds: [...groupCall.screenshareFeeds], screenshareFeeds: [...groupCall.screenshareFeeds],
}); });
} }
@@ -303,7 +296,7 @@ export function useGroupCall(
function onActiveSpeakerChanged(activeSpeaker: CallFeed | undefined): void { function onActiveSpeakerChanged(activeSpeaker: CallFeed | undefined): void {
updateState({ updateState({
activeSpeaker: activeSpeaker ?? null, activeSpeaker: activeSpeaker,
}); });
} }
@@ -319,12 +312,11 @@ export function useGroupCall(
function onLocalScreenshareStateChanged( function onLocalScreenshareStateChanged(
isScreensharing: boolean, isScreensharing: boolean,
_localScreenshareFeed: CallFeed, _localScreenshareFeed?: CallFeed,
localDesktopCapturerSourceId: string localDesktopCapturerSourceId?: string
): void { ): void {
updateState({ updateState({
isScreensharing, isScreensharing,
localDesktopCapturerSourceId,
}); });
} }
@@ -340,6 +332,7 @@ export function useGroupCall(
} }
function onError(e: GroupCallError): void { function onError(e: GroupCallError): void {
Sentry.captureException(e);
if (e.code === GroupCallErrorCode.UnknownDevice) { if (e.code === GroupCallErrorCode.UnknownDevice) {
const unknownDeviceError = e as GroupCallUnknownDeviceError; const unknownDeviceError = e as GroupCallUnknownDeviceError;
addUnencryptedEventUser(unknownDeviceError.userId); addUnencryptedEventUser(unknownDeviceError.userId);
@@ -405,15 +398,14 @@ export function useGroupCall(
); );
updateState({ updateState({
error: null, error: undefined,
state: groupCall.state, state: groupCall.state,
localCallFeed: groupCall.localCallFeed, localCallFeed: groupCall.localCallFeed,
activeSpeaker: groupCall.activeSpeaker ?? null, activeSpeaker: groupCall.activeSpeaker,
userMediaFeeds: [...groupCall.userMediaFeeds], userMediaFeeds: [...groupCall.userMediaFeeds],
microphoneMuted: groupCall.isMicrophoneMuted(), microphoneMuted: groupCall.isMicrophoneMuted(),
localVideoMuted: groupCall.isLocalVideoMuted(), localVideoMuted: groupCall.isLocalVideoMuted(),
isScreensharing: groupCall.isScreensharing(), isScreensharing: groupCall.isScreensharing(),
localDesktopCapturerSourceId: groupCall.localDesktopCapturerSourceId,
screenshareFeeds: [...groupCall.screenshareFeeds], screenshareFeeds: [...groupCall.screenshareFeeds],
participants: getParticipants(groupCall), participants: getParticipants(groupCall),
hasLocalParticipant: groupCall.hasLocalParticipant(), hasLocalParticipant: groupCall.hasLocalParticipant(),
@@ -516,7 +508,7 @@ export function useGroupCall(
}, [groupCall]); }, [groupCall]);
const setMicrophoneMuted = useCallback( const setMicrophoneMuted = useCallback(
(setMuted) => { (setMuted: boolean) => {
groupCall.setMicrophoneMuted(setMuted); groupCall.setMicrophoneMuted(setMuted);
groupCallOTelMembership?.onSetMicrophoneMuted(setMuted); groupCallOTelMembership?.onSetMicrophoneMuted(setMuted);
PosthogAnalytics.instance.eventMuteMicrophone.track( PosthogAnalytics.instance.eventMuteMicrophone.track(
@@ -575,7 +567,7 @@ export function useGroupCall(
desktopCapturerSourceId: data.desktopCapturerSourceId as string, desktopCapturerSourceId: data.desktopCapturerSourceId as string,
audio: !data.desktopCapturerSourceId, audio: !data.desktopCapturerSourceId,
}); });
await widget.api.transport.reply(ev.detail, {}); await widget?.api.transport.reply(ev.detail, {});
}, },
[groupCall, updateState] [groupCall, updateState]
); );
@@ -584,7 +576,7 @@ export function useGroupCall(
async (ev: CustomEvent<IWidgetApiRequest>) => { async (ev: CustomEvent<IWidgetApiRequest>) => {
updateState({ requestingScreenshare: false }); updateState({ requestingScreenshare: false });
await groupCall.setScreensharingEnabled(false); await groupCall.setScreensharingEnabled(false);
await widget.api.transport.reply(ev.detail, {}); await widget?.api.transport.reply(ev.detail, {});
}, },
[groupCall, updateState] [groupCall, updateState]
); );
@@ -601,11 +593,11 @@ export function useGroupCall(
); );
return () => { return () => {
widget.lazyActions.off( widget?.lazyActions.off(
ElementWidgetActions.ScreenshareStart, ElementWidgetActions.ScreenshareStart,
onScreenshareStart onScreenshareStart
); );
widget.lazyActions.off( widget?.lazyActions.off(
ElementWidgetActions.ScreenshareStop, ElementWidgetActions.ScreenshareStop,
onScreenshareStop onScreenshareStop
); );
@@ -644,7 +636,6 @@ export function useGroupCall(
requestingScreenshare, requestingScreenshare,
isScreensharing, isScreensharing,
screenshareFeeds, screenshareFeeds,
localDesktopCapturerSourceId,
participants, participants,
hasLocalParticipant, hasLocalParticipant,
unencryptedEventsFromUsers, unencryptedEventsFromUsers,
+30 -12
View File
@@ -34,8 +34,26 @@ import { widget } from "../widget";
const STATS_COLLECT_INTERVAL_TIME_MS = 10000; const STATS_COLLECT_INTERVAL_TIME_MS = 10000;
export type GroupCallLoaded = {
kind: "loaded";
groupCall: GroupCall;
};
export type GroupCallLoadFailed = {
kind: "failed";
error: Error;
};
export type GroupCallLoading = {
kind: "loading";
};
export type GroupCallStatus =
| GroupCallLoaded
| GroupCallLoadFailed
| GroupCallLoading;
export interface GroupCallLoadState { export interface GroupCallLoadState {
loading: boolean;
error?: Error; error?: Error;
groupCall?: GroupCall; groupCall?: GroupCall;
} }
@@ -45,13 +63,11 @@ export const useLoadGroupCall = (
roomIdOrAlias: string, roomIdOrAlias: string,
viaServers: string[], viaServers: string[],
createPtt: boolean createPtt: boolean
): GroupCallLoadState => { ): GroupCallStatus => {
const { t } = useTranslation(); const { t } = useTranslation();
const [state, setState] = useState<GroupCallLoadState>({ loading: true }); const [state, setState] = useState<GroupCallStatus>({ kind: "loading" });
useEffect(() => { useEffect(() => {
setState({ loading: true });
const fetchOrCreateRoom = async (): Promise<Room> => { const fetchOrCreateRoom = async (): Promise<Room> => {
try { try {
// We lowercase the localpart when we create the room, so we must lowercase // We lowercase the localpart when we create the room, so we must lowercase
@@ -74,8 +90,14 @@ export const useLoadGroupCall = (
} catch (error) { } catch (error) {
if ( if (
isLocalRoomId(roomIdOrAlias, client) && isLocalRoomId(roomIdOrAlias, client) &&
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
(error.errcode === "M_NOT_FOUND" || (error.errcode === "M_NOT_FOUND" ||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
(error.message && (error.message &&
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
error.message.indexOf("Failed to fetch alias") !== -1)) error.message.indexOf("Failed to fetch alias") !== -1))
) { ) {
// The room doesn't exist, but we can create it // The room doesn't exist, but we can create it
@@ -86,7 +108,7 @@ export const useLoadGroupCall = (
); );
// likewise, wait for the room // likewise, wait for the room
await client.waitUntilRoomReadyForGroupCalls(roomId); await client.waitUntilRoomReadyForGroupCalls(roomId);
return client.getRoom(roomId); return client.getRoom(roomId)!;
} else { } else {
throw error; throw error;
} }
@@ -170,12 +192,8 @@ export const useLoadGroupCall = (
waitForClientSyncing() waitForClientSyncing()
.then(fetchOrCreateGroupCall) .then(fetchOrCreateGroupCall)
.then((groupCall) => .then((groupCall) => setState({ kind: "loaded", groupCall }))
setState((prevState) => ({ ...prevState, loading: false, groupCall })) .catch((error) => setState({ kind: "failed", error }));
)
.catch((error) =>
setState((prevState) => ({ ...prevState, loading: false, error }))
);
}, [client, roomIdOrAlias, viaServers, createPtt, t]); }, [client, roomIdOrAlias, viaServers, createPtt, t]);
return state; return state;
+8
View File
@@ -55,14 +55,22 @@ export function usePageUnload(callback: () => void) {
// iOS doesn't fire beforeunload event, so leave the call when you hide the page. // iOS doesn't fire beforeunload event, so leave the call when you hide the page.
if (isIOS()) { if (isIOS()) {
window.addEventListener("pagehide", onBeforeUnload); window.addEventListener("pagehide", onBeforeUnload);
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
document.addEventListener("visibilitychange", onBeforeUnload); document.addEventListener("visibilitychange", onBeforeUnload);
} }
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
window.addEventListener("beforeunload", onBeforeUnload); window.addEventListener("beforeunload", onBeforeUnload);
return () => { return () => {
window.removeEventListener("pagehide", onBeforeUnload); window.removeEventListener("pagehide", onBeforeUnload);
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
document.removeEventListener("visibilitychange", onBeforeUnload); document.removeEventListener("visibilitychange", onBeforeUnload);
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
window.removeEventListener("beforeunload", onBeforeUnload); window.removeEventListener("beforeunload", onBeforeUnload);
clearTimeout(pageVisibilityTimeout); clearTimeout(pageVisibilityTimeout);
}; };
+2
View File
@@ -35,6 +35,8 @@ export function FeedbackSettingsTab({ roomId }: Props) {
const sendRageshakeRequest = useRageshakeRequest(); const sendRageshakeRequest = useRageshakeRequest();
const onSubmitFeedback = useCallback( const onSubmitFeedback = useCallback(
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
(e) => { (e) => {
e.preventDefault(); e.preventDefault();
const data = new FormData(e.target); const data = new FormData(e.target);
+8
View File
@@ -59,8 +59,14 @@ export function ProfileSettingsTab({ client }: Props) {
? displayNameDataEntry ? displayNameDataEntry
: displayNameDataEntry?.name ?? null; : displayNameDataEntry?.name ?? null;
if (!displayName) {
return;
}
saveProfile({ saveProfile({
displayName, displayName,
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
avatar: avatar && avatarSize > 0 ? avatar : undefined, avatar: avatar && avatarSize > 0 ? avatar : undefined,
removeAvatar: removeAvatar.current && (!avatar || avatarSize === 0), removeAvatar: removeAvatar.current && (!avatar || avatarSize === 0),
}); });
@@ -71,6 +77,7 @@ export function ProfileSettingsTab({ client }: Props) {
return ( return (
<form onChange={onFormChange} ref={formRef} className={styles.content}> <form onChange={onFormChange} ref={formRef} className={styles.content}>
<FieldRow className={styles.avatarFieldRow}> <FieldRow className={styles.avatarFieldRow}>
{displayName && (
<AvatarInputField <AvatarInputField
id="avatar" id="avatar"
name="avatar" name="avatar"
@@ -79,6 +86,7 @@ export function ProfileSettingsTab({ client }: Props) {
displayName={displayName} displayName={displayName}
onRemoveAvatar={onRemoveAvatar} onRemoveAvatar={onRemoveAvatar}
/> />
)}
</FieldRow> </FieldRow>
<FieldRow> <FieldRow>
<InputField <InputField
+48 -33
View File
@@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
import { ChangeEvent, useCallback, useState } from "react"; import { ChangeEvent, Key, useCallback, useState } from "react";
import { Item } from "@react-stately/collections"; import { Item } from "@react-stately/collections";
import { Trans, useTranslation } from "react-i18next"; import { Trans, useTranslation } from "react-i18next";
import { MatrixClient } from "matrix-js-sdk"; import { MatrixClient } from "matrix-js-sdk";
@@ -99,8 +99,8 @@ export const SettingsModal = (props: Props) => {
const [selectedTab, setSelectedTab] = useState<string | undefined>(); const [selectedTab, setSelectedTab] = useState<string | undefined>();
const onSelectedTabChanged = useCallback( const onSelectedTabChanged = useCallback(
(tab) => { (tab: Key) => {
setSelectedTab(tab); setSelectedTab(tab.toString());
}, },
[setSelectedTab] [setSelectedTab]
); );
@@ -118,19 +118,7 @@ export const SettingsModal = (props: Props) => {
const devices = props.mediaDevicesSwitcher; const devices = props.mediaDevicesSwitcher;
return ( const audioTab = (
<Modal
title={t("Settings")}
isDismissable
mobileFullScreen
className={styles.settingsModal}
{...props}
>
<TabContainer
onSelectionChange={onSelectedTabChanged}
selectedKey={selectedTab ?? props.defaultTab ?? "audio"}
className={styles.tabContainer}
>
<TabItem <TabItem
key="audio" key="audio"
title={ title={
@@ -143,6 +131,9 @@ export const SettingsModal = (props: Props) => {
{devices && generateDeviceSelection(devices.audioIn, t("Microphone"))} {devices && generateDeviceSelection(devices.audioIn, t("Microphone"))}
{devices && generateDeviceSelection(devices.audioOut, t("Speaker"))} {devices && generateDeviceSelection(devices.audioOut, t("Speaker"))}
</TabItem> </TabItem>
);
const videoTab = (
<TabItem <TabItem
key="video" key="video"
title={ title={
@@ -154,7 +145,9 @@ export const SettingsModal = (props: Props) => {
> >
{devices && generateDeviceSelection(devices.videoIn, t("Camera"))} {devices && generateDeviceSelection(devices.videoIn, t("Camera"))}
</TabItem> </TabItem>
{!isEmbedded && ( );
const profileTab = (
<TabItem <TabItem
key="profile" key="profile"
title={ title={
@@ -166,7 +159,9 @@ export const SettingsModal = (props: Props) => {
> >
<ProfileSettingsTab client={props.client} /> <ProfileSettingsTab client={props.client} />
</TabItem> </TabItem>
)} );
const feedbackTab = (
<TabItem <TabItem
key="feedback" key="feedback"
title={ title={
@@ -178,6 +173,9 @@ export const SettingsModal = (props: Props) => {
> >
<FeedbackSettingsTab roomId={props.roomId} /> <FeedbackSettingsTab roomId={props.roomId} />
</TabItem> </TabItem>
);
const moreTab = (
<TabItem <TabItem
key="more" key="more"
title={ title={
@@ -188,18 +186,14 @@ export const SettingsModal = (props: Props) => {
} }
> >
<h4>Developer</h4> <h4>Developer</h4>
<p> <p>Version: {(import.meta.env.VITE_APP_VERSION as string) || "dev"}</p>
Version: {(import.meta.env.VITE_APP_VERSION as string) || "dev"}
</p>
<FieldRow> <FieldRow>
<InputField <InputField
id="developerSettingsTab" id="developerSettingsTab"
type="checkbox" type="checkbox"
checked={developerSettingsTab} checked={developerSettingsTab}
label={t("Developer Settings")} label={t("Developer Settings")}
description={t( description={t("Expose developer settings in the settings window.")}
"Expose developer settings in the settings window."
)}
onChange={(event: ChangeEvent<HTMLInputElement>) => onChange={(event: ChangeEvent<HTMLInputElement>) =>
setDeveloperSettingsTab(event.target.checked) setDeveloperSettingsTab(event.target.checked)
} }
@@ -210,15 +204,17 @@ export const SettingsModal = (props: Props) => {
<InputField <InputField
id="optInAnalytics" id="optInAnalytics"
type="checkbox" type="checkbox"
checked={optInAnalytics} checked={optInAnalytics ?? undefined}
description={optInDescription} description={optInDescription}
onChange={(event: ChangeEvent<HTMLInputElement>) => onChange={(event: ChangeEvent<HTMLInputElement>) => {
setOptInAnalytics(event.target.checked) setOptInAnalytics?.(event.target.checked);
} }}
/> />
</FieldRow> </FieldRow>
</TabItem> </TabItem>
{developerSettingsTab && ( );
const developerTab = (
<TabItem <TabItem
key="developer" key="developer"
title={ title={
@@ -260,12 +256,31 @@ export const SettingsModal = (props: Props) => {
/> />
</FieldRow> </FieldRow>
<FieldRow> <FieldRow>
<Button onPress={downloadDebugLog}> <Button onPress={downloadDebugLog}>{t("Download debug logs")}</Button>
{t("Download debug logs")}
</Button>
</FieldRow> </FieldRow>
</TabItem> </TabItem>
)} );
const tabs: JSX.Element[] = [];
tabs.push(audioTab, videoTab);
if (!isEmbedded) tabs.push(profileTab);
tabs.push(feedbackTab, moreTab);
if (developerSettingsTab) tabs.push(developerTab);
return (
<Modal
title={t("Settings")}
isDismissable
mobileFullScreen
className={styles.settingsModal}
{...props}
>
<TabContainer
onSelectionChange={onSelectedTabChanged}
selectedKey={selectedTab ?? props.defaultTab ?? "audio"}
className={styles.tabContainer}
>
{tabs}
</TabContainer> </TabContainer>
</Modal> </Modal>
); );
+31 -22
View File
@@ -79,11 +79,17 @@ class ConsoleLogger extends EventEmitter {
warn: "W", warn: "W",
error: "E", error: "E",
}; };
Object.keys(consoleFunctionsToLevels).forEach((fnName) => {
const level = consoleFunctionsToLevels[fnName]; Object.entries(consoleFunctionsToLevels).forEach(([name, level]) => {
const originalFn = consoleObj[fnName].bind(consoleObj); // eslint-disable-next-line @typescript-eslint/ban-ts-comment
this.originalFunctions[fnName] = originalFn; // @ts-ignore
consoleObj[fnName] = (...args) => { const originalFn = consoleObj[name].bind(consoleObj);
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
this.originalFunctions[name] = originalFn;
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
consoleObj[name] = (...args) => {
this.log(level, ...args); this.log(level, ...args);
originalFn(...args); originalFn(...args);
}; };
@@ -147,9 +153,9 @@ class ConsoleLogger extends EventEmitter {
// A class which stores log lines in an IndexedDB instance. // A class which stores log lines in an IndexedDB instance.
class IndexedDBLogStore { class IndexedDBLogStore {
private index = 0; private index = 0;
private db: IDBDatabase = null; private db?: IDBDatabase;
private flushPromise: Promise<void> = null; private flushPromise?: Promise<void>;
private flushAgainPromise: Promise<void> = null; private flushAgainPromise?: Promise<void>;
private id: string; private id: string;
constructor( constructor(
@@ -175,7 +181,7 @@ class IndexedDBLogStore {
}; };
req.onerror = () => { req.onerror = () => {
const err = "Failed to open log database: " + req.error.name; const err = "Failed to open log database: " + req?.error?.name;
logger.error(err); logger.error(err);
reject(new Error(err)); reject(new Error(err));
}; };
@@ -264,7 +270,7 @@ class IndexedDBLogStore {
return this.flush(); return this.flush();
}) })
.then(() => { .then(() => {
this.flushAgainPromise = null; this.flushAgainPromise = undefined;
}); });
return this.flushAgainPromise; return this.flushAgainPromise;
} }
@@ -288,13 +294,13 @@ class IndexedDBLogStore {
}; };
txn.onerror = (event) => { txn.onerror = (event) => {
logger.error("Failed to flush logs : ", event); logger.error("Failed to flush logs : ", event);
reject(new Error("Failed to write logs: " + txn.error.message)); reject(new Error("Failed to write logs: " + txn?.error?.message));
}; };
objStore.add(this.generateLogEntry(lines)); objStore.add(this.generateLogEntry(lines));
const lastModStore = txn.objectStore("logslastmod"); const lastModStore = txn.objectStore("logslastmod");
lastModStore.put(this.generateLastModifiedTime()); lastModStore.put(this.generateLastModifiedTime());
}).then(() => { }).then(() => {
this.flushPromise = null; this.flushPromise = undefined;
}); });
return this.flushPromise; return this.flushPromise;
}; };
@@ -311,11 +317,14 @@ class IndexedDBLogStore {
*/ */
public async consume(): Promise<LogEntry[]> { public async consume(): Promise<LogEntry[]> {
const db = this.db; const db = this.db;
if (!db) {
return Promise.reject(new Error("No connected database"));
}
// Returns: a string representing the concatenated logs for this ID. // Returns: a string representing the concatenated logs for this ID.
// Stops adding log fragments when the size exceeds maxSize // Stops adding log fragments when the size exceeds maxSize
function fetchLogs(id: string, maxSize: number): Promise<string> { function fetchLogs(id: string, maxSize: number): Promise<string> {
const objectStore = db const objectStore = db!
.transaction("logs", "readonly") .transaction("logs", "readonly")
.objectStore("logs"); .objectStore("logs");
@@ -325,7 +334,7 @@ class IndexedDBLogStore {
.openCursor(IDBKeyRange.only(id), "prev"); .openCursor(IDBKeyRange.only(id), "prev");
let lines = ""; let lines = "";
query.onerror = () => { query.onerror = () => {
reject(new Error("Query failed: " + query.error.message)); reject(new Error("Query failed: " + query?.error?.message));
}; };
query.onsuccess = () => { query.onsuccess = () => {
const cursor = query.result; const cursor = query.result;
@@ -346,7 +355,7 @@ class IndexedDBLogStore {
// Returns: A sorted array of log IDs. (newest first) // Returns: A sorted array of log IDs. (newest first)
function fetchLogIds(): Promise<string[]> { function fetchLogIds(): Promise<string[]> {
// To gather all the log IDs, query for all records in logslastmod. // To gather all the log IDs, query for all records in logslastmod.
const o = db const o = db!
.transaction("logslastmod", "readonly") .transaction("logslastmod", "readonly")
.objectStore("logslastmod"); .objectStore("logslastmod");
return selectQuery<{ ts: number; id: string }>(o, undefined, (cursor) => { return selectQuery<{ ts: number; id: string }>(o, undefined, (cursor) => {
@@ -366,7 +375,7 @@ class IndexedDBLogStore {
function deleteLogs(id: number): Promise<void> { function deleteLogs(id: number): Promise<void> {
return new Promise<void>((resolve, reject) => { return new Promise<void>((resolve, reject) => {
const txn = db.transaction(["logs", "logslastmod"], "readwrite"); const txn = db!.transaction(["logs", "logslastmod"], "readwrite");
const o = txn.objectStore("logs"); const o = txn.objectStore("logs");
// only load the key path, not the data which may be huge // only load the key path, not the data which may be huge
const query = o.index("id").openKeyCursor(IDBKeyRange.only(id)); const query = o.index("id").openKeyCursor(IDBKeyRange.only(id));
@@ -384,7 +393,7 @@ class IndexedDBLogStore {
txn.onerror = () => { txn.onerror = () => {
reject( reject(
new Error( new Error(
"Failed to delete logs for " + `'${id}' : ${txn.error.message}` "Failed to delete logs for " + `'${id}' : ${txn?.error?.message}`
) )
); );
}; };
@@ -395,7 +404,7 @@ class IndexedDBLogStore {
} }
const allLogIds = await fetchLogIds(); const allLogIds = await fetchLogIds();
let removeLogIds = []; let removeLogIds: number[] = [];
const logs: LogEntry[] = []; const logs: LogEntry[] = [];
let size = 0; let size = 0;
for (let i = 0; i < allLogIds.length; i++) { for (let i = 0; i < allLogIds.length; i++) {
@@ -414,7 +423,7 @@ class IndexedDBLogStore {
if (size >= MAX_LOG_SIZE) { if (size >= MAX_LOG_SIZE) {
// the remaining log IDs should be removed. If we go out of // the remaining log IDs should be removed. If we go out of
// bounds this is just [] // bounds this is just []
removeLogIds = allLogIds.slice(i + 1); removeLogIds = allLogIds.slice(i + 1).map((id) => parseInt(id, 10));
break; break;
} }
} }
@@ -462,14 +471,14 @@ class IndexedDBLogStore {
*/ */
function selectQuery<T>( function selectQuery<T>(
store: IDBObjectStore, store: IDBObjectStore,
keyRange: IDBKeyRange, keyRange: IDBKeyRange | undefined,
resultMapper: (cursor: IDBCursorWithValue) => T resultMapper: (cursor: IDBCursorWithValue) => T
): Promise<T[]> { ): Promise<T[]> {
const query = store.openCursor(keyRange); const query = store.openCursor(keyRange);
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const results = []; const results: T[] = [];
query.onerror = () => { query.onerror = () => {
reject(new Error("Query failed: " + query.error.message)); reject(new Error("Query failed: " + query?.error?.message));
}; };
// collect results // collect results
query.onsuccess = () => { query.onsuccess = () => {
+44 -27
View File
@@ -15,10 +15,12 @@ limitations under the License.
*/ */
import { useCallback, useContext, useEffect, useState } from "react"; import { useCallback, useContext, useEffect, useState } from "react";
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import pako from "pako"; import pako from "pako";
import { MatrixEvent } from "matrix-js-sdk/src/models/event"; import { MatrixEvent } from "matrix-js-sdk/src/models/event";
import { OverlayTriggerState } from "@react-stately/overlays"; import { OverlayTriggerState } from "@react-stately/overlays";
import { MatrixClient, ClientEvent } from "matrix-js-sdk/src/client"; import { ClientEvent } from "matrix-js-sdk/src/client";
import { getLogsForReport } from "./rageshake"; import { getLogsForReport } from "./rageshake";
import { useClient } from "../ClientContext"; import { useClient } from "../ClientContext";
@@ -46,20 +48,27 @@ export function useSubmitRageshake(): {
submitRageshake: (opts: RageShakeSubmitOptions) => Promise<void>; submitRageshake: (opts: RageShakeSubmitOptions) => Promise<void>;
sending: boolean; sending: boolean;
sent: boolean; sent: boolean;
error: Error; error?: Error;
} { } {
const client: MatrixClient = useClient().client; const { client } = useClient();
// The value of the context is the whole tuple returned from setState, // The value of the context is the whole tuple returned from setState,
// so we just want the current state. // so we just want the current state.
const [inspectorState] = useContext(InspectorContext); const [inspectorState] = useContext(InspectorContext);
const [{ sending, sent, error }, setState] = useState({ const [{ sending, sent, error }, setState] = useState<{
sending: boolean;
sent: boolean;
error?: Error;
}>({
sending: false, sending: false,
sent: false, sent: false,
error: null, error: undefined,
}); });
const submitRageshake = useCallback( const submitRageshake = useCallback(
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
async (opts) => { async (opts) => {
if (!Config.get().rageshake?.submit_url) { if (!Config.get().rageshake?.submit_url) {
throw new Error("No rageshake URL is configured"); throw new Error("No rageshake URL is configured");
@@ -70,7 +79,7 @@ export function useSubmitRageshake(): {
} }
try { try {
setState({ sending: true, sent: false, error: null }); setState({ sending: true, sent: false, error: undefined });
let userAgent = "UNKNOWN"; let userAgent = "UNKNOWN";
if (window.navigator && window.navigator.userAgent) { if (window.navigator && window.navigator.userAgent) {
@@ -104,11 +113,11 @@ export function useSubmitRageshake(): {
body.append("call_backend", "livekit"); body.append("call_backend", "livekit");
if (client) { if (client) {
const userId = client.getUserId(); const userId = client.getUserId()!;
const user = client.getUser(userId); const user = client.getUser(userId);
body.append("display_name", user?.displayName); body.append("display_name", user?.displayName ?? "");
body.append("user_id", client.credentials.userId); body.append("user_id", client.credentials.userId ?? "");
body.append("device_id", client.deviceId); body.append("device_id", client.deviceId ?? "");
if (opts.roomId) { if (opts.roomId) {
body.append("room_id", opts.roomId); body.append("room_id", opts.roomId);
@@ -120,11 +129,11 @@ export function useSubmitRageshake(): {
keys.push(`curve25519:${client.getDeviceCurve25519Key()}`); keys.push(`curve25519:${client.getDeviceCurve25519Key()}`);
} }
body.append("device_keys", keys.join(", ")); body.append("device_keys", keys.join(", "));
body.append("cross_signing_key", client.getCrossSigningId()); body.append("cross_signing_key", client.getCrossSigningId()!);
// add cross-signing status information // add cross-signing status information
const crossSigning = client.crypto.crossSigningInfo; const crossSigning = client.crypto!.crossSigningInfo;
const secretStorage = client.crypto.secretStorage; const secretStorage = client.crypto!.secretStorage;
body.append( body.append(
"cross_signing_ready", "cross_signing_ready",
@@ -138,7 +147,7 @@ export function useSubmitRageshake(): {
) )
) )
); );
body.append("cross_signing_key", crossSigning.getId()); body.append("cross_signing_key", crossSigning.getId()!);
body.append( body.append(
"cross_signing_privkey_in_secret_storage", "cross_signing_privkey_in_secret_storage",
String( String(
@@ -150,14 +159,17 @@ export function useSubmitRageshake(): {
body.append( body.append(
"cross_signing_master_privkey_cached", "cross_signing_master_privkey_cached",
String( String(
!!(pkCache && (await pkCache.getCrossSigningKeyCache("master"))) !!(
pkCache?.getCrossSigningKeyCache &&
(await pkCache.getCrossSigningKeyCache("master"))
)
) )
); );
body.append( body.append(
"cross_signing_self_signing_privkey_cached", "cross_signing_self_signing_privkey_cached",
String( String(
!!( !!(
pkCache && pkCache?.getCrossSigningKeyCache &&
(await pkCache.getCrossSigningKeyCache("self_signing")) (await pkCache.getCrossSigningKeyCache("self_signing"))
) )
) )
@@ -166,7 +178,7 @@ export function useSubmitRageshake(): {
"cross_signing_user_signing_privkey_cached", "cross_signing_user_signing_privkey_cached",
String( String(
!!( !!(
pkCache && pkCache?.getCrossSigningKeyCache &&
(await pkCache.getCrossSigningKeyCache("user_signing")) (await pkCache.getCrossSigningKeyCache("user_signing"))
) )
) )
@@ -186,7 +198,7 @@ export function useSubmitRageshake(): {
String(!!(await client.isKeyBackupKeyStored())) String(!!(await client.isKeyBackupKeyStored()))
); );
const sessionBackupKeyFromCache = const sessionBackupKeyFromCache =
await client.crypto.getSessionBackupPrivateKey(); await client.crypto!.getSessionBackupPrivateKey();
body.append( body.append(
"session_backup_key_cached", "session_backup_key_cached",
String(!!sessionBackupKeyFromCache) String(!!sessionBackupKeyFromCache)
@@ -233,7 +245,7 @@ export function useSubmitRageshake(): {
Object.keys(estimate.usageDetails).forEach((k) => { Object.keys(estimate.usageDetails).forEach((k) => {
body.append( body.append(
`storageManager_usage_${k}`, `storageManager_usage_${k}`,
String(estimate.usageDetails[k]) String(estimate.usageDetails![k])
); );
}); });
} }
@@ -271,14 +283,14 @@ export function useSubmitRageshake(): {
); );
} }
await fetch(Config.get().rageshake?.submit_url, { await fetch(Config.get().rageshake!.submit_url, {
method: "POST", method: "POST",
body, body,
}); });
setState({ sending: false, sent: true, error: null }); setState({ sending: false, sent: true, error: undefined });
} catch (error) { } catch (error) {
setState({ sending: false, sent: false, error }); setState({ sending: false, sent: false, error: error as Error });
console.error(error); console.error(error);
} }
}, },
@@ -307,7 +319,7 @@ export function useDownloadDebugLog(): () => void {
el.click(); el.click();
setTimeout(() => { setTimeout(() => {
URL.revokeObjectURL(url); URL.revokeObjectURL(url);
el.parentNode.removeChild(el); el.parentNode!.removeChild(el);
}, 0); }, 0);
}, [json]); }, [json]);
@@ -321,8 +333,8 @@ export function useRageshakeRequest(): (
const { client } = useClient(); const { client } = useClient();
const sendRageshakeRequest = useCallback( const sendRageshakeRequest = useCallback(
(roomId, rageshakeRequestId) => { (roomId: string, rageshakeRequestId: string) => {
client.sendEvent(roomId, "org.matrix.rageshake_request", { client!.sendEvent(roomId, "org.matrix.rageshake_request", {
request_id: rageshakeRequestId, request_id: rageshakeRequestId,
}); });
}, },
@@ -347,10 +359,12 @@ export function useRageshakeRequestModal(roomId: string): {
modalState: OverlayTriggerState; modalState: OverlayTriggerState;
modalProps: ModalProps; modalProps: ModalProps;
}; };
const client: MatrixClient = useClient().client; const { client } = useClient();
const [rageshakeRequestId, setRageshakeRequestId] = useState<string>(); const [rageshakeRequestId, setRageshakeRequestId] = useState<string>();
useEffect(() => { useEffect(() => {
if (!client) return;
const onEvent = (event: MatrixEvent) => { const onEvent = (event: MatrixEvent) => {
const type = event.getType(); const type = event.getType();
@@ -371,5 +385,8 @@ export function useRageshakeRequestModal(roomId: string): {
}; };
}, [modalState.open, roomId, client, modalState]); }, [modalState.open, roomId, client, modalState]);
return { modalState, modalProps: { ...modalProps, rageshakeRequestId } }; return {
modalState,
modalProps: { ...modalProps, rageshakeRequestId: rageshakeRequestId ?? "" },
};
} }
+3 -3
View File
@@ -32,7 +32,7 @@ export function TabContainer<T extends object>(
props: TabContainerProps<T> props: TabContainerProps<T>
): JSX.Element { ): JSX.Element {
const state = useTabListState<T>(props); const state = useTabListState<T>(props);
const ref = useRef<HTMLUListElement>(); const ref = useRef<HTMLUListElement>(null);
const { tabListProps } = useTabList(props, state, ref); const { tabListProps } = useTabList(props, state, ref);
return ( return (
<div className={classNames(styles.tabContainer, props.className)}> <div className={classNames(styles.tabContainer, props.className)}>
@@ -53,7 +53,7 @@ interface TabProps<T> {
function Tab<T>({ item, state }: TabProps<T>): JSX.Element { function Tab<T>({ item, state }: TabProps<T>): JSX.Element {
const { key, rendered } = item; const { key, rendered } = item;
const ref = useRef<HTMLLIElement>(); const ref = useRef<HTMLLIElement>(null);
const { tabProps } = useTab({ key }, state, ref); const { tabProps } = useTab({ key }, state, ref);
return ( return (
@@ -75,7 +75,7 @@ interface TabPanelProps<T> extends AriaTabPanelProps {
} }
function TabPanel<T>({ state, ...props }: TabPanelProps<T>): JSX.Element { function TabPanel<T>({ state, ...props }: TabPanelProps<T>): JSX.Element {
const ref = useRef<HTMLDivElement>(); const ref = useRef<HTMLDivElement>(null);
const { tabPanelProps } = useTabPanel(props, state, ref); const { tabPanelProps } = useTabPanel(props, state, ref);
return ( return (
<div {...tabPanelProps} ref={ref} className={styles.tabPanel}> <div {...tabPanelProps} ref={ref} className={styles.tabPanel}>
+13 -7
View File
@@ -46,7 +46,7 @@ export const Headline = forwardRef<HTMLHeadingElement, TypographyProps>(
{ {
...rest, ...rest,
className: classNames( className: classNames(
styles[fontWeight], styles[fontWeight ?? ""],
{ [styles.overflowEllipsis]: overflowEllipsis }, { [styles.overflowEllipsis]: overflowEllipsis },
className className
), ),
@@ -74,7 +74,7 @@ export const Title = forwardRef<HTMLHeadingElement, TypographyProps>(
{ {
...rest, ...rest,
className: classNames( className: classNames(
styles[fontWeight], styles[fontWeight ?? ""],
{ [styles.overflowEllipsis]: overflowEllipsis }, { [styles.overflowEllipsis]: overflowEllipsis },
className className
), ),
@@ -102,7 +102,7 @@ export const Subtitle = forwardRef<HTMLParagraphElement, TypographyProps>(
{ {
...rest, ...rest,
className: classNames( className: classNames(
styles[fontWeight], styles[fontWeight ?? ""],
{ [styles.overflowEllipsis]: overflowEllipsis }, { [styles.overflowEllipsis]: overflowEllipsis },
className className
), ),
@@ -130,7 +130,7 @@ export const Body = forwardRef<HTMLParagraphElement, TypographyProps>(
{ {
...rest, ...rest,
className: classNames( className: classNames(
styles[fontWeight], styles[fontWeight ?? ""],
{ [styles.overflowEllipsis]: overflowEllipsis }, { [styles.overflowEllipsis]: overflowEllipsis },
className className
), ),
@@ -159,7 +159,7 @@ export const Caption = forwardRef<HTMLParagraphElement, TypographyProps>(
...rest, ...rest,
className: classNames( className: classNames(
styles.caption, styles.caption,
styles[fontWeight], styles[fontWeight ?? ""],
{ [styles.overflowEllipsis]: overflowEllipsis }, { [styles.overflowEllipsis]: overflowEllipsis },
className className
), ),
@@ -188,7 +188,7 @@ export const Micro = forwardRef<HTMLParagraphElement, TypographyProps>(
...rest, ...rest,
className: classNames( className: classNames(
styles.micro, styles.micro,
styles[fontWeight], styles[fontWeight ?? ""],
{ [styles.overflowEllipsis]: overflowEllipsis }, { [styles.overflowEllipsis]: overflowEllipsis },
className className
), ),
@@ -219,6 +219,8 @@ export const Link = forwardRef<HTMLAnchorElement, LinkProps>(
}, },
ref ref
) => { ) => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const Component: string | RouterLink = as || (to ? RouterLink : "a"); const Component: string | RouterLink = as || (to ? RouterLink : "a");
let externalLinkProps: { href: string; target: string; rel: string }; let externalLinkProps: { href: string; target: string; rel: string };
@@ -233,12 +235,16 @@ export const Link = forwardRef<HTMLAnchorElement, LinkProps>(
return createElement( return createElement(
Component, Component,
{ {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
...externalLinkProps, ...externalLinkProps,
...rest, ...rest,
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
to: to, to: to,
className: classNames( className: classNames(
styles[color], styles[color],
styles[fontWeight], styles[fontWeight ?? ""],
{ [styles.overflowEllipsis]: overflowEllipsis }, { [styles.overflowEllipsis]: overflowEllipsis },
className className
), ),
+7 -2
View File
@@ -31,8 +31,13 @@ export const useEventTarget = <T extends Event>(
) => { ) => {
useEffect(() => { useEffect(() => {
if (target) { if (target) {
target.addEventListener(eventType, listener, options); target.addEventListener(eventType, listener as EventListener, options);
return () => target.removeEventListener(eventType, listener, options); return () =>
target.removeEventListener(
eventType,
listener as EventListener,
options
);
} }
}, [target, eventType, listener, options]); }, [target, eventType, listener, options]);
}; };
+5 -1
View File
@@ -21,7 +21,9 @@ export function useLocationNavigation(enabled = false): void {
const history = useHistory(); const history = useHistory();
useEffect(() => { useEffect(() => {
let unblock; // eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
let unblock = undefined;
if (enabled) { if (enabled) {
unblock = history.block((tx) => { unblock = history.block((tx) => {
@@ -33,6 +35,8 @@ export function useLocationNavigation(enabled = false): void {
} }
return () => { return () => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
if (unblock) { if (unblock) {
unblock(); unblock();
} }
+4 -3
View File
@@ -55,7 +55,7 @@ export interface Grid {
cells: Cell[]; cells: Cell[];
} }
interface SparseGrid { export interface SparseGrid {
columns: number; columns: number;
/** /**
* The cells of the grid, in left-to-right top-to-bottom order. * The cells of the grid, in left-to-right top-to-bottom order.
@@ -803,7 +803,7 @@ export function setTileSize<G extends Grid | SparseGrid>(
const result: SparseGrid = gridWithoutTile; const result: SparseGrid = gridWithoutTile;
placeTile(to, toEnd, result); placeTile(to, toEnd, result);
return fillGaps(result, true, (i) => inArea(i, to, toEnd, g)) as G; return fillGaps(result, true, (i: number) => inArea(i, to, toEnd, g)) as G;
} else if (toWidth >= fromWidth && toHeight >= fromHeight) { } else if (toWidth >= fromWidth && toHeight >= fromHeight) {
// The tile is growing, which might be able to happen in-place // The tile is growing, which might be able to happen in-place
const to = findNearestCell( const to = findNearestCell(
@@ -1054,7 +1054,8 @@ export const BigGrid: Layout<Grid> = {
emptyState: { columns: 4, cells: [] }, emptyState: { columns: 4, cells: [] },
updateTiles, updateTiles,
updateBounds, updateBounds,
getTiles: <T,>(g) => g.cells.filter((c) => c.origin).map((c) => c!.item as T), getTiles: <T,>(g: Grid) =>
g.cells.filter((c) => c.origin).map((c) => c!.item as T),
canDragTile: () => true, canDragTile: () => true,
dragTile, dragTile,
toggleFocus: cycleTileSize, toggleFocus: cycleTileSize,
+11
View File
@@ -271,10 +271,19 @@ export function NewVideoGrid<T>({
// gesture using the much more sensible ref-based method. // gesture using the much more sensible ref-based method.
const onTileDrag = ( const onTileDrag = (
tileId: string, tileId: string,
{ {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
tap, tap,
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
initial: [initialX, initialY], initial: [initialX, initialY],
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
delta: [dx, dy], delta: [dx, dy],
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
last, last,
}: Parameters<Handler<"drag", EventTypes["drag"]>>[0] }: Parameters<Handler<"drag", EventTypes["drag"]>>[0]
) => { ) => {
@@ -325,6 +334,8 @@ export function NewVideoGrid<T>({
const scrollOffset = useRef(0); const scrollOffset = useRef(0);
useScroll( useScroll(
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
({ xy: [, y], delta: [, dy] }) => { ({ xy: [, y], delta: [, dy] }) => {
scrollOffset.current = y; scrollOffset.current = y;
+18 -2
View File
@@ -695,7 +695,7 @@ function getSubGridPositions(
// Calculates the number of possible tiles that can be displayed // Calculates the number of possible tiles that can be displayed
function displayedTileCount( function displayedTileCount(
layout: Layout, layout: Layout,
tileCount, tileCount: number,
gridWidth: number, gridWidth: number,
gridHeight: number gridHeight: number
): number { ): number {
@@ -854,7 +854,7 @@ export function VideoGrid<T>({
tilePositions: [], tilePositions: [],
}); });
const [scrollPosition, setScrollPosition] = useState<number>(0); const [scrollPosition, setScrollPosition] = useState<number>(0);
const draggingTileRef = useRef<DragTileData>(null); const draggingTileRef = useRef<DragTileData | null>(null);
const lastTappedRef = useRef<{ [index: Key]: number }>({}); const lastTappedRef = useRef<{ [index: Key]: number }>({});
const lastLayoutRef = useRef<Layout>(layout); const lastLayoutRef = useRef<Layout>(layout);
const isMounted = useIsMounted(); const isMounted = useIsMounted();
@@ -1189,11 +1189,23 @@ export function VideoGrid<T>({
const onTileDrag = ( const onTileDrag = (
tileId: string, tileId: string,
{ {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
active, active,
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
xy, xy,
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
movement, movement,
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
tap, tap,
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
last, last,
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
event, event,
}: Parameters<Handler<"drag", EventTypes["drag"]>>[0] }: Parameters<Handler<"drag", EventTypes["drag"]>>[0]
) => { ) => {
@@ -1345,7 +1357,11 @@ export function VideoGrid<T>({
const bindGrid = useGesture( const bindGrid = useGesture(
{ {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
onWheel: (e) => onGridGesture(e, true), onWheel: (e) => onGridGesture(e, true),
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
onDrag: (e) => onGridGesture(e, false), onDrag: (e) => onGridGesture(e, false),
}, },
{} {}
+1 -1
View File
@@ -136,7 +136,7 @@ export const VideoTile = forwardRef<HTMLDivElement, Props>(
<AudioButton <AudioButton
key="localVolume" key="localVolume"
className={styles.button} className={styles.button}
volume={(sfuParticipant as RemoteParticipant).getVolume()} volume={(sfuParticipant as RemoteParticipant).getVolume() ?? 0}
onPress={onOptionsPress} onPress={onOptionsPress}
/> />
); );
+1 -1
View File
@@ -32,7 +32,7 @@ const LocalVolume: React.FC<LocalVolumeProps> = ({
participant, participant,
}: LocalVolumeProps) => { }: LocalVolumeProps) => {
const [localVolume, setLocalVolume] = useState<number>( const [localVolume, setLocalVolume] = useState<number>(
participant.getVolume() participant.getVolume() ?? 0
); );
const onLocalVolumeChanged = (event: ChangeEvent<HTMLInputElement>) => { const onLocalVolumeChanged = (event: ChangeEvent<HTMLInputElement>) => {
+3 -5
View File
@@ -109,7 +109,7 @@ export const widget: WidgetHelpers | null = (() => {
baseUrl, baseUrl,
e2eEnabled, e2eEnabled,
allowIceFallback, allowIceFallback,
} = getUrlParams(); } = getUrlParams(true);
if (!roomId) throw new Error("Room ID must be supplied"); if (!roomId) throw new Error("Room ID must be supplied");
if (!userId) throw new Error("User ID must be supplied"); if (!userId) throw new Error("User ID must be supplied");
if (!deviceId) throw new Error("Device ID must be supplied"); if (!deviceId) throw new Error("Device ID must be supplied");
@@ -164,7 +164,7 @@ export const widget: WidgetHelpers | null = (() => {
// message so that we can use the widget API in less racy mode, but we need to change // message so that we can use the widget API in less racy mode, but we need to change
// element-web to use waitForIFrameLoad=false. Once that change has rolled out, // element-web to use waitForIFrameLoad=false. Once that change has rolled out,
// we can just start the client after we've fetched the config. // we can just start the client after we've fetched the config.
foci: [], livekitServiceURL: undefined,
} }
); );
@@ -178,9 +178,7 @@ export const widget: WidgetHelpers | null = (() => {
// Now we've fetched the config, be evil and use the getter to inject the focus // Now we've fetched the config, be evil and use the getter to inject the focus
// into the client (see above XXX). // into the client (see above XXX).
if (focus) { if (focus) {
client.getFoci().push({ client.setLivekitServiceURL(livekit.livekit_service_url);
livekitServiceUrl: livekit.livekit_service_url,
});
} }
await client.startClient(); await client.startClient();
resolve(client); resolve(client);
+98
View File
@@ -0,0 +1,98 @@
/*
Copyright 2023 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import { mocked } from "jest-mock";
import { getUrlParams } from "../src/UrlParams";
import { Config } from "../src/config/Config";
const ROOM_NAME = "roomNameHere";
const ROOM_ID = "d45f138fsd";
const ORIGIN = "https://call.element.io";
const HOMESERVER = "call.ems.host";
jest.mock("../src/config/Config");
describe("UrlParams", () => {
beforeAll(() => {
mocked(Config.defaultServerName).mockReturnValue("call.ems.host");
});
describe("handles URL with /room/", () => {
it("and nothing else", () => {
expect(getUrlParams(false, "", `/room/${ROOM_NAME}`, "").roomAlias).toBe(
`#${ROOM_NAME}:${HOMESERVER}`
);
});
it("and #", () => {
expect(
getUrlParams(false, "", `${ORIGIN}/room/`, `#${ROOM_NAME}`).roomAlias
).toBe(`#${ROOM_NAME}:${HOMESERVER}`);
});
it("and # and server part", () => {
expect(
getUrlParams(false, "", `/room/`, `#${ROOM_NAME}:${HOMESERVER}`)
.roomAlias
).toBe(`#${ROOM_NAME}:${HOMESERVER}`);
});
it("and server part", () => {
expect(
getUrlParams(false, "", `/room/${ROOM_NAME}:${HOMESERVER}`, "")
.roomAlias
).toBe(`#${ROOM_NAME}:${HOMESERVER}`);
});
});
describe("handles URL without /room/", () => {
it("and nothing else", () => {
expect(getUrlParams(false, "", `/${ROOM_NAME}`, "").roomAlias).toBe(
`#${ROOM_NAME}:${HOMESERVER}`
);
});
it("and with #", () => {
expect(getUrlParams(false, "", "", `#${ROOM_NAME}`).roomAlias).toBe(
`#${ROOM_NAME}:${HOMESERVER}`
);
});
it("and with # and server part", () => {
expect(
getUrlParams(false, "", "", `#${ROOM_NAME}:${HOMESERVER}`).roomAlias
).toBe(`#${ROOM_NAME}:${HOMESERVER}`);
});
it("and with server part", () => {
expect(
getUrlParams(false, "", `/${ROOM_NAME}:${HOMESERVER}`, "").roomAlias
).toBe(`#${ROOM_NAME}:${HOMESERVER}`);
});
});
describe("handles search params", () => {
it("(roomId)", () => {
expect(getUrlParams(true, `?roomId=${ROOM_ID}`).roomId).toBe(ROOM_ID);
});
});
it("ignores room alias", () => {
expect(
getUrlParams(true, "", `/room/${ROOM_NAME}:${HOMESERVER}`).roomAlias
).toBeFalsy();
});
});
+1 -1
View File
@@ -34,7 +34,7 @@ describe("CallList", () => {
it("should show room", async () => { it("should show room", async () => {
const rooms = [ const rooms = [
{ roomName: "Room #1", roomId: "!roomId" }, { roomName: "Room #1", roomAlias: "#room-name:server.org" },
] as GroupCallRoom[]; ] as GroupCallRoom[];
const result = renderComponent(rooms); const result = renderComponent(rooms);
+3 -3
View File
@@ -102,7 +102,7 @@ describe("ObjectFlattener", () => {
localCandidateType: "srfx", localCandidateType: "srfx",
remoteCandidateType: "srfx", remoteCandidateType: "srfx",
networkType: "ethernet", networkType: "ethernet",
rtt: null, rtt: 0,
}, },
], ],
audioConcealment: new Map([ audioConcealment: new Map([
@@ -167,7 +167,7 @@ describe("ObjectFlattener", () => {
"matrix.call.stats.connection.transport.1.localCandidateType": "srfx", "matrix.call.stats.connection.transport.1.localCandidateType": "srfx",
"matrix.call.stats.connection.transport.1.remoteCandidateType": "srfx", "matrix.call.stats.connection.transport.1.remoteCandidateType": "srfx",
"matrix.call.stats.connection.transport.1.networkType": "ethernet", "matrix.call.stats.connection.transport.1.networkType": "ethernet",
"matrix.call.stats.connection.transport.1.rtt": "null", "matrix.call.stats.connection.transport.1.rtt": 0,
}); });
}); });
}); });
@@ -234,7 +234,7 @@ describe("ObjectFlattener", () => {
"matrix.call.stats.connection.transport.1.localCandidateType": "srfx", "matrix.call.stats.connection.transport.1.localCandidateType": "srfx",
"matrix.call.stats.connection.transport.1.remoteCandidateType": "srfx", "matrix.call.stats.connection.transport.1.remoteCandidateType": "srfx",
"matrix.call.stats.connection.transport.1.networkType": "ethernet", "matrix.call.stats.connection.transport.1.networkType": "ethernet",
"matrix.call.stats.connection.transport.1.rtt": "null", "matrix.call.stats.connection.transport.1.rtt": 0,
"matrix.call.stats.connection.audioConcealment.REMOTE_AUDIO_TRACK_ID.concealedAudio": 0, "matrix.call.stats.connection.audioConcealment.REMOTE_AUDIO_TRACK_ID.concealedAudio": 0,
"matrix.call.stats.connection.audioConcealment.REMOTE_AUDIO_TRACK_ID.totalAudioDuration": 0, "matrix.call.stats.connection.audioConcealment.REMOTE_AUDIO_TRACK_ID.totalAudioDuration": 0,
"matrix.call.stats.connection.audioConcealment.REMOTE_VIDEO_TRACK_ID.concealedAudio": 0, "matrix.call.stats.connection.audioConcealment.REMOTE_VIDEO_TRACK_ID.concealedAudio": 0,
+4 -1
View File
@@ -21,6 +21,7 @@ import {
fillGaps, fillGaps,
forEachCellInArea, forEachCellInArea,
Grid, Grid,
SparseGrid,
resize, resize,
row, row,
moveTile, moveTile,
@@ -339,7 +340,9 @@ function testAddItems(
output: string output: string
): void { ): void {
test(`addItems ${title}`, () => { test(`addItems ${title}`, () => {
expect(showGrid(addItems(items, mkGrid(input)))).toBe(output); expect(showGrid(addItems(items, mkGrid(input) as SparseGrid) as Grid)).toBe(
output
);
}); });
} }
+20 -12
View File
@@ -1,23 +1,31 @@
{ {
"compilerOptions": { "compilerOptions": {
"target": "es2016", "target": "es2016",
"esModuleInterop": true,
"module": "es2020", "module": "es2020",
"moduleResolution": "node",
"noEmit": true,
"noImplicitAny": false,
"noUnusedLocals": true,
"jsx": "react-jsx", "jsx": "react-jsx",
"lib": ["es2020", "dom", "dom.iterable"], "lib": ["es2020", "dom", "dom.iterable"],
"strict": false,
"plugins": [ // From Matrix-JS-SDK
{ "strict": true,
"name": "typescript-strict-plugin", "noEmit": true,
"paths": ["src"] "noEmitOnError": true,
} "experimentalDecorators": true,
] "esModuleInterop": true,
"noUnusedLocals": true,
"moduleResolution": "node",
"declaration": true
// TODO: Enable the following options later.
// "forceConsistentCasingInFileNames": true,
// "noFallthroughCasesInSwitch": true,
// "noImplicitOverride": true,
// "noImplicitReturns": true,
// "noPropertyAccessFromIndexSignature": true,
// "noUncheckedIndexedAccess": true,
// "noUnusedParameters": true,
}, },
"include": [ "include": [
"./node_modules/matrix-js-sdk/src/@types/*.d.ts",
"./src/**/*.ts", "./src/**/*.ts",
"./src/**/*.tsx", "./src/**/*.tsx",
"./test/**/*.ts", "./test/**/*.ts",
+2
View File
@@ -19,6 +19,7 @@ import svgrPlugin from "vite-plugin-svgr";
import htmlTemplate from "vite-plugin-html-template"; import htmlTemplate from "vite-plugin-html-template";
import sentryVitePlugin from "@sentry/vite-plugin"; import sentryVitePlugin from "@sentry/vite-plugin";
import react from "@vitejs/plugin-react"; import react from "@vitejs/plugin-react";
import basicSsl from "@vitejs/plugin-basic-ssl";
// https://vitejs.dev/config/ // https://vitejs.dev/config/
export default defineConfig(({ mode }) => { export default defineConfig(({ mode }) => {
@@ -26,6 +27,7 @@ export default defineConfig(({ mode }) => {
const plugins = [ const plugins = [
react(), react(),
basicSsl(),
svgrPlugin(), svgrPlugin(),
htmlTemplate.default({ htmlTemplate.default({
data: { data: {
+110 -22
View File
@@ -2014,6 +2014,13 @@
dependencies: dependencies:
"@sinclair/typebox" "^0.24.1" "@sinclair/typebox" "^0.24.1"
"@jest/schemas@^29.4.3":
version "29.4.3"
resolved "https://registry.yarnpkg.com/@jest/schemas/-/schemas-29.4.3.tgz#39cf1b8469afc40b6f5a2baaa146e332c4151788"
integrity sha512-VLYKXQmtmuEz6IxJsrZwzG9NvtkQsWNnWMsKxqWNu3+CnfzJQhp0WDDKWLVV9hLKr0l3SLLFRqcYHjhtyuDVxg==
dependencies:
"@sinclair/typebox" "^0.25.16"
"@jest/source-map@^29.2.0": "@jest/source-map@^29.2.0":
version "29.2.0" version "29.2.0"
resolved "https://registry.yarnpkg.com/@jest/source-map/-/source-map-29.2.0.tgz#ab3420c46d42508dcc3dc1c6deee0b613c235744" resolved "https://registry.yarnpkg.com/@jest/source-map/-/source-map-29.2.0.tgz#ab3420c46d42508dcc3dc1c6deee0b613c235744"
@@ -2088,6 +2095,18 @@
"@types/yargs" "^17.0.8" "@types/yargs" "^17.0.8"
chalk "^4.0.0" chalk "^4.0.0"
"@jest/types@^29.5.0":
version "29.5.0"
resolved "https://registry.yarnpkg.com/@jest/types/-/types-29.5.0.tgz#f59ef9b031ced83047c67032700d8c807d6e1593"
integrity sha512-qbu7kN6czmVRc3xWFQcAN03RAUamgppVUdXrvl1Wr3jlNF93o9mJbGcDWrwGB6ht44u7efB1qCFgVQmca24Uog==
dependencies:
"@jest/schemas" "^29.4.3"
"@types/istanbul-lib-coverage" "^2.0.0"
"@types/istanbul-reports" "^3.0.0"
"@types/node" "*"
"@types/yargs" "^17.0.8"
chalk "^4.0.0"
"@joshwooding/vite-plugin-react-docgen-typescript@0.0.2": "@joshwooding/vite-plugin-react-docgen-typescript@0.0.2":
version "0.0.2" version "0.0.2"
resolved "https://registry.yarnpkg.com/@joshwooding/vite-plugin-react-docgen-typescript/-/vite-plugin-react-docgen-typescript-0.0.2.tgz#e0ae8c94f468da3a273a7b0acf23ba3565f86cbc" resolved "https://registry.yarnpkg.com/@joshwooding/vite-plugin-react-docgen-typescript/-/vite-plugin-react-docgen-typescript-0.0.2.tgz#e0ae8c94f468da3a273a7b0acf23ba3565f86cbc"
@@ -2186,10 +2205,10 @@
"@react-hook/latest" "^1.0.3" "@react-hook/latest" "^1.0.3"
clsx "^1.2.1" clsx "^1.2.1"
"@matrix-org/matrix-sdk-crypto-js@^0.1.0-alpha.10": "@matrix-org/matrix-sdk-crypto-js@^0.1.1":
version "0.1.0-alpha.10" version "0.1.3"
resolved "https://registry.yarnpkg.com/@matrix-org/matrix-sdk-crypto-js/-/matrix-sdk-crypto-js-0.1.0-alpha.10.tgz#b6a6395cffd3197ae2e0a88f4eeae8b315571fd2" resolved "https://registry.yarnpkg.com/@matrix-org/matrix-sdk-crypto-js/-/matrix-sdk-crypto-js-0.1.3.tgz#19981e7613d3673d07c885a98d39276b5fe74ef0"
integrity sha512-8V2NKuzGOFzEZeZVgF2is7gmuopdRbMZ064tzPDE0vN34iX6s3O8A4oxIT7SA3qtymwm3t1yEvTnT+0gfbmh4g== integrity sha512-RcRlE3wcMnE5ijACHIHmhXFogEEJdIcb/CbJ4rK1PCMduQ4yvxycVpMxwh7aKxFNitZbHZLCK7TfRzUpzjU2tw==
"@matrix-org/olm@https://gitlab.matrix.org/api/v4/projects/27/packages/npm/@matrix-org/olm/-/@matrix-org/olm-3.2.14.tgz": "@matrix-org/olm@https://gitlab.matrix.org/api/v4/projects/27/packages/npm/@matrix-org/olm/-/@matrix-org/olm-3.2.14.tgz":
version "3.2.14" version "3.2.14"
@@ -3098,6 +3117,11 @@
resolved "https://registry.yarnpkg.com/@sinclair/typebox/-/typebox-0.24.51.tgz#645f33fe4e02defe26f2f5c0410e1c094eac7f5f" resolved "https://registry.yarnpkg.com/@sinclair/typebox/-/typebox-0.24.51.tgz#645f33fe4e02defe26f2f5c0410e1c094eac7f5f"
integrity sha512-1P1OROm/rdubP5aFDSZQILU0vrLCJ4fvHt6EoqHEM+2D/G5MK3bIaymUKLit8Js9gbns5UyJnkP/TZROLw4tUA== integrity sha512-1P1OROm/rdubP5aFDSZQILU0vrLCJ4fvHt6EoqHEM+2D/G5MK3bIaymUKLit8Js9gbns5UyJnkP/TZROLw4tUA==
"@sinclair/typebox@^0.25.16":
version "0.25.24"
resolved "https://registry.yarnpkg.com/@sinclair/typebox/-/typebox-0.25.24.tgz#8c7688559979f7079aacaf31aa881c3aa410b718"
integrity sha512-XJfwUVUKDHF5ugKwIcxEgc9k8b7HbznCp6eUfWgu710hMPNIO4aw4/zB5RogDQz8nd6gyCDpU9O/m6qYEWY6yQ==
"@sinonjs/commons@^1.7.0": "@sinonjs/commons@^1.7.0":
version "1.8.3" version "1.8.3"
resolved "https://registry.yarnpkg.com/@sinonjs/commons/-/commons-1.8.3.tgz#3802ddd21a50a949b6721ddd72da36e67e7f1b2d" resolved "https://registry.yarnpkg.com/@sinonjs/commons/-/commons-1.8.3.tgz#3802ddd21a50a949b6721ddd72da36e67e7f1b2d"
@@ -3893,6 +3917,11 @@
resolved "https://registry.yarnpkg.com/@types/caseless/-/caseless-0.12.2.tgz#f65d3d6389e01eeb458bd54dc8f52b95a9463bc8" resolved "https://registry.yarnpkg.com/@types/caseless/-/caseless-0.12.2.tgz#f65d3d6389e01eeb458bd54dc8f52b95a9463bc8"
integrity sha512-6ckxMjBBD8URvjB6J3NcnuAn5Pkl7t3TizAg+xdlzzQGSPSmBcXf8KoIH0ua/i+tio+ZRUHEXp0HEmvaR4kt0w== integrity sha512-6ckxMjBBD8URvjB6J3NcnuAn5Pkl7t3TizAg+xdlzzQGSPSmBcXf8KoIH0ua/i+tio+ZRUHEXp0HEmvaR4kt0w==
"@types/content-type@^1.1.5":
version "1.1.5"
resolved "https://registry.yarnpkg.com/@types/content-type/-/content-type-1.1.5.tgz#aa02dca40864749a9e2bf0161a6216da57e3ede5"
integrity sha512-dgMN+syt1xb7Hk8LU6AODOfPlvz5z1CbXpPuJE5ZrX9STfBOIXF09pEB8N7a97WT9dbngt3ksDCm6GW6yMrxfQ==
"@types/eslint-scope@^3.7.3": "@types/eslint-scope@^3.7.3":
version "3.7.4" version "3.7.4"
resolved "https://registry.yarnpkg.com/@types/eslint-scope/-/eslint-scope-3.7.4.tgz#37fc1223f0786c39627068a12e94d6e6fc61de16" resolved "https://registry.yarnpkg.com/@types/eslint-scope/-/eslint-scope-3.7.4.tgz#37fc1223f0786c39627068a12e94d6e6fc61de16"
@@ -3956,6 +3985,11 @@
dependencies: dependencies:
"@types/unist" "*" "@types/unist" "*"
"@types/history@^4.7.11":
version "4.7.11"
resolved "https://registry.yarnpkg.com/@types/history/-/history-4.7.11.tgz#56588b17ae8f50c53983a524fc3cc47437969d64"
integrity sha512-qjDJRrmvBMiTx+jyLxvLfJU7UznFuokDv4f3WRuriHKERccVpFU+8XMQUAbDzoiJCsmexxRExQeMwwCdamSKDA==
"@types/html-minifier-terser@^5.0.0": "@types/html-minifier-terser@^5.0.0":
version "5.1.2" version "5.1.2"
resolved "https://registry.yarnpkg.com/@types/html-minifier-terser/-/html-minifier-terser-5.1.2.tgz#693b316ad323ea97eed6b38ed1a3cc02b1672b57" resolved "https://registry.yarnpkg.com/@types/html-minifier-terser/-/html-minifier-terser-5.1.2.tgz#693b316ad323ea97eed6b38ed1a3cc02b1672b57"
@@ -4104,6 +4138,23 @@
dependencies: dependencies:
"@types/react" "*" "@types/react" "*"
"@types/react-router-dom@^5.3.3":
version "5.3.3"
resolved "https://registry.yarnpkg.com/@types/react-router-dom/-/react-router-dom-5.3.3.tgz#e9d6b4a66fcdbd651a5f106c2656a30088cc1e83"
integrity sha512-kpqnYK4wcdm5UaWI3fLcELopqLrHgLqNsdpHauzlQktfkHL3npOSwtj1Uz9oKBAzs7lFtVkV8j83voAz2D8fhw==
dependencies:
"@types/history" "^4.7.11"
"@types/react" "*"
"@types/react-router" "*"
"@types/react-router@*":
version "5.1.20"
resolved "https://registry.yarnpkg.com/@types/react-router/-/react-router-5.1.20.tgz#88eccaa122a82405ef3efbcaaa5dcdd9f021387c"
integrity sha512-jGjmu/ZqS7FjSH6owMcD5qpq19+1RS9DeVRqfl1FeBMxTDQAGwlMWOcs52NDoXaNKyG3d1cYQFMs9rCrb88o9Q==
dependencies:
"@types/history" "^4.7.11"
"@types/react" "*"
"@types/react-syntax-highlighter@11.0.5": "@types/react-syntax-highlighter@11.0.5":
version "11.0.5" version "11.0.5"
resolved "https://registry.yarnpkg.com/@types/react-syntax-highlighter/-/react-syntax-highlighter-11.0.5.tgz#0d546261b4021e1f9d85b50401c0a42acb106087" resolved "https://registry.yarnpkg.com/@types/react-syntax-highlighter/-/react-syntax-highlighter-11.0.5.tgz#0d546261b4021e1f9d85b50401c0a42acb106087"
@@ -4194,6 +4245,11 @@
resolved "https://registry.yarnpkg.com/@types/unist/-/unist-2.0.6.tgz#250a7b16c3b91f672a24552ec64678eeb1d3a08d" resolved "https://registry.yarnpkg.com/@types/unist/-/unist-2.0.6.tgz#250a7b16c3b91f672a24552ec64678eeb1d3a08d"
integrity sha512-PBjIUxZHOuj0R15/xuwJYjFi+KZdNFrehocChv4g5hu6aFroHue8m0lBP0POdK2nKzbw0cgV1mws8+V/JAcEkQ== integrity sha512-PBjIUxZHOuj0R15/xuwJYjFi+KZdNFrehocChv4g5hu6aFroHue8m0lBP0POdK2nKzbw0cgV1mws8+V/JAcEkQ==
"@types/uuid@9":
version "9.0.2"
resolved "https://registry.yarnpkg.com/@types/uuid/-/uuid-9.0.2.tgz#ede1d1b1e451548d44919dc226253e32a6952c4b"
integrity sha512-kNnC1GFBLuhImSnV7w4njQkUiJi0ZXUycu1rUaouPqiKlXkh77JKgdRnTAp1x5eBwcIwbtI+3otwzuIDEuDoxQ==
"@types/webpack-env@^1.16.0": "@types/webpack-env@^1.16.0":
version "1.17.0" version "1.17.0"
resolved "https://registry.yarnpkg.com/@types/webpack-env/-/webpack-env-1.17.0.tgz#f99ce359f1bfd87da90cc4a57cab0a18f34a48d0" resolved "https://registry.yarnpkg.com/@types/webpack-env/-/webpack-env-1.17.0.tgz#f99ce359f1bfd87da90cc4a57cab0a18f34a48d0"
@@ -4328,6 +4384,11 @@
dependencies: dependencies:
"@use-gesture/core" "10.2.16" "@use-gesture/core" "10.2.16"
"@vitejs/plugin-basic-ssl@^1.0.1":
version "1.0.1"
resolved "https://registry.yarnpkg.com/@vitejs/plugin-basic-ssl/-/plugin-basic-ssl-1.0.1.tgz#48c46eab21e0730921986ce742563ae83fe7fe34"
integrity sha512-pcub+YbFtFhaGRTo1832FQHQSHvMrlb43974e2eS8EKleR3p1cDdkJFPci1UhwkEf1J9Bz+wKBSzqpKp7nNj2A==
"@vitejs/plugin-react@^1.0.8": "@vitejs/plugin-react@^1.0.8":
version "1.3.2" version "1.3.2"
resolved "https://registry.yarnpkg.com/@vitejs/plugin-react/-/plugin-react-1.3.2.tgz#2fcf0b6ce9bcdcd4cec5c760c199779d5657ece1" resolved "https://registry.yarnpkg.com/@vitejs/plugin-react/-/plugin-react-1.3.2.tgz#2fcf0b6ce9bcdcd4cec5c760c199779d5657ece1"
@@ -6399,6 +6460,11 @@ crypto-browserify@^3.11.0:
randombytes "^2.0.0" randombytes "^2.0.0"
randomfill "^1.0.3" randomfill "^1.0.3"
crypto-js@^4.1.1:
version "4.1.1"
resolved "https://registry.yarnpkg.com/crypto-js/-/crypto-js-4.1.1.tgz#9e485bcf03521041bd85844786b83fb7619736cf"
integrity sha512-o2JlM7ydqd3Qk9CA0L4NL6mTzU2sdx96a+oOfPu8Mkl/PK51vSyoi8/rQ8NknZtk44vq15lmhAj9CIAGwgeWKw==
css-blank-pseudo@^3.0.3: css-blank-pseudo@^3.0.3:
version "3.0.3" version "3.0.3"
resolved "https://registry.yarnpkg.com/css-blank-pseudo/-/css-blank-pseudo-3.0.3.tgz#36523b01c12a25d812df343a32c322d2a2324561" resolved "https://registry.yarnpkg.com/css-blank-pseudo/-/css-blank-pseudo-3.0.3.tgz#36523b01c12a25d812df343a32c322d2a2324561"
@@ -9170,13 +9236,6 @@ history@^4.9.0:
tiny-warning "^1.0.0" tiny-warning "^1.0.0"
value-equal "^1.0.1" value-equal "^1.0.1"
history@^5.2.0:
version "5.3.0"
resolved "https://registry.yarnpkg.com/history/-/history-5.3.0.tgz#1548abaa245ba47992f063a0783db91ef201c73b"
integrity sha512-ZqaKwjjrAYUYfLG+htGaIIZ4nioX2L70ZUMIFysS3xvBsSG4x/n1V6TXV3N8ZYNuFGlDirFg32T7B6WOUPDYcQ==
dependencies:
"@babel/runtime" "^7.7.6"
hmac-drbg@^1.0.1: hmac-drbg@^1.0.1:
version "1.0.1" version "1.0.1"
resolved "https://registry.yarnpkg.com/hmac-drbg/-/hmac-drbg-1.0.1.tgz#d2745701025a6c775a6c545793ed502fc0c649a1" resolved "https://registry.yarnpkg.com/hmac-drbg/-/hmac-drbg-1.0.1.tgz#d2745701025a6c775a6c545793ed502fc0c649a1"
@@ -10274,6 +10333,15 @@ jest-mock@^29.3.1:
"@types/node" "*" "@types/node" "*"
jest-util "^29.3.1" jest-util "^29.3.1"
jest-mock@^29.5.0:
version "29.5.0"
resolved "https://registry.yarnpkg.com/jest-mock/-/jest-mock-29.5.0.tgz#26e2172bcc71d8b0195081ff1f146ac7e1518aed"
integrity sha512-GqOzvdWDE4fAV2bWQLQCkujxYWL7RxjCnj71b5VhDAGOevB3qj3Ovg26A5NI84ZpODxyzaozXLOh2NCgkbvyaw==
dependencies:
"@jest/types" "^29.5.0"
"@types/node" "*"
jest-util "^29.5.0"
jest-pnp-resolver@^1.2.2: jest-pnp-resolver@^1.2.2:
version "1.2.2" version "1.2.2"
resolved "https://registry.yarnpkg.com/jest-pnp-resolver/-/jest-pnp-resolver-1.2.2.tgz#b704ac0ae028a89108a4d040b3f919dfddc8e33c" resolved "https://registry.yarnpkg.com/jest-pnp-resolver/-/jest-pnp-resolver-1.2.2.tgz#b704ac0ae028a89108a4d040b3f919dfddc8e33c"
@@ -10416,6 +10484,18 @@ jest-util@^29.3.1:
graceful-fs "^4.2.9" graceful-fs "^4.2.9"
picomatch "^2.2.3" picomatch "^2.2.3"
jest-util@^29.5.0:
version "29.5.0"
resolved "https://registry.yarnpkg.com/jest-util/-/jest-util-29.5.0.tgz#24a4d3d92fc39ce90425311b23c27a6e0ef16b8f"
integrity sha512-RYMgG/MTadOr5t8KdhejfvUU82MxsCu5MF6KuDUHl+NuwzUt+Sm6jJWxTJVrDR1j5M/gJVCPKQEpWXY+yIQ6lQ==
dependencies:
"@jest/types" "^29.5.0"
"@types/node" "*"
chalk "^4.0.0"
ci-info "^3.2.0"
graceful-fs "^4.2.9"
picomatch "^2.2.3"
jest-validate@^29.2.2: jest-validate@^29.2.2:
version "29.2.2" version "29.2.2"
resolved "https://registry.yarnpkg.com/jest-validate/-/jest-validate-29.2.2.tgz#e43ce1931292dfc052562a11bc681af3805eadce" resolved "https://registry.yarnpkg.com/jest-validate/-/jest-validate-29.2.2.tgz#e43ce1931292dfc052562a11bc681af3805eadce"
@@ -10613,6 +10693,11 @@ junk@^3.1.0:
resolved "https://registry.yarnpkg.com/junk/-/junk-3.1.0.tgz#31499098d902b7e98c5d9b9c80f43457a88abfa1" resolved "https://registry.yarnpkg.com/junk/-/junk-3.1.0.tgz#31499098d902b7e98c5d9b9c80f43457a88abfa1"
integrity sha512-pBxcB3LFc8QVgdggvZWyeys+hnrNWg4OcZIU/1X59k5jQdLBlCsYGRQaz234SqoRLTCgMH00fY0xRJH+F9METQ== integrity sha512-pBxcB3LFc8QVgdggvZWyeys+hnrNWg4OcZIU/1X59k5jQdLBlCsYGRQaz234SqoRLTCgMH00fY0xRJH+F9METQ==
jwt-decode@^3.1.2:
version "3.1.2"
resolved "https://registry.yarnpkg.com/jwt-decode/-/jwt-decode-3.1.2.tgz#3fb319f3675a2df0c2895c8f5e9fa4b67b04ed59"
integrity sha512-UfpWE/VZn0iP50d8cz9NrZLM9lSWhcJ+0Gt/nm4by88UL+J1SiKN8/5dkjMmbEzwL2CAe+67GsegCbIKtbp75A==
khroma@^1.4.1: khroma@^1.4.1:
version "1.4.1" version "1.4.1"
resolved "https://registry.yarnpkg.com/khroma/-/khroma-1.4.1.tgz#ad6a5b6a972befc5112ce5129887a1a83af2c003" resolved "https://registry.yarnpkg.com/khroma/-/khroma-1.4.1.tgz#ad6a5b6a972befc5112ce5129887a1a83af2c003"
@@ -10972,18 +11057,20 @@ matrix-events-sdk@0.0.1:
resolved "https://registry.yarnpkg.com/matrix-events-sdk/-/matrix-events-sdk-0.0.1.tgz#c8c38911e2cb29023b0bbac8d6f32e0de2c957dd" resolved "https://registry.yarnpkg.com/matrix-events-sdk/-/matrix-events-sdk-0.0.1.tgz#c8c38911e2cb29023b0bbac8d6f32e0de2c957dd"
integrity sha512-1QEOsXO+bhyCroIe2/A5OwaxHvBm7EsSQ46DEDn8RBIfQwN5HWBpFvyWWR4QY0KHPPnnJdI99wgRiAl7Ad5qaA== integrity sha512-1QEOsXO+bhyCroIe2/A5OwaxHvBm7EsSQ46DEDn8RBIfQwN5HWBpFvyWWR4QY0KHPPnnJdI99wgRiAl7Ad5qaA==
"matrix-js-sdk@github:matrix-org/matrix-js-sdk#9ba44b96202e36d8bd6fbcff3222b7c70fc371d7": "matrix-js-sdk@github:matrix-org/matrix-js-sdk#b698217445318f453e0b1086364a33113eaa85d9":
version "26.0.1" version "26.2.0"
resolved "https://codeload.github.com/matrix-org/matrix-js-sdk/tar.gz/9ba44b96202e36d8bd6fbcff3222b7c70fc371d7" resolved "https://codeload.github.com/matrix-org/matrix-js-sdk/tar.gz/b698217445318f453e0b1086364a33113eaa85d9"
dependencies: dependencies:
"@babel/runtime" "^7.12.5" "@babel/runtime" "^7.12.5"
"@matrix-org/matrix-sdk-crypto-js" "^0.1.0-alpha.10" "@matrix-org/matrix-sdk-crypto-js" "^0.1.1"
another-json "^0.2.0" another-json "^0.2.0"
bs58 "^5.0.0" bs58 "^5.0.0"
content-type "^1.0.4" content-type "^1.0.4"
jwt-decode "^3.1.2"
loglevel "^1.7.1" loglevel "^1.7.1"
matrix-events-sdk "0.0.1" matrix-events-sdk "0.0.1"
matrix-widget-api "^1.3.1" matrix-widget-api "^1.3.1"
oidc-client-ts "^2.2.4"
p-retry "4" p-retry "4"
sdp-transform "^2.14.1" sdp-transform "^2.14.1"
unhomoglyph "^1.0.6" unhomoglyph "^1.0.6"
@@ -11670,6 +11757,14 @@ objectorarray@^1.0.5:
resolved "https://registry.yarnpkg.com/objectorarray/-/objectorarray-1.0.5.tgz#2c05248bbefabd8f43ad13b41085951aac5e68a5" resolved "https://registry.yarnpkg.com/objectorarray/-/objectorarray-1.0.5.tgz#2c05248bbefabd8f43ad13b41085951aac5e68a5"
integrity sha512-eJJDYkhJFFbBBAxeh8xW+weHlkI28n2ZdQV/J/DNfWfSKlGEf2xcfAbZTv3riEXHAhL9SVOTs2pRmXiSTf78xg== integrity sha512-eJJDYkhJFFbBBAxeh8xW+weHlkI28n2ZdQV/J/DNfWfSKlGEf2xcfAbZTv3riEXHAhL9SVOTs2pRmXiSTf78xg==
oidc-client-ts@^2.2.4:
version "2.2.4"
resolved "https://registry.yarnpkg.com/oidc-client-ts/-/oidc-client-ts-2.2.4.tgz#7d86b5efe2248f3637a6f3a0ee1af86764aea125"
integrity sha512-nOZwIomju+AmXObl5Oq5PjrES/qTt8bLsENJCIydVgi9TEWk7SCkOU6X3RNkY7yfySRM1OJJvDKdREZdmnDT2g==
dependencies:
crypto-js "^4.1.1"
jwt-decode "^3.1.2"
on-finished@2.4.1: on-finished@2.4.1:
version "2.4.1" version "2.4.1"
resolved "https://registry.yarnpkg.com/on-finished/-/on-finished-2.4.1.tgz#58c8c44116e54845ad57f14ab10b03533184ac3f" resolved "https://registry.yarnpkg.com/on-finished/-/on-finished-2.4.1.tgz#58c8c44116e54845ad57f14ab10b03533184ac3f"
@@ -12981,13 +13076,6 @@ react-router@5.3.3:
tiny-invariant "^1.0.2" tiny-invariant "^1.0.2"
tiny-warning "^1.0.0" tiny-warning "^1.0.0"
react-router@6:
version "6.3.0"
resolved "https://registry.yarnpkg.com/react-router/-/react-router-6.3.0.tgz#3970cc64b4cb4eae0c1ea5203a80334fdd175557"
integrity sha512-7Wh1DzVQ+tlFjkeo+ujvjSqSJmkt1+8JO+T5xklPlgrh70y7ogx75ODRW0ThWhY7S+6yEDks8TYrtQe/aoboBQ==
dependencies:
history "^5.2.0"
react-syntax-highlighter@^15.4.5: react-syntax-highlighter@^15.4.5:
version "15.5.0" version "15.5.0"
resolved "https://registry.yarnpkg.com/react-syntax-highlighter/-/react-syntax-highlighter-15.5.0.tgz#4b3eccc2325fa2ec8eff1e2d6c18fa4a9e07ab20" resolved "https://registry.yarnpkg.com/react-syntax-highlighter/-/react-syntax-highlighter-15.5.0.tgz#4b3eccc2325fa2ec8eff1e2d6c18fa4a9e07ab20"