blob: 1d0e797530c5a37fcd2094410439953537e6b152 [file] [log] [blame]
package com.pt.service;
import com.pt.entity.Download;
import com.pt.entity.Resource;
import com.pt.entity.TorrentMeta;
import com.pt.repository.DownloadRepository;
import com.pt.repository.ResourceRepository;
import com.pt.repository.TorrentMetaRepository;
import com.pt.utils.BencodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
@Service
public class ResourceService {
@Autowired
private ResourceRepository resourceRepository;
@Autowired
private DownloadRepository downloadRepository;
@Autowired
private TorrentService torrentService;
@Autowired
private TorrentMetaRepository torrentMetaRepository;
public List<Resource> getAllResources() {
return resourceRepository.findAll();
}
public List<Resource> getResourcesByAuthor(String username) {
return resourceRepository.findByAuthor(username);
}
// 发布资源时,将种子文件二进制数据保存到数据库
public void publishResource(String name, String description, String author, double size) throws Exception {
// 保存资源信息到数据库,包括种子文件的二进制数据
Resource resource = new Resource();
resource.setName(name);
resource.setDescription(description);
resource.setAuthor(author);
resource.setSize(size);
resource.setPublishTime(LocalDateTime.now());
// 生成种子数据 byte[]
byte[] torrentData = torrentService.generateTorrentBytes("uploads/" + name);
resource.setTorrentData(torrentData);
resourceRepository.save(resource);
}
// 获取资源时,返回BLOB字段内容作为torrent文件
public byte[] getTorrentFileByResource(Resource resource, String username) {
if(resource == null || resource.getTorrentData() == null) return null;
// 记录下载日志
Download download = new Download();
download.setResourceId(String.valueOf(resource.getResourceId()));
download.setDownloader(username);
download.setDownloadTime(LocalDateTime.now());
downloadRepository.save(download);
return resource.getTorrentData();
}
public Resource getResourceById(int id) {
return resourceRepository.findById(id).orElse(null);
}
public void deleteResource(int id) {
Resource resource = getResourceById(id);
if (resource != null) {
// 删除数据库资源记录
resourceRepository.deleteById(id);
// 删除对应的 TorrentMeta 元信息
TorrentMeta meta = torrentMetaRepository.findByFilename(resource.getName());
if (meta != null) {
torrentMetaRepository.delete(meta);
}
}
}
public List<Resource> searchByQuery(String query) {
return resourceRepository.findByNameContainingIgnoreCase(query);
}
}