Search in sources :

Example 11 with TOTorrent

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

the class GlobalManagerImpl method exportDownloadStateToMapSupport.

private Map exportDownloadStateToMapSupport(DownloadManager dm, boolean internal_export) {
    DownloadManagerStats dm_stats = dm.getStats();
    Map<String, Object> dmMap = new HashMap<>();
    TOTorrent torrent = dm.getTorrent();
    if (torrent != null) {
        try {
            dmMap.put("torrent_hash", torrent.getHash());
        } catch (TOTorrentException e) {
            Debug.printStackTrace(e);
        }
    }
    File save_loc = dm.getAbsoluteSaveLocation();
    dmMap.put("persistent", new Long(dm.isPersistent() ? 1 : 0));
    dmMap.put("torrent", dm.getTorrentFileName());
    dmMap.put("save_dir", save_loc.getParent());
    dmMap.put("save_file", save_loc.getName());
    dmMap.put("maxdl", new Long(dm_stats.getDownloadRateLimitBytesPerSecond()));
    dmMap.put("maxul", new Long(dm_stats.getUploadRateLimitBytesPerSecond()));
    int state = dm.getState();
    if (state == DownloadManager.STATE_ERROR) {
        // torrents in error state always come back stopped
        state = DownloadManager.STATE_STOPPED;
    } else if (dm.getAssumedComplete() && !dm.isForceStart() && state != DownloadManager.STATE_STOPPED) {
        state = DownloadManager.STATE_QUEUED;
    } else if (state != DownloadManager.STATE_STOPPED && state != DownloadManager.STATE_QUEUED && state != DownloadManager.STATE_WAITING) {
        state = DownloadManager.STATE_WAITING;
    }
    dmMap.put("state", new Long(state));
    if (internal_export) {
        dmMap.put("position", new Long(dm.getPosition()));
    }
    dmMap.put("downloaded", new Long(dm_stats.getTotalDataBytesReceived()));
    dmMap.put("uploaded", new Long(dm_stats.getTotalDataBytesSent()));
    dmMap.put("completedbytes", new Long(dm_stats.getDownloadCompletedBytes()));
    dmMap.put("discarded", new Long(dm_stats.getDiscarded()));
    dmMap.put("hashfailbytes", new Long(dm_stats.getHashFailBytes()));
    dmMap.put("forceStart", new Long(dm.isForceStart() && (dm.getState() != DownloadManager.STATE_CHECKING) ? 1 : 0));
    dmMap.put("secondsDownloading", new Long(dm_stats.getSecondsDownloading()));
    dmMap.put("secondsOnlySeeding", new Long(dm_stats.getSecondsOnlySeeding()));
    // although this has been migrated, keep storing it to allow regression for a while
    dmMap.put("uploads", new Long(dm.getMaxUploads()));
    dmMap.put("creationTime", new Long(dm.getCreationTime()));
    // save file priorities
    dm.saveDownload();
    List file_priorities = (List) dm.getUserData("file_priorities");
    if (file_priorities != null) {
        int count = file_priorities.size();
        Map<String, String> map_file_priorities = new HashMap<>();
        Long priority = (Long) file_priorities.get(0);
        int posStart = 0;
        int posEnd = 0;
        while (posStart < count) {
            priority = (Long) file_priorities.get(posStart);
            while (posEnd + 1 < count && (Long) file_priorities.get(posEnd + 1) == priority) {
                posEnd++;
            }
            String key = priority.toString();
            String val = map_file_priorities.get(key);
            if (val == null) {
                val = "" + posStart;
            } else {
                val += "," + posStart;
            }
            if (posStart != posEnd) {
                val += "-" + posEnd;
            }
            map_file_priorities.put(key, val);
            posStart = posEnd + 1;
        }
        // dmMap.put( "file_priorities" , file_priorities );
        dmMap.put("file_priorities_c", map_file_priorities);
    }
    dmMap.put("allocated", new Long(dm.isDataAlreadyAllocated() ? 1 : 0));
    return (dmMap);
}
Also used : TOTorrentException(com.biglybt.core.torrent.TOTorrentException) TOTorrent(com.biglybt.core.torrent.TOTorrent) File(java.io.File)

