All files / src/components ImportFeature.tsx

88.88% Statements 160/180
80.31% Branches 102/127
90.47% Functions 19/21
89.69% Lines 148/165

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535                                      2x   2x     28x 28x                                                                                                   2x         10x   5x 1x 1x     4x                     4x 4x 4x 3x   1x     4x 1x   4x 1x   4x 1x     4x 12x 1x 1x   11x 4x             11x       4x 3x     4x 1x     4x 4x       4x 2x   4x 4x   4x     2x                 4x 4x 4x 4x             4x 4x 4x 4x 4x 4x 4x 1x   4x 4x     4x 4x 4x   3x   3x 2x 1x 1x                                     1x   1x     1x         4x 3x 3x     3x   1x           1x   4x                   2x 16x 16x 16x 16x   16x   16x 16x   16x 16x 16x   16x 16x   16x   16x 4x   4x 4x 4x 4x 4x 4x     4x 1x     1x 1x 1x   3x 3x       3x 3x       3x                 16x 1x         1x                 1x       1x 1x 1x           16x 1x 1x 1x     1x 1x 1x 1x     16x 1x       1x 1x     16x               16x 1x       1x 1x     16x 1x     1x         16x                                                                                                           16x                           16x         4x           16x                         16x                                                         16x                                 16x 16x 16x 16x 16x 16x 16x   16x   16x     2x  
import { parse as parseCsv, unparse as unparseCsv, ParseResult } from "papaparse";
import { ChangeEvent, ReactElement, useState } from "react";
 
import {
  Button,
  Card,
  CardActions,
  CardContent,
  CardHeader,
  Checkbox,
  Container,
  FormControlLabel,
  NativeSelect,
} from "@mui/material";
import { DataProvider, useTranslate } from "ra-core";
import { useDataProvider, useNotify, RaRecord, Title } from "react-admin";
 
import { generateRandomMxId, generateRandomPassword } from "../synapse/synapse";
 
const LOGGING = true;
 
const expectedFields = ["id", "displayname"].sort();
 
function TranslatableOption({ value, text }) {
  const translate = useTranslate();
  return <option value={value}>{translate(text)}</option>;
}
 
type Progress = {
  done: number;
  limit: number;
} | null;
 
interface ImportLine {
  id: string;
  displayname: string;
  user_type?: string;
  name?: string;
  deactivated?: boolean;
  guest?: boolean;
  admin?: boolean;
  is_admin?: boolean;
  password?: string;
  avatar_url?: string;
}
 
interface ChangeStats {
  total: number;
  id: number;
  is_guest: number;
  admin: number;
  password: number;
}
 
interface ImportResult {
  skippedRecords: RaRecord[];
  erroredRecords: RaRecord[];
  succeededRecords: RaRecord[];
  totalRecordCount: number;
  changeStats: ChangeStats;
  wasDryRun: boolean;
}
 
type VerifyCsvHandlers = {
  setError: (message: string | string[]) => void;
  setStats: (stats: ChangeStats & Record<string, unknown>) => void;
  setValues: (values: ImportLine[]) => void;
};
 
type DoImportHandlers = {
  setError: (message: string) => void;
  setProgress: (progress: Progress) => void;
  translate: (key: string, options?: Record<string, unknown>) => string;
};
 
