Search in sources :

Example 21 with Tag

use of com.biglybt.core.tag.Tag 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 22 with Tag

use of com.biglybt.core.tag.Tag 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)

Example 23 with Tag

use of com.biglybt.core.tag.Tag in project BiglyBT by BiglySoftware.

the class DownloadManagerDefaultPaths method getDownloadOrTagMovementInformation.

static MovementInformation getDownloadOrTagMovementInformation(DownloadManager dm, MovementInformation def_mi) {
    boolean move_data = true;
    boolean move_torrent = false;
    File move_to_target = null;
    String context_str = "";
    String mi_str = "";
    DownloadManagerState state = dm.getDownloadState();
    String explicit_target = state.getAttribute(DownloadManagerState.AT_MOVE_ON_COMPLETE_DIR);
    if (explicit_target != null && explicit_target.length() > 0) {
        File move_to = new File(explicit_target);
        if (!move_to.exists()) {
            move_to.mkdirs();
        }
        if (move_to.isDirectory() && move_to.canWrite()) {
            move_to_target = move_to;
            context_str = "Download-specific move-on-complete directory";
            mi_str = "Download-specific Move on Completion";
        } else {
            logInfo("Ignoring invalid download move-to location: " + move_to, dm);
        }
    }
    if (move_to_target == null) {
        List<Tag> dm_tags = TagManagerFactory.getTagManager().getTagsForTaggable(dm);
        if (dm_tags != null) {
            List<Tag> applicable_tags = new ArrayList<>();
            for (Tag tag : dm_tags) {
                if (tag.getTagType().hasTagTypeFeature(TagFeature.TF_FILE_LOCATION)) {
                    TagFeatureFileLocation fl = (TagFeatureFileLocation) tag;
                    if (fl.supportsTagMoveOnComplete()) {
                        File move_to = fl.getTagMoveOnCompleteFolder();
                        if (move_to != null) {
                            if (!move_to.exists()) {
                                move_to.mkdirs();
                            }
                            if (move_to.isDirectory() && move_to.canWrite()) {
                                applicable_tags.add(tag);
                            } else {
                                logInfo("Ignoring invalid tag move-to location: " + move_to, dm);
                            }
                        }
                    }
                }
            }
            if (!applicable_tags.isEmpty()) {
                if (applicable_tags.size() > 1) {
                    Collections.sort(applicable_tags, new Comparator<Tag>() {

                        @Override
                        public int compare(Tag o1, Tag o2) {
                            return (o1.getTagID() - o2.getTagID());
                        }
                    });
                    String str = "";
                    for (Tag tag : applicable_tags) {
                        str += (str.length() == 0 ? "" : ", ") + tag.getTagName(true);
                    }
                    logInfo("Multiple applicable tags found: " + str + " - selecting first", dm);
                }
                Tag tag_target = applicable_tags.get(0);
                TagFeatureFileLocation fl = (TagFeatureFileLocation) tag_target;
                move_to_target = fl.getTagMoveOnCompleteFolder();
                long options = fl.getTagMoveOnCompleteOptions();
                move_data = (options & TagFeatureFileLocation.FL_DATA) != 0;
                move_torrent = (options & TagFeatureFileLocation.FL_TORRENT) != 0;
                context_str = "Tag '" + tag_target.getTagName(true) + "' move-on-complete directory";
                mi_str = "Tag Move on Completion";
            }
        }
    }
    if (move_to_target != null) {
        SourceSpecification source = new SourceSpecification();
        if (def_mi.target.getBoolean("enabled", false)) {
            source.setBoolean("default dir", "Move Only When In Default Save Dir");
            source.setBoolean("default subdir", SUBDIR_PARAM);
        } else {
            source.setBoolean("default dir", false);
        }
        source.setBoolean("incomplete dl", false);
        TargetSpecification dest = new TargetSpecification();
        if (move_data) {
            dest.setBoolean("enabled", true);
            dest.setString("target_raw", move_to_target.getAbsolutePath());
        } else {
            dest.setBoolean("enabled", def_mi.target.getBoolean("enabled", false));
        }
        dest.setContext(context_str);
        if (move_torrent) {
            dest.setBoolean("torrent", true);
            dest.setString("torrent_path_raw", move_to_target.getAbsolutePath());
        } else {
            dest.setBoolean("torrent", "Move Torrent When Done");
            dest.setString("torrent_path", "Move Torrent When Done Directory");
        }
        TransferSpecification trans = new TransferSpecification();
        MovementInformation mi = new MovementInformation(source, dest, trans, mi_str);
        return (mi);
    } else {
        return (def_mi);
    }
}
Also used : DownloadManagerState(com.biglybt.core.download.DownloadManagerState) Tag(com.biglybt.core.tag.Tag) TagFeatureFileLocation(com.biglybt.core.tag.TagFeatureFileLocation) File(java.io.File)

