⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 startstoprulesdefaultplugin.java

📁 基于JXTA开发平台的下载软件开发源代码
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
				} else {
					if (state == Download.ST_DOWNLOADING)
						downloading++;
					if (dlData.getActivelyDownloading())
						activelyDLing++;

					if (state == Download.ST_READY || state == Download.ST_WAITING
							|| state == Download.ST_PREPARING) {
						waitingToDL++;
					} else if (state == Download.ST_QUEUED) {
						incompleteQueued++;
					} //if state
				} // if completionLevel
			} // for

			if (!bOkToStartSeeding && totalOKScrapes == complete)
				bOkToStartSeeding = true;
				
			maxSeeders = calcMaxSeeders(activelyDLing + waitingToDL);
			maxActive = getMaxActive();

			if (maxActive == 0) {
				maxTorrents = 9999;
			} else if (iMaxUploadSpeed == 0) {
				maxTorrents = maxActive + 4;
			} else {
				// Don't allow more "seeding/downloading" torrents than there is enough
				// bandwidth for.  There needs to be enough bandwidth for at least
				// each torrent to get to its minSpeedForActiveSeeding  
				// (we buffer it at 2x just to be safe).
				int minSpeedPerActive = (minSpeedForActiveSeeding * 2) / 1024;
				// Even more buffering/limiting.  Limit to enough bandwidth for
				// each torrent to have potentially 3kbps.
				if (minSpeedPerActive < 3)
					minSpeedPerActive = 3;
				maxTorrents = (iMaxUploadSpeed / minSpeedPerActive);
				// Allow user to do stupid things like have more slots than their 
				// upload speed can handle
				if (maxTorrents < maxActive)
					maxTorrents = maxActive;
				//System.out.println("maxTorrents = " + maxTorrents + " = " + iMaxUploadSpeed + " / " + minSpeedPerActive);
				//System.out.println("totalTorrents = " + (activeSeedingCount + totalStalledSeeders + totalDownloading));
			}
		} // constructor
	}

	/**
	 * Running totals and stuff that gets used during a process run.
	 * Split into class so complete/incomplete can be seperated into functions
	 */
	public class ProcessVars {
		int numWaitingOrSeeding; // Running Count

		int numWaitingOrDLing; // Running Count

		/**
		 * store whether there's a torrent higher in the list that is queued
		 * We don't want to start a torrent lower in the list if there's a higherQueued
		 */
		boolean higherQueued;

		/**
		 * Tracks the position we should be at in the Completed torrents list
		 * Updates position.
		 */
		int posComplete;

		boolean bStopAndQueued;
	}

	protected void process() {
		try {
			this_mon.enter();

			// long  process_time = SystemTime.getCurrentTime();

			boolean bDebugOn = false;

			// pull the data into a local array, so we don't have to lock/synchronize
			DefaultRankCalculator[] dlDataArray;
			dlDataArray = (DefaultRankCalculator[]) downloadDataMap.values().toArray(
					new DefaultRankCalculator[downloadDataMap.size()]);

			TotalsStats totals = new TotalsStats(dlDataArray);

			String[] mainDebugEntries = null;
			if (bDebugLog) {
				log.log(LoggerChannel.LT_INFORMATION, ">>process()");
				mainDebugEntries = new String[] {
						"ok2Start=" + boolDebug(totals.bOkToStartSeeding),
						"tFrcdCding=" + totals.forcedSeeding,
						"actvCDs=" + totals.activelyCDing,
						"tW8tingToCd=" + totals.waitingToSeed,
						"tDLing=" + totals.downloading,
						"actvDLs=" + totals.activelyDLing,
						"tW8tingToDL=" + totals.waitingToDL,
						"tCom=" + totals.complete,
						"tIncQd=" + totals.incompleteQueued,
						"mxCdrs=" + totals.maxSeeders,
						"tFP=" + totals.firstPriority,
						"maxT=" + totals.maxTorrents };
			}

			somethingChanged = false;

			// Sort
			Arrays.sort(dlDataArray);

			ProcessVars vars = new ProcessVars();

			// pre-included Forced Start torrents so a torrent "above" it doesn't 
			// start (since normally it would start and assume the torrent below it
			// would stop)
			vars.numWaitingOrSeeding = totals.forcedSeeding; // Running Count
			vars.numWaitingOrDLing = 0; // Running Count
			vars.higherQueued = false;
			vars.posComplete = 0;

			// Loop 2 of 2:
			// - Start/Stop torrents based on criteria

			for (int i = 0; i < dlDataArray.length; i++) {
				DefaultRankCalculator dlData = dlDataArray[i];
				Download download = dlData.getDownloadObject();
				vars.bStopAndQueued = false;
				dlData.sTrace = "";

				// Initialize STATE_WAITING torrents
				if ((download.getState() == Download.ST_WAITING)) {
					try {
						download.initialize();
					} catch (Exception ignore) {
						/*ignore*/
					}
					if (bDebugLog && download.getState() == Download.ST_WAITING) {
						dlData.sTrace += "still in waiting state after initialize!\n";
					}
				}

				if (bAutoReposition && (iRankType != RANK_NONE)
						&& download.getStats().getDownloadCompleted(false) == 1000
						&& (totals.bOkToStartSeeding || totals.firstPriority > 0))
					download.setPosition(++vars.posComplete);

				int state = download.getState();

				// Never do anything to stopped entries
				if (state == Download.ST_STOPPING || state == Download.ST_STOPPED
						|| state == Download.ST_ERROR) {
					continue;
				}

				// Handle incomplete DLs
				if (download.getStats().getDownloadCompleted(false) != 1000) {
					handleInCompleteDownload(dlData, vars, totals);
				} else if (totals.bOkToStartSeeding) {
					handleCompletedDownload(dlDataArray, dlData, vars, totals);
				}

			} // Loop 2/2 (Start/Stopping)

			if (bDebugLog) {
				String[] mainDebugEntries2 = new String[] {
						"ok2Start=" + boolDebug(totals.bOkToStartSeeding),
						"tFrcdCding=" + totals.forcedSeeding,
						"actvCDs=" + totals.activelyCDing,
						"tW8tingToCd=" + totals.waitingToSeed,
						"tDLing=" + totals.downloading,
						"actvDLs=" + totals.activelyDLing,
						"tW8tingToDL=" + totals.waitingToDL,
						"tCom=" + totals.complete,
						"tIncQd=" + totals.incompleteQueued,
						"mxCdrs=" + totals.maxSeeders,
						"tFP=" + totals.firstPriority,
						"maxT=" + totals.maxTorrents };
				printDebugChanges("<<process() ", mainDebugEntries, mainDebugEntries2,
						"", "", true, null);
			}
		} finally {

			this_mon.exit();
		}
	} // process()

	/**
	 * @param dlData
	 * @param vars 
	 * @param totals 
	 */
	private void handleInCompleteDownload(DefaultRankCalculator dlData,
			ProcessVars vars, TotalsStats totals) {
		Download download = dlData.dl;
		int state = download.getState();

		if (download.isForceStart()) {
			if (bDebugLog) {
				String s = "isForceStart.. rules skipped";
				log.log(download.getTorrent(), LoggerChannel.LT_INFORMATION, s);
				dlData.sTrace += s + "\n";
			}
			return;
		}

		// Don't mess with preparing torrents.  they could be in the 
		// middle of resume-data building, or file allocating.
		if (state == Download.ST_PREPARING) {
			vars.numWaitingOrDLing++;
			if (bDebugLog) {
				String s = "ST_PREPARING.. rules skipped. numW8tngorDLing="
						+ vars.numWaitingOrDLing;
				log.log(download.getTorrent(), LoggerChannel.LT_INFORMATION, s);
				dlData.sTrace += s + "\n";
			}
			return;
		}

		int maxDLs = 0;
		int DLmax = 0;
		if (totals.maxActive == 0) {
			maxDLs = maxDownloads;
		} else {
			DLmax = totals.stalledFPSeeders + totals.maxActive - totals.firstPriority
					- totals.forcedSeedingNonFP;
			maxDLs = (DLmax <= 0) ? 0 : maxDownloads - DLmax <= 0 ? maxDownloads
					: DLmax;
		}

		if (bDebugLog) {
			String s = ">> state=" + sStates.charAt(download.getState())
					+ ";shareRatio=" + download.getStats().getShareRatio()
					+ ";numW8tngorDLing=" + vars.numWaitingOrDLing + ";maxCDrs="
					+ totals.maxSeeders + ";forced=" + boolDebug(download.isForceStart())
					+ ";actvDLs=" + totals.activelyDLing + ";maxDLs=" + maxDLs
					+ ";ActDLing=" + boolDebug(dlData.getActivelyDownloading())
					+ ";isCmplt="+boolDebug(download.isComplete());
			log.log(download.getTorrent(), LoggerChannel.LT_INFORMATION, s);
			dlData.sTrace += s + "\n";
		}

		//    if (bDebugOn) {
		//      System.out.println( "maxActive: " + totals.maxActive + " / activeSeedingCount: " + totals.activeluCDing + " / maxDownloads: " + maxDownloads + " / maxDLs: " + maxDLs + " / DLmax: " + DLmax);
		//      System.out.println("totalFirstPriority: " + totals.firstPriority + " / totalFPStalledSeeders: " + totals.stalledFPSeeders + " / total0PeerSeeders: "  + totals.zeroPeerSeeders);	        	
		//    }

		if (state == Download.ST_READY || state == Download.ST_DOWNLOADING
				|| state == Download.ST_WAITING) {

			boolean bActivelyDownloading = dlData.getActivelyDownloading();

			// Stop torrent if over limit
			if ((maxDownloads != 0)
					&& (vars.numWaitingOrDLing >= maxDLs)
					&& ((bActivelyDownloading || state != Download.ST_DOWNLOADING) || (state == Download.ST_DOWNLOADING
							&& totals.maxActive != 0 && !bActivelyDownloading && totals.activelyCDing
							+ totals.activelyDLing >= totals.maxActive))) {
				try {
					if (bDebugLog) {
						String s = "   stopAndQueue: " + vars.numWaitingOrDLing
								+ " waiting or downloading, when limit is " + maxDownloads;
						log.log(download.getTorrent(), LoggerChannel.LT_INFORMATION, s);
						dlData.sTrace += s + "\n";
					}
					download.stopAndQueue();
					// reduce counts
					if (state == Download.ST_DOWNLOADING) {
						totals.downloading--;
						if (bActivelyDownloading)
							totals.activelyDLing--;
					} else {
						totals.waitingToDL--;
					}
					totals.maxSeeders = calcMaxSeeders(totals.activelyDLing
							+ totals.waitingToDL);
				} catch (Exception ignore) {
					/*ignore*/
				}

				state = download.getState();
			}
		}

		if (state == Download.ST_READY) {
			if ((maxDownloads == 0) || (totals.activelyDLing < maxDLs)) {
				try {
					if (bDebugLog) {
						String s = "   start: READY && activelyDLing (" + totals.activelyDLing
								+ ") < maxDLs (" + maxDownloads + ")";
						log.log(download.getTorrent(), LoggerChannel.LT_INFORMATION, s);
						dlData.sTrace += s + "\n";
					}
					download.start();

					// adjust counts
					totals.waitingToDL--;
					totals.activelyDLing++;
					totals.maxSeeders = calcMaxSeeders(totals.activelyDLing
							+ totals.waitingToDL);
				} catch (Exception ignore) {
					/*ignore*/
				}
				state = download.getState();
			}
		}

		if (state == Download.ST_QUEUED) {
			if ((maxDownloads == 0) || (vars.numWaitingOrDLing < maxDLs)) {
				try {
					if (bDebugLog) {
						String s = "   restart: QUEUED && numWaitingOrDLing ("
								+ vars.numWaitingOrDLing + ") < maxDLS (" + maxDLs + ")";
						log.log(LoggerChannel.LT_INFORMATION, s);
						dlData.sTrace += s + "\n";
					}
					download.restart();

					// increase counts
					totals.waitingToDL++;
					totals.maxSeeders = calcMaxSeeders(totals.activelyDLing
							+ totals.waitingToDL);
				} catch (Exception ignore) {/*ignore*/
				}
				state = download.getState();
			}
		}

		// must use fresh getActivelyDownloading() in case state changed to 
		// downloading
		if ((state == Download.ST_DOWNLOADING && dlData.getActivelyDownloading())
				|| state == Download.ST_READY || state == Download.ST_WAITING
				|| state == Download.ST_PREPARING) {
			vars.numWaitingOrDLing++;
		}

		if (bDebugLog) {
			String s = "<< state=" + sStates.charAt(download.getState())
					+ ";shareRatio=" + download.getStats().getShareRatio()
					+ ";numW8tngorDLing=" + vars.numWaitingOrDLing + ";maxCDrs="
					+ totals.maxSeeders + ";forced=" + boolDebug(download.isForceStart())
					+ ";actvDLs=" + totals.activelyDLing 
					+ ";ActDLing=" + boolDebug(dlData.getActivelyDownloading());
			log.log(download.getTorrent(), LoggerChannel.LT_INFORMATION, s);
			dlData.sTrace += s + "\n";
		}
	}

	/**
	 * Process Completed (Seeding) downloads, starting and stopping as needed
	 * 
	 * @param dlDataArray All download data (rank objects) we handle
	 * @param dlData Current download data (rank object) we are processing
	 * @param vars Running calculations
	 * @param totals Summary values used in logic
	 */
	private void handleCompletedDownload(DefaultRankCalculator[] dlDataArray,
			DefaultRankCalculator dlData, ProcessVars vars, TotalsStats totals) {
		Download download = dlData.dl;
		int state = download.getState();

		String[] debugEntries = null;
		String sDebugLine = "";
		// Queuing process:
		// 1) Torrent is Queued (Stopped)
		// 2) Slot becomes available
		// 3) Queued Torrent changes to Waiting
		// 4) Waiting Torrent changes to Ready
		// 5) Ready torrent changes to Seeding (with startDownload)
		// 6) Trigger stops Seeding torrent
		//    a) Queue Ranking drops
		//    b) User pressed stop
		//    c) other
		// 7) Seeding Torrent changes to Queued.  Go to step 1.

		if (!totals.bOkToStartSeeding)
			return;

		int numPeers = calcPeersNoUs(download);

		if (bDebugLog) {
			debugEntries = new String[] { "state=" + sStates.charAt(state),
					"shareR=" + download.getStats().getShareRatio(),
					"nWorCDing=" + vars.numWaitingOrSeeding,
					"nWorDLing=" + vars.numWaitingOrDLing,
					"sr=" + download.getSeedingRank(),
					"hgherQd=" + boolDebug(vars.higherQueued),
					"maxCDrs=" + totals.maxSeeders,
					"FP=" + boolDebug(dlData.isFirstPriority()),
					"nActCDing=" + totals.activelyCDing,
					"ActCDing=" + boolDebug(dlData.getActivelySeeding()) };
		}

		try {

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -