blob: 4eb782335eff93521702439fcdef18ed2a95c89d [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.service.TrackerService; // 新增导入
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.HashMap;
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;
@Autowired
private TrackerService trackerService; // 新增注入
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, byte[] torrentBytes, String username) throws Exception {
// 解析并保存torrent元信息
TorrentMeta meta = torrentService.parseAndSaveTorrent(torrentBytes);
// 保存资源信息,并关联torrent信息
Resource resource = new Resource();
resource.setName(name);
resource.setDescription(description);
resource.setAuthor(author);
resource.setPublishTime(LocalDateTime.now());
resource.setTorrentData(torrentBytes);
// 这里可以保存torrent文件路径,或直接存数据库,依据你的设计
resourceRepository.save(resource);
// 在Tracker中注册相关信息
// Map<String, String[]> params = new HashMap<>();
// params.put("info_hash", new String[]{meta.getInfoHash()});
// // 这里peer_id和port可以先使用默认值,实际应用中可以根据需求修改
// params.put("peer_id", new String[]{username});
// params.put("port", new String[]{"6881"});
// trackerService.handleAnnounce(params, ip);
}
// 获取资源时,返回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);
}
}