Search in sources :

Example 21 with PEPeerManager

use of com.biglybt.core.peer.PEPeerManager in project BiglyBT by BiglySoftware.

the class DiskManagerRandomReadController method executeRequest.

private void executeRequest() {
    DiskManagerRandomReadRequestImpl request;
    synchronized (requests) {
        if (requests.isEmpty()) {
            return;
        }
        request = requests.remove(0);
    }
    if (request.isCancelled()) {
        return;
    }
    DiskManagerFileInfoListener info_listener = null;
    com.biglybt.core.disk.DiskManagerFileInfo core_file = request.getFile().getCore();
    DownloadManager core_download = core_file.getDownloadManager();
    int prev_hint_piece = -1;
    int curr_hint_piece = -1;
    try {
        if (core_download.getTorrent() == null) {
            throw (new DownloadException("Torrent invalid"));
        }
        if (core_download.isDestroyed()) {
            Debug.out("Download has been removed");
            throw (new DownloadException("Download has been removed"));
        }
        TOTorrentFile tf = core_file.getTorrentFile();
        TOTorrent torrent = tf.getTorrent();
        TOTorrentFile[] tfs = torrent.getFiles();
        long core_file_start_byte = 0;
        for (int i = 0; i < core_file.getIndex(); i++) {
            core_file_start_byte += tfs[i].getLength();
        }
        long download_byte_start = core_file_start_byte + request.getOffset();
        long download_byte_end = download_byte_start + request.getLength();
        int piece_size = (int) tf.getTorrent().getPieceLength();
        if (core_file.getDownloaded() != core_file.getLength()) {
            if (core_file.isSkipped()) {
                core_file.setSkipped(false);
            }
            boolean force_start = download.isForceStart();
            if (!force_start) {
                download.setForceStart(true);
                set_force_start = true;
                final AESemaphore running_sem = new AESemaphore("rs");
                DownloadListener dl_listener = new DownloadListener() {

                    @Override
                    public void stateChanged(Download download, int old_state, int new_state) {
                        if (new_state == Download.ST_DOWNLOADING || new_state == Download.ST_SEEDING) {
                            running_sem.release();
                        }
                    }

                    @Override
                    public void positionChanged(Download download, int oldPosition, int newPosition) {
                    }
                };
                download.addListener(dl_listener);
                try {
                    if (download.getState() != Download.ST_DOWNLOADING && download.getState() != Download.ST_SEEDING) {
                        if (!running_sem.reserve(10 * 1000)) {
                            throw (new DownloadException("timeout waiting for download to start"));
                        }
                    }
                } finally {
                    download.removeListener(dl_listener);
                }
            }
        }
        boolean is_reverse = request.isReverse();
        final AESemaphore wait_sem = new AESemaphore("rr:waiter");
        info_listener = new DiskManagerFileInfoListener() {

            @Override
            public void dataWritten(long offset, long length) {
                wait_sem.release();
            }

            @Override
            public void dataChecked(long offset, long length) {
            }
        };
        long start_time = SystemTime.getMonotonousTime();
        boolean has_started = false;
        core_file.addListener(info_listener);
        while (download_byte_start < download_byte_end) {
            if (request.isCancelled()) {
                throw (new Exception("request cancelled"));
            }
            // System.out.println( "Request current: " + download_byte_start + " -> " + download_byte_end );
            long now = SystemTime.getMonotonousTime();
            int piece_start = (int) (download_byte_start / piece_size);
            int piece_start_offset = (int) (download_byte_start % piece_size);
            int piece_end = (int) ((download_byte_end - 1) / piece_size);
            int piece_end_offset = (int) ((download_byte_end - 1) % piece_size) + 1;
            // System.out.println( "    piece details: " + piece_start + "/" + piece_start_offset + " -> " + piece_end + "/" + piece_end_offset );
            DiskManagerPiece[] pieces = null;
            DiskManager disk_manager = core_download.getDiskManager();
            if (disk_manager != null) {
                pieces = disk_manager.getPieces();
            }
            long avail_start;
            long avail_end;
            if (pieces == null) {
                if (core_file.getDownloaded() == core_file.getLength()) {
                    avail_start = download_byte_start;
                    avail_end = download_byte_end;
                } else {
                    if (now - start_time < 10000 && !has_started) {
                        wait_sem.reserve(250);
                        continue;
                    }
                    throw (new Exception("download stopped"));
                }
            } else {
                has_started = true;
                if (is_reverse) {
                    long min_done = download_byte_end;
                    for (int i = piece_end; i >= piece_start; i--) {
                        int p_start = i == piece_start ? piece_start_offset : 0;
                        int p_end = i == piece_end ? piece_end_offset : piece_size;
                        DiskManagerPiece piece = pieces[i];
                        boolean[] done = piece.getWritten();
                        if (done == null) {
                            if (piece.isDone()) {
                                min_done = i * (long) piece_size;
                                continue;
                            } else {
                                break;
                            }
                        }
                        int block_size = piece.getBlockSize(0);
                        int first_block = p_start / block_size;
                        int last_block = (p_end - 1) / block_size;
                        for (int j = last_block; j >= first_block; j--) {
                            if (done[j]) {
                                min_done = i * (long) piece_size + j * block_size;
                            } else {
                                break;
                            }
                        }
                    }
                    avail_start = Math.max(download_byte_start, min_done);
                    avail_end = download_byte_end;
                } else {
                    long max_done = download_byte_start;
                    for (int i = piece_start; i <= piece_end; i++) {
                        int p_start = i == piece_start ? piece_start_offset : 0;
                        int p_end = i == piece_end ? piece_end_offset : piece_size;
                        DiskManagerPiece piece = pieces[i];
                        boolean[] done = piece.getWritten();
                        if (done == null) {
                            if (piece.isDone()) {
                                max_done = (i + 1) * (long) piece_size;
                                continue;
                            } else {
                                break;
                            }
                        }
                        int block_size = piece.getBlockSize(0);
                        int first_block = p_start / block_size;
                        int last_block = (p_end - 1) / block_size;
                        for (int j = first_block; j <= last_block; j++) {
                            if (done[j]) {
                                max_done = i * (long) piece_size + (j + 1) * block_size;
                            } else {
                                break;
                            }
                        }
                    }
                    avail_start = download_byte_start;
                    avail_end = Math.min(download_byte_end, max_done);
                }
            }
            // System.out.println( "    avail: " + avail_start + " -> " + avail_end );
            int max_chunk = 128 * 1024;
            if (avail_end > avail_start) {
                long length = avail_end - avail_start;
                if (length > max_chunk) {
                    if (is_reverse) {
                        avail_start = avail_end - max_chunk;
                    } else {
                        avail_end = avail_start + max_chunk;
                    }
                }
                // System.out.println( "got data: " + avail_start + " -> " + avail_end );
                long read_offset = avail_start - core_file_start_byte;
                int read_length = (int) (avail_end - avail_start);
                DirectByteBuffer buffer = core_file.read(read_offset, read_length);
                request.dataAvailable(buffer, read_offset, read_length);
                if (is_reverse) {
                    download_byte_end = avail_start;
                } else {
                    download_byte_start = avail_end;
                }
                continue;
            }
            PEPeerManager pm = core_download.getPeerManager();
            if (pm == null) {
                if (now - start_time < 10000 && !has_started) {
                    wait_sem.reserve(250);
                    continue;
                }
                throw (new Exception("download stopped"));
            } else {
                has_started = true;
            }
            PiecePicker picker = pm.getPiecePicker();
            picker.setReverseBlockOrder(is_reverse);
            int hint_piece;
            int hint_offset;
            int hint_length;
            if (piece_start == piece_end) {
                hint_piece = piece_start;
                hint_offset = piece_start_offset;
                hint_length = piece_end_offset - piece_start_offset;
            } else {
                if (is_reverse) {
                    hint_piece = piece_end;
                    hint_offset = 0;
                    hint_length = piece_end_offset;
                } else {
                    hint_piece = piece_start;
                    hint_offset = piece_start_offset;
                    hint_length = piece_size - piece_start_offset;
                }
            }
            if (curr_hint_piece == -1) {
                int[] existing = picker.getGlobalRequestHint();
                if (existing != null) {
                    curr_hint_piece = existing[0];
                }
            }
            // System.out.println( "hint: " + hint_piece + "/" + hint_offset + "/" + hint_length + ": curr=" + curr_hint_piece + ", prev=" + prev_hint_piece );
            picker.setGlobalRequestHint(hint_piece, hint_offset, hint_length);
            if (hint_piece != curr_hint_piece) {
                prev_hint_piece = curr_hint_piece;
                curr_hint_piece = hint_piece;
            }
            if (prev_hint_piece != -1) {
                clearHint(pm, prev_hint_piece);
            }
            wait_sem.reserve(250);
        }
    } catch (Throwable e) {
        request.failed(e);
    } finally {
        PEPeerManager pm = core_download.getPeerManager();
        if (pm != null) {
            PiecePicker picker = pm.getPiecePicker();
            if (picker != null) {
                picker.setReverseBlockOrder(false);
                picker.setGlobalRequestHint(-1, 0, 0);
                if (curr_hint_piece != -1) {
                    clearHint(pm, curr_hint_piece);
                }
            }
        }
        if (info_listener != null) {
            core_file.removeListener(info_listener);
        }
    }
}
Also used : PiecePicker(com.biglybt.core.peermanager.piecepicker.PiecePicker) DiskManager(com.biglybt.core.disk.DiskManager) DownloadManager(com.biglybt.core.download.DownloadManager) DiskManagerFileInfoListener(com.biglybt.core.disk.DiskManagerFileInfoListener) DownloadException(com.biglybt.pif.download.DownloadException) DiskManagerPiece(com.biglybt.core.disk.DiskManagerPiece) Download(com.biglybt.pif.download.Download) DownloadException(com.biglybt.pif.download.DownloadException) TOTorrentFile(com.biglybt.core.torrent.TOTorrentFile) DownloadListener(com.biglybt.pif.download.DownloadListener) TOTorrent(com.biglybt.core.torrent.TOTorrent) PEPeerManager(com.biglybt.core.peer.PEPeerManager)

