Commit 55c49535 authored by Thomas's avatar Thomas
Browse files

OUT-798: Normalize file names of attachments

parent 1d5e4cce
......@@ -1049,6 +1049,56 @@ namespace pEp
return isAttachedMail;
}
/// <summary>
/// Normalizes the file name of a given attachment.
/// </summary>
/// <param name="attachmentFileNames">The list of file names in this message before processing.</param>
/// <param name="normalizedAttachments">The list of normalized file names.</param>
public void NormalizeFileName(List<string> attachmentFileNames, List<PEPAttachment> normalizedAttachments)
{
if (string.IsNullOrEmpty(this.FileName))
{
return;
}
// Remove file path
if (this.FileName.Contains('\\'))
{
this.FileName = this.FileName.Split('\\')?.Last();
}
/* Add numbering to file name if necessary. If 'file.ext' exists multiple times,
* rename to 'file.ext', 'file (1).ext', 'file (2).ext' etc.
*/
bool error = false;
int counter = 1;
string normalizedFileName = this.FileName;
// If there is already a file with this file name, add number
while (normalizedAttachments.Any(a => a.FileName?.Equals(normalizedFileName) == true) &&
(error == false))
{
do
{
try
{
var fileParts = this.FileName.Split('.');
normalizedFileName = string.Join("", new ArraySegment<string>(fileParts, 0, fileParts.Length - 1));
normalizedFileName += " (" + counter++ + ")." + fileParts.Last();
}
catch (Exception ex)
{
error = true;
Log.Error("NormalizeFileNames: Error occured. " + ex.ToString());
}
// Doublecheck to make sure the modified file name doesn't exist yet
} while ((attachmentFileNames.Contains(normalizedFileName)) &&
(error == false));
}
this.FileName = normalizedFileName;
}
/**************************************************************
*
......
......@@ -3294,6 +3294,15 @@ namespace pEp
// Attachments
newMessage.Attachments.Clear();
attachments = omi.Attachments;
// Create a preliminary list for later normalizing of file names
List<string> attachmentFileNames = new List<string>();
for (int i = 1; i <= attachments.Count; i++)
{
attachmentFileNames.Add(attachments[i].FileName.Split('\\').Last());
}
// Add attachments to new message
for (int i = 1; i <= attachments.Count; i++)
{
attachment = attachments[i];
......@@ -3303,6 +3312,9 @@ namespace pEp
var newAttachment = new PEPAttachment(attachment, newMessage.LongMsgFormattedHtml ?? newMessage.LongMsgFormattedRtf ?? newMessage.LongMsg);
if (newAttachment?.Data != null)
{
// Normalize the file name if necessary
newAttachment.NormalizeFileName(attachmentFileNames, newMessage.Attachments);
newMessage.Attachments.Add(newAttachment);
}
}
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment