Search in sources :

Example 21 with PluginInterface

use of com.biglybt.pif.PluginInterface in project BiglyBT by BiglySoftware.

the class SubscriptionManagerImpl method downloadSubscription.

private void downloadSubscription(final String description, final TOTorrent torrent, final InetSocketAddress peer, byte[] subs_id, int version, String name, final downloadListener listener) {
    try {
        // testing purposes, see if local exists
        LightWeightSeed lws = LightWeightSeedManager.getSingleton().get(new HashWrapper(torrent.getHash()));
        if (lws != null) {
            log("Light weight seed found");
            listener.complete(lws.getDataLocation());
        } else {
            String sid = ByteFormatter.encodeString(subs_id);
            File dir = getSubsDir();
            dir = new File(dir, "temp");
            if (!dir.exists()) {
                if (!dir.mkdirs()) {
                    throw (new IOException("Failed to create dir '" + dir + "'"));
                }
            }
            final File torrent_file = new File(dir, sid + "_" + version + ".torrent");
            final File data_file = new File(dir, VuzeFileHandler.getVuzeFileName(sid + "_" + version));
            PluginInterface pi = PluginInitializer.getDefaultInterface();
            final DownloadManager dm = pi.getDownloadManager();
            Download download = dm.getDownload(torrent.getHash());
            if (download == null) {
                log("Adding download for subscription '" + new String(torrent.getName()) + "'");
                boolean is_update = getSubscriptionFromSID(subs_id) != null;
                PlatformTorrentUtils.setContentTitle(torrent, "Subscription " + (is_update ? "Update" : "Download") + ": " + description + "(" + name + ")");
                // PlatformTorrentUtils.setContentThumbnail(torrent, thumbnail);
                TorrentUtils.setFlag(torrent, TorrentUtils.TORRENT_FLAG_LOW_NOISE, true);
                Torrent t = new TorrentImpl(torrent);
                t.setDefaultEncoding();
                t.writeToFile(torrent_file);
                download = dm.addDownload(t, torrent_file, data_file);
                download.setFlag(Download.FLAG_DISABLE_AUTO_FILE_MOVE, true);
                download.setBooleanAttribute(ta_subs_download, true);
                Map rd = listener.getRecoveryData();
                if (rd != null) {
                    download.setMapAttribute(ta_subs_download_rd, rd);
                }
            } else {
                log("Existing download found for subscription '" + new String(torrent.getName()) + "'");
            }
            final Download f_download = download;
            final TimerEventPeriodic[] event = { null };
            event[0] = SimpleTimer.addPeriodicEvent("SM:cancelTimer", 10 * 1000, new TimerEventPerformer() {

                private long start_time = SystemTime.getMonotonousTime();

                @Override
                public void perform(TimerEvent ev) {
                    boolean kill = false;
                    try {
                        Download download = dm.getDownload(torrent.getHash());
                        if (listener.isCancelled() || download == null) {
                            kill = true;
                        } else {
                            int state = download.getState();
                            if (state == Download.ST_ERROR) {
                                log("Download entered error state, removing");
                                kill = true;
                            } else {
                                long now = SystemTime.getMonotonousTime();
                                long running_for = now - start_time;
                                if (running_for > 10 * 60 * 1000) {
                                    log("Download hasn't completed in permitted time, removing");
                                    kill = true;
                                } else if (running_for > 4 * 60 * 1000) {
                                    if (download.getStats().getDownloaded() == 0) {
                                        log("Download has zero downloaded, removing");
                                        kill = true;
                                    }
                                } else if (running_for > 2 * 60 * 1000) {
                                    DownloadScrapeResult scrape = download.getLastScrapeResult();
                                    if (scrape == null || scrape.getSeedCount() <= 0) {
                                        log("Download has no seeds, removing");
                                        kill = true;
                                    }
                                }
                            }
                        }
                    } catch (Throwable e) {
                        log("Download failed", e);
                        kill = true;
                    }
                    if (kill && event[0] != null) {
                        try {
                            event[0].cancel();
                            if (!listener.isCancelled()) {
                                listener.failed(new SubscriptionException("Download abandoned"));
                            }
                        } finally {
                            removeDownload(f_download, true);
                            torrent_file.delete();
                        }
                    }
                }
            });
            download.addCompletionListener(new DownloadCompletionListener() {

                @Override
                public void onCompletion(Download d) {
                    listener.complete(d, torrent_file);
                }
            });
            if (download.isComplete()) {
                listener.complete(download, torrent_file);
            } else {
                download.setForceStart(true);
                if (peer != null) {
                    download.addPeerListener(new DownloadPeerListener() {

                        @Override
                        public void peerManagerAdded(Download download, PeerManager peer_manager) {
                            InetSocketAddress tcp = AddressUtils.adjustTCPAddress(peer, true);
                            InetSocketAddress udp = AddressUtils.adjustUDPAddress(peer, true);
                            log("    Injecting peer into download: " + tcp);
                            peer_manager.addPeer(tcp.getAddress().getHostAddress(), tcp.getPort(), udp.getPort(), true);
                        }

                        @Override
                        public void peerManagerRemoved(Download download, PeerManager peer_manager) {
                        }
                    });
                }
            }
        }
    } catch (Throwable e) {
        log("Failed to add download", e);
        listener.failed(e);
    }
}
Also used : Torrent(com.biglybt.pif.torrent.Torrent) TOTorrent(com.biglybt.core.torrent.TOTorrent) TorrentImpl(com.biglybt.pifimpl.local.torrent.TorrentImpl) InetSocketAddress(java.net.InetSocketAddress) LightWeightSeed(com.biglybt.core.lws.LightWeightSeed) PluginInterface(com.biglybt.pif.PluginInterface) PeerManager(com.biglybt.pif.peers.PeerManager) VuzeFile(com.biglybt.core.vuzefile.VuzeFile)

