RepositoryApiServiceImpl.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.facade.impl;

import org.genesys.blocks.security.model.AclAwareModel;
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.ReferencedRepositoryFileException;
import org.genesys.filerepository.model.RepositoryFile;
import org.genesys.filerepository.model.RepositoryFolder;
import org.genesys.filerepository.service.ImageGalleryService;
import org.genesys.filerepository.service.RepositoryService;
import org.genesys.filerepository.service.VirusFoundException;
import org.genesys.server.api.Pagination;
import org.genesys.server.api.v2.facade.RepositoryApiService;
import org.genesys.server.api.v2.mapper.MapstructMapper;
import org.genesys.server.api.v2.model.impl.RepositoryFileDTO;
import org.genesys.server.api.v2.model.impl.RepositoryFolderDTO;
import org.genesys.server.api.v2.model.impl.RepositoryImageDTO;
import org.genesys.server.exception.NotFoundElement;
import org.genesys.server.service.impl.FilesMetadataInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.UUID;
import java.util.stream.Stream;

@Service
@Transactional(readOnly = true)
public class RepositoryApiServiceImpl implements RepositoryApiService {

	@Autowired
	private RepositoryService service;
	
	@Autowired
	private ImageGalleryService imageGalleryService;

	@Autowired
	private FilesMetadataInfo filesMetadataInfo;
	
	@Autowired
	private MapstructMapper mapper;
	
	@Override
	@Transactional
	public <T extends RepositoryFileDTO> T addFile(Path repositoryPath, String originalFilename, String contentType, byte[] bytes, T metaData) throws InvalidRepositoryPathException, InvalidRepositoryFileDataException, IOException {
		return (T) mapper.map(service.addFile(repositoryPath, originalFilename, contentType, bytes, mapper.map(metaData)));
	}

	@Override
	@Transactional
	public <T extends RepositoryFileDTO> T addFile(Path repositoryPath, String originalFilename, String contentType, File fileWithData, T metaData) throws InvalidRepositoryPathException, InvalidRepositoryFileDataException, IOException {
		return (T) mapper.map(service.addFile(repositoryPath, originalFilename, contentType, fileWithData, mapper.map(metaData)));
	}

	@Override
	@Transactional
	public <T extends RepositoryFileDTO> T addFile(Path repositoryPath, String originalFilename, String contentType, InputStream inputStream, T metaData) throws InvalidRepositoryPathException, InvalidRepositoryFileDataException, IOException {
		return (T) mapper.map(service.addFile(repositoryPath, originalFilename, contentType, inputStream, mapper.map(metaData)));
	}

	@Override
	@Transactional
	public void ensureThumbnails(RepositoryImageDTO repositoryImageDTO) {
		service.ensureThumbnails(mapper.map(repositoryImageDTO));
	}

	@Override
	public <T extends RepositoryFileDTO> T getFile(UUID fileUuid) throws NoSuchRepositoryFileException {
		return (T) mapper.map((RepositoryFile) service.getFile(fileUuid));
	}

	@Override
	public <T extends RepositoryFileDTO> T getFile(UUID fileUuid, int version) throws NoSuchRepositoryFileException {
		return (T) mapper.map((RepositoryFile) service.getFile(fileUuid, version));
	}

	@Override
	public <T extends RepositoryFileDTO> T getFile(Path path, String filename) throws NoSuchRepositoryFileException, InvalidRepositoryPathException {
		return (T) mapper.map((RepositoryFile) service.getFile(path, filename));
	}

	@Override
	public byte[] getFileBytes(RepositoryFileDTO repositoryFileDTO) throws IOException {
		return service.getFileBytes(mapper.map(repositoryFileDTO));
	}

	@Override
	public void streamFileBytes(RepositoryFileDTO repositoryFileDTO, OutputStream outputStream) throws IOException {
		service.streamFileBytes(mapper.map(repositoryFileDTO), outputStream);
	}

	@Override
	public OutputStream getFolderAsZip(RepositoryFolderDTO repositoryFolderDTO, OutputStream outputStream, int maxFilesLimit) throws InvalidRepositoryPathException, IOException {
		return service.getFolderAsZip(mapper.map(repositoryFolderDTO), outputStream, maxFilesLimit);
	}

	@Override
	public OutputStream getFolderAsZip(RepositoryFolderDTO repositoryFolderDTO, OutputStream outputStream) throws InvalidRepositoryPathException, IOException {
		return service.getFolderAsZip(mapper.map(repositoryFolderDTO), outputStream);
	}

	@Override
	@Transactional
	public List<RepositoryFileDTO> extractZip(RepositoryFileDTO repositoryFileDTO) throws InvalidRepositoryFileDataException, IOException, InvalidRepositoryPathException, NoSuchRepositoryFileException {
		return mapper.map(service.extractZip(mapper.map(repositoryFileDTO)), mapper::map);
	}

