forked from flightlesstux/S3-Directory-Listing
-
Notifications
You must be signed in to change notification settings - Fork 0
/
s3.js
259 lines (210 loc) · 7.58 KB
/
s3.js
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
// S3 bucket name
const bucketName = 's3-directory-listing';
const s3Domain = 's3.amazonaws.com';
const objectList = document.getElementById('object-list');
const breadcrumb = document.getElementById('breadcrumb');
const searchInput = document.getElementById('search');
const loading = document.getElementById('loading');
const errorAlert = document.getElementById('error');
const itemsPerPage = 10;
let totalPages = 0;
let currentPage = 1;
let currentPath = '';
function isFolder(key) {
return key.endsWith('/');
}
function createDownloadLink(key) {
const url = `https://${bucketName}.${s3Domain}/${key}`;
const link = document.createElement('a');
link.href = url;
// Create the icon element
const icon = document.createElement('i');
icon.className = isFolder(key) ? 'fas fa-folder mr-2' : 'fas fa-file mr-2';
// Create the span element to hold the text
const textSpan = document.createElement('span');
if (isFolder(key)) {
textSpan.textContent = key.slice(0, -1).split('/').pop();
} else {
textSpan.textContent = key.split('/').pop();
link.setAttribute('download', '');
}
// Append the icon and the text span to the link
link.appendChild(icon);
link.appendChild(textSpan);
return link;
}
function navigateTo(path) {
currentPath = path;
listObjects(currentPath);
}
function updateBreadcrumb(path) {
const parts = path.split('/').filter((part) => part);
let crumbPath = '';
breadcrumb.innerHTML = '<li class="breadcrumb-item"><a href="#">Home</a></li>';
parts.forEach((part, index) => {
crumbPath += part + '/';
const listItem = document.createElement('li');
listItem.className = 'breadcrumb-item';
if (index === parts.length - 1) {
listItem.textContent = part;
listItem.classList.add('active');
} else {
const link = document.createElement('a');
link.href = '#';
link.textContent = part;
let thisCrumbPath = crumbPath;
link.onclick = (e) => {
e.preventDefault();
navigateTo(thisCrumbPath);
}
listItem.appendChild(link);
}
breadcrumb.appendChild(listItem);
});
}
function formatSize(size) {
if (isNaN(size)) {
return 'Unknown';
}
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
let index;
for (index = 0; size >= 1024 && index < units.length - 1; index++) {
size /= 1024;
}
return `${size.toFixed(2)} ${units[index]}`;
}
function listObjects(path) {
const prefix = path ? `prefix=${path}&` : '';
const url = `https://${bucketName}.${s3Domain}/?list-type=2&${prefix}delimiter=%2F`;
loading.classList.remove('d-none');
errorAlert.classList.add('d-none');
fetch(url)
.then((response) => {
if (!response.ok) {
throw new Error(`Error fetching objects: ${response.status}`);
}
return response.text();
})
.then((text) => {
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(text, 'text/xml');
const keys = xmlDoc.getElementsByTagName('Key');
const prefixes = xmlDoc.getElementsByTagName('Prefix');
// Pagination logic
const startIndex = (currentPage - 1) * itemsPerPage;
const endIndex = startIndex + itemsPerPage;
// Slice the items based on pagination
const displayedPrefixes = Array.from(prefixes).slice(startIndex, endIndex);
const displayedKeys = Array.from(keys).slice(startIndex, endIndex - displayedPrefixes.length);
totalItems = prefixes.length + keys.length;
totalPages = Math.ceil(totalItems / itemsPerPage);
const nextContinuationToken = xmlDoc.querySelector('NextContinuationToken') ? xmlDoc.querySelector('NextContinuationToken').textContent : null;
if (nextContinuationToken) {
// Enable the "Next" button since there are more items to fetch
document.getElementById('nextPage').addEventListener('click', function() {
listObjects(currentPath, nextContinuationToken);
});
} else {
document.getElementById('nextPage').disabled = true;
}
objectList.innerHTML = '';
displayedPrefixes.forEach((prefix) => {
const key = prefix.textContent;
if (key === path) {
return;
}
const row = document.createElement('tr');
const nameCell = document.createElement('td');
const link = createDownloadLink(key);
link.onclick = (e) => {
e.preventDefault();
navigateTo(key);
};
nameCell.appendChild(link);
row.appendChild(nameCell);
row.insertCell(-1).textContent = ''; // Empty cells for last modified and size
row.insertCell(-1).textContent = '';
objectList.appendChild(row);
});
displayedKeys.forEach((keyElement) => {
const key = keyElement.textContent;
if (key === 'index.html' || key === 's3.js' || key === 'dark-mode.css') {
return;
}
const lastModified = new Date(keyElement.nextElementSibling.textContent);
const sizeElement = keyElement.parentNode.querySelector('Size');
const size = sizeElement ? parseInt(sizeElement.textContent, 10) : NaN;
const row = document.createElement('tr');
const nameCell = document.createElement('td');
const link = createDownloadLink(key);
nameCell.appendChild(link);
row.appendChild(nameCell);
row.insertCell(-1).textContent = lastModified.toLocaleString();
row.insertCell(-1).textContent = formatSize(size);
objectList.appendChild(row);
});
updateBreadcrumb(path);
updatePaginationControls();
loading.classList.add('d-none');
loading.classList.add('d-none');
})
.catch((error) => {
console.error('Error fetching objects:', error);
loading.classList.add('d-none');
errorAlert.textContent = `Error fetching objects: ${error.message}`;
errorAlert.classList.remove('d-none');
});
}
searchInput.addEventListener('input', (e) => {
const filter = e.target.value.toLowerCase();
const rows = objectList.getElementsByTagName('tr');
for (let i = 0; i < rows.length; i++) {
const nameCell = rows[i].getElementsByTagName('td')[0];
const name = nameCell.textContent || nameCell.innerText;
if (name.toLowerCase().indexOf(filter) > -1) {
rows[i].style.display = '';
} else {
rows[i].style.display = 'none';
}
}
});
const darkModeSwitch = document.getElementById('darkModeSwitch');
darkModeSwitch.addEventListener('change', (e) => {
const darkModeStyle = document.getElementById('dark-mode-style');
if (e.target.checked) {
darkModeStyle.disabled = false;
localStorage.setItem('darkMode', 'true');
} else {
darkModeStyle.disabled = true;
localStorage.setItem('darkMode', 'false');
}
});
const darkModeStyle = document.getElementById('dark-mode-style');
if (localStorage.getItem('darkMode') === 'true') {
darkModeSwitch.checked = true;
darkModeStyle.disabled = false;
} else {
darkModeSwitch.checked = false;
darkModeStyle.disabled = true;
}
breadcrumb.onclick = (e) => {
e.preventDefault();
if (e.target.tagName === 'A') {
navigateTo('');
}
};
navigateTo('');
// Pagination controls logic
document.getElementById('prevPage').addEventListener('click', function() {
currentPage = Math.max(currentPage - 1, 1);
listObjects(currentPath);
});
document.getElementById('nextPage').addEventListener('click', function() {
currentPage = Math.min(currentPage + 1, totalPages);
listObjects(currentPath);
});
function updatePaginationControls() {
document.getElementById('pageInfo').textContent = `Page ${currentPage} of ${totalPages}`;
document.getElementById('prevPage').disabled = currentPage <= 1;
document.getElementById('nextPage').disabled = currentPage >= totalPages;
}