Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.en-US.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,13 @@ English (US) release notes, mirroring CHANGELOG.md (Brazilian Portuguese). Befor

## [Unreleased]

## [1.6.0-beta.5]
### Heads-up: beta version, not the stable one
- This is a test version of 1.6. The stable version is still 1.5.1, and people on it don't get this update automatically: only those who turned on Settings → "Receive test versions (alpha and beta)" or are already on an alpha/beta. If something breaks, go back to 1.5.1 and report it with the feedback button (attach `consolemode.log`).

### What's new
- Session menu: without ControlFS installed, pressing A on "File explorer (ControlFS)" now downloads and installs ControlFS right there, without leaving the controller: the row shows the progress, the installer is checked (SHA-256) before it runs and, when done, ControlFS opens full screen. If it can't (no internet, for example), the row says so and the next A opens the download page. (#136)

## [1.6.0-beta.4]
### Heads-up: beta version, not the stable one
- This is a test version of 1.6. The stable version is still 1.5.1, and people on it don't get this update automatically: only those who turned on Settings → "Receive test versions (alpha and beta)" or are already on an alpha/beta. If something breaks, go back to 1.5.1 and report it with the feedback button (attach `consolemode.log`).
Expand Down
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,13 @@ Notas em português do Brasil; a versão em inglês (Estados Unidos) fica em `CH

## [Unreleased]

## [1.6.0-beta.5]
### Atenção: versão beta, não é a estável
- Esta é uma versão de teste da 1.6. A versão estável continua sendo a 1.5.1, e quem está nela não recebe esta atualização automaticamente: só quem ligou Ajustes → "Receber versões de teste (alpha e beta)" ou já está numa alpha/beta. Se algo falhar, volte para a 1.5.1 e conte pelo botão de feedback (anexe o `consolemode.log`).

### Novidades
- Menu da sessão: sem o ControlFS instalado, apertar A em "Explorador de arquivos (ControlFS)" agora baixa e instala o ControlFS ali mesmo, sem sair do controle: a linha mostra o progresso, o instalador é conferido (SHA-256) antes de rodar e, ao terminar, o ControlFS abre em tela cheia. Se não der (sem internet, por exemplo), a linha avisa e o próximo A abre a página de download. (#136)

## [1.6.0-beta.4]
### Atenção: versão beta, não é a estável
- Esta é uma versão de teste da 1.6. A versão estável continua sendo a 1.5.1, e quem está nela não recebe esta atualização automaticamente: só quem ligou Ajustes → "Receber versões de teste (alpha e beta)" ou já está numa alpha/beta. Se algo falhar, volte para a 1.5.1 e conte pelo botão de feedback (anexe o `consolemode.log`).
Expand Down
8 changes: 6 additions & 2 deletions docs/TESTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ Pré-condições: sessão ativa com Big Picture (ou jogo borderless) na tela; co

## 1d. Explorador de arquivos (ControlFS) no menu da sessão

Pré-condição: ControlFS instalado (https://github.com/nextestudios/ControlFS).
Pré-condição: ControlFS instalado (https://github.com/nextestudios/ControlFS), exceto nos itens de instalação pelo menu.

- [ ] Select + Y: no topo da lateral esquerda, fora da lista que rola, há o painel "Explorador de arquivos (ControlFS)"; o restante das opções rola por baixo dele. Resultado: ______
- [ ] Direcional para cima a partir de "Voltar ao jogo" chega nele; A abre o ControlFS em tela cheia na TV, por cima do jogo/Big Picture, e o menu fecha. Resultado: ______
Expand All @@ -170,7 +170,11 @@ Pré-condição: ControlFS instalado (https://github.com/nextestudios/ControlFS)
- [ ] Com o ControlFS já aberto: A só o traz para a frente (não abre uma segunda instância). Resultado: ______
- [ ] A sessão **não** termina nem restaura a mesa enquanto o ControlFS está na frente; ao sair dele (Menu do ControlFS → Sair) volta-se ao jogo. Resultado: ______
- [ ] Select + Y com o ControlFS na frente abre o menu por cima dele (saída de emergência). Resultado: ______
- [ ] Sem o ControlFS instalado: a linha diz "Não instalado · aperte para baixar" e A abre a página de releases no navegador. Resultado: ______
- [ ] **Instalar pelo menu** (desinstale o ControlFS antes): a linha diz "Não instalado · aperte para baixar e instalar". A começa o download: a linha mostra "Baixando… N%" com a barra enchendo, depois "Instalando…" com a barra em movimento, sem nenhuma janela de instalador nem pedido de administrador. Ao terminar, o menu fecha e o ControlFS abre em tela cheia na tela da sessão. Resultado: ______
- [ ] Durante o download o menu continua respondendo (direcional, volume); apertar A de novo na linha não começa um segundo download. Resultado: ______
- [ ] Fechar o menu durante a instalação: ela termina em segundo plano e o ControlFS **não** abre por cima do jogo; ao reabrir o menu a linha já diz "Navegue pelos seus arquivos com o controle". Resultado: ______
- [ ] Sem internet (cabo/Wi-Fi desligado): A na linha mostra "Não deu para instalar · aperte para abrir a página de download" e o log registra `ControlFS: instalar: ...`; o A seguinte abre a página de releases no navegador. Reabrindo o menu, a linha volta a oferecer a instalação. Resultado: ______
- [ ] Depois de instalado pelo menu, o ControlFS aparece em Configurações → Aplicativos instalados e nenhum `ControlFS-Setup-x64.exe` sobra em `%TEMP%ConsoleModeUpdate`. Resultado: ______
- [ ] Fora da sessão (prévia do menu) o painel funciona igual. Resultado: ______

## 2. Links `consolemode://`
Expand Down
4 changes: 2 additions & 2 deletions src/ConsoleMode/ConsoleMode.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<LangVersion>latest</LangVersion>
<Platform Condition="'$(Platform)' == ''">x64</Platform>
<Version>1.6.0-beta.4</Version>
<Version>1.6.0-beta.5</Version>
<AssemblyVersion>1.6.0.0</AssemblyVersion>
<FileVersion>1.6.0.0</FileVersion>
<InformationalVersion>1.6.0-beta.4</InformationalVersion>
<InformationalVersion>1.6.0-beta.5</InformationalVersion>
<AssemblyTitle>Console Mode</AssemblyTitle>
<Product>Console Mode</Product>
<Authors>lippdev</Authors>
Expand Down
5 changes: 4 additions & 1 deletion src/ConsoleMode/Resources/Strings.en-US.json
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,10 @@
"CloseMenu": "Close menu",
"ControlFsCard": "File explorer (ControlFS)",
"ControlFsOpen": "Browse your files with the controller",
"ControlFsMissing": "Not installed · press to get it",
"ControlFsMissing": "Not installed · press to download and install",
"ControlFsDownloading": "Downloading… {0}%",
"ControlFsInstalling": "Installing…",
"ControlFsInstallFailed": "Couldn't install · press to open the download page",
"ControlFsMissingNote": "ControlFS is not installed. Opening its download page in the browser.",
"SessionWindowsCard": "Windows",
"SessionWindowsCount": "{0} open",
Expand Down
5 changes: 4 additions & 1 deletion src/ConsoleMode/Resources/Strings.es-ES.json
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,10 @@
"CloseMenu": "Cerrar menú",
"ControlFsCard": "Explorador de archivos (ControlFS)",
"ControlFsOpen": "Explora tus archivos con el mando",
"ControlFsMissing": "No instalado · pulsa para descargarlo",
"ControlFsMissing": "No instalado · pulsa para descargar e instalar",
"ControlFsDownloading": "Descargando… {0}%",
"ControlFsInstalling": "Instalando…",
"ControlFsInstallFailed": "No se pudo instalar · pulsa para abrir la página de descarga",
"ControlFsMissingNote": "ControlFS no está instalado. Abriendo su página de descarga en el navegador.",
"SessionWindowsCard": "Ventanas",
"SessionWindowsCount": "{0} abiertas",
Expand Down
5 changes: 4 additions & 1 deletion src/ConsoleMode/Resources/Strings.pt-BR.json
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,10 @@
"CloseMenu": "Fechar menu",
"ControlFsCard": "Explorador de arquivos (ControlFS)",
"ControlFsOpen": "Navegue pelos seus arquivos com o controle",
"ControlFsMissing": "Não instalado · aperte para baixar",
"ControlFsMissing": "Não instalado · aperte para baixar e instalar",
"ControlFsDownloading": "Baixando… {0}%",
"ControlFsInstalling": "Instalando…",
"ControlFsInstallFailed": "Não deu para instalar · aperte para abrir a página de download",
"ControlFsMissingNote": "O ControlFS não está instalado. Abrindo a página de download no navegador.",
"SessionWindowsCard": "Janelas",
"SessionWindowsCount": "{0} abertas",
Expand Down
78 changes: 78 additions & 0 deletions src/ConsoleMode/Services/ControlFsInstaller.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
using System.Diagnostics;

