Compare commits
16
Commits
f3aa6324c2
...
NCBACK-26
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
19d8f61e1d | ||
|
|
8fe4d854a6 | ||
|
|
4c607f5bf9 | ||
|
|
ce879fea18 | ||
|
|
33479ea9af | ||
|
|
76e8f4ab1d | ||
|
|
c03ca2566d | ||
|
|
1932784264 | ||
|
|
bd78b88f33 | ||
|
|
22c2eed8a1 | ||
|
|
f3266ee0e5 | ||
|
|
280bd91257 | ||
|
|
31b90f942c | ||
|
|
d167e92d90 | ||
|
|
651b92cb59 | ||
|
|
d34a304763 |
@@ -12,6 +12,8 @@ WORKDIR /app
|
|||||||
|
|
||||||
COPY --from=build /app/build/libs/*.jar app.jar
|
COPY --from=build /app/build/libs/*.jar app.jar
|
||||||
|
|
||||||
|
RUN mkdir -p /data/uploads && chmod 755 /data/uploads
|
||||||
|
|
||||||
EXPOSE 8080
|
EXPOSE 8080
|
||||||
|
|
||||||
CMD ["java", "-jar", "app.jar"]
|
CMD ["java", "-jar", "app.jar"]
|
||||||
|
|||||||
+13
-2
@@ -1,6 +1,16 @@
|
|||||||
version: '3.9'
|
version: '3.9'
|
||||||
|
|
||||||
services:
|
services:
|
||||||
|
storage:
|
||||||
|
image: alpine:latest
|
||||||
|
container_name: file-storage
|
||||||
|
networks:
|
||||||
|
- app-network
|
||||||
|
volumes:
|
||||||
|
- uploads_data:/storage:rw
|
||||||
|
command: tail -f /dev/null
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
db:
|
db:
|
||||||
image: postgres:17
|
image: postgres:17
|
||||||
restart: always
|
restart: always
|
||||||
@@ -30,6 +40,7 @@ services:
|
|||||||
POSTGRES_PASSWORD: postgres
|
POSTGRES_PASSWORD: postgres
|
||||||
POSTGRES_PORT: 5432
|
POSTGRES_PORT: 5432
|
||||||
POSTGRES_HOST: db
|
POSTGRES_HOST: db
|
||||||
|
STORAGE_SERVICE_URL: http://storage:8081
|
||||||
depends_on:
|
depends_on:
|
||||||
- db
|
- db
|
||||||
ports:
|
ports:
|
||||||
@@ -41,7 +52,7 @@ services:
|
|||||||
- backend
|
- backend
|
||||||
- api
|
- api
|
||||||
volumes:
|
volumes:
|
||||||
- ./uploads:/data/uploads:rw
|
- uploads_data:/data/uploads:rw
|
||||||
|
|
||||||
grafana:
|
grafana:
|
||||||
image: grafana/grafana:10.3.1
|
image: grafana/grafana:10.3.1
|
||||||
@@ -146,7 +157,7 @@ volumes:
|
|||||||
loki_chunks:
|
loki_chunks:
|
||||||
loki_index:
|
loki_index:
|
||||||
loki_rules:
|
loki_rules:
|
||||||
# uploads_volume:
|
uploads_data:
|
||||||
|
|
||||||
networks:
|
networks:
|
||||||
app-network:
|
app-network:
|
||||||
|
|||||||
@@ -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,14 +82,39 @@ 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 \\
|
||||||
|
-v /opt/uploads:/data/uploads:rw \\
|
||||||
-e POSTGRES_DB=no_copy_ \\
|
-e POSTGRES_DB=no_copy_ \\
|
||||||
-e POSTGRES_USER=postgres \\
|
-e POSTGRES_USER=postgres \\
|
||||||
-e POSTGRES_PASSWORD=postgres \\
|
-e POSTGRES_PASSWORD=postgres \\
|
||||||
@@ -87,18 +123,36 @@ 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 '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 'Deployment successful'
|
||||||
echo 'Application URL: http://${params.SERVER}:80'
|
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'
|
||||||
else
|
else
|
||||||
echo 'Application failed to start'
|
echo 'Application failed to start'
|
||||||
docker logs app-backend
|
docker logs app-backend
|
||||||
|
|||||||
@@ -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("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");
|
||||||
|
|
||||||
|
|||||||
@@ -2,20 +2,47 @@ package ru.soune.nocopy.entity.file;
|
|||||||
|
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
@Getter
|
@Getter
|
||||||
public enum FileType {
|
public enum FileType {
|
||||||
PHOTO("photo"),
|
PHOTO("photo", Arrays.asList("jpg", "jpeg", "png", "gif", "bmp")),
|
||||||
VIDEO("video"),
|
IMAGE("image", Arrays.asList("jpg", "jpeg", "png", "gif", "bmp", "svg", "tiff", "tif", "ico",
|
||||||
AUDIO("audio"),
|
"psd", "ai", "eps", "raw", "heic", "heif")),
|
||||||
DOCUMENT("document");
|
VIDEO("video", Arrays.asList("mp4", "avi", "mov", "wmv", "flv", "mkv", "webm", "m4v", "mpg", "mpeg",
|
||||||
|
"3gp", "3g2", "f4v", "m2ts", "mts", "vob", "ogv", "divx")),
|
||||||
|
AUDIO("audio", Arrays.asList("mp3", "wav", "ogg", "aac", "flac", "m4a", "wma", "aiff", "aif", "amr",
|
||||||
|
"opus", "mka", "ac3", "alac")),
|
||||||
|
DOCUMENT("document", Arrays.asList(
|
||||||
|
"pdf", "txt", "rtf",
|
||||||
|
"doc", "docx", "xls", "xlsx", "ppt", "pptx", "pps", "ppsx", "dot", "dotx", "xlt", "xltx", "pot", "potx",
|
||||||
|
"odt", "ods", "odp", "odg", "odf", "odb", "odc", "odi", "odm", "ott", "ots", "otp", "otg", "oth",
|
||||||
|
"sxw", "sxc", "sxi", "sxd", "sxg", "stc", "sti", "stw", "sxm",
|
||||||
|
"pages", "numbers", "key",
|
||||||
|
"csv", "tsv", "xml", "html", "htm", "tex", "md", "markdown",
|
||||||
|
"epub", "mobi", "azw", "azw3", "fb2",
|
||||||
|
"wps", "wpt", "et", "dps", "vsd", "vsdx",
|
||||||
|
"java", "py", "cpp", "c", "h", "js", "css", "php", "sql", "json", "yaml", "yml", "sh", "bat",
|
||||||
|
"one", "note"));
|
||||||
|
|
||||||
private final String code;
|
private final String displayName;
|
||||||
|
private final List<String> allowedExtensions;
|
||||||
|
|
||||||
FileType(String code) {
|
FileType(String displayName, List<String> allowedExtensions) {
|
||||||
this.code = code;
|
this.displayName = displayName;
|
||||||
|
this.allowedExtensions = allowedExtensions;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getCode() {
|
public String getDisplayName() {
|
||||||
return code;
|
return displayName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<String> getAllowedExtensions() {
|
||||||
|
return allowedExtensions;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean supportsExtension(String extension) {
|
||||||
|
return allowedExtensions.contains(extension.toLowerCase());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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(),
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import lombok.extern.slf4j.Slf4j;
|
|||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
import org.springframework.validation.BeanPropertyBindingResult;
|
import org.springframework.validation.BeanPropertyBindingResult;
|
||||||
import org.springframework.validation.BindingResult;
|
import org.springframework.validation.BindingResult;
|
||||||
|
import org.springframework.validation.FieldError;
|
||||||
import ru.soune.nocopy.dto.*;
|
import ru.soune.nocopy.dto.*;
|
||||||
import ru.soune.nocopy.dto.file.*;
|
import ru.soune.nocopy.dto.file.*;
|
||||||
import ru.soune.nocopy.entity.AuthToken;
|
import ru.soune.nocopy.entity.AuthToken;
|
||||||
@@ -17,10 +18,8 @@ import ru.soune.nocopy.repository.AuthTokenRepository;
|
|||||||
import ru.soune.nocopy.repository.FileUploadSessionRepository;
|
import ru.soune.nocopy.repository.FileUploadSessionRepository;
|
||||||
import ru.soune.nocopy.service.file.FileUploadService;
|
import ru.soune.nocopy.service.file.FileUploadService;
|
||||||
|
|
||||||
import java.util.Arrays;
|
import java.util.*;
|
||||||
import java.util.HashMap;
|
import java.util.stream.Collectors;
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Optional;
|
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@Component
|
@Component
|
||||||
@@ -70,18 +69,31 @@ public class FileUploadHandler implements RequestHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private BaseResponse handleInitUpload(BaseRequest request, FileUploadRequest fileRequest) {
|
private BaseResponse handleInitUpload(BaseRequest request, FileUploadRequest fileRequest) {
|
||||||
try {
|
|
||||||
String token = fileRequest.getToken();
|
String token = fileRequest.getToken();
|
||||||
|
|
||||||
Optional<AuthToken> tokenOptional = authTokenRepository.findByToken(token);
|
Optional<AuthToken> tokenOptional = authTokenRepository.findByToken(token);
|
||||||
|
|
||||||
|
if (tokenOptional.isEmpty()) {
|
||||||
|
return new BaseResponse(request.getMsgId(), MessageCode.INVALID_TOKEN.getCode(),
|
||||||
|
MessageCode.INVALID_TOKEN.getDescription(), Map.of("token", token));
|
||||||
|
}
|
||||||
|
|
||||||
AuthToken authToken = tokenOptional.orElseThrow(() -> new NotFoundAuthToken("Token not found"));
|
AuthToken authToken = tokenOptional.orElseThrow(() -> new NotFoundAuthToken("Token not found"));
|
||||||
|
|
||||||
BindingResult bindingResult = new BeanPropertyBindingResult(fileRequest, "fileRequest");
|
BindingResult bindingResult = new BeanPropertyBindingResult(fileRequest, "fileRequest");
|
||||||
fileUploadRequestValidator.validate(fileRequest, bindingResult);
|
fileUploadRequestValidator.validate(fileRequest, bindingResult);
|
||||||
|
|
||||||
if (bindingResult.hasErrors()) {
|
if (bindingResult.hasErrors()) {
|
||||||
throw new ValidationException(bindingResult, request.getMsgId());
|
Map<String, String> fieldErrors = bindingResult.getFieldErrors()
|
||||||
|
.stream()
|
||||||
|
.collect(Collectors.toMap(
|
||||||
|
FieldError::getField,
|
||||||
|
fieldError -> fieldError.getDefaultMessage() != null
|
||||||
|
? fieldError.getDefaultMessage()
|
||||||
|
: "Validation error"));
|
||||||
|
|
||||||
|
return new BaseResponse(request.getMsgId(), MessageCode.INVALID_FIELD.getCode(),
|
||||||
|
MessageCode.INVALID_FIELD.getDescription(), fieldErrors);
|
||||||
}
|
}
|
||||||
|
|
||||||
FileUploadSession session = fileUploadService.initUpload(
|
FileUploadSession session = fileUploadService.initUpload(
|
||||||
@@ -101,15 +113,6 @@ public class FileUploadHandler implements RequestHandler {
|
|||||||
|
|
||||||
return new BaseResponse(request.getMsgId(), MessageCode.SUCCESS.getCode(),
|
return new BaseResponse(request.getMsgId(), MessageCode.SUCCESS.getCode(),
|
||||||
MessageCode.SUCCESS.getDescription(), fileResponse);
|
MessageCode.SUCCESS.getDescription(), fileResponse);
|
||||||
|
|
||||||
} catch (NotFoundAuthToken e) {
|
|
||||||
InitFileResponse initFileResponse = InitFileResponse.builder()
|
|
||||||
.build();
|
|
||||||
|
|
||||||
throw new NotValidFieldException("Invalid or expired token: " + fileRequest.getToken(),
|
|
||||||
new BaseResponse(request.getMsgId(), MessageCode.INVALID_TOKEN.getCode(),
|
|
||||||
MessageCode.INVALID_TOKEN.getDescription(), initFileResponse));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private BaseResponse handleGetProgress(BaseRequest request, FileUploadRequest fileRequest) {
|
private BaseResponse handleGetProgress(BaseRequest request, FileUploadRequest fileRequest) {
|
||||||
|
|||||||
@@ -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()));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,9 +7,12 @@ import ru.soune.nocopy.dto.file.FileUploadRequest;
|
|||||||
import ru.soune.nocopy.entity.file.FileType;
|
import ru.soune.nocopy.entity.file.FileType;
|
||||||
|
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
@Component
|
@Component
|
||||||
public class FileUploadRequestValidator implements Validator {
|
public class FileUploadRequestValidator implements Validator {
|
||||||
|
private final List<FileType> supportedFileTypes = Arrays.asList(FileType.values());
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean supports(Class<?> clazz) {
|
public boolean supports(Class<?> clazz) {
|
||||||
return FileUploadRequest.class.isAssignableFrom(clazz);
|
return FileUploadRequest.class.isAssignableFrom(clazz);
|
||||||
@@ -21,7 +24,7 @@ public class FileUploadRequestValidator implements Validator {
|
|||||||
|
|
||||||
validateType(request.getFileType(), errors);
|
validateType(request.getFileType(), errors);
|
||||||
validateFileName(request.getFileName(), errors);
|
validateFileName(request.getFileName(), errors);
|
||||||
validateExtension(request.getExtension(), errors);
|
validateExtension(request.getExtension(), request.getFileType(), errors);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void validateType(String fileType, Errors errors) {
|
private void validateType(String fileType, Errors errors) {
|
||||||
@@ -31,7 +34,12 @@ public class FileUploadRequestValidator implements Validator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
FileType.valueOf(fileType.toUpperCase());
|
FileType parsedType = FileType.valueOf(fileType.toUpperCase());
|
||||||
|
|
||||||
|
if (!supportedFileTypes.contains(parsedType)) {
|
||||||
|
errors.rejectValue("fileType", "fileType.unsupported",
|
||||||
|
"Unsupported file type. Valid types: " + Arrays.toString(FileType.values()));
|
||||||
|
}
|
||||||
} catch (IllegalArgumentException e) {
|
} catch (IllegalArgumentException e) {
|
||||||
errors.rejectValue("fileType", "fileType.invalid",
|
errors.rejectValue("fileType", "fileType.invalid",
|
||||||
"Invalid file type. Valid types: " + Arrays.toString(FileType.values()));
|
"Invalid file type. Valid types: " + Arrays.toString(FileType.values()));
|
||||||
@@ -50,17 +58,34 @@ public class FileUploadRequestValidator implements Validator {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void validateExtension(String extension, Errors errors) {
|
private void validateExtension(String extension, String fileType, Errors errors) {
|
||||||
if (extension == null || extension.isBlank()) {
|
if (extension == null || extension.isBlank()) {
|
||||||
errors.rejectValue("extension", "extension.required", "Extension is required");
|
errors.rejectValue("fileType", "fileType.required", "File type is required");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!extension.startsWith(".")) {
|
if (extension.contains(".")) {
|
||||||
errors.rejectValue("extension", "extension.invalid.format",
|
errors.rejectValue("extension", "extension.required", "Extension contains comma");
|
||||||
"Extension must start with '.'");
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
FileType parsedType = FileType.valueOf(fileType.toUpperCase());
|
||||||
|
|
||||||
|
if (!parsedType.supportsExtension(extension)) {
|
||||||
|
errors.rejectValue("fileName", "fileType.extension.mismatch",
|
||||||
|
String.format("File extension '%s' does not match file type '%s'. Allowed extensions for %s: %s",
|
||||||
|
extension, parsedType.getDisplayName(), parsedType.getDisplayName(),
|
||||||
|
parsedType.getAllowedExtensions()));
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
errors.rejectValue("fileType", "fileType.invalid",
|
||||||
|
"Invalid file type. Valid types: " + Arrays.toString(FileType.values()));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private String getFileExtension(String fileName) {
|
||||||
|
return fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -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