feat(postit): capture écran et audio sous Linux
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
parent
3bf7dd88f5
commit
82095f4435
14 changed files with 533 additions and 29 deletions
|
|
@ -36,6 +36,10 @@
|
||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
|
|
||||||
|
* [PostIt/Capture] Automatically upload finalized screen recordings as `video/mp4` to `Mes fichiers / screencast`, streaming the multipart file from disk and retaining the local copy if the upload fails.
|
||||||
|
|
||||||
|
* [PostIt/Capture] Decode the PipeWire node identifier from the ScreenCast portal `streams` array of `(node id, properties)` structures, let the user choose a full screen, a window or the portal picker, and mux system audio from the default output monitor into the H.264/AAC MP4. Stop GStreamer with SIGINT so the muxer receives EOS and writes a valid `moov` atom.
|
||||||
|
|
||||||
* [PostIt.Tests] Run every Avalonia UI test in the shared `AvaloniaUiCollection` fixture: replace `[AvaloniaFact]`/`[AvaloniaTheory]` and direct `GetOrStartForAssembly` dispatches, which started a second headless session alongside the fixture's and could hang `PodcastBroadcasterTests`, with `ui.RunAsync` (new synchronous overload). Update contact-preference assertions in `MessagingSessionTests` for the audio-only capabilities the Linux desktop announces.
|
* [PostIt.Tests] Run every Avalonia UI test in the shared `AvaloniaUiCollection` fixture: replace `[AvaloniaFact]`/`[AvaloniaTheory]` and direct `GetOrStartForAssembly` dispatches, which started a second headless session alongside the fixture's and could hang `PodcastBroadcasterTests`, with `ui.RunAsync` (new synchronous overload). Update contact-preference assertions in `MessagingSessionTests` for the audio-only capabilities the Linux desktop announces.
|
||||||
|
|
||||||
* [PostIt/Podcasts] Reuse the replay playback controls for live video on desktop and Android, remove the duplicate play/pause button, and retain seeking only for replays. Report resume failures and cover playback controls with targeted tests.
|
* [PostIt/Podcasts] Reuse the replay playback controls for live video on desktop and Android, remove the duplicate play/pause button, and retain seeking only for replays. Report resume failures and cover playback controls with targeted tests.
|
||||||
|
|
|
||||||
|
|
@ -23,6 +23,7 @@ public class LinuxScreenCaptureService : IScreenCaptureService
|
||||||
|
|
||||||
private DBusConnection? _dbusConnection;
|
private DBusConnection? _dbusConnection;
|
||||||
private Process? _gstProcess;
|
private Process? _gstProcess;
|
||||||
|
private Task<string>? _gstErrorOutput;
|
||||||
private SafeFileHandle? _pipewireFd;
|
private SafeFileHandle? _pipewireFd;
|
||||||
private CancellationTokenSource? _timerCts;
|
private CancellationTokenSource? _timerCts;
|
||||||
|
|
||||||
|
|
@ -32,9 +33,13 @@ public class LinuxScreenCaptureService : IScreenCaptureService
|
||||||
[DllImport("libc", SetLastError = true)]
|
[DllImport("libc", SetLastError = true)]
|
||||||
private static extern int fcntl(int fd, int cmd, int arg);
|
private static extern int fcntl(int fd, int cmd, int arg);
|
||||||
|
|
||||||
|
[DllImport("libc", SetLastError = true)]
|
||||||
|
private static extern int kill(int pid, int sig);
|
||||||
|
|
||||||
private const int F_GETFD = 1;
|
private const int F_GETFD = 1;
|
||||||
private const int F_SETFD = 2;
|
private const int F_SETFD = 2;
|
||||||
private const int FD_CLOEXEC = 1;
|
private const int FD_CLOEXEC = 1;
|
||||||
|
private const int SIGINT = 2;
|
||||||
|
|
||||||
public string? LatestRestoreToken { get; private set; }
|
public string? LatestRestoreToken { get; private set; }
|
||||||
|
|
||||||
|
|
@ -52,6 +57,8 @@ public class LinuxScreenCaptureService : IScreenCaptureService
|
||||||
{
|
{
|
||||||
if (IsRecording) throw new InvalidOperationException("Un enregistrement est déjà en cours.");
|
if (IsRecording) throw new InvalidOperationException("Un enregistrement est déjà en cours.");
|
||||||
|
|
||||||
|
LatestRestoreToken = options.RestoreToken;
|
||||||
|
|
||||||
// 1. Connexion D-Bus avec DBusConnection et DBusAddress
|
// 1. Connexion D-Bus avec DBusConnection et DBusAddress
|
||||||
_dbusConnection = new DBusConnection(DBusAddress.Session!);
|
_dbusConnection = new DBusConnection(DBusAddress.Session!);
|
||||||
await _dbusConnection.ConnectAsync();
|
await _dbusConnection.ConnectAsync();
|
||||||
|
|
@ -68,16 +75,19 @@ public class LinuxScreenCaptureService : IScreenCaptureService
|
||||||
() => CallCreateSessionAsync(createToken, sessionToken),
|
() => CallCreateSessionAsync(createToken, sessionToken),
|
||||||
cancellationToken
|
cancellationToken
|
||||||
);
|
);
|
||||||
if (createResponse.TryGetValue("restore_token", out var tokenVariant))
|
|
||||||
{
|
|
||||||
LatestRestoreToken = tokenVariant.GetString();
|
|
||||||
// Pense à sauvegarder LatestRestoreToken dans tes préférences utilisateur ici !
|
|
||||||
}
|
|
||||||
|
|
||||||
string sessionHandle = createResponse["session_handle"].GetString();
|
string sessionHandle = createResponse["session_handle"].GetString();
|
||||||
|
|
||||||
// 3. Sélection de la source
|
// 3. Sélection de la source
|
||||||
uint sourceType = options.TargetWindowHandle.HasValue ? 2u : 1u;
|
ScreenCaptureSource effectiveSource = options.TargetWindowHandle.HasValue
|
||||||
|
? ScreenCaptureSource.Window
|
||||||
|
: options.Source;
|
||||||
|
uint sourceType = effectiveSource switch
|
||||||
|
{
|
||||||
|
ScreenCaptureSource.Screen => 1u,
|
||||||
|
ScreenCaptureSource.Window => 2u,
|
||||||
|
ScreenCaptureSource.Prompt => 3u,
|
||||||
|
_ => throw new ArgumentOutOfRangeException(nameof(options), options.Source, "Source de capture inconnue.")
|
||||||
|
};
|
||||||
uint cursorMode = options.CaptureCursor ? 2u : 1u;
|
uint cursorMode = options.CaptureCursor ? 2u : 1u;
|
||||||
|
|
||||||
string selectToken = $"monapp_req_{Guid.NewGuid():N}";
|
string selectToken = $"monapp_req_{Guid.NewGuid():N}";
|
||||||
|
|
@ -85,7 +95,12 @@ public class LinuxScreenCaptureService : IScreenCaptureService
|
||||||
|
|
||||||
await SendPortalRequestAsync(
|
await SendPortalRequestAsync(
|
||||||
expectedSelectPath,
|
expectedSelectPath,
|
||||||
() => CallSelectSourcesAsync(sessionHandle, selectToken, sourceType, cursorMode, LatestRestoreToken),
|
() => CallSelectSourcesAsync(
|
||||||
|
sessionHandle,
|
||||||
|
selectToken,
|
||||||
|
sourceType,
|
||||||
|
cursorMode,
|
||||||
|
effectiveSource == ScreenCaptureSource.Screen ? LatestRestoreToken : null),
|
||||||
cancellationToken
|
cancellationToken
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|
@ -99,11 +114,16 @@ public class LinuxScreenCaptureService : IScreenCaptureService
|
||||||
cancellationToken
|
cancellationToken
|
||||||
);
|
);
|
||||||
|
|
||||||
var streams = startResponse["streams"].GetArray<VariantValue>();
|
if (startResponse.TryGetValue("restore_token", out var tokenVariant))
|
||||||
if (streams.Length == 0)
|
{
|
||||||
|
LatestRestoreToken = tokenVariant.GetString();
|
||||||
|
}
|
||||||
|
|
||||||
|
var streams = startResponse["streams"];
|
||||||
|
if (streams.Count == 0)
|
||||||
throw new OperationCanceledException("Aucune source vidéo sélectionnée.");
|
throw new OperationCanceledException("Aucune source vidéo sélectionnée.");
|
||||||
|
|
||||||
uint pipewireNodeId = streams[0].GetUInt32();
|
uint pipewireNodeId = streams.GetItem(0).GetItem(0).GetUInt32();
|
||||||
|
|
||||||
// 5. Récupération du File Descriptor PipeWire
|
// 5. Récupération du File Descriptor PipeWire
|
||||||
|
|
||||||
|
|
@ -112,7 +132,7 @@ public class LinuxScreenCaptureService : IScreenCaptureService
|
||||||
|
|
||||||
MakeFdInheritable(rawFd); // Indispensable pour que gst-launch-1.0 voie le flux PipeWire
|
MakeFdInheritable(rawFd); // Indispensable pour que gst-launch-1.0 voie le flux PipeWire
|
||||||
|
|
||||||
StartGStreamerPipeline(rawFd, pipewireNodeId, options);
|
await StartGStreamerPipelineAsync(rawFd, pipewireNodeId, options);
|
||||||
|
|
||||||
IsRecording = true;
|
IsRecording = true;
|
||||||
StartDurationTimer();
|
StartDurationTimer();
|
||||||
|
|
@ -131,7 +151,7 @@ public class LinuxScreenCaptureService : IScreenCaptureService
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private void StartGStreamerPipeline(int fd, uint nodeId, CaptureOptions options)
|
private async Task StartGStreamerPipelineAsync(int fd, uint nodeId, CaptureOptions options)
|
||||||
{
|
{
|
||||||
// Pipeline GStreamer :
|
// Pipeline GStreamer :
|
||||||
// pipewiresrc lit directement les textures GPU (DMA-BUF)
|
// pipewiresrc lit directement les textures GPU (DMA-BUF)
|
||||||
|
|
@ -143,7 +163,16 @@ public class LinuxScreenCaptureService : IScreenCaptureService
|
||||||
|
|
||||||
string args = $"-e pipewiresrc fd={fd} path={nodeId} do-timestamp=true keepalive-time=1000 ! " +
|
string args = $"-e pipewiresrc fd={fd} path={nodeId} do-timestamp=true keepalive-time=1000 ! " +
|
||||||
$"videorate ! video/x-raw,framerate={options.Fps}/1 ! " +
|
$"videorate ! video/x-raw,framerate={options.Fps}/1 ! " +
|
||||||
$"{encoder} ! h264parse ! mp4mux ! filesink location=\"{options.OutputFilePath}\"";
|
$"{encoder} ! h264parse ! queue ! mp4mux name=mux ! " +
|
||||||
|
$"filesink location=\"{EscapeGStreamerString(options.OutputFilePath)}\"";
|
||||||
|
|
||||||
|
if (options.CaptureAudio)
|
||||||
|
{
|
||||||
|
string audioDevice = await GetDefaultAudioMonitorAsync();
|
||||||
|
args += $" pulsesrc device=\"{EscapeGStreamerString(audioDevice)}\" do-timestamp=true ! " +
|
||||||
|
"queue ! audioconvert ! audioresample ! avenc_aac bitrate=192000 ! " +
|
||||||
|
"aacparse ! queue ! mux.";
|
||||||
|
}
|
||||||
|
|
||||||
_gstProcess = new Process
|
_gstProcess = new Process
|
||||||
{
|
{
|
||||||
|
|
@ -158,7 +187,61 @@ public class LinuxScreenCaptureService : IScreenCaptureService
|
||||||
};
|
};
|
||||||
|
|
||||||
_gstProcess.Start();
|
_gstProcess.Start();
|
||||||
|
_gstErrorOutput = _gstProcess.StandardError.ReadToEndAsync();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static string EscapeGStreamerString(string value) =>
|
||||||
|
value.Replace("\\", "\\\\", StringComparison.Ordinal)
|
||||||
|
.Replace("\"", "\\\"", StringComparison.Ordinal);
|
||||||
|
|
||||||
|
private static async Task<string> GetDefaultAudioMonitorAsync()
|
||||||
|
{
|
||||||
|
Process process = new Process
|
||||||
|
{
|
||||||
|
StartInfo = new ProcessStartInfo
|
||||||
|
{
|
||||||
|
FileName = "pactl",
|
||||||
|
Arguments = "get-default-sink",
|
||||||
|
UseShellExecute = false,
|
||||||
|
RedirectStandardOutput = true,
|
||||||
|
RedirectStandardError = true,
|
||||||
|
CreateNoWindow = true
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
process.Start();
|
||||||
|
Task<string> outputTask = process.StandardOutput.ReadToEndAsync();
|
||||||
|
Task<string> errorTask = process.StandardError.ReadToEndAsync();
|
||||||
|
await process.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(3));
|
||||||
|
|
||||||
|
string output = (await outputTask).Trim();
|
||||||
|
if (process.ExitCode != 0 || string.IsNullOrWhiteSpace(output))
|
||||||
|
{
|
||||||
|
string error = (await errorTask).Trim();
|
||||||
|
throw new InvalidOperationException(
|
||||||
|
$"Impossible de déterminer la sortie audio par défaut.{FormatProcessError(error)}");
|
||||||
|
}
|
||||||
|
|
||||||
|
return output + ".monitor";
|
||||||
|
}
|
||||||
|
catch (TimeoutException)
|
||||||
|
{
|
||||||
|
if (!process.HasExited)
|
||||||
|
{
|
||||||
|
process.Kill(entireProcessTree: true);
|
||||||
|
await process.WaitForExitAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new InvalidOperationException("La détection de la sortie audio a expiré.");
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
process.Dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private static bool HasVaapiSupport()
|
private static bool HasVaapiSupport()
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
|
|
@ -200,11 +283,72 @@ public class LinuxScreenCaptureService : IScreenCaptureService
|
||||||
|
|
||||||
public async Task StopRecordingAsync()
|
public async Task StopRecordingAsync()
|
||||||
{
|
{
|
||||||
if (!IsRecording) return;
|
if (!IsRecording && _gstProcess is null) return;
|
||||||
|
|
||||||
IsRecording = false;
|
IsRecording = false;
|
||||||
|
_timerCts?.Cancel();
|
||||||
|
_timerCts?.Dispose();
|
||||||
|
_timerCts = null;
|
||||||
|
|
||||||
|
Process? process = _gstProcess;
|
||||||
|
if (process is null) return;
|
||||||
|
|
||||||
|
string errorOutput;
|
||||||
|
int exitCode;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (!process.HasExited && kill(process.Id, SIGINT) != 0)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException(
|
||||||
|
$"Impossible d'envoyer SIGINT à GStreamer (errno {Marshal.GetLastPInvokeError()}).");
|
||||||
|
}
|
||||||
|
|
||||||
|
await process.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(10));
|
||||||
|
errorOutput = _gstErrorOutput is null ? string.Empty : await _gstErrorOutput;
|
||||||
|
exitCode = process.ExitCode;
|
||||||
|
}
|
||||||
|
catch (TimeoutException)
|
||||||
|
{
|
||||||
|
if (!process.HasExited)
|
||||||
|
{
|
||||||
|
process.Kill(entireProcessTree: true);
|
||||||
|
await process.WaitForExitAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new InvalidOperationException(
|
||||||
|
"GStreamer n'a pas finalisé le fichier MP4 dans les dix secondes.");
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
if (!process.HasExited)
|
||||||
|
{
|
||||||
|
process.Kill(entireProcessTree: true);
|
||||||
|
await process.WaitForExitAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_pipewireFd?.Dispose();
|
||||||
|
_pipewireFd = null;
|
||||||
|
_dbusConnection?.Dispose();
|
||||||
|
_dbusConnection = null;
|
||||||
|
process.Dispose();
|
||||||
|
_gstProcess = null;
|
||||||
|
_gstErrorOutput = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (exitCode != 0)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException(
|
||||||
|
$"GStreamer s'est arrêté avec le code {exitCode}.{FormatProcessError(errorOutput)}");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static string FormatProcessError(string errorOutput) =>
|
||||||
|
string.IsNullOrWhiteSpace(errorOutput) ? string.Empty : $" Détail : {errorOutput.Trim()}";
|
||||||
|
|
||||||
private async Task<Dictionary<string, VariantValue>> SendPortalRequestAsync(
|
private async Task<Dictionary<string, VariantValue>> SendPortalRequestAsync(
|
||||||
string expectedRequestPath,
|
string expectedRequestPath,
|
||||||
Func<Task> dbusCall,
|
Func<Task> dbusCall,
|
||||||
|
|
@ -339,8 +483,23 @@ public class LinuxScreenCaptureService : IScreenCaptureService
|
||||||
public void Dispose()
|
public void Dispose()
|
||||||
{
|
{
|
||||||
_timerCts?.Cancel();
|
_timerCts?.Cancel();
|
||||||
_gstProcess?.Kill();
|
_timerCts?.Dispose();
|
||||||
_gstProcess?.Dispose();
|
|
||||||
|
if (_gstProcess is not null)
|
||||||
|
{
|
||||||
|
if (!_gstProcess.HasExited)
|
||||||
|
{
|
||||||
|
kill(_gstProcess.Id, SIGINT);
|
||||||
|
if (!_gstProcess.WaitForExit(10_000))
|
||||||
|
{
|
||||||
|
_gstProcess.Kill(entireProcessTree: true);
|
||||||
|
_gstProcess.WaitForExit();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_gstProcess.Dispose();
|
||||||
|
}
|
||||||
|
|
||||||
_pipewireFd?.Dispose();
|
_pipewireFd?.Dispose();
|
||||||
_dbusConnection?.Dispose();
|
_dbusConnection?.Dispose();
|
||||||
}
|
}
|
||||||
|
|
|
||||||
89
src/PostIt/PostIt.Tests/UserFilesApiClientTests.cs
Normal file
89
src/PostIt/PostIt.Tests/UserFilesApiClientTests.cs
Normal file
|
|
@ -0,0 +1,89 @@
|
||||||
|
using System.Net.Http;
|
||||||
|
using System.Text;
|
||||||
|
using Yavsc.Api.Client;
|
||||||
|
|
||||||
|
namespace PostIt.Tests;
|
||||||
|
|
||||||
|
public class UserFilesApiClientTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public async Task Upload_from_file_streams_video_to_screencast_directory()
|
||||||
|
{
|
||||||
|
string filePath = Path.Combine(Path.GetTempPath(), $"postit-{Guid.NewGuid():N}.mp4");
|
||||||
|
byte[] expected = [0x00, 0x00, 0x00, 0x20, 0x66, 0x74, 0x79, 0x70];
|
||||||
|
await File.WriteAllBytesAsync(filePath, expected, TestContext.Current.CancellationToken);
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var api = new UploadApi();
|
||||||
|
var client = new UserFilesApiClient(api, "https://blogs.example/api/v1/");
|
||||||
|
|
||||||
|
var received = await client.UploadAsync(
|
||||||
|
"screencast",
|
||||||
|
filePath,
|
||||||
|
"video/mp4",
|
||||||
|
TestContext.Current.CancellationToken);
|
||||||
|
|
||||||
|
Assert.Single(received);
|
||||||
|
Assert.Equal(HttpMethod.Post, api.Method);
|
||||||
|
Assert.Equal("fs/screencast", api.Path);
|
||||||
|
string multipart = Encoding.UTF8.GetString(api.MultipartBody);
|
||||||
|
Assert.Contains(Path.GetFileName(filePath), multipart);
|
||||||
|
Assert.Contains("video/mp4", multipart);
|
||||||
|
Assert.True(api.MultipartBody.AsSpan().IndexOf(expected) >= 0);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
File.Delete(filePath);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class UploadApi : IYavscApiClient
|
||||||
|
{
|
||||||
|
public HttpClient Http { get; } = new();
|
||||||
|
public HttpMethod? Method { get; private set; }
|
||||||
|
public string? Path { get; private set; }
|
||||||
|
public byte[] MultipartBody { get; private set; } = [];
|
||||||
|
|
||||||
|
public async Task<T> CallAsync<T>(
|
||||||
|
HttpMethod method,
|
||||||
|
string path,
|
||||||
|
Func<HttpContent> contentFactory,
|
||||||
|
CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
Method = method;
|
||||||
|
Path = path;
|
||||||
|
using HttpContent content = contentFactory();
|
||||||
|
MultipartBody = await content.ReadAsByteArrayAsync(ct);
|
||||||
|
return (T)(object)new List<FileReceivedDto>
|
||||||
|
{
|
||||||
|
new() { FileName = Path, ContentType = "video/mp4", Length = MultipartBody.Length }
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<T> CallAsync<T>(
|
||||||
|
HttpMethod method,
|
||||||
|
string path,
|
||||||
|
object? body = null,
|
||||||
|
CancellationToken ct = default) => throw new NotSupportedException();
|
||||||
|
|
||||||
|
public Task CallAsync(
|
||||||
|
HttpMethod method,
|
||||||
|
string path,
|
||||||
|
object? body = null,
|
||||||
|
CancellationToken ct = default) => throw new NotSupportedException();
|
||||||
|
|
||||||
|
public Task CallAsync(
|
||||||
|
HttpMethod method,
|
||||||
|
string path,
|
||||||
|
Func<HttpContent> contentFactory,
|
||||||
|
CancellationToken ct = default) => throw new NotSupportedException();
|
||||||
|
|
||||||
|
public Task<byte[]> DownloadAsync(
|
||||||
|
HttpMethod method,
|
||||||
|
string path,
|
||||||
|
CancellationToken ct = default) => throw new NotSupportedException();
|
||||||
|
|
||||||
|
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -2,11 +2,13 @@ using System;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using PostIt.Services;
|
using PostIt.Services;
|
||||||
using PostIt.ViewModels;
|
using PostIt.ViewModels;
|
||||||
|
using PostIt.ViewModels.Capture;
|
||||||
using PostIt.ViewModels.Chat;
|
using PostIt.ViewModels.Chat;
|
||||||
using PostIt.Views;
|
using PostIt.Views;
|
||||||
using PostIt.Views.Blogs;
|
using PostIt.Views.Blogs;
|
||||||
using PostIt.Views.Chat;
|
using PostIt.Views.Chat;
|
||||||
using PostIt.Views.Commands;
|
using PostIt.Views.Commands;
|
||||||
|
using PostIt.Views.Video;
|
||||||
using Yavsc.Api.Client;
|
using Yavsc.Api.Client;
|
||||||
|
|
||||||
namespace PostIt.Helpers;
|
namespace PostIt.Helpers;
|
||||||
|
|
@ -137,7 +139,8 @@ public static class ServiceCollectionHelpers
|
||||||
services.AddTransient<ContactsPageViewModel>();
|
services.AddTransient<ContactsPageViewModel>();
|
||||||
services.AddSingleton<ActivitiesPageViewModel>();
|
services.AddSingleton<ActivitiesPageViewModel>();
|
||||||
services.AddTransient<SelectableHairPrestationItem>();
|
services.AddTransient<SelectableHairPrestationItem>();
|
||||||
|
services.AddSingleton<ScreenCaptureViewModel>();
|
||||||
|
services.AddSingleton<ScreenCaptureView>();
|
||||||
// Dialogs (modal-light pages): the ViewLocator resolves
|
// Dialogs (modal-light pages): the ViewLocator resolves
|
||||||
// them when a caller pushes a PostAclDialogViewModel or
|
// them when a caller pushes a PostAclDialogViewModel or
|
||||||
// AddCircleMemberDialogViewModel via App.PushPageAsync.
|
// AddCircleMemberDialogViewModel via App.PushPageAsync.
|
||||||
|
|
|
||||||
|
|
@ -4,12 +4,21 @@ using System.Threading.Tasks;
|
||||||
|
|
||||||
namespace PostIt.Interfaces;
|
namespace PostIt.Interfaces;
|
||||||
|
|
||||||
|
public enum ScreenCaptureSource
|
||||||
|
{
|
||||||
|
Screen,
|
||||||
|
Window,
|
||||||
|
Prompt
|
||||||
|
}
|
||||||
|
|
||||||
public record CaptureOptions(
|
public record CaptureOptions(
|
||||||
string OutputFilePath,
|
string OutputFilePath,
|
||||||
int Fps = 60,
|
int Fps = 60,
|
||||||
IntPtr? TargetWindowHandle = null, // Null = Écran principal complet
|
IntPtr? TargetWindowHandle = null, // Null = Écran principal complet
|
||||||
bool CaptureCursor = true,
|
bool CaptureCursor = true,
|
||||||
string? RestoreToken = null // Token sauvegardé de la session précédente
|
string? RestoreToken = null, // Token sauvegardé de la session précédente
|
||||||
|
ScreenCaptureSource Source = ScreenCaptureSource.Screen,
|
||||||
|
bool CaptureAudio = true
|
||||||
);
|
);
|
||||||
|
|
||||||
public interface IScreenCaptureService : IDisposable
|
public interface IScreenCaptureService : IDisposable
|
||||||
|
|
|
||||||
|
|
@ -10,6 +10,8 @@ using PostIt.Views;
|
||||||
using PostIt.Views.Blogs;
|
using PostIt.Views.Blogs;
|
||||||
using PostIt.Views.Chat;
|
using PostIt.Views.Chat;
|
||||||
using PostIt.Views.Commands;
|
using PostIt.Views.Commands;
|
||||||
|
using PostIt.ViewModels.Capture;
|
||||||
|
using PostIt.Views.Video;
|
||||||
|
|
||||||
namespace PostIt;
|
namespace PostIt;
|
||||||
|
|
||||||
|
|
@ -41,6 +43,7 @@ public class ViewLocator : IDataTemplate
|
||||||
var services = app!.ServiceProvider!;
|
var services = app!.ServiceProvider!;
|
||||||
return data switch
|
return data switch
|
||||||
{
|
{
|
||||||
|
ScreenCaptureViewModel => services.GetRequiredService<ScreenCaptureView>(),
|
||||||
BlogsViewModel => services.GetRequiredService<BlogsPage>(),
|
BlogsViewModel => services.GetRequiredService<BlogsPage>(),
|
||||||
VideoPageViewModel => services.GetRequiredService<VideoPage>(),
|
VideoPageViewModel => services.GetRequiredService<VideoPage>(),
|
||||||
ReplayEditorPageViewModel => services.GetRequiredService<ReplayEditorPage>(),
|
ReplayEditorPageViewModel => services.GetRequiredService<ReplayEditorPage>(),
|
||||||
|
|
|
||||||
|
|
@ -606,6 +606,9 @@ public partial class BlogsViewModel : ViewModelBase, IActionStatusViewModel
|
||||||
Services = services;
|
Services = services;
|
||||||
_resources = resources ?? new BlogResourceService();
|
_resources = resources ?? new BlogResourceService();
|
||||||
Init(settings);
|
Init(settings);
|
||||||
|
ScreenCaptureViewModel = Platform.IsScreenCaptureSupported && services is not null
|
||||||
|
? services.GetService<ScreenCaptureViewModel>()
|
||||||
|
: null;
|
||||||
}
|
}
|
||||||
|
|
||||||
partial void OnSearchTextChanged(string value)
|
partial void OnSearchTextChanged(string value)
|
||||||
|
|
|
||||||
|
|
@ -1,36 +1,121 @@
|
||||||
using System;
|
using System;
|
||||||
using System.IO;
|
using System.IO;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
using CommunityToolkit.Mvvm.ComponentModel;
|
||||||
|
using CommunityToolkit.Mvvm.Input;
|
||||||
using PostIt.Interfaces;
|
using PostIt.Interfaces;
|
||||||
|
using PostIt.Models;
|
||||||
using PostIt.Services;
|
using PostIt.Services;
|
||||||
|
using Yavsc.Api.Client;
|
||||||
|
|
||||||
namespace PostIt.ViewModels.Capture;
|
namespace PostIt.ViewModels.Capture;
|
||||||
|
|
||||||
public class ScreenCaptureViewModel : ViewModelBase
|
public record CaptureSourceOption(ScreenCaptureSource Source, string Label);
|
||||||
|
|
||||||
|
public partial class ScreenCaptureViewModel : ViewModelBase, IActionStatusViewModel
|
||||||
{
|
{
|
||||||
IScreenCaptureService _captureService;
|
IScreenCaptureService _captureService;
|
||||||
|
private readonly UserFilesApiClient? _userFiles;
|
||||||
|
private string? _outputFilePath;
|
||||||
|
|
||||||
public ScreenCaptureViewModel()
|
public CaptureSourceOption[] CaptureSources { get; } =
|
||||||
|
[
|
||||||
|
new(ScreenCaptureSource.Screen, "Écran entier"),
|
||||||
|
new(ScreenCaptureSource.Window, "Fenêtre"),
|
||||||
|
new(ScreenCaptureSource.Prompt, "Choisir au lancement")
|
||||||
|
];
|
||||||
|
|
||||||
|
private CaptureSourceOption _selectedCaptureSource = null!;
|
||||||
|
public CaptureSourceOption SelectedCaptureSource
|
||||||
|
{
|
||||||
|
get => _selectedCaptureSource;
|
||||||
|
set => SetProperty(ref _selectedCaptureSource, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool _captureAudio = true;
|
||||||
|
public bool CaptureAudio
|
||||||
|
{
|
||||||
|
get => _captureAudio;
|
||||||
|
set => SetProperty(ref _captureAudio, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool _isBusy;
|
||||||
|
public bool IsBusy
|
||||||
|
{
|
||||||
|
get => _isBusy;
|
||||||
|
set
|
||||||
|
{
|
||||||
|
if (SetProperty(ref _isBusy, value))
|
||||||
|
OnPropertyChanged(nameof(CanConfigure));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool CanConfigure => !IsRecording && !IsBusy;
|
||||||
|
|
||||||
|
private string _statusMessage = "Prêt.";
|
||||||
|
public string StatusMessage
|
||||||
|
{
|
||||||
|
get => _statusMessage;
|
||||||
|
set => SetProperty(ref _statusMessage, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
private StatusNotice _actionStatus = StatusNotice.Info("Prêt.");
|
||||||
|
public StatusNotice ActionStatus
|
||||||
|
{
|
||||||
|
get => _actionStatus;
|
||||||
|
set => SetProperty(ref _actionStatus, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
public ScreenCaptureViewModel(UserFilesApiClient userFiles)
|
||||||
{
|
{
|
||||||
if (Platform.IsScreenCaptureSupported)
|
if (Platform.IsScreenCaptureSupported)
|
||||||
_captureService = Platform.CreateScreenCaptureService!();
|
_captureService = Platform.CreateScreenCaptureService!();
|
||||||
else
|
else
|
||||||
throw new NotSupportedException("Screen capture is not supported on this platform.");
|
throw new NotSupportedException("Screen capture is not supported on this platform.");
|
||||||
|
|
||||||
|
_userFiles = userFiles;
|
||||||
|
SelectedCaptureSource = CaptureSources[0];
|
||||||
}
|
}
|
||||||
string screencastNName = "screencast";
|
|
||||||
|
public ScreenCaptureViewModel() : this(null!) { }
|
||||||
|
|
||||||
|
[ObservableProperty]
|
||||||
|
public partial string ScreencastNName { get; set; } = "screencast";
|
||||||
|
|
||||||
private string GetTokenFilePath() => Path.Combine(
|
private string GetTokenFilePath() => Path.Combine(
|
||||||
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
|
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
|
||||||
App.AppName,
|
App.AppName,
|
||||||
screencastNName+"_token.txt"
|
$"{SanitizeFileName(ScreencastNName)}_{SelectedCaptureSource.Source.ToString().ToLowerInvariant()}_token.txt"
|
||||||
);
|
);
|
||||||
|
|
||||||
public bool IsRecording => _captureService?.IsRecording ?? false;
|
|
||||||
|
public bool IsRecording { get => _captureService?.IsRecording ?? false; }
|
||||||
|
|
||||||
|
[RelayCommand]
|
||||||
public async Task ToggleRecordingAsync()
|
public async Task ToggleRecordingAsync()
|
||||||
{
|
{
|
||||||
if (_captureService.IsRecording)
|
if (_captureService.IsRecording)
|
||||||
{
|
{
|
||||||
await _captureService.StopRecordingAsync();
|
IsBusy = true;
|
||||||
|
bool finalized = false;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await _captureService.StopRecordingAsync();
|
||||||
|
finalized = true;
|
||||||
|
this.OnPropertyChanged(nameof(IsRecording));
|
||||||
|
this.OnPropertyChanged(nameof(CanConfigure));
|
||||||
|
await UploadRecordingAsync();
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
this.SetErrorStatus(finalized
|
||||||
|
? $"La capture est finalisée localement, mais son envoi a échoué : {ex.Message}"
|
||||||
|
: $"La finalisation de la capture a échoué : {ex.Message}");
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
IsBusy = false;
|
||||||
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -40,11 +125,18 @@ public class ScreenCaptureViewModel : ViewModelBase
|
||||||
? await File.ReadAllTextAsync(tokenFilePath)
|
? await File.ReadAllTextAsync(tokenFilePath)
|
||||||
: null;
|
: null;
|
||||||
|
|
||||||
|
string fileName = EnsureMp4Extension(SanitizeFileName(ScreencastNName));
|
||||||
|
_outputFilePath = Path.Combine(Path.GetTempPath(), fileName);
|
||||||
|
if (File.Exists(_outputFilePath))
|
||||||
|
File.Delete(_outputFilePath);
|
||||||
|
|
||||||
var options = new CaptureOptions(
|
var options = new CaptureOptions(
|
||||||
OutputFilePath: Path.Combine(Path.GetTempPath(), screencastNName + ".mp4"),
|
OutputFilePath: _outputFilePath,
|
||||||
Fps: 60,
|
Fps: 60,
|
||||||
CaptureCursor: true,
|
CaptureCursor: true,
|
||||||
RestoreToken: savedToken
|
RestoreToken: savedToken,
|
||||||
|
Source: SelectedCaptureSource.Source,
|
||||||
|
CaptureAudio: CaptureAudio
|
||||||
);
|
);
|
||||||
|
|
||||||
// 2. Lancer la capture (silencieuse si le token est valide)
|
// 2. Lancer la capture (silencieuse si le token est valide)
|
||||||
|
|
@ -56,13 +148,46 @@ public class ScreenCaptureViewModel : ViewModelBase
|
||||||
Directory.CreateDirectory(Path.GetDirectoryName(tokenFilePath)!);
|
Directory.CreateDirectory(Path.GetDirectoryName(tokenFilePath)!);
|
||||||
await File.WriteAllTextAsync(tokenFilePath, _captureService.LatestRestoreToken);
|
await File.WriteAllTextAsync(tokenFilePath, _captureService.LatestRestoreToken);
|
||||||
}
|
}
|
||||||
|
this.OnPropertyChanged(nameof(IsRecording));
|
||||||
|
this.OnPropertyChanged(nameof(CanConfigure));
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task UploadRecordingAsync()
|
||||||
|
{
|
||||||
|
if (_userFiles is null)
|
||||||
|
throw new InvalidOperationException("Le client de fichiers utilisateur est indisponible.");
|
||||||
|
if (string.IsNullOrWhiteSpace(_outputFilePath) || !File.Exists(_outputFilePath))
|
||||||
|
throw new FileNotFoundException("Le fichier vidéo finalisé est introuvable.", _outputFilePath);
|
||||||
|
if (new FileInfo(_outputFilePath).Length == 0)
|
||||||
|
throw new InvalidOperationException("Le fichier vidéo finalisé est vide.");
|
||||||
|
|
||||||
|
this.SetInfoStatus("Envoi de la capture dans Mes fichiers / screencast...");
|
||||||
|
var received = await _userFiles.UploadAsync("screencast", _outputFilePath, "video/mp4");
|
||||||
|
if (received.Count != 1 || received[0].QuotaOffense)
|
||||||
|
throw new InvalidOperationException("Le quota de stockage a refusé la capture.");
|
||||||
|
|
||||||
|
File.Delete(_outputFilePath);
|
||||||
|
_outputFilePath = null;
|
||||||
|
this.SetInfoStatus("Capture envoyée dans Mes fichiers / screencast.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string EnsureMp4Extension(string name) =>
|
||||||
|
name.EndsWith(".mp4", StringComparison.OrdinalIgnoreCase) ? name : name + ".mp4";
|
||||||
|
|
||||||
|
private static string SanitizeFileName(string value)
|
||||||
|
{
|
||||||
|
string name = string.IsNullOrWhiteSpace(value) ? "screencast" : value.Trim();
|
||||||
|
foreach (char invalid in Path.GetInvalidFileNameChars())
|
||||||
|
name = name.Replace(invalid, '_');
|
||||||
|
name = name.Replace('/', '_').Replace('\\', '_').Trim('.');
|
||||||
|
return string.IsNullOrWhiteSpace(name) ? "screencast" : name;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void StopRecordingAsync()
|
public void StopRecordingAsync()
|
||||||
{
|
{
|
||||||
if (_captureService.IsRecording)
|
if (_captureService.IsRecording)
|
||||||
{
|
{
|
||||||
_captureService.StopRecordingAsync().GetAwaiter().GetResult();
|
ToggleRecordingAsync().GetAwaiter().GetResult();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -13,6 +13,7 @@ using PostIt.ViewModels.Chat;
|
||||||
using Yavsc.Abstract.Workflow;
|
using Yavsc.Abstract.Workflow;
|
||||||
using Yavsc.Abstract.Models.Messaging;
|
using Yavsc.Abstract.Models.Messaging;
|
||||||
using Yavsc.Api.Client;
|
using Yavsc.Api.Client;
|
||||||
|
using PostIt.ViewModels.Capture;
|
||||||
|
|
||||||
|
|
||||||
namespace PostIt.ViewModels;
|
namespace PostIt.ViewModels;
|
||||||
|
|
@ -86,6 +87,13 @@ public class HomePageViewModel : ViewModelBase
|
||||||
?? throw new InvalidOperationException("Page podcasts indisponible.");
|
?? throw new InvalidOperationException("Page podcasts indisponible.");
|
||||||
await app.PushPageAsync(vm);
|
await app.PushPageAsync(vm);
|
||||||
});
|
});
|
||||||
|
OpenScreenCapture = new AsyncRelayCommand(async () =>
|
||||||
|
{
|
||||||
|
var app = Application.Current as App ?? throw new InvalidOperationException("Application indisponible.");
|
||||||
|
var vm = app.ServiceProvider?.GetRequiredService<ScreenCaptureViewModel>()
|
||||||
|
?? throw new InvalidOperationException("Page capture d'écran indisponible.");
|
||||||
|
await app.PushPageAsync(vm);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -106,6 +114,8 @@ public class HomePageViewModel : ViewModelBase
|
||||||
public IAsyncRelayCommand RefreshNotificationsCommand { get; }
|
public IAsyncRelayCommand RefreshNotificationsCommand { get; }
|
||||||
public IAsyncRelayCommand<Notification?> DismissNotificationCommand { get; }
|
public IAsyncRelayCommand<Notification?> DismissNotificationCommand { get; }
|
||||||
|
|
||||||
|
public IAsyncRelayCommand OpenScreenCapture { get; }
|
||||||
|
|
||||||
public async Task DismissNotificationAsync(Notification? notification)
|
public async Task DismissNotificationAsync(Notification? notification)
|
||||||
{
|
{
|
||||||
if (notification is null)
|
if (notification is null)
|
||||||
|
|
|
||||||
|
|
@ -84,6 +84,11 @@
|
||||||
Command="{Binding OpenSubscriptions}"
|
Command="{Binding OpenSubscriptions}"
|
||||||
IsEnabled="{Binding SessionStatus.IsLoggedIn}"
|
IsEnabled="{Binding SessionStatus.IsLoggedIn}"
|
||||||
Label="Mon abonnement PayPal" />
|
Label="Mon abonnement PayPal" />
|
||||||
|
<CommandBarButton
|
||||||
|
HorizontalAlignment="Center"
|
||||||
|
Command="{Binding OpenScreenCapture}"
|
||||||
|
IsEnabled="{Binding SessionStatus.IsLoggedIn}"
|
||||||
|
Label="Capture d'écran" />
|
||||||
<CommandBarButton
|
<CommandBarButton
|
||||||
HorizontalAlignment="Center"
|
HorizontalAlignment="Center"
|
||||||
Command="{Binding OpenAdministration}"
|
Command="{Binding OpenAdministration}"
|
||||||
|
|
|
||||||
|
|
@ -5,6 +5,9 @@
|
||||||
xmlns:vm="using:PostIt.ViewModels"
|
xmlns:vm="using:PostIt.ViewModels"
|
||||||
xmlns:abs="using:Yavsc.Abstract.Streaming"
|
xmlns:abs="using:Yavsc.Abstract.Streaming"
|
||||||
x:DataType="vm:ReplayEditorPageViewModel">
|
x:DataType="vm:ReplayEditorPageViewModel">
|
||||||
|
<Design.DataContext>
|
||||||
|
<vm:ReplayEditorPageViewModel />
|
||||||
|
</Design.DataContext>
|
||||||
<Grid x:Name="EditorGrid" ColumnDefinitions="2*,*" RowDefinitions="Auto,*,Auto,Auto" Margin="16" ColumnSpacing="16" RowSpacing="8">
|
<Grid x:Name="EditorGrid" ColumnDefinitions="2*,*" RowDefinitions="Auto,*,Auto,Auto" Margin="16" ColumnSpacing="16" RowSpacing="8">
|
||||||
<TextBlock x:Name="EditorTitle" Grid.ColumnSpan="2" Text="{Binding Title}" FontSize="22" TextWrapping="Wrap" />
|
<TextBlock x:Name="EditorTitle" Grid.ColumnSpan="2" Text="{Binding Title}" FontSize="22" TextWrapping="Wrap" />
|
||||||
<Border x:Name="VideoBorder" Grid.Row="1" Background="Black" BorderThickness="1" BorderBrush="Green" MinHeight="240">
|
<Border x:Name="VideoBorder" Grid.Row="1" Background="Black" BorderThickness="1" BorderBrush="Green" MinHeight="240">
|
||||||
|
|
|
||||||
37
src/PostIt/PostIt/Views/Video/ScreenCaptureView.axaml
Normal file
37
src/PostIt/PostIt/Views/Video/ScreenCaptureView.axaml
Normal file
|
|
@ -0,0 +1,37 @@
|
||||||
|
<ContentPage xmlns="https://github.com/avaloniaui"
|
||||||
|
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||||
|
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||||
|
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||||
|
xmlns:vm="using:PostIt.ViewModels.Capture"
|
||||||
|
mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
|
||||||
|
x:Class="PostIt.Views.Video.ScreenCaptureView"
|
||||||
|
x:DataType="vm:ScreenCaptureViewModel"
|
||||||
|
>
|
||||||
|
<Design.DataContext>
|
||||||
|
<vm:ScreenCaptureViewModel />
|
||||||
|
</Design.DataContext>
|
||||||
|
<StackPanel Spacing="8" Margin="12">
|
||||||
|
<TextBlock Text="Capture d'écran" FontWeight="SemiBold" />
|
||||||
|
<TextBlock Text="Enregistrement en cours" IsVisible="{Binding IsRecording}" />
|
||||||
|
<TextBlock Text="{Binding StatusMessage}" TextWrapping="Wrap" />
|
||||||
|
<TextBox Text="{Binding ScreencastNName}"
|
||||||
|
PlaceholderText="Nom de la capture"
|
||||||
|
IsEnabled="{Binding CanConfigure}" />
|
||||||
|
<ComboBox ItemsSource="{Binding CaptureSources}"
|
||||||
|
SelectedItem="{Binding SelectedCaptureSource}"
|
||||||
|
IsEnabled="{Binding CanConfigure}">
|
||||||
|
<ComboBox.ItemTemplate>
|
||||||
|
<DataTemplate x:DataType="vm:CaptureSourceOption">
|
||||||
|
<TextBlock Text="{Binding Label}" />
|
||||||
|
</DataTemplate>
|
||||||
|
</ComboBox.ItemTemplate>
|
||||||
|
</ComboBox>
|
||||||
|
<CheckBox Content="Inclure l'audio du système"
|
||||||
|
IsChecked="{Binding CaptureAudio}"
|
||||||
|
IsEnabled="{Binding CanConfigure}" />
|
||||||
|
<Button Content="Démarrer / arrêter la capture"
|
||||||
|
Command="{Binding ToggleRecordingAsync}"
|
||||||
|
IsEnabled="{Binding !IsBusy}" />
|
||||||
|
</StackPanel>
|
||||||
|
|
||||||
|
</ContentPage>
|
||||||
12
src/PostIt/PostIt/Views/Video/ScreenCaptureView.cs
Normal file
12
src/PostIt/PostIt/Views/Video/ScreenCaptureView.cs
Normal file
|
|
@ -0,0 +1,12 @@
|
||||||
|
using Avalonia.Controls;
|
||||||
|
|
||||||
|
namespace PostIt.Views.Video;
|
||||||
|
|
||||||
|
|
||||||
|
public partial class ScreenCaptureView : ContentPage
|
||||||
|
{
|
||||||
|
public ScreenCaptureView()
|
||||||
|
{
|
||||||
|
InitializeComponent();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
|
using System.IO;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Net.Http;
|
using System.Net.Http;
|
||||||
using System.Net.Http.Headers;
|
using System.Net.Http.Headers;
|
||||||
|
|
@ -67,6 +68,34 @@ public sealed class UserFilesApiClient
|
||||||
return _api.CallAsync<List<FileReceivedDto>>(HttpMethod.Post, path, () => CreateMultipartContent(files), ct);
|
return _api.CallAsync<List<FileReceivedDto>>(HttpMethod.Post, path, () => CreateMultipartContent(files), ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Téléverse un fichier depuis le disque sans le charger intégralement
|
||||||
|
/// en mémoire. La fabrique rouvre le flux si une nouvelle tentative
|
||||||
|
/// d'authentification est nécessaire après une réponse 401.
|
||||||
|
/// </summary>
|
||||||
|
public Task<List<FileReceivedDto>> UploadAsync(
|
||||||
|
string subdir,
|
||||||
|
string filePath,
|
||||||
|
string? contentType = null,
|
||||||
|
CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(filePath))
|
||||||
|
throw new ArgumentException("File path is required.", nameof(filePath));
|
||||||
|
if (!File.Exists(filePath))
|
||||||
|
throw new FileNotFoundException("The upload file does not exist.", filePath);
|
||||||
|
|
||||||
|
var path = string.IsNullOrWhiteSpace(subdir)
|
||||||
|
? PathPrefix
|
||||||
|
: $"{PathPrefix}/{subdir.TrimStart('/')}";
|
||||||
|
var fileName = Path.GetFileName(filePath);
|
||||||
|
|
||||||
|
return _api.CallAsync<List<FileReceivedDto>>(
|
||||||
|
HttpMethod.Post,
|
||||||
|
path,
|
||||||
|
() => CreateMultipartContent(fileName, () => File.OpenRead(filePath), contentType),
|
||||||
|
ct);
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Supprime un fichier ou répertoire de l'espace perso
|
/// Supprime un fichier ou répertoire de l'espace perso
|
||||||
/// (<c>DELETE fs/{path}</c>).
|
/// (<c>DELETE fs/{path}</c>).
|
||||||
|
|
@ -109,4 +138,17 @@ public sealed class UserFilesApiClient
|
||||||
}
|
}
|
||||||
return content;
|
return content;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
private static HttpContent CreateMultipartContent(
|
||||||
|
string fileName,
|
||||||
|
Func<Stream> streamFactory,
|
||||||
|
string? contentType)
|
||||||
|
{
|
||||||
|
var content = new MultipartFormDataContent();
|
||||||
|
var fileContent = new StreamContent(streamFactory());
|
||||||
|
fileContent.Headers.ContentType = new MediaTypeHeaderValue(
|
||||||
|
string.IsNullOrWhiteSpace(contentType) ? "application/octet-stream" : contentType);
|
||||||
|
content.Add(fileContent, "file", fileName);
|
||||||
|
return content;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue