-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOpenWithLiveServer.cs
More file actions
229 lines (196 loc) · 7.8 KB
/
Copy pathOpenWithLiveServer.cs
File metadata and controls
229 lines (196 loc) · 7.8 KB
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
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Net.WebSockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Shapes;
namespace FirstCell
{
public class LiveReloadServer
{
private readonly HttpListener httpListener = new();
private HttpListenerContext? lastHtmlContext;
private readonly List<WebSocket> connectedSockets = new();
private readonly string rootPath;
private bool running = false;
public LiveReloadServer(string projectRoot)
{
rootPath = projectRoot;
httpListener.Prefixes.Add("http://localhost:8080/");
}
public async Task StartAsync()
{
if (running) return;
running = true;
httpListener.Start();
_ = Task.Run(async () =>
{
while (running)
{
var context = await httpListener.GetContextAsync();
if (context.Request.IsWebSocketRequest)
_ = HandleWebSocketAsync(context);
else
_ = HandleHttpRequestAsync(context);
}
});
}
public void Stop()
{
running = false;
httpListener.Stop();
foreach (var ws in connectedSockets)
if (ws.State == WebSocketState.Open)
ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "Server stopping", CancellationToken.None).Wait();
}
private async Task HandleHttpRequestAsync(HttpListenerContext context)
{
string relativePath = context.Request.Url!.AbsolutePath.TrimStart('/');
string filePath = System.IO.Path.Combine(rootPath, relativePath);
if (!System.IO.File.Exists(filePath))
{
context.Response.StatusCode = 404;
context.Response.Close();
return;
}
string contentType = filePath.EndsWith(".html") ? "text/html" :
filePath.EndsWith(".js") ? "application/javascript" :
filePath.EndsWith(".css") ? "text/css" : "application/octet-stream";
byte[] content;
if (filePath.EndsWith(".html"))
{
lastHtmlContext = context;
string html;
using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var reader = new StreamReader(fs, Encoding.UTF8))
{
html = await reader.ReadToEndAsync();
}
if (!html.Contains("__livereload"))
{
html = LiveReloadInjector.Inject(html);
}
content = Encoding.UTF8.GetBytes(html);
}
else
{
using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var ms = new MemoryStream())
{
await fs.CopyToAsync(ms);
content = ms.ToArray();
}
}
context.Response.ContentType = contentType;
context.Response.ContentLength64 = content.Length;
await context.Response.OutputStream.WriteAsync(content, 0, content.Length);
context.Response.Close();
}
private async Task HandleWebSocketAsync(HttpListenerContext context)
{
var wsContext = await context.AcceptWebSocketAsync(null);
var socket = wsContext.WebSocket;
connectedSockets.Add(socket);
var buffer = new byte[1024];
while (socket.State == WebSocketState.Open)
{
var result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
if (result.MessageType == WebSocketMessageType.Close)
{
await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Client closed", CancellationToken.None);
}
}
connectedSockets.Remove(socket);
}
public async Task ReloadClientsAsync()
{
var message = Encoding.UTF8.GetBytes("reload");
foreach (var socket in connectedSockets)
{
if (socket.State == WebSocketState.Open)
await socket.SendAsync(new ArraySegment<byte>(message), WebSocketMessageType.Text, true, CancellationToken.None);
}
}
}
public static class LiveReloadInjector
{
private const string ScriptId = "__livereload";
private const string InjectedScript =
"<script id=\"__livereload\">" +
"var ws = new WebSocket('ws://localhost:8080');" +
"ws.onmessage = function(msg) { if (msg.data === 'reload') location.reload(); };" +
"</script>";
public static string Inject(string html)
{
if (html.Contains(ScriptId)) return html;
return Regex.Replace(html, "</body>", InjectedScript + "</body>", RegexOptions.IgnoreCase);
}
public static string Remove(string html)
{
return Regex.Replace(html, $"<script[^>]*id=\"{ScriptId}\"[^>]*>.*?</script>", string.Empty, RegexOptions.Singleline);
}
public static void RemoveFromFile(string filePath)
{
string content = System.IO.File.ReadAllText(filePath);
string cleaned = Remove(content);
System.IO.File.WriteAllText(filePath, cleaned);
}
}
public class FileWatcher
{
private FileSystemWatcher watcher;
private string projectpath;
private LiveReloadServer liveReloadServer;
public FileWatcher(string projectPath, LiveReloadServer liveReloadServer)
{
this.liveReloadServer = liveReloadServer;
watcher = new FileSystemWatcher(projectPath)
{
IncludeSubdirectories = true,
EnableRaisingEvents = true,
Filter = "*.*"
};
watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName;
watcher.Changed += OnChanged;
}
private readonly Dictionary<string, DateTime> _lastChanged = new();
private async void OnChanged(object sender, FileSystemEventArgs e)
{
var now = DateTime.Now;
if (_lastChanged.TryGetValue(e.FullPath, out DateTime lastTime))
{
if ((now - lastTime).TotalMilliseconds < 500)
return;
}
_lastChanged[e.FullPath] = now;
await Application.Current.Dispatcher.InvokeAsync(async () =>
{
for (int i = 0; i < 5; i++)
{
if (IsFileReady(e.FullPath))
{
await liveReloadServer.ReloadClientsAsync();
break;
}
await Task.Delay(100);
}
});
}
private bool IsFileReady(string path)
{
try
{
using var stream = System.IO.File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
return true;
}
catch
{
return false;
}
}
}
}