### WebTorrent Configuration and Usage Example Source: https://context7.com/aldenml/libtorrent4j/llms.txt This example demonstrates how to configure libtorrent4j for WebTorrent, including setting a STUN server, enabling DHT, configuring listen interfaces, and downloading a torrent compatible with WebTorrent trackers. ```APIDOC ## WebTorrent Configuration and Usage ### Description This example showcases the setup and usage of WebTorrent features within libtorrent4j. It covers initializing the session, configuring WebTorrent-specific settings like the STUN server and listen interfaces, and initiating a download with a WebTorrent-compatible torrent file. ### Method N/A (This is a Java code example demonstrating library usage) ### Endpoint N/A ### Parameters N/A ### Request Example ```java import org.libtorrent4j.*; import org.libtorrent4j.alerts.*; import java.io.File; public class WebTorrentExample { public static void main(String[] args) throws Exception { SessionManager session = new SessionManager(); session.addListener(new AlertListener() { @Override public int[] types() { return null; } @Override public void alert(Alert alert) { switch (alert.type()) { case ADD_TORRENT: ((AddTorrentAlert) alert).handle().resume(); break; case PEER_CONNECT: PeerConnectAlert peerAlert = (PeerConnectAlert) alert; System.out.println("Peer connected: " + peerAlert.ip()); break; case BLOCK_FINISHED: BlockFinishedAlert blockAlert = (BlockFinishedAlert) alert; int progress = (int) (blockAlert.handle().status().progress() * 100); System.out.println("Progress: " + progress + "%"); break; case TORRENT_FINISHED: System.out.println("Download complete!"); break; } } }); // Configure WebTorrent settings SettingsPack settings = new SettingsPack(); // Set STUN server for NAT traversal (ICE/WebRTC) settings.setWebtorrentStunServer("stun.l.google.com:19302"); // Enable DHT for peer discovery settings.setEnableDht(true); // Configure listen interfaces settings.listenInterfaces("0.0.0.0:6881,[::]:6881"); session.start(new SessionParams(settings)); // Load torrent with WebTorrent tracker File torrentFile = new File("webtorrent-compatible.torrent"); TorrentInfo ti = new TorrentInfo(torrentFile); session.download(ti, new File("/downloads")); TorrentHandle handle = session.find(ti.infoHash()); if (handle != null) { // Display trackers (WebTorrent uses WebSocket trackers) for (AnnounceEntry tracker : handle.trackers()) { System.out.println("Tracker: " + tracker.url()); // WebTorrent trackers use wss:// URLs } } // Keep running for download Thread.sleep(60000); session.stop(); } } ``` ### Response N/A (This is a client-side code example) ### Response Example N/A ``` -------------------------------- ### Manage Torrent Operations with TorrentHandle Source: https://context7.com/aldenml/libtorrent4j/llms.txt This example demonstrates how to control a torrent's lifecycle, including pausing, resuming, setting file priorities, managing trackers, and configuring bandwidth limits using the libtorrent4j library. ```java import org.libtorrent4j.*; import org.libtorrent4j.swig.torrent_flags_t; import java.io.File; import java.util.List; public class TorrentHandleExample { public static void main(String[] args) throws Exception { SessionManager session = new SessionManager(); session.start(); TorrentInfo ti = new TorrentInfo(new File("example.torrent")); session.download(ti, new File("/downloads")); TorrentHandle handle = session.find(ti.infoHash()); if (handle != null && handle.isValid()) { TorrentStatus status = handle.status(); System.out.println("Name: " + handle.getName()); System.out.println("Progress: " + (status.progress() * 100) + "%"); handle.pause(); handle.resume(); int numFiles = ti.numFiles(); Priority[] priorities = new Priority[numFiles]; priorities[0] = Priority.TOP_PRIORITY; for (int i = 1; i < numFiles; i++) { priorities[i] = Priority.IGNORE; } handle.prioritizeFiles(priorities); handle.setDownloadLimit(500 * 1024); handle.setUploadLimit(250 * 1024); String magnetUri = handle.makeMagnetUri(); System.out.println("Magnet: " + magnetUri); } session.stop(); } } ``` -------------------------------- ### Configure and Use WebTorrent with libtorrent4j Source: https://context7.com/aldenml/libtorrent4j/llms.txt This Java code demonstrates how to initialize libtorrent4j, configure WebTorrent-specific settings like a STUN server and DHT, and start a download. It includes an alert listener to monitor download progress and completion, and shows how to identify WebTorrent trackers. ```java import org.libtorrent4j.*; import org.libtorrent4j.alerts.*; import java.io.File; public class WebTorrentExample { public static void main(String[] args) throws Exception { SessionManager session = new SessionManager(); session.addListener(new AlertListener() { @Override public int[] types() { return null; } @Override public void alert(Alert alert) { switch (alert.type()) { case ADD_TORRENT: ((AddTorrentAlert) alert).handle().resume(); break; case PEER_CONNECT: PeerConnectAlert peerAlert = (PeerConnectAlert) alert; System.out.println("Peer connected: " + peerAlert.ip()); break; case BLOCK_FINISHED: BlockFinishedAlert blockAlert = (BlockFinishedAlert) alert; int progress = (int) (blockAlert.handle().status().progress() * 100); System.out.println("Progress: " + progress + "%"); break; case TORRENT_FINISHED: System.out.println("Download complete!"); break; } } }); // Configure WebTorrent settings SettingsPack settings = new SettingsPack(); // Set STUN server for NAT traversal (ICE/WebRTC) settings.setWebtorrentStunServer("stun.l.google.com:19302"); // Enable DHT for peer discovery settings.setEnableDht(true); // Configure listen interfaces settings.listenInterfaces("0.0.0.0:6881,[::]:6881"); session.start(new SessionParams(settings)); // Load torrent with WebTorrent tracker File torrentFile = new File("webtorrent-compatible.torrent"); TorrentInfo ti = new TorrentInfo(torrentFile); session.download(ti, new File("/downloads")); TorrentHandle handle = session.find(ti.infoHash()); if (handle != null) { // Display trackers (WebTorrent uses WebSocket trackers) for (AnnounceEntry tracker : handle.trackers()) { System.out.println("Tracker: " + tracker.url()); // WebTorrent trackers use wss:// URLs } } // Keep running for download Thread.sleep(60000); session.stop(); } } ``` -------------------------------- ### Basic Torrent Download with SessionManager in Java Source: https://context7.com/aldenml/libtorrent4j/llms.txt Demonstrates how to use SessionManager to initiate and manage a basic torrent download. It includes setting up an alert listener for progress and completion, starting the session, downloading a torrent file, and cleaning up resources. ```Java import org.libtorrent4j.*; import org.libtorrent4j.alerts.*; import java.io.File; import java.util.concurrent.CountDownLatch; public class BasicDownloadExample { public static void main(String[] args) throws Exception { // Create session manager with optional logging SessionManager session = new SessionManager(false); // Set up alert listener for download progress final CountDownLatch completionSignal = new CountDownLatch(1); session.addListener(new AlertListener() { @Override public int[] types() { return null; // Listen to all alert types } @Override public void alert(Alert alert) { switch (alert.type()) { case ADD_TORRENT: System.out.println("Torrent added successfully"); ((AddTorrentAlert) alert).handle().resume(); break; case BLOCK_FINISHED: BlockFinishedAlert a = (BlockFinishedAlert) alert; int progress = (int) (a.handle().status().progress() * 100); System.out.println("Download progress: " + progress + "%"); break; case TORRENT_FINISHED: System.out.println("Download complete!"); completionSignal.countDown(); break; } } }); // Start the session session.start(); // Load and download torrent File torrentFile = new File("example.torrent"); TorrentInfo torrentInfo = new TorrentInfo(torrentFile); File saveDirectory = new File("/downloads"); session.download(torrentInfo, saveDirectory); // Wait for completion completionSignal.await(); // Clean up session.stop(); } } ``` -------------------------------- ### Create and Configure Torrents using TorrentBuilder Source: https://context7.com/aldenml/libtorrent4j/llms.txt This example demonstrates how to initialize a TorrentBuilder, add trackers, DHT nodes, and web seeds, and apply custom file filtering. It concludes by generating the torrent metadata and saving the bencoded data to a file. ```java import org.libtorrent4j.*; import java.io.File; import java.nio.file.Files; public class TorrentBuilderExample { public static void main(String[] args) throws Exception { TorrentBuilder builder = new TorrentBuilder() .path(new File("/path/to/content")) .pieceSize(256 * 1024) .comment("Created with libtorrent4j") .creator("MyTorrentApp/1.0") .creationDate(System.currentTimeMillis() / 1000) .setPrivate(false); builder.addTracker("udp://tracker.opentrackr.org:1337", 0) .addTracker("udp://tracker.openbittorrent.com:6969", 0) .addTracker("http://tracker.example.com:8080/announce", 1); builder.addNode(new Pair<>("dht.transmissionbt.com", 6881)) .addNode(new Pair<>("router.bittorrent.com", 6881)); builder.addUrlSeed("https://example.com/downloads/"); builder.addCollection("my-collection"); builder.addSimilarTorrent(Sha1Hash.parseHex("0123456789abcdef0123456789abcdef01234567")); builder.listener(new TorrentBuilder.Listener() { @Override public boolean accept(String filename) { return !filename.startsWith(".") && !filename.endsWith(".tmp") && !filename.endsWith(".bak"); } @Override public void progress(int pieceIndex, int numPieces) { int percent = (int) ((pieceIndex / (float) numPieces) * 100); System.out.println("Hashing: " + percent + "%"); } }); TorrentBuilder.Result result = builder.generate(); Entry entry = result.entry(); byte[] torrentData = entry.bencode(); Files.write(new File("my-torrent.torrent").toPath(), torrentData); } } ``` -------------------------------- ### Perform DHT Operations in Java Source: https://context7.com/aldenml/libtorrent4j/llms.txt This example shows how to initialize the DHT, store and retrieve immutable and mutable data, and perform peer discovery. It utilizes the SessionManager class to manage the DHT lifecycle and network interactions. ```java import org.libtorrent4j.*; import java.util.ArrayList; import java.util.Arrays; public class DhtOperationsExample { public static void main(String[] args) throws Exception { SessionManager session = new SessionManager(); session.start(); // Wait for DHT to bootstrap System.out.println("Waiting for DHT to start..."); while (!session.isDhtRunning() || session.dhtNodes() < 10) { Thread.sleep(1000); System.out.println("DHT nodes: " + session.dhtNodes()); } System.out.println("DHT ready with " + session.dhtNodes() + " nodes"); // Immutable Item Operations Entry data = new Entry("Hello, DHT!"); Sha1Hash key = session.dhtPutItem(data); System.out.println("Stored immutable item with key: " + key); Entry retrieved = session.dhtGetItem(key, 30); if (retrieved != null) { System.out.println("Retrieved: " + retrieved.toString()); } // Mutable Item Operations byte[] seed = Ed25519.createSeed(); Pair keyPair = Ed25519.createKeypair(seed); byte[] publicKey = keyPair.first; byte[] privateKey = keyPair.second; Entry mutableData = new Entry("Mutable DHT data"); byte[] salt = new byte[0]; session.dhtPutItem(publicKey, privateKey, mutableData, salt); SessionManager.MutableItem mutableItem = session.dhtGetItem(publicKey, salt, 30); if (mutableItem != null) { System.out.println("Retrieved mutable: " + mutableItem.item.toString()); } // Peer Discovery Sha1Hash infoHash = Sha1Hash.parseHex("0123456789abcdef0123456789abcdef01234567"); ArrayList peers = session.dhtGetPeers(infoHash, 30); session.dhtAnnounce(infoHash, 6881, (byte) 0); session.stop(); } } ``` -------------------------------- ### Session Configuration with SessionParams in Java Source: https://context7.com/aldenml/libtorrent4j/llms.txt Illustrates how to configure libtorrent4j sessions using SessionParams. This includes restoring a session from saved state or starting with custom settings like download/upload rate limits, connection limits, and enabling DHT/LSD. ```Java import org.libtorrent4j.*; import java.io.File; import java.nio.file.Files; public class SessionConfigurationExample { public static void main(String[] args) throws Exception { SessionManager session = new SessionManager(); // Check for saved session state File stateFile = new File("session_state.dat"); if (stateFile.exists()) { // Restore session from saved state session.start(new SessionParams(stateFile)); System.out.println("Session restored from saved state"); } else { // Start with custom settings SettingsPack settings = new SettingsPack(); settings.downloadRateLimit(1024 * 1024); // 1 MB/s download limit settings.uploadRateLimit(512 * 1024); // 512 KB/s upload limit settings.connectionsLimit(200); settings.activeDownloads(3); settings.activeSeeds(5); settings.setEnableDht(true); settings.setEnableLsd(true); SessionParams params = new SessionParams(settings); session.start(params); System.out.println("Session started with custom settings"); } // ... perform operations ... // Save session state before stopping byte[] state = session.saveState(); Files.write(stateFile.toPath(), state); System.out.println("Session state saved"); session.stop(); } } ``` -------------------------------- ### Build Docker Image for Android Builds Source: https://github.com/aldenml/libtorrent4j/blob/master/README.md This command builds the Docker image required for local Android builds. It should be executed once and may take a significant amount of time. Ensure Docker is installed and running. ```bash docker build -t lt4j:latest . ``` -------------------------------- ### GET /torrent/{infoHash}/status Source: https://context7.com/aldenml/libtorrent4j/llms.txt Retrieves detailed status and progress metrics for a specific torrent handle. ```APIDOC ## GET /torrent/{infoHash}/status ### Description Retrieves comprehensive status information for a specific torrent, including progress, peer counts, and state information. ### Method GET ### Endpoint TorrentHandle.status() ### Parameters #### Path Parameters - **infoHash** (string) - Required - The unique identifier for the torrent ### Request Example N/A (Method call) ### Response #### Success Response (200) - **name** (string) - Torrent name - **progress** (float) - Completion percentage (0.0 to 1.0) - **state** (enum) - Current torrent state (e.g., downloading, seeding) - **numPeers** (int) - Number of connected peers - **numSeeds** (int) - Number of connected seeds #### Response Example { "name": "example_file.iso", "progress": 0.75, "state": "downloading", "numPeers": 12, "numSeeds": 5 } ``` -------------------------------- ### GET /session/statistics Source: https://context7.com/aldenml/libtorrent4j/llms.txt Retrieves global session-level statistics including transfer rates, DHT status, and network connectivity. ```APIDOC ## GET /session/statistics ### Description Retrieves the current session-level metrics such as download/upload rates, total data transferred, DHT node count, and firewall status. ### Method GET ### Endpoint SessionManager.stats() ### Parameters None ### Request Example N/A (Method call) ### Response #### Success Response (200) - **downloadRate** (long) - Current download rate in bytes/s - **uploadRate** (long) - Current upload rate in bytes/s - **totalDownload** (long) - Total bytes downloaded in session - **totalUpload** (long) - Total bytes uploaded in session - **dhtNodes** (int) - Number of active DHT nodes - **isFirewalled** (boolean) - Connection status regarding firewall #### Response Example { "downloadRate": 102400, "uploadRate": 51200, "totalDownload": 2048000, "totalUpload": 1024000, "dhtNodes": 150, "isFirewalled": false } ``` -------------------------------- ### GET /magnet/metadata Source: https://context7.com/aldenml/libtorrent4j/llms.txt Fetches only the metadata associated with a magnet link, returning the bencoded torrent data without downloading the actual file content. ```APIDOC ## GET /magnet/metadata ### Description Retrieves torrent metadata from a magnet URI. This is useful for inspecting torrent contents before initiating a full download. ### Method GET ### Endpoint /magnet/metadata ### Parameters #### Query Parameters - **magnetUri** (string) - Required - The magnet link to fetch metadata from. - **timeout** (integer) - Required - Maximum time in seconds to wait for metadata. ### Request Example GET /magnet/metadata?magnetUri=magnet:?xt=urn:btih:EXAMPLEINFOHASH&timeout=60 ### Response #### Success Response (200) - **torrentData** (byte[]) - The raw bencoded torrent data. #### Response Example { "torrentData": "d8:announce..." } ``` -------------------------------- ### SessionManager - Torrent Lifecycle Management Source: https://context7.com/aldenml/libtorrent4j/llms.txt The SessionManager class serves as the primary controller for managing BitTorrent sessions, including starting, stopping, and monitoring torrent downloads via alert listeners. ```APIDOC ## SessionManager.download(TorrentInfo, File) ### Description Initiates the download of a torrent file to a specified directory within the current session. ### Method POST ### Endpoint SessionManager.download(TorrentInfo, File) ### Parameters #### Path Parameters - **torrentInfo** (TorrentInfo) - Required - The metadata object representing the torrent to download. - **saveDirectory** (File) - Required - The local filesystem path where the torrent content will be saved. ### Request Example ```java File torrentFile = new File("example.torrent"); TorrentInfo torrentInfo = new TorrentInfo(torrentFile); File saveDirectory = new File("/downloads"); session.download(torrentInfo, saveDirectory); ``` ### Response #### Success Response (200) - **status** (void) - The method initiates the download process asynchronously; progress is tracked via AlertListener. ``` -------------------------------- ### Configure Session Settings with SettingsPack in Java Source: https://context7.com/aldenml/libtorrent4j/llms.txt Demonstrates how to use the SettingsPack class to control various session parameters like rate limits, connection limits, DHT configuration, and network settings. It shows how to apply these settings to a SessionManager and query the current configuration. ```Java import org.libtorrent4j.*; import org.libtorrent4j.swig.settings_pack; public class SettingsPackExample { public static void main(String[] args) { SessionManager session = new SessionManager(); session.start(); // Create and configure settings pack SettingsPack settings = new SettingsPack(); // Rate limiting settings.downloadRateLimit(2 * 1024 * 1024); // 2 MB/s settings.uploadRateLimit(1024 * 1024); // 1 MB/s // Connection settings settings.connectionsLimit(500); settings.maxPeerlistSize(4000); // Torrent queue management settings.activeDownloads(5); settings.activeSeeds(10); settings.activeLimit(20); settings.activeChecking(2); // DHT settings settings.setEnableDht(true); settings.activeDhtLimit(88); settings.setDhtBootstrapNodes( "dht.libtorrent.org:25401,த்தானrouter.bittorrent.com:6881,router.utorrent.com:6881" ); // Network interface configuration settings.listenInterfaces("0.0.0.0:6881,[::]:6881"); // WebTorrent STUN server for NAT traversal settings.setWebtorrentStunServer("stun.l.google.com:19302"); // Privacy settings settings.anonymousMode(false); settings.seedingOutgoingConnections(true); // Performance tuning settings.tickInterval(100); settings.sendBufferWatermark(512 * 1024); settings.maxQueuedDiskBytes(16 * 1024 * 1024); // Alert settings settings.alertQueueSize(5000); settings.stopTrackerTimeout(5); // Apply settings to session session.applySettings(settings); // Query current settings SettingsPack currentSettings = session.settings(); System.out.println("Download limit: " + currentSettings.downloadRateLimit() + " bytes/s"); System.out.println("Upload limit: " + currentSettings.uploadRateLimit() + " bytes/s"); System.out.println("DHT enabled: " + currentSettings.isEnableDht()); session.stop(); } } ``` -------------------------------- ### SettingsPack - Session Settings Source: https://context7.com/aldenml/libtorrent4j/llms.txt Demonstrates how to configure session settings using the SettingsPack class, including rate limits, connection limits, DHT configuration, and network settings. ```APIDOC ## SettingsPack - Session Settings ### Description The `SettingsPack` class provides fine-grained control over session behavior including rate limits, connection limits, DHT configuration, and various protocol settings. ### Method Not applicable (this is a class configuration example) ### Endpoint Not applicable ### Parameters Not applicable ### Request Example ```java import org.libtorrent4j.*; import org.libtorrent4j.swig.settings_pack; public class SettingsPackExample { public static void main(String[] args) { SessionManager session = new SessionManager(); session.start(); // Create and configure settings pack SettingsPack settings = new SettingsPack(); // Rate limiting settings.downloadRateLimit(2 * 1024 * 1024); // 2 MB/s settings.uploadRateLimit(1024 * 1024); // 1 MB/s // Connection settings settings.connectionsLimit(500); settings.maxPeerlistSize(4000); // Torrent queue management settings.activeDownloads(5); settings.activeSeeds(10); settings.activeLimit(20); settings.activeChecking(2); // DHT settings settings.setEnableDht(true); settings.activeDhtLimit(88); settings.setDhtBootstrapNodes( "dht.libtorrent.org:25401," "router.bittorrent.com:6881," "router.utorrent.com:6881" ); // Network interface configuration settings.listenInterfaces("0.0.0.0:6881,[::]:6881"); // WebTorrent STUN server for NAT traversal settings.setWebtorrentStunServer("stun.l.google.com:19302"); // Privacy settings settings.anonymousMode(false); settings.seedingOutgoingConnections(true); // Performance tuning settings.tickInterval(100); settings.sendBufferWatermark(512 * 1024); settings.maxQueuedDiskBytes(16 * 1024 * 1024); // Alert settings settings.alertQueueSize(5000); settings.stopTrackerTimeout(5); // Apply settings to session session.applySettings(settings); // Query current settings SettingsPack currentSettings = session.settings(); System.out.println("Download limit: " + currentSettings.downloadRateLimit() + " bytes/s"); System.out.println("Upload limit: " + currentSettings.uploadRateLimit() + " bytes/s"); System.out.println("DHT enabled: " + currentSettings.isEnableDht()); session.stop(); } } ``` ### Response Not applicable (this is a class configuration example) ``` -------------------------------- ### Resume Data - Save and Restore Source: https://context7.com/aldenml/libtorrent4j/llms.txt Demonstrates how to save and restore torrent state using resume data for fast resume capabilities in libtorrent4j. ```APIDOC ## Resume Data - Save and Restore Save and restore torrent state using resume data for fast resume. ### Description This section details the process of managing torrent resume data. It covers both saving the current state of a torrent and loading existing resume data to quickly resume a download. ### Method This example uses a Java program interacting with the libtorrent4j library. ### Endpoint N/A (This is a library usage example, not a direct API endpoint) ### Parameters N/A ### Request Example ```java // Java code demonstrating resume data saving and loading import org.libtorrent4j.*; import org.libtorrent4j.alerts.*; import org.libtorrent4j.swig.*; import java.io.File; import java.nio.file.Files; import java.util.concurrent.CountDownLatch; public class ResumeDataExample { public static void main(String[] args) throws Exception { SessionManager session = new SessionManager(); final CountDownLatch resumeSaved = new CountDownLatch(1); final byte[][] savedResumeData = new byte[1][]; session.addListener(new AlertListener() { @Override public int[] types() { return new int[] { AlertType.SAVE_RESUME_DATA.swig(), AlertType.SAVE_RESUME_DATA_FAILED.swig() }; } @Override public void alert(Alert alert) { if (alert.type() == AlertType.SAVE_RESUME_DATA) { SaveResumeDataAlert resumeAlert = (SaveResumeDataAlert) alert; AddTorrentParams params = resumeAlert.params(); savedResumeData[0] = params.bencode(); System.out.println("Resume data saved: " + savedResumeData[0].length + " bytes"); resumeSaved.countDown(); } else if (alert.type() == AlertType.SAVE_RESUME_DATA_FAILED) { SaveResumeDataFailedAlert failedAlert = (SaveResumeDataFailedAlert) alert; System.err.println("Failed to save resume data: " + failedAlert.error().message()); resumeSaved.countDown(); } } }); session.start(); File torrentFile = new File("example.torrent"); File saveDir = new File("/downloads"); File resumeFile = new File("example.resume"); // === Load with existing resume data === if (resumeFile.exists()) { // Use resume data for fast resume byte[] resumeData = Files.readAllBytes(resumeFile.toPath()); TorrentInfo ti = new TorrentInfo(torrentFile); session.download(ti, saveDir, resumeFile, null, null, new torrent_flags_t()); System.out.println("Started with resume data"); } else { // Fresh download TorrentInfo ti = new TorrentInfo(torrentFile); session.download(ti, saveDir); System.out.println("Started fresh download"); } TorrentHandle handle = session.find(new TorrentInfo(torrentFile).infoHash()); // === Save resume data === if (handle != null && handle.isValid()) { // Check if resume data needs saving if (handle.needSaveResumeData()) { // Request resume data (async operation) handle.saveResumeData(TorrentHandle.SAVE_INFO_DICT); // Wait for save to complete resumeSaved.await(); // Write to file if (savedResumeData[0] != null) { Files.write(resumeFile.toPath(), savedResumeData[0]); System.out.println("Resume data written to: " + resumeFile); } } // Options for saving resume data // FLUSH_DISK_CACHE - flush disk cache before saving // SAVE_INFO_DICT - include torrent metadata // ONLY_IF_MODIFIED - skip if nothing changed handle.saveResumeData( TorrentHandle.FLUSH_DISK_CACHE .or_(TorrentHandle.SAVE_INFO_DICT) ); } session.stop(); } } ``` ### Response N/A (This is a library usage example, not a direct API endpoint) ### Response Example N/A ``` -------------------------------- ### Control File and Piece Download Priorities in Java Source: https://context7.com/aldenml/libtorrent4j/llms.txt Demonstrates how to control download priorities for individual files and pieces within a torrent using libtorrent4j. This includes setting priorities for specific file types, prioritizing pieces for streaming, and managing piece deadlines. ```Java import org.libtorrent4j.*; import java.io.File; public class PriorityExample { public static void main(String[] args) throws Exception { SessionManager session = new SessionManager(); session.start(); TorrentInfo ti = new TorrentInfo(new File("multi-file.torrent")); session.download(ti, new File("/downloads")); TorrentHandle handle = session.find(ti.infoHash()); if (handle != null) { int numFiles = ti.numFiles(); int numPieces = ti.numPieces(); // === File Priorities === // Create priority array for files Priority[] filePriorities = new Priority[numFiles]; // Download only specific files for (int i = 0; i < numFiles; i++) { String fileName = ti.files().fileName(i); if (fileName.endsWith(".mp4") || fileName.endsWith(".mkv")) { filePriorities[i] = Priority.TOP_PRIORITY; // Video files first } else if (fileName.endsWith(".srt") || fileName.endsWith(".sub")) { filePriorities[i] = Priority.DEFAULT; // Subtitles normal priority } else { filePriorities[i] = Priority.IGNORE; // Skip other files } } handle.prioritizeFiles(filePriorities); // Set individual file priority handle.filePriority(0, Priority.TOP_PRIORITY); // Get current file priorities Priority[] currentFilePriorities = handle.filePriorities(); for (int i = 0; i < currentFilePriorities.length; i++) { System.out.println("File " + i + " priority: " + currentFilePriorities[i]); } // === Piece Priorities === // Prioritize first and last pieces for video preview Priority[] piecePriorities = Priority.array(Priority.DEFAULT, numPieces); piecePriorities[0] = Priority.TOP_PRIORITY; // First piece piecePriorities[numPieces - 1] = Priority.TOP_PRIORITY; // Last piece handle.prioritizePieces(piecePriorities); // Set individual piece priority handle.piecePriority(0, Priority.TOP_PRIORITY); // Get piece priority Priority p = handle.piecePriority(0); System.out.println("Piece 0 priority: " + p); // Get all piece priorities Priority[] allPiecePriorities = handle.piecePriorities(); // === Streaming Support === // Set piece deadline for time-critical streaming // Request piece 0 to be downloaded within 1000ms handle.setPieceDeadline(0, 1000); // Request piece with alert when available handle.setPieceDeadline(1, 2000, TorrentHandle.ALERT_WHEN_AVAILABLE); // Clear deadline handle.resetPieceDeadline(0); handle.clearPieceDeadlines(); // Sequential download mode for video streaming handle.setSequentialRange(0, numPieces - 1); // Check if piece is available boolean havePiece = handle.havePiece(0); System.out.println("Have piece 0: " + havePiece); // Get piece availability (number of peers with each piece) int[] availability = handle.pieceAvailability(); for (int i = 0; i < Math.min(10, availability.length); i++) { System.out.println("Piece " + i + " availability: " + availability[i]); } } session.stop(); } } ``` -------------------------------- ### POST /magnet/download Source: https://context7.com/aldenml/libtorrent4j/llms.txt Initiates a torrent download process from a magnet URI, including automatic metadata fetching and file saving. ```APIDOC ## POST /magnet/download ### Description Starts a torrent download session using a magnet URI. The session manager handles the handshake, metadata retrieval, and file download process. ### Method POST ### Endpoint /magnet/download ### Parameters #### Request Body - **magnetUri** (string) - Required - The magnet link string containing the info hash. - **saveDir** (File) - Required - The local directory path where the torrent content will be saved. - **flags** (torrent_flags_t) - Optional - Configuration flags for the torrent download. ### Request Example { "magnetUri": "magnet:?xt=urn:btih:EXAMPLEINFOHASH&dn=Example+Torrent", "saveDir": "/downloads" } ### Response #### Success Response (200) - **status** (string) - Indicates the download has been initiated. #### Response Example { "status": "download_started" } ``` -------------------------------- ### Accessing Session and Torrent Statistics with Java Source: https://context7.com/aldenml/libtorrent4j/llms.txt This Java code demonstrates how to use the libtorrent4j library to access and print detailed statistics for both the libtorrent session and individual torrents. It covers session-level data like rates and totals, and torrent-level data like progress, peers, and state. Ensure the libtorrent4j library is included as a dependency. ```java import org.libtorrent4j.*; import org.libtorrent4j.alerts.*; public class StatisticsExample { public static void main(String[] args) throws Exception { SessionManager session = new SessionManager(); session.start(); // ... add torrents ... // Session-level statistics System.out.println("=== Session Statistics ==="); System.out.println("Download rate: " + session.downloadRate() + " bytes/s"); System.out.println("Upload rate: " + session.uploadRate() + " bytes/s"); System.out.println("Total downloaded: " + session.totalDownload() + " bytes"); System.out.println("Total uploaded: " + session.totalUpload() + " bytes"); System.out.println("DHT nodes: " + session.dhtNodes()); System.out.println("Firewalled: " + session.isFirewalled()); System.out.println("External address: " + session.externalAddress()); // Detailed session stats SessionStats stats = session.stats(); System.out.println("Detailed stats: " + stats.downloadRate() + " down, " + stats.uploadRate() + " up"); // Listen endpoints for (String endpoint : session.listenEndpoints()) { System.out.println("Listening on: " + endpoint); } // Post stats alert manually session.postSessionStats(); session.postDhtStats(); // Torrent-level statistics TorrentHandle handle = /* get handle */; if (handle != null && handle.isValid()) { TorrentStatus status = handle.status(); System.out.println("\n=== Torrent Statistics ==="); System.out.println("Name: " + status.name()); System.out.println("State: " + status.state()); System.out.println("Progress: " + (status.progress() * 100) + "%"); System.out.println("Download rate: " + status.downloadRate() + " bytes/s"); System.out.println("Upload rate: " + status.uploadRate() + " bytes/s"); System.out.println("Total downloaded: " + status.totalDone() + " bytes"); System.out.println("Total wanted: " + status.totalWanted() + " bytes"); System.out.println("Total wanted done: " + status.totalWantedDone() + " bytes"); System.out.println("Peers: " + status.numPeers()); System.out.println("Seeds: " + status.numSeeds()); System.out.println("Connections: " + status.numConnections()); System.out.println("Uploads: " + status.numUploads()); System.out.println("Pieces: " + status.numPieces()); System.out.println("Finished: " + status.isFinished()); System.out.println("Seeding: " + status.isSeeding()); System.out.println("Paused: " + status.isPaused()); System.out.println("Auto managed: " + status.isAutoManaged()); System.out.println("Save path: " + status.savePath()); System.out.println("Info hash: " + status.infoHash()); System.out.println("Queue position: " + status.queuePosition()); System.out.println("Active time: " + status.activeDuration() + "s"); System.out.println("Seeding time: " + status.seedingDuration() + "s"); } session.stop(); } } ``` -------------------------------- ### Download Torrent from Magnet URI Source: https://context7.com/aldenml/libtorrent4j/llms.txt Demonstrates how to download a full torrent using a magnet link. It utilizes a SessionManager and an AlertListener to monitor the lifecycle of the torrent, including metadata acquisition and completion. ```java import org.libtorrent4j.*; import org.libtorrent4j.alerts.*; import org.libtorrent4j.swig.torrent_flags_t; import java.io.File; import java.util.concurrent.CountDownLatch; public class MagnetDownloadExample { public static void main(String[] args) throws Exception { SessionManager session = new SessionManager(); final CountDownLatch metadataReceived = new CountDownLatch(1); final CountDownLatch downloadComplete = new CountDownLatch(1); session.addListener(new AlertListener() { @Override public int[] types() { return new int[] { AlertType.ADD_TORRENT.swig(), AlertType.METADATA_RECEIVED.swig(), AlertType.TORRENT_FINISHED.swig() }; } @Override public void alert(Alert alert) { switch (alert.type()) { case ADD_TORRENT: AddTorrentAlert addAlert = (AddTorrentAlert) alert; if (addAlert.error().value() == 0) { System.out.println("Magnet link added, fetching metadata..."); addAlert.handle().resume(); } else { System.err.println("Error adding torrent: " + addAlert.error().message()); } break; case METADATA_RECEIVED: MetadataReceivedAlert metaAlert = (MetadataReceivedAlert) alert; TorrentHandle h = metaAlert.handle(); TorrentInfo ti = h.torrentFile(); System.out.println("Metadata received!"); System.out.println("Torrent name: " + ti.name()); System.out.println("Total size: " + ti.totalSize() + " bytes"); System.out.println("Files: " + ti.numFiles()); metadataReceived.countDown(); break; case TORRENT_FINISHED: System.out.println("Download complete!"); downloadComplete.countDown(); break; } } }); session.start(); String magnetUri = "magnet:?xt=urn:btih:EXAMPLEINFOHASH&dn=Example+Torrent"; File saveDir = new File("/downloads"); session.download(magnetUri, saveDir, new torrent_flags_t()); metadataReceived.await(); downloadComplete.await(); session.stop(); } } ``` -------------------------------- ### Run Android Build Script for Architecture Source: https://github.com/aldenml/libtorrent4j/blob/master/README.md This command executes a build script to compile Android binaries for a specific architecture (e.g., ARM). After running, the generated JAR files can be found in the 'build/libs' directory at the project's root. Repeat for other desired architectures. ```bash ./build-arm.sh ``` -------------------------------- ### Save and Restore Torrent Resume Data in Java Source: https://context7.com/aldenml/libtorrent4j/llms.txt This Java code demonstrates how to save and restore torrent session state using resume data. It handles both initiating a download with existing resume data for fast resume and saving the current torrent state to a file. The code utilizes libtorrent4j's SessionManager and TorrentHandle to interact with the torrent client, managing alerts for save operations and writing the bencoded resume data to a file. Dependencies include libtorrent4j and standard Java IO/NIO. ```java import org.libtorrent4j.*; import org.libtorrent4j.alerts.*; import org.libtorrent4j.swig.*; import java.io.File; import java.nio.file.Files; import java.util.concurrent.CountDownLatch; public class ResumeDataExample { public static void main(String[] args) throws Exception { SessionManager session = new SessionManager(); final CountDownLatch resumeSaved = new CountDownLatch(1); final byte[][] savedResumeData = new byte[1][]; session.addListener(new AlertListener() { @Override public int[] types() { return new int[] { AlertType.SAVE_RESUME_DATA.swig(), AlertType.SAVE_RESUME_DATA_FAILED.swig() }; } @Override public void alert(Alert alert) { if (alert.type() == AlertType.SAVE_RESUME_DATA) { SaveResumeDataAlert resumeAlert = (SaveResumeDataAlert) alert; AddTorrentParams params = resumeAlert.params(); savedResumeData[0] = params.bencode(); System.out.println("Resume data saved: " + savedResumeData[0].length + " bytes"); resumeSaved.countDown(); } else if (alert.type() == AlertType.SAVE_RESUME_DATA_FAILED) { SaveResumeDataFailedAlert failedAlert = (SaveResumeDataFailedAlert) alert; System.err.println("Failed to save resume data: " + failedAlert.error().message()); resumeSaved.countDown(); } } }); session.start(); File torrentFile = new File("example.torrent"); File saveDir = new File("/downloads"); File resumeFile = new File("example.resume"); // === Load with existing resume data === if (resumeFile.exists()) { // Use resume data for fast resume byte[] resumeData = Files.readAllBytes(resumeFile.toPath()); TorrentInfo ti = new TorrentInfo(torrentFile); session.download(ti, saveDir, resumeFile, null, null, new torrent_flags_t()); System.out.println("Started with resume data"); } else { // Fresh download TorrentInfo ti = new TorrentInfo(torrentFile); session.download(ti, saveDir); System.out.println("Started fresh download"); } TorrentHandle handle = session.find(new TorrentInfo(torrentFile).infoHash()); // === Save resume data === if (handle != null && handle.isValid()) { // Check if resume data needs saving if (handle.needSaveResumeData()) { // Request resume data (async operation) handle.saveResumeData(TorrentHandle.SAVE_INFO_DICT); // Wait for save to complete resumeSaved.await(); // Write to file if (savedResumeData[0] != null) { Files.write(resumeFile.toPath(), savedResumeData[0]); System.out.println("Resume data written to: " + resumeFile); } } // Options for saving resume data // FLUSH_DISK_CACHE - flush disk cache before saving // SAVE_INFO_DICT - include torrent metadata // ONLY_IF_MODIFIED - skip if nothing changed handle.saveResumeData( TorrentHandle.FLUSH_DISK_CACHE .or_(TorrentHandle.SAVE_INFO_DICT) ); } session.stop(); } } ``` -------------------------------- ### Configure libtorrent4j CMake Project Source: https://github.com/aldenml/libtorrent4j/blob/master/swig/CMakeLists.txt Sets up the project metadata, C++ standards, and shared library compilation targets. It defines the source files and includes necessary headers for the JNI SWIG binding. ```cmake cmake_minimum_required(VERSION 3.16) project(libtorrent4j DESCRIPTION "libtorrent JNI SWIG binding" VERSION 2.1.0 LANGUAGES CXX) add_library(torrent4j SHARED libtorrent_jni.cpp jni.h libtorrent.hpp libtorrent_jni.h) target_compile_features(torrent4j PUBLIC cxx_std_17) ``` -------------------------------- ### Handle Torrent Alerts in Java Source: https://context7.com/aldenml/libtorrent4j/llms.txt This snippet shows how to set up an alert listener for a libtorrent4j session to process various torrent-related alerts such as IP alerts, listen success, port mapping, and torrent errors. ```Java System.out.println("External IP: " + ipAlert.externalAddress()); break; case LISTEN_SUCCEEDED: ListenSucceededAlert listenAlert = (ListenSucceededAlert) alert; System.out.println("Listening on: " + listenAlert.address() + ":" + listenAlert.port()); break; case PORTMAP: PortmapAlert portAlert = (PortmapAlert) alert; System.out.println("Port mapped: " + portAlert.externalPort()); break; case TORRENT_ERROR: TorrentErrorAlert torrentError = (TorrentErrorAlert) alert; System.err.println("Torrent error: " + torrentError.error().message()); break; } } }); session.start(); // ... download torrents ... session.stop(); } } ```