namespace AIStudio.Tools; /// /// The temporary folder of AI Studio below its data directory, for files which live only while AI Studio runs. /// /// /// /// 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. /// /// /// 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. /// /// internal static class TemporaryFiles { /// /// The name of the folder in the data directory. /// /// /// 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. /// public const string FOLDER_NAME = "tmp"; /// /// The folder below the data directory, see DataBackupContents. /// public const string DIRECTORY = $"{FOLDER_NAME}/"; /// /// The folders in which earlier versions of AI Studio kept their temporary files, as patterns of folders directly /// in the data directory. /// /// /// They are deleted on every start, which costs a look per pattern, so that no installation keeps them. /// private static readonly string[] FOLDERS_OF_EARLIER_VERSIONS = ["mailAttachments", "pandoc-install-*", ".document-staging", ".plugin-staging", "media-staging"]; /// /// 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. /// private static readonly EnumerationOptions ALL_FOLDERS = new() { AttributesToSkip = FileAttributes.None }; private static string? FOLDER_PATH; /// /// Sets the folder below the given data directory and empties it, together with the folders of earlier versions. /// /// /// 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. /// /// The data directory of AI Studio, as the runtime reports it. /// Where to report a folder which cannot be deleted. 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); } /// /// Makes up the path of a new file in the folder. /// /// The extension of the file, including the leading dot. /// The path, where no file exists yet. /// AI Studio has not set the folder yet. public static string GetFilePath(string fileExtension) => Path.Join(GetDirectory(), $"{Guid.NewGuid():N}{fileExtension}"); /// /// Creates a new, empty folder in the folder, e.g., for files which belong together. /// /// The path of the new folder. /// AI Studio has not set the folder yet. public static string CreateDirectory() { var path = Path.Join(GetDirectory(), Guid.NewGuid().ToString("N")); Directory.CreateDirectory(path); return path; } /// /// Deletes everything in the folder. AI Studio does so when it starts and when it stops. /// /// Where to report a folder which cannot be deleted. 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; } /// /// Deletes a folder with everything in it. A link is removed, but never followed: whatever it points to stays. /// /// The folder. /// Where to report a folder which cannot be deleted, e.g., since a file in it is open. 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); } } }