FileRequestPathServletParametersImpl.java

package server.restful.common.parameter.requestpath.impl;

import libsidplay.sidtune.CompanionFiles;
import libsidutils.IOUtils;
import net.java.truevfs.access.TFile;
import server.restful.common.parameter.ServletParameterParser;
import server.restful.common.parameter.UsageParameter;
import ui.assembly64.ContentEntry;
import ui.assembly64.Assembly64Client;
import ui.assembly64.ContentEntrySearchResult;
import ui.common.Convenience;
import ui.entities.config.Configuration;
import ui.entities.config.SidPlay2Section;

import java.io.*;
import java.net.URISyntaxException;
import java.util.*;
import java.util.stream.Collectors;

import static libsidutils.IOUtils.ioWrap;
import static server.restful.common.JSIDPlay2Servlet.*;

public abstract class FileRequestPathServletParametersImpl extends UsageParameter {

    private static final String ASSEMBLY64_CSDB_REU_ID = "25";

    public File fetchFile(Configuration configuration, Properties directoryProperties, ServletParameterParser parser,
                          boolean hasAdminAccess) throws IOException, URISyntaxException {
        File file = resolveFile(configuration, directoryProperties, hasAdminAccess);
        if (file == null && getFilePath() != null) parser.setException(new FileNotFoundException(getFilePath()));
        return file;
    }

    /**
     * Resolve a resource independently of servlet usage/error reporting.
     */
    public File resolveFile(Configuration configuration, Properties directoryProperties, boolean hasAdminAccess)
            throws IOException, URISyntaxException {
        SidPlay2Section sidplay2Section = configuration.getSidplay2Section();

        String path = getFilePath();
        if (path == null) {
            return null;
        }
        if (getItemId() != null && getCategoryId() != null) {
            File file = fetchAssembly64File(configuration, getServerId(), getItemId(), getCategoryId(), path.substring(1), hasAdminAccess);
            if (file != null && file.exists()) {
                return file;
            }
        } else if (sidplay2Section.getHvsc() != null && path.startsWith(C64_MUSIC)) {
            File file = IOUtils.getFile(path.substring(C64_MUSIC.length()), sidplay2Section.getHvsc(), null);
            if (file.exists() && file.getAbsolutePath().startsWith(sidplay2Section.getHvsc().getAbsolutePath())) {
                return file;
            }
        } else if (sidplay2Section.getCgsc() != null && path.startsWith(CGSC)) {
            File file = IOUtils.getFile(path.substring(CGSC.length()), null, sidplay2Section.getCgsc());
            if (file.exists() && file.getAbsolutePath().startsWith(sidplay2Section.getCgsc().getAbsolutePath())) {
                return file;
            }
        } else if (new File(path).getAbsolutePath().startsWith(sidplay2Section.getTmpDir().getAbsolutePath())) {
            File file = new File(path);
            if (file.exists()) {
                return file;
            }
        } else {
            for (String directoryLogicalName : directoryProperties.stringPropertyNames()) {
                String[] splitted = directoryProperties.getProperty(directoryLogicalName).split(",");
                String directoryValue = splitted.length > 0 ? splitted[0] : null;
                boolean needToBeAdmin = splitted.length > 1 && Boolean.parseBoolean(splitted[1]);
                if ((!needToBeAdmin || hasAdminAccess) && path.startsWith(directoryLogicalName)
                        && directoryValue != null) {
                    TFile root = new TFile(directoryValue);
                    File file = IOUtils.getFile(path.substring(directoryLogicalName.length()), root, null);
                    if (file.exists() && file.getAbsolutePath().startsWith(root.getAbsolutePath())) {
                        return file;
                    }
                }
            }
        }
        return null;
    }

    public boolean isREU() {
        return (getServerId() == null || getServerId() == ui.assembly64.HomeServer.CONFIGURED_SERVER)
                && ASSEMBLY64_CSDB_REU_ID.equals(getCategoryId());
    }

