Search in sources :

Example 66 with DownloadManager

use of com.biglybt.core.download.DownloadManager 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 67 with DownloadManager

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

the class TagUIUtils method addLibraryViewTagsSubMenu.

public static void addLibraryViewTagsSubMenu(final DownloadManager[] dms, Menu menu_tags) {
    MenuItem[] items = menu_tags.getItems();
    for (MenuItem item : items) {
        item.dispose();
    }
    final TagManager tm = TagManagerFactory.getTagManager();
    Map<TagType, List<Tag>> auto_map = new HashMap<>();
    TagType manual_tt = tm.getTagType(TagType.TT_DOWNLOAD_MANUAL);
    Map<Tag, Integer> manual_map = new HashMap<>();
    for (DownloadManager dm : dms) {
        List<Tag> tags = tm.getTagsForTaggable(dm);
        for (Tag t : tags) {
            TagType tt = t.getTagType();
            if (tt.isTagTypeAuto() || t.isTagAuto()[0] || t.isTagAuto()[1]) {
                List<Tag> x = auto_map.get(tt);
                if (x == null) {
                    x = new ArrayList<>();
                    auto_map.put(tt, x);
                }
                x.add(t);
            } else if (tt == manual_tt) {
                Integer i = manual_map.get(t);
                manual_map.put(t, i == null ? 1 : i + 1);
            }
        }
    }
    if (auto_map.size() > 0) {
        final Menu menuAuto = new Menu(menu_tags.getShell(), SWT.DROP_DOWN);
        final MenuItem autoItem = new MenuItem(menu_tags, SWT.CASCADE);
        Messages.setLanguageText(autoItem, "wizard.maketorrent.auto");
        autoItem.setMenu(menuAuto);
        List<TagType> auto_tags = sortTagTypes(auto_map.keySet());
        for (TagType tt : auto_tags) {
            MenuItem tt_i = new MenuItem(menuAuto, Constants.isOSX ? SWT.CHECK : SWT.PUSH);
            String tt_str = tt.getTagTypeName(true) + ": ";
            List<Tag> tags = auto_map.get(tt);
            Map<Tag, Integer> tag_counts = new HashMap<>();
            for (Tag t : tags) {
                Integer i = tag_counts.get(t);
                tag_counts.put(t, i == null ? 1 : i + 1);
            }
            tags = sortTags(tag_counts.keySet());
            int num = 0;
            for (Tag t : tags) {
                tt_str += (num == 0 ? "" : ", ") + t.getTagName(true);
                num++;
                if (dms.length > 1) {
                    tt_str += " (" + tag_counts.get(t) + ")";
                }
            }
            tt_i.setText(tt_str);
            if (Constants.isOSX) {
                tt_i.setSelection(true);
            } else {
                Utils.setMenuItemImage(tt_i, "graytick");
            }
        // tt_i.setEnabled(false);
        }
    }
    List<Tag> manual_t = manual_tt.getTags();
    if (manual_t.size() > 0) {
        if (auto_map.size() > 0) {
            new MenuItem(menu_tags, SWT.SEPARATOR);
        }
        List<String> menu_names = new ArrayList<>();
        Map<String, Tag> menu_name_map = new IdentityHashMap<>();
        for (Tag t : manual_t) {
            if (!t.isTagAuto()[0]) {
                String name = t.getTagName(true);
                menu_names.add(name);
                menu_name_map.put(name, t);
            }
        }
        List<Object> menu_structure = MenuBuildUtils.splitLongMenuListIntoHierarchy(menu_names, MAX_TOP_LEVEL_TAGS_IN_MENU);
        for (Object obj : menu_structure) {
            List<Tag> bucket_tags = new ArrayList<>();
            Menu parent_menu;
            if (obj instanceof String) {
                parent_menu = menu_tags;
                bucket_tags.add(menu_name_map.get((String) obj));
            } else {
                Object[] entry = (Object[]) obj;
                List<String> tag_names = (List<String>) entry[1];
                boolean sub_all_selected = true;
                boolean sub_some_selected = false;
                for (String name : tag_names) {
                    Tag sub_tag = menu_name_map.get(name);
                    Integer c = manual_map.get(sub_tag);
                    if (c != null && c == dms.length) {
                        sub_some_selected = true;
                    } else {
                        sub_all_selected = false;
                    }
                    bucket_tags.add(sub_tag);
                }
                String mod;
                if (sub_all_selected) {
                    mod = " (*)";
                } else if (sub_some_selected) {
                    mod = " (+)";
                } else {
                    mod = "";
                }
                Menu menu_bucket = new Menu(menu_tags.getShell(), SWT.DROP_DOWN);
                MenuItem bucket_item = new MenuItem(menu_tags, SWT.CASCADE);
                bucket_item.setText((String) entry[0] + mod);
                bucket_item.setMenu(menu_bucket);
                parent_menu = menu_bucket;
            }
            for (final Tag t : bucket_tags) {
                final MenuItem t_i = new MenuItem(parent_menu, SWT.CHECK);
                String tag_name = t.getTagName(true);
                Integer c = manual_map.get(t);
                if (c != null) {
                    if (c == dms.length) {
                        t_i.setSelection(true);
                        t_i.setText(tag_name);
                    } else {
                        t_i.setText(tag_name + " (" + c + ")");
                    }
                } else {
                    t_i.setText(tag_name);
                }
                t_i.addListener(SWT.Selection, new Listener() {

                    @Override
                    public void handleEvent(Event event) {
                        boolean selected = t_i.getSelection();
                        for (DownloadManager dm : dms) {
                            if (selected) {
                                t.addTaggable(dm);
                            } else {
                                t.removeTaggable(dm);
                            }
                        }
                    }
                });
            }
        }
    }
    new MenuItem(menu_tags, SWT.SEPARATOR);
    MenuItem item_create = new MenuItem(menu_tags, SWT.PUSH);
    Messages.setLanguageText(item_create, "label.add.tag");
    item_create.addListener(SWT.Selection, new Listener() {

        @Override
        public void handleEvent(Event event) {
            createManualTag(new UIFunctions.TagReturner() {

                @Override
                public void returnedTags(Tag[] tags) {
                    if (tags != null) {
                        for (Tag new_tag : tags) {
                            for (DownloadManager dm : dms) {
                                new_tag.addTaggable(dm);
                            }
                            COConfigurationManager.setParameter("Library.TagInSideBar", true);
                        }
                    }
                }
            });
        }
    });
}
Also used : DisposeListener(org.eclipse.swt.events.DisposeListener) MenuItemListener(com.biglybt.pif.ui.menus.MenuItemListener) UserPrompterResultListener(com.biglybt.ui.UserPrompterResultListener) UIInputReceiverListener(com.biglybt.pif.ui.UIInputReceiverListener) CoreRunningListener(com.biglybt.core.CoreRunningListener) TrackerEditorListener(com.biglybt.ui.swt.maketorrent.TrackerEditorListener) DownloadManager(com.biglybt.core.download.DownloadManager) List(java.util.List) DisposeEvent(org.eclipse.swt.events.DisposeEvent)

