-
Notifications
You must be signed in to change notification settings - Fork 815
Expand file tree
/
Copy pathTelemetryHandler.cs
More file actions
378 lines (320 loc) · 12.7 KB
/
TelemetryHandler.cs
File metadata and controls
378 lines (320 loc) · 12.7 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
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
using System.Net.Http.Headers;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
using UniGetUI.Core.Data;
using UniGetUI.Core.Language;
using UniGetUI.Core.Logging;
using UniGetUI.Core.SettingsEngine;
using UniGetUI.Core.Tools;
using UniGetUI.PackageEngine;
using UniGetUI.PackageEngine.Enums;
using UniGetUI.PackageEngine.Interfaces;
namespace UniGetUI.Interface.Telemetry;
public enum TEL_InstallReferral
{
DIRECT_SEARCH,
FROM_BUNDLE,
ALREADY_INSTALLED,
}
public enum TEL_OP_RESULT
{
SUCCESS,
FAILED,
CANCELED,
}
public static class TelemetryHandler
{
private const string OpenSearchUrl = "https://telemetry2.devolutions.net:9200";
private static string _openSearchUsername = "";
private static string _openSearchPassword = "";
private static bool _credentialsWarningLogged;
internal static Func<HttpRequestMessage, Task<HttpResponseMessage>>? TestSendAsyncOverride;
public static void Configure(string username, string password)
{
_openSearchUsername = username;
_openSearchPassword = password;
}
private static bool CredentialsConfigured()
{
if (!string.IsNullOrEmpty(_openSearchUsername)
&& !_openSearchUsername.EndsWith("_UNSET")
&& !string.IsNullOrEmpty(_openSearchPassword)
&& !_openSearchPassword.EndsWith("_UNSET"))
return true;
if (!_credentialsWarningLogged)
{
Logger.Warn("[Telemetry] OpenSearch credentials are not configured — telemetry is disabled for this build.");
_credentialsWarningLogged = true;
}
return false;
}
// Index names — to be created on the OpenSearch server
private const string IndexActivity = "unigetui_activity_events";
private const string IndexPackage = "unigetui_package_events";
private const string IndexBundle = "unigetui_bundle_events";
#if DEBUG
private const string IndexPrefix = "dev-";
#else
private const string IndexPrefix = "";
#endif
private static readonly HttpClient _httpClient;
static TelemetryHandler()
{
_httpClient = new HttpClient(CoreTools.GenericHttpClientParameters)
{
Timeout = TimeSpan.FromSeconds(30),
};
_httpClient.DefaultRequestHeaders.UserAgent.ParseAdd(CoreData.UserAgentString);
}
private static readonly Settings.K[] SettingsToSend =
[
Settings.K.DisableAutoUpdateWingetUI,
Settings.K.EnableUniGetUIBeta,
Settings.K.DisableSystemTray,
Settings.K.DisableNotifications,
Settings.K.DisableAutoCheckforUpdates,
Settings.K.AutomaticallyUpdatePackages,
Settings.K.AskToDeleteNewDesktopShortcuts,
Settings.K.EnablePackageBackup_LOCAL,
Settings.K.DoCacheAdminRights,
Settings.K.DoCacheAdminRightsForBatches,
Settings.K.ForceLegacyBundledWinGet,
Settings.K.UseSystemChocolatey,
];
// -------------------------------------------------------------------------
public static async Task InitializeAsync()
{
try
{
if (Settings.Get(Settings.K.DisableTelemetry))
return;
await CoreTools.WaitForInternetConnection();
string[] enabledManagers = PEInterface.Managers
.Where(m => m.IsEnabled())
.Select(m => m.Name)
.ToArray();
string[] foundManagers = PEInterface.Managers
.Where(m => m.IsEnabled() && m.Status.Found)
.Select(m => m.Name)
.ToArray();
var ev = new UniGetUIActivityEvent
{
InstallID = GetRandomizedId(),
Locale = LanguageEngine.SelectedLocale,
EnabledManagers = enabledManagers,
FoundManagers = foundManagers,
ActiveSettings = ComputeActiveSettingsBitmask(),
Application = BuildApplicationInfo(),
Platform = BuildPlatformInfo(),
};
await PostToOpenSearchAsync(IndexActivity, ev, TelemetrySerializerContext.Trimming.UniGetUIActivityEvent);
}
catch (Exception ex)
{
Logger.Error("[Telemetry] Hard crash in InitializeAsync");
Logger.Error(ex);
}
}
internal static int ComputeActiveSettingsBitmask()
{
int settingsMagicValue = 0;
int mask = 0x1;
foreach (var setting in SettingsToSend)
{
bool enabled = Settings.Get(
key: setting,
invert: Settings.ResolveKey(setting).StartsWith("Disable"));
if (enabled)
settingsMagicValue |= mask;
mask <<= 1;
if (mask == 0x1)
throw new OverflowException();
}
foreach (var sp in new[] { "SP1", "SP2" })
{
bool enabled = sp switch
{
"SP1" => File.Exists("ForceUniGetUIPortable"),
"SP2" => CoreData.WasDaemon,
_ => throw new NotImplementedException(),
};
if (enabled)
settingsMagicValue |= mask;
mask <<= 1;
if (mask == 0x1)
throw new OverflowException();
}
return settingsMagicValue;
}
internal static void ResetTestState()
{
_openSearchUsername = "";
_openSearchPassword = "";
_credentialsWarningLogged = false;
TestSendAsyncOverride = null;
}
// -------------------------------------------------------------------------
public static void InstallPackage(
IPackage package,
TEL_OP_RESULT status,
TEL_InstallReferral source
) => _ = TrackPackageEventAsync(package, "install", status, source.ToString());
public static void UpdatePackage(IPackage package, TEL_OP_RESULT status) =>
_ = TrackPackageEventAsync(package, "update", status);
public static void DownloadPackage(
IPackage package,
TEL_OP_RESULT status,
TEL_InstallReferral source
) => _ = TrackPackageEventAsync(package, "download", status, source.ToString());
public static void UninstallPackage(IPackage package, TEL_OP_RESULT status) =>
_ = TrackPackageEventAsync(package, "uninstall", status);
public static void PackageDetails(IPackage package, string eventSource) =>
_ = TrackPackageEventAsync(package, "details", eventSource: eventSource);
private static async Task TrackPackageEventAsync(
IPackage package,
string operation,
TEL_OP_RESULT? result = null,
string? eventSource = null)
{
try
{
if (result is null && eventSource is null)
throw new ArgumentException("result and eventSource cannot both be null");
if (Settings.Get(Settings.K.DisableTelemetry))
return;
await CoreTools.WaitForInternetConnection();
var ev = new UniGetUIPackageEvent
{
InstallID = GetRandomizedId(),
Locale = LanguageEngine.SelectedLocale,
Application = BuildApplicationInfo(),
Platform = BuildPlatformInfo(),
Operation = operation,
PackageId = package.Id,
ManagerName = package.Manager.Name,
SourceName = package.Source.Name,
OperationResult = result?.ToString(),
EventSource = eventSource,
};
await PostToOpenSearchAsync(IndexPackage, ev, TelemetrySerializerContext.Trimming.UniGetUIPackageEvent);
}
catch (Exception ex)
{
Logger.Error($"[Telemetry] Hard crash in TrackPackageEventAsync ({operation})");
Logger.Error(ex);
}
}
// -------------------------------------------------------------------------
public static void ImportBundle(BundleFormatType type) =>
_ = TrackBundleEventAsync("import", type.ToString());
public static void ExportBundle(BundleFormatType type) =>
_ = TrackBundleEventAsync("export", type.ToString());
public static void ExportBatch() =>
_ = TrackBundleEventAsync("export", "PS1_SCRIPT");
private static async Task TrackBundleEventAsync(string operation, string bundleType)
{
try
{
if (Settings.Get(Settings.K.DisableTelemetry))
return;
await CoreTools.WaitForInternetConnection();
var ev = new UniGetUIBundleEvent
{
InstallID = GetRandomizedId(),
Locale = LanguageEngine.SelectedLocale,
Application = BuildApplicationInfo(),
Platform = BuildPlatformInfo(),
Operation = operation,
BundleType = bundleType,
};
await PostToOpenSearchAsync(IndexBundle, ev, TelemetrySerializerContext.Trimming.UniGetUIBundleEvent);
}
catch (Exception ex)
{
Logger.Error($"[Telemetry] Hard crash in TrackBundleEventAsync ({operation})");
Logger.Error(ex);
}
}
// ─── OpenSearch HTTP ──────────────────────────────────────────────────────
private static async Task PostToOpenSearchAsync<T>(string indexName, T eventData, JsonTypeInfo<T> typeInfo)
{
if (!CredentialsConfigured())
return;
try
{
string fullIndex = IndexPrefix + indexName;
string json = JsonSerializer.Serialize(eventData, typeInfo);
string credentials = Convert.ToBase64String(
Encoding.UTF8.GetBytes($"{_openSearchUsername}:{_openSearchPassword}"));
using var content = new StringContent(json, Encoding.UTF8, "application/json");
using var request = new HttpRequestMessage(HttpMethod.Post, $"{OpenSearchUrl}/{fullIndex}/_doc")
{
Content = content,
};
request.Headers.Authorization = new AuthenticationHeaderValue("Basic", credentials);
HttpResponseMessage response = TestSendAsyncOverride is { } sendAsync
? await sendAsync(request)
: await _httpClient.SendAsync(request);
if (response.IsSuccessStatusCode)
Logger.Debug($"[Telemetry] Sent to {fullIndex}");
else
Logger.Warn($"[Telemetry] {fullIndex} returned {(int)response.StatusCode}");
}
catch (Exception ex)
{
Logger.Error($"[Telemetry] Hard crash posting to {indexName}");
Logger.Error(ex);
}
}
// ─── Helpers ─────────────────────────────────────────────────────────────
private static string GetRandomizedId()
{
string id = Settings.GetValue(Settings.K.TelemetryClientToken);
if (id.Length != 64)
{
id = CoreTools.RandomString(64);
Settings.SetValue(Settings.K.TelemetryClientToken, id);
}
return id;
}
private static TelemetryApplicationInfo BuildApplicationInfo() =>
new()
{
Name = "UniGetUI",
Version = CoreData.VersionName,
DataSource = "NotApplicable",
Pricing = "Free",
Language = LanguageEngine.SelectedLocale,
ArchitectureType = RuntimeInformation.ProcessArchitecture.ToString(),
};
private static TelemetryPlatformInfo BuildPlatformInfo() =>
new()
{
Name = GetPlatformName(),
Version = Environment.OSVersion.VersionString,
Architecture = RuntimeInformation.OSArchitecture.ToString(),
};
private static string GetPlatformName()
{
if (OperatingSystem.IsWindows()) return "Windows";
if (OperatingSystem.IsMacOS()) return "Mac";
return "Linux";
}
}
// Source-generated JSON context — required for AOT/trimmed builds (WinUI).
// Reflection-based serialization is disabled in that configuration.
[JsonSourceGenerationOptions(DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)]
[JsonSerializable(typeof(UniGetUIActivityEvent))]
[JsonSerializable(typeof(UniGetUIPackageEvent))]
[JsonSerializable(typeof(UniGetUIBundleEvent))]
internal partial class TelemetrySerializerContext : JsonSerializerContext
{
internal static readonly TelemetrySerializerContext Trimming =
new(new JsonSerializerOptions(SerializationHelpers.DefaultOptions)
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
});
}