Update eslint for typescript

Change-Id: I39ad44666fe958dd4f6c8f0d88b3dc960d7cb6c7
This commit is contained in:
Manuel Stahl 2024-04-22 15:36:13 +02:00
parent 72f5ab937e
commit 4761ea36bc
39 changed files with 781 additions and 2795 deletions

13
.editorconfig Normal file
View file

@ -0,0 +1,13 @@
# EditorConfig https://EditorConfig.org
# top-most EditorConfig file
root = true
[*]
charset = utf-8
end_of_line = lf
indent_size = 2
indent_style = space
insert_final_newline = true
max_line_length = 120
trim_trailing_whitespace = true

View file

@ -17,5 +17,7 @@ jobs:
node-version: "18" node-version: "18"
- name: Install dependencies - name: Install dependencies
run: yarn --immutable run: yarn --immutable
- name: Run checks
run: yarn lint
- name: Run tests - name: Run tests
run: yarn test run: yarn test

View file

@ -1 +1,2 @@
.vscode
.yarn .yarn

View file

@ -1,11 +0,0 @@
{
"printWidth": 80,
"tabWidth": 2,
"useTabs": false,
"semi": true,
"singleQuote": false,
"trailingComma": "es5",
"bracketSpacing": true,
"bracketSameLine": false,
"arrowParens": "avoid"
}

View file

@ -104,10 +104,7 @@ or to a list of homeservers:
```json ```json
{ {
"restrictBaseUrl": [ "restrictBaseUrl": ["https://your-first-matrix-server.example.com", "https://your-second-matrix-server.example.com"]
"https://your-first-matrix-server.example.com",
"https://your-second-matrix-server.example.com"
]
} }
``` ```
@ -166,5 +163,6 @@ services:
## Development ## Development
- See https://yarnpkg.com/getting-started/editor-sdks how to setup your IDE - See https://yarnpkg.com/getting-started/editor-sdks how to setup your IDE
- Use `yarn test` to run all style, lint and unit tests - Use `yarn lint` to run all style and linter checks
- Use `yarn test` to run all unit tests
- Use `yarn fix` to fix the coding style - Use `yarn fix` to fix the coding style

View file

