PlaybackService.java

package server.restful.common.playback;

import jakarta.servlet.http.Part;
import libsidplay.sidtune.CompanionFiles;
import libsidplay.sidtune.SidTune;
import libsidplay.sidtune.SidTuneError;
import server.restful.common.parameter.requestpath.FileRequestPathServletParameters;
import ui.assembly64.Assembly64Client;
import ui.entities.config.Configuration;

import java.io.*;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import static libsidutils.ZipFileUtils.newFileInputStream;
import static server.restful.common.JSIDPlay2Servlet.OBJECT_MAPPER;
import static server.restful.common.IServletSystemProperties.UploadServlet.UPLOADSERVLET_MAX_REQUEST_SIZE;

/**
 * One resolver and portable bundle format for browser playback, conversion and downloads.
 */
public final class PlaybackService {
    public static final String STEREO = "stereo";
    public static final String CARTRIDGE = "cartridge";
    public static final String MANIFEST = "launch.json";

    private final Configuration configuration;
    private final Properties directories;
    private final boolean admin;

    public PlaybackService(Configuration configuration, Properties directories, boolean admin) {
        this.configuration = configuration;
        this.directories = directories;
        this.admin = admin;
    }

    public PlaybackLaunch discover(PlaybackLaunch.Resource primary) throws IOException, URISyntaxException {
        PlaybackLaunch launch = new PlaybackLaunch();
        launch.primary = primary;
        validate(launch);
        requireAccess(launch);
        if (CompanionFiles.isMus(primary.path)) {
            File file = fetch(primary);
            File[] siblings = file.getParentFile().listFiles();
            String companion = CompanionFiles.findStereoCompanion(file.getName(), siblings == null ? new String[0]
                    : Arrays.stream(siblings).filter(File::isFile).map(File::getName).toArray(String[]::new));
            if (companion != null) {
                String path = primary.path.substring(0, primary.path.lastIndexOf('/') + 1) + companion;
                PlaybackLaunch.Resource other = new PlaybackLaunch.Resource(path, primary.itemId, primary.categoryId, primary.serverId);
                if (CompanionFiles.isSecondary(primary.path, companion)) {
                    launch.primary = other;
                    other = primary;
                }
                launch.companions.add(new PlaybackLaunch.Companion(STEREO, other));
            }
        }
        return launch;
    }

    public File fetch(PlaybackLaunch.Resource resource) throws IOException, URISyntaxException {
        if (resource == null || resource.path == null || resource.upload != null) {
            throw new IllegalArgumentException("Missing playback resource");
        }
        FileRequestPathServletParameters parameters = new FileRequestPathServletParameters();
        parameters.setFilePath(resource.path.startsWith("/") ? resource.path : "/" + resource.path);
        parameters.setItemId(resource.itemId);
        parameters.setCategoryId(resource.categoryId);
        parameters.setServerId(resource.serverId);
        File file = parameters.resolveFile(configuration, directories, admin);
        if (file == null || !file.isFile()) throw new FileNotFoundException(resource.path);
        return file;
    }

    public SidTune tune(PlaybackLaunch launch, File primary) throws Exception {
        PlaybackLaunch.Resource stereo = launch.companion(STEREO);
        if (CompanionFiles.isMus(primary.getName())) {
            return SidTune.load(primary.getName(), contents(primary), stereo == null ? null : basename(stereo.path),
                    stereo == null ? null : contents(fetch(stereo)));
        }
        if (stereo != null) throw new SidTuneError("Stereo companion requires MUS/STR content");
        return SidTune.load(primary);
    }

    public static byte[] contents(File file) throws IOException {
        try (InputStream input = newFileInputStream(file)) {
            return input.readAllBytes();
        }
    }

