// EarnedStats for .NET apps: .NET MAUI, Avalonia, Uno, WinUI, and Unity games on iOS and Android. // One file, no packages: copy it into the project. // // EarnedStats.Configure("SITE_ID", "com.example.app", appVersion: "1.2.0"); // EarnedStats.Screen("Home"); // EarnedStats.Track("signup", new Dictionary { ["plan"] = "pro" }); // EarnedStats.Foreground(); / EarnedStats.Background(); // from the app's lifecycle events // // Unity (2021.2 or later): add System.Text.Json to the project first (for example with NuGetForUnity), then call // Configure in a startup MonoBehaviour with dataDirectory: Application.persistentDataPath, and Background() from // OnApplicationPause(true), Foreground() from OnApplicationPause(false). // // Screens are sent as app:///. One random install id, made on first launch and kept only in the app, // makes one install one visitor. No advertising id, no device identifier. #nullable enable using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Runtime.InteropServices; using System.Text; using System.Text.Json.Nodes; using System.Threading; using System.Threading.Tasks; public static class EarnedStats { public const string SdkVersion = "1.0.0"; const int MaxQueue = 500; const long MaxAgeMs = 48L * 3_600_000; static readonly string[] CampaignKeys = { "utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content", "ref", "via" }; static readonly HttpClient Http = new HttpClient { Timeout = TimeSpan.FromSeconds(15) }; static readonly SemaphoreSlim Gate = new SemaphoreSlim(1, 1); static readonly object Lock = new object(); static List queue = new List(); static string siteId = "", appId = "", endpoint = "", dir = ""; static string? appVersion, os, device, campaign; static int screenWidth; static bool debug; static string lastScreen = "/"; static DateTime? foregroundSince; static Timer? timer; static JsonObject state = new JsonObject(); /// Start tracking. Call once at startup. /// The site id from EarnedStats, Settings, Tracking code. /// The app id the site was added with (iOS bundle id or Android package name). /// Shown as "App 1.2.0" in Browsers. MAUI: AppInfo.VersionString. Unity: Application.version. /// ios, ipados, android, macos, windows or linux. Detected when left out. /// mobile, tablet, desktop or tv. /// Where the install id and offline queue are kept. MAUI: FileSystem.AppDataDirectory. /// Unity: Application.persistentDataPath. public static void Configure(string siteId, string appId, string? appVersion = null, string host = "https://earnedstats.com", string? os = null, string? device = null, int screenWidth = 0, string? dataDirectory = null, bool debug = false) { EarnedStats.siteId = siteId; EarnedStats.appId = appId.ToLowerInvariant(); EarnedStats.appVersion = appVersion; EarnedStats.endpoint = host.TrimEnd('/') + "/api/event"; EarnedStats.os = os ?? DetectOs(); EarnedStats.device = device ?? (EarnedStats.os is "ios" or "android" ? "mobile" : EarnedStats.os == "ipados" ? "tablet" : "desktop"); EarnedStats.screenWidth = screenWidth; EarnedStats.debug = debug; dir = dataDirectory ?? Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); try { Directory.CreateDirectory(dir); } catch { } try { state = JsonNode.Parse(File.ReadAllText(Path.Combine(dir, "earnedstats.json"))) as JsonObject ?? new JsonObject(); } catch { } try { if (JsonNode.Parse(File.ReadAllText(Path.Combine(dir, "earnedstats-queue.json"))) is JsonArray arr) lock (Lock) queue = arr.OfType().Select(x => (JsonObject)x.DeepClone()).Concat(queue).ToList(); } catch { } if (state["install"] == null) { state["install"] = Guid.NewGuid().ToString(); SaveState(); } foregroundSince = DateTime.UtcNow; timer?.Dispose(); timer = new Timer(_ => _ = Flush(), null, TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(10)); _ = Flush(); } /// A screen view. "Home" is the page /Home. public static void Screen(string name, IDictionary? parameters = null) { var path = "/" + string.Join("-", name.Trim().Trim('/').Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries)); var parts = (parameters ?? new Dictionary()).Select(kv => Uri.EscapeDataString(kv.Key) + "=" + Uri.EscapeDataString(kv.Value)).ToList(); if (campaign != null) parts.Add(campaign); campaign = null; lastScreen = path; Enqueue(new JsonObject { ["t"] = "pageview", ["path"] = parts.Count > 0 ? path + "?" + string.Join("&", parts) : path }); } /// A goal or custom event, with up to 10 properties. public static void Track(string name, IDictionary? properties = null) { var e = new JsonObject { ["t"] = "goal", ["path"] = lastScreen, ["n"] = name.Length > 64 ? name.Substring(0, 64) : name }; if (properties != null && properties.Count > 0) { // Built by hand (no reflection), so it also works in trimmed and ahead of time compiled apps. var p = new JsonObject(); foreach (var kv in properties.Take(10)) p[kv.Key] = kv.Value switch { null => null, string str => JsonValue.Create(str), bool b => JsonValue.Create(b), int n => JsonValue.Create(n), long n => JsonValue.Create(n), double n => JsonValue.Create(n), float n => JsonValue.Create(n), decimal n => JsonValue.Create(n), _ => JsonValue.Create(kv.Value.ToString()), }; e["p"] = p; } Enqueue(e); } /// Tie this install to your own user, so their visits and payments show on one profile. public static void Identify(string userId, string? email = null, string? name = null) { Enqueue(new JsonObject { ["t"] = "identify", ["path"] = lastScreen, ["p"] = new JsonObject { ["user_id"] = userId, ["email"] = email, ["name"] = name } }); } /// A deep link the app was opened with: its utm_ and ref parameters credit the next screen view. public static void OpenUrl(string url) { var i = url.IndexOf('?'); if (i < 0) return; var kept = url.Substring(i + 1).Split('#')[0].Split('&').Where(p => CampaignKeys.Contains(Uri.UnescapeDataString(p.Split('=')[0]))).ToList(); if (kept.Count > 0) campaign = string.Join("&", kept); } /// This install's visitor id, known after the first event is sent. Give it to RevenueCat as es_visitor_id. public static string? VisitorId => (string?)state["visitor"]; /// Stop or resume sending (an in-app analytics opt out). Kept across launches. public static bool Enabled { get => (bool?)state["disabled"] != true; set { state["disabled"] = !value; SaveState(); if (!value) { lock (Lock) queue.Clear(); SaveQueue(); } } } /// Call when the app comes to the foreground. public static void Foreground() => foregroundSince = DateTime.UtcNow; /// Call when the app goes to the background: sends the time it was in use. public static void Background() { if (foregroundSince is DateTime since) { var ms = (long)(DateTime.UtcNow - since).TotalMilliseconds; if (ms >= 1000) Enqueue(new JsonObject { ["t"] = "ping", ["path"] = lastScreen, ["d"] = Math.Min(ms, 600_000) }); } foregroundSince = null; _ = Flush(); } static void Enqueue(JsonObject e) { if (siteId.Length == 0 || !Enabled) return; e["ts"] = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); int count; lock (Lock) { queue.Add(e); if (queue.Count > MaxQueue) queue.RemoveRange(0, queue.Count - MaxQueue); count = queue.Count; } SaveQueue(); if ((string?)e["t"] != "pageview" || count >= 20) _ = Flush(); else _ = Task.Delay(1000).ContinueWith(_ => Flush()); } /// Send what is queued now. Network failures stay queued; refused events are dropped. public static async Task Flush() { if (siteId.Length == 0 || !await Gate.WaitAsync(0)) return; try { while (true) { JsonObject? e; lock (Lock) e = queue.FirstOrDefault(); if (e == null) break; var age = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - ((long?)e["ts"] ?? 0); if (age > MaxAgeMs) { Drop(e); continue; } var meta = new JsonObject { ["i"] = (string?)state["install"], ["os"] = os, ["osv"] = Environment.OSVersion.Version.ToString(), ["dev"] = device, ["sdk"] = "dotnet/" + SdkVersion }; if (appVersion != null) meta["av"] = appVersion; var body = new JsonObject { ["w"] = siteId, ["t"] = (string?)e["t"], ["u"] = "app://" + appId + ((string?)e["path"] ?? "/"), ["m"] = meta }; if (screenWidth > 0) body["sw"] = screenWidth; if (age > 2000) body["ago"] = age; foreach (var k in new[] { "n", "p", "d" }) if (e[k] != null) body[k] = e[k]!.DeepClone(); if (debug) { Console.WriteLine("EarnedStats (debug, not sent): " + body.ToJsonString()); Drop(e); continue; } int status; try { using var req = new HttpRequestMessage(HttpMethod.Post, endpoint) { Content = new StringContent(body.ToJsonString(), Encoding.UTF8, "application/json") }; req.Headers.TryAddWithoutValidation("User-Agent", "EarnedStats-DotNet/" + SdkVersion); using var res = await Http.SendAsync(req).ConfigureAwait(false); status = (int)res.StatusCode; if (res.IsSuccessStatusCode) { try { var v = (string?)JsonNode.Parse(await res.Content.ReadAsStringAsync().ConfigureAwait(false))?["v"]; if (!string.IsNullOrEmpty(v) && v != VisitorId) { state["visitor"] = v; SaveState(); } } catch { } } } catch { status = 0; } if (status == 0 || status >= 500) break; Drop(e); } SaveQueue(); } finally { Gate.Release(); } } static void Drop(JsonObject e) { lock (Lock) queue.Remove(e); } static string DetectOs() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Create("ANDROID"))) return "android"; if (RuntimeInformation.IsOSPlatform(OSPlatform.Create("IOS"))) return "ios"; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) return "windows"; if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) return "macos"; if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) return "linux"; return "other"; } static void SaveState() { try { File.WriteAllText(Path.Combine(dir, "earnedstats.json"), state.ToJsonString()); } catch { } } static void SaveQueue() { string json; lock (Lock) json = new JsonArray(queue.Select(x => (JsonNode)x.DeepClone()).ToArray()).ToJsonString(); try { File.WriteAllText(Path.Combine(dir, "earnedstats-queue.json"), json); } catch { } } }