Example 22 with PluginInterface

use of com.biglybt.pif.PluginInterface in project BiglyBT by BiglySoftware.

the class SubscriptionManagerImpl method lookupAssociations.

protected void lookupAssociations(boolean high_priority) {
    synchronized (this) {
        if (periodic_lookup_in_progress) {
            if (high_priority) {
                priority_lookup_pending++;
            }
            return;
        }
        periodic_lookup_in_progress = true;
    }
    try {
        PluginInterface pi = PluginInitializer.getDefaultInterface();
        Download[] downloads = pi.getDownloadManager().getDownloads();
        long now = SystemTime.getCurrentTime();
        long newest_time = 0;
        Download newest_download = null;
        for (int i = 0; i < downloads.length; i++) {
            Download download = downloads[i];
            if (downloadIsIgnored(download)) {
                continue;
            }
            Map map = download.getMapAttribute(ta_subscription_info);
            if (map == null) {
                map = new LightHashMap();
            } else {
                map = new LightHashMap(map);
            }
            Long l_last_check = (Long) map.get("lc");
            long last_check = l_last_check == null ? 0 : l_last_check.longValue();
            if (last_check > now) {
                last_check = now;
                map.put("lc", new Long(last_check));
                download.setMapAttribute(ta_subscription_info, map);
            }
            List subs = (List) map.get("s");
            int sub_count = subs == null ? 0 : subs.size();
            if (sub_count > 8) {
                continue;
            }
            long create_time = download.getCreationTime();
            int time_between_checks = (sub_count + 1) * 24 * 60 * 60 * 1000 + (int) (create_time % 4 * 60 * 60 * 1000);
            if (now - last_check >= time_between_checks) {
                if (create_time > newest_time) {
                    newest_time = create_time;
                    newest_download = download;
                }
            }
        }
        if (newest_download != null) {
            DHTPluginInterface dht_plugin = selectDHTPlugin(newest_download);
            if (dht_plugin != null) {
                byte[] hash = newest_download.getTorrent().getHash();
                log("Association lookup starts for " + newest_download.getName() + "/" + ByteFormatter.encodeString(hash));
                lookupAssociationsSupport(dht_plugin, hash, newest_download.getName(), new SubscriptionLookupListener() {

                    @Override
                    public void found(byte[] hash, Subscription subscription) {
                    }

                    @Override
                    public void failed(byte[] hash, SubscriptionException error) {
                        log("Association lookup failed for " + ByteFormatter.encodeString(hash), error);
                        associationLookupComplete();
                    }

                    @Override
                    public void complete(byte[] hash, Subscription[] subs) {
                        log("Association lookup complete for " + ByteFormatter.encodeString(hash));
                        associationLookupComplete();
                    }
                });
            } else {
                associationLookupComplete();
            }
        } else {
            associationLookupComplete();
        }
    } catch (Throwable e) {
        log("Association lookup check failed", e);
        associationLookupComplete();
    }
}
Also used : PluginInterface(com.biglybt.pif.PluginInterface)

