use of com.biglybt.core.vuzefile.VuzeFile in project BiglyBT by BiglySoftware.
the class MetaSearchManagerImpl method syncRefresh.
protected void syncRefresh() throws MetaSearchException {
boolean refresh_completed = false;
boolean first_run = false;
try {
refresh_sem.reserve();
first_run = COConfigurationManager.getBooleanParameter("metasearch.refresh.first_run", true);
if (!checked_customization) {
checked_customization = true;
CustomizationManager cust_man = CustomizationManagerFactory.getSingleton();
Customization cust = cust_man.getActiveCustomization();
if (cust != null) {
String cust_name = COConfigurationManager.getStringParameter("metasearch.custom.name", "");
String cust_version = COConfigurationManager.getStringParameter("metasearch.custom.version", "0");
boolean new_name = !cust_name.equals(cust.getName());
boolean new_version = com.biglybt.core.util.Constants.compareVersions(cust_version, cust.getVersion()) < 0;
if (new_name || new_version) {
log("Customization: checking templates for " + cust.getName() + "/" + cust.getVersion());
try {
InputStream[] streams = cust.getResources(Customization.RT_META_SEARCH_TEMPLATES);
if (streams.length > 0 && new_name) {
// reset engines
log(" setting auto-mode to false");
setAutoMode(false);
/*
Engine[] engines = meta_search.getEngines( false, false );
for (int i=0;i<engines.length;i++){
Engine engine = engines[i];
if ( engine.getSelectionState()) == Engine.SEL_STATE_MANUAL_SELECTED ){
}
}
*/
}
for (int i = 0; i < streams.length; i++) {
InputStream is = streams[i];
try {
VuzeFile vf = VuzeFileHandler.getSingleton().loadVuzeFile(is);
if (vf != null) {
VuzeFileComponent[] comps = vf.getComponents();
for (int j = 0; j < comps.length; j++) {
VuzeFileComponent comp = comps[j];
if (comp.getType() == VuzeFileComponent.COMP_TYPE_METASEARCH_TEMPLATE) {
try {
Engine e = getSingleton().importEngine(comp.getContent(), false);
log(" updated " + e.getName());
e.setSelectionState(Engine.SEL_STATE_MANUAL_SELECTED);
} catch (Throwable e) {
Debug.printStackTrace(e);
}
}
}
}
} finally {
try {
is.close();
} catch (Throwable e) {
}
}
}
} finally {
COConfigurationManager.setParameter("metasearch.custom.name", cust.getName());
COConfigurationManager.setParameter("metasearch.custom.version", cust.getVersion());
}
}
}
}
log("Refreshing engines");
// featured templates are always shown - can't be deselected
// popular ones are selected if in 'auto' mode
// manually selected ones are, well, manually selected
Map<Long, PlatformMetaSearchMessenger.templateInfo> vuze_selected_ids = new HashMap<>();
Map<Long, PlatformMetaSearchMessenger.templateInfo> vuze_preload_ids = new HashMap<>();
Set<Long> featured_ids = new HashSet<>();
Set<Long> popular_ids = new HashSet<>();
Set<Long> manual_vuze_ids = new HashSet<>();
boolean auto_mode = isAutoMode();
Engine[] engines = meta_search.getEngines(false, false);
String fud = meta_search.getFUD();
try {
PlatformMetaSearchMessenger.templateInfo[] featured = PlatformMetaSearchMessenger.listFeaturedTemplates(extension_key, fud);
String featured_str = "";
for (int i = 0; i < featured.length; i++) {
PlatformMetaSearchMessenger.templateInfo template = featured[i];
if (!template.isVisible()) {
continue;
}
Long key = new Long(template.getId());
vuze_selected_ids.put(key, template);
featured_ids.add(key);
featured_str += (featured_str.length() == 0 ? "" : ",") + key;
}
log("Featured templates: " + featured_str);
if (auto_mode || first_run) {
PlatformMetaSearchMessenger.templateInfo[] popular = PlatformMetaSearchMessenger.listTopPopularTemplates(extension_key, fud);
String popular_str = "";
String preload_str = "";
for (int i = 0; i < popular.length; i++) {
PlatformMetaSearchMessenger.templateInfo template = popular[i];
if (!template.isVisible()) {
continue;
}
Long key = new Long(template.getId());
if (auto_mode) {
if (!vuze_selected_ids.containsKey(key)) {
vuze_selected_ids.put(key, template);
popular_ids.add(key);
popular_str += (popular_str.length() == 0 ? "" : ",") + key;
}
} else {
if (!vuze_preload_ids.containsKey(key)) {
vuze_preload_ids.put(key, template);
preload_str += (preload_str.length() == 0 ? "" : ",") + key;
}
}
}
log("Popular templates: " + popular_str);
if (preload_str.length() > 0) {
log("Pre-load templates: " + popular_str);
}
}
// pick up explicitly selected vuze ones
String manual_str = "";
for (int i = 0; i < engines.length; i++) {
Engine engine = engines[i];
Long key = new Long(engine.getId());
if (engine.getSource() == Engine.ENGINE_SOURCE_VUZE && engine.getSelectionState() == Engine.SEL_STATE_MANUAL_SELECTED && !vuze_selected_ids.containsKey(key)) {
manual_vuze_ids.add(key);
}
}
if (manual_vuze_ids.size() > 0) {
long[] manual_ids = new long[manual_vuze_ids.size()];
Iterator<Long> it = manual_vuze_ids.iterator();
int pos = 0;
while (it.hasNext()) {
manual_ids[pos++] = it.next().longValue();
}
PlatformMetaSearchMessenger.templateInfo[] manual = PlatformMetaSearchMessenger.getTemplateDetails(extension_key, manual_ids);
for (int i = 0; i < manual.length; i++) {
PlatformMetaSearchMessenger.templateInfo template = manual[i];
if (!template.isVisible()) {
continue;
}
Long key = new Long(template.getId());
vuze_selected_ids.put(key, template);
manual_str += (manual_str.length() == 0 ? "" : ",") + key;
}
}
log("Manual templates: " + manual_str);
Map<Long, Engine> existing_engine_map = new HashMap<>();
String existing_str = "";
for (int i = 0; i < engines.length; i++) {
Engine engine = engines[i];
Long key = new Long(engine.getId());
existing_engine_map.put(key, engine);
existing_str += (existing_str.length() == 0 ? "" : ",") + key + "[source=" + Engine.ENGINE_SOURCE_STRS[engine.getSource()] + ",type=" + engine.getType() + ",selected=" + Engine.SEL_STATE_STRINGS[engine.getSelectionState()] + "]";
}
log("Existing templates: " + existing_str);
// we've compiled a list of the engines we should have and their latest dates
// update any that are out of date
Iterator<Map.Entry<Long, PlatformMetaSearchMessenger.templateInfo>> it = vuze_selected_ids.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Long, PlatformMetaSearchMessenger.templateInfo> entry = it.next();
vuze_preload_ids.remove(entry.getKey());
long id = entry.getKey().longValue();
PlatformMetaSearchMessenger.templateInfo template = entry.getValue();
long modified = template.getModifiedDate();
Engine this_engine = (Engine) existing_engine_map.get(new Long(id));
boolean update = this_engine == null || this_engine.getLastUpdated() < modified;
if (update) {
PlatformMetaSearchMessenger.templateDetails details = PlatformMetaSearchMessenger.getTemplate(extension_key, id);
log("Downloading definition of template " + id);
log(details.getValue());
if (details.isVisible()) {
try {
this_engine = meta_search.importFromJSONString(details.getType() == PlatformMetaSearchMessenger.templateDetails.ENGINE_TYPE_JSON ? Engine.ENGINE_TYPE_JSON : Engine.ENGINE_TYPE_REGEX, details.getId(), details.getModifiedDate(), details.getRankBias(), details.getName(), details.getValue());
this_engine.setSource(Engine.ENGINE_SOURCE_VUZE);
meta_search.addEngine(this_engine);
} catch (Throwable e) {
log("Failed to import engine '" + details.getValue() + "'", e);
}
}
} else if (this_engine.getRankBias() != template.getRankBias()) {
this_engine.setRankBias(template.getRankBias());
log("Updating rank bias for " + this_engine.getString() + " to " + template.getRankBias());
} else {
log("Not updating " + this_engine.getString() + " as unchanged");
}
if (this_engine != null) {
int sel_state = this_engine.getSelectionState();
if (sel_state == Engine.SEL_STATE_DESELECTED) {
log("Auto-selecting " + this_engine.getString());
this_engine.setSelectionState(Engine.SEL_STATE_AUTO_SELECTED);
} else if (auto_mode && sel_state == Engine.SEL_STATE_MANUAL_SELECTED) {
log("Switching Manual to Auto select for " + this_engine.getString());
this_engine.setSelectionState(Engine.SEL_STATE_AUTO_SELECTED);
}
}
}
// do any pre-loads
it = vuze_preload_ids.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Long, PlatformMetaSearchMessenger.templateInfo> entry = it.next();
long id = ((Long) entry.getKey()).longValue();
Engine this_engine = (Engine) existing_engine_map.get(new Long(id));
if (this_engine == null) {
PlatformMetaSearchMessenger.templateDetails details = PlatformMetaSearchMessenger.getTemplate(extension_key, id);
log("Downloading pre-load definition of template " + id);
log(details.getValue());
if (details.isVisible()) {
try {
this_engine = meta_search.importFromJSONString(details.getType() == PlatformMetaSearchMessenger.templateDetails.ENGINE_TYPE_JSON ? Engine.ENGINE_TYPE_JSON : Engine.ENGINE_TYPE_REGEX, details.getId(), details.getModifiedDate(), details.getRankBias(), details.getName(), details.getValue());
this_engine.setSource(Engine.ENGINE_SOURCE_VUZE);
this_engine.setSelectionState(Engine.SEL_STATE_DESELECTED);
meta_search.addEngine(this_engine);
} catch (Throwable e) {
log("Failed to import engine '" + details.getValue() + "'", e);
}
}
}
}
for (int i = 0; i < engines.length; i++) {
Engine engine = engines[i];
if (engine.getSource() == Engine.ENGINE_SOURCE_VUZE && engine.getSelectionState() == Engine.SEL_STATE_AUTO_SELECTED && !vuze_selected_ids.containsKey(new Long(engine.getId()))) {
log("Deselecting " + engine.getString() + " as no longer visible on Vuze");
engine.setSelectionState(Engine.SEL_STATE_DESELECTED);
}
}
for (int i = 0; i < engines.length; i++) {
Engine engine = engines[i];
if (engine.getSource() == Engine.ENGINE_SOURCE_VUZE && engine.getSelectionState() == Engine.SEL_STATE_MANUAL_SELECTED) {
engine.recordSelectionState();
} else {
engine.checkSelectionStateRecorded();
}
}
refresh_completed = true;
} catch (Throwable e) {
log("Refresh failed", e);
throw (new MetaSearchException("Refresh failed", e));
}
} finally {
if (first_run && refresh_completed) {
COConfigurationManager.setParameter("metasearch.refresh.first_run", false);
}
refresh_sem.release();
initial_refresh_sem.releaseForever();
}
}
use of com.biglybt.core.vuzefile.VuzeFile in project BiglyBT by BiglySoftware.
the class MetaSearchManagerImpl method preInitialise.
public static void preInitialise() {
VuzeFileHandler.getSingleton().addProcessor(new VuzeFileProcessor() {
@Override
public void process(VuzeFile[] files, int expected_types) {
for (int i = 0; i < files.length; i++) {
VuzeFile vf = files[i];
VuzeFileComponent[] comps = vf.getComponents();
for (int j = 0; j < comps.length; j++) {
VuzeFileComponent comp = comps[j];
int comp_type = comp.getType();
if (comp_type == VuzeFileComponent.COMP_TYPE_METASEARCH_TEMPLATE) {
try {
Engine e = getSingleton().importEngine(comp.getContent(), (expected_types & VuzeFileComponent.COMP_TYPE_METASEARCH_TEMPLATE) == 0);
comp.setProcessed();
if (e != null) {
comp.setData(Engine.VUZE_FILE_COMPONENT_ENGINE_KEY, e);
}
} catch (Throwable e) {
Debug.printStackTrace(e);
}
} else if (comp_type == VuzeFileComponent.COMP_TYPE_METASEARCH_OPERATION) {
getSingleton().addOperation(comp.getContent());
comp.setProcessed();
}
}
}
}
});
TorrentUtils.addTorrentAttributeListener(new TorrentUtils.torrentAttributeListener() {
@Override
public void attributeSet(TOTorrent torrent, String attribute, Object value) {
if (attribute == TorrentUtils.TORRENT_AZ_PROP_OBTAINED_FROM && !TorrentUtils.isReallyPrivate(torrent)) {
try {
getSingleton().checkPotentialAssociations(torrent.getHash(), (String) value);
} catch (Throwable e) {
Debug.printStackTrace(e);
}
}
}
});
}
use of com.biglybt.core.vuzefile.VuzeFile in project BiglyBT by BiglySoftware.
the class WebEngine method getWebPageContentSupport.
private pageDetails getWebPageContentSupport(Proxy proxy, String proxy_host, String searchURL, SearchParameter[] searchParameters, Map<String, String> searchContext, String headers, boolean only_if_modified) throws SearchException {
try {
TorrentUtils.setTLSDescription("Search: " + getName());
if (requiresLogin()) {
throw new SearchLoginException("login required");
}
boolean vuze_file = searchURL.toLowerCase().startsWith("vuze:");
if (!vuze_file) {
String[] from_strs = new String[searchParameters.length];
String[] to_strs = new String[searchParameters.length];
for (int i = 0; i < searchParameters.length; i++) {
SearchParameter parameter = searchParameters[i];
from_strs[i] = "%" + parameter.getMatchPattern();
to_strs[i] = URLEncoder.encode(parameter.getValue(), "UTF-8");
}
searchURL = GeneralUtils.replaceAll(searchURL, from_strs, to_strs);
Iterator<Map.Entry<String, String>> it = searchContext.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> entry = it.next();
String key = entry.getKey();
if (supportsContext(key)) {
if (searchURL.indexOf('?') == -1) {
searchURL += "?";
} else {
searchURL += "&";
}
String value = entry.getValue();
searchURL += key + "=" + URLEncoder.encode(value, "UTF-8");
}
}
}
// System.out.println(searchURL);
// hack to support POST by encoding into URL
// http://xxxx/index.php?main=search&azmethod=post_basic:SearchString1=%s&SearchString=&search=Search
ResourceDownloaderFactory rdf = StaticUtilities.getResourceDownloaderFactory();
URL initial_url;
ResourceDownloader initial_url_rd;
int post_pos = searchURL.indexOf("azmethod=");
if (post_pos > 0) {
String post_params = searchURL.substring(post_pos + 9);
searchURL = searchURL.substring(0, post_pos - 1);
debugLog("search_url: " + searchURL + ", post=" + post_params);
initial_url = new URL(searchURL);
int sep = post_params.indexOf(':');
String type = post_params.substring(0, sep);
if (!type.equals("post_basic")) {
throw (new SearchException("Only basic type supported"));
}
post_params = post_params.substring(sep + 1);
if (proxy == null) {
initial_url_rd = rdf.create(initial_url, post_params);
} else {
initial_url_rd = rdf.create(initial_url, post_params, proxy);
}
initial_url_rd.setProperty("URL_Content-Type", "application/x-www-form-urlencoded");
} else {
debugLog("search_url: " + searchURL);
initial_url = new URL(searchURL);
if (proxy == null) {
initial_url_rd = rdf.create(initial_url);
} else {
initial_url_rd = rdf.create(initial_url, proxy);
}
}
if (proxy_host != null) {
initial_url_rd.setProperty("URL_HOST", proxy_host);
}
setHeaders(initial_url_rd, headers);
if (needsAuth && local_cookies != null) {
initial_url_rd.setProperty("URL_Cookie", local_cookies);
} else if (fullCookies != null && fullCookies.length() > 0) {
initial_url_rd.setProperty("URL_Cookie", fullCookies);
}
if (only_if_modified) {
String last_modified = getLocalString(LD_LAST_MODIFIED);
String etag = getLocalString(LD_ETAG);
if (last_modified != null) {
initial_url_rd.setProperty("URL_If-Modified-Since", last_modified);
}
if (etag != null) {
initial_url_rd.setProperty("URL_If-None-Match", etag);
}
}
InputStream is = null;
try {
String content_charset = "UTF-8";
ResourceDownloader mr_rd = null;
if (initial_url.getProtocol().equalsIgnoreCase("file")) {
// handle file://c:/ - map to file:/c:/
String str = initial_url.toExternalForm();
if (initial_url.getAuthority() != null) {
str = str.replaceFirst("://", ":/");
}
int pos = str.indexOf('?');
if (pos != -1) {
str = str.substring(0, pos);
}
is = new FileInputStream(new File(new URL(str).toURI()));
} else {
if (proxy == null) {
initial_url_rd.setProperty("URL_Connect_Timeout", 10 * 1000);
initial_url_rd.setProperty("URL_Read_Timeout", 10 * 1000);
}
mr_rd = rdf.getMetaRefreshDownloader(initial_url_rd);
try {
is = mr_rd.download();
} catch (ResourceDownloaderException e) {
Long response = (Long) mr_rd.getProperty("URL_HTTP_Response");
if (response != null && response.longValue() == 304) {
return (new pageDetails(initial_url, initial_url, ""));
} else {
throw (e);
}
}
if (needsAuth) {
List cookies_list = (List) mr_rd.getProperty("URL_Set-Cookie");
List cookies_set = new ArrayList();
if (cookies_list != null) {
for (int i = 0; i < cookies_list.size(); i++) {
String[] cookies = ((String) cookies_list.get(i)).split(";");
for (int j = 0; j < cookies.length; j++) {
String cookie = cookies[j].trim();
if (cookie.indexOf('=') != -1) {
cookies_set.add(cookie);
}
}
}
}
// well, not much we can do with the cookies anyway as in general the ones
// set are the ones missing/expired, not the existing ones. That is, we can't
// deduce anything from the fact that a required cookie is not 'set' here
// the most we could do is catch a server that explicitly deleted invalid
// cookies by expiring it, but I doubt this is a common practice.
// Also note the complexity of cookie syntax
// Set-Cookie: old standard using expires=, new using MaxAge
// Set-Cookie2:
// Maybe use http://jcookie.sourceforge.net/ if needed
}
if (only_if_modified) {
String last_modified = extractProperty(mr_rd.getProperty("URL_Last-Modified"));
String etag = extractProperty(mr_rd.getProperty("URL_ETag"));
if (last_modified != null) {
setLocalString(LD_LAST_MODIFIED, last_modified);
}
if (etag != null) {
setLocalString(LD_ETAG, etag);
}
}
List cts = (List) mr_rd.getProperty("URL_Content-Type");
if (cts != null && cts.size() > 0) {
String content_type = (String) cts.get(0);
int pos = content_type.toLowerCase().indexOf("charset");
if (pos != -1) {
content_type = content_type.substring(pos + 1);
pos = content_type.indexOf('=');
if (pos != -1) {
content_type = content_type.substring(pos + 1).trim();
pos = content_type.indexOf(';');
if (pos != -1) {
content_type = content_type.substring(0, pos).trim();
}
if (content_type.startsWith("\"")) {
content_type = content_type.substring(1).trim();
}
if (content_type.endsWith("\"")) {
content_type = content_type.substring(0, content_type.length() - 1).trim();
}
try {
if (Charset.isSupported(content_type)) {
debugLog("charset: " + content_type);
content_charset = content_type;
}
} catch (Throwable e) {
try {
// handle lowercase 'utf-8' for example
content_type = content_type.toUpperCase();
if (Charset.isSupported(content_type)) {
debugLog("charset: " + content_type);
content_charset = content_type;
}
} catch (Throwable f) {
log("Content type '" + content_type + "' not supported", f);
}
}
}
}
}
}
ByteArrayOutputStream baos = new ByteArrayOutputStream(8192);
byte[] buffer = new byte[8192];
while (true) {
int len = is.read(buffer);
if (len <= 0) {
break;
}
baos.write(buffer, 0, len);
}
byte[] data = baos.toByteArray();
if (vuze_file) {
try {
VuzeFileHandler vfh = VuzeFileHandler.getSingleton();
VuzeFile vf = vfh.loadVuzeFile(data);
vfh.handleFiles(new VuzeFile[] { vf }, VuzeFileComponent.COMP_TYPE_NONE);
} catch (Throwable e) {
Debug.out(e);
}
return (new pageDetails(initial_url, initial_url, null));
}
String page = null;
String content = new String(data, 0, Math.min(data.length, 2048), content_charset);
String lc_content = content.toLowerCase();
{
// first look for xml charset
// e.g. <?xml version="1.0" encoding="windows-1251" ?>
int pos1 = lc_content.indexOf("<?xml");
if (pos1 != -1) {
int pos2 = lc_content.indexOf("?>");
if (pos2 != -1) {
int pos3 = lc_content.indexOf("encoding", pos1);
if (pos3 != -1) {
pos3 = lc_content.indexOf("\"", pos3);
}
if (pos3 > pos1 && pos3 < pos2) {
pos3++;
int pos4 = lc_content.indexOf("\"", pos3);
if (pos4 > pos3 && pos4 < pos2) {
String encoding = content.substring(pos3, pos4).trim();
try {
if (Charset.isSupported(encoding)) {
debugLog("charset from xml tag: " + encoding);
content_charset = encoding;
// some feeds have crap at the start which makes pos2 mismatch for the above '?' - adjust if necessary
int data_start = pos2;
int max_skip = 64;
while (data[data_start] != '?' && max_skip-- > 0) {
data_start++;
}
page = content.substring(0, pos3) + "utf-8" + content.substring(pos4, pos2) + new String(data, data_start, data.length - data_start, content_charset);
}
} catch (Throwable e) {
log("Content type '" + encoding + "' not supported", e);
}
}
}
}
}
}
if (page == null) {
// next look for http-equiv charset
// e.g. <meta http-equiv="Content-Type" content="text/html; charset=windows-1251" />
int pos = 0;
while (true) {
int pos1 = lc_content.indexOf("http-equiv", pos);
if (pos1 != -1) {
int pos2 = lc_content.indexOf(">", pos1);
if (pos2 != -1) {
int pos3 = lc_content.indexOf("charset", pos1);
if (pos3 != -1 && pos3 < pos2) {
pos3 = lc_content.indexOf("=", pos3);
if (pos3 != -1) {
pos3++;
int pos4 = lc_content.indexOf("\"", pos3);
if (pos4 != -1) {
int pos5 = lc_content.indexOf(";", pos3);
if (pos5 != -1 && pos5 < pos4) {
pos4 = pos5;
}
String encoding = content.substring(pos3, pos4).trim();
try {
if (Charset.isSupported(encoding)) {
debugLog("charset from http-equiv : " + encoding);
content_charset = encoding;
// some feeds have crap at the start which makes pos2 mismatch for the above '?' - adjust if necessary
int data_start = pos2;
int max_skip = 64;
while (data[data_start] != '?' && max_skip-- > 0) {
data_start++;
}
page = content.substring(0, pos3) + "utf-8" + content.substring(pos4, pos2) + new String(data, data_start, data.length - data_start, content_charset);
}
} catch (Throwable e) {
log("Content type '" + encoding + "' not supported", e);
}
break;
}
}
}
pos = pos2;
} else {
break;
}
} else {
break;
}
}
}
if (page == null) {
page = new String(data, content_charset);
}
debugLog("page:");
debugLog(page);
try {
Matcher m = baseTagPattern.matcher(page);
if (m.find()) {
basePage = m.group(1);
debugLog("base_page: " + basePage);
}
} catch (Exception e) {
// No BASE tag in the page
}
URL final_url = initial_url;
if (mr_rd != null) {
URL x = (URL) mr_rd.getProperty("URL_URL");
if (x != null) {
final_url = x;
}
}
return (new pageDetails(initial_url, final_url, page));
} finally {
if (is != null) {
is.close();
}
}
} catch (SearchException e) {
throw (e);
} catch (Throwable e) {
// e.printStackTrace();
debugLog("Failed to load page: " + Debug.getNestedExceptionMessageAndStack(e));
throw (new SearchException("Failed to load page", e));
} finally {
TorrentUtils.setTLSDescription(null);
}
}
use of com.biglybt.core.vuzefile.VuzeFile in project BiglyBT by BiglySoftware.
the class MetaSearchListener method handleMessage.
@Override
public void handleMessage(BrowserMessage message) {
String opid = message.getOperationId();
MetaSearchManager metaSearchManager = MetaSearchManagerFactory.getSingleton();
metaSearchManager.log("BrowserListener: received " + message);
if (OP_SEARCH.equals(opid)) {
Map decodedMap = message.getDecodedMap();
search(decodedMap, null);
} else if (OP_ENGINE_PREFERRED.equals(opid)) {
final Map decodedMap = message.getDecodedMap();
long engine_id = ((Long) decodedMap.get("engine_id")).longValue();
Engine engine = getEngineFromId(engine_id);
if (engine != null) {
metaSearchManager.getMetaSearch().enginePreferred(engine);
}
} else if (OP_ENGINE_LOGIN.equals(opid)) {
final Map decodedMap = message.getDecodedMap();
long engine_id = ((Long) decodedMap.get("engine_id")).longValue();
final Long sid = (Long) decodedMap.get("sid");
final Engine engine = getEngineFromId(engine_id);
if (engine != null && engine instanceof WebEngine) {
final WebEngine webEngine = (WebEngine) engine;
Utils.execSWTThread(new Runnable() {
@Override
public void run() {
new ExternalLoginWindow(new ExternalLoginListener() {
private String previous_cookies;
private boolean search_done;
@Override
public void canceled(ExternalLoginWindow window) {
/* gouss doesn't wan't anything on cancel
if ( !outcome_informed ){
outcome_informed = true;
Map params = getParams( webEngine );
params.put( "error", "operation cancelled" );
sendBrowserMessage("metasearch", "engineFailed", params );
}
*/
}
@Override
public void cookiesFound(ExternalLoginWindow window, String cookies) {
if (handleCookies(cookies, false)) {
window.close();
}
}
@Override
public void done(ExternalLoginWindow window, String cookies) {
handleCookies(cookies, true);
/*
if ( !outcome_informed ){
outcome_informed = true;
Map params = getParams( webEngine );
sendBrowserMessage("metasearch", "engineCompleted", params );
}
*/
}
private boolean handleCookies(String cookies, boolean force_if_ready) {
if (search_done) {
return (false);
}
String[] required = webEngine.getRequiredCookies();
boolean skip_search = required.length == 0 && !force_if_ready;
if (CookieParser.cookiesContain(required, cookies)) {
webEngine.setCookies(cookies);
if (previous_cookies == null || !previous_cookies.equals(cookies)) {
previous_cookies = cookies;
if (!skip_search) {
// search operation will report outcome
search_done = true;
search(decodedMap, webEngine);
}
}
}
return (search_done);
}
}, webEngine.getName(), webEngine.getLoginPageUrl(), false, webEngine.getAuthMethod(), engine.isMine());
}
});
} else {
Map<String, Object> params = new HashMap<>();
if (sid != null) {
params.put("sid", sid);
}
params.put("error", "engine not found or not a web engine");
sendBrowserMessage("metasearch", "engineFailed", params);
}
} else if (OP_GET_LOGIN_COOKIES.equals(opid)) {
final Map decodedMap = message.getDecodedMap();
final String url = ((String) decodedMap.get("url")).replaceAll("%s", "");
Utils.execSWTThread(new Runnable() {
@Override
public void run() {
new ExternalLoginWindow(new ExternalLoginListener() {
@Override
public void canceled(ExternalLoginWindow window) {
sendBrowserMessage("metasearch", "setCookiesFailed", new HashMap());
}
@Override
public void cookiesFound(ExternalLoginWindow window, String cookies) {
}
@Override
public void done(ExternalLoginWindow window, String cookies) {
String[] cookieNames = CookieParser.getCookiesNames(cookies);
Map<String, Object> params = new HashMap<>();
params.put("cookieNames", cookieNames);
params.put("currentCookie", cookies);
params.put("cookieMethod", window.proxyCaptureModeRequired() ? WebEngine.AM_PROXY : WebEngine.AM_TRANSPARENT);
sendBrowserMessage("metasearch", "setCookies", params);
}
}, url, url, true, WebEngine.AM_PROXY, true);
}
});
} else if (OP_GET_ENGINES.equals(opid)) {
String subscriptionId = null;
try {
final Map decodedMap = message.getDecodedMap();
subscriptionId = ((String) decodedMap.get("subs_id"));
} catch (Exception e) {
// No parameters
}
Engine[] engines = null;
if (subscriptionId != null) {
engines = new Engine[0];
Subscription subs = SubscriptionManagerFactory.getSingleton().getSubscriptionByID(subscriptionId);
if (subs != null) {
try {
Engine engine = subs.getEngine();
if (engine != null) {
engines = new Engine[] { engine };
}
} catch (Throwable e) {
Debug.out(e);
}
}
}
if (engines == null) {
engines = metaSearchManager.getMetaSearch().getEngines(true, true);
}
List params = new ArrayList();
for (int i = 0; i < engines.length; i++) {
Engine engine = engines[i];
if (!engine.isActive() || engine.getSource() == Engine.ENGINE_SOURCE_UNKNOWN) {
if (subscriptionId == null) {
continue;
}
}
Map<String, Object> engineMap = new HashMap<>();
engineMap.put("id", new Long(engine.getId()));
engineMap.put("name", engine.getName());
engineMap.put("favicon", engine.getIcon());
engineMap.put("dl_link_css", engine.getDownloadLinkCSS());
engineMap.put("selected", Engine.SEL_STATE_STRINGS[engine.getSelectionState()]);
engineMap.put("type", Engine.ENGINE_SOURCE_STRS[engine.getSource()]);
engineMap.put("shareable", Boolean.valueOf(engine.isShareable()));
params.add(engineMap);
}
sendBrowserMessage("metasearch", "enginesUsed", params);
} else if (OP_GET_ALL_ENGINES.equals(opid)) {
Engine[] engines = metaSearchManager.getMetaSearch().getEngines(false, true);
List params = new ArrayList();
for (int i = 0; i < engines.length; i++) {
Engine engine = engines[i];
if (engine.getSource() == Engine.ENGINE_SOURCE_UNKNOWN) {
continue;
}
Map<String, Object> engineMap = new HashMap<>();
engineMap.put("id", new Long(engine.getId()));
engineMap.put("name", engine.getName());
engineMap.put("favicon", engine.getIcon());
engineMap.put("dl_link_css", engine.getDownloadLinkCSS());
engineMap.put("selected", Engine.SEL_STATE_STRINGS[engine.getSelectionState()]);
engineMap.put("type", Engine.ENGINE_SOURCE_STRS[engine.getSource()]);
engineMap.put("shareable", Boolean.valueOf(engine.isShareable()));
params.add(engineMap);
}
sendBrowserMessage("metasearch", "engineList", params);
} else if (OP_SET_SELECTED_ENGINES.equals(opid)) {
Map decodedMap = message.getDecodedMap();
List template_ids = (List) decodedMap.get("template_ids");
long[] ids = new long[template_ids.size()];
for (int i = 0; i < ids.length; i++) {
Map m = (Map) template_ids.get(i);
ids[i] = ((Long) m.get("id")).longValue();
}
boolean auto = ((Boolean) decodedMap.get("auto")).booleanValue();
// there's some code that attempts to switch to 'auto=true' on first use as
// when 3110 defaults to false and the decision was made to switch this
// disable the behaviour if we are customised
Boolean is_default = (Boolean) decodedMap.get("set_default");
boolean skip = false;
if (is_default != null && is_default.booleanValue()) {
if (CustomizationManagerFactory.getSingleton().getActiveCustomization() != null) {
skip = true;
}
}
try {
if (!skip) {
metaSearchManager.setSelectedEngines(ids, auto);
}
Map<String, Object> params = new HashMap<>();
sendBrowserMessage("metasearch", "setSelectedCompleted", params);
} catch (Throwable e) {
Debug.out(e);
Map<String, Object> params = new HashMap<>();
params.put("error", Debug.getNestedExceptionMessage(e));
sendBrowserMessage("metasearch", "setSelectedFailed", params);
}
} else if (OP_CHANGE_ENGINE_SELECTION.equals(opid)) {
Map decodedMap = message.getDecodedMap();
MetaSearch ms = metaSearchManager.getMetaSearch();
Engine[] engines = ms.getEngines(false, true);
Set selected = new HashSet();
for (int i = 0; i < engines.length; i++) {
Engine e = engines[i];
if (e.getSelectionState() == Engine.SEL_STATE_MANUAL_SELECTED) {
selected.add(new Long(e.getId()));
}
}
List l_engines = (List) decodedMap.get("engines");
for (int i = 0; i < l_engines.size(); i++) {
Map map = (Map) l_engines.get(i);
long id = ((Long) map.get("id")).longValue();
String str = (String) map.get("selected");
if (str.equalsIgnoreCase(Engine.SEL_STATE_STRINGS[Engine.SEL_STATE_MANUAL_SELECTED])) {
selected.add(new Long(id));
} else if (str.equalsIgnoreCase(Engine.SEL_STATE_STRINGS[Engine.SEL_STATE_DESELECTED])) {
selected.remove(new Long(id));
}
}
long[] ids = new long[selected.size()];
Iterator it = selected.iterator();
int pos = 0;
while (it.hasNext()) {
long id = ((Long) it.next()).longValue();
ids[pos++] = id;
}
try {
metaSearchManager.setSelectedEngines(ids, metaSearchManager.isAutoMode());
Map<String, Object> params = new HashMap<>();
sendBrowserMessage("metasearch", "changeEngineSelectionCompleted", params);
} catch (Throwable e) {
Debug.out(e);
Map<String, Object> params = new HashMap<>();
params.put("error", Debug.getNestedExceptionMessage(e));
sendBrowserMessage("metasearch", "changeEngineSelectionFailed", params);
}
} else if (OP_GET_AUTO_MODE.equals(opid)) {
boolean mode = metaSearchManager.isAutoMode();
Map<String, Object> params = new HashMap<>();
params.put("auto", Boolean.valueOf(mode));
boolean custom = CustomizationManagerFactory.getSingleton().getActiveCustomization() != null;
params.put("is_custom", Boolean.valueOf(custom));
sendBrowserMessage("metasearch", "getAutoModeResult", params);
} else if (OP_SAVE_TEMPLATE.equals(opid)) {
Map decodedMap = message.getDecodedMap();
String type_str = (String) decodedMap.get("type");
String name = (String) decodedMap.get("name");
Long l_id = (Long) decodedMap.get("id");
long id = l_id == null ? -1 : l_id.longValue();
String json = (String) decodedMap.get("value");
String cookies = (String) decodedMap.get("current_cookie");
try {
Engine engine = metaSearchManager.addEngine(id, type_str.equals("json") ? Engine.ENGINE_TYPE_JSON : Engine.ENGINE_TYPE_REGEX, name, json);
engine.setMine(true);
if (cookies != null && engine instanceof WebEngine) {
WebEngine we = (WebEngine) engine;
we.setCookies(cookies);
}
Map<String, Object> params = new HashMap<>();
params.put("id", new Long(engine.getId()));
sendBrowserMessage("metasearch", "saveTemplateCompleted", params);
} catch (Throwable e) {
Debug.out(e);
Map<String, Object> params = new HashMap<>();
params.put("id", new Long(id));
params.put("error", Debug.getNestedExceptionMessage(e));
sendBrowserMessage("metasearch", "saveTemplateFailed", params);
}
} else if (OP_LOAD_TEMPLATE.equals(opid)) {
Map decodedMap = message.getDecodedMap();
long id = ((Long) decodedMap.get("id")).longValue();
Engine engine = metaSearchManager.getMetaSearch().getEngine(id);
if (engine == null) {
Map<String, Object> params = new HashMap<>();
params.put("id", new Long(id));
params.put("error", "Template not found");
sendBrowserMessage("metasearch", "loadTemplateFailed", params);
} else {
try {
Map<String, Object> params = new HashMap<>();
params.put("id", new Long(engine.getId()));
params.put("name", engine.getName());
int type = engine.getType();
params.put("type", type < Engine.ENGINE_TYPE_STRS.length ? Engine.ENGINE_TYPE_STRS[type] : type);
params.put("value", JSONObject.escape(engine.exportToJSONString()));
params.put("shareable", Boolean.valueOf(engine.isShareable()));
params.put("uid", engine.getUID());
params.put("supports_direct_download", Boolean.valueOf(engine.supportsField(Engine.FIELD_TORRENTLINK) || engine.supportsField(Engine.FIELD_DOWNLOADBTNLINK)));
params.put("auto_dl_supported", Boolean.valueOf(engine.getAutoDownloadSupported() == Engine.AUTO_DL_SUPPORTED_YES));
sendBrowserMessage("metasearch", "loadTemplateCompleted", params);
} catch (Throwable e) {
Debug.out(e);
Map<String, Object> params = new HashMap<>();
params.put("id", new Long(id));
params.put("error", Debug.getNestedExceptionMessage(e));
sendBrowserMessage("metasearch", "loadTemplateFailed", params);
}
}
} else if (OP_DELETE_TEMPLATE.equals(opid)) {
Map decodedMap = message.getDecodedMap();
long id = ((Long) decodedMap.get("id")).longValue();
Engine engine = metaSearchManager.getMetaSearch().getEngine(id);
if (engine == null) {
Map<String, Object> params = new HashMap<>();
params.put("id", new Long(id));
params.put("error", "Template not found");
sendBrowserMessage("metasearch", "deleteTemplateFailed", params);
} else if (engine.getSource() != Engine.ENGINE_SOURCE_LOCAL) {
Map<String, Object> params = new HashMap<>();
params.put("id", new Long(id));
params.put("error", "Template is not local");
sendBrowserMessage("metasearch", "deleteTemplateFailed", params);
} else {
engine.delete();
Map<String, Object> params = new HashMap<>();
params.put("id", new Long(id));
sendBrowserMessage("metasearch", "deleteTemplateCompleted", params);
}
} else if (OP_TEST_TEMPLATE.equals(opid)) {
Map decodedMap = message.getDecodedMap();
final long id = ((Long) decodedMap.get("id")).longValue();
long match_count = ((Long) decodedMap.get("max_matches")).longValue();
String searchText = (String) decodedMap.get("searchText");
String headers = (String) decodedMap.get("headers");
final Long sid = (Long) decodedMap.get("sid");
Engine engine = metaSearchManager.getMetaSearch().getEngine(id);
if (engine == null) {
Map<String, Object> params = new HashMap<>();
params.put("id", new Long(id));
params.put("error", "Template not found");
if (sid != null)
params.put("sid", sid);
sendBrowserMessage("metasearch", "testTemplateFailed", params);
} else {
SearchParameter parameter = new SearchParameter("s", searchText);
SearchParameter[] parameters = new SearchParameter[] { parameter };
try {
engine.search(parameters, new HashMap(), (int) match_count, (int) match_count, headers, new ResultListener() {
private String content;
private List matches = new ArrayList();
@Override
public void contentReceived(Engine engine, String _content) {
content = _content;
}
@Override
public void matchFound(Engine engine, String[] fields) {
matches.add(fields);
}
@Override
public void resultsReceived(Engine engine, Result[] results) {
}
@Override
public void resultsComplete(Engine engine) {
Map<String, Object> params = new HashMap<>();
params.put("id", new Long(id));
if (sid != null)
params.put("sid", sid);
params.put("content", JSONObject.escape(content));
JSONArray l_matches = new JSONArray();
params.put("matches", l_matches);
for (int i = 0; i < matches.size(); i++) {
String[] match = (String[]) matches.get(i);
JSONArray l_match = new JSONArray();
l_matches.add(l_match);
Collections.addAll(l_match, match);
}
sendBrowserMessage("metasearch", "testTemplateCompleted", params);
}
@Override
public void engineFailed(Engine engine, Throwable e) {
Debug.out(e);
Map<String, Object> params = new HashMap<>();
params.put("id", new Long(id));
params.put("error", Debug.getNestedExceptionMessage(e));
if (sid != null)
params.put("sid", sid);
sendBrowserMessage("metasearch", "testTemplateFailed", params);
}
@Override
public void engineRequiresLogin(Engine engine, Throwable e) {
Map<String, Object> params = new HashMap<>();
params.put("id", new Long(id));
params.put("error", Debug.getNestedExceptionMessage(e));
if (sid != null)
params.put("sid", sid);
sendBrowserMessage("metasearch", "testTemplateRequiresLogin", params);
}
});
} catch (SearchException e) {
// listener handles
}
}
} else if (OP_EXPORT_TEMPLATE.equals(opid)) {
Map decodedMap = message.getDecodedMap();
final long id = ((Long) decodedMap.get("id")).longValue();
final Engine engine = metaSearchManager.getMetaSearch().getEngine(id);
if (engine == null) {
Map<String, Object> params = new HashMap<>();
params.put("error", "template '" + id + "' not found");
sendBrowserMessage("metasearch", "exportTemplateFailed", params);
} else {
final Shell shell = Utils.findAnyShell();
shell.getDisplay().asyncExec(new AERunnable() {
@Override
public void runSupport() {
FileDialog dialog = new FileDialog(shell, SWT.SYSTEM_MODAL | SWT.SAVE);
dialog.setFilterPath(TorrentOpener.getFilterPathData());
dialog.setText(MessageText.getString("metasearch.export.select.template.file"));
dialog.setFilterExtensions(VuzeFileHandler.getVuzeFileFilterExtensions());
dialog.setFilterNames(VuzeFileHandler.getVuzeFileFilterExtensions());
String path = TorrentOpener.setFilterPathData(dialog.open());
if (path != null) {
if (!VuzeFileHandler.isAcceptedVuzeFileName(path)) {
path = VuzeFileHandler.getVuzeFileName(path);
}
try {
engine.exportToVuzeFile(new File(path));
Map<String, Object> params = new HashMap<>();
params.put("id", new Long(id));
sendBrowserMessage("metasearch", "exportTemplateCompleted", params);
} catch (Throwable e) {
Debug.out(e);
Map<String, Object> params = new HashMap<>();
params.put("id", new Long(id));
params.put("error", "save failed: " + Debug.getNestedExceptionMessage(e));
sendBrowserMessage("metasearch", "exportTemplateFailed", params);
}
} else {
Map<String, Object> params = new HashMap<>();
params.put("id", new Long(id));
params.put("error", "operation cancelled");
sendBrowserMessage("metasearch", "exportTemplateFailed", params);
}
}
});
}
} else if (OP_IMPORT_TEMPLATE.equals(opid)) {
final Shell shell = Utils.findAnyShell();
shell.getDisplay().asyncExec(new AERunnable() {
@Override
public void runSupport() {
FileDialog dialog = new FileDialog(shell, SWT.SYSTEM_MODAL | SWT.OPEN);
dialog.setFilterPath(TorrentOpener.getFilterPathData());
dialog.setText(MessageText.getString("metasearch.import.select.template.file"));
dialog.setFilterExtensions(VuzeFileHandler.getVuzeFileFilterExtensions());
dialog.setFilterNames(VuzeFileHandler.getVuzeFileFilterExtensions());
String path = TorrentOpener.setFilterPathData(dialog.open());
if (path != null) {
VuzeFileHandler vfh = VuzeFileHandler.getSingleton();
VuzeFile vf = vfh.loadAndHandleVuzeFile(path, VuzeFileComponent.COMP_TYPE_METASEARCH_TEMPLATE);
if (vf == null) {
Map<String, Object> params = new HashMap<>();
params.put("error", "invalid .biglybt file");
sendBrowserMessage("metasearch", "importTemplateFailed", params);
} else {
VuzeFileComponent[] comps = vf.getComponents();
for (int i = 0; i < comps.length; i++) {
VuzeFileComponent comp = comps[i];
if (comp.getType() == VuzeFileComponent.COMP_TYPE_METASEARCH_TEMPLATE) {
Engine engine = (Engine) comp.getData(Engine.VUZE_FILE_COMPONENT_ENGINE_KEY);
if (engine != null) {
Map<String, Object> params = new HashMap<>();
params.put("id", new Long(engine.getId()));
sendBrowserMessage("metasearch", "importTemplateCompleted", params);
return;
}
}
}
Map<String, Object> params = new HashMap<>();
params.put("error", "invalid search template file");
sendBrowserMessage("metasearch", "importTemplateFailed", params);
}
} else {
Map<String, Object> params = new HashMap<>();
// don't change this message as the UI uses it!
params.put("error", "operation cancelled");
sendBrowserMessage("metasearch", "importTemplateFailed", params);
}
}
});
} else if (OP_OPEN_SEARCH_RESULTS.equals(opid)) {
Map decodedMap = message.getDecodedMap();
openCloseSearchDetailsListener.openSearchResults(decodedMap);
} else if (OP_CLOSE_SEARCH_RESULTS.equals(opid)) {
Map decodedMap = message.getDecodedMap();
openCloseSearchDetailsListener.closeSearchResults(decodedMap);
} else if (OP_LOAD_TORRENT.equals(opid)) {
Map decodedMap = message.getDecodedMap();
String torrentUrl = (String) decodedMap.get("torrent_url");
String referer_str = (String) decodedMap.get("referer_url");
try {
Map headers = UrlUtils.getBrowserHeaders(referer_str);
String subscriptionId = ((String) decodedMap.get("subs_id"));
String subscriptionResultId = ((String) decodedMap.get("subs_rid"));
if (subscriptionId != null) {
Subscription subs = SubscriptionManagerFactory.getSingleton().getSubscriptionByID(subscriptionId);
if (subs != null) {
try {
Engine engine = subs.getEngine();
if (engine != null && engine instanceof WebEngine) {
WebEngine webEngine = (WebEngine) engine;
if (webEngine.isNeedsAuth()) {
headers.put("Cookie", webEngine.getCookies());
}
}
} catch (Throwable e) {
Debug.out(e);
}
if (subscriptionResultId != null) {
subs.addPotentialAssociation(subscriptionResultId, torrentUrl);
}
}
} else {
try {
long engineID = ((Long) decodedMap.get("engine_id")).longValue();
Engine engine = metaSearchManager.getMetaSearch().getEngine(engineID);
if (engine != null) {
engine.addPotentialAssociation(torrentUrl);
}
if (engine != null && engine instanceof WebEngine) {
WebEngine webEngine = (WebEngine) engine;
if (webEngine.isNeedsAuth()) {
headers.put("Cookie", webEngine.getCookies());
}
}
} catch (Throwable e) {
Debug.printStackTrace(e);
}
}
try {
String hash = (String) decodedMap.get("hash");
if (hash != null) {
if (!torrentUrl.toLowerCase(Locale.US).startsWith("magnet:")) {
headers.put("X-Alternative-URI-1", UrlUtils.getMagnetURI(Base32.decode(hash)));
}
}
} catch (Throwable e) {
}
PluginInitializer.getDefaultInterface().getDownloadManager().addDownload(new URL(torrentUrl), headers);
Map<String, Object> params = new HashMap<>();
params.put("torrent_url", torrentUrl);
params.put("referer_url", referer_str);
sendBrowserMessage("metasearch", "loadTorrentCompleted", params);
} catch (Exception e) {
Map<String, Object> params = new HashMap<>();
params.put("torrent_url", torrentUrl);
params.put("referer_url", referer_str);
params.put("error", e.getMessage());
sendBrowserMessage("metasearch", "loadTorrentFailed", params);
}
} else if (OP_HAS_LOAD_TORRENT.equals(opid)) {
Map<String, Object> params = new HashMap<>();
params.put("result", "1");
sendBrowserMessage("metasearch", "hasLoadTorrent", params);
} else if (OP_CREATE_SUBSCRIPTION.equals(opid)) {
Map decodedMap = message.getDecodedMap();
Long tid = (Long) decodedMap.get("tid");
String name = (String) decodedMap.get("name");
Boolean isPublic = (Boolean) decodedMap.get("is_public");
Map options = (Map) decodedMap.get("options");
Boolean isEnabled = (Boolean) options.get("is_enabled");
Boolean autoDownload = (Boolean) options.get("auto_dl");
Map<String, Object> result = new HashMap<>();
if (tid != null)
result.put("tid", tid);
try {
JSONObject payload = new JSONObject();
// change this you need to change update too below
payload.put("engine_id", decodedMap.get("engine_id"));
payload.put("search_term", decodedMap.get("search_term"));
payload.put("filters", decodedMap.get("filters"));
payload.put("schedule", decodedMap.get("schedule"));
payload.put("options", decodedMap.get("options"));
Subscription subs = SubscriptionManagerFactory.getSingleton().create(name, isPublic.booleanValue(), payload.toString());
subs.getHistory().setDetails(isEnabled == null ? true : isEnabled.booleanValue(), autoDownload == null ? false : autoDownload.booleanValue());
result.put("id", subs.getID());
subs.requestAttention();
sendBrowserMessage("metasearch", "createSubscriptionCompleted", result);
} catch (Throwable e) {
Debug.out(e);
result.put("error", "create failed: " + Debug.getNestedExceptionMessage(e));
sendBrowserMessage("metasearch", "createSubscriptionFailed", result);
}
} else if (OP_READ_SUBSCRIPTION.equals(opid)) {
Map decodedMap = message.getDecodedMap();
final Long tid = (Long) decodedMap.get("tid");
final String sid = (String) decodedMap.get("id");
Map<String, Object> result = new HashMap<>();
if (tid != null)
result.put("tid", tid);
try {
Subscription subs = SubscriptionManagerFactory.getSingleton().getSubscriptionByID(sid);
if (subs == null) {
result.put("error", "Subscription not found");
sendBrowserMessage("metasearch", "readSubscriptionFailed", result);
} else {
boolean shareable = subs.isShareable();
// override public flag if not shareable
result.put("id", subs.getID());
result.put("name", subs.getName());
result.put("is_public", Boolean.valueOf(shareable && subs.isPublic()));
result.put("is_author", Boolean.valueOf(subs.isMine()));
result.put("is_shareable", Boolean.valueOf(shareable));
result.put("auto_dl_supported", Boolean.valueOf(subs.isAutoDownloadSupported()));
SubscriptionHistory history = subs.getHistory();
Map<String, Object> options = new HashMap<>();
result.put("options", options);
options.put("is_enabled", Boolean.valueOf(history.isEnabled()));
options.put("auto_dl", Boolean.valueOf(history.isAutoDownload()));
Map<String, Object> info = new HashMap<>();
result.put("info", info);
info.put("last_scan", new Long(history.getLastScanTime()));
info.put("last_new", new Long(history.getLastNewResultTime()));
info.put("num_unread", new Long(history.getNumUnread()));
info.put("num_read", new Long(history.getNumRead()));
String json = subs.getJSON();
Map map = JSONUtils.decodeJSON(json);
result.put("engine_id", map.get("engine_id"));
result.put("search_term", map.get("search_term"));
result.put("filters", map.get("filters"));
result.put("schedule", map.get("schedule"));
sendBrowserMessage("metasearch", "readSubscriptionCompleted", result);
}
} catch (Throwable e) {
Debug.out(e);
result.put("error", "read failed: " + Debug.getNestedExceptionMessage(e));
sendBrowserMessage("metasearch", "readSubscriptionFailed", result);
}
} else if (OP_UPDATE_SUBSCRIPTION.equals(opid)) {
Map decodedMap = message.getDecodedMap();
final Long tid = (Long) decodedMap.get("tid");
final String name = (String) decodedMap.get("name");
final Boolean isPublic = (Boolean) decodedMap.get("is_public");
final String sid = (String) decodedMap.get("id");
Map options = (Map) decodedMap.get("options");
Boolean isEnabled = (Boolean) options.get("is_enabled");
Boolean autoDownload = (Boolean) options.get("auto_dl");
Map<String, Object> result = new HashMap<>();
if (tid != null)
result.put("tid", tid);
try {
Subscription subs = SubscriptionManagerFactory.getSingleton().getSubscriptionByID(sid);
if (subs == null) {
result.put("error", "Subscription not found");
sendBrowserMessage("metasearch", "updateSubscriptionFailed", result);
} else {
JSONObject payload = new JSONObject();
// change this you need to change create too above
payload.put("engine_id", decodedMap.get("engine_id"));
payload.put("search_term", decodedMap.get("search_term"));
payload.put("filters", decodedMap.get("filters"));
payload.put("schedule", decodedMap.get("schedule"));
payload.put("options", decodedMap.get("options"));
boolean changed = subs.setDetails(name, isPublic.booleanValue(), payload.toString());
subs.getHistory().setDetails(isEnabled == null ? true : isEnabled.booleanValue(), autoDownload == null ? false : autoDownload.booleanValue());
if (changed) {
subs.reset();
try {
subs.getManager().getScheduler().downloadAsync(subs, true);
} catch (Throwable e) {
Debug.out(e);
}
}
result.put("id", subs.getID());
sendBrowserMessage("metasearch", "updateSubscriptionCompleted", result);
}
} catch (Throwable e) {
Debug.out(e);
result.put("error", "update failed: " + Debug.getNestedExceptionMessage(e));
sendBrowserMessage("metasearch", "updateSubscriptionFailed", result);
}
} else if (OP_SUBSCRIPTION_SET_AUTODL.equals(opid)) {
Map decodedMap = message.getDecodedMap();
String sid = (String) decodedMap.get("id");
Long tid = (Long) decodedMap.get("tid");
Boolean autoDownload = (Boolean) decodedMap.get("auto_dl");
Map<String, Object> result = new HashMap<>();
if (tid != null)
result.put("tid", tid);
try {
Subscription subs = SubscriptionManagerFactory.getSingleton().getSubscriptionByID(sid);
if (subs == null) {
result.put("error", "Subscription not found");
sendBrowserMessage("metasearch", "setSubscriptionAutoDownloadFailed", result);
} else {
subs.getHistory().setAutoDownload(autoDownload.booleanValue());
sendBrowserMessage("metasearch", "setSubscriptionAutoDownloadCompleted", result);
}
} catch (Throwable e) {
Debug.out(e);
result.put("error", "update failed: " + Debug.getNestedExceptionMessage(e));
sendBrowserMessage("metasearch", "setSubscriptionAutoDownloadFailed", result);
}
} else if (OP_READ_SUBSCRIPTION_RESULTS.equals(opid)) {
Map decodedMap = message.getDecodedMap();
final Long tid = (Long) decodedMap.get("tid");
final String sid = (String) decodedMap.get("id");
final Map<String, Object> result = new HashMap<>();
if (tid != null)
result.put("tid", tid);
try {
final Subscription subs = SubscriptionManagerFactory.getSingleton().getSubscriptionByID(sid);
if (subs == null) {
result.put("error", "Subscription not found");
sendBrowserMessage("metasearch", "readSubscriptionResultsFailed", result);
} else {
result.put("id", subs.getID());
if (!handleSubscriptionAuth(subs, result)) {
if (subs.getHistory().getLastScanTime() == 0) {
subs.getManager().getScheduler().download(subs, false, new SubscriptionDownloadListener() {
@Override
public void complete(Subscription subs) {
if (!handleSubscriptionAuth(subs, result)) {
encodeResults(subs, result);
sendBrowserMessage("metasearch", "readSubscriptionResultsCompleted", result);
openCloseSearchDetailsListener.resizeMainBrowser();
}
}
@Override
public void failed(Subscription subs, SubscriptionException error) {
Debug.out(error);
result.put("error", "read failed: " + Debug.getNestedExceptionMessage(error));
sendBrowserMessage("metasearch", "readSubscriptionResultsFailed", result);
}
});
} else {
encodeResults(subs, result);
sendBrowserMessage("metasearch", "readSubscriptionResultsCompleted", result);
openCloseSearchDetailsListener.resizeMainBrowser();
}
}
}
} catch (Throwable e) {
Debug.out(e);
result.put("error", "read failed: " + Debug.getNestedExceptionMessage(e));
sendBrowserMessage("metasearch", "readSubscriptionFailed", result);
}
} else if (OP_DELETE_SUBSCRIPTION_RESULTS.equals(opid)) {
Map decodedMap = message.getDecodedMap();
String sid = (String) decodedMap.get("id");
List rids = (List) decodedMap.get("rids");
try {
Subscription subs = SubscriptionManagerFactory.getSingleton().getSubscriptionByID(sid);
if (subs == null) {
Map<String, Object> params = new HashMap<>();
params.put("error", "Subscription not found");
sendBrowserMessage("metasearch", "deleteSubscriptionResultsFailed", params);
} else {
String[] rids_a = (String[]) rids.toArray(new String[rids.size()]);
subs.getHistory().deleteResults(rids_a);
Map<String, Object> result = new HashMap<>();
result.put("rids", rids);
sendBrowserMessage("metasearch", "deleteSubscriptionResultsCompleted", result);
}
} catch (Throwable e) {
Debug.out(e);
Map<String, Object> params = new HashMap<>();
params.put("error", "delete failed: " + Debug.getNestedExceptionMessage(e));
sendBrowserMessage("metasearch", "deleteSubscriptionResultsFailed", params);
}
} else if (OP_MARK_SUBSCRIPTION_RESULTS.equals(opid)) {
Map decodedMap = message.getDecodedMap();
String sid = (String) decodedMap.get("id");
List rids = (List) decodedMap.get("rids");
List reads = (List) decodedMap.get("reads");
Map<String, Object> result = new HashMap<>();
try {
Subscription subs = SubscriptionManagerFactory.getSingleton().getSubscriptionByID(sid);
if (subs == null) {
result.put("error", "Subscription not found");
sendBrowserMessage("metasearch", "markSubscriptionResultsFailed", result);
} else {
String[] rids_a = (String[]) rids.toArray(new String[rids.size()]);
boolean[] reads_a = new boolean[reads.size()];
for (int i = 0; i < reads.size(); i++) {
reads_a[i] = ((Boolean) reads.get(i)).booleanValue();
}
subs.getHistory().markResults(rids_a, reads_a);
result.put("rids", rids);
result.put("reads", reads);
sendBrowserMessage("metasearch", "markSubscriptionResultsCompleted", result);
}
} catch (Throwable e) {
Debug.out(e);
result.put("error", "mark failed: " + Debug.getNestedExceptionMessage(e));
sendBrowserMessage("metasearch", "markSubscriptionResultsFailed", result);
}
} else if (OP_DOWNLOAD_SUBSCRIPTION.equals(opid)) {
Map decodedMap = message.getDecodedMap();
final Long tid = (Long) decodedMap.get("tid");
final String sid = (String) decodedMap.get("id");
final Map<String, Object> result = new HashMap<>();
if (tid != null)
result.put("tid", tid);
try {
Subscription subs = SubscriptionManagerFactory.getSingleton().getSubscriptionByID(sid);
if (subs == null) {
result.put("error", "Subscription not found");
sendBrowserMessage("metasearch", "downloadSubscriptionFailed", result);
} else {
result.put("id", subs.getID());
if (!handleSubscriptionAuth(subs, result)) {
subs.getManager().getScheduler().download(subs, false, new SubscriptionDownloadListener() {
@Override
public void complete(Subscription subs) {
if (!handleSubscriptionAuth(subs, result)) {
encodeResults(subs, result);
sendBrowserMessage("metasearch", "downloadSubscriptionCompleted", result);
}
}
@Override
public void failed(Subscription subs, SubscriptionException error) {
Debug.out(error);
result.put("error", "read failed: " + Debug.getNestedExceptionMessage(error));
sendBrowserMessage("metasearch", "downloadSubscriptionFailed", result);
}
});
}
}
} catch (Throwable e) {
Debug.out(e);
result.put("error", "read failed: " + Debug.getNestedExceptionMessage(e));
sendBrowserMessage("metasearch", "downloadSubscriptionFailed", result);
}
} else if (OP_IS_CUSTOMISED.equals(opid)) {
boolean custom = CustomizationManagerFactory.getSingleton().getActiveCustomization() != null;
Map<String, Object> params = new HashMap<>();
params.put("is_custom", Boolean.valueOf(custom));
sendBrowserMessage("metasearch", "isCustomizedResult", params);
}
}
use of com.biglybt.core.vuzefile.VuzeFile in project BiglyBT by BiglySoftware.
the class CoreImpl method start.
@Override
public void start() throws CoreException {
if (!canStart()) {
throw (new CoreException("Core: already started (alternative process)"));
}
AEThread2.setOurThread();
try {
this_mon.enter();
if (started) {
throw (new CoreException("Core: already started"));
}
if (stopped) {
throw (new CoreException("Core: already stopped"));
}
started = true;
} finally {
this_mon.exit();
}
// If a user sets this property, it is an alias for the following settings.
if ("1".equals(System.getProperty(SystemProperties.SYSPROP_SAFEMODE))) {
if (Logger.isEnabled())
Logger.log(new LogEvent(LOGID, "Safe mode enabled"));
Constants.isSafeMode = true;
System.setProperty(SystemProperties.SYSPROP_LOADPLUGINS, "0");
System.setProperty(SystemProperties.SYSPROP_DISABLEDOWNLOADS, "1");
System.setProperty(SystemProperties.SYSPROP_SKIP_SWTCHECK, "1");
// Not using localised text - not sure it's safe to this early.
Logger.log(new LogAlert(LogAlert.UNREPEATABLE, LogEvent.LT_WARNING, "You are running " + Constants.APP_NAME + " in safe mode - you " + "can change your configuration, but any downloads added will " + "not be remembered when you close " + Constants.APP_NAME + "."));
}
/**
* test to see if UI plays nicely with a really slow initialization
*/
String sDelayCore = System.getProperty("delay.core", null);
if (sDelayCore != null) {
try {
long delayCore = Long.parseLong(sDelayCore);
Thread.sleep(delayCore);
} catch (Exception e) {
e.printStackTrace();
}
}
// run plugin loading in parallel to the global manager loading
AEThread2 pluginload = new AEThread2("PluginLoader", true) {
@Override
public void run() {
if (Logger.isEnabled())
Logger.log(new LogEvent(LOGID, "Loading of Plugins starts"));
pi.loadPlugins(CoreImpl.this, false, !"0".equals(System.getProperty(SystemProperties.SYSPROP_LOADPLUGINS)), true, true);
if (Logger.isEnabled())
Logger.log(new LogEvent(LOGID, "Loading of Plugins complete"));
}
};
if (LOAD_PLUGINS_IN_OTHER_THREAD) {
pluginload.start();
} else {
pluginload.run();
}
// Disable async loading of existing torrents, because there are many things
// (like hosting) that require all the torrents to be loaded. While we
// can write code for each of these cases to wait until the torrents are
// loaded, it's a pretty big job to find them all and fix all their quirks.
// Too big of a job for this late in the release stage.
// Other example is the tracker plugin that is coded in a way where it must
// always publish a complete rss feed
global_manager = GlobalManagerFactory.create(this, null, 0);
if (stopped) {
System.err.println("Core stopped while starting");
return;
}
// wait until plugin loading is done
if (LOAD_PLUGINS_IN_OTHER_THREAD) {
pluginload.join();
}
if (stopped) {
System.err.println("Core stopped while starting");
return;
}
VuzeFileHandler.getSingleton().addProcessor(new VuzeFileProcessor() {
@Override
public void process(VuzeFile[] files, int expected_types) {
for (int i = 0; i < files.length; i++) {
VuzeFile vf = files[i];
VuzeFileComponent[] comps = vf.getComponents();
for (int j = 0; j < comps.length; j++) {
VuzeFileComponent comp = comps[j];
int comp_type = comp.getType();
if (comp_type == VuzeFileComponent.COMP_TYPE_ADD_TORRENT) {
PluginInterface default_pi = getPluginManager().getDefaultPluginInterface();
Map map = comp.getContent();
try {
Torrent torrent;
String url = MapUtils.getMapString(map, "torrent_url", null);
if (url != null) {
TorrentDownloader dl = default_pi.getTorrentManager().getURLDownloader(new URL(url));
torrent = dl.download();
} else {
String tf = MapUtils.getMapString(map, "torrent_file", null);
if (tf != null) {
File file = new File(tf);
if (!file.canRead() || file.isDirectory()) {
throw (new Exception("torrent_file '" + tf + "' is invalid"));
}
torrent = default_pi.getTorrentManager().createFromBEncodedFile(file);
} else {
throw (new Exception("torrent_url or torrent_file must be specified"));
}
}
File dest = null;
String save_folder = MapUtils.getMapString(map, "save_folder", null);
if (save_folder != null) {
dest = new File(save_folder, torrent.getName());
} else {
String save_file = MapUtils.getMapString(map, "save_file", null);
if (save_file != null) {
dest = new File(save_file);
}
}
if (dest != null) {
dest.getParentFile().mkdirs();
}
default_pi.getDownloadManager().addDownload(torrent, null, dest);
} catch (Throwable e) {
Debug.out(e);
}
comp.setProcessed();
}
}
}
}
});
triggerLifeCycleComponentCreated(global_manager);
pi.initialisePlugins();
if (stopped) {
System.err.println("Core stopped while starting");
return;
}
if (Logger.isEnabled())
Logger.log(new LogEvent(LOGID, "Initializing Plugins complete"));
try {
PluginInterface dht_pi = getPluginManager().getPluginInterfaceByClass(DHTPlugin.class);
if (dht_pi != null) {
dht_pi.addEventListener(new PluginEventListener() {
private boolean first_dht = true;
@Override
public void handleEvent(PluginEvent ev) {
if (ev.getType() == DHTPlugin.EVENT_DHT_AVAILABLE) {
if (first_dht) {
first_dht = false;
DHT dht = (DHT) ev.getValue();
dht.addListener(new DHTListener() {
@Override
public void speedTesterAvailable(DHTSpeedTester tester) {
if (speed_manager != null) {
speed_manager.setSpeedTester(tester);
}
}
});
global_manager.addListener(new GlobalManagerAdapter() {
@Override
public void seedingStatusChanged(boolean seeding_only_mode, boolean b) {
checkConfig();
}
});
COConfigurationManager.addAndFireParameterListeners(new String[] { TransferSpeedValidator.AUTO_UPLOAD_ENABLED_CONFIGKEY, TransferSpeedValidator.AUTO_UPLOAD_SEEDING_ENABLED_CONFIGKEY }, new ParameterListener() {
@Override
public void parameterChanged(String parameterName) {
checkConfig();
}
});
}
}
}
protected void checkConfig() {
if (speed_manager != null) {
speed_manager.setEnabled(TransferSpeedValidator.isAutoSpeedActive(global_manager));
}
}
});
}
} catch (Throwable e) {
}
if (COConfigurationManager.getBooleanParameter("Resume Downloads On Start")) {
global_manager.resumeDownloads();
}
VersionCheckClient.getSingleton().initialise();
instance_manager.initialize();
NetworkManager.getSingleton().initialize(this);
SpeedLimitHandler.getSingleton(this);
Runtime.getRuntime().addShutdownHook(new AEThread("Shutdown Hook") {
@Override
public void runSupport() {
Logger.log(new LogEvent(LOGID, "Shutdown hook triggered"));
CoreImpl.this.stop();
}
});
DelayedTask delayed_task = UtilitiesImpl.addDelayedTask("Core", new Runnable() {
@Override
public void run() {
new AEThread2("core:delayTask", true) {
@Override
public void run() {
AEDiagnostics.checkDumpsAndNatives();
COConfigurationManager.setParameter("diags.enable.pending.writes", true);
AEDiagnostics.flushPendingLogs();
NetworkAdmin na = NetworkAdmin.getSingleton();
na.runInitialChecks(CoreImpl.this);
na.addPropertyChangeListener(new NetworkAdminPropertyChangeListener() {
private String last_as;
@Override
public void propertyChanged(String property) {
NetworkAdmin na = NetworkAdmin.getSingleton();
if (property.equals(NetworkAdmin.PR_NETWORK_INTERFACES)) {
boolean found_usable = false;
NetworkAdminNetworkInterface[] intf = na.getInterfaces();
for (int i = 0; i < intf.length; i++) {
NetworkAdminNetworkInterfaceAddress[] addresses = intf[i].getAddresses();
for (int j = 0; j < addresses.length; j++) {
if (!addresses[j].isLoopback()) {
found_usable = true;
}
}
}
if (!found_usable) {
return;
}
Logger.log(new LogEvent(LOGID, "Network interfaces have changed (new=" + na.getNetworkInterfacesAsString() + ")"));
announceAll(false);
} else if (property.equals(NetworkAdmin.PR_AS)) {
String as = na.getCurrentASN().getAS();
if (last_as == null) {
last_as = as;
} else if (!as.equals(last_as)) {
Logger.log(new LogEvent(LOGID, "AS has changed (new=" + as + ")"));
last_as = as;
announceAll(false);
}
}
}
});
setupSleepAndCloseActions();
}
}.start();
}
});
delayed_task.queue();
if (stopped) {
System.err.println("Core stopped while starting");
return;
}
PairingManagerFactory.getSingleton();
CoreRunningListener[] runningListeners;
mon_coreRunningListeners.enter();
try {
if (coreRunningListeners == null) {
runningListeners = new CoreRunningListener[0];
} else {
runningListeners = coreRunningListeners.toArray(new CoreRunningListener[0]);
coreRunningListeners = null;
}
} finally {
mon_coreRunningListeners.exit();
}
// Trigger Listeners now that core is started
new AEThread2("Plugin Init Complete", false) {
@Override
public void run() {
try {
PlatformManagerFactory.getPlatformManager().startup(CoreImpl.this);
} catch (Throwable e) {
Debug.out("PlatformManager: init failed", e);
}
Iterator it = lifecycle_listeners.iterator();
while (it.hasNext()) {
try {
CoreLifecycleListener listener = (CoreLifecycleListener) it.next();
if (!listener.requiresPluginInitCompleteBeforeStartedEvent()) {
listener.started(CoreImpl.this);
}
} catch (Throwable e) {
Debug.printStackTrace(e);
}
}
pi.initialisationComplete();
it = lifecycle_listeners.iterator();
while (it.hasNext()) {
try {
CoreLifecycleListener listener = (CoreLifecycleListener) it.next();
if (listener.requiresPluginInitCompleteBeforeStartedEvent()) {
listener.started(CoreImpl.this);
}
} catch (Throwable e) {
Debug.printStackTrace(e);
}
}
}
}.start();
// Typically there are many runningListeners, most with quick execution, and
// a few longer ones. Let 3 run at a time, queue the rest. Without
// a ThreadPool, the slow ones would delay the startup processes that run
// after this start() method
ThreadPool tp = new ThreadPool("Trigger CoreRunning Listeners", 3);
for (final CoreRunningListener l : runningListeners) {
try {
tp.run(new AERunnable() {
@Override
public void runSupport() {
l.coreRunning(CoreImpl.this);
}
});
} catch (Throwable t) {
Debug.out(t);
}
}
// Debug.out("Core Start Complete");
}
Aggregations