fix(streaming): rewrite file streaming with NIO and HTTP caching (#512)
* fix(streaming): rewrite file streaming with NIO and HTTP caching * fix(streaming): improve file transfer handling and enhance client disconnect detection * fix(streaming): improve If-None-Match header evaluation for improved caching * fix(streaming): improve chapter tracking and loading in audiobook player * fix(streaming): remove unused imports in audiobook player component * fix(streaming): improve chapter tracking and state management in audiobook player (again) * fix: fix merge conflict errors and update code
This commit is contained in:
@@ -3,21 +3,40 @@ package org.booklore.service;
|
|||||||
import jakarta.servlet.http.HttpServletRequest;
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
import jakarta.servlet.http.HttpServletResponse;
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.booklore.exception.ApiError;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.web.context.request.async.AsyncRequestNotUsableException;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.OutputStream;
|
import java.io.OutputStream;
|
||||||
import java.io.RandomAccessFile;
|
|
||||||
import java.net.SocketTimeoutException;
|
import java.net.SocketTimeoutException;
|
||||||
|
import java.nio.channels.Channels;
|
||||||
|
import java.nio.channels.FileChannel;
|
||||||
|
import java.nio.channels.WritableByteChannel;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.NoSuchFileException;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.StandardOpenOption;
|
||||||
|
import java.nio.file.attribute.BasicFileAttributes;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.time.ZoneId;
|
||||||
|
import java.time.format.DateTimeFormatter;
|
||||||
|
import java.time.format.DateTimeParseException;
|
||||||
|
import java.util.Locale;
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@Service
|
@Service
|
||||||
public class FileStreamingService {
|
public class FileStreamingService {
|
||||||
|
|
||||||
private static final int BUFFER_SIZE = 64 * 1024;
|
private static final DateTimeFormatter HTTP_DATE_FORMAT = DateTimeFormatter
|
||||||
|
.ofPattern("EEE, dd MMM yyyy HH:mm:ss z", Locale.US)
|
||||||
|
.withZone(ZoneId.of("GMT"));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Streams a file with HTTP Range support for seeking.
|
||||||
|
* Uses Java NIO FileChannel for zero-copy transfer (sendfile) where supported.
|
||||||
|
* Supports conditional requests via ETag / If-None-Match and If-Range (RFC 7233).
|
||||||
|
*/
|
||||||
public void streamWithRangeSupport(
|
public void streamWithRangeSupport(
|
||||||
Path filePath,
|
Path filePath,
|
||||||
String contentType,
|
String contentType,
|
||||||
@@ -25,46 +44,63 @@ public class FileStreamingService {
|
|||||||
HttpServletResponse response
|
HttpServletResponse response
|
||||||
) throws IOException {
|
) throws IOException {
|
||||||
|
|
||||||
if (!Files.exists(filePath)) {
|
// Single syscall: existence check + size + last-modified
|
||||||
response.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found");
|
BasicFileAttributes attrs;
|
||||||
|
try {
|
||||||
|
attrs = Files.readAttributes(filePath, BasicFileAttributes.class);
|
||||||
|
} catch (NoSuchFileException _) {
|
||||||
|
throw ApiError.FILE_NOT_FOUND.createException(filePath.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
long fileSize = attrs.size();
|
||||||
|
Instant lastModified = attrs.lastModifiedTime().toInstant();
|
||||||
|
String etag = generateETag(fileSize, lastModified);
|
||||||
|
String rangeHeader = request.getHeader("Range");
|
||||||
|
|
||||||
|
// Standard headers for media streaming
|
||||||
|
response.setHeader("Accept-Ranges", "bytes");
|
||||||
|
response.setContentType(contentType);
|
||||||
|
response.setHeader("ETag", etag);
|
||||||
|
response.setDateHeader("Last-Modified", lastModified.toEpochMilli());
|
||||||
|
// Allow caching with mandatory revalidation via ETag eliminates
|
||||||
|
// redundant byte transfers on seeks while keeping access-control checks.
|
||||||
|
response.setHeader("Cache-Control", "no-cache");
|
||||||
|
response.setHeader("Content-Disposition", "inline");
|
||||||
|
|
||||||
|
// Conditional: If-None-Match, 304
|
||||||
|
String ifNoneMatch = request.getHeader("If-None-Match");
|
||||||
|
if (evaluateIfNoneMatch(ifNoneMatch, etag)) {
|
||||||
|
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
long fileSize = Files.size(filePath);
|
// HEAD request 200 with Content-Length, no body
|
||||||
String rangeHeader = request.getHeader("Range");
|
|
||||||
|
|
||||||
response.setHeader("Accept-Ranges", "bytes");
|
|
||||||
response.setHeader("Cache-Control", "no-store");
|
|
||||||
response.setHeader("Content-Disposition", "inline");
|
|
||||||
response.setContentType(contentType);
|
|
||||||
|
|
||||||
// -------------------------
|
|
||||||
// HEAD
|
|
||||||
// -------------------------
|
|
||||||
if ("HEAD".equalsIgnoreCase(request.getMethod())) {
|
if ("HEAD".equalsIgnoreCase(request.getMethod())) {
|
||||||
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
|
response.setStatus(HttpServletResponse.SC_OK);
|
||||||
response.setHeader(
|
|
||||||
"Content-Range",
|
|
||||||
"bytes 0-" + (fileSize - 1) + "/" + fileSize
|
|
||||||
);
|
|
||||||
response.setContentLengthLong(fileSize);
|
response.setContentLengthLong(fileSize);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try (var fileChannel = FileChannel.open(filePath, StandardOpenOption.READ)) {
|
||||||
// -------------------------
|
|
||||||
// NO RANGE
|
String ifRange = request.getHeader("If-Range");
|
||||||
// -------------------------
|
if (rangeHeader != null && ifRange != null && !validateIfRange(ifRange, etag, lastModified)) {
|
||||||
if (rangeHeader == null) {
|
// If-Range failed: return full file
|
||||||
response.setStatus(HttpServletResponse.SC_OK);
|
response.setStatus(HttpServletResponse.SC_OK);
|
||||||
response.setContentLengthLong(fileSize);
|
response.setContentLengthLong(fileSize);
|
||||||
streamBytes(filePath, 0, fileSize - 1, response.getOutputStream());
|
transferFile(fileChannel, 0, fileSize, response.getOutputStream());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// NO RANGE
|
||||||
|
if (rangeHeader == null) {
|
||||||
|
response.setStatus(HttpServletResponse.SC_OK);
|
||||||
|
response.setContentLengthLong(fileSize);
|
||||||
|
transferFile(fileChannel, 0, fileSize, response.getOutputStream());
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// -------------------------
|
|
||||||
// RANGE
|
// RANGE
|
||||||
// -------------------------
|
|
||||||
Range range = parseRange(rangeHeader, fileSize);
|
Range range = parseRange(rangeHeader, fileSize);
|
||||||
if (range == null) {
|
if (range == null) {
|
||||||
response.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
|
response.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
|
||||||
@@ -73,28 +109,124 @@ public class FileStreamingService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
long length = range.end - range.start + 1;
|
long length = range.end - range.start + 1;
|
||||||
|
|
||||||
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
|
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
|
||||||
response.setHeader(
|
response.setHeader("Content-Range", "bytes " + range.start + "-" + range.end + "/" + fileSize);
|
||||||
"Content-Range",
|
|
||||||
"bytes " + range.start + "-" + range.end + "/" + fileSize
|
|
||||||
);
|
|
||||||
response.setContentLengthLong(length);
|
response.setContentLengthLong(length);
|
||||||
|
|
||||||
streamBytes(filePath, range.start, range.end, response.getOutputStream());
|
transferFile(fileChannel, range.start, length, response.getOutputStream());
|
||||||
|
|
||||||
|
} catch (NoSuchFileException _) {
|
||||||
|
throw ApiError.FILE_NOT_FOUND.createException(filePath.toString());
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
if (isClientDisconnect(e)) {
|
if (isClientDisconnect(e)) {
|
||||||
log.debug("Client disconnected during streaming: {}", e.getMessage());
|
log.debug("Client disconnected during streaming: {}", e.getMessage());
|
||||||
} else {
|
} else {
|
||||||
throw e;
|
log.error("Error during file streaming: {}", filePath, e);
|
||||||
|
if (!response.isCommitted()) {
|
||||||
|
throw ApiError.INTERNAL_SERVER_ERROR.createException("Streaming error: " + e.getMessage());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ------------------------------------------------------------
|
/**
|
||||||
// RANGE PARSER — RFC 7233 compliant
|
* Validates the If-Range header against current ETag and lastModified.
|
||||||
// ------------------------------------------------------------
|
* RFC 7233: If-Range can be a strong ETag OR an HTTP-date.
|
||||||
|
*/
|
||||||
|
private boolean validateIfRange(String ifRange, String etag, Instant lastModified) {
|
||||||
|
if (!ifRange.isEmpty() && ifRange.charAt(0) == '\"') {
|
||||||
|
// ETag comparison (Strong match required)
|
||||||
|
return etag.equals(ifRange);
|
||||||
|
} else {
|
||||||
|
// HTTP-date comparison
|
||||||
|
try {
|
||||||
|
Instant ifRangeDate = Instant.from(HTTP_DATE_FORMAT.parse(ifRange));
|
||||||
|
// Exact match on seconds required by RFC
|
||||||
|
return lastModified.getEpochSecond() == ifRangeDate.getEpochSecond();
|
||||||
|
} catch (DateTimeParseException e) {
|
||||||
|
log.trace("Failed to parse If-Range date: {}", ifRange);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Evaluates the If-None-Match header against the current ETag.
|
||||||
|
* RFC 7232: If-None-Match can be "*", a single entity-tag, or a list of them.
|
||||||
|
*/
|
||||||
|
private boolean evaluateIfNoneMatch(String ifNoneMatch, String currentEtag) {
|
||||||
|
if (ifNoneMatch == null || ifNoneMatch.isBlank()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
String trimmedValue = ifNoneMatch.trim();
|
||||||
|
if ("*".equals(trimmedValue)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Split by comma. Entity-tags are [weak] opaque-tag.
|
||||||
|
String[] parts = trimmedValue.split(",");
|
||||||
|
for (String part : parts) {
|
||||||
|
String tag = part.trim();
|
||||||
|
if (tag.isEmpty()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (isWeakMatch(tag, currentEtag)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Weak comparison of two ETags.
|
||||||
|
* RFC 7232 Section 2.3.2: Two entity-tags are a weak match if their opaque-tags are equal,
|
||||||
|
* regardless of whether either or both have a "W/" prefix.
|
||||||
|
*/
|
||||||
|
private boolean isWeakMatch(String tag1, String tag2) {
|
||||||
|
String opaque1 = tag1.startsWith("W/") ? tag1.substring(2) : tag1;
|
||||||
|
String opaque2 = tag2.startsWith("W/") ? tag2.substring(2) : tag2;
|
||||||
|
return opaque1.equals(opaque2);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Zero-copy transfer from file channel to output stream via NIO.
|
||||||
|
* Delegates to sendfile(2) on Linux / equivalent on macOS when the
|
||||||
|
* servlet container's OutputStream maps to a socket channel.
|
||||||
|
* Closes the output stream upon completion as the channel wrapper propagates close.
|
||||||
|
*/
|
||||||
|
private void transferFile(FileChannel source, long position, long count, OutputStream out) throws IOException {
|
||||||
|
try (WritableByteChannel destination = Channels.newChannel(out)) {
|
||||||
|
long remaining = count;
|
||||||
|
long currentPos = position;
|
||||||
|
int zeroTransferCount = 0;
|
||||||
|
|
||||||
|
while (remaining > 0) {
|
||||||
|
long transferred = source.transferTo(currentPos, remaining, destination);
|
||||||
|
if (transferred <= 0) {
|
||||||
|
++zeroTransferCount;
|
||||||
|
if (zeroTransferCount > 100) {
|
||||||
|
throw new IOException("File transfer stalled with " + remaining + " bytes remaining");
|
||||||
|
}
|
||||||
|
Thread.onSpinWait();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
zeroTransferCount = 0;
|
||||||
|
currentPos += transferred;
|
||||||
|
remaining -= transferred;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Strong ETag derived from file size and last-modified epoch millis.
|
||||||
|
* Sufficient for static-file identity without content hashing overhead.
|
||||||
|
*/
|
||||||
|
String generateETag(long fileSize, Instant lastModified) {
|
||||||
|
return "\"" + Long.toHexString(fileSize) + "-" + Long.toHexString(lastModified.toEpochMilli()) + "\"";
|
||||||
|
}
|
||||||
|
|
||||||
|
// RANGE PARSER (not) RFC 7233 compliant
|
||||||
Range parseRange(String header, long size) {
|
Range parseRange(String header, long size) {
|
||||||
if (header == null || !header.startsWith("bytes=")) {
|
if (header == null || !header.startsWith("bytes=")) {
|
||||||
return null;
|
return null;
|
||||||
@@ -136,45 +268,23 @@ public class FileStreamingService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ------------------------------------------------------------
|
|
||||||
// STREAM BYTES
|
|
||||||
// ------------------------------------------------------------
|
|
||||||
private void streamBytes(Path path, long start, long end, OutputStream out)
|
|
||||||
throws IOException {
|
|
||||||
|
|
||||||
try (RandomAccessFile raf = new RandomAccessFile(path.toFile(), "r")) {
|
|
||||||
raf.seek(start);
|
|
||||||
|
|
||||||
long remaining = end - start + 1;
|
|
||||||
byte[] buffer = new byte[BUFFER_SIZE];
|
|
||||||
|
|
||||||
while (remaining > 0) {
|
|
||||||
int read = raf.read(buffer, 0, (int) Math.min(buffer.length, remaining));
|
|
||||||
if (read == -1) break;
|
|
||||||
out.write(buffer, 0, read);
|
|
||||||
remaining -= read;
|
|
||||||
}
|
|
||||||
|
|
||||||
out.flush();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ------------------------------------------------------------
|
|
||||||
// DISCONNECT DETECTION
|
// DISCONNECT DETECTION
|
||||||
// ------------------------------------------------------------
|
|
||||||
boolean isClientDisconnect(IOException e) {
|
boolean isClientDisconnect(IOException e) {
|
||||||
if (e instanceof SocketTimeoutException) return true;
|
return switch (e) {
|
||||||
|
case SocketTimeoutException _, AsyncRequestNotUsableException _ -> true;
|
||||||
String msg = e.getMessage();
|
case IOException io when io.getMessage() != null -> {
|
||||||
if (msg == null) return false;
|
String msg = io.getMessage();
|
||||||
|
yield msg.contains("Broken pipe")
|
||||||
return msg.contains("Broken pipe")
|
|| msg.contains("Connection reset")
|
||||||
|| msg.contains("Connection reset")
|
|| msg.contains("connection was aborted")
|
||||||
|| msg.contains("connection was aborted")
|
|| msg.contains("An established connection was aborted")
|
||||||
|| msg.contains("An established connection was aborted")
|
|| msg.contains("Response not usable")
|
||||||
|| msg.contains("SocketTimeout")
|
|| msg.contains("SocketTimeout")
|
||||||
|| msg.contains("timed out");
|
|| msg.contains("timed out");
|
||||||
|
}
|
||||||
|
default -> false;
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
record Range(long start, long end) {}
|
record Range(long start, long end) {}
|
||||||
}
|
}
|
||||||
|
|||||||
+16
-3
@@ -110,10 +110,23 @@ public class AudioFileUtilityService {
|
|||||||
while (i2 < s2.length() && Character.isDigit(s2.charAt(i2))) {
|
while (i2 < s2.length() && Character.isDigit(s2.charAt(i2))) {
|
||||||
b2.append(s2.charAt(i2++));
|
b2.append(s2.charAt(i2++));
|
||||||
}
|
}
|
||||||
|
String n1 = b1.toString();
|
||||||
|
String n2 = b2.toString();
|
||||||
|
|
||||||
long v1 = Long.parseLong(b1.toString());
|
// Strip leading zeros for numeric comparison
|
||||||
long v2 = Long.parseLong(b2.toString());
|
int start1 = 0;
|
||||||
if (v1 != v2) return Long.compare(v1, v2);
|
while (start1 < n1.length() - 1 && n1.charAt(start1) == '0') start1++;
|
||||||
|
int start2 = 0;
|
||||||
|
while (start2 < n2.length() - 1 && n2.charAt(start2) == '0') start2++;
|
||||||
|
|
||||||
|
String s1_norm = n1.substring(start1);
|
||||||
|
String s2_norm = n2.substring(start2);
|
||||||
|
|
||||||
|
if (s1_norm.length() != s2_norm.length()) {
|
||||||
|
return s1_norm.length() - s2_norm.length();
|
||||||
|
}
|
||||||
|
int cmp = s1_norm.compareTo(s2_norm);
|
||||||
|
if (cmp != 0) return cmp;
|
||||||
} else {
|
} else {
|
||||||
int cmp = Character.compare(Character.toLowerCase(c1), Character.toLowerCase(c2));
|
int cmp = Character.compare(Character.toLowerCase(c1), Character.toLowerCase(c2));
|
||||||
if (cmp != 0) return cmp;
|
if (cmp != 0) return cmp;
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ package org.booklore.service;
|
|||||||
import jakarta.servlet.ServletOutputStream;
|
import jakarta.servlet.ServletOutputStream;
|
||||||
import jakarta.servlet.http.HttpServletRequest;
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
import jakarta.servlet.http.HttpServletResponse;
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
|
import org.booklore.exception.APIException;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.jupiter.api.io.TempDir;
|
import org.junit.jupiter.api.io.TempDir;
|
||||||
@@ -15,6 +17,8 @@ import java.io.IOException;
|
|||||||
import java.net.SocketTimeoutException;
|
import java.net.SocketTimeoutException;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.attribute.BasicFileAttributes;
|
||||||
|
import java.time.Instant;
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.*;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
import static org.mockito.Mockito.*;
|
import static org.mockito.Mockito.*;
|
||||||
@@ -46,10 +50,10 @@ class FileStreamingServiceTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void streamWithRangeSupport_noRangeHeader_streamsFullFile() throws IOException {
|
void streamWithRangeSupport_noRangeHeader_streamsFullFile() throws IOException {
|
||||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
var request = mock(HttpServletRequest.class);
|
||||||
HttpServletResponse response = mock(HttpServletResponse.class);
|
var response = mock(HttpServletResponse.class);
|
||||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
var outputStream = new ByteArrayOutputStream();
|
||||||
ServletOutputStream servletOutputStream = createServletOutputStream(outputStream);
|
var servletOutputStream = createServletOutputStream(outputStream);
|
||||||
|
|
||||||
when(request.getHeader("Range")).thenReturn(null);
|
when(request.getHeader("Range")).thenReturn(null);
|
||||||
when(response.getOutputStream()).thenReturn(servletOutputStream);
|
when(response.getOutputStream()).thenReturn(servletOutputStream);
|
||||||
@@ -65,24 +69,25 @@ class FileStreamingServiceTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void streamWithRangeSupport_fileNotFound_sends404() throws IOException {
|
void streamWithRangeSupport_fileNotFound_sends404() throws IOException {
|
||||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
var request = mock(HttpServletRequest.class);
|
||||||
HttpServletResponse response = mock(HttpServletResponse.class);
|
var response = mock(HttpServletResponse.class);
|
||||||
|
|
||||||
Path nonexistent = tempDir.resolve("nonexistent.bin");
|
Path nonexistent = tempDir.resolve("nonexistent.bin");
|
||||||
|
|
||||||
fileStreamingService.streamWithRangeSupport(nonexistent, "audio/mp4", request, response);
|
APIException exception = assertThrows(APIException.class, () ->
|
||||||
|
fileStreamingService.streamWithRangeSupport(nonexistent, "audio/mp4", request, response)
|
||||||
verify(response).sendError(HttpServletResponse.SC_NOT_FOUND, "File not found");
|
);
|
||||||
|
assertEquals(HttpStatus.NOT_FOUND, exception.getStatus());
|
||||||
}
|
}
|
||||||
|
|
||||||
// ==================== streamWithRangeSupport - Range request tests ====================
|
// ==================== streamWithRangeSupport - Range request tests ====================
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void streamWithRangeSupport_fullRange_streamsPartialContent() throws IOException {
|
void streamWithRangeSupport_fullRange_streamsPartialContent() throws IOException {
|
||||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
var request = mock(HttpServletRequest.class);
|
||||||
HttpServletResponse response = mock(HttpServletResponse.class);
|
var response = mock(HttpServletResponse.class);
|
||||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
var outputStream = new ByteArrayOutputStream();
|
||||||
ServletOutputStream servletOutputStream = createServletOutputStream(outputStream);
|
var servletOutputStream = createServletOutputStream(outputStream);
|
||||||
|
|
||||||
when(request.getHeader("Range")).thenReturn("bytes=0-99");
|
when(request.getHeader("Range")).thenReturn("bytes=0-99");
|
||||||
when(response.getOutputStream()).thenReturn(servletOutputStream);
|
when(response.getOutputStream()).thenReturn(servletOutputStream);
|
||||||
@@ -100,10 +105,10 @@ class FileStreamingServiceTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void streamWithRangeSupport_openEndedRange_streamsToEnd() throws IOException {
|
void streamWithRangeSupport_openEndedRange_streamsToEnd() throws IOException {
|
||||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
var request = mock(HttpServletRequest.class);
|
||||||
HttpServletResponse response = mock(HttpServletResponse.class);
|
var response = mock(HttpServletResponse.class);
|
||||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
var outputStream = new ByteArrayOutputStream();
|
||||||
ServletOutputStream servletOutputStream = createServletOutputStream(outputStream);
|
var servletOutputStream = createServletOutputStream(outputStream);
|
||||||
|
|
||||||
when(request.getHeader("Range")).thenReturn("bytes=9900-");
|
when(request.getHeader("Range")).thenReturn("bytes=9900-");
|
||||||
when(response.getOutputStream()).thenReturn(servletOutputStream);
|
when(response.getOutputStream()).thenReturn(servletOutputStream);
|
||||||
@@ -121,10 +126,10 @@ class FileStreamingServiceTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void streamWithRangeSupport_suffixRange_streamsLastNBytes() throws IOException {
|
void streamWithRangeSupport_suffixRange_streamsLastNBytes() throws IOException {
|
||||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
var request = mock(HttpServletRequest.class);
|
||||||
HttpServletResponse response = mock(HttpServletResponse.class);
|
var response = mock(HttpServletResponse.class);
|
||||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
var outputStream = new ByteArrayOutputStream();
|
||||||
ServletOutputStream servletOutputStream = createServletOutputStream(outputStream);
|
var servletOutputStream = createServletOutputStream(outputStream);
|
||||||
|
|
||||||
when(request.getHeader("Range")).thenReturn("bytes=-500");
|
when(request.getHeader("Range")).thenReturn("bytes=-500");
|
||||||
when(response.getOutputStream()).thenReturn(servletOutputStream);
|
when(response.getOutputStream()).thenReturn(servletOutputStream);
|
||||||
@@ -142,8 +147,8 @@ class FileStreamingServiceTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void streamWithRangeSupport_invalidRange_sends416() throws IOException {
|
void streamWithRangeSupport_invalidRange_sends416() throws IOException {
|
||||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
var request = mock(HttpServletRequest.class);
|
||||||
HttpServletResponse response = mock(HttpServletResponse.class);
|
var response = mock(HttpServletResponse.class);
|
||||||
|
|
||||||
when(request.getHeader("Range")).thenReturn("bytes=50000-60000"); // Beyond file size
|
when(request.getHeader("Range")).thenReturn("bytes=50000-60000"); // Beyond file size
|
||||||
|
|
||||||
@@ -155,10 +160,10 @@ class FileStreamingServiceTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void streamWithRangeSupport_rangeEndBeyondFileSize_clampsToFileSize() throws IOException {
|
void streamWithRangeSupport_rangeEndBeyondFileSize_clampsToFileSize() throws IOException {
|
||||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
var request = mock(HttpServletRequest.class);
|
||||||
HttpServletResponse response = mock(HttpServletResponse.class);
|
var response = mock(HttpServletResponse.class);
|
||||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
var outputStream = new ByteArrayOutputStream();
|
||||||
ServletOutputStream servletOutputStream = createServletOutputStream(outputStream);
|
var servletOutputStream = createServletOutputStream(outputStream);
|
||||||
|
|
||||||
when(request.getHeader("Range")).thenReturn("bytes=9990-99999"); // End beyond file
|
when(request.getHeader("Range")).thenReturn("bytes=9990-99999"); // End beyond file
|
||||||
when(response.getOutputStream()).thenReturn(servletOutputStream);
|
when(response.getOutputStream()).thenReturn(servletOutputStream);
|
||||||
@@ -169,20 +174,163 @@ class FileStreamingServiceTest {
|
|||||||
verify(response).setContentLengthLong(10); // 9990 to 9999
|
verify(response).setContentLengthLong(10); // 9990 to 9999
|
||||||
verify(response).setHeader("Content-Range", "bytes 9990-9999/" + testContent.length);
|
verify(response).setHeader("Content-Range", "bytes 9990-9999/" + testContent.length);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void streamWithRangeSupport_setsCacheControlHeader() throws IOException {
|
void streamWithRangeSupport_setsETagAndCacheHeaders() throws IOException {
|
||||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
var request = mock(HttpServletRequest.class);
|
||||||
HttpServletResponse response = mock(HttpServletResponse.class);
|
var response = mock(HttpServletResponse.class);
|
||||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
var outputStream = new ByteArrayOutputStream();
|
||||||
ServletOutputStream servletOutputStream = createServletOutputStream(outputStream);
|
var servletOutputStream = createServletOutputStream(outputStream);
|
||||||
|
|
||||||
when(request.getHeader("Range")).thenReturn(null);
|
when(request.getHeader("Range")).thenReturn(null);
|
||||||
when(response.getOutputStream()).thenReturn(servletOutputStream);
|
when(response.getOutputStream()).thenReturn(servletOutputStream);
|
||||||
|
|
||||||
fileStreamingService.streamWithRangeSupport(testFile, "audio/mp4", request, response);
|
fileStreamingService.streamWithRangeSupport(testFile, "audio/mp4", request, response);
|
||||||
|
|
||||||
verify(response).setHeader("Cache-Control", "no-store");
|
String expectedETag = computeExpectedETag(testFile);
|
||||||
|
verify(response).setHeader("ETag", expectedETag);
|
||||||
|
verify(response).setHeader("Cache-Control", "no-cache");
|
||||||
|
verify(response, never()).setHeader(eq("Pragma"), any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void streamWithRangeSupport_ifNoneMatchMatchingEtag_returns304() throws IOException {
|
||||||
|
var request = mock(HttpServletRequest.class);
|
||||||
|
var response = mock(HttpServletResponse.class);
|
||||||
|
|
||||||
|
String etag = computeExpectedETag(testFile);
|
||||||
|
when(request.getHeader("If-None-Match")).thenReturn(etag);
|
||||||
|
|
||||||
|
fileStreamingService.streamWithRangeSupport(testFile, "audio/mp4", request, response);
|
||||||
|
|
||||||
|
verify(response).setStatus(HttpServletResponse.SC_NOT_MODIFIED);
|
||||||
|
verify(response, never()).getOutputStream();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void streamWithRangeSupport_ifNoneMatchStaleEtag_streamsNormally() throws IOException {
|
||||||
|
var request = mock(HttpServletRequest.class);
|
||||||
|
var response = mock(HttpServletResponse.class);
|
||||||
|
var outputStream = new ByteArrayOutputStream();
|
||||||
|
var servletOutputStream = createServletOutputStream(outputStream);
|
||||||
|
|
||||||
|
when(request.getHeader("If-None-Match")).thenReturn("\"stale-etag\"");
|
||||||
|
when(request.getHeader("Range")).thenReturn(null);
|
||||||
|
when(response.getOutputStream()).thenReturn(servletOutputStream);
|
||||||
|
|
||||||
|
fileStreamingService.streamWithRangeSupport(testFile, "audio/mp4", request, response);
|
||||||
|
|
||||||
|
verify(response).setStatus(HttpServletResponse.SC_OK);
|
||||||
|
assertArrayEquals(testContent, outputStream.toByteArray());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void streamWithRangeSupport_ifNoneMatchWildcard_returns304() throws IOException {
|
||||||
|
var request = mock(HttpServletRequest.class);
|
||||||
|
var response = mock(HttpServletResponse.class);
|
||||||
|
|
||||||
|
when(request.getHeader("If-None-Match")).thenReturn("*");
|
||||||
|
|
||||||
|
fileStreamingService.streamWithRangeSupport(testFile, "audio/mp4", request, response);
|
||||||
|
|
||||||
|
verify(response).setStatus(HttpServletResponse.SC_NOT_MODIFIED);
|
||||||
|
verify(response, never()).getOutputStream();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void streamWithRangeSupport_ifNoneMatchList_returns304() throws IOException {
|
||||||
|
var request = mock(HttpServletRequest.class);
|
||||||
|
var response = mock(HttpServletResponse.class);
|
||||||
|
|
||||||
|
String etag = computeExpectedETag(testFile);
|
||||||
|
when(request.getHeader("If-None-Match")).thenReturn("\"other\", " + etag);
|
||||||
|
|
||||||
|
fileStreamingService.streamWithRangeSupport(testFile, "audio/mp4", request, response);
|
||||||
|
|
||||||
|
verify(response).setStatus(HttpServletResponse.SC_NOT_MODIFIED);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void streamWithRangeSupport_ifNoneMatchWeakTag_returns304() throws IOException {
|
||||||
|
var request = mock(HttpServletRequest.class);
|
||||||
|
var response = mock(HttpServletResponse.class);
|
||||||
|
|
||||||
|
String etag = computeExpectedETag(testFile);
|
||||||
|
String weakEtag = "W/" + etag;
|
||||||
|
when(request.getHeader("If-None-Match")).thenReturn(weakEtag);
|
||||||
|
|
||||||
|
fileStreamingService.streamWithRangeSupport(testFile, "audio/mp4", request, response);
|
||||||
|
|
||||||
|
verify(response).setStatus(HttpServletResponse.SC_NOT_MODIFIED);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void streamWithRangeSupport_headRequest_returns200WithContentLength() throws IOException {
|
||||||
|
var request = mock(HttpServletRequest.class);
|
||||||
|
var response = mock(HttpServletResponse.class);
|
||||||
|
|
||||||
|
when(request.getMethod()).thenReturn("HEAD");
|
||||||
|
|
||||||
|
fileStreamingService.streamWithRangeSupport(testFile, "audio/mp4", request, response);
|
||||||
|
|
||||||
|
verify(response).setStatus(HttpServletResponse.SC_OK);
|
||||||
|
verify(response).setContentLengthLong(testContent.length);
|
||||||
|
verify(response).setHeader("Accept-Ranges", "bytes");
|
||||||
|
verify(response, never()).getOutputStream();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void streamWithRangeSupport_ifRangeMatchingEtag_servesRange() throws IOException {
|
||||||
|
var request = mock(HttpServletRequest.class);
|
||||||
|
var response = mock(HttpServletResponse.class);
|
||||||
|
var outputStream = new ByteArrayOutputStream();
|
||||||
|
var servletOutputStream = createServletOutputStream(outputStream);
|
||||||
|
|
||||||
|
String etag = computeExpectedETag(testFile);
|
||||||
|
when(request.getHeader("Range")).thenReturn("bytes=0-99");
|
||||||
|
when(request.getHeader("If-Range")).thenReturn(etag);
|
||||||
|
when(response.getOutputStream()).thenReturn(servletOutputStream);
|
||||||
|
|
||||||
|
fileStreamingService.streamWithRangeSupport(testFile, "audio/mp4", request, response);
|
||||||
|
|
||||||
|
verify(response).setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
|
||||||
|
verify(response).setContentLengthLong(100);
|
||||||
|
assertEquals(100, outputStream.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void streamWithRangeSupport_ifRangeStaleEtag_servesFullFile() throws IOException {
|
||||||
|
var request = mock(HttpServletRequest.class);
|
||||||
|
var response = mock(HttpServletResponse.class);
|
||||||
|
var outputStream = new ByteArrayOutputStream();
|
||||||
|
var servletOutputStream = createServletOutputStream(outputStream);
|
||||||
|
|
||||||
|
when(request.getHeader("Range")).thenReturn("bytes=0-99");
|
||||||
|
when(request.getHeader("If-Range")).thenReturn("\"stale-etag\"");
|
||||||
|
when(response.getOutputStream()).thenReturn(servletOutputStream);
|
||||||
|
|
||||||
|
fileStreamingService.streamWithRangeSupport(testFile, "audio/mp4", request, response);
|
||||||
|
|
||||||
|
// Stale If-Range ignore range, return full file
|
||||||
|
verify(response).setStatus(HttpServletResponse.SC_OK);
|
||||||
|
verify(response).setContentLengthLong(testContent.length);
|
||||||
|
assertArrayEquals(testContent, outputStream.toByteArray());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void streamWithRangeSupport_setsLastModifiedHeader() throws IOException {
|
||||||
|
var request = mock(HttpServletRequest.class);
|
||||||
|
var response = mock(HttpServletResponse.class);
|
||||||
|
var outputStream = new ByteArrayOutputStream();
|
||||||
|
var servletOutputStream = createServletOutputStream(outputStream);
|
||||||
|
|
||||||
|
when(request.getHeader("Range")).thenReturn(null);
|
||||||
|
when(response.getOutputStream()).thenReturn(servletOutputStream);
|
||||||
|
|
||||||
|
fileStreamingService.streamWithRangeSupport(testFile, "audio/mp4", request, response);
|
||||||
|
|
||||||
|
var attrs = Files.readAttributes(testFile, BasicFileAttributes.class);
|
||||||
|
long expectedMs = attrs.lastModifiedTime().toInstant().toEpochMilli();
|
||||||
|
verify(response).setDateHeader("Last-Modified", expectedMs);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ==================== parseRange tests ====================
|
// ==================== parseRange tests ====================
|
||||||
@@ -263,7 +411,6 @@ class FileStreamingServiceTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void parseRange_withLeadingTrailingWhitespace_parsesCorrectly() {
|
void parseRange_withLeadingTrailingWhitespace_parsesCorrectly() {
|
||||||
// Leading/trailing whitespace around the range spec is trimmed
|
|
||||||
var result = fileStreamingService.parseRange("bytes=100-199", 1000);
|
var result = fileStreamingService.parseRange("bytes=100-199", 1000);
|
||||||
|
|
||||||
assertNotNull(result);
|
assertNotNull(result);
|
||||||
@@ -307,7 +454,6 @@ class FileStreamingServiceTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void isClientDisconnect_nullMessage_checksClassName() {
|
void isClientDisconnect_nullMessage_checksClassName() {
|
||||||
// Create an IOException with null message but class name containing "Timeout"
|
|
||||||
IOException timeoutException = new SocketTimeoutException();
|
IOException timeoutException = new SocketTimeoutException();
|
||||||
assertTrue(fileStreamingService.isClientDisconnect(timeoutException));
|
assertTrue(fileStreamingService.isClientDisconnect(timeoutException));
|
||||||
}
|
}
|
||||||
@@ -324,15 +470,14 @@ class FileStreamingServiceTest {
|
|||||||
Path emptyFile = tempDir.resolve("empty.bin");
|
Path emptyFile = tempDir.resolve("empty.bin");
|
||||||
Files.createFile(emptyFile);
|
Files.createFile(emptyFile);
|
||||||
|
|
||||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
var request = mock(HttpServletRequest.class);
|
||||||
HttpServletResponse response = mock(HttpServletResponse.class);
|
var response = mock(HttpServletResponse.class);
|
||||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
var outputStream = new ByteArrayOutputStream();
|
||||||
ServletOutputStream servletOutputStream = createServletOutputStream(outputStream);
|
var servletOutputStream = createServletOutputStream(outputStream);
|
||||||
|
|
||||||
when(request.getHeader("Range")).thenReturn(null);
|
when(request.getHeader("Range")).thenReturn(null);
|
||||||
when(response.getOutputStream()).thenReturn(servletOutputStream);
|
when(response.getOutputStream()).thenReturn(servletOutputStream);
|
||||||
|
|
||||||
// This should handle empty file gracefully - the stream will be empty
|
|
||||||
fileStreamingService.streamWithRangeSupport(emptyFile, "audio/mp4", request, response);
|
fileStreamingService.streamWithRangeSupport(emptyFile, "audio/mp4", request, response);
|
||||||
|
|
||||||
verify(response).setStatus(HttpServletResponse.SC_OK);
|
verify(response).setStatus(HttpServletResponse.SC_OK);
|
||||||
@@ -341,10 +486,10 @@ class FileStreamingServiceTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void streamWithRangeSupport_singleByteRange_streamsOneByte() throws IOException {
|
void streamWithRangeSupport_singleByteRange_streamsOneByte() throws IOException {
|
||||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
var request = mock(HttpServletRequest.class);
|
||||||
HttpServletResponse response = mock(HttpServletResponse.class);
|
var response = mock(HttpServletResponse.class);
|
||||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
var outputStream = new ByteArrayOutputStream();
|
||||||
ServletOutputStream servletOutputStream = createServletOutputStream(outputStream);
|
var servletOutputStream = createServletOutputStream(outputStream);
|
||||||
|
|
||||||
when(request.getHeader("Range")).thenReturn("bytes=50-50");
|
when(request.getHeader("Range")).thenReturn("bytes=50-50");
|
||||||
when(response.getOutputStream()).thenReturn(servletOutputStream);
|
when(response.getOutputStream()).thenReturn(servletOutputStream);
|
||||||
@@ -365,10 +510,10 @@ class FileStreamingServiceTest {
|
|||||||
"9999, 9999"
|
"9999, 9999"
|
||||||
})
|
})
|
||||||
void streamWithRangeSupport_variousValidRanges_streamsCorrectContent(int start, int end) throws IOException {
|
void streamWithRangeSupport_variousValidRanges_streamsCorrectContent(int start, int end) throws IOException {
|
||||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
var request = mock(HttpServletRequest.class);
|
||||||
HttpServletResponse response = mock(HttpServletResponse.class);
|
var response = mock(HttpServletResponse.class);
|
||||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
var outputStream = new ByteArrayOutputStream();
|
||||||
ServletOutputStream servletOutputStream = createServletOutputStream(outputStream);
|
var servletOutputStream = createServletOutputStream(outputStream);
|
||||||
|
|
||||||
when(request.getHeader("Range")).thenReturn("bytes=" + start + "-" + end);
|
when(request.getHeader("Range")).thenReturn("bytes=" + start + "-" + end);
|
||||||
when(response.getOutputStream()).thenReturn(servletOutputStream);
|
when(response.getOutputStream()).thenReturn(servletOutputStream);
|
||||||
@@ -383,7 +528,14 @@ class FileStreamingServiceTest {
|
|||||||
assertArrayEquals(expected, outputStream.toByteArray());
|
assertArrayEquals(expected, outputStream.toByteArray());
|
||||||
}
|
}
|
||||||
|
|
||||||
// Helper method to create a mock ServletOutputStream
|
// ==================== Helpers ====================
|
||||||
|
|
||||||
|
private String computeExpectedETag(Path file) throws IOException {
|
||||||
|
var attrs = Files.readAttributes(file, BasicFileAttributes.class);
|
||||||
|
return fileStreamingService.generateETag(
|
||||||
|
attrs.size(), attrs.lastModifiedTime().toInstant());
|
||||||
|
}
|
||||||
|
|
||||||
private ServletOutputStream createServletOutputStream(ByteArrayOutputStream outputStream) {
|
private ServletOutputStream createServletOutputStream(ByteArrayOutputStream outputStream) {
|
||||||
return new ServletOutputStream() {
|
return new ServletOutputStream() {
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
+14
@@ -296,6 +296,20 @@ class AudioFileUtilityServiceTest {
|
|||||||
assertEquals("100.mp3", result.get(3).getFileName().toString());
|
assertEquals("100.mp3", result.get(3).getFileName().toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void listAudioFiles_handlesVeryLongNumericStrings() throws IOException {
|
||||||
|
String longNum1 = "track-12345678901234567890.mp3";
|
||||||
|
String longNum2 = "track-12345678901234567891.mp3";
|
||||||
|
Files.createFile(tempDir.resolve(longNum2));
|
||||||
|
Files.createFile(tempDir.resolve(longNum1));
|
||||||
|
|
||||||
|
List<Path> result = audioFileUtility.listAudioFiles(tempDir);
|
||||||
|
|
||||||
|
assertEquals(2, result.size());
|
||||||
|
assertEquals(longNum1, result.get(0).getFileName().toString());
|
||||||
|
assertEquals(longNum2, result.get(1).getFileName().toString());
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void listAudioFiles_sortsCaseInsensitively() throws IOException {
|
void listAudioFiles_sortsCaseInsensitively() throws IOException {
|
||||||
Files.createFile(tempDir.resolve("Alpha.mp3"));
|
Files.createFile(tempDir.resolve("Alpha.mp3"));
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
import {defineConfig, devices} from '@playwright/test';
|
import {defineConfig, devices} from '@playwright/test';
|
||||||
|
|
||||||
const host = process.env.PLAYWRIGHT_HOST ?? '127.0.0.1';
|
const host = process.env['PLAYWRIGHT_HOST'] ?? '127.0.0.1';
|
||||||
const port = Number(process.env.PLAYWRIGHT_PORT ?? '4301');
|
const port = Number(process.env['PLAYWRIGHT_PORT'] ?? '4301');
|
||||||
const baseURL = process.env.PLAYWRIGHT_BASE_URL ?? `http://${host}:${port}`;
|
const baseURL = process.env['PLAYWRIGHT_BASE_URL'] ?? `http://${host}:${port}`;
|
||||||
const startServer = process.env.PLAYWRIGHT_START_SERVER !== 'false';
|
const startServer = process.env['PLAYWRIGHT_START_SERVER'] !== 'false';
|
||||||
const reuseExistingServer = process.env.PLAYWRIGHT_REUSE_SERVER === 'true';
|
const reuseExistingServer = process.env['PLAYWRIGHT_REUSE_SERVER'] === 'true';
|
||||||
const outputDir = process.env.PLAYWRIGHT_OUTPUT_DIR ?? `output/playwright-${port}`;
|
const outputDir = process.env['PLAYWRIGHT_OUTPUT_DIR'] ?? `output/playwright-${port}`;
|
||||||
const workers = Number(process.env.PLAYWRIGHT_WORKERS ?? '1');
|
const workers = Number(process.env['PLAYWRIGHT_WORKERS'] ?? '1');
|
||||||
|
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
testDir: './playwright',
|
testDir: './playwright',
|
||||||
@@ -14,7 +14,7 @@ export default defineConfig({
|
|||||||
workers,
|
workers,
|
||||||
outputDir,
|
outputDir,
|
||||||
reporter: [['list']],
|
reporter: [['list']],
|
||||||
retries: process.env.CI ? 1 : 0,
|
retries: process.env['CI'] ? 1 : 0,
|
||||||
use: {
|
use: {
|
||||||
baseURL,
|
baseURL,
|
||||||
trace: 'on-first-retry',
|
trace: 'on-first-retry',
|
||||||
|
|||||||
@@ -1,4 +1,14 @@
|
|||||||
import {ChangeDetectionStrategy, ChangeDetectorRef, Component, DestroyRef, ElementRef, inject, OnDestroy, OnInit, ViewChild} from '@angular/core';
|
import {
|
||||||
|
ChangeDetectionStrategy,
|
||||||
|
ChangeDetectorRef,
|
||||||
|
Component,
|
||||||
|
DestroyRef,
|
||||||
|
ElementRef,
|
||||||
|
inject,
|
||||||
|
OnDestroy,
|
||||||
|
OnInit,
|
||||||
|
ViewChild
|
||||||
|
} from '@angular/core';
|
||||||
import {Location} from '@angular/common';
|
import {Location} from '@angular/common';
|
||||||
import {ActivatedRoute} from '@angular/router';
|
import {ActivatedRoute} from '@angular/router';
|
||||||
import {FormsModule} from '@angular/forms';
|
import {FormsModule} from '@angular/forms';
|
||||||
@@ -57,6 +67,8 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
|||||||
private pageTitle = inject(PageTitleService);
|
private pageTitle = inject(PageTitleService);
|
||||||
private readonly t = inject(TranslocoService);
|
private readonly t = inject(TranslocoService);
|
||||||
private readonly cdr = inject(ChangeDetectorRef);
|
private readonly cdr = inject(ChangeDetectorRef);
|
||||||
|
|
||||||
|
private loadRequestId = 0;
|
||||||
isLoading = true;
|
isLoading = true;
|
||||||
audioLoading = false;
|
audioLoading = false;
|
||||||
audioInitialized = false;
|
audioInitialized = false;
|
||||||
@@ -149,6 +161,21 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private loadAudiobook(bookId: number): Observable<void> {
|
private loadAudiobook(bookId: number): Observable<void> {
|
||||||
|
const loadRequestId = ++this.loadRequestId;
|
||||||
|
|
||||||
|
if (this.audiobookInfo && this.bookId !== bookId) {
|
||||||
|
this.saveProgress();
|
||||||
|
const audio = this.audioElement?.nativeElement;
|
||||||
|
if (audio) {
|
||||||
|
audio.pause();
|
||||||
|
audio.removeAttribute('src');
|
||||||
|
audio.load();
|
||||||
|
}
|
||||||
|
if (this.audiobookSessionService.isSessionActive()) {
|
||||||
|
this.audiobookSessionService.endSession(Math.round(this.currentTime * 1000));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
this.bookId = bookId;
|
this.bookId = bookId;
|
||||||
this.resetState();
|
this.resetState();
|
||||||
this.isLoading = true;
|
this.isLoading = true;
|
||||||
@@ -162,6 +189,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
|||||||
),
|
),
|
||||||
tap(({info, book}) => {
|
tap(({info, book}) => {
|
||||||
this.audiobookInfo = info;
|
this.audiobookInfo = info;
|
||||||
|
this.updateCurrentChapter();
|
||||||
if (info.folderBased && info.tracks && info.tracks.length > 0) {
|
if (info.folderBased && info.tracks && info.tracks.length > 0) {
|
||||||
this.audioSrc = this.audiobookService.getTrackStreamUrl(bookId, 0);
|
this.audioSrc = this.audiobookService.getTrackStreamUrl(bookId, 0);
|
||||||
const track = info.tracks[0];
|
const track = info.tracks[0];
|
||||||
@@ -183,11 +211,12 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
|||||||
this.applyBookDetails(book, info);
|
this.applyBookDetails(book, info);
|
||||||
}
|
}
|
||||||
|
|
||||||
this.loadBookmarks();
|
this.loadBookmarks(bookId);
|
||||||
|
|
||||||
// Defer the branch flip to a new macrotask so Angular's CD cycle
|
|
||||||
// sees a consistent @if state (prevents NG0100).
|
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
|
if (loadRequestId !== this.loadRequestId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
this.isLoading = false;
|
this.isLoading = false;
|
||||||
this.cdr.markForCheck();
|
this.cdr.markForCheck();
|
||||||
});
|
});
|
||||||
@@ -220,6 +249,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
|||||||
if (audio && audio.readyState >= 1 && this.savedPosition > 0) {
|
if (audio && audio.readyState >= 1 && this.savedPosition > 0) {
|
||||||
audio.currentTime = this.savedPosition;
|
audio.currentTime = this.savedPosition;
|
||||||
this.currentTime = this.savedPosition;
|
this.currentTime = this.savedPosition;
|
||||||
|
this.updateCurrentChapter();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Handle track index for folder-based audiobooks
|
// Handle track index for folder-based audiobooks
|
||||||
@@ -238,6 +268,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
|||||||
|
|
||||||
if (this.savedPosition > 0) {
|
if (this.savedPosition > 0) {
|
||||||
this.currentTime = this.savedPosition;
|
this.currentTime = this.savedPosition;
|
||||||
|
this.updateCurrentChapter();
|
||||||
}
|
}
|
||||||
this.updateCurrentChapter();
|
this.updateCurrentChapter();
|
||||||
}
|
}
|
||||||
@@ -274,6 +305,8 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
|||||||
this.buffered = 0;
|
this.buffered = 0;
|
||||||
this.savedPosition = 0;
|
this.savedPosition = 0;
|
||||||
this.currentTrackIndex = 0;
|
this.currentTrackIndex = 0;
|
||||||
|
this.currentChapter = undefined;
|
||||||
|
this.currentChapterIdx = -1;
|
||||||
this.audioSrc = '';
|
this.audioSrc = '';
|
||||||
this.audioLoading = false;
|
this.audioLoading = false;
|
||||||
this.audioInitialized = false;
|
this.audioInitialized = false;
|
||||||
@@ -296,6 +329,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
|||||||
if (this.savedPosition > 0 && this.savedPosition < this.duration) {
|
if (this.savedPosition > 0 && this.savedPosition < this.duration) {
|
||||||
audio.currentTime = this.savedPosition;
|
audio.currentTime = this.savedPosition;
|
||||||
this.currentTime = this.savedPosition;
|
this.currentTime = this.savedPosition;
|
||||||
|
this.updateCurrentChapter();
|
||||||
this.savedPosition = 0;
|
this.savedPosition = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -332,6 +366,31 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private updateCurrentChapter(): void {
|
||||||
|
if (!this.audiobookInfo?.chapters) {
|
||||||
|
this.currentChapter = undefined;
|
||||||
|
this.currentChapterIdx = 0;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const chapters = this.audiobookInfo.chapters;
|
||||||
|
const currentMs = this.currentTime * 1000;
|
||||||
|
let chapterIdx = chapters.findIndex(
|
||||||
|
ch => currentMs >= ch.startTimeMs && currentMs < ch.endTimeMs
|
||||||
|
);
|
||||||
|
|
||||||
|
if (chapterIdx === -1) {
|
||||||
|
for (let i = chapters.length - 1; i >= 0; i--) {
|
||||||
|
if (currentMs >= chapters[i].startTimeMs) {
|
||||||
|
chapterIdx = i;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
this.currentChapterIdx = chapterIdx >= 0 ? chapterIdx : 0;
|
||||||
|
this.currentChapter = chapterIdx >= 0 ? chapters[chapterIdx] : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
onProgress(): void {
|
onProgress(): void {
|
||||||
const audio = this.audioElement?.nativeElement;
|
const audio = this.audioElement?.nativeElement;
|
||||||
if (audio && audio.buffered.length > 0) {
|
if (audio && audio.buffered.length > 0) {
|
||||||
@@ -404,6 +463,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
|||||||
if (audio) {
|
if (audio) {
|
||||||
audio.currentTime = details.seekTime;
|
audio.currentTime = details.seekTime;
|
||||||
this.currentTime = details.seekTime;
|
this.currentTime = details.seekTime;
|
||||||
|
this.updateCurrentChapter();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -525,6 +585,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
|||||||
audio.currentTime = seekTime;
|
audio.currentTime = seekTime;
|
||||||
}
|
}
|
||||||
this.isSeeking = false;
|
this.isSeeking = false;
|
||||||
|
this.updateCurrentChapter();
|
||||||
}, 150);
|
}, 150);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -582,6 +643,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
|||||||
this.loadTrack(this.currentTrackIndex - 1);
|
this.loadTrack(this.currentTrackIndex - 1);
|
||||||
this.currentTime = 0;
|
this.currentTime = 0;
|
||||||
this.savedPosition = 0;
|
this.savedPosition = 0;
|
||||||
|
this.updateCurrentChapter();
|
||||||
if (this.isPlaying) {
|
if (this.isPlaying) {
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
this.audioElement?.nativeElement?.play();
|
this.audioElement?.nativeElement?.play();
|
||||||
@@ -597,6 +659,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
|||||||
this.loadTrack(this.currentTrackIndex + 1);
|
this.loadTrack(this.currentTrackIndex + 1);
|
||||||
this.currentTime = 0;
|
this.currentTime = 0;
|
||||||
this.savedPosition = 0;
|
this.savedPosition = 0;
|
||||||
|
this.updateCurrentChapter();
|
||||||
if (this.isPlaying) {
|
if (this.isPlaying) {
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
this.audioElement?.nativeElement?.play();
|
this.audioElement?.nativeElement?.play();
|
||||||
@@ -613,6 +676,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
|||||||
this.currentTime = 0;
|
this.currentTime = 0;
|
||||||
this.savedPosition = 0;
|
this.savedPosition = 0;
|
||||||
this.buffered = 0;
|
this.buffered = 0;
|
||||||
|
this.updateCurrentChapter();
|
||||||
const trackInfo = this.audiobookInfo.tracks?.[track.index];
|
const trackInfo = this.audiobookInfo.tracks?.[track.index];
|
||||||
if (trackInfo?.durationMs) {
|
if (trackInfo?.durationMs) {
|
||||||
this.duration = trackInfo.durationMs / 1000;
|
this.duration = trackInfo.durationMs / 1000;
|
||||||
@@ -702,17 +766,12 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private updateCurrentChapter(): void {
|
getCurrentChapter(): AudiobookChapter | undefined {
|
||||||
if (!this.audiobookInfo?.chapters) {
|
return this.currentChapter;
|
||||||
this.currentChapter = undefined;
|
}
|
||||||
this.currentChapterIdx = 0;
|
|
||||||
return;
|
getCurrentChapterIndex(): number {
|
||||||
}
|
return this.currentChapterIdx;
|
||||||
const currentMs = this.currentTime * 1000;
|
|
||||||
this.currentChapter = this.audiobookInfo.chapters.find(
|
|
||||||
ch => currentMs >= ch.startTimeMs && currentMs < ch.endTimeMs
|
|
||||||
);
|
|
||||||
this.currentChapterIdx = this.currentChapter?.index ?? 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
hasMultipleChapters(): boolean {
|
hasMultipleChapters(): boolean {
|
||||||
@@ -733,8 +792,9 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
|||||||
const chapters = this.audiobookInfo?.chapters;
|
const chapters = this.audiobookInfo?.chapters;
|
||||||
if (!chapters) return;
|
if (!chapters) return;
|
||||||
|
|
||||||
if (this.currentChapterIdx > 0) {
|
const currentIndex = this.getCurrentChapterIndex();
|
||||||
const prevChapter = chapters[this.currentChapterIdx - 1];
|
if (currentIndex > 0) {
|
||||||
|
const prevChapter = chapters[currentIndex - 1];
|
||||||
this.selectChapter(prevChapter);
|
this.selectChapter(prevChapter);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -743,8 +803,9 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
|||||||
const chapters = this.audiobookInfo?.chapters;
|
const chapters = this.audiobookInfo?.chapters;
|
||||||
if (!chapters) return;
|
if (!chapters) return;
|
||||||
|
|
||||||
if (this.currentChapterIdx < chapters.length - 1) {
|
const currentIndex = this.getCurrentChapterIndex();
|
||||||
const nextChapter = chapters[this.currentChapterIdx + 1];
|
if (currentIndex < chapters.length - 1) {
|
||||||
|
const nextChapter = chapters[currentIndex + 1];
|
||||||
this.selectChapter(nextChapter);
|
this.selectChapter(nextChapter);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -980,10 +1041,13 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
loadBookmarks(): void {
|
loadBookmarks(bookId = this.bookId): void {
|
||||||
this.bookMarkService.getBookmarksForBook(this.bookId)
|
this.bookMarkService.getBookmarksForBook(bookId)
|
||||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||||
.subscribe(bookmarks => {
|
.subscribe(bookmarks => {
|
||||||
|
if (bookId !== this.bookId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
this.bookmarks = bookmarks;
|
this.bookmarks = bookmarks;
|
||||||
this.cdr.markForCheck();
|
this.cdr.markForCheck();
|
||||||
});
|
});
|
||||||
@@ -997,6 +1061,8 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
addBookmark(): void {
|
addBookmark(): void {
|
||||||
|
const requestBookId = this.bookId;
|
||||||
|
const requestId = this.loadRequestId;
|
||||||
const currentTrack = this.currentTrack;
|
const currentTrack = this.currentTrack;
|
||||||
|
|
||||||
let title: string;
|
let title: string;
|
||||||
@@ -1019,6 +1085,9 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
|||||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||||
.subscribe({
|
.subscribe({
|
||||||
next: (bookmark) => {
|
next: (bookmark) => {
|
||||||
|
if (requestId !== this.loadRequestId || requestBookId !== this.bookId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
this.bookmarks = [...this.bookmarks, bookmark];
|
this.bookmarks = [...this.bookmarks, bookmark];
|
||||||
this.messageService.add({
|
this.messageService.add({
|
||||||
severity: 'success',
|
severity: 'success',
|
||||||
@@ -1028,6 +1097,9 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
|||||||
this.cdr.markForCheck();
|
this.cdr.markForCheck();
|
||||||
},
|
},
|
||||||
error: (err) => {
|
error: (err) => {
|
||||||
|
if (requestId !== this.loadRequestId || requestBookId !== this.bookId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
const isDuplicate = err?.status === 409;
|
const isDuplicate = err?.status === 409;
|
||||||
this.messageService.add({
|
this.messageService.add({
|
||||||
severity: isDuplicate ? 'warn' : 'error',
|
severity: isDuplicate ? 'warn' : 'error',
|
||||||
@@ -1060,6 +1132,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
|||||||
audio.removeEventListener('canplay', seekAndPlay);
|
audio.removeEventListener('canplay', seekAndPlay);
|
||||||
audio.currentTime = targetPosition;
|
audio.currentTime = targetPosition;
|
||||||
this.currentTime = targetPosition;
|
this.currentTime = targetPosition;
|
||||||
|
this.updateCurrentChapter();
|
||||||
audio.play();
|
audio.play();
|
||||||
this.isPlaying = true;
|
this.isPlaying = true;
|
||||||
this.startProgressSaveInterval();
|
this.startProgressSaveInterval();
|
||||||
@@ -1093,6 +1166,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
|||||||
this.currentTime = targetPosition;
|
this.currentTime = targetPosition;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
this.updateCurrentChapter();
|
||||||
this.showBookmarkList = false;
|
this.showBookmarkList = false;
|
||||||
|
|
||||||
if (!this.isPlaying) {
|
if (!this.isPlaying) {
|
||||||
@@ -1117,9 +1191,14 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
|||||||
|
|
||||||
deleteBookmark(event: MouseEvent, bookmarkId: number): void {
|
deleteBookmark(event: MouseEvent, bookmarkId: number): void {
|
||||||
event.stopPropagation();
|
event.stopPropagation();
|
||||||
|
const requestBookId = this.bookId;
|
||||||
|
const requestId = this.loadRequestId;
|
||||||
this.bookMarkService.deleteBookmark(bookmarkId)
|
this.bookMarkService.deleteBookmark(bookmarkId)
|
||||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||||
.subscribe(() => {
|
.subscribe(() => {
|
||||||
|
if (requestId !== this.loadRequestId || requestBookId !== this.bookId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
this.bookmarks = this.bookmarks.filter(b => b.id !== bookmarkId);
|
this.bookmarks = this.bookmarks.filter(b => b.id !== bookmarkId);
|
||||||
this.messageService.add({
|
this.messageService.add({
|
||||||
severity: 'info',
|
severity: 'info',
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import {defineConfig} from 'vitest/config';
|
import {defineConfig} from 'vitest/config';
|
||||||
import angular from '@analogjs/vite-plugin-angular';
|
import angular from '@analogjs/vite-plugin-angular';
|
||||||
|
|
||||||
const shouldEnforceCoverageGate = process.env.COVERAGE_GATE === '1';
|
const shouldEnforceCoverageGate = process.env['COVERAGE_GATE'] === '1';
|
||||||
|
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
plugins: [angular({tsconfig: 'tsconfig.spec.json'})],
|
plugins: [angular({tsconfig: 'tsconfig.spec.json'})],
|
||||||
|
|||||||
Reference in New Issue
Block a user