RepositoryController.java

/*
 * Copyright 2019 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.gringlobal.api.v1.impl;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;
import org.genesys.blocks.model.JsonViews;
import org.genesys.filerepository.FolderNotEmptyException;
import org.genesys.filerepository.InvalidRepositoryFileDataException;
import org.genesys.filerepository.InvalidRepositoryPathException;
import org.genesys.filerepository.NoSuchRepositoryFileException;
import org.genesys.filerepository.model.ImageGallery;
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.gringlobal.api.exception.NotFoundElement;
import org.gringlobal.api.v1.ApiBaseController;
import org.gringlobal.api.v1.Pagination;
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.RequestMethod;
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 com.fasterxml.jackson.annotation.JsonView;

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


/**
 * @author Maxym Borodenko
 */
@RestController("repositoryApi1")
@RequestMapping(RepositoryController.CONTROLLER_URL)
@PreAuthorize("isAuthenticated()")
@Tag(name = "Repository")
@Slf4j
public class RepositoryController extends ApiBaseController {

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

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

	@Autowired
	private ImageGalleryService imagegalleryService;

//	@Autowired
//	private FilesMetadataUpdate filesMetadataUpdate;
//
//	@Autowired
//	private FilesMetadataInfo filesMetadataInfo;

	/**
	 * Gets the file.
	 *
	 * @param fileUuid the file uuid
	 * @return the file
	 * @throws NoSuchRepositoryFileException the no such repository file exception
	 */
	@GetMapping(value = "/file/{fileUuid}")
	public RepositoryFile getFile(@PathVariable("fileUuid") final UUID fileUuid) throws NoSuchRepositoryFileException {
		return repositoryService.getFile(fileUuid);
	}

//	/**
//	 * 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 {
//		final String folderPath = ((String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)).substring((CONTROLLER_URL + "/download/folder-metadata").length());
//		final RepositoryFolder folder = repositoryService.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 = repositoryService.streamFiles(Paths.get(folder.getPath()), RepositoryFile.DEFAULT_SORT);
//		filesMetadataInfo.downloadMetadata(files, response, '\t', '"', '\\', "\n", "UTF-8");
//	}

