aldenml / libtorrent4j

libtorrent for java, a swig Java interface for libtorrent
http://libtorrent4j.org
Other
204 stars 31 forks source link

Piece Priority behaves erratically #233

Open nishantkr18 opened 1 year ago

nishantkr18 commented 1 year ago

Piece priority of a torrent does not change if I rerun the code with a changed priority and a partially downloaded file.

To test it out, run the code as it is, then stop it and rerun with a changed priority.

Is this behavior expected? Maybe I am missing something..

Here's the code I use for this issue:

import org.libtorrent4j.AlertListener;
import org.libtorrent4j.Entry;
import org.libtorrent4j.Priority;
import org.libtorrent4j.SessionManager;
import org.libtorrent4j.TorrentHandle;
import org.libtorrent4j.TorrentInfo;
import org.libtorrent4j.alerts.*;

import java.io.File;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * To test issue https://github.com/frostwire/frostwire-jlibtorrent/issues/195
 *
 * @author gubatron
 * @author aldenml
 */
public final class DownloadTorrent {

    public static void main(String[] args) throws Throwable {

        final String magnet = "magnet:?xt=urn:btih:5a4140bd59d66bcac57cf05af4a8fab4ebcae1c1&dn=Avengers%20Endgame%20(2019)%20%5BBluRay%5D%20%5B720p%5D&tr=udp://tracker.internetwarriors.net:1337/announce&tr=udp://tracker.opentrackr.org:1337/announce&tr=udp://p4p.arenabg.ch:1337/announce&tr=udp://tracker.openbittorrent.com:6969/announce&tr=udp://www.torrent.eu.org:451/announce&tr=udp://tracker.torrent.eu.org:%20451/announce&tr=udp://retracker.lanta-net.ru:2710/announce&tr=udp://open.stealth.si:80/announce&tr=udp://exodus.desync.com:6969/announce&tr=udp://tracker.tiny-vps.com:6969/announce";

        final SessionManager s = new SessionManager();

        startdl(magnet, s);

        System.in.read();
        s.stop();
    }

    private static void log(String s) {
        System.out.println(s);
    }

    private static void startdl(String magnetLink, SessionManager sm) throws InterruptedException {
        //Torrent dbTorrent = torrentService.findByTorrentName(name);
        String link = magnetLink;//dbTorrent.getPathToTorrent();
        File saveDir = new File("torrents/");
        if (!saveDir.exists()) {
            saveDir.mkdirs();
        }
        final SessionManager s = sm;//storrent.getSessionManager();
        AlertListener l = new AlertListener() {
            private int grade = 0;

            @Override
            public int[] types() {
                return null;
            }

            @Override
            public void alert(Alert<?> alert) {
                AlertType type = alert.type();
                switch (type) {
                    case ADD_TORRENT:
                        //((AddTorrentAlert) alert).handle().setFlags(TorrentFlags.SEQUENTIAL_DOWNLOAD);
                        System.out.println("ADD_TORRENT");
                        TorrentHandle th = ((AddTorrentAlert) alert).handle();
                        th.resume();

                        Priority[] priorities = th.piecePriorities();

                        for (int i = 0; i < priorities.length; i++) {
                            if (i > 100 && i < 150) {
                                priorities[i] = Priority.TOP_PRIORITY;
                                log(String.valueOf(i));
                            }
                            else{
                                priorities[i] = Priority.IGNORE;
                            }
                        }

                        th.prioritizePieces(priorities);
                        Priority[] temp = th.piecePriorities();
                        for(int i=0; i<temp.length; i++){
                            if(temp[i] != priorities[i]){
                                log("error");
                            }
                        }

                        break;
                    case PIECE_FINISHED:
                        // int progress = (int) (((PieceFinishedAlert) alert).handle().status().progress() * 100);
                        // if (grade < progress / 20) {
                        //     int index = (int) (((PieceFinishedAlert) alert).pieceIndex());
                        //     log("index: " + index);
                        //     grade += 1;
                        //     s.downloadRate();
                        //     log(progress + " %  downloaded");
                        // }
                        int index = (int) (((PieceFinishedAlert) alert).pieceIndex());
                        System.out.println("PIECE_FINISHED: " + index);
                        break;
                    case TORRENT_FINISHED:
                        grade = 0;
                        ((TorrentFinishedAlert) alert).handle().pause();
                        System.out.println("TORRENT_FINISHED");
                        break;
                    // case TORRENT_ERROR:
                    //     log(((TorrentErrorAlert) alert).what());
                    //     log("is paused = " + ((TorrentErrorAlert) alert).handle().status());
                    //     break;
                    // case BLOCK_FINISHED:
                    //     System.out.println("HERE: " + ((BlockFinishedAlert) alert).handle().status().progress());
                    //     progress = (int) (((BlockFinishedAlert) alert).handle().status().progress() * 100);
                    //     if (grade < progress / 20) {
                    //         int index = (int) (((BlockFinishedAlert) alert).pieceIndex());
                    //         log("index: " + index);
                    //         grade += 1;
                    //         s.downloadRate();
                    //         log(progress + " %  downloaded");
                    //     }
                    //     System.out.println("BLOCK_FINISHED");
                    //     break;
                    // case STATE_UPDATE:
                    //     log(((StateUpdateAlert) alert).message());
                    //     break;
                    case METADATA_RECEIVED:
                        log("metadata received");
                        TorrentHandle th2 = ((MetadataReceivedAlert) alert).handle();

                        break;
                    // case DHT_ERROR:
                    //     log("dht error");
                    //     log(((DhtErrorAlert) alert).message());
                    //     break;
                    default:
                        break;
                }
            }
        };
        s.addListener(l);
        if (s.isRunning() != true)
            s.start();
        if (link.startsWith("magnet:?")) {
            // waitForNodesInDHT(s);
            byte[] data = s.fetchMagnet(link, 30, new File("/tmp"));
            if(data == null) return;
            TorrentInfo ti = TorrentInfo.bdecode(data);
            log(Entry.bdecode(data).toString());
            log("is valid ? =" + ti.isValid());
            s.download(ti, saveDir);
            // s.downloadRateLimit(100);
            // s.uploadRateLimit(100);
            log("torrent added with name = " + ti.name());
            //storrent.addTh(s.find(ti.infoHash()), name);
            log(s.find(ti.infoHash()).isValid() + " isvalid");
            log("torrent added to session");
            //this.videoname = ti.name();
            while (true) {
                TimeUnit.SECONDS.sleep(1);
                log(s.find(ti.infoHash()).status().state() + " state");
                // log(s.find(ti.infoHash()).status().pieces() + " pieces");
                log(s.find(ti.infoHash()).status().downloadRate() + " download rate");
                log(s.find(ti.infoHash()).status().progress() * 100 + " progress");
            }
        }
    }
}
aldenml commented 1 year ago

Hi @nishantkr18, to better control the priorities and resume state, you need to use the more elaborated download override, see https://github.com/aldenml/libtorrent4j/blob/004ad972f2cf1c3a5ae8cc746ab40113827f8d49/src/main/java/org/libtorrent4j/SessionManager.java#L487

Let me know if this answer your question. Thanks for trying this library.