Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
158 lines (145 loc) · 6.72 KB
/
Copy pathProgram.cs
File metadata and controls
158 lines (145 loc) · 6.72 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
// IntuneBlockJob: turn an exported list of detected apps into block lists.
//
// dotnet run --project examples/IntuneBlockJob -- \
// --in discovered-apps.csv --column "Bundle ID" \
// --block "Social Networking,Streaming Media" --max-age 12 --out ./out
//
// Writes out/ios-bundle-ids.txt, out/android-packages.txt and out/report.csv.
// The key is read from APPBLOCKLIST_API_KEY. Exit codes: 0 done, 2 bad
// arguments or key, 3 monthly lookups used up (partial output is written).
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using AppBlockList;
internal static class Program
{
private static async Task<int> Main(string[] args)
{
var opts = ParseArgs(args);
if (!opts.TryGetValue("in", out var input) || !File.Exists(input))
{
Console.Error.WriteLine("usage: IntuneBlockJob --in <csv> [--column <header>] [--block \"A,B\"] [--max-age 12] [--out <dir>]");
return 2;
}
var blocked = (opts.TryGetValue("block", out var b) ? b : "Social Networking,Streaming Media")
.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
int? maxAge = opts.TryGetValue("max-age", out var m) && int.TryParse(m.TrimEnd('+'), out var age) ? age : null;
var outDir = opts.TryGetValue("out", out var o) ? o : ".";
Directory.CreateDirectory(outDir);
var ids = ReadIds(input, opts.TryGetValue("column", out var c) ? c : null);
Console.WriteLine($"{ids.Count} rows read from {input}");
using var cts = new CancellationTokenSource(TimeSpan.FromHours(2));
using var client = new AppBlockListClient();
var ios = new SortedSet<string>(StringComparer.Ordinal);
var android = new SortedSet<string>(StringComparer.Ordinal);
var report = new StringBuilder("id,found,name,developer,age_rating,categories,verdict,reason\n");
var exitCode = 0;
var checkedCount = 0;
try
{
await foreach (var outcome in client.LookupManyAsync(ids, TimeSpan.FromMilliseconds(100), cts.Token))
{
checkedCount++;
var (verdict, reason) = Decide(outcome, blocked, maxAge);
var app = outcome.App;
if (verdict == "block" && app is not null)
{
if (!string.IsNullOrEmpty(app.BundleId)) ios.Add(app.BundleId);
if (app.IsOnGooglePlay) android.Add(app.AndroidPackage);
}
report.AppendLine(string.Join(",", new[]
{
Csv(outcome.Id), (app?.Found ?? false).ToString(CultureInfo.InvariantCulture).ToLowerInvariant(),
Csv(app?.Name), Csv(app?.Developer), Csv(app?.AgeRating),
Csv(app is null ? "" : string.Join("; ", app.FilteringCategories)), verdict, Csv(reason),
}));
}
}
catch (QuotaExceededException e)
{
Console.Error.WriteLine($"Monthly lookups used up ({e.MonthlyLookups}); writing partial output.");
exitCode = 3;
}
catch (AppBlockListException e) when (e.StatusCode == 401 || e.StatusCode == 0)
{
Console.Error.WriteLine("Check APPBLOCKLIST_API_KEY: " + e.Message);
return 2;
}
await File.WriteAllLinesAsync(Path.Combine(outDir, "ios-bundle-ids.txt"), ios);
await File.WriteAllLinesAsync(Path.Combine(outDir, "android-packages.txt"), android);
await File.WriteAllTextAsync(Path.Combine(outDir, "report.csv"), report.ToString());
Console.WriteLine($"{checkedCount} apps checked: {ios.Count} iOS and {android.Count} Android IDs to block.");
return exitCode;
}
private static (string Verdict, string Reason) Decide(LookupOutcome o, string[] blocked, int? maxAge)
{
if (!o.IsOk) return ("error", o.Error!.Message);
var app = o.App!;
if (!app.Found) return ("unknown", app.Message ?? "");
if (app.InCategory(blocked)) return ("block", "category " + app.PrimaryCategory);
if (maxAge is int max && app.MinimumAge is int min && min > max) return ("block", "age rating " + app.AgeRating);
return ("allow", "");
}
/// <summary>Reads the ID column. Without --column, picks the first header that mentions a bundle, package or app ID.</summary>
private static List<string> ReadIds(string path, string? column)
{
using var reader = new StreamReader(path, detectEncodingFromByteOrderMarks: true);
var header = SplitCsvLine(reader.ReadLine() ?? "");
int index = column is not null
? header.FindIndex(h => string.Equals(h.Trim(), column, StringComparison.OrdinalIgnoreCase))
: header.FindIndex(h =>
{
var l = h.ToLowerInvariant();
return l.Contains("bundle") || l.Contains("package") || l.Contains("app id") || l.Contains("application id");
});
if (index < 0) throw new InvalidOperationException($"ID column not found in header: {string.Join(" | ", header)}");
var ids = new List<string>();
string? line;
while ((line = reader.ReadLine()) is not null)
{
var cells = SplitCsvLine(line);
if (index < cells.Count && !string.IsNullOrWhiteSpace(cells[index])) ids.Add(cells[index].Trim());
}
return ids;
}
private static List<string> SplitCsvLine(string line)
{
var cells = new List<string>();
var cell = new StringBuilder();
var quoted = false;
for (var i = 0; i < line.Length; i++)
{
var ch = line[i];
if (quoted)
{
if (ch == '"' && i + 1 < line.Length && line[i + 1] == '"') { cell.Append('"'); i++; }
else if (ch == '"') quoted = false;
else cell.Append(ch);
}
else if (ch == '"') quoted = true;
else if (ch == ',') { cells.Add(cell.ToString()); cell.Clear(); }
else cell.Append(ch);
}
cells.Add(cell.ToString());
return cells;
}
private static string Csv(string? s)
{
s ??= "";
return s.IndexOfAny(new[] { ',', '"', '\n' }) >= 0 ? "\"" + s.Replace("\"", "\"\"") + "\"" : s;
}
private static Dictionary<string, string> ParseArgs(string[] args)
{
var d = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
for (var i = 0; i + 1 < args.Length; i += 2)
{
if (args[i].StartsWith("--", StringComparison.Ordinal)) d[args[i].Substring(2)] = args[i + 1];
}
return d;
}
}