Files
AI-Studio/app/MindWork AI Studio/Tools/TemporaryFiles.cs
T

153 lines
6.7 KiB
C#
Raw Normal View History

namespace AIStudio.Tools;
/// <summary>
/// The temporary folder of AI Studio below its data directory, for files which live only while AI Studio runs.
/// </summary>
/// <remarks>
/// <para>
/// AI Studio does not write into the temporary folder of the system. On many Linux systems, that folder lives in
/// memory (tmpfs). In a Flatpak, it always does, limited to a tenth of the memory, and a recording or a document with
/// videos takes hundreds of megabytes. Besides, all users of a Linux computer share /tmp, and each of them can read
/// a file which .NET creates there, whereas the data directory lies in the home folder of the user.
/// </para>
/// <para>
/// AI Studio empties the folder when it starts, before any service runs, and once more when it stops. A file therefore
/// lives at most as long as AI Studio runs, and whatever a crash left behind is gone with the next start. Whoever
/// creates a file or a folder here still deletes it once done, since AI Studio may run for weeks. A backup leaves the
/// folder out, see DataBackupContents.
/// </para>
/// </remarks>
internal static class TemporaryFiles
{
/// <summary>
/// The name of the folder in the data directory.
/// </summary>
/// <remarks>
/// Keep in sync with TEMPORARY_DIRECTORY_NAME in runtime/src/share_sheet.rs: the runtime hands only plugin
/// archives from this folder to the share sheet of the operating system.
/// </remarks>
public const string FOLDER_NAME = "tmp";
/// <summary>
/// The folder below the data directory, see DataBackupContents.
/// </summary>
public const string DIRECTORY = $"{FOLDER_NAME}/";
/// <summary>
/// The folders in which earlier versions of AI Studio kept their temporary files, as patterns of folders directly
/// in the data directory.
/// </summary>
/// <remarks>
/// They are deleted on every start, which costs a look per pattern, so that no installation keeps them.
/// </remarks>
private static readonly string[] FOLDERS_OF_EARLIER_VERSIONS = ["mailAttachments", "pandoc-install-*", ".document-staging", ".plugin-staging", "media-staging"];
/// <summary>
/// Finds the folders of earlier versions also when they are hidden: on Linux and macOS, .NET takes a name which
/// begins with a dot for hidden.
/// </summary>
private static readonly EnumerationOptions ALL_FOLDERS = new() { AttributesToSkip = FileAttributes.None };
private static string? FOLDER_PATH;
/// <summary>
/// Sets the folder below the given data directory and empties it, together with the folders of earlier versions.
/// </summary>
/// <remarks>
/// AI Studio calls this once, before any service runs, since emptying the folder deletes what a running operation
/// wrote there. Only the first instance of AI Studio starts its server, so a second one never deletes the files of
/// the first.
/// </remarks>
/// <param name="dataDirectory">The data directory of AI Studio, as the runtime reports it.</param>
/// <param name="logger">Where to report a folder which cannot be deleted.</param>
public static void Initialize(string dataDirectory, ILogger logger)
{
// Below a relative path, the folder would lie in the working directory, and emptying it would delete files there:
if (!Path.IsPathFullyQualified(dataDirectory))
{
logger.LogError("The temporary folder of AI Studio is not available, because the data directory '{DataDirectory}' is not an absolute path.", dataDirectory);
return;
}
FOLDER_PATH = Path.Join(dataDirectory, FOLDER_NAME);
Clear(logger);
DeleteFoldersOfEarlierVersions(dataDirectory, logger);
}
/// <summary>
/// Makes up the path of a new file in the folder.
/// </summary>
/// <param name="fileExtension">The extension of the file, including the leading dot.</param>
/// <returns>The path, where no file exists yet.</returns>
/// <exception cref="InvalidOperationException">AI Studio has not set the folder yet.</exception>
public static string GetFilePath(string fileExtension) => Path.Join(GetDirectory(), $"{Guid.NewGuid():N}{fileExtension}");
/// <summary>
/// Creates a new, empty folder in the folder, e.g., for files which belong together.
/// </summary>
/// <returns>The path of the new folder.</returns>
/// <exception cref="InvalidOperationException">AI Studio has not set the folder yet.</exception>
public static string CreateDirectory()
{
var path = Path.Join(GetDirectory(), Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(path);
return path;
}
/// <summary>
/// Deletes everything in the folder. AI Studio does so when it starts and when it stops.
/// </summary>
/// <param name="logger">Where to report a folder which cannot be deleted.</param>
public static void Clear(ILogger logger)
{
if (FOLDER_PATH is not null)
Delete(FOLDER_PATH, logger);
}
private static void DeleteFoldersOfEarlierVersions(string dataDirectory, ILogger logger)
{
if (!Directory.Exists(dataDirectory))
return;
try
{
foreach (var pattern in FOLDERS_OF_EARLIER_VERSIONS)
{
foreach (var folder in Directory.EnumerateDirectories(dataDirectory, pattern, ALL_FOLDERS))
Delete(folder, logger);
}
}
catch (Exception exception)
{
logger.LogWarning(exception, "The temporary folders of earlier versions of AI Studio in '{DataDirectory}' could not be looked through. The next start of AI Studio tries again.", dataDirectory);
}
}
private static string GetDirectory()
{
var path = FOLDER_PATH ?? throw new InvalidOperationException("The temporary folder of AI Studio is not set yet.");
Directory.CreateDirectory(path);
return path;
}
/// <summary>
/// Deletes a folder with everything in it. A link is removed, but never followed: whatever it points to stays.
/// </summary>
/// <param name="path">The folder.</param>
/// <param name="logger">Where to report a folder which cannot be deleted, e.g., since a file in it is open.</param>
private static void Delete(string path, ILogger logger)
{
try
{
var folder = new DirectoryInfo(path);
if (folder.LinkTarget is not null)
folder.Delete();
else if (folder.Exists)
folder.Delete(recursive: true);
}
catch (Exception exception)
{
logger.LogWarning(exception, "The temporary folder '{Path}' could not be deleted. The next start of AI Studio tries again.", path);
}
}
}