Compare commits

102 Commits

Author SHA1 Message Date
Aine
b925c63171 clear storage on logout 2024-11-07 10:46:25 +02:00
Aine
6faebaf9df properly handle restrictBaseUrl config option, fixes #128 2024-11-07 10:34:06 +02:00
Aine
c698f57395 Add support for config from /.well-known/matrix/client (#126)
* Add support for config from /.well-known/matrix/client

* final fixes, refactoring, updated readme
2024-11-07 00:24:33 +02:00
Borislav Pantaleev
9adc13e722 Add User Rate Limits tab (#125)
* Add User Rate Limits tab

* update readme
2024-11-06 23:55:14 +02:00
Borislav Pantaleev
a04b24a5d5 add random password generation on user create/edit form (#123)
* Add button to generate password in UserEdit

* increase default random password length to 64, add more possible symbols to the generator

* update readme
2024-11-06 11:48:44 +02:00
Borislav Pantaleev
cd1ca7c039 Add option to control user's experimental features (#111)
* Add option to control user's experimental features

* Don't use ReferenceManyField, load experimental features manually

* cleanup

* Move experimental features to their own components, improve UI

* remove background from Stack

* update readme
2024-11-06 11:25:47 +02:00
dependabot[bot]
86b4987b7f Bump ra-i18n-polyglot from 5.3.1 to 5.3.2 (#113)
Bumps [ra-i18n-polyglot](https://github.com/marmelab/react-admin) from 5.3.1 to 5.3.2.
- [Release notes](https://github.com/marmelab/react-admin/releases)
- [Changelog](https://github.com/marmelab/react-admin/blob/master/CHANGELOG.md)
- [Commits](https://github.com/marmelab/react-admin/compare/v5.3.1...v5.3.2)

---
updated-dependencies:
- dependency-name: ra-i18n-polyglot
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-11-04 11:48:36 +02:00
dependabot[bot]
a7cf647669 Bump @types/lodash from 4.17.12 to 4.17.13 (#114)
Bumps [@types/lodash](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/lodash) from 4.17.12 to 4.17.13.
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/lodash)

---
updated-dependencies:
- dependency-name: "@types/lodash"
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-11-04 11:48:25 +02:00
dependabot[bot]
80d40d2fb5 Bump @tanstack/react-query from 5.59.16 to 5.59.19 (#116)
Bumps [@tanstack/react-query](https://github.com/TanStack/query/tree/HEAD/packages/react-query) from 5.59.16 to 5.59.19.
- [Release notes](https://github.com/TanStack/query/releases)
- [Commits](https://github.com/TanStack/query/commits/v5.59.19/packages/react-query)

---
updated-dependencies:
- dependency-name: "@tanstack/react-query"
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-11-04 11:43:55 +02:00
dependabot[bot]
b19e961a35 Bump typescript-eslint from 8.11.0 to 8.12.2 (#117)
Bumps [typescript-eslint](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/typescript-eslint) from 8.11.0 to 8.12.2.
- [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases)
- [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/typescript-eslint/CHANGELOG.md)
- [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.12.2/packages/typescript-eslint)

---
updated-dependencies:
- dependency-name: typescript-eslint
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-11-04 11:43:42 +02:00
dependabot[bot]
08f5f8ebd2 Bump @types/node from 22.8.1 to 22.8.7 (#118)
Bumps [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) from 22.8.1 to 22.8.7.
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node)

---
updated-dependencies:
- dependency-name: "@types/node"
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-11-04 11:43:30 +02:00
dependabot[bot]
1edf196049 Bump ra-language-english from 5.3.1 to 5.3.2 (#119)
Bumps [ra-language-english](https://github.com/marmelab/react-admin) from 5.3.1 to 5.3.2.
- [Release notes](https://github.com/marmelab/react-admin/releases)
- [Changelog](https://github.com/marmelab/react-admin/blob/master/CHANGELOG.md)
- [Commits](https://github.com/marmelab/react-admin/compare/v5.3.1...v5.3.2)

---
updated-dependencies:
- dependency-name: ra-language-english
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-11-04 11:43:11 +02:00
dependabot[bot]
1f66b4d14a Bump ra-core from 5.3.1 to 5.3.2 (#120)
Bumps [ra-core](https://github.com/marmelab/react-admin) from 5.3.1 to 5.3.2.
- [Release notes](https://github.com/marmelab/react-admin/releases)
- [Changelog](https://github.com/marmelab/react-admin/blob/master/CHANGELOG.md)
- [Commits](https://github.com/marmelab/react-admin/compare/v5.3.1...v5.3.2)

---
updated-dependencies:
- dependency-name: ra-core
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-11-04 11:42:57 +02:00
dependabot[bot]
cec5b0af9a Bump @testing-library/jest-dom from 6.6.2 to 6.6.3 (#121)
Bumps [@testing-library/jest-dom](https://github.com/testing-library/jest-dom) from 6.6.2 to 6.6.3.
- [Release notes](https://github.com/testing-library/jest-dom/releases)
- [Changelog](https://github.com/testing-library/jest-dom/blob/main/CHANGELOG.md)
- [Commits](https://github.com/testing-library/jest-dom/compare/v6.6.2...v6.6.3)

---
updated-dependencies:
- dependency-name: "@testing-library/jest-dom"
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-11-04 11:42:44 +02:00
dependabot[bot]
2b0e1e7c0e Bump @mui/material from 6.1.5 to 6.1.6 (#122)
Bumps [@mui/material](https://github.com/mui/material-ui/tree/HEAD/packages/mui-material) from 6.1.5 to 6.1.6.
- [Release notes](https://github.com/mui/material-ui/releases)
- [Changelog](https://github.com/mui/material-ui/blob/master/CHANGELOG.md)
- [Commits](https://github.com/mui/material-ui/commits/v6.1.6/packages/mui-material)

---
updated-dependencies:
- dependency-name: "@mui/material"
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-11-04 11:42:31 +02:00
Aine
a613a88232 allow setting version using SYNAPSE_ADMIN_VERSION env var on build (if git is not available) 2024-10-31 17:18:28 +02:00
Aine
7afce71bef handle envs without git in the build hook 2024-10-31 17:11:27 +02:00
Aine
fe4ba22a03 update README 2024-10-30 18:49:32 +02:00
Aine
eb35d9e122 remove CI hack to include version into manifest.json (now generated on each build automatically) 2024-10-30 18:00:05 +02:00
Aine
fa79fecc9d Generate extended manifest.json on build 2024-10-30 17:58:33 +02:00
dependabot[bot]
61366b3792 Bump ra-language-english from 5.3.0 to 5.3.1 (#102)
Bumps [ra-language-english](https://github.com/marmelab/react-admin) from 5.3.0 to 5.3.1.
- [Release notes](https://github.com/marmelab/react-admin/releases)
- [Changelog](https://github.com/marmelab/react-admin/blob/master/CHANGELOG.md)
- [Commits](https://github.com/marmelab/react-admin/compare/v5.3.0...v5.3.1)

---
updated-dependencies:
- dependency-name: ra-language-english
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-10-28 10:55:00 +02:00
dependabot[bot]
b55033d983 Bump react-admin from 5.3.0 to 5.3.1 (#103)
Bumps [react-admin](https://github.com/marmelab/react-admin) from 5.3.0 to 5.3.1.
- [Release notes](https://github.com/marmelab/react-admin/releases)
- [Changelog](https://github.com/marmelab/react-admin/blob/master/CHANGELOG.md)
- [Commits](https://github.com/marmelab/react-admin/compare/v5.3.0...v5.3.1)

---
updated-dependencies:
- dependency-name: react-admin
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-10-28 10:54:46 +02:00
dependabot[bot]
b1f42988c8 Bump ra-language-french from 5.3.0 to 5.3.1 (#104)
Bumps [ra-language-french](https://github.com/marmelab/react-admin) from 5.3.0 to 5.3.1.
- [Release notes](https://github.com/marmelab/react-admin/releases)
- [Changelog](https://github.com/marmelab/react-admin/blob/master/CHANGELOG.md)
- [Commits](https://github.com/marmelab/react-admin/compare/v5.3.0...v5.3.1)

---
updated-dependencies:
- dependency-name: ra-language-french
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-10-28 10:54:27 +02:00
dependabot[bot]
ef05b366c3 Bump eslint-plugin-jsx-a11y from 6.10.1 to 6.10.2 (#105)
Bumps [eslint-plugin-jsx-a11y](https://github.com/jsx-eslint/eslint-plugin-jsx-a11y) from 6.10.1 to 6.10.2.
- [Release notes](https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/releases)
- [Changelog](https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/main/CHANGELOG.md)
- [Commits](https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/compare/v6.10.1...v6.10.2)

---
updated-dependencies:
- dependency-name: eslint-plugin-jsx-a11y
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-10-28 10:53:30 +02:00
dependabot[bot]
b3d52e7d23 Bump @types/node from 22.7.9 to 22.8.1 (#106)
Bumps [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) from 22.7.9 to 22.8.1.
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node)

---
updated-dependencies:
- dependency-name: "@types/node"
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-10-28 10:53:18 +02:00
dependabot[bot]
d1c4250b46 Bump @tanstack/react-query from 5.59.15 to 5.59.16 (#107)
Bumps [@tanstack/react-query](https://github.com/TanStack/query/tree/HEAD/packages/react-query) from 5.59.15 to 5.59.16.
- [Release notes](https://github.com/TanStack/query/releases)
- [Commits](https://github.com/TanStack/query/commits/v5.59.16/packages/react-query)

---
updated-dependencies:
- dependency-name: "@tanstack/react-query"
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-10-28 10:53:04 +02:00
dependabot[bot]
8d44077b24 Bump ra-core from 5.3.0 to 5.3.1 (#109)
Bumps [ra-core](https://github.com/marmelab/react-admin) from 5.3.0 to 5.3.1.
- [Release notes](https://github.com/marmelab/react-admin/releases)
- [Changelog](https://github.com/marmelab/react-admin/blob/master/CHANGELOG.md)
- [Commits](https://github.com/marmelab/react-admin/compare/v5.3.0...v5.3.1)

---
updated-dependencies:
- dependency-name: ra-core
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-10-28 10:52:37 +02:00
Aine
44e8b82412 Sanitize CSV on import (#101)
* Sanitize CSV on import

* update readme
2024-10-25 11:52:26 +03:00
Aine
791ae2c869 update naming 2024-10-24 21:49:00 +03:00
Aine
ee3753466a update manifest 2024-10-24 17:27:10 +03:00
Aine
b7dc703157 add community room to the footer 2024-10-24 14:17:02 +03:00
Aine
2eca0dcc33 better visual 2024-10-24 14:11:59 +03:00
Aine
d2219c1667 try adding community room to the readme 2024-10-24 14:11:23 +03:00
Aine
132ea6f97f add images 2024-10-24 13:44:12 +03:00
Aine
28ef08de03 Fix room state events display (#100)
* Fix room state events table display

* update readme
2024-10-23 13:48:21 +03:00
Aine
865e53388e fix yarn lint 2024-10-23 12:31:52 +03:00
dependabot[bot]
3a105bb8c7 Bump eslint from 8.57.1 to 9.13.0 (#99)
Bumps [eslint](https://github.com/eslint/eslint) from 8.57.1 to 9.13.0.
- [Release notes](https://github.com/eslint/eslint/releases)
- [Changelog](https://github.com/eslint/eslint/blob/main/CHANGELOG.md)
- [Commits](https://github.com/eslint/eslint/compare/v8.57.1...v9.13.0)

---
updated-dependencies:
- dependency-name: eslint
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-10-23 12:14:33 +03:00
dependabot[bot]
edcda7a202 Bump @mui/icons-material from 6.1.1 to 6.1.5 (#98)
Bumps [@mui/icons-material](https://github.com/mui/material-ui/tree/HEAD/packages/mui-icons-material) from 6.1.1 to 6.1.5.
- [Release notes](https://github.com/mui/material-ui/releases)
- [Changelog](https://github.com/mui/material-ui/blob/master/CHANGELOG.md)
- [Commits](https://github.com/mui/material-ui/commits/v6.1.5/packages/mui-icons-material)

---
updated-dependencies:
- dependency-name: "@mui/icons-material"
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-10-23 12:13:59 +03:00
dependabot[bot]
edd69273e2 Bump typescript-eslint from 8.10.0 to 8.11.0 (#88)
Bumps [typescript-eslint](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/typescript-eslint) from 8.10.0 to 8.11.0.
- [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases)
- [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/typescript-eslint/CHANGELOG.md)
- [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.11.0/packages/typescript-eslint)

---
updated-dependencies:
- dependency-name: typescript-eslint
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-10-23 12:10:43 +03:00
dependabot[bot]
444bfacbd9 Bump eslint-plugin-unused-imports from 3.2.0 to 4.1.4 (#93)
Bumps [eslint-plugin-unused-imports](https://github.com/sweepline/eslint-plugin-unused-imports) from 3.2.0 to 4.1.4.
- [Commits](https://github.com/sweepline/eslint-plugin-unused-imports/commits/v4.1.4)

---
updated-dependencies:
- dependency-name: eslint-plugin-unused-imports
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-10-23 12:07:18 +03:00
dependabot[bot]
970e0a550f Bump @types/node from 22.7.7 to 22.7.9 (#91)
Bumps [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) from 22.7.7 to 22.7.9.
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node)

---
updated-dependencies:
- dependency-name: "@types/node"
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-10-23 12:06:41 +03:00
dependabot[bot]
b3ef68d66e Bump @types/jest from 29.5.13 to 29.5.14 (#95)
Bumps [@types/jest](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/jest) from 29.5.13 to 29.5.14.
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/jest)

---
updated-dependencies:
- dependency-name: "@types/jest"
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-10-23 12:06:26 +03:00
dependabot[bot]
31382a42ee Bump @typescript-eslint/eslint-plugin from 8.10.0 to 8.11.0 (#92)
Bumps [@typescript-eslint/eslint-plugin](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/eslint-plugin) from 8.10.0 to 8.11.0.
- [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases)
- [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/CHANGELOG.md)
- [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.11.0/packages/eslint-plugin)

---
updated-dependencies:
- dependency-name: "@typescript-eslint/eslint-plugin"
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-10-23 12:06:11 +03:00
dependabot[bot]
1a7748d1ef Bump @vitejs/plugin-react from 4.3.2 to 4.3.3 (#87)
Bumps [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/tree/HEAD/packages/plugin-react) from 4.3.2 to 4.3.3.
- [Release notes](https://github.com/vitejs/vite-plugin-react/releases)
- [Changelog](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite-plugin-react/commits/v4.3.3/packages/plugin-react)

---
updated-dependencies:
- dependency-name: "@vitejs/plugin-react"
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-10-23 12:05:51 +03:00
dependabot[bot]
039b28cc5c Bump vite from 5.4.6 to 5.4.10 (#89)
Bumps [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite) from 5.4.6 to 5.4.10.
- [Release notes](https://github.com/vitejs/vite/releases)
- [Changelog](https://github.com/vitejs/vite/blob/v5.4.10/packages/vite/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite/commits/v5.4.10/packages/vite)

---
updated-dependencies:
- dependency-name: vite
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-10-23 12:03:42 +03:00
dependabot[bot]
57eae3edb3 Bump @mui/material from 6.1.1 to 6.1.5 (#94)
Bumps [@mui/material](https://github.com/mui/material-ui/tree/HEAD/packages/mui-material) from 6.1.1 to 6.1.5.
- [Release notes](https://github.com/mui/material-ui/releases)
- [Changelog](https://github.com/mui/material-ui/blob/master/CHANGELOG.md)
- [Commits](https://github.com/mui/material-ui/commits/v6.1.5/packages/mui-material)

---
updated-dependencies:
- dependency-name: "@mui/material"
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-10-23 12:03:20 +03:00
dependabot[bot]
dadc9416c0 Bump eslint-plugin-jsx-a11y from 6.10.0 to 6.10.1 (#97)
Bumps [eslint-plugin-jsx-a11y](https://github.com/jsx-eslint/eslint-plugin-jsx-a11y) from 6.10.0 to 6.10.1.
- [Release notes](https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/releases)
- [Changelog](https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/main/CHANGELOG.md)
- [Commits](https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/compare/v6.10.0...v6.10.1)

---
updated-dependencies:
- dependency-name: eslint-plugin-jsx-a11y
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-10-23 12:03:03 +03:00
dependabot[bot]
eab2342114 Bump @types/lodash from 4.17.7 to 4.17.12 (#96)
Bumps [@types/lodash](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/lodash) from 4.17.7 to 4.17.12.
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/lodash)

---
updated-dependencies:
- dependency-name: "@types/lodash"
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-10-23 12:02:40 +03:00
dependabot[bot]
9cf2f83936 Bump ra-language-french from 5.2.0 to 5.3.0 (#90)
Bumps [ra-language-french](https://github.com/marmelab/react-admin) from 5.2.0 to 5.3.0.
- [Release notes](https://github.com/marmelab/react-admin/releases)
- [Changelog](https://github.com/marmelab/react-admin/blob/master/CHANGELOG.md)
- [Commits](https://github.com/marmelab/react-admin/compare/v5.2.0...v5.3.0)

---
updated-dependencies:
- dependency-name: ra-language-french
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-10-23 12:02:09 +03:00
dependabot[bot]
d823856873 Bump @typescript-eslint/parser from 8.10.0 to 8.11.0 (#86)
Bumps [@typescript-eslint/parser](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/parser) from 8.10.0 to 8.11.0.
- [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases)
- [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/parser/CHANGELOG.md)
- [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.11.0/packages/parser)

---
updated-dependencies:
- dependency-name: "@typescript-eslint/parser"
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-10-23 12:01:17 +03:00
dependabot[bot]
9b96c7cec8 Bump @eslint/js from 9.10.0 to 9.13.0 (#85)
Bumps [@eslint/js](https://github.com/eslint/eslint/tree/HEAD/packages/js) from 9.10.0 to 9.13.0.
- [Release notes](https://github.com/eslint/eslint/releases)
- [Changelog](https://github.com/eslint/eslint/blob/main/CHANGELOG.md)
- [Commits](https://github.com/eslint/eslint/commits/v9.13.0/packages/js)

---
updated-dependencies:
- dependency-name: "@eslint/js"
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-10-23 12:01:01 +03:00
dependabot[bot]
f211aba873 Bump @types/react from 18.3.8 to 18.3.12 (#84)
Bumps [@types/react](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/react) from 18.3.8 to 18.3.12.
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/react)

---
updated-dependencies:
- dependency-name: "@types/react"
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-10-23 12:00:50 +03:00
dependabot[bot]
c0fc2d8937 Bump @tanstack/react-query from 5.56.2 to 5.59.15 (#83)
Bumps [@tanstack/react-query](https://github.com/TanStack/query/tree/HEAD/packages/react-query) from 5.56.2 to 5.59.15.
- [Release notes](https://github.com/TanStack/query/releases)
- [Commits](https://github.com/TanStack/query/commits/v5.59.15/packages/react-query)

---
updated-dependencies:
- dependency-name: "@tanstack/react-query"
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-10-23 12:00:37 +03:00
Aine
a88b397748 increase dependabot PR limits 2024-10-23 11:58:50 +03:00
Aine
abc922c956 Enable visual customization (#81)
* Enable visual customization

* update readme
2024-10-23 00:03:06 +03:00
Aine
4f2cd38344 Add user profile to the top menu (#80)
* Add user profile to the top menu

* update readme
2024-10-22 12:18:55 +03:00
Aine
ca71038874 Custom Menu Items (#79)
* Custom Menu Items

* update readme

* fix indentation
2024-10-21 23:33:51 +03:00
Borislav Pantaleev
be867b6b0d Fix types and missing translations (#78) 2024-10-21 19:37:29 +03:00
Aine
f2f540b429 fix footer content overlapping and scrollbar 2024-10-21 13:27:32 +03:00
Aine
7feec4ba07 update eslint typescript 2024-10-21 12:01:12 +03:00
Aine
1d5fef1e53 add missing package 2024-10-21 11:43:26 +03:00
dependabot[bot]
9c40efde17 Bump typescript-eslint from 7.18.0 to 8.10.0 (#76)
Bumps [typescript-eslint](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/typescript-eslint) from 7.18.0 to 8.10.0.
- [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases)
- [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/typescript-eslint/CHANGELOG.md)
- [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.10.0/packages/typescript-eslint)

---
updated-dependencies:
- dependency-name: typescript-eslint
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-10-21 11:34:26 +03:00
dependabot[bot]
53dff66978 Bump react-admin from 5.2.0 to 5.3.0 (#77)
Bumps [react-admin](https://github.com/marmelab/react-admin) from 5.2.0 to 5.3.0.
- [Release notes](https://github.com/marmelab/react-admin/releases)
- [Changelog](https://github.com/marmelab/react-admin/blob/master/CHANGELOG.md)
- [Commits](https://github.com/marmelab/react-admin/compare/v5.2.0...v5.3.0)

---
updated-dependencies:
- dependency-name: react-admin
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-10-21 11:31:09 +03:00
dependabot[bot]
3a595247e8 Bump vite-plugin-version-mark from 0.1.1 to 0.1.2 (#75)
Bumps [vite-plugin-version-mark](https://github.com/ZhongxuYang/vite-plugin-version-mark) from 0.1.1 to 0.1.2.
- [Release notes](https://github.com/ZhongxuYang/vite-plugin-version-mark/releases)
- [Changelog](https://github.com/ZhongxuYang/vite-plugin-version-mark/blob/main/CHANGELOG.md)
- [Commits](https://github.com/ZhongxuYang/vite-plugin-version-mark/compare/v0.1.1...v0.1.2)

---
updated-dependencies:
- dependency-name: vite-plugin-version-mark
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-10-21 11:29:57 +03:00
dependabot[bot]
33f5f60e31 Bump eslint-plugin-import from 2.30.0 to 2.31.0 (#74)
Bumps [eslint-plugin-import](https://github.com/import-js/eslint-plugin-import) from 2.30.0 to 2.31.0.
- [Release notes](https://github.com/import-js/eslint-plugin-import/releases)
- [Changelog](https://github.com/import-js/eslint-plugin-import/blob/main/CHANGELOG.md)
- [Commits](https://github.com/import-js/eslint-plugin-import/compare/v2.30.0...v2.31.0)

---
updated-dependencies:
- dependency-name: eslint-plugin-import
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-10-21 11:29:35 +03:00
dependabot[bot]
9dd2ea57c9 Bump @types/papaparse from 5.3.14 to 5.3.15 (#73)
Bumps [@types/papaparse](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/papaparse) from 5.3.14 to 5.3.15.
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/papaparse)

---
updated-dependencies:
- dependency-name: "@types/papaparse"
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-10-21 11:29:16 +03:00
dependabot[bot]
fae7a696de Bump ra-i18n-polyglot from 5.2.0 to 5.3.0 (#68)
Bumps [ra-i18n-polyglot](https://github.com/marmelab/react-admin) from 5.2.0 to 5.3.0.
- [Release notes](https://github.com/marmelab/react-admin/releases)
- [Changelog](https://github.com/marmelab/react-admin/blob/master/CHANGELOG.md)
- [Commits](https://github.com/marmelab/react-admin/compare/v5.2.0...v5.3.0)

---
updated-dependencies:
- dependency-name: ra-i18n-polyglot
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-10-19 16:23:56 +03:00
dependabot[bot]
49e8b2d0f5 Bump vite-plugin-version-mark from 0.1.0 to 0.1.1 (#72)
Bumps [vite-plugin-version-mark](https://github.com/ZhongxuYang/vite-plugin-version-mark) from 0.1.0 to 0.1.1.
- [Release notes](https://github.com/ZhongxuYang/vite-plugin-version-mark/releases)
- [Changelog](https://github.com/ZhongxuYang/vite-plugin-version-mark/blob/main/CHANGELOG.md)
- [Commits](https://github.com/ZhongxuYang/vite-plugin-version-mark/compare/v0.1.0...v0.1.1)

---
updated-dependencies:
- dependency-name: vite-plugin-version-mark
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-10-19 16:22:15 +03:00
dependabot[bot]
281d908d3f Bump ra-language-english from 5.2.0 to 5.3.0 (#71)
Bumps [ra-language-english](https://github.com/marmelab/react-admin) from 5.2.0 to 5.3.0.
- [Release notes](https://github.com/marmelab/react-admin/releases)
- [Changelog](https://github.com/marmelab/react-admin/blob/master/CHANGELOG.md)
- [Commits](https://github.com/marmelab/react-admin/compare/v5.2.0...v5.3.0)

---
updated-dependencies:
- dependency-name: ra-language-english
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-10-19 16:21:57 +03:00
dependabot[bot]
bacc42fe9c Bump react-router-dom from 6.26.2 to 6.27.0 (#70)
Bumps [react-router-dom](https://github.com/remix-run/react-router/tree/HEAD/packages/react-router-dom) from 6.26.2 to 6.27.0.
- [Release notes](https://github.com/remix-run/react-router/releases)
- [Changelog](https://github.com/remix-run/react-router/blob/react-router-dom@6.27.0/packages/react-router-dom/CHANGELOG.md)
- [Commits](https://github.com/remix-run/react-router/commits/react-router-dom@6.27.0/packages/react-router-dom)

---
updated-dependencies:
- dependency-name: react-router-dom
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-10-19 16:21:44 +03:00
dependabot[bot]
1c26a28ca9 Bump react-hook-form from 7.53.0 to 7.53.1 (#69)
Bumps [react-hook-form](https://github.com/react-hook-form/react-hook-form) from 7.53.0 to 7.53.1.
- [Release notes](https://github.com/react-hook-form/react-hook-form/releases)
- [Changelog](https://github.com/react-hook-form/react-hook-form/blob/master/CHANGELOG.md)
- [Commits](https://github.com/react-hook-form/react-hook-form/compare/v7.53.0...v7.53.1)

---
updated-dependencies:
- dependency-name: react-hook-form
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-10-19 16:21:33 +03:00
dependabot[bot]
d3a04cd132 Bump @vitejs/plugin-react from 4.3.1 to 4.3.2 (#67)
Bumps [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/tree/HEAD/packages/plugin-react) from 4.3.1 to 4.3.2.
- [Release notes](https://github.com/vitejs/vite-plugin-react/releases)
- [Changelog](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite-plugin-react/commits/v4.3.2/packages/plugin-react)

---
updated-dependencies:
- dependency-name: "@vitejs/plugin-react"
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-10-19 16:20:58 +03:00
dependabot[bot]
e6060a23ac Bump @types/node from 20.16.5 to 22.7.7 (#66)
Bumps [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) from 20.16.5 to 22.7.7.
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node)

---
updated-dependencies:
- dependency-name: "@types/node"
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-10-19 16:20:43 +03:00
dependabot[bot]
4b7fbf483a Bump typescript from 5.6.2 to 5.6.3 (#65)
Bumps [typescript](https://github.com/microsoft/TypeScript) from 5.6.2 to 5.6.3.
- [Release notes](https://github.com/microsoft/TypeScript/releases)
- [Changelog](https://github.com/microsoft/TypeScript/blob/main/azure-pipelines.release.yml)
- [Commits](https://github.com/microsoft/TypeScript/compare/v5.6.2...v5.6.3)

---
updated-dependencies:
- dependency-name: typescript
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-10-19 16:20:31 +03:00
dependabot[bot]
bc3c30da92 Bump @testing-library/jest-dom from 6.5.0 to 6.6.2 (#64)
Bumps [@testing-library/jest-dom](https://github.com/testing-library/jest-dom) from 6.5.0 to 6.6.2.
- [Release notes](https://github.com/testing-library/jest-dom/releases)
- [Changelog](https://github.com/testing-library/jest-dom/blob/main/CHANGELOG.md)
- [Commits](https://github.com/testing-library/jest-dom/compare/v6.5.0...v6.6.2)

---
updated-dependencies:
- dependency-name: "@testing-library/jest-dom"
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-10-19 16:20:02 +03:00
dependabot[bot]
1896f770d1 Bump ra-core from 5.2.0 to 5.3.0 (#63)
Bumps [ra-core](https://github.com/marmelab/react-admin) from 5.2.0 to 5.3.0.
- [Release notes](https://github.com/marmelab/react-admin/releases)
- [Changelog](https://github.com/marmelab/react-admin/blob/master/CHANGELOG.md)
- [Commits](https://github.com/marmelab/react-admin/compare/v5.2.0...v5.3.0)

---
updated-dependencies:
- dependency-name: ra-core
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-10-19 16:19:34 +03:00
dependabot[bot]
99d0b9ad72 Bump docker/setup-buildx-action from 1 to 3 (#62)
Bumps [docker/setup-buildx-action](https://github.com/docker/setup-buildx-action) from 1 to 3.
- [Release notes](https://github.com/docker/setup-buildx-action/releases)
- [Commits](https://github.com/docker/setup-buildx-action/compare/v1...v3)

---
updated-dependencies:
- dependency-name: docker/setup-buildx-action
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-10-19 16:19:06 +03:00
Aine
944afb9056 bring back dependabot config 2024-10-19 16:15:23 +03:00
Aine
23f5a24803 update README.md 2024-10-19 15:57:12 +03:00
Borislav Pantaleev
60ae00ac14 Add seprate login button for access token (#61) 2024-10-19 12:03:46 +00:00
Borislav Pantaleev
26862fa708 Add etke.cc to footer and package.json (#60)
* Add etke.cc to footer and package.json

* more links
2024-10-19 11:24:45 +03:00
Aine
853d14c1ce fix 'Sign in' button disabled on SSO-only servers when attempting access token login 2024-10-18 10:21:48 +03:00
jamazi
11a5cac709 Refactor required fields check on Bulk CSV upload (#59)
Related to https://github.com/etkecc/synapse-admin/pull/32
2024-10-17 22:56:19 +03:00
Borislav Pantaleev
0d021021df Add option for access token login (#58)
* Fix SSO login flow, redirect is done after auth

* Add accessToken login

* Add confirmation for session destroy on accessToken logout

* add translations, fix tests, minor renaming

* update readme
2024-10-17 18:34:20 +03:00
Aine
19302466ef update README.md 2024-10-10 22:13:50 +03:00
Aine
0594259ae4 make avatar field sortable in the users list 2024-10-08 12:15:03 +03:00
Aine
ba485bbb18 Merge branch 'master' 2024-10-08 10:51:16 +03:00
Dirk Klimpel
9fc005032c Fix for empty user default tab after creation (#628) 2024-10-08 09:20:55 +02:00
Aine
f5d6f24b30 correctly treat empty or "almost empty" restrictBaseUrl config option, fixes #56 2024-10-07 12:00:33 +03:00
Aine
a42efe7eda do not color failed federation destinations, use an icon instead 2024-10-04 00:16:11 +03:00
Borislav Pantaleev
31d3712dbb Better media preview/download implementation (#53)
* Add download option for non image media

* make view media button change the icon during the loading; update readme
2024-10-03 11:23:51 +03:00
Aine
a15dad4a31 ensure preview works for images only (for now) 2024-10-03 01:18:45 +03:00
Borislav Pantaleev
9062a6afb1 Remove Dialog window for image preview, open all media in new tab 2024-10-03 00:52:07 +03:00
Borislav Pantaleev
a79c3597d6 Authenticated Media Support (#51)
* Fix AvatarField to work with authenticated media

* Fix ViewMediaButton to work for user's media tab and reported events

* remove console.log

* cleanup AvatarField

* use correct thumbnail size

* fix AvatarField.test

* ignore postgres data for watchman

* fix new avatar preview

* watchman should ignore testdata completely, instead of specific subdirs

* update README

* change user's media icon in sidebar - use the same icon as the media tab

* Add preview for user media files if mimeType is image/*

* Add new line in user media Dialog
2024-10-03 00:38:35 +03:00
Aine
470f1b5455 adjust 'redact all user events on remove' to the new API 2024-10-02 23:34:07 +03:00
Aine
46cc0e2fda refactor users' after delete to react-admin lifecycle hooks, fixes #50 2024-09-29 19:46:00 +03:00
Aine
f3080e9468 Provide options to delete media and redact events on user erase (#49)
* Provide options to delete media and redact events on user erase

* update readme
2024-09-29 00:16:44 +03:00
Aine
f8fe1166e2 Do not block deleted rooms from being rejoined by default (UI option), fixes #48 2024-09-27 19:25:15 +03:00
Borislav Pantaleev
02bee92806 Fix missing QueryClient (#47) 2024-09-26 21:42:09 +00:00
Aine
b7f8e03894 update README 2024-09-25 19:26:26 +03:00
Aine
59bb4b4183 update README 2024-09-25 19:10:43 +03:00
Aine
bb53d53692 Add Contact support button (#45) 2024-09-25 19:09:58 +03:00
51 changed files with 2875 additions and 1596 deletions

19
.github/dependabot.yml vendored Normal file
View File

@@ -0,0 +1,19 @@
version: 2
updates:
- package-ecosystem: "npm"
directory: "/"
schedule:
interval: "weekly"
open-pull-requests-limit: 10
- package-ecosystem: "docker"
directory: "/"
schedule:
interval: "weekly"
open-pull-requests-limit: 10
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"
open-pull-requests-limit: 10

View File

@@ -25,10 +25,6 @@ jobs:
cache: yarn cache: yarn
- name: Install dependencies - name: Install dependencies
run: yarn install --immutable --network-timeout=300000 run: yarn install --immutable --network-timeout=300000
- name: Set version into manifest.json
run: |
TAG=$(git describe --tags --abbrev=0 || echo "latest")
sed -i "s|\"icons\"|\"version\": \"$TAG\",\\n \"icons\"|g" public/manifest.json
- name: Build - name: Build
run: yarn build --base=${{ env.base_path }} run: yarn build --base=${{ env.base_path }}
- uses: actions/upload-artifact@v4 - uses: actions/upload-artifact@v4
@@ -52,7 +48,7 @@ jobs:
name: dist name: dist
path: dist/ path: dist/
- name: Set up Docker Buildx - name: Set up Docker Buildx
uses: docker/setup-buildx-action@v1 uses: docker/setup-buildx-action@v3
- name: Login to ghcr.io - name: Login to ghcr.io
uses: docker/login-action@v3 uses: docker/login-action@v3
with: with:

5
.watchmanconfig Normal file
View File

@@ -0,0 +1,5 @@
{
"ignore_dirs": [
"testdata"
]
}

391
README.md
View File

@@ -1,16 +1,56 @@
# Synapse Admin UI [![GitHub license](https://img.shields.io/github/license/Awesome-Technologies/synapse-admin)](https://github.com/Awesome-Technologies/synapse-admin/blob/master/LICENSE) <p align="center">
<img alt="Synapse Admin Logo" src="./public/images/logo.webp" height="140" />
<h3 align="center">
Synapse Admin<br>
<a href="https://matrix.to/#/#synapse-admin:etke.cc">
<img alt="Community room" src="https://img.shields.io/badge/room-community_room-green?logo=matrix&label=%23synapse-admin%3Aetke.cc">
</a><br>
<img alt="License" src="https://img.shields.io/github/license/etkecc/synapse-admin">
</h3>
<p align="center">Manager your Synapse homeserver with ease</p>
</p>
---
![Screenshots](./screenshots.jpg)
This project is built using [react-admin](https://marmelab.com/react-admin/). This project is built using [react-admin](https://marmelab.com/react-admin/).
<!-- vim-markdown-toc GFM -->
* [Fork differences](#fork-differences)
* [Availability](#availability)
* [Changes](#changes)
* [Development](#development)
* [Configuration](#configuration)
* [Restricting available homeserver](#restricting-available-homeserver)
* [Protecting appservice managed users](#protecting-appservice-managed-users)
* [Adding custom menu items](#adding-custom-menu-items)
* [Providing support URL](#providing-support-url)
* [Usage](#usage)
* [Supported Synapse](#supported-synapse)
* [Prerequisites](#prerequisites)
* [Use without install](#use-without-install)
* [Step-By-Step install](#step-by-step-install)
* [Steps for 1)](#steps-for-1)
* [Steps for 2)](#steps-for-2)
* [Steps for 3)](#steps-for-3)
* [Serving Synapse Admin on a different path](#serving-synapse-admin-on-a-different-path)
* [Development](#development-1)
<!-- vim-markdown-toc -->
## Fork differences ## Fork differences
With [Awesome-Technologies/synapse-admin](https://github.com/Awesome-Technologies/synapse-admin) as the upstream, this With [Awesome-Technologies/synapse-admin](https://github.com/Awesome-Technologies/synapse-admin) as the upstream, this
fork is intended to be a more feature-rich version of the original project. The main goal is to provide a more fork is intended to be a more feature-rich version of the original project. The main goal is to provide a more
user-friendly interface for managing Synapse homeservers. user-friendly interface for managing Synapse homeservers.
### Available via CDN ### Availability
On [admin.etke.cc](https://admin.etke.cc) you can find the latest version of this fork. * As a core/default component on [etke.cc](https://etke.cc/?utm_source=github&utm_medium=readme&utm_campaign=synapse-admin)
* Via CDN on [admin.etke.cc](https://admin.etke.cc)
* As a component in [Matrix-Docker-Ansible-Deploy Playbook](https://github.com/spantaleev/matrix-docker-ansible-deploy/blob/master/docs/configuring-playbook-synapse-admin.md)
### Changes ### Changes
@@ -26,14 +66,31 @@ The following changes are already implemented:
* [Fix redirect URL after user creation](https://github.com/etkecc/synapse-admin/pull/16) * [Fix redirect URL after user creation](https://github.com/etkecc/synapse-admin/pull/16)
* [Display actual Synapse errors](https://github.com/etkecc/synapse-admin/pull/17) * [Display actual Synapse errors](https://github.com/etkecc/synapse-admin/pull/17)
* [Fix base_url being undefined on unsuccessful login](https://github.com/etkecc/synapse-admin/pull/18) * [Fix base_url being undefined on unsuccessful login](https://github.com/etkecc/synapse-admin/pull/18)
* [Put the version into manifest.json](https://github.com/Awesome-Technologies/synapse-admin/issues/507) (CI only) * [Put the version into manifest.json](https://github.com/Awesome-Technologies/synapse-admin/issues/507) (later replaced
* [Federation page improvements](https://github.com/Awesome-Technologies/synapse-admin/pull/583) (using theme colors) with a proper manifest.json generation on build)
* [Federation page improvements](https://github.com/Awesome-Technologies/synapse-admin/pull/583) (using icons)
* [Add UI option to block deleted rooms from being rejoined](https://github.com/etkecc/synapse-admin/pull/26) * [Add UI option to block deleted rooms from being rejoined](https://github.com/etkecc/synapse-admin/pull/26)
* [Fix required fields check on Bulk registration CSV upload](https://github.com/etkecc/synapse-admin/pull/32) * [Fix required fields check on Bulk registration CSV upload](https://github.com/etkecc/synapse-admin/pull/32)
* [Fix requests with invalid MXIDs on Bulk registration](https://github.com/etkecc/synapse-admin/pull/33) * [Fix requests with invalid MXIDs on Bulk registration](https://github.com/etkecc/synapse-admin/pull/33)
* [Expose user avatar URL field in the UI](https://github.com/etkecc/synapse-admin/pull/27) * [Expose user avatar URL field in the UI](https://github.com/etkecc/synapse-admin/pull/27)
* [Upgrade react-admin to v5](https://github.com/etkecc/synapse-admin/pull/40) * [Upgrade react-admin to v5](https://github.com/etkecc/synapse-admin/pull/40)
* [Restrict actions on specific users](https://github.com/etkecc/synapse-admin/pull/42) * [Restrict actions on specific users](https://github.com/etkecc/synapse-admin/pull/42)
* [Add `Contact support` menu item](https://github.com/etkecc/synapse-admin/pull/45)
* [Provide options to delete media and redact events on user erase](https://github.com/etkecc/synapse-admin/pull/49)
* [Authenticated Media support](https://github.com/etkecc/synapse-admin/pull/51)
* [Better media preview/download](https://github.com/etkecc/synapse-admin/pull/53)
* [Login with access token](https://github.com/etkecc/synapse-admin/pull/58)
* [Fix footer causing vertical scrollbar](https://github.com/etkecc/synapse-admin/pull/60)
* [Custom Menu Items](https://github.com/etkecc/synapse-admin/pull/79)
* [Add user profile to the top menu](https://github.com/etkecc/synapse-admin/pull/80)
* [Enable visual customization](https://github.com/etkecc/synapse-admin/pull/81)
* [Fix room state events display](https://github.com/etkecc/synapse-admin/pull/100)
* [Sanitize CSV on import](https://github.com/etkecc/synapse-admin/pull/101)
* Allow setting version using `SYNAPSE_ADMIN_VERSION` environment variable on build (if git is not available)
* [Add option to control user's experimental features](https://github.com/etkecc/synapse-admin/pull/111)
* [Add random password generation on user create/edit form](https://github.com/etkecc/synapse-admin/pull/123)
* [Add option to set user's rate limits](https://github.com/etkecc/synapse-admin/pull/125)
* [Support configuration via /.well-known/matrix/client](https://github.com/etkecc/synapse-admin/pull/126)
_the list will be updated as new changes are added_ _the list will be updated as new changes are added_
@@ -48,125 +105,13 @@ After that open `http://localhost:5173` in your browser, login using the followi
* Password: admin * Password: admin
* Homeserver URL: http://localhost:8008 * Homeserver URL: http://localhost:8008
## Usage
### Supported Synapse
It needs at least [Synapse](https://github.com/element-hq/synapse) v1.93.0 for all functions to work as expected!
You get your server version with the request `/_synapse/admin/v1/server_version`.
See also [Synapse version API](https://element-hq.github.io/synapse/latest/admin_api/version_api.html).
After entering the URL on the login page of synapse-admin the server version appears below the input field.
### Prerequisites
You need access to the following endpoints:
- `/_matrix`
- `/_synapse/admin`
See also [Synapse administration endpoints](https://element-hq.github.io/synapse/latest/reverse_proxy.html#synapse-administration-endpoints)
### Use without install
You can use the current version of Synapse Admin without own installation direct
via [GitHub Pages](https://awesome-technologies.github.io/synapse-admin/).
**Note:**
If you want to use the deployment, you have to make sure that the admin endpoints (`/_synapse/admin`) are accessible for your browser.
**Remember: You have no need to expose these endpoints to the internet but to your network.**
If you want your own deployment, follow the [Step-By-Step Install Guide](#step-by-step-install) below.
### Step-By-Step install
You have three options:
1. [Download the tarball and serve with any webserver](#steps-for-1)
2. [Download the source code from github and run using nodejs](#steps-for-2)
3. [Run the Docker container](#steps-for-3)
#### Steps for 1)
- make sure you have a webserver installed that can serve static files (any webserver like nginx or apache will do)
- configure a vhost for synapse admin on your webserver
- download the .tar.gz from the latest release: https://github.com/Awesome-Technologies/synapse-admin/releases/latest
- unpack the .tar.gz
- move or symlink the `synapse-admin-x.x.x` into your vhosts root dir
- open the url of the vhost in your browser
#### Steps for 2)
- make sure you have installed the following: git, yarn, nodejs
- download the source code: `git clone https://github.com/Awesome-Technologies/synapse-admin.git`
- change into downloaded directory: `cd synapse-admin`
- download dependencies: `yarn install`
- start web server: `yarn start`
#### Steps for 3)
- run the Docker container from the public docker registry: `docker run -p 8080:80 awesometechnologies/synapse-admin` or use the [docker-compose.yml](docker-compose.yml): `docker-compose up -d`
> note: if you're building on an architecture other than amd64 (for example a raspberry pi), make sure to define a maximum ram for node. otherwise the build will fail.
```yml
services:
synapse-admin:
container_name: synapse-admin
hostname: synapse-admin
build:
context: https://github.com/Awesome-Technologies/synapse-admin.git
args:
- BUILDKIT_CONTEXT_KEEP_GIT_DIR=1
# - NODE_OPTIONS="--max_old_space_size=1024"
# - BASE_PATH="/synapse-admin"
ports:
- "8080:80"
restart: unless-stopped
```
- browse to http://localhost:8080
### Serving Synapse-Admin on a different path
The path prefix where synapse-admin is served can only be changed during the build step.
If you downloaded the source code, use `yarn build --base=/my-prefix` to set a path prefix.
If you want to build your own Docker container, use the `BASE_PATH` argument.
We do not support directly changing the path where Synapse-Admin is served in the pre-built Docker container. Instead please use a reverse proxy if you need to move Synapse-Admin to a different base path. If you want to serve multiple applications with different paths on the same domain, you need a reverse proxy anyway.
Example for Traefik:
`docker-compose.yml`
```yml
services:
traefik:
image: traefik:mimolette
restart: unless-stopped
ports:
- 80:80
- 443:443
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
synapse-admin:
image: awesometechnologies/synapse-admin:latest
restart: unless-stopped
labels:
- "traefik.enable=true"
- "traefik.http.routers.synapse-admin.rule=Host(`example.com`)&&PathPrefix(`/admin`)"
- "traefik.http.routers.synapse-admin.middlewares=admin,admin_path"
- "traefik.http.middlewares.admin.redirectregex.regex=^(.*)/admin/?"
- "traefik.http.middlewares.admin.redirectregex.replacement=$${1}/admin/"
- "traefik.http.middlewares.admin_path.stripprefix.prefixes=/admin"
```
## Configuration ## Configuration
You can use `config.json` file to configure synapse-admin You can use `config.json` file to configure Synapse Admin instance,
and `/.well-known/matrix/client` file to provide Synapse Admin configuration specifically for your homeserver.
In the latter case, any instance of Synapse Admin will automatically pick up the configuration from the homeserver.
Note that configuration inside the `/.well-known/matrix/client` file should go under the `cc.etke.synapse-admin` key,
and it will override the configuration from the `config.json` file.
The `config.json` can be injected into a Docker container using a bind mount. The `config.json` can be injected into a Docker container using a bind mount.
@@ -191,6 +136,16 @@ Edit `config.json` to restrict either to a single homeserver:
} }
``` ```
similar for `/.well-known/matrix/client`:
```json
{
"cc.etke.synapse-admin": {
"restrictBaseUrl": "https://your-matrixs-erver.example.com"
}
}
```
or to a list of homeservers: or to a list of homeservers:
```json ```json
@@ -199,6 +154,16 @@ or to a list of homeservers:
} }
``` ```
similar for `/.well-known/matrix/client`:
```json
{
"cc.etke.synapse-admin": {
"restrictBaseUrl": ["https://your-first-matrix-server.example.com", "https://your-second-matrix-server.example.com"]
}
}
```
### Protecting appservice managed users ### Protecting appservice managed users
To avoid accidental adjustments of appservice-managed users (e.g., puppets created by a bridge) and breaking the bridge, To avoid accidental adjustments of appservice-managed users (e.g., puppets created by a bridge) and breaking the bridge,
@@ -212,9 +177,187 @@ Example for [mautrix-telegram](https://github.com/mautrix/telegram)
} }
``` ```
## Screenshots similar for `/.well-known/matrix/client`:
![Screenshots](./screenshots.jpg) ```json
{
"cc.etke.synapse-admin": {
"asManagedUsers": ["^@telegram_[a-zA-Z0-9]+:example\\.com$"]
}
}
```
### Adding custom menu items
You can add custom menu items to the main menu by providing a `menu` array in the `config.json`.
```json
{
"menu": [
{
"label": "Contact support",
"icon": "SupportAgent",
"url": "https://github.com/etkecc/synapse-admin/issues"
}
]
}
```
similar for `/.well-known/matrix/client`:
```json
{
"cc.etke.synapse-admin": {
"menu": [
{
"label": "Contact support",
"icon": "SupportAgent",
"url": "https://github.com/etkecc/synapse-admin/issues"
}
]
}
}
```
Where `icon` is one of the [preloaded icons](./src/components/icons.ts)
### Providing support URL
**Deprecated**: use `menu` config option described above. Automatically migrated to the `menu` if the `supportURL` is present.
~~Synapse Admin provides a support link in the main menu - `Contact support`. By default, the link points to the GitHub issues page of the project. You can change this link by providing a `supportURL` in the `config.json`.~~
```json
{
"supportURL": "https://example.com/support"
}
```
similar for `/.well-known/matrix/client`:
```json
{
"cc.etke.synapse-admin": {
"supportURL": "https://example.com/support"
}
}
```
## Usage
### Supported Synapse
It needs at least [Synapse](https://github.com/element-hq/synapse) v1.116.0 for all functions to work as expected!
You get your server version with the request `/_synapse/admin/v1/server_version`.
See also [Synapse version API](https://element-hq.github.io/synapse/latest/admin_api/version_api.html).
After entering the URL on the login page of synapse-admin the server version appears below the input field.
### Prerequisites
You need access to the following endpoints:
- `/_matrix`
- `/_synapse/admin`
See also [Synapse administration endpoints](https://element-hq.github.io/synapse/latest/reverse_proxy.html#synapse-administration-endpoints)
### Use without install
You can use the current version of Synapse Admin without own installation direct
via [admin.etke.cc](https://admin.etke.cc).
**Note:**
If you want to use the deployment, you have to make sure that the admin endpoints (`/_synapse/admin`) are accessible for your browser.
**Remember: You have no need to expose these endpoints to the internet but to your network.**
If you want your own deployment, follow the [Step-By-Step Install Guide](#step-by-step-install) below.
### Step-By-Step install
You have three options:
1. [Download the tarball and serve with any webserver](#steps-for-1)
2. [Download the source code from github and run using nodejs](#steps-for-2)
3. [Run the Docker container](#steps-for-3)
#### Steps for 1)
- make sure you have a webserver installed that can serve static files (any webserver like nginx or apache will do)
- configure a vhost for synapse admin on your webserver
- download the .tar.gz [from the latest release](https://github.com/etkecc/synapse-admin/releases/latest)
- unpack the .tar.gz
- move or symlink the `synapse-admin` into your vhosts root dir
- open the url of the vhost in your browser
#### Steps for 2)
- make sure you have installed the following: git, yarn, nodejs
- download the source code: `git clone https://github.com/etkecc/synapse-admin.git`
- change into downloaded directory: `cd synapse-admin`
- download dependencies: `yarn install`
- start web server: `yarn start`
#### Steps for 3)
- run the Docker container from the public docker registry: `docker run -p 8080:80 ghcr.io/etkecc/synapse-admin` or use the [docker-compose.yml](docker-compose.yml): `docker-compose up -d`
> note: if you're building on an architecture other than amd64 (for example a raspberry pi), make sure to define a maximum ram for node. otherwise the build will fail.
```yml
services:
synapse-admin:
container_name: synapse-admin
hostname: synapse-admin
build:
context: https://github.com/etkecc/synapse-admin.git
args:
- BUILDKIT_CONTEXT_KEEP_GIT_DIR=1
# - NODE_OPTIONS="--max_old_space_size=1024"
# - BASE_PATH="/synapse-admin"
ports:
- "8080:80"
restart: unless-stopped
```
- browse to http://localhost:8080
### Serving Synapse Admin on a different path
The path prefix where synapse-admin is served can only be changed during the build step.
If you downloaded the source code, use `yarn build --base=/my-prefix` to set a path prefix.
If you want to build your own Docker container, use the `BASE_PATH` argument.
We do not support directly changing the path where Synapse Admin is served in the pre-built Docker container. Instead please use a reverse proxy if you need to move Synapse Admin to a different base path. If you want to serve multiple applications with different paths on the same domain, you need a reverse proxy anyway.
Example for Traefik:
`docker-compose.yml`
```yml
services:
traefik:
image: traefik:mimolette
restart: unless-stopped
ports:
- 80:80
- 443:443
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
synapse-admin:
image: etkecc/synapse-admin:latest
restart: unless-stopped
labels:
- "traefik.enable=true"
- "traefik.http.routers.synapse-admin.rule=Host(`example.com`)&&PathPrefix(`/admin`)"
- "traefik.http.routers.synapse-admin.middlewares=admin,admin_path"
- "traefik.http.middlewares.admin.redirectregex.regex=^(.*)/admin/?"
- "traefik.http.middlewares.admin.redirectregex.replacement=$${1}/admin/"
- "traefik.http.middlewares.admin_path.stripprefix.prefixes=/admin"
```
## Development ## Development

View File

@@ -4,17 +4,14 @@
<meta charset="utf-8" /> <meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" /> <meta name="theme-color" content="#000000" />
<meta <meta name="description" content="Synapse Admin" />
name="description"
content="Synapse-Admin"
/>
<!-- <!--
manifest.json provides metadata used when your web app is installed on a manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/ user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
--> -->
<link rel="manifest" href="./manifest.json" /> <link rel="manifest" href="./manifest.json" />
<link rel="shortcut icon" href="./favicon.ico" /> <link rel="shortcut icon" href="./favicon.ico" />
<title>Synapse-Admin</title> <title>Synapse Admin</title>
<style> <style>
body { body {
margin: 0; margin: 0;
@@ -22,6 +19,11 @@
font-family: sans-serif; font-family: sans-serif;
} }
.layout {
min-height: 90vh !important;
height: 90vh;
}
.loader-container { .loader-container {
display: flex; display: flex;
align-items: center; align-items: center;
@@ -120,13 +122,7 @@
</div> </div>
</div> </div>
<script type="module" src="/src/index.tsx"></script> <script type="module" src="/src/index.tsx"></script>
<footer <span id="js-version" style="display: none;"></span>
style="position: relative; z-index: 2; height: 2em; margin-top: 0; line-height: 2em; background-color: #eee; border: 0.5px solid #ddd">
<a id="copyright" href="https://github.com/etkecc/synapse-admin"
style="margin-left: 1em; color: #888; font-family: Roboto, Helvetica, Arial, sans-serif; font-weight: 100; font-size: 0.8em; text-decoration: none;">
Synapse-Admin <b><span id="version"></span></b> by Awesome Technologies Innovationslabor GmbH
</a>
</footer>
</body> </body>
<script>document.getElementById("version").textContent = __SYNAPSE_ADMIN_VERSION__</script> <script>document.getElementById("js-version").textContent = __SYNAPSE_ADMIN_VERSION__</script>
</html> </html>

View File

@@ -25,11 +25,15 @@ run-dev:
stop-dev: stop-dev:
@docker-compose -f docker-compose-dev.yml stop @docker-compose -f docker-compose-dev.yml stop
# register a user in the dev stack
register-user localpart password *admin: register-user localpart password *admin:
docker-compose exec synapse register_new_matrix_user {{ if admin == "1" {"--admin"} else {"--no-admin"} }} -u {{ localpart }} -p {{ password }} -c /config/homeserver.yaml http://localhost:8008 docker-compose exec synapse register_new_matrix_user {{ if admin == "1" {"--admin"} else {"--no-admin"} }} -u {{ localpart }} -p {{ password }} -c /config/homeserver.yaml http://localhost:8008
# run yarn {fix,lint,test} commands
test:
@-yarn run fix
@-yarn run lint
@-yarn run test
# run the app in a production mode # run the app in a production mode
run-prod: build run-prod: build

View File

@@ -3,7 +3,7 @@
"version": "0.10.3", "version": "0.10.3",
"description": "Admin GUI for the Matrix.org server Synapse", "description": "Admin GUI for the Matrix.org server Synapse",
"type": "module", "type": "module",
"author": "Awesome Technologies Innovationslabor GmbH", "author": "etke.cc (originally by Awesome Technologies Innovationslabor GmbH)",
"license": "Apache-2.0", "license": "Apache-2.0",
"homepage": ".", "homepage": ".",
"repository": { "repository": {
@@ -11,25 +11,25 @@
"url": "https://github.com/etkecc/synapse-admin" "url": "https://github.com/etkecc/synapse-admin"
}, },
"devDependencies": { "devDependencies": {
"@eslint/js": "^9.7.0", "@eslint/js": "^9.13.0",
"@testing-library/dom": "^10.0.0", "@testing-library/dom": "^10.0.0",
"@testing-library/jest-dom": "^6.0.0", "@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.0.0", "@testing-library/react": "^16.0.0",
"@testing-library/user-event": "^14.5.2", "@testing-library/user-event": "^14.5.2",
"@types/jest": "^29.5.13", "@types/jest": "^29.5.14",
"@types/lodash": "^4.17.7", "@types/lodash": "^4.17.13",
"@types/node": "^20.14.12", "@types/node": "^22.8.7",
"@types/papaparse": "^5.3.14", "@types/papaparse": "^5.3.15",
"@types/react": "^18.3.3", "@types/react": "^18.3.12",
"@typescript-eslint/eslint-plugin": "^7.16.1", "@typescript-eslint/eslint-plugin": "^8.11.0",
"@typescript-eslint/parser": "^7.16.1", "@typescript-eslint/parser": "^8.11.0",
"@vitejs/plugin-react": "^4.3.1", "@vitejs/plugin-react": "^4.3.3",
"eslint": "^8.57.0", "eslint": "^9.13.0",
"eslint-config-prettier": "^9.1.0", "eslint-config-prettier": "^9.1.0",
"eslint-plugin-import": "^2.29.1", "eslint-plugin-import": "^2.31.0",
"eslint-plugin-jsx-a11y": "^6.9.0", "eslint-plugin-jsx-a11y": "^6.10.2",
"eslint-plugin-prettier": "^5.2.1", "eslint-plugin-prettier": "^5.2.1",
"eslint-plugin-unused-imports": "^3.2.0", "eslint-plugin-unused-imports": "^4.1.4",
"eslint-plugin-yaml": "^1.0.3", "eslint-plugin-yaml": "^1.0.3",
"jest": "^29.7.0", "jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0", "jest-environment-jsdom": "^29.7.0",
@@ -38,41 +38,42 @@
"react-test-renderer": "^18.3.1", "react-test-renderer": "^18.3.1",
"ts-jest": "^29.2.5", "ts-jest": "^29.2.5",
"ts-node": "^10.9.2", "ts-node": "^10.9.2",
"typescript": "^5.4.5", "typescript": "^5.6.3",
"typescript-eslint": "^7.16.1", "typescript-eslint": "^8.12.2",
"vite": "^5.4.6", "vite": "^5.4.10",
"vite-plugin-version-mark": "^0.1.0" "vite-plugin-version-mark": "^0.1.2"
}, },
"dependencies": { "dependencies": {
"@emotion/react": "^11.13.0", "@emotion/react": "^11.13.0",
"@emotion/styled": "^11.13.0", "@emotion/styled": "^11.13.0",
"@haleos/ra-language-german": "^1.0.0", "@haleos/ra-language-german": "^1.0.0",
"@haxqer/ra-language-chinese": "^4.16.2", "@haxqer/ra-language-chinese": "^4.16.2",
"@mui/icons-material": "^6.1.1", "@mui/icons-material": "^6.1.5",
"@mui/material": "^6.1.1", "@mui/material": "^6.1.6",
"@tanstack/react-query": "^5.56.2", "@mui/utils": "^5.16.6",
"@tanstack/react-query": "^5.59.19",
"history": "^5.3.0", "history": "^5.3.0",
"lodash": "^4.17.21", "lodash": "^4.17.21",
"papaparse": "^5.4.1", "papaparse": "^5.4.1",
"ra-core": "^5.2.0", "ra-core": "^5.3.2",
"ra-i18n-polyglot": "^5.2.0", "ra-i18n-polyglot": "^5.3.2",
"ra-language-english": "^5.2.0", "ra-language-english": "^5.3.2",
"ra-language-farsi": "^5.0.0", "ra-language-farsi": "^5.0.0",
"ra-language-french": "^5.2.0", "ra-language-french": "^5.3.1",
"ra-language-italian": "^3.13.1", "ra-language-italian": "^3.13.1",
"ra-language-russian": "^4.14.2", "ra-language-russian": "^4.14.2",
"react": "^18.3.1", "react": "^18.3.1",
"react-admin": "^5.2.0", "react-admin": "^5.3.1",
"react-dom": "^18.3.1", "react-dom": "^18.3.1",
"react-hook-form": "^7.53.0", "react-hook-form": "^7.53.1",
"react-is": "^18.3.1", "react-is": "^18.3.1",
"react-router": "^6.26.2", "react-router": "^6.26.2",
"react-router-dom": "^6.26.2" "react-router-dom": "^6.27.0"
}, },
"scripts": { "scripts": {
"start": "vite serve", "start": "vite serve",
"build": "vite build", "build": "vite build",
"lint": "eslint --ignore-path .gitignore --ext .ts,.tsx,.yml,.yaml .", "lint": "ESLINT_USE_FLAT_CONFIG=false eslint --ignore-path .gitignore --ignore-pattern testdata/ --ext .ts,.tsx,.yml,.yaml .",
"fix": "yarn lint --fix", "fix": "yarn lint --fix",
"test": "yarn jest", "test": "yarn jest",
"test:watch": "yarn jest --watch" "test:watch": "yarn jest --watch"

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

After

Width:  |  Height:  |  Size: 4.2 KiB

BIN
public/images/logo.webp Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

View File

@@ -1,15 +0,0 @@
{
"short_name": "Synapse-Admin",
"name": "Synapse-Admin",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

View File

@@ -1,4 +1,4 @@
import { render, screen, waitFor } from "@testing-library/react"; import { render, screen } from "@testing-library/react";
import fetchMock from "jest-fetch-mock"; import fetchMock from "jest-fetch-mock";
fetchMock.enableMocks(); fetchMock.enableMocks();

View File

@@ -4,6 +4,7 @@ import polyglotI18nProvider from "ra-i18n-polyglot";
import { Admin, CustomRoutes, Resource, resolveBrowserLocale } from "react-admin"; import { Admin, CustomRoutes, Resource, resolveBrowserLocale } from "react-admin";
import { Route } from "react-router-dom"; import { Route } from "react-router-dom";
import { AdminLayout } from "./components/AdminLayout";
import { ImportFeature } from "./components/ImportFeature"; import { ImportFeature } from "./components/ImportFeature";
import germanMessages from "./i18n/de"; import germanMessages from "./i18n/de";
import englishMessages from "./i18n/en"; import englishMessages from "./i18n/en";
@@ -21,6 +22,8 @@ import userMediaStats from "./resources/user_media_statistics";
import users from "./resources/users"; import users from "./resources/users";
import authProvider from "./synapse/authProvider"; import authProvider from "./synapse/authProvider";
import dataProvider from "./synapse/dataProvider"; import dataProvider from "./synapse/dataProvider";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import Footer from "./components/Footer";
// TODO: Can we use lazy loading together with browser locale? // TODO: Can we use lazy loading together with browser locale?
const messages = { const messages = {
@@ -45,36 +48,42 @@ const i18nProvider = polyglotI18nProvider(
] ]
); );
const queryClient = new QueryClient();
const App = () => ( const App = () => (
<Admin <QueryClientProvider client={queryClient}>
disableTelemetry <Admin
requireAuth disableTelemetry
loginPage={LoginPage} requireAuth
authProvider={authProvider} layout={AdminLayout}
dataProvider={dataProvider} loginPage={LoginPage}
i18nProvider={i18nProvider} authProvider={authProvider}
> dataProvider={dataProvider}
<CustomRoutes> i18nProvider={i18nProvider}
<Route path="/import_users" element={<ImportFeature />} /> >
</CustomRoutes> <CustomRoutes>
<Resource {...users} /> <Route path="/import_users" element={<ImportFeature />} />
<Resource {...rooms} /> </CustomRoutes>
<Resource {...userMediaStats} /> <Resource {...users} />
<Resource {...reports} /> <Resource {...rooms} />
<Resource {...roomDirectory} /> <Resource {...userMediaStats} />
<Resource {...destinations} /> <Resource {...reports} />
<Resource {...registrationToken} /> <Resource {...roomDirectory} />
<Resource name="connections" /> <Resource {...destinations} />
<Resource name="devices" /> <Resource {...registrationToken} />
<Resource name="room_members" /> <Resource name="connections" />
<Resource name="users_media" /> <Resource name="devices" />
<Resource name="joined_rooms" /> <Resource name="room_members" />
<Resource name="pushers" /> <Resource name="users_media" />
<Resource name="servernotices" /> <Resource name="joined_rooms" />
<Resource name="forward_extremities" /> <Resource name="pushers" />
<Resource name="room_state" /> <Resource name="servernotices" />
<Resource name="destination_rooms" /> <Resource name="forward_extremities" />
</Admin> <Resource name="room_state" />
<Resource name="destination_rooms" />
</Admin>
<Footer />
</QueryClientProvider>
); );
export default App; export default App;

View File

@@ -1,10 +1,6 @@
import { createContext, useContext } from "react"; import { createContext, useContext } from "react";
import { Config } from "./components/config";
interface AppContextType {
restrictBaseUrl: string | string[];
asManagedUsers: string[];
}
export const AppContext = createContext({}); export const AppContext = createContext({});
export const useAppContext = () => useContext(AppContext) as AppContextType; export const useAppContext = () => useContext(AppContext) as Config;

View File

@@ -0,0 +1,103 @@
import { AppBar, TitlePortal, InspectorButton, Confirm, Layout, Logout, Menu, useLogout, UserMenu } from "react-admin";
import { LoginMethod } from "../pages/LoginPage";
import { useEffect, useState, Suspense } from "react";
import { Icons, DefaultIcon } from "./icons";
import { ClearConfig } from "./config";
const AdminUserMenu = () => {
const [open, setOpen] = useState(false);
const logout = useLogout();
const checkLoginType = (ev: React.MouseEvent<HTMLDivElement>) => {
const loginType: LoginMethod = (localStorage.getItem("login_type") || "credentials") as LoginMethod;
if (loginType === "accessToken") {
ev.stopPropagation();
setOpen(true);
}
};
const handleConfirm = () => {
setOpen(false);
logout();
};
const handleDialogClose = () => {
setOpen(false);
ClearConfig();
window.location.reload();
};
return (
<UserMenu>
<div onClickCapture={checkLoginType}>
<Logout />
</div>
<Confirm
isOpen={open}
title="synapseadmin.auth.logout_acces_token_dialog.title"
content="synapseadmin.auth.logout_acces_token_dialog.content"
onConfirm={handleConfirm}
onClose={handleDialogClose}
confirm="synapseadmin.auth.logout_acces_token_dialog.confirm"
cancel="synapseadmin.auth.logout_acces_token_dialog.cancel"
/>
</UserMenu>
);
};
const AdminAppBar = () => {
return (<AppBar userMenu={<AdminUserMenu />}>
<TitlePortal />
<InspectorButton />
</AppBar>);
};
const AdminMenu = (props) => {
const [menu, setMenu] = useState([]);
useEffect(() => {
const menuConfig = localStorage.getItem('menu');
if (menuConfig) {
try {
setMenu(JSON.parse(menuConfig));
} catch (e) {
console.error('Error parsing menu configuration', e);
}
}
}, []);
return (
<Menu {...props}>
<Menu.ResourceItems />
{menu.map((item, index) => {
const { url, icon, label } = item;
const IconComponent = Icons[icon] as React.ComponentType<any> | undefined;
return (
<Suspense key={index}>
<Menu.Item
to={url}
target="_blank"
primaryText={label}
leftIcon={IconComponent ? <IconComponent /> : <DefaultIcon />}
onClick={props.onMenuClick}
/>
</Suspense>
);
})}
</Menu>
);
};
export const AdminLayout = ({ children }) => (
<Layout appBar={AdminAppBar} menu={AdminMenu} sx={{
['& .RaLayout-appFrame']: {
minHeight: '90vh',
height: '90vh',
},
['& .RaLayout-content']: {
marginBottom: '3rem',
},
}}>
{children}
</Layout>
);

View File

@@ -1,18 +1,43 @@
import { render, screen } from "@testing-library/react"; import { render, screen, waitFor } from "@testing-library/react";
import { RecordContextProvider } from "react-admin"; import { RecordContextProvider } from "react-admin";
import { act } from "react";
import AvatarField from "./AvatarField"; import AvatarField from "./AvatarField";
describe("AvatarField", () => { describe("AvatarField", () => {
it("shows image", () => { beforeEach(() => {
// Mock fetch
global.fetch = jest.fn(() =>
Promise.resolve({
blob: () => Promise.resolve(new Blob(["mock image data"], { type: 'image/jpeg' })),
})
) as jest.Mock;
// Mock URL.createObjectURL
global.URL.createObjectURL = jest.fn(() => "mock-object-url");
});
afterEach(() => {
jest.restoreAllMocks();
});
it.only("shows image", async () => {
const value = { const value = {
avatar: "foo", avatar: "mxc://serverName/mediaId",
}; };
render(
<RecordContextProvider value={value}> await act(async () => {
<AvatarField source="avatar" /> render(
</RecordContextProvider> <RecordContextProvider value={value}>
); <AvatarField source="avatar" />
expect(screen.getByRole("img").getAttribute("src")).toBe("foo"); </RecordContextProvider>
);
});
await waitFor(() => {
const img = screen.getByRole("img");
expect(img.getAttribute("src")).toBe("mock-object-url");
});
expect(global.fetch).toHaveBeenCalled();
}); });
}); });

View File

@@ -1,12 +1,36 @@
import { get } from "lodash"; import { get } from "lodash";
import { Avatar, AvatarProps } from "@mui/material";
import { FieldProps, useRecordContext } from "react-admin";
import { useState, useEffect, useCallback } from "react";
import { fetchAuthenticatedMedia } from "../utils/fetchMedia";
import { Avatar } from "@mui/material"; const AvatarField = ({ source, ...rest }: AvatarProps & FieldProps) => {
import { useRecordContext } from "react-admin";
const AvatarField = ({ source, ...rest }) => {
const record = useRecordContext(rest);
const src = get(record, source)?.toString();
const { alt, classes, sizes, sx, variant } = rest; const { alt, classes, sizes, sx, variant } = rest;
const record = useRecordContext(rest);
const mxcURL = get(record, source)?.toString();
const [src, setSrc] = useState<string>("");
const fetchAvatar = useCallback(async (mxcURL: string) => {
const response = await fetchAuthenticatedMedia(mxcURL, "thumbnail");
const blob = await response.blob();
const blobURL = URL.createObjectURL(blob);
setSrc(blobURL);
}, []);
useEffect(() => {
if (mxcURL) {
fetchAvatar(mxcURL);
}
// Cleanup function to revoke the object URL
return () => {
if (src) {
URL.revokeObjectURL(src);
}
};
}, [mxcURL, fetchAvatar]);
return <Avatar alt={alt} classes={classes} sizes={sizes} src={src} sx={sx} variant={variant} />; return <Avatar alt={alt} classes={classes} sizes={sizes} src={src} sx={sx} variant={variant} />;
}; };

View File

@@ -16,7 +16,7 @@ const resourceName = "rooms";
const DeleteRoomButton: React.FC<DeleteRoomButtonProps> = (props) => { const DeleteRoomButton: React.FC<DeleteRoomButtonProps> = (props) => {
const translate = useTranslate(); const translate = useTranslate();
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [block, setBlock] = useState(true); const [block, setBlock] = useState(false);
const notify = useNotify(); const notify = useNotify();
const redirect = useRedirect(); const redirect = useRedirect();
@@ -78,7 +78,7 @@ const DeleteRoomButton: React.FC<DeleteRoomButtonProps> = (props) => {
value={block} value={block}
onChange={(event: React.ChangeEvent<HTMLInputElement>) => setBlock(event.target.checked)} onChange={(event: React.ChangeEvent<HTMLInputElement>) => setBlock(event.target.checked)}
label="resources.rooms.action.erase.fields.block" label="resources.rooms.action.erase.fields.block"
defaultValue={true} defaultValue={false}
/> />
</SimpleForm> </SimpleForm>
</DialogContent> </DialogContent>

View File

@@ -0,0 +1,117 @@
import { Button, Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle } from "@mui/material";
import { Fragment, useState } from "react";
import { SimpleForm, BooleanInput, useTranslate, RaRecord, useNotify, useRedirect, useDelete, NotificationType, useDeleteMany, Identifier, useUnselectAll } from "react-admin";
import ActionDelete from "@mui/icons-material/Delete";
import ActionCheck from "@mui/icons-material/CheckCircle";
import AlertError from "@mui/icons-material/ErrorOutline";
interface DeleteUserButtonProps {
selectedIds: Identifier[];
confirmTitle: string;
confirmContent: string;
}
const resourceName = "users";
const DeleteUserButton: React.FC<DeleteUserButtonProps> = (props) => {
const translate = useTranslate();
const [open, setOpen] = useState(false);
const [deleteMedia, setDeleteMedia] = useState(false);
const [redactEvents, setRedactEvents] = useState(false);
const notify = useNotify();
const redirect = useRedirect();
const [deleteMany, { isLoading }] = useDeleteMany();
const unselectAll = useUnselectAll(resourceName);
const recordIds = props.selectedIds;
const handleDialogOpen = () => setOpen(true);
const handleDialogClose = () => setOpen(false);
const handleDelete = (values: {deleteMedia: boolean, redactEvents: boolean}) => {
deleteMany(
resourceName,
{ ids: recordIds, meta: values },
{
onSuccess: () => {
notify("ra.notification.deleted", {
messageArgs: {
smart_count: recordIds.length,
},
type: 'info' as NotificationType,
});
handleDialogClose();
unselectAll();
redirect("/users");
},
onError: (error) =>
notify("ra.notification.data_provider_error", { type: 'error' as NotificationType }),
}
);
};
const handleConfirm = () => {
setOpen(false);
handleDelete({ deleteMedia: deleteMedia, redactEvents: redactEvents });
};
return (
<Fragment>
<Button
onClick={handleDialogOpen}
disabled={isLoading}
className={"ra-delete-button"}
key="button"
size="small"
sx={{
"&.MuiButton-sizeSmall": {
lineHeight: 1.5,
},
}}
color={"error"}
startIcon={<ActionDelete />}
>
{translate("ra.action.delete")}
</Button>
<Dialog open={open} onClose={handleDialogClose}>
<DialogTitle>{translate(props.confirmTitle)}</DialogTitle>
<DialogContent>
<DialogContentText>{translate(props.confirmContent)}</DialogContentText>
<SimpleForm toolbar={false}>
<BooleanInput
source="deleteMedia"
value={deleteMedia}
onChange={(event: React.ChangeEvent<HTMLInputElement>) => setDeleteMedia(event.target.checked)}
label="resources.users.action.delete_media"
defaultValue={false}
/>
<BooleanInput
source="redactEvents"
value={redactEvents}
onChange={(event: React.ChangeEvent<HTMLInputElement>) => setRedactEvents(event.target.checked)}
label="resources.users.action.redact_events"
defaultValue={false}
/>
</SimpleForm>
</DialogContent>
<DialogActions>
<Button disabled={false} onClick={handleDialogClose} startIcon={<AlertError />}>
{translate("ra.action.cancel")}
</Button>
<Button
disabled={false}
onClick={handleConfirm}
className={"ra-confirm RaConfirm-confirmPrimary"}
autoFocus
startIcon={<ActionCheck />}
>
{translate("ra.action.confirm")}
</Button>
</DialogActions>
</Dialog>
</Fragment>
);
};
export default DeleteUserButton;

View File

@@ -0,0 +1,95 @@
import { useRecordContext } from "react-admin";
import { useNotify } from "react-admin";
import { useDataProvider } from "react-admin";
import { useState, useEffect } from "react";
import { Stack, Switch, Typography } from "@mui/material";
import { ExperimentalFeaturesModel, SynapseDataProvider } from "../synapse/dataProvider";
const experimentalFeaturesMap = {
msc3881: "enable remotely toggling push notifications for another client",
msc3575: "enable experimental sliding sync support",
};
const ExperimentalFeatureRow = (props: { featureKey: string, featureValue: boolean, updateFeature: (feature_name: string, feature_value: boolean) => void}) => {
const featureKey = props.featureKey;
const featureValue = props.featureValue;
const featureDescription = experimentalFeaturesMap[featureKey] ?? "";
const [checked, setChecked] = useState(featureValue);
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setChecked(event.target.checked);
props.updateFeature(featureKey, event.target.checked);
};
return <Stack
direction="row"
spacing={2}
alignItems="start"
sx={{
padding: 2,
}}
>
<Switch checked={checked} onChange={handleChange} />
<Stack>
<Typography
variant="subtitle1"
sx={{
fontWeight: "medium",
color: "text.primary"
}}
>
{featureKey}
</Typography>
<Typography
variant="body2"
color="text.secondary"
>
{featureDescription}
</Typography>
</Stack>
</Stack>
}
export const ExperimentalFeaturesList = () => {
const record = useRecordContext();
const notify = useNotify();
const dataProvider = useDataProvider() as SynapseDataProvider;
const [features, setFeatures] = useState({});
if (!record) {
return null;
}
useEffect(() => {
const fetchFeatures = async () => {
const features = await dataProvider.getFeatures(record.id);
setFeatures(features);
}
fetchFeatures();
}, []);
const updateFeature = async (feature_name: string, feature_value: boolean) => {
const updatedFeatures = {...features, [feature_name]: feature_value} as ExperimentalFeaturesModel;
setFeatures(updatedFeatures);
const reponse = await dataProvider.updateFeatures(record.id, updatedFeatures);
notify("ra.notification.updated", {
messageArgs: { smart_count: 1 },
type: "success",
});
};
return <>
<Stack
direction="column"
spacing={1}
>
{Object.keys(features).map((featureKey: string) =>
<ExperimentalFeatureRow
key={featureKey}
featureKey={featureKey}
featureValue={features[featureKey]}
updateFeature={updateFeature}
/>
)}
</Stack>
</>
}

41
src/components/Footer.tsx Normal file
View File

@@ -0,0 +1,41 @@
import { Avatar, Box, Link, Typography } from "@mui/material";
import { useEffect, useState } from "react";
const Footer = () => {
const [version, setVersion] = useState<string | null>(null);
useEffect(() => {
const version = document.getElementById("js-version")?.textContent;
if (version) {
setVersion(version);
}
}, []);
return (<Box
component="footer"
sx={{
position: 'fixed',
zIndex: 100,
bottom: 0,
width: '100%',
bgcolor: "#eee",
borderTop: '1px solid',
borderColor: '#ddd',
p: 1,
}}>
<Typography variant="body2" component="div">
<Avatar src="./images/logo.webp" sx={{ width: "1rem", height: "1rem", display: "inline-block", verticalAlign: "sub" }} />
<Link sx={{ color: "#888", textDecoration: 'none' }} href="https://github.com/etkecc/synapse-admin" target="_blank">
Synapse Admin
</Link> <Link href={`https://github.com/etkecc/synapse-admin/releases/tag/`+version} target="_blank">
<span style={{ fontWeight: 'bold', color: "#000" }}>{version}</span>
</Link> <Link sx={{ color: "#888", textDecoration: 'none' }} href="https://etke.cc/?utm_source=synapse-admin&utm_medium=footer&utm_campaign=synapse-admin" target="_blank">
by etke.cc
</Link> <Link sx={{ color: "#888", textDecoration: 'none' }} href="https://github.com/awesome-technologies/synapse-admin" target="_blank">
(originally developed by Awesome Technologies Innovationslabor GmbH).
</Link> <Link sx={{ fontWeight: 'bold', color: "#000", textDecoration: 'none' }} href="https://matrix.to/#/#synapse-admin:etke.cc" target="_blank">#synapse-admin:etke.cc</Link>
</Typography>
</Box>
);
};
export default Footer;

View File

@@ -121,11 +121,8 @@ const FilePicker = () => {
const verifyCsv = ({ data, meta, errors }: ParseResult<ImportLine>, { setValues, setStats, setError }) => { const verifyCsv = ({ data, meta, errors }: ParseResult<ImportLine>, { setValues, setStats, setError }) => {
/* First, verify the presence of required fields */ /* First, verify the presence of required fields */
const missingFields = expectedFields.filter(eF => { meta.fields = meta.fields?.map(f => f.trim().toLowerCase());
const result = meta.fields?.find(mF => eF === mF); const missingFields = expectedFields.filter(eF => !meta.fields?.find(mF => eF === mF));
if (result === undefined) { return eF; } // missing field
return undefined; // field found
});
if (missingFields.length > 0) { if (missingFields.length > 0) {
setError(translate("import_users.error.required_field", { field: missingFields[0] })); setError(translate("import_users.error.required_field", { field: missingFields[0] }));
@@ -151,6 +148,15 @@ const FilePicker = () => {
}; };
const errorMessages = errors.map(e => e.message); const errorMessages = errors.map(e => e.message);
// sanitize the data first
data = data.map(line => {
const newLine = {} as ImportLine;
for (const [key, value] of Object.entries(line)) {
newLine[key.trim().toLowerCase()] = value;
}
return newLine;
});
// process the data
data.forEach((line, idx) => { data.forEach((line, idx) => {
if (line.user_type === undefined || line.user_type === "") { if (line.user_type === undefined || line.user_type === "") {
stats.user_types.default++; stats.user_types.default++;
@@ -177,6 +183,7 @@ const FilePicker = () => {
line[f] = true; // we need true booleans instead of strings line[f] = true; // we need true booleans instead of strings
} else { } else {
if (line[f] !== "false" && line[f] !== "") { if (line[f] !== "false" && line[f] !== "") {
console.log("invalid value", line[f], "for field " + f + " in row " + idx);
errorMessages.push( errorMessages.push(
translate("import_users.error.invalid_value", { translate("import_users.error.invalid_value", {
field: f, field: f,

View File

@@ -0,0 +1,58 @@
import { styled } from "@mui/material/styles";
import { Box } from "@mui/material";
const LoginFormBox = styled(Box)(({ theme }) => ({
display: "flex",
flexDirection: "column",
minHeight: "calc(100vh - 1rem)",
alignItems: "center",
justifyContent: "flex-start",
background: "url(./images/floating-cogs.svg)",
backgroundColor: "#f9f9f9",
backgroundRepeat: "no-repeat",
backgroundSize: "cover",
[`& .card`]: {
width: "30rem",
marginTop: "6rem",
marginBottom: "6rem",
},
[`& .avatar`]: {
margin: "1rem",
display: "flex",
justifyContent: "center",
},
[`& .icon`]: {
backgroundColor: theme.palette.grey[500],
},
[`& .hint`]: {
marginTop: "1em",
marginBottom: "1em",
display: "flex",
justifyContent: "center",
color: theme.palette.grey[600],
},
[`& .form`]: {
padding: "0 1rem 1rem 1rem",
},
[`& .select`]: {
marginBottom: "2rem",
},
[`& .actions`]: {
padding: "0 1rem 1rem 1rem",
},
[`& .serverVersion`]: {
color: theme.palette.grey[500],
fontFamily: "Roboto, Helvetica, Arial, sans-serif",
marginLeft: "0.5rem",
},
[`& .matrixVersions`]: {
color: theme.palette.grey[500],
fontFamily: "Roboto, Helvetica, Arial, sans-serif",
fontSize: "0.8rem",
marginBottom: "1rem",
marginLeft: "0.5rem",
},
}));
export default LoginFormBox;

View File

@@ -0,0 +1,90 @@
import { Stack, Typography } from "@mui/material";
import { useEffect, useState } from "react";
import { useDataProvider, useNotify, useRecordContext, useTranslate } from "react-admin";
import { TextField } from "@mui/material";
import { useFormContext } from "react-hook-form";
const RateLimitRow = ({ limit, value, updateRateLimit }: { limit: string, value: number, updateRateLimit: (limit: string, value: number) => void }) => {
const translate = useTranslate();
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
updateRateLimit(limit, parseInt(event.target.value));
};
return <Stack
spacing={1}
alignItems="start"
sx={{
padding: 2,
}}
>
<TextField
id="outlined-number"
type="number"
value={value}
onChange={handleChange}
slotProps={{
inputLabel: {
shrink: true,
},
}}
label={translate(`resources.users.limits.${limit}`)}
/>
<Stack>
<Typography
variant="body2"
color="text.secondary"
>
{translate(`resources.users.limits.${limit}_text`)}
</Typography>
</Stack>
</Stack>
}
export const UserRateLimits = () => {
const translate = useTranslate();
const notify = useNotify();
const record = useRecordContext();
const form = useFormContext();
const dataProvider = useDataProvider();
const [rateLimits, setRateLimits] = useState({
messages_per_second: 0,
burst_count: 0,
});
if (!record) {
return null;
}
useEffect(() => {
const fetchRateLimits = async () => {
const rateLimits = await dataProvider.getRateLimits(record.id);
if (Object.keys(rateLimits).length > 0) {
setRateLimits(rateLimits);
}
}
fetchRateLimits();
}, []);
const updateRateLimit = async (limit: string, value: number) => {
let updatedRateLimits = { ...rateLimits, [limit]: value };
setRateLimits(updatedRateLimits);
form.setValue(`rates.${limit}`, value, { shouldDirty: true });
};
return <>
<Stack
direction="column"
>
{Object.keys(rateLimits).map((limit: string) =>
<RateLimitRow
key={limit}
limit={limit}
value={rateLimits[limit]}
updateRateLimit={updateRateLimit}
/>
)}
</Stack>
</>
};

87
src/components/config.ts Normal file
View File

@@ -0,0 +1,87 @@
import storage from "../storage";
export interface Config {
restrictBaseUrl: string | string[];
asManagedUsers: string[];
supportURL: string;
menu: MenuItem[];
}
export interface MenuItem {
label: string;
icon: string;
url: string;
}
export const WellKnownKey = "cc.etke.synapse-admin";
export const LoadConfig = (context: Config): Config => {
if (context.restrictBaseUrl) {
storage.setItem("restrict_base_url", JSON.stringify(context.restrictBaseUrl));
}
if (context.asManagedUsers) {
storage.setItem("as_managed_users", JSON.stringify(context.asManagedUsers));
}
let menu: MenuItem[] = [];
if (context.menu) {
menu = context.menu;
}
if (context.supportURL) {
const migratedSupportURL = {
label: "Contact support",
icon: "SupportAgent",
url: context.supportURL,
};
console.warn("supportURL config option is deprecated. Please, use the menu option instead. Automatically migrated to the new menu option:", migratedSupportURL);
menu.push(migratedSupportURL as MenuItem);
}
if (menu.length > 0) {
storage.setItem("menu", JSON.stringify(menu));
}
// below we try to calculate "final" config, which will contain values from context and already set values in storage
// because LoadConfig could be called multiple times to get config from different sources
let finalRestrictBaseUrl: string | string[] = "";
try {
finalRestrictBaseUrl = JSON.parse(storage.getItem("restrict_base_url") || "");
if (Array.isArray(finalRestrictBaseUrl) && finalRestrictBaseUrl.length == 1) {
finalRestrictBaseUrl = finalRestrictBaseUrl[0];
}
} catch (e) {}
let finalAsManagedUsers: string[] = [];
try {
finalAsManagedUsers = JSON.parse(storage.getItem("as_managed_users") || "");
} catch (e) {}
let finalMenu: MenuItem[] = [];
try {
finalMenu = JSON.parse(storage.getItem("menu") || "");
} catch (e) {}
return {
restrictBaseUrl: finalRestrictBaseUrl,
asManagedUsers: finalAsManagedUsers,
supportURL: storage.getItem("support_url") || "",
menu: finalMenu,
} as Config;
}
export const ClearConfig = () => {
// config.json
storage.removeItem("restrict_base_url");
storage.removeItem("as_managed_users");
storage.removeItem("support_url");
storage.removeItem("menu");
// session
storage.removeItem("home_server");
storage.removeItem("base_url");
storage.removeItem("user_id");
storage.removeItem("device_id");
storage.removeItem("access_token");
storage.removeItem("login_type");
}

12
src/components/icons.ts Normal file
View File

@@ -0,0 +1,12 @@
import { lazy } from "react";
export const Icons = {
Announcement: lazy(() => import('@mui/icons-material/Announcement')),
Engineering: lazy(() => import('@mui/icons-material/Engineering')),
HelpCenter: lazy(() => import('@mui/icons-material/HelpCenter')),
SupportAgent: lazy(() => import('@mui/icons-material/SupportAgent')),
Default: lazy(() => import('@mui/icons-material/OpenInNew')),
// Add more icons as needed
};
export const DefaultIcon = Icons.Default;

View File

@@ -8,7 +8,9 @@ import DeleteSweepIcon from "@mui/icons-material/DeleteSweep";
import FileOpenIcon from "@mui/icons-material/FileOpen"; import FileOpenIcon from "@mui/icons-material/FileOpen";
import LockIcon from "@mui/icons-material/Lock"; import LockIcon from "@mui/icons-material/Lock";
import LockOpenIcon from "@mui/icons-material/LockOpen"; import LockOpenIcon from "@mui/icons-material/LockOpen";
import { Box, Dialog, DialogContent, DialogContentText, DialogTitle, Tooltip } from "@mui/material"; import DownloadIcon from '@mui/icons-material/Download';
import DownloadingIcon from '@mui/icons-material/Downloading';
import { Grid2 as Grid, Box, Dialog, DialogContent, DialogContentText, DialogTitle, Tooltip, Link } from "@mui/material";
import { alpha, useTheme } from "@mui/material/styles"; import { alpha, useTheme } from "@mui/material/styles";
import { import {
BooleanInput, BooleanInput,
@@ -29,12 +31,11 @@ import {
useTranslate, useTranslate,
} from "react-admin"; } from "react-admin";
import { useMutation } from "@tanstack/react-query"; import { useMutation } from "@tanstack/react-query";
import { Link } from "react-router-dom";
import { dateParser } from "./date"; import { dateParser } from "./date";
import { DeleteMediaParams, SynapseDataProvider } from "../synapse/dataProvider"; import { DeleteMediaParams, SynapseDataProvider } from "../synapse/dataProvider";
import { getMediaUrl } from "../synapse/synapse";
import storage from "../storage"; import storage from "../storage";
import { fetchAuthenticatedMedia } from "../utils/fetchMedia";
const DeleteMediaDialog = ({ open, onClose, onSubmit }) => { const DeleteMediaDialog = ({ open, onClose, onSubmit }) => {
const translate = useTranslate(); const translate = useTranslate();
@@ -311,48 +312,104 @@ export const QuarantineMediaButton = (props: ButtonProps) => {
); );
}; };
export const ViewMediaButton = ({ media_id, label }) => { export const ViewMediaButton = ({ mxcURL, label, uploadName, mimetype }) => {
const translate = useTranslate(); const translate = useTranslate();
const url = getMediaUrl(media_id); const [loading, setLoading] = useState(false);
const isImage = mimetype && mimetype.startsWith("image/");
const openFileInNewTab = (blobURL: string) => {
const anchorElement = document.createElement("a");
anchorElement.href = blobURL;
anchorElement.target = "_blank";
document.body.appendChild(anchorElement);
anchorElement.click();
document.body.removeChild(anchorElement);
setTimeout(() => URL.revokeObjectURL(blobURL), 10);
};
const downloadFile = async (blobURL: string) => {
console.log("downloadFile", blobURL, uploadName);
const anchorElement = document.createElement("a");
anchorElement.href = blobURL;
anchorElement.download = uploadName;
document.body.appendChild(anchorElement);
anchorElement.click();
document.body.removeChild(anchorElement);
setTimeout(() => URL.revokeObjectURL(blobURL), 10);;
};
const handleFile = async (preview: boolean) => {
setLoading(true);
const response = await fetchAuthenticatedMedia(mxcURL, "original");
const blob = await response.blob();
const blobURL = URL.createObjectURL(blob);
if (preview) {
openFileInNewTab(blobURL);
} else {
downloadFile(blobURL);
}
setLoading(false);
};
return ( return (
<Box style={{ whiteSpace: "pre" }}> <>
<Tooltip title={translate("resources.users_media.action.open")}> <Box display="flex" alignItems="center">
<span> <Tooltip title={translate("resources.users_media.action.open")}>
<Button <span>
component={Link} {isImage && (
to={url} <Button
target="_blank" disabled={loading}
rel="noopener" onClick={() => handleFile(true)}
style={{ minWidth: 0, paddingLeft: 0, paddingRight: 0 }} style={{ minWidth: 0, padding: 0, marginRight: 8 }}
> >
<FileOpenIcon /> {loading ? <DownloadingIcon /> : <FileOpenIcon />}
</Button> </Button>
</span> )}
</Tooltip> </span>
{label} </Tooltip>
</Box> <Button
disabled={loading}
onClick={() => handleFile(false)}
style={{ minWidth: 0, padding: 0, marginRight: 8 }}
>
{loading ? <DownloadingIcon /> : <DownloadIcon />}
</Button>
<span>{label}</span>
</Box>
</>
); );
}; };
export const MediaIDField = ({ source }) => { export const MediaIDField = ({ source }) => {
const record = useRecordContext();
if (!record) {
return null;
}
const homeserver = storage.getItem("home_server"); const homeserver = storage.getItem("home_server");
const record = useRecordContext();
if (!record) return null;
const src = get(record, source)?.toString(); const mediaID = get(record, source)?.toString();
if (!src) return null; if (!mediaID) {
return null;
}
return <ViewMediaButton media_id={`${homeserver}/${src}`} label={src} />; const uploadName = decodeURIComponent(get(record, "upload_name")?.toString());
const mxcURL = `mxc://${homeserver}/${mediaID}`;
return <ViewMediaButton mxcURL={mxcURL} label={mediaID} uploadName={uploadName} mimetype={record.media_type}/>;
}; };
export const MXCField = ({ source }) => { export const ReportMediaContent = ({ source }) => {
const record = useRecordContext(); const record = useRecordContext();
if (!record) return null; if (!record) {
return null;
}
const src = get(record, source)?.toString(); const mxcURL = get(record, source)?.toString();
if (!src) return null; if (!mxcURL) {
return null;
}
const media_id = src.replace("mxc://", ""); const uploadName = decodeURIComponent(get(record, "event_json.content.body")?.toString());
return <ViewMediaButton media_id={media_id} label={src} />; return <ViewMediaButton mxcURL={mxcURL} label={mxcURL} uploadName={uploadName} mimetype={record.media_type}/>;
}; };

View File

@@ -1,11 +1,12 @@
import { Identifier } from "ra-core";
/** /**
* Check if a user is managed by an application service * Check if a user is managed by an application service
* @param id The user ID to check * @param id The user ID to check
* @returns Whether the user is managed by an application service * @returns Whether the user is managed by an application service
*/ */
export const isASManaged = (id: string) => { export const isASManaged = (id: string | Identifier): boolean => {
const managedUsersString = localStorage.getItem("as_managed_users"); const managedUsersString = localStorage.getItem("as_managed_users") || '';
try { try {
const asManagedUsers = JSON.parse(managedUsersString).map(regex => new RegExp(regex)); const asManagedUsers = JSON.parse(managedUsersString).map(regex => new RegExp(regex));
return asManagedUsers.some(regex => regex.test(id)); return asManagedUsers.some(regex => regex.test(id));

View File

@@ -2,7 +2,7 @@ import { formalGermanMessages } from "@haleos/ra-language-german";
import { SynapseTranslationMessages } from "."; import { SynapseTranslationMessages } from ".";
const de: SynapseTranslationMessages = { const fixedGermanMessages = {
...formalGermanMessages, ...formalGermanMessages,
ra: { ra: {
...formalGermanMessages.ra, ...formalGermanMessages.ra,
@@ -10,8 +10,30 @@ const de: SynapseTranslationMessages = {
...formalGermanMessages.ra.navigation, ...formalGermanMessages.ra.navigation,
no_filtered_results: "Keine Ergebnisse", no_filtered_results: "Keine Ergebnisse",
clear_filters: "Alle Filter entfernen", clear_filters: "Alle Filter entfernen",
add_filter: "Filter hinzufügen",
},
action: {
...formalGermanMessages.ra.action,
update_application: "Anwendung aktualisieren",
},
page: {
...formalGermanMessages.ra.page,
empty: "Leer",
access_denied: "Zugriff verweigert",
authentication_error: "Authentifizierungsfehler",
},
message: {
...formalGermanMessages.ra.message,
access_denied:
"Sie haben nicht die richtigen Berechtigungen um auf diese Seite zuzugreifen.",
authentication_error:
"Der Authentifizierungsserver hat einen Fehler zurückgegeben und Ihre Anmeldedaten konnten nicht überprüft werden.",
}, },
}, },
}
const de: SynapseTranslationMessages = {
...fixedGermanMessages,
synapseadmin: { synapseadmin: {
auth: { auth: {
base_url: "Heimserver URL", base_url: "Heimserver URL",
@@ -22,10 +44,18 @@ const de: SynapseTranslationMessages = {
protocol_error: "Die URL muss mit 'http://' oder 'https://' beginnen", protocol_error: "Die URL muss mit 'http://' oder 'https://' beginnen",
url_error: "Keine gültige Matrix Server URL", url_error: "Keine gültige Matrix Server URL",
sso_sign_in: "Anmeldung mit SSO", sso_sign_in: "Anmeldung mit SSO",
credentials: "Anmeldedaten",
access_token: "Zugriffstoken",
logout_acces_token_dialog: {
title: "Sie verwenden ein bestehendes Matrix-Zugriffstoken.",
content: "Möchten Sie diese Sitzung (die anderswo, z.B. in einem Matrix-Client, verwendet werden könnte) beenden oder sich nur vom Admin-Panel abmelden?",
confirm: "Sitzung beenden",
cancel: "Nur vom Admin-Panel abmelden",
},
}, },
users: { users: {
invalid_user_id: "Lokaler Anteil der Matrix Benutzer-ID ohne Homeserver.", invalid_user_id: "Lokaler Anteil der Matrix Benutzer-ID ohne Homeserver.",
tabs: { sso: "SSO" }, tabs: { sso: "SSO", experimental: "Experimentell", limits: "Rate Limits" },
}, },
rooms: { rooms: {
details: "Raumdetails", details: "Raumdetails",
@@ -151,13 +181,23 @@ const de: SynapseTranslationMessages = {
password: "Durch die Änderung des Passworts wird der Benutzer von allen Sitzungen abgemeldet.", password: "Durch die Änderung des Passworts wird der Benutzer von allen Sitzungen abgemeldet.",
deactivate: "Sie müssen ein Passwort angeben, um ein Konto wieder zu aktivieren.", deactivate: "Sie müssen ein Passwort angeben, um ein Konto wieder zu aktivieren.",
erase: "DSGVO konformes Löschen der Benutzerdaten.", erase: "DSGVO konformes Löschen der Benutzerdaten.",
erase_text: "Das bedeutet, dass die von dem/den Benutzer(n) gesendeten Nachrichten für alle, die zum Zeitpunkt des Sendens im Raum waren, sichtbar bleiben, aber für Benutzer, die dem Raum später beitreten, nicht sichtbar sind.",
erase_admin_error: "Das Löschen des eigenen Benutzers ist nicht erlaubt.", erase_admin_error: "Das Löschen des eigenen Benutzers ist nicht erlaubt.",
modify_managed_user_error: "Das Ändern eines vom System verwalteten Benutzers ist nicht zulässig.", modify_managed_user_error: "Das Ändern eines vom System verwalteten Benutzers ist nicht zulässig.",
}, },
action: { action: {
erase: "Lösche Benutzerdaten", erase: "Lösche Benutzerdaten",
erase_avatar: "Avatar löschen" erase_avatar: "Avatar löschen",
delete_media: "Alle von dem/den Benutzer(n) hochgeladenen Medien löschen",
redact_events: "Schwärzen aller vom Benutzer gesendeten Ereignisse (-s)",
generate_password: "Passwort generieren",
}, },
limits: {
messages_per_second: "Nachrichten pro Sekunde",
messages_per_second_text: "Die Anzahl der Aktionen, die in einer Sekunde durchgeführt werden können. 0 bedeutet, dass die Rate-Limitierung für diesen Benutzer deaktiviert ist.",
burst_count: "Burst-Anzahl",
burst_count_text: "Die Anzahl der Aktionen, die vor der Begrenzung durchgeführt werden können.",
}
}, },
rooms: { rooms: {
name: "Raum |||| Räume", name: "Raum |||| Räume",

View File

@@ -14,10 +14,22 @@ const en: SynapseTranslationMessages = {
protocol_error: "URL has to start with 'http://' or 'https://'", protocol_error: "URL has to start with 'http://' or 'https://'",
url_error: "Not a valid Matrix server URL", url_error: "Not a valid Matrix server URL",
sso_sign_in: "Sign in with SSO", sso_sign_in: "Sign in with SSO",
credentials: "Credentials",
access_token: "Access token",
logout_acces_token_dialog: {
title: "You are using an existing Matrix access token.",
content: "Do you want to destroy this session (that could be used elsewhere, e.g. in a Matrix client) or just logout from the admin panel?",
confirm: "Destroy session",
cancel: "Just logout from admin panel",
},
}, },
users: { users: {
invalid_user_id: "Localpart of a Matrix user-id without homeserver.", invalid_user_id: "Localpart of a Matrix user-id without homeserver.",
tabs: { sso: "SSO" }, tabs: {
sso: "SSO",
experimental: "Experimental",
limits: "Rate Limits",
},
}, },
rooms: { rooms: {
details: "Room details", details: "Room details",
@@ -142,13 +154,23 @@ const en: SynapseTranslationMessages = {
password: "Changing password will log user out of all sessions.", password: "Changing password will log user out of all sessions.",
deactivate: "You must provide a password to re-activate an account.", deactivate: "You must provide a password to re-activate an account.",
erase: "Mark the user as GDPR-erased", erase: "Mark the user as GDPR-erased",
erase_text: "This means messages sent by the user(-s) will still be visible by anyone who was in the room when these messages were sent, but hidden from users joining the room afterward.",
erase_admin_error: "Deleting own user is not allowed.", erase_admin_error: "Deleting own user is not allowed.",
modify_managed_user_error: "Modifying a system-managed user is not allowed.", modify_managed_user_error: "Modifying a system-managed user is not allowed.",
}, },
action: { action: {
erase: "Erase user data", erase: "Erase user data",
erase_avatar: "Erase avatar" erase_avatar: "Erase avatar",
delete_media: "Delete all media uploaded by the user(-s)",
redact_events: "Redact all events sent by the user(-s)",
generate_password: "Generate password",
}, },
limits: {
messages_per_second: "Messages per second",
messages_per_second_text: "The number of actions that can be performed in a second. 0 mean that ratelimiting is disabled for this user",
burst_count: "Burst count",
burst_count_text: "How many actions that can be performed before being limited.",
}
}, },
rooms: { rooms: {
name: "Room |||| Rooms", name: "Room |||| Rooms",

View File

@@ -13,10 +13,18 @@ const fa: SynapseTranslationMessages = {
protocol_error: "URL باید با 'http://' یا 'https://' شروع شود", protocol_error: "URL باید با 'http://' یا 'https://' شروع شود",
url_error: "آدرس وارد شده یک سرور معتبر نیست", url_error: "آدرس وارد شده یک سرور معتبر نیست",
sso_sign_in: "با SSO وارد شوید", sso_sign_in: "با SSO وارد شوید",
credentials: "اعتبارنامه",
access_token: "توکن دسترسی",
logout_acces_token_dialog: {
title: "شما در حال استفاده از یک نشانه دسترسی ماتریکس موجود هستید.",
content: "آیا می‌خواهید این جلسه (که می‌تواند در جای دیگر، مانند یک کلاینت ماتریکس استفاده شود) را نابود کنید یا فقط از پنل مدیریت خارج شوید؟",
confirm: "نابودی جلسه",
cancel: "فقط خروج از پنل مدیریت",
},
}, },
users: { users: {
invalid_user_id: "بخش محلی یک شناسه کاربری ماتریکس بدون سرور خانگی.", invalid_user_id: "بخش محلی یک شناسه کاربری ماتریکس بدون سرور خانگی.",
tabs: { sso: "SSO" }, tabs: { sso: "SSO", experimental: "تجربی", limits: "محدودیت ها" },
}, },
rooms: { rooms: {
tabs: { tabs: {
@@ -138,12 +146,23 @@ const fa: SynapseTranslationMessages = {
password: "با تغییر رمز عبور کاربر از تمام دستگاه ها خارج می شود.", password: "با تغییر رمز عبور کاربر از تمام دستگاه ها خارج می شود.",
deactivate: "برای فعالسازی مجدد حساب باید رمز عبور وارد کنید.", deactivate: "برای فعالسازی مجدد حساب باید رمز عبور وارد کنید.",
erase: "کاربر را به عنوان GDPR پاک شده علامت گذاری کنید", erase: "کاربر را به عنوان GDPR پاک شده علامت گذاری کنید",
erase_text: "وهذا يعني أن الرسائل المرسلة من قبل المستخدم (المستخدمين) ستظل مرئية من قبل أي شخص كان في الغرفة عند إرسال هذه الرسائل، ولكنها مخفية عن المستخدمين الذين ينضمون إلى الغرفة بعد ذلك.",
erase_admin_error: "حذف المستخدم الخاص غير مسموح به.", erase_admin_error: "حذف المستخدم الخاص غير مسموح به.",
modify_managed_user_error: "لا يُسمح بتغيير المستخدم الذي يديره النظام.", modify_managed_user_error: "لا يُسمح بتغيير المستخدم الذي يديره النظام.",
}, },
action: { action: {
erase: "پاک کردن اطلاعات کاربر", erase: "پاک کردن اطلاعات کاربر",
erase_avatar: "محو الصورة الرمزية",
delete_media: "حذف جميع الوسائط التي تم تحميلها بواسطة المستخدم (المستخدمين)",
redact_events: "تنقيح جميع الأحداث المرسلة من قبل المستخدم (-s)",
generate_password: "توليد رمز عبور",
}, },
limits: {
messages_per_second: "پیام در ثانیه",
messages_per_second_text: "تعداد عملیاتی که می تواند در یک ثانیه انجام شود. 0 به معنای غیرفعال کردن محدودیت برای این کاربر است.",
burst_count: "تعداد پیچیدگی",
burst_count_text: "تعداد عملیاتی که می تواند قبل از محدودیت انجام شود.",
}
}, },
rooms: { rooms: {
name: "اتاق |||| اتاق ها", name: "اتاق |||| اتاق ها",
@@ -195,6 +214,11 @@ const fa: SynapseTranslationMessages = {
title: "حذف اتاق", title: "حذف اتاق",
content: content:
"آیا مطمئن هستید که می خواهید اتاق را حذف کنید؟ این قابل بازگشت نیست. همه پیام ها و رسانه های مشترک در اتاق از سرور حذف می شوند!", "آیا مطمئن هستید که می خواهید اتاق را حذف کنید؟ این قابل بازگشت نیست. همه پیام ها و رسانه های مشترک در اتاق از سرور حذف می شوند!",
fields: {
block: "حذف",
},
success: "اتاق با موفقیت حذف شد.",
failure: "خطایی رخ داده است.",
}, },
}, },
}, },

View File

@@ -13,10 +13,18 @@ const fr: SynapseTranslationMessages = {
protocol_error: "L'URL doit commencer par « http:// » ou « https:// »", protocol_error: "L'URL doit commencer par « http:// » ou « https:// »",
url_error: "L'URL du serveur Matrix n'est pas valide", url_error: "L'URL du serveur Matrix n'est pas valide",
sso_sign_in: "Se connecter avec lauthentification unique", sso_sign_in: "Se connecter avec lauthentification unique",
credentials: "Identifiants",
access_token: "Jeton d'accès",
logout_acces_token_dialog: {
title: "Vous utilisez un jeton d'accès Matrix existant.",
content: "Voulez-vous détruire cette session (qui pourrait être utilisée ailleurs, par exemple dans un client Matrix) ou simplement vous déconnecter du panneau d'administration?",
confirm: "Détruire la session",
cancel: "Se déconnecter simplement du panneau d'administration",
},
}, },
users: { users: {
invalid_user_id: "Partie locale d'un identifiant utilisateur Matrix sans le nom du serveur daccueil.", invalid_user_id: "Partie locale d'un identifiant utilisateur Matrix sans le nom du serveur daccueil.",
tabs: { sso: "Authentification unique" }, tabs: { sso: "Authentification unique", experimental: "Expérimental", limits: "Limites" },
}, },
rooms: { rooms: {
tabs: { tabs: {
@@ -140,13 +148,23 @@ const fr: SynapseTranslationMessages = {
helper: { helper: {
deactivate: "Vous devrez fournir un mot de passe pour réactiver le compte.", deactivate: "Vous devrez fournir un mot de passe pour réactiver le compte.",
erase: "Marquer l'utilisateur comme effacé conformément au RGPD", erase: "Marquer l'utilisateur comme effacé conformément au RGPD",
erase_text: "Cela signifie que les messages envoyés par le(s) utilisateur(s) seront toujours visibles par toute personne qui se trouvait dans la salle au moment où ces messages ont été envoyés, mais qu'ils seront cachés aux utilisateurs qui rejoindront la salle par la suite.",
erase_admin_error: "La suppression de son propre utilisateur n'est pas autorisée.", erase_admin_error: "La suppression de son propre utilisateur n'est pas autorisée.",
modify_managed_user_error: "La modification d'un utilisateur géré par le système n'est pas autorisée.", modify_managed_user_error: "La modification d'un utilisateur géré par le système n'est pas autorisée.",
}, },
action: { action: {
erase: "Effacer les données de l'utilisateur", erase: "Effacer les données de l'utilisateur",
erase_avatar: "Effacer l'avatar", erase_avatar: "Effacer l'avatar",
delete_media: "Supprimer tous les médias téléchargés par le(s) utilisateur(s)",
redact_events: "Expurger tous les événements envoyés par l'utilisateur(-s)",
generate_password: "Générer un mot de passe",
}, },
limits: {
messages_per_second: "Messages par seconde",
messages_per_second_text: "Le nombre d'actions que l'utilisateur peut effectuer par seconde. 0 signifie que la limitation est désactivée pour cet utilisateur.",
burst_count: "Compteur de pics",
burst_count_text: "Le nombre d'actions que l'utilisateur peut effectuer avant d'être limité.",
}
}, },
rooms: { rooms: {
name: "Salon |||| Salons", name: "Salon |||| Salons",
@@ -198,9 +216,9 @@ const fr: SynapseTranslationMessages = {
title: "Supprimer le salon", title: "Supprimer le salon",
content: content:
"Voulez-vous vraiment supprimer le salon ? Cette opération ne peut être annulée. Tous les messages et médias partagés du salon seront supprimés du serveur !", "Voulez-vous vraiment supprimer le salon ? Cette opération ne peut être annulée. Tous les messages et médias partagés du salon seront supprimés du serveur !",
fields: { fields: {
block: "Bloquer et empêcher les utilisateurs de rejoindre la salle", block: "Bloquer et empêcher les utilisateurs de rejoindre la salle",
}, },
success: "Salle/s supprimées avec succès.", success: "Salle/s supprimées avec succès.",
failure: "La/les salle/s n'ont pas pu être supprimées.", failure: "La/les salle/s n'ont pas pu être supprimées.",
}, },

21
src/i18n/index.d.ts vendored
View File

@@ -11,10 +11,18 @@ interface SynapseTranslationMessages extends TranslationMessages {
protocol_error: string; protocol_error: string;
url_error: string; url_error: string;
sso_sign_in: string; sso_sign_in: string;
credentials: string;
access_token: string;
logout_acces_token_dialog: {
title: string;
content: string;
confirm: string;
cancel: string;
};
}; };
users: { users: {
invalid_user_id: string; invalid_user_id: string;
tabs: { sso: string }; tabs: { sso: string; experimental: string; limits: string; };
}; };
rooms: { rooms: {
details?: string; // TODO: fa, fr, it, zh details?: string; // TODO: fa, fr, it, zh
@@ -138,11 +146,22 @@ interface SynapseTranslationMessages extends TranslationMessages {
password?: string; password?: string;
deactivate: string; deactivate: string;
erase: string; erase: string;
erase_text: string;
erase_admin_error: string; erase_admin_error: string;
modify_managed_user_error: string;
}; };
action: { action: {
erase: string; erase: string;
erase_avatar: string; erase_avatar: string;
delete_media: string;
redact_events: string;
generate_password: string;
};
limits: {
messages_per_second: string;
messages_per_second_text: string;
burst_count: string;
burst_count_text: string;
}; };
}; };
rooms: { rooms: {

View File

@@ -13,10 +13,18 @@ const it: SynapseTranslationMessages = {
protocol_error: "L'URL deve iniziare per 'http://' o 'https://'", protocol_error: "L'URL deve iniziare per 'http://' o 'https://'",
url_error: "URL del server Matrix non valido", url_error: "URL del server Matrix non valido",
sso_sign_in: "Accedi con SSO", sso_sign_in: "Accedi con SSO",
credentials: "Credenziali",
access_token: "Token di accesso",
logout_acces_token_dialog: {
title: "Stai utilizzando un token di accesso Matrix esistente.",
content: "Vuoi distruggere questa sessione (che potrebbe essere utilizzata altrove, ad esempio in un client Matrix) o semplicemente disconnetterti dal pannello di amministrazione?",
confirm: "Distruggi sessione",
cancel: "Disconnetti solo dal pannello di amministrazione",
},
}, },
users: { users: {
invalid_user_id: "ID utente non valido su questo homeserver.", invalid_user_id: "ID utente non valido su questo homeserver.",
tabs: { sso: "SSO" }, tabs: { sso: "SSO", experimental: "Sperimentale", limits: "Limiti" },
}, },
rooms: { rooms: {
tabs: { tabs: {
@@ -139,12 +147,23 @@ const it: SynapseTranslationMessages = {
password: "Cambiando la password l'utente verrà disconnesso da tutte le sessioni attive.", password: "Cambiando la password l'utente verrà disconnesso da tutte le sessioni attive.",
deactivate: "Devi fornire una password per riattivare l'account.", deactivate: "Devi fornire una password per riattivare l'account.",
erase: "Constrassegna l'utente come cancellato dal GDPR", erase: "Constrassegna l'utente come cancellato dal GDPR",
}, erase_text: "Ciò significa che i messaggi inviati dall'utente (o dagli utenti) saranno ancora visibili da chiunque si trovasse nella stanza al momento dell'invio, ma saranno nascosti agli utenti che si uniranno alla stanza in seguito.",
action: {
erase: "Cancella i dati dell'utente",
erase_admin_error: "Non è consentito eliminare il proprio utente.", erase_admin_error: "Non è consentito eliminare il proprio utente.",
modify_managed_user_error: "La modifica di un utente gestito dal sistema non è consentita.", modify_managed_user_error: "La modifica di un utente gestito dal sistema non è consentita.",
}, },
action: {
erase: "Cancella i dati dell'utente",
erase_avatar: "Cancella l'avatar dell'utente",
delete_media: "Elimina tutti i media caricati dall'utente(-s)",
redact_events: "Ridurre tutti gli eventi inviati dall'utente(-s)",
generate_password: "Genera password",
},
limits: {
messages_per_second: "Messaggi al secondo",
messages_per_second_text: "Il numero di azioni che l'utente può eseguire al secondo. 0 significa che la limitazione è disabilitata per questo utente.",
burst_count: "Burst-conteggio",
burst_count_text: "Il numero di azioni che l'utente può eseguire prima di essere limitato.",
}
}, },
rooms: { rooms: {
name: "Stanza |||| Stanze", name: "Stanza |||| Stanze",
@@ -170,211 +189,211 @@ const it: SynapseTranslationMessages = {
}, },
helper: { helper: {
/* forward_extremities: /* forward_extremities:
"Forward extremities are the leaf events at the end of a Directed acyclic graph (DAG) in a room, aka events that have no children. The more exist in a room, the more state resolution that Synapse needs to perform (hint: it's an expensive operation). While Synapse has code to prevent too many of these existing at one time in a room, bugs can sometimes make them crop up again. If a room has >10 forward extremities, it's worth checking which room is the culprit and potentially removing them using the SQL queries mentioned in #1760.", */ "Forward extremities are the leaf events at the end of a Directed acyclic graph (DAG) in a room, aka events that have no children. The more exist in a room, the more state resolution that Synapse needs to perform (hint: it's an expensive operation). While Synapse has code to prevent too many of these existing at one time in a room, bugs can sometimes make them crop up again. If a room has >10 forward extremities, it's worth checking which room is the culprit and potentially removing them using the SQL queries mentioned in #1760.", */
}, },
enums: { enums: {
join_rules: { join_rules: {
public: "Pubblica", public: "Pubblica",
knock: "Bussa", knock: "Bussa",
invite: "Invita", invite: "Invita",
private: "Privata", private: "Privata",
},
guest_access: {
can_join: "Gli utenti ospiti possono entrare",
forbidden: "Gli utenti ospiti non possono entrare",
},
history_visibility: {
invited: "Dall'invito",
joined: "Dall'entrata",
shared: "Dalla condivisione",
world_readable: "Chiunque",
},
unencrypted: "Non criptata",
}, },
action: { guest_access: {
erase: { can_join: "Gli utenti ospiti possono entrare",
title: "Cancella stanza", forbidden: "Gli utenti ospiti non possono entrare",
content:
"Sei sicuro di voler eliminare questa stanza? Questa azione è definitiva. Tutti i messaggi e i media condivisi in questa stanza verranno eliminati dal server!",
},
}, },
history_visibility: {
invited: "Dall'invito",
joined: "Dall'entrata",
shared: "Dalla condivisione",
world_readable: "Chiunque",
},
unencrypted: "Non criptata",
}, },
reports: { action: {
name: "Evento segnalato |||| Eventi segnalati", erase: {
fields: { title: "Cancella stanza",
id: "ID",
received_ts: "Orario del report",
user_id: "richiedente",
name: "nome della stanza",
score: "punteggio",
reason: "ragione",
event_id: "ID dell'evento",
event_json: {
origin: "server di origine",
origin_server_ts: "ora dell'invio",
type: "tipo di evento",
content: {
msgtype: "tipo di contenuto",
body: "contenuto",
format: "formato",
formatted_body: "contenuto formattato",
algorithm: "algoritmo",
},
},
},
},
connections: {
name: "Connessioni",
fields: {
last_seen: "Data",
ip: "Indirizzo IP",
user_agent: "agente utente",
},
},
devices: {
name: "Dispositivo |||| Dispositivi",
fields: {
device_id: "ID del dispositivo",
display_name: "Nome del dispositivo",
last_seen_ts: "Timestamp",
last_seen_ip: "Indirizzo IP",
},
action: {
erase: {
title: "Rimozione del dispositivo %{id}",
content: 'Sei sicuro di voler rimuovere il dispositivo "%{name}"?',
success: "Dispositivo rimosso con successo.",
failure: "C'è stato un errore.",
},
},
},
users_media: {
name: "Media",
fields: {
media_id: "ID del media",
media_length: "Peso del file (in Byte)",
media_type: "Tipo",
upload_name: "Nome del file",
quarantined_by: "In quarantena da",
safe_from_quarantine: "Protetto dalla quarantena",
created_ts: "Creato",
last_access_ts: "Ultimo accesso",
},
},
protect_media: {
action: {
create: "Non protetto, proteggi",
delete: "Protetto, rimuovi protezione",
none: "In quarantena",
send_success: "Stato della protezione cambiato con successo.",
send_failure: "C'è stato un errore.",
},
},
quarantine_media: {
action: {
name: "Quarantina",
create: "Aggiungi alla quarantena",
delete: "In quarantena, rimuovi dalla quarantena",
none: "Protetto dalla quarantena",
send_success: "Stato della quarantena cambiato con successo.",
send_failure: "C'è stato un errore.",
},
},
pushers: {
name: "Pusher |||| Pusher",
fields: {
app: "App",
app_display_name: "Nome dell'app",
app_id: "ID dell'app",
device_display_name: "Nome del dispositivo",
kind: "Tipo",
lang: "Lingua",
profile_tag: "Tag del profilo",
pushkey: "Pushkey",
data: { url: "URL" },
},
},
servernotices: {
name: "Avvisi del server",
send: "Invia avvisi",
fields: {
body: "Messaggio",
},
action: {
send: "Invia nota",
send_success: "Avviso inviato con successo.",
send_failure: "C'è stato un errore.",
},
helper: {
send: 'Invia un avviso dal server agli utenti selezionati. La feature "Avvisi del server" è stata attivata sul server.',
},
},
user_media_statistics: {
name: "Media degli utenti",
fields: {
media_count: "Numero media",
media_length: "Lunghezza media",
},
},
forward_extremities: {
name: "Invia estremità",
fields: {
id: "Event ID",
received_ts: "Timestamp",
depth: "Profondità",
state_group: "State group",
},
},
room_state: {
name: "Eventi di stato",
fields: {
type: "Tipo",
content: "Contenuto",
origin_server_ts: "Ora dell'invio",
sender: "Mittente",
},
},
room_directory: {
name: "Elenco delle stanze",
fields: {
world_readable: "gli utenti ospite possono vedere senza entrare",
guest_can_join: "gli utenti ospite possono entrare",
},
action: {
title: "Cancella stanza dall'elenco |||| Cancella %{smart_count} stanze dall'elenco",
content: content:
"Sei sicuro di voler rimuovere questa stanza dall'elenco? |||| Sei sicuro di voler rimuovere %{smart_count} stanze dall'elenco?", "Sei sicuro di voler eliminare questa stanza? Questa azione è definitiva. Tutti i messaggi e i media condivisi in questa stanza verranno eliminati dal server!",
erase: "Rimuovi dall'elenco",
create: "Crea",
send_success: "Stanza creata con successo.",
send_failure: "C'è stato un errore.",
}, },
}, },
destinations: { },
name: "Federazione", reports: {
fields: { name: "Evento segnalato |||| Eventi segnalati",
destination: "Destinazione", fields: {
failure_ts: "Timestamp dell'errore", id: "ID",
retry_last_ts: "Tentativo ultimo timestamp", received_ts: "Orario del report",
retry_interval: "Intervallo dei tentativi", user_id: "richiedente",
last_successful_stream_ordering: "Ultimo flusso riuscito con successo", name: "nome della stanza",
stream_ordering: "Flusso", score: "punteggio",
reason: "ragione",
event_id: "ID dell'evento",
event_json: {
origin: "server di origine",
origin_server_ts: "ora dell'invio",
type: "tipo di evento",
content: {
msgtype: "tipo di contenuto",
body: "contenuto",
format: "formato",
formatted_body: "contenuto formattato",
algorithm: "algoritmo",
},
}, },
action: { reconnect: "Riconnetti" },
}, },
registration_tokens: { },
name: "Token di registrazione", connections: {
fields: { name: "Connessioni",
token: "Token", fields: {
valid: "Token valido", last_seen: "Data",
uses_allowed: "Usi permessi", ip: "Indirizzo IP",
pending: "In attesa", user_agent: "agente utente",
completed: "Completato", },
expiry_time: "Data della scadenza", },
length: "Lunghezza", devices: {
name: "Dispositivo |||| Dispositivi",
fields: {
device_id: "ID del dispositivo",
display_name: "Nome del dispositivo",
last_seen_ts: "Timestamp",
last_seen_ip: "Indirizzo IP",
},
action: {
erase: {
title: "Rimozione del dispositivo %{id}",
content: 'Sei sicuro di voler rimuovere il dispositivo "%{name}"?',
success: "Dispositivo rimosso con successo.",
failure: "C'è stato un errore.",
}, },
helper: { length: "Lunghezza del token se non viene dato alcun token." },
}, },
}, },
users_media: {
name: "Media",
fields: {
media_id: "ID del media",
media_length: "Peso del file (in Byte)",
media_type: "Tipo",
upload_name: "Nome del file",
quarantined_by: "In quarantena da",
safe_from_quarantine: "Protetto dalla quarantena",
created_ts: "Creato",
last_access_ts: "Ultimo accesso",
},
},
protect_media: {
action: {
create: "Non protetto, proteggi",
delete: "Protetto, rimuovi protezione",
none: "In quarantena",
send_success: "Stato della protezione cambiato con successo.",
send_failure: "C'è stato un errore.",
},
},
quarantine_media: {
action: {
name: "Quarantina",
create: "Aggiungi alla quarantena",
delete: "In quarantena, rimuovi dalla quarantena",
none: "Protetto dalla quarantena",
send_success: "Stato della quarantena cambiato con successo.",
send_failure: "C'è stato un errore.",
},
},
pushers: {
name: "Pusher |||| Pusher",
fields: {
app: "App",
app_display_name: "Nome dell'app",
app_id: "ID dell'app",
device_display_name: "Nome del dispositivo",
kind: "Tipo",
lang: "Lingua",
profile_tag: "Tag del profilo",
pushkey: "Pushkey",
data: { url: "URL" },
},
},
servernotices: {
name: "Avvisi del server",
send: "Invia avvisi",
fields: {
body: "Messaggio",
},
action: {
send: "Invia nota",
send_success: "Avviso inviato con successo.",
send_failure: "C'è stato un errore.",
},
helper: {
send: 'Invia un avviso dal server agli utenti selezionati. La feature "Avvisi del server" è stata attivata sul server.',
},
},
user_media_statistics: {
name: "Media degli utenti",
fields: {
media_count: "Numero media",
media_length: "Lunghezza media",
},
},
forward_extremities: {
name: "Invia estremità",
fields: {
id: "Event ID",
received_ts: "Timestamp",
depth: "Profondità",
state_group: "State group",
},
},
room_state: {
name: "Eventi di stato",
fields: {
type: "Tipo",
content: "Contenuto",
origin_server_ts: "Ora dell'invio",
sender: "Mittente",
},
},
room_directory: {
name: "Elenco delle stanze",
fields: {
world_readable: "gli utenti ospite possono vedere senza entrare",
guest_can_join: "gli utenti ospite possono entrare",
},
action: {
title: "Cancella stanza dall'elenco |||| Cancella %{smart_count} stanze dall'elenco",
content:
"Sei sicuro di voler rimuovere questa stanza dall'elenco? |||| Sei sicuro di voler rimuovere %{smart_count} stanze dall'elenco?",
erase: "Rimuovi dall'elenco",
create: "Crea",
send_success: "Stanza creata con successo.",
send_failure: "C'è stato un errore.",
},
},
destinations: {
name: "Federazione",
fields: {
destination: "Destinazione",
failure_ts: "Timestamp dell'errore",
retry_last_ts: "Tentativo ultimo timestamp",
retry_interval: "Intervallo dei tentativi",
last_successful_stream_ordering: "Ultimo flusso riuscito con successo",
stream_ordering: "Flusso",
},
action: { reconnect: "Riconnetti" },
},
registration_tokens: {
name: "Token di registrazione",
fields: {
token: "Token",
valid: "Token valido",
uses_allowed: "Usi permessi",
pending: "In attesa",
completed: "Completato",
expiry_time: "Data della scadenza",
length: "Lunghezza",
},
helper: { length: "Lunghezza del token se non viene dato alcun token." },
},
},
}; };
export default it; export default it;

View File

@@ -2,7 +2,7 @@ import russianMessages from "ra-language-russian";
import { SynapseTranslationMessages } from "."; import { SynapseTranslationMessages } from ".";
const ru: SynapseTranslationMessages = { const fixedRussianMessages = {
...russianMessages, ...russianMessages,
ra: { ra: {
...russianMessages.ra, ...russianMessages.ra,
@@ -11,7 +11,24 @@ const ru: SynapseTranslationMessages = {
no_filtered_results: "Нет результатов", no_filtered_results: "Нет результатов",
clear_filters: "Все фильтры сбросить", clear_filters: "Все фильтры сбросить",
}, },
page: {
...russianMessages.ra.page,
empty: "Пусто",
access_denied: "Доступ запрещен",
authentication_error: "Ошибка аутентификации",
},
message: {
...russianMessages.ra.message,
access_denied:
"У вас нет прав доступа к этой странице.",
authentication_error:
"Сервер аутентификации вернул ошибку и не смог проверить ваши учетные данные.",
},
}, },
}
const ru: SynapseTranslationMessages = {
...fixedRussianMessages,
synapseadmin: { synapseadmin: {
auth: { auth: {
base_url: "Адрес домашнего сервера", base_url: "Адрес домашнего сервера",
@@ -22,10 +39,18 @@ const ru: SynapseTranslationMessages = {
protocol_error: "Адрес должен начинаться с 'http://' или 'https://'", protocol_error: "Адрес должен начинаться с 'http://' или 'https://'",
url_error: "Неверный адрес сервера Matrix", url_error: "Неверный адрес сервера Matrix",
sso_sign_in: "Вход через SSO", sso_sign_in: "Вход через SSO",
credentials: "Учетные данные",
access_token: "Токен доступа",
logout_acces_token_dialog: {
title: "Вы используете существующий токен доступа Matrix.",
content: "Вы хотите завершить эту сессию (которая может быть использована в другом месте, например, в клиенте Matrix) или просто выйти из панели администрирования?",
confirm: "Завершить сессию",
cancel: "Просто выйти из панели администрирования",
},
}, },
users: { users: {
invalid_user_id: "Локальная часть ID пользователя Matrix без адреса домашнего сервера.", invalid_user_id: "Локальная часть ID пользователя Matrix без адреса домашнего сервера.",
tabs: { sso: "SSO" }, tabs: { sso: "SSO", experimental: "Экспериментальные", limits: "Ограничения" },
}, },
rooms: { rooms: {
details: "Данные комнаты", details: "Данные комнаты",
@@ -87,7 +112,7 @@ const ru: SynapseTranslationMessages = {
header: "Загрузить CSV файл", header: "Загрузить CSV файл",
explanation: explanation:
"Здесь вы можете загрузить файл со значениями, разделёнными запятыми, которые будут использованы для создания или обновления данных пользователей. \ "Здесь вы можете загрузить файл со значениями, разделёнными запятыми, которые будут использованы для создания или обновления данных пользователей. \
В файле должны быть поля 'id' и 'displayname'. Вы можете скачать и изменить файл-образец отсюда: ", В файле должны быть поля 'id' и 'displayname'. Вы можете скачать и изменить файл-образец отсюда: ",
}, },
startImport: { startImport: {
simulate_only: "Только симулировать", simulate_only: "Только симулировать",
@@ -122,10 +147,10 @@ const ru: SynapseTranslationMessages = {
helper: { helper: {
send: "Это API удаляет локальные файлы с вашего собственного сервера, включая локальные миниатюры и копии скачанных файлов. \ send: "Это API удаляет локальные файлы с вашего собственного сервера, включая локальные миниатюры и копии скачанных файлов. \
Данный API не затрагивает файлы, загруженные во внешние хранилища.", Данный API не затрагивает файлы, загруженные во внешние хранилища.",
}, },
}, },
resources: { resources: {
users: { users: {
name: "Пользователь |||| Пользователи", name: "Пользователь |||| Пользователи",
email: "Почта", email: "Почта",
msisdn: "Телефон", msisdn: "Телефон",
@@ -159,265 +184,275 @@ const ru: SynapseTranslationMessages = {
password: "Смена пароля завершит все сессии пользователя.", password: "Смена пароля завершит все сессии пользователя.",
deactivate: "Вы должны предоставить пароль для реактивации учётной записи.", deactivate: "Вы должны предоставить пароль для реактивации учётной записи.",
erase: "Пометить пользователя как удалённого в соответствии с GDPR", erase: "Пометить пользователя как удалённого в соответствии с GDPR",
erase_text: "Это означает, что сообщения, отправленные пользователем (-ами), будут по-прежнему видны всем, кто находился в комнате в момент их отправки, но будут скрыты от пользователей, присоединившихся к комнате после этого.",
erase_admin_error: "Удаление собственного пользователя запрещено.", erase_admin_error: "Удаление собственного пользователя запрещено.",
modify_managed_user_error: "Изменение пользователя, управляемого системой, не допускается.", modify_managed_user_error: "Изменение пользователя, управляемого системой, не допускается.",
}, },
action: { action: {
erase: "Удалить данные пользователя", erase: "Удалить данные пользователя",
erase_avatar: "Удалить аватар", erase_avatar: "Удалить аватар",
delete_media: "Удаление всех медиафайлов, загруженных пользователем (-ами)",
redact_events: "Удаление всех событий, отправленных пользователем (-ами)",
generate_password: "Сгенерировать пароль",
}, },
limits: {
messages_per_second: "Сообщений в секунду",
messages_per_second_text: "Количество действий, которые могут быть выполнены в секунду. 0 означает, что ограничение на количество действий отключено для этого пользователя.",
burst_count: "Burst-счётчик",
burst_count_text: "Количество действий, которые могут быть выполнены до ограничения.",
}
}, },
rooms: { rooms: {
name: "Комната |||| Комнаты", name: "Комната |||| Комнаты",
fields: { fields: {
room_id: "ID комнаты", room_id: "ID комнаты",
name: "Название", name: "Название",
canonical_alias: "Псевдоним", canonical_alias: "Псевдоним",
joined_members: "Участники", joined_members: "Участники",
joined_local_members: "Локальные участники", joined_local_members: "Локальные участники",
joined_local_devices: "Локальные устройства", joined_local_devices: "Локальные устройства",
state_events: "События состояния / Сложность", state_events: "События состояния / Сложность",
version: "Версия", version: "Версия",
is_encrypted: "Зашифровано", is_encrypted: "Зашифровано",
encryption: "Шифрование", encryption: "Шифрование",
federatable: "Федерация", federatable: "Федерация",
public: "Отображается в каталоге комнат", public: "Отображается в каталоге комнат",
creator: "Создатель", creator: "Создатель",
join_rules: "Правила входа", join_rules: "Правила входа",
guest_access: "Гостевой доступ", guest_access: "Гостевой доступ",
history_visibility: "Видимость истории", history_visibility: "Видимость истории",
topic: "Тема", topic: "Тема",
avatar: "Аватар", avatar: "Аватар",
}, },
helper: { helper: {
forward_extremities: forward_extremities:
"Оконечности — это события-листья в конце ориентированного ациклического графа (DAG) в комнате, т.е. события без дочерних элементов. \ "Оконечности — это события-листья в конце ориентированного ациклического графа (DAG) в комнате, т.е. события без дочерних элементов. \
Чем больше их в комнате, тем больше Synapse работает над разрешением состояния (это дорогостоящая операция). \ Чем больше их в комнате, тем больше Synapse работает над разрешением состояния (это дорогостоящая операция). \
Хотя Synapse старается не допускать существования слишком большого числа таких событий в комнате, из-за ошибок они иногда снова появляются. \ Хотя Synapse старается не допускать существования слишком большого числа таких событий в комнате, из-за ошибок они иногда снова появляются. \
Если в комнате >10 оконечностей, стоит найти комнату-виновника и попробовать удалить их с помощью SQL-запросов из #1760.", Если в комнате >10 оконечностей, стоит найти комнату-виновника и попробовать удалить их с помощью SQL-запросов из #1760.",
},
enums: {
join_rules: {
public: "Для всех",
knock: "Надо постучать",
invite: "По приглашению",
private: "Приватная",
}, },
guest_access: { enums: {
can_join: "Гости могут войти", join_rules: {
forbidden: "Гости не могут войти", public: "Для всех",
}, knock: "Надо постучать",
history_visibility: { invite: "По приглашению",
invited: "С момента приглашения", private: "Приватная",
joined: "С момента входа", },
shared: "С момента открытия доступа", guest_access: {
world_readable: "Для всех", can_join: "Гости могут войти",
}, forbidden: "Гости не могут войти",
unencrypted: "Без шифрования", },
}, history_visibility: {
action: { invited: "С момента приглашения",
erase: { joined: "С момента входа",
title: "Удалить комнату", shared: "С момента открытия доступа",
content: world_readable: "Для всех",
"Действительно удалить эту комнату? Это действие будет невозможно отменить. Все сообщения и файлы в комнате будут удалены с сервера!", },
fields: { unencrypted: "Без шифрования",
block: "Заблокировать и запретить пользователям присоединяться к комнате", },
action: {
erase: {
title: "Удалить комнату",
content:
"Действительно удалить эту комнату? Это действие будет невозможно отменить. Все сообщения и файлы в комнате будут удалены с сервера!",
fields: {
block: "Заблокировать и запретить пользователям присоединяться к комнате",
},
success: "Комната/ы успешно удалены",
failure: "Комната/ы не могут быть удалены.",
}, },
success: "Комната/ы успешно удалены",
failure: "Комната/ы не могут быть удалены.",
}, },
}, },
}, reports: {
reports: { name: "Жалоба |||| Жалобы",
name: "Жалоба |||| Жалобы", fields: {
fields: { id: "ID",
id: "ID", received_ts: "Дата и время жалобы",
received_ts: "Дата и время жалобы", user_id: "Автор жалобы",
user_id: "Автор жалобы", name: "Название комнаты",
name: "Название комнаты", score: "Баллы",
score: "Баллы", reason: "Причина",
reason: "Причина", event_id: "ID события",
event_id: "ID события", event_json: {
event_json: { origin: "Исходнный сервер",
origin: "Исходнный сервер", origin_server_ts: "Дата и время отправки",
origin_server_ts: "Дата и время отправки", type: "Тип события",
type: "Тип события", content: {
content: { msgtype: "Тип содержимого",
msgtype: "Тип содержимого", body: "Содержимое",
body: "Содержимое", format: "Формат",
format: "Формат", formatted_body: "Форматированное содержимое",
formatted_body: "Форматированное содержимое", algorithm: "Алгоритм",
algorithm: "Алгоритм", url: "Ссылка",
url: "Ссылка", info: {
info: { mimetype: "Тип",
mimetype: "Тип", },
}, },
}, },
}, },
}, action: {
action: { erase: {
erase: { title: "Удалить жалобу",
title: "Удалить жалобу", content: "Действительно удалить жалобу? Это действие будет невозможно отменить.",
content: "Действительно удалить жалобу? Это действие будет невозможно отменить.", },
}, },
}, },
}, connections: {
connections: { name: "Подключения",
name: "Подключения", fields: {
fields: { last_seen: "Дата",
last_seen: "Дата", ip: "IP адрес",
ip: "IP адрес", user_agent: "Юзер-агент",
user_agent: "Юзер-агент",
},
},
devices: {
name: "Устройство |||| Устройства",
fields: {
device_id: "ID устройства",
display_name: "Название",
last_seen_ts: "Дата и время",
last_seen_ip: "IP адрес",
},
action: {
erase: {
title: "Удаление %{id}",
content: 'Действительно удалить устройство "%{name}"?',
success: "Устройство успешно удалено.",
failure: "Произошла ошибка.",
}, },
}, },
}, devices: {
users_media: { name: "Устройство |||| Устройства",
name: "Файлы", fields: {
fields: { device_id: "ID устройства",
media_id: "ID файла", display_name: "Название",
media_length: "Размер файла (в байтах)", last_seen_ts: "Дата и время",
media_type: "Тип", last_seen_ip: "IP адрес",
upload_name: "Имя файла", },
quarantined_by: "На карантине", action: {
safe_from_quarantine: "Защитить от карантина", erase: {
created_ts: "Создано", title: "Удаление %{id}",
last_access_ts: "Последний доступ", content: 'Действительно удалить устройство "%{name}"?',
success: "Устройство успешно удалено.",
failure: "Произошла ошибка.",
},
},
}, },
action: { users_media: {
open: "Открыть файл в новом окне", name: "Файлы",
fields: {
media_id: "ID файла",
media_length: "Размер файла (в байтах)",
media_type: "Тип",
upload_name: "Имя файла",
quarantined_by: "На карантине",
safe_from_quarantine: "Защитить от карантина",
created_ts: "Создано",
last_access_ts: "Последний доступ",
},
action: {
open: "Открыть файл в новом окне",
},
}, },
}, protect_media: {
protect_media: { action: {
action: { create: "Не защищён, установить защиту",
create: "Не защищён, установить защиту", delete: "Защищён, снять защиту",
delete: "Защищён, снять защиту", none: "На карантине",
none: "На карантине", send_success: "Статус защиты успешно изменён.",
send_success: "Статус защиты успешно изменён.", send_failure: "Произошла ошибка.",
send_failure: "Произошла ошибка.", },
}, },
}, quarantine_media: {
quarantine_media: { action: {
action: { name: "Карантин",
name: "Карантин", create: "Поместить на карантин",
create: "Поместить на карантин", delete: "На карантине, снять карантин",
delete: "На карантине, снять карантин", none: "Защищено от карантина",
none: "Защищено от карантина", send_success: "Статус карантина успешно изменён.",
send_success: "Статус карантина успешно изменён.", send_failure: "Произошла ошибка.",
send_failure: "Произошла ошибка.", },
}, },
}, pushers: {
pushers: { name: "Пушер |||| Пушеры",
name: "Пушер |||| Пушеры", fields: {
fields: { app: "Приложение",
app: риложение", app_display_name: "Название приложения",
app_display_name: "Название приложения", app_id: "ID приложения",
app_id: "ID приложения", device_display_name: "Название устройства",
device_display_name: "Название устройства", kind: "Вид",
kind: "Вид", lang: "Язык",
lang: "Язык", profile_tag: "Тег профиля",
profile_tag: "Тег профиля", pushkey: "Ключ",
pushkey: "Ключ", data: { url: "URL" },
data: { url: "URL" }, },
}, },
}, servernotices: {
servernotices: { name: "Серверные уведомления",
name: "Серверные уведомления", send: "Отправить серверные уведомления",
send: "Отправить серверные уведомления", fields: {
fields: { body: "Сообщение",
body: "Сообщение", },
action: {
send: "Отправить",
send_success: "Серверное уведомление успешно отправлено.",
send_failure: "Произошла ошибка.",
},
helper: {
send: 'Отправить серверное уведомление выбранным пользователям. На сервере должна быть активна функция "Server Notices".',
},
}, },
action: { user_media_statistics: {
send: "Отправить", name: "Файлы пользователей",
send_success: "Серверное уведомление успешно отправлено.", fields: {
send_failure: "Произошла ошибка.", media_count: "Количество файлов",
media_length: "Размер файлов",
},
}, },
helper: { forward_extremities: {
send: 'Отправить серверное уведомление выбранным пользователям. На сервере должна быть активна функция "Server Notices".', name: "Оконечности",
fields: {
id: "ID события",
received_ts: "Дата и время",
depth: "Глубина",
state_group: "Группа состояния",
},
}, },
}, room_state: {
user_media_statistics: { name: "События состояния",
name: "Файлы пользователей", fields: {
fields: { type: "Тип",
media_count: "Количество файлов", content: "Содержимое",
media_length: "Размер файлов", origin_server_ts: "Дата отправки",
sender: "Отправитель",
},
}, },
}, room_directory: {
forward_extremities: { name: "Каталог комнат",
name: "Оконечности", fields: {
fields: { world_readable: "Гости могут просматривать без входа",
id: "ID события", guest_can_join: "Гости могут войти",
received_ts: "Дата и время", },
depth: "Глубина", action: {
state_group: "Группа состояния", title:
"Удалить комнату из каталога |||| Удалить %{smart_count} комнаты из каталога |||| Удалить %{smart_count} комнат из каталога",
content:
"Действительно удалить комнату из каталога? |||| Действительно удалить %{smart_count} комнаты из каталога? |||| Действительно удалить %{smart_count} комнат из каталога?",
erase: "Удалить из каталога комнат",
create: "Опубликовать в каталоге комнат",
send_success: "Комната успешно опубликована.",
send_failure: "Произошла ошибка.",
},
}, },
}, destinations: {
room_state: { name: "Федерация",
name: "События состояния", fields: {
fields: { destination: "Назначение",
type: "Тип", failure_ts: "Дата и время ошибки",
content: "Содержимое", retry_last_ts: "Дата и время последней попытки",
origin_server_ts: "Дата отправки", retry_interval: "Интервал между попытками",
sender: "Отправитель", last_successful_stream_ordering: "Последний успешный поток",
stream_ordering: "Поток",
},
action: { reconnect: "Переподключиться" },
}, },
}, registration_tokens: {
room_directory: { name: "Токены регистрации",
name: "Каталог комнат", fields: {
fields: { token: "Токен",
world_readable: "Гости могут просматривать без входа", valid: "Рабочий токен",
guest_can_join: "Гости могут войти", uses_allowed: "Количество использований",
pending: "Ожидает",
completed: "Завершено",
expiry_time: "Дата окончания",
length: "Длина",
},
helper: { length: "Длина токена, если токен не задан." },
}, },
action: { },
title:
"Удалить комнату из каталога |||| Удалить %{smart_count} комнаты из каталога |||| Удалить %{smart_count} комнат из каталога",
content:
"Действительно удалить комнату из каталога? |||| Действительно удалить %{smart_count} комнаты из каталога? |||| Действительно удалить %{smart_count} комнат из каталога?",
erase: "Удалить из каталога комнат",
create: "Опубликовать в каталоге комнат",
send_success: "Комната успешно опубликована.",
send_failure: "Произошла ошибка.",
},
},
destinations: {
name: "Федерация",
fields: {
destination: "Назначение",
failure_ts: "Дата и время ошибки",
retry_last_ts: "Дата и время последней попытки",
retry_interval: "Интервал между попытками",
last_successful_stream_ordering: "Последний успешный поток",
stream_ordering: "Поток",
},
action: { reconnect: "Переподключиться" },
},
registration_tokens: {
name: "Токены регистрации",
fields: {
token: "Токен",
valid: "Рабочий токен",
uses_allowed: "Количество использований",
pending: "Ожидает",
completed: "Завершено",
expiry_time: "Дата окончания",
length: "Длина",
},
helper: { length: "Длина токена, если токен не задан." },
},
},
}; };
export default ru; export default ru;

View File

@@ -2,7 +2,7 @@ import chineseMessages from "@haxqer/ra-language-chinese";
import { SynapseTranslationMessages } from "."; import { SynapseTranslationMessages } from ".";
const zh: SynapseTranslationMessages = { const fixedChineseMessages = {
...chineseMessages, ...chineseMessages,
ra: { ra: {
...chineseMessages.ra, ...chineseMessages.ra,
@@ -11,7 +11,27 @@ const zh: SynapseTranslationMessages = {
no_filtered_results: "没有结果", no_filtered_results: "没有结果",
clear_filters: "清除所有过滤器", clear_filters: "清除所有过滤器",
}, },
action: {
...chineseMessages.ra.action,
update_application: "Anwendung aktualisieren",
},
page: {
...chineseMessages.ra.page,
access_denied: "拒绝访问",
authentication_error: "认证错误",
},
message: {
...chineseMessages.ra.message,
access_denied:
"您没有访问此页面的权限。",
authentication_error:
"身份验证服务器返回错误,无法验证您的凭据。",
},
}, },
}
const zh: SynapseTranslationMessages = {
...fixedChineseMessages,
synapseadmin: { synapseadmin: {
auth: { auth: {
base_url: "服务器 URL", base_url: "服务器 URL",
@@ -21,10 +41,18 @@ const zh: SynapseTranslationMessages = {
protocol_error: "URL 需要以'http://'或'https://'作为起始", protocol_error: "URL 需要以'http://'或'https://'作为起始",
url_error: "不是一个有效的 Matrix 服务器地址", url_error: "不是一个有效的 Matrix 服务器地址",
sso_sign_in: "使用 SSO 登录", sso_sign_in: "使用 SSO 登录",
credentials: "凭证",
access_token: "访问令牌",
logout_acces_token_dialog: {
title: "您正在使用现有的 Matrix 访问令牌。",
content: "您想销毁此会话(可能在其他地方使用,例如在 Matrix 客户端中)还是仅从管理面板退出?",
confirm: "销毁会话",
cancel: "仅从管理面板退出",
},
}, },
users: { users: {
invalid_user_id: "必须要是一个有效的 Matrix 用户 ID ,例如 @user_id:homeserver", invalid_user_id: "必须要是一个有效的 Matrix 用户 ID ,例如 @user_id:homeserver",
tabs: { sso: "SSO" }, tabs: { sso: "SSO", experimental: "实验性", limits: "限制" },
}, },
rooms: { rooms: {
tabs: { tabs: {
@@ -143,13 +171,23 @@ const zh: SynapseTranslationMessages = {
helper: { helper: {
deactivate: "您必须提供一串密码来激活账户。", deactivate: "您必须提供一串密码来激活账户。",
erase: "将用户标记为根据 GDPR 的要求抹除了", erase: "将用户标记为根据 GDPR 的要求抹除了",
erase_text: "这意味着用户发送的信息对于发送信息时在房间内的任何人来说都是可见的,但对于之后加入房间的用户来说则是隐藏的。",
erase_admin_error: "不允许删除自己的用户", erase_admin_error: "不允许删除自己的用户",
modify_managed_user_error: "不允许修改系统管理的用户。", modify_managed_user_error: "不允许修改系统管理的用户。",
}, },
action: { action: {
erase: "抹除用户信息", erase: "抹除用户信息",
erase_avatar: "抹掉头像", erase_avatar: "抹掉头像",
delete_media: "删除用户上传的所有媒体",
redact_events: "重新编辑用户(-s发送的所有事件",
generate_password: "生成密码",
}, },
limits: {
messages_per_second: "每秒消息数",
messages_per_second_text: "每秒可以执行的操作数。0 表示禁用此用户的限制。",
burst_count: "Burst-计数",
burst_count_text: "在限制之前可以执行的操作数。",
}
}, },
rooms: { rooms: {
name: "房间", name: "房间",

View File

@@ -3,18 +3,42 @@ import React from "react";
import { createRoot } from "react-dom/client"; import { createRoot } from "react-dom/client";
import App from "./App"; import App from "./App";
import { Config, WellKnownKey, LoadConfig } from "./components/config";
import { AppContext } from "./AppContext"; import { AppContext } from "./AppContext";
import storage from "./storage"; import storage from "./storage";
fetch("config.json") // load config.json
.then(res => res.json()) let props: Config = {};
.then(props => { try {
storage.setItem("as_managed_users", JSON.stringify(props.asManagedUsers)); const resp = await fetch("config.json");
return createRoot(document.getElementById("root")).render( const configJSON = await resp.json();
console.log("Loaded config.json", configJSON);
props = LoadConfig(configJSON as Config);
} catch (e) {
console.error(e);
}
// if home_server is set, try to load https://home_server/.well-known/matrix/client
const homeserver = storage.getItem("home_server");
if (homeserver) {
try {
const resp = await fetch(`https://${homeserver}/.well-known/matrix/client`);
const configWK = await resp.json();
if (!configWK[WellKnownKey]) {
console.log(`Loaded https://${homeserver}.well-known/matrix/client, but it doesn't contain ${WellKnownKey} key, skipping`, configWK);
} else {
console.log(`Loaded https://${homeserver}.well-known/matrix/client`, configWK);
props = LoadConfig(configWK[WellKnownKey] as Config);
}
} catch (e) {
console.log(`https://${homeserver}/.well-known/matrix/client not found, skipping`, e);
}
}
createRoot(document.getElementById("root")).render(
<React.StrictMode> <React.StrictMode>
<AppContext.Provider value={props}> <AppContext.Provider value={props}>
<App /> <App />
</AppContext.Provider> </AppContext.Provider>
</React.StrictMode> </React.StrictMode>
) );
});

View File

@@ -1,8 +1,6 @@
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import LockIcon from "@mui/icons-material/Lock"; import { Avatar, Box, Button, Card, CardActions, CircularProgress, MenuItem, Select, Tab, Tabs, Typography } from "@mui/material";
import { Avatar, Box, Button, Card, CardActions, CircularProgress, MenuItem, Select, Typography } from "@mui/material";
import { styled } from "@mui/material/styles";
import { import {
Form, Form,
FormDataConsumer, FormDataConsumer,
@@ -17,7 +15,7 @@ import {
useLocales, useLocales,
} from "react-admin"; } from "react-admin";
import { useFormContext } from "react-hook-form"; import { useFormContext } from "react-hook-form";
import LoginFormBox from "../components/LoginFormBox";
import { useAppContext } from "../AppContext"; import { useAppContext } from "../AppContext";
import { import {
getServerVersion, getServerVersion,
@@ -29,66 +27,18 @@ import {
} from "../synapse/synapse"; } from "../synapse/synapse";
import storage from "../storage"; import storage from "../storage";
const FormBox = styled(Box)(({ theme }) => ({ export type LoginMethod = "credentials" | "accessToken";
display: "flex",
flexDirection: "column",
minHeight: "calc(100vh - 1rem)",
alignItems: "center",
justifyContent: "flex-start",
background: "url(./images/floating-cogs.svg)",
backgroundColor: "#f9f9f9",
backgroundRepeat: "no-repeat",
backgroundSize: "cover",
[`& .card`]: {
width: "30rem",
marginTop: "6rem",
marginBottom: "6rem",
},
[`& .avatar`]: {
margin: "1rem",
display: "flex",
justifyContent: "center",
},
[`& .icon`]: {
backgroundColor: theme.palette.grey[500],
},
[`& .hint`]: {
marginTop: "1em",
marginBottom: "1em",
display: "flex",
justifyContent: "center",
color: theme.palette.grey[600],
},
[`& .form`]: {
padding: "0 1rem 1rem 1rem",
},
[`& .select`]: {
marginBottom: "2rem",
},
[`& .actions`]: {
padding: "0 1rem 1rem 1rem",
},
[`& .serverVersion`]: {
color: theme.palette.grey[500],
fontFamily: "Roboto, Helvetica, Arial, sans-serif",
marginLeft: "0.5rem",
},
[`& .matrixVersions`]: {
color: theme.palette.grey[500],
fontFamily: "Roboto, Helvetica, Arial, sans-serif",
fontSize: "0.8rem",
marginBottom: "1rem",
marginLeft: "0.5rem",
},
}));
const LoginPage = () => { const LoginPage = () => {
const login = useLogin(); const login = useLogin();
const notify = useNotify(); const notify = useNotify();
const { restrictBaseUrl } = useAppContext(); const { restrictBaseUrl } = useAppContext();
const allowSingleBaseUrl = typeof restrictBaseUrl === "string"; const allowSingleBaseUrl = typeof restrictBaseUrl === "string" && restrictBaseUrl !== "";
const allowMultipleBaseUrls = Array.isArray(restrictBaseUrl); const allowMultipleBaseUrls =
Array.isArray(restrictBaseUrl) &&
restrictBaseUrl.length > 0 &&
restrictBaseUrl[0] !== "" &&
restrictBaseUrl[0] !== null;
const allowAnyBaseUrl = !(allowSingleBaseUrl || allowMultipleBaseUrls); const allowAnyBaseUrl = !(allowSingleBaseUrl || allowMultipleBaseUrls);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [supportPassAuth, setSupportPassAuth] = useState(true); const [supportPassAuth, setSupportPassAuth] = useState(true);
@@ -98,8 +48,13 @@ const LoginPage = () => {
const base_url = allowSingleBaseUrl ? restrictBaseUrl : storage.getItem("base_url"); const base_url = allowSingleBaseUrl ? restrictBaseUrl : storage.getItem("base_url");
const [ssoBaseUrl, setSSOBaseUrl] = useState(""); const [ssoBaseUrl, setSSOBaseUrl] = useState("");
const loginToken = /\?loginToken=([a-zA-Z0-9_-]+)/.exec(window.location.href); const loginToken = /\?loginToken=([a-zA-Z0-9_-]+)/.exec(window.location.href);
const [loginMethod, setLoginMethod] = useState<LoginMethod>("credentials");
useEffect(() => {
if (!loginToken) {
return;
}
if (loginToken) {
const ssoToken = loginToken[1]; const ssoToken = loginToken[1];
console.log("SSO token is", ssoToken); console.log("SSO token is", ssoToken);
// Prevent further requests // Prevent further requests
@@ -127,7 +82,7 @@ const LoginPage = () => {
console.error(error); console.error(error);
}); });
} }
} }, [loginToken]);
const validateBaseUrl = value => { const validateBaseUrl = value => {
if (!value.match(/^(http|https):\/\//)) { if (!value.match(/^(http|https):\/\//)) {
@@ -213,29 +168,53 @@ const LoginPage = () => {
return ( return (
<> <>
<Box> <Tabs
<TextInput value={loginMethod}
autoFocus onChange={(_, newValue) => setLoginMethod(newValue as LoginMethod)}
source="username" indicatorColor="primary"
label="ra.auth.username" textColor="primary"
autoComplete="username" centered
disabled={loading || !supportPassAuth} >
onBlur={handleUsernameChange} <Tab label={translate("synapseadmin.auth.credentials")} value="credentials" />
resettable <Tab label={translate("synapseadmin.auth.access_token")} value="accessToken" />
validate={required()} </Tabs>
/> {loginMethod === "credentials" ? (
</Box> <>
<Box> <Box>
<PasswordInput <TextInput
source="password" autoFocus
label="ra.auth.password" source="username"
type="password" label="ra.auth.username"
autoComplete="current-password" autoComplete="username"
disabled={loading || !supportPassAuth} disabled={loading || !supportPassAuth}
resettable onBlur={handleUsernameChange}
validate={required()} resettable
/> validate={required()}
</Box> />
</Box>
<Box>
<PasswordInput
source="password"
label="ra.auth.password"
type="password"
autoComplete="current-password"
disabled={loading || !supportPassAuth}
resettable
validate={required()}
/>
</Box>
</>
) : (
<Box>
<TextInput
source="accessToken"
label="synapseadmin.auth.access_token"
disabled={loading}
resettable
validate={required()}
/>
</Box>
)}
<Box> <Box>
<TextInput <TextInput
source="base_url" source="base_url"
@@ -263,15 +242,13 @@ const LoginPage = () => {
return ( return (
<Form defaultValues={{ base_url: base_url }} onSubmit={handleSubmit} mode="onTouched"> <Form defaultValues={{ base_url: base_url }} onSubmit={handleSubmit} mode="onTouched">
<FormBox> <LoginFormBox>
<Card className="card"> <Card className="card">
<Box className="avatar"> <Box className="avatar">
{loading ? ( {loading ? (
<CircularProgress size={25} thickness={2} /> <CircularProgress size={25} thickness={2} />
) : ( ) : (
<Avatar className="icon"> <Avatar sx={{ width: "120px", height: "120px" }} src="./images/logo.webp"/>
<LockIcon />
</Avatar>
)} )}
</Box> </Box>
<Box className="hint">{translate("synapseadmin.auth.welcome")}</Box> <Box className="hint">{translate("synapseadmin.auth.welcome")}</Box>
@@ -290,7 +267,7 @@ const LoginPage = () => {
))} ))}
</Select> </Select>
<FormDataConsumer>{formDataProps => <UserData {...formDataProps} />}</FormDataConsumer> <FormDataConsumer>{formDataProps => <UserData {...formDataProps} />}</FormDataConsumer>
<CardActions className="actions"> {loginMethod === "credentials" && <CardActions className="actions">
<Button <Button
variant="contained" variant="contained"
type="submit" type="submit"
@@ -309,10 +286,21 @@ const LoginPage = () => {
> >
{translate("synapseadmin.auth.sso_sign_in")} {translate("synapseadmin.auth.sso_sign_in")}
</Button> </Button>
</CardActions> </CardActions>}
{loginMethod === "accessToken" && <CardActions className="actions">
<Button
variant="contained"
type="submit"
color="primary"
disabled={loading}
fullWidth
>
{translate("ra.auth.sign_in")}
</Button>
</CardActions>}
</Box> </Box>
</Card> </Card>
</FormBox> </LoginFormBox>
<Notification /> <Notification />
</Form> </Form>
); );

View File

@@ -4,9 +4,11 @@ import AutorenewIcon from "@mui/icons-material/Autorenew";
import DestinationsIcon from "@mui/icons-material/CloudQueue"; import DestinationsIcon from "@mui/icons-material/CloudQueue";
import FolderSharedIcon from "@mui/icons-material/FolderShared"; import FolderSharedIcon from "@mui/icons-material/FolderShared";
import ViewListIcon from "@mui/icons-material/ViewList"; import ViewListIcon from "@mui/icons-material/ViewList";
import ErrorIcon from '@mui/icons-material/Error';
import { import {
Button, Button,
Datagrid, Datagrid,
DatagridConfigurable,
DateField, DateField,
List, List,
ListProps, ListProps,
@@ -21,6 +23,7 @@ import {
Tab, Tab,
TabbedShowLayout, TabbedShowLayout,
TextField, TextField,
FunctionField,
TopToolbar, TopToolbar,
useRecordContext, useRecordContext,
useDelete, useDelete,
@@ -35,13 +38,6 @@ import { get } from "lodash";
const DestinationPagination = () => <Pagination rowsPerPageOptions={[10, 25, 50, 100, 500, 1000]} />; const DestinationPagination = () => <Pagination rowsPerPageOptions={[10, 25, 50, 100, 500, 1000]} />;
const destinationRowSx = (record: RaRecord) => ({
backgroundColor: record.retry_last_ts > 0 ? "warning.light" : "primary.contrastText",
"& .MuiButtonBase-root": {
color: "primary.dark",
},
});
const destinationFilters = [<SearchInput source="destination" alwaysOn />]; const destinationFilters = [<SearchInput source="destination" alwaysOn />];
export const DestinationReconnectButton = () => { export const DestinationReconnectButton = () => {
@@ -105,7 +101,22 @@ const RetryDateField = (props: DateFieldProps) => {
return <DateField {...props} />; return <DateField {...props} />;
}; };
const destinationFieldRender = (record: RaRecord) => {
if (record.retry_last_ts > 0) {
return (
<>
<ErrorIcon fontSize="inherit" color="error" sx={{verticalAlign: "middle"}}/>
{record.destination}
</>
);
}
return <> {record.destination} </>;
}
export const DestinationList = (props: ListProps) => { export const DestinationList = (props: ListProps) => {
const record = useRecordContext(props);
return ( return (
<List <List
{...props} {...props}
@@ -113,14 +124,14 @@ export const DestinationList = (props: ListProps) => {
pagination={<DestinationPagination />} pagination={<DestinationPagination />}
sort={{ field: "destination", order: "ASC" }} sort={{ field: "destination", order: "ASC" }}
> >
<Datagrid rowSx={destinationRowSx} rowClick={id => `${id}/show/rooms`} bulkActionButtons={false}> <DatagridConfigurable rowClick={id => `${id}/show/rooms`} bulkActionButtons={false}>
<TextField source="destination" /> <FunctionField source="destination" render={destinationFieldRender} />
<DateField source="failure_ts" showTime options={DATE_FORMAT} /> <DateField source="failure_ts" showTime options={DATE_FORMAT} />
<RetryDateField source="retry_last_ts" showTime options={DATE_FORMAT} /> <RetryDateField source="retry_last_ts" showTime options={DATE_FORMAT} />
<TextField source="retry_interval" /> <TextField source="retry_interval" />
<TextField source="last_successful_stream_ordering" /> <TextField source="last_successful_stream_ordering" />
<DestinationReconnectButton /> <DestinationReconnectButton />
</Datagrid> </DatagridConfigurable>
</List> </List>
); );
}; };

View File

@@ -4,6 +4,7 @@ import {
Create, Create,
CreateProps, CreateProps,
Datagrid, Datagrid,
DatagridConfigurable,
DateField, DateField,
DateTimeInput, DateTimeInput,
Edit, Edit,
@@ -39,13 +40,13 @@ export const RegistrationTokenList = (props: ListProps) => (
pagination={false} pagination={false}
perPage={500} perPage={500}
> >
<Datagrid rowClick="edit"> <DatagridConfigurable rowClick="edit">
<TextField source="token" sortable={false} /> <TextField source="token" sortable={false} />
<NumberField source="uses_allowed" sortable={false} /> <NumberField source="uses_allowed" sortable={false} />
<NumberField source="pending" sortable={false} /> <NumberField source="pending" sortable={false} />
<NumberField source="completed" sortable={false} /> <NumberField source="completed" sortable={false} />
<DateField source="expiry_time" showTime options={DATE_FORMAT} sortable={false} /> <DateField source="expiry_time" showTime options={DATE_FORMAT} sortable={false} />
</Datagrid> </DatagridConfigurable>
</List> </List>
); );

View File

@@ -3,6 +3,7 @@ import ViewListIcon from "@mui/icons-material/ViewList";
import ReportIcon from "@mui/icons-material/Warning"; import ReportIcon from "@mui/icons-material/Warning";
import { import {
Datagrid, Datagrid,
DatagridConfigurable,
DateField, DateField,
DeleteButton, DeleteButton,
List, List,
@@ -22,7 +23,7 @@ import {
} from "react-admin"; } from "react-admin";
import { DATE_FORMAT } from "../components/date"; import { DATE_FORMAT } from "../components/date";
import { MXCField } from "../components/media"; import { ReportMediaContent } from "../components/media";
const ReportPagination = () => <Pagination rowsPerPageOptions={[10, 25, 50, 100, 500, 1000]} />; const ReportPagination = () => <Pagination rowsPerPageOptions={[10, 25, 50, 100, 500, 1000]} />;
@@ -62,7 +63,7 @@ export const ReportShow = (props: ShowProps) => {
<TextField source="event_json.content.msgtype" /> <TextField source="event_json.content.msgtype" />
<TextField source="event_json.content.body" /> <TextField source="event_json.content.body" />
<TextField source="event_json.content.info.mimetype" /> <TextField source="event_json.content.info.mimetype" />
<MXCField source="event_json.content.url" /> <ReportMediaContent source="event_json.content.url" />
<TextField source="event_json.content.format" /> <TextField source="event_json.content.format" />
<TextField source="event_json.content.formatted_body" /> <TextField source="event_json.content.formatted_body" />
<TextField source="event_json.content.algorithm" /> <TextField source="event_json.content.algorithm" />
@@ -90,13 +91,13 @@ const ReportShowActions = () => {
export const ReportList = (props: ListProps) => ( export const ReportList = (props: ListProps) => (
<List {...props} pagination={<ReportPagination />} sort={{ field: "received_ts", order: "DESC" }}> <List {...props} pagination={<ReportPagination />} sort={{ field: "received_ts", order: "DESC" }}>
<Datagrid rowClick="show" bulkActionButtons={false}> <DatagridConfigurable rowClick="show" bulkActionButtons={false}>
<TextField source="id" sortable={false} /> <TextField source="id" sortable={false} />
<DateField source="received_ts" showTime options={DATE_FORMAT} sortable={true} /> <DateField source="received_ts" showTime options={DATE_FORMAT} sortable={true} />
<TextField sortable={false} source="user_id" /> <TextField sortable={false} source="user_id" />
<TextField sortable={false} source="name" /> <TextField sortable={false} source="name" />
<TextField sortable={false} source="score" /> <TextField sortable={false} source="score" />
</Datagrid> </DatagridConfigurable>
</List> </List>
); );

View File

@@ -26,9 +26,9 @@ import {
useUnselectAll, useUnselectAll,
} from "react-admin"; } from "react-admin";
import { useMutation } from "@tanstack/react-query"; import { useMutation } from "@tanstack/react-query";
import AvatarField from "../components/AvatarField"; import AvatarField from "../components/AvatarField";
const RoomDirectoryPagination = () => <Pagination rowsPerPageOptions={[100, 500, 1000, 2000]} />; const RoomDirectoryPagination = () => <Pagination rowsPerPageOptions={[100, 500, 1000, 2000]} />;
export const RoomDirectoryUnpublishButton = (props: DeleteButtonProps) => { export const RoomDirectoryUnpublishButton = (props: DeleteButtonProps) => {
@@ -144,7 +144,6 @@ export const RoomDirectoryList = () => (
> >
<AvatarField <AvatarField
source="avatar_src" source="avatar_src"
sortable={false}
sx={{ height: "40px", width: "40px" }} sx={{ height: "40px", width: "40px" }}
label="resources.rooms.fields.avatar" label="resources.rooms.fields.avatar"
/> />

View File

@@ -47,6 +47,7 @@ import {
} from "./room_directory"; } from "./room_directory";
import { DATE_FORMAT } from "../components/date"; import { DATE_FORMAT } from "../components/date";
import DeleteRoomButton from "../components/DeleteRoomButton"; import DeleteRoomButton from "../components/DeleteRoomButton";
import AvatarField from "../components/AvatarField";
const RoomPagination = () => <Pagination rowsPerPageOptions={[10, 25, 50, 100, 500, 1000]} />; const RoomPagination = () => <Pagination rowsPerPageOptions={[10, 25, 50, 100, 500, 1000]} />;
@@ -90,6 +91,11 @@ export const RoomShow = (props: ShowProps) => {
<Show {...props} actions={<RoomShowActions />} title={<RoomTitle />}> <Show {...props} actions={<RoomShowActions />} title={<RoomTitle />}>
<TabbedShowLayout> <TabbedShowLayout>
<Tab label="synapseadmin.rooms.tabs.basic" icon={<ViewListIcon />}> <Tab label="synapseadmin.rooms.tabs.basic" icon={<ViewListIcon />}>
<AvatarField
source="avatar"
sx={{ height: "120px", width: "120px" }}
label="resources.rooms.fields.avatar"
/>
<TextField source="room_id" /> <TextField source="room_id" />
<TextField source="name" /> <TextField source="name" />
<TextField source="topic" /> <TextField source="topic" />
@@ -181,7 +187,7 @@ export const RoomShow = (props: ShowProps) => {
<Datagrid style={{ width: "100%" }} bulkActionButtons={false}> <Datagrid style={{ width: "100%" }} bulkActionButtons={false}>
<TextField source="type" sortable={false} /> <TextField source="type" sortable={false} />
<DateField source="origin_server_ts" showTime options={DATE_FORMAT} sortable={false} /> <DateField source="origin_server_ts" showTime options={DATE_FORMAT} sortable={false} />
<TextField source="content" sortable={false} /> <FunctionField source="content" sortable={false} render={record => `${JSON.stringify(record.content, null, 2)}`} />
<ReferenceField source="sender" reference="users" sortable={false}> <ReferenceField source="sender" reference="users" sortable={false}>
<TextField source="id" /> <TextField source="id" />
</ReferenceField> </ReferenceField>

View File

@@ -1,6 +1,7 @@
import EqualizerIcon from "@mui/icons-material/Equalizer"; import PermMediaIcon from "@mui/icons-material/PermMedia";
import { import {
Datagrid, Datagrid,
DatagridConfigurable,
ExportButton, ExportButton,
List, List,
ListProps, ListProps,
@@ -37,18 +38,18 @@ export const UserMediaStatsList = (props: ListProps) => (
pagination={<UserMediaStatsPagination />} pagination={<UserMediaStatsPagination />}
sort={{ field: "media_length", order: "DESC" }} sort={{ field: "media_length", order: "DESC" }}
> >
<Datagrid rowClick={id => "/users/" + id + "/media"} bulkActionButtons={false}> <DatagridConfigurable rowClick={id => "/users/" + id + "/media"} bulkActionButtons={false}>
<TextField source="user_id" label="resources.users.fields.id" /> <TextField source="user_id" label="resources.users.fields.id" />
<TextField source="displayname" label="resources.users.fields.displayname" /> <TextField source="displayname" label="resources.users.fields.displayname" />
<NumberField source="media_count" /> <NumberField source="media_count" />
<NumberField source="media_length" /> <NumberField source="media_length" />
</Datagrid> </DatagridConfigurable>
</List> </List>
); );
const resource: ResourceProps = { const resource: ResourceProps = {
name: "user_media_statistics", name: "user_media_statistics",
icon: EqualizerIcon, icon: PermMediaIcon,
list: UserMediaStatsList, list: UserMediaStatsList,
}; };

View File

@@ -7,14 +7,17 @@ import NotificationsIcon from "@mui/icons-material/Notifications";
import PermMediaIcon from "@mui/icons-material/PermMedia"; import PermMediaIcon from "@mui/icons-material/PermMedia";
import PersonPinIcon from "@mui/icons-material/PersonPin"; import PersonPinIcon from "@mui/icons-material/PersonPin";
import SettingsInputComponentIcon from "@mui/icons-material/SettingsInputComponent"; import SettingsInputComponentIcon from "@mui/icons-material/SettingsInputComponent";
import ScienceIcon from "@mui/icons-material/Science";
import LockClockIcon from '@mui/icons-material/LockClock';
import ViewListIcon from "@mui/icons-material/ViewList"; import ViewListIcon from "@mui/icons-material/ViewList";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { Alert, ownerDocument } from "@mui/material"; import { Alert } from "@mui/material";
import { import {
ArrayInput, ArrayInput,
ArrayField, ArrayField,
Button, Button,
Datagrid, Datagrid,
DatagridConfigurable,
DateField, DateField,
Create, Create,
CreateProps, CreateProps,
@@ -36,7 +39,6 @@ import {
ResourceProps, ResourceProps,
SearchInput, SearchInput,
SelectInput, SelectInput,
BulkDeleteButton,
DeleteButton, DeleteButton,
maxLength, maxLength,
regex, regex,
@@ -52,20 +54,26 @@ import {
NumberField, NumberField,
useListContext, useListContext,
useNotify, useNotify,
ToolbarClasses,
Identifier, Identifier,
RaRecord, ToolbarClasses,
ImageInput, ImageInput,
ImageField, ImageField,
FunctionField,
useDataProvider,
} from "react-admin"; } from "react-admin";
import { Link } from "react-router-dom"; import { Link } from "react-router-dom";
import AvatarField from "../components/AvatarField"; import AvatarField from "../components/AvatarField";
import DeleteUserButton from "../components/DeleteUserButton";
import { isASManaged } from "../components/mxid"; import { isASManaged } from "../components/mxid";
import { ServerNoticeButton, ServerNoticeBulkButton } from "../components/ServerNotices"; import { ServerNoticeButton, ServerNoticeBulkButton } from "../components/ServerNotices";
import { DATE_FORMAT } from "../components/date"; import { DATE_FORMAT } from "../components/date";
import { DeviceRemoveButton } from "../components/devices"; import { DeviceRemoveButton } from "../components/devices";
import { MediaIDField, ProtectMediaButton, QuarantineMediaButton } from "../components/media"; import { MediaIDField, ProtectMediaButton, QuarantineMediaButton } from "../components/media";
import { generateRandomPassword } from "../synapse/synapse";
import { useFormContext } from "react-hook-form";
import { ExperimentalFeaturesList } from "../components/ExperimentalFeatures";
import { UserRateLimits } from "../components/UserRateLimits";
const choices_medium = [ const choices_medium = [
{ id: "email", name: "resources.users.email" }, { id: "email", name: "resources.users.email" },
@@ -90,11 +98,6 @@ const UserListActions = () => {
); );
}; };
UserListActions.defaultProps = {
selectedIds: [],
onUnselectItems: () => null,
};
const UserPagination = () => <Pagination rowsPerPageOptions={[10, 25, 50, 100, 500, 1000]} />; const UserPagination = () => <Pagination rowsPerPageOptions={[10, 25, 50, 100, 500, 1000]} />;
const userFilters = [ const userFilters = [
@@ -129,8 +132,6 @@ const UserBulkActionButtons = () => {
const [asManagedUserIsSelected, setAsManagedUserIsSelected] = useState(false); const [asManagedUserIsSelected, setAsManagedUserIsSelected] = useState(false);
const selectedIds = record.selectedIds; const selectedIds = record.selectedIds;
const ownUserId = localStorage.getItem("user_id"); const ownUserId = localStorage.getItem("user_id");
const notify = useNotify();
const translate = useTranslate();
useEffect(() => { useEffect(() => {
setOwnUserIsSelected(selectedIds.includes(ownUserId)); setOwnUserIsSelected(selectedIds.includes(ownUserId));
@@ -141,20 +142,16 @@ const UserBulkActionButtons = () => {
<> <>
<ServerNoticeBulkButton /> <ServerNoticeBulkButton />
<UserPreventSelfDelete ownUserIsSelected={ownUserIsSelected} asManagedUserIsSelected={asManagedUserIsSelected}> <UserPreventSelfDelete ownUserIsSelected={ownUserIsSelected} asManagedUserIsSelected={asManagedUserIsSelected}>
<BulkDeleteButton <DeleteUserButton
label="resources.users.action.erase" selectedIds={selectedIds}
confirmTitle="resources.users.helper.erase" confirmTitle="resources.users.helper.erase"
mutationMode="pessimistic" confirmContent="resources.users.helper.erase_text"
/> />
</UserPreventSelfDelete> </UserPreventSelfDelete>
</> </>
); );
}; };
const usersRowClick = (id: Identifier, resource: string, record: RaRecord): string => {
return `/users/${id}`;
};
export const UserList = (props: ListProps) => ( export const UserList = (props: ListProps) => (
<List <List
{...props} {...props}
@@ -164,7 +161,10 @@ export const UserList = (props: ListProps) => (
actions={<UserListActions />} actions={<UserListActions />}
pagination={<UserPagination />} pagination={<UserPagination />}
> >
<Datagrid rowClick={usersRowClick} bulkActionButtons={<UserBulkActionButtons />}> <DatagridConfigurable
rowClick={(id: Identifier, resource: string) => `/${resource}/${id}`}
bulkActionButtons={<UserBulkActionButtons />}
>
<AvatarField source="avatar_src" sx={{ height: "40px", width: "40px" }} sortBy="avatar_url" /> <AvatarField source="avatar_src" sx={{ height: "40px", width: "40px" }} sortBy="avatar_url" />
<TextField source="id" sortBy="name" /> <TextField source="id" sortBy="name" />
<TextField source="displayname" /> <TextField source="displayname" />
@@ -174,7 +174,7 @@ export const UserList = (props: ListProps) => (
<BooleanField source="locked" /> <BooleanField source="locked" />
<BooleanField source="erased" sortable={false} /> <BooleanField source="erased" sortable={false} />
<DateField source="creation_ts" label="resources.users.fields.creation_ts_ms" showTime options={DATE_FORMAT} /> <DateField source="creation_ts" label="resources.users.fields.creation_ts_ms" showTime options={DATE_FORMAT} />
</Datagrid> </DatagridConfigurable>
</List> </List>
); );
@@ -200,15 +200,15 @@ const UserEditActions = () => {
return ( return (
<TopToolbar> <TopToolbar>
{!record?.deactivated && <ServerNoticeButton />} {!record?.deactivated && <ServerNoticeButton />}
{record && record.id && (
<UserPreventSelfDelete ownUserIsSelected={ownUserIsSelected} asManagedUserIsSelected={asManagedUserIsSelected}> <UserPreventSelfDelete ownUserIsSelected={ownUserIsSelected} asManagedUserIsSelected={asManagedUserIsSelected}>
<DeleteButton <DeleteUserButton
label="resources.users.action.erase" selectedIds={[record?.id]}
confirmTitle={translate("resources.users.helper.erase", { confirmTitle="resources.users.helper.erase"
smart_count: 1, confirmContent="resources.users.helper.erase_text"
})}
mutationMode="pessimistic"
/> />
</UserPreventSelfDelete> </UserPreventSelfDelete>
)}
</TopToolbar> </TopToolbar>
); );
}; };
@@ -216,9 +216,7 @@ const UserEditActions = () => {
export const UserCreate = (props: CreateProps) => ( export const UserCreate = (props: CreateProps) => (
<Create <Create
{...props} {...props}
redirect={(resource, id, data) => { redirect={(resource: string | undefined, id: Identifier | undefined) => `${resource}/${id}`}
return `users/${id}`;
}}
> >
<SimpleForm> <SimpleForm>
<TextInput source="id" autoComplete="off" validate={validateUser} /> <TextInput source="id" autoComplete="off" validate={validateUser} />
@@ -245,6 +243,10 @@ export const UserCreate = (props: CreateProps) => (
const UserTitle = () => { const UserTitle = () => {
const record = useRecordContext(); const record = useRecordContext();
const translate = useTranslate(); const translate = useTranslate();
if (!record) {
return null;
}
let username = record ? (record.displayname ? `"${record.displayname}"` : `"${record.name}"`) : "" let username = record ? (record.displayname ? `"${record.displayname}"` : `"${record.name}"`) : ""
if (isASManaged(record?.id)) { if (isASManaged(record?.id)) {
username += " 🤖"; username += " 🤖";
@@ -303,12 +305,33 @@ const UserBooleanInput = props => {
const UserPasswordInput = props => { const UserPasswordInput = props => {
const record = useRecordContext(); const record = useRecordContext();
let asManagedUserIsSelected = false; let asManagedUserIsSelected = false;
// Get form context to update field value
const form = useFormContext();
if (record) { if (record) {
asManagedUserIsSelected = isASManaged(record.id); asManagedUserIsSelected = isASManaged(record.id);
} }
const generatePassword = () => {
const password = generateRandomPassword();
if (record) {
form.setValue("password", password, { shouldDirty: true });
}
};
return ( return (
<PasswordInput {...props} helperText="resources.users.helper.modify_managed_user_error" disabled={asManagedUserIsSelected} /> <>
<PasswordInput {...props} helperText="resources.users.helper.modify_managed_user_error"
{...(asManagedUserIsSelected ? { disabled: true } : {})}
/>
<Button
variant="outlined"
label="Generate Password"
onClick={generatePassword}
sx={{ marginBottom: "10px" }}
disabled={asManagedUserIsSelected}
/>
</>
); );
}; };
@@ -316,17 +339,26 @@ export const UserEdit = (props: EditProps) => {
const translate = useTranslate(); const translate = useTranslate();
return ( return (
<Edit {...props} title={<UserTitle />} actions={<UserEditActions />} mutationMode="pessimistic"> <Edit {...props} title={<UserTitle />} actions={<UserEditActions />} mutationMode="pessimistic" queryOptions={{
meta: {
include: ["features"] // Tell your dataProvider to include features
}
}}>
<TabbedForm toolbar={<UserEditToolbar />}> <TabbedForm toolbar={<UserEditToolbar />}>
<FormTab label={translate("resources.users.name", { smart_count: 1 })} icon={<PersonPinIcon />}> <FormTab label={translate("resources.users.name", { smart_count: 1 })} icon={<PersonPinIcon />}>
<AvatarField source="avatar_src" sortable={false} sx={{ height: "120px", width: "120px" }} /> <AvatarField source="avatar_src" sx={{ height: "120px", width: "120px" }} />
<BooleanInput source="avatar_erase" label="resources.users.action.erase_avatar" /> <BooleanInput source="avatar_erase" label="resources.users.action.erase_avatar" />
<ImageInput <ImageInput
source="avatar_file" source="avatar_file"
label="resources.users.fields.avatar" label="resources.users.fields.avatar"
accept={{ "image/*": [".png", ".jpg"] }} accept={{ "image/*": [".png", ".jpg"] }}
> >
<ImageField source="src" title="Avatar" /> <ImageField source="src" title="Avatar" sx={{ '& img': {
width: "120px !important",
height: "120px !important",
objectFit: "cover !important",
borderRadius: '50% !important',
}}} />
</ImageInput> </ImageInput>
<TextInput source="id" readOnly /> <TextInput source="id" readOnly />
<TextInput source="displayname" /> <TextInput source="displayname" />
@@ -360,7 +392,7 @@ export const UserEdit = (props: EditProps) => {
<FormTab label={translate("resources.devices.name", { smart_count: 2 })} icon={<DevicesIcon />} path="devices"> <FormTab label={translate("resources.devices.name", { smart_count: 2 })} icon={<DevicesIcon />} path="devices">
<ReferenceManyField reference="devices" target="user_id" label={false}> <ReferenceManyField reference="devices" target="user_id" label={false}>
<Datagrid style={{ width: "100%" }} bulkActionButtons=""> <Datagrid style={{ width: "100%" }} bulkActionButtons={false}>
<TextField source="device_id" sortable={false} /> <TextField source="device_id" sortable={false} />
<TextField source="display_name" sortable={false} /> <TextField source="display_name" sortable={false} />
<TextField source="last_seen_ip" sortable={false} /> <TextField source="last_seen_ip" sortable={false} />
@@ -400,8 +432,8 @@ export const UserEdit = (props: EditProps) => {
<DateField source="created_ts" showTime options={DATE_FORMAT} /> <DateField source="created_ts" showTime options={DATE_FORMAT} />
<DateField source="last_access_ts" showTime options={DATE_FORMAT} /> <DateField source="last_access_ts" showTime options={DATE_FORMAT} />
<NumberField source="media_length" /> <NumberField source="media_length" />
<TextField source="media_type" /> <TextField source="media_type" sx={{ display: "block", width: 200, wordBreak: "break-word" }} />
<TextField source="upload_name" /> <FunctionField source="upload_name" render={record => decodeURIComponent(record.upload_name)} />
<TextField source="quarantined_by" /> <TextField source="quarantined_by" />
<QuarantineMediaButton label="resources.quarantine_media.action.name" /> <QuarantineMediaButton label="resources.quarantine_media.action.name" />
<ProtectMediaButton label="resources.users_media.fields.safe_from_quarantine" /> <ProtectMediaButton label="resources.users_media.fields.safe_from_quarantine" />
@@ -445,6 +477,14 @@ export const UserEdit = (props: EditProps) => {
</Datagrid> </Datagrid>
</ReferenceManyField> </ReferenceManyField>
</FormTab> </FormTab>
<FormTab label="synapseadmin.users.tabs.experimental" icon={<ScienceIcon />} path="experimental">
<ExperimentalFeaturesList />
</FormTab>
<FormTab label="synapseadmin.users.tabs.limits" icon={<LockClockIcon />} path="limits">
<UserRateLimits />
</FormTab>
</TabbedForm> </TabbedForm>
</Edit> </Edit>
); );

View File

@@ -23,14 +23,14 @@ describe("authProvider", () => {
}) })
); );
const ret: undefined = await authProvider.login({ const ret = await authProvider.login({
base_url: "http://example.com", base_url: "http://example.com",
username: "@user:example.com", username: "@user:example.com",
password: "secret", password: "secret",
}); });
expect(ret).toBe(undefined); expect(ret).toEqual({redirectTo: "/"});
expect(fetch).toBeCalledWith("http://example.com/_matrix/client/r0/login", { expect(fetch).toHaveBeenCalledWith("http://example.com/_matrix/client/v3/login", {
body: '{"device_id":null,"initial_device_display_name":"Synapse Admin","type":"m.login.password","identifier":{"type":"m.id.user","user":"@user:example.com"},"password":"secret"}', body: '{"device_id":null,"initial_device_display_name":"Synapse Admin","type":"m.login.password","identifier":{"type":"m.id.user","user":"@user:example.com"},"password":"secret"}',
headers: new Headers({ headers: new Headers({
Accept: "application/json", Accept: "application/json",
@@ -55,13 +55,13 @@ describe("authProvider", () => {
}) })
); );
const ret: undefined = await authProvider.login({ const ret = await authProvider.login({
base_url: "https://example.com/", base_url: "https://example.com/",
loginToken: "login_token", loginToken: "login_token",
}); });
expect(ret).toBe(undefined); expect(ret).toEqual({redirectTo: "/"});
expect(fetch).toHaveBeenCalledWith("https://example.com/_matrix/client/r0/login", { expect(fetch).toHaveBeenCalledWith("https://example.com/_matrix/client/v3/login", {
body: '{"device_id":null,"initial_device_display_name":"Synapse Admin","type":"m.login.token","token":"login_token"}', body: '{"device_id":null,"initial_device_display_name":"Synapse Admin","type":"m.login.token","token":"login_token"}',
headers: new Headers({ headers: new Headers({
Accept: "application/json", Accept: "application/json",
@@ -83,7 +83,7 @@ describe("authProvider", () => {
await authProvider.logout(null); await authProvider.logout(null);
expect(fetch).toBeCalledWith("example.com/_matrix/client/r0/logout", { expect(fetch).toHaveBeenCalledWith("example.com/_matrix/client/v3/logout", {
headers: new Headers({ headers: new Headers({
Accept: "application/json", Accept: "application/json",
Authorization: "Bearer foo", Authorization: "Bearer foo",
@@ -123,7 +123,9 @@ describe("authProvider", () => {
describe("getPermissions", () => { describe("getPermissions", () => {
it("should do nothing", async () => { it("should do nothing", async () => {
await expect(authProvider.getPermissions(null)).resolves.toBeUndefined(); if (authProvider.getPermissions) {
await expect(authProvider.getPermissions(null)).resolves.toBeUndefined();
}
}); });
}); });
}); });

View File

@@ -1,7 +1,9 @@
import { AuthProvider, HttpError, Options, fetchUtils, useTranslate } from "react-admin"; import { AuthProvider, HttpError, Options, fetchUtils } from "react-admin";
import storage from "../storage"; import storage from "../storage";
import { MatrixError, displayError } from "../components/error"; import { MatrixError, displayError } from "../components/error";
import { fetchAuthenticatedMedia } from "../utils/fetchMedia";
import { ClearConfig } from "../components/config";
const authProvider: AuthProvider = { const authProvider: AuthProvider = {
// called when the user attempts to log in // called when the user attempts to log in
@@ -10,14 +12,16 @@ const authProvider: AuthProvider = {
username, username,
password, password,
loginToken, loginToken,
accessToken,
}: { }: {
base_url: string; base_url: string;
username: string; username: string;
password: string; password: string;
loginToken: string; loginToken: string;
accessToken: string;
}) => { }) => {
console.log("login "); console.log("login ");
const options: Options = { let options: Options = {
method: "POST", method: "POST",
body: JSON.stringify( body: JSON.stringify(
Object.assign( Object.assign(
@@ -55,11 +59,30 @@ const authProvider: AuthProvider = {
storage.setItem("base_url", base_url); storage.setItem("base_url", base_url);
const decoded_base_url = window.decodeURIComponent(base_url); const decoded_base_url = window.decodeURIComponent(base_url);
const login_api_url = decoded_base_url + "/_matrix/client/r0/login"; let login_api_url = decoded_base_url + (accessToken ? "/_matrix/client/v3/account/whoami" : "/_matrix/client/v3/login");
let response; let response;
try { try {
if (accessToken) {
// this a login with an already obtained access token, let's just validate it
options = {
headers: new Headers({
Accept: 'application/json',
Authorization: `Bearer ${accessToken}`,
}),
};
}
response = await fetchUtils.fetchJson(login_api_url, options); response = await fetchUtils.fetchJson(login_api_url, options);
const json = response.json;
storage.setItem("home_server", accessToken ? json.user_id.split(":")[1] : json.home_server);
storage.setItem("user_id", json.user_id);
storage.setItem("access_token", accessToken ? accessToken : json.access_token);
storage.setItem("device_id", json.device_id);
storage.setItem("login_type", accessToken ? "accessToken" : "credentials");
return Promise.resolve({redirectTo: "/"});
} catch(err) { } catch(err) {
const error = err as HttpError; const error = err as HttpError;
const errorStatus = error.status; const errorStatus = error.status;
@@ -71,20 +94,51 @@ const authProvider: AuthProvider = {
errMsg, errMsg,
errorStatus, errorStatus,
) )
); );
}
},
getIdentity: async () => {
const access_token = storage.getItem("access_token");
const user_id = storage.getItem("user_id");
const base_url = storage.getItem("base_url");
if (typeof access_token !== "string" || typeof user_id !== "string" || typeof base_url !== "string") {
return Promise.reject();
} }
const json = response.json; const options: Options = {
storage.setItem("home_server", json.home_server); headers: new Headers({
storage.setItem("user_id", json.user_id); Accept: "application/json",
storage.setItem("access_token", json.access_token); Authorization: `Bearer ${access_token}`,
storage.setItem("device_id", json.device_id); }),
};
const whoami_api_url = base_url + `/_matrix/client/v3/profile/${user_id}`;
try {
let avatar_url = "";
const response = await fetchUtils.fetchJson(whoami_api_url, options);
if (response.json.avatar_url) {
const mediaresp = await fetchAuthenticatedMedia(response.json.avatar_url, "thumbnail");
const blob = await mediaresp.blob();
avatar_url = URL.createObjectURL(blob);
}
return Promise.resolve({
id: user_id,
fullName: response.json.displayname,
avatar: avatar_url,
});
} catch (err) {
console.log("Error getting identity", err);
return Promise.reject();
}
}, },
// called when the user clicks on the logout button // called when the user clicks on the logout button
logout: async () => { logout: async () => {
console.log("logout"); console.log("logout");
const logout_api_url = storage.getItem("base_url") + "/_matrix/client/r0/logout"; const logout_api_url = storage.getItem("base_url") + "/_matrix/client/v3/logout";
const access_token = storage.getItem("access_token"); const access_token = storage.getItem("access_token");
const options: Options = { const options: Options = {
@@ -96,8 +150,13 @@ const authProvider: AuthProvider = {
}; };
if (typeof access_token === "string") { if (typeof access_token === "string") {
await fetchUtils.fetchJson(logout_api_url, options); try {
storage.removeItem("access_token"); await fetchUtils.fetchJson(logout_api_url, options);
} catch (err) {
console.log("Error logging out", err);
} finally {
ClearConfig();
}
} }
}, },
// called when the API returns an error // called when the API returns an error

View File

@@ -1,6 +1,7 @@
import { import {
DataProvider, DataProvider,
DeleteParams, DeleteParams,
DeleteManyParams,
HttpError, HttpError,
Identifier, Identifier,
Options, Options,
@@ -41,21 +42,16 @@ const jsonClient = async (url: string, options: Options = {}) => {
} }
}; };
const mxcUrlToHttp = (mxcUrl: string) => {
const homeserver = storage.getItem("base_url");
const re = /^mxc:\/\/([^/]+)\/(\w+)/;
const ret = re.exec(mxcUrl);
console.log("mxcClient " + ret);
if (ret == null) return null;
const serverName = ret[1];
const mediaId = ret[2];
return `${homeserver}/_matrix/media/r0/thumbnail/${serverName}/${mediaId}?width=24&height=24&method=scale`;
};
const filterUndefined = (obj: Record<string, any>) => { const filterUndefined = (obj: Record<string, any>) => {
return Object.fromEntries(Object.entries(obj).filter(([key, value]) => value !== undefined)); return Object.fromEntries(Object.entries(obj).filter(([key, value]) => value !== undefined));
}; };
interface Action {
endpoint: string;
method?: string;
body?: Record<string, any>;
}
interface Room { interface Room {
room_id: string; room_id: string;
name?: string; name?: string;
@@ -252,18 +248,32 @@ export interface UploadMediaResult {
content_uri: string; content_uri: string;
} }
export interface ExperimentalFeaturesModel {
features: {
[key: string]: boolean;
};
}
export interface RateLimitsModel {
messages_per_second?: number;
burst_count?: number;
}
export interface SynapseDataProvider extends DataProvider { export interface SynapseDataProvider extends DataProvider {
deleteMedia: (params: DeleteMediaParams) => Promise<DeleteMediaResult>; deleteMedia: (params: DeleteMediaParams) => Promise<DeleteMediaResult>;
uploadMedia: (params: UploadMediaParams) => Promise<UploadMediaResult>; uploadMedia: (params: UploadMediaParams) => Promise<UploadMediaResult>;
updateFeatures: (id: Identifier, features: ExperimentalFeaturesModel) => Promise<void>;
getRateLimits: (id: Identifier) => Promise<RateLimitsModel>;
setRateLimits: (id: Identifier, rateLimits: RateLimitsModel) => Promise<void>;
} }
const resourceMap = { const resourceMap = {
users: { users: {
path: "/_synapse/admin/v2/users", path: "/_synapse/admin/v2/users",
map: (u: User) => ({ map: async (u: User) => ({
...u, ...u,
id: returnMXID(u.name), id: returnMXID(u.name),
avatar_src: u.avatar_url ? mxcUrlToHttp(u.avatar_url) : undefined, avatar_src: u.avatar_url ? u.avatar_url : undefined,
is_guest: !!u.is_guest, is_guest: !!u.is_guest,
admin: !!u.admin, admin: !!u.admin,
deactivated: !!u.deactivated, deactivated: !!u.deactivated,
@@ -451,7 +461,7 @@ const resourceMap = {
id: rd.room_id, id: rd.room_id,
public: !!rd.public, public: !!rd.public,
guest_access: !!rd.guest_access, guest_access: !!rd.guest_access,
avatar_src: rd.avatar_url ? mxcUrlToHttp(rd.avatar_url) : undefined, avatar_src: rd.avatar_url ? rd.avatar_url : undefined,
}), }),
data: "chunk", data: "chunk",
total: json => json.total_room_count_estimate, total: json => json.total_room_count_estimate,
@@ -557,8 +567,10 @@ const baseDataProvider: SynapseDataProvider = {
const url = `${endpoint_url}?${new URLSearchParams(filterUndefined(query)).toString()}`; const url = `${endpoint_url}?${new URLSearchParams(filterUndefined(query)).toString()}`;
const { json } = await jsonClient(url); const { json } = await jsonClient(url);
const formattedData = await json[res.data].map(res.map);
return { return {
data: json[res.data].map(res.map), data: formattedData,
total: res.total(json, from, perPage), total: res.total(json, from, perPage),
}; };
}, },
@@ -577,13 +589,28 @@ const baseDataProvider: SynapseDataProvider = {
getMany: async (resource, params) => { getMany: async (resource, params) => {
console.log("getMany " + resource); console.log("getMany " + resource);
const homeserver = storage.getItem("base_url"); const base_url = storage.getItem("base_url");
if (!homeserver || !(resource in resourceMap)) throw Error("Homerserver not set"); const homeserver = storage.getItem("home_server");
if (!base_url || !(resource in resourceMap)) throw Error("base_url not set");
const res = resourceMap[resource]; const res = resourceMap[resource];
const endpoint_url = homeserver + res.path; const endpoint_url = base_url + res.path;
const responses = await Promise.all(params.ids.map(id => jsonClient(`${endpoint_url}/${encodeURIComponent(id)}`))); const responses = await Promise.all(params.ids.map(id => {
// edge case: when user is external / federated, homeserver will return error, as querying external users via
// /_synapse/admin/v2/users is not allowed.
// That leads to an issue when a user is referenced (e.g., in room state datagrid) - the user cell is just empty.
// To avoid that, we fake the response with one specific field (name) which is used in the datagrid.
if (homeserver && resource === "users") {
if (!(<string>id).endsWith(homeserver)) {
const json = {
name: id,
};
return Promise.resolve({ json });
}
}
return jsonClient(`${endpoint_url}/${encodeURIComponent(id)}`);
}));
return { return {
data: responses.map(({ json }) => res.map(json)), data: responses.map(({ json }) => res.map(json)),
total: responses.length, total: responses.length,
@@ -714,7 +741,7 @@ const baseDataProvider: SynapseDataProvider = {
}, },
deleteMany: async (resource, params) => { deleteMany: async (resource, params) => {
console.log("deleteMany " + resource); console.log("deleteMany " + resource, "params", params);
const homeserver = storage.getItem("base_url"); const homeserver = storage.getItem("base_url");
if (!homeserver || !(resource in resourceMap)) throw Error("Homeserver not set"); if (!homeserver || !(resource in resourceMap)) throw Error("Homeserver not set");
@@ -731,6 +758,7 @@ const baseDataProvider: SynapseDataProvider = {
}); });
}) })
); );
return { return {
data: responses.map(({ json }) => json), data: responses.map(({ json }) => json),
}; };
@@ -784,6 +812,28 @@ const baseDataProvider: SynapseDataProvider = {
}); });
return json as UploadMediaResult; return json as UploadMediaResult;
}, },
getFeatures: async (id: Identifier) => {
const base_url = storage.getItem("base_url");
const endpoint_url = `${base_url}/_synapse/admin/v1/experimental_features/${encodeURIComponent(returnMXID(id))}`;
const { json } = await jsonClient(endpoint_url);
return json.features as ExperimentalFeaturesModel;
},
updateFeatures: async (id: Identifier, features: ExperimentalFeaturesModel) => {
const base_url = storage.getItem("base_url");
const endpoint_url = `${base_url}/_synapse/admin/v1/experimental_features/${encodeURIComponent(returnMXID(id))}`;
await jsonClient(endpoint_url, { method: "PUT", body: JSON.stringify({ features }) });
},
getRateLimits: async (id: Identifier) => {
const base_url = storage.getItem("base_url");
const endpoint_url = `${base_url}/_synapse/admin/v1/users/${encodeURIComponent(returnMXID(id))}/override_ratelimit`;
const { json } = await jsonClient(endpoint_url);
return json as RateLimitsModel;
},
setRateLimits: async (id: Identifier, rateLimits: RateLimitsModel) => {
const base_url = storage.getItem("base_url");
const endpoint_url = `${base_url}/_synapse/admin/v1/users/${encodeURIComponent(returnMXID(id))}/override_ratelimit`;
await jsonClient(endpoint_url, { method: "POST", body: JSON.stringify(rateLimits) });
},
}; };
const dataProvider = withLifecycleCallbacks(baseDataProvider, [ const dataProvider = withLifecycleCallbacks(baseDataProvider, [
@@ -792,6 +842,12 @@ const dataProvider = withLifecycleCallbacks(baseDataProvider, [
beforeUpdate: async (params: UpdateParams<any>, dataProvider: DataProvider) => { beforeUpdate: async (params: UpdateParams<any>, dataProvider: DataProvider) => {
const avatarFile = params.data.avatar_file?.rawFile; const avatarFile = params.data.avatar_file?.rawFile;
const avatarErase = params.data.avatar_erase; const avatarErase = params.data.avatar_erase;
const rates = params.data.rates;
if (rates) {
await dataProvider.setRateLimits(params.id, rates);
delete params.data.rates;
}
if (avatarErase) { if (avatarErase) {
params.data.avatar_url = ""; params.data.avatar_url = "";
@@ -808,6 +864,39 @@ const dataProvider = withLifecycleCallbacks(baseDataProvider, [
} }
return params; return params;
}, },
beforeDelete: async (params: DeleteParams<any>, dataProvider: DataProvider) => {
if (params.meta?.deleteMedia) {
const base_url = storage.getItem("base_url");
const endpoint_url = `${base_url}/_synapse/admin/v1/users/${encodeURIComponent(returnMXID(params.id))}/media`;
await jsonClient(endpoint_url, { method: "DELETE" });
}
if (params.meta?.redactEvents) {
const base_url = storage.getItem("base_url");
const endpoint_url = `${base_url}/_synapse/admin/v1/user/${encodeURIComponent(returnMXID(params.id))}/redact`;
await jsonClient(endpoint_url, { method: "POST", body: JSON.stringify({ rooms: [] }) });
}
return params;
},
beforeDeleteMany: async (params: DeleteManyParams<any>, dataProvider: DataProvider) => {
await Promise.all(
params.ids.map(async id => {
if (params.meta?.deleteMedia) {
const base_url = storage.getItem("base_url");
const endpoint_url = `${base_url}/_synapse/admin/v1/users/${encodeURIComponent(returnMXID(id))}/media`;
await jsonClient(endpoint_url, { method: "DELETE" });
}
if (params.meta?.redactEvents) {
const base_url = storage.getItem("base_url");
const endpoint_url = `${base_url}/_synapse/admin/v1/user/${encodeURIComponent(returnMXID(id))}/redact`;
await jsonClient(endpoint_url, { method: "POST", body: JSON.stringify({ rooms: [] }) });
}
})
);
return params;
},
}, },
]); ]);

View File

@@ -54,11 +54,6 @@ export const getSupportedLoginFlows = async baseUrl => {
return response.json.flows; return response.json.flows;
}; };
export const getMediaUrl = media_id => {
const baseUrl = storage.getItem("base_url");
return `${baseUrl}/_matrix/media/v1/download/${media_id}?allow_redirect=true`;
};
/** /**
* Generate a random MXID for current homeserver * Generate a random MXID for current homeserver
* @returns full MXID as string * @returns full MXID as string
@@ -96,8 +91,8 @@ export function returnMXID(input: string | Identifier): string {
* Generate a random user password * Generate a random user password
* @returns a new random password as string * @returns a new random password as string
*/ */
export function generateRandomPassword(length = 20): string { export function generateRandomPassword(length = 64): string {
const characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~!@-#$"; const characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~`!@#$%^&*()_-+={[}]|:;'.?/<>,";
return Array.from(crypto.getRandomValues(new Uint32Array(length))) return Array.from(crypto.getRandomValues(new Uint32Array(length)))
.map(x => characters[x % characters.length]) .map(x => characters[x % characters.length])
.join(""); .join("");

43
src/utils/fetchMedia.ts Normal file
View File

@@ -0,0 +1,43 @@
import storage from "../storage";
export const getServerAndMediaIdFromMxcUrl = (mxcUrl: string): { serverName: string, mediaId: string } => {
const re = /^mxc:\/\/([^/]+)\/(\w+)/;
const ret = re.exec(mxcUrl);
console.log("mxcClient " + ret);
if (ret == null) {
throw new Error("Invalid mxcUrl");
}
const serverName = ret[1];
const mediaId = ret[2];
return { serverName, mediaId };
};
export type MediaType = "thumbnail" | "original";
export const fetchAuthenticatedMedia = async (mxcUrl: string, type: MediaType): Promise<Response> => {
const homeserver = storage.getItem("base_url");
const accessToken = storage.getItem("access_token");
const { serverName, mediaId } = getServerAndMediaIdFromMxcUrl(mxcUrl);
if (!serverName || !mediaId) {
throw new Error("Invalid mxcUrl");
}
let url = "";
if (type === "thumbnail") {
// ref: https://spec.matrix.org/latest/client-server-api/#thumbnails
url = `${homeserver}/_matrix/client/v1/media/thumbnail/${serverName}/${mediaId}?width=320&height=240&method=scale`;
} else if (type === "original") {
url = `${homeserver}/_matrix/client/v1/media/download/${serverName}/${mediaId}`;
} else {
throw new Error("Invalid authenticated media type");
}
const response = await fetch(`${url}`, {
headers: {
authorization: `Bearer ${accessToken}`,
},
});
return response;
};

View File

@@ -5,13 +5,41 @@ import { defineConfig } from "vite";
export default defineConfig({ export default defineConfig({
base: "./", base: "./",
build: {
target: "esnext",
},
plugins: [ plugins: [
react(), react(),
vitePluginVersionMark({ vitePluginVersionMark({
command: "git describe --tags || git rev-parse --short HEAD", name: "Synapse Admin",
ifMeta: true, command: 'git describe --tags || git rev-parse --short HEAD || echo "${SYNAPSE_ADMIN_VERSION:-unknown}"',
ifLog: true, ifMeta: false,
ifLog: false,
ifGlobal: true, ifGlobal: true,
outputFile: (version) => ({
path: "manifest.json",
content: JSON.stringify({
name: "Synapse Admin",
version: version,
description: "Synapse Admin is an admin console for synapse Matrix homeserver with additional features.",
categories: ["productivity", "utilities"],
orientation: "landscape",
icons: [{
src: "favicon.ico",
sizes: "32x32",
type: "image/x-icon"
},{
src: "images/logo.webp",
sizes: "512x512",
type: "image/webp",
purpose: "any maskable"
}],
start_url: ".",
display: "standalone",
theme_color: "#000000",
background_color: "#ffffff"
}),
}),
}), }),
], ],
}); });

1230
yarn.lock

File diff suppressed because it is too large Load Diff