Search in sources :

Example 1 with GlobalManagerAdapter

use of com.biglybt.core.global.GlobalManagerAdapter in project BiglyBT by BiglySoftware.

the class TorrentLog method performCommand.

@Override
protected boolean performCommand(ConsoleInput ci, DownloadManager dm, List args) {
    try {
        dms_mon.enter();
        if (!gm_listener_added) {
            gm_listener_added = true;
            GlobalManager gm = CoreFactory.getSingleton().getGlobalManager();
            gm.addListener(new GlobalManagerAdapter() {

                @Override
                public void downloadManagerRemoved(DownloadManager dm) {
                    dms.remove(dm);
                }
            }, false);
        }
        boolean turnOn;
        if (mode == MODE_FLIP) {
            turnOn = !dms.contains(dm);
        } else {
            turnOn = mode == MODE_ON;
        }
        if (turnOn) {
            ci.out.print("->on] ");
            if (dms.contains(dm)) {
                return true;
            }
            dms.add(dm);
            if (dms.size() == 1) {
                Logger.addListener(this);
            }
        } else {
            ci.out.print("->off] ");
            dms.remove(dm);
            if (dms.size() == 0) {
                Logger.removeListener(this);
            }
        }
    } catch (Exception e) {
        e.printStackTrace(ci.out);
        return false;
    } finally {
        dms_mon.exit();
    }
    return true;
}
Also used : GlobalManager(com.biglybt.core.global.GlobalManager) GlobalManagerAdapter(com.biglybt.core.global.GlobalManagerAdapter) DownloadManager(com.biglybt.core.download.DownloadManager)

Example 2 with GlobalManagerAdapter

use of com.biglybt.core.global.GlobalManagerAdapter in project BiglyBT by BiglySoftware.

the class TranscodeManagerImpl method checkCategories.

void checkCategories() {
    Category[] cats = CategoryManager.getCategories();
    Map<Category, Object[]> active_map = new HashMap<>();
    for (Category cat : cats) {
        String target = cat.getStringAttribute(Category.AT_AUTO_TRANSCODE_TARGET);
        if (target != null) {
            String device_id = null;
            if (target.endsWith("/blank")) {
                device_id = target.substring(0, target.length() - 6);
            }
            DeviceMediaRenderer target_dmr = null;
            TranscodeProfile target_profile = null;
            for (DeviceImpl device : device_manager.getDevices()) {
                if (!(device instanceof DeviceMediaRenderer)) {
                    continue;
                }
                DeviceMediaRenderer dmr = (DeviceMediaRenderer) device;
                if (device_id != null) {
                    if (device.getID().equals(device_id)) {
                        target_dmr = dmr;
                        target_profile = device.getBlankProfile();
                        break;
                    }
                } else {
                    TranscodeProfile[] profs = device.getTranscodeProfiles();
                    for (TranscodeProfile prof : profs) {
                        if (prof.getUID().equals(target)) {
                            target_dmr = dmr;
                            target_profile = prof;
                            break;
                        }
                    }
                }
            }
            if (target_dmr != null) {
                active_map.put(cat, new Object[] { target_dmr, target_profile });
            }
        }
    }
    Map<Category, Object[]> to_process = new HashMap<>();
    synchronized (category_map) {
        if (category_listener == null) {
            category_listener = new CategoryListener() {

                @Override
                public void downloadManagerAdded(Category cat, DownloadManager manager) {
                    Object[] details;
                    synchronized (category_map) {
                        details = category_map.get(cat);
                    }
                    if (details != null) {
                        processCategory(cat, details, manager);
                    }
                }

                @Override
                public void downloadManagerRemoved(Category cat, DownloadManager removed) {
                }
            };
        }
        Iterator<Category> it = category_map.keySet().iterator();
        while (it.hasNext()) {
            Category c = it.next();
            if (!active_map.containsKey(c)) {
                c.removeCategoryListener(category_listener);
                it.remove();
            }
        }
        for (final Category c : active_map.keySet()) {
            if (!category_map.containsKey(c)) {
                to_process.put(c, active_map.get(c));
                c.addCategoryListener(category_listener);
                category_map.put(c, active_map.get(c));
                if (c.getType() == Category.TYPE_UNCATEGORIZED) {
                    if (category_dl_listener == null) {
                        // new downloads don't get a category-change event fired when added
                        // we also want to delay things a bit to allow other components
                        // to set an initial category. there's no hurry anyways
                        category_dl_listener = new GlobalManagerAdapter() {

                            @Override
                            public void downloadManagerAdded(final DownloadManager dm) {
                                new DelayedEvent("TM:cat-check", 10 * 1000, new AERunnable() {

                                    @Override
                                    public void runSupport() {
                                        Category dm_c = dm.getDownloadState().getCategory();
                                        if (dm_c == null || dm_c == c) {
                                            // still uncategorised
                                            Object[] details;
                                            synchronized (category_map) {
                                                details = category_map.get(c);
                                            }
                                            if (details != null) {
                                                processCategory(c, details, dm);
                                            }
                                        }
                                    }
                                });
                            }

                            @Override
                            public void downloadManagerRemoved(DownloadManager dm) {
                            }
                        };
                        core.getGlobalManager().addListener(category_dl_listener, false);
                    }
                }
            }
        }
    }
    if (to_process.size() > 0) {
        List<DownloadManager> downloads = core.getGlobalManager().getDownloadManagers();
        for (Map.Entry<Category, Object[]> entry : to_process.entrySet()) {
            Category c = entry.getKey();
            Object[] details = entry.getValue();
            List<DownloadManager> list = c.getDownloadManagers(downloads);
            for (DownloadManager dm : list) {
                processCategory(c, details, dm);
            }
        }
    }
}
Also used : Category(com.biglybt.core.category.Category) DownloadManager(com.biglybt.core.download.DownloadManager) GlobalManagerAdapter(com.biglybt.core.global.GlobalManagerAdapter) CategoryListener(com.biglybt.core.category.CategoryListener)

