2025-04-15 15:15:08 +01:00
|
|
|
package stirling.software.SPDF.controller.web;
|
|
|
|
|
2025-05-21 16:41:11 +02:00
|
|
|
import java.util.Locale;
|
2025-04-29 11:40:08 +01:00
|
|
|
import java.util.regex.Pattern;
|
|
|
|
|
2025-04-15 15:15:08 +01:00
|
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
|
|
|
import org.springframework.stereotype.Service;
|
|
|
|
|
|
|
|
import lombok.extern.slf4j.Slf4j;
|
|
|
|
|
2025-04-29 11:40:08 +01:00
|
|
|
import stirling.software.SPDF.model.ApplicationProperties;
|
2025-04-15 15:15:08 +01:00
|
|
|
|
|
|
|
@Service
|
|
|
|
@Slf4j
|
|
|
|
public class UploadLimitService {
|
|
|
|
|
2025-04-29 11:40:08 +01:00
|
|
|
@Autowired private ApplicationProperties applicationProperties;
|
2025-04-15 15:15:08 +01:00
|
|
|
|
|
|
|
public long getUploadLimit() {
|
2025-04-20 16:43:24 +01:00
|
|
|
String maxUploadSize =
|
2025-04-29 11:40:08 +01:00
|
|
|
applicationProperties.getSystem().getFileUploadLimit() != null
|
|
|
|
? applicationProperties.getSystem().getFileUploadLimit()
|
|
|
|
: "";
|
2025-04-15 15:15:08 +01:00
|
|
|
|
|
|
|
if (maxUploadSize.isEmpty()) {
|
|
|
|
return 0;
|
2025-04-29 11:40:08 +01:00
|
|
|
} else if (!Pattern.compile("^[1-9][0-9]{0,2}[KMGkmg][Bb]$")
|
|
|
|
.matcher(maxUploadSize)
|
|
|
|
.matches()) {
|
2025-04-15 15:15:08 +01:00
|
|
|
log.error(
|
2025-04-29 11:40:08 +01:00
|
|
|
"Invalid maxUploadSize format. Expected format: [1-9][0-9]{0,2}[KMGkmg][Bb], but got: {}",
|
|
|
|
maxUploadSize);
|
2025-04-15 15:15:08 +01:00
|
|
|
return 0;
|
|
|
|
} else {
|
|
|
|
String unit = maxUploadSize.replaceAll("[1-9][0-9]{0,2}", "").toUpperCase();
|
|
|
|
String number = maxUploadSize.replaceAll("[KMGkmg][Bb]", "");
|
|
|
|
long size = Long.parseLong(number);
|
|
|
|
return switch (unit) {
|
|
|
|
case "KB" -> size * 1024;
|
|
|
|
case "MB" -> size * 1024 * 1024;
|
|
|
|
case "GB" -> size * 1024 * 1024 * 1024;
|
|
|
|
default -> 0;
|
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2025-04-29 11:40:08 +01:00
|
|
|
// TODO: why do this server side not client?
|
2025-04-15 15:15:08 +01:00
|
|
|
public String getReadableUploadLimit() {
|
|
|
|
return humanReadableByteCount(getUploadLimit());
|
|
|
|
}
|
|
|
|
|
|
|
|
private String humanReadableByteCount(long bytes) {
|
|
|
|
if (bytes < 1024) return bytes + " B";
|
|
|
|
int exp = (int) (Math.log(bytes) / Math.log(1024));
|
|
|
|
String pre = "KMGTPE".charAt(exp - 1) + "B";
|
2025-05-21 16:41:11 +02:00
|
|
|
return String.format(Locale.US, "%.1f %s", bytes / Math.pow(1024, exp), pre);
|
2025-04-15 15:15:08 +01:00
|
|
|
}
|
2025-04-20 16:43:24 +01:00
|
|
|
}
|