    public static void validate(PlaybackLaunch launch) {
        if (launch == null || launch.version != 1 || launch.primary == null || launch.companions == null
                || launch.settings == null || launch.companions.size() > 2) {
            throw new IllegalArgumentException("Unsupported playback launch");
        }
        Set<String> roles = new HashSet<>();
        for (PlaybackLaunch.Companion companion : launch.companions) {
            if (companion == null || companion.role == null || !Set.of(STEREO, CARTRIDGE).contains(companion.role)
                    || !roles.add(companion.role) || companion.resource == null || companion.resource.path == null) {
                throw new IllegalArgumentException("Invalid or duplicate companion role");
            }
            if (CARTRIDGE.equals(companion.role)) {
                String path = companion.resource.path.toLowerCase(Locale.ROOT);
                if (!path.endsWith(".crt") && !path.endsWith(".reu")) {
                    throw new IllegalArgumentException("Cartridge companion must be a CRT or REU image");
                }
            }
        }
        for (PlaybackLaunch.Resource resource : launch.resources()) {
            if (resource == null || resource.path == null || resource.path.isBlank() || basename(resource.path).isBlank()
                    || Set.of(".", "..").contains(basename(resource.path))
                    || (resource.itemId == null) != (resource.categoryId == null)
                    || resource.serverId != null && resource.itemId == null) {
                throw new IllegalArgumentException("Invalid playback resource");
            }
        }
        PlaybackLaunch.Resource stereo = launch.companion(STEREO);
        if (stereo != null && CompanionFiles.findStereoCompanion(basename(launch.primary.path),
                new String[]{basename(stereo.path)}) == null) {
            throw new IllegalArgumentException("Stereo companion filename does not match the primary");
        }
        Set<String> selectors = Set.of("share", "itemId", "categoryId", "serverId", "playUrl", "download", "help", "devtools");
        for (var setting : launch.settings.entrySet()) {
            if (!setting.getKey().matches("[a-zA-Z][a-zA-Z0-9]*") || selectors.contains(setting.getKey())
                    || setting.getValue() == null) throw new IllegalArgumentException("Invalid playback setting");
        }
    }

    /**
     * Apply saved scalar settings through the existing bean setters before parsing explicit URL overrides.
     */
    public static void applySettings(PlaybackLaunch launch, Object... targets) throws IOException {
        for (Object target : targets) {
            var properties = OBJECT_MAPPER.valueToTree(target);
            Map<String, String> updates = new LinkedHashMap<>();
            launch.settings.forEach((key, value) -> {
                if (properties.has(key) && !properties.get(key).isContainerNode()) updates.put(key, value);
            });
            OBJECT_MAPPER.readerForUpdating(target).readValue(OBJECT_MAPPER.writeValueAsBytes(updates));
        }
    }

    public Path sharesRoot() throws IOException {
        Path root = Path.of(configuration.getSidplay2Section().getTmpDir().getPath()).resolve("playback-shares");
        Files.createDirectories(root);
        return root;
    }

    public PlaybackLaunch read(String id) throws IOException {
        // A share ID is never a user-controlled filesystem path.
        UUID.fromString(id);
        PlaybackLaunch launch = OBJECT_MAPPER.readValue(sharesRoot().resolve(id).resolve(MANIFEST).toFile(), PlaybackLaunch.class);
        validate(launch);
        requireAccess(launch);
        return launch;
    }

    private void requireAccess(PlaybackLaunch launch) throws IOException {
        for (PlaybackLaunch.Resource resource : launch.resources()) {
            if (resource.itemId != null && resource.categoryId != null) {
                Assembly64Client.requireAccess(resource.serverId, admin);
            }
        }
    }

    public PlaybackLaunch save(PlaybackLaunch launch, Map<String, Part> uploads) throws Exception {
        validate(launch);
        String id = UUID.randomUUID().toString();
        Path dir = sharesRoot().resolve(id);
        Files.createDirectory(dir);
        try {
            int index = 0;
            for (PlaybackLaunch.Resource resource : launch.resources()) {
                if (resource.upload != null) {
                    Part part = uploads.get(resource.upload);
                    if (part == null) throw new FileNotFoundException("Missing upload: " + resource.upload);
                    Path destination = dir.resolve(Integer.toString(index++)).resolve(basename(resource.path));
                    Files.createDirectories(destination.getParent());
                    try (InputStream input = part.getInputStream()) {
                        Files.copy(input, destination);
                    }
                    resource.path = destination.toString();
                    resource.itemId = resource.categoryId = resource.upload = null;
                    resource.serverId = null;
                }
                fetch(resource); // Fail before publishing an incomplete share.
            }
            launch.id = id;
            OBJECT_MAPPER.writeValue(dir.resolve(MANIFEST).toFile(), launch);
            return launch;
        } catch (Exception e) {
            deleteTree(dir);
            throw e;
        }
    }

    public void bundle(PlaybackLaunch launch, OutputStream output) throws Exception {
        validate(launch);
        PlaybackLaunch portable = OBJECT_MAPPER.readValue(OBJECT_MAPPER.writeValueAsBytes(launch), PlaybackLaunch.class);
        portable.id = null;
        List<PlaybackLaunch.Resource> source = launch.resources(), target = portable.resources();
        List<File> files = new ArrayList<>();
        for (PlaybackLaunch.Resource resource : source) files.add(fetch(resource));
        try (ZipOutputStream zip = new ZipOutputStream(output)) {
            for (int i = 0; i < source.size(); i++) {
                String path = (i == 0 ? "primary/" : "companions/" + launch.companions.get(i - 1).role + "/")
                        + basename(source.get(i).path);
                zip.putNextEntry(new ZipEntry(path));
                try (InputStream input = newFileInputStream(files.get(i))) {
                    input.transferTo(zip);
                }
                zip.closeEntry();
                target.get(i).path = path;
                target.get(i).itemId = target.get(i).categoryId = target.get(i).upload = null;
                target.get(i).serverId = null;
            }
            zip.putNextEntry(new ZipEntry(MANIFEST));
            zip.write(OBJECT_MAPPER.writeValueAsBytes(portable));
            zip.closeEntry();
        }
    }

    public PlaybackLaunch importBundle(InputStream input) throws Exception {
        String id = UUID.randomUUID().toString();
        Path dir = sharesRoot().resolve(id);
        Files.createDirectory(dir);
        try {
            long total = 0;
            int entries = 0;
            try (ZipInputStream zip = new ZipInputStream(input)) {
                ZipEntry entry;
                byte[] buffer = new byte[8192];
                while ((entry = zip.getNextEntry()) != null) {
                    if (++entries > 32) throw new IOException("Too many bundle entries");
                    Path destination = bundlePath(dir, entry.getName());
                    if (entry.isDirectory()) continue;
                    Files.createDirectories(destination.getParent());
                    try (OutputStream out = Files.newOutputStream(destination)) {
                        int length;
                        while ((length = zip.read(buffer)) != -1) {
                            total += length;
                            if (total > UPLOADSERVLET_MAX_REQUEST_SIZE) throw new IOException("Bundle is too large");
                            out.write(buffer, 0, length);
                        }
                    }
                }
            }
            PlaybackLaunch launch = OBJECT_MAPPER.readValue(dir.resolve(MANIFEST).toFile(), PlaybackLaunch.class);
            validate(launch);
            for (PlaybackLaunch.Resource resource : launch.resources()) {
                if (resource.itemId != null || resource.upload != null)
                    throw new IOException("Bundle resources must be local");
                Path path = bundlePath(dir, resource.path);
                if (!Files.isRegularFile(path)) throw new FileNotFoundException(resource.path);
                resource.path = path.toString();
            }
            launch.id = id;
            OBJECT_MAPPER.writeValue(dir.resolve(MANIFEST).toFile(), launch);
            return launch;
        } catch (Exception e) {
            deleteTree(dir);
            throw e;
        }
    }

    static Path bundlePath(Path root, String path) throws IOException {
        Path result = root.resolve(path.replace('\\', '/')).normalize();
        if (!result.startsWith(root) || result.equals(root)) throw new IOException("Invalid bundle path");
        return result;
    }

    private static void deleteTree(Path dir) throws IOException {
        try (var paths = Files.walk(dir)) {
            for (Path path : paths.sorted(Comparator.reverseOrder()).toList()) Files.deleteIfExists(path);
        }
    }

    public static String basename(String path) {
        String normalized = path.replace('\\', '/');
        return normalized.substring(normalized.lastIndexOf('/') + 1);
    }
}