Skip to content

Commit 8b6e6e4

Browse files
committed
Refactor
1 parent 326d795 commit 8b6e6e4

2 files changed

Lines changed: 10 additions & 4 deletions

File tree

src/main/java/pl/geek/tewu/gmail_attachments_extractor/GmailAttachmentsExtractor.java

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -157,16 +157,13 @@ public boolean extractAttachments() throws IOException, MessagingException, Pars
157157
continue;
158158
String unsanitizedFileName = fileName;
159159
fileName = Utils.resolvingSanitizeFileName(attachmentsDir, fileName);
160+
fileName = Utils.findUniqueFileName(attachmentsDir, fileName, 100); // There can be multiple files with the same name, because file name can change during sanitization, or because the headers can be malformed (see Utils.getPartFileName)
160161
Path filePath = attachmentsDir.resolve(fileName);
161162
String contentType = part.getContentType();
162163
String mimeType = contentType.indexOf(";") > 0 ?
163164
contentType.substring(0, contentType.indexOf(";")) :
164165
contentType;
165166
// Save part to file
166-
int fileIdx = 2;
167-
while (filePath.toFile().exists()) // There can be multiple files with the same name, because the headers can be malformed (see Utils.getPartFileName)
168-
filePath = filePath.resolveSibling(fileName + " " + fileIdx++);
169-
fileName = filePath.getFileName().toString();
170167
saveToFile(part, filePath);
171168
// Calculate part/file size
172169
long fileSize = Files.size(filePath);

src/main/java/pl/geek/tewu/gmail_attachments_extractor/Utils.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,15 @@ public static FileOutputStream openOutputStream(final File file, final boolean a
183183
return new FileOutputStream(file, append);
184184
}
185185

186+
public static String findUniqueFileName(Path dirPath, String fileName, int maxNum) {
187+
int i = 2;
188+
Path path = dirPath.resolve(fileName);
189+
while (path.toFile().exists() && i <= maxNum)
190+
path = dirPath.resolve(fileName + " " + i++);
191+
if (path.toFile().exists()) throw new RuntimeException("Can't find unique file patch for '" + dirPath.resolve(fileName) + "'");
192+
return path.getFileName().toString();
193+
}
194+
186195
/***** Mail *****/
187196
public static final String CONTENT_TYPE_HNAME = "Content-Type";
188197
public static final String CONTENT_DISPOSITION_HNAME = "Content-Disposition";

0 commit comments

Comments
 (0)