Search in sources :

Example 11 with Torrent

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

the class ShareHosterPlugin method resourceAdded.

@Override
public void resourceAdded(final ShareResource resource) {
    log.log(LoggerChannel.LT_INFORMATION, "Resource added:".concat(resource.getName()));
    try {
        resource.addDeletionListener(new ShareResourceWillBeDeletedListener() {

            @Override
            public void resourceWillBeDeleted(ShareResource resource) throws ShareResourceDeletionVetoException {
                canResourceBeDeleted(resource);
            }
        });
        Download old_download = null;
        Download new_download = null;
        int type = resource.getType();
        if (type == ShareResource.ST_FILE) {
            ShareResourceFile file_resource = (ShareResourceFile) resource;
            ShareItem item = file_resource.getItem();
            Torrent torrent = item.getTorrent();
            old_download = download_manager.getDownload(torrent);
            if (old_download == null) {
                new_download = addDownload(resource, torrent, item.getTorrentFile(), file_resource.getFile());
            }
        } else if (type == ShareResource.ST_DIR) {
            ShareResourceDir dir_resource = (ShareResourceDir) resource;
            ShareItem item = dir_resource.getItem();
            Torrent torrent = item.getTorrent();
            old_download = download_manager.getDownload(torrent);
            if (old_download == null) {
                new_download = addDownload(resource, torrent, item.getTorrentFile(), dir_resource.getDir());
            }
        }
        final Download f_old_download = old_download;
        final Download f_new_download = new_download;
        ShareResourceListener resource_listneer = new ShareResourceListener() {

            @Override
            public void shareResourceChanged(ShareResource resource, ShareResourceEvent event) {
                Download download = f_old_download == null ? f_new_download : f_old_download;
                int type = event.getType();
                if (type == ShareResourceEvent.ET_ATTRIBUTE_CHANGED) {
                    TorrentAttribute attribute = (TorrentAttribute) event.getData();
                    // System.out.println( "sh: res -> ds: " + attribute.getName() + "/" + resource.getAttribute( attribute ));
                    download.setAttribute(attribute, resource.getAttribute(attribute));
                } else if (type == ShareResourceEvent.ET_PROPERTY_CHANGED) {
                    String[] entry = (String[]) event.getData();
                    String key = entry[0];
                    if (key.equals(ShareManager.PR_TAGS)) {
                        if (!event.isInternal()) {
                            String new_tags_str = entry[2];
                            Set<Tag> new_tags = decodeTags(new_tags_str);
                            com.biglybt.core.download.DownloadManager core_dm = PluginCoreUtils.unwrap(download);
                            Set<Tag> existing = new HashSet<>(tag_manager.getTagsForTaggable(TagType.TT_DOWNLOAD_MANUAL, core_dm));
                            for (Tag tag : new_tags) {
                                existing.remove(tag);
                                if (!tag.hasTaggable(core_dm)) {
                                    tag.addTaggable(core_dm);
                                }
                            }
                            for (Tag tag : existing) {
                                boolean[] auto = tag.isTagAuto();
                                if (!auto[0]) {
                                    tag.removeTaggable(core_dm);
                                }
                            }
                        }
                    }
                }
            }
        };
        DownloadAttributeListener attribute_listener = new DownloadAttributeListener() {

            @Override
            public void attributeEventOccurred(Download d, TorrentAttribute attr, int event_type) {
                resource.setAttribute(attr, d.getAttribute(attr));
            }
        };
        if (old_download != null) {
            resource.addChangeListener(resource_listneer);
            old_download.addAttributeListener(attribute_listener, plugin_interface.getTorrentManager().getAttribute(TorrentAttribute.TA_CATEGORY), DownloadAttributeListener.WRITTEN);
            synchronized (taggable_map) {
                taggable_map.put(PluginCoreUtils.unwrap(old_download), resource);
            }
        } else if (new_download != null) {
            resource_dl_map.put(resource, new_download);
            resource.addChangeListener(resource_listneer);
            TorrentAttribute[] attributes = resource.getAttributes();
            for (int i = 0; i < attributes.length; i++) {
                TorrentAttribute ta = attributes[i];
                new_download.setAttribute(ta, resource.getAttribute(ta));
            }
            new_download.addAttributeListener(attribute_listener, plugin_interface.getTorrentManager().getAttribute(TorrentAttribute.TA_CATEGORY), DownloadAttributeListener.WRITTEN);
            synchronized (taggable_map) {
                taggable_map.put(PluginCoreUtils.unwrap(new_download), resource);
            }
            boolean persistent = resource.isPersistent();
            Torrent dl_torrent = new_download.getTorrent();
            if (dl_torrent != null) {
                TrackerTorrent tt = tracker.host(dl_torrent, persistent);
                if (!persistent) {
                    tt.addRemovalListener(new TrackerTorrentWillBeRemovedListener() {

                        @Override
                        public void torrentWillBeRemoved(TrackerTorrent tt) throws TrackerTorrentRemovalVetoException {
                            if (tt != torrent_being_removed) {
                                throw (new TrackerTorrentRemovalVetoException(MessageText.getString("plugin.sharing.torrent.remove.veto")));
                            }
                        }
                    });
                }
                resource_tt_map.put(resource, tt);
            }
            if (!persistent) {
                new_download.addDownloadWillBeRemovedListener(new DownloadWillBeRemovedListener() {

                    @Override
                    public void downloadWillBeRemoved(Download dl) throws DownloadRemovalVetoException {
                        if (dl != download_being_removed) {
                            throw (new DownloadRemovalVetoException(MessageText.getString("plugin.sharing.download.remove.veto")));
                        }
                    }
                });
            }
        }
    } catch (Throwable e) {
        Debug.printStackTrace(e);
    }
}
Also used : TrackerTorrent(com.biglybt.pif.tracker.TrackerTorrent) Torrent(com.biglybt.pif.torrent.Torrent) TrackerTorrent(com.biglybt.pif.tracker.TrackerTorrent) TrackerTorrentWillBeRemovedListener(com.biglybt.pif.tracker.TrackerTorrentWillBeRemovedListener) TorrentAttribute(com.biglybt.pif.torrent.TorrentAttribute) TrackerTorrentRemovalVetoException(com.biglybt.pif.tracker.TrackerTorrentRemovalVetoException) Tag(com.biglybt.core.tag.Tag)

Example 12 with Torrent

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

the class LocalTrackerPlugin method downloadAdded.

@Override
public void downloadAdded(Download download) {
    try {
        mon.enter();
        Torrent torrent = download.getTorrent();
        if (torrent == null) {
            return;
        }
        if (TorrentUtils.isReallyPrivate(PluginCoreUtils.unwrap(torrent))) {
            log.log("Not tracking " + download.getName() + ": torrent is private");
            return;
        }
        String[] networks = download.getListAttribute(ta_networks);
        boolean public_net = false;
        if (networks != null) {
            for (int i = 0; i < networks.length; i++) {
                if (networks[i].equalsIgnoreCase("Public")) {
                    public_net = true;
                    break;
                }
            }
        }
        if (!public_net) {
            log.log("Not tracking " + download.getName() + ": torrent has no public network");
            return;
        }
        if (enabled.getValue()) {
            log.log("Tracking " + download.getName());
        }
        long[] data = downloads.get(download);
        if (data == null) {
            data = new long[4];
            downloads.put(download, data);
        } else {
            data[0] = 0;
        }
        download.addListener(this);
    } finally {
        mon.exit();
    }
}
Also used : Torrent(com.biglybt.pif.torrent.Torrent)

Example 13 with Torrent

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

the class RelatedContentManager method publish.

private boolean publish(final DownloadInfo from_info, final DownloadInfo to_info) throws Exception {
    final DHTPluginInterface dht_plugin = selectDHT(from_info.getNetworksInternal());
    if (dht_plugin == null) {
        return (false);
    }
    final String from_hash = ByteFormatter.encodeString(from_info.getHash());
    final String to_hash = ByteFormatter.encodeString(to_info.getHash());
    final byte[] key_bytes = ("az:rcm:assoc:" + from_hash).getBytes("UTF-8");
    String title = to_info.getTitle();
    if (title.length() > MAX_TITLE_LENGTH) {
        title = title.substring(0, MAX_TITLE_LENGTH);
    }
    Map<String, Object> map = new HashMap<>();
    map.put("d", title);
    map.put("r", new Long(Math.abs(to_info.getRand() % 1000)));
    String tracker = to_info.getTracker();
    if (tracker == null) {
        map.put("h", to_info.getHash());
    } else {
        map.put("t", tracker);
    }
    if (to_info.getLevel() == 0) {
        try {
            Download to_download = to_info.getRelatedToDownload();
            if (to_download != null) {
                int version = RelatedContent.VERSION_INITIAL;
                Torrent torrent = to_download.getTorrent();
                if (torrent != null) {
                    long secs = torrent.getCreationDate();
                    long hours = secs / (60 * 60);
                    if (hours > 0) {
                        map.put("p", new Long(hours));
                    }
                }
                DownloadManagerState state = PluginCoreUtils.unwrap(to_download).getDownloadState();
                int leechers = -1;
                int seeds = -1;
                int[] aggregate_seeds_leechers = DownloadManagerStateFactory.getCachedAggregateScrapeSeedsLeechers(state);
                if (aggregate_seeds_leechers == null) {
                    long cache = state.getLongAttribute(DownloadManagerState.AT_SCRAPE_CACHE);
                    if (cache != -1) {
                        seeds = (int) ((cache >> 32) & 0x00ffffff);
                        leechers = (int) (cache & 0x00ffffff);
                    }
                } else {
                    seeds = aggregate_seeds_leechers[0];
                    leechers = aggregate_seeds_leechers[1];
                    version = RelatedContent.VERSION_BETTER_SCRAPE;
                }
                if (version > 0) {
                    map.put("v", new Long(version));
                }
                if (leechers > 0) {
                    map.put("l", new Long(leechers));
                }
                if (seeds > 0) {
                    map.put("z", new Long(seeds));
                }
                byte[][] keys = getKeys(to_download);
                if (keys[0] != null) {
                    map.put("k", keys[0]);
                }
                if (keys[1] != null) {
                    map.put("w", keys[1]);
                }
                String[] _tags = getTags(to_download);
                if (_tags != null) {
                    map.put("g", encodeTags(_tags));
                }
                byte nets = getNetworks(to_download);
                if (nets != NET_PUBLIC) {
                    map.put("o", new Long(nets & 0xff));
                }
            }
        } catch (Throwable e) {
            Debug.out(e);
        }
    }
    Download from_download = from_info.getRelatedToDownload();
    final Set<String> my_tags = new HashSet<>();
    try {
        if (from_download != null) {
            String[] _tags = getTags(from_download);
            if (_tags != null) {
                map.put("b", from_info.getRand() % 100);
                map.put("m", encodeTags(_tags));
                Collections.addAll(my_tags, _tags);
            }
        }
    } catch (Throwable e) {
        Debug.out(e);
    }
    Set<String> my_tags_original = new HashSet<>(my_tags);
    long size = to_info.getSize();
    if (size != 0) {
        map.put("s", new Long(size));
    }
    final byte[] map_bytes = BEncoder.encode(map);
    // System.out.println( "rcmsize=" + map_bytes.length );
    final int max_hits = 30;
    dht_plugin.get(key_bytes, "Content rel test: " + from_hash.substring(0, 16), DHTPlugin.FLAG_SINGLE_VALUE, max_hits, 30 * 1000, false, false, new DHTPluginOperationListener() {

        private boolean diversified;

        private int hits;

        private Set<String> entries = new HashSet<>();

        private Set<String> discovered_tags = new HashSet<>();

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

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

        @Override
        public void valueRead(DHTPluginContact originator, DHTPluginValue value) {
            try {
                Map<String, Object> map = (Map<String, Object>) BDecoder.decode(value.getValue());
                DownloadInfo info = decodeInfo(map, from_info.getHash(), 1, false, entries);
                try {
                    String[] r_tags = decodeTags((byte[]) map.get("m"));
                    if (r_tags != null) {
                        Long b = (Long) map.get("b");
                        if (b == null || from_info.getRand() % 100 != b % 100) {
                            for (String tag : r_tags) {
                                synchronized (my_tags) {
                                    my_tags.remove(tag);
                                    if (!my_tags_original.contains(tag)) {
                                        discovered_tags.add(tag);
                                    }
                                }
                            }
                        }
                    }
                } catch (Throwable e) {
                }
                if (info != null) {
                    analyseResponse(info, null);
                }
            } catch (Throwable e) {
            }
            hits++;
        }

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

        @Override
        public void complete(byte[] key, boolean timeout_occurred) {
            if (from_download != null) {
                synchronized (my_tags) {
                    if (!discovered_tags.isEmpty()) {
                        Set<String> interesting = new HashSet<>();
                        for (String tag : discovered_tags) {
                            if (TagUtils.isInternalTagName(tag)) {
                                continue;
                            }
                            interesting.add(tag);
                        }
                        if (!interesting.isEmpty()) {
                            try {
                                DownloadManagerState dms = PluginCoreUtils.unwrap(from_download).getDownloadState();
                                String[] old = dms.getListAttribute(DownloadManagerState.AT_SWARM_TAGS);
                                if (old == null || old.length == 0) {
                                    dms.setListAttribute(DownloadManagerState.AT_SWARM_TAGS, interesting.toArray(new String[0]));
                                } else {
                                    if (old.length < 16) {
                                        interesting.addAll(Arrays.asList(old));
                                        if (interesting.size() > old.length) {
                                            dms.setListAttribute(DownloadManagerState.AT_SWARM_TAGS, interesting.toArray(new String[0]));
                                        }
                                    }
                                }
                            } catch (Throwable e) {
                            }
                        }
                    }
                }
            }
            // if we have something to say prioritise it somewhat
            int f_cutoff = my_tags.size() > 0 ? 20 : 10;
            try {
                boolean do_it;
                if (diversified || hits >= f_cutoff) {
                    do_it = false;
                } else if (hits <= f_cutoff / 2) {
                    do_it = true;
                } else {
                    do_it = RandomUtils.nextInt(hits - (f_cutoff / 2) + 1) == 0;
                }
                if (do_it) {
                    try {
                        dht_plugin.put(key_bytes, "Content rel: " + from_hash.substring(0, 16) + " -> " + to_hash.substring(0, 16), map_bytes, DHTPlugin.FLAG_ANON, 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) {
                                publishNext();
                            }
                        });
                    } catch (Throwable e) {
                        Debug.printStackTrace(e);
                        publishNext();
                    }
                } else {
                    publishNext();
                }
            } finally {
                checkAlternativePubs(to_info, map_bytes, f_cutoff);
            }
        }
    });
    return (true);
}
Also used : TOTorrent(com.biglybt.core.torrent.TOTorrent) Torrent(com.biglybt.pif.torrent.Torrent) TOTorrentAnnounceURLSet(com.biglybt.core.torrent.TOTorrentAnnounceURLSet) DownloadManagerState(com.biglybt.core.download.DownloadManagerState) Download(com.biglybt.pif.download.Download)

