Search in sources :

Example 36 with Download

use of com.biglybt.pif.download.Download in project BiglyBT by BiglySoftware.

the class TagManagerImpl method evalScript.

protected Object evalScript(Tag tag, String script, DownloadManager dm, String intent_key) {
    String script_type = "";
    if (script.length() >= 10 && script.substring(0, 10).toLowerCase(Locale.US).startsWith("javascript")) {
        int p1 = script.indexOf('(');
        int p2 = script.lastIndexOf(')');
        if (p1 != -1 && p2 != -1) {
            script = script.substring(p1 + 1, p2).trim();
            if (script.startsWith("\"") && script.endsWith("\"")) {
                script = script.substring(1, script.length() - 1);
            }
            // allow people to escape " if it makes them feel better
            script = script.replaceAll("\\\\\"", "\"");
            script_type = ScriptProvider.ST_JAVASCRIPT;
        }
    }
    if (script_type == "") {
        Debug.out("Unrecognised script type: " + script);
        return (null);
    }
    boolean provider_found = false;
    List<ScriptProvider> providers = CoreFactory.getSingleton().getPluginManager().getDefaultPluginInterface().getUtilities().getScriptProviders();
    for (ScriptProvider p : providers) {
        if (p.getScriptType() == script_type) {
            provider_found = true;
            Download plugin_dm = PluginCoreUtils.wrap(dm);
            if (plugin_dm == null) {
                // deleted in the meantime
                return (null);
            }
            Map<String, Object> bindings = new HashMap<>();
            String dm_name = dm.getDisplayName();
            if (dm_name.length() > 32) {
                dm_name = dm_name.substring(0, 29) + "...";
            }
            String intent = intent_key + "(\"" + tag.getTagName() + "\",\"" + dm_name + "\")";
            bindings.put("intent", intent);
            bindings.put("download", plugin_dm);
            bindings.put("tag", tag);
            try {
                Object result = p.eval(script, bindings);
                return (result);
            } catch (Throwable e) {
                Debug.out(e);
                return (null);
            }
        }
    }
    if (!provider_found) {
        if (!js_plugin_install_tried) {
            js_plugin_install_tried = true;
            PluginUtils.installJavaScriptPlugin();
        }
    }
    return (null);
}
Also used : ScriptProvider(com.biglybt.pif.utils.ScriptProvider) Download(com.biglybt.pif.download.Download)

Example 37 with Download

use of com.biglybt.pif.download.Download in project BiglyBT by BiglySoftware.

the class MagnetPluginMDDownloader method startSupport.

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

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

                    private PeerManagerListener2 pm_listener = this;

                    private int md_size;

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

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

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

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

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

            private Object lock = this;

            private TimerEventPeriodic timer_event;

            private boolean removed;

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

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

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

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

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

Example 38 with Download

use of com.biglybt.pif.download.Download in project BiglyBT by BiglySoftware.

the class MainMDISetup method setupSideBar.

public static void setupSideBar(final MultipleDocumentInterfaceSWT mdi, final MdiListener l) {
    if (Utils.isAZ2UI()) {
        setupSidebarClassic(mdi);
    } else {
        setupSidebarVuzeUI(mdi);
    }
    SBC_TorrentDetailsView.TorrentDetailMdiEntry.register(mdi);
    PluginInterface pi = PluginInitializer.getDefaultInterface();
    pi.getUIManager().addUIListener(new UIManagerListener2() {

        @Override
        public void UIDetached(UIInstance instance) {
        }

        @Override
        public void UIAttached(UIInstance instance) {
        }

        @Override
        public void UIAttachedComplete(UIInstance instance) {
            PluginInitializer.getDefaultInterface().getUIManager().removeUIListener(this);
            MdiEntry currentEntry = mdi.getCurrentEntry();
            if (currentEntry != null) {
                // User or another plugin selected an entry
                return;
            }
            final String CFG_STARTTAB = "v3.StartTab";
            final String CFG_STARTTAB_DS = "v3.StartTab.ds";
            String startTab;
            String datasource = null;
            boolean showWelcome = false;
            if (showWelcome) {
                startTab = SideBar.SIDEBAR_SECTION_WELCOME;
            } else {
                if (!COConfigurationManager.hasParameter(CFG_STARTTAB, true)) {
                    COConfigurationManager.setParameter(CFG_STARTTAB, SideBar.SIDEBAR_SECTION_LIBRARY);
                }
                startTab = COConfigurationManager.getStringParameter(CFG_STARTTAB);
                datasource = COConfigurationManager.getStringParameter(CFG_STARTTAB_DS, null);
            }
            if (!mdi.loadEntryByID(startTab, true, false, datasource)) {
                mdi.showEntryByID(SideBar.SIDEBAR_SECTION_LIBRARY);
            }
            if (l != null) {
                mdi.addListener(l);
            }
        }
    });
    configBetaEnabledListener = new ParameterListener() {

        @Override
        public void parameterChanged(String parameterName) {
            boolean enabled = COConfigurationManager.getBooleanParameter("Beta Programme Enabled");
            if (enabled) {
                boolean closed = COConfigurationManager.getBooleanParameter("Beta Programme Sidebar Closed");
                if (!closed) {
                    mdi.loadEntryByID(MultipleDocumentInterface.SIDEBAR_SECTION_BETAPROGRAM, false);
                }
            }
        }
    };
    COConfigurationManager.addAndFireParameterListener("Beta Programme Enabled", configBetaEnabledListener);
    mdi.registerEntry(StatsView.VIEW_ID, new MdiEntryCreationListener() {

        @Override
        public MdiEntry createMDiEntry(String id) {
            MdiEntry entry = mdi.createEntryFromEventListener(MultipleDocumentInterface.SIDEBAR_HEADER_PLUGINS, new StatsView(), id, true, null, null);
            return entry;
        }
    });
    mdi.registerEntry(MultipleDocumentInterface.SIDEBAR_SECTION_ALLPEERS, new MdiEntryCreationListener() {

        @Override
        public MdiEntry createMDiEntry(String id) {
            MdiEntry entry = mdi.createEntryFromEventListener(MultipleDocumentInterface.SIDEBAR_HEADER_TRANSFERS, new PeersSuperView(), id, true, null, null);
            entry.setImageLeftID("image.sidebar.allpeers");
            return entry;
        }
    });
    mdi.registerEntry(MultipleDocumentInterface.SIDEBAR_SECTION_LOGGER, new MdiEntryCreationListener() {

        @Override
        public MdiEntry createMDiEntry(String id) {
            MdiEntry entry = mdi.createEntryFromEventListener(MultipleDocumentInterface.SIDEBAR_HEADER_PLUGINS, new LoggerView(), id, true, null, null);
            return entry;
        }
    });
    mdi.registerEntry(MultipleDocumentInterface.SIDEBAR_SECTION_TAGS, new MdiEntryCreationListener() {

        @Override
        public MdiEntry createMDiEntry(String id) {
            MdiEntry entry = mdi.createEntryFromSkinRef(MultipleDocumentInterface.SIDEBAR_HEADER_TRANSFERS, id, "tagsview", "{tags.view.heading}", null, null, true, null);
            entry.setImageLeftID("image.sidebar.tag-overview");
            entry.setDefaultExpanded(true);
            return entry;
        }
    });
    mdi.registerEntry(MultipleDocumentInterface.SIDEBAR_SECTION_TAG_DISCOVERY, new MdiEntryCreationListener() {

        @Override
        public MdiEntry createMDiEntry(String id) {
            MdiEntry entry = mdi.createEntryFromSkinRef(MultipleDocumentInterface.SIDEBAR_SECTION_TAGS, id, "tagdiscoveryview", "{mdi.entry.tagdiscovery}", null, null, true, null);
            entry.setImageLeftID("image.sidebar.tag-overview");
            return entry;
        }
    });
    mdi.registerEntry(MultipleDocumentInterface.SIDEBAR_SECTION_CHAT, new MdiEntryCreationListener() {

        @Override
        public MdiEntry createMDiEntry(String id) {
            final ViewTitleInfo title_info = new ViewTitleInfo() {

                @Override
                public Object getTitleInfoProperty(int propertyID) {
                    BuddyPluginBeta bp = BuddyPluginUtils.getBetaPlugin();
                    if (bp == null) {
                        return (null);
                    }
                    if (propertyID == TITLE_INDICATOR_TEXT) {
                        int num = 0;
                        for (ChatInstance chat : bp.getChats()) {
                            if (chat.getMessageOutstanding()) {
                                num++;
                            }
                        }
                        if (num > 0) {
                            return (String.valueOf(num));
                        } else {
                            return (null);
                        }
                    } else if (propertyID == TITLE_INDICATOR_COLOR) {
                        for (ChatInstance chat : bp.getChats()) {
                            if (chat.getMessageOutstanding()) {
                                if (chat.hasUnseenMessageWithNick()) {
                                    return (SBC_ChatOverview.COLOR_MESSAGE_WITH_NICK);
                                }
                            }
                        }
                    }
                    return null;
                }
            };
            MdiEntry mdi_entry = mdi.createEntryFromSkinRef(MultipleDocumentInterface.SIDEBAR_HEADER_DISCOVERY, MultipleDocumentInterface.SIDEBAR_SECTION_CHAT, "chatsview", "{mdi.entry.chatsoverview}", title_info, null, true, null);
            mdi_entry.setImageLeftID("image.sidebar.chat-overview");
            final TimerEventPeriodic timer = SimpleTimer.addPeriodicEvent("sb:chatup", 5 * 1000, new TimerEventPerformer() {

                private String last_text;

                private int[] last_colour;

                @Override
                public void perform(TimerEvent event) {
                    String text = (String) title_info.getTitleInfoProperty(ViewTitleInfo.TITLE_INDICATOR_TEXT);
                    int[] colour = (int[]) title_info.getTitleInfoProperty(ViewTitleInfo.TITLE_INDICATOR_COLOR);
                    boolean changed = text != last_text && (text == null || last_text == null || !text.equals(last_text));
                    if (!changed) {
                        changed = colour != last_colour && (colour == null || last_colour == null || !Arrays.equals(colour, last_colour));
                    }
                    if (changed) {
                        last_text = text;
                        last_colour = colour;
                        mdi_entry.redraw();
                    }
                    ViewTitleInfoManager.refreshTitleInfo(title_info);
                }
            });
            mdi_entry.addListener(new MdiCloseListener() {

                @Override
                public void mdiEntryClosed(MdiEntry entry, boolean userClosed) {
                    timer.cancel();
                }
            });
            return mdi_entry;
        }
    });
    mdi.registerEntry(MultipleDocumentInterface.SIDEBAR_SECTION_ARCHIVED_DOWNLOADS, new MdiEntryCreationListener() {

        @Override
        public MdiEntry createMDiEntry(String id) {
            final com.biglybt.pif.download.DownloadManager download_manager = PluginInitializer.getDefaultInterface().getDownloadManager();
            final ViewTitleInfo title_info = new ViewTitleInfo() {

                @Override
                public Object getTitleInfoProperty(int propertyID) {
                    if (propertyID == TITLE_INDICATOR_TEXT) {
                        int num = download_manager.getDownloadStubCount();
                        return (String.valueOf(num));
                    }
                    return null;
                }
            };
            MdiEntry entry = mdi.createEntryFromSkinRef(MultipleDocumentInterface.SIDEBAR_HEADER_TRANSFERS, MultipleDocumentInterface.SIDEBAR_SECTION_ARCHIVED_DOWNLOADS, "archivedlsview", "{mdi.entry.archiveddownloadsview}", title_info, null, true, null);
            entry.setImageLeftID("image.sidebar.archive");
            final DownloadStubListener stub_listener = new DownloadStubListener() {

                @Override
                public void downloadStubEventOccurred(DownloadStubEvent event) {
                    ViewTitleInfoManager.refreshTitleInfo(title_info);
                }
            };
            download_manager.addDownloadStubListener(stub_listener, false);
            entry.addListener(new MdiCloseListener() {

                @Override
                public void mdiEntryClosed(MdiEntry entry, boolean userClosed) {
                    download_manager.removeDownloadStubListener(stub_listener);
                }
            });
            entry.addListener(new MdiEntryDropListener() {

                @Override
                public boolean mdiEntryDrop(MdiEntry entry, Object data) {
                    if (data instanceof String) {
                        String str = (String) data;
                        if (str.startsWith("DownloadManager\n")) {
                            String[] bits = str.split("\n");
                            com.biglybt.pif.download.DownloadManager dm = PluginInitializer.getDefaultInterface().getDownloadManager();
                            List<Download> downloads = new ArrayList<>();
                            boolean failed = false;
                            for (int i = 1; i < bits.length; i++) {
                                byte[] hash = Base32.decode(bits[i]);
                                try {
                                    Download download = dm.getDownload(hash);
                                    if (download.canStubbify()) {
                                        downloads.add(download);
                                    } else {
                                        failed = true;
                                    }
                                } catch (Throwable e) {
                                }
                            }
                            final boolean f_failed = failed;
                            ManagerUtils.moveToArchive(downloads, new ManagerUtils.ArchiveCallback() {

                                boolean error = f_failed;

                                @Override
                                public void failed(DownloadStub original, Throwable e) {
                                    error = true;
                                }

                                @Override
                                public void completed() {
                                    if (error) {
                                        String title = MessageText.getString("archive.failed.title");
                                        String text = MessageText.getString("archive.failed.text");
                                        MessageBoxShell prompter = new MessageBoxShell(title, text, new String[] { MessageText.getString("Button.ok") }, 0);
                                        prompter.setAutoCloseInMS(0);
                                        prompter.open(null);
                                    }
                                }
                            });
                        }
                        return (true);
                    }
                    return false;
                }
            });
            return entry;
        }
    });
    // download history
    mdi.registerEntry(MultipleDocumentInterface.SIDEBAR_SECTION_DOWNLOAD_HISTORY, new MdiEntryCreationListener() {

        @Override
        public MdiEntry createMDiEntry(String id) {
            final DownloadHistoryManager history_manager = (DownloadHistoryManager) CoreFactory.getSingleton().getGlobalManager().getDownloadHistoryManager();
            final ViewTitleInfo title_info = new ViewTitleInfo() {

                @Override
                public Object getTitleInfoProperty(int propertyID) {
                    if (propertyID == TITLE_INDICATOR_TEXT) {
                        if (history_manager == null) {
                            return (null);
                        } else if (history_manager.isEnabled()) {
                            int num = history_manager.getHistoryCount();
                            return (String.valueOf(num));
                        } else {
                            return (MessageText.getString("label.disabled"));
                        }
                    }
                    return null;
                }
            };
            MdiEntry entry = mdi.createEntryFromSkinRef(MultipleDocumentInterface.SIDEBAR_HEADER_TRANSFERS, MultipleDocumentInterface.SIDEBAR_SECTION_DOWNLOAD_HISTORY, "downloadhistoryview", "{mdi.entry.downloadhistoryview}", title_info, null, true, null);
            entry.setImageLeftID("image.sidebar.logview");
            if (history_manager != null) {
                final DownloadHistoryListener history_listener = new DownloadHistoryListener() {

                    @Override
                    public void downloadHistoryEventOccurred(DownloadHistoryEvent event) {
                        ViewTitleInfoManager.refreshTitleInfo(title_info);
                    }
                };
                history_manager.addListener(history_listener, false);
                entry.addListener(new MdiCloseListener() {

                    @Override
                    public void mdiEntryClosed(MdiEntry entry, boolean userClosed) {
                        history_manager.removeListener(history_listener);
                    }
                });
            }
            return entry;
        }
    });
    // torrent options
    mdi.registerEntry(MultipleDocumentInterface.SIDEBAR_SECTION_TORRENT_OPTIONS, new MdiEntryCreationListener() {

        @Override
        public MdiEntry createMDiEntry(String id) {
            MdiEntry entry = mdi.createEntryFromEventListener(MultipleDocumentInterface.SIDEBAR_HEADER_TRANSFERS, TorrentOptionsView.class, MultipleDocumentInterface.SIDEBAR_SECTION_TORRENT_OPTIONS, true, null, null);
            entry.setImageLeftID("image.sidebar.torrentoptions");
            return entry;
        }
    });
    mdi.registerEntry(MultipleDocumentInterface.SIDEBAR_SECTION_MY_SHARES, new MdiEntryCreationListener() {

        @Override
        public MdiEntry createMDiEntry(String id) {
            MdiEntry entry = mdi.createEntryFromEventListener(MultipleDocumentInterface.SIDEBAR_HEADER_TRANSFERS, MySharesView.class, MultipleDocumentInterface.SIDEBAR_SECTION_MY_SHARES, true, null, null);
            entry.setImageLeftID("image.sidebar.myshares");
            return entry;
        }
    });
    mdi.registerEntry(MultipleDocumentInterface.SIDEBAR_SECTION_MY_TRACKER, new MdiEntryCreationListener() {

        @Override
        public MdiEntry createMDiEntry(String id) {
            MdiEntry entry = mdi.createEntryFromEventListener(MultipleDocumentInterface.SIDEBAR_HEADER_TRANSFERS, MyTrackerView.class, MultipleDocumentInterface.SIDEBAR_SECTION_MY_TRACKER, true, null, null);
            entry.setImageLeftID("image.sidebar.mytracker");
            return entry;
        }
    });
    mdi.registerEntry(MultipleDocumentInterface.SIDEBAR_SECTION_CLIENT_STATS, new MdiEntryCreationListener() {

        @Override
        public MdiEntry createMDiEntry(String id) {
            MdiEntry entry = mdi.createEntryFromEventListener(MultipleDocumentInterface.SIDEBAR_HEADER_PLUGINS, ClientStatsView.class, MultipleDocumentInterface.SIDEBAR_SECTION_CLIENT_STATS, true, null, null);
            entry.setImageLeftID("image.sidebar.clientstats");
            return entry;
        }
    });
    mdi.registerEntry(MultipleDocumentInterface.SIDEBAR_SECTION_CONFIG, new MdiEntryCreationListener2() {

        @Override
        public MdiEntry createMDiEntry(MultipleDocumentInterface mdi, String id, Object datasource, Map<?, ?> params) {
            String section = (datasource instanceof String) ? ((String) datasource) : null;
            boolean uiClassic = COConfigurationManager.getStringParameter("ui").equals("az2");
            if (uiClassic || COConfigurationManager.getBooleanParameter("Show Options In Side Bar")) {
                MdiEntry entry = ((MultipleDocumentInterfaceSWT) mdi).createEntryFromEventListener(MultipleDocumentInterface.SIDEBAR_HEADER_PLUGINS, ConfigView.class, MultipleDocumentInterface.SIDEBAR_SECTION_CONFIG, true, null, null);
                entry.setImageLeftID("image.sidebar.config");
                return entry;
            }
            ConfigShell.getInstance().open(section);
            return null;
        }
    });
    try {
        if (!COConfigurationManager.getBooleanParameter("my.shares.view.auto.open.done", false)) {
            final ShareManager share_manager = pi.getShareManager();
            if (share_manager.getShares().length > 0) {
            // stop showing this by default
            // mdi.showEntryByID(MultipleDocumentInterface.SIDEBAR_SECTION_MY_SHARES);
            } else {
                shareManagerListener = new ShareManagerListener() {

                    boolean done = false;

                    @Override
                    public void resourceModified(ShareResource old_resource, ShareResource new_resource) {
                    }

                    @Override
                    public void resourceDeleted(ShareResource resource) {
                    }

                    @Override
                    public void resourceAdded(ShareResource resource) {
                        if (done) {
                            return;
                        }
                        done = true;
                        share_manager.removeListener(this);
                        COConfigurationManager.setParameter("my.shares.view.auto.open.done", true);
                        mdi.loadEntryByID(MultipleDocumentInterface.SIDEBAR_SECTION_MY_SHARES, false);
                    }

                    @Override
                    public void reportProgress(int percent_complete) {
                    }

                    @Override
                    public void reportCurrentTask(String task_description) {
                    }
                };
                share_manager.addListener(shareManagerListener);
            }
        }
    } catch (Throwable t) {
    }
    try {
        if (!COConfigurationManager.getBooleanParameter("my.tracker.view.auto.open.done", false)) {
            // Load Tracker View on first host of file
            TRHost trackerHost = CoreFactory.getSingleton().getTrackerHost();
            trackerHostListener = new TRHostListener() {

                boolean done = false;

                @Override
                public void torrentRemoved(TRHostTorrent t) {
                }

                @Override
                public void torrentChanged(TRHostTorrent t) {
                }

                @Override
                public void torrentAdded(TRHostTorrent t) {
                    if (done) {
                        return;
                    }
                    done = true;
                    trackerHost.removeListener(this);
                    COConfigurationManager.setParameter("my.tracker.view.auto.open.done", true);
                    mdi.loadEntryByID(MultipleDocumentInterface.SIDEBAR_SECTION_MY_TRACKER, false);
                }

                @Override
                public boolean handleExternalRequest(InetSocketAddress client_address, String user, String url, URL absolute_url, String header, InputStream is, OutputStream os, AsyncController async) throws IOException {
                    return false;
                }
            };
            trackerHost.addListener(trackerHostListener);
        }
    } catch (Throwable t) {
    }
    UIManager uim = pi.getUIManager();
    if (uim != null) {
        MenuItem menuItem = uim.getMenuManager().addMenuItem(MenuManager.MENU_MENUBAR, "tags.view.heading");
        menuItem.setDisposeWithUIDetach(UIInstance.UIT_SWT);
        menuItem.addListener(new MenuItemListener() {

            @Override
            public void selected(MenuItem menu, Object target) {
                UIFunctionsManager.getUIFunctions().getMDI().showEntryByID(MultipleDocumentInterface.SIDEBAR_SECTION_TAGS);
            }
        });
        menuItem = uim.getMenuManager().addMenuItem(MenuManager.MENU_MENUBAR, "tag.discovery.view.heading");
        menuItem.setDisposeWithUIDetach(UIInstance.UIT_SWT);
        menuItem.addListener(new MenuItemListener() {

            @Override
            public void selected(MenuItem menu, Object target) {
                UIFunctionsManager.getUIFunctions().getMDI().showEntryByID(MultipleDocumentInterface.SIDEBAR_SECTION_TAG_DISCOVERY);
            }
        });
        menuItem = uim.getMenuManager().addMenuItem(MenuManager.MENU_MENUBAR, "chats.view.heading");
        menuItem.setDisposeWithUIDetach(UIInstance.UIT_SWT);
        menuItem.addListener(new MenuItemListener() {

            @Override
            public void selected(MenuItem menu, Object target) {
                UIFunctionsManager.getUIFunctions().getMDI().showEntryByID(MultipleDocumentInterface.SIDEBAR_SECTION_CHAT);
            }
        });
        menuItem = uim.getMenuManager().addMenuItem(MenuManager.MENU_MENUBAR, "archivedlsview.view.heading");
        menuItem.setDisposeWithUIDetach(UIInstance.UIT_SWT);
        menuItem.addListener(new MenuItemListener() {

            @Override
            public void selected(MenuItem menu, Object target) {
                UIFunctionsManager.getUIFunctions().getMDI().showEntryByID(MultipleDocumentInterface.SIDEBAR_SECTION_ARCHIVED_DOWNLOADS);
            }
        });
        menuItem = uim.getMenuManager().addMenuItem(MenuManager.MENU_MENUBAR, "downloadhistoryview.view.heading");
        menuItem.setDisposeWithUIDetach(UIInstance.UIT_SWT);
        menuItem.addListener(new MenuItemListener() {

            @Override
            public void selected(MenuItem menu, Object target) {
                UIFunctionsManager.getUIFunctions().getMDI().showEntryByID(MultipleDocumentInterface.SIDEBAR_SECTION_DOWNLOAD_HISTORY);
            }
        });
    }
// System.out.println("Activate sidebar " + startTab + " took "
// + (SystemTime.getCurrentTime() - startTime) + "ms");
// startTime = SystemTime.getCurrentTime();
}
Also used : TimerEventPeriodic(com.biglybt.core.util.TimerEventPeriodic) DownloadHistoryManager(com.biglybt.core.history.DownloadHistoryManager) ChatInstance(com.biglybt.plugin.net.buddy.BuddyPluginBeta.ChatInstance) InetSocketAddress(java.net.InetSocketAddress) OutputStream(java.io.OutputStream) ArrayList(java.util.ArrayList) UIManager(com.biglybt.pif.ui.UIManager) UIManagerListener2(com.biglybt.pif.ui.UIManagerListener2) DownloadStub(com.biglybt.pif.download.DownloadStub) TimerEventPerformer(com.biglybt.core.util.TimerEventPerformer) TimerEvent(com.biglybt.core.util.TimerEvent) ShareManagerListener(com.biglybt.pif.sharing.ShareManagerListener) MenuItemListener(com.biglybt.pif.ui.menus.MenuItemListener) UIInstance(com.biglybt.pif.ui.UIInstance) StatsView(com.biglybt.ui.swt.views.stats.StatsView) ClientStatsView(com.biglybt.ui.swt.views.clientstats.ClientStatsView) TRHostTorrent(com.biglybt.core.tracker.host.TRHostTorrent) DownloadStubEvent(com.biglybt.pif.download.DownloadStubEvent) TRHost(com.biglybt.core.tracker.host.TRHost) DownloadHistoryListener(com.biglybt.core.history.DownloadHistoryListener) ViewTitleInfo(com.biglybt.ui.common.viewtitleinfo.ViewTitleInfo) AsyncController(com.biglybt.core.util.AsyncController) ShareManager(com.biglybt.pif.sharing.ShareManager) ManagerUtils(com.biglybt.ui.swt.views.utils.ManagerUtils) URL(java.net.URL) DownloadHistoryEvent(com.biglybt.core.history.DownloadHistoryEvent) BuddyPluginBeta(com.biglybt.plugin.net.buddy.BuddyPluginBeta) Download(com.biglybt.pif.download.Download) ShareResource(com.biglybt.pif.sharing.ShareResource) InputStream(java.io.InputStream) PluginInterface(com.biglybt.pif.PluginInterface) DownloadStubListener(com.biglybt.pif.download.DownloadStubListener) MessageBoxShell(com.biglybt.ui.swt.shells.MessageBoxShell) MenuItem(com.biglybt.pif.ui.menus.MenuItem) IOException(java.io.IOException) TRHostListener(com.biglybt.core.tracker.host.TRHostListener) ParameterListener(com.biglybt.core.config.ParameterListener) ClientStatsView(com.biglybt.ui.swt.views.clientstats.ClientStatsView)

Example 39 with Download

use of com.biglybt.pif.download.Download in project BiglyBT by BiglySoftware.

the class SelectedContentManager method selectedContentToObject.

private static Object selectedContentToObject(ISelectedContent content) {
    DownloadManager dm = content.getDownloadManager();
    if (dm == null) {
        return (null);
    }
    Download dl = PluginCoreUtils.wrap(dm);
    if (dl == null) {
        return null;
    }
    int i = content.getFileIndex();
    if (i < 0) {
        return dl;
    }
    return dl.getDiskManagerFileInfo(i);
}
Also used : DownloadManager(com.biglybt.core.download.DownloadManager) Download(com.biglybt.pif.download.Download)

Example 40 with Download

use of com.biglybt.pif.download.Download in project BiglyBT by BiglySoftware.

the class InitialisationFunctions method hookDownloadAddition.

protected static void hookDownloadAddition() {
    PluginInterface pi = PluginInitializer.getDefaultInterface();
    DownloadManager dm = pi.getDownloadManager();
    // need to get in early to ensure property present on initial announce
    dm.addDownloadWillBeAddedListener(new DownloadWillBeAddedListener() {

        @Override
        public void initialised(Download download) {
            // unfortunately the has-been-opened state is updated by the client when a user opens content
            // but is also preserved across torrent export/import (e.g. when downloaded via magnet
            // URL. So reset it here if it is found to be set
            com.biglybt.core.download.DownloadManager dm = PluginCoreUtils.unwrap(download);
            if (PlatformTorrentUtils.getHasBeenOpened(dm)) {
                PlatformTorrentUtils.setHasBeenOpened(dm, false);
            }
        }
    });
}
Also used : DownloadWillBeAddedListener(com.biglybt.pif.download.DownloadWillBeAddedListener) PluginInterface(com.biglybt.pif.PluginInterface) DownloadManager(com.biglybt.pif.download.DownloadManager) Download(com.biglybt.pif.download.Download)

Aggregations

Download (com.biglybt.pif.download.Download)80 DownloadManager (com.biglybt.core.download.DownloadManager)22 Torrent (com.biglybt.pif.torrent.Torrent)17 DiskManagerFileInfo (com.biglybt.pif.disk.DiskManagerFileInfo)12 File (java.io.File)12 TOTorrent (com.biglybt.core.torrent.TOTorrent)11 PluginInterface (com.biglybt.pif.PluginInterface)11 URL (java.net.URL)10 DownloadManagerState (com.biglybt.core.download.DownloadManagerState)8 PEPeerManager (com.biglybt.core.peer.PEPeerManager)8 List (java.util.List)7 Tag (com.biglybt.core.tag.Tag)6 MenuItem (com.biglybt.pif.ui.menus.MenuItem)6 IOException (java.io.IOException)6 ArrayList (java.util.ArrayList)6 DownloadException (com.biglybt.pif.download.DownloadException)5 DiskManager (com.biglybt.core.disk.DiskManager)4 DownloadManager (com.biglybt.pif.download.DownloadManager)4 DownloadScrapeResult (com.biglybt.pif.download.DownloadScrapeResult)4 Peer (com.biglybt.pif.peers.Peer)4