Example 22 with PEPeerManager

use of com.biglybt.core.peer.PEPeerManager in project BiglyBT by BiglySoftware.

the class DownloadImpl method addPeerListener.

@Override
public void addPeerListener(final DownloadPeerListener listener) {
    DownloadManagerPeerListener delegate = new DownloadManagerPeerListener() {

        @Override
        public void peerManagerAdded(PEPeerManager manager) {
            PeerManager pm = PeerManagerImpl.getPeerManager(manager);
            listener.peerManagerAdded(DownloadImpl.this, pm);
        }

        @Override
        public void peerManagerRemoved(PEPeerManager manager) {
            PeerManager pm = PeerManagerImpl.getPeerManager(manager);
            listener.peerManagerRemoved(DownloadImpl.this, pm);
        }

        @Override
        public void peerManagerWillBeAdded(PEPeerManager manager) {
        }

        @Override
        public void peerAdded(PEPeer peer) {
        }

        @Override
        public void peerRemoved(PEPeer peer) {
        }
    };
    try {
        peer_listeners_mon.enter();
        peer_listeners.put(listener, delegate);
    } finally {
        peer_listeners_mon.exit();
    }
    download_manager.addPeerListener(delegate);
}
Also used : PEPeer(com.biglybt.core.peer.PEPeer) PEPeerManager(com.biglybt.core.peer.PEPeerManager) PeerManager(com.biglybt.pif.peers.PeerManager) PEPeerManager(com.biglybt.core.peer.PEPeerManager)

Example 23 with PEPeerManager

use of com.biglybt.core.peer.PEPeerManager 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()));
    secondary_lookup = config.addBooleanParameter2("MagnetPlugin.use.lookup.service", "MagnetPlugin.use.lookup.service", true);
    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);
    md_lookup.addEnabledOnSelection(md_lookup_delay);
    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);
    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()) {
                            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=")) {
                        InetAddress ip = NetworkAdmin.getSingleton().getDefaultPublicAddress();
                        InetAddress ip_v6 = NetworkAdmin.getSingleton().getDefaultPublicAddressV6();
                        int port = TCPNetworkManager.getSingleton().getTCPListeningPortNumber();
                        if (ip != null && port > 0) {
                            cb_data += "&xsource=" + UrlUtils.encode(ip.getHostAddress() + ":" + port);
                        }
                        if (ip_v6 != null && port > 0) {
                            cb_data += "&xsource=" + UrlUtils.encode(ip_v6.getHostAddress() + ":" + 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<>();
                                DownloadManager dm = PluginCoreUtils.unwrap(download);
                                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(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(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) {
                    Torrent torrent = dl.getTorrent();
                    if (torrent != null) {
                        byte[] torrent_data = torrent.writeToBEncodedData();
                        torrent_data = addTrackersAndWebSeedsEtc(torrent_data, args, new HashSet<String>());
                        return (torrent_data);
                    }
                }
            } catch (Throwable e) {
                Debug.printStackTrace(e);
            }
            return (recoverableDownload(muh_listener, hash, args, sources, timeout, false));
        }

        @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.stop();
                        } catch (Throwable e) {
                        }
                        try {
                            download.remove(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();
                    plugin_interface.getDistributedDatabase();
                }
            };
            t.start();
        }

        @Override
        public void closedownInitiated() {
        }

        @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) 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 24 with PEPeerManager

use of com.biglybt.core.peer.PEPeerManager in project BiglyBT by BiglySoftware.

the class TorrentUtil method fillTorrentMenu.

