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
Expand Up @@ -7,7 +7,7 @@

<PropertyGroup>
<Title>BootstrapBlazor MediaMTX CLI</Title>
<Description>Downloads and verifies MediaMTX from GitHub and copies tools to application build and publish directories.</Description>
<Description>Downloads and verifies MediaMTX from GitHub or GitCode and copies tools to application build and publish directories.</Description>
<PackAsTool>true</PackAsTool>
<ToolCommandName>bb-mediamtx</ToolCommandName>
<PackageTags>BootstrapBlazor MediaMTX CLI</PackageTags>
Expand Down
40 changes: 25 additions & 15 deletions tools/BootstrapBlazor.MediaMtx.Cli/MediaMtxInstaller.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,15 @@ namespace BootstrapBlazor.MediaMtx.Cli;

static partial class MediaMtxInstaller
{
private const string Repository = "https://api.github.com/repos/bluenviron/mediamtx";
private static (string Repository, Uri DownloadBase) GetSource(string source) => source switch
{
"github.com" => ("https://api.github.com/repos/bluenviron/mediamtx",
new Uri("https://github.com/bluenviron/mediamtx/releases/download/")),
"gitcode.com" => ("https://api.gitcode.com/api/v5/repos/LongbowEnterprise/mediamtx",
new Uri("https://gitcode.com/LongbowEnterprise/mediamtx/releases/download/")),
_ => throw new ArgumentException($"Unsupported source '{source}'. Supported sources: github.com, gitcode.com.")
};

private static readonly JsonSerializerOptions _jsonOptions = new()
{
WriteIndented = true
Expand All @@ -30,13 +38,13 @@ static partial class MediaMtxInstaller
["osx-arm64"] = "darwin_arm64.tar.gz"
};

public static async Task DownloadAllAsync(string? output, bool copy, bool force, CancellationToken cancellationToken)
public static async Task DownloadAllAsync(string source, 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);
await DeployAsync(source, rid, null, download: true, copy: false, force: false, skipExistingOutput: false, cancellationToken);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
Expand All @@ -50,13 +58,14 @@ public static async Task DownloadAllAsync(string? output, bool copy, bool force,

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

public static async Task DeployAsync(string? rid, string? output, bool download, bool copy,
public static async Task DeployAsync(string source, string? rid, string? output, bool download, bool copy,
bool force, bool skipExistingOutput, CancellationToken cancellationToken)
{
var (repository, downloadBase) = GetSource(source);
rid ??= GetCurrentRid();
if (!_platforms.TryGetValue(rid, out var platform))
{
Expand Down Expand Up @@ -103,26 +112,26 @@ await GetHashAsync(license, cancellationToken) == installed.LicenseSha256)
}

using var client = CreateClient();
using var releaseStream = await client.GetStreamAsync($"{Repository}/releases/tags/{tag}", cancellationToken);
using var releaseStream = await client.GetStreamAsync($"{repository}/releases/tags/{tag}", cancellationToken);
using var release = await JsonDocument.ParseAsync(releaseStream, cancellationToken: cancellationToken);
if (release.RootElement.GetProperty("tag_name").GetString() != tag)
{
throw new InvalidDataException("The GitHub release does not match the requested version.");
throw new InvalidDataException($"The {source} release does not match the requested version.");
}
var assetName = $"mediamtx_{tag}_{platform}";
var assets = release.RootElement.GetProperty("assets");
var asset = assets.EnumerateArray().FirstOrDefault(item => item.GetProperty("name").GetString() == assetName);
if (asset.ValueKind == JsonValueKind.Undefined)
{
throw new InvalidDataException($"Release '{tag}' has no asset for '{rid}' ({assetName}).");
throw new InvalidDataException($"Release '{tag}' on {source} has no asset for '{rid}' ({assetName}).");
}
var digest = await GetAssetDigestAsync(client, assets, asset, assetName, cancellationToken);
var digest = await GetAssetDigestAsync(client, assets, asset, assetName, downloadBase, cancellationToken);
var staging = Path.Combine(toolRoot, $".install-{Guid.NewGuid():N}");
Directory.CreateDirectory(staging);
try
{
var archivePath = Path.Combine(staging, platform.EndsWith(".zip", StringComparison.Ordinal) ? "archive.zip" : "archive.tar.gz");
var assetUrl = GetAssetUrl(asset);
var assetUrl = GetAssetUrl(asset, downloadBase);
await Console.Out.WriteLineAsync($"Downloading {assetName} from {assetUrl}", cancellationToken);
await DownloadAsync(client, assetUrl, archivePath, cancellationToken);
if (await GetHashAsync(archivePath, cancellationToken) != digest)
Expand Down Expand Up @@ -273,18 +282,19 @@ private static string GetCurrentRid()
return $"{os}-{RuntimeInformation.OSArchitecture.ToString().ToLowerInvariant()}";
}

private static Uri GetAssetUrl(JsonElement asset)
private static Uri GetAssetUrl(JsonElement asset, Uri downloadBase)
{
var url = asset.GetProperty("browser_download_url").GetString();
if (!Uri.TryCreate(url, UriKind.Absolute, out var uri) || uri.Scheme != Uri.UriSchemeHttps ||
uri.Host != "github.com" || !uri.AbsolutePath.StartsWith("/bluenviron/mediamtx/releases/download/", StringComparison.Ordinal))
uri.Host != downloadBase.Host || !uri.AbsolutePath.StartsWith(downloadBase.AbsolutePath, StringComparison.Ordinal))
{
throw new InvalidDataException("The release asset is not a MediaMTX GitHub download.");
throw new InvalidDataException($"The release asset is not a MediaMTX download from {downloadBase.Host}.");
}
return uri;
}

private static async Task<string> GetAssetDigestAsync(HttpClient client, JsonElement assets, JsonElement asset, string assetName, CancellationToken cancellationToken)
private static async Task<string> GetAssetDigestAsync(HttpClient client, JsonElement assets, JsonElement asset, string assetName,
Uri downloadBase, CancellationToken cancellationToken)
{
if (asset.TryGetProperty("digest", out var digest) && digest.GetString() is { } value &&
value.StartsWith("sha256:", StringComparison.Ordinal))
Expand All @@ -297,7 +307,7 @@ private static async Task<string> GetAssetDigestAsync(HttpClient client, JsonEle
{
throw new InvalidDataException($"No SHA-256 checksum is available for '{assetName}'.");
}
var checksums = await client.GetStringAsync(GetAssetUrl(checksumAsset), cancellationToken);
var checksums = await client.GetStringAsync(GetAssetUrl(checksumAsset, downloadBase), cancellationToken);
foreach (var line in checksums.Split('\n'))
{
var parts = line.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);
Expand Down
29 changes: 23 additions & 6 deletions tools/BootstrapBlazor.MediaMtx.Cli/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,17 @@
if (args.Contains("--help") || args.Contains("-h"))
{
await Console.Out.WriteLineAsync("""
Usage: bb-mediamtx [--download] [--copy] [--rid <rid>] [--output <directory>] [--force]
Usage: bb-mediamtx [--download] [--copy] [--source <source>] [--rid <rid>] [--output <directory>] [--force]
bb-mediamtx --help
bb-mediamtx -h

Without --download or --copy, copy missing files from the cache.
--download Verify the cache for the selected RID; download from GitHub if missing
--download Verify the cache for the selected RID; download from the selected source 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.
--source <source> Select github.com (default) or gitcode.com for downloads.
Sources share the same cache. Does not force a download or enable downloading.
--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,
Expand All @@ -31,12 +33,13 @@ Cannot be used with --download unless --copy is also specified.

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
BootstrapBlazor/mediamtx. Options, sources 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 --source gitcode.com
bb-mediamtx --download --rid all
bb-mediamtx --download --copy --rid linux-arm64 --output publish
bb-mediamtx --copy --rid linux-arm64 --output publish --force
Expand All @@ -56,6 +59,7 @@ cannot be repeated.
{
string? rid = null;
string? output = null;
string? source = null;
var ridSpecified = false;
var force = false;
var download = false;
Expand All @@ -73,6 +77,18 @@ cannot be repeated.
case "--copy" when !copy:
copy = true;
break;
case "--source" when source is null:
if (index + 1 == args.Length || args[index + 1].StartsWith("--", StringComparison.Ordinal) ||
string.IsNullOrWhiteSpace(args[index + 1]))
{
throw new ArgumentException("Option '--source' requires github.com or gitcode.com.");
}
source = args[++index].Trim();
if (source is not ("github.com" or "gitcode.com"))
{
throw new ArgumentException($"Unsupported source '{source}'. Supported sources: github.com, gitcode.com.");
}
break;
case "--rid" when !ridSpecified:
if (index + 1 == args.Length || args[index + 1].StartsWith("--", StringComparison.Ordinal))
{
Expand All @@ -91,22 +107,23 @@ cannot be repeated.
output = args[++index];
break;
default:
throw new ArgumentException("Usage: bb-mediamtx [--download] [--copy] [--rid <rid>] [--output <directory>] [--force].");
throw new ArgumentException("Usage: bb-mediamtx [--download] [--copy] [--source <source>] [--rid <rid>] [--output <directory>] [--force].");
}
}
if (download && !copy && force)
{
throw new ArgumentException("Option '--force' requires copying; use it with '--copy'.");
}
source ??= "github.com";
var defaultAction = !download && !copy;
if (download && rid == "all")
{
cancellation.CancelAfter(TimeSpan.FromMinutes(30));
await MediaMtxInstaller.DownloadAllAsync(output, copy, force, cancellation.Token);
await MediaMtxInstaller.DownloadAllAsync(source, output, copy, force, cancellation.Token);
}
else
{
await MediaMtxInstaller.DeployAsync(rid, output, download, copy || defaultAction, force,
await MediaMtxInstaller.DeployAsync(source, rid, output, download, copy || defaultAction, force,
skipExistingOutput: !download, cancellationToken: cancellation.Token);
}
}
Expand Down
23 changes: 16 additions & 7 deletions tools/BootstrapBlazor.MediaMtx.Cli/readme.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# BootstrapBlazor.MediaMtx.Cli

独立的 .NET CLI 工具,用于下载、校验和缓存 [MediaMTX](https://github.com/bluenviron/mediamtx/releases),并将可执行文件和许可证复制到应用目录。工具包不包含 MediaMTX 二进制文件;`BootstrapBlazor.MediaMtx` 主包也不会自动安装 CLI 或下载 MediaMTX。
独立的 .NET CLI 工具,用于从 [GitHub](https://github.com/bluenviron/mediamtx/releases) 或 [GitCode](https://gitcode.com/LongbowEnterprise/mediamtx/releases) 下载、校验和缓存 MediaMTX,并将可执行文件和许可证复制到应用目录。工具包不包含 MediaMTX 二进制文件;`BootstrapBlazor.MediaMtx` 主包也不会自动安装 CLI 或下载 MediaMTX。

CLI 目标为 .NET 11:安装工具需要 .NET SDK,运行需要 .NET 11 运行时。若只有更高主版本的运行时,需另行启用运行时 roll-forward。

Expand All @@ -21,7 +21,7 @@ bb-mediamtx --help
"isRoot": true,
"tools": {
"bootstrapblazor.mediamtx.cli": {
"version": "11.0.3",
"version": "11.0.4",
"commands": ["bb-mediamtx"]
}
}
Expand All @@ -40,16 +40,17 @@ dotnet bb-mediamtx --help
## 参数

```text
bb-mediamtx [--download] [--copy] [--rid <rid>] [--output <directory>] [--force]
bb-mediamtx [--download] [--copy] [--source <source>] [--rid <rid>] [--output <directory>] [--force]
bb-mediamtx --help
```

参数顺序不限;参数名和 RID 区分大小写,动作及其选项不能重复。包含 `--help` 或 `-h` 时只显示帮助。
参数顺序不限;参数名、下载源和 RID 区分大小写,动作及其选项不能重复。包含 `--help` 或 `-h` 时只显示帮助。

| 参数 | 说明 |
| --- | --- |
| `--download` | 检查目标 RID 的缓存,缺失或校验失败时从 GitHub 下载并校验;不单独复制到输出目录。下载时显示资源地址和进度。 |
| `--download` | 检查目标 RID 的缓存,缺失或校验失败时从指定源下载并校验;不单独复制到输出目录。下载时显示资源地址和进度。 |
| `--copy` | 从已校验的缓存复制工具和许可证,不联网;缓存缺失或损坏时输出警告。可与 `--download` 组合。 |
| `--source <source>` | 下载源,只接受 `github.com`(默认)或 `gitcode.com`。两者共用缓存;设置此参数不自动下载、不强制刷新缓存,也不在源之间自动回退。 |
| `--rid <rid>` | 指定目标平台。省略或显式传入空字符串时使用当前操作系统和架构。`--download --rid all` 准备全部支持平台;与 `--copy` 组合时只复制本机平台。`all` 不能单独用于复制。 |
| `--output <directory>` | 复制的输出基目录。省略时使用命令执行时的当前工作目录;相对路径也以当前工作目录为基准。仅下载时不使用此参数。 |
| `--force` | 复制时覆盖输出目录中已有的可执行文件和许可证,不强制重新下载;有效缓存仍会复用。单独 `--download` 不能与 `--force` 组合。 |
Expand All @@ -70,6 +71,12 @@ bb-mediamtx --download
bb-mediamtx --copy --output .\publish
```

使用 GitCode 下载并复制:

```powershell
bb-mediamtx --download --copy --source gitcode.com --rid win-x64 --output .\publish
```

准备指定平台并复制;也可以合并两个动作:

```powershell
Expand All @@ -94,11 +101,13 @@ bb-mediamtx --copy --rid linux-arm64 --output .\publish --force

## 缓存和故障排查

CLI 固定使用 MediaMTX `1.22.0`,缓存位于本机应用数据目录下的 `BootstrapBlazor\mediamtx\v1.22.0\<RID>`,构建和发布共用。下载通过 GitHub 发布 API 获取资源,校验 SHA-256 后只提取可执行文件和许可证,不使用压缩包中的 `mediamtx.yml`。有效缓存会校验后复用;下载进度在可获取文件大小时显示百分比,否则显示已下载字节数。
CLI 固定使用 MediaMTX `1.22.0`,缓存位于本机应用数据目录下的 `BootstrapBlazor\mediamtx\v1.22.0\<RID>`,不同下载源、构建和发布共用。下载通过所选源的发布 API 获取同名附件及 SHA-256,校验后只提取可执行文件和许可证,不使用压缩包中的 `mediamtx.yml`。有效缓存会校验后复用;下载进度在可获取文件大小时显示百分比,否则显示已下载字节数。

GitHub 使用 `bluenviron/mediamtx`,GitCode 使用 `LongbowEnterprise/mediamtx`。所选源必须提供目标平台附件和 SHA-256;缺失时输出警告,不自动切换到其他源。`--copy` 即使指定下载源也不会联网。

`--download --rid all` 逐个平台处理,某个平台失败会输出警告并继续;其他模式处理指定或本机平台。参数、下载、校验、复制失败或取消时 CLI 输出警告,但仍以成功状态退出,以免阻断宿主构建或发布。因此不能只依据退出码判断是否部署成功,应检查警告及目标文件。

离线构建前需在有网络时准备目标 RID 的缓存,并提前安装 CLI。若复制时提示缓存缺失或损坏,先用相同 RID 执行 `--download`。如需更新已经存在的输出文件,复制时添加 `--force`;它不强制从 GitHub 重新下载。
离线构建前需在有网络时准备目标 RID 的缓存,并提前安装 CLI。若复制时提示缓存缺失或损坏,先用相同 RID 执行 `--download`。如需更新已经存在的输出文件,复制时添加 `--force`;它不强制重新下载。

在 Linux/macOS 上安装时会设置可执行权限;从 Windows 跨平台复制后,需在目标机器上设置执行权限。`--force` 不能绕过文件占用或权限限制。

Expand Down
Loading