Search in sources :

Example 1 with TorrentManager

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

the class SubscriptionManagerImpl method initWithCore.

protected void initWithCore(Core _core) {
    synchronized (this) {
        if (started) {
            return;
        }
        started = true;
    }
    core = _core;
    final PluginInterface default_pi = PluginInitializer.getDefaultInterface();
    rss_publisher = new SubscriptionRSSFeed(this, default_pi);
    TorrentManager tm = default_pi.getTorrentManager();
    ta_subs_download = tm.getPluginAttribute("azsubs.subs_dl");
    ta_subs_download_rd = tm.getPluginAttribute("azsubs.subs_dl_rd");
    ta_subscription_info = tm.getPluginAttribute("azsubs.subs_info");
    ta_category = tm.getAttribute(TorrentAttribute.TA_CATEGORY);
    ta_networks = tm.getAttribute(TorrentAttribute.TA_NETWORKS);
    PluginInterface dht_plugin_pi = CoreFactory.getSingleton().getPluginManager().getPluginInterfaceByClass(DHTPlugin.class);
    if (dht_plugin_pi != null) {
        dht_plugin_public = (DHTPlugin) dht_plugin_pi.getPlugin();
        /*
			if ( Constants.isCVSVersion()){

				addListener(
						new SubscriptionManagerListener()
						{
							public void
							subscriptionAdded(
								Subscription subscription )
							{
							}

							public void
							subscriptionChanged(
								Subscription		subscription )
							{
							}

							public void
							subscriptionRemoved(
								Subscription subscription )
							{
							}

							public void
							associationsChanged(
								byte[] hash )
							{
								System.out.println( "Subscriptions changed: " + ByteFormatter.encodeString( hash ));

								Subscription[] subs = getKnownSubscriptions( hash );

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

									System.out.println( "    " + subs[i].getString());
								}
							}
						});
			}
			*/
        default_pi.getDownloadManager().addListener(new DownloadManagerListener() {

            @Override
            public void downloadAdded(Download download) {
                Torrent torrent = download.getTorrent();
                if (torrent != null) {
                    byte[] hash = torrent.getHash();
                    Object[] entry;
                    synchronized (potential_associations2) {
                        entry = (Object[]) potential_associations2.remove(new HashWrapper(hash));
                    }
                    if (entry != null) {
                        SubscriptionImpl[] subs = (SubscriptionImpl[]) entry[0];
                        String subs_str = "";
                        for (int i = 0; i < subs.length; i++) {
                            subs_str += (i == 0 ? "" : ",") + subs[i].getName();
                        }
                        log("Applying deferred asocciation for " + ByteFormatter.encodeString(hash) + " -> " + subs_str);
                        recordAssociationsSupport(hash, subs, ((Boolean) entry[1]).booleanValue());
                    }
                }
            }

            @Override
            public void downloadRemoved(Download download) {
            }
        }, false);
        default_pi.getDownloadManager().addDownloadWillBeAddedListener(new DownloadWillBeAddedListener() {

            @Override
            public void initialised(Download download) {
                Torrent torrent = download.getTorrent();
                if (torrent != null) {
                    byte[] hash = torrent.getHash();
                    HashWrapper hw = new HashWrapper(hash);
                    Object[] entry;
                    synchronized (potential_associations2) {
                        entry = (Object[]) potential_associations2.get(hw);
                    }
                    if (entry != null) {
                        SubscriptionImpl[] subs = (SubscriptionImpl[]) entry[0];
                        prepareDownload(download, subs, null);
                    } else {
                        synchronized (potential_associations3) {
                            entry = potential_associations3.get(hw);
                        }
                        if (entry != null) {
                            Subscription[] subs = (Subscription[]) entry[0];
                            SubscriptionResult[] results = (SubscriptionResult[]) entry[1];
                            prepareDownload(download, subs, results);
                        }
                    }
                }
            }
        });
        TorrentUtils.addTorrentAttributeListener(new TorrentUtils.torrentAttributeListener() {

            @Override
            public void attributeSet(TOTorrent torrent, String attribute, Object value) {
                if (attribute == TorrentUtils.TORRENT_AZ_PROP_OBTAINED_FROM) {
                    try {
                        checkPotentialAssociations(torrent.getHash(), (String) value);
                    } catch (Throwable e) {
                        Debug.printStackTrace(e);
                    }
                }
            }
        });
        DelayedTask delayed_task = UtilitiesImpl.addDelayedTask("Subscriptions", new Runnable() {

            @Override
            public void run() {
                new AEThread2("Subscriptions:delayInit", true) {

                    @Override
                    public void run() {
                        asyncInit();
                    }
                }.start();
            }

            protected void asyncInit() {
                Download[] downloads = default_pi.getDownloadManager().getDownloads();
                for (int i = 0; i < downloads.length; i++) {
                    Download download = downloads[i];
                    if (download.getBooleanAttribute(ta_subs_download)) {
                        Map rd = download.getMapAttribute(ta_subs_download_rd);
                        boolean delete_it;
                        if (rd == null) {
                            delete_it = true;
                        } else {
                            delete_it = !recoverSubscriptionUpdate(download, rd);
                        }
                        if (delete_it) {
                            removeDownload(download, true);
                        }
                    }
                }
                default_pi.getDownloadManager().addListener(new DownloadManagerListener() {

                    @Override
                    public void downloadAdded(final Download download) {
                        if (!downloadIsIgnored(download)) {
                            if (!dht_plugin_public.isInitialising()) {
                                // if new download then we want to check out its subscription status
                                lookupAssociations(download.getMapAttribute(ta_subscription_info) == null);
                            } else {
                                new AEThread2("Subscriptions:delayInit", true) {

                                    @Override
                                    public void run() {
                                        lookupAssociations(download.getMapAttribute(ta_subscription_info) == null);
                                    }
                                }.start();
                            }
                        }
                    }

                    @Override
                    public void downloadRemoved(Download download) {
                    }
                }, false);
                for (int i = 0; i < PUB_ASSOC_CONC_MAX; i++) {
                    if (publishAssociations()) {
                        break;
                    }
                }
                publishSubscriptions();
                COConfigurationManager.addParameterListener(CONFIG_MAX_RESULTS, new ParameterListener() {

                    @Override
                    public void parameterChanged(String name) {
                        final int max_results = COConfigurationManager.getIntParameter(CONFIG_MAX_RESULTS);
                        new AEThread2("Subs:max results changer", true) {

                            @Override
                            public void run() {
                                checkMaxResults(max_results);
                            }
                        }.start();
                    }
                });
                SimpleTimer.addPeriodicEvent("SubscriptionChecker", TIMER_PERIOD, new TimerEventPerformer() {

                    private int ticks;

                    @Override
                    public void perform(TimerEvent event) {
                        ticks++;
                        checkStuff(ticks);
                    }
                });
            }
        });
        delayed_task.queue();
    }
    if (isSearchEnabled()) {
        try {
            default_pi.getUtilities().registerSearchProvider(new SearchProvider() {

                private Map<Integer, Object> properties = new HashMap<>();

                {
                    properties.put(PR_NAME, MessageText.getString("ConfigView.section.Subscriptions"));
                    try {
                        URL url = MagnetURIHandler.getSingleton().registerResource(new MagnetURIHandler.ResourceProvider() {

                            @Override
                            public String getUID() {
                                return (SubscriptionManager.class.getName() + ".2");
                            }

                            @Override
                            public String getFileType() {
                                return ("png");
                            }

                            @Override
                            public byte[] getData() {
                                InputStream is = getClass().getClassLoader().getResourceAsStream("com/biglybt/ui/images/subscription_icon_1616.png");
                                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) {
                                    return (null);
                                }
                            }
                        });
                        properties.put(PR_ICON_URL, url.toExternalForm());
                    } catch (Throwable e) {
                        Debug.out(e);
                    }
                }

                @Override
                public SearchInstance search(Map<String, Object> search_parameters, SearchObserver observer) throws SearchException {
                    try {
                        return (searchSubscriptions(search_parameters, observer));
                    } catch (Throwable e) {
                        throw (new SearchException("Search failed", e));
                    }
                }

                @Override
                public Object getProperty(int property) {
                    return (properties.get(property));
                }

                @Override
                public void setProperty(int property, Object value) {
                    properties.put(property, value);
                }
            });
        } catch (Throwable e) {
            Debug.out("Failed to register search provider");
        }
    }
    default_pi.getUtilities().registerJSONRPCServer(new Utilities.JSONServer() {

        private List<String> methods = new ArrayList<>();

        {
            methods.add("vuze-subs-list");
        }

        @Override
        public String getName() {
            return ("Subscriptions");
        }

        @Override
        public List<String> getSupportedMethods() {
            return (methods);
        }

        @Override
        public Map call(String method, Map args) throws PluginException {
            throw (new PluginException("derp"));
        }
    });
}
Also used : Torrent(com.biglybt.pif.torrent.Torrent) TOTorrent(com.biglybt.core.torrent.TOTorrent) URL(java.net.URL) Utilities(com.biglybt.pif.utils.Utilities) StaticUtilities(com.biglybt.pif.utils.StaticUtilities) DelayedTask(com.biglybt.pif.utils.DelayedTask) PlatformTorrentUtils(com.biglybt.core.torrent.PlatformTorrentUtils) GZIPInputStream(java.util.zip.GZIPInputStream) PluginInterface(com.biglybt.pif.PluginInterface) PluginException(com.biglybt.pif.PluginException) TorrentManager(com.biglybt.pif.torrent.TorrentManager) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) TOTorrent(com.biglybt.core.torrent.TOTorrent) ParameterListener(com.biglybt.core.config.ParameterListener)