Example 68 with DownloadManager

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

the class TagUIUtils method showFilesView.

private static void showFilesView(final TagDownload tag) {
    Shell shell = ShellFactory.createShell(Utils.findAnyShell(), SWT.SHELL_TRIM);
    FillLayout fillLayout = new FillLayout();
    fillLayout.marginHeight = 2;
    fillLayout.marginWidth = 2;
    shell.setLayout(fillLayout);
    final FilesView view = new FilesView(false);
    view.setDisableWhenEmpty(false);
    Set<DownloadManager> dms = tag.getTaggedDownloads();
    view.dataSourceChanged(dms.toArray());
    view.initialize(shell);
    view.viewActivated();
    view.refresh();
    final UIUpdatable viewUpdater = new UIUpdatable() {

        @Override
        public void updateUI() {
            view.refresh();
        }

        @Override
        public String getUpdateUIName() {
            return view.getFullTitle();
        }
    };
    UIUpdaterSWT.getInstance().addUpdater(viewUpdater);
    final TagListener tag_listener = new TagListener() {

        @Override
        public void taggableSync(Tag tag) {
        }

        @Override
        public void taggableRemoved(Tag t, Taggable tagged) {
            Set<DownloadManager> dms = tag.getTaggedDownloads();
            view.dataSourceChanged(dms.toArray());
        }

        @Override
        public void taggableAdded(Tag t, Taggable tagged) {
            Set<DownloadManager> dms = tag.getTaggedDownloads();
            view.dataSourceChanged(dms.toArray());
        }
    };
    tag.addTagListener(tag_listener, false);
    shell.addDisposeListener(new DisposeListener() {

        @Override
        public void widgetDisposed(DisposeEvent e) {
            tag.removeTagListener(tag_listener);
            UIUpdaterSWT.getInstance().removeUpdater(viewUpdater);
            view.delete();
        }
    });
    shell.layout(true, true);
    shell.setText(tag.getTagName(true));
    shell.open();
}
Also used : UIUpdatable(com.biglybt.ui.common.updater.UIUpdatable) DisposeListener(org.eclipse.swt.events.DisposeListener) MessageBoxShell(com.biglybt.ui.swt.shells.MessageBoxShell) FilesView(com.biglybt.ui.swt.views.FilesView) FillLayout(org.eclipse.swt.layout.FillLayout) DisposeEvent(org.eclipse.swt.events.DisposeEvent) DownloadManager(com.biglybt.core.download.DownloadManager)