@ -12,6 +12,7 @@
}, },
"packageManager": "yarn@4.1.1", "packageManager": "yarn@4.1.1",
"devDependencies": { "devDependencies": {
"@eslint/js": "^9.1.1",
"@testing-library/dom": "^10.0.0", "@testing-library/dom": "^10.0.0",
"@testing-library/jest-dom": "^6.0.0", "@testing-library/jest-dom": "^6.0.0",
"@testing-library/react": "^15.0.2", "@testing-library/react": "^15.0.2",
@ -21,11 +22,16 @@
"@types/node": "^20.12.7", "@types/node": "^20.12.7",
"@types/papaparse": "^5.3.14", "@types/papaparse": "^5.3.14",
"@types/react": "^18.2.79", "@types/react": "^18.2.79",
"@typescript-eslint/eslint-plugin": "^7.7.1",
"@typescript-eslint/parser": "^7.7.1",
"@vitejs/plugin-react": "^4.0.0", "@vitejs/plugin-react": "^4.0.0",
"eslint": "^8.57.0", "eslint": "^8.57.0",
"eslint-config-prettier": "^9.1.0", "eslint-config-prettier": "^9.1.0",
"eslint-config-react-app": "^7.0.1", "eslint-plugin-import": "^2.29.1",
"eslint-plugin-jsx-a11y": "^6.8.0",
"eslint-plugin-prettier": "^5.1.3", "eslint-plugin-prettier": "^5.1.3",
"eslint-plugin-unused-imports": "^3.1.0",
"eslint-plugin-yaml": "^0.5.0",
"jest": "^29.7.0", "jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0", "jest-environment-jsdom": "^29.7.0",
"jest-fetch-mock": "^3.0.3", "jest-fetch-mock": "^3.0.3",
@ -34,6 +40,7 @@
"ts-jest": "^29.1.2", "ts-jest": "^29.1.2",
"ts-node": "^10.9.2", "ts-node": "^10.9.2",
"typescript": "^5.4.5", "typescript": "^5.4.5",
"typescript-eslint": "^7.7.1",
"vite": "^5.0.0", "vite": "^5.0.0",
"vite-plugin-version-mark": "^0.0.13" "vite-plugin-version-mark": "^0.0.13"
}, },
@ -66,17 +73,79 @@
"scripts": { "scripts": {
"start": "vite serve", "start": "vite serve",
"build": "vite build", "build": "vite build",
"fix:other": "yarn prettier --write", "lint": "eslint --ignore-path .gitignore --ext .ts,.tsx,.yml,.yaml .",
"fix:code": "yarn test:lint --fix", "fix": "yarn lint --fix",
"fix": "yarn fix:code && yarn fix:other", "test": "yarn jest",
"prettier": "prettier \"**/*.{js,jsx,ts,tsx,json,md,scss,yaml,yml}\"", "test:watch": "yarn jest --watch"
"test:code": "jest",
"test:lint": "eslint --ignore-path .gitignore --ext .js,.jsx,.ts,.jsx .",
"test:style": "yarn prettier --check",
"test": "yarn test:style && yarn test:lint && yarn test:code"
}, },
"eslintConfig": { "eslintConfig": {
"extends": "react-app" "env": {
"browser": true
},
"plugins": [
"import",
"prettier",
"unused-imports",
"@typescript-eslint",
"yaml"
],
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"plugin:@typescript-eslint/stylistic",
"plugin:import/typescript",
"plugin:yaml/recommended"
],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"project": "./tsconfig.eslint.json"
},
"root": true,
"rules": {
"prettier/prettier": "error",
"import/no-extraneous-dependencies": [
"error",
{
"devDependencies": [
"**/vite.config.ts",
"**/jest.setup.ts",
"**/*.test.ts",
"**/*.test.tsx"
]
}
],
"import/order": [
"error",
{
"alphabetize": {
"order": "asc",
"caseInsensitive": false
},
"newlines-between": "always",
"groups": [
"external",
"builtin",
"internal",
[
"parent",
"sibling",
"index"
]
]
}
],
"unused-imports/no-unused-imports-ts": 2
}
},
"prettier": {
"printWidth": 120,
"tabWidth": 2,
"useTabs": false,
"semi": true,
"singleQuote": false,
"trailingComma": "es5",
"bracketSpacing": true,
"arrowParens": "avoid"
}, },
"browserslist": { "browserslist": {
"production": [ "production": [

View file

@ -1,4 +1,5 @@
import { render, screen } from "@testing-library/react"; import { render, screen } from "@testing-library/react";
import App from "./App"; import App from "./App";
describe("App", () => { describe("App", () => {

View file

@ -1,28 +1,25 @@
import {
Admin,
CustomRoutes,
Resource,
resolveBrowserLocale,
} from "react-admin";
import polyglotI18nProvider from "ra-i18n-polyglot";
import { merge } from "lodash"; import { merge } from "lodash";
import authProvider from "./synapse/authProvider"; import polyglotI18nProvider from "ra-i18n-polyglot";
import dataProvider from "./synapse/dataProvider";
import users from "./components/users"; import { Admin, CustomRoutes, Resource, resolveBrowserLocale } from "react-admin";
import rooms from "./components/rooms"; import { Route } from "react-router-dom";
import userMediaStats from "./components/statistics";
import reports from "./components/EventReports"; import reports from "./components/EventReports";
import { ImportFeature } from "./components/ImportFeature";
import LoginPage from "./components/LoginPage";
import registrationToken from "./components/RegistrationTokens";
import roomDirectory from "./components/RoomDirectory"; import roomDirectory from "./components/RoomDirectory";
import destinations from "./components/destinations"; import destinations from "./components/destinations";
import registrationToken from "./components/RegistrationTokens"; import rooms from "./components/rooms";
import LoginPage from "./components/LoginPage"; import userMediaStats from "./components/statistics";
import { ImportFeature } from "./components/ImportFeature"; import users from "./components/users";
import { Route } from "react-router-dom";
import germanMessages from "./i18n/de"; import germanMessages from "./i18n/de";
import englishMessages from "./i18n/en"; import englishMessages from "./i18n/en";
import frenchMessages from "./i18n/fr"; import frenchMessages from "./i18n/fr";
import chineseMessages from "./i18n/zh";
import italianMessages from "./i18n/it"; import italianMessages from "./i18n/it";
import chineseMessages from "./i18n/zh";
import authProvider from "./synapse/authProvider";
import dataProvider from "./synapse/dataProvider";
// TODO: Can we use lazy loading together with browser locale? // TODO: Can we use lazy loading together with browser locale?
const messages = { const messages = {
@ -33,8 +30,7 @@ const messages = {
zh: chineseMessages, zh: chineseMessages,
}; };
const i18nProvider = polyglotI18nProvider( const i18nProvider = polyglotI18nProvider(
locale => locale => (messages[locale] ? merge({}, messages.en, messages[locale]) : messages.en),
messages[locale] ? merge({}, messages.en, messages[locale]) : messages.en,
resolveBrowserLocale(), resolveBrowserLocale(),
[ [
{ locale: "en", name: "English" }, { locale: "en", name: "English" },

View file

@ -1,5 +1,6 @@
import { RecordContextProvider } from "react-admin";
import { render, screen } from "@testing-library/react"; import { render, screen } from "@testing-library/react";
import { RecordContextProvider } from "react-admin";
import AvatarField from "./AvatarField"; import AvatarField from "./AvatarField";
describe("AvatarField", () => { describe("AvatarField", () => {

View file

@ -1,4 +1,5 @@
import { get } from "lodash"; import { get } from "lodash";
import { Avatar } from "@mui/material"; import { Avatar } from "@mui/material";
import { useRecordContext } from "react-admin"; import { useRecordContext } from "react-admin";
@ -6,16 +7,7 @@ const AvatarField = ({ source, ...rest }) => {
const record = useRecordContext(rest); const record = useRecordContext(rest);
const src = get(record, source)?.toString(); const src = get(record, source)?.toString();
const { alt, classes, sizes, sx, variant } = rest; const { alt, classes, sizes, sx, variant } = rest;
return ( return <Avatar alt={alt} classes={classes} sizes={sizes} src={src} sx={sx} variant={variant} />;
<Avatar
alt={alt}
classes={classes}
sizes={sizes}
src={src}
sx={sx}
variant={variant}
/>
);
}; };
export default AvatarField; export default AvatarField;

View file

@ -1,3 +1,6 @@
import PageviewIcon from "@mui/icons-material/Pageview";
import ViewListIcon from "@mui/icons-material/ViewList";
import ReportIcon from "@mui/icons-material/Warning";
import { import {
Datagrid, Datagrid,
DateField, DateField,
@ -17,15 +20,11 @@ import {
useRecordContext, useRecordContext,
useTranslate, useTranslate,
} from "react-admin"; } from "react-admin";
import { MXCField } from "./media";
import PageviewIcon from "@mui/icons-material/Pageview";
import ReportIcon from "@mui/icons-material/Warning";
import ViewListIcon from "@mui/icons-material/ViewList";
import { date_format } from "./date";
const ReportPagination = () => ( import { DATE_FORMAT } from "./date";
<Pagination rowsPerPageOptions={[10, 25, 50, 100, 500, 1000]} /> import { MXCField } from "./media";
);
const ReportPagination = () => <Pagination rowsPerPageOptions={[10, 25, 50, 100, 500, 1000]} />;
export const ReportShow = (props: ShowProps) => { export const ReportShow = (props: ShowProps) => {
const translate = useTranslate(); const translate = useTranslate();
@ -38,43 +37,21 @@ export const ReportShow = (props: ShowProps) => {
})} })}
icon={<ViewListIcon />} icon={<ViewListIcon />}
> >
<DateField <DateField source="received_ts" showTime options={DATE_FORMAT} sortable={true} />
source="received_ts"
showTime
options={date_format}
sortable={true}
/>
<ReferenceField source="user_id" reference="users"> <ReferenceField source="user_id" reference="users">
<TextField source="id" /> <TextField source="id" />
</ReferenceField> </ReferenceField>
<NumberField source="score" /> <NumberField source="score" />
<TextField source="reason" /> <TextField source="reason" />
<TextField source="name" /> <TextField source="name" />
<TextField <TextField source="canonical_alias" label="resources.rooms.fields.canonical_alias" />
source="canonical_alias" <ReferenceField source="room_id" reference="rooms" link="show" label="resources.rooms.fields.room_id">
label="resources.rooms.fields.canonical_alias"
/>
<ReferenceField
source="room_id"
reference="rooms"
link="show"
label="resources.rooms.fields.room_id"
>
<TextField source="id" /> <TextField source="id" />
</ReferenceField> </ReferenceField>
</Tab> </Tab>
<Tab <Tab label="synapseadmin.reports.tabs.detail" icon={<PageviewIcon />} path="detail">
label="synapseadmin.reports.tabs.detail" <DateField source="event_json.origin_server_ts" showTime options={DATE_FORMAT} sortable={true} />
icon={<PageviewIcon />}
path="detail"
>
<DateField
source="event_json.origin_server_ts"
showTime
options={date_format}
sortable={true}
/>
<ReferenceField source="sender" reference="users"> <ReferenceField source="sender" reference="users">
<TextField source="id" /> <TextField source="id" />
</ReferenceField> </ReferenceField>
@ -89,10 +66,7 @@ export const ReportShow = (props: ShowProps) => {
<TextField source="event_json.content.format" /> <TextField source="event_json.content.format" />
<TextField source="event_json.content.formatted_body" /> <TextField source="event_json.content.formatted_body" />
<TextField source="event_json.content.algorithm" /> <TextField source="event_json.content.algorithm" />
<TextField <TextField source="event_json.content.device_id" label="resources.devices.fields.device_id" />
source="event_json.content.device_id"
label="resources.devices.fields.device_id"
/>
</Tab> </Tab>
</TabbedShowLayout> </TabbedShowLayout>
</Show> </Show>
@ -115,19 +89,10 @@ const ReportShowActions = () => {
}; };
export const ReportList = (props: ListProps) => ( export const ReportList = (props: ListProps) => (
<List <List {...props} pagination={<ReportPagination />} sort={{ field: "received_ts", order: "DESC" }}>
{...props}
pagination={<ReportPagination />}
sort={{ field: "received_ts", order: "DESC" }}
>
<Datagrid rowClick="show" bulkActionButtons={false}> <Datagrid rowClick="show" bulkActionButtons={false}>
<TextField source="id" sortable={false} /> <TextField source="id" sortable={false} />
<DateField <DateField source="received_ts" showTime options={DATE_FORMAT} sortable={true} />
source="received_ts"
showTime
options={date_format}
sortable={true}
/>
<TextField sortable={false} source="user_id" /> <TextField sortable={false} source="user_id" />
<TextField sortable={false} source="name" /> <TextField sortable={false} source="name" />
<TextField sortable={false} source="score" /> <TextField sortable={false} source="score" />

View file

@ -1,10 +1,6 @@
import { parse as parseCsv, unparse as unparseCsv, ParseResult } from "papaparse";
import { ChangeEvent, useState } from "react"; import { ChangeEvent, useState } from "react";
import { useDataProvider, useNotify, RaRecord, Title } from "react-admin";
import {
parse as parseCsv,
unparse as unparseCsv,
ParseResult,
} from "papaparse";
import { import {
Button, Button,
Card, Card,
@ -17,6 +13,8 @@ import {
NativeSelect, NativeSelect,
} from "@mui/material"; } from "@mui/material";
import { DataProvider, useTranslate } from "ra-core"; import { DataProvider, useTranslate } from "ra-core";
import { useDataProvider, useNotify, RaRecord, Title } from "react-admin";
import { generateRandomMxId, generateRandomPassword } from "../synapse/synapse"; import { generateRandomMxId, generateRandomPassword } from "../synapse/synapse";
const LOGGING = true; const LOGGING = true;
@ -121,21 +119,12 @@ const FilePicker = () => {
} }
}; };
const verifyCsv = ( const verifyCsv = ({ data, meta, errors }: ParseResult<ImportLine>, { setValues, setStats, setError }) => {
{ data, meta, errors }: ParseResult<ImportLine>,
{ setValues, setStats, setError }
) => {
/* First, verify the presence of required fields */ /* First, verify the presence of required fields */
const missingFields = expectedFields.filter(eF => const missingFields = expectedFields.filter(eF => meta.fields?.find(mF => eF === mF));
meta.fields?.find(mF => eF === mF)
);
if (missingFields.length > 0) { if (missingFields.length > 0) {
setError( setError(translate("import_users.error.required_field", { field: missingFields[0] }));
translate("import_users.error.required_field", {
field: missingFields[0],
})
);
return false; return false;
} }
@ -157,7 +146,7 @@ const FilePicker = () => {
total: data.length, total: data.length,
}; };
var errorMessages = errors.map(e => e.message); const errorMessages = errors.map(e => e.message);
data.forEach((line, idx) => { data.forEach((line, idx) => {
if (line.user_type === undefined || line.user_type === "") { if (line.user_type === undefined || line.user_type === "") {
stats.user_types.default++; stats.user_types.default++;
@ -305,10 +294,7 @@ const FilePicker = () => {
* We do a simple retry loop so that an accidental hit on an existing ID * We do a simple retry loop so that an accidental hit on an existing ID
* doesn't trip us up. * doesn't trip us up.
*/ */
if (LOGGING) if (LOGGING) console.log("will check for existence of record " + JSON.stringify(userRecord));
console.log(
"will check for existence of record " + JSON.stringify(userRecord)
);
let retries = 0; let retries = 0;
const submitRecord = (recordData: ImportLine) => { const submitRecord = (recordData: ImportLine) => {
return dataProvider.getOne("users", { id: recordData.id }).then( return dataProvider.getOne("users", { id: recordData.id }).then(
@ -337,14 +323,7 @@ const FilePicker = () => {
} }
}, },
async () => { async () => {
if (LOGGING) if (LOGGING) console.log("OK to create record " + recordData.id + " (" + recordData.displayname + ").");
console.log(
"OK to create record " +
recordData.id +
" (" +
recordData.displayname +
")."
);
if (!dryRun) { if (!dryRun) {
await dataProvider.create("users", { data: recordData }); await dataProvider.create("users", { data: recordData });
@ -429,28 +408,11 @@ const FilePicker = () => {
const statsCards = stats && const statsCards = stats &&
!importResults && [ !importResults && [
<Container> <Container>
<CardHeader <CardHeader title={translate("import_users.cards.importstats.header")} />
title={translate("import_users.cards.importstats.header")}
/>
<CardContent> <CardContent>
<div> <div>{translate("import_users.cards.importstats.users_total", stats.total)}</div>
{translate( <div>{translate("import_users.cards.importstats.guest_count", stats.is_guest)}</div>
"import_users.cards.importstats.users_total", <div>{translate("import_users.cards.importstats.admin_count", stats.admin)}</div>
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> </CardContent>
</Container>, </Container>,
<Container> <Container>
@ -463,19 +425,9 @@ const FilePicker = () => {
</div> </div>
{stats.id > 0 ? ( {stats.id > 0 ? (
<div> <div>
<NativeSelect <NativeSelect onChange={onUseridModeChanged} value={useridMode} disabled={progress !== null}>
onChange={onUseridModeChanged} <TranslatableOption value="ignore" text="import_users.cards.ids.mode.ignore" />
value={useridMode} <TranslatableOption value="update" text="import_users.cards.ids.mode.update" />
disabled={progress !== null}
>
<TranslatableOption
value="ignore"
text="import_users.cards.ids.mode.ignore"
/>
<TranslatableOption
value="update"
text="import_users.cards.ids.mode.update"
/>
</NativeSelect> </NativeSelect>
</div> </div>
) : ( ) : (
@ -489,20 +441,13 @@ const FilePicker = () => {
<div> <div>
{stats.password === stats.total {stats.password === stats.total
? translate("import_users.cards.passwords.all_passwords_present") ? translate("import_users.cards.passwords.all_passwords_present")
: translate( : translate("import_users.cards.passwords.count_passwords_present", stats.password)}
"import_users.cards.passwords.count_passwords_present",
stats.password
)}
</div> </div>
{stats.password > 0 ? ( {stats.password > 0 ? (
<div> <div>
<FormControlLabel <FormControlLabel
control={ control={
<Checkbox <Checkbox checked={passwordMode} disabled={progress !== null} onChange={onPasswordModeChange} />
checked={passwordMode}
disabled={progress !== null}
onChange={onPasswordModeChange}
/>
} }
label={translate("import_users.cards.passwords.use_passwords")} label={translate("import_users.cards.passwords.use_passwords")}
/> />
@ -519,19 +464,9 @@ const FilePicker = () => {
<CardHeader title={translate("import_users.cards.conflicts.header")} /> <CardHeader title={translate("import_users.cards.conflicts.header")} />
<CardContent> <CardContent>
<div> <div>
<NativeSelect <NativeSelect onChange={onConflictModeChanged} value={conflictMode} disabled={progress !== null}>
onChange={onConflictModeChanged} <TranslatableOption value="stop" text="import_users.cards.conflicts.mode.stop" />
value={conflictMode} <TranslatableOption value="skip" text="import_users.cards.conflicts.mode.skip" />
disabled={progress !== null}
>
<TranslatableOption
value="stop"
text="import_users.cards.conflicts.mode.stop"
/>
<TranslatableOption
value="skip"
text="import_users.cards.conflicts.mode.skip"
/>
</NativeSelect> </NativeSelect>
</div> </div>
</CardContent> </CardContent>
@ -557,11 +492,7 @@ const FilePicker = () => {
<a href="./data/example.csv">example.csv</a> <a href="./data/example.csv">example.csv</a>
<br /> <br />
<br /> <br />
<input <input type="file" onChange={onFileChange} disabled={progress !== null} />
type="file"
onChange={onFileChange}
disabled={progress !== null}
/>
</CardContent> </CardContent>
</Container> </Container>
); );
@ -570,22 +501,13 @@ const FilePicker = () => {
<CardContent> <CardContent>
<CardHeader title={translate("import_users.cards.results.header")} /> <CardHeader title={translate("import_users.cards.results.header")} />
<div> <div>
{translate( {translate("import_users.cards.results.total", importResults.totalRecordCount)}
"import_users.cards.results.total",
importResults.totalRecordCount
)}
<br /> <br />
{translate( {translate("import_users.cards.results.successful", importResults.succeededRecords.length)}
"import_users.cards.results.successful",
importResults.succeededRecords.length
)}
<br /> <br />
{importResults.skippedRecords.length {importResults.skippedRecords.length
? [ ? [
translate( translate("import_users.cards.results.skipped", importResults.skippedRecords.length),
"import_users.cards.results.skipped",
importResults.skippedRecords.length
),
<div> <div>
<button onClick={downloadSkippedRecords}> <button onClick={downloadSkippedRecords}>
{translate("import_users.cards.results.download_skipped")} {translate("import_users.cards.results.download_skipped")}
@ -595,19 +517,10 @@ const FilePicker = () => {
] ]
: ""} : ""}
{importResults.erroredRecords.length {importResults.erroredRecords.length
? [ ? [translate("import_users.cards.results.skipped", importResults.erroredRecords.length), <br />]
translate(
"import_users.cards.results.skipped",
importResults.erroredRecords.length
),
<br />,
]
: ""} : ""}
<br /> <br />
{importResults.wasDryRun && [ {importResults.wasDryRun && [translate("import_users.cards.results.simulated_only"), <br />]}
translate("import_users.cards.results.simulated_only"),
<br />,
]}
</div> </div>
</CardContent> </CardContent>
); );
@ -616,13 +529,7 @@ const FilePicker = () => {
!values || values.length === 0 || importResults ? undefined : ( !values || values.length === 0 || importResults ? undefined : (
<CardActions> <CardActions>
<FormControlLabel <FormControlLabel
control={ control={<Checkbox checked={dryRun} onChange={onDryRunModeChanged} disabled={progress !== null} />}
<Checkbox
checked={dryRun}
onChange={onDryRunModeChanged}
disabled={progress !== null}
/>
}
label={translate("import_users.cards.startImport.simulate_only")} label={translate("import_users.cards.startImport.simulate_only")}
/> />
<Button size="large" onClick={runImport} disabled={progress !== null}> <Button size="large" onClick={runImport} disabled={progress !== null}>
@ -646,10 +553,7 @@ const FilePicker = () => {
const cardContainer = <Card>{allCards}</Card>; const cardContainer = <Card>{allCards}</Card>;
return [ return [<Title defaultTitle={translate("import_users.title")} />, cardContainer];
<Title defaultTitle={translate("import_users.title")} />,
cardContainer,
];
}; };
export const ImportFeature = FilePicker; export const ImportFeature = FilePicker;

View file

@ -1,13 +1,13 @@
import polyglotI18nProvider from "ra-i18n-polyglot";
import { render, screen } from "@testing-library/react"; import { render, screen } from "@testing-library/react";
import { AdminContext } from "react-admin"; import { AdminContext } from "react-admin";
import polyglotI18nProvider from "ra-i18n-polyglot";
import LoginPage from "./LoginPage"; import LoginPage from "./LoginPage";
import { AppContext } from "../AppContext"; import { AppContext } from "../AppContext";
import englishMessages from "../i18n/en"; import englishMessages from "../i18n/en";
const i18nProvider = polyglotI18nProvider(() => englishMessages, "en", [ const i18nProvider = polyglotI18nProvider(() => englishMessages, "en", [{ locale: "en", name: "English" }]);
{ locale: "en", name: "English" },
]);
describe("LoginForm", () => { describe("LoginForm", () => {
it("renders with no restriction to homeserver", () => { it("renders with no restriction to homeserver", () => {
@ -30,9 +30,7 @@ describe("LoginForm", () => {
it("renders with single restricted homeserver", () => { it("renders with single restricted homeserver", () => {
render( render(
<AppContext.Provider <AppContext.Provider value={{ restrictBaseUrl: "https://matrix.example.com" }}>
value={{ restrictBaseUrl: "https://matrix.example.com" }}
>
<AdminContext i18nProvider={i18nProvider}> <AdminContext i18nProvider={i18nProvider}>
<LoginPage /> <LoginPage />
</AdminContext> </AdminContext>
@ -54,10 +52,7 @@ describe("LoginForm", () => {
render( render(
<AppContext.Provider <AppContext.Provider
value={{ value={{
restrictBaseUrl: [ restrictBaseUrl: ["https://matrix.example.com", "https://matrix.example.org"],
"https://matrix.example.com",
"https://matrix.example.org",
],
}} }}
> >
<AdminContext i18nProvider={i18nProvider}> <AdminContext i18nProvider={i18nProvider}>

View file

@ -1,4 +1,8 @@
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import LockIcon from "@mui/icons-material/Lock";
import { Avatar, Box, Button, Card, CardActions, CircularProgress, MenuItem, Select, Typography } from "@mui/material";
import { styled } from "@mui/material/styles";
import { import {
Form, Form,
FormDataConsumer, FormDataConsumer,
@ -13,19 +17,6 @@ import {
useLocales, useLocales,
} from "react-admin"; } from "react-admin";
import { useFormContext } from "react-hook-form"; import { useFormContext } from "react-hook-form";
import {
Avatar,
Box,
Button,
Card,
CardActions,
CircularProgress,
MenuItem,
Select,
Typography,
} from "@mui/material";
import { styled } from "@mui/material/styles";
import LockIcon from "@mui/icons-material/Lock";
import { useAppContext } from "../AppContext"; import { useAppContext } from "../AppContext";
import { import {
@ -103,9 +94,7 @@ const LoginPage = () => {
const [locale, setLocale] = useLocaleState(); const [locale, setLocale] = useLocaleState();
const locales = useLocales(); const locales = useLocales();
const translate = useTranslate(); const translate = useTranslate();
const base_url = allowSingleBaseUrl const base_url = allowSingleBaseUrl ? restrictBaseUrl : localStorage.getItem("base_url");
? restrictBaseUrl
: localStorage.getItem("base_url");
const [ssoBaseUrl, setSSOBaseUrl] = useState(""); const [ssoBaseUrl, setSSOBaseUrl] = useState("");
const loginToken = /\?loginToken=([a-zA-Z0-9_-]+)/.exec(window.location.href); const loginToken = /\?loginToken=([a-zA-Z0-9_-]+)/.exec(window.location.href);
@ -113,11 +102,7 @@ const LoginPage = () => {
const ssoToken = loginToken[1]; const ssoToken = loginToken[1];
console.log("SSO token is", ssoToken); console.log("SSO token is", ssoToken);
// Prevent further requests // Prevent further requests
window.history.replaceState( window.history.replaceState({}, "", window.location.href.replace(loginToken[0], "#").split("#")[0]);
{},
"",
window.location.href.replace(loginToken[0], "#").split("#")[0]
);
const baseUrl = localStorage.getItem("sso_base_url"); const baseUrl = localStorage.getItem("sso_base_url");
localStorage.removeItem("sso_base_url"); localStorage.removeItem("sso_base_url");
if (baseUrl) { if (baseUrl) {
@ -146,9 +131,7 @@ const LoginPage = () => {
const validateBaseUrl = value => { const validateBaseUrl = value => {
if (!value.match(/^(http|https):\/\//)) { if (!value.match(/^(http|https):\/\//)) {
return translate("synapseadmin.auth.protocol_error"); return translate("synapseadmin.auth.protocol_error");
} else if ( } else if (!value.match(/^(http|https):\/\/[a-zA-Z0-9\-.]+(:\d{1,5})?[^?&\s]*$/)) {
!value.match(/^(http|https):\/\/[a-zA-Z0-9\-.]+(:\d{1,5})?[^?&\s]*$/)
) {
return translate("synapseadmin.auth.url_error"); return translate("synapseadmin.auth.url_error");
} else { } else {
return undefined; return undefined;
@ -189,10 +172,7 @@ const LoginPage = () => {
const domain = splitMxid(formData.username)?.domain; const domain = splitMxid(formData.username)?.domain;
if (domain) { if (domain) {
getWellKnownUrl(domain).then(url => { getWellKnownUrl(domain).then(url => {
if ( if (allowAnyBaseUrl || (allowMultipleBaseUrls && restrictBaseUrl.includes(url)))
allowAnyBaseUrl ||
(allowMultipleBaseUrls && restrictBaseUrl.includes(url))
)
form.setValue("base_url", url); form.setValue("base_url", url);
}); });
} }
@ -205,28 +185,20 @@ const LoginPage = () => {
if (!isValidBaseUrl(formData.base_url)) return; if (!isValidBaseUrl(formData.base_url)) return;
getServerVersion(formData.base_url) getServerVersion(formData.base_url)
.then(serverVersion => .then(serverVersion => setServerVersion(`${translate("synapseadmin.auth.server_version")} ${serverVersion}`))
setServerVersion(
`${translate("synapseadmin.auth.server_version")} ${serverVersion}`
)
)
.catch(() => setServerVersion("")); .catch(() => setServerVersion(""));
getSupportedFeatures(formData.base_url) getSupportedFeatures(formData.base_url)
.then(features => .then(features =>
setMatrixVersions( setMatrixVersions(`${translate("synapseadmin.auth.supports_specs")} ${features.versions.join(", ")}`)
`${translate("synapseadmin.auth.supports_specs")} ${features.versions.join(", ")}`
)
) )
.catch(() => setMatrixVersions("")); .catch(() => setMatrixVersions(""));
// Set SSO Url // Set SSO Url
getSupportedLoginFlows(formData.base_url) getSupportedLoginFlows(formData.base_url)
.then(loginFlows => { .then(loginFlows => {
const supportPass = const supportPass = loginFlows.find(f => f.type === "m.login.password") !== undefined;
loginFlows.find(f => f.type === "m.login.password") !== undefined; const supportSSO = loginFlows.find(f => f.type === "m.login.sso") !== undefined;
const supportSSO =
loginFlows.find(f => f.type === "m.login.sso") !== undefined;
setSupportPassAuth(supportPass); setSupportPassAuth(supportPass);
setSSOBaseUrl(supportSSO ? formData.base_url : ""); setSSOBaseUrl(supportSSO ? formData.base_url : "");
}) })
@ -287,11 +259,7 @@ const LoginPage = () => {
}; };
return ( return (
<Form <Form defaultValues={{ base_url: base_url }} onSubmit={handleSubmit} mode="onTouched">
defaultValues={{ base_url: base_url }}
onSubmit={handleSubmit}
mode="onTouched"
>
<FormBox> <FormBox>
<Card className="card"> <Card className="card">
<Box className="avatar"> <Box className="avatar">
@ -318,9 +286,7 @@ const LoginPage = () => {
</MenuItem> </MenuItem>
))} ))}
</Select> </Select>
<FormDataConsumer> <FormDataConsumer>{formDataProps => <UserData {...formDataProps} />}</FormDataConsumer>
{formDataProps => <UserData {...formDataProps} />}
</FormDataConsumer>
<CardActions className="actions"> <CardActions className="actions">
<Button <Button
variant="contained" variant="contained"

View file

@ -1,3 +1,4 @@
import RegistrationTokenIcon from "@mui/icons-material/ConfirmationNumber";
import { import {
BooleanInput, BooleanInput,
Create, Create,
@ -21,8 +22,8 @@ import {
TextField, TextField,
Toolbar, Toolbar,
} from "react-admin"; } from "react-admin";
import RegistrationTokenIcon from "@mui/icons-material/ConfirmationNumber";
import { date_format, dateFormatter, dateParser } from "./date"; import { DATE_FORMAT, dateFormatter, dateParser } from "./date";
const validateToken = [regex(/^[A-Za-z0-9._~-]{0,64}$/)]; const validateToken = [regex(/^[A-Za-z0-9._~-]{0,64}$/)];
const validateUsesAllowed = [number()]; const validateUsesAllowed = [number()];
@ -43,12 +44,7 @@ export const RegistrationTokenList = (props: ListProps) => (
<NumberField source="uses_allowed" sortable={false} /> <NumberField source="uses_allowed" sortable={false} />
<NumberField source="pending" sortable={false} /> <NumberField source="pending" sortable={false} />
<NumberField source="completed" sortable={false} /> <NumberField source="completed" sortable={false} />
<DateField <DateField source="expiry_time" showTime options={DATE_FORMAT} sortable={false} />
source="expiry_time"
showTime
options={date_format}
sortable={false}
/>
</Datagrid> </Datagrid>
</List> </List>
); );
@ -63,23 +59,14 @@ export const RegistrationTokenCreate = (props: CreateProps) => (
</Toolbar> </Toolbar>
} }
> >
<TextInput <TextInput source="token" autoComplete="off" validate={validateToken} resettable />
source="token"
autoComplete="off"
validate={validateToken}
resettable
/>
<NumberInput <NumberInput
source="length" source="length"
validate={validateLength} validate={validateLength}
helperText="resources.registration_tokens.helper.length" helperText="resources.registration_tokens.helper.length"
step={1} step={1}
/> />
<NumberInput <NumberInput source="uses_allowed" validate={validateUsesAllowed} step={1} />
source="uses_allowed"
validate={validateUsesAllowed}
step={1}
/>
<DateTimeInput source="expiry_time" parse={dateParser} /> <DateTimeInput source="expiry_time" parse={dateParser} />
</SimpleForm> </SimpleForm>
</Create> </Create>
@ -91,16 +78,8 @@ export const RegistrationTokenEdit = (props: EditProps) => (
<TextInput source="token" disabled /> <TextInput source="token" disabled />
<NumberInput source="pending" disabled /> <NumberInput source="pending" disabled />
<NumberInput source="completed" disabled /> <NumberInput source="completed" disabled />
<NumberInput <NumberInput source="uses_allowed" validate={validateUsesAllowed} step={1} />
source="uses_allowed" <DateTimeInput source="expiry_time" parse={dateParser} format={dateFormatter} />
validate={validateUsesAllowed}
step={1}
/>
<DateTimeInput
source="expiry_time"
parse={dateParser}
format={dateFormatter}
/>
</SimpleForm> </SimpleForm>
</Edit> </Edit>
); );

View file

@ -1,3 +1,4 @@
import RoomDirectoryIcon from "@mui/icons-material/FolderShared";
import { import {
BooleanField, BooleanField,
BulkDeleteButton, BulkDeleteButton,
@ -25,12 +26,10 @@ import {
useUnselectAll, useUnselectAll,
} from "react-admin"; } from "react-admin";
import { useMutation } from "react-query"; import { useMutation } from "react-query";
import RoomDirectoryIcon from "@mui/icons-material/FolderShared";
import AvatarField from "./AvatarField"; import AvatarField from "./AvatarField";
const RoomDirectoryPagination = () => ( const RoomDirectoryPagination = () => <Pagination rowsPerPageOptions={[100, 500, 1000, 2000]} />;
<Pagination rowsPerPageOptions={[100, 500, 1000, 2000]} />
);
export const RoomDirectoryUnpublishButton = (props: DeleteButtonProps) => { export const RoomDirectoryUnpublishButton = (props: DeleteButtonProps) => {
const translate = useTranslate(); const translate = useTranslate();
@ -53,9 +52,7 @@ export const RoomDirectoryUnpublishButton = (props: DeleteButtonProps) => {
); );
}; };
export const RoomDirectoryBulkUnpublishButton = ( export const RoomDirectoryBulkUnpublishButton = (props: BulkDeleteButtonProps) => (
props: BulkDeleteButtonProps
) => (
<BulkDeleteButton <BulkDeleteButton
{...props} {...props}
label="resources.room_directory.action.erase" label="resources.room_directory.action.erase"
@ -93,12 +90,7 @@ export const RoomDirectoryBulkPublishButton = (props: ButtonProps) => {
); );
return ( return (
<Button <Button {...props} label="resources.room_directory.action.create" onClick={mutate} disabled={isLoading}>
{...props}
label="resources.room_directory.action.create"
onClick={mutate}
disabled={isLoading}
>
<RoomDirectoryIcon /> <RoomDirectoryIcon />
</Button> </Button>
); );
@ -128,12 +120,7 @@ export const RoomDirectoryPublishButton = (props: ButtonProps) => {
}; };
return ( return (
<Button <Button {...props} label="resources.room_directory.action.create" onClick={handleSend} disabled={isLoading}>
{...props}
label="resources.room_directory.action.create"
onClick={handleSend}
disabled={isLoading}
>
<RoomDirectoryIcon /> <RoomDirectoryIcon />
</Button> </Button>
); );
@ -147,11 +134,7 @@ const RoomDirectoryListActions = () => (
); );
export const RoomDirectoryList = () => ( export const RoomDirectoryList = () => (
<List <List pagination={<RoomDirectoryPagination />} perPage={100} actions={<RoomDirectoryListActions />}>
pagination={<RoomDirectoryPagination />}
perPage={100}
actions={<RoomDirectoryListActions />}
>
<DatagridConfigurable <DatagridConfigurable
rowClick={id => "/rooms/" + id + "/show"} rowClick={id => "/rooms/" + id + "/show"}
bulkActionButtons={<RoomDirectoryBulkUnpublishButton />} bulkActionButtons={<RoomDirectoryBulkUnpublishButton />}
@ -163,41 +146,13 @@ export const RoomDirectoryList = () => (
sx={{ height: "40px", width: "40px" }} sx={{ height: "40px", width: "40px" }}
label="resources.rooms.fields.avatar" label="resources.rooms.fields.avatar"
/> />
<TextField <TextField source="name" sortable={false} label="resources.rooms.fields.name" />
source="name" <TextField source="room_id" sortable={false} label="resources.rooms.fields.room_id" />
sortable={false} <TextField source="canonical_alias" sortable={false} label="resources.rooms.fields.canonical_alias" />
label="resources.rooms.fields.name" <TextField source="topic" sortable={false} label="resources.rooms.fields.topic" />
/> <NumberField source="num_joined_members" sortable={false} label="resources.rooms.fields.joined_members" />
<TextField <BooleanField source="world_readable" sortable={false} label="resources.room_directory.fields.world_readable" />
source="room_id" <BooleanField source="guest_can_join" sortable={false} label="resources.room_directory.fields.guest_can_join" />
sortable={false}
label="resources.rooms.fields.room_id"
/>
<TextField
source="canonical_alias"
sortable={false}
label="resources.rooms.fields.canonical_alias"
/>
<TextField
source="topic"
sortable={false}
label="resources.rooms.fields.topic"
/>
<NumberField
source="num_joined_members"
sortable={false}
label="resources.rooms.fields.joined_members"
/>
<BooleanField
source="world_readable"
sortable={false}
label="resources.room_directory.fields.world_readable"
/>
<BooleanField
source="guest_can_join"
sortable={false}
label="resources.room_directory.fields.guest_can_join"
/>
</DatagridConfigurable> </DatagridConfigurable>
</List> </List>
); );

View file

@ -1,4 +1,8 @@
import { useState } from "react"; import { useState } from "react";
import IconCancel from "@mui/icons-material/Cancel";
import MessageIcon from "@mui/icons-material/Message";
import { Dialog, DialogContent, DialogContentText, DialogTitle } from "@mui/material";
import { import {
Button, Button,
RaRecord, RaRecord,
@ -17,26 +21,13 @@ import {
useUnselectAll, useUnselectAll,
} from "react-admin"; } from "react-admin";
import { useMutation } from "react-query"; import { useMutation } from "react-query";
import MessageIcon from "@mui/icons-material/Message";
import IconCancel from "@mui/icons-material/Cancel";
import {
Dialog,
DialogContent,
DialogContentText,
DialogTitle,
} from "@mui/material";
const ServerNoticeDialog = ({ open, onClose, onSubmit }) => { const ServerNoticeDialog = ({ open, onClose, onSubmit }) => {
const translate = useTranslate(); const translate = useTranslate();
const ServerNoticeToolbar = ( const ServerNoticeToolbar = (props: ToolbarProps & { pristine?: boolean }) => (
props: ToolbarProps & { pristine?: boolean }
) => (
<Toolbar {...props}> <Toolbar {...props}>
<SaveButton <SaveButton label="resources.servernotices.action.send" disabled={props.pristine} />
label="resources.servernotices.action.send"
disabled={props.pristine}
/>
<Button label="ra.action.cancel" onClick={onClose}> <Button label="ra.action.cancel" onClick={onClose}>
<IconCancel /> <IconCancel />
</Button> </Button>
@ -45,13 +36,9 @@ const ServerNoticeDialog = ({ open, onClose, onSubmit }) => {
return ( return (
<Dialog open={open} onClose={onClose}> <Dialog open={open} onClose={onClose}>
<DialogTitle> <DialogTitle>{translate("resources.servernotices.action.send")}</DialogTitle>
{translate("resources.servernotices.action.send")}
</DialogTitle>
<DialogContent> <DialogContent>
<DialogContentText> <DialogContentText>{translate("resources.servernotices.helper.send")}</DialogContentText>
{translate("resources.servernotices.helper.send")}
</DialogContentText>
<SimpleForm toolbar={<ServerNoticeToolbar />} onSubmit={onSubmit}> <SimpleForm toolbar={<ServerNoticeToolbar />} onSubmit={onSubmit}>
<TextInput <TextInput
source="body" source="body"
@ -96,18 +83,10 @@ export const ServerNoticeButton = () => {
return ( return (
<> <>
<Button <Button label="resources.servernotices.send" onClick={handleDialogOpen} disabled={isLoading}>
label="resources.servernotices.send"
onClick={handleDialogOpen}
disabled={isLoading}
>
<MessageIcon /> <MessageIcon />
</Button> </Button>
<ServerNoticeDialog <ServerNoticeDialog open={open} onClose={handleDialogClose} onSubmit={handleSend} />
open={open}
onClose={handleDialogClose}
onSubmit={handleSend}
/>
</> </>
); );
}; };
@ -142,18 +121,10 @@ export const ServerNoticeBulkButton = () => {
return ( return (
<> <>
<Button <Button label="resources.servernotices.send" onClick={openDialog} disabled={isLoading}>
label="resources.servernotices.send"
onClick={openDialog}
disabled={isLoading}
>
<MessageIcon /> <MessageIcon />
</Button> </Button>
<ServerNoticeDialog <ServerNoticeDialog open={open} onClose={closeDialog} onSubmit={sendNotices} />
open={open}
onClose={closeDialog}
onSubmit={sendNotices}
/>
</> </>
); );
}; };

View file

@ -1,4 +1,4 @@
export const date_format: Intl.DateTimeFormatOptions = { export const DATE_FORMAT: Intl.DateTimeFormatOptions = {
year: "numeric", year: "numeric",
month: "2-digit", month: "2-digit",
day: "2-digit", day: "2-digit",
@ -12,9 +12,7 @@ export const dateParser = (v: string | number | Date): number => {
return d.getTime(); return d.getTime();
}; };
export const dateFormatter = ( export const dateFormatter = (v: string | number | Date | undefined | null): string => {
v: string | number | Date | undefined | null
): string => {
if (v === undefined || v === null) return ""; if (v === undefined || v === null) return "";
const d = new Date(v); const d = new Date(v);

View file

@ -29,11 +29,9 @@ import {
useTranslate, useTranslate,
} from "react-admin"; } from "react-admin";
import { date_format } from "./date"; import { DATE_FORMAT } from "./date";
const DestinationPagination = () => ( const DestinationPagination = () => <Pagination rowsPerPageOptions={[10, 25, 50, 100, 500, 1000]} />;
<Pagination rowsPerPageOptions={[10, 25, 50, 100, 500, 1000]} />
);
const destinationRowSx = (record: RaRecord) => ({ const destinationRowSx = (record: RaRecord) => ({
backgroundColor: record.retry_last_ts > 0 ? "#ffcccc" : "white", backgroundColor: record.retry_last_ts > 0 ? "#ffcccc" : "white",
@ -72,11 +70,7 @@ export const DestinationReconnectButton = () => {
}; };
return ( return (
<Button <Button label="resources.destinations.action.reconnect" onClick={handleClick} disabled={isLoading}>
label="resources.destinations.action.reconnect"
onClick={handleClick}
disabled={isLoading}
>
<AutorenewIcon /> <AutorenewIcon />
</Button> </Button>
); );
@ -106,14 +100,10 @@ export const DestinationList = (props: ListProps) => {
pagination={<DestinationPagination />} pagination={<DestinationPagination />}
sort={{ field: "destination", order: "ASC" }} sort={{ field: "destination", order: "ASC" }}
> >
<Datagrid <Datagrid rowSx={destinationRowSx} rowClick={id => `${id}/show/rooms`} bulkActionButtons={false}>
rowSx={destinationRowSx}
rowClick={id => `${id}/show/rooms`}
bulkActionButtons={false}
>
<TextField source="destination" /> <TextField source="destination" />
<DateField source="failure_ts" showTime options={date_format} /> <DateField source="failure_ts" showTime options={DATE_FORMAT} />
<DateField source="retry_last_ts" showTime options={date_format} /> <DateField source="retry_last_ts" showTime options={DATE_FORMAT} />
<TextField source="retry_interval" /> <TextField source="retry_interval" />
<TextField source="last_successful_stream_ordering" /> <TextField source="last_successful_stream_ordering" />
<DestinationReconnectButton /> <DestinationReconnectButton />
@ -125,25 +115,17 @@ export const DestinationList = (props: ListProps) => {
export const DestinationShow = (props: ShowProps) => { export const DestinationShow = (props: ShowProps) => {
const translate = useTranslate(); const translate = useTranslate();
return ( return (
<Show <Show actions={<DestinationShowActions />} title={<DestinationTitle />} {...props}>
actions={<DestinationShowActions />}
title={<DestinationTitle />}
{...props}
>
<TabbedShowLayout> <TabbedShowLayout>
<Tab label="status" icon={<ViewListIcon />}> <Tab label="status" icon={<ViewListIcon />}>
<TextField source="destination" /> <TextField source="destination" />
<DateField source="failure_ts" showTime options={date_format} /> <DateField source="failure_ts" showTime options={DATE_FORMAT} />
<DateField source="retry_last_ts" showTime options={date_format} /> <DateField source="retry_last_ts" showTime options={DATE_FORMAT} />
<TextField source="retry_interval" /> <TextField source="retry_interval" />
<TextField source="last_successful_stream_ordering" /> <TextField source="last_successful_stream_ordering" />
</Tab> </Tab>
<Tab <Tab label={translate("resources.rooms.name", { smart_count: 2 })} icon={<FolderSharedIcon />} path="rooms">
label={translate("resources.rooms.name", { smart_count: 2 })}
icon={<FolderSharedIcon />}
path="rooms"
>
<ReferenceManyField <ReferenceManyField
reference="destination_rooms" reference="destination_rooms"
target="destination" target="destination"
@ -151,14 +133,8 @@ export const DestinationShow = (props: ShowProps) => {
pagination={<DestinationPagination />} pagination={<DestinationPagination />}
perPage={50} perPage={50}
> >
<Datagrid <Datagrid style={{ width: "100%" }} rowClick={id => `/rooms/${id}/show`}>
style={{ width: "100%" }} <TextField source="room_id" label="resources.rooms.fields.room_id" />
rowClick={id => `/rooms/${id}/show`}
>
<TextField
source="room_id"
label="resources.rooms.fields.room_id"
/>
<TextField source="stream_ordering" sortable={false} /> <TextField source="stream_ordering" sortable={false} />
<ReferenceField <ReferenceField
label="resources.rooms.fields.name" label="resources.rooms.fields.name"

View file

@ -1,8 +1,4 @@
import { import { DeleteWithConfirmButton, DeleteWithConfirmButtonProps, useRecordContext } from "react-admin";
DeleteWithConfirmButton,
DeleteWithConfirmButtonProps,
useRecordContext,
} from "react-admin";
export const DeviceRemoveButton = (props: DeleteWithConfirmButtonProps) => { export const DeviceRemoveButton = (props: DeleteWithConfirmButtonProps) => {
const record = useRecordContext(); const record = useRecordContext();

View file

@ -1,5 +1,15 @@
import { useState } from "react";
import { get } from "lodash"; import { get } from "lodash";
import { useState } from "react";
import BlockIcon from "@mui/icons-material/Block";
import IconCancel from "@mui/icons-material/Cancel";
import ClearIcon from "@mui/icons-material/Clear";
import DeleteSweepIcon from "@mui/icons-material/DeleteSweep";
import FileOpenIcon from "@mui/icons-material/FileOpen";
import LockIcon from "@mui/icons-material/Lock";
import LockOpenIcon from "@mui/icons-material/LockOpen";
import { Box, Dialog, DialogContent, DialogContentText, DialogTitle, Tooltip } from "@mui/material";
import { alpha, useTheme } from "@mui/material/styles";
import { import {
BooleanInput, BooleanInput,
Button, Button,
@ -18,22 +28,7 @@ import {
useTranslate, useTranslate,
} from "react-admin"; } from "react-admin";
import { Link } from "react-router-dom"; import { Link } from "react-router-dom";
import BlockIcon from "@mui/icons-material/Block";
import ClearIcon from "@mui/icons-material/Clear";
import DeleteSweepIcon from "@mui/icons-material/DeleteSweep";
import {
Box,
Dialog,
DialogContent,
DialogContentText,
DialogTitle,
Tooltip,
} from "@mui/material";
import IconCancel from "@mui/icons-material/Cancel";
import LockIcon from "@mui/icons-material/Lock";
import LockOpenIcon from "@mui/icons-material/LockOpen";
import FileOpenIcon from "@mui/icons-material/FileOpen";
import { alpha, useTheme } from "@mui/material/styles";
import { dateParser } from "./date"; import { dateParser } from "./date";
import { getMediaUrl } from "../synapse/synapse"; import { getMediaUrl } from "../synapse/synapse";
@ -42,10 +37,7 @@ const DeleteMediaDialog = ({ open, onClose, onSubmit }) => {
const DeleteMediaToolbar = (props: ToolbarProps) => ( const DeleteMediaToolbar = (props: ToolbarProps) => (
<Toolbar {...props}> <Toolbar {...props}>
<SaveButton <SaveButton label="resources.delete_media.action.send" icon={<DeleteSweepIcon />} />
label="resources.delete_media.action.send"
icon={<DeleteSweepIcon />}
/>
<Button label="ra.action.cancel" onClick={onClose}> <Button label="ra.action.cancel" onClick={onClose}>
<IconCancel /> <IconCancel />
</Button> </Button>
@ -54,13 +46,9 @@ const DeleteMediaDialog = ({ open, onClose, onSubmit }) => {
return ( return (
<Dialog open={open} onClose={onClose}> <Dialog open={open} onClose={onClose}>
<DialogTitle> <DialogTitle>{translate("resources.delete_media.action.send")}</DialogTitle>
{translate("resources.delete_media.action.send")}
</DialogTitle>
<DialogContent> <DialogContent>
<DialogContentText> <DialogContentText>{translate("resources.delete_media.helper.send")}</DialogContentText>
{translate("resources.delete_media.helper.send")}
</DialogContentText>
<SimpleForm toolbar={<DeleteMediaToolbar />} onSubmit={onSubmit}> <SimpleForm toolbar={<DeleteMediaToolbar />} onSubmit={onSubmit}>
<DateTimeInput <DateTimeInput
fullWidth fullWidth
@ -98,11 +86,7 @@ export const DeleteMediaButton = (props: ButtonProps) => {
const openDialog = () => setOpen(true); const openDialog = () => setOpen(true);
const closeDialog = () => setOpen(false); const closeDialog = () => setOpen(false);
const deleteMedia = (values: { const deleteMedia = (values: { before_ts: string; size_gt: number; keep_profiles: boolean }) => {
before_ts: string;
size_gt: number;
keep_profiles: boolean;
}) => {
deleteOne( deleteOne(
"delete_media", "delete_media",
// needs meta.before_ts, meta.size_gt and meta.keep_profiles // needs meta.before_ts, meta.size_gt and meta.keep_profiles
@ -140,11 +124,7 @@ export const DeleteMediaButton = (props: ButtonProps) => {
> >
<DeleteSweepIcon /> <DeleteSweepIcon />
</Button> </Button>
<DeleteMediaDialog <DeleteMediaDialog open={open} onClose={closeDialog} onSubmit={deleteMedia} />
open={open}
onClose={closeDialog}
onSubmit={deleteMedia}
/>
</> </>
); );
}; };
@ -313,11 +293,7 @@ export const QuarantineMediaButton = (props: ButtonProps) => {
})} })}
> >
<div> <div>
<Button <Button {...props} onClick={handleRemoveQuarantaine} disabled={isLoading}>
{...props}
onClick={handleRemoveQuarantaine}
disabled={isLoading}
>
<BlockIcon color="error" /> <BlockIcon color="error" />
</Button> </Button>
</div> </div>

View file

@ -1,3 +1,14 @@
import EventIcon from "@mui/icons-material/Event";
import FastForwardIcon from "@mui/icons-material/FastForward";
import UserIcon from "@mui/icons-material/Group";
import HttpsIcon from "@mui/icons-material/Https";
import NoEncryptionIcon from "@mui/icons-material/NoEncryption";
import PageviewIcon from "@mui/icons-material/Pageview";
import ViewListIcon from "@mui/icons-material/ViewList";
import RoomIcon from "@mui/icons-material/ViewList";
import VisibilityIcon from "@mui/icons-material/Visibility";
import Box from "@mui/material/Box";
import { useTheme } from "@mui/material/styles";
import { import {
BooleanField, BooleanField,
BulkDeleteButton, BulkDeleteButton,
@ -26,28 +37,16 @@ import {
useRecordContext, useRecordContext,
useTranslate, useTranslate,
} from "react-admin"; } from "react-admin";
import { useTheme } from "@mui/material/styles";
import Box from "@mui/material/Box";
import FastForwardIcon from "@mui/icons-material/FastForward";
import HttpsIcon from "@mui/icons-material/Https";
import NoEncryptionIcon from "@mui/icons-material/NoEncryption";
import PageviewIcon from "@mui/icons-material/Pageview";
import UserIcon from "@mui/icons-material/Group";
import ViewListIcon from "@mui/icons-material/ViewList";
import VisibilityIcon from "@mui/icons-material/Visibility";
import EventIcon from "@mui/icons-material/Event";
import RoomIcon from "@mui/icons-material/ViewList";
import { import {
RoomDirectoryBulkUnpublishButton, RoomDirectoryBulkUnpublishButton,
RoomDirectoryBulkPublishButton, RoomDirectoryBulkPublishButton,
RoomDirectoryUnpublishButton, RoomDirectoryUnpublishButton,
RoomDirectoryPublishButton, RoomDirectoryPublishButton,
} from "./RoomDirectory"; } from "./RoomDirectory";
import { date_format } from "./date"; import { DATE_FORMAT } from "./date";
const RoomPagination = () => ( const RoomPagination = () => <Pagination rowsPerPageOptions={[10, 25, 50, 100, 500, 1000]} />;
<Pagination rowsPerPageOptions={[10, 25, 50, 100, 500, 1000]} />
);
const RoomTitle = () => { const RoomTitle = () => {
const record = useRecordContext(); const record = useRecordContext();
@ -66,11 +65,7 @@ const RoomTitle = () => {
const RoomShowActions = () => { const RoomShowActions = () => {
const record = useRecordContext(); const record = useRecordContext();
const publishButton = record.public ? ( const publishButton = record.public ? <RoomDirectoryUnpublishButton /> : <RoomDirectoryPublishButton />;
<RoomDirectoryUnpublishButton />
) : (
<RoomDirectoryPublishButton />
);
// FIXME: refresh after (un)publish // FIXME: refresh after (un)publish
return ( return (
<TopToolbar> <TopToolbar>
@ -99,42 +94,19 @@ export const RoomShow = (props: ShowProps) => {
</ReferenceField> </ReferenceField>
</Tab> </Tab>
<Tab <Tab label="synapseadmin.rooms.tabs.detail" icon={<PageviewIcon />} path="detail">
label="synapseadmin.rooms.tabs.detail"
icon={<PageviewIcon />}
path="detail"
>
<TextField source="joined_members" /> <TextField source="joined_members" />
<TextField source="joined_local_members" /> <TextField source="joined_local_members" />
<TextField source="joined_local_devices" /> <TextField source="joined_local_devices" />
<TextField source="state_events" /> <TextField source="state_events" />
<TextField source="version" /> <TextField source="version" />
<TextField <TextField source="encryption" emptyText={translate("resources.rooms.enums.unencrypted")} />
source="encryption"
emptyText={translate("resources.rooms.enums.unencrypted")}
/>
</Tab> </Tab>
<Tab <Tab label="synapseadmin.rooms.tabs.members" icon={<UserIcon />} path="members">
label="synapseadmin.rooms.tabs.members" <ReferenceManyField reference="room_members" target="room_id" label={false}>
icon={<UserIcon />} <Datagrid style={{ width: "100%" }} rowClick={id => "/users/" + id} bulkActionButtons={false}>
path="members" <TextField source="id" sortable={false} label="resources.users.fields.id" />
>
<ReferenceManyField
reference="room_members"
target="room_id"
label={false}
>
<Datagrid
style={{ width: "100%" }}
rowClick={id => "/users/" + id}
bulkActionButtons={false}
>
<TextField
source="id"
sortable={false}
label="resources.users.fields.id"
/>
<ReferenceField <ReferenceField
label="resources.users.fields.displayname" label="resources.users.fields.displayname"
source="id" source="id"
@ -148,11 +120,7 @@ export const RoomShow = (props: ShowProps) => {
</ReferenceManyField> </ReferenceManyField>
</Tab> </Tab>
<Tab <Tab label="synapseadmin.rooms.tabs.permission" icon={<VisibilityIcon />} path="permission">
label="synapseadmin.rooms.tabs.permission"
icon={<VisibilityIcon />}
path="permission"
>
<BooleanField source="federatable" /> <BooleanField source="federatable" />
<BooleanField source="public" /> <BooleanField source="public" />
<SelectField <SelectField
@ -203,41 +171,20 @@ export const RoomShow = (props: ShowProps) => {
/> />
</Tab> </Tab>
<Tab <Tab label={translate("resources.room_state.name", { smart_count: 2 })} icon={<EventIcon />} path="state">
label={translate("resources.room_state.name", { smart_count: 2 })} <ReferenceManyField reference="room_state" target="room_id" label={false}>
icon={<EventIcon />}
path="state"
>
<ReferenceManyField
reference="room_state"
target="room_id"
label={false}
>
<Datagrid style={{ width: "100%" }} bulkActionButtons={false}> <Datagrid style={{ width: "100%" }} bulkActionButtons={false}>
<TextField source="type" sortable={false} /> <TextField source="type" sortable={false} />
<DateField <DateField source="origin_server_ts" showTime options={DATE_FORMAT} sortable={false} />
source="origin_server_ts"
showTime
options={date_format}
sortable={false}
/>
<TextField source="content" sortable={false} /> <TextField source="content" sortable={false} />
<ReferenceField <ReferenceField source="sender" reference="users" sortable={false}>
source="sender"
reference="users"
sortable={false}
>
<TextField source="id" /> <TextField source="id" />
</ReferenceField> </ReferenceField>
</Datagrid> </Datagrid>
</ReferenceManyField> </ReferenceManyField>
</Tab> </Tab>
<Tab <Tab label="resources.forward_extremities.name" icon={<FastForwardIcon />} path="forward_extremities">
label="resources.forward_extremities.name"
icon={<FastForwardIcon />}
path="forward_extremities"
>
<Box <Box
sx={{ sx={{
fontFamily: "Roboto, Helvetica, Arial, sans-serif", fontFamily: "Roboto, Helvetica, Arial, sans-serif",
@ -246,19 +193,10 @@ export const RoomShow = (props: ShowProps) => {
> >
{translate("resources.rooms.helper.forward_extremities")} {translate("resources.rooms.helper.forward_extremities")}
</Box> </Box>
<ReferenceManyField <ReferenceManyField reference="forward_extremities" target="room_id" label={false}>
reference="forward_extremities"
target="room_id"
label={false}
>
<Datagrid style={{ width: "100%" }} bulkActionButtons={false}> <Datagrid style={{ width: "100%" }} bulkActionButtons={false}>
<TextField source="id" sortable={false} /> <TextField source="id" sortable={false} />
<DateField <DateField source="received_ts" showTime options={DATE_FORMAT} sortable={false} />
source="received_ts"
showTime
options={date_format}
sortable={false}
/>
<NumberField source="depth" sortable={false} /> <NumberField source="depth" sortable={false} />
<TextField source="state_group" sortable={false} /> <TextField source="state_group" sortable={false} />
</Datagrid> </Datagrid>
@ -304,12 +242,7 @@ export const RoomList = (props: ListProps) => {
<DatagridConfigurable <DatagridConfigurable
rowClick="show" rowClick="show"
bulkActionButtons={<RoomBulkActionButtons />} bulkActionButtons={<RoomBulkActionButtons />}
omit={[ omit={["joined_local_members", "state_events", "version", "federatable"]}
"joined_local_members",
"state_events",
"version",
"federatable",
]}
> >
<BooleanField <BooleanField
source="is_encrypted" source="is_encrypted"
@ -322,12 +255,7 @@ export const RoomList = (props: ListProps) => {
[`& [data-testid="false"]`]: { color: theme.palette.error.main }, [`& [data-testid="false"]`]: { color: theme.palette.error.main },
}} }}
/> />
<FunctionField <FunctionField source="name" render={record => record["name"] || record["canonical_alias"] || record["id"]} />
source="name"
render={record =>
record["name"] || record["canonical_alias"] || record["id"]
}
/>
<TextField source="joined_members" /> <TextField source="joined_members" />
<TextField source="joined_local_members" /> <TextField source="joined_local_members" />
<TextField source="state_events" /> <TextField source="state_events" />

View file

@ -25,9 +25,7 @@ const ListActions = () => {
); );
}; };
const UserMediaStatsPagination = () => ( const UserMediaStatsPagination = () => <Pagination rowsPerPageOptions={[10, 25, 50, 100, 500, 1000]} />;
<Pagination rowsPerPageOptions={[10, 25, 50, 100, 500, 1000]} />
);
const userMediaStatsFilters = [<SearchInput source="search_term" alwaysOn />]; const userMediaStatsFilters = [<SearchInput source="search_term" alwaysOn />];
@ -39,15 +37,9 @@ export const UserMediaStatsList = (props: ListProps) => (
pagination={<UserMediaStatsPagination />} pagination={<UserMediaStatsPagination />}
sort={{ field: "media_length", order: "DESC" }} sort={{ field: "media_length", order: "DESC" }}
> >
<Datagrid <Datagrid rowClick={id => "/users/" + id + "/media"} bulkActionButtons={false}>
rowClick={id => "/users/" + id + "/media"}
bulkActionButtons={false}
>
<TextField source="user_id" label="resources.users.fields.id" /> <TextField source="user_id" label="resources.users.fields.id" />
<TextField <TextField source="displayname" label="resources.users.fields.displayname" />
source="displayname"
label="resources.users.fields.displayname"
/>
<NumberField source="media_count" /> <NumberField source="media_count" />
<NumberField source="media_length" /> <NumberField source="media_length" />
</Datagrid> </Datagrid>

View file

@ -2,11 +2,11 @@ import AssignmentIndIcon from "@mui/icons-material/AssignmentInd";
import ContactMailIcon from "@mui/icons-material/ContactMail"; import ContactMailIcon from "@mui/icons-material/ContactMail";
import DevicesIcon from "@mui/icons-material/Devices"; import DevicesIcon from "@mui/icons-material/Devices";
import GetAppIcon from "@mui/icons-material/GetApp"; import GetAppIcon from "@mui/icons-material/GetApp";
import UserIcon from "@mui/icons-material/Group";
import NotificationsIcon from "@mui/icons-material/Notifications"; import NotificationsIcon from "@mui/icons-material/Notifications";
import PermMediaIcon from "@mui/icons-material/PermMedia"; import PermMediaIcon from "@mui/icons-material/PermMedia";
import PersonPinIcon from "@mui/icons-material/PersonPin"; import PersonPinIcon from "@mui/icons-material/PersonPin";
import SettingsInputComponentIcon from "@mui/icons-material/SettingsInputComponent"; import SettingsInputComponentIcon from "@mui/icons-material/SettingsInputComponent";
import UserIcon from "@mui/icons-material/Group";
import ViewListIcon from "@mui/icons-material/ViewList"; import ViewListIcon from "@mui/icons-material/ViewList";
import { import {
ArrayInput, ArrayInput,
@ -49,15 +49,12 @@ import {
useListContext, useListContext,
} from "react-admin"; } from "react-admin";
import { Link } from "react-router-dom"; import { Link } from "react-router-dom";
import AvatarField from "./AvatarField"; import AvatarField from "./AvatarField";
import { ServerNoticeButton, ServerNoticeBulkButton } from "./ServerNotices"; import { ServerNoticeButton, ServerNoticeBulkButton } from "./ServerNotices";
import { DATE_FORMAT } from "./date";
import { DeviceRemoveButton } from "./devices"; import { DeviceRemoveButton } from "./devices";
import { import { MediaIDField, ProtectMediaButton, QuarantineMediaButton } from "./media";
MediaIDField,
ProtectMediaButton,
QuarantineMediaButton,
} from "./media";
import { date_format } from "./date";
const choices_medium = [ const choices_medium = [
{ id: "email", name: "resources.users.email" }, { id: "email", name: "resources.users.email" },
@ -87,18 +84,12 @@ UserListActions.defaultProps = {
onUnselectItems: () => null, onUnselectItems: () => null,
}; };
const UserPagination = () => ( const UserPagination = () => <Pagination rowsPerPageOptions={[10, 25, 50, 100, 500, 1000]} />;
<Pagination rowsPerPageOptions={[10, 25, 50, 100, 500, 1000]} />
);
const userFilters = [ const userFilters = [
<SearchInput source="name" alwaysOn />, <SearchInput source="name" alwaysOn />,
<BooleanInput source="guests" alwaysOn />, <BooleanInput source="guests" alwaysOn />,
<BooleanInput <BooleanInput label="resources.users.fields.show_deactivated" source="deactivated" alwaysOn />,
label="resources.users.fields.show_deactivated"
source="deactivated"
alwaysOn
/>,
]; ];
const UserBulkActionButtons = () => ( const UserBulkActionButtons = () => (
@ -122,22 +113,13 @@ export const UserList = (props: ListProps) => (
pagination={<UserPagination />} pagination={<UserPagination />}
> >
<Datagrid rowClick="edit" bulkActionButtons={<UserBulkActionButtons />}> <Datagrid rowClick="edit" bulkActionButtons={<UserBulkActionButtons />}>
<AvatarField <AvatarField source="avatar_src" sx={{ height: "40px", width: "40px" }} sortBy="avatar_url" />
source="avatar_src"
sx={{ height: "40px", width: "40px" }}
sortBy="avatar_url"
/>
<TextField source="id" sortBy="name" /> <TextField source="id" sortBy="name" />
<TextField source="displayname" /> <TextField source="displayname" />
<BooleanField source="is_guest" /> <BooleanField source="is_guest" />
<BooleanField source="admin" /> <BooleanField source="admin" />
<BooleanField source="deactivated" /> <BooleanField source="deactivated" />
<DateField <DateField source="creation_ts" label="resources.users.fields.creation_ts_ms" showTime options={DATE_FORMAT} />
source="creation_ts"
label="resources.users.fields.creation_ts_ms"
showTime
options={date_format}
/>
</Datagrid> </Datagrid>
</List> </List>
); );
@ -146,11 +128,7 @@ export const UserList = (props: ListProps) => (
// here only local part of user_id // here only local part of user_id
// maxLength = 255 - "@" - ":" - localStorage.getItem("home_server").length // maxLength = 255 - "@" - ":" - localStorage.getItem("home_server").length
// localStorage.getItem("home_server").length is not valid here // localStorage.getItem("home_server").length is not valid here
const validateUser = [ const validateUser = [required(), maxLength(253), regex(/^[a-z0-9._=\-/]+$/, "synapseadmin.users.invalid_user_id")];
required(),
maxLength(253),
regex(/^[a-z0-9._=\-/]+$/, "synapseadmin.users.invalid_user_id"),
];
const validateAddress = [required(), maxLength(255)]; const validateAddress = [required(), maxLength(255)];
@ -177,36 +155,19 @@ export const UserCreate = (props: CreateProps) => (
<SimpleForm> <SimpleForm>
<TextInput source="id" autoComplete="off" validate={validateUser} /> <TextInput source="id" autoComplete="off" validate={validateUser} />
<TextInput source="displayname" validate={maxLength(256)} /> <TextInput source="displayname" validate={maxLength(256)} />
<PasswordInput <PasswordInput source="password" autoComplete="new-password" validate={maxLength(512)} />
source="password" <SelectInput source="user_type" choices={choices_type} translateChoice={false} resettable />
autoComplete="new-password"
validate={maxLength(512)}
/>
<SelectInput
source="user_type"
choices={choices_type}
translateChoice={false}
resettable
/>
<BooleanInput source="admin" /> <BooleanInput source="admin" />
<ArrayInput source="threepids"> <ArrayInput source="threepids">
<SimpleFormIterator disableReordering> <SimpleFormIterator disableReordering>
<SelectInput <SelectInput source="medium" choices={choices_medium} validate={required()} />
source="medium"
choices={choices_medium}
validate={required()}
/>
<TextInput source="address" validate={validateAddress} /> <TextInput source="address" validate={validateAddress} />
</SimpleFormIterator> </SimpleFormIterator>
</ArrayInput> </ArrayInput>
<ArrayInput source="external_ids" label="synapseadmin.users.tabs.sso"> <ArrayInput source="external_ids" label="synapseadmin.users.tabs.sso">
<SimpleFormIterator disableReordering> <SimpleFormIterator disableReordering>
<TextInput source="auth_provider" validate={required()} /> <TextInput source="auth_provider" validate={required()} />
<TextInput <TextInput source="external_id" label="resources.users.fields.id" validate={required()} />
source="external_id"
label="resources.users.fields.id"
validate={required()}
/>
</SimpleFormIterator> </SimpleFormIterator>
</ArrayInput> </ArrayInput>
</SimpleForm> </SimpleForm>
@ -231,42 +192,19 @@ export const UserEdit = (props: EditProps) => {
return ( return (
<Edit {...props} title={<UserTitle />} actions={<UserEditActions />}> <Edit {...props} title={<UserTitle />} actions={<UserEditActions />}>
<TabbedForm> <TabbedForm>
<FormTab <FormTab label={translate("resources.users.name", { smart_count: 1 })} icon={<PersonPinIcon />}>
label={translate("resources.users.name", { smart_count: 1 })} <AvatarField source="avatar_src" sortable={false} sx={{ height: "120px", width: "120px", float: "right" }} />
icon={<PersonPinIcon />}
>
<AvatarField
source="avatar_src"
sortable={false}
sx={{ height: "120px", width: "120px", float: "right" }}
/>
<TextInput source="id" disabled /> <TextInput source="id" disabled />
<TextInput source="displayname" /> <TextInput source="displayname" />
<PasswordInput <PasswordInput source="password" autoComplete="new-password" helperText="resources.users.helper.password" />
source="password" <SelectInput source="user_type" choices={choices_type} translateChoice={false} resettable />
autoComplete="new-password"
helperText="resources.users.helper.password"
/>
<SelectInput
source="user_type"
choices={choices_type}
translateChoice={false}
resettable
/>
<BooleanInput source="admin" /> <BooleanInput source="admin" />
<BooleanInput <BooleanInput source="deactivated" helperText="resources.users.helper.deactivate" />
source="deactivated" <DateField source="creation_ts_ms" showTime options={DATE_FORMAT} />
helperText="resources.users.helper.deactivate"
/>
<DateField source="creation_ts_ms" showTime options={date_format} />
<TextField source="consent_version" /> <TextField source="consent_version" />
</FormTab> </FormTab>
<FormTab <FormTab label="resources.users.threepid" icon={<ContactMailIcon />} path="threepid">
label="resources.users.threepid"
icon={<ContactMailIcon />}
path="threepid"
>
<ArrayInput source="threepids"> <ArrayInput source="threepids">
<SimpleFormIterator disableReordering> <SimpleFormIterator disableReordering>
<SelectInput source="medium" choices={choices_medium} /> <SelectInput source="medium" choices={choices_medium} />
@ -275,76 +213,34 @@ export const UserEdit = (props: EditProps) => {
</ArrayInput> </ArrayInput>
</FormTab> </FormTab>
<FormTab <FormTab label="synapseadmin.users.tabs.sso" icon={<AssignmentIndIcon />} path="sso">
label="synapseadmin.users.tabs.sso"
icon={<AssignmentIndIcon />}
path="sso"
>
<ArrayInput source="external_ids" label={false}> <ArrayInput source="external_ids" label={false}>
<SimpleFormIterator disableReordering> <SimpleFormIterator disableReordering>
<TextInput source="auth_provider" validate={required()} /> <TextInput source="auth_provider" validate={required()} />
<TextInput <TextInput source="external_id" label="resources.users.fields.id" validate={required()} />
source="external_id"
label="resources.users.fields.id"
validate={required()}
/>
</SimpleFormIterator> </SimpleFormIterator>
</ArrayInput> </ArrayInput>
</FormTab> </FormTab>
<FormTab <FormTab label={translate("resources.devices.name", { smart_count: 2 })} icon={<DevicesIcon />} path="devices">
label={translate("resources.devices.name", { smart_count: 2 })} <ReferenceManyField reference="devices" target="user_id" label={false}>
icon={<DevicesIcon />}
path="devices"
>
<ReferenceManyField
reference="devices"
target="user_id"
label={false}
>
<Datagrid style={{ width: "100%" }}> <Datagrid style={{ width: "100%" }}>
<TextField source="device_id" sortable={false} /> <TextField source="device_id" sortable={false} />
<TextField source="display_name" sortable={false} /> <TextField source="display_name" sortable={false} />
<TextField source="last_seen_ip" sortable={false} /> <TextField source="last_seen_ip" sortable={false} />
<DateField <DateField source="last_seen_ts" showTime options={DATE_FORMAT} sortable={false} />
source="last_seen_ts"
showTime
options={date_format}
sortable={false}
/>
<DeviceRemoveButton /> <DeviceRemoveButton />
</Datagrid> </Datagrid>
</ReferenceManyField> </ReferenceManyField>
</FormTab> </FormTab>
<FormTab <FormTab label="resources.connections.name" icon={<SettingsInputComponentIcon />} path="connections">
label="resources.connections.name" <ReferenceField reference="connections" source="id" label={false} link={false}>
icon={<SettingsInputComponentIcon />} <ArrayField source="devices[].sessions[0].connections" label="resources.connections.name">
path="connections"
>
<ReferenceField
reference="connections"
source="id"
label={false}
link={false}
>
<ArrayField
source="devices[].sessions[0].connections"
label="resources.connections.name"
>
<Datagrid style={{ width: "100%" }} bulkActionButtons={false}> <Datagrid style={{ width: "100%" }} bulkActionButtons={false}>
<TextField source="ip" sortable={false} /> <TextField source="ip" sortable={false} />
<DateField <DateField source="last_seen" showTime options={DATE_FORMAT} sortable={false} />
source="last_seen" <TextField source="user_agent" sortable={false} style={{ width: "100%" }} />
showTime
options={date_format}
sortable={false}
/>
<TextField
source="user_agent"
sortable={false}
style={{ width: "100%" }}
/>
</Datagrid> </Datagrid>
</ArrayField> </ArrayField>
</ReferenceField> </ReferenceField>
@ -365,12 +261,8 @@ export const UserEdit = (props: EditProps) => {
> >
<Datagrid style={{ width: "100%" }}> <Datagrid style={{ width: "100%" }}>
<MediaIDField source="media_id" /> <MediaIDField source="media_id" />
<DateField source="created_ts" showTime options={date_format} /> <DateField source="created_ts" showTime options={DATE_FORMAT} />
<DateField <DateField source="last_access_ts" showTime options={DATE_FORMAT} />
source="last_access_ts"
showTime
options={date_format}
/>
<NumberField source="media_length" /> <NumberField source="media_length" />
<TextField source="media_type" /> <TextField source="media_type" />
<TextField source="upload_name" /> <TextField source="upload_name" />
@ -382,26 +274,10 @@ export const UserEdit = (props: EditProps) => {
</ReferenceManyField> </ReferenceManyField>
</FormTab> </FormTab>
<FormTab <FormTab label={translate("resources.rooms.name", { smart_count: 2 })} icon={<ViewListIcon />} path="rooms">
label={translate("resources.rooms.name", { smart_count: 2 })} <ReferenceManyField reference="joined_rooms" target="user_id" label={false}>
icon={<ViewListIcon />} <Datagrid style={{ width: "100%" }} rowClick={id => "/rooms/" + id + "/show"} bulkActionButtons={false}>
path="rooms" <TextField source="id" sortable={false} label="resources.rooms.fields.room_id" />
>
<ReferenceManyField
reference="joined_rooms"
target="user_id"
label={false}
>
<Datagrid
style={{ width: "100%" }}
rowClick={id => "/rooms/" + id + "/show"}
bulkActionButtons={false}
>
<TextField
source="id"
sortable={false}
label="resources.rooms.fields.room_id"
/>
<ReferenceField <ReferenceField
label="resources.rooms.fields.name" label="resources.rooms.fields.name"
source="id" source="id"
@ -420,11 +296,7 @@ export const UserEdit = (props: EditProps) => {
icon={<NotificationsIcon />} icon={<NotificationsIcon />}
path="pushers" path="pushers"
> >
<ReferenceManyField <ReferenceManyField reference="pushers" target="user_id" label={false}>
reference="pushers"
target="user_id"
label={false}
>
<Datagrid style={{ width: "100%" }} bulkActionButtons={false}> <Datagrid style={{ width: "100%" }} bulkActionButtons={false}>
<TextField source="kind" sortable={false} /> <TextField source="kind" sortable={false} />
<TextField source="app_display_name" sortable={false} /> <TextField source="app_display_name" sortable={false} />

View file

@ -1,4 +1,5 @@
import { formalGermanMessages } from "@haleos/ra-language-german"; import { formalGermanMessages } from "@haleos/ra-language-german";
import { SynapseTranslationMessages } from "."; import { SynapseTranslationMessages } from ".";
const de: SynapseTranslationMessages = { const de: SynapseTranslationMessages = {
@ -45,11 +46,9 @@ const de: SynapseTranslationMessages = {
cards: { cards: {
importstats: { importstats: {
header: "Benutzer importieren", header: "Benutzer importieren",
users_total: users_total: "%{smart_count} Benutzer in der CSV Datei |||| %{smart_count} Benutzer in der CSV Datei",
"%{smart_count} Benutzer in der CSV Datei |||| %{smart_count} Benutzer in der CSV Datei",
guest_count: "%{smart_count} Gast |||| %{smart_count} Gäste", guest_count: "%{smart_count} Gast |||| %{smart_count} Gäste",
admin_count: admin_count: "%{smart_count} Server Administrator |||| %{smart_count} Server Administratoren",
"%{smart_count} Server Administrator |||| %{smart_count} Server Administratoren",
}, },
conflicts: { conflicts: {
header: "Konfliktstrategie", header: "Konfliktstrategie",
@ -61,8 +60,7 @@ const de: SynapseTranslationMessages = {
ids: { ids: {
header: "IDs", header: "IDs",
all_ids_present: "IDs in jedem Eintrag vorhanden", all_ids_present: "IDs in jedem Eintrag vorhanden",
count_ids_present: count_ids_present: "%{smart_count} Eintrag mit ID |||| %{smart_count} Einträge mit IDs",
"%{smart_count} Eintrag mit ID |||| %{smart_count} Einträge mit IDs",
mode: { mode: {
ignore: "Ignoriere IDs der CSV-Datei und erstelle neue", ignore: "Ignoriere IDs der CSV-Datei und erstelle neue",
update: "Aktualisiere existierende Benutzer", update: "Aktualisiere existierende Benutzer",
@ -71,8 +69,7 @@ const de: SynapseTranslationMessages = {
passwords: { passwords: {
header: "Passwörter", header: "Passwörter",
all_passwords_present: "Passwörter in jedem Eintrag vorhanden", all_passwords_present: "Passwörter in jedem Eintrag vorhanden",
count_passwords_present: count_passwords_present: "%{smart_count} Eintrag mit Passwort |||| %{smart_count} Einträge mit Passwörtern",
"%{smart_count} Eintrag mit Passwort |||| %{smart_count} Einträge mit Passwörtern",
use_passwords: "Verwende Passwörter aus der CSV Datei", use_passwords: "Verwende Passwörter aus der CSV Datei",
}, },
upload: { upload: {
@ -86,13 +83,11 @@ const de: SynapseTranslationMessages = {
}, },
results: { results: {
header: "Ergebnis", header: "Ergebnis",
total: total: "%{smart_count} Eintrag insgesamt |||| %{smart_count} Einträge insgesamt",
"%{smart_count} Eintrag insgesamt |||| %{smart_count} Einträge insgesamt",
successful: "%{smart_count} Einträge erfolgreich importiert", successful: "%{smart_count} Einträge erfolgreich importiert",
skipped: "%{smart_count} Einträge übersprungen", skipped: "%{smart_count} Einträge übersprungen",
download_skipped: "Übersprungene Einträge herunterladen", download_skipped: "Übersprungene Einträge herunterladen",
with_error: with_error: "%{smart_count} Eintrag mit Fehlern ||| %{smart_count} Einträge mit Fehlern",
"%{smart_count} Eintrag mit Fehlern ||| %{smart_count} Einträge mit Fehlern",
simulated_only: "Import-Vorgang war nur simuliert", simulated_only: "Import-Vorgang war nur simuliert",
}, },
}, },
@ -126,10 +121,8 @@ const de: SynapseTranslationMessages = {
user_type: "Benutzertyp", user_type: "Benutzertyp",
}, },
helper: { helper: {
password: password: "Durch die Änderung des Passworts wird der Benutzer von allen Sitzungen abgemeldet.",
"Durch die Änderung des Passworts wird der Benutzer von allen Sitzungen abgemeldet.", deactivate: "Sie müssen ein Passwort angeben, um ein Konto wieder zu aktivieren.",
deactivate:
"Sie müssen ein Passwort angeben, um ein Konto wieder zu aktivieren.",
erase: "DSGVO konformes Löschen der Benutzerdaten", erase: "DSGVO konformes Löschen der Benutzerdaten",
}, },
action: { action: {
@ -360,8 +353,7 @@ const de: SynapseTranslationMessages = {
guest_can_join: "Gastbenutzer dürfen beitreten", guest_can_join: "Gastbenutzer dürfen beitreten",
}, },
action: { action: {
title: title: "Raum aus Verzeichnis löschen |||| %{smart_count} Räume aus Verzeichnis löschen",
"Raum aus Verzeichnis löschen |||| %{smart_count} Räume aus Verzeichnis löschen",
content: 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?", "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", erase: "Lösche aus Verzeichnis",

View file

@ -1,4 +1,5 @@
import englishMessages from "ra-language-english"; import englishMessages from "ra-language-english";
import { SynapseTranslationMessages } from "."; import { SynapseTranslationMessages } from ".";
const en: SynapseTranslationMessages = { const en: SynapseTranslationMessages = {
@ -34,10 +35,8 @@ const en: SynapseTranslationMessages = {
at_entry: "At entry %{entry}: %{message}", at_entry: "At entry %{entry}: %{message}",
error: "Error", error: "Error",
required_field: "Required field '%{field}' is not present", required_field: "Required field '%{field}' is not present",
invalid_value: invalid_value: "Invalid value on line %{row}. '%{field}' field may only be 'true' or 'false'",
"Invalid value on line %{row}. '%{field}' field may only be 'true' or 'false'", unreasonably_big: "Refused to load unreasonably big file of %{size} megabytes",
unreasonably_big:
"Refused to load unreasonably big file of %{size} megabytes",
already_in_progress: "An import run is already in progress", already_in_progress: "An import run is already in progress",
id_exits: "ID %{id} already present", id_exits: "ID %{id} already present",
}, },
@ -46,8 +45,7 @@ const en: SynapseTranslationMessages = {
cards: { cards: {
importstats: { importstats: {
header: "Import users", header: "Import users",
users_total: users_total: "%{smart_count} user in CSV file |||| %{smart_count} users in CSV file",
"%{smart_count} user in CSV file |||| %{smart_count} users in CSV file",
guest_count: "%{smart_count} guest |||| %{smart_count} guests", guest_count: "%{smart_count} guest |||| %{smart_count} guests",
admin_count: "%{smart_count} admin |||| %{smart_count} admins", admin_count: "%{smart_count} admin |||| %{smart_count} admins",
}, },
@ -61,8 +59,7 @@ const en: SynapseTranslationMessages = {
ids: { ids: {
header: "IDs", header: "IDs",
all_ids_present: "IDs present on every entry", all_ids_present: "IDs present on every entry",
count_ids_present: count_ids_present: "%{smart_count} entry with ID |||| %{smart_count} entries with IDs",
"%{smart_count} entry with ID |||| %{smart_count} entries with IDs",
mode: { mode: {
ignore: "Ignore IDs in CSV and create new ones", ignore: "Ignore IDs in CSV and create new ones",
update: "Update existing records", update: "Update existing records",
@ -71,8 +68,7 @@ const en: SynapseTranslationMessages = {
passwords: { passwords: {
header: "Passwords", header: "Passwords",
all_passwords_present: "Passwords present on every entry", all_passwords_present: "Passwords present on every entry",
count_passwords_present: count_passwords_present: "%{smart_count} entry with password |||| %{smart_count} entries with passwords",
"%{smart_count} entry with password |||| %{smart_count} entries with passwords",
use_passwords: "Use passwords from CSV", use_passwords: "Use passwords from CSV",
}, },
upload: { upload: {
@ -86,13 +82,11 @@ const en: SynapseTranslationMessages = {
}, },
results: { results: {
header: "Import results", header: "Import results",
total: total: "%{smart_count} entry in total |||| %{smart_count} entries in total",
"%{smart_count} entry in total |||| %{smart_count} entries in total",
successful: "%{smart_count} entries successfully imported", successful: "%{smart_count} entries successfully imported",
skipped: "%{smart_count} entries skipped", skipped: "%{smart_count} entries skipped",
download_skipped: "Download skipped records", download_skipped: "Download skipped records",
with_error: with_error: "%{smart_count} entry with errors ||| %{smart_count} entries with errors",
"%{smart_count} entry with errors ||| %{smart_count} entries with errors",
simulated_only: "Run was only simulated", simulated_only: "Run was only simulated",
}, },
}, },
@ -217,8 +211,7 @@ const en: SynapseTranslationMessages = {
action: { action: {
erase: { erase: {
title: "Delete reported event", title: "Delete reported event",
content: content: "Are you sure you want to delete the reported event? This cannot be undone.",
"Are you sure you want to delete the reported event? This cannot be undone.",
}, },
}, },
}, },
@ -359,8 +352,7 @@ const en: SynapseTranslationMessages = {
guest_can_join: "guest users may join", guest_can_join: "guest users may join",
}, },
action: { action: {
title: title: "Delete room from directory |||| Delete %{smart_count} rooms from directory",
"Delete room from directory |||| Delete %{smart_count} rooms from directory",
content: 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?", "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", erase: "Delete from room directory",

View file

@ -1,4 +1,5 @@
import farsiMessages from "ra-language-farsi"; import farsiMessages from "ra-language-farsi";
import { SynapseTranslationMessages } from "."; import { SynapseTranslationMessages } from ".";
const fa: SynapseTranslationMessages = { const fa: SynapseTranslationMessages = {
@ -32,10 +33,8 @@ const fa: SynapseTranslationMessages = {
at_entry: "در هنگام ورود %{entry}: %{message}", at_entry: "در هنگام ورود %{entry}: %{message}",
error: "Error", error: "Error",
required_field: "فیلد الزامی '%{field}' وجود ندارد", required_field: "فیلد الزامی '%{field}' وجود ندارد",
invalid_value: invalid_value: "خطا در خط %{row}. '%{field}' فیلد ممکن است فقط 'درست' یا 'نادرست' باشد",
"خطا در خط %{row}. '%{field}' فیلد ممکن است فقط 'درست' یا 'نادرست' باشد", unreasonably_big: "از بارگذاری فایل هایی با حجم غیر منطقی خودداری کنید %{size} مگابایت",
unreasonably_big:
"از بارگذاری فایل هایی با حجم غیر منطقی خودداری کنید %{size} مگابایت",
already_in_progress: "یک بارگذاری از قبل در حال انجام است", already_in_progress: "یک بارگذاری از قبل در حال انجام است",
id_exits: "شناسه %{id} موجود است", id_exits: "شناسه %{id} موجود است",
}, },
@ -44,8 +43,7 @@ const fa: SynapseTranslationMessages = {
cards: { cards: {
importstats: { importstats: {
header: "وارد کردن کاربران", header: "وارد کردن کاربران",
users_total: users_total: "%{smart_count} user in CSV file |||| %{smart_count} users in CSV file",
"%{smart_count} user in CSV file |||| %{smart_count} users in CSV file",
guest_count: "%{smart_count} guest |||| %{smart_count} guests", guest_count: "%{smart_count} guest |||| %{smart_count} guests",
admin_count: "%{smart_count} admin |||| %{smart_count} admins", admin_count: "%{smart_count} admin |||| %{smart_count} admins",
}, },
@ -59,8 +57,7 @@ const fa: SynapseTranslationMessages = {
ids: { ids: {
header: "شناسنامه ها", header: "شناسنامه ها",
all_ids_present: "شناسه های موجود در هر ورودی", all_ids_present: "شناسه های موجود در هر ورودی",
count_ids_present: count_ids_present: "%{smart_count} ورود با شناسه |||| %{smart_count} ورودی با شناسه",
"%{smart_count} ورود با شناسه |||| %{smart_count} ورودی با شناسه",
mode: { mode: {
ignore: "شناسه ها را در CSV نادیده بگیر و شناسه های جدید ایجاد کن", ignore: "شناسه ها را در CSV نادیده بگیر و شناسه های جدید ایجاد کن",
update: "سوابق موجود را به روز کنید", update: "سوابق موجود را به روز کنید",
@ -69,8 +66,7 @@ const fa: SynapseTranslationMessages = {
passwords: { passwords: {
header: "رمز عبور", header: "رمز عبور",
all_passwords_present: "رمزهای عبور موجود در هر ورودی", all_passwords_present: "رمزهای عبور موجود در هر ورودی",
count_passwords_present: count_passwords_present: "%{smart_count} ورود با رمز عبور |||| %{smart_count} ورودی با رمز عبور",
"%{smart_count} ورود با رمز عبور |||| %{smart_count} ورودی با رمز عبور",
use_passwords: "از پسوردهای CSV استفاده کنید", use_passwords: "از پسوردهای CSV استفاده کنید",
}, },
upload: { upload: {
@ -88,8 +84,7 @@ const fa: SynapseTranslationMessages = {
successful: "%{smart_count} ورودی ها با موفقیت وارد شدند", successful: "%{smart_count} ورودی ها با موفقیت وارد شدند",
skipped: "%{smart_count} ورودی ها نادیده گرفته شدند", skipped: "%{smart_count} ورودی ها نادیده گرفته شدند",
download_skipped: "دانلود رکوردهای نادیده گرفته شده", download_skipped: "دانلود رکوردهای نادیده گرفته شده",
with_error: with_error: "%{smart_count} ورود با خطا ||| %{smart_count} ورودی های دارای خطا",
"%{smart_count} ورود با خطا ||| %{smart_count} ورودی های دارای خطا",
simulated_only: "اجرا فقط شبیه سازی شد", simulated_only: "اجرا فقط شبیه سازی شد",
}, },
}, },
@ -227,8 +222,7 @@ const fa: SynapseTranslationMessages = {
action: { action: {
erase: { erase: {
title: "حذف کردن %{id}", title: "حذف کردن %{id}",
content: content: 'آیا مطمئن هستید که می خواهید دستگاه را حذف کنید؟ "%{name}"?',
'آیا مطمئن هستید که می خواهید دستگاه را حذف کنید؟ "%{name}"?',
success: "دستگاه با موفقیت حذف شد.", success: "دستگاه با موفقیت حذف شد.",
failure: "خطایی رخ داده است.", failure: "خطایی رخ داده است.",
}, },
@ -343,8 +337,7 @@ const fa: SynapseTranslationMessages = {
guest_can_join: "کاربران مهمان ممکن است ملحق شوند", guest_can_join: "کاربران مهمان ممکن است ملحق شوند",
}, },
action: { action: {
title: title: "اتاق را از فهرست حذف کنید |||| حذف کنید %{smart_count} اتاق ها از دایرکتوری",
"اتاق را از فهرست حذف کنید |||| حذف کنید %{smart_count} اتاق ها از دایرکتوری",
content: content:
"آیا مطمئنید که می خواهید این اتاق را از فهرست راهنمای حذف کنید؟ |||| آیا مطمئن هستید که می خواهید این موارد را %{smart_count} از راهنمای اتاق ها حذف کنید؟", "آیا مطمئنید که می خواهید این اتاق را از فهرست راهنمای حذف کنید؟ |||| آیا مطمئن هستید که می خواهید این موارد را %{smart_count} از راهنمای اتاق ها حذف کنید؟",
erase: "حذف از فهرست اتاق", erase: "حذف از فهرست اتاق",

View file

@ -1,4 +1,5 @@
import frenchMessages from "ra-language-french"; import frenchMessages from "ra-language-french";
import { SynapseTranslationMessages } from "."; import { SynapseTranslationMessages } from ".";
const fr: SynapseTranslationMessages = { const fr: SynapseTranslationMessages = {
@ -8,15 +9,13 @@ const fr: SynapseTranslationMessages = {
base_url: "URL du serveur daccueil", base_url: "URL du serveur daccueil",
welcome: "Bienvenue sur Synapse-admin", welcome: "Bienvenue sur Synapse-admin",
server_version: "Version du serveur Synapse", server_version: "Version du serveur Synapse",
username_error: username_error: "Veuillez entrer un nom d'utilisateur complet : « @utilisateur:domaine »",
"Veuillez entrer un nom d'utilisateur complet : « @utilisateur:domaine »",
protocol_error: "L'URL doit commencer par « http:// » ou « https:// »", protocol_error: "L'URL doit commencer par « http:// » ou « https:// »",
url_error: "L'URL du serveur Matrix n'est pas valide", url_error: "L'URL du serveur Matrix n'est pas valide",
sso_sign_in: "Se connecter avec lauthentification unique", sso_sign_in: "Se connecter avec lauthentification unique",
}, },
users: { users: {
invalid_user_id: invalid_user_id: "Partie locale d'un identifiant utilisateur Matrix sans le nom du serveur daccueil.",
"Partie locale d'un identifiant utilisateur Matrix sans le nom du serveur daccueil.",
tabs: { sso: "Authentification unique" }, tabs: { sso: "Authentification unique" },
}, },
rooms: { rooms: {
@ -36,8 +35,7 @@ const fr: SynapseTranslationMessages = {
required_field: "Le champ requis « %{field} » est manquant", required_field: "Le champ requis « %{field} » est manquant",
invalid_value: invalid_value:
"Valeur non valide à la ligne %{row}. Le champ « %{field} » ne peut être que « true » ou « false »", "Valeur non valide à la ligne %{row}. Le champ « %{field} » ne peut être que « true » ou « false »",
unreasonably_big: unreasonably_big: "Refus de charger un fichier trop volumineux de %{size} mégaoctets",
"Refus de charger un fichier trop volumineux de %{size} mégaoctets",
already_in_progress: "Un import est déjà en cours", already_in_progress: "Un import est déjà en cours",
id_exits: "L'identifiant %{id} déjà présent", id_exits: "L'identifiant %{id} déjà présent",
}, },
@ -49,8 +47,7 @@ const fr: SynapseTranslationMessages = {
users_total: users_total:
"%{smart_count} utilisateur dans le fichier CSV |||| %{smart_count} utilisateurs dans le fichier CSV", "%{smart_count} utilisateur dans le fichier CSV |||| %{smart_count} utilisateurs dans le fichier CSV",
guest_count: "%{smart_count} visiteur |||| %{smart_count} visiteurs", guest_count: "%{smart_count} visiteur |||| %{smart_count} visiteurs",
admin_count: admin_count: "%{smart_count} administrateur |||| %{smart_count} administrateurs",
"%{smart_count} administrateur |||| %{smart_count} administrateurs",
}, },
conflicts: { conflicts: {
header: "Stratégie de résolution des conflits", header: "Stratégie de résolution des conflits",
@ -62,11 +59,9 @@ const fr: SynapseTranslationMessages = {
ids: { ids: {
header: "Identifiants", header: "Identifiants",
all_ids_present: "Identifiants présents pour chaque entrée", all_ids_present: "Identifiants présents pour chaque entrée",
count_ids_present: count_ids_present: "%{smart_count} entrée avec identifiant |||| %{smart_count} entrées avec identifiant",
"%{smart_count} entrée avec identifiant |||| %{smart_count} entrées avec identifiant",
mode: { mode: {
ignore: ignore: "Ignorer les identifiants dans le ficher CSV et en créer de nouveaux",
"Ignorer les identifiants dans le ficher CSV et en créer de nouveaux",
update: "Mettre à jour les enregistrements existants", update: "Mettre à jour les enregistrements existants",
}, },
}, },
@ -88,13 +83,11 @@ const fr: SynapseTranslationMessages = {
}, },
results: { results: {
header: "Résultats de l'import", header: "Résultats de l'import",
total: total: "%{smart_count} entrée au total |||| %{smart_count} entrées au total",
"%{smart_count} entrée au total |||| %{smart_count} entrées au total",
successful: "%{smart_count} entrées importées avec succès", successful: "%{smart_count} entrées importées avec succès",
skipped: "%{smart_count} entrées ignorées", skipped: "%{smart_count} entrées ignorées",
download_skipped: "Télécharger les entrées ignorées", download_skipped: "Télécharger les entrées ignorées",
with_error: with_error: "%{smart_count} entrée avec des erreurs ||| %{smart_count} entrées avec des erreurs",
"%{smart_count} entrée avec des erreurs ||| %{smart_count} entrées avec des erreurs",
simulated_only: "L'import était simulé", simulated_only: "L'import était simulé",
}, },
}, },
@ -127,8 +120,7 @@ const fr: SynapseTranslationMessages = {
auth_provider: "Fournisseur d'identité", auth_provider: "Fournisseur d'identité",
}, },
helper: { helper: {
deactivate: deactivate: "Vous devrez fournir un mot de passe pour réactiver le compte.",
"Vous devrez fournir un mot de passe pour réactiver le compte.",
erase: "Marquer l'utilisateur comme effacé conformément au RGPD", erase: "Marquer l'utilisateur comme effacé conformément au RGPD",
}, },
action: { action: {
@ -342,13 +334,11 @@ const fr: SynapseTranslationMessages = {
room_directory: { room_directory: {
name: "Répertoire des salons", name: "Répertoire des salons",
fields: { fields: {
world_readable: world_readable: "Tout utilisateur peut avoir un aperçu du salon, sans en devenir membre",
"Tout utilisateur peut avoir un aperçu du salon, sans en devenir membre",
guest_can_join: "Les visiteurs peuvent rejoindre le salon", guest_can_join: "Les visiteurs peuvent rejoindre le salon",
}, },
action: { action: {
title: title: "Supprimer un salon du répertoire |||| Supprimer %{smart_count} salons du répertoire",
"Supprimer un salon du répertoire |||| Supprimer %{smart_count} salons du répertoire",
content: content:
"Voulez-vous vraiment supprimer ce salon du répertoire ? |||| Voulez-vous vraiment supprimer ces %{smart_count} salons du répertoire ?", "Voulez-vous vraiment supprimer ce salon du répertoire ? |||| Voulez-vous vraiment supprimer ces %{smart_count} salons du répertoire ?",
erase: "Supprimer du répertoire des salons", erase: "Supprimer du répertoire des salons",
@ -369,8 +359,7 @@ const fr: SynapseTranslationMessages = {
length: "Longueur", length: "Longueur",
}, },
helper: { helper: {
length: length: "Longueur du jeton généré aléatoirement si aucun jeton n'est pas spécifié",
"Longueur du jeton généré aléatoirement si aucun jeton n'est pas spécifié",
}, },
}, },
}, },

View file

@ -1,4 +1,5 @@
import italianMessages from "ra-language-italian"; import italianMessages from "ra-language-italian";
import { SynapseTranslationMessages } from "."; import { SynapseTranslationMessages } from ".";
const it: SynapseTranslationMessages = { const it: SynapseTranslationMessages = {
@ -8,8 +9,7 @@ const it: SynapseTranslationMessages = {
base_url: "URL dell'homeserver", base_url: "URL dell'homeserver",
welcome: "Benvenuto in Synapse-admin", welcome: "Benvenuto in Synapse-admin",
server_version: "Versione di Synapse", server_version: "Versione di Synapse",
username_error: username_error: "Per favore inserisci un ID utente completo: '@utente:dominio'",
"Per favore inserisci un ID utente completo: '@utente:dominio'",
protocol_error: "L'URL deve iniziare per 'http://' o 'https://'", protocol_error: "L'URL deve iniziare per 'http://' o 'https://'",
url_error: "URL del server Matrix non valido", url_error: "URL del server Matrix non valido",
sso_sign_in: "Accedi con SSO", sso_sign_in: "Accedi con SSO",
@ -33,10 +33,8 @@ const it: SynapseTranslationMessages = {
at_entry: "Alla voce %{entry}: %{message}", at_entry: "Alla voce %{entry}: %{message}",
error: "Errore", error: "Errore",
required_field: "Il campo '%{field}' non è presente", required_field: "Il campo '%{field}' non è presente",
invalid_value: invalid_value: "Valore non valido alla riga %{row}. '%{field}' Il campo può essere solo 'true' o 'false'",
"Valore non valido alla riga %{row}. '%{field}' Il campo può essere solo 'true' o 'false'", unreasonably_big: "Impossibile caricare un file così grosso (%{size} megabyte)",
unreasonably_big:
"Impossibile caricare un file così grosso (%{size} megabyte)",
already_in_progress: "Un import è attualmente già in caricamento", already_in_progress: "Un import è attualmente già in caricamento",
id_exits: "L'ID %{id} è già presente", id_exits: "L'ID %{id} è già presente",
}, },
@ -45,11 +43,9 @@ const it: SynapseTranslationMessages = {
cards: { cards: {
importstats: { importstats: {
header: "Importa utenti", header: "Importa utenti",
users_total: users_total: "%{smart_count} utente nel file CSV |||| %{smart_count} utenti nel file CSV",
"%{smart_count} utente nel file CSV |||| %{smart_count} utenti nel file CSV",
guest_count: "%{smart_count} ospite |||| %{smart_count} ospiti", guest_count: "%{smart_count} ospite |||| %{smart_count} ospiti",
admin_count: admin_count: "%{smart_count} amministratore |||| %{smart_count} amministratori",
"%{smart_count} amministratore |||| %{smart_count} amministratori",
}, },
conflicts: { conflicts: {
header: "Strategia di conflitto", header: "Strategia di conflitto",
@ -61,8 +57,7 @@ const it: SynapseTranslationMessages = {
ids: { ids: {
header: "ID", header: "ID",
all_ids_present: "ID presenti in ogni voce", all_ids_present: "ID presenti in ogni voce",
count_ids_present: count_ids_present: "%{smart_count} voce con ID |||| %{smart_count} voci con ID",
"%{smart_count} voce con ID |||| %{smart_count} voci con ID",
mode: { mode: {
ignore: "Ignora gli ID nel file CSV e creane di nuovi", ignore: "Ignora gli ID nel file CSV e creane di nuovi",
update: "Aggiorna le voci esistenti", update: "Aggiorna le voci esistenti",
@ -71,8 +66,7 @@ const it: SynapseTranslationMessages = {
passwords: { passwords: {
header: "Passwords", header: "Passwords",
all_passwords_present: "Password presenti in ogni voce", all_passwords_present: "Password presenti in ogni voce",
count_passwords_present: count_passwords_present: "%{smart_count} voce con password |||| %{smart_count} voci con password",
"%{smart_count} voce con password |||| %{smart_count} voci con password",
use_passwords: "Usa le password dal file CSV", use_passwords: "Usa le password dal file CSV",
}, },
upload: { upload: {
@ -86,13 +80,11 @@ const it: SynapseTranslationMessages = {
}, },
results: { results: {
header: "Importa i risultati", header: "Importa i risultati",
total: total: "%{smart_count} voce in totale |||| %{smart_count} voci in totale",
"%{smart_count} voce in totale |||| %{smart_count} voci in totale",
successful: "%{smart_count} voci importate con successo", successful: "%{smart_count} voci importate con successo",
skipped: "%{smart_count} voci ignorate", skipped: "%{smart_count} voci ignorate",
download_skipped: "Scarica le voci ignorate", download_skipped: "Scarica le voci ignorate",
with_error: with_error: "%{smart_count} voce con errori ||| %{smart_count} voci con errori",
"%{smart_count} voce con errori ||| %{smart_count} voci con errori",
simulated_only: "Il processo era stato solamente simulato", simulated_only: "Il processo era stato solamente simulato",
}, },
}, },
@ -126,8 +118,7 @@ const it: SynapseTranslationMessages = {
user_type: "Tipo d'utente", user_type: "Tipo d'utente",
}, },
helper: { helper: {
password: password: "Cambiando la password l'utente verrà disconnesso da tutte le sessioni attive.",
"Cambiando la password l'utente verrà disconnesso da tutte le sessioni attive.",
deactivate: "Devi fornire una password per riattivare l'account.", deactivate: "Devi fornire una password per riattivare l'account.",
erase: "Constrassegna l'utente come cancellato dal GDPR", erase: "Constrassegna l'utente come cancellato dal GDPR",
}, },
@ -346,8 +337,7 @@ const it: SynapseTranslationMessages = {
guest_can_join: "gli utenti ospite possono entrare", guest_can_join: "gli utenti ospite possono entrare",
}, },
action: { action: {
title: title: "Cancella stanza dall'elenco |||| Cancella %{smart_count} stanze dall'elenco",
"Cancella stanza dall'elenco |||| Cancella %{smart_count} stanze dall'elenco",
content: content:
"Sei sicuro di voler rimuovere questa stanza dall'elenco? |||| Sei sicuro di voler rimuovere %{smart_count} stanze dall'elenco?", "Sei sicuro di voler rimuovere questa stanza dall'elenco? |||| Sei sicuro di voler rimuovere %{smart_count} stanze dall'elenco?",
erase: "Rimuovi dall'elenco", erase: "Rimuovi dall'elenco",

View file

@ -1,4 +1,5 @@
import chineseMessages from "@haxqer/ra-language-chinese"; import chineseMessages from "@haxqer/ra-language-chinese";
import { SynapseTranslationMessages } from "."; import { SynapseTranslationMessages } from ".";
const zh: SynapseTranslationMessages = { const zh: SynapseTranslationMessages = {
@ -14,8 +15,7 @@ const zh: SynapseTranslationMessages = {
sso_sign_in: "使用 SSO 登录", sso_sign_in: "使用 SSO 登录",
}, },
users: { users: {
invalid_user_id: invalid_user_id: "必须要是一个有效的 Matrix 用户 ID ,例如 @user_id:homeserver",
"必须要是一个有效的 Matrix 用户 ID ,例如 @user_id:homeserver",
tabs: { sso: "SSO" }, tabs: { sso: "SSO" },
}, },
rooms: { rooms: {
@ -33,8 +33,7 @@ const zh: SynapseTranslationMessages = {
at_entry: "在条目 %{entry}: %{message}", at_entry: "在条目 %{entry}: %{message}",
error: "错误", error: "错误",
required_field: "需要的值 '%{field}' 未被设置。", required_field: "需要的值 '%{field}' 未被设置。",
invalid_value: invalid_value: "第 %{row} 行出现无效值。 '%{field}' 只可以是 'true' 或 'false'。",
"第 %{row} 行出现无效值。 '%{field}' 只可以是 'true' 或 'false'。",
unreasonably_big: "拒绝加载过大的文件: %{size} MB", unreasonably_big: "拒绝加载过大的文件: %{size} MB",
already_in_progress: "一个导入进程已经在运行中", already_in_progress: "一个导入进程已经在运行中",
id_exits: "ID %{id} 已经存在", id_exits: "ID %{id} 已经存在",
@ -44,8 +43,7 @@ const zh: SynapseTranslationMessages = {
cards: { cards: {
importstats: { importstats: {
header: "导入用户", header: "导入用户",
users_total: users_total: "%{smart_count} 用户在 CSV 文件中 |||| %{smart_count} 用户在 CSV 文件中",
"%{smart_count} 用户在 CSV 文件中 |||| %{smart_count} 用户在 CSV 文件中",
guest_count: "%{smart_count} 访客 |||| %{smart_count} 访客", guest_count: "%{smart_count} 访客 |||| %{smart_count} 访客",
admin_count: "%{smart_count} 管理员 |||| %{smart_count} 管理员", admin_count: "%{smart_count} 管理员 |||| %{smart_count} 管理员",
}, },
@ -59,8 +57,7 @@ const zh: SynapseTranslationMessages = {
ids: { ids: {
header: "IDs", header: "IDs",
all_ids_present: "每条记录的 ID", all_ids_present: "每条记录的 ID",
count_ids_present: count_ids_present: "%{smart_count} 个含 ID 的记录 |||| %{smart_count} 个含 ID 的记录",
"%{smart_count} 个含 ID 的记录 |||| %{smart_count} 个含 ID 的记录",
mode: { mode: {
ignore: "忽略 CSV 中的 ID 并创建新的", ignore: "忽略 CSV 中的 ID 并创建新的",
update: "更新已经存在的记录", update: "更新已经存在的记录",
@ -69,8 +66,7 @@ const zh: SynapseTranslationMessages = {
passwords: { passwords: {
header: "密码", header: "密码",
all_passwords_present: "每条记录的密码", all_passwords_present: "每条记录的密码",
count_passwords_present: count_passwords_present: "%{smart_count} 个含密码的记录 |||| %{smart_count} 个含密码的记录",
"%{smart_count} 个含密码的记录 |||| %{smart_count} 个含密码的记录",
use_passwords: "使用 CSV 中标记的密码", use_passwords: "使用 CSV 中标记的密码",
}, },
upload: { upload: {
@ -88,8 +84,7 @@ const zh: SynapseTranslationMessages = {
successful: "%{smart_count} 条记录导入成功", successful: "%{smart_count} 条记录导入成功",
skipped: "跳过 %{smart_count} 条记录", skipped: "跳过 %{smart_count} 条记录",
download_skipped: "下载跳过的记录", download_skipped: "下载跳过的记录",
with_error: with_error: "%{smart_count} 条记录出现错误 ||| %{smart_count} 条记录出现错误",
"%{smart_count} 条记录出现错误 ||| %{smart_count} 条记录出现错误",
simulated_only: "只是一次模拟运行", simulated_only: "只是一次模拟运行",
}, },
}, },

View file

@ -1,4 +1,5 @@
import React from "react"; import React from "react";
import { createRoot } from "react-dom/client"; import { createRoot } from "react-dom/client";
import App from "./App"; import App from "./App";

View file

@ -1,4 +1,5 @@
import fetchMock from "jest-fetch-mock"; import fetchMock from "jest-fetch-mock";
import authProvider from "./authProvider"; import authProvider from "./authProvider";
fetchMock.enableMocks(); fetchMock.enableMocks();
@ -27,17 +28,14 @@ describe("authProvider", () => {
}); });
expect(ret).toBe(undefined); expect(ret).toBe(undefined);
expect(fetch).toBeCalledWith( expect(fetch).toBeCalledWith("http://example.com/_matrix/client/r0/login", {
"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"}', body: '{"device_id":null,"initial_device_display_name":"Synapse Admin","type":"m.login.password","user":"@user:example.com","password":"secret"}',
headers: new Headers({ headers: new Headers({
Accept: "application/json", Accept: "application/json",
"Content-Type": "application/json", "Content-Type": "application/json",
}), }),
method: "POST", method: "POST",
} });
);
expect(localStorage.getItem("base_url")).toEqual("http://example.com"); expect(localStorage.getItem("base_url")).toEqual("http://example.com");
expect(localStorage.getItem("user_id")).toEqual("@user:example.com"); expect(localStorage.getItem("user_id")).toEqual("@user:example.com");
expect(localStorage.getItem("access_token")).toEqual("foobar"); expect(localStorage.getItem("access_token")).toEqual("foobar");
@ -61,17 +59,14 @@ describe("authProvider", () => {
}); });
expect(ret).toBe(undefined); expect(ret).toBe(undefined);
expect(fetch).toHaveBeenCalledWith( expect(fetch).toHaveBeenCalledWith("https://example.com/_matrix/client/r0/login", {
"https://example.com/_matrix/client/r0/login",
{
body: '{"device_id":null,"initial_device_display_name":"Synapse Admin","type":"m.login.token","token":"login_token"}', body: '{"device_id":null,"initial_device_display_name":"Synapse Admin","type":"m.login.token","token":"login_token"}',
headers: new Headers({ headers: new Headers({
Accept: "application/json", Accept: "application/json",
"Content-Type": "application/json", "Content-Type": "application/json",
}), }),
method: "POST", method: "POST",
} });
);
expect(localStorage.getItem("base_url")).toEqual("https://example.com"); expect(localStorage.getItem("base_url")).toEqual("https://example.com");
expect(localStorage.getItem("user_id")).toEqual("@user:example.com"); expect(localStorage.getItem("user_id")).toEqual("@user:example.com");
expect(localStorage.getItem("access_token")).toEqual("foobar"); expect(localStorage.getItem("access_token")).toEqual("foobar");
@ -100,21 +95,15 @@ describe("authProvider", () => {
describe("checkError", () => { describe("checkError", () => {
it("should resolve if error.status is not 401 or 403", async () => { it("should resolve if error.status is not 401 or 403", async () => {
await expect( await expect(authProvider.checkError({ status: 200 })).resolves.toBeUndefined();
authProvider.checkError({ status: 200 })
).resolves.toBeUndefined();
}); });
it("should reject if error.status is 401", async () => { it("should reject if error.status is 401", async () => {
await expect( await expect(authProvider.checkError({ status: 401 })).rejects.toBeUndefined();
authProvider.checkError({ status: 401 })
).rejects.toBeUndefined();
}); });
it("should reject if error.status is 403", async () => { it("should reject if error.status is 403", async () => {
await expect( await expect(authProvider.checkError({ status: 403 })).rejects.toBeUndefined();
authProvider.checkError({ status: 403 })
).rejects.toBeUndefined();
}); });
}); });

View file

@ -55,8 +55,7 @@ const authProvider: AuthProvider = {
logout: async () => { logout: async () => {
console.log("logout"); console.log("logout");
const logout_api_url = const logout_api_url = localStorage.getItem("base_url") + "/_matrix/client/r0/logout";
localStorage.getItem("base_url") + "/_matrix/client/r0/logout";
const access_token = localStorage.getItem("access_token"); const access_token = localStorage.getItem("access_token");
const options: Options = { const options: Options = {
@ -84,9 +83,7 @@ const authProvider: AuthProvider = {
checkAuth: () => { checkAuth: () => {
const access_token = localStorage.getItem("access_token"); const access_token = localStorage.getItem("access_token");
console.log("checkAuth " + access_token); console.log("checkAuth " + access_token);
return typeof access_token === "string" return typeof access_token === "string" ? Promise.resolve() : Promise.reject();
? Promise.resolve()
: Promise.reject();
}, },
// called when the user navigates to a new location, to check for permissions / roles // called when the user navigates to a new location, to check for permissions / roles
getPermissions: () => Promise.resolve(), getPermissions: () => Promise.resolve(),

View file

@ -1,4 +1,5 @@
import fetchMock from "jest-fetch-mock"; import fetchMock from "jest-fetch-mock";
import dataProvider from "./dataProvider"; import dataProvider from "./dataProvider";
fetchMock.enableMocks(); fetchMock.enableMocks();
@ -45,8 +46,8 @@ describe("dataProvider", () => {
filter: { author_id: 12 }, filter: { author_id: 12 },
}); });
expect(users["data"][0]["id"]).toEqual("user_id1"); expect(users.data[0].id).toEqual("user_id1");
expect(users["total"]).toEqual(200); expect(users.total).toEqual(200);
expect(fetch).toHaveBeenCalledTimes(1); expect(fetch).toHaveBeenCalledTimes(1);
}); });
@ -74,8 +75,8 @@ describe("dataProvider", () => {
const user = await dataProvider.getOne("users", { id: "user_id1" }); const user = await dataProvider.getOne("users", { id: "user_id1" });
expect(user["data"]["id"]).toEqual("user_id1"); expect(user.data.id).toEqual("user_id1");
expect(user["data"]["displayname"]).toEqual("User"); expect(user.data.displayname).toEqual("User");
expect(fetch).toHaveBeenCalledTimes(1); expect(fetch).toHaveBeenCalledTimes(1);
}); });
}); });

View file

@ -1,13 +1,7 @@
import {
DataProvider,
DeleteParams,
Identifier,
Options,
RaRecord,
fetchUtils,
} from "react-admin";
import { stringify } from "query-string"; import { stringify } from "query-string";
import { DataProvider, DeleteParams, Identifier, Options, RaRecord, fetchUtils } from "react-admin";
// Adds the access token to all requests // Adds the access token to all requests
const jsonClient = (url: string, options: Options = {}) => { const jsonClient = (url: string, options: Options = {}) => {
const token = localStorage.getItem("access_token"); const token = localStorage.getItem("access_token");
@ -223,16 +217,12 @@ const resourceMap = {
data: "users", data: "users",
total: json => json.total, total: json => json.total,
create: (data: RaRecord) => ({ create: (data: RaRecord) => ({
endpoint: `/_synapse/admin/v2/users/@${encodeURIComponent( endpoint: `/_synapse/admin/v2/users/@${encodeURIComponent(data.id)}:${localStorage.getItem("home_server")}`,
data.id
)}:${localStorage.getItem("home_server")}`,
body: data, body: data,
method: "PUT", method: "PUT",
}), }),
delete: (params: DeleteParams) => ({ delete: (params: DeleteParams) => ({
endpoint: `/_synapse/admin/v1/deactivate/${encodeURIComponent( endpoint: `/_synapse/admin/v1/deactivate/${encodeURIComponent(params.id)}`,
params.id
)}`,
body: { erase: true }, body: { erase: true },
method: "POST", method: "POST",
}), }),
@ -272,9 +262,7 @@ const resourceMap = {
endpoint: `/_synapse/admin/v2/users/${encodeURIComponent(id)}/devices`, endpoint: `/_synapse/admin/v2/users/${encodeURIComponent(id)}/devices`,
}), }),
delete: (params: DeleteParams) => ({ delete: (params: DeleteParams) => ({
endpoint: `/_synapse/admin/v2/users/${encodeURIComponent( endpoint: `/_synapse/admin/v2/users/${encodeURIComponent(params.previousData.user_id)}/devices/${params.id}`,
params.previousData.user_id
)}/devices/${params.id}`,
}), }),
}, },
connections: { connections: {
@ -322,9 +310,7 @@ const resourceMap = {
id: jr, id: jr,
}), }),
reference: (id: Identifier) => ({ reference: (id: Identifier) => ({
endpoint: `/_synapse/admin/v1/users/${encodeURIComponent( endpoint: `/_synapse/admin/v1/users/${encodeURIComponent(id)}/joined_rooms`,
id
)}/joined_rooms`,
}), }),
data: "joined_rooms", data: "joined_rooms",
total: json => json.total, total: json => json.total,
@ -340,9 +326,7 @@ const resourceMap = {
data: "media", data: "media",
total: json => json.total, total: json => json.total,
delete: (params: DeleteParams) => ({ delete: (params: DeleteParams) => ({
endpoint: `/_synapse/admin/v1/media/${localStorage.getItem( endpoint: `/_synapse/admin/v1/media/${localStorage.getItem("home_server")}/${params.id}`,
"home_server"
)}/${params.id}`,
}), }),
}, },
delete_media: { delete_media: {
@ -369,15 +353,11 @@ const resourceMap = {
quarantine_media: { quarantine_media: {
map: (qm: UserMedia) => ({ id: qm.media_id }), map: (qm: UserMedia) => ({ id: qm.media_id }),
create: (params: UserMedia) => ({ create: (params: UserMedia) => ({
endpoint: `/_synapse/admin/v1/media/quarantine/${localStorage.getItem( endpoint: `/_synapse/admin/v1/media/quarantine/${localStorage.getItem("home_server")}/${params.media_id}`,
"home_server"
)}/${params.media_id}`,
method: "POST", method: "POST",
}), }),
delete: (params: DeleteParams) => ({ delete: (params: DeleteParams) => ({
endpoint: `/_synapse/admin/v1/media/unquarantine/${localStorage.getItem( endpoint: `/_synapse/admin/v1/media/unquarantine/${localStorage.getItem("home_server")}/${params.id}`,
"home_server"
)}/${params.id}`,
method: "POST", method: "POST",
}), }),
}, },
@ -504,15 +484,7 @@ function getSearchOrder(order: "ASC" | "DESC") {
const dataProvider: DataProvider = { const dataProvider: DataProvider = {
getList: async (resource, params) => { getList: async (resource, params) => {
console.log("getList " + resource); console.log("getList " + resource);
const { const { user_id, name, guests, deactivated, search_term, destination, valid } = params.filter;
user_id,
name,
guests,
deactivated,
search_term,
destination,
valid,
} = params.filter;
const { page, perPage } = params.pagination; const { page, perPage } = params.pagination;
const { field, order } = params.sort; const { field, order } = params.sort;
const from = (page - 1) * perPage; const from = (page - 1) * perPage;
@ -530,8 +502,7 @@ const dataProvider: DataProvider = {
dir: getSearchOrder(order), dir: getSearchOrder(order),
}; };
const homeserver = localStorage.getItem("base_url"); const homeserver = localStorage.getItem("base_url");
if (!homeserver || !(resource in resourceMap)) if (!homeserver || !(resource in resourceMap)) throw Error("Homeserver not set");
throw Error("Homeserver not set");
const res = resourceMap[resource]; const res = resourceMap[resource];
@ -548,32 +519,24 @@ const dataProvider: DataProvider = {
getOne: async (resource, params) => { getOne: async (resource, params) => {
console.log("getOne " + resource); console.log("getOne " + resource);
const homeserver = localStorage.getItem("base_url"); const homeserver = localStorage.getItem("base_url");
if (!homeserver || !(resource in resourceMap)) if (!homeserver || !(resource in resourceMap)) throw Error("Homeserver not set");
throw Error("Homeserver not set");
const res = resourceMap[resource]; const res = resourceMap[resource];
const endpoint_url = homeserver + res.path; const endpoint_url = homeserver + res.path;
const { json } = await jsonClient( const { json } = await jsonClient(`${endpoint_url}/${encodeURIComponent(params.id)}`);
`${endpoint_url}/${encodeURIComponent(params.id)}`
);
return { data: res.map(json) }; return { data: res.map(json) };
}, },
getMany: async (resource, params) => { getMany: async (resource, params) => {
console.log("getMany " + resource); console.log("getMany " + resource);
const homeserver = localStorage.getItem("base_url"); const homeserver = localStorage.getItem("base_url");
if (!homeserver || !(resource in resourceMap)) if (!homeserver || !(resource in resourceMap)) throw Error("Homerserver not set");
throw Error("Homerserver not set");
const res = resourceMap[resource]; const res = resourceMap[resource];
const endpoint_url = homeserver + res.path; const endpoint_url = homeserver + res.path;
const responses = await Promise.all( const responses = await Promise.all(params.ids.map(id => jsonClient(`${endpoint_url}/${encodeURIComponent(id)}`)));
params.ids.map(id =>
jsonClient(`${endpoint_url}/${encodeURIComponent(id)}`)
)
);
return { return {
data: responses.map(({ json }) => res.map(json)), data: responses.map(({ json }) => res.map(json)),
total: responses.length, total: responses.length,
@ -593,12 +556,11 @@ const dataProvider: DataProvider = {
}; };
const homeserver = localStorage.getItem("base_url"); const homeserver = localStorage.getItem("base_url");
if (!homeserver || !(resource in resourceMap)) if (!homeserver || !(resource in resourceMap)) throw Error("Homeserver not set");
throw Error("Homeserver not set");
const res = resourceMap[resource]; const res = resourceMap[resource];
const ref = res["reference"](params.id); const ref = res.reference(params.id);
const endpoint_url = `${homeserver}${ref.endpoint}?${stringify(query)}`; const endpoint_url = `${homeserver}${ref.endpoint}?${stringify(query)}`;
const { json } = await jsonClient(endpoint_url); const { json } = await jsonClient(endpoint_url);
@ -611,39 +573,31 @@ const dataProvider: DataProvider = {
update: async (resource, params) => { update: async (resource, params) => {
console.log("update " + resource); console.log("update " + resource);
const homeserver = localStorage.getItem("base_url"); const homeserver = localStorage.getItem("base_url");
if (!homeserver || !(resource in resourceMap)) if (!homeserver || !(resource in resourceMap)) throw Error("Homeserver not set");
throw Error("Homeserver not set");
const res = resourceMap[resource]; const res = resourceMap[resource];
const endpoint_url = homeserver + res.path; const endpoint_url = homeserver + res.path;
const { json } = await jsonClient( const { json } = await jsonClient(`${endpoint_url}/${encodeURIComponent(params.id)}`, {
`${endpoint_url}/${encodeURIComponent(params.id)}`,
{
method: "PUT", method: "PUT",
body: JSON.stringify(params.data, filterNullValues), body: JSON.stringify(params.data, filterNullValues),
} });
);
return { data: res.map(json) }; return { data: res.map(json) };
}, },
updateMany: async (resource, params) => { updateMany: async (resource, params) => {
console.log("updateMany " + resource); console.log("updateMany " + resource);
const homeserver = localStorage.getItem("base_url"); const homeserver = localStorage.getItem("base_url");
if (!homeserver || !(resource in resourceMap)) if (!homeserver || !(resource in resourceMap)) throw Error("Homeserver not set");
throw Error("Homeserver not set");
const res = resourceMap[resource]; const res = resourceMap[resource];
const endpoint_url = homeserver + res.path; const endpoint_url = homeserver + res.path;
const responses = await Promise.all( const responses = await Promise.all(
params.ids.map( params.ids.map(id => jsonClient(`${endpoint_url}/${encodeURIComponent(id)}`), {
id => jsonClient(`${endpoint_url}/${encodeURIComponent(id)}`),
{
method: "PUT", method: "PUT",
body: JSON.stringify(params.data, filterNullValues), body: JSON.stringify(params.data, filterNullValues),
} })
)
); );
return { data: responses.map(({ json }) => json) }; return { data: responses.map(({ json }) => json) };
}, },
@ -651,13 +605,12 @@ const dataProvider: DataProvider = {
create: async (resource, params) => { create: async (resource, params) => {
console.log("create " + resource); console.log("create " + resource);
const homeserver = localStorage.getItem("base_url"); const homeserver = localStorage.getItem("base_url");
if (!homeserver || !(resource in resourceMap)) if (!homeserver || !(resource in resourceMap)) throw Error("Homeserver not set");
throw Error("Homeserver not set");
const res = resourceMap[resource]; const res = resourceMap[resource];
if (!("create" in res)) return Promise.reject(); if (!("create" in res)) return Promise.reject();
const create = res["create"](params.data); const create = res.create(params.data);
const endpoint_url = homeserver + create.endpoint; const endpoint_url = homeserver + create.endpoint;
const { json } = await jsonClient(endpoint_url, { const { json } = await jsonClient(endpoint_url, {
method: create.method, method: create.method,
@ -666,14 +619,10 @@ const dataProvider: DataProvider = {
return { data: res.map(json) }; return { data: res.map(json) };
}, },
createMany: async ( createMany: async (resource: string, params: { ids: Identifier[]; data: RaRecord }) => {
resource: string,
params: { ids: Identifier[]; data: RaRecord }
) => {
console.log("createMany " + resource); console.log("createMany " + resource);
const homeserver = localStorage.getItem("base_url"); const homeserver = localStorage.getItem("base_url");
if (!homeserver || !(resource in resourceMap)) if (!homeserver || !(resource in resourceMap)) throw Error("Homeserver not set");
throw Error("Homeserver not set");
const res = resourceMap[resource]; const res = resourceMap[resource];
if (!("create" in res)) throw Error(`Create ${resource} is not allowed`); if (!("create" in res)) throw Error(`Create ${resource} is not allowed`);
@ -681,7 +630,7 @@ const dataProvider: DataProvider = {
const responses = await Promise.all( const responses = await Promise.all(
params.ids.map(id => { params.ids.map(id => {
params.data.id = id; params.data.id = id;
const cre = res["create"](params.data); const cre = res.create(params.data);
const endpoint_url = homeserver + cre.endpoint; const endpoint_url = homeserver + cre.endpoint;
return jsonClient(endpoint_url, { return jsonClient(endpoint_url, {
method: cre.method, method: cre.method,
@ -695,13 +644,12 @@ const dataProvider: DataProvider = {
delete: async (resource, params) => { delete: async (resource, params) => {
console.log("delete " + resource); console.log("delete " + resource);
const homeserver = localStorage.getItem("base_url"); const homeserver = localStorage.getItem("base_url");
if (!homeserver || !(resource in resourceMap)) if (!homeserver || !(resource in resourceMap)) throw Error("Homeserver not set");
throw Error("Homeserver not set");
const res = resourceMap[resource]; const res = resourceMap[resource];
if ("delete" in res) { if ("delete" in res) {
const del = res["delete"](params); const del = res.delete(params);
const endpoint_url = homeserver + del.endpoint; const endpoint_url = homeserver + del.endpoint;
const { json } = await jsonClient(endpoint_url, { const { json } = await jsonClient(endpoint_url, {
method: "method" in del ? del.method : "DELETE", method: "method" in del ? del.method : "DELETE",
@ -721,15 +669,14 @@ const dataProvider: DataProvider = {
deleteMany: async (resource, params) => { deleteMany: async (resource, params) => {
console.log("deleteMany " + resource); console.log("deleteMany " + resource);
const homeserver = localStorage.getItem("base_url"); const homeserver = localStorage.getItem("base_url");
if (!homeserver || !(resource in resourceMap)) if (!homeserver || !(resource in resourceMap)) throw Error("Homeserver not set");
throw Error("Homeserver not set");
const res = resourceMap[resource]; const res = resourceMap[resource];
if ("delete" in res) { if ("delete" in res) {
const responses = await Promise.all( const responses = await Promise.all(
params.ids.map(id => { params.ids.map(id => {
const del = res["delete"]({ ...params, id: id }); const del = res.delete({ ...params, id: id });
const endpoint_url = homeserver + del.endpoint; const endpoint_url = homeserver + del.endpoint;
return jsonClient(endpoint_url, { return jsonClient(endpoint_url, {
method: "method" in del ? del.method : "DELETE", method: "method" in del ? del.method : "DELETE",

View file

@ -10,22 +10,14 @@ describe("splitMxid", () => {
}); });
describe("isValidBaseUrl", () => { describe("isValidBaseUrl", () => {
it("accepts a http URL", () => it("accepts a http URL", () => expect(isValidBaseUrl("http://foo.bar")).toBeTruthy());
expect(isValidBaseUrl("http://foo.bar")).toBeTruthy()); it("accepts a https URL", () => expect(isValidBaseUrl("https://foo.bar")).toBeTruthy());
it("accepts a https URL", () => it("accepts a valid URL with port", () => expect(isValidBaseUrl("https://foo.bar:1234")).toBeTruthy());
expect(isValidBaseUrl("https://foo.bar")).toBeTruthy()); it("rejects undefined base URLs", () => expect(isValidBaseUrl(undefined)).toBeFalsy());
it("accepts a valid URL with port", () =>
expect(isValidBaseUrl("https://foo.bar:1234")).toBeTruthy());
it("rejects undefined base URLs", () =>
expect(isValidBaseUrl(undefined)).toBeFalsy());
it("rejects null base URLs", () => expect(isValidBaseUrl(null)).toBeFalsy()); it("rejects null base URLs", () => expect(isValidBaseUrl(null)).toBeFalsy());
it("rejects empty base URLs", () => expect(isValidBaseUrl("")).toBeFalsy()); it("rejects empty base URLs", () => expect(isValidBaseUrl("")).toBeFalsy());
it("rejects non-string base URLs", () => it("rejects non-string base URLs", () => expect(isValidBaseUrl({})).toBeFalsy());
expect(isValidBaseUrl({})).toBeFalsy()); it("rejects base URLs without protocol", () => expect(isValidBaseUrl("foo.bar")).toBeFalsy());
it("rejects base URLs without protocol", () => it("rejects base URLs with path", () => expect(isValidBaseUrl("http://foo.bar/path")).toBeFalsy());
expect(isValidBaseUrl("foo.bar")).toBeFalsy()); it("rejects invalid base URLs", () => expect(isValidBaseUrl("http:/foo.bar")).toBeFalsy());
it("rejects base URLs with path", () =>
expect(isValidBaseUrl("http://foo.bar/path")).toBeFalsy());
it("rejects invalid base URLs", () =>
expect(isValidBaseUrl("http:/foo.bar")).toBeFalsy());
}); });

View file

@ -1,13 +1,11 @@
import { fetchUtils } from "react-admin"; import { fetchUtils } from "react-admin";
export const splitMxid = mxid => { export const splitMxid = mxid => {
const re = const re = /^@(?<name>[a-zA-Z0-9._=\-/]+):(?<domain>[a-zA-Z0-9\-.]+\.[a-zA-Z]+)$/;
/^@(?<name>[a-zA-Z0-9._=\-/]+):(?<domain>[a-zA-Z0-9\-.]+\.[a-zA-Z]+)$/;
return re.exec(mxid)?.groups; return re.exec(mxid)?.groups;
}; };
export const isValidBaseUrl = baseUrl => export const isValidBaseUrl = baseUrl => /^(http|https):\/\/[a-zA-Z0-9\-.]+(:\d{1,5})?$/.test(baseUrl);
/^(http|https):\/\/[a-zA-Z0-9\-.]+(:\d{1,5})?$/.test(baseUrl);
/** /**
* Resolve the homeserver URL using the well-known lookup * Resolve the homeserver URL using the well-known lookup
@ -77,8 +75,7 @@ export function generateRandomMxId(): string {
* @returns a new random password as string * @returns a new random password as string
*/ */
export function generateRandomPassword(length = 20): string { export function generateRandomPassword(length = 20): string {
const characters = const characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~!@-#$";
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~!@-#$";
return Array.from(crypto.getRandomValues(new Uint32Array(length))) return Array.from(crypto.getRandomValues(new Uint32Array(length)))
.map(x => characters[x % characters.length]) .map(x => characters[x % characters.length])
.join(""); .join("");

View file

@ -1,7 +1,8 @@
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { vitePluginVersionMark } from "vite-plugin-version-mark"; import { vitePluginVersionMark } from "vite-plugin-version-mark";
import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";
export default defineConfig({ export default defineConfig({
plugins: [ plugins: [
react(), react(),

2067
yarn.lock

File diff suppressed because it is too large Load diff