Example 12 with TOTorrent

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

the class TorrentFolderWatcher method importAddedFiles.

void importAddedFiles() {
    Core core = CoreFactory.getSingleton();
    try {
        this_mon.enter();
        if (!running) {
            return;
        }
        GlobalManager global_manager = _global_manager;
        if (global_manager == null || !core.isStarted()) {
            return;
        }
        com.biglybt.pif.download.DownloadManager plugin_dm = core.getPluginManager().getDefaultPluginInterface().getDownloadManager();
        boolean save_torrents_default = COConfigurationManager.getBooleanParameter("Save Torrent Files");
        String torrent_save_path = COConfigurationManager.getStringParameter("General_sDefaultTorrent_Directory");
        int start_state = COConfigurationManager.getBooleanParameter("Start Watched Torrents Stopped") ? DownloadManager.STATE_STOPPED : DownloadManager.STATE_QUEUED;
        int num_folders = COConfigurationManager.getIntParameter("Watch Torrent Folder Path Count", 1);
        List<File> folders = new ArrayList<>();
        List<String> tags = new ArrayList<>();
        for (int i = 0; i < num_folders; i++) {
            String folder_path = COConfigurationManager.getStringParameter("Watch Torrent Folder Path" + (i == 0 ? "" : (" " + i)));
            File folder = null;
            if (folder_path != null && folder_path.length() > 0) {
                folder = new File(folder_path);
                if (!folder.isDirectory()) {
                    if (!folder.exists()) {
                        FileUtil.mkdirs(folder);
                    }
                    if (!folder.isDirectory()) {
                        if (Logger.isEnabled())
                            Logger.log(new LogEvent(LOGID, LogEvent.LT_ERROR, "[Watch Torrent Folder Path] " + "does not exist or " + "is not a dir"));
                        folder = null;
                    }
                }
            }
            if (folder != null) {
                folders.add(folder);
                String tag = COConfigurationManager.getStringParameter("Watch Torrent Folder Tag" + (i == 0 ? "" : (" " + i)), null);
                if (tag != null && tag.trim().length() == 0) {
                    tag = null;
                }
                tags.add(tag);
            }
        }
        if (folders.isEmpty()) {
            if (Logger.isEnabled())
                Logger.log(new LogEvent(LOGID, LogEvent.LT_ERROR, "[Watch Torrent Folder Path] not configured"));
            return;
        }
        String data_save_path = COConfigurationManager.getStringParameter("Default save path");
        File f = null;
        if (data_save_path != null && data_save_path.length() > 0) {
            f = new File(data_save_path);
            // Path is not an existing directory.
            if (!f.isDirectory()) {
                if (!f.exists()) {
                    FileUtil.mkdirs(f);
                }
                // If path is still not a directory, abort.
                if (!f.isDirectory()) {
                    if (Logger.isEnabled()) {
                        Logger.log(new LogEvent(LOGID, LogEvent.LT_ERROR, "[Default save path] does not exist or is not a dir"));
                    }
                    Logger.log(new LogAlert(LogAlert.UNREPEATABLE, LogAlert.AT_ERROR, "[Default save path] does not exist or is not a dir"));
                    return;
                }
            }
        }
        // If we get here, and this is true, then data_save_path isn't valid.
        if (f == null) {
            if (Logger.isEnabled()) {
                Logger.log(new LogEvent(LOGID, LogEvent.LT_ERROR, "[Default save path] needs to be set for auto-.torrent-import to work"));
            }
            Logger.log(new LogAlert(LogAlert.UNREPEATABLE, LogAlert.AT_ERROR, "[Default save path] needs to be set for auto-.torrent-import to work"));
        }
        for (int i = 0; i < to_delete.size(); i++) {
            TOTorrent torrent = (TOTorrent) to_delete.get(i);
            try {
                TorrentUtils.delete(torrent);
            } catch (Throwable e) {
                Debug.printStackTrace(e);
            }
        }
        to_delete.clear();
        for (int folder_index = 0; folder_index < folders.size(); folder_index++) {
            File folder = folders.get(folder_index);
            final String tag_name = tags.get(folder_index);
            // if we are saving torrents to the same location as we import them from
            // then we can't assume that its safe to delete the torrent after import!
            boolean save_torrents = save_torrents_default;
            if (torrent_save_path.length() == 0 || new File(torrent_save_path).getAbsolutePath().equals(folder.getAbsolutePath()) || !new File(torrent_save_path).isDirectory()) {
                save_torrents = false;
            }
            String[] currentFileList = folder.list(filename_filter);
            if (currentFileList == null) {
                Logger.log(new LogEvent(LOGID, LogEvent.LT_ERROR, "There was a problem trying to get a listing of torrents from " + folder));
            } else {
                for (int i = 0; i < currentFileList.length; i++) {
                    if (!running) {
                        return;
                    }
                    File file = new File(folder, currentFileList[i]);
                    if (file.getName().toLowerCase(Locale.US).endsWith(".magnet")) {
                        handleMagnet(file);
                    } else {
                        try {
                            TOTorrent torrent = TorrentUtils.readFromFile(file, false);
                            if (global_manager.getDownloadManager(torrent) != null) {
                                if (Logger.isEnabled())
                                    Logger.log(new LogEvent(LOGID, file.getAbsolutePath() + " is already being downloaded"));
                            // we can't touch the torrent file as it is (probably)
                            // being used for the download
                            } else if (plugin_dm.lookupDownloadStub(torrent.getHash()) != null) {
                                if (Logger.isEnabled())
                                    Logger.log(new LogEvent(LOGID, file.getAbsolutePath() + " is an archived download"));
                                if (!save_torrents) {
                                    File imported = new File(folder, file.getName() + ".imported");
                                    TorrentUtils.move(file, imported);
                                } else {
                                    to_delete.add(torrent);
                                }
                            } else {
                                final DownloadManagerInitialisationAdapter dmia = new DownloadManagerInitialisationAdapter() {

                                    @Override
                                    public int getActions() {
                                        return (ACT_ASSIGNS_TAGS);
                                    }

                                    @Override
                                    public void initialised(DownloadManager dm, boolean for_seeding) {
                                        if (tag_name != null) {
                                            TagManager tm = TagManagerFactory.getTagManager();
                                            TagType tt = tm.getTagType(TagType.TT_DOWNLOAD_MANUAL);
                                            Tag tag = tt.getTag(tag_name, true);
                                            try {
                                                if (tag == null) {
                                                    tag = tt.createTag(tag_name, true);
                                                }
                                                tag.addTaggable(dm);
                                            } catch (Throwable e) {
                                                Debug.out(e);
                                            }
                                        }
                                    }
                                };
                                byte[] hash = null;
                                try {
                                    hash = torrent.getHash();
                                } catch (Exception e) {
                                }
                                if (!save_torrents) {
                                    File imported = new File(folder, file.getName() + ".imported");
                                    TorrentUtils.move(file, imported);
                                    global_manager.addDownloadManager(imported.getAbsolutePath(), hash, data_save_path, start_state, true, false, dmia);
                                } else {
                                    global_manager.addDownloadManager(file.getAbsolutePath(), hash, data_save_path, start_state, true, false, dmia);
                                    // add torrent for deletion, since there will be a
                                    // saved copy elsewhere
                                    to_delete.add(torrent);
                                }
                                if (Logger.isEnabled())
                                    Logger.log(new LogEvent(LOGID, "Auto-imported " + file.getAbsolutePath()));
                            }
                        } catch (Throwable e) {
                            Debug.out("Failed to auto-import torrent file '" + file.getAbsolutePath() + "' - " + Debug.getNestedExceptionMessage(e));
                            Debug.printStackTrace(e);
                        }
                    }
                }
            }
        }
    } finally {
        this_mon.exit();
    }
}
Also used : LogEvent(com.biglybt.core.logging.LogEvent) ArrayList(java.util.ArrayList) DownloadManagerInitialisationAdapter(com.biglybt.core.download.DownloadManagerInitialisationAdapter) DownloadManager(com.biglybt.core.download.DownloadManager) LogAlert(com.biglybt.core.logging.LogAlert) TagType(com.biglybt.core.tag.TagType) TagManager(com.biglybt.core.tag.TagManager) GlobalManager(com.biglybt.core.global.GlobalManager) TOTorrent(com.biglybt.core.torrent.TOTorrent) Tag(com.biglybt.core.tag.Tag) File(java.io.File) Core(com.biglybt.core.Core)

