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
Original file line number Diff line number Diff line change
@@ -1,19 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks />
<TargetFramework>net8.0</TargetFramework>
<Version>11.0.2</Version>
<OutputType>Exe</OutputType>
<Version>11.0.0</Version>
</PropertyGroup>

<PropertyGroup>
<Title>BootstrapBlazor MediaMTX CLI</Title>
<Description>Downloads and verifies MediaMTX from GitHub and copies tools to application build and publish directories.</Description>
<PackAsTool>true</PackAsTool>
<ToolCommandName>bb-mediamtx</ToolCommandName>
<RollForward>Major</RollForward>
<RootNamespace>BootstrapBlazor.MediaMtx.Cli</RootNamespace>
<Description>Downloads and verifies MediaMTX from GitHub and copies tools to application build and publish directories.</Description>
<PackageTags>BootstrapBlazor MediaMTX CLI</PackageTags>
<PackageReadmeFile>readme.md</PackageReadmeFile>
</PropertyGroup>

<ItemGroup>
<SupportedPlatform Remove="browser" />
</ItemGroup>

<ItemGroup>
<None Include="readme.md" Pack="true" PackagePath="" />
</ItemGroup>

</Project>
118 changes: 97 additions & 21 deletions tools/BootstrapBlazor.MediaMtx.Cli/MediaMtxInstaller.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
// See the LICENSE file in the project root for more information.
// Maintainer: Argo Zhang([email protected]) Website: https://www.blazor.zone

using System.Diagnostics;
using System.Formats.Tar;
using System.IO.Compression;
using System.Runtime.InteropServices;
Expand All @@ -12,9 +13,13 @@

namespace BootstrapBlazor.MediaMtx.Cli;

