Compare commits

..

3 Commits

Author SHA1 Message Date
Manuel Stahl
36f9ce6b07 Use vite.js instead of react-scripts
- react-scripts are not maintained anymore
- vite.js is well suited for single page applications

See https://darekkay.com/blog/create-react-app-to-vite/

Change-Id: Ib884748e373094a640b576894ff67b98c3584ec8
2024-02-07 17:03:28 +01:00
Manuel Stahl
83c9704633 Use store from react-admin instead of localStorage
By default this is the same, but it can be changed.

Change-Id: Id1b11872b5f7bc83c18f8d74b03ba6401c277da0
2024-02-07 17:03:28 +01:00
Manuel Stahl
8c1546cd5a WIP: Extract process.env
Change-Id: I9efb1079c0c88e6e0272c5fda734a367aa8f84a3
2024-02-07 17:03:28 +01:00
29 changed files with 955 additions and 7363 deletions

View File

@ -1,6 +1,7 @@
# Exclude a bunch of stuff which can make the build context a larger than it needs to be
tests/
build/
dist/
lib/
node_modules/
electron_app/

View File

@ -16,6 +16,6 @@ jobs:
with:
node-version: "18"
- name: Install dependencies
run: yarn --immutable
run: yarn --frozen-lockfile
- name: Run tests
run: yarn test

View File

@ -1,5 +1,4 @@
name: Create docker image(s) and push to docker hub and ghcr.io
# see https://docs.github.com/en/actions/publishing-packages/publishing-docker-images#publishing-images-to-docker-hub-and-github-packages
name: Create docker image(s) and push to docker hub
on:
push:
@ -14,50 +13,39 @@ on:
jobs:
docker:
name: Push Docker image to multiple registries
runs-on: ubuntu-latest
permissions:
packages: write
contents: read
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-tags: true
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Login to DockerHub
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Login to GHCR
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata (tags, labels) for Docker
id: meta
uses: docker/metadata-action@v5
with:
images: |
awesometechnologies/synapse-admin
ghcr.io/${{ github.repository }}
- 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@v5
with:
context: .
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
tags: "awesometechnologies/synapse-admin:${{ steps.set-tag.outputs.tag }}"
platforms: linux/amd64,linux/arm64

View File

@ -11,14 +11,12 @@ jobs:
steps:
- name: Checkout 🛎️
uses: actions/checkout@v4
with:
fetch-tags: true
- uses: actions/setup-node@v4
with:
node-version: "18"
- name: Install and Build 🔧
run: |
yarn install --immutable
yarn install
yarn build
- name: Deploy 🚀

View File

