Search in sources :

Example 51 with PEPeerManager

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

the class LeecherMaxCompletion method refresh.

@Override
public void refresh(TableCell cell) {
    int average = -1;
    DownloadManager dm = (DownloadManager) cell.getDataSource();
    if (dm != null) {
        PEPeerManager pm = dm.getPeerManager();
        if (pm != null) {
            average = pm.getMaxCompletionInThousandNotation(true);
        }
    }
    if (!cell.setSortValue(average) && cell.isValid()) {
        return;
    }
    if (average < 0) {
        cell.setText("");
    } else {
        cell.setText(DisplayFormatters.formatPercentFromThousands(average));
    }
}
Also used : PEPeerManager(com.biglybt.core.peer.PEPeerManager) DownloadManager(com.biglybt.core.download.DownloadManager)

Example 52 with PEPeerManager

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

the class AvailabilityItem method refresh.

@Override
public void refresh(TableCell cell) {
    String sText = "";
    DownloadManager dm = (DownloadManager) cell.getDataSource();
    if (dm == null)
        return;
    PEPeerManager pm = dm.getPeerManager();
    if (pm != null) {
        float f = pm.getMinAvailability();
        if (!cell.setSortValue((long) (f * 1000)) && cell.isValid())
            return;
        sText = String.valueOf((int) (f * iTimesBy));
        if (numZeros - sText.length() > 0)
            sText = zeros.substring(0, numZeros - sText.length()) + sText;
        sText = sText.substring(0, sText.length() - numZeros + 1) + "." + sText.substring(sText.length() - numZeros + 1);
    } else {
        cell.setSortValue(0);
    }
    cell.setText(sText);
}
Also used : PEPeerManager(com.biglybt.core.peer.PEPeerManager) DownloadManager(com.biglybt.core.download.DownloadManager)

Example 53 with PEPeerManager

use of com.biglybt.core.peer.PEPeerManager 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)

Example 54 with PEPeerManager

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

the class Show method execute.

@Override
public void execute(String commandName, ConsoleInput ci, List args) {
    if (args.isEmpty()) {
        printHelp(ci.out, args);
        return;
    }
    String subCommand = (String) args.remove(0);
    if (subCommand.equalsIgnoreCase("options") || subCommand.equalsIgnoreCase("o")) {
        ci.invokeCommand("set", null);
    } else if (subCommand.equalsIgnoreCase("files") || subCommand.equalsIgnoreCase("f")) {
        ci.invokeCommand("add", Arrays.asList(new String[] { "--list" }));
    } else if (subCommand.equalsIgnoreCase("torrents") || subCommand.equalsIgnoreCase("t")) {
        ci.out.println("> -----");
        ci.torrents.clear();
        ci.torrents.addAll(ci.getGlobalManager().getDownloadManagers());
        Collections.sort(ci.torrents, new TorrentComparator());
        if (ci.torrents.isEmpty()) {
            ci.out.println("No Torrents");
            ci.out.println("> -----");
            return;
        }
        long totalReceived = 0;
        long totalSent = 0;
        long totalDiscarded = 0;
        int connectedSeeds = 0;
        int connectedPeers = 0;
        PEPeerManagerStats ps;
        boolean bShowOnlyActive = false;
        boolean bShowOnlyComplete = false;
        boolean bShowOnlyIncomplete = false;
        boolean bShowOnlyTransferring = false;
        int bShowDeadForDays = 0;
        for (ListIterator<String> iter = args.listIterator(); iter.hasNext(); ) {
            String arg = (String) iter.next();
            if ("active".equalsIgnoreCase(arg) || "a".equalsIgnoreCase(arg)) {
                bShowOnlyActive = true;
                iter.remove();
            } else if ("complete".equalsIgnoreCase(arg) || "c".equalsIgnoreCase(arg)) {
                bShowOnlyComplete = true;
                iter.remove();
            } else if ("incomplete".equalsIgnoreCase(arg) || "i".equalsIgnoreCase(arg)) {
                bShowOnlyIncomplete = true;
                iter.remove();
            } else if ("transferring".equalsIgnoreCase(arg) || "x".equalsIgnoreCase(arg)) {
                bShowOnlyTransferring = true;
                bShowOnlyActive = true;
                iter.remove();
            } else if ("dead".equalsIgnoreCase(arg) || "d".equalsIgnoreCase(arg)) {
                iter.remove();
                // default 1 week
                bShowDeadForDays = 7;
                if (iter.hasNext()) {
                    String days = iter.next();
                    try {
                        bShowDeadForDays = Integer.parseInt(days);
                        iter.remove();
                    } catch (Throwable e) {
                        iter.previous();
                    }
                }
            }
        }
        Iterator torrent;
        if (args.size() > 0) {
            List matchedTorrents = new TorrentFilter().getTorrents(ci.torrents, args);
            torrent = matchedTorrents.iterator();
        } else
            torrent = ci.torrents.iterator();
        List shown_torrents = new ArrayList();
        while (torrent.hasNext()) {
            DownloadManager dm = (DownloadManager) torrent.next();
            DownloadManagerStats stats = dm.getStats();
            boolean bDownloadCompleted = stats.getDownloadCompleted(false) == 1000;
            boolean bCanShow = ((bShowOnlyComplete == bShowOnlyIncomplete) || (bDownloadCompleted && bShowOnlyComplete) || (!bDownloadCompleted && bShowOnlyIncomplete));
            if (bCanShow && bShowOnlyActive) {
                int dmstate = dm.getState();
                bCanShow = (dmstate == DownloadManager.STATE_SEEDING) || (dmstate == DownloadManager.STATE_DOWNLOADING) || (dmstate == DownloadManager.STATE_CHECKING) || (dmstate == DownloadManager.STATE_INITIALIZING) || (dmstate == DownloadManager.STATE_ALLOCATING);
            }
            if (bCanShow && bShowOnlyTransferring) {
                try {
                    ps = dm.getPeerManager().getStats();
                    bCanShow = ps.getDataSendRate() > 0 || ps.getDataReceiveRate() > 0;
                } catch (Exception e) {
                }
            }
            if (bCanShow && bShowDeadForDays > 0) {
                int dmstate = dm.getState();
                bCanShow = false;
                if (dmstate == DownloadManager.STATE_SEEDING || (bDownloadCompleted && (dmstate == DownloadManager.STATE_QUEUED || dmstate == DownloadManager.STATE_STOPPED))) {
                    long seeding_secs = stats.getSecondsOnlySeeding();
                    long seeding_days = seeding_secs / (24 * 60 * 60);
                    if (seeding_days >= bShowDeadForDays) {
                        int secs_since_last_up = stats.getTimeSinceLastDataSentInSeconds();
                        if (secs_since_last_up == -1) {
                            // never uploaded
                            bCanShow = true;
                        } else {
                            int days_since_last_up = secs_since_last_up / (24 * 60 * 60);
                            if (days_since_last_up >= bShowDeadForDays) {
                                bCanShow = true;
                            }
                        }
                    }
                }
            }
            if (bCanShow) {
                shown_torrents.add(dm);
                try {
                    PEPeerManager pm = dm.getPeerManager();
                    ps = pm == null ? null : pm.getStats();
                } catch (Exception e) {
                    ps = null;
                }
                if (ps != null) {
                    totalReceived += dm.getStats().getTotalDataBytesReceived();
                    totalSent += dm.getStats().getTotalDataBytesSent();
                    totalDiscarded += ps.getTotalDiscarded();
                    connectedSeeds += dm.getNbSeeds();
                    connectedPeers += dm.getNbPeers();
                }
                ci.out.print(((shown_torrents.size() < 10) ? " " : "") + shown_torrents.size() + " ");
                ci.out.println(getTorrentSummary(dm));
                ci.out.println();
            }
        }
        ci.torrents.clear();
        ci.torrents.addAll(shown_torrents);
        GlobalManager gm = ci.getGlobalManager();
        ci.out.println("Total Speed (down/up): " + DisplayFormatters.formatByteCountToKiBEtcPerSec(gm.getStats().getDataReceiveRate() + gm.getStats().getProtocolReceiveRate()) + " / " + DisplayFormatters.formatByteCountToKiBEtcPerSec(gm.getStats().getDataSendRate() + gm.getStats().getProtocolSendRate()));
        ci.out.println("Transferred Volume (down/up/discarded): " + DisplayFormatters.formatByteCountToKiBEtc(totalReceived) + " / " + DisplayFormatters.formatByteCountToKiBEtc(totalSent) + " / " + DisplayFormatters.formatByteCountToKiBEtc(totalDiscarded));
        ci.out.println("Total Connected Peers (seeds/peers): " + Integer.toString(connectedSeeds) + " / " + Integer.toString(connectedPeers));
        ci.out.println("> -----");
    } else if (subCommand.equalsIgnoreCase("dht") || subCommand.equalsIgnoreCase("d")) {
        showDHTStats(ci);
    } else if (subCommand.equalsIgnoreCase("nat") || subCommand.equalsIgnoreCase("n")) {
        IndentWriter iw = new IndentWriter(new PrintWriter(ci.out));
        iw.setForce(true);
        NetworkAdmin.getSingleton().logNATStatus(iw);
    } else if (subCommand.equalsIgnoreCase("stats") || subCommand.equalsIgnoreCase("s")) {
        String pattern = CoreStats.ST_ALL;
        if (args.size() > 0) {
            pattern = (String) args.get(0);
            if (pattern.equals("*")) {
                pattern = ".*";
            }
        }
        if (args.size() > 1) {
            CoreStats.setEnableAverages(((String) args.get(1)).equalsIgnoreCase("on"));
        }
        java.util.Set types = new HashSet();
        types.add(pattern);
        Map reply = CoreStats.getStats(types);
        Iterator it = reply.entrySet().iterator();
        List lines = new ArrayList();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            lines.add(entry.getKey() + " -> " + entry.getValue());
        }
        Collections.sort(lines);
        for (int i = 0; i < lines.size(); i++) {
            ci.out.println(lines.get(i));
        }
    } else if (subCommand.equalsIgnoreCase("diag") || subCommand.equalsIgnoreCase("z")) {
        try {
            ci.out.println("Writing diagnostics to file 'az.diag'");
            FileWriter fw = new FileWriter("az.diag");
            PrintWriter pw = new PrintWriter(fw);
            AEDiagnostics.generateEvidence(pw);
            pw.flush();
            fw.close();
        } catch (Throwable e) {
            ci.out.println(e);
        }
    } else {
        if ((ci.torrents == null) || (ci.torrents != null) && ci.torrents.isEmpty()) {
            ci.out.println("> Command 'show': No torrents in list (try 'show torrents' first).");
            return;
        }
        try {
            int number = Integer.parseInt(subCommand);
            if ((number == 0) || (number > ci.torrents.size())) {
                ci.out.println("> Command 'show': Torrent #" + number + " unknown.");
                return;
            }
            DownloadManager dm = (DownloadManager) ci.torrents.get(number - 1);
            printTorrentDetails(ci.out, dm, number, args);
        } catch (Exception e) {
            ci.out.println("> Command 'show': Subcommand '" + subCommand + "' unknown.");
            return;
        }
    }
}
Also used : IndentWriter(com.biglybt.core.util.IndentWriter) HashSet(java.util.HashSet) FileWriter(java.io.FileWriter) ArrayList(java.util.ArrayList) DownloadManager(com.biglybt.core.download.DownloadManager) GlobalManager(com.biglybt.core.global.GlobalManager) ListIterator(java.util.ListIterator) Iterator(java.util.Iterator) ArrayList(java.util.ArrayList) List(java.util.List) DownloadManagerStats(com.biglybt.core.download.DownloadManagerStats) PrintWriter(java.io.PrintWriter) HashSet(java.util.HashSet) PEPeerManagerStats(com.biglybt.core.peer.PEPeerManagerStats) PEPeerManager(com.biglybt.core.peer.PEPeerManager) Map(java.util.Map)

