Search in sources :

Example 16 with TOTorrentFile

use of com.biglybt.core.torrent.TOTorrentFile in project BiglyBT by BiglySoftware.

the class ExternalSeedReaderGetRight method setupDownloaders.

private void setupDownloaders() {
    synchronized (this) {
        if (http_downloaders != null) {
            return;
        }
        TOTorrent to_torrent = ((TorrentImpl) getTorrent()).getTorrent();
        String ua = getUserAgent();
        if (to_torrent.isSimpleTorrent()) {
            http_downloaders = new ExternalSeedHTTPDownloader[] { linear_download ? new ExternalSeedHTTPDownloaderLinear(url, ua) : new ExternalSeedHTTPDownloaderRange(url, ua) };
            downloader_offsets = new long[] { 0 };
            downloader_lengths = new long[] { to_torrent.getSize() };
        } else {
            TOTorrentFile[] files = to_torrent.getFiles();
            http_downloaders = new ExternalSeedHTTPDownloader[files.length];
            downloader_offsets = new long[files.length];
            downloader_lengths = new long[files.length];
            long offset = 0;
            // encoding is a problem, assume ISO-8859-1
            String base_url = url.toString();
            if (base_url.endsWith("/")) {
                base_url = base_url.substring(0, base_url.length() - 1);
            }
            try {
                base_url += "/" + URLEncoder.encode(new String(to_torrent.getName(), "ISO-8859-1"), "ISO-8859-1").replaceAll("\\+", "%20");
                for (int i = 0; i < files.length; i++) {
                    TOTorrentFile file = files[i];
                    long length = file.getLength();
                    String file_url_str = base_url;
                    byte[][] bits = file.getPathComponents();
                    for (int j = 0; j < bits.length; j++) {
                        file_url_str += "/" + URLEncoder.encode(new String(bits[j], "ISO-8859-1"), "ISO-8859-1").replaceAll("\\+", "%20");
                    }
                    http_downloaders[i] = linear_download ? new ExternalSeedHTTPDownloaderLinear(new URL(file_url_str), ua) : new ExternalSeedHTTPDownloaderRange(new URL(file_url_str), ua);
                    downloader_offsets[i] = offset;
                    downloader_lengths[i] = length;
                    offset += length;
                }
            } catch (Throwable e) {
                Debug.out(e);
            }
        }
    }
}
Also used : ExternalSeedHTTPDownloaderRange(com.biglybt.plugin.extseed.util.ExternalSeedHTTPDownloaderRange) TOTorrentFile(com.biglybt.core.torrent.TOTorrentFile) TorrentImpl(com.biglybt.pifimpl.local.torrent.TorrentImpl) TOTorrent(com.biglybt.core.torrent.TOTorrent) ExternalSeedHTTPDownloaderLinear(com.biglybt.plugin.extseed.util.ExternalSeedHTTPDownloaderLinear) URL(java.net.URL)

Example 17 with TOTorrentFile

use of com.biglybt.core.torrent.TOTorrentFile 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);
    }
}
Also used : URL(java.net.URL) TOTorrentFile(com.biglybt.core.torrent.TOTorrentFile) MessageBoxShell(com.biglybt.ui.swt.shells.MessageBoxShell) LocaleUtilDecoder(com.biglybt.core.internat.LocaleUtilDecoder) TOTorrent(com.biglybt.core.torrent.TOTorrent) TOTorrentFile(com.biglybt.core.torrent.TOTorrentFile) File(java.io.File) TOTorrentAnnounceURLSet(com.biglybt.core.torrent.TOTorrentAnnounceURLSet)

Example 18 with TOTorrentFile

use of com.biglybt.core.torrent.TOTorrentFile in project BiglyBT by BiglySoftware.

the class TorrentUIUtilsV3 method getContentImage.

/**
 * Retrieves the thumbnail for the content, pulling it from the web if
 * it can
 *
 * @param datasource
 * @param l When the thumbnail is available, this listener is triggered
 * @return If the image is immediately available, the image will be returned
 *         as well as the trigger being fired.  If the image isn't available
 *         null will be returned and the listener will trigger when avail
 *
 * @since 4.0.0.5
 */
public static Image[] getContentImage(Object datasource, boolean big, final ContentImageLoadedListener l) {
    if (l == null) {
        return null;
    }
    TOTorrent torrent = DataSourceUtils.getTorrent(datasource);
    if (torrent == null) {
        l.contentImageLoaded(null, true);
        return null;
    }
    if (imageLoaderThumb == null) {
        imageLoaderThumb = new ImageLoader(null, null);
    }
    String thumbnailUrl = PlatformTorrentUtils.getContentThumbnailUrl(torrent);
    // System.out.println("thumburl= " + thumbnailUrl);
    if (thumbnailUrl != null && imageLoaderThumb.imageExists(thumbnailUrl)) {
        // System.out.println("return thumburl");
        Image image = imageLoaderThumb.getImage(thumbnailUrl);
        l.contentImageLoaded(image, true);
        return new Image[] { image };
    }
    String hash = null;
    try {
        hash = torrent.getHashWrapper().toBase32String();
    } catch (TOTorrentException e) {
    }
    if (hash == null) {
        l.contentImageLoaded(null, true);
        return null;
    }
    int thumbnailVersion = PlatformTorrentUtils.getContentVersion(torrent);
    // add torrent size here to differentiate meta-data downloads from actuals
    final String id = "Thumbnail." + hash + "." + torrent.getSize() + "." + thumbnailVersion;
    Image image = imageLoaderThumb.imageAdded(id) ? imageLoaderThumb.getImage(id) : null;
    // System.out.println("image = " + image);
    if (image != null && !image.isDisposed()) {
        l.contentImageLoaded(image, true);
        return new Image[] { image };
    }
    final byte[] imageBytes = PlatformTorrentUtils.getContentThumbnail(torrent);
    // System.out.println("imageBytes = " + imageBytes);
    if (imageBytes != null) {
        image = (Image) Utils.execSWTThreadWithObject("thumbcreator", new AERunnableObject() {

            @Override
            public Object runSupport() {
                try {
                    ByteArrayInputStream bis = new ByteArrayInputStream(imageBytes);
                    Image image = new Image(Display.getDefault(), bis);
                    return image;
                } catch (Throwable e) {
                    return (null);
                }
            }
        }, 500);
    }
    /**
     *		if ((image == null || image.isDisposed()) && thumbnailUrl != null) {
     *			//System.out.println("get image from " + thumbnailUrl);
     *			image = imageLoader.getUrlImage(thumbnailUrl,
     *					new ImageDownloaderListener() {
     *						public void imageDownloaded(Image image, boolean returnedImmediately) {
     *							l.contentImageLoaded(image, returnedImmediately);
     *							//System.out.println("got image from thumburl");
     *						}
     *					});
     *			//System.out.println("returning " + image + " (url loading)");
     *			return image == null ? null : new Image[] { image };
     *		}
     */
    if (image == null || image.isDisposed()) {
        // System.out.println("build image from files");
        DownloadManager dm = DataSourceUtils.getDM(datasource);
        /*
			 * Try to get an image from the OS
			 */
        String path = null;
        if (dm == null) {
            TOTorrentFile[] files = torrent.getFiles();
            if (files.length > 0) {
                path = files[0].getRelativePath();
            }
        } else {
            DiskManagerFileInfo primaryFile = dm.getDownloadState().getPrimaryFile();
            path = primaryFile == null ? null : primaryFile.getFile(true).getName();
        }
        if (path != null) {
            image = ImageRepository.getPathIcon(path, big, false);
            if (image != null && !torrent.isSimpleTorrent()) {
                Image[] images = new Image[] { image, ImageRepository.getPathIcon(new File(path).getParent(), false, false) };
                return images;
            }
        }
        if (image == null) {
            imageLoaderThumb.addImageNoDipose(id, ImageLoader.noImage);
        } else {
            imageLoaderThumb.addImageNoDipose(id, image);
        }
    } else {
        // System.out.println("has mystery image");
        imageLoaderThumb.addImage(id, image);
    }
    l.contentImageLoaded(image, true);
    return new Image[] { image };
}
Also used : DiskManagerFileInfo(com.biglybt.core.disk.DiskManagerFileInfo) Image(org.eclipse.swt.graphics.Image) DownloadManager(com.biglybt.core.download.DownloadManager) TOTorrentException(com.biglybt.core.torrent.TOTorrentException) TOTorrentFile(com.biglybt.core.torrent.TOTorrentFile) ByteArrayInputStream(java.io.ByteArrayInputStream) TOTorrent(com.biglybt.core.torrent.TOTorrent) ImageLoader(com.biglybt.ui.swt.imageloader.ImageLoader) TOTorrentFile(com.biglybt.core.torrent.TOTorrentFile) File(java.io.File)

Example 19 with TOTorrentFile

use of com.biglybt.core.torrent.TOTorrentFile in project BiglyBT by BiglySoftware.

the class FMFileImpl method reserveAccess.

private void reserveAccess(String reason) throws FMFileManagerException {
    if (clone) {
        return;
    }
    try {
        file_map_mon.enter();
        // System.out.println( "FMFile::reserveAccess:" + canonical_path + "("+ owner.getName() + ")" + " [" + (access_mode==FM_WRITE?"write":"read") + "]" + " - " + Debug.getCompressedStackTrace());
        List owners = (List) file_map.get(canonical_path);
        Object[] my_entry = null;
        if (owners == null) {
            Debug.out("reserveAccess fail");
            throw (new FMFileManagerException("File '" + canonical_path + "' has not been reserved (no entries), '" + owner.getName() + "'"));
        }
        for (Iterator it = owners.iterator(); it.hasNext(); ) {
            Object[] entry = (Object[]) it.next();
            String entry_name = ((FMFileOwner) entry[0]).getName();
            if (owner.getName().equals(entry_name)) {
                my_entry = entry;
            }
        }
        if (my_entry == null) {
            Debug.out("reserveAccess fail");
            throw (new FMFileManagerException("File '" + canonical_path + "' has not been reserved (not found), '" + owner.getName() + "'"));
        }
        my_entry[1] = Boolean.valueOf(access_mode == FM_WRITE);
        my_entry[2] = reason;
        int read_access = 0;
        int write_access = 0;
        int write_access_lax = 0;
        TOTorrentFile my_torrent_file = owner.getTorrentFile();
        StringBuilder users_sb = owners.size() == 1 ? null : new StringBuilder(128);
        for (Iterator it = owners.iterator(); it.hasNext(); ) {
            Object[] entry = (Object[]) it.next();
            FMFileOwner this_owner = (FMFileOwner) entry[0];
            if (((Boolean) entry[1]).booleanValue()) {
                write_access++;
                TOTorrentFile this_tf = this_owner.getTorrentFile();
                if (my_torrent_file != null && this_tf != null && my_torrent_file.getLength() == this_tf.getLength()) {
                    write_access_lax++;
                }
                if (users_sb != null) {
                    if (users_sb.length() > 0) {
                        users_sb.append(",");
                    }
                    users_sb.append(this_owner.getName());
                    users_sb.append(" [write]");
                }
            } else {
                read_access++;
                if (users_sb != null) {
                    if (users_sb.length() > 0) {
                        users_sb.append(",");
                    }
                    users_sb.append(this_owner.getName());
                    users_sb.append(" [read]");
                }
            }
        }
        if (write_access > 1 || (write_access == 1 && read_access > 0)) {
            if (!COConfigurationManager.getBooleanParameter("File.strict.locking")) {
                if (write_access_lax == write_access) {
                    return;
                }
            }
            Debug.out("reserveAccess fail");
            throw (new FMFileManagerException("File '" + canonical_path + "' is in use by '" + (users_sb == null ? "eh?" : users_sb.toString()) + "'"));
        }
    } finally {
        file_map_mon.exit();
    }
}
Also used : FMFileManagerException(com.biglybt.core.diskmanager.file.FMFileManagerException) TOTorrentFile(com.biglybt.core.torrent.TOTorrentFile) FMFileOwner(com.biglybt.core.diskmanager.file.FMFileOwner)

Example 20 with TOTorrentFile

use of com.biglybt.core.torrent.TOTorrentFile in project BiglyBT by BiglySoftware.

the class CacheFileManagerImpl method allocateCacheSpace.

/**
 * allocates space but does NOT add it to the cache list due to synchronization issues. Basically
 * the caller mustn't hold their monitor when calling allocate, as a flush may result in one or more
 * other files being flushed which results in their monitor being taken, and we've got an A->B and
 * B->A classic deadlock situation. However, we must keep the file's cache and our cache in step.
 * It is not acceptable to have an entry inserted into our records but not in the file's as this
 * then screws up the flush algorithm (which assumes that if it finds an entry in our list, a flush
 * of that file is guaranteed to release space). Therefore we add the cache entry in addCacheSpace
 * so that the caller can safely do this while synchronised firstly on its monitor and then we can
 * sync on our. Hence we only ever get A->B monitor grabs which won't deadlock
 * @param file
 * @param buffer
 * @param file_position
 * @param length
 * @return
 * @throws CacheFileManagerException
 */