Example 23 with PluginInterface

use of com.biglybt.pif.PluginInterface in project BiglyBT by BiglySoftware.

the class SubscriptionManagerImpl method getKnownSubscriptions.

@Override
public Subscription[] getKnownSubscriptions(byte[] hash) {
    PluginInterface pi = PluginInitializer.getDefaultInterface();
    try {
        Download download = pi.getDownloadManager().getDownload(hash);
        if (download != null) {
            Map m = download.getMapAttribute(ta_subscription_info);
            if (m != null) {
                List s = (List) m.get("s");
                if (s != null && s.size() > 0) {
                    List result = new ArrayList(s.size());
                    boolean hide_search = hideSearchTemplates();
                    for (int i = 0; i < s.size(); i++) {
                        byte[] sid = (byte[]) s.get(i);
                        SubscriptionImpl subs = getSubscriptionFromSID(sid);
                        if (subs != null) {
                            if (isVisible(subs)) {
                                if (hide_search && subs.isSearchTemplate()) {
                                } else {
                                    result.add(subs);
                                }
                            }
                        }
                    }
                    return ((Subscription[]) result.toArray(new Subscription[result.size()]));
                }
            }
        }
    } catch (Throwable e) {
        log("Failed to get known subscriptions", e);
    }
    return (new Subscription[0]);
}
Also used : PluginInterface(com.biglybt.pif.PluginInterface)

Example 24 with PluginInterface

use of com.biglybt.pif.PluginInterface in project BiglyBT by BiglySoftware.

the class SubscriptionManagerImpl method getLinkedSubscriptions.

@Override
public Subscription[] getLinkedSubscriptions(byte[] hash) {
    PluginInterface pi = PluginInitializer.getDefaultInterface();
    try {
        Download download = pi.getDownloadManager().getDownload(hash);
        if (download != null) {
            Map m = download.getMapAttribute(ta_subscription_info);
            if (m != null) {
                List s = (List) m.get("s");
                if (s != null && s.size() > 0) {
                    List result = new ArrayList(s.size());
                    for (int i = 0; i < s.size(); i++) {
                        byte[] sid = (byte[]) s.get(i);
                        SubscriptionImpl subs = getSubscriptionFromSID(sid);
                        if (subs != null) {
                            if (subs.hasAssociation(hash)) {
                                result.add(subs);
                            }
                        }
                    }
                    return ((Subscription[]) result.toArray(new Subscription[result.size()]));
                }
            }
        }
    } catch (Throwable e) {
        log("Failed to get known subscriptions", e);
    }
    return (new Subscription[0]);
}
Also used : PluginInterface(com.biglybt.pif.PluginInterface)

Example 25 with PluginInterface

use of com.biglybt.pif.PluginInterface in project BiglyBT by BiglySoftware.

the class ClientRestarterImpl method runUpdateProcess.

