Skip to content
Open
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
2 changes: 1 addition & 1 deletion backend/FwHeadless/Controllers/MediaFileController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,7 @@ private static async Task<FileMetadata> InitMetadata(FileMetadata? metadata, IFo
mediaFile = new MediaFile()
{
Id = fileId.Value,
Filename = MediaFilePath.Normalize(Path.Join(LinkedFiles, subfolder, fileId.ToString(), filename)),
Filename = MediaFilePath.ForUpload(subfolder, fileId.Value, filename),
ProjectId = projectId,
Metadata = metadata,
};
Expand Down
7 changes: 7 additions & 0 deletions backend/FwHeadless/Media/MediaFilePath.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
using System.Text;
using FwHeadless.Controllers;

namespace FwHeadless.Media;

/// <summary>
Expand All @@ -10,4 +13,8 @@ namespace FwHeadless.Media;
public static class MediaFilePath
{
public static string Normalize(string path) => path.Replace('\\', '/');

// NFC like FLEx names its files (LabeledMultiStringView.CreateNewSoundFilename).
public static string ForUpload(string subfolder, Guid fileId, string filename) =>
Normalize(Path.Join(MediaFileController.LinkedFiles, subfolder, fileId.ToString(), filename.Normalize(NormalizationForm.FormC)));
}
15 changes: 12 additions & 3 deletions backend/FwHeadless/Media/MediaFileService.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System.Net.Mime;
using System.Security.Cryptography;
using System.Text;
using FwHeadless.Controllers;
using FwHeadless.Services;
using LcmCrdt.MediaServer;
Expand Down Expand Up @@ -87,8 +88,16 @@ private IEnumerable<string> FilesRelativeToHgRepo(LcmCache cache)
var fwDataFolder = config.Value.GetFwDataFolder(config.Value.GetProjectFolder(projectId));
if (!path.StartsWith(fwDataFolder)) return null;
var relativePath = MediaFilePath.Normalize(Path.GetRelativePath(fwDataFolder, path));
//normalize the stored column too: legacy rows may have been written under a different OS's separators
return dbContext.Files.FirstOrDefault(f => f.ProjectId == projectId && f.Filename.Replace("\\", "/") == relativePath);
// LCM hands us NFD paths, but files may be named either way (see MediaFilePath.ForUpload). Mirrors FLEx's
// exact, NFC, NFD lookup: https://github.com/sillsdev/liblcm/blob/da7140f07b92/src/SIL.LCModel.Utils/FileUtils.cs#L434
string[] spellings = [relativePath, relativePath.Normalize(NormalizationForm.FormC), relativePath.Normalize(NormalizationForm.FormD)];
//normalize the stored column too: legacy rows may have been written under a different OS's separators.
//Inline Replace, not MediaFilePath.Normalize, so EF can translate it to SQL.
return dbContext.Files
.Where(f => f.ProjectId == projectId && spellings.Contains(f.Filename.Replace("\\", "/")))
.AsEnumerable()
.OrderBy(f => MediaFilePath.Normalize(f.Filename) == relativePath ? 0 : 1)
.FirstOrDefault();
}

