use of com.biglybt.core.torrent.TOTorrentException in project BiglyBT by BiglySoftware.
the class TOTorrentXMLDeserialiser method decodeInfo.
protected void decodeInfo(SimpleXMLParserDocumentNode doc, TOTorrentImpl torrent) throws TOTorrentException {
SimpleXMLParserDocumentNode[] kids = doc.getChildren();
byte[] torrent_name = null;
long torrent_length = 0;
SimpleXMLParserDocumentNode[] file_nodes = null;
for (int i = 0; i < kids.length; i++) {
SimpleXMLParserDocumentNode kid = kids[i];
String name = kid.getName();
if (name.equalsIgnoreCase("PIECE_LENGTH")) {
torrent.setPieceLength(readGenericLong(kid).longValue());
} else if (name.equalsIgnoreCase("LENGTH")) {
torrent.setSimpleTorrent(true);
torrent_length = readGenericLong(kid).longValue();
} else if (name.equalsIgnoreCase("NAME")) {
torrent.setName(readLocalisableString(kid));
} else if (name.equalsIgnoreCase("FILES")) {
torrent.setSimpleTorrent(false);
file_nodes = kid.getChildren();
} else if (name.equalsIgnoreCase("PIECES")) {
SimpleXMLParserDocumentNode[] piece_nodes = kid.getChildren();
byte[][] pieces = new byte[piece_nodes.length][];
for (int j = 0; j < pieces.length; j++) {
pieces[j] = readGenericBytes(piece_nodes[j]);
}
torrent.setPieces(pieces);
} else {
mapEntry entry = readGenericMapEntry(kid);
torrent.addAdditionalInfoProperty(entry.name, entry.value);
}
}
if (torrent.isSimpleTorrent()) {
torrent.setFiles(new TOTorrentFileImpl[] { new TOTorrentFileImpl(torrent, 0, 0, torrent_length, new byte[][] { torrent.getName() }) });
} else {
if (file_nodes == null) {
throw (new TOTorrentException("FILES element missing", TOTorrentException.RT_DECODE_FAILS));
}
TOTorrentFileImpl[] files = new TOTorrentFileImpl[file_nodes.length];
long offset = 0;
for (int j = 0; j < files.length; j++) {
SimpleXMLParserDocumentNode file_node = file_nodes[j];
SimpleXMLParserDocumentNode[] file_entries = file_node.getChildren();
long file_length = 0;
boolean length_entry_found = false;
byte[][] path_comps = null;
Vector additional_props = new Vector();
for (int k = 0; k < file_entries.length; k++) {
SimpleXMLParserDocumentNode file_entry = file_entries[k];
String entry_name = file_entry.getName();
if (entry_name.equalsIgnoreCase("LENGTH")) {
file_length = readGenericLong(file_entry).longValue();
length_entry_found = true;
} else if (entry_name.equalsIgnoreCase("PATH")) {
SimpleXMLParserDocumentNode[] path_nodes = file_entry.getChildren();
path_comps = new byte[path_nodes.length][];
for (int n = 0; n < path_nodes.length; n++) {
path_comps[n] = readLocalisableString(path_nodes[n]);
}
} else {
additional_props.addElement(readGenericMapEntry(file_entry));
}
}
if ((!length_entry_found) || path_comps == null) {
throw (new TOTorrentException("FILE element invalid (file length = " + file_length + ")", TOTorrentException.RT_DECODE_FAILS));
}
files[j] = new TOTorrentFileImpl(torrent, j, offset, file_length, path_comps);
offset += file_length;
for (int k = 0; k < additional_props.size(); k++) {
mapEntry entry = (mapEntry) additional_props.elementAt(k);
files[j].setAdditionalProperty(entry.name, entry.value);
}
}
torrent.setFiles(files);
}
}
use of com.biglybt.core.torrent.TOTorrentException in project BiglyBT by BiglySoftware.
the class TOTorrentXMLSerialiser method serialiseToFile.
protected void serialiseToFile(File file) throws TOTorrentException {
resetIndent();
try {
setOutputStream(new FileOutputStream(file));
writeRoot();
} catch (IOException e) {
throw (new TOTorrentException("TOTorrentXMLSerialiser: file write fails: " + e.toString(), TOTorrentException.RT_WRITE_FAILS));
} finally {
try {
closeOutputStream();
} catch (Throwable e) {
throw (new TOTorrentException("TOTorrentXMLSerialiser: file close fails: " + e.toString(), TOTorrentException.RT_WRITE_FAILS));
}
}
}
use of com.biglybt.core.torrent.TOTorrentException in project BiglyBT by BiglySoftware.
the class TRHostConfigImpl method saveConfig.
protected void saveConfig(boolean immediate) {
if (loading) {
return;
}
synchronized (saved_stats_to_delete) {
if (saved_stats_to_delete.size() > 0) {
Map saved_stats_copy = new HashMap(saved_stats);
for (int i = 0; i < saved_stats_to_delete.size(); i++) {
saved_stats_copy.remove(saved_stats_to_delete.get(i));
}
saved_stats_to_delete.clear();
saved_stats = saved_stats_copy;
}
}
if (immediate || save_outstanding) {
save_outstanding = false;
try {
Map map = new HashMap();
List list = new ArrayList();
TRHostTorrent[] torrents = host.getTorrents();
List stats_entries = new ArrayList();
Set added = new HashSet();
for (int i = 0; i < torrents.length; i++) {
try {
TRHostTorrent torrent = (TRHostTorrent) torrents[i];
added.add(torrent.getTorrent().getHashWrapper());
StringBuffer stats_entry = new StringBuffer(2048);
byte[] hash = torrent.getTorrent().getHash();
byte[] name = torrent.getTorrent().getName();
int status = torrent.getStatus();
long completed = torrent.getCompletedCount();
long announces = torrent.getAnnounceCount();
long scrapes = torrent.getScrapeCount();
long uploaded = torrent.getTotalUploaded();
long downloaded = torrent.getTotalDownloaded();
long bytes_in = torrent.getTotalBytesIn();
long bytes_out = torrent.getTotalBytesOut();
long date_added = torrent.getDateAdded();
int seed_count = torrent.getSeedCount();
int non_seed_count = torrent.getLeecherCount();
Map t_map = new HashMap();
t_map.put("persistent", new Long(torrent.isPersistent() ? 1 : 0));
t_map.put("passive", new Long(torrent.isPassive() ? 1 : 0));
if (torrent.isPassive()) {
try {
String file = TorrentUtils.getTorrentFileName(torrent.getTorrent());
t_map.put("torrent_file", file.getBytes(Constants.BYTE_ENCODING));
} catch (Throwable e) {
Debug.printStackTrace(e);
}
}
t_map.put("hash", hash);
t_map.put("dateadded", new Long(date_added));
t_map.put("status", new Long(status));
list.add(t_map);
Map s_map = new HashMap();
t_map.put("stats", s_map);
s_map.put("completed", new Long(completed));
s_map.put("announces", new Long(announces));
s_map.put("scrapes", new Long(scrapes));
s_map.put("uploaded", new Long(uploaded));
s_map.put("downloaded", new Long(downloaded));
s_map.put("bytesin", new Long(bytes_in));
s_map.put("bytesout", new Long(bytes_out));
stats_entry.append(new String(name, Constants.DEFAULT_ENCODING));
stats_entry.append(",");
stats_entry.append(ByteFormatter.nicePrint(hash, true));
stats_entry.append(",");
stats_entry.append(status);
stats_entry.append(",");
stats_entry.append(seed_count);
stats_entry.append(",");
stats_entry.append(non_seed_count);
stats_entry.append(",");
stats_entry.append(completed);
stats_entry.append(",");
stats_entry.append(announces);
stats_entry.append(",");
stats_entry.append(scrapes);
stats_entry.append(",");
stats_entry.append(DisplayFormatters.formatByteCountToKiBEtc(uploaded));
stats_entry.append(",");
stats_entry.append(DisplayFormatters.formatByteCountToKiBEtc(downloaded));
stats_entry.append(",");
stats_entry.append(DisplayFormatters.formatByteCountToKiBEtcPerSec(torrent.getAverageUploaded()));
stats_entry.append(",");
stats_entry.append(DisplayFormatters.formatByteCountToKiBEtcPerSec(torrent.getAverageDownloaded()));
stats_entry.append(",");
stats_entry.append(DisplayFormatters.formatByteCountToKiBEtc(torrent.getTotalLeft()));
stats_entry.append(",");
stats_entry.append(DisplayFormatters.formatByteCountToKiBEtc(bytes_in));
stats_entry.append(",");
stats_entry.append(DisplayFormatters.formatByteCountToKiBEtc(bytes_out));
stats_entry.append(",");
stats_entry.append(DisplayFormatters.formatByteCountToKiBEtcPerSec(torrent.getAverageBytesIn()));
stats_entry.append(",");
stats_entry.append(DisplayFormatters.formatByteCountToKiBEtcPerSec(torrent.getAverageBytesOut()));
stats_entry.append("\r\n");
stats_entries.add(stats_entry);
} catch (TOTorrentException e) {
Debug.printStackTrace(e);
}
}
// now save any non-recovered stats for a while in case the torrent
// gets re-added in the near future
Iterator it = saved_stats.keySet().iterator();
long now = SystemTime.getCurrentTime();
while (it.hasNext()) {
HashWrapper hash = (HashWrapper) it.next();
if (added.contains(hash)) {
continue;
}
Map t_map = (Map) saved_stats.get(hash);
Long backup = (Long) t_map.get("backup_time");
if (backup == null) {
backup = new Long(now);
t_map.put("backup_time", backup);
}
if (now - backup.longValue() < BACKUP_RETENTION_PERIOD) {
list.add(t_map);
added.add(hash);
}
}
map.put("torrents", list);
try {
save_lock_mon.enter();
if (torrents.length == 0) {
if (config_exists) {
FileUtil.deleteResilientConfigFile("tracker.config");
config_exists = false;
}
} else {
config_exists = true;
FileUtil.writeResilientConfigFile("tracker.config", map);
}
if (COConfigurationManager.getBooleanParameter("Tracker Log Enable") && stats_entries.size() > 0) {
try {
String timeStamp = "[" + new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss").format(new Date()) + "] ";
PrintWriter pw = null;
File file_name = new File(log_dir.concat(File.separator).concat(LOG_FILE_NAME));
try {
pw = new PrintWriter(new FileWriter(file_name, true));
for (int i = 0; i < stats_entries.size(); i++) {
StringBuffer stats_entry = (StringBuffer) stats_entries.get(i);
String str = timeStamp + stats_entry.toString();
pw.print(str);
}
} catch (Throwable e) {
Debug.printStackTrace(e);
} finally {
if (pw != null) {
try {
pw.close();
} catch (Throwable e) {
}
}
}
} catch (Throwable e) {
Debug.printStackTrace(e);
}
}
} finally {
save_lock_mon.exit();
}
} catch (Throwable e) {
Debug.printStackTrace(e);
}
}
}
use of com.biglybt.core.torrent.TOTorrentException in project BiglyBT by BiglySoftware.
the class TorrentUtil method addSpeedLimitsMenu.
protected static void addSpeedLimitsMenu(DownloadManager[] dms, Menu menu) {
Core core = CoreFactory.getSingleton();
Shell menu_shell = menu.getShell();
final SpeedLimitHandler slh = SpeedLimitHandler.getSingleton(core);
boolean all_have_limit = true;
Set<String> common_profiles = new HashSet<>();
final List<byte[]> dm_hashes = new ArrayList<>();
for (int i = 0; i < dms.length; i++) {
DownloadManager dm = dms[i];
int maxul = dm.getStats().getUploadRateLimitBytesPerSecond();
int maxdl = dm.getStats().getDownloadRateLimitBytesPerSecond();
if (maxul == 0 && maxdl == 0) {
all_have_limit = false;
}
TOTorrent t = dm.getTorrent();
if (t == null) {
common_profiles.clear();
} else {
try {
byte[] hash = t.getHash();
dm_hashes.add(hash);
List<String> profs = slh.getProfilesForDownload(hash);
if (i == 0) {
common_profiles.addAll(profs);
} else {
common_profiles.retainAll(profs);
}
} catch (TOTorrentException e) {
Debug.out(e);
common_profiles.clear();
}
}
}
java.util.List<String> profiles = slh.getProfileNames();
// add to profile
final Menu add_to_prof_menu = new Menu(menu_shell, SWT.DROP_DOWN);
MenuItem add_to_prof_item = new MenuItem(menu, SWT.CASCADE);
add_to_prof_item.setMenu(add_to_prof_menu);
Messages.setLanguageText(add_to_prof_item, "MyTorrentsView.menu.sl_add_to_prof");
if (!all_have_limit) {
add_to_prof_item.setEnabled(false);
} else {
for (final String p : profiles) {
MenuItem addItem = new MenuItem(add_to_prof_menu, SWT.PUSH);
addItem.setText(p);
addItem.addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event arg0) {
slh.addDownloadsToProfile(p, dm_hashes);
MenuFactory.showText("MainWindow.menu.speed_limits.info.title", MessageText.getString("MainWindow.menu.speed_limits.info.prof", new String[] { p }), slh.getProfile(p));
}
});
}
}
// remove from profile
final Menu remove_from_prof_menu = new Menu(menu_shell, SWT.DROP_DOWN);
MenuItem remove_from_prof_item = new MenuItem(menu, SWT.CASCADE);
remove_from_prof_item.setMenu(remove_from_prof_menu);
Messages.setLanguageText(remove_from_prof_item, "MyTorrentsView.menu.sl_remove_from_prof");
if (common_profiles.isEmpty()) {
remove_from_prof_item.setEnabled(false);
} else {
for (final String p : common_profiles) {
MenuItem addItem = new MenuItem(remove_from_prof_menu, SWT.PUSH);
addItem.setText(p);
addItem.addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event arg0) {
slh.removeDownloadsFromProfile(p, dm_hashes);
MenuFactory.showText("MainWindow.menu.speed_limits.info.title", MessageText.getString("MainWindow.menu.speed_limits.info.prof", new String[] { p }), slh.getProfile(p));
}
});
}
}
}
use of com.biglybt.core.torrent.TOTorrentException 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;
}
Aggregations