Example 3 with GlobalManagerAdapter

use of com.biglybt.core.global.GlobalManagerAdapter in project BiglyBT by BiglySoftware.

the class CoreImpl method start.

@Override
public void start() throws CoreException {
    if (!canStart()) {
        throw (new CoreException("Core: already started (alternative process)"));
    }
    AEThread2.setOurThread();
    try {
        this_mon.enter();
        if (started) {
            throw (new CoreException("Core: already started"));
        }
        if (stopped) {
            throw (new CoreException("Core: already stopped"));
        }
        started = true;
    } finally {
        this_mon.exit();
    }
    // If a user sets this property, it is an alias for the following settings.
    if ("1".equals(System.getProperty(SystemProperties.SYSPROP_SAFEMODE))) {
        if (Logger.isEnabled())
            Logger.log(new LogEvent(LOGID, "Safe mode enabled"));
        Constants.isSafeMode = true;
        System.setProperty(SystemProperties.SYSPROP_LOADPLUGINS, "0");
        System.setProperty(SystemProperties.SYSPROP_DISABLEDOWNLOADS, "1");
        System.setProperty(SystemProperties.SYSPROP_SKIP_SWTCHECK, "1");
        // Not using localised text - not sure it's safe to this early.
        Logger.log(new LogAlert(LogAlert.UNREPEATABLE, LogEvent.LT_WARNING, "You are running " + Constants.APP_NAME + " in safe mode - you " + "can change your configuration, but any downloads added will " + "not be remembered when you close " + Constants.APP_NAME + "."));
    }
    /**
     * test to see if UI plays nicely with a really slow initialization
     */
    String sDelayCore = System.getProperty("delay.core", null);
    if (sDelayCore != null) {
        try {
            long delayCore = Long.parseLong(sDelayCore);
            Thread.sleep(delayCore);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // run plugin loading in parallel to the global manager loading
    AEThread2 pluginload = new AEThread2("PluginLoader", true) {

        @Override
        public void run() {
            if (Logger.isEnabled())
                Logger.log(new LogEvent(LOGID, "Loading of Plugins starts"));
            pi.loadPlugins(CoreImpl.this, false, !"0".equals(System.getProperty(SystemProperties.SYSPROP_LOADPLUGINS)), true, true);
            if (Logger.isEnabled())
                Logger.log(new LogEvent(LOGID, "Loading of Plugins complete"));
        }
    };
    if (LOAD_PLUGINS_IN_OTHER_THREAD) {
        pluginload.start();
    } else {
        pluginload.run();
    }
    // Disable async loading of existing torrents, because there are many things
    // (like hosting) that require all the torrents to be loaded.  While we
    // can write code for each of these cases to wait until the torrents are
    // loaded, it's a pretty big job to find them all and fix all their quirks.
    // Too big of a job for this late in the release stage.
    // Other example is the tracker plugin that is coded in a way where it must
    // always publish a complete rss feed
    global_manager = GlobalManagerFactory.create(this, null, 0);
    if (stopped) {
        System.err.println("Core stopped while starting");
        return;
    }
    // wait until plugin loading is done
    if (LOAD_PLUGINS_IN_OTHER_THREAD) {
        pluginload.join();
    }
    if (stopped) {
        System.err.println("Core stopped while starting");
        return;
    }
    VuzeFileHandler.getSingleton().addProcessor(new VuzeFileProcessor() {

        @Override
        public void process(VuzeFile[] files, int expected_types) {
            for (int i = 0; i < files.length; i++) {
                VuzeFile vf = files[i];
                VuzeFileComponent[] comps = vf.getComponents();
                for (int j = 0; j < comps.length; j++) {
                    VuzeFileComponent comp = comps[j];
                    int comp_type = comp.getType();
                    if (comp_type == VuzeFileComponent.COMP_TYPE_ADD_TORRENT) {
                        PluginInterface default_pi = getPluginManager().getDefaultPluginInterface();
                        Map map = comp.getContent();
                        try {
                            Torrent torrent;
                            String url = MapUtils.getMapString(map, "torrent_url", null);
                            if (url != null) {
                                TorrentDownloader dl = default_pi.getTorrentManager().getURLDownloader(new URL(url));
                                torrent = dl.download();
                            } else {
                                String tf = MapUtils.getMapString(map, "torrent_file", null);
                                if (tf != null) {
                                    File file = new File(tf);
                                    if (!file.canRead() || file.isDirectory()) {
                                        throw (new Exception("torrent_file '" + tf + "' is invalid"));
                                    }
                                    torrent = default_pi.getTorrentManager().createFromBEncodedFile(file);
                                } else {
                                    throw (new Exception("torrent_url or torrent_file must be specified"));
                                }
                            }
                            File dest = null;
                            String save_folder = MapUtils.getMapString(map, "save_folder", null);
                            if (save_folder != null) {
                                dest = new File(save_folder, torrent.getName());
                            } else {
                                String save_file = MapUtils.getMapString(map, "save_file", null);
                                if (save_file != null) {
                                    dest = new File(save_file);
                                }
                            }
                            if (dest != null) {
                                dest.getParentFile().mkdirs();
                            }
                            default_pi.getDownloadManager().addDownload(torrent, null, dest);
                        } catch (Throwable e) {
                            Debug.out(e);
                        }
                        comp.setProcessed();
                    }
                }
            }
        }
    });
    triggerLifeCycleComponentCreated(global_manager);
    pi.initialisePlugins();
    if (stopped) {
        System.err.println("Core stopped while starting");
        return;
    }
    if (Logger.isEnabled())
        Logger.log(new LogEvent(LOGID, "Initializing Plugins complete"));
    try {
        PluginInterface dht_pi = getPluginManager().getPluginInterfaceByClass(DHTPlugin.class);
        if (dht_pi != null) {
            dht_pi.addEventListener(new PluginEventListener() {

                private boolean first_dht = true;

                @Override
                public void handleEvent(PluginEvent ev) {
                    if (ev.getType() == DHTPlugin.EVENT_DHT_AVAILABLE) {
                        if (first_dht) {
                            first_dht = false;
                            DHT dht = (DHT) ev.getValue();
                            dht.addListener(new DHTListener() {

                                @Override
                                public void speedTesterAvailable(DHTSpeedTester tester) {
                                    if (speed_manager != null) {
                                        speed_manager.setSpeedTester(tester);
                                    }
                                }
                            });
                            global_manager.addListener(new GlobalManagerAdapter() {

                                @Override
                                public void seedingStatusChanged(boolean seeding_only_mode, boolean b) {
                                    checkConfig();
                                }
                            });
                            COConfigurationManager.addAndFireParameterListeners(new String[] { TransferSpeedValidator.AUTO_UPLOAD_ENABLED_CONFIGKEY, TransferSpeedValidator.AUTO_UPLOAD_SEEDING_ENABLED_CONFIGKEY }, new ParameterListener() {

                                @Override
                                public void parameterChanged(String parameterName) {
                                    checkConfig();
                                }
                            });
                        }
                    }
                }

                protected void checkConfig() {
                    if (speed_manager != null) {
                        speed_manager.setEnabled(TransferSpeedValidator.isAutoSpeedActive(global_manager));
                    }
                }
            });
        }
    } catch (Throwable e) {
    }
    if (COConfigurationManager.getBooleanParameter("Resume Downloads On Start")) {
        global_manager.resumeDownloads();
    }
    VersionCheckClient.getSingleton().initialise();
    instance_manager.initialize();
    NetworkManager.getSingleton().initialize(this);
    SpeedLimitHandler.getSingleton(this);
    Runtime.getRuntime().addShutdownHook(new AEThread("Shutdown Hook") {

        @Override
        public void runSupport() {
            Logger.log(new LogEvent(LOGID, "Shutdown hook triggered"));
            CoreImpl.this.stop();
        }
    });
    DelayedTask delayed_task = UtilitiesImpl.addDelayedTask("Core", new Runnable() {

        @Override
        public void run() {
            new AEThread2("core:delayTask", true) {

                @Override
                public void run() {
                    AEDiagnostics.checkDumpsAndNatives();
                    COConfigurationManager.setParameter("diags.enable.pending.writes", true);
                    AEDiagnostics.flushPendingLogs();
                    NetworkAdmin na = NetworkAdmin.getSingleton();
                    na.runInitialChecks(CoreImpl.this);
                    na.addPropertyChangeListener(new NetworkAdminPropertyChangeListener() {

                        private String last_as;

                        @Override
                        public void propertyChanged(String property) {
                            NetworkAdmin na = NetworkAdmin.getSingleton();
                            if (property.equals(NetworkAdmin.PR_NETWORK_INTERFACES)) {
                                boolean found_usable = false;
                                NetworkAdminNetworkInterface[] intf = na.getInterfaces();
                                for (int i = 0; i < intf.length; i++) {
                                    NetworkAdminNetworkInterfaceAddress[] addresses = intf[i].getAddresses();
                                    for (int j = 0; j < addresses.length; j++) {
                                        if (!addresses[j].isLoopback()) {
                                            found_usable = true;
                                        }
                                    }
                                }
                                if (!found_usable) {
                                    return;
                                }
                                Logger.log(new LogEvent(LOGID, "Network interfaces have changed (new=" + na.getNetworkInterfacesAsString() + ")"));
                                announceAll(false);
                            } else if (property.equals(NetworkAdmin.PR_AS)) {
                                String as = na.getCurrentASN().getAS();
                                if (last_as == null) {
                                    last_as = as;
                                } else if (!as.equals(last_as)) {
                                    Logger.log(new LogEvent(LOGID, "AS has changed (new=" + as + ")"));
                                    last_as = as;
                                    announceAll(false);
                                }
                            }
                        }
                    });
                    setupSleepAndCloseActions();
                }
            }.start();
        }
    });
    delayed_task.queue();
    if (stopped) {
        System.err.println("Core stopped while starting");
        return;
    }
    PairingManagerFactory.getSingleton();
    CoreRunningListener[] runningListeners;
    mon_coreRunningListeners.enter();
    try {
        if (coreRunningListeners == null) {
            runningListeners = new CoreRunningListener[0];
        } else {
            runningListeners = coreRunningListeners.toArray(new CoreRunningListener[0]);
            coreRunningListeners = null;
        }
    } finally {
        mon_coreRunningListeners.exit();
    }
    // Trigger Listeners now that core is started
    new AEThread2("Plugin Init Complete", false) {

        @Override
        public void run() {
            try {
                PlatformManagerFactory.getPlatformManager().startup(CoreImpl.this);
            } catch (Throwable e) {
                Debug.out("PlatformManager: init failed", e);
            }
            Iterator it = lifecycle_listeners.iterator();
            while (it.hasNext()) {
                try {
                    CoreLifecycleListener listener = (CoreLifecycleListener) it.next();
                    if (!listener.requiresPluginInitCompleteBeforeStartedEvent()) {
                        listener.started(CoreImpl.this);
                    }
                } catch (Throwable e) {
                    Debug.printStackTrace(e);
                }
            }
            pi.initialisationComplete();
            it = lifecycle_listeners.iterator();
            while (it.hasNext()) {
                try {
                    CoreLifecycleListener listener = (CoreLifecycleListener) it.next();
                    if (listener.requiresPluginInitCompleteBeforeStartedEvent()) {
                        listener.started(CoreImpl.this);
                    }
                } catch (Throwable e) {
                    Debug.printStackTrace(e);
                }
            }
        }
    }.start();
    // Typically there are many runningListeners, most with quick execution, and
    // a few longer ones.  Let 3 run at a time, queue the rest.  Without
    // a ThreadPool, the slow ones would delay the startup processes that run
    // after this start() method
    ThreadPool tp = new ThreadPool("Trigger CoreRunning Listeners", 3);
    for (final CoreRunningListener l : runningListeners) {
        try {
            tp.run(new AERunnable() {

                @Override
                public void runSupport() {
                    l.coreRunning(CoreImpl.this);
                }
            });
        } catch (Throwable t) {
            Debug.out(t);
        }
    }
// Debug.out("Core Start Complete");
}
Also used : Torrent(com.biglybt.pif.torrent.Torrent) TOTorrent(com.biglybt.core.torrent.TOTorrent) DHTSpeedTester(com.biglybt.core.dht.speed.DHTSpeedTester) VuzeFileComponent(com.biglybt.core.vuzefile.VuzeFileComponent) URL(java.net.URL) DHT(com.biglybt.core.dht.DHT) NetworkAdmin(com.biglybt.core.networkmanager.admin.NetworkAdmin) DHTListener(com.biglybt.core.dht.DHTListener) VuzeFile(com.biglybt.core.vuzefile.VuzeFile) DelayedTask(com.biglybt.pif.utils.DelayedTask) LogEvent(com.biglybt.core.logging.LogEvent) LogAlert(com.biglybt.core.logging.LogAlert) VuzeFileProcessor(com.biglybt.core.vuzefile.VuzeFileProcessor) NetworkAdminPropertyChangeListener(com.biglybt.core.networkmanager.admin.NetworkAdminPropertyChangeListener) GlobalManagerAdapter(com.biglybt.core.global.GlobalManagerAdapter) ParameterListener(com.biglybt.core.config.ParameterListener) TorrentDownloader(com.biglybt.pif.torrent.TorrentDownloader) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File) VuzeFile(com.biglybt.core.vuzefile.VuzeFile)

Example 4 with GlobalManagerAdapter

use of com.biglybt.core.global.GlobalManagerAdapter in project BiglyBT by BiglySoftware.

the class GlobalManagerFileMerger method initialise.

void initialise() {
    COConfigurationManager.addAndFireParameterListeners(new String[] { "Merge Same Size Files", "Merge Same Size Files Extended" }, new ParameterListener() {

        @Override
        public void parameterChanged(String _name) {
            enabled = COConfigurationManager.getBooleanParameter("Merge Same Size Files");
            enabled_extended = COConfigurationManager.getBooleanParameter("Merge Same Size Files Extended");
            if (initialised) {
                syncFileSets();
            }
        }
    });
    gm.addListener(new GlobalManagerAdapter() {

        @Override
        public void downloadManagerAdded(DownloadManager dm) {
            syncFileSets();
        }

        @Override
        public void downloadManagerRemoved(DownloadManager dm) {
            syncFileSets();
        }
    }, false);
    syncFileSets();
    initialised = true;
}
Also used : GlobalManagerAdapter(com.biglybt.core.global.GlobalManagerAdapter) ParameterListener(com.biglybt.core.config.ParameterListener) DownloadManager(com.biglybt.core.download.DownloadManager)

Example 5 with GlobalManagerAdapter

use of com.biglybt.core.global.GlobalManagerAdapter in project BiglyBT by BiglySoftware.

the class NetworkManager method initialize.

public void initialize(Core _core) {
    upload_processor = new TransferProcessor(TransferProcessor.TYPE_UPLOAD, new LimitedRateGroup() {

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

        @Override
        public int getRateLimitBytesPerSecond() {
            return max_upload_rate_bps;
        }

        @Override
        public boolean isDisabled() {
            return (max_upload_rate_bps == -1);
        }

        @Override
        public void updateBytesUsed(int used) {
        }
    }, write_controllers.size() > 1);
    download_processor = new TransferProcessor(TransferProcessor.TYPE_DOWNLOAD, new LimitedRateGroup() {

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

        @Override
        public int getRateLimitBytesPerSecond() {
            return max_download_rate_bps;
        }

        @Override
        public boolean isDisabled() {
            return (max_download_rate_bps == -1);
        }

        @Override
        public void updateBytesUsed(int used) {
        }
    }, read_controllers.size() > 1);
    lan_upload_processor = new TransferProcessor(TransferProcessor.TYPE_UPLOAD, new LimitedRateGroup() {

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

        @Override
        public int getRateLimitBytesPerSecond() {
            return max_lan_upload_rate_bps;
        }

        @Override
        public boolean isDisabled() {
            return (max_lan_upload_rate_bps == -1);
        }

        @Override
        public void updateBytesUsed(int used) {
        }
    }, write_controllers.size() > 1);
    lan_download_processor = new TransferProcessor(TransferProcessor.TYPE_DOWNLOAD, new LimitedRateGroup() {

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

        @Override
        public int getRateLimitBytesPerSecond() {
            return max_lan_download_rate_bps;
        }

        @Override
        public boolean isDisabled() {
            return (max_lan_download_rate_bps == -1);
        }

        @Override
        public void updateBytesUsed(int used) {
        }
    }, read_controllers.size() > 1);
    HTTPNetworkManager.getSingleton();
    refreshRates();
    _core.getGlobalManager().addListener(new GlobalManagerAdapter() {

        @Override
        public void seedingStatusChanged(boolean seeding_only, boolean b) {
            seeding_only_mode = seeding_only;
            refreshRates();
        }
    });
    core = _core;
}
Also used : GlobalManagerAdapter(com.biglybt.core.global.GlobalManagerAdapter)

Aggregations

GlobalManagerAdapter (com.biglybt.core.global.GlobalManagerAdapter)7 DownloadManager (com.biglybt.core.download.DownloadManager)5 ParameterListener (com.biglybt.core.config.ParameterListener)3 GlobalManager (com.biglybt.core.global.GlobalManager)3 Category (com.biglybt.core.category.Category)2 CategoryListener (com.biglybt.core.category.CategoryListener)2 TOTorrent (com.biglybt.core.torrent.TOTorrent)2 File (java.io.File)2 CategoryManagerListener (com.biglybt.core.category.CategoryManagerListener)1 DHT (com.biglybt.core.dht.DHT)1 DHTListener (com.biglybt.core.dht.DHTListener)1 DHTSpeedTester (com.biglybt.core.dht.speed.DHTSpeedTester)1 DownloadManagerAdapter (com.biglybt.core.download.impl.DownloadManagerAdapter)1 GlobalManagerListener (com.biglybt.core.global.GlobalManagerListener)1 LogAlert (com.biglybt.core.logging.LogAlert)1 LogEvent (com.biglybt.core.logging.LogEvent)1 NetworkAdmin (com.biglybt.core.networkmanager.admin.NetworkAdmin)1 NetworkAdminPropertyChangeListener (com.biglybt.core.networkmanager.admin.NetworkAdminPropertyChangeListener)1 TOTorrentException (com.biglybt.core.torrent.TOTorrentException)1 TOTorrentFile (com.biglybt.core.torrent.TOTorrentFile)1