use of com.biglybt.core.torrent.TOTorrent in project BiglyBT by BiglySoftware.
the class TorrentOpener method addTorrent.
/**
* @param torrentOptions
* @return
* @since 5.0.0.1
*
* @TODO: Remove SWT UI parts (use UIFunctions) and move out of SWT tree
*/
public static final boolean addTorrent(final TorrentOpenOptions torrentOptions) {
try {
if (torrentOptions.getTorrent() == null) {
return false;
}
final DownloadManagerInitialisationAdapter dmia = new DownloadManagerInitialisationAdapter() {
@Override
public int getActions() {
return (ACT_ASSIGNS_TAGS);
}
@Override
public void initialised(DownloadManager dm, boolean for_seeding) {
DiskManagerFileInfoSet file_info_set = dm.getDiskManagerFileInfoSet();
DiskManagerFileInfo[] fileInfos = file_info_set.getFiles();
boolean reorder_mode = COConfigurationManager.getBooleanParameter("Enable reorder storage mode");
int reorder_mode_min_mb = COConfigurationManager.getIntParameter("Reorder storage mode min MB");
try {
dm.getDownloadState().suppressStateSave(true);
boolean[] toSkip = new boolean[fileInfos.length];
boolean[] toCompact = new boolean[fileInfos.length];
boolean[] toReorderCompact = new boolean[fileInfos.length];
int[] priorities = null;
int comp_num = 0;
int reorder_comp_num = 0;
final TorrentOpenFileOptions[] files = torrentOptions.getFiles();
for (int iIndex = 0; iIndex < fileInfos.length; iIndex++) {
DiskManagerFileInfo fileInfo = fileInfos[iIndex];
if (iIndex >= 0 && iIndex < files.length && files[iIndex].lSize == fileInfo.getLength()) {
// Always pull destination file from fileInfo and not from
// TorrentFileInfo because the destination may have changed
// by magic code elsewhere
File fDest = fileInfo.getFile(true);
if (files[iIndex].isLinked()) {
fDest = files[iIndex].getDestFileFullName();
// Can't use fileInfo.setLink(fDest) as it renames
// the existing file if there is one
dm.getDownloadState().setFileLink(iIndex, fileInfo.getFile(false), fDest);
}
if (files[iIndex].isToDownload()) {
int priority = files[iIndex].getPriority();
if (priority != 0) {
if (priorities == null) {
priorities = new int[fileInfos.length];
}
priorities[iIndex] = priority;
}
} else {
toSkip[iIndex] = true;
if (!fDest.exists()) {
if (reorder_mode && (fileInfo.getLength() / (1024 * 1024)) >= reorder_mode_min_mb) {
toReorderCompact[iIndex] = true;
reorder_comp_num++;
} else {
toCompact[iIndex] = true;
comp_num++;
}
}
}
}
}
if (files.length == 1) {
TorrentOpenFileOptions file = files[0];
if (file.isManualRename()) {
String fileRename = file.getDestFileName();
if (fileRename != null && fileRename.length() > 0) {
dm.getDownloadState().setDisplayName(fileRename);
}
}
} else {
String folderRename = torrentOptions.getManualRename();
if (folderRename != null && folderRename.length() > 0) {
dm.getDownloadState().setDisplayName(folderRename);
}
}
if (comp_num > 0) {
file_info_set.setStorageTypes(toCompact, DiskManagerFileInfo.ST_COMPACT);
}
if (reorder_comp_num > 0) {
file_info_set.setStorageTypes(toReorderCompact, DiskManagerFileInfo.ST_REORDER_COMPACT);
}
file_info_set.setSkipped(toSkip, true);
if (priorities != null) {
file_info_set.setPriority(priorities);
}
int maxUp = torrentOptions.getMaxUploadSpeed();
int kInB = DisplayFormatters.getKinB();
if (maxUp > 0) {
dm.getStats().setUploadRateLimitBytesPerSecond(maxUp * kInB);
}
int maxDown = torrentOptions.getMaxDownloadSpeed();
if (maxDown > 0) {
dm.getStats().setDownloadRateLimitBytesPerSecond(maxDown * kInB);
}
DownloadManagerState dm_state = dm.getDownloadState();
if (torrentOptions.disableIPFilter) {
dm_state.setFlag(DownloadManagerState.FLAG_DISABLE_IP_FILTER, true);
}
if (torrentOptions.peerSource != null) {
for (String peerSource : torrentOptions.peerSource.keySet()) {
boolean enable = torrentOptions.peerSource.get(peerSource);
dm_state.setPeerSourceEnabled(peerSource, enable);
}
}
Map<String, Boolean> enabledNetworks = torrentOptions.getEnabledNetworks();
if (enabledNetworks != null) {
if (!dm_state.getFlag(DownloadManagerState.FLAG_INITIAL_NETWORKS_SET)) {
for (String net : enabledNetworks.keySet()) {
boolean enable = enabledNetworks.get(net);
dm_state.setNetworkEnabled(net, enable);
}
}
}
List<Tag> initialTags = torrentOptions.getInitialTags();
for (Tag t : initialTags) {
t.addTaggable(dm);
}
List<List<String>> trackers = torrentOptions.getTrackers(true);
if (trackers != null) {
TOTorrent torrent = dm.getTorrent();
TorrentUtils.listToAnnounceGroups(trackers, torrent);
try {
TorrentUtils.writeToFile(torrent);
} catch (Throwable e2) {
Debug.printStackTrace(e2);
}
}
if (torrentOptions.bSequentialDownload) {
dm_state.setFlag(DownloadManagerState.FLAG_SEQUENTIAL_DOWNLOAD, true);
}
File moc = torrentOptions.getMoveOnComplete();
if (moc != null) {
dm_state.setAttribute(DownloadManagerState.AT_MOVE_ON_COMPLETE_DIR, moc.getAbsolutePath());
}
} finally {
dm.getDownloadState().suppressStateSave(false);
}
}
};
CoreFactory.addCoreRunningListener(new CoreRunningListener() {
@Override
public void coreRunning(Core core) {
TOTorrent torrent = torrentOptions.getTorrent();
byte[] hash = null;
try {
hash = torrent.getHash();
} catch (TOTorrentException e1) {
}
int iStartState = (torrentOptions.getStartMode() == TorrentOpenOptions.STARTMODE_STOPPED) ? DownloadManager.STATE_STOPPED : DownloadManager.STATE_QUEUED;
GlobalManager gm = core.getGlobalManager();
DownloadManager dm = gm.addDownloadManager(torrentOptions.sFileName, hash, torrentOptions.getParentDir(), torrentOptions.getSubDir(), iStartState, true, torrentOptions.getStartMode() == TorrentOpenOptions.STARTMODE_SEEDING, dmia);
// since gm.addDown.. will handle it.
if (dm == null) {
return;
}
if (torrentOptions.iQueueLocation == TorrentOpenOptions.QUEUELOCATION_TOP) {
gm.moveTop(new DownloadManager[] { dm });
}
if (torrentOptions.getStartMode() == TorrentOpenOptions.STARTMODE_FORCESTARTED) {
dm.setForceStart(true);
}
}
});
} catch (Exception e) {
UIFunctions uif = UIFunctionsManager.getUIFunctions();
if (uif != null) {
uif.showErrorMessage("OpenTorrentWindow.mb.openError", Debug.getStackTrace(e), new String[] { torrentOptions.sOriginatingLocation, e.getMessage() });
}
return false;
}
return true;
}
use of com.biglybt.core.torrent.TOTorrent in project BiglyBT by BiglySoftware.
the class GeneralView method refresh.
public void refresh() {
if (gFile == null || gFile.isDisposed() || manager == null)
return;
loopFactor++;
if ((loopFactor % graphicsUpdate) == 0) {
updateAvailability();
availabilityImage.redraw();
updatePiecesInfo(false);
piecesImage.redraw();
}
DiskManager dm = manager.getDiskManager();
String remaining;
String eta = DisplayFormatters.formatETA(manager.getStats().getSmoothedETA());
if (dm != null) {
long rem = dm.getRemainingExcludingDND();
String data_rem = DisplayFormatters.formatByteCountToKiBEtc(rem);
if (rem > 0) {
remaining = eta + (eta.length() == 0 ? "" : " ") + data_rem;
} else {
if (eta.length() == 0) {
remaining = data_rem;
} else {
remaining = eta;
}
}
} else {
// only got eta value, just use that
remaining = eta;
}
setTime(manager.getStats().getElapsedTime(), remaining);
TRTrackerScraperResponse hd = manager.getTrackerScrapeResponse();
String seeds_str = manager.getNbSeeds() + " " + MessageText.getString("GeneralView.label.connected");
String peers_str = manager.getNbPeers() + " " + MessageText.getString("GeneralView.label.connected");
String completed;
if (hd != null && hd.isValid()) {
seeds_str += " ( " + hd.getSeeds() + " " + MessageText.getString("GeneralView.label.in_swarm") + " )";
peers_str += " ( " + hd.getPeers() + " " + MessageText.getString("GeneralView.label.in_swarm") + " )";
completed = hd.getCompleted() > -1 ? Integer.toString(hd.getCompleted()) : "?";
} else {
completed = "?";
}
String _shareRatio = "";
int sr = manager.getStats().getShareRatio();
if (sr == -1)
_shareRatio = Constants.INFINITY_STRING;
if (sr > 0) {
String partial = "" + sr % 1000;
while (partial.length() < 3) partial = "0" + partial;
_shareRatio = (sr / 1000) + "." + partial;
}
DownloadManagerStats stats = manager.getStats();
String swarm_speed = DisplayFormatters.formatByteCountToKiBEtcPerSec(stats.getTotalAverage()) + " ( " + DisplayFormatters.formatByteCountToKiBEtcPerSec(stats.getTotalAveragePerPeer()) + " " + MessageText.getString("GeneralView.label.averagespeed") + " )";
String swarm_completion = "";
String distributedCopies = "0.000";
String piecesDoneAndSum = "" + manager.getNbPieces();
PEPeerManager pm = manager.getPeerManager();
if (pm != null) {
int comp = pm.getAverageCompletionInThousandNotation();
if (comp >= 0) {
swarm_completion = DisplayFormatters.formatPercentFromThousands(comp);
}
piecesDoneAndSum = pm.getPiecePicker().getNbPiecesDone() + "/" + piecesDoneAndSum;
distributedCopies = new DecimalFormat("0.000").format(pm.getPiecePicker().getMinAvailability() - pm.getNbSeeds() - (pm.isSeeding() && stats.getDownloadCompleted(false) == 1000 ? 1 : 0));
}
int kInB = DisplayFormatters.getKinB();
setStats(DisplayFormatters.formatDownloaded(stats), DisplayFormatters.formatByteCountToKiBEtc(stats.getTotalDataBytesSent()), DisplayFormatters.formatByteCountToKiBEtcPerSec(stats.getDataReceiveRate()), DisplayFormatters.formatByteCountToKiBEtcPerSec(stats.getDataSendRate()), swarm_speed, "" + manager.getStats().getDownloadRateLimitBytesPerSecond() / kInB, "" + (manager.getStats().getUploadRateLimitBytesPerSecond() / kInB), seeds_str, peers_str, completed, DisplayFormatters.formatHashFails(manager), _shareRatio, swarm_completion, distributedCopies);
TOTorrent torrent = manager.getTorrent();
String creation_date = DisplayFormatters.formatDate(manager.getTorrentCreationDate() * 1000);
byte[] created_by = torrent == null ? null : torrent.getCreatedBy();
if (created_by != null) {
try {
creation_date = MessageText.getString("GeneralView.torrent_created_on_and_by", new String[] { creation_date, new String(created_by, Constants.DEFAULT_ENCODING) });
} catch (java.io.UnsupportedEncodingException e) {
/* forget it */
}
}
setInfos(manager.getDisplayName(), DisplayFormatters.formatByteCountToKiBEtc(manager.getSize()), DisplayFormatters.formatDownloadStatus(manager), manager.getState() == DownloadManager.STATE_ERROR, manager.getSaveLocation().toString(), TorrentUtils.nicePrintTorrentHash(torrent), piecesDoneAndSum, manager.getPieceLength(), manager.getTorrentComment(), creation_date, manager.getDownloadState().getUserComment(), MessageText.getString("GeneralView." + (torrent != null && torrent.getPrivate() ? "yes" : "no")));
// the initial layout fails.
if (loopFactor == 2) {
getComposite().layout(true);
}
}
use of com.biglybt.core.torrent.TOTorrent in project BiglyBT by BiglySoftware.
the class PrivacyView method swt_updateFields.
private void swt_updateFields(DownloadManager old_dm, DownloadManager new_dm) {
if (cMainComposite == null || cMainComposite.isDisposed()) {
return;
}
byte[] hash = null;
if (new_dm != null) {
TOTorrent torrent = new_dm.getTorrent();
if (torrent != null) {
try {
hash = torrent.getHash();
} catch (Throwable e) {
}
}
}
i2p_lookup_button.setData("hash", hash);
updateI2PState();
Utils.disposeComposite(i2p_lookup_comp, false);
i2p_result_summary.setText("");
i2p_result_list.setText("");
if (old_dm != null) {
DownloadManagerState state = old_dm.getDownloadState();
state.removeListener(this, DownloadManagerState.AT_NETWORKS, DownloadManagerStateAttributeListener.WRITTEN);
state.removeListener(this, DownloadManagerState.AT_PEER_SOURCES, DownloadManagerStateAttributeListener.WRITTEN);
state.removeListener(this, DownloadManagerState.AT_FLAGS, DownloadManagerStateAttributeListener.WRITTEN);
}
if (new_dm != null) {
DownloadManagerState state = new_dm.getDownloadState();
state.addListener(this, DownloadManagerState.AT_NETWORKS, DownloadManagerStateAttributeListener.WRITTEN);
state.addListener(this, DownloadManagerState.AT_PEER_SOURCES, DownloadManagerStateAttributeListener.WRITTEN);
state.addListener(this, DownloadManagerState.AT_FLAGS, DownloadManagerStateAttributeListener.WRITTEN);
setupNetworksAndSources(new_dm);
setupTorrentTracker(new_dm);
} else {
setupNetworksAndSources(null);
setupTorrentTracker(null);
}
}
use of com.biglybt.core.torrent.TOTorrent in project BiglyBT by BiglySoftware.
the class ScrapeInfoView method initialize.
private void initialize(Composite parent) {
cParent = parent;
Label label;
GridData gridData;
final Display display = parent.getDisplay();
if (cScrapeInfoView == null || cScrapeInfoView.isDisposed()) {
cScrapeInfoView = new Composite(parent, SWT.NONE);
}
gridData = new GridData(GridData.FILL_BOTH);
cScrapeInfoView.setLayoutData(gridData);
GridLayout layoutInfo = new GridLayout();
layoutInfo.numColumns = 4;
cScrapeInfoView.setLayout(layoutInfo);
label = new Label(cScrapeInfoView, SWT.LEFT);
// $NON-NLS-1$
Messages.setLanguageText(label, "GeneralView.label.trackerurl");
label.setCursor(display.getSystemCursor(SWT.CURSOR_HAND));
label.setForeground(Colors.blue);
label.addMouseListener(new MouseAdapter() {
@Override
public void mouseDoubleClick(MouseEvent arg0) {
String announce = trackerUrlValue.getText();
if (announce != null && announce.length() != 0) {
new Clipboard(display).setContents(new Object[] { announce }, new Transfer[] { TextTransfer.getInstance() });
}
}
@Override
public void mouseDown(MouseEvent arg0) {
String announce = trackerUrlValue.getText();
if (announce != null && announce.length() != 0) {
new Clipboard(display).setContents(new Object[] { announce }, new Transfer[] { TextTransfer.getInstance() });
}
}
});
menuTracker = new Menu(parent.getShell(), SWT.POP_UP);
itemSelect = new MenuItem(menuTracker, SWT.CASCADE);
Messages.setLanguageText(itemSelect, "GeneralView.menu.selectTracker");
MenuItem itemEdit = new MenuItem(menuTracker, SWT.NULL);
Messages.setLanguageText(itemEdit, "MyTorrentsView.menu.editTracker");
cScrapeInfoView.addDisposeListener(new DisposeListener() {
@Override
public void widgetDisposed(DisposeEvent e) {
menuTracker.dispose();
}
});
itemEdit.addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event e) {
final TOTorrent torrent = manager.getTorrent();
if (torrent == null) {
return;
}
List<List<String>> group = TorrentUtils.announceGroupsToList(torrent);
new MultiTrackerEditor(null, null, group, new TrackerEditorListener() {
@Override
public void trackersChanged(String str, String str2, List<List<String>> _group) {
TorrentUtils.listToAnnounceGroups(_group, torrent);
try {
TorrentUtils.writeToFile(torrent);
} catch (Throwable e2) {
Debug.printStackTrace(e2);
}
TRTrackerAnnouncer tc = manager.getTrackerClient();
if (tc != null) {
tc.resetTrackerUrl(true);
}
}
}, true, true);
}
});
TOTorrent torrent = manager == null ? null : manager.getTorrent();
itemEdit.setEnabled(torrent != null && !TorrentUtils.isReallyPrivate(torrent));
final Listener menuListener = new Listener() {
@Override
public void handleEvent(Event e) {
if (e.widget instanceof MenuItem) {
String text = ((MenuItem) e.widget).getText();
TOTorrent torrent = manager.getTorrent();
TorrentUtils.announceGroupsSetFirst(torrent, text);
try {
TorrentUtils.writeToFile(torrent);
} catch (TOTorrentException f) {
Debug.printStackTrace(f);
}
TRTrackerAnnouncer tc = manager.getTrackerClient();
if (tc != null) {
tc.resetTrackerUrl(false);
}
}
}
};
menuTracker.addListener(SWT.Show, new Listener() {
@Override
public void handleEvent(Event e) {
Menu menuSelect = itemSelect.getMenu();
if (menuSelect != null && !menuSelect.isDisposed()) {
menuSelect.dispose();
}
if (manager == null || cScrapeInfoView == null || cScrapeInfoView.isDisposed()) {
return;
}
List<List<String>> groups = TorrentUtils.announceGroupsToList(manager.getTorrent());
menuSelect = new Menu(cScrapeInfoView.getShell(), SWT.DROP_DOWN);
itemSelect.setMenu(menuSelect);
for (List<String> trackers : groups) {
MenuItem menuItem = new MenuItem(menuSelect, SWT.CASCADE);
Messages.setLanguageText(menuItem, "wizard.multitracker.group");
Menu menu = new Menu(cScrapeInfoView.getShell(), SWT.DROP_DOWN);
menuItem.setMenu(menu);
for (String url : trackers) {
MenuItem menuItemTracker = new MenuItem(menu, SWT.CASCADE);
menuItemTracker.setText(url);
menuItemTracker.addListener(SWT.Selection, menuListener);
}
}
}
});
trackerUrlValue = new BufferedTruncatedLabel(cScrapeInfoView, SWT.LEFT, 70);
trackerUrlValue.addMouseListener(new MouseAdapter() {
@Override
public void mouseDown(MouseEvent event) {
if (event.button == 3 || (event.button == 1 && event.stateMask == SWT.CONTROL)) {
menuTracker.setVisible(true);
} else if (event.button == 1) {
String url = trackerUrlValue.getText();
if (url.startsWith("http://") || url.startsWith("https://")) {
int pos = -1;
if ((pos = url.indexOf("/announce")) != -1) {
url = url.substring(0, pos + 1);
}
Utils.launch(url);
}
}
}
});
gridData = new GridData(GridData.FILL_HORIZONTAL);
gridData.horizontalSpan = 3;
trackerUrlValue.setLayoutData(gridData);
// //////////////////////
label = new Label(cScrapeInfoView, SWT.LEFT);
Messages.setLanguageText(label, "GeneralView.label.tracker");
tracker_status = new BufferedTruncatedLabel(cScrapeInfoView, SWT.LEFT, 150);
gridData = new GridData(GridData.FILL_HORIZONTAL);
gridData.horizontalSpan = 3;
tracker_status.setLayoutData(gridData);
label = new Label(cScrapeInfoView, SWT.LEFT);
Messages.setLanguageText(label, "GeneralView.label.updatein");
trackerUpdateIn = new BufferedLabel(cScrapeInfoView, SWT.LEFT);
gridData = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_CENTER);
trackerUpdateIn.setLayoutData(gridData);
updateButton = new Button(cScrapeInfoView, SWT.PUSH);
Messages.setLanguageText(updateButton, "GeneralView.label.trackerurlupdate");
updateButton.setLayoutData(new GridData());
updateButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
new AEThread2("SIV:async") {
@Override
public void run() {
if (manager.getTrackerClient() != null) {
manager.requestTrackerAnnounce(false);
} else {
manager.requestTrackerScrape(true);
}
}
}.start();
}
});
cScrapeInfoView.layout(true);
}
use of com.biglybt.core.torrent.TOTorrent in project BiglyBT by BiglySoftware.
the class ScrapeInfoView method setTracker.
private void setTracker() {
if (cScrapeInfoView == null || cScrapeInfoView.isDisposed()) {
return;
}
Display display = cScrapeInfoView.getDisplay();
String status = manager.getTrackerStatus();
int time = manager.getTrackerTime();
TRTrackerAnnouncer trackerClient = manager.getTrackerClient();
if (trackerClient != null) {
tracker_status.setText(trackerClient.getStatusString());
time = trackerClient.getTimeUntilNextUpdate();
} else {
tracker_status.setText(status);
}
if (time < 0) {
trackerUpdateIn.setText(MessageText.getString("GeneralView.label.updatein.querying"));
} else {
trackerUpdateIn.setText(TimeFormatter.formatColon(time));
}
boolean update_state;
String trackerURL = null;
if (trackerClient != null) {
URL temp = trackerClient.getTrackerURL();
if (temp != null) {
trackerURL = temp.toString();
}
}
if (trackerURL == null) {
TOTorrent torrent = manager.getTorrent();
if (torrent != null) {
trackerURL = torrent.getAnnounceURL().toString();
}
}
if (trackerURL != null) {
trackerUrlValue.setText(trackerURL);
if ((trackerURL.startsWith("http://") || trackerURL.startsWith("https://"))) {
trackerUrlValue.setForeground(Colors.blue);
trackerUrlValue.setCursor(display.getSystemCursor(SWT.CURSOR_HAND));
Messages.setLanguageText(trackerUrlValue.getWidget(), "GeneralView.label.trackerurlopen.tooltip", true);
} else {
trackerUrlValue.setForeground(null);
trackerUrlValue.setCursor(null);
Messages.setLanguageText(trackerUrlValue.getWidget(), null);
trackerUrlValue.setToolTipText(null);
}
}
if (trackerClient != null) {
update_state = ((SystemTime.getCurrentTime() / 1000 - trackerClient.getLastUpdateTime() >= TRTrackerAnnouncer.REFRESH_MINIMUM_SECS));
} else {
TRTrackerScraperResponse sr = manager.getTrackerScrapeResponse();
if (sr == null) {
update_state = true;
} else {
update_state = ((SystemTime.getCurrentTime() - sr.getScrapeStartTime() >= TRTrackerScraper.REFRESH_MINIMUM_SECS * 1000));
}
}
if (updateButton.getEnabled() != update_state) {
updateButton.setEnabled(update_state);
}
cScrapeInfoView.layout();
}
Aggregations