211 Commits

Author SHA1 Message Date
d6749b413a 更新 'src/synapse/dataProvider.js' 2022-07-09 15:20:06 +08:00
d8df2fa2e8 更新 'src/synapse/dataProvider.js' 2022-07-09 14:54:05 +08:00
cef7e31cb2 更新 'src/i18n/zh.js' 2022-07-09 14:37:58 +08:00
b2d1dc0be1 更新 'src/components/users.js' 2022-07-09 14:34:45 +08:00
72bc40f322 更新 'src/synapse/dataProvider.js' 2022-07-09 14:25:55 +08:00
44b9aca138 更新 'src/synapse/dataProvider.js' 2022-07-09 14:21:33 +08:00
ab673a91a1 更新 'src/components/rooms.js' 2022-07-09 14:20:08 +08:00
e2ecf90f66 更新 'src/components/users.js' 2022-07-09 14:18:20 +08:00
1ac7d8d87b 更新 'src/App.js' 2022-07-09 14:16:28 +08:00
7914caa70e 更新 'src/components/users.js' 2022-07-09 14:15:10 +08:00
24952cba56 更新 'src/synapse/dataProvider.js' 2022-07-09 14:13:50 +08:00
6f26a31604 更新 'src/synapse/dataProvider.js' 2022-07-09 14:10:09 +08:00
dbb9a7f547 更新 'src/components/users.js' 2022-07-09 14:07:42 +08:00
705244b4fc 更新 'src/synapse/dataProvider.js' 2022-07-09 11:05:56 +08:00
46259d3740 更新 'src/synapse/dataProvider.js' 2022-07-09 10:43:40 +08:00
4772083040 更新 'src/synapse/dataProvider.js' 2022-07-09 10:23:28 +08:00
61e4444727 更新 'src/synapse/dataProvider.js' 2022-07-09 10:20:21 +08:00
df57f5f908 更新 'src/synapse/dataProvider.js' 2022-07-09 10:12:46 +08:00
94d8bb2772 更新 'src/components/users.js' 2022-07-09 10:10:43 +08:00
e6f7f1d591 更新 'src/synapse/dataProvider.js' 2022-07-09 10:09:12 +08:00
de7e8d1ff3 更新 'src/App.js' 2022-07-09 10:05:50 +08:00
317de6ce80 更新 'src/components/users.js' 2022-07-09 10:04:54 +08:00
f74249073a 更新 'src/synapse/dataProvider.js' 2022-07-09 10:04:05 +08:00
33dcd46f74 更新 'src/components/users.js' 2022-07-09 09:59:13 +08:00
2ab4ab66e3 更新 'src/components/users.js' 2022-07-09 09:56:42 +08:00
3410deb510 更新 'src/components/users.js' 2022-07-09 09:44:42 +08:00
b1c35b670f 更新 'src/components/rooms.js' 2022-07-09 09:44:34 +08:00
39dea09895 更新 'src/components/users.js' 2022-07-09 09:26:50 +08:00
8804bdc94d 更新 'src/i18n/zh.js' 2022-07-09 08:22:08 +08:00
36bf2dff3e 更新 'src/synapse/dataProvider.js' 2022-07-07 12:01:58 +08:00
0958f376a9 更新 'src/synapse/dataProvider.js' 2022-07-07 11:59:08 +08:00
f287555d53 更新 'src/App.js' 2022-07-07 11:56:24 +08:00
b66a4596e4 更新 'src/components/rooms.js' 2022-07-07 11:54:31 +08:00
4ff83bf261 更新 'src/synapse/dataProvider.js' 2022-07-07 11:48:21 +08:00
c79453f4f4 更新 'src/components/rooms.js' 2022-07-07 11:12:09 +08:00
149c8590c2 更新 'src/synapse/dataProvider.js' 2022-07-07 11:08:21 +08:00
eefd5796d0 更新 'src/components/rooms.js' 2022-07-07 09:48:03 +08:00
2b712e5bd9 更新 'src/components/rooms.js' 2022-07-07 09:46:28 +08:00
26014820dc 更新 'src/components/rooms.js' 2022-07-07 09:43:48 +08:00
fbb82c99a5 更新 'src/i18n/zh.js' 2022-07-07 09:43:38 +08:00
27655602da 更新 'src/components/rooms.js' 2022-07-07 09:38:16 +08:00
dcf6dbe8ae 更新 'src/components/users.js' 2022-07-06 21:30:37 +08:00
216a23cbb2 更新 'src/components/users.js' 2022-07-06 21:27:18 +08:00
e83087444c 更新 'src/components/users.js' 2022-07-06 21:25:53 +08:00
07bb80a1e6 更新 'src/components/users.js' 2022-07-06 21:22:07 +08:00
fdb43c9193 更新 'src/components/users.js' 2022-07-06 21:18:37 +08:00
2c002afe8e 更新 'src/synapse/dataProvider.js' 2022-07-06 21:17:43 +08:00
29aa686e70 更新 'src/components/users.js' 2022-07-06 21:15:49 +08:00
edd7f12e5d 更新 'src/synapse/dataProvider.js' 2022-07-06 20:40:23 +08:00
c5b73a222c 更新 'src/synapse/dataProvider.js' 2022-07-06 20:33:36 +08:00
5b6edfbf11 更新 'src/synapse/dataProvider.js' 2022-07-06 20:31:49 +08:00
573857ed4a 更新 'src/components/users.js' 2022-07-06 20:30:51 +08:00
9b1e3dbfd2 更新 'src/components/users.js' 2022-07-06 20:26:42 +08:00
e78c2bedaa 更新 'src/i18n/zh.js' 2022-07-06 20:23:16 +08:00
0872e31411 更新 'src/components/users.js' 2022-07-06 20:18:36 +08:00
84a253f50b 更新 'src/components/users.js' 2022-07-06 20:16:25 +08:00
0726dc788d 更新 'src/components/users.js' 2022-07-06 20:08:09 +08:00
b9501c77f0 更新 'src/i18n/zh.js' 2022-07-06 20:04:17 +08:00
558ed60bb4 更新 'src/i18n/zh.js' 2022-07-06 19:54:36 +08:00
2197356a1e 更新 'src/i18n/zh.js' 2022-07-06 19:52:29 +08:00
96c718e45f 更新 'src/i18n/zh.js' 2022-07-06 19:51:11 +08:00
339848e117 更新 'src/i18n/zh.js' 2022-07-06 19:44:06 +08:00
7faf321346 更新 'src/i18n/zh.js' 2022-07-06 19:41:37 +08:00
5cdd110bf1 更新 'src/i18n/zh.js' 2022-07-06 19:35:31 +08:00
9a05dfee7a 更新 'src/i18n/zh.js' 2022-07-06 19:29:08 +08:00
9110a8ac99 更新 'README.md' 2022-07-06 17:19:07 +08:00
Dirk Klimpel
0b153ddcbb Update README.md
Co-authored-by: Dominik Fuchß <develop@fuchss.org>
2022-05-23 14:07:49 +02:00
Dirk Klimpel
784c284723 Add note to GH pages 2022-05-23 14:07:49 +02:00
dependabot[bot]
e5f73ea8b4 Bump minimist from 1.2.5 to 1.2.6
Bumps [minimist](https://github.com/substack/minimist) from 1.2.5 to 1.2.6.
- [Release notes](https://github.com/substack/minimist/releases)
- [Commits](https://github.com/substack/minimist/compare/1.2.5...1.2.6)

---
updated-dependencies:
- dependency-name: minimist
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-05-23 14:07:01 +02:00
dependabot[bot]
96551259c5 Bump cross-fetch from 3.1.4 to 3.1.5
Bumps [cross-fetch](https://github.com/lquixada/cross-fetch) from 3.1.4 to 3.1.5.
- [Release notes](https://github.com/lquixada/cross-fetch/releases)
- [Commits](https://github.com/lquixada/cross-fetch/compare/v3.1.4...v3.1.5)

---
updated-dependencies:
- dependency-name: cross-fetch
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-05-23 14:06:50 +02:00
dependabot[bot]
b2fa533ef0 Bump async from 2.6.3 to 2.6.4
Bumps [async](https://github.com/caolan/async) from 2.6.3 to 2.6.4.
- [Release notes](https://github.com/caolan/async/releases)
- [Changelog](https://github.com/caolan/async/blob/v2.6.4/CHANGELOG.md)
- [Commits](https://github.com/caolan/async/compare/v2.6.3...v2.6.4)

---
updated-dependencies:
- dependency-name: async
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-05-23 14:06:40 +02:00
Leon Schmidt
7aa0f9f50d Make PUBLIC_URL and REACT_APP_SERVER configurable (#266)
* Adjust Dockerfile to include args in build process
* Adjust README.md
2022-05-23 14:06:04 +02:00
Dirk Klimpel
5aa90c25f7 Add path to rooms tab "members" (#232) 2022-03-22 19:11:12 +01:00
dependabot[bot]
38d58db08d Bump url-parse from 1.5.7 to 1.5.10 (#253)
Bumps [url-parse](https://github.com/unshiftio/url-parse) from 1.5.7 to 1.5.10.
- [Release notes](https://github.com/unshiftio/url-parse/releases)
- [Commits](https://github.com/unshiftio/url-parse/compare/1.5.7...1.5.10)

---
updated-dependencies:
- dependency-name: url-parse
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-03-22 18:17:18 +01:00
Dirk Klimpel
e637df232a Upgrade react-admin to ^3.19.7 (#241) 2022-03-22 18:13:01 +01:00
Dirk Klimpel
d97c633cd0 Remove not needed {" "} from EventReports (#235) 2022-03-22 17:59:48 +01:00
Dirk Klimpel
b02396c61f disableReordering in users' SimpleFormIterator (#219) 2022-03-22 17:58:28 +01:00
Michael Albert
95de50b925 Bump version to 0.8.5
Change-Id: I8c8f0af01d693bb76dbf706a92fdd4dfa6ba9a8b
2022-02-17 20:56:27 +01:00
dependabot[bot]
1a150a10fd Bump url-parse from 1.5.3 to 1.5.7 (#244)
Bumps [url-parse](https://github.com/unshiftio/url-parse) from 1.5.3 to 1.5.7.
- [Release notes](https://github.com/unshiftio/url-parse/releases)
- [Commits](https://github.com/unshiftio/url-parse/compare/1.5.3...1.5.7)

---
updated-dependencies:
- dependency-name: url-parse
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-02-17 20:53:56 +01:00
Dirk Klimpel
158e7dbe98 Move date format to a constant in EventReports.js (#237) 2022-02-17 20:52:13 +01:00
Dirk Klimpel
a642f11503 Fix typo notification in german language file (#233) 2022-02-17 20:51:42 +01:00
Dirk Klimpel
888a3f001b Move date format to a constant in rooms.js (#238) 2022-02-17 20:51:11 +01:00
Dirk Klimpel
4b0845bee8 Move date format to a constant in users.js (#223)
* Move date format to a constant in `users.js`

* yarn prettier
2022-02-17 20:50:38 +01:00
Dirk Klimpel
f449e3277a Replace deprecated fade in devices.js (#220) 2022-02-17 20:49:34 +01:00
Dirk Klimpel
3303f253b4 Replace deprecated fade in media.js (#221) 2022-02-17 20:49:19 +01:00
dependabot[bot]
0250954ee7 Bump follow-redirects from 1.14.7 to 1.14.8 (#243)
Bumps [follow-redirects](https://github.com/follow-redirects/follow-redirects) from 1.14.7 to 1.14.8.
- [Release notes](https://github.com/follow-redirects/follow-redirects/releases)
- [Commits](https://github.com/follow-redirects/follow-redirects/compare/v1.14.7...v1.14.8)

---
updated-dependencies:
- dependency-name: follow-redirects
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-02-17 20:45:37 +01:00
Dirk Klimpel
efed8b2774 Add token based registration creation and management (#200)
* Add token based registration creation and management

* yarn fix

* Apply suggestions from code review

Remove empty line

* move date to `const date_format`
2022-02-17 20:45:21 +01:00
Nya Candy
c891afa611 feat: support SSO login (#196)
* feat: support SSO login

* fix: lint

* fix: add back homeserver force protection

* fix: add back login notice

* fix: simplify login options
2022-02-17 20:24:46 +01:00
Michael Albert
38541b8f02 Fix english translation for room deletion
Change-Id: I5bb02e64832902a79379d66c77d3128169d3fca8
2022-02-17 20:15:49 +01:00
Dirk Klimpel
0f4c382c18 Remove not needed translation backtolist (#208) 2022-01-31 17:50:14 +01:00
Dirk Klimpel
b90d4ef00f Add more headlines for installation to README (#216) 2022-01-31 17:39:18 +01:00
Dominik Fuchß
3fb33facc5 GitHub Pages Deploy (#189)
* Create edge_ghpage.yml

Added Build and Deploy Edge version to GH Pages

* Update edge_ghpage.yml

Added missing node setup

* Update edge_ghpage.yml

Restrict building of GH Pages to main / master branch & workflow dispatch

* Update .github/workflows/edge_ghpage.yml

Co-authored-by: Dirk Klimpel <5740567+dklimpel@users.noreply.github.com>

* Update .github/workflows/edge_ghpage.yml

Co-authored-by: Dirk Klimpel <5740567+dklimpel@users.noreply.github.com>

* Update .github/workflows/edge_ghpage.yml

Co-authored-by: Dirk Klimpel <5740567+dklimpel@users.noreply.github.com>

* Update .github/workflows/edge_ghpage.yml

Co-authored-by: Dirk Klimpel <5740567+dklimpel@users.noreply.github.com>

Co-authored-by: Dirk Klimpel <5740567+dklimpel@users.noreply.github.com>
2022-01-31 17:38:34 +01:00
Dirk Klimpel
c4a68ff1d5 Fix typo in .prettierrc (#224) 2022-01-31 17:24:37 +01:00
dependabot[bot]
c4f0fa48ec Bump nanoid from 3.1.30 to 3.2.0 (#229)
Bumps [nanoid](https://github.com/ai/nanoid) from 3.1.30 to 3.2.0.
- [Release notes](https://github.com/ai/nanoid/releases)
- [Changelog](https://github.com/ai/nanoid/blob/main/CHANGELOG.md)
- [Commits](https://github.com/ai/nanoid/compare/3.1.30...3.2.0)

---
updated-dependencies:
- dependency-name: nanoid
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-01-31 17:20:39 +01:00
dependabot[bot]
26ed63d65e Bump follow-redirects from 1.14.6 to 1.14.7 (#227)
Bumps [follow-redirects](https://github.com/follow-redirects/follow-redirects) from 1.14.6 to 1.14.7.
- [Release notes](https://github.com/follow-redirects/follow-redirects/releases)
- [Commits](https://github.com/follow-redirects/follow-redirects/compare/v1.14.6...v1.14.7)

---
updated-dependencies:
- dependency-name: follow-redirects
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-01-31 17:20:29 +01:00
Michael Albert
b9e81b2278 Bump version and update dependencies
Change-Id: I0c0349b4429ce06bea51453c092f0a11156aaa05
2021-12-17 20:38:18 +01:00
sakkiii
f6f437b17a version tag on docker hub (#187)
* version tag on docker hub

* resolve name collision

* master branch added for latest tag

* prettier-ignore fix
2021-12-08 22:02:43 +01:00
Dirk Klimpel
91af8f1c04 Add sorting users by creation timestamp (#174)
* Add `creation_ts` to list users

* remove filter

* Bring back origin columns sort order
2021-12-08 21:59:09 +01:00
Aaron R
abc9d5154e Switch Dockerfile to use current LTS version of Node (#205)
Node 17 current fails due to https://github.com/webpack/webpack/issues/14532. It probably makes sense to use the current LTS version of Node instead of the absolute latest version of Node so these kinds of bleeding edge issues are less likely to happen.
2021-11-15 21:35:23 +01:00
dependabot[bot]
8228d7d2c2 Bump tar from 6.1.8 to 6.1.11 (#207)
Bumps [tar](https://github.com/npm/node-tar) from 6.1.8 to 6.1.11.
- [Release notes](https://github.com/npm/node-tar/releases)
- [Changelog](https://github.com/npm/node-tar/blob/main/CHANGELOG.md)
- [Commits](https://github.com/npm/node-tar/compare/v6.1.8...v6.1.11)

---
updated-dependencies:
- dependency-name: tar
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-11-15 21:18:58 +01:00
Dirk Klimpel
4adc20f80d replace undoable prop with mutationMode prop (#202) 2021-11-15 21:18:29 +01:00
Dirk Klimpel
a5c7d7dd22 Make items in "Room directory" are clickable (#199) 2021-11-15 21:15:11 +01:00
dependabot[bot]
dc5c2c1d68 Bump tmpl from 1.0.4 to 1.0.5 (#193)
Bumps [tmpl](https://github.com/daaku/nodejs-tmpl) from 1.0.4 to 1.0.5.
- [Release notes](https://github.com/daaku/nodejs-tmpl/releases)
- [Commits](https://github.com/daaku/nodejs-tmpl/commits/v1.0.5)

---
updated-dependencies:
- dependency-name: tmpl
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-11-15 21:11:49 +01:00
Dirk Klimpel
42b3252353 Add pristine to UserEdit and ServerNotice (#185) 2021-11-15 21:02:47 +01:00
Dirk Klimpel
1a17d3e69b Automatically set the homeserver for a new user (#184)
and enhance form validation
2021-11-15 20:57:38 +01:00
Dirk Klimpel
79ef38ee6b Enable modify user external_ids (#179)
* Enable modify user `external_ids`

* add input validation
2021-11-15 20:40:05 +01:00
Manuel Stahl
0ff4b30d71 Remove update repo stop from docker release action
See https://github.com/peter-evans/dockerhub-description/issues/10

Change-Id: I42d2d4e1a28117be1419591f7d43653591182f0c
2021-08-26 10:43:11 +02:00
Manuel Stahl
6c4ff6c791 Add write permissions to github release action
Change-Id: Ie7db1e7410bbc1c0fccbc2d00119363629e10f22
2021-08-26 10:40:11 +02:00
Manuel Stahl
9c36ed6566 Increment version
Change-Id: I48fb812632dc2e498ad267477809a16fc882cf4c
2021-08-25 10:42:34 +02:00
dklimpel
8536f552d4 Add button to quarantine media (#180)
Change-Id: I6496826fdf75ab8b7b3ed5a9056abf86a50caea3
2021-08-25 10:42:34 +02:00
Manuel Stahl
aaf782d24f Use .gitignore for prettier as well
Change-Id: Ibfe73812a5375cc251b859b8aa441583c0cdcd41
2021-08-25 10:42:34 +02:00
Manuel Stahl
2886203594 Add github action that builds docker images and pushes them to docker hub
Change-Id: I60d39cc266c2e8b905e2ac4a367bd5a22b79b57b
2021-08-25 10:42:34 +02:00
csett86
865fc98336 Add github action that packages a release tarball (#148)
Change-Id: I368a834a27f69550596a041c1e6b84afd40011b7
2021-08-24 09:58:35 +02:00
Dirk Klimpel
e6f01f035b Add buttons to protect and unprotect users' media from quarantine (#150) 2021-08-19 11:51:07 +02:00
Manuel Stahl
32e088ac5a yarn: Upgrade packages
- babel 7.15
- eslint 7.32
- react-admin 3.17

Change-Id: Ief4ad5870ae721fb432e19686607376b83eff12a
2021-08-18 09:48:41 +02:00
Dirk Klimpel
bf3d13916f Add SSO external_ids to user (#168) 2021-08-18 09:33:22 +02:00
Manuel Stahl
07b1df5855 Add Github action badge for build checks 2021-08-18 09:27:25 +02:00
Dirk Klimpel
634341ea07 Add GitHub Action to run CI tests (#162) 2021-08-18 09:18:09 +02:00
Dirk Klimpel
361643c3da Fix link in README.md (#175) 2021-08-17 08:22:36 +02:00
Dirk Klimpel
5262518699 Update links to new Synapse documentation (#164) 2021-07-06 09:57:44 +02:00
Dirk Klimpel
78a282863a Fix broken CI with language files (#165) 2021-07-06 09:56:09 +02:00
Michael Albert
ff0201273a Bump version and update packages
Change-Id: If148587c9e5895ab6b8a70ec34c9190f0bb8f2e0
2021-07-05 14:48:25 +02:00
Dirk Klimpel
e50c95b4be Fix CSV import button (#154) 2021-07-05 14:32:51 +02:00
Dirk Klimpel
9f16e5c6ba Change delete room API to DELETE (#151) 2021-07-05 14:32:44 +02:00
dependabot[bot]
509a45cba4 Bump dns-packet from 1.3.1 to 1.3.4 (#145)
Bumps [dns-packet](https://github.com/mafintosh/dns-packet) from 1.3.1 to 1.3.4.
- [Release notes](https://github.com/mafintosh/dns-packet/releases)
- [Changelog](https://github.com/mafintosh/dns-packet/blob/master/CHANGELOG.md)
- [Commits](https://github.com/mafintosh/dns-packet/compare/v1.3.1...v1.3.4)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-06-15 11:03:47 +02:00
dependabot[bot]
5c6e5a9641 Bump ws from 6.2.1 to 6.2.2 (#152)
Bumps [ws](https://github.com/websockets/ws) from 6.2.1 to 6.2.2.
- [Release notes](https://github.com/websockets/ws/releases)
- [Commits](https://github.com/websockets/ws/commits)

---
updated-dependencies:
- dependency-name: ws
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-06-15 11:03:31 +02:00
Dirk Klimpel
e3d5d51342 Fix broken RoomDirectoryFilter (#155) 2021-06-15 11:03:03 +02:00
Michael Albert
985673b161 Increment version
Change-Id: I149896f55be7840b240d92fed5880e3f5624b857
2021-05-25 15:03:15 +02:00
John Francis Sukamto
d72357f64f Update en.js (#144)
Suggested a UI name change for media size (assuming length is size in bytes)
2021-05-25 15:01:13 +02:00
Dirk Klimpel
e19c34324b Allow fixed homeserver (#142) 2021-05-18 12:39:53 +02:00
Dirk Klimpel
3ea1f51eb5 Add a new tab to rooms with forward extremities (#107)
Add a new tab to rooms with forward extremities.
2021-05-08 19:10:51 +02:00
Manuel Stahl
229518e456 Show room alias or room id in room list if room has no name
Change-Id: Iad769f31347566ccf0b8a978b31f5123553e9dbc
2021-05-05 20:24:15 +02:00
Dirk Klimpel
5a5a7143af Enable sorting of user list (#133)
New in Synapse 1.32.0
Fixes: #132, #136
2021-05-05 19:36:47 +02:00
Manuel Stahl
dda8ba5e85 Update nodejs version for travis
Change-Id: I7d44f5df7d4479efcb1d44f5ba23467effad147e
2021-05-05 19:31:50 +02:00
Manuel Stahl
5208198b76 Replace enzyme with testing-library/react
Enzyme is not compatible with react 17.

Change-Id: If9bca2c482bfe10a18d2ee2bc213dab966849b5b
2021-05-05 19:23:01 +02:00
Manuel Stahl
c8082a7198 Remove TestContext from App.test.js
The TestContext is only required for components that depend on react-admin,
but not for the Admin component itself.

Change-Id: I3e07cb6bfa592f1bf59ca282cdf1c2e6c922f619
2021-05-05 19:23:01 +02:00
Michael Albert
10831796e3 Add missing translation
Change-Id: Iab3203742498d2c6768b5885c0522ff8365b58f2
2021-05-05 09:41:05 +00:00
Michael Albert
5ee5288edf Fix some DOM errors
Change-Id: I22a108fd5ce6a344e629e4af0345a0221de44052
2021-05-05 09:40:48 +00:00
Manuel Stahl
a5528d9fe7 yarn: Upgrade packages
- eslint 7.25
- ra-language-german 3.13
- react-admin 3.15
- react-dom 17.0
- react-scripts 4.0

Change-Id: Iad982cf647470bc16194000519a72c401009c9fa
2021-05-04 18:42:05 +02:00
Manuel Stahl
e2fd934851 Allow base URL with path
Ignore and remove trailing slashes.
Fixes #134.

Change-Id: Iedf266e9a93e6939f7f66707fee59a2b56226216
2021-05-04 18:41:54 +02:00
Manuel Stahl
0bc1ce3226 Reuse device_id for synapse-admin on login
Change-Id: I47bbfd1e33ef8bffb618101ae233aeb093cf0ada
2021-05-04 17:10:49 +02:00
Manuel Stahl
41ce58bac8 Enable sorting in tab of users' media (#138) 2021-05-04 16:18:12 +02:00
Manuel Stahl
57c41cc069 Increment version 2021-05-04 15:06:41 +02:00
Nya Candy
0e3375c5ad Add zh-cn support (#131) 2021-05-04 15:06:41 +02:00
Dirk Klimpel
2cdd41b615 Add a new tab to rooms with state events (#108)
Co-authored-by: Michael Albert <37796947+awesome-michael@users.noreply.github.com>
2021-05-04 14:42:27 +02:00
Dirk Klimpel
2ab4343970 Add the lists of public rooms on the server (#105)
* Add room directory and the switches to rooms settings

* Fix react admin version
2021-05-04 13:52:43 +02:00
Dirk Klimpel
0268cc0e94 Add joined_local_devices to rooms (#96) 2021-05-04 13:49:20 +02:00
Lukas Wolfsteiner
f8331a459d Add notes about the docker-compose usage
Change-Id: I73c8467ab58caf2082740e682c9175f3eb494a14
2021-04-21 10:51:19 +02:00
Lukas Wolfsteiner
a12cf95457 Add docker-compose.yml 2021-04-21 10:51:17 +02:00
dklimpel
60854bcc60 Add button to delete media by size and date 2021-04-21 10:51:14 +02:00
Manuel Stahl
62b3d094b7 yarn: Upgrade packages
- babel: 7.13
- material-ui: 4.11
- prettier: 2.2
- react-admin: 3.14

Change-Id: I26ab6d9d75110f3522282b83cd1131af98b8c43c
2021-04-21 10:50:49 +02:00
dependabot[bot]
81231b5ea6 Bump y18n from 4.0.0 to 4.0.1
Bumps [y18n](https://github.com/yargs/y18n) from 4.0.0 to 4.0.1.
- [Release notes](https://github.com/yargs/y18n/releases)
- [Changelog](https://github.com/yargs/y18n/blob/master/CHANGELOG.md)
- [Commits](https://github.com/yargs/y18n/commits)

Signed-off-by: dependabot[bot] <support@github.com>
2021-04-21 09:35:59 +02:00
dependabot[bot]
c114e58278 Bump ssri from 6.0.1 to 6.0.2
Bumps [ssri](https://github.com/npm/ssri) from 6.0.1 to 6.0.2.
- [Release notes](https://github.com/npm/ssri/releases)
- [Changelog](https://github.com/npm/ssri/blob/v6.0.2/CHANGELOG.md)
- [Commits](https://github.com/npm/ssri/compare/v6.0.1...v6.0.2)

Signed-off-by: dependabot[bot] <support@github.com>
2021-04-19 18:23:21 +00:00
Dirk Klimpel
c6b6e54617 Fix broken redirect to login page (#116) 2021-03-16 12:13:32 +01:00
Michael Albert
8ff0ac913c Add missing translations
Change-Id: Ie46554bcd10dde771c03e7d3fd0c3639f904429d
2021-03-16 12:12:54 +01:00
dependabot[bot]
96d2c96740 Bump elliptic from 6.5.3 to 6.5.4 (#122)
Bumps [elliptic](https://github.com/indutny/elliptic) from 6.5.3 to 6.5.4.
- [Release notes](https://github.com/indutny/elliptic/releases)
- [Commits](https://github.com/indutny/elliptic/compare/v6.5.3...v6.5.4)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-03-11 13:29:43 +01:00
Aaron Raimist
8adab0e927 Name device used by Synapse Admin and hook up logout button (#113)
* Name device used by Synapse Admin

* Actually logout when the logout button is pressed so that old sessions get deleted

* Fix lint
2021-03-02 11:45:05 +01:00
Dirk Klimpel
536ffc2fbf Disable telemetry which was introduced with react-admin v3.11.0 (#109) 2021-03-01 09:26:58 +01:00
Michael Albert
684c44e470 Bump version to 0.7.0
Change-Id: I5b854ae8720c12e0895c2c614f4c02f1257c0d09
2021-02-11 21:26:23 +01:00
Dirk Klimpel
7f92e1a3c0 Add new list with information about users' media (#89) 2021-02-11 21:14:02 +01:00
Dirk Klimpel
ea59d0dd02 Add a new tab to user page with media (#87)
* Add a new tab to user page with media
2021-02-11 21:11:34 +01:00
Dirk Klimpel
706114a382 Add a new tab to user page with room memberships (#73)
The admin API for user's room memberships is new in synapse v1.21.0.

Co-authored-by: Michael Albert <37796947+awesome-michael@users.noreply.github.com>
2021-02-11 20:45:02 +01:00
Dirk Klimpel
f2a1275673 Add a new tab to user page with pushers (#85)
* Add a new tab to user page with pushers

* Update pushers `total` and `id`
2021-02-11 20:37:20 +01:00
Dirk Klimpel
425c210cfc Add delete button to room detail page (#97)
* Add delete button to room detail page

* Add confirmation dialog for room deletion
2021-02-11 20:24:17 +01:00
Dirk Klimpel
b184954ffa Update total in dataProvider (#101) 2021-02-11 20:20:42 +01:00
Dirk Klimpel
2f96951c19 Add view of reported events (#84) 2021-01-04 09:14:33 +01:00
dependabot[bot]
1706cd3c9d Bump ini from 1.3.5 to 1.3.7
Bumps [ini](https://github.com/isaacs/ini) from 1.3.5 to 1.3.7.
- [Release notes](https://github.com/isaacs/ini/releases)
- [Commits](https://github.com/isaacs/ini/compare/v1.3.5...v1.3.7)

Signed-off-by: dependabot[bot] <support@github.com>
2020-12-14 13:13:16 +01:00
Dirk Klimpel
eadc04a6a0 Update helper text for activate an user (#95) 2020-12-14 13:12:13 +01:00
Manuel Stahl
1432724a64 yarn: Upgrade packages
- react-admin: 3.10.0
 - react-dom: 16.14.0
 - react-scripts: 3.4.4

Change-Id: I805bcd2f65419747f7e8c5a3e2c6b9896010ca9e
2020-11-16 13:31:39 +01:00
Manuel Stahl
c841720f0c Fix style
Change-Id: I345a942905f15edfa21f51de228efd7671f080c7
2020-11-16 10:55:00 +01:00
Dirk Klimpel
60ecafdf54 Bugfix translation in users' device tab (#86) 2020-11-16 10:54:43 +01:00
Dirk Klimpel
5de5015655 Add SearchInput to RoomFilter (#83) 2020-11-12 14:56:21 +01:00
dklimpel
2bf8a6debb Switch to relative URL for example.csv 2020-11-12 14:48:11 +01:00
dklimpel
c8d9a6db55 Bugfix URL for import users from CSV 2020-11-12 14:48:11 +01:00
Michael Albert
e5d2d895d9 Import users from CSV
Change-Id: I3565dae7531b7de1d68ebcb2392be931083dda9e
2020-11-02 18:29:56 +00:00
Dirk Klimpel
3d4f45d070 Bugfix delete room (#72)
Fixes #70
Bugfix delete a room in room list with `deleteMany`.
2020-10-28 09:25:22 +01:00
Dirk Klimpel
cfe4f4a995 Add more information and requirements to README.md (#79) 2020-10-28 09:25:17 +01:00
Michael Albert
04de65ce51 Add missing translation
Change-Id: I8f827f5e0c3bf6f32f3578a41c73462e70a2cc95
2020-10-13 11:28:20 +00:00
Michael Albert
3d7c0bf67f Add search for users
Change-Id: I4bb4b33819b66846645e2e7a3d38d3e837a5bcd8
2020-10-08 08:07:55 +02:00
Michael Albert
4324ebfdb8 Add confirmation when deleting rooms
Change-Id: I5dce8ebfb7cab988e0e6664c704c04b44a4d2f92
2020-10-07 21:42:19 +02:00
Dirk Klimpel
26b8cea6a5 Add button to purge rooms to room list (#44)
* Add button to purge rooms to room list

Add button (BulkDeleteButton) to delete rooms with no local users:
- purge rooms `POST /_synapse/admin/v1/purge_room`
(https://github.com/matrix-org/synapse/blob/master/docs/admin_api/purge_room.md)

* Bugfix of merge 'master'

* Change from purge room to delete room endpoint
2020-10-07 20:50:10 +02:00
Manuel Stahl
8db881a64d Use current node image as builder
Change-Id: I2bccf5bcd21e37625477695ee927d49dd4333ac4
2020-08-25 17:19:17 +02:00
Manuel Stahl
c09e59d47a yarn: Upgrade packages
- babel: 7.11

Change-Id: I6eebc1afbf54b6ce72e1b534f240e3e0aeb1c30a
2020-08-25 17:19:17 +02:00
Dirk Klimpel
8bdf76f27e Bugfix plural in user tab (#62) 2020-08-11 10:25:05 +02:00
Michael Albert
7c9a87bc86 Show room members in room detail view
Change-Id: I7d82f728de0e503d4834f6815bde000c7a0204a3
2020-08-07 21:29:58 +02:00
Manuel Stahl
1f56bac356 Add basic tests for dataProvider
Change-Id: Ib399cbb4e927ab18f714371e07606df83170df52
2020-07-30 13:52:17 +02:00
Manuel Stahl
bbbca0c57c Add git context to docker, so we can derive the release version
"git describe --tags" requires the git context.

Change-Id: I2bc5dde056c2ac480513004fb99336397355af30
2020-07-29 17:49:30 +02:00
Manuel Stahl
314906657f Add support to remove user devices (#57)
Change-Id: I19176daa656b9280ccd00f1ca0095e72870ca21e
2020-07-29 17:49:30 +02:00
Manuel Stahl
78e7c5f391 Fix translation of user devices
Fixes #58.

Change-Id: Ic2f91917310fd1ba59636d06c81c338ca9dd297e
2020-07-23 09:24:18 +02:00
Michael Albert
1074178e31 Rename Admin -> Server Administrator
Change-Id: Ic11539252af553dbb7cca37996f2402669a9c0e4
2020-07-21 11:52:13 +02:00
Manuel Stahl
352ab1290a Add devices tab to UserEdit component
Allows to view user devices.
API was added by synapse v1.15.0.

Change-Id: Id0693bf6cd6f6182c657412cf8036537e2db9df7
2020-07-13 10:32:13 +02:00
Manuel Stahl
12447b7708 Increase export of users up to 10000
Change-Id: I54c7a52ae35aeb311074f0f3b103a2fdb92aaedd
2020-07-13 10:20:24 +02:00
Manuel Stahl
cd4efb7c07 yarn: Upgrade packages
- react-admin:  3.7.0

Change-Id: I01e4a2244a6ca0d6fc231fe83a94f73d48618824
2020-07-13 10:20:03 +02:00
Michael Albert
ff59ee4c2e Hide some room list information by default
Change-Id: Ic6fbf0d941d2ffcc87fb5b7793517b96792ce16d
2020-07-08 11:19:09 +02:00
Manuel Stahl
61938405e9 Add room detail view
Needs Synapse v1.14.0 or later

Change-Id: I6e3956a1e02fad5ba2f847458cd184af6aaedef0
2020-07-08 10:46:49 +02:00
Manuel Stahl
ac0657c428 Add hint about required synapse version
Change-Id: I8152681d695ded78d0f9b9d82bc038aa67723fbc
2020-07-08 09:55:52 +02:00
Michael Albert
ab709aee3e Add screenshots and install instructions
Change-Id: Ibfede12d700924b7b3b01af5f3a3624f21a93862
2020-07-08 07:49:42 +00:00
dklimpel
6da3c8b885 Bugfix translation of plural in UserTitle 2020-07-08 08:50:00 +02:00
Manuel Stahl
ab04db5baf Get avatar_url and displayname from v2/users API
API was added by synapse v1.13.0.

Change-Id: I927b81882fa20e5b3de3d9fc216e2136f7036bba
2020-07-07 18:51:35 +02:00
Dirk Klimpel
8282a3caf8 Move threepids in UserEdit to a separate tab (#51)
Separates information into individual tabs for a better overview.
2020-07-06 12:35:26 +02:00
Michael Albert
2fc75cd6fc Merge pull request #43 from dklimpel/extend_room_list
Extend the room list with further attributes
2020-07-03 19:32:00 +02:00
Dirk Klimpel
3fd615943c Shows encrypted status with icons 2020-07-01 22:36:15 +02:00
dklimpel
aaf1ebb909 Change field creation_ts * 1000 to creation_ts_ms 2020-06-16 10:15:22 +02:00
dklimpel
627f3d2917 Add creation timestamp and consent version to UserEdit
Add information about the user to UserEdit
- creation timestamp
- consent version
2020-06-16 10:15:22 +02:00
dklimpel
168e249296 Bugfix removes the ability to click on individual connections.
If you click on a connection in UserEdit, you will get an empty page.
This solves the problem.
2020-06-16 09:45:43 +02:00
dklimpel
5bdfb80db7 Bugfix sort users by user_id
Users are not sortable by `user_id`.
Set `sortable={false}`.
2020-06-10 13:11:35 +02:00
dependabot[bot]
b7c3684b80 Bump websocket-extensions from 0.1.3 to 0.1.4 (#49)
Bumps [websocket-extensions](https://github.com/faye/websocket-extensions-node) from 0.1.3 to 0.1.4.
- [Release notes](https://github.com/faye/websocket-extensions-node/releases)
- [Changelog](https://github.com/faye/websocket-extensions-node/blob/master/CHANGELOG.md)
- [Commits](https://github.com/faye/websocket-extensions-node/compare/0.1.3...0.1.4)

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2020-06-09 14:50:58 +02:00
Manuel Stahl
0ada5287d7 Show Synapse server version on login page
Change-Id: Id9b0d2adf83590524069d308f4fe9e5d14147295
2020-05-25 13:29:15 +02:00
dklimpel
3884c50012 Extend the room list with further attributes
Add further attributes:
- is_encrypted
- federatable
- public
- state_events
- version
- joined_local_members

Also add the ability to sort.

API was added by synapse v1.13.0.
2020-05-23 17:43:33 +02:00
Michael Albert
300e22a537 Show version of Synapse-Admin
Change-Id: I354e3f3b3e4f45e5ca72318ce70b66bee433f3d6
2020-05-15 13:28:51 +02:00
Dirk Klimpel
009ce803e2 Add ServerNoticeButton to UserBulkActionButtons (#41)
This adds the button to send "Server Notices" to many users at once.
2020-05-06 09:03:33 +02:00
38 changed files with 9906 additions and 5334 deletions

View File

@@ -1,5 +1,4 @@
# Exclude a bunch of stuff which can make the build context a larger than it needs to be
.git/
tests/
build/
lib/

5
.env Normal file
View File

@@ -0,0 +1,5 @@
# This setting allows to fix the homeserver.
# If you set this setting, the user will not be able to select
# the server and have to use synapse-admin with this server.
#REACT_APP_SERVER=https://yourmatrixserver.example.com

21
.github/workflows/build-test.yml vendored Normal file
View File

@@ -0,0 +1,21 @@
name: build-test
on:
push:
branches: ["master"]
pull_request:
jobs:
check:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Setup node
uses: actions/setup-node@v2
with:
node-version: 14
- name: Install dependencies
run: yarn --frozen-lockfile
- name: Run tests
run: yarn test

51
.github/workflows/docker-release.yml vendored Normal file
View File

@@ -0,0 +1,51 @@
name: Create docker image(s) and push to docker hub
on:
push:
# Sequence of patterns matched against refs/heads
# prettier-ignore
branches:
# Push events on master branch
- master
# Sequence of patterns matched against refs/tags
tags:
- '[0-9]+\.[0-9]+\.[0-9]+' # Push events to 0.X.X tag
jobs:
docker:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Set up QEMU
uses: docker/setup-qemu-action@v1
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v1
- name: Login to DockerHub
uses: docker/login-action@v1
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Calculate docker image tag
id: set-tag
run: |
case "${GITHUB_REF}" in
refs/heads/master|refs/heads/main)
tag=latest
;;
refs/tags/*)
tag=${GITHUB_REF#refs/tags/}
;;
*)
tag=${GITHUB_SHA}
;;
esac
echo "::set-output name=tag::$tag"
- name: Build and Push Tag
uses: docker/build-push-action@v2
with:
context: .
push: true
tags: "awesometechnologies/synapse-admin:${{ steps.set-tag.outputs.tag }}"
platforms: linux/amd64,linux/arm64

26
.github/workflows/edge_ghpage.yml vendored Normal file
View File

@@ -0,0 +1,26 @@
name: Build and Deploy Edge version to GH Pages
on:
workflow_dispatch:
push:
branches:
- main
- master
jobs:
build-and-deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout 🛎️
uses: actions/checkout@v2.3.1
- uses: actions/setup-node@v2
with:
node-version: "14"
- name: Install and Build 🔧
run: |
yarn install
yarn build
- name: Deploy 🚀
uses: JamesIves/github-pages-deploy-action@4.1.5
with:
branch: gh-pages
folder: build

31
.github/workflows/github-release.yml vendored Normal file
View File

@@ -0,0 +1,31 @@
name: Create release tarball and attach to tag
on:
push:
tags:
- "*"
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: write
packages: write
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: "14"
- run: yarn install
- run: yarn build
- run: |
version=`git describe --dirty --tags || echo unknown`
mkdir -p dist
cp -r build synapse-admin-$version
tar chvzf dist/synapse-admin-$version.tar.gz synapse-admin-$version
- uses: softprops/action-gh-release@b7e450da2a4b4cb4bfbae528f788167786cfcedf
with:
files: dist/*.tar.gz
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -7,5 +7,5 @@
"trailingComma": "es5",
"bracketSpacing": true,
"jsxBracketSameLine": false,
"arrowParens": "avoid",
"arrowParens": "avoid"
}

View File

@@ -1,5 +1,5 @@
language: node_js
node_js:
- 13
- lts/*
cache: yarn

View File

@@ -1,11 +1,14 @@
# Builder
FROM node:10-alpine as builder
FROM node:lts as builder
ARG PUBLIC_URL=/
ARG REACT_APP_SERVER
WORKDIR /src
COPY . /src
RUN yarn --network-timeout=100000 install
RUN yarn build
RUN PUBLIC_URL=$PUBLIC_URL REACT_APP_SERVER=$REACT_APP_SERVER yarn build
# App

111
README.md
View File

@@ -1,9 +1,116 @@
[![Build Status](https://travis-ci.org/Awesome-Technologies/synapse-admin.svg?branch=master)](https://travis-ci.org/Awesome-Technologies/synapse-admin)
[![build-test](https://github.com/Awesome-Technologies/synapse-admin/actions/workflows/build-test.yml/badge.svg)](https://github.com/Awesome-Technologies/synapse-admin/actions/workflows/build-test.yml)
# Synapse admin ui
This project is built using [react-admin](https://marmelab.com/react-admin/).
Use `yarn install` after cloning this repo.
```
curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -
Use `yarn start` to launch the webserver.
## Run `sudo apt-get install -y nodejs` to install Node.js 14.x and npm
## You may also need development tools to build native addons:
sudo apt-get install gcc g++ make
## To install the Yarn package manager, run:
curl -sL https://dl.yarnpkg.com/debian/pubkey.gpg | gpg --dearmor | sudo tee /usr/share/keyrings/yarnkey.gpg >/dev/null
echo "deb [signed-by=/usr/share/keyrings/yarnkey.gpg] https://dl.yarnpkg.com/debian stable main" | sudo tee /etc/apt/sources.list.d/yarn.list
sudo apt-get update && sudo apt-get install yarn
```
## Usage
### Supported Synapse
It needs at least [Synapse](https://github.com/matrix-org/synapse) v1.42.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://matrix-org.github.io/synapse/develop/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://matrix-org.github.io/synapse/develop/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`
You can fix the homeserver, so that the user can no longer define it himself.
Either you define it at startup (e.g. `REACT_APP_SERVER=https://yourmatrixserver.example.com yarn start`)
or by editing it in the [.env](.env) file. See also the
[documentation](https://create-react-app.dev/docs/adding-custom-environment-variables/).
#### 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
version: "3"
services:
synapse-admin:
container_name: synapse-admin
hostname: synapse-admin
build:
context: https://github.com/Awesome-Technologies/synapse-admin.git
# args:
# - NODE_OPTIONS="--max_old_space_size=1024"
# # see #266
# - PUBLIC_URL="/synapse-admin"
# - REACT_APP_SERVER="https://matrix.example.com"
ports:
- "8080:80"
restart: unless-stopped
```
- browse to http://localhost:8080
## Screenshots
![Screenshots](./screenshots.jpg)
## Development
- Use `yarn test` to run all style, lint and unit tests
- Use `yarn fix` to fix the coding style

21
docker-compose.yml Normal file
View File

@@ -0,0 +1,21 @@
version: "3"
services:
synapse-admin:
container_name: synapse-admin
hostname: synapse-admin
image: awesometechnologies/synapse-admin:latest
# build:
# context: .
# to use the docker-compose as standalone without a local repo clone,
# replace the context definition with this:
# context: https://github.com/Awesome-Technologies/synapse-admin.git
# if you're building on an architecture other than amd64, make sure
# to define a maximum ram for node. otherwise the build will fail.
# args:
# - NODE_OPTIONS="--max_old_space_size=1024"
ports:
- "8080:80"
restart: unless-stopped

View File

@@ -1,6 +1,6 @@
{
"name": "synapse-admin",
"version": "0.1.0",
"version": "0.8.5",
"description": "Admin GUI for the Matrix.org server Synapse",
"author": "Awesome Technologies Innovationslabor GmbH",
"license": "Apache-2.0",
@@ -11,30 +11,32 @@
},
"devDependencies": {
"@testing-library/jest-dom": "^5.1.1",
"@testing-library/react": "^10.0.2",
"@testing-library/user-event": "^10.0.1",
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.2",
"eslint": "^6.8.0",
"eslint-config-prettier": "^6.10.1",
"@testing-library/react": "^11.2.6",
"@testing-library/user-event": "^13.1.8",
"eslint": "^7.25.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^3.1.2",
"prettier": "^2.0.0"
"jest-fetch-mock": "^3.0.3",
"prettier": "^2.2.0",
"ra-test": "^3.15.0"
},
"dependencies": {
"papaparse": "^5.2.0",
"prop-types": "^15.7.2",
"ra-language-german": "^2.1.2",
"react": "^16.13.1",
"react-admin": "^3.4.0",
"react-dom": "^16.13.1",
"react-scripts": "^3.4.1"
"ra-language-chinese": "^2.0.10",
"ra-language-german": "^3.13.4",
"react": "^17.0.0",
"react-admin": "^3.19.7",
"react-dom": "^17.0.2",
"react-scripts": "^4.0.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"start": "REACT_APP_VERSION=$(git describe --tags) react-scripts start",
"build": "REACT_APP_VERSION=$(git describe --tags) react-scripts build",
"fix:other": "yarn prettier --write",
"fix:code": "yarn test:lint --fix",
"fix": "yarn fix:code && yarn fix:other",
"prettier": "prettier \"**/*.{js,jsx,json,md,scss,yaml,yml}\"",
"prettier": "prettier --ignore-path .gitignore \"**/*.{js,jsx,json,md,scss,yaml,yml}\"",
"test:code": "react-scripts test",
"test:lint": "eslint --ignore-path .gitignore --ext .js,.jsx .",
"test:style": "yarn prettier --list-different",

3
public/data/example.csv Normal file
View File

@@ -0,0 +1,3 @@
id,displayname,password,is_guest,admin,deactivated
@testuser22:example.org,Jane Doe,secretpassword,false,true,false
,John Doe,,false,false,false
1 id displayname password is_guest admin deactivated
2 @testuser22:example.org Jane Doe secretpassword false true false
3 John Doe false false false

View File

@@ -38,5 +38,12 @@
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
<footer
style="position: relative; z-index: 2; height: 2em; margin-top: -2em; line-height: 2em; background-color: #eee; border: 0.5px solid #ddd">
<a id="copyright" href="https://github.com/Awesome-Technologies/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>(%REACT_APP_VERSION%)</b> by Awesome Technologies Innovationslabor GmbH
</a>
</footer>
</body>
</html>
</html>

BIN
screenshots.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 222 KiB

View File

@@ -4,17 +4,33 @@ import polyglotI18nProvider from "ra-i18n-polyglot";
import authProvider from "./synapse/authProvider";
import dataProvider from "./synapse/dataProvider";
import { UserList, UserCreate, UserEdit } from "./components/users";
import { RoomList } from "./components/rooms";
import { RoomList, RoomShow } from "./components/rooms";
import { ReportList, ReportShow } from "./components/EventReports";
import LoginPage from "./components/LoginPage";
import UserIcon from "@material-ui/icons/Group";
import { ViewListIcon as RoomIcon } from "@material-ui/icons/ViewList";
import ConfirmationNumberIcon from "@material-ui/icons/ConfirmationNumber";
import EqualizerIcon from "@material-ui/icons/Equalizer";
import { UserMediaStatsList } from "./components/statistics";
import RoomIcon from "@material-ui/icons/ViewList";
import ReportIcon from "@material-ui/icons/Warning";
import FolderSharedIcon from "@material-ui/icons/FolderShared";
import { ImportFeature } from "./components/ImportFeature";
import {
RegistrationTokenCreate,
RegistrationTokenEdit,
RegistrationTokenList,
} from "./components/RegistrationTokens";
import { RoomDirectoryList } from "./components/RoomDirectory";
import { Route } from "react-router-dom";
import germanMessages from "./i18n/de";
import englishMessages from "./i18n/en";
import chineseMessages from "./i18n/zh";
// TODO: Can we use lazy loading together with browser locale?
const messages = {
de: germanMessages,
en: englishMessages,
zh: chineseMessages,
};
const i18nProvider = polyglotI18nProvider(
locale => (messages[locale] ? messages[locale] : messages.en),
@@ -23,10 +39,14 @@ const i18nProvider = polyglotI18nProvider(
const App = () => (
<Admin
disableTelemetry
loginPage={LoginPage}
authProvider={authProvider}
dataProvider={dataProvider}
i18nProvider={i18nProvider}
customRoutes={[
<Route key="userImport" path="/import_users" component={ImportFeature} />,
]}
>
<Resource
name="users"
@@ -35,9 +55,40 @@ const App = () => (
edit={UserEdit}
icon={UserIcon}
/>
<Resource name="rooms" list={RoomList} icon={RoomIcon} />
<Resource name="rooms" list={RoomList} show={RoomShow} icon={RoomIcon} />
<Resource
name="user_media_statistics"
list={UserMediaStatsList}
icon={EqualizerIcon}
/>
<Resource
name="reports"
list={ReportList}
show={ReportShow}
icon={ReportIcon}
/>
<Resource
name="room_directory"
list={RoomDirectoryList}
icon={FolderSharedIcon}
/>
<Resource
name="registration_tokens"
list={RegistrationTokenList}
create={RegistrationTokenCreate}
edit={RegistrationTokenEdit}
icon={ConfirmationNumberIcon}
/>
<Resource name="connections" />
<Resource name="devices" />
<Resource name="room_members" />
<Resource name="users_media" />
<Resource name="joined_rooms" />
<Resource name="pushers" />
<Resource name="servernotices" />
<Resource name="forward_extremities" />
<Resource name="room_state" />
<Resource name="user_urlpreview" />
</Admin>
);

View File

@@ -1,14 +1,9 @@
import React from "react";
import { TestContext } from "react-admin";
import { shallow } from "enzyme";
import { render } from "@testing-library/react";
import App from "./App";
describe("App", () => {
it("renders", () => {
shallow(
<TestContext>
<App />
</TestContext>
);
render(<App />);
});
});

View File

@@ -0,0 +1,122 @@
import React from "react";
import {
Datagrid,
DateField,
List,
NumberField,
Pagination,
ReferenceField,
Show,
Tab,
TabbedShowLayout,
TextField,
useTranslate,
} from "react-admin";
import PageviewIcon from "@material-ui/icons/Pageview";
import ViewListIcon from "@material-ui/icons/ViewList";
const date_format = {
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
};
const ReportPagination = props => (
<Pagination {...props} rowsPerPageOptions={[10, 25, 50, 100, 500, 1000]} />
);
export const ReportShow = props => {
const translate = useTranslate();
return (
<Show {...props}>
<TabbedShowLayout>
<Tab
label={translate("synapseadmin.reports.tabs.basic", {
smart_count: 1,
})}
icon={<ViewListIcon />}
>
<DateField
source="received_ts"
showTime
options={date_format}
sortable={true}
/>
<ReferenceField source="user_id" reference="users">
<TextField source="id" />
</ReferenceField>
<NumberField source="score" />
<TextField source="reason" />
<TextField source="name" />
<TextField
source="canonical_alias"
label="resources.rooms.fields.canonical_alias"
/>
<ReferenceField
source="room_id"
reference="rooms"
link="show"
label="resources.rooms.fields.room_id"
>
<TextField source="id" />
</ReferenceField>
</Tab>
<Tab
label="synapseadmin.reports.tabs.detail"
icon={<PageviewIcon />}
path="detail"
>
<DateField
source="event_json.origin_server_ts"
showTime
options={date_format}
sortable={true}
/>
<ReferenceField source="sender" reference="users">
<TextField source="id" />
</ReferenceField>
<TextField source="event_id" />
<TextField source="event_json.origin" />
<TextField source="event_json.type" />
<TextField source="event_json.content.msgtype" />
<TextField source="event_json.content.body" />
<TextField source="event_json.content.format" />
<TextField source="event_json.content.formatted_body" />
<TextField source="event_json.content.algorithm" />
<TextField
source="event_json.content.device_id"
label="resources.users.fields.device_id"
/>
</Tab>
</TabbedShowLayout>
</Show>
);
};
export const ReportList = ({ ...props }) => {
return (
<List
{...props}
pagination={<ReportPagination />}
sort={{ field: "received_ts", order: "DESC" }}
bulkActionButtons={false}
>
<Datagrid rowClick="show">
<TextField source="id" sortable={false} />
<DateField
source="received_ts"
showTime
options={date_format}
sortable={true}
/>
<TextField sortable={false} source="user_id" />
<TextField sortable={false} source="name" />
<TextField sortable={false} source="score" />
</Datagrid>
</List>
);
};

View File

@@ -0,0 +1,674 @@
import React, { useState } from "react";
import {
Button as ReactAdminButton,
useDataProvider,
useNotify,
Title,
} from "react-admin";
import { parse as parseCsv, unparse as unparseCsv } from "papaparse";
import GetAppIcon from "@material-ui/icons/GetApp";
import {
Button,
Card,
CardActions,
CardContent,
CardHeader,
FormControlLabel,
Checkbox,
NativeSelect,
} from "@material-ui/core";
import { useTranslate } from "ra-core";
import Container from "@material-ui/core/Container/Container";
import { generateRandomUser } from "./users";
const LOGGING = true;
export const ImportButton = ({ label, variant = "text" }) => {
return (
<ReactAdminButton
color="primary"
component="span"
variant={variant}
label={label}
>
<GetAppIcon style={{ transform: "rotate(180deg)", fontSize: "20" }} />
</ReactAdminButton>
);
};
const expectedFields = ["id", "displayname"].sort();
const optionalFields = [
"user_type",
"guest",
"admin",
"deactivated",
"avatar_url",
"password",
].sort();
function TranslatableOption({ value, text }) {
const translate = useTranslate();
return <option value={value}>{translate(text)}</option>;
}
const FilePicker = props => {
const [values, setValues] = useState(null);
const [error, setError] = useState(null);
const [stats, setStats] = useState(null);
const [dryRun, setDryRun] = useState(true);
const [progress, setProgress] = useState(null);
const [importResults, setImportResults] = useState(null);
const [skippedRecords, setSkippedRecords] = useState(null);
const [conflictMode, setConflictMode] = useState("stop");
const [passwordMode, setPasswordMode] = useState(true);
const [useridMode, setUseridMode] = useState("ignore");
const translate = useTranslate();
const notify = useNotify();
const dataProvider = useDataProvider();
const onFileChange = async e => {
if (progress !== null) return;
setValues(null);
setError(null);
setStats(null);
setImportResults(null);
const file = e.target.files ? e.target.files[0] : null;
/* Let's refuse some unreasonably big files instead of freezing
* up the browser */
if (file.size > 100000000) {
const message = translate("import_users.errors.unreasonably_big", {
size: (file.size / (1024 * 1024)).toFixed(2),
});
notify(message);
setError(message);
return;
}
try {
parseCsv(file, {
header: true,
skipEmptyLines: true /* especially for a final EOL in the csv file */,
complete: result => {
if (result.error) {
setError(result.error);
}
/* Papaparse is very lenient, we may be able to salvage
* the data in the file. */
verifyCsv(result, { setValues, setStats, setError });
},
});
} catch {
setError(true);
return null;
}
};
const verifyCsv = (
{ data, meta, errors },
{ setValues, setStats, setError }
) => {
/* First, verify the presence of required fields */
let eF = Array.from(expectedFields);
let oF = Array.from(optionalFields);
meta.fields.forEach(name => {
if (eF.includes(name)) {
eF = eF.filter(v => v !== name);
}
if (oF.includes(name)) {
oF = oF.filter(v => v !== name);
}
});
if (eF.length !== 0) {
setError(
translate("import_users.error.required_field", { field: eF[0] })
);
return false;
}
// XXX after deciding on how "name" and friends should be handled below,
// this place will want changes, too.
/* Collect some stats to prevent sneaky csv files from adding admin
users or something.
*/
let stats = {
user_types: { default: 0 },
is_guest: 0,
admin: 0,
deactivated: 0,
password: 0,
avatar_url: 0,
id: 0,
total: data.length,
};
data.forEach((line, idx) => {
if (line.user_type === undefined || line.user_type === "") {
stats.user_types.default++;
} else {
stats.user_types[line.user_type] += 1;
}
/* XXX correct the csv export that react-admin offers for the users
* resource so it gives sensible field names and doesn't duplicate
* id as "name"?
*/
if (meta.fields.includes("name")) {
delete line.name;
}
if (meta.fields.includes("user_type")) {
delete line.user_type;
}
if (meta.fields.includes("is_admin")) {
line.admin = line.is_admin;
delete line.is_admin;
}
["is_guest", "admin", "deactivated"].forEach(f => {
if (line[f] === "true") {
stats[f]++;
line[f] = true; // we need true booleans instead of strings
} else {
if (line[f] !== "false" && line[f] !== "") {
errors.push(
translate("import_users.error.invalid_value", {
field: f,
row: idx,
})
);
}
line[f] = false; // default values to false
}
});
if (line.password !== undefined && line.password !== "") {
stats.password++;
}
if (line.avatar_url !== undefined && line.avatar_url !== "") {
stats.avatar_url++;
}
if (line.id !== undefined && line.id !== "") {
stats.id++;
}
});
if (errors.length > 0) {
setError(errors);
}
setStats(stats);
setValues(data);
return true;
};
const runImport = async e => {
if (progress !== null) {
notify("import_users.errors.already_in_progress");
return;
}
const results = await doImport(
dataProvider,
values,
conflictMode,
passwordMode,
useridMode,
dryRun,
setProgress,
setError
);
setImportResults(results);
// offer CSV download of skipped or errored records
// (so that the user doesn't have to filter out successful
// records manually when fixing stuff in the CSV)
setSkippedRecords(unparseCsv(results.skippedRecords));
if (LOGGING) console.log("Skipped records:");
if (LOGGING) console.log(skippedRecords);
};
// XXX every single one of the requests will restart the activity indicator
// which doesn't look very good.
const doImport = async (
dataProvider,
data,
conflictMode,
passwordMode,
useridMode,
dryRun,
setProgress,
setError
) => {
let skippedRecords = [];
let erroredRecords = [];
let succeededRecords = [];
let changeStats = {
toAdmin: 0,
toGuest: 0,
toRegular: 0,
replacedPassword: 0,
};
let entriesDone = 0;
let entriesCount = data.length;
try {
setProgress({ done: entriesDone, limit: entriesCount });
for (const entry of data) {
let userRecord = {};
let overwriteData = {};
// No need to do a bunch of cryptographic random number getting if
// we are using neither a generated password nor a generated user id.
if (
useridMode === "ignore" ||
entry.id === undefined ||
entry.password === undefined ||
passwordMode === false
) {
overwriteData = generateRandomUser();
// Ignoring IDs or the entry lacking an ID means we keep the
// ID field in the overwrite data.
if (!(useridMode === "ignore" || entry.id === undefined)) {
delete overwriteData.id;
}
// Not using passwords from the csv or this entry lacking a password
// means we keep the password field in the overwrite data.
if (
!(
passwordMode === false ||
entry.password === undefined ||
entry.password === ""
)
) {
delete overwriteData.password;
}
}
/* TODO record update stats (especially admin no -> yes, deactivated x -> !x, ... */
Object.assign(userRecord, entry);
Object.assign(userRecord, overwriteData);
/* For these modes we will consider the ID that's in the record.
* If the mode is "stop", we will not continue adding more records, and
* we will offer information on what was already added and what was
* skipped.
*
* If the mode is "skip", we record the record for later, but don't
* send it to the server.
*
* If the mode is "update", we change fields that are reasonable to
* update.
* - If the "password mode" is "true" (i.e. "use passwords from csv"):
* - if the record has a password
* - send the password along with the record
* - if the record has no password
* - generate a new password
* - If the "password mode" is "false"
* - never generate a new password to update existing users with
*/
/* We just act as if there are no IDs in the CSV, so every user will be
* created anew.
* We do a simple retry loop so that an accidental hit on an existing ID
* doesn't trip us up.
*/
if (LOGGING)
console.log(
"will check for existence of record " + JSON.stringify(userRecord)
);
let retries = 0;
const submitRecord = recordData => {
return dataProvider.getOne("users", { id: recordData.id }).then(
async alreadyExists => {
if (LOGGING) console.log("already existed");
if (useridMode === "update" || conflictMode === "skip") {
skippedRecords.push(recordData);
} else if (conflictMode === "stop") {
throw new Error(
translate("import_users.error.id_exits", {
id: recordData.id,
})
);
} else {
const overwriteData = generateRandomUser();
const newRecordData = Object.assign({}, recordData, {
id: overwriteData.id,
});
retries++;
if (retries > 512) {
console.warn("retry loop got stuck? pathological situation?");
skippedRecords.push(recordData);
} else {
await submitRecord(newRecordData);
}
}
},
async okToSubmit => {
if (LOGGING)
console.log(
"OK to create record " +
recordData.id +
" (" +
recordData.displayname +
")."
);
if (!dryRun) {
await dataProvider.create("users", { data: recordData });
}
succeededRecords.push(recordData);
}
);
};
await submitRecord(userRecord);
entriesDone++;
setProgress({ done: entriesDone, limit: data.length });
}
setProgress(null);
} catch (e) {
setError(
translate("import_users.error.at_entry", {
entry: entriesDone + 1,
message: e.message,
})
);
setProgress(null);
}
return {
skippedRecords,
erroredRecords,
succeededRecords,
totalRecordCount: entriesCount,
changeStats,
wasDryRun: dryRun,
};
};
const downloadSkippedRecords = () => {
const element = document.createElement("a");
console.log(skippedRecords);
const file = new Blob([skippedRecords], {
type: "text/comma-separated-values",
});
element.href = URL.createObjectURL(file);
element.download = "skippedRecords.csv";
document.body.appendChild(element); // Required for this to work in FireFox
element.click();
};
const onConflictModeChanged = async e => {
if (progress !== null) {
return;
}
const value = e.target.value;
setConflictMode(value);
};
const onPasswordModeChange = e => {
if (progress !== null) {
return;
}
setPasswordMode(e.target.checked);
};
const onUseridModeChanged = async e => {
if (progress !== null) {
return;
}
const value = e.target.value;
setUseridMode(value);
};
const onDryRunModeChanged = ev => {
if (progress !== null) {
return;
}
setDryRun(ev.target.checked);
};
// render individual small components
const statsCards = stats &&
!importResults && [
<Container>
<CardHeader
title={translate("import_users.cards.importstats.header")}
/>
<CardContent>
<div>
{translate(
"import_users.cards.importstats.users_total",
stats.total
)}
</div>
<div>
{translate(
"import_users.cards.importstats.guest_count",
stats.is_guest
)}
</div>
<div>
{translate(
"import_users.cards.importstats.admin_count",
stats.admin
)}
</div>
</CardContent>
</Container>,
<Container>
<CardHeader title={translate("import_users.cards.ids.header")} />
<CardContent>
<div>
{stats.id === stats.total
? translate("import_users.cards.ids.all_ids_present")
: translate("import_users.cards.ids.count_ids_present", stats.id)}
</div>
{stats.id > 0 ? (
<div>
<NativeSelect
onChange={onUseridModeChanged}
value={useridMode}
enabled={(progress !== null).toString()}
>
<TranslatableOption
value="ignore"
text="import_users.cards.ids.mode.ignore"
/>
<TranslatableOption
value="update"
text="import_users.cards.ids.mode.update"
/>
</NativeSelect>
</div>
) : (
""
)}
</CardContent>
</Container>,
<Container>
<CardHeader title={translate("import_users.cards.passwords.header")} />
<CardContent>
<div>
{stats.password === stats.total
? translate("import_users.cards.passwords.all_passwords_present")
: translate(
"import_users.cards.passwords.count_passwords_present",
stats.password
)}
</div>
{stats.password > 0 ? (
<div>
<FormControlLabel
control={
<Checkbox
checked={passwordMode}
enabled={(progress !== null).toString()}
onChange={onPasswordModeChange}
/>
}
label={translate("import_users.cards.passwords.use_passwords")}
/>
</div>
) : (
""
)}
</CardContent>
</Container>,
];
let conflictCards = stats && !importResults && (
<Container>
<CardHeader title={translate("import_users.cards.conflicts.header")} />
<CardContent>
<div>
<NativeSelect
onChange={onConflictModeChanged}
value={conflictMode}
enabled={(progress !== null).toString()}
>
<TranslatableOption
value="stop"
text="import_users.cards.conflicts.mode.stop"
/>
<TranslatableOption
value="skip"
text="import_users.cards.conflicts.mode.skip"
/>
</NativeSelect>
</div>
</CardContent>
</Container>
);
let errorCards = error && (
<Container>
<CardHeader title={translate("import_users.error.error")} />
<CardContent>
{(Array.isArray(error) ? error : [error]).map(e => (
<div>{e}</div>
))}
</CardContent>
</Container>
);
let uploadCard = !importResults && (
<Container>
<CardHeader title={translate("import_users.cards.upload.header")} />
<CardContent>
{translate("import_users.cards.upload.explanation")}
<a href="./data/example.csv">example.csv</a>
<br />
<br />
<input
type="file"
onChange={onFileChange}
enabled={(progress !== null).toString()}
/>
</CardContent>
</Container>
);
let resultsCard = importResults && (
<CardContent>
<CardHeader title={translate("import_users.cards.results.header")} />
<div>
{translate(
"import_users.cards.results.total",
importResults.totalRecordCount
)}
<br />
{translate(
"import_users.cards.results.successful",
importResults.succeededRecords.length
)}
<br />
{importResults.skippedRecords.length
? [
translate(
"import_users.cards.results.skipped",
importResults.skippedRecords.length
),
<div>
<button onClick={downloadSkippedRecords}>
{translate("import_users.cards.results.download_skipped")}
</button>
</div>,
<br />,
]
: ""}
{importResults.erroredRecords.length
? [
translate(
"import_users.cards.results.skipped",
importResults.erroredRecords.length
),
<br />,
]
: ""}
<br />
{importResults.wasDryRun && [
translate("import_users.cards.results.simulated_only"),
<br />,
]}
</div>
</CardContent>
);
let startImportCard =
!values || values.length === 0 || importResults ? undefined : (
<CardActions>
<FormControlLabel
control={
<Checkbox
checked={dryRun}
onChange={onDryRunModeChanged}
enabled={(progress !== null).toString()}
/>
}
label={translate("import_users.cards.startImport.simulate_only")}
/>
<Button
size="large"
onClick={runImport}
enabled={(progress !== null).toString()}
>
{translate("import_users.cards.startImport.run_import")}
</Button>
{progress !== null ? (
<div>
{progress.done} of {progress.limit} done
</div>
) : null}
</CardActions>
);
let allCards = [];
if (uploadCard) allCards.push(uploadCard);
if (errorCards) allCards.push(errorCards);
if (conflictCards) allCards.push(conflictCards);
if (statsCards) allCards.push(...statsCards);
if (startImportCard) allCards.push(startImportCard);
if (resultsCard) allCards.push(resultsCard);
let cardContainer = <Card>{allCards}</Card>;
return [
<Title defaultTitle={translate("import_users.title")} />,
cardContainer,
];
};
export const ImportFeature = FilePicker;

View File

@@ -1,4 +1,4 @@
import React, { useState } from "react";
import React, { useState, useEffect } from "react";
import {
fetchUtils,
FormDataConsumer,
@@ -29,7 +29,7 @@ const useStyles = makeStyles(theme => ({
main: {
display: "flex",
flexDirection: "column",
minHeight: "100vh",
minHeight: "calc(100vh - 1em)",
alignItems: "center",
justifyContent: "flex-start",
background: "url(./images/floating-cogs.svg)",
@@ -40,6 +40,7 @@ const useStyles = makeStyles(theme => ({
card: {
minWidth: "30em",
marginTop: "6em",
marginBottom: "6em",
},
avatar: {
margin: "1em",
@@ -64,6 +65,12 @@ const useStyles = makeStyles(theme => ({
actions: {
padding: "0 1em 1em 1em",
},
serverVersion: {
color: "#9e9e9e",
fontFamily: "Roboto, Helvetica, Arial, sans-serif",
marginBottom: "1em",
marginLeft: "0.5em",
},
}));
const LoginPage = ({ theme }) => {
@@ -71,10 +78,48 @@ const LoginPage = ({ theme }) => {
const login = useLogin();
const notify = useNotify();
const [loading, setLoading] = useState(false);
const [supportPassAuth, setSupportPassAuth] = useState(true);
var locale = useLocale();
const setLocale = useSetLocale();
const translate = useTranslate();
const base_url = localStorage.getItem("base_url");
const cfg_base_url = process.env.REACT_APP_SERVER;
const [ssoBaseUrl, setSSOBaseUrl] = useState("");
const loginToken = /\?loginToken=([a-zA-Z0-9_-]+)/.exec(window.location.href);
if (loginToken) {
const ssoToken = loginToken[1];
console.log("SSO token is", ssoToken);
// Prevent further requests
window.history.replaceState(
{},
"",
window.location.href.replace(loginToken[0], "#").split("#")[0]
);
const baseUrl = localStorage.getItem("sso_base_url");
localStorage.removeItem("sso_base_url");
if (baseUrl) {
const auth = {
base_url: baseUrl,
username: null,
password: null,
loginToken: ssoToken,
};
console.log("Base URL is:", baseUrl);
console.log("SSO Token is:", ssoToken);
console.log("Let's try token login...");
login(auth).catch(error => {
alert(
typeof error === "string"
? error
: typeof error === "undefined" || !error.message
? "ra.auth.sign_in_error"
: error.message
);
console.error(error);
});
}
}
const renderInput = ({
meta: { touched, error } = {},
@@ -104,7 +149,9 @@ const LoginPage = ({ theme }) => {
if (!values.base_url.match(/^(http|https):\/\//)) {
errors.base_url = translate("synapseadmin.auth.protocol_error");
} else if (
!values.base_url.match(/^(http|https):\/\/[a-zA-Z0-9\-.]+(:\d{1,5})?$/)
!values.base_url.match(
/^(http|https):\/\/[a-zA-Z0-9\-.]+(:\d{1,5})?[^?&\s]*$/
)
) {
errors.base_url = translate("synapseadmin.auth.url_error");
}
@@ -127,6 +174,14 @@ const LoginPage = ({ theme }) => {
});
};
const handleSSO = () => {
localStorage.setItem("sso_base_url", ssoBaseUrl);
const ssoFullUrl = `${ssoBaseUrl}/_matrix/client/r0/login/sso/redirect?redirectUrl=${encodeURIComponent(
window.location.href
)}`;
window.location.href = ssoFullUrl;
};
const extractHomeServer = username => {
const usernameRegex = /@[a-zA-Z0-9._=\-/]+:([a-zA-Z0-9\-.]+\.[a-zA-Z]+)/;
if (!username) return null;
@@ -137,9 +192,10 @@ const LoginPage = ({ theme }) => {
const UserData = ({ formData }) => {
const form = useForm();
const [serverVersion, setServerVersion] = useState("");
const handleUsernameChange = _ => {
if (formData.base_url) return;
if (formData.base_url || cfg_base_url) return;
// check if username is a full qualified userId then set base_url accordially
const home_server = extractHomeServer(formData.username);
const wellKnownUrl = `https://${home_server}/.well-known/matrix/client`;
@@ -157,6 +213,55 @@ const LoginPage = ({ theme }) => {
}
};
useEffect(
_ => {
if (
!formData.base_url ||
!formData.base_url.match(/^(http|https):\/\/[a-zA-Z0-9\-.]+$/)
)
return;
const versionUrl = `${formData.base_url}/_synapse/admin/v1/server_version`;
fetchUtils
.fetchJson(versionUrl, { method: "GET" })
.then(({ json }) => {
setServerVersion(
`${translate("synapseadmin.auth.server_version")} ${
json["server_version"]
}`
);
})
.catch(_ => {
setServerVersion("");
});
// Set SSO Url
const authMethodUrl = `${formData.base_url}/_matrix/client/r0/login`;
let supportPass = false,
supportSSO = false;
fetchUtils
.fetchJson(authMethodUrl, { method: "GET" })
.then(({ json }) => {
json.flows.forEach(f => {
if (f.type === "m.login.password") {
supportPass = true;
} else if (f.type === "m.login.sso") {
supportSSO = true;
}
});
setSupportPassAuth(supportPass);
if (supportSSO) {
setSSOBaseUrl(formData.base_url);
} else {
setSSOBaseUrl("");
}
})
.catch(_ => {
setSSOBaseUrl("");
});
},
[formData.base_url]
);
return (
<div>
<div className={classes.input}>
@@ -165,8 +270,9 @@ const LoginPage = ({ theme }) => {
name="username"
component={renderInput}
label={translate("ra.auth.username")}
disabled={loading}
disabled={loading || !supportPassAuth}
onBlur={handleUsernameChange}
resettable
fullWidth
/>
</div>
@@ -176,7 +282,8 @@ const LoginPage = ({ theme }) => {
component={renderInput}
label={translate("ra.auth.password")}
type="password"
disabled={loading}
disabled={loading || !supportPassAuth}
resettable
fullWidth
/>
</div>
@@ -185,17 +292,19 @@ const LoginPage = ({ theme }) => {
name="base_url"
component={renderInput}
label={translate("synapseadmin.auth.base_url")}
disabled={loading}
disabled={cfg_base_url || loading}
resettable
fullWidth
/>
</div>
<div className={classes.serverVersion}>{serverVersion}</div>
</div>
);
};
return (
<Form
initialValues={{ base_url: base_url }}
initialValues={{ base_url: cfg_base_url || base_url }}
onSubmit={handleSubmit}
validate={validate}
render={({ handleSubmit }) => (
@@ -222,6 +331,7 @@ const LoginPage = ({ theme }) => {
>
<MenuItem value="de">Deutsch</MenuItem>
<MenuItem value="en">English</MenuItem>
<MenuItem value="zh">简体中文</MenuItem>
</Select>
</div>
<FormDataConsumer>
@@ -233,13 +343,24 @@ const LoginPage = ({ theme }) => {
variant="contained"
type="submit"
color="primary"
disabled={loading}
disabled={loading || !supportPassAuth}
className={classes.button}
fullWidth
>
{loading && <CircularProgress size={25} thickness={2} />}
{translate("ra.auth.sign_in")}
</Button>
<Button
variant="contained"
color="secondary"
onClick={handleSSO}
disabled={loading || ssoBaseUrl === ""}
className={classes.button}
fullWidth
>
{loading && <CircularProgress size={25} thickness={2} />}
{translate("synapseadmin.auth.sso_sign_in")}
</Button>
</CardActions>
</Card>
<Notification />

View File

@@ -1,11 +1,11 @@
import React from "react";
import { TestContext } from "react-admin";
import { shallow } from "enzyme";
import { render } from "@testing-library/react";
import { TestContext } from "ra-test";
import LoginPage from "./LoginPage";
describe("LoginForm", () => {
it("renders", () => {
shallow(
render(
<TestContext>
<LoginPage />
</TestContext>

39
src/components/Menu.js Normal file
View File

@@ -0,0 +1,39 @@
// in src/Menu.js
import * as React from "react";
import { useSelector } from "react-redux";
import { useMediaQuery } from "@material-ui/core";
import { MenuItemLink, getResources } from "react-admin";
import DefaultIcon from "@material-ui/icons/ViewList";
import LabelIcon from "@material-ui/icons/Label";
const Menu = ({ onMenuClick, logout }) => {
const isXSmall = useMediaQuery(theme => theme.breakpoints.down("xs"));
const open = useSelector(state => state.admin.ui.sidebarOpen);
const resources = useSelector(getResources);
return (
<div>
{resources.map(resource => (
<MenuItemLink
key={resource.name}
to={`/${resource.name}`}
primaryText={
(resource.options && resource.options.label) || resource.name
}
leftIcon={resource.icon ? <resource.icon /> : <DefaultIcon />}
onClick={onMenuClick}
sidebarIsOpen={open}
/>
))}
<MenuItemLink
to="/custom-route"
primaryText="Miscellaneous"
leftIcon={<LabelIcon />}
onClick={onMenuClick}
sidebarIsOpen={open}
/>
{isXSmall && logout}
</div>
);
};
export default Menu;

View File

@@ -0,0 +1,132 @@
import React from "react";
import {
BooleanInput,
Create,
Datagrid,
DateField,
DateTimeInput,
Edit,
Filter,
List,
maxValue,
number,
NumberField,
NumberInput,
regex,
SimpleForm,
TextInput,
TextField,
Toolbar,
} from "react-admin";
const date_format = {
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
};
const validateToken = [regex(/^[A-Za-z0-9._~-]{0,64}$/)];
const validateUsesAllowed = [number()];
const validateLength = [number(), maxValue(64)];
const dateParser = v => {
const d = new Date(v);
if (isNaN(d)) return 0;
return d.getTime();
};
const dateFormatter = v => {
if (v === undefined || v === null) return;
const d = new Date(v);
const pad = "00";
const year = d.getFullYear().toString();
const month = (pad + (d.getMonth() + 1).toString()).slice(-2);
const day = (pad + d.getDate().toString()).slice(-2);
const hour = (pad + d.getHours().toString()).slice(-2);
const minute = (pad + d.getMinutes().toString()).slice(-2);
// target format yyyy-MM-ddThh:mm
return `${year}-${month}-${day}T${hour}:${minute}`;
};
const RegistrationTokenFilter = props => (
<Filter {...props}>
<BooleanInput source="valid" alwaysOn />
</Filter>
);
export const RegistrationTokenList = props => {
return (
<List
{...props}
filters={<RegistrationTokenFilter />}
filterDefaultValues={{ valid: true }}
pagination={false}
perPage={500}
>
<Datagrid rowClick="edit">
<TextField source="token" sortable={false} />
<NumberField source="uses_allowed" sortable={false} />
<NumberField source="pending" sortable={false} />
<NumberField source="completed" sortable={false} />
<DateField
source="expiry_time"
showTime
options={date_format}
sortable={false}
/>
</Datagrid>
</List>
);
};
export const RegistrationTokenCreate = props => (
<Create {...props}>
<SimpleForm redirect="list" toolbar={<Toolbar alwaysEnableSaveButton />}>
<TextInput
source="token"
autoComplete="off"
validate={validateToken}
resettable
/>
<NumberInput
source="length"
validate={validateLength}
helperText="resources.registration_tokens.helper.length"
step={1}
/>
<NumberInput
source="uses_allowed"
validate={validateUsesAllowed}
step={1}
/>
<DateTimeInput source="expiry_time" parse={dateParser} />
</SimpleForm>
</Create>
);
export const RegistrationTokenEdit = props => {
return (
<Edit {...props}>
<SimpleForm>
<TextInput source="token" disabled />
<NumberInput source="pending" disabled />
<NumberInput source="completed" disabled />
<NumberInput
source="uses_allowed"
validate={validateUsesAllowed}
step={1}
/>
<DateTimeInput
source="expiry_time"
parse={dateParser}
format={dateFormatter}
/>
</SimpleForm>
</Edit>
);
};

View File

@@ -0,0 +1,256 @@
import React, { Fragment } from "react";
import Avatar from "@material-ui/core/Avatar";
import { Chip } from "@material-ui/core";
import { connect } from "react-redux";
import FolderSharedIcon from "@material-ui/icons/FolderShared";
import { makeStyles } from "@material-ui/core/styles";
import {
BooleanField,
BulkDeleteButton,
Button,
Datagrid,
DeleteButton,
Filter,
List,
NumberField,
Pagination,
TextField,
useCreate,
useMutation,
useNotify,
useTranslate,
useRefresh,
useUnselectAll,
} from "react-admin";
const useStyles = makeStyles({
small: {
height: "40px",
width: "40px",
},
});
const RoomDirectoryPagination = props => (
<Pagination {...props} rowsPerPageOptions={[100, 500, 1000, 2000]} />
);
export const RoomDirectoryDeleteButton = props => {
const translate = useTranslate();
return (
<DeleteButton
{...props}
label="resources.room_directory.action.erase"
redirect={false}
mutationMode="pessimistic"
confirmTitle={translate("resources.room_directory.action.title", {
smart_count: 1,
})}
confirmContent={translate("resources.room_directory.action.content", {
smart_count: 1,
})}
resource="room_directory"
icon={<FolderSharedIcon />}
/>
);
};
export const RoomDirectoryBulkDeleteButton = props => (
<BulkDeleteButton
{...props}
label="resources.room_directory.action.erase"
mutationMode="pessimistic"
confirmTitle="resources.room_directory.action.title"
confirmContent="resources.room_directory.action.content"
resource="room_directory"
icon={<FolderSharedIcon />}
/>
);
export const RoomDirectoryBulkSaveButton = ({ selectedIds }) => {
const notify = useNotify();
const refresh = useRefresh();
const unselectAll = useUnselectAll();
const [createMany, { loading }] = useMutation();
const handleSend = values => {
createMany(
{
type: "createMany",
resource: "room_directory",
payload: { ids: selectedIds, data: {} },
},
{
onSuccess: ({ data }) => {
notify("resources.room_directory.action.send_success");
unselectAll("rooms");
refresh();
},
onFailure: error =>
notify("resources.room_directory.action.send_failure", "error"),
}
);
};
return (
<Button
label="resources.room_directory.action.create"
onClick={handleSend}
disabled={loading}
>
<FolderSharedIcon />
</Button>
);
};
export const RoomDirectorySaveButton = ({ record }) => {
const notify = useNotify();
const refresh = useRefresh();
const [create, { loading }] = useCreate("room_directory");
const handleSend = values => {
create(
{
payload: { data: { id: record.id } },
},
{
onSuccess: ({ data }) => {
notify("resources.room_directory.action.send_success");
refresh();
},
onFailure: error =>
notify("resources.room_directory.action.send_failure", "error"),
}
);
};
return (
<Button
label="resources.room_directory.action.create"
onClick={handleSend}
disabled={loading}
>
<FolderSharedIcon />
</Button>
);
};
const RoomDirectoryBulkActionButtons = props => (
<Fragment>
<RoomDirectoryBulkDeleteButton {...props} />
</Fragment>
);
const AvatarField = ({ source, className, record = {} }) => (
<Avatar src={record[source]} className={className} />
);
const RoomDirectoryFilter = ({ ...props }) => {
const translate = useTranslate();
return (
<Filter {...props}>
<Chip
label={translate("resources.rooms.fields.room_id")}
source="room_id"
defaultValue={false}
style={{ marginBottom: 8 }}
/>
<Chip
label={translate("resources.rooms.fields.topic")}
source="topic"
defaultValue={false}
style={{ marginBottom: 8 }}
/>
<Chip
label={translate("resources.rooms.fields.canonical_alias")}
source="canonical_alias"
defaultValue={false}
style={{ marginBottom: 8 }}
/>
</Filter>
);
};
export const FilterableRoomDirectoryList = ({
roomDirectoryFilters,
dispatch,
...props
}) => {
const classes = useStyles();
const translate = useTranslate();
const filter = roomDirectoryFilters;
const roomIdFilter = filter && filter.room_id ? true : false;
const topicFilter = filter && filter.topic ? true : false;
const canonicalAliasFilter = filter && filter.canonical_alias ? true : false;
return (
<List
{...props}
pagination={<RoomDirectoryPagination />}
bulkActionButtons={<RoomDirectoryBulkActionButtons />}
filters={<RoomDirectoryFilter />}
perPage={100}
>
<Datagrid rowClick={(id, basePath, record) => "/rooms/" + id + "/show"}>
<AvatarField
source="avatar_src"
sortable={false}
className={classes.small}
label={translate("resources.rooms.fields.avatar")}
/>
<TextField
source="name"
sortable={false}
label={translate("resources.rooms.fields.name")}
/>
{roomIdFilter && (
<TextField
source="room_id"
sortable={false}
label={translate("resources.rooms.fields.room_id")}
/>
)}
{canonicalAliasFilter && (
<TextField
source="canonical_alias"
sortable={false}
label={translate("resources.rooms.fields.canonical_alias")}
/>
)}
{topicFilter && (
<TextField
source="topic"
sortable={false}
label={translate("resources.rooms.fields.topic")}
/>
)}
<NumberField
source="num_joined_members"
sortable={false}
label={translate("resources.rooms.fields.joined_members")}
/>
<BooleanField
source="world_readable"
sortable={false}
label={translate("resources.room_directory.fields.world_readable")}
/>
<BooleanField
source="guest_can_join"
sortable={false}
label={translate("resources.room_directory.fields.guest_can_join")}
/>
</Datagrid>
</List>
);
};
function mapStateToProps(state) {
return {
roomDirectoryFilters:
state.admin.resources.room_directory.list.params.displayedFilters,
};
}
export const RoomDirectoryList = connect(mapStateToProps)(
FilterableRoomDirectoryList
);

View File

@@ -7,8 +7,10 @@ import {
Toolbar,
required,
useCreate,
useMutation,
useNotify,
useTranslate,
useUnselectAll,
} from "react-admin";
import MessageIcon from "@material-ui/icons/Message";
import IconCancel from "@material-ui/icons/Cancel";
@@ -22,7 +24,10 @@ const ServerNoticeDialog = ({ open, loading, onClose, onSend }) => {
const ServerNoticeToolbar = props => (
<Toolbar {...props}>
<SaveButton label="resources.servernotices.action.send" />
<SaveButton
label="resources.servernotices.action.send"
disabled={props.pristine}
/>
<Button label="ra.action.cancel" onClick={onClose}>
<IconCancel />
</Button>
@@ -98,3 +103,49 @@ export const ServerNoticeButton = ({ record }) => {
</Fragment>
);
};
export const ServerNoticeBulkButton = ({ selectedIds }) => {
const [open, setOpen] = useState(false);
const notify = useNotify();
const unselectAll = useUnselectAll();
const [createMany, { loading }] = useMutation();
const handleDialogOpen = () => setOpen(true);
const handleDialogClose = () => setOpen(false);
const handleSend = values => {
createMany(
{
type: "createMany",
resource: "servernotices",
payload: { ids: selectedIds, data: values },
},
{
onSuccess: ({ data }) => {
notify("resources.servernotices.action.send_success");
unselectAll("users");
handleDialogClose();
},
onFailure: error =>
notify("resources.servernotices.action.send_failure", "error"),
}
);
};
return (
<Fragment>
<Button
label="resources.servernotices.send"
onClick={handleDialogOpen}
disabled={loading}
>
<MessageIcon />
</Button>
<ServerNoticeDialog
open={open}
onClose={handleDialogClose}
onSend={handleSend}
/>
</Fragment>
);
};

89
src/components/devices.js Normal file
View File

@@ -0,0 +1,89 @@
import React, { Fragment, useState } from "react";
import {
Button,
useMutation,
useNotify,
Confirm,
useRefresh,
} from "react-admin";
import ActionDelete from "@material-ui/icons/Delete";
import { makeStyles } from "@material-ui/core/styles";
import { alpha } from "@material-ui/core/styles/colorManipulator";
import classnames from "classnames";
const useStyles = makeStyles(
theme => ({
deleteButton: {
color: theme.palette.error.main,
"&:hover": {
backgroundColor: alpha(theme.palette.error.main, 0.12),
// Reset on mouse devices
"@media (hover: none)": {
backgroundColor: "transparent",
},
},
},
}),
{ name: "RaDeleteDeviceButton" }
);
export const DeviceRemoveButton = props => {
const { record } = props;
const classes = useStyles(props);
const [open, setOpen] = useState(false);
const refresh = useRefresh();
const notify = useNotify();
const [removeDevice, { loading }] = useMutation();
if (!record) return null;
const handleClick = () => setOpen(true);
const handleDialogClose = () => setOpen(false);
const handleConfirm = () => {
removeDevice(
{
type: "delete",
resource: "devices",
payload: {
id: record.id,
user_id: record.user_id,
},
},
{
onSuccess: () => {
notify("resources.devices.action.erase.success");
refresh();
},
onFailure: () =>
notify("resources.devices.action.erase.failure", "error"),
}
);
setOpen(false);
};
return (
<Fragment>
<Button
label="ra.action.remove"
onClick={handleClick}
className={classnames("ra-delete-button", classes.deleteButton)}
>
<ActionDelete />
</Button>
<Confirm
isOpen={open}
loading={loading}
onConfirm={handleConfirm}
onClose={handleDialogClose}
title="resources.devices.action.erase.title"
content="resources.devices.action.erase.content"
translateOptions={{
id: record.id,
name: record.display_name ? record.display_name : record.id,
}}
/>
</Fragment>
);
};

327
src/components/media.js Normal file
View File

@@ -0,0 +1,327 @@
import React, { Fragment, useState } from "react";
import classnames from "classnames";
import { alpha } from "@material-ui/core/styles/colorManipulator";
import { makeStyles } from "@material-ui/core/styles";
import { Tooltip } from "@material-ui/core";
import {
BooleanInput,
Button,
DateTimeInput,
NumberInput,
SaveButton,
SimpleForm,
Toolbar,
useCreate,
useDelete,
useNotify,
useRefresh,
useTranslate,
} from "react-admin";
import BlockIcon from "@material-ui/icons/Block";
import ClearIcon from "@material-ui/icons/Clear";
import DeleteSweepIcon from "@material-ui/icons/DeleteSweep";
import Dialog from "@material-ui/core/Dialog";
import DialogContent from "@material-ui/core/DialogContent";
import DialogContentText from "@material-ui/core/DialogContentText";
import DialogTitle from "@material-ui/core/DialogTitle";
import IconCancel from "@material-ui/icons/Cancel";
import LockIcon from "@material-ui/icons/Lock";
import LockOpenIcon from "@material-ui/icons/LockOpen";
const useStyles = makeStyles(
theme => ({
deleteButton: {
color: theme.palette.error.main,
"&:hover": {
backgroundColor: alpha(theme.palette.error.main, 0.12),
// Reset on mouse devices
"@media (hover: none)": {
backgroundColor: "transparent",
},
},
},
}),
{ name: "RaDeleteDeviceButton" }
);
const DeleteMediaDialog = ({ open, loading, onClose, onSend }) => {
const translate = useTranslate();
const dateParser = v => {
const d = new Date(v);
if (isNaN(d)) return 0;
return d.getTime();
};
const DeleteMediaToolbar = props => {
return (
<Toolbar {...props}>
<SaveButton
label="resources.delete_media.action.send"
icon={<DeleteSweepIcon />}
/>
<Button label="ra.action.cancel" onClick={onClose}>
<IconCancel />
</Button>
</Toolbar>
);
};
return (
<Dialog open={open} onClose={onClose} loading={loading}>
<DialogTitle>
{translate("resources.delete_media.action.send")}
</DialogTitle>
<DialogContent>
<DialogContentText>
{translate("resources.delete_media.helper.send")}
</DialogContentText>
<SimpleForm
toolbar={<DeleteMediaToolbar />}
submitOnEnter={false}
redirect={false}
save={onSend}
>
<DateTimeInput
fullWidth
source="before_ts"
label="resources.delete_media.fields.before_ts"
defaultValue={0}
parse={dateParser}
/>
<NumberInput
fullWidth
source="size_gt"
label="resources.delete_media.fields.size_gt"
defaultValue={0}
min={0}
step={1024}
/>
<BooleanInput
fullWidth
source="keep_profiles"
label="resources.delete_media.fields.keep_profiles"
defaultValue={true}
/>
</SimpleForm>
</DialogContent>
</Dialog>
);
};
export const DeleteMediaButton = props => {
const classes = useStyles(props);
const [open, setOpen] = useState(false);
const notify = useNotify();
const [deleteOne, { loading }] = useDelete("delete_media");
const handleDialogOpen = () => setOpen(true);
const handleDialogClose = () => setOpen(false);
const handleSend = values => {
deleteOne(
{ payload: { ...values } },
{
onSuccess: () => {
notify("resources.delete_media.action.send_success");
handleDialogClose();
},
onFailure: () =>
notify("resources.delete_media.action.send_failure", "error"),
}
);
};
return (
<Fragment>
<Button
label="resources.delete_media.action.send"
onClick={handleDialogOpen}
disabled={loading}
className={classnames("ra-delete-button", classes.deleteButton)}
>
<DeleteSweepIcon />
</Button>
<DeleteMediaDialog
open={open}
onClose={handleDialogClose}
onSend={handleSend}
/>
</Fragment>
);
};
export const ProtectMediaButton = props => {
const { record } = props;
const translate = useTranslate();
const refresh = useRefresh();
const notify = useNotify();
const [create, { loading }] = useCreate("protect_media");
const [deleteOne] = useDelete("protect_media");
if (!record) return null;
const handleProtect = () => {
create(
{ payload: { data: record } },
{
onSuccess: () => {
notify("resources.protect_media.action.send_success");
refresh();
},
onFailure: () =>
notify("resources.protect_media.action.send_failure", "error"),
}
);
};
const handleUnprotect = () => {
deleteOne(
{ payload: { ...record } },
{
onSuccess: () => {
notify("resources.protect_media.action.send_success");
refresh();
},
onFailure: () =>
notify("resources.protect_media.action.send_failure", "error"),
}
);
};
return (
/*
Wrapping Tooltip with <div>
https://github.com/marmelab/react-admin/issues/4349#issuecomment-578594735
*/
<Fragment>
{record.quarantined_by && (
<Tooltip
title={translate("resources.protect_media.action.none", {
_: "resources.protect_media.action.none",
})}
>
<div>
{/*
Button instead BooleanField for
consistent appearance and position in the column
*/}
<Button disabled={true}>
<ClearIcon />
</Button>
</div>
</Tooltip>
)}
{record.safe_from_quarantine && (
<Tooltip
title={translate("resources.protect_media.action.delete", {
_: "resources.protect_media.action.delete",
})}
arrow
>
<div>
<Button onClick={handleUnprotect} disabled={loading}>
<LockIcon />
</Button>
</div>
</Tooltip>
)}
{!record.safe_from_quarantine && !record.quarantined_by && (
<Tooltip
title={translate("resources.protect_media.action.create", {
_: "resources.protect_media.action.create",
})}
>
<div>
<Button onClick={handleProtect} disabled={loading}>
<LockOpenIcon />
</Button>
</div>
</Tooltip>
)}
</Fragment>
);
};
export const QuarantineMediaButton = props => {
const { record } = props;
const translate = useTranslate();
const refresh = useRefresh();
const notify = useNotify();
const [create, { loading }] = useCreate("quarantine_media");
const [deleteOne] = useDelete("quarantine_media");
if (!record) return null;
const handleQuarantaine = () => {
create(
{ payload: { data: record } },
{
onSuccess: () => {
notify("resources.quarantine_media.action.send_success");
refresh();
},
onFailure: () =>
notify("resources.quarantine_media.action.send_failure", "error"),
}
);
};
const handleRemoveQuarantaine = () => {
deleteOne(
{ payload: { ...record } },
{
onSuccess: () => {
notify("resources.quarantine_media.action.send_success");
refresh();
},
onFailure: () =>
notify("resources.quarantine_media.action.send_failure", "error"),
}
);
};
return (
<Fragment>
{record.safe_from_quarantine && (
<Tooltip
title={translate("resources.quarantine_media.action.none", {
_: "resources.quarantine_media.action.none",
})}
>
<div>
<Button disabled={true}>
<ClearIcon />
</Button>
</div>
</Tooltip>
)}
{record.quarantined_by && (
<Tooltip
title={translate("resources.quarantine_media.action.delete", {
_: "resources.quarantine_media.action.delete",
})}
>
<div>
<Button onClick={handleRemoveQuarantaine} disabled={loading}>
<BlockIcon color="error" />
</Button>
</div>
</Tooltip>
)}
{!record.safe_from_quarantine && !record.quarantined_by && (
<Tooltip
title={translate("resources.quarantine_media.action.create", {
_: "resources.quarantine_media.action.create",
})}
>
<div>
<Button onClick={handleQuarantaine} disabled={loading}>
<BlockIcon />
</Button>
</div>
</Tooltip>
)}
</Fragment>
);
};

View File

@@ -1,17 +1,412 @@
import React from "react";
import { Datagrid, List, TextField, Pagination } from "react-admin";
import React, { Fragment } from "react";
import { connect } from "react-redux";
import {
BooleanField,
BulkDeleteButton,
DateField,
Datagrid,
DeleteButton,
Filter,
List,
NumberField,
Pagination,
ReferenceField,
ReferenceManyField,
SearchInput,
SelectField,
Show,
Tab,
TabbedShowLayout,
TextField,
TopToolbar,
useRecordContext,
useTranslate,
} from "react-admin";
import get from "lodash/get";
import PropTypes from "prop-types";
import { makeStyles } from "@material-ui/core/styles";
import { Tooltip, Typography, Chip } from "@material-ui/core";
import FastForwardIcon from "@material-ui/icons/FastForward";
import HttpsIcon from "@material-ui/icons/Https";
import NoEncryptionIcon from "@material-ui/icons/NoEncryption";
import PageviewIcon from "@material-ui/icons/Pageview";
import UserIcon from "@material-ui/icons/Group";
import ViewListIcon from "@material-ui/icons/ViewList";
import VisibilityIcon from "@material-ui/icons/Visibility";
import EventIcon from "@material-ui/icons/Event";
import {
RoomDirectoryBulkDeleteButton,
RoomDirectoryBulkSaveButton,
RoomDirectoryDeleteButton,
RoomDirectorySaveButton,
} from "./RoomDirectory";
const date_format = {
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
};
const useStyles = makeStyles(theme => ({
helper_forward_extremities: {
fontFamily: "Roboto, Helvetica, Arial, sans-serif",
margin: "0.5em",
},
}));
const RoomPagination = props => (
<Pagination {...props} rowsPerPageOptions={[10, 25, 50, 100, 500, 1000]} />
);
export const RoomList = props => (
<List {...props} pagination={<RoomPagination />}>
<Datagrid>
<TextField source="room_id" />
<TextField source="name" />
<TextField source="canonical_alias" />
<TextField source="joined_members" />
</Datagrid>
</List>
const EncryptionField = ({ source, record = {}, emptyText }) => {
const translate = useTranslate();
const value = get(record, source);
let ariaLabel = value === false ? "ra.boolean.false" : "ra.boolean.true";
if (value === false || value === true) {
return (
<Typography component="span" variant="body2">
<Tooltip title={translate(ariaLabel, { _: ariaLabel })}>
{value === true ? (
<HttpsIcon data-testid="true" htmlColor="limegreen" />
) : (
<NoEncryptionIcon data-testid="false" color="error" />
)}
</Tooltip>
</Typography>
);
}
return (
<Typography component="span" variant="body2">
{emptyText}
</Typography>
);
};
const RoomTitle = ({ record }) => {
const translate = useTranslate();
var name = "";
if (record) {
name = record.name !== "" ? record.name : record.id;
}
return (
<span>
{translate("resources.rooms.name", 1)} {name}
</span>
);
};
const RoomShowActions = ({ basePath, data, resource }) => {
var roomDirectoryStatus = "";
if (data) {
roomDirectoryStatus = data.public;
}
return (
<TopToolbar>
{roomDirectoryStatus === false && (
<RoomDirectorySaveButton record={data} />
)}
{roomDirectoryStatus === true && (
<RoomDirectoryDeleteButton record={data} />
)}
<DeleteButton
basePath={basePath}
record={data}
resource={resource}
mutationMode="pessimistic"
confirmTitle="resources.rooms.action.erase.title"
confirmContent="resources.rooms.action.erase.content"
/>
</TopToolbar>
);
};
export const RoomShow = props => {
const classes = useStyles({ props });
const translate = useTranslate();
return (
<Show {...props} actions={<RoomShowActions />} title={<RoomTitle />}>
<TabbedShowLayout>
<Tab label="synapseadmin.rooms.tabs.basic" icon={<ViewListIcon />}>
<TextField source="room_id" />
<TextField source="name" />
<TextField source="canonical_alias" />
<ReferenceField source="creator" reference="users">
<TextField source="id" />
</ReferenceField>
</Tab>
<Tab
label="synapseadmin.rooms.tabs.detail"
icon={<PageviewIcon />}
path="detail"
>
<TextField source="joined_members" />
<TextField source="joined_local_members" />
<TextField source="joined_local_devices" />
<TextField source="state_events" />
<TextField source="version" />
<TextField
source="encryption"
emptyText={translate("resources.rooms.enums.unencrypted")}
/>
</Tab>
<Tab
label="synapseadmin.rooms.tabs.members"
icon={<UserIcon />}
path="members"
>
<ReferenceManyField
reference="room_members"
target="room_id"
addLabel={false}
>
<Datagrid
style={{ width: "100%" }}
rowClick={(id, basePath, record) => "/users/" + id}
>
<TextField
source="id"
sortable={false}
label="resources.users.fields.id"
/>
<ReferenceField
label="resources.users.fields.displayname"
source="id"
reference="users"
sortable={false}
link=""
>
<TextField source="displayname" sortable={false} />
</ReferenceField>
</Datagrid>
</ReferenceManyField>
</Tab>
<Tab
label="synapseadmin.rooms.tabs.permission"
icon={<VisibilityIcon />}
path="permission"
>
<BooleanField source="federatable" />
<BooleanField source="public" />
<SelectField
source="join_rules"
choices={[
{ id: "public", name: "resources.rooms.enums.join_rules.public" },
{ id: "knock", name: "resources.rooms.enums.join_rules.knock" },
{ id: "invite", name: "resources.rooms.enums.join_rules.invite" },
{
id: "private",
name: "resources.rooms.enums.join_rules.private",
},
]}
/>
<SelectField
source="guest_access"
choices={[
{
id: "can_join",
name: "resources.rooms.enums.guest_access.can_join",
},
{
id: "forbidden",
name: "resources.rooms.enums.guest_access.forbidden",
},
]}
/>
<SelectField
source="history_visibility"
choices={[
{
id: "invited",
name: "resources.rooms.enums.history_visibility.invited",
},
{
id: "joined",
name: "resources.rooms.enums.history_visibility.joined",
},
{
id: "shared",
name: "resources.rooms.enums.history_visibility.shared",
},
{
id: "world_readable",
name: "resources.rooms.enums.history_visibility.world_readable",
},
]}
/>
</Tab>
<Tab
label={translate("resources.room_state.name", { smart_count: 2 })}
icon={<EventIcon />}
path="state"
>
<ReferenceManyField
reference="room_state"
target="room_id"
addLabel={false}
>
<Datagrid style={{ width: "100%" }}>
<TextField source="type" sortable={false} />
<DateField
source="origin_server_ts"
showTime
options={date_format}
sortable={false}
/>
<TextField source="content" sortable={false} />
<ReferenceField
source="sender"
reference="users"
sortable={false}
>
<TextField source="id" />
</ReferenceField>
</Datagrid>
</ReferenceManyField>
</Tab>
<Tab
label="resources.forward_extremities.name"
icon={<FastForwardIcon />}
path="forward_extremities"
>
<div className={classes.helper_forward_extremities}>
{translate("resources.rooms.helper.forward_extremities")}
</div>
<ReferenceManyField
reference="forward_extremities"
target="room_id"
addLabel={false}
>
<Datagrid style={{ width: "100%" }}>
<TextField source="id" sortable={false} />
<DateField
source="received_ts"
showTime
options={date_format}
sortable={false}
/>
<NumberField source="depth" sortable={false} />
<TextField source="state_group" sortable={false} />
</Datagrid>
</ReferenceManyField>
</Tab>
</TabbedShowLayout>
</Show>
);
};
const RoomBulkActionButtons = props => (
<Fragment>
<RoomDirectoryBulkSaveButton {...props} />
<RoomDirectoryBulkDeleteButton {...props} />
<BulkDeleteButton
{...props}
confirmTitle="resources.rooms.action.erase.title"
confirmContent="resources.rooms.action.erase.content"
mutationMode="pessimistic"
/>
</Fragment>
);
const RoomFilter = ({ ...props }) => {
const translate = useTranslate();
return (
<Filter {...props}>
<SearchInput source="search_term" alwaysOn />
<Chip
label={translate("resources.rooms.fields.joined_local_members")}
source="joined_local_members"
defaultValue={false}
style={{ marginBottom: 8 }}
/>
<Chip
label={translate("resources.rooms.fields.state_events")}
source="state_events"
defaultValue={false}
style={{ marginBottom: 8 }}
/>
<Chip
label={translate("resources.rooms.fields.version")}
source="version"
defaultValue={false}
style={{ marginBottom: 8 }}
/>
<Chip
label={translate("resources.rooms.fields.federatable")}
source="federatable"
defaultValue={false}
style={{ marginBottom: 8 }}
/>
</Filter>
);
};
const RoomNameField = props => {
const { source } = props;
const record = useRecordContext(props);
return (
<span>{record[source] || record["canonical_alias"] || record["id"]}</span>
);
};
RoomNameField.propTypes = {
label: PropTypes.string,
record: PropTypes.object,
source: PropTypes.string.isRequired,
};
const FilterableRoomList = ({ roomFilters, dispatch, ...props }) => {
const filter = roomFilters;
const localMembersFilter =
filter && filter.joined_local_members ? true : false;
const stateEventsFilter = filter && filter.state_events ? true : false;
const versionFilter = filter && filter.version ? true : false;
const federateableFilter = filter && filter.federatable ? true : false;
return (
<List
{...props}
pagination={<RoomPagination />}
sort={{ field: "name", order: "ASC" }}
filters={<RoomFilter />}
bulkActionButtons={<RoomBulkActionButtons />}
>
<Datagrid rowClick="show">
<EncryptionField
source="is_encrypted"
sortBy="encryption"
label={<HttpsIcon />}
/>
<RoomNameField source="name" />
<TextField source="joined_members" />
{localMembersFilter && <TextField source="joined_local_members" />}
{stateEventsFilter && <TextField source="state_events" />}
{versionFilter && <TextField source="version" />}
{federateableFilter && <BooleanField source="federatable" />}
<BooleanField source="public" />
</Datagrid>
</List>
);
};
function mapStateToProps(state) {
return {
roomFilters: state.admin.resources.rooms.list.params.displayedFilters,
};
}
export const RoomList = connect(mapStateToProps)(FilterableRoomList);

View File

@@ -0,0 +1,81 @@
import React from "react";
import { cloneElement } from "react";
import {
Datagrid,
ExportButton,
Filter,
List,
NumberField,
Pagination,
sanitizeListRestProps,
SearchInput,
TextField,
TopToolbar,
useListContext,
} from "react-admin";
import { DeleteMediaButton } from "./media";
const ListActions = props => {
const { className, exporter, filters, maxResults, ...rest } = props;
const {
currentSort,
resource,
displayedFilters,
filterValues,
showFilter,
total,
} = useListContext();
return (
<TopToolbar className={className} {...sanitizeListRestProps(rest)}>
{filters &&
cloneElement(filters, {
resource,
showFilter,
displayedFilters,
filterValues,
context: "button",
})}
<DeleteMediaButton />
<ExportButton
disabled={total === 0}
resource={resource}
sort={currentSort}
filterValues={filterValues}
maxResults={maxResults}
/>
</TopToolbar>
);
};
const UserMediaStatsPagination = props => (
<Pagination {...props} rowsPerPageOptions={[10, 25, 50, 100, 500, 1000]} />
);
const UserMediaStatsFilter = props => (
<Filter {...props}>
<SearchInput source="search_term" alwaysOn />
</Filter>
);
export const UserMediaStatsList = props => {
return (
<List
{...props}
actions={<ListActions />}
filters={<UserMediaStatsFilter />}
pagination={<UserMediaStatsPagination />}
sort={{ field: "media_length", order: "DESC" }}
bulkActionButtons={false}
>
<Datagrid rowClick={(id, basePath, record) => "/users/" + id + "/media"}>
<TextField source="user_id" label="resources.users.fields.id" />
<TextField
source="displayname"
label="resources.users.fields.displayname"
/>
<NumberField source="media_count" />
<NumberField source="media_length" />
</Datagrid>
</List>
);
};

View File

@@ -1,9 +1,19 @@
import React, { Fragment } from "react";
import React, { cloneElement, Fragment } from "react";
import Avatar from "@material-ui/core/Avatar";
import AssignmentIndIcon from "@material-ui/icons/AssignmentInd";
import ContactMailIcon from "@material-ui/icons/ContactMail";
import DevicesIcon from "@material-ui/icons/Devices";
import GetAppIcon from "@material-ui/icons/GetApp";
import NotificationsIcon from "@material-ui/icons/Notifications";
import PermMediaIcon from "@material-ui/icons/PermMedia";
import PersonPinIcon from "@material-ui/icons/PersonPin";
import SettingsInputComponentIcon from "@material-ui/icons/SettingsInputComponent";
import ViewListIcon from "@material-ui/icons/ViewList";
import {
ArrayInput,
ArrayField,
Button,
Datagrid,
DateField,
Create,
@@ -17,20 +27,109 @@ import {
FormTab,
BooleanField,
BooleanInput,
ImageField,
PasswordInput,
TextField,
TextInput,
ReferenceField,
ReferenceManyField,
SearchInput,
SelectInput,
BulkDeleteButton,
DeleteButton,
SaveButton,
maxLength,
regex,
required,
useTranslate,
Pagination,
CreateButton,
ExportButton,
TopToolbar,
sanitizeListRestProps,
NumberField,
} from "react-admin";
import { ServerNoticeButton } from "./ServerNotices";
import { Link } from "react-router-dom";
import { ServerNoticeButton, ServerNoticeBulkButton } from "./ServerNotices";
import { DeviceRemoveButton } from "./devices";
import { ProtectMediaButton, QuarantineMediaButton } from "./media";
import { makeStyles } from "@material-ui/core/styles";
const redirect = () => {
return {
pathname: "/import_users",
};
};
const useStyles = makeStyles({
small: {
height: "40px",
width: "40px",
},
large: {
height: "120px",
width: "120px",
float: "right",
},
});
const date_format = {
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
};
const UserListActions = ({
currentSort,
className,
resource,
filters,
displayedFilters,
exporter, // you can hide ExportButton if exporter = (null || false)
filterValues,
permanentFilter,
hasCreate, // you can hide CreateButton if hasCreate = false
basePath,
selectedIds,
onUnselectItems,
showFilter,
maxResults,
total,
...rest
}) => {
return (
<TopToolbar className={className} {...sanitizeListRestProps(rest)}>
{filters &&
cloneElement(filters, {
resource,
showFilter,
displayedFilters,
filterValues,
context: "button",
})}
<CreateButton basePath={basePath} />
<ExportButton
disabled={total === 0}
resource={resource}
sort={currentSort}
filter={{ ...filterValues, ...permanentFilter }}
exporter={exporter}
maxResults={maxResults}
/>
{/* Add your custom actions */}
<Button component={Link} to={redirect} label="CSV Import">
<GetAppIcon style={{ transform: "rotate(180deg)", fontSize: "20" }} />
</Button>
</TopToolbar>
);
};
UserListActions.defaultProps = {
selectedIds: [],
onUnselectItems: () => null,
};
const UserPagination = props => (
<Pagination {...props} rowsPerPageOptions={[10, 25, 50, 100, 500, 1000]} />
@@ -38,6 +137,7 @@ const UserPagination = props => (
const UserFilter = props => (
<Filter {...props}>
<SearchInput source="name" alwaysOn />
<BooleanInput source="guests" alwaysOn />
<BooleanInput
label="resources.users.fields.show_deactivated"
@@ -47,67 +147,120 @@ const UserFilter = props => (
</Filter>
);
const UserBulkActionButtons = props => {
const translate = useTranslate();
const UserBulkActionButtons = props => (
<Fragment>
<ServerNoticeBulkButton {...props} />
<BulkDeleteButton
{...props}
label="resources.users.action.erase"
confirmTitle="resources.users.helper.erase"
mutationMode="pessimistic"
/>
</Fragment>
);
const AvatarField = ({ source, className, record = {} }) => (
<Avatar src={record[source]} className={className} />
);
export const UserList = props => {
const classes = useStyles();
return (
<Fragment>
<BulkDeleteButton
{...props}
label="resources.users.action.erase"
title={translate("resources.users.helper.erase")}
/>
</Fragment>
<List
{...props}
filters={<UserFilter />}
filterDefaultValues={{ guests: true, deactivated: false }}
sort={{ field: "name", order: "ASC" }}
actions={<UserListActions maxResults={10000} />}
bulkActionButtons={<UserBulkActionButtons />}
pagination={<UserPagination />}
>
<Datagrid rowClick="edit">
<AvatarField
source="avatar_src"
className={classes.small}
sortBy="avatar_url"
/>
<TextField source="id" sortBy="name" />
<TextField source="displayname" />
<BooleanField source="is_guest" />
<BooleanField source="admin" />
<BooleanField source="deactivated" />
<DateField
source="creation_ts"
label="resources.users.fields.creation_ts_ms"
showTime
options={date_format}
/>
</Datagrid>
</List>
);
};
export const UserList = props => (
<List
{...props}
filters={<UserFilter />}
filterDefaultValues={{ guests: true, deactivated: false }}
bulkActionButtons={<UserBulkActionButtons />}
pagination={<UserPagination />}
>
<Datagrid rowClick="edit">
<ReferenceField
source="Avatar"
reference="users"
link={false}
sortable={false}
>
<ImageField source="avatar_url" title="displayname" />
</ReferenceField>
<TextField source="id" />
{/* Hack since the users endpoint does not give displaynames in the list*/}
<ReferenceField
source="name"
reference="users"
link={false}
sortable={false}
>
<TextField source="displayname" />
</ReferenceField>
<BooleanField source="is_guest" sortable={false} />
<BooleanField source="admin" sortable={false} />
<BooleanField source="deactivated" sortable={false} />
</Datagrid>
</List>
);
// https://matrix.org/docs/spec/appendices#user-identifiers
const validateUser = regex(
/^@[a-z0-9._=\-/]+:.*/,
"synapseadmin.users.invalid_user_id"
);
// here only local part of user_id
// maxLength = 255 - "@" - ":" - localStorage.getItem("home_server").length
// localStorage.getItem("home_server").length is not valid here
const validateUser = [
required(),
maxLength(253),
regex(/^[a-z0-9._=\-/]+$/, "synapseadmin.users.invalid_user_id"),
];
const validateAddress = [required(), maxLength(255)];
export function generateRandomUser() {
const homeserver = localStorage.getItem("home_server");
const user_id =
"@" +
Array(8)
.fill("0123456789abcdefghijklmnopqrstuvwxyz")
.map(
x =>
x[
Math.floor(
(crypto.getRandomValues(new Uint32Array(1))[0] /
(0xffffffff + 1)) *
x.length
)
]
)
.join("") +
":" +
homeserver;
const password = Array(20)
.fill(
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~!@-#$"
)
.map(
x =>
x[
Math.floor(
(crypto.getRandomValues(new Uint32Array(1))[0] / (0xffffffff + 1)) *
x.length
)
]
)
.join("");
return {
id: user_id,
password: password,
};
}
const UserEditToolbar = props => {
const translate = useTranslate();
return (
<Toolbar {...props}>
<SaveButton submitOnEnter={true} />
<SaveButton submitOnEnter={true} disabled={props.pristine} />
<DeleteButton
label="resources.users.action.erase"
title={translate("resources.users.helper.erase")}
confirmTitle={translate("resources.users.helper.erase", {
smart_count: 1,
})}
mutationMode="pessimistic"
/>
<ServerNoticeButton />
</Toolbar>
@@ -118,19 +271,34 @@ export const UserCreate = props => (
<Create {...props}>
<SimpleForm>
<TextInput source="id" autoComplete="off" validate={validateUser} />
<TextInput source="displayname" />
<PasswordInput source="password" autoComplete="new-password" />
<TextInput source="displayname" validate={maxLength(256)} />
<PasswordInput
source="password"
autoComplete="new-password"
validate={maxLength(512)}
/>
<BooleanInput source="admin" />
<ArrayInput source="threepids">
<SimpleFormIterator>
<SimpleFormIterator disableReordering>
<SelectInput
source="medium"
choices={[
{ id: "email", name: "resources.users.email" },
{ id: "msisdn", name: "resources.users.msisdn" },
]}
validate={required()}
/>
<TextInput source="address" validate={validateAddress} />
</SimpleFormIterator>
</ArrayInput>
<ArrayInput source="external_ids" label="synapseadmin.users.tabs.sso">
<SimpleFormIterator disableReordering>
<TextInput source="auth_provider" validate={required()} />
<TextInput
source="external_id"
label="resources.users.fields.id"
validate={required()}
/>
<TextInput source="address" />
</SimpleFormIterator>
</ArrayInput>
</SimpleForm>
@@ -141,69 +309,244 @@ const UserTitle = ({ record }) => {
const translate = useTranslate();
return (
<span>
{translate("resources.users.name")}{" "}
{translate("resources.users.name", {
smart_count: 1,
})}{" "}
{record ? `"${record.displayname}"` : ""}
</span>
);
};
export const UserEdit = props => (
<Edit {...props} title={<UserTitle />}>
<TabbedForm toolbar={<UserEditToolbar />}>
<FormTab label="resources.users.name" icon={<PersonPinIcon />}>
<TextInput source="id" disabled />
<TextInput source="displayname" />
<PasswordInput source="password" autoComplete="new-password" />
<BooleanInput source="admin" />
<BooleanInput
source="deactivated"
helperText="resources.users.helper.deactivate"
/>
<ArrayInput source="threepids">
<SimpleFormIterator>
<SelectInput
source="medium"
choices={[
{ id: "email", name: "resources.users.email" },
{ id: "msisdn", name: "resources.users.msisdn" },
]}
/>
<TextInput source="address" />
</SimpleFormIterator>
</ArrayInput>
</FormTab>
<FormTab
label="resources.connections.name"
icon={<SettingsInputComponentIcon />}
>
<ReferenceField reference="connections" source="id" addLabel={false}>
<ArrayField
source="devices[].sessions[0].connections"
label="resources.connections.name"
export const UserEdit = props => {
const classes = useStyles();
const translate = useTranslate();
return (
<Edit {...props} title={<UserTitle />}>
<TabbedForm toolbar={<UserEditToolbar />}>
<FormTab
label={translate("resources.users.name", { smart_count: 1 })}
icon={<PersonPinIcon />}
>
<AvatarField
source="avatar_src"
sortable={false}
className={classes.large}
/>
<TextInput source="id" disabled />
<TextInput source="displayname" />
<PasswordInput source="password" autoComplete="new-password" />
<BooleanInput source="admin" />
<BooleanInput
source="deactivated"
helperText="resources.users.helper.deactivate"
/>
<DateField source="creation_ts_ms" showTime options={date_format} />
<TextField source="consent_version" />
</FormTab>
<FormTab
label="resources.users.threepid"
icon={<ContactMailIcon />}
path="threepid"
>
<ArrayInput source="threepids">
<SimpleFormIterator disableReordering>
<SelectInput
source="medium"
choices={[
{ id: "email", name: "resources.users.email" },
{ id: "msisdn", name: "resources.users.msisdn" },
]}
/>
<TextInput source="address" />
</SimpleFormIterator>
</ArrayInput>
</FormTab>
<FormTab
label="synapseadmin.users.tabs.sso"
icon={<AssignmentIndIcon />}
path="sso"
>
<ArrayInput source="external_ids" label={false}>
<SimpleFormIterator disableReordering>
<TextInput source="auth_provider" validate={required()} />
<TextInput
source="external_id"
label="resources.users.fields.id"
validate={required()}
/>
</SimpleFormIterator>
</ArrayInput>
</FormTab>
<FormTab
label={translate("resources.devices.name", { smart_count: 2 })}
icon={<DevicesIcon />}
path="devices"
>
<ReferenceManyField
reference="devices"
target="user_id"
addLabel={false}
>
<Datagrid style={{ width: "100%" }}>
<TextField source="ip" sortable={false} />
<TextField source="device_id" sortable={false} />
<TextField source="display_name" sortable={false} />
<TextField source="last_seen_ip" sortable={false} />
<DateField
source="last_seen"
source="last_seen_ts"
showTime
options={{
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
}}
options={date_format}
sortable={false}
/>
<TextField
source="user_agent"
sortable={false}
style={{ width: "100%" }}
/>
<DeviceRemoveButton />
</Datagrid>
</ArrayField>
</ReferenceField>
</FormTab>
</TabbedForm>
</Edit>
);
</ReferenceManyField>
</FormTab>
<FormTab
label="resources.connections.name"
icon={<SettingsInputComponentIcon />}
path="connections"
>
<ReferenceField
reference="connections"
source="id"
addLabel={false}
link={false}
>
<ArrayField
source="devices[].sessions[0].connections"
label="resources.connections.name"
>
<Datagrid style={{ width: "100%" }}>
<TextField source="ip" sortable={false} />
<TextField source="port" sortable={false} emptyText="13001" />
<DateField
source="last_seen"
showTime
options={date_format}
sortable={false}
/>
<TextField
source="user_agent"
sortable={false}
style={{ width: "90%" }}
/>
</Datagrid>
</ArrayField>
</ReferenceField>
</FormTab>
<FormTab
label={translate("resources.users_media.name", { smart_count: 2 })}
icon={<PermMediaIcon />}
path="media"
>
<ReferenceManyField
reference="users_media"
target="user_id"
addLabel={false}
pagination={<UserPagination />}
perPage={50}
sort={{ field: "created_ts", order: "DESC" }}
>
<Datagrid style={{ width: "100%" }}>
<DateField source="created_ts" showTime options={date_format} />
<DateField
source="last_access_ts"
showTime
options={date_format}
/>
<TextField source="media_id" />
<NumberField source="media_length" />
<TextField source="media_type" />
<TextField source="upload_name" />
<TextField source="quarantined_by" />
<QuarantineMediaButton label="resources.quarantine_media.action.name" />
<ProtectMediaButton label="resources.users_media.fields.safe_from_quarantine" />
<DeleteButton mutationMode="pessimistic" redirect={false} />
</Datagrid>
</ReferenceManyField>
</FormTab>
<FormTab
label={translate("resources.urlpreview.name", { smart_count: 2 })}
icon={<PermMediaIcon />}
path="user_urlpreview"
>
<ReferenceManyField
reference="user_urlpreview"
target="user_id"
addLabel={false}
pagination={<UserPagination />}
perPage={50}
sort={{ field: "created_ts", order: "DESC" }}
>
<Datagrid style={{ width: "100%" }}>
<DateField source="created_ts" showTime options={date_format} sortable={false} />
<TextField source="media_id" sortable={false} />
<TextField source="url_cache" sortable={false} />
</Datagrid>
</ReferenceManyField>
</FormTab>
<FormTab
label={translate("resources.rooms.name", { smart_count: 2 })}
icon={<ViewListIcon />}
path="rooms"
>
<ReferenceManyField
reference="joined_rooms"
target="user_id"
addLabel={false}
>
<Datagrid
style={{ width: "100%" }}
rowClick={(id, basePath, record) => "/rooms/" + id + "/show"}
>
<TextField
source="id"
sortable={false}
label="resources.rooms.fields.room_id"
/>
<ReferenceField
label="resources.rooms.fields.name"
source="id"
reference="rooms"
sortable={false}
link=""
>
<TextField source="name" sortable={false} />
</ReferenceField>
</Datagrid>
</ReferenceManyField>
</FormTab>
<FormTab
label={translate("resources.pushers.name", { smart_count: 2 })}
icon={<NotificationsIcon />}
path="pushers"
>
<ReferenceManyField
reference="pushers"
target="user_id"
addLabel={false}
>
<Datagrid style={{ width: "100%" }}>
<TextField source="kind" sortable={false} />
<TextField source="app_display_name" sortable={false} />
<TextField source="app_id" sortable={false} />
<TextField source="data.url" sortable={false} />
<TextField source="device_display_name" sortable={false} />
<TextField source="lang" sortable={false} />
<TextField source="profile_tag" sortable={false} />
<TextField source="pushkey" sortable={false} />
</Datagrid>
</ReferenceManyField>
</FormTab>
</TabbedForm>
</Edit>
);
};

View File

@@ -1,32 +1,112 @@
import germanMessages from "ra-language-german";
export default {
const de = {
...germanMessages,
synapseadmin: {
auth: {
base_url: "Heimserver URL",
welcome: "Willkommen bei Synapse-admin",
server_version: "Synapse Version",
username_error: "Bitte vollständigen Nutzernamen angeben: '@user:domain'",
protocol_error: "Die URL muss mit 'http://' oder 'https://' beginnen",
url_error: "Keine gültige Matrix Server URL",
sso_sign_in: "Anmeldung mit SSO",
},
users: {
invalid_user_id:
"Muss eine vollständige Matrix Benutzer-ID sein, z.B. @benutzer_id:homeserver",
invalid_user_id: "Lokaler Anteil der Matrix Benutzer-ID ohne Homeserver.",
tabs: { sso: "SSO" },
},
rooms: {
details: "Raumdetails",
tabs: {
basic: "Allgemein",
members: "Mitglieder",
detail: "Details",
permission: "Berechtigungen",
},
},
reports: { tabs: { basic: "Allgemein", detail: "Details" } },
},
import_users: {
error: {
at_entry: "Bei Eintrag %{entry}: %{message}",
error: "Fehler",
required_field: "Pflichtfeld '%{field}' fehlt",
invalid_value:
"Ungültiger Wert in Zeile %{row}. Feld '%{field}' darf nur die Werte 'true' oder 'false' enthalten",
unreasonably_big: "Datei ist zu groß für den Import (%{size} Megabytes)",
already_in_progress: "Es läuft bereits ein Import",
id_exits: "ID %{id} existiert bereits",
},
title: "Benutzer aus CSV importieren",
goToPdf: "Gehe zum PDF",
cards: {
importstats: {
header: "Benutzer importieren",
users_total:
"%{smart_count} Benutzer in der CSV Datei |||| %{smart_count} Benutzer in der CSV Datei",
guest_count: "%{smart_count} Gast |||| %{smart_count} Gäste",
admin_count:
"%{smart_count} Server Administrator |||| %{smart_count} Server Administratoren",
},
conflicts: {
header: "Konfliktstrategie",
mode: {
stop: "Stoppe bei Fehlern",
skip: "Zeige Fehler und überspringe fehlerhafte Einträge",
},
},
ids: {
header: "IDs",
all_ids_present: "IDs in jedem Eintrag vorhanden",
count_ids_present:
"%{smart_count} Eintrag mit ID |||| %{smart_count} Einträge mit IDs",
mode: {
ignore: "Ignoriere IDs der CSV-Datei und erstelle neue",
update: "Aktualisiere existierende Benutzer",
},
},
passwords: {
header: "Passwörter",
all_passwords_present: "Passwörter in jedem Eintrag vorhanden",
count_passwords_present:
"%{smart_count} Eintrag mit Passwort |||| %{smart_count} Einträge mit Passwörtern",
use_passwords: "Verwende Passwörter aus der CSV Datei",
},
upload: {
header: "CSV Datei importieren",
explanation:
"Hier können Sie eine Datei mit kommagetrennten Daten hochladen, die verwendet werden um Benutzer anzulegen oder zu ändern. Die Datei muss mindestens die Felder 'id' und 'displayname' enthalten. Hier können Sie eine Beispieldatei herunterladen und anpassen: ",
},
startImport: {
simulate_only: "Nur simulieren",
run_import: "Importieren",
},
results: {
header: "Ergebnis",
total:
"%{smart_count} Eintrag insgesamt |||| %{smart_count} Einträge insgesamt",
successful: "%{smart_count} Einträge erfolgreich importiert",
skipped: "%{smart_count} Einträge übersprungen",
download_skipped: "Übersprungene Einträge herunterladen",
with_error:
"%{smart_count} Eintrag mit Fehlern ||| %{smart_count} Einträge mit Fehlern",
simulated_only: "Import-Vorgang war nur simuliert",
},
},
},
resources: {
users: {
backtolist: "Zurück zur Liste",
name: "Benutzer",
email: "E-Mail",
msisdn: "Telefon",
threepid: "E-Mail / Telefon",
fields: {
avatar: "Avatar",
id: "Benutzer-ID",
name: "Name",
is_guest: "Gast",
admin: "Admin",
admin: "Server Administrator",
deactivated: "Deaktiviert",
guests: "Zeige Gäste",
show_deactivated: "Zeige deaktivierte Benutzer",
@@ -34,12 +114,17 @@ export default {
displayname: "Anzeigename",
password: "Passwort",
avatar_url: "Avatar URL",
avatar_src: "Avatar",
medium: "Medium",
threepids: "3PIDs",
address: "Adresse",
creation_ts_ms: "Zeitpunkt der Erstellung",
consent_version: "Zugestimmte Geschäftsbedingungen",
auth_provider: "Provider",
},
helper: {
deactivate: "Deaktivierte Nutzer können nicht wieder aktiviert werden.",
deactivate:
"Sie müssen ein Passwort angeben, um ein Konto wieder zu aktivieren.",
erase: "DSGVO konformes Löschen der Benutzerdaten",
},
action: {
@@ -53,6 +138,74 @@ export default {
name: "Name",
canonical_alias: "Alias",
joined_members: "Mitglieder",
joined_local_members: "Lokale Mitglieder",
joined_local_devices: "Lokale Endgeräte",
state_events: "Zustandsereignisse / Komplexität",
version: "Version",
is_encrypted: "Verschlüsselt",
encryption: "Verschlüsselungs-Algorithmus",
federatable: "Fö­de­rierbar",
public: "Sichtbar im Raumverzeichnis",
creator: "Ersteller",
join_rules: "Beitrittsregeln",
guest_access: "Gastzugriff",
history_visibility: "Historie-Sichtbarkeit",
topic: "Thema",
avatar: "Avatar",
},
helper: {
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.",
},
enums: {
join_rules: {
public: "Öffentlich",
knock: "Auf Anfrage",
invite: "Nur auf Einladung",
private: "Privat",
},
guest_access: {
can_join: "Gäste können beitreten",
forbidden: "Gäste können nicht beitreten",
},
history_visibility: {
invited: "Ab Einladung",
joined: "Ab Beitritt",
shared: "Ab Setzen der Einstellung",
world_readable: "Jeder",
},
unencrypted: "Nicht verschlüsselt",
},
action: {
erase: {
title: "Raum löschen",
content:
"Sind Sie sicher dass Sie den Raum löschen möchten? Diese Aktion kann nicht rückgängig gemacht werden. Alle Nachrichten und Medien, die der Raum beinhaltet werden vom Server gelöscht!",
},
},
},
reports: {
name: "Ereignisbericht |||| Ereignisberichte",
fields: {
id: "ID",
received_ts: "Meldezeit",
user_id: "Meldender",
name: "Raumname",
score: "Wert",
reason: "Grund",
event_id: "Event-ID",
event_json: {
origin: "Ursprungsserver",
origin_server_ts: "Sendezeit",
type: "Eventtyp",
content: {
msgtype: "Inhaltstyp",
body: "Nachrichteninhalt",
format: "Nachrichtenformat",
formatted_body: "Formatierter Nachrichteninhalt",
algorithm: "Verschlüsselungsalgorithmus",
},
},
},
},
connections: {
@@ -63,6 +216,85 @@ export default {
user_agent: "User Agent",
},
},
devices: {
name: "Gerät |||| Geräte",
fields: {
device_id: "Geräte-ID",
display_name: "Gerätename",
last_seen_ts: "Zeitstempel",
last_seen_ip: "IP-Adresse",
},
action: {
erase: {
title: "Entferne %{id}",
content: 'Möchten Sie das Gerät "%{name}" wirklich entfernen?',
success: "Gerät erfolgreich entfernt.",
failure: "Beim Entfernen ist ein Fehler aufgetreten.",
},
},
},
users_media: {
name: "Medien",
fields: {
media_id: "Medien ID",
media_length: "Größe",
media_type: "Typ",
upload_name: "Dateiname",
quarantined_by: "Zur Quarantäne hinzugefügt",
safe_from_quarantine: "Schutz vor Quarantäne",
created_ts: "Erstellt",
last_access_ts: "Letzter Zugriff",
},
},
delete_media: {
name: "Medien",
fields: {
before_ts: "Letzter Zugriff vor",
size_gt: "Größer als (in Bytes)",
keep_profiles: "Behalte Profilbilder",
},
action: {
send: "Medien löschen",
send_success: "Anfrage erfolgreich versendet.",
send_failure: "Beim Versenden ist ein Fehler aufgetreten.",
},
helper: {
send: "Diese API löscht die lokalen Medien von der Festplatte des eigenen Servers. Dies umfasst alle lokalen Miniaturbilder und Kopien von Medien. Diese API wirkt sich nicht auf Medien aus, die sich in externen Medien-Repositories befinden.",
},
},
protect_media: {
action: {
create: "Ungeschützt, Schutz erstellen",
delete: "Geschützt, Schutz aufheben",
none: "In Quarantäne",
send_success: "Erfolgreich den Schutz-Status geändert.",
send_failure: "Beim Versenden ist ein Fehler aufgetreten.",
},
},
quarantine_media: {
action: {
name: "Quarantäne",
create: "Zur Quarantäne hinzufügen",
delete: "In Quarantäne, Quarantäne aufheben",
none: "Geschützt vor Quarantäne",
send_success: "Erfolgreich den Quarantäne-Status geändert.",
send_failure: "Beim Versenden ist ein Fehler aufgetreten.",
},
},
pushers: {
name: "Pusher |||| Pushers",
fields: {
app: "App",
app_display_name: "App-Anzeigename",
app_id: "App ID",
device_display_name: "Geräte-Anzeigename",
kind: "Art",
lang: "Sprache",
profile_tag: "Profil-Tag",
pushkey: "Pushkey",
data: { url: "URL" },
},
},
servernotices: {
name: "Serverbenachrichtigungen",
send: "Servernachricht versenden",
@@ -75,13 +307,71 @@ export default {
send_failure: "Beim Versenden ist ein Fehler aufgetreten.",
},
helper: {
send:
'Sendet eine Serverbenachrichtigung an die ausgewählten Nutzer. Hierfür muss das Feature "Server Notices" auf dem Server aktiviert sein.',
send: 'Sendet eine Serverbenachrichtigung an die ausgewählten Nutzer. Hierfür muss das Feature "Server Notices" auf dem Server aktiviert sein.',
},
},
user_media_statistics: {
name: "Dateien je Benutzer",
fields: {
media_count: "Anzahl der Dateien",
media_length: "Größe der Dateien",
},
},
forward_extremities: {
name: "Vorderextremitäten",
fields: {
id: "Event-ID",
received_ts: "Zeitstempel",
depth: "Tiefe",
state_group: "Zustandsgruppe",
},
},
room_state: {
name: "Zustandsereignisse",
fields: {
type: "Typ",
content: "Inhalt",
origin_server_ts: "Sendezeit",
sender: "Absender",
},
},
room_directory: {
name: "Raumverzeichnis",
fields: {
world_readable: "Gastbenutzer dürfen ohne Beitritt lesen",
guest_can_join: "Gastbenutzer dürfen beitreten",
},
action: {
title:
"Raum aus Verzeichnis löschen |||| %{smart_count} Räume aus Verzeichnis löschen",
content:
"Möchten Sie den Raum wirklich aus dem Raumverzeichnis löschen? |||| Möchten Sie die %{smart_count} Räume wirklich aus dem Raumverzeichnis löschen?",
erase: "Lösche aus Verzeichnis",
create: "Eintragen ins Verzeichnis",
send_success: "Raum erfolgreich eingetragen.",
send_failure: "Beim Entfernen ist ein Fehler aufgetreten.",
},
},
registration_tokens: {
name: "Registrierungstoken",
fields: {
token: "Token",
valid: "Gültige Token",
uses_allowed: "Anzahl",
pending: "Ausstehend",
completed: "Abgeschlossen",
expiry_time: "Ablaufzeit",
length: "Länge",
},
helper: { length: "Länge des Tokens, wenn kein Token vorgegeben wird." },
},
},
ra: {
...germanMessages.ra,
action: {
...germanMessages.ra.action,
unselect: "Abwählen",
},
auth: {
...germanMessages.ra.auth,
auth_check_error: "Anmeldung fehlgeschlagen",
@@ -95,8 +385,18 @@ export default {
},
},
notification: {
...germanMessages.ra.notifiaction,
...germanMessages.ra.notification,
logged_out: "Abgemeldet",
},
page: {
...germanMessages.ra.page,
empty: "Keine Einträge vorhanden",
invite: "",
},
navigation: {
...germanMessages.ra.navigation,
skip_nav: "Zum Inhalt springen",
},
},
};
export default de;

View File

@@ -1,32 +1,111 @@
import englishMessages from "ra-language-english";
export default {
const en = {
...englishMessages,
synapseadmin: {
auth: {
base_url: "Homeserver URL",
welcome: "Welcome to Synapse-admin",
server_version: "Synapse version",
username_error: "Please enter fully qualified user ID: '@user:domain'",
protocol_error: "URL has to start with 'http://' or 'https://'",
url_error: "Not a valid Matrix server URL",
sso_sign_in: "Sign in with SSO",
},
users: {
invalid_user_id:
"Must be a fully qualified Matrix user-id, e.g. @user_id:homeserver",
invalid_user_id: "Localpart of a Matrix user-id without homeserver.",
tabs: { sso: "SSO" },
},
rooms: {
tabs: {
basic: "Basic",
members: "Members",
detail: "Details",
permission: "Permissions",
},
},
reports: { tabs: { basic: "Basic", detail: "Details" } },
},
import_users: {
error: {
at_entry: "At entry %{entry}: %{message}",
error: "Error",
required_field: "Required field '%{field}' is not present",
invalid_value:
"Invalid value on line %{row}. '%{field}' field may only be 'true' or 'false'",
unreasonably_big:
"Refused to load unreasonably big file of %{size} megabytes",
already_in_progress: "An import run is already in progress",
id_exits: "ID %{id} already present",
},
title: "Import users via CSV",
goToPdf: "Go to PDF",
cards: {
importstats: {
header: "Import users",
users_total:
"%{smart_count} user in CSV file |||| %{smart_count} users in CSV file",
guest_count: "%{smart_count} guest |||| %{smart_count} guests",
admin_count: "%{smart_count} admin |||| %{smart_count} admins",
},
conflicts: {
header: "Conflict strategy",
mode: {
stop: "Stop on conflict",
skip: "Show error and skip on conflict",
},
},
ids: {
header: "IDs",
all_ids_present: "IDs present on every entry",
count_ids_present:
"%{smart_count} entry with ID |||| %{smart_count} entries with IDs",
mode: {
ignore: "Ignore IDs in CSV and create new ones",
update: "Update existing records",
},
},
passwords: {
header: "Passwords",
all_passwords_present: "Passwords present on every entry",
count_passwords_present:
"%{smart_count} entry with password |||| %{smart_count} entries with passwords",
use_passwords: "Use passwords from CSV",
},
upload: {
header: "Input CSV file",
explanation:
"Here you can upload a file with comma separated values that is processed to create or update users. The file must include the fields 'id' and 'displayname'. You can download and adapt an example file here: ",
},
startImport: {
simulate_only: "Simulate only",
run_import: "Import",
},
results: {
header: "Import results",
total:
"%{smart_count} entry in total |||| %{smart_count} entries in total",
successful: "%{smart_count} entries successfully imported",
skipped: "%{smart_count} entries skipped",
download_skipped: "Download skipped records",
with_error:
"%{smart_count} entry with errors ||| %{smart_count} entries with errors",
simulated_only: "Run was only simulated",
},
},
},
resources: {
users: {
backtolist: "Back to list",
name: "User |||| Users",
email: "Email",
msisdn: "Phone",
threepid: "Email / Phone",
fields: {
avatar: "Avatar",
id: "User-ID",
name: "Name",
is_guest: "Guest",
admin: "Admin",
admin: "Server Administrator",
deactivated: "Deactivated",
guests: "Show guests",
show_deactivated: "Show deactivated users",
@@ -34,12 +113,16 @@ export default {
displayname: "Displayname",
password: "Password",
avatar_url: "Avatar URL",
avatar_src: "Avatar",
medium: "Medium",
threepids: "3PIDs",
address: "Address",
creation_ts_ms: "Creation timestamp",
consent_version: "Consent version",
auth_provider: "Provider",
},
helper: {
deactivate: "Deactivated users cannot be reactivated",
deactivate: "You must provide a password to re-activate an account.",
erase: "Mark the user as GDPR-erased",
},
action: {
@@ -53,6 +136,74 @@ export default {
name: "Name",
canonical_alias: "Alias",
joined_members: "Members",
joined_local_members: "Local members",
joined_local_devices: "Local devices",
state_events: "State events / Complexity",
version: "Version",
is_encrypted: "Encrypted",
encryption: "Encryption",
federatable: "Federatable",
public: "Visible in room directory",
creator: "Creator",
join_rules: "Join rules",
guest_access: "Guest access",
history_visibility: "History visibility",
topic: "Topic",
avatar: "Avatar",
},
helper: {
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.",
},
enums: {
join_rules: {
public: "Public",
knock: "Knock",
invite: "Invite",
private: "Private",
},
guest_access: {
can_join: "Guests can join",
forbidden: "Guests can not join",
},
history_visibility: {
invited: "Since invited",
joined: "Since joined",
shared: "Since shared",
world_readable: "Anyone",
},
unencrypted: "Unencrypted",
},
action: {
erase: {
title: "Delete room",
content:
"Are you sure you want to delete the room? This cannot be undone. All messages and shared media in the room will be deleted from the server!",
},
},
},
reports: {
name: "Reported event |||| Reported events",
fields: {
id: "ID",
received_ts: "report time",
user_id: "announcer",
name: "name of the room",
score: "score",
reason: "reason",
event_id: "event ID",
event_json: {
origin: "origin server",
origin_server_ts: "time of send",
type: "event typ",
content: {
msgtype: "content type",
body: "content",
format: "format",
formatted_body: "formatted content",
algorithm: "algorithm",
},
},
},
},
connections: {
@@ -63,6 +214,85 @@ export default {
user_agent: "User agent",
},
},
devices: {
name: "Device |||| Devices",
fields: {
device_id: "Device-ID",
display_name: "Device name",
last_seen_ts: "Timestamp",
last_seen_ip: "IP address",
},
action: {
erase: {
title: "Removing %{id}",
content: 'Are you sure you want to remove the device "%{name}"?',
success: "Device successfully removed.",
failure: "An error has occurred.",
},
},
},
users_media: {
name: "Media",
fields: {
media_id: "Media ID",
media_length: "File Size (in Bytes)",
media_type: "Type",
upload_name: "File name",
quarantined_by: "Quarantined by",
safe_from_quarantine: "Safe from quarantine",
created_ts: "Created",
last_access_ts: "Last access",
},
},
delete_media: {
name: "Media",
fields: {
before_ts: "last access before",
size_gt: "Larger then (in bytes)",
keep_profiles: "Keep profile images",
},
action: {
send: "Delete media",
send_success: "Request successfully sent.",
send_failure: "An error has occurred.",
},
helper: {
send: "This API deletes the local media from the disk of your own server. This includes any local thumbnails and copies of media downloaded. This API will not affect media that has been uploaded to external media repositories.",
},
},
protect_media: {
action: {
create: "Unprotected, create protection",
delete: "Protected, remove protection",
none: "In quarantine",
send_success: "Successfully changed the protection status.",
send_failure: "An error has occurred.",
},
},
quarantine_media: {
action: {
name: "Quarantine",
create: "Add to quarantine",
delete: "In quarantine, unquarantine",
none: "Protected from quarantine",
send_success: "Successfully changed the quarantine status.",
send_failure: "An error has occurred.",
},
},
pushers: {
name: "Pusher |||| Pushers",
fields: {
app: "App",
app_display_name: "App display name",
app_id: "App ID",
device_display_name: "Device display name",
kind: "Kind",
lang: "Language",
profile_tag: "Profile tag",
pushkey: "Pushkey",
data: { url: "URL" },
},
},
servernotices: {
name: "Server Notices",
send: "Send server notices",
@@ -75,9 +305,64 @@ export default {
send_failure: "An error has occurred.",
},
helper: {
send:
'Sends a server notice to the selected users. The feature "Server Notices" has to be activated at the server.',
send: 'Sends a server notice to the selected users. The feature "Server Notices" has to be activated at the server.',
},
},
user_media_statistics: {
name: "Users' media",
fields: {
media_count: "Media count",
media_length: "Media length",
},
},
forward_extremities: {
name: "Forward Extremities",
fields: {
id: "Event ID",
received_ts: "Timestamp",
depth: "Depth",
state_group: "State group",
},
},
room_state: {
name: "State events",
fields: {
type: "Type",
content: "Content",
origin_server_ts: "time of send",
sender: "Sender",
},
},
room_directory: {
name: "Room directory",
fields: {
world_readable: "guest users may view without joining",
guest_can_join: "guest users may join",
},
action: {
title:
"Delete room from directory |||| Delete %{smart_count} rooms from directory",
content:
"Are you sure you want to remove this room from directory? |||| Are you sure you want to remove these %{smart_count} rooms from directory",
erase: "Delete from room directory",
create: "Publish in room directory",
send_success: "Room successfully published.",
send_failure: "An error has occurred.",
},
},
},
registration_tokens: {
name: "Registration tokens",
fields: {
token: "Token",
valid: "Valid token",
uses_allowed: "Uses allowed",
pending: "Pending",
completed: "Completed",
expiry_time: "Expiry time",
length: "Length",
},
helper: { length: "Length of the token if no token is given." },
},
};
export default en;

318
src/i18n/zh.js Normal file
View File

@@ -0,0 +1,318 @@
import chineseMessages from "ra-language-chinese";
const zh = {
...chineseMessages,
synapseadmin: {
auth: {
base_url: "服务器 URL",
welcome: "欢迎来到 Synapse-admin",
server_version: "Synapse 版本",
username_error: "请输入完整有效的用户 ID: '@user:domain'",
protocol_error: "URL 需要以'http://'或'https://'作为起始",
url_error: "不是一个有效的 Matrix 服务器地址",
sso_sign_in: "使用 SSO 登录",
},
users: {
invalid_user_id:
"必须要是一个有效的 Matrix 用户 ID ,例如 @user_id:homeserver",
tabs: { sso: "SSO" },
},
rooms: {
tabs: {
basic: "基本",
members: "成员",
detail: "细节",
permission: "权限",
},
delete: {
title: "删除房间",
message:
"您确定要删除这个房间吗?该操作无法被撤销。这个房间里所有的消息和分享的媒体都将被从服务器上删除!",
},
},
reports: { tabs: { basic: "基本", detail: "细节" } },
},
import_users: {
error: {
at_entry: "在条目 %{entry}: %{message}",
error: "错误",
required_field: "需要的值 '%{field}' 未被设置。",
invalid_value:
"第 %{row} 行出现无效值。 '%{field}' 只可以是 'true' 或 'false'。",
unreasonably_big: "拒绝加载过大的文件: %{size} MB",
already_in_progress: "一个导入进程已经在运行中",
id_exits: "ID %{id} 已经存在",
},
title: "通过 CSV 导入用户",
goToPdf: "转到 PDF",
cards: {
importstats: {
header: "导入用户",
users_total:
"%{smart_count} 用户在 CSV 文件中 |||| %{smart_count} 用户在 CSV 文件中",
guest_count: "%{smart_count} 访客 |||| %{smart_count} 访客",
admin_count: "%{smart_count} 管理员 |||| %{smart_count} 管理员",
},
conflicts: {
header: "冲突处理策略",
mode: {
stop: "在冲突处停止",
skip: "显示错误并跳过冲突",
},
},
ids: {
header: "IDs",
all_ids_present: "每条记录的 ID",
count_ids_present:
"%{smart_count} 个含 ID 的记录 |||| %{smart_count} 个含 ID 的记录",
mode: {
ignore: "忽略 CSV 中的 ID 并创建新的",
update: "更新已经存在的记录",
},
},
passwords: {
header: "密码",
all_passwords_present: "每条记录的密码",
count_passwords_present:
"%{smart_count} 个含密码的记录 |||| %{smart_count} 个含密码的记录",
use_passwords: "使用 CSV 中标记的密码",
},
upload: {
header: "导入 CSV 文件",
explanation:
"在这里,你可以上传一个用逗号分隔的文件,用于创建或更新用户。该文件必须包括 'id' 和 'displayname' 字段。你可以在这里下载并修改一个示例文件:",
},
startImport: {
simulate_only: "模拟模式",
run_import: "导入",
},
results: {
header: "导入结果",
total: "共计 %{smart_count} 条记录 |||| 共计 %{smart_count} 条记录",
successful: "%{smart_count} 条记录导入成功",
skipped: "跳过 %{smart_count} 条记录",
download_skipped: "下载跳过的记录",
with_error:
"%{smart_count} 条记录出现错误 ||| %{smart_count} 条记录出现错误",
simulated_only: "只是一次模拟运行",
},
},
},
resources: {
users: {
name: "用户",
email: "邮箱",
msisdn: "电话",
threepid: "邮箱 / 电话",
fields: {
avatar: "邮箱",
id: "用户 ID",
name: "用户名",
is_guest: "访客",
admin: "服务器管理员",
deactivated: "被禁用",
guests: "显示访客",
show_deactivated: "显示被禁用的账户",
user_id: "搜索用户",
displayname: "显示名字",
password: "密码",
avatar_url: "头像 URL",
avatar_src: "头像",
medium: "Medium",
threepids: "3PIDs",
address: "地址",
creation_ts_ms: "创建时间戳",
consent_version: "协议版本",
device_id: "设备ID"
},
helper: {
deactivate: "您必须提供一串密码来激活账户。",
erase: "将用户标记为根据 GDPR 的要求抹除了",
},
action: {
erase: "抹除用户信息",
},
},
rooms: {
name: "房间",
fields: {
room_id: "房间 ID",
name: "房间名",
canonical_alias: "别名",
joined_members: "成员",
joined_local_members: "本地成员",
state_events: "状态事件",
version: "版本",
is_encrypted: "已经加密",
encryption: "加密",
federatable: "可联合的",
public: "公开",
creator: "创建者",
join_rules: "加入规则",
guest_access: "访客访问",
history_visibility: "历史可见性",
},
enums: {
join_rules: {
public: "公开",
knock: "申请",
invite: "邀请",
private: "私有",
},
guest_access: {
can_join: "访客可以加入",
forbidden: "访客不可加入",
},
history_visibility: {
invited: "自从被邀请",
joined: "自从加入",
shared: "自从分享",
world_readable: "任何人",
},
unencrypted: "未加密",
},
helper: {
forward_extremities: "转发"
}
},
reports: {
name: "举报事件",
fields: {
id: "ID",
received_ts: "举报时间",
user_id: "举报者",
name: "房间名",
score: "分数",
reason: "原因",
event_id: "事件 ID",
event_json: {
origin: "原始服务器",
origin_server_ts: "发送时间",
type: "事件类型",
content: {
msgtype: "内容类型",
body: "内容",
format: "格式",
formatted_body: "格式化的数据",
algorithm: "算法",
},
},
},
},
connections: {
name: "连接",
fields: {
last_seen: "日期",
ip: "源IP地址",
port: "源端口",
user_agent: "用户代理 (UA)",
},
},
devices: {
name: "设备",
fields: {
device_id: "设备 ID",
display_name: "设备名",
last_seen_ts: "时间戳",
last_seen_ip: "IP 地址",
},
action: {
erase: {
title: "移除 %{id}",
content: '您确定要移除设备 "%{name}"?',
success: "设备移除成功。",
failure: "出现了一个错误。",
},
},
},
users_media: {
name: "媒体文件",
fields: {
media_id: "媒体文件 ID",
media_length: "长度",
media_type: "类型",
upload_name: "文件名",
quarantined_by: "被隔离",
safe_from_quarantine: "取消隔离",
created_ts: "创建",
last_access_ts: "上一次访问",
},
},
delete_media: {
name: "媒体文件",
fields: {
before_ts: "最后访问时间",
size_gt: "大于 (字节)",
keep_profiles: "保留头像",
},
action: {
send: "删除媒体",
send_success: "请求发送成功。",
send_failure: "出现了一个错误。",
},
helper: {
send: "这个API会删除您硬盘上的本地媒体。包含了任何的本地缓存和下载的媒体备份。这个API不会影响上传到外部媒体存储库上的媒体文件。",
},
},
pushers: {
name: "发布者",
fields: {
app: "App",
app_display_name: "App 名称",
app_id: "App ID",
device_display_name: "设备显示名",
kind: "类型",
lang: "语言",
profile_tag: "数据标签",
pushkey: "Pushkey",
data: { url: "URL" },
},
},
servernotices: {
name: "服务器提示",
send: "发送服务器提示",
fields: {
body: "信息",
},
action: {
send: "发送提示",
send_success: "服务器提示发送成功。",
send_failure: "出现了一个错误。",
},
helper: {
send: '向选中的用户发送服务器提示。服务器配置中的 "服务器提示(Server Notices)" 选项需要被设置为启用。',
},
},
user_media_statistics: {
name: "用户的媒体文件",
fields: {
media_count: "媒体文件统计",
media_length: "媒体文件长度",
},
},
room_state: {
name: "状态"
},
room_directory:{
name: "目录",
action: {
create: "新建"
}
},
forward_extremities: {
name: "转发"
},
registration_tokens: {
name: "注册"
},
urlpreview: {
name: "第三方链接"
},
quarantine_media: {
action: {
name: "隔离"
}
}
},
};
export default zh;

View File

@@ -1,4 +1,3 @@
import { configure } from "enzyme";
import Adapter from "enzyme-adapter-react-16";
import fetchMock from "jest-fetch-mock";
configure({ adapter: new Adapter() });
fetchMock.enableMocks();

View File

@@ -2,20 +2,37 @@ import { fetchUtils } from "react-admin";
const authProvider = {
// called when the user attempts to log in
login: ({ base_url, username, password }) => {
login: ({ base_url, username, password, loginToken }) => {
// force homeserver for protection in case the form is manipulated
base_url = process.env.REACT_APP_SERVER || base_url;
console.log("login ");
const options = {
method: "POST",
body: JSON.stringify({
type: "m.login.password",
user: username,
password: password,
}),
body: JSON.stringify(
Object.assign(
{
device_id: localStorage.getItem("device_id"),
initial_device_display_name: "Synapse Admin",
},
loginToken
? {
type: "m.login.token",
token: loginToken,
}
: {
type: "m.login.password",
user: username,
password: password,
}
)
),
};
// use the base_url from login instead of the well_known entry from the
// server, since the admin might want to access the admin API via some
// private address
base_url = base_url.replace(/\/+$/g, "");
localStorage.setItem("base_url", base_url);
const decoded_base_url = window.decodeURIComponent(base_url);
@@ -30,8 +47,25 @@ const authProvider = {
},
// called when the user clicks on the logout button
logout: () => {
console.log("logout ");
localStorage.removeItem("access_token");
console.log("logout");
const logout_api_url =
localStorage.getItem("base_url") + "/_matrix/client/r0/logout";
const access_token = localStorage.getItem("access_token");
const options = {
method: "POST",
user: {
authenticated: true,
token: `Bearer ${access_token}`,
},
};
if (typeof access_token === "string") {
fetchUtils.fetchJson(logout_api_url, options).then(({ json }) => {
localStorage.removeItem("access_token");
});
}
return Promise.resolve();
},
// called when the API returns an error
@@ -46,7 +80,7 @@ const authProvider = {
checkAuth: () => {
const access_token = localStorage.getItem("access_token");
console.log("checkAuth " + access_token);
return typeof access_token == "string"
return typeof access_token === "string"
? Promise.resolve()
: Promise.reject();
},

View File

@@ -14,29 +14,41 @@ const jsonClient = (url, options = {}) => {
return fetchUtils.fetchJson(url, options);
};
const mxcUrlToHttp = mxcUrl => {
const homeserver = localStorage.getItem("base_url");
const re = /^mxc:\/\/([^/]+)\/(\w+)/;
var 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 resourceMap = {
users: {
path: "/_synapse/admin/v2/users",
map: u => ({
...u,
id: u.name,
avatar_src: mxcUrlToHttp(u.avatar_url),
is_guest: !!u.is_guest,
admin: !!u.admin,
deactivated: !!u.deactivated,
// need timestamp in milliseconds
creation_ts_ms: u.creation_ts * 1000,
}),
data: "users",
total: (json, from, perPage) => {
return json.next_token
? parseInt(json.next_token, 10) + perPage
: from + json.users.length;
},
total: json => json.total,
create: data => ({
endpoint: `/_synapse/admin/v2/users/${data.id}`,
endpoint: `/_synapse/admin/v2/users/@${data.id}:${localStorage.getItem(
"home_server"
)}`,
body: data,
method: "PUT",
}),
delete: id => ({
endpoint: `/_synapse/admin/v1/deactivate/${id}`,
delete: params => ({
endpoint: `/_synapse/admin/v1/deactivate/${params.id}`,
body: { erase: true },
method: "POST",
}),
@@ -48,20 +60,169 @@ const resourceMap = {
id: r.room_id,
alias: r.canonical_alias,
members: r.joined_members,
is_encrypted: !!r.encryption,
federatable: !!r.federatable,
public: !!r.public,
}),
data: "rooms",
total: json => {
return json.total_rooms;
},
delete: params => ({
endpoint: `/_synapse/admin/v1/rooms/${params.id}`,
body: { block: false },
}),
},
reports: {
path: "/_synapse/admin/v1/event_reports",
map: er => ({
...er,
id: er.id,
}),
data: "event_reports",
total: json => json.total,
},
devices: {
map: d => ({
...d,
id: d.device_id,
}),
data: "devices",
total: json => {
return json.total;
},
reference: id => ({
endpoint: `/_synapse/admin/v2/users/${id}/devices`,
}),
delete: params => ({
endpoint: `/_synapse/admin/v2/users/${params.user_id}/devices/${params.id}`,
}),
},
connections: {
path: "/_synapse/admin/v1/whois",
map: c => ({
...c,
id: c.user_id,
id: c.user_id
}),
data: "connections",
},
room_members: {
map: m => ({
id: m,
}),
reference: id => ({
endpoint: `/_synapse/admin/v1/rooms/${id}/members`,
}),
data: "members",
total: json => {
return json.total;
},
},
room_state: {
map: rs => ({
...rs,
id: rs.event_id,
}),
reference: id => ({
endpoint: `/_synapse/admin/v1/rooms/${id}/state`,
}),
data: "state",
total: json => {
return json.state.length;
},
},
pushers: {
map: p => ({
...p,
id: p.pushkey,
}),
reference: id => ({
endpoint: `/_synapse/admin/v1/users/${id}/pushers`,
}),
data: "pushers",
total: json => {
return json.total;
},
},
joined_rooms: {
map: jr => ({
id: jr,
}),
reference: id => ({
endpoint: `/_synapse/admin/v1/users/${id}/joined_rooms`,
}),
data: "joined_rooms",
total: json => {
return json.total;
},
},
user_urlpreview: {
map: uu => ({
...uu,
id: uu.media_id,
}),
reference: id => ({
endpoint: `/_synapse/admin/v1/users/${id}/urlpreview`,
}),
data: "urlpreview",
total: json => {
return json.total;
},
},
users_media: {
map: um => ({
...um,
id: um.media_id,
}),
reference: id => ({
endpoint: `/_synapse/admin/v1/users/${id}/media`,
}),
data: "media",
total: json => {
return json.total;
},
delete: params => ({
endpoint: `/_synapse/admin/v1/media/${localStorage.getItem(
"home_server"
)}/${params.id}`,
}),
},
delete_media: {
delete: params => ({
endpoint: `/_synapse/admin/v1/media/${localStorage.getItem(
"home_server"
)}/delete?before_ts=${params.before_ts}&size_gt=${
params.size_gt
}&keep_profiles=${params.keep_profiles}`,
method: "POST",
}),
},
protect_media: {
map: pm => ({ id: pm.media_id }),
create: params => ({
endpoint: `/_synapse/admin/v1/media/protect/${params.media_id}`,
method: "POST",
}),
delete: params => ({
endpoint: `/_synapse/admin/v1/media/unprotect/${params.media_id}`,
method: "POST",
}),
},
quarantine_media: {
map: qm => ({ id: qm.media_id }),
create: params => ({
endpoint: `/_synapse/admin/v1/media/quarantine/${localStorage.getItem(
"home_server"
)}/${params.media_id}`,
method: "POST",
}),
delete: params => ({
endpoint: `/_synapse/admin/v1/media/unquarantine/${localStorage.getItem(
"home_server"
)}/${params.media_id}`,
method: "POST",
}),
},
servernotices: {
map: n => ({ id: n.event_id }),
create: data => ({
@@ -76,6 +237,76 @@ const resourceMap = {
method: "POST",
}),
},
user_media_statistics: {
path: "/_synapse/admin/v1/statistics/users/media",
map: usms => ({
...usms,
id: usms.user_id,
}),
data: "users",
total: json => {
return json.total;
},
},
forward_extremities: {
map: fe => ({
...fe,
id: fe.event_id,
}),
reference: id => ({
endpoint: `/_synapse/admin/v1/rooms/${id}/forward_extremities`,
}),
data: "results",
total: json => {
return json.count;
},
delete: params => ({
endpoint: `/_synapse/admin/v1/rooms/${params.id}/forward_extremities`,
}),
},
room_directory: {
path: "/_matrix/client/r0/publicRooms",
map: rd => ({
...rd,
id: rd.room_id,
public: !!rd.public,
guest_access: !!rd.guest_access,
avatar_src: mxcUrlToHttp(rd.avatar_url),
}),
data: "chunk",
total: json => {
return json.total_room_count_estimate;
},
create: params => ({
endpoint: `/_matrix/client/r0/directory/list/room/${params.id}`,
body: { visibility: "public" },
method: "PUT",
}),
delete: params => ({
endpoint: `/_matrix/client/r0/directory/list/room/${params.id}`,
body: { visibility: "private" },
method: "PUT",
}),
},
registration_tokens: {
path: "/_synapse/admin/v1/registration_tokens",
map: rt => ({
...rt,
id: rt.token,
}),
data: "registration_tokens",
total: json => {
return json.registration_tokens.length;
},
create: params => ({
endpoint: "/_synapse/admin/v1/registration_tokens/new",
body: params,
method: "POST",
}),
delete: params => ({
endpoint: `/_synapse/admin/v1/registration_tokens/${params.id}`,
}),
}
};
function filterNullValues(key, value) {
@@ -86,18 +317,33 @@ function filterNullValues(key, value) {
return value;
}
function getSearchOrder(order) {
if (order === "DESC") {
return "b";
} else {
return "f";
}
}
const dataProvider = {
getList: (resource, params) => {
console.log("getList " + resource);
const { user_id, guests, deactivated } = params.filter;
const { user_id, name, guests, deactivated, search_term, valid } =
params.filter;
const { page, perPage } = params.pagination;
const { field, order } = params.sort;
const from = (page - 1) * perPage;
const query = {
from: from,
limit: perPage,
user_id: user_id,
search_term: search_term,
name: name,
guests: guests,
deactivated: deactivated,
valid: valid,
order_by: field,
dir: getSearchOrder(order),
};
const homeserver = localStorage.getItem("base_url");
if (!homeserver || !(resource in resourceMap)) return Promise.reject();
@@ -138,21 +384,20 @@ const dataProvider = {
params.ids.map(id => jsonClient(`${endpoint_url}/${id}`))
).then(responses => ({
data: responses.map(({ json }) => res.map(json)),
total: responses.length,
}));
},
getManyReference: (resource, params) => {
// FIXME
console.log("getManyReference " + resource);
const { page, perPage } = params.pagination;
const { field, order } = params.sort;
const from = (page - 1) * perPage;
const query = {
sort: JSON.stringify([field, order]),
range: JSON.stringify([(page - 1) * perPage, page * perPage - 1]),
filter: JSON.stringify({
...params.filter,
[params.target]: params.id,
}),
from: from,
limit: perPage,
order_by: field,
dir: getSearchOrder(order),
};
const homeserver = localStorage.getItem("base_url");
@@ -160,12 +405,12 @@ const dataProvider = {
const res = resourceMap[resource];
const endpoint_url = homeserver + res.path;
const url = `${endpoint_url}?${stringify(query)}`;
const ref = res["reference"](params.id);
const endpoint_url = `${homeserver}${ref.endpoint}?${stringify(query)}`;
return jsonClient(url).then(({ headers, json }) => ({
data: json,
total: parseInt(headers.get("content-range").split("/").pop(), 10),
return jsonClient(endpoint_url).then(({ headers, json }) => ({
data: json[res.data].map(res.map),
total: res.total(json, from, perPage),
}));
},
@@ -221,6 +466,29 @@ const dataProvider = {
}));
},
createMany: (resource, params) => {
console.log("createMany " + resource);
const homeserver = localStorage.getItem("base_url");
if (!homeserver || !(resource in resourceMap)) return Promise.reject();
const res = resourceMap[resource];
if (!("create" in res)) return Promise.reject();
return Promise.all(
params.ids.map(id => {
params.data.id = id;
const cre = res["create"](params.data);
const endpoint_url = homeserver + cre.endpoint;
return jsonClient(endpoint_url, {
method: cre.method,
body: JSON.stringify(cre.body, filterNullValues),
});
})
).then(responses => ({
data: responses.map(({ json }) => json),
}));
},
delete: (resource, params) => {
console.log("delete " + resource);
const homeserver = localStorage.getItem("base_url");
@@ -229,11 +497,11 @@ const dataProvider = {
const res = resourceMap[resource];
if ("delete" in res) {
const del = res["delete"](params.id);
const del = res["delete"](params);
const endpoint_url = homeserver + del.endpoint;
return jsonClient(endpoint_url, {
method: del.method,
body: JSON.stringify(del.body),
method: "method" in del ? del.method : "DELETE",
body: "body" in del ? JSON.stringify(del.body) : null,
}).then(({ json }) => ({
data: json,
}));
@@ -258,11 +526,11 @@ const dataProvider = {
if ("delete" in res) {
return Promise.all(
params.ids.map(id => {
const del = res["delete"](id);
const del = res["delete"]({ ...params, id: id });
const endpoint_url = homeserver + del.endpoint;
return jsonClient(endpoint_url, {
method: del.method,
body: JSON.stringify(del.body),
method: "method" in del ? del.method : "DELETE",
body: "body" in del ? JSON.stringify(del.body) : null,
});
})
).then(responses => ({

View File

@@ -0,0 +1,78 @@
import dataProvider from "./dataProvider";
beforeEach(() => {
fetch.resetMocks();
});
describe("dataProvider", () => {
localStorage.setItem("base_url", "http://localhost");
localStorage.setItem("access_token", "access_token");
it("fetches all users", async () => {
fetch.mockResponseOnce(
JSON.stringify({
users: [
{
name: "user_id1",
password_hash: "password_hash1",
is_guest: 0,
admin: 0,
user_type: null,
deactivated: 0,
displayname: "User One",
},
{
name: "user_id2",
password_hash: "password_hash2",
is_guest: 0,
admin: 1,
user_type: null,
deactivated: 0,
displayname: "User Two",
},
],
next_token: "100",
total: 200,
})
);
const users = await dataProvider.getList("users", {
pagination: { page: 1, perPage: 5 },
sort: { field: "title", order: "ASC" },
filter: { author_id: 12 },
});
expect(users["data"][0]["id"]).toEqual("user_id1");
expect(users["total"]).toEqual(200);
expect(fetch).toHaveBeenCalledTimes(1);
});
it("fetches one user", async () => {
fetch.mockResponseOnce(
JSON.stringify({
name: "user_id1",
password: "user_password",
displayname: "User",
threepids: [
{
medium: "email",
address: "user@mail_1.com",
},
{
medium: "email",
address: "user@mail_2.com",
},
],
avatar_url: "mxc://localhost/user1",
admin: false,
deactivated: false,
})
);
const user = await dataProvider.getOne("users", { id: "user_id1" });
expect(user["data"]["id"]).toEqual("user_id1");
expect(user["data"]["displayname"]).toEqual("User");
expect(fetch).toHaveBeenCalledTimes(1);
});
});

10554
yarn.lock

File diff suppressed because it is too large Load Diff