Search in sources :

Example 6 with Torrent

use of com.biglybt.pif.torrent.Torrent in project BiglyBT by BiglySoftware.

the class SubscriptionManagerImpl method downloadSubscription.

private void downloadSubscription(final String description, final TOTorrent torrent, final InetSocketAddress peer, byte[] subs_id, int version, String name, final downloadListener listener) {
    try {
        // testing purposes, see if local exists
        LightWeightSeed lws = LightWeightSeedManager.getSingleton().get(new HashWrapper(torrent.getHash()));
        if (lws != null) {
            log("Light weight seed found");
            listener.complete(lws.getDataLocation());
        } else {
            String sid = ByteFormatter.encodeString(subs_id);
            File dir = getSubsDir();
            dir = FileUtil.newFile(dir, "temp");
            if (!dir.exists()) {
                if (!dir.mkdirs()) {
                    throw (new IOException("Failed to create dir '" + dir + "'"));
                }
            }
            final File torrent_file = FileUtil.newFile(dir, sid + "_" + version + ".torrent");
            final File data_file = FileUtil.newFile(dir, VuzeFileHandler.getVuzeFileName(sid + "_" + version));
            PluginInterface pi = PluginInitializer.getDefaultInterface();
            final DownloadManager dm = pi.getDownloadManager();
            Download download = dm.getDownload(torrent.getHash());
            if (download == null) {
                log("Adding download for subscription '" + new String(torrent.getName()) + "'");
                boolean is_update = getSubscriptionFromSID(subs_id) != null;
                PlatformTorrentUtils.setContentTitle(torrent, "Subscription " + (is_update ? "Update" : "Download") + ": " + description + "(" + name + ")");
                // PlatformTorrentUtils.setContentThumbnail(torrent, thumbnail);
                TorrentUtils.setFlag(torrent, TorrentUtils.TORRENT_FLAG_LOW_NOISE, true);
                Torrent t = new TorrentImpl(torrent);
                t.setDefaultEncoding();
                t.writeToFile(torrent_file);
                download = dm.addDownload(t, torrent_file, data_file);
                download.setFlag(Download.FLAG_DISABLE_AUTO_FILE_MOVE, true);
                download.setFlag(Download.FLAG_DISABLE_STOP_AFTER_ALLOC, true);
                download.setBooleanAttribute(ta_subs_download, true);
                Map rd = listener.getRecoveryData();
                if (rd != null) {
                    download.setMapAttribute(ta_subs_download_rd, rd);
                }
            } else {
                log("Existing download found for subscription '" + new String(torrent.getName()) + "'");
            }
            final Download f_download = download;
            final TimerEventPeriodic[] event = { null };
            event[0] = SimpleTimer.addPeriodicEvent("SM:cancelTimer", 10 * 1000, new TimerEventPerformer() {

                private long start_time = SystemTime.getMonotonousTime();

                @Override
                public void perform(TimerEvent ev) {
                    boolean kill = false;
                    try {
                        Download download = dm.getDownload(torrent.getHash());
                        if (listener.isCancelled() || download == null) {
                            kill = true;
                        } else {
                            int state = download.getState();
                            if (state == Download.ST_ERROR) {
                                log("Download entered error state, removing");
                                kill = true;
                            } else {
                                long now = SystemTime.getMonotonousTime();
                                long running_for = now - start_time;
                                if (running_for > 10 * 60 * 1000) {
                                    log("Download hasn't completed in permitted time, removing");
                                    kill = true;
                                } else if (running_for > 4 * 60 * 1000) {
                                    if (download.getStats().getDownloaded() == 0) {
                                        log("Download has zero downloaded, removing");
                                        kill = true;
                                    }
                                } else if (running_for > 2 * 60 * 1000) {
                                    DownloadScrapeResult scrape = download.getLastScrapeResult();
                                    if (scrape == null || scrape.getSeedCount() <= 0) {
                                        log("Download has no seeds, removing");
                                        kill = true;
                                    }
                                }
                            }
                        }
                    } catch (Throwable e) {
                        log("Download failed", e);
                        kill = true;
                    }
                    if (kill && event[0] != null) {
                        try {
                            event[0].cancel();
                            if (!listener.isCancelled()) {
                                listener.failed(new SubscriptionException("Download abandoned"));
                            }
                        } finally {
                            removeDownload(f_download, true);
                            torrent_file.delete();
                        }
                    }
                }
            });
            download.addCompletionListener(new DownloadCompletionListener() {

                @Override
                public void onCompletion(Download d) {
                    listener.complete(d, torrent_file);
                }
            });
            if (download.isComplete()) {
                listener.complete(download, torrent_file);
            } else {
                download.setForceStart(true);
                if (peer != null) {
                    download.addPeerListener(new DownloadPeerListener() {

                        @Override
                        public void peerManagerAdded(Download download, PeerManager peer_manager) {
                            InetSocketAddress tcp = AddressUtils.adjustTCPAddress(peer, true);
                            InetSocketAddress udp = AddressUtils.adjustUDPAddress(peer, true);
                            log("    Injecting peer into download: " + tcp);
                            peer_manager.addPeer(tcp.getAddress().getHostAddress(), tcp.getPort(), udp.getPort(), true);
                        }

                        @Override
                        public void peerManagerRemoved(Download download, PeerManager peer_manager) {
                        }
                    });
                }
            }
        }
    } catch (Throwable e) {
        log("Failed to add download", e);
        listener.failed(e);
    }
}
Also used : Torrent(com.biglybt.pif.torrent.Torrent) TOTorrent(com.biglybt.core.torrent.TOTorrent) TorrentImpl(com.biglybt.pifimpl.local.torrent.TorrentImpl) InetSocketAddress(java.net.InetSocketAddress) LightWeightSeed(com.biglybt.core.lws.LightWeightSeed) PluginInterface(com.biglybt.pif.PluginInterface) PeerManager(com.biglybt.pif.peers.PeerManager) VuzeFile(com.biglybt.core.vuzefile.VuzeFile)

