using System.Globalization;
using System.Net;
using Febe.App;
using Febe.Browser.Recipes;
namespace Febe.Desktop.Core;
///
/// How the browser of Instagram is hosted on Windows: the three attempts of S2, in the order of spec §6.6. The first is
/// the default; the others are fallbacks Alberto chooses with --browser while testing S2 (docs/windows.md).
///
public enum BrowserHosting
{
/// «finestra»: WebView2 in its own window «Browser di Febe», kept open but out of view, occlusion off.
Window,
/// «composizione»: the same window, with WebView2 hosted as a DirectComposition visual.
Composition,
/// «edge»: Microsoft Edge started as a process and driven like Chromium in Docker (ChromiumProcessHost).
Edge,
}
/// Italian names of , for the command line, the setting and the log.
public static class BrowserHostingNames
{
/// Setting key (table setting) of the hosting chosen with --browser; it stays for the next starts.
public const string SettingKey = "desktop.browser";
public static string Name(BrowserHosting hosting) => hosting switch
{
BrowserHosting.Composition => "composizione",
BrowserHosting.Edge => "edge",
_ => "finestra",
};
public static bool TryParse(string? text, out BrowserHosting hosting)
{
switch (text?.Trim().ToLowerInvariant())
{
case "finestra":
hosting = BrowserHosting.Window;
return true;
case "composizione":
hosting = BrowserHosting.Composition;
return true;
case "edge":
hosting = BrowserHosting.Edge;
return true;
default:
hosting = BrowserHosting.Window;
return false;
}
}
}
/// The folders Windows gives Febe by default (spec §12): tests pass their own.
/// %LOCALAPPDATA%.
/// The user's Pictures folder («Immagini»).
public sealed record DesktopFolders(string LocalAppData, string Pictures)
{
/// The folders of the current user.
public static DesktopFolders Current() => new(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData, Environment.SpecialFolderOption.DoNotVerify),
Environment.GetFolderPath(Environment.SpecialFolder.MyPictures, Environment.SpecialFolderOption.DoNotVerify));
/// Default Data folder: %LOCALAPPDATA%\Febe.
public string DefaultDataFolder => Path.Combine(LocalAppData, "Febe");
/// Default library: Immagini\Febe.
public string DefaultLibraryFolder => Path.Combine(Pictures, "Febe");
}
/// Configuration of the Windows application, from its command line (spec §12).
public sealed record DesktopOptions
{
/// Data folder chosen with --dati (development, a second account); null: the recorded or default one.
public string? DataFolder { get; init; }
///
/// Library chosen with --libreria (tests on Windows, a second account): the default of the setting instead of
/// Immagini\Febe. A folder chosen later in Impostazioni still wins.
///
public string? LibraryFolder { get; init; }
/// --nascosto: start with the icon in the notification area only (start with the computer).
public bool StartHidden { get; init; }
/// --browser finestra|composizione|edge: the hosting of S2, stored for the next starts.
public BrowserHosting? Hosting { get; init; }
/// --sviluppo: the developer tools of the interface window (never of the browser of Febe).
public bool DeveloperTools { get; init; }
/// Development: the local test site (tools/Febe.SitoDiProva) instead of Instagram, for S1 and S2.
public Uri? TestSite { get; init; }
/// Development: the «CDN» of the test site (default: 127.0.0.2, site port + 1).
public Uri? TestCdn { get; init; }
/// Development, test site only: opens the site once at start-up so its session cookie exists.
public bool TestSiteAutoLogin { get; init; }
/// Development: the first session after this delay instead of 2–10 minutes.
public TimeSpan? FirstSessionDelay { get; init; }
///
/// --raccolta pagine|richieste (issue #36, S4): by the pages (default, as before S4) or by requests with the
/// saved session, only for the operations the site's catalog configures.
///
public CollectionRoute Collection { get; init; } = CollectionRoute.Pages;
/// The fixed DevTools port of Edge (fallback «edge» only), on 127.0.0.1.
public int EdgeDebugPort { get; init; } = 9222;
/// Size of the page of the browser of Febe, always the same (spec §6.1).
public int BrowserWidth { get; init; } = 1280;
public int BrowserHeight { get; init; } = 900;
/// The site the browser works on: Instagram, or the local test site in development.
public CollectionSite Site => TestSite is { } site
? CollectionSite.TestSite(site.Authority, (TestCdn ?? DefaultCdn(site)).Authority)
: CollectionSite.Instagram;
/// The page «Accedi a Instagram» opens: the real login page, or a page of the test site.
public string LoginUrl => TestSite is { } site ? new Uri(site, "/benvenuto").AbsoluteUri : "https://www.instagram.com/accounts/login/";
/// The options of the shared composition.
public FebeAppOptions AppOptions(string dataFolder, DesktopFolders folders) => new()
{
DataFolder = dataFolder,
LibraryFolder = LibraryFolder ?? folders.DefaultLibraryFolder,
LibraryFolderFromSettings = true,
ImportFolder = null,
ZoneId = TimeZoneInfo.Local.Id,
Zone = TimeZoneInfo.Local,
Language = CultureInfo.CurrentUICulture.Name,
Site = Site,
LoginUrl = LoginUrl,
TestSite = TestSite,
TestSiteAutoLogin = TestSiteAutoLogin,
FirstSessionDelay = FirstSessionDelay,
Collection = Collection,
};
private static Uri DefaultCdn(Uri site) => new UriBuilder(site) { Host = "127.0.0.2", Port = site.Port + 1, Path = "/" }.Uri;
}
/// Reads the command line of Febe.exe. Nothing secret ever passes on it.
public static class DesktopCommandLine
{
public const string Usage =
"Uso: Febe.exe [--nascosto] [--dati cartella] [--libreria cartella] [--browser finestra|composizione|edge] [--sviluppo]\n"
+ " [--sito-di-prova http://127.0.0.1:8481 [--cdn-di-prova http://127.0.0.2:8482] [--accesso-di-prova]] [--prima-sessione secondi]\n"
+ " [--raccolta pagine|richieste]";
public static bool TryParse(string[] args, out DesktopOptions options, out string problem)
{
ArgumentNullException.ThrowIfNull(args);
options = new DesktopOptions();
problem = string.Empty;
for (var i = 0; i < args.Length; i++)
{
var arg = args[i];
string? Next() => i + 1 < args.Length ? args[++i] : null;
switch (arg.ToLowerInvariant())
{
case "--nascosto":
options = options with { StartHidden = true };
break;
case "--sviluppo":
options = options with { DeveloperTools = true };
break;
case "--dati":
{
var text = Next();
if (string.IsNullOrWhiteSpace(text) || !Path.IsPathFullyQualified(text))
{
problem = "Dopo --dati serve il percorso completo di una cartella.";
return false;
}
options = options with { DataFolder = Path.GetFullPath(text) };
break;
}
case "--libreria":
{
var text = Next();
if (string.IsNullOrWhiteSpace(text) || !Path.IsPathFullyQualified(text))
{
problem = "Dopo --libreria serve il percorso completo di una cartella.";
return false;
}
options = options with { LibraryFolder = Path.GetFullPath(text) };
break;
}
case "--browser":
{
var text = Next();
if (!BrowserHostingNames.TryParse(text, out var hosting))
{
problem = $"Valore non valido dopo --browser («{text}»): finestra, composizione oppure edge.";
return false;
}
options = options with { Hosting = hosting };
break;
}
case "--sito-di-prova":
case "--cdn-di-prova":
{
var text = Next();
if (!TryLocalAddress(text, out var address))
{
problem = $"Indirizzo non valido dopo {arg} («{text}»): serve un indirizzo http di questo computer, per esempio http://127.0.0.1:8481.";
return false;
}
options = arg.Equals("--sito-di-prova", StringComparison.OrdinalIgnoreCase)
? options with { TestSite = address }
: options with { TestCdn = address };
break;
}
case "--accesso-di-prova":
options = options with { TestSiteAutoLogin = true };
break;
case CollectionRouteNames.Option:
{
var text = Next();
if (!CollectionRouteNames.TryParse(text, out var route))
{
problem = CollectionRouteNames.Problem(CollectionRouteNames.Option, text);
return false;
}
options = options with { Collection = route };
break;
}
case "--prima-sessione":
{
var text = Next();
if (!int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var seconds) || seconds is < 1 or > 3600)
{
problem = $"Valore non valido dopo --prima-sessione («{text}»): secondi fra 1 e 3600.";
return false;
}
options = options with { FirstSessionDelay = TimeSpan.FromSeconds(seconds) };
break;
}
default:
problem = $"Opzione sconosciuta: {arg}.";
return false;
}
}
if (options.TestSiteAutoLogin && options.TestSite is null)
{
problem = "--accesso-di-prova vale solo con --sito-di-prova: con Instagram l'accesso lo fa sempre Alberto, a mano.";
return false;
}
if (options.TestCdn is not null && options.TestSite is null)
{
problem = "--cdn-di-prova vale solo con --sito-di-prova.";
return false;
}
return true;
}
/// The test site must be on this computer: the switch can never point the browser elsewhere.
private static bool TryLocalAddress(string? text, out Uri address)
{
address = null!;
if (!Uri.TryCreate(text, UriKind.Absolute, out var uri) || uri.Scheme != Uri.UriSchemeHttp)
{
return false;
}
var local = uri.IsLoopback || (IPAddress.TryParse(uri.Host, out var ip) && IPAddress.IsLoopback(ip));
if (!local)
{
return false;
}
address = new Uri(uri.GetLeftPart(UriPartial.Authority) + "/");
return true;
}
}