/// <summary>
Expand Down Expand Up @@ -168,7 +177,7 @@ public virtual async Task SyncMediaFiles(Guid projectId, LcmMediaService lcmMedi
{
Id = lcmResource.Id,
ProjectId = projectId,
Filename = Path.Join(MediaFileController.LinkedFiles, subfolder, lcmResource.Id.ToString(), metadata.Filename),
Filename = MediaFilePath.ForUpload(subfolder, lcmResource.Id, metadata.Filename),
Metadata = FromLcmFileMetadata(metadata),
Revision = 0, // pending: no binary uploaded yet
};
Expand Down
66 changes: 66 additions & 0 deletions backend/FwLite/FwDataMiniLcmBridge.Tests/MediaFileTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ public class MediaFileTests : IAsyncLifetime
{
private readonly FwDataMiniLcmApi _api;
private readonly WritingSystemId _audioWs = "en-Zxxx-x-audio";
// ü as one code point, and as u + combining diaeresis
private const string Nfc = "\u00fc";
private const string Nfd = "u\u0308";
private IMediaAdapter _mediaAdapter;

public MediaFileTests(ProjectLoaderFixture fixture)
Expand Down Expand Up @@ -209,6 +212,69 @@ public async Task AudioWsValuesAreStoredAsNfdByLcm()
GetFwAudioValue(entryId).Should().Be(nfd);
}

[Fact]
public async Task GetEntry_FindsAudioSavedUnderAnNfcNameLikeFlexDoes()
{
var entryId = await AddFileDirectly($"638000000000000000{Nfc}.wav", "audio");

var entry = await _api.GetEntry(entryId);

entry!.CitationForm[_audioWs].Should().NotBe(MediaUri.NotFound.ToString());
}

[Fact]
public async Task SaveFile_StoresTheFileUnderItsNfcName()
{
var upload = await _api.SaveFile(new MemoryStream("audio"u8.ToArray()), new LcmFileMetadata($"{Nfd}.wav", "audio/wav"));

var path = _mediaAdapter.PathFromMediaUri(upload.MediaUri!.Value, _api.Cache);

Path.GetFileName(path).Should().Be($"{Nfc}.wav");
}

[Fact]
public async Task SaveFile_PictureIsFoundAfterLcmStoresItsReferenceAsNfd()
{
var upload = await _api.SaveFile(new MemoryStream("picture"u8.ToArray()), new LcmFileMetadata($"{Nfc}.jpg", "image/jpeg"));
var mediaUri = upload.MediaUri!.Value;
var created = await _api.CreateEntry(new Entry
{
LexemeForm = { ["en"] = "test" },
Senses = [new Sense { Pictures = [new Picture { MediaUri = mediaUri }] }]
});

var entry = await _api.GetEntry(created.Id);

entry!.Senses[0].Pictures[0].MediaUri.Should().Be(mediaUri);
}

[Fact]
public async Task SaveFile_AudioIsFoundAfterLcmStoresItsReferenceAsNfd()
{
var upload = await _api.SaveFile(new MemoryStream("audio"u8.ToArray()), new LcmFileMetadata($"{Nfc}.wav", "audio/wav"));
var mediaUri = upload.MediaUri!.Value;
var created = await _api.CreateEntry(new Entry { LexemeForm = { ["en"] = "test" } });
var after = created.Copy();
after.CitationForm[_audioWs] = mediaUri.ToString();
await _api.UpdateEntry(created, after);

var entry = await _api.GetEntry(created.Id);

entry!.CitationForm[_audioWs].Should().Be(mediaUri.ToString());
}

[Fact]
public async Task SaveFile_TreatsAnNfdFileAsTakingTheName()
{
var olderId = await StoreFileContentsAsync($"{Nfd}.wav", "older upload");

var upload = await _api.SaveFile(new MemoryStream("new upload"u8.ToArray()), new LcmFileMetadata($"{Nfc}.wav", "audio/wav"));

Path.GetFileName(_mediaAdapter.PathFromMediaUri(upload.MediaUri!.Value, _api.Cache)).Should().Be($"{Nfc}-1.wav");
(await ReadFile(upload.MediaUri!.Value)).Should().Be("new upload");
(await ReadFile(new MediaUri(olderId, "localhost"))).Should().Be("older upload");
}

[Fact]
public async Task CanOpenAFile()
{
Expand Down
5 changes: 4 additions & 1 deletion backend/FwLite/FwDataMiniLcmBridge/Api/FwDataMiniLcmApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2044,7 +2044,10 @@ public Task<ReadFileResponse> GetFileStream(MediaUri mediaUri, bool downloadIfMi
public async Task<UploadFileResponse> SaveFile(Stream stream, LcmFileMetadata metadata)
{
if (stream.SafeLength() > MediaFile.MaxFileSize) return new UploadFileResponse(UploadFileResult.TooBig);
var fullPath = Path.Combine(Cache.LangProject.LinkedFilesRootDir, TypeToLinkedFolder(metadata.MimeType), Path.GetFileName(metadata.Filename));
// NFC like FLEx names recordings; LCM still stores the reference as NFD, which LocalMediaAdapter resolves like FLEx.
// https://github.com/sillsdev/FieldWorks/blob/aa84a72144ba/Src/Common/Controls/Widgets/LabeledMultiStringView.cs#L431-L432
var fileName = Path.GetFileName(metadata.Filename).Normalize(NormalizationForm.FormC);
var fullPath = Path.Combine(Cache.LangProject.LinkedFilesRootDir, TypeToLinkedFolder(metadata.MimeType), fileName);
var directory = Path.GetDirectoryName(fullPath);
if (directory is not null)
{
Expand Down
4 changes: 4 additions & 0 deletions backend/FwLite/FwDataMiniLcmBridge/Media/LocalMediaAdapter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using Microsoft.Extensions.Logging;
using MiniLcm.Media;
using SIL.LCModel;
using SIL.LCModel.Utils;
using UUIDNext;

namespace FwDataMiniLcmBridge.Media;
Expand Down Expand Up @@ -57,6 +58,9 @@ private static string PreferNfd(string curr, string @new)
public MediaUri MediaUriFromPath(string path, LcmCache cache)
{
if (!Path.IsPathRooted(path)) throw new ArgumentException("Path must be absolute, " + path, nameof(path));
// LCM hands us NFD references, but FLEx names files NFC (older versions NFD). FLEx finds them with this:
// https://github.com/sillsdev/liblcm/blob/da7140f07b92/src/SIL.LCModel.Utils/FileUtils.cs#L434
path = FileUtils.ActualFilePath(path);
if (!File.Exists(path)) return MediaUri.NotFound;
var uri = PathToUri(path);
Paths(cache).TryAdd(uri.FileId, path);
Expand Down
19 changes: 16 additions & 3 deletions backend/FwLite/MiniLcm/Media/LocalMediaFiles.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
using System.Text;

namespace MiniLcm.Media;

/// <summary>
Expand Down Expand Up @@ -53,7 +55,7 @@ public static bool ContentEquals(string pathA, string pathB)
/// </summary>
public static IEnumerable<string> ExistingCopies(string sourcePath, string targetPath)
{
return Candidates(targetPath).TakeWhile(File.Exists).Where(candidate => ContentEquals(sourcePath, candidate));
return Candidates(targetPath).TakeWhile(IsTaken).Where(candidate => ContentEquals(sourcePath, candidate));
}

/// <summary>
Expand All @@ -69,7 +71,7 @@ public static string MoveToFreePath(string sourcePath, string targetPath)

private static bool TryMove(string sourcePath, string targetPath)
{
if (File.Exists(targetPath)) return false;
if (IsTaken(targetPath)) return false;
try
{
File.Move(sourcePath, targetPath, overwrite: false);
Expand All @@ -87,7 +89,18 @@ private static bool TryMove(string sourcePath, string targetPath)
/// </summary>
public static string EnsureUnique(string filePath)
{
return Candidates(filePath).First(candidate => !File.Exists(candidate));
return Candidates(filePath).First(candidate => !IsTaken(candidate));
}

// NTFS and ext4 treat NFC and NFD names as different files, but media ids treat them as one
// (LocalMediaAdapter.NewGuidV5), so either spelling takes the name.
private static bool IsTaken(string filePath)
{
var directory = Path.GetDirectoryName(filePath) ?? "";
var name = Path.GetFileName(filePath);
return File.Exists(filePath)
|| File.Exists(Path.Join(directory, name.Normalize(NormalizationForm.FormC)))
|| File.Exists(Path.Join(directory, name.Normalize(NormalizationForm.FormD)));
}

public static void DeleteIfExists(string path)
Expand Down
17 changes: 17 additions & 0 deletions backend/Testing/FwHeadless/MediaFilePathTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using FwHeadless.Media;

namespace Testing.FwHeadless;

public class MediaFilePathTests
{
// ü as one code point, and as u + combining diaeresis
private const string Nfc = "\u00fc";
private const string Nfd = "u\u0308";
[Fact]
public void ForUpload_StoresTheFilenameAsNfc()
{
var fileId = Guid.NewGuid();
MediaFilePath.ForUpload("Pictures", fileId, $"{Nfd}.jpg")
.Should().Be($"LinkedFiles/Pictures/{fileId}/{Nfc}.jpg");
}
}
23 changes: 23 additions & 0 deletions backend/Testing/FwHeadless/MediaFileServiceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ namespace Testing.FwHeadless;
[Trait("Category", "RequiresDb")]
public class MediaFileServiceTests : IDisposable
{
// ü as one code point, and as u + combining diaeresis
private const string Nfc = "\u00fc";
private const string Nfd = "u\u0308";

private readonly MediaFileService _service;
private readonly LexboxFwDataMediaAdapter _adapter;
private readonly FwHeadlessConfig _fwHeadlessConfig;
Expand Down Expand Up @@ -414,4 +418,23 @@ public async Task FindMediaFile_MatchesRowWithForeignPathSeparators()
found.Should().NotBeNull();
found!.Id.Should().Be(seeded.Id);
}

[Fact]
public async Task FindMediaFile_MatchesNfdPathToRowSavedAsNfc()
{
var nfcRow = await AddDbFile($"{Nfc}.wav");
var nfdPath = Path.Join(_cache.ProjectId.ProjectFolder, LinkedFileRelativePath($"{Nfd}.wav"));

_service.FindMediaFile(_projectId, nfdPath)!.Id.Should().Be(nfcRow.Id);
}

[Fact]
public async Task FindMediaFile_PrefersTheExactSpellingOverItsNfcTwin()
{
await AddDbFile($"{Nfc}.wav");
var nfdRow = await AddDbFile($"{Nfd}.wav");
var nfdPath = Path.Join(_cache.ProjectId.ProjectFolder, LinkedFileRelativePath($"{Nfd}.wav"));

_service.FindMediaFile(_projectId, nfdPath)!.Id.Should().Be(nfdRow.Id);
}
}
15 changes: 15 additions & 0 deletions backend/Testing/FwHeadless/SyncMediaFilesReconcileTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ namespace Testing.FwHeadless;
[Trait("Category", "RequiresDb")]
public class SyncMediaFilesReconcileTests : IAsyncLifetime
{
// ü as one code point, and as u + combining diaeresis
private const string Nfc = "\u00fc";
private const string Nfd = "u\u0308";

private readonly MediaFileService _lexboxMediaService;
private readonly LexBoxDbContext _dbContext;
private readonly Guid _projectId = Guid.NewGuid();
Expand Down Expand Up @@ -194,6 +198,17 @@ public async Task SyncMediaFiles_ReservesPendingHtmlUnderPlugins()
MediaFilePath.Normalize(pendingRow.Filename).Should().Be($"LinkedFiles/Plugins/{pendingId}/plugin-abc123.html");
}

[Fact]
public async Task SyncMediaFiles_ReservesPendingPathAsNfc()
{
var pendingId = await SeedPendingResource($"{Nfd}.wav");

await _lexboxMediaService.SyncMediaFiles(_projectId, _lcmMediaService);

MediaFilePath.Normalize(_dbContext.Files.Single(f => f.Id == pendingId).Filename)
.Should().Be($"LinkedFiles/AudioVisual/{pendingId}/{Nfc}.wav");
}

[Fact]
public async Task SyncMediaFiles_LeavesResourceWithoutMetadataUntouched()
{
Expand Down
Loading