export const verifyImportCsv = (
  { data, meta, errors }: ParseResult<ImportLine>,
  { setValues, setStats, setError, translate }: VerifyCsvHandlers & Pick<DoImportHandlers, "translate">
) => {
  /* First, verify the presence of required fields */
  const missingFields = expectedFields.filter(eF => !meta.fields?.includes(eF));
 
  if (missingFields.length > 0) {
    setError(translate("import_users.error.required_field", { field: missingFields[0] }));
    return false;
  }
 
  const stats = {
    user_types: { default: 0 },
    is_guest: 0,
    admin: 0,
    deactivated: 0,
    password: 0,
    avatar_url: 0,
    id: 0,
    total: data.length,
  };
 
  const errorMessages = errors.map(e => e.message);
  data.forEach((line, idx) => {
    if (line.user_type === undefined || line.user_type === "") {
      stats.user_types.default++;
    } else {
      stats.user_types[line.user_type] += 1;
    }
 
    if (meta.fields?.includes("name")) {
      delete line.name;
    }
    if (meta.fields?.includes("user_type")) {
      delete line.user_type;
    }
    if (meta.fields?.includes("is_admin")) {
      delete line.is_admin;
    }
 
    ["is_guest", "admin", "deactivated"].forEach(f => {
      if (line[f] === "true") {
        stats[f]++;
        line[f] = true;
      } else {
        if (line[f] !== "false" && line[f] !== "") {
          errorMessages.push(
            translate("import_users.error.invalid_value", {
              field: f,
              row: idx,
            })
          );
        }
        line[f] = false;
      }
    });
 
    if (line.password !== undefined && line.password !== "") {
      stats.password++;
    }
 
    if (line.avatar_url !== undefined && line.avatar_url !== "") {
      stats.avatar_url++;
    }
 
    Eif (line.id !== undefined && line.id !== "") {
      stats.id++;
    }
  });
 
  if (errorMessages.length > 0) {
    setError(errorMessages);
  }
  setStats(stats);
  setValues(data);
 
  return true;
};
 
export const doUserImport = async (
  dataProvider: DataProvider,
  data: ImportLine[],
  conflictMode: string,
  passwordMode: boolean,
  useridMode: string,
  dryRun: boolean,
  { setProgress, setError, translate }: DoImportHandlers
): Promise<ImportResult> => {
  const skippedRecords: ImportLine[] = [];
  const erroredRecords: ImportLine[] = [];
  const succeededRecords: ImportLine[] = [];
  const changeStats: ChangeStats = {
    total: 0,
    id: 0,
    is_guest: 0,
    admin: 0,
    password: 0,
  };
  let entriesDone = 0;
  const entriesCount = data.length;
  try {
    setProgress({ done: entriesDone, limit: entriesCount });
    for (const entry of data) {
      const userRecord = { ...entry };
      if (useridMode === "ignore" || userRecord.id === undefined) {
        userRecord.id = generateRandomMxId();
      }
      Eif (passwordMode === false || entry.password === undefined) {
        userRecord.password = generateRandomPassword();
      }
 
      let retries = 0;
      const submitRecord = (recordData: ImportLine): Promise<void> => {
        return dataProvider.getOne("users", { id: recordData.id }).then(
          async () => {
            Eif (LOGGING) console.log("already existed");
 
            if (useridMode === "update" || conflictMode === "skip") {
              skippedRecords.push(recordData);
            } else if (conflictMode === "stop") {
              throw new Error(
                translate("import_users.error.id_exists", {
                  id: recordData.id,
                })
              );
            } else E{
              const newRecordData = Object.assign({}, recordData, {
                id: generateRandomMxId(),
              });
              retries++;
              if (retries > 512) {
                console.warn("retry loop got stuck? pathological situation?");
                skippedRecords.push(recordData);
              } else {
                await submitRecord(newRecordData);
              }
            }
          },
          async () => {
            Eif (LOGGING) console.log("OK to create record " + recordData.id + " (" + recordData.displayname + ").");
 
            Iif (!dryRun) {
              await dataProvider.create("users", { data: recordData });
            }
            succeededRecords.push(recordData);
          }
        );
      };
 
      await submitRecord(userRecord);
      entriesDone++;
      setProgress({ done: entriesDone, limit: data.length });
    }
 
    setProgress(null);
  } catch (e) {
    setError(
      translate("import_users.error.at_entry", {
        entry: entriesDone + 1,
        message: e instanceof Error ? e.message : String(e),
      })
    );
    setProgress(null);
  }
  return {
    skippedRecords,
    erroredRecords,
    succeededRecords,
    totalRecordCount: entriesCount,
    changeStats,
    wasDryRun: dryRun,
  };
};
 
