Search in sources :

Example 6 with BasicPluginConfigModel

use of com.biglybt.pif.ui.model.BasicPluginConfigModel 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 7 with BasicPluginConfigModel

use of com.biglybt.pif.ui.model.BasicPluginConfigModel in project BiglyBT by BiglySoftware.

the class LocalTrackerPlugin method initialize.

@Override
public void initialize(PluginInterface _plugin_interface) {
    plugin_interface = _plugin_interface;
    ta_networks = plugin_interface.getTorrentManager().getAttribute(TorrentAttribute.TA_NETWORKS);
    ta_peer_sources = plugin_interface.getTorrentManager().getAttribute(TorrentAttribute.TA_PEER_SOURCES);
    mon = plugin_interface.getUtilities().getMonitor();
    log = plugin_interface.getLogger().getTimeStampedChannel(PLUGIN_NAME);
    UIManager ui_manager = plugin_interface.getUIManager();
    BasicPluginConfigModel config = ui_manager.createBasicPluginConfigModel(ConfigSection.SECTION_PLUGINS, PLUGIN_CONFIGSECTION_ID);
    config.addLabelParameter2("Plugin.localtracker.info");
    enabled = config.addBooleanParameter2("Plugin.localtracker.enable", "Plugin.localtracker.enable", true);
    config.addLabelParameter2("Plugin.localtracker.networks.info");
    final StringParameter subnets = config.addStringParameter2("Plugin.localtracker.networks", "Plugin.localtracker.networks", "");
    final BooleanParameter include_wellknown = config.addBooleanParameter2("Plugin.localtracker.wellknownlocals", "Plugin.localtracker.wellknownlocals", true);
    config.addLabelParameter2("Plugin.localtracker.autoadd.info");
    final StringParameter autoadd = config.addStringParameter2("Plugin.localtracker.autoadd", "Plugin.localtracker.autoadd", "");
    /*
		 * actually these parameters affect LAN detection as a whole, not just the local tracker,
		 * so leave them enabled...
		 *
		enabled.addEnabledOnSelection( lp1 );
		enabled.addEnabledOnSelection( subnets );
		enabled.addEnabledOnSelection( lp2 );
		enabled.addEnabledOnSelection( autoadd );
		*/
    final BasicPluginViewModel view_model = plugin_interface.getUIManager().createBasicPluginViewModel("Plugin.localtracker.name");
    view_model.setConfigSectionID(PLUGIN_CONFIGSECTION_ID);
    view_model.getActivity().setVisible(false);
    view_model.getProgress().setVisible(false);
    log.addListener(new LoggerChannelListener() {

        @Override
        public void messageLogged(int type, String content) {
            view_model.getLogArea().appendText(content + "\n");
        }

        @Override
        public void messageLogged(String str, Throwable error) {
            if (str.length() > 0) {
                view_model.getLogArea().appendText(str + "\n");
            }
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            error.printStackTrace(pw);
            pw.flush();
            view_model.getLogArea().appendText(sw.toString() + "\n");
        }
    });
    plugin_start_time = plugin_interface.getUtilities().getCurrentSystemTime();
    // Assume we have a core, since this is a plugin
    instance_manager = CoreFactory.getSingleton().getInstanceManager();
    instance_manager.addListener(this);
    plugin_interface.getPluginconfig().addListener(new PluginConfigListener() {

        @Override
        public void configSaved() {
            processSubNets(subnets.getValue(), include_wellknown.getValue());
            processAutoAdd(autoadd.getValue());
        }
    });
    processSubNets(subnets.getValue(), include_wellknown.getValue());
    processAutoAdd(autoadd.getValue());
    final DelayedTask dt = plugin_interface.getUtilities().createDelayedTask(new Runnable() {

        @Override
        public void run() {
            plugin_interface.getDownloadManager().addListener(LocalTrackerPlugin.this);
        }
    });
    dt.queue();
}
Also used : StringParameter(com.biglybt.pif.ui.config.StringParameter) LoggerChannelListener(com.biglybt.pif.logging.LoggerChannelListener) UIManager(com.biglybt.pif.ui.UIManager) PluginConfigListener(com.biglybt.pif.PluginConfigListener) BasicPluginViewModel(com.biglybt.pif.ui.model.BasicPluginViewModel) BooleanParameter(com.biglybt.pif.ui.config.BooleanParameter) StringWriter(java.io.StringWriter) DelayedTask(com.biglybt.pif.utils.DelayedTask) BasicPluginConfigModel(com.biglybt.pif.ui.model.BasicPluginConfigModel) PrintWriter(java.io.PrintWriter)

Example 8 with BasicPluginConfigModel

use of com.biglybt.pif.ui.model.BasicPluginConfigModel in project BiglyBT by BiglySoftware.

the class UPnPPlugin method initialize.

@Override
public void initialize(PluginInterface _plugin_interface) {
    plugin_interface = _plugin_interface;
    log = plugin_interface.getLogger().getTimeStampedChannel("UPnP");
    log.setDiagnostic();
    log.setForce(true);
    UIManager ui_manager = plugin_interface.getUIManager();
    final BasicPluginViewModel model = ui_manager.createBasicPluginViewModel("UPnP");
    model.setConfigSectionID(UPNP_PLUGIN_CONFIGSECTION_ID);
    BasicPluginConfigModel upnp_config = ui_manager.createBasicPluginConfigModel(ConfigSection.SECTION_PLUGINS, UPNP_PLUGIN_CONFIGSECTION_ID);
    // NATPMP
    BasicPluginConfigModel natpmp_config = ui_manager.createBasicPluginConfigModel(UPNP_PLUGIN_CONFIGSECTION_ID, NATPMP_PLUGIN_CONFIGSECTION_ID);
    natpmp_config.addLabelParameter2("natpmp.info");
    ActionParameter natpmp_wiki = natpmp_config.addActionParameter2("Utils.link.visit", "MainWindow.about.internet.wiki");
    natpmp_wiki.setStyle(ActionParameter.STYLE_LINK);
    natpmp_wiki.addListener(new ParameterListener() {

        @Override
        public void parameterChanged(Parameter param) {
            try {
                plugin_interface.getUIManager().openURL(new URL(Constants.URL_WIKI + "w/NATPMP"));
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    });
    natpmp_enable_param = natpmp_config.addBooleanParameter2("natpmp.enable", "natpmp.enable", false);
    nat_pmp_router = natpmp_config.addStringParameter2("natpmp.routeraddress", "natpmp.routeraddress", "");
    natpmp_enable_param.addListener(new ParameterListener() {

        @Override
        public void parameterChanged(Parameter param) {
            setNATPMPEnableState();
        }
    });
    natpmp_enable_param.addEnabledOnSelection(nat_pmp_router);
    // UPNP
    upnp_config.addLabelParameter2("upnp.info");
    upnp_config.addHyperlinkParameter2("upnp.wiki_link", Constants.URL_WIKI + "w/UPnP");
    upnp_enable_param = upnp_config.addBooleanParameter2("upnp.enable", "upnp.enable", true);
    grab_ports_param = upnp_config.addBooleanParameter2("upnp.grabports", "upnp.grabports", false);
    release_mappings_param = upnp_config.addBooleanParameter2("upnp.releasemappings", "upnp.releasemappings", true);
    ActionParameter refresh_param = upnp_config.addActionParameter2("upnp.refresh.label", "upnp.refresh.button");
    refresh_param.addListener(new ParameterListener() {

        @Override
        public void parameterChanged(Parameter param) {
            UPnPPlugin.this.refreshMappings();
        }
    });
    // Auto-refresh mappings every minute when enabled.
    final BooleanParameter auto_refresh_on_bad_nat_param = upnp_config.addBooleanParameter2("upnp.refresh_on_bad_nat", "upnp.refresh_mappings_on_bad_nat", false);
    plugin_interface.getUtilities().createTimer("upnp mapping auto-refresh", true).addPeriodicEvent(1 * 60 * 1000, new UTTimerEventPerformer() {

        private long last_bad_nat = 0;

        @Override
        public void perform(UTTimerEvent event) {
            if (upnp == null) {
                return;
            }
            if (!auto_refresh_on_bad_nat_param.getValue()) {
                return;
            }
            if (!upnp_enable_param.getValue()) {
                return;
            }
            int status = plugin_interface.getConnectionManager().getNATStatus();
            if (status == ConnectionManager.NAT_BAD) {
                // Only try to refresh the mappings if this is the first bad NAT
                // message we've been given in the last 15 minutes - we don't want
                // to endlessly retry performing the mappings
                long now = plugin_interface.getUtilities().getCurrentSystemTime();
                if (last_bad_nat + (15 * 60 * 1000) < now) {
                    last_bad_nat = now;
                    log.log(LoggerChannel.LT_WARNING, "NAT status is firewalled - trying to refresh UPnP mappings");
                    refreshMappings(true);
                }
            }
        }
    });
    upnp_config.addLabelParameter2("blank.resource");
    alert_success_param = upnp_config.addBooleanParameter2("upnp.alertsuccess", "upnp.alertsuccess", false);
    alert_other_port_param = upnp_config.addBooleanParameter2("upnp.alertothermappings", "upnp.alertothermappings", true);
    alert_device_probs_param = upnp_config.addBooleanParameter2("upnp.alertdeviceproblems", "upnp.alertdeviceproblems", true);
    selected_interfaces_param = upnp_config.addStringParameter2("upnp.selectedinterfaces", "upnp.selectedinterfaces", "");
    selected_interfaces_param.setGenerateIntermediateEvents(false);
    selected_addresses_param = upnp_config.addStringParameter2("upnp.selectedaddresses", "upnp.selectedaddresses", "");
    selected_addresses_param.setGenerateIntermediateEvents(false);
    desc_prefix_param = upnp_config.addStringParameter2("upnp.descprefix", "upnp.descprefix", Constants.APP_NAME + " UPnP");
    desc_prefix_param.setGenerateIntermediateEvents(false);
    ignore_bad_devices = upnp_config.addBooleanParameter2("upnp.ignorebaddevices", "upnp.ignorebaddevices", true);
    ignored_devices_list = upnp_config.addLabelParameter2("upnp.ignorebaddevices.info");
    ActionParameter reset_param = upnp_config.addActionParameter2("upnp.ignorebaddevices.reset", "upnp.ignorebaddevices.reset.action");
    reset_param.addListener(new ParameterListener() {

        @Override
        public void parameterChanged(Parameter param) {
            PluginConfig pc = plugin_interface.getPluginconfig();
            for (int i = 0; i < STATS_KEYS.length; i++) {
                String key = "upnp.device.stats." + STATS_KEYS[i];
                pc.setPluginMapParameter(key, new HashMap());
            }
            pc.setPluginMapParameter("upnp.device.ignorelist", new HashMap());
            updateIgnoreList();
        }
    });
    trace_to_log = upnp_config.addBooleanParameter2("upnp.trace_to_log", "upnp.trace_to_log", false);
    final boolean enabled = upnp_enable_param.getValue();
    upnp_enable_param.addEnabledOnSelection(alert_success_param);
    upnp_enable_param.addEnabledOnSelection(grab_ports_param);
    upnp_enable_param.addEnabledOnSelection(refresh_param);
    auto_refresh_on_bad_nat_param.addEnabledOnSelection(refresh_param);
    upnp_enable_param.addEnabledOnSelection(alert_other_port_param);
    upnp_enable_param.addEnabledOnSelection(alert_device_probs_param);
    upnp_enable_param.addEnabledOnSelection(release_mappings_param);
    upnp_enable_param.addEnabledOnSelection(selected_interfaces_param);
    upnp_enable_param.addEnabledOnSelection(selected_addresses_param);
    upnp_enable_param.addEnabledOnSelection(desc_prefix_param);
    upnp_enable_param.addEnabledOnSelection(ignore_bad_devices);
    upnp_enable_param.addEnabledOnSelection(ignored_devices_list);
    upnp_enable_param.addEnabledOnSelection(reset_param);
    upnp_enable_param.addEnabledOnSelection(trace_to_log);
    natpmp_enable_param.setEnabled(enabled);
    model.getStatus().setText(enabled ? "Running" : "Disabled");
    upnp_enable_param.addListener(new ParameterListener() {

        @Override
        public void parameterChanged(Parameter p) {
            boolean e = upnp_enable_param.getValue();
            natpmp_enable_param.setEnabled(e);
            model.getStatus().setText(e ? "Running" : "Disabled");
            if (e) {
                startUp();
            } else {
                closeDown(true);
            }
            setNATPMPEnableState();
        }
    });
    model.getActivity().setVisible(false);
    model.getProgress().setVisible(false);
    log.addListener(new LoggerChannelListener() {

        @Override
        public void messageLogged(int type, String message) {
            model.getLogArea().appendText(message + "\n");
        }

        @Override
        public void messageLogged(String str, Throwable error) {
            model.getLogArea().appendText(error.toString() + "\n");
        }
    });
    // startup() used to be called on initializationComplete()
    // Moved to delayed task because rootDeviceFound can take
    // a lot of CPU cycle.  Let's hope nothing breaks
    DelayedTask dt = plugin_interface.getUtilities().createDelayedTask(new Runnable() {

        @Override
        public void run() {
            if (enabled) {
                updateIgnoreList();
                startUp();
            }
        }
    });
    dt.queue();
    plugin_interface.addListener(new PluginListener() {

        @Override
        public void initializationComplete() {
        }

        @Override
        public void closedownInitiated() {
            if (services.size() == 0) {
                plugin_interface.getPluginconfig().setPluginParameter("plugin.info", "");
            }
        }

        @Override
        public void closedownComplete() {
            closeDown(true);
        }
    });
}
Also used : LoggerChannelListener(com.biglybt.pif.logging.LoggerChannelListener) UTTimerEvent(com.biglybt.pif.utils.UTTimerEvent) UIManager(com.biglybt.pif.ui.UIManager) BasicPluginViewModel(com.biglybt.pif.ui.model.BasicPluginViewModel) URL(java.net.URL) PluginListener(com.biglybt.pif.PluginListener) PluginConfig(com.biglybt.pif.PluginConfig) DelayedTask(com.biglybt.pif.utils.DelayedTask) BasicPluginConfigModel(com.biglybt.pif.ui.model.BasicPluginConfigModel) UTTimerEventPerformer(com.biglybt.pif.utils.UTTimerEventPerformer)

Example 9 with BasicPluginConfigModel

use of com.biglybt.pif.ui.model.BasicPluginConfigModel in project BiglyBT by BiglySoftware.

the class DownloadRemoveRulesPlugin method initialize.

@Override
public void initialize(PluginInterface _plugin_interface) {
    plugin_interface = _plugin_interface;
    log = plugin_interface.getLogger().getChannel("DLRemRules");
    BasicPluginConfigModel config = plugin_interface.getUIManager().createBasicPluginConfigModel("torrents", "download.removerules.name");
    config.addLabelParameter2("download.removerules.unauthorised.info");
    remove_unauthorised = config.addBooleanParameter2("download.removerules.unauthorised", "download.removerules.unauthorised", false);
    remove_unauthorised_seeding_only = config.addBooleanParameter2("download.removerules.unauthorised.seedingonly", "download.removerules.unauthorised.seedingonly", true);
    remove_unauthorised_data = config.addBooleanParameter2("download.removerules.unauthorised.data", "download.removerules.unauthorised.data", false);
    remove_unauthorised.addEnabledOnSelection(remove_unauthorised_seeding_only);
    remove_unauthorised.addEnabledOnSelection(remove_unauthorised_data);
    remove_update_torrents = config.addBooleanParameter2("download.removerules.updatetorrents", "download.removerules.updatetorrents", true);
    new DelayedEvent("DownloadRemovalRules", INITIAL_DELAY, new AERunnable() {

        @Override
        public void runSupport() {
            plugin_interface.getDownloadManager().addListener(DownloadRemoveRulesPlugin.this);
        }
    });
}
Also used : AERunnable(com.biglybt.core.util.AERunnable) DelayedEvent(com.biglybt.core.util.DelayedEvent) BasicPluginConfigModel(com.biglybt.pif.ui.model.BasicPluginConfigModel)

Example 10 with BasicPluginConfigModel

use of com.biglybt.pif.ui.model.BasicPluginConfigModel in project BiglyBT by BiglySoftware.

the class RSSGeneratorPlugin method initStage.

@Override
protected void initStage(int num) {
    if (num == 1) {
        BasicPluginConfigModel config = getConfigModel();
        test_param = config.addHyperlinkParameter2("rss.internal.test.url", "");
        enable_low_noise = config.addBooleanParameter2("rss.internal.enable.low.noise", "rss.internal.enable.low.noise", true);
        test_param.setEnabled(isPluginEnabled());
    }
}
Also used : BasicPluginConfigModel(com.biglybt.pif.ui.model.BasicPluginConfigModel)

Aggregations

BasicPluginConfigModel (com.biglybt.pif.ui.model.BasicPluginConfigModel)18 PluginListener (com.biglybt.pif.PluginListener)6 UIManager (com.biglybt.pif.ui.UIManager)6 LoggerChannelListener (com.biglybt.pif.logging.LoggerChannelListener)5 BasicPluginViewModel (com.biglybt.pif.ui.model.BasicPluginViewModel)5 UIInstance (com.biglybt.pif.ui.UIInstance)4 UIManagerListener (com.biglybt.pif.ui.UIManagerListener)4 AERunnable (com.biglybt.core.util.AERunnable)3 BooleanParameter (com.biglybt.pif.ui.config.BooleanParameter)3 DelayedTask (com.biglybt.pif.utils.DelayedTask)3 PluginInterface (com.biglybt.pif.PluginInterface)2 Torrent (com.biglybt.pif.torrent.Torrent)2 ParameterListener (com.biglybt.pif.ui.config.ParameterListener)2 UTTimerEvent (com.biglybt.pif.utils.UTTimerEvent)2 UTTimerEventPerformer (com.biglybt.pif.utils.UTTimerEventPerformer)2 File (java.io.File)2 InetSocketAddress (java.net.InetSocketAddress)2 URL (java.net.URL)2 ParameterListener (com.biglybt.core.config.ParameterListener)1 DHT (com.biglybt.core.dht.DHT)1