-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathMainWindow.xaml.cs
611 lines (506 loc) · 23 KB
/
MainWindow.xaml.cs
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
using System;
using System.Reflection;
using System.Windows;
using System.IO;
using Microsoft.Web.WebView2.Core;
using System.Diagnostics;
using Sigma.Hubs;
using Microsoft.Extensions.Hosting;
using System.ComponentModel;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Builder;
using System.Threading;
using System.Windows.Input;
using System.Security.Policy;
using Microsoft.AspNetCore.Hosting.Server;
using Newtonsoft.Json;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
namespace sigmanuts_webview2
{
/// <summary>
/// This class is fairly loaded because I couldnt be bothered to split it up
///
/// Defined main app window, hosts SignalR instance for interaction between the app and
/// the server on which the widget is server, and handles window interactions.
///
/// If someone decides to organize it without losing any functionality, be my guest.
/// </summary>
public partial class MainWindow : Window
{
public static string CacheFolderPath => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Sigmanuts");
private Microsoft.AspNetCore.SignalR.IHubContext<StreamHub> hubContext; // This is not used anymore, but I'll leave it here
private bool isChatEnabled = false;
private bool isPreviewEnabled = false;
private static string currentWidget = "";
/// <summary>
/// URLs
/// </summary>
private string chatUrl = "http://localhost:6969/tutorial.html";//"https://www.youtube.com/live_chat?v=jfKfPfyJRdk"
private string appUrl = "http://localhost:6969/app.html";
private string widgetUrl = $"http://localhost:6969/widgets/{currentWidget}/widget.html";
private SimpleHTTPServer myServer;
public MainWindow()
{
try
{
InitializeComponent();
Directory.CreateDirectory(Path.Combine(CacheFolderPath, @".\localserver\widgets"));
if (!File.Exists(Path.Combine(CacheFolderPath, @".\localserver")))
{
string sourceDirectory = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @".\web-src");
string targetDirectory = Path.Combine(CacheFolderPath, @".\localserver");
Debug.WriteLine(sourceDirectory);
DirectoryInfo diSource = new DirectoryInfo(sourceDirectory);
DirectoryInfo diTarget = new DirectoryInfo(targetDirectory);
CopyDir.CopyAll(diSource, diTarget);
}
HandleWidgets();
Debug.WriteLine("Running...");
new Thread(() => InitSignalR()) { IsBackground = true }.Start();
// Start the server
string folder = Path.Combine(CacheFolderPath, @".\localserver");
myServer = new SimpleHTTPServer(folder, 6969);
currentWidget = "";
Application.Current.Exit += CurrentOnExit;
}
catch (Exception ex)
{
Directory.CreateDirectory(Path.Combine(CacheFolderPath, @".\crash-logs"));
string[] exception =
{
ex.Message };
File.WriteAllLinesAsync(Path.Combine(CacheFolderPath, @".\crash-logs\latest.log"), exception);
}
}
protected override async void OnInitialized(EventArgs e)
{
/// This method sets user data folder and initial URLs for
/// app windows, as well as performs other startup things
base.OnInitialized(e);
var environment = await CoreWebView2Environment.CreateAsync(null, CacheFolderPath);
await webView.EnsureCoreWebView2Async(environment);
await appView.EnsureCoreWebView2Async(environment);
await widgetView.EnsureCoreWebView2Async(environment);
if (File.Exists(Path.Combine(CacheFolderPath, @".\localserver\config.ini")))
{
chatUrl = File.ReadAllText(Path.Combine(CacheFolderPath, @".\localserver\config.ini"));
}
webView.Source = new UriBuilder(chatUrl).Uri;
appView.Source = new UriBuilder(appUrl).Uri;
widgetView.Source = new UriBuilder(widgetUrl).Uri;
widgetView.DefaultBackgroundColor = System.Drawing.Color.Transparent;
appView.CoreWebView2.WebMessageReceived += HandleWebMessage;
webView.CoreWebView2.DOMContentLoaded += OnWebViewDOMContentLoaded;
appView.DefaultBackgroundColor = System.Drawing.Color.Transparent;
}
private void CurrentOnExit(object sender, ExitEventArgs exitEventArgs)
{
/// This method exists to delete the user data folder upon exit
/// It's deprecated now that the UDF is stored inside AppData/Local/
/// Keep it, but forget about this.
try
{
// Delete WebView2 user data before application exits
string? webViewCacheDir = Path.Combine(CacheFolderPath, @".\EBWebView\Default\Cache");
var webViewProcessId = Convert.ToInt32(webView.CoreWebView2.BrowserProcessId);
var webViewProcess = Process.GetProcessById(webViewProcessId);
ClearBrowserData();
// Shutdown browser with Dispose, and wait for process to exit
webView.Dispose();
webViewProcess.WaitForExit(2000);
//Disabling cache deletion
//Directory.Delete(webViewCacheDir, true);
}
catch (Exception ex)
{
// log warning
}
Environment.Exit(0);
}
/// <summary>
/// Logic for JS interaction
/// </summary>
///
public async void HandleWebMessage(object sender, CoreWebView2WebMessageReceivedEventArgs args)
{
if (args == null)
{
return;
}
String content = args.TryGetWebMessageAsString();
dynamic stuff = JsonConvert.DeserializeObject(content);
switch (stuff.listener.ToString())
{
case "toggle-chat":
ToggleChat(Boolean.Parse(stuff.value.ToString()));
break;
case "toggle-fullscreen":
ToggleFullscreen();
break;
case "toggle-login":
ToggleLogin();
break;
case "toggle-update":
OpenUrl("https://github.com/sigmacw/sigmanuts-webview2/releases");
break;
case "change-url":
string url = stuff.value;
webView.CoreWebView2.Navigate(url);
webView.CoreWebView2.DOMContentLoaded += OnWebViewDOMContentLoaded;
string[] lines =
{
url
};
await File.WriteAllLinesAsync(Path.Combine(CacheFolderPath, @".\localserver\config.ini"), lines);
break;
case "change-widget":
currentWidget = stuff.value;
string[] current =
{
currentWidget
};
await File.WriteAllLinesAsync(Path.Combine(CacheFolderPath, @".\localserver\widgets\activeWidget.active"), current);
widgetUrl = $"http://localhost:6969/widgets/{currentWidget}/widget.html";
widgetView.CoreWebView2.Navigate(widgetUrl);
break;
case "widget-load":
string widgetData = stuff.value;
string widgetName = stuff.name;
bool active = stuff.active;
if (!active) break;
string[] dataToWrite = { widgetData };
try
{
await File.WriteAllLinesAsync(Path.Combine(CacheFolderPath, $@".\localserver\widgets\{widgetName}\src\data.txt"), dataToWrite);
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
}
break;
case "create-widget":
string name = stuff.name;
string _srcDir = WidgetOperations.CreateWidgetFolder(name);
HandleWidgets();
break;
case "populate-widget":
string _name = stuff.name;
string HTML = stuff.htmlvalue;
string CSS = stuff.cssvalue;
string JS = stuff.jsvalue;
string FIELDS = stuff.fieldsvalue;
string DATA = stuff.datavalue;
string[] _HTML = { HTML };
string[] _CSS = { CSS };
string[] _JS = { JS };
string[] _FIELDS = { FIELDS };
string[] _DATA = { DATA };
string widgetDirectory = Path.Combine(CacheFolderPath, @$".\localserver\widgets\{_name}");
string srcDirectory = Path.Combine(widgetDirectory, "src");
await File.WriteAllLinesAsync(Path.Combine(srcDirectory, @".\html.html"), _HTML);
await File.WriteAllLinesAsync(Path.Combine(srcDirectory, @".\css.css"), _CSS);
await File.WriteAllLinesAsync(Path.Combine(srcDirectory, @".\js.js"), _JS);
await File.WriteAllLinesAsync(Path.Combine(srcDirectory, @".\fields.json"), _FIELDS);
await File.WriteAllLinesAsync(Path.Combine(srcDirectory, @".\data.txt"), _DATA);
WidgetOperations.CreateWidget(_name, appView);
HandleWidgets();
widgetUrl = $"http://localhost:6969/widgets/{currentWidget}/widget.html";
widgetView.CoreWebView2.Navigate(widgetUrl);
break;
case "refresh-widget":
string _name_ = stuff.name;
Debug.WriteLine(_name_);
WidgetOperations.CreateWidget(_name_, appView);
widgetView.CoreWebView2.Navigate(widgetUrl);
break;
case "refresh-widget-list":
HandleWidgets();
await appView.CoreWebView2.ExecuteScriptAsync($"location.reload();");
break;
case "delete-widget":
string __name_ = stuff.name;
string widgetDir = Path.Combine(CacheFolderPath, @$".\localserver\widgets\{__name_}");
Directory.Delete(widgetDir, true);
HandleWidgets();
string[] clearActive = { "" };
await File.WriteAllLinesAsync(Path.Combine(CacheFolderPath, @".\localserver\widgets\activeWidget.active"), clearActive);
await appView.CoreWebView2.ExecuteScriptAsync($"retrieveData().then(updateUI()); $('iframe').attr('src', ``)");
break;
case "test-message":
string type = stuff.type;
await webView.CoreWebView2.ExecuteScriptAsync("testMessage('" + type + "')");
break;
case "open-folder":
Process.Start("explorer.exe",Path.Combine(CacheFolderPath, @".\localserver\widgets\"));
break;
case "request-history":
string __history_name = stuff.name;
string __history_code = stuff.code;
string __history_amount = stuff.amount;
webView.CoreWebView2.ExecuteScriptAsync($"sendPastChats('{__history_name}', '{__history_code}', {__history_amount})");
break;
default:
break;
}
}
public void ToggleChat(bool active)
{
/// Simple function to toggle chat visibility on and off.
///
/// I am aware that I can change Visibility to Hidden or Collapsed,
/// it's done by setting Height to 0 for a reason. YouTube chat pauses if not focused.
/// Do not ask about this.
if (isChatEnabled == active) return;
isChatEnabled = active;
if (isChatEnabled)
{
appView.HorizontalAlignment = HorizontalAlignment.Left;
appView.Width = 51;
//
/*
if (WindowState == WindowState.Maximized)
{
var margin = new Thickness(0, 0, window.ActualWidth - 51, 0);
appView.Margin = margin;
}
else
{
var margin = new Thickness(0, 0, window.ActualWidth - 51, 0);
appView.Margin = margin;
}*/
}
else
{
appView.HorizontalAlignment = HorizontalAlignment.Stretch;
appView.Width = Double.NaN;
/*
var margin = new Thickness(0, 0, 0, 0);
appView.Margin = margin;*/
}
}
public void ToggleLogin()
{
ToggleChat(true);
webView.CoreWebView2.Navigate("https://www.youtube.com/account");
}
public async void ToggleFullscreen()
{
/// Simple function to toggle fullscreen preview visibility on and off.
if (!File.Exists(Path.Combine(CacheFolderPath, $@".\localserver\widgets\{currentWidget.Replace("\r\n", string.Empty)}\widget.html")))
{
return;
}
isPreviewEnabled = !isPreviewEnabled;
if (isPreviewEnabled)
{
if (WindowState == WindowState.Maximized)
{
widgetView.Height = window.ActualHeight - 110;
}
else
{
widgetView.Height = window.ActualHeight - 94;
}
}
else
{
widgetView.Height = 0;
}
await appView.CoreWebView2.ExecuteScriptAsync("$('.fullscreen').toggle('fast');");
}
public async void HandleWidgets()
{
if (File.Exists(Path.Combine(CacheFolderPath, @".\localserver\widgets\activeWidget.active")))
{
currentWidget = File.ReadAllText(Path.Combine(CacheFolderPath, @".\localserver\widgets\activeWidget.active"));
}
else
{
string[] current =
{
""
};
await File.WriteAllLinesAsync(Path.Combine(CacheFolderPath, @".\localserver\widgets\activeWidget.active"), current);
}
try
{
string[] dirs = Directory.GetDirectories(Path.Combine(CacheFolderPath, @".\localserver\widgets"), "*", SearchOption.TopDirectoryOnly);
await File.WriteAllLinesAsync(Path.Combine(CacheFolderPath, @$".\localserver\widgets\widgets.ini"), dirs);
}
catch (Exception e)
{
Debug.WriteLine("The process failed: {0}", e.ToString());
}
}
/// <summary>
/// Listening for JS events
/// </summary>
private async void OnWebViewDOMContentLoaded(object sender, CoreWebView2DOMContentLoadedEventArgs arg)
{
/// This function injects scraping script into YouTube live chat.
webView.CoreWebView2.DOMContentLoaded -= OnWebViewDOMContentLoaded;
webView.Focus();
string pathToScript = System.IO.Path.Combine(
System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @".\web-src\js\script.js");
string contents = File.ReadAllText(pathToScript);
await webView.CoreWebView2.ExecuteScriptAsync(contents);
}
private async void OnNavigationCompleted(object sender, CoreWebView2NavigationCompletedEventArgs arg)
{
/// I know this function is basically equivalent OnWebViewDOMContentLoaded...
/// I just couldn't be bothered to generalize these since I'm not gonna be
/// expanding on any functionality on these events
webView.NavigationCompleted -= OnNavigationCompleted;
webView.Focus();
string pathToScript = System.IO.Path.Combine(
System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @".\web-src\js\script.js");
string contents = File.ReadAllText(pathToScript);
await webView.CoreWebView2.ExecuteScriptAsync(contents);
}
private async void ClearBrowserData()
{
CoreWebView2Profile profile;
if (webView.CoreWebView2 != null)
{
profile = appView.CoreWebView2.Profile;
CoreWebView2BrowsingDataKinds dataKinds = (CoreWebView2BrowsingDataKinds)
(CoreWebView2BrowsingDataKinds.DiskCache | CoreWebView2BrowsingDataKinds.AllDomStorage);
await profile.ClearBrowsingDataAsync(dataKinds);
}
}
/// <summary>
/// Methods related to the SignalR instance.
/// Some of the methods are unused, but I'm keeping them just in case.
/// Do not suggest to delete those.
/// </summary>
private IHost _host;
private async void InitSignalR()
{
_host?.Dispose();
_host = Host.CreateDefaultBuilder()
.ConfigureWebHostDefaults(webBuilder => webBuilder
.UseUrls("http://localhost:6970")
.ConfigureServices(services => services.AddSignalR())
//.ConfigureServices(services => services.AddTransient<HubMethods<StreamHub>>())
.ConfigureServices(services => services.AddCors(
options =>
{
options.AddDefaultPolicy(
webBuilder =>
{
webBuilder.WithOrigins("http://localhost:6969")
.WithOrigins("https://www.youtube.com")
.AllowAnyHeader()
.WithMethods("GET", "POST")
.AllowCredentials();
});
}
))
.Configure(app =>
{
app.UseCors();
app.UseRouting();
app.UseEndpoints(endpoints => endpoints.MapHub<StreamHub>("stream"));
}))
.Build();
await _host.StartAsync();
}
private async void StopSignalR()
{
if (_host != null)
{
await _host.StopAsync();
_host.Dispose();
}
}
protected override void OnClosing(CancelEventArgs e)
{
_host?.Dispose();
base.OnClosing(e);
}
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
// Can execute
private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
// Minimize
private void CommandBinding_Executed_Minimize(object sender, ExecutedRoutedEventArgs e)
{
SystemCommands.MinimizeWindow(this);
}
// Maximize
private void CommandBinding_Executed_Maximize(object sender, ExecutedRoutedEventArgs e)
{/*
isPreviewEnabled = false;
widgetView.Height = 0;
isChatEnabled = false;
var margin = new Thickness(0, 0, 0, 0);
appView.Margin = margin;*/
SystemCommands.MaximizeWindow(this);
}
// Restore
private void CommandBinding_Executed_Restore(object sender, ExecutedRoutedEventArgs e)
{/*
isPreviewEnabled = false;
widgetView.Height = 0;
isChatEnabled = false;
var margin = new Thickness(0, 5, 0, 0);
appView.Margin = margin;*/
SystemCommands.RestoreWindow(this);
}
// Close
private void CommandBinding_Executed_Close(object sender, ExecutedRoutedEventArgs e)
{
SystemCommands.CloseWindow(this);
}
// State change
private void MainWindowStateChangeRaised(object sender, EventArgs e)
{
if (WindowState == WindowState.Maximized)
{
MainWindowBorder.BorderThickness = new Thickness(8);
RestoreButton.Visibility = Visibility.Visible;
MaximizeButton.Visibility = Visibility.Collapsed;
}
else
{
MainWindowBorder.BorderThickness = new Thickness(0);
RestoreButton.Visibility = Visibility.Collapsed;
MaximizeButton.Visibility = Visibility.Visible;
}
}
private void OpenUrl(string url)
{
try
{
Process.Start(url);
}
catch
{
// hack because of this: https://github.com/dotnet/corefx/issues/10361
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
url = url.Replace("&", "^&");
Process.Start(new ProcessStartInfo(url) { UseShellExecute = true });
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
Process.Start("xdg-open", url);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
Process.Start("open", url);
}
else
{
throw;
}
}
}
}
}