2024-04-23 01:15:24 +01:00
|
|
|
package cc.fascinated.backend.service;
|
2024-04-23 00:43:05 +01:00
|
|
|
|
2024-04-23 21:16:42 +01:00
|
|
|
import cc.fascinated.backend.exception.impl.BadRequestException;
|
2024-04-23 01:15:24 +01:00
|
|
|
import cc.fascinated.backend.model.Paste;
|
|
|
|
import cc.fascinated.backend.exception.impl.ResourceNotFoundException;
|
|
|
|
import cc.fascinated.backend.repository.PasteRepository;
|
2024-04-23 00:43:05 +01:00
|
|
|
import org.apache.commons.lang3.RandomStringUtils;
|
|
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
|
|
|
import org.springframework.beans.factory.annotation.Value;
|
|
|
|
import org.springframework.stereotype.Service;
|
|
|
|
|
|
|
|
import java.util.Optional;
|
|
|
|
|
|
|
|
@Service
|
|
|
|
public class PasteService {
|
|
|
|
|
|
|
|
/**
|
|
|
|
* The {@link PasteRepository} instance.
|
|
|
|
*/
|
|
|
|
private final PasteRepository pasteRepository;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* The length of the paste id.
|
|
|
|
*/
|
|
|
|
@Value("${paste.id-length}")
|
|
|
|
private int idLength;
|
|
|
|
|
2024-04-23 21:16:42 +01:00
|
|
|
/**
|
|
|
|
* The maximum size of the paste content.
|
|
|
|
*/
|
|
|
|
@Value("${paste.upload-size-limit}")
|
|
|
|
private int uploadSizeLimit;
|
|
|
|
|
2024-04-23 00:43:05 +01:00
|
|
|
@Autowired
|
|
|
|
public PasteService(PasteRepository pasteRepository) {
|
|
|
|
this.pasteRepository = pasteRepository;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Creates a new paste with the specified content.
|
|
|
|
*
|
|
|
|
* @param content The content of the paste.
|
|
|
|
* @return The id of the paste.
|
|
|
|
*/
|
|
|
|
public String createPaste(String content) {
|
2024-04-23 21:16:42 +01:00
|
|
|
int length = content.length();
|
|
|
|
if (length > uploadSizeLimit) {
|
|
|
|
throw new BadRequestException("The paste content is too large, the limit is " + uploadSizeLimit + " characters");
|
|
|
|
}
|
|
|
|
|
2024-04-23 03:36:14 +01:00
|
|
|
return pasteRepository.save(new Paste(
|
|
|
|
RandomStringUtils.randomAlphabetic(idLength),
|
|
|
|
System.currentTimeMillis(),
|
|
|
|
content
|
|
|
|
)).getId();
|
2024-04-23 00:43:05 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Gets the content of the paste with the specified id.
|
|
|
|
*
|
|
|
|
* @param id The id of the paste.
|
|
|
|
* @return The content of the paste.
|
|
|
|
*/
|
|
|
|
public Paste getPaste(String id) {
|
|
|
|
Optional<Paste> paste = pasteRepository.findById(id);
|
|
|
|
|
|
|
|
// The paste does not exist.
|
|
|
|
if (paste.isEmpty()) {
|
|
|
|
throw new ResourceNotFoundException("Paste with id '%s' not found".formatted(id));
|
|
|
|
}
|
|
|
|
return paste.get();
|
|
|
|
}
|
|
|
|
}
|