Search in sources :

Example 46 with PEPeerManager

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

the class PrivacyView method updatePeersEtc.

private void updatePeersEtc(final DownloadManager dm) {
    final PEPeerManager pm;
    if (dm != null) {
        pm = dm.getPeerManager();
    } else {
        pm = null;
    }
    Utils.execSWTThread(new AERunnable() {

        @Override
        public void runSupport() {
            if (peer_info == null || peer_info.isDisposed()) {
                return;
            }
            if (pm == null) {
                peer_info.setText(dm == null ? "" : MessageText.getString("privacy.view.dl.not.running"));
            } else {
                AEProxySelector proxy_selector = AEProxySelectorFactory.getSelector();
                Proxy proxy = proxy_selector.getActiveProxy();
                boolean socks_bad_incoming = false;
                List<PEPeer> peers = pm.getPeers();
                String[] all_nets = AENetworkClassifier.AT_NETWORKS;
                int[] counts = new int[all_nets.length];
                int incoming = 0;
                int outgoing = 0;
                int outgoing_connected = 0;
                for (PEPeer peer : peers) {
                    String net = PeerUtils.getNetwork(peer);
                    for (int i = 0; i < all_nets.length; i++) {
                        if (all_nets[i] == net) {
                            counts[i]++;
                            break;
                        }
                    }
                    boolean is_incoming = peer.isIncoming();
                    if (is_incoming) {
                        incoming++;
                    } else {
                        outgoing++;
                        if (peer.getPeerState() == PEPeer.TRANSFERING) {
                            outgoing_connected++;
                        }
                    }
                    if (proxy != null) {
                        if (is_incoming) {
                            if (!peer.isLANLocal()) {
                                try {
                                    if (InetAddress.getByAddress(HostNameToIPResolver.hostAddressToBytes(peer.getIp())).isLoopbackAddress()) {
                                        continue;
                                    }
                                } catch (Throwable e) {
                                }
                                socks_bad_incoming = true;
                                break;
                            }
                        }
                    }
                }
                String str = "";
                for (int i = 0; i < all_nets.length; i++) {
                    int num = counts[i];
                    if (num > 0) {
                        str += (str.length() == 0 ? "" : ", ") + all_nets[i] + "=" + num;
                    }
                }
                if (str.length() == 0) {
                    str = MessageText.getString("privacy.view.no.peers");
                } else {
                    str += ", " + MessageText.getString("label.incoming") + "=" + incoming + ", " + MessageText.getString("label.outgoing") + "=" + outgoing_connected + "/" + outgoing;
                }
                if (socks_bad_incoming) {
                    str += " (" + MessageText.getString("privacy.view.non.local.peer") + ")";
                }
                peer_info.setText(str);
            }
            updateVPNSocks();
        }
    });
}
Also used : AERunnable(com.biglybt.core.util.AERunnable) Proxy(java.net.Proxy) PEPeer(com.biglybt.core.peer.PEPeer) AEProxySelector(com.biglybt.core.proxy.AEProxySelector) PEPeerManager(com.biglybt.core.peer.PEPeerManager) List(java.util.List)

Example 47 with PEPeerManager

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

the class FilesViewMenuUtil method fillMenu.

