seria/src/Torrents/TorrentsContext.php

88 lines
2.7 KiB
PHP

<?php
namespace Seria\Torrents;
use Index\Data\IDbConnection;
use Index\Serialisation\Bencode;
use Seria\GitInfo;
use Seria\Users\UserInfo;
class TorrentsContext {
private Torrents $torrents;
private TorrentFiles $files;
private TorrentPeers $peers;
private TorrentPieces $pieces;
public function __construct(IDbConnection $dbConn) {
$this->torrents = new Torrents($dbConn);
$this->files = new TorrentFiles($dbConn);
$this->peers = new TorrentPeers($dbConn);
$this->pieces = new TorrentPieces($dbConn);
}
public function getTorrents(): Torrents {
return $this->torrents;
}
public function getFiles(): TorrentFiles {
return $this->files;
}
public function getPeers(): TorrentPeers {
return $this->peers;
}
public function getPieces(): TorrentPieces {
return $this->pieces;
}
public function canDownloadTorrent(TorrentInfo|string $torrentInfo, ?UserInfo $userInfo): string {
if(is_string($torrentInfo))
$torrentInfo = $this->torrents->getTorrent($torrentInfo, 'id');
if(!$torrentInfo->isActive())
return 'inactive';
if($torrentInfo->isPrivate() && $userInfo === null)
return 'private';
if(!$torrentInfo->isApproved() && ($userInfo !== null && !$userInfo->canApproveTorrents() && $torrentInfo->getUserId() !== $userInfo->getId()))
return 'pending';
return '';
}
public function encodeTorrent(TorrentInfo|string $torrentInfo, string $announceUrl): string {
if(is_string($torrentInfo))
$torrentInfo = $this->torrents->getTorrent($torrentInfo, 'id');
$pieces = '';
$pieceInfos = $this->pieces->getPieces($torrentInfo);
foreach($pieceInfos as $piece)
$pieces .= $piece->getHash();
// VERY IMPORTANT DETAIL: keep ordering identical to how it is in TorrentBuilder to not fuck up info hashes
// this should really be combined somehow
$info = [
'files' => $this->files->getFiles($torrentInfo),
'name' => $torrentInfo->getName(),
'piece length' => $torrentInfo->getPieceLength(),
'pieces' => $pieces,
];
if($torrentInfo->isPrivate())
$info['private'] = 1;
$data = [
'announce' => $announceUrl,
'created by' => sprintf('Seria %s', GitInfo::version()),
'creation date' => $torrentInfo->getCreatedTime(),
'info' => $info,
];
if($torrentInfo->hasComment())
$data['comment'] = $torrentInfo->getComment();
return Bencode::encode($data);
}
}