Example 13 with TOTorrent

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

the class DownloadManagerStatsImpl method getHashFailCount.

@Override
public long getHashFailCount() {
    TOTorrent t = download_manager.getTorrent();
    if (t == null) {
        return (0);
    }
    long total = getHashFailBytes();
    long res = total / t.getPieceLength();
    if (res == 0 && total > 0) {
        res = 1;
    }
    return (res);
}
Also used : TOTorrent(com.biglybt.core.torrent.TOTorrent)

Example 14 with TOTorrent

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

the class GlobalManagerFileMerger method syncFileSets.

void syncFileSets() {
    List<DownloadManager> dms = gm.getDownloadManagers();
    synchronized (dm_map) {
        boolean changed = false;
        Set<HashWrapper> existing_dm_hashes = new HashSet<>(dm_map.keySet());
        if (enabled) {
            for (DownloadManager dm : dms) {
                /* 
					 * not sure why we were ignoring shares, one might share a local file in order to help
					 * out a 'normal' download
					 * 
					if ( !dm.isPersistent()){

						continue;
					}
					*/
                DownloadManagerState state = dm.getDownloadState();
                if (state.getFlag(DownloadManagerState.FLAG_LOW_NOISE) || state.getFlag(DownloadManagerState.FLAG_METADATA_DOWNLOAD)) {
                    continue;
                }
                if (enabled_extended || !dm.isDownloadComplete(false)) {
                    TOTorrent torrent = dm.getTorrent();
                    if (torrent != null) {
                        try {
                            HashWrapper hw = torrent.getHashWrapper();
                            if (dm_map.containsKey(hw)) {
                                existing_dm_hashes.remove(hw);
                            } else {
                                dm_map.put(hw, dm);
                                changed = true;
                            }
                        } catch (Throwable e) {
                        }
                    }
                }
            }
        }
        if (existing_dm_hashes.size() > 0) {
            changed = true;
            for (HashWrapper hw : existing_dm_hashes) {
                dm_map.remove(hw);
            }
        }
        if (changed) {
            List<Set<DiskManagerFileInfo>> interesting = new LinkedList<>();
            Map<Long, Set<DiskManagerFileInfo>> size_map = new HashMap<>();
            for (DownloadManager dm : dm_map.values()) {
                TOTorrent torrent = dm.getTorrent();
                if (torrent == null) {
                    continue;
                }
                DiskManagerFileInfo[] files = dm.getDiskManagerFileInfoSet().getFiles();
                for (DiskManagerFileInfo file : files) {
                    if (file.getNbPieces() < MIN_PIECES) {
                        continue;
                    }
                    long len = file.getLength();
                    Set<DiskManagerFileInfo> set = size_map.get(len);
                    if (set == null) {
                        set = new HashSet<>();
                        size_map.put(len, set);
                    }
                    boolean same_dm = false;
                    for (DiskManagerFileInfo existing : set) {
                        if (existing.getDownloadManager() == dm) {
                            same_dm = true;
                            break;
                        }
                    }
                    if (!same_dm) {
                        set.add(file);
                        if (set.size() == 2) {
                            interesting.add(set);
                        }
                    }
                }
            }
            // remove sets consisting of only completed files
            Iterator<Set<DiskManagerFileInfo>> interesting_it = interesting.iterator();
            while (interesting_it.hasNext()) {
                Set<DiskManagerFileInfo> set = interesting_it.next();
                boolean all_done = true;
                for (DiskManagerFileInfo file : set) {
                    if (file.getDownloaded() != file.getLength()) {
                        all_done = false;
                        break;
                    }
                }
                if (all_done) {
                    interesting_it.remove();
                }
            }
            List<SameSizeFiles> sames_copy = new LinkedList<>(sames);
            for (Set<DiskManagerFileInfo> set : interesting) {
                boolean found = false;
                Iterator<SameSizeFiles> sames_it = sames_copy.iterator();
                while (sames_it.hasNext()) {
                    SameSizeFiles same = sames_it.next();
                    if (same.sameAs(set)) {
                        found = true;
                        sames_it.remove();
                        break;
                    }
                }
                if (!found) {
                    sames.add(new SameSizeFiles(set));
                }
            }
            for (SameSizeFiles dead : sames_copy) {
                dead.destroy();
                sames.remove(dead);
            }
            if (sames.size() > 0) {
                if (timer_event == null) {
                    timer_event = SimpleTimer.addPeriodicEvent("GMFM:sync", TIMER_PERIOD, new TimerEventPerformer() {

                        private int tick_count = 0;

                        @Override
                        public void perform(TimerEvent event) {
                            tick_count++;
                            synchronized (dm_map) {
                                for (SameSizeFiles s : sames) {
                                    s.sync(tick_count);
                                }
                            }
                        }
                    });
                }
            } else {
                if (timer_event != null) {
                    timer_event.cancel();
                    timer_event = null;
                }
            }
        }
    }
}
Also used : DownloadManager(com.biglybt.core.download.DownloadManager) DownloadManagerState(com.biglybt.core.download.DownloadManagerState) DiskManagerFileInfo(com.biglybt.core.disk.DiskManagerFileInfo) TOTorrent(com.biglybt.core.torrent.TOTorrent)

