This repository has been archived by the owner on May 18, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathUtils.cs
729 lines (619 loc) · 25.2 KB
/
Utils.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
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RestSharp;
using System.Windows;
using System.Windows.Controls;
using System.Net;
using System.Threading;
using System.Globalization;
using System.Windows.Media.Imaging;
using System.Windows.Media;
using Microsoft.Win32;
using System.IO;
using System.Security.Cryptography;
using System.Diagnostics;
using System.Deployment.Application;
using System.Reflection;
using Newtonsoft.Json.Linq;
using System.Windows.Threading;
using Newtonsoft.Json;
using System.Security.RightsManagement;
using Notifications.Wpf;
using IWshRuntimeLibrary;
namespace OS_Game_Launcher
{
public static class Utils
{
public static RestClient Client = new RestClient(Properties.Settings.Default.host);
public static NotificationManager notificationManager;
public static async Task PutTaskDelay(int Miliseconds)
{
await Task.Delay(Miliseconds);
}
public static void Init()
{
Client.UserAgent = "OSGameLauncherClient/0.0.1";
Guid clientUuidGenerated = Guid.NewGuid();
RegistryKey launcherRootReg = Registry.CurrentUser;
RegistryKey rootReg = RegistryOpenCreateKey(launcherRootReg, Properties.Settings.Default.regestryPath);
string clientUuid = (string) RegistryGetSet(rootReg, "clientUuid", clientUuidGenerated.ToString());
Console.WriteLine("Client UUID: " + clientUuid);
Client.AddDefaultHeader("client-uuid", clientUuid);
Client.AddDefaultHeader("client-version", getRunningVersion().ToString());
notificationManager = new NotificationManager();
Settings.Load();
}
public static string getExecutablePath()
{
return System.Reflection.Assembly.GetExecutingAssembly().Location;
}
public async static Task<bool> WaitForExitAsync(Process process, int timeout)
{
return await Task.Run(() => process.WaitForExit(timeout));
}
public async static void setURLProtocol()
{
if (!RegistryContainsSubKey(Registry.ClassesRoot, "osgamelauncher"))
{
Console.WriteLine("URL Protocol not registered!");
Process p = new Process();
p.StartInfo.FileName = "RegisterRegistry.exe";
p.StartInfo.Verb = "runas";
p.StartInfo.Arguments = "\"" + getExecutablePath() + "\"";
//p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.StartInfo.UseShellExecute = true;
try
{
p.Start();
await WaitForExitAsync(p, 100000);
} catch
{
Utils.showMessage("The \"RegisterRegistry\" program is required to let you start games from your desktop!");
}
}
}
public static NamedPipeManager PipeManager;
public static void startPipeServer()
{
PipeManager = new NamedPipeManager("OSGameLauncher");
PipeManager.StartServer();
PipeManager.ReceiveString += PipeManager_OpenRequest;
}
public static void stopPipServer()
{
PipeManager.StopServer();
}
public static void PipeManager_OpenRequest(string text)
{
App.Current.Dispatcher.Invoke(() =>
{
if (!string.IsNullOrEmpty(text))
{
String[] seperators = { "::" };
var msgParts = text.Split(seperators, 2, StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine("Received Pipe Message: " + text);
Console.WriteLine("Message Action: " + msgParts[0]);
switch (msgParts[0])
{
case "STARTUP_ARGS":
List<string> args = JsonConvert.DeserializeObject<List<string>>(msgParts[1]);
_ = Account.HandleStartupArgs(args);
break;
case "CUSTOM_ACTION":
switch (msgParts[1])
{
case "SET_MAIN_WND_FOCUS":
MainWindow mainWindow = (MainWindow)App.Current.MainWindow;
mainWindow.SetFocus();
break;
default:
Console.WriteLine("Unknown custom action");
break;
}
break;
default:
Console.WriteLine("Unknown operator");
break;
}
}
});
}
public static byte[] file_get_byte_contents(string fileName)
{
byte[] sContents;
if (fileName.ToLower().IndexOf("http:") > -1)
{
// URL
System.Net.WebClient wc = new System.Net.WebClient();
sContents = wc.DownloadData(fileName);
}
else
{
// Get file size
FileInfo fi = new FileInfo(fileName);
// Disk
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
sContents = br.ReadBytes((int)fi.Length);
br.Close();
fs.Close();
}
return sContents;
}
public static async void CheckVersion()
{
Console.WriteLine("Checking for updates");
Version currentAppVersion = getRunningVersion();
var request = new RestRequest("/update");
var cTokeS = new CancellationTokenSource();
var response = await Client.ExecuteGetAsync(request, cTokeS.Token);
var data = JObject.Parse(response.Content);
string newestAppVersion = (string)data["version"];
Version newestAppVersion_ = Version.Parse(newestAppVersion);
string patchNotes = (string)data["patch-notes"];
string installer = (string)data["url"];
bool mandatory = (bool)data["mandatory"];
string md5 = (string)data["md5"];
if (currentAppVersion.CompareTo(newestAppVersion_) < 0)
{
Console.WriteLine("Version is outdated!");
notificationManager.Show(new NotificationContent
{
Title = "OS Game-Launcher Update",
Message = "A new version of the OS Game-Launcher is available!",
Type = NotificationType.Information
}, expirationTime: TimeSpan.FromSeconds(15));
showMessage("A newer version of OS Game-Launcher is available. Your currently installed version is " +
currentAppVersion.ToString() + " and the newest version is " + newestAppVersion + "!\n\nUpdate " +
currentAppVersion.ToString() + " => " + newestAppVersion + "\n\nChange log: " + patchNotes + "\n\nNew version is getting Downloaded...");
Console.WriteLine("Installed version outdated. Downloading new version");
string tempFolderPath = Path.GetTempPath();
string installationPath = Path.Combine(tempFolderPath, "osg-updater-" + newestAppVersion.Replace(".", "-") + ".exe");
DriveInfo installDrive = GetDriverFromPrefix(Path.GetPathRoot(new FileInfo(installationPath).FullName));
var freeDiscSpace = installDrive.AvailableFreeSpace;
if (await GetHttpStatusCode(installer) &&
await GetFileSize(new Uri(installer)) < freeDiscSpace)
{
WebClient webClient = new WebClient();
await webClient.DownloadFileTaskAsync(installer, installationPath);
webClient.Dispose();
Console.WriteLine("Updater successfully downloaded! Comparing MD5");
string downloaded_comp_hash = CalculateMD5(installationPath);
if (downloaded_comp_hash == (md5).ToLowerInvariant())
{
Process p = new Process();
p.StartInfo.FileName = installationPath;
p.StartInfo.Verb = "runas";
p.Start();
} else
{
Console.WriteLine("MD5 not same! DANGER!! Deleting installer");
await Utils.DeleteAsync(new FileInfo(installationPath));
Console.WriteLine("Update cleaned up!");
showMessage("The update installer is not valid! For more infos visit: " + patchNotes);
}
} else
{
Console.WriteLine("Installer not available or not enough Disc space");
showMessage("The update installer is not available or you don't have enough disc space! For more infos visit: " + patchNotes);
}
Application.Current.Shutdown(0);
} else if (currentAppVersion.CompareTo(newestAppVersion_) == 0)
{
Console.WriteLine("Version is up to date!");
} else
{
Console.WriteLine("Version is not published yet!");
}
}
public static Version getRunningVersion()
{
try
{
return ApplicationDeployment.CurrentDeployment.CurrentVersion;
}
catch (Exception)
{
return Assembly.GetExecutingAssembly().GetName().Version;
}
}
public static void DisplayLoading(Frame frame)
{
frame.Visibility = Visibility.Visible;
frame.Navigate(new Pages.loading());
}
public static void HideLoading(Frame frame)
{
frame.Navigate(null);
frame.Visibility = Visibility.Hidden;
}
public static string UrlShortcutToDesktop(string linkName, string linkUrl, string IconFile, int IconIndex)
{
string deskDir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
using (StreamWriter writer = new StreamWriter(Path.Combine(deskDir, linkName + ".url")))
{
writer.WriteLine("[InternetShortcut]");
writer.WriteLine("URL=" + linkUrl);
writer.WriteLine("IconFile=" + IconFile);
writer.WriteLine("IconIndex=" + IconIndex);
writer.WriteLine("HotKey=0");
writer.WriteLine("IDList=");
writer.Flush();
}
return Path.Combine(deskDir, linkName + ".url");
}
public static string CreateShortcut(string Name, string Target, string Description=null, string Hotkey=null, string WorkingDirectory=null, string IconPath=null, string Arguments=null)
{
if (!Settings.CreateDesktopShortcuts)
return null;
object shDesktop = (object)"Desktop";
WshShell shell = new WshShell();
string shortcutAddress = (string)shell.SpecialFolders.Item(ref shDesktop) + @"\" + Name + ".lnk";
IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutAddress);
shortcut.TargetPath = Target;
if (WorkingDirectory != null) shortcut.WorkingDirectory = WorkingDirectory;
if (Description != null) shortcut.Description = Description;
if (Hotkey != null) shortcut.Hotkey = Hotkey;
if (IconPath != null) shortcut.IconLocation = IconPath;
if (Arguments != null) shortcut.Arguments = Arguments;
shortcut.Save();
return shortcutAddress;
}
public static bool? showMessage(string message, bool showCancelButton = false)
{
return new Windows.msgBox(message, showCancelButton).ShowDialog();
}
public static void RestartApp()
{
System.Diagnostics.Process.Start(Application.ResourceAssembly.Location);
Application.Current.Shutdown(0);
}
public async static Task<bool> CheckUrl(string url)
{
try
{
using (var client = new PrivateWebClientHead())
{
client.HeadOnly = true;
var cTokeS = new CancellationTokenSource();
await client.DownloadStringTaskAsync(new Uri(url));
return true;
}
} catch
{
return false;
}
}
public async static Task<bool> UrlIsImage(string url)
{
var req = (HttpWebRequest)HttpWebRequest.Create(url);
req.Method = "HEAD";
using (var resp = await req.GetResponseAsync())
{
return resp.ContentType.ToLower(CultureInfo.InvariantCulture)
.StartsWith("image/");
}
}
public static ImageBrush UniformImageBrush(BitmapImage image, int width, int height)
{
ImageBrush uniformToFillBrush = new ImageBrush();
uniformToFillBrush.ImageSource = image;
uniformToFillBrush.Stretch = Stretch.UniformToFill;
// Freeze the brush (make it unmodifiable) for performance benefits.
//uniformToFillBrush.Freeze();
return uniformToFillBrush;
}
public static bool RegistryContainsSubKey(RegistryKey regKey, string value)
{
return (regKey.GetSubKeyNames().Contains(value));
}
public static RegistryKey RegistryOpenCreateKey(RegistryKey regKey, string regPath)
{
var reg = regKey.OpenSubKey(regPath, true);
if (reg == null)
{
return regKey.CreateSubKey(regPath, true);
} else
{
return reg;
}
}
public static object RegistryGetSet(RegistryKey reg, string keyName, object setter)
{
if (reg.GetValue(keyName) == null)
{
reg.SetValue(keyName, setter);
return setter;
} else
{
return reg.GetValue(keyName);
}
}
public static string ProgramFilesx86()
{
if (8 == IntPtr.Size
|| (!String.IsNullOrEmpty(Environment.GetEnvironmentVariable("PROCESSOR_ARCHITEW6432"))))
{
return Environment.GetEnvironmentVariable("ProgramFiles(x86)");
}
return Environment.GetEnvironmentVariable("ProgramFiles");
}
public static string SizeSuffix(Int64 value, int decimalPlaces = 1)
{
string[] SizeSuffixes =
{ "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
if (decimalPlaces < 0) { throw new ArgumentOutOfRangeException("decimalPlaces"); }
if (value < 0) { return "-" + SizeSuffix(-value); }
if (value == 0) { return string.Format("{0:n" + decimalPlaces + "} bytes", 0); }
// mag is 0 for bytes, 1 for KB, 2, for MB, etc.
int mag = (int)Math.Log(value, 1024);
// 1L << (mag * 10) == 2 ^ (10 * mag)
// [i.e. the number of bytes in the unit corresponding to mag]
decimal adjustedSize = (decimal)value / (1L << (mag * 10));
// make adjustment when the value is large enough that
// it would round up to 1000 or more
if (Math.Round(adjustedSize, decimalPlaces) >= 1000)
{
mag += 1;
adjustedSize /= 1024;
}
return string.Format("{0:n" + decimalPlaces + "} {1}",
adjustedSize,
SizeSuffixes[mag]);
}
public static string GetDefaultInstallationPath()
{
string DefaultPathGenerated = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "OS Game-Launcher Games");
string DefaultPathReg = (string)Utils.RegistryGetSet(RegistryOpenCreateKey(Registry.CurrentUser, Properties.Settings.Default.regestryPath), "DefaultGameInstallationPath", DefaultPathGenerated);
return DefaultPathReg;
}
public static string Truncate(this string value, int maxLength)
{
if (string.IsNullOrEmpty(value)) return value;
return value.Length <= maxLength ? value : value.Substring(0, maxLength);
}
public static string CreateDirectoryIfNotExists(string path)
{
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(path);
}
return path;
}
public async static Task<bool> GetHttpStatusCode(string url)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest
.Create(url);
webRequest.AllowAutoRedirect = false;
HttpWebResponse response = await Task.Run(() => (HttpWebResponse)webRequest.GetResponse());
Console.Write(response.StatusCode.ToString());
if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.Accepted ||
response.StatusCode == HttpStatusCode.MultipleChoices || response.StatusCode == HttpStatusCode.Redirect)
{
return true;
} else
{
return false;
}
}
public static Task DeleteAsync(this FileInfo fi)
{
return Task.Factory.StartNew(() => fi.Delete());
}
public static void DeleteDirectory(string targetDir)
{
System.IO.File.SetAttributes(targetDir, FileAttributes.Normal);
string[] files = Directory.GetFiles(targetDir);
string[] dirs = Directory.GetDirectories(targetDir);
foreach (string file in files)
{
System.IO.File.SetAttributes(file, FileAttributes.Normal);
System.IO.File.Delete(file);
}
foreach (string dir in dirs)
{
DeleteDirectory(dir);
}
Directory.Delete(targetDir, false);
}
public static Task DeleteFolderAsync(this FileInfo fi)
{
return Task.Factory.StartNew(() => DeleteDirectory(fi.FullName));
}
public static string CalculateMD5(string filename)
{
using (var md5 = MD5.Create())
{
using (var stream = System.IO.File.OpenRead(filename))
{
var hash = md5.ComputeHash(stream);
return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
}
}
}
public async static Task<int> GetFileSize(Uri uriPath)
{
var webRequest = HttpWebRequest.Create(uriPath);
webRequest.Method = "HEAD";
using (var webResponse = await webRequest.GetResponseAsync())
{
var fileSize = Convert.ToInt32(webResponse.Headers.Get("Content-Length"));
return fileSize;
}
}
public static bool IsRunning(this Process process)
{
if (process == null)
return false;
try
{
Process.GetProcessById(process.Id);
}
catch (ArgumentException)
{
return false;
}
return true;
}
public static String GetTimestamp(DateTime value)
{
return value.ToString("yyyyMMddHHmmssffff");
}
public static string FormatRushTime(TimeSpan span)
{
if (span.Days != 0)
{
return String.Format("{0:d} days {1:d} hours", span.Days, Math.Abs(span.Hours));
}
if (span.Hours != 0)
{
return String.Format("{0:d} hours {1:d} minutes", span.Hours, Math.Abs(span.Minutes));
}
if (span.Minutes != 0)
{
return String.Format("{0:d} minutes", span.Minutes, Math.Abs(span.Seconds));
}
return String.Format("{0:d} seconds", span.Seconds);
}
public static string FormatNumber(int num)
{
if (num >= 100000)
return FormatNumber(num / 1000) + " K";
if (num >= 10000)
{
return (num / 1000D).ToString("0.#") + " K";
}
return num.ToString("#,0");
}
public static DriveInfo GetDriverFromPrefix(string drivePrefix)
{
DriveInfo[] allDrives = DriveInfo.GetDrives();
foreach (var drive in allDrives)
{
Console.WriteLine(drive.Name);
if (drive.Name == drivePrefix)
{
return drive;
}
}
return allDrives[0];
}
public static bool CheckForServerConnection()
{
try
{
WebClient wc = new WebClientWithTimeout();
_ = wc.DownloadString(Properties.Settings.Default.host);
return true;
}
catch
{
return false;
}
}
public async static Task<List<int>> getInstalledGames()
{
List<int> games = new List<int>();
RegistryKey regKey = Registry.CurrentUser.OpenSubKey(Properties.Settings.Default.regestryPath + "\\Games");
var foundGames = regKey.GetSubKeyNames();
foreach (object game in foundGames)
{
games.Add(Convert.ToInt32(game));
}
Console.WriteLine();
return games;
}
public async static Task fixInstallingGames()
{
RegistryKey launcherRootReg = Registry.CurrentUser;
RegistryKey gamesRootReg = RegistryOpenCreateKey(launcherRootReg, Properties.Settings.Default.regestryPath + "\\Games");
var installedGames = await getInstalledGames();
foreach (int game in installedGames)
{
var installed = Account.CheckGameInstalled(game);
if (installed is string)
{
bool gameInstalling = Account.CheckGameInstalling(game);
if (gameInstalling)
{
Console.WriteLine("Game " + game + " in installing process! Fixing...");
await Account.UninstallGame(game, true);
}
}
}
}
public static bool ValidateRequest(JObject requestResult, bool hasSuccess = true)
{
if (requestResult.ContainsKey("success"))
{
if ((bool)requestResult["success"] == true)
{
return true;
} else
{
return false;
}
} else
{
if (hasSuccess)
{
return false;
} else
{
return true;
}
}
}
}
class WebClientWithTimeout : WebClient
{
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest wr = base.GetWebRequest(address);
wr.Timeout = 10000; // timeout in milliseconds (ms)
return wr;
}
}
class PrivateWebClientHead : WebClient
{
public bool HeadOnly { get; set; }
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest req = base.GetWebRequest(address);
if (HeadOnly && req.Method == "GET")
{
req.Method = "HEAD";
}
return req;
}
}
public class Game
{
public BitmapImage Cover { get; internal set; }
public string CoverPath { get; internal set; }
public string Title { get; internal set; }
public int ID { get; internal set; }
public float Price { get; internal set; }
public int PublisherID { get; internal set; }
public bool Installed { get; internal set; }
public string GroupingHeader { get; internal set; }
public Visibility InstalledVisibility { get; internal set; }
public Visibility OwnedVisibility { get; internal set; }
}
public enum Dimensions
{
Width,
Height
}
public enum AnchorPosition
{
Top,
Center,
Bottom,
Left,
Right
}
}