Search in sources :

Example 6 with LoggerChannelListener

use of com.biglybt.pif.logging.LoggerChannelListener 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 7 with LoggerChannelListener

use of com.biglybt.pif.logging.LoggerChannelListener in project BiglyBT by BiglySoftware.

the class WebPlugin method initialize.

@Override
public void initialize(PluginInterface _plugin_interface) throws PluginException {
    plugin_interface = _plugin_interface;
    plugin_config = plugin_interface.getPluginconfig();
    Properties plugin_properties = plugin_interface.getPluginProperties();
    if (plugin_properties != null) {
        Object o = plugin_properties.get("plugin." + PR_ROOT_DIR.replaceAll(" ", "_"));
        if (o instanceof String) {
            properties.put(PR_ROOT_DIR, o);
        }
    }
    Boolean pr_enable = (Boolean) properties.get(PR_ENABLE);
    if (pr_enable != null) {
        CONFIG_ENABLE_DEFAULT = pr_enable.booleanValue();
    }
    Integer pr_port = (Integer) properties.get(PR_PORT);
    if (pr_port != null) {
        CONFIG_PORT_DEFAULT = pr_port.intValue();
    }
    String pr_bind_ip = (String) properties.get(PR_BIND_IP);
    if (pr_bind_ip != null) {
        CONFIG_BIND_IP_DEFAULT = pr_bind_ip.trim();
    }
    String pr_root_resource = (String) properties.get(PR_ROOT_RESOURCE);
    if (pr_root_resource != null) {
        CONFIG_ROOT_RESOURCE_DEFAULT = pr_root_resource;
    }
    String pr_home_page = (String) properties.get(PR_HOME_PAGE);
    if (pr_home_page != null) {
        CONFIG_HOME_PAGE_DEFAULT = pr_home_page;
    }
    String pr_root_dir = (String) properties.get(PR_ROOT_DIR);
    if (pr_root_dir != null) {
        CONFIG_ROOT_DIR_DEFAULT = pr_root_dir;
    }
    String pr_access = (String) properties.get(PR_ACCESS);
    if (pr_access != null) {
        CONFIG_ACCESS_DEFAULT = pr_access;
    }
    Boolean pr_enable_upnp = (Boolean) properties.get(PR_ENABLE_UPNP);
    if (pr_enable_upnp != null) {
        CONFIG_UPNP_ENABLE_DEFAULT = pr_enable_upnp.booleanValue();
    }
    Boolean pr_hide_resource_config = (Boolean) properties.get(PR_HIDE_RESOURCE_CONFIG);
    log = (LoggerChannel) properties.get(PR_LOG);
    if (log == null) {
        log = plugin_interface.getLogger().getChannel("WebPlugin");
    }
    Boolean prop_pairing_enable = (Boolean) properties.get(PR_ENABLE_PAIRING);
    if (prop_pairing_enable == null || prop_pairing_enable) {
        // default is based on sid availability
        p_sid = (String) properties.get(PR_PAIRING_SID);
    }
    UIManager ui_manager = plugin_interface.getUIManager();
    view_model = (BasicPluginViewModel) properties.get(PR_VIEW_MODEL);
    if (view_model == null) {
        view_model = ui_manager.createBasicPluginViewModel(plugin_interface.getPluginName());
    }
    String plugin_id = plugin_interface.getPluginID();
    String sConfigSectionID = "plugins." + plugin_id;
    view_model.setConfigSectionID(sConfigSectionID);
    view_model.getStatus().setText("Running");
    view_model.getActivity().setVisible(false);
    view_model.getProgress().setVisible(false);
    log.addListener(new LoggerChannelListener() {

        @Override
        public void messageLogged(int type, String message) {
            log(message + "\n");
        }

        @Override
        public void messageLogged(String str, Throwable error) {
            log(str + "\n");
            log(error.toString() + "\n");
        }

        private void log(String str) {
            UITextArea area = view_model.getLogArea();
            if (area != null) {
                area.appendText(str);
            }
        }
    });
    config_model = (BasicPluginConfigModel) properties.get(PR_CONFIG_MODEL);
    if (config_model == null) {
        String[] cm_params = (String[]) properties.get(PR_CONFIG_MODEL_PARAMS);
        if (cm_params == null || cm_params.length == 0) {
            config_model = ui_manager.createBasicPluginConfigModel(ConfigSection.SECTION_PLUGINS, sConfigSectionID);
        } else if (cm_params.length == 1) {
            config_model = ui_manager.createBasicPluginConfigModel(cm_params[0]);
        } else {
            config_model = ui_manager.createBasicPluginConfigModel(cm_params[0], cm_params[1]);
        }
    }
    /* removed 2017/12/01 - no longer needed 
	
		boolean	save_needed = false;

		if ( !plugin_config.getPluginBooleanParameter( CONFIG_MIGRATED, false )){

			plugin_config.setPluginParameter( CONFIG_MIGRATED, true );

			save_needed	= true;

			plugin_config.setPluginParameter(
					CONFIG_PASSWORD_ENABLE,
					plugin_config.getUnsafeBooleanParameter(
							"Tracker Password Enable Web", CONFIG_PASSWORD_ENABLE_DEFAULT ));

			plugin_config.setPluginParameter(
					CONFIG_USER,
					plugin_config.getUnsafeStringParameter(
							"Tracker Username", CONFIG_USER_DEFAULT ));

			plugin_config.setPluginParameter(
					CONFIG_PASSWORD,
					plugin_config.getUnsafeByteParameter(
							"Tracker Password", CONFIG_PASSWORD_DEFAULT ));

		}

		if ( !plugin_config.getPluginBooleanParameter( PROPERTIES_MIGRATED, false )){

			plugin_config.setPluginParameter( PROPERTIES_MIGRATED, true );

			Properties	props = plugin_interface.getPluginProperties();

				// make sure we've got an old properties file too

			if ( props.getProperty( "port", "" ).length() > 0 ){

				save_needed = true;

				String	prop_port		= props.getProperty( "port",			""+CONFIG_PORT_DEFAULT );
				String	prop_protocol	= props.getProperty( "protocol", 		CONFIG_PROTOCOL_DEFAULT );
				String	prop_home		= props.getProperty( "homepage", 		CONFIG_HOME_PAGE_DEFAULT );
				String	prop_rootdir	= props.getProperty( "rootdir", 		CONFIG_ROOT_DIR_DEFAULT );
				String	prop_rootres	= props.getProperty( "rootresource", 	CONFIG_ROOT_RESOURCE_DEFAULT );
				String	prop_mode		= props.getProperty( "mode", 			CONFIG_MODE_DEFAULT );
				String	prop_access		= props.getProperty( "access", 			CONFIG_ACCESS_DEFAULT );

				int	prop_port_int = CONFIG_PORT_DEFAULT;

				try{
					prop_port_int	= Integer.parseInt( prop_port );

				}catch( Throwable e ){
				}

				plugin_config.setPluginParameter(CONFIG_PORT, prop_port_int );
				plugin_config.setPluginParameter(CONFIG_PROTOCOL, prop_protocol );
				plugin_config.setPluginParameter(CONFIG_HOME_PAGE, prop_home );
				plugin_config.setPluginParameter(CONFIG_ROOT_DIR, prop_rootdir );
				plugin_config.setPluginParameter(CONFIG_ROOT_RESOURCE, prop_rootres );
				plugin_config.setPluginParameter(CONFIG_MODE, prop_mode );
				plugin_config.setPluginParameter(CONFIG_ACCESS, prop_access );

				File	props_file = new File( plugin_interface.getPluginDirectoryName(), "plugin.properties" );

				PrintWriter pw = null;

				try{
					File	backup = new File( plugin_interface.getPluginDirectoryName(), "plugin.properties.bak" );

					props_file.renameTo( backup );

					pw = new PrintWriter( new FileWriter( props_file ));

					pw.println( "plugin.class=" + props.getProperty( "plugin.class" ));
					pw.println( "plugin.name=" + props.getProperty( "plugin.name" ));
					pw.println( "plugin.version=" + props.getProperty( "plugin.version" ));
					pw.println( "plugin.id=" + props.getProperty( "plugin.id" ));
					pw.println( "" );
					pw.println( "# configuration has been migrated to plugin config - see view->config->plugins" );
					pw.println( "# in the SWT user interface" );

					log.logAlert( 	LoggerChannel.LT_INFORMATION,
							plugin_interface.getPluginName() + " - plugin.properties settings migrated to plugin configuration." );

				}catch( Throwable  e ){

					Debug.printStackTrace( e );

					log.logAlert( 	LoggerChannel.LT_ERROR,
									plugin_interface.getPluginName() + " - plugin.properties settings migration failed." );

				}finally{

					if ( pw != null ){

						pw.close();
					}
				}
			}
		}

		if ( save_needed ){

			plugin_config.save();
		}
		*/
    Boolean disablable = (Boolean) properties.get(PR_DISABLABLE);
    final BooleanParameter param_enable;
    if (disablable != null && disablable) {
        param_enable = config_model.addBooleanParameter2(CONFIG_ENABLE, "webui.enable", CONFIG_ENABLE_DEFAULT);
        plugin_enabled = param_enable.getValue();
    } else {
        param_enable = null;
        plugin_enabled = true;
    }
    initStage(1);
    // connection group
    param_port = config_model.addIntParameter2(CONFIG_PORT, "webui.port", CONFIG_PORT_DEFAULT);
    param_port.setGenerateIntermediateEvents(false);
    param_bind = config_model.addStringParameter2(CONFIG_BIND_IP, "webui.bindip", CONFIG_BIND_IP_DEFAULT);
    param_bind.setGenerateIntermediateEvents(false);
    param_protocol = config_model.addStringListParameter2(CONFIG_PROTOCOL, "webui.protocol", new String[] { "http", "https" }, CONFIG_PROTOCOL_DEFAULT);
    param_protocol.setGenerateIntermediateEvents(false);
    ParameterListener update_server_listener = new ParameterListener() {

        @Override
        public void parameterChanged(Parameter param) {
            setupServer();
        }
    };
    param_port.addListener(update_server_listener);
    param_bind.addListener(update_server_listener);
    param_protocol.addListener(update_server_listener);
    param_i2p_dest = config_model.addInfoParameter2("webui.i2p_dest", "");
    param_i2p_dest.setVisible(false);
    param_tor_dest = config_model.addInfoParameter2("webui.tor_dest", "");
    param_tor_dest.setVisible(false);
    if (param_enable != null) {
        COConfigurationManager.registerExportedParameter(plugin_id + ".enable", param_enable.getConfigKeyName());
    }
    COConfigurationManager.registerExportedParameter(plugin_id + ".port", param_port.getConfigKeyName());
    COConfigurationManager.registerExportedParameter(plugin_id + ".protocol", param_protocol.getConfigKeyName());
    p_upnp_enable = config_model.addBooleanParameter2(CONFIG_UPNP_ENABLE, "webui.upnpenable", CONFIG_UPNP_ENABLE_DEFAULT);
    p_upnp_enable.addListener(new ParameterListener() {

        @Override
        public void parameterChanged(Parameter param) {
            setupUPnP();
        }
    });
    plugin_interface.addListener(new PluginListener() {

        @Override
        public void initializationComplete() {
            setupUPnP();
        }

        @Override
        public void closedownInitiated() {
        }

        @Override
        public void closedownComplete() {
        }
    });
    final LabelParameter pairing_info;
    final BooleanParameter pairing_enable;
    final HyperlinkParameter pairing_test;
    final HyperlinkParameter connection_test;
    if (p_sid != null) {
        final PairingManager pm = PairingManagerFactory.getSingleton();
        pairing_info = config_model.addLabelParameter2("webui.pairing.info." + (pm.isEnabled() ? "y" : "n"));
        pairing_enable = config_model.addBooleanParameter2(CONFIG_PAIRING_ENABLE, "webui.pairingenable", CONFIG_PAIRING_ENABLE_DEFAULT);
        if (!plugin_config.getPluginBooleanParameter(PAIRING_MIGRATED, false)) {
            // if they already have a password, don't override it by setting auto-auth
            boolean has_pw_enabled = plugin_config.getPluginBooleanParameter(CONFIG_PASSWORD_ENABLE, CONFIG_PASSWORD_ENABLE_DEFAULT);
            if (has_pw_enabled) {
                plugin_config.setPluginParameter(CONFIG_PAIRING_AUTO_AUTH, false);
            }
            plugin_config.setPluginParameter(PAIRING_MIGRATED, true);
        }
        param_port_or = config_model.addIntParameter2(CONFIG_PORT_OVERRIDE, "webui.port.override", 0);
        param_auto_auth = config_model.addBooleanParameter2(CONFIG_PAIRING_AUTO_AUTH, "webui.pairing.autoauth", CONFIG_PAIRING_AUTO_AUTH_DEFAULT);
        param_auto_auth.addListener(new ParameterListener() {

            @Override
            public void parameterChanged(Parameter param) {
                if (pairing_enable.getValue() && pm.isEnabled()) {
                    setupAutoAuth();
                } else {
                    setupSessionCode(null);
                }
            }
        });
        connection_test = config_model.addHyperlinkParameter2("webui.connectiontest", getConnectionTestURL(p_sid));
        pairing_test = config_model.addHyperlinkParameter2("webui.pairingtest", "http://remote.vuze.com/?sid=" + p_sid);
        // listeners setup later as they depend on userame params etc
        String sid_key = "Plugin." + plugin_id + ".pairing.sid";
        COConfigurationManager.setStringDefault(sid_key, p_sid);
        COConfigurationManager.registerExportedParameter(plugin_id + ".pairing.sid", sid_key);
        COConfigurationManager.registerExportedParameter(plugin_id + ".pairing.enable", pairing_enable.getConfigKeyName());
        COConfigurationManager.registerExportedParameter(plugin_id + ".pairing.auto_auth", param_auto_auth.getConfigKeyName());
    } else {
        pairing_info = null;
        pairing_enable = null;
        param_auto_auth = null;
        param_port_or = null;
        pairing_test = null;
        connection_test = null;
    }
    config_model.createGroup("ConfigView.section.Pairing", new Parameter[] { pairing_info, pairing_enable, param_port_or, param_auto_auth, connection_test, pairing_test });
    config_model.createGroup("ConfigView.section.server", new Parameter[] { param_port, param_bind, param_protocol, param_i2p_dest, param_tor_dest, p_upnp_enable });
    param_home = config_model.addStringParameter2(CONFIG_HOME_PAGE, "webui.homepage", CONFIG_HOME_PAGE_DEFAULT);
    param_rootdir = config_model.addStringParameter2(CONFIG_ROOT_DIR, "webui.rootdir", CONFIG_ROOT_DIR_DEFAULT);
    param_rootres = config_model.addStringParameter2(CONFIG_ROOT_RESOURCE, "webui.rootres", CONFIG_ROOT_RESOURCE_DEFAULT);
    if (pr_hide_resource_config != null && pr_hide_resource_config.booleanValue()) {
        param_home.setVisible(false);
        param_rootdir.setVisible(false);
        param_rootres.setVisible(false);
    } else {
        ParameterListener update_resources_listener = new ParameterListener() {

            @Override
            public void parameterChanged(Parameter param) {
                setupResources();
            }
        };
        param_home.addListener(update_resources_listener);
        param_rootdir.addListener(update_resources_listener);
        param_rootres.addListener(update_resources_listener);
    }
    // access group
    LabelParameter a_label1 = config_model.addLabelParameter2("webui.mode.info");
    StringListParameter param_mode = config_model.addStringListParameter2(CONFIG_MODE, "webui.mode", new String[] { "full", "view" }, CONFIG_MODE_DEFAULT);
    LabelParameter a_label2 = config_model.addLabelParameter2("webui.access.info");
    param_access = config_model.addStringParameter2(CONFIG_ACCESS, "webui.access", CONFIG_ACCESS_DEFAULT);
    param_access.addListener(new ParameterListener() {

        @Override
        public void parameterChanged(Parameter param) {
            setupAccess();
        }
    });
    pw_enable = config_model.addBooleanParameter2(CONFIG_PASSWORD_ENABLE, "webui.passwordenable", CONFIG_PASSWORD_ENABLE_DEFAULT);
    p_user_name = config_model.addStringParameter2(CONFIG_USER, "webui.user", CONFIG_USER_DEFAULT);
    p_password = config_model.addPasswordParameter2(CONFIG_PASSWORD, "webui.password", PasswordParameter.ET_SHA1, CONFIG_PASSWORD_DEFAULT);
    p_no_pw_whitelist = config_model.addStringParameter2(CONFIG_NO_PW_WHITELIST, "webui.nopwwhitelist", CONFIG_NO_PW_WHITELIST_DEFAULT);
    pw_enable.addEnabledOnSelection(p_user_name);
    pw_enable.addEnabledOnSelection(p_password);
    pw_enable.addDisabledOnSelection(p_no_pw_whitelist);
    ParameterListener auth_change_listener = new ParameterListener() {

        @Override
        public void parameterChanged(Parameter param) {
            if (param_auto_auth != null) {
                if (!setting_auto_auth) {
                    log("Disabling pairing auto-authentication as overridden by user");
                    param_auto_auth.setValue(false);
                }
            }
            if (param == p_user_name || param == p_password) {
                setupSessionCode(null);
            }
        }
    };
    p_user_name.addListener(auth_change_listener);
    p_password.addListener(auth_change_listener);
    pw_enable.addListener(auth_change_listener);
    config_model.createGroup("webui.group.access", new Parameter[] { a_label1, param_mode, a_label2, param_access, pw_enable, p_user_name, p_password, p_no_pw_whitelist });
    if (p_sid != null) {
        final PairingManager pm = PairingManagerFactory.getSingleton();
        pairing_enable.addListener(new ParameterListener() {

            @Override
            public void parameterChanged(Parameter param) {
                boolean enabled = pairing_enable.getValue();
                param_auto_auth.setEnabled(pm.isEnabled() && enabled);
                param_port_or.setEnabled(pm.isEnabled() && enabled);
                boolean test_ok = pm.isEnabled() && pairing_enable.getValue() && pm.peekAccessCode() != null && !pm.hasActionOutstanding();
                pairing_test.setEnabled(test_ok);
                connection_test.setEnabled(test_ok);
                setupPairing(p_sid, enabled);
            }
        });
        pairing_listener = new PairingManagerListener() {

            @Override
            public void somethingChanged(PairingManager pm) {
                pairing_info.setLabelKey("webui.pairing.info." + (pm.isEnabled() ? "y" : "n"));
                if (plugin_enabled) {
                    pairing_enable.setEnabled(pm.isEnabled());
                    param_auto_auth.setEnabled(pm.isEnabled() && pairing_enable.getValue());
                    param_port_or.setEnabled(pm.isEnabled() && pairing_enable.getValue());
                    boolean test_ok = pm.isEnabled() && pairing_enable.getValue() && pm.peekAccessCode() != null && !pm.hasActionOutstanding();
                    pairing_test.setEnabled(test_ok);
                    connection_test.setEnabled(test_ok);
                }
                connection_test.setHyperlink(getConnectionTestURL(p_sid));
                setupPairing(p_sid, pairing_enable.getValue());
            }
        };
        pairing_listener.somethingChanged(pm);
        pm.addListener(pairing_listener);
        setupPairing(p_sid, pairing_enable.getValue());
        ParameterListener update_pairing_listener = new ParameterListener() {

            @Override
            public void parameterChanged(Parameter param) {
                updatePairing(p_sid);
                setupUPnP();
            }
        };
        param_port.addListener(update_pairing_listener);
        param_port_or.addListener(update_pairing_listener);
        param_protocol.addListener(update_pairing_listener);
    /*
			config_model.addActionParameter2( "test", "test" ).addListener(
				new ParameterListener()
				{
					public void
					parameterChanged(
						Parameter param )
					{
						try{
							pm.testService(
								p_sid,
								new PairingTestListener()
								{
									public void
									testStarted(
										PairingTest test )
									{
										System.out.println( "Test starts" );
									}

									public void
									testComplete(
										PairingTest test)
									{
										System.out.println( "Test complete: " + test.getOutcome() + "/" + test.getErrorMessage());
									}
								});
						}catch( Throwable e ){

							Debug.out( e );
						}
					}
				});
			*/
    }
    if (param_enable != null) {
        final List<Parameter> changed_params = new ArrayList<>();
        if (!plugin_enabled) {
            Parameter[] params = config_model.getParameters();
            for (Parameter param : params) {
                if (param == param_enable) {
                    continue;
                }
                if (param.isEnabled()) {
                    changed_params.add(param);
                    param.setEnabled(false);
                }
            }
        }
        param_enable.addListener(new ParameterListener() {

            @Override
            public void parameterChanged(Parameter e_p) {
                // this doesn't quite work as tne enabler/disabler parameter logic is implemented
                // badly and only toggles the UI component, not the enabled state of the
                // underlying parameter. grr. better than nothing though
                plugin_enabled = ((BooleanParameter) e_p).getValue();
                if (plugin_enabled) {
                    for (Parameter p : changed_params) {
                        p.setEnabled(true);
                    }
                } else {
                    changed_params.clear();
                    Parameter[] params = config_model.getParameters();
                    for (Parameter param : params) {
                        if (param == e_p) {
                            continue;
                        }
                        if (param.isEnabled()) {
                            changed_params.add(param);
                            param.setEnabled(false);
                        }
                    }
                }
                setupServer();
                setupUPnP();
                if (p_sid != null) {
                    setupPairing(p_sid, pairing_enable.getValue());
                }
            }
        });
    }
    // end config
    setupResources();
    setupAccess();
    setupServer();
}
Also used : LoggerChannelListener(com.biglybt.pif.logging.LoggerChannelListener) UIManager(com.biglybt.pif.ui.UIManager) UITextArea(com.biglybt.pif.ui.components.UITextArea) JSONObject(org.json.simple.JSONObject)

