Search in sources :

Example 1 with DownloadManagerInitialisationAdapter

use of com.biglybt.core.download.DownloadManagerInitialisationAdapter 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 2 with DownloadManagerInitialisationAdapter

use of com.biglybt.core.download.DownloadManagerInitialisationAdapter in project BiglyBT by BiglySoftware.

the class TagManagerImpl method init.

private void init() {
    if (!enabled) {
        return;
    }
    Core core = CoreFactory.getSingleton();
    final TagPropertyTrackerHandler auto_tracker = new TagPropertyTrackerHandler(core, this);
    untagged_handler = new TagPropertyUntaggedHandler(core, this);
    new TagPropertyTrackerTemplateHandler(core, this);
    constraint_handler = new TagPropertyConstraintHandler(core, this);
    core.addLifecycleListener(new CoreLifecycleAdapter() {

        @Override
        public void started(Core core) {
            core.getPluginManager().getDefaultPluginInterface().getDownloadManager().getGlobalDownloadEventNotifier().addCompletionListener(TagManagerImpl.this);
        }

        @Override
        public void componentCreated(Core core, CoreComponent component) {
            if (component instanceof GlobalManager) {
                GlobalManager global_manager = (GlobalManager) component;
                global_manager.addDownloadManagerInitialisationAdapter(new DownloadManagerInitialisationAdapter() {

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

                    @Override
                    public void initialised(DownloadManager manager, boolean for_seeding) {
                        com.biglybt.core.disk.DiskManagerFileInfo[] files = manager.getDiskManagerFileInfoSet().getFiles();
                        for (com.biglybt.core.disk.DiskManagerFileInfo file : files) {
                            if (file.getTorrentFile().getPathComponents().length == 1) {
                                String name = file.getTorrentFile().getRelativePath().toLowerCase(Locale.US);
                                if (name.equals("index.html") || name.equals("index.htm")) {
                                    TagType tt = TagManagerFactory.getTagManager().getTagType(TagType.TT_DOWNLOAD_MANUAL);
                                    String tag_name = "Websites";
                                    Tag tag = tt.getTag(tag_name, true);
                                    try {
                                        if (tag == null) {
                                            tag = tt.createTag(tag_name, true);
                                        }
                                        if (!tag.hasTaggable(manager)) {
                                            tag.addTaggable(manager);
                                            tag.setDescription(MessageText.getString("tag.website.desc"));
                                        }
                                    } catch (Throwable e) {
                                        Debug.out(e);
                                    }
                                    break;
                                }
                            }
                        }
                    }
                });
                global_manager.addDownloadManagerInitialisationAdapter(new DownloadManagerInitialisationAdapter() {

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

                    @Override
                    public void initialised(DownloadManager manager, boolean for_seeding) {
                        if (for_seeding) {
                            return;
                        }
                        // perform any auto-tagging - note that auto-tags aren't applied to the download
                        // yet
                        List<Tag> auto_tags = auto_tracker.getTagsForDownload(manager);
                        Set<Tag> tags = new HashSet<>(getTagsForTaggable(TagType.TT_DOWNLOAD_MANUAL, manager));
                        tags.addAll(auto_tags);
                        if (tags.size() == 0) {
                            // pick up untagged tags here as they haven't been added yet :(
                            tags.addAll(untagged_handler.getUntaggedTags());
                        }
                        if (tags.size() > 0) {
                            List<Tag> sl_tags = new ArrayList<>();
                            for (Tag tag : tags) {
                                TagFeatureFileLocation fl = (TagFeatureFileLocation) tag;
                                if (fl.supportsTagInitialSaveFolder()) {
                                    File save_loc = fl.getTagInitialSaveFolder();
                                    if (save_loc != null) {
                                        sl_tags.add(tag);
                                    }
                                }
                            }
                            if (sl_tags.size() > 0) {
                                if (sl_tags.size() > 1) {
                                    Collections.sort(sl_tags, new Comparator<Tag>() {

                                        @Override
                                        public int compare(Tag o1, Tag o2) {
                                            return (o1.getTagID() - o2.getTagID());
                                        }
                                    });
                                }
                                TagFeatureFileLocation tag = (TagFeatureFileLocation) sl_tags.get(0);
                                long options = tag.getTagInitialSaveOptions();
                                boolean set_data = (options & TagFeatureFileLocation.FL_DATA) != 0;
                                boolean set_torrent = (options & TagFeatureFileLocation.FL_TORRENT) != 0;
                                File new_loc = tag.getTagInitialSaveFolder();
                                if (set_data) {
                                    File old_loc = manager.getSaveLocation();
                                    if (!new_loc.equals(old_loc)) {
                                        manager.setTorrentSaveDir(new_loc.getAbsolutePath());
                                    }
                                }
                                if (set_torrent) {
                                    File old_torrent_file = new File(manager.getTorrentFileName());
                                    if (old_torrent_file.exists()) {
                                        try {
                                            manager.setTorrentFile(new_loc, old_torrent_file.getName());
                                        } catch (Throwable e) {
                                            Debug.out(e);
                                        }
                                    }
                                }
                            }
                        }
                    }
                });
            }
        }

        @Override
        public void stopped(Core core) {
            destroy();
        }
    });
    SimpleTimer.addPeriodicEvent("TM:Sync", 30 * 1000, new TimerEventPerformer() {

        @Override
        public void perform(TimerEvent event) {
            for (TagType tt : tag_types) {
                ((TagTypeBase) tt).sync();
            }
        }
    });
}
Also used : CoreLifecycleAdapter(com.biglybt.core.CoreLifecycleAdapter) DownloadManager(com.biglybt.core.download.DownloadManager) GlobalManager(com.biglybt.core.global.GlobalManager) CoreComponent(com.biglybt.core.CoreComponent) Core(com.biglybt.core.Core) DiskManagerFileInfo(com.biglybt.pif.disk.DiskManagerFileInfo) DownloadManagerInitialisationAdapter(com.biglybt.core.download.DownloadManagerInitialisationAdapter) VuzeFile(com.biglybt.core.vuzefile.VuzeFile) File(java.io.File)