@ -14,19 +14,17 @@ jobs:
steps:
- uses: actions/checkout@v4
with:
fetch-tags: true
- uses: actions/setup-node@v4
with:
node-version: "18"
- run: yarn install --immutable
- 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@3198ee18f814cdf787321b4a32a26ddbf37acc52
- uses: softprops/action-gh-release@de2c0eb89ae2a093876385947365aca7b0e5f844
with:
files: dist/*.tar.gz
env:

1
.gitignore vendored
View File

@ -10,6 +10,7 @@
# production
/build
/dist
# misc
.DS_Store

6
.travis.yml Normal file
View File

@ -0,0 +1,6 @@
dist: focal
language: node_js
node_js:
- 18
cache: yarn

View File

@ -1,12 +1,12 @@
# Builder
FROM node:lts as builder
LABEL org.opencontainers.image.url=https://github.com/Awesome-Technologies/synapse-admin org.opencontainers.image.source=https://github.com/Awesome-Technologies/synapse-admin
ARG REACT_APP_SERVER
WORKDIR /src
COPY . /src
RUN yarn --network-timeout=300000 install --immutable
RUN yarn --network-timeout=300000 install
RUN REACT_APP_SERVER=$REACT_APP_SERVER yarn build

149
index.html Normal file
View File

@ -0,0 +1,149 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="shortcut icon" href="./favicon.ico" />
<meta
name="viewport"
content="minimum-scale=1, initial-scale=1, width=device-width, shrink-to-fit=no"
/>
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Synapse-Admin"
/>
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="./manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>Synapse-Admin</title>
<style>
body {
margin: 0;
padding: 0;
font-family: sans-serif;
}
.loader-container {
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
background-color: #fafafa;
}
/* CSS Spinner from https://projects.lukehaas.me/css-loaders/ */
.loader,
.loader:before,
.loader:after {
border-radius: 50%;
}
.loader {
color: #283593;
font-size: 11px;
text-indent: -99999em;
margin: 55px auto;
position: relative;
width: 10em;
height: 10em;
box-shadow: inset 0 0 0 1em;
-webkit-transform: translateZ(0);
-ms-transform: translateZ(0);
transform: translateZ(0);
}
.loader:before,
.loader:after {
position: absolute;
content: '';
}
.loader:before {
width: 5.2em;
height: 10.2em;
background: #fafafa;
border-radius: 10.2em 0 0 10.2em;
top: -0.1em;
left: -0.1em;
-webkit-transform-origin: 5.2em 5.1em;
transform-origin: 5.2em 5.1em;
-webkit-animation: load2 2s infinite ease 1.5s;
animation: load2 2s infinite ease 1.5s;
}
.loader:after {
width: 5.2em;
height: 10.2em;
background: #fafafa;
border-radius: 0 10.2em 10.2em 0;
top: -0.1em;
left: 5.1em;
-webkit-transform-origin: 0px 5.1em;
transform-origin: 0px 5.1em;
-webkit-animation: load2 2s infinite ease;
animation: load2 2s infinite ease;
}
@-webkit-keyframes load2 {
0% {
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
100% {
-webkit-transform: rotate(360deg);
transform: rotate(360deg);
}
}
@keyframes load2 {
0% {
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
100% {
-webkit-transform: rotate(360deg);
transform: rotate(360deg);
}
}
</style>
<link rel="preconnect" href="https://fonts.gstatic.com" />
<link
href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap"
rel="stylesheet"
/>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root">
<div class="loader-container">
<div class="loader">Loading...</div>
</div>
</div>
<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>
<script type="module" src="/src/index.jsx"></script>
</html>

View File

@ -1,6 +1,6 @@
{
"name": "synapse-admin",
"version": "0.9.2",
"version": "0.9.0",
"description": "Admin GUI for the Matrix.org server Synapse",
"author": "Awesome Technologies Innovationslabor GmbH",
"license": "Apache-2.0",
@ -11,34 +11,33 @@
},
"devDependencies": {
"@testing-library/jest-dom": "^6.0.0",
"@testing-library/react": "^15.0.2",
"@testing-library/react": "^14.0.0",
"@testing-library/user-event": "^14.5.2",
"eslint": "^8.57.0",
"@vitejs/plugin-react": "^4.0.0",
"eslint": "^8.56.0",
"eslint-config-prettier": "^9.1.0",
"eslint-config-react-app": "^7.0.1",
"eslint-plugin-prettier": "^5.1.3",
"jest-fetch-mock": "^3.0.3",
"prettier": "^3.2.5"
"prettier": "^3.2.5",
"vite": "^4.0.0"
},
"dependencies": {
"@mui/icons-material": "^5.15.15",
"@mui/material": "^5.15.15",
"@mui/styles": "^5.15.15",
"@mui/icons-material": "^5.15.7",
"@mui/material": "^5.15.7",
"@mui/styles": "^5.15.8",
"papaparse": "^5.4.1",
"ra-language-chinese": "^2.0.10",
"ra-language-french": "^4.16.15",
"ra-language-french": "^4.16.9",
"ra-language-german": "^3.13.4",
"ra-language-italian": "^3.13.1",
"ra-language-farsi": "^4.2.0",
"ra-language-russian": "^4.14.2",
"react": "^18.0.0",
"react-admin": "^4.16.15",
"react-dom": "^18.0.0",
"react-scripts": "^5.0.1"
"react-admin": "^4.16.9",
"react-dom": "^18.0.0"
},
"scripts": {
"start": "REACT_APP_VERSION=$(git describe --tags) react-scripts start",
"build": "REACT_APP_VERSION=$(git describe --tags) react-scripts build",
"start": "REACT_APP_VERSION=$(git describe --tags) vite serve",
"build": "REACT_APP_VERSION=$(git describe --tags) vite build",
"fix:other": "yarn prettier --write",
"fix:code": "yarn test:lint --fix",
"fix": "yarn fix:code && yarn fix:other",
@ -46,8 +45,7 @@
"test:code": "react-scripts test",
"test:lint": "eslint --ignore-path .gitignore --ext .js,.jsx .",
"test:style": "yarn prettier --list-different",
"test": "yarn test:style && yarn test:lint && yarn test:code",
"eject": "react-scripts eject"
"test": "yarn test:style && yarn test:lint && yarn test:code"
},
"eslintConfig": {
"extends": "react-app"

View File

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

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

View File

@ -14,6 +14,7 @@ import userMediaStats from "./components/statistics";
import reports from "./components/EventReports";
import roomDirectory from "./components/RoomDirectory";
import destinations from "./components/destinations";
import registrationToken from "./components/RegistrationTokens";
import LoginPage from "./components/LoginPage";
import { ImportFeature } from "./components/ImportFeature";
import { Route } from "react-router-dom";
@ -22,7 +23,8 @@ import englishMessages from "./i18n/en";
import frenchMessages from "./i18n/fr";
import chineseMessages from "./i18n/zh";
import italianMessages from "./i18n/it";
import russianMessages from "./i18n/ru";
const fixed_base_url = undefined; // FIXME: process.env.REACT_APP_SERVER;
// TODO: Can we use lazy loading together with browser locale?
const messages = {
@ -31,7 +33,6 @@ const messages = {
fr: frenchMessages,
it: italianMessages,
zh: chineseMessages,
ru: russianMessages
};
const i18nProvider = polyglotI18nProvider(
locale => (messages[locale] ? messages[locale] : messages.en),
@ -43,7 +44,7 @@ const App = () => (
disableTelemetry
requireAuth
loginPage={LoginPage}
authProvider={authProvider}
authProvider={authProvider(fixed_base_url)}
dataProvider={dataProvider}
i18nProvider={i18nProvider}
>
@ -56,6 +57,7 @@ const App = () => (
<Resource {...reports} />
<Resource {...roomDirectory} />
<Resource {...destinations} />
<Resource {...registrationToken} />
<Resource name="connections" />
<Resource name="devices" />
<Resource name="room_members" />

View File

@ -1,10 +1,9 @@
import React from "react";
import { render, screen } from "@testing-library/react";
import { render } from "@testing-library/react";
import App from "./App";
describe("App", () => {
it("renders", async () => {
it("renders", () => {
render(<App />);
await screen.findAllByText("Welcome to Synapse-admin");
});
});

View File

@ -7,6 +7,7 @@ import {
useLogin,
useNotify,
useLocaleState,
useStoreContext,
useTranslate,
PasswordInput,
TextInput,
@ -21,13 +22,13 @@ import {
CircularProgress,
MenuItem,
Select,
TextField,
Typography,
} from "@mui/material";
import { styled } from "@mui/material/styles";
import LockIcon from "@mui/icons-material/Lock";
import {
getServerVersion,
getSupportedFeatures,
getSupportedLoginFlows,
getWellKnownUrl,
isValidBaseUrl,
@ -37,7 +38,7 @@ import {
const FormBox = styled(Box)(({ theme }) => ({
display: "flex",
flexDirection: "column",
minHeight: "calc(100vh - 1rem)",
minHeight: "calc(100vh - 1em)",
alignItems: "center",
justifyContent: "flex-start",
background: "url(./images/floating-cogs.svg)",
@ -46,12 +47,12 @@ const FormBox = styled(Box)(({ theme }) => ({
backgroundSize: "cover",
[`& .card`]: {
width: "30rem",
marginTop: "6rem",
marginBottom: "6rem",
minWidth: "30em",
marginTop: "6em",
marginBottom: "6em",
},
[`& .avatar`]: {
margin: "1rem",
margin: "1em",
display: "flex",
justifyContent: "center",
},
@ -60,43 +61,36 @@ const FormBox = styled(Box)(({ theme }) => ({
},
[`& .hint`]: {
marginTop: "1em",
marginBottom: "1em",
display: "flex",
justifyContent: "center",
color: theme.palette.grey[600],
},
[`& .form`]: {
padding: "0 1rem 1rem 1rem",
padding: "0 1em 1em 1em",
},
[`& .select`]: {
marginBottom: "2rem",
[`& .input`]: {
marginTop: "1em",
},
[`& .actions`]: {
padding: "0 1rem 1rem 1rem",
padding: "0 1em 1em 1em",
},
[`& .serverVersion`]: {
color: theme.palette.grey[500],
fontFamily: "Roboto, Helvetica, Arial, sans-serif",
marginLeft: "0.5rem",
},
[`& .matrixVersions`]: {
color: theme.palette.grey[500],
fontFamily: "Roboto, Helvetica, Arial, sans-serif",
fontSize: "0.8rem",
marginBottom: "1rem",
marginLeft: "0.5rem",
marginBottom: "1em",
marginLeft: "0.5em",
},
}));
const LoginPage = () => {
const LoginPage = ({ cfg_base_url }) => {
const login = useLogin();
const notify = useNotify();
const store = useStoreContext();
const [loading, setLoading] = useState(false);
const [supportPassAuth, setSupportPassAuth] = useState(true);
const [locale, setLocale] = useLocaleState();
const translate = useTranslate();
const base_url = localStorage.getItem("base_url");
const cfg_base_url = process.env.REACT_APP_SERVER;
const base_url = store.getItem("base_url");
const [ssoBaseUrl, setSSOBaseUrl] = useState("");
const loginToken = /\?loginToken=([a-zA-Z0-9_-]+)/.exec(window.location.href);
@ -109,8 +103,8 @@ const LoginPage = () => {
"",
window.location.href.replace(loginToken[0], "#").split("#")[0]
);
const baseUrl = localStorage.getItem("sso_base_url");
localStorage.removeItem("sso_base_url");
const baseUrl = store.getItem("sso_base_url");
store.removeItem("sso_base_url");
if (baseUrl) {
const auth = {
base_url: baseUrl,
@ -134,6 +128,20 @@ const LoginPage = () => {
}
}
const renderInput = ({
meta: { touched, error } = {},
input: { ...inputProps },
...props
}) => (
<TextField
error={!!(touched && error)}
helperText={touched && error}
{...inputProps}
{...props}
fullWidth
/>
);
const validateBaseUrl = value => {
if (!value.match(/^(http|https):\/\//)) {
return translate("synapseadmin.auth.protocol_error");
@ -162,7 +170,7 @@ const LoginPage = () => {
};
const handleSSO = () => {
localStorage.setItem("sso_base_url", ssoBaseUrl);
store.setItem("sso_base_url", ssoBaseUrl);
const ssoFullUrl = `${ssoBaseUrl}/_matrix/client/r0/login/sso/redirect?redirectUrl=${encodeURIComponent(
window.location.href
)}`;
@ -172,7 +180,6 @@ const LoginPage = () => {
const UserData = ({ formData }) => {
const form = useFormContext();
const [serverVersion, setServerVersion] = useState("");
const [matrixVersions, setMatrixVersions] = useState("");
const handleUsernameChange = _ => {
if (formData.base_url || cfg_base_url) return;
@ -194,14 +201,6 @@ const LoginPage = () => {
)
.catch(() => setServerVersion(""));
getSupportedFeatures(formData.base_url)
.then(features =>
setMatrixVersions(
`${translate("synapseadmin.auth.supports_specs")} ${features.versions.join(", ")}`
)
)
.catch(() => setMatrixVersions(""));
// Set SSO Url
getSupportedLoginFlows(formData.base_url)
.then(loginFlows => {
@ -221,6 +220,7 @@ const LoginPage = () => {
<TextInput
autoFocus
name="username"
component={renderInput}
label="ra.auth.username"
disabled={loading || !supportPassAuth}
onBlur={handleUsernameChange}
@ -233,6 +233,7 @@ const LoginPage = () => {
<Box>
<PasswordInput
name="password"
component={renderInput}
label="ra.auth.password"
type="password"
disabled={loading || !supportPassAuth}
@ -245,8 +246,9 @@ const LoginPage = () => {
<Box>
<TextInput
name="base_url"
component={renderInput}
label="synapseadmin.auth.base_url"
disabled={cfg_base_url || loading}
disabled={cfg_base_url != null || loading}
resettable
fullWidth
className="input"
@ -254,7 +256,6 @@ const LoginPage = () => {
/>
</Box>
<Typography className="serverVersion">{serverVersion}</Typography>
<Typography className="matrixVersions">{matrixVersions}</Typography>
</>
);
};
@ -285,15 +286,13 @@ const LoginPage = () => {
}}
fullWidth
disabled={loading}
className="select"
className="input"
>
<MenuItem value="de">Deutsch</MenuItem>
<MenuItem value="en">English</MenuItem>
<MenuItem value="fr">Français</MenuItem>
<MenuItem value="it">Italiano</MenuItem>
<MenuItem value="zh">简体中文</MenuItem>
<MenuItem value="fa">Persian(فارسی)</MenuItem>
<MenuItem value="ru">Русский</MenuItem>
</Select>
<FormDataConsumer>
{formDataProps => <UserData {...formDataProps} />}

View File

@ -132,7 +132,7 @@ export const RegistrationTokenEdit = props => (
);
const resource = {
name: "registration_tokens",
name: "users",
icon: RegistrationTokenIcon,
list: RegistrationTokenList,
edit: RegistrationTokenEdit,

View File

@ -134,7 +134,6 @@ export const RoomShow = props => {
<Datagrid
style={{ width: "100%" }}
rowClick={(id, resource, record) => "/users/" + id}
bulkActionButtons={false}
>
<TextField
source="id"
@ -219,7 +218,7 @@ export const RoomShow = props => {
target="room_id"
addLabel={false}
>
<Datagrid style={{ width: "100%" }} bulkActionButtons={false}>
<Datagrid style={{ width: "100%" }}>
<TextField source="type" sortable={false} />
<DateField
source="origin_server_ts"
@ -257,7 +256,7 @@ export const RoomShow = props => {
target="room_id"
addLabel={false}
>
<Datagrid style={{ width: "100%" }} bulkActionButtons={false}>
<Datagrid style={{ width: "100%" }}>
<TextField source="id" sortable={false} />
<DateField
source="received_ts"

View File

@ -417,7 +417,7 @@ export const UserEdit = props => {
source="devices[].sessions[0].connections"
label="resources.connections.name"
>
<Datagrid style={{ width: "100%" }} bulkActionButtons={false}>
<Datagrid style={{ width: "100%" }}>
<TextField source="ip" sortable={false} />
<DateField
source="last_seen"
@ -480,7 +480,6 @@ export const UserEdit = props => {
<Datagrid
style={{ width: "100%" }}
rowClick={(id, resource, record) => "/rooms/" + id + "/show"}
bulkActionButtons={false}
>
<TextField
source="id"
@ -510,7 +509,7 @@ export const UserEdit = props => {
target="user_id"
addLabel={false}
>
<Datagrid style={{ width: "100%" }} bulkActionButtons={false}>
<Datagrid style={{ width: "100%" }}>
<TextField source="kind" sortable={false} />
<TextField source="app_display_name" sortable={false} />
<TextField source="app_id" sortable={false} />

View File

@ -7,7 +7,6 @@ const de = {
base_url: "Heimserver URL",
welcome: "Willkommen bei Synapse-admin",
server_version: "Synapse Version",
supports_specs: "unterstützt Matrix-Specs",
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",

View File

@ -7,7 +7,6 @@ const en = {
base_url: "Homeserver URL",
welcome: "Welcome to Synapse-admin",
server_version: "Synapse version",
supports_specs: "supports Matrix specs",
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",

View File

@ -1,382 +0,0 @@
import farsiMessages from "ra-language-farsi";
const fa = {
...farsiMessages,
synapseadmin: {
auth: {
base_url: "آدرس سرور",
welcome: "به پنل مدیریت سیناپس خوش آمدید!",
server_version: "نسخه",
username_error: "لطفاً شناسه کاربر را وارد کنید: '@user:domain'",
protocol_error: "URL باید با 'http://' یا 'https://' شروع شود",
url_error: "آدرس وارد شده یک سرور معتبر نیست",
sso_sign_in: "با SSO وارد شوید",
},
users: {
invalid_user_id: "بخش محلی یک شناسه کاربری ماتریکس بدون سرور خانگی.",
tabs: { sso: "SSO" },
},
rooms: {
tabs: {
basic: "اصلی",
members: "اعضا",
detail: "جزئیات",
permission: "مجوزها",
},
},
reports: { tabs: { basic: "اصلی", detail: "جزئیات" } },
},
import_users: {
error: {
at_entry: "در هنگام ورود %{entry}: %{message}",
error: "Error",
required_field: "فیلد الزامی '%{field}' وجود ندارد",
invalid_value:
"خطا در خط %{row}. '%{field}' فیلد ممکن است فقط 'درست' یا 'نادرست' باشد",
unreasonably_big:
"از بارگذاری فایل هایی با حجم غیر منطقی خودداری کنید %{size} مگابایت",
already_in_progress: "یک بارگذاری از قبل در حال انجام است",
id_exits: "شناسه %{id} موجود است",
},
title: "کاربران را از طریق فایل CSV وارد کنید",
goToPdf: "رفتن به PDF",
cards: {
importstats: {
header: "وارد کردن کاربران",
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: "استراتژی متغارض",
mode: {
stop: "توقف",
skip: "نمایش خطا و رد شدن",
},
},
ids: {
header: "شناسنامه ها",
all_ids_present: "شناسه های موجود در هر ورودی",
count_ids_present:
"%{smart_count} ورود با شناسه |||| %{smart_count} ورودی با شناسه",
mode: {
ignore: "شناسه ها را در CSV نادیده بگیر و شناسه های جدید ایجاد کن",
update: "سوابق موجود را به روز کنید",
},
},
passwords: {
header: "رمز عبور",
all_passwords_present: "رمزهای عبور موجود در هر ورودی",
count_passwords_present:
"%{smart_count} ورود با رمز عبور |||| %{smart_count} ورودی با رمز عبور",
use_passwords: "از پسوردهای CSV استفاده کنید",
},
upload: {
header: "Input CSV file",
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: "شناسه کاربر",
name: "نام",
is_guest: "مهمان",
admin: "مدیر سرور",
deactivated: "غیرفعال",
guests: "نمایش مهمانان",
show_deactivated: "نمایش کاربران غیرفعال شده",
user_id: "جستجوی کاربر",
displayname: "نام نمایشی",
password: "رمز عبور",
avatar_url: "آواتار سرور",
avatar_src: "آواتار",
medium: "متوسط",
threepids: "سرویس احراز هویت",
address: "آدرس",
creation_ts_ms: "ساخته شده در",
consent_version: "Consent نسخه",
auth_provider: "ارائه دهنده",
user_type: "نوع کاربر",
},
helper: {
password: "با تغییر رمز عبور کاربر از تمام دستگاه ها خارج می شود.",
deactivate: "برای فعالسازی مجدد حساب باید رمز عبور وارد کنید.",
erase: "کاربر را به عنوان GDPR پاک شده علامت گذاری کنید",
},
action: {
erase: "پاک کردن اطلاعات کاربر",
},
},
rooms: {
name: "اتاق |||| اتاق ها",
fields: {
room_id: "شناسه اتاق",
name: "نام",
canonical_alias: "نام مستعار",
joined_members: "اعضا",
joined_local_members: "اعضای محلی",
joined_local_devices: "دستگاه های محلی",
state_events: "رویدادهای حالت / پیچیدگی",
version: "نسخه",
is_encrypted: "رمزگذاری شده است",
encryption: "رمزگذاری",
federatable: "Federatable",
public: "قابل مشاهده در فهرست اتاق",
creator: "سازنده",
join_rules: "به قوانین بپیوندید",
guest_access: "دسترسی مهمان",
history_visibility: "مشاهده تاریخچه",
topic: "موضوع",
avatar: "آواتار",
},
helper: {
forward_extremities:
"اندام های رو به جلو، رویدادهای برگ در انتهای نمودار غیر چرخه ای جهت دار (DAG) در یک اتاق هستند، رویدادهایی که فرزند ندارند. هر چه تعداد بیشتری در یک اتاق وجود داشته باشد، وضوح حالت بیشتری را که سیناپس باید انجام دهد (نکته: این یک عملیات گران است). در حالی که Synapse کدی برای جلوگیری از وجود تعداد زیادی از این موارد در یک زمان در اتاق دارد، گاهی اوقات باگ‌ها می‌توانند دوباره ظاهر شوند. اگر اتاقی بیش از 10 انتهای رو به جلو دارد، بهتر است بررسی کنید که کدام اتاق مقصر است و احتمالاً آنها را با استفاده از جستارهای SQL ذکر شده در آن حذف کنید. #1760.",
},
enums: {
join_rules: {
public: "عمومی",
knock: "در زدن",
invite: "دعوت کردن",
private: "خصوصی",
},
guest_access: {
can_join: "مهمانان می توانند ملحق شوند",
forbidden: "مهمانان نمی توانند ملحق شوند",
},
history_visibility: {
invited: "از آنجایی که دعوت شده است",
joined: "از زمانی که پیوست",
shared: "از آنجایی که به اشتراک گذاشته شده است",
world_readable: "هر کسی",
},
unencrypted: "رمزگذاری نشده",
},
action: {
erase: {
title: "حذف اتاق",
content:
"آیا مطمئن هستید که می خواهید اتاق را حذف کنید؟ این قابل بازگشت نیست. همه پیام ها و رسانه های مشترک در اتاق از سرور حذف می شوند!",
},
},
},
reports: {
name: "رویداد گزارش شده |||| رویدادهای گزارش شده",
fields: {
id: "شناسه",
received_ts: "زمان گزارش",
user_id: "گوینده",
name: "نام اتاق",
score: "نمره",
reason: "دلیل",
event_id: "شناسه رویداد",
event_json: {
origin: "سرور مبدا",
origin_server_ts: "زمان ارسال",
type: "نوع رویداد",
content: {
msgtype: "نوع محتوا",
body: "محتوا",
format: "قالب",
formatted_body: "محتوای قالب بندی شده",
algorithm: "الگوریتم",
},
},
},
},
connections: {
name: "اتصالات",
fields: {
last_seen: "تاریخ",
ip: "آدرس آی پی",
user_agent: "نماینده کاربر",
},
},
devices: {
name: "دستگاه |||| دستگاه ها",
fields: {
device_id: "شناسه دستگاه",
display_name: "نام دستگاه",
last_seen_ts: "مهر زمان",
last_seen_ip: "آدرس آی پی",
},
action: {
erase: {
title: "حذف کردن %{id}",
content:
'آیا مطمئن هستید که می خواهید دستگاه را حذف کنید؟ "%{name}"?',
success: "دستگاه با موفقیت حذف شد.",
failure: "خطایی رخ داده است.",
},
},
},
users_media: {
name: "رسانه ها",
fields: {
media_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 بر رسانه‌هایی که در مخازن رسانه خارجی آپلود شده‌اند تأثیری نخواهد گذاشت.",
},
},
protect_media: {
action: {
create: "محافظت نشده، حفاظت ایجاد کنید",
delete: "محافظت شده، حفاظت را بردارید",
none: "در قرنطینه",
send_success: "وضعیت حفاظت با موفقیت تغییر کرد.",
send_failure: "خطایی رخ داده است.",
},
},
quarantine_media: {
action: {
name: "قرنطینه",
create: "به قرنطینه اضافه کنید",
delete: "در قرنطینه، غیر قرنطینه",
none: "از قرنطینه محافظت می شود",
send_success: "وضعیت قرنطینه با موفقیت تغییر کرد.",
send_failure: "خطایی رخ داده است.",
},
},
pushers: {
name: "هل دهنده |||| هل دهنده ها",
fields: {
app: "برنامه",
app_display_name: "نام نمایش برنامه",
app_id: "شناسه برنامه",
device_display_name: "نام نمایشی برنامه",
kind: "نوع",
lang: "زبان",
profile_tag: "برچسب پروفایل",
pushkey: "کلید",
data: { url: "URL" },
},
},
servernotices: {
name: "اطلاعیه های سرور",
send: "ارسال اعلانات سرور",
fields: {
body: "پیام",
},
action: {
send: "ارسال یادداشت",
send_success: "اعلان سرور با موفقیت ارسال شد.",
send_failure: "خطایی رخ داده است.",
},
helper: {
send: "اعلان سرور را برای کاربران انتخاب شده ارسال می کند. ویژگی 'اعلامیه های سرور' باید در سرور فعال شود.",
},
},
user_media_statistics: {
name: "رسانه کاربران",
fields: {
media_count: "شمارش رسانه ها",
media_length: "طول رسانه",
},
},
forward_extremities: {
name: "Forward Extremities",
fields: {
id: "شناسه رویداد",
received_ts: "مهر زمان",
depth: "عمق",
state_group: "گروه دولتی",
},
},
room_state: {
name: "رویدادهای وضعیت",
fields: {
type: "نوع",
content: "محتوا",
origin_server_ts: "زمان ارسال",
sender: "فرستنده",
},
},
room_directory: {
name: "راهنمای اتاق",
fields: {
world_readable: "کاربران مهمان می توانند بدون عضویت مشاهده کنند",
guest_can_join: "کاربران مهمان ممکن است ملحق شوند",
},
action: {
title:
"اتاق را از فهرست حذف کنید |||| حذف کنید %{smart_count} اتاق ها از دایرکتوری",
content:
"آیا مطمئنید که می خواهید این اتاق را از فهرست راهنمای حذف کنید؟ |||| آیا مطمئن هستید که می خواهید این موارد را %{smart_count} از راهنمای اتاق ها حذف کنید؟",
erase: "حذف از فهرست اتاق",
create: "انتشار در راهنما اتاق",
send_success: "اتاق با موفقیت منتشر شد.",
send_failure: "خطایی رخ داده است.",
},
},
destinations: {
name: "سرور های مرتبط",
fields: {
destination: "آدرس",
failure_ts: "زمان شکست",
retry_last_ts: "آخرین زمان اتصال",
retry_interval: "بازه امتحان مجدد",
last_successful_stream_ordering: "آخرین جریان موفق",
stream_ordering: "جریان",
},
action: { reconnect: "دوباره وصل شوید" },
},
},
registration_tokens: {
name: "توکن های ثبت نام",
fields: {
token: "توکن",
valid: "توکن معتبر",
uses_allowed: "موارد استفاده مجاز",
pending: "انتظار",
completed: "تکمیل شد",
expiry_time: "زمان انقضا",
length: "طول",
},
helper: { length: "طول توکن در صورت عدم ارائه توکن." },
},
};
export default fa;

View File

@ -1,390 +0,0 @@
import russianMessages from "ra-language-russian";
const ru = {
...russianMessages,
synapseadmin: {
auth: {
base_url: "Домашняя страница",
welcome: "Добро пожаловать в Synapse-admin",
server_version: "Версия Synapse",
supports_specs: "поддерживает спецификации Matrix",
username_error: "Введите полный идентификатор пользователя: '@user:domain'",
protocol_error: "Адрес должен начинаться с 'http://' или 'https://'",
url_error: "Некорректный сервер Matrix",
sso_sign_in: "Присоединиться с помощью SSO",
},
users: {
invalid_user_id: "Локальная часть идентификатора пользователя Matrix без домашнего сервера.",
tabs: { sso: "SSO" },
},
rooms: {
tabs: {
basic: "Основное",
members: "Участники",
detail: "Подробности",
permission: "Права",
},
},
reports: { tabs: { basic: "Основное", detail: "Подробности" } },
},
import_users: {
error: {
at_entry: "При входе %{entry}: %{message}",
error: "Ошибка",
required_field: "Обязательное поле '%{field}' не представленно",
invalid_value:
"Недопустимое значение в строке %{row}. '%{field}' поле может быть только 'true' или 'false'",
unreasonably_big:
"Отказался загружать неоправданно большой файл %{size} Мбайт",
already_in_progress: "Импорт уже запущен",
id_exits: "Идентификатор %{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: "Идентификаторы",
all_ids_present: "Идентификаторы представлены для каждой записи",
count_ids_present:
"%{smart_count} запись с идентификатором |||| %{smart_count} записей с идентификатором",
mode: {
ignore: "Игнорировать идентификаторы в CSV и создавать новые",
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: "Идентификатор пользователя",
name: "Имя",
is_guest: "Гость",
admin: "Администратор",
deactivated: "Деактивирован",
guests: "Показать гостей",
show_deactivated: "Показать деактивированных пользователей",
user_id: "Найти пользователя",
displayname: "Отображаемое имя",
password: "Пароль",
avatar_url: "Ссылка на аватар",
avatar_src: "Аватар",
medium: "Тип",
threepids: "Иной идентификатор",
address: "Адрес",
creation_ts_ms: "Время создания",
consent_version: "Версия соглашения",
auth_provider: "Поставщик",
user_type: "Тип пользователя",
},
helper: {
password: "Изменение пароля приведет к выходу пользователя из всех сеансов.",
deactivate: "Вы должны ввести пароль для повторной активации учетной записи.",
erase: "Пометить пользователя как удаленного в связи с защитой персональных данных",
},
action: {
erase: "Удаление пользовательских данных",
},
},
rooms: {
name: "Комнат |||| Комнаты",
fields: {
room_id: "Идентификатор комнаты",
name: "Название",
canonical_alias: "Псевдоним",
joined_members: "Участники",
joined_local_members: "Внутренние участники",
joined_local_devices: "Используемые устройства",
state_events: "События изменения состояния",
version: "Версия",
is_encrypted: "Зашифрованно",
encryption: "Шифрование",
federatable: "Федерация",
public: "Видимость в списке комнат",
creator: "Создатель",
join_rules: "Правила присоединения",
guest_access: "Гостевой доступ",
history_visibility: "Видимость истории",
topic: "Тема",
avatar: "Аватар",
},
helper: {
forward_extremities:
"Перенаправленные заключения, это такие события, которые не имеют потомков в рамках графа, отвечающего за их репрезентацию. Чем больше пользователей находится в комнате, тем больше операций требуется выполнить Synapse для разрешения коллиций, которые возникают при их проверке наступления событий (это дорогостоящая операция). Хотя в Synapse есть код, предотвращающий одновременное присутствие слишком большого количества таких объектов в комнате, ошибки иногда могут привести к их повторному появлению. Если в комнате содержится >10 перенаправленных заключений, имеет смысл выяснить, какая комната стала причиной их появления и, возможно, удалить их, используя SQL-запросы, упомянутые issue #1760.",
},
enums: {
join_rules: {
public: "Публичный",
knock: "По запросу",
invite: "По приглашению",
private: "Приватный",
},
guest_access: {
can_join: "Гости могут присоединиться",
forbidden: "Гости не могут присоединиться",
},
history_visibility: {
invited: "С момента приглашения",
joined: "С момента присоединения",
shared: "С момента разрешения",
world_readable: "Всегда",
},
unencrypted: "Не зашифрованно",
},
action: {
erase: {
title: "Удалить комнату",
content:
"Вы уверены, что хотите удалить комнату? Это невозможно отменить. Все сообщения и медиафайлы, находящиеся в общем доступе в комнате, будут удалены с сервера!",
},
},
},
reports: {
name: "Жалоб |||| Жалобы",
fields: {
id: "идентификатор",
received_ts: "время жалобы",
user_id: "коментатор",
name: "название комнаты",
score: "оценка",
reason: "причина",
event_id: "идентификатор события",
event_json: {
origin: "сервер",
origin_server_ts: "время отправки",
type: "тип события",
content: {
msgtype: "тип содержания",
body: "содержание",
format: "формат",
formatted_body: "форматированное содержание",
algorithm: "алгоритм",
},
},
},
action: {
erase: {
title: "Удалить жалобу",
content:
"Вы уверены, что хотите удалить жалобу? Это невозможно отменить.",
},
},
},
connections: {
name: "Подключения",
fields: {
last_seen: "Дата",
ip: "IP адрес",
user_agent: "User agent",
},
},
devices: {
name: "Устройств |||| Устройства",
fields: {
device_id: "Идентификатор устройства",
display_name: "Название устройства",
last_seen_ts: "Метка времени",
last_seen_ip: "IP адрес",
},
action: {
erase: {
title: "Удаление %{id}",
content: 'Вы уверены, что хотите удалить устройство "%{name}"?',
success: "Устройство успешно удалено.",
failure: "Произошла ошибка.",
},
},
},
users_media: {
name: "Медиа",
fields: {
media_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: "Этот метод удаляет медиафайлы с диска сервера. Это включает в себя любые миниатюры и копии загруженных файлов. Этот метод не повлияет на файлы, загруженные во внешние хранилища.",
},
},
protect_media: {
action: {
create: "Не защищено, установить защиту",
delete: "Защищено, удалить защиту",
none: "В карантине",
send_success: "Успешно изменен статус защиты.",
send_failure: "Произошла ошибка.",
},
},
quarantine_media: {
action: {
name: "Карантин",
create: "Добавить в карантин",
delete: "В карантине, вывести из карантина",
none: "Защищено от карантина",
send_success: "Успешно изменен статус карантина.",
send_failure: "Произошла ошибка.",
},
},
pushers: {
name: "Уведомление |||| Уведомления",
fields: {
app: "Приложение",
app_display_name: "Отображаемое имя приложения",
app_id: "Идентификатор приложения",
device_display_name: "Отображаемое имя устройства",
kind: "Тип",
lang: "Язык",
profile_tag: "Тег профиля",
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: "Длина медиафайлов",
},
},
forward_extremities: {
name: "Перенаправленные заключения",
fields: {
id: "Идентификатор события",
received_ts: "Время",
depth: "Глубина",
state_group: "Группа состояния",
},
},
room_state: {
name: "События изменения состояния",
fields: {
type: "Тип",
content: "Содержание",
origin_server_ts: "время отправления",
sender: "Отправитель",
},
},
room_directory: {
name: "Публичных комнат |||| Публичные комнаты",
fields: {
world_readable: "Видимо для гостей",
guest_can_join: "Гости могут присоединиться",
},
action: {
title:
"Удалить комнату |||| Удалить %{smart_count} комнат",
content:
"Вы уверены, что хотите удалить комнату? |||| Вы уверены, что хотите удалить %{smart_count} комнат?",
erase: "Удалить комнату",
create: "Опубликовать комнату",
send_success: "Комната успешно опубликована.",
send_failure: "Произошла ошибка.",
},
},
destinations: {
name: "Федераций |||| Федерация",
fields: {
destination: "Назначение",
failure_ts: "Время сбоя",
retry_last_ts: "Время последней попытки",
retry_interval: "Интервал повторения",
last_successful_stream_ordering: "Последнее успешное соединение",
stream_ordering: "Соединение",
},
action: { reconnect: "Переподключиться" },
},
},
registration_tokens: {
name: "Токены регистрации",
fields: {
token: "Токен",
valid: "Допустимый токен",
uses_allowed: "Разрешено",
pending: "Ожидается",
completed: "Использован",
expiry_time: "Время истечения срока действия",
length: "Длина",
},
helper: { length: "Длина токена, если токен не указан." },
},
};
export default ru;

View File

@ -1,8 +1,10 @@
import React from "react";
import { createRoot } from "react-dom/client";
import ReactDOM from "react-dom/client";
import App from "./App";
createRoot(document.getElementById("root")).render(
const REACT_APP_SERVER = import.meta.env.VITE_APP_SERVER;
ReactDOM.createRoot(document.getElementById("root")).render(
<React.StrictMode>
<App />
</React.StrictMode>

View File

@ -1,10 +1,10 @@
import { fetchUtils } from "react-admin";
const authProvider = {
const authProvider = (fixed_base_url, store) => ({
// called when the user attempts to log in
login: async ({ base_url, username, password, loginToken }) => {
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;
base_url = fixed_base_url || base_url;
console.log("login ");
const options = {
@ -12,7 +12,7 @@ const authProvider = {
body: JSON.stringify(
Object.assign(
{
device_id: localStorage.getItem("device_id"),
device_id: store.getItem("device_id"),
initial_device_display_name: "Synapse Admin",
},
loginToken
@ -33,19 +33,20 @@ const authProvider = {
// 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);
store.setItem("base_url", base_url);
const decoded_base_url = window.decodeURIComponent(base_url);
const login_api_url = decoded_base_url + "/_matrix/client/r0/login";
const { json } = await fetchUtils.fetchJson(login_api_url, options);
localStorage.setItem("home_server", json.home_server);
localStorage.setItem("user_id", json.user_id);
localStorage.setItem("access_token", json.access_token);
localStorage.setItem("device_id", json.device_id);
return fetchUtils.fetchJson(login_api_url, options).then(({ json }) => {
store.setItem("home_server", json.home_server);
store.setItem("user_id", json.user_id);
store.setItem("access_token", json.access_token);
store.setItem("device_id", json.device_id);
});
},
// called when the user clicks on the logout button
logout: async () => {
logout: () => {
console.log("logout");
const logout_api_url =
@ -61,9 +62,11 @@ const authProvider = {
};
if (typeof access_token === "string") {
await fetchUtils.fetchJson(logout_api_url, options);
fetchUtils.fetchJson(logout_api_url, options).then(({ json }) => {
localStorage.removeItem("access_token");
});
}
return Promise.resolve();
},
// called when the API returns an error
checkError: ({ status }) => {
@ -83,6 +86,6 @@ const authProvider = {
},
// called when the user navigates to a new location, to check for permissions / roles
getPermissions: () => Promise.resolve(),
};
});
export default authProvider;

View File

@ -1,135 +0,0 @@
import authProvider from "./authProvider";
describe("authProvider", () => {
beforeEach(() => {
fetch.resetMocks();
localStorage.clear();
});
describe("login", () => {
it("should successfully login with username and password", async () => {
fetch.once(
JSON.stringify({
home_server: "example.com",
user_id: "@user:example.com",
access_token: "foobar",
device_id: "some_device",
})
);
const ret = await authProvider.login({
base_url: "http://example.com",
username: "@user:example.com",
password: "secret",
});
expect(ret).toBe(undefined);
expect(fetch).toBeCalledWith(
"http://example.com/_matrix/client/r0/login",
{
body: '{"device_id":null,"initial_device_display_name":"Synapse Admin","type":"m.login.password","user":"@user:example.com","password":"secret"}',
headers: new Headers({
Accept: ["application/json"],
"Content-Type": ["application/json"],
}),
method: "POST",
}
);
expect(localStorage.getItem("base_url")).toEqual("http://example.com");
expect(localStorage.getItem("user_id")).toEqual("@user:example.com");
expect(localStorage.getItem("access_token")).toEqual("foobar");
expect(localStorage.getItem("device_id")).toEqual("some_device");
});
});
it("should successfully login with token", async () => {
fetch.once(
JSON.stringify({
home_server: "example.com",
user_id: "@user:example.com",
access_token: "foobar",
device_id: "some_device",
})
);
const ret = await authProvider.login({
base_url: "https://example.com/",
loginToken: "login_token",
});
expect(ret).toBe(undefined);
expect(fetch).toBeCalledWith(
"https://example.com/_matrix/client/r0/login",
{
body: '{"device_id":null,"initial_device_display_name":"Synapse Admin","type":"m.login.token","token":"login_token"}',
headers: new Headers({
Accept: ["application/json"],
"Content-Type": ["application/json"],
}),
method: "POST",
}
);
expect(localStorage.getItem("base_url")).toEqual("https://example.com");
expect(localStorage.getItem("user_id")).toEqual("@user:example.com");
expect(localStorage.getItem("access_token")).toEqual("foobar");
expect(localStorage.getItem("device_id")).toEqual("some_device");
});
describe("logout", () => {
it("should remove the access_token from localStorage", async () => {
localStorage.setItem("base_url", "example.com");
localStorage.setItem("access_token", "foo");
fetch.mockResponse(JSON.stringify({}));
await authProvider.logout();
expect(fetch).toBeCalledWith("example.com/_matrix/client/r0/logout", {
headers: new Headers({
Accept: ["application/json"],
Authorization: ["Bearer foo"],
}),
method: "POST",
user: { authenticated: true, token: "Bearer foo" },
});
expect(localStorage.getItem("access_token")).toBeNull();
});
});
describe("checkError", () => {
it("should resolve if error.status is not 401 or 403", async () => {
await expect(
authProvider.checkError({ status: 200 })
).resolves.toBeUndefined();
});
it("should reject if error.status is 401", async () => {
await expect(
authProvider.checkError({ status: 401 })
).rejects.toBeUndefined();
});
it("should reject if error.status is 403", async () => {
await expect(
authProvider.checkError({ status: 403 })
).rejects.toBeUndefined();
});
});
describe("checkAuth", () => {
it("should reject when not logged in", async () => {
await expect(authProvider.checkAuth({})).rejects.toBeUndefined();
});
it("should resolve when logged in", async () => {
localStorage.setItem("access_token", "foobar");
await expect(authProvider.checkAuth({})).resolves.toBeUndefined();
});
});
describe("getPermissions", () => {
it("should do nothing", async () => {
await expect(authProvider.getPermissions()).resolves.toBeUndefined();
});
});
});

View File

@ -348,7 +348,7 @@ function getSearchOrder(order) {
}
const dataProvider = {
getList: async (resource, params) => {
getList: (resource, params) => {
console.log("getList " + resource);
const {
user_id,
@ -383,14 +383,13 @@ const dataProvider = {
const endpoint_url = homeserver + res.path;
const url = `${endpoint_url}?${stringify(query)}`;
const { json } = await jsonClient(url);
return {
return jsonClient(url).then(({ json }) => ({
data: json[res.data].map(res.map),
total: res.total(json, from, perPage),
};
}));
},
getOne: async (resource, params) => {
getOne: (resource, params) => {
console.log("getOne " + resource);
const homeserver = localStorage.getItem("base_url");
if (!homeserver || !(resource in resourceMap)) return Promise.reject();
@ -398,13 +397,14 @@ const dataProvider = {
const res = resourceMap[resource];
const endpoint_url = homeserver + res.path;
const { json } = await jsonClient(
`${endpoint_url}/${encodeURIComponent(params.id)}`
return jsonClient(`${endpoint_url}/${encodeURIComponent(params.id)}`).then(
({ json }) => ({
data: res.map(json),
})
);
return { data: res.map(json) };
},
getMany: async (resource, params) => {
getMany: (resource, params) => {
console.log("getMany " + resource);
const homeserver = localStorage.getItem("base_url");
if (!homeserver || !(resource in resourceMap)) return Promise.reject();
@ -412,18 +412,17 @@ const dataProvider = {
const res = resourceMap[resource];
const endpoint_url = homeserver + res.path;
const responses = await Promise.all(
return Promise.all(
params.ids.map(id =>
jsonClient(`${endpoint_url}/${encodeURIComponent(id)}`)
)
);
return {
).then(responses => ({
data: responses.map(({ json }) => res.map(json)),
total: responses.length,
};
}));
},
getManyReference: async (resource, params) => {
getManyReference: (resource, params) => {
console.log("getManyReference " + resource);
const { page, perPage } = params.pagination;
const { field, order } = params.sort;
@ -443,14 +442,13 @@ const dataProvider = {
const ref = res["reference"](params.id);
const endpoint_url = `${homeserver}${ref.endpoint}?${stringify(query)}`;
const { json } = await jsonClient(endpoint_url);
return {
return jsonClient(endpoint_url).then(({ headers, json }) => ({
data: json[res.data].map(res.map),
total: res.total(json, from, perPage),
};
}));
},
update: async (resource, params) => {
update: (resource, params) => {
console.log("update " + resource);
const homeserver = localStorage.getItem("base_url");
if (!homeserver || !(resource in resourceMap)) return Promise.reject();
@ -458,17 +456,15 @@ const dataProvider = {
const res = resourceMap[resource];
const endpoint_url = homeserver + res.path;
const { json } = await jsonClient(
`${endpoint_url}/${encodeURIComponent(params.id)}`,
{
return jsonClient(`${endpoint_url}/${encodeURIComponent(params.id)}`, {
method: "PUT",
body: JSON.stringify(params.data, filterNullValues),
}
);
return { data: res.map(json) };
}).then(({ json }) => ({
data: res.map(json),
}));
},
updateMany: async (resource, params) => {
updateMany: (resource, params) => {
console.log("updateMany " + resource);
const homeserver = localStorage.getItem("base_url");
if (!homeserver || !(resource in resourceMap)) return Promise.reject();
@ -476,7 +472,7 @@ const dataProvider = {
const res = resourceMap[resource];
const endpoint_url = homeserver + res.path;
const responses = await Promise.all(
return Promise.all(
params.ids.map(
id => jsonClient(`${endpoint_url}/${encodeURIComponent(id)}`),
{
@ -484,11 +480,12 @@ const dataProvider = {
body: JSON.stringify(params.data, filterNullValues),
}
)
);
return { data: responses.map(({ json }) => json) };
).then(responses => ({
data: responses.map(({ json }) => json),
}));
},
create: async (resource, params) => {
create: (resource, params) => {
console.log("create " + resource);
const homeserver = localStorage.getItem("base_url");
if (!homeserver || !(resource in resourceMap)) return Promise.reject();
@ -498,14 +495,15 @@ const dataProvider = {
const create = res["create"](params.data);
const endpoint_url = homeserver + create.endpoint;
const { json } = await jsonClient(endpoint_url, {
return jsonClient(endpoint_url, {
method: create.method,
body: JSON.stringify(create.body, filterNullValues),
});
return { data: res.map(json) };
}).then(({ json }) => ({
data: res.map(json),
}));
},
createMany: async (resource, params) => {
createMany: (resource, params) => {
console.log("createMany " + resource);
const homeserver = localStorage.getItem("base_url");
if (!homeserver || !(resource in resourceMap)) return Promise.reject();
@ -513,7 +511,7 @@ const dataProvider = {
const res = resourceMap[resource];
if (!("create" in res)) return Promise.reject();
const responses = await Promise.all(
return Promise.all(
params.ids.map(id => {
params.data.id = id;
const cre = res["create"](params.data);
@ -523,11 +521,12 @@ const dataProvider = {
body: JSON.stringify(cre.body, filterNullValues),
});
})
);
return { data: responses.map(({ json }) => json) };
).then(responses => ({
data: responses.map(({ json }) => json),
}));
},
delete: async (resource, params) => {
delete: (resource, params) => {
console.log("delete " + resource);
const homeserver = localStorage.getItem("base_url");
if (!homeserver || !(resource in resourceMap)) return Promise.reject();
@ -537,22 +536,24 @@ const dataProvider = {
if ("delete" in res) {
const del = res["delete"](params);
const endpoint_url = homeserver + del.endpoint;
const { json } = await jsonClient(endpoint_url, {
return jsonClient(endpoint_url, {
method: "method" in del ? del.method : "DELETE",
body: "body" in del ? JSON.stringify(del.body) : null,
});
return { data: json };
}).then(({ json }) => ({
data: json,
}));
} else {
const endpoint_url = homeserver + res.path;
const { json } = await jsonClient(`${endpoint_url}/${params.id}`, {
return jsonClient(`${endpoint_url}/${params.id}`, {
method: "DELETE",
body: JSON.stringify(params.previousData, filterNullValues),
});
return { data: json };
}).then(({ json }) => ({
data: json,
}));
}
},
deleteMany: async (resource, params) => {
deleteMany: (resource, params) => {
console.log("deleteMany " + resource);
const homeserver = localStorage.getItem("base_url");
if (!homeserver || !(resource in resourceMap)) return Promise.reject();
@ -560,7 +561,7 @@ const dataProvider = {
const res = resourceMap[resource];
if ("delete" in res) {
const responses = await Promise.all(
return Promise.all(
params.ids.map(id => {
const del = res["delete"]({ ...params, id: id });
const endpoint_url = homeserver + del.endpoint;
@ -569,21 +570,21 @@ const dataProvider = {
body: "body" in del ? JSON.stringify(del.body) : null,
});
})
);
return {
).then(responses => ({
data: responses.map(({ json }) => json),
};
}));
} else {
const endpoint_url = homeserver + res.path;
const responses = await Promise.all(
return Promise.all(
params.ids.map(id =>
jsonClient(`${endpoint_url}/${id}`, {
method: "DELETE",
body: JSON.stringify(params.data, filterNullValues),
})
)
);
return { data: responses.map(({ json }) => json) };
).then(responses => ({
data: responses.map(({ json }) => json),
}));
}
},
};

View File

@ -36,13 +36,6 @@ export const getServerVersion = async baseUrl => {
return response.json.server_version;
};
/** Get supported Matrix features */
export const getSupportedFeatures = async baseUrl => {
const versionUrl = `${baseUrl}/_matrix/client/versions`;
const response = await fetchUtils.fetchJson(versionUrl, { method: "GET" });
return response.json;
};
/**
* Get supported login flows
* @param baseUrl the base URL of the homeserver

6
vite.config.js Normal file
View File

@ -0,0 +1,6 @@
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
export default defineConfig({
plugins: [react()],
});

6891
yarn.lock

File diff suppressed because it is too large Load Diff