1 package org
.asamk
.signal
.manager
;
3 import org
.asamk
.signal
.manager
.util
.IOUtils
;
4 import org
.asamk
.signal
.manager
.util
.MimeUtils
;
5 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentPointer
;
6 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentRemoteId
;
9 import java
.io
.FileOutputStream
;
10 import java
.io
.IOException
;
11 import java
.io
.OutputStream
;
12 import java
.util
.Optional
;
14 public class AttachmentStore
{
16 private final File attachmentsPath
;
18 public AttachmentStore(final File attachmentsPath
) {
19 this.attachmentsPath
= attachmentsPath
;
22 public void storeAttachmentPreview(
23 final SignalServiceAttachmentPointer pointer
, final AttachmentStorer storer
24 ) throws IOException
{
25 storeAttachment(getAttachmentPreviewFile(pointer
.getRemoteId(),
26 pointer
.getFileName(),
27 Optional
.ofNullable(pointer
.getContentType())), storer
);
30 public void storeAttachment(
31 final SignalServiceAttachmentPointer pointer
, final AttachmentStorer storer
32 ) throws IOException
{
33 storeAttachment(getAttachmentFile(pointer
), storer
);
36 public File
getAttachmentFile(final SignalServiceAttachmentPointer pointer
) {
37 return getAttachmentFile(pointer
.getRemoteId(),
38 pointer
.getFileName(),
39 Optional
.ofNullable(pointer
.getContentType()));
42 private void storeAttachment(final File attachmentFile
, final AttachmentStorer storer
) throws IOException
{
43 createAttachmentsDir();
44 try (OutputStream output
= new FileOutputStream(attachmentFile
)) {
49 private File
getAttachmentPreviewFile(
50 SignalServiceAttachmentRemoteId attachmentId
, Optional
<String
> filename
, Optional
<String
> contentType
52 final var extension
= getAttachmentExtension(filename
, contentType
);
53 return new File(attachmentsPath
, attachmentId
.toString() + extension
+ ".preview");
56 private File
getAttachmentFile(
57 SignalServiceAttachmentRemoteId attachmentId
, Optional
<String
> filename
, Optional
<String
> contentType
59 final var extension
= getAttachmentExtension(filename
, contentType
);
60 return new File(attachmentsPath
, attachmentId
.toString() + extension
);
63 private static String
getAttachmentExtension(
64 final Optional
<String
> filename
, final Optional
<String
> contentType
66 return filename
.filter(f
-> f
.contains("."))
67 .map(f
-> f
.substring(f
.lastIndexOf(".") + 1))
68 .or(() -> contentType
.flatMap(MimeUtils
::guessExtensionFromMimeType
))
69 .map(ext
-> "." + ext
)
73 private void createAttachmentsDir() throws IOException
{
74 IOUtils
.createPrivateDirectories(attachmentsPath
);
78 public interface AttachmentStorer
{
80 void store(OutputStream outputStream
) throws IOException
;