//------------------------------------------------------------- public void pieceHashedDelegate(object o, PieceHashedEventArgs e) //------------------------------------------------------------- { if (e != null && o != null) { TorrentManager torrentManager = (TorrentManager)o; if (torrentManager.State == TorrentState.Stopped) { return; } if (kobberLan != null && e.TorrentManager != null && e.TorrentManager.Torrent != null) { kobberLan.Invoke(new Action(() => { bool status = kobberLan.UpdateProgressBar(TorrentState.Hashing, (int)(e.Progress * 100.0), e.TorrentManager.Torrent.Name); // e.TorrentManager.State if (status == false) { torrentManager.PieceHashed -= pieceHashedDelegate; torrentManager.StopAsync(); Log.Get().Write("PieceHashed failed", Log.LogType.Error); } })); } } }
async Task Remove() { await manager.StopAsync(); await manager.Engine.Unregister(manager); parent.RemoveTorrentFromList(this); }
public override async Task CancelAsync() { if (_torrentManager == null) { return; } await _torrentManager.StopAsync(); await torrentEngine.RemoveAsync(_torrentManager); }
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { Torrent torrent = Torrent.Load(entry.FilePath + ".torrent"); // Create the manager which will download the torrent to savePath // using the default settings. TorrentManager manager = new TorrentManager(torrent, entry.downloadsPath, new TorrentSettings()); engine = new ClientEngine(); // Register the manager with the engine this.engine.Register(manager); // Begin the download. It is not necessary to call HashCheck on the manager // before starting the download. If a hash check has not been performed, the // manager will enter the Hashing state and perform a hash check before it // begins downloading. // If the torrent is fully downloaded already, calling 'Start' will place // the manager in the Seeding state. manager.StartAsync(); while (progressBar1.Value < 100) { BeginInvoke(new MethodInvoker(delegate { progressBar1.Value = (int)manager.Bitfield.PercentComplete; label2.Text = manager.Bitfield.PercentComplete.ToString() + "%"; })); System.Threading.Thread.Sleep(200); } BeginInvoke(new MethodInvoker(delegate { button1.Text = "Загружено"; })); manager.StopAsync(); engine.Dispose(); manager.Dispose(); }
private async void ToggleWillDownload() { if (WillDownload == true) { await TorrentClientAPI.engine.Register(Tmanager); await Tmanager.StartAsync(); } else { try { await Tmanager.StopAsync(); await TorrentClientAPI.engine.Unregister(Tmanager); } catch (Exception) { } } }
//------------------------------------------------------------- public void DownloadTorrent(MonoTorrent.Torrent torrent) //------------------------------------------------------------- { if (torrent == null) { Log.Get().Write("torrent is null", Log.LogType.Error); } if (torrent.AnnounceUrls.Count <= 0) { Log.Get().Write("torrent missing announce", Log.LogType.Error); } string path = Helper.GetDirection(); Log.Get().Write("Client downloading files torrent: " + torrent.Name); if (!Helper.IsPortAvailable(CLIENT_PORT)) { Log.Get().Write("Failed starting client downloading file on port: " + CLIENT_PORT + " Port in use", Log.LogType.Error); } if (settings == null || engine == null) { //Settings settings = new EngineSettings(); settings.AllowedEncryption = EncryptionTypes.All; settings.PreferEncryption = true; settings.SavePath = path; settings.ListenPort = CLIENT_PORT; //Create client engine engine = new ClientEngine(settings); } //Check if torrent exist (reStarting a torrent) var torrentManagersResult = torrentManagers.Where(t => t.Torrent.Name.Equals(torrent.Name)).ToList(); if (torrentManagersResult.Count >= 1) { Log.Get().Write("ReStarting torrent: " + torrent.Name); torrentManagersResult.FirstOrDefault().StartAsync(); } else //New torrent { Log.Get().Write("Preparing new torrent: " + torrent.Name); var torrentSettings = new TorrentSettings(); torrentSettings.AllowDht = false; torrentSettings.AllowPeerExchange = true; TorrentManager torrentManager = new TorrentManager(torrent, path, torrentSettings); //Add logning torrentManager.ConnectionAttemptFailed += delegate(object o, ConnectionAttemptFailedEventArgs e) { Log.Get().Write("TorrentManager connectionAttemptFailed reason:" + e.Reason.ToString(), Log.LogType.Error); }; torrentManager.PeerConnected += delegate(object o, PeerConnectedEventArgs e) { Log.Get().Write("TorrentManager PeerConnected"); }; torrentManager.PeerDisconnected += delegate(object o, PeerDisconnectedEventArgs e) { Log.Get().Write("TorrentManager PeerDisconnected"); }; torrentManager.PeersFound += delegate(object o, PeersAddedEventArgs e) { Log.Get().Write("TorrentManager PeersAdded"); }; torrentManager.PieceHashed += pieceHashedDelegate; torrentManager.TorrentStateChanged += delegate(object o, TorrentStateChangedEventArgs e) { Log.Get().Write("TorrentManager TorrentStateChanged, oldstate: " + e.OldState + " , newState: " + e.NewState); if (kobberLan != null) { kobberLan.Invoke(new Action(() => { bool status = kobberLan.UpdateProgressBar(e.NewState, (int)(torrentManager.Progress), torrentManager.Torrent.Name); if (status == false) { torrentManager.StopAsync(); if (e.NewState != MonoTorrent.Client.TorrentState.Stopped && e.NewState != MonoTorrent.Client.TorrentState.Stopping) { Log.Get().Write("TorrentHandler failed", Log.LogType.Error); } } })); } }; engine.CriticalException += delegate(object o, CriticalExceptionEventArgs e) { Log.Get().Write("TorrentEngine CriticalException", Log.LogType.Error); }; engine.StatsUpdate += delegate(object o, StatsUpdateEventArgs e) { if (o.GetType() == typeof(MonoTorrent.Client.ClientEngine)) { ClientEngine clientEngine = (ClientEngine)o; Log.Get().Write("TorrentEngine Statsupdate running: " + clientEngine.IsRunning + " , torrent Seeds: " + torrentManager.Peers.Seeds + ", Leech: " + torrentManager.Peers.Leechs + " , progress: " + torrentManager.Progress ); if (kobberLan != null && kobberLan.Disposing == false) { kobberLan.Invoke(new Action(() => { bool status = kobberLan.UpdateProgressBar(torrentManager.State, (int)(torrentManager.Progress), torrentManager.Torrent.Name); if (status == false) { torrentManager.StopAsync(); if (torrentManager.State != MonoTorrent.Client.TorrentState.Stopped && torrentManager.State != MonoTorrent.Client.TorrentState.Stopping) { Log.Get().Write("TorrentHandler failed", Log.LogType.Error); } } })); } } else { Log.Get().Write("TorrentEngine Statsupdate: Unknown", Log.LogType.Error); } }; //Start downloading engine.Register(torrentManager); engine.StartAllAsync(); //Add torrent to list torrentManagers.Add(torrentManager); } }
public async Task <ImmutableList <string> > Download(string url, List <string>?potentialArchives, bool enablePortForwarding, string outputPath, CancellationToken cancellationToken) { var stopWatch = Stopwatch.StartNew(); var paddingFolder = _fileSystem.Path.Combine(outputPath, ".____padding_file"); var doesPaddingFolderExistToStart = _fileSystem.Directory.Exists(paddingFolder); var progressBar = _console.Progress() .AutoClear(false) .Columns(new ProgressColumn[] { new SpinnerColumn { CompletedText = Emoji.Known.CheckMark }, new DownloadedColumnExtended(), new TaskDescriptionColumn(), new TorrentProgressBarColumn(), new PercentageColumn(), new TransferSpeedColumn(), new RemainingTimeColumn() }); ImmutableList <TorrentFile>?downloadedFiles = null; await progressBar.StartAsync(async ctx => { _console.WriteLine("Loading torrent..."); var httpClient = new HttpClient(); var torrentContents = await httpClient.GetByteArrayAsync(url, cancellationToken); var settings = new EngineSettings { AllowedEncryption = EncryptionTypes.All, SavePath = outputPath, MaximumHalfOpenConnections = 16 }; _console.WriteLine("Initializing BitTorrent engine..."); var engine = new ClientEngine(settings); if (enablePortForwarding) { _console.WriteLine("Attempting to forward ports"); await engine.EnablePortForwardingAsync(cancellationToken); } var torrent = await Torrent.LoadAsync(torrentContents); if (potentialArchives != null) { foreach (var torrentFile in torrent.Files) { if (!potentialArchives.Contains(torrentFile.Path)) { torrentFile.Priority = Priority.DoNotDownload; } } } var manager = new TorrentManager( torrent, outputPath, new TorrentSettings { MaximumConnections = 250 }, string.Empty); await engine.Register(manager); await engine.StartAll(); downloadedFiles = manager.Torrent.Files .Where(i => i.Priority != Priority.DoNotDownload).ToImmutableList(); var fileTasks = downloadedFiles .ToDictionary( i => i.Path, file => ctx.AddTask(file.Path, new ProgressTaskSettings { MaxValue = file.Length, AutoStart = false }) ); while (manager.State != TorrentState.Stopped && manager.State != TorrentState.Seeding) { foreach (var torrentFile in downloadedFiles) { var progressTask = fileTasks[torrentFile.Path]; if (torrentFile.BytesDownloaded > 0 && progressTask.IsStarted == false) { progressTask.StartTask(); } progressTask.Increment(torrentFile.BytesDownloaded - progressTask.Value); progressTask.State.Update <BitSmuggler>("torrentBits", _ => new BitSmuggler(torrentFile.BitField)); } await Task.Delay(100, cancellationToken); } await manager.StopAsync(); await engine.StopAllAsync(); try { // the stackoverflow torrent files, and I think all of archive.org // seem to have these padding files that sneak into the download even // if they aren't included in the file list. not quite sure how to prevent that // so I'm gonna delete them after the fact I guess if (!doesPaddingFolderExistToStart && _fileSystem.Directory.Exists(paddingFolder)) { _fileSystem.Directory.Delete(paddingFolder, true); } } catch { /* swallow */ } foreach (var progressTask in fileTasks) { progressTask.Value.StopTask(); } }); stopWatch.Stop(); _console.MarkupLine($"Download complete in [blue]{stopWatch.Elapsed.Humanize()}[/]."); return(downloadedFiles?.Select(i => _fileSystem.Path.Combine(outputPath, i.Path)).ToImmutableList() ?? ImmutableList <string> .Empty); }
public async Task Stop() { await MonoTorrentManager.StopAsync(); }