Example 8 with LoggerChannelListener

use of com.biglybt.pif.logging.LoggerChannelListener in project BiglyBT by BiglySoftware.

the class PluginUpdatePlugin method addUpdate.

public Update addUpdate(final PluginInterface pi_for_update, final UpdateChecker checker, final String update_name, final String[] update_details, final String old_version, final String new_version, final ResourceDownloader resource_downloader, final boolean is_jar, final int restart_type, final boolean verify) {
    final Update update = checker.addUpdate(update_name, update_details, old_version, new_version, resource_downloader, restart_type);
    update.setUserObject(pi_for_update);
    resource_downloader.addListener(new ResourceDownloaderAdapter() {

        @Override
        public boolean completed(final ResourceDownloader downloader, InputStream data) {
            // during the update phase report any messages
            // to the downloader
            LoggerChannelListener list = new LoggerChannelListener() {

                @Override
                public void messageLogged(int type, String content) {
                    downloader.reportActivity(content);
                }

                @Override
                public void messageLogged(String str, Throwable error) {
                    downloader.reportActivity(str);
                }
            };
            try {
                log.addListener(list);
                installUpdate(checker, update, pi_for_update, restart_type == Update.RESTART_REQUIRED_NO, is_jar, old_version, new_version, data, verify);
                return (true);
            } finally {
                log.removeListener(list);
            }
        }

        @Override
        public void failed(ResourceDownloader downloader, ResourceDownloaderException e) {
            if (!downloader.isCancelled()) {
                Debug.out(downloader.getName() + " failed", e);
            }
            update.complete(false);
        }
    });
    return (update);
}
Also used : ResourceDownloaderAdapter(com.biglybt.pif.utils.resourcedownloader.ResourceDownloaderAdapter) LoggerChannelListener(com.biglybt.pif.logging.LoggerChannelListener) ZipInputStream(java.util.zip.ZipInputStream) ResourceDownloaderException(com.biglybt.pif.utils.resourcedownloader.ResourceDownloaderException) ResourceDownloader(com.biglybt.pif.utils.resourcedownloader.ResourceDownloader)

Example 9 with LoggerChannelListener

use of com.biglybt.pif.logging.LoggerChannelListener in project BiglyBT by BiglySoftware.

the class PluginUpdatePlugin method initialize.

@Override
public void initialize(PluginInterface _plugin_interface) {
    plugin_interface = _plugin_interface;
    plugin_interface.getPluginProperties().setProperty("plugin.version", "1.0");
    plugin_interface.getPluginProperties().setProperty("plugin.name", "Plugin Updater");
    log = plugin_interface.getLogger().getChannel("Plugin Update");
    log.setDiagnostic();
    log.setForce(true);
    UIManager ui_manager = plugin_interface.getUIManager();
    final BasicPluginViewModel model = ui_manager.createBasicPluginViewModel(PLUGIN_RESOURCE_ID);
    final PluginConfig plugin_config = plugin_interface.getPluginconfig();
    boolean enabled = plugin_config.getPluginBooleanParameter("enable.update", true);
    model.setConfigSectionID(PLUGIN_CONFIGSECTION_ID);
    model.getStatus().setText(enabled ? "Running" : "Optional checks disabled");
    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");
        }
    });
    BasicPluginConfigModel config = ui_manager.createBasicPluginConfigModel(ConfigSection.SECTION_PLUGINS, PLUGIN_CONFIGSECTION_ID);
    config.addBooleanParameter2("enable.update", "Plugin.pluginupdate.enablecheck", true);
    plugin_interface.addEventListener(new PluginEventListener() {

        @Override
        public void handleEvent(PluginEvent ev) {
            if (ev.getType() == PluginEvent.PEV_ALL_PLUGINS_INITIALISED) {
                plugin_interface.removeEventListener(this);
                initComplete(plugin_config);
            }
        }
    });
}
Also used : LoggerChannelListener(com.biglybt.pif.logging.LoggerChannelListener) UIManager(com.biglybt.pif.ui.UIManager) BasicPluginViewModel(com.biglybt.pif.ui.model.BasicPluginViewModel) BasicPluginConfigModel(com.biglybt.pif.ui.model.BasicPluginConfigModel)

Example 10 with LoggerChannelListener

use of com.biglybt.pif.logging.LoggerChannelListener in project BiglyBT by BiglySoftware.

the class ExternalSeedPlugin method initialize.

@Override
public void initialize(PluginInterface _plugin_interface) {
    plugin_interface = _plugin_interface;
    dm_stats = plugin_interface.getDownloadManager().getStats();
    log = plugin_interface.getLogger().getTimeStampedChannel("External Seeds");
    final BasicPluginViewModel view_model = plugin_interface.getUIManager().createBasicPluginViewModel("Plugin.extseed.name");
    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");
        }
    });
    status_field = view_model.getStatus();
    setStatus("Initialising");
    download_mon = plugin_interface.getUtilities().getMonitor();
    Utilities utilities = plugin_interface.getUtilities();
    final DelayedTask dt = plugin_interface.getUtilities().createDelayedTask(new Runnable() {

        @Override
        public void run() {
            AEThread2 t = new AEThread2("ExternalSeedInitialise", true) {

                @Override
                public void run() {
                    setStatus("Running");
                    plugin_interface.getDownloadManager().addListener(ExternalSeedPlugin.this);
                }
            };
            t.setPriority(Thread.MIN_PRIORITY);
            t.start();
        }
    });
    dt.queue();
    UTTimer timer = utilities.createTimer("ExternalPeerScheduler", true);
    timer.addPeriodicEvent(5000, new UTTimerEventPerformer() {

        @Override
        public void perform(UTTimerEvent event) {
            try {
                Iterator it = download_map.values().iterator();
                while (it.hasNext()) {
                    List peers = randomiseList((List) it.next());
                    for (int i = 0; i < peers.size(); i++) {
                        if (((ExternalSeedPeer) peers.get(i)).checkConnection()) {
                            break;
                        }
                    }
                }
            } catch (Throwable e) {
            // we do this without holding the monitor as doing so causes potential
            // deadlock between download_mon and the connection's connection_mon
            // so ignore possible errors here that may be caused by concurrent
            // modification to the download_map ans associated lists. We are only
            // reading the data so errors will only be transient
            }
        }
    });
}
Also used : LoggerChannelListener(com.biglybt.pif.logging.LoggerChannelListener) BasicPluginViewModel(com.biglybt.pif.ui.model.BasicPluginViewModel) AEThread2(com.biglybt.core.util.AEThread2) StringWriter(java.io.StringWriter) PrintWriter(java.io.PrintWriter)

Aggregations

LoggerChannelListener (com.biglybt.pif.logging.LoggerChannelListener)14 UIManager (com.biglybt.pif.ui.UIManager)6 BasicPluginConfigModel (com.biglybt.pif.ui.model.BasicPluginConfigModel)5 BasicPluginViewModel (com.biglybt.pif.ui.model.BasicPluginViewModel)5 DelayedTask (com.biglybt.pif.utils.DelayedTask)3 PluginListener (com.biglybt.pif.PluginListener)2 UTTimerEvent (com.biglybt.pif.utils.UTTimerEvent)2 UTTimerEventPerformer (com.biglybt.pif.utils.UTTimerEventPerformer)2 PrintWriter (java.io.PrintWriter)2 StringWriter (java.io.StringWriter)2 Core (com.biglybt.core.Core)1 DHT (com.biglybt.core.dht.DHT)1 DHTLogger (com.biglybt.core.dht.DHTLogger)1 DHTControlActivity (com.biglybt.core.dht.control.DHTControlActivity)1 DHTControlContact (com.biglybt.core.dht.control.DHTControlContact)1 DHTNATPuncher (com.biglybt.core.dht.nat.DHTNATPuncher)1 DHTRouterContact (com.biglybt.core.dht.router.DHTRouterContact)1 DHTTransportContact (com.biglybt.core.dht.transport.DHTTransportContact)1 DHTTransportFullStats (com.biglybt.core.dht.transport.DHTTransportFullStats)1 DHTTransportUDP (com.biglybt.core.dht.transport.udp.DHTTransportUDP)1