	@Override
	public <T extends RepositoryFileDTO> void scanBytes(T repositoryFileDTO) throws VirusFoundException, IOException {
		service.scanBytes(mapper.map(repositoryFileDTO));
	}

	@Override
	public List<RepositoryFileDTO> getFiles(Path folderPath, Sort sort) throws InvalidRepositoryPathException {
		return mapper.map(service.getFiles(folderPath, sort), mapper::map);
	}

	@Override
	public Page<RepositoryFileDTO> listFiles(Path folderPath, Pageable page) throws InvalidRepositoryPathException {
		return mapper.map(service.listFiles(folderPath, page), mapper::map);
	}

	@Override
	public Stream<RepositoryFileDTO> streamFiles(Path root, Sort sort) throws InvalidRepositoryPathException {
		return service.streamFiles(root, sort).map(mapper::map);
	}

	@Override
	@Transactional
	public <T extends RepositoryFileDTO> T updateMetadata(T repositoryFileDTO) throws NoSuchRepositoryFileException {
		return (T) mapper.map(service.updateMetadata(mapper.map(repositoryFileDTO)));
	}

	@Override
	@Transactional
	public <T extends RepositoryFileDTO> T updateBytes(T repositoryFileDTO, String contentType, byte[] bytes) throws NoSuchRepositoryFileException, IOException {
		return (T) mapper.map(service.updateBytes(mapper.map(repositoryFileDTO), contentType, bytes));
	}

	@Override
	@Transactional
	public <T extends RepositoryFileDTO> T updateBytes(T repositoryFileDTO, String contentType, InputStream inputStream) throws NoSuchRepositoryFileException, IOException {
		return (T) mapper.map(service.updateBytes(mapper.map(repositoryFileDTO), contentType, inputStream));
	}

	@Override
	@Transactional
	public <T extends RepositoryFileDTO> T updateBytes(T repositoryFileDTO, String contentType, File fileWithBytes) throws NoSuchRepositoryFileException, IOException {
		return (T) mapper.map(service.updateBytes(mapper.map(repositoryFileDTO), contentType, fileWithBytes));
	}

	@Override
	@Transactional
	public RepositoryImageDTO updateImageBytes(RepositoryImageDTO repositoryImageDTO, String contentType, byte[] bytes) throws NoSuchRepositoryFileException, IOException {
		return mapper.map(service.updateImageBytes(mapper.map(repositoryImageDTO), contentType, bytes));
	}

	@Override
	@Transactional
	public <T extends RepositoryFileDTO> T removeFileIfPossible(T repositoryFileDTO) throws NoSuchRepositoryFileException, ReferencedRepositoryFileException, IOException {
		return (T) mapper.map(service.removeFileIfPossible(mapper.map(repositoryFileDTO)));
	}

	@Override
	@Transactional
	public <T extends RepositoryFileDTO> T removeFile(T repositoryFileDTO) throws NoSuchRepositoryFileException, IOException {
		return (T) mapper.map(service.removeFile(mapper.map(repositoryFileDTO)));
	}

	@Override
	@Transactional
	public <T extends RepositoryFileDTO> T moveFile(T repositoryFileDTO, Path target) throws NoSuchRepositoryFileException, InvalidRepositoryPathException {
		return (T) mapper.map(service.moveFile(mapper.map(repositoryFileDTO), target));
	}

	@Override
	@Transactional
	public <T extends RepositoryFileDTO> T moveAndRenameFile(T repositoryFileDTO, Path fullPath) throws InvalidRepositoryPathException, InvalidRepositoryFileDataException {
		return (T) mapper.map(service.moveAndRenameFile(mapper.map(repositoryFileDTO), fullPath));
	}

	@Override
	public List<RepositoryImageDTO> listImages(Path path, Sort sort) {
		return mapper.map(service.listImages(path, sort), mapper::map);
	}

	@Override
	public List<RepositoryFolderDTO> listPathsRecursively(Path root) throws InvalidRepositoryPathException {
		return mapper.map(service.listPathsRecursively(root), mapper::map);
	}

	@Override
	@Transactional
	public RepositoryImageDTO addImage(Path repositoryPath, String originalFilename, String contentType, byte[] bytes, RepositoryImageDTO metaData) throws InvalidRepositoryPathException, InvalidRepositoryFileDataException, IOException {
		return mapper.map(service.addImage(repositoryPath, originalFilename, contentType, bytes, mapper.map(metaData)));
	}

	@Override
	@Transactional
	public RepositoryImageDTO updateImageMetadata(RepositoryImageDTO repositoryImageDTO) throws NoSuchRepositoryFileException {
		return mapper.map(service.updateImageMetadata(mapper.map(repositoryImageDTO)));
	}