protected CacheEntry allocateCacheSpace(int entry_type, CacheFileWithCache file, DirectByteBuffer buffer, long file_position, int length) throws CacheFileManagerException {
    boolean ok = false;
    boolean log = false;
    while (!ok) {
        // musn't invoke synchronised CacheFile methods while holding manager lock as this
        // can cause deadlocks (as CacheFile calls manager methods with locks)
        CacheEntry oldest_entry = null;
        try {
            this_mon.enter();
            if (length < cache_space_free || cache_space_free == cache_size) {
                ok = true;
            } else {
                oldest_entry = (CacheEntry) cache_entries.keySet().iterator().next();
            }
        } finally {
            this_mon.exit();
        }
        if (!ok) {
            log = true;
            long old_free = cache_space_free;
            CacheFileWithCache oldest_file = oldest_entry.getFile();
            try {
                oldest_file.flushCache(oldest_entry.getFilePosition(), true, cache_minimum_free_size);
            } catch (CacheFileManagerException e) {
                if (oldest_file != file) {
                    oldest_file.setPendingException(e);
                } else {
                    throw (e);
                }
            }
            long flushed = cache_space_free - old_free;
            if (Logger.isEnabled()) {
                TOTorrentFile tf = file.getTorrentFile();
                TOTorrent torrent = tf == null ? null : tf.getTorrent();
                Logger.log(new LogEvent(torrent, LOGID, "DiskCache: cache full, flushed " + flushed + " from " + oldest_file.getName()));
            }
            if (flushed == 0) {
                try {
                    this_mon.enter();
                    if (cache_entries.size() > 0 && (CacheEntry) cache_entries.keySet().iterator().next() == oldest_entry) {
                        throw (new CacheFileManagerException(null, "Cache inconsistent: 0 flushed"));
                    }
                } finally {
                    this_mon.exit();
                }
            }
        }
    }
    CacheEntry entry = new CacheEntry(entry_type, file, buffer, file_position, length);
    if (log && Logger.isEnabled()) {
        TOTorrentFile tf = file.getTorrentFile();
        TOTorrent torrent = tf == null ? null : tf.getTorrent();
        Logger.log(new LogEvent(torrent, LOGID, "DiskCache: cr=" + cache_bytes_read + ",cw=" + cache_bytes_written + ",fr=" + file_bytes_read + ",fw=" + file_bytes_written));
    }
    return (entry);
}
Also used : TOTorrentFile(com.biglybt.core.torrent.TOTorrentFile) LogEvent(com.biglybt.core.logging.LogEvent) TOTorrent(com.biglybt.core.torrent.TOTorrent)

Aggregations

TOTorrentFile (com.biglybt.core.torrent.TOTorrentFile)25 TOTorrent (com.biglybt.core.torrent.TOTorrent)11 File (java.io.File)9 DiskManagerFileInfo (com.biglybt.core.disk.DiskManagerFileInfo)5 DownloadManager (com.biglybt.core.download.DownloadManager)4 LocaleUtilDecoder (com.biglybt.core.internat.LocaleUtilDecoder)4 IOException (java.io.IOException)4 URL (java.net.URL)4 CacheFile (com.biglybt.core.diskmanager.cache.CacheFile)3 FMFileManagerException (com.biglybt.core.diskmanager.file.FMFileManagerException)3 DiskManager (com.biglybt.core.disk.DiskManager)2 DiskManagerFileInfoSet (com.biglybt.core.disk.DiskManagerFileInfoSet)2 DiskManagerPiece (com.biglybt.core.disk.DiskManagerPiece)2 FMFile (com.biglybt.core.diskmanager.file.FMFile)2 DownloadManagerException (com.biglybt.core.download.DownloadManagerException)2 DownloadManagerState (com.biglybt.core.download.DownloadManagerState)2 TOTorrentException (com.biglybt.core.torrent.TOTorrentException)2 PluginInterface (com.biglybt.pif.PluginInterface)2 Download (com.biglybt.pif.download.Download)2 RandomAccessFile (java.io.RandomAccessFile)2