M6 Windows: composizione condivisa Febe.App per Server e Desktop; Febe per Windows (WPF) con l'interfaccia in WebView2, area di notifica, istanza unica, «Browser di Febe» su WebView2 con CDP filtrato (WebView2CdpSession) e ripieghi di S2 (composizione, Edge), guscio nativo, avvisi, spostamento verificato della cartella dei dati, icona del marchio; un solo Febe.exe, installatore NSIS e zip portabile; guida docs/windows.md e prove dal vivo S1–S3
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
73 files changed
+7914
-699
No files matched your search
@@ -0,0 +1,68 @@
|
||||
namespace Febe.Desktop.Core;
|
||||
|
||||
/// <summary>
|
||||
/// «Avvia Febe all'accensione del computer» (spec §12): the value <c>Febe</c> under
|
||||
/// <c>HKCU\Software\Microsoft\Windows\CurrentVersion\Run</c>, per user, no administrator rights. Febe then starts with
|
||||
/// <c>--nascosto</c>: only the icon in the notification area, the window stays closed.
|
||||
/// </summary>
|
||||
public static class Autostart
|
||||
{
|
||||
/// <summary>The registry key, under HKEY_CURRENT_USER.</summary>
|
||||
public const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Run";
|
||||
|
||||
/// <summary>The name of the value.</summary>
|
||||
public const string ValueName = "Febe";
|
||||
|
||||
/// <summary>The command written in the value: the quoted executable and <c>--nascosto</c>.</summary>
|
||||
public static string Command(string executable)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(executable);
|
||||
if (executable.Contains('"', StringComparison.Ordinal))
|
||||
{
|
||||
throw new ArgumentException("Percorso dell'eseguibile non valido.", nameof(executable));
|
||||
}
|
||||
|
||||
return $"\"{executable}\" --nascosto";
|
||||
}
|
||||
|
||||
/// <summary>True when <paramref name="value"/> starts this executable (a value left by another copy of Febe is not ours).</summary>
|
||||
public static bool PointsTo(string? value, string executable)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(value) || string.IsNullOrWhiteSpace(executable))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var text = value.Trim();
|
||||
string target;
|
||||
if (text.StartsWith('"'))
|
||||
{
|
||||
var end = text.IndexOf('"', 1);
|
||||
if (end < 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
target = text[1..end];
|
||||
}
|
||||
else
|
||||
{
|
||||
var space = text.IndexOf(' ', StringComparison.Ordinal);
|
||||
target = space < 0 ? text : text[..space];
|
||||
}
|
||||
|
||||
return string.Equals(Normalize(target), Normalize(executable), StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private static string Normalize(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
return Path.GetFullPath(path);
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)
|
||||
{
|
||||
return path;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
using System.Buffers.Binary;
|
||||
using SkiaSharp;
|
||||
|
||||
namespace Febe.Desktop.Core;
|
||||
|
||||
/// <summary>
|
||||
/// The brand mark of appendix C — a rounded square in the accent colour with a ring and a dot, a body and its moon —
|
||||
/// drawn with SkiaSharp at any size, the same way the SVG describes it:
|
||||
/// <code>
|
||||
/// <rect width="32" height="32" rx="8" fill="#0F5C8C"/>
|
||||
/// <circle cx="14.5" cy="17.5" r="7.4" fill="none" stroke="#FFFFFF" stroke-width="2.6"/>
|
||||
/// <circle cx="23.2" cy="8.8" r="3.1" fill="#FFFFFF"/>
|
||||
/// </code>
|
||||
/// </summary>
|
||||
public static class BrandMark
|
||||
{
|
||||
/// <summary>The sizes of the Windows icon: window, notification area, taskbar, Explorer, installer.</summary>
|
||||
public static IReadOnlyList<int> IconSizes { get; } = [16, 24, 32, 48, 64, 128, 256];
|
||||
|
||||
private static readonly SKColor Accent = new(0x0F, 0x5C, 0x8C);
|
||||
|
||||
/// <summary>The mark as a square bitmap of <paramref name="size"/> pixels, premultiplied BGRA, transparent corners.</summary>
|
||||
public static SKBitmap Render(int size)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(size, 1);
|
||||
ArgumentOutOfRangeException.ThrowIfGreaterThan(size, 1024);
|
||||
var bitmap = new SKBitmap(new SKImageInfo(size, size, SKColorType.Bgra8888, SKAlphaType.Premul));
|
||||
using var canvas = new SKCanvas(bitmap);
|
||||
canvas.Clear(SKColors.Transparent);
|
||||
var scale = size / 32f;
|
||||
canvas.Scale(scale);
|
||||
using (var square = new SKPaint { Color = Accent, IsAntialias = true, Style = SKPaintStyle.Fill })
|
||||
{
|
||||
canvas.DrawRoundRect(new SKRect(0, 0, 32, 32), 8, 8, square);
|
||||
}
|
||||
|
||||
using (var ring = new SKPaint { Color = SKColors.White, IsAntialias = true, Style = SKPaintStyle.Stroke, StrokeWidth = 2.6f })
|
||||
{
|
||||
canvas.DrawCircle(14.5f, 17.5f, 7.4f, ring);
|
||||
}
|
||||
|
||||
using (var moon = new SKPaint { Color = SKColors.White, IsAntialias = true, Style = SKPaintStyle.Fill })
|
||||
{
|
||||
canvas.DrawCircle(23.2f, 8.8f, 3.1f, moon);
|
||||
}
|
||||
|
||||
canvas.Flush();
|
||||
return bitmap;
|
||||
}
|
||||
|
||||
/// <summary>The multi-size Windows icon (<see cref="IconSizes"/>) of the mark, as the bytes of an .ico file.</summary>
|
||||
public static byte[] RenderIcon()
|
||||
{
|
||||
var images = new List<SKBitmap>();
|
||||
try
|
||||
{
|
||||
foreach (var size in IconSizes)
|
||||
{
|
||||
images.Add(Render(size));
|
||||
}
|
||||
|
||||
return IcoWriter.Write(images);
|
||||
}
|
||||
finally
|
||||
{
|
||||
foreach (var image in images)
|
||||
{
|
||||
image.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes Windows .ico files by hand (no package for it, spec §3): the 256-pixel image as PNG, the smaller ones as
|
||||
/// 32-bit DIBs (BGRA with alpha, bottom-up, plus the 1-bit AND mask), which every part of Windows reads — window icons,
|
||||
/// the notification area, Explorer, NSIS.
|
||||
/// </summary>
|
||||
public static class IcoWriter
|
||||
{
|
||||
/// <summary>Images at or above this size are stored as PNG (the Vista format); smaller ones as DIB.</summary>
|
||||
public const int PngFrom = 256;
|
||||
|
||||
private const int DirectoryHeader = 6;
|
||||
private const int DirectoryEntry = 16;
|
||||
private const int BitmapInfoHeader = 40;
|
||||
|
||||
/// <summary>The .ico bytes of square <paramref name="images"/> (1 to 256 pixels), in the order given.</summary>
|
||||
public static byte[] Write(IReadOnlyList<SKBitmap> images)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(images);
|
||||
if (images.Count is 0 or > ushort.MaxValue)
|
||||
{
|
||||
throw new ArgumentException("Un'icona contiene da 1 a 65535 immagini.", nameof(images));
|
||||
}
|
||||
|
||||
var payloads = new List<byte[]>(images.Count);
|
||||
foreach (var image in images)
|
||||
{
|
||||
if (image.Width != image.Height || image.Width is < 1 or > 256)
|
||||
{
|
||||
throw new ArgumentException("Le immagini di un'icona sono quadrate, da 1 a 256 pixel.", nameof(images));
|
||||
}
|
||||
|
||||
payloads.Add(image.Width >= PngFrom ? Png(image) : Dib(image));
|
||||
}
|
||||
|
||||
using var output = new MemoryStream();
|
||||
Span<byte> header = stackalloc byte[DirectoryHeader];
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(header, 0); // reserved
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(header[2..], 1); // 1 = icon
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(header[4..], (ushort)images.Count);
|
||||
output.Write(header);
|
||||
|
||||
var offset = DirectoryHeader + (DirectoryEntry * images.Count);
|
||||
Span<byte> entry = stackalloc byte[DirectoryEntry];
|
||||
for (var i = 0; i < images.Count; i++)
|
||||
{
|
||||
var size = images[i].Width;
|
||||
entry.Clear();
|
||||
entry[0] = (byte)(size >= 256 ? 0 : size); // 0 means 256
|
||||
entry[1] = (byte)(size >= 256 ? 0 : size);
|
||||
entry[2] = 0; // no palette
|
||||
entry[3] = 0; // reserved
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(entry[4..], 1); // colour planes
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(entry[6..], 32); // bits per pixel
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(entry[8..], (uint)payloads[i].Length);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(entry[12..], (uint)offset);
|
||||
output.Write(entry);
|
||||
offset += payloads[i].Length;
|
||||
}
|
||||
|
||||
foreach (var payload in payloads)
|
||||
{
|
||||
output.Write(payload);
|
||||
}
|
||||
|
||||
return output.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>Reads the directory of an .ico file: size, bytes, whether the image is PNG (tests, checks).</summary>
|
||||
public static IReadOnlyList<IcoEntry> ReadDirectory(ReadOnlySpan<byte> ico)
|
||||
{
|
||||
if (ico.Length < DirectoryHeader || BinaryPrimitives.ReadUInt16LittleEndian(ico) != 0 || BinaryPrimitives.ReadUInt16LittleEndian(ico[2..]) != 1)
|
||||
{
|
||||
throw new InvalidDataException("Non è un file .ico.");
|
||||
}
|
||||
|
||||
var count = BinaryPrimitives.ReadUInt16LittleEndian(ico[4..]);
|
||||
var entries = new List<IcoEntry>(count);
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
var e = ico.Slice(DirectoryHeader + (i * DirectoryEntry), DirectoryEntry);
|
||||
var size = e[0] == 0 ? 256 : e[0];
|
||||
var length = (int)BinaryPrimitives.ReadUInt32LittleEndian(e[8..]);
|
||||
var offset = (int)BinaryPrimitives.ReadUInt32LittleEndian(e[12..]);
|
||||
if (offset < 0 || length < 0 || offset + length > ico.Length)
|
||||
{
|
||||
throw new InvalidDataException("Immagine fuori dal file .ico.");
|
||||
}
|
||||
|
||||
var data = ico.Slice(offset, length);
|
||||
var png = data.Length >= 8 && data[..8].SequenceEqual(PngSignature);
|
||||
entries.Add(new IcoEntry(size, BinaryPrimitives.ReadUInt16LittleEndian(e[6..]), offset, length, png));
|
||||
}
|
||||
|
||||
return entries;
|
||||
}
|
||||
|
||||
/// <summary>The image of an entry as a bitmap (DIB or PNG), for comparisons.</summary>
|
||||
public static SKBitmap Decode(ReadOnlySpan<byte> ico, IcoEntry entry)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(entry);
|
||||
var data = ico.Slice(entry.Offset, entry.Length);
|
||||
if (entry.IsPng)
|
||||
{
|
||||
return SKBitmap.Decode(data.ToArray()) ?? throw new InvalidDataException("PNG dell'icona non leggibile.");
|
||||
}
|
||||
|
||||
var size = entry.Size;
|
||||
var bitmap = new SKBitmap(new SKImageInfo(size, size, SKColorType.Bgra8888, SKAlphaType.Unpremul));
|
||||
var pixels = data[BitmapInfoHeader..];
|
||||
for (var y = 0; y < size; y++)
|
||||
{
|
||||
var row = pixels.Slice((size - 1 - y) * size * 4, size * 4);
|
||||
for (var x = 0; x < size; x++)
|
||||
{
|
||||
bitmap.SetPixel(x, y, new SKColor(row[(x * 4) + 2], row[(x * 4) + 1], row[x * 4], row[(x * 4) + 3]));
|
||||
}
|
||||
}
|
||||
|
||||
return bitmap;
|
||||
}
|
||||
|
||||
private static ReadOnlySpan<byte> PngSignature => [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
|
||||
|
||||
private static byte[] Png(SKBitmap image)
|
||||
{
|
||||
using var data = image.Encode(SKEncodedImageFormat.Png, 100) ?? throw new InvalidOperationException("Codifica PNG non riuscita.");
|
||||
return data.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>A 32-bit DIB: BITMAPINFOHEADER with twice the height (image + mask), BGRA rows bottom-up, AND mask.</summary>
|
||||
private static byte[] Dib(SKBitmap image)
|
||||
{
|
||||
var size = image.Width;
|
||||
var maskStride = ((size + 31) / 32) * 4;
|
||||
var pixelBytes = size * size * 4;
|
||||
var result = new byte[BitmapInfoHeader + pixelBytes + (maskStride * size)];
|
||||
var span = result.AsSpan();
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(span, BitmapInfoHeader);
|
||||
BinaryPrimitives.WriteInt32LittleEndian(span[4..], size);
|
||||
BinaryPrimitives.WriteInt32LittleEndian(span[8..], size * 2);
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(span[12..], 1); // planes
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(span[14..], 32); // bits per pixel
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(span[16..], 0); // BI_RGB
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(span[20..], (uint)(pixelBytes + (maskStride * size)));
|
||||
|
||||
var pixels = span[BitmapInfoHeader..];
|
||||
var mask = span[(BitmapInfoHeader + pixelBytes)..];
|
||||
for (var y = 0; y < size; y++)
|
||||
{
|
||||
var row = pixels.Slice((size - 1 - y) * size * 4, size * 4);
|
||||
for (var x = 0; x < size; x++)
|
||||
{
|
||||
// GetPixel gives straight (not premultiplied) alpha, as icons want it.
|
||||
var c = image.GetPixel(x, y);
|
||||
row[x * 4] = c.Blue;
|
||||
row[(x * 4) + 1] = c.Green;
|
||||
row[(x * 4) + 2] = c.Red;
|
||||
row[(x * 4) + 3] = c.Alpha;
|
||||
if (c.Alpha == 0)
|
||||
{
|
||||
// Transparent pixels are also set in the AND mask, for the readers that ignore the alpha channel.
|
||||
var maskRow = mask.Slice((size - 1 - y) * maskStride, maskStride);
|
||||
maskRow[x / 8] |= (byte)(0x80 >> (x % 8));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One image of an .ico file.</summary>
|
||||
public sealed record IcoEntry(int Size, int BitsPerPixel, int Offset, int Length, bool IsPng);
|
||||
@@ -0,0 +1,85 @@
|
||||
using Febe.Browser.Hosting;
|
||||
|
||||
namespace Febe.Desktop.Core;
|
||||
|
||||
/// <summary>
|
||||
/// The arguments of the browser of Febe on Windows for S2 (spec §6.6): the page must keep loading and scrolling while
|
||||
/// the window «Browser di Febe» is open but out of view.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// <c>--disable-features=CalculateNativeWinOcclusion</c> stops Chromium from computing whether its window is covered or
|
||||
/// off-screen; <c>--disable-backgrounding-occluded-windows</c> stops it from treating such a window as hidden (lower
|
||||
/// priority, no painting, throttled timers). They are not forbidden by rule 2 of spec §2: they change how the browser
|
||||
/// schedules its own work, not what it declares. User agent, client hints, <c>navigator</c> properties (including
|
||||
/// <c>webdriver</c>), language, time zone and headers stay exactly those of a normal Edge/WebView2; nothing is
|
||||
/// injected into the page. The page sees a visible window, as it does with Chromium on Xvfb in Docker and with any
|
||||
/// browser window left open behind others where Windows does not report occlusion. Spec §6.6 itself prescribes this
|
||||
/// first attempt of S2.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// WebView2 also stops painting when its controller's <c>IsVisible</c> is false: the desktop never sets it to false and
|
||||
/// moves the window off-screen instead of hiding or minimising it.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public static class BrowserArguments
|
||||
{
|
||||
/// <summary>The switches of S2, the same for WebView2 and for Edge.</summary>
|
||||
public static IReadOnlyList<string> KeepPaintingOutOfView { get; } =
|
||||
[
|
||||
"--disable-features=CalculateNativeWinOcclusion",
|
||||
"--disable-backgrounding-occluded-windows",
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// <c>CoreWebView2EnvironmentOptions.AdditionalBrowserArguments</c> of the browser of Febe. Each switch passes the
|
||||
/// same check as Chromium's extra arguments (<see cref="ChromiumCommandLine.EnsureAllowed"/>).
|
||||
/// </summary>
|
||||
public static string ForWebView2()
|
||||
{
|
||||
foreach (var argument in KeepPaintingOutOfView)
|
||||
{
|
||||
ChromiumCommandLine.EnsureAllowed(argument);
|
||||
}
|
||||
|
||||
return string.Join(' ', KeepPaintingOutOfView);
|
||||
}
|
||||
|
||||
/// <summary>Extra arguments of Edge started as a process (fallback «edge»), checked the same way.</summary>
|
||||
public static IReadOnlyList<string> ForEdge() => KeepPaintingOutOfView;
|
||||
}
|
||||
|
||||
/// <summary>Finds Microsoft Edge for the last fallback of S2 (spec §6.6): App Paths first, then the usual folders.</summary>
|
||||
public static class EdgeLocator
|
||||
{
|
||||
/// <summary>
|
||||
/// The places Edge is looked for, in order: the <c>App Paths\msedge.exe</c> value of the registry (passed by the
|
||||
/// desktop), Program Files (x86), Program Files, and a per-user installation in <c>%LOCALAPPDATA%</c>.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<string> Candidates(string? appPathsValue, string? programFilesX86, string? programFiles, string? localAppData)
|
||||
{
|
||||
var list = new List<string>();
|
||||
if (!string.IsNullOrWhiteSpace(appPathsValue))
|
||||
{
|
||||
list.Add(appPathsValue.Trim().Trim('"'));
|
||||
}
|
||||
|
||||
foreach (var root in new[] { programFilesX86, programFiles, localAppData })
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(root))
|
||||
{
|
||||
list.Add(Path.Combine(root, "Microsoft", "Edge", "Application", "msedge.exe"));
|
||||
}
|
||||
}
|
||||
|
||||
return list.Distinct(StringComparer.OrdinalIgnoreCase).ToList();
|
||||
}
|
||||
|
||||
/// <summary>The first candidate that exists, or null.</summary>
|
||||
public static string? Find(IEnumerable<string> candidates, Func<string, bool>? exists = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(candidates);
|
||||
exists ??= File.Exists;
|
||||
return candidates.FirstOrDefault(c => c.EndsWith("msedge.exe", StringComparison.OrdinalIgnoreCase) && exists(c));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,301 @@
|
||||
using System.Security.Cryptography;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Web.Api;
|
||||
using Febe.Web.Library;
|
||||
|
||||
namespace Febe.Desktop.Core;
|
||||
|
||||
/// <summary>
|
||||
/// Where the Data folder of the Windows application is recorded, outside the folder itself (the desktop keeps it in
|
||||
/// <c>HKCU\Software\Febe</c>): the folder in use after a move, and a move asked from Impostazioni for the next start.
|
||||
/// </summary>
|
||||
public interface IDataFolderLocationStore
|
||||
{
|
||||
/// <summary>The Data folder in use after a move; null: the default (<c>%LOCALAPPDATA%\Febe</c>).</summary>
|
||||
string? Current { get; }
|
||||
|
||||
/// <summary>The folder chosen in Impostazioni, used from the next start; null: none.</summary>
|
||||
string? Pending { get; }
|
||||
|
||||
void SetCurrent(string? folder);
|
||||
|
||||
void SetPending(string? folder);
|
||||
}
|
||||
|
||||
/// <summary>What happened to a move of the Data folder at start-up.</summary>
|
||||
public enum DataFolderMoveOutcome
|
||||
{
|
||||
/// <summary>No move was asked.</summary>
|
||||
NotRequested,
|
||||
|
||||
/// <summary>Every file was copied and verified; the new folder is in use and the old one was deleted.</summary>
|
||||
Moved,
|
||||
|
||||
/// <summary>Moved, but the old folder could not be deleted entirely (it still holds a copy of the session).</summary>
|
||||
MovedOldFolderLeft,
|
||||
|
||||
/// <summary>The move did not happen: Febe goes on with the old folder, untouched.</summary>
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// <summary>Outcome of <see cref="DataFolderMove.ApplyPending"/>, with an Italian message for the log and a notification.</summary>
|
||||
public sealed record DataFolderMoveResult(DataFolderMoveOutcome Outcome, string DataFolder, string? Message);
|
||||
|
||||
/// <summary>Progress of the copy: files and bytes.</summary>
|
||||
public sealed record DataFolderMoveProgress(int FilesDone, int FilesTotal, long BytesDone, long BytesTotal);
|
||||
|
||||
/// <summary>
|
||||
/// «Cambia…» of the Data folder on Windows (spec §8.2). The Data folder holds the database and the browser profile with
|
||||
/// the Instagram session, so it never moves while Febe runs: the choice is recorded and applied at the next start,
|
||||
/// before anything opens the folder. Every file is copied and read back (SHA-256); only when every copy matches is the
|
||||
/// new folder used and the old one deleted — it holds a copy of the session, which must not stay behind (spec §13.2).
|
||||
/// Any error leaves the old folder in use and untouched, and removes the partial copy.
|
||||
/// </summary>
|
||||
public static class DataFolderMove
|
||||
{
|
||||
/// <summary>Why <paramref name="requested"/> cannot become the Data folder, in Italian; null when it can.</summary>
|
||||
public static string? Validate(string current, string requested, DataFolderCheck? check = null)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(current);
|
||||
if (string.IsNullOrWhiteSpace(requested) || !Path.IsPathFullyQualified(requested))
|
||||
{
|
||||
return "Serve il percorso completo di una cartella.";
|
||||
}
|
||||
|
||||
var from = Normalize(current);
|
||||
var to = Normalize(requested);
|
||||
if (Same(from, to))
|
||||
{
|
||||
return "È già la cartella dei dati.";
|
||||
}
|
||||
|
||||
if (Inside(to, from) || Inside(from, to))
|
||||
{
|
||||
return "La nuova cartella dei dati non può stare dentro quella attuale, né contenerla.";
|
||||
}
|
||||
|
||||
if (Directory.Exists(to) && Directory.EnumerateFileSystemEntries(to).Any())
|
||||
{
|
||||
return "Scegli una cartella vuota (o una nuova): Febe non mescola i suoi dati con altri file.";
|
||||
}
|
||||
|
||||
if (File.Exists(to))
|
||||
{
|
||||
return "Il percorso indica un file, non una cartella.";
|
||||
}
|
||||
|
||||
var existed = Directory.Exists(to);
|
||||
try
|
||||
{
|
||||
if ((check ?? new DataFolderCheck()).Check(to) is { } problem)
|
||||
{
|
||||
return $"{problem.Title}. {problem.Remedy}";
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
// The check may have created the folder to try writing in it: a choice that is not applied leaves nothing.
|
||||
if (!existed)
|
||||
{
|
||||
TryDeleteEmpty(to);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Applies the move asked from Impostazioni, if any. Call it before anything opens <paramref name="current"/>.
|
||||
/// </summary>
|
||||
public static DataFolderMoveResult ApplyPending(IDataFolderLocationStore store, string current, IProgress<DataFolderMoveProgress>? progress = null, DataFolderCheck? check = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(store);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(current);
|
||||
if (store.Pending is not { } pending)
|
||||
{
|
||||
return new DataFolderMoveResult(DataFolderMoveOutcome.NotRequested, current, null);
|
||||
}
|
||||
|
||||
var from = Normalize(current);
|
||||
var to = Normalize(pending);
|
||||
if (Validate(from, to, check) is { } reason)
|
||||
{
|
||||
store.SetPending(null);
|
||||
return new DataFolderMoveResult(DataFolderMoveOutcome.Failed, from, $"La cartella dei dati non è stata spostata in {to}: {reason} Febe usa ancora {from}.");
|
||||
}
|
||||
|
||||
if (!Directory.Exists(from))
|
||||
{
|
||||
// Nothing to copy (Febe never ran here): the new folder is simply used from now on.
|
||||
Directory.CreateDirectory(to);
|
||||
store.SetCurrent(to);
|
||||
store.SetPending(null);
|
||||
return new DataFolderMoveResult(DataFolderMoveOutcome.Moved, to, $"Cartella dei dati: {to}.");
|
||||
}
|
||||
|
||||
var createdTarget = !Directory.Exists(to);
|
||||
try
|
||||
{
|
||||
CopyVerified(from, to, progress);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException)
|
||||
{
|
||||
RemovePartialCopy(to, createdTarget);
|
||||
store.SetPending(null);
|
||||
return new DataFolderMoveResult(
|
||||
DataFolderMoveOutcome.Failed,
|
||||
from,
|
||||
$"La cartella dei dati non è stata spostata in {to}: {ex.Message} Febe usa ancora {from}, che non è stata toccata; la copia parziale è stata tolta.");
|
||||
}
|
||||
|
||||
store.SetCurrent(to);
|
||||
store.SetPending(null);
|
||||
try
|
||||
{
|
||||
Directory.Delete(from, recursive: true);
|
||||
return new DataFolderMoveResult(DataFolderMoveOutcome.Moved, to, $"Cartella dei dati spostata in {to}: ogni file è stato copiato e controllato, la vecchia cartella è stata cancellata.");
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
return new DataFolderMoveResult(
|
||||
DataFolderMoveOutcome.MovedOldFolderLeft,
|
||||
to,
|
||||
$"Cartella dei dati spostata in {to}, ma la vecchia ({from}) non si è potuta cancellare del tutto ({ex.Message}). Cancellala tu: contiene ancora una copia della sessione di Instagram.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Copies every file of <paramref name="from"/> into <paramref name="to"/> and reads each copy back.</summary>
|
||||
internal static void CopyVerified(string from, string to, IProgress<DataFolderMoveProgress>? progress)
|
||||
{
|
||||
var files = new DirectoryInfo(from)
|
||||
.EnumerateFiles("*", new EnumerationOptions { RecurseSubdirectories = true, AttributesToSkip = FileAttributes.ReparsePoint, IgnoreInaccessible = false })
|
||||
.ToList();
|
||||
var total = files.Sum(f => f.Length);
|
||||
long bytes = 0;
|
||||
var done = 0;
|
||||
Directory.CreateDirectory(to);
|
||||
foreach (var directory in Directory.EnumerateDirectories(from, "*", new EnumerationOptions { RecurseSubdirectories = true, AttributesToSkip = FileAttributes.ReparsePoint }))
|
||||
{
|
||||
Directory.CreateDirectory(Path.Combine(to, Path.GetRelativePath(from, directory)));
|
||||
}
|
||||
|
||||
foreach (var file in files)
|
||||
{
|
||||
var relative = Path.GetRelativePath(from, file.FullName);
|
||||
var target = Path.Combine(to, relative);
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
|
||||
byte[] sourceHash;
|
||||
using (var source = new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.Read))
|
||||
using (var destination = new FileStream(target, FileMode.CreateNew, FileAccess.Write, FileShare.None))
|
||||
using (var sha = IncrementalHash.CreateHash(HashAlgorithmName.SHA256))
|
||||
{
|
||||
var buffer = new byte[1024 * 1024];
|
||||
int read;
|
||||
while ((read = source.Read(buffer, 0, buffer.Length)) > 0)
|
||||
{
|
||||
sha.AppendData(buffer, 0, read);
|
||||
destination.Write(buffer, 0, read);
|
||||
}
|
||||
|
||||
destination.Flush(flushToDisk: true);
|
||||
sourceHash = sha.GetHashAndReset();
|
||||
}
|
||||
|
||||
byte[] copyHash;
|
||||
using (var copy = new FileStream(target, FileMode.Open, FileAccess.Read, FileShare.Read))
|
||||
{
|
||||
copyHash = SHA256.HashData(copy);
|
||||
}
|
||||
|
||||
if (!CryptographicOperations.FixedTimeEquals(sourceHash, copyHash))
|
||||
{
|
||||
throw new InvalidDataException($"la copia di {relative} non corrisponde all'originale.");
|
||||
}
|
||||
|
||||
File.SetLastWriteTimeUtc(target, file.LastWriteTimeUtc);
|
||||
bytes += file.Length;
|
||||
done++;
|
||||
progress?.Report(new DataFolderMoveProgress(done, files.Count, bytes, total));
|
||||
}
|
||||
}
|
||||
|
||||
private static void RemovePartialCopy(string to, bool createdTarget)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (createdTarget)
|
||||
{
|
||||
Directory.Delete(to, recursive: true);
|
||||
}
|
||||
else
|
||||
{
|
||||
// The folder existed and was empty (Validate): empty it again.
|
||||
foreach (var entry in new DirectoryInfo(to).EnumerateFileSystemInfos())
|
||||
{
|
||||
if (entry is DirectoryInfo directory)
|
||||
{
|
||||
directory.Delete(recursive: true);
|
||||
}
|
||||
else
|
||||
{
|
||||
entry.Delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private static void TryDeleteEmpty(string folder)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(folder) && !Directory.EnumerateFileSystemEntries(folder).Any())
|
||||
{
|
||||
Directory.Delete(folder);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private static string Normalize(string path) => Path.TrimEndingDirectorySeparator(Path.GetFullPath(path));
|
||||
|
||||
private static StringComparison Comparison => OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
|
||||
|
||||
private static bool Same(string a, string b) => string.Equals(a, b, Comparison);
|
||||
|
||||
private static bool Inside(string path, string folder) => path.StartsWith(folder + Path.DirectorySeparatorChar, Comparison);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="IDataFolderChange"/> of the Windows application: «Cambia…» records the new folder, which
|
||||
/// <see cref="DataFolderMove.ApplyPending"/> moves to at the next start. Not available when the Data folder was given
|
||||
/// on the command line (<c>--dati</c>): then it is the command line that decides.
|
||||
/// </summary>
|
||||
public sealed class DesktopDataFolderChange(IDataFolderLocationStore store, string currentDataFolder, bool fixedByCommandLine, DataFolderCheck? check = null) : IDataFolderChange
|
||||
{
|
||||
public bool CanChange => !fixedByCommandLine;
|
||||
|
||||
public Task<string> RequestChangeAsync(string newFolder, CancellationToken ct)
|
||||
{
|
||||
if (fixedByCommandLine)
|
||||
{
|
||||
throw new BadRequestException("Febe è stato avviato con --dati: la cartella dei dati la decide la riga di comando.");
|
||||
}
|
||||
|
||||
if (DataFolderMove.Validate(currentDataFolder, newFolder, check) is { } reason)
|
||||
{
|
||||
throw new BadRequestException(reason);
|
||||
}
|
||||
|
||||
var target = Path.TrimEndingDirectorySeparator(Path.GetFullPath(newFolder));
|
||||
store.SetPending(target);
|
||||
return Task.FromResult(
|
||||
$"Al prossimo avvio Febe sposterà i suoi dati in {target}: copia ogni file, lo controlla e solo dopo cancella la "
|
||||
+ "vecchia cartella. Per farlo subito, esci da Febe dall'area di notifica e riaprilo.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using Febe.App;
|
||||
using Febe.Browser.Recipes;
|
||||
|
||||
namespace Febe.Desktop.Core;
|
||||
|
||||
/// <summary>
|
||||
/// 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 <c>--browser</c> while testing S2 (docs/windows.md).
|
||||
/// </summary>
|
||||
public enum BrowserHosting
|
||||
{
|
||||
/// <summary>«finestra»: WebView2 in its own window «Browser di Febe», kept open but out of view, occlusion off.</summary>
|
||||
Window,
|
||||
|
||||
/// <summary>«composizione»: the same window, with WebView2 hosted as a DirectComposition visual.</summary>
|
||||
Composition,
|
||||
|
||||
/// <summary>«edge»: Microsoft Edge started as a process and driven like Chromium in Docker (ChromiumProcessHost).</summary>
|
||||
Edge,
|
||||
}
|
||||
|
||||
/// <summary>Italian names of <see cref="BrowserHosting"/>, for the command line, the setting and the log.</summary>
|
||||
public static class BrowserHostingNames
|
||||
{
|
||||
/// <summary>Setting key (table <c>setting</c>) of the hosting chosen with <c>--browser</c>; it stays for the next starts.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The folders Windows gives Febe by default (spec §12): tests pass their own.</summary>
|
||||
/// <param name="LocalAppData"><c>%LOCALAPPDATA%</c>.</param>
|
||||
/// <param name="Pictures">The user's Pictures folder («Immagini»).</param>
|
||||
public sealed record DesktopFolders(string LocalAppData, string Pictures)
|
||||
{
|
||||
/// <summary>The folders of the current user.</summary>
|
||||
public static DesktopFolders Current() => new(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData, Environment.SpecialFolderOption.DoNotVerify),
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.MyPictures, Environment.SpecialFolderOption.DoNotVerify));
|
||||
|
||||
/// <summary>Default Data folder: <c>%LOCALAPPDATA%\Febe</c>.</summary>
|
||||
public string DefaultDataFolder => Path.Combine(LocalAppData, "Febe");
|
||||
|
||||
/// <summary>Default library: <c>Immagini\Febe</c>.</summary>
|
||||
public string DefaultLibraryFolder => Path.Combine(Pictures, "Febe");
|
||||
}
|
||||
|
||||
/// <summary>Configuration of the Windows application, from its command line (spec §12).</summary>
|
||||
public sealed record DesktopOptions
|
||||
{
|
||||
/// <summary>Data folder chosen with <c>--dati</c> (development, a second account); null: the recorded or default one.</summary>
|
||||
public string? DataFolder { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Library chosen with <c>--libreria</c> (tests on Windows, a second account): the default of the setting instead of
|
||||
/// <c>Immagini\Febe</c>. A folder chosen later in Impostazioni still wins.
|
||||
/// </summary>
|
||||
public string? LibraryFolder { get; init; }
|
||||
|
||||
/// <summary><c>--nascosto</c>: start with the icon in the notification area only (start with the computer).</summary>
|
||||
public bool StartHidden { get; init; }
|
||||
|
||||
/// <summary><c>--browser finestra|composizione|edge</c>: the hosting of S2, stored for the next starts.</summary>
|
||||
public BrowserHosting? Hosting { get; init; }
|
||||
|
||||
/// <summary><c>--sviluppo</c>: the developer tools of the interface window (never of the browser of Febe).</summary>
|
||||
public bool DeveloperTools { get; init; }
|
||||
|
||||
/// <summary>Development: the local test site (tools/Febe.SitoDiProva) instead of Instagram, for S1 and S2.</summary>
|
||||
public Uri? TestSite { get; init; }
|
||||
|
||||
/// <summary>Development: the «CDN» of the test site (default: 127.0.0.2, site port + 1).</summary>
|
||||
public Uri? TestCdn { get; init; }
|
||||
|
||||
/// <summary>Development, test site only: opens the site once at start-up so its session cookie exists.</summary>
|
||||
public bool TestSiteAutoLogin { get; init; }
|
||||
|
||||
/// <summary>Development: the first session after this delay instead of 2–10 minutes.</summary>
|
||||
public TimeSpan? FirstSessionDelay { get; init; }
|
||||
|
||||
/// <summary>The fixed DevTools port of Edge (fallback «edge» only), on 127.0.0.1.</summary>
|
||||
public int EdgeDebugPort { get; init; } = 9222;
|
||||
|
||||
/// <summary>Size of the page of the browser of Febe, always the same (spec §6.1).</summary>
|
||||
public int BrowserWidth { get; init; } = 1280;
|
||||
|
||||
public int BrowserHeight { get; init; } = 900;
|
||||
|
||||
/// <summary>The site the browser works on: Instagram, or the local test site in development.</summary>
|
||||
public CollectionSite Site => TestSite is { } site
|
||||
? CollectionSite.TestSite(site.Authority, (TestCdn ?? DefaultCdn(site)).Authority)
|
||||
: CollectionSite.Instagram;
|
||||
|
||||
/// <summary>The page «Accedi a Instagram» opens: the real login page, or a page of the test site.</summary>
|
||||
public string LoginUrl => TestSite is { } site ? new Uri(site, "/benvenuto").AbsoluteUri : "https://www.instagram.com/accounts/login/";
|
||||
|
||||
/// <summary>The options of the shared composition.</summary>
|
||||
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,
|
||||
};
|
||||
|
||||
private static Uri DefaultCdn(Uri site) => new UriBuilder(site) { Host = "127.0.0.2", Port = site.Port + 1, Path = "/" }.Uri;
|
||||
}
|
||||
|
||||
/// <summary>Reads the command line of Febe.exe. Nothing secret ever passes on it.</summary>
|
||||
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]";
|
||||
|
||||
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 "--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;
|
||||
}
|
||||
|
||||
/// <summary>The test site must be on this computer: the switch can never point the browser elsewhere.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,334 @@
|
||||
using System.Globalization;
|
||||
using Febe.App;
|
||||
using Febe.Browser.Cdp;
|
||||
using Febe.Browser.Hosting;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Web;
|
||||
using Febe.Web.Api;
|
||||
using Febe.Web.Connection;
|
||||
using Febe.Web.Library;
|
||||
using Febe.Web.Native;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Febe.Desktop.Core;
|
||||
|
||||
/// <summary>How the window «Browser di Febe» hosts WebView2 (spec §6.1, §12, S2).</summary>
|
||||
/// <param name="ProfileDirectory">The WebView2 user data folder: <c>Dati\browser</c>, with the Instagram session.</param>
|
||||
/// <param name="Width">Width of the page in CSS pixels, always the same.</param>
|
||||
/// <param name="Height">Height of the page in CSS pixels, always the same.</param>
|
||||
/// <param name="Hosting"><see cref="BrowserHosting.Window"/> or <see cref="BrowserHosting.Composition"/>.</param>
|
||||
/// <param name="AdditionalBrowserArguments">The switches of S2 (<see cref="BrowserArguments.ForWebView2"/>).</param>
|
||||
public sealed record WebView2BrowserSettings(string ProfileDirectory, int Width, int Height, BrowserHosting Hosting, string AdditionalBrowserArguments);
|
||||
|
||||
/// <summary>
|
||||
/// What the Windows-only part of the desktop (Febe.Desktop, WPF) gives the platform: the native shell, the WebView2
|
||||
/// browser, Edge's window, the notifications, the WebView2 runtime probe. Tests on Linux pass fakes.
|
||||
/// </summary>
|
||||
public interface IDesktopShell
|
||||
{
|
||||
/// <summary>Folder picker, «Mostra nella cartella», default browser, notifications, start with the computer.</summary>
|
||||
INativeShell Native { get; }
|
||||
|
||||
/// <summary>Windows notifications (balloon tips of the notification-area icon); null when there is no icon.</summary>
|
||||
IAlertChannel? Notifications { get; }
|
||||
|
||||
/// <summary>The installed WebView2 runtime; null when missing.</summary>
|
||||
string? WebView2Version();
|
||||
|
||||
/// <summary>The window «Browser di Febe» on WebView2.</summary>
|
||||
IFebeBrowser CreateWebView2Browser(WebView2BrowserSettings settings, FebePlatformContext context);
|
||||
|
||||
/// <summary>Microsoft Edge (fallback «edge» of S2); null when it is not installed.</summary>
|
||||
string? FindEdge();
|
||||
|
||||
/// <summary>Brings the main window of a process (Edge) to the front, on screen.</summary>
|
||||
Task ShowProcessWindowAsync(int processId, CancellationToken ct);
|
||||
|
||||
/// <summary>Moves the main window of a process (Edge) out of view, still open: never minimised (S2).</summary>
|
||||
Task HideProcessWindowAsync(int processId, CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The Windows edition's parts of the composition (spec §12, §13.1): the interface on 127.0.0.1 with a port chosen at
|
||||
/// start-up and a token of this start, the Data folder and the WebView2 runtime checked at start-up, the browser of
|
||||
/// Instagram in its own window (or, for S2, as a composition visual or as Edge), and the native functions.
|
||||
/// </summary>
|
||||
public sealed class DesktopPlatform : IFebePlatform
|
||||
{
|
||||
private readonly DesktopOptions _options;
|
||||
private readonly IDesktopShell _shell;
|
||||
private readonly IDataFolderLocationStore _locations;
|
||||
private readonly bool _dataFolderFixed;
|
||||
|
||||
/// <param name="options">The command line.</param>
|
||||
/// <param name="shell">The Windows-only part.</param>
|
||||
/// <param name="locations">Where a move of the Data folder is recorded.</param>
|
||||
/// <param name="dataFolderFixed">True when the Data folder came from <c>--dati</c>: «Cambia…» is not offered.</param>
|
||||
public DesktopPlatform(DesktopOptions options, IDesktopShell shell, IDataFolderLocationStore locations, bool dataFolderFixed)
|
||||
{
|
||||
_options = options ?? throw new ArgumentNullException(nameof(options));
|
||||
_shell = shell ?? throw new ArgumentNullException(nameof(shell));
|
||||
_locations = locations ?? throw new ArgumentNullException(nameof(locations));
|
||||
_dataFolderFixed = dataFolderFixed;
|
||||
WebOptions = new FebeWebOptions
|
||||
{
|
||||
Edition = FebeEdition.Desktop,
|
||||
Access = AccessMode.Token,
|
||||
AccessToken = AccessToken,
|
||||
AllowedHosts = FebeWebOptions.LoopbackHosts(0),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>The token of this start: the interface window opens <c>/?gettone=…</c> once. Never logged.</summary>
|
||||
public string AccessToken { get; } = Febe.Web.Security.AccessToken.Create();
|
||||
|
||||
public FebeWebOptions WebOptions { get; }
|
||||
|
||||
/// <summary>127.0.0.1 only, on a port chosen at start-up.</summary>
|
||||
public FebeListen Listen => FebeListen.Loopback(0);
|
||||
|
||||
/// <summary>The hosting actually used (after a missing Edge fell back to the window).</summary>
|
||||
public BrowserHosting? Hosting { get; private set; }
|
||||
|
||||
/// <summary>The address the interface window opens once: the token becomes a cookie and leaves the address.</summary>
|
||||
public Uri FirstAddress(Uri address)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(address);
|
||||
return new Uri(address, "/?" + Febe.Web.Security.AccessToken.QueryName + "=" + Uri.EscapeDataString(AccessToken));
|
||||
}
|
||||
|
||||
public IReadOnlyList<ConfigurationProblem> CheckConfiguration(FebeAppOptions options, DataFolderCheck dataFolderCheck)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
return DesktopStartupChecks.Run(options.DataFolder, _shell.WebView2Version, dataFolderCheck);
|
||||
}
|
||||
|
||||
public async Task<IFebeBrowser> CreateBrowserAsync(FebePlatformContext context, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
var settings = context.Storage.Settings;
|
||||
BrowserHosting hosting;
|
||||
if (_options.Hosting is { } chosen)
|
||||
{
|
||||
hosting = chosen;
|
||||
await settings.SetAsync(BrowserHostingNames.SettingKey, BrowserHostingNames.Name(chosen), ct).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
BrowserHostingNames.TryParse(await settings.GetAsync(BrowserHostingNames.SettingKey, ct).ConfigureAwait(false), out hosting);
|
||||
}
|
||||
|
||||
var profile = context.Data.BrowserProfile;
|
||||
if (hosting == BrowserHosting.Edge)
|
||||
{
|
||||
if (_shell.FindEdge() is { } edge)
|
||||
{
|
||||
Hosting = hosting;
|
||||
context.Log.Info("browser", $"Browser di Febe: Microsoft Edge avviato come processo (ripiego di S2), porta di debug {_options.EdgeDebugPort.ToString(CultureInfo.InvariantCulture)} solo su 127.0.0.1.");
|
||||
return new EdgeBrowser(CreateEdge(context, edge), _shell, context);
|
||||
}
|
||||
|
||||
context.Log.Warn("browser", "Microsoft Edge non si trova su questo computer: il browser di Febe usa la sua finestra WebView2.");
|
||||
hosting = BrowserHosting.Window;
|
||||
}
|
||||
|
||||
Hosting = hosting;
|
||||
context.Log.Info("browser", $"Browser di Febe: WebView2 nella sua finestra ({BrowserHostingNames.Name(hosting)}), fuori vista quando non serve.");
|
||||
return _shell.CreateWebView2Browser(
|
||||
new WebView2BrowserSettings(profile, _options.BrowserWidth, _options.BrowserHeight, hosting, BrowserArguments.ForWebView2()),
|
||||
context);
|
||||
}
|
||||
|
||||
public void RegisterServices(IServiceCollection services, FebeApp app)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(services);
|
||||
ArgumentNullException.ThrowIfNull(app);
|
||||
services.AddSingleton(_shell.Native);
|
||||
services.AddSingleton<IBrowserWindow>(new DesktopBrowserWindow(() => app.Browser));
|
||||
services.AddSingleton<IDataFolderChange>(new DesktopDataFolderChange(_locations, app.Options.DataFolder, _dataFolderFixed));
|
||||
if (_shell.Notifications is { } notifications)
|
||||
{
|
||||
services.AddSingleton(notifications);
|
||||
}
|
||||
}
|
||||
|
||||
public void RegisterProblemServices(IServiceCollection services, FebeApp app)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(services);
|
||||
services.AddSingleton(_shell.Native);
|
||||
}
|
||||
|
||||
public Task StoppingAsync() => Task.CompletedTask;
|
||||
|
||||
/// <summary>
|
||||
/// Edge for the last fallback of S2: the same <see cref="ChromiumProcessHost"/> as Docker, with its fixed DevTools
|
||||
/// port on 127.0.0.1, a profile of its own inside <c>Dati\browser</c> (so «Scollega» deletes both), preferences
|
||||
/// with password saving and autofill off, and the switches of S2.
|
||||
/// </summary>
|
||||
private ChromiumBrowser CreateEdge(FebePlatformContext context, string executable) => new(
|
||||
new ChromiumBrowserSettings
|
||||
{
|
||||
ProfileDirectory = Path.Combine(context.Data.BrowserProfile, "edge"),
|
||||
ProfileFolderToDelete = context.Data.BrowserProfile,
|
||||
WindowWidth = _options.BrowserWidth,
|
||||
WindowHeight = _options.BrowserHeight,
|
||||
DebugPort = _options.EdgeDebugPort,
|
||||
ExecutablePath = executable,
|
||||
Display = null,
|
||||
Launch = new ChromiumLaunchOptions
|
||||
{
|
||||
ExtraArguments = BrowserArguments.ForEdge(),
|
||||
SessionCookie = _options.Site.SessionCookie,
|
||||
SeedProfilePreferences = true,
|
||||
},
|
||||
},
|
||||
context.Clock,
|
||||
context.Log);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// «Apri il browser» on Windows (spec §10.3): brings the window «Browser di Febe» to the front. While it is in front
|
||||
/// Alberto is driving and the engine is still; closing the window ends it.
|
||||
/// </summary>
|
||||
public sealed class DesktopBrowserWindow(Func<IFebeBrowser?> browser) : IBrowserWindow
|
||||
{
|
||||
public bool IsSeparateWindow => true;
|
||||
|
||||
public async Task ShowAsync(CancellationToken ct)
|
||||
{
|
||||
if (browser() is not { } current)
|
||||
{
|
||||
throw new BadRequestException("Il browser di Febe non è in funzione in questo momento.");
|
||||
}
|
||||
|
||||
if (!current.IsAvailable)
|
||||
{
|
||||
throw new BadRequestException(current.LastError is { } error
|
||||
? "Il browser di Febe non è in funzione: " + error
|
||||
: "Il browser di Febe si sta avviando: riprova fra qualche secondo.");
|
||||
}
|
||||
|
||||
await current.ShowToUserAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Edge started as a process (the last fallback of S2): a <see cref="ChromiumBrowser"/> whose window is moved out of
|
||||
/// view after every start and brought to the front when Alberto uses it. While it is in front Alberto is driving.
|
||||
/// </summary>
|
||||
public sealed class EdgeBrowser : IFebeBrowser
|
||||
{
|
||||
private readonly ChromiumBrowser _inner;
|
||||
private readonly IDesktopShell _shell;
|
||||
private readonly FebePlatformContext _context;
|
||||
private readonly Lock _gate = new();
|
||||
private IDisposable? _lease;
|
||||
|
||||
public EdgeBrowser(ChromiumBrowser inner, IDesktopShell shell, FebePlatformContext context)
|
||||
{
|
||||
_inner = inner ?? throw new ArgumentNullException(nameof(inner));
|
||||
_shell = shell ?? throw new ArgumentNullException(nameof(shell));
|
||||
_context = context ?? throw new ArgumentNullException(nameof(context));
|
||||
_inner.Host.Connection.Reconnected += OnRestarted;
|
||||
}
|
||||
|
||||
public ChromiumBrowser Inner => _inner;
|
||||
|
||||
public ICdpSession Cdp => _inner.Cdp;
|
||||
|
||||
public UserDrivingGate UserDriving => _inner.UserDriving;
|
||||
|
||||
public bool UserIsDriving => _inner.UserIsDriving;
|
||||
|
||||
public bool IsAvailable => _inner.IsAvailable;
|
||||
|
||||
public string? LastError => _inner.LastError;
|
||||
|
||||
public string ProfileDirectory => _inner.ProfileDirectory;
|
||||
|
||||
public int WindowWidth => _inner.WindowWidth;
|
||||
|
||||
public int WindowHeight => _inner.WindowHeight;
|
||||
|
||||
public async Task RunAsync(CancellationToken ct)
|
||||
{
|
||||
await _inner.RunAsync(ct).ConfigureAwait(false);
|
||||
if (_inner.IsAvailable)
|
||||
{
|
||||
await MoveOutOfViewAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
public Task<NavigationResult> RestAsync(CancellationToken ct) => _inner.RestAsync(ct);
|
||||
|
||||
public async Task ShowToUserAsync(CancellationToken ct)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_lease ??= _inner.UserDriving.Begin();
|
||||
}
|
||||
|
||||
_context.Tracker.MarkUsed(_context.Clock.Now);
|
||||
if (_inner.Host.ProcessId is { } pid)
|
||||
{
|
||||
await _shell.ShowProcessWindowAsync(pid, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task HideFromUserAsync(CancellationToken ct)
|
||||
{
|
||||
ReleaseLease();
|
||||
await MoveOutOfViewAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public Task RestartWithEmptyProfileAsync(CancellationToken ct) => _inner.RestartWithEmptyProfileAsync(ct);
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
_inner.Host.Connection.Reconnected -= OnRestarted;
|
||||
ReleaseLease();
|
||||
await _inner.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task MoveOutOfViewAsync(CancellationToken ct)
|
||||
{
|
||||
if (_inner.Host.ProcessId is { } pid)
|
||||
{
|
||||
await _shell.HideProcessWindowAsync(pid, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Edge restarted (it crashed, or Alberto closed its window): a new window opens on screen, it goes out of view.</summary>
|
||||
private void OnRestarted(object? sender, EventArgs e)
|
||||
{
|
||||
ReleaseLease();
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
await MoveOutOfViewAsync(CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is InvalidOperationException or IOException)
|
||||
{
|
||||
_context.Log.Warn("browser", "La finestra di Edge non è andata fuori vista.", ex);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void ReleaseLease()
|
||||
{
|
||||
IDisposable? lease;
|
||||
lock (_gate)
|
||||
{
|
||||
lease = _lease;
|
||||
_lease = null;
|
||||
}
|
||||
|
||||
if (lease is not null)
|
||||
{
|
||||
lease.Dispose();
|
||||
_context.Tracker.MarkUsed(_context.Clock.Now);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
using Febe.App;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Web.Connection;
|
||||
|
||||
namespace Febe.Desktop.Core;
|
||||
|
||||
/// <summary>
|
||||
/// The checks made before anything starts on Windows (spec §8.2, §12): the Data folder is on a local disk and writable,
|
||||
/// and the WebView2 runtime is installed (it is in Windows 11 and in almost every Windows 10). With a problem the engine
|
||||
/// and the browser do not start.
|
||||
/// </summary>
|
||||
public static class DesktopStartupChecks
|
||||
{
|
||||
public const string WebView2Missing = "webview2-assente";
|
||||
|
||||
/// <summary>The official page of the WebView2 runtime (Microsoft), with the Evergreen installer.</summary>
|
||||
public const string WebView2DownloadPage = "https://developer.microsoft.com/microsoft-edge/webview2/";
|
||||
|
||||
/// <summary>
|
||||
/// Every problem found, in the order the error page shows them.
|
||||
/// </summary>
|
||||
/// <param name="dataFolder">The Data folder.</param>
|
||||
/// <param name="webView2Version">
|
||||
/// The installed WebView2 runtime (<c>CoreWebView2Environment.GetAvailableBrowserVersionString</c>), null when missing.
|
||||
/// </param>
|
||||
/// <param name="check">The Data folder check (tests inject a mount table).</param>
|
||||
public static IReadOnlyList<ConfigurationProblem> Run(string dataFolder, Func<string?> webView2Version, DataFolderCheck? check = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(webView2Version);
|
||||
var problems = new List<ConfigurationProblem>();
|
||||
if (DataFolderProblems.Check(dataFolder, check) is { } data)
|
||||
{
|
||||
problems.Add(data);
|
||||
}
|
||||
|
||||
string? version;
|
||||
try
|
||||
{
|
||||
version = webView2Version();
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
version = null;
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(version))
|
||||
{
|
||||
problems.Add(WebView2Problem());
|
||||
}
|
||||
|
||||
return problems;
|
||||
}
|
||||
|
||||
/// <summary>«Manca il runtime WebView2», with the link to the official page.</summary>
|
||||
public static ConfigurationProblem WebView2Problem() => new(
|
||||
WebView2Missing,
|
||||
"Manca il runtime WebView2 di Microsoft",
|
||||
"Febe mostra la sua interfaccia e apre Instagram con WebView2, il componente di Microsoft Edge che Windows 11 e "
|
||||
+ "quasi tutti i Windows 10 hanno già. Su questo computer non c'è, quindi Febe non ha avviato né il motore né il browser.",
|
||||
$"Installa il runtime WebView2 «Evergreen» dalla pagina ufficiale di Microsoft ({WebView2DownloadPage}), poi riavvia Febe. "
|
||||
+ "Non servono permessi di amministratore e non cambia nulla nel tuo Edge.");
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<!-- La parte del programma per Windows che non dipende da Windows (specifica §12): opzioni e cartelle, riga di comando,
|
||||
istanza unica, controlli all'avvio, spostamento della cartella dei dati, icona, Edge come ripiego di S2,
|
||||
composizione con IFebePlatform. Sta in net10.0 perché le prove girano su Linux; le chiamate a Windows (WebView2,
|
||||
registro, area di notifica) restano in Febe.Desktop dietro interfacce piccole. -->
|
||||
<ItemGroup>
|
||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||
<ProjectReference Include="..\Febe.Core\Febe.Core.csproj" />
|
||||
<ProjectReference Include="..\Febe.Browser\Febe.Browser.csproj" />
|
||||
<ProjectReference Include="..\Febe.Web\Febe.Web.csproj" />
|
||||
<ProjectReference Include="..\Febe.App\Febe.App.csproj" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="Febe.Tests" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,75 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace Febe.Desktop.Core;
|
||||
|
||||
/// <summary>
|
||||
/// One Febe at a time for a Data folder (spec §12, rule 4): the names of the mutex and of the pipe through which a
|
||||
/// second launch asks the first one to show its window. Derived from the Data folder, so that a second account with
|
||||
/// folders of its own (spec §3) is a second instance; the same folder is the same instance whatever the case of its
|
||||
/// letters.
|
||||
/// </summary>
|
||||
public static class InstanceIdentity
|
||||
{
|
||||
/// <summary>A short stable name for a Data folder: «Febe-» and 16 hexadecimal digits of SHA-256 of its full path.</summary>
|
||||
public static string For(string dataFolder)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(dataFolder);
|
||||
var full = Path.TrimEndingDirectorySeparator(Path.GetFullPath(dataFolder)).ToUpperInvariant();
|
||||
var hash = SHA256.HashData(Encoding.UTF8.GetBytes(full));
|
||||
return "Febe-" + Convert.ToHexString(hash, 0, 8).ToLowerInvariant();
|
||||
}
|
||||
|
||||
/// <summary>The named mutex, in the session namespace (one per logged-in user).</summary>
|
||||
public static string MutexName(string dataFolder) => @"Local\" + For(dataFolder);
|
||||
|
||||
/// <summary>The named pipe of the first instance (current user only).</summary>
|
||||
public static string PipeName(string dataFolder) => For(dataFolder);
|
||||
}
|
||||
|
||||
/// <summary>What a second launch asks the running Febe.</summary>
|
||||
public enum InstanceRequest
|
||||
{
|
||||
/// <summary>Show the window (a normal launch: Start menu, desktop shortcut).</summary>
|
||||
Show,
|
||||
|
||||
/// <summary>Nothing visible (a start with the computer while Febe already runs).</summary>
|
||||
StayHidden,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The one-line messages between two launches of Febe, over a pipe that only the current user can open. A message
|
||||
/// carries no path and no secret; anything else than the two known lines is ignored.
|
||||
/// </summary>
|
||||
public static class InstanceMessages
|
||||
{
|
||||
private const string Prefix = "FEBE1 ";
|
||||
|
||||
/// <summary>The longest message read (anything longer is not one of ours).</summary>
|
||||
public const int MaxLength = 64;
|
||||
|
||||
/// <summary>The message a second launch with these options sends.</summary>
|
||||
public static string For(DesktopOptions options)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
return Format(options.StartHidden ? InstanceRequest.StayHidden : InstanceRequest.Show);
|
||||
}
|
||||
|
||||
public static string Format(InstanceRequest request) => Prefix + (request == InstanceRequest.StayHidden ? "nascosto" : "mostra");
|
||||
|
||||
/// <summary>The request in a message; null for anything that is not one of ours.</summary>
|
||||
public static InstanceRequest? Parse(string? message)
|
||||
{
|
||||
if (message is null || message.Length > MaxLength)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return message.Trim() switch
|
||||
{
|
||||
"FEBE1 mostra" => InstanceRequest.Show,
|
||||
"FEBE1 nascosto" => InstanceRequest.StayHidden,
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user