use of com.biglybt.core.torrent.TOTorrent in project BiglyBT by BiglySoftware.
the class SubscriptionImpl method checkPublish.
protected void checkPublish() {
synchronized (this) {
if (destroyed) {
return;
}
if (isSingleton()) {
return;
}
if (!isSubscribed()) {
return;
}
if (popularity > 100) {
if (lws_skip_check == 2) {
return;
} else if (lws_skip_check == 0) {
if (RandomUtils.nextInt((int) ((popularity + 99) / 100)) == 0) {
lws_skip_check = 1;
} else {
lws_skip_check = 2;
return;
}
}
}
if (hash != null) {
boolean create = false;
if (lws == null) {
create = true;
} else {
if (!Arrays.equals(lws.getHash().getBytes(), hash)) {
lws.remove();
create = true;
}
}
if (create) {
try {
File original_data_location = manager.getVuzeFile(this);
if (original_data_location.exists()) {
// make a version based filename to avoid issues regarding multiple
// versions
final File versioned_data_location = new File(original_data_location.getParent(), original_data_location.getName() + "." + getVersion());
if (!versioned_data_location.exists()) {
if (!FileUtil.copyFile(original_data_location, versioned_data_location)) {
throw (new Exception("Failed to copy file to '" + versioned_data_location + "'"));
}
}
lws = LightWeightSeedManager.getSingleton().add(getName(), new HashWrapper(hash), TorrentUtils.getDecentralisedEmptyURL(), versioned_data_location, isAnonymous() ? AENetworkClassifier.AT_I2P : AENetworkClassifier.AT_PUBLIC, new LightWeightSeedAdapter() {
@Override
public TOTorrent getTorrent(byte[] hash, URL announce_url, File data_location) throws Exception {
log("Generating light-weight torrent: hash=" + ByteFormatter.encodeString(hash));
TOTorrentCreator creator = TOTorrentFactory.createFromFileOrDirWithFixedPieceLength(data_location, announce_url, 256 * 1024);
TOTorrent t = creator.create();
t.setHashOverride(hash);
return (t);
}
});
}
} catch (Throwable e) {
log("Failed to create light-weight-seed", e);
}
}
}
}
}
use of com.biglybt.core.torrent.TOTorrent in project BiglyBT by BiglySoftware.
the class SubscriptionManagerImpl method downloadTorrent.
protected Object[] downloadTorrent(byte[] hash, int update_size) {
if (!isSubsDownloadEnabled()) {
log(" Can't download subscription " + Base32.encode(hash) + " as feature disabled");
return (null);
}
final MagnetPlugin magnet_plugin = getMagnetPlugin();
if (magnet_plugin == null) {
log(" Can't download, no magnet plugin");
return (null);
}
try {
final InetSocketAddress[] sender = { null };
byte[] torrent_data = magnet_plugin.download(new MagnetPluginProgressListener() {
@Override
public void reportSize(long size) {
}
@Override
public void reportActivity(String str) {
log(" MagnetDownload: " + str);
}
@Override
public void reportCompleteness(int percent) {
}
@Override
public void reportContributor(InetSocketAddress address) {
synchronized (sender) {
sender[0] = address;
}
}
@Override
public boolean verbose() {
return (false);
}
@Override
public boolean cancelled() {
return (false);
}
}, hash, "", new InetSocketAddress[0], 300 * 1000, MagnetPlugin.FL_DISABLE_MD_LOOKUP);
if (torrent_data == null) {
log(" download failed - timeout");
return (null);
}
log("Subscription torrent downloaded");
TOTorrent torrent = TOTorrentFactory.deserialiseFromBEncodedByteArray(torrent_data);
if (torrent.getSize() > update_size + 10 * 1024) {
log("Subscription download abandoned, torrent size is " + torrent.getSize() + ", underlying data size is " + update_size);
return (null);
}
if (torrent.getSize() > 4 * 1024 * 1024) {
log("Subscription download abandoned, torrent size is too large (" + torrent.getSize() + ")");
return (null);
}
synchronized (sender) {
return (new Object[] { torrent, sender[0] });
}
} catch (Throwable e) {
log(" download failed", e);
return (null);
}
}
use of com.biglybt.core.torrent.TOTorrent in project BiglyBT by BiglySoftware.
the class SubscriptionManagerImpl method initWithCore.
protected void initWithCore(Core _core) {
synchronized (this) {
if (started) {
return;
}
started = true;
}
core = _core;
final PluginInterface default_pi = PluginInitializer.getDefaultInterface();
rss_publisher = new SubscriptionRSSFeed(this, default_pi);
TorrentManager tm = default_pi.getTorrentManager();
ta_subs_download = tm.getPluginAttribute("azsubs.subs_dl");
ta_subs_download_rd = tm.getPluginAttribute("azsubs.subs_dl_rd");
ta_subscription_info = tm.getPluginAttribute("azsubs.subs_info");
ta_category = tm.getAttribute(TorrentAttribute.TA_CATEGORY);
ta_networks = tm.getAttribute(TorrentAttribute.TA_NETWORKS);
PluginInterface dht_plugin_pi = CoreFactory.getSingleton().getPluginManager().getPluginInterfaceByClass(DHTPlugin.class);
if (dht_plugin_pi != null) {
dht_plugin_public = (DHTPlugin) dht_plugin_pi.getPlugin();
/*
if ( Constants.isCVSVersion()){
addListener(
new SubscriptionManagerListener()
{
public void
subscriptionAdded(
Subscription subscription )
{
}
public void
subscriptionChanged(
Subscription subscription )
{
}
public void
subscriptionRemoved(
Subscription subscription )
{
}
public void
associationsChanged(
byte[] hash )
{
System.out.println( "Subscriptions changed: " + ByteFormatter.encodeString( hash ));
Subscription[] subs = getKnownSubscriptions( hash );
for (int i=0;i<subs.length;i++){
System.out.println( " " + subs[i].getString());
}
}
});
}
*/
default_pi.getDownloadManager().addListener(new DownloadManagerListener() {
@Override
public void downloadAdded(Download download) {
Torrent torrent = download.getTorrent();
if (torrent != null) {
byte[] hash = torrent.getHash();
Object[] entry;
synchronized (potential_associations2) {
entry = (Object[]) potential_associations2.remove(new HashWrapper(hash));
}
if (entry != null) {
SubscriptionImpl[] subs = (SubscriptionImpl[]) entry[0];
String subs_str = "";
for (int i = 0; i < subs.length; i++) {
subs_str += (i == 0 ? "" : ",") + subs[i].getName();
}
log("Applying deferred asocciation for " + ByteFormatter.encodeString(hash) + " -> " + subs_str);
recordAssociationsSupport(hash, subs, ((Boolean) entry[1]).booleanValue());
}
}
}
@Override
public void downloadRemoved(Download download) {
}
}, false);
default_pi.getDownloadManager().addDownloadWillBeAddedListener(new DownloadWillBeAddedListener() {
@Override
public void initialised(Download download) {
Torrent torrent = download.getTorrent();
if (torrent != null) {
byte[] hash = torrent.getHash();
HashWrapper hw = new HashWrapper(hash);
Object[] entry;
synchronized (potential_associations2) {
entry = (Object[]) potential_associations2.get(hw);
}
if (entry != null) {
SubscriptionImpl[] subs = (SubscriptionImpl[]) entry[0];
prepareDownload(download, subs, null);
} else {
synchronized (potential_associations3) {
entry = potential_associations3.get(hw);
}
if (entry != null) {
Subscription[] subs = (Subscription[]) entry[0];
SubscriptionResult[] results = (SubscriptionResult[]) entry[1];
prepareDownload(download, subs, results);
}
}
}
}
});
TorrentUtils.addTorrentAttributeListener(new TorrentUtils.torrentAttributeListener() {
@Override
public void attributeSet(TOTorrent torrent, String attribute, Object value) {
if (attribute == TorrentUtils.TORRENT_AZ_PROP_OBTAINED_FROM) {
try {
checkPotentialAssociations(torrent.getHash(), (String) value);
} catch (Throwable e) {
Debug.printStackTrace(e);
}
}
}
});
DelayedTask delayed_task = UtilitiesImpl.addDelayedTask("Subscriptions", new Runnable() {
@Override
public void run() {
new AEThread2("Subscriptions:delayInit", true) {
@Override
public void run() {
asyncInit();
}
}.start();
}
protected void asyncInit() {
Download[] downloads = default_pi.getDownloadManager().getDownloads();
for (int i = 0; i < downloads.length; i++) {
Download download = downloads[i];
if (download.getBooleanAttribute(ta_subs_download)) {
Map rd = download.getMapAttribute(ta_subs_download_rd);
boolean delete_it;
if (rd == null) {
delete_it = true;
} else {
delete_it = !recoverSubscriptionUpdate(download, rd);
}
if (delete_it) {
removeDownload(download, true);
}
}
}
default_pi.getDownloadManager().addListener(new DownloadManagerListener() {
@Override
public void downloadAdded(final Download download) {
if (!downloadIsIgnored(download)) {
if (!dht_plugin_public.isInitialising()) {
// if new download then we want to check out its subscription status
lookupAssociations(download.getMapAttribute(ta_subscription_info) == null);
} else {
new AEThread2("Subscriptions:delayInit", true) {
@Override
public void run() {
lookupAssociations(download.getMapAttribute(ta_subscription_info) == null);
}
}.start();
}
}
}
@Override
public void downloadRemoved(Download download) {
}
}, false);
for (int i = 0; i < PUB_ASSOC_CONC_MAX; i++) {
if (publishAssociations()) {
break;
}
}
publishSubscriptions();
COConfigurationManager.addParameterListener(CONFIG_MAX_RESULTS, new ParameterListener() {
@Override
public void parameterChanged(String name) {
final int max_results = COConfigurationManager.getIntParameter(CONFIG_MAX_RESULTS);
new AEThread2("Subs:max results changer", true) {
@Override
public void run() {
checkMaxResults(max_results);
}
}.start();
}
});
SimpleTimer.addPeriodicEvent("SubscriptionChecker", TIMER_PERIOD, new TimerEventPerformer() {
private int ticks;
@Override
public void perform(TimerEvent event) {
ticks++;
checkStuff(ticks);
}
});
}
});
delayed_task.queue();
}
if (isSearchEnabled()) {
try {
default_pi.getUtilities().registerSearchProvider(new SearchProvider() {
private Map<Integer, Object> properties = new HashMap<>();
{
properties.put(PR_NAME, MessageText.getString("ConfigView.section.Subscriptions"));
try {
URL url = MagnetURIHandler.getSingleton().registerResource(new MagnetURIHandler.ResourceProvider() {
@Override
public String getUID() {
return (SubscriptionManager.class.getName() + ".2");
}
@Override
public String getFileType() {
return ("png");
}
@Override
public byte[] getData() {
InputStream is = getClass().getClassLoader().getResourceAsStream("com/biglybt/ui/images/subscription_icon_1616.png");
if (is == null) {
return (null);
}
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
byte[] buffer = new byte[8192];
while (true) {
int len = is.read(buffer);
if (len <= 0) {
break;
}
baos.write(buffer, 0, len);
}
} finally {
is.close();
}
return (baos.toByteArray());
} catch (Throwable e) {
return (null);
}
}
});
properties.put(PR_ICON_URL, url.toExternalForm());
} catch (Throwable e) {
Debug.out(e);
}
}
@Override
public SearchInstance search(Map<String, Object> search_parameters, SearchObserver observer) throws SearchException {
try {
return (searchSubscriptions(search_parameters, observer));
} catch (Throwable e) {
throw (new SearchException("Search failed", e));
}
}
@Override
public Object getProperty(int property) {
return (properties.get(property));
}
@Override
public void setProperty(int property, Object value) {
properties.put(property, value);
}
});
} catch (Throwable e) {
Debug.out("Failed to register search provider");
}
}
default_pi.getUtilities().registerJSONRPCServer(new Utilities.JSONServer() {
private List<String> methods = new ArrayList<>();
{
methods.add("vuze-subs-list");
}
@Override
public String getName() {
return ("Subscriptions");
}
@Override
public List<String> getSupportedMethods() {
return (methods);
}
@Override
public Map call(String method, Map args) throws PluginException {
throw (new PluginException("derp"));
}
});
}
use of com.biglybt.core.torrent.TOTorrent in project BiglyBT by BiglySoftware.
the class SubscriptionManagerImpl method downloadSubscription.
private void downloadSubscription(final String description, final TOTorrent torrent, final InetSocketAddress peer, byte[] subs_id, int version, String name, final downloadListener listener) {
try {
// testing purposes, see if local exists
LightWeightSeed lws = LightWeightSeedManager.getSingleton().get(new HashWrapper(torrent.getHash()));
if (lws != null) {
log("Light weight seed found");
listener.complete(lws.getDataLocation());
} else {
String sid = ByteFormatter.encodeString(subs_id);
File dir = getSubsDir();
dir = new File(dir, "temp");
if (!dir.exists()) {
if (!dir.mkdirs()) {
throw (new IOException("Failed to create dir '" + dir + "'"));
}
}
final File torrent_file = new File(dir, sid + "_" + version + ".torrent");
final File data_file = new File(dir, VuzeFileHandler.getVuzeFileName(sid + "_" + version));
PluginInterface pi = PluginInitializer.getDefaultInterface();
final DownloadManager dm = pi.getDownloadManager();
Download download = dm.getDownload(torrent.getHash());
if (download == null) {
log("Adding download for subscription '" + new String(torrent.getName()) + "'");
boolean is_update = getSubscriptionFromSID(subs_id) != null;
PlatformTorrentUtils.setContentTitle(torrent, "Subscription " + (is_update ? "Update" : "Download") + ": " + description + "(" + name + ")");
// PlatformTorrentUtils.setContentThumbnail(torrent, thumbnail);
TorrentUtils.setFlag(torrent, TorrentUtils.TORRENT_FLAG_LOW_NOISE, true);
Torrent t = new TorrentImpl(torrent);
t.setDefaultEncoding();
t.writeToFile(torrent_file);
download = dm.addDownload(t, torrent_file, data_file);
download.setFlag(Download.FLAG_DISABLE_AUTO_FILE_MOVE, true);
download.setBooleanAttribute(ta_subs_download, true);
Map rd = listener.getRecoveryData();
if (rd != null) {
download.setMapAttribute(ta_subs_download_rd, rd);
}
} else {
log("Existing download found for subscription '" + new String(torrent.getName()) + "'");
}
final Download f_download = download;
final TimerEventPeriodic[] event = { null };
event[0] = SimpleTimer.addPeriodicEvent("SM:cancelTimer", 10 * 1000, new TimerEventPerformer() {
private long start_time = SystemTime.getMonotonousTime();
@Override
public void perform(TimerEvent ev) {
boolean kill = false;
try {
Download download = dm.getDownload(torrent.getHash());
if (listener.isCancelled() || download == null) {
kill = true;
} else {
int state = download.getState();
if (state == Download.ST_ERROR) {
log("Download entered error state, removing");
kill = true;
} else {
long now = SystemTime.getMonotonousTime();
long running_for = now - start_time;
if (running_for > 10 * 60 * 1000) {
log("Download hasn't completed in permitted time, removing");
kill = true;
} else if (running_for > 4 * 60 * 1000) {
if (download.getStats().getDownloaded() == 0) {
log("Download has zero downloaded, removing");
kill = true;
}
} else if (running_for > 2 * 60 * 1000) {
DownloadScrapeResult scrape = download.getLastScrapeResult();
if (scrape == null || scrape.getSeedCount() <= 0) {
log("Download has no seeds, removing");
kill = true;
}
}
}
}
} catch (Throwable e) {
log("Download failed", e);
kill = true;
}
if (kill && event[0] != null) {
try {
event[0].cancel();
if (!listener.isCancelled()) {
listener.failed(new SubscriptionException("Download abandoned"));
}
} finally {
removeDownload(f_download, true);
torrent_file.delete();
}
}
}
});
download.addCompletionListener(new DownloadCompletionListener() {
@Override
public void onCompletion(Download d) {
listener.complete(d, torrent_file);
}
});
if (download.isComplete()) {
listener.complete(download, torrent_file);
} else {
download.setForceStart(true);
if (peer != null) {
download.addPeerListener(new DownloadPeerListener() {
@Override
public void peerManagerAdded(Download download, PeerManager peer_manager) {
InetSocketAddress tcp = AddressUtils.adjustTCPAddress(peer, true);
InetSocketAddress udp = AddressUtils.adjustUDPAddress(peer, true);
log(" Injecting peer into download: " + tcp);
peer_manager.addPeer(tcp.getAddress().getHostAddress(), tcp.getPort(), udp.getPort(), true);
}
@Override
public void peerManagerRemoved(Download download, PeerManager peer_manager) {
}
});
}
}
}
} catch (Throwable e) {
log("Failed to add download", e);
listener.failed(e);
}
}
use of com.biglybt.core.torrent.TOTorrent in project BiglyBT by BiglySoftware.
the class TagManagerImpl method taggableAdded.
public void taggableAdded(TagType tag_type, Tag tag, Taggable tagged) {
// hack to support initial-save-location logic when a user manually assigns a tag and the download
// hasn't had files allocated yet (most common scenario is user has 'add-torrent-stopped' set up)
int tt = tag_type.getTagType();
try {
if (tt == TagType.TT_DOWNLOAD_MANUAL && tagged instanceof DownloadManager) {
TagFeatureFileLocation fl = (TagFeatureFileLocation) tag;
if (fl.supportsTagInitialSaveFolder()) {
File save_loc = fl.getTagInitialSaveFolder();
if (save_loc != null) {
DownloadManager dm = (DownloadManager) tagged;
if (dm.getState() == DownloadManager.STATE_STOPPED) {
TOTorrent torrent = dm.getTorrent();
if (torrent != null) {
if (dm.getGlobalManager().getDownloadManager(torrent.getHashWrapper()) != null) {
long options = fl.getTagInitialSaveOptions();
boolean set_data = (options & TagFeatureFileLocation.FL_DATA) != 0;
boolean set_torrent = (options & TagFeatureFileLocation.FL_TORRENT) != 0;
if (set_data) {
File existing_save_loc = dm.getSaveLocation();
if (!(existing_save_loc.equals(save_loc) || existing_save_loc.exists())) {
dm.setTorrentSaveDir(save_loc.getAbsolutePath());
}
}
if (set_torrent) {
File old_torrent_file = new File(dm.getTorrentFileName());
if (old_torrent_file.exists()) {
try {
dm.setTorrentFile(save_loc, old_torrent_file.getName());
} catch (Throwable e) {
Debug.out(e);
}
}
}
}
}
}
}
}
}
} catch (Throwable e) {
Debug.out(e);
}
if (tt == TagType.TT_DOWNLOAD_MANUAL) {
synchronized (lifecycle_handlers) {
long type = tagged.getTaggableType();
LifecycleHandlerImpl handler = lifecycle_handlers.get(type);
if (handler == null) {
handler = new LifecycleHandlerImpl();
lifecycle_handlers.put(type, handler);
}
handler.taggableTagged(tag_type, tag, tagged);
}
}
}
Aggregations