Search in sources :

Example 1 with DiskManagerFileInfoSet

use of com.biglybt.core.disk.DiskManagerFileInfoSet in project BiglyBT by BiglySoftware.

the class ManagerUtils method browse.

public static String browse(final DownloadManager dm, DiskManagerFileInfo _file, final boolean anon, final boolean launch) {
    Properties props = new Properties();
    File save_location = dm.getSaveLocation();
    final String root_dir;
    if (save_location.isFile()) {
        root_dir = save_location.getParentFile().getAbsolutePath();
    } else {
        root_dir = save_location.getAbsolutePath();
    }
    final String url_suffix;
    boolean always_browse = COConfigurationManager.getBooleanParameter("Library.LaunchWebsiteInBrowserDirList");
    if (!always_browse) {
        if (_file == null) {
            _file = getBrowseHomePage(dm);
        }
    }
    final DiskManagerFileInfo file = _file;
    if (file == null) {
        // asked to launch a download (note that the double-click on a download that has an index.html file will by default result in
        // us getting here with the file set, not null)
        url_suffix = "";
    } else {
        String relative_path = file.getTorrentFile().getRelativePath();
        String[] bits = relative_path.replace(File.separatorChar, '/').split("/");
        String _url_suffix = "";
        int bits_to_use = always_browse ? bits.length - 1 : bits.length;
        for (int i = 0; i < bits_to_use; i++) {
            String bit = bits[i];
            if (bit.length() == 0) {
                continue;
            }
            _url_suffix += (_url_suffix == "" ? "" : "/") + UrlUtils.encode(bit);
        }
        url_suffix = _url_suffix;
    }
    synchronized (browse_plugins) {
        WebPlugin plugin = browse_plugins.get(dm);
        if (plugin == null) {
            props.put(WebPlugin.PR_PORT, 0);
            props.put(WebPlugin.PR_BIND_IP, "127.0.0.1");
            props.put(WebPlugin.PR_HOME_PAGE, "");
            props.put(WebPlugin.PR_ROOT_DIR, root_dir);
            props.put(WebPlugin.PR_ACCESS, "local");
            props.put(WebPlugin.PR_HIDE_RESOURCE_CONFIG, true);
            props.put(WebPlugin.PR_ENABLE_KEEP_ALIVE, true);
            props.put(WebPlugin.PR_ENABLE_PAIRING, false);
            props.put(WebPlugin.PR_ENABLE_UPNP, false);
            props.put(WebPlugin.PR_ENABLE_I2P, false);
            props.put(WebPlugin.PR_ENABLE_TOR, false);
            final String plugin_id = "webserver:" + dm.getInternalName();
            final String plugin_name = "Web Server for " + dm.getDisplayName();
            Properties messages = new Properties();
            messages.put("plugins." + plugin_id, plugin_name);
            PluginInitializer.getDefaultInterface().getUtilities().getLocaleUtilities().integrateLocalisedMessageBundle(messages);
            final AESemaphore waiter = new AESemaphore("waiter");
            final String[] url_holder = { null };
            plugin = new UnloadableWebPlugin(props) {

                private Map<String, Object> file_map = new HashMap<>();

                private String protocol;

                private String host;

                private int port;

                @Override
                public void initialize(PluginInterface plugin_interface) throws PluginException {
                    DiskManagerFileInfoSet file_set = dm.getDiskManagerFileInfoSet();
                    DiskManagerFileInfo[] files = file_set.getFiles();
                    Set<Object> root_dir = new HashSet<>();
                    file_map.put("", root_dir);
                    for (DiskManagerFileInfo dm_file : files) {
                        TOTorrentFile file = dm_file.getTorrentFile();
                        String path = file.getRelativePath();
                        file_map.put(path, dm_file);
                        if (path.startsWith(File.separator)) {
                            path = path.substring(1);
                        }
                        Set<Object> dir = root_dir;
                        int pos = 0;
                        while (true) {
                            int next_pos = path.indexOf(File.separatorChar, pos);
                            if (next_pos == -1) {
                                dir.add(dm_file);
                                break;
                            } else {
                                String bit = path.substring(pos, next_pos);
                                dir.add(bit);
                                String sub_path = path.substring(0, next_pos);
                                dir = (Set<Object>) file_map.get(sub_path);
                                if (dir == null) {
                                    dir = new HashSet<>();
                                    file_map.put(sub_path, dir);
                                }
                                pos = next_pos + 1;
                            }
                        }
                    }
                    Properties props = plugin_interface.getPluginProperties();
                    props.put("plugin.name", plugin_name);
                    super.initialize(plugin_interface);
                    InetAddress bind_ip = getServerBindIP();
                    if (bind_ip.isAnyLocalAddress()) {
                        host = "127.0.0.1";
                    } else {
                        host = bind_ip.getHostAddress();
                    }
                    port = getServerPort();
                    log("Assigned port: " + port);
                    protocol = getProtocol();
                    String url = protocol + "://" + host + ":" + port + "/" + url_suffix;
                    if (launch) {
                        Utils.launch(url, false, true, anon);
                    } else {
                        synchronized (url_holder) {
                            url_holder[0] = url;
                        }
                        waiter.release();
                    }
                }

                @Override
                public boolean generate(TrackerWebPageRequest request, TrackerWebPageResponse response) throws IOException {
                    try {
                        boolean res = super.generate(request, response);
                        if (!res) {
                            response.setReplyStatus(404);
                        }
                    } catch (Throwable e) {
                        response.setReplyStatus(404);
                    }
                    return (true);
                }

                @Override
                protected boolean useFile(TrackerWebPageRequest request, final TrackerWebPageResponse response, String root, String relative_url) throws IOException {
                    URL absolute_url = request.getAbsoluteURL();
                    String query = absolute_url.getQuery();
                    if (query != null) {
                        String[] args = query.split("&");
                        String vuze_source = null;
                        int vuze_file_index = -1;
                        String vuze_file_name = null;
                        List<String> networks = new ArrayList<>();
                        for (String arg : args) {
                            String[] bits = arg.split("=");
                            String lhs = bits[0];
                            String rhs = UrlUtils.decode(bits[1]);
                            if (lhs.equals("vuze_source")) {
                                if (rhs.endsWith(".torrent") || rhs.startsWith("magnet")) {
                                    vuze_source = rhs;
                                }
                            } else if (lhs.equals("vuze_file_index")) {
                                vuze_file_index = Integer.parseInt(rhs);
                            } else if (lhs.equals("vuze_file_name")) {
                                vuze_file_name = rhs;
                            } else if (lhs.equals("vuze_network")) {
                                String net = AENetworkClassifier.internalise(rhs);
                                if (net != null) {
                                    networks.add(net);
                                }
                            }
                        }
                        if (vuze_source != null) {
                            String referrer = (String) request.getHeaders().get("referer");
                            if (referrer == null || !referrer.contains("://" + host + ":" + port)) {
                                response.setReplyStatus(403);
                                return (true);
                            }
                            if (vuze_source.endsWith(".torrent")) {
                                Object file_node = file_map.get(vuze_source);
                                if (file_node instanceof DiskManagerFileInfo) {
                                    DiskManagerFileInfo dm_file = (DiskManagerFileInfo) file_node;
                                    long file_size = dm_file.getLength();
                                    File target_file = dm_file.getFile(true);
                                    boolean done = dm_file.getDownloaded() == file_size && target_file.length() == file_size;
                                    if (done) {
                                        return (handleRedirect(dm, target_file, vuze_file_index, vuze_file_name, networks, request, response));
                                    } else {
                                        try {
                                            File torrent_file = AETemporaryFileHandler.createTempFile();
                                            final FileOutputStream fos = new FileOutputStream(torrent_file);
                                            try {
                                                DiskManagerChannel chan = PluginCoreUtils.wrap(dm_file).createChannel();
                                                try {
                                                    final DiskManagerRequest req = chan.createRequest();
                                                    req.setOffset(0);
                                                    req.setLength(file_size);
                                                    req.addListener(new DiskManagerListener() {

                                                        @Override
                                                        public void eventOccurred(DiskManagerEvent event) {
                                                            int type = event.getType();
                                                            if (type == DiskManagerEvent.EVENT_TYPE_BLOCKED) {
                                                                return;
                                                            } else if (type == DiskManagerEvent.EVENT_TYPE_FAILED) {
                                                                throw (new RuntimeException(event.getFailure()));
                                                            }
                                                            PooledByteBuffer buffer = event.getBuffer();
                                                            if (buffer == null) {
                                                                throw (new RuntimeException("eh?"));
                                                            }
                                                            try {
                                                                byte[] data = buffer.toByteArray();
                                                                fos.write(data);
                                                            } catch (IOException e) {
                                                                throw (new RuntimeException("Failed to write to " + file, e));
                                                            } finally {
                                                                buffer.returnToPool();
                                                            }
                                                        }
                                                    });
                                                    req.run();
                                                } finally {
                                                    chan.destroy();
                                                }
                                            } finally {
                                                fos.close();
                                            }
                                            return (handleRedirect(dm, torrent_file, vuze_file_index, vuze_file_name, networks, request, response));
                                        } catch (Throwable e) {
                                            Debug.out(e);
                                            return (false);
                                        }
                                    }
                                } else {
                                    return (false);
                                }
                            } else {
                                URL magnet = new URL(vuze_source);
                                File torrent_file = AETemporaryFileHandler.createTempFile();
                                try {
                                    URLConnection connection = magnet.openConnection();
                                    connection.connect();
                                    FileUtil.copyFile(connection.getInputStream(), torrent_file.getAbsoluteFile());
                                    return (handleRedirect(dm, torrent_file, vuze_file_index, vuze_file_name, networks, request, response));
                                } catch (Throwable e) {
                                    Debug.out(e);
                                }
                            }
                        }
                    }
                    String path = absolute_url.getPath();
                    if (path.equals("/")) {
                        if (COConfigurationManager.getBooleanParameter("Library.LaunchWebsiteInBrowserDirList")) {
                            relative_url = "/";
                        }
                    }
                    String download_name = XUXmlWriter.escapeXML(dm.getDisplayName());
                    String relative_file = relative_url.replace('/', File.separatorChar);
                    String node_key = relative_file.substring(1);
                    Object file_node = file_map.get(node_key);
                    boolean file_node_is_parent = false;
                    if (file_node == null) {
                        int pos = node_key.lastIndexOf(File.separator);
                        if (pos == -1) {
                            node_key = "";
                        } else {
                            node_key = node_key.substring(0, pos);
                        }
                        file_node = file_map.get(node_key);
                        file_node_is_parent = true;
                    }
                    if (file_node == null) {
                        return (false);
                    }
                    if (file_node instanceof Set) {
                        if (relative_url.equals("/favicon.ico")) {
                            try {
                                InputStream stream = getClass().getClassLoader().getResourceAsStream("com/biglybt/ui/icons/favicon.ico");
                                response.useStream("image/x-icon", stream);
                                return (true);
                            } catch (Throwable e) {
                            }
                        }
                        Set<Object> kids = (Set<Object>) file_node;
                        String request_url = request.getURL();
                        if (file_node_is_parent) {
                            int pos = request_url.lastIndexOf("/");
                            if (pos == -1) {
                                request_url = "";
                            } else {
                                request_url = request_url.substring(0, pos);
                            }
                        }
                        response.setContentType("text/html");
                        OutputStream os = response.getOutputStream();
                        String title = XUXmlWriter.escapeXML(UrlUtils.decode(request_url));
                        if (title.length() == 0) {
                            title = "/";
                        }
                        os.write(("<html>" + NL + " <head>" + NL + " <meta charset=\"UTF-8\">" + NL + "  <title>" + download_name + ": Index of " + title + "</title>" + NL + " </head>" + NL + " <body>" + NL + "  <p>" + download_name + "</p>" + NL + "  <h1>Index of " + title + "</h1>" + NL + "  <pre><hr>" + NL).getBytes("UTF-8"));
                        String root_url = request_url;
                        if (!root_url.endsWith("/")) {
                            root_url += "/";
                        }
                        if (request_url.length() > 1) {
                            int pos = request_url.lastIndexOf('/');
                            if (pos == 0) {
                                pos++;
                            }
                            String parent = request_url.substring(0, pos);
                            os.write(("<a href=\"" + parent + "\">..</a>" + NL).getBytes("UTF-8"));
                        }
                        List<String[]> filenames = new ArrayList<>(kids.size());
                        int max_filename = 0;
                        int MAX_LEN = 120;
                        for (Object entry : kids) {
                            DiskManagerFileInfo file;
                            String file_name;
                            if (entry instanceof String) {
                                file = null;
                                file_name = (String) entry;
                            } else {
                                file = (DiskManagerFileInfo) entry;
                                if (file.isSkipped()) {
                                    continue;
                                }
                                file_name = file.getTorrentFile().getRelativePath();
                                int pos = file_name.lastIndexOf(File.separatorChar);
                                if (pos != -1) {
                                    file_name = file_name.substring(pos + 1);
                                }
                            }
                            String url = root_url + UrlUtils.encode(file_name);
                            if (file == null) {
                                file_name += "/";
                            }
                            int len = file_name.length();
                            if (len > MAX_LEN) {
                                file_name = file_name.substring(0, MAX_LEN - 3) + "...";
                                len = file_name.length();
                            }
                            if (len > max_filename) {
                                max_filename = len;
                            }
                            filenames.add(new String[] { url, file_name, file == null ? "" : DisplayFormatters.formatByteCountToKiBEtc(file.getLength()) });
                        }
                        max_filename = ((max_filename + 15) / 8) * 8;
                        char[] padding = new char[max_filename];
                        Arrays.fill(padding, ' ');
                        Collections.sort(filenames, new Comparator<String[]>() {

                            Comparator comp = new FormattersImpl().getAlphanumericComparator(true);

                            @Override
                            public int compare(String[] o1, String[] o2) {
                                return (comp.compare(o1[0], o2[0]));
                            }
                        });
                        for (String[] entry : filenames) {
                            String file_name = entry[1];
                            int len = file_name.length();
                            StringBuilder line = new StringBuilder(max_filename + 64);
                            line.append("<a href=\"").append(entry[0]).append("\">").append(XUXmlWriter.escapeXML(file_name)).append("</a>");
                            line.append(padding, 0, max_filename - len);
                            line.append(entry[2]);
                            line.append(NL);
                            os.write(line.toString().getBytes("UTF-8"));
                        }
                        os.write(("  <hr></pre>" + NL + "  <address>" + Constants.APP_NAME + " Web Server at " + host + " Port " + getServerPort() + "</address>" + NL + " </body>" + NL + "</html>").getBytes("UTF-8"));
                        return (true);
                    } else {
                        DiskManagerFileInfo dm_file = (DiskManagerFileInfo) file_node;
                        long file_size = dm_file.getLength();
                        File target_file = dm_file.getFile(true);
                        boolean done = dm_file.getDownloaded() == file_size && target_file.length() == file_size;
                        String file_type;
                        // Use the original torrent file name when deducing file type to
                        // avoid incomplete suffix issues etc
                        String relative_path = dm_file.getTorrentFile().getRelativePath();
                        int pos = relative_path.lastIndexOf(".");
                        if (pos == -1) {
                            file_type = "";
                        } else {
                            file_type = relative_path.substring(pos + 1);
                        }
                        if (file_size >= 512 * 1024) {
                            String content_type = HTTPUtils.guessContentTypeFromFileType(file_type);
                            if (content_type.startsWith("text/") || content_type.startsWith("image/")) {
                            // don't want to be redirecting here as (for example) .html needs
                            // to remain in the 'correct' place so that relative assets work
                            } else {
                                URL stream_url = getMediaServerContentURL(dm_file);
                                if (stream_url != null) {
                                    OutputStream os = response.getRawOutputStream();
                                    os.write(("HTTP/1.1 302 Found" + NL + "Location: " + stream_url.toExternalForm() + NL + NL).getBytes("UTF-8"));
                                    return (true);
                                }
                            }
                        }
                        if (done) {
                            if (file_size < 512 * 1024) {
                                FileInputStream fis = null;
                                try {
                                    fis = new FileInputStream(target_file);
                                    response.useStream(file_type, fis);
                                    return (true);
                                } finally {
                                    if (fis != null) {
                                        fis.close();
                                    }
                                }
                            } else {
                                OutputStream os = null;
                                InputStream is = null;
                                try {
                                    os = response.getRawOutputStream();
                                    os.write(("HTTP/1.1 200 OK" + NL + "Content-Type:" + HTTPUtils.guessContentTypeFromFileType(file_type) + NL + "Content-Length: " + file_size + NL + "Connection: close" + NL + NL).getBytes("UTF-8"));
                                    byte[] buffer = new byte[128 * 1024];
                                    is = new FileInputStream(target_file);
                                    while (true) {
                                        int len = is.read(buffer);
                                        if (len <= 0) {
                                            break;
                                        }
                                        os.write(buffer, 0, len);
                                    }
                                } catch (Throwable e) {
                                // e.printStackTrace();
                                } finally {
                                    try {
                                        os.close();
                                    } catch (Throwable e) {
                                    }
                                    try {
                                        is.close();
                                    } catch (Throwable e) {
                                    }
                                }
                                return (true);
                            }
                        } else {
                            dm_file.setPriority(10);
                            try {
                                final OutputStream os = response.getRawOutputStream();
                                os.write(("HTTP/1.1 200 OK" + NL + "Content-Type:" + HTTPUtils.guessContentTypeFromFileType(file_type) + NL + "Content-Length: " + file_size + NL + "Connection: close" + NL + "X-Vuze-Hack: X").getBytes("UTF-8"));
                                DiskManagerChannel chan = PluginCoreUtils.wrap(dm_file).createChannel();
                                try {
                                    final DiskManagerRequest req = chan.createRequest();
                                    final boolean[] header_complete = { false };
                                    final long[] last_write = { 0 };
                                    req.setOffset(0);
                                    req.setLength(file_size);
                                    req.addListener(new DiskManagerListener() {

                                        @Override
                                        public void eventOccurred(DiskManagerEvent event) {
                                            int type = event.getType();
                                            if (type == DiskManagerEvent.EVENT_TYPE_BLOCKED) {
                                                return;
                                            } else if (type == DiskManagerEvent.EVENT_TYPE_FAILED) {
                                                throw (new RuntimeException(event.getFailure()));
                                            }
                                            PooledByteBuffer buffer = event.getBuffer();
                                            if (buffer == null) {
                                                throw (new RuntimeException("eh?"));
                                            }
                                            try {
                                                boolean do_header = false;
                                                synchronized (header_complete) {
                                                    if (!header_complete[0]) {
                                                        do_header = true;
                                                        header_complete[0] = true;
                                                    }
                                                    last_write[0] = SystemTime.getMonotonousTime();
                                                }
                                                if (do_header) {
                                                    os.write((NL + NL).getBytes("UTF-8"));
                                                }
                                                byte[] data = buffer.toByteArray();
                                                os.write(data);
                                            } catch (IOException e) {
                                                throw (new RuntimeException("Failed to write to " + file, e));
                                            } finally {
                                                buffer.returnToPool();
                                            }
                                        }
                                    });
                                    final TimerEventPeriodic[] timer_event = { null };
                                    timer_event[0] = SimpleTimer.addPeriodicEvent("KeepAlive", 10 * 1000, new TimerEventPerformer() {

                                        boolean cancel_outstanding = false;

                                        @Override
                                        public void perform(TimerEvent event) {
                                            if (cancel_outstanding) {
                                                req.cancel();
                                            } else {
                                                synchronized (header_complete) {
                                                    if (header_complete[0]) {
                                                        if (SystemTime.getMonotonousTime() - last_write[0] >= 5 * 60 * 1000) {
                                                            req.cancel();
                                                        }
                                                    } else {
                                                        try {
                                                            os.write("X".getBytes("UTF-8"));
                                                            os.flush();
                                                        } catch (Throwable e) {
                                                            req.cancel();
                                                        }
                                                    }
                                                }
                                                if (!response.isActive()) {
                                                    cancel_outstanding = true;
                                                }
                                            }
                                        }
                                    });
                                    try {
                                        req.run();
                                    } finally {
                                        timer_event[0].cancel();
                                    }
                                    return (true);
                                } finally {
                                    chan.destroy();
                                }
                            } catch (Throwable e) {
                                return (false);
                            }
                        }
                    }
                }

                private boolean handleRedirect(DownloadManager dm, File torrent_file, int file_index, String file_name, List<String> networks, TrackerWebPageRequest request, TrackerWebPageResponse response) {
                    try {
                        TOTorrent torrent = TOTorrentFactory.deserialiseFromBEncodedFile(torrent_file);
                        GlobalManager gm = CoreFactory.getSingleton().getGlobalManager();
                        UIFunctions uif = UIFunctionsManager.getUIFunctions();
                        TorrentOpenOptions torrent_options = new TorrentOpenOptions(torrent_file.getAbsolutePath(), torrent, false);
                        torrent_options.setTorrent(torrent);
                        String[] existing_nets;
                        if (networks.size() == 0) {
                            // inherit networks from parent
                            existing_nets = dm.getDownloadState().getNetworks();
                        } else {
                            existing_nets = networks.toArray(new String[networks.size()]);
                        }
                        for (String net : AENetworkClassifier.AT_NETWORKS) {
                            boolean found = false;
                            for (String x : existing_nets) {
                                if (net == x) {
                                    found = true;
                                    break;
                                }
                            }
                            torrent_options.setNetworkEnabled(net, found);
                        }
                        Map<String, Object> add_options = new HashMap<>();
                        add_options.put(UIFunctions.OTO_SILENT, true);
                        if (uif.addTorrentWithOptions(torrent_options, add_options)) {
                            long start = SystemTime.getMonotonousTime();
                            while (true) {
                                DownloadManager o_dm = gm.getDownloadManager(torrent);
                                if (o_dm != null) {
                                    if (!o_dm.getDownloadState().getFlag(DownloadManagerState.FLAG_METADATA_DOWNLOAD)) {
                                        DiskManagerFileInfo[] files = o_dm.getDiskManagerFileInfoSet().getFiles();
                                        DiskManagerFileInfo o_dm_file = null;
                                        if (file_name != null) {
                                            for (DiskManagerFileInfo file : files) {
                                                String path = file.getTorrentFile().getRelativePath();
                                                if (path.equals(file_name)) {
                                                    o_dm_file = file;
                                                    break;
                                                }
                                            }
                                            if (o_dm_file == null) {
                                                o_dm_file = files[0];
                                            }
                                        } else {
                                            if (file_index < 0) {
                                                long largest = -1;
                                                for (DiskManagerFileInfo file : files) {
                                                    if (file.getLength() > largest) {
                                                        o_dm_file = file;
                                                        largest = file.getLength();
                                                    }
                                                }
                                            } else {
                                                o_dm_file = files[file_index];
                                            }
                                        }
                                        String original_path = request.getAbsoluteURL().getPath();
                                        if (original_path.endsWith(".html")) {
                                            String url = browse(o_dm, file_index < 0 ? null : o_dm_file, anon, false);
                                            OutputStream os = response.getRawOutputStream();
                                            os.write(("HTTP/1.1 302 Found" + NL + "Location: " + url + NL + NL).getBytes("UTF-8"));
                                            return (true);
                                        } else {
                                            URL stream_url = getMediaServerContentURL(o_dm_file);
                                            if (stream_url != null) {
                                                OutputStream os = response.getRawOutputStream();
                                                os.write(("HTTP/1.1 302 Found" + NL + "Location: " + stream_url.toExternalForm() + NL + NL).getBytes("UTF-8"));
                                                return (true);
                                            }
                                        }
                                    }
                                }
                                long now = SystemTime.getMonotonousTime();
                                if (now - start > 3 * 60 * 1000) {
                                    Debug.out("Timeout waiting for download to be added");
                                    return (false);
                                }
                                Thread.sleep(1000);
                            }
                        } else {
                            Debug.out("Failed to add download for some reason");
                            return (false);
                        }
                    } catch (Throwable e) {
                        Debug.out(e);
                        return (false);
                    }
                }

                @Override
                public void unload() throws PluginException {
                    synchronized (browse_plugins) {
                        browse_plugins.remove(dm);
                    }
                    super.unload();
                }
            };
            PluginManager.registerPlugin(plugin, plugin_id, plugin_id);
            browse_plugins.put(dm, plugin);
            if (launch) {
                return (null);
            } else {
                waiter.reserve(10 * 1000);
                synchronized (url_holder) {
                    return (url_holder[0]);
                }
            }
        } else {
            String protocol = plugin.getProtocol();
            InetAddress bind_ip = plugin.getServerBindIP();
            String host;
            if (bind_ip.isAnyLocalAddress()) {
                host = "127.0.0.1";
            } else {
                host = bind_ip.getHostAddress();
            }
            String url = protocol + "://" + host + ":" + plugin.getServerPort() + "/" + url_suffix;
            if (launch) {
                Utils.launch(url, false, true, anon);
                return (null);
            } else {
                return (url);
            }
        }
    }
}
Also used : TrackerWebPageRequest(com.biglybt.pif.tracker.web.TrackerWebPageRequest) TrackerWebPageResponse(com.biglybt.pif.tracker.web.TrackerWebPageResponse) DownloadManager(com.biglybt.core.download.DownloadManager) GlobalManager(com.biglybt.core.global.GlobalManager) DiskManagerListener(com.biglybt.pif.disk.DiskManagerListener) UIFunctions(com.biglybt.ui.UIFunctions) DiskManagerChannel(com.biglybt.pif.disk.DiskManagerChannel) PluginException(com.biglybt.pif.PluginException) DiskManagerFileInfoSet(com.biglybt.core.disk.DiskManagerFileInfoSet) TOTorrentFile(com.biglybt.core.torrent.TOTorrentFile) TOTorrentFile(com.biglybt.core.torrent.TOTorrentFile) InetAddress(java.net.InetAddress) DiskManagerFileInfoSet(com.biglybt.core.disk.DiskManagerFileInfoSet) URL(java.net.URL) TorrentOpenOptions(com.biglybt.core.torrent.impl.TorrentOpenOptions) PooledByteBuffer(com.biglybt.pif.utils.PooledByteBuffer) WebPlugin(com.biglybt.ui.webplugin.WebPlugin) DiskManagerFileInfo(com.biglybt.core.disk.DiskManagerFileInfo) DiskManagerRequest(com.biglybt.pif.disk.DiskManagerRequest) PluginInterface(com.biglybt.pif.PluginInterface) FormattersImpl(com.biglybt.pifimpl.local.utils.FormattersImpl) URLConnection(java.net.URLConnection) TOTorrent(com.biglybt.core.torrent.TOTorrent) DiskManagerEvent(com.biglybt.pif.disk.DiskManagerEvent)

Example 2 with DiskManagerFileInfoSet

use of com.biglybt.core.disk.DiskManagerFileInfoSet in project BiglyBT by BiglySoftware.

the class TorrentUtil method fillTorrentMenu.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Example 3 with DiskManagerFileInfoSet

use of com.biglybt.core.disk.DiskManagerFileInfoSet in project BiglyBT by BiglySoftware.

the class TorrentUtil method calculateToolbarStates.

// XXX Don't think *View's need this call anymore.  ToolBarView does it fo them
public static Map<String, Long> calculateToolbarStates(ISelectedContent[] currentContent, String viewID_unused) {
    // System.out.println("calculateToolbarStates(" + currentContent.length + ", " + viewID_unused + " via " + Debug.getCompressedStackTrace());
    /*
		String[] TBKEYS = new String[] {
			"download",
			"play",
			"stream",
			"run",
			"top",
			"up",
			"down",
			"bottom",
			"start",
			"stop",
			"remove"
		};
		*/
    Map<String, Long> mapNewToolbarStates = new HashMap<>();
    String[] itemsNeedingSelection = {};
    String[] itemsNeedingRealDMSelection = { "remove", "top", "bottom", "transcode", "startstop" };
    String[] itemsRequiring1DMwithHash = { "details", "comment", "up", "down" };
    String[] itemsRequiring1DMSelection = {};
    int numSelection = currentContent.length;
    boolean hasSelection = numSelection > 0;
    boolean has1Selection = numSelection == 1;
    for (int i = 0; i < itemsNeedingSelection.length; i++) {
        String itemID = itemsNeedingSelection[i];
        mapNewToolbarStates.put(itemID, hasSelection ? UIToolBarItem.STATE_ENABLED : 0);
    }
    TableView tv = SelectedContentManager.getCurrentlySelectedTableView();
    // not sure why we assume that the existance of any table view
    boolean hasRealDM = tv != null;
    if (!hasRealDM && numSelection > 0) {
        hasRealDM = true;
        for (int i = 0; i < currentContent.length; i++) {
            ISelectedContent content = currentContent[i];
            DownloadManager dm = content.getDownloadManager();
            if (dm == null) {
                hasRealDM = false;
                break;
            }
        }
    }
    if (!hasRealDM) {
        MultipleDocumentInterfaceSWT mdi = UIFunctionsManagerSWT.getUIFunctionsSWT().getMDISWT();
        if (mdi != null) {
            MdiEntrySWT entry = mdi.getCurrentEntrySWT();
            if (entry != null) {
                if (entry.getDatasource() instanceof DownloadManager) {
                    hasRealDM = true;
                } else if ((entry instanceof UIPluginView) && (((UIPluginView) entry).getDataSource() instanceof DownloadManager)) {
                    hasRealDM = true;
                }
            }
        }
    }
    boolean canStart = false;
    boolean canStop = false;
    boolean canRemoveFileInfo = false;
    boolean canRunFileInfo = false;
    boolean canCheckExist = false;
    boolean hasDM = false;
    boolean canRecheck = false;
    if (currentContent.length > 0 && hasRealDM) {
        // well, in fact, we can have hasRealDM set to true here (because tv isn't null) and actually not have a real dm.
        // fancy that - protect against null DownloadManagers...
        boolean canMoveUp = false;
        boolean canMoveDown = false;
        boolean canDownload = false;
        canCheckExist = true;
        GlobalManager gm = null;
        for (int i = 0; i < currentContent.length; i++) {
            ISelectedContent content = currentContent[i];
            DownloadManager dm = content.getDownloadManager();
            if (dm == null) {
                if (!canDownload && content.getDownloadInfo() != null) {
                    canDownload = true;
                }
                continue;
            }
            if (gm == null) {
                gm = dm.getGlobalManager();
            }
            int state = dm.getState();
            canCheckExist &= (state == DownloadManager.STATE_ERROR || state == DownloadManager.STATE_STOPPED || state == DownloadManager.STATE_QUEUED);
            int fileIndex = content.getFileIndex();
            if (fileIndex == -1) {
                if (!canMoveUp && gm.isMoveableUp(dm)) {
                    canMoveUp = true;
                }
                if (!canMoveDown && gm.isMoveableDown(dm)) {
                    canMoveDown = true;
                }
                hasDM = true;
                if (!canStart && ManagerUtils.isStartable(dm)) {
                    canStart = true;
                }
                if (!canStop && ManagerUtils.isStopable(dm)) {
                    canStop = true;
                }
            } else {
                DiskManagerFileInfoSet fileInfos = dm.getDiskManagerFileInfoSet();
                if (fileIndex < fileInfos.nbFiles()) {
                    DiskManagerFileInfo fileInfo = fileInfos.getFiles()[fileIndex];
                    if (!canStart && (fileInfo.isSkipped())) {
                        canStart = true;
                    }
                    if (!canStop && !fileInfo.isSkipped()) {
                        canStop = true;
                    }
                    if (!canRemoveFileInfo && !fileInfo.isSkipped()) {
                        int storageType = fileInfo.getStorageType();
                        if (storageType == DiskManagerFileInfo.ST_LINEAR || storageType == DiskManagerFileInfo.ST_COMPACT) {
                            canRemoveFileInfo = true;
                        }
                    }
                    if (!canRunFileInfo && fileInfo.getAccessMode() == DiskManagerFileInfo.READ && fileInfo.getDownloaded() == fileInfo.getLength() && fileInfo.getFile(true).exists()) {
                        canRunFileInfo = true;
                    }
                }
            }
            canRecheck = canRecheck || dm.canForceRecheck();
        }
        boolean canRemove = hasDM || canRemoveFileInfo;
        mapNewToolbarStates.put("remove", canRemove ? UIToolBarItem.STATE_ENABLED : 0);
        mapNewToolbarStates.put("download", canDownload ? UIToolBarItem.STATE_ENABLED : 0);
        if (currentContent.length == 1) {
            mapNewToolbarStates.put("up", canMoveUp ? UIToolBarItem.STATE_ENABLED : 0);
            mapNewToolbarStates.put("down", canMoveDown ? UIToolBarItem.STATE_ENABLED : 0);
        }
    }
    boolean canRun = has1Selection && ((hasDM && !canRunFileInfo) || (!hasDM && canRunFileInfo));
    if (canRun) {
        ISelectedContent content = currentContent[0];
        DownloadManager dm = content.getDownloadManager();
        if (dm == null) {
            canRun = false;
        } else {
            TOTorrent torrent = dm.getTorrent();
            if (torrent == null) {
                canRun = false;
            } else if (!dm.getAssumedComplete() && torrent.isSimpleTorrent()) {
                canRun = false;
            /*
									} else if (PlatformTorrentUtils.useEMP(torrent)
											&& PlatformTorrentUtils.embeddedPlayerAvail()
											&& PlayUtils.canProgressiveOrIsComplete(torrent)) {
										// play button enabled and not UMP.. don't need launch

										canRun = false;

									}
									*/
            }
        }
    }
    mapNewToolbarStates.put("run", canRun ? UIToolBarItem.STATE_ENABLED : 0);
    mapNewToolbarStates.put("start", canStart ? UIToolBarItem.STATE_ENABLED : 0);
    mapNewToolbarStates.put("stop", canStop ? UIToolBarItem.STATE_ENABLED : 0);
    mapNewToolbarStates.put("startstop", canStart || canStop ? UIToolBarItem.STATE_ENABLED : 0);
    for (int i = 0; i < itemsNeedingRealDMSelection.length; i++) {
        String itemID = itemsNeedingRealDMSelection[i];
        if (!mapNewToolbarStates.containsKey(itemID)) {
            mapNewToolbarStates.put(itemID, hasSelection && hasDM && hasRealDM ? UIToolBarItem.STATE_ENABLED : 0);
        }
    }
    for (int i = 0; i < itemsRequiring1DMSelection.length; i++) {
        String itemID = itemsRequiring1DMSelection[i];
        if (!mapNewToolbarStates.containsKey(itemID)) {
            mapNewToolbarStates.put(itemID, has1Selection && hasDM ? UIToolBarItem.STATE_ENABLED : 0);
        }
    }
    for (int i = 0; i < itemsRequiring1DMwithHash.length; i++) {
        String itemID = itemsRequiring1DMwithHash[i];
        if (!mapNewToolbarStates.containsKey(itemID)) {
            mapNewToolbarStates.put(itemID, hasDM ? UIToolBarItem.STATE_ENABLED : 0);
        }
    }
    mapNewToolbarStates.put("download", has1Selection && (!(currentContent[0] instanceof ISelectedVuzeFileContent)) && currentContent[0].getDownloadManager() == null && (currentContent[0].getHash() != null || currentContent[0].getDownloadInfo() != null) ? UIToolBarItem.STATE_ENABLED : 0);
    if (tv != null) {
        TableColumn tc = tv.getTableColumn(RankItem.COLUMN_ID);
        if (tc != null && !tc.isVisible()) {
            mapNewToolbarStates.put("up", 0L);
            mapNewToolbarStates.put("down", 0L);
        }
    }
    mapNewToolbarStates.put(TU_ITEM_RECHECK, canRecheck ? UIToolBarItem.STATE_ENABLED : 0);
    mapNewToolbarStates.put(TU_ITEM_CHECK_FILES, canCheckExist ? UIToolBarItem.STATE_ENABLED : 0);
    return mapNewToolbarStates;
}
Also used : ISelectedVuzeFileContent(com.biglybt.ui.selectedcontent.ISelectedVuzeFileContent) DiskManagerFileInfo(com.biglybt.core.disk.DiskManagerFileInfo) ISelectedContent(com.biglybt.ui.selectedcontent.ISelectedContent) DiskManagerFileInfoSet(com.biglybt.core.disk.DiskManagerFileInfoSet) MdiEntrySWT(com.biglybt.ui.swt.mdi.MdiEntrySWT) DownloadManager(com.biglybt.core.download.DownloadManager) TableColumn(com.biglybt.pif.ui.tables.TableColumn) GlobalManager(com.biglybt.core.global.GlobalManager) TOTorrent(com.biglybt.core.torrent.TOTorrent) UIPluginView(com.biglybt.pif.ui.UIPluginView) MultipleDocumentInterfaceSWT(com.biglybt.ui.swt.mdi.MultipleDocumentInterfaceSWT) TableView(com.biglybt.ui.common.table.TableView)

