-
Notifications
You must be signed in to change notification settings - Fork 3
/
app.py
171 lines (141 loc) · 5.76 KB
/
app.py
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
import dataclasses
import os
import boto3
import botocore
import humanize
from flask import Flask, Response, redirect, render_template, request
app = Flask(__name__)
app.secret_key = "your_secure_random_key_here" # noqa: S105
AWS_ACCESS_KEY_ID = os.getenv("AWS_ACCESS_KEY_ID")
AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_ACCESS_KEY")
AWS_DEFAULT_REGION = os.getenv("AWS_DEFAULT_REGION", "eu-central-1")
AWS_ENDPOINT_URL = os.getenv("AWS_ENDPOINT_URL", None)
AWS_KWARGS = {
"aws_access_key_id": AWS_ACCESS_KEY_ID,
"aws_secret_access_key": AWS_SECRET_ACCESS_KEY,
"region_name": AWS_DEFAULT_REGION,
}
if AWS_ENDPOINT_URL:
AWS_KWARGS["endpoint_url"] = AWS_ENDPOINT_URL
@app.route("/", methods=["GET"])
def index() -> str:
s3 = boto3.resource("s3", **AWS_KWARGS)
all_buckets = s3.buckets.all()
return render_template("index.html", buckets=all_buckets)
@app.route("/buckets")
def buckets() -> str:
s3 = boto3.resource("s3", **AWS_KWARGS)
all_buckets = s3.buckets.all()
return render_template("index.html", buckets=all_buckets)
@dataclasses.dataclass(eq=True, frozen=True)
class S3Entry:
"""Representation of S3 object."""
name: str
type: str
size: str = ""
date_modified: str = ""
def parse_responses(responses: list, search_param: str) -> list[S3Entry]:
contents: set[S3Entry] = set()
for response in responses:
# Add folders to contents
if "CommonPrefixes" in response:
for item in response["CommonPrefixes"]:
contents.add(S3Entry(name=item["Prefix"], type="folder"))
# Add files to contents
if "Contents" in response:
for item in response["Contents"]:
if not item["Key"].endswith("/"):
contents.add(
S3Entry(
name=item["Key"],
type="file",
size=humanize.naturalsize(item["Size"]),
date_modified=item["LastModified"])
)
contents_list = list(contents)
if search_param:
contents_list = list(filter(lambda x: search_param in x.name, contents_list))
return sorted(contents_list, key=lambda x: x.type, reverse=True)
def list_objects(s3_client: botocore.client.BaseClient, bucket_name: str, path: str, delimiter: str = "") -> list[dict]:
responses = []
list_params = {"Bucket": bucket_name, "Prefix": path}
if delimiter:
list_params["Delimiter"] = "/"
while True:
response = s3_client.list_objects_v2(**list_params)
responses.append(response)
if response["IsTruncated"]:
list_params["ContinuationToken"] = response["NextContinuationToken"]
else:
break
return responses
@app.route("/search/buckets/<bucket_name>", defaults={"path": ""})
@app.route("/search/buckets/<bucket_name>/<path:path>")
def search_bucket(bucket_name: str, path: str) -> str:
s3_client = boto3.client("s3", **AWS_KWARGS)
responses = []
try:
responses.extend(list_objects(s3_client, bucket_name, path))
responses.extend(list_objects(s3_client, bucket_name, path, "/"))
except botocore.exceptions.ClientError as e:
match e.response["Error"]["Code"]:
case "AccessDenied":
return render_template(
"error.html",
error="You do not have permission to access this bucket.",
)
case "NoSuchBucket":
return render_template("error.html", error="The specified bucket does not exist.")
case _:
return render_template("error.html", error=f"An unknown error occurred: {e}")
except Exception as e: # noqa: BLE001
return render_template("error.html", error=f"An unknown error occurred: {e}")
search_param = request.args.get("search", "")
contents = parse_responses(responses, search_param)
return render_template(
"bucket_contents.html",
contents=contents,
bucket_name=bucket_name,
path=path,
search_param=search_param,
)
@app.route("/buckets/<bucket_name>", defaults={"path": ""})
@app.route("/buckets/<bucket_name>/<path:path>")
def view_bucket(bucket_name: str, path: str) -> str:
s3_client = boto3.client("s3", **AWS_KWARGS)
responses = []
try:
responses.extend(list_objects(s3_client, bucket_name, path, "/"))
except botocore.exceptions.ClientError as e:
match e.response["Error"]["Code"]:
case "AccessDenied":
return render_template(
"error.html",
error="You do not have permission to access this bucket.",
)
case "NoSuchBucket":
return render_template("error.html", error="The specified bucket does not exist.")
case _:
return render_template("error.html", error=f"An unknown error occurred: {e}")
except Exception as e: # noqa: BLE001
return render_template("error.html", error=f"An unknown error occurred: {e}")
search_param = request.args.get("search", "")
contents = parse_responses(responses, search_param)
return render_template(
"bucket_contents.html",
contents=contents,
bucket_name=bucket_name,
path=path,
search_param=search_param,
)
@app.route("/download/buckets/<bucket_name>/<path:path>")
def download_file(bucket_name: str, path: str) -> Response:
s3_client = boto3.client("s3", **AWS_KWARGS)
url = s3_client.generate_presigned_url(
"get_object",
Params={"Bucket": bucket_name, "Key": path},
ExpiresIn=3600,
) # URL expires in 1 hour
return redirect(url)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000) # noqa: S104