-
Notifications
You must be signed in to change notification settings - Fork 9
/
index.js
282 lines (234 loc) · 7.88 KB
/
index.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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
import * as Utils from "./utils.js";
let hostName = ""; // name of host folder, e.g. "host", "host2"...
let swScope = ""; // scope of Service Worker
let folderHandle = null; // File system API handle (or polyfill) of folder to serve
let folderName = "";
let hasIndexHtml = false; // True if root directory has index.html
const pickFolderButton = document.getElementById("pickfolder");
const inputFolderElem = document.getElementById("inputfolder");
// Register a hit for server-side visitor counting. The offline support means that a subsequent visit
// will load fully client-side without contacting the server at all. Fetching hit.html, which is not cached,
// with a cache-busting request will hit the server and so log a visit even with a fully cached load, so long
// as the internet connection is available. The result is ignored and the request can fail with no consequence
// other than the visit not being logged.
fetch("hit.html", {cache: "no-store" /* bypass cache */ })
.catch(() => {}); // noop on error
// Use File System API if available
if (window.showDirectoryPicker)
{
async function InitFolderHandle()
{
folderName = folderHandle.name;
// Check if folder has index.html file
try {
await folderHandle.getFileHandle("index.html");
hasIndexHtml = true;
}
catch
{
hasIndexHtml = false;
}
// Ensure SW ready then tell it to start hosting for this client
await Utils.WaitForSWReady();
Utils.PostToSW({
type: "host-start"
});
};
pickFolderButton.removeAttribute("hidden");
pickFolderButton.addEventListener("click", async () =>
{
try {
// Pick folder
folderHandle = await window.showDirectoryPicker();
}
catch (err)
{
console.log("Exception picking folder: ", err);
}
if (!folderHandle)
return;
await InitFolderHandle();
// Write this folder handle to storage so it can be re-used next time
await Utils.storageSet("folder", folderHandle);
});
// Check if a folder handle is in storage. If so show a button to re-use it,
// since it will require a gesture to request permission to read from it.
const savedFolderHandle = await Utils.storageGet("folder");
if (savedFolderHandle)
{
const useLastFolderButton = document.getElementById("uselastfolder");
useLastFolderButton.textContent = `Use last folder (${savedFolderHandle.name})`;
useLastFolderButton.removeAttribute("hidden");
useLastFolderButton.addEventListener("click", async () =>
{
const permission = await savedFolderHandle.requestPermission({
mode: "read"
});
if (permission === "granted")
{
useLastFolderButton.setAttribute("hidden", "");
folderHandle = savedFolderHandle;
await InitFolderHandle();
}
});
}
}
else
{
// If File System API not supported, fall back to file input with webkitdirectory attribute
async function InitFileList()
{
// Use a polyfill to make these files look like the File System Access API
folderName = "";
folderHandle = new Utils.FakeDirectory("");
for (const file of inputFolderElem.files)
{
let pathStr = file.webkitRelativePath;
// Every path begins with the folder name. Parse off the folder name from
// the first path, and always remove the folder name from the path.
let i = pathStr.indexOf("/");
if (i !== -1)
{
if (!folderName)
folderName = pathStr.substr(0, i);
pathStr = pathStr.substr(i + 1);
}
// Add this file to the folder structure
folderHandle.AddFile(pathStr, file);
}
hasIndexHtml = folderHandle.HasFile("index.html");
// Ensure SW ready then tell it to start hosting for this client
await Utils.WaitForSWReady();
Utils.PostToSW({
type: "host-start"
});
};
inputFolderElem.removeAttribute("hidden");
inputFolderElem.addEventListener("change", InitFileList);
// If browser has remembered file list, e.g. Firefox reloading page, init immediately
if (inputFolderElem.files.length > 0)
InitFileList();
}
Utils.RegisterSW();
await Utils.WaitForSWReady();
console.log("SW ready");
// When closing this client tell the SW to stop hosting for it
window.addEventListener("unload", () =>
{
Utils.PostToSW({
type: "host-stop",
hostName
});
});
// Handle messages from SW
navigator.serviceWorker.addEventListener("message", e =>
{
switch (e.data.type) {
case "start-ok":
OnHostStarted(e.data);
break;
case "fetch":
HandleFetch(e);
break;
default:
console.warn(`Unknown message from SW '${e.data.type}'`);
break;
}
});
// SW indicates hosting started OK: get info and display URL
function OnHostStarted(data)
{
hostName = data.hostName;
swScope = data.scope;
document.getElementById("hostinfo").style.display = "block";
document.getElementById("foldername").textContent = folderName;
const hostLinkElem = document.getElementById("hostlink");
const hostUrl = `${swScope}${hostName}/${hasIndexHtml ? "index.html" : ""}`;
hostLinkElem.setAttribute("href", hostUrl);
hostLinkElem.textContent = hostUrl;
document.title = `Serving '${folderName}' to '${hostName}'`;
}
// Message from SW to read a file for a fetch
async function HandleFetch(e)
{
try {
let relativeUrl = decodeURIComponent(e.data.url);
const urlEndsWithSlash = relativeUrl.endsWith("/");
// Strip trailing / if any, so the last token is the folder/file name
if (urlEndsWithSlash)
relativeUrl = relativeUrl.substr(0, relativeUrl.length - 1);
// Strip query string and hash if any, since it will cause file name lookups to fail
const q = relativeUrl.indexOf("?");
if (q !== -1)
relativeUrl = relativeUrl.substr(0, q);
const h = relativeUrl.indexOf("#");
if (h !== -1)
relativeUrl = relativeUrl.substr(0, h);
// Look up through any subfolders in path.
// Note this uses File System Access API methods, either the real kind or a mini
// polyfill when using webkitdirectory fallback.
const subfolderArr = relativeUrl.split("/");
let curFolderHandle = folderHandle;
for (let i = 0, len = subfolderArr.length - 1 /* skip last */; i < len; ++i)
{
const subfolder = subfolderArr[i];
curFolderHandle = await curFolderHandle.getDirectoryHandle(subfolder);
}
// Check if the name is a directory or a file
let file = null;
const lastName = subfolderArr[subfolderArr.length - 1];
if (!lastName) // empty name, e.g. for root /, treated as folder
{
file = await GenerateDirectoryListing(curFolderHandle, relativeUrl);
}
else
{
try {
const listHandle = await curFolderHandle.getDirectoryHandle(lastName);
// Require that directory listing URLs end with a slash, for relative URLs in the
// directory listing to resolve correctly. Without a slash, it will return 404.
if (listHandle && !urlEndsWithSlash)
throw new Error("expected trailing slash");
file = await GenerateDirectoryListing(listHandle, relativeUrl);
}
catch
{
const fileHandle = await curFolderHandle.getFileHandle(lastName);
file = await fileHandle.getFile();
}
}
// Post file content back to SW down MessageChannel it sent for response
e.data.port.postMessage({
type: "ok",
file
});
}
catch (err)
{
console.error(`Unable to serve file '${e.data.url}': `, err);
e.data.port.postMessage({
type: "not-found"
});
}
}
// For generating a directory listing page for a folder
async function GenerateDirectoryListing(dirHandle, relativeUrl)
{
// Display folder with / at end
if (relativeUrl && !relativeUrl.endsWith("/"))
relativeUrl += "/";
let str = `<!DOCTYPE html>
<html><head>
<meta charset="utf-8">
<title>Directory listing for ${relativeUrl || "/"}</title>
</head><body>
<h1>Directory listing for ${relativeUrl || "/"}</h1><ul>`;
for await (const [name, handle] of dirHandle.entries())
{
// Display folders as "name/", otherwise just use name
const suffix = (handle.kind === "directory" ? "/" : "");
str += `<li><a href="${name}${suffix}">${name}${suffix}</a></li>`;
}
str += `</ul></body></html>`;
return new Blob([str], { type: "text/html" });
}