mirror of
https://github.com/vector-im/element-call.git
synced 2026-11-28 10:01:09 +08:00
Compare commits
90
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
157a81d91a | ||
|
|
6f328bac02 | ||
|
|
0118be7ee7 | ||
|
|
788f43f578 | ||
|
|
1816cb3887 | ||
|
|
bddd96e509 | ||
|
|
0ae0dbcbb5 | ||
|
|
c0370c254c | ||
|
|
cd1685091f | ||
|
|
48ada17b19 | ||
|
|
4f6a919aa6 | ||
|
|
13ce1c2648 | ||
|
|
9a7ce81396 | ||
|
|
a50a7d19f2 | ||
|
|
a96091411c | ||
|
|
532803d5f5 | ||
|
|
56d5d87954 | ||
|
|
f0ce686a27 | ||
|
|
35310b2771 | ||
|
|
b2b768b4d0 | ||
|
|
2362694216 | ||
|
|
608198be9a | ||
|
|
08be167644 | ||
|
|
df34bb06ff | ||
|
|
c573afee08 | ||
|
|
ddfd48138a | ||
|
|
60c2c353c6 | ||
|
|
fab67321e3 | ||
|
|
00851b0f4f | ||
|
|
92e0965347 | ||
|
|
ada8d6b464 | ||
|
|
caf5e28b23 | ||
|
|
e71203f913 | ||
|
|
2bf7b1385b | ||
|
|
eb69706111 | ||
|
|
9cb668eabb | ||
|
|
d53e1a25c0 | ||
|
|
58f41e1f59 | ||
|
|
e18322462b | ||
|
|
b40ccc4091 | ||
|
|
4daf10d043 | ||
|
|
d440cd49b2 | ||
|
|
cd44d0ff5b | ||
|
|
b6b2af595f | ||
|
|
e881803922 | ||
|
|
1c93370462 | ||
|
|
9bd510c1bf | ||
|
|
88eb3aaf9d | ||
|
|
d85c1d86f0 | ||
|
|
ca5fc7adc0 | ||
|
|
dbfe494852 | ||
|
|
78ddd9839c | ||
|
|
64ad1d7314 | ||
|
|
1c4d2c5d29 | ||
|
|
b4408dcecf | ||
|
|
98afaa71ce | ||
|
|
aef28af48a | ||
|
|
35280e3847 | ||
|
|
2c85cdb308 | ||
|
|
6ca17f4e2d | ||
|
|
6751c753ea | ||
|
|
707b218e38 | ||
|
|
95d24486ef | ||
|
|
8d04612f9c | ||
|
|
dc2e64c666 | ||
|
|
20b989b3e5 | ||
|
|
ecd542f526 | ||
|
|
be85e0b49d | ||
|
|
b5571dd837 | ||
|
|
e3b414434c | ||
|
|
69ad5ff68c | ||
|
|
cc93991fbe | ||
|
|
7b803e1dc8 | ||
|
|
96e6a811f4 | ||
|
|
2b5ad74ede | ||
|
|
208ef89d7c | ||
|
|
a3edc058a0 | ||
|
|
1b94460ddf | ||
|
|
17e3c02aa5 | ||
|
|
d3b653d25d | ||
|
|
f1e82b9e85 | ||
|
|
ff11990046 | ||
|
|
87bd273fa5 | ||
|
|
a5dd993dd4 | ||
|
|
b3fe19f192 | ||
|
|
e631979256 | ||
|
|
a27a76d6f1 | ||
|
|
8b9dde62d1 | ||
|
|
5f776519b1 | ||
|
|
904062b917 |
@@ -0,0 +1,53 @@
|
||||
<!-- Maintainer template. External contributors use the default template. -->
|
||||
|
||||
## Motivation and context
|
||||
|
||||
<!-- Link the issue this closes, or explain the context for a bug fix -->
|
||||
|
||||
## Plan (optional)
|
||||
|
||||
_Reviewer: read and challenge this plan carefully as part of the review._
|
||||
|
||||
<!--
|
||||
Only if this change was made with AI; delete this section otherwise.
|
||||
Plan := the final version of the human-edited plan/prompt this change used.
|
||||
It is not the implementation plan from Claude's plan mode. That goes under Content.
|
||||
-->
|
||||
|
||||
## Content
|
||||
|
||||
<!--
|
||||
Mandatory. Describe what has been changed.
|
||||
This is also where an LLM implementation plan or other plan artifacts are linked:
|
||||
paste them in a collapsed <details> block, or attach them as files.
|
||||
-->
|
||||
|
||||
## Screenshots / GIFs / Storybook links
|
||||
|
||||
<!--
|
||||
|
||||
You can use a table like this to show a before/after comparison.
|
||||
Uncomment the markdown table below and fill in the last line:
|
||||
|
||||
|Before|After|
|
||||
|-|-|
|
||||
|||
|
||||
|
||||
-->
|
||||
|
||||
## Tests
|
||||
|
||||
<!-- Explain how you tested your changes -->
|
||||
|
||||
- Step 1
|
||||
- Step ...
|
||||
|
||||
## Checklist
|
||||
|
||||
- [ ] Exactly one `PR-*` label is set.
|
||||
- [ ] New behaviour has unit tests, a story if it renders, and an e2e spec if it is user-facing.
|
||||
- [ ] Visible changes link their Storybook stories (add the `storybook build` label for a preview deploy).
|
||||
- [ ] Visible changes without a story include screenshots or a video.
|
||||
- [ ] Checked standalone, as a widget and as a component.
|
||||
- [ ] Linter and other CI checks pass.
|
||||
- [ ] Claude review has been run at least once (assign the Claude-Review label)
|
||||
@@ -9,6 +9,11 @@ on:
|
||||
required: false
|
||||
type: string
|
||||
default: ${{ github.run_id }}
|
||||
secrets:
|
||||
TS_OAUTH_CLIENT_ID:
|
||||
required: true
|
||||
TS_AUDIENCE:
|
||||
required: true
|
||||
|
||||
env:
|
||||
REGISTRY: ghcr.io
|
||||
|
||||
@@ -7,7 +7,7 @@ on:
|
||||
type: string
|
||||
package:
|
||||
type: string # This would ideally be a `choice` type, but that isn't supported yet
|
||||
description: The package type to be built. Must be one of 'full', 'embedded', or 'sdk'
|
||||
description: The package type to be built. Must be one of 'full', 'embedded', or 'widget-rtc-sdk'
|
||||
required: true
|
||||
build_mode:
|
||||
type: string # This would ideally be a `choice` type, but that isn't supported yet
|
||||
@@ -38,7 +38,7 @@ jobs:
|
||||
- name: Enable Corepack
|
||||
run: corepack enable
|
||||
- name: pnpm cache
|
||||
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
with:
|
||||
cache: "pnpm"
|
||||
node-version-file: ".node-version"
|
||||
|
||||
@@ -7,10 +7,15 @@ on:
|
||||
- labeled
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
build_full_element_call:
|
||||
# Use the full package vite build
|
||||
uses: ./.github/workflows/build-element-call.yaml
|
||||
permissions:
|
||||
contents: read
|
||||
uses: $/.github/workflows/build-element-call.yaml
|
||||
with:
|
||||
package: full
|
||||
vite_app_version: ${{ github.event.release.tag_name || github.sha }}
|
||||
@@ -26,6 +31,7 @@ jobs:
|
||||
if: github.ref == 'refs/heads/main'
|
||||
needs: build_full_element_call
|
||||
runs-on: ubuntu-24.04
|
||||
permissions: {}
|
||||
steps:
|
||||
- name: Deploy to call.element.dev
|
||||
uses: actions/github-script@d7906e4ad0b1822421a7e6a35d5ca353c962f410 # v6
|
||||
@@ -50,8 +56,10 @@ jobs:
|
||||
contents: write
|
||||
packages: write
|
||||
id-token: write
|
||||
uses: ./.github/workflows/build-and-publish-docker.yaml
|
||||
secrets: inherit
|
||||
uses: $/.github/workflows/build-and-publish-docker.yaml
|
||||
secrets:
|
||||
TS_OAUTH_CLIENT_ID: ${{ secrets.TS_OAUTH_CLIENT_ID }}
|
||||
TS_AUDIENCE: ${{ secrets.TS_AUDIENCE }}
|
||||
with:
|
||||
artifact_run_id: ${{ github.run_id }}
|
||||
docker_tags: |
|
||||
@@ -60,7 +68,9 @@ jobs:
|
||||
type=raw,value=latest-ci_{{date 'X' }}
|
||||
build_embedded_element_call:
|
||||
# Use the embedded package vite build
|
||||
uses: ./.github/workflows/build-element-call.yaml
|
||||
permissions:
|
||||
contents: read
|
||||
uses: $/.github/workflows/build-element-call.yaml
|
||||
with:
|
||||
package: embedded
|
||||
vite_app_version: ${{ github.event.release.tag_name || github.sha }}
|
||||
@@ -72,14 +82,14 @@ jobs:
|
||||
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
|
||||
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
|
||||
|
||||
build_sdk_element_call:
|
||||
# The 'sdk' package is the CallViewModel bundle that predates the sdk/
|
||||
# package (build:sdk:production, sdk-target-based-on-call-view-model/), not
|
||||
# the package itself. The name is shared with pr-deploy.yaml, which always
|
||||
# runs from main, so it stays until the bundle's consumers have moved over.
|
||||
uses: ./.github/workflows/build-element-call.yaml
|
||||
build_widget_rtc_sdk:
|
||||
# The widget wrapper around the sdk/ package (widget-rtc-sdk/), not the
|
||||
# package itself. Deployed by pr-deploy.yaml as the pr<N>-widget-rtc-sdk preview.
|
||||
permissions:
|
||||
contents: read
|
||||
uses: $/.github/workflows/build-element-call.yaml
|
||||
with:
|
||||
package: sdk
|
||||
package: widget-rtc-sdk
|
||||
vite_app_version: ${{ github.event.release.tag_name || github.sha }}
|
||||
build_mode: ${{ github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'development build') && 'development' || 'production' }}
|
||||
secrets:
|
||||
@@ -93,6 +103,8 @@ jobs:
|
||||
name: Build Storybook
|
||||
if: contains(github.event.pull_request.labels.*.name, 'storybook build')
|
||||
runs-on: ubuntu-24.04
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
@@ -101,7 +113,7 @@ jobs:
|
||||
- name: Enable Corepack
|
||||
run: corepack enable
|
||||
- name: pnpm cache
|
||||
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
with:
|
||||
cache: "pnpm"
|
||||
node-version-file: ".node-version"
|
||||
|
||||
@@ -44,12 +44,13 @@ jobs:
|
||||
that still deliver value?
|
||||
|
||||
2. Commits:
|
||||
|
||||
|
||||
- Is the work split into self-contained commits of reasonable size?
|
||||
- Are the commits arranged in a sensible order?
|
||||
- Have required refactorings been split out into separate commits?
|
||||
- Is the history free of "wip", checkpoint and fixup-style commits
|
||||
which only correct an earlier commit in the same PR?
|
||||
- Are SDK and Element Call changes split into separate commits?
|
||||
|
||||
3. Code:
|
||||
|
||||
@@ -60,6 +61,19 @@ jobs:
|
||||
- Don't check anything that is already validated via other GitHub
|
||||
workflows like linting, formatting or tests passing.
|
||||
|
||||
4. Code style:
|
||||
|
||||
- Does the change follow docs/agents/code-style.md and
|
||||
docs/agents/architecture.md?
|
||||
|
||||
5. Repo architecture:
|
||||
|
||||
- Does the change follow "Element Call on the SDK" in
|
||||
docs/agents/architecture.md and, where it touches `sdk/`,
|
||||
sdk/SdkArchitecture.md?
|
||||
- If an `api.ts` changed and the PR description does not document
|
||||
it, summarize the change in the final review comment.
|
||||
|
||||
Read the commits themselves with `git log` and `git diff` against
|
||||
the base branch of the PR.
|
||||
|
||||
@@ -68,9 +82,9 @@ jobs:
|
||||
"🟠 medium" or "🔴 high". Devise at least one possible resolution for each
|
||||
finding.
|
||||
|
||||
Report the graded findings and resolutions from the "Code" angle as inline
|
||||
comments. Add a footer "_-- Finding from automated review_" to each inline
|
||||
comment.
|
||||
Report the graded findings and resolutions from the "Code" and "Code style"
|
||||
angles as inline comments. Add a footer "_-- Finding from automated review_"
|
||||
to each inline comment.
|
||||
|
||||
Finally, report your overall result as PR comment. Start your message with
|
||||
"# Automated review". Then add one section per review angle with:
|
||||
|
||||
@@ -17,7 +17,7 @@ on:
|
||||
package:
|
||||
required: true
|
||||
type: string
|
||||
description: Which package to deploy - 'full', 'embedded', 'sdk', or 'storybook'
|
||||
description: Which package to deploy - 'full', 'embedded', 'widget-rtc-sdk', or 'storybook'
|
||||
artifact_run_id:
|
||||
required: false
|
||||
type: string
|
||||
@@ -64,25 +64,27 @@ jobs:
|
||||
run: curl -s https://raw.githubusercontent.com/element-hq/element-call/main/config/netlify_redirects > webapp/_redirects
|
||||
|
||||
- name: Add config file
|
||||
# Not needed for storybook deployments
|
||||
if: inputs.package != 'storybook'
|
||||
run: |
|
||||
if [ "${INPUTS_PACKAGE}" = "full" ]; then
|
||||
curl -s "https://raw.githubusercontent.com/${INPUTS_PR_HEAD_FULL_NAME}/${INPUTS_PR_HEAD_REF}/config/config_netlify_preview.json" > webapp/config.json
|
||||
else
|
||||
curl -s "https://raw.githubusercontent.com/${INPUTS_PR_HEAD_FULL_NAME}/${INPUTS_PR_HEAD_REF}/config/config_netlify_preview_sdk.json" > webapp/config.json
|
||||
fi
|
||||
# Only the app reads a config.json beside it. A widget gets everything
|
||||
# about the homeserver from its host.
|
||||
if: inputs.package == 'full'
|
||||
run: curl -s "https://raw.githubusercontent.com/${INPUTS_PR_HEAD_FULL_NAME}/${INPUTS_PR_HEAD_REF}/config/config_netlify_preview.json" > webapp/config.json
|
||||
env:
|
||||
INPUTS_PACKAGE: ${{ inputs.package }}
|
||||
INPUTS_PR_HEAD_FULL_NAME: ${{ inputs.pr_head_full_name }}
|
||||
INPUTS_PR_HEAD_REF: ${{ inputs.pr_head_ref }}
|
||||
- name: Add headers file
|
||||
# A widget page on another origin imports the widget RTC SDK bundle as a
|
||||
# module, which the browser only allows with CORS
|
||||
if: inputs.package == 'widget-rtc-sdk'
|
||||
run: |
|
||||
printf '/*\n Access-Control-Allow-Origin: *\n' > webapp/_headers
|
||||
|
||||
- name: ☁️ Deploy to Netlify
|
||||
id: netlify
|
||||
uses: nwtgck/actions-netlify@4cbaf4c08f1a7bfa537d6113472ef4424e4eb654 # v3.0
|
||||
with:
|
||||
publish-dir: webapp
|
||||
deploy-message: "Deploy from GitHub Actions"
|
||||
alias: ${{ inputs.package == 'sdk' && format('pr{0}-sdk', inputs.pr_number) || inputs.package == 'storybook' && format('pr{0}-storybook', inputs.pr_number) || format('pr{0}', inputs.pr_number) }}
|
||||
alias: ${{ inputs.package == 'widget-rtc-sdk' && format('pr{0}-widget-rtc-sdk', inputs.pr_number) || inputs.package == 'storybook' && format('pr{0}-storybook', inputs.pr_number) || format('pr{0}', inputs.pr_number) }}
|
||||
env:
|
||||
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
|
||||
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
|
||||
|
||||
@@ -7,10 +7,15 @@ on:
|
||||
type: string
|
||||
required: false
|
||||
description: The matrix-js-sdk commit to build against instead of the locked one
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
name: Lint, format & type check
|
||||
runs-on: ubuntu-24.04
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
@@ -21,7 +26,7 @@ jobs:
|
||||
- name: Enable Corepack
|
||||
run: corepack enable
|
||||
- name: pnpm cache
|
||||
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
with:
|
||||
cache: "pnpm"
|
||||
node-version-file: ".node-version"
|
||||
|
||||
@@ -7,6 +7,8 @@ on:
|
||||
types:
|
||||
- completed
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
prdetails:
|
||||
# Logic:
|
||||
@@ -18,6 +20,8 @@ jobs:
|
||||
github.event.workflow_run.event == 'pull_request' &&
|
||||
github.event.workflow_run.head_repository.full_name == github.repository
|
||||
runs-on: ubuntu-24.04
|
||||
permissions:
|
||||
pull-requests: read
|
||||
outputs:
|
||||
pr_number: ${{ steps.prdetails.outputs.pr_id }}
|
||||
pr_data_json: ${{ steps.prdetails.outputs.data }}
|
||||
@@ -33,7 +37,7 @@ jobs:
|
||||
needs: prdetails
|
||||
permissions:
|
||||
deployments: write
|
||||
uses: ./.github/workflows/deploy-to-netlify.yaml
|
||||
uses: $/.github/workflows/deploy-to-netlify.yaml
|
||||
with:
|
||||
artifact_run_id: ${{ github.event.workflow_run.id || github.run_id }}
|
||||
pr_number: ${{ needs.prdetails.outputs.pr_number }}
|
||||
@@ -46,18 +50,18 @@ jobs:
|
||||
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
|
||||
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
|
||||
|
||||
netlify-sdk:
|
||||
netlify-widget-rtc-sdk:
|
||||
needs: prdetails
|
||||
permissions:
|
||||
deployments: write
|
||||
uses: ./.github/workflows/deploy-to-netlify.yaml
|
||||
uses: $/.github/workflows/deploy-to-netlify.yaml
|
||||
with:
|
||||
artifact_run_id: ${{ github.event.workflow_run.id || github.run_id }}
|
||||
pr_number: ${{ needs.prdetails.outputs.pr_number }}
|
||||
pr_head_full_name: ${{ github.event.workflow_run.head_repository.full_name }}
|
||||
pr_head_ref: ${{ needs.prdetails.outputs.pr_data_json && fromJSON(needs.prdetails.outputs.pr_data_json).head.ref }}
|
||||
deployment_ref: ${{ needs.prdetails.outputs.pr_data_json && fromJSON(needs.prdetails.outputs.pr_data_json).head.sha || github.ref || github.head_ref }}
|
||||
package: sdk
|
||||
package: widget-rtc-sdk
|
||||
secrets:
|
||||
ELEMENT_BOT_TOKEN: ${{ secrets.ELEMENT_BOT_TOKEN }}
|
||||
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
|
||||
@@ -68,7 +72,7 @@ jobs:
|
||||
if: ${{ needs.prdetails.outputs.pr_data_json && contains(fromJSON(needs.prdetails.outputs.pr_data_json).labels.*.name, 'storybook build') }}
|
||||
permissions:
|
||||
deployments: write
|
||||
uses: ./.github/workflows/deploy-to-netlify.yaml
|
||||
uses: $/.github/workflows/deploy-to-netlify.yaml
|
||||
with:
|
||||
artifact_run_id: ${{ github.event.workflow_run.id || github.run_id }}
|
||||
pr_number: ${{ needs.prdetails.outputs.pr_number }}
|
||||
@@ -88,8 +92,10 @@ jobs:
|
||||
contents: write
|
||||
packages: write
|
||||
id-token: write
|
||||
uses: ./.github/workflows/build-and-publish-docker.yaml
|
||||
secrets: inherit
|
||||
uses: $/.github/workflows/build-and-publish-docker.yaml
|
||||
secrets:
|
||||
TS_OAUTH_CLIENT_ID: ${{ secrets.TS_OAUTH_CLIENT_ID }}
|
||||
TS_AUDIENCE: ${{ secrets.TS_AUDIENCE }}
|
||||
with:
|
||||
artifact_run_id: ${{ github.event.workflow_run.id || github.run_id }}
|
||||
docker_tags: |
|
||||
|
||||
@@ -73,9 +73,10 @@ jobs:
|
||||
- name: Enable Corepack
|
||||
run: corepack enable
|
||||
- name: Setup node
|
||||
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
# No dependency cache: a release build must not restore one another workflow could have poisoned
|
||||
with:
|
||||
package-manager-cache: false
|
||||
node-version-file: .node-version
|
||||
registry-url: "https://registry.npmjs.org"
|
||||
# Layered like build-element-call.yaml, so a PR paired with a matrix-js-sdk branch
|
||||
@@ -112,8 +113,10 @@ jobs:
|
||||
if: ${{ needs.versioning.outputs.DRY_RUN == 'false' }}
|
||||
name: Update release notes
|
||||
runs-on: ubuntu-24.04
|
||||
# Shared with publish-embedded-packages.yaml, which appends to the same release: two
|
||||
# appends at once would each write back the body without the other's section
|
||||
# Shared with publish.yaml and publish-embedded-packages.yaml, which append to the same
|
||||
# release. GitHub lets only one job wait per group, so if all three arrive at once the
|
||||
# waiting one is cancelled: re-run it. To mitigate this, the append exits early when its
|
||||
# heading already exists.
|
||||
concurrency:
|
||||
group: release-notes-${{ github.event.release.tag_name || github.run_id }}
|
||||
cancel-in-progress: false
|
||||
@@ -121,10 +124,20 @@ jobs:
|
||||
contents: write # to update release notes
|
||||
steps:
|
||||
- name: Add release notes
|
||||
uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2
|
||||
with:
|
||||
append_body: true
|
||||
body: |
|
||||
run: |
|
||||
gh release view "$RELEASE_TAG" --json body --jq .body > release-body.md
|
||||
if grep -qF "$HEADING" release-body.md; then
|
||||
echo "Section already present, nothing to add"
|
||||
exit 0
|
||||
fi
|
||||
printf '%s\n' "$NOTES" >> release-body.md
|
||||
gh release edit "$RELEASE_TAG" --notes-file release-body.md
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
RELEASE_TAG: ${{ github.event.release.tag_name }}
|
||||
HEADING: "## React component (experimental)"
|
||||
NOTES: |
|
||||
|
||||
## React component (experimental)
|
||||
|
||||
|
||||
@@ -11,6 +11,8 @@ on:
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
versioning:
|
||||
name: Versioning
|
||||
@@ -62,7 +64,9 @@ jobs:
|
||||
|
||||
build_element_call:
|
||||
needs: versioning
|
||||
uses: ./.github/workflows/build-element-call.yaml
|
||||
permissions:
|
||||
contents: read
|
||||
uses: $/.github/workflows/build-element-call.yaml
|
||||
with:
|
||||
vite_app_version: embedded-${{ needs.versioning.outputs.PREFIXED_VERSION }}
|
||||
package: embedded
|
||||
@@ -97,11 +101,11 @@ jobs:
|
||||
run: find ${FILENAME_PREFIX} -type f -print0 | sort -z | xargs -0 sha256sum | tee ${FILENAME_PREFIX}.sha256
|
||||
- name: Upload
|
||||
if: ${{ needs.versioning.outputs.DRY_RUN == 'false' }}
|
||||
uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2
|
||||
with:
|
||||
files: |
|
||||
${{ env.FILENAME_PREFIX }}.tar.gz
|
||||
${{ env.FILENAME_PREFIX }}.sha256
|
||||
run: gh release upload "$RELEASE_TAG" "${FILENAME_PREFIX}.tar.gz" "${FILENAME_PREFIX}.sha256" --clobber
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
RELEASE_TAG: ${{ github.event.release.tag_name }}
|
||||
|
||||
publish_npm:
|
||||
needs: [build_element_call, versioning]
|
||||
@@ -129,8 +133,10 @@ jobs:
|
||||
|
||||
# n.b. We don't enable corepack here because we are using plain npm
|
||||
- name: Setup node
|
||||
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
# No dependency cache: a release build must not restore one another workflow could have poisoned
|
||||
with:
|
||||
package-manager-cache: false
|
||||
node-version-file: .node-version
|
||||
registry-url: "https://registry.npmjs.org"
|
||||
|
||||
@@ -283,8 +289,10 @@ jobs:
|
||||
if: always()
|
||||
name: Update release notes
|
||||
runs-on: ubuntu-24.04
|
||||
# Shared with publish-component.yaml, which appends to the same release: two appends
|
||||
# at once would each write back the body without the other's section
|
||||
# Shared with publish.yaml and publish-component.yaml, which append to the same
|
||||
# release. GitHub lets only one job wait per group, so if all three arrive at once the
|
||||
# waiting one is cancelled: re-run it. To mitigate this, the append exits early when its
|
||||
# heading already exists.
|
||||
concurrency:
|
||||
group: release-notes-${{ github.event.release.tag_name || github.run_id }}
|
||||
cancel-in-progress: false
|
||||
@@ -302,10 +310,20 @@ jobs:
|
||||
NEEDS_PUBLISH_IOS_OUTPUTS_ARTIFACT_VERSION: ${{ needs.publish_ios.outputs.ARTIFACT_VERSION }}
|
||||
- name: Add release notes
|
||||
if: ${{ needs.versioning.outputs.DRY_RUN == 'false' }}
|
||||
uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2
|
||||
with:
|
||||
append_body: true
|
||||
body: |
|
||||
run: |
|
||||
gh release view "$RELEASE_TAG" --json body --jq .body > release-body.md
|
||||
if grep -qF "$HEADING" release-body.md; then
|
||||
echo "Section already present, nothing to add"
|
||||
exit 0
|
||||
fi
|
||||
printf '%s\n' "$NOTES" >> release-body.md
|
||||
gh release edit "$RELEASE_TAG" --notes-file release-body.md
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
RELEASE_TAG: ${{ github.event.release.tag_name }}
|
||||
HEADING: "## Embedded packages"
|
||||
NOTES: |
|
||||
|
||||
## Embedded packages
|
||||
|
||||
|
||||
@@ -7,9 +7,13 @@ on:
|
||||
env:
|
||||
VERSION: ${{ github.event.release.tag_name }}
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
build_element_call:
|
||||
uses: ./.github/workflows/build-element-call.yaml
|
||||
permissions:
|
||||
contents: read
|
||||
uses: $/.github/workflows/build-element-call.yaml
|
||||
with:
|
||||
package: full
|
||||
vite_app_version: ${{ github.event.release.tag_name }} # Using ${{ env.VERSION }} here doesn't work
|
||||
@@ -42,11 +46,10 @@ jobs:
|
||||
- name: Create Checksum
|
||||
run: find ${FILENAME_PREFIX} -type f -print0 | sort -z | xargs -0 sha256sum | tee ${FILENAME_PREFIX}.sha256
|
||||
- name: Upload
|
||||
uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2
|
||||
with:
|
||||
files: |
|
||||
${{ env.FILENAME_PREFIX }}.tar.gz
|
||||
${{ env.FILENAME_PREFIX }}.sha256
|
||||
run: gh release upload "$VERSION" "${FILENAME_PREFIX}.tar.gz" "${FILENAME_PREFIX}.sha256" --clobber
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
|
||||
publish_docker:
|
||||
needs: build_element_call
|
||||
@@ -56,8 +59,10 @@ jobs:
|
||||
contents: write
|
||||
packages: write
|
||||
id-token: write
|
||||
uses: ./.github/workflows/build-and-publish-docker.yaml
|
||||
secrets: inherit
|
||||
uses: $/.github/workflows/build-and-publish-docker.yaml
|
||||
secrets:
|
||||
TS_OAUTH_CLIENT_ID: ${{ secrets.TS_OAUTH_CLIENT_ID }}
|
||||
TS_AUDIENCE: ${{ secrets.TS_AUDIENCE }}
|
||||
with:
|
||||
artifact_run_id: ${{ github.event.workflow_run.id || github.run_id }}
|
||||
docker_tags: |
|
||||
@@ -69,12 +74,30 @@ jobs:
|
||||
needs: publish_docker
|
||||
name: Add docker release note
|
||||
runs-on: ubuntu-24.04
|
||||
# Shared with publish-component.yaml and publish-embedded-packages.yaml, which append
|
||||
# to the same release. GitHub lets only one job wait per group, so if all three arrive at once the
|
||||
# waiting one is cancelled: re-run it. To mitigate this, the append exits early when its
|
||||
# heading already exists.
|
||||
concurrency:
|
||||
group: release-notes-${{ github.event.release.tag_name || github.run_id }}
|
||||
cancel-in-progress: false
|
||||
permissions:
|
||||
contents: write # to update release notes
|
||||
steps:
|
||||
- name: Add release note
|
||||
uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2
|
||||
with:
|
||||
append_body: true
|
||||
body: |
|
||||
run: |
|
||||
gh release view "$VERSION" --json body --jq .body > release-body.md
|
||||
if grep -qF "$HEADING" release-body.md; then
|
||||
echo "Section already present, nothing to add"
|
||||
exit 0
|
||||
fi
|
||||
printf '\n%s\n' "$NOTES" >> release-body.md
|
||||
gh release edit "$VERSION" --notes-file release-body.md
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
HEADING: "## Docker full package"
|
||||
NOTES: |
|
||||
## Docker full package
|
||||
Element Call is available as a Docker image from the [GitHub Container Registry](https://github.com/element-hq/element-call/pkgs/container/element-call).
|
||||
|
||||
|
||||
@@ -22,10 +22,16 @@ on:
|
||||
secrets:
|
||||
CODECOV_TOKEN:
|
||||
required: false
|
||||
|
||||
# Each job asks for what it needs
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
vitest:
|
||||
name: Run unit tests
|
||||
runs-on: ubuntu-24.04
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
@@ -36,7 +42,7 @@ jobs:
|
||||
- name: Enable Corepack
|
||||
run: corepack enable
|
||||
- name: pnpm cache
|
||||
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
with:
|
||||
cache: "pnpm"
|
||||
node-version-file: ".node-version"
|
||||
@@ -75,6 +81,8 @@ jobs:
|
||||
if: ${{ !inputs.disable_e2e_tests }}
|
||||
timeout-minutes: 60
|
||||
runs-on: ubuntu-24.04
|
||||
permissions:
|
||||
contents: read
|
||||
# We manually shard the tests across runners. Playwright's own shards cut
|
||||
# the list of tests into equal counts in file order, which would leave the
|
||||
# widget suite, the slowest tests by far, together at the end.
|
||||
@@ -100,7 +108,7 @@ jobs:
|
||||
persist-credentials: false
|
||||
- name: Enable Corepack
|
||||
run: corepack enable
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
with:
|
||||
cache: "pnpm"
|
||||
node-version-file: ".node-version"
|
||||
@@ -151,6 +159,8 @@ jobs:
|
||||
needs: playwright
|
||||
if: ${{ always() && !inputs.disable_e2e_tests }}
|
||||
runs-on: ubuntu-24.04
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
|
||||
with:
|
||||
@@ -159,7 +169,7 @@ jobs:
|
||||
persist-credentials: false
|
||||
- name: Enable Corepack
|
||||
run: corepack enable
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
with:
|
||||
cache: "pnpm"
|
||||
node-version-file: ".node-version"
|
||||
|
||||
@@ -20,7 +20,7 @@ jobs:
|
||||
- name: Enable Corepack
|
||||
run: corepack enable
|
||||
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
with:
|
||||
cache: "pnpm"
|
||||
node-version-file: ".node-version"
|
||||
|
||||
@@ -20,4 +20,4 @@ jobs:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Run zizmor 🌈
|
||||
uses: zizmorcore/zizmor-action@192e21d79ab29983730a13d1382995c2307fbcaa # v0.5.7
|
||||
uses: zizmorcore/zizmor-action@1b4550e929643b8b26a62303c6bd64814271a4f1 # v0.9.2
|
||||
|
||||
@@ -2,6 +2,7 @@ node_modules
|
||||
.DS_Store
|
||||
.env
|
||||
dist
|
||||
/dist-widget-rtc-sdk-example
|
||||
dist-ssr
|
||||
*.local
|
||||
*.bkp
|
||||
|
||||
@@ -43,8 +43,10 @@ Git-ignored. One kebab-case subfolder per task, matching the branch topic:
|
||||
promoted into the PR body or a doc before the task ends.
|
||||
- Never write scratch files to the repo root. Stray `load_test_summary.md` and
|
||||
`config.json_` files are what this folder prevents.
|
||||
- Start `pr-body.md` from `.github/PULL_REQUEST_TEMPLATE.md` and fill every
|
||||
section.
|
||||
- Start `pr-body.md` from `.github/PULL_REQUEST_TEMPLATE/maintainer.md` when
|
||||
working for a maintainer, otherwise from `.github/PULL_REQUEST_TEMPLATE.md`.
|
||||
In the maintainer template, Plan is the human-edited prompt (`NN-prompt.md`);
|
||||
`plan.md` is the implementation plan and goes under Content.
|
||||
|
||||
## Gates
|
||||
|
||||
|
||||
@@ -46,6 +46,11 @@ The issue is where we resolve all of that **before** anyone writes code.
|
||||
5. **Open a PR.** Link to the issue in your PR description and satisfy the checklist
|
||||
in the PR template.
|
||||
|
||||
Maintainers use the simpler
|
||||
[maintainer template](.github/PULL_REQUEST_TEMPLATE/maintainer.md) instead:
|
||||
`gh pr create --template maintainer.md`, or add `&template=maintainer.md` to the
|
||||
compare URL.
|
||||
|
||||
## Code Quality
|
||||
|
||||
Element Call moves fast and the codebase must stay clean and maintainable.
|
||||
|
||||
@@ -245,12 +245,15 @@ the build (`allowBuilds` in its `pnpm-workspace.yaml`).
|
||||
|
||||
##### Use
|
||||
|
||||
1. Provide the externals yourself: `react`, `react-dom`, `matrix-js-sdk`,
|
||||
1. Provide the externals yourself: `react`, `react-dom`,
|
||||
`@vector-im/compound-web`, `@vector-im/compound-design-tokens`, and
|
||||
Compound's stylesheet.
|
||||
Compound's stylesheet. The component bundles its own `matrix-js-sdk`; the
|
||||
host's client and room can be on any version that has what the `client`
|
||||
and `room` props pick from them, which the host's type check enforces.
|
||||
2. Import `@element-hq/element-call-component/style.css`.
|
||||
3. Await `initializeElementCall(config)` once before rendering.
|
||||
4. Render the component with `client`, `roomId` and an `intent`; optionally
|
||||
4. Render the component with `client`, `room` (from that client) and an
|
||||
`intent`; optionally
|
||||
pass `config`, `hostBridge`, `language` and `theme` (both can change
|
||||
mid-call). Control it through the `ref` handle (`join`, `hangUp`,
|
||||
`setDeviceMute`).
|
||||
@@ -275,7 +278,11 @@ API is in `component/index.tsx`, `component/api.ts` and `component/host.ts`.
|
||||
|
||||
##### Develop
|
||||
|
||||
- `pnpm build:component` builds the library into `component/dist`.
|
||||
- `pnpm build:component` builds the library into `component/dist`. It ends
|
||||
with `scripts/check-component-bundle.mjs`, which fails the build on what a
|
||||
host must not be handed: an asset inlined as a data URL, a file referenced
|
||||
by an absolute path, the standalone app's client store worker, or a module
|
||||
over its size budget.
|
||||
- `pnpm dev:component` serves a test host on `https://localhost:3001`: two
|
||||
calls side by side in resizable boxes, with host messages logged at the
|
||||
bottom. It uses the development backend, `public/config.json` if present,
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { afterEach, beforeEach, expect, test, vi } from "vitest";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { type MatrixClient, type Room } from "matrix-js-sdk";
|
||||
|
||||
import { mockEmitter, mockMatrixRoom } from "../src/utils/test";
|
||||
import { ElementCall } from "./index";
|
||||
|
||||
// The call itself is out of scope: what matters is what it is handed
|
||||
const callView = vi.hoisted(() => vi.fn());
|
||||
vi.mock("../src/room/CallView", () => ({
|
||||
CallView: (props: object): string => {
|
||||
callView(props);
|
||||
return "call";
|
||||
},
|
||||
}));
|
||||
|
||||
// Media devices need a browser jsdom does not have
|
||||
vi.mock("../src/state/AppViewModel", () => ({
|
||||
AppViewModel: class {
|
||||
public mediaDevices = {};
|
||||
public backgroundEffects = {};
|
||||
},
|
||||
}));
|
||||
|
||||
const roomId = "!room:example.org";
|
||||
let room: Room;
|
||||
|
||||
beforeEach(() => {
|
||||
// What the call's backend takes from the room
|
||||
room = mockMatrixRoom({
|
||||
roomId,
|
||||
getMembersWithMembership: vi.fn(),
|
||||
getLiveTimeline: vi.fn(),
|
||||
getVersion: vi.fn(),
|
||||
hasMembershipState: vi.fn(),
|
||||
_unstable_getStickyEvents: vi.fn(),
|
||||
getMxcAvatarUrl: vi.fn(),
|
||||
getJoinRule: vi.fn(),
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
callView.mockClear();
|
||||
});
|
||||
|
||||
test("calls in the room, leaving the session to the call", async () => {
|
||||
render(<ElementCall client={mockClient()} room={room} />);
|
||||
|
||||
await screen.findByText("call");
|
||||
const props = callView.mock.lastCall?.[0];
|
||||
expect(props).toMatchObject({ backend: { roomId } });
|
||||
expect(props).not.toHaveProperty("rtcSession");
|
||||
});
|
||||
|
||||
// No `matrixRTC`: the host's session manager is not ours to use
|
||||
function mockClient(): MatrixClient {
|
||||
return {
|
||||
...mockEmitter(),
|
||||
// What the call view's client is made from
|
||||
baseUrl: "https://matrix.example.org",
|
||||
getUserId: () => "@alice:example.org",
|
||||
getDeviceId: () => "DEVICE",
|
||||
getAccessToken: () => "token",
|
||||
getSyncState: () => null,
|
||||
getUser: () => null,
|
||||
getCrypto: () => undefined,
|
||||
sendEvent: vi.fn(),
|
||||
sendStateEvent: vi.fn(),
|
||||
_unstable_sendStickyEvent: vi.fn(),
|
||||
_unstable_sendStickyDelayedEvent: vi.fn(),
|
||||
cancelPendingEvent: vi.fn(),
|
||||
encryptAndSendToDevice: vi.fn(),
|
||||
redactEvent: vi.fn(),
|
||||
decryptEventIfNeeded: vi.fn(),
|
||||
setDisplayName: vi.fn(),
|
||||
setAvatarUrl: vi.fn(),
|
||||
uploadContent: vi.fn(),
|
||||
doesServerSupportUnstableFeature: vi.fn(),
|
||||
} as unknown as MatrixClient;
|
||||
}
|
||||
+36
-4
@@ -25,10 +25,12 @@ Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import type { Ref } from "react";
|
||||
import type { MatrixClient } from "matrix-js-sdk";
|
||||
import type { Room } from "matrix-js-sdk";
|
||||
|
||||
import type { UrlProperties } from "../src/UrlParams";
|
||||
import type { ElementCallHandle, ElementCallHostBridge } from "./host";
|
||||
import type { HostClientPart } from "./componentLocalJsClient";
|
||||
import type { SuppliedClient } from "../src/ClientContext";
|
||||
import {
|
||||
BackgroundStyle,
|
||||
configurationForIntent,
|
||||
@@ -69,14 +71,44 @@ export {
|
||||
export type ElementCallConfiguration = Partial<UrlConfiguration> &
|
||||
Partial<Pick<UrlProperties, "background">>;
|
||||
|
||||
/**
|
||||
* Everything Element Call reads of the host's room. Listed here rather than
|
||||
* taken from the call's backend, whose types a host cannot resolve.
|
||||
*
|
||||
* STOP GAP until the host passes an interface of our own instead of its `Room`.
|
||||
*/
|
||||
type HostRoomPart = Pick<
|
||||
Room,
|
||||
| "roomId"
|
||||
| "on"
|
||||
| "off"
|
||||
| "getMembersWithMembership"
|
||||
| "getLiveTimeline"
|
||||
| "getVersion"
|
||||
| "hasMembershipState"
|
||||
| "_unstable_getStickyEvents"
|
||||
| "name"
|
||||
| "getMxcAvatarUrl"
|
||||
| "getJoinRule"
|
||||
| "relations"
|
||||
>;
|
||||
|
||||
export interface ElementCallProps {
|
||||
/**
|
||||
* The client to place the call with. Element Call does not authenticate
|
||||
* anyone or manage a session of its own; this one is the host's.
|
||||
*
|
||||
* Typed with the host's own js-sdk, as only what Element Call calls on it: by
|
||||
* the call's backend, and by the rest of the call through its context. A
|
||||
* js-sdk too old for Element Call fails to type-check rather than failing
|
||||
* once a call is shown.
|
||||
*/
|
||||
client: MatrixClient;
|
||||
/** The room to call in. The host's client must already know about it. */
|
||||
roomId: string;
|
||||
client: HostClientPart & SuppliedClient;
|
||||
/**
|
||||
* The room to call in, from the host's client. Typed like `client`: only what
|
||||
* Element Call reads of it.
|
||||
*/
|
||||
room: HostRoomPart;
|
||||
/**
|
||||
* What the user asked for — whether they started the call or joined one that
|
||||
* was already running, and whether it is a call in a group or a DM. Element
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { afterEach, expect, test, vi } from "vitest";
|
||||
import {
|
||||
ClientEvent,
|
||||
ConnectionError,
|
||||
EventType,
|
||||
type MatrixClient,
|
||||
SyncState,
|
||||
} from "matrix-js-sdk";
|
||||
|
||||
import { createComponentLocalJsClient } from "./componentLocalJsClient";
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
test("reads the host's live state from the host's client", () => {
|
||||
const host = mockHost();
|
||||
const client = createComponentLocalJsClient(host);
|
||||
const listener = (): void => {};
|
||||
|
||||
expect(client.getSyncState()).toBe(SyncState.Syncing);
|
||||
client.on(ClientEvent.Sync, listener);
|
||||
client.off(ClientEvent.Sync, listener);
|
||||
client.getUser("@bob:example.org");
|
||||
client.getCrypto();
|
||||
|
||||
expect(host.getSyncState).toHaveBeenCalledOnce();
|
||||
expect(host.on).toHaveBeenCalledWith(ClientEvent.Sync, listener);
|
||||
expect(host.off).toHaveBeenCalledWith(ClientEvent.Sync, listener);
|
||||
expect(host.getUser).toHaveBeenCalledWith("@bob:example.org");
|
||||
expect(host.getCrypto).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
test("sends the RTC session's encrypted events with the host's crypto", async () => {
|
||||
const host = mockHost();
|
||||
const client = createComponentLocalJsClient(host);
|
||||
|
||||
await client._unstable_sendStickyEvent(
|
||||
"!room:example.org",
|
||||
1000,
|
||||
null,
|
||||
EventType.RTCMembership,
|
||||
{ slot_id: "m.call#ROOM", msc4354_sticky_key: "key" },
|
||||
);
|
||||
await client.encryptAndSendToDevice("m.room.encrypted", [], {});
|
||||
|
||||
expect(host._unstable_sendStickyEvent).toHaveBeenCalledOnce();
|
||||
expect(host.encryptAndSendToDevice).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
test.each([
|
||||
"sendEvent",
|
||||
"redactEvent",
|
||||
"decryptEventIfNeeded",
|
||||
"_unstable_sendStickyEvent",
|
||||
"_unstable_sendStickyDelayedEvent",
|
||||
"encryptAndSendToDevice",
|
||||
"sendStateEvent",
|
||||
"setDisplayName",
|
||||
"setAvatarUrl",
|
||||
"uploadContent",
|
||||
"doesServerSupportUnstableFeature",
|
||||
] as const)(
|
||||
"the host's %s fails with errors our js-sdk recognises",
|
||||
async (method) => {
|
||||
const host = mockHost();
|
||||
// A ConnectionError of the host's own js-sdk: not ours, but shaped like it
|
||||
const hostError = Object.assign(new Error("fetch failed"), {
|
||||
name: "ConnectionError",
|
||||
});
|
||||
vi.mocked(host[method]).mockRejectedValue(hostError);
|
||||
const client = createComponentLocalJsClient(host);
|
||||
|
||||
await expect(
|
||||
(client[method] as () => Promise<unknown>)(),
|
||||
).rejects.toBeInstanceOf(ConnectionError);
|
||||
},
|
||||
);
|
||||
|
||||
test("takes its credentials from the host", () => {
|
||||
const client = createComponentLocalJsClient(mockHost());
|
||||
|
||||
expect(client.getUserId()).toBe("@alice:example.org");
|
||||
expect(client.getDeviceId()).toBe("DEVICE");
|
||||
expect(client.getDomain()).toBe("example.org");
|
||||
expect(client.baseUrl).toBe("https://matrix.example.org");
|
||||
});
|
||||
|
||||
test("makes requests with whichever token the host holds now", async () => {
|
||||
const fetch = vi.fn(
|
||||
async () =>
|
||||
await Promise.resolve(
|
||||
new Response(JSON.stringify({ access_token: "openid" }), {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
}),
|
||||
),
|
||||
);
|
||||
vi.stubGlobal("fetch", fetch);
|
||||
const host = mockHost();
|
||||
const client = createComponentLocalJsClient(host);
|
||||
// As if the host had refreshed its token after we were created
|
||||
host.token = "refreshed";
|
||||
|
||||
await client.getOpenIdToken();
|
||||
|
||||
expect(fetch).toHaveBeenCalledOnce();
|
||||
const [url, init] = fetch.mock.calls[0] as unknown as [URL, RequestInit];
|
||||
expect(url.toString()).toBe(
|
||||
"https://matrix.example.org/_matrix/client/v3/user/%40alice%3Aexample.org/openid/request_token",
|
||||
);
|
||||
expect(new Headers(init.headers).get("Authorization")).toBe(
|
||||
"Bearer refreshed",
|
||||
);
|
||||
});
|
||||
|
||||
function mockHost(): MatrixClient & { token: string } {
|
||||
const host = {
|
||||
token: "first",
|
||||
baseUrl: "https://matrix.example.org",
|
||||
getUserId: (): string => "@alice:example.org",
|
||||
getDeviceId: (): string => "DEVICE",
|
||||
getAccessToken: (): string => host.token,
|
||||
getSyncState: vi.fn(() => SyncState.Syncing),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
getUser: vi.fn(() => null),
|
||||
getCrypto: vi.fn(() => undefined),
|
||||
sendEvent: vi.fn(),
|
||||
sendStateEvent: vi.fn(),
|
||||
_unstable_sendStickyEvent: vi.fn(),
|
||||
_unstable_sendStickyDelayedEvent: vi.fn(),
|
||||
encryptAndSendToDevice: vi.fn(),
|
||||
redactEvent: vi.fn(),
|
||||
decryptEventIfNeeded: vi.fn(),
|
||||
setDisplayName: vi.fn(),
|
||||
setAvatarUrl: vi.fn(),
|
||||
uploadContent: vi.fn(),
|
||||
doesServerSupportUnstableFeature: vi.fn(),
|
||||
};
|
||||
return host as unknown as MatrixClient & { token: string };
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { createClient, type MatrixClient } from "matrix-js-sdk";
|
||||
import type { createCallMatrixBackend } from "../src/CallMatrixBackend";
|
||||
import { adoptingHostErrors } from "./hostErrors";
|
||||
|
||||
/**
|
||||
* Everything the component calls on the host's client. Part of the public
|
||||
* `client` prop (see api.ts), so that a host whose js-sdk lacks one of these
|
||||
* fails to type-check.
|
||||
*
|
||||
* STOP GAP until the host passes an interface of our own instead of its
|
||||
* `MatrixClient`.
|
||||
*/
|
||||
export type HostClientPart = Pick<
|
||||
MatrixClient,
|
||||
| "baseUrl"
|
||||
| "getUserId"
|
||||
| "getDeviceId"
|
||||
| "getAccessToken"
|
||||
| "getSyncState"
|
||||
| "on"
|
||||
| "off"
|
||||
| "getUser"
|
||||
| "getCrypto"
|
||||
| "sendEvent"
|
||||
| "redactEvent"
|
||||
| "decryptEventIfNeeded"
|
||||
| "_unstable_sendStickyEvent"
|
||||
| "_unstable_sendStickyDelayedEvent"
|
||||
| "encryptAndSendToDevice"
|
||||
| "sendStateEvent"
|
||||
| "setDisplayName"
|
||||
| "setAvatarUrl"
|
||||
| "uploadContent"
|
||||
| "doesServerSupportUnstableFeature"
|
||||
>;
|
||||
|
||||
/**
|
||||
* The client for Element Call in Component mode.
|
||||
* We do get the full host client but we dont want to use it as it
|
||||
* might use older versions of methods were we expect changes. (f.ex. getLivekitToken)
|
||||
* We really want the expected implementation to not get runtime errors.
|
||||
*
|
||||
* This creates a new client that does use the hosts token and "stable"
|
||||
* methods but uses the ElementCall Components js-sdk's client impl for anything else.
|
||||
*/
|
||||
export function createComponentLocalJsClient(
|
||||
host: HostClientPart,
|
||||
): Parameters<typeof createCallMatrixBackend>[0] {
|
||||
const own = createClient({
|
||||
baseUrl: host.baseUrl,
|
||||
userId: host.getUserId() ?? undefined,
|
||||
deviceId: host.getDeviceId() ?? undefined,
|
||||
accessToken: host.getAccessToken() ?? undefined,
|
||||
// The host refreshes its token without telling us, so each request takes
|
||||
// whichever token the host holds now
|
||||
fetchFn: async (input, init) => {
|
||||
const headers = new Headers(init?.headers);
|
||||
const token = host.getAccessToken();
|
||||
if (token !== null) headers.set("Authorization", `Bearer ${token}`);
|
||||
return globalThis.fetch(input, { ...init, headers });
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
// Own has no sync loop: `syncApi?.getSyncState() ?? null` is always null
|
||||
getSyncState: host.getSyncState.bind(host),
|
||||
// Only the syncing host emits `Sync`, `ToDeviceEvent` and `Decrypted`
|
||||
on: host.on.bind(host),
|
||||
// The same emitter as `on`
|
||||
off: host.off.bind(host),
|
||||
// `this.store.getUser`: own's store is empty, only the host's sync fills it
|
||||
getUser: host.getUser.bind(host),
|
||||
// Own never inits crypto, and a second one on the device would corrupt it
|
||||
getCrypto: host.getCrypto.bind(host),
|
||||
// Every one of the host's methods that can fail rejects with our error
|
||||
// classes, which ours can recognise (see hostErrors.ts)
|
||||
|
||||
// Own has no rooms: `encryptEventIfNeeded`'s `if (!room) return` skips E2EE
|
||||
sendEvent: adoptingHostErrors(host.sendEvent.bind(host)),
|
||||
// Not encrypted, but the local echo goes to `getRoom()`: only the host's
|
||||
redactEvent: adoptingHostErrors(host.redactEvent.bind(host)),
|
||||
// `attemptDecryption` only runs `if (this.getCrypto())`: a no-op on own
|
||||
decryptEventIfNeeded: adoptingHostErrors(
|
||||
host.decryptEventIfNeeded.bind(host),
|
||||
),
|
||||
// Like `sendEvent`: on own, `if (!room) return` sends it in plaintext
|
||||
_unstable_sendStickyEvent: adoptingHostErrors(
|
||||
host._unstable_sendStickyEvent.bind(host),
|
||||
),
|
||||
// Like `sendEvent`: delayed, but still `encryptEventIfNeeded(event, room)`
|
||||
_unstable_sendStickyDelayedEvent: adoptingHostErrors(
|
||||
host._unstable_sendStickyDelayedEvent.bind(host),
|
||||
),
|
||||
// `if (!this.cryptoBackend) throw`: own has no crypto
|
||||
encryptAndSendToDevice: adoptingHostErrors(
|
||||
host.encryptAndSendToDevice.bind(host),
|
||||
),
|
||||
|
||||
// Static: own was created with the host's user id
|
||||
getUserId: own.getUserId.bind(own),
|
||||
// Static: own was created with the host's device id
|
||||
getDeviceId: own.getDeviceId.bind(own),
|
||||
// Static: derived from the user id
|
||||
getDomain: own.getDomain.bind(own),
|
||||
// Static: own was created with the host's base URL
|
||||
baseUrl: own.baseUrl,
|
||||
// MSC4143 stable or unstable prefix, picked by /versions: ours knows both
|
||||
getRTCTransports: own.getRTCTransports.bind(own),
|
||||
// Plain HTTP with the copied credentials, like the other LiveKit auth
|
||||
getOpenIdToken: own.getOpenIdToken.bind(own),
|
||||
// MSC4195 stable or `io.element.msc4195` prefix: an older host may lack it
|
||||
getLivekitToken: own.getLivekitToken.bind(own),
|
||||
// MSC4195, like `getLivekitToken`: an older host may lack it
|
||||
delegateDelayedLeave: own.delegateDelayedLeave.bind(own),
|
||||
// Plain HTTP into own's cache, which `getCachedCapabilities` reads
|
||||
fetchCapabilities: own.fetchCapabilities.bind(own),
|
||||
// Has to be the client whose cache `fetchCapabilities` filled
|
||||
getCachedCapabilities: own.getCachedCapabilities.bind(own),
|
||||
// Straight to `scheduleDelayedEvent`: no room, no crypto, plain HTTP
|
||||
_unstable_sendDelayedStateEvent:
|
||||
own._unstable_sendDelayedStateEvent.bind(own),
|
||||
// Plain POST `/delayed_events/{id}/cancel`; newer API an old host may lack
|
||||
_unstable_cancelScheduledDelayedEvent:
|
||||
own._unstable_cancelScheduledDelayedEvent.bind(own),
|
||||
// Plain POST by the server's delay id: restarts the host's sticky leave too
|
||||
_unstable_restartScheduledDelayedEvent:
|
||||
own._unstable_restartScheduledDelayedEvent.bind(own),
|
||||
// Plain POST `/delayed_events/{id}/send`; newer API an old host may lack
|
||||
_unstable_sendScheduledDelayedEvent:
|
||||
own._unstable_sendScheduledDelayedEvent.bind(own),
|
||||
|
||||
// Plain HTTP, either client works; a stable API, so the host's
|
||||
sendStateEvent: adoptingHostErrors(host.sendStateEvent.bind(host)),
|
||||
// Updates the `User` in the host's store, which `useProfile` listens to
|
||||
setDisplayName: adoptingHostErrors(host.setDisplayName.bind(host)),
|
||||
// Like `setDisplayName`: updates the `User` in the host's store
|
||||
setAvatarUrl: adoptingHostErrors(host.setAvatarUrl.bind(host)),
|
||||
// Plain HTTP, either client works; a stable API, so the host's
|
||||
uploadContent: adoptingHostErrors(host.uploadContent.bind(host)),
|
||||
// Reads the host's /versions, which it has already fetched
|
||||
doesServerSupportUnstableFeature: adoptingHostErrors(
|
||||
host.doesServerSupportUnstableFeature.bind(host),
|
||||
),
|
||||
};
|
||||
}
|
||||
@@ -99,6 +99,7 @@ const Pane: FC<{
|
||||
log: (pane: string, message: string) => void;
|
||||
}> = ({ session, roomId, theme, language, log }): ReactNode => {
|
||||
const [mounted, setMounted] = useState(true);
|
||||
const room = session.client.getRoom(roomId);
|
||||
|
||||
const bridge = useMemo(
|
||||
() =>
|
||||
@@ -159,11 +160,12 @@ const Pane: FC<{
|
||||
{/* Resizable, because how Element Call copes with the size it is given is
|
||||
one of the things we cannot find out from the standalone app */}
|
||||
<div className={styles.paneCall} data-testid="call-container">
|
||||
{mounted && (
|
||||
{mounted && room === null && <p>This client does not know {roomId}</p>}
|
||||
{mounted && room !== null && (
|
||||
<ElementCall
|
||||
ref={handle}
|
||||
client={session.client}
|
||||
roomId={roomId}
|
||||
room={room}
|
||||
hostBridge={bridge}
|
||||
theme={theme}
|
||||
language={language}
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { expect, test } from "vitest";
|
||||
import {
|
||||
ConnectionError,
|
||||
HTTPError,
|
||||
MatrixError,
|
||||
UnsupportedDelayedEventsEndpointError,
|
||||
UnsupportedStickyEventsEndpointError,
|
||||
} from "matrix-js-sdk";
|
||||
|
||||
import { adoptHostError, adoptingHostErrors } from "./hostErrors";
|
||||
|
||||
test("a rate limit from the host is one of ours, retry delay included", () => {
|
||||
const error = adoptHostError(
|
||||
new HostMatrixError(
|
||||
{ errcode: "M_LIMIT_EXCEEDED", error: "Too many requests" },
|
||||
429,
|
||||
"https://matrix.example.org/_matrix/client/v3/rooms/x/send",
|
||||
new Headers({ "Retry-After": "3" }),
|
||||
),
|
||||
);
|
||||
|
||||
expect(error).toBeInstanceOf(MatrixError);
|
||||
const matrixError = error as MatrixError;
|
||||
expect(matrixError.errcode).toBe("M_LIMIT_EXCEEDED");
|
||||
expect(matrixError.data).toEqual({
|
||||
errcode: "M_LIMIT_EXCEEDED",
|
||||
error: "Too many requests",
|
||||
});
|
||||
expect(matrixError.httpStatus).toBe(429);
|
||||
expect(matrixError.url).toBe(
|
||||
"https://matrix.example.org/_matrix/client/v3/rooms/x/send",
|
||||
);
|
||||
expect(matrixError.isRateLimitError()).toBe(true);
|
||||
expect(matrixError.getRetryAfterMs()).toBe(3000);
|
||||
});
|
||||
|
||||
test("an HTTP error without a Matrix body from the host is one of ours", () => {
|
||||
const error = adoptHostError(new HostHTTPError("Conflict", 409));
|
||||
|
||||
expect(error).toBeInstanceOf(HTTPError);
|
||||
expect(error).not.toBeInstanceOf(MatrixError);
|
||||
expect((error as HTTPError).httpStatus).toBe(409);
|
||||
expect((error as HTTPError).message).toBe("Conflict");
|
||||
});
|
||||
|
||||
test("a connection failure from the host is one of ours", () => {
|
||||
const error = adoptHostError(new HostConnectionError("fetch failed"));
|
||||
|
||||
expect(error).toBeInstanceOf(ConnectionError);
|
||||
expect((error as ConnectionError).message).toBe("fetch failed");
|
||||
});
|
||||
|
||||
test("missing sticky and delayed event endpoints on the host's server are ours", () => {
|
||||
const sticky = adoptHostError(
|
||||
new HostUnsupportedEndpointError(
|
||||
"UnsupportedStickyEventsEndpointError",
|
||||
"sendStickyEvent",
|
||||
),
|
||||
);
|
||||
const delayed = adoptHostError(
|
||||
new HostUnsupportedEndpointError(
|
||||
"UnsupportedDelayedEventsEndpointError",
|
||||
"sendDelayedStateEvent",
|
||||
),
|
||||
);
|
||||
|
||||
expect(sticky).toBeInstanceOf(UnsupportedStickyEventsEndpointError);
|
||||
expect((sticky as UnsupportedStickyEventsEndpointError).clientEndpoint).toBe(
|
||||
"sendStickyEvent",
|
||||
);
|
||||
expect(delayed).toBeInstanceOf(UnsupportedDelayedEventsEndpointError);
|
||||
expect(
|
||||
(delayed as UnsupportedDelayedEventsEndpointError).clientEndpoint,
|
||||
).toBe("sendDelayedStateEvent");
|
||||
});
|
||||
|
||||
test("keeps where the host's error was thrown", () => {
|
||||
const original = new HostConnectionError("fetch failed");
|
||||
|
||||
expect((adoptHostError(original) as Error).stack).toBe(original.stack);
|
||||
});
|
||||
|
||||
test("leaves our own errors and everything else as they are", () => {
|
||||
const own = new MatrixError({ errcode: "M_FORBIDDEN" }, 403);
|
||||
const refusedByWidgetHost = new Error("Action not allowed");
|
||||
const aborted = new DOMException("Aborted", "AbortError");
|
||||
|
||||
expect(adoptHostError(own)).toBe(own);
|
||||
expect(adoptHostError(refusedByWidgetHost)).toBe(refusedByWidgetHost);
|
||||
expect(adoptHostError(aborted)).toBe(aborted);
|
||||
expect(adoptHostError("not an error")).toBe("not an error");
|
||||
});
|
||||
|
||||
test("a wrapped host method rejects with ours and resolves as it did", async () => {
|
||||
const failing = adoptingHostErrors(async (): Promise<string> =>
|
||||
Promise.reject(new HostConnectionError("fetch failed")),
|
||||
);
|
||||
const succeeding = adoptingHostErrors(
|
||||
async (a: number, b: number): Promise<number> => Promise.resolve(a + b),
|
||||
);
|
||||
|
||||
await expect(failing()).rejects.toBeInstanceOf(ConnectionError);
|
||||
await expect(succeeding(1, 2)).resolves.toBe(3);
|
||||
});
|
||||
|
||||
// Lookalikes of the host js-sdk's classes: the same shape, but not ours
|
||||
|
||||
class HostHTTPError extends Error {
|
||||
public constructor(
|
||||
message: string,
|
||||
public readonly httpStatus?: number,
|
||||
public readonly httpHeaders?: Headers,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public isRateLimitError(): boolean {
|
||||
return this.httpStatus === 429;
|
||||
}
|
||||
}
|
||||
|
||||
class HostMatrixError extends HostHTTPError {
|
||||
public readonly errcode?: string;
|
||||
|
||||
public constructor(
|
||||
public data: { errcode?: string; error?: string },
|
||||
httpStatus?: number,
|
||||
public url?: string,
|
||||
httpHeaders?: Headers,
|
||||
) {
|
||||
super(`MatrixError: ${data.error}`, httpStatus, httpHeaders);
|
||||
this.errcode = data.errcode;
|
||||
this.name = data.errcode ?? "Unknown error code";
|
||||
}
|
||||
}
|
||||
|
||||
class HostConnectionError extends Error {
|
||||
public get name(): string {
|
||||
return "ConnectionError";
|
||||
}
|
||||
}
|
||||
|
||||
class HostUnsupportedEndpointError extends Error {
|
||||
public constructor(
|
||||
name: string,
|
||||
public clientEndpoint: string,
|
||||
) {
|
||||
super(`Server does not support ${clientEndpoint}`);
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import {
|
||||
ConnectionError,
|
||||
HTTPError,
|
||||
MatrixError,
|
||||
UnsupportedDelayedEventsEndpointError,
|
||||
UnsupportedStickyEventsEndpointError,
|
||||
} from "matrix-js-sdk";
|
||||
|
||||
/**
|
||||
* Wraps a method of the host's client so that what it rejects with is
|
||||
* {@link adoptHostError adopted}.
|
||||
*/
|
||||
export function adoptingHostErrors<
|
||||
F extends (...args: never[]) => Promise<unknown>,
|
||||
>(call: F): F {
|
||||
const adopting = async (
|
||||
...args: Parameters<F>
|
||||
): Promise<Awaited<ReturnType<F>>> => {
|
||||
try {
|
||||
return (await call(...args)) as Awaited<ReturnType<F>>;
|
||||
} catch (e) {
|
||||
throw adoptHostError(e);
|
||||
}
|
||||
};
|
||||
return adopting as F;
|
||||
}
|
||||
|
||||
/**
|
||||
* The same error as one of our own js-sdk's classes, where it is one of the
|
||||
* host's.
|
||||
*
|
||||
* The host's client is a different copy of the js-sdk, and ours (the MatrixRTC
|
||||
* session above all) tells rate limits, network failures and missing endpoints
|
||||
* apart with `instanceof`, which never matches the host's classes.
|
||||
*/
|
||||
export function adoptHostError(error: unknown): unknown {
|
||||
if (!(error instanceof Error) || isOwn(error)) return error;
|
||||
const adopted = adopt(error);
|
||||
if (adopted === undefined) return error;
|
||||
adopted.stack = error.stack;
|
||||
return adopted;
|
||||
}
|
||||
|
||||
function isOwn(error: Error): boolean {
|
||||
return (
|
||||
error instanceof HTTPError ||
|
||||
error instanceof ConnectionError ||
|
||||
error instanceof UnsupportedStickyEventsEndpointError ||
|
||||
error instanceof UnsupportedDelayedEventsEndpointError
|
||||
);
|
||||
}
|
||||
|
||||
/** Recognised by shape, since the host's classes cannot be named. */
|
||||
function adopt(error: Error & Partial<HostErrorFields>): Error | undefined {
|
||||
switch (error.name) {
|
||||
case "ConnectionError":
|
||||
return new ConnectionError(error.message);
|
||||
case "UnsupportedStickyEventsEndpointError":
|
||||
return new UnsupportedStickyEventsEndpointError(
|
||||
error.message,
|
||||
error.clientEndpoint as UnsupportedStickyEventsEndpointError["clientEndpoint"],
|
||||
{ cause: error.cause },
|
||||
);
|
||||
case "UnsupportedDelayedEventsEndpointError":
|
||||
return new UnsupportedDelayedEventsEndpointError(
|
||||
error.message,
|
||||
error.clientEndpoint as UnsupportedDelayedEventsEndpointError["clientEndpoint"],
|
||||
);
|
||||
}
|
||||
if (typeof error.isRateLimitError !== "function") return undefined;
|
||||
if (error.data !== undefined)
|
||||
return new MatrixError(
|
||||
error.data,
|
||||
error.httpStatus,
|
||||
error.url,
|
||||
error.event,
|
||||
error.httpHeaders,
|
||||
);
|
||||
return new HTTPError(error.message, error.httpStatus, error.httpHeaders);
|
||||
}
|
||||
|
||||
type HostErrorFields = Pick<
|
||||
MatrixError,
|
||||
"data" | "httpStatus" | "httpHeaders" | "url" | "event" | "isRateLimitError"
|
||||
> & { clientEndpoint: string };
|
||||
+13
-13
@@ -11,7 +11,7 @@ Please see LICENSE in the repository root for full details.
|
||||
* Element Call as a React component, for an application that wants to show a
|
||||
* call inside itself rather than in an iframe.
|
||||
*
|
||||
* The host supplies the client and says which room to call in; Element Call
|
||||
* The host supplies the client and the room to call in; Element Call
|
||||
* supplies the call. Everything it would otherwise take from the page it is on
|
||||
* — the URL, the document body, a Matrix session of its own — comes from the
|
||||
* host instead, or is confined to the container it is mounted in.
|
||||
@@ -84,7 +84,9 @@ import styles from "./ElementCall.module.css";
|
||||
import { useComponentHostBridge } from "./host";
|
||||
import { CallPortalRoot } from "./CallPortalRoot";
|
||||
import { type ElementCallProps } from "./api";
|
||||
import { createComponentLocalJsClient } from "./componentLocalJsClient";
|
||||
import { supportedLanguages, translationsBackend } from "./localization";
|
||||
import { createCallMatrixBackend } from "../src/CallMatrixBackend";
|
||||
|
||||
// The languages Element Call can be shown in
|
||||
export { supportedLanguages } from "./localization";
|
||||
@@ -148,7 +150,7 @@ const Decoration: FC<{ children: JSX.Element }> = ({ children }) => {
|
||||
|
||||
export const ElementCall: FC<ElementCallProps> = ({
|
||||
client,
|
||||
roomId,
|
||||
room,
|
||||
intent = UserIntent.JoinExistingCall,
|
||||
config,
|
||||
hostBridge: suppliedHostBridge,
|
||||
@@ -179,6 +181,7 @@ export const ElementCall: FC<ElementCallProps> = ({
|
||||
// to be stable for as long as its contents are. A host writing `config`
|
||||
// inline would otherwise tear the call down on every render.
|
||||
const stableConfig = useStableValue(config);
|
||||
const { roomId } = room;
|
||||
const params = useMemo(
|
||||
(): UrlParams => ({
|
||||
...componentProperties,
|
||||
@@ -204,23 +207,17 @@ export const ElementCall: FC<ElementCallProps> = ({
|
||||
};
|
||||
}, [controlledAudioDevices, callIntent]);
|
||||
|
||||
const room = client.getRoom(roomId);
|
||||
const rtcSession = useMemo(
|
||||
() => (room === null ? null : client.matrixRTC.getRoomSession(room)),
|
||||
const backend = useMemo(
|
||||
() => createCallMatrixBackend(createComponentLocalJsClient(client), room),
|
||||
[client, room],
|
||||
);
|
||||
|
||||
if (rtcSession === null)
|
||||
logger.error(
|
||||
`Element Call was asked to call in ${roomId}, which its host's client does not know about`,
|
||||
);
|
||||
|
||||
// Everything the call needs is in hand once these exist, and the first
|
||||
// render with them is where the call itself appears: the moment the host
|
||||
// is told that Element Call has loaded, as the widget tells its client once
|
||||
// its own initialisation is over. Once per mount, however often the pieces
|
||||
// are later swapped out.
|
||||
const ready = container !== null && rtcSession !== null && vm !== null;
|
||||
const ready = container !== null && vm !== null;
|
||||
const announcedLoaded = useRef(false);
|
||||
useEffect(() => {
|
||||
if (!ready || announcedLoaded.current) return;
|
||||
@@ -250,14 +247,17 @@ export const ElementCall: FC<ElementCallProps> = ({
|
||||
>
|
||||
<Decoration>
|
||||
<TooltipProvider>
|
||||
{/* The host's own client: what reads it through
|
||||
the context (avatars, the encryption system,
|
||||
rageshakes, the disconnected banner) uses only its
|
||||
stable methods. */}
|
||||
<ClientProvider client={client}>
|
||||
<MediaDevicesContext value={vm.mediaDevices}>
|
||||
<BackgroundEffectsProvider
|
||||
effects={vm.backgroundEffects}
|
||||
>
|
||||
<CallView
|
||||
client={client}
|
||||
rtcSession={rtcSession}
|
||||
backend={backend}
|
||||
isPasswordlessUser={false}
|
||||
confineToRoom={params.confineToRoom}
|
||||
preload={params.preload}
|
||||
|
||||
@@ -42,7 +42,6 @@
|
||||
"peerDependencies": {
|
||||
"@vector-im/compound-design-tokens": "^11.0.0",
|
||||
"@vector-im/compound-web": "^10.3.1",
|
||||
"matrix-js-sdk": "*",
|
||||
"react": "^19",
|
||||
"react-dom": "^19"
|
||||
}
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
{
|
||||
"default_server_config": {
|
||||
"m.homeserver": {
|
||||
"base_url": "https://call-unstable.ems.host",
|
||||
"server_name": "call-unstable.ems.host"
|
||||
}
|
||||
},
|
||||
"ssla": "https://static.element.io/legal/element-software-and-services-license-agreement-uk-1.pdf",
|
||||
"matrix_rtc_session": {
|
||||
"membership_event_expiry_ms": 180000000,
|
||||
"network_error_retry_ms": 100
|
||||
}
|
||||
}
|
||||
@@ -63,7 +63,7 @@ services:
|
||||
- ecbackend
|
||||
|
||||
livekit:
|
||||
image: livekit/livekit-server:v1.13.4
|
||||
image: livekit/livekit-server:v1.13.11
|
||||
pull_policy: always
|
||||
hostname: livekit-sfu
|
||||
command: --dev --config /etc/livekit.yaml
|
||||
@@ -86,7 +86,7 @@ services:
|
||||
- ecbackend
|
||||
|
||||
livekit-1:
|
||||
image: livekit/livekit-server:v1.13.4
|
||||
image: livekit/livekit-server:v1.13.11
|
||||
pull_policy: always
|
||||
hostname: livekit-sfu-1
|
||||
command: --dev --config /etc/livekit.yaml
|
||||
|
||||
@@ -19,10 +19,10 @@ services:
|
||||
- ./backend/playwright_homeserver-othersite.yaml:/data/cfg/homeserver.yaml:Z
|
||||
element-web:
|
||||
# Pin to a SHA so that upstream cannot break our tests. Renovate handles regular updates.
|
||||
image: ghcr.io/element-hq/element-web:develop@sha256:b355371adc13161afc7e3c436b533f99e26bd6482e9b53e9572501821f8ddb21
|
||||
image: ghcr.io/element-hq/element-web:develop@sha256:58b673f867f78fe83c08f2b688b254e34625ebfcebdc5eff84bfdf407445e88e
|
||||
element-web-1:
|
||||
# Pin to a SHA so that upstream cannot break our tests. Renovate handles regular updates.
|
||||
image: ghcr.io/element-hq/element-web:develop@sha256:b355371adc13161afc7e3c436b533f99e26bd6482e9b53e9572501821f8ddb21
|
||||
image: ghcr.io/element-hq/element-web:develop@sha256:58b673f867f78fe83c08f2b688b254e34625ebfcebdc5eff84bfdf407445e88e
|
||||
volumes:
|
||||
# The other site opens the embedded package under test in place of the
|
||||
# copy its image bundles (the first site opens the dev server's app.
|
||||
|
||||
+39
-12
@@ -4,12 +4,17 @@
|
||||
|
||||
- Call logic lives in `src/state/`. A component that derives call state is
|
||||
misplaced logic.
|
||||
- Composing behaviors: a factory taking `(scope, ...deps$)`, returning named
|
||||
behaviors plus callbacks. Copy `src/state/LayoutSwitchViewModel.ts`. Prefer this
|
||||
for anything new.
|
||||
- Owning a resource: a class taking the scope in its constructor — `MediaDevices`,
|
||||
`MuteStates`, `TileStore`, `Publisher`, `Connection`. Both styles are current;
|
||||
don't convert one to the other in passing.
|
||||
- New state is a `create<Thing>$(scope, …)` factory returning an interface of
|
||||
named behaviors plus callbacks — `createCallViewModel$`,
|
||||
`createCallNotificationLifecycle$`, the SDK's `createLocalMembership$`. Prefer
|
||||
it to a class for anything new, including something that owns a resource.
|
||||
- Inside the factory, mutable state is a local `BehaviorSubject` exposed through
|
||||
`scope.behavior(…)`, a resource is released in `scope.onEnd`, and the returned
|
||||
object comes before the helpers it calls, which are `function` declarations
|
||||
beneath it.
|
||||
- Older resource owners are classes taking the scope in their constructor —
|
||||
`MediaDevices`, `MuteStates`, `TileStore`, `Publisher`, `Connection`. Convert
|
||||
one only when that is the task, never in passing.
|
||||
- A factory's required parameters are what the thing is made of: no sensible
|
||||
default. Several of them go in a props interface, so each can carry a doc
|
||||
comment. Its trailing `options` bag is how the host wants it to behave: every
|
||||
@@ -73,6 +78,27 @@ and widget behaviour.
|
||||
`AudioOutput`. Intent presets set it on non-desktop; standalone leaves it off.
|
||||
- URL params are a published contract: change one, update `docs/url_params.md`.
|
||||
|
||||
## Element Call on the SDK
|
||||
|
||||
`sdk/` is `@element-hq/matrixrtc-sdk`; its design is
|
||||
[`sdk/SdkArchitecture.md`](../../sdk/SdkArchitecture.md). Read it before touching
|
||||
`sdk/`.
|
||||
|
||||
- MatrixRTC and media logic lives in `sdk/`; UI, configuration, settings and host
|
||||
concerns stay in `src/`. The dependency points Element Call → SDK, never back:
|
||||
`element-call/sdk-import-boundary` rejects `src/`, React, i18n or Compound
|
||||
under `sdk/`.
|
||||
- The SDK assumes no host — no widget, URL params or config file. It is designed for any
|
||||
matrix rtc application/type. What only makes sense for a call stays in `CallViewModel`;
|
||||
the SDK doc lists it under [Call-specific things kept out of the client](../../sdk/SdkArchitecture.md#call-specific-things-kept-out-of-the-client).
|
||||
- Element Call imports the SDK from `@element-hq/matrixrtc-sdk` only — never a
|
||||
path into `sdk/src/`, never a copy of what the SDK already does. Missing
|
||||
something? Extend the SDK's API.
|
||||
- Every `api.ts` is a contract: `sdk/src/api.ts`, `sdk/src/media-api.ts`, the
|
||||
internal `sdk/src/media-backend/api.ts` and `component/api.ts`. A PR that
|
||||
changes one lists the change in its body.
|
||||
- SDK and Element Call changes go in separate commits.
|
||||
|
||||
## Build targets
|
||||
|
||||
Code that builds in only one is a bug.
|
||||
@@ -82,12 +108,13 @@ Code that builds in only one is a bug.
|
||||
- `build:sdk` — `@element-hq/matrixrtc-sdk`, sources in `sdk/`, entry `sdk/index.ts`.
|
||||
Packaged exactly like the component (own pnpm project, run pnpm from the repo
|
||||
root, types from `sdk/tsconfig.build.json`, externals checked by
|
||||
`pnpm lint:externals`). Interface only so far; the design is `sdk-plan.md`.
|
||||
- `build:sdk-target-based-on-call-view-model` — the SDK demo that predates the
|
||||
package, one bundle of the `CallViewModel`; entry
|
||||
`sdk-target-based-on-call-view-model/main.ts`. CI's `sdk` package
|
||||
(`build:sdk:production` / `build:sdk:development`, the Netlify `-sdk` preview)
|
||||
is still this bundle, not `build:sdk`.
|
||||
`pnpm lint:externals`). Minified by default (`build:sdk:production`),
|
||||
unminified with `build:sdk:development`; source maps in both.
|
||||
- `build:widget-rtc-sdk` — a single bundle for widget pages that wraps the
|
||||
`sdk/` package and the widget API, nothing of `src/`; entry
|
||||
`widget-rtc-sdk/main.ts`. CI builds it as the `widget-rtc-sdk` package
|
||||
(`build:widget-rtc-sdk:production` / `:development`) and deploys it as the
|
||||
`pr<N>-widget-rtc-sdk` Netlify preview.
|
||||
- `build:component` — `@element-hq/element-call-component`, sources in `component/`
|
||||
(its own pnpm project; run pnpm from the repo root). Host API is in the README;
|
||||
`pnpm lint:externals` rejects an import of a `react` / `react-dom` /
|
||||
|
||||
@@ -21,6 +21,18 @@ rejected and why — never add one silently. Extend or parameterise before forki
|
||||
and extract shared logic into a hook both callers use before copying it; if you
|
||||
copy, the PR says so.
|
||||
|
||||
The same holds for tools and patterns: solve a problem the way the codebase
|
||||
already solves it. A new library or pattern is a decision the PR body names, not a
|
||||
side effect.
|
||||
|
||||
## Pick the primitive the job needs
|
||||
|
||||
- Call state lives in a view model; `useState` holds only what the view alone
|
||||
cares about — an open menu, a hover.
|
||||
- A prop by default. Context is for what a whole mounted instance shares — the
|
||||
host bridge, the root element, URL params — not for skipping a level of props.
|
||||
- A `Behavior` for anything with a current value, a plain observable for events.
|
||||
|
||||
## Ordering
|
||||
|
||||
- **Newspaper order.** Headline first, detail down. A file opens with what it
|
||||
|
||||
@@ -60,4 +60,5 @@ pnpm backend # Synapse + LiveKit, required for e2e
|
||||
pnpm test:playwright # or :open
|
||||
pnpm dev:component # component harness, port 3001
|
||||
pnpm dev:sdk # SDK harness, port 3002
|
||||
pnpm dev:widget-rtc-sdk # widget RTC SDK example widget, port 3003
|
||||
```
|
||||
|
||||
@@ -14,7 +14,8 @@ export default {
|
||||
"vite-embedded.config.ts",
|
||||
"vite-sdk.config.ts",
|
||||
"vite-sdk-dev.config.ts",
|
||||
"vite-sdk-target-based-on-call-view-model.config.ts",
|
||||
"vite-widget-rtc-sdk.config.ts",
|
||||
"vite-widget-rtc-sdk-dev.config.ts",
|
||||
"vite-component.config.ts",
|
||||
"vite-component-dev.config.ts",
|
||||
],
|
||||
|
||||
@@ -118,8 +118,6 @@
|
||||
"livekit_connection_error": "Failed to connect to Livekit server",
|
||||
"livekit_connection_error_description": "An error occurred while connecting to the Livekit server (<1>Reason:</1> <2>{{ reason }}</2>).",
|
||||
"matrix_rtc_transport_missing": "The server is not configured to work with {{brand}} and no other call participant provides a usable transport. Please contact your server admin (Domain: {{domain}}, Error Code: {{ errorCode }}).",
|
||||
"membership_manager": "Membership Manager Error",
|
||||
"membership_manager_description": "The Membership Manager had to shut down. This is caused by many consecutive failed network requests.",
|
||||
"no_matrix_2_authorization_service": "The authorization service for your media server (SFU) is out of date.",
|
||||
"open_elsewhere": "Opened in another tab",
|
||||
"open_elsewhere_description": "{{brand}} has been opened in another tab. If that doesn't sound right, try reloading the page.",
|
||||
|
||||
+15
-12
@@ -8,6 +8,7 @@
|
||||
"dev:embedded": "vite --config vite-embedded.config.js",
|
||||
"dev:component": "vite --config vite-component-dev.config.ts",
|
||||
"dev:sdk": "vite --config vite-sdk-dev.config.ts",
|
||||
"dev:widget-rtc-sdk": "vite --config vite-widget-rtc-sdk-dev.config.ts",
|
||||
"build": "pnpm build:full",
|
||||
"build:full": "node --max-old-space-size=16384 node_modules/vite/bin/vite.js build",
|
||||
"build:full:production": "pnpm build:full",
|
||||
@@ -18,14 +19,17 @@
|
||||
"build:sdk": "pnpm build:sdk:js && pnpm build:sdk:types",
|
||||
"build:sdk:js": "pnpm build:full --config vite-sdk.config.js",
|
||||
"build:sdk:types": "tsc -p sdk/tsconfig.build.json",
|
||||
"build:sdk-target-based-on-call-view-model": "pnpm build:full --config vite-sdk-target-based-on-call-view-model.config.js",
|
||||
"build:sdk:production": "pnpm build:sdk-target-based-on-call-view-model",
|
||||
"build:sdk:development": "pnpm build:sdk-target-based-on-call-view-model --mode development",
|
||||
"build:component": "pnpm build:component:js && pnpm build:component:types",
|
||||
"build:sdk:production": "pnpm build:sdk",
|
||||
"build:sdk:development": "pnpm build:sdk:js --mode development && pnpm build:sdk:types",
|
||||
"build:widget-rtc-sdk": "pnpm build:full --config vite-widget-rtc-sdk.config.js",
|
||||
"build:widget-rtc-sdk:production": "pnpm build:widget-rtc-sdk",
|
||||
"build:widget-rtc-sdk:development": "pnpm build:widget-rtc-sdk --mode development",
|
||||
"build:component": "pnpm build:component:js && pnpm build:component:check && pnpm build:component:types",
|
||||
"build:component:js": "pnpm build:full --config vite-component.config.js",
|
||||
"build:component:check": "node scripts/check-component-bundle.mjs",
|
||||
"build:component:types": "tsc -p component/tsconfig.build.json",
|
||||
"build:component:production": "pnpm build:component",
|
||||
"build:component:development": "pnpm build:component:js --mode development && pnpm build:component:types",
|
||||
"build:component:development": "pnpm build:component:js --mode development && pnpm build:component:check && pnpm build:component:types",
|
||||
"serve": "vite preview",
|
||||
"format": "oxfmt",
|
||||
"format:check": "oxfmt --check; rc=$?; [[ $rc -ne 0 ]] && printf '\\033[46;30m INFO \\033[0m To fix, run: pnpm format\\n' >&2; exit $rc",
|
||||
@@ -51,20 +55,20 @@
|
||||
"build-storybook": "storybook build"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@codecov/vite-plugin": "^1.3.0",
|
||||
"@codecov/vite-plugin": "^2.0.0",
|
||||
"@fontsource/inconsolata": "^5.1.0",
|
||||
"@fontsource/inter": "^5.1.0",
|
||||
"@formatjs/intl-durationformat": "^0.10.0",
|
||||
"@formatjs/intl-durationformat": "^0.13.0",
|
||||
"@formatjs/intl-segmenter": "^11.7.3",
|
||||
"@livekit/components-core": "^0.12.0",
|
||||
"@livekit/track-processors": "^0.7.1",
|
||||
"@livekit/track-processors": "^0.8.0",
|
||||
"@mediapipe/tasks-vision": "^0.10.18",
|
||||
"@playwright/test": "^1.60.0",
|
||||
"@radix-ui/react-dialog": "^1.0.4",
|
||||
"@radix-ui/react-slider": "^1.1.2",
|
||||
"@radix-ui/react-visually-hidden": "^1.0.3",
|
||||
"@react-spring/web": "^10.0.0",
|
||||
"@rolldown/plugin-babel": "^0.2.3",
|
||||
"@rolldown/plugin-babel": "^0.3.0",
|
||||
"@sentry/react": "^8.0.0",
|
||||
"@sentry/vite-plugin": "^3.0.0",
|
||||
"@storybook/addon-docs": "^10.3.6",
|
||||
@@ -79,7 +83,6 @@
|
||||
"@types/jsdom": "^21.1.7",
|
||||
"@types/lodash-es": "^4.17.12",
|
||||
"@types/node": "^24.0.0",
|
||||
"@types/pako": "^2.0.3",
|
||||
"@types/qrcode": "^1.5.5",
|
||||
"@types/react": "^19.0.0",
|
||||
"@types/react-dom": "^19.0.0",
|
||||
@@ -91,7 +94,7 @@
|
||||
"@vitejs/plugin-react": "^6.0.2",
|
||||
"@vitest/browser-playwright": "^4.1.5",
|
||||
"@vitest/coverage-v8": "^4.0.18",
|
||||
"@vitest/ui": "4.1.11",
|
||||
"@vitest/ui": "4.1.12",
|
||||
"babel-plugin-react-compiler": "^1.0.0",
|
||||
"classnames": "^2.3.1",
|
||||
"copy-to-clipboard": "^3.3.3",
|
||||
@@ -114,7 +117,7 @@
|
||||
"oxfmt": "^0.79.0",
|
||||
"oxlint": "^1.70.0",
|
||||
"oxlint-tsgolint": "^0.25.0",
|
||||
"pako": "^2.0.4",
|
||||
"pako": "^3.0.3",
|
||||
"postcss": "^8.4.41",
|
||||
"postcss-preset-env": "^10.0.0",
|
||||
"postcss-selector-parser": "^7.1.1",
|
||||
|
||||
+34
-1
@@ -13,6 +13,7 @@ import { fileURLToPath } from "node:url";
|
||||
|
||||
import { COMPONENT_HARNESS_URL } from "./playwright/component/harness.ts";
|
||||
import { SDK_HARNESS_URL } from "./playwright/sdk/harness.ts";
|
||||
import { WIDGET_RTC_SDK_URL } from "./playwright/widget/test-helpers.ts";
|
||||
|
||||
const baseURL = process.env.USE_DOCKER
|
||||
? "http://localhost:8080"
|
||||
@@ -82,6 +83,11 @@ export default defineConfig({
|
||||
name: "build-embedded",
|
||||
testMatch: "**/widget/embedded/build.setup.ts",
|
||||
},
|
||||
{
|
||||
// Builds the widget RTC SDK's example widget for its preview server
|
||||
name: "build-widget-rtc-sdk",
|
||||
testMatch: "**/widget/widget-rtc-sdk.setup.ts",
|
||||
},
|
||||
{
|
||||
name: "chromium",
|
||||
testIgnore: ["**/mobile/**", "**/widget/**"],
|
||||
@@ -93,12 +99,21 @@ export default defineConfig({
|
||||
name: "widget",
|
||||
dependencies: ["build-embedded"],
|
||||
testMatch: "**/widget/**/*.@(spec|test).ts",
|
||||
testIgnore: "**/widget/widget-rtc-sdk.spec.ts",
|
||||
use: desktopChrome,
|
||||
},
|
||||
{
|
||||
// The widget RTC SDK's example widget in Element Web. CI does not run
|
||||
// this project; see widget-rtc-sdk/README.md for running it by hand.
|
||||
name: "widget-rtc-sdk",
|
||||
dependencies: ["build-widget-rtc-sdk"],
|
||||
testMatch: "**/widget/widget-rtc-sdk.spec.ts",
|
||||
use: desktopChrome,
|
||||
},
|
||||
{
|
||||
name: "firefox",
|
||||
dependencies: ["build-embedded"],
|
||||
testIgnore: "**/mobile/**",
|
||||
testIgnore: ["**/mobile/**", "**/widget/widget-rtc-sdk.spec.ts"],
|
||||
use: {
|
||||
...devices["Desktop Firefox"],
|
||||
ignoreHTTPSErrors: true,
|
||||
@@ -183,5 +198,23 @@ export default defineConfig({
|
||||
timeout: 500,
|
||||
},
|
||||
},
|
||||
{
|
||||
// The widget RTC SDK's example widget, which Element Web opens as a
|
||||
// widget. Bundled rather than from the dev server: Firefox now and then
|
||||
// stalls on the dev server's hundreds of module requests. Servers start
|
||||
// before any project, so the build-widget-rtc-sdk project fills the
|
||||
// directory later and only the projects that open the widget wait for
|
||||
// it. Until then there is no page, hence the port rather than the url.
|
||||
command:
|
||||
"mkdir -p dist-widget-rtc-sdk-example && " +
|
||||
"pnpm exec vite preview --config vite-widget-rtc-sdk-dev.config.ts",
|
||||
port: Number(new URL(WIDGET_RTC_SDK_URL).port),
|
||||
reuseExistingServer: !process.env.CI,
|
||||
ignoreHTTPSErrors: true,
|
||||
gracefulShutdown: {
|
||||
signal: "SIGTERM",
|
||||
timeout: 500,
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
@@ -32,9 +32,11 @@ export interface MyFixtures {
|
||||
export const widgetTest = test.extend<MyFixtures>({
|
||||
// allow per-test override: `widgetTest.use({ callType: "dm" })`
|
||||
callType: ["room", { option: true }],
|
||||
asWidget: async ({ browser, callType }, pUse) => {
|
||||
const brooksDisplayName = `brooks_${Date.now()}`;
|
||||
const whistlerDisplayName = `whistler_${Date.now()}`;
|
||||
asWidget: async ({ browser, callType }, pUse, testInfo) => {
|
||||
// Tests in parallel workers can reach this in the same millisecond.
|
||||
const uniqueSuffix = `${Date.now()}_${testInfo.parallelIndex}`;
|
||||
const brooksDisplayName = `brooks_${uniqueSuffix}`;
|
||||
const whistlerDisplayName = `whistler_${uniqueSuffix}`;
|
||||
|
||||
// Register users
|
||||
const {
|
||||
|
||||
@@ -58,20 +58,20 @@ const cases: {
|
||||
guestFlows: ["cs-api"],
|
||||
},
|
||||
{
|
||||
// The client-server API is preferred wherever a transport names a url.
|
||||
// Clients since 0.28.1 match such a publisher by either identity.
|
||||
// Publishers keep the legacy participant identity that clients predating
|
||||
// MSC4195 expect, which only the JWT service assigns.
|
||||
hostShape: "url+legacy",
|
||||
guestShape: "url+legacy",
|
||||
hostFlows: ["cs-api"],
|
||||
guestFlows: ["cs-api"],
|
||||
hostFlows: ["service-legacy"],
|
||||
guestFlows: ["service-legacy"],
|
||||
},
|
||||
{
|
||||
// The MatrixRTC mode has no bearing on the choice.
|
||||
hostShape: "url+legacy",
|
||||
guestShape: "url+legacy",
|
||||
mode: "2_0",
|
||||
hostFlows: ["cs-api"],
|
||||
guestFlows: ["cs-api"],
|
||||
hostFlows: ["service-legacy"],
|
||||
guestFlows: ["service-legacy"],
|
||||
},
|
||||
{
|
||||
hostShape: "url",
|
||||
@@ -80,12 +80,10 @@ const cases: {
|
||||
guestFlows: ["service-legacy", "cs-api"],
|
||||
},
|
||||
{
|
||||
// Both reach the SFU through the client-server API, under one identity
|
||||
// each, so one connection serves the own and the other's transport.
|
||||
hostShape: "url",
|
||||
guestShape: "url+legacy",
|
||||
hostFlows: ["cs-api"],
|
||||
guestFlows: ["cs-api"],
|
||||
hostFlows: ["cs-api", "service-default"],
|
||||
guestFlows: ["service-legacy", "cs-api"],
|
||||
},
|
||||
];
|
||||
|
||||
@@ -162,50 +160,6 @@ test("Publisher shows an error when the homeserver lacks MSC4195", async ({
|
||||
).toBeVisible();
|
||||
});
|
||||
|
||||
test("Falls back to the JWT service for a url+legacy transport when the homeserver lacks MSC4195", async ({
|
||||
browser,
|
||||
page,
|
||||
browserName,
|
||||
}) => {
|
||||
skipOnFirefox(browserName);
|
||||
|
||||
// The host starts the call; its C-S requests fail.
|
||||
await advertiseTransport(page, shapes["url+legacy"]);
|
||||
await rejectCsApiTokens(page);
|
||||
const hostRequests = recordAuthRequests(page);
|
||||
await page.goto("/");
|
||||
await SpaHelpers.createCall(page, "Androl", "HelloCall", true);
|
||||
const inviteLink = await SpaHelpers.getCallInviteLink(page);
|
||||
|
||||
// The guest joins, and its C-S requests fail as well.
|
||||
const guestContext = await browser.newContext({ reducedMotion: "reduce" });
|
||||
const guestPage = await guestContext.newPage();
|
||||
await advertiseTransport(guestPage, shapes["url+legacy"]);
|
||||
await rejectCsApiTokens(guestPage);
|
||||
const guestRequests = recordAuthRequests(guestPage);
|
||||
await SpaHelpers.joinCallFromInviteLink(guestPage, inviteLink, "Pevara");
|
||||
|
||||
// The call connects all the same.
|
||||
await SpaHelpers.expectVideoTilesCount(page, 2);
|
||||
await SpaHelpers.expectVideoTilesCount(guestPage, 2);
|
||||
|
||||
for (const requests of [hostRequests, guestRequests]) {
|
||||
// Each published through the JWT service, under the legacy identity, and
|
||||
// subscribes to the other over that same connection.
|
||||
expect(flowsOf(requests)).toEqual(
|
||||
new Set<Flow>(["cs-api", "service-legacy"]),
|
||||
);
|
||||
for (const request of requests) {
|
||||
if (request.flow === "cs-api") {
|
||||
expect(request.status).toBe(404);
|
||||
} else {
|
||||
expect(request.status).toBe(200);
|
||||
expect(request.identity).toMatch(legacyIdentity);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("Group call with all possible transport shapes at once", async ({
|
||||
browser,
|
||||
page,
|
||||
@@ -239,12 +193,13 @@ test("Group call with all possible transport shapes at once", async ({
|
||||
});
|
||||
|
||||
/**
|
||||
* Delegation follows the flow that authenticated the publisher.
|
||||
* Delegation follows the flow that authenticated the publisher: the homeserver
|
||||
* for a `url`-only transport, the JWT service wherever there is one.
|
||||
*/
|
||||
const delegationCases: { shape: Shape; via: Delegation["via"] }[] = [
|
||||
{ shape: "url", via: "homeserver" },
|
||||
{ shape: "legacy", via: "service" },
|
||||
{ shape: "url+legacy", via: "homeserver" },
|
||||
{ shape: "url+legacy", via: "service" },
|
||||
];
|
||||
|
||||
for (const { shape, via } of delegationCases) {
|
||||
@@ -273,9 +228,10 @@ for (const { shape, via } of delegationCases) {
|
||||
await SpaHelpers.expectVideoTilesCount(page, 2);
|
||||
await SpaHelpers.expectVideoTilesCount(guestPage, 2);
|
||||
|
||||
// The guest handed its delayed leave over. A JWT service is first probed
|
||||
// for delegation support with a bodiless request, which counts as
|
||||
// supported unless it 404s. A homeserver that issued the token is not.
|
||||
// The guest handed its delayed leave over, after probing for delegation
|
||||
// support with bodiless requests, which count as supported unless they
|
||||
// 404. The homeserver is always probed; the JWT service only when there
|
||||
// is one.
|
||||
await expect
|
||||
.poll(() => delegations.at(-1))
|
||||
.toEqual({
|
||||
@@ -285,9 +241,7 @@ for (const { shape, via } of delegationCases) {
|
||||
...(via === "homeserver" && { sfuUrl }),
|
||||
});
|
||||
const probes = delegations.slice(0, -1);
|
||||
expect(probes.map((probe) => probe.via)).toEqual(
|
||||
via === "service" ? ["service"] : [],
|
||||
);
|
||||
expect(probes.some((probe) => probe.via === via)).toBe(true);
|
||||
for (const probe of probes) {
|
||||
expect(probe.status).toBeGreaterThanOrEqual(400);
|
||||
expect(probe.status).not.toBe(404);
|
||||
|
||||
@@ -5,9 +5,10 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { test as setup } from "@playwright/test";
|
||||
import { expect, test as setup } from "@playwright/test";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { mkdirSync } from "node:fs";
|
||||
import { mkdirSync, readdirSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
const EMBEDDED_DIST = "embedded/web/dist";
|
||||
|
||||
@@ -17,4 +18,8 @@ setup("build the embedded package", () => {
|
||||
execFileSync("pnpm", ["build:embedded", "--outDir", EMBEDDED_DIST], {
|
||||
stdio: "inherit",
|
||||
});
|
||||
// The host does the crypto, and nothing runs the standalone client
|
||||
expect(readdirSync(join(EMBEDDED_DIST, "assets"))).not.toContainEqual(
|
||||
expect.stringMatching(/rust-crypto|matrix_sdk_crypto|IndexedDBWorker/),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -22,6 +22,12 @@ const PASSWORD = "foobarbaz1!";
|
||||
export const HOST1 = "https://app.m.localhost/#/welcome";
|
||||
export const HOST2 = "https://app.othersite.m.localhost/#/welcome";
|
||||
|
||||
/**
|
||||
* Where the widget RTC SDK's example widget is served (`pnpm dev:widget-rtc-sdk`):
|
||||
* `widget-rtc-sdk/index.html`, running the bundle from source.
|
||||
*/
|
||||
export const WIDGET_RTC_SDK_URL = "https://localhost:3003";
|
||||
|
||||
export type RtcMode = "compat" | "2_0";
|
||||
|
||||
export class TestHelpers {
|
||||
@@ -206,8 +212,11 @@ export class TestHelpers {
|
||||
await expect(dialog).toBeHidden({ timeout: 5000 });
|
||||
}
|
||||
// The same element shows the next toast a moment after the click, so
|
||||
// reading it straight away acts on the dismissed one a second time
|
||||
await expect(toastTitle).not.toHaveText(title, { timeout: 5000 });
|
||||
// reading it straight away acts on the dismissed one a second time.
|
||||
// Counted rather than read, as the last toast leaves no title behind.
|
||||
await expect(toastTitle.filter({ hasText: title })).toHaveCount(0, {
|
||||
timeout: 5000,
|
||||
});
|
||||
} else {
|
||||
// Unknown toast. We don't want to act on unknown toasts
|
||||
break;
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { test as setup } from "@playwright/test";
|
||||
import { execFileSync } from "node:child_process";
|
||||
|
||||
// Into the directory the widget RTC SDK's preview server already serves (see
|
||||
// playwright.config.ts)
|
||||
setup("build the widget RTC SDK example", () => {
|
||||
setup.setTimeout(10 * 60 * 1000);
|
||||
execFileSync(
|
||||
"pnpm",
|
||||
["exec", "vite", "build", "--config", "vite-widget-rtc-sdk-dev.config.ts"],
|
||||
{ stdio: "inherit" },
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,129 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { expect, type FrameLocator, type Page } from "@playwright/test";
|
||||
|
||||
import { widgetTest } from "../fixtures/widget-user.ts";
|
||||
import { WIDGET_RTC_SDK_URL } from "./test-helpers.ts";
|
||||
|
||||
/**
|
||||
* The widget RTC SDK's example widget, `widget-rtc-sdk/index.html`, added to a
|
||||
* room as a custom widget and opened in two Element Webs: the bundle's whole
|
||||
* public API, from the widget API to the data channel.
|
||||
*/
|
||||
|
||||
widgetTest.describe.configure({ timeout: 300_000 });
|
||||
|
||||
const WIDGET_ID = "widget-rtc-sdk-example";
|
||||
const WIDGET_NAME = "Widget RTC SDK";
|
||||
|
||||
/** Accepts the prompts Element Web shows before it runs a widget, and finds it. */
|
||||
async function openWidget(page: Page): Promise<FrameLocator> {
|
||||
// Only for a widget someone else added
|
||||
const loadPrompt = page.getByRole("button", { name: "Continue" });
|
||||
const capabilitiesPrompt = page.getByRole("button", { name: "Approve" });
|
||||
await expect(loadPrompt.or(capabilitiesPrompt)).toBeVisible({
|
||||
timeout: 30_000,
|
||||
});
|
||||
if (await loadPrompt.isVisible()) await loadPrompt.click();
|
||||
await capabilitiesPrompt.click({ timeout: 30_000 });
|
||||
// The SDK authenticates with the media transport by an OpenID token, and
|
||||
// asks for more than one, so the answer has to be remembered
|
||||
const openIdPrompt = page.getByRole("dialog", {
|
||||
name: "Allow this widget to verify your identity",
|
||||
});
|
||||
await openIdPrompt.getByText("Remember this").click({ timeout: 30_000 });
|
||||
await openIdPrompt.getByRole("button", { name: "Continue" }).click();
|
||||
return page.frameLocator(`iframe[title="${WIDGET_NAME}"]`);
|
||||
}
|
||||
|
||||
widgetTest(
|
||||
"data sent from one widget arrives in the other",
|
||||
async ({ asWidget }) => {
|
||||
const { brooks, whistler } = asWidget;
|
||||
|
||||
// Brooks adds the example widget to the room and pins it to the top, so
|
||||
// that both Element Webs open it without anyone looking for it
|
||||
await brooks.clientHandle.evaluate(
|
||||
async (client, { widgetId, name, url }) => {
|
||||
const roomId = client
|
||||
.getRooms()
|
||||
.find((room) => room.name === "Welcome Room")!.roomId;
|
||||
await client.sendStateEvent(
|
||||
roomId,
|
||||
// @ts-expect-error not in the js-sdk's state event map
|
||||
"im.vector.modular.widgets",
|
||||
{
|
||||
id: widgetId,
|
||||
type: "m.custom",
|
||||
name,
|
||||
url,
|
||||
data: {},
|
||||
creatorUserId: client.getUserId(),
|
||||
},
|
||||
widgetId,
|
||||
);
|
||||
await client.sendStateEvent(
|
||||
roomId,
|
||||
// @ts-expect-error not in the js-sdk's state event map
|
||||
"io.element.widgets.layout",
|
||||
{
|
||||
widgets: {
|
||||
[widgetId]: {
|
||||
container: "top",
|
||||
index: 0,
|
||||
width: 100,
|
||||
height: 50,
|
||||
},
|
||||
},
|
||||
},
|
||||
"",
|
||||
);
|
||||
},
|
||||
{
|
||||
widgetId: WIDGET_ID,
|
||||
name: WIDGET_NAME,
|
||||
// Element Web fills the $ variables in and adds widgetId and parentUrl
|
||||
url:
|
||||
`${WIDGET_RTC_SDK_URL}/?widgetId=$matrix_widget_id&roomId=$matrix_room_id` +
|
||||
"&userId=$matrix_user_id&deviceId=$org.matrix.msc3819.matrix_device_id" +
|
||||
"&baseUrl=$org.matrix.msc4039.matrix_base_url",
|
||||
},
|
||||
);
|
||||
|
||||
const brooksWidget = await openWidget(brooks.page);
|
||||
const whistlerWidget = await openWidget(whistler.page);
|
||||
|
||||
// The example joins on load; each sees the other as a member
|
||||
for (const [widget, other] of [
|
||||
[brooksWidget, whistler],
|
||||
[whistlerWidget, brooks],
|
||||
] as const) {
|
||||
await expect(widget.locator("#connect_status")).toHaveText("Connected", {
|
||||
timeout: 60_000,
|
||||
});
|
||||
await expect(widget.locator("#members")).toContainText(other.mxId, {
|
||||
timeout: 60_000,
|
||||
});
|
||||
}
|
||||
|
||||
// Data is not queued: the receiver drops what arrives before it has matched
|
||||
// the sender on the media transport, which the example does not show. So
|
||||
// send until it arrives.
|
||||
await expect(async () => {
|
||||
await brooksWidget.getByRole("button", { name: "Send Text" }).click();
|
||||
await expect(whistlerWidget.locator("#data")).toContainText(
|
||||
"Hello, world!",
|
||||
{ timeout: 2_000 },
|
||||
);
|
||||
}).toPass({ timeout: 60_000 });
|
||||
// Our own data is not echoed back
|
||||
await expect(brooksWidget.locator("#data")).not.toContainText(
|
||||
"Hello, world!",
|
||||
);
|
||||
},
|
||||
);
|
||||
Generated
+1960
-2299
File diff suppressed because it is too large
Load Diff
+10
-14
@@ -30,22 +30,14 @@ overrides:
|
||||
"minimatch": "^11.0.0"
|
||||
# Security fix: https://github.com/element-hq/element-call/security/dependabot/109
|
||||
"glob": "^10.5.0"
|
||||
# Security fixes:
|
||||
# - https://github.com/element-hq/element-call/security/dependabot/110
|
||||
# - https://github.com/element-hq/element-call/security/dependabot/122
|
||||
# - https://github.com/element-hq/element-call/security/dependabot/179
|
||||
"qs": "^6.15.2"
|
||||
# Security fixes:
|
||||
# - https://github.com/element-hq/element-call/security/dependabot/106
|
||||
# - https://github.com/element-hq/element-call/security/dependabot/203
|
||||
"js-yaml": "^4.2.0"
|
||||
# Security fix: https://github.com/advisories/GHSA-6pq8-jhm2-2vcw
|
||||
"qs": ">=6.16.1"
|
||||
# Security fix: https://github.com/advisories/GHSA-2883-xcg3-v3hh
|
||||
"js-yaml": "^4.3.2"
|
||||
# Storybook declares support for 0.27.0 only but empirically works fine with 0.28.0.
|
||||
"esbuild": "^0.28.0"
|
||||
# Security fixes:
|
||||
# - https://github.com/nodejs/undici/releases/tag/v6.24.0
|
||||
# - https://github.com/element-hq/element-call/security/dependabot/201
|
||||
# - https://github.com/element-hq/element-call/security/dependabot/199
|
||||
"undici": "^6.27.0"
|
||||
# Security fix: https://github.com/advisories/GHSA-w293-vg96-wgc3
|
||||
"undici": "^6.29.1"
|
||||
# Security fix: https://github.com/advisories/GHSA-rf6f-7fwh-wjgh
|
||||
"flatted": "^3.4.2"
|
||||
# Security fix: https://github.com/element-hq/element-call/security/dependabot/184
|
||||
@@ -63,3 +55,7 @@ overrides:
|
||||
# - https://github.com/advisories/GHSA-mrv2-3pqr-j5jr
|
||||
# - https://github.com/advisories/GHSA-c6gr-qvv4-5v3f
|
||||
"dompurify": "^3.4.17"
|
||||
# Security fix: https://github.com/advisories/GHSA-73wf-gq98-2v4g
|
||||
"browserslist": ">=4.28.7"
|
||||
# Security fix: https://github.com/advisories/GHSA-7w5x-hrqm-74c2
|
||||
"smol-toml": ">=1.9.0"
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Checks the component build's output for what a host must not be handed.
|
||||
*
|
||||
* A library build inlines every asset it meets as a data URL unless the import
|
||||
* says otherwise, and does so silently: one import without `no-inline` and the
|
||||
* module grows by the asset, encoded a third larger, that every host then
|
||||
* downloads and parses before the first call. MediaPipe's runtime alone is
|
||||
* 11 MB. A reference to a file by an absolute path is just as silent and
|
||||
* breaks at runtime instead, since a host serves the module from wherever it
|
||||
* likes. And the standalone app's client store worker, which carries a copy of
|
||||
* the Matrix SDK and its crypto, has no business in a package whose host
|
||||
* supplies the client: the bundler emits it on loading its import, used or
|
||||
* not (see src/utils/initClient.ts). This fails the build on each of those.
|
||||
*/
|
||||
|
||||
import { existsSync } from "node:fs";
|
||||
import { readdir, readFile, stat } from "node:fs/promises";
|
||||
import { basename, join } from "node:path";
|
||||
|
||||
const dist = "component/dist";
|
||||
|
||||
/** The client store worker, whose chunk is named after this file. */
|
||||
const workerSource = "src/IndexedDBWorker.ts";
|
||||
|
||||
/** The longest data URL a chunk may carry: enough for an icon, not a sound. */
|
||||
const inlineLimit = 16 * 1024;
|
||||
|
||||
/**
|
||||
* The module itself, in bytes. Well above where it sits with its assets as
|
||||
* files, so that only an asset finding its way back in trips it.
|
||||
*/
|
||||
const moduleBudget = 4 * 1024 * 1024;
|
||||
|
||||
const problems = [];
|
||||
|
||||
// A rename would otherwise turn the worker check off without a word.
|
||||
if (!existsSync(workerSource))
|
||||
problems.push(
|
||||
`${workerSource} is gone, so the check for the client store worker ` +
|
||||
`cannot recognise its chunk. Point \`workerSource\` in ` +
|
||||
`scripts/check-component-bundle.mjs at the worker's new name.`,
|
||||
);
|
||||
const workerName = basename(workerSource, ".ts");
|
||||
|
||||
for (const name of await assets())
|
||||
if (name.includes(workerName))
|
||||
problems.push(
|
||||
`${dist}/assets/${name}: the standalone app's client store worker is ` +
|
||||
`in the package. Something the component reaches imports the worker; ` +
|
||||
`keep it on the standalone app's side (see src/utils/initClient.ts ` +
|
||||
`and the \`loadClient\` prop of ClientProvider).`,
|
||||
);
|
||||
|
||||
for (const file of await modules()) {
|
||||
const code = await readFile(file, "utf8");
|
||||
|
||||
// Up to the closing quote rather than the end of the base64 alphabet, since
|
||||
// SVGs are inlined URL-encoded rather than as base64.
|
||||
for (const [, , type, payload] of code.matchAll(
|
||||
/(["'`])data:([a-z0-9/.+-]*)(?:;base64)?,(.*?)\1/g,
|
||||
))
|
||||
if (payload.length > inlineLimit)
|
||||
problems.push(
|
||||
`${file}: a ${type} asset of ${Math.round(payload.length / 1024)} kB ` +
|
||||
`is inlined as a data URL. Import it with \`?url&no-inline\` so ` +
|
||||
`that it is emitted as a file.`,
|
||||
);
|
||||
|
||||
for (const [reference] of code.matchAll(/["'`]\/assets\/[^"'`]+["'`]/g))
|
||||
problems.push(
|
||||
`${file}: ${reference} is an absolute path, which only resolves ` +
|
||||
`against an origin that serves the package at its root. The build ` +
|
||||
`is meant to render relative references; check \`base\` in ` +
|
||||
`vite-component.config.ts.`,
|
||||
);
|
||||
}
|
||||
|
||||
const moduleSize = (await stat(join(dist, "element-call.js"))).size;
|
||||
if (moduleSize > moduleBudget)
|
||||
problems.push(
|
||||
`${dist}/element-call.js is ${(moduleSize / 1024 / 1024).toFixed(1)} MB, ` +
|
||||
`over its ${moduleBudget / 1024 / 1024} MB budget. Something large ` +
|
||||
`has been bundled into the module that a host would rather fetch when ` +
|
||||
`it is needed.`,
|
||||
);
|
||||
|
||||
if (problems.length > 0) {
|
||||
console.error(`The component build is not fit to publish:\n`);
|
||||
for (const problem of problems) console.error(` ${problem}\n`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
/** The files under `assets/`, none if the build emitted no such directory. */
|
||||
async function assets() {
|
||||
try {
|
||||
return await readdir(join(dist, "assets"));
|
||||
} catch (e) {
|
||||
if (e.code === "ENOENT") return [];
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The modules a host bundles: the entry points and their chunks, at the top of
|
||||
* the package. What sits under `assets/` is fetched as it is, by URL.
|
||||
*/
|
||||
async function modules() {
|
||||
const names = await readdir(dist);
|
||||
return names.filter((name) => name.endsWith(".js")).map((n) => join(dist, n));
|
||||
}
|
||||
@@ -9,11 +9,11 @@ Please see LICENSE in the repository root for full details.
|
||||
* Checks that the library builds leave the packages a host must supply to the
|
||||
* host.
|
||||
*
|
||||
* A host application already has React, the Matrix SDK and Compound,
|
||||
* and a second copy of any of them is worse than dead weight: React would hold
|
||||
* two sets of hooks, the Matrix client would run two sync loops, and a second
|
||||
* Compound would style the tooltips it floats into the host's body with class
|
||||
* names the host's stylesheet does not know. So each library build lists them
|
||||
* A host application already has React and Compound (and, for the SDK build,
|
||||
* the Matrix SDK), and a second copy of any of them is worse than dead weight:
|
||||
* React would hold two sets of hooks, and a second Compound would style the
|
||||
* tooltips it floats into the host's body with class names the host's
|
||||
* stylesheet does not know. So each library build lists them
|
||||
* as external — but that list has to name every subpath, since the bundler
|
||||
* silently ignores the pattern and callback forms of the option, and an import
|
||||
* it does not cover is bundled with no warning at all. That is the failure
|
||||
@@ -47,10 +47,10 @@ const TARGETS = [
|
||||
// `sdk` too: the build resolves `@element-hq/matrixrtc-sdk` to its source
|
||||
sources: ["src", "component", "sdk"],
|
||||
excluded: ["component/dev", "sdk/dev"],
|
||||
// Not the Matrix SDK: the component bundles its own (see the build config)
|
||||
mustBeExternal: [
|
||||
"react",
|
||||
"react-dom",
|
||||
"matrix-js-sdk",
|
||||
"@vector-im/compound-web",
|
||||
"@vector-im/compound-design-tokens",
|
||||
],
|
||||
|
||||
@@ -1,68 +0,0 @@
|
||||
# SDK mode (LEGACY)
|
||||
|
||||
> Superseded by the `sdk/` package (`@element-hq/matrixrtc-sdk`) and its harness in
|
||||
> `sdk/dev`; see `sdk/SdkArchitecture.md`. This bundle is in production use, so it
|
||||
> keeps building as a thin layer over that package until its consumers have moved
|
||||
> to the package directly. It will then be removed. Its members are the package's
|
||||
> `RTCMember`s now, in place of its own wrapper around the raw membership.
|
||||
|
||||
EC can be build in sdk mode. This will result in a compiled js file that can be imported in very simple webapps.
|
||||
|
||||
It allows to use matrixRTC in combination with livekit without relying on element call.
|
||||
|
||||
This is done by instantiating the call view model and exposing some useful behaviors (observables) and methods.
|
||||
|
||||
This folder contains an example index.html file that showcases the sdk in use (hosted on localhost:8123 with a webserver allowing cors (for example `npx serve -l 81234 --cors`)) as a godot engine HTML export template.
|
||||
|
||||
## Getting started
|
||||
|
||||
To get started run
|
||||
|
||||
```
|
||||
pnpm install
|
||||
pnpm build:sdk-target-based-on-call-view-model
|
||||
```
|
||||
|
||||
in the repository root. (`pnpm build:sdk` builds the `sdk/` package instead.)
|
||||
|
||||
CI's `sdk` package (`build:sdk:production`, `build:sdk:development`, the
|
||||
`build-output-sdk` artifact and the `pr<N>-sdk` Netlify preview) is still this
|
||||
bundle, not the `sdk/` package, until its consumers have moved over.
|
||||
|
||||
It will create `dist` containing the compiled js file, `matrixrtc-sdk.js`.
|
||||
|
||||
This file needs to be hosted. Locally (via `npx serve -l 81234 --cors`) or on a remote server.
|
||||
|
||||
Now you just need to add the widget to element web via:
|
||||
|
||||
```
|
||||
/addwidget http://localhost:3000?widgetId=$matrix_widget_id&userId=$matrix_user_id&deviceId=$org.matrix.msc3819.matrix_device_id&baseUrl=$org.matrix.msc4039.matrix_base_url&roomId=$matrix_room_id
|
||||
```
|
||||
|
||||
## Widgets
|
||||
|
||||
The sdk mode is particularly interesting to be used in widgets. In widgets you do not need to pay attention to matrix login/cs api ...
|
||||
To create a widget see the example `index.html` file in this folder. And add it to EW via:
|
||||
`/addwidget <widgetUrl>` (see **url parameters** for more details on `<widgetUrl>`)
|
||||
|
||||
### url parameters
|
||||
|
||||
The url parameters are needed to pass initial data to the widget. They will automatically be used
|
||||
by the matrixRTCSdk to start the postmessage widget api (communication between the client (e.g. Element Web) and the widget)
|
||||
|
||||
```
|
||||
widgetId = $matrix_widget_id
|
||||
userId = $matrix_user_id
|
||||
deviceId = $org.matrix.msc3819.matrix_device_id
|
||||
baseUrl = $org.matrix.msc4039.matrix_base_url
|
||||
```
|
||||
|
||||
`parentUrl = // will be inserted automatically`
|
||||
|
||||
Full template use as `<widgetUrl>`:
|
||||
|
||||
```
|
||||
http://localhost:3000?widgetId=$matrix_widget_id&userId=$matrix_user_id&deviceId=$org.matrix.msc3819.matrix_device_id&baseUrl=$org.matrix.msc4039.matrix_base_url&roomId=$matrix_room_id
|
||||
```
|
||||
|
||||
the `$` prefixed variables will be replaced by EW on widget instantiation. (e.g. `$matrix_user_id` -> `@user:example.com` (url encoding will also be applied automatically by EW) -> `%40user%3Aexample.com`)
|
||||
@@ -1,193 +0,0 @@
|
||||
/*
|
||||
Copyright 2025-2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
/**
|
||||
* LEGACY, in production use
|
||||
*
|
||||
* The entrypoint of `pnpm build:sdk-target-based-on-call-view-model`, a
|
||||
* bundle for widgets that exposes `createMatrixRTCSdk`: join a slot and
|
||||
* exchange realtime data, with the `@element-hq/matrixrtc-sdk` package and
|
||||
* Element Call's call view model doing the work underneath. New consumers use
|
||||
* the package directly; this bundle goes away once the existing ones have.
|
||||
*/
|
||||
|
||||
import { logger as rootLogger } from "matrix-js-sdk/lib/logger";
|
||||
import { EMPTY, filter, map, type Observable, of, switchMap, take } from "rxjs";
|
||||
import {
|
||||
type Behavior,
|
||||
createRTCSlot,
|
||||
E2eeType,
|
||||
type LocalRTCMember,
|
||||
ObservableScope,
|
||||
type RemoteRTCMember,
|
||||
type RTCParticipation,
|
||||
} from "@element-hq/matrixrtc-sdk";
|
||||
|
||||
import {
|
||||
callViewModelOptionsFromParams,
|
||||
type CallViewModel,
|
||||
createCallViewModel$,
|
||||
initialPublishRequests,
|
||||
} from "../src/state/CallViewModel/CallViewModel";
|
||||
import {
|
||||
captureSettings,
|
||||
rtcParticipationOptions,
|
||||
rtcSlotOptions,
|
||||
} from "../src/room/InCallView";
|
||||
import { createWidgetHostBridge } from "../src/HostBridge";
|
||||
import { MediaDevices } from "../src/state/MediaDevices";
|
||||
import { MuteStates } from "../src/state/MuteStates";
|
||||
import { getUrlParams } from "../src/UrlParams";
|
||||
import { observeElementSize$ } from "../src/utils/elementSize";
|
||||
import { initializeWidget } from "../src/widget";
|
||||
|
||||
/** The data channel topic this bundle has always used, so that old and new builds talk. */
|
||||
const TOPIC = "matrixRTC";
|
||||
|
||||
export interface MatrixRTCSdk {
|
||||
/** Joins the slot; `connected$` tracks the progress. A second call does nothing. */
|
||||
join: () => void;
|
||||
leave: () => void;
|
||||
/** Ends everything. The sdk cannot be restarted; create a new one. */
|
||||
stop: () => void;
|
||||
connected$: Behavior<boolean>;
|
||||
/** Our own member, null until our membership has been seen in the room. */
|
||||
localMember$: Behavior<LocalRTCMember | null>;
|
||||
/** The other members of the slot, with the media the participation carries for them. */
|
||||
remoteMembers$: Behavior<RemoteRTCMember[]>;
|
||||
/** What other members sent with `sendData`. */
|
||||
data$: Observable<{ rtcBackendIdentity: string; data: string }>;
|
||||
/** Sends to every member on our transport. Rejects while not joined. */
|
||||
sendData: (data: unknown) => Promise<void>;
|
||||
sendRoomMessage: (message: string) => Promise<void>;
|
||||
}
|
||||
|
||||
export async function createMatrixRTCSdk(
|
||||
application = "m.call",
|
||||
id = "",
|
||||
sticky = false,
|
||||
): Promise<MatrixRTCSdk> {
|
||||
const logger = rootLogger.getChild("[MatrixRTCSdk]");
|
||||
const scope = new ObservableScope();
|
||||
const widget = initializeWidget(application, true);
|
||||
if (!widget) throw new Error("No widget: this bundle only runs as a widget");
|
||||
const client = await widget.client;
|
||||
const hostBridge = createWidgetHostBridge(widget);
|
||||
const urlParams = getUrlParams();
|
||||
const { roomId, controlledAudioDevices, callIntent } = urlParams;
|
||||
const room = roomId === null ? null : client.getRoom(roomId);
|
||||
if (room === null) throw new Error("No room: the url needs a joined roomId");
|
||||
|
||||
const mediaDevices = new MediaDevices(scope, {
|
||||
controlledAudioDevices,
|
||||
callIntent,
|
||||
});
|
||||
const muteStates = new MuteStates(
|
||||
scope,
|
||||
mediaDevices,
|
||||
{ audioEnabled: false, videoEnabled: false },
|
||||
hostBridge,
|
||||
);
|
||||
const encryptionSystem = { kind: E2eeType.PER_PARTICIPANT } as const;
|
||||
const capture = captureSettings();
|
||||
const slot = createRTCSlot(scope, client, room, {
|
||||
...rtcSlotOptions(encryptionSystem),
|
||||
application,
|
||||
id,
|
||||
});
|
||||
let vm: CallViewModel | undefined;
|
||||
const failed =
|
||||
(what: string) =>
|
||||
(e: unknown): void =>
|
||||
logger.error(what, e);
|
||||
|
||||
const over = <T>(
|
||||
pick: (participation: RTCParticipation) => Observable<T>,
|
||||
fallback: T,
|
||||
): Behavior<T> =>
|
||||
scope.behavior(
|
||||
slot.participation$.pipe(
|
||||
switchMap((p) => (p === null ? of(fallback) : pick(p))),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
join: (): void => {
|
||||
if (slot.participation$.value !== null) return;
|
||||
if (sticky)
|
||||
widget.api
|
||||
.setAlwaysOnScreen(true)
|
||||
.catch(failed("Failed to make the widget sticky"));
|
||||
const participation = slot.join({
|
||||
...rtcParticipationOptions(urlParams),
|
||||
publish: initialPublishRequests(muteStates, mediaDevices, capture),
|
||||
});
|
||||
vm = createCallViewModel$(
|
||||
scope,
|
||||
{
|
||||
rtcParticipation: participation,
|
||||
matrixRoom: room,
|
||||
mediaDevices,
|
||||
muteStates,
|
||||
encryptionSystem,
|
||||
// The bundle owns its page, so the body is the space it has
|
||||
viewSize$: scope.behavior(observeElementSize$(document.body)),
|
||||
handsRaisedSubject$: of({}),
|
||||
reactionsSubject$: of({}),
|
||||
},
|
||||
{
|
||||
...callViewModelOptionsFromParams(urlParams),
|
||||
capture,
|
||||
hostBridge,
|
||||
},
|
||||
);
|
||||
// Once the hang-up has gone through, unstick and ask the host to close us
|
||||
vm.leave$
|
||||
.pipe(
|
||||
switchMap(() =>
|
||||
participation.state$.pipe(
|
||||
filter((state) => state.kind === "left"),
|
||||
take(1),
|
||||
),
|
||||
),
|
||||
scope.bind(),
|
||||
)
|
||||
.subscribe(() => {
|
||||
hostBridge
|
||||
.setAlwaysOnScreen(false)
|
||||
.catch(failed("Failed to unstick the widget"))
|
||||
.then(() => hostBridge.close?.())
|
||||
.catch(failed("Failed to ask the host to close"));
|
||||
});
|
||||
},
|
||||
leave: (): void => vm?.leave(),
|
||||
stop: (): void => scope.end(),
|
||||
connected$: over(
|
||||
(p) => p.state$.pipe(map((state) => state.kind === "connected")),
|
||||
false,
|
||||
),
|
||||
localMember$: over((p) => p.localMember$, null),
|
||||
remoteMembers$: over((p) => p.remoteMembers$, []),
|
||||
// Attested members only: the SDK has matched the sender
|
||||
data$: slot.participation$.pipe(
|
||||
switchMap((p) => p?.data$ ?? EMPTY),
|
||||
filter(({ topic }) => topic === TOPIC),
|
||||
map(({ member, text }) => ({
|
||||
rtcBackendIdentity: member.rtcBackendIdentity,
|
||||
data: text,
|
||||
})),
|
||||
),
|
||||
sendData: async (data): Promise<void> => {
|
||||
const participation = slot.participation$.value;
|
||||
if (participation === null) throw new Error("Not joined");
|
||||
await participation.sendData(TOPIC, JSON.stringify(data));
|
||||
},
|
||||
sendRoomMessage: async (message): Promise<void> => {
|
||||
await client.sendTextMessage(room.roomId, message);
|
||||
},
|
||||
};
|
||||
}
|
||||
+9
-8
@@ -5,8 +5,7 @@ it joins a MatrixRTC slot in a Matrix room, writes and watches the memberships,
|
||||
connects to the media transport (LiveKit today), publishes the local media and
|
||||
exposes every member and their tracks as observables. It has no UI. Element
|
||||
Call's own `CallViewModel` is one consumer of it; any host can build a different
|
||||
view on top. The design is in [`SdkArchitecture.md`](./SdkArchitecture.md), what
|
||||
moved out of Element Call's `src/` in [`SdkMigration.md`](./SdkMigration.md).
|
||||
view on top. The design is in [`SdkArchitecture.md`](./SdkArchitecture.md).
|
||||
|
||||
**Status:** first implementation. `createRTCSlot` and `slot.join()` join the
|
||||
session, connect to the transport, publish the local media and expose every
|
||||
@@ -19,6 +18,7 @@ nothing in Element Call's `src/`.
|
||||
```ts
|
||||
import {
|
||||
createRTCSlot,
|
||||
createSdkMatrixBackend,
|
||||
E2eeType,
|
||||
MatrixRTCMode,
|
||||
ObservableScope,
|
||||
@@ -28,15 +28,15 @@ import {
|
||||
const scope = new ObservableScope();
|
||||
const slot = createRTCSlot(
|
||||
scope,
|
||||
client, // a matrix-js-sdk MatrixClient, logged in and syncing
|
||||
room, // the matrix-js-sdk Room, from client.getRoom() once the join has synced
|
||||
{
|
||||
encryptionSystem: { kind: E2eeType.PER_PARTICIPANT },
|
||||
matrixRTCMode: MatrixRTCMode.Compatibility,
|
||||
},
|
||||
createSdkMatrixBackend(
|
||||
client, // a matrix-js-sdk MatrixClient, logged in and syncing
|
||||
room, // the matrix-js-sdk Room, from client.getRoom() once the join has synced
|
||||
),
|
||||
{ encryptionSystem: { kind: E2eeType.PER_PARTICIPANT } }, // the room's call, m.call#ROOM
|
||||
);
|
||||
const participation = slot.join({
|
||||
publish: [{ source: "microphone" }, { source: "camera" }],
|
||||
matrixRTCMode: MatrixRTCMode.Compatibility,
|
||||
});
|
||||
|
||||
// A <video> for each remote member's camera and an <audio> for its microphone.
|
||||
@@ -99,6 +99,7 @@ own only so that a host can install it as a git dependency (see
|
||||
```sh
|
||||
pnpm dev:sdk # the harness, https://localhost:3002
|
||||
pnpm build:sdk # dist/matrixrtc-sdk.js and dist/types
|
||||
pnpm build:sdk:development # the same, unminified
|
||||
pnpm test:playwright playwright/sdk # needs `pnpm backend`
|
||||
```
|
||||
|
||||
|
||||
+41
-64
@@ -10,8 +10,7 @@ interface.
|
||||
Element Call becomes one consumer of it: `CallViewModel` keeps what makes a session
|
||||
a _call_ (ringing, auto-leave, layout, sounds, reactions, settings, the host
|
||||
bridge) and takes everything else from the client. The dependency direction is
|
||||
therefore `Element Call → sdk`, never the reverse. What moved out of Element
|
||||
Call's `src/` to get there is listed in [`SdkMigration.md`](./SdkMigration.md).
|
||||
therefore `Element Call → sdk`, never the reverse.
|
||||
|
||||
## The architecture
|
||||
|
||||
@@ -121,10 +120,10 @@ LiveKit participants.
|
||||
The session discovers the transport from the homeserver and the backend prepares
|
||||
it, both before `join()`, so that the membership can name it and the first frames
|
||||
go out as soon as the state event is sent. Preparing is the backend's own
|
||||
business: for LiveKit the token exchange for the publisher connection, and
|
||||
with it whether that service can take over the delayed leave (assumed for a homeserver
|
||||
probed for a JWT service), which picks the delayed leave timings the join uses. The
|
||||
join waits for the publisher to hold its token, so that the LiveKit room exists
|
||||
business: for LiveKit the token exchange for the publisher connection, and the
|
||||
probe that decides whether the service that issued the token can take over the
|
||||
delayed leave, which picks the delayed leave timings the join uses. The join
|
||||
waits for the publisher to hold its token, so that the LiveKit room exists
|
||||
before a subscriber, who lacks the permission to create it, asks for a token
|
||||
of its own. The tracks are created once the membership is `joined`, with their
|
||||
upstream paused until then. A lobby that wants them earlier captures them with
|
||||
@@ -132,7 +131,10 @@ upstream paused until then. A lobby that wants them earlier captures them with
|
||||
hands the media to `join()` as `publish`: the tracks are moved, not shared — they
|
||||
leave the lobby's `tracks$`, their objects are finished, and the backend
|
||||
publishes the very same device tracks and the processor already running on them,
|
||||
so nothing is captured or initialised again at the join. The upstream flows
|
||||
so nothing is captured or initialised again at the join. Given the media quality
|
||||
the join is given, it opens the camera at the resolution the backend captures
|
||||
at, so that a join through a lobby publishes what a join without one does. The
|
||||
upstream flows
|
||||
exactly while the membership is `joined`: a sync outage pauses it, and `leave()`
|
||||
pauses it for good and sends the leave.
|
||||
|
||||
@@ -143,18 +145,18 @@ participation split in
|
||||
[`client-into-slot-session-split-plan.md`](./client-into-slot-session-split-plan.md);
|
||||
the sections below still describe `MatrixRTCClient` until that lands.
|
||||
|
||||
| Word | Meaning here | Elsewhere |
|
||||
| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------- |
|
||||
| slot | an `RTCSlot`: the namespace in a room that memberships join into, `application` plus `id`. It exists while the room does, with nobody in it too. Holds `members$`, its open or closed `status$`, and `join()` | the js-sdk `MatrixRTCSession` is one per slot; the MSC4143 slot event |
|
||||
| participation | an `RTCParticipation`: the span between our `join()` of a slot and our `leave()`. Holds the connection and its `state$`, `localMember$`, `remoteMembers$`, the connected transports and the data channel. Made by `slot.join()`, never reused | "session" is not used here, because in the js-sdk it means the slot |
|
||||
| member | an `RTCMember`: one membership in a slot with what the SDK derives from it, `rtcBackendIdentity`, `userId`, `deviceId`, `memberId`, `displayName$`, `avatarUrl$`, `transport$` and `applicationData$`. No media. What the slot hands out in `members$` | the js-sdk `CallMembership` behind it, which never leaves the SDK; Element Call's old "matrixLivekitMember" |
|
||||
| local member, remote member | `LocalRTCMember` and `RemoteRTCMember`: an `RTCMember` plus its `MemberMedia`, which only a participation can carry. The local one's tracks carry the controls. What the participation hands out in `localMember$` and `remoteMembers$` | LiveKit `LocalParticipant` and `RemoteParticipant`, which never leave the SDK |
|
||||
| media | a `MemberMedia`: what a member sends once it has arrived on its transport, `tracks$`, null while waiting, and `encryptionError$` beside it. The media backend supplies exactly these two fields per member | Element Call's `MediaViewModel` is a view of it |
|
||||
| track | a `MediaTrack`: one publication of a member, audio or video, with `source`, `kind`, `id` and the behaviors on it. `LocalAudioMediaTrack` and `LocalVideoMediaTrack` add the controls over our own | LiveKit `TrackPublication` and `Track`, which never leave the SDK |
|
||||
| publish request | a `PublishRequest`: a source, where to capture it from and how to encode it. Given at the join in `publish`, or later to `publish` on the participation | |
|
||||
| attach, detach | handing a `<video>` or `<audio>` element to a track and taking it back. The SDK owns the stream and the observers on the element | LiveKit `Track.attach` |
|
||||
| transport | an `RTCTransport`: where media is exchanged, a LiveKit service url today. Carries the raw js-sdk `Transport` from the membership and, in `resolved$`, what the backend fetched to connect to it | MSC4143 "focus" |
|
||||
| media backend | a `MediaBackend`: what carries the media, behind `sdk/src/media-backend/api.ts`. One per participation, chosen with `backend` in the join options; LiveKit under `sdk/src/media-backend/livekit/` is the one that exists | "SFU", a LiveKit room, a peer connection |
|
||||
| Word | Meaning here | Elsewhere |
|
||||
| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------- |
|
||||
| slot | an `RTCSlot`: the namespace in a room that memberships join into, `application` plus `id`. It exists while the room does, with nobody in it too. Holds `members$`, its open or closed `status$`, and `join()` | the js-sdk `MatrixRTCSession` is one per slot; the MSC4143 slot event |
|
||||
| participation | an `RTCParticipation`: the span between our `join()` of a slot and our `leave()`. Holds the connection and its `state$`, `localMember$`, `remoteMembers$`, the connected transports and the data channel. Made by `slot.join()`, never reused | "session" is not used here, because in the js-sdk it means the slot |
|
||||
| member | an `RTCMember`: one membership in a slot with what the SDK derives from it, `rtcBackendIdentity`, `userId`, `deviceId`, `memberId`, `matrixEventId$`, `displayName$`, `avatarUrl$`, `transport$` and `applicationData$`. No media. What the slot hands out in `members$` | the js-sdk `CallMembership` behind it, which never leaves the SDK; Element Call's old "matrixLivekitMember" |
|
||||
| local member, remote member | `LocalRTCMember` and `RemoteRTCMember`: an `RTCMember` plus its `MemberMedia`, which only a participation can carry. The local one's tracks carry the controls. What the participation hands out in `localMember$` and `remoteMembers$` | LiveKit `LocalParticipant` and `RemoteParticipant`, which never leave the SDK |
|
||||
| media | a `MemberMedia`: what a member sends once it has arrived on its transport, `tracks$`, null while waiting, and `encryptionError$` beside it. The media backend supplies exactly these two fields per member | Element Call's `MediaViewModel` is a view of it |
|
||||
| track | a `MediaTrack`: one publication of a member, audio or video, with `source`, `kind`, `id` and the behaviors on it. `LocalAudioMediaTrack` and `LocalVideoMediaTrack` add the controls over our own | LiveKit `TrackPublication` and `Track`, which never leave the SDK |
|
||||
| publish request | a `PublishRequest`: a source, where to capture it from and how to encode it. Given at the join in `publish`, or later to `publish` on the participation | |
|
||||
| attach, detach | handing a `<video>` or `<audio>` element to a track and taking it back. The SDK owns the stream and the observers on the element | LiveKit `Track.attach` |
|
||||
| transport | an `RTCTransport`: where media is exchanged, a LiveKit service url today. Carries the raw js-sdk `Transport` from the membership and, in `resolved$`, what the backend fetched to connect to it | MSC4143 "focus" |
|
||||
| media backend | a `MediaBackend`: what carries the media, behind `sdk/src/media-backend/api.ts`. One per participation, chosen with `backend` in the join options; LiveKit under `sdk/src/media-backend/livekit/` is the one that exists | "SFU", a LiveKit room, a peer connection |
|
||||
|
||||
Names use `RTC` in capitals, as the js-sdk does: `RTCSlot`, `RTCParticipation`,
|
||||
`RTCMember`, `matrixRTCMode`.
|
||||
@@ -586,56 +588,32 @@ without one, LiveKit is built from the LiveKit-flavoured client options.
|
||||
|
||||
A LiveKit transport comes in three shapes while MSC4195 settles: an SFU `url`,
|
||||
a JWT service `livekit_service_url`, or both. `media-backend/livekit/auth/`
|
||||
fronts the two flows and chooses between them from the shape, preferring the
|
||||
client-server API wherever the transport names a `url`:
|
||||
fronts the two flows and chooses between them per connection, from the shape
|
||||
and from the role we take on the transport:
|
||||
|
||||
| Transport | Publisher | Subscriber |
|
||||
| -------------------------- | ---------------------------------------------------------------- | ------------------------------------------------------------------ |
|
||||
| `url` only | client-server API `get_token`, no fallback | client-server API `get_token`, no fallback |
|
||||
| `livekit_service_url` only | JWT service `/sfu/get` (legacy identity) | JWT service `/get_token` (hashed identity) |
|
||||
| both | client-server API, else JWT service `/sfu/get` (legacy identity) | client-server API, else JWT service `/get_token` (hashed identity) |
|
||||
| Transport | Publisher | Subscriber |
|
||||
| -------------------------- | ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------- |
|
||||
| `url` only | client-server API `get_token`, no fallback | client-server API `get_token`, no fallback |
|
||||
| `livekit_service_url` only | JWT service `/sfu/get` (legacy identity) | JWT service `/get_token` (hashed identity) |
|
||||
| both | JWT service `/sfu/get` (legacy identity) | client-server API, falling back to the JWT service `/get_token` where the homeserver, or a widget host, has no MSC4195 |
|
||||
|
||||
A member whose transport names both is matched against either identity (since
|
||||
Element Call 0.28.1), so a publisher may take either flow. On the JWT service
|
||||
a publisher uses `/sfu/get`, the only endpoint that assigns the legacy
|
||||
`<user_id>:<device_id>` identity. A subscriber is matched by nobody and takes
|
||||
the hashed one.
|
||||
|
||||
The JWT service stands in only where our homeserver has no MSC4195 endpoints.
|
||||
A homeserver that has them advertises a `url`, so whether the API is usable is
|
||||
read off our own transport: `prepareLocalTransport` stores it with the local
|
||||
transport, and it is the one input, next to a transport's shape, to
|
||||
`chooseAuthFlow`. Where ours names only a JWT service, transports naming both
|
||||
go through that service from the start.
|
||||
|
||||
A homeserver may advertise a `url` and still lack the endpoints, as may a
|
||||
widget host. A token request is then answered with a 404, `M_NOT_FOUND` or
|
||||
`M_UNRECOGNIZED` (`isCsApiUnavailable`) and fails with
|
||||
`NoMatrix2AuthorizationService`, which the connection reports to the backend
|
||||
before the error surfaces. Where our transport names a JWT service too, the
|
||||
backend stores the local transport again with the API ruled out; the failed
|
||||
connection is stopped with its map and never shows as an error. A transport
|
||||
with a `url` alone has no fallback and fails the join. The MatrixRTC mode
|
||||
plays no part in the choice.
|
||||
|
||||
A connection is created with its flow and keeps it for life. The delayed leave
|
||||
is delegated through the publisher connection's flow, the one that issued its
|
||||
token, so that the service watches for the identity we publish under. A
|
||||
homeserver that issued the token is assumed to delegate. Only a JWT service is
|
||||
probed, before the join.
|
||||
A publisher on a transport with a service URL keeps the legacy
|
||||
`<user_id>:<device_id>` identity, because clients predating MSC4195 match a
|
||||
membership against that and nothing else; a subscriber is matched by nobody and
|
||||
takes the more private hashed identity. A publisher never falls back: a
|
||||
homeserver that advertises a `url` without implementing MSC4195 is misconfigured
|
||||
and fails with `NoMatrix2AuthorizationService`, so the admin hears about it.
|
||||
The MatrixRTC mode plays no part in the choice. The delayed leave is delegated
|
||||
through the same flow that issued the publisher's token, so that the identity
|
||||
the service watches for on the SFU is the one we publish under, and the
|
||||
delegation probe before the join asks only that service.
|
||||
|
||||
The client-server API needs the name of the homeserver the transport belongs to:
|
||||
our own homeserver asks that server for the token, over federation where it is
|
||||
not ours. The backend derives it from the member's user id, and from our own for
|
||||
the local transport. A JWT service is reached directly, so members of several
|
||||
homeservers advertising the same one share a connection.
|
||||
|
||||
Connections are keyed on the flow and what it authenticates against: the `url`
|
||||
plus the server name for the client-server API, the service URL for the JWT
|
||||
service. Transports with the same key would get us the same identity on the
|
||||
same SFU, so they share a connection. A connection map is built per local
|
||||
transport, so whether the API is usable is fixed for the life of a map and of
|
||||
every key in it; ruling the API out replaces the map.
|
||||
the local transport, and keys its connections on the transport plus the server
|
||||
name where the transport has a `url`. A JWT service is reached directly, so
|
||||
members of several homeservers advertising the same one share a connection.
|
||||
|
||||
## Media: `tracks$` and `MediaTrack`
|
||||
|
||||
@@ -803,7 +781,6 @@ sdk/
|
||||
src/utils/ mapScoped, network retry, display names, test helpers
|
||||
dev/ the harness (below)
|
||||
SdkArchitecture.md this document
|
||||
SdkMigration.md what moved from Element Call's src/ into the SDK
|
||||
```
|
||||
|
||||
The lint rule `element-call/sdk-import-boundary` keeps it that way: nothing under
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
# What moved from `src/` into the SDK
|
||||
|
||||
Element Call's `CallViewModel` used to do everything; now it consumes the SDK and
|
||||
keeps only what makes a session a call. This is the inventory of what moved out
|
||||
of `src/` on the way, so that a reader of either side knows where to look. It
|
||||
names source files, so it ages with the code; the shape they make is in
|
||||
[`SdkArchitecture.md`](./SdkArchitecture.md).
|
||||
|
||||
Everything in the table is gone from `src/`. Each module came with its tests;
|
||||
`sdk/src/utils/test.ts` and `test-fixtures.ts` are the subset of Element Call's
|
||||
test helpers they need. `Behavior`, `ObservableScope`, the observable operators,
|
||||
`E2eeType`, `EncryptionSystem` and `MatrixRTCMode` are re-exported from the SDK
|
||||
by their old `src/` paths, so the rest of Element Call did not have to change.
|
||||
|
||||
| Was in `src/` | Is in `sdk/src/` | What changed on the way |
|
||||
| ----------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `state/Behavior.ts`, `state/ObservableScope.ts`, `utils/observable.ts` | `reactive/` | as is |
|
||||
| `state/SessionBehaviors.ts` | `matrixrtc/JsRtcSessionBehaviors.ts` | the memberships and key rotation behaviors only |
|
||||
| `state/CallViewModel/localMember/HomeserverConnected.ts` | `matrixrtc/HomeserverConnected.ts` | the grace period defaults to `defaultSessionTimings` instead of `Config.get()` |
|
||||
| `state/CallViewModel/localMember/LocalMember.ts` | `matrixrtc/LocalMembership.ts`, `media-backend/livekit/LocalMedia.ts`, `participationState.ts` | split into the Matrix side, the media side and the state machine that combines them |
|
||||
| `state/CallViewModel/localMember/LocalTransport.ts`, `RtcTransportAutoDiscovery.ts` | `matrixrtc/LocalTransport.ts`, `TransportAutoDiscovery.ts` | the override and the fallback are transports from the options, not a setting and a resolved config |
|
||||
| `state/CallViewModel/remoteMembers/MatrixLivekitMembers.ts` | `media-backend/livekit/LivekitBackend.ts` (`mediaFor`) | matches participants to members inside the backend; the SDK hands out `RTCMember`s |
|
||||
| `state/CallViewModel/remoteMembers/MatrixMemberMetadata.ts`, `utils/displayname.ts` | `matrixrtc/MatrixMemberMetadata.ts`, `utils/displayname.ts` | as is |
|
||||
| `state/CallViewModel/remoteMembers/Connection.ts` | `media-backend/livekit/Connection.ts` | throws `MatrixRTCError`s; `ConnectionState` is a discriminated union; fetches its own token for its role |
|
||||
| `state/CallViewModel/remoteMembers/ConnectionFactory.ts` | `media-backend/livekit/ConnectionFactory.ts` | `LivekitConnectionFactory` builds the room options from the publish requests and `mediaQuality`, not from settings |
|
||||
| `state/CallViewModel/remoteMembers/ConnectionManager.ts` | `media-backend/livekit/ConnectionMap.ts` | keyed by `TransportLocator`; the publisher role is the local transport's |
|
||||
| `state/CallViewModel/localMember/Publisher.ts` | `media-backend/livekit/Publisher.ts` | rewritten on publish requests instead of `MuteStates` |
|
||||
| `livekit/openIDSFU.ts`, later `livekit/auth/` | `media-backend/livekit/auth/` | the flow is chosen by the transport's shape and our role; the delegated leave timeout is a parameter |
|
||||
| `livekit/options.ts` | `media-backend/livekit/livekitOptions.ts` | `buildLiveKitOptions(mediaQuality?)` only; the `Config` singleton is gone |
|
||||
| `e2ee/matrixKeyProvider.ts`, the key provider selection | `media-backend/livekit/MatrixKeyProvider.ts`, `KeyProvider.ts` | as is; selection keyed off `encryptionSystem` |
|
||||
| `e2ee/e2eeType.ts`, `EncryptionSystem` from `e2ee/sharedKeyManagement.ts` | `encryption.ts` | the React hooks stayed behind |
|
||||
| `MatrixRTCMode`, the timings and media quality types from `config/ConfigOptions.ts` | `config.ts` | `defaultSessionTimings` and `defaultMediaQuality` replace `DEFAULT_CONFIG` |
|
||||
| `utils/errors.ts` | `errors.ts` | `MatrixRTCError` with `code` and `category` replaces `ElementCallError`; messages are plain English, the host translates by code |
|
||||
| `doNetworkOperationWithRetry` from `utils/matrix.ts` | `utils/network.ts` | takes a `shouldRetry` predicate |
|
||||
| the join in `CallViewModel.ts` (`enterRTCSession`) | `matrixrtc/joinJsSdkSession.ts` | the timings and the delayed leave variant are parameters |
|
||||
| `livekit/MatrixAudioRenderer.tsx`, the participant reads in `state/media/` | `media-backend/livekit/LivekitMediaTrack.ts`, `LivekitMemberMedia.ts` | the view models get `MediaTrack`s with `attach`; nothing in `src/` imports a LiveKit participant any more |
|
||||
|
||||
## What still binds Element Call to LiveKit
|
||||
|
||||
Each is a gap in the SDK's API rather than something to rename; the import goes
|
||||
away when the SDK grows the piece. The names Element Call owes to the outside
|
||||
stay as they are: the `livekit.livekit_service_url` key in `config.json`, the
|
||||
persisted setting keys `extended-livekit-logs` and `custom-transport`, the
|
||||
Posthog fields `callBackend` and `callReconnectingCountLivekit`, the rageshake
|
||||
field `call_backend`, and the translated error strings.
|
||||
|
||||
| Gap | Where it shows |
|
||||
| ----------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ |
|
||||
| Preview before `join()`: local tracks for the lobby, handed out as `MediaTrack`s | `LobbyView` (`usePreviewTracks`), `VideoPreview` (`LocalVideoTrack`, `facingModeFromLocalTrack`) |
|
||||
| Device enumeration without LiveKit's helpers | `MediaDevices` (`createMediaDeviceObserver`), `CallView` (`Room.getLocalDevices`) |
|
||||
| A `logging` option: log level and a sink for the transport's logs | `initializer.tsx`, the `extended-livekit-logs` setting |
|
||||
| A `capabilities` field: output selection and background processors, asked of the SDK rather than of LiveKit | `CallFooterViewModel` (`supportsAudioOutputSelection`, `supportsBackgroundProcessors`) |
|
||||
| Element Call's error and analytics types on the SDK's | `PosthogEvents` (`DisconnectReason`), `errors.ts` (`ConnectionError`, `LivekitConnectionError`) |
|
||||
+3
-2
@@ -16,6 +16,7 @@ import { combineLatest, type Observable, of, switchMap } from "rxjs";
|
||||
import {
|
||||
type AudioMediaTrack,
|
||||
createRTCSlot,
|
||||
createSdkMatrixBackend,
|
||||
E2eeType,
|
||||
type LocalRTCMember,
|
||||
MatrixRTCMode,
|
||||
@@ -70,12 +71,12 @@ async function start(
|
||||
const room = await joinRoom(client, roomIdOrAlias);
|
||||
|
||||
const scope = new ObservableScope();
|
||||
const slot = createRTCSlot(scope, client, room, {
|
||||
const slot = createRTCSlot(scope, createSdkMatrixBackend(client, room), {
|
||||
encryptionSystem: { kind: E2eeType.PER_PARTICIPANT },
|
||||
matrixRTCMode: MatrixRTCMode.Compatibility,
|
||||
});
|
||||
const rtcParticipation = slot.join({
|
||||
publish: [{ source: "microphone" }, { source: "camera" }],
|
||||
matrixRTCMode: MatrixRTCMode.Compatibility,
|
||||
});
|
||||
rtcParticipation.state$.pipe(scope.bind()).subscribe((state) => {
|
||||
status.textContent =
|
||||
|
||||
+7
-2
@@ -57,6 +57,11 @@ export * from "./src/media-api";
|
||||
export * from "./src/media-backend/api";
|
||||
export { trackBySource$, type TrackOfSource } from "./src/utils/tracks";
|
||||
export { createRTCSlot } from "./src/RTCSlot";
|
||||
export {
|
||||
createSdkMatrixBackend,
|
||||
type SdkMatrixBackend,
|
||||
withEmitter,
|
||||
} from "./src/SdkMatrixBackend";
|
||||
export {
|
||||
createLivekitBackend,
|
||||
type LivekitBackendOptions,
|
||||
@@ -70,6 +75,6 @@ export {
|
||||
} from "./src/media-backend/livekit/videoProcessor";
|
||||
// For a developer panel to check a transport before using it
|
||||
export {
|
||||
authenticateWithTransport,
|
||||
type AuthenticateWithTransportParams,
|
||||
getSFUConfig as authenticateWithTransport,
|
||||
type GetSFUConfigParams as AuthenticateWithTransportParams,
|
||||
} from "./src/media-backend/livekit/auth";
|
||||
|
||||
+156
-28
@@ -13,7 +13,7 @@ import { type LocalVideoMediaTrack, type VideoProcessor } from "./media-api";
|
||||
describe("createLocalMedia", () => {
|
||||
it("opens the microphone and the camera in one request", async () => {
|
||||
const getUserMedia = fakeGetUserMedia();
|
||||
const media = createLocalMedia(getUserMedia);
|
||||
const media = createLocalMedia({ getUserMedia });
|
||||
|
||||
const tracks = await media.capture([
|
||||
{ source: "microphone", deviceId: "mic" },
|
||||
@@ -35,9 +35,34 @@ describe("createLocalMedia", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("opens a camera asked for without a resolution at the one a backend captures at", async () => {
|
||||
const getUserMedia = fakeGetUserMedia();
|
||||
const media = createLocalMedia({ getUserMedia });
|
||||
|
||||
await media.capture([{ source: "camera" }]);
|
||||
|
||||
expect(getUserMedia).toHaveBeenCalledExactlyOnceWith({
|
||||
video: { width: 1280, height: 720, frameRate: 30 },
|
||||
});
|
||||
});
|
||||
|
||||
it("opens the camera at the resolution of the media quality it is given", async () => {
|
||||
const getUserMedia = fakeGetUserMedia();
|
||||
const media = createLocalMedia({
|
||||
mediaQuality: { video: { max_resolution: 360 } },
|
||||
getUserMedia,
|
||||
});
|
||||
|
||||
await media.capture([{ source: "camera" }]);
|
||||
|
||||
expect(getUserMedia).toHaveBeenCalledExactlyOnceWith({
|
||||
video: { width: 640, height: 360, frameRate: 20 },
|
||||
});
|
||||
});
|
||||
|
||||
it("joins an identical capture still in flight rather than opening the devices again", async () => {
|
||||
const getUserMedia = fakeGetUserMedia();
|
||||
const media = createLocalMedia(getUserMedia);
|
||||
const media = createLocalMedia({ getUserMedia });
|
||||
const requests = [{ source: "camera" as const }];
|
||||
|
||||
const [first, second] = await Promise.all([
|
||||
@@ -52,7 +77,7 @@ describe("createLocalMedia", () => {
|
||||
|
||||
it("shows the processor's output, initialised once", async () => {
|
||||
const processor = fakeProcessor();
|
||||
const media = createLocalMedia(fakeGetUserMedia());
|
||||
const media = createLocalMedia({ getUserMedia: fakeGetUserMedia() });
|
||||
const [camera] = await media.capture([{ source: "camera", processor }]);
|
||||
const element = document.createElement("video");
|
||||
|
||||
@@ -65,7 +90,7 @@ describe("createLocalMedia", () => {
|
||||
it("hands the tracks over as they are: no second capture, no second init", async () => {
|
||||
const getUserMedia = fakeGetUserMedia();
|
||||
const processor = fakeProcessor();
|
||||
const media = createLocalMedia(getUserMedia);
|
||||
const media = createLocalMedia({ getUserMedia });
|
||||
const [microphone, camera] = await media.capture([
|
||||
{ source: "microphone" },
|
||||
{ source: "camera", processor },
|
||||
@@ -76,7 +101,7 @@ describe("createLocalMedia", () => {
|
||||
expect(taken.get("microphone")?.track).toBe(trackBehind(microphone));
|
||||
expect(taken.get("camera")).toEqual({
|
||||
track: trackBehind(camera),
|
||||
constraints: {},
|
||||
constraints: at720p(),
|
||||
muted: false,
|
||||
processor: { processor, processedTrack: processor.output },
|
||||
});
|
||||
@@ -89,7 +114,7 @@ describe("createLocalMedia", () => {
|
||||
});
|
||||
|
||||
it("finishes a handed-over track", async () => {
|
||||
const media = createLocalMedia(fakeGetUserMedia());
|
||||
const media = createLocalMedia({ getUserMedia: fakeGetUserMedia() });
|
||||
const [camera] = await media.capture([{ source: "camera" }]);
|
||||
const element = document.createElement("video");
|
||||
camera.attach(element);
|
||||
@@ -102,7 +127,7 @@ describe("createLocalMedia", () => {
|
||||
});
|
||||
|
||||
it("mutes by disabling the track and hands the mute over", async () => {
|
||||
const media = createLocalMedia(fakeGetUserMedia());
|
||||
const media = createLocalMedia({ getUserMedia: fakeGetUserMedia() });
|
||||
const [microphone] = await media.capture([{ source: "microphone" }]);
|
||||
|
||||
await expect(microphone.setEnabled(false)).resolves.toBe(false);
|
||||
@@ -115,7 +140,7 @@ describe("createLocalMedia", () => {
|
||||
it("switches the device by opening it anew", async () => {
|
||||
const getUserMedia = fakeGetUserMedia();
|
||||
const processor = fakeProcessor();
|
||||
const media = createLocalMedia(getUserMedia);
|
||||
const media = createLocalMedia({ getUserMedia });
|
||||
const [camera] = await media.capture([{ source: "camera", processor }]);
|
||||
const first = trackBehind(camera);
|
||||
const element = document.createElement("video");
|
||||
@@ -124,7 +149,7 @@ describe("createLocalMedia", () => {
|
||||
await camera.setDevice("other");
|
||||
|
||||
expect(getUserMedia).toHaveBeenLastCalledWith({
|
||||
video: { deviceId: { exact: "other" } },
|
||||
video: at720p({ deviceId: { exact: "other" } }),
|
||||
});
|
||||
expect(first.stop).toHaveBeenCalled();
|
||||
expect(processor.restart).toHaveBeenCalledOnce();
|
||||
@@ -132,28 +157,108 @@ describe("createLocalMedia", () => {
|
||||
expect(restartedOn).not.toBe(first);
|
||||
expect(input).toBe(vi.mocked(processor.init).mock.calls[0][1]);
|
||||
expect(tracksOn(element)).toEqual([processor.output]);
|
||||
expect(media.takeTracks().get("camera")?.constraints).toEqual({
|
||||
deviceId: { exact: "other" },
|
||||
expect(media.takeTracks().get("camera")?.constraints).toEqual(
|
||||
at720p({ deviceId: { exact: "other" } }),
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
gone: ["mic"],
|
||||
audio: { deviceId: { ideal: "mic" } },
|
||||
video: at720p({ deviceId: { exact: "cam" } }),
|
||||
},
|
||||
{
|
||||
gone: ["cam"],
|
||||
audio: { deviceId: { exact: "mic" } },
|
||||
video: at720p({ deviceId: { ideal: "cam" } }),
|
||||
},
|
||||
{
|
||||
gone: ["mic", "cam"],
|
||||
audio: { deviceId: { ideal: "mic" } },
|
||||
video: at720p({ deviceId: { ideal: "cam" } }),
|
||||
},
|
||||
])(
|
||||
"lets only a device that is gone off the one asked for: $gone",
|
||||
async ({ gone, audio, video }) => {
|
||||
const getUserMedia = without(gone, fakeGetUserMedia());
|
||||
const media = createLocalMedia({ getUserMedia });
|
||||
|
||||
const tracks = await media.capture([
|
||||
{ source: "microphone", deviceId: "mic" },
|
||||
{ source: "camera", deviceId: "cam" },
|
||||
]);
|
||||
|
||||
expect(getUserMedia).toHaveBeenLastCalledWith({ audio, video });
|
||||
expect(tracks.map((t) => t.source)).toEqual(["microphone", "camera"]);
|
||||
},
|
||||
);
|
||||
|
||||
it("asks twice for a single device that is gone", async () => {
|
||||
const getUserMedia = without(["cam"], fakeGetUserMedia());
|
||||
const media = createLocalMedia({ getUserMedia });
|
||||
|
||||
await media.capture([{ source: "camera", deviceId: "cam" }]);
|
||||
|
||||
expect(vi.mocked(getUserMedia).mock.calls).toEqual([
|
||||
[{ video: at720p({ deviceId: { exact: "cam" } }) }],
|
||||
[{ video: at720p({ deviceId: { ideal: "cam" } }) }],
|
||||
]);
|
||||
});
|
||||
|
||||
it("hands over the device that opened in place of the one that is gone", async () => {
|
||||
const getUserMedia = without(
|
||||
["cam"],
|
||||
fakeGetUserMedia({ deviceId: "built-in" }),
|
||||
);
|
||||
const media = createLocalMedia({ getUserMedia });
|
||||
|
||||
await media.capture([{ source: "camera", deviceId: "cam" }]);
|
||||
|
||||
expect(media.takeTracks().get("camera")?.constraints).toEqual(
|
||||
at720p({ deviceId: { exact: "built-in" } }),
|
||||
);
|
||||
});
|
||||
|
||||
it("takes a refusal that is not an Error for a device that is gone", async () => {
|
||||
const getUserMedia = vi.mocked(fakeGetUserMedia());
|
||||
getUserMedia.mockRejectedValueOnce({ name: "OverconstrainedError" });
|
||||
const media = createLocalMedia({ getUserMedia });
|
||||
|
||||
await media.capture([{ source: "camera", deviceId: "cam" }]);
|
||||
|
||||
expect(getUserMedia).toHaveBeenLastCalledWith({
|
||||
video: at720p({ deviceId: { ideal: "cam" } }),
|
||||
});
|
||||
});
|
||||
|
||||
it("opens the browser's choice where the device asked for is gone", async () => {
|
||||
it("does not ask again where the device is there and refused", async () => {
|
||||
const getUserMedia = vi.mocked(fakeGetUserMedia());
|
||||
getUserMedia.mockRejectedValueOnce(overconstrained());
|
||||
const media = createLocalMedia(getUserMedia);
|
||||
const denied = Object.assign(new Error(), { name: "NotAllowedError" });
|
||||
getUserMedia.mockRejectedValueOnce(denied);
|
||||
const media = createLocalMedia({ getUserMedia });
|
||||
|
||||
const tracks = await media.capture([
|
||||
{ source: "microphone", deviceId: "unplugged" },
|
||||
{ source: "camera", deviceId: "cam" },
|
||||
]);
|
||||
await expect(
|
||||
media.capture([{ source: "camera", deviceId: "cam" }]),
|
||||
).rejects.toBe(denied);
|
||||
|
||||
expect(getUserMedia).toHaveBeenLastCalledWith({ audio: {}, video: {} });
|
||||
expect(tracks.map((t) => t.source)).toEqual(["microphone", "camera"]);
|
||||
expect(getUserMedia).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("rejects where no device opens at all", async () => {
|
||||
const refusal = overconstrained();
|
||||
const media = createLocalMedia({
|
||||
getUserMedia: vi.fn().mockRejectedValue(refusal),
|
||||
});
|
||||
|
||||
await expect(
|
||||
media.capture([{ source: "camera", deviceId: "cam" }]),
|
||||
).rejects.toBe(refusal);
|
||||
});
|
||||
|
||||
it("keeps the camera it has where another cannot be opened", async () => {
|
||||
const getUserMedia = vi.mocked(fakeGetUserMedia());
|
||||
const media = createLocalMedia(getUserMedia);
|
||||
const media = createLocalMedia({ getUserMedia });
|
||||
const [camera] = await media.capture([
|
||||
{ source: "camera", deviceId: "cam" },
|
||||
]);
|
||||
@@ -171,7 +276,7 @@ describe("createLocalMedia", () => {
|
||||
|
||||
it("lets go of the device it was opened on to face the other way", async () => {
|
||||
const getUserMedia = fakeGetUserMedia({ facingMode: "user" });
|
||||
const media = createLocalMedia(getUserMedia);
|
||||
const media = createLocalMedia({ getUserMedia });
|
||||
const [camera] = (await media.capture([
|
||||
{ source: "camera", deviceId: "front" },
|
||||
])) as [LocalVideoMediaTrack];
|
||||
@@ -179,13 +284,13 @@ describe("createLocalMedia", () => {
|
||||
await camera.switchFacingMode();
|
||||
|
||||
expect(getUserMedia).toHaveBeenLastCalledWith({
|
||||
video: { facingMode: "environment" },
|
||||
video: at720p({ facingMode: "environment" }),
|
||||
});
|
||||
});
|
||||
|
||||
it("reports the facing mode and switches it", async () => {
|
||||
const getUserMedia = fakeGetUserMedia({ facingMode: "user" });
|
||||
const media = createLocalMedia(getUserMedia);
|
||||
const media = createLocalMedia({ getUserMedia });
|
||||
const [camera] = (await media.capture([{ source: "camera" }])) as [
|
||||
LocalVideoMediaTrack,
|
||||
];
|
||||
@@ -194,13 +299,13 @@ describe("createLocalMedia", () => {
|
||||
await camera.switchFacingMode();
|
||||
|
||||
expect(getUserMedia).toHaveBeenLastCalledWith({
|
||||
video: { facingMode: "environment" },
|
||||
video: at720p({ facingMode: "environment" }),
|
||||
});
|
||||
});
|
||||
|
||||
// As the built-in camera of a Mac
|
||||
it("takes a camera that doesn't say which way it faces to face the user", async () => {
|
||||
const media = createLocalMedia(fakeGetUserMedia());
|
||||
const media = createLocalMedia({ getUserMedia: fakeGetUserMedia() });
|
||||
const [camera] = (await media.capture([{ source: "camera" }])) as [
|
||||
LocalVideoMediaTrack,
|
||||
];
|
||||
@@ -208,7 +313,7 @@ describe("createLocalMedia", () => {
|
||||
});
|
||||
|
||||
it("releases one device and stops the rest", async () => {
|
||||
const media = createLocalMedia(fakeGetUserMedia());
|
||||
const media = createLocalMedia({ getUserMedia: fakeGetUserMedia() });
|
||||
const [microphone, camera] = await media.capture([
|
||||
{ source: "microphone" },
|
||||
{ source: "camera" },
|
||||
@@ -225,7 +330,7 @@ describe("createLocalMedia", () => {
|
||||
});
|
||||
|
||||
it("refuses a screen share", async () => {
|
||||
const media = createLocalMedia(fakeGetUserMedia());
|
||||
const media = createLocalMedia({ getUserMedia: fakeGetUserMedia() });
|
||||
await expect(media.capture([{ source: "screenShare" }])).rejects.toThrow(
|
||||
"screen share",
|
||||
);
|
||||
@@ -273,6 +378,29 @@ function fakeGetUserMedia(videoSettings?: MediaTrackSettings): GetUserMedia {
|
||||
});
|
||||
}
|
||||
|
||||
/** Camera constraints with the resolution a request without one is opened at. */
|
||||
function at720p(
|
||||
constraints: MediaTrackConstraints = {},
|
||||
): MediaTrackConstraints {
|
||||
return { ...constraints, width: 1280, height: 720, frameRate: 30 };
|
||||
}
|
||||
|
||||
/** A browser these devices are unplugged from: asked for one of them exactly, it refuses. */
|
||||
function without(gone: string[], getUserMedia: GetUserMedia): GetUserMedia {
|
||||
return vi.fn(async (constraints: MediaStreamConstraints) => {
|
||||
for (const wanted of [constraints.audio, constraints.video]) {
|
||||
const deviceId = typeof wanted === "object" ? wanted.deviceId : undefined;
|
||||
const exact =
|
||||
typeof deviceId === "object" && !Array.isArray(deviceId)
|
||||
? deviceId.exact
|
||||
: undefined;
|
||||
if (typeof exact === "string" && gone.includes(exact))
|
||||
throw overconstrained();
|
||||
}
|
||||
return getUserMedia(constraints);
|
||||
});
|
||||
}
|
||||
|
||||
function overconstrained(): Error {
|
||||
return Object.assign(new Error("deviceId"), { name: "OverconstrainedError" });
|
||||
}
|
||||
|
||||
+80
-35
@@ -7,6 +7,11 @@ Please see LICENSE in the repository root for full details.
|
||||
|
||||
import { BehaviorSubject, type Observable, of } from "rxjs";
|
||||
|
||||
import {
|
||||
cameraCaptureResolution,
|
||||
type CaptureResolution,
|
||||
type MediaQuality,
|
||||
} from "./config";
|
||||
import { MatrixRTCError } from "./errors";
|
||||
import {
|
||||
type HandedOverTrack,
|
||||
@@ -28,15 +33,28 @@ export type GetUserMedia = (
|
||||
constraints: MediaStreamConstraints,
|
||||
) => Promise<MediaStream>;
|
||||
|
||||
export interface LocalMediaOptions {
|
||||
/**
|
||||
* The media quality the join is given. A camera asked for without a
|
||||
* resolution is opened at the one this means, as the backend opens it at
|
||||
* the join; left to the browser it would be published at a lower one.
|
||||
*/
|
||||
mediaQuality?: MediaQuality;
|
||||
/** In place of the browser's, for a test. */
|
||||
getUserMedia?: GetUserMedia;
|
||||
}
|
||||
|
||||
/**
|
||||
* Local media on the browser's devices alone, for a lobby ahead of a join:
|
||||
* no backend is involved, so whichever backend joins can take the tracks
|
||||
* over. Activity and level are not measured; stats are none.
|
||||
*/
|
||||
export function createLocalMedia(
|
||||
getUserMedia: GetUserMedia = async (constraints) =>
|
||||
export function createLocalMedia({
|
||||
mediaQuality,
|
||||
getUserMedia = async (constraints) =>
|
||||
navigator.mediaDevices.getUserMedia(constraints),
|
||||
): LocalMedia {
|
||||
}: LocalMediaOptions = {}): LocalMedia {
|
||||
const cameraResolution = cameraCaptureResolution(mediaQuality);
|
||||
const capturedTracks = new Map<Source, CapturedTrack>();
|
||||
const requests = new Map<Source, Request>();
|
||||
const tracks$ = new BehaviorSubject<
|
||||
@@ -80,10 +98,10 @@ export function createLocalMedia(
|
||||
}
|
||||
const { stream, constraints } = await open(getUserMedia, {
|
||||
microphone: bySource.has("microphone")
|
||||
? trackConstraints(bySource.get("microphone")!)
|
||||
? trackConstraints(bySource.get("microphone")!, cameraResolution)
|
||||
: undefined,
|
||||
camera: bySource.has("camera")
|
||||
? trackConstraints(bySource.get("camera")!)
|
||||
? trackConstraints(bySource.get("camera")!, cameraResolution)
|
||||
: undefined,
|
||||
});
|
||||
const captured: CapturedTrack[] = [];
|
||||
@@ -146,39 +164,68 @@ type SourceConstraints = Partial<Record<Source, MediaTrackConstraints>>;
|
||||
|
||||
/**
|
||||
* Opens the devices asked for. Where one of them is gone, as a remembered
|
||||
* choice that was unplugged, the browser picks instead.
|
||||
*
|
||||
* This is needed because we use `exact` device ids: an exact request for a
|
||||
* device that no longer exists fails, where a preferred one would have opened
|
||||
* another device. Without the retry here a stale choice would open nothing.
|
||||
* choice that was unplugged, that source opens on another device and the
|
||||
* other source keeps the device picked: an exact request for a device that no
|
||||
* longer exists would otherwise open nothing.
|
||||
*/
|
||||
async function open(
|
||||
getUserMedia: GetUserMedia,
|
||||
constraints: SourceConstraints,
|
||||
): Promise<{ stream: MediaStream; constraints: SourceConstraints }> {
|
||||
const streamOf = async (wanted: SourceConstraints): Promise<MediaStream> =>
|
||||
getUserMedia({
|
||||
...(wanted.microphone && { audio: wanted.microphone }),
|
||||
...(wanted.camera && { video: wanted.camera }),
|
||||
});
|
||||
try {
|
||||
return { stream: await streamOf(constraints), constraints };
|
||||
} catch (e) {
|
||||
if (!(e instanceof Error) || e.name !== "OverconstrainedError") throw e;
|
||||
const anyDevice: SourceConstraints = {
|
||||
...(constraints.microphone && {
|
||||
microphone: { ...constraints.microphone, deviceId: undefined },
|
||||
}),
|
||||
...(constraints.camera && {
|
||||
camera: { ...constraints.camera, deviceId: undefined },
|
||||
}),
|
||||
};
|
||||
return { stream: await streamOf(anyDevice), constraints: anyDevice };
|
||||
let refusal: unknown;
|
||||
for (const attempt of attempts(constraints)) {
|
||||
try {
|
||||
const stream = await getUserMedia({
|
||||
...(attempt.microphone && { audio: attempt.microphone }),
|
||||
...(attempt.camera && { video: attempt.camera }),
|
||||
});
|
||||
return { stream, constraints: attempt };
|
||||
} catch (e) {
|
||||
if (!isOverconstrained(e)) throw e;
|
||||
refusal ??= e;
|
||||
}
|
||||
}
|
||||
throw refusal;
|
||||
}
|
||||
|
||||
/**
|
||||
* As asked, then with one source let off its device, then both: the refusal
|
||||
* does not say which of the two devices is gone.
|
||||
*/
|
||||
function attempts(wanted: SourceConstraints): SourceConstraints[] {
|
||||
const { microphone, camera } = wanted;
|
||||
const camera_ = camera && relaxed(camera);
|
||||
const microphone_ = microphone && relaxed(microphone);
|
||||
return [
|
||||
wanted,
|
||||
...(camera_ ? [{ ...wanted, camera: camera_ }] : []),
|
||||
...(microphone_ ? [{ ...wanted, microphone: microphone_ }] : []),
|
||||
...(camera_ && microphone_
|
||||
? [{ microphone: microphone_, camera: camera_ }]
|
||||
: []),
|
||||
];
|
||||
}
|
||||
|
||||
/** The same request with its device preferred, not required; nothing where it requires none. */
|
||||
function relaxed(
|
||||
constraints: MediaTrackConstraints,
|
||||
): MediaTrackConstraints | undefined {
|
||||
const { deviceId } = constraints;
|
||||
if (typeof deviceId !== "object" || Array.isArray(deviceId)) return undefined;
|
||||
if (deviceId.exact === undefined) return undefined;
|
||||
return { ...constraints, deviceId: { ideal: deviceId.exact } };
|
||||
}
|
||||
|
||||
/** By name: the refusal is not an `Error` in every browser. */
|
||||
function isOverconstrained(e: unknown): boolean {
|
||||
return (e as { name?: unknown } | null)?.name === "OverconstrainedError";
|
||||
}
|
||||
|
||||
/** The constraints a request means to the browser. */
|
||||
function trackConstraints(request: Request): MediaTrackConstraints {
|
||||
function trackConstraints(
|
||||
request: Request,
|
||||
cameraResolution: CaptureResolution,
|
||||
): MediaTrackConstraints {
|
||||
// THE FIX for "cannot switch cameras in Chrome" (#4479), first capture.
|
||||
// `exact` makes the browser open this device or fail. A plain
|
||||
// `deviceId: "abc"` is only a wish, and Chromium ignores the wish and
|
||||
@@ -187,14 +234,12 @@ function trackConstraints(request: Request): MediaTrackConstraints {
|
||||
deviceId: { exact: request.deviceId },
|
||||
};
|
||||
if (request.source === "microphone") return { ...device, ...request.capture };
|
||||
const resolution = request.capture?.resolution;
|
||||
const resolution = request.capture?.resolution ?? cameraResolution;
|
||||
return {
|
||||
...device,
|
||||
...(resolution && {
|
||||
width: resolution.width,
|
||||
height: resolution.height,
|
||||
frameRate: resolution.frameRate,
|
||||
}),
|
||||
width: resolution.width,
|
||||
height: resolution.height,
|
||||
frameRate: resolution.frameRate,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -22,7 +22,6 @@ import {
|
||||
type ParticipationState,
|
||||
type RTCMember,
|
||||
type RTCParticipationOptions,
|
||||
type RTCSlot,
|
||||
type TransportMetadata,
|
||||
} from "./api";
|
||||
import { defaultSessionTimings, MatrixRTCMode } from "./config";
|
||||
@@ -86,6 +85,7 @@ function member(
|
||||
rtcBackendIdentity: overrides.memberId,
|
||||
backendIdentities: [overrides.memberId],
|
||||
deviceId: "DEV",
|
||||
matrixEventId$: constant(`$${overrides.memberId}`),
|
||||
transport$: constant(metadata(transport)),
|
||||
applicationData$: constant({}),
|
||||
displayName$: constant(overrides.userId),
|
||||
@@ -111,7 +111,6 @@ interface FakeBackend {
|
||||
|
||||
function setup(
|
||||
options: Partial<RTCParticipationOptions> = {},
|
||||
slotOptions: { matrixRTCMode?: MatrixRTCMode } = {},
|
||||
{
|
||||
homeserverTransports = [transport],
|
||||
memberships = [],
|
||||
@@ -191,19 +190,24 @@ function setup(
|
||||
scope,
|
||||
{
|
||||
client,
|
||||
room,
|
||||
slot: {} as RTCSlot,
|
||||
jsSdkSession: mockedSession,
|
||||
members$: scope.behavior(members$),
|
||||
transports: { get: metadata, connected$: constant([]) },
|
||||
slotOptions: {
|
||||
matrixRTCMode: MatrixRTCMode.Compatibility,
|
||||
encryptionSystem: { kind: E2eeType.PER_PARTICIPANT },
|
||||
...slotOptions,
|
||||
slot: {
|
||||
roomId: room.roomId,
|
||||
application: "m.call",
|
||||
id: "ROOM",
|
||||
status$: constant(undefined),
|
||||
members$: scope.behavior(members$),
|
||||
},
|
||||
jsSdkSession: mockedSession,
|
||||
transports: { get: metadata, connected$: constant([]) },
|
||||
slotOptions: { encryptionSystem: { kind: E2eeType.PER_PARTICIPANT } },
|
||||
logger,
|
||||
},
|
||||
{ publish: [], backend: backendFactory, ...options },
|
||||
{
|
||||
publish: [],
|
||||
matrixRTCMode: MatrixRTCMode.Compatibility,
|
||||
backend: backendFactory,
|
||||
...options,
|
||||
},
|
||||
);
|
||||
const states: ParticipationState[] = [];
|
||||
participation.state$.subscribe((state) => states.push(state));
|
||||
@@ -254,7 +258,6 @@ describe("createRTCParticipation", () => {
|
||||
fociPreferred: [{ type: "livekit", url: "wss://sfu.example.org" }],
|
||||
});
|
||||
const { join, fake } = setup(
|
||||
{},
|
||||
{},
|
||||
{ homeserverTransports: [], memberships: [bobOnSfu] },
|
||||
);
|
||||
@@ -349,7 +352,7 @@ describe("createRTCParticipation", () => {
|
||||
});
|
||||
compatibility.scope.end();
|
||||
|
||||
const matrix2 = setup({}, { matrixRTCMode: MatrixRTCMode.Matrix_2_0 });
|
||||
const matrix2 = setup({ matrixRTCMode: MatrixRTCMode.Matrix_2_0 });
|
||||
const { memberId } = matrix2.fake.context.ownMembershipIdentity;
|
||||
expect(memberId).not.toBe(legacyMemberId);
|
||||
expect(memberId).toMatch(/^[0-9a-f-]{36}$/);
|
||||
|
||||
+53
-33
@@ -5,7 +5,7 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { type MatrixClient, type Room } from "matrix-js-sdk";
|
||||
import { type MatrixClient } from "matrix-js-sdk";
|
||||
import { type Logger } from "matrix-js-sdk/lib/logger";
|
||||
import {
|
||||
type MatrixRTCSession as JsSdkRTCSession,
|
||||
@@ -30,19 +30,17 @@ import {
|
||||
|
||||
import { defaultSessionTimings, MatrixRTCMode } from "./config";
|
||||
import { E2eeType } from "./encryption";
|
||||
import { type Behavior } from "./reactive/Behavior";
|
||||
import { type ObservableScope } from "./reactive/ObservableScope";
|
||||
import { generateItems } from "./reactive/observable";
|
||||
import { mapScoped } from "./utils/mapScoped";
|
||||
import {
|
||||
type ParticipationSlot,
|
||||
type DataMessage,
|
||||
type LocalRTCMember,
|
||||
type ParticipationState,
|
||||
type RemoteRTCMember,
|
||||
type RTCMember,
|
||||
type RTCParticipation,
|
||||
type RTCParticipationOptions,
|
||||
type RTCSlot,
|
||||
type RTCSlotOptions,
|
||||
} from "./api";
|
||||
import {
|
||||
@@ -67,15 +65,34 @@ import { createKeyRotationSuppressed$ } from "./matrixrtc/JsRtcSessionBehaviors"
|
||||
import { type TransportRegistry } from "./matrixrtc/Transports";
|
||||
import { participationState } from "./participationState";
|
||||
|
||||
/** What the slot lends a participation. */
|
||||
/** What is needed for our own participation. */
|
||||
export interface ParticipationDeps {
|
||||
client: MatrixClient;
|
||||
room: Room;
|
||||
slot: RTCSlot;
|
||||
client: Pick<
|
||||
MatrixClient,
|
||||
// Our own membership identity
|
||||
| "getUserId"
|
||||
| "getDeviceId"
|
||||
// Local transport discovery
|
||||
| "getDomain"
|
||||
| "getRTCTransports"
|
||||
// LiveKit auth: `getOpenIdToken` for the JWT service flow, `getLivekitToken`
|
||||
// for the client-server API flow (MSC4195), `delegateDelayedLeave` and
|
||||
// `baseUrl` for the delayed leave delegation and its probe
|
||||
| "getOpenIdToken"
|
||||
| "getLivekitToken"
|
||||
| "delegateDelayedLeave"
|
||||
| "baseUrl"
|
||||
// Homeserver connection: whether the client is syncing
|
||||
| "getSyncState"
|
||||
// `on`/`off`, to listen for:
|
||||
// - `ClientEvent.Sync` (homeserver connection)
|
||||
| "on"
|
||||
| "off"
|
||||
>;
|
||||
slot: ParticipationSlot;
|
||||
jsSdkSession: JsSdkRTCSession;
|
||||
members$: Behavior<RTCMember[]>;
|
||||
transports: TransportRegistry;
|
||||
slotOptions: Pick<RTCSlotOptions, "matrixRTCMode" | "encryptionSystem">;
|
||||
slotOptions: RTCSlotOptions;
|
||||
logger: Logger;
|
||||
}
|
||||
|
||||
@@ -94,16 +111,19 @@ export function createRTCParticipation(
|
||||
scope: ObservableScope,
|
||||
{
|
||||
client,
|
||||
room,
|
||||
slot,
|
||||
jsSdkSession,
|
||||
members$,
|
||||
transports,
|
||||
slotOptions: { matrixRTCMode, encryptionSystem },
|
||||
slotOptions: { encryptionSystem },
|
||||
logger: parentLogger,
|
||||
}: ParticipationDeps,
|
||||
options: RTCParticipationOptions,
|
||||
): ParticipationInternals {
|
||||
const { matrixRTCMode } = options;
|
||||
const { roomId, members$ } = slot;
|
||||
// The full `{application}#{id}`, which the auth service and the other
|
||||
// members key the media room on
|
||||
const slotId = jsSdkSession.slotId;
|
||||
const logger = parentLogger.getChild("[RTCParticipation]");
|
||||
const userId = client.getUserId()!;
|
||||
const deviceId = client.getDeviceId()!;
|
||||
@@ -122,8 +142,8 @@ export function createRTCParticipation(
|
||||
};
|
||||
|
||||
const backend = createBackend(scope, client, options, {
|
||||
roomId: room.roomId,
|
||||
slotId: jsSdkSession.slotId,
|
||||
roomId,
|
||||
slotId,
|
||||
ownMembershipIdentity,
|
||||
publish: options.publish,
|
||||
encryptionSystem,
|
||||
@@ -144,8 +164,8 @@ export function createRTCParticipation(
|
||||
// to come back later rather than wait in a half-working lobby
|
||||
memberships: jsSdkSession.memberships,
|
||||
ownMembershipIdentity,
|
||||
roomId: room.roomId,
|
||||
slotId: jsSdkSession.slotId,
|
||||
roomId,
|
||||
slotId,
|
||||
logger,
|
||||
})
|
||||
: null;
|
||||
@@ -175,21 +195,15 @@ export function createRTCParticipation(
|
||||
timings.syncDisconnectGracePeriodMs,
|
||||
),
|
||||
joinMatrixRTC: (transport, delayedLeave) =>
|
||||
joinJsSdkSession(
|
||||
room.roomId,
|
||||
jsSdkSession,
|
||||
ownMembershipIdentity,
|
||||
transport,
|
||||
{
|
||||
encryptMedia: encryptionSystem.kind !== E2eeType.NONE,
|
||||
matrixRTCMode,
|
||||
sendNotificationType: options.sendNotificationType,
|
||||
callIntent: options.callIntent,
|
||||
applicationData: options.applicationData,
|
||||
timings,
|
||||
delayedLeave,
|
||||
},
|
||||
),
|
||||
joinJsSdkSession(roomId, jsSdkSession, ownMembershipIdentity, transport, {
|
||||
encryptMedia: encryptionSystem.kind !== E2eeType.NONE,
|
||||
matrixRTCMode,
|
||||
sendNotificationType: options.sendNotificationType,
|
||||
callIntent: options.callIntent,
|
||||
applicationData: options.applicationData,
|
||||
timings,
|
||||
delayedLeave,
|
||||
}),
|
||||
membershipManagerError$: fromEvent(
|
||||
jsSdkSession,
|
||||
MatrixRTCSessionEvent.MembershipManagerError,
|
||||
@@ -315,7 +329,13 @@ export function createRTCParticipation(
|
||||
/** The host's backend, or LiveKit configured from the participation options. */
|
||||
function createBackend(
|
||||
scope: ObservableScope,
|
||||
client: MatrixClient,
|
||||
client: Pick<
|
||||
MatrixClient,
|
||||
// LiveKit auth: `getOpenIdToken` for the JWT service flow, `getLivekitToken`
|
||||
// for the client-server API flow (MSC4195), `delegateDelayedLeave` and
|
||||
// `baseUrl` for the delayed leave delegation and its probe
|
||||
"getOpenIdToken" | "getLivekitToken" | "delegateDelayedLeave" | "baseUrl"
|
||||
>,
|
||||
{ backend, mediaQuality }: RTCParticipationOptions,
|
||||
context: MediaBackendContext,
|
||||
): MediaBackend {
|
||||
|
||||
+202
-9
@@ -5,23 +5,39 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { type MatrixClient, type Room } from "matrix-js-sdk";
|
||||
import { EMPTY } from "rxjs";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { type MatrixClient, type Room, SyncState } from "matrix-js-sdk";
|
||||
import { EventType } from "matrix-js-sdk/lib/@types/event";
|
||||
import { type MatrixEvent } from "matrix-js-sdk/lib/models/event";
|
||||
import {
|
||||
type RoomState,
|
||||
RoomStateEvent,
|
||||
} from "matrix-js-sdk/lib/models/room-state";
|
||||
import { RoomStickyEventsEvent } from "matrix-js-sdk/lib/models/room-sticky-events";
|
||||
|
||||
import {
|
||||
MatrixRTCSessionEvent,
|
||||
type MatrixRTCSessionEventHandlerMap,
|
||||
} from "matrix-js-sdk/lib/matrixrtc";
|
||||
|
||||
import { createRTCSlot } from "./RTCSlot";
|
||||
import { type RTCSlotOptions } from "./api";
|
||||
import { type SdkMatrixBackend } from "./SdkMatrixBackend";
|
||||
import { ObservableScope } from "./reactive/ObservableScope";
|
||||
import { type RTCParticipationOptions, type RTCSlotOptions } from "./api";
|
||||
import { MatrixRTCMode } from "./config";
|
||||
import { E2eeType } from "./encryption";
|
||||
import { mockEmitter, MockRTCSession, testScope } from "./utils/test";
|
||||
import { MatrixRTCError } from "./errors";
|
||||
import { type MediaBackend, MediaConnectionState } from "./media-backend/api";
|
||||
import { constant } from "./reactive/Behavior";
|
||||
import {
|
||||
mockEmitter,
|
||||
mockRtcMembership,
|
||||
MockRTCSession,
|
||||
testScope,
|
||||
} from "./utils/test";
|
||||
|
||||
const options: RTCSlotOptions = {
|
||||
matrixRTCMode: MatrixRTCMode.Compatibility,
|
||||
encryptionSystem: { kind: E2eeType.NONE },
|
||||
};
|
||||
|
||||
@@ -34,28 +50,140 @@ function setup(): {
|
||||
...mockEmitter(),
|
||||
roomId: "!room:example.org",
|
||||
getMembersWithMembership: (): [] => [],
|
||||
// An empty room, for a session of the slot's own
|
||||
getLiveTimeline: () => ({ getState: (): undefined => undefined }),
|
||||
hasMembershipState: (): boolean => false,
|
||||
getVersion: (): string => "11",
|
||||
_unstable_getStickyEvents: (): [] => [],
|
||||
} as unknown as Room;
|
||||
const session = new MockRTCSession(room);
|
||||
const client = {
|
||||
...mockEmitter(),
|
||||
getUserId: (): string => "@alice:example.org",
|
||||
getDeviceId: (): string => "AAAA",
|
||||
matrixRTC: { getRoomSession: (): MockRTCSession => session },
|
||||
} as unknown as MatrixClient;
|
||||
return { client, room, session };
|
||||
}
|
||||
|
||||
function backendOf(client: MatrixClient, room: Room): SdkMatrixBackend {
|
||||
return {
|
||||
...client,
|
||||
...room,
|
||||
clientEmitter: client,
|
||||
roomEmitter: room,
|
||||
} as unknown as SdkMatrixBackend;
|
||||
}
|
||||
|
||||
/** A media backend whose transport never gets ready: a participation on it stays waiting. */
|
||||
function idleBackend(): MediaBackend {
|
||||
return {
|
||||
transportTypes: ["livekit"],
|
||||
prepareLocalTransport: async () => new Promise(() => {}),
|
||||
delegateDelayedLeave: vi.fn(),
|
||||
local: {
|
||||
connectionState$: constant(MediaConnectionState.Initialized),
|
||||
setPublishing: vi.fn(),
|
||||
publishError$: constant(null),
|
||||
publish: vi.fn(),
|
||||
unpublish: vi.fn(),
|
||||
tracks$: constant(null),
|
||||
encryptionError$: EMPTY,
|
||||
},
|
||||
mediaFor: vi.fn(),
|
||||
connections$: constant([]),
|
||||
setAudioOutputDeviceId: vi.fn(),
|
||||
sendData: vi.fn(),
|
||||
data$: EMPTY,
|
||||
};
|
||||
}
|
||||
|
||||
describe("createRTCSlot", () => {
|
||||
describe("session", () => {
|
||||
it("joins the room's call slot by default", () => {
|
||||
const { client, room } = setup();
|
||||
const slot = createRTCSlot(testScope(), backendOf(client, room), options);
|
||||
expect(slot).toMatchObject({ application: "m.call", id: "ROOM" });
|
||||
});
|
||||
|
||||
it("joins the slot the options name", () => {
|
||||
const { client, room } = setup();
|
||||
const slot = createRTCSlot(testScope(), backendOf(client, room), {
|
||||
...options,
|
||||
slotDescription: { application: "io.element.example", id: "" },
|
||||
});
|
||||
expect(slot).toMatchObject({ application: "io.element.example", id: "" });
|
||||
});
|
||||
|
||||
it("stops its own session when the scope ends", async () => {
|
||||
const { client, room } = setup();
|
||||
const off = vi.spyOn(room, "off");
|
||||
const scope = new ObservableScope();
|
||||
createRTCSlot(scope, backendOf(client, room), options);
|
||||
|
||||
scope.end();
|
||||
await vi.waitFor(() =>
|
||||
expect(off).toHaveBeenCalledWith(
|
||||
RoomStickyEventsEvent.Update,
|
||||
expect.any(Function),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it("leaves a session it is given to its caller", () => {
|
||||
const { client, room, session } = setup();
|
||||
const given = session.asMockedSession();
|
||||
given.stop = vi.fn();
|
||||
const scope = new ObservableScope();
|
||||
createRTCSlot(scope, backendOf(client, room), options, given);
|
||||
|
||||
scope.end();
|
||||
expect(given.stop).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("has the session's statistics and sent call notifications", () => {
|
||||
const { client, room, session } = setup();
|
||||
const slot = createRTCSlot(
|
||||
testScope(),
|
||||
backendOf(client, room),
|
||||
options,
|
||||
session.asMockedSession(),
|
||||
);
|
||||
expect(slot.statistics).toBe(session.statistics);
|
||||
|
||||
const sent: unknown[] = [];
|
||||
slot.sentCallNotification$.subscribe((n) => sent.push(n));
|
||||
const notification = { event_id: "$notification" };
|
||||
session.emit(
|
||||
MatrixRTCSessionEvent.DidSendCallNotification,
|
||||
notification as Parameters<
|
||||
MatrixRTCSessionEventHandlerMap[MatrixRTCSessionEvent.DidSendCallNotification]
|
||||
>[0],
|
||||
);
|
||||
expect(sent).toEqual([notification]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("status$", () => {
|
||||
it("is undefined while the room has no slot event", () => {
|
||||
const { client, room } = setup();
|
||||
const slot = createRTCSlot(testScope(), client, room, options);
|
||||
const { client, room, session } = setup();
|
||||
const slot = createRTCSlot(
|
||||
testScope(),
|
||||
backendOf(client, room),
|
||||
options,
|
||||
session.asMockedSession(),
|
||||
);
|
||||
expect(slot.status$.value).toBeUndefined();
|
||||
});
|
||||
|
||||
it("follows the slot event", () => {
|
||||
const { client, room, session } = setup();
|
||||
session.rtcSlot = { status: "open" };
|
||||
const slot = createRTCSlot(testScope(), client, room, options);
|
||||
const slot = createRTCSlot(
|
||||
testScope(),
|
||||
backendOf(client, room),
|
||||
options,
|
||||
session.asMockedSession(),
|
||||
);
|
||||
expect(slot.status$.value).toBe("open");
|
||||
|
||||
session.rtcSlot = { status: "closed" };
|
||||
@@ -68,4 +196,69 @@ describe("createRTCSlot", () => {
|
||||
expect(slot.status$.value).toBe("closed");
|
||||
});
|
||||
});
|
||||
|
||||
describe("join", () => {
|
||||
it("holds one participation at a time, and is free again once it has left", () => {
|
||||
const { client, room, session } = setup();
|
||||
const slot = createRTCSlot(
|
||||
testScope(),
|
||||
backendOf(
|
||||
{
|
||||
...client,
|
||||
getDomain: (): string => "example.org",
|
||||
getSyncState: (): SyncState => SyncState.Syncing,
|
||||
getRTCTransports: vi.fn().mockResolvedValue([]),
|
||||
} as unknown as MatrixClient,
|
||||
room,
|
||||
),
|
||||
options,
|
||||
session.asMockedSession(),
|
||||
);
|
||||
const joinOptions: RTCParticipationOptions = {
|
||||
publish: [],
|
||||
matrixRTCMode: MatrixRTCMode.Compatibility,
|
||||
backend: idleBackend,
|
||||
};
|
||||
expect(slot.participation$.value).toBeNull();
|
||||
|
||||
const participation = slot.join(joinOptions);
|
||||
expect(slot.participation$.value).toBe(participation);
|
||||
expect(participation.slot).toMatchObject({
|
||||
roomId: room.roomId,
|
||||
application: "m.call",
|
||||
id: "ROOM",
|
||||
});
|
||||
expect(() => slot.join(joinOptions)).toThrow(MatrixRTCError);
|
||||
|
||||
participation.leave();
|
||||
expect(slot.participation$.value).toBeNull();
|
||||
const again = slot.join(joinOptions);
|
||||
expect(slot.participation$.value).toBe(again);
|
||||
again.leave();
|
||||
});
|
||||
});
|
||||
|
||||
describe("members$", () => {
|
||||
it("keeps the member when its membership is sent again, with the new event id", () => {
|
||||
const { client, room, session } = setup();
|
||||
const first = mockRtcMembership("@bob:example.org", "BOB");
|
||||
session.memberships = [first];
|
||||
const slot = createRTCSlot(
|
||||
testScope(),
|
||||
backendOf(client, room),
|
||||
options,
|
||||
session.asMockedSession(),
|
||||
);
|
||||
const [bob] = slot.members$.value;
|
||||
expect(bob.matrixEventId$.value).toBe(first.eventId);
|
||||
|
||||
const resent = mockRtcMembership("@bob:example.org", "BOB");
|
||||
session.memberships = [resent];
|
||||
session.emit(MatrixRTCSessionEvent.MembershipsChanged, [first], [resent]);
|
||||
expect(slot.members$.value).toHaveLength(1);
|
||||
expect(slot.members$.value[0]).toBe(bob);
|
||||
expect(bob.matrixEventId$.value).toBe(resent.eventId);
|
||||
expect(resent.eventId).not.toBe(first.eventId);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
+124
-74
@@ -5,12 +5,14 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { type MatrixClient, type Room } from "matrix-js-sdk";
|
||||
import { type MatrixClient } from "matrix-js-sdk";
|
||||
import { EventType } from "matrix-js-sdk/lib/@types/event";
|
||||
import { type Logger, logger as rootLogger } from "matrix-js-sdk/lib/logger";
|
||||
import { logger as rootLogger } from "matrix-js-sdk/lib/logger";
|
||||
import {
|
||||
type MatrixRTCSession as JsSdkRTCSession,
|
||||
MatrixRTCSessionManager,
|
||||
type Statistics,
|
||||
MatrixRTCSession as JsMatrixRTCSession,
|
||||
MatrixRTCSessionEvent,
|
||||
type IRTCNotificationContent,
|
||||
type SlotDescription,
|
||||
} from "matrix-js-sdk/lib/matrixrtc";
|
||||
import { type MatrixEvent } from "matrix-js-sdk/lib/models/event";
|
||||
@@ -20,6 +22,7 @@ import {
|
||||
filter,
|
||||
fromEvent,
|
||||
map,
|
||||
type Observable,
|
||||
of,
|
||||
startWith,
|
||||
switchMap,
|
||||
@@ -28,6 +31,7 @@ import {
|
||||
import { ObservableScope } from "./reactive/ObservableScope";
|
||||
import { generateItems } from "./reactive/observable";
|
||||
import {
|
||||
type ParticipationSlot,
|
||||
type RTCMember,
|
||||
type RTCParticipation,
|
||||
type RTCParticipationOptions,
|
||||
@@ -50,33 +54,64 @@ import {
|
||||
membershipKeys,
|
||||
} from "./matrixrtc/Members";
|
||||
import { createTransportRegistry } from "./matrixrtc/Transports";
|
||||
import {
|
||||
type createSdkMatrixBackend,
|
||||
type SdkMatrixBackend,
|
||||
withEmitter,
|
||||
} from "./SdkMatrixBackend";
|
||||
|
||||
const ROOM_CALL_SLOT: SlotDescription = { application: "m.call", id: "ROOM" };
|
||||
|
||||
/**
|
||||
* Takes the whole `MatrixClient` rather than a slice of it, and finds the
|
||||
* MatrixRTC session itself. The js-sdk is the MatrixRTC implementation today;
|
||||
* when the rust-rtc crate replaces it, the SDK has to bridge the crate to the
|
||||
* js-sdk client, and only the SDK knows what that bridge needs. Holding the
|
||||
* client keeps that change inside the SDK.
|
||||
* The slot runs on a matrix-js-sdk session of its own, from the SDK's copy of
|
||||
* matrix-js-sdk rather than the client's, and stops it when the scope ends.
|
||||
*/
|
||||
export function createRTCSlot(
|
||||
scope: ObservableScope,
|
||||
client: MatrixClient,
|
||||
room: Room,
|
||||
backend: SdkMatrixBackend,
|
||||
options: RTCSlotOptions,
|
||||
): RTCSlot {
|
||||
/**
|
||||
* @deprecated A session the caller owns and stops, in place of the slot's
|
||||
* own; `options.slotDescription` is then the session's. Only for the
|
||||
* standalone app, which still takes its session from its client's session
|
||||
* manager.
|
||||
*/
|
||||
externalJsSdkSession?: JsMatrixRTCSession,
|
||||
): RTCSlot & {
|
||||
// STOP GAP: This should be its own external machine. It is call
|
||||
// specific and should not live inside the sdk/rtc-slot.
|
||||
// We only put it here today, to make sure the rtcSession is fully
|
||||
// hidden inside the sdk.
|
||||
// Next step. disable sending call notificaitons in the sdk, write a new
|
||||
// notification sender in EC directly on client + room.
|
||||
sentCallNotification$: Observable<
|
||||
{
|
||||
event_id: string;
|
||||
} & IRTCNotificationContent
|
||||
>;
|
||||
// STOP GAP: the same as above. Has to live here. but should become a native
|
||||
// SDK propery independent of the rtcSession
|
||||
statistics: Statistics;
|
||||
} {
|
||||
// STOP GAP: the slot is still written against a client and a room. Both
|
||||
// are refactored along with the backend.
|
||||
const client = withEmitter(backend, backend.clientEmitter);
|
||||
const room = withEmitter(backend, backend.roomEmitter);
|
||||
const logger = rootLogger.getChild("[RTCSlot]");
|
||||
const userId = client.getUserId();
|
||||
const deviceId = client.getDeviceId();
|
||||
const roomId = room.roomId;
|
||||
if (!(userId && deviceId))
|
||||
throw new MatrixRTCError("The client has to be logged in");
|
||||
const { application = "m.call", id = "ROOM" } = options;
|
||||
|
||||
const jsSdkSession = sessionManager(
|
||||
scope,
|
||||
client,
|
||||
{ application, id },
|
||||
logger,
|
||||
).getRoomSession(room);
|
||||
const jsSdkSession =
|
||||
externalJsSdkSession ??
|
||||
createJsSdkSession(
|
||||
scope,
|
||||
client,
|
||||
room,
|
||||
options.slotDescription ?? ROOM_CALL_SLOT,
|
||||
);
|
||||
const memberships$ = createMemberships$(scope, jsSdkSession);
|
||||
|
||||
const active$ = new BehaviorSubject<ParticipationInternals | null>(null);
|
||||
@@ -126,70 +161,85 @@ export function createRTCSlot(
|
||||
),
|
||||
);
|
||||
|
||||
const slot: RTCSlot = {
|
||||
roomId: room.roomId,
|
||||
application,
|
||||
id,
|
||||
const participationSlot: ParticipationSlot = {
|
||||
roomId,
|
||||
status$,
|
||||
members$,
|
||||
...jsSdkSession.slotDescription,
|
||||
};
|
||||
|
||||
const join = (
|
||||
participationOptions: RTCParticipationOptions,
|
||||
): RTCParticipation => {
|
||||
if (active$.value !== null)
|
||||
throw new MatrixRTCError(
|
||||
"Already in this slot: leave the participation before joining again",
|
||||
);
|
||||
const participationScope = new ObservableScope();
|
||||
participationScopes.add(participationScope);
|
||||
const internals = createRTCParticipation(
|
||||
participationScope,
|
||||
{
|
||||
client,
|
||||
slot: participationSlot,
|
||||
jsSdkSession,
|
||||
transports,
|
||||
slotOptions: options,
|
||||
logger,
|
||||
},
|
||||
participationOptions,
|
||||
);
|
||||
participationScope.onEnd(() => {
|
||||
participationScopes.delete(participationScope);
|
||||
if (active$.value === internals) active$.next(null);
|
||||
});
|
||||
active$.next(internals);
|
||||
return internals.participation;
|
||||
};
|
||||
|
||||
const slot = {
|
||||
join,
|
||||
participation$: scope.behavior(
|
||||
active$.pipe(map((active) => active?.participation ?? null)),
|
||||
),
|
||||
join: (participationOptions: RTCParticipationOptions): RTCParticipation => {
|
||||
if (active$.value !== null)
|
||||
throw new MatrixRTCError(
|
||||
"Already in this slot: leave the participation before joining again",
|
||||
);
|
||||
const participationScope = new ObservableScope();
|
||||
participationScopes.add(participationScope);
|
||||
const internals = createRTCParticipation(
|
||||
participationScope,
|
||||
{
|
||||
client,
|
||||
room,
|
||||
slot,
|
||||
jsSdkSession,
|
||||
members$,
|
||||
transports,
|
||||
slotOptions: options,
|
||||
logger,
|
||||
},
|
||||
participationOptions,
|
||||
);
|
||||
participationScope.onEnd(() => {
|
||||
participationScopes.delete(participationScope);
|
||||
if (active$.value === internals) active$.next(null);
|
||||
});
|
||||
active$.next(internals);
|
||||
return internals.participation;
|
||||
},
|
||||
...participationSlot,
|
||||
};
|
||||
return slot;
|
||||
|
||||
return {
|
||||
...slot,
|
||||
sentCallNotification$: fromEvent(
|
||||
jsSdkSession,
|
||||
MatrixRTCSessionEvent.DidSendCallNotification,
|
||||
(notification: { event_id: string } & IRTCNotificationContent) =>
|
||||
notification,
|
||||
),
|
||||
statistics: jsSdkSession.statistics,
|
||||
};
|
||||
}
|
||||
|
||||
function createJsSdkSession(
|
||||
scope: ObservableScope,
|
||||
client: Pick<
|
||||
MatrixClient,
|
||||
keyof Parameters<typeof createSdkMatrixBackend>[0]
|
||||
>,
|
||||
room: ConstructorParameters<typeof JsMatrixRTCSession>[1],
|
||||
slotDescription: SlotDescription,
|
||||
): JsMatrixRTCSession {
|
||||
const session = new JsMatrixRTCSession(
|
||||
// The session's type also asks for `cancelPendingEvent`,
|
||||
// `_unstable_updateDelayedEvent` and `decryptEventIfNeeded`, which it
|
||||
// never calls
|
||||
client as ConstructorParameters<typeof JsMatrixRTCSession>[0],
|
||||
room,
|
||||
slotDescription,
|
||||
);
|
||||
scope.onEnd(() => void session.stop());
|
||||
return session;
|
||||
}
|
||||
|
||||
function slotStatus(
|
||||
session: Pick<JsSdkRTCSession, "getRtcSlot">,
|
||||
session: Pick<JsMatrixRTCSession, "getRtcSlot">,
|
||||
): "open" | "closed" | undefined {
|
||||
return session.getRtcSlot()?.status;
|
||||
}
|
||||
|
||||
/**
|
||||
* The js-sdk keeps one session manager per slot. The client comes with the
|
||||
* manager for the default slot; any other slot gets a manager of its own,
|
||||
* which lives as long as the scope.
|
||||
*/
|
||||
function sessionManager(
|
||||
scope: ObservableScope,
|
||||
client: MatrixClient,
|
||||
{ application, id }: SlotDescription,
|
||||
logger: Logger,
|
||||
): MatrixRTCSessionManager {
|
||||
if (application === "m.call" && id === "ROOM") return client.matrixRTC;
|
||||
const manager = new MatrixRTCSessionManager(logger, client, {
|
||||
application,
|
||||
id,
|
||||
});
|
||||
manager.start();
|
||||
scope.onEnd(() => manager.stop());
|
||||
return manager;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
ClientEvent,
|
||||
createClient,
|
||||
type MatrixClient,
|
||||
Room,
|
||||
RoomEvent,
|
||||
SyncState,
|
||||
} from "matrix-js-sdk";
|
||||
|
||||
import { createSdkMatrixBackend, withEmitter } from "./SdkMatrixBackend";
|
||||
|
||||
describe("createSdkMatrixBackend", () => {
|
||||
it("calls each member on the client or the room it came from", () => {
|
||||
const { client, room } = setup();
|
||||
const backend = createSdkMatrixBackend(client, room);
|
||||
|
||||
expect(backend.getUserId()).toBe("@alice:example.org");
|
||||
expect(backend.roomId).toBe("!room:example.org");
|
||||
expect(backend.getVersion()).toBe(room.getVersion());
|
||||
});
|
||||
|
||||
it("keeps the client's and the room's events apart", () => {
|
||||
const { client, room } = setup();
|
||||
const backend = createSdkMatrixBackend(client, room);
|
||||
const onClient = vi.fn();
|
||||
const onRoom = vi.fn();
|
||||
backend.clientEmitter.on(ClientEvent.Sync, onClient);
|
||||
backend.roomEmitter.on(RoomEvent.Name, onRoom);
|
||||
|
||||
client.emit(ClientEvent.Sync, SyncState.Syncing, null);
|
||||
expect(onClient).toHaveBeenCalledOnce();
|
||||
expect(onRoom).not.toHaveBeenCalled();
|
||||
|
||||
room.emit(RoomEvent.Name, room);
|
||||
expect(onRoom).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
|
||||
describe("withEmitter", () => {
|
||||
it("is the backend with one side's events", () => {
|
||||
const { client, room } = setup();
|
||||
const backend = createSdkMatrixBackend(client, room);
|
||||
const asRoom = withEmitter(backend, backend.roomEmitter);
|
||||
const listener = vi.fn();
|
||||
|
||||
asRoom.on(RoomEvent.Name, listener);
|
||||
room.emit(RoomEvent.Name, room);
|
||||
|
||||
expect(listener).toHaveBeenCalledOnce();
|
||||
expect(asRoom.getUserId()).toBe("@alice:example.org");
|
||||
});
|
||||
|
||||
it("reads the backend's getters through", () => {
|
||||
const { room } = setup();
|
||||
const asRoom = withEmitter(
|
||||
{
|
||||
get name() {
|
||||
return room.name;
|
||||
},
|
||||
},
|
||||
room,
|
||||
);
|
||||
|
||||
room.name = "Renamed";
|
||||
expect(asRoom.name).toBe("Renamed");
|
||||
});
|
||||
});
|
||||
|
||||
function setup(): { client: MatrixClient; room: Room } {
|
||||
const client = createClient({
|
||||
baseUrl: "https://matrix.example.org",
|
||||
userId: "@alice:example.org",
|
||||
deviceId: "DEVICE",
|
||||
});
|
||||
const room = new Room("!room:example.org", client, "@alice:example.org");
|
||||
return { client, room };
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { type MatrixClient, type Room } from "matrix-js-sdk";
|
||||
|
||||
/** What the SDK needs of the client. */
|
||||
type SdkClientPart = Pick<
|
||||
MatrixClient,
|
||||
// Our own membership identity
|
||||
| "getUserId"
|
||||
| "getDeviceId"
|
||||
// The session: memberships, delayed leave events, sticky events, call
|
||||
// notifications, and the media keys sent to device
|
||||
| "fetchCapabilities"
|
||||
| "getCachedCapabilities"
|
||||
| "sendEvent"
|
||||
| "sendStateEvent"
|
||||
| "_unstable_sendDelayedStateEvent"
|
||||
| "_unstable_cancelScheduledDelayedEvent"
|
||||
| "_unstable_restartScheduledDelayedEvent"
|
||||
| "_unstable_sendScheduledDelayedEvent"
|
||||
| "_unstable_sendStickyEvent"
|
||||
| "_unstable_sendStickyDelayedEvent"
|
||||
| "encryptAndSendToDevice"
|
||||
// Local transport discovery
|
||||
| "getDomain"
|
||||
| "getRTCTransports"
|
||||
// LiveKit auth: `getOpenIdToken` for the JWT service flow, `getLivekitToken`
|
||||
// for the client-server API flow (MSC4195), `delegateDelayedLeave` and
|
||||
// `baseUrl` for the delayed leave delegation and its probe
|
||||
| "getOpenIdToken"
|
||||
| "getLivekitToken"
|
||||
| "delegateDelayedLeave"
|
||||
| "baseUrl"
|
||||
// Homeserver connection: whether the client is syncing
|
||||
| "getSyncState"
|
||||
>;
|
||||
|
||||
/** What the SDK needs of the room. */
|
||||
type SdkRoomPart = Pick<
|
||||
Room,
|
||||
| "roomId"
|
||||
// The members' display names and avatars
|
||||
| "getMembersWithMembership"
|
||||
// The session: memberships from the room's state, timeline and sticky events
|
||||
| "getLiveTimeline"
|
||||
| "getVersion"
|
||||
| "hasMembershipState"
|
||||
| "_unstable_getStickyEvents"
|
||||
>;
|
||||
|
||||
/**
|
||||
* STOP GAP: what the SDK needs of a Matrix client and room, on one object.
|
||||
* Only their emitters stay apart, since both have an `on` and an `off`. It is
|
||||
* to converge, along with the SDK that takes it, on whichever API fits every
|
||||
* layer best.
|
||||
*/
|
||||
export interface SdkMatrixBackend extends SdkClientPart, SdkRoomPart {
|
||||
/**
|
||||
* `ClientEvent.Sync` (homeserver connection) and `ClientEvent.ToDeviceEvent`
|
||||
* (the session's media keys)
|
||||
*/
|
||||
clientEmitter: Pick<MatrixClient, "on" | "off">;
|
||||
/** The room's state, member and sticky events */
|
||||
roomEmitter: Pick<Room, "on" | "off">;
|
||||
}
|
||||
|
||||
/** The SDK's backend from a client and a room. */
|
||||
export function createSdkMatrixBackend(
|
||||
client: SdkClientPart & Pick<MatrixClient, "on" | "off">,
|
||||
room: SdkRoomPart & Pick<Room, "on" | "off">,
|
||||
): SdkMatrixBackend {
|
||||
return {
|
||||
getUserId: client.getUserId.bind(client),
|
||||
getDeviceId: client.getDeviceId.bind(client),
|
||||
fetchCapabilities: client.fetchCapabilities.bind(client),
|
||||
getCachedCapabilities: client.getCachedCapabilities.bind(client),
|
||||
sendEvent: client.sendEvent.bind(client),
|
||||
sendStateEvent: client.sendStateEvent.bind(client),
|
||||
_unstable_sendDelayedStateEvent:
|
||||
client._unstable_sendDelayedStateEvent.bind(client),
|
||||
_unstable_cancelScheduledDelayedEvent:
|
||||
client._unstable_cancelScheduledDelayedEvent.bind(client),
|
||||
_unstable_restartScheduledDelayedEvent:
|
||||
client._unstable_restartScheduledDelayedEvent.bind(client),
|
||||
_unstable_sendScheduledDelayedEvent:
|
||||
client._unstable_sendScheduledDelayedEvent.bind(client),
|
||||
_unstable_sendStickyEvent: client._unstable_sendStickyEvent.bind(client),
|
||||
_unstable_sendStickyDelayedEvent:
|
||||
client._unstable_sendStickyDelayedEvent.bind(client),
|
||||
encryptAndSendToDevice: client.encryptAndSendToDevice.bind(client),
|
||||
getDomain: client.getDomain.bind(client),
|
||||
getRTCTransports: client.getRTCTransports.bind(client),
|
||||
getOpenIdToken: client.getOpenIdToken.bind(client),
|
||||
getLivekitToken: client.getLivekitToken.bind(client),
|
||||
delegateDelayedLeave: client.delegateDelayedLeave.bind(client),
|
||||
baseUrl: client.baseUrl,
|
||||
getSyncState: client.getSyncState.bind(client),
|
||||
roomId: room.roomId,
|
||||
getMembersWithMembership: room.getMembersWithMembership.bind(room),
|
||||
getLiveTimeline: room.getLiveTimeline.bind(room),
|
||||
getVersion: room.getVersion.bind(room),
|
||||
hasMembershipState: room.hasMembershipState.bind(room),
|
||||
_unstable_getStickyEvents: room._unstable_getStickyEvents.bind(room),
|
||||
clientEmitter: client,
|
||||
roomEmitter: room,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* STOP GAP: the backend as the client (or the room) code written against one
|
||||
* still expects, with that side's `on` and `off`.
|
||||
*/
|
||||
export function withEmitter<
|
||||
Backend extends object,
|
||||
Emitter extends {
|
||||
on: (...args: never[]) => unknown;
|
||||
off: (...args: never[]) => unknown;
|
||||
},
|
||||
>(backend: Backend, emitter: Emitter): Backend & Pick<Emitter, "on" | "off"> {
|
||||
return Object.defineProperties<object>(
|
||||
{ on: emitter.on.bind(emitter), off: emitter.off.bind(emitter) },
|
||||
Object.getOwnPropertyDescriptors(backend),
|
||||
) as Backend & Pick<Emitter, "on" | "off">;
|
||||
}
|
||||
+23
-7
@@ -14,6 +14,7 @@ Please see LICENSE in the repository root for full details.
|
||||
import {
|
||||
type RTCCallIntent,
|
||||
type RTCNotificationType,
|
||||
type SlotDescription,
|
||||
type Transport,
|
||||
} from "matrix-js-sdk/lib/matrixrtc";
|
||||
import { type Observable } from "rxjs";
|
||||
@@ -43,13 +44,9 @@ export { MatrixRTCError } from "./errors";
|
||||
// Slot
|
||||
|
||||
export interface RTCSlotOptions {
|
||||
/** The application the slot belongs to, as named in the membership. Default `m.call`. */
|
||||
application?: string;
|
||||
/** The application's slot in the room. Default `ROOM`. */
|
||||
id?: string;
|
||||
/** How memberships and keys in this slot are written. Resolved by the host. */
|
||||
matrixRTCMode: MatrixRTCMode;
|
||||
encryptionSystem: EncryptionSystem;
|
||||
/** Which slot of the room to join. Defaults to the room's call, `m.call#ROOM`. */
|
||||
slotDescription?: SlotDescription;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -81,6 +78,12 @@ export interface RTCSlot {
|
||||
join(options: RTCParticipationOptions): RTCParticipation; // Maybe MediaSession,
|
||||
}
|
||||
|
||||
/**
|
||||
* The slot as its participation sees it: members, status and identity, without
|
||||
* `join` and `participation$`, which belong to whoever joins.
|
||||
*/
|
||||
export type ParticipationSlot = Omit<RTCSlot, "join" | "participation$">;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Participation
|
||||
|
||||
@@ -95,6 +98,12 @@ export interface RTCParticipationOptions {
|
||||
* before the first connection exists.
|
||||
*/
|
||||
publish: PublishRequest[] | LocalMedia;
|
||||
/**
|
||||
* How our membership and keys are written: the member id and whether the
|
||||
* membership is a sticky event. Resolved by the host. Others' memberships
|
||||
* are read whatever their mode.
|
||||
*/
|
||||
matrixRTCMode: MatrixRTCMode;
|
||||
/**
|
||||
* LEGACY
|
||||
*
|
||||
@@ -166,7 +175,8 @@ export type ParticipationState =
|
||||
|
||||
/** The span between our `join()` of a slot and our `leave()`. */
|
||||
export interface RTCParticipation {
|
||||
readonly slot: RTCSlot;
|
||||
/** Required slot information (no `join` fn and `participation`) */
|
||||
readonly slot: ParticipationSlot;
|
||||
/** Sends the leave, tears the connections down and ends the participation. */
|
||||
leave(): void;
|
||||
state$: Behavior<ParticipationState>;
|
||||
@@ -289,6 +299,12 @@ export interface RTCMember {
|
||||
deviceId: string;
|
||||
/** The membership's own id; what the Matrix 2.0 identity is derived from. */
|
||||
memberId: string;
|
||||
/**
|
||||
* The Matrix event currently carrying the membership, which events about
|
||||
* it (reactions, raised hands) relate to. Changes when the membership is
|
||||
* sent again while the member stays the same.
|
||||
*/
|
||||
matrixEventId$: Behavior<string>;
|
||||
/** Which transport this member is on; undefined when the membership has none. */
|
||||
transport$: Behavior<TransportMetadata | undefined>;
|
||||
/** What the member's application says about itself, e.g. `intent`. */
|
||||
|
||||
@@ -99,3 +99,37 @@ export const defaultMediaQuality = {
|
||||
max_framerate: 30,
|
||||
},
|
||||
} as const satisfies MediaQuality;
|
||||
|
||||
export interface CaptureResolution {
|
||||
width: number;
|
||||
height: number;
|
||||
frameRate: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* What a camera is captured at for a media quality. A lobby that opens the
|
||||
* camera ahead of the join asks for this, so that the track it hands over is
|
||||
* the one the backend would have captured.
|
||||
*/
|
||||
export function cameraCaptureResolution(
|
||||
mediaQuality?: MediaQuality,
|
||||
): CaptureResolution {
|
||||
const height =
|
||||
mediaQuality?.video?.max_resolution ??
|
||||
defaultMediaQuality.video.max_resolution;
|
||||
return (
|
||||
captureResolutions.find((resolution) => height <= resolution.height) ??
|
||||
captureResolutions.at(-1)!
|
||||
);
|
||||
}
|
||||
|
||||
/** Lowest first; a height between two takes the higher. */
|
||||
const captureResolutions: CaptureResolution[] = [
|
||||
{ width: 320, height: 180, frameRate: 20 },
|
||||
{ width: 640, height: 360, frameRate: 20 },
|
||||
{ width: 960, height: 540, frameRate: 25 },
|
||||
{ width: 1280, height: 720, frameRate: 30 },
|
||||
{ width: 1920, height: 1080, frameRate: 30 },
|
||||
{ width: 2560, height: 1440, frameRate: 30 },
|
||||
{ width: 3840, height: 2160, frameRate: 30 },
|
||||
];
|
||||
|
||||
@@ -8,7 +8,7 @@ Please see LICENSE in the repository root for full details.
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach } from "vitest";
|
||||
import { EventEmitter } from "events";
|
||||
import { ClientEvent, SyncState } from "matrix-js-sdk";
|
||||
import { ClientEvent, type MatrixClient, SyncState } from "matrix-js-sdk";
|
||||
import { MembershipManagerEvent, Status } from "matrix-js-sdk/lib/matrixrtc";
|
||||
|
||||
import { ObservableScope } from "../reactive/ObservableScope";
|
||||
@@ -20,7 +20,7 @@ import { testScope, withTestScheduler } from "../utils/test";
|
||||
```
|
||||
createHomeserverConnected$(
|
||||
scope: ObservableScope,
|
||||
client: NodeStyleEventEmitter & Pick<MatrixClient, "getSyncState">,
|
||||
client: Pick<MatrixClient, "getSyncState" | "on" | "off">,
|
||||
matrixRTCSession: NodeStyleEventEmitter &
|
||||
Pick<MatrixRTCSession, "membershipStatus" | "probablyLeft">,
|
||||
)
|
||||
@@ -34,12 +34,15 @@ class MockMatrixClient extends EventEmitter {
|
||||
}
|
||||
public setSyncState(state: SyncState): void {
|
||||
this.syncState = state;
|
||||
// Matrix's Sync event in createHomeserverConnected$ expects [SyncState]
|
||||
this.emit(ClientEvent.Sync, [state]);
|
||||
this.emit(ClientEvent.Sync, state);
|
||||
}
|
||||
public getSyncState(): SyncState {
|
||||
return this.syncState;
|
||||
}
|
||||
/** `MatrixClient`'s `on`/`off` return the client itself, which no mock is. */
|
||||
public get asClient(): Pick<MatrixClient, "getSyncState" | "on" | "off"> {
|
||||
return this as unknown as Pick<MatrixClient, "getSyncState" | "on" | "off">;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -47,7 +50,7 @@ class MockMatrixClient extends EventEmitter {
|
||||
```
|
||||
createHomeserverConnected$(
|
||||
scope: ObservableScope,
|
||||
client: NodeStyleEventEmitter & Pick<MatrixClient, "getSyncState">,
|
||||
client: Pick<MatrixClient, "getSyncState" | "on" | "off">,
|
||||
matrixRTCSession: NodeStyleEventEmitter &
|
||||
Pick<MatrixRTCSession, "membershipStatus" | "probablyLeft">,
|
||||
)
|
||||
@@ -99,18 +102,33 @@ describe("createHomeserverConnected$", () => {
|
||||
// easy enough to read them so I think they can stay.
|
||||
// Note: gracePeriodMs is set to 0 to avoid debouncing delays in tests
|
||||
it("reports syncing reason when sync state is not Syncing", () => {
|
||||
const hsConnected = createHomeserverConnected$(scope, client, session, 0);
|
||||
const hsConnected = createHomeserverConnected$(
|
||||
scope,
|
||||
client.asClient,
|
||||
session,
|
||||
0,
|
||||
);
|
||||
expect(hsConnected.disconnectReason$.value).toEqual("sync");
|
||||
});
|
||||
|
||||
it("reports membership reason when sync is Syncing but membership is not Connected", () => {
|
||||
const hsConnected = createHomeserverConnected$(scope, client, session, 0);
|
||||
const hsConnected = createHomeserverConnected$(
|
||||
scope,
|
||||
client.asClient,
|
||||
session,
|
||||
0,
|
||||
);
|
||||
client.setSyncState(SyncState.Syncing);
|
||||
expect(hsConnected.disconnectReason$.value).toEqual("membership");
|
||||
});
|
||||
|
||||
it("reports probablyLeft reason when membership transitions to Connected but ProbablyLeft is true", () => {
|
||||
const hsConnected = createHomeserverConnected$(scope, client, session, 0);
|
||||
const hsConnected = createHomeserverConnected$(
|
||||
scope,
|
||||
client.asClient,
|
||||
session,
|
||||
0,
|
||||
);
|
||||
// Make sync loop OK
|
||||
client.setSyncState(SyncState.Syncing);
|
||||
// Indicate probable leave before connection
|
||||
@@ -120,7 +138,12 @@ describe("createHomeserverConnected$", () => {
|
||||
});
|
||||
|
||||
it("becomes null (connected) only when all three conditions are satisfied", () => {
|
||||
const hsConnected = createHomeserverConnected$(scope, client, session, 0);
|
||||
const hsConnected = createHomeserverConnected$(
|
||||
scope,
|
||||
client.asClient,
|
||||
session,
|
||||
0,
|
||||
);
|
||||
// 1. Sync loop connected
|
||||
client.setSyncState(SyncState.Syncing);
|
||||
expect(hsConnected.disconnectReason$.value).toEqual("membership"); // not yet membership connected
|
||||
@@ -130,7 +153,12 @@ describe("createHomeserverConnected$", () => {
|
||||
});
|
||||
|
||||
it("returns syncing reason when sync loop leaves Syncing", () => {
|
||||
const hsConnected = createHomeserverConnected$(scope, client, session, 0);
|
||||
const hsConnected = createHomeserverConnected$(
|
||||
scope,
|
||||
client.asClient,
|
||||
session,
|
||||
0,
|
||||
);
|
||||
// Reach connected state
|
||||
client.setSyncState(SyncState.Syncing);
|
||||
session.setMembershipStatus(Status.Connected);
|
||||
@@ -142,7 +170,12 @@ describe("createHomeserverConnected$", () => {
|
||||
});
|
||||
|
||||
it("returns membershipConnected reason when membership status becomes disconnected", () => {
|
||||
const hsConnected = createHomeserverConnected$(scope, client, session, 0);
|
||||
const hsConnected = createHomeserverConnected$(
|
||||
scope,
|
||||
client.asClient,
|
||||
session,
|
||||
0,
|
||||
);
|
||||
client.setSyncState(SyncState.Syncing);
|
||||
session.setMembershipStatus(Status.Connected);
|
||||
expect(hsConnected.disconnectReason$.value).toEqual(null);
|
||||
@@ -152,7 +185,12 @@ describe("createHomeserverConnected$", () => {
|
||||
});
|
||||
|
||||
it("returns certainlyConnected reason when ProbablyLeft is emitted", () => {
|
||||
const hsConnected = createHomeserverConnected$(scope, client, session, 0);
|
||||
const hsConnected = createHomeserverConnected$(
|
||||
scope,
|
||||
client.asClient,
|
||||
session,
|
||||
0,
|
||||
);
|
||||
client.setSyncState(SyncState.Syncing);
|
||||
session.setMembershipStatus(Status.Connected);
|
||||
expect(hsConnected.disconnectReason$.value).toEqual(null);
|
||||
@@ -162,7 +200,12 @@ describe("createHomeserverConnected$", () => {
|
||||
});
|
||||
|
||||
it("recovers to null (connected) if ProbablyLeft becomes false again while other conditions remain true", () => {
|
||||
const hsConnected = createHomeserverConnected$(scope, client, session, 0);
|
||||
const hsConnected = createHomeserverConnected$(
|
||||
scope,
|
||||
client.asClient,
|
||||
session,
|
||||
0,
|
||||
);
|
||||
client.setSyncState(SyncState.Syncing);
|
||||
session.setMembershipStatus(Status.Connected);
|
||||
expect(hsConnected.disconnectReason$.value).toEqual(null);
|
||||
@@ -176,7 +219,12 @@ describe("createHomeserverConnected$", () => {
|
||||
});
|
||||
|
||||
it("composite sequence reflects each individual failure reason", () => {
|
||||
const hsConnected = createHomeserverConnected$(scope, client, session, 0);
|
||||
const hsConnected = createHomeserverConnected$(
|
||||
scope,
|
||||
client.asClient,
|
||||
session,
|
||||
0,
|
||||
);
|
||||
|
||||
// Initially: sync error + membership disconnected → syncing wins (highest priority)
|
||||
expect(hsConnected.disconnectReason$.value).toEqual("sync");
|
||||
@@ -225,7 +273,7 @@ describe("createHomeserverConnected$ - disconnectReason$ reason values", () => {
|
||||
it("is null when all three conditions are satisfied", () => {
|
||||
const { disconnectReason$ } = createHomeserverConnected$(
|
||||
scope,
|
||||
client,
|
||||
client.asClient,
|
||||
session,
|
||||
0,
|
||||
);
|
||||
@@ -237,7 +285,7 @@ describe("createHomeserverConnected$ - disconnectReason$ reason values", () => {
|
||||
it("reports syncing when sync loop is not Syncing", () => {
|
||||
const { disconnectReason$ } = createHomeserverConnected$(
|
||||
scope,
|
||||
client,
|
||||
client.asClient,
|
||||
session,
|
||||
0,
|
||||
);
|
||||
@@ -248,7 +296,7 @@ describe("createHomeserverConnected$ - disconnectReason$ reason values", () => {
|
||||
it("reports membershipConnected when sync is fine but membership is not Connected", () => {
|
||||
const { disconnectReason$ } = createHomeserverConnected$(
|
||||
scope,
|
||||
client,
|
||||
client.asClient,
|
||||
session,
|
||||
0,
|
||||
);
|
||||
@@ -260,7 +308,7 @@ describe("createHomeserverConnected$ - disconnectReason$ reason values", () => {
|
||||
it("reports certainlyConnected when probablyLeft is true", () => {
|
||||
const { disconnectReason$ } = createHomeserverConnected$(
|
||||
scope,
|
||||
client,
|
||||
client.asClient,
|
||||
session,
|
||||
0,
|
||||
);
|
||||
@@ -273,7 +321,7 @@ describe("createHomeserverConnected$ - disconnectReason$ reason values", () => {
|
||||
it("prioritises syncing over membershipConnected when both fail", () => {
|
||||
const { disconnectReason$ } = createHomeserverConnected$(
|
||||
scope,
|
||||
client,
|
||||
client.asClient,
|
||||
session,
|
||||
0,
|
||||
);
|
||||
@@ -284,7 +332,7 @@ describe("createHomeserverConnected$ - disconnectReason$ reason values", () => {
|
||||
it("updates reason as conditions change", () => {
|
||||
const { disconnectReason$ } = createHomeserverConnected$(
|
||||
scope,
|
||||
client,
|
||||
client.asClient,
|
||||
session,
|
||||
0,
|
||||
);
|
||||
@@ -329,7 +377,7 @@ describe("createHomeserverConnected$ - Grace Period", () => {
|
||||
});
|
||||
const hsConnected = createHomeserverConnected$(
|
||||
testScope(),
|
||||
client,
|
||||
client.asClient,
|
||||
session,
|
||||
GRACE_PERIOD,
|
||||
);
|
||||
|
||||
@@ -17,7 +17,6 @@ import {
|
||||
startWith,
|
||||
map,
|
||||
tap,
|
||||
type Observable,
|
||||
distinctUntilChanged,
|
||||
switchMap,
|
||||
of,
|
||||
@@ -61,7 +60,15 @@ export interface HomeserverConnected {
|
||||
*/
|
||||
export function createHomeserverConnected$(
|
||||
scope: ObservableScope,
|
||||
client: NodeStyleEventEmitter & Pick<MatrixClient, "getSyncState">,
|
||||
client: Pick<
|
||||
MatrixClient,
|
||||
// Whether the client is syncing
|
||||
| "getSyncState"
|
||||
// `on`/`off`, to listen for:
|
||||
// - `ClientEvent.Sync`
|
||||
| "on"
|
||||
| "off"
|
||||
>,
|
||||
matrixRTCSession: NodeStyleEventEmitter &
|
||||
Pick<MatrixRTCSession, "membershipStatus" | "probablyLeft">,
|
||||
gracePeriodMs?: number,
|
||||
@@ -71,11 +78,13 @@ export function createHomeserverConnected$(
|
||||
const graceMs =
|
||||
gracePeriodMs ?? defaultSessionTimings.syncDisconnectGracePeriodMs;
|
||||
|
||||
const syncing$ = (
|
||||
fromEvent(client, ClientEvent.Sync) as Observable<[SyncState]>
|
||||
const syncing$ = fromEvent(
|
||||
client,
|
||||
ClientEvent.Sync,
|
||||
(state: SyncState) => state,
|
||||
).pipe(
|
||||
startWith([client.getSyncState()]),
|
||||
map(([state]) => state === SyncState.Syncing),
|
||||
startWith(client.getSyncState()),
|
||||
map((state) => state === SyncState.Syncing),
|
||||
distinctUntilChanged(),
|
||||
switchMap((isSyncing) => {
|
||||
if (isSyncing || graceMs <= 0) {
|
||||
|
||||
@@ -23,7 +23,9 @@ export type RoomMemberMap = Map<
|
||||
string,
|
||||
Pick<RoomMember, "userId" | "getMxcAvatarUrl" | "rawDisplayName">
|
||||
>;
|
||||
export function roomToMembersMap(matrixRoom: MatrixRoom): RoomMemberMap {
|
||||
export function roomToMembersMap(
|
||||
matrixRoom: Pick<MatrixRoom, "getMembersWithMembership">,
|
||||
): RoomMemberMap {
|
||||
const members = matrixRoom
|
||||
.getMembersWithMembership(KnownMembership.Join)
|
||||
.concat(matrixRoom.getMembersWithMembership(KnownMembership.Invite));
|
||||
@@ -37,9 +39,10 @@ export function roomToMembersMap(matrixRoom: MatrixRoom): RoomMemberMap {
|
||||
}, new Map());
|
||||
}
|
||||
|
||||
/** Listens for `RoomStateEvent.Members` on the room. */
|
||||
export function createRoomMembers$(
|
||||
scope: ObservableScope,
|
||||
matrixRoom: MatrixRoom,
|
||||
matrixRoom: Pick<MatrixRoom, "getMembersWithMembership" | "on" | "off">,
|
||||
): Behavior<RoomMemberMap> {
|
||||
return scope.behavior(
|
||||
fromEvent(matrixRoom, RoomStateEvent.Members).pipe(
|
||||
|
||||
@@ -57,6 +57,12 @@ export function createRTCMember(
|
||||
userId,
|
||||
deviceId,
|
||||
memberId,
|
||||
matrixEventId$: scope.behavior(
|
||||
membership$.pipe(
|
||||
map((membership) => membership.eventId),
|
||||
distinctUntilChanged(),
|
||||
),
|
||||
),
|
||||
displayName$: scope.behavior(
|
||||
metadata
|
||||
.createDisplayNameBehavior$(scope, userId)
|
||||
|
||||
@@ -42,11 +42,7 @@ import {
|
||||
} from "./Connection.ts";
|
||||
import { ObservableScope } from "../../reactive/ObservableScope";
|
||||
import { type ClientGetTokenParts, type ClientOpenIDParts } from "./auth";
|
||||
import {
|
||||
LivekitConnectionError,
|
||||
MatrixRTCError,
|
||||
NoMatrix2AuthorizationService,
|
||||
} from "../../errors";
|
||||
import { LivekitConnectionError, MatrixRTCError } from "../../errors";
|
||||
import { testJWTToken } from "../../utils/test-fixtures";
|
||||
import { ownMemberMock } from "../../utils/test";
|
||||
import { mockRemoteParticipant } from "./test";
|
||||
@@ -67,15 +63,15 @@ const FIREFOX_USER_AGENT =
|
||||
const CHROME_USER_AGENT =
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36";
|
||||
|
||||
const url = "wss://matrix-rtc.m.localhost/livekit/sfu";
|
||||
const transport: UnstableLivekitTransport = { type: "livekit", url };
|
||||
const transport: UnstableLivekitTransport = {
|
||||
type: "livekit",
|
||||
url: "wss://matrix-rtc.m.localhost/livekit/sfu",
|
||||
};
|
||||
|
||||
/** The options of a subscriber connection to `transport`. */
|
||||
function connectionOpts(): ConnectionOpts {
|
||||
return {
|
||||
client,
|
||||
flow: { kind: "csApi", url },
|
||||
onCsApiMissing: vi.fn(),
|
||||
roomId: ROOM_ID,
|
||||
slotId: SLOT_ID,
|
||||
role: "subscriber",
|
||||
@@ -376,7 +372,6 @@ describe("Start connection states", () => {
|
||||
...connectionOpts(),
|
||||
role: "publisher",
|
||||
transport: { type: "livekit", livekit_service_url: serviceUrl },
|
||||
flow: { kind: "openID", serviceUrl },
|
||||
},
|
||||
logger,
|
||||
);
|
||||
@@ -392,49 +387,6 @@ describe("Start connection states", () => {
|
||||
expect(connection.livekitAlias).toBe("!example_room_id");
|
||||
});
|
||||
|
||||
it("reports the CS API missing where the homeserver lacks the endpoint", async () => {
|
||||
setupTest();
|
||||
const opts = connectionOpts();
|
||||
client.getLivekitToken.mockRejectedValue(
|
||||
new MatrixError({ errcode: "M_UNRECOGNIZED" }, 404),
|
||||
);
|
||||
const connection = new Connection(opts, logger);
|
||||
|
||||
await expect(connection.start()).rejects.toThrow(
|
||||
expect.any(NoMatrix2AuthorizationService),
|
||||
);
|
||||
expect(opts.onCsApiMissing).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("does not show as failed when reporting the CS API missing gets it stopped", async () => {
|
||||
setupTest();
|
||||
fakeLivekitRoom.disconnect.mockResolvedValue(undefined);
|
||||
client.getLivekitToken.mockRejectedValue(
|
||||
new MatrixError({ errcode: "M_UNRECOGNIZED" }, 404),
|
||||
);
|
||||
const connection: Connection = new Connection(
|
||||
{ ...connectionOpts(), onCsApiMissing: () => void connection.stop() },
|
||||
logger,
|
||||
);
|
||||
|
||||
await connection.start();
|
||||
await vi.waitFor(() =>
|
||||
expect(connection.state$.value).toEqual({ state: "stopped" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("does not report the CS API missing where the homeserver refuses the request", async () => {
|
||||
setupTest();
|
||||
const opts = connectionOpts();
|
||||
client.getLivekitToken.mockRejectedValue(
|
||||
new MatrixError({ errcode: "M_FORBIDDEN" }, 403),
|
||||
);
|
||||
const connection = new Connection(opts, logger);
|
||||
|
||||
await expect(connection.start()).rejects.toThrow();
|
||||
expect(opts.onCsApiMissing).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("retries a join that failed on the WebSocket in Firefox", async () => {
|
||||
setupTest();
|
||||
mockUserAgent(FIREFOX_USER_AGENT);
|
||||
|
||||
@@ -32,7 +32,6 @@ import { type CallMembershipIdentityParts } from "matrix-js-sdk/lib/matrixrtc/En
|
||||
import {
|
||||
type ClientGetTokenParts,
|
||||
type ClientOpenIDParts,
|
||||
type AuthFlow,
|
||||
type ConnectionRole,
|
||||
getSFUConfig,
|
||||
type SFUConfig,
|
||||
@@ -43,7 +42,6 @@ import {
|
||||
MatrixRTCError,
|
||||
InsufficientCapacityError,
|
||||
LivekitConnectionError,
|
||||
NoMatrix2AuthorizationService,
|
||||
PeerConnectionTimeoutError,
|
||||
SFURoomCreationRestrictedError,
|
||||
UnknownRTCError,
|
||||
@@ -60,10 +58,6 @@ export interface ConnectionOpts {
|
||||
serverName: string;
|
||||
/** The Matrix client, for the token exchange. */
|
||||
client: ClientGetTokenParts & ClientOpenIDParts;
|
||||
/** The flow to authenticate with, for as long as the connection lives. */
|
||||
flow: AuthFlow;
|
||||
/** Called when the client-server API flow finds the API missing. */
|
||||
onCsApiMissing: () => void;
|
||||
/** The Matrix room the session is in. */
|
||||
roomId: string;
|
||||
/** The MatrixRTC slot the session is in. */
|
||||
@@ -112,9 +106,6 @@ export class Connection {
|
||||
/** The homeserver the transport belongs to. */
|
||||
public readonly serverName: string;
|
||||
|
||||
/** The flow that issues this connection's tokens. */
|
||||
public readonly flow: AuthFlow;
|
||||
|
||||
public readonly livekitRoom: LivekitRoom;
|
||||
|
||||
private scope: ObservableScope;
|
||||
@@ -143,7 +134,6 @@ export class Connection {
|
||||
protected stopped = false;
|
||||
|
||||
private readonly client: ClientGetTokenParts & ClientOpenIDParts;
|
||||
private readonly onCsApiMissing: () => void;
|
||||
private readonly roomId: string;
|
||||
private readonly slotId: string;
|
||||
private readonly logger: Logger;
|
||||
@@ -171,8 +161,6 @@ export class Connection {
|
||||
this.transport = transport;
|
||||
this.serverName = serverName;
|
||||
this.client = client;
|
||||
this.flow = opts.flow;
|
||||
this.onCsApiMissing = opts.onCsApiMissing;
|
||||
|
||||
this.remoteParticipants$ = scope.behavior(
|
||||
// Only tracks remote participants
|
||||
@@ -413,23 +401,16 @@ export class Connection {
|
||||
}
|
||||
|
||||
protected async getSFUConfig(): Promise<SFUConfig> {
|
||||
try {
|
||||
return await getSFUConfig({
|
||||
client: this.client,
|
||||
membership: this.ownMembershipIdentity,
|
||||
role: this.role,
|
||||
flow: this.flow,
|
||||
serverName: this.serverName,
|
||||
roomId: this.roomId,
|
||||
slotId: this.slotId,
|
||||
logger: this.logger,
|
||||
});
|
||||
} catch (e) {
|
||||
// Reported before the error surfaces: where there is a fallback, this
|
||||
// connection is stopped and replaced, so it never shows as failed
|
||||
if (e instanceof NoMatrix2AuthorizationService) this.onCsApiMissing();
|
||||
throw e;
|
||||
}
|
||||
return await getSFUConfig({
|
||||
client: this.client,
|
||||
membership: this.ownMembershipIdentity,
|
||||
role: this.role,
|
||||
transport: this.transport,
|
||||
serverName: this.serverName,
|
||||
roomId: this.roomId,
|
||||
slotId: this.slotId,
|
||||
logger: this.logger,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -18,11 +18,7 @@ import { type PublishRequest } from "../../media-api";
|
||||
import { constant } from "../../reactive/Behavior";
|
||||
import { ownMemberMock, testScope } from "../../utils/test";
|
||||
import { testJWTToken } from "../../utils/test-fixtures";
|
||||
import {
|
||||
type ClientGetTokenParts,
|
||||
type ClientOpenIDParts,
|
||||
chooseAuthFlow,
|
||||
} from "./auth";
|
||||
import { type ClientGetTokenParts, type ClientOpenIDParts } from "./auth";
|
||||
import {
|
||||
LivekitConnectionFactory,
|
||||
type ResolvedConnection,
|
||||
@@ -54,7 +50,6 @@ function create(
|
||||
): { connection: ResolvedConnection; options: RoomOptions } {
|
||||
const factory = new LivekitConnectionFactory(
|
||||
client(),
|
||||
() => {},
|
||||
"!room:example.org",
|
||||
"m.call#ROOM",
|
||||
publish,
|
||||
@@ -67,7 +62,6 @@ function create(
|
||||
"subscriber",
|
||||
transport,
|
||||
"example.org",
|
||||
chooseAuthFlow(transport, true),
|
||||
ownMemberMock,
|
||||
logger,
|
||||
) as ResolvedConnection;
|
||||
|
||||
@@ -24,7 +24,6 @@ import { type PublishRequest } from "../../media-api";
|
||||
import { type Behavior } from "../../reactive/Behavior";
|
||||
import { type ObservableScope } from "../../reactive/ObservableScope";
|
||||
import {
|
||||
type AuthFlow,
|
||||
type ClientGetTokenParts,
|
||||
type ClientOpenIDParts,
|
||||
type ConnectionRole,
|
||||
@@ -45,7 +44,6 @@ export interface ConnectionFactory {
|
||||
role: ConnectionRole,
|
||||
transport: UnstableLivekitTransport,
|
||||
serverName: string,
|
||||
flow: AuthFlow,
|
||||
ownMembershipIdentity: CallMembershipIdentityParts,
|
||||
logger: Logger,
|
||||
): Connection;
|
||||
@@ -104,7 +102,6 @@ function resolvedTransport(config: SFUConfig): ResolvedTransport {
|
||||
export class LivekitConnectionFactory implements ConnectionFactory {
|
||||
public constructor(
|
||||
private readonly client: ClientGetTokenParts & ClientOpenIDParts,
|
||||
private readonly onCsApiMissing: () => void,
|
||||
private readonly roomId: string,
|
||||
private readonly slotId: string,
|
||||
private readonly publish: PublishRequest[],
|
||||
@@ -118,7 +115,6 @@ export class LivekitConnectionFactory implements ConnectionFactory {
|
||||
role: ConnectionRole,
|
||||
transport: UnstableLivekitTransport,
|
||||
serverName: string,
|
||||
flow: AuthFlow,
|
||||
ownMembershipIdentity: CallMembershipIdentityParts,
|
||||
logger: Logger,
|
||||
): Connection {
|
||||
@@ -129,9 +125,7 @@ export class LivekitConnectionFactory implements ConnectionFactory {
|
||||
role,
|
||||
transport,
|
||||
serverName,
|
||||
flow,
|
||||
client: this.client,
|
||||
onCsApiMissing: this.onCsApiMissing,
|
||||
scope,
|
||||
livekitRoomFactory: () =>
|
||||
new LivekitRoom(
|
||||
|
||||
@@ -16,7 +16,11 @@ import {
|
||||
mapEpoch,
|
||||
ObservableScope,
|
||||
} from "../../reactive/ObservableScope";
|
||||
import { createConnectionMap$, ConnectionMap } from "./ConnectionMap.ts";
|
||||
import {
|
||||
createConnectionMap$,
|
||||
ConnectionMap,
|
||||
keyFor,
|
||||
} from "./ConnectionMap.ts";
|
||||
import { type ConnectionFactory } from "./ConnectionFactory.ts";
|
||||
import { type Connection } from "./Connection.ts";
|
||||
import { ownMemberMock, withTestScheduler } from "../../utils/test";
|
||||
@@ -39,33 +43,6 @@ const TRANSPORT_2: TransportLocator = {
|
||||
serverName: "sample.com",
|
||||
};
|
||||
|
||||
const SERVICE_URL_TRANSPORT: TransportLocator = {
|
||||
transport: {
|
||||
type: "livekit",
|
||||
livekit_service_url: "https://jwt.example.org",
|
||||
},
|
||||
serverName: "example.org",
|
||||
};
|
||||
|
||||
const URL_TRANSPORT: TransportLocator = {
|
||||
transport: { type: "livekit", url: "wss://sfu.example.org" },
|
||||
serverName: "example.org",
|
||||
};
|
||||
|
||||
/** Names the same SFU as URL_TRANSPORT and the same service as SERVICE_URL_TRANSPORT. */
|
||||
const URL_AND_SERVICE_URL_TRANSPORT: TransportLocator = {
|
||||
transport: {
|
||||
type: "livekit",
|
||||
url: "wss://sfu.example.org",
|
||||
livekit_service_url: "https://jwt.example.org",
|
||||
},
|
||||
serverName: "example.org",
|
||||
};
|
||||
|
||||
/** Tells the locators used here apart; not the key the map folds them by. */
|
||||
const keyFor = ({ transport, serverName }: TransportLocator): string =>
|
||||
JSON.stringify([transport, serverName]);
|
||||
|
||||
function findConnection(
|
||||
transport: TransportLocator,
|
||||
connections: Connection[],
|
||||
@@ -125,7 +102,6 @@ describe("connections$ stream", () => {
|
||||
a: new Epoch([TRANSPORT_1, TRANSPORT_2], 0),
|
||||
}),
|
||||
logger: logger,
|
||||
csApiUsable: true,
|
||||
ownMembershipIdentity: ownMemberMock,
|
||||
});
|
||||
|
||||
@@ -163,7 +139,6 @@ describe("connections$ stream", () => {
|
||||
a: new Epoch([TRANSPORT_2], 0),
|
||||
}),
|
||||
logger: logger,
|
||||
csApiUsable: true,
|
||||
ownMembershipIdentity: ownMemberMock,
|
||||
});
|
||||
|
||||
@@ -175,7 +150,6 @@ describe("connections$ stream", () => {
|
||||
"publisher",
|
||||
TRANSPORT_1.transport,
|
||||
TRANSPORT_1.serverName,
|
||||
{ kind: "openID", serviceUrl: "https://lk.example.org" },
|
||||
ownMemberMock,
|
||||
expect.anything(),
|
||||
);
|
||||
@@ -184,7 +158,6 @@ describe("connections$ stream", () => {
|
||||
"subscriber",
|
||||
TRANSPORT_2.transport,
|
||||
TRANSPORT_2.serverName,
|
||||
{ kind: "openID", serviceUrl: "https://lk.sample.com" },
|
||||
ownMemberMock,
|
||||
expect.anything(),
|
||||
);
|
||||
@@ -208,7 +181,6 @@ describe("connections$ stream", () => {
|
||||
a: new Epoch([sameServiceElsewhere], 0),
|
||||
}),
|
||||
logger: logger,
|
||||
csApiUsable: true,
|
||||
ownMembershipIdentity: ownMemberMock,
|
||||
});
|
||||
|
||||
@@ -226,7 +198,6 @@ describe("connections$ stream", () => {
|
||||
"publisher",
|
||||
TRANSPORT_1.transport,
|
||||
"example.org",
|
||||
{ kind: "openID", serviceUrl: "https://lk.example.org" },
|
||||
expect.anything(),
|
||||
expect.anything(),
|
||||
);
|
||||
@@ -254,7 +225,6 @@ describe("connections$ stream", () => {
|
||||
a: new Epoch([sameUrlElsewhere], 0),
|
||||
}),
|
||||
logger: logger,
|
||||
csApiUsable: true,
|
||||
ownMembershipIdentity: ownMemberMock,
|
||||
});
|
||||
|
||||
@@ -273,43 +243,42 @@ describe("connections$ stream", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("Shares connection between url transport and url + livekit_service_url transport", () => {
|
||||
withTestScheduler(({ expectObservable, scope }) => {
|
||||
test("Shares connection between local livekit_service_url transport and remote url + livekit_service_url transport", () => {
|
||||
withTestScheduler(({ behavior, expectObservable, scope }) => {
|
||||
const serviceUrlTransport: TransportLocator = {
|
||||
transport: {
|
||||
type: "livekit",
|
||||
livekit_service_url: "https://jwt.example.org",
|
||||
},
|
||||
serverName: "example.org",
|
||||
};
|
||||
const urlAndServiceUrlTransport: TransportLocator = {
|
||||
transport: {
|
||||
type: "livekit",
|
||||
livekit_service_url: "https://jwt.example.org",
|
||||
url: "wss://sfu.elsewhere.org",
|
||||
},
|
||||
// Should pass even if local server != remote server
|
||||
serverName: "elsewhere.org",
|
||||
};
|
||||
const connectionMap$ = createConnectionMap$({
|
||||
scope,
|
||||
connectionFactory: fakeConnectionFactory,
|
||||
localTransport: URL_AND_SERVICE_URL_TRANSPORT,
|
||||
remoteTransports$: constant(
|
||||
new Epoch([URL_TRANSPORT, SERVICE_URL_TRANSPORT]),
|
||||
),
|
||||
csApiUsable: true,
|
||||
localTransport: serviceUrlTransport,
|
||||
remoteTransports$: constant(new Epoch([urlAndServiceUrlTransport])),
|
||||
logger,
|
||||
ownMembershipIdentity: ownMemberMock,
|
||||
});
|
||||
|
||||
expectObservable(connectionMap$).toBe("a", {
|
||||
a: expect.toSatisfy(({ value: map }: Epoch<ConnectionMap>) => {
|
||||
// Both get the CS API flow, and with it the same identity on the
|
||||
// same SFU. The JWT service assigns another, so it may stay apart.
|
||||
expect(map.getConnections().length).toBe(2);
|
||||
const shared = map.getConnectionForTransport(
|
||||
URL_AND_SERVICE_URL_TRANSPORT,
|
||||
);
|
||||
expect(shared).not.toBeNull();
|
||||
expect(map.getConnectionForTransport(URL_TRANSPORT)).toBe(shared);
|
||||
expect(map.getConnectionForTransport(SERVICE_URL_TRANSPORT)).not.toBe(
|
||||
shared,
|
||||
);
|
||||
expect(
|
||||
vi.mocked(fakeConnectionFactory).createConnection,
|
||||
).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
"publisher",
|
||||
URL_AND_SERVICE_URL_TRANSPORT.transport,
|
||||
"example.org",
|
||||
{ kind: "csApi", url: "wss://sfu.example.org" },
|
||||
ownMemberMock,
|
||||
expect.anything(),
|
||||
expectObservable(
|
||||
connectionMap$.pipe(mapEpoch((d) => d.getConnections())),
|
||||
).toBe("a", {
|
||||
a: expect.toSatisfy(({ value: cs }: Epoch<Connection[]>) => {
|
||||
// One connection total, since local and remote connections are shared
|
||||
expect(cs.length).toBe(1);
|
||||
expect(findConnection(serviceUrlTransport, cs)).toBeDefined();
|
||||
expect(findConnection(serviceUrlTransport, cs)).toBe(
|
||||
findConnection(urlAndServiceUrlTransport, cs),
|
||||
);
|
||||
return true;
|
||||
}),
|
||||
@@ -317,35 +286,44 @@ describe("connections$ stream", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("Shares connection between livekit_service_url transport and url + livekit_service_url transport without the CS API", () => {
|
||||
withTestScheduler(({ expectObservable, scope }) => {
|
||||
test("Shares connection between remote livekit_service_url transport and remote url + livekit_service_url transport", () => {
|
||||
withTestScheduler(({ behavior, expectObservable, scope }) => {
|
||||
const serviceUrlTransport: TransportLocator = {
|
||||
transport: {
|
||||
type: "livekit",
|
||||
livekit_service_url: "https://jwt.example.org",
|
||||
},
|
||||
serverName: "example.org",
|
||||
};
|
||||
const urlAndServiceUrlTransport: TransportLocator = {
|
||||
transport: {
|
||||
type: "livekit",
|
||||
livekit_service_url: "https://jwt.example.org",
|
||||
url: "wss://sfu.elsewhere.org",
|
||||
},
|
||||
// Should pass even if local server != remote server
|
||||
serverName: "elsewhere.org",
|
||||
};
|
||||
const connectionMap$ = createConnectionMap$({
|
||||
scope,
|
||||
connectionFactory: fakeConnectionFactory,
|
||||
localTransport: SERVICE_URL_TRANSPORT,
|
||||
localTransport: TRANSPORT_2,
|
||||
remoteTransports$: constant(
|
||||
new Epoch([
|
||||
{
|
||||
...URL_AND_SERVICE_URL_TRANSPORT,
|
||||
// Should pass even if local server != remote server
|
||||
serverName: "elsewhere.org",
|
||||
},
|
||||
]),
|
||||
new Epoch([serviceUrlTransport, urlAndServiceUrlTransport]),
|
||||
),
|
||||
csApiUsable: false,
|
||||
logger,
|
||||
ownMembershipIdentity: ownMemberMock,
|
||||
});
|
||||
|
||||
expectObservable(connectionMap$).toBe("a", {
|
||||
a: expect.toSatisfy(({ value: map }: Epoch<ConnectionMap>) => {
|
||||
// One connection total, since both go through the same JWT service
|
||||
expect(map.getConnections().length).toBe(1);
|
||||
expect(
|
||||
map.getConnectionForTransport(SERVICE_URL_TRANSPORT),
|
||||
).not.toBeNull();
|
||||
expect(map.getConnectionForTransport(SERVICE_URL_TRANSPORT)).toBe(
|
||||
map.getConnectionForTransport(URL_AND_SERVICE_URL_TRANSPORT),
|
||||
expectObservable(
|
||||
connectionMap$.pipe(mapEpoch((d) => d.getConnections())),
|
||||
).toBe("a", {
|
||||
a: expect.toSatisfy(({ value: cs }: Epoch<Connection[]>) => {
|
||||
// Two connections total: a local connection and a shared remote connection
|
||||
expect(cs.length).toBe(2);
|
||||
expect(findConnection(serviceUrlTransport, cs)).toBeDefined();
|
||||
expect(findConnection(serviceUrlTransport, cs)).toBe(
|
||||
findConnection(urlAndServiceUrlTransport, cs),
|
||||
);
|
||||
return true;
|
||||
}),
|
||||
@@ -353,30 +331,6 @@ describe("connections$ stream", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("Publishes on a url + livekit_service_url transport through the JWT service without the CS API", () => {
|
||||
createConnectionMap$({
|
||||
scope: testScope,
|
||||
connectionFactory: fakeConnectionFactory,
|
||||
localTransport: URL_AND_SERVICE_URL_TRANSPORT,
|
||||
remoteTransports$: constant(new Epoch([])),
|
||||
csApiUsable: false,
|
||||
logger,
|
||||
ownMembershipIdentity: ownMemberMock,
|
||||
});
|
||||
|
||||
expect(
|
||||
vi.mocked(fakeConnectionFactory).createConnection,
|
||||
).toHaveBeenCalledExactlyOnceWith(
|
||||
expect.anything(),
|
||||
"publisher",
|
||||
URL_AND_SERVICE_URL_TRANSPORT.transport,
|
||||
"example.org",
|
||||
{ kind: "openID", serviceUrl: "https://jwt.example.org" },
|
||||
ownMemberMock,
|
||||
expect.anything(),
|
||||
);
|
||||
});
|
||||
|
||||
test("Should start connection only once", () => {
|
||||
withTestScheduler(({ behavior, expectObservable }) => {
|
||||
const connectionMap$ = createConnectionMap$({
|
||||
@@ -392,7 +346,6 @@ describe("connections$ stream", () => {
|
||||
f: new Epoch([TRANSPORT_1, TRANSPORT_2], 5),
|
||||
}),
|
||||
logger: logger,
|
||||
csApiUsable: true,
|
||||
ownMembershipIdentity: ownMemberMock,
|
||||
});
|
||||
|
||||
@@ -433,7 +386,6 @@ describe("connections$ stream", () => {
|
||||
c: new Epoch([TRANSPORT_1], 2),
|
||||
}),
|
||||
logger: logger,
|
||||
csApiUsable: true,
|
||||
ownMembershipIdentity: ownMemberMock,
|
||||
});
|
||||
|
||||
@@ -472,7 +424,7 @@ describe("connections$ stream", () => {
|
||||
describe("ConnectionMap", () => {
|
||||
test("warns when a second connection to the same URL is merged", () => {
|
||||
const warn = vi.spyOn(logger, "warn").mockImplementation(() => {});
|
||||
const data = new ConnectionMap(true, logger);
|
||||
const data = new ConnectionMap(logger);
|
||||
const connection = TRANSPORT_1 as unknown as Connection;
|
||||
const p = (identity: string): RemoteParticipant =>
|
||||
({ identity }) as unknown as RemoteParticipant;
|
||||
@@ -573,7 +525,6 @@ describe("connectionMap$", () => {
|
||||
a: new Epoch([TRANSPORT_1, TRANSPORT_2], 0),
|
||||
}),
|
||||
logger,
|
||||
csApiUsable: true,
|
||||
ownMembershipIdentity: ownMemberMock,
|
||||
});
|
||||
|
||||
|
||||
@@ -18,29 +18,32 @@ import {
|
||||
type ObservableScope,
|
||||
} from "../../reactive/ObservableScope";
|
||||
import { generateItemsWithEpoch } from "../../reactive/observable";
|
||||
import { chooseAuthFlow, type TransportLocator } from "./auth";
|
||||
import {
|
||||
chooseAuthFlow,
|
||||
type ConnectionRole,
|
||||
type TransportLocator,
|
||||
} from "./auth";
|
||||
import { type Connection } from "./Connection";
|
||||
import { type ConnectionFactory } from "./ConnectionFactory";
|
||||
|
||||
// Branded, so that only values returned by `keyFor` can be used as keys
|
||||
type TransportKey = string & { __transportKey: true };
|
||||
export type TransportKey = string & { __transportKey: true };
|
||||
|
||||
/**
|
||||
* Converts a {@link TransportLocator} to a key suitable for identifying it in a
|
||||
* map of connections.
|
||||
*
|
||||
* @param csApiUsable - Whether the map it is for uses the client-server API
|
||||
* where a transport leaves the choice.
|
||||
*/
|
||||
function keyFor(
|
||||
{ transport, serverName }: TransportLocator,
|
||||
csApiUsable: boolean,
|
||||
): TransportKey {
|
||||
export function keyFor({
|
||||
transport,
|
||||
serverName,
|
||||
}: TransportLocator): TransportKey {
|
||||
// Base the key on the auth flow we would use, so that we never create two
|
||||
// connections that share the same auth details. (That would be bad, as we
|
||||
// might then try to connect to the same SFU twice with the same participant
|
||||
// ID, resulting in only one working connection.)
|
||||
const flow = chooseAuthFlow(transport, csApiUsable);
|
||||
// TODO: This strategy will not work once `chooseAuthFlow` begins allowing for
|
||||
// falling back from the CS API flow to the OpenID flow.
|
||||
const flow = chooseAuthFlow(transport);
|
||||
// Serialize the fields in a consistent order
|
||||
return JSON.stringify([
|
||||
flow.kind,
|
||||
@@ -49,6 +52,18 @@ function keyFor(
|
||||
]) as TransportKey;
|
||||
}
|
||||
|
||||
function removeDuplicateTransports(
|
||||
transports: TransportLocator[],
|
||||
): TransportLocator[] {
|
||||
// The first locator wins, so the local one stays first in the list
|
||||
const map = new Map<TransportKey, TransportLocator>();
|
||||
for (const transport of transports) {
|
||||
const key = keyFor(transport);
|
||||
if (!map.has(key)) map.set(key, transport);
|
||||
}
|
||||
return [...map.values()];
|
||||
}
|
||||
|
||||
/** The connections at one moment, with the remote participants seen on each. */
|
||||
export class ConnectionMap {
|
||||
private readonly map = new Map<
|
||||
@@ -56,16 +71,10 @@ export class ConnectionMap {
|
||||
{ connection: Connection; participants: RemoteParticipant[] }
|
||||
>();
|
||||
|
||||
/**
|
||||
* @param csApiUsable - What the connections were keyed with.
|
||||
*/
|
||||
public constructor(
|
||||
private readonly csApiUsable = true,
|
||||
private readonly logger?: Logger,
|
||||
) {}
|
||||
public constructor(private readonly logger?: Logger) {}
|
||||
|
||||
public add(connection: Connection, participants: RemoteParticipant[]): void {
|
||||
const key = keyFor(connection, this.csApiUsable);
|
||||
const key = keyFor(connection);
|
||||
const existing = this.map.get(key);
|
||||
if (!existing) {
|
||||
this.map.set(key, { connection, participants });
|
||||
@@ -86,15 +95,13 @@ export class ConnectionMap {
|
||||
public getConnectionForTransport(
|
||||
transport: TransportLocator,
|
||||
): Connection | null {
|
||||
const key = keyFor(transport, this.csApiUsable);
|
||||
return this.map.get(key)?.connection ?? null;
|
||||
return this.map.get(keyFor(transport))?.connection ?? null;
|
||||
}
|
||||
|
||||
public getParticipantsForTransport(
|
||||
transport: TransportLocator,
|
||||
): RemoteParticipant[] {
|
||||
const key = keyFor(transport, this.csApiUsable);
|
||||
return this.map.get(key)?.participants ?? [];
|
||||
return this.map.get(keyFor(transport))?.participants ?? [];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -105,11 +112,6 @@ interface Props {
|
||||
localTransport: TransportLocator;
|
||||
/** Every transport some member is on, deduplicated against the local one. */
|
||||
remoteTransports$: Behavior<Epoch<TransportLocator[]>>;
|
||||
/**
|
||||
* Whether a transport naming both a `url` and a `livekit_service_url` is
|
||||
* reached through the client-server API. Fixed for the life of the map.
|
||||
*/
|
||||
csApiUsable: boolean;
|
||||
logger: Logger;
|
||||
ownMembershipIdentity: CallMembershipIdentityParts;
|
||||
}
|
||||
@@ -124,45 +126,46 @@ export function createConnectionMap$({
|
||||
connectionFactory,
|
||||
localTransport,
|
||||
remoteTransports$,
|
||||
csApiUsable,
|
||||
logger: parentLogger,
|
||||
ownMembershipIdentity,
|
||||
}: Props): Behavior<Epoch<ConnectionMap>> {
|
||||
const logger = parentLogger.getChild("[ConnectionMap]");
|
||||
|
||||
const transportsByKey$ = scope.behavior(
|
||||
remoteTransports$.pipe(
|
||||
mapEpoch(
|
||||
(remote) =>
|
||||
// The last locator wins a key, so the local one goes last
|
||||
new Map(
|
||||
[...remote, localTransport].map((transport) => [
|
||||
keyFor(transport, csApiUsable),
|
||||
transport,
|
||||
]),
|
||||
),
|
||||
const localAndRemoteTransports$: Behavior<Epoch<TransportLocator[]>> =
|
||||
scope.behavior(
|
||||
remoteTransports$.pipe(
|
||||
mapEpoch((remoteTransports) =>
|
||||
removeDuplicateTransports([localTransport, ...remoteTransports]),
|
||||
),
|
||||
tap((transports) =>
|
||||
logger.debug("localAndRemoteTransports$ = ", transports),
|
||||
),
|
||||
),
|
||||
tap(({ value }) =>
|
||||
logger.debug("transportsByKey$ = ", [...value.values()]),
|
||||
),
|
||||
),
|
||||
);
|
||||
);
|
||||
|
||||
const localTransportKey = keyFor(localTransport);
|
||||
|
||||
const localTransportKey = keyFor(localTransport, csApiUsable);
|
||||
const connections$ = scope.behavior(
|
||||
transportsByKey$.pipe(
|
||||
localAndRemoteTransports$.pipe(
|
||||
generateItemsWithEpoch(
|
||||
"ConnectionMap connections$",
|
||||
// The locator is an object, so a stable key stands in for it
|
||||
(byKey) => Array.from(byKey, ([key, data]) => ({ keys: [key], data })),
|
||||
(scope, locator$, key) => {
|
||||
function* (transports) {
|
||||
for (const transport of transports) {
|
||||
const role: ConnectionRole =
|
||||
keyFor(transport) === localTransportKey
|
||||
? "publisher"
|
||||
: "subscriber";
|
||||
// The locator is an object, so a stable key stands in for it
|
||||
yield { keys: [role, keyFor(transport)], data: transport };
|
||||
}
|
||||
},
|
||||
(scope, locator$, role, _key) => {
|
||||
const { transport, serverName } = locator$.value;
|
||||
const connection = connectionFactory.createConnection(
|
||||
scope,
|
||||
key === localTransportKey ? "publisher" : "subscriber",
|
||||
role,
|
||||
transport,
|
||||
serverName,
|
||||
chooseAuthFlow(transport, csApiUsable),
|
||||
ownMembershipIdentity,
|
||||
logger,
|
||||
);
|
||||
@@ -178,7 +181,7 @@ export function createConnectionMap$({
|
||||
connections$.pipe(
|
||||
switchMap(({ value: connections, epoch }) => {
|
||||
if (connections.length === 0)
|
||||
return of(new Epoch(new ConnectionMap(csApiUsable), epoch));
|
||||
return of(new Epoch(new ConnectionMap(), epoch));
|
||||
return combineLatest(
|
||||
connections.map((connection) =>
|
||||
connection.remoteParticipants$.pipe(
|
||||
@@ -186,7 +189,7 @@ export function createConnectionMap$({
|
||||
),
|
||||
),
|
||||
(...list) => {
|
||||
const map = new ConnectionMap(csApiUsable, logger);
|
||||
const map = new ConnectionMap(logger);
|
||||
for (const item of list)
|
||||
map.add(item.connection, item.participants);
|
||||
return new Epoch(map, epoch);
|
||||
|
||||
@@ -148,6 +148,7 @@ describe("toMediaConnectionState", () => {
|
||||
|
||||
describe("createLivekitBackend", () => {
|
||||
const homeserver = "https://matrix.example.org";
|
||||
const homeserverEndpoint = `${homeserver}/_matrix/client/unstable/io.element.msc4195/rtc/livekit/delegate_delayed_leave`;
|
||||
const urlTransport: UnstableLivekitTransport = {
|
||||
type: "livekit",
|
||||
url: "wss://sfu.example.org",
|
||||
@@ -168,7 +169,6 @@ describe("createLivekitBackend", () => {
|
||||
participants$: BehaviorSubject<RemoteParticipant[]>;
|
||||
state$: BehaviorSubject<ConnectionState>;
|
||||
}[];
|
||||
let onCsApiMissing: () => void;
|
||||
const connected: ConnectionState = {
|
||||
state: "authenticated",
|
||||
livekitState: LivekitConnectionState.Connected,
|
||||
@@ -177,15 +177,13 @@ describe("createLivekitBackend", () => {
|
||||
/** Stands in for the factory: connections whose state and participants the test drives. */
|
||||
function stubFactory(initialState: ConnectionState): void {
|
||||
vi.spyOn(connectionFactory, "LivekitConnectionFactory").mockImplementation(
|
||||
function (this: unknown, _client, onMissing) {
|
||||
onCsApiMissing = onMissing;
|
||||
function (this: unknown) {
|
||||
return {
|
||||
createConnection: (
|
||||
scope: ObservableScope,
|
||||
role: auth.ConnectionRole,
|
||||
transport: UnstableLivekitTransport,
|
||||
serverName: string,
|
||||
flow: auth.AuthFlow,
|
||||
): Connection => {
|
||||
const participants$ = new BehaviorSubject<RemoteParticipant[]>([]);
|
||||
const state$ = new BehaviorSubject<ConnectionState>(initialState);
|
||||
@@ -193,7 +191,6 @@ describe("createLivekitBackend", () => {
|
||||
role,
|
||||
transport,
|
||||
serverName,
|
||||
flow,
|
||||
state$,
|
||||
remoteParticipants$: scope.behavior(participants$),
|
||||
livekitRoom: fakeLivekitRoom(),
|
||||
@@ -235,15 +232,17 @@ describe("createLivekitBackend", () => {
|
||||
}
|
||||
|
||||
// Delegation goes through whichever service authenticates us as a
|
||||
// publisher.
|
||||
// publisher: the JWT service wherever the transport names one, the
|
||||
// homeserver for a `url` alone
|
||||
it.each([
|
||||
["a JWT service that delegates", exampleTransport, 401, true],
|
||||
["a JWT service that does not", exampleTransport, 404, false],
|
||||
["the homeserver over the JWT service", bothTransport, 404, true],
|
||||
["the homeserver", urlTransport, 404, true],
|
||||
["the JWT service", exampleTransport, 404, 401, true],
|
||||
["the JWT service, and only it", bothTransport, 401, 404, false],
|
||||
["the homeserver", urlTransport, 401, 404, true],
|
||||
["neither", exampleTransport, 404, 404, false],
|
||||
])(
|
||||
"prepares the local transport for delegation through %s",
|
||||
async (_name, transport, serviceStatus, expected) => {
|
||||
"prepares the local transport and asks %s about delegation",
|
||||
async (_name, transport, homeserverStatus, serviceStatus, expected) => {
|
||||
fetchMock.post(homeserverEndpoint, homeserverStatus);
|
||||
fetchMock.post(
|
||||
`${exampleServiceUrl}/delegate_delayed_leave`,
|
||||
serviceStatus,
|
||||
@@ -252,10 +251,6 @@ describe("createLivekitBackend", () => {
|
||||
const capabilities = await backend().prepareLocalTransport(transport);
|
||||
|
||||
expect(capabilities).toEqual({ canDelegateDelayedLeave: expected });
|
||||
// Only the service that issued the publisher's token is asked.
|
||||
expect(
|
||||
fetchMock.called(`${exampleServiceUrl}/delegate_delayed_leave`),
|
||||
).toBe(transport === exampleTransport);
|
||||
expect(connections).toHaveLength(1);
|
||||
expect(connections[0].connection.role).toBe("publisher");
|
||||
expect(connections[0].connection.transport).toEqual(transport);
|
||||
@@ -264,8 +259,9 @@ describe("createLivekitBackend", () => {
|
||||
);
|
||||
|
||||
it("prepares a remote SFU's transport on its homeserver, where delegation is not possible", async () => {
|
||||
// A token through the homeserver means delegation, unless the SFU is
|
||||
// another homeserver's.
|
||||
// Our own homeserver would delegate, so only the SFU being remote can
|
||||
// explain delegation being skipped
|
||||
fetchMock.post(homeserverEndpoint, 401);
|
||||
const remoteTransport: UnstableLivekitTransport = {
|
||||
type: "livekit",
|
||||
url: "wss://sfu.sample.com",
|
||||
@@ -280,6 +276,7 @@ describe("createLivekitBackend", () => {
|
||||
});
|
||||
|
||||
it("waits for the publisher connection to hold its token before the join", async () => {
|
||||
fetchMock.post(homeserverEndpoint, 404);
|
||||
fetchMock.post(`${exampleServiceUrl}/delegate_delayed_leave`, 404);
|
||||
stubFactory({ state: "authenticating" });
|
||||
|
||||
@@ -296,6 +293,7 @@ describe("createLivekitBackend", () => {
|
||||
});
|
||||
|
||||
it("fails the preparation with the publisher connection's error", async () => {
|
||||
fetchMock.post(homeserverEndpoint, 404);
|
||||
fetchMock.post(`${exampleServiceUrl}/delegate_delayed_leave`, 404);
|
||||
stubFactory({ state: "authenticating" });
|
||||
const preparing = backend().prepareLocalTransport(exampleTransport);
|
||||
@@ -305,60 +303,8 @@ describe("createLivekitBackend", () => {
|
||||
await expect(preparing).rejects.toBe(error);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["names no JWT service", urlTransport],
|
||||
["names no url", exampleTransport],
|
||||
])(
|
||||
"keeps its connections where the CS API is found missing and our transport %s",
|
||||
async (_what, transport) => {
|
||||
fetchMock.post(`${exampleServiceUrl}/delegate_delayed_leave`, 404);
|
||||
await backend().prepareLocalTransport(transport);
|
||||
onCsApiMissing();
|
||||
expect(connections).toHaveLength(1);
|
||||
},
|
||||
);
|
||||
|
||||
it("moves the publisher to the JWT service where the CS API is found missing", async () => {
|
||||
fetchMock.post(`${exampleServiceUrl}/delegate_delayed_leave`, 401);
|
||||
const delegate = vi.spyOn(auth, "delegateDelayedLeave").mockResolvedValue();
|
||||
stubFactory({ state: "authenticating" });
|
||||
|
||||
const b = backend();
|
||||
let prepared = false;
|
||||
const preparing = b.prepareLocalTransport(bothTransport).then((c) => {
|
||||
prepared = true;
|
||||
return c;
|
||||
});
|
||||
await flushPromises();
|
||||
expect(connections).toHaveLength(1);
|
||||
expect(connections[0].connection.flow.kind).toBe("csApi");
|
||||
|
||||
// The publisher's token request finds no API.
|
||||
onCsApiMissing();
|
||||
expect(connections).toHaveLength(2);
|
||||
expect(connections[1].connection.role).toBe("publisher");
|
||||
expect(connections[1].connection.transport).toEqual(bothTransport);
|
||||
expect(connections[1].connection.flow.kind).toBe("openID");
|
||||
|
||||
// The replaced connection winding down is not the preparation failing.
|
||||
connections[0].state$.next({ state: "stopped" });
|
||||
await flushPromises();
|
||||
expect(prepared).toBe(false);
|
||||
|
||||
connections[1].state$.next(connected);
|
||||
expect(await preparing).toEqual({ canDelegateDelayedLeave: true });
|
||||
expect(
|
||||
fetchMock.called(`${exampleServiceUrl}/delegate_delayed_leave`),
|
||||
).toBe(true);
|
||||
|
||||
await b.delegateDelayedLeave("delay-1");
|
||||
expect(delegate.mock.calls[0][0].flow).toEqual({
|
||||
kind: "openID",
|
||||
serviceUrl: exampleServiceUrl,
|
||||
});
|
||||
});
|
||||
|
||||
it("delegates the leave through the flow that authenticated the publisher", async () => {
|
||||
fetchMock.post(homeserverEndpoint, 401);
|
||||
const delegate = vi.spyOn(auth, "delegateDelayedLeave").mockResolvedValue();
|
||||
const b = backend();
|
||||
await expect(b.delegateDelayedLeave("delay-1")).rejects.toThrow(
|
||||
@@ -372,7 +318,7 @@ describe("createLivekitBackend", () => {
|
||||
expect.objectContaining({
|
||||
client,
|
||||
membership: ownMemberMock,
|
||||
flow: { kind: "csApi", url: "wss://sfu.example.org" },
|
||||
transport: urlTransport,
|
||||
roomId: "!room:example.org",
|
||||
slotId: "m.call#ROOM",
|
||||
delayId: "delay-1",
|
||||
@@ -398,6 +344,7 @@ describe("createLivekitBackend", () => {
|
||||
userId: "@bob:example.org",
|
||||
deviceId: "DEV000",
|
||||
memberId: legacyId,
|
||||
matrixEventId$: constant("$bob"),
|
||||
transport$: constant({
|
||||
type: "livekit",
|
||||
id: JSON.stringify(transport),
|
||||
@@ -413,6 +360,7 @@ describe("createLivekitBackend", () => {
|
||||
async function prepared(): Promise<
|
||||
ReturnType<typeof createLivekitBackend>
|
||||
> {
|
||||
fetchMock.post(homeserverEndpoint, 404);
|
||||
fetchMock.post(`${exampleServiceUrl}/delegate_delayed_leave`, 404);
|
||||
const b = backend();
|
||||
await b.prepareLocalTransport(bothTransport);
|
||||
@@ -444,30 +392,6 @@ describe("createLivekitBackend", () => {
|
||||
},
|
||||
);
|
||||
|
||||
it("reaches a url + livekit_service_url member through the JWT service where our transport names no url", async () => {
|
||||
fetchMock.post(`${exampleServiceUrl}/delegate_delayed_leave`, 404);
|
||||
const b = backend();
|
||||
await b.prepareLocalTransport(exampleTransport);
|
||||
const media = b.mediaFor(
|
||||
testScope(),
|
||||
bob(bothTransport, [hashedId, legacyId]),
|
||||
);
|
||||
await flushPromises();
|
||||
// Bob names our JWT service, so no connection of his own, and none
|
||||
// through a client-server API our homeserver does not have
|
||||
expect(connections).toHaveLength(1);
|
||||
expect(connections[0].connection.flow.kind).toBe("openID");
|
||||
|
||||
connections[0].participants$.next([
|
||||
mockRemoteParticipant({
|
||||
identity: hashedId,
|
||||
trackPublications: new Map(),
|
||||
}),
|
||||
]);
|
||||
await flushPromises();
|
||||
expect(media.tracks$.value).toEqual([]);
|
||||
});
|
||||
|
||||
it("does not match a member with two candidate identities to anyone else", async () => {
|
||||
const b = await prepared();
|
||||
const media = b.mediaFor(
|
||||
@@ -539,11 +463,10 @@ describe("createLivekitBackend", () => {
|
||||
(c) => c.connection.role === "subscriber",
|
||||
);
|
||||
expect(remote?.connection.transport).toEqual(otherTransport);
|
||||
const transports = b.connections$.value.map(({ transport }) => transport);
|
||||
expect(transports).toHaveLength(2);
|
||||
expect(transports).toEqual(
|
||||
expect.arrayContaining([bothTransport, otherTransport]),
|
||||
);
|
||||
expect(b.connections$.value.map(({ transport }) => transport)).toEqual([
|
||||
bothTransport,
|
||||
otherTransport,
|
||||
]);
|
||||
|
||||
transport$.next(bob(bothTransport, [legacyId]).transport$.value);
|
||||
await flushPromises();
|
||||
|
||||
@@ -18,7 +18,6 @@ import {
|
||||
filter,
|
||||
firstValueFrom,
|
||||
map,
|
||||
NEVER,
|
||||
type Observable,
|
||||
of,
|
||||
switchMap,
|
||||
@@ -42,9 +41,18 @@ import {
|
||||
type MediaBackendContext,
|
||||
type TransportCapabilities,
|
||||
} from "../api";
|
||||
import { delegateDelayedLeave, type TransportLocator } from "./auth";
|
||||
import {
|
||||
chooseAuthFlow,
|
||||
delegateDelayedLeave,
|
||||
type TransportLocator,
|
||||
} from "./auth";
|
||||
import { type Connection } from "./Connection";
|
||||
import { ConnectionMap, createConnectionMap$ } from "./ConnectionMap";
|
||||
import {
|
||||
ConnectionMap,
|
||||
createConnectionMap$,
|
||||
keyFor,
|
||||
type TransportKey,
|
||||
} from "./ConnectionMap";
|
||||
import {
|
||||
LivekitConnectionFactory,
|
||||
ResolvedConnection,
|
||||
@@ -58,20 +66,10 @@ import {
|
||||
} from "./LivekitMemberMedia";
|
||||
import { createLivekitLocalMedia } from "./LocalMedia";
|
||||
|
||||
/** The transport we publish on, with what is fixed for its connection map. */
|
||||
interface LocalTransport extends TransportLocator {
|
||||
/**
|
||||
* Whether a transport naming both a `url` and a `livekit_service_url` is
|
||||
* reached through the client-server API: where ours names a `url`, until
|
||||
* a connection finds the API missing.
|
||||
*/
|
||||
csApiUsable: boolean;
|
||||
}
|
||||
|
||||
export interface LivekitBackendOptions {
|
||||
/**
|
||||
* `getOpenIdToken` for the JWT service flow, the MSC4195 methods for the
|
||||
* client-server API flow, `baseUrl` for the delegation handover.
|
||||
* client-server API flow, `baseUrl` for the delegation probe and handover.
|
||||
*/
|
||||
client: Pick<
|
||||
MatrixClient,
|
||||
@@ -105,20 +103,12 @@ export function createLivekitBackend(
|
||||
: [requestsOrMedia.requests, requestsOrMedia];
|
||||
const keyProvider = createKeyProvider(encryptionSystem, mediaKeys$, logger);
|
||||
const transports = createTransportRegistry(scope);
|
||||
const localTransport$ = new BehaviorSubject<LocalTransport | null>(null);
|
||||
const localTransport$ = new BehaviorSubject<TransportLocator | null>(null);
|
||||
const audioOutputDeviceId$ = new BehaviorSubject<string | undefined>(
|
||||
undefined,
|
||||
);
|
||||
const connectionFactory = new LivekitConnectionFactory(
|
||||
client,
|
||||
// The MSC defines no unstable feature flag, so a homeserver that
|
||||
// advertises a `url` without the API shows in a token request. Where our
|
||||
// transport names a JWT service too, start over without the API.
|
||||
() => {
|
||||
const local = localTransport$.value;
|
||||
if (local?.csApiUsable && "livekit_service_url" in local.transport)
|
||||
localTransport$.next({ ...local, csApiUsable: false });
|
||||
},
|
||||
roomId,
|
||||
slotId,
|
||||
publish,
|
||||
@@ -128,8 +118,7 @@ export function createLivekitBackend(
|
||||
);
|
||||
|
||||
// A new map, in a scope of its own, whenever the local transport changes:
|
||||
// the publisher role sits on one connection, and which one is fixed per map,
|
||||
// as is whether the client-server API is usable
|
||||
// the publisher role sits on one connection, and which one is fixed per map
|
||||
const connectionMap$ = scope.behavior<Epoch<ConnectionMap>>(
|
||||
mapScoped(scope, localTransport$, (mapScope, localTransport) =>
|
||||
createConnectionMap$({
|
||||
@@ -137,7 +126,6 @@ export function createLivekitBackend(
|
||||
connectionFactory,
|
||||
localTransport,
|
||||
remoteTransports$: transports.transports$,
|
||||
csApiUsable: localTransport.csApiUsable,
|
||||
logger,
|
||||
ownMembershipIdentity,
|
||||
}),
|
||||
@@ -155,6 +143,13 @@ export function createLivekitBackend(
|
||||
logger,
|
||||
});
|
||||
|
||||
// Probed once: the answer cannot change within a session
|
||||
const homeserverSupportsDelegation = supportsDelegation(
|
||||
`${client.baseUrl}/_matrix/client/unstable/io.element.msc4195/rtc/livekit/delegate_delayed_leave`,
|
||||
"homeserver",
|
||||
logger,
|
||||
);
|
||||
|
||||
const ownServerName = serverNameOf(ownMembershipIdentity.userId);
|
||||
|
||||
const prepareLocalTransport = async (
|
||||
@@ -167,45 +162,45 @@ export function createLivekitBackend(
|
||||
ownMembershipIdentity.userId,
|
||||
);
|
||||
const locator: TransportLocator = { transport, serverName };
|
||||
// A homeserver with the client-server API advertises a `url`
|
||||
localTransport$.next({ ...locator, csApiUsable: "url" in transport });
|
||||
// The membership is only sent once the publisher connection holds its
|
||||
// token, so that the LiveKit room exists before anyone subscribes to it:
|
||||
// a subscriber lacks the permission to create it and would fail without
|
||||
// retrying
|
||||
const { flow } = await authenticated(localMedia_.connection$);
|
||||
let canDelegate: Promise<boolean>;
|
||||
if (serverName !== ownServerName) {
|
||||
// Our homeserver only takes over leaves for its own SFUs
|
||||
logger.info(
|
||||
`Publishing on a remote SFU of ${serverName}, delegation is not possible`,
|
||||
);
|
||||
return { canDelegateDelayedLeave: false };
|
||||
canDelegate = Promise.resolve(false);
|
||||
} else {
|
||||
// Check for support using the same auth flow that we intend to use later
|
||||
const flow = chooseAuthFlow(transport);
|
||||
canDelegate =
|
||||
flow.kind === "openID"
|
||||
? supportsDelegation(
|
||||
`${flow.serviceUrl}/delegate_delayed_leave`,
|
||||
`transport ${flow.serviceUrl}`,
|
||||
logger,
|
||||
)
|
||||
: homeserverSupportsDelegation;
|
||||
}
|
||||
// Delegation goes through the flow that authenticated us
|
||||
if (flow.kind === "csApi") {
|
||||
// If the client-server authentication endpoint is available, the delegation
|
||||
// endpoint is available, too. Both have been released together in lk-jwt-service.
|
||||
return { canDelegateDelayedLeave: true };
|
||||
}
|
||||
// The OpenID flow was used but the lk-jwt-instance may still predate delegation. Check
|
||||
// if the delegation endpoint is supported.
|
||||
return {
|
||||
canDelegateDelayedLeave: await supportsDelegation(
|
||||
`${flow.serviceUrl}/delegate_delayed_leave`,
|
||||
`transport ${flow.serviceUrl}`,
|
||||
logger,
|
||||
),
|
||||
};
|
||||
localTransport$.next(locator);
|
||||
// The membership is only sent once the publisher connection holds its
|
||||
// token, so that the LiveKit room exists before anyone subscribes to it:
|
||||
// a subscriber lacks the permission to create it and would fail without
|
||||
// retrying
|
||||
const [, canDelegateDelayedLeave] = await Promise.all([
|
||||
authenticated(localMedia_.connection$),
|
||||
canDelegate,
|
||||
]);
|
||||
return { canDelegateDelayedLeave };
|
||||
};
|
||||
|
||||
const delegateLeave = async (delayId: string): Promise<void> => {
|
||||
const connection = localMedia_.connection$.value;
|
||||
if (connection === null)
|
||||
const local = localTransport$.value;
|
||||
if (local === null)
|
||||
throw new MatrixRTCError("No local transport to delegate the leave to");
|
||||
await delegateDelayedLeave({
|
||||
client,
|
||||
membership: ownMembershipIdentity,
|
||||
flow: connection.flow,
|
||||
transport: local.transport,
|
||||
roomId,
|
||||
slotId,
|
||||
delayId,
|
||||
@@ -230,9 +225,7 @@ export function createLivekitBackend(
|
||||
}
|
||||
: undefined;
|
||||
}),
|
||||
distinctUntilChanged(
|
||||
(a, b) => (a && registryKeyFor(a)) === (b && registryKeyFor(b)),
|
||||
),
|
||||
distinctUntilChanged((a, b) => (a && keyFor(a)) === (b && keyFor(b))),
|
||||
),
|
||||
);
|
||||
transports.follow(memberScope, locator$);
|
||||
@@ -299,31 +292,27 @@ export function createLivekitBackend(
|
||||
};
|
||||
}
|
||||
|
||||
/** Resolves with the connection once it holds its token; rejects with its error otherwise. */
|
||||
/** Resolves once the connection holds its token; rejects with its error otherwise. */
|
||||
async function authenticated(
|
||||
connection$: Behavior<Connection | null>,
|
||||
): Promise<Connection> {
|
||||
const { connection, state } = await firstValueFrom(
|
||||
): Promise<void> {
|
||||
const state = await firstValueFrom(
|
||||
connection$.pipe(
|
||||
switchMap(
|
||||
(connection) =>
|
||||
connection?.state$.pipe(map((state) => ({ connection, state }))) ??
|
||||
NEVER,
|
||||
),
|
||||
switchMap((connection) => connection?.state$ ?? of(null)),
|
||||
filter(
|
||||
({ state }) =>
|
||||
state.state === "authenticated" ||
|
||||
state.state === "error" ||
|
||||
state.state === "stopped",
|
||||
(state) =>
|
||||
state !== null &&
|
||||
(state.state === "authenticated" ||
|
||||
state.state === "error" ||
|
||||
state.state === "stopped"),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (state.state === "error") throw state.error;
|
||||
if (state.state === "stopped")
|
||||
if (state?.state === "error") throw state.error;
|
||||
if (state?.state === "stopped")
|
||||
throw new MatrixRTCError(
|
||||
"The local connection stopped before it was authenticated",
|
||||
);
|
||||
return connection;
|
||||
}
|
||||
|
||||
function backendConnection$(
|
||||
@@ -342,19 +331,6 @@ function backendConnection$(
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The key used for a transport locator in the transport registry.
|
||||
*
|
||||
* Note that this is *not* the key used for folding locators into connections.
|
||||
*/
|
||||
function registryKeyFor({ transport, serverName }: TransportLocator): string {
|
||||
return JSON.stringify([
|
||||
"url" in transport ? transport.url : null,
|
||||
"livekit_service_url" in transport ? transport.livekit_service_url : null,
|
||||
serverName,
|
||||
]);
|
||||
}
|
||||
|
||||
export interface TransportRegistry {
|
||||
/** Keeps a member's transport registered for as long as its scope lives. */
|
||||
follow(
|
||||
@@ -374,7 +350,7 @@ export function createTransportRegistry(
|
||||
scope: ObservableScope,
|
||||
): TransportRegistry {
|
||||
const counts = new Map<
|
||||
string,
|
||||
TransportKey,
|
||||
{ locator: TransportLocator; count: number }
|
||||
>();
|
||||
const transports = new BehaviorSubject<TransportLocator[]>([]);
|
||||
@@ -382,7 +358,7 @@ export function createTransportRegistry(
|
||||
transports.next([...counts.values()].map(({ locator }) => locator));
|
||||
|
||||
const register = (locator: TransportLocator): (() => void) => {
|
||||
const key = registryKeyFor(locator);
|
||||
const key = keyFor(locator);
|
||||
const entry = counts.get(key) ?? { locator, count: 0 };
|
||||
entry.count++;
|
||||
if (entry.count === 1) {
|
||||
|
||||
@@ -210,7 +210,11 @@ describe("createLivekitMediaTrack", () => {
|
||||
await expect(track.setEnabled(false)).resolves.toBe(false);
|
||||
expect(setEnabled).toHaveBeenCalledWith("microphone", false);
|
||||
await track.setDevice("mic-2");
|
||||
expect(switchActiveDevice).toHaveBeenCalledWith("audioinput", "mic-2");
|
||||
expect(switchActiveDevice).toHaveBeenCalledWith(
|
||||
"audioinput",
|
||||
"mic-2",
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
// LiveKit's media stream track is the processed one while a processor runs,
|
||||
@@ -253,36 +257,61 @@ describe("createLivekitMediaTrack", () => {
|
||||
|
||||
await track.setDevice(deviceId);
|
||||
expect(switchActiveDevice.mock.calls).toEqual(
|
||||
switches ? [["videoinput", deviceId]] : [],
|
||||
switches ? [["videoinput", deviceId, true]] : [],
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it("rejects where the camera did not move to the device asked for", async () => {
|
||||
const camera = Object.assign(Object.create(LocalVideoTrack.prototype), {
|
||||
source: Track.Source.Camera,
|
||||
_mediaStreamTrack: {
|
||||
readyState: "live",
|
||||
label: "",
|
||||
getSettings: () => ({ deviceId: "cam-1" }),
|
||||
},
|
||||
}) as LocalVideoTrack;
|
||||
const { participant, publication, room } = fakes({
|
||||
track: camera as unknown as FakeTrack,
|
||||
});
|
||||
const track = createLocalLivekitMediaTrack(
|
||||
scope,
|
||||
Object.assign(participant, {
|
||||
isLocal: true,
|
||||
}) as unknown as LocalParticipant,
|
||||
publication as unknown as TrackPublication,
|
||||
Object.assign(room, {
|
||||
switchActiveDevice: vi.fn().mockResolvedValue(true),
|
||||
}),
|
||||
vi.fn(),
|
||||
);
|
||||
it("rejects where the camera did not move to the device asked for, and returns to the one it had", async () => {
|
||||
const switchActiveDevice = vi.fn().mockResolvedValue(true);
|
||||
const track = localCameraOn(scope, "cam-1", switchActiveDevice);
|
||||
|
||||
await expect(track.setDevice("cam-2")).rejects.toThrow("another device");
|
||||
|
||||
expect(switchActiveDevice.mock.calls).toEqual([
|
||||
["videoinput", "cam-2", true],
|
||||
["videoinput", "cam-1", true],
|
||||
]);
|
||||
});
|
||||
|
||||
it("returns to the device it had where the one asked for does not open", async () => {
|
||||
const gone = new Error("gone");
|
||||
const switchActiveDevice = vi
|
||||
.fn()
|
||||
.mockRejectedValueOnce(gone)
|
||||
.mockResolvedValue(true);
|
||||
const track = localCameraOn(scope, "cam-1", switchActiveDevice);
|
||||
|
||||
await expect(track.setDevice("cam-2")).rejects.toBe(gone);
|
||||
|
||||
expect(switchActiveDevice).toHaveBeenLastCalledWith(
|
||||
"videoinput",
|
||||
"cam-1",
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("reports the switch that failed where the return fails too", async () => {
|
||||
const gone = new Error("gone");
|
||||
const switchActiveDevice = vi
|
||||
.fn()
|
||||
.mockRejectedValueOnce(gone)
|
||||
.mockRejectedValue(new Error("busy"));
|
||||
const track = localCameraOn(scope, "cam-1", switchActiveDevice);
|
||||
|
||||
await expect(track.setDevice("cam-2")).rejects.toBe(gone);
|
||||
});
|
||||
|
||||
// It is stopped, and opens the device LiveKit remembers on turning on
|
||||
it("does not return a camera that is off to its device", async () => {
|
||||
const switchActiveDevice = vi.fn().mockRejectedValue(new Error("gone"));
|
||||
const track = localCameraOn(scope, "cam-1", switchActiveDevice, {
|
||||
isMuted: true,
|
||||
});
|
||||
|
||||
await expect(track.setDevice("cam-2")).rejects.toThrow("gone");
|
||||
|
||||
expect(switchActiveDevice).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("takes the facing mode of a processed camera from the camera", async () => {
|
||||
@@ -383,6 +412,36 @@ function fakeTrack(): FakeTrack {
|
||||
}) as FakeTrack;
|
||||
}
|
||||
|
||||
/** Our own camera, open on a device, in a room whose device switch the test decides. */
|
||||
function localCameraOn(
|
||||
scope: ObservableScope,
|
||||
deviceId: string,
|
||||
switchActiveDevice: LivekitRoom["switchActiveDevice"],
|
||||
state: { isMuted?: boolean } = {},
|
||||
): LocalVideoMediaTrack {
|
||||
const camera = Object.assign(Object.create(LocalVideoTrack.prototype), {
|
||||
source: Track.Source.Camera,
|
||||
_mediaStreamTrack: {
|
||||
readyState: "live",
|
||||
label: "",
|
||||
getSettings: () => ({ deviceId }),
|
||||
},
|
||||
...state,
|
||||
}) as LocalVideoTrack;
|
||||
const { participant, publication, room } = fakes({
|
||||
track: camera as unknown as FakeTrack,
|
||||
});
|
||||
return createLocalLivekitMediaTrack(
|
||||
scope,
|
||||
Object.assign(participant, {
|
||||
isLocal: true,
|
||||
}) as unknown as LocalParticipant,
|
||||
publication as unknown as TrackPublication,
|
||||
Object.assign(room, { switchActiveDevice }),
|
||||
vi.fn(),
|
||||
) as LocalVideoMediaTrack;
|
||||
}
|
||||
|
||||
function fakes({
|
||||
track = fakeTrack(),
|
||||
kind = Track.Kind.Video,
|
||||
|
||||
@@ -203,32 +203,35 @@ export function createLocalLivekitMediaTrack(
|
||||
// of the camera track itself: with a processor on, LiveKit's media
|
||||
// stream track is the processed one, which names no device
|
||||
const current = publication.track;
|
||||
if (
|
||||
current instanceof LocalTrack &&
|
||||
(await current.getDeviceId(false)) === deviceId
|
||||
)
|
||||
return;
|
||||
// THE FIX for "cannot switch cameras in Chrome" (#4479), switching in
|
||||
// the call. No third argument: LiveKit then asks for the device with
|
||||
// `exact`. Passing `false` there made it a wish, which Chromium ignores
|
||||
// by reopening its default device.
|
||||
await room.switchActiveDevice(
|
||||
base.kind === "audio" ? "audioinput" : "videoinput",
|
||||
deviceId,
|
||||
);
|
||||
// A check that the switch really happened, so that a failure is an
|
||||
// error and not silence. Asked of the track again rather than taken
|
||||
// from LiveKit's answer, which compares against the processed track
|
||||
// too. A muted track is stopped and takes the device on turning on again
|
||||
const now = publication.track;
|
||||
const deviceNow =
|
||||
now instanceof LocalTrack && !now.isMuted
|
||||
? await now.getDeviceId(false)
|
||||
const previous =
|
||||
current instanceof LocalTrack
|
||||
? await current.getDeviceId(false)
|
||||
: undefined;
|
||||
if (deviceNow !== undefined && deviceNow !== deviceId)
|
||||
throw new MatrixRTCError(
|
||||
`The ${base.source} is on another device than the one asked for`,
|
||||
);
|
||||
if (previous === deviceId) return;
|
||||
const kind = base.kind === "audio" ? "audioinput" : "videoinput";
|
||||
try {
|
||||
// Exact: asked for as a preference, the browser may open another
|
||||
// device that fits the rest of the constraints better
|
||||
await room.switchActiveDevice(kind, deviceId, true);
|
||||
// A check that the switch really happened, so that a failure is an
|
||||
// error and not silence. Asked of the track again rather than taken
|
||||
// from LiveKit's answer, which compares against the processed track
|
||||
// too. A muted track is stopped and takes the device on turning on again
|
||||
const deviceNow = await openDevice(publication.track);
|
||||
if (deviceNow !== undefined && deviceNow !== deviceId)
|
||||
throw new MatrixRTCError(
|
||||
`The ${base.source} is on another device than the one asked for`,
|
||||
);
|
||||
} catch (e) {
|
||||
// LiveKit stops the track before it opens the device asked for, so a
|
||||
// switch that fails leaves nothing running
|
||||
if (previous !== undefined && !isMuted(publication.track))
|
||||
// The failed switch is the error to report, not this one
|
||||
await room
|
||||
.switchActiveDevice(kind, previous, true)
|
||||
.catch(() => undefined);
|
||||
throw e;
|
||||
}
|
||||
},
|
||||
};
|
||||
if (base.kind === "audio") return { ...base, ...local };
|
||||
@@ -270,6 +273,19 @@ export function createLocalLivekitMediaTrack(
|
||||
};
|
||||
}
|
||||
|
||||
/** The device a local track captures from; none while it is muted. */
|
||||
async function openDevice(
|
||||
track: Track | undefined,
|
||||
): Promise<string | undefined> {
|
||||
return track instanceof LocalTrack && !isMuted(track)
|
||||
? track.getDeviceId(false)
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function isMuted(track: Track | undefined): boolean {
|
||||
return track instanceof LocalTrack && track.isMuted;
|
||||
}
|
||||
|
||||
/** The track behind a publication; a remote one arrives on subscription. */
|
||||
function publicationTrack$(
|
||||
scope: ObservableScope,
|
||||
|
||||
@@ -20,13 +20,7 @@ import {
|
||||
} from "../../../utils/test-fixtures";
|
||||
import type * as csApi from "./csApi";
|
||||
import type * as openID from "./openID";
|
||||
import {
|
||||
type AuthFlow,
|
||||
authenticateWithTransport,
|
||||
chooseAuthFlow,
|
||||
delegateDelayedLeave,
|
||||
getSFUConfig,
|
||||
} from ".";
|
||||
import { chooseAuthFlow, delegateDelayedLeave, getSFUConfig } from ".";
|
||||
|
||||
const aliceId = `${aliceUserId}:${aliceDeviceId}`;
|
||||
const csApiJWTToken = createJWTToken(aliceId, "via CS API");
|
||||
@@ -73,9 +67,6 @@ const urlAndServiceUrlTransport: UnstableLivekitTransport = {
|
||||
...serviceUrlTransport,
|
||||
};
|
||||
|
||||
const viaCsApi: AuthFlow = { kind: "csApi", url: "wss://livekit.example.org" };
|
||||
const viaOpenID: AuthFlow = { kind: "openID", serviceUrl };
|
||||
|
||||
/** The JWT service, answering each endpoint with a token that names it. */
|
||||
function mockJWTService(): void {
|
||||
fetchMock.post(`${serviceUrl}/sfu/get`, {
|
||||
@@ -109,9 +100,11 @@ describe("getSFUConfig", () => {
|
||||
logger,
|
||||
};
|
||||
|
||||
it("uses the CS API for the CS API flow", async () => {
|
||||
it("uses CS API with url transport", async () => {
|
||||
mockJWTService();
|
||||
expect(await getSFUConfig({ ...defaultParams, flow: viaCsApi })).toEqual(
|
||||
expect(
|
||||
await getSFUConfig({ ...defaultParams, transport: urlTransport }),
|
||||
).toEqual(
|
||||
expect.objectContaining({
|
||||
jwt: csApiJWTToken,
|
||||
livekitAlias: "via CS API",
|
||||
@@ -127,19 +120,21 @@ describe("getSFUConfig", () => {
|
||||
expect(jwtServiceCalls()).toEqual([]);
|
||||
});
|
||||
|
||||
it("reports the CS API missing where the homeserver lacks the endpoint, without falling back", async () => {
|
||||
it("does not fall back to OpenID with url transport", async () => {
|
||||
mockJWTService();
|
||||
client.getLivekitToken.mockRejectedValueOnce(unsupportedError);
|
||||
await expect(
|
||||
getSFUConfig({ ...defaultParams, flow: viaCsApi }),
|
||||
getSFUConfig({ ...defaultParams, transport: urlTransport }),
|
||||
).rejects.toThrow(expect.any(NoMatrix2AuthorizationService));
|
||||
expect(client.getLivekitToken).toHaveBeenCalled();
|
||||
expect(jwtServiceCalls()).toEqual([]);
|
||||
});
|
||||
|
||||
it("uses the JWT service for the OpenID flow", async () => {
|
||||
it("uses OpenID with livekit_service_url transport", async () => {
|
||||
mockJWTService();
|
||||
expect(await getSFUConfig({ ...defaultParams, flow: viaOpenID })).toEqual(
|
||||
expect(
|
||||
await getSFUConfig({ ...defaultParams, transport: serviceUrlTransport }),
|
||||
).toEqual(
|
||||
expect.objectContaining({
|
||||
jwt: defaultJWTToken,
|
||||
livekitAlias: "via default endpoint",
|
||||
@@ -149,141 +144,80 @@ describe("getSFUConfig", () => {
|
||||
expect(jwtServiceCalls()).toEqual(["/get_token"]);
|
||||
});
|
||||
|
||||
it("does not report the CS API missing where the homeserver refuses the request", async () => {
|
||||
mockJWTService();
|
||||
const forbidden = new MatrixError({ errcode: "M_FORBIDDEN" }, 403);
|
||||
client.getLivekitToken.mockRejectedValueOnce(forbidden);
|
||||
await expect(
|
||||
getSFUConfig({ ...defaultParams, flow: viaCsApi }),
|
||||
).rejects.toThrow(forbidden);
|
||||
expect(jwtServiceCalls()).toEqual([]);
|
||||
});
|
||||
|
||||
it("reports the CS API missing for another homeserver's transport", async () => {
|
||||
mockJWTService();
|
||||
client.getLivekitToken.mockRejectedValueOnce(
|
||||
new MatrixError({ errcode: "M_UNRECOGNIZED" }, 404),
|
||||
);
|
||||
await expect(
|
||||
getSFUConfig({
|
||||
...defaultParams,
|
||||
serverName: "elsewhere.org",
|
||||
flow: viaCsApi,
|
||||
}),
|
||||
).rejects.toThrow(expect.any(NoMatrix2AuthorizationService));
|
||||
expect(jwtServiceCalls()).toEqual([]);
|
||||
});
|
||||
|
||||
it("reports the CS API missing where a widget host relays the homeserver's not found", async () => {
|
||||
mockJWTService();
|
||||
// The widget API's WidgetApiResponseError arrives in a minified build.
|
||||
const relayed = Object.assign(new Error("Unrecognized request"), {
|
||||
name: "n",
|
||||
data: {
|
||||
matrix_api_error: {
|
||||
http_status: 404,
|
||||
response: { errcode: "M_UNRECOGNIZED" },
|
||||
},
|
||||
},
|
||||
});
|
||||
client.getLivekitToken.mockRejectedValueOnce(relayed);
|
||||
await expect(
|
||||
getSFUConfig({ ...defaultParams, flow: viaCsApi }),
|
||||
).rejects.toThrow(expect.any(NoMatrix2AuthorizationService));
|
||||
expect(jwtServiceCalls()).toEqual([]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["a token that does not decode", { jwt: "not a token" }],
|
||||
["an error of our own", new TypeError("oops")],
|
||||
])("does not judge the CS API by %s", async (_what, outcome) => {
|
||||
mockJWTService();
|
||||
if (outcome instanceof Error)
|
||||
client.getLivekitToken.mockRejectedValueOnce(outcome);
|
||||
else client.getLivekitToken.mockResolvedValueOnce(outcome);
|
||||
await expect(
|
||||
getSFUConfig({ ...defaultParams, flow: viaCsApi }),
|
||||
).rejects.not.toBeInstanceOf(NoMatrix2AuthorizationService);
|
||||
expect(jwtServiceCalls()).toEqual([]);
|
||||
});
|
||||
|
||||
it("uses the CS API when publishing through the CS API flow", async () => {
|
||||
it("uses OpenID when subscribing with url + livekit_service_url transport", async () => {
|
||||
mockJWTService();
|
||||
expect(
|
||||
await getSFUConfig({
|
||||
...defaultParams,
|
||||
flow: viaCsApi,
|
||||
transport: urlAndServiceUrlTransport,
|
||||
}),
|
||||
).toEqual(
|
||||
expect.objectContaining({
|
||||
jwt: defaultJWTToken,
|
||||
livekitAlias: "via default endpoint",
|
||||
}),
|
||||
);
|
||||
expect(client.getLivekitToken).not.toHaveBeenCalled();
|
||||
expect(jwtServiceCalls()).toEqual(["/get_token"]);
|
||||
});
|
||||
|
||||
it("surfaces the widget host's refusal with url transport", async () => {
|
||||
mockJWTService();
|
||||
const error = new Error(
|
||||
"The rtc_livekit_get_token action is not supported by the client.",
|
||||
);
|
||||
client.getLivekitToken.mockRejectedValueOnce(error);
|
||||
await expect(
|
||||
getSFUConfig({ ...defaultParams, transport: urlTransport }),
|
||||
).rejects.toThrow(error);
|
||||
expect(jwtServiceCalls()).toEqual([]);
|
||||
});
|
||||
|
||||
it("uses CS API when publishing with url transport", async () => {
|
||||
mockJWTService();
|
||||
expect(
|
||||
await getSFUConfig({
|
||||
...defaultParams,
|
||||
transport: urlTransport,
|
||||
role: "publisher",
|
||||
}),
|
||||
).toEqual(expect.objectContaining({ jwt: csApiJWTToken }));
|
||||
expect(client.getLivekitToken).toHaveBeenCalled();
|
||||
expect(jwtServiceCalls()).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("authenticateWithTransport", () => {
|
||||
const defaultParams = {
|
||||
client,
|
||||
membership,
|
||||
serverName: "example.org",
|
||||
role: "subscriber" as const,
|
||||
roomId,
|
||||
slotId,
|
||||
logger,
|
||||
};
|
||||
|
||||
it("uses CS API with url + livekit_service_url transport", async () => {
|
||||
mockJWTService();
|
||||
expect(
|
||||
await authenticateWithTransport({
|
||||
...defaultParams,
|
||||
transport: urlAndServiceUrlTransport,
|
||||
}),
|
||||
).toEqual(expect.objectContaining({ jwt: csApiJWTToken }));
|
||||
expect(jwtServiceCalls()).toEqual([]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["subscriber", "/get_token", defaultJWTToken],
|
||||
["publisher", "/sfu/get", legacyJWTToken],
|
||||
] as const)(
|
||||
"falls back to OpenID as %s where the homeserver lacks the endpoint",
|
||||
async (role, endpoint, jwt) => {
|
||||
mockJWTService();
|
||||
client.getLivekitToken.mockRejectedValueOnce(unsupportedError);
|
||||
expect(
|
||||
await authenticateWithTransport({
|
||||
...defaultParams,
|
||||
transport: urlAndServiceUrlTransport,
|
||||
role,
|
||||
}),
|
||||
).toEqual(expect.objectContaining({ jwt }));
|
||||
expect(client.getLivekitToken).toHaveBeenCalledTimes(1);
|
||||
expect(jwtServiceCalls()).toEqual([endpoint]);
|
||||
},
|
||||
);
|
||||
|
||||
it("does not fall back with url transport", async () => {
|
||||
it("does not fall back to OpenID when publishing with url transport", async () => {
|
||||
mockJWTService();
|
||||
client.getLivekitToken.mockRejectedValueOnce(unsupportedError);
|
||||
await expect(
|
||||
authenticateWithTransport({ ...defaultParams, transport: urlTransport }),
|
||||
getSFUConfig({
|
||||
...defaultParams,
|
||||
transport: urlTransport,
|
||||
role: "publisher",
|
||||
}),
|
||||
).rejects.toThrow(expect.any(NoMatrix2AuthorizationService));
|
||||
expect(client.getLivekitToken).toHaveBeenCalledTimes(1);
|
||||
expect(client.getLivekitToken).toHaveBeenCalled();
|
||||
expect(jwtServiceCalls()).toEqual([]);
|
||||
});
|
||||
|
||||
it("does not fall back where the homeserver refuses the request", async () => {
|
||||
it("uses the legacy OpenID endpoint when publishing with url + livekit_service_url transport", async () => {
|
||||
mockJWTService();
|
||||
const forbidden = new MatrixError({ errcode: "M_FORBIDDEN" }, 403);
|
||||
client.getLivekitToken.mockRejectedValueOnce(forbidden);
|
||||
await expect(
|
||||
authenticateWithTransport({
|
||||
// Subscribers predating MSC4195 expect a legacy participant identity from
|
||||
// anyone advertising a membership, which only the JWT service assigns
|
||||
expect(
|
||||
await getSFUConfig({
|
||||
...defaultParams,
|
||||
transport: urlAndServiceUrlTransport,
|
||||
role: "publisher",
|
||||
}),
|
||||
).rejects.toThrow(forbidden);
|
||||
expect(jwtServiceCalls()).toEqual([]);
|
||||
).toEqual(
|
||||
expect.objectContaining({
|
||||
jwt: legacyJWTToken,
|
||||
livekitAlias: "via legacy endpoint",
|
||||
}),
|
||||
);
|
||||
expect(client.getLivekitToken).not.toHaveBeenCalled();
|
||||
expect(jwtServiceCalls()).toEqual(["/sfu/get"]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -308,9 +242,9 @@ describe("delegateDelayedLeave", () => {
|
||||
return { delay_id, delay_timeout, delay_cs_api_url };
|
||||
}
|
||||
|
||||
it("uses the CS API for the CS API flow", async () => {
|
||||
it("uses CS API with url transport", async () => {
|
||||
mockJWTService();
|
||||
await delegateDelayedLeave({ ...defaultParams, flow: viaCsApi });
|
||||
await delegateDelayedLeave({ ...defaultParams, transport: urlTransport });
|
||||
expect(client.delegateDelayedLeave).toHaveBeenCalledWith({
|
||||
url: urlTransport.url,
|
||||
room_id: roomId,
|
||||
@@ -321,19 +255,37 @@ describe("delegateDelayedLeave", () => {
|
||||
expect(jwtServiceCalls()).toEqual([]);
|
||||
});
|
||||
|
||||
it("does not fall back to the JWT service from the CS API flow", async () => {
|
||||
it("does not fall back to OpenID with url transport", async () => {
|
||||
mockJWTService();
|
||||
client.delegateDelayedLeave.mockRejectedValueOnce(unsupportedError);
|
||||
await expect(
|
||||
delegateDelayedLeave({ ...defaultParams, flow: viaCsApi }),
|
||||
delegateDelayedLeave({ ...defaultParams, transport: urlTransport }),
|
||||
).rejects.toThrow();
|
||||
expect(client.delegateDelayedLeave).toHaveBeenCalled();
|
||||
expect(jwtServiceCalls()).toEqual([]);
|
||||
});
|
||||
|
||||
it("uses the JWT service for the OpenID flow", async () => {
|
||||
it("uses OpenID with livekit_service_url transport", async () => {
|
||||
mockJWTService();
|
||||
await delegateDelayedLeave({ ...defaultParams, flow: viaOpenID });
|
||||
await delegateDelayedLeave({
|
||||
...defaultParams,
|
||||
transport: serviceUrlTransport,
|
||||
});
|
||||
expect(client.delegateDelayedLeave).not.toHaveBeenCalled();
|
||||
expect(delegationViaJWTService()).toEqual({
|
||||
delay_id: "delay123",
|
||||
delay_timeout: 3_600_000,
|
||||
delay_cs_api_url: client.baseUrl,
|
||||
});
|
||||
});
|
||||
|
||||
it("uses OpenID with url + livekit_service_url transport", async () => {
|
||||
mockJWTService();
|
||||
// Must match the flow that got the token, so the identities line up
|
||||
await delegateDelayedLeave({
|
||||
...defaultParams,
|
||||
transport: urlAndServiceUrlTransport,
|
||||
});
|
||||
expect(client.delegateDelayedLeave).not.toHaveBeenCalled();
|
||||
expect(delegationViaJWTService()).toEqual({
|
||||
delay_id: "delay123",
|
||||
@@ -345,16 +297,21 @@ describe("delegateDelayedLeave", () => {
|
||||
|
||||
describe("chooseAuthFlow", () => {
|
||||
it.each([
|
||||
["url", urlTransport, true, viaCsApi],
|
||||
["url", urlTransport, false, viaCsApi],
|
||||
["livekit_service_url", serviceUrlTransport, true, viaOpenID],
|
||||
["livekit_service_url", serviceUrlTransport, false, viaOpenID],
|
||||
["url + livekit_service_url", urlAndServiceUrlTransport, true, viaCsApi],
|
||||
["url + livekit_service_url", urlAndServiceUrlTransport, false, viaOpenID],
|
||||
["url", urlTransport, { kind: "csApi", url: urlTransport.url }],
|
||||
[
|
||||
"livekit_service_url",
|
||||
serviceUrlTransport,
|
||||
{ kind: "openID", serviceUrl },
|
||||
],
|
||||
[
|
||||
"url + livekit_service_url",
|
||||
urlAndServiceUrlTransport,
|
||||
{ kind: "openID", serviceUrl },
|
||||
],
|
||||
] as const)(
|
||||
"chooses the flow for a %s transport with the CS API usable: %s",
|
||||
(_shape, transport, csApiUsable, flow) => {
|
||||
expect(chooseAuthFlow(transport, csApiUsable)).toEqual(flow);
|
||||
"chooses the flow for a %s transport as %s",
|
||||
(_shape, transport, flow) => {
|
||||
expect(chooseAuthFlow(transport)).toEqual(flow);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@@ -6,10 +6,13 @@ Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Authentication with a LiveKit transport.
|
||||
* Authentication with a LiveKit transport: the MSC4195 client-server API
|
||||
* through our homeserver for a transport with an SFU `url`, the OpenID flow
|
||||
* against the JWT service for one with a `livekit_service_url`, and the
|
||||
* choice between them where a transport carries both.
|
||||
*/
|
||||
|
||||
import { MatrixError } from "matrix-js-sdk";
|
||||
import { ConnectionError, MatrixError } from "matrix-js-sdk";
|
||||
import { type Logger } from "matrix-js-sdk/lib/logger";
|
||||
import { type UnstableLivekitTransport } from "matrix-js-sdk/lib/matrixrtc";
|
||||
import { type CallMembershipIdentityParts } from "matrix-js-sdk/lib/matrixrtc/EncryptionManager";
|
||||
@@ -25,66 +28,35 @@ export type * from "./types";
|
||||
|
||||
/**
|
||||
* Whether an error means the homeserver does not implement the MSC4195
|
||||
* endpoints. Such a homeserver answers with whatever it uses for unknown
|
||||
* routes (Synapse: 404 with `M_UNRECOGNIZED`), so any 404 counts.
|
||||
* endpoints. The MSC says `M_NOT_FOUND`; a homeserver without support answers
|
||||
* with whatever it uses for unknown routes (Synapse: 404 with
|
||||
* `M_UNRECOGNIZED`), so any 404 counts.
|
||||
*/
|
||||
export function isCsApiUnavailable(e: unknown): boolean {
|
||||
const answer = unwrapErrorDetails(e);
|
||||
function isEndpointUnsupported(e: unknown): boolean {
|
||||
return (
|
||||
answer !== undefined &&
|
||||
(answer.status === 404 ||
|
||||
answer.errcode === "M_NOT_FOUND" ||
|
||||
answer.errcode === "M_UNRECOGNIZED")
|
||||
e instanceof MatrixError &&
|
||||
(e.httpStatus === 404 ||
|
||||
e.errcode === "M_NOT_FOUND" ||
|
||||
e.errcode === "M_UNRECOGNIZED")
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tries to unwrap the details from an unknown error object, regardless of whether
|
||||
* it came from the Widget API or not.
|
||||
* Whether an error means the MSC4195 client-server API cannot be used from
|
||||
* here: the homeserver does not implement it, or the request never reached
|
||||
* the homeserver because a widget host does not expose the endpoint
|
||||
* (MSC4533), which the widget API reports as a plain error. A connection
|
||||
* error is neither: the endpoint may well exist.
|
||||
*/
|
||||
function unwrapErrorDetails(
|
||||
e: unknown,
|
||||
): { status?: number; errcode?: string } | undefined {
|
||||
// If the error is an instance of `MatrixError`, take its details directly.
|
||||
if (e instanceof MatrixError) {
|
||||
return { status: e.httpStatus, errcode: e.errcode };
|
||||
}
|
||||
|
||||
// If the error originated from the widget API, try to extract the bundled
|
||||
// Matrix API error. We identify the widget's `WidgetApiResponseError` by
|
||||
// the shape of its payload to avoid making the SDK dependent on the widget
|
||||
// API. This isn't great, but we'll drop this branch anyway once we eliminate
|
||||
// usage.
|
||||
if (e instanceof Error && "data" in e) {
|
||||
const relayed = (
|
||||
e as {
|
||||
data?: {
|
||||
matrix_api_error?: {
|
||||
http_status?: unknown;
|
||||
response?: { errcode?: unknown };
|
||||
};
|
||||
};
|
||||
}
|
||||
).data?.matrix_api_error;
|
||||
if (typeof relayed === "object" && relayed !== null) {
|
||||
const { http_status: status, response } = relayed;
|
||||
const errcode = response?.errcode;
|
||||
return {
|
||||
status: typeof status === "number" ? status : undefined,
|
||||
errcode: typeof errcode === "string" ? errcode : undefined,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// We're not able to extract any details from this error.
|
||||
return undefined;
|
||||
export function isCsApiUnavailable(e: unknown): boolean {
|
||||
if (isEndpointUnsupported(e)) return true;
|
||||
return !(e instanceof MatrixError) && !(e instanceof ConnectionError);
|
||||
}
|
||||
|
||||
export interface GetSFUConfigParams {
|
||||
client: csApi.ClientGetTokenParts & openID.ClientOpenIDParts;
|
||||
membership: CallMembershipIdentityParts;
|
||||
/** The flow to authenticate with, as chosen by {@link chooseAuthFlow}. */
|
||||
flow: AuthFlow;
|
||||
transport: UnstableLivekitTransport;
|
||||
/** The homeserver the transport belongs to. */
|
||||
serverName: string;
|
||||
roomId: string;
|
||||
@@ -94,23 +66,20 @@ export interface GetSFUConfigParams {
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets an {@link SFUConfig} for connecting to a transport through the given
|
||||
* auth flow.
|
||||
*
|
||||
* @throws {@link NoMatrix2AuthorizationService} if the client-server API flow
|
||||
* finds the API missing. The MSC defines no unstable feature flag, so this is
|
||||
* how a caller learns to choose its flows without the API from then on.
|
||||
* Gets an {@link SFUConfig} appropriate for connecting to a given transport,
|
||||
* using whichever auth flow is appropriate.
|
||||
*/
|
||||
export async function getSFUConfig({
|
||||
client,
|
||||
membership,
|
||||
flow,
|
||||
transport,
|
||||
serverName,
|
||||
roomId,
|
||||
slotId,
|
||||
role,
|
||||
logger,
|
||||
}: GetSFUConfigParams): Promise<SFUConfig> {
|
||||
const flow = chooseAuthFlow(transport);
|
||||
if (flow.kind === "openID") {
|
||||
return await openID.getSFUConfig({
|
||||
client,
|
||||
@@ -132,14 +101,10 @@ export async function getSFUConfig({
|
||||
slotId,
|
||||
});
|
||||
} catch (e) {
|
||||
if (isCsApiUnavailable(e)) {
|
||||
logger.warn(
|
||||
if (isEndpointUnsupported(e)) {
|
||||
logger.error(
|
||||
`Homeserver does not support the MSC4195 get_token endpoint, cannot get token for transport ${flow.url}`,
|
||||
);
|
||||
// This is our own homeserver's answer: as per MSC4195, only 403 /
|
||||
// M_FORBIDDEN and 400 / M_INVALID_PARAM are forwarded from the remote
|
||||
// server. Any other remote error becomes 502 / M_UNKNOWN on the
|
||||
// client-server API.
|
||||
throw new NoMatrix2AuthorizationService(e as Error);
|
||||
}
|
||||
throw e;
|
||||
@@ -147,40 +112,11 @@ export async function getSFUConfig({
|
||||
}
|
||||
}
|
||||
|
||||
export type AuthenticateWithTransportParams = Omit<
|
||||
GetSFUConfigParams,
|
||||
"flow"
|
||||
> & { transport: UnstableLivekitTransport };
|
||||
|
||||
/**
|
||||
* Authenticates with a transport once, outside any session. This automatically
|
||||
* falls back from the client-server API flow to the OpenID flow if needed and
|
||||
* possible.
|
||||
*
|
||||
* @throws {@link NoMatrix2AuthorizationService} if the client-server API is missing
|
||||
* but the transport does not allow falling back to the OpenID flow.
|
||||
*/
|
||||
export async function authenticateWithTransport({
|
||||
transport,
|
||||
...params
|
||||
}: AuthenticateWithTransportParams): Promise<SFUConfig> {
|
||||
try {
|
||||
const flow = chooseAuthFlow(transport, true);
|
||||
return await getSFUConfig({ ...params, flow });
|
||||
} catch (e) {
|
||||
const flow = chooseAuthFlow(transport, false);
|
||||
// Nothing else to try unless the API is missing and there is a JWT service
|
||||
if (!(e instanceof NoMatrix2AuthorizationService) || flow.kind !== "openID")
|
||||
throw e;
|
||||
return await getSFUConfig({ ...params, flow });
|
||||
}
|
||||
}
|
||||
|
||||
export interface DelegateDelayedLeaveParams {
|
||||
client: csApi.ClientDelegationParts & openID.ClientOpenIDParts;
|
||||
membership: CallMembershipIdentityParts;
|
||||
/** The flow that issued the token we publish with. */
|
||||
flow: AuthFlow;
|
||||
/** The transport we publish on. */
|
||||
transport: UnstableLivekitTransport;
|
||||
roomId: string;
|
||||
slotId: string;
|
||||
delayId: string;
|
||||
@@ -197,13 +133,14 @@ export interface DelegateDelayedLeaveParams {
|
||||
export async function delegateDelayedLeave({
|
||||
client,
|
||||
membership,
|
||||
flow,
|
||||
transport,
|
||||
roomId,
|
||||
slotId,
|
||||
delayId,
|
||||
delayTimeoutMs,
|
||||
logger,
|
||||
}: DelegateDelayedLeaveParams): Promise<void> {
|
||||
const flow = chooseAuthFlow(transport);
|
||||
if (flow.kind === "csApi") {
|
||||
try {
|
||||
await csApi.delegateDelayedLeave({
|
||||
@@ -215,7 +152,7 @@ export async function delegateDelayedLeave({
|
||||
delayId,
|
||||
});
|
||||
} catch (e) {
|
||||
if (isCsApiUnavailable(e))
|
||||
if (isEndpointUnsupported(e))
|
||||
logger.error(
|
||||
"Server misconfigured: transport contains a 'url' field but server does not support the MSC4195 delegate_delayed_leave endpoint",
|
||||
);
|
||||
@@ -244,21 +181,18 @@ export type AuthFlow =
|
||||
| { kind: "openID"; serviceUrl: string };
|
||||
|
||||
/**
|
||||
* Chooses which auth flow to use for a given transport.
|
||||
* Chooses which auth flow to use for a given transport. For now this returns a
|
||||
* single auth flow, with no provision for a fallback behavior.
|
||||
*/
|
||||
export function chooseAuthFlow(
|
||||
transport: UnstableLivekitTransport,
|
||||
csApiUsable: boolean,
|
||||
): AuthFlow {
|
||||
// If we only have url, we have no choice but to use the CS API.
|
||||
export function chooseAuthFlow(transport: UnstableLivekitTransport): AuthFlow {
|
||||
if ("url" in transport && !("livekit_service_url" in transport))
|
||||
return { kind: "csApi", url: transport.url };
|
||||
|
||||
// If we have both url and livekit_service_url, prefer the CS API if it is usable.
|
||||
if ("url" in transport && csApiUsable)
|
||||
return { kind: "csApi", url: transport.url };
|
||||
|
||||
// If the CS API is not usable or we only have livekit_service_url, fall back
|
||||
// to using the OpenID flow.
|
||||
// All other transports use the OpenID flow, even if they contain a `url`.
|
||||
// This is necessary since the auth flow determines the participant identity
|
||||
// format, and we still have older clients out in the wild which would not yet
|
||||
// know to look for a hashed participant identity in case `url` is present in
|
||||
// someone else's transport.
|
||||
// TODO: Once users have updated their clients, choose the CS API flow if
|
||||
// available, keeping OpenID as a fallback.
|
||||
return { kind: "openID", serviceUrl: transport.livekit_service_url };
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ Please see LICENSE in the repository root for full details.
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { VideoPresets, type VideoPreset } from "livekit-client";
|
||||
|
||||
import { cameraCaptureResolution } from "../../config";
|
||||
import { buildLiveKitOptions } from "./livekitOptions";
|
||||
|
||||
describe("buildLiveKitOptions", () => {
|
||||
@@ -108,6 +109,33 @@ describe("buildLiveKitOptions", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
undefined,
|
||||
90,
|
||||
180,
|
||||
240,
|
||||
360,
|
||||
480,
|
||||
540,
|
||||
720,
|
||||
1080,
|
||||
1440,
|
||||
2160,
|
||||
4320,
|
||||
])(
|
||||
"captures at what a lobby opens the camera at ahead of the join: %s",
|
||||
(height) => {
|
||||
const mediaQuality =
|
||||
height === undefined
|
||||
? undefined
|
||||
: { video: { max_resolution: height } };
|
||||
|
||||
expect(
|
||||
buildLiveKitOptions(mediaQuality).videoCaptureDefaults?.resolution,
|
||||
).toMatchObject(cameraCaptureResolution(mediaQuality));
|
||||
},
|
||||
);
|
||||
|
||||
it("screen share layers fall back to max_framerate, then 30", () => {
|
||||
const fromMax = buildLiveKitOptions({
|
||||
screen_share: {
|
||||
|
||||
@@ -276,6 +276,7 @@ export class MockRTCSession extends TypedEventEmitter<
|
||||
return this.joined;
|
||||
}
|
||||
|
||||
public slotDescription = { application: "m.call", id: "ROOM" };
|
||||
public slotId = "m.call#ROOM";
|
||||
/** The id of the delayed leave event; undefined until the manager has sent one. */
|
||||
public delayId: string | undefined = undefined;
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { afterEach, expect, test, vi } from "vitest";
|
||||
|
||||
const initSPA = vi.hoisted(() => vi.fn());
|
||||
vi.mock("./utils/spa", () => ({ initSPA }));
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs();
|
||||
vi.resetModules();
|
||||
initSPA.mockReset();
|
||||
});
|
||||
|
||||
test("the app restores its own session", async () => {
|
||||
vi.stubEnv("VITE_PACKAGE", "full");
|
||||
const { loadStandaloneClient } = await import("./App");
|
||||
const loadSession = vi.fn();
|
||||
const clearSession = vi.fn();
|
||||
initSPA.mockResolvedValue(null);
|
||||
|
||||
await expect(loadStandaloneClient!(loadSession, clearSession)).resolves.toBe(
|
||||
null,
|
||||
);
|
||||
expect(initSPA).toHaveBeenCalledWith(loadSession, clearSession);
|
||||
});
|
||||
|
||||
test("the embedded package has no session of its own", async () => {
|
||||
vi.stubEnv("VITE_PACKAGE", "embedded");
|
||||
const { loadStandaloneClient } = await import("./App");
|
||||
|
||||
expect(loadStandaloneClient).toBeUndefined();
|
||||
});
|
||||
+6
-2
@@ -64,8 +64,12 @@ const SentryRoute = Sentry.withSentryReactRouterV7Routing(Route);
|
||||
// - Imported on demand, as it was before, so that a widget, which gets its
|
||||
// client from the host, never downloads it.
|
||||
// - Module-level, so that the provider's effect sees one stable loader.
|
||||
const loadStandaloneClient: ClientLoader = async (...args) =>
|
||||
(await import("./utils/spa")).initSPA(...args);
|
||||
// - None in the embedded package, which only runs as a widget: the constant
|
||||
// condition lets its build drop the client setup and the store worker.
|
||||
export const loadStandaloneClient: ClientLoader | undefined =
|
||||
import.meta.env.VITE_PACKAGE === "embedded"
|
||||
? undefined
|
||||
: async (...args) => (await import("./utils/spa")).initSPA(...args);
|
||||
|
||||
interface SimpleProviderProps {
|
||||
children: JSX.Element;
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { expect, test } from "vitest";
|
||||
import { createClient, Room } from "matrix-js-sdk";
|
||||
import { withEmitter } from "@element-hq/matrixrtc-sdk";
|
||||
|
||||
import { createCallMatrixBackend } from "./CallMatrixBackend";
|
||||
|
||||
test("has the SDK's part and the call's own", () => {
|
||||
const { backend, room } = setup();
|
||||
|
||||
expect(backend.getUserId()).toBe("@alice:example.org");
|
||||
expect(backend.getJoinRule()).toBe(room.getJoinRule());
|
||||
expect(backend.relations).toBe(room.relations);
|
||||
});
|
||||
|
||||
test("reads the room's name as it is now, also as a room", () => {
|
||||
const { backend, room } = setup();
|
||||
const asRoom = withEmitter(backend, backend.roomEmitter);
|
||||
|
||||
room.name = "Renamed";
|
||||
expect(backend.name).toBe("Renamed");
|
||||
expect(asRoom.name).toBe("Renamed");
|
||||
});
|
||||
|
||||
function setup(): {
|
||||
backend: ReturnType<typeof createCallMatrixBackend>;
|
||||
room: Room;
|
||||
} {
|
||||
const client = createClient({
|
||||
baseUrl: "https://matrix.example.org",
|
||||
userId: "@alice:example.org",
|
||||
deviceId: "DEVICE",
|
||||
});
|
||||
const room = new Room("!room:example.org", client, "@alice:example.org");
|
||||
return { backend: createCallMatrixBackend(client, room), room };
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { type MatrixClient, type Room } from "matrix-js-sdk";
|
||||
import {
|
||||
createSdkMatrixBackend,
|
||||
type SdkMatrixBackend,
|
||||
} from "@element-hq/matrixrtc-sdk";
|
||||
|
||||
/** What a call needs of the client beyond the SDK's part. */
|
||||
type CallClientPart = Pick<
|
||||
MatrixClient,
|
||||
// Reactions and raised hands: decrypting, and lowering a hand
|
||||
| "decryptEventIfNeeded"
|
||||
| "redactEvent"
|
||||
// Our own display name and avatar
|
||||
| "getUser"
|
||||
// Changing them, where the host lets us (`supportsProfileChanges`)
|
||||
| "setDisplayName"
|
||||
| "setAvatarUrl"
|
||||
| "uploadContent"
|
||||
// Developer settings
|
||||
| "doesServerSupportUnstableFeature"
|
||||
| "getCrypto"
|
||||
>;
|
||||
|
||||
/** What a call needs of the room beyond the SDK's part. */
|
||||
type CallRoomPart = Pick<
|
||||
Room,
|
||||
// The header and the invite link
|
||||
| "name"
|
||||
| "getMxcAvatarUrl"
|
||||
// Whether to offer the invite link
|
||||
| "getJoinRule"
|
||||
// Raised hands already in the room
|
||||
| "relations"
|
||||
>;
|
||||
|
||||
/**
|
||||
* STOP GAP: everything a call needs from Matrix on one object. Its
|
||||
* `clientEmitter` also carries `MatrixEventEvent.Decrypted` (reactions); its
|
||||
* `roomEmitter` every room event.
|
||||
*/
|
||||
export interface CallMatrixBackend
|
||||
extends SdkMatrixBackend, CallClientPart, CallRoomPart {}
|
||||
|
||||
/** A call's backend from a client and a room. */
|
||||
export function createCallMatrixBackend(
|
||||
client: Parameters<typeof createSdkMatrixBackend>[0] & CallClientPart,
|
||||
room: Parameters<typeof createSdkMatrixBackend>[1] & CallRoomPart,
|
||||
): CallMatrixBackend {
|
||||
return {
|
||||
...createSdkMatrixBackend(client, room),
|
||||
decryptEventIfNeeded: client.decryptEventIfNeeded.bind(client),
|
||||
redactEvent: client.redactEvent.bind(client),
|
||||
getUser: client.getUser.bind(client),
|
||||
setDisplayName: client.setDisplayName.bind(client),
|
||||
setAvatarUrl: client.setAvatarUrl.bind(client),
|
||||
uploadContent: client.uploadContent.bind(client),
|
||||
doesServerSupportUnstableFeature:
|
||||
client.doesServerSupportUnstableFeature.bind(client),
|
||||
getCrypto: client.getCrypto.bind(client),
|
||||
// Read through: the room is renamed while we show it
|
||||
get name() {
|
||||
return room.name;
|
||||
},
|
||||
getMxcAvatarUrl: room.getMxcAvatarUrl.bind(room),
|
||||
getJoinRule: room.getJoinRule.bind(room),
|
||||
get relations() {
|
||||
return room.relations;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -20,7 +20,7 @@ import {
|
||||
const mockClient = (userId = "@alice:example.org"): MatrixClient =>
|
||||
({
|
||||
on: vi.fn(),
|
||||
removeListener: vi.fn(),
|
||||
off: vi.fn(),
|
||||
getUserId: () => userId,
|
||||
getDeviceId: () => "AAAA",
|
||||
stopClient: vi.fn(),
|
||||
|
||||
+41
-3
@@ -142,7 +142,7 @@ interface Props {
|
||||
* itself — from the widget API, or by restoring or creating a session of its
|
||||
* own.
|
||||
*/
|
||||
client?: MatrixClient;
|
||||
client?: SuppliedClient;
|
||||
/**
|
||||
* How Element Call finds a client when none is supplied: the standalone app
|
||||
* restores or creates a session of its own. Stable, as a hook dependency.
|
||||
@@ -161,6 +161,37 @@ interface Props {
|
||||
loadClient?: ClientLoader;
|
||||
}
|
||||
|
||||
/**
|
||||
* What is read of a supplied client under a call, and by this provider and
|
||||
* analytics. Stable methods only, so a host's client, from the host's own copy
|
||||
* of matrix-js-sdk, will do.
|
||||
*/
|
||||
export type SuppliedClient = Pick<
|
||||
MatrixClient,
|
||||
// The disconnected banner, and stopping a client opened elsewhere
|
||||
| "on"
|
||||
| "off"
|
||||
| "stopClient"
|
||||
// Analytics, through `window.matrixclient`
|
||||
| "getCrypto"
|
||||
| "isGuest"
|
||||
| "getAccountDataFromServer"
|
||||
| "setAccountData"
|
||||
// The room's encryption system
|
||||
| "getRoom"
|
||||
// Avatars
|
||||
| "mxcUrlToHttp"
|
||||
| "getAccessToken"
|
||||
// Rageshakes: who sends them, their crypto state, and asking others for theirs
|
||||
| "getUserId"
|
||||
| "getUser"
|
||||
| "credentials"
|
||||
| "deviceId"
|
||||
| "secretStorage"
|
||||
| "isKeyBackupKeyStored"
|
||||
| "sendEvent"
|
||||
>;
|
||||
|
||||
/**
|
||||
* Restores or creates a session of Element Call's own, kept where the given
|
||||
* functions keep it. Resolves to null when no one is signed in.
|
||||
@@ -170,7 +201,14 @@ export type ClientLoader = (
|
||||
clearSession: () => void,
|
||||
) => Promise<InitResult | null>;
|
||||
|
||||
export const ClientProvider: FC<Props> = ({ children, client, loadClient }) => {
|
||||
export const ClientProvider: FC<Props> = ({
|
||||
children,
|
||||
client: suppliedClient,
|
||||
loadClient,
|
||||
}) => {
|
||||
// STOP GAP: held as a whole client, as the standalone and widget pages need
|
||||
// one. A component host's client is only read through `SuppliedClient`.
|
||||
const client = suppliedClient as MatrixClient | undefined;
|
||||
const leaveToHome = useLeaveToHome();
|
||||
const hostBridge = useHostBridge();
|
||||
|
||||
@@ -372,7 +410,7 @@ export const ClientProvider: FC<Props> = ({ children, client, loadClient }) => {
|
||||
|
||||
return (): void => {
|
||||
if (initClientState.client) {
|
||||
initClientState.client.removeListener(ClientEvent.Sync, onSync);
|
||||
initClientState.client.off(ClientEvent.Sync, onSync);
|
||||
}
|
||||
};
|
||||
}, [initClientState, onSync, hostBridge]);
|
||||
|
||||
@@ -18,11 +18,17 @@ Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import {
|
||||
RTC_CALL_INTENT_AUDIO,
|
||||
RTC_CALL_INTENT_VIDEO,
|
||||
type RTCCallIntent,
|
||||
type RTCNotificationType,
|
||||
} from "matrix-js-sdk/lib/matrixrtc";
|
||||
// Not from the `matrixrtc` index above. Those are not type imports,
|
||||
// So those two imports would add a whole copy of "matrix-js-sdk/lib/matrixrtc"
|
||||
// The "api.ts" file is meant to be the only thing loaded by EW on pageload.
|
||||
// Everything beyond it should be lazy loaded on first call start.
|
||||
import {
|
||||
RTC_CALL_INTENT_AUDIO,
|
||||
RTC_CALL_INTENT_VIDEO,
|
||||
} from "matrix-js-sdk/lib/matrixrtc/CallIntent";
|
||||
|
||||
import { platform } from "./Platform";
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
afterAll,
|
||||
} from "vitest";
|
||||
import { logger } from "matrix-js-sdk/lib/logger";
|
||||
import { type MatrixRTCSession } from "matrix-js-sdk/lib/matrixrtc";
|
||||
import { type Statistics } from "matrix-js-sdk/lib/matrixrtc";
|
||||
|
||||
import { PosthogAnalytics } from "./PosthogAnalytics";
|
||||
import {
|
||||
@@ -34,16 +34,14 @@ const defaultTotals = {
|
||||
roomEventEncryptionKeysReceivedTotalAge: 500,
|
||||
};
|
||||
|
||||
function createMockRtcSession(overrides?: {
|
||||
function createMockStatistics(overrides?: {
|
||||
counters?: Partial<typeof defaultCounters>;
|
||||
totals?: Partial<typeof defaultTotals>;
|
||||
}): MatrixRTCSession {
|
||||
}): Statistics {
|
||||
return {
|
||||
statistics: {
|
||||
counters: { ...defaultCounters, ...overrides?.counters },
|
||||
totals: { ...defaultTotals, ...overrides?.totals },
|
||||
},
|
||||
} as unknown as MatrixRTCSession;
|
||||
counters: { ...defaultCounters, ...overrides?.counters },
|
||||
totals: { ...defaultTotals, ...overrides?.totals },
|
||||
} as Statistics;
|
||||
}
|
||||
|
||||
describe("CallEnded", () => {
|
||||
@@ -65,9 +63,9 @@ describe("CallEnded", () => {
|
||||
it("warns if startTime is missing when track is called", () => {
|
||||
const warnSpy = vi.spyOn(logger, "warn");
|
||||
const tracker = new CallEndedTracker();
|
||||
const mockSession = createMockRtcSession();
|
||||
const statistics = createMockStatistics();
|
||||
|
||||
tracker.track("test-call-id", 2, false, mockSession);
|
||||
tracker.track("test-call-id", 2, false, statistics);
|
||||
|
||||
expect(warnSpy).toHaveBeenCalledWith(
|
||||
"[PosthogEvents] Failed to send posthog callEnded event due to missing startTime",
|
||||
@@ -77,11 +75,11 @@ describe("CallEnded", () => {
|
||||
|
||||
it("tracks event with correct properties when startTime is set", () => {
|
||||
const tracker = new CallEndedTracker();
|
||||
const mockSession = createMockRtcSession();
|
||||
const statistics = createMockStatistics();
|
||||
|
||||
tracker.cacheStartCall(new Date(Date.now() - 60000));
|
||||
tracker.cacheParticipantCountChanged(5);
|
||||
tracker.track("test-call-id", 3, true, mockSession);
|
||||
tracker.track("test-call-id", 3, true, statistics);
|
||||
|
||||
expect(PosthogAnalytics.instance.trackEvent).toHaveBeenCalledWith(
|
||||
{
|
||||
@@ -105,13 +103,13 @@ describe("CallEnded", () => {
|
||||
|
||||
it("tracks maxParticipantsCount correctly across multiple changes", () => {
|
||||
const tracker = new CallEndedTracker();
|
||||
const mockSession = createMockRtcSession();
|
||||
const statistics = createMockStatistics();
|
||||
|
||||
tracker.cacheStartCall(new Date());
|
||||
tracker.cacheParticipantCountChanged(3);
|
||||
tracker.cacheParticipantCountChanged(7);
|
||||
tracker.cacheParticipantCountChanged(2);
|
||||
tracker.track("test-call-id", 1, false, mockSession);
|
||||
tracker.track("test-call-id", 1, false, statistics);
|
||||
|
||||
expect(PosthogAnalytics.instance.trackEvent).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
@@ -123,12 +121,12 @@ describe("CallEnded", () => {
|
||||
|
||||
it("computes roomEventEncryptionKeysReceivedAverageAge as 0 when no keys received", () => {
|
||||
const tracker = new CallEndedTracker();
|
||||
const mockSession = createMockRtcSession({
|
||||
const statistics = createMockStatistics({
|
||||
counters: { roomEventEncryptionKeysReceived: 0 },
|
||||
});
|
||||
|
||||
tracker.cacheStartCall(new Date());
|
||||
tracker.track("test-call-id", 1, false, mockSession);
|
||||
tracker.track("test-call-id", 1, false, statistics);
|
||||
|
||||
expect(PosthogAnalytics.instance.trackEvent).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
@@ -140,13 +138,13 @@ describe("CallEnded", () => {
|
||||
|
||||
it("computes roomEventEncryptionKeysReceivedAverageAge correctly when keys are received", () => {
|
||||
const tracker = new CallEndedTracker();
|
||||
const mockSession = createMockRtcSession({
|
||||
const statistics = createMockStatistics({
|
||||
counters: { roomEventEncryptionKeysReceived: 4 },
|
||||
totals: { roomEventEncryptionKeysReceivedTotalAge: 200 },
|
||||
});
|
||||
|
||||
tracker.cacheStartCall(new Date());
|
||||
tracker.track("test-call-id", 1, false, mockSession);
|
||||
tracker.track("test-call-id", 1, false, statistics);
|
||||
|
||||
expect(PosthogAnalytics.instance.trackEvent).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
@@ -158,10 +156,10 @@ describe("CallEnded", () => {
|
||||
|
||||
it("passes send_instantly option correctly", () => {
|
||||
const tracker = new CallEndedTracker();
|
||||
const mockSession = createMockRtcSession();
|
||||
const statistics = createMockStatistics();
|
||||
|
||||
tracker.cacheStartCall(new Date());
|
||||
tracker.track("test-call-id", 1, false, mockSession);
|
||||
tracker.track("test-call-id", 1, false, statistics);
|
||||
|
||||
expect(PosthogAnalytics.instance.trackEvent).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
@@ -171,14 +169,14 @@ describe("CallEnded", () => {
|
||||
|
||||
it("includes per-reason reconnecting counts in CallEnded", () => {
|
||||
const tracker = new CallEndedTracker();
|
||||
const mockSession = createMockRtcSession();
|
||||
const statistics = createMockStatistics();
|
||||
|
||||
tracker.cacheStartCall(new Date());
|
||||
tracker.cacheReconnecting("sync");
|
||||
tracker.cacheReconnecting("sync");
|
||||
tracker.cacheReconnecting("livekit");
|
||||
tracker.cacheReconnecting("membership");
|
||||
tracker.track("test-call-id", 1, false, mockSession);
|
||||
tracker.track("test-call-id", 1, false, statistics);
|
||||
|
||||
expect(PosthogAnalytics.instance.trackEvent).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
|
||||
@@ -7,7 +7,7 @@ Please see LICENSE in the repository root for full details.
|
||||
|
||||
import { type DisconnectReason } from "livekit-client";
|
||||
import { logger } from "matrix-js-sdk/lib/logger";
|
||||
import { type MatrixRTCSession } from "matrix-js-sdk/lib/matrixrtc";
|
||||
import { type Statistics } from "matrix-js-sdk/lib/matrixrtc";
|
||||
|
||||
import {
|
||||
type IPosthogEvent,
|
||||
@@ -80,7 +80,7 @@ export class CallEndedTracker {
|
||||
callId: string,
|
||||
callParticipantsNow: number,
|
||||
sendInstantly: boolean,
|
||||
rtcSession: MatrixRTCSession,
|
||||
statistics: Statistics,
|
||||
): void {
|
||||
if (this.cache.startTime) {
|
||||
PosthogAnalytics.instance.trackEvent<CallEnded>(
|
||||
@@ -91,14 +91,13 @@ export class CallEndedTracker {
|
||||
callParticipantsOnLeave: callParticipantsNow,
|
||||
callDuration: (Date.now() - this.cache.startTime.getTime()) / 1000,
|
||||
roomEventEncryptionKeysSent:
|
||||
rtcSession.statistics.counters.roomEventEncryptionKeysSent,
|
||||
statistics.counters.roomEventEncryptionKeysSent,
|
||||
roomEventEncryptionKeysReceived:
|
||||
rtcSession.statistics.counters.roomEventEncryptionKeysReceived,
|
||||
statistics.counters.roomEventEncryptionKeysReceived,
|
||||
roomEventEncryptionKeysReceivedAverageAge:
|
||||
rtcSession.statistics.counters.roomEventEncryptionKeysReceived > 0
|
||||
? rtcSession.statistics.totals
|
||||
.roomEventEncryptionKeysReceivedTotalAge /
|
||||
rtcSession.statistics.counters.roomEventEncryptionKeysReceived
|
||||
statistics.counters.roomEventEncryptionKeysReceived > 0
|
||||
? statistics.totals.roomEventEncryptionKeysReceivedTotalAge /
|
||||
statistics.counters.roomEventEncryptionKeysReceived
|
||||
: 0,
|
||||
callReconnectingCount: this.cache.reconnectingCount,
|
||||
callReconnectingCountSync: this.cache.reconnectingCountByReason.sync,
|
||||
|
||||
@@ -147,11 +147,13 @@ export const RegisterPage: FC = () => {
|
||||
}
|
||||
}, [loading, navigate, authenticated, passwordlessUser, registering]);
|
||||
|
||||
if (loading) {
|
||||
return <LoadingPage />;
|
||||
} else {
|
||||
PosthogAnalytics.instance.eventSignup.cacheSignupStart(new Date());
|
||||
}
|
||||
useEffect(() => {
|
||||
if (!loading) {
|
||||
PosthogAnalytics.instance.eventSignup.cacheSignupStart(new Date());
|
||||
}
|
||||
}, [loading]);
|
||||
|
||||
if (loading) return <LoadingPage />;
|
||||
|
||||
return (
|
||||
<>
|
||||
|
||||
@@ -10,13 +10,13 @@ import { expect, test } from "vitest";
|
||||
import { TooltipProvider } from "@vector-im/compound-web";
|
||||
import { userEvent } from "@testing-library/user-event";
|
||||
import { type ReactNode } from "react";
|
||||
import { type MatrixClient, type Room } from "matrix-js-sdk";
|
||||
|
||||
import { ReactionToggleButton } from "./ReactionToggleButton";
|
||||
import { ElementCallReactionEventType } from "../reactions";
|
||||
import { type CallViewModel } from "../state/CallViewModel/CallViewModel";
|
||||
import { getBasicCallViewModelEnvironment } from "../utils/test-viewmodel";
|
||||
import { alice, local, localRtcMember } from "../utils/test-fixtures";
|
||||
import { type MockRTCSession } from "../utils/test";
|
||||
import { ReactionsSenderProvider } from "../reactions/useReactionsSender";
|
||||
import { initializeWidget } from "../widget";
|
||||
initializeWidget();
|
||||
@@ -24,18 +24,17 @@ initializeWidget();
|
||||
const localIdent = `${localRtcMember.userId}:${localRtcMember.deviceId}`;
|
||||
|
||||
function TestComponent({
|
||||
rtcSession,
|
||||
matrixRoom,
|
||||
client,
|
||||
vm,
|
||||
}: {
|
||||
rtcSession: MockRTCSession;
|
||||
matrixRoom: Room;
|
||||
client: MatrixClient;
|
||||
vm: CallViewModel;
|
||||
}): ReactNode {
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<ReactionsSenderProvider
|
||||
vm={vm}
|
||||
rtcSession={rtcSession.asMockedSession()}
|
||||
>
|
||||
<ReactionsSenderProvider vm={vm} room={matrixRoom} client={client}>
|
||||
<ReactionToggleButton
|
||||
reactionData={{
|
||||
reactions$: vm.reactions$,
|
||||
@@ -50,9 +49,9 @@ function TestComponent({
|
||||
|
||||
test("Can open menu", async () => {
|
||||
const user = userEvent.setup();
|
||||
const { vm, rtcSession } = getBasicCallViewModelEnvironment([alice]);
|
||||
const { vm, matrixRoom, client } = getBasicCallViewModelEnvironment([alice]);
|
||||
const { getByLabelText, container } = render(
|
||||
<TestComponent vm={vm} rtcSession={rtcSession} />,
|
||||
<TestComponent vm={vm} matrixRoom={matrixRoom} client={client} />,
|
||||
);
|
||||
await user.click(getByLabelText("Reactions"));
|
||||
expect(container).toMatchSnapshot();
|
||||
@@ -60,15 +59,15 @@ test("Can open menu", async () => {
|
||||
|
||||
test("Can raise hand", async () => {
|
||||
const user = userEvent.setup();
|
||||
const { vm, rtcSession, handRaisedSubject$ } =
|
||||
const { vm, matrixRoom, client, handRaisedSubject$ } =
|
||||
getBasicCallViewModelEnvironment([local, alice]);
|
||||
const { getByLabelText, container } = render(
|
||||
<TestComponent vm={vm} rtcSession={rtcSession} />,
|
||||
<TestComponent vm={vm} matrixRoom={matrixRoom} client={client} />,
|
||||
);
|
||||
await user.click(getByLabelText("Reactions"));
|
||||
await user.click(getByLabelText("Raise hand"));
|
||||
expect(rtcSession.room.client.sendEvent).toHaveBeenCalledWith(
|
||||
rtcSession.room.roomId,
|
||||
expect(client.sendEvent).toHaveBeenCalledWith(
|
||||
matrixRoom.roomId,
|
||||
"m.reaction",
|
||||
{
|
||||
"m.relates_to": {
|
||||
@@ -94,10 +93,10 @@ test("Can raise hand", async () => {
|
||||
test("Can lower hand", async () => {
|
||||
const reactionEventId = "$my-reaction-event:example.org";
|
||||
const user = userEvent.setup();
|
||||
const { vm, rtcSession, handRaisedSubject$ } =
|
||||
const { vm, matrixRoom, client, handRaisedSubject$ } =
|
||||
getBasicCallViewModelEnvironment([local, alice]);
|
||||
const { getByLabelText, container } = render(
|
||||
<TestComponent vm={vm} rtcSession={rtcSession} />,
|
||||
<TestComponent vm={vm} matrixRoom={matrixRoom} client={client} />,
|
||||
);
|
||||
await user.click(getByLabelText("Reactions"));
|
||||
await user.click(getByLabelText("Raise hand"));
|
||||
@@ -112,8 +111,8 @@ test("Can lower hand", async () => {
|
||||
});
|
||||
await user.click(getByLabelText("Reactions"));
|
||||
await user.click(getByLabelText("Lower hand"));
|
||||
expect(rtcSession.room.client.redactEvent).toHaveBeenCalledWith(
|
||||
rtcSession.room.roomId,
|
||||
expect(client.redactEvent).toHaveBeenCalledWith(
|
||||
matrixRoom.roomId,
|
||||
reactionEventId,
|
||||
);
|
||||
act(() => {
|
||||
@@ -125,14 +124,17 @@ test("Can lower hand", async () => {
|
||||
|
||||
test("Can react with emoji", async () => {
|
||||
const user = userEvent.setup();
|
||||
const { vm, rtcSession } = getBasicCallViewModelEnvironment([local, alice]);
|
||||
const { vm, matrixRoom, client } = getBasicCallViewModelEnvironment([
|
||||
local,
|
||||
alice,
|
||||
]);
|
||||
const { getByLabelText, getByText } = render(
|
||||
<TestComponent vm={vm} rtcSession={rtcSession} />,
|
||||
<TestComponent vm={vm} matrixRoom={matrixRoom} client={client} />,
|
||||
);
|
||||
await user.click(getByLabelText("Reactions"));
|
||||
await user.click(getByText("🐶"));
|
||||
expect(rtcSession.room.client.sendEvent).toHaveBeenCalledWith(
|
||||
rtcSession.room.roomId,
|
||||
expect(client.sendEvent).toHaveBeenCalledWith(
|
||||
matrixRoom.roomId,
|
||||
ElementCallReactionEventType,
|
||||
{
|
||||
"m.relates_to": {
|
||||
@@ -147,16 +149,19 @@ test("Can react with emoji", async () => {
|
||||
|
||||
test("Can fully expand emoji picker", async () => {
|
||||
const user = userEvent.setup();
|
||||
const { vm, rtcSession } = getBasicCallViewModelEnvironment([local, alice]);
|
||||
const { vm, matrixRoom, client } = getBasicCallViewModelEnvironment([
|
||||
local,
|
||||
alice,
|
||||
]);
|
||||
const { getByLabelText, container, getByText } = render(
|
||||
<TestComponent vm={vm} rtcSession={rtcSession} />,
|
||||
<TestComponent vm={vm} matrixRoom={matrixRoom} client={client} />,
|
||||
);
|
||||
await user.click(getByLabelText("Reactions"));
|
||||
await user.click(getByLabelText("Show more"));
|
||||
expect(container).toMatchSnapshot();
|
||||
await user.click(getByText("🦗"));
|
||||
expect(rtcSession.room.client.sendEvent).toHaveBeenCalledWith(
|
||||
rtcSession.room.roomId,
|
||||
expect(client.sendEvent).toHaveBeenCalledWith(
|
||||
matrixRoom.roomId,
|
||||
ElementCallReactionEventType,
|
||||
{
|
||||
"m.relates_to": {
|
||||
@@ -171,9 +176,12 @@ test("Can fully expand emoji picker", async () => {
|
||||
|
||||
test("Can close reaction dialog", async () => {
|
||||
const user = userEvent.setup();
|
||||
const { vm, rtcSession } = getBasicCallViewModelEnvironment([local, alice]);
|
||||
const { vm, matrixRoom, client } = getBasicCallViewModelEnvironment([
|
||||
local,
|
||||
alice,
|
||||
]);
|
||||
const { getByLabelText, container } = render(
|
||||
<TestComponent vm={vm} rtcSession={rtcSession} />,
|
||||
<TestComponent vm={vm} matrixRoom={matrixRoom} client={client} />,
|
||||
);
|
||||
await user.click(getByLabelText("Reactions"));
|
||||
await user.click(getByLabelText("Show more"));
|
||||
|
||||
@@ -37,7 +37,12 @@ interface UseProfile extends ProfileLoadState {
|
||||
saveProfile: ProfileSaveCallback;
|
||||
}
|
||||
|
||||
export function useProfile(client: MatrixClient | undefined): UseProfile {
|
||||
export type ProfileClientParts = Pick<
|
||||
MatrixClient,
|
||||
"getUserId" | "getUser" | "setDisplayName" | "setAvatarUrl" | "uploadContent"
|
||||
>;
|
||||
|
||||
export function useProfile(client: ProfileClientParts | undefined): UseProfile {
|
||||
const [{ success, loading, displayName, avatarUrl, error }, setState] =
|
||||
useState<ProfileLoadState>(() => {
|
||||
let user: User | undefined = undefined;
|
||||
|
||||
@@ -23,30 +23,130 @@ import {
|
||||
localRtcMember,
|
||||
} from "../utils/test-fixtures";
|
||||
import { getBasicRTCSession } from "../utils/test-viewmodel";
|
||||
import { testScope, withTestScheduler } from "../utils/test";
|
||||
import { mockRtcMembership, testScope, withTestScheduler } from "../utils/test";
|
||||
import { ElementCallReactionEventType, ReactionSet } from ".";
|
||||
|
||||
afterEach(() => {
|
||||
vitest.useRealTimers();
|
||||
});
|
||||
|
||||
test("handles a hand raised reaction", () => {
|
||||
const { rtcSession } = getBasicRTCSession([local, alice]);
|
||||
function raiseLocalHand(
|
||||
matrixRoom: ReturnType<typeof getBasicRTCSession>["matrixRoom"],
|
||||
reactionEventId: string,
|
||||
localTimestamp: Date,
|
||||
): void {
|
||||
matrixRoom.emit(
|
||||
MatrixRoomEvent.Timeline,
|
||||
new MatrixEvent({
|
||||
room_id: matrixRoom.roomId,
|
||||
event_id: reactionEventId,
|
||||
sender: localRtcMember.userId,
|
||||
type: EventType.Reaction,
|
||||
origin_server_ts: localTimestamp.getTime(),
|
||||
content: {
|
||||
"m.relates_to": { event_id: localRtcMember.eventId, key: "🖐️" },
|
||||
},
|
||||
}),
|
||||
matrixRoom,
|
||||
undefined,
|
||||
false,
|
||||
{} as IRoomTimelineData,
|
||||
);
|
||||
}
|
||||
|
||||
test("lowers the hand of a member who leaves", () => {
|
||||
const { members$, matrixRoom, client, rtcMemberships$ } = getBasicRTCSession([
|
||||
local,
|
||||
alice,
|
||||
]);
|
||||
const reactionEventId = "$my_event_id:example.org";
|
||||
const localTimestamp = new Date();
|
||||
withTestScheduler(({ schedule, expectObservable }) => {
|
||||
renderHook(() => {
|
||||
const { raisedHands$ } = new ReactionsReader(
|
||||
testScope(),
|
||||
rtcSession.asMockedSession(),
|
||||
members$,
|
||||
matrixRoom,
|
||||
client,
|
||||
);
|
||||
schedule("abc", {
|
||||
a: () => {},
|
||||
b: () => raiseLocalHand(matrixRoom, reactionEventId, localTimestamp),
|
||||
c: () => rtcMemberships$.next([aliceRtcMember]),
|
||||
});
|
||||
expectObservable(raisedHands$).toBe("abc", {
|
||||
a: {},
|
||||
b: {
|
||||
[`${localRtcMember.userId}:${localRtcMember.deviceId}`]: {
|
||||
reactionEventId,
|
||||
membershipEventId: localRtcMember.eventId,
|
||||
time: localTimestamp,
|
||||
},
|
||||
},
|
||||
c: {},
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test("lowers the hand of a member whose membership is sent again", () => {
|
||||
const { members$, matrixRoom, client, rtcMemberships$ } = getBasicRTCSession([
|
||||
local,
|
||||
alice,
|
||||
]);
|
||||
const reactionEventId = "$my_event_id:example.org";
|
||||
const localTimestamp = new Date();
|
||||
const resent = mockRtcMembership(
|
||||
localRtcMember.userId,
|
||||
localRtcMember.deviceId,
|
||||
);
|
||||
withTestScheduler(({ schedule, expectObservable }) => {
|
||||
renderHook(() => {
|
||||
const { raisedHands$ } = new ReactionsReader(
|
||||
testScope(),
|
||||
members$,
|
||||
matrixRoom,
|
||||
client,
|
||||
);
|
||||
schedule("abc", {
|
||||
a: () => {},
|
||||
b: () => raiseLocalHand(matrixRoom, reactionEventId, localTimestamp),
|
||||
c: () => rtcMemberships$.next([resent, aliceRtcMember]),
|
||||
});
|
||||
expectObservable(raisedHands$).toBe("abc", {
|
||||
a: {},
|
||||
b: {
|
||||
[`${localRtcMember.userId}:${localRtcMember.deviceId}`]: {
|
||||
reactionEventId,
|
||||
membershipEventId: localRtcMember.eventId,
|
||||
time: localTimestamp,
|
||||
},
|
||||
},
|
||||
c: {},
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test("handles a hand raised reaction", () => {
|
||||
const { members$, matrixRoom, client } = getBasicRTCSession([local, alice]);
|
||||
const reactionEventId = "$my_event_id:example.org";
|
||||
const localTimestamp = new Date();
|
||||
withTestScheduler(({ schedule, expectObservable }) => {
|
||||
renderHook(() => {
|
||||
const { raisedHands$ } = new ReactionsReader(
|
||||
testScope(),
|
||||
members$,
|
||||
matrixRoom,
|
||||
client,
|
||||
);
|
||||
schedule("ab", {
|
||||
a: () => {},
|
||||
b: () => {
|
||||
rtcSession.room.emit(
|
||||
matrixRoom.emit(
|
||||
MatrixRoomEvent.Timeline,
|
||||
new MatrixEvent({
|
||||
room_id: rtcSession.room.roomId,
|
||||
room_id: matrixRoom.roomId,
|
||||
event_id: reactionEventId,
|
||||
sender: localRtcMember.userId,
|
||||
type: EventType.Reaction,
|
||||
@@ -58,7 +158,7 @@ test("handles a hand raised reaction", () => {
|
||||
},
|
||||
},
|
||||
}),
|
||||
rtcSession.room,
|
||||
matrixRoom,
|
||||
undefined,
|
||||
false,
|
||||
{} as IRoomTimelineData,
|
||||
@@ -80,22 +180,24 @@ test("handles a hand raised reaction", () => {
|
||||
});
|
||||
|
||||
test("handles a redaction", () => {
|
||||
const { rtcSession } = getBasicRTCSession([local, alice]);
|
||||
const { members$, matrixRoom, client } = getBasicRTCSession([local, alice]);
|
||||
const reactionEventId = "$my_event_id:example.org";
|
||||
const localTimestamp = new Date();
|
||||
withTestScheduler(({ schedule, expectObservable }) => {
|
||||
renderHook(() => {
|
||||
const { raisedHands$ } = new ReactionsReader(
|
||||
testScope(),
|
||||
rtcSession.asMockedSession(),
|
||||
members$,
|
||||
matrixRoom,
|
||||
client,
|
||||
);
|
||||
schedule("abc", {
|
||||
a: () => {},
|
||||
b: () => {
|
||||
rtcSession.room.emit(
|
||||
matrixRoom.emit(
|
||||
MatrixRoomEvent.Timeline,
|
||||
new MatrixEvent({
|
||||
room_id: rtcSession.room.roomId,
|
||||
room_id: matrixRoom.roomId,
|
||||
event_id: reactionEventId,
|
||||
sender: localRtcMember.userId,
|
||||
type: EventType.Reaction,
|
||||
@@ -107,23 +209,23 @@ test("handles a redaction", () => {
|
||||
},
|
||||
},
|
||||
}),
|
||||
rtcSession.room,
|
||||
matrixRoom,
|
||||
undefined,
|
||||
false,
|
||||
{} as IRoomTimelineData,
|
||||
);
|
||||
},
|
||||
c: () => {
|
||||
rtcSession.room.emit(
|
||||
matrixRoom.emit(
|
||||
MatrixRoomEvent.Redaction,
|
||||
new MatrixEvent({
|
||||
room_id: rtcSession.room.roomId,
|
||||
room_id: matrixRoom.roomId,
|
||||
event_id: reactionEventId,
|
||||
sender: localRtcMember.userId,
|
||||
type: EventType.RoomRedaction,
|
||||
redacts: reactionEventId,
|
||||
}),
|
||||
rtcSession.room,
|
||||
matrixRoom,
|
||||
undefined,
|
||||
);
|
||||
},
|
||||
@@ -144,20 +246,22 @@ test("handles a redaction", () => {
|
||||
});
|
||||
|
||||
test("handles waiting for event decryption", () => {
|
||||
const { rtcSession } = getBasicRTCSession([local, alice]);
|
||||
const { members$, matrixRoom, client } = getBasicRTCSession([local, alice]);
|
||||
const reactionEventId = "$my_event_id:example.org";
|
||||
const localTimestamp = new Date();
|
||||
withTestScheduler(({ schedule, expectObservable }) => {
|
||||
renderHook(() => {
|
||||
const { raisedHands$ } = new ReactionsReader(
|
||||
testScope(),
|
||||
rtcSession.asMockedSession(),
|
||||
members$,
|
||||
matrixRoom,
|
||||
client,
|
||||
);
|
||||
schedule("abc", {
|
||||
a: () => {},
|
||||
b: () => {
|
||||
const encryptedEvent = new MatrixEvent({
|
||||
room_id: rtcSession.room.roomId,
|
||||
room_id: matrixRoom.roomId,
|
||||
event_id: reactionEventId,
|
||||
sender: localRtcMember.userId,
|
||||
type: EventType.Reaction,
|
||||
@@ -171,20 +275,20 @@ test("handles waiting for event decryption", () => {
|
||||
});
|
||||
// Should ignore encrypted events that are still encrypting
|
||||
encryptedEvent["decryptionPromise"] = Promise.resolve();
|
||||
rtcSession.room.emit(
|
||||
matrixRoom.emit(
|
||||
MatrixRoomEvent.Timeline,
|
||||
encryptedEvent,
|
||||
rtcSession.room,
|
||||
matrixRoom,
|
||||
undefined,
|
||||
false,
|
||||
{} as IRoomTimelineData,
|
||||
);
|
||||
},
|
||||
c: () => {
|
||||
rtcSession.room.client.emit(
|
||||
client.emit(
|
||||
MatrixEventEvent.Decrypted,
|
||||
new MatrixEvent({
|
||||
room_id: rtcSession.room.roomId,
|
||||
room_id: matrixRoom.roomId,
|
||||
event_id: reactionEventId,
|
||||
sender: localRtcMember.userId,
|
||||
type: EventType.Reaction,
|
||||
@@ -214,22 +318,24 @@ test("handles waiting for event decryption", () => {
|
||||
});
|
||||
|
||||
test("hands rejecting events without a proper membership", () => {
|
||||
const { rtcSession } = getBasicRTCSession([local, alice]);
|
||||
const { members$, matrixRoom, client } = getBasicRTCSession([local, alice]);
|
||||
const reactionEventId = "$my_event_id:example.org";
|
||||
const localTimestamp = new Date();
|
||||
withTestScheduler(({ schedule, expectObservable }) => {
|
||||
renderHook(() => {
|
||||
const { raisedHands$ } = new ReactionsReader(
|
||||
testScope(),
|
||||
rtcSession.asMockedSession(),
|
||||
members$,
|
||||
matrixRoom,
|
||||
client,
|
||||
);
|
||||
schedule("ab", {
|
||||
a: () => {},
|
||||
b: () => {
|
||||
rtcSession.room.emit(
|
||||
matrixRoom.emit(
|
||||
MatrixRoomEvent.Timeline,
|
||||
new MatrixEvent({
|
||||
room_id: rtcSession.room.roomId,
|
||||
room_id: matrixRoom.roomId,
|
||||
event_id: reactionEventId,
|
||||
sender: localRtcMember.userId,
|
||||
type: EventType.Reaction,
|
||||
@@ -241,7 +347,7 @@ test("hands rejecting events without a proper membership", () => {
|
||||
},
|
||||
},
|
||||
}),
|
||||
rtcSession.room,
|
||||
matrixRoom,
|
||||
undefined,
|
||||
false,
|
||||
{} as IRoomTimelineData,
|
||||
@@ -256,7 +362,7 @@ test("hands rejecting events without a proper membership", () => {
|
||||
});
|
||||
|
||||
test("handles a reaction", () => {
|
||||
const { rtcSession } = getBasicRTCSession([local, alice]);
|
||||
const { members$, matrixRoom, client } = getBasicRTCSession([local, alice]);
|
||||
const reactionEventId = "$my_event_id:example.org";
|
||||
const reaction = ReactionSet[1];
|
||||
|
||||
@@ -267,15 +373,17 @@ test("handles a reaction", () => {
|
||||
renderHook(() => {
|
||||
const { reactions$ } = new ReactionsReader(
|
||||
testScope(),
|
||||
rtcSession.asMockedSession(),
|
||||
members$,
|
||||
matrixRoom,
|
||||
client,
|
||||
);
|
||||
schedule(`abc`, {
|
||||
a: () => {},
|
||||
b: () => {
|
||||
rtcSession.room.emit(
|
||||
matrixRoom.emit(
|
||||
MatrixRoomEvent.Timeline,
|
||||
new MatrixEvent({
|
||||
room_id: rtcSession.room.roomId,
|
||||
room_id: matrixRoom.roomId,
|
||||
event_id: reactionEventId,
|
||||
sender: localRtcMember.userId,
|
||||
type: ElementCallReactionEventType,
|
||||
@@ -287,7 +395,7 @@ test("handles a reaction", () => {
|
||||
},
|
||||
},
|
||||
}),
|
||||
rtcSession.room,
|
||||
matrixRoom,
|
||||
undefined,
|
||||
false,
|
||||
{} as IRoomTimelineData,
|
||||
@@ -316,7 +424,11 @@ test("handles a reaction", () => {
|
||||
});
|
||||
|
||||
test("ignores bad reaction events", () => {
|
||||
const { rtcSession } = getBasicRTCSession([local, alice]);
|
||||
const {
|
||||
members$,
|
||||
matrixRoom: room,
|
||||
client,
|
||||
} = getBasicRTCSession([local, alice]);
|
||||
const reactionEventId = "$my_event_id:example.org";
|
||||
const reaction = ReactionSet[1];
|
||||
|
||||
@@ -326,31 +438,33 @@ test("ignores bad reaction events", () => {
|
||||
renderHook(() => {
|
||||
const { reactions$ } = new ReactionsReader(
|
||||
testScope(),
|
||||
rtcSession.asMockedSession(),
|
||||
members$,
|
||||
room,
|
||||
client,
|
||||
);
|
||||
schedule("ab", {
|
||||
a: () => {},
|
||||
b: () => {
|
||||
// Missing content
|
||||
rtcSession.room.emit(
|
||||
room.emit(
|
||||
MatrixRoomEvent.Timeline,
|
||||
new MatrixEvent({
|
||||
room_id: rtcSession.room.roomId,
|
||||
room_id: room.roomId,
|
||||
event_id: reactionEventId,
|
||||
sender: localRtcMember.userId,
|
||||
type: ElementCallReactionEventType,
|
||||
content: {},
|
||||
}),
|
||||
rtcSession.room,
|
||||
room,
|
||||
undefined,
|
||||
false,
|
||||
{} as IRoomTimelineData,
|
||||
);
|
||||
// Wrong relates event
|
||||
rtcSession.room.emit(
|
||||
room.emit(
|
||||
MatrixRoomEvent.Timeline,
|
||||
new MatrixEvent({
|
||||
room_id: rtcSession.room.roomId,
|
||||
room_id: room.roomId,
|
||||
event_id: reactionEventId,
|
||||
sender: localRtcMember.userId,
|
||||
type: ElementCallReactionEventType,
|
||||
@@ -362,16 +476,16 @@ test("ignores bad reaction events", () => {
|
||||
},
|
||||
},
|
||||
}),
|
||||
rtcSession.room,
|
||||
room,
|
||||
undefined,
|
||||
false,
|
||||
{} as IRoomTimelineData,
|
||||
);
|
||||
// Wrong rtc member event
|
||||
rtcSession.room.emit(
|
||||
room.emit(
|
||||
MatrixRoomEvent.Timeline,
|
||||
new MatrixEvent({
|
||||
room_id: rtcSession.room.roomId,
|
||||
room_id: room.roomId,
|
||||
event_id: reactionEventId,
|
||||
sender: aliceRtcMember.userId,
|
||||
type: ElementCallReactionEventType,
|
||||
@@ -383,16 +497,16 @@ test("ignores bad reaction events", () => {
|
||||
},
|
||||
},
|
||||
}),
|
||||
rtcSession.room,
|
||||
room,
|
||||
undefined,
|
||||
false,
|
||||
{} as IRoomTimelineData,
|
||||
);
|
||||
// No emoji
|
||||
rtcSession.room.emit(
|
||||
room.emit(
|
||||
MatrixRoomEvent.Timeline,
|
||||
new MatrixEvent({
|
||||
room_id: rtcSession.room.roomId,
|
||||
room_id: room.roomId,
|
||||
event_id: reactionEventId,
|
||||
sender: localRtcMember.userId,
|
||||
type: ElementCallReactionEventType,
|
||||
@@ -403,16 +517,16 @@ test("ignores bad reaction events", () => {
|
||||
},
|
||||
},
|
||||
}),
|
||||
rtcSession.room,
|
||||
room,
|
||||
undefined,
|
||||
false,
|
||||
{} as IRoomTimelineData,
|
||||
);
|
||||
// Invalid emoji
|
||||
rtcSession.room.emit(
|
||||
room.emit(
|
||||
MatrixRoomEvent.Timeline,
|
||||
new MatrixEvent({
|
||||
room_id: rtcSession.room.roomId,
|
||||
room_id: room.roomId,
|
||||
event_id: reactionEventId,
|
||||
sender: localRtcMember.userId,
|
||||
type: ElementCallReactionEventType,
|
||||
@@ -424,7 +538,7 @@ test("ignores bad reaction events", () => {
|
||||
},
|
||||
},
|
||||
}),
|
||||
rtcSession.room,
|
||||
room,
|
||||
undefined,
|
||||
false,
|
||||
{} as IRoomTimelineData,
|
||||
@@ -439,7 +553,7 @@ test("ignores bad reaction events", () => {
|
||||
});
|
||||
|
||||
test("that reactions cannot be spammed", () => {
|
||||
const { rtcSession } = getBasicRTCSession([local, alice]);
|
||||
const { members$, matrixRoom, client } = getBasicRTCSession([local, alice]);
|
||||
const reactionEventId = "$my_event_id:example.org";
|
||||
const reactionA = ReactionSet[1];
|
||||
const reactionB = ReactionSet[2];
|
||||
@@ -451,15 +565,17 @@ test("that reactions cannot be spammed", () => {
|
||||
renderHook(() => {
|
||||
const { reactions$ } = new ReactionsReader(
|
||||
testScope(),
|
||||
rtcSession.asMockedSession(),
|
||||
members$,
|
||||
matrixRoom,
|
||||
client,
|
||||
);
|
||||
schedule("abcd", {
|
||||
a: () => {},
|
||||
b: () => {
|
||||
rtcSession.room.emit(
|
||||
matrixRoom.emit(
|
||||
MatrixRoomEvent.Timeline,
|
||||
new MatrixEvent({
|
||||
room_id: rtcSession.room.roomId,
|
||||
room_id: matrixRoom.roomId,
|
||||
event_id: reactionEventId,
|
||||
sender: localRtcMember.userId,
|
||||
type: ElementCallReactionEventType,
|
||||
@@ -471,17 +587,17 @@ test("that reactions cannot be spammed", () => {
|
||||
},
|
||||
},
|
||||
}),
|
||||
rtcSession.room,
|
||||
matrixRoom,
|
||||
undefined,
|
||||
false,
|
||||
{} as IRoomTimelineData,
|
||||
);
|
||||
},
|
||||
c: () => {
|
||||
rtcSession.room.emit(
|
||||
matrixRoom.emit(
|
||||
MatrixRoomEvent.Timeline,
|
||||
new MatrixEvent({
|
||||
room_id: rtcSession.room.roomId,
|
||||
room_id: matrixRoom.roomId,
|
||||
event_id: reactionEventId,
|
||||
sender: localRtcMember.userId,
|
||||
type: ElementCallReactionEventType,
|
||||
@@ -493,7 +609,7 @@ test("that reactions cannot be spammed", () => {
|
||||
},
|
||||
},
|
||||
}),
|
||||
rtcSession.room,
|
||||
matrixRoom,
|
||||
undefined,
|
||||
false,
|
||||
{} as IRoomTimelineData,
|
||||
|
||||
@@ -5,20 +5,28 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import {
|
||||
type CallMembership,
|
||||
MatrixRTCSessionEvent,
|
||||
type MatrixRTCSession,
|
||||
} from "matrix-js-sdk/lib/matrixrtc";
|
||||
import { logger } from "matrix-js-sdk/lib/logger";
|
||||
import { type MatrixEvent, MatrixEventEvent } from "matrix-js-sdk";
|
||||
import {
|
||||
type MatrixClient,
|
||||
type MatrixEvent,
|
||||
MatrixEventEvent,
|
||||
type Room,
|
||||
} from "matrix-js-sdk";
|
||||
import { type ReactionEventContent } from "matrix-js-sdk/lib/types";
|
||||
import {
|
||||
RelationType,
|
||||
EventType,
|
||||
RoomEvent as MatrixRoomEvent,
|
||||
} from "matrix-js-sdk";
|
||||
import { BehaviorSubject, delay } from "rxjs";
|
||||
import {
|
||||
BehaviorSubject,
|
||||
combineLatest,
|
||||
delay,
|
||||
map,
|
||||
of,
|
||||
switchMap,
|
||||
} from "rxjs";
|
||||
import { type RTCMember } from "@element-hq/matrixrtc-sdk";
|
||||
|
||||
import {
|
||||
ElementCallReactionEventType,
|
||||
@@ -29,13 +37,20 @@ import {
|
||||
type ReactionInfo,
|
||||
} from ".";
|
||||
import { type ObservableScope } from "../state/ObservableScope";
|
||||
import { type Behavior } from "../state/Behavior";
|
||||
|
||||
export const REACTION_ACTIVE_TIME_MS = 3000;
|
||||
|
||||
/** A member's membership event, which its reactions relate to. */
|
||||
interface MembershipEvent {
|
||||
userId: string;
|
||||
deviceId: string;
|
||||
eventId: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Listens for reactions from a RTCSession and populates subjects
|
||||
* for consumption by the CallViewModel.
|
||||
* @param rtcSession
|
||||
* Listens for reactions to the slot members' memberships and populates
|
||||
* subjects for consumption by the CallViewModel.
|
||||
*/
|
||||
export class ReactionsReader {
|
||||
private readonly raisedHandsSubject$ = new BehaviorSubject<
|
||||
@@ -55,9 +70,33 @@ export class ReactionsReader {
|
||||
*/
|
||||
public readonly reactions$ = this.reactionsSubject$.asObservable();
|
||||
|
||||
private memberships: MembershipEvent[] = [];
|
||||
|
||||
public constructor(
|
||||
private readonly scope: ObservableScope,
|
||||
private readonly rtcSession: MatrixRTCSession,
|
||||
members$: Behavior<RTCMember[]>,
|
||||
private readonly room: Pick<
|
||||
Room,
|
||||
// To ignore events from other rooms
|
||||
| "roomId"
|
||||
// The raised hands already in the room, as reactions to memberships
|
||||
| "relations"
|
||||
// `on`/`off`, to listen for:
|
||||
// - `RoomEvent.Timeline` (new reactions)
|
||||
// - `RoomEvent.Redaction` (lowered hands)
|
||||
// - `RoomEvent.LocalEchoUpdated` (the real id of our own reactions)
|
||||
| "on"
|
||||
| "off"
|
||||
>,
|
||||
private readonly client: Pick<
|
||||
MatrixClient,
|
||||
// Reactions that arrived encrypted
|
||||
| "decryptEventIfNeeded"
|
||||
// `on`/`off`, to listen for:
|
||||
// - `MatrixEventEvent.Decrypted` (reactions once decrypted)
|
||||
| "on"
|
||||
| "off"
|
||||
>,
|
||||
) {
|
||||
// Hide reactions after a given time.
|
||||
this.reactionsSubject$
|
||||
@@ -76,62 +115,44 @@ export class ReactionsReader {
|
||||
// TODO: Convert this class to the functional reactive style and get rid of
|
||||
// all this manual setup and teardown for event listeners
|
||||
|
||||
this.rtcSession.room.on(MatrixRoomEvent.Timeline, this.handleReactionEvent);
|
||||
this.room.on(MatrixRoomEvent.Timeline, this.handleReactionEvent);
|
||||
this.scope.onEnd(() =>
|
||||
this.rtcSession.room.off(
|
||||
MatrixRoomEvent.Timeline,
|
||||
this.handleReactionEvent,
|
||||
),
|
||||
this.room.off(MatrixRoomEvent.Timeline, this.handleReactionEvent),
|
||||
);
|
||||
|
||||
this.rtcSession.room.on(
|
||||
MatrixRoomEvent.Redaction,
|
||||
this.handleReactionEvent,
|
||||
);
|
||||
this.room.on(MatrixRoomEvent.Redaction, this.handleReactionEvent);
|
||||
this.scope.onEnd(() =>
|
||||
this.rtcSession.room.off(
|
||||
MatrixRoomEvent.Redaction,
|
||||
this.handleReactionEvent,
|
||||
),
|
||||
this.room.off(MatrixRoomEvent.Redaction, this.handleReactionEvent),
|
||||
);
|
||||
|
||||
this.rtcSession.room.client.on(
|
||||
MatrixEventEvent.Decrypted,
|
||||
this.handleReactionEvent,
|
||||
);
|
||||
this.client.on(MatrixEventEvent.Decrypted, this.handleReactionEvent);
|
||||
this.scope.onEnd(() =>
|
||||
this.rtcSession.room.client.off(
|
||||
MatrixEventEvent.Decrypted,
|
||||
this.handleReactionEvent,
|
||||
),
|
||||
this.client.off(MatrixEventEvent.Decrypted, this.handleReactionEvent),
|
||||
);
|
||||
|
||||
// We listen for a local echo to get the real event ID, as timeline events
|
||||
// may still be sending.
|
||||
this.rtcSession.room.on(
|
||||
MatrixRoomEvent.LocalEchoUpdated,
|
||||
this.handleReactionEvent,
|
||||
);
|
||||
this.room.on(MatrixRoomEvent.LocalEchoUpdated, this.handleReactionEvent);
|
||||
this.scope.onEnd(() =>
|
||||
this.rtcSession.room.off(
|
||||
MatrixRoomEvent.LocalEchoUpdated,
|
||||
this.handleReactionEvent,
|
||||
),
|
||||
this.room.off(MatrixRoomEvent.LocalEchoUpdated, this.handleReactionEvent),
|
||||
);
|
||||
|
||||
this.rtcSession.on(
|
||||
MatrixRTCSessionEvent.MembershipsChanged,
|
||||
this.onMembershipsChanged,
|
||||
);
|
||||
this.scope.onEnd(() =>
|
||||
this.rtcSession.off(
|
||||
MatrixRTCSessionEvent.MembershipsChanged,
|
||||
this.onMembershipsChanged,
|
||||
),
|
||||
);
|
||||
|
||||
// Run this once to ensure we have fetched the state from the call.
|
||||
this.onMembershipsChanged([]);
|
||||
members$
|
||||
.pipe(
|
||||
switchMap((members) =>
|
||||
members.length === 0
|
||||
? of([])
|
||||
: combineLatest(
|
||||
members.map(({ userId, deviceId, matrixEventId$ }) =>
|
||||
matrixEventId$.pipe(
|
||||
map((eventId) => ({ userId, deviceId, eventId })),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
this.scope.bind(),
|
||||
)
|
||||
.subscribe(this.onMembershipsChanged);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -145,7 +166,7 @@ export class ReactionsReader {
|
||||
membershipEventId: string,
|
||||
expectedSender: string,
|
||||
): MatrixEvent | undefined {
|
||||
const relations = this.rtcSession.room.relations.getChildEventsForEvent(
|
||||
const relations = this.room.relations.getChildEventsForEvent(
|
||||
membershipEventId,
|
||||
RelationType.Annotation,
|
||||
EventType.Reaction,
|
||||
@@ -162,22 +183,23 @@ export class ReactionsReader {
|
||||
/**
|
||||
* Will remove any hand raises by old members, and look for any
|
||||
* existing hand raises by new members.
|
||||
* @param oldMemberships Any members who have left the call.
|
||||
* @param memberships The membership events of everyone in the call now.
|
||||
*/
|
||||
private onMembershipsChanged = (oldMemberships: CallMembership[]): void => {
|
||||
private onMembershipsChanged = (memberships: MembershipEvent[]): void => {
|
||||
this.memberships = memberships;
|
||||
// Remove any raised hands for users no longer joined to the call.
|
||||
const present = new Set(
|
||||
memberships.map((m) => `${m.userId}:${m.deviceId}`),
|
||||
);
|
||||
for (const identifier of Object.keys(this.raisedHandsSubject$.value).filter(
|
||||
(rhId) => oldMemberships.find((u) => u.userId == rhId),
|
||||
(rhId) => !present.has(rhId),
|
||||
)) {
|
||||
this.removeRaisedHand(identifier);
|
||||
}
|
||||
|
||||
// For each member in the call, check to see if a reaction has
|
||||
// been raised and adjust.
|
||||
for (const m of this.rtcSession.memberships) {
|
||||
if (!m.userId || !m.eventId) {
|
||||
continue;
|
||||
}
|
||||
for (const m of memberships) {
|
||||
const identifier = `${m.userId}:${m.deviceId}`;
|
||||
if (
|
||||
this.raisedHandsSubject$.value[identifier] &&
|
||||
@@ -235,9 +257,8 @@ export class ReactionsReader {
|
||||
* @param event The incoming matrix event, which may or may not be decrypted.
|
||||
*/
|
||||
private handleReactionEvent = (event: MatrixEvent): void => {
|
||||
const room = this.rtcSession.room;
|
||||
// Decrypted events might come from a different room
|
||||
if (event.getRoomId() !== room.roomId) return;
|
||||
if (event.getRoomId() !== this.room.roomId) return;
|
||||
// Skip any events that are still sending.
|
||||
if (event.isSending()) return;
|
||||
|
||||
@@ -246,7 +267,7 @@ export class ReactionsReader {
|
||||
// Skip any event without a sender or event ID.
|
||||
if (!sender || !reactionEventId) return;
|
||||
|
||||
room.client
|
||||
this.client
|
||||
.decryptEventIfNeeded(event)
|
||||
.catch((e) => logger.warn(`Failed to decrypt ${event.getId()}`, e));
|
||||
if (event.isBeingDecrypted() || event.isDecryptionFailure()) return;
|
||||
@@ -255,7 +276,7 @@ export class ReactionsReader {
|
||||
const content: ECallReactionEventContent = event.getContent();
|
||||
|
||||
const membershipEventId = content?.["m.relates_to"]?.event_id;
|
||||
const membershipEvent = this.rtcSession.memberships.find(
|
||||
const membershipEvent = this.memberships.find(
|
||||
(e) => e.eventId === membershipEventId && e.userId === sender,
|
||||
);
|
||||
// Check to see if this reaction was made to a membership event (and the
|
||||
@@ -315,7 +336,7 @@ export class ReactionsReader {
|
||||
|
||||
// Check to see if this reaction was made to a membership event (and the
|
||||
// sender of the reaction matches the membership)
|
||||
const membershipEvent = this.rtcSession.memberships.find(
|
||||
const membershipEvent = this.memberships.find(
|
||||
(e) => e.eventId === membershipEventId && e.userId === sender,
|
||||
);
|
||||
if (!membershipEvent) {
|
||||
|
||||
@@ -5,7 +5,12 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { EventType, RelationType } from "matrix-js-sdk";
|
||||
import {
|
||||
EventType,
|
||||
type MatrixClient,
|
||||
RelationType,
|
||||
type Room,
|
||||
} from "matrix-js-sdk";
|
||||
import {
|
||||
createContext,
|
||||
use,
|
||||
@@ -14,14 +19,15 @@ import {
|
||||
useMemo,
|
||||
type JSX,
|
||||
} from "react";
|
||||
import { type MatrixRTCSession } from "matrix-js-sdk/lib/matrixrtc";
|
||||
import { logger } from "matrix-js-sdk/lib/logger";
|
||||
|
||||
import { useMatrixRTCSessionMemberships } from "../useMatrixRTCSessionMemberships";
|
||||
import { useClientState } from "../ClientContext";
|
||||
import { ElementCallReactionEventType, type ReactionOption } from ".";
|
||||
import { type CallViewModel } from "../state/CallViewModel/CallViewModel";
|
||||
import { useBehavior } from "../useBehavior";
|
||||
import { constant } from "../state/Behavior";
|
||||
|
||||
const noMembershipEvent$ = constant(undefined);
|
||||
|
||||
interface ReactionsSenderContextType {
|
||||
supportsReactions: boolean;
|
||||
@@ -46,28 +52,34 @@ export const useReactionsSender = (): ReactionsSenderContextType => {
|
||||
*/
|
||||
export const ReactionsSenderProvider = ({
|
||||
children,
|
||||
rtcSession,
|
||||
room,
|
||||
client,
|
||||
vm,
|
||||
}: {
|
||||
children: ReactNode;
|
||||
rtcSession: MatrixRTCSession;
|
||||
/** The room the reactions are sent in. */
|
||||
room: Pick<Room, "roomId">;
|
||||
client: Pick<
|
||||
MatrixClient,
|
||||
// Our own identity, which reactions and raised hands are keyed by
|
||||
| "getUserId"
|
||||
| "getDeviceId"
|
||||
// Sending reactions and raising a hand
|
||||
| "sendEvent"
|
||||
// Lowering a hand
|
||||
| "redactEvent"
|
||||
>;
|
||||
/** Our own membership, which the reactions relate to, and the current reactions. */
|
||||
vm: CallViewModel;
|
||||
}): JSX.Element => {
|
||||
const memberships = useMatrixRTCSessionMemberships(rtcSession);
|
||||
const clientState = useClientState();
|
||||
const supportsReactions =
|
||||
clientState?.state === "valid" && clientState.supportedFeatures.reactions;
|
||||
const room = rtcSession.room;
|
||||
const myUserId = room.client.getUserId();
|
||||
const myDeviceId = room.client.getDeviceId();
|
||||
const myMembershipIdentifier = `${myUserId}:${myDeviceId}`;
|
||||
const myMembershipIdentifier = `${client.getUserId()}:${client.getDeviceId()}`;
|
||||
|
||||
const myMembershipEvent = useMemo(
|
||||
() =>
|
||||
memberships.find(
|
||||
(m) => m.userId === myUserId && m.deviceId === myDeviceId,
|
||||
)?.eventId,
|
||||
[memberships, myUserId, myDeviceId],
|
||||
const localMember = useBehavior(vm.localMember$);
|
||||
const myMembershipEvent = useBehavior(
|
||||
localMember?.matrixEventId$ ?? noMembershipEvent$,
|
||||
);
|
||||
|
||||
const reactions = useBehavior(vm.reactions$);
|
||||
@@ -99,8 +111,8 @@ export const ReactionsSenderProvider = ({
|
||||
if (!myMembershipEvent) {
|
||||
throw new Error("Cannot find own membership event");
|
||||
}
|
||||
const reaction = await room.client.sendEvent(
|
||||
rtcSession.room.roomId,
|
||||
const reaction = await client.sendEvent(
|
||||
room.roomId,
|
||||
EventType.Reaction,
|
||||
{
|
||||
"m.relates_to": {
|
||||
@@ -116,20 +128,14 @@ export const ReactionsSenderProvider = ({
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
await room.client.redactEvent(rtcSession.room.roomId, myReactionId);
|
||||
await client.redactEvent(room.roomId, myReactionId);
|
||||
logger.debug("Redacted raise hand event");
|
||||
} catch (ex) {
|
||||
logger.error("Failed to redact reaction event", myReactionId, ex);
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
}, [
|
||||
myMembershipEvent,
|
||||
myMembershipIdentifier,
|
||||
myRaisedHand,
|
||||
rtcSession,
|
||||
room,
|
||||
]);
|
||||
}, [myMembershipEvent, myMembershipIdentifier, myRaisedHand, client, room]);
|
||||
|
||||
const sendReaction = useCallback(
|
||||
async (reaction: ReactionOption) => {
|
||||
@@ -140,20 +146,16 @@ export const ReactionsSenderProvider = ({
|
||||
if (!myMembershipEvent) {
|
||||
throw new Error("Cannot find own membership event");
|
||||
}
|
||||
await room.client.sendEvent(
|
||||
rtcSession.room.roomId,
|
||||
ElementCallReactionEventType,
|
||||
{
|
||||
"m.relates_to": {
|
||||
rel_type: RelationType.Reference,
|
||||
event_id: myMembershipEvent,
|
||||
},
|
||||
emoji: reaction.emoji,
|
||||
name: reaction.name,
|
||||
await client.sendEvent(room.roomId, ElementCallReactionEventType, {
|
||||
"m.relates_to": {
|
||||
rel_type: RelationType.Reference,
|
||||
event_id: myMembershipEvent,
|
||||
},
|
||||
);
|
||||
emoji: reaction.emoji,
|
||||
name: reaction.name,
|
||||
});
|
||||
},
|
||||
[myMembershipEvent, myReaction, room, myMembershipIdentifier, rtcSession],
|
||||
[myMembershipEvent, myReaction, client, room, myMembershipIdentifier],
|
||||
);
|
||||
|
||||
return (
|
||||
|
||||
@@ -6,13 +6,12 @@ Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { type FC, type FormEventHandler, useCallback, useState } from "react";
|
||||
import { type MatrixClient } from "matrix-js-sdk";
|
||||
import { Trans, useTranslation } from "react-i18next";
|
||||
import { Button, Heading, Text } from "@vector-im/compound-web";
|
||||
|
||||
import styles from "./CallEndedView.module.css";
|
||||
import feedbackStyle from "../input/FeedbackInput.module.css";
|
||||
import { useProfile } from "../profile/useProfile";
|
||||
import { type ProfileClientParts, useProfile } from "../profile/useProfile";
|
||||
import { Header, HeaderLogo, LeftNav, RightNav } from "../Header";
|
||||
import { PosthogAnalytics } from "../analytics/PosthogAnalytics";
|
||||
import { FieldRow, InputField } from "../input/Input";
|
||||
@@ -22,7 +21,7 @@ import { LeaveToHomeLink } from "../button/LeaveToHomeLink";
|
||||
import { useLeaveToHome } from "../LeaveToHomeContext";
|
||||
|
||||
interface Props {
|
||||
client: MatrixClient;
|
||||
client: ProfileClientParts;
|
||||
isPasswordlessUser: boolean;
|
||||
hideHeader: boolean;
|
||||
confineToRoom: boolean;
|
||||
|
||||
+46
-80
@@ -19,16 +19,8 @@ import {
|
||||
vitest,
|
||||
} from "vitest";
|
||||
import { render, waitFor, screen, act } from "@testing-library/react";
|
||||
import {
|
||||
type MatrixClient,
|
||||
JoinRule,
|
||||
type RoomState,
|
||||
UnsupportedStickyEventsEndpointError,
|
||||
} from "matrix-js-sdk";
|
||||
import {
|
||||
MatrixRTCSessionEvent,
|
||||
type MatrixRTCSession,
|
||||
} from "matrix-js-sdk/lib/matrixrtc";
|
||||
import { type MatrixClient, JoinRule } from "matrix-js-sdk";
|
||||
import { type MatrixRTCSession } from "matrix-js-sdk/lib/matrixrtc";
|
||||
import { BrowserRouter } from "react-router-dom";
|
||||
import userEvent, {
|
||||
PointerEventsCheckLevel,
|
||||
@@ -53,7 +45,7 @@ import {
|
||||
testScope,
|
||||
} from "../utils/test";
|
||||
import { CallView } from "./CallView";
|
||||
import { GroupCallErrorBoundary } from "./GroupCallErrorBoundary";
|
||||
import { type CallMatrixBackend } from "../CallMatrixBackend";
|
||||
import {
|
||||
type HostBridge,
|
||||
HostBridgeProvider,
|
||||
@@ -61,7 +53,10 @@ import {
|
||||
nullHostBridge,
|
||||
} from "../HostBridge";
|
||||
import { type JoinCallData } from "../widget";
|
||||
import { MatrixRTCTransportMissingError } from "../utils/errors";
|
||||
import {
|
||||
ConnectionLostError,
|
||||
MatrixRTCTransportMissingError,
|
||||
} from "../utils/errors";
|
||||
import {
|
||||
BackgroundEffectsProvider,
|
||||
createAppBackgroundEffects,
|
||||
@@ -146,7 +141,6 @@ function createCallView(
|
||||
hostBridge: HostBridge,
|
||||
joined = true,
|
||||
options: {
|
||||
withErrorBoundary?: boolean;
|
||||
/** Wait for the host to say when to join, rather than joining at once. */
|
||||
preload?: boolean;
|
||||
} = {},
|
||||
@@ -155,6 +149,7 @@ function createCallView(
|
||||
getByText: ReturnType<typeof render>["getByText"];
|
||||
} {
|
||||
const client = {
|
||||
...mockEmitter(),
|
||||
getUser: () => null,
|
||||
getUserId: () => localRtcMember.userId,
|
||||
getDeviceId: () => localRtcMember.deviceId,
|
||||
@@ -170,28 +165,14 @@ function createCallView(
|
||||
client,
|
||||
roomId,
|
||||
getMember: (userId) => roomMembers.get(userId) ?? null,
|
||||
getMembersWithMembership: () => [carol],
|
||||
getMxcAvatarUrl: () => null,
|
||||
getCanonicalAlias: () => null,
|
||||
currentState: {
|
||||
...mockEmitter(),
|
||||
getJoinRule: () => JoinRule.Invite,
|
||||
} as Partial<RoomState> as RoomState,
|
||||
getJoinRule: () => JoinRule.Invite,
|
||||
});
|
||||
const rtcSession = new MockRTCSession(room, []).withMemberships(
|
||||
constant([localRtcMember]),
|
||||
);
|
||||
rtcSession.joined = joined;
|
||||
const callView = (
|
||||
<CallView
|
||||
client={client}
|
||||
isPasswordlessUser={false}
|
||||
confineToRoom={false}
|
||||
preload={options.preload ?? false}
|
||||
// Straight into the (mocked) call, past the lobby
|
||||
skipLobby
|
||||
rtcSession={rtcSession.asMockedSession()}
|
||||
/>
|
||||
);
|
||||
const { getByText } = render(
|
||||
<BrowserRouter>
|
||||
<HostBridgeProvider value={hostBridge}>
|
||||
@@ -200,13 +181,22 @@ function createCallView(
|
||||
<BackgroundEffectsProvider
|
||||
effects={createAppBackgroundEffects(testScope())}
|
||||
>
|
||||
{options.withErrorBoundary ? (
|
||||
<GroupCallErrorBoundary recoveryActionHandler={vi.fn()}>
|
||||
{callView}
|
||||
</GroupCallErrorBoundary>
|
||||
) : (
|
||||
callView
|
||||
)}
|
||||
<CallView
|
||||
backend={
|
||||
{
|
||||
...client,
|
||||
...room,
|
||||
clientEmitter: client,
|
||||
roomEmitter: room,
|
||||
} as unknown as CallMatrixBackend
|
||||
}
|
||||
isPasswordlessUser={false}
|
||||
confineToRoom={false}
|
||||
preload={options.preload ?? false}
|
||||
// Straight into the (mocked) call, past the lobby
|
||||
skipLobby
|
||||
rtcSession={rtcSession.asMockedSession()}
|
||||
/>
|
||||
</BackgroundEffectsProvider>
|
||||
</MediaDevicesContext>
|
||||
</TooltipProvider>
|
||||
@@ -371,52 +361,28 @@ test.skip("CallView shows errors that occur during joining", async () => {
|
||||
screen.getByText("Call is not supported");
|
||||
});
|
||||
|
||||
test("translates wrapped UnsupportedStickyEventsEndpointError to the StickyEventsRequiredError screen", async () => {
|
||||
// Mirror the shape the SDK emits: the MembershipManager scheduler wraps
|
||||
// the original UnsupportedStickyEventsEndpointError in a generic Error
|
||||
// but preserves the original on `.cause`.
|
||||
const stickyError = new UnsupportedStickyEventsEndpointError(
|
||||
"Server does not support the sticky events",
|
||||
"sendStickyEvent",
|
||||
test("user can reconnect after losing the connection", async () => {
|
||||
// What the call throws once the view model reports the connection lost
|
||||
(ActiveCall as MockedFunction<typeof ActiveCall>).mockImplementation(
|
||||
({ onLeft }) => {
|
||||
const [error, setError] = useState<Error | null>(null);
|
||||
if (error !== null) throw error;
|
||||
return (
|
||||
<div>
|
||||
<button onClick={() => onLeft("user")}>Leave</button>
|
||||
<button onClick={() => setError(new ConnectionLostError())}>
|
||||
LoseConnection
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
);
|
||||
const wrappedError = new Error(
|
||||
"The MembershipManager shut down because of the end condition: " +
|
||||
String(stickyError),
|
||||
{ cause: stickyError },
|
||||
);
|
||||
|
||||
const { rtcSession } = createCallView(nullHostBridge, true, {
|
||||
withErrorBoundary: true,
|
||||
});
|
||||
|
||||
await act(() =>
|
||||
rtcSession.emit(MatrixRTCSessionEvent.MembershipManagerError, wrappedError),
|
||||
);
|
||||
|
||||
await screen.findByText("Homeserver does not support Matrix 2.0 calls");
|
||||
});
|
||||
|
||||
test("falls back to ConnectionLostError for unrecognised membership manager errors", async () => {
|
||||
const { rtcSession } = createCallView(nullHostBridge, true, {
|
||||
withErrorBoundary: true,
|
||||
});
|
||||
|
||||
await act(() =>
|
||||
rtcSession.emit(
|
||||
MatrixRTCSessionEvent.MembershipManagerError,
|
||||
new Error("something else broke"),
|
||||
),
|
||||
);
|
||||
|
||||
await screen.findByText("Connection lost");
|
||||
});
|
||||
|
||||
test("user can reconnect after a membership manager error", async () => {
|
||||
const user = userEvent.setup();
|
||||
const { rtcSession } = createCallView(nullHostBridge, true);
|
||||
await act(() =>
|
||||
rtcSession.emit(MatrixRTCSessionEvent.MembershipManagerError, undefined),
|
||||
);
|
||||
createCallView(nullHostBridge, true);
|
||||
await user.click(screen.getByRole("button", { name: "LoseConnection" }));
|
||||
await screen.findByText("Connection lost");
|
||||
// Never joined, so there was no call to leave
|
||||
expect(playSound).not.toHaveBeenCalled();
|
||||
// XXX: Wrapping the following click in act() shouldn't be necessary (the
|
||||
// async state update should be processed automatically by the waitFor call),
|
||||
// and yet here we are.
|
||||
|
||||
+184
-101
@@ -13,21 +13,24 @@ import {
|
||||
useMemo,
|
||||
useState,
|
||||
} from "react";
|
||||
import {
|
||||
type MatrixClient,
|
||||
JoinRule,
|
||||
type Room,
|
||||
UnsupportedStickyEventsEndpointError,
|
||||
} from "matrix-js-sdk";
|
||||
import { type MatrixClient, JoinRule, type Room } from "matrix-js-sdk";
|
||||
import {
|
||||
Room as LivekitRoom,
|
||||
isE2EESupported as isE2EESupportedBrowser,
|
||||
} from "livekit-client";
|
||||
import { logger } from "matrix-js-sdk/lib/logger";
|
||||
import {
|
||||
MatrixRTCSessionEvent,
|
||||
type MatrixRTCSession,
|
||||
type Statistics,
|
||||
} from "matrix-js-sdk/lib/matrixrtc";
|
||||
import { type Observable } from "rxjs";
|
||||
import {
|
||||
createRTCSlot,
|
||||
type EncryptionSystem,
|
||||
MembershipManagerError as RTCMembershipManagerError,
|
||||
type RTCSlot,
|
||||
withEmitter,
|
||||
} from "@element-hq/matrixrtc-sdk";
|
||||
|
||||
import { type JoinCallData } from "../widget";
|
||||
import { LobbyView } from "./LobbyView";
|
||||
@@ -39,7 +42,6 @@ import { findDeviceByName } from "../utils/media";
|
||||
import { ActiveCall } from "./InCallView";
|
||||
import { type MuteStates } from "../state/MuteStates";
|
||||
import { useMediaDevices } from "../MediaDevicesContext";
|
||||
import { useMatrixRTCSessionMemberships } from "../useMatrixRTCSessionMemberships";
|
||||
import {
|
||||
saveKeyForRoom,
|
||||
useRoomEncryptionSystem,
|
||||
@@ -57,14 +59,11 @@ import {
|
||||
} from "./CallEventAudioRenderer";
|
||||
import { useLatest } from "../useLatest";
|
||||
import {
|
||||
ConnectionLostError,
|
||||
E2EENotSupportedError,
|
||||
ElementCallError,
|
||||
StickyEventsRequiredError,
|
||||
UnknownCallError,
|
||||
} from "../utils/errors.ts";
|
||||
import { GroupCallErrorBoundary } from "./GroupCallErrorBoundary.tsx";
|
||||
import { useTypedEventEmitter } from "../useEvents";
|
||||
import { muteAllAudio$ } from "../state/MuteAllAudioModel.ts";
|
||||
import { useAppBarTitle } from "../AppBar.tsx";
|
||||
import { useBehavior } from "../useBehavior.ts";
|
||||
@@ -73,6 +72,9 @@ import { useHostBridge } from "../HostBridge.ts";
|
||||
import { useMuteStates } from "../state/useMuteStates.ts";
|
||||
import { useLeaveToHome } from "../LeaveToHomeContext.ts";
|
||||
import { useLocalMedia } from "../useLocalMedia.ts";
|
||||
import { ObservableScope } from "../state/ObservableScope.ts";
|
||||
import { type CallNotificationWrapper } from "../state/CallViewModel/CallNotificationLifecycle.ts";
|
||||
import { type CallMatrixBackend } from "../CallMatrixBackend.ts";
|
||||
|
||||
/**
|
||||
* If there already are this many participants in the call, we automatically mute
|
||||
@@ -80,17 +82,19 @@ import { useLocalMedia } from "../useLocalMedia.ts";
|
||||
*/
|
||||
export const MUTE_PARTICIPANT_COUNT = 8;
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
rtcSession?: MatrixRTCSession;
|
||||
}
|
||||
}
|
||||
|
||||
interface Props {
|
||||
/** The client to place the call with. */
|
||||
client: MatrixClient;
|
||||
/** The call to join. */
|
||||
rtcSession: MatrixRTCSession;
|
||||
/** The client and room to place the call with and in. */
|
||||
backend: CallMatrixBackend;
|
||||
/**
|
||||
* The call to join, which the RTC slot is built on.
|
||||
* Passing undefined -> the SDK will create a inner RTCSession (or in the future a rust equivalent)
|
||||
* @deprecated: It should not get its rtcSession from here.
|
||||
* The goal is that the RTC session is fully encapsulated inside the SDK (`createRTCSlot`)
|
||||
* We keep this as a fallback for the SPA. In that mode we currently expect to manage Our
|
||||
* own rtcSession with `useLoadGroupCall`. This is an open TODO. Until then we have this
|
||||
* alternative.
|
||||
*/
|
||||
rtcSession?: MatrixRTCSession;
|
||||
/**
|
||||
* Whether the user is signed in as a guest, and so should be offered the
|
||||
* chance to create an account when the call ends.
|
||||
@@ -121,18 +125,58 @@ interface Props {
|
||||
* whatever is hosting it — the standalone app's own shell, or an application
|
||||
* embedding Element Call as a component. Both render this.
|
||||
*/
|
||||
export const CallView: FC<Props> = (props): ReactNode => {
|
||||
export const CallView: FC<Props> = ({
|
||||
backend,
|
||||
rtcSession: externalRtcSession,
|
||||
...props
|
||||
}): ReactNode => {
|
||||
// STOP GAP: what is below is still written against a client and a room.
|
||||
// Both are refactored along with the backend.
|
||||
const client = useMemo(
|
||||
() => withEmitter(backend, backend.clientEmitter),
|
||||
[backend],
|
||||
);
|
||||
const room = useMemo(
|
||||
() => withEmitter(backend, backend.roomEmitter),
|
||||
[backend],
|
||||
);
|
||||
|
||||
// Whether the user is in the call is the call's own business, not its host's.
|
||||
// Held here rather than below so that it survives the mute state being
|
||||
// rebuilt.
|
||||
const [joined, setJoined] = useState(false);
|
||||
const muteStates = useMuteStates();
|
||||
const e2eeSystem = useRoomEncryptionSystem(backend.roomId);
|
||||
|
||||
if (muteStates === null) return null;
|
||||
// One slot for every join of this call: leaving and joining again, to
|
||||
// reconnect or from the lobby, happens on the same one
|
||||
const [slot, setSlot] = useState<ReturnType<typeof createRTCSlot> | null>(
|
||||
null,
|
||||
);
|
||||
useEffect(() => {
|
||||
const scope = new ObservableScope();
|
||||
setSlot(
|
||||
createRTCSlot(
|
||||
scope,
|
||||
backend,
|
||||
{ encryptionSystem: e2eeSystem },
|
||||
externalRtcSession,
|
||||
),
|
||||
);
|
||||
return (): void => scope.end();
|
||||
}, [backend, e2eeSystem, externalRtcSession]);
|
||||
|
||||
if (muteStates === null || slot === null) return null;
|
||||
|
||||
return (
|
||||
<LoadedCallView
|
||||
{...props}
|
||||
client={client}
|
||||
room={room}
|
||||
sentCallNotification$={slot.sentCallNotification$}
|
||||
statistics={slot.statistics}
|
||||
slot={slot}
|
||||
e2eeSystem={e2eeSystem}
|
||||
joined={joined}
|
||||
setJoined={setJoined}
|
||||
muteStates={muteStates}
|
||||
@@ -140,20 +184,100 @@ export const CallView: FC<Props> = (props): ReactNode => {
|
||||
);
|
||||
};
|
||||
|
||||
interface LoadedProps extends Props {
|
||||
// Here we do not pass the rtcSession anymore. This is a huge step!!
|
||||
// We only rely on our sdk abstraction (+ client and +room but only a
|
||||
// smaller list of callbacks.)
|
||||
interface LoadedProps extends Omit<Props, "rtcSession" | "backend"> {
|
||||
// Narrower than `Props.client`: the `slot` already has what only it and its
|
||||
// session need, `getRTCTransports`, `delegateDelayedLeave`, `baseUrl`,
|
||||
// `getSyncState`, `ClientEvent.Sync`, and the session's sending
|
||||
client: Pick<
|
||||
MatrixClient,
|
||||
| "getUserId"
|
||||
| "getDeviceId"
|
||||
| "getDomain"
|
||||
| "getOpenIdToken"
|
||||
| "getLivekitToken"
|
||||
| "sendEvent"
|
||||
| "redactEvent"
|
||||
| "decryptEventIfNeeded"
|
||||
| "getUser"
|
||||
| "setDisplayName"
|
||||
| "setAvatarUrl"
|
||||
| "uploadContent"
|
||||
| "doesServerSupportUnstableFeature"
|
||||
| "getCrypto"
|
||||
// `on`/`off`, to listen for `MatrixEventEvent.Decrypted` (reactions once
|
||||
// decrypted)
|
||||
| "on"
|
||||
| "off"
|
||||
>;
|
||||
// Narrower than `Props.room`: the `slot` already follows
|
||||
// `RoomStateEvent.Events` for its status, `RoomStateEvent.Members` for its
|
||||
// own members, and the timeline its session reads the memberships from
|
||||
room: Pick<
|
||||
Room,
|
||||
| "roomId"
|
||||
| "name"
|
||||
| "getMxcAvatarUrl"
|
||||
| "getJoinRule"
|
||||
| "getMembersWithMembership"
|
||||
| "_unstable_getStickyEvents"
|
||||
| "getLiveTimeline"
|
||||
| "relations"
|
||||
// `on`/`off`, to listen for:
|
||||
// - `RoomEvent.Name` (room name)
|
||||
// - `RoomStateEvent.Update` and `RoomEvent.CurrentStateUpdated` (avatar
|
||||
// and join rule hooks)
|
||||
// - `RoomStateEvent.Members` (call view model members)
|
||||
// - `RoomStateEvent.Events` (call view model functional members)
|
||||
// - `RoomEvent.Timeline` and `RoomStickyEventsEvent.Update` (call notifications)
|
||||
// - `RoomEvent.Timeline`, `RoomEvent.Redaction` and
|
||||
// `RoomEvent.LocalEchoUpdated` (reactions and raised hands)
|
||||
| "on"
|
||||
| "off"
|
||||
>;
|
||||
/**
|
||||
* The call notifications the session sends with our join, so the call can
|
||||
* show it ringing: the slot's `sentCallNotification$`.
|
||||
*/
|
||||
sentCallNotification$: Observable<CallNotificationWrapper>;
|
||||
/** The session's media key statistics, reported when the call ends. */
|
||||
statistics: Statistics;
|
||||
slot: RTCSlot;
|
||||
e2eeSystem: EncryptionSystem;
|
||||
joined: boolean;
|
||||
setJoined: (value: boolean) => void;
|
||||
muteStates: MuteStates;
|
||||
}
|
||||
|
||||
/** {@link CallView}, once it has the mute state everything below needs. */
|
||||
/**
|
||||
* Whether our membership is live in the slot: seen in the room, and not taken
|
||||
* down by the membership manager stopping. Leaving the call only makes sense
|
||||
* then; an error before the join, or one that ended the membership, leaves
|
||||
* nothing to leave.
|
||||
*/
|
||||
function isInCall(slot: RTCSlot): boolean {
|
||||
const participation = slot.participation$.value;
|
||||
if (participation?.localMember$.value == null) return false;
|
||||
const state = participation.state$.value;
|
||||
return !(
|
||||
state.kind === "failed" && state.error instanceof RTCMembershipManagerError
|
||||
);
|
||||
}
|
||||
|
||||
/** {@link CallView}, once it has the slot and mute state everything below needs. */
|
||||
const LoadedCallView: FC<LoadedProps> = ({
|
||||
client,
|
||||
room,
|
||||
isPasswordlessUser,
|
||||
confineToRoom,
|
||||
preload,
|
||||
skipLobby,
|
||||
rtcSession,
|
||||
slot,
|
||||
sentCallNotification$,
|
||||
statistics,
|
||||
e2eeSystem,
|
||||
joined,
|
||||
setJoined,
|
||||
muteStates,
|
||||
@@ -162,7 +286,7 @@ const LoadedCallView: FC<LoadedProps> = ({
|
||||
const [externalError, setExternalError] = useState<ElementCallError | null>(
|
||||
null,
|
||||
);
|
||||
const memberships = useMatrixRTCSessionMemberships(rtcSession);
|
||||
const members = useBehavior(slot.members$);
|
||||
const rootElement = useRootElement();
|
||||
const hostBridge = useHostBridge();
|
||||
// A host that can close us is a host that decides when we stop existing, so
|
||||
@@ -181,7 +305,7 @@ const LoadedCallView: FC<LoadedProps> = ({
|
||||
);
|
||||
// This should use `useEffectEvent` (only available in experimental versions)
|
||||
useEffect(() => {
|
||||
if (memberships.length >= MUTE_PARTICIPANT_COUNT)
|
||||
if (members.length >= MUTE_PARTICIPANT_COUNT)
|
||||
muteStates.audio.setEnabled$.value?.(false);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
@@ -203,48 +327,10 @@ const LoadedCallView: FC<LoadedProps> = ({
|
||||
};
|
||||
}, [rootElement]);
|
||||
|
||||
useEffect(() => {
|
||||
window.rtcSession = rtcSession;
|
||||
return (): void => {
|
||||
delete window.rtcSession;
|
||||
};
|
||||
}, [rtcSession]);
|
||||
|
||||
// TODO move this into the callViewModel LocalMembership.ts
|
||||
// We might actually not need this at all. Since we get into fatalError on those errors already?
|
||||
useTypedEventEmitter(
|
||||
rtcSession,
|
||||
MatrixRTCSessionEvent.MembershipManagerError,
|
||||
(error) => {
|
||||
// When matrix_rtc_mode=matrix_2_0 is in effect but the homeserver does
|
||||
// not advertise MSC4354 (sticky events), the SDK throws an
|
||||
// `UnsupportedStickyEventsEndpointError`. The MembershipManager
|
||||
// scheduler wraps it and exposes the original via `.cause`.
|
||||
if (
|
||||
error instanceof Error &&
|
||||
error.cause instanceof UnsupportedStickyEventsEndpointError
|
||||
) {
|
||||
setExternalError(new StickyEventsRequiredError());
|
||||
} else {
|
||||
setExternalError(new ConnectionLostError());
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
// Sanity check the room object
|
||||
if (client.getRoom(rtcSession.room.roomId) !== rtcSession.room)
|
||||
logger.warn(
|
||||
`We've ended up with multiple rooms for the same ID (${rtcSession.room.roomId}). This indicates a bug in the group call loading code, and may lead to incomplete room state.`,
|
||||
);
|
||||
}, [client, rtcSession.room]);
|
||||
|
||||
const room = rtcSession.room as Room;
|
||||
const { displayName, avatarUrl } = useProfile(client);
|
||||
const roomName = useRoomName(room);
|
||||
const roomAvatar = useRoomAvatar(room);
|
||||
const { returnToLobby, password: passwordFromUrl, header } = useUrlParams();
|
||||
const e2eeSystem = useRoomEncryptionSystem(room.roomId);
|
||||
|
||||
// Save the password once we start the groupCallView
|
||||
useEffect(() => {
|
||||
@@ -260,7 +346,6 @@ const LoadedCallView: FC<LoadedProps> = ({
|
||||
avatarUrl: avatarUrl!,
|
||||
roomId: room.roomId,
|
||||
roomName,
|
||||
roomAlias: room.getCanonicalAlias(),
|
||||
roomAvatar,
|
||||
e2eeSystem,
|
||||
};
|
||||
@@ -268,8 +353,8 @@ const LoadedCallView: FC<LoadedProps> = ({
|
||||
|
||||
// Count each member only once, regardless of how many devices they use
|
||||
const participantCount = useMemo(
|
||||
() => new Set<string>(memberships.map((m) => m.userId!)).size,
|
||||
[memberships],
|
||||
() => new Set<string>(members.map((m) => m.userId)).size,
|
||||
[members],
|
||||
);
|
||||
|
||||
const mediaDevices = useMediaDevices();
|
||||
@@ -277,27 +362,24 @@ const LoadedCallView: FC<LoadedProps> = ({
|
||||
// Opened by the lobby, published by the call: one capture for both
|
||||
const media = useLocalMedia();
|
||||
|
||||
const enterRTCSessionOrError = useCallback(
|
||||
async (rtcSession: MatrixRTCSession): Promise<void> => {
|
||||
try {
|
||||
setJoined(true);
|
||||
// TODO-MULTI-SFU what to do with error handling now that we don't use this function?
|
||||
// @BillCarsonFr
|
||||
} catch (e) {
|
||||
if (e instanceof ElementCallError) {
|
||||
setExternalError(e);
|
||||
} else {
|
||||
logger.error(`Unknown Error while entering RTC session`, e);
|
||||
const error = new UnknownCallError(
|
||||
e instanceof Error ? e : new Error("Unknown error", { cause: e }),
|
||||
);
|
||||
setExternalError(error);
|
||||
}
|
||||
const enterRTCSessionOrError = useCallback(async (): Promise<void> => {
|
||||
try {
|
||||
setJoined(true);
|
||||
// TODO-MULTI-SFU what to do with error handling now that we don't use this function?
|
||||
// @BillCarsonFr
|
||||
} catch (e) {
|
||||
if (e instanceof ElementCallError) {
|
||||
setExternalError(e);
|
||||
} else {
|
||||
logger.error(`Unknown Error while entering RTC session`, e);
|
||||
const error = new UnknownCallError(
|
||||
e instanceof Error ? e : new Error("Unknown error", { cause: e }),
|
||||
);
|
||||
setExternalError(error);
|
||||
}
|
||||
return Promise.resolve();
|
||||
},
|
||||
[setJoined],
|
||||
);
|
||||
}
|
||||
return Promise.resolve();
|
||||
}, [setJoined]);
|
||||
|
||||
useEffect(() => {
|
||||
const defaultDeviceSetup = async ({
|
||||
@@ -360,7 +442,6 @@ const LoadedCallView: FC<LoadedProps> = ({
|
||||
}
|
||||
}, [
|
||||
hostBridge,
|
||||
rtcSession,
|
||||
preload,
|
||||
skipLobby,
|
||||
mediaDevices,
|
||||
@@ -407,9 +488,9 @@ const LoadedCallView: FC<LoadedProps> = ({
|
||||
const sendInstantly = hostControlsLifetime;
|
||||
PosthogAnalytics.instance.eventCallEnded.track(
|
||||
room.roomId,
|
||||
rtcSession.memberships.length,
|
||||
slot.members$.value.length,
|
||||
sendInstantly,
|
||||
rtcSession,
|
||||
statistics,
|
||||
);
|
||||
// Unfortunately the PostHog library provides no way to await the
|
||||
// tracking of an event, but we don't really want it to hold up our
|
||||
@@ -455,7 +536,8 @@ const LoadedCallView: FC<LoadedProps> = ({
|
||||
hostBridge,
|
||||
hostControlsLifetime,
|
||||
room.roomId,
|
||||
rtcSession,
|
||||
slot,
|
||||
statistics,
|
||||
isPasswordlessUser,
|
||||
confineToRoom,
|
||||
returnToLobby,
|
||||
@@ -469,7 +551,7 @@ const LoadedCallView: FC<LoadedProps> = ({
|
||||
hostBridge.setAlwaysOnScreen(true).catch((e) => {
|
||||
logger.error("Error calling setAlwaysOnScreen(true)", e);
|
||||
});
|
||||
}, [hostBridge, joined, rtcSession]);
|
||||
}, [hostBridge, joined]);
|
||||
|
||||
const joinRule = useJoinRule(room);
|
||||
|
||||
@@ -530,7 +612,8 @@ const LoadedCallView: FC<LoadedProps> = ({
|
||||
<ActiveCall
|
||||
client={client}
|
||||
matrixInfo={matrixInfo}
|
||||
rtcSession={rtcSession as MatrixRTCSession}
|
||||
slot={slot}
|
||||
sentCallNotification$={sentCallNotification$}
|
||||
matrixRoom={room}
|
||||
onLeft={onLeft}
|
||||
media={media}
|
||||
@@ -553,7 +636,7 @@ const LoadedCallView: FC<LoadedProps> = ({
|
||||
if (isPasswordlessUser || PosthogAnalytics.instance.isEnabled()) {
|
||||
body = (
|
||||
<CallEndedView
|
||||
endedCallId={rtcSession.room.roomId}
|
||||
endedCallId={room.roomId}
|
||||
client={client}
|
||||
isPasswordlessUser={isPasswordlessUser}
|
||||
hideHeader={header === HeaderStyle.None}
|
||||
@@ -570,7 +653,7 @@ const LoadedCallView: FC<LoadedProps> = ({
|
||||
// Left, and the host decides what happens next:
|
||||
body = returnToLobby ? lobbyView : null;
|
||||
} else if (preload || skipLobby) {
|
||||
// The RTC session is not joined to yet (`isJoined`), but enterRTCSessionOrError should have been called.
|
||||
// Not in the call yet: waiting for the host to say when, or about to join
|
||||
body = null;
|
||||
} else {
|
||||
body = lobbyView;
|
||||
@@ -582,16 +665,16 @@ const LoadedCallView: FC<LoadedProps> = ({
|
||||
setExternalError(null);
|
||||
if (action == "reconnect") {
|
||||
setLeft(false);
|
||||
await enterRTCSessionOrError(rtcSession).catch((e) => {
|
||||
await enterRTCSessionOrError().catch((e) => {
|
||||
logger.error("Error re-entering RTC session", e);
|
||||
});
|
||||
}
|
||||
}}
|
||||
onError={(_error) => {
|
||||
if (rtcSession.isJoined()) onLeft("error");
|
||||
if (isInCall(slot)) onLeft("error");
|
||||
// If there is an error we need to be dismissible again. This is done in
|
||||
// `onLeft` as well; we need it here explicitly in case
|
||||
// rtcSession.isJoined is false.
|
||||
// `onLeft` as well; we need it here explicitly in case we were not in
|
||||
// the call.
|
||||
void hostBridge.setAlwaysOnScreen(false);
|
||||
}}
|
||||
>
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user