Example 69 with DownloadManager

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

the class CategoryUIUtils method createMenuItems.

public static void createMenuItems(final Menu menu, final Category category) {
    if (category.getType() == Category.TYPE_USER) {
        final MenuItem itemDelete = new MenuItem(menu, SWT.PUSH);
        Messages.setLanguageText(itemDelete, "MyTorrentsView.menu.category.delete");
        itemDelete.addListener(SWT.Selection, new Listener() {

            @Override
            public void handleEvent(Event event) {
                GlobalManager gm = CoreFactory.getSingleton().getGlobalManager();
                List<DownloadManager> managers = category.getDownloadManagers(gm.getDownloadManagers());
                // move to array,since setCategory removed it from the category,
                // which would mess up our loop
                DownloadManager[] dms = managers.toArray(new DownloadManager[managers.size()]);
                for (DownloadManager dm : dms) {
                    DownloadManagerState state = dm.getDownloadState();
                    if (state != null) {
                        state.setCategory(null);
                    }
                }
                CategoryManager.removeCategory(category);
            }
        });
    }
    if (category.getType() != Category.TYPE_ALL) {
        long kInB = DisplayFormatters.getKinB();
        long maxDownload = COConfigurationManager.getIntParameter("Max Download Speed KBs", 0) * kInB;
        long maxUpload = COConfigurationManager.getIntParameter("Max Upload Speed KBs", 0) * kInB;
        int down_speed = category.getDownloadSpeed();
        int up_speed = category.getUploadSpeed();
        ViewUtils.addSpeedMenu(menu.getShell(), menu, true, true, true, true, false, down_speed == 0, down_speed, down_speed, maxDownload, false, up_speed == 0, up_speed, up_speed, maxUpload, 1, null, new SpeedAdapter() {

            @Override
            public void setDownSpeed(int val) {
                category.setDownloadSpeed(val);
            }

            @Override
            public void setUpSpeed(int val) {
                category.setUploadSpeed(val);
            }
        });
    }
    GlobalManager gm = CoreFactory.getSingleton().getGlobalManager();
    List<DownloadManager> managers = category.getDownloadManagers(gm.getDownloadManagers());
    final DownloadManager[] dms = managers.toArray(new DownloadManager[managers.size()]);
    boolean start = false;
    boolean stop = false;
    for (DownloadManager dm : dms) {
        stop = stop || ManagerUtils.isStopable(dm);
        start = start || ManagerUtils.isStartable(dm);
    }
    // Queue
    final MenuItem itemQueue = new MenuItem(menu, SWT.PUSH);
    Messages.setLanguageText(itemQueue, "MyTorrentsView.menu.queue");
    Utils.setMenuItemImage(itemQueue, "start");
    itemQueue.addListener(SWT.Selection, new Listener() {

        @Override
        public void handleEvent(Event event) {
            GlobalManager gm = CoreFactory.getSingleton().getGlobalManager();
            List<?> managers = category.getDownloadManagers(gm.getDownloadManagers());
            Object[] dms = managers.toArray();
            TorrentUtil.queueDataSources(dms, true);
        }
    });
    itemQueue.setEnabled(start);
    // 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) {
            GlobalManager gm = CoreFactory.getSingleton().getGlobalManager();
            List<?> managers = category.getDownloadManagers(gm.getDownloadManagers());
            Object[] dms = managers.toArray();
            TorrentUtil.stopDataSources(dms);
        }
    });
    itemStop.setEnabled(stop);
    if (category.canBePublic()) {
        new MenuItem(menu, SWT.SEPARATOR);
        final MenuItem itemPublic = new MenuItem(menu, SWT.CHECK);
        itemPublic.setSelection(category.isPublic());
        Messages.setLanguageText(itemPublic, "cat.share");
        itemPublic.addListener(SWT.Selection, new Listener() {

            @Override
            public void handleEvent(Event event) {
                category.setPublic(itemPublic.getSelection());
            }
        });
    }
    // share with friends
    PluginInterface bpi = PluginInitializer.getDefaultInterface().getPluginManager().getPluginInterfaceByClass(BuddyPlugin.class);
    int cat_type = category.getType();
    if (bpi != null && cat_type != Category.TYPE_UNCATEGORIZED) {
        final BuddyPlugin buddy_plugin = (BuddyPlugin) bpi.getPlugin();
        if (buddy_plugin.isClassicEnabled()) {
            final Menu share_menu = new Menu(menu.getShell(), SWT.DROP_DOWN);
            final MenuItem share_item = new MenuItem(menu, SWT.CASCADE);
            Messages.setLanguageText(share_item, "azbuddy.ui.menu.cat.share");
            share_item.setMenu(share_menu);
            List<BuddyPluginBuddy> buddies = buddy_plugin.getBuddies();
            if (buddies.size() == 0) {
                final MenuItem item = new MenuItem(share_menu, SWT.CHECK);
                item.setText(MessageText.getString("general.add.friends"));
                item.setEnabled(false);
            } else {
                final String cname;
                if (cat_type == Category.TYPE_ALL) {
                    cname = "All";
                } else {
                    cname = category.getName();
                }
                final boolean is_public = buddy_plugin.isPublicTagOrCategory(cname);
                final MenuItem itemPubCat = new MenuItem(share_menu, SWT.CHECK);
                Messages.setLanguageText(itemPubCat, "general.all.friends");
                itemPubCat.setSelection(is_public);
                itemPubCat.addListener(SWT.Selection, new Listener() {

                    @Override
                    public void handleEvent(Event event) {
                        if (is_public) {
                            buddy_plugin.removePublicTagOrCategory(cname);
                        } else {
                            buddy_plugin.addPublicTagOrCategory(cname);
                        }
                    }
                });
                new MenuItem(share_menu, SWT.SEPARATOR);
                for (final BuddyPluginBuddy buddy : buddies) {
                    if (buddy.getNickName() == null) {
                        continue;
                    }
                    final boolean auth = buddy.isLocalRSSTagOrCategoryAuthorised(cname);
                    final MenuItem itemShare = new MenuItem(share_menu, SWT.CHECK);
                    itemShare.setText(buddy.getName());
                    itemShare.setSelection(auth || is_public);
                    if (is_public) {
                        itemShare.setEnabled(false);
                    }
                    itemShare.addListener(SWT.Selection, new Listener() {

                        @Override
                        public void handleEvent(Event event) {
                            if (auth) {
                                buddy.removeLocalAuthorisedRSSTagOrCategory(cname);
                            } else {
                                buddy.addLocalAuthorisedRSSTagOrCategory(cname);
                            }
                        }
                    });
                }
            }
        }
    }
    if (category.getType() != Category.TYPE_ALL) {
        TrancodeUIUtils.TranscodeTarget[] tts = TrancodeUIUtils.getTranscodeTargets();
        if (tts.length > 0) {
            final Menu t_menu = new Menu(menu.getShell(), SWT.DROP_DOWN);
            final MenuItem t_item = new MenuItem(menu, SWT.CASCADE);
            Messages.setLanguageText(t_item, "cat.autoxcode");
            t_item.setMenu(t_menu);
            String existing = category.getStringAttribute(Category.AT_AUTO_TRANSCODE_TARGET);
            for (TrancodeUIUtils.TranscodeTarget tt : tts) {
                TrancodeUIUtils.TranscodeProfile[] profiles = tt.getProfiles();
                if (profiles.length > 0) {
                    final Menu tt_menu = new Menu(t_menu.getShell(), SWT.DROP_DOWN);
                    final MenuItem tt_item = new MenuItem(t_menu, SWT.CASCADE);
                    tt_item.setText(tt.getName());
                    tt_item.setMenu(tt_menu);
                    for (final TrancodeUIUtils.TranscodeProfile tp : profiles) {
                        final MenuItem p_item = new MenuItem(tt_menu, SWT.CHECK);
                        p_item.setText(tp.getName());
                        boolean selected = existing != null && existing.equals(tp.getUID());
                        if (selected) {
                            Utils.setMenuItemImage(tt_item, "blacktick");
                        }
                        p_item.setSelection(selected);
                        p_item.addListener(SWT.Selection, new Listener() {

                            @Override
                            public void handleEvent(Event event) {
                                category.setStringAttribute(Category.AT_AUTO_TRANSCODE_TARGET, p_item.getSelection() ? tp.getUID() : null);
                            }
                        });
                    }
                }
            }
        }
    }
    // rss feed
    final MenuItem rssOption = new MenuItem(menu, SWT.CHECK);
    rssOption.setSelection(category.getBooleanAttribute(Category.AT_RSS_GEN));
    Messages.setLanguageText(rssOption, "cat.rss.gen");
    rssOption.addListener(SWT.Selection, new Listener() {

        @Override
        public void handleEvent(Event event) {
            boolean set = rssOption.getSelection();
            category.setBooleanAttribute(Category.AT_RSS_GEN, set);
        }
    });
    if (cat_type != Category.TYPE_UNCATEGORIZED && cat_type != Category.TYPE_ALL) {
        final MenuItem upPriority = new MenuItem(menu, SWT.CHECK);
        upPriority.setSelection(category.getIntAttribute(Category.AT_UPLOAD_PRIORITY) > 0);
        Messages.setLanguageText(upPriority, "cat.upload.priority");
        upPriority.addListener(SWT.Selection, new Listener() {

            @Override
            public void handleEvent(Event event) {
                boolean set = upPriority.getSelection();
                category.setIntAttribute(Category.AT_UPLOAD_PRIORITY, set ? 1 : 0);
            }
        });
    }
    // options
    MenuItem itemOptions = new MenuItem(menu, SWT.PUSH);
    Messages.setLanguageText(itemOptions, "cat.options");
    itemOptions.addListener(SWT.Selection, new Listener() {

        @Override
        public void handleEvent(Event event) {
            UIFunctions uiFunctions = UIFunctionsManager.getUIFunctions();
            if (uiFunctions != null) {
                MultipleDocumentInterface mdi = uiFunctions.getMDI();
                if (mdi != null) {
                    mdi.showEntryByID(MultipleDocumentInterface.SIDEBAR_SECTION_TORRENT_OPTIONS, dms);
                }
            }
        }
    });
    if (dms.length == 0) {
        itemOptions.setEnabled(false);
    }
}
Also used : Listener(org.eclipse.swt.widgets.Listener) UIInputReceiverListener(com.biglybt.pif.ui.UIInputReceiverListener) MenuListener(org.eclipse.swt.events.MenuListener) DownloadManager(com.biglybt.core.download.DownloadManager) DownloadManagerState(com.biglybt.core.download.DownloadManagerState) BuddyPlugin(com.biglybt.plugin.net.buddy.BuddyPlugin) SpeedAdapter(com.biglybt.ui.swt.views.ViewUtils.SpeedAdapter) GlobalManager(com.biglybt.core.global.GlobalManager) UIFunctions(com.biglybt.ui.UIFunctions) List(java.util.List) Menu(org.eclipse.swt.widgets.Menu) PluginInterface(com.biglybt.pif.PluginInterface) MenuItem(org.eclipse.swt.widgets.MenuItem) MultipleDocumentInterface(com.biglybt.ui.mdi.MultipleDocumentInterface) BuddyPluginBuddy(com.biglybt.plugin.net.buddy.BuddyPluginBuddy) Event(org.eclipse.swt.widgets.Event) MenuEvent(org.eclipse.swt.events.MenuEvent)

Example 70 with DownloadManager

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

the class TorrentFolderWatcher method importAddedFiles.

void importAddedFiles() {
    Core core = CoreFactory.getSingleton();
    try {
        this_mon.enter();
        if (!running) {
            return;
        }
        GlobalManager global_manager = _global_manager;
        if (global_manager == null || !core.isStarted()) {
            return;
        }
        com.biglybt.pif.download.DownloadManager plugin_dm = core.getPluginManager().getDefaultPluginInterface().getDownloadManager();
        boolean save_torrents_default = COConfigurationManager.getBooleanParameter("Save Torrent Files");
        String torrent_save_path = COConfigurationManager.getStringParameter("General_sDefaultTorrent_Directory");
        int start_state = COConfigurationManager.getBooleanParameter("Start Watched Torrents Stopped") ? DownloadManager.STATE_STOPPED : DownloadManager.STATE_QUEUED;
        int num_folders = COConfigurationManager.getIntParameter("Watch Torrent Folder Path Count", 1);
        List<File> folders = new ArrayList<>();
        List<String> tags = new ArrayList<>();
        for (int i = 0; i < num_folders; i++) {
            String folder_path = COConfigurationManager.getStringParameter("Watch Torrent Folder Path" + (i == 0 ? "" : (" " + i)));
            File folder = null;
            if (folder_path != null && folder_path.length() > 0) {
                folder = new File(folder_path);
                if (!folder.isDirectory()) {
                    if (!folder.exists()) {
                        FileUtil.mkdirs(folder);
                    }
                    if (!folder.isDirectory()) {
                        if (Logger.isEnabled())
                            Logger.log(new LogEvent(LOGID, LogEvent.LT_ERROR, "[Watch Torrent Folder Path] " + "does not exist or " + "is not a dir"));
                        folder = null;
                    }
                }
            }
            if (folder != null) {
                folders.add(folder);
                String tag = COConfigurationManager.getStringParameter("Watch Torrent Folder Tag" + (i == 0 ? "" : (" " + i)), null);
                if (tag != null && tag.trim().length() == 0) {
                    tag = null;
                }
                tags.add(tag);
            }
        }
        if (folders.isEmpty()) {
            if (Logger.isEnabled())
                Logger.log(new LogEvent(LOGID, LogEvent.LT_ERROR, "[Watch Torrent Folder Path] not configured"));
            return;
        }
        String data_save_path = COConfigurationManager.getStringParameter("Default save path");
        File f = null;
        if (data_save_path != null && data_save_path.length() > 0) {
            f = new File(data_save_path);
            // Path is not an existing directory.
            if (!f.isDirectory()) {
                if (!f.exists()) {
                    FileUtil.mkdirs(f);
                }
                // If path is still not a directory, abort.
                if (!f.isDirectory()) {
                    if (Logger.isEnabled()) {
                        Logger.log(new LogEvent(LOGID, LogEvent.LT_ERROR, "[Default save path] does not exist or is not a dir"));
                    }
                    Logger.log(new LogAlert(LogAlert.UNREPEATABLE, LogAlert.AT_ERROR, "[Default save path] does not exist or is not a dir"));
                    return;
                }
            }
        }
        // If we get here, and this is true, then data_save_path isn't valid.
        if (f == null) {
            if (Logger.isEnabled()) {
                Logger.log(new LogEvent(LOGID, LogEvent.LT_ERROR, "[Default save path] needs to be set for auto-.torrent-import to work"));
            }
            Logger.log(new LogAlert(LogAlert.UNREPEATABLE, LogAlert.AT_ERROR, "[Default save path] needs to be set for auto-.torrent-import to work"));
        }
        for (int i = 0; i < to_delete.size(); i++) {
            TOTorrent torrent = (TOTorrent) to_delete.get(i);
            try {
                TorrentUtils.delete(torrent);
            } catch (Throwable e) {
                Debug.printStackTrace(e);
            }
        }
        to_delete.clear();
        for (int folder_index = 0; folder_index < folders.size(); folder_index++) {
            File folder = folders.get(folder_index);
            final String tag_name = tags.get(folder_index);
            // if we are saving torrents to the same location as we import them from
            // then we can't assume that its safe to delete the torrent after import!
            boolean save_torrents = save_torrents_default;
            if (torrent_save_path.length() == 0 || new File(torrent_save_path).getAbsolutePath().equals(folder.getAbsolutePath()) || !new File(torrent_save_path).isDirectory()) {
                save_torrents = false;
            }
            String[] currentFileList = folder.list(filename_filter);
            if (currentFileList == null) {
                Logger.log(new LogEvent(LOGID, LogEvent.LT_ERROR, "There was a problem trying to get a listing of torrents from " + folder));
            } else {
                for (int i = 0; i < currentFileList.length; i++) {
                    if (!running) {
                        return;
                    }
                    File file = new File(folder, currentFileList[i]);
                    if (file.getName().toLowerCase(Locale.US).endsWith(".magnet")) {
                        handleMagnet(file);
                    } else {
                        try {
                            TOTorrent torrent = TorrentUtils.readFromFile(file, false);
                            if (global_manager.getDownloadManager(torrent) != null) {
                                if (Logger.isEnabled())
                                    Logger.log(new LogEvent(LOGID, file.getAbsolutePath() + " is already being downloaded"));
                            // we can't touch the torrent file as it is (probably)
                            // being used for the download
                            } else if (plugin_dm.lookupDownloadStub(torrent.getHash()) != null) {
                                if (Logger.isEnabled())
                                    Logger.log(new LogEvent(LOGID, file.getAbsolutePath() + " is an archived download"));
                                if (!save_torrents) {
                                    File imported = new File(folder, file.getName() + ".imported");
                                    TorrentUtils.move(file, imported);
                                } else {
                                    to_delete.add(torrent);
                                }
                            } else {
                                final DownloadManagerInitialisationAdapter dmia = new DownloadManagerInitialisationAdapter() {

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

                                    @Override
                                    public void initialised(DownloadManager dm, boolean for_seeding) {
                                        if (tag_name != null) {
                                            TagManager tm = TagManagerFactory.getTagManager();
                                            TagType tt = tm.getTagType(TagType.TT_DOWNLOAD_MANUAL);
                                            Tag tag = tt.getTag(tag_name, true);
                                            try {
                                                if (tag == null) {
                                                    tag = tt.createTag(tag_name, true);
                                                }
                                                tag.addTaggable(dm);
                                            } catch (Throwable e) {
                                                Debug.out(e);
                                            }
                                        }
                                    }
                                };
                                byte[] hash = null;
                                try {
                                    hash = torrent.getHash();
                                } catch (Exception e) {
                                }
                                if (!save_torrents) {
                                    File imported = new File(folder, file.getName() + ".imported");
                                    TorrentUtils.move(file, imported);
                                    global_manager.addDownloadManager(imported.getAbsolutePath(), hash, data_save_path, start_state, true, false, dmia);
                                } else {
                                    global_manager.addDownloadManager(file.getAbsolutePath(), hash, data_save_path, start_state, true, false, dmia);
                                    // add torrent for deletion, since there will be a
                                    // saved copy elsewhere
                                    to_delete.add(torrent);
                                }
                                if (Logger.isEnabled())
                                    Logger.log(new LogEvent(LOGID, "Auto-imported " + file.getAbsolutePath()));
                            }
                        } catch (Throwable e) {
                            Debug.out("Failed to auto-import torrent file '" + file.getAbsolutePath() + "' - " + Debug.getNestedExceptionMessage(e));
                            Debug.printStackTrace(e);
                        }
                    }
                }
            }
        }
    } finally {
        this_mon.exit();
    }
}
Also used : LogEvent(com.biglybt.core.logging.LogEvent) ArrayList(java.util.ArrayList) DownloadManagerInitialisationAdapter(com.biglybt.core.download.DownloadManagerInitialisationAdapter) DownloadManager(com.biglybt.core.download.DownloadManager) LogAlert(com.biglybt.core.logging.LogAlert) TagType(com.biglybt.core.tag.TagType) TagManager(com.biglybt.core.tag.TagManager) GlobalManager(com.biglybt.core.global.GlobalManager) TOTorrent(com.biglybt.core.torrent.TOTorrent) Tag(com.biglybt.core.tag.Tag) File(java.io.File) Core(com.biglybt.core.Core)

