use of com.biglybt.core.internat.LocaleUtilDecoder in project BiglyBT by BiglySoftware.
the class DiskManagerImpl method countDataFiles.
private static int countDataFiles(TOTorrent torrent, String torrent_save_dir, String torrent_save_file) {
try {
int res = 0;
LocaleUtilDecoder locale_decoder = LocaleTorrentUtil.getTorrentEncoding(torrent);
TOTorrentFile[] files = torrent.getFiles();
for (int i = 0; i < files.length; i++) {
byte[][] path_comps = files[i].getPathComponents();
String path_str = torrent_save_dir + File.separator + torrent_save_file + File.separator;
for (int j = 0; j < path_comps.length; j++) {
String comp = locale_decoder.decodeString(path_comps[j]);
comp = FileUtil.convertOSSpecificChars(comp, j != path_comps.length - 1);
path_str += (j == 0 ? "" : File.separator) + comp;
}
File file = new File(path_str).getCanonicalFile();
File linked_file = FMFileManagerFactory.getSingleton().getFileLink(torrent, i, file);
boolean skip = false;
if (linked_file != file) {
if (!linked_file.getCanonicalPath().startsWith(new File(torrent_save_dir).getCanonicalPath())) {
skip = true;
}
}
if (!skip && file.exists() && !file.isDirectory()) {
res++;
}
}
return (res);
} catch (Throwable e) {
Debug.printStackTrace(e);
return (-1);
}
}
use of com.biglybt.core.internat.LocaleUtilDecoder in project BiglyBT by BiglySoftware.
the class DiskManagerImpl method deleteDataFileContents.
private static void deleteDataFileContents(TOTorrent torrent, String torrent_save_dir, String torrent_save_file, boolean force_no_recycle) throws TOTorrentException, UnsupportedEncodingException, LocaleUtilEncodingException {
LocaleUtilDecoder locale_decoder = LocaleTorrentUtil.getTorrentEncoding(torrent);
TOTorrentFile[] files = torrent.getFiles();
String root_path = torrent_save_dir + File.separator + torrent_save_file + File.separator;
boolean delete_if_not_in_dir = COConfigurationManager.getBooleanParameter("File.delete.include_files_outside_save_dir");
for (int i = 0; i < files.length; i++) {
byte[][] path_comps = files[i].getPathComponents();
String path_str = root_path;
for (int j = 0; j < path_comps.length; j++) {
try {
String comp = locale_decoder.decodeString(path_comps[j]);
comp = FileUtil.convertOSSpecificChars(comp, j != path_comps.length - 1);
path_str += (j == 0 ? "" : File.separator) + comp;
} catch (UnsupportedEncodingException e) {
Debug.out("file - unsupported encoding!!!!");
}
}
File file = new File(path_str);
File linked_file = FMFileManagerFactory.getSingleton().getFileLink(torrent, i, file);
boolean delete;
if (linked_file == file) {
delete = true;
} else {
try {
if (delete_if_not_in_dir || linked_file.getCanonicalPath().startsWith(new File(root_path).getCanonicalPath())) {
file = linked_file;
delete = true;
} else {
delete = false;
}
} catch (Throwable e) {
Debug.printStackTrace(e);
delete = false;
}
}
if (delete && file.exists() && !file.isDirectory()) {
try {
FileUtil.deleteWithRecycle(file, force_no_recycle);
} catch (Exception e) {
Debug.out(e.toString());
}
}
}
TorrentUtils.recursiveEmptyDirDelete(new File(torrent_save_dir, torrent_save_file));
}
use of com.biglybt.core.internat.LocaleUtilDecoder in project BiglyBT by BiglySoftware.
the class TOTorrentFileImpl method getRelativePath.
@Override
public String getRelativePath() {
if (torrent == null) {
return "";
}
byte[][] pathComponentsUTF8 = getPathComponentsUTF8();
if (pathComponentsUTF8 != null) {
StringBuilder sRelativePathSB = null;
for (int j = 0; j < pathComponentsUTF8.length; j++) {
try {
String comp;
try {
comp = new String(pathComponentsUTF8[j], "utf8");
} catch (UnsupportedEncodingException e) {
System.out.println("file - unsupported encoding!!!!");
comp = "UnsupportedEncoding";
}
comp = FileUtil.convertOSSpecificChars(comp, j != pathComponentsUTF8.length - 1);
if (j == 0) {
if (pathComponentsUTF8.length == 1) {
return (comp);
} else {
sRelativePathSB = new StringBuilder(512);
}
} else {
sRelativePathSB.append(File.separator);
}
sRelativePathSB.append(comp);
} catch (Exception ex) {
Debug.out(ex);
}
}
return sRelativePathSB == null ? "" : sRelativePathSB.toString();
}
LocaleUtilDecoder decoder = null;
try {
decoder = LocaleTorrentUtil.getTorrentEncodingIfAvailable(torrent);
if (decoder == null) {
LocaleUtil localeUtil = LocaleUtil.getSingleton();
decoder = localeUtil.getSystemDecoder();
}
} catch (Exception e) {
// Do Nothing
}
if (decoder != null) {
StringBuilder sRelativePathSB = null;
byte[][] components = getPathComponents();
for (int j = 0; j < components.length; j++) {
try {
String comp;
try {
comp = decoder.decodeString(components[j]);
} catch (UnsupportedEncodingException e) {
System.out.println("file - unsupported encoding!!!!");
try {
comp = new String(components[j]);
} catch (Exception e2) {
comp = "UnsupportedEncoding";
}
}
comp = FileUtil.convertOSSpecificChars(comp, j != components.length - 1);
if (j == 0) {
if (components.length == 1) {
return (comp);
} else {
sRelativePathSB = new StringBuilder(512);
}
} else {
sRelativePathSB.append(File.separator);
}
sRelativePathSB.append(comp);
} catch (Exception ex) {
Debug.out(ex);
}
}
return sRelativePathSB == null ? "" : sRelativePathSB.toString();
} else {
return ("");
}
}
use of com.biglybt.core.internat.LocaleUtilDecoder in project BiglyBT by BiglySoftware.
the class MenuFactory method handleTorrentView.
private static void handleTorrentView() {
final Shell shell = Utils.findAnyShell();
try {
FileDialog dialog = new FileDialog(shell, SWT.SYSTEM_MODAL | SWT.OPEN);
dialog.setFilterExtensions(new String[] { "*.torrent", "*.tor", Constants.FILE_WILDCARD });
dialog.setFilterNames(new String[] { "*.torrent", "*.tor", Constants.FILE_WILDCARD });
dialog.setFilterPath(TorrentOpener.getFilterPathTorrent());
dialog.setText(MessageText.getString("torrent.fix.corrupt.browse"));
String str = dialog.open();
if (str != null) {
TorrentOpener.setFilterPathTorrent(str);
File file = new File(str);
StringBuilder content = new StringBuilder();
String NL = "\r\n";
try {
TOTorrent torrent = TOTorrentFactory.deserialiseFromBEncodedFile(file);
LocaleUtilDecoder locale_decoder = LocaleTorrentUtil.getTorrentEncoding(torrent);
content.append("Character Encoding:\t").append(locale_decoder.getName()).append(NL);
String display_name = locale_decoder.decodeString(torrent.getName());
content.append("Name:\t").append(display_name).append(NL);
byte[] hash = torrent.getHash();
content.append("Hash:\t").append(ByteFormatter.encodeString(hash)).append(NL);
content.append("Size:\t").append(DisplayFormatters.formatByteCountToKiBEtc(torrent.getSize())).append(", piece size=").append(DisplayFormatters.formatByteCountToKiBEtc(torrent.getPieceLength())).append(", piece count=").append(torrent.getPieces().length).append(NL);
if (torrent.getPrivate()) {
content.append("Private Torrent").append(NL);
}
URL announce_url = torrent.getAnnounceURL();
if (announce_url != null) {
content.append("Announce URL:\t").append(announce_url).append(NL);
}
TOTorrentAnnounceURLSet[] sets = torrent.getAnnounceURLGroup().getAnnounceURLSets();
if (sets.length > 0) {
content.append("Announce List").append(NL);
for (TOTorrentAnnounceURLSet set : sets) {
String x = "";
URL[] urls = set.getAnnounceURLs();
for (URL u : urls) {
x += (x.length() == 0 ? "" : ", ") + u;
}
content.append("\t").append(x).append(NL);
}
}
content.append("Magnet URI:\t").append(UrlUtils.getMagnetURI(display_name, PluginCoreUtils.wrap(torrent))).append(NL);
long c_date = torrent.getCreationDate();
if (c_date > 0) {
content.append("Created On:\t").append(DisplayFormatters.formatDate(c_date * 1000)).append(NL);
}
byte[] created_by = torrent.getCreatedBy();
if (created_by != null) {
content.append("Created By:\t").append(locale_decoder.decodeString(created_by)).append(NL);
}
byte[] comment = torrent.getComment();
if (comment != null) {
content.append("Comment:\t").append(locale_decoder.decodeString(comment)).append(NL);
}
TOTorrentFile[] files = torrent.getFiles();
content.append("Files:\t").append(files.length).append(" - simple=").append(torrent.isSimpleTorrent()).append(NL);
for (TOTorrentFile tf : files) {
byte[][] comps = tf.getPathComponents();
String f_name = "";
for (byte[] comp : comps) {
f_name += (f_name.length() == 0 ? "" : File.separator) + locale_decoder.decodeString(comp);
}
content.append("\t").append(f_name).append("\t\t").append(DisplayFormatters.formatByteCountToKiBEtc(tf.getLength())).append(NL);
}
} catch (Throwable e) {
content.append(Debug.getNestedExceptionMessage(e));
}
new TextViewerWindow(MessageText.getString("MainWindow.menu.quick_view") + ": " + file.getName(), null, content.toString(), false);
}
} catch (Throwable e) {
Debug.out(e);
}
}
use of com.biglybt.core.internat.LocaleUtilDecoder in project BiglyBT by BiglySoftware.
the class DownloadManagerImpl method readTorrent.
private void readTorrent(String torrent_save_dir, String torrent_save_file, // can be null for initial torrents
byte[] torrent_hash, // probably equivalend to (torrent_hash == null)????
boolean new_torrent, boolean for_seeding, boolean has_ever_been_started, int initial_state) {
try {
// default if things go wrong decoding it
display_name = torrentFileName;
internal_name = "";
torrent_comment = "";
torrent_created_by = "";
try {
// this is the first thing we do and most likely to go wrong - hence its
// existence is used below to indicate success or not
download_manager_state = DownloadManagerStateImpl.getDownloadState(this, torrentFileName, torrent_hash, initial_state == DownloadManager.STATE_STOPPED || initial_state == DownloadManager.STATE_QUEUED);
readParameters();
// establish any file links
DownloadManagerStateAttributeListener attr_listener = new DownloadManagerStateAttributeListener() {
private final ThreadLocal<Boolean> links_changing = new ThreadLocal<Boolean>() {
@Override
protected Boolean initialValue() {
return Boolean.FALSE;
}
};
@Override
public void attributeEventOccurred(DownloadManager dm, String attribute_name, int event_type) {
if (attribute_name.equals(DownloadManagerState.AT_FILE_LINKS2)) {
if (links_changing.get()) {
System.out.println("recursive!");
return;
}
links_changing.set(true);
try {
setFileLinks();
} finally {
links_changing.set(false);
}
} else if (attribute_name.equals(DownloadManagerState.AT_PARAMETERS)) {
readParameters();
} else if (attribute_name.equals(DownloadManagerState.AT_NETWORKS)) {
TRTrackerAnnouncer tc = tracker_client;
if (tc != null) {
tc.resetTrackerUrl(false);
}
}
}
};
download_manager_state.addListener(attr_listener, DownloadManagerState.AT_FILE_LINKS2, DownloadManagerStateAttributeListener.WRITTEN);
download_manager_state.addListener(attr_listener, DownloadManagerState.AT_PARAMETERS, DownloadManagerStateAttributeListener.WRITTEN);
download_manager_state.addListener(attr_listener, DownloadManagerState.AT_NETWORKS, DownloadManagerStateAttributeListener.WRITTEN);
torrent = download_manager_state.getTorrent();
setFileLinks();
if (!dl_identity_obtained) {
// flag set true below
dl_identity = torrent_hash == null ? torrent.getHash() : torrent_hash;
this.dl_identity_hashcode = new String(dl_identity).hashCode();
}
if (!Arrays.equals(dl_identity, torrent.getHash())) {
// prevent this download from being used
torrent = null;
// set up some kinda default else things don't work wel...
torrent_save_location = new File(torrent_save_dir, torrentFileName);
throw (new NoStackException("Download identity changed - please remove and re-add the download"));
}
// no longer needed if we saved it
read_torrent_state = null;
LocaleUtilDecoder locale_decoder = LocaleTorrentUtil.getTorrentEncoding(torrent);
// if its a simple torrent and an explicit save file wasn't supplied, use
// the torrent name itself
display_name = FileUtil.convertOSSpecificChars(TorrentUtils.getLocalisedName(torrent), false);
byte[] hash = torrent.getHash();
internal_name = ByteFormatter.nicePrint(hash, true);
// now we know if its a simple torrent or not we can make some choices about
// the save dir and file. On initial entry the save_dir will have the user-selected
// save location and the save_file will be null
File save_dir_file = new File(torrent_save_dir);
if (torrent_save_file == null) {
try {
if (save_dir_file.exists()) {
save_dir_file = save_dir_file.getCanonicalFile();
}
} catch (Throwable e) {
Debug.printStackTrace(e);
}
if (torrent.isSimpleTorrent()) {
if (save_dir_file.exists()) {
if (save_dir_file.isDirectory()) {
torrent_save_file = display_name;
} else {
torrent_save_dir = save_dir_file.getParent().toString();
torrent_save_file = save_dir_file.getName();
}
} else {
if (save_dir_file.getParent() == null) {
throw (new NoStackException("Data location '" + torrent_save_dir + "' is invalid"));
}
torrent_save_dir = save_dir_file.getParent().toString();
torrent_save_file = save_dir_file.getName();
}
} else {
if (save_dir_file.exists()) {
if (!save_dir_file.isDirectory()) {
throw (new NoStackException("'" + torrent_save_dir + "' is not a directory"));
}
if (save_dir_file.getName().equals(display_name)) {
torrent_save_dir = save_dir_file.getParent().toString();
}
}
torrent_save_file = display_name;
}
}
torrent_save_location = new File(torrent_save_dir, torrent_save_file);
if (!(new_torrent || Constants.isWindows)) {
if (has_ever_been_started) {
File linked_target = getSaveLocation();
if (!linked_target.exists()) {
throw (new NoStackException(MessageText.getString("DownloadManager.error.datamissing") + " " + Debug.secretFileName(linked_target.toString())));
}
}
}
// propagate properties from torrent to download
boolean low_noise = TorrentUtils.getFlag(torrent, TorrentUtils.TORRENT_FLAG_LOW_NOISE);
if (low_noise) {
download_manager_state.setFlag(DownloadManagerState.FLAG_LOW_NOISE, true);
}
boolean metadata_dl = TorrentUtils.getFlag(torrent, TorrentUtils.TORRENT_FLAG_METADATA_TORRENT);
if (metadata_dl) {
download_manager_state.setFlag(DownloadManagerState.FLAG_METADATA_DOWNLOAD, true);
}
if (new_torrent) {
download_manager_state.setLongParameter(DownloadManagerState.PARAM_DOWNLOAD_ADDED_TIME, SystemTime.getCurrentTime());
Map peer_cache = TorrentUtils.getPeerCache(torrent);
if (peer_cache != null) {
try {
download_manager_state.setTrackerResponseCache(peer_cache);
} catch (Throwable e) {
Debug.out(e);
download_manager_state.setTrackerResponseCache(new HashMap());
}
} else {
download_manager_state.setTrackerResponseCache(new HashMap());
}
if (for_seeding) {
DiskManagerFactory.setTorrentResumeDataNearlyComplete(download_manager_state);
// Prevent download being considered for on-completion moving - it's considered complete anyway.
download_manager_state.setFlag(DownloadManagerState.FLAG_MOVE_ON_COMPLETION_DONE, true);
} else {
download_manager_state.clearResumeData();
}
if (persistent && !for_seeding && !torrent.isSimpleTorrent()) {
String dnd_sf = dnd_subfolder;
if (dnd_sf != null) {
if (torrent.getFiles().length <= DownloadManagerStateFactory.MAX_FILES_FOR_INCOMPLETE_AND_DND_LINKAGE) {
if (download_manager_state.getAttribute(DownloadManagerState.AT_DND_SUBFOLDER) == null) {
download_manager_state.setAttribute(DownloadManagerState.AT_DND_SUBFOLDER, dnd_sf);
}
boolean use_prefix = COConfigurationManager.getBooleanParameter("Use Incomplete File Prefix");
if (use_prefix) {
if (download_manager_state.getAttribute(DownloadManagerState.AT_DND_PREFIX) == null) {
String prefix = Base32.encode(hash).substring(0, 12).toLowerCase(Locale.US) + "_";
download_manager_state.setAttribute(DownloadManagerState.AT_DND_PREFIX, prefix);
}
}
}
}
}
} else {
long add_time = download_manager_state.getLongParameter(DownloadManagerState.PARAM_DOWNLOAD_ADDED_TIME);
if (add_time == 0) {
try {
add_time = new File(torrentFileName).lastModified();
} catch (Throwable e) {
}
if (add_time == 0) {
add_time = SystemTime.getCurrentTime();
}
download_manager_state.setLongParameter(DownloadManagerState.PARAM_DOWNLOAD_ADDED_TIME, add_time);
}
}
// trackerUrl = torrent.getAnnounceURL().toString();
torrent_comment = StringInterner.intern(locale_decoder.decodeString(torrent.getComment()));
if (torrent_comment == null) {
torrent_comment = "";
}
torrent_created_by = locale_decoder.decodeString(torrent.getCreatedBy());
if (torrent_created_by == null) {
torrent_created_by = "";
}
if (download_manager_state.isResumeDataComplete() || for_seeding) {
// actually, can't think of a good reason not to restore the
// cache for seeds, after all if the tracker's down we still want
// to connect to peers to upload to
// download_manager_state.clearTrackerResponseCache();
stats.setDownloadCompletedBytes(getSize());
setAssumedComplete(true);
} else {
setAssumedComplete(false);
}
if (download_manager_state.getDisplayName() == null) {
String title = com.biglybt.core.torrent.PlatformTorrentUtils.getContentTitle(torrent);
if (title != null && title.length() > 0) {
download_manager_state.setDisplayName(title);
}
}
} catch (TOTorrentException e) {
// Debug.printStackTrace( e );
setFailed(TorrentUtils.exceptionToText(e));
} catch (UnsupportedEncodingException e) {
Debug.printStackTrace(e);
setFailed(MessageText.getString("DownloadManager.error.unsupportedencoding"));
} catch (NoStackException e) {
Debug.outNoStack(e.getMessage());
} catch (Throwable e) {
Debug.printStackTrace(e);
setFailed(e);
} finally {
dl_identity_obtained = true;
}
if (download_manager_state == null) {
read_torrent_state = new Object[] { torrent_save_dir, torrent_save_file, torrent_hash, Boolean.valueOf(new_torrent), Boolean.valueOf(for_seeding), Boolean.valueOf(has_ever_been_started), new Integer(initial_state) };
// torrent's stuffed - create a dummy "null object" to simplify use
// by other code
download_manager_state = DownloadManagerStateImpl.getDownloadState(this);
if (torrent_save_file == null) {
torrent_save_location = new File(torrent_save_dir);
} else {
torrent_save_location = new File(torrent_save_dir, torrent_save_file);
}
} else {
if (torrent_save_file == null) {
torrent_save_location = new File(torrent_save_dir);
}
if (torrent != null && !download_manager_state.hasAttribute(DownloadManagerState.AT_NETWORKS)) {
String[] networks = AENetworkClassifier.getNetworks(torrent, display_name);
download_manager_state.setNetworks(networks);
}
}
} finally {
if (torrent_save_location != null) {
boolean already_done = false;
String cache = download_manager_state.getAttribute(DownloadManagerState.AT_CANONICAL_SD_DMAP);
if (cache != null) {
String key = torrent_save_location.getAbsolutePath() + "\n";
if (cache.startsWith(key)) {
torrent_save_location = new File(cache.substring(key.length()));
already_done = true;
}
}
if (!already_done) {
String key = torrent_save_location.getAbsolutePath() + "\n";
try {
torrent_save_location = torrent_save_location.getCanonicalFile();
} catch (Throwable e) {
torrent_save_location = torrent_save_location.getAbsoluteFile();
}
download_manager_state.setAttribute(DownloadManagerState.AT_CANONICAL_SD_DMAP, key + torrent_save_location.getAbsolutePath());
}
// update cached stuff in case something changed
getSaveLocation();
}
// must be after torrent read, so that any listeners have a TOTorrent
// not that if things have failed above this method won't override a failed
// state with the initial one
controller.setInitialState(initial_state);
}
}
Aggregations