Example 14 with Torrent

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

the class MagnetPlugin method initialize.

@Override
public void initialize(PluginInterface _plugin_interface) {
    plugin_interface = _plugin_interface;
    MagnetURIHandler uri_handler = MagnetURIHandler.getSingleton();
    final LocaleUtilities lu = plugin_interface.getUtilities().getLocaleUtilities();
    lu.addListener(new LocaleListener() {

        @Override
        public void localeChanged(Locale l) {
            updateLocale(lu);
        }
    });
    updateLocale(lu);
    BasicPluginConfigModel config = plugin_interface.getUIManager().createBasicPluginConfigModel(ConfigSection.SECTION_PLUGINS, PLUGIN_CONFIGSECTION_ID);
    config.addInfoParameter2("MagnetPlugin.current.port", String.valueOf(uri_handler.getPort()));
    md_lookup = config.addBooleanParameter2("MagnetPlugin.use.md.download", "MagnetPlugin.use.md.download", true);
    md_lookup_delay = config.addIntParameter2("MagnetPlugin.use.md.download.delay", "MagnetPlugin.use.md.download.delay", MD_LOOKUP_DELAY_SECS_DEFAULT);
    String et_default = "";
    for (String etd : MD_EXTRA_TRACKERS) {
        et_default += (et_default.isEmpty() ? "" : "\n") + etd;
    }
    md_extra_trackers = config.addStringParameter2("MagnetPlugin.md.extra.trackers", "MagnetPlugin.md.extra.trackers", et_default);
    md_extra_trackers.setMultiLine(3);
    md_lookup.addEnabledOnSelection(md_lookup_delay);
    md_lookup.addEnabledOnSelection(md_extra_trackers);
    timeout_param = config.addIntParameter2("MagnetPlugin.timeout.secs", "MagnetPlugin.timeout.secs", PLUGIN_DOWNLOAD_TIMEOUT_SECS_DEFAULT);
    sources_param = config.addStringListParameter2("MagnetPlugin.add.sources", "MagnetPlugin.add.sources", SOURCE_VALUES, SOURCE_STRINGS, SOURCE_VALUES[1]);
    sources_extra_param = config.addIntParameter2("MagnetPlugin.add.sources.extra", "MagnetPlugin.add.sources.extra", 0);
    magnet_recovery = config.addBooleanParameter2("MagnetPlugin.recover.magnets", "MagnetPlugin.recover.magnets", true);
    magnet_recovery_concurrency = config.addIntParameter2("MagnetPlugin.recover.magnets.conc", "MagnetPlugin.recover.magnets.conc", 32, 8, 512);
    magnet_recovery_concurrency.setIndent(1, true);
    magnet_recovery.addEnabledOnSelection(magnet_recovery_concurrency);
    BooleanParameter rename = config.addBooleanParameter2("MagnetPlugin.rename.using.dn", "MagnetPlugin.rename.using.dn", false);
    BooleanParameter rename_ext = config.addBooleanParameter2("MagnetPlugin.rename.using.dn.only.with.ext", "MagnetPlugin.rename.using.dn.only.with.ext", false);
    rename_ext.setIndent(1, true);
    rename.addEnabledOnSelection(rename_ext);
    Parameter[] nps = new Parameter[AENetworkClassifier.AT_NETWORKS.length];
    for (int i = 0; i < nps.length; i++) {
        String nn = AENetworkClassifier.AT_NETWORKS[i];
        String config_name = "Network Selection Default." + nn;
        String msg_text = "ConfigView.section.connection.networks." + nn;
        final BooleanParameter param = config.addBooleanParameter2(config_name, msg_text, COConfigurationManager.getBooleanParameter(config_name));
        COConfigurationManager.addParameterListener(config_name, new com.biglybt.core.config.ParameterListener() {

            @Override
            public void parameterChanged(String name) {
                param.setDefaultValue(COConfigurationManager.getBooleanParameter(name));
            }
        });
        nps[i] = param;
        net_params.put(nn, param);
    }
    config.createGroup("label.default.nets", nps);
    MenuItemListener listener = new MenuItemListener() {

        @Override
        public void selected(MenuItem _menu, Object _target) {
            TableRow[] rows = (TableRow[]) _target;
            String cb_all_data = "";
            for (TableRow row : rows) {
                Torrent torrent;
                String name;
                Object ds = row.getDataSource();
                Download download = null;
                ShareResource share = null;
                if (ds instanceof ShareResourceFile) {
                    ShareResourceFile sf = (ShareResourceFile) ds;
                    try {
                        torrent = sf.getItem().getTorrent();
                    } catch (ShareException e) {
                        continue;
                    }
                    name = sf.getName();
                    share = sf;
                } else if (ds instanceof ShareResourceDir) {
                    ShareResourceDir sd = (ShareResourceDir) ds;
                    try {
                        torrent = sd.getItem().getTorrent();
                    } catch (ShareException e) {
                        continue;
                    }
                    name = sd.getName();
                    share = sd;
                } else if (ds instanceof Download) {
                    download = (Download) ds;
                    torrent = download.getTorrent();
                    name = download.getName();
                } else {
                    continue;
                }
                boolean is_share = false;
                Set<String> networks = new HashSet<>();
                if (share != null) {
                    is_share = true;
                    Map<String, String> properties = share.getProperties();
                    if (properties != null) {
                        String nets = properties.get(ShareManager.PR_NETWORKS);
                        if (nets != null) {
                            String[] bits = nets.split(",");
                            for (String bit : bits) {
                                bit = AENetworkClassifier.internalise(bit.trim());
                                if (bit != null) {
                                    networks.add(bit);
                                }
                            }
                        }
                    }
                }
                if (download != null) {
                    TorrentAttribute ta = plugin_interface.getTorrentManager().getAttribute(TorrentAttribute.TA_NETWORKS);
                    String[] nets = download.getListAttribute(ta);
                    networks.addAll(Arrays.asList(nets));
                    try {
                        byte[] hash = download.getTorrentHash();
                        if (plugin_interface.getShareManager().lookupShare(hash) != null) {
                            is_share = true;
                        }
                    } catch (Throwable e) {
                    }
                }
                String cb_data = download == null ? UrlUtils.getMagnetURI(name, torrent) : UrlUtils.getMagnetURI(download);
                if (download != null) {
                    List<Tag> tags = TagManagerFactory.getTagManager().getTagsForTaggable(TagType.TT_DOWNLOAD_MANUAL, PluginCoreUtils.unwrap(download));
                    for (Tag tag : tags) {
                        if (tag.isPublic()) {
                            if (!tag.isTagAuto()[0]) {
                                cb_data += "&tag=" + UrlUtils.encode(tag.getTagName(true));
                            }
                        }
                    }
                }
                String sources = sources_param.getValue();
                boolean add_sources = sources.equals("2") || (sources.equals("1") && is_share);
                if (add_sources) {
                    if (networks.isEmpty()) {
                        for (String net : AENetworkClassifier.AT_NETWORKS) {
                            if (isNetworkEnabled(net)) {
                                networks.add(net);
                            }
                        }
                    }
                    if (networks.contains(AENetworkClassifier.AT_PUBLIC) && !cb_data.contains("xsource=")) {
                        DownloadManager dm = download == null ? null : PluginCoreUtils.unwrap(download);
                        InetAddress ip = NetworkAdmin.getSingleton().getDefaultPublicAddress();
                        InetAddress ip_v6 = NetworkAdmin.getSingleton().getDefaultPublicAddressV6();
                        int port = dm == null ? TCPNetworkManager.getSingleton().getDefaultTCPListeningPortNumber() : dm.getTCPListeningPortNumber();
                        if (ip != null && port > 0) {
                            cb_data += "&xsource=" + UrlUtils.encode(UrlUtils.getURLForm(ip, port));
                        }
                        if (ip_v6 != null && port > 0) {
                            cb_data += "&xsource=" + UrlUtils.encode(UrlUtils.getURLForm(ip_v6, port));
                        }
                        int extra = sources_extra_param.getValue();
                        if (extra > 0) {
                            if (download == null) {
                                if (torrent != null) {
                                    download = plugin_interface.getDownloadManager().getDownload(torrent);
                                }
                            }
                            if (download != null) {
                                Set<String> added = new HashSet<>();
                                PEPeerManager pm = dm.getPeerManager();
                                if (pm != null) {
                                    List<PEPeer> peers = pm.getPeers();
                                    for (PEPeer peer : peers) {
                                        String peer_ip = peer.getIp();
                                        if (AENetworkClassifier.categoriseAddress(peer_ip) == AENetworkClassifier.AT_PUBLIC) {
                                            int peer_port = peer.getTCPListenPort();
                                            if (peer_port > 0) {
                                                cb_data += "&xsource=" + UrlUtils.encode(UrlUtils.getURLForm(peer_ip, peer_port));
                                                added.add(peer_ip);
                                                extra--;
                                                if (extra == 0) {
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }
                                if (extra > 0) {
                                    Map response_cache = dm.getDownloadState().getTrackerResponseCache();
                                    if (response_cache != null) {
                                        List<TRTrackerAnnouncerResponsePeer> peers = TRTrackerAnnouncerFactory.getCachedPeers(response_cache);
                                        for (TRTrackerAnnouncerResponsePeer peer : peers) {
                                            String peer_ip = peer.getAddress();
                                            if (AENetworkClassifier.categoriseAddress(peer_ip) == AENetworkClassifier.AT_PUBLIC) {
                                                if (!added.contains(peer_ip)) {
                                                    int peer_port = peer.getPort();
                                                    if (peer_port > 0) {
                                                        cb_data += "&xsource=" + UrlUtils.encode(UrlUtils.getURLForm(peer_ip, peer_port));
                                                        added.add(peer_ip);
                                                        extra--;
                                                        if (extra == 0) {
                                                            break;
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                // removed this as well - nothing wrong with allowing magnet copy
                // for private torrents - they still can't be tracked if you don't
                // have permission
                /*if ( torrent.isPrivate()){

							cb_data = getMessageText( "private_torrent" );

						}else if ( torrent.isDecentralised()){
						*/
                // ok
                /* relaxed this as we allow such torrents to be downloaded via magnet links
							 * (as opposed to tracked in the DHT)

						}else if ( torrent.isDecentralisedBackupEnabled()){

							TorrentAttribute ta_peer_sources 	= plugin_interface.getTorrentManager().getAttribute( TorrentAttribute.TA_PEER_SOURCES );

							String[]	sources = download.getListAttribute( ta_peer_sources );

							boolean	ok = false;

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

								if ( sources[i].equalsIgnoreCase( "DHT")){

									ok	= true;

									break;
								}
							}

							if ( !ok ){

								cb_data = getMessageText( "decentral_disabled" );
							}
						}else{

							cb_data = getMessageText( "decentral_backup_disabled" );
							*/
                // }
                // System.out.println( "MagnetPlugin: export = " + url );
                cb_all_data += (cb_all_data.length() == 0 ? "" : "\n") + cb_data;
            }
            try {
                plugin_interface.getUIManager().copyToClipBoard(cb_all_data);
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    };
    List<TableContextMenuItem> menus = new ArrayList<>();
    for (String table : TableManager.TABLE_MYTORRENTS_ALL) {
        TableContextMenuItem menu = plugin_interface.getUIManager().getTableManager().addContextMenuItem(table, "MagnetPlugin.contextmenu.exporturi");
        menu.addMultiListener(listener);
        menu.setHeaderCategory(MenuItem.HEADER_SOCIAL);
        menus.add(menu);
    }
    uri_handler.addListener(new MagnetURIHandlerListener() {

        @Override
        public byte[] badge() {
            InputStream is = getClass().getClassLoader().getResourceAsStream("com/biglybt/plugin/magnet/Magnet.gif");
            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) {
                Debug.printStackTrace(e);
                return (null);
            }
        }

        @Override
        public byte[] download(MagnetURIHandlerProgressListener muh_listener, byte[] hash, String args, InetSocketAddress[] sources, long timeout) throws MagnetURIHandlerException {
            try {
                Download dl = plugin_interface.getDownloadManager().getDownload(hash);
                if (dl != null) {
                    // might just be an existing metadata download
                    com.biglybt.core.download.DownloadManager core_dm = PluginCoreUtils.unwrap(dl);
                    if (!core_dm.getDownloadState().getFlag(DownloadManagerState.FLAG_METADATA_DOWNLOAD)) {
                        Torrent torrent = dl.getTorrent();
                        if (torrent != null) {
                            byte[] torrent_data = torrent.writeToBEncodedData();
                            torrent_data = addTrackersAndWebSeedsEtc(torrent_data, args, new HashSet<String>(), Collections.emptyList(), Collections.emptyMap());
                            return (torrent_data);
                        }
                    }
                }
            } catch (Throwable e) {
                Debug.printStackTrace(e);
            }
            Object[] result = { null };
            AESemaphore sem = new AESemaphore("dlwait");
            DownloadAsyncListener dl_listener = new DownloadAsyncListener() {

                @Override
                public void failed(MagnetURIHandlerException error) {
                    synchronized (result) {
                        result[0] = error;
                    }
                    sem.release();
                }

                @Override
                public void complete(byte[] torrent_data) {
                    synchronized (result) {
                        result[0] = torrent_data;
                    }
                    sem.release();
                }
            };
            recoverableDownload(muh_listener, hash, args, sources, Collections.emptyList(), Collections.emptyMap(), timeout, SystemTime.getCurrentTime(), false, dl_listener);
            sem.reserve();
            synchronized (result) {
                Object r = result[0];
                if (r instanceof MagnetURIHandlerException) {
                    throw ((MagnetURIHandlerException) r);
                } else {
                    return ((byte[]) r);
                }
            }
        }

        @Override
        public boolean download(URL url) throws MagnetURIHandlerException {
            try {
                plugin_interface.getDownloadManager().addDownload(url, false);
                return (true);
            } catch (DownloadException e) {
                throw (new MagnetURIHandlerException("Operation failed", e));
            }
        }

        @Override
        public boolean set(String name, Map values) {
            List l = listeners.getList();
            for (int i = 0; i < l.size(); i++) {
                if (((MagnetPluginListener) l.get(i)).set(name, values)) {
                    return (true);
                }
            }
            return (false);
        }

        @Override
        public int get(String name, Map values) {
            List l = listeners.getList();
            for (int i = 0; i < l.size(); i++) {
                int res = ((MagnetPluginListener) l.get(i)).get(name, values);
                if (res != Integer.MIN_VALUE) {
                    return (res);
                }
            }
            return (Integer.MIN_VALUE);
        }
    });
    plugin_interface.getUIManager().addUIListener(new UIManagerListener() {

        @Override
        public void UIAttached(UIInstance instance) {
            if (instance.getUIType().equals(UIInstance.UIT_SWT)) {
                try {
                    Class.forName("com.biglybt.plugin.magnet.swt.MagnetPluginUISWT").getConstructor(new Class[] { UIInstance.class, TableContextMenuItem[].class }).newInstance(new Object[] { instance, menus.toArray(new TableContextMenuItem[menus.size()]) });
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void UIDetached(UIInstance instance) {
        }
    });
    final List<Download> to_delete = new ArrayList<>();
    Download[] downloads = plugin_interface.getDownloadManager().getDownloads();
    for (Download download : downloads) {
        if (download.getFlag(Download.FLAG_METADATA_DOWNLOAD)) {
            to_delete.add(download);
        }
    }
    final AESemaphore delete_done = new AESemaphore("delete waiter");
    if (to_delete.size() > 0) {
        AEThread2 t = new AEThread2("MagnetPlugin:delmds", true) {

            @Override
            public void run() {
                try {
                    for (Download download : to_delete) {
                        try {
                            download.stopAndRemove(true, true);
                        } catch (Throwable e) {
                            Debug.out(e);
                        }
                    }
                } finally {
                    delete_done.release();
                }
            }
        };
        t.start();
    } else {
        delete_done.release();
    }
    plugin_interface.addListener(new PluginListener() {

        @Override
        public void initializationComplete() {
            // make sure DDB is initialised as we need it to register its
            // transfer types
            AEThread2 t = new AEThread2("MagnetPlugin:init", true) {

                @Override
                public void run() {
                    delete_done.reserve();
                    recoverDownloads();
                    try {
                        DistributedDatabase db = plugin_interface.getDistributedDatabase();
                        synchronized (db_holder) {
                            db_holder[0] = db;
                        }
                    } catch (Throwable e) {
                        Debug.out(e);
                    } finally {
                        db_waiter.releaseForever();
                    }
                }
            };
            t.start();
        }

        @Override
        public void closedownInitiated() {
            updateRecoverableDownloads();
        }

        @Override
        public void closedownComplete() {
        }
    });
}
Also used : Torrent(com.biglybt.pif.torrent.Torrent) TOTorrent(com.biglybt.core.torrent.TOTorrent) PEPeer(com.biglybt.core.peer.PEPeer) ShareResourceDir(com.biglybt.pif.sharing.ShareResourceDir) InetSocketAddress(java.net.InetSocketAddress) LocaleUtilities(com.biglybt.pif.utils.LocaleUtilities) DownloadManager(com.biglybt.core.download.DownloadManager) DownloadException(com.biglybt.pif.download.DownloadException) MenuItemListener(com.biglybt.pif.ui.menus.MenuItemListener) UIInstance(com.biglybt.pif.ui.UIInstance) MagnetURIHandler(com.biglybt.net.magneturi.MagnetURIHandler) TableRow(com.biglybt.pif.ui.tables.TableRow) PEPeerManager(com.biglybt.core.peer.PEPeerManager) InetAddress(java.net.InetAddress) ShareResourceFile(com.biglybt.pif.sharing.ShareResourceFile) MagnetURIHandlerProgressListener(com.biglybt.net.magneturi.MagnetURIHandlerProgressListener) TableContextMenuItem(com.biglybt.pif.ui.tables.TableContextMenuItem) URL(java.net.URL) PluginListener(com.biglybt.pif.PluginListener) ShareException(com.biglybt.pif.sharing.ShareException) LocaleListener(com.biglybt.pif.utils.LocaleListener) Download(com.biglybt.pif.download.Download) ShareResource(com.biglybt.pif.sharing.ShareResource) InputStream(java.io.InputStream) TableContextMenuItem(com.biglybt.pif.ui.tables.TableContextMenuItem) MenuItem(com.biglybt.pif.ui.menus.MenuItem) ByteArrayOutputStream(java.io.ByteArrayOutputStream) BooleanParameter(com.biglybt.pif.ui.config.BooleanParameter) TorrentAttribute(com.biglybt.pif.torrent.TorrentAttribute) BooleanParameter(com.biglybt.pif.ui.config.BooleanParameter) StringParameter(com.biglybt.pif.ui.config.StringParameter) Parameter(com.biglybt.pif.ui.config.Parameter) StringListParameter(com.biglybt.pif.ui.config.StringListParameter) IntParameter(com.biglybt.pif.ui.config.IntParameter) TRTrackerAnnouncerResponsePeer(com.biglybt.core.tracker.client.TRTrackerAnnouncerResponsePeer) Tag(com.biglybt.core.tag.Tag) MagnetURIHandlerListener(com.biglybt.net.magneturi.MagnetURIHandlerListener) MagnetURIHandlerException(com.biglybt.net.magneturi.MagnetURIHandlerException) UIManagerListener(com.biglybt.pif.ui.UIManagerListener) BasicPluginConfigModel(com.biglybt.pif.ui.model.BasicPluginConfigModel)

Example 15 with Torrent

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

the class BuddyPluginAZ2 method processAZ2Request.

protected Map processAZ2Request(final BuddyPluginBuddy from_buddy, Map request) throws BuddyPluginException {
    logMessage(from_buddy, "AZ2 request received: " + from_buddy.getString() + " -> " + request);
    int type = ((Long) request.get("type")).intValue();
    Map reply = new HashMap();
    if (type == RT_AZ2_REQUEST_MESSAGE) {
        try {
            String msg = new String((byte[]) request.get("msg"), "UTF8");
            from_buddy.setLastMessageReceived(msg);
        } catch (Throwable e) {
        }
        reply.put("type", new Long(RT_AZ2_REPLY_MESSAGE));
    } else if (type == RT_AZ2_REQUEST_SEND_TORRENT) {
        try {
            final Torrent torrent = plugin_network.getPluginInterface().getTorrentManager().createFromBEncodedData((byte[]) request.get("torrent"));
            new AEThread2("torrentAdder", true) {

                @Override
                public void run() {
                    PluginInterface pi = plugin_network.getPluginInterface();
                    String msg = pi.getUtilities().getLocaleUtilities().getLocalisedMessageText("azbuddy.addtorrent.msg", new String[] { from_buddy.getName(), torrent.getName() });
                    long res = pi.getUIManager().showMessageBox("azbuddy.addtorrent.title", "!" + msg + "!", UIManagerEvent.MT_YES | UIManagerEvent.MT_NO);
                    if (res == UIManagerEvent.MT_YES) {
                        pi.getUIManager().openTorrent(torrent);
                    }
                }
            }.start();
            reply.put("type", new Long(RT_AZ2_REPLY_SEND_TORRENT));
        } catch (Throwable e) {
            throw (new BuddyPluginException("Torrent receive failed " + type));
        }
    } else if (type == RT_AZ2_REQUEST_CHAT) {
        Map msg = (Map) request.get("msg");
        String id = new String((byte[]) msg.get("id"));
        int chat_msg_type = ((Long) msg.get("type")).intValue();
        boolean dont_create_chat = chat_msg_type == CHAT_MSG_TYPE_PARTICIPANTS_REMOVED;
        chatInstance chat;
        boolean new_chat = false;
        synchronized (chats) {
            chat = (chatInstance) chats.get(id);
            if (chat == null) {
                if (!dont_create_chat) {
                    if (chats.size() > 32) {
                        throw (new BuddyPluginException("Too many chats"));
                    }
                    chat = new chatInstance(id);
                    chats.put(id, chat);
                    new_chat = true;
                }
            }
        }
        if (chat != null) {
            if (new_chat) {
                informCreated(chat);
            }
            chat.addParticipant(from_buddy);
            chat.process(from_buddy, msg);
        }
        reply.put("type", new Long(RT_AZ2_REPLY_CHAT));
    } else if (type == RT_AZ2_REQUEST_TRACK) {
        Map msg = (Map) request.get("msg");
        Iterator it = track_listeners.iterator();
        boolean ok = false;
        while (it.hasNext()) {
            try {
                Map res = ((BuddyPluginAZ2TrackerListener) it.next()).messageReceived(from_buddy, msg);
                if (res != null) {
                    reply.put("msg", res);
                    reply.put("type", new Long(RT_AZ2_REPLY_TRACK));
                    ok = true;
                    break;
                }
            } catch (Throwable e) {
                Debug.printStackTrace(e);
            }
        }
        if (!ok) {
            throw (new BuddyPluginException("Unhandled request type " + type));
        }
    } else if (type == RT_AZ2_REQUEST_RSS) {
        try {
            Map<String, Object> res = new HashMap<>();
            reply.put("msg", res);
            reply.put("type", new Long(RT_AZ2_REPLY_RSS));
            Map msg = (Map) request.get("msg");
            String category = new String((byte[]) msg.get("cat"), "UTF-8");
            byte[] hash = (byte[]) msg.get("hash");
            if (hash == null) {
                byte[] if_mod = (byte[]) msg.get("if_mod");
                BuddyPlugin.FeedDetails feed = plugin_network.getPlugin().getRSS(from_buddy, category, if_mod == null ? null : new String(if_mod, "UTF-8"));
                res.put("rss", feed.getContent());
                res.put("last_mod", feed.getLastModified());
            } else {
                res.put("torrent", plugin_network.getPlugin().getRSSTorrent(from_buddy, category, hash));
            }
        } catch (BuddyPluginException e) {
            throw (e);
        } catch (Throwable e) {
            throw (new BuddyPluginException("Failed to handle rss", e));
        }
    } else if (type == RT_AZ2_REQUEST_PROFILE_INFO) {
        List<String> info = plugin_network.getProfileInfo();
        if (info == null) {
            throw (new BuddyPluginException("Unauthorised"));
        }
        Map<String, Object> res = new HashMap<>();
        reply.put("msg", res);
        reply.put("type", new Long(RT_AZ2_REPLY_PROFILE_INFO));
        res.put("props", info);
    } else {
        throw (new BuddyPluginException("Unrecognised request type " + type));
    }
    logMessage(from_buddy, "AZ2 reply sent: " + from_buddy.getString() + " <- " + reply);
    return (reply);
}
Also used : Torrent(com.biglybt.pif.torrent.Torrent) PluginInterface(com.biglybt.pif.PluginInterface)

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