Aggregations

DownloadManager (com.biglybt.core.download.DownloadManager)307 DiskManagerFileInfo (com.biglybt.core.disk.DiskManagerFileInfo)54 TOTorrent (com.biglybt.core.torrent.TOTorrent)35 GlobalManager (com.biglybt.core.global.GlobalManager)33 PEPeerManager (com.biglybt.core.peer.PEPeerManager)29 File (java.io.File)29 List (java.util.List)21 Core (com.biglybt.core.Core)17 Download (com.biglybt.pif.download.Download)17 Point (org.eclipse.swt.graphics.Point)17 UIFunctions (com.biglybt.ui.UIFunctions)16 Tag (com.biglybt.core.tag.Tag)15 UIInputReceiverListener (com.biglybt.pif.ui.UIInputReceiverListener)14 TOTorrentException (com.biglybt.core.torrent.TOTorrentException)13 ArrayList (java.util.ArrayList)13 DiskManager (com.biglybt.core.disk.DiskManager)12 DownloadManagerStats (com.biglybt.core.download.DownloadManagerStats)12 CoreRunningListener (com.biglybt.core.CoreRunningListener)11 DownloadManagerState (com.biglybt.core.download.DownloadManagerState)11 PEPeer (com.biglybt.core.peer.PEPeer)11