use of com.biglybt.pif.PluginException in project BiglyBT by BiglySoftware.
the class ManagerUtils method browse.
public static String browse(final DownloadManager dm, DiskManagerFileInfo _file, final boolean anon, final boolean launch) {
Properties props = new Properties();
File save_location = dm.getSaveLocation();
final String root_dir;
if (save_location.isFile()) {
root_dir = save_location.getParentFile().getAbsolutePath();
} else {
root_dir = save_location.getAbsolutePath();
}
final String url_suffix;
boolean always_browse = COConfigurationManager.getBooleanParameter("Library.LaunchWebsiteInBrowserDirList");
if (!always_browse) {
if (_file == null) {
_file = getBrowseHomePage(dm);
}
}
final DiskManagerFileInfo file = _file;
if (file == null) {
// asked to launch a download (note that the double-click on a download that has an index.html file will by default result in
// us getting here with the file set, not null)
url_suffix = "";
} else {
String relative_path = file.getTorrentFile().getRelativePath();
String[] bits = relative_path.replace(File.separatorChar, '/').split("/");
String _url_suffix = "";
int bits_to_use = always_browse ? bits.length - 1 : bits.length;
for (int i = 0; i < bits_to_use; i++) {
String bit = bits[i];
if (bit.length() == 0) {
continue;
}
_url_suffix += (_url_suffix == "" ? "" : "/") + UrlUtils.encode(bit);
}
url_suffix = _url_suffix;
}
synchronized (browse_plugins) {
WebPlugin plugin = browse_plugins.get(dm);
if (plugin == null) {
props.put(WebPlugin.PR_PORT, 0);
props.put(WebPlugin.PR_BIND_IP, "127.0.0.1");
props.put(WebPlugin.PR_HOME_PAGE, "");
props.put(WebPlugin.PR_ROOT_DIR, root_dir);
props.put(WebPlugin.PR_ACCESS, "local");
props.put(WebPlugin.PR_HIDE_RESOURCE_CONFIG, true);
props.put(WebPlugin.PR_ENABLE_KEEP_ALIVE, true);
props.put(WebPlugin.PR_ENABLE_PAIRING, false);
props.put(WebPlugin.PR_ENABLE_UPNP, false);
props.put(WebPlugin.PR_ENABLE_I2P, false);
props.put(WebPlugin.PR_ENABLE_TOR, false);
final String plugin_id = "webserver:" + dm.getInternalName();
final String plugin_name = "Web Server for " + dm.getDisplayName();
Properties messages = new Properties();
messages.put("plugins." + plugin_id, plugin_name);
PluginInitializer.getDefaultInterface().getUtilities().getLocaleUtilities().integrateLocalisedMessageBundle(messages);
final AESemaphore waiter = new AESemaphore("waiter");
final String[] url_holder = { null };
plugin = new UnloadableWebPlugin(props) {
private Map<String, Object> file_map = new HashMap<>();
private String protocol;
private String host;
private int port;
@Override
public void initialize(PluginInterface plugin_interface) throws PluginException {
DiskManagerFileInfoSet file_set = dm.getDiskManagerFileInfoSet();
DiskManagerFileInfo[] files = file_set.getFiles();
Set<Object> root_dir = new HashSet<>();
file_map.put("", root_dir);
for (DiskManagerFileInfo dm_file : files) {
TOTorrentFile file = dm_file.getTorrentFile();
String path = file.getRelativePath();
file_map.put(path, dm_file);
if (path.startsWith(File.separator)) {
path = path.substring(1);
}
Set<Object> dir = root_dir;
int pos = 0;
while (true) {
int next_pos = path.indexOf(File.separatorChar, pos);
if (next_pos == -1) {
dir.add(dm_file);
break;
} else {
String bit = path.substring(pos, next_pos);
dir.add(bit);
String sub_path = path.substring(0, next_pos);
dir = (Set<Object>) file_map.get(sub_path);
if (dir == null) {
dir = new HashSet<>();
file_map.put(sub_path, dir);
}
pos = next_pos + 1;
}
}
}
Properties props = plugin_interface.getPluginProperties();
props.put("plugin.name", plugin_name);
super.initialize(plugin_interface);
InetAddress bind_ip = getServerBindIP();
if (bind_ip.isAnyLocalAddress()) {
host = "127.0.0.1";
} else {
host = bind_ip.getHostAddress();
}
port = getServerPort();
log("Assigned port: " + port);
protocol = getProtocol();
String url = protocol + "://" + host + ":" + port + "/" + url_suffix;
if (launch) {
Utils.launch(url, false, true, anon);
} else {
synchronized (url_holder) {
url_holder[0] = url;
}
waiter.release();
}
}
@Override
public boolean generate(TrackerWebPageRequest request, TrackerWebPageResponse response) throws IOException {
try {
boolean res = super.generate(request, response);
if (!res) {
response.setReplyStatus(404);
}
} catch (Throwable e) {
response.setReplyStatus(404);
}
return (true);
}
@Override
protected boolean useFile(TrackerWebPageRequest request, final TrackerWebPageResponse response, File root, String relative_url) throws IOException {
URL absolute_url = request.getAbsoluteURL();
String query = absolute_url.getQuery();
if (query != null) {
String[] args = query.split("&");
String vuze_source = null;
int vuze_file_index = -1;
String vuze_file_name = null;
List<String> networks = new ArrayList<>();
for (String arg : args) {
String[] bits = arg.split("=");
String lhs = bits[0];
String rhs = UrlUtils.decode(bits[1]);
if (lhs.equals("vuze_source")) {
if (rhs.endsWith(".torrent") || rhs.startsWith("magnet")) {
vuze_source = rhs;
}
} else if (lhs.equals("vuze_file_index")) {
vuze_file_index = Integer.parseInt(rhs);
} else if (lhs.equals("vuze_file_name")) {
vuze_file_name = rhs;
} else if (lhs.equals("vuze_network")) {
String net = AENetworkClassifier.internalise(rhs);
if (net != null) {
networks.add(net);
}
}
}
if (vuze_source != null) {
String referrer = (String) request.getHeaders().get("referer");
if (referrer == null || !referrer.contains("://" + host + ":" + port)) {
response.setReplyStatus(403);
return (true);
}
if (vuze_source.endsWith(".torrent")) {
Object file_node = file_map.get(vuze_source);
if (file_node instanceof DiskManagerFileInfo) {
DiskManagerFileInfo dm_file = (DiskManagerFileInfo) file_node;
long file_size = dm_file.getLength();
File target_file = dm_file.getFile(true);
boolean done = dm_file.getDownloaded() == file_size && target_file.length() == file_size;
if (done) {
return (handleRedirect(dm, target_file, vuze_file_index, vuze_file_name, networks, request, response));
} else {
try {
File torrent_file = AETemporaryFileHandler.createTempFile();
final FileOutputStream fos = new FileOutputStream(torrent_file);
try {
DiskManagerChannel chan = PluginCoreUtils.wrap(dm_file).createChannel();
try {
final DiskManagerRequest req = chan.createRequest();
req.setOffset(0);
req.setLength(file_size);
req.addListener(new DiskManagerListener() {
@Override
public void eventOccurred(DiskManagerEvent event) {
int type = event.getType();
if (type == DiskManagerEvent.EVENT_TYPE_BLOCKED) {
return;
} else if (type == DiskManagerEvent.EVENT_TYPE_FAILED) {
throw (new RuntimeException(event.getFailure()));
}
PooledByteBuffer buffer = event.getBuffer();
if (buffer == null) {
throw (new RuntimeException("eh?"));
}
try {
byte[] data = buffer.toByteArray();
fos.write(data);
} catch (IOException e) {
throw (new RuntimeException("Failed to write to " + file, e));
} finally {
buffer.returnToPool();
}
}
});
req.run();
} finally {
chan.destroy();
}
} finally {
fos.close();
}
return (handleRedirect(dm, torrent_file, vuze_file_index, vuze_file_name, networks, request, response));
} catch (Throwable e) {
Debug.out(e);
return (false);
}
}
} else {
return (false);
}
} else {
URL magnet = new URL(vuze_source);
File torrent_file = AETemporaryFileHandler.createTempFile();
try {
URLConnection connection = magnet.openConnection();
connection.connect();
FileUtil.copyFile(connection.getInputStream(), torrent_file.getAbsoluteFile());
return (handleRedirect(dm, torrent_file, vuze_file_index, vuze_file_name, networks, request, response));
} catch (Throwable e) {
Debug.out(e);
}
}
}
}
String path = absolute_url.getPath();
if (path.equals("/")) {
if (COConfigurationManager.getBooleanParameter("Library.LaunchWebsiteInBrowserDirList")) {
relative_url = "/";
}
}
String download_name = XUXmlWriter.escapeXML(dm.getDisplayName());
String relative_file = relative_url.replace('/', File.separatorChar);
String node_key = relative_file.substring(1);
Object file_node = file_map.get(node_key);
boolean file_node_is_parent = false;
if (file_node == null) {
int pos = node_key.lastIndexOf(File.separator);
if (pos == -1) {
node_key = "";
} else {
node_key = node_key.substring(0, pos);
}
file_node = file_map.get(node_key);
file_node_is_parent = true;
}
if (file_node == null) {
return (false);
}
if (file_node instanceof Set) {
if (relative_url.equals("/favicon.ico")) {
try {
InputStream stream = getClass().getClassLoader().getResourceAsStream("com/biglybt/ui/icons/favicon.ico");
response.useStream("image/x-icon", stream);
return (true);
} catch (Throwable e) {
}
}
Set<Object> kids = (Set<Object>) file_node;
String request_url = request.getURL();
if (file_node_is_parent) {
int pos = request_url.lastIndexOf("/");
if (pos == -1) {
request_url = "";
} else {
request_url = request_url.substring(0, pos);
}
}
response.setContentType("text/html");
OutputStream os = response.getOutputStream();
String title = XUXmlWriter.escapeXML(UrlUtils.decode(request_url));
if (title.length() == 0) {
title = "/";
}
os.write(("<html>" + NL + " <head>" + NL + " <meta charset=\"UTF-8\">" + NL + " <title>" + download_name + ": Index of " + title + "</title>" + NL + " </head>" + NL + " <body>" + NL + " <p>" + download_name + "</p>" + NL + " <h1>Index of " + title + "</h1>" + NL + " <pre><hr>" + NL).getBytes("UTF-8"));
String root_url = request_url;
if (!root_url.endsWith("/")) {
root_url += "/";
}
if (request_url.length() > 1) {
int pos = request_url.lastIndexOf('/');
if (pos == 0) {
pos++;
}
String parent = request_url.substring(0, pos);
os.write(("<a href=\"" + parent + "\">..</a>" + NL).getBytes("UTF-8"));
}
List<String[]> filenames = new ArrayList<>(kids.size());
int max_filename = 0;
int MAX_LEN = 120;
for (Object entry : kids) {
DiskManagerFileInfo file;
String file_name;
if (entry instanceof String) {
file = null;
file_name = (String) entry;
} else {
file = (DiskManagerFileInfo) entry;
if (file.isSkipped()) {
continue;
}
file_name = file.getTorrentFile().getRelativePath();
int pos = file_name.lastIndexOf(File.separatorChar);
if (pos != -1) {
file_name = file_name.substring(pos + 1);
}
}
String url = root_url + UrlUtils.encode(file_name);
if (file == null) {
file_name += "/";
}
int len = file_name.length();
if (len > MAX_LEN) {
file_name = file_name.substring(0, MAX_LEN - 3) + "...";
len = file_name.length();
}
if (len > max_filename) {
max_filename = len;
}
filenames.add(new String[] { url, file_name, file == null ? "" : DisplayFormatters.formatByteCountToKiBEtc(file.getLength()) });
}
max_filename = ((max_filename + 15) / 8) * 8;
char[] padding = new char[max_filename];
Arrays.fill(padding, ' ');
Collections.sort(filenames, new Comparator<String[]>() {
Comparator comp = new FormattersImpl().getAlphanumericComparator(true);
@Override
public int compare(String[] o1, String[] o2) {
return (comp.compare(o1[0], o2[0]));
}
});
for (String[] entry : filenames) {
String file_name = entry[1];
int len = file_name.length();
StringBuilder line = new StringBuilder(max_filename + 64);
line.append("<a href=\"").append(entry[0]).append("\">").append(XUXmlWriter.escapeXML(file_name)).append("</a>");
line.append(padding, 0, max_filename - len);
line.append(entry[2]);
line.append(NL);
os.write(line.toString().getBytes("UTF-8"));
}
os.write((" <hr></pre>" + NL + " <address>" + Constants.APP_NAME + " Web Server at " + host + " Port " + getServerPort() + "</address>" + NL + " </body>" + NL + "</html>").getBytes("UTF-8"));
return (true);
} else {
DiskManagerFileInfo dm_file = (DiskManagerFileInfo) file_node;
long file_size = dm_file.getLength();
File target_file = dm_file.getFile(true);
boolean done = dm_file.getDownloaded() == file_size && target_file.length() == file_size;
String file_type;
// Use the original torrent file name when deducing file type to
// avoid incomplete suffix issues etc
String relative_path = dm_file.getTorrentFile().getRelativePath();
int pos = relative_path.lastIndexOf(".");
if (pos == -1) {
file_type = "";
} else {
file_type = relative_path.substring(pos + 1);
}
if (file_size >= 512 * 1024) {
String content_type = HTTPUtils.guessContentTypeFromFileType(file_type);
if (content_type.startsWith("text/") || content_type.startsWith("image/")) {
// don't want to be redirecting here as (for example) .html needs
// to remain in the 'correct' place so that relative assets work
} else {
URL stream_url = getMediaServerContentURL(dm_file);
if (stream_url != null) {
OutputStream os = response.getRawOutputStream();
os.write(("HTTP/1.1 302 Found" + NL + "Location: " + stream_url.toExternalForm() + NL + NL).getBytes("UTF-8"));
return (true);
}
}
}
if (done) {
if (file_size < 512 * 1024) {
FileInputStream fis = null;
try {
fis = new FileInputStream(target_file);
response.useStream(file_type, fis);
return (true);
} finally {
if (fis != null) {
fis.close();
}
}
} else {
OutputStream os = null;
InputStream is = null;
try {
os = response.getRawOutputStream();
os.write(("HTTP/1.1 200 OK" + NL + "Content-Type:" + HTTPUtils.guessContentTypeFromFileType(file_type) + NL + "Content-Length: " + file_size + NL + "Connection: close" + NL + NL).getBytes("UTF-8"));
byte[] buffer = new byte[128 * 1024];
is = new FileInputStream(target_file);
while (true) {
int len = is.read(buffer);
if (len <= 0) {
break;
}
os.write(buffer, 0, len);
}
} catch (Throwable e) {
// e.printStackTrace();
} finally {
try {
os.close();
} catch (Throwable e) {
}
try {
is.close();
} catch (Throwable e) {
}
}
return (true);
}
} else {
dm_file.setPriority(10);
try {
final OutputStream os = response.getRawOutputStream();
os.write(("HTTP/1.1 200 OK" + NL + "Content-Type:" + HTTPUtils.guessContentTypeFromFileType(file_type) + NL + "Content-Length: " + file_size + NL + "Connection: close" + NL + "X-Vuze-Hack: X").getBytes("UTF-8"));
DiskManagerChannel chan = PluginCoreUtils.wrap(dm_file).createChannel();
try {
final DiskManagerRequest req = chan.createRequest();
final boolean[] header_complete = { false };
final long[] last_write = { 0 };
req.setOffset(0);
req.setLength(file_size);
req.addListener(new DiskManagerListener() {
@Override
public void eventOccurred(DiskManagerEvent event) {
int type = event.getType();
if (type == DiskManagerEvent.EVENT_TYPE_BLOCKED) {
return;
} else if (type == DiskManagerEvent.EVENT_TYPE_FAILED) {
throw (new RuntimeException(event.getFailure()));
}
PooledByteBuffer buffer = event.getBuffer();
if (buffer == null) {
throw (new RuntimeException("eh?"));
}
try {
boolean do_header = false;
synchronized (header_complete) {
if (!header_complete[0]) {
do_header = true;
header_complete[0] = true;
}
last_write[0] = SystemTime.getMonotonousTime();
}
if (do_header) {
os.write((NL + NL).getBytes("UTF-8"));
}
byte[] data = buffer.toByteArray();
os.write(data);
} catch (IOException e) {
throw (new RuntimeException("Failed to write to " + file, e));
} finally {
buffer.returnToPool();
}
}
});
final TimerEventPeriodic[] timer_event = { null };
timer_event[0] = SimpleTimer.addPeriodicEvent("KeepAlive", 10 * 1000, new TimerEventPerformer() {
boolean cancel_outstanding = false;
@Override
public void perform(TimerEvent event) {
if (cancel_outstanding) {
req.cancel();
} else {
synchronized (header_complete) {
if (header_complete[0]) {
if (SystemTime.getMonotonousTime() - last_write[0] >= 5 * 60 * 1000) {
req.cancel();
}
} else {
try {
os.write("X".getBytes("UTF-8"));
os.flush();
} catch (Throwable e) {
req.cancel();
}
}
}
if (!response.isActive()) {
cancel_outstanding = true;
}
}
}
});
try {
req.run();
} finally {
timer_event[0].cancel();
}
return (true);
} finally {
chan.destroy();
}
} catch (Throwable e) {
return (false);
}
}
}
}
private boolean handleRedirect(DownloadManager dm, File torrent_file, int file_index, String file_name, List<String> networks, TrackerWebPageRequest request, TrackerWebPageResponse response) {
try {
TOTorrent torrent = TOTorrentFactory.deserialiseFromBEncodedFile(torrent_file);
GlobalManager gm = CoreFactory.getSingleton().getGlobalManager();
UIFunctions uif = UIFunctionsManager.getUIFunctions();
TorrentOpenOptions torrent_options = new TorrentOpenOptions(torrent_file.getAbsolutePath(), torrent, false, null);
torrent_options.setTorrent(torrent);
String[] existing_nets;
if (networks.size() == 0) {
// inherit networks from parent
existing_nets = dm.getDownloadState().getNetworks();
} else {
existing_nets = networks.toArray(new String[networks.size()]);
}
for (String net : AENetworkClassifier.AT_NETWORKS) {
boolean found = false;
for (String x : existing_nets) {
if (net == x) {
found = true;
break;
}
}
torrent_options.setNetworkEnabled(net, found);
}
Map<String, Object> add_options = new HashMap<>();
add_options.put(UIFunctions.OTO_SILENT, true);
if (uif.addTorrentWithOptions(torrent_options, add_options)) {
long start = SystemTime.getMonotonousTime();
while (true) {
DownloadManager o_dm = gm.getDownloadManager(torrent);
if (o_dm != null) {
if (!o_dm.getDownloadState().getFlag(DownloadManagerState.FLAG_METADATA_DOWNLOAD)) {
DiskManagerFileInfo[] files = o_dm.getDiskManagerFileInfoSet().getFiles();
DiskManagerFileInfo o_dm_file = null;
if (file_name != null) {
for (DiskManagerFileInfo file : files) {
String path = file.getTorrentFile().getRelativePath();
if (path.equals(file_name)) {
o_dm_file = file;
break;
}
}
if (o_dm_file == null) {
o_dm_file = files[0];
}
} else {
if (file_index < 0) {
long largest = -1;
for (DiskManagerFileInfo file : files) {
if (file.getLength() > largest) {
o_dm_file = file;
largest = file.getLength();
}
}
} else {
o_dm_file = files[file_index];
}
}
String original_path = request.getAbsoluteURL().getPath();
if (original_path.endsWith(".html")) {
String url = browse(o_dm, file_index < 0 ? null : o_dm_file, anon, false);
OutputStream os = response.getRawOutputStream();
os.write(("HTTP/1.1 302 Found" + NL + "Location: " + url + NL + NL).getBytes("UTF-8"));
return (true);
} else {
URL stream_url = getMediaServerContentURL(o_dm_file);
if (stream_url != null) {
OutputStream os = response.getRawOutputStream();
os.write(("HTTP/1.1 302 Found" + NL + "Location: " + stream_url.toExternalForm() + NL + NL).getBytes("UTF-8"));
return (true);
}
}
}
}
long now = SystemTime.getMonotonousTime();
if (now - start > 3 * 60 * 1000) {
Debug.out("Timeout waiting for download to be added");
return (false);
}
Thread.sleep(1000);
}
} else {
Debug.out("Failed to add download for some reason");
return (false);
}
} catch (Throwable e) {
Debug.out(e);
return (false);
}
}
@Override
public void unload() throws PluginException {
synchronized (browse_plugins) {
browse_plugins.remove(dm);
}
super.unload();
}
};
PluginManager.registerPlugin(plugin, plugin_id, plugin_id);
browse_plugins.put(dm, plugin);
if (launch) {
return (null);
} else {
waiter.reserve(10 * 1000);
synchronized (url_holder) {
return (url_holder[0]);
}
}
} else {
String protocol = plugin.getProtocol();
InetAddress bind_ip = plugin.getServerBindIP();
String host;
if (bind_ip.isAnyLocalAddress()) {
host = "127.0.0.1";
} else {
host = bind_ip.getHostAddress();
}
String url = protocol + "://" + host + ":" + plugin.getServerPort() + "/" + url_suffix;
if (launch) {
Utils.launch(url, false, true, anon);
return (null);
} else {
return (url);
}
}
}
}
use of com.biglybt.pif.PluginException in project BiglyBT by BiglySoftware.
the class DeviceInfoArea method buildBetaArea.
private void buildBetaArea(Composite parent, Control above) {
FormData fd;
Group betaArea = new Group(parent, SWT.NONE);
betaArea.setText("Beta Debug");
betaArea.setLayout(new FormLayout());
fd = Utils.getFilledFormData();
fd.top = new FormAttachment(above, 5);
betaArea.setLayoutData(fd);
fd = new FormData();
fd.left = new FormAttachment(0, 0);
fd.right = new FormAttachment(100, 0);
fd.top = new FormAttachment(0, 0);
Label label = new Label(betaArea, SWT.NULL);
label.setText("Transcode Providers:");
label.setLayoutData(fd);
Button vuze_button = new Button(betaArea, SWT.NULL);
vuze_button.setText("Install Vuze Transcoder");
if (CoreFactory.isCoreRunning()) {
final PluginInstaller installer = CoreFactory.getSingleton().getPluginManager().getPluginInstaller();
StandardPlugin vuze_plugin = null;
try {
vuze_plugin = installer.getStandardPlugin("vuzexcode");
} catch (Throwable e) {
}
if (vuze_plugin == null || vuze_plugin.isAlreadyInstalled()) {
vuze_button.setEnabled(false);
}
final StandardPlugin f_vuze_plugin = vuze_plugin;
vuze_button.addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event arg0) {
try {
f_vuze_plugin.install(false);
} catch (Throwable e) {
Debug.printStackTrace(e);
}
}
});
fd = new FormData();
fd.left = new FormAttachment(0, 0);
fd.top = new FormAttachment(label, 4);
vuze_button.setLayoutData(fd);
}
Control top = vuze_button;
TranscodeProvider[] providers = DeviceManagerFactory.getSingleton().getTranscodeManager().getProviders();
for (TranscodeProvider provider : providers) {
fd = new FormData();
fd.left = new FormAttachment(0, 10);
fd.right = new FormAttachment(100, 0);
fd.top = new FormAttachment(top, 4);
Label prov_lab = new Label(betaArea, SWT.NULL);
prov_lab.setText(provider.getName());
prov_lab.setLayoutData(fd);
top = prov_lab;
TranscodeProfile[] profiles = provider.getProfiles();
String line = null;
for (TranscodeProfile profile : profiles) {
if (line == null) {
line = profile.getName();
} else {
line += ", " + profile.getName();
}
}
if (line != null) {
fd = new FormData();
fd.left = new FormAttachment(0, 25);
fd.right = new FormAttachment(100, 0);
fd.top = new FormAttachment(top, 4);
Label prof_lab = new Label(betaArea, SWT.WRAP);
prof_lab.setText("Profiles: " + line);
prof_lab.setLayoutData(fd);
top = prof_lab;
}
}
// both - installer test
final Button both_button = new Button(betaArea, SWT.NULL);
both_button.setText("Test! Install RSSGen and AZBlog!");
if (CoreFactory.isCoreRunning()) {
final PluginInstaller installer = CoreFactory.getSingleton().getPluginManager().getPluginInstaller();
StandardPlugin plugin1 = null;
StandardPlugin plugin2 = null;
try {
plugin1 = installer.getStandardPlugin("azrssgen");
} catch (Throwable e) {
}
try {
plugin2 = installer.getStandardPlugin("azblog");
} catch (Throwable e) {
}
if (plugin1 != null && plugin2 != null) {
final Composite install_area = new Composite(betaArea, SWT.BORDER);
fd = new FormData();
fd.left = new FormAttachment(both_button, 0);
fd.right = new FormAttachment(100, 0);
fd.top = new FormAttachment(top, 4);
fd.bottom = new FormAttachment(100, 0);
install_area.setLayoutData(fd);
final StandardPlugin f_plugin1 = plugin1;
final StandardPlugin f_plugin2 = plugin2;
both_button.addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event arg0) {
both_button.setEnabled(false);
try {
Map<Integer, Object> properties = new HashMap<>();
properties.put(UpdateCheckInstance.PT_UI_STYLE, UpdateCheckInstance.PT_UI_STYLE_SIMPLE);
properties.put(UpdateCheckInstance.PT_UI_PARENT_SWT_COMPOSITE, install_area);
properties.put(UpdateCheckInstance.PT_UI_DISABLE_ON_SUCCESS_SLIDEY, true);
installer.install(new InstallablePlugin[] { f_plugin1, f_plugin2 }, false, properties, new PluginInstallationListener() {
@Override
public void completed() {
System.out.println("Install completed!");
tidy();
}
@Override
public void cancelled() {
System.out.println("Install cancelled");
tidy();
}
@Override
public void failed(PluginException e) {
System.out.println("Install failed: " + e);
tidy();
}
protected void tidy() {
Utils.execSWTThread(new Runnable() {
@Override
public void run() {
Control[] kids = install_area.getChildren();
for (Control c : kids) {
c.dispose();
}
both_button.setEnabled(true);
}
});
}
});
} catch (Throwable e) {
Debug.printStackTrace(e);
}
}
});
} else {
both_button.setEnabled(false);
}
fd = new FormData();
fd.left = new FormAttachment(0, 0);
fd.top = new FormAttachment(top, 4);
fd.bottom = new FormAttachment(100, 0);
both_button.setLayoutData(fd);
}
}
use of com.biglybt.pif.PluginException in project BiglyBT by BiglySoftware.
the class ConfigSectionPlugins method configSectionCreate.
@Override
public Composite configSectionCreate(final Composite parent) {
if (!CoreFactory.isCoreRunning()) {
Composite cSection = new Composite(parent, SWT.NULL);
cSection.setLayout(new FillLayout());
Label lblNotAvail = new Label(cSection, SWT.WRAP);
Messages.setLanguageText(lblNotAvail, "core.not.available");
return cSection;
}
GridLayout layout;
GridData gridData;
Label label;
ImageLoader imageLoader = ImageLoader.getInstance();
imgRedLed = imageLoader.getImage("redled");
imgGreenLed = imageLoader.getImage("greenled");
Composite infoGroup = new Composite(parent, SWT.NULL);
gridData = new GridData(GridData.VERTICAL_ALIGN_FILL | GridData.HORIZONTAL_ALIGN_FILL);
Utils.setLayoutData(infoGroup, gridData);
layout = new GridLayout();
layout.numColumns = 1;
layout.marginWidth = 0;
layout.marginHeight = 0;
infoGroup.setLayout(layout);
infoGroup.setLayout(new GridLayout());
String sep = System.getProperty("file.separator");
File fUserPluginDir = FileUtil.getUserFile("plugins");
String sUserPluginDir;
try {
sUserPluginDir = fUserPluginDir.getCanonicalPath();
} catch (Throwable e) {
sUserPluginDir = fUserPluginDir.toString();
}
if (!sUserPluginDir.endsWith(sep)) {
sUserPluginDir += sep;
}
File fAppPluginDir = FileUtil.getApplicationFile("plugins");
String sAppPluginDir;
try {
sAppPluginDir = fAppPluginDir.getCanonicalPath();
} catch (Throwable e) {
sAppPluginDir = fAppPluginDir.toString();
}
if (!sAppPluginDir.endsWith(sep)) {
sAppPluginDir += sep;
}
label = new Label(infoGroup, SWT.WRAP);
Utils.setLayoutData(label, new GridData(GridData.FILL_HORIZONTAL));
Messages.setLanguageText(label, "ConfigView.pluginlist.whereToPut");
label = new Label(infoGroup, SWT.WRAP);
gridData = new GridData(GridData.FILL_HORIZONTAL);
gridData.horizontalIndent = 10;
Utils.setLayoutData(label, gridData);
label.setText(sUserPluginDir.replaceAll("&", "&&"));
label.setForeground(Colors.blue);
label.setCursor(label.getDisplay().getSystemCursor(SWT.CURSOR_HAND));
final String _sUserPluginDir = sUserPluginDir;
label.addMouseListener(new MouseAdapter() {
@Override
public void mouseUp(MouseEvent arg0) {
if (_sUserPluginDir.endsWith("/plugins/") || _sUserPluginDir.endsWith("\\plugins\\")) {
File f = new File(_sUserPluginDir);
String dir = _sUserPluginDir;
if (!(f.exists() && f.isDirectory())) {
dir = _sUserPluginDir.substring(0, _sUserPluginDir.length() - 9);
}
Utils.launch(dir);
}
}
});
label = new Label(infoGroup, SWT.WRAP);
Utils.setLayoutData(label, new GridData(GridData.FILL_HORIZONTAL));
Messages.setLanguageText(label, "ConfigView.pluginlist.whereToPutOr");
label = new Label(infoGroup, SWT.WRAP);
gridData = new GridData(GridData.FILL_HORIZONTAL);
gridData.horizontalIndent = 10;
Utils.setLayoutData(label, gridData);
label.setText(sAppPluginDir.replaceAll("&", "&&"));
label.setForeground(Colors.blue);
label.setCursor(label.getDisplay().getSystemCursor(SWT.CURSOR_HAND));
final String _sAppPluginDir = sAppPluginDir;
// TODO : Fix it for windows
label.addMouseListener(new MouseAdapter() {
@Override
public void mouseUp(MouseEvent arg0) {
if (_sAppPluginDir.endsWith("/plugins/") || _sAppPluginDir.endsWith("\\plugins\\")) {
File f = new File(_sAppPluginDir);
if (f.exists() && f.isDirectory()) {
Utils.launch(_sAppPluginDir);
} else {
String appDir = _sAppPluginDir.substring(0, _sAppPluginDir.length() - 9);
System.out.println(appDir);
Utils.launch(appDir);
}
}
}
});
pluginIFs = rebuildPluginIFs();
Collections.sort(pluginIFs, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
return (((PluginInterface) o1).getPluginName().compareToIgnoreCase(((PluginInterface) o2).getPluginName()));
}
});
Label labelInfo = new Label(infoGroup, SWT.WRAP);
Utils.setLayoutData(labelInfo, new GridData(GridData.FILL_HORIZONTAL));
Messages.setLanguageText(labelInfo, "ConfigView.pluginlist.info");
table = new Table(infoGroup, SWT.BORDER | SWT.SINGLE | SWT.CHECK | SWT.VIRTUAL | SWT.FULL_SELECTION);
gridData = new GridData(GridData.FILL_BOTH);
gridData.heightHint = 200;
gridData.widthHint = 200;
Utils.setLayoutData(table, gridData);
for (int i = 0; i < COLUMN_HEADERS.length; i++) {
final TableColumn tc = new TableColumn(table, COLUMN_ALIGNS[i]);
tc.setWidth(Utils.adjustPXForDPI(COLUMN_SIZES[i]));
tc.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
boolean ascending = comparator.setField(table.indexOf(tc));
try {
table.setSortColumn(tc);
table.setSortDirection(ascending ? SWT.UP : SWT.DOWN);
} catch (NoSuchMethodError ignore) {
// Ignore Pre 3.0
}
Collections.sort(pluginIFs, comparator);
table.clearAll();
}
});
Messages.setLanguageText(tc, HEADER_PREFIX + COLUMN_HEADERS[i]);
}
table.setHeaderVisible(true);
Composite cButtons = new Composite(infoGroup, SWT.NONE);
layout = new GridLayout();
layout.marginHeight = 0;
layout.marginWidth = 0;
layout.numColumns = 5;
cButtons.setLayout(layout);
Utils.setLayoutData(cButtons, new GridData());
final Button btnUnload = new Button(cButtons, SWT.PUSH);
Utils.setLayoutData(btnUnload, new GridData());
Messages.setLanguageText(btnUnload, "ConfigView.pluginlist.unloadSelected");
btnUnload.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
final int[] items = table.getSelectionIndices();
new AEThread2("unload") {
@Override
public void run() {
for (int i = 0; i < items.length; i++) {
int index = items[i];
if (index >= 0 && index < pluginIFs.size()) {
PluginInterface pluginIF = (PluginInterface) pluginIFs.get(index);
if (pluginIF.getPluginState().isOperational()) {
if (pluginIF.getPluginState().isUnloadable()) {
try {
pluginIF.getPluginState().unload();
} catch (PluginException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
Utils.execSWTThread(new Runnable() {
@Override
public void run() {
pluginIFs = rebuildPluginIFs();
table.setItemCount(pluginIFs.size());
Collections.sort(pluginIFs, comparator);
table.clearAll();
}
});
}
}
}
}.start();
}
});
btnUnload.setEnabled(false);
final Button btnLoad = new Button(cButtons, SWT.PUSH);
Utils.setLayoutData(btnUnload, new GridData());
Messages.setLanguageText(btnLoad, "ConfigView.pluginlist.loadSelected");
btnLoad.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
final int[] items = table.getSelectionIndices();
new AEThread2("load") {
@Override
public void run() {
for (int i = 0; i < items.length; i++) {
int index = items[i];
if (index >= 0 && index < pluginIFs.size()) {
PluginInterface pluginIF = (PluginInterface) pluginIFs.get(index);
// Already loaded.
if (pluginIF.getPluginState().isOperational()) {
continue;
}
// initialise.
if (pluginIF.getPluginState().isDisabled()) {
if (pluginIF.getPluginState().hasFailed()) {
continue;
}
pluginIF.getPluginState().setDisabled(false);
}
try {
pluginIF.getPluginState().reload();
} catch (PluginException e1) {
// TODO Auto-generated catch block
Debug.printStackTrace(e1);
}
Utils.execSWTThread(new Runnable() {
@Override
public void run() {
if (table == null || table.isDisposed()) {
return;
}
pluginIFs = rebuildPluginIFs();
table.setItemCount(pluginIFs.size());
Collections.sort(pluginIFs, comparator);
table.clearAll();
}
});
}
}
}
}.start();
}
});
btnLoad.setEnabled(false);
// scan
final Button btnScan = new Button(cButtons, SWT.PUSH);
Utils.setLayoutData(btnScan, new GridData());
Messages.setLanguageText(btnScan, "ConfigView.pluginlist.scan");
btnScan.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
CoreFactory.getSingleton().getPluginManager().refreshPluginList(false);
pluginIFs = rebuildPluginIFs();
table.setItemCount(pluginIFs.size());
Collections.sort(pluginIFs, comparator);
table.clearAll();
}
});
// uninstall
final Button btnUninstall = new Button(cButtons, SWT.PUSH);
Utils.setLayoutData(btnUninstall, new GridData());
Messages.setLanguageText(btnUninstall, "ConfigView.pluginlist.uninstallSelected");
btnUninstall.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
btnUninstall.setEnabled(false);
final int[] items = table.getSelectionIndices();
new AEThread2("uninstall") {
@Override
public void run() {
try {
List<PluginInterface> pis = new ArrayList<>();
for (int i = 0; i < items.length; i++) {
int index = items[i];
if (index >= 0 && index < pluginIFs.size()) {
PluginInterface pluginIF = (PluginInterface) pluginIFs.get(index);
pis.add(pluginIF);
}
}
if (pis.size() > 0) {
PluginInterface[] ps = new PluginInterface[pis.size()];
pis.toArray(ps);
try {
final AESemaphore wait_sem = new AESemaphore("unist:wait");
ps[0].getPluginManager().getPluginInstaller().uninstall(ps, new PluginInstallationListener() {
@Override
public void completed() {
wait_sem.release();
}
@Override
public void cancelled() {
wait_sem.release();
}
@Override
public void failed(PluginException e) {
wait_sem.release();
}
});
wait_sem.reserve();
} catch (Exception e) {
Debug.printStackTrace(e);
}
}
} finally {
Utils.execSWTThread(new Runnable() {
@Override
public void run() {
pluginIFs = rebuildPluginIFs();
table.setItemCount(pluginIFs.size());
Collections.sort(pluginIFs, comparator);
table.clearAll();
table.setSelection(new int[0]);
}
});
}
}
}.start();
}
});
btnUninstall.setEnabled(false);
table.addListener(SWT.SetData, new Listener() {
@Override
public void handleEvent(Event event) {
TableItem item = (TableItem) event.item;
int index = table.indexOf(item);
PluginInterface pluginIF = (PluginInterface) pluginIFs.get(index);
for (int i = 0; i < COLUMN_HEADERS.length; i++) {
if (i == FilterComparator.FIELD_NAME)
item.setImage(i, pluginIF.getPluginState().isOperational() ? imgGreenLed : imgRedLed);
String sText = comparator.getFieldValue(i, pluginIF);
if (sText == null)
sText = "";
item.setText(i, sText);
}
item.setGrayed(pluginIF.getPluginState().isMandatory());
boolean bEnabled = pluginIF.getPluginState().isLoadedAtStartup();
Utils.setCheckedInSetData(item, bEnabled);
item.setData("PluginID", pluginIF.getPluginID());
Utils.alternateRowBackground(item);
}
});
table.addMouseListener(new MouseAdapter() {
@Override
public void mouseDoubleClick(MouseEvent e) {
TableItem[] items = table.getSelection();
if (items.length == 1) {
int index = table.indexOf(items[0]);
PluginInterface pluginIF = (PluginInterface) pluginIFs.get(index);
PluginConfigModel[] models = pluginIF.getUIManager().getPluginConfigModels();
for (PluginConfigModel model : models) {
if (model.getPluginInterface() == pluginIF) {
if (model instanceof BasicPluginConfigModel) {
String id = ((BasicPluginConfigModel) model).getSection();
UIFunctions uiFunctions = UIFunctionsManager.getUIFunctions();
if (uiFunctions != null) {
uiFunctions.getMDI().showEntryByID(MultipleDocumentInterface.SIDEBAR_SECTION_CONFIG, id);
}
}
}
}
}
}
});
table.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
TableItem item = (TableItem) e.item;
int index = table.indexOf(item);
PluginInterface pluginIF = (PluginInterface) pluginIFs.get(index);
if (e.detail == SWT.CHECK) {
if (item.getGrayed()) {
if (!item.getChecked())
item.setChecked(true);
return;
}
pluginIF.getPluginState().setDisabled(!item.getChecked());
pluginIF.getPluginState().setLoadedAtStartup(item.getChecked());
}
btnUnload.setEnabled(pluginIF.getPluginState().isOperational() && pluginIF.getPluginState().isUnloadable());
btnLoad.setEnabled(!pluginIF.getPluginState().isOperational() && !pluginIF.getPluginState().hasFailed());
btnUninstall.setEnabled(!(pluginIF.getPluginState().isBuiltIn() || pluginIF.getPluginState().isMandatory()));
}
});
table.setItemCount(pluginIFs.size());
return infoGroup;
}
use of com.biglybt.pif.PluginException in project BiglyBT by BiglySoftware.
the class SimplePluginInstaller method install.
public boolean install() {
try {
installer = CoreFactory.getSingleton().getPluginManager().getPluginInstaller();
StandardPlugin sp = installer.getStandardPlugin(plugin_id);
if (sp == null) {
throw (new Exception("Unknown plugin"));
}
Map<Integer, Object> properties = new HashMap<>();
properties.put(UpdateCheckInstance.PT_UI_STYLE, UpdateCheckInstance.PT_UI_STYLE_NONE);
properties.put(UpdateCheckInstance.PT_UI_DISABLE_ON_SUCCESS_SLIDEY, true);
final AESemaphore sem = new AESemaphore("plugin-install");
final Object[] result = new Object[] { null };
instance = installer.install(new InstallablePlugin[] { sp }, false, properties, new PluginInstallationListener() {
@Override
public void completed() {
synchronized (SimplePluginInstaller.this) {
completed = true;
}
result[0] = true;
if (listener != null) {
listener.finished();
}
sem.release();
}
@Override
public void cancelled() {
result[0] = new Exception("Cancelled");
if (listener != null) {
listener.finished();
}
sem.release();
}
@Override
public void failed(PluginException e) {
result[0] = e;
if (listener != null) {
listener.finished();
}
sem.release();
}
});
boolean kill_it;
synchronized (this) {
kill_it = cancelled;
}
if (kill_it) {
instance.cancel();
action_listener.actionComplete(new Exception("Cancelled"));
return (false);
}
instance.addListener(new UpdateCheckInstanceListener() {
@Override
public void cancelled(UpdateCheckInstance instance) {
}
@Override
public void complete(UpdateCheckInstance instance) {
Update[] updates = instance.getUpdates();
for (final Update update : updates) {
ResourceDownloader[] rds = update.getDownloaders();
for (ResourceDownloader rd : rds) {
rd.addListener(new ResourceDownloaderAdapter() {
@Override
public void reportActivity(ResourceDownloader downloader, String activity) {
}
@Override
public void reportPercentComplete(ResourceDownloader downloader, int percentage) {
if (listener != null) {
listener.progress(percentage);
}
}
});
}
}
}
});
sem.reserve();
action_listener.actionComplete(result[0]);
return (result[0] instanceof Boolean);
} catch (Throwable e) {
// must report error before hitting the listener otherwise the listener cancels the action
// and the error gets lost
action_listener.actionComplete(e);
if (listener != null) {
listener.finished();
}
}
return false;
}
use of com.biglybt.pif.PluginException in project BiglyBT by BiglySoftware.
the class IPWFilePanel method checkValidFile.
private void checkValidFile(Core core) {
String fileName = txtFile.getText();
String error_message = null;
try {
File f = new File(fileName);
if (f.isFile() && (f.getName().endsWith(".jar") || f.getName().endsWith(".zip") || f.getName().endsWith(".biglybt"))) {
wizard.setErrorMessage("");
wizard.setNextEnabled(true);
List<InstallablePlugin> list = new ArrayList<InstallablePlugin>();
InstallablePlugin plugin = core.getPluginManager().getPluginInstaller().installFromFile(f);
list.add(plugin);
wizard.plugins = list;
valid = true;
return;
}
} catch (PluginException e) {
error_message = e.getMessage();
} catch (Exception e) {
error_message = null;
Debug.printStackTrace(e);
}
valid = false;
if (!fileName.equals("")) {
String error_message_full;
if (new File(fileName).isFile()) {
error_message_full = MessageText.getString("installPluginsWizard.file.invalidfile");
} else {
error_message_full = MessageText.getString("installPluginsWizard.file.no_such_file");
}
if (error_message != null) {
error_message_full += " (" + error_message + ")";
}
wizard.setErrorMessage(error_message_full);
wizard.setNextEnabled(false);
}
}
Aggregations