Example 15 with TOTorrent

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

the class GlobalManagerHostSupport method lookupTorrent.

@Override
public TOTorrent lookupTorrent(byte[] hash) {
    DownloadManager dm = gm.getDownloadManager(new HashWrapper(hash));
    if (dm != null) {
        TOTorrent torrent = dm.getTorrent();
        if (torrent != null) {
            return (torrent);
        }
    }
    TOTorrent torrent = DownloadManagerImpl.getStubTorrent(hash);
    return (torrent);
}
Also used : HashWrapper(com.biglybt.core.util.HashWrapper) TOTorrent(com.biglybt.core.torrent.TOTorrent) DownloadManager(com.biglybt.core.download.DownloadManager)

Aggregations

TOTorrent (com.biglybt.core.torrent.TOTorrent)123 DownloadManager (com.biglybt.core.download.DownloadManager)34 File (java.io.File)32 TOTorrentException (com.biglybt.core.torrent.TOTorrentException)29 URL (java.net.URL)25 DiskManagerFileInfo (com.biglybt.core.disk.DiskManagerFileInfo)15 TOTorrentFile (com.biglybt.core.torrent.TOTorrentFile)13 IOException (java.io.IOException)13 GlobalManager (com.biglybt.core.global.GlobalManager)10 VuzeFile (com.biglybt.core.vuzefile.VuzeFile)10 Torrent (com.biglybt.pif.torrent.Torrent)9 DownloadManagerState (com.biglybt.core.download.DownloadManagerState)8 TOTorrentAnnounceURLSet (com.biglybt.core.torrent.TOTorrentAnnounceURLSet)8 MessageBoxShell (com.biglybt.ui.swt.shells.MessageBoxShell)8 List (java.util.List)8 Map (java.util.Map)7 Core (com.biglybt.core.Core)6 DiskManagerFileInfoSet (com.biglybt.core.disk.DiskManagerFileInfoSet)6 Download (com.biglybt.pif.download.Download)6 TorrentImpl (com.biglybt.pifimpl.local.torrent.TorrentImpl)6