Example 3 with DownloadManagerInitialisationAdapter

use of com.biglybt.core.download.DownloadManagerInitialisationAdapter 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;
}
Also used : DownloadManager(com.biglybt.core.download.DownloadManager) DownloadManagerState(com.biglybt.core.download.DownloadManagerState) GlobalManager(com.biglybt.core.global.GlobalManager) UIFunctions(com.biglybt.ui.UIFunctions) CoreRunningListener(com.biglybt.core.CoreRunningListener) ArrayList(java.util.ArrayList) List(java.util.List) Core(com.biglybt.core.Core) DiskManagerFileInfo(com.biglybt.core.disk.DiskManagerFileInfo) TorrentOpenFileOptions(com.biglybt.core.torrent.impl.TorrentOpenFileOptions) DiskManagerFileInfoSet(com.biglybt.core.disk.DiskManagerFileInfoSet) DownloadManagerInitialisationAdapter(com.biglybt.core.download.DownloadManagerInitialisationAdapter) TOTorrentException(com.biglybt.core.torrent.TOTorrentException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) TOTorrentException(com.biglybt.core.torrent.TOTorrentException) TOTorrent(com.biglybt.core.torrent.TOTorrent) Tag(com.biglybt.core.tag.Tag) VuzeFile(com.biglybt.core.vuzefile.VuzeFile) File(java.io.File)

Example 4 with DownloadManagerInitialisationAdapter

use of com.biglybt.core.download.DownloadManagerInitialisationAdapter in project BiglyBT by BiglySoftware.

the class ProgressPanel method makeTorrent.

public void makeTorrent() {
    int tracker_type = wizard.getTrackerType();
    if (tracker_type == NewTorrentWizard.TT_EXTERNAL) {
        TrackersUtil.getInstance().addTracker(wizard.trackerURL);
    }
    File f;
    if (wizard.create_mode == NewTorrentWizard.MODE_DIRECTORY) {
        f = new File(wizard.directoryPath);
    } else if (wizard.create_mode == NewTorrentWizard.MODE_SINGLE_FILE) {
        f = new File(wizard.singlePath);
    } else {
        f = wizard.byo_desc_file;
    }
    try {
        URL url = new URL(wizard.trackerURL);
        final TOTorrent torrent;
        if (wizard.getPieceSizeComputed()) {
            wizard.creator = TOTorrentFactory.createFromFileOrDirWithComputedPieceLength(f, url, wizard.getAddOtherHashes());
            wizard.creator.addListener(this);
            wizard.creator.setFileIsLayoutDescriptor(wizard.create_mode == NewTorrentWizard.MODE_BYO);
            torrent = wizard.creator.create();
        } else {
            wizard.creator = TOTorrentFactory.createFromFileOrDirWithFixedPieceLength(f, url, wizard.getAddOtherHashes(), wizard.getPieceSizeManual());
            wizard.creator.addListener(this);
            wizard.creator.setFileIsLayoutDescriptor(wizard.create_mode == NewTorrentWizard.MODE_BYO);
            torrent = wizard.creator.create();
        }
        if (tracker_type == NewTorrentWizard.TT_DECENTRAL) {
            TorrentUtils.setDecentralised(torrent);
        }
        torrent.setComment(wizard.getComment());
        TorrentUtils.setDHTBackupEnabled(torrent, wizard.permitDHT);
        TorrentUtils.setPrivate(torrent, wizard.getPrivateTorrent());
        LocaleTorrentUtil.setDefaultTorrentEncoding(torrent);
        // mark this newly created torrent as complete to avoid rechecking on open
        final File save_dir;
        if (wizard.create_mode == NewTorrentWizard.MODE_DIRECTORY) {
            save_dir = f;
        } else if (wizard.create_mode == NewTorrentWizard.MODE_SINGLE_FILE) {
            save_dir = f.getParentFile();
        } else {
            String save_path = COConfigurationManager.getStringParameter("Default save path");
            File f_save_path = new File(save_path);
            if (!f_save_path.canWrite()) {
                throw (new Exception("Default save path is not configured: See Tools->Options->File"));
            }
            save_dir = f_save_path;
        }
        if (wizard.useMultiTracker) {
            this.reportCurrentTask(MessageText.getString("wizard.addingmt"));
            TorrentUtils.listToAnnounceGroups(wizard.trackers, torrent);
        }
        if (wizard.useWebSeed && wizard.webseeds.size() > 0) {
            this.reportCurrentTask(MessageText.getString("wizard.webseed.adding"));
            Map ws = wizard.webseeds;
            List getright = (List) ws.get("getright");
            if (getright.size() > 0) {
                for (int i = 0; i < getright.size(); i++) {
                    reportCurrentTask("    GetRight: " + getright.get(i));
                }
                torrent.setAdditionalListProperty("url-list", new ArrayList(getright));
            }
            List webseed = (List) ws.get("webseed");
            if (webseed.size() > 0) {
                for (int i = 0; i < webseed.size(); i++) {
                    reportCurrentTask("    WebSeed: " + webseed.get(i));
                }
                torrent.setAdditionalListProperty("httpseeds", new ArrayList(webseed));
            }
        }
        // must do this last as it saves a copy of the torrent state for future opening...
        /*
       * actually, don't need to do this as the "open-for-seeding" option used when adding the download
       * does the job. Reason I stopped doing this is
       * https://sourceforge.net/tracker/index.php?func=detail&aid=1721917&group_id=84122&atid=575154
       *
	  DownloadManagerState	download_manager_state =
			DownloadManagerStateFactory.getDownloadState( torrent );

	  TorrentUtils.setResumeDataCompletelyValid( download_manager_state );

	  download_manager_state.save();
     */
        this.reportCurrentTask(MessageText.getString("wizard.maketorrent.savingfile"));
        final File torrent_file = new File(wizard.savePath);
        torrent.serialiseToBEncodedFile(torrent_file);
        this.reportCurrentTask(MessageText.getString("wizard.maketorrent.filesaved"));
        wizard.switchToClose(new Runnable() {

            @Override
            public void run() {
                show_torrent_file.setEnabled(true);
            }
        });
        if (wizard.autoOpen) {
            CoreWaiterSWT.waitForCore(TriggerInThread.NEW_THREAD, new CoreRunningListener() {

                @Override
                public void coreRunning(Core core) {
                    boolean start_stopped = COConfigurationManager.getBooleanParameter("Default Start Torrents Stopped");
                    byte[] hash = null;
                    try {
                        hash = torrent.getHash();
                    } catch (TOTorrentException e1) {
                    }
                    if (wizard.forceStart || wizard.superseed) {
                        // superseeding can only be set for an active download...
                        start_stopped = false;
                    }
                    DownloadManagerInitialisationAdapter dmia;
                    final String initialTags = wizard.getInitialTags(true);
                    if (initialTags.length() > 0) {
                        dmia = new DownloadManagerInitialisationAdapter() {

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

                            @Override
                            public void initialised(DownloadManager dm, boolean for_seeding) {
                                TagManager tm = TagManagerFactory.getTagManager();
                                TagType tag_type = tm.getTagType(TagType.TT_DOWNLOAD_MANUAL);
                                String[] bits = initialTags.replace(';', ',').split(",");
                                for (String tag : bits) {
                                    tag = tag.trim();
                                    if (tag.length() > 0) {
                                        try {
                                            Tag t = tag_type.getTag(tag, true);
                                            if (t == null) {
                                                t = tag_type.createTag(tag, true);
                                            }
                                            t.addTaggable(dm);
                                        } catch (Throwable e) {
                                            Debug.out(e);
                                        }
                                    }
                                }
                            }
                        };
                    } else {
                        dmia = null;
                    }
                    final DownloadManager dm = core.getGlobalManager().addDownloadManager(torrent_file.toString(), hash, save_dir.toString(), start_stopped ? DownloadManager.STATE_STOPPED : // persistent
                    DownloadManager.STATE_QUEUED, // persistent
                    true, // for seeding
                    true, dmia);
                    if (!start_stopped && dm != null) {
                        // We want this to move to seeding ASAP, so move it to the top
                        // of the download list, where it will do the quick check and
                        // move to the seeding list
                        // (the for seeding flag should really be smarter and verify
                        // it's a seeding torrent and set appropriately)
                        dm.getGlobalManager().moveTop(new DownloadManager[] { dm });
                    }
                    if (wizard.autoHost && wizard.getTrackerType() != NewTorrentWizard.TT_EXTERNAL) {
                        try {
                            core.getTrackerHost().hostTorrent(torrent, true, false);
                        } catch (TRHostException e) {
                            Logger.log(new LogAlert(LogAlert.REPEATABLE, "Host operation fails", e));
                        }
                    }
                    if (dm != null) {
                        if (wizard.forceStart) {
                            dm.setForceStart(true);
                        }
                        if (wizard.superseed) {
                            new AEThread2("startwait") {

                                @Override
                                public void run() {
                                    long start = SystemTime.getMonotonousTime();
                                    while (true) {
                                        if (dm.isDestroyed()) {
                                            break;
                                        }
                                        long elapsed = SystemTime.getMonotonousTime() - start;
                                        if (elapsed > 60 * 1000) {
                                            int state = dm.getState();
                                            if (state == DownloadManager.STATE_ERROR || state == DownloadManager.STATE_STOPPED) {
                                                break;
                                            }
                                        }
                                        if (elapsed > 5 * 60 * 1000) {
                                            break;
                                        }
                                        PEPeerManager pm = dm.getPeerManager();
                                        if (pm != null) {
                                            pm.setSuperSeedMode(true);
                                            break;
                                        }
                                        try {
                                            Thread.sleep(1000);
                                        } catch (Throwable e) {
                                            break;
                                        }
                                    }
                                }
                            }.start();
                        }
                    }
                }
            });
        }
    } catch (Exception e) {
        if (e instanceof TOTorrentException) {
            TOTorrentException te = (TOTorrentException) e;
            if (te.getReason() == TOTorrentException.RT_CANCELLED) {
            // expected failure, don't log exception
            } else {
                reportCurrentTask(MessageText.getString("wizard.operationfailed"));
                reportCurrentTask(TorrentUtils.exceptionToText(te));
            }
        } else {
            Debug.printStackTrace(e);
            reportCurrentTask(MessageText.getString("wizard.operationfailed"));
            reportCurrentTask(Debug.getStackTrace(e));
        }
        wizard.switchToClose();
    }
}
Also used : TRHostException(com.biglybt.core.tracker.host.TRHostException) ArrayList(java.util.ArrayList) DownloadManager(com.biglybt.core.download.DownloadManager) URL(java.net.URL) CoreRunningListener(com.biglybt.core.CoreRunningListener) ArrayList(java.util.ArrayList) List(java.util.List) Core(com.biglybt.core.Core) DownloadManagerInitialisationAdapter(com.biglybt.core.download.DownloadManagerInitialisationAdapter) TRHostException(com.biglybt.core.tracker.host.TRHostException) LogAlert(com.biglybt.core.logging.LogAlert) TagType(com.biglybt.core.tag.TagType) TagManager(com.biglybt.core.tag.TagManager) PEPeerManager(com.biglybt.core.peer.PEPeerManager) Tag(com.biglybt.core.tag.Tag) File(java.io.File) Map(java.util.Map)

