From a65f5eb00438d2a79b4bfc6797eecbe55d9b76bf Mon Sep 17 00:00:00 2001 From: fyears Date: Sun, 7 Nov 2021 15:29:18 +0800 Subject: [PATCH] head bucket --- src/main.ts | 28 +++++++++++++++++++++++++++- src/s3.ts | 29 +++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 1 deletion(-) diff --git a/src/main.ts b/src/main.ts index 54fae64..dead1c1 100644 --- a/src/main.ts +++ b/src/main.ts @@ -24,7 +24,13 @@ import { import type { SyncStatusType } from "./sync"; import { getSyncPlan, doActualSync } from "./sync"; -import { DEFAULT_S3_CONFIG, getS3Client, listFromRemote, S3Config } from "./s3"; +import { + DEFAULT_S3_CONFIG, + getS3Client, + listFromRemote, + S3Config, + checkS3Connectivity, +} from "./s3"; import { exportSyncPlansToFiles } from "./debugMode"; interface SaveRemotePluginSettings { @@ -247,6 +253,26 @@ class SaveRemoteSettingTab extends PluginSettingTab { }) ); + new Setting(containerEl) + .setName("check connectivity") + .setDesc("check connectivity") + .addButton(async (button) => { + button.setButtonText("Check"); + button.onClick(async () => { + new Notice("Checking..."); + const s3Client = getS3Client(this.plugin.settings.s3); + const res = await checkS3Connectivity( + s3Client, + this.plugin.settings.s3 + ); + if (res) { + new Notice("Great! The bucket can be accessed."); + } else { + new Notice("The S3 bucket cannot be reached."); + } + }); + }); + containerEl.createEl("h2", { text: "General" }); new Setting(containerEl) .setName("encryption password") diff --git a/src/s3.ts b/src/s3.ts index e26e986..44aedf1 100644 --- a/src/s3.ts +++ b/src/s3.ts @@ -10,6 +10,7 @@ import { GetObjectCommand, DeleteObjectCommand, HeadObjectCommand, + HeadBucketCommand, } from "@aws-sdk/client-s3"; import type { _Object } from "@aws-sdk/client-s3"; @@ -266,3 +267,31 @@ export const deleteFromRemote = async ( // pass } }; + +/** + * Check the config of S3 by heading bucket + * https://stackoverflow.com/questions/50842835 + * @param s3Client + * @param s3Config + * @returns + */ +export const checkS3Connectivity = async ( + s3Client: S3Client, + s3Config: S3Config +) => { + try { + const results = await s3Client.send( + new HeadBucketCommand({ Bucket: s3Config.s3BucketName }) + ); + if ( + results === undefined || + results.$metadata === undefined || + results.$metadata.httpStatusCode === undefined + ) { + return false; + } + return results.$metadata.httpStatusCode === 200; + } catch (err) { + return false; + } +};