Compare commits
9
Commits
f3aa6324c2
...
NCBACK-15
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1932784264 | ||
|
|
bd78b88f33 | ||
|
|
22c2eed8a1 | ||
|
|
f3266ee0e5 | ||
|
|
280bd91257 | ||
|
|
31b90f942c | ||
|
|
d167e92d90 | ||
|
|
651b92cb59 | ||
|
|
d34a304763 |
@@ -54,15 +54,26 @@ pipeline {
|
|||||||
echo 'Step 1: Checking current state...'
|
echo 'Step 1: Checking current state...'
|
||||||
|
|
||||||
# Смотрим что запущено
|
# Смотрим что запущено
|
||||||
docker ps --filter 'name=postgres|app-backend' --format 'table {{.Names}}\\t{{.Status}}\\t{{.Ports}}'
|
docker ps --filter 'name=postgres|app-backend' --format 'table {{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}'
|
||||||
|
|
||||||
echo 'Step 2: Stopping only application (keeping DB)...'
|
echo 'Step 2: Force cleanup old application...'
|
||||||
|
|
||||||
# Останавливаем только приложение, БД оставляем работать
|
# Принудительно удаляем старый контейнер и образ
|
||||||
docker stop app-backend 2>/dev/null || echo 'App not running'
|
docker stop app-backend 2>/dev/null || echo 'App not running'
|
||||||
docker rm app-backend 2>/dev/null || echo 'App not found'
|
docker rm app-backend 2>/dev/null || echo 'App not found'
|
||||||
|
docker rmi app-backend:latest 2>/dev/null || echo 'Image not found'
|
||||||
|
|
||||||
# Проверяем что БД работает, если нет - запускаем
|
# Удаляем все образы app-backend
|
||||||
|
docker images --filter 'reference=app-backend*' -q | xargs -r docker rmi 2>/dev/null || echo 'No images to remove'
|
||||||
|
|
||||||
|
echo 'Step 3: Verify copied files...'
|
||||||
|
echo 'Files in directory:'
|
||||||
|
ls -la
|
||||||
|
echo ''
|
||||||
|
echo 'Checking Java sources:'
|
||||||
|
find . -name '*.java' | head -2
|
||||||
|
|
||||||
|
echo 'Step 4: Check if PostgreSQL is running...'
|
||||||
if ! docker ps | grep -q postgres; then
|
if ! docker ps | grep -q postgres; then
|
||||||
echo 'Starting PostgreSQL...'
|
echo 'Starting PostgreSQL...'
|
||||||
docker-compose up -d db
|
docker-compose up -d db
|
||||||
@@ -71,13 +82,37 @@ pipeline {
|
|||||||
echo 'PostgreSQL already running'
|
echo 'PostgreSQL already running'
|
||||||
fi
|
fi
|
||||||
|
|
||||||
echo 'Step 3: Building new application image...'
|
echo 'Step 5: Build application with forced rebuild...'
|
||||||
docker build --no-cache -t app-backend:latest .
|
echo 'Checking Dockerfile exists:'
|
||||||
|
ls -la Dockerfile 2>/dev/null || echo 'Dockerfile not found, creating simple one'
|
||||||
|
|
||||||
echo 'Step 4: Starting application...'
|
# Если нет Dockerfile, создаем простой
|
||||||
|
if [ ! -f Dockerfile ]; then
|
||||||
|
echo 'Creating simple Dockerfile...'
|
||||||
|
cat > Dockerfile << 'EOF'
|
||||||
|
FROM eclipse-temurin:21-jre
|
||||||
|
WORKDIR /app
|
||||||
|
COPY . /app/
|
||||||
|
CMD ["java", "-jar", "app.jar"]
|
||||||
|
EOF
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Собираем с подробным выводом
|
||||||
|
echo 'Building Docker image...'
|
||||||
|
docker build --no-cache --progress=plain -t app-backend:latest . 2>&1 | tail -50
|
||||||
|
|
||||||
|
echo 'Step 6: Verify new image...'
|
||||||
|
echo 'Current app-backend images:'
|
||||||
|
docker images | grep app-backend
|
||||||
|
|
||||||
|
echo 'Image creation time:'
|
||||||
|
docker inspect app-backend:latest --format='{{.Created}}' 2>/dev/null || echo 'Cannot inspect image'
|
||||||
|
|
||||||
|
echo 'Step 7: Starting application with alias...'
|
||||||
docker run -d \\
|
docker run -d \\
|
||||||
--name app-backend \\
|
--name app-backend \\
|
||||||
--network app-network \\
|
--network app-network \\
|
||||||
|
--network-alias app \\
|
||||||
-p 80:8080 \\
|
-p 80:8080 \\
|
||||||
-e POSTGRES_DB=no_copy_ \\
|
-e POSTGRES_DB=no_copy_ \\
|
||||||
-e POSTGRES_USER=postgres \\
|
-e POSTGRES_USER=postgres \\
|
||||||
@@ -87,17 +122,35 @@ pipeline {
|
|||||||
--restart unless-stopped \\
|
--restart unless-stopped \\
|
||||||
app-backend:latest
|
app-backend:latest
|
||||||
|
|
||||||
echo 'Step 5: Checking deployment...'
|
echo 'Step 8: Checking deployment...'
|
||||||
sleep 10
|
sleep 10
|
||||||
|
|
||||||
echo 'Containers status:'
|
echo 'Containers status:'
|
||||||
docker ps --filter 'name=postgres|app-backend' --format 'table {{.Names}}\\t{{.Status}}\\t{{.Ports}}'
|
docker ps --filter 'name=postgres|app-backend' --format 'table {{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.CreatedAt}}'
|
||||||
|
|
||||||
echo 'Application logs (last 5 lines):'
|
echo 'Checking image inside container:'
|
||||||
docker logs --tail=5 app-backend 2>/dev/null || echo 'Logs not available yet'
|
docker exec app-backend ls -la /app/ 2>/dev/null || echo 'Cannot check container files'
|
||||||
|
|
||||||
|
echo 'Application logs (last 10 lines):'
|
||||||
|
docker logs --tail=10 app-backend 2>/dev/null || echo 'Logs not available yet'
|
||||||
|
|
||||||
|
echo 'Step 9: Health check...'
|
||||||
if docker ps | grep -q app-backend; then
|
if docker ps | grep -q app-backend; then
|
||||||
echo 'Deployment successful'
|
echo 'Container is running'
|
||||||
|
echo 'Testing application health...'
|
||||||
|
for i in {1..5}; do
|
||||||
|
if curl -s -f http://localhost:80/health > /dev/null 2>&1; then
|
||||||
|
echo 'Health check passed'
|
||||||
|
echo 'Deployment successful'
|
||||||
|
echo 'Application URL: http://${params.SERVER}:80'
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
echo 'Waiting for application to start... attempt ' \$i
|
||||||
|
sleep 5
|
||||||
|
done
|
||||||
|
|
||||||
|
echo 'Health check failed, but container is running'
|
||||||
|
echo 'Application might be starting slowly'
|
||||||
echo 'Application URL: http://${params.SERVER}:80'
|
echo 'Application URL: http://${params.SERVER}:80'
|
||||||
else
|
else
|
||||||
echo 'Application failed to start'
|
echo 'Application failed to start'
|
||||||
|
|||||||
@@ -15,13 +15,15 @@ public class HandlerConfig {
|
|||||||
RegRequestHandler reg,
|
RegRequestHandler reg,
|
||||||
LoginRequestHandler login,
|
LoginRequestHandler login,
|
||||||
FileUploadHandler upload,
|
FileUploadHandler upload,
|
||||||
FileEntityHandler file
|
FileEntityHandler file,
|
||||||
|
LogoutRequestHandler logoutHandler
|
||||||
) {
|
) {
|
||||||
Map<Integer, RequestHandler> map = new HashMap<>();
|
Map<Integer, RequestHandler> map = new HashMap<>();
|
||||||
map.put(20001, login);
|
map.put(20001, login);
|
||||||
map.put(20002, reg);
|
map.put(20002, reg);
|
||||||
map.put(20004, upload);
|
map.put(20004, upload);
|
||||||
map.put(20005, file);
|
map.put(20005, file);
|
||||||
|
map.put(20006, logoutHandler);
|
||||||
|
|
||||||
return map;
|
return map;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,10 @@ package ru.soune.nocopy.controller;
|
|||||||
|
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.core.io.Resource;
|
||||||
|
import org.springframework.core.io.UrlResource;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.validation.BindingResult;
|
import org.springframework.validation.BindingResult;
|
||||||
import org.springframework.validation.FieldError;
|
import org.springframework.validation.FieldError;
|
||||||
@@ -13,13 +17,22 @@ import ru.soune.nocopy.dto.MessageCode;
|
|||||||
import ru.soune.nocopy.dto.RegAnswer;
|
import ru.soune.nocopy.dto.RegAnswer;
|
||||||
import ru.soune.nocopy.dto.file.ChunkUploadResponse;
|
import ru.soune.nocopy.dto.file.ChunkUploadResponse;
|
||||||
import ru.soune.nocopy.dto.file.CompleteUploadResponse;
|
import ru.soune.nocopy.dto.file.CompleteUploadResponse;
|
||||||
|
import ru.soune.nocopy.dto.file.FileEntityResponse;
|
||||||
import ru.soune.nocopy.dto.file.UploadProgress;
|
import ru.soune.nocopy.dto.file.UploadProgress;
|
||||||
|
import ru.soune.nocopy.entity.AuthToken;
|
||||||
import ru.soune.nocopy.entity.file.UploadStatus;
|
import ru.soune.nocopy.entity.file.UploadStatus;
|
||||||
|
import ru.soune.nocopy.exception.NotFoundAuthToken;
|
||||||
import ru.soune.nocopy.exception.NotValidFieldException;
|
import ru.soune.nocopy.exception.NotValidFieldException;
|
||||||
import ru.soune.nocopy.exception.ValidationException;
|
import ru.soune.nocopy.exception.ValidationException;
|
||||||
import ru.soune.nocopy.handler.*;
|
import ru.soune.nocopy.handler.*;
|
||||||
|
import ru.soune.nocopy.repository.AuthTokenRepository;
|
||||||
|
import ru.soune.nocopy.service.file.FileEntityService;
|
||||||
import ru.soune.nocopy.service.file.FileUploadService;
|
import ru.soune.nocopy.service.file.FileUploadService;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
@@ -34,6 +47,9 @@ public class ApiController {
|
|||||||
|
|
||||||
private final Map<Integer, RequestHandler> handlers;
|
private final Map<Integer, RequestHandler> handlers;
|
||||||
|
|
||||||
|
private final FileEntityService fileEntityService;
|
||||||
|
|
||||||
|
private final AuthTokenRepository authTokenRepository;
|
||||||
|
|
||||||
@PostMapping("/v{version}/data")
|
@PostMapping("/v{version}/data")
|
||||||
public ResponseEntity<?> handlePostRequest(@RequestBody BaseRequest request,
|
public ResponseEntity<?> handlePostRequest(@RequestBody BaseRequest request,
|
||||||
@@ -219,6 +235,117 @@ public class ApiController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@GetMapping("/v{version}/files/download/{fileId}")
|
||||||
|
public ResponseEntity<Resource> downloadFile(
|
||||||
|
@PathVariable String fileId,
|
||||||
|
@PathVariable Integer version,
|
||||||
|
@RequestHeader("Authorization") String tokenHeader) {
|
||||||
|
|
||||||
|
try {
|
||||||
|
Long userId = getUserIdFromToken(tokenHeader);
|
||||||
|
FileEntityResponse fileInfo = fileEntityService.getById(fileId, version);
|
||||||
|
|
||||||
|
if (!fileInfo.getUserId().equals(userId)) {
|
||||||
|
return ResponseEntity.status(403).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!fileInfo.isExistsOnDisk()) {
|
||||||
|
return ResponseEntity.status(404)
|
||||||
|
.body(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
Path filePath = Paths.get(fileInfo.getFilePath());
|
||||||
|
Resource resource = new UrlResource(filePath.toUri());
|
||||||
|
|
||||||
|
if (!resource.exists()) {
|
||||||
|
return ResponseEntity.status(404).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
String contentType = determineContentType(filePath);
|
||||||
|
|
||||||
|
return ResponseEntity.ok()
|
||||||
|
.contentType(MediaType.parseMediaType(contentType))
|
||||||
|
.header(HttpHeaders.CONTENT_DISPOSITION,
|
||||||
|
"attachment; filename=\"" + fileInfo.getOriginalFileName() + "\"")
|
||||||
|
.header(HttpHeaders.CONTENT_LENGTH, String.valueOf(fileInfo.getFileSize()))
|
||||||
|
.body(resource);
|
||||||
|
|
||||||
|
} catch (NotFoundAuthToken e) {
|
||||||
|
return ResponseEntity.status(401).build();
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("Error downloading file", e);
|
||||||
|
return ResponseEntity.status(500).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/v{version}/files/info/{fileId}")
|
||||||
|
public ResponseEntity<FileEntityResponse> getFileInfo(
|
||||||
|
@PathVariable String fileId,
|
||||||
|
@PathVariable Integer version,
|
||||||
|
@RequestHeader("Authorization") String tokenHeader) {
|
||||||
|
|
||||||
|
try {
|
||||||
|
Long userId = getUserIdFromToken(tokenHeader);
|
||||||
|
FileEntityResponse fileInfo = fileEntityService.getById(fileId, version);
|
||||||
|
|
||||||
|
if (!fileInfo.getUserId().equals(userId)) {
|
||||||
|
return ResponseEntity.status(403).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
return ResponseEntity.ok(fileInfo);
|
||||||
|
|
||||||
|
} catch (NotFoundAuthToken e) {
|
||||||
|
return ResponseEntity.status(401).build();
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("Error getting file info", e);
|
||||||
|
return ResponseEntity.status(500).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/v{version}/files/preview/{fileId}")
|
||||||
|
public ResponseEntity<Resource> previewFile(
|
||||||
|
@PathVariable String fileId,
|
||||||
|
@PathVariable Integer version,
|
||||||
|
@RequestHeader("Authorization") String tokenHeader) {
|
||||||
|
|
||||||
|
try {
|
||||||
|
Long userId = getUserIdFromToken(tokenHeader);
|
||||||
|
FileEntityResponse fileInfo = fileEntityService.getById(fileId, version);
|
||||||
|
|
||||||
|
if (!fileInfo.getUserId().equals(userId)) {
|
||||||
|
return ResponseEntity.status(403).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isPreviewSupported(fileInfo.getMimeType())) {
|
||||||
|
return ResponseEntity.status(415)
|
||||||
|
.body(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
Path filePath = Paths.get(fileInfo.getFilePath());
|
||||||
|
Resource resource = new UrlResource(filePath.toUri());
|
||||||
|
|
||||||
|
if (!resource.exists()) {
|
||||||
|
return ResponseEntity.status(404).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
String contentType = determineContentType(filePath);
|
||||||
|
|
||||||
|
return ResponseEntity.ok()
|
||||||
|
.contentType(MediaType.parseMediaType(contentType))
|
||||||
|
.header(HttpHeaders.CONTENT_DISPOSITION,
|
||||||
|
"inline; filename=\"" + fileInfo.getOriginalFileName() + "\"")
|
||||||
|
.body(resource);
|
||||||
|
|
||||||
|
} catch (NotFoundAuthToken e) {
|
||||||
|
return ResponseEntity.status(401).build();
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("Error previewing file", e);
|
||||||
|
return ResponseEntity.status(500).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
private ResponseEntity<BaseResponse> createValidationErrorResponse(BindingResult bindingResult, Integer msgId) {
|
private ResponseEntity<BaseResponse> createValidationErrorResponse(BindingResult bindingResult, Integer msgId) {
|
||||||
List<Map<String, String>> fieldErrors = bindingResult.getFieldErrors()
|
List<Map<String, String>> fieldErrors = bindingResult.getFieldErrors()
|
||||||
.stream()
|
.stream()
|
||||||
@@ -245,4 +372,32 @@ public class ApiController {
|
|||||||
|
|
||||||
return errorDetail;
|
return errorDetail;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
private String determineContentType(Path filePath) throws IOException {
|
||||||
|
String contentType = Files.probeContentType(filePath);
|
||||||
|
if (contentType == null) {
|
||||||
|
contentType = "application/octet-stream";
|
||||||
|
}
|
||||||
|
return contentType;
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isPreviewSupported(String mimeType) {
|
||||||
|
if (mimeType == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return mimeType.startsWith("image/") ||
|
||||||
|
mimeType.startsWith("text/") ||
|
||||||
|
mimeType.equals("application/pdf") ||
|
||||||
|
mimeType.startsWith("video/") ||
|
||||||
|
mimeType.startsWith("audio/");
|
||||||
|
}
|
||||||
|
|
||||||
|
private Long getUserIdFromToken(String tokenHeader) {
|
||||||
|
String token = tokenHeader.replace("Bearer ", "");
|
||||||
|
AuthToken authToken = authTokenRepository.findByToken(token)
|
||||||
|
.orElseThrow(() -> new NotFoundAuthToken("Token not found"));
|
||||||
|
return authToken.getUser().getId();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,37 +0,0 @@
|
|||||||
package ru.soune.nocopy.controller;
|
|
||||||
|
|
||||||
import lombok.RequiredArgsConstructor;
|
|
||||||
import org.springframework.http.ResponseEntity;
|
|
||||||
import org.springframework.web.bind.annotation.*;
|
|
||||||
import ru.soune.nocopy.entity.AuthToken;
|
|
||||||
import ru.soune.nocopy.exception.TokenNotFoundException;
|
|
||||||
import ru.soune.nocopy.repository.AuthTokenRepository;
|
|
||||||
import ru.soune.nocopy.service.AuthService;
|
|
||||||
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Optional;
|
|
||||||
|
|
||||||
@RestController
|
|
||||||
@RequestMapping("v1/api/auth")
|
|
||||||
@RequiredArgsConstructor
|
|
||||||
public class AuthController {
|
|
||||||
|
|
||||||
private final AuthService authService;
|
|
||||||
|
|
||||||
private final AuthTokenRepository authTokenRepository;
|
|
||||||
|
|
||||||
@PostMapping("/logout")
|
|
||||||
public ResponseEntity<?> logout(@RequestHeader("Authorization") String tokenHeader) {
|
|
||||||
String token = tokenHeader.replace("Bearer ", "");
|
|
||||||
|
|
||||||
Optional<AuthToken> opToken = authTokenRepository.findByToken(token);
|
|
||||||
|
|
||||||
if (opToken.isEmpty()) {
|
|
||||||
throw new TokenNotFoundException("Token not found");
|
|
||||||
}
|
|
||||||
|
|
||||||
authService.logout(token);
|
|
||||||
|
|
||||||
return ResponseEntity.ok(Map.of("success", true));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,172 +0,0 @@
|
|||||||
package ru.soune.nocopy.controller.file;
|
|
||||||
|
|
||||||
import lombok.RequiredArgsConstructor;
|
|
||||||
import lombok.extern.slf4j.Slf4j;
|
|
||||||
import org.springframework.core.io.Resource;
|
|
||||||
import org.springframework.core.io.UrlResource;
|
|
||||||
import org.springframework.http.HttpHeaders;
|
|
||||||
import org.springframework.http.MediaType;
|
|
||||||
import org.springframework.http.ResponseEntity;
|
|
||||||
import org.springframework.web.bind.annotation.*;
|
|
||||||
import ru.soune.nocopy.dto.file.FileEntityResponse;
|
|
||||||
import ru.soune.nocopy.entity.AuthToken;
|
|
||||||
import ru.soune.nocopy.exception.NotFoundAuthToken;
|
|
||||||
import ru.soune.nocopy.repository.AuthTokenRepository;
|
|
||||||
import ru.soune.nocopy.service.file.FileEntityService;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.nio.file.Files;
|
|
||||||
import java.nio.file.Path;
|
|
||||||
import java.nio.file.Paths;
|
|
||||||
|
|
||||||
@Slf4j
|
|
||||||
@RestController
|
|
||||||
@RequestMapping("/api/files")
|
|
||||||
@RequiredArgsConstructor
|
|
||||||
public class FileDownloadController {
|
|
||||||
|
|
||||||
private final FileEntityService fileEntityService;
|
|
||||||
private final AuthTokenRepository authTokenRepository;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Скачать файл по ID FileEntity
|
|
||||||
*/
|
|
||||||
@GetMapping("/download/{fileId}")
|
|
||||||
public ResponseEntity<Resource> downloadFile(
|
|
||||||
@PathVariable String fileId,
|
|
||||||
@RequestHeader("Authorization") String tokenHeader) {
|
|
||||||
|
|
||||||
try {
|
|
||||||
Long userId = getUserIdFromToken(tokenHeader);
|
|
||||||
FileEntityResponse fileInfo = fileEntityService.getById(fileId);
|
|
||||||
|
|
||||||
if (!fileInfo.getUserId().equals(userId)) {
|
|
||||||
return ResponseEntity.status(403).build();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!fileInfo.isExistsOnDisk()) {
|
|
||||||
return ResponseEntity.status(404)
|
|
||||||
.body(null);
|
|
||||||
}
|
|
||||||
|
|
||||||
Path filePath = Paths.get(fileInfo.getFilePath());
|
|
||||||
Resource resource = new UrlResource(filePath.toUri());
|
|
||||||
|
|
||||||
if (!resource.exists()) {
|
|
||||||
return ResponseEntity.status(404).build();
|
|
||||||
}
|
|
||||||
|
|
||||||
String contentType = determineContentType(filePath);
|
|
||||||
|
|
||||||
return ResponseEntity.ok()
|
|
||||||
.contentType(MediaType.parseMediaType(contentType))
|
|
||||||
.header(HttpHeaders.CONTENT_DISPOSITION,
|
|
||||||
"attachment; filename=\"" + fileInfo.getOriginalFileName() + "\"")
|
|
||||||
.header(HttpHeaders.CONTENT_LENGTH, String.valueOf(fileInfo.getFileSize()))
|
|
||||||
.body(resource);
|
|
||||||
|
|
||||||
} catch (NotFoundAuthToken e) {
|
|
||||||
return ResponseEntity.status(401).build();
|
|
||||||
} catch (Exception e) {
|
|
||||||
log.error("Error downloading file", e);
|
|
||||||
return ResponseEntity.status(500).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Получить предпросмотр файла (если поддерживается)
|
|
||||||
*/
|
|
||||||
@GetMapping("/preview/{fileId}")
|
|
||||||
public ResponseEntity<Resource> previewFile(
|
|
||||||
@PathVariable String fileId,
|
|
||||||
@RequestHeader("Authorization") String tokenHeader) {
|
|
||||||
|
|
||||||
try {
|
|
||||||
Long userId = getUserIdFromToken(tokenHeader);
|
|
||||||
FileEntityResponse fileInfo = fileEntityService.getById(fileId);
|
|
||||||
|
|
||||||
if (!fileInfo.getUserId().equals(userId)) {
|
|
||||||
return ResponseEntity.status(403).build();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!isPreviewSupported(fileInfo.getMimeType())) {
|
|
||||||
return ResponseEntity.status(415)
|
|
||||||
.body(null);
|
|
||||||
}
|
|
||||||
|
|
||||||
Path filePath = Paths.get(fileInfo.getFilePath());
|
|
||||||
Resource resource = new UrlResource(filePath.toUri());
|
|
||||||
|
|
||||||
if (!resource.exists()) {
|
|
||||||
return ResponseEntity.status(404).build();
|
|
||||||
}
|
|
||||||
|
|
||||||
String contentType = determineContentType(filePath);
|
|
||||||
|
|
||||||
return ResponseEntity.ok()
|
|
||||||
.contentType(MediaType.parseMediaType(contentType))
|
|
||||||
.header(HttpHeaders.CONTENT_DISPOSITION,
|
|
||||||
"inline; filename=\"" + fileInfo.getOriginalFileName() + "\"")
|
|
||||||
.body(resource);
|
|
||||||
|
|
||||||
} catch (NotFoundAuthToken e) {
|
|
||||||
return ResponseEntity.status(401).build();
|
|
||||||
} catch (Exception e) {
|
|
||||||
log.error("Error previewing file", e);
|
|
||||||
return ResponseEntity.status(500).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Получить информацию о файле для фронтенда
|
|
||||||
*/
|
|
||||||
@GetMapping("/info/{fileId}")
|
|
||||||
public ResponseEntity<FileEntityResponse> getFileInfo(
|
|
||||||
@PathVariable String fileId,
|
|
||||||
@RequestHeader("Authorization") String tokenHeader) {
|
|
||||||
|
|
||||||
try {
|
|
||||||
Long userId = getUserIdFromToken(tokenHeader);
|
|
||||||
FileEntityResponse fileInfo = fileEntityService.getById(fileId);
|
|
||||||
|
|
||||||
if (!fileInfo.getUserId().equals(userId)) {
|
|
||||||
return ResponseEntity.status(403).build();
|
|
||||||
}
|
|
||||||
|
|
||||||
return ResponseEntity.ok(fileInfo);
|
|
||||||
|
|
||||||
} catch (NotFoundAuthToken e) {
|
|
||||||
return ResponseEntity.status(401).build();
|
|
||||||
} catch (Exception e) {
|
|
||||||
log.error("Error getting file info", e);
|
|
||||||
return ResponseEntity.status(500).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private String determineContentType(Path filePath) throws IOException {
|
|
||||||
String contentType = Files.probeContentType(filePath);
|
|
||||||
if (contentType == null) {
|
|
||||||
contentType = "application/octet-stream";
|
|
||||||
}
|
|
||||||
return contentType;
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean isPreviewSupported(String mimeType) {
|
|
||||||
if (mimeType == null) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return mimeType.startsWith("image/") ||
|
|
||||||
mimeType.startsWith("text/") ||
|
|
||||||
mimeType.equals("application/pdf") ||
|
|
||||||
mimeType.startsWith("video/") ||
|
|
||||||
mimeType.startsWith("audio/");
|
|
||||||
}
|
|
||||||
|
|
||||||
private Long getUserIdFromToken(String tokenHeader) {
|
|
||||||
String token = tokenHeader.replace("Bearer ", "");
|
|
||||||
AuthToken authToken = authTokenRepository.findByToken(token)
|
|
||||||
.orElseThrow(() -> new NotFoundAuthToken("Token not found"));
|
|
||||||
return authToken.getUser().getId();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -4,14 +4,9 @@ import lombok.AllArgsConstructor;
|
|||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
import lombok.NoArgsConstructor;
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
@Data
|
@Data
|
||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
@NoArgsConstructor
|
@NoArgsConstructor
|
||||||
public class LogOutAnswer {
|
public class LogOutAnswer {
|
||||||
private String Token;
|
private String email;
|
||||||
|
|
||||||
private List<Map<String, String>> fieldErrors;
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package ru.soune.nocopy.dto;
|
||||||
|
|
||||||
|
import jakarta.validation.constraints.Email;
|
||||||
|
import jakarta.validation.constraints.NotBlank;
|
||||||
|
import jakarta.validation.constraints.Size;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@AllArgsConstructor
|
||||||
|
@NoArgsConstructor
|
||||||
|
public class LogoutRequest {
|
||||||
|
@NotBlank(message = "error.not.blank") @Email(message = "error.not.email") @Size(max = 128)
|
||||||
|
private String email;
|
||||||
|
|
||||||
|
@NotBlank(message = "error.not.blank")
|
||||||
|
private String token;
|
||||||
|
}
|
||||||
@@ -14,6 +14,8 @@ public enum MessageCode {
|
|||||||
FILE_ENTITY_ERROR(2, "File entity error"),
|
FILE_ENTITY_ERROR(2, "File entity error"),
|
||||||
ACCESS_DENIED(2, "Access denied"),
|
ACCESS_DENIED(2, "Access denied"),
|
||||||
AUTH_EMAIL_NOT_FOUND(4, "Email not found"),
|
AUTH_EMAIL_NOT_FOUND(4, "Email not found"),
|
||||||
|
AUTH_EMAIL_OR_TOKEN_NOT_FOUND(4, "Email or Token not found "),
|
||||||
|
AUTH_TOKEN_MISMATCH(4, "Token mismatch"),
|
||||||
FILE_NOT_FOUND(4, "File not found"),
|
FILE_NOT_FOUND(4, "File not found"),
|
||||||
AUTH_PASSWORD_NOT_MATCHES(2, "Password does not match");
|
AUTH_PASSWORD_NOT_MATCHES(2, "Password does not match");
|
||||||
|
|
||||||
|
|||||||
@@ -68,7 +68,7 @@ public class FileEntityHandler implements RequestHandler {
|
|||||||
private BaseResponse handleGetFileInfo(BaseRequest request, FileEntityRequest fileRequest) {
|
private BaseResponse handleGetFileInfo(BaseRequest request, FileEntityRequest fileRequest) {
|
||||||
try {
|
try {
|
||||||
Long userId = getUserIdFromToken(fileRequest.getToken());
|
Long userId = getUserIdFromToken(fileRequest.getToken());
|
||||||
FileEntityResponse fileInfo = fileEntityService.getById(fileRequest.getFileId());
|
FileEntityResponse fileInfo = fileEntityService.getById(fileRequest.getFileId(), request.getVersion());
|
||||||
|
|
||||||
if (!fileInfo.getUserId().equals(userId)) {
|
if (!fileInfo.getUserId().equals(userId)) {
|
||||||
return new BaseResponse(request.getMsgId(),
|
return new BaseResponse(request.getMsgId(),
|
||||||
@@ -99,7 +99,8 @@ public class FileEntityHandler implements RequestHandler {
|
|||||||
private BaseResponse handleGetFileBySession(BaseRequest request, FileEntityRequest fileRequest) {
|
private BaseResponse handleGetFileBySession(BaseRequest request, FileEntityRequest fileRequest) {
|
||||||
try {
|
try {
|
||||||
Long userId = getUserIdFromToken(fileRequest.getToken());
|
Long userId = getUserIdFromToken(fileRequest.getToken());
|
||||||
FileEntityResponse fileInfo = fileEntityService.getByUploadSessionId(fileRequest.getUploadSessionId());
|
FileEntityResponse fileInfo = fileEntityService.getByUploadSessionId(fileRequest.getUploadSessionId(),
|
||||||
|
request.getVersion());
|
||||||
|
|
||||||
if (!fileInfo.getUserId().equals(userId)) {
|
if (!fileInfo.getUserId().equals(userId)) {
|
||||||
return new BaseResponse(request.getMsgId(),
|
return new BaseResponse(request.getMsgId(),
|
||||||
@@ -133,7 +134,7 @@ public class FileEntityHandler implements RequestHandler {
|
|||||||
int page = fileRequest.getPage() != null ? fileRequest.getPage() : 1;
|
int page = fileRequest.getPage() != null ? fileRequest.getPage() : 1;
|
||||||
int pageSize = fileRequest.getPageSize() != null ? fileRequest.getPageSize() : 20;
|
int pageSize = fileRequest.getPageSize() != null ? fileRequest.getPageSize() : 20;
|
||||||
|
|
||||||
FileResponse files = fileEntityService.getUserFiles(userId, page, pageSize);
|
FileResponse files = fileEntityService.getUserFiles(userId, page, pageSize, request.getVersion());
|
||||||
|
|
||||||
return new BaseResponse(request.getMsgId(),
|
return new BaseResponse(request.getMsgId(),
|
||||||
MessageCode.SUCCESS.getCode(),
|
MessageCode.SUCCESS.getCode(),
|
||||||
@@ -164,7 +165,7 @@ public class FileEntityHandler implements RequestHandler {
|
|||||||
return handleGetUserFiles(request, fileRequest);
|
return handleGetUserFiles(request, fileRequest);
|
||||||
}
|
}
|
||||||
|
|
||||||
FileResponse allFiles = fileEntityService.getUserFiles(userId, 1, 1000);
|
FileResponse allFiles = fileEntityService.getUserFiles(userId, 1, 1000, request.getVersion());
|
||||||
|
|
||||||
var filteredFiles = allFiles.getFiles().stream()
|
var filteredFiles = allFiles.getFiles().stream()
|
||||||
.filter(f -> f.getOriginalFileName().toLowerCase().contains(fileRequest.getQuery().toLowerCase()))
|
.filter(f -> f.getOriginalFileName().toLowerCase().contains(fileRequest.getQuery().toLowerCase()))
|
||||||
@@ -234,7 +235,7 @@ public class FileEntityHandler implements RequestHandler {
|
|||||||
private BaseResponse handleDeleteFile(BaseRequest request, FileEntityRequest fileRequest) {
|
private BaseResponse handleDeleteFile(BaseRequest request, FileEntityRequest fileRequest) {
|
||||||
try {
|
try {
|
||||||
Long userId = getUserIdFromToken(fileRequest.getToken());
|
Long userId = getUserIdFromToken(fileRequest.getToken());
|
||||||
FileEntityResponse fileInfo = fileEntityService.getById(fileRequest.getFileId());
|
FileEntityResponse fileInfo = fileEntityService.getById(fileRequest.getFileId(), request.getVersion());
|
||||||
|
|
||||||
if (!fileInfo.getUserId().equals(userId)) {
|
if (!fileInfo.getUserId().equals(userId)) {
|
||||||
return new BaseResponse(request.getMsgId(),
|
return new BaseResponse(request.getMsgId(),
|
||||||
|
|||||||
@@ -0,0 +1,56 @@
|
|||||||
|
package ru.soune.nocopy.handler;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import ru.soune.nocopy.dto.*;
|
||||||
|
import ru.soune.nocopy.entity.AuthToken;
|
||||||
|
import ru.soune.nocopy.entity.User;
|
||||||
|
import ru.soune.nocopy.exception.NotValidFieldException;
|
||||||
|
import ru.soune.nocopy.repository.AuthTokenRepository;
|
||||||
|
import ru.soune.nocopy.repository.UserRepository;
|
||||||
|
import ru.soune.nocopy.service.AuthService;
|
||||||
|
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class LogoutRequestHandler implements RequestHandler {
|
||||||
|
|
||||||
|
private final AuthService authService;
|
||||||
|
|
||||||
|
private final AuthTokenRepository authTokenRepository;
|
||||||
|
|
||||||
|
private final ObjectMapper objectMapper;
|
||||||
|
|
||||||
|
private final UserRepository userRepository;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public BaseResponse handle(BaseRequest request) {
|
||||||
|
LogoutRequest logoutRequest = objectMapper.convertValue(request.getMessageBody(), LogoutRequest.class);
|
||||||
|
|
||||||
|
Optional<AuthToken> opToken = authTokenRepository.findByToken(logoutRequest.getToken());
|
||||||
|
Optional<User> user = userRepository.findByEmail(logoutRequest.getEmail());
|
||||||
|
|
||||||
|
if (opToken.isEmpty() || user.isEmpty()) {
|
||||||
|
throw new NotValidFieldException("User with email or token not found",
|
||||||
|
new BaseResponse(request.getMsgId(), MessageCode.AUTH_EMAIL_OR_TOKEN_NOT_FOUND.getCode(),
|
||||||
|
MessageCode.AUTH_EMAIL_OR_TOKEN_NOT_FOUND.getDescription(),
|
||||||
|
new LogoutRequest(logoutRequest.getEmail(), logoutRequest.getToken())));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!Objects.equals(opToken.get().getUser().getId(), user.get().getId())) {
|
||||||
|
throw new NotValidFieldException("User token mismatch with user",
|
||||||
|
new BaseResponse(request.getMsgId(), MessageCode.AUTH_TOKEN_MISMATCH.getCode(),
|
||||||
|
MessageCode.AUTH_TOKEN_MISMATCH.getDescription(),
|
||||||
|
new LogoutRequest(logoutRequest.getEmail(), logoutRequest.getToken())));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
authService.logout(logoutRequest.getToken());
|
||||||
|
|
||||||
|
return new BaseResponse(request.getMsgId(), MessageCode.SUCCESS.getCode(), MessageCode.SUCCESS.getDescription(),
|
||||||
|
new LogOutAnswer(logoutRequest.getEmail()));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -55,12 +55,5 @@ public class FileUploadRequestValidator implements Validator {
|
|||||||
errors.rejectValue("extension", "extension.required", "Extension is required");
|
errors.rejectValue("extension", "extension.required", "Extension is required");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!extension.startsWith(".")) {
|
|
||||||
errors.rejectValue("extension", "extension.invalid.format",
|
|
||||||
"Extension must start with '.'");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
|
||||||
@@ -79,38 +79,38 @@ public class FileEntityService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
@Transactional(readOnly = true)
|
||||||
public FileEntityResponse getById(String fileId) {
|
public FileEntityResponse getById(String fileId, int version) {
|
||||||
FileEntity fileEntity = fileEntityRepository.findById(fileId)
|
FileEntity fileEntity = fileEntityRepository.findById(fileId)
|
||||||
.orElseThrow(() -> new FileEntityNotFoundException(fileId));
|
.orElseThrow(() -> new FileEntityNotFoundException(fileId));
|
||||||
|
|
||||||
return convertToResponse(fileEntity);
|
return convertToResponse(fileEntity, version);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
@Transactional(readOnly = true)
|
||||||
public FileEntityResponse getByUploadSessionId(String uploadSessionId) {
|
public FileEntityResponse getByUploadSessionId(String uploadSessionId, int version) {
|
||||||
FileEntity fileEntity = fileEntityRepository.findByUploadSessionId(uploadSessionId)
|
FileEntity fileEntity = fileEntityRepository.findByUploadSessionId(uploadSessionId)
|
||||||
.orElseThrow(() -> new FileEntityNotFoundException(
|
.orElseThrow(() -> new FileEntityNotFoundException(
|
||||||
"Not found for upload session: " + uploadSessionId));
|
"Not found for upload session: " + uploadSessionId));
|
||||||
|
|
||||||
return convertToResponse(fileEntity);
|
return convertToResponse(fileEntity, version);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
@Transactional(readOnly = true)
|
||||||
public FileEntityResponse getByFilePath(String filePath) {
|
public FileEntityResponse getByFilePath(String filePath, int version) {
|
||||||
FileEntity fileEntity = fileEntityRepository.findByFilePath(filePath)
|
FileEntity fileEntity = fileEntityRepository.findByFilePath(filePath)
|
||||||
.orElseThrow(() -> new FileEntityNotFoundException("Path: " + filePath));
|
.orElseThrow(() -> new FileEntityNotFoundException("Path: " + filePath));
|
||||||
|
|
||||||
return convertToResponse(fileEntity);
|
return convertToResponse(fileEntity, version);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
@Transactional(readOnly = true)
|
||||||
public FileResponse getAllUserFiles(Long userId) {
|
public FileResponse getAllUserFiles(Long userId, int version) {
|
||||||
List<FileEntity> fileEntities = fileEntityRepository.findByUserIdAndStatus(
|
List<FileEntity> fileEntities = fileEntityRepository.findByUserIdAndStatus(
|
||||||
userId, FileStatus.ACTIVE);
|
userId, FileStatus.ACTIVE);
|
||||||
|
|
||||||
List<FileEntityResponse> files = fileEntities.stream()
|
List<FileEntityResponse> files = fileEntities.stream()
|
||||||
.map(this::convertToResponse)
|
.map(file -> convertToResponse(file, version))
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
long totalSize = fileEntities.stream()
|
long totalSize = fileEntities.stream()
|
||||||
@@ -129,7 +129,7 @@ public class FileEntityService {
|
|||||||
|
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
@Transactional(readOnly = true)
|
||||||
public FileResponse getUserFiles(Long userId, int page, int pageSize) {
|
public FileResponse getUserFiles(Long userId, int page, int pageSize, int version) {
|
||||||
List<FileEntity> allFiles = fileEntityRepository.findByUserIdAndStatus(
|
List<FileEntity> allFiles = fileEntityRepository.findByUserIdAndStatus(
|
||||||
userId, FileStatus.ACTIVE);
|
userId, FileStatus.ACTIVE);
|
||||||
|
|
||||||
@@ -150,7 +150,7 @@ public class FileEntityService {
|
|||||||
List<FileEntity> pageFiles = allFiles.subList(start, end);
|
List<FileEntity> pageFiles = allFiles.subList(start, end);
|
||||||
|
|
||||||
List<FileEntityResponse> files = pageFiles.stream()
|
List<FileEntityResponse> files = pageFiles.stream()
|
||||||
.map(this::convertToResponse)
|
.map(file -> convertToResponse(file, version))
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
long totalSize = allFiles.stream()
|
long totalSize = allFiles.stream()
|
||||||
@@ -185,16 +185,6 @@ public class FileEntityService {
|
|||||||
return totalSize != null ? totalSize : 0L;
|
return totalSize != null ? totalSize : 0L;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public List<FileEntityResponse> searchFiles(Long userId, String query) {
|
|
||||||
List<FileEntity> files = fileEntityRepository.searchByFileName(userId, query);
|
|
||||||
|
|
||||||
return files.stream()
|
|
||||||
.filter(f -> f.getStatus() == FileStatus.ACTIVE)
|
|
||||||
.map(this::convertToResponse)
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean checkFileExistsOnDisk(String filePath) {
|
private boolean checkFileExistsOnDisk(String filePath) {
|
||||||
try {
|
try {
|
||||||
return Files.exists(Paths.get(filePath));
|
return Files.exists(Paths.get(filePath));
|
||||||
@@ -204,7 +194,7 @@ public class FileEntityService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private FileEntityResponse convertToResponse(FileEntity fileEntity) {
|
private FileEntityResponse convertToResponse(FileEntity fileEntity, int version) {
|
||||||
boolean existsOnDisk = checkFileExistsOnDisk(fileEntity.getFilePath());
|
boolean existsOnDisk = checkFileExistsOnDisk(fileEntity.getFilePath());
|
||||||
|
|
||||||
return FileEntityResponse.builder()
|
return FileEntityResponse.builder()
|
||||||
@@ -222,7 +212,7 @@ public class FileEntityService {
|
|||||||
.createdAt(fileEntity.getCreatedAt())
|
.createdAt(fileEntity.getCreatedAt())
|
||||||
.updatedAt(fileEntity.getUpdatedAt())
|
.updatedAt(fileEntity.getUpdatedAt())
|
||||||
.formattedSize(formatFileSize(fileEntity.getFileSize()))
|
.formattedSize(formatFileSize(fileEntity.getFileSize()))
|
||||||
.downloadUrl("/api/files/download/" + fileEntity.getId())
|
.downloadUrl("/api/v" + version + "/files/download/" + fileEntity.getId())
|
||||||
.existsOnDisk(existsOnDisk)
|
.existsOnDisk(existsOnDisk)
|
||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user