- All Implemented Interfaces:
CoordinatorListener, ShutdownListener, StorageListener
- Direct Known Subclasses:
FetchAndAdd
Nested Class Summary
Nested ClassesModifier and TypeClassDescription(package private) static classA unique exception class to blame the router that can be caught by SnarkManager.Field Summary
Modifier and TypeFieldDescriptionprivate static final AtomicIntegerCounter numbering the downloads for the console.private booleanTrue if the download may stop itself.private final ObjectLock for the comments state.private CommentSetComments fetched for the torrent.private TorrentDestThe transient destination, when multi-dest is enabled; null otherwise or on stop.private final LogLogger for the download.private final PeerCoordinatorSetShared set of connected peers.private longCurrent backoff delay for the next session creation retry.private SimpleTimer2.TimedEventStartup retry event, when a per-torrent session creation failed.private longWall-clock time of the first failed session creation, for the give-up window.private final intThis download's console id.private intLeechers from the last scrape.private intPartial completions from the last scrape.private intSeeders from the last scrape.private longWhen the download started.private longStop count, incremented bystopTorrent()so a retry event that already fired cannot reconnect a torrent stopped while its event was pending.private booleanSet whengotMetaInfo(PeerCoordinator, MetaInfo)could not create the storage.protected final I2PSnarkUtilThe util.private ConnectionAcceptorAcceptor of incoming peer connections.private StringExtra tracker URL from the config, may be null.private booleanTrue when every file has been checked.private booleanTrue while a file check is running.private final CompleteListenerListener notified when the download completes.private PeerCoordinatorCoordinator of the peer connections.private final byte[]Our 20-byte peer id for this download.private final byte[]The torrent's info hash.private longWhen the tracker last replied.(package private) static final intMaximum peers we upload to across all torrents.private MetaInfoMetadata of the torrent being downloaded.(package private) static final intMaintain a configurable total uploader cap CoordinatorListener.private booleanTrue once the completion notice was sent.static final StringMaximum connections.private static final longInitial startup retry delay after a failed per-torrent session creation, in milliseconds.private static final longMaximum startup retry delay (backoff cap), in milliseconds.private static final longGive up on a per-torrent session after this long, in milliseconds.private final FileRoot directory of the downloaded data.private longUploaded bytes saved in the stats file.private booleanTrue while the download is starting up.private booleanTrue once the download has stopped.private StorageStorage of the downloaded files.booleanWhether the torrent storage has reported completion.private StringMost of these used to be public; use accessors below instead.private TrackerClientThe tracker client.private StringLast tracker error message, null if none.private intPeers reported by the tracker.Constructor Summary
ConstructorsModifierConstructorDescriptionprotectedSnark(I2PSnarkUtil util, String torrent, byte[] ih, String trackerURL, CompleteListener complistener, PeerCoordinatorSet peerCoordinatorSet, ConnectionAcceptor connectionAcceptor, boolean ignored, String rootDir) Create the torrent in multitorrent or magnet mode, for the snark-rpc plugin.Snark(I2PSnarkUtil util, String torrent, byte[] ih, String trackerURL, CompleteListener complistener, PeerCoordinatorSet peerCoordinatorSet, ConnectionAcceptor connectionAcceptor, String rootDir) Create the torrent in multitorrent or magnet mode.Snark(I2PSnarkUtil util, String torrent, String ip, int user_port, StorageListener slistener, CoordinatorListener clistener, CompleteListener complistener, PeerCoordinatorSet peerCoordinatorSet, ConnectionAcceptor connectionAcceptor, String rootDir) Create the torrent in multitorrent mode.Snark(I2PSnarkUtil util, String torrent, String ip, int user_port, StorageListener slistener, CoordinatorListener clistener, CompleteListener complistener, PeerCoordinatorSet peerCoordinatorSet, ConnectionAcceptor connectionAcceptor, String rootDir, File baseFile) Create the torrent in multitorrent mode.Method Summary
Modifier and TypeMethodDescriptionbooleanaddComments(List<Comment> comments) Add to the current comment set for this torrent, creating it if it didn't previously exist.voidaddMessage(String message) StorageListener and CoordinatorListener callback.(package private) voidawaitUnannounces(long ms) Wait, capped at ms, for this torrent's unannounces to dispatch.voidBan the given hash.private voidCancel a pending startup retry, if any.private voidAborts program abnormally.private voidAborts program abnormally: logs the failure, stops the torrent, tells the CompleteListener, and throws.private voidfatalRouter(String s, Throwable t) Throws a unique exception class to blame the router that can be caught bySnarkManager.private byte[]Our peer ID for trackers and peers: the spoofed client identity selected for this torrent's destination when i2psnark.clientId is configured, else the legacy anonymous ID of nine zero bytes, three 0x03 bytes, then eight random bytes.private StringThe base name with path and error info, for error logging only.The base name of the torrent.doubleThe progress of file checking as a percentage.The current comment set for this torrent.longThe total length of all non-padding torrent files; equalsgetTotalLength()for torrents without BEP 47 padding files.getDest()The transient multi-dest destination, or null when multi-dest is disabled or the torrent is stopped.longThe total number of bytes downloaded.longThe current download rate in bytes per second.byte[]getID()The peer ID.byte[]The info hash.longThe wall-clock time of the last valid tracker announce or scrape response, or 0 if none was ever received.The metainfo.getName()The file name of the .torrent file.longThe number of pieces still missing.longBytes still wanted.intThe peer count.The peer list.intgetPieceLength(int p) The piece length.intThe number of pieces.longBytes not yet in storage.intgetRPCID()A unique ID for this torrent, useful for RPC.intThe best-known leech count from tracker scrapes.intThe best-known partial seed count from tracker scrapes.intThe best-known seed count from tracker scrapes.longBytes not received and set to skipped.longWhen did we start this torrent For RPC.The storage.intDistinct swarm peers seen recently (via announce, PEX or DHT) or currently connected, for the torrent view peer count.longThe total length of all torrent files, padding files included.Not HTML escaped.intThe tracker seen peers count.The tracker URL.longThe total number of bytes uploaded.longThe current upload rate in bytes per second.voidgotMetaInfo(PeerCoordinator coordinator, MetaInfo metainfo) Called when the PeerCoordinator got the MetaInfo via magnet.booleanCheck if disk allocation (ballooning) is in progress.booleanCheck if the torrent is auto-stoppable.booleanIs the given hash banned?booleanCheck if file checking is in progress.booleanWhether a completion notification has already been sent for this torrent.booleanCheck if startup is in progress.booleanCheck if the torrent is stopped.booleanWhether the torrent storage has completed.booleanoverUploadLimit(int uploaders) CoordinatorListener callback to check if the total uploaders across all torrents exceeds the configured limit.voidpeerChange(PeerCoordinator coordinator, Peer peer) CoordinatorListener no-op.voidreplaceMetaInfo(MetaInfo metainfo) Call after editing torrent.private voidReset the session creation retry backoff state, on success and on stop.booleanRestart the connection acceptor.private voidscheduleRetry(long delay) Schedule a retry of startTorrent() after a per-torrent session creation failure.voidsetAutoStoppable(boolean yes) Store whether the torrent is auto-stoppable.voidsetLastTrackerResponse(long t) Record a valid tracker announce or scrape response.voidsetNotificationSent(boolean sent) Mark that a completion notification has been sent.voidMark startup in progress.voidStore the tracker problems string.voidsetTrackerSeenPeers(int p) Store the tracker seen peers count.voidsetWantedPieces(Storage storage) StorageListener callback to update the coordinator's wanted piece set.voidshutdown()SnarkShutdown callback unused.voidStart up contacting peers and querying the tracker.voidStop contacting the tracker and talking with peers.voidstopTorrent(boolean fast) Stop contacting the tracker and talking with peers.(package private) voidstopTorrent(boolean fast, boolean deferTeardown) Stop contacting the tracker and talking with peers, optionally leaving the I2P session open so the caller can dispatch unannounces before teardown.voidstorageAllChecked(Storage storage) StorageListener callback called when all pieces have been checked.voidstorageAllocated(Storage storage, long length) No-op; deliberately empty.voidstorageChecked(Storage storage, int num, boolean checked) StorageListener callback called when a piece check completes.voidstorageCompleted(Storage storage) StorageListener callback called when the torrent has completed.voidstorageCreateFile(Storage storage, String name, long length) StorageListener no-op.(package private) voidDestroy the I2P session for this stopped torrent.voidRecalculate piece priorities.voidupdateScrape(int seeders, int leechers) Update the best-known swarm composition from a tracker scrape (BEP 15/48).voidupdateScrape(int seeders, int leechers, int partials) Update the best-known swarm composition from a tracker scrape (BEP 15/48/21).private voidStarts the torrent's components.
Field Details
PROP_MAX_CONNECTIONS
torrent
Most of these used to be public; use accessors below instead.meta
Metadata of the torrent being downloaded.storage
Storage of the downloaded files.coordinator
Coordinator of the peer connections.acceptor
Acceptor of incoming peer connections.trackerclient
The tracker client.rootDataDir
Root directory of the downloaded data.completeListener
Listener notified when the download completes.stopped
private volatile boolean stoppedTrue once the download has stopped.starting
private volatile boolean startingTrue while the download is starting up.id
private final byte[] idOur 20-byte peer id for this download.infoHash
private final byte[] infoHashThe torrent's info hash.additionalTrackerURL
Extra tracker URL from the config, may be null._dest
The transient destination, when multi-dest is enabled; null otherwise or on stop._util
The util._log
Logger for the download._peerCoordinatorSet
Shared set of connected peers.trackerProblems
Last tracker error message, null if none.lastTrackerResponse
private volatile long lastTrackerResponseWhen the tracker last replied.trackerSeenPeers
private volatile int trackerSeenPeersPeers reported by the tracker._scrapeSeeders
private volatile int _scrapeSeedersSeeders from the last scrape._scrapeLeechers
private volatile int _scrapeLeechersLeechers from the last scrape._scrapePartials
private volatile int _scrapePartialsPartial completions from the last scrape._autoStoppable
private volatile boolean _autoStoppableTrue if the download may stop itself.savedUploaded
private long savedUploadedUploaded bytes saved in the stats file._startedTime
private long _startedTimeWhen the download started._comments
Comments fetched for the torrent._commentLock
Lock for the comments state.__RPCID
Counter numbering the downloads for the console._rpcID
private final int _rpcIDThis download's console id.RETRY_INITIAL_MS
private static final long RETRY_INITIAL_MSInitial startup retry delay after a failed per-torrent session creation, in milliseconds.- See Also:
RETRY_MAX_MS
private static final long RETRY_MAX_MSMaximum startup retry delay (backoff cap), in milliseconds.- See Also:
RETRY_TOTAL_MS
private static final long RETRY_TOTAL_MSGive up on a per-torrent session after this long, in milliseconds.- See Also:
_retryEvent
Startup retry event, when a per-torrent session creation failed._retryDelay
private long _retryDelayCurrent backoff delay for the next session creation retry._retryStart
private long _retryStartWall-clock time of the first failed session creation, for the give-up window._stopCount
private long _stopCountStop count, incremented bystopTorrent()so a retry event that already fired cannot reconnect a torrent stopped while its event was pending._storageCreationFailed
private volatile boolean _storageCreationFailedSet whengotMetaInfo(PeerCoordinator, MetaInfo)could not create the storage. The torrent is then left with no metainfo and possibly with some of its files already created on disk, so a restart would fetch the metainfo again only to fail on the pre-existing data location. startTorrent() refuses to start such a torrent; the user has to remove the leftover files (or the torrent) and add it again.allChecked
private boolean allCheckedTrue when every file has been checked.checking
private boolean checkingTrue while a file check is running.storageCompleted
public boolean storageCompletedWhether the torrent storage has reported completion.MIN_TOTAL_UPLOADERS
static final int MIN_TOTAL_UPLOADERSMaintain a configurable total uploader cap CoordinatorListener.- See Also:
MAX_TOTAL_UPLOADERS
static final int MAX_TOTAL_UPLOADERSMaximum peers we upload to across all torrents.- See Also:
notificationSent
private boolean notificationSentTrue once the completion notice was sent.
Constructor Details
Snark
public Snark(I2PSnarkUtil util, String torrent, String ip, int user_port, StorageListener slistener, CoordinatorListener clistener, CompleteListener complistener, PeerCoordinatorSet peerCoordinatorSet, ConnectionAcceptor connectionAcceptor, String rootDir) Create the torrent in multitorrent mode.Will not start itself. Caller must call
startTorrent()if desired.- Parameters:
util- the I2PSnarkUtiltorrent- the .torrent file name, used as the storage base nameip- the IP addressuser_port- the user portslistener- the storage listenerclistener- the coordinator listenercomplistener- the complete listenerpeerCoordinatorSet- the peer coordinator setconnectionAcceptor- the connection acceptorrootDir- the root data directory- Throws:
RuntimeException- if the storage for the torrent cannot be createdSnark.RouterException- if the torrent cannot be bound to I2P
Snark
public Snark(I2PSnarkUtil util, String torrent, String ip, int user_port, StorageListener slistener, CoordinatorListener clistener, CompleteListener complistener, PeerCoordinatorSet peerCoordinatorSet, ConnectionAcceptor connectionAcceptor, String rootDir, File baseFile) Create the torrent in multitorrent mode.Will not start itself. Caller must call startTorrent() if desired.
- Parameters:
util- the I2PSnarkUtiltorrent- the .torrent file name, used as the storage base nameip- the IP addressuser_port- the user portslistener- the storage listenerclistener- the coordinator listenercomplistener- the complete listenerpeerCoordinatorSet- the peer coordinator setconnectionAcceptor- the connection acceptorrootDir- the root data directorybaseFile- if null, use rootDir/torrentName; if non-null, use it instead- Throws:
RuntimeException- if the storage for the torrent cannot be createdSnark.RouterException- if the torrent cannot be bound to I2P
Snark
protected Snark(I2PSnarkUtil util, String torrent, byte[] ih, String trackerURL, CompleteListener complistener, PeerCoordinatorSet peerCoordinatorSet, ConnectionAcceptor connectionAcceptor, boolean ignored, String rootDir) Create the torrent in multitorrent or magnet mode, for the snark-rpc plugin.Will not start itself. Caller must call startTorrent() if desired.
- Parameters:
util- the I2PSnarkUtiltorrent- a placeholder .torrent file name, since the info hash is all that is knownih- the info hashtrackerURL- the tracker URLcomplistener- the complete listenerpeerCoordinatorSet- the peer coordinator setconnectionAcceptor- the connection acceptorignored- used to be autostartrootDir- the root data directory- Throws:
RuntimeException- if the storage for the torrent cannot be createdSnark.RouterException- if the torrent cannot be bound to I2P
Snark
public Snark(I2PSnarkUtil util, String torrent, byte[] ih, String trackerURL, CompleteListener complistener, PeerCoordinatorSet peerCoordinatorSet, ConnectionAcceptor connectionAcceptor, String rootDir) Create the torrent in multitorrent or magnet mode.Will not start itself. Caller must call startTorrent() if desired.
- Parameters:
util- the I2PSnarkUtiltorrent- a fake name for now (not a file name)ih- 20-byte info hashtrackerURL- may be nullcomplistener- the complete listenerpeerCoordinatorSet- the peer coordinator setconnectionAcceptor- the connection acceptorrootDir- the root data directory- Throws:
RuntimeException- if the storage for the torrent cannot be createdSnark.RouterException- if the torrent cannot be bound to I2P
Method Details
generateID
private byte[] generateID()Our peer ID for trackers and peers: the spoofed client identity selected for this torrent's destination when i2psnark.clientId is configured, else the legacy anonymous ID of nine zero bytes, three 0x03 bytes, then eight random bytes.- Returns:
- 20-byte peer ID
- Throws:
Snark.RouterException- if the router is shutting down
startTorrent
public void startTorrent()Start up contacting peers and querying the tracker. Blocks if tunnel is not yet open.Does nothing if the storage could not be created for a magnet: that leaves the torrent without metainfo and possibly with a partial data location on disk, and a restart would fail again on the leftover files.
- Throws:
Snark.RouterException- if the router cannot be reached or no session can be created for the torrent's listening destination
x_startTorrent
private void x_startTorrent()Starts the torrent's components.scheduleRetry
private void scheduleRetry(long delay) Schedule a retry of startTorrent() after a per-torrent session creation failure. Rescheduled on each subsequent failure; cancelled by stopTorrent() or a manual start.- Parameters:
delay- delay before the retry, in milliseconds
resetRetry
private void resetRetry()Reset the session creation retry backoff state, on success and on stop.cancelRetry
private void cancelRetry()Cancel a pending startup retry, if any.stopTorrent
public void stopTorrent()Stop contacting the tracker and talking with peers.stopTorrent
public void stopTorrent(boolean fast) Stop contacting the tracker and talking with peers.- Parameters:
fast- if true, limit the life of the unannounce threads
stopTorrent
void stopTorrent(boolean fast, boolean deferTeardown) Stop contacting the tracker and talking with peers, optionally leaving the I2P session open so the caller can dispatch unannounces before teardown.- Parameters:
fast- if true, limit the life of the unannounce threadsdeferTeardown- if true, keep the session for teardownSession()
teardownSession
void teardownSession()Destroy the I2P session for this stopped torrent. Called by stopTorrent() or, after the stop's unannounces have had a chance to dispatch, by stopAllTorrents().In single-destination mode the session is shared by every torrent, so it is only dropped once no other torrent still needs it. A transient lookup torrent never owned the shared session, so destroying one must not take it down: trackers such as zzzot submit throwaway lookup magnets and delete them again minutes later, and each delete used to disconnect every running torrent, forcing a fresh destination and a full tunnel rebuild.
awaitUnannounces
void awaitUnannounces(long ms) Wait, capped at ms, for this torrent's unannounces to dispatch.- Parameters:
ms- the time in milliseconds to wait before giving up, 0 to return immediately
getName
The file name of the .torrent file.- Returns:
- file name of .torrent file (should be full absolute path), or a fake name if in magnet mode.
getBaseName
getBaseInfo
The base name with path and error info, for error logging only.- Returns:
- base name for torrent [filtered version of getMetaInfo.getName()], or a fake name if in magnet mode, followed by path info and error message, for error logging only
getID
public byte[] getID()The peer ID.- Returns:
- always will be valid even in magnet mode
getInfoHash
public byte[] getInfoHash()The info hash.- Returns:
- always will be valid even in magnet mode
getDest
The transient multi-dest destination, or null when multi-dest is disabled or the torrent is stopped.- Returns:
- the destination, or null
getMetaInfo
getStorage
isStopped
public boolean isStopped()Check if the torrent is stopped.- Returns:
- true if stopped
isStarting
public boolean isStarting()Check if startup is in progress.- Returns:
- true if starting
setStarting
public void setStarting()Mark startup in progress.isChecking
public boolean isChecking()Check if file checking is in progress.- Returns:
- true if checking is in progress, false otherwise
getCheckingProgress
public double getCheckingProgress()The progress of file checking as a percentage. If checking is in progress, return completion 0.0 ... 1.0, else return 1.0.- Returns:
- checking progress as a percentage (0.0 to 1.0)
isAllocating
public boolean isAllocating()Check if disk allocation (ballooning) is in progress.- Returns:
- true if allocating, false otherwise
getDownloadRate
public long getDownloadRate()The current download rate in bytes per second.- Returns:
- download rate in bytes per second, or 0 if not available
getUploadRate
public long getUploadRate()The current upload rate in bytes per second.- Returns:
- upload rate in bytes per second, or 0 if not available
getDownloaded
public long getDownloaded()The total number of bytes downloaded.- Returns:
- total bytes downloaded, or 0 if not available
getUploaded
public long getUploaded()The total number of bytes uploaded.- Returns:
- total bytes uploaded, including saved uploaded if coordinator is not available
getPeerCount
public int getPeerCount()The peer count.- Returns:
- connected peers, 0 if the coordinator has not been created yet
getPeerList
getSwarmPeerCount
public int getSwarmPeerCount()Distinct swarm peers seen recently (via announce, PEX or DHT) or currently connected, for the torrent view peer count.- Returns:
- the count, 0 if no coordinator
getTrackerProblems
Not HTML escaped.- Returns:
- String returned from tracker, or null if no error
setTrackerProblems
Store the tracker problems string.- Parameters:
p- tracker error string or null
getLastTrackerResponse
public long getLastTrackerResponse()The wall-clock time of the last valid tracker announce or scrape response, or 0 if none was ever received.- Returns:
- milliseconds since epoch
setLastTrackerResponse
public void setLastTrackerResponse(long t) Record a valid tracker announce or scrape response.- Parameters:
t- milliseconds since epoch
getTrackerSeenPeers
public int getTrackerSeenPeers()The tracker seen peers count.- Returns:
- count returned from tracker
setTrackerSeenPeers
public void setTrackerSeenPeers(int p) Store the tracker seen peers count.- Parameters:
p- peer count from tracker
getScrapeSeeders
public int getScrapeSeeders()The best-known seed count from tracker scrapes.- Returns:
- the seed count, 0 if no scrape yet
getScrapeLeechers
public int getScrapeLeechers()The best-known leech count from tracker scrapes.- Returns:
- the leech count, 0 if no scrape yet
getScrapePartialSeeds
public int getScrapePartialSeeds()The best-known partial seed count from tracker scrapes.Partial seeds have some files but download nothing more (BEP 21).
- Returns:
- the partial seed count, 0 if no scrape yet or not supported
updateScrape
public void updateScrape(int seeders, int leechers) Update the best-known swarm composition from a tracker scrape (BEP 15/48).Keeps the maximum of each count, and raises the aggregate tracker seen peers to the sum when larger.
- Parameters:
seeders- the seed countleechers- the leech count
updateScrape
public void updateScrape(int seeders, int leechers, int partials) Update the best-known swarm composition from a tracker scrape (BEP 15/48/21).Keeps the maximum of each count, and raises the aggregate tracker seen peers to the sum when larger.
- Parameters:
seeders- the seed countleechers- the leech countpartials- the partial seed count, 0 if unknown
updatePiecePriorities
public void updatePiecePriorities()Recalculate piece priorities.getTotalLength
public long getTotalLength()The total length of all torrent files, padding files included.- Returns:
- total of all torrent files, or total of metainfo file if fetching magnet, or -1
getDataLength
public long getDataLength()The total length of all non-padding torrent files; equalsgetTotalLength()for torrents without BEP 47 padding files. The projected downloaded size.- Returns:
- total of all non-padding files, or -1 if unavailable
getRemainingLength
public long getRemainingLength()Bytes not yet in storage. Does NOT account for skipped files.- Returns:
- exact value. or -1 if no storage yet.
getNeeded()* pieceLength(0) isn't accurate if last piece is still needed.
getNeededLength
public long getNeededLength()Bytes still wanted. DOES account for (i.e. does not include) skipped files.- Returns:
- exact value. or -1 if no storage yet or when not running.
getSkippedLength
public long getSkippedLength()Bytes not received and set to skipped. This is not the same as the total of all skipped files, since pieces may span multiple files.- Returns:
- exact value. or 0 if no storage yet.
getNeeded
public long getNeeded()The number of pieces still missing. Does not account for (i.e. includes) skipped files.In metadata-only mode (the metainfo is known from a magnet but no Storage exists yet, which is how a zzzot hashlist lookup is answered) no piece has been received, so the whole torrent counts as needed.
- Returns:
- number of pieces still needed, or -1 if neither the metainfo nor the storage is available
getPieceLength
public int getPieceLength(int p) The piece length.- Parameters:
p- the piece number- Returns:
- metainfo piece length or 16K if fetching magnet
getPieces
public int getPieces()The number of pieces.- Returns:
- number of pieces, or -1 if the metainfo is not known yet (a magnet that has not resolved), in which case
getPieceLength(int)reports the 16 KiB placeholder length
restartAcceptor
public boolean restartAcceptor()Restart the connection acceptor.- Returns:
- true if restarted
getTrackerURL
The tracker URL.- Returns:
- trackerURL string from magnet-mode constructor, may be null
isAutoStoppable
public boolean isAutoStoppable()Check if the torrent is auto-stoppable.- Returns:
- true if auto-stoppable
setAutoStoppable
public void setAutoStoppable(boolean yes) Store whether the torrent is auto-stoppable.- Parameters:
yes- true if auto-stoppable
fatal
Aborts program abnormally.- Parameters:
s- the failure text logged and reported to the CompleteListener- Throws:
RuntimeException- always, after stopping the torrent and notifying the CompleteListener
fatal
Aborts program abnormally: logs the failure, stops the torrent, tells the CompleteListener, and throws.- Parameters:
s- the failure text logged and reported to the CompleteListenert- the cause, may be null- Throws:
RuntimeException- always, after stopping the torrent and notifying the CompleteListener
fatalRouter
Throws a unique exception class to blame the router that can be caught bySnarkManager.- Parameters:
s- the error message to log and pass to the CompleteListenert- the cause, attached to the thrown RouterException- Throws:
Snark.RouterException- always, after logging the failure, stopping the torrent and notifying the CompleteListener
peerChange
CoordinatorListener no-op.- Specified by:
peerChangein interfaceCoordinatorListener- Parameters:
coordinator- the PeerCoordinator reporting the changepeer- the peer whose state changed
gotMetaInfo
Called when the PeerCoordinator got the MetaInfo via magnet. CoordinatorListener. Create the storage, tell SnarkManager, and give the storage back to the coordinator.- Specified by:
gotMetaInfoin interfaceCoordinatorListener- Parameters:
coordinator- the PeerCoordinator that retrieved the metadatametainfo- the torrent metadata parsed out of the magnet URI- Throws:
RuntimeException- if the data location cannot be created for the metainfo that arrived
replaceMetaInfo
Call after editing torrent. Caller must ensure infohash, files, etc. did not change.- Parameters:
metainfo- the replacement metainfo describing the same torrent under new parameters such as trackers and comment metadata
storageCreateFile
StorageListener no-op.- Specified by:
storageCreateFilein interfaceStorageListener- Parameters:
storage- the torrent storage the event came fromname- the file namelength- the file length
storageAllocated
No-op; deliberately empty.- Specified by:
storageAllocatedin interfaceStorageListener- Parameters:
storage- the torrent storage the event came fromlength- the number of bytes allocated
storageChecked
StorageListener callback called when a piece check completes.- Specified by:
storageCheckedin interfaceStorageListener- Parameters:
storage- the Storage that completed the checknum- the piece numberchecked- true if the piece hash was correct
storageAllChecked
StorageListener callback called when all pieces have been checked.- Specified by:
storageAllCheckedin interfaceStorageListener- Parameters:
storage- the Storage that finished checking every piece
storageCompleted
StorageListener callback called when the torrent has completed.- Specified by:
storageCompletedin interfaceStorageListener- Parameters:
storage- the Storage that reported the download complete
isStorageCompleted
public boolean isStorageCompleted()Whether the torrent storage has completed.- Returns:
- true if the torrent storage has completed
setWantedPieces
StorageListener callback to update the coordinator's wanted piece set.- Specified by:
setWantedPiecesin interfaceStorageListener- Parameters:
storage- the Storage whose wanted piece set has changed
shutdown
public void shutdown()SnarkShutdown callback unused.- Specified by:
shutdownin interfaceShutdownListener
addMessage
StorageListener and CoordinatorListener callback.- Specified by:
addMessagein interfaceCoordinatorListener- Specified by:
addMessagein interfaceStorageListener- Parameters:
message- the message to display
overUploadLimit
public boolean overUploadLimit(int uploaders) CoordinatorListener callback to check if the total uploaders across all torrents exceeds the configured limit.- Specified by:
overUploadLimitin interfaceCoordinatorListener- Parameters:
uploaders- the number of interested uploaders on this coordinator- Returns:
- true if the global upload limit is exceeded
getRPCID
public int getRPCID()A unique ID for this torrent, useful for RPC.- Returns:
- positive value unless you wrap around
getStartedTime
public long getStartedTime()When did we start this torrent For RPC.- Returns:
- 0 if not started before. Not cleared when stopped.
getComments
The current comment set for this torrent. Not a copy. Caller MUST synch on the returned object for all operations.- Returns:
- may be null if none
addComments
isNotificationSent
public boolean isNotificationSent()Whether a completion notification has already been sent for this torrent.- Returns:
- true if a completion notification has already been sent for this torrent
setNotificationSent
public void setNotificationSent(boolean sent) Mark that a completion notification has been sent.- Parameters:
sent- true if the notification was sent
isBanned
Is the given hash banned?- Specified by:
isBannedin interfaceCoordinatorListener- Parameters:
h- the peer's destination hash, counted as bad up to the acceptor's limit- Returns:
- true if banned
ban
Ban the given hash.- Specified by:
banin interfaceCoordinatorListener- Parameters:
h- the peer's destination hash to count against the acceptor's limit