Search in sources :

Example 1 with TagManager

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

the class SystemTraySWT method updateUI.

// @see UIUpdatable#updateUI()
@Override
public void updateUI(boolean is_visible) {
    if (interval++ % 10 > 0) {
        return;
    }
    if (trayItem.isDisposed()) {
        uiFunctions.getUIUpdater().removeUpdater(this);
        return;
    }
    if (core == null || !core.isStarted()) {
        return;
    }
    if (enableTooltip) {
        GlobalManagerStats stats = gm.getStats();
        StringBuilder toolTip = new StringBuilder();
        int seeding = 0;
        int downloading = 0;
        DownloadManager next_download = null;
        long next_download_eta = Long.MAX_VALUE;
        TagManager tm = TagManagerFactory.getTagManager();
        if (tm != null && tm.isEnabled()) {
            TagType tt = tm.getTagType(TagType.TT_DOWNLOAD_STATE);
            if (tt != null) {
                TagDownload dl_tag = (TagDownload) tt.getTag(1);
                downloading = dl_tag.getTaggedCount();
                seeding = tt.getTag(2).getTaggedCount();
                if (enableTooltipNextETA && downloading > 0) {
                    for (DownloadManager dl : dl_tag.getTaggedDownloads()) {
                        DownloadManagerStats dl_stats = dl.getStats();
                        long eta = dl_stats.getSmoothedETA();
                        if (eta < next_download_eta) {
                            next_download_eta = eta;
                            next_download = dl;
                        }
                    }
                }
            }
        } else {
        // OMG this must be slow on 10k lists
        /*
		  		List<?> managers = gm.getDownloadManagers();
		  		for (int i = 0; i < managers.size(); i++) {
		  			DownloadManager manager = (DownloadManager) managers.get(i);
		  			int state = manager.getState();
		  			if (state == DownloadManager.STATE_DOWNLOADING)
		  				downloading++;
		  			if (state == DownloadManager.STATE_SEEDING)
		  				seeding++;
		  		}
		  		*/
        }
        String seeding_text = seedingKeyVal.replaceAll("%1", "" + seeding);
        String downloading_text = downloadingKeyVal.replaceAll("%1", "" + downloading);
        toolTip.append(seeding_text).append(downloading_text).append("\n");
        if (next_download != null) {
            String dl_name = next_download.getDisplayName();
            if (dl_name.length() > 80) {
                dl_name = dl_name.substring(0, 77) + "...";
            }
            dl_name = dl_name.replaceAll("&", "&&");
            toolTip.append("  ");
            toolTip.append(dl_name);
            toolTip.append(": ");
            toolTip.append(etaKeyVal);
            toolTip.append("=");
            toolTip.append(DisplayFormatters.formatETA(next_download_eta));
            toolTip.append("\n");
        }
        toolTip.append(dlAbbrKeyVal).append(" ");
        toolTip.append(DisplayFormatters.formatDataProtByteCountToKiBEtcPerSec(stats.getDataReceiveRate(), stats.getProtocolReceiveRate()));
        toolTip.append(", ").append(ulAbbrKeyVal).append(" ");
        toolTip.append(DisplayFormatters.formatDataProtByteCountToKiBEtcPerSec(stats.getDataSendRate(), stats.getProtocolSendRate()));
        int alerts = Alerts.getUnviewedLogAlertCount();
        if (alerts > 0) {
            toolTip.append("\n");
            toolTip.append(alertsKeyVal.replaceAll("%1", "" + alerts));
        }
        trayItem.setToolTipText(toolTip.toString());
    }
    if (Constants.isUnix && gm != null) {
        GlobalManagerStats stats = gm.getStats();
        long l = (stats.getDataReceiveRate() + stats.getDataSendRate()) / 1024;
        if (l != lastUnixVal) {
            lastUnixVal = l;
            trayItem.setMenu(menu, menuBuilder);
        }
    }
    // Why should we refresh the image? it never changes ...
    // and is a memory bottleneck for some non-obvious reasons.
    // trayItem.setImage(ImageLoader.getInstance().getImage("logo16"));
    trayItem.setVisible(true);
}
Also used : TagType(com.biglybt.core.tag.TagType) TagManager(com.biglybt.core.tag.TagManager) GlobalManagerStats(com.biglybt.core.global.GlobalManagerStats) DownloadManagerStats(com.biglybt.core.download.DownloadManagerStats) DownloadManager(com.biglybt.core.download.DownloadManager) TagDownload(com.biglybt.core.tag.TagDownload)

Example 2 with TagManager

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

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

the class StartStopRulesDefaultPlugin method reloadConfigParams.

private void reloadConfigParams() {
    try {
        this_mon.enter();
        int iNewRankType = plugin_config.getUnsafeIntParameter("StartStopManager_iRankType");
        minSpeedForActiveSeeding = plugin_config.getUnsafeIntParameter("StartStopManager_iMinSpeedForActiveSeeding");
        maxStalledSeeding = plugin_config.getUnsafeIntParameter("StartStopManager_iMaxStalledSeeding");
        if (maxStalledSeeding <= 0) {
            // insanity :)
            maxStalledSeeding = 999;
        }
        stalledSeedingIgnoreZP = plugin_config.getUnsafeBooleanParameter("StartStopManager_bMaxStalledSeedingIgnoreZP");
        _maxActive = plugin_config.getUnsafeIntParameter("max active torrents");
        _maxActiveWhenSeedingEnabled = plugin_config.getUnsafeBooleanParameter("StartStopManager_bMaxActiveTorrentsWhenSeedingEnabled");
        _maxActiveWhenSeeding = plugin_config.getUnsafeIntParameter("StartStopManager_iMaxActiveTorrentsWhenSeeding");
        maxConfiguredDownloads = plugin_config.getUnsafeIntParameter("max downloads");
        boolean min_eq_max = plugin_config.getUnsafeBooleanParameter("StartStopManager_bMaxMinDLLinked");
        if (min_eq_max) {
            minDownloads = maxConfiguredDownloads;
        } else {
            minDownloads = plugin_config.getUnsafeIntParameter("min downloads");
        }
        bMaxDownloadIgnoreChecking = plugin_config.getUnsafeBooleanParameter("StartStopManager_bMaxDownloadIgnoreChecking");
        numPeersAsFullCopy = plugin_config.getUnsafeIntParameter("StartStopManager_iNumPeersAsFullCopy");
        iFakeFullCopySeedStart = plugin_config.getUnsafeIntParameter("StartStopManager_iFakeFullCopySeedStart");
        bAutoReposition = plugin_config.getUnsafeBooleanParameter("StartStopManager_bAutoReposition");
        minTimeAlive = plugin_config.getUnsafeIntParameter("StartStopManager_iMinSeedingTime") * 1000;
        bDebugLog = plugin_config.getUnsafeBooleanParameter("StartStopManager_bDebugLog");
        bAutoStart0Peers = plugin_config.getUnsafeBooleanParameter("StartStopManager_bAutoStart0Peers");
        globalDownloadLimit = plugin_config.getUnsafeIntParameter("Max Download Speed KBs", 0);
        globalUploadLimit = plugin_config.getUnsafeIntParameter("Max Upload Speed KBs", 0);
        globalUploadWhenSeedingLimit = plugin_config.getUnsafeBooleanParameter("enable.seedingonly.upload.rate") ? plugin_config.getUnsafeIntParameter("Max Upload Speed Seeding KBs", 0) : globalUploadLimit;
        bStopOnceBandwidthMet = plugin_config.getUnsafeBooleanParameter("StartStopManager_bStopOnceBandwidthMet");
        bStartNoMoreSeedsWhenUpLimitMet = plugin_config.getUnsafeBooleanParameter("StartStopManager_bStartNoMoreSeedsWhenUpLimitMet");
        bStartNoMoreSeedsWhenUpLimitMetPercent = plugin_config.getUnsafeBooleanParameter("StartStopManager_bStartNoMoreSeedsWhenUpLimitMetPercent");
        bStartNoMoreSeedsWhenUpLimitMetSlack = plugin_config.getUnsafeIntParameter("StartStopManager_bStartNoMoreSeedsWhenUpLimitMetSlack");
        boolean move_top = plugin_config.getUnsafeBooleanParameter("StartStopManager_bNewSeedsMoveTop");
        plugin_config.setCoreBooleanParameter(PluginConfig.CORE_PARAM_BOOLEAN_NEW_SEEDS_START_AT_TOP, move_top);
        if (iNewRankType != iRankType) {
            iRankType = iNewRankType;
            // shorten recalc for timed rank type, since the calculation is fast and we want to stop on the second
            if (iRankType == RANK_TIMED) {
                if (recalcSeedingRanksTask == null) {
                    recalcAllSeedingRanks(false);
                    recalcSeedingRanksTask = new RecalcSeedingRanksTask();
                    SimpleTimer.addPeriodicEvent("StartStop:recalcSR", 1000, recalcSeedingRanksTask);
                }
            } else if (recalcSeedingRanksTask != null) {
                recalcSeedingRanksTask.cancel();
                recalcSeedingRanksTask = null;
            }
        }
        iDownloadSortType = plugin_config.getUnsafeIntParameter("StartStopManager_Downloading_iSortType", -1);
        // migrate from old boolean setting
        if (iDownloadSortType == -1) {
            boolean bDownloadAutoReposition = plugin_config.getUnsafeBooleanParameter("StartStopManager_Downloading_bAutoReposition");
            iDownloadSortType = bDownloadAutoReposition ? DefaultRankCalculator.DOWNLOAD_ORDER_SPEED : DefaultRankCalculator.DOWNLOAD_ORDER_INDEX;
            plugin_config.setCoreIntParameter("StartStopManager_Downloading_iSortType", iDownloadSortType);
        }
        iDownloadTestTimeMillis = plugin_config.getUnsafeIntParameter("StartStopManager_Downloading_iTestTimeSecs") * 1000;
        iDownloadReTestMillis = plugin_config.getUnsafeIntParameter("StartStopManager_Downloading_iRetestTimeMins") * 60 * 1000;
        bTagFirstPriority = plugin_config.getUnsafeBooleanParameter("StartStopManager_bTagFirstPriority");
        if (bTagFirstPriority) {
            TagManager tag_manager = TagManagerFactory.getTagManager();
            if (tag_manager != null && tag_manager.isEnabled()) {
                TagType tt = tag_manager.getTagType(TagType.TT_DOWNLOAD_MANUAL);
                if (fp_tag == null) {
                    fp_tag = tt.getTag("First Priority", true);
                    if (fp_tag == null) {
                        try {
                            fp_tag = tt.createTag("First Priority", true);
                        } catch (Throwable e) {
                            Debug.out(e);
                        }
                    }
                }
                Tag not_fp_tag = tt.getTag("Not First Priority", true);
                if (not_fp_tag == null) {
                    try {
                        not_fp_tag = tt.createTag("Not First Priority", true);
                    } catch (Throwable e) {
                        Debug.out(e);
                    }
                }
                if (not_fp_tag != null) {
                    TagProperty constraint = ((TagFeatureProperties) not_fp_tag).getProperty(TagFeatureProperties.PR_CONSTRAINT);
                    constraint.setStringList(new String[] { "isComplete() && !hasTag( \"First Priority\" )" });
                }
            }
        }
        /*
			 // limit _maxActive and maxDownloads based on TheColonel's specs

			 // maxActive = max_upload_speed / (slots_per_torrent * min_speed_per_peer)
			 if (_maxActive > 0) {
			 int iSlotsPerTorrent = plugin_config.getUnsafeIntParameter("Max Uploads");
			 // TODO: Track upload speed, storing the max upload speed over a minute
			 //        and use that for "unlimited" setting, or huge settings (like 200)
			 if (iSlotsPerTorrent > 0) {
			 int iMinSpeedPerPeer = 3; // for now.  TODO: config value
			 int _maxActiveLimit = iMaxUploadSpeed / (iSlotsPerTorrent * iMinSpeedPerPeer);
			 if (_maxActive > _maxActiveLimit) {
			 _maxActive = _maxActiveLimit;
			 plugin_config.setCoreIntParameter(PluginConfig.CORE_PARAM_INT_MAX_ACTIVE, _maxActive);
			 }
			 }

			 if (maxDownloads > _maxActive) {
			 maxDownloads = _maxActive;
			 plugin_config.setCoreIntParameter(PluginConfig.CORE_PARAM_INT_MAX_DOWNLOADS, maxDownloads);
			 }
			 }
			 */
        // force a recalc on all downloads by setting SR to 0, scheduling
        // a recalc on next process, and requsting a process cycle
        Collection<DefaultRankCalculator> allDownloads = downloadDataMap.values();
        DefaultRankCalculator[] dlDataArray = allDownloads.toArray(new DefaultRankCalculator[0]);
        for (int i = 0; i < dlDataArray.length; i++) {
            dlDataArray[i].getDownloadObject().setSeedingRank(0);
        }
        try {
            ranksToRecalc_mon.enter();
            synchronized (downloadDataMap) {
                ranksToRecalc.addAll(allDownloads);
            }
        } finally {
            ranksToRecalc_mon.exit();
        }
        requestProcessCycle(null);
        if (bDebugLog) {
            log.log(LoggerChannel.LT_INFORMATION, "somethingChanged: config reload");
            try {
                if (debugMenuItem == null) {
                    final String DEBUG_MENU_ID = "StartStopRules.menu.viewDebug";
                    MenuItemListener menuListener = new MenuItemListener() {

                        @Override
                        public void selected(MenuItem menu, Object target) {
                            if (!(target instanceof TableRow))
                                return;
                            TableRow tr = (TableRow) target;
                            Object ds = tr.getDataSource();
                            if (!(ds instanceof Download))
                                return;
                            DefaultRankCalculator dlData = downloadDataMap.get(ds);
                            if (dlData != null) {
                                if (swt_ui != null)
                                    swt_ui.openDebugWindow(dlData);
                                else
                                    pi.getUIManager().showTextMessage(null, null, "FP:\n" + dlData.sExplainFP + "\n" + "SR:" + dlData.sExplainSR + "\n" + "TRACE:\n" + dlData.sTrace);
                            }
                        }
                    };
                    TableManager tm = pi.getUIManager().getTableManager();
                    debugMenuItem = tm.addContextMenuItem(TableManager.TABLE_MYTORRENTS_COMPLETE, DEBUG_MENU_ID);
                    debugMenuItem.setHeaderCategory(MenuItem.HEADER_CONTROL);
                    debugMenuItem.addListener(menuListener);
                    debugMenuItem = tm.addContextMenuItem(TableManager.TABLE_MYTORRENTS_INCOMPLETE, DEBUG_MENU_ID);
                    debugMenuItem.setHeaderCategory(MenuItem.HEADER_CONTROL);
                    debugMenuItem.addListener(menuListener);
                }
            } catch (Throwable t) {
                Debug.printStackTrace(t);
            }
        }
    } finally {
        this_mon.exit();
    }
}
Also used : TagProperty(com.biglybt.core.tag.TagFeatureProperties.TagProperty) MenuItem(com.biglybt.pif.ui.menus.MenuItem) TagType(com.biglybt.core.tag.TagType) TagManager(com.biglybt.core.tag.TagManager) MenuItemListener(com.biglybt.pif.ui.menus.MenuItemListener) Tag(com.biglybt.core.tag.Tag) TagFeatureProperties(com.biglybt.core.tag.TagFeatureProperties)