Example 24 with Tag

use of com.biglybt.core.tag.Tag in project BiglyBT by BiglySoftware.

the class CoreImpl method checkSleepActions.

protected void checkSleepActions() {
    boolean ps_downloading = COConfigurationManager.getBooleanParameter("Prevent Sleep Downloading");
    boolean ps_fp_seed = COConfigurationManager.getBooleanParameter("Prevent Sleep FP Seeding");
    String tag_name = COConfigurationManager.getStringParameter("Prevent Sleep Tag");
    Tag ps_tag = null;
    tag_name = tag_name.trim();
    if (!tag_name.isEmpty()) {
        ps_tag = TagManagerFactory.getTagManager().getTagType(TagType.TT_DOWNLOAD_MANUAL).getTag(tag_name, true);
    }
    String declining_subsystems = "";
    for (PowerManagementListener l : power_listeners) {
        try {
            if (!l.requestPowerStateChange(PowerManagementListener.ST_SLEEP, null)) {
                declining_subsystems += (declining_subsystems.length() == 0 ? "" : ",") + l.getPowerName();
            }
        } catch (Throwable e) {
            Debug.out(e);
        }
    }
    PlatformManager platform = PlatformManagerFactory.getPlatformManager();
    if (declining_subsystems.length() == 0 && !(ps_downloading || ps_fp_seed || ps_tag != null)) {
        if (platform.getPreventComputerSleep()) {
            setPreventComputerSleep(platform, false, "configuration change");
        }
        return;
    }
    boolean prevent_sleep = false;
    String prevent_reason = null;
    if (declining_subsystems.length() > 0) {
        prevent_sleep = true;
        prevent_reason = "subsystems declined sleep: " + declining_subsystems;
    } else if (ps_tag != null && ps_tag.getTaggedCount() > 0) {
        prevent_sleep = true;
        prevent_reason = "tag '" + tag_name + "' has entries";
    } else {
        List<DownloadManager> managers = getGlobalManager().getDownloadManagers();
        for (DownloadManager manager : managers) {
            int state = manager.getState();
            if (state == DownloadManager.STATE_FINISHING || manager.getDownloadState().getFlag(DownloadManagerState.FLAG_METADATA_DOWNLOAD)) {
                if (ps_downloading) {
                    prevent_sleep = true;
                    prevent_reason = "active downloads";
                    break;
                }
            } else {
                if (state == DownloadManager.STATE_DOWNLOADING) {
                    PEPeerManager pm = manager.getPeerManager();
                    if (pm != null) {
                        if (pm.hasDownloadablePiece()) {
                            if (ps_downloading) {
                                prevent_sleep = true;
                                prevent_reason = "active downloads";
                                break;
                            }
                        } else {
                            // its effectively seeding, change so logic about recheck obeyed below
                            state = DownloadManager.STATE_SEEDING;
                        }
                    }
                }
                if (state == DownloadManager.STATE_SEEDING && ps_fp_seed) {
                    DiskManager disk_manager = manager.getDiskManager();
                    if (disk_manager != null && disk_manager.getCompleteRecheckStatus() != -1) {
                        if (ps_downloading) {
                            prevent_sleep = true;
                            prevent_reason = "active downloads";
                            break;
                        }
                    } else {
                        try {
                            DefaultRankCalculator calc = StartStopRulesDefaultPlugin.getRankCalculator(PluginCoreUtils.wrap(manager));
                            if (calc.getCachedIsFP()) {
                                prevent_sleep = true;
                                prevent_reason = "first-priority seeding";
                                break;
                            }
                        } catch (Throwable e) {
                        }
                    }
                }
            }
        }
    }
    if (prevent_sleep != platform.getPreventComputerSleep()) {
        if (prevent_sleep) {
            prevent_sleep_remove_trigger = false;
        } else {
            if (!prevent_sleep_remove_trigger) {
                prevent_sleep_remove_trigger = true;
                return;
            }
        }
        if (prevent_reason == null) {
            if (ps_downloading && ps_fp_seed) {
                prevent_reason = "no active downloads or first-priority seeding";
            } else if (ps_downloading) {
                prevent_reason = "no active downloads";
            } else {
                prevent_reason = "no active first-priority seeding";
            }
        }
        setPreventComputerSleep(platform, prevent_sleep, prevent_reason);
    }
}
Also used : DefaultRankCalculator(com.biglybt.plugin.startstoprules.defaultplugin.DefaultRankCalculator) PlatformManager(com.biglybt.platform.PlatformManager) PEPeerManager(com.biglybt.core.peer.PEPeerManager) Tag(com.biglybt.core.tag.Tag) DiskManager(com.biglybt.core.disk.DiskManager) PowerManagementListener(com.biglybt.pif.utils.PowerManagementListener) DownloadManager(com.biglybt.core.download.DownloadManager)