	/**
	 * 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.
	 */
	@RequestMapping(value = "/download/{fileUuid:\\w{8}\\-\\w{4}.+}", method = { RequestMethod.GET, RequestMethod.POST })
	public void downloadFile(@PathVariable("fileUuid") final UUID fileUuid, final HttpServletRequest request, final HttpServletResponse response) throws NoSuchRepositoryFileException, IOException {
		final RepositoryFile 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().getEpochSecond() < sinceDate) {
			response.setStatus(HttpStatus.NOT_MODIFIED.value());
			response.flushBuffer();
			return;
		}
		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().getEpochSecond());
		response.setHeader(HttpHeaders.ETAG, eTag);
		response.setContentType(repositoryFile.getContentType());
		response.addHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", repositoryFile.getOriginalFilename()));

		response.setContentLength(repositoryFile.getSize());
		repositoryService.streamFileBytes(repositoryFile, response.getOutputStream());
		response.flushBuffer();
	}

	/**
	 * Download folder as zip.
	 *
	 * @param folderUuid the folder uuid
	 * @throws IOException error in reading from repository or writing to zip
	 * @throws InvalidRepositoryPathException the invalid repository path of folder
	 */
	@RequestMapping(value = "/folder/download/{folderUuid:\\w{8}\\-\\w{4}.+}", method = { RequestMethod.GET, RequestMethod.POST })
	public void downloadFolderAsZip(@PathVariable("folderUuid") final UUID folderUuid, final HttpServletResponse response) throws IOException, InvalidRepositoryPathException {
		final RepositoryFolder repositoryFolder = repositoryService.getFolder(folderUuid);

		response.setContentType("application/zip");
		response.addHeader("Content-Disposition", String.format("attachment; filename=\"%s.zip\"", repositoryFolder.getName()));

		repositoryService.getFolderAsZip(repositoryFolder, response.getOutputStream());

		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<RepositoryFile> extractZip(@PathVariable("fileUuid") final UUID fileUuid)
		throws NoSuchRepositoryFileException, IOException, InvalidRepositoryPathException, InvalidRepositoryFileDataException {

		final RepositoryFile 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", produces = { MediaType.APPLICATION_JSON_VALUE })
	public RepositoryFile moveAndRenameFile(@PathVariable("fileUuid") final UUID fileUuid, @RequestBody final String fullPath)
			throws NoSuchRepositoryFileException, InvalidRepositoryPathException, InvalidRepositoryFileDataException {
		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", produces = { MediaType.APPLICATION_JSON_VALUE })
	@JsonView(JsonViews.Protected.class)
	public FolderDetails renameFolder(@PathVariable("folderUuid") final UUID folderUuid, @RequestBody final String fullPath) throws InvalidRepositoryPathException {
		RepositoryFolder folder = repositoryService.getFolder(folderUuid);
		if (folder == null) {
			throw new NotFoundElement("No folder with uuid=" + folderUuid);
		}
		return folderDetails(repositoryService.renamePath(folder.getFolderPath(), Paths.get(fullPath)).getFolderPath());
	}

	/**
	 * 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")
	@JsonView(JsonViews.Protected.class)
	public 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 folderDetails(Paths.get(folderPath));
	}

	/**
	 * Gets the folder subfolders.
	 *
	 * @param request the request
	 * @param page the page
	 * @return the folder sub-folders
	 * @throws InvalidRepositoryPathException the invalid repository path exception
	 */
	@GetMapping(value = "/folder/**", params = { "folders" })
	@Operation(operationId = "getSubfolders", summary = "List sub-folders of folder path")
	@JsonView(JsonViews.Protected.class)
	public Page<RepositoryFolder> getFolderSubfolders(final HttpServletRequest request, 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 sub-folders of folder path")
	@JsonView(JsonViews.Protected.class)
	public Page<RepositoryFile> getFolderFiles(final HttpServletRequest request, 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));
	}

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

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

	/**
	 * Update folder title and description
	 *
	 * @param folders the list of folders
	 * @return list of operation responses
	 */
	@PutMapping("/folder")
	@Operation(operationId = "updateFolder", summary = "Update folder title and description")
	@JsonView(JsonViews.Protected.class)
	public List<OpResponse<FolderDetails>> updateFolders(@RequestBody final List<RepositoryFolder> folders) {
		return folders.stream().map(folder -> {
			try {
				folder = repositoryService.updateFolder(folder);
				return new OpResponse<>(folderDetails(folder.getFolderPath()));
			} catch (Throwable e) {
				return new OpResponse<FolderDetails>(e, folder);
			}
		}).collect(Collectors.toList());
	}

	/**
	 * Remove folder by 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")
	@JsonView(JsonViews.Protected.class)
	public RepositoryFolder deleteFolder(final HttpServletRequest request)
			throws InvalidRepositoryPathException, FolderNotEmptyException {

		final String folderPath = ((String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)).substring((CONTROLLER_URL + "/folder").length());
		RepositoryFolder folder = repositoryService.getFolder(Paths.get(folderPath));
		repositoryService.deleteFolder(Paths.get(folderPath));
		return folder;
	}

	/**
	 * Remove folders by UUIDs.
	 *
	 * @param uuids the list of files uuids
	 * @return list of operation responses
	 */
	@PostMapping(value = "/folder/remove")
	@JsonView(JsonViews.Protected.class)
	public List<OpResponse<RepositoryFolder>> deleteFolders(@RequestBody final List<UUID> uuids) {
		return uuids.stream().map(folderUUID -> {
			try {
				RepositoryFolder folder = repositoryService.getFolder(folderUUID);
				return new OpResponse<>(repositoryService.deleteFolder(folder.getFolderPath()));
			} catch (Throwable e) {
				return new OpResponse<RepositoryFolder>(e, folderUUID);
			}
		}).collect(Collectors.toList());
	}

	/**
	 * 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 RepositoryFile uploadFile(@RequestPart(name = "file", required = true) final MultipartFile file,
			@RequestPart(name = "metadata", required = false) final RepositoryFile metadata, final HttpServletRequest request)
			throws IOException, InvalidRepositoryPathException, InvalidRepositoryFileDataException {

		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);
	}

	/**
	 * Update files.
	 *
	 * @param metadataList the metadata
	 * @return list of operation responses
	 */
	@PutMapping(value = "/file")
	public List<OpResponse<RepositoryFile>> updateFiles(@RequestBody final List<RepositoryFile> metadataList) {
		return metadataList.stream().map(metadata -> {
			try {
				return new OpResponse<>(repositoryService.updateMetadata(metadata));
			} catch (Throwable e) {
				return new OpResponse<RepositoryFile>(e, metadata);
			}
		}).collect(Collectors.toList());
	}

	/**
	 * Removes files.
	 *
	 * @param uuids the list of files uuids
	 * @return list of operation responses
	 */
	@PostMapping(value = "/file/remove")
	public List<OpResponse<RepositoryFile>> removeFile(@RequestBody final List<UUID> uuids) {
		return uuids.stream().map(fileUuid -> {
			try {
				RepositoryFile removedFile = repositoryService.removeFile(repositoryService.getFile(fileUuid));
				return new OpResponse<>(removedFile);
			} catch (Throwable e) {
				return new OpResponse<RepositoryFile>(e, fileUuid);
			}
		}).collect(Collectors.toList());
	}

	/**
	 * Creates the gallery.
	 *
	 * @param request the request
	 * @return the image gallery
	 * @throws InvalidRepositoryPathException the invalid repository path exception
	 */
	@PostMapping("/gallery/**")
	@JsonView(JsonViews.Root.class)
	public ImageGallery 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());
		return imagegalleryService.createImageGallery(Paths.get(folderPath), metadata.getTitle(), metadata.getDescription());
	}

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

//	/**
//	 * Upload folder metadata file.
//	 *
//	 * @param file the file
//	 * @param request the request
//	 * @return repository files by specified folder path
//	 * @throws IOException Signals that an I/O exception has occurred.
//	 * @throws InvalidRepositoryPathException the invalid repository path exception
//	 */
//	@PostMapping(value = "/upload/folder-metadata/**")
//	public Page<RepositoryFile> uploadFolderMetadata(@RequestPart(name = "file", required = true) final MultipartFile file,
//			final HttpServletRequest request) throws InvalidRepositoryPathException, IOException {
//
//		final String folderPath = ((String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)).substring((CONTROLLER_URL + "/upload/folder-metadata").length());
//		filesMetadataUpdate.updateFromCsv(file.getInputStream(), '\t', '"', '\\');
//		return repositoryService.listFiles(Paths.get(folderPath), Pagination.toPageRequest(50, RepositoryFile.DEFAULT_SORT));
//	}

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

	/**
	 * The Class FolderDetails.
	 */
	public static class FolderDetails {

		/** The folder itself (may be null for /). */
		public RepositoryFolder folder;

		/** Subfolders */
		public Page<RepositoryFolder> subFolders;

		/** The files. */
		public Page<RepositoryFile> files;

		/** The gallery. */
		public ImageGallery gallery;

	}

}