static class MediaMtxInstaller
static partial class MediaMtxInstaller
{
private const string Repository = "https://api.github.com/repos/bluenviron/mediamtx";
private static readonly JsonSerializerOptions _jsonOptions = new()
{
WriteIndented = true
};
private static readonly Dictionary<string, string> _platforms = new(StringComparer.Ordinal)
{
["win-x64"] = "windows_amd64.zip",
Expand All @@ -25,19 +30,46 @@ static class MediaMtxInstaller
["osx-arm64"] = "darwin_arm64.tar.gz"
};

public static async Task DeployAsync(string? rid, CancellationToken cancellationToken, bool force = false)
public static async Task DownloadAllAsync(string? output, bool copy, bool force, CancellationToken cancellationToken)
{
foreach (var rid in _platforms.Keys)
{
try
{
await DeployAsync(rid, null, download: true, copy: false, force: false, skipExistingOutput: false, cancellationToken);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
throw;
}
catch (Exception exception)
{
await Console.Out.WriteLineAsync($"[MediaMTX] Warning - deployment failed for {rid}: {exception.Message}", cancellationToken);
}
}

if (copy)
{
await DeployAsync(null, output, download: false, copy: true, force, skipExistingOutput: false, cancellationToken);
}
}

public static async Task DeployAsync(string? rid, string? output, bool download, bool copy,
bool force, bool skipExistingOutput, CancellationToken cancellationToken)
{
rid ??= GetCurrentRid();
if (!_platforms.TryGetValue(rid, out var platform))
{
throw new ArgumentException($"Unsupported RID '{rid}'. Supported RIDs: {string.Join(", ", _platforms.Keys)}.");
}
var outputDirectory = Path.Combine(Directory.GetCurrentDirectory(), "mediamtx-tools", rid);
var outputDirectory = copy
? Path.Combine(Path.GetFullPath(output ?? Directory.GetCurrentDirectory()), "mediamtx-tools", rid)
: string.Empty;
var executableName = rid == "win-x64" ? "mediamtx.exe" : "mediamtx";
if (!force && File.Exists(Path.Combine(outputDirectory, executableName)) &&
if (copy && skipExistingOutput && !force && File.Exists(Path.Combine(outputDirectory, executableName)) &&
File.Exists(Path.Combine(outputDirectory, "LICENSE.MediaMTX")))
{
await Console.Out.WriteLineAsync($"MediaMTX tools already exist at {outputDirectory}; skipping deployment.");
await Console.Out.WriteLineAsync($"MediaMTX tools already exist at {outputDirectory}; skipping deployment.", cancellationToken);
return;
}

Expand All @@ -57,11 +89,19 @@ await GetHashAsync(executable, cancellationToken) == installed.ExecutableSha256
await GetHashAsync(license, cancellationToken) == installed.LicenseSha256)
{
SetExecutablePermission(executable);
await Console.Out.WriteLineAsync($"MediaMTX {tag} for {rid}: verified cached tools at {toolDirectory}");
await CopyToolsAsync(toolDirectory, rid, outputDirectory, cancellationToken, force);
await Console.Out.WriteLineAsync($"MediaMTX {tag} for {rid}: verified cached tools at {toolDirectory}", cancellationToken);
if (copy)
{
await CopyToolsAsync(toolDirectory, rid, outputDirectory, force, cancellationToken);
}
return;
}

if (!download)
{
throw new InvalidDataException($"MediaMTX cache for {rid} is missing or invalid at {toolDirectory}. Run dotnet bb-mediamtx --download first.");
}

using var client = CreateClient();
using var releaseStream = await client.GetStreamAsync($"{Repository}/releases/tags/{tag}", cancellationToken);
using var release = await JsonDocument.ParseAsync(releaseStream, cancellationToken: cancellationToken);
Expand All @@ -82,12 +122,9 @@ await GetHashAsync(license, cancellationToken) == installed.LicenseSha256)
try
{
var archivePath = Path.Combine(staging, platform.EndsWith(".zip", StringComparison.Ordinal) ? "archive.zip" : "archive.tar.gz");
await Console.Out.WriteLineAsync($"Downloading {assetName} from GitHub...");
await using (var source = await client.GetStreamAsync(GetAssetUrl(asset), cancellationToken))
await using (var destination = File.Create(archivePath))
{
await source.CopyToAsync(destination, cancellationToken);
}
var assetUrl = GetAssetUrl(asset);
await Console.Out.WriteLineAsync($"Downloading {assetName} from {assetUrl}", cancellationToken);
await DownloadAsync(client, assetUrl, archivePath, cancellationToken);
if (await GetHashAsync(archivePath, cancellationToken) != digest)
{
throw new InvalidDataException($"SHA-256 verification failed for '{assetName}'. No tool files were installed.");
Expand All @@ -108,11 +145,14 @@ await GetHashAsync(stagedExecutable, cancellationToken),
File.Move(stagedExecutable, executable, overwrite: true);
File.Move(stagedLicense, license, overwrite: true);
var stagedMarker = Path.Combine(staging, "installation.json");
await File.WriteAllTextAsync(stagedMarker, JsonSerializer.Serialize(installation, new JsonSerializerOptions { WriteIndented = true }), cancellationToken);
await File.WriteAllTextAsync(stagedMarker, JsonSerializer.Serialize(installation, _jsonOptions), cancellationToken);
File.Move(stagedMarker, markerPath, overwrite: true);
await Console.Out.WriteLineAsync($"Prepared MediaMTX {tag} for {rid}.");
await Console.Out.WriteLineAsync($"Tools: {toolDirectory}");
await CopyToolsAsync(toolDirectory, rid, outputDirectory, cancellationToken, force);
await Console.Out.WriteLineAsync($"Prepared MediaMTX {tag} for {rid}.", cancellationToken);
await Console.Out.WriteLineAsync($"Tools: {toolDirectory}", cancellationToken);
if (copy)
{
await CopyToolsAsync(toolDirectory, rid, outputDirectory, force, cancellationToken);
}
}
finally
{
Expand All @@ -132,7 +172,7 @@ await GetHashAsync(stagedExecutable, cancellationToken),
}
catch (JsonException exception)
{
await Console.Error.WriteLineAsync($"Invalid MediaMTX cache record '{markerPath}': {exception.Message}. Tools will be verified and downloaded again.");
await Console.Error.WriteLineAsync($"Invalid MediaMTX cache record '{markerPath}': {exception.Message}.", cancellationToken);
return null;
}
}
Expand All @@ -144,7 +184,40 @@ private static HttpClient CreateClient()
return client;
}

