2021-02-03 18:44:33 +01:00
|
|
|
import * as fet from "node-fetch";
|
|
|
|
|
2021-06-07 19:25:55 +02:00
|
|
|
import { CryptoService } from "jslib-common/abstractions/crypto.service";
|
2021-02-03 18:44:33 +01:00
|
|
|
|
2021-06-07 19:25:55 +02:00
|
|
|
import { SymmetricCryptoKey } from "jslib-common/models/domain/symmetricCryptoKey";
|
2021-02-03 18:44:33 +01:00
|
|
|
|
2021-06-07 19:25:55 +02:00
|
|
|
import { Response } from "jslib-node/cli/models/response";
|
2022-01-19 16:45:14 +01:00
|
|
|
import { FileResponse } from "jslib-node/cli/models/response/fileResponse";
|
2021-02-03 18:44:33 +01:00
|
|
|
|
|
|
|
import { CliUtils } from "../utils";
|
|
|
|
|
|
|
|
export abstract class DownloadCommand {
|
|
|
|
constructor(protected cryptoService: CryptoService) {}
|
|
|
|
|
|
|
|
protected async saveAttachmentToFile(
|
|
|
|
url: string,
|
|
|
|
key: SymmetricCryptoKey,
|
|
|
|
fileName: string,
|
|
|
|
output?: string
|
|
|
|
) {
|
|
|
|
const response = await fet.default(new fet.Request(url, { headers: { cache: "no-cache" } }));
|
|
|
|
if (response.status !== 200) {
|
|
|
|
return Response.error(
|
|
|
|
"A " + response.status + " error occurred while downloading the attachment."
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
|
|
|
const buf = await response.arrayBuffer();
|
|
|
|
const decBuf = await this.cryptoService.decryptFromBytes(buf, key);
|
2022-01-19 16:45:14 +01:00
|
|
|
if (process.env.BW_SERVE === "true") {
|
|
|
|
const res = new FileResponse(Buffer.from(decBuf), fileName);
|
|
|
|
return Response.success(res);
|
|
|
|
} else {
|
|
|
|
return await CliUtils.saveResultToFile(Buffer.from(decBuf), output, fileName);
|
|
|
|
}
|
2021-02-03 18:44:33 +01:00
|
|
|
} catch (e) {
|
|
|
|
if (typeof e === "string") {
|
|
|
|
return Response.error(e);
|
|
|
|
} else {
|
|
|
|
return Response.error("An error occurred while saving the attachment.");
|
|
|
|
}
|
|
|
|
}
|
2021-12-20 18:04:00 +01:00
|
|
|
}
|
2021-02-03 18:44:33 +01:00
|
|
|
}
|