Example 25 with Tag

use of com.biglybt.core.tag.Tag in project BiglyBT by BiglySoftware.

the class DeviceMediaRendererImpl method updateStatus.

@Override
protected void updateStatus(int tick_count) {
    super.updateStatus(tick_count);
    if (tick_count > 0 && tick_count % TAG_SHARE_CHECK_TICKS == 0) {
        long tag_id = getAutoShareToTagID();
        if (tag_id != -1) {
            synchronized (DeviceMediaRendererImpl.class) {
                if (share_ta == null) {
                    share_ta = PluginInitializer.getDefaultInterface().getTorrentManager().getPluginAttribute("DeviceMediaRendererImpl:tag_share");
                }
            }
            TagManager tm = TagManagerFactory.getTagManager();
            Tag assigned_tag = tm.lookupTagByUID(tag_id);
            if (assigned_tag != null) {
                // not going to want this to be public
                assigned_tag.setPublic(false);
                synchronized (share_requests) {
                    if (share_requests.size() == 0) {
                        Set<Taggable> taggables = assigned_tag.getTagged();
                        Set<String> done_files = new HashSet<>();
                        for (Taggable temp : taggables) {
                            if (!(temp instanceof DownloadManager)) {
                                continue;
                            }
                            DownloadManager dm = (DownloadManager) temp;
                            Download download = PluginCoreUtils.wrap(dm);
                            String attr = download.getAttribute(share_ta);
                            if (attr != null) {
                                done_files.add(attr);
                            }
                        }
                        TranscodeFileImpl[] files = getFiles();
                        for (TranscodeFileImpl file : files) {
                            if (file.isComplete()) {
                                try {
                                    File target_file = file.getTargetFile().getFile(true);
                                    long size = target_file.length();
                                    if (target_file.exists() && size > 0) {
                                        String suffix = " (" + file.getProfileName() + " - " + DisplayFormatters.formatByteCountToKiBEtc(size) + ")";
                                        String share_name = file.getName() + suffix;
                                        String key = target_file.getName() + suffix;
                                        if (!done_files.contains(key)) {
                                            share_requests.add(new Object[] { key, target_file, share_name, assigned_tag });
                                        }
                                    }
                                } catch (Throwable e) {
                                }
                            }
                        }
                        if (share_requests.size() > 0) {
                            shareRequestAdded();
                        }
                    }
                }
            }
        }
    }
}
Also used : DownloadManager(com.biglybt.core.download.DownloadManager) TagManager(com.biglybt.core.tag.TagManager) Tag(com.biglybt.core.tag.Tag) Taggable(com.biglybt.core.tag.Taggable) Download(com.biglybt.pif.download.Download) ShareResourceFile(com.biglybt.pif.sharing.ShareResourceFile) File(java.io.File)

Aggregations

Tag (com.biglybt.core.tag.Tag)55 DownloadManager (com.biglybt.core.download.DownloadManager)15 TagFeatureRateLimit (com.biglybt.core.tag.TagFeatureRateLimit)12 File (java.io.File)9 TagManager (com.biglybt.core.tag.TagManager)8 TagType (com.biglybt.core.tag.TagType)8 ArrayList (java.util.ArrayList)8 List (java.util.List)5 Core (com.biglybt.core.Core)4 CoreRunningListener (com.biglybt.core.CoreRunningListener)4 PEPeerManager (com.biglybt.core.peer.PEPeerManager)4 TagFeatureFileLocation (com.biglybt.core.tag.TagFeatureFileLocation)4 Point (org.eclipse.swt.graphics.Point)4 Category (com.biglybt.core.category.Category)3 DiskManagerFileInfo (com.biglybt.core.disk.DiskManagerFileInfo)3 DownloadManagerInitialisationAdapter (com.biglybt.core.download.DownloadManagerInitialisationAdapter)3 DownloadManagerState (com.biglybt.core.download.DownloadManagerState)3 TOTorrent (com.biglybt.core.torrent.TOTorrent)3 Download (com.biglybt.pif.download.Download)3 GlobalManager (com.biglybt.core.global.GlobalManager)2