-
Notifications
You must be signed in to change notification settings - Fork 10
/
ApiDumpTool.cs
562 lines (443 loc) · 17.9 KB
/
ApiDumpTool.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
using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using RobloxDeployHistory;
using Microsoft.Win32;
#pragma warning disable IDE1006 // Naming Styles
namespace RobloxApiDumpTool
{
public partial class ApiDumpTool : Form
{
public static RegistryKey VersionRegistry => Program.GetMainRegistryKey("Current Versions");
private const string API_DUMP_CSS_FILE = "api-dump.css";
private const string LIVE = Program.LIVE;
private delegate void StatusDelegate(string msg);
private delegate string ItemDelegate(ComboBox comboBox);
private static readonly WebClient http = new WebClient();
private static TaskCompletionSource<Bitmap> renderFinished;
public ApiDumpTool()
{
InitializeComponent();
}
private string getSelectedItem(ComboBox comboBox)
{
object result;
if (InvokeRequired)
{
ItemDelegate itemDelegate = new ItemDelegate(getSelectedItem);
result = Invoke(itemDelegate, comboBox);
}
else
{
result = comboBox.SelectedItem;
}
return result?.ToString() ?? LIVE;
}
private Channel getChannel()
{
return "LIVE";
// return getSelectedItem(channel);
}
private string getApiDumpFormat()
{
return getSelectedItem(apiDumpFormat);
}
private void loadSelectedIndex(ComboBox comboBox, string registryKey)
{
string value = Program.GetRegistryString(registryKey);
comboBox.SelectedIndex = Math.Max(0, comboBox.Items.IndexOf(value));
}
private void updateEnabledStates()
{
try
{
string format = getApiDumpFormat();
viewApiDump.Enabled = (format != "PNG");
compareVersions.Enabled = (format != "JSON");
}
catch
{
// ¯\_(ツ)_/¯
}
}
public static async Task<DeployLog> GetLastDeployLog(Channel channel)
{
var history = await StudioDeployLogs.Get(channel);
var latestDeploy = history.CurrentLogs_x64
.OrderBy(log => log.TimeStamp)
.Last();
return latestDeploy;
}
public static async Task<string> GetVersion(Channel channel)
{
var log = await GetLastDeployLog(channel);
return log.VersionGuid;
}
private void setStatus(string msg = "")
{
if (InvokeRequired)
{
StatusDelegate status = new StatusDelegate(setStatus);
Invoke(status, msg);
}
else
{
status.Text = "Status: " + msg;
status.Refresh();
}
}
private async Task lockWindowAndRunTask(Func<Task> task)
{
Enabled = false;
UseWaitCursor = true;
await Task.Run(task);
Enabled = true;
UseWaitCursor = false;
setStatus("Ready!");
}
private static bool writeFile(string path, string contents)
{
if (!File.Exists(path) || File.ReadAllText(path, Encoding.UTF8) != contents)
{
File.WriteAllText(path, contents, Encoding.UTF8);
return true;
}
return false;
}
private static void writeAndViewFile(string path, string contents)
{
writeFile(path, contents);
Process.Start(path);
}
private static Bitmap renderApiDumpImpl(WebBrowser browser)
{
var body = browser.Document.Body;
body.Style = "zoom:150%";
const int extraWidth = 21;
Rectangle size = body.ScrollRectangle;
int width = size.Width + extraWidth;
browser.Width = width + 8;
int height = size.Height;
browser.Height = height + 24;
Bitmap apiRender = new Bitmap(width, height);
browser.DrawToBitmap(apiRender, size);
// Fill in some extra space on the right that we missed.
using (Graphics graphics = Graphics.FromImage(apiRender))
{
Color backColor = apiRender.GetPixel(0, 0);
using (Brush brush = new SolidBrush(backColor))
{
Rectangle fillArea = new Rectangle
(
width - extraWidth, 0,
extraWidth, height
);
graphics.FillRectangle(brush, fillArea);
}
}
// Apply some random noise and transparency to the edges.
// Doing this so websites like Twitter can't force the image
// to use lossy compression. Its a nice little hack :)
Random rng = new Random();
var addNoise = new Action<int, int>((x, y) =>
{
const int alpha = (224 << 24);
int lum = 10 + (int)(rng.NextDouble() * 30);
int argb = alpha | (lum << 16) | (lum << 8) | lum;
Color pixel = Color.FromArgb(argb);
apiRender.SetPixel(x, y, pixel);
});
for (int x = 0; x < width; x++)
{
addNoise(x, 0);
addNoise(x, height - 1);
}
for (int y = 0; y < height; y++)
{
addNoise(0, y);
addNoise(width - 1, y);
}
return apiRender;
}
private static void onDocumentComplete(object sender, WebBrowserDocumentCompletedEventArgs e)
{
var browser = sender as WebBrowser;
Bitmap image = renderApiDumpImpl(browser);
renderFinished.SetResult(image);
browser.Dispose();
Application.ExitThread();
}
public static string GetWorkDirectory()
{
string localAppData = Environment.GetEnvironmentVariable("LocalAppData");
string workDir = Path.Combine(localAppData, "RobloxApiDumpFiles");
Directory.CreateDirectory(workDir);
return workDir;
}
public static string PostProcessHtml(string result, string workDir = "")
{
// Preload the API Dump CSS file.
if (workDir == "")
workDir = GetWorkDirectory();
string apiDumpCss = Path.Combine(workDir, API_DUMP_CSS_FILE);
File.WriteAllText(apiDumpCss, Properties.Resources.ApiDumpStyler);
return "<head>\n"
+ "\t<link rel=\"stylesheet\" href=\"" + API_DUMP_CSS_FILE + "\">\n"
+ "</head>\n\n"
+ result.Trim();
}
public static async Task<Bitmap> RenderApiDump(string htmlFilePath)
{
var docReady = new WebBrowserDocumentCompletedEventHandler(onDocumentComplete);
string fileUrl = "file://" + htmlFilePath.Replace('\\', '/');
Thread renderThread = new Thread(() =>
{
var renderer = new WebBrowser()
{
Url = new Uri(fileUrl),
ScrollBarsEnabled = false,
};
renderer.DocumentCompleted += docReady;
Application.Run();
});
renderFinished = new TaskCompletionSource<Bitmap>();
renderThread.SetApartmentState(ApartmentState.STA);
renderThread.Start();
await renderFinished.Task;
var apiRender = renderFinished.Task.Result;
return apiRender;
}
public static async Task<string> GetApiDumpFilePath(Channel channel, string versionGuid, bool full, Action<string> setStatus = null)
{
string coreBin = GetWorkDirectory();
string fileName = full ? "Full-API-Dump" : "API-Dump";
string apiUrl = $"{channel.BaseUrl}/{versionGuid}-{fileName}.json";
string file = Path.Combine(coreBin, $"{versionGuid}-{fileName}.json");
if (!File.Exists(file))
{
setStatus?.Invoke("Grabbing API Dump for " + channel);
string apiDump = await http.DownloadStringTaskAsync(apiUrl);
File.WriteAllText(file, apiDump);
}
else
{
setStatus?.Invoke("Already up to date!");
}
return file;
}
public static async Task<string> GetApiDumpFilePath(Channel channel, int versionId, bool full, Action<string> setStatus = null)
{
setStatus?.Invoke("Fetching deploy logs for " + channel);
var logs = await StudioDeployLogs.Get(channel);
var deployLog = logs.CurrentLogs_x64
.Where(log => log.Version == versionId)
.OrderBy(log => log.Changelist)
.LastOrDefault();
if (deployLog == null)
throw new Exception("Unknown version id: " + versionId);
string versionGuid = deployLog.VersionGuid;
return await GetApiDumpFilePath(channel, versionGuid, full, setStatus);
}
public static async Task<string> GetApiDumpFilePath(Channel channel, bool full, Action<string> setStatus = null, bool fetchPrevious = false)
{
setStatus?.Invoke("Checking for update...");
string versionGuid = await GetVersion(channel);
if (fetchPrevious)
versionGuid = await ReflectionHistory.GetPreviousVersionGuid(channel, versionGuid);
string file = await GetApiDumpFilePath(channel, versionGuid, full, setStatus);
if (fetchPrevious)
channel += "-prev";
VersionRegistry.SetValue(channel, versionGuid);
clearOldVersionFiles();
return file;
}
private async Task<string> getApiDumpFilePath(Channel channel, bool full, bool fetchPrevious = false)
{
return await GetApiDumpFilePath(channel, full, setStatus, fetchPrevious);
}
private void channel_SelectedIndexChanged(object sender, EventArgs e)
{
Channel channel = getChannel();
if (channel.Equals(LIVE))
compareVersions.Text = "Compare Previous Version";
else
compareVersions.Text = "Compare to Production";
Program.MainRegistry.SetValue("LastSelectedChannel", channel);
updateEnabledStates();
}
private async void viewApiDumpClassic_Click(object sender, EventArgs e)
{
await lockWindowAndRunTask(async () =>
{
var channel = getChannel();
string format = getApiDumpFormat();
string apiFilePath = await getApiDumpFilePath(channel, fullDump.Checked);
if (format == "JSON")
{
Process.Start(apiFilePath);
return;
}
var api = new ReflectionDatabase(apiFilePath);
var dumper = new ReflectionDumper(api);
string result;
if (format == "HTML" || format == "PNG")
result = dumper.DumpApi(ReflectionDumper.DumpUsingHtml, PostProcessHtml);
else
result = dumper.DumpApi(ReflectionDumper.DumpUsingTxt);
FileInfo info = new FileInfo(apiFilePath);
string directory = info.DirectoryName;
string resultPath = Path.Combine(directory, channel + "-api-dump." + format.ToLower());
writeAndViewFile(resultPath, result);
});
}
private async void compareVersions_Click(object sender, EventArgs e)
{
await lockWindowAndRunTask(async () =>
{
Channel newChannel = getChannel();
bool fetchPrevious = newChannel.Equals(LIVE);
bool full = fullDump.Checked;
string newApiFilePath = await getApiDumpFilePath(newChannel, full);
string oldApiFilePath = await getApiDumpFilePath(LIVE, full, fetchPrevious);
var latestLog = await GetLastDeployLog(newChannel);
string version = latestLog.VersionId;
setStatus($"Reading the {(fetchPrevious ? "Previous" : "Production")} API...");
var oldApi = new ReflectionDatabase(oldApiFilePath, LIVE, version);
setStatus($"Reading the {(fetchPrevious ? "Production" : "New")} API...");
var newApi = new ReflectionDatabase(newApiFilePath, newChannel, version);
setStatus("Comparing APIs...");
string format = getApiDumpFormat();
string result = ReflectionDiffer.CompareDatabases(oldApi, newApi, format);
if (result.Length > 0)
{
FileInfo info = new FileInfo(newApiFilePath);
string dirName = info.DirectoryName;
string fileBase = Path.Combine(dirName, $"{newChannel}-diff.");
string filePath = fileBase + format.ToLower();
if (format == "PNG")
{
string htmlPath = $"{fileBase}.html";
writeFile(htmlPath, result);
setStatus("Rendering Image...");
Bitmap apiRender = await RenderApiDump(htmlPath);
apiRender.Save(filePath);
Process.Start(filePath);
}
else
{
writeAndViewFile(filePath, result);
}
}
else
{
MessageBox.Show("No differences were found!", "Well, this is awkward...", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
clearOldVersionFiles();
});
}
private static void clearOldVersionFiles()
{
string workDir = GetWorkDirectory();
string[] activeVersions = VersionRegistry.GetValueNames()
.Select(channel => Program.GetRegistryString(VersionRegistry, channel))
.ToArray();
string[] oldFiles = Directory.GetFiles(workDir, "version-*.json")
.Select(file => new FileInfo(file))
.Where(fileInfo => !activeVersions.Contains(fileInfo.Name.Substring(0, 24)))
.Select(fileInfo => fileInfo.FullName)
.ToArray();
foreach (string oldFile in oldFiles)
{
try
{
File.Delete(oldFile);
}
catch
{
Console.WriteLine("Could not delete file {0}", oldFile);
}
}
}
private async Task initVersionCache()
{
await lockWindowAndRunTask(async () =>
{
string[] channels = channel.Items.Cast<string>().ToArray();
setStatus("Initializing version cache...");
foreach (string channelName in channels)
{
string versionGuid = await GetVersion(channelName);
VersionRegistry.SetValue(channelName, versionGuid);
}
Program.MainRegistry.SetValue("InitializedChannels", true);
});
}
private async void ApiDumpTool_Load(object sender, EventArgs e)
{
WebRequest.DefaultWebProxy = null;
if (!Program.GetRegistryBool("InitializedChannels"))
{
await initVersionCache();
clearOldVersionFiles();
}
loadSelectedIndex(channel, "LastSelectedChannel");
loadSelectedIndex(apiDumpFormat, "PreferredFormat");
}
private void apiDumpFormat_SelectedIndexChanged(object sender, EventArgs e)
{
string format = getApiDumpFormat();
Program.MainRegistry.SetValue("PreferredFormat", format);
updateEnabledStates();
}
private async void channel_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode != Keys.Enter)
return;
Channel input = channel.Text;
e.SuppressKeyPress = true;
foreach (var item in channel.Items)
{
Channel old = item.ToString();
if (old.Name == input.Name)
{
channel.SelectedItem = item;
return;
}
}
try
{
var logs = await StudioDeployLogs.Get(input);
if (logs.CurrentLogs_x64.Any())
{
var addItem = new Action(() =>
{
var index = channel.Items.Add(channel.Text);
channel.SelectedIndex = index;
});
Invoke(addItem);
return;
}
throw new Exception("No channels to work with!");
}
catch
{
var reset = new Action(() => channel.SelectedIndex = 0);
MessageBox.Show
(
$"Channel '{input}' had no valid data on Roblox's CDN!",
"Invalid channel!",
MessageBoxButtons.OK,
MessageBoxIcon.Error
);
Invoke(reset);
}
}
}
}