Aggregations

Core (com.biglybt.core.Core)4 DownloadManager (com.biglybt.core.download.DownloadManager)4 DownloadManagerInitialisationAdapter (com.biglybt.core.download.DownloadManagerInitialisationAdapter)4 File (java.io.File)4 GlobalManager (com.biglybt.core.global.GlobalManager)3 Tag (com.biglybt.core.tag.Tag)3 ArrayList (java.util.ArrayList)3 CoreRunningListener (com.biglybt.core.CoreRunningListener)2 LogAlert (com.biglybt.core.logging.LogAlert)2 TagManager (com.biglybt.core.tag.TagManager)2 TagType (com.biglybt.core.tag.TagType)2 TOTorrent (com.biglybt.core.torrent.TOTorrent)2 VuzeFile (com.biglybt.core.vuzefile.VuzeFile)2 List (java.util.List)2 CoreComponent (com.biglybt.core.CoreComponent)1 CoreLifecycleAdapter (com.biglybt.core.CoreLifecycleAdapter)1 DiskManagerFileInfo (com.biglybt.core.disk.DiskManagerFileInfo)1 DiskManagerFileInfoSet (com.biglybt.core.disk.DiskManagerFileInfoSet)1 DownloadManagerState (com.biglybt.core.download.DownloadManagerState)1 LogEvent (com.biglybt.core.logging.LogEvent)1