Search in sources :

Example 1 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 2 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 = new File(dir, "temp");
            if (!dir.exists()) {
                if (!dir.mkdirs()) {
                    throw (new IOException("Failed to create dir '" + dir + "'"));
                }
            }
            final File torrent_file = new File(dir, sid + "_" + version + ".torrent");
            final File data_file = new File(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.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 3 with Torrent

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

the class ShareManagerImpl method getDebugName.

protected String getDebugName(ShareResource _share) {
    Torrent torrent = null;
    try {
        if (_share instanceof ShareResourceFile) {
            ShareResourceFile share = (ShareResourceFile) _share;
            torrent = share.getItem().getTorrent();
        } else if (_share instanceof ShareResourceDir) {
            ShareResourceDir share = (ShareResourceDir) _share;
            torrent = share.getItem().getTorrent();
        }
    } catch (Throwable e) {
    }
    if (torrent == null) {
        return (Debug.secretFileName(_share.getName()));
    } else {
        return (Debug.secretFileName(torrent.getName()) + "/" + ByteFormatter.encodeString(torrent.getHash()));
    }
}
Also used : Torrent(com.biglybt.pif.torrent.Torrent)

Example 4 with Torrent

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

the class RPTorrentDownloader method _process.

@Override
public RPReply _process(RPRequest request) {
    String method = request.getMethod();
    if (method.equals("download")) {
        try {
            Torrent to = delegate.download();
            RPTorrent res = RPTorrent.create(to);
            return (new RPReply(res));
        } catch (TorrentException e) {
            return (new RPReply(e));
        }
    } else if (method.equals("download[String]")) {
        try {
            Torrent to = delegate.download((String) request.getParams()[0]);
            RPTorrent res = RPTorrent.create(to);
            return (new RPReply(res));
        } catch (TorrentException e) {
            return (new RPReply(e));
        }
    }
    throw (new RPException("Unknown method: " + method));
}
Also used : Torrent(com.biglybt.pif.torrent.Torrent) RPException(com.biglybt.pifimpl.remote.RPException) RPReply(com.biglybt.pifimpl.remote.RPReply) TorrentException(com.biglybt.pif.torrent.TorrentException)

Example 5 with Torrent

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

the class RPTracker method _process.

@Override
public RPReply _process(RPRequest request) {
    String method = request.getMethod();
    Object[] params = request.getParams();
    if (method.equals("host[Torrent,boolean]")) {
        try {
            Torrent torrent = params[0] == null ? null : (Torrent) ((RPTorrent) params[0])._setLocal();
            if (torrent == null) {
                throw (new RPException("Invalid torrent"));
            }
            TrackerTorrent tt = delegate.host(torrent, ((Boolean) params[1]).booleanValue());
            RPTrackerTorrent res = RPTrackerTorrent.create(tt);
            return (new RPReply(res));
        } catch (TrackerException e) {
            return (new RPReply(e));
        }
    } else if (method.equals("getTorrents")) {
        TrackerTorrent[] torrents = delegate.getTorrents();
        RPTrackerTorrent[] res = new RPTrackerTorrent[torrents.length];
        for (int i = 0; i < res.length; i++) {
            res[i] = RPTrackerTorrent.create(torrents[i]);
        }
        return (new RPReply(res));
    }
    throw (new RPException("Unknown method: " + method));
}
Also used : TrackerException(com.biglybt.pif.tracker.TrackerException) RPTorrent(com.biglybt.pifimpl.remote.torrent.RPTorrent) Torrent(com.biglybt.pif.torrent.Torrent) TrackerTorrent(com.biglybt.pif.tracker.TrackerTorrent) TrackerTorrent(com.biglybt.pif.tracker.TrackerTorrent) RPException(com.biglybt.pifimpl.remote.RPException) RPTorrent(com.biglybt.pifimpl.remote.torrent.RPTorrent) RPReply(com.biglybt.pifimpl.remote.RPReply) RPObject(com.biglybt.pifimpl.remote.RPObject)

Aggregations

Torrent (com.biglybt.pif.torrent.Torrent)39 Download (com.biglybt.pif.download.Download)15 TOTorrent (com.biglybt.core.torrent.TOTorrent)12 URL (java.net.URL)12 DownloadManager (com.biglybt.core.download.DownloadManager)6 PluginInterface (com.biglybt.pif.PluginInterface)6 TorrentAttribute (com.biglybt.pif.torrent.TorrentAttribute)4 File (java.io.File)4 InetSocketAddress (java.net.InetSocketAddress)4 PEPeerManager (com.biglybt.core.peer.PEPeerManager)3 DiskManagerFileInfo (com.biglybt.pif.disk.DiskManagerFileInfo)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 ParameterListener (com.biglybt.core.config.ParameterListener)2 DownloadManagerState (com.biglybt.core.download.DownloadManagerState)2 PEPeer (com.biglybt.core.peer.PEPeer)2 Tag (com.biglybt.core.tag.Tag)2 VuzeFile (com.biglybt.core.vuzefile.VuzeFile)2