public static void fillMenu(final TableView<?> tv, String columnName, final Menu menu, final DownloadManager[] manager_list, final DiskManagerFileInfo[][] files_list) {
    Shell shell = menu.getShell();
    final List<DiskManagerFileInfo> all_files = new ArrayList<>();
    for (DiskManagerFileInfo[] files : files_list) {
        all_files.addAll(Arrays.asList(files));
    }
    boolean hasSelection = (all_files.size() > 0);
    final MenuItem itemOpen = new MenuItem(menu, SWT.PUSH);
    Messages.setLanguageText(itemOpen, "FilesView.menu.open");
    Utils.setMenuItemImage(itemOpen, "run");
    // Invoke open on enter, double click
    menu.setDefaultItem(itemOpen);
    // Explore  (Copied from MyTorrentsView)
    final boolean use_open_containing_folder = COConfigurationManager.getBooleanParameter("MyTorrentsView.menu.show_parent_folder_enabled");
    final MenuItem itemExplore = new MenuItem(menu, SWT.PUSH);
    Messages.setLanguageText(itemExplore, "MyTorrentsView.menu." + (use_open_containing_folder ? "open_parent_folder" : "explore"));
    itemExplore.addListener(SWT.Selection, new Listener() {

        @Override
        public void handleEvent(Event event) {
            for (int i = all_files.size() - 1; i >= 0; i--) {
                DiskManagerFileInfo info = (DiskManagerFileInfo) all_files.get(i);
                if (info != null) {
                    ManagerUtils.open(info, use_open_containing_folder);
                }
            }
        }
    });
    itemExplore.setEnabled(hasSelection);
    // open in browser
    final Menu menuBrowse = new Menu(menu.getShell(), SWT.DROP_DOWN);
    final MenuItem itemBrowse = new MenuItem(menu, SWT.CASCADE);
    Messages.setLanguageText(itemBrowse, "MyTorrentsView.menu.browse");
    itemBrowse.setMenu(menuBrowse);
    final MenuItem itemBrowsePublic = new MenuItem(menuBrowse, SWT.PUSH);
    itemBrowsePublic.setText(MessageText.getString("label.public") + "...");
    itemBrowsePublic.addListener(SWT.Selection, new Listener() {

        @Override
        public void handleEvent(Event event) {
            for (int i = all_files.size() - 1; i >= 0; i--) {
                DiskManagerFileInfo info = (DiskManagerFileInfo) all_files.get(i);
                if (info != null) {
                    ManagerUtils.browse(info, false, true);
                }
            }
        }
    });
    final MenuItem itemBrowseAnon = new MenuItem(menuBrowse, SWT.PUSH);
    itemBrowseAnon.setText(MessageText.getString("label.anon") + "...");
    itemBrowseAnon.addListener(SWT.Selection, new Listener() {

        @Override
        public void handleEvent(Event event) {
            for (int i = all_files.size() - 1; i >= 0; i--) {
                DiskManagerFileInfo info = all_files.get(i);
                if (info != null) {
                    ManagerUtils.browse(info, true, true);
                }
            }
        }
    });
    new MenuItem(menuBrowse, SWT.SEPARATOR);
    final MenuItem itemBrowseURL = new MenuItem(menuBrowse, SWT.PUSH);
    Messages.setLanguageText(itemBrowseURL, "label.copy.url.to.clip");
    itemBrowseURL.addListener(SWT.Selection, new Listener() {

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

                @Override
                public void runSupport() {
                    String url = ManagerUtils.browse(all_files.get(0), true, false);
                    if (url != null) {
                        ClipboardCopy.copyToClipBoard(url);
                    }
                }
            });
        }
    });
    itemBrowseURL.setEnabled(all_files.size() == 1);
    itemBrowse.setEnabled(hasSelection);
    // rename/retarget
    MenuItem itemRenameOrRetarget = null, itemRenameOrRetargetBatch = null, itemRename = null, itemRetarget = null;
    // "Rename or Retarget" -- Opens up file chooser (can choose new dir and new name)
    itemRenameOrRetarget = new MenuItem(menu, SWT.PUSH);
    Messages.setLanguageText(itemRenameOrRetarget, "FilesView.menu.rename");
    itemRenameOrRetarget.setData("rename", Boolean.valueOf(true));
    itemRenameOrRetarget.setData("retarget", Boolean.valueOf(true));
    itemRenameOrRetarget.setData("batch", Boolean.valueOf(false));
    // "Rename or Retarget (Batch)"
    itemRenameOrRetargetBatch = new MenuItem(menu, SWT.PUSH);
    Messages.setLanguageText(itemRenameOrRetargetBatch, "FilesView.menu.rename.batch");
    itemRenameOrRetargetBatch.setData("rename", Boolean.valueOf(true));
    itemRenameOrRetargetBatch.setData("retarget", Boolean.valueOf(true));
    itemRenameOrRetargetBatch.setData("batch", Boolean.valueOf(true));
    // "Quick Rename" -- opens up input box with name
    itemRename = new MenuItem(menu, SWT.PUSH);
    Messages.setLanguageText(itemRename, "FilesView.menu.rename_only");
    itemRename.setData("rename", Boolean.valueOf(true));
    itemRename.setData("retarget", Boolean.valueOf(false));
    itemRename.setData("batch", Boolean.valueOf(false));
    // "Move Files" -- opens up directory chooser
    itemRetarget = new MenuItem(menu, SWT.PUSH);
    Messages.setLanguageText(itemRetarget, "FilesView.menu.retarget");
    itemRetarget.setData("rename", Boolean.valueOf(false));
    itemRetarget.setData("retarget", Boolean.valueOf(true));
    itemRename.setData("batch", Boolean.valueOf(false));
    // revert
    final MenuItem itemRevertFiles = new MenuItem(menu, SWT.PUSH);
    Messages.setLanguageText(itemRevertFiles, "MyTorrentsView.menu.revertfiles");
    // locate files
    final MenuItem itemLocateFiles = new MenuItem(menu, SWT.PUSH);
    Messages.setLanguageText(itemLocateFiles, "MyTorrentsView.menu.locatefiles");
    // find more
    final MenuItem itemfindMore = new MenuItem(menu, SWT.PUSH);
    Messages.setLanguageText(itemfindMore, "MyTorrentsView.menu.findmorelikethis");
    // clear links
    MenuItem itemClearLinks = null;
    final int userMode = COConfigurationManager.getIntParameter("User Mode");
    if (userMode > 1) {
        itemClearLinks = new MenuItem(menu, SWT.PUSH);
        Messages.setLanguageText(itemClearLinks, "FilesView.menu.clear.links");
    }
    // quick view
    final MenuItem itemQuickView = new MenuItem(menu, SWT.CHECK);
    Messages.setLanguageText(itemQuickView, "MainWindow.menu.quick_view");
    itemQuickView.setEnabled(all_files.size() == 1 && Utils.isQuickViewSupported(all_files.get(0)));
    itemQuickView.setSelection(all_files.size() == 1 && Utils.isQuickViewActive(all_files.get(0)));
    itemQuickView.addListener(SWT.Selection, new Listener() {

        @Override
        public void handleEvent(Event arg) {
            Utils.setQuickViewActive(all_files.get(0), itemQuickView.getSelection());
        }
    });
    if (manager_list.length == 1) {
        // lazy for the moment
        MenuFactory.addAlertsMenu(menu, manager_list[0], files_list[0]);
    }
    // personal share
    final MenuItem itemPersonalShare = new MenuItem(menu, SWT.PUSH);
    Messages.setLanguageText(itemPersonalShare, "MyTorrentsView.menu.create_personal_share");
    // priority
    final MenuItem itemPriority = new MenuItem(menu, SWT.CASCADE);
    Messages.setLanguageText(itemPriority, "FilesView.menu.setpriority");
    final Menu menuPriority = new Menu(shell, SWT.DROP_DOWN);
    itemPriority.setMenu(menuPriority);
    final MenuItem itemHigh = new MenuItem(menuPriority, SWT.CASCADE);
    itemHigh.setData("Priority", PRIORITY_HIGH);
    Messages.setLanguageText(itemHigh, "FilesView.menu.setpriority.high");
    final MenuItem itemNormal = new MenuItem(menuPriority, SWT.CASCADE);
    itemNormal.setData("Priority", PRIORITY_NORMAL);
    Messages.setLanguageText(itemNormal, "FilesView.menu.setpriority.normal");
    final MenuItem itemLow = new MenuItem(menuPriority, SWT.CASCADE);
    itemLow.setData("Priority", PRIORITY_LOW);
    Messages.setLanguageText(itemLow, "FileItem.low");
    final MenuItem itemNumeric = new MenuItem(menuPriority, SWT.CASCADE);
    itemNumeric.setData("Priority", PRIORITY_NUMERIC);
    Messages.setLanguageText(itemNumeric, "FilesView.menu.setpriority.numeric");
    final MenuItem itemNumericAuto = new MenuItem(menuPriority, SWT.CASCADE);
    itemNumericAuto.setData("Priority", PRIORITY_NUMERIC_AUTO);
    Messages.setLanguageText(itemNumericAuto, "FilesView.menu.setpriority.numeric.auto");
    final MenuItem itemSkipped = new MenuItem(menuPriority, SWT.CASCADE);
    itemSkipped.setData("Priority", PRIORITY_SKIPPED);
    Messages.setLanguageText(itemSkipped, "FilesView.menu.setpriority.skipped");
    final MenuItem itemDelete = new MenuItem(menuPriority, SWT.CASCADE);
    itemDelete.setData("Priority", PRIORITY_DELETE);
    // lazy but we're near release
    Messages.setLanguageText(itemDelete, "wizard.multitracker.delete");
    if (all_files.size() == 1) {
        DiskManagerFileInfo file = all_files.get(0);
        final MenuItem itemSequential = new MenuItem(menu, SWT.CHECK);
        Messages.setLanguageText(itemSequential, "menu.sequential.file");
        PEPeerManager pm = file.getDownloadManager().getPeerManager();
        if (pm == null || file.getDownloaded() == file.getLength() || file.isSkipped()) {
            itemSequential.setEnabled(false);
        } else {
            PiecePicker pp = pm.getPiecePicker();
            int info = pp.getSequentialInfo();
            itemSequential.setSelection(file.getFirstPieceNumber() == info - 1);
            itemSequential.addListener(SWT.Selection, new Listener() {

                @Override
                public void handleEvent(Event arg) {
                    if (itemSequential.getSelection()) {
                        pp.setSequentialAscendingFrom(file.getFirstPieceNumber());
                    } else {
                        pp.clearSequential();
                    }
                }
            });
        }
    }
    new MenuItem(menu, SWT.SEPARATOR);
    if (!hasSelection) {
        itemOpen.setEnabled(false);
        itemPriority.setEnabled(false);
        itemRenameOrRetarget.setEnabled(false);
        itemRenameOrRetargetBatch.setEnabled(false);
        itemRename.setEnabled(false);
        itemRetarget.setEnabled(false);
        itemRevertFiles.setEnabled(false);
        itemLocateFiles.setEnabled(false);
        itemfindMore.setEnabled(false);
        if (itemClearLinks != null) {
            itemClearLinks.setEnabled(false);
        }
        itemPersonalShare.setEnabled(false);
        return;
    }
    boolean all_persistent = true;
    boolean open = true;
    boolean all_compact = true;
    boolean all_dnd_not_deleted = true;
    boolean all_high_pri = true;
    boolean all_normal_pri = true;
    boolean all_low_pri = true;
    boolean all_complete = true;
    boolean any_relocated = false;
    final List<DiskManagerFileInfo> files_with_links = new ArrayList<>();
    for (int j = 0; j < manager_list.length; j++) {
        DownloadManager manager = manager_list[j];
        int dm_file_count = manager.getNumFileInfos();
        if (!manager.isPersistent()) {
            all_persistent = false;
        }
        DiskManagerFileInfo[] files = files_list[j];
        DownloadManagerState dm_state = manager.getDownloadState();
        int[] storage_types = manager.getStorageType(files);
        for (int i = 0; i < files.length; i++) {
            DiskManagerFileInfo file_info = files[i];
            if (open && file_info.getAccessMode() != DiskManagerFileInfo.READ) {
                open = false;
            }
            boolean isCompact = storage_types[i] == DiskManagerFileInfo.ST_COMPACT || storage_types[i] == DiskManagerFileInfo.ST_REORDER_COMPACT;
            if (all_compact && !isCompact) {
                all_compact = false;
            }
            if (all_dnd_not_deleted || all_high_pri || all_normal_pri || all_low_pri) {
                if (file_info.isSkipped()) {
                    all_high_pri = all_normal_pri = all_low_pri = false;
                    if (isCompact) {
                        all_dnd_not_deleted = false;
                    }
                } else {
                    all_dnd_not_deleted = false;
                    // Only do this check if we need to.
                    if (all_high_pri || all_normal_pri || all_low_pri) {
                        int file_pri = file_info.getPriority();
                        if (file_pri == 0) {
                            all_high_pri = all_low_pri = false;
                        } else if (file_pri == 1) {
                            all_normal_pri = all_low_pri = false;
                        } else if (file_pri == -1) {
                            all_normal_pri = all_high_pri = false;
                        } else {
                            all_low_pri = all_normal_pri = all_high_pri = false;
                        }
                    }
                }
            }
            File file_link = file_info.getFile(true);
            File file_nolink = file_info.getFile(false);
            if (file_info.getDownloaded() != file_info.getLength() || file_link.length() != file_info.getLength()) {
                all_complete = false;
            }
            if (dm_file_count > 1) {
                if (!file_nolink.getAbsolutePath().equals(file_link.getAbsolutePath())) {
                    files_with_links.add(file_info);
                }
            }
            File target = dm_state.getFileLink(file_info.getIndex(), file_nolink);
            if (target != null) {
                if (target != file_nolink) {
                    if (!target.equals(file_nolink)) {
                        any_relocated = true;
                    }
                }
            }
        }
    }
    // we can only open files if they are read-only
    itemOpen.setEnabled(open);
    // can't rename files for non-persistent downloads (e.g. shares) as these
    // are managed "externally"
    itemRenameOrRetarget.setEnabled(all_persistent);
    itemRenameOrRetargetBatch.setEnabled(all_persistent);
    itemRename.setEnabled(all_persistent);
    itemRetarget.setEnabled(all_persistent);
    // only enable for single files - people prolly don't expect a multi-selection to result
    // in multiple shares, rather they would expect one share with the files they selected
    // which we don't support
    itemPersonalShare.setEnabled(all_complete && all_files.size() == 1);
    itemSkipped.setEnabled(!all_dnd_not_deleted);
    itemHigh.setEnabled(!all_high_pri);
    itemNormal.setEnabled(!all_normal_pri);
    itemLow.setEnabled(!all_low_pri);
    itemDelete.setEnabled(!all_compact);
    itemOpen.addListener(SWT.Selection, new Listener() {

        @Override
        public void handleEvent(Event event) {
            for (int i = 0; i < all_files.size(); i++) {
                DiskManagerFileInfo info = (DiskManagerFileInfo) all_files.get(i);
                if (info != null && info.getAccessMode() == DiskManagerFileInfo.READ) {
                    Utils.launch(info);
                }
            }
        }
    });
    Listener rename_listener = new Listener() {

        @Override
        public void handleEvent(Event event) {
            final boolean rename_it = ((Boolean) event.widget.getData("rename")).booleanValue();
            final boolean retarget_it = ((Boolean) event.widget.getData("retarget")).booleanValue();
            final boolean batch = ((Boolean) event.widget.getData("batch")).booleanValue();
            rename(tv, all_files.toArray(new Object[all_files.size()]), rename_it, retarget_it, batch);
        }
    };
    itemRenameOrRetargetBatch.addListener(SWT.Selection, rename_listener);
    itemRenameOrRetarget.addListener(SWT.Selection, rename_listener);
    itemRename.addListener(SWT.Selection, rename_listener);
    itemRetarget.addListener(SWT.Selection, rename_listener);
    itemLocateFiles.addListener(SWT.Selection, new Listener() {

        @Override
        public void handleEvent(Event event) {
            ManagerUtils.locateFiles(manager_list, files_list, menu.getShell());
        }
    });
    itemLocateFiles.setEnabled(true);
    if (ManagerUtils.canFindMoreLikeThis()) {
        itemfindMore.addListener(SWT.Selection, new Listener() {

            @Override
            public void handleEvent(Event event) {
                ManagerUtils.findMoreLikeThis(all_files.get(0), menu.getShell());
            }
        });
        itemfindMore.setEnabled(all_files.size() == 1);
    }
    itemRevertFiles.setEnabled(any_relocated);
    itemRevertFiles.addListener(SWT.Selection, new Listener() {

        @Override
        public void handleEvent(Event event) {
            revertFiles(tv, all_files);
        }
    });
    if (itemClearLinks != null) {
        itemClearLinks.setEnabled(files_with_links.size() > 0);
        itemClearLinks.addListener(SWT.Selection, new Listener() {

            @Override
            public void handleEvent(Event event) {
                for (DiskManagerFileInfo file : files_with_links) {
                    file.setLink(null);
                }
                invalidateRows(tv, files_with_links);
            }
        });
    }
    itemPersonalShare.addListener(SWT.Selection, new Listener() {

        @Override
        public void handleEvent(Event event) {
            Map<String, String> properties = new HashMap<>();
            properties.put(ShareManager.PR_PERSONAL, "true");
            for (int i = 0; i < all_files.size(); i++) {
                DiskManagerFileInfo file_info = all_files.get(i);
                File file = file_info.getFile(true);
                if (file.isFile()) {
                    ShareUtils.shareFile(file.getAbsolutePath(), properties);
                } else if (file.isDirectory()) {
                    ShareUtils.shareDir(file.getAbsolutePath(), properties);
                }
            }
        }
    });
    Listener priorityListener = new Listener() {

        @Override
        public void handleEvent(Event event) {
            final Object priority = event.widget.getData("Priority");
            Utils.getOffOfSWTThread(new AERunnable() {

                @Override
                public void runSupport() {
                    changePriority(priority, all_files);
                }
            });
        }
    };
    itemNumeric.addListener(SWT.Selection, priorityListener);
    itemNumericAuto.addListener(SWT.Selection, priorityListener);
    itemHigh.addListener(SWT.Selection, priorityListener);
    itemNormal.addListener(SWT.Selection, priorityListener);
    itemLow.addListener(SWT.Selection, priorityListener);
    itemSkipped.addListener(SWT.Selection, priorityListener);
    itemDelete.addListener(SWT.Selection, priorityListener);
    if (columnName.equals(ColumnUnopened.COLUMN_ID)) {
        final MenuItem toggle = new MenuItem(menu, SWT.PUSH);
        Messages.setLanguageText(toggle, "label.toggle.new.marker");
        toggle.addListener(SWT.Selection, new Listener() {

            @Override
            public void handleEvent(Event arg) {
                for (int i = 0; i < all_files.size(); i++) {
                    DiskManagerFileInfo file = all_files.get(i);
                    DownloadManager dm = file.getDownloadManager();
                    int ff = dm.getDownloadState().getFileFlags(file.getIndex());
                    ff ^= DownloadManagerState.FILE_FLAG_NOT_NEW;
                    dm.getDownloadState().setFileFlags(file.getIndex(), ff);
                }
            }
        });
        new MenuItem(menu, SWT.SEPARATOR);
    }
    com.biglybt.pif.ui.menus.MenuItem[] menu_items = MenuItemManager.getInstance().getAllAsArray(MenuManager.MENU_FILE_CONTEXT);
    if (menu_items.length > 0) {
        // plugins take com.biglybt.pif.disk.DiskManagerFileInfo
        com.biglybt.pif.disk.DiskManagerFileInfo[] fileInfos = new com.biglybt.pif.disk.DiskManagerFileInfo[all_files.size()];
        for (int i = 0; i < all_files.size(); i++) {
            fileInfos[i] = (com.biglybt.pif.disk.DiskManagerFileInfo) PluginCoreUtils.convert(all_files.get(i), false);
        }
        MenuBuildUtils.addPluginMenuItems(menu_items, menu, false, true, new MenuBuildUtils.MenuItemPluginMenuControllerImpl(fileInfos));
    }
}
Also used : UserPrompterResultListener(com.biglybt.ui.UserPrompterResultListener) UIInputReceiverListener(com.biglybt.pif.ui.UIInputReceiverListener) PiecePicker(com.biglybt.core.peermanager.piecepicker.PiecePicker) DownloadManager(com.biglybt.core.download.DownloadManager) DownloadManagerState(com.biglybt.core.download.DownloadManagerState) MessageBoxShell(com.biglybt.ui.swt.shells.MessageBoxShell) DiskManagerFileInfo(com.biglybt.core.disk.DiskManagerFileInfo) PEPeerManager(com.biglybt.core.peer.PEPeerManager) File(java.io.File) MenuBuildUtils(com.biglybt.ui.swt.MenuBuildUtils)