	@Override
	@Transactional
	public RepositoryImageDTO removeImage(RepositoryImageDTO repositoryImageDTO) throws NoSuchRepositoryFileException, IOException, ReferencedRepositoryFileException {
		return mapper.map(service.removeImage(mapper.map(repositoryImageDTO)));
	}

	@Override
	public RepositoryFolderDTO getFolder(UUID uuid) {
		return mapper.map(service.getFolder(uuid));
	}

	@Override
	public RepositoryFolderDTO getFolder(Path folderPath) throws InvalidRepositoryPathException {
		return mapper.map(service.getFolder(folderPath));
	}

	@Override
	@Transactional
	public RepositoryFolderDTO updateFolder(RepositoryFolderDTO folder) throws NoSuchRepositoryFolderException, InvalidRepositoryPathException {
		return mapper.map(service.updateFolder(mapper.map(folder)));
	}

	@Override
	public boolean hasPath(Path path) throws InvalidRepositoryPathException {
		return service.hasPath(path);
	}

	@Override
	@Transactional
	public RepositoryFolderDTO renamePath(Path currentPath, Path newPath) throws InvalidRepositoryPathException {
		return mapper.map(service.renamePath(currentPath, newPath));
	}

	@Override
	@Transactional
	public RepositoryFolderDTO ensureFolder(Path path) throws InvalidRepositoryPathException {
		return mapper.map(service.ensureFolder(path));
	}

	// TODO AclAwareModel aclParentObject
	@Override
	@Transactional
	public RepositoryFolderDTO ensureFolder(Path path, AclAwareModel aclParentObject) throws InvalidRepositoryPathException {
		return mapper.map(service.ensureFolder(path, aclParentObject));
	}

	@Override
	@Transactional(rollbackFor = Throwable.class)
	public RepositoryFolderDTO deleteFolder(Path path) throws FolderNotEmptyException, InvalidRepositoryPathException {
		return mapper.map(service.deleteFolder(path));
	}

	@Override
	public List<RepositoryFolderDTO> getFolders(Path root, Sort sort) throws InvalidRepositoryPathException {
		return mapper.map(service.getFolders(root, sort), mapper::map);
	}

	@Override
	public Page<RepositoryFolderDTO> listFolders(Path root, Pageable page) throws InvalidRepositoryPathException {
		return mapper.map(service.listFolders(root, page), mapper::map);
	}

	@Override
	public byte[] getThumbnail(Path path, String name, String extension, RepositoryFileDTO repositoryFileDTO) throws Exception {
		return service.getThumbnail(path, name, extension, mapper.map(repositoryFileDTO));
	}

	@Override
	@Transactional
	public FolderDetails renameFolder(final UUID folderUuid, String fullPath) throws InvalidRepositoryPathException {
		RepositoryFolder folder = service.getFolder(folderUuid);
		if (folder == null) {
			throw new NotFoundElement("No folder with uuid=" + folderUuid);
		}
		return folderDetails(Paths.get(renamePath(folder.getFolderPath(), Paths.get(fullPath)).getPath()));
	}

	/**
	 * Folder details.
	 *
	 * @param path the path
	 * @return the folder details
	 * @throws InvalidRepositoryPathException the invalid repository path exception
	 */
	@Transactional
	@Override
	public FolderDetails folderDetails(final Path path) throws InvalidRepositoryPathException {
		FolderDetails fd = new FolderDetails();
		fd.folder = getFolder(path);
		fd.subFolders = listFolders(path, Pagination.toPageRequest(50, RepositoryFolder.DEFAULT_SORT));
		if (fd.folder == null && !path.toAbsolutePath().toString().equals("/")) {
			throw new NotFoundElement("No such folder");
		}
		fd.files = listFiles(path, Pagination.toPageRequest(50, RepositoryFile.DEFAULT_SORT));
		fd.gallery = mapper.map(imageGalleryService.loadImageGallery(path));
		return fd;
	}

	@Override
	public void downloadFolderMetadata(HttpServletRequest request, HttpServletResponse response, String controllerUrl)
			throws NotFoundElement, IOException, InvalidRepositoryPathException {
		final String folderPath = ((String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)).substring((controllerUrl + "/download/folder-metadata").length());
		final RepositoryFolderDTO folder = getFolder(Paths.get(folderPath));
		if (folder == null) {
			throw new NotFoundElement("No folder with path=" + folderPath);
		}
		response.setContentType("text/csv;charset=UTF-8");
		response.setHeader("Content-Disposition", "attachment; filename=" + folder.getName() + "_files_metadata.csv ");

		Stream<RepositoryFile> files = service.streamFiles(Paths.get(folder.getPath()), RepositoryFile.DEFAULT_SORT);
		filesMetadataInfo.downloadMetadata(files, response, '\t', '"', '\\', "\n", "UTF-8");
	}
}