Search in sources :

Example 36 with DownloadManagerState

use of com.biglybt.core.download.DownloadManagerState in project BiglyBT by BiglySoftware.

the class MagnetPluginMDDownloader method startSupport.

private void startSupport(final DownloadListener listener) {
    String hash_str = ByteFormatter.encodeString(hash);
    File tmp_dir = null;
    File data_file = null;
    File torrent_file = null;
    DownloadManager download_manager = plugin_interface.getDownloadManager();
    Download download = null;
    final Throwable[] error = { null };
    final boolean[] manually_removed = { false };
    final ByteArrayOutputStream result = new ByteArrayOutputStream(32 * 1024);
    TOTorrentAnnounceURLSet[] url_sets = null;
    try {
        synchronized (active_set) {
            if (active_set.contains(hash_str)) {
                throw (new Exception("Download already active for hash " + hash_str));
            }
            active_set.add(hash_str);
        }
        Download existing_download = download_manager.getDownload(hash);
        if (existing_download != null) {
            throw (new Exception("download already exists"));
        }
        tmp_dir = AETemporaryFileHandler.createTempDir();
        int rand = RandomUtils.generateRandomIntUpto(10000);
        data_file = new File(tmp_dir, hash_str + "_" + rand + ".torrent");
        torrent_file = new File(tmp_dir, hash_str + "_" + rand + ".metatorrent");
        RandomAccessFile raf = new RandomAccessFile(data_file, "rw");
        try {
            byte[] buffer = new byte[512 * 1024];
            Arrays.fill(buffer, (byte) 0xff);
            for (long i = 0; i < 64 * 1024 * 1024; i += buffer.length) {
                raf.write(buffer);
            }
        } finally {
            raf.close();
        }
        URL announce_url = TorrentUtils.getDecentralisedURL(hash);
        TOTorrentCreator creator = TOTorrentFactory.createFromFileOrDirWithFixedPieceLength(data_file, announce_url, 16 * 1024);
        TOTorrent meta_torrent = creator.create();
        String[] bits = args.split("&");
        List<String> trackers = new ArrayList<>();
        String name = "magnet:" + Base32.encode(hash);
        Map<String, String> magnet_args = new HashMap<>();
        for (String bit : bits) {
            String[] x = bit.split("=");
            if (x.length == 2) {
                String lhs = x[0].toLowerCase();
                String rhs = UrlUtils.decode(x[1]);
                magnet_args.put(lhs, rhs);
                if (lhs.equals("tr")) {
                    String tracker = rhs;
                    trackers.add(tracker);
                } else if (lhs.equals("dn")) {
                    name = rhs;
                }
            }
        }
        if (trackers.size() > 0) {
            // stick the decentralised one we created above in position 0 - this will be
            // removed later if the torrent is downloaded
            trackers.add(0, announce_url.toExternalForm());
            TOTorrentAnnounceURLGroup ag = meta_torrent.getAnnounceURLGroup();
            List<TOTorrentAnnounceURLSet> sets = new ArrayList<>();
            for (String tracker : trackers) {
                try {
                    URL tracker_url = new URL(tracker);
                    sets.add(ag.createAnnounceURLSet(new URL[] { tracker_url }));
                } catch (Throwable e) {
                    Debug.out(e);
                }
            }
            if (sets.size() > 0) {
                url_sets = sets.toArray(new TOTorrentAnnounceURLSet[sets.size()]);
                ag.setAnnounceURLSets(url_sets);
            }
        }
        if (!data_file.delete()) {
            throw (new Exception("Failed to delete " + data_file));
        }
        meta_torrent.setHashOverride(hash);
        TorrentUtils.setFlag(meta_torrent, TorrentUtils.TORRENT_FLAG_METADATA_TORRENT, true);
        TorrentUtils.setFlag(meta_torrent, TorrentUtils.TORRENT_FLAG_LOW_NOISE, true);
        meta_torrent.serialiseToBEncodedFile(torrent_file);
        download_manager.clearNonPersistentDownloadState(hash);
        download = download_manager.addNonPersistentDownloadStopped(PluginCoreUtils.wrap(meta_torrent), torrent_file, data_file);
        String display_name = MessageText.getString("MagnetPlugin.use.md.download.name", new String[] { name });
        DownloadManagerState state = PluginCoreUtils.unwrap(download).getDownloadState();
        state.setDisplayName(display_name + ".torrent");
        if (networks.size() == 0 || (networks.size() == 1 && networks.contains(AENetworkClassifier.AT_PUBLIC))) {
            for (String network : AENetworkClassifier.AT_NETWORKS) {
                state.setNetworkEnabled(network, true);
            }
        } else {
            for (String network : networks) {
                state.setNetworkEnabled(network, true);
            }
            if (!networks.contains(AENetworkClassifier.AT_PUBLIC)) {
                state.setNetworkEnabled(AENetworkClassifier.AT_PUBLIC, false);
            }
        }
        if (!plugin.isNetworkEnabled(AENetworkClassifier.AT_PUBLIC)) {
            state.setNetworkEnabled(AENetworkClassifier.AT_PUBLIC, false);
        }
        final List<InetSocketAddress> peers_to_inject = new ArrayList<>();
        if (addresses != null && addresses.length > 0) {
            String[] enabled_nets = state.getNetworks();
            for (InetSocketAddress address : addresses) {
                String host = AddressUtils.getHostAddress(address);
                String net = AENetworkClassifier.categoriseAddress(host);
                for (String n : enabled_nets) {
                    if (n == net) {
                        peers_to_inject.add(address);
                        break;
                    }
                }
            }
        }
        final Set<String> peer_networks = new HashSet<>();
        final List<Map<String, Object>> peers_for_cache = new ArrayList<>();
        download.addPeerListener(new DownloadPeerListener() {

            @Override
            public void peerManagerAdded(final Download download, final PeerManager peer_manager) {
                if (cancelled || completed) {
                    download.removePeerListener(this);
                    return;
                }
                final PEPeerManager pm = PluginCoreUtils.unwrap(peer_manager);
                peer_manager.addListener(new PeerManagerListener2() {

                    private PeerManagerListener2 pm_listener = this;

                    private int md_size;

                    @Override
                    public void eventOccurred(PeerManagerEvent event) {
                        if (cancelled || completed) {
                            peer_manager.removeListener(this);
                            return;
                        }
                        if (event.getType() != PeerManagerEvent.ET_PEER_ADDED) {
                            return;
                        }
                        final Peer peer = event.getPeer();
                        try {
                            String peer_ip = peer.getIp();
                            String network = AENetworkClassifier.categoriseAddress(peer_ip);
                            synchronized (peer_networks) {
                                peer_networks.add(network);
                                Map<String, Object> map = new HashMap<>();
                                peers_for_cache.add(map);
                                map.put("ip", peer_ip.getBytes("UTF-8"));
                                map.put("port", new Long(peer.getPort()));
                            }
                        } catch (Throwable e) {
                            Debug.out(e);
                        }
                        peer.addListener(new PeerListener2() {

                            @Override
                            public void eventOccurred(PeerEvent event) {
                                if (cancelled || completed || md_size > 0) {
                                    peer.removeListener(this);
                                    return;
                                }
                                if (event.getType() != PeerEvent.ET_STATE_CHANGED) {
                                    return;
                                }
                                if ((Integer) event.getData() != Peer.TRANSFERING) {
                                    return;
                                }
                                synchronized (pm_listener) {
                                    if (md_size > 0) {
                                        return;
                                    }
                                    md_size = pm.getTorrentInfoDictSize();
                                    if (md_size > 0) {
                                        peer_manager.removeListener(pm_listener);
                                    } else {
                                        return;
                                    }
                                }
                                listener.reportProgress(0, md_size);
                                new AEThread2("") {

                                    @Override
                                    public void run() {
                                        DiskManagerChannel channel = null;
                                        try {
                                            channel = download.getDiskManagerFileInfo()[0].createChannel();
                                            final DiskManagerRequest request = channel.createRequest();
                                            request.setType(DiskManagerRequest.REQUEST_READ);
                                            request.setOffset(0);
                                            request.setLength(md_size);
                                            request.setMaximumReadChunkSize(16 * 1024);
                                            request.addListener(new DiskManagerListener() {

                                                @Override
                                                public void eventOccurred(DiskManagerEvent event) {
                                                    int type = event.getType();
                                                    if (type == DiskManagerEvent.EVENT_TYPE_FAILED) {
                                                        error[0] = event.getFailure();
                                                        running_sem.releaseForever();
                                                    } else if (type == DiskManagerEvent.EVENT_TYPE_SUCCESS) {
                                                        PooledByteBuffer buffer = null;
                                                        try {
                                                            buffer = event.getBuffer();
                                                            byte[] bytes = buffer.toByteArray();
                                                            int dl_size;
                                                            synchronized (MagnetPluginMDDownloader.this) {
                                                                result.write(bytes);
                                                                dl_size = result.size();
                                                                if (dl_size == md_size) {
                                                                    completed = true;
                                                                    listener.reportProgress(md_size, md_size);
                                                                    running_sem.releaseForever();
                                                                }
                                                            }
                                                            if (!completed) {
                                                                listener.reportProgress(dl_size, md_size);
                                                            }
                                                        } catch (Throwable e) {
                                                            error[0] = e;
                                                            request.cancel();
                                                            running_sem.releaseForever();
                                                        } finally {
                                                            if (buffer != null) {
                                                                buffer.returnToPool();
                                                            }
                                                        }
                                                    } else if (type == DiskManagerEvent.EVENT_TYPE_BLOCKED) {
                                                    // System.out.println( "Waiting..." );
                                                    }
                                                }
                                            });
                                            synchronized (MagnetPluginMDDownloader.this) {
                                                if (cancelled) {
                                                    return;
                                                }
                                                requests.add(request);
                                            }
                                            request.run();
                                            synchronized (MagnetPluginMDDownloader.this) {
                                                requests.remove(request);
                                            }
                                        } catch (Throwable e) {
                                            error[0] = e;
                                            running_sem.releaseForever();
                                        } finally {
                                            if (channel != null) {
                                                channel.destroy();
                                            }
                                        }
                                    }
                                }.start();
                            }
                        });
                    }
                });
            }

            @Override
            public void peerManagerRemoved(Download download, PeerManager peer_manager) {
            }
        });
        final Download f_download = download;
        DownloadManagerListener dl_listener = new DownloadManagerListener() {

            private Object lock = this;

            private TimerEventPeriodic timer_event;

            private boolean removed;

            @Override
            public void downloadAdded(final Download download) {
                if (download == f_download) {
                    synchronized (lock) {
                        if (!removed) {
                            if (timer_event == null) {
                                timer_event = SimpleTimer.addPeriodicEvent("announcer", 30 * 1000, new TimerEventPerformer() {

                                    @Override
                                    public void perform(TimerEvent event) {
                                        synchronized (lock) {
                                            if (removed) {
                                                return;
                                            }
                                            if (running_sem.isReleasedForever()) {
                                                if (timer_event != null) {
                                                    timer_event.cancel();
                                                    timer_event = null;
                                                }
                                                return;
                                            }
                                        }
                                        download.requestTrackerAnnounce(true);
                                        injectPeers(download);
                                    }
                                });
                            }
                            if (peers_to_inject.size() > 0) {
                                SimpleTimer.addEvent("injecter", SystemTime.getOffsetTime(5 * 1000), new TimerEventPerformer() {

                                    @Override
                                    public void perform(TimerEvent event) {
                                        injectPeers(download);
                                    }
                                });
                            }
                        }
                    }
                }
            }

            private void injectPeers(Download download) {
                PeerManager pm = download.getPeerManager();
                if (pm != null) {
                    for (InetSocketAddress address : peers_to_inject) {
                        pm.addPeer(AddressUtils.getHostAddress(address), address.getPort());
                    }
                }
            }

            @Override
            public void downloadRemoved(Download dl) {
                if (dl == f_download) {
                    synchronized (lock) {
                        removed = true;
                        if (timer_event != null) {
                            timer_event.cancel();
                            timer_event = null;
                        }
                    }
                    if (!(cancelled || completed)) {
                        error[0] = new Exception("Download manually removed");
                        manually_removed[0] = true;
                        running_sem.releaseForever();
                    }
                }
            }
        };
        download_manager.addListener(dl_listener, true);
        try {
            download.moveTo(1);
            download.setForceStart(true);
            download.setFlag(Download.FLAG_DISABLE_AUTO_FILE_MOVE, true);
            running_sem.reserve();
        } finally {
            download_manager.removeListener(dl_listener);
        }
        if (completed) {
            byte[] bytes = result.toByteArray();
            Map info = BDecoder.decode(bytes);
            Map map = new HashMap();
            map.put("info", info);
            TOTorrent torrent = TOTorrentFactory.deserialiseFromMap(map);
            byte[] final_hash = torrent.getHash();
            if (!Arrays.equals(hash, final_hash)) {
                throw (new Exception("Metadata torrent hash mismatch: expected=" + ByteFormatter.encodeString(hash) + ", actual=" + ByteFormatter.encodeString(final_hash)));
            }
            if (url_sets != null) {
                // first entry should be the decentralised one that we want to remove now
                List<TOTorrentAnnounceURLSet> updated = new ArrayList<>();
                for (TOTorrentAnnounceURLSet set : url_sets) {
                    if (!TorrentUtils.isDecentralised(set.getAnnounceURLs()[0])) {
                        updated.add(set);
                    }
                }
                if (updated.size() == 0) {
                    url_sets = null;
                } else {
                    url_sets = updated.toArray(new TOTorrentAnnounceURLSet[updated.size()]);
                }
            }
            if (url_sets != null) {
                torrent.setAnnounceURL(url_sets[0].getAnnounceURLs()[0]);
                torrent.getAnnounceURLGroup().setAnnounceURLSets(url_sets);
            } else {
                torrent.setAnnounceURL(TorrentUtils.getDecentralisedURL(hash));
            }
            if (peers_for_cache.size() > 0) {
                Map<String, List<Map<String, Object>>> peer_cache = new HashMap<>();
                peer_cache.put("tracker_peers", peers_for_cache);
                TorrentUtils.setPeerCache(torrent, peer_cache);
            }
            try {
                String dn = magnet_args.get("dn");
                if (dn != null) {
                    PlatformTorrentUtils.setContentTitle(torrent, dn);
                }
                String pfi_str = magnet_args.get("pfi");
                if (pfi_str != null) {
                    PlatformTorrentUtils.setContentPrimaryFileIndex(torrent, Integer.parseInt(pfi_str));
                }
            } catch (Throwable e) {
            }
            listener.complete(torrent, peer_networks);
        } else {
            if (cancelled) {
                throw (new Exception("Download cancelled"));
            } else {
                cancelSupport(true);
                try {
                    if (error[0] != null) {
                        throw (error[0]);
                    } else {
                        throw (new Exception("Download terminated prematurely"));
                    }
                } catch (Throwable e) {
                    listener.failed(manually_removed[0], e);
                    Debug.out(e);
                    throw (e);
                }
            }
        }
    } catch (Throwable e) {
        boolean was_cancelled = cancelled;
        cancelSupport(true);
        if (!was_cancelled) {
            listener.failed(manually_removed[0], e);
            Debug.out(e);
        }
    } finally {
        try {
            if (download != null) {
                try {
                    download.stop();
                } catch (Throwable e) {
                }
                try {
                    download.remove();
                } catch (Throwable e) {
                    Debug.out(e);
                }
            }
            List<DiskManagerRequest> to_cancel;
            synchronized (this) {
                to_cancel = new ArrayList<>(requests);
                requests.clear();
            }
            for (DiskManagerRequest request : to_cancel) {
                request.cancel();
            }
            if (torrent_file != null) {
                torrent_file.delete();
            }
            if (data_file != null) {
                data_file.delete();
            }
            if (tmp_dir != null) {
                tmp_dir.delete();
            }
        } catch (Throwable e) {
            Debug.out(e);
        } finally {
            synchronized (active_set) {
                active_set.remove(hash_str);
            }
            complete_sem.releaseForever();
        }
    }
}
Also used : InetSocketAddress(java.net.InetSocketAddress) DownloadManager(com.biglybt.pif.download.DownloadManager) DiskManagerListener(com.biglybt.pif.disk.DiskManagerListener) DiskManagerChannel(com.biglybt.pif.disk.DiskManagerChannel) DownloadPeerListener(com.biglybt.pif.download.DownloadPeerListener) RandomAccessFile(java.io.RandomAccessFile) PEPeerManager(com.biglybt.core.peer.PEPeerManager) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File) DownloadManagerListener(com.biglybt.pif.download.DownloadManagerListener) DownloadManagerState(com.biglybt.core.download.DownloadManagerState) URL(java.net.URL) PooledByteBuffer(com.biglybt.pif.utils.PooledByteBuffer) Download(com.biglybt.pif.download.Download) DiskManagerRequest(com.biglybt.pif.disk.DiskManagerRequest) ByteArrayOutputStream(java.io.ByteArrayOutputStream) PEPeerManager(com.biglybt.core.peer.PEPeerManager) DiskManagerEvent(com.biglybt.pif.disk.DiskManagerEvent)

Example 37 with DownloadManagerState

use of com.biglybt.core.download.DownloadManagerState in project BiglyBT by BiglySoftware.

the class ShareResourceFileOrDirImpl method createTorrent.

protected void createTorrent() throws ShareException {
    try {
        manager.reportCurrentTask((item == null ? "Creating" : "Re-creating").concat(" torrent for '").concat(file.toString()).concat("'"));
        URL[] urls = manager.getAnnounceURLs();
        TOTorrentCreator creator = TOTorrentFactory.createFromFileOrDirWithComputedPieceLength(file, urls[0], manager.getAddHashes());
        creator.addListener(manager);
        TOTorrent to_torrent;
        try {
            manager.setTorrentCreator(creator);
            to_torrent = creator.create();
        } finally {
            manager.setTorrentCreator(null);
        }
        if (personal_key != null) {
            Map map = to_torrent.serialiseToMap();
            Map info = (Map) map.get("info");
            info.put("az_salt", personal_key);
            to_torrent = TOTorrentFactory.deserialiseFromMap(map);
        }
        LocaleTorrentUtil.setDefaultTorrentEncoding(to_torrent);
        for (int i = 1; i < urls.length; i++) {
            TorrentUtils.announceGroupsInsertLast(to_torrent, new URL[] { urls[i] });
        }
        String comment = COConfigurationManager.getStringParameter("Sharing Torrent Comment").trim();
        boolean private_torrent = COConfigurationManager.getBooleanParameter("Sharing Torrent Private");
        boolean dht_backup_enabled = COConfigurationManager.getBooleanParameter("Sharing Permit DHT");
        TorrentAttribute ta_props = TorrentManagerImpl.getSingleton().getAttribute(TorrentAttribute.TA_SHARE_PROPERTIES);
        String props = getAttribute(ta_props);
        if (props != null) {
            StringTokenizer tok = new StringTokenizer(props, ";");
            while (tok.hasMoreTokens()) {
                String token = tok.nextToken();
                int pos = token.indexOf('=');
                if (pos == -1) {
                    Debug.out("ShareProperty invalid: " + props);
                } else {
                    String lhs = token.substring(0, pos).trim().toLowerCase();
                    String rhs = token.substring(pos + 1).trim().toLowerCase();
                    boolean set = rhs.equals("true");
                    if (lhs.equals("private")) {
                        private_torrent = set;
                    } else if (lhs.equals("dht_backup")) {
                        dht_backup_enabled = set;
                    } else if (lhs.equals("comment")) {
                        comment = rhs;
                    } else {
                        Debug.out("ShareProperty invalid: " + props);
                        break;
                    }
                }
            }
        }
        if (comment.length() > 0) {
            to_torrent.setComment(comment);
        }
        TorrentUtils.setDHTBackupEnabled(to_torrent, dht_backup_enabled);
        TorrentUtils.setPrivate(to_torrent, private_torrent);
        if (TorrentUtils.isDecentralised(to_torrent)) {
            TorrentUtils.setDecentralised(to_torrent);
        }
        if (COConfigurationManager.getBooleanParameter("Sharing Disable RCM")) {
            TorrentUtils.setFlag(to_torrent, TorrentUtils.TORRENT_FLAG_DISABLE_RCM, true);
        }
        DownloadManagerState download_manager_state = DownloadManagerStateFactory.getDownloadState(to_torrent);
        TorrentUtils.setResumeDataCompletelyValid(download_manager_state);
        download_manager_state.save();
        if (item == null) {
            byte[] fingerprint = getFingerPrint();
            item = new ShareItemImpl(this, fingerprint, new TorrentImpl(to_torrent));
        } else {
            item.setTorrent(new TorrentImpl(to_torrent));
            item.writeTorrent();
        }
    } catch (TOTorrentException e) {
        if (e.getReason() == TOTorrentException.RT_CANCELLED) {
            throw (new ShareException("ShareResource: Operation cancelled", e));
        } else {
            throw (new ShareException("ShareResource: Torrent create failed", e));
        }
    } catch (Throwable e) {
        throw (new ShareException("ShareResource: Torrent create failed", e));
    }
}
Also used : TorrentImpl(com.biglybt.pifimpl.local.torrent.TorrentImpl) DownloadManagerState(com.biglybt.core.download.DownloadManagerState) URL(java.net.URL) TOTorrentException(com.biglybt.core.torrent.TOTorrentException) StringTokenizer(java.util.StringTokenizer) TorrentAttribute(com.biglybt.pif.torrent.TorrentAttribute) ShareException(com.biglybt.pif.sharing.ShareException) TOTorrent(com.biglybt.core.torrent.TOTorrent) TOTorrentCreator(com.biglybt.core.torrent.TOTorrentCreator) Map(java.util.Map)

Example 38 with DownloadManagerState

use of com.biglybt.core.download.DownloadManagerState in project BiglyBT by BiglySoftware.

the class TorrentMenuFancy method buildTorrentCustomMenu_Control.

public void buildTorrentCustomMenu_Control(final Composite cParent, final DownloadManager[] dms) {
    final int userMode = COConfigurationManager.getIntParameter("User Mode");
    boolean start = false;
    boolean stop = false;
    boolean pause = false;
    boolean recheck = false;
    boolean barsOpened = true;
    boolean bChangeDir = hasSelection;
    for (int i = 0; i < dms.length; i++) {
        DownloadManager dm = dms[i];
        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();
        boolean stopped = ManagerUtils.isStopped(dm);
        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 {
                DiskManagerFileInfo[] files = dm.getDiskManagerFileInfoSet().getFiles();
                bChangeDir = false;
                for (DiskManagerFileInfo info : files) {
                    if (info.isSkipped()) {
                        continue;
                    }
                    bChangeDir = !info.getFile(true).exists();
                    break;
                }
            }
        }
    }
    Composite cQuickCommands = new Composite(cParent, SWT.NONE);
    // cQuickCommands.setBackground(ColorCache.getRandomColor());
    RowLayout rowLayout = new RowLayout(SWT.HORIZONTAL);
    rowLayout.justify = true;
    rowLayout.marginLeft = 0;
    rowLayout.marginRight = 0;
    cQuickCommands.setLayout(rowLayout);
    GridData gd = new GridData();
    gd.grabExcessHorizontalSpace = true;
    gd.horizontalAlignment = SWT.FILL;
    Utils.setLayoutData(cQuickCommands, gd);
    // Queue
    createActionButton(dms, cQuickCommands, "MyTorrentsView.menu.queue", "start", start, new ListenerGetOffSWT() {

        @Override
        void handleEventOffSWT(Event event) {
            TorrentUtil.queueDataSources(dms, true);
        }
    });
    // Force Start
    if (userMode > 0) {
        boolean forceStart = false;
        boolean forceStartEnabled = false;
        for (int i = 0; i < dms.length; i++) {
            DownloadManager dm = dms[i];
            forceStartEnabled = forceStartEnabled || ManagerUtils.isForceStartable(dm);
            forceStart = forceStart || dm.isForceStart();
        }
        final boolean newForceStart = !forceStart;
        createActionButton(dms, cQuickCommands, "MyTorrentsView.menu.forceStart", "forcestart", forceStartEnabled, forceStart ? SWT.BORDER : SWT.PUSH, new ListenerDMTask(dms) {

            @Override
            public void run(DownloadManager dm) {
                if (ManagerUtils.isForceStartable(dm)) {
                    dm.setForceStart(newForceStart);
                }
            }
        });
    }
    // Pause
    if (userMode > 0) {
        createActionButton(dms, cQuickCommands, "v3.MainWindow.button.pause", "pause", pause, new ListenerGetOffSWT() {

            @Override
            public void handleEventOffSWT(Event event) {
                TorrentUtil.pauseDataSources(dms);
            }
        });
    }
    // Stop
    createActionButton(dms, cQuickCommands, "MyTorrentsView.menu.stop", "stop", stop, new ListenerGetOffSWT() {

        @Override
        public void handleEventOffSWT(Event event) {
            TorrentUtil.stopDataSources(dms);
        }
    });
    // Force Recheck
    createActionButton(dms, cQuickCommands, "MyTorrentsView.menu.recheck", "recheck", recheck, new ListenerDMTask(dms) {

        @Override
        public void run(DownloadManager dm) {
            if (dm.canForceRecheck()) {
                dm.forceRecheck();
            }
        }
    });
    // Delete
    createActionButton(dms, cQuickCommands, "menu.delete.options", "delete", hasSelection, new Listener() {

        @Override
        public void handleEvent(Event event) {
            TorrentUtil.removeDownloads(dms, null, true);
        }
    });
    if (bChangeDir) {
        createRow(cParent, "MyTorrentsView.menu.changeDirectory", null, new Listener() {

            @Override
            public void handleEvent(Event e) {
                TorrentUtil.changeDirSelectedTorrents(dms, parentShell);
            }
        });
    }
    // Open Details
    if (hasSelection) {
        createRow(cParent, "MyTorrentsView.menu.showdetails", "details", 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);
                }
            }
        });
    }
    // Open Bar
    if (hasSelection) {
        FancyRowInfo row = createRow(cParent, "MyTorrentsView.menu.showdownloadbar", "downloadBar", new ListenerDMTask(dms) {

            @Override
            public void run(DownloadManager dm) {
                if (DownloadBar.getManager().isOpen(dm)) {
                    DownloadBar.close(dm);
                } else {
                    DownloadBar.open(dm, parentShell);
                }
            }
        });
        row.setSelection(barsOpened);
    }
    if (hasSelection) {
        FancyRowInfo rowSpeedDL = createRow(cParent, "MyTorrentsView.menu.downSpeedLimit", "image.torrentspeed.down", false, new Listener() {

            @Override
            public void handleEvent(Event e) {
                Event event = new Event();
                event.type = SWT.MouseUp;
                event.widget = e.widget;
                event.stateMask = e.stateMask;
                event.button = e.button;
                e.display.post(event);
                Core core = CoreFactory.getSingleton();
                SelectableSpeedMenu.invokeSlider((Control) event.widget, core, dms, false, shell);
                if (e.display.getActiveShell() != shell) {
                    if (!shell.isDisposed()) {
                        shell.dispose();
                    }
                    return;
                }
                FancyRowInfo rowInfo = findRowInfo(event.widget);
                if (rowInfo != null) {
                    updateRowSpeed(rowInfo, false);
                }
            }
        });
        rowSpeedDL.keepMenu = true;
        updateRowSpeed(rowSpeedDL, false);
    }
    if (hasSelection) {
        FancyRowInfo rowSpeedUL = createRow(cParent, "MyTorrentsView.menu.upSpeedLimit", "image.torrentspeed.up", false, new Listener() {

            @Override
            public void handleEvent(Event e) {
                Event event = new Event();
                event.type = SWT.MouseUp;
                event.widget = e.widget;
                event.stateMask = e.stateMask;
                event.button = e.button;
                e.display.post(event);
                Core core = CoreFactory.getSingleton();
                SelectableSpeedMenu.invokeSlider((Control) e.widget, core, dms, true, shell);
                if (e.display.getActiveShell() != shell) {
                    if (!shell.isDisposed()) {
                        shell.dispose();
                    }
                    return;
                }
                FancyRowInfo rowInfo = findRowInfo(event.widget);
                if (rowInfo != null) {
                    updateRowSpeed(rowInfo, true);
                }
            }
        });
        rowSpeedUL.keepMenu = true;
        updateRowSpeed(rowSpeedUL, true);
    }
    if (hasSelection && userMode > 0) {
        createMenuRow(cParent, "MyTorrentsView.menu.tracker", null, new FancyMenuRowInfoListener() {

            @Override
            public void buildMenu(Menu menu) {
                boolean changeUrl = hasSelection;
                boolean manualUpdate = true;
                boolean allStopped = true;
                boolean canMove = true;
                int userMode = COConfigurationManager.getIntParameter("User Mode");
                final boolean use_open_containing_folder = COConfigurationManager.getBooleanParameter("MyTorrentsView.menu.show_parent_folder_enabled");
                for (DownloadManager dm : dms) {
                    boolean stopped = ManagerUtils.isStopped(dm);
                    allStopped &= stopped;
                    canMove = canMove && dm.canMoveDataFiles();
                    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;
                        }
                    }
                }
                TorrentUtil.addTrackerTorrentMenu(menu, dms, changeUrl, manualUpdate, allStopped, use_open_containing_folder, canMove);
            }
        });
    }
    if (hasSelection) {
        Core core = CoreFactory.getSingleton();
        SpeedLimitHandler slh = SpeedLimitHandler.getSingleton(core);
        if (slh.hasAnyProfiles()) {
            createMenuRow(cParent, IMenuConstants.MENU_ID_SPEED_LIMITS, null, new FancyMenuRowInfoListener() {

                @Override
                public void buildMenu(Menu menu) {
                    TorrentUtil.addSpeedLimitsMenu(dms, menu);
                }
            });
        }
    }
    if (userMode > 0 && hasSelection) {
        boolean can_pause = false;
        for (int i = 0; i < dms.length; i++) {
            DownloadManager dm = dms[i];
            if (ManagerUtils.isPauseable(dm)) {
                can_pause = true;
                break;
            }
        }
        if (can_pause) {
            createRow(detailArea, "MainWindow.menu.transfers.pausetransfersfor", null, new Listener() {

                @Override
                public void handleEvent(Event event) {
                    TorrentUtil.pauseDownloadsFor(dms);
                }
            });
        }
    }
    if (userMode > 0 && dms.length > 1) {
        createRow(cParent, "label.options.and.info", null, 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) {
        createMenuRow(cParent, "MyTorrentsView.menu.peersource", null, new FancyMenuRowInfoListener() {

            @Override
            public void buildMenu(Menu menu) {
                TorrentUtil.addPeerSourceSubMenu(dms, menu);
            }
        });
    }
    // Sequential download
    {
        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;
        }
        final boolean newSeq = !bChecked;
        FancyRowInfo row = createRow(cParent, "menu.sequential.download", null, new ListenerDMTask(dms) {

            @Override
            public void run(DownloadManager dm) {
                dm.getDownloadState().setFlag(DownloadManagerState.FLAG_SEQUENTIAL_DOWNLOAD, newSeq);
            }
        });
        row.setSelection(bChecked);
    }
    // IP Filter Enable
    if (userMode > 0 && IpFilterManagerFactory.getSingleton().getIPFilter().isEnabled()) {
        boolean allEnabled = true;
        boolean allDisabled = true;
        for (int j = 0; j < dms.length; j++) {
            DownloadManager dm = dms[j];
            boolean filterDisabled = dm.getDownloadState().getFlag(DownloadManagerState.FLAG_DISABLE_IP_FILTER);
            if (filterDisabled) {
                allEnabled = false;
            } else {
                allDisabled = false;
            }
        }
        boolean bChecked;
        if (allEnabled) {
            bChecked = true;
        } else if (allDisabled) {
            bChecked = false;
        } else {
            bChecked = false;
        }
        final boolean newDisable = bChecked;
        FancyRowInfo row = createRow(cParent, "MyTorrentsView.menu.ipf_enable", null, new ListenerDMTask(dms) {

            @Override
            public void run(DownloadManager dm) {
                dm.getDownloadState().setFlag(DownloadManagerState.FLAG_DISABLE_IP_FILTER, newDisable);
            }
        });
        row.setSelection(bChecked);
    }
    if (userMode > 1) {
        createMenuRow(cParent, "MyTorrentsView.menu.networks", null, new FancyMenuRowInfoListener() {

            @Override
            public void buildMenu(Menu menu) {
                TorrentUtil.addNetworksSubMenu(dms, menu);
            }
        });
    }
    // Advanced menu with stuff I don't know where to put
    if (userMode > 0) {
        createMenuRow(cParent, "MyTorrentsView.menu.advancedmenu", null, new FancyMenuRowInfoListener() {

            @Override
            public void buildMenu(Menu menu) {
                boolean allStopped = true;
                boolean allScanSelected = true;
                boolean allScanNotSelected = true;
                boolean fileMove = true;
                boolean allResumeIncomplete = true;
                boolean hasClearableLinks = false;
                boolean hasRevertableFiles = false;
                for (DownloadManager dm : dms) {
                    boolean stopped = ManagerUtils.isStopped(dm);
                    allStopped &= stopped;
                    fileMove = fileMove && dm.canMoveDataFiles();
                    boolean scan = dm.getDownloadState().getFlag(DownloadManagerState.FLAG_SCAN_INCOMPLETE_PIECES);
                    // include DND files in incomplete stat, since a recheck may
                    // find those files have been completed
                    boolean incomplete = !dm.isDownloadComplete(true);
                    allScanSelected = incomplete && allScanSelected && scan;
                    allScanNotSelected = incomplete && allScanNotSelected && !scan;
                    DownloadManagerState dms = dm.getDownloadState();
                    if (dms.isResumeDataComplete()) {
                        allResumeIncomplete = false;
                    }
                    if (stopped && !hasClearableLinks) {
                        if (dm.getDiskManagerFileInfoSet().nbFiles() > 1) {
                            if (dms.getFileLinks().hasLinks()) {
                                hasClearableLinks = true;
                            }
                        }
                    }
                    if (dm.getDownloadState().getFileLinks().size() > 0) {
                        hasRevertableFiles = true;
                    }
                }
                boolean fileRescan = allScanSelected || allScanNotSelected;
                final MenuItem itemFileRescan = new MenuItem(menu, 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(menu, 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(menu, 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(menu, 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(menu, 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);
                if (userMode > 1 && isSeedingView) {
                    boolean canSetSuperSeed = false;
                    boolean superSeedAllYes = true;
                    boolean superSeedAllNo = true;
                    for (DownloadManager dm : dms) {
                        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;
                        }
                    }
                    final MenuItem itemSuperSeed = new MenuItem(menu, 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);
                                    }
                                }
                            }
                        });
                    }
                }
            }
        });
    }
}
Also used : TableSelectedRowsListener(com.biglybt.ui.swt.views.table.TableSelectedRowsListener) SpeedLimitHandler(com.biglybt.core.speedmanager.SpeedLimitHandler) DownloadManager(com.biglybt.core.download.DownloadManager) DownloadManagerState(com.biglybt.core.download.DownloadManagerState) UIFunctions(com.biglybt.ui.UIFunctions) TableRowCore(com.biglybt.ui.common.table.TableRowCore) TableCellCore(com.biglybt.ui.common.table.TableCellCore) Core(com.biglybt.core.Core) TableColumnCore(com.biglybt.ui.common.table.TableColumnCore) DiskManagerFileInfo(com.biglybt.core.disk.DiskManagerFileInfo) DiskManagerFileInfoSet(com.biglybt.core.disk.DiskManagerFileInfoSet) MenuItem(com.biglybt.pif.ui.menus.MenuItem) Point(org.eclipse.swt.graphics.Point) TRTrackerAnnouncer(com.biglybt.core.tracker.client.TRTrackerAnnouncer) PEPeerManager(com.biglybt.core.peer.PEPeerManager) File(java.io.File)

Aggregations

DownloadManagerState (com.biglybt.core.download.DownloadManagerState)38 File (java.io.File)14 DownloadManager (com.biglybt.core.download.DownloadManager)11 TOTorrent (com.biglybt.core.torrent.TOTorrent)9 TOTorrentFile (com.biglybt.core.torrent.TOTorrentFile)8 DiskManagerFileInfo (com.biglybt.core.disk.DiskManagerFileInfo)6 CacheFile (com.biglybt.core.diskmanager.cache.CacheFile)6 PEPeerManager (com.biglybt.core.peer.PEPeerManager)5 TOTorrentException (com.biglybt.core.torrent.TOTorrentException)5 Download (com.biglybt.pif.download.Download)4 UIInputReceiverListener (com.biglybt.pif.ui.UIInputReceiverListener)4 IOException (java.io.IOException)4 Map (java.util.Map)4 CoreRunningListener (com.biglybt.core.CoreRunningListener)3 DiskManagerFileInfoSet (com.biglybt.core.disk.DiskManagerFileInfoSet)3 Tag (com.biglybt.core.tag.Tag)3 UIFunctions (com.biglybt.ui.UIFunctions)3 List (java.util.List)3 Core (com.biglybt.core.Core)2 ParameterListener (com.biglybt.core.config.ParameterListener)2