Example 48 with PEPeerManager

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

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

the class BuddyPluginTracker method doTracking.

protected void doTracking() {
    if (!(plugin_enabled && tracker_enabled)) {
        return;
    }
    Map<BuddyPluginBuddy, List<Download>> peers_to_check = new HashMap<>();
    Map<PartialBuddy, List<Download>> partials_to_check = new HashMap<>();
    Set<Download> active_set = new HashSet<>();
    synchronized (online_buddies) {
        Iterator<BuddyPluginBuddy> it = online_buddies.iterator();
        while (it.hasNext()) {
            BuddyPluginBuddy buddy = it.next();
            BuddyTrackingData buddy_data = getBuddyData(buddy);
            Map<Download, Boolean> active = buddy_data.getDownloadsToTrack();
            if (active.size() > 0) {
                Iterator<Map.Entry<Download, Boolean>> it2 = active.entrySet().iterator();
                List<Download> check_peers = new ArrayList<>();
                while (it2.hasNext()) {
                    Map.Entry<Download, Boolean> entry = it2.next();
                    Download dl = entry.getKey();
                    boolean check_peer = entry.getValue();
                    if (check_peer) {
                        check_peers.add(dl);
                    }
                    active_set.add(dl);
                }
                if (check_peers.size() > 0) {
                    peers_to_check.put(buddy, check_peers);
                }
            }
        }
        for (PartialBuddyData pbd : partial_buddies.values()) {
            active_set.addAll(pbd.downloads);
        }
    }
    synchronized (actively_tracking) {
        Iterator<Download> it = active_set.iterator();
        while (it.hasNext()) {
            Download dl = it.next();
            if (!actively_tracking.contains(dl)) {
                actively_tracking.add(dl);
                trackPeers(dl);
            }
        }
        it = actively_tracking.iterator();
        while (it.hasNext()) {
            Download dl = (Download) it.next();
            if (!active_set.contains(dl)) {
                it.remove();
                untrackPeers(dl);
            }
        }
    }
    // check peer connections
    Iterator<Map.Entry<BuddyPluginBuddy, List<Download>>> it = peers_to_check.entrySet().iterator();
    boolean lan = plugin.getPeersAreLANLocal();
    while (it.hasNext()) {
        Map.Entry<BuddyPluginBuddy, List<Download>> entry = it.next();
        BuddyPluginBuddy buddy = entry.getKey();
        if (!buddy.isOnline(false)) {
            continue;
        }
        InetAddress ip = buddy.getAdjustedIP();
        if (ip == null) {
            continue;
        }
        int tcp_port = buddy.getTCPPort();
        int udp_port = buddy.getUDPPort();
        List<Download> downloads = (List<Download>) entry.getValue();
        for (int i = 0; i < downloads.size(); i++) {
            Download download = downloads.get(i);
            PeerManager pm = download.getPeerManager();
            if (pm == null) {
                continue;
            }
            Peer[] existing_peers = pm.getPeers(ip.getHostAddress());
            boolean connected = false;
            for (int j = 0; j < existing_peers.length; j++) {
                Peer peer = existing_peers[j];
                if (peer.getTCPListenPort() == tcp_port || peer.getUDPListenPort() == udp_port) {
                    if (lan && !peer.isLANLocal()) {
                        AddressUtils.addLANRateLimitAddress(ip);
                        peer.resetLANLocalStatus();
                    }
                    connected = true;
                    break;
                }
            }
            if (connected) {
                log(download.getName() + " - peer " + ip.getHostAddress() + " already connected");
                continue;
            }
            log(download.getName() + " - connecting to peer " + ip.getHostAddress());
            PEPeerManager c_pm = PluginCoreUtils.unwrap(pm);
            Map user_data = new LightHashMap();
            user_data.put(PEER_KEY, download);
            user_data.put(Peer.PR_PRIORITY_CONNECTION, Boolean.TRUE);
            c_pm.addPeer(ip.getHostAddress(), tcp_port, udp_port, true, user_data);
        }
    }
}
Also used : PEPeerManager(com.biglybt.core.peer.PEPeerManager) BuddyPluginBuddy(com.biglybt.plugin.net.buddy.BuddyPluginBuddy) PEPeerManager(com.biglybt.core.peer.PEPeerManager) PartialBuddy(com.biglybt.plugin.net.buddy.PartialBuddy) InetAddress(java.net.InetAddress)

Example 50 with PEPeerManager

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

the class FileAvailabilityItem method refresh.

@Override
public void refresh(TableCell cell) {
    String sText = "";
    DiskManagerFileInfo file = (DiskManagerFileInfo) cell.getDataSource();
    if (file == null)
        return;
    if (file.getLength() == 0) {
        sText = "-";
        cell.setSortValue(Long.MAX_VALUE);
    } else {
        DownloadManager dm = file.getDownloadManager();
        PEPeerManager pm = dm == null ? null : dm.getPeerManager();
        if (pm != null) {
            int index = file.getIndex();
            if (index >= 0) {
                float f = pm.getMinAvailability(index);
                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);
            }
        } else {
            cell.setSortValue(0);
        }
    }
    cell.setText(sText);
}
Also used : DiskManagerFileInfo(com.biglybt.core.disk.DiskManagerFileInfo) PEPeerManager(com.biglybt.core.peer.PEPeerManager) DownloadManager(com.biglybt.core.download.DownloadManager)

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