|
| 1 | +import dataclasses |
1 | 2 | import enum |
| 3 | +import functools |
2 | 4 | import typing |
3 | 5 |
|
4 | 6 | import boto3 |
5 | | -import chalicelib.config |
| 7 | +import chalicelib.config as config_module |
6 | 8 |
|
7 | 9 | if typing.TYPE_CHECKING: |
8 | 10 | import mypy_boto3_s3.client |
|
15 | 17 | s3_client: "mypy_boto3_s3.client.S3Client" = boto3.client(service_name="s3") |
16 | 18 |
|
17 | 19 |
|
18 | | -class S3ResourcePath(enum.StrEnum): |
19 | | - email_template = "email/template/{filename}.html" |
| 20 | +@dataclasses.dataclass |
| 21 | +class S3ResourceInfo: |
| 22 | + prefix: str |
| 23 | + extension: str |
20 | 24 |
|
21 | | - def as_path(self, filename: str) -> str: |
22 | | - return self.value.format(filename=filename) |
| 25 | + def as_path(self, code: str) -> str: |
| 26 | + return self.prefix + f"{code}.{self.extension}" |
23 | 27 |
|
24 | | - def download(self, conf: chalicelib.config.Config, filename: str) -> bytes: |
25 | | - return s3_client.get_object(Bucket=conf.infra.s3_bucket_name, Key=self.as_path(filename))["Body"].read() |
| 28 | + |
| 29 | +class S3ResourcePath(enum.Enum): |
| 30 | + email_template = S3ResourceInfo(prefix="email/template/", extension="json") |
| 31 | + telegram_template = S3ResourceInfo(prefix="telegram/template/", extension="json") |
| 32 | + firebase_template = S3ResourceInfo(prefix="firebase/template/", extension="json") |
| 33 | + |
| 34 | + @functools.cached_property |
| 35 | + def s3_bucket_name(self) -> config_module.InfraConfig: |
| 36 | + return config_module.config.infra.s3_bucket_name |
| 37 | + |
| 38 | + def download(self, code: str) -> bytes: |
| 39 | + return s3_client.get_object(Bucket=self.s3_bucket_name, Key=self.value.as_path(code))["Body"].read() |
| 40 | + |
| 41 | + def upload(self, code: str, content: str) -> None: |
| 42 | + s3_client.put_object(Bucket=self.s3_bucket_name, Key=self.value.as_path(code), Body=content) |
| 43 | + |
| 44 | + def delete(self, code: str) -> None: |
| 45 | + s3_client.delete_object(Bucket=self.s3_bucket_name, Key=self.value.as_path(code)) |
| 46 | + |
| 47 | + def list_objects(self, filter_by_extension: bool = False) -> list[str]: |
| 48 | + return [ |
| 49 | + key |
| 50 | + for obj in s3_client.list_objects(Bucket=self.s3_bucket_name, Prefix=self.value.prefix)["Contents"] |
| 51 | + if (key := obj["Key"].replace(self.value.prefix, "")) |
| 52 | + and (not filter_by_extension or key.split(".")[-1] == self.value.extension) |
| 53 | + ] |
0 commit comments