Example 4 with DiskManagerFileInfoSet

use of com.biglybt.core.disk.DiskManagerFileInfoSet in project BiglyBT by BiglySoftware.

the class TorrentOpener method addTorrent.

/**
 * @param torrentOptions
 * @return
 * @since 5.0.0.1
 *
 * @TODO: Remove SWT UI parts (use UIFunctions) and move out of SWT tree
 */
public static final boolean addTorrent(final TorrentOpenOptions torrentOptions) {
    try {
        if (torrentOptions.getTorrent() == null) {
            return false;
        }
        final DownloadManagerInitialisationAdapter dmia = new DownloadManagerInitialisationAdapter() {

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

            @Override
            public void initialised(DownloadManager dm, boolean for_seeding) {
                DiskManagerFileInfoSet file_info_set = dm.getDiskManagerFileInfoSet();
                DiskManagerFileInfo[] fileInfos = file_info_set.getFiles();
                boolean reorder_mode = COConfigurationManager.getBooleanParameter("Enable reorder storage mode");
                int reorder_mode_min_mb = COConfigurationManager.getIntParameter("Reorder storage mode min MB");
                try {
                    dm.getDownloadState().suppressStateSave(true);
                    boolean[] toSkip = new boolean[fileInfos.length];
                    boolean[] toCompact = new boolean[fileInfos.length];
                    boolean[] toReorderCompact = new boolean[fileInfos.length];
                    int[] priorities = null;
                    int comp_num = 0;
                    int reorder_comp_num = 0;
                    final TorrentOpenFileOptions[] files = torrentOptions.getFiles();
                    for (int iIndex = 0; iIndex < fileInfos.length; iIndex++) {
                        DiskManagerFileInfo fileInfo = fileInfos[iIndex];
                        if (iIndex >= 0 && iIndex < files.length && files[iIndex].lSize == fileInfo.getLength()) {
                            // Always pull destination file from fileInfo and not from
                            // TorrentFileInfo because the destination may have changed
                            // by magic code elsewhere
                            File fDest = fileInfo.getFile(true);
                            if (files[iIndex].isLinked()) {
                                fDest = files[iIndex].getDestFileFullName();
                                // Can't use fileInfo.setLink(fDest) as it renames
                                // the existing file if there is one
                                dm.getDownloadState().setFileLink(iIndex, fileInfo.getFile(false), fDest);
                            }
                            if (files[iIndex].isToDownload()) {
                                int priority = files[iIndex].getPriority();
                                if (priority != 0) {
                                    if (priorities == null) {
                                        priorities = new int[fileInfos.length];
                                    }
                                    priorities[iIndex] = priority;
                                }
                            } else {
                                toSkip[iIndex] = true;
                                if (!fDest.exists()) {
                                    if (reorder_mode && (fileInfo.getLength() / (1024 * 1024)) >= reorder_mode_min_mb) {
                                        toReorderCompact[iIndex] = true;
                                        reorder_comp_num++;
                                    } else {
                                        toCompact[iIndex] = true;
                                        comp_num++;
                                    }
                                }
                            }
                        }
                    }
                    if (files.length == 1) {
                        TorrentOpenFileOptions file = files[0];
                        if (file.isManualRename()) {
                            String fileRename = file.getDestFileName();
                            if (fileRename != null && fileRename.length() > 0) {
                                dm.getDownloadState().setDisplayName(fileRename);
                            }
                        }
                    } else {
                        String folderRename = torrentOptions.getManualRename();
                        if (folderRename != null && folderRename.length() > 0) {
                            dm.getDownloadState().setDisplayName(folderRename);
                        }
                    }
                    if (comp_num > 0) {
                        file_info_set.setStorageTypes(toCompact, DiskManagerFileInfo.ST_COMPACT);
                    }
                    if (reorder_comp_num > 0) {
                        file_info_set.setStorageTypes(toReorderCompact, DiskManagerFileInfo.ST_REORDER_COMPACT);
                    }
                    file_info_set.setSkipped(toSkip, true);
                    if (priorities != null) {
                        file_info_set.setPriority(priorities);
                    }
                    int maxUp = torrentOptions.getMaxUploadSpeed();
                    int kInB = DisplayFormatters.getKinB();
                    if (maxUp > 0) {
                        dm.getStats().setUploadRateLimitBytesPerSecond(maxUp * kInB);
                    }
                    int maxDown = torrentOptions.getMaxDownloadSpeed();
                    if (maxDown > 0) {
                        dm.getStats().setDownloadRateLimitBytesPerSecond(maxDown * kInB);
                    }
                    DownloadManagerState dm_state = dm.getDownloadState();
                    if (torrentOptions.disableIPFilter) {
                        dm_state.setFlag(DownloadManagerState.FLAG_DISABLE_IP_FILTER, true);
                    }
                    if (torrentOptions.peerSource != null) {
                        for (String peerSource : torrentOptions.peerSource.keySet()) {
                            boolean enable = torrentOptions.peerSource.get(peerSource);
                            dm_state.setPeerSourceEnabled(peerSource, enable);
                        }
                    }
                    Map<String, Boolean> enabledNetworks = torrentOptions.getEnabledNetworks();
                    if (enabledNetworks != null) {
                        if (!dm_state.getFlag(DownloadManagerState.FLAG_INITIAL_NETWORKS_SET)) {
                            for (String net : enabledNetworks.keySet()) {
                                boolean enable = enabledNetworks.get(net);
                                dm_state.setNetworkEnabled(net, enable);
                            }
                        }
                    }
                    List<Tag> initialTags = torrentOptions.getInitialTags();
                    for (Tag t : initialTags) {
                        t.addTaggable(dm);
                    }
                    List<List<String>> trackers = torrentOptions.getTrackers(true);
                    if (trackers != null) {
                        TOTorrent torrent = dm.getTorrent();
                        TorrentUtils.listToAnnounceGroups(trackers, torrent);
                        try {
                            TorrentUtils.writeToFile(torrent);
                        } catch (Throwable e2) {
                            Debug.printStackTrace(e2);
                        }
                    }
                    if (torrentOptions.bSequentialDownload) {
                        dm_state.setFlag(DownloadManagerState.FLAG_SEQUENTIAL_DOWNLOAD, true);
                    }
                    File moc = torrentOptions.getMoveOnComplete();
                    if (moc != null) {
                        dm_state.setAttribute(DownloadManagerState.AT_MOVE_ON_COMPLETE_DIR, moc.getAbsolutePath());
                    }
                } finally {
                    dm.getDownloadState().suppressStateSave(false);
                }
            }
        };
        CoreFactory.addCoreRunningListener(new CoreRunningListener() {

            @Override
            public void coreRunning(Core core) {
                TOTorrent torrent = torrentOptions.getTorrent();
                byte[] hash = null;
                try {
                    hash = torrent.getHash();
                } catch (TOTorrentException e1) {
                }
                int iStartState = (torrentOptions.getStartMode() == TorrentOpenOptions.STARTMODE_STOPPED) ? DownloadManager.STATE_STOPPED : DownloadManager.STATE_QUEUED;
                GlobalManager gm = core.getGlobalManager();
                DownloadManager dm = gm.addDownloadManager(torrentOptions.sFileName, hash, torrentOptions.getParentDir(), torrentOptions.getSubDir(), iStartState, true, torrentOptions.getStartMode() == TorrentOpenOptions.STARTMODE_SEEDING, dmia);
                // since gm.addDown.. will handle it.
                if (dm == null) {
                    return;
                }
                if (torrentOptions.iQueueLocation == TorrentOpenOptions.QUEUELOCATION_TOP) {
                    gm.moveTop(new DownloadManager[] { dm });
                }
                if (torrentOptions.getStartMode() == TorrentOpenOptions.STARTMODE_FORCESTARTED) {
                    dm.setForceStart(true);
                }
            }
        });
    } catch (Exception e) {
        UIFunctions uif = UIFunctionsManager.getUIFunctions();
        if (uif != null) {
            uif.showErrorMessage("OpenTorrentWindow.mb.openError", Debug.getStackTrace(e), new String[] { torrentOptions.sOriginatingLocation, e.getMessage() });
        }
        return false;
    }
    return true;
}
Also used : DownloadManager(com.biglybt.core.download.DownloadManager) DownloadManagerState(com.biglybt.core.download.DownloadManagerState) GlobalManager(com.biglybt.core.global.GlobalManager) UIFunctions(com.biglybt.ui.UIFunctions) CoreRunningListener(com.biglybt.core.CoreRunningListener) ArrayList(java.util.ArrayList) List(java.util.List) Core(com.biglybt.core.Core) DiskManagerFileInfo(com.biglybt.core.disk.DiskManagerFileInfo) TorrentOpenFileOptions(com.biglybt.core.torrent.impl.TorrentOpenFileOptions) DiskManagerFileInfoSet(com.biglybt.core.disk.DiskManagerFileInfoSet) DownloadManagerInitialisationAdapter(com.biglybt.core.download.DownloadManagerInitialisationAdapter) TOTorrentException(com.biglybt.core.torrent.TOTorrentException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) TOTorrentException(com.biglybt.core.torrent.TOTorrentException) TOTorrent(com.biglybt.core.torrent.TOTorrent) Tag(com.biglybt.core.tag.Tag) VuzeFile(com.biglybt.core.vuzefile.VuzeFile) File(java.io.File)

