use of com.biglybt.core.download.DownloadManagerState in project BiglyBT by BiglySoftware.
the class DiskManagerUtil method getFileInfoSkeleton.
public static DiskManagerFileInfoSet getFileInfoSkeleton(final DownloadManager download_manager, final DiskManagerListener listener) {
final TOTorrent torrent = download_manager.getTorrent();
if (torrent == null) {
return (new DiskManagerFileInfoSetImpl(new DiskManagerFileInfoImpl[0], null));
}
String tempRootDir = download_manager.getAbsoluteSaveLocation().getParent();
if (// in case we alraedy are at the root
tempRootDir == null)
tempRootDir = download_manager.getAbsoluteSaveLocation().getPath();
if (!torrent.isSimpleTorrent()) {
tempRootDir += File.separator + download_manager.getAbsoluteSaveLocation().getName();
}
tempRootDir += File.separator;
// prevent attempted state saves and associated nastyness during population of
// the file skeleton entries
final boolean[] loading = { true };
try {
final String root_dir = StringInterner.intern(tempRootDir);
try {
final LocaleUtilDecoder locale_decoder = LocaleTorrentUtil.getTorrentEncoding(torrent);
TOTorrentFile[] torrent_files = torrent.getFiles();
final FileSkeleton[] res = new FileSkeleton[torrent_files.length];
final String incomplete_suffix = download_manager.getDownloadState().getAttribute(DownloadManagerState.AT_INCOMP_FILE_SUFFIX);
final DiskManagerFileInfoSet fileSetSkeleton = new DiskManagerFileInfoSet() {
@Override
public DiskManagerFileInfo[] getFiles() {
return res;
}
@Override
public int nbFiles() {
return res.length;
}
@Override
public void setPriority(int[] toChange) {
if (toChange.length != res.length)
throw new IllegalArgumentException("array length mismatches the number of files");
for (int i = 0; i < res.length; i++) res[i].priority = toChange[i];
if (!loading[0]) {
DiskManagerImpl.storeFilePriorities(download_manager, res);
}
for (int i = 0; i < res.length; i++) if (toChange[i] != 0)
listener.filePriorityChanged(res[i]);
}
@Override
public void setSkipped(boolean[] toChange, boolean setSkipped) {
if (toChange.length != res.length)
throw new IllegalArgumentException("array length mismatches the number of files");
if (!setSkipped) {
String[] types = DiskManagerImpl.getStorageTypes(download_manager);
boolean[] toLinear = new boolean[toChange.length];
boolean[] toReorder = new boolean[toChange.length];
int num_linear = 0;
int num_reorder = 0;
for (int i = 0; i < toChange.length; i++) {
if (toChange[i]) {
int old_type = DiskManagerUtil.convertDMStorageTypeFromString(types[i]);
if (old_type == DiskManagerFileInfo.ST_COMPACT) {
toLinear[i] = true;
num_linear++;
} else if (old_type == DiskManagerFileInfo.ST_REORDER_COMPACT) {
toReorder[i] = true;
num_reorder++;
}
}
}
if (num_linear > 0) {
if (!Arrays.equals(toLinear, setStorageTypes(toLinear, DiskManagerFileInfo.ST_LINEAR))) {
return;
}
}
if (num_reorder > 0) {
if (!Arrays.equals(toReorder, setStorageTypes(toReorder, DiskManagerFileInfo.ST_REORDER))) {
return;
}
}
}
File[] to_link = new File[res.length];
for (int i = 0; i < res.length; i++) {
if (toChange[i]) {
to_link[i] = res[i].setSkippedInternal(setSkipped);
}
}
if (!loading[0]) {
DiskManagerImpl.storeFilePriorities(download_manager, res);
}
List<Integer> from_indexes = new ArrayList<>();
List<File> from_links = new ArrayList<>();
List<File> to_links = new ArrayList<>();
for (int i = 0; i < res.length; i++) {
if (to_link[i] != null) {
from_indexes.add(i);
from_links.add(res[i].getFile(false));
to_links.add(to_link[i]);
}
}
if (from_links.size() > 0) {
download_manager.getDownloadState().setFileLinks(from_indexes, from_links, to_links);
}
if (!setSkipped) {
doFileExistenceChecks(this, toChange, download_manager, true);
}
for (int i = 0; i < res.length; i++) {
if (toChange[i]) {
listener.filePriorityChanged(res[i]);
}
}
}
@Override
public boolean[] setStorageTypes(boolean[] toChange, int newStorageType) {
if (toChange.length != res.length)
throw new IllegalArgumentException("array length mismatches the number of files");
String[] types = DiskManagerImpl.getStorageTypes(download_manager);
boolean[] modified = new boolean[res.length];
boolean[] toSkip = new boolean[res.length];
int toSkipCount = 0;
DownloadManagerState dmState = download_manager.getDownloadState();
try {
dmState.suppressStateSave(true);
for (int i = 0; i < res.length; i++) {
if (!toChange[i])
continue;
final int idx = i;
int old_type = DiskManagerUtil.convertDMStorageTypeFromString(types[i]);
if (newStorageType == old_type) {
modified[i] = true;
continue;
}
try {
File target_file = res[i].getFile(true);
if (target_file.exists()) {
CacheFile cache_file = CacheFileManagerFactory.getSingleton().createFile(new CacheFileOwner() {
@Override
public String getCacheFileOwnerName() {
return (download_manager.getInternalName());
}
@Override
public TOTorrentFile getCacheFileTorrentFile() {
return (res[idx].getTorrentFile());
}
@Override
public File getCacheFileControlFileDir() {
return (download_manager.getDownloadState().getStateFile());
}
@Override
public int getCacheMode() {
return (CacheFileOwner.CACHE_MODE_NORMAL);
}
}, target_file, DiskManagerUtil.convertDMStorageTypeToCache(newStorageType));
// need this to trigger recovery for re-order files :(
cache_file.getLength();
cache_file.close();
}
toSkip[i] = (newStorageType == FileSkeleton.ST_COMPACT || newStorageType == FileSkeleton.ST_REORDER_COMPACT) && !res[i].isSkipped();
if (toSkip[i]) {
toSkipCount++;
}
modified[i] = true;
} catch (Throwable e) {
Debug.printStackTrace(e);
Logger.log(new LogAlert(download_manager, LogAlert.REPEATABLE, LogAlert.AT_ERROR, "Failed to change storage type for '" + res[i].getFile(true) + "': " + Debug.getNestedExceptionMessage(e)));
// download's not running - tag for recheck
RDResumeHandler.recheckFile(download_manager, res[i]);
}
types[i] = DiskManagerUtil.convertDMStorageTypeToString(newStorageType);
}
/*
* set storage type and skipped before we do piece clearing and file
* clearing checks as those checks work better when skipped/stype is set
* properly
*/
dmState.setListAttribute(DownloadManagerState.AT_FILE_STORE_TYPES, types);
if (toSkipCount > 0) {
setSkipped(toSkip, true);
}
for (int i = 0; i < res.length; i++) {
if (!toChange[i])
continue;
// download's not running, update resume data as necessary
int cleared = RDResumeHandler.storageTypeChanged(download_manager, res[i]);
if (cleared > 0) {
res[i].downloaded = res[i].downloaded - cleared * res[i].getTorrentFile().getTorrent().getPieceLength();
if (res[i].downloaded < 0)
res[i].downloaded = 0;
}
}
DiskManagerImpl.storeFileDownloaded(download_manager, res, true);
doFileExistenceChecks(this, toChange, download_manager, newStorageType == FileSkeleton.ST_LINEAR || newStorageType == FileSkeleton.ST_REORDER);
} finally {
dmState.suppressStateSave(false);
dmState.save();
}
return modified;
}
};
for (int i = 0; i < res.length; i++) {
final TOTorrentFile torrent_file = torrent_files[i];
final int file_index = i;
FileSkeleton info = new FileSkeleton() {
private volatile CacheFile read_cache_file;
// do not access this field directly, use lazyGetFile() instead
private WeakReference dataFile = new WeakReference(null);
@Override
public void setPriority(int b) {
priority = b;
DiskManagerImpl.storeFilePriorities(download_manager, res);
listener.filePriorityChanged(this);
}
@Override
public void setSkipped(boolean _skipped) {
if (!_skipped && getStorageType() == ST_COMPACT) {
if (!setStorageType(ST_LINEAR)) {
return;
}
}
if (!_skipped && getStorageType() == ST_REORDER_COMPACT) {
if (!setStorageType(ST_REORDER)) {
return;
}
}
File to_link = setSkippedInternal(_skipped);
DiskManagerImpl.storeFilePriorities(download_manager, res);
if (to_link != null) {
download_manager.getDownloadState().setFileLink(file_index, getFile(false), to_link);
}
if (!_skipped) {
boolean[] toCheck = new boolean[fileSetSkeleton.nbFiles()];
toCheck[file_index] = true;
doFileExistenceChecks(fileSetSkeleton, toCheck, download_manager, true);
}
listener.filePriorityChanged(this);
}
@Override
public int getAccessMode() {
return (READ);
}
@Override
public long getDownloaded() {
return (downloaded);
}
@Override
public long getLastModified() {
return (getFile(true).lastModified());
}
@Override
public void setDownloaded(long l) {
downloaded = l;
}
@Override
public String getExtension() {
String ext = lazyGetFile().getName();
if (incomplete_suffix != null && ext.endsWith(incomplete_suffix)) {
ext = ext.substring(0, ext.length() - incomplete_suffix.length());
}
int separator = ext.lastIndexOf(".");
if (separator == -1)
separator = 0;
return ext.substring(separator);
}
@Override
public int getFirstPieceNumber() {
return (torrent_file.getFirstPieceNumber());
}
@Override
public int getLastPieceNumber() {
return (torrent_file.getLastPieceNumber());
}
@Override
public long getLength() {
return (torrent_file.getLength());
}
@Override
public int getIndex() {
return (file_index);
}
@Override
public int getNbPieces() {
return (torrent_file.getNumberOfPieces());
}
@Override
public int getPriority() {
return (priority);
}
@Override
protected File setSkippedInternal(boolean _skipped) {
// returns the file to link to if linkage is required
skipped_internal = _skipped;
if (!download_manager.isDestroyed()) {
DownloadManagerState dm_state = download_manager.getDownloadState();
String dnd_sf = dm_state.getAttribute(DownloadManagerState.AT_DND_SUBFOLDER);
if (dnd_sf != null) {
File link = getLink();
File file = getFile(false);
if (_skipped) {
if (link == null || link.equals(file)) {
File parent = file.getParentFile();
if (parent != null) {
String prefix = dm_state.getAttribute(DownloadManagerState.AT_DND_PREFIX);
String file_name = file.getName();
if (prefix != null && !file_name.startsWith(prefix)) {
file_name = prefix + file_name;
}
File new_parent = new File(parent, dnd_sf);
File new_file = new File(new_parent, file_name);
if (!new_file.exists()) {
if (!new_parent.exists()) {
new_parent.mkdirs();
}
if (new_parent.canWrite()) {
boolean ok;
if (file.exists()) {
ok = FileUtil.renameFile(file, new_file);
} else {
ok = true;
}
if (ok) {
return (new_file);
}
}
}
}
}
} else {
if (link != null && !file.exists()) {
File parent = file.getParentFile();
if (parent != null && parent.canWrite()) {
File new_parent = parent.getName().equals(dnd_sf) ? parent : new File(parent, dnd_sf);
// use link name to handle incomplete file suffix if set
File new_file = new File(new_parent, link.getName());
if (new_file.equals(link)) {
boolean ok;
String incomp_ext = dm_state.getAttribute(DownloadManagerState.AT_INCOMP_FILE_SUFFIX);
String file_name = file.getName();
String prefix = dm_state.getAttribute(DownloadManagerState.AT_DND_PREFIX);
boolean prefix_removed = false;
if (prefix != null && file_name.startsWith(prefix)) {
file_name = file_name.substring(prefix.length());
prefix_removed = true;
}
if (incomp_ext != null && incomp_ext.length() > 0 && getDownloaded() != getLength()) {
if (prefix == null) {
prefix = "";
}
file = new File(file.getParentFile(), prefix + file_name + incomp_ext);
} else if (prefix_removed) {
file = new File(file.getParentFile(), file_name);
}
if (new_file.exists()) {
ok = FileUtil.renameFile(new_file, file);
} else {
ok = true;
}
if (ok) {
File[] files = new_parent.listFiles();
if (files != null && files.length == 0) {
new_parent.delete();
}
return (file);
}
}
}
}
}
}
}
return (null);
}
@Override
public boolean isSkipped() {
return (skipped_internal);
}
@Override
public DiskManager getDiskManager() {
return (null);
}
@Override
public DownloadManager getDownloadManager() {
return (download_manager);
}
@Override
public File getFile(boolean follow_link) {
if (follow_link) {
File link = getLink();
if (link != null) {
return (link);
}
}
return lazyGetFile();
}
private File lazyGetFile() {
File toReturn = (File) dataFile.get();
if (toReturn != null)
return toReturn;
TOTorrent tor = download_manager.getTorrent();
String path_str = root_dir;
File simpleFile = null;
if (tor == null || tor.isSimpleTorrent()) {
// rumour has it tor can sometimes be null
simpleFile = download_manager.getAbsoluteSaveLocation();
} else {
byte[][] path_comps = torrent_file.getPathComponents();
for (int j = 0; j < path_comps.length; j++) {
String comp;
try {
comp = locale_decoder.decodeString(path_comps[j]);
} catch (UnsupportedEncodingException e) {
Debug.printStackTrace(e);
comp = "undecodableFileName" + file_index;
}
comp = FileUtil.convertOSSpecificChars(comp, j != path_comps.length - 1);
path_str += (j == 0 ? "" : File.separator) + comp;
}
}
dataFile = new WeakReference(toReturn = simpleFile != null ? simpleFile : new File(path_str));
// System.out.println("new file:"+toReturn);
return toReturn;
}
@Override
public TOTorrentFile getTorrentFile() {
return (torrent_file);
}
@Override
public boolean setLink(File link_destination) {
/**
* If we a simple torrent, then we'll redirect the call to the download and move the
* data files that way - that'll keep everything in sync.
*/
if (download_manager.getTorrent().isSimpleTorrent()) {
try {
download_manager.moveDataFiles(link_destination.getParentFile(), link_destination.getName());
return true;
} catch (DownloadManagerException e) {
// What should we do with the error?
return false;
}
}
return setLinkAtomic(link_destination);
}
@Override
public boolean setLinkAtomic(File link_destination) {
return (setFileLink(download_manager, res, this, lazyGetFile(), link_destination, null));
}
@Override
public boolean setLinkAtomic(File link_destination, FileUtil.ProgressListener pl) {
return (setFileLink(download_manager, res, this, lazyGetFile(), link_destination, pl));
}
@Override
public File getLink() {
return (download_manager.getDownloadState().getFileLink(file_index, lazyGetFile()));
}
@Override
public boolean setStorageType(int type) {
boolean[] change = new boolean[res.length];
change[file_index] = true;
return fileSetSkeleton.setStorageTypes(change, type)[file_index];
}
@Override
public int getStorageType() {
return (DiskManagerUtil.convertDMStorageTypeFromString(DiskManagerImpl.getStorageType(download_manager, file_index)));
}
@Override
public void flushCache() {
}
@Override
public DirectByteBuffer read(long offset, int length) throws IOException {
CacheFile temp;
try {
cache_read_mon.enter();
if (read_cache_file == null) {
try {
int type = convertDMStorageTypeFromString(DiskManagerImpl.getStorageType(download_manager, file_index));
read_cache_file = CacheFileManagerFactory.getSingleton().createFile(new CacheFileOwner() {
@Override
public String getCacheFileOwnerName() {
return (download_manager.getInternalName());
}
@Override
public TOTorrentFile getCacheFileTorrentFile() {
return (torrent_file);
}
@Override
public File getCacheFileControlFileDir() {
return (download_manager.getDownloadState().getStateFile());
}
@Override
public int getCacheMode() {
return (CacheFileOwner.CACHE_MODE_NORMAL);
}
}, getFile(true), convertDMStorageTypeToCache(type));
} catch (Throwable e) {
Debug.printStackTrace(e);
throw (new IOException(e.getMessage()));
}
}
temp = read_cache_file;
} finally {
cache_read_mon.exit();
}
DirectByteBuffer buffer = DirectByteBufferPool.getBuffer(DirectByteBuffer.AL_DM_READ, length);
try {
temp.read(buffer, offset, CacheFile.CP_READ_CACHE);
} catch (Throwable e) {
buffer.returnToPool();
Debug.printStackTrace(e);
throw (new IOException(e.getMessage()));
}
return (buffer);
}
@Override
public int getReadBytesPerSecond() {
CacheFile temp = read_cache_file;
if (temp == null) {
return (0);
}
return (0);
}
@Override
public int getWriteBytesPerSecond() {
return (0);
}
@Override
public long getETA() {
return (-1);
}
@Override
public void close() {
CacheFile temp;
try {
cache_read_mon.enter();
temp = read_cache_file;
read_cache_file = null;
} finally {
cache_read_mon.exit();
}
if (temp != null) {
try {
temp.close();
} catch (Throwable e) {
Debug.printStackTrace(e);
}
}
}
@Override
public void addListener(DiskManagerFileInfoListener listener) {
if (getDownloaded() == getLength()) {
try {
listener.dataWritten(0, getLength());
listener.dataChecked(0, getLength());
} catch (Throwable e) {
Debug.printStackTrace(e);
}
}
}
@Override
public void removeListener(DiskManagerFileInfoListener listener) {
}
};
res[i] = info;
}
loadFilePriorities(download_manager, fileSetSkeleton);
loadFileDownloaded(download_manager, res);
return (fileSetSkeleton);
} finally {
loading[0] = false;
}
} catch (Throwable e) {
Debug.printStackTrace(e);
return (new DiskManagerFileInfoSetImpl(new DiskManagerFileInfoImpl[0], null));
}
}
use of com.biglybt.core.download.DownloadManagerState in project BiglyBT by BiglySoftware.
the class DiskManagerFileInfoSetImpl method setStorageTypes.
@Override
public boolean[] setStorageTypes(boolean[] toChange, int newStroageType) {
if (toChange.length != files.length)
throw new IllegalArgumentException("array length mismatches the number of files");
if (files.length == 0)
return new boolean[0];
String[] types = diskManager.getStorageTypes();
boolean[] modified = new boolean[files.length];
DownloadManagerState dm_state = diskManager.getDownloadState();
if (newStroageType == DiskManagerFileInfo.ST_COMPACT || newStroageType == DiskManagerFileInfo.ST_REORDER_COMPACT) {
Debug.out("Download must be stopped for linear -> compact conversion");
return modified;
}
try {
dm_state.suppressStateSave(true);
for (int i = 0; i < files.length; i++) {
if (!toChange[i])
continue;
int old_type = DiskManagerUtil.convertDMStorageTypeFromString(types[i]);
if (newStroageType == old_type) {
modified[i] = true;
continue;
}
DiskManagerFileInfoImpl file = files[i];
try {
file.getCacheFile().setStorageType(DiskManagerUtil.convertDMStorageTypeToCache(newStroageType));
modified[i] = true;
} catch (Throwable e) {
Debug.printStackTrace(e);
diskManager.setFailed(file, "Failed to change storage type for '" + file.getFile(true) + "': " + Debug.getNestedExceptionMessage(e));
break;
} finally {
types[i] = DiskManagerUtil.convertCacheStorageTypeToString(file.getCacheFile().getStorageType());
}
}
dm_state.setListAttribute(DownloadManagerState.AT_FILE_STORE_TYPES, types);
DiskManagerUtil.doFileExistenceChecks(this, toChange, dm_state.getDownloadManager(), true);
} finally {
dm_state.suppressStateSave(false);
dm_state.save();
}
return modified;
}
use of com.biglybt.core.download.DownloadManagerState in project BiglyBT by BiglySoftware.
the class DiskManagerImpl method filesExist.
protected boolean filesExist(String root_dir) {
if (!torrent.isSimpleTorrent()) {
root_dir += File.separator + download_manager.getAbsoluteSaveLocation().getName();
}
if (!root_dir.endsWith(File.separator)) {
root_dir += File.separator;
}
// System.out.println( "root dir = " + root_dir_file );
DMPieceMapperFile[] pm_files = piece_mapper.getFiles();
String[] storage_types = getStorageTypes();
DownloadManagerState state = download_manager.getDownloadState();
for (int i = 0; i < pm_files.length; i++) {
DMPieceMapperFile pm_info = pm_files[i];
File relative_file = pm_info.getDataFile();
long target_length = pm_info.getLength();
// use the cache file to ascertain length in case the caching/writing algorithm
// fiddles with the real length
// Unfortunately we may be called here BEFORE the disk manager has been
// started and hence BEFORE the file info has been setup...
// Maybe one day we could allocate the file info earlier. However, if we do
// this then we'll need to handle the "already moved" stuff too...
DiskManagerFileInfoImpl file_info = pm_info.getFileInfo();
boolean close_it = false;
try {
if (file_info == null) {
int storage_type = DiskManagerUtil.convertDMStorageTypeFromString(storage_types[i]);
file_info = createFileInfo(state, pm_info, i, root_dir, relative_file, storage_type);
close_it = true;
}
try {
CacheFile cache_file = file_info.getCacheFile();
File data_file = file_info.getFile(true);
if (!cache_file.exists()) {
// look for something sensible to report
File current = data_file;
while (!current.exists()) {
File parent = current.getParentFile();
if (parent == null) {
break;
} else if (!parent.exists()) {
current = parent;
} else {
if (parent.isDirectory()) {
errorMessage = current.toString() + " not found.";
} else {
errorMessage = parent.toString() + " is not a directory.";
}
return (false);
}
}
errorMessage = data_file.toString() + " not found.";
return false;
}
// only test for too big as if incremental creation selected
// then too small is OK
long existing_length = file_info.getCacheFile().getLength();
if (existing_length > target_length) {
if (COConfigurationManager.getBooleanParameter("File.truncate.if.too.large")) {
file_info.setAccessMode(DiskManagerFileInfo.WRITE);
file_info.getCacheFile().setLength(target_length);
Debug.out("Existing data file length too large [" + existing_length + ">" + target_length + "]: " + data_file.getAbsolutePath() + ", truncating");
} else {
errorMessage = "Existing data file length too large [" + existing_length + ">" + target_length + "]: " + data_file.getAbsolutePath();
return false;
}
}
} finally {
if (close_it) {
file_info.getCacheFile().close();
}
}
} catch (Throwable e) {
errorMessage = Debug.getNestedExceptionMessage(e) + " (filesExist:" + relative_file.toString() + ")";
return (false);
}
}
return true;
}
use of com.biglybt.core.download.DownloadManagerState in project BiglyBT by BiglySoftware.
the class DiskManagerImpl method getStorageTypes.
// Used by DownloadManagerImpl too.
public static String[] getStorageTypes(DownloadManager download_manager) {
DownloadManagerState state = download_manager.getDownloadState();
String[] types = state.getListAttribute(DownloadManagerState.AT_FILE_STORE_TYPES);
if (types == null || types.length == 0) {
TOTorrentFile[] files = download_manager.getTorrent().getFiles();
types = new String[download_manager.getTorrent().getFiles().length];
if (reorder_storage_mode) {
int existing = state.getIntAttribute(DownloadManagerState.AT_REORDER_MIN_MB);
if (existing < 0) {
existing = reorder_storage_mode_min_mb;
state.setIntAttribute(DownloadManagerState.AT_REORDER_MIN_MB, existing);
}
for (int i = 0; i < types.length; i++) {
if (files[i].getLength() / (1024 * 1024) >= existing) {
types[i] = "R";
} else {
types[i] = "L";
}
}
} else {
for (int i = 0; i < types.length; i++) {
types[i] = "L";
}
}
state.setListAttribute(DownloadManagerState.AT_FILE_STORE_TYPES, types);
}
return (types);
}
use of com.biglybt.core.download.DownloadManagerState in project BiglyBT by BiglySoftware.
the class DiskManagerImpl method setPieceDone.
/**
* Called when status has CHANGED and should only be called by DiskManagerPieceImpl
*/
@Override
public void setPieceDone(DiskManagerPieceImpl dmPiece, boolean done) {
int piece_number = dmPiece.getPieceNumber();
int piece_length = dmPiece.getLength();
try {
file_piece_mon.enter();
if (dmPiece.isDone() != done) {
dmPiece.setDoneSupport(done);
if (done)
remaining -= piece_length;
else
remaining += piece_length;
DMPieceList piece_list = getPieceList(piece_number);
for (int i = 0; i < piece_list.size(); i++) {
DMPieceMapEntry piece_map_entry = piece_list.get(i);
DiskManagerFileInfoImpl this_file = piece_map_entry.getFile();
long file_length = this_file.getLength();
long file_done = this_file.getDownloaded();
long file_done_before = file_done;
if (done)
file_done += piece_map_entry.getLength();
else
file_done -= piece_map_entry.getLength();
if (file_done < 0) {
Debug.out("piece map entry length negative");
file_done = 0;
} else if (file_done > file_length) {
Debug.out("piece map entry length too large");
file_done = file_length;
}
if (this_file.isSkipped()) {
skipped_but_downloaded += (file_done - file_done_before);
}
this_file.setDownloaded(file_done);
if (file_done == file_length) {
try {
DownloadManagerState state = download_manager.getDownloadState();
try {
String suffix = state.getAttribute(DownloadManagerState.AT_INCOMP_FILE_SUFFIX);
if (suffix != null && suffix.length() > 0) {
String prefix = state.getAttribute(DownloadManagerState.AT_DND_PREFIX);
if (prefix == null) {
prefix = "";
}
File base_file = this_file.getFile(false);
int file_index = this_file.getIndex();
File link = state.getFileLink(file_index, base_file);
if (link != null) {
String name = link.getName();
if (name.endsWith(suffix) && name.length() > suffix.length()) {
String new_name = name.substring(0, name.length() - suffix.length());
if (!this_file.isSkipped()) {
if (prefix.length() > 0 && new_name.startsWith(prefix)) {
new_name = new_name.substring(prefix.length());
}
}
File new_file = new File(link.getParentFile(), new_name);
if (!new_file.exists()) {
this_file.renameFile(new_name);
if (base_file.equals(new_file)) {
state.setFileLink(file_index, base_file, null);
} else {
state.setFileLink(file_index, base_file, new_file);
}
}
}
} else {
if (this_file.getTorrentFile().getTorrent().isSimpleTorrent()) {
File save_location = download_manager.getSaveLocation();
String name = save_location.getName();
if (name.endsWith(suffix) && name.length() > suffix.length()) {
String new_name = name.substring(0, name.length() - suffix.length());
if (!this_file.isSkipped()) {
if (prefix.length() > 0 && new_name.startsWith(prefix)) {
new_name = new_name.substring(prefix.length());
}
}
File new_file = new File(save_location.getParentFile(), new_name);
if (!new_file.exists()) {
this_file.renameFile(new_name);
if (save_location.equals(new_file)) {
state.setFileLink(0, save_location, null);
} else {
state.setFileLink(0, save_location, new_file);
}
}
}
}
}
}
} finally {
if (this_file.getAccessMode() == DiskManagerFileInfo.WRITE) {
this_file.setAccessMode(DiskManagerFileInfo.READ);
}
if (getState() == READY) {
state.setLongParameter(DownloadManagerState.PARAM_DOWNLOAD_FILE_COMPLETED_TIME, SystemTime.getCurrentTime());
}
}
} catch (Throwable e) {
setFailed("Disk access error - " + Debug.getNestedExceptionMessage(e));
Debug.printStackTrace(e);
}
// note - we don't set the access mode to write if incomplete as we may
// be rechecking a file and during this process the "file_done" amount
// will not be file_length until the end. If the file is read-only then
// changing to write will cause trouble!
}
}
if (getState() == READY) {
// don't start firing these until we're ready otherwise we send notifications
// for complete pieces during initialisation
listeners.dispatch(LDT_PIECE_DONE_CHANGED, dmPiece);
}
}
} finally {
file_piece_mon.exit();
}
}
Aggregations