Example 55 with PEPeerManager

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

the class Show method printTorrentDetails.

/**
 * prints out the full details of a particular torrent
 * @param out
 * @param dm
 * @param torrentNum
 */
private static void printTorrentDetails(PrintStream out, DownloadManager dm, int torrentNum, List<String> args) {
    String name = dm.getDisplayName();
    if (name == null)
        name = "?";
    out.println("> -----");
    out.println("Info on Torrent #" + torrentNum + " (" + name + ")");
    out.println("- General Info -");
    String[] health = { "- no info -", "stopped", "no remote connections", "no tracker", "OK", "ko" };
    try {
        out.println("Health: " + health[dm.getHealthStatus()]);
    } catch (Exception e) {
        out.println("Health: " + health[0]);
    }
    out.println("State: " + Integer.toString(dm.getState()));
    if (dm.getState() == DownloadManager.STATE_ERROR)
        out.println("Error: " + dm.getErrorDetails());
    out.println("Hash: " + TorrentUtils.nicePrintTorrentHash(dm.getTorrent(), true));
    out.println("- Torrent file -");
    out.println("Torrent Filename: " + dm.getTorrentFileName());
    out.println("Saving to: " + dm.getSaveLocation());
    out.println("Created By: " + dm.getTorrentCreatedBy());
    out.println("Comment: " + dm.getTorrentComment());
    Category cat = dm.getDownloadState().getCategory();
    if (cat != null) {
        out.println("Category: " + cat.getName());
    }
    List<Tag> tags = TagManagerFactory.getTagManager().getTagsForTaggable(TagType.TT_DOWNLOAD_MANUAL, dm);
    String tags_str;
    if (tags.size() == 0) {
        tags_str = "None";
    } else {
        tags_str = "";
        for (Tag t : tags) {
            tags_str += (tags_str.length() == 0 ? "" : ",") + t.getTagName(true);
        }
    }
    out.println("Tags: " + tags_str);
    out.println("- Tracker Info -");
    TRTrackerAnnouncer trackerclient = dm.getTrackerClient();
    if (trackerclient != null) {
        out.println("URL: " + trackerclient.getTrackerURL());
        String timestr;
        try {
            int time = trackerclient.getTimeUntilNextUpdate();
            if (time < 0) {
                timestr = MessageText.getString("GeneralView.label.updatein.querying");
            } else {
                int minutes = time / 60;
                int seconds = time % 60;
                String strSeconds = "" + seconds;
                if (seconds < 10) {
                    // $NON-NLS-1$
                    strSeconds = "0" + seconds;
                }
                timestr = minutes + ":" + strSeconds;
            }
        } catch (Exception e) {
            timestr = "unknown";
        }
        out.println("Time till next Update: " + timestr);
        out.println("Status: " + trackerclient.getStatusString());
    } else
        out.println("  Not available");
    out.println("- Files Info -");
    DiskManagerFileInfo[] files = dm.getDiskManagerFileInfo();
    if (files != null) {
        for (int i = 0; i < files.length; i++) {
            out.print(((i < 9) ? "   " : "  ") + Integer.toString(i + 1) + " (");
            String tmp = ">";
            if (files[i].getPriority() > 0)
                tmp = "+";
            if (files[i].isSkipped())
                tmp = "!";
            out.print(tmp + ") ");
            if (files[i] != null) {
                long fLen = files[i].getLength();
                if (fLen > 0) {
                    DecimalFormat df = new DecimalFormat("000.0%");
                    out.print(df.format(files[i].getDownloaded() * 1.0 / fLen));
                    out.println("\t" + files[i].getFile(true).getName());
                } else
                    out.println("Info not available.");
            } else
                out.println("Info not available.");
        }
    } else {
        out.println("  Info not available.");
    }
    for (String arg : args) {
        arg = arg.toLowerCase();
        if (arg.startsWith("pie")) {
            out.println("Pieces");
            PEPeerManager pm = dm.getPeerManager();
            if (pm != null) {
                PiecePicker picker = pm.getPiecePicker();
                PEPiece[] pieces = pm.getPieces();
                String line = "";
                for (int i = 0; i < pieces.length; i++) {
                    String str = picker.getPieceString(i);
                    line += (line.length() == 0 ? (i + " ") : ",") + str;
                    PEPiece piece = pieces[i];
                    if (piece != null) {
                        line += ":" + piece.getString();
                    }
                    if ((i + 1) % 10 == 0) {
                        out.println(line);
                        line = "";
                    }
                }
                if (line.length() > 0) {
                    out.println(line);
                }
            }
        } else if (arg.startsWith("pee")) {
            out.println("Peers");
            PEPeerManager pm = dm.getPeerManager();
            if (pm != null) {
                List<PEPeer> peers = pm.getPeers();
                out.println("\tConnected to " + peers.size() + " peers");
                for (PEPeer peer : peers) {
                    PEPeerStats stats = peer.getStats();
                    System.out.println("\t\t" + peer.getIp() + ", in=" + (peer.isIncoming() ? "Y" : "N") + ", prot=" + peer.getProtocol() + ", choked=" + (peer.isChokingMe() ? "Y" : "N") + ", up=" + DisplayFormatters.formatByteCountToKiBEtcPerSec(stats.getDataSendRate() + stats.getProtocolSendRate()) + ", down=" + DisplayFormatters.formatByteCountToKiBEtcPerSec(stats.getDataReceiveRate() + stats.getProtocolReceiveRate()) + ", in_req=" + peer.getIncomingRequestCount() + ", out_req=" + peer.getOutgoingRequestCount());
                }
            }
        }
    }
    out.println("> -----");
}
Also used : DiskManagerFileInfo(com.biglybt.core.disk.DiskManagerFileInfo) PEPeer(com.biglybt.core.peer.PEPeer) Category(com.biglybt.core.category.Category) PiecePicker(com.biglybt.core.peermanager.piecepicker.PiecePicker) DecimalFormat(java.text.DecimalFormat) PEPeerStats(com.biglybt.core.peer.PEPeerStats) PEPiece(com.biglybt.core.peer.PEPiece) TRTrackerAnnouncer(com.biglybt.core.tracker.client.TRTrackerAnnouncer) PEPeerManager(com.biglybt.core.peer.PEPeerManager) ArrayList(java.util.ArrayList) List(java.util.List) Tag(com.biglybt.core.tag.Tag)

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