blob: 7d68817e32c8dd93d6353209a03308d28ea54209 [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 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;
@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, byte[] torrentBytes) throws Exception {
// 解析并保存torrent元信息
TorrentMeta meta = torrentService.parseAndSaveTorrent(torrentBytes);
// 保存资源信息,并关联torrent信息
Resource resource = new Resource();
resource.setName(name);
resource.setDescription(description);
resource.setAuthor(author);
resource.setSize(size);
resource.setPublishTime(LocalDateTime.now());
resource.setTorrentData(torrentBytes);
resource.setInfo_hash(meta.getInfoHash());
// 这里可以保存torrent文件路径,或直接存数据库,依据你的设计
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);
}
}