    public static File fetchAssembly64File(Configuration configuration, String itemId, String categoryId, String fileId)
            throws IOException, URISyntaxException {
        return fetchAssembly64File(configuration, null, itemId, categoryId, fileId);
    }

    public static File fetchAssembly64File(Configuration configuration, Integer serverId, String itemId,
                                           String categoryId, String fileId) throws IOException, URISyntaxException {
        return fetchAssembly64File(configuration, serverId, itemId, categoryId, fileId, false);
    }

    public static File fetchAssembly64File(Configuration configuration, Integer serverId, String itemId,
                                           String categoryId, String fileId, boolean hasAdminAccess) throws IOException, URISyntaxException {
        Assembly64Client client = new Assembly64Client(configuration, serverId, hasAdminAccess);
        ContentEntrySearchResult contentEntries = client.entries(itemId, categoryId);

        File targetDir = new File(configuration.getSidplay2Section().getTmpDir(), UUID.randomUUID().toString());
        ioWrap(targetDir::mkdir);

        File file = new File(fileId);
        boolean mustFetchAttachments = VIDEO_TUNE_FILE_FILTER.accept(file) || DISK_FILE_FILTER.accept(file)
                || TAPE_FILE_FILTER.accept(file) || CART_FILE_FILTER.accept(file);

        String stereo = CompanionFiles.findStereoCompanion(fileId,
                contentEntries.getContentEntry().stream().map(ContentEntry::getPath).toArray(String[]::new));

        List<ContentEntry> contentEntriesToFetch = contentEntries.getContentEntry().stream()
                .filter(e -> e.getPath() != null && !e.getPath().startsWith(Convenience.MACOSX))
                .filter(contentEntry -> Objects.equals(contentEntry.getPath(), fileId) || Objects.equals(contentEntry.getPath(), stereo)
                        || (mustFetchAttachments && (DISK_FILE_FILTER.accept(new File(contentEntry.getPath()))
                        || TAPE_FILE_FILTER.accept(new File(contentEntry.getPath()))
                        || CART_FILE_FILTER.accept(new File(contentEntry.getPath())))))
                .collect(Collectors.toList());

        File result = null;
        for (ContentEntry contentEntry : contentEntriesToFetch) {

            File contentEntryFile = new File(targetDir, contentEntry.getPath());
            if (!contentEntryFile.toPath().normalize().startsWith(targetDir.toPath())) {
                throw new IOException("Invalid Assembly64 content path: " + contentEntry.getPath());
            }
            // create a file as a directory to handle subdirectories (subdir/file.txt)
            //noinspection ResultOfMethodCallIgnored
            contentEntryFile.getParentFile().mkdirs();

            try (InputStream input = client.download(itemId, categoryId, contentEntry);
                 OutputStream output = new FileOutputStream(contentEntryFile)) {
                IOUtils.copy(input, output);
            }

            if (Objects.equals(contentEntry.getPath(), fileId)) {
                result = contentEntryFile;
            }
        }
        return result;
    }

    public static void fetchAssembly64File(Configuration configuration, String itemId, String categoryId, String fileId,
                                           File contentEntryFile) throws IOException, URISyntaxException {
        Assembly64Client client = new Assembly64Client(configuration, (Integer) null);
        ContentEntry entry = client.entries(itemId, categoryId).getContentEntry().stream()
                .filter(e -> Objects.equals(fileId, e.getPath())).findFirst()
                .orElseThrow(() -> new FileNotFoundException(fileId));
        try (InputStream input = client.download(itemId, categoryId, entry);
             OutputStream outputStream = new FileOutputStream(contentEntryFile)) {
            IOUtils.copy(input, outputStream);
        }
    }

    public Integer getServerId() {
        return null;
    }

    public abstract String getFilePath();

    public abstract String getItemId();

    public abstract String getCategoryId();
}