Example 5 with DiskManagerFileInfoSet

use of com.biglybt.core.disk.DiskManagerFileInfoSet in project BiglyBT by BiglySoftware.

the class MyTorrentsView method rowRefresh.

// @see com.biglybt.pif.ui.tables.TableRowRefreshListener#rowRefresh(com.biglybt.pif.ui.tables.TableRow)
@Override
public void rowRefresh(TableRow row) {
    if (!(row instanceof TableRowCore)) {
        return;
    }
    TableRowCore rowCore = (TableRowCore) row;
    Object ds = rowCore.getDataSource(true);
    if (!(ds instanceof DownloadManager)) {
        return;
    }
    DownloadManager dm = (DownloadManager) ds;
    if (rowCore.getSubItemCount() == 0 && dm.getTorrent() != null && !dm.getTorrent().isSimpleTorrent() && rowCore.isVisible() && dm.getNumFileInfos() > 0) {
        DiskManagerFileInfoSet fileInfos = dm.getDiskManagerFileInfoSet();
        if (fileInfos != null) {
            DiskManagerFileInfo[] files = fileInfos.getFiles();
            boolean copied = false;
            int pos = 0;
            for (int i = 0; i < files.length; i++) {
                DiskManagerFileInfo fileInfo = files[i];
                if (fileInfo.isSkipped() && (fileInfo.getStorageType() == DiskManagerFileInfo.ST_COMPACT || fileInfo.getStorageType() == DiskManagerFileInfo.ST_REORDER_COMPACT)) {
                    continue;
                }
                if (pos != i) {
                    if (!copied) {
                        // we *MUSTN'T* modify the returned array!!!!
                        DiskManagerFileInfo[] oldFiles = files;
                        files = new DiskManagerFileInfo[files.length];
                        System.arraycopy(oldFiles, 0, files, 0, files.length);
                        copied = true;
                    }
                    files[pos] = files[i];
                }
                pos++;
            }
            if (pos != files.length) {
                DiskManagerFileInfo[] oldFiles = files;
                files = new DiskManagerFileInfo[pos];
                System.arraycopy(oldFiles, 0, files, 0, pos);
            }
            rowCore.setSubItems(files);
        }
    }
}
Also used : DiskManagerFileInfo(com.biglybt.core.disk.DiskManagerFileInfo) DiskManagerFileInfoSet(com.biglybt.core.disk.DiskManagerFileInfoSet) DownloadManager(com.biglybt.core.download.DownloadManager)