private boolean runUpdateProcess(boolean update_only, boolean no_wait) throws CoreException {
    PluginInterface pi = core.getPluginManager().getPluginInterfaceByID("azupdater");
    if (pi == null) {
        Logger.log(new LogAlert(LogAlert.UNREPEATABLE, LogAlert.AT_ERROR, "Can't update/restart, mandatory plugin 'azupdater' not found"));
        throw (new CoreException("mandatory plugin 'azupdater' not found"));
    }
    String updater_dir = pi.getPluginDirectoryName();
    classpath_prefix = updater_dir + File.separator + UPDATER_JAR;
    String app_path = SystemProperties.getApplicationPath();
    while (app_path.endsWith(File.separator)) {
        app_path = app_path.substring(0, app_path.length() - 1);
    }
    String user_path = SystemProperties.getUserPath();
    while (user_path.endsWith(File.separator)) {
        user_path = user_path.substring(0, user_path.length() - 1);
    }
    String config_override = System.getProperty(SystemProperties.SYS_PROP_CONFIG_OVERRIDE);
    if (config_override == null) {
        config_override = "";
    }
    String[] parameters = { update_only ? "updateonly" : "restart", app_path, user_path, config_override };
    FileOutputStream fos = null;
    try {
        Properties update_properties = new Properties();
        long max_mem = Runtime.getRuntime().maxMemory();
        update_properties.put("max_mem", "" + max_mem);
        update_properties.put("app_name", SystemProperties.getApplicationName());
        update_properties.put("app_entry", SystemProperties.getApplicationEntryPoint());
        if (System.getProperty(SystemProperties.SYSPROP_NATIVELAUNCHER) != null || Constants.isOSX) {
            try {
                String cmd = PlatformManagerFactory.getPlatformManager().getApplicationCommandLine();
                if (cmd != null) {
                    update_properties.put("app_cmd", cmd);
                }
            } catch (Throwable e) {
                Debug.printStackTrace(e);
            }
        }
        if (no_wait) {
            update_properties.put("no_wait", "1");
        }
        update_properties.put("instance_port", String.valueOf(Constants.INSTANCE_PORT));
        fos = new FileOutputStream(new File(user_path, UPDATE_PROPERTIES));
        // this handles unicode chars by writing \\u escapes
        update_properties.store(fos, "BiglyBT restart properties");
    } catch (Throwable e) {
        Debug.printStackTrace(e);
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (Throwable e) {
                Debug.printStackTrace(e);
            }
        }
    }
    String[] properties = { "-Duser.dir=\"" + app_path + "\"" };
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    boolean res = restartApp(new PrintWriter(os) {

        @Override
        public void println(String str) {
            // we intercept these logs and log immediately
            Logger.log(new LogEvent(LOGID, str));
        }
    }, MAIN_CLASS, properties, parameters, update_only);
    // just check if any non-logged data exists
    byte[] bytes = os.toByteArray();
    if (bytes.length > 0) {
        Logger.log(new LogEvent(LOGID, "BiglyBTUpdater: extra log - " + new String(bytes)));
    }
    return (res);
}
Also used : LogEvent(com.biglybt.core.logging.LogEvent) PluginInterface(com.biglybt.pif.PluginInterface) ByteArrayOutputStream(java.io.ByteArrayOutputStream) SystemProperties(com.biglybt.core.util.SystemProperties) Properties(java.util.Properties) LogAlert(com.biglybt.core.logging.LogAlert) CoreException(com.biglybt.core.CoreException) FileOutputStream(java.io.FileOutputStream) File(java.io.File) PrintWriter(java.io.PrintWriter)

Aggregations

PluginInterface (com.biglybt.pif.PluginInterface)120 URL (java.net.URL)15 IPCInterface (com.biglybt.pif.ipc.IPCInterface)14 UIManager (com.biglybt.pif.ui.UIManager)13 PluginManager (com.biglybt.pif.PluginManager)12 HashMap (java.util.HashMap)12 List (java.util.List)12 Download (com.biglybt.pif.download.Download)10 MenuItemListener (com.biglybt.pif.ui.menus.MenuItemListener)10 File (java.io.File)10 Map (java.util.Map)10 DownloadManager (com.biglybt.core.download.DownloadManager)9 UIFunctions (com.biglybt.ui.UIFunctions)9 ArrayList (java.util.ArrayList)9 PluginException (com.biglybt.pif.PluginException)8 MenuItem (com.biglybt.pif.ui.menus.MenuItem)8 MenuManager (com.biglybt.pif.ui.menus.MenuManager)8 DHTPlugin (com.biglybt.plugin.dht.DHTPlugin)8 DHT (com.biglybt.core.dht.DHT)7 SelectionEvent (org.eclipse.swt.events.SelectionEvent)7