Example 2 with TorrentManager

use of com.biglybt.pif.torrent.TorrentManager 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 3 with TorrentManager

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

the class ShareManagerImpl method generate.

@Override
public void generate(IndentWriter writer) {
    writer.println("Shares");
    try {
        writer.indent();
        ShareResource[] shares = getShares();
        HashSet share_map = new HashSet();
        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 {
                writer.println(getDebugName(share));
            }
        }
        Iterator it = share_map.iterator();
        // Hopefully all the things we need are avail on core create
        if (!CoreFactory.isCoreAvailable()) {
            // could probably log some stuff below, but for now
            // be safe and lazy and just exit
            writer.println("No Core");
            return;
        }
        TorrentManager tm = PluginInitializer.getDefaultInterface().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);
            extra += ",rec=" + root.isRecursive();
            writer.println(root.getName() + extra);
            generate(writer, root);
        }
    } finally {
        writer.exdent();
    }
}
Also used : TorrentAttribute(com.biglybt.pif.torrent.TorrentAttribute) TorrentManager(com.biglybt.pif.torrent.TorrentManager)

Aggregations

TorrentManager (com.biglybt.pif.torrent.TorrentManager)3 TorrentAttribute (com.biglybt.pif.torrent.TorrentAttribute)2 ParameterListener (com.biglybt.core.config.ParameterListener)1 PlatformTorrentUtils (com.biglybt.core.torrent.PlatformTorrentUtils)1 TOTorrent (com.biglybt.core.torrent.TOTorrent)1 AEThread (com.biglybt.core.util.AEThread)1 PluginException (com.biglybt.pif.PluginException)1 PluginInterface (com.biglybt.pif.PluginInterface)1 Torrent (com.biglybt.pif.torrent.Torrent)1 DelayedTask (com.biglybt.pif.utils.DelayedTask)1 StaticUtilities (com.biglybt.pif.utils.StaticUtilities)1 Utilities (com.biglybt.pif.utils.Utilities)1 File (java.io.File)1 URL (java.net.URL)1 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)1 GZIPInputStream (java.util.zip.GZIPInputStream)1