// Pair a table device with packeroo: ask for a code, show it, keep the token, wait until // someone enters the code in the app. .NET 8 or newer, no packages. // // dotnet run // // PACKEROO_BASE_URL API address, default the sandbox https://api.qm.packeroo.com/api/v1 // PACKEROO_TOKEN_FILE where the token is kept, default ~/.config/packeroo/device-token // PACKEROO_POLL_SECONDS seconds between two GET /device, default 5 using System.Globalization; using System.Net; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; // What the device shows, in the language of the location. var TEXT = new { Code = "Code am Tisch: {0} (gilt bis {1:HH:mm} Uhr)", Link = "QR-Code mit diesem Link: {0}", Enter = "Code eingeben in der packeroo-App unter Profil › Organisation › Tische, dort am Tisch „Gerät verbinden“, oder den QR-Code mit dem Handy scannen.", Expired = "Der Code ist abgelaufen. Ich hole einen neuen.", Unpaired = "Das gespeicherte Token gilt nicht mehr. Ich hole einen neuen Code.", Off = "Tischgeräte sind bei packeroo gerade ausgeschaltet. Neuer Versuch in 60 s.", Offline = "Keine Verbindung ({0}), neuer Versuch in {1} s", Paired = "Verbunden mit {0} ({1})", NoLocation = "ohne Standort", Error = "Fehler {0} {1}: {2}", Unexpected = "unerwartete Antwort", }; var baseUrl = (Environment.GetEnvironmentVariable("PACKEROO_BASE_URL") ?? "https://api.qm.packeroo.com/api/v1").TrimEnd('/'); var tokenFile = Environment.GetEnvironmentVariable("PACKEROO_TOKEN_FILE") ?? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".config", "packeroo", "device-token"); var pollSeconds = double.Parse(Environment.GetEnvironmentVariable("PACKEROO_POLL_SECONDS") ?? "5", CultureInfo.InvariantCulture); // After errors in a row the pause doubles, up to this many seconds. const double MaxPauseSeconds = 60; using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(30) }; // Every request names the device: product and firmware. http.DefaultRequestHeaders.UserAgent.ParseAdd("Kickertisch-Beispiel/1.0"); http.DefaultRequestHeaders.Accept.ParseAdd("application/json"); http.DefaultRequestHeaders.AcceptLanguage.ParseAdd("de"); var token = File.Exists(tokenFile) ? File.ReadAllText(tokenFile).Trim() : null; if (string.IsNullOrEmpty(token)) token = null; // With a stored token, ask first whether it still signs in; null after a 401. var device = token is null ? null : await WaitForPairing(token, null); while (device is null) { var (newToken, expiresAt) = await RequestCode(token); token = newToken; device = await WaitForPairing(token, expiresAt); if (device is null && expiresAt is null) { // Paired a moment ago, unpaired now: this token is of no use any more. Console.WriteLine(TEXT.Unpaired); token = null; } else if (device is null) Console.WriteLine(TEXT.Expired); } var d = device.Value; Console.WriteLine(TEXT.Paired, d.GetProperty("table").GetProperty("name").GetString(), d.GetProperty("location").GetProperty("name").GetString() ?? TEXT.NoLocation); // One request to the API. Network errors are retried. async Task<(HttpStatusCode Status, JsonElement Json, HttpResponseHeaders Headers)> Call(HttpMethod method, string path, string? bearer, object? body = null, string? idempotencyKey = null) { for (var failures = 1; ; failures++) { using var request = new HttpRequestMessage(method, baseUrl + path); if (bearer is not null) request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", bearer); // A write carries an Idempotency-Key; a retry of the same request sends the same key. if (idempotencyKey is not null) request.Headers.Add("Idempotency-Key", idempotencyKey); if (body is not null) request.Content = JsonContent.Create(body); try { using var response = await http.SendAsync(request); return (response.StatusCode, ParseJson(await response.Content.ReadAsStringAsync()), response.Headers); } catch (Exception error) when (error is HttpRequestException or TaskCanceledException) { await PauseAfterError(failures, error.Message); } } } // The body as JSON; empty when there is none or it is no JSON, such as the error page of a proxy. static JsonElement ParseJson(string text) { try { return text.Length > 0 ? JsonDocument.Parse(text).RootElement.Clone() : default; } catch (JsonException) { return default; } } // Waits after a network error, a 5xx or an unexpected answer: pollSeconds, doubled with every error // in a row, at most MaxPauseSeconds. A device never asks again without a pause. async Task PauseAfterError(int failures, string reason) { var seconds = Math.Min(pollSeconds * Math.Pow(2, failures - 1), MaxPauseSeconds); Console.Error.WriteLine(TEXT.Offline, reason, seconds); await Task.Delay(TimeSpan.FromSeconds(seconds)); } // Asks for a code. Returns the token and when the code runs out; null when the token is paired already. async Task<(string? Token, DateTimeOffset? ExpiresAt)> RequestCode(string? bearer) { var key = Guid.NewGuid().ToString(); var failures = 0; while (true) { var (status, json, headers) = await Call(HttpMethod.Post, "/device-pairings", bearer, new { model = "Kickertisch-Beispiel", firmware = "1.0" }, key); if (status == HttpStatusCode.Created) { var data = json.GetProperty("data"); var newToken = data.GetProperty("token").GetString()!; // Shown only this once: keep it before anything else. SaveToken(newToken); var code = data.GetProperty("code").GetString()!; var expiresAt = DateTimeOffset.Parse(data.GetProperty("expires_at").GetString()!, CultureInfo.InvariantCulture); ShowCode(code, expiresAt); return (newToken, expiresAt); } var problem = ProblemCode(json); if (status == HttpStatusCode.Conflict && problem == "device_already_paired") return (bearer, null); if (status == HttpStatusCode.Conflict && problem == "table_devices_off") { Console.WriteLine(TEXT.Off); await Task.Delay(TimeSpan.FromSeconds(60)); } else if (status == HttpStatusCode.TooManyRequests) await Task.Delay(RetryAfter(headers)); // The API is busy or being deployed: the same request with the same key, after a pause. else if ((int)status >= 500) await PauseAfterError(++failures, $"HTTP {(int)status}"); else Fail(status, json); } } // GET /device until it answers 200. Null once the code has run out, or at once when no code is // waiting (expiresAt null) and the token does not sign in: the device was unpaired. // Only 401 means "not paired"; on a 5xx it keeps the code and asks again, another answer is an error. async Task WaitForPairing(string? bearer, DateTimeOffset? expiresAt) { var failures = 0; while (true) { var (status, json, headers) = await Call(HttpMethod.Get, "/device", bearer); if (status == HttpStatusCode.OK) return json.GetProperty("data"); if (status == HttpStatusCode.TooManyRequests) { await Task.Delay(RetryAfter(headers)); continue; } // A request the API refuses, such as a wrong PACKEROO_BASE_URL: asking again changes nothing. if ((int)status is >= 400 and < 500 && status != HttpStatusCode.Unauthorized) Fail(status, json); if (status != HttpStatusCode.Unauthorized) { // Someone may be typing the code right now: keep it, ask again after a pause. await PauseAfterError(++failures, $"HTTP {(int)status}"); continue; } failures = 0; if (expiresAt is null || DateTimeOffset.UtcNow >= expiresAt) return null; await Task.Delay(TimeSpan.FromSeconds(pollSeconds)); } } // Keeps the token in a file only this user can read, written in one step. void SaveToken(string value) { Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(tokenFile))!); var temporary = tokenFile + ".tmp"; // A leftover from a crash may have other rights: remove it, then create the file anew. File.Delete(temporary); var options = new FileStreamOptions { Mode = FileMode.CreateNew, Access = FileAccess.Write }; if (!OperatingSystem.IsWindows()) options.UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite; using (var stream = new FileStream(temporary, options)) using (var writer = new StreamWriter(stream)) writer.WriteLine(value); File.Move(temporary, tokenFile, overwrite: true); } void ShowCode(string code, DateTimeOffset expiresAt) { // The app address for the QR code: api.qm.packeroo.com becomes app.qm.packeroo.com. // For a QR code on a display, a package such as QRCoder draws this link. var host = new Uri(baseUrl).Authority; if (host.StartsWith("api.")) host = "app." + host[4..]; Console.WriteLine(); Console.WriteLine(TEXT.Code, $"{code[..3]} {code[3..]}", expiresAt.ToLocalTime()); Console.WriteLine(TEXT.Link, $"https://{host}/verbinden?code={code}"); Console.WriteLine(TEXT.Enter); Console.WriteLine(); } // Seconds to wait after a 429, from Retry-After: a number of seconds or an HTTP date. static TimeSpan RetryAfter(HttpResponseHeaders headers) { var wait = headers.RetryAfter?.Delta ?? (headers.RetryAfter?.Date - DateTimeOffset.UtcNow) ?? TimeSpan.FromSeconds(60); return wait < TimeSpan.FromSeconds(1) ? TimeSpan.FromSeconds(1) : wait; } static string? ProblemCode(JsonElement json) => json.ValueKind == JsonValueKind.Object && json.TryGetProperty("code", out var code) ? code.GetString() : null; void Fail(HttpStatusCode status, JsonElement json) { var detail = json.ValueKind == JsonValueKind.Object && json.TryGetProperty("detail", out var text) ? text.GetString() : TEXT.Unexpected; Console.Error.WriteLine(TEXT.Error, (int)status, ProblemCode(json), detail); Environment.Exit(1); }