Example 4 with TagManager

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

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

TagManager (com.biglybt.core.tag.TagManager)9 Tag (com.biglybt.core.tag.Tag)8 DownloadManager (com.biglybt.core.download.DownloadManager)4 TagType (com.biglybt.core.tag.TagType)4 File (java.io.File)4 List (java.util.List)3 Core (com.biglybt.core.Core)2 CoreRunningListener (com.biglybt.core.CoreRunningListener)2 DownloadManagerInitialisationAdapter (com.biglybt.core.download.DownloadManagerInitialisationAdapter)2 LogAlert (com.biglybt.core.logging.LogAlert)2 MenuItem (com.biglybt.pif.ui.menus.MenuItem)2 MenuItemListener (com.biglybt.pif.ui.menus.MenuItemListener)2 ArrayList (java.util.ArrayList)2 SelectionEvent (org.eclipse.swt.events.SelectionEvent)2 DownloadManagerStats (com.biglybt.core.download.DownloadManagerStats)1 GlobalManager (com.biglybt.core.global.GlobalManager)1 GlobalManagerStats (com.biglybt.core.global.GlobalManagerStats)1 LogEvent (com.biglybt.core.logging.LogEvent)1 PEPeerManager (com.biglybt.core.peer.PEPeerManager)1 TagDownload (com.biglybt.core.tag.TagDownload)1