Aggregations

DiskManagerFileInfo (com.biglybt.core.disk.DiskManagerFileInfo)7 DiskManagerFileInfoSet (com.biglybt.core.disk.DiskManagerFileInfoSet)7 DownloadManager (com.biglybt.core.download.DownloadManager)6 TOTorrent (com.biglybt.core.torrent.TOTorrent)4 UIFunctions (com.biglybt.ui.UIFunctions)4 File (java.io.File)4 DownloadManagerState (com.biglybt.core.download.DownloadManagerState)3 GlobalManager (com.biglybt.core.global.GlobalManager)3 TOTorrentException (com.biglybt.core.torrent.TOTorrentException)3 Core (com.biglybt.core.Core)2 PEPeerManager (com.biglybt.core.peer.PEPeerManager)2 TRTrackerAnnouncer (com.biglybt.core.tracker.client.TRTrackerAnnouncer)2 IOException (java.io.IOException)2 URL (java.net.URL)2 List (java.util.List)2 CoreRunningListener (com.biglybt.core.CoreRunningListener)1 DownloadManagerInitialisationAdapter (com.biglybt.core.download.DownloadManagerInitialisationAdapter)1 SpeedLimitHandler (com.biglybt.core.speedmanager.SpeedLimitHandler)1 Tag (com.biglybt.core.tag.Tag)1 TOTorrentAnnounceURLSet (com.biglybt.core.torrent.TOTorrentAnnounceURLSet)1