package com.hotwj.platform.video.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import com.hotwj.platform.video.config.VideoUploadProperties;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.exception.ServiceException;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.MediaType;
import org.springframework.http.MediaTypeFactory;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;

/**
 * 本地 HLS 资源公开访问接口
 */
@SaIgnore
@RestController
@RequiredArgsConstructor
public class VideoHlsController {

    private final VideoUploadProperties properties;

    @GetMapping("${video.upload.public-url-prefix:/video-hls}/{fileHash}/{fileName:.+}")
    public void stream(@PathVariable String fileHash, @PathVariable String fileName, HttpServletResponse response) throws IOException {
        File file = new File(properties.getWorkDir(),
            "hls" + File.separator + fileHash + File.separator + fileName);
        if (!file.exists() || !file.isFile()) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        if (fileName.contains("..")) {
            throw new ServiceException("非法文件路径");
        }
        MediaType mediaType = MediaTypeFactory.getMediaType(file.getName()).orElse(MediaType.APPLICATION_OCTET_STREAM);
        response.setContentType(mediaType.toString());
        response.setHeader("Cache-Control", "public, max-age=60");
        FileCopyUtils.copy(new FileSystemResource(file).getInputStream(), response.getOutputStream());
    }
}