const FilePicker = () => {
  const [values, setValues] = useState<ImportLine[]>([]);
  const [error, setError] = useState<string | string[] | null>(null);
  const [stats, setStats] = useState<ChangeStats | null>(null);
  const [dryRun, setDryRun] = useState(true);
 
  const [progress, setProgress] = useState<Progress>(null);
 
  const [importResults, setImportResults] = useState<ImportResult | null>(null);
  const [skippedRecords, setSkippedRecords] = useState<string>("");
 
  const [conflictMode, setConflictMode] = useState("stop");
  const [passwordMode, setPasswordMode] = useState(true);
  const [useridMode, setUseridMode] = useState("ignore");
 
  const translate = useTranslate();
  const notify = useNotify();
 
  const dataProvider = useDataProvider();
 
  const onFileChange = async (e: ChangeEvent<HTMLInputElement>) => {
    Iif (progress !== null) return;
 
    setValues([]);
    setError(null);
    setStats(null);
    setImportResults(null);
    const file = e.target.files ? e.target.files[0] : null;
    Iif (!file) return;
    /* Let's refuse some unreasonably big files instead of freezing
     * up the browser */
    if (file.size > 100000000) {
      const message = translate("import_users.errors.unreasonably_big", {
        size: (file.size / (1024 * 1024)).toFixed(2),
      });
      notify(message);
      setError(message);
      return;
    }
    try {
      parseCsv<ImportLine>(file, {
        header: true,
        skipEmptyLines: true /* especially for a final EOL in the csv file */,
        complete: result => {
          Eif (result.errors) {
            setError(result.errors.map(e => e.toString()));
          }
          /* Papaparse is very lenient, we may be able to salvage
           * the data in the file. */
          verifyImportCsv(result, { setValues, setStats, setError, translate });
        },
      });
    } catch {
      setError("Unknown error");
      return null;
    }
  };
 
  const runImport = async () => {
    Iif (progress !== null) {
      notify("import_users.errors.already_in_progress");
      return;
    }
 
    const results = await doUserImport(
      dataProvider,
      values,
      conflictMode,
      passwordMode,
      useridMode,
      dryRun,
      { setProgress, setError, translate }
    );
    setImportResults(results);
    // offer CSV download of skipped or errored records
    // (so that the user doesn't have to filter out successful
    // records manually when fixing stuff in the CSV)
    setSkippedRecords(unparseCsv(results.skippedRecords));
    Eif (LOGGING) console.log("Skipped records:");
    Eif (LOGGING) console.log(skippedRecords);
  };
 
  // XXX every single one of the requests will restart the activity indicator
  //     which doesn't look very good.
 
  const downloadSkippedRecords = () => {
    const element = document.createElement("a");
    console.log(skippedRecords);
    const file = new Blob([skippedRecords], {
      type: "text/comma-separated-values",
    });
    element.href = URL.createObjectURL(file);
    element.download = "skippedRecords.csv";
    document.body.appendChild(element); // Required for this to work in FireFox
    element.click();
  };
 
  const onConflictModeChanged = async (e: ChangeEvent<HTMLSelectElement>) => {
    Iif (progress !== null) {
      return;
    }
 
    const value = e.target.value;
    setConflictMode(value);
  };
 
  const onPasswordModeChange = (e: ChangeEvent<HTMLInputElement>) => {
    if (progress !== null) {
      return;
    }
 
    setPasswordMode(e.target.checked);
  };
 
  const onUseridModeChanged = async (e: ChangeEvent<HTMLSelectElement>) => {
    Iif (progress !== null) {
      return;
    }
 
    const value = e.target.value;
    setUseridMode(value);
  };
 
  const onDryRunModeChanged = (e: ChangeEvent<HTMLInputElement>) => {
    Iif (progress !== null) {
      return;
    }
    setDryRun(e.target.checked);
  };
 
  // render individual small components
 
  const statsCards = stats &&
    !importResults && [
      <Container>
        <CardHeader title={translate("import_users.cards.importstats.header")} />
        <CardContent>
          <div>{translate("import_users.cards.importstats.users_total", stats.total)}</div>
          <div>{translate("import_users.cards.importstats.guest_count", stats.is_guest)}</div>
          <div>{translate("import_users.cards.importstats.admin_count", stats.admin)}</div>
        </CardContent>
      </Container>,
      <Container>
        <CardHeader title={translate("import_users.cards.ids.header")} />
        <CardContent>
          <div>
            {stats.id === stats.total
              ? translate("import_users.cards.ids.all_ids_present")
              : translate("import_users.cards.ids.count_ids_present", stats.id)}
          </div>
          {stats.id > 0 ? (
            <div>
              <NativeSelect onChange={onUseridModeChanged} value={useridMode} disabled={progress !== null}>
                <TranslatableOption value="ignore" text="import_users.cards.ids.mode.ignore" />
                <TranslatableOption value="update" text="import_users.cards.ids.mode.update" />
              </NativeSelect>
            </div>
          ) : (
            ""
          )}
        </CardContent>
      </Container>,
      <Container>
        <CardHeader title={translate("import_users.cards.passwords.header")} />
        <CardContent>
          <div>
            {stats.password === stats.total
              ? translate("import_users.cards.passwords.all_passwords_present")
              : translate("import_users.cards.passwords.count_passwords_present", stats.password)}
          </div>
          {stats.password > 0 ? (
            <div>
              <FormControlLabel
                control={
                  <Checkbox checked={passwordMode} disabled={progress !== null} onChange={onPasswordModeChange} />
                }
                label={translate("import_users.cards.passwords.use_passwords")}
              />
            </div>
          ) : (
            ""
          )}
        </CardContent>
      </Container>,
    ];
 
  const conflictCards = stats && !importResults && (
    <Container>
      <CardHeader title={translate("import_users.cards.conflicts.header")} />
      <CardContent>
        <div>
          <NativeSelect onChange={onConflictModeChanged} value={conflictMode} disabled={progress !== null}>
            <TranslatableOption value="stop" text="import_users.cards.conflicts.mode.stop" />
            <TranslatableOption value="skip" text="import_users.cards.conflicts.mode.skip" />
          </NativeSelect>
        </div>
      </CardContent>
    </Container>
  );
 
  const errorCards = error && (
    <Container>
      <CardHeader title={translate("import_users.error.error")} />
      <CardContent>
        {(Array.isArray(error) ? error : [error]).map(e => (
          <div>{e}</div>
        ))}
      </CardContent>
    </Container>
  );
 
  const uploadCard = !importResults && (
    <Container>
      <CardHeader title={translate("import_users.cards.upload.header")} />
      <CardContent>
        {translate("import_users.cards.upload.explanation")}
        <a href="./data/example.csv">example.csv</a>
        <br />
        <br />
        <input type="file" onChange={onFileChange} disabled={progress !== null} />
      </CardContent>
    </Container>
  );
 
  const resultsCard = importResults && (
    <CardContent>
      <CardHeader title={translate("import_users.cards.results.header")} />
      <div>
        {translate("import_users.cards.results.total", importResults.totalRecordCount)}
        <br />
        {translate("import_users.cards.results.successful", importResults.succeededRecords.length)}
        <br />
        {importResults.skippedRecords.length
          ? [
              translate("import_users.cards.results.skipped", importResults.skippedRecords.length),
              <div>
                <button onClick={downloadSkippedRecords}>
                  {translate("import_users.cards.results.download_skipped")}
                </button>
              </div>,
              <br />,
            ]
          : ""}
        {importResults.erroredRecords.length
          ? [translate("import_users.cards.results.skipped", importResults.erroredRecords.length), <br />]
          : ""}
        <br />
        {importResults.wasDryRun && [translate("import_users.cards.results.simulated_only"), <br />]}
      </div>
    </CardContent>
  );
 
  const startImportCard =
    !values || values.length === 0 || importResults ? undefined : (
      <CardActions>
        <FormControlLabel
          control={<Checkbox checked={dryRun} onChange={onDryRunModeChanged} disabled={progress !== null} />}
          label={translate("import_users.cards.startImport.simulate_only")}
        />
        <Button size="large" onClick={runImport} disabled={progress !== null}>
          {translate("import_users.cards.startImport.run_import")}
        </Button>
        {progress !== null ? (
          <div>
            {progress.done} of {progress.limit} done
          </div>
        ) : null}
      </CardActions>
    );
 
  const allCards: ReactElement[] = [];
  if (uploadCard) allCards.push(uploadCard);
  if (errorCards) allCards.push(errorCards);
  if (conflictCards) allCards.push(conflictCards);
  if (statsCards) allCards.push(...statsCards);
  if (startImportCard) allCards.push(startImportCard);
  if (resultsCard) allCards.push(resultsCard);
 
  const cardContainer = <Card>{allCards}</Card>;
 
  return [<Title defaultTitle={translate("import_users.title")} />, cardContainer];
};
 
export const ImportFeature = FilePicker;