private static async Task CopyToolsAsync(string toolDirectory, string rid, string destinationDirectory, CancellationToken cancellationToken, bool force)
private static async Task DownloadAsync(HttpClient client, Uri uri, string archivePath, CancellationToken cancellationToken)
{
using var response = await client.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
response.EnsureSuccessStatusCode();
var total = response.Content.Headers.ContentLength;
await using var source = await response.Content.ReadAsStreamAsync(cancellationToken);
await using var destination = File.Create(archivePath);
var buffer = new byte[81920];
long downloaded = 0;
var lastPercent = -5;
var timer = Stopwatch.StartNew();
while (await source.ReadAsync(buffer, cancellationToken) is var count && count > 0)
{
await destination.WriteAsync(buffer.AsMemory(0, count), cancellationToken);
downloaded += count;
if (total is > 0)
{
var percent = (int)Math.Min(100, downloaded * 100.0 / total.Value);
if (percent >= lastPercent + 5)
{
await Console.Out.WriteLineAsync($"Downloaded {downloaded} / {total} bytes ({percent}%).", cancellationToken);
lastPercent = percent;
}
}
else if (timer.Elapsed >= TimeSpan.FromSeconds(1))
{
await Console.Out.WriteLineAsync($"Downloaded {downloaded} bytes.", cancellationToken);
timer.Restart();
}
}
await Console.Out.WriteLineAsync($"Download complete: {downloaded} bytes.", cancellationToken);
}

private static async Task CopyToolsAsync(string toolDirectory, string rid, string destinationDirectory, bool force, CancellationToken cancellationToken)
{
Directory.CreateDirectory(destinationDirectory);
var executableName = rid == "win-x64" ? "mediamtx.exe" : "mediamtx";
Expand Down Expand Up @@ -175,7 +248,7 @@ private static async Task CopyToolsAsync(string toolDirectory, string rid, strin
File.Delete(temporary);
}
}
await Console.Out.WriteLineAsync($"MediaMTX tools copied to {destinationDirectory}");
await Console.Out.WriteLineAsync($"MediaMTX tools copied to {destinationDirectory}", cancellationToken);
}

private static async Task<FileStream> AcquireCacheLockAsync(string path, CancellationToken cancellationToken)
Expand Down Expand Up @@ -238,13 +311,16 @@ private static async Task<string> GetAssetDigestAsync(HttpClient client, JsonEle

private static string ValidateHash(string value)
{
if (!Regex.IsMatch(value, "^[0-9a-fA-F]{64}$", RegexOptions.CultureInvariant))
if (!Sha256Regex().IsMatch(value))
{
throw new InvalidDataException("The release SHA-256 checksum is invalid.");
}
return value.ToLowerInvariant();
}

[GeneratedRegex("^[0-9a-fA-F]{64}$", RegexOptions.CultureInvariant)]
private static partial Regex Sha256Regex();

private static async Task<string> GetHashAsync(string path, CancellationToken cancellationToken)
{
await using var stream = File.OpenRead(path);
Expand Down
95 changes: 74 additions & 21 deletions tools/BootstrapBlazor.MediaMtx.Cli/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,44 @@
// Maintainer: Argo Zhang([email protected]) Website: https://www.blazor.zone

using BootstrapBlazor.MediaMtx.Cli;
using System.Text.Json;

if (args.Contains("--help") || args.Contains("-h"))
{
await Console.Out.WriteLineAsync("""
bb-mediamtx [--rid <rid>] [--force]
Usage: bb-mediamtx [--download] [--copy] [--rid <rid>] [--output <directory>] [--force]
bb-mediamtx --help
bb-mediamtx -h

Copies missing MediaMTX 1.21.4 tools to mediamtx-tools/<rid> in the current directory.
By default, existing files are not overwritten and complete output skips cache checks and downloads.
The tool cache is stored under local application data in BootstrapBlazor/mediamtx.
--rid win-x64, linux-x64, linux-arm64, linux-arm, osx-x64, osx-arm64.
Defaults to the current operating system and architecture.
--force Verify/prepare the cache and overwrite the output executable and license.
""");
return 0;
Without --download or --copy, copy missing files from the cache.
--download Verify the cache for the selected RID; download from GitHub if missing
or invalid. Shows the download URL and progress. Does not copy by itself.
--copy Copy the executable and license from the verified cache without downloading.
Can be combined with --download.
--rid <rid> Select win-x64, linux-x64, linux-arm64, linux-arm, osx-x64, or osx-arm64.
Omitted or empty selects the current OS and architecture.
With --download, all prepares every supported RID; combined with --copy,
only the current RID is copied. all cannot be used for copy alone.
When preparing all RIDs, failures are reported and processing continues.
--output <directory> Base directory for copies; defaults to the current working directory.
Relative paths are based on the current working directory.
Files go to mediamtx-tools/<rid> under this directory.
--force Overwrite existing output files; does not force a download.
Cannot be used with --download unless --copy is also specified.
--help, -h Show this help without performing other actions.

Existing output files are preserved unless --force is used. Copy-only skips cache validation
when both output files already exist. The cache is under local application data in
BootstrapBlazor/mediamtx. Options and RIDs are case-sensitive; options other than help
cannot be repeated.
Failures and cancellations are warnings and do not produce a nonzero exit code.

Examples:
bb-mediamtx --download
bb-mediamtx --download --rid all
bb-mediamtx --download --copy --rid linux-arm64 --output publish
bb-mediamtx --copy --rid linux-arm64 --output publish --force
""", CancellationToken.None);
return;
}

using var cancellation = new CancellationTokenSource();
Expand All @@ -32,36 +55,66 @@ Defaults to the current operating system and architecture.
try
{
string? rid = null;
string? output = null;
var ridSpecified = false;
var force = false;
var download = false;
var copy = false;
for (var index = 0; index < args.Length; index++)
{
switch (args[index])
{
case "--force" when !force:
force = true;
break;
case "--rid" when rid is null:
case "--download" when !download:
download = true;
break;
case "--copy" when !copy:
copy = true;
break;
case "--rid" when !ridSpecified:
if (index + 1 == args.Length || args[index + 1].StartsWith("--", StringComparison.Ordinal))
{
throw new ArgumentException("Option '--rid' requires a value.");
}
rid = args[++index];
ridSpecified = true;
var ridArgument = args[++index].Trim();
rid = ridArgument.Length == 0 ? null : ridArgument;
break;
case "--output" when output is null:
if (index + 1 == args.Length || args[index + 1].StartsWith("--", StringComparison.Ordinal) ||
string.IsNullOrWhiteSpace(args[index + 1]))
{
throw new ArgumentException("Option '--output' requires a directory.");
}
output = args[++index];
break;
default:
throw new ArgumentException("Usage: bb-mediamtx [--rid <rid>] [--force].");
throw new ArgumentException("Usage: bb-mediamtx [--download] [--copy] [--rid <rid>] [--output <directory>] [--force].");
}
}
await MediaMtxInstaller.DeployAsync(rid, cancellation.Token, force);
return 0;
if (download && !copy && force)
{
throw new ArgumentException("Option '--force' requires copying; use it with '--copy'.");
}
var defaultAction = !download && !copy;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Deployment succeeds without MediaMTX

When the default action runs with an empty cache, defaultAction calls MediaMtxInstaller.DeployAsync with download false, so cache validation fails and the CLI reports a warning while exiting successfully; the documented deployment finishes without MediaMTX files.

Make the default action download the required files before copying them, or otherwise ensure a missing cache causes deployment to fail rather than report success.

Also at tools/BootstrapBlazor.MediaMtx.Cli/Program.cs:109-110.

Prompt for AI agents
In `tools/BootstrapBlazor.MediaMtx.Cli/Program.cs` at line 101:

**Deployment succeeds without MediaMTX**

When the default action runs with an empty cache, `defaultAction` calls `MediaMtxInstaller.DeployAsync` with `download` false, so cache validation fails and the CLI reports a warning while exiting successfully; the documented deployment finishes without MediaMTX files.

Make the default action download the required files before copying them, or otherwise ensure a missing cache causes deployment to fail rather than report success.

Also at `tools/BootstrapBlazor.MediaMtx.Cli/Program.cs:109-110`.

From #1374:

Deploy MediaMTX 1.21.4 under `mediamtx-tools/<RID>` in the current directory, automatically detecting the platform or accepting `--rid`.

if (download && rid == "all")
{
cancellation.CancelAfter(TimeSpan.FromMinutes(30));
await MediaMtxInstaller.DownloadAllAsync(output, copy, force, cancellation.Token);
}
else
{
await MediaMtxInstaller.DeployAsync(rid, output, download, copy || defaultAction, force,
skipExistingOutput: !download, cancellationToken: cancellation.Token);
}
}
catch (OperationCanceledException)
{
await Console.Error.WriteLineAsync("MediaMTX deployment was canceled or timed out.");
return 130;
await Console.Out.WriteLineAsync("[MediaMTX] Warning - deployment was canceled or timed out.", CancellationToken.None);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Failed deployments report success

When a build or publish invokes the CLI and parsing, downloading, cache validation, copying, or cancellation fails, Program catches cancellation and every other exception, prints a warning, and exits normally with status 0; build or publish automation therefore reports success even when parsing, downloading, cache validation, or copying failed and the output is missing MediaMTX files.

Return a nonzero exit status for failed operations, or make success-on-failure an explicit opt-in that host automation can handle deliberately.

Also at tools/BootstrapBlazor.MediaMtx.Cli/Program.cs:117-120.

Prompt for AI agents
In `tools/BootstrapBlazor.MediaMtx.Cli/Program.cs` at line 115:

**Failed deployments report success**

When a build or publish invokes the CLI and parsing, downloading, cache validation, copying, or cancellation fails, `Program` catches cancellation and every other exception, prints a warning, and exits normally with status 0; build or publish automation therefore reports success even when parsing, downloading, cache validation, or copying failed and the output is missing MediaMTX files.

Return a nonzero exit status for failed operations, or make success-on-failure an explicit opt-in that host automation can handle deliberately.

Also at `tools/BootstrapBlazor.MediaMtx.Cli/Program.cs:117-120`.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Failed copies report success

When a forced copy is interrupted or encounters an I/O error after replacing one output file but before replacing the other, CopyToolsAsync can replace the executable and then fail before replacing the license; Program catches the exception and returns success, and a later non-forced copy skips because both files exist, leaving a mixed deployment in place.

Commit the executable and license as one recoverable deployment, or ensure failed copies are reported as failures and subsequent copies detect and repair an incomplete pair.

Prompt for AI agents
In `tools/BootstrapBlazor.MediaMtx.Cli/Program.cs` at line 115:

**Failed copies report success**

When a forced copy is interrupted or encounters an I/O error after replacing one output file but before replacing the other, `CopyToolsAsync` can replace the executable and then fail before replacing the license; `Program` catches the exception and returns success, and a later non-forced copy skips because both files exist, leaving a mixed deployment in place.

Commit the executable and license as one recoverable deployment, or ensure failed copies are reported as failures and subsequent copies detect and repair an incomplete pair.

}
catch (Exception exception) when (exception is ArgumentException or InvalidOperationException or
IOException or UnauthorizedAccessException or HttpRequestException or JsonException or NotSupportedException)
catch (Exception exception)
{
await Console.Error.WriteLineAsync($"MediaMTX deployment failed: {exception.Message}");
return 1;
await Console.Out.WriteLineAsync($"[MediaMTX] Warning - deployment failed: {exception.Message}", CancellationToken.None);
}
Loading
Loading