|
| 1 | +using System.IO; |
| 2 | +using System.Text; |
| 3 | +using System.Text.Json; |
| 4 | +using System.Text.RegularExpressions; |
| 5 | + |
| 6 | +namespace AddonObfuscator.Core |
| 7 | +{ |
| 8 | + public class Obfuscator |
| 9 | + { |
| 10 | + private readonly string source; |
| 11 | + private readonly string target; |
| 12 | + private readonly Formatting formatting; |
| 13 | + |
| 14 | + public Obfuscator(string source, string target, Formatting formatting = Formatting.Default) |
| 15 | + { |
| 16 | + this.source = source; |
| 17 | + this.target = target; |
| 18 | + this.formatting = formatting; |
| 19 | + } |
| 20 | + |
| 21 | + public void Run() |
| 22 | + { |
| 23 | + foreach (var filePath in Directory.GetFiles(source, "*.*", SearchOption.AllDirectories)) |
| 24 | + { |
| 25 | + var directory = Path.GetDirectoryName(filePath); |
| 26 | + if (string.IsNullOrEmpty(directory)) |
| 27 | + return; |
| 28 | + |
| 29 | + var newDirectory = Path.Combine(target, Path.GetRelativePath(source, directory)); |
| 30 | + Directory.CreateDirectory(newDirectory); |
| 31 | + |
| 32 | + var newFilePath = Path.Combine(newDirectory, Path.GetFileName(filePath)); |
| 33 | + |
| 34 | + if (Path.GetExtension(newFilePath) == ".json" && Path.GetFileNameWithoutExtension(newFilePath) != "manifest") |
| 35 | + File.WriteAllText(newFilePath, Obfuscate(ApplyFormatting(File.ReadAllText(filePath)))); |
| 36 | + else |
| 37 | + File.WriteAllText(newFilePath, File.ReadAllText(filePath)); |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + private string Obfuscate(string content) |
| 42 | + { |
| 43 | + return Regex.Replace(content, "(\"(?:.*?)\")", (match) => |
| 44 | + { |
| 45 | + var stringBuilder = new StringBuilder(); |
| 46 | + var escape = false; |
| 47 | + |
| 48 | + foreach (var character in match.Value) |
| 49 | + { |
| 50 | + stringBuilder.Append(character != '"' || escape ? $"\\u{(ushort)character:X4}" : '"'); |
| 51 | + escape = character == '\\'; |
| 52 | + } |
| 53 | + |
| 54 | + return stringBuilder.ToString(); |
| 55 | + }, RegexOptions.Compiled); |
| 56 | + } |
| 57 | + |
| 58 | + private string ApplyFormatting(string content) |
| 59 | + { |
| 60 | + switch (formatting) |
| 61 | + { |
| 62 | + case Formatting.Minify: |
| 63 | + { |
| 64 | + var options = new JsonSerializerOptions() |
| 65 | + { |
| 66 | + ReadCommentHandling = JsonCommentHandling.Skip, |
| 67 | + WriteIndented = false |
| 68 | + }; |
| 69 | + |
| 70 | + var json = JsonSerializer.Deserialize<object>(content, options); |
| 71 | + return JsonSerializer.Serialize(json, options); |
| 72 | + } |
| 73 | + |
| 74 | + default: |
| 75 | + return content; |
| 76 | + } |
| 77 | + } |
| 78 | + } |
| 79 | +} |
0 commit comments