RepositoryController.java

/*
 * Copyright 2024 Global Crop Diversity Trust
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.genesys.server.api.v2.impl;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

import org.genesys.filerepository.FolderNotEmptyException;
import org.genesys.filerepository.InvalidRepositoryFileDataException;
import org.genesys.filerepository.InvalidRepositoryPathException;
import org.genesys.filerepository.NoSuchRepositoryFileException;
import org.genesys.filerepository.NoSuchRepositoryFolderException;
import org.genesys.filerepository.model.ImageGallery;
import org.genesys.server.api.ApiBaseController;
import org.genesys.server.api.Pagination;
import org.genesys.server.api.v2.facade.ImageGalleryApiService;
import org.genesys.server.api.v2.facade.RepositoryApiService;
import org.genesys.server.api.v2.model.impl.ImageGalleryDTO;
import org.genesys.server.api.v2.model.impl.RepositoryFileDTO;
import org.genesys.server.api.v2.model.impl.RepositoryFolderDTO;
import org.genesys.server.exception.NotFoundElement;
import org.genesys.server.service.impl.FilesMetadataUpdate;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController("repositoryApi2")
@RequestMapping(RepositoryController.CONTROLLER_URL)
@PreAuthorize("isAuthenticated()")
@Tag(name = "Repository")
public class RepositoryController extends ApiBaseController {

	/** The Constant CONTROLLER_URL. */
	public static final String CONTROLLER_URL = ApiBaseController.APIv2_BASE + "/repository";

	/** The repository service. */
	@Autowired
	protected RepositoryApiService repositoryService;

	@Autowired
	private ImageGalleryApiService imagegalleryService;

	@Autowired
	private FilesMetadataUpdate filesMetadataUpdate;

	/**
	 * Gets the file.
	 *
	 * @param fileUuid the file uuid
	 * @return the file
	 * @throws NoSuchRepositoryFileException the no such repository file exception
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	@GetMapping(value = "/file/{fileUuid}")
	public RepositoryFileDTO getFile(@PathVariable("fileUuid") final UUID fileUuid) throws NoSuchRepositoryFileException, IOException {
		return repositoryService.getFile(fileUuid);
	}

	/**
	 * Update file.
	 *
	 * @param metadata the metadata
	 * @return the repository file
	 * @throws NoSuchRepositoryFileException the no such repository file exception
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	@PutMapping(value = "/file")
	public RepositoryFileDTO updateFile(@RequestBody final RepositoryFileDTO metadata) throws NoSuchRepositoryFileException {
		return repositoryService.updateMetadata(metadata);
	}

	/**
	 * Removes the file.
	 *
	 * @param fileUuid the file uuid
	 * @return the repository file
	 * @throws NoSuchRepositoryFileException the no such repository file exception
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	@DeleteMapping(value = "/file/{fileUuid}")
	public RepositoryFileDTO removeFile(@PathVariable("fileUuid") final UUID fileUuid) throws NoSuchRepositoryFileException, IOException {
		return repositoryService.removeFile(repositoryService.getFile(fileUuid));
	}

	/**
	 * Upload file to specified folder.
	 *
	 * @param file the file
	 * @param request the request
	 * @return repository file metadata
	 * @throws InvalidRepositoryPathException the invalid repository path exception
	 * @throws InvalidRepositoryFileDataException the invalid repository file data
	 * exception
	 * @throws IOException Signals that an I/O exception has occurred.
	 * @throws NotFoundElement the not found element
	 */
	@PostMapping(value = "/upload/**")
	public RepositoryFileDTO uploadFile(@RequestPart(name = "file", required = true) final MultipartFile file,
		@RequestPart(name = "metadata", required = false) final RepositoryFileDTO metadata,
		final HttpServletRequest request) throws InvalidRepositoryPathException, InvalidRepositoryFileDataException, IOException {

		final String folderPath = ((String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)).substring((CONTROLLER_URL + "/upload").length());
		Path repositoryPath = Paths.get(folderPath);
		LOG.info("Upload file {} to path {}", file.getOriginalFilename(), repositoryPath);
		return repositoryService.addFile(repositoryPath, file.getOriginalFilename(), file.getContentType(), file.getInputStream(), metadata);
	}

	/**
	 * Upload folder metadata file.
	 *
	 * @param file the file
	 * @return map of error messages by file uuid
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	@PostMapping(value = "/upload/folder-metadata/**")
	public Map<String, String> uploadFolderMetadata(@RequestPart(name = "file", required = true) final MultipartFile file) throws IOException {

		var result = filesMetadataUpdate.updateFromCsv(file.getInputStream(), '\t', '"', '\\');
		return result;
	}

	/**
	 * Download file metadata of specified folder.
	 *
	 * @param request the request
	 * @param response the response
	 * @throws NotFoundElement the no such repository folder
	 * @throws IOException Signals that an I/O exception has occurred.
	 * @throws InvalidRepositoryPathException the invalid repository path exception
	 */
	@GetMapping(value = "/download/folder-metadata/**")
	public void downloadFolderMetadata(final HttpServletRequest request, final HttpServletResponse response) throws NotFoundElement, IOException, InvalidRepositoryPathException {
		repositoryService.downloadFolderMetadata(request, response, CONTROLLER_URL);
	}

	/**
	 * Download file.
	 *
	 * @param fileUuid the file uuid
	 * @param response the response
	 * @throws NoSuchRepositoryFileException the no such repository file exception
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	@GetMapping(value = "/download/{fileUuid:\\w{8}\\-\\w{4}.+}")
	public void downloadFile(@PathVariable("fileUuid") final UUID fileUuid, final HttpServletRequest request, final HttpServletResponse response) throws NoSuchRepositoryFileException, IOException {
		final RepositoryFileDTO repositoryFile = repositoryService.getFile(fileUuid);
		String eTag = repositoryFile.getSha1Sum();

		if (eTag.equals(request.getHeader(HttpHeaders.IF_NONE_MATCH))) {
			response.setStatus(HttpStatus.NOT_MODIFIED.value());
			response.flushBuffer();
			return;
		}

		long sinceDate = request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE);
		if (sinceDate >= -1 && repositoryFile.getLastModifiedDate().toEpochMilli() < sinceDate) {
			response.setStatus(HttpStatus.NOT_MODIFIED.value());
			response.flushBuffer();
			return;
		}

		final byte[] data = repositoryService.getFileBytes(repositoryFile);
		if (data != null) {
			response.setHeader(HttpHeaders.CACHE_CONTROL, "max-age=86400, s-maxage=86400, public, no-transform");
			response.setHeader(HttpHeaders.PRAGMA, "");
			response.setDateHeader(HttpHeaders.LAST_MODIFIED, repositoryFile.getLastModifiedDate().toEpochMilli());
			response.setHeader(HttpHeaders.ETAG, eTag);
			response.setContentType(repositoryFile.getContentType());
			response.addHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", repositoryFile.getOriginalFilename()));

			response.setContentLength(data.length);
			response.getOutputStream().write(data);
		} else {
			throw new NoSuchRepositoryFileException("Bytes not available");
		}

		response.flushBuffer();
	}

	/**
	 * Extract zip in repository folder.
	 *
	 * @param fileUuid the repository zip file uuid
	 * @throws IOException error in writing to repository
	 * @throws NoSuchRepositoryFileException the repository file doesn't exist
	 * @throws InvalidRepositoryPathException error in creating sub repository folders
	 * @throws InvalidRepositoryFileDataException if the target repositoryFile doesn't have a zip extension.
	 * @return the list of created repository files from zip
	 */
	@GetMapping(value = "/file/extract/{fileUuid:\\w{8}\\-\\w{4}.+}")
	public List<RepositoryFileDTO> extractZip(@PathVariable("fileUuid") final UUID fileUuid)
		throws NoSuchRepositoryFileException, IOException, InvalidRepositoryPathException, InvalidRepositoryFileDataException {

		final RepositoryFileDTO repositoryFile = repositoryService.getFile(fileUuid);
		return repositoryService.extractZip(repositoryFile);
	}

	/**
	 * Move specified file to the specified full file path (folder + new
	 * originalFilename).
	 *
	 * @param fileUuid file UUID
	 * @param fullPath full folder path + new orignalFilename
	 * @return the repository file
	 * @throws InvalidRepositoryPathException the invalid repository path exception
	 * @throws InvalidRepositoryFileDataException the invalid repository file data
	 * exception
	 * @throws NoSuchRepositoryFileException the no such repository file exception
	 */
	@PostMapping(value = "/file/{fileUuid}/move", consumes = MediaType.TEXT_PLAIN_VALUE)
	public RepositoryFileDTO moveAndRenameFile(@PathVariable("fileUuid") final UUID fileUuid, @RequestBody(required = true) String fullPath) throws InvalidRepositoryPathException,
		InvalidRepositoryFileDataException, NoSuchRepositoryFileException {
		return repositoryService.moveAndRenameFile(repositoryService.getFile(fileUuid), Paths.get(fullPath));
	}

	/**
	 * Rename folder.
	 *
	 * @param folderUuid the folder uuid
	 * @param fullPath the full path
	 * @return the folder details
	 * @throws InvalidRepositoryPathException the invalid repository path exception
	 */
	@PostMapping(value = "/folder/{folderUuid}/rename", consumes = MediaType.APPLICATION_JSON_VALUE)
	public RepositoryApiService.FolderDetails renameFolder(@PathVariable("folderUuid") final UUID folderUuid, @RequestBody(required = true) String fullPath) throws InvalidRepositoryPathException {
		return repositoryService.renameFolder(folderUuid, fullPath);
	}

	/**
	 * Update folder title and description
	 *
	 * @return the folder
	 * @throws InvalidRepositoryPathException the invalid repository path exception
	 * @throws NoSuchRepositoryFolderException
	 */
	@PutMapping("/folder")
	@Operation(operationId = "updateFolder", summary = "Update folder title and description")
	public RepositoryApiService.FolderDetails updateFolder(@RequestBody(required = true) RepositoryFolderDTO folder) throws InvalidRepositoryPathException, NoSuchRepositoryFolderException {
		folder = repositoryService.updateFolder(folder);
		return repositoryService.folderDetails(Paths.get(folder.getPath()));
	}

	/**
	 * Create or load folder at specified path
	 *
	 * @param request the request
	 * @return the repository folder
	 * @throws InvalidRepositoryPathException the invalid repository path exception
	 */
	@PutMapping("/folder/**")
	@Operation(operationId = "ensureFolder", summary = "Create or load folder at specified path")
	public RepositoryFolderDTO ensureFolder(final HttpServletRequest request) throws InvalidRepositoryPathException {
		final String folderPath = ((String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)).substring((CONTROLLER_URL + "/folder").length());
		RepositoryFolderDTO folder = repositoryService.ensureFolder(Paths.get(folderPath));
		return folder;
	}

	/**
	 * Gets folder details at specified path.
	 *
	 * @param request the request
	 * @return the folder
	 * @throws InvalidRepositoryPathException the invalid repository path exception
	 */
	@GetMapping("/folder/**")
	@Operation(operationId = "getFolder", summary = "Get folder details by folder path")
	public RepositoryApiService.FolderDetails getFolder(final HttpServletRequest request) throws InvalidRepositoryPathException {
		final String folderPath = ((String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)).substring((CONTROLLER_URL + "/folder").length());
		return repositoryService.folderDetails(Paths.get(folderPath));
	}

	/**
	 * Gets the folder subfolders.
	 *
	 * @param request the request
	 * @param page the page
	 * @return the folder subfolders
	 * @throws InvalidRepositoryPathException the invalid repository path exception
	 */
	@GetMapping(value = "/folder/**", params = { "folders" })
	@Operation(operationId = "getSubfolders", summary = "List subfolders of folder path")
	public Page<RepositoryFolderDTO> getFolderSubfolders(final HttpServletRequest request, @ParameterObject final Pagination page) throws InvalidRepositoryPathException {
		final String folderPath = ((String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)).substring((CONTROLLER_URL + "/folder").length());
		return repositoryService.listFolders(Paths.get(folderPath), page.toPageRequest(MAX_PAGE_SIZE, DEFAULT_PAGE_SIZE));
	}

	/**
	 * Gets the folder files.
	 *
	 * @param request the request
	 * @param page the page
	 * @return the folder files
	 * @throws InvalidRepositoryPathException the invalid repository path exception
	 */
	@GetMapping(value = "/folder/**", params = { "files" })
	@Operation(operationId = "getSubfolders", summary = "List subfolders of folder path")
	public Page<RepositoryFileDTO> getFolderFiles(final HttpServletRequest request, @ParameterObject final Pagination page) throws InvalidRepositoryPathException {
		final String folderPath = ((String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)).substring((CONTROLLER_URL + "/folder").length());
		return repositoryService.listFiles(Paths.get(folderPath), page.toPageRequest(MAX_PAGE_SIZE, DEFAULT_PAGE_SIZE));
	}

	/**
	 * Gets folder details at specified path.
	 *
	 * @param request the request
	 * @return the deleted folder
	 * @throws InvalidRepositoryPathException the invalid repository path exception
	 * @throws FolderNotEmptyException
	 */
	@DeleteMapping("/folder/**")
	@Operation(operationId = "deleteFolder", summary = "Delete folder")
	public RepositoryFolderDTO deleteFolder(final HttpServletRequest request) throws InvalidRepositoryPathException, FolderNotEmptyException {
		final String folderPath = ((String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)).substring((CONTROLLER_URL + "/folder").length());
		Path path = Paths.get(folderPath);
		RepositoryFolderDTO folder = repositoryService.getFolder(path);
		repositoryService.deleteFolder(path);
		return folder;
	}

	/**
	 * Get image gallery.
	 *
	 * @param request the request
	 * @return the gallery
	 * @throws InvalidRepositoryPathException the invalid repository path exception
	 */
	@GetMapping("/gallery/**")
	public ImageGalleryDTO getGallery(final HttpServletRequest request) throws InvalidRepositoryPathException {
		final String folderPath = ((String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)).substring((CONTROLLER_URL + "/gallery").length());
		ImageGalleryDTO imageGallery = imagegalleryService.loadImageGallery(Paths.get(folderPath));
		return imageGallery;
	}

	/**
	 * Creates the gallery.
	 *
	 * @param request the request
	 * @return the image gallery
	 * @throws InvalidRepositoryPathException the invalid repository path exception
	 */
	@PostMapping("/gallery/**")
	public ImageGalleryDTO createGallery(final HttpServletRequest request, @RequestBody ImageGallery metadata) throws InvalidRepositoryPathException {
		final String folderPath = ((String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)).substring((CONTROLLER_URL + "/gallery").length());
		ImageGalleryDTO imageGallery = imagegalleryService.createImageGallery(Paths.get(folderPath), metadata.getTitle(), metadata.getDescription());

		return imageGallery;
	}

	/**
	 * Update gallery information
	 *
	 * @param imageGallery the image gallery
	 * @return the image gallery
	 * @throws InvalidRepositoryPathException the invalid repository path exception
	 */
	@PutMapping("/gallery")
	public ImageGalleryDTO updateGallery(@RequestBody ImageGalleryDTO imageGallery) throws InvalidRepositoryPathException {
		return imagegalleryService.updateImageGalery(imageGallery, imageGallery.getTitle(), imageGallery.getDescription());
	}

	/**
	 * Creates the gallery.
	 *
	 * @param request the request
	 * @return the image gallery
	 * @throws InvalidRepositoryPathException the invalid repository path exception
	 */
	@DeleteMapping("/gallery/**")
	public ImageGalleryDTO removeGallery(final HttpServletRequest request) throws InvalidRepositoryPathException {
		final String folderPath = ((String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)).substring((CONTROLLER_URL + "/gallery").length());
		ImageGalleryDTO imageGallery = imagegalleryService.loadImageGallery(Paths.get(folderPath));
		imagegalleryService.removeGallery(imageGallery);
		return imageGallery;
	}


}