56 lines
2.0 KiB
Java

package com.magamochi.content.service.strategy;
import com.magamochi.content.model.dto.MangaContentArchiveDTO;
import com.magamochi.content.model.entity.MangaContentImage;
import com.magamochi.content.model.enumeration.ContentArchiveFileType;
import com.magamochi.image.service.ImageService;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.stereotype.Component;
@Log4j2
@Component
@RequiredArgsConstructor
public class CbzArchiveStrategy implements ContentArchiveStrategy {
private final ImageService imageService;
@Override
public boolean supports(ContentArchiveFileType contentArchiveFileType) {
return ContentArchiveFileType.CBZ.equals(contentArchiveFileType);
}
@Override
public MangaContentArchiveDTO createArchive(String title, List<MangaContentImage> chapterImages)
throws IOException {
var byteArrayOutputStream = new ByteArrayOutputStream();
var bufferedOutputStream = new BufferedOutputStream(byteArrayOutputStream);
var zipOutputStream = new ZipOutputStream(bufferedOutputStream);
var totalPages = chapterImages.size();
var paddingLength = String.valueOf(totalPages).length();
for (var pageNumber = 1; pageNumber <= totalPages; pageNumber++) {
var imgSrc = chapterImages.get(pageNumber - 1);
var paddedFileName = String.format("%0" + paddingLength + "d.jpg", imgSrc.getPosition());
zipOutputStream.putNextEntry(new ZipEntry(paddedFileName));
IOUtils.copy(imageService.getStream(imgSrc.getImage()), zipOutputStream);
zipOutputStream.closeEntry();
}
zipOutputStream.finish();
zipOutputStream.flush();
IOUtils.closeQuietly(zipOutputStream);
return new MangaContentArchiveDTO(title + ".cbz", byteArrayOutputStream.toByteArray());
}
}