1
|
|
|
package com.osomapps.pt.reportphoto; |
2
|
|
|
|
3
|
|
|
import com.osomapps.pt.ResourceNotFoundException; |
4
|
|
|
import com.osomapps.pt.goals.InUserPhotoRepository; |
5
|
|
|
import com.osomapps.pt.token.InUserPhoto; |
6
|
|
|
import com.osomapps.pt.user.UserService; |
7
|
|
|
import java.io.IOException; |
8
|
|
|
import java.io.OutputStream; |
9
|
|
|
import java.util.Base64; |
10
|
|
|
import org.springframework.stereotype.Service; |
11
|
|
|
|
12
|
|
|
@Service |
13
|
|
|
class ReportPhotoFileService { |
14
|
|
|
private static final String BASE64_PREFIX = ";base64,"; |
15
|
|
|
private static final int BASE64_PREFIX_LENGTH = 8; |
16
|
|
|
private final InUserPhotoRepository inUserPhotoRepository; |
17
|
|
|
private final UserService userService; |
18
|
|
|
|
19
|
|
|
ReportPhotoFileService(InUserPhotoRepository inUserPhotoRepository, UserService userService) { |
20
|
|
|
this.inUserPhotoRepository = inUserPhotoRepository; |
21
|
|
|
this.userService = userService; |
22
|
|
|
} |
23
|
|
|
|
24
|
|
|
ReportPhotoFileDTO findOne(String token, Long id, String fileName, OutputStream outputStream) |
|
|
|
|
25
|
|
|
throws IOException { |
26
|
|
|
if (!token.isEmpty()) { |
27
|
|
|
userService.checkUserToken(token); |
28
|
|
|
final InUserPhoto inUserPhoto = inUserPhotoRepository.findById(id).orElse(null); |
29
|
|
|
if (inUserPhoto == null) { |
30
|
|
|
throw new ResourceNotFoundException("File with id " + id + " not found"); |
31
|
|
|
} |
32
|
|
|
dataUrlToOutputStream(inUserPhoto.getData_url(), outputStream); |
33
|
|
|
return new ReportPhotoFileDTO() |
34
|
|
|
.setId(inUserPhoto.getId()) |
35
|
|
|
.setFileName(inUserPhoto.getFile_name()) |
36
|
|
|
.setFileType(inUserPhoto.getFile_type()); |
37
|
|
|
} |
38
|
|
|
return new ReportPhotoFileDTO(); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
void dataUrlToOutputStream(String dataUrl, OutputStream outputStream) throws IOException { |
42
|
|
|
final String encodedString = |
43
|
|
|
dataUrl.substring(dataUrl.indexOf(BASE64_PREFIX) + BASE64_PREFIX_LENGTH); |
44
|
|
|
outputStream.write(Base64.getDecoder().decode(encodedString)); |
45
|
|
|
} |
46
|
|
|
} |
47
|
|
|
|