2026-08-06 10:42:20 +02:00
using System.IO.Compression ;
using AIStudio.Settings ;
using AIStudio.Tools.PluginSystem ;
using AIStudio.Tools.Rust ;
namespace AIStudio.Tools.Services ;
public sealed class PluginShareService ( NativeShareService nativeShareService , RustService rustService , SettingsManager settingsManager , ILogger < PluginShareService > logger )
{
2026-10-19 14:39:12 +02:00
private static PluginShareResult ShareError ( IAvailablePlugin plugin , string issue ) => new ( PluginShareOutcome . FAILED , plugin . Name , string . Empty , issue );
private static PluginShareResult ShareSheetUnavailable ( IAvailablePlugin plugin , string issue ) => new ( PluginShareOutcome . SHARE_SHEET_UNAVAILABLE , plugin . Name , string . Empty , issue );
2026-08-06 10:42:20 +02:00
private static string TB ( string fallbackEN ) => I18N . I . T ( fallbackEN , typeof ( PluginShareService ). Namespace , nameof ( PluginShareService ));
2026-11-13 10:16:56 +01:00
private static string TA ( string fallbackEN ) => I18N . I . TA ( fallbackEN , typeof ( PluginShareService ). Namespace , nameof ( PluginShareService ));
2026-08-06 10:42:20 +02:00
private const string PLUGIN_FILE_NAME = "plugin.lua" ;
private const int FILE_NAME_PREFIX_MAX_LEN = 80 ;
2026-10-19 14:39:12 +02:00
/// <summary>
/// Whether sharing a plugin exports its archive to a location of the user's choice instead of
/// handing it to the share sheet of the operating system.
/// </summary>
public bool UsesExport => ! nativeShareService . IsAvailable ;
2026-08-06 10:42:20 +02:00
/// <summary>
/// Creates a shareable plugin archive from a local plugin and hands it over to the user.
/// The archive contains the plugin root contents, so <c>plugin.lua</c> is located at the archive root.
/// </summary>
/// <remarks>
2026-11-29 18:45:34 +01:00
/// On Windows and macOS, the archive is created in the temporary folder of AI Studio and handed over
/// to the native share sheet. Linux has no such share sheet, since the XDG desktop portals do not provide
2026-10-19 14:39:12 +02:00
/// a share interface. Thus, the archive is exported to a location of the user's choice there. The
/// same happens on Windows and macOS once the share sheet failed or did not respond, until AI
/// Studio restarts.
2026-08-06 10:42:20 +02:00
/// </remarks>
/// <param name="plugin">The local plugin to archive and share.</param>
2026-10-25 22:10:38 +01:00
/// <param name="exportFeedback">Shows that the archive is being written, once the user chose where.
/// The caller ends it with the success, which only the caller announces.</param>
2026-08-06 10:42:20 +02:00
/// <param name="token">Cancellation token for archive creation.</param>
2026-10-19 14:39:12 +02:00
/// <returns>The share result, including the archive path when successful. When the share sheet
/// failed or did not respond, the outcome is SHARE_SHEET_UNAVAILABLE, and ExportAsync can still
/// export the plugin.</returns>
2026-10-25 22:10:38 +01:00
public async Task < PluginShareResult > ShareAsync ( IAvailablePlugin plugin , FileExportFeedback exportFeedback , CancellationToken token )
2026-08-06 10:42:20 +02:00
{
2026-10-19 14:39:12 +02:00
if (! this . TryGetShareablePluginRoot ( plugin , out var pluginRoot , out var issue ))
return ShareError ( plugin , issue );
2026-08-06 10:42:20 +02:00
2026-10-19 14:39:12 +02:00
if ( this . UsesExport )
2026-10-25 22:10:38 +01:00
return await this . ExportArchiveAsync ( plugin , pluginRoot , exportFeedback , token );
2026-08-06 10:42:20 +02:00
2026-10-19 14:39:12 +02:00
return await this . ShareViaNativeSheetAsync ( plugin , pluginRoot , token );
}
2026-08-06 10:42:20 +02:00
2026-10-19 14:39:12 +02:00
/// <summary>
/// Exports a plugin archive to a location of the user's choice, even where a share sheet would
/// be available. This is the way out after the share sheet failed or did not respond.
/// </summary>
/// <param name="plugin">The local plugin to archive and export.</param>
2026-10-25 22:10:38 +01:00
/// <param name="exportFeedback">Shows that the archive is being written, once the user chose where.
/// The caller ends it with the success, which only the caller announces.</param>
2026-10-19 14:39:12 +02:00
/// <param name="token">Cancellation token for archive creation.</param>
/// <returns>The export result, including the chosen archive path when successful.</returns>
2026-10-25 22:10:38 +01:00
public async Task < PluginShareResult > ExportAsync ( IAvailablePlugin plugin , FileExportFeedback exportFeedback , CancellationToken token )
2026-10-19 14:39:12 +02:00
{
if (! this . TryGetShareablePluginRoot ( plugin , out var pluginRoot , out var issue ))
2026-08-06 10:42:20 +02:00
return ShareError ( plugin , issue );
2026-10-25 22:10:38 +01:00
return await this . ExportArchiveAsync ( plugin , pluginRoot , exportFeedback , token );
2026-10-19 14:39:12 +02:00
}
2026-08-06 10:42:20 +02:00
2026-10-19 14:39:12 +02:00
/// <summary>
/// Checks whether a plugin may leave AI Studio as an archive at all, no matter whether it is
/// shared or exported.
/// </summary>
/// <param name="plugin">The local plugin to check.</param>
/// <param name="pluginRoot">The validated plugin root directory, when the plugin may leave.</param>
/// <param name="issue">Why the plugin may not leave; empty otherwise.</param>
/// <returns>True when the plugin may be shared or exported.</returns>
private bool TryGetShareablePluginRoot ( IAvailablePlugin plugin , out string pluginRoot , out string issue )
{
pluginRoot = string . Empty ;
if ( plugin . IsInternal )
{
issue = TB ( "Internal plugins cannot be shared." );
return false ;
}
if ( plugin . IsManagedByConfigServer )
{
issue = TB ( "Config Server managed plugins cannot be shared." );
return false ;
}
if (! settingsManager . ConfigurationData . App . AllowUserToSharePlugins )
{
2026-11-13 10:16:56 +01:00
issue = TA ( "Your organization has disabled sharing plugins." );
2026-10-19 14:39:12 +02:00
return false ;
}
return TryGetPluginRoot ( plugin , out pluginRoot , out issue );
2026-08-06 10:42:20 +02:00
}
/// <summary>
/// Asks the user for a target location and writes the plugin archive to it.
/// </summary>
/// <param name="plugin">The local plugin to archive.</param>
/// <param name="pluginRoot">The validated plugin root directory.</param>
2026-10-25 22:10:38 +01:00
/// <param name="exportFeedback">Shows that the archive is being written.</param>
2026-08-06 10:42:20 +02:00
/// <param name="token">Cancellation token for archive creation.</param>
/// <returns>The share result, including the chosen archive path when successful.</returns>
2026-10-25 22:10:38 +01:00
private async Task < PluginShareResult > ExportArchiveAsync ( IAvailablePlugin plugin , string pluginRoot , FileExportFeedback exportFeedback , CancellationToken token )
2026-08-06 10:42:20 +02:00
{
var suggestedFileName = $"{CreateSafeFileNamePrefix(plugin.Name)}{PluginArchive.PLUGIN_FILE_EXTENSION}" ;
var saveResponse = await rustService . SaveFile ( TB ( "Export plugin archive" ), [ FileTypes . PLUGIN_ARCHIVE ], suggestedFileName );
if ( saveResponse . UserCancelled )
2026-10-19 14:39:12 +02:00
return new ( PluginShareOutcome . CANCELLED , plugin . Name , string . Empty , string . Empty );
2026-08-06 10:42:20 +02:00
var archivePath = saveResponse . SaveFilePath ;
2026-10-25 22:10:38 +01:00
exportFeedback . ShowRunning ( archivePath );
2026-08-06 10:42:20 +02:00
try
{
token . ThrowIfCancellationRequested ();
2026-08-15 19:55:42 +02:00
await Task . Run ( async () =>
2026-08-06 10:42:20 +02:00
{
token . ThrowIfCancellationRequested ();
2026-08-15 19:55:42 +02:00
//
// The save dialog already asked the user about overwriting an existing file, so we
// write into the file the user picked instead of removing and recreating it. That
// matters on Linux: inside a Flatpak, the file dialog hands out one single file
// through the desktop portal. We may write that file, but we may not create a new
// one next to it, which is what deleting and recreating would come down to.
//
await using var archiveStream = File . Create ( archivePath );
2026-11-04 14:04:10 +01:00
await ZipFile . CreateFromDirectoryAsync ( pluginRoot , archiveStream , CompressionLevel . Optimal , false , token );
2026-08-06 10:42:20 +02:00
}, token );
logger . LogInformation ( "Exported plugin '{PluginName}' ({PluginId}) to the archive '{ArchivePath}'." , plugin . Name , plugin . Id , archivePath );
2026-10-19 14:39:12 +02:00
return new ( PluginShareOutcome . EXPORTED , plugin . Name , archivePath , string . Empty );
2026-08-06 10:42:20 +02:00
}
catch ( OperationCanceledException )
{
this . TryDeleteArchive ( archivePath );
throw ;
}
catch ( Exception exception )
{
this . TryDeleteArchive ( archivePath );
logger . LogError ( exception , "Failed to export plugin '{PluginName}' ({PluginId})." , plugin . Name , plugin . Id );
return ShareError ( plugin , string . Format ( TB ( "Unexpected error: {0}" ), exception . Message ));
}
}
/// <summary>
2026-11-29 18:45:34 +01:00
/// Creates the plugin archive in the temporary folder of AI Studio and opens the native share sheet for it.
2026-08-06 10:42:20 +02:00
/// </summary>
2026-11-29 18:45:34 +01:00
/// <remarks>
/// The runtime hands only archives from the temporary folder of AI Studio to the share sheet, see
/// TemporaryFiles. The archive gets a folder of its own there, so it can carry the name of the plugin,
/// which the recipient sees, just like an exported archive.
/// </remarks>
2026-08-06 10:42:20 +02:00
/// <param name="plugin">The local plugin to archive and share.</param>
/// <param name="pluginRoot">The validated plugin root directory.</param>
/// <param name="token">Cancellation token for archive creation.</param>
/// <returns>The share result, including the retained temporary archive path when successful.</returns>
private async Task < PluginShareResult > ShareViaNativeSheetAsync ( IAvailablePlugin plugin , string pluginRoot , CancellationToken token )
{
2026-11-29 18:45:34 +01:00
string? archiveDirectory = null ;
2026-08-06 10:42:20 +02:00
try
{
token . ThrowIfCancellationRequested ();
2026-11-29 18:45:34 +01:00
archiveDirectory = TemporaryFiles . CreateDirectory ();
var archivePath = Path . Join ( archiveDirectory , $"{CreateSafeFileNamePrefix(plugin.Name)}{PluginArchive.PLUGIN_FILE_EXTENSION}" );
2026-08-06 10:42:20 +02:00
2026-11-04 14:04:10 +01:00
await Task . Run ( async () =>
2026-08-06 10:42:20 +02:00
{
token . ThrowIfCancellationRequested ();
2026-11-04 14:04:10 +01:00
await ZipFile . CreateFromDirectoryAsync ( pluginRoot , archivePath , CompressionLevel . Optimal , false , token );
2026-08-06 10:42:20 +02:00
}, token );
token . ThrowIfCancellationRequested ();
2026-10-19 14:39:12 +02:00
var shareResponse = await nativeShareService . Share ( archivePath );
switch ( shareResponse . Outcome )
2026-08-06 10:42:20 +02:00
{
2026-10-19 14:39:12 +02:00
case ShareSheetOutcome . OPENED :
break ;
//
// A share sheet which did not respond may still appear later and ask for the archive.
2026-11-29 18:45:34 +01:00
// We keep it for that case; AI Studio deletes it when it quits or starts again:
2026-10-19 14:39:12 +02:00
//
case ShareSheetOutcome . UNRESPONSIVE :
2026-11-13 10:16:56 +01:00
return ShareSheetUnavailable ( plugin , TA ( "The share dialog of your operating system did not respond." ));
2026-10-19 14:39:12 +02:00
case ShareSheetOutcome . FAILED :
case ShareSheetOutcome . UNKNOWN :
default :
2026-11-29 18:45:34 +01:00
this . TryDeleteArchiveDirectory ( archiveDirectory );
2026-10-19 14:39:12 +02:00
return ShareSheetUnavailable ( plugin , TB ( "The native share dialog could not be opened." ));
2026-08-06 10:42:20 +02:00
}
logger . LogInformation ( "Created plugin archive '{ArchivePath}' for plugin '{PluginName}' ({PluginId})." , archivePath , plugin . Name , plugin . Id );
2026-10-19 14:39:12 +02:00
return new ( PluginShareOutcome . SHARED , plugin . Name , archivePath , string . Empty );
2026-08-06 10:42:20 +02:00
}
catch ( OperationCanceledException )
{
2026-11-29 18:45:34 +01:00
this . TryDeleteArchiveDirectory ( archiveDirectory );
2026-08-06 10:42:20 +02:00
throw ;
}
catch ( Exception exception )
{
2026-11-29 18:45:34 +01:00
this . TryDeleteArchiveDirectory ( archiveDirectory );
2026-08-06 10:42:20 +02:00
logger . LogError ( exception , "Failed to create a share archive for plugin '{PluginName}' ({PluginId})." , plugin . Name , plugin . Id );
return ShareError ( plugin , string . Format ( TB ( "Unexpected error: {0}" ), exception . Message ));
}
}
private static bool TryGetPluginRoot ( IAvailablePlugin plugin , out string pluginRoot , out string issue )
{
pluginRoot = string . Empty ;
issue = string . Empty ;
if ( string . IsNullOrWhiteSpace ( plugin . LocalPath ))
{
issue = TB ( "The plugin has no local directory." );
return false ;
}
try
{
pluginRoot = Path . GetFullPath ( plugin . LocalPath );
}
catch ( Exception exception )
{
issue = string . Format ( TB ( "The plugin directory is invalid: {0}" ), exception . Message );
return false ;
}
if (! Directory . Exists ( pluginRoot ))
{
issue = TB ( "The plugin directory does not exist." );
return false ;
}
var pluginFile = Path . Join ( pluginRoot , PLUGIN_FILE_NAME );
if (! IsPathInsideDirectory ( pluginRoot , pluginFile ) || ! File . Exists ( pluginFile ))
{
issue = TB ( "The plugin directory does not contain a plugin.lua file." );
return false ;
}
return true ;
}
private static string CreateSafeFileNamePrefix ( string pluginName )
{
var invalidCharacters = Path . GetInvalidFileNameChars (). ToHashSet ();
var fileName = new string ( pluginName
. Trim ()
. Select ( character => char . IsLetterOrDigit ( character ) || (( character is '-' or '_' or '.' ) && ! invalidCharacters . Contains ( character ))
? character
: '-' )
. ToArray ())
. Trim ( '-' , '.' );
if ( fileName . Length > FILE_NAME_PREFIX_MAX_LEN )
fileName = fileName [.. FILE_NAME_PREFIX_MAX_LEN ]. Trim ( '-' , '.' );
return string . IsNullOrWhiteSpace ( fileName ) ? "plugin" : fileName ;
}
private static bool IsPathInsideDirectory ( string parentDirectory , string path )
{
var parentPath = Path . GetFullPath ( parentDirectory ). TrimEnd ( Path . DirectorySeparatorChar , Path . AltDirectorySeparatorChar ) + Path . DirectorySeparatorChar ;
var childPath = Path . GetFullPath ( path ). TrimEnd ( Path . DirectorySeparatorChar , Path . AltDirectorySeparatorChar ) + Path . DirectorySeparatorChar ;
return childPath . StartsWith ( parentPath , StringComparison . OrdinalIgnoreCase );
}
2026-11-29 18:45:34 +01:00
private void TryDeleteArchiveDirectory ( string? archiveDirectory )
{
if ( archiveDirectory is null || ! Directory . Exists ( archiveDirectory ))
return ;
try
{
Directory . Delete ( archiveDirectory , true );
}
catch ( Exception exception )
{
logger . LogWarning ( exception , "Failed to delete the temporary plugin archive in '{ArchiveDirectory}'. AI Studio deletes it when it starts again." , archiveDirectory );
}
}
2026-08-06 10:42:20 +02:00
private void TryDeleteArchive ( string archivePath )
{
if (! File . Exists ( archivePath ))
return ;
try
{
File . Delete ( archivePath );
}
catch ( Exception exception )
{
logger . LogWarning ( exception , "Failed to delete temporary plugin archive '{ArchivePath}'." , archivePath );
}
}
}