namespace ConsoleMode.Services;

/// <summary>
/// Installs ControlFS from the session menu, when the user asks for it there: downloads the setup of its newest
/// release, checks it against GitHub's SHA-256 and runs it silently. The setup is per user (no admin prompt) and
/// does not start ControlFS when silent. Updating it afterwards is ControlFS's own business.
/// </summary>
public static class ControlFsInstaller
{
private static readonly TimeSpan SetupTimeout = TimeSpan.FromMinutes(5);

/// <summary>
/// Returns the installed exe. Throws with the reason when it can't be installed. <paramref name="progress"/> gets
/// the download from 0 to 1, then <see cref="double.PositiveInfinity"/> once the setup is running.
/// </summary>
public static async Task<string> InstallAsync(IProgress<double>? progress, CancellationToken ct = default)
{
if (!Environment.Is64BitOperatingSystem) throw new PlatformNotSupportedException("ControlFS só tem instalador x64.");
// A setup from an earlier attempt (or its Inno child, "ControlFS-Setup-x64.tmp") may still be at work:
// never start a second one next to it.
if (IsSetupRunning()) throw new InvalidOperationException("outro instalador do ControlFS ainda está rodando");

var setup = await UpdateService.FindControlFsSetupAsync(ct)
?? throw new InvalidOperationException("nenhuma release com instalador verificável");
var dir = Path.Combine(Path.GetTempPath(), "ConsoleModeUpdate");
Directory.CreateDirectory(dir);
var file = Path.Combine(dir, setup.Name);
try
{
await UpdateService.DownloadAsync(setup.Url, file, progress, ct);
if (!await UpdateIntegrity.VerifyFileAsync(file, setup.Digest, ct))
throw new InvalidDataException("o SHA-256 do instalador não confere");
AppLog.Write($"ControlFS: instalador {setup.Version} baixado e verificado");

progress?.Report(double.PositiveInfinity);
using var process = Process.Start(new ProcessStartInfo
{
FileName = file,
Arguments = "/VERYSILENT /SUPPRESSMSGBOXES /NORESTART",
UseShellExecute = false
}) ?? throw new InvalidOperationException("o instalador não iniciou");
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
timeout.CancelAfter(SetupTimeout);
try { await process.WaitForExitAsync(timeout.Token); }
catch (OperationCanceledException)
{
// Given up on: stop it (Inno runs a second, child process), or it could finish later and a new
// attempt from the menu would start a second installer next to it.
try { process.Kill(entireProcessTree: true); } catch { /* already gone */ }
await process.WaitForExitAsync(CancellationToken.None);
Comment thread
pullfrog[bot] marked this conversation as resolved.
throw new TimeoutException($"o instalador não terminou em {SetupTimeout.TotalMinutes:0} min e foi encerrado");
}
if (process.ExitCode != 0) throw new InvalidOperationException($"o instalador saiu com o código {process.ExitCode}");
}
finally
{
try { File.Delete(file); } catch { /* the temp folder is cleaned by Windows */ }
}

return ControlFsService.FindExe() ?? throw new InvalidOperationException("instalado, mas o ControlFS.exe não foi encontrado");
}

private static bool IsSetupRunning()
{
var running = false;
foreach (var process in Process.GetProcesses())
{
using (process)
{
try { running |= process.ProcessName.StartsWith("ControlFS-Setup", StringComparison.OrdinalIgnoreCase); }
catch { /* exited while listing */ }
}
}
return running;
}
}
48 changes: 48 additions & 0 deletions src/ConsoleMode/Services/ControlFsRelease.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using System.Text.Json;

