Search in sources :

Example 1 with TorrentAttribute

use of com.biglybt.pif.torrent.TorrentAttribute in project BiglyBT by BiglySoftware.

the class Share method execute.

@Override
public void execute(String commandName, final ConsoleInput ci, List args) {
    if (args.isEmpty()) {
        printHelp(ci.out, args);
        return;
    }
    final ShareManager share_manager;
    try {
        share_manager = ci.core.getPluginManager().getDefaultPluginInterface().getShareManager();
    } catch (ShareException e) {
        ci.out.println("ERROR: " + e.getMessage() + " ::");
        Debug.printStackTrace(e);
        return;
    }
    final String arg = (String) args.remove(0);
    if (args.isEmpty() && ("list".equalsIgnoreCase(arg))) {
        ShareResource[] shares = share_manager.getShares();
        if (shares.length == 0) {
            ci.out.println("> No shares found");
        } else {
            HashSet share_map = new HashSet();
            int share_num = 0;
            for (int i = 0; i < shares.length; i++) {
                ShareResource share = shares[i];
                if (share instanceof ShareResourceDirContents) {
                    share_map.add(share);
                } else if (share.getParent() != null) {
                } else {
                    ci.out.println("> " + share_num++ + ": " + shares[i].getName());
                }
            }
            Iterator it = share_map.iterator();
            TorrentManager tm = ci.core.getPluginManager().getDefaultPluginInterface().getTorrentManager();
            TorrentAttribute category_attribute = tm.getAttribute(TorrentAttribute.TA_CATEGORY);
            TorrentAttribute props_attribute = tm.getAttribute(TorrentAttribute.TA_SHARE_PROPERTIES);
            while (it.hasNext()) {
                ShareResourceDirContents root = (ShareResourceDirContents) it.next();
                String cat = root.getAttribute(category_attribute);
                String props = root.getAttribute(props_attribute);
                String extra = cat == null ? "" : (",cat=" + cat);
                extra += props == null ? "" : (",props=" + props);
                ci.out.println("> " + share_num++ + ": " + root.getName() + extra);
                outputChildren(ci, "    ", root);
            }
        }
        return;
    }
    String first_arg = (String) args.get(0);
    if (first_arg.equals("hash") && args.size() > 1) {
        byte[] hash = ByteFormatter.decodeString((String) args.get(1));
        boolean force = false;
        if (args.size() > 2) {
            force = ((String) args.get(2)).equalsIgnoreCase("true");
        }
        if (("remove".equalsIgnoreCase(arg))) {
            ShareResource[] shares = share_manager.getShares();
            boolean done = false;
            for (int i = 0; i < shares.length; i++) {
                ShareResource share = shares[i];
                ShareItem item = null;
                if (share instanceof ShareResourceFile) {
                    item = ((ShareResourceFile) share).getItem();
                } else if (share instanceof ShareResourceDir) {
                    item = ((ShareResourceDir) share).getItem();
                }
                if (item != null) {
                    try {
                        byte[] item_hash = item.getTorrent().getHash();
                        if (Arrays.equals(hash, item_hash)) {
                            share.delete(force);
                            ci.out.println("> Share " + share.getName() + " removed");
                            done = true;
                            break;
                        }
                    } catch (Throwable e) {
                        ci.out.println("ERROR: " + e.getMessage() + " ::");
                        Debug.printStackTrace(e);
                    }
                }
            }
            if (!done) {
                ci.out.println("> Share with hash " + ByteFormatter.encodeString(hash) + " not found");
            }
        } else {
            ci.out.println("ERROR: Unsupported hash based command '" + arg + "'");
        }
        return;
    }
    final File path = new File(first_arg);
    if (!path.exists()) {
        ci.out.println("ERROR: path [" + path + "] does not exist.");
        return;
    }
    if (("remove".equalsIgnoreCase(arg))) {
        ShareResource[] shares = share_manager.getShares();
        boolean done = false;
        for (int i = 0; i < shares.length; i++) {
            if (shares[i].getName().equals(path.toString())) {
                try {
                    shares[i].delete();
                    ci.out.println("> Share " + path.toString() + " removed");
                    done = true;
                } catch (Throwable e) {
                    ci.out.println("ERROR: " + e.getMessage() + " ::");
                    Debug.printStackTrace(e);
                }
                break;
            }
        }
        if (!done) {
            ci.out.println("> Share " + path.toString() + " not found");
        }
        return;
    }
    String category = null;
    String props = null;
    if (args.size() == 2) {
        String properties = (String) args.get(1);
        StringTokenizer tok = new StringTokenizer(properties, ";");
        while (tok.hasMoreTokens()) {
            String token = tok.nextToken();
            int pos = token.indexOf('=');
            if (pos == -1) {
                ci.out.println("ERROR: invalid properties string '" + properties + "'");
                return;
            } else {
                String lhs = token.substring(0, pos).trim().toLowerCase();
                String rhs = token.substring(pos + 1).trim();
                if (lhs.equals("category")) {
                    category = rhs;
                } else {
                    if (lhs.equals("private") || lhs.equals("dht_backup") || lhs.equals("comment")) {
                        if (props == null) {
                            props = "";
                        }
                        if (lhs.equals("comment")) {
                            rhs = rhs.replace('_', ' ');
                        }
                        if (rhs.length() > 0) {
                            props += (props.length() == 0 ? "" : ";") + lhs + "=" + rhs;
                        }
                    } else {
                        ci.out.println("ERROR: invalid properties string '" + properties + "'");
                        return;
                    }
                }
            }
        }
    }
    final String f_category = category;
    final String f_props = props;
    new AEThread("shareFile") {

        @Override
        public void runSupport() {
            try {
                ShareResource resource = share_manager.getShare(path);
                if ("file".equalsIgnoreCase(arg)) {
                    ci.out.println("File [" + path + "] share being processed in background...");
                    if (resource == null) {
                        resource = share_manager.addFile(path);
                    }
                } else if ("folder".equalsIgnoreCase(arg)) {
                    ci.out.println("Folder [" + path + "] share being processed in background...");
                    if (resource == null) {
                        resource = share_manager.addDir(path);
                    }
                } else if ("contents".equalsIgnoreCase(arg)) {
                    ci.out.println("Folder contents [" + path + "] share being processed in background...");
                    if (resource == null) {
                        resource = share_manager.addDirContents(path, false);
                    }
                } else if ("rcontents".equalsIgnoreCase(arg)) {
                    ci.out.println("Folder contents recursive [" + path + "] share being processed in background...");
                    if (resource == null) {
                        resource = share_manager.addDirContents(path, true);
                    }
                } else {
                    ci.out.println("ERROR: type '" + arg + "' unknown.");
                }
                if (resource != null) {
                    TorrentManager tm = ci.core.getPluginManager().getDefaultPluginInterface().getTorrentManager();
                    String cat = f_category;
                    if (cat != null) {
                        if (cat.length() == 0) {
                            cat = null;
                        }
                        resource.setAttribute(tm.getAttribute(TorrentAttribute.TA_CATEGORY), cat);
                    }
                    String pro = f_props;
                    if (pro != null) {
                        if (pro.length() == 0) {
                            pro = null;
                        }
                        resource.setAttribute(tm.getAttribute(TorrentAttribute.TA_SHARE_PROPERTIES), pro);
                    }
                }
                if (resource != null) {
                    ci.out.println("... processing complete");
                }
            } catch (Throwable e) {
                ci.out.println("ERROR: " + e.getMessage() + " ::");
                Debug.printStackTrace(e);
            }
        }
    }.start();
}
Also used : TorrentManager(com.biglybt.pif.torrent.TorrentManager) AEThread(com.biglybt.core.util.AEThread) TorrentAttribute(com.biglybt.pif.torrent.TorrentAttribute) File(java.io.File)

Example 2 with TorrentAttribute

use of com.biglybt.pif.torrent.TorrentAttribute in project BiglyBT by BiglySoftware.

the class DownloadImpl method attributeEventOccurred.

@Override
public void attributeEventOccurred(DownloadManager download, String attribute, int event_type) {
    CopyOnWriteMap attr_listener_map = getAttributeMapForType(event_type);
    TorrentAttribute attr = convertAttribute(attribute);
    if (attr == null) {
        return;
    }
    List listeners = null;
    listeners = ((CopyOnWriteList) attr_listener_map.get(attribute)).getList();
    if (listeners == null) {
        return;
    }
    for (int i = 0; i < listeners.size(); i++) {
        DownloadAttributeListener dal = (DownloadAttributeListener) listeners.get(i);
        try {
            dal.attributeEventOccurred(this, attr, event_type);
        } catch (Throwable t) {
            Debug.printStackTrace(t);
        }
    }
}
Also used : TorrentAttribute(com.biglybt.pif.torrent.TorrentAttribute)

Example 3 with TorrentAttribute

use of com.biglybt.pif.torrent.TorrentAttribute in project BiglyBT by BiglySoftware.

the class MagnetPlugin method initialize.

@Override
public void initialize(PluginInterface _plugin_interface) {
    plugin_interface = _plugin_interface;
    MagnetURIHandler uri_handler = MagnetURIHandler.getSingleton();
    final LocaleUtilities lu = plugin_interface.getUtilities().getLocaleUtilities();
    lu.addListener(new LocaleListener() {

        @Override
        public void localeChanged(Locale l) {
            updateLocale(lu);
        }
    });
    updateLocale(lu);
    BasicPluginConfigModel config = plugin_interface.getUIManager().createBasicPluginConfigModel(ConfigSection.SECTION_PLUGINS, PLUGIN_CONFIGSECTION_ID);
    config.addInfoParameter2("MagnetPlugin.current.port", String.valueOf(uri_handler.getPort()));
    secondary_lookup = config.addBooleanParameter2("MagnetPlugin.use.lookup.service", "MagnetPlugin.use.lookup.service", true);
    md_lookup = config.addBooleanParameter2("MagnetPlugin.use.md.download", "MagnetPlugin.use.md.download", true);
    md_lookup_delay = config.addIntParameter2("MagnetPlugin.use.md.download.delay", "MagnetPlugin.use.md.download.delay", MD_LOOKUP_DELAY_SECS_DEFAULT);
    md_lookup.addEnabledOnSelection(md_lookup_delay);
    timeout_param = config.addIntParameter2("MagnetPlugin.timeout.secs", "MagnetPlugin.timeout.secs", PLUGIN_DOWNLOAD_TIMEOUT_SECS_DEFAULT);
    sources_param = config.addStringListParameter2("MagnetPlugin.add.sources", "MagnetPlugin.add.sources", SOURCE_VALUES, SOURCE_STRINGS, SOURCE_VALUES[1]);
    sources_extra_param = config.addIntParameter2("MagnetPlugin.add.sources.extra", "MagnetPlugin.add.sources.extra", 0);
    magnet_recovery = config.addBooleanParameter2("MagnetPlugin.recover.magnets", "MagnetPlugin.recover.magnets", true);
    Parameter[] nps = new Parameter[AENetworkClassifier.AT_NETWORKS.length];
    for (int i = 0; i < nps.length; i++) {
        String nn = AENetworkClassifier.AT_NETWORKS[i];
        String config_name = "Network Selection Default." + nn;
        String msg_text = "ConfigView.section.connection.networks." + nn;
        final BooleanParameter param = config.addBooleanParameter2(config_name, msg_text, COConfigurationManager.getBooleanParameter(config_name));
        COConfigurationManager.addParameterListener(config_name, new com.biglybt.core.config.ParameterListener() {

            @Override
            public void parameterChanged(String name) {
                param.setDefaultValue(COConfigurationManager.getBooleanParameter(name));
            }
        });
        nps[i] = param;
        net_params.put(nn, param);
    }
    config.createGroup("label.default.nets", nps);
    MenuItemListener listener = new MenuItemListener() {

        @Override
        public void selected(MenuItem _menu, Object _target) {
            TableRow[] rows = (TableRow[]) _target;
            String cb_all_data = "";
            for (TableRow row : rows) {
                Torrent torrent;
                String name;
                Object ds = row.getDataSource();
                Download download = null;
                ShareResource share = null;
                if (ds instanceof ShareResourceFile) {
                    ShareResourceFile sf = (ShareResourceFile) ds;
                    try {
                        torrent = sf.getItem().getTorrent();
                    } catch (ShareException e) {
                        continue;
                    }
                    name = sf.getName();
                    share = sf;
                } else if (ds instanceof ShareResourceDir) {
                    ShareResourceDir sd = (ShareResourceDir) ds;
                    try {
                        torrent = sd.getItem().getTorrent();
                    } catch (ShareException e) {
                        continue;
                    }
                    name = sd.getName();
                    share = sd;
                } else if (ds instanceof Download) {
                    download = (Download) ds;
                    torrent = download.getTorrent();
                    name = download.getName();
                } else {
                    continue;
                }
                boolean is_share = false;
                Set<String> networks = new HashSet<>();
                if (share != null) {
                    is_share = true;
                    Map<String, String> properties = share.getProperties();
                    if (properties != null) {
                        String nets = properties.get(ShareManager.PR_NETWORKS);
                        if (nets != null) {
                            String[] bits = nets.split(",");
                            for (String bit : bits) {
                                bit = AENetworkClassifier.internalise(bit.trim());
                                if (bit != null) {
                                    networks.add(bit);
                                }
                            }
                        }
                    }
                }
                if (download != null) {
                    TorrentAttribute ta = plugin_interface.getTorrentManager().getAttribute(TorrentAttribute.TA_NETWORKS);
                    String[] nets = download.getListAttribute(ta);
                    networks.addAll(Arrays.asList(nets));
                    try {
                        byte[] hash = download.getTorrentHash();
                        if (plugin_interface.getShareManager().lookupShare(hash) != null) {
                            is_share = true;
                        }
                    } catch (Throwable e) {
                    }
                }
                String cb_data = download == null ? UrlUtils.getMagnetURI(name, torrent) : UrlUtils.getMagnetURI(download);
                if (download != null) {
                    List<Tag> tags = TagManagerFactory.getTagManager().getTagsForTaggable(TagType.TT_DOWNLOAD_MANUAL, PluginCoreUtils.unwrap(download));
                    for (Tag tag : tags) {
                        if (tag.isPublic()) {
                            cb_data += "&tag=" + UrlUtils.encode(tag.getTagName(true));
                        }
                    }
                }
                String sources = sources_param.getValue();
                boolean add_sources = sources.equals("2") || (sources.equals("1") && is_share);
                if (add_sources) {
                    if (networks.isEmpty()) {
                        for (String net : AENetworkClassifier.AT_NETWORKS) {
                            if (isNetworkEnabled(net)) {
                                networks.add(net);
                            }
                        }
                    }
                    if (networks.contains(AENetworkClassifier.AT_PUBLIC) && !cb_data.contains("xsource=")) {
                        InetAddress ip = NetworkAdmin.getSingleton().getDefaultPublicAddress();
                        InetAddress ip_v6 = NetworkAdmin.getSingleton().getDefaultPublicAddressV6();
                        int port = TCPNetworkManager.getSingleton().getTCPListeningPortNumber();
                        if (ip != null && port > 0) {
                            cb_data += "&xsource=" + UrlUtils.encode(ip.getHostAddress() + ":" + port);
                        }
                        if (ip_v6 != null && port > 0) {
                            cb_data += "&xsource=" + UrlUtils.encode(ip_v6.getHostAddress() + ":" + port);
                        }
                        int extra = sources_extra_param.getValue();
                        if (extra > 0) {
                            if (download == null) {
                                if (torrent != null) {
                                    download = plugin_interface.getDownloadManager().getDownload(torrent);
                                }
                            }
                            if (download != null) {
                                Set<String> added = new HashSet<>();
                                DownloadManager dm = PluginCoreUtils.unwrap(download);
                                PEPeerManager pm = dm.getPeerManager();
                                if (pm != null) {
                                    List<PEPeer> peers = pm.getPeers();
                                    for (PEPeer peer : peers) {
                                        String peer_ip = peer.getIp();
                                        if (AENetworkClassifier.categoriseAddress(peer_ip) == AENetworkClassifier.AT_PUBLIC) {
                                            int peer_port = peer.getTCPListenPort();
                                            if (peer_port > 0) {
                                                cb_data += "&xsource=" + UrlUtils.encode(peer_ip + ":" + peer_port);
                                                added.add(peer_ip);
                                                extra--;
                                                if (extra == 0) {
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }
                                if (extra > 0) {
                                    Map response_cache = dm.getDownloadState().getTrackerResponseCache();
                                    if (response_cache != null) {
                                        List<TRTrackerAnnouncerResponsePeer> peers = TRTrackerAnnouncerFactory.getCachedPeers(response_cache);
                                        for (TRTrackerAnnouncerResponsePeer peer : peers) {
                                            String peer_ip = peer.getAddress();
                                            if (AENetworkClassifier.categoriseAddress(peer_ip) == AENetworkClassifier.AT_PUBLIC) {
                                                if (!added.contains(peer_ip)) {
                                                    int peer_port = peer.getPort();
                                                    if (peer_port > 0) {
                                                        cb_data += "&xsource=" + UrlUtils.encode(peer_ip + ":" + peer_port);
                                                        added.add(peer_ip);
                                                        extra--;
                                                        if (extra == 0) {
                                                            break;
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                // removed this as well - nothing wrong with allowing magnet copy
                // for private torrents - they still can't be tracked if you don't
                // have permission
                /*if ( torrent.isPrivate()){

							cb_data = getMessageText( "private_torrent" );

						}else if ( torrent.isDecentralised()){
						*/
                // ok
                /* relaxed this as we allow such torrents to be downloaded via magnet links
							 * (as opposed to tracked in the DHT)

						}else if ( torrent.isDecentralisedBackupEnabled()){

							TorrentAttribute ta_peer_sources 	= plugin_interface.getTorrentManager().getAttribute( TorrentAttribute.TA_PEER_SOURCES );

							String[]	sources = download.getListAttribute( ta_peer_sources );

							boolean	ok = false;

							for (int i=0;i<sources.length;i++){

								if ( sources[i].equalsIgnoreCase( "DHT")){

									ok	= true;

									break;
								}
							}

							if ( !ok ){

								cb_data = getMessageText( "decentral_disabled" );
							}
						}else{

							cb_data = getMessageText( "decentral_backup_disabled" );
							*/
                // }
                // System.out.println( "MagnetPlugin: export = " + url );
                cb_all_data += (cb_all_data.length() == 0 ? "" : "\n") + cb_data;
            }
            try {
                plugin_interface.getUIManager().copyToClipBoard(cb_all_data);
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    };
    List<TableContextMenuItem> menus = new ArrayList<>();
    for (String table : TableManager.TABLE_MYTORRENTS_ALL) {
        TableContextMenuItem menu = plugin_interface.getUIManager().getTableManager().addContextMenuItem(table, "MagnetPlugin.contextmenu.exporturi");
        menu.addMultiListener(listener);
        menu.setHeaderCategory(MenuItem.HEADER_SOCIAL);
        menus.add(menu);
    }
    uri_handler.addListener(new MagnetURIHandlerListener() {

        @Override
        public byte[] badge() {
            InputStream is = getClass().getClassLoader().getResourceAsStream("com/biglybt/plugin/magnet/Magnet.gif");
            if (is == null) {
                return (null);
            }
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                try {
                    byte[] buffer = new byte[8192];
                    while (true) {
                        int len = is.read(buffer);
                        if (len <= 0) {
                            break;
                        }
                        baos.write(buffer, 0, len);
                    }
                } finally {
                    is.close();
                }
                return (baos.toByteArray());
            } catch (Throwable e) {
                Debug.printStackTrace(e);
                return (null);
            }
        }

        @Override
        public byte[] download(MagnetURIHandlerProgressListener muh_listener, byte[] hash, String args, InetSocketAddress[] sources, long timeout) throws MagnetURIHandlerException {
            try {
                Download dl = plugin_interface.getDownloadManager().getDownload(hash);
                if (dl != null) {
                    Torrent torrent = dl.getTorrent();
                    if (torrent != null) {
                        byte[] torrent_data = torrent.writeToBEncodedData();
                        torrent_data = addTrackersAndWebSeedsEtc(torrent_data, args, new HashSet<String>());
                        return (torrent_data);
                    }
                }
            } catch (Throwable e) {
                Debug.printStackTrace(e);
            }
            return (recoverableDownload(muh_listener, hash, args, sources, timeout, false));
        }

        @Override
        public boolean download(URL url) throws MagnetURIHandlerException {
            try {
                plugin_interface.getDownloadManager().addDownload(url, false);
                return (true);
            } catch (DownloadException e) {
                throw (new MagnetURIHandlerException("Operation failed", e));
            }
        }

        @Override
        public boolean set(String name, Map values) {
            List l = listeners.getList();
            for (int i = 0; i < l.size(); i++) {
                if (((MagnetPluginListener) l.get(i)).set(name, values)) {
                    return (true);
                }
            }
            return (false);
        }

        @Override
        public int get(String name, Map values) {
            List l = listeners.getList();
            for (int i = 0; i < l.size(); i++) {
                int res = ((MagnetPluginListener) l.get(i)).get(name, values);
                if (res != Integer.MIN_VALUE) {
                    return (res);
                }
            }
            return (Integer.MIN_VALUE);
        }
    });
    plugin_interface.getUIManager().addUIListener(new UIManagerListener() {

        @Override
        public void UIAttached(UIInstance instance) {
            if (instance.getUIType().equals(UIInstance.UIT_SWT)) {
                try {
                    Class.forName("com.biglybt.plugin.magnet.swt.MagnetPluginUISWT").getConstructor(new Class[] { UIInstance.class, TableContextMenuItem[].class }).newInstance(new Object[] { instance, menus.toArray(new TableContextMenuItem[menus.size()]) });
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void UIDetached(UIInstance instance) {
        }
    });
    final List<Download> to_delete = new ArrayList<>();
    Download[] downloads = plugin_interface.getDownloadManager().getDownloads();
    for (Download download : downloads) {
        if (download.getFlag(Download.FLAG_METADATA_DOWNLOAD)) {
            to_delete.add(download);
        }
    }
    final AESemaphore delete_done = new AESemaphore("delete waiter");
    if (to_delete.size() > 0) {
        AEThread2 t = new AEThread2("MagnetPlugin:delmds", true) {

            @Override
            public void run() {
                try {
                    for (Download download : to_delete) {
                        try {
                            download.stop();
                        } catch (Throwable e) {
                        }
                        try {
                            download.remove(true, true);
                        } catch (Throwable e) {
                            Debug.out(e);
                        }
                    }
                } finally {
                    delete_done.release();
                }
            }
        };
        t.start();
    } else {
        delete_done.release();
    }
    plugin_interface.addListener(new PluginListener() {

        @Override
        public void initializationComplete() {
            // make sure DDB is initialised as we need it to register its
            // transfer types
            AEThread2 t = new AEThread2("MagnetPlugin:init", true) {

                @Override
                public void run() {
                    delete_done.reserve();
                    recoverDownloads();
                    plugin_interface.getDistributedDatabase();
                }
            };
            t.start();
        }

        @Override
        public void closedownInitiated() {
        }

        @Override
        public void closedownComplete() {
        }
    });
}
Also used : Torrent(com.biglybt.pif.torrent.Torrent) TOTorrent(com.biglybt.core.torrent.TOTorrent) PEPeer(com.biglybt.core.peer.PEPeer) ShareResourceDir(com.biglybt.pif.sharing.ShareResourceDir) InetSocketAddress(java.net.InetSocketAddress) LocaleUtilities(com.biglybt.pif.utils.LocaleUtilities) DownloadManager(com.biglybt.core.download.DownloadManager) DownloadException(com.biglybt.pif.download.DownloadException) MenuItemListener(com.biglybt.pif.ui.menus.MenuItemListener) UIInstance(com.biglybt.pif.ui.UIInstance) MagnetURIHandler(com.biglybt.net.magneturi.MagnetURIHandler) TableRow(com.biglybt.pif.ui.tables.TableRow) PEPeerManager(com.biglybt.core.peer.PEPeerManager) InetAddress(java.net.InetAddress) ShareResourceFile(com.biglybt.pif.sharing.ShareResourceFile) MagnetURIHandlerProgressListener(com.biglybt.net.magneturi.MagnetURIHandlerProgressListener) TableContextMenuItem(com.biglybt.pif.ui.tables.TableContextMenuItem) URL(java.net.URL) PluginListener(com.biglybt.pif.PluginListener) ShareException(com.biglybt.pif.sharing.ShareException) LocaleListener(com.biglybt.pif.utils.LocaleListener) Download(com.biglybt.pif.download.Download) ShareResource(com.biglybt.pif.sharing.ShareResource) InputStream(java.io.InputStream) TableContextMenuItem(com.biglybt.pif.ui.tables.TableContextMenuItem) MenuItem(com.biglybt.pif.ui.menus.MenuItem) ByteArrayOutputStream(java.io.ByteArrayOutputStream) BooleanParameter(com.biglybt.pif.ui.config.BooleanParameter) TorrentAttribute(com.biglybt.pif.torrent.TorrentAttribute) BooleanParameter(com.biglybt.pif.ui.config.BooleanParameter) Parameter(com.biglybt.pif.ui.config.Parameter) StringListParameter(com.biglybt.pif.ui.config.StringListParameter) IntParameter(com.biglybt.pif.ui.config.IntParameter) TRTrackerAnnouncerResponsePeer(com.biglybt.core.tracker.client.TRTrackerAnnouncerResponsePeer) Tag(com.biglybt.core.tag.Tag) MagnetURIHandlerListener(com.biglybt.net.magneturi.MagnetURIHandlerListener) MagnetURIHandlerException(com.biglybt.net.magneturi.MagnetURIHandlerException) UIManagerListener(com.biglybt.pif.ui.UIManagerListener) BasicPluginConfigModel(com.biglybt.pif.ui.model.BasicPluginConfigModel)

Example 4 with TorrentAttribute

use of com.biglybt.pif.torrent.TorrentAttribute in project BiglyBT by BiglySoftware.

the class ShareHosterPlugin method resourceAdded.

@Override
public void resourceAdded(final ShareResource resource) {
    log.log(LoggerChannel.LT_INFORMATION, "Resource added:".concat(resource.getName()));
    try {
        resource.addDeletionListener(new ShareResourceWillBeDeletedListener() {

            @Override
            public void resourceWillBeDeleted(ShareResource resource) throws ShareResourceDeletionVetoException {
                canResourceBeDeleted(resource);
            }
        });
        Download new_download = null;
        int type = resource.getType();
        if (type == ShareResource.ST_FILE) {
            ShareResourceFile file_resource = (ShareResourceFile) resource;
            ShareItem item = file_resource.getItem();
            Torrent torrent = item.getTorrent();
            Download download = download_manager.getDownload(torrent);
            if (download == null) {
                new_download = addDownload(resource, torrent, item.getTorrentFile(), file_resource.getFile());
            }
        } else if (type == ShareResource.ST_DIR) {
            ShareResourceDir dir_resource = (ShareResourceDir) resource;
            ShareItem item = dir_resource.getItem();
            Torrent torrent = item.getTorrent();
            Download download = download_manager.getDownload(torrent);
            if (download == null) {
                new_download = addDownload(resource, torrent, item.getTorrentFile(), dir_resource.getDir());
            }
        }
        if (new_download != null) {
            final Download f_new_download = new_download;
            resource_dl_map.put(resource, new_download);
            resource.addChangeListener(new ShareResourceListener() {

                @Override
                public void shareResourceChanged(ShareResource resource, ShareResourceEvent event) {
                    if (event.getType() == ShareResourceEvent.ET_ATTRIBUTE_CHANGED) {
                        TorrentAttribute attribute = (TorrentAttribute) event.getData();
                        // System.out.println( "sh: res -> ds: " + attribute.getName() + "/" + resource.getAttribute( attribute ));
                        f_new_download.setAttribute(attribute, resource.getAttribute(attribute));
                    }
                }
            });
            TorrentAttribute[] attributes = resource.getAttributes();
            for (int i = 0; i < attributes.length; i++) {
                TorrentAttribute ta = attributes[i];
                new_download.setAttribute(ta, resource.getAttribute(ta));
            }
            new_download.addAttributeListener(new DownloadAttributeListener() {

                @Override
                public void attributeEventOccurred(Download d, TorrentAttribute attr, int event_type) {
                    resource.setAttribute(attr, d.getAttribute(attr));
                }
            }, plugin_interface.getTorrentManager().getAttribute(TorrentAttribute.TA_CATEGORY), DownloadAttributeListener.WRITTEN);
            boolean persistent = resource.isPersistent();
            Torrent dl_torrent = new_download.getTorrent();
            if (dl_torrent != null) {
                TrackerTorrent tt = tracker.host(dl_torrent, persistent);
                if (!persistent) {
                    tt.addRemovalListener(new TrackerTorrentWillBeRemovedListener() {

                        @Override
                        public void torrentWillBeRemoved(TrackerTorrent tt) throws TrackerTorrentRemovalVetoException {
                            if (tt != torrent_being_removed) {
                                throw (new TrackerTorrentRemovalVetoException(MessageText.getString("plugin.sharing.torrent.remove.veto")));
                            }
                        }
                    });
                }
                resource_tt_map.put(resource, tt);
            }
            if (!persistent) {
                new_download.addDownloadWillBeRemovedListener(new DownloadWillBeRemovedListener() {

                    @Override
                    public void downloadWillBeRemoved(Download dl) throws DownloadRemovalVetoException {
                        if (dl != download_being_removed) {
                            throw (new DownloadRemovalVetoException(MessageText.getString("plugin.sharing.download.remove.veto")));
                        }
                    }
                });
            }
        }
    } catch (Throwable e) {
        Debug.printStackTrace(e);
    }
}
Also used : Torrent(com.biglybt.pif.torrent.Torrent) TrackerTorrent(com.biglybt.pif.tracker.TrackerTorrent) TrackerTorrentWillBeRemovedListener(com.biglybt.pif.tracker.TrackerTorrentWillBeRemovedListener) TrackerTorrent(com.biglybt.pif.tracker.TrackerTorrent) TorrentAttribute(com.biglybt.pif.torrent.TorrentAttribute) TrackerTorrentRemovalVetoException(com.biglybt.pif.tracker.TrackerTorrentRemovalVetoException)

Example 5 with TorrentAttribute

use of com.biglybt.pif.torrent.TorrentAttribute in project BiglyBT by BiglySoftware.

the class ExternalSeedPlugin method downloadAdded.

@Override
public void downloadAdded(Download download) {
    Torrent torrent = download.getTorrent();
    if (torrent == null) {
        return;
    }
    List peers = new ArrayList();
    for (int i = 0; i < factories.length; i++) {
        String attributeID = "no-ext-seeds-" + factories[i].getClass().getSimpleName();
        TorrentAttribute attribute = plugin_interface.getTorrentManager().getPluginAttribute(attributeID);
        boolean noExternalSeeds = download.getBooleanAttribute(attribute);
        if (noExternalSeeds) {
            continue;
        }
        ExternalSeedReader[] x = factories[i].getSeedReaders(this, download);
        if (x.length == 0) {
            download.setBooleanAttribute(attribute, true);
        } else {
            for (int j = 0; j < x.length; j++) {
                ExternalSeedReader reader = x[j];
                ExternalSeedPeer peer = new ExternalSeedPeer(this, download, reader);
                peers.add(peer);
            }
        }
    }
    addPeers(download, peers);
}
Also used : Torrent(com.biglybt.pif.torrent.Torrent) TorrentAttribute(com.biglybt.pif.torrent.TorrentAttribute)

Aggregations

TorrentAttribute (com.biglybt.pif.torrent.TorrentAttribute)11 Torrent (com.biglybt.pif.torrent.Torrent)5 Download (com.biglybt.pif.download.Download)3 TOTorrent (com.biglybt.core.torrent.TOTorrent)2 DownloadAttributeListener (com.biglybt.pif.download.DownloadAttributeListener)2 ShareException (com.biglybt.pif.sharing.ShareException)2 TorrentManager (com.biglybt.pif.torrent.TorrentManager)2 ContentDownload (com.biglybt.core.content.ContentDownload)1 DownloadManager (com.biglybt.core.download.DownloadManager)1 DownloadManagerState (com.biglybt.core.download.DownloadManagerState)1 PEPeer (com.biglybt.core.peer.PEPeer)1 PEPeerManager (com.biglybt.core.peer.PEPeerManager)1 Tag (com.biglybt.core.tag.Tag)1 TOTorrentCreator (com.biglybt.core.torrent.TOTorrentCreator)1 TOTorrentException (com.biglybt.core.torrent.TOTorrentException)1 TRTrackerAnnouncerResponsePeer (com.biglybt.core.tracker.client.TRTrackerAnnouncerResponsePeer)1 AEThread (com.biglybt.core.util.AEThread)1 CopyOnWriteList (com.biglybt.core.util.CopyOnWriteList)1 MagnetURIHandler (com.biglybt.net.magneturi.MagnetURIHandler)1 MagnetURIHandlerException (com.biglybt.net.magneturi.MagnetURIHandlerException)1