Example 7 with Torrent

use of com.biglybt.pif.torrent.Torrent in project BiglyBT by BiglySoftware.

the class SubscriptionManagerImpl method initWithCore.

protected void initWithCore(Core _core) {
    synchronized (this) {
        if (started) {
            return;
        }
        started = true;
    }
    core = _core;
    final PluginInterface default_pi = PluginInitializer.getDefaultInterface();
    rss_publisher = new SubscriptionRSSFeed(this, default_pi);
    TorrentManager tm = default_pi.getTorrentManager();
    ta_subs_download = tm.getPluginAttribute("azsubs.subs_dl");
    ta_subs_download_rd = tm.getPluginAttribute("azsubs.subs_dl_rd");
    ta_subscription_info = tm.getPluginAttribute("azsubs.subs_info");
    ta_category = tm.getAttribute(TorrentAttribute.TA_CATEGORY);
    ta_networks = tm.getAttribute(TorrentAttribute.TA_NETWORKS);
    PluginInterface dht_plugin_pi = CoreFactory.getSingleton().getPluginManager().getPluginInterfaceByClass(DHTPlugin.class);
    if (dht_plugin_pi != null) {
        dht_plugin_public = (DHTPlugin) dht_plugin_pi.getPlugin();
        /*
			if ( Constants.isCVSVersion()){

				addListener(
						new SubscriptionManagerListener()
						{
							public void
							subscriptionAdded(
								Subscription subscription )
							{
							}

							public void
							subscriptionChanged(
								Subscription		subscription )
							{
							}

							public void
							subscriptionRemoved(
								Subscription subscription )
							{
							}

							public void
							associationsChanged(
								byte[] hash )
							{
								System.out.println( "Subscriptions changed: " + ByteFormatter.encodeString( hash ));

								Subscription[] subs = getKnownSubscriptions( hash );

								for (int i=0;i<subs.length;i++){

									System.out.println( "    " + subs[i].getString());
								}
							}
						});
			}
			*/
        default_pi.getDownloadManager().addListener(new DownloadManagerListener() {

            @Override
            public void downloadAdded(Download download) {
                Torrent torrent = download.getTorrent();
                if (torrent != null) {
                    byte[] hash = torrent.getHash();
                    Object[] entry;
                    synchronized (potential_associations2) {
                        entry = (Object[]) potential_associations2.remove(new HashWrapper(hash));
                    }
                    if (entry != null) {
                        SubscriptionImpl[] subs = (SubscriptionImpl[]) entry[0];
                        String subs_str = "";
                        for (int i = 0; i < subs.length; i++) {
                            subs_str += (i == 0 ? "" : ",") + subs[i].getName();
                        }
                        log("Applying deferred asocciation for " + ByteFormatter.encodeString(hash) + " -> " + subs_str);
                        recordAssociationsSupport(hash, subs, ((Boolean) entry[1]).booleanValue());
                    }
                }
            }

            @Override
            public void downloadRemoved(Download download) {
            }
        }, false);
        default_pi.getDownloadManager().addDownloadWillBeAddedListener(new DownloadWillBeAddedListener() {

            @Override
            public void initialised(Download download) {
                Torrent torrent = download.getTorrent();
                if (torrent != null) {
                    byte[] hash = torrent.getHash();
                    HashWrapper hw = new HashWrapper(hash);
                    Object[] entry;
                    synchronized (potential_associations2) {
                        entry = (Object[]) potential_associations2.get(hw);
                    }
                    if (entry != null) {
                        SubscriptionImpl[] subs = (SubscriptionImpl[]) entry[0];
                        prepareDownload(download, subs, null);
                    } else {
                        synchronized (potential_associations3) {
                            entry = potential_associations3.get(hw);
                        }
                        if (entry != null) {
                            Subscription[] subs = (Subscription[]) entry[0];
                            SubscriptionResult[] results = (SubscriptionResult[]) entry[1];
                            prepareDownload(download, subs, results);
                        }
                    }
                }
            }
        });
        TorrentUtils.addTorrentAttributeListener(new TorrentUtils.torrentAttributeListener() {

            @Override
            public void attributeSet(TOTorrent torrent, String attribute, Object value) {
                if (attribute == TorrentUtils.TORRENT_AZ_PROP_OBTAINED_FROM) {
                    try {
                        checkPotentialAssociations(torrent.getHash(), (String) value);
                    } catch (Throwable e) {
                        Debug.printStackTrace(e);
                    }
                }
            }
        });
        DelayedTask delayed_task = UtilitiesImpl.addDelayedTask("Subscriptions", new Runnable() {

            @Override
            public void run() {
                new AEThread2("Subscriptions:delayInit", true) {

                    @Override
                    public void run() {
                        asyncInit();
                    }
                }.start();
            }

            protected void asyncInit() {
                Download[] downloads = default_pi.getDownloadManager().getDownloads();
                for (int i = 0; i < downloads.length; i++) {
                    Download download = downloads[i];
                    if (download.getBooleanAttribute(ta_subs_download)) {
                        Map rd = download.getMapAttribute(ta_subs_download_rd);
                        boolean delete_it;
                        if (rd == null) {
                            delete_it = true;
                        } else {
                            delete_it = !recoverSubscriptionUpdate(download, rd);
                        }
                        if (delete_it) {
                            removeDownload(download, true);
                        }
                    }
                }
                default_pi.getDownloadManager().addListener(new DownloadManagerListener() {

                    @Override
                    public void downloadAdded(final Download download) {
                        if (!downloadIsIgnored(download)) {
                            if (!dht_plugin_public.isInitialising()) {
                                // if new download then we want to check out its subscription status
                                lookupAssociations(download.getMapAttribute(ta_subscription_info) == null);
                            } else {
                                new AEThread2("Subscriptions:delayInit", true) {

                                    @Override
                                    public void run() {
                                        lookupAssociations(download.getMapAttribute(ta_subscription_info) == null);
                                    }
                                }.start();
                            }
                        }
                    }

                    @Override
                    public void downloadRemoved(Download download) {
                    }
                }, false);
                for (int i = 0; i < PUB_ASSOC_CONC_MAX; i++) {
                    if (publishAssociations()) {
                        break;
                    }
                }
                publishSubscriptions();
                COConfigurationManager.addParameterListener(CONFIG_MAX_RESULTS, new ParameterListener() {

                    @Override
                    public void parameterChanged(String name) {
                        final int max_results = COConfigurationManager.getIntParameter(CONFIG_MAX_RESULTS);
                        new AEThread2("Subs:max results changer", true) {

                            @Override
                            public void run() {
                                checkMaxResults(max_results);
                            }
                        }.start();
                    }
                });
                SimpleTimer.addPeriodicEvent("SubscriptionChecker", TIMER_PERIOD, new TimerEventPerformer() {

                    private int ticks;

                    @Override
                    public void perform(TimerEvent event) {
                        ticks++;
                        checkStuff(ticks);
                    }
                });
            }
        });
        delayed_task.queue();
    }
    if (isSearchEnabled()) {
        try {
            default_pi.getUtilities().registerSearchProvider(new SearchProvider() {

                private Map<Integer, Object> properties = new HashMap<>();

                {
                    properties.put(PR_NAME, MessageText.getString("ConfigView.section.Subscriptions"));
                    try {
                        URL url = MagnetURIHandler.getSingleton().registerResource(new MagnetURIHandler.ResourceProvider() {

                            @Override
                            public String getUID() {
                                return (SubscriptionManager.class.getName() + ".2");
                            }

                            @Override
                            public String getFileType() {
                                return ("png");
                            }

                            @Override
                            public byte[] getData() {
                                InputStream is = getClass().getClassLoader().getResourceAsStream("com/biglybt/ui/images/subscription_icon_1616.png");
                                if (is == null) {
                                    return (null);
                                }
                                try {
                                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                                    try {
                                        byte[] buffer = new byte[8192];
                                        while (true) {
                                            int len = is.read(buffer);
                                            if (len <= 0) {
                                                break;
                                            }
                                            baos.write(buffer, 0, len);
                                        }
                                    } finally {
                                        is.close();
                                    }
                                    return (baos.toByteArray());
                                } catch (Throwable e) {
                                    return (null);
                                }
                            }
                        });
                        properties.put(PR_ICON_URL, url.toExternalForm());
                    } catch (Throwable e) {
                        Debug.out(e);
                    }
                }

                @Override
                public SearchInstance search(Map<String, Object> search_parameters, SearchObserver observer) throws SearchException {
                    try {
                        return (searchSubscriptions(search_parameters, observer));
                    } catch (Throwable e) {
                        throw (new SearchException("Search failed", e));
                    }
                }

                @Override
                public Object getProperty(int property) {
                    return (properties.get(property));
                }

                @Override
                public void setProperty(int property, Object value) {
                    properties.put(property, value);
                }
            });
        } catch (Throwable e) {
            Debug.out("Failed to register search provider");
        }
    }
    default_pi.getUtilities().registerJSONRPCServer(new Utilities.JSONServer() {

        private List<String> methods = new ArrayList<>();

        {
            methods.add("vuze-subs-list");
        }

        @Override
        public String getName() {
            return ("Subscriptions");
        }

        @Override
        public List<String> getSupportedMethods() {
            return (methods);
        }

        @Override
        public Map call(String method, Map args) throws PluginException {
            throw (new PluginException("derp"));
        }
    });
}
Also used : Torrent(com.biglybt.pif.torrent.Torrent) TOTorrent(com.biglybt.core.torrent.TOTorrent) URL(java.net.URL) Utilities(com.biglybt.pif.utils.Utilities) StaticUtilities(com.biglybt.pif.utils.StaticUtilities) DelayedTask(com.biglybt.pif.utils.DelayedTask) PlatformTorrentUtils(com.biglybt.core.torrent.PlatformTorrentUtils) GZIPInputStream(java.util.zip.GZIPInputStream) PluginInterface(com.biglybt.pif.PluginInterface) PluginException(com.biglybt.pif.PluginException) TorrentManager(com.biglybt.pif.torrent.TorrentManager) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) TOTorrent(com.biglybt.core.torrent.TOTorrent) ParameterListener(com.biglybt.core.config.ParameterListener)

Example 8 with Torrent

use of com.biglybt.pif.torrent.Torrent in project BiglyBT by BiglySoftware.

the class DHTTrackerPlugin method getDerivedTrackMetric.

protected long getDerivedTrackMetric(Download download) {
    // metric between -100 and + 100. Note that all -ve mean 'don't do it'
    // they're just indicating different reasons
    Torrent t = download.getTorrent();
    if (t == null) {
        return (-100);
    }
    if (t.getSize() < 10 * 1024 * 1024) {
        return (-99);
    }
    DownloadAnnounceResult announce = download.getLastAnnounceResult();
    if (announce == null || announce.getResponseType() != DownloadAnnounceResult.RT_SUCCESS) {
        return (-98);
    }
    DownloadScrapeResult scrape = download.getLastScrapeResult();
    if (scrape == null || scrape.getResponseType() != DownloadScrapeResult.RT_SUCCESS) {
        return (-97);
    }
    int leechers = scrape.getNonSeedCount();
    // int seeds		= scrape.getSeedCount();
    // parg - changed to just use leecher count rather than seeds+leechers
    int total = leechers;
    if (total >= 2000) {
        return (100);
    } else if (total <= 200) {
        return (0);
    } else {
        return ((total - 200) / 4);
    }
}
Also used : Torrent(com.biglybt.pif.torrent.Torrent)

Example 9 with Torrent

use of com.biglybt.pif.torrent.Torrent in project BiglyBT by BiglySoftware.

the class DHTTrackerPlugin method addDownload.

public void addDownload(final Download download) {
    Torrent torrent = download.getTorrent();
    if (torrent == null) {
        return;
    }
    URL announce_url = torrent.getAnnounceURL();
    boolean is_decentralised = TorrentUtils.isDecentralised(announce_url);
    if (download.getFlag(Download.FLAG_LOW_NOISE) && !is_decentralised) {
        if (!announce_url.getHost().endsWith(".amazonaws.com")) {
            return;
        }
    }
    if (track_only_decentralsed) {
        if (!is_decentralised) {
            return;
        }
    }
    if (is_running) {
        String[] networks = download.getListAttribute(ta_networks);
        if (networks != null) {
            boolean public_net = false;
            for (int i = 0; i < networks.length; i++) {
                if (networks[i].equalsIgnoreCase("Public")) {
                    public_net = true;
                    break;
                }
            }
            if (public_net && !torrent.isPrivate()) {
                boolean our_download = torrent.wasCreatedByUs();
                long delay;
                if (our_download) {
                    if (download.getCreationTime() > start_time) {
                        delay = 0;
                    } else {
                        delay = plugin_interface.getUtilities().getCurrentSystemTime() + INTERESTING_INIT_MIN_OURS + random.nextInt(INTERESTING_INIT_RAND_OURS);
                    }
                } else {
                    int min;
                    int rand;
                    if (TorrentUtils.isDecentralised(torrent.getAnnounceURL())) {
                        min = INTERESTING_DHT_INIT_MIN;
                        rand = INTERESTING_DHT_INIT_RAND;
                    } else {
                        min = INTERESTING_INIT_MIN_OTHERS;
                        rand = INTERESTING_INIT_RAND_OTHERS;
                    }
                    delay = plugin_interface.getUtilities().getCurrentSystemTime() + min + random.nextInt(rand);
                }
                try {
                    this_mon.enter();
                    interesting_downloads.put(download, new Long(delay));
                } finally {
                    this_mon.exit();
                }
            }
        }
        download.addAttributeListener(DHTTrackerPlugin.this, ta_networks, DownloadAttributeListener.WRITTEN);
        download.addAttributeListener(DHTTrackerPlugin.this, ta_peer_sources, DownloadAttributeListener.WRITTEN);
        download.addTrackerListener(DHTTrackerPlugin.this);
        download.addListener(DHTTrackerPlugin.this);
        checkDownloadForRegistration(download, true);
    } else {
        if (torrent.isDecentralised()) {
            download.addListener(new DownloadListener() {

                @Override
                public void stateChanged(final Download download, int old_state, int new_state) {
                    int state = download.getState();
                    if (state == Download.ST_DOWNLOADING || state == Download.ST_SEEDING) {
                        download.setAnnounceResult(new DownloadAnnounceResult() {

                            @Override
                            public Download getDownload() {
                                return (download);
                            }

                            @Override
                            public int getResponseType() {
                                return (DownloadAnnounceResult.RT_ERROR);
                            }

                            @Override
                            public int getReportedPeerCount() {
                                return (0);
                            }

                            @Override
                            public int getSeedCount() {
                                return (0);
                            }

                            @Override
                            public int getNonSeedCount() {
                                return (0);
                            }

                            @Override
                            public String getError() {
                                return ("Distributed Database Offline");
                            }

                            @Override
                            public URL getURL() {
                                return (download.getTorrent().getAnnounceURL());
                            }

                            @Override
                            public DownloadAnnounceResultPeer[] getPeers() {
                                return (new DownloadAnnounceResultPeer[0]);
                            }

                            @Override
                            public long getTimeToWait() {
                                return (0);
                            }

                            @Override
                            public Map getExtensions() {
                                return (null);
                            }
                        });
                    }
                }

                @Override
                public void positionChanged(Download download, int oldPosition, int newPosition) {
                }
            });
            download.setScrapeResult(new DownloadScrapeResult() {

                @Override
                public Download getDownload() {
                    return (download);
                }

                @Override
                public int getResponseType() {
                    return (DownloadScrapeResult.RT_ERROR);
                }

                @Override
                public int getSeedCount() {
                    return (-1);
                }

                @Override
                public int getNonSeedCount() {
                    return (-1);
                }

                @Override
                public long getScrapeStartTime() {
                    return (SystemTime.getCurrentTime());
                }

                @Override
                public void setNextScrapeStartTime(long nextScrapeStartTime) {
                }

                @Override
                public long getNextScrapeStartTime() {
                    return (-1);
                }

                @Override
                public String getStatus() {
                    return ("Distributed Database Offline");
                }

                @Override
                public URL getURL() {
                    return (download.getTorrent().getAnnounceURL());
                }
            });
        }
    }
}
Also used : Torrent(com.biglybt.pif.torrent.Torrent) URL(java.net.URL)

Example 10 with Torrent

use of com.biglybt.pif.torrent.Torrent in project BiglyBT by BiglySoftware.

the class DHTTrackerPlugin method processNonRegistrations.

protected void processNonRegistrations() {
    Download ready_download = null;
    long ready_download_next_check = -1;
    long now = plugin_interface.getUtilities().getCurrentSystemTime();
    // unfortunately getting scrape results can acquire locks and there is a vague
    // possibility of deadlock here, so pre-fetch the scrape results
    List<Download> to_scrape = new ArrayList<>();
    try {
        this_mon.enter();
        Iterator<Download> it = interesting_downloads.keySet().iterator();
        while (it.hasNext() && ready_download == null) {
            Download download = it.next();
            Torrent torrent = download.getTorrent();
            if (torrent == null) {
                continue;
            }
            int[] run_data = running_downloads.get(download);
            if (run_data == null || run_data[0] == REG_TYPE_DERIVED) {
                // looks like we'll need the scrape below
                to_scrape.add(download);
            }
        }
    } finally {
        this_mon.exit();
    }
    Map<Download, DownloadScrapeResult> scrapes = new HashMap<>();
    for (int i = 0; i < to_scrape.size(); i++) {
        Download download = (Download) to_scrape.get(i);
        scrapes.put(download, download.getLastScrapeResult());
    }
    try {
        this_mon.enter();
        Iterator<Download> it = interesting_downloads.keySet().iterator();
        while (it.hasNext() && ready_download == null) {
            Download download = it.next();
            Torrent torrent = download.getTorrent();
            if (torrent == null) {
                continue;
            }
            int[] run_data = running_downloads.get(download);
            if (run_data == null || run_data[0] == REG_TYPE_DERIVED) {
                boolean force = torrent.wasCreatedByUs();
                if (!force) {
                    if (interesting_pub_max > 0 && interesting_published > interesting_pub_max) {
                        continue;
                    }
                    DownloadScrapeResult scrape = (DownloadScrapeResult) scrapes.get(download);
                    if (scrape == null) {
                        continue;
                    }
                    if (scrape.getSeedCount() + scrape.getNonSeedCount() > NUM_WANT) {
                        continue;
                    }
                }
                long target = ((Long) interesting_downloads.get(download)).longValue();
                long check_period = TorrentUtils.isDecentralised(torrent.getAnnounceURL()) ? INTERESTING_DHT_CHECK_PERIOD : INTERESTING_CHECK_PERIOD;
                if (target <= now) {
                    ready_download = download;
                    ready_download_next_check = now + check_period;
                    interesting_downloads.put(download, new Long(ready_download_next_check));
                } else if (target - now > check_period) {
                    interesting_downloads.put(download, new Long(now + (target % check_period)));
                }
            }
        }
    } finally {
        this_mon.exit();
    }
    if (ready_download != null) {
        final Download f_ready_download = ready_download;
        final Torrent torrent = ready_download.getTorrent();
        if (ready_download.getFlag(Download.FLAG_METADATA_DOWNLOAD)) {
            try {
                this_mon.enter();
                interesting_downloads.remove(f_ready_download);
            } finally {
                this_mon.exit();
            }
        } else if (dht.isDiversified(torrent.getHash())) {
            try {
                this_mon.enter();
                interesting_downloads.remove(f_ready_download);
            } finally {
                this_mon.exit();
            }
        } else {
            // System.out.println( "presence query for " + ready_download.getName());
            final long start = now;
            final long f_next_check = ready_download_next_check;
            dht.get(torrent.getHash(), "Presence query for '" + ready_download.getName() + "'", (byte) 0, INTERESTING_AVAIL_MAX, ANNOUNCE_TIMEOUT, false, false, new DHTPluginOperationListener() {

                private boolean diversified;

                private int leechers = 0;

                private int seeds = 0;

                private int i2p_leechers = 0;

                private int i2p_seeds = 0;

                @Override
                public boolean diversified() {
                    diversified = true;
                    return (false);
                }

                @Override
                public void starts(byte[] key) {
                }

                @Override
                public void valueRead(DHTPluginContact originator, DHTPluginValue value) {
                    boolean is_leecher = (value.getFlags() & DHTPlugin.FLAG_DOWNLOADING) == 1;
                    if (is_leecher) {
                        leechers++;
                    } else {
                        seeds++;
                    }
                    try {
                        String[] tokens = new String(value.getValue()).split(";");
                        for (int i = 1; i < tokens.length; i++) {
                            String token = tokens[i].trim();
                            if (token.length() > 0) {
                                if (!Character.isDigit(token.charAt(0))) {
                                    String flag_str = token;
                                    if (flag_str.contains("I")) {
                                        if (is_leecher) {
                                            i2p_leechers++;
                                        } else {
                                            i2p_seeds++;
                                        }
                                    }
                                }
                            }
                        }
                    } catch (Throwable e) {
                    }
                }

                @Override
                public void valueWritten(DHTPluginContact target, DHTPluginValue value) {
                }

                @Override
                public void complete(byte[] key, boolean timeout_occurred) {
                    // System.out.println( "    presence query for " + f_ready_download.getName() + "->" + total + "/div = " + diversified );
                    int total = leechers + seeds;
                    log(f_ready_download, "Presence query: availability=" + (total == INTERESTING_AVAIL_MAX ? (INTERESTING_AVAIL_MAX + "+") : (total + "")) + ",div=" + diversified + " (elapsed=" + TimeFormatter.formatColonMillis(SystemTime.getCurrentTime() - start) + ")");
                    if (diversified) {
                        try {
                            this_mon.enter();
                            interesting_downloads.remove(f_ready_download);
                        } finally {
                            this_mon.exit();
                        }
                    } else if (total < INTERESTING_AVAIL_MAX) {
                        try {
                            this_mon.enter();
                            interesting_downloads.remove(f_ready_download);
                        } finally {
                            this_mon.exit();
                        }
                        interesting_published++;
                        if (!disable_put) {
                            dht.put(torrent.getHash(), "Presence store for '" + f_ready_download.getName() + "'", // port 0, no connections
                            "0".getBytes(), (byte) 0, new DHTPluginOperationListener() {

                                @Override
                                public boolean diversified() {
                                    return (true);
                                }

                                @Override
                                public void starts(byte[] key) {
                                }

                                @Override
                                public void valueRead(DHTPluginContact originator, DHTPluginValue value) {
                                }

                                @Override
                                public void valueWritten(DHTPluginContact target, DHTPluginValue value) {
                                }

                                @Override
                                public void complete(byte[] key, boolean timeout_occurred) {
                                }
                            });
                        }
                    }
                    try {
                        this_mon.enter();
                        int[] run_data = running_downloads.get(f_ready_download);
                        if (run_data == null) {
                            run_data = run_data_cache.get(f_ready_download);
                        }
                        if (run_data != null) {
                            if (total < INTERESTING_AVAIL_MAX) {
                                run_data[1] = seeds;
                                run_data[2] = leechers;
                                run_data[3] = total;
                            } else {
                                run_data[1] = Math.max(run_data[1], seeds);
                                run_data[2] = Math.max(run_data[2], leechers);
                            }
                            run_data[4] = (int) (SystemTime.getCurrentTime() / 1000);
                        }
                    } finally {
                        this_mon.exit();
                    }
                    if (i2p_seeds + i2p_leechers > 0) {
                        int[] details = (int[]) f_ready_download.getUserData(DOWNLOAD_USER_DATA_I2P_SCRAPE_KEY);
                        if (details == null) {
                            details = new int[] { i2p_seeds, i2p_leechers };
                            f_ready_download.setUserData(DOWNLOAD_USER_DATA_I2P_SCRAPE_KEY, details);
                        } else {
                            details[0] = Math.max(details[0], i2p_seeds);
                            details[1] = Math.max(details[1], i2p_leechers);
                        }
                    }
                    f_ready_download.setScrapeResult(new DownloadScrapeResult() {

                        @Override
                        public Download getDownload() {
                            return (null);
                        }

                        @Override
                        public int getResponseType() {
                            return (DownloadScrapeResult.RT_SUCCESS);
                        }

                        @Override
                        public int getSeedCount() {
                            return (seeds);
                        }

                        @Override
                        public int getNonSeedCount() {
                            return (leechers);
                        }

                        @Override
                        public long getScrapeStartTime() {
                            return (SystemTime.getCurrentTime());
                        }

                        @Override
                        public void setNextScrapeStartTime(long nextScrapeStartTime) {
                        }

                        @Override
                        public long getNextScrapeStartTime() {
                            return (f_next_check);
                        }

                        @Override
                        public String getStatus() {
                            return ("OK");
                        }

                        @Override
                        public URL getURL() {
                            URL url_to_report = torrent.isDecentralised() ? torrent.getAnnounceURL() : DEFAULT_URL;
                            return (url_to_report);
                        }
                    });
                }
            });
        }
    }
}
Also used : DHTPluginValue(com.biglybt.plugin.dht.DHTPluginValue) Torrent(com.biglybt.pif.torrent.Torrent) DHTPluginContact(com.biglybt.plugin.dht.DHTPluginContact) URL(java.net.URL) DHTPluginOperationListener(com.biglybt.plugin.dht.DHTPluginOperationListener)

Aggregations

Torrent (com.biglybt.pif.torrent.Torrent)41 Download (com.biglybt.pif.download.Download)16 TOTorrent (com.biglybt.core.torrent.TOTorrent)13 URL (java.net.URL)12 PluginInterface (com.biglybt.pif.PluginInterface)7 DownloadManager (com.biglybt.core.download.DownloadManager)6 TorrentAttribute (com.biglybt.pif.torrent.TorrentAttribute)5 File (java.io.File)5 Tag (com.biglybt.core.tag.Tag)4 InetSocketAddress (java.net.InetSocketAddress)4 DownloadManagerState (com.biglybt.core.download.DownloadManagerState)3 PEPeerManager (com.biglybt.core.peer.PEPeerManager)3 TrackerTorrent (com.biglybt.pif.tracker.TrackerTorrent)3 TorrentImpl (com.biglybt.pifimpl.local.torrent.TorrentImpl)3 RPException (com.biglybt.pifimpl.remote.RPException)3 RPReply (com.biglybt.pifimpl.remote.RPReply)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3 ParameterListener (com.biglybt.core.config.ParameterListener)2 PEPeer (com.biglybt.core.peer.PEPeer)2