namespace ConsoleMode.Services;

/// <summary>The ControlFS installer of one release: what to download and the SHA-256 it must have.</summary>
public sealed record ControlFsSetup(string Version, string Url, string Name, string Digest, long Size);

/// <summary>
/// Picks the ControlFS installer out of GitHub's list of its releases. Pure, so the rules are tested: only a
/// published release, only the x64 setup, only with GitHub's SHA-256 digest and only from that repository's
/// own downloads. Anything else is not installed from the menu (the download page opens instead).
/// </summary>
public static class ControlFsRelease
{
public const string Repository = "nextestudios/ControlFS";
public const string SetupAssetName = "ControlFS-Setup-x64.exe";
public const string DownloadPrefix = "https://github.com/" + Repository + "/releases/download/";

/// <summary>The setup of the newest published release (GitHub lists them newest first), or null.</summary>
public static ControlFsSetup? Pick(JsonElement releases)
{
if (releases.ValueKind != JsonValueKind.Array) return null;
foreach (var release in releases.EnumerateArray())
{
if (release.ValueKind != JsonValueKind.Object) continue;
if (release.TryGetProperty("draft", out var draft) && draft.ValueKind == JsonValueKind.True) continue;
if (!release.TryGetProperty("assets", out var assets) || assets.ValueKind != JsonValueKind.Array) continue;
foreach (var asset in assets.EnumerateArray())
{
if (!string.Equals(Text(asset, "name"), SetupAssetName, StringComparison.OrdinalIgnoreCase)) continue;
var url = Text(asset, "browser_download_url");
var digest = Text(asset, "digest");
// The newest release decides: without a digest or from somewhere else, nothing is run.
if (!IsTrustedUrl(url) || !UpdateIntegrity.IsValidSha256Digest(digest)) return null;
var size = asset.TryGetProperty("size", out var s) && s.TryGetInt64(out var bytes) ? bytes : 0;
return new ControlFsSetup(Text(release, "tag_name").TrimStart('v', 'V'), url, SetupAssetName, digest, size);
}
}
return null;
}

public static bool IsTrustedUrl(string? url) =>
url is not null && url.StartsWith(DownloadPrefix, StringComparison.Ordinal);

private static string Text(JsonElement element, string name) =>
element.ValueKind == JsonValueKind.Object && element.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String
? value.GetString() ?? "" : "";
}
2 changes: 2 additions & 0 deletions src/ConsoleMode/Services/LocalizationService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,8 @@ internal void NotifyAll()
public string ControlFsCard => LocalizationService.Get(nameof(ControlFsCard));
public string ControlFsOpen => LocalizationService.Get(nameof(ControlFsOpen));
public string ControlFsMissing => LocalizationService.Get(nameof(ControlFsMissing));
public string ControlFsInstalling => LocalizationService.Get(nameof(ControlFsInstalling));
public string ControlFsInstallFailed => LocalizationService.Get(nameof(ControlFsInstallFailed));
public string SessionWindowsCard => LocalizationService.Get(nameof(SessionWindowsCard));
public string SwitcherEmpty => LocalizationService.Get(nameof(SwitcherEmpty));
public string SwitcherOpen => LocalizationService.Get(nameof(SwitcherOpen));
Expand Down
16 changes: 15 additions & 1 deletion src/ConsoleMode/Services/UpdateService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,21 @@ public static async Task ApplyAsync(UpdateInfo update, IProgress<double>? progre
});
}

private static async Task DownloadAsync(string url, string file, IProgress<double>? progress, CancellationToken ct)
/// <summary>The installer of ControlFS's newest release (see <see cref="ControlFsRelease"/>), or null when there is none to trust.</summary>
internal static async Task<ControlFsSetup?> FindControlFsSetupAsync(CancellationToken ct = default)
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
timeout.CancelAfter(CheckTimeout);
using var request = new HttpRequestMessage(HttpMethod.Get, $"https://api.github.com/repos/{ControlFsRelease.Repository}/releases?per_page=10");
request.Headers.Accept.ParseAdd("application/vnd.github+json");
using var response = await Http.SendAsync(request, timeout.Token);
response.EnsureSuccessStatusCode();
await using var stream = await response.Content.ReadAsStreamAsync(timeout.Token);
using var doc = await JsonDocument.ParseAsync(stream, cancellationToken: timeout.Token);
return ControlFsRelease.Pick(doc.RootElement);
}

internal static async Task DownloadAsync(string url, string file, IProgress<double>? progress, CancellationToken ct)
{
// Cancelled only when no bytes arrive for StallTimeout, not after a fixed total time.
using var stall = CancellationTokenSource.CreateLinkedTokenSource(ct);
Expand Down
5 changes: 5 additions & 0 deletions src/ConsoleMode/SessionMenuWindow.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,11 @@
<StackPanel Grid.Column="1" VerticalAlignment="Center" Spacing="2">
<TextBlock Style="{StaticResource TileValue}" FontSize="18" Text="{x:Bind ViewModel.Texts.ControlFsCard, Mode=OneWay}"/>
<TextBlock Style="{StaticResource TileLabel}" FontSize="14" Text="{x:Bind ViewModel.ControlFsRowText, Mode=OneWay}"/>
<!-- Installing from this row: the download fills the bar, the setup leaves it running. -->
<ProgressBar Minimum="0" Maximum="100" Height="4" CornerRadius="2" Margin="0,3,0,0"
Value="{x:Bind ViewModel.ControlFsProgress, Mode=OneWay}"
IsIndeterminate="{x:Bind ViewModel.ControlFsSetupRunning, Mode=OneWay}"
Visibility="{x:Bind ViewModel.ControlFsInstalling, Mode=OneWay}"/>
</StackPanel>
</Grid>
</Button>
Expand Down
Loading
Loading