// selected_dl_types -> 0 (determine that automatically), +1 (downloading), +2 (seeding), +3 (mixed - not used by anything yet)
public static void fillTorrentMenu(final Menu menu, final DownloadManager[] dms, final Core core, boolean include_show_details, int selected_dl_types, final TableView tv) {
    // TODO: Build submenus on the fly
    Shell shell = Utils.findAnyShell();
    Shell menu_shell = menu.getShell();
    final boolean isSeedingView;
    switch(selected_dl_types) {
        case 1:
            isSeedingView = false;
            break;
        case 2:
            isSeedingView = true;
            break;
        case 0:
            {
                if (dms.length == 1) {
                    isSeedingView = dms[0].isDownloadComplete(false);
                    break;
                }
            }
        default:
            // I was going to raise an error, but let's not be too hasty. :)
            isSeedingView = false;
    }
    boolean hasSelection = dms.length > 0;
    boolean isSingleSelection = dms.length == 1;
    boolean isTrackerOn = TRTrackerUtils.isTrackerEnabled();
    int userMode = COConfigurationManager.getIntParameter("User Mode");
    // Enable/Disable Logic
    boolean bChangeDir = hasSelection;
    boolean start, stop, pause, changeUrl, barsOpened, forceStart;
    boolean forceStartEnabled, recheck, manualUpdate, fileMove, canSetMOC, canClearMOC, fileExport, fileRescan;
    changeUrl = barsOpened = manualUpdate = fileMove = canSetMOC = fileExport = fileRescan = true;
    forceStart = forceStartEnabled = recheck = start = stop = pause = canClearMOC = false;
    boolean canSetSuperSeed = false;
    boolean superSeedAllYes = true;
    boolean superSeedAllNo = true;
    boolean upSpeedDisabled = false;
    long totalUpSpeed = 0;
    boolean upSpeedUnlimited = false;
    long upSpeedSetMax = 0;
    boolean downSpeedDisabled = false;
    long totalDownSpeed = 0;
    boolean downSpeedUnlimited = false;
    long downSpeedSetMax = 0;
    boolean allScanSelected = true;
    boolean allScanNotSelected = true;
    boolean allStopped = true;
    boolean allResumeIncomplete = true;
    boolean hasClearableLinks = false;
    boolean hasRevertableFiles = false;
    if (hasSelection) {
        for (int i = 0; i < dms.length; i++) {
            DownloadManager dm = (DownloadManager) dms[i];
            try {
                int maxul = dm.getStats().getUploadRateLimitBytesPerSecond();
                if (maxul == 0) {
                    upSpeedUnlimited = true;
                } else {
                    if (maxul > upSpeedSetMax) {
                        upSpeedSetMax = maxul;
                    }
                }
                if (maxul == -1) {
                    maxul = 0;
                    upSpeedDisabled = true;
                }
                totalUpSpeed += maxul;
                int maxdl = dm.getStats().getDownloadRateLimitBytesPerSecond();
                if (maxdl == 0) {
                    downSpeedUnlimited = true;
                } else {
                    if (maxdl > downSpeedSetMax) {
                        downSpeedSetMax = maxdl;
                    }
                }
                if (maxdl == -1) {
                    maxdl = 0;
                    downSpeedDisabled = true;
                }
                totalDownSpeed += maxdl;
            } catch (Exception ex) {
                Debug.printStackTrace(ex);
            }
            if (barsOpened && !DownloadBar.getManager().isOpen(dm)) {
                barsOpened = false;
            }
            stop = stop || ManagerUtils.isStopable(dm);
            start = start || ManagerUtils.isStartable(dm);
            pause = pause || ManagerUtils.isPauseable(dm);
            recheck = recheck || dm.canForceRecheck();
            forceStartEnabled = forceStartEnabled || ManagerUtils.isForceStartable(dm);
            forceStart = forceStart || dm.isForceStart();
            boolean stopped = ManagerUtils.isStopped(dm);
            allStopped &= stopped;
            fileMove = fileMove && dm.canMoveDataFiles();
            fileExport = fileExport && dm.canExportDownload();
            if (userMode < 2) {
                TRTrackerAnnouncer trackerClient = dm.getTrackerClient();
                if (trackerClient != null) {
                    boolean update_state = ((SystemTime.getCurrentTime() / 1000 - trackerClient.getLastUpdateTime() >= TRTrackerAnnouncer.REFRESH_MINIMUM_SECS));
                    manualUpdate = manualUpdate & update_state;
                }
            }
            int state = dm.getState();
            bChangeDir &= (state == DownloadManager.STATE_ERROR || state == DownloadManager.STATE_STOPPED || state == DownloadManager.STATE_QUEUED);
            /**
             * Only perform a test on disk if:
             *    1) We are currently set to allow the "Change Data Directory" option, and
             *    2) We've only got one item selected - otherwise, we may potentially end up checking massive
             *       amounts of files across multiple torrents before we generate a menu.
             */
            if (bChangeDir && dms.length == 1) {
                bChangeDir = dm.isDataAlreadyAllocated();
                if (bChangeDir && state == DownloadManager.STATE_ERROR) {
                    // filesExist is way too slow!
                    bChangeDir = !dm.filesExist(true);
                } else {
                    bChangeDir = false;
                }
            }
            boolean incomplete = !dm.isDownloadComplete(true);
            DownloadManagerState dm_state = dm.getDownloadState();
            String moc_dir = dm_state.getAttribute(DownloadManagerState.AT_MOVE_ON_COMPLETE_DIR);
            canSetMOC &= incomplete;
            canClearMOC |= (moc_dir != null && moc_dir.length() > 0);
            boolean scan = dm_state.getFlag(DownloadManagerState.FLAG_SCAN_INCOMPLETE_PIECES);
            // include DND files in incomplete stat, since a recheck may
            // find those files have been completed
            allScanSelected = incomplete && allScanSelected && scan;
            allScanNotSelected = incomplete && allScanNotSelected && !scan;
            PEPeerManager pm = dm.getPeerManager();
            if (pm != null) {
                if (pm.canToggleSuperSeedMode()) {
                    canSetSuperSeed = true;
                }
                if (pm.isSuperSeedMode()) {
                    superSeedAllYes = false;
                } else {
                    superSeedAllNo = false;
                }
            } else {
                superSeedAllYes = false;
                superSeedAllNo = false;
            }
            if (dm_state.isResumeDataComplete()) {
                allResumeIncomplete = false;
            }
            if (stopped && !hasClearableLinks) {
                if (dm.getDiskManagerFileInfoSet().nbFiles() > 1) {
                    if (dm_state.getFileLinks().hasLinks()) {
                        hasClearableLinks = true;
                    }
                }
            }
            if (dm_state.getFileLinks().size() > 0) {
                hasRevertableFiles = true;
            }
        }
        fileRescan = allScanSelected || allScanNotSelected;
    } else {
        // empty right-click
        barsOpened = false;
        forceStart = false;
        forceStartEnabled = false;
        start = false;
        stop = false;
        fileMove = false;
        fileExport = false;
        fileRescan = false;
        canSetMOC = false;
        upSpeedDisabled = true;
        downSpeedDisabled = true;
        changeUrl = false;
        recheck = false;
        manualUpdate = false;
    }
    if (bChangeDir) {
        MenuItem menuItemChangeDir = new MenuItem(menu, SWT.PUSH);
        Messages.setLanguageText(menuItemChangeDir, "MyTorrentsView.menu.changeDirectory");
        menuItemChangeDir.addListener(SWT.Selection, new Listener() {

            @Override
            public void handleEvent(Event e) {
                changeDirSelectedTorrents(dms, shell);
            }
        });
    }
    // Open Details
    if (include_show_details) {
        final MenuItem itemDetails = new MenuItem(menu, SWT.PUSH);
        Messages.setLanguageText(itemDetails, "MyTorrentsView.menu.showdetails");
        menu.setDefaultItem(itemDetails);
        Utils.setMenuItemImage(itemDetails, "details");
        itemDetails.addListener(SWT.Selection, new ListenerDMTask(dms) {

            @Override
            public void run(DownloadManager dm) {
                UIFunctions uiFunctions = UIFunctionsManager.getUIFunctions();
                if (uiFunctions != null) {
                    uiFunctions.getMDI().showEntryByID(MultipleDocumentInterface.SIDEBAR_SECTION_TORRENT_DETAILS, dm);
                }
            }
        });
        itemDetails.setEnabled(hasSelection);
    }
    // Open Bar
    final MenuItem itemBar = new MenuItem(menu, SWT.CHECK);
    Messages.setLanguageText(itemBar, "MyTorrentsView.menu.showdownloadbar");
    Utils.setMenuItemImage(itemBar, "downloadBar");
    itemBar.addListener(SWT.Selection, new ListenerDMTask(dms) {

        @Override
        public void run(DownloadManager dm) {
            if (DownloadBar.getManager().isOpen(dm)) {
                DownloadBar.close(dm);
            } else {
                DownloadBar.open(dm, shell);
            }
        }
    });
    itemBar.setEnabled(hasSelection);
    itemBar.setSelection(barsOpened);
    // ---
    new MenuItem(menu, SWT.SEPARATOR);
    // Run Data File
    final MenuItem itemOpen = new MenuItem(menu, SWT.PUSH);
    Messages.setLanguageText(itemOpen, "MyTorrentsView.menu.open");
    Utils.setMenuItemImage(itemOpen, "run");
    itemOpen.addListener(SWT.Selection, new ListenerDMTask(dms) {

        @Override
        public void run(DownloadManager[] dms) {
            runDataSources(dms);
        }
    });
    itemOpen.setEnabled(hasSelection);
    // Explore (or open containing folder)
    final boolean use_open_containing_folder = COConfigurationManager.getBooleanParameter("MyTorrentsView.menu.show_parent_folder_enabled");
    final MenuItem itemExplore = new MenuItem(menu, SWT.PUSH);
    Messages.setLanguageText(itemExplore, "MyTorrentsView.menu." + (use_open_containing_folder ? "open_parent_folder" : "explore"));
    itemExplore.addListener(SWT.Selection, new ListenerDMTask(dms, false) {

        @Override
        public void run(DownloadManager dm) {
            ManagerUtils.open(dm, use_open_containing_folder);
        }
    });
    itemExplore.setEnabled(hasSelection);
    // Open in browser
    final Menu menuBrowse = new Menu(menu_shell, SWT.DROP_DOWN);
    final MenuItem itemBrowse = new MenuItem(menu, SWT.CASCADE);
    Messages.setLanguageText(itemBrowse, "MyTorrentsView.menu.browse");
    itemBrowse.setMenu(menuBrowse);
    final MenuItem itemBrowsePublic = new MenuItem(menuBrowse, SWT.PUSH);
    itemBrowsePublic.setText(MessageText.getString("label.public") + "...");
    itemBrowsePublic.addListener(SWT.Selection, new ListenerDMTask(dms) {

        @Override
        public void run(DownloadManager dm) {
            ManagerUtils.browse(dm, false, true);
        }
    });
    final MenuItem itemBrowseAnon = new MenuItem(menuBrowse, SWT.PUSH);
    itemBrowseAnon.setText(MessageText.getString("label.anon") + "...");
    itemBrowseAnon.addListener(SWT.Selection, new ListenerDMTask(dms) {

        @Override
        public void run(DownloadManager dm) {
            ManagerUtils.browse(dm, true, true);
        }
    });
    new MenuItem(menuBrowse, SWT.SEPARATOR);
    final MenuItem itemBrowseURL = new MenuItem(menuBrowse, SWT.PUSH);
    Messages.setLanguageText(itemBrowseURL, "label.copy.url.to.clip");
    itemBrowseURL.addListener(SWT.Selection, new Listener() {

        @Override
        public void handleEvent(Event event) {
            Utils.getOffOfSWTThread(new AERunnable() {

                @Override
                public void runSupport() {
                    String url = ManagerUtils.browse(dms[0], true, false);
                    if (url != null) {
                        ClipboardCopy.copyToClipBoard(url);
                    }
                }
            });
        }
    });
    itemBrowseURL.setEnabled(isSingleSelection);
    new MenuItem(menuBrowse, SWT.SEPARATOR);
    final MenuItem itemBrowseDir = new MenuItem(menuBrowse, SWT.CHECK);
    Messages.setLanguageText(itemBrowseDir, "library.launch.web.in.browser.dir.list");
    itemBrowseDir.setSelection(COConfigurationManager.getBooleanParameter("Library.LaunchWebsiteInBrowserDirList"));
    itemBrowseDir.addListener(SWT.Selection, new Listener() {

        @Override
        public void handleEvent(Event event) {
            COConfigurationManager.setParameter("Library.LaunchWebsiteInBrowserDirList", itemBrowseDir.getSelection());
        }
    });
    itemBrowse.setEnabled(hasSelection);
    // === advanced menu ===
    final MenuItem itemAdvanced = new MenuItem(menu, SWT.CASCADE);
    // $NON-NLS-1$
    Messages.setLanguageText(itemAdvanced, "MyTorrentsView.menu.advancedmenu");
    itemAdvanced.setEnabled(hasSelection);
    final Menu menuAdvanced = new Menu(menu_shell, SWT.DROP_DOWN);
    itemAdvanced.setMenu(menuAdvanced);
    // advanced > Download Speed Menu //
    long kInB = DisplayFormatters.getKinB();
    long maxDownload = COConfigurationManager.getIntParameter("Max Download Speed KBs", 0) * kInB;
    long maxUpload = COConfigurationManager.getIntParameter("Max Upload Speed KBs", 0) * kInB;
    ViewUtils.addSpeedMenu(menu_shell, menuAdvanced, true, true, true, hasSelection, downSpeedDisabled, downSpeedUnlimited, totalDownSpeed, downSpeedSetMax, maxDownload, upSpeedDisabled, upSpeedUnlimited, totalUpSpeed, upSpeedSetMax, maxUpload, dms.length, null, new ViewUtils.SpeedAdapter() {

        @Override
        public void setDownSpeed(final int speed) {
            ListenerDMTask task = new ListenerDMTask(dms) {

                @Override
                public void run(DownloadManager dm) {
                    dm.getStats().setDownloadRateLimitBytesPerSecond(speed);
                }
            };
            task.go();
        }

        @Override
        public void setUpSpeed(final int speed) {
            ListenerDMTask task = new ListenerDMTask(dms) {

                @Override
                public void run(DownloadManager dm) {
                    dm.getStats().setUploadRateLimitBytesPerSecond(speed);
                }
            };
            task.go();
        }
    });
    // advanced > Speed Limits
    final Menu speedLimitsMenu = new Menu(menuAdvanced.getShell(), SWT.DROP_DOWN);
    final MenuItem speedLimitsMenuItem = new MenuItem(menuAdvanced, SWT.CASCADE);
    Messages.setLanguageText(speedLimitsMenuItem, IMenuConstants.MENU_ID_SPEED_LIMITS);
    speedLimitsMenuItem.setMenu(speedLimitsMenu);
    MenuBuildUtils.addMaintenanceListenerForMenu(speedLimitsMenu, new MenuBuildUtils.MenuBuilder() {

        @Override
        public void buildMenu(Menu menu, MenuEvent menuEvent) {
            addSpeedLimitsMenu(dms, speedLimitsMenu);
        }
    });
    // advanced > Tracker Menu //
    final Menu menuTracker = new Menu(menu_shell, SWT.DROP_DOWN);
    final MenuItem itemTracker = new MenuItem(menuAdvanced, SWT.CASCADE);
    Messages.setLanguageText(itemTracker, "MyTorrentsView.menu.tracker");
    itemTracker.setMenu(menuTracker);
    itemExplore.setEnabled(hasSelection);
    addTrackerTorrentMenu(menuTracker, dms, changeUrl, manualUpdate, allStopped, use_open_containing_folder, fileMove);
    // advanced > files
    final MenuItem itemFiles = new MenuItem(menuAdvanced, SWT.CASCADE);
    Messages.setLanguageText(itemFiles, "ConfigView.section.files");
    final Menu menuFiles = new Menu(menu_shell, SWT.DROP_DOWN);
    itemFiles.setMenu(menuFiles);
    final MenuItem itemFileMoveData = new MenuItem(menuFiles, SWT.PUSH);
    Messages.setLanguageText(itemFileMoveData, "MyTorrentsView.menu.movedata");
    itemFileMoveData.addListener(SWT.Selection, new ListenerDMTask(dms) {

        @Override
        public void run(DownloadManager[] dms) {
            moveDataFiles(shell, dms);
        }
    });
    itemFileMoveData.setEnabled(fileMove);
    final MenuItem itemFileMoveTorrent = new MenuItem(menuFiles, SWT.PUSH);
    Messages.setLanguageText(itemFileMoveTorrent, "MyTorrentsView.menu.movetorrent");
    itemFileMoveTorrent.addListener(SWT.Selection, new ListenerDMTask(dms) {

        @Override
        public void run(DownloadManager[] dms) {
            moveTorrentFile(shell, dms);
        }
    });
    itemFileMoveTorrent.setEnabled(fileMove);
    // move on complete
    final Menu moc_menu = new Menu(shell, SWT.DROP_DOWN);
    MenuItem moc_item = new MenuItem(menuFiles, SWT.CASCADE);
    Messages.setLanguageText(moc_item, "label.move.on.comp");
    moc_item.setMenu(moc_menu);
    MenuItem clear_item = new MenuItem(moc_menu, SWT.PUSH);
    Messages.setLanguageText(clear_item, "Button.clear");
    clear_item.addListener(SWT.Selection, new ListenerDMTask(dms) {

        @Override
        public void run(DownloadManager[] dms) {
            clearMOC(dms);
        }
    });
    clear_item.setEnabled(canClearMOC);
    MenuItem set_item = new MenuItem(moc_menu, SWT.PUSH);
    Messages.setLanguageText(set_item, "label.set");
    set_item.addListener(SWT.Selection, new ListenerDMTask(dms) {

        @Override
        public void run(DownloadManager[] dms) {
            setMOC(shell, dms);
        }
    });
    set_item.setEnabled(canSetMOC);
    moc_item.setEnabled(canClearMOC || canSetMOC);
    // file export
    final MenuItem itemFileExport = new MenuItem(menuFiles, SWT.PUSH);
    Messages.setLanguageText(itemFileExport, "MyTorrentsView.menu.exportdownload");
    itemFileExport.addListener(SWT.Selection, new ListenerDMTask(dms) {

        @Override
        public void run(DownloadManager[] dms) {
            exportDownloads(shell, dms);
        }
    });
    itemFileExport.setEnabled(fileExport);
    final MenuItem itemCheckFilesExist = new MenuItem(menuFiles, SWT.PUSH);
    Messages.setLanguageText(itemCheckFilesExist, "MyTorrentsView.menu.checkfilesexist");
    itemCheckFilesExist.addListener(SWT.Selection, new ListenerDMTask(dms) {

        @Override
        public void run(DownloadManager dm) {
            dm.filesExist(true);
        }
    });
    final MenuItem itemLocateFiles = new MenuItem(menuFiles, SWT.PUSH);
    Messages.setLanguageText(itemLocateFiles, "MyTorrentsView.menu.locatefiles");
    itemLocateFiles.addListener(SWT.Selection, new ListenerDMTask(dms) {

        @Override
        public void run(DownloadManager[] dms) {
            ManagerUtils.locateFiles(dms, shell);
        }
    });
    final MenuItem itemFileRescan = new MenuItem(menuFiles, SWT.CHECK);
    Messages.setLanguageText(itemFileRescan, "MyTorrentsView.menu.rescanfile");
    itemFileRescan.addListener(SWT.Selection, new ListenerDMTask(dms) {

        @Override
        public void run(DownloadManager dm) {
            dm.getDownloadState().setFlag(DownloadManagerState.FLAG_SCAN_INCOMPLETE_PIECES, itemFileRescan.getSelection());
        }
    });
    itemFileRescan.setSelection(allScanSelected);
    itemFileRescan.setEnabled(fileRescan);
    // revert
    final MenuItem itemRevertFiles = new MenuItem(menu, SWT.PUSH);
    Messages.setLanguageText(itemRevertFiles, "MyTorrentsView.menu.revertfiles");
    itemRevertFiles.addListener(SWT.Selection, new ListenerDMTask(dms) {

        @Override
        public void run(DownloadManager[] dms) {
            FilesViewMenuUtil.revertFiles(tv, dms);
        }
    });
    itemRevertFiles.setEnabled(hasRevertableFiles);
    // clear links
    final MenuItem itemClearLinks = new MenuItem(menuFiles, SWT.PUSH);
    Messages.setLanguageText(itemClearLinks, "FilesView.menu.clear.links");
    itemClearLinks.addListener(SWT.Selection, new ListenerDMTask(dms) {

        @Override
        public void run(DownloadManager dm) {
            if (ManagerUtils.isStopped(dm) && dm.getDownloadState().getFileLinks().hasLinks()) {
                DiskManagerFileInfoSet fis = dm.getDiskManagerFileInfoSet();
                if (fis.nbFiles() > 1) {
                    DiskManagerFileInfo[] files = fis.getFiles();
                    for (DiskManagerFileInfo file_info : files) {
                        File file_link = file_info.getFile(true);
                        File file_nolink = file_info.getFile(false);
                        if (!file_nolink.getAbsolutePath().equals(file_link.getAbsolutePath())) {
                            file_info.setLink(null);
                        }
                    }
                }
            }
        }
    });
    itemClearLinks.setEnabled(hasClearableLinks);
    // clear allocation
    MenuItem itemFileClearAlloc = new MenuItem(menuFiles, SWT.PUSH);
    Messages.setLanguageText(itemFileClearAlloc, "MyTorrentsView.menu.clear_alloc_data");
    itemFileClearAlloc.addListener(SWT.Selection, new ListenerDMTask(dms) {

        @Override
        public void run(DownloadManager dm) {
            dm.setDataAlreadyAllocated(false);
        }
    });
    itemFileClearAlloc.setEnabled(allStopped);
    // clear resume
    MenuItem itemFileClearResume = new MenuItem(menuFiles, SWT.PUSH);
    Messages.setLanguageText(itemFileClearResume, "MyTorrentsView.menu.clear_resume_data");
    itemFileClearResume.addListener(SWT.Selection, new ListenerDMTask(dms) {

        @Override
        public void run(DownloadManager dm) {
            dm.getDownloadState().clearResumeData();
        }
    });
    itemFileClearResume.setEnabled(allStopped);
    // set resume complete
    MenuItem itemFileSetResumeComplete = new MenuItem(menuFiles, SWT.PUSH);
    Messages.setLanguageText(itemFileSetResumeComplete, "MyTorrentsView.menu.set.resume.complete");
    itemFileSetResumeComplete.addListener(SWT.Selection, new ListenerDMTask(dms) {

        @Override
        public void run(DownloadManager dm) {
            TorrentUtils.setResumeDataCompletelyValid(dm.getDownloadState());
        }
    });
    itemFileSetResumeComplete.setEnabled(allStopped && allResumeIncomplete);
    // Advanced -> archive
    final List<Download> ar_dms = new ArrayList<>();
    for (DownloadManager dm : dms) {
        Download stub = PluginCoreUtils.wrap(dm);
        if (!stub.canStubbify()) {
            continue;
        }
        ar_dms.add(stub);
    }
    MenuItem itemArchive = new MenuItem(menuAdvanced, SWT.PUSH);
    Messages.setLanguageText(itemArchive, "MyTorrentsView.menu.archive");
    Utils.setMenuItemImage(itemArchive, "archive");
    itemArchive.addListener(SWT.Selection, new ListenerDMTask(dms) {

        @Override
        public void run(DownloadManager dm) {
            ManagerUtils.moveToArchive(ar_dms, null);
        }
    });
    itemArchive.setEnabled(ar_dms.size() > 0);
    // Advanced - > Rename
    final MenuItem itemRename = new MenuItem(menuAdvanced, SWT.DROP_DOWN);
    Messages.setLanguageText(itemRename, "MyTorrentsView.menu.rename");
    itemRename.setEnabled(hasSelection);
    itemRename.addListener(SWT.Selection, new Listener() {

        @Override
        public void handleEvent(Event event) {
            for (DownloadManager dm : dms) {
                AdvRenameWindow window = new AdvRenameWindow();
                window.open(dm);
            }
        }
    });
    if (ManagerUtils.canFindMoreLikeThis()) {
        final MenuItem itemFindMore = new MenuItem(menuAdvanced, SWT.PUSH);
        Messages.setLanguageText(itemFindMore, "MyTorrentsView.menu.findmorelikethis");
        itemFindMore.addListener(SWT.Selection, new ListenerDMTask(dms) {

            @Override
            public void run(DownloadManager[] dms) {
                ManagerUtils.findMoreLikeThis(dms[0], shell);
            }
        });
        itemFindMore.setSelection(isSingleSelection);
    }
    // === advanced > quick view
    final Menu quickViewMenu = new Menu(menuAdvanced.getShell(), SWT.DROP_DOWN);
    final MenuItem quickViewMenuItem = new MenuItem(menuAdvanced, SWT.CASCADE);
    Messages.setLanguageText(quickViewMenuItem, IMenuConstants.MENU_ID_QUICK_VIEW);
    quickViewMenuItem.setMenu(quickViewMenu);
    MenuBuildUtils.addMaintenanceListenerForMenu(quickViewMenu, new MenuBuildUtils.MenuBuilder() {

        @Override
        public void buildMenu(Menu menu, MenuEvent menuEvent) {
            DownloadManager dm = dms[0];
            DiskManagerFileInfo[] files = dm.getDiskManagerFileInfoSet().getFiles();
            int added = 0;
            for (final DiskManagerFileInfo file : files) {
                if (Utils.isQuickViewSupported(file)) {
                    final MenuItem addItem = new MenuItem(menu, SWT.CHECK);
                    addItem.setSelection(Utils.isQuickViewActive(file));
                    addItem.setText(file.getTorrentFile().getRelativePath());
                    addItem.addListener(SWT.Selection, new Listener() {

                        @Override
                        public void handleEvent(Event arg) {
                            Utils.setQuickViewActive(file, addItem.getSelection());
                        }
                    });
                    added++;
                }
            }
            if (added == 0) {
                final MenuItem addItem = new MenuItem(menu, SWT.PUSH);
                addItem.setText(MessageText.getString("quick.view.no.files"));
                addItem.setEnabled(false);
            }
        }
    });
    quickViewMenuItem.setEnabled(isSingleSelection);
    // Alerts
    MenuFactory.addAlertsMenu(menuAdvanced, true, dms);
    if (userMode > 0) {
        final MenuItem itemExport = new MenuItem(menuAdvanced, SWT.CASCADE);
        // $NON-NLS-1$
        Messages.setLanguageText(itemExport, "MyTorrentsView.menu.exportmenu");
        Utils.setMenuItemImage(itemExport, "export");
        itemExport.setEnabled(hasSelection);
        final Menu menuExport = new Menu(menu_shell, SWT.DROP_DOWN);
        itemExport.setMenu(menuExport);
        // Advanced > Export > Export XML
        final MenuItem itemExportXML = new MenuItem(menuExport, SWT.PUSH);
        Messages.setLanguageText(itemExportXML, "MyTorrentsView.menu.export");
        itemExportXML.addListener(SWT.Selection, new ListenerDMTask(dms) {

            @Override
            public void run(DownloadManager[] dms) {
                // First only.
                DownloadManager dm = dms[0];
                if (dm != null)
                    new ExportTorrentWizard(itemExportXML.getDisplay(), dm);
            }
        });
        // Advanced > Export > Export Torrent
        final MenuItem itemExportTorrent = new MenuItem(menuExport, SWT.PUSH);
        Messages.setLanguageText(itemExportTorrent, "MyTorrentsView.menu.exporttorrent");
        itemExportTorrent.addListener(SWT.Selection, new ListenerDMTask(dms) {

            @Override
            public void run(DownloadManager[] dms) {
                exportTorrent(dms, shell);
            }
        });
        // end DMTask
        // Advanced > Export > WebSeed URL
        final MenuItem itemWebSeed = new MenuItem(menuExport, SWT.PUSH);
        Messages.setLanguageText(itemWebSeed, "MyTorrentsView.menu.exporthttpseeds");
        itemWebSeed.addListener(SWT.Selection, new ListenerDMTask(dms) {

            @Override
            public void run(DownloadManager[] dms) {
                exportHTTPSeeds(dms);
            }
        });
    }
    if (userMode > 0) {
        final MenuItem itemExportXML = new MenuItem(menuAdvanced, SWT.PUSH);
        Messages.setLanguageText(itemExportXML, "label.options.and.info");
        itemExportXML.addListener(SWT.Selection, new ListenerDMTask(dms) {

            @Override
            public void run(DownloadManager[] dms) {
                UIFunctions uiFunctions = UIFunctionsManager.getUIFunctions();
                if (uiFunctions != null) {
                    uiFunctions.getMDI().showEntryByID(MultipleDocumentInterface.SIDEBAR_SECTION_TORRENT_OPTIONS, dms);
                }
            }
        });
    }
    if (userMode > 0) {
        final MenuItem itemPeerSource = new MenuItem(menuAdvanced, SWT.CASCADE);
        // $NON-NLS-1$
        Messages.setLanguageText(itemPeerSource, "MyTorrentsView.menu.peersource");
        final Menu menuPeerSource = new Menu(menu_shell, SWT.DROP_DOWN);
        itemPeerSource.setMenu(menuPeerSource);
        addPeerSourceSubMenu(dms, menuPeerSource);
    }
    // Sequential download
    {
        final MenuItem dl_seq_enable = new MenuItem(menuAdvanced, SWT.CHECK);
        Messages.setLanguageText(dl_seq_enable, "menu.sequential.download");
        dl_seq_enable.addListener(SWT.Selection, new ListenerDMTask(dms) {

            @Override
            public void run(DownloadManager dm) {
                dm.getDownloadState().setFlag(DownloadManagerState.FLAG_SEQUENTIAL_DOWNLOAD, dl_seq_enable.getSelection());
            }
        });
        boolean allSeq = true;
        boolean AllNonSeq = true;
        for (int j = 0; j < dms.length; j++) {
            DownloadManager dm = dms[j];
            boolean seq = dm.getDownloadState().getFlag(DownloadManagerState.FLAG_SEQUENTIAL_DOWNLOAD);
            if (seq) {
                AllNonSeq = false;
            } else {
                allSeq = false;
            }
        }
        boolean bChecked;
        if (allSeq) {
            bChecked = true;
        } else if (AllNonSeq) {
            bChecked = false;
        } else {
            bChecked = false;
        }
        dl_seq_enable.setSelection(bChecked);
    }
    // IP Filter Enable
    if (userMode > 0) {
        final MenuItem ipf_enable = new MenuItem(menuAdvanced, SWT.CHECK);
        Messages.setLanguageText(ipf_enable, "MyTorrentsView.menu.ipf_enable");
        ipf_enable.addListener(SWT.Selection, new ListenerDMTask(dms) {

            @Override
            public void run(DownloadManager dm) {
                dm.getDownloadState().setFlag(DownloadManagerState.FLAG_DISABLE_IP_FILTER, !ipf_enable.getSelection());
            }
        });
        boolean bEnabled = IpFilterManagerFactory.getSingleton().getIPFilter().isEnabled();
        if (bEnabled) {
            boolean allChecked = true;
            boolean allUnchecked = true;
            for (int j = 0; j < dms.length; j++) {
                DownloadManager dm = (DownloadManager) dms[j];
                boolean b = dm.getDownloadState().getFlag(DownloadManagerState.FLAG_DISABLE_IP_FILTER);
                if (b) {
                    allUnchecked = false;
                } else {
                    allChecked = false;
                }
            }
            boolean bChecked;
            if (allUnchecked) {
                bChecked = true;
            } else if (allChecked) {
                bChecked = false;
            } else {
                bChecked = false;
            }
            ipf_enable.setSelection(bChecked);
        }
        ipf_enable.setEnabled(bEnabled);
    }
    if (userMode > 1) {
        final MenuItem itemNetworks = new MenuItem(menuAdvanced, SWT.CASCADE);
        // $NON-NLS-1$
        Messages.setLanguageText(itemNetworks, "MyTorrentsView.menu.networks");
        final Menu menuNetworks = new Menu(menu_shell, SWT.DROP_DOWN);
        itemNetworks.setMenu(menuNetworks);
        addNetworksSubMenu(dms, menuNetworks);
    }
    // superseed
    if (userMode > 1 && isSeedingView) {
        final MenuItem itemSuperSeed = new MenuItem(menuAdvanced, SWT.CHECK);
        Messages.setLanguageText(itemSuperSeed, "ManagerItem.superseeding");
        boolean enabled = canSetSuperSeed && (superSeedAllNo || superSeedAllYes);
        itemSuperSeed.setEnabled(enabled);
        final boolean selected = superSeedAllNo;
        if (enabled) {
            itemSuperSeed.setSelection(selected);
            itemSuperSeed.addListener(SWT.Selection, new ListenerDMTask(dms) {

                @Override
                public void run(DownloadManager dm) {
                    PEPeerManager pm = dm.getPeerManager();
                    if (pm != null) {
                        if (pm.isSuperSeedMode() == selected && pm.canToggleSuperSeedMode()) {
                            pm.setSuperSeedMode(!selected);
                        }
                    }
                }
            });
        }
    }
    // Advanced > Pause For..
    if (userMode > 0) {
        boolean can_pause = false;
        for (int i = 0; i < dms.length; i++) {
            DownloadManager dm = dms[i];
            if (ManagerUtils.isPauseable(dm)) {
                can_pause = true;
                break;
            }
        }
        final MenuItem itemPauseFor = new MenuItem(menuAdvanced, SWT.PUSH);
        itemPauseFor.setEnabled(can_pause);
        Messages.setLanguageText(itemPauseFor, "MainWindow.menu.transfers.pausetransfersfor");
        itemPauseFor.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {
                pauseDownloadsFor(dms);
            }
        });
    }
    // Advanced > Reposition
    final MenuItem itemPositionManual = new MenuItem(menuAdvanced, SWT.PUSH);
    Messages.setLanguageText(itemPositionManual, "MyTorrentsView.menu.reposition.manual");
    Utils.setMenuItemImage(itemPositionManual, "move");
    itemPositionManual.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            repositionManual(tv, dms, shell, isSeedingView);
        }
    });
    // back to main menu
    if (userMode > 0 && isTrackerOn) {
        // Host
        final MenuItem itemHost = new MenuItem(menu, SWT.PUSH);
        Messages.setLanguageText(itemHost, "MyTorrentsView.menu.host");
        Utils.setMenuItemImage(itemHost, "host");
        itemHost.addListener(SWT.Selection, new Listener() {

            @Override
            public void handleEvent(Event event) {
                hostTorrents(dms);
            }
        });
        // Publish
        final MenuItem itemPublish = new MenuItem(menu, SWT.PUSH);
        Messages.setLanguageText(itemPublish, "MyTorrentsView.menu.publish");
        Utils.setMenuItemImage(itemPublish, "publish");
        itemPublish.addListener(SWT.Selection, new Listener() {

            @Override
            public void handleEvent(Event event) {
                publishTorrents(dms);
            }
        });
        itemHost.setEnabled(hasSelection);
        itemPublish.setEnabled(hasSelection);
    }
    /*  //TODO ensure that all limits combined don't go under the min 5kbs ?
		 //Disable at the end of the list, thus the first item of the array is instanciated last.
		 itemsSpeed[0] = new MenuItem(menuSpeed,SWT.PUSH);
		 Messages.setLanguageText(itemsSpeed[0],"MyTorrentsView.menu.setSpeed.disable");
		 itemsSpeed[0].setData("maxul", new Integer(-1));
		 itemsSpeed[0].addListener(SWT.Selection,itemsSpeedListener);
		 */
    // Category
    Menu menuCategory = new Menu(menu_shell, SWT.DROP_DOWN);
    final MenuItem itemCategory = new MenuItem(menu, SWT.CASCADE);
    // $NON-NLS-1$
    Messages.setLanguageText(itemCategory, "MyTorrentsView.menu.setCategory");
    // itemCategory.setImage(ImageRepository.getImage("speed"));
    itemCategory.setMenu(menuCategory);
    itemCategory.setEnabled(hasSelection);
    addCategorySubMenu(dms, menuCategory);
    // Tags
    Menu menuTags = new Menu(menu_shell, SWT.DROP_DOWN);
    final MenuItem itemTags = new MenuItem(menu, SWT.CASCADE);
    Messages.setLanguageText(itemTags, "label.tags");
    itemTags.setMenu(menuTags);
    itemTags.setEnabled(hasSelection);
    TagUIUtils.addLibraryViewTagsSubMenu(dms, menuTags);
    if (isSeedingView) {
        final MenuItem itemPersonalShare = new MenuItem(menu, SWT.PUSH);
        Messages.setLanguageText(itemPersonalShare, "MyTorrentsView.menu.create_personal_share");
        itemPersonalShare.addListener(SWT.Selection, new ListenerDMTask(dms, false) {

            @Override
            public void run(DownloadManager dm) {
                File file = dm.getSaveLocation();
                Map<String, String> properties = new HashMap<>();
                properties.put(ShareManager.PR_PERSONAL, "true");
                if (file.isFile()) {
                    ShareUtils.shareFile(file.getAbsolutePath(), properties);
                } else if (file.isDirectory()) {
                    ShareUtils.shareDir(file.getAbsolutePath(), properties);
                }
            }
        });
        boolean can_share_pers = dms.length > 0;
        for (DownloadManager dm : dms) {
            File file = dm.getSaveLocation();
            if (!file.exists()) {
                can_share_pers = false;
                break;
            }
        }
        itemPersonalShare.setEnabled(can_share_pers);
    }
    // ---
    new MenuItem(menu, SWT.SEPARATOR);
    // Queue
    final MenuItem itemQueue = new MenuItem(menu, SWT.PUSH);
    // $NON-NLS-1$
    Messages.setLanguageText(itemQueue, "MyTorrentsView.menu.queue");
    Utils.setMenuItemImage(itemQueue, "start");
    itemQueue.addListener(SWT.Selection, new Listener() {

        @Override
        public void handleEvent(Event event) {
            Utils.getOffOfSWTThread(new AERunnable() {

                @Override
                public void runSupport() {
                    queueDataSources(dms, true);
                }
            });
        }
    });
    itemQueue.setEnabled(start);
    // Force Start
    if (userMode > 0) {
        final MenuItem itemForceStart = new MenuItem(menu, SWT.CHECK);
        Messages.setLanguageText(itemForceStart, "MyTorrentsView.menu.forceStart");
        Utils.setMenuItemImage(itemForceStart, "forcestart");
        itemForceStart.addListener(SWT.Selection, new ListenerDMTask(dms) {

            @Override
            public void run(DownloadManager dm) {
                if (ManagerUtils.isForceStartable(dm)) {
                    dm.setForceStart(itemForceStart.getSelection());
                }
            }
        });
        itemForceStart.setSelection(forceStart);
        itemForceStart.setEnabled(forceStartEnabled);
    }
    // Pause
    if (userMode > 0) {
        final MenuItem itemPause = new MenuItem(menu, SWT.PUSH);
        Messages.setLanguageText(itemPause, "v3.MainWindow.button.pause");
        Utils.setMenuItemImage(itemPause, "pause");
        itemPause.addListener(SWT.Selection, new Listener() {

            @Override
            public void handleEvent(Event event) {
                Utils.getOffOfSWTThread(new AERunnable() {

                    @Override
                    public void runSupport() {
                        pauseDataSources(dms);
                    }
                });
            }
        });
        itemPause.setEnabled(pause);
    }
    // Stop
    final MenuItem itemStop = new MenuItem(menu, SWT.PUSH);
    Messages.setLanguageText(itemStop, "MyTorrentsView.menu.stop");
    Utils.setMenuItemImage(itemStop, "stop");
    itemStop.addListener(SWT.Selection, new Listener() {

        @Override
        public void handleEvent(Event event) {
            Utils.getOffOfSWTThread(new AERunnable() {

                @Override
                public void runSupport() {
                    stopDataSources(dms);
                }
            });
        }
    });
    itemStop.setEnabled(stop);
    // Force Recheck
    final MenuItem itemRecheck = new MenuItem(menu, SWT.PUSH);
    Messages.setLanguageText(itemRecheck, "MyTorrentsView.menu.recheck");
    Utils.setMenuItemImage(itemRecheck, "recheck");
    itemRecheck.addListener(SWT.Selection, new ListenerDMTask(dms) {

        @Override
        public void run(DownloadManager dm) {
            if (dm.canForceRecheck()) {
                dm.forceRecheck();
            }
        }
    });
    itemRecheck.setEnabled(recheck);
    // Delete
    final MenuItem itemRemove = new MenuItem(menu, SWT.PUSH);
    Messages.setLanguageText(itemRemove, "menu.delete.options");
    Utils.setMenuItemImage(itemRemove, "delete");
    itemRemove.addListener(SWT.Selection, new Listener() {

        @Override
        public void handleEvent(Event event) {
            removeDownloads(dms, null, true);
        }
    });
    itemRemove.setEnabled(hasSelection);
}
Also used : UIManagerListener(com.biglybt.pif.ui.UIManagerListener) UserPrompterResultListener(com.biglybt.ui.UserPrompterResultListener) UIInputReceiverListener(com.biglybt.pif.ui.UIInputReceiverListener) WebSeedsEditorListener(com.biglybt.ui.swt.maketorrent.WebSeedsEditorListener) UIToolBarActivationListener(com.biglybt.pif.ui.toolbar.UIToolBarActivationListener) TrackerEditorListener(com.biglybt.ui.swt.maketorrent.TrackerEditorListener) AdvRenameWindow(com.biglybt.ui.swt.shells.AdvRenameWindow) ExportTorrentWizard(com.biglybt.ui.swt.exporttorrent.wizard.ExportTorrentWizard) DownloadManager(com.biglybt.core.download.DownloadManager) DownloadManagerState(com.biglybt.core.download.DownloadManagerState) ViewUtils(com.biglybt.ui.swt.views.ViewUtils) MessageBoxShell(com.biglybt.ui.swt.shells.MessageBoxShell) UIFunctions(com.biglybt.ui.UIFunctions) SelectionEvent(org.eclipse.swt.events.SelectionEvent) Download(com.biglybt.pif.download.Download) MenuEvent(org.eclipse.swt.events.MenuEvent) DiskManagerFileInfo(com.biglybt.core.disk.DiskManagerFileInfo) DiskManagerFileInfoSet(com.biglybt.core.disk.DiskManagerFileInfoSet) SelectionAdapter(org.eclipse.swt.events.SelectionAdapter) TOTorrentException(com.biglybt.core.torrent.TOTorrentException) IOException(java.io.IOException) TRTrackerAnnouncer(com.biglybt.core.tracker.client.TRTrackerAnnouncer) MenuEvent(org.eclipse.swt.events.MenuEvent) SelectionEvent(org.eclipse.swt.events.SelectionEvent) PEPeerManager(com.biglybt.core.peer.PEPeerManager) File(java.io.File)

Example 25 with PEPeerManager

use of com.biglybt.core.peer.PEPeerManager in project BiglyBT by BiglySoftware.

the class ProgressPanel method makeTorrent.

public void makeTorrent() {
    int tracker_type = wizard.getTrackerType();
    if (tracker_type == NewTorrentWizard.TT_EXTERNAL) {
        TrackersUtil.getInstance().addTracker(wizard.trackerURL);
    }
    File f;
    if (wizard.create_mode == NewTorrentWizard.MODE_DIRECTORY) {
        f = new File(wizard.directoryPath);
    } else if (wizard.create_mode == NewTorrentWizard.MODE_SINGLE_FILE) {
        f = new File(wizard.singlePath);
    } else {
        f = wizard.byo_desc_file;
    }
    try {
        URL url = new URL(wizard.trackerURL);
        final TOTorrent torrent;
        if (wizard.getPieceSizeComputed()) {
            wizard.creator = TOTorrentFactory.createFromFileOrDirWithComputedPieceLength(f, url, wizard.getAddOtherHashes());
            wizard.creator.addListener(this);
            wizard.creator.setFileIsLayoutDescriptor(wizard.create_mode == NewTorrentWizard.MODE_BYO);
            torrent = wizard.creator.create();
        } else {
            wizard.creator = TOTorrentFactory.createFromFileOrDirWithFixedPieceLength(f, url, wizard.getAddOtherHashes(), wizard.getPieceSizeManual());
            wizard.creator.addListener(this);
            wizard.creator.setFileIsLayoutDescriptor(wizard.create_mode == NewTorrentWizard.MODE_BYO);
            torrent = wizard.creator.create();
        }
        if (tracker_type == NewTorrentWizard.TT_DECENTRAL) {
            TorrentUtils.setDecentralised(torrent);
        }
        torrent.setComment(wizard.getComment());
        TorrentUtils.setDHTBackupEnabled(torrent, wizard.permitDHT);
        TorrentUtils.setPrivate(torrent, wizard.getPrivateTorrent());
        LocaleTorrentUtil.setDefaultTorrentEncoding(torrent);
        // mark this newly created torrent as complete to avoid rechecking on open
        final File save_dir;
        if (wizard.create_mode == NewTorrentWizard.MODE_DIRECTORY) {
            save_dir = f;
        } else if (wizard.create_mode == NewTorrentWizard.MODE_SINGLE_FILE) {
            save_dir = f.getParentFile();
        } else {
            String save_path = COConfigurationManager.getStringParameter("Default save path");
            File f_save_path = new File(save_path);
            if (!f_save_path.canWrite()) {
                throw (new Exception("Default save path is not configured: See Tools->Options->File"));
            }
            save_dir = f_save_path;
        }
        if (wizard.useMultiTracker) {
            this.reportCurrentTask(MessageText.getString("wizard.addingmt"));
            TorrentUtils.listToAnnounceGroups(wizard.trackers, torrent);
        }
        if (wizard.useWebSeed && wizard.webseeds.size() > 0) {
            this.reportCurrentTask(MessageText.getString("wizard.webseed.adding"));
            Map ws = wizard.webseeds;
            List getright = (List) ws.get("getright");
            if (getright.size() > 0) {
                for (int i = 0; i < getright.size(); i++) {
                    reportCurrentTask("    GetRight: " + getright.get(i));
                }
                torrent.setAdditionalListProperty("url-list", new ArrayList(getright));
            }
            List webseed = (List) ws.get("webseed");
            if (webseed.size() > 0) {
                for (int i = 0; i < webseed.size(); i++) {
                    reportCurrentTask("    WebSeed: " + webseed.get(i));
                }
                torrent.setAdditionalListProperty("httpseeds", new ArrayList(webseed));
            }
        }
        // must do this last as it saves a copy of the torrent state for future opening...
        /*
       * actually, don't need to do this as the "open-for-seeding" option used when adding the download
       * does the job. Reason I stopped doing this is
       * https://sourceforge.net/tracker/index.php?func=detail&aid=1721917&group_id=84122&atid=575154
       *
	  DownloadManagerState	download_manager_state =
			DownloadManagerStateFactory.getDownloadState( torrent );

	  TorrentUtils.setResumeDataCompletelyValid( download_manager_state );

	  download_manager_state.save();
     */
        this.reportCurrentTask(MessageText.getString("wizard.maketorrent.savingfile"));
        final File torrent_file = new File(wizard.savePath);
        torrent.serialiseToBEncodedFile(torrent_file);
        this.reportCurrentTask(MessageText.getString("wizard.maketorrent.filesaved"));
        wizard.switchToClose(new Runnable() {

            @Override
            public void run() {
                show_torrent_file.setEnabled(true);
            }
        });
        if (wizard.autoOpen) {
            CoreWaiterSWT.waitForCore(TriggerInThread.NEW_THREAD, new CoreRunningListener() {

                @Override
                public void coreRunning(Core core) {
                    boolean start_stopped = COConfigurationManager.getBooleanParameter("Default Start Torrents Stopped");
                    byte[] hash = null;
                    try {
                        hash = torrent.getHash();
                    } catch (TOTorrentException e1) {
                    }
                    if (wizard.forceStart || wizard.superseed) {
                        // superseeding can only be set for an active download...
                        start_stopped = false;
                    }
                    DownloadManagerInitialisationAdapter dmia;
                    final String initialTags = wizard.getInitialTags(true);
                    if (initialTags.length() > 0) {
                        dmia = new DownloadManagerInitialisationAdapter() {

                            @Override
                            public int getActions() {
                                return (ACT_ASSIGNS_TAGS);
                            }

                            @Override
                            public void initialised(DownloadManager dm, boolean for_seeding) {
                                TagManager tm = TagManagerFactory.getTagManager();
                                TagType tag_type = tm.getTagType(TagType.TT_DOWNLOAD_MANUAL);
                                String[] bits = initialTags.replace(';', ',').split(",");
                                for (String tag : bits) {
                                    tag = tag.trim();
                                    if (tag.length() > 0) {
                                        try {
                                            Tag t = tag_type.getTag(tag, true);
                                            if (t == null) {
                                                t = tag_type.createTag(tag, true);
                                            }
                                            t.addTaggable(dm);
                                        } catch (Throwable e) {
                                            Debug.out(e);
                                        }
                                    }
                                }
                            }
                        };
                    } else {
                        dmia = null;
                    }
                    final DownloadManager dm = core.getGlobalManager().addDownloadManager(torrent_file.toString(), hash, save_dir.toString(), start_stopped ? DownloadManager.STATE_STOPPED : // persistent
                    DownloadManager.STATE_QUEUED, // persistent
                    true, // for seeding
                    true, dmia);
                    if (!start_stopped && dm != null) {
                        // We want this to move to seeding ASAP, so move it to the top
                        // of the download list, where it will do the quick check and
                        // move to the seeding list
                        // (the for seeding flag should really be smarter and verify
                        // it's a seeding torrent and set appropriately)
                        dm.getGlobalManager().moveTop(new DownloadManager[] { dm });
                    }
                    if (wizard.autoHost && wizard.getTrackerType() != NewTorrentWizard.TT_EXTERNAL) {
                        try {
                            core.getTrackerHost().hostTorrent(torrent, true, false);
                        } catch (TRHostException e) {
                            Logger.log(new LogAlert(LogAlert.REPEATABLE, "Host operation fails", e));
                        }
                    }
                    if (dm != null) {
                        if (wizard.forceStart) {
                            dm.setForceStart(true);
                        }
                        if (wizard.superseed) {
                            new AEThread2("startwait") {

                                @Override
                                public void run() {
                                    long start = SystemTime.getMonotonousTime();
                                    while (true) {
                                        if (dm.isDestroyed()) {
                                            break;
                                        }
                                        long elapsed = SystemTime.getMonotonousTime() - start;
                                        if (elapsed > 60 * 1000) {
                                            int state = dm.getState();
                                            if (state == DownloadManager.STATE_ERROR || state == DownloadManager.STATE_STOPPED) {
                                                break;
                                            }
                                        }
                                        if (elapsed > 5 * 60 * 1000) {
                                            break;
                                        }
                                        PEPeerManager pm = dm.getPeerManager();
                                        if (pm != null) {
                                            pm.setSuperSeedMode(true);
                                            break;
                                        }
                                        try {
                                            Thread.sleep(1000);
                                        } catch (Throwable e) {
                                            break;
                                        }
                                    }
                                }
                            }.start();
                        }
                    }
                }
            });
        }
    } catch (Exception e) {
        if (e instanceof TOTorrentException) {
            TOTorrentException te = (TOTorrentException) e;
            if (te.getReason() == TOTorrentException.RT_CANCELLED) {
            // expected failure, don't log exception
            } else {
                reportCurrentTask(MessageText.getString("wizard.operationfailed"));
                reportCurrentTask(TorrentUtils.exceptionToText(te));
            }
        } else {
            Debug.printStackTrace(e);
            reportCurrentTask(MessageText.getString("wizard.operationfailed"));
            reportCurrentTask(Debug.getStackTrace(e));
        }
        wizard.switchToClose();
    }
}
Also used : TRHostException(com.biglybt.core.tracker.host.TRHostException) ArrayList(java.util.ArrayList) DownloadManager(com.biglybt.core.download.DownloadManager) URL(java.net.URL) CoreRunningListener(com.biglybt.core.CoreRunningListener) ArrayList(java.util.ArrayList) List(java.util.List) Core(com.biglybt.core.Core) DownloadManagerInitialisationAdapter(com.biglybt.core.download.DownloadManagerInitialisationAdapter) TRHostException(com.biglybt.core.tracker.host.TRHostException) LogAlert(com.biglybt.core.logging.LogAlert) TagType(com.biglybt.core.tag.TagType) TagManager(com.biglybt.core.tag.TagManager) PEPeerManager(com.biglybt.core.peer.PEPeerManager) Tag(com.biglybt.core.tag.Tag) File(java.io.File) Map(java.util.Map)

Aggregations

PEPeerManager (com.biglybt.core.peer.PEPeerManager)60 DownloadManager (com.biglybt.core.download.DownloadManager)29 PEPeer (com.biglybt.core.peer.PEPeer)18 DiskManager (com.biglybt.core.disk.DiskManager)13 DiskManagerFileInfo (com.biglybt.core.disk.DiskManagerFileInfo)9 DiskManagerPiece (com.biglybt.core.disk.DiskManagerPiece)8 PEPiece (com.biglybt.core.peer.PEPiece)8 PiecePicker (com.biglybt.core.peermanager.piecepicker.PiecePicker)7 List (java.util.List)7 LogEvent (com.biglybt.core.logging.LogEvent)6 Download (com.biglybt.pif.download.Download)6 File (java.io.File)6 ArrayList (java.util.ArrayList)6 DownloadManagerState (com.biglybt.core.download.DownloadManagerState)5 TOTorrent (com.biglybt.core.torrent.TOTorrent)5 URL (java.net.URL)5 Map (java.util.Map)5 GlobalManager (com.biglybt.core.global.GlobalManager)4 Tag (com.biglybt.core.tag.Tag)4 AERunnable (com.biglybt.core.util.AERunnable)4