protected string Add(Torrent torrent, string outputDirectoryPath) { // Create the torrent manager. var torrentManager = new TorrentManager(torrent, outputDirectoryPath, DefaultTorrentSettings, ""); // Setup fast resume. if (FastResume.ContainsKey(torrent.InfoHash.ToHex())) { torrentManager.LoadFastResume(new FastResume((BEncodedDictionary)FastResume [torrent.InfoHash.ToHex()])); } // Add to mappings cache. TorrentMappingsCache.RemoveAll(tmc => tmc.InfoHash == torrent.InfoHash.ToString()); TorrentMappingsCache.Add(new TorrentMapping { InfoHash = torrent.InfoHash.ToString(), OutputDirectoryPath = outputDirectoryPath }); TorrentMappingsCache.Save(); // Register and start. Engine.Register(torrentManager); torrentManager.Start(); // Return Id. return(torrentManager.InfoHash.ToString()); }
public void AddTorrent(string pathToTorrentFile) { Messenger.Default.Send(new AddTorrentShowDialog((dialogResult) => { if (dialogResult == true) { ViewModelLocator locator = new ViewModelLocator(); var addTorrentViewModel = locator.AddTorrent; TorrentManager manager = new TorrentManager(addTorrentViewModel.Torrent, addTorrentViewModel.PathToFolder, tSettings); if (!engine.Contains(manager.InfoHash)) { saveLoadManager.Add(manager); engine.Register(manager); manager.Start(); TorrentManagerWrapper wrapper = new TorrentManagerWrapper(manager); Torrents.Add(wrapper); } } }, pathToTorrentFile)); }
public void NoAnnouncesTest() { rig.TorrentDict.Remove("announce-list"); rig.TorrentDict.Remove("announce"); Torrent t = Torrent.Load(rig.TorrentDict); rig.Engine.Unregister(rig.Manager); TorrentManager manager = new TorrentManager(t, "", new TorrentSettings()); rig.Engine.Register(manager); AutoResetEvent handle = new AutoResetEvent(false); manager.TorrentStateChanged += delegate(object o, TorrentStateChangedEventArgs e) { if (e.NewState == TorrentState.Downloading || e.NewState == TorrentState.Stopped) { handle.Set(); } }; manager.Start(); handle.WaitOne(); System.Threading.Thread.Sleep(1000); manager.Stop(); Assert.IsTrue(handle.WaitOne(10000, true), "#1"); Assert.IsTrue(manager.TrackerManager.Announce().WaitOne(10000, true), "#2");; }
public void Start() { TM.Start(); foreach (var T in GetTracker()) { //TM.TrackerManager.Announce(T); } }
public void Start() { if (!engine.IsRunning) { engine.StartAll(); } manager.Start(); }
private static void Downloader(string torrentFilePath, string downloadFolderPath) { Torrent torrent = Torrent.Load(torrentFilePath); //управления одним торрентом ClientEngine engine = new ClientEngine(new EngineSettings()); //настройки самого движка нашего клиента, для начала пренебрегая этими настройками. TorrentManager manager = new TorrentManager(torrent, downloadFolderPath, new TorrentSettings()); //осуществления контроля и управления за всеми торрентами engine.Register(manager); //отслеживание движком нашего менеджера manager.Start(); //начала загрузки файлов }
static void Main(string[] args) { var manager = new TorrentManager( "magnet:?xt=urn:btih:TJM7HROVMEEQNACMMY6JYVCQ5VW2RIK5&tr=http://nyaa.tracker.wf:7777/announce&tr=udp://tracker.coppersurfer.tk:6969/announce&tr=udp://tracker.internetwarriors.net:1337/announce&tr=udp://tracker.leechersparadise.org:6969/announce&tr=udp://tracker.opentrackr.org:1337/announce&tr=udp://open.stealth.si:80/announce&tr=udp://p4p.arenabg.com:1337/announce&tr=udp://mgtracker.org:6969/announce&tr=udp://tracker.tiny-vps.com:6969/announce&tr=udp://peerfect.org:6969/announce&tr=http://share.camoe.cn:8080/announce&tr=http://t.nyaatracker.com:80/announce&tr=https://open.kickasstracker.com:443/announce", Path.Combine(Directory.GetCurrentDirectory(), "Downloads")); manager.Start().Wait(); Thread.Sleep(1000000); manager.ShutDown().Wait(); }
public void AddTorrents(IEnumerable<IFileContainer> files) { foreach (var file in files) { var torrent = Torrent.Load(file.Content); var manager = new TorrentManager(torrent, downloadsDirectory, new TorrentSettings()); this.engine.Register(manager); manager.Start(); } }
public override void ViewDidLoad() { base.ViewDidLoad(); if (manager == null) { return; } Update(); tableView.DataSource = this; tableView.Delegate = this; Start.Clicked += delegate { manager.Start(); Update(); }; Pause.Clicked += delegate { manager.Pause(); Update(); }; Remove.Clicked += delegate { var message = manager.HasMetadata ? "Are you sure to remove " + manager.Torrent.Name + " torrent?" : "Are you sure to remove this magnet torrent?"; var actionController = UIAlertController.Create(null, message, UIAlertControllerStyle.ActionSheet); var removeAll = UIAlertAction.Create("Yes and remove data", UIAlertActionStyle.Destructive, delegate { if (manager.State == TorrentState.Stopped) { Manager.Singletone.UnregisterManager(manager); } else { manager.TorrentStateChanged += (sender, e) => { if (e.NewState == TorrentState.Stopped) { Manager.Singletone.UnregisterManager(manager); } }; manager.Stop(); } Manager.Singletone.managers.Remove(manager); Directory.Delete(Path.Combine(Manager.RootFolder, manager.Torrent.Name), true); File.Delete(manager.Torrent.TorrentPath); if (UIApplication.SharedApplication.KeyWindow.RootViewController is UISplitViewController splitController) { if (splitController.Collapsed) { (splitController.ViewControllers[0] as UINavigationController).PopViewController(true); } splitController.ShowDetailViewController(Utils.CreateEmptyViewController(), this); } });
/// <summary> /// Adds the file to download. This method returns when the torrent is /// added and doesn't wait for the download to complete. /// </summary> /// <param name="torrent">The torrent.</param> /// <param name="savePath">The save path.</param> public void StartDownloadingFile(Torrent torrent, string savePath, int lastPieceInProfile) { TorrentSettings torrentDefaults = new TorrentSettings(4, 150, 0, 0); var tm = new TorrentManager(torrent, savePath, torrentDefaults, "", lastPieceInProfile); // There is no need to scrape since we manage the tracker. tm.TrackerManager.CurrentTracker.CanScrape = false; _clientEngine.Register(tm); tm.TrackerManager.CurrentTracker.AnnounceComplete += new EventHandler <AnnounceResponseEventArgs>( TorrentEventHandlers.HandleAnnounceComplete); tm.TrackerManager.CurrentTracker.ScrapeComplete += delegate(object o, ScrapeResponseEventArgs e) { logger.DebugFormat("Scrape completed. Successful={0}, Tracker={1}", e.Successful, e.Tracker.Uri); }; tm.TorrentStateChanged += new EventHandler <TorrentStateChangedEventArgs>( TorrentEventHandlers.HandleTorrentStateChanged); tm.PieceHashed += new EventHandler <PieceHashedEventArgs>( TorrentEventHandlers.HandlePieceHashed); tm.PeerConnected += delegate(object o, PeerConnectionEventArgs e) { // Only log three connections. if (e.TorrentManager.OpenConnections < 4) { logger.DebugFormat( "Peer ({0}) Connected. Currently {1} open connection.", e.PeerID.Uri, e.TorrentManager.OpenConnections); } }; tm.PieceManager.BlockReceived += delegate(object o, BlockEventArgs e) { logger.DebugFormat("Block {0} from piece {1} is received.", e.Block.StartOffset / Piece.BlockSize, e.Piece.Index); }; // We really only deal with one file. foreach (var file in tm.Torrent.Files) { _torrentManagerTable[file.FullPath] = tm; } tm.Start(); logger.DebugFormat( "Starting to download torrent: {0}. Torrent manager started.", tm.Torrent.Name); }
/// <summary> /// Add torrent into my torrent list and return success code. /// </summary> /// <param name="fileName">filename of torrent</param> /// <param name="name">name to export as excel document</param> /// <param name="torrent">torrent object</param> /// <returns>0: success, 1: duplicated torrent, 2: duplicated name, 3: unexpected error</returns> public int AddTorrent(string fileName, string name, Torrent torrent) { int maxId = -1; // check validation foreach (TorrentModel model in torrentModels) { if (model.FileName.Equals(fileName)) { return(1); } if (model.TorrentManager.Torrent.InfoHash.Equals(torrent.InfoHash)) { return(1); } if (model.Name.Equals(name)) { return(2); } if (model.Id > maxId) { maxId = model.Id; } } // When any preprocessing has been completed, you create a TorrentManager // which you then register with the engine. TorrentManager manager = new TorrentManager(torrent, downloadsPath, torrentDefaults); //if(fastResume.ContainsKey(torrent.InfoHash.ToHex())) // remove fast resume //{ // remove fast resume // manager.LoadFastResume(new FastResume((BEncodedDictionary)fastResume[torrent.InfoHash.ToHex()])); // remove fast resume //} // remove fast resume engine.Register(manager); manager.PeersFound += new EventHandler <PeersAddedEventArgs>(manager_PeersFound); // Store the torrent manager in our list so we can access it later TorrentModel newModel = new TorrentModel { FileName = fileName, Name = name, TorrentManager = manager, Id = maxId + 1 }; torrentModels.Add(newModel); // Start the torrentmanager. The file will then hash (if required) and begin downloading/seeding manager.Start(); models_Changed(); return(0); }
private static void StartDownload(ClientEngine clientEngine, TorrentSettings torrentDefaultSettings) { string baseDir = Path.Combine(Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.Personal), "var"), "MonoTorrent"); Debug.WriteLine(string.Format("Base Dir is {0}", baseDir)); var torrent = Torrent.Load(Path.Combine(baseDir, TorrentFileName)); var torrentManager = new TorrentManager(torrent, Path.Combine(baseDir, "Downloads"), torrentDefaultSettings, "", -1); clientEngine.Register(torrentManager); torrentManager.Start(); Console.Read(); }
public void AddTorrent(string torrentUrl) { // TODO: This temp file stuff is a bit dodgy, but we can leave it until we start to sort out making the settings configurable var tempFile = Path.GetTempFileName(); using (WebClient client = new WebClient()) { client.DownloadFile(torrentUrl, tempFile); } Torrent torrent = Torrent.Load(tempFile); TorrentManager manager = new TorrentManager(torrent, downloadsDirectory, new TorrentSettings()); engine.Register(manager); manager.Start(); }
private static void StartDownload(ClientEngine clientEngine, TorrentSettings torrentDefaultSettings) { string baseDir = Path.Combine(Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.Personal), "var"), "MonoTorrent"); Debug.WriteLine(string.Format("Base Dir is {0}", baseDir)); var torrent = Torrent.Load(Path.Combine(baseDir, TorrentFileName)); var torrentManager = new TorrentManager(torrent, Path.Combine(baseDir, "Downloads"), torrentDefaultSettings, "", -1); clientEngine.Register(torrentManager); torrentManager.Start(); Console.Read(); }
private void initTorrent() { try { torrent = Torrent.Load(torrentFile); } catch {} // remove non existing trackers List <RawTrackerTier> toRemove = new List <RawTrackerTier>(); torrent.AnnounceUrls.ToList().ForEach(delegate(RawTrackerTier t) { t.ToList().ForEach(delegate(String s) { try { Uri result; Uri.TryCreate(s, UriKind.Absolute, out result); Dns.GetHostAddresses(result.Host); } catch { toRemove.Add(t); } }); }); toRemove.ForEach(delegate(RawTrackerTier t) { torrent.AnnounceUrls.Remove(t); }); torrentSettings = new TorrentSettings(4, 100, 600 * 1024, 60 * 1024, false); torrentSettings.EnablePeerExchange = true; torrentSettings.UseDht = true; torrentManager = new TorrentManager(torrent, savePath, torrentSettings, savePath); usedFastResume = "false"; if (fastResume != null) { if (torrentManager.InfoHash == fastResume.Infohash) { torrentManager.LoadFastResume(fastResume); usedFastResume = "true"; } } clientEngine.Register(torrentManager); torrentManager.Start(); }
public void StartDownload() { if (CurrentState == State.Streaming) { return; } if (TorrentManager.Torrent != null) { TorrentManager_TorrentStateChanged(null, new TorrentStateChangedEventArgs(TorrentManager, TorrentState.Metadata, TorrentState.Hashing)); } else { CurrentState = State.Metadata; } TorrentManager.Start(); }
private void OnStartItemActivated(object sender, EventArgs args) { if (selectedTorrent.State == TorrentState.Seeding || selectedTorrent.State == TorrentState.Downloading) { try{ selectedTorrent.Pause(); } catch (Exception) { logger.Warn("Unable to pause " + selectedTorrent.Torrent.Name); } } else { try{ selectedTorrent.Start(); }catch (Exception) { } logger.Warn("Unable to start " + selectedTorrent.Torrent.Name); } }
internal void SeedTorrents(List <string> torrentPaths) { this.engineState = EngineState.Seeding; this.StartDht(this.engine, Properties.Settings.Default.listenPort); this.managers.Clear(); this.torrents.Clear(); this.torrentPaths = torrentPaths; string fastResumeFile = Path.Combine(this.parent.localAppDataFolder, "fastresume.data"); BEncodedDictionary fastResume; try { fastResume = BEncodedValue.Decode <BEncodedDictionary>(File.ReadAllBytes(fastResumeFile)); } catch { fastResume = new BEncodedDictionary(); } foreach (string filePath in torrentPaths) { Torrent torrent = null; try { torrent = Torrent.Load(filePath); } catch (Exception e) { Console.WriteLine(e); debug(e.ToString()); continue; } this.torrents.Add(torrent); Console.WriteLine(Properties.Settings.Default.seedRate); TorrentSettings settings = new TorrentSettings(10, 50, 0, this.engine.Settings.GlobalMaxUploadSpeed); TorrentManager manager = new TorrentManager(torrent, engine.Settings.SavePath, settings); if (fastResume.ContainsKey(torrent.InfoHash.ToHex())) { manager.LoadFastResume(new FastResume((BEncodedDictionary)fastResume[torrent.InfoHash.ToHex()])); } this.managers.Add(manager); this.engine.Register(manager); manager.PeerConnected += manager_PeerConnected; manager.TorrentStateChanged += checkIncomplete; manager.TrackerManager.Announce(); manager.Start(); } //this.engine.StartAll(); }
static void StartDownload(ClientEngine clientEngine, TorrentSettings torrentDefaultSettings) { string baseDir = Path.Combine(Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.Personal), "var"), "MonoTorrent"); Debug.WriteLine(string.Format("Base Dir is {0}", baseDir)); var torrent = Torrent.Load(Path.Combine(baseDir, TorrentFileName)); (torrent.Files[0] as TorrentFile).Priority = Priority.Highest; (torrent.Files[1] as TorrentFile).Priority = Priority.DoNotDownload; (torrent.Files[2] as TorrentFile).Priority = Priority.DoNotDownload; long targetDownloadSize = (torrent.Files[0] as TorrentFile).Length; long totalSize = torrent.Size; double targetPercentage = (double)targetDownloadSize / totalSize; Debug.WriteLine(string.Format("Intend to download {0}/{1} = {2}", targetDownloadSize, totalSize, targetPercentage)); var torrentManager = new TorrentManager(torrent, Path.Combine(baseDir, "Downloads"), torrentDefaultSettings); var progressMonitor = new PartialDownloadProgressMonitor(torrentManager); progressMonitor.FileDownloaded += new EventHandler <FileDownloadedEventArgs>(progressMonitor_FileDownloaded); clientEngine.Register(torrentManager); torrentManager.TorrentStateChanged += new EventHandler <TorrentStateChangedEventArgs>(torrentManager_TorrentStateChanged); // Start downloading torrentManager.Start(); // Keep running while the torrent isn't stopped or paused. while (torrentManager.State != TorrentState.Stopped && torrentManager.State != TorrentState.Paused) { Debug.WriteLine(string.Format("Progress: {0}", torrentManager.Progress)); System.Threading.Thread.Sleep(2000); } Console.Read(); }
private bool DownloadTorrent(string path) { try { ClientEngine engine = new ClientEngine(new EngineSettings()); MonoTorrent.Common.Torrent torrent = MonoTorrent.Common.Torrent.Load(@"C:\WexflowTesting\Torrent\sample.torrent"); TorrentManager torrentManager = new TorrentManager(torrent, @"C:\WexflowTesting\Torrent\", new TorrentSettings()); engine.Register(torrentManager); torrentManager.Start(); // Keep running while the torrent isn't stopped or paused. while (torrentManager.State != TorrentState.Stopped && torrentManager.State != TorrentState.Paused) { Thread.Sleep(1000); if (torrentManager.Progress == 100.0) { // If we want to stop a torrent, or the engine for whatever reason, we call engine.StopAll() torrentManager.Stop(); engine.StopAll(); break; } } InfoFormat("The torrent {0} download succeeded.", path); return(true); } catch (ThreadAbortException) { throw; } catch (Exception e) { ErrorFormat("An error occured while downloading the torrent {0}: {1}", path, e.Message); return(false); } }
/// <summary> /// Запускает загрузку /// </summary> /// <param name="TorrentPath">Путь к торрент файлу</param> /// <param name="DownloadPath">Путь загрузки</param> public void Start(string TorrentPath, string DownloadPath, DownloadModel downloadModel) { //Вспомогательный класс Top10Listener listener = new Top10Listener(10); TorrentManager _manager; Torrent _torrent = null; EngineSettings _engineSettings = new EngineSettings() { SavePath = DownloadPath, ListenPort = 31337 }; TorrentSettings _torrentDef = new TorrentSettings(5, 100, 0, 0); //Движок, реализующий функции закачки ClientEngine _engine = new ClientEngine(_engineSettings); BEncodedDictionary _fastResume; _fastResume = new BEncodedDictionary(); try { _torrent = Torrent.Load(TorrentPath + downloadModel.NameFile); } catch { _engine.Dispose(); } try { downloadModel.Name = _torrent.Name; _manager = new TorrentManager(_torrent, DownloadPath, _torrentDef); _engine.Register(_manager); _manager.TorrentStateChanged += delegate(object o, TorrentStateChangedEventArgs e) { lock (listener) listener.WriteLine("Last status: " + e.OldState.ToString() + " Current status: " + e.NewState.ToString()); }; foreach (TrackerTier ttier in _manager.TrackerManager.TrackerTiers) { foreach (Tracker tr in ttier.GetTrackers()) { tr.AnnounceComplete += delegate(object sender, AnnounceResponseEventArgs e) { listener.WriteLine(string.Format($"{e.Successful}: {e.Tracker}")); }; } } _manager.Start(); int i = 0; bool _running = true; StringBuilder _stringBuilder = new StringBuilder(1024); while (_running) { if ((i++) % 10 == 0) { if (_manager.State == TorrentState.Stopped) { _running = false; } downloadModel.Percent = Convert.ToInt16(_manager.Progress); downloadModel.Upload = _manager.Peers.Seeds; downloadModel.Download = _manager.Peers.Leechs; var Status = _manager.State; } } } catch { return; } }
public override void DetailsReceived() { if (isCanceled) { return; } // Restart transfer. if (manager != null) { manager.Start(); return; } if (file.Pieces.Length == 0) { throw new InvalidOperationException("No pieces"); } LoggingService.LogDebug("{0}: Calling Start:\n{1}", Environment.TickCount, Environment.StackTrace); if (file.Pieces.Length == 0) { throw new InvalidOperationException("No pieces"); } if (string.IsNullOrEmpty(file.InfoHash)) { throw new InvalidOperationException("No info hash"); } BitTorrentFileTransferProvider provider = (BitTorrentFileTransferProvider)Core.FileTransferManager.Provider; Torrent torrent = BitTorrentFileTransfer.CreateTorrent(file); #if RIDICULOUS_DEBUG_OUTPUT // Dump the hashes to the screen for (int i=0; i < torrent.Pieces.Count; i++) LoggingService.LogDebug(string.Format("{0}) {1}", i, BitConverter.ToString(torrent.Pieces.ReadHash(i)))); #endif manager = provider.CreateTorrentManager(torrent, file); manager.Settings.MaxUploadSpeed = maxUploadSpeed; manager.Settings.MaxDownloadSpeed = maxDownloadSpeed; manager.PeersFound += manager_PeersFound; manager.PieceHashed += manager_PieceHashed; manager.TorrentStateChanged += manager_TorrentStateChanged; manager.PeerConnected += new EventHandler<PeerConnectionEventArgs>(manager_PeerConnected); manager.PeerDisconnected += new EventHandler<PeerConnectionEventArgs>(manager_PeerDisconnected); #if RIDICULOUS_DEBUG_OUTPUT LoggingService.LogDebug("Engine ID: {0}", provider.Engine.PeerId); #endif manager.Start(); if (file is LocalFile) { foreach (BitTorrentFileTransferPeer peer in this.peers) { peer.Network.SendFileDetails(peer.Node, (LocalFile)file); } } }
public void Start() { manager.Start(); }
public void TorrentControl(int selected) { Dialog d = new Dialog(60, 8, "Torrent Control"); TorrentManager item = items [selected]; d.Add(new TrimLabel(1, 1, 60 - 6, item.Torrent.Name)); bool stopped = item.State == TorrentState.Stopped; Button bstartstop = new Button(stopped ? "Start" : "Stop"); bstartstop.Clicked += delegate { if (stopped) { item.Start(); } else { item.Stop(); } d.Running = false; }; d.AddButton(bstartstop); // Later, when we hook it up, look up the state bool paused = item.State == TorrentState.Paused; Button br = new Button(paused ? "Resume" : "Pause"); br.Clicked += delegate { if (paused) { item.Start(); } else { item.Pause(); } d.Running = false; }; d.AddButton(br); Button bd = new Button("Delete"); bd.Clicked += delegate { Application.Error("Not Implemented", "I have not implemented delete yet"); d.Running = false; }; d.AddButton(bd); Button bmap = new Button("Map"); bmap.Clicked += delegate { Application.Error("Not Implemented", "I have not implemented map yet"); d.Running = false; }; d.AddButton(bmap); Button bcancel = new Button("Cancel"); bcancel.Clicked += delegate { d.Running = false; }; Application.Run(d); UpdateStatus(); }
public void NoAnnouncesTest() { rig.TorrentDict.Remove("announce-list"); rig.TorrentDict.Remove("announce"); Torrent t = Torrent.Load(rig.TorrentDict); rig.Engine.Unregister(rig.Manager); TorrentManager manager = new TorrentManager(t, "", new TorrentSettings()); rig.Engine.Register(manager); AutoResetEvent handle = new AutoResetEvent(false); manager.TorrentStateChanged += delegate(object o, TorrentStateChangedEventArgs e) { if (e.NewState == TorrentState.Downloading || e.NewState == TorrentState.Stopped) handle.Set(); }; manager.Start(); handle.WaitOne(); System.Threading.Thread.Sleep(1000); manager.Stop(); Assert.IsTrue(handle.WaitOne(10000, true), "#1"); Assert.IsTrue(manager.TrackerManager.Announce().WaitOne(10000, true), "#2"); ; }
public async void tor() { var port = 6881; var dhtPort = 15000; // Use Universal.Nat to enable upnp port mapping /* var natManager = new NatManager(port); natManager.Start();*/ var picker = new FileOpenPicker(); picker.FileTypeFilter.Add(".torrent"); var file = await picker.PickSingleFileAsync(); var stream = await file.OpenStreamForReadAsync(); var torrent = Universal.Torrent.Common.Torrent.Load(stream); if (torrent != null) { var engineSettings = new EngineSettings(savePath, port) { PreferEncryption = true, AllowedEncryption = EncryptionTypes.All }; // Create the default settings which a torrent will have. // 4 Upload slots - a good ratio is one slot per 5kB of upload speed // 50 open connections - should never really need to be changed // Unlimited download speed - valid range from 0 -> int.Max // Unlimited upload speed - valid range from 0 -> int.Max var torrentDefaults = new TorrentSettings(4, 150, 0, 0) { UseDht = true, EnablePeerExchange = true }; // Create an instance of the engine. var engine = new ClientEngine(engineSettings); //engine.ChangeListenEndpoint(new IPEndPoint(IPAddress.Any, port)); //var dhtListner = new DhtListener(new IPEndPoint(IPAddress.Any, dhtPort)); //var dht = new DhtEngine(dhtListner); //engine.RegisterDht(dht); //dhtListner.Start(); //engine.DhtEngine.Start(); // When any preprocessing has been completed, you create a TorrentManager // which you then register with the engine. var manager = new TorrentManager(torrent, ApplicationData.Current.LocalFolder, torrentDefaults); engine.Register(manager); // Every time a piece is hashed, this is fired. manager.PieceHashed += delegate (object o, PieceHashedEventArgs e) { //Debug.WriteLine("Piece Hashed: {0} - {1}", e.PieceIndex, e.HashPassed ? "Pass" : "Fail"); }; // Every time the state changes (Stopped -> Seeding -> Downloading -> Hashing) this is fired manager.TorrentStateChanged += delegate (object o, TorrentStateChangedEventArgs e) { //Debug.WriteLine("OldState: " + e.OldState + " NewState: " + e.NewState); }; // Every time the tracker's state changes, this is fired foreach (var t in manager.TrackerManager.SelectMany(tier => tier.Trackers)) { t.AnnounceComplete += delegate (object sender, AnnounceResponseEventArgs e) { // Debug.WriteLine("{0}: {1}", e.Successful, e.Tracker); }; } // Start the torrentmanager. The file will then hash (if required) and begin downloading/seeding manager.Start(); var dispatcher = Window.Current.Dispatcher; engine.StatsUpdate += async (sender, args) => { await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { //TextBlock.Text = $"{manager.Peers.Seeds} seeds / {manager.Peers.Leechs} leechs / {manager.Progress} %"; }); }; } }
/// <summary> /// Adds the file to download. This method returns when the torrent is /// added and doesn't wait for the download to complete. /// </summary> /// <param name="torrent">The torrent.</param> /// <param name="savePath">The save path.</param> public void StartDownloadingFile(Torrent torrent, string savePath, int lastPieceInProfile) { TorrentSettings torrentDefaults = new TorrentSettings(4, 150, 0, 0); var tm = new TorrentManager(torrent, savePath, torrentDefaults, "", lastPieceInProfile); // There is no need to scrape since we manage the tracker. tm.TrackerManager.CurrentTracker.CanScrape = false; _clientEngine.Register(tm); tm.TrackerManager.CurrentTracker.AnnounceComplete += new EventHandler<AnnounceResponseEventArgs>( TorrentEventHandlers.HandleAnnounceComplete); tm.TrackerManager.CurrentTracker.ScrapeComplete += delegate(object o, ScrapeResponseEventArgs e) { logger.DebugFormat("Scrape completed. Successful={0}, Tracker={1}", e.Successful, e.Tracker.Uri); }; tm.TorrentStateChanged += new EventHandler<TorrentStateChangedEventArgs>( TorrentEventHandlers.HandleTorrentStateChanged); tm.PieceHashed += new EventHandler<PieceHashedEventArgs>( TorrentEventHandlers.HandlePieceHashed); tm.PeerConnected += delegate(object o, PeerConnectionEventArgs e) { // Only log three connections. if (e.TorrentManager.OpenConnections < 4) { logger.DebugFormat( "Peer ({0}) Connected. Currently {1} open connection.", e.PeerID.Uri, e.TorrentManager.OpenConnections); } }; tm.PieceManager.BlockReceived += delegate(object o, BlockEventArgs e) { logger.DebugFormat("Block {0} from piece {1} is received.", e.Block.StartOffset / Piece.BlockSize, e.Piece.Index); }; // We really only deal with one file. foreach (var file in tm.Torrent.Files) { _torrentManagerTable[file.FullPath] = tm; } tm.Start(); logger.DebugFormat( "Starting to download torrent: {0}. Torrent manager started.", tm.Torrent.Name); }
public override void DetailsReceived() { if (isCanceled) { return; } // Restart transfer. if (manager != null) { manager.Start(); return; } if (file.Pieces.Length == 0) { throw new InvalidOperationException("No pieces"); } LoggingService.LogDebug("{0}: Calling Start:\n{1}", Environment.TickCount, Environment.StackTrace); if (file.Pieces.Length == 0) { throw new InvalidOperationException("No pieces"); } if (string.IsNullOrEmpty(file.InfoHash)) { throw new InvalidOperationException("No info hash"); } var provider = (BitTorrentFileTransferProvider)core.FileTransferManager.Provider; var torrent = CreateTorrent(file); #if RIDICULOUS_DEBUG_OUTPUT // Dump the hashes to the screen for (int i = 0; i < torrent.Pieces.Count; i++) { LoggingService.LogDebug(string.Format("{0}) {1}", i, BitConverter.ToString(torrent.Pieces.ReadHash(i)))); } #endif manager = provider.CreateTorrentManager(torrent, file); manager.Settings.MaxUploadSpeed = maxUploadSpeed; manager.Settings.MaxDownloadSpeed = maxDownloadSpeed; manager.PeersFound += manager_PeersFound; manager.PieceHashed += manager_PieceHashed; manager.TorrentStateChanged += manager_TorrentStateChanged; manager.PeerConnected += manager_PeerConnected; manager.PeerDisconnected += manager_PeerDisconnected; #if RIDICULOUS_DEBUG_OUTPUT LoggingService.LogDebug("Engine ID: {0}", provider.Engine.PeerId); #endif manager.Start(); if (file is LocalFile) { foreach (BitTorrentFileTransferPeer peer in peers) { peer.Network.SendFileDetails(peer.Node, (LocalFile)file); } } }
public async Task TestMethod1() { var manager = new TorrentManager("magnet:?xt=urn:btih:TJM7HROVMEEQNACMMY6JYVCQ5VW2RIK5&tr=http://nyaa.tracker.wf:7777/announce&tr=udp://tracker.coppersurfer.tk:6969/announce&tr=udp://tracker.internetwarriors.net:1337/announce&tr=udp://tracker.leechersparadise.org:6969/announce&tr=udp://tracker.opentrackr.org:1337/announce&tr=udp://open.stealth.si:80/announce&tr=udp://p4p.arenabg.com:1337/announce&tr=udp://mgtracker.org:6969/announce&tr=udp://tracker.tiny-vps.com:6969/announce&tr=udp://peerfect.org:6969/announce&tr=http://share.camoe.cn:8080/announce&tr=http://t.nyaatracker.com:80/announce&tr=https://open.kickasstracker.com:443/announce", Path.Combine(Directory.GetCurrentDirectory(), "Downloads")); await manager.Start(); }
public void Resume() => TorrentManager.Start();
private void DownloaderWorker_DoWork(object sender, DoWorkEventArgs e) { try { if (e.Argument == null) return; basePath = Environment.CurrentDirectory; dhtNodeFile = System.IO.Path.Combine(basePath, "DhtNodes"); downloadsPath = System.IO.Path.Combine(basePath, "Downloads"); torrentsPath = System.IO.Path.Combine(basePath, "Torrents"); fastResumeFile = System.IO.Path.Combine(torrentsPath, "fastresume.data"); torrents = new List<TorrentManager>(); // The list where all the torrentManagers will be stored that the engine gives us listener = new Top10Listener(10); string torrentpath = e.Argument.ToString(); int port = 6969; Torrent torrent = null; // Create the settings which the engine will use // downloadsPath - this is the path where we will save all the files to // port - this is the port we listen for connections on EngineSettings engineSettings = new EngineSettings(downloadsPath, port); engineSettings.PreferEncryption = false; engineSettings.AllowedEncryption = EncryptionTypes.All; //engineSettings.GlobalMaxUploadSpeed = 30 * 1024; //engineSettings.GlobalMaxDownloadSpeed = 100 * 1024; //engineSettings.MaxReadRate = 1 * 1024 * 1024; // Create the default settings which a torrent will have. // 4 Upload slots - a good ratio is one slot per 5kB of upload speed // 50 open connections - should never really need to be changed // Unlimited download speed - valid range from 0 -> int.Max // Unlimited upload speed - valid range from 0 -> int.Max TorrentSettings torrentDefaults = new TorrentSettings(4, 150, 0, 0); // Create an instance of the engine. engine = new ClientEngine(engineSettings); engine.ChangeListenEndpoint(new IPEndPoint(IPAddress.Any, port)); byte[] nodes = null; try { nodes = File.ReadAllBytes(dhtNodeFile); } catch { Console.WriteLine("No existing dht nodes could be loaded"); } DhtListener dhtListner = new DhtListener(new IPEndPoint(IPAddress.Any, port)); DhtEngine dht = new DhtEngine(dhtListner); engine.RegisterDht(dht); dhtListner.Start(); engine.DhtEngine.Start(nodes); // If the SavePath does not exist, we want to create it. if (!Directory.Exists(engine.Settings.SavePath)) Directory.CreateDirectory(engine.Settings.SavePath); // If the torrentsPath does not exist, we want to create it if (!Directory.Exists(torrentsPath)) Directory.CreateDirectory(torrentsPath); BEncodedDictionary fastResume; try { fastResume = BEncodedValue.Decode<BEncodedDictionary>(File.ReadAllBytes(fastResumeFile)); } catch { fastResume = new BEncodedDictionary(); } // Load the .torrent from the file into a Torrent instance // You can use this to do preprocessing should you need to torrent = Torrent.Load(torrentpath); // When any preprocessing has been completed, you create a TorrentManager // which you then register with the engine. TorrentManager manager = new TorrentManager(torrent, downloadsPath, torrentDefaults); //if (fastResume.ContainsKey(torrent.InfoHash.ToHex())) // manager.LoadFastResume(new FastResume((BEncodedDictionary)fastResume[torrent.infoHash.ToHex()])); engine.Register(manager); // Store the torrent manager in our list so we can access it later torrents.Add(manager); manager.PeersFound += new EventHandler<PeersAddedEventArgs>(manager_PeersFound); // Every time a piece is hashed, this is fired. manager.PieceHashed += delegate (object o, PieceHashedEventArgs ec) { lock (listener) listener.WriteLine(string.Format("Piece Hashed: {0} - {1}", ec.PieceIndex, ec.HashPassed ? "Pass" : "Fail")); }; // Every time the state changes (Stopped -> Seeding -> Downloading -> Hashing) this is fired manager.TorrentStateChanged += delegate (object o, TorrentStateChangedEventArgs ev) { lock (listener) listener.WriteLine("OldState: " + ev.OldState.ToString() + " NewState: " + ev.NewState.ToString()); }; // Every time the tracker's state changes, this is fired //foreach (TrackerTier tier in manager.TrackerManager) //{ // //foreach (MonoTorrent.Client.Tracker.Tracker t in tier.Trackers) // //{ // // t.AnnounceComplete += delegate (object sender, AnnounceResponseEventArgs e) // // { // // listener.WriteLine(string.Format("{0}: {1}", e.Successful, e.Tracker.ToString())); // // }; // //} //} // Start the torrentmanager. The file will then hash (if required) and begin downloading/seeding manager.Start(); // While the torrents are still running, print out some stats to the screen. // Details for all the loaded torrent managers are shown. bool running = true; StringBuilder sb = new StringBuilder(1024); while (running) { //if ((i++) % 10 == 0) //{ sb.Remove(0, sb.Length); running = torrents.Exists(delegate (TorrentManager m) { return m.State != TorrentState.Stopped; }); //AppendFormat(sb, "Total Download Rate: {0:0.00}kB/sec", engine.TotalDownloadSpeed / 1024.0); downloadspeed = (engine.TotalDownloadSpeed / 1024.0).ToString(); //AppendFormat(sb, "Total Upload Rate: {0:0.00}kB/sec", engine.TotalUploadSpeed / 1024.0); //AppendFormat(sb, "Disk Read Rate: {0:0.00} kB/s", engine.DiskManager.ReadRate / 1024.0); //AppendFormat(sb, "Disk Write Rate: {0:0.00} kB/s", engine.DiskManager.WriteRate / 1024.0); //AppendFormat(sb, "Total Read: {0:0.00} kB", engine.DiskManager.TotalRead / 1024.0); //AppendFormat(sb, "Total Written: {0:0.00} kB", engine.DiskManager.TotalWritten / 1024.0); //AppendFormat(sb, "Open Connections: {0}", engine.ConnectionManager.OpenConnections); //AppendSeperator(sb); //AppendFormat(sb, "State: {0}", manager.State); //AppendFormat(sb, "Name: {0}", manager.Torrent == null ? "MetaDataMode" : manager.Torrent.Name); //AppendFormat(sb, "Progress: {0:0.00}", manager.Progress); //progress = manager.Progress.ToString(); //AppendFormat(sb, "Download Speed: {0:0.00} kB/s", manager.Monitor.DownloadSpeed / 1024.0); //AppendFormat(sb, "Upload Speed: {0:0.00} kB/s", manager.Monitor.UploadSpeed / 1024.0); //AppendFormat(sb, "Total Downloaded: {0:0.00} MB", manager.Monitor.DataBytesDownloaded / (1024.0 * 1024.0)); //AppendFormat(sb, "Total Uploaded: {0:0.00} MB", manager.Monitor.DataBytesUploaded / (1024.0 * 1024.0)); MonoTorrent.Client.Tracker.Tracker tracker = manager.TrackerManager.CurrentTracker; //AppendFormat(sb, "Tracker Status: {0}", tracker == null ? "<no tracker>" : tracker.State.ToString()); //AppendFormat(sb, "Warning Message: {0}", tracker == null ? "<no tracker>" : tracker.WarningMessage); //AppendFormat(sb, "Failure Message: {0}", tracker == null ? "<no tracker>" : tracker.FailureMessage); //if (manager.PieceManager != null) // AppendFormat(sb, "Current Requests: {0}", manager.PieceManager.CurrentRequestCount()); //foreach (PeerId p in manager.GetPeers()) // AppendFormat(sb, "\t{2} - {1:0.00}/{3:0.00}kB/sec - {0}", p.Peer.ConnectionUri, // p.Monitor.DownloadSpeed / 1024.0, // p.AmRequestingPiecesCount, // p.Monitor.UploadSpeed / 1024.0); //AppendFormat(sb, "", null); //if (manager.Torrent != null) // foreach (TorrentFile file in manager.Torrent.Files) // AppendFormat(sb, "{1:0.00}% - {0}", file.Path, file.BitField.PercentComplete); //Console.Clear(); //Console.WriteLine(sb.ToString()); //listener.ExportTo(Console.Out); //} DownloaderWorker.ReportProgress(Convert.ToInt32(manager.Progress), manager.State.ToString()); System.Threading.Thread.Sleep(500); } } catch (Exception ex) { } }
/// <summary> /// Adds a torrent file to a client /// </summary> /// <param name="file">Path to torrent</param> public void AddTorrent(string file) { var fileInfo = new FileInfo(file); var newFile = Path.Combine(TorrentPath, fileInfo.Name); if (!File.Exists(newFile)) File.Copy(file, newFile); Torrent torrent = Torrent.Load(newFile); if (_engine.Contains(torrent.InfoHash)) return; TorrentManager manager = new TorrentManager(torrent, DownloadPath, GetDefaultTorrentSettings()); var fastResume = GetFastResume(); if (fastResume.ContainsKey(torrent.InfoHash.ToHex())) manager.LoadFastResume( new FastResume((BEncodedDictionary)fastResume[torrent.InfoHash.ToHex()])); _engine.Register(manager); _torrents.Add(manager); _torrentData.Add(GetTorrentData(manager)); manager.Start(); }
public override void ViewDidLoad() { base.ViewDidLoad(); Instance = this; tableView.DataSource = this; tableView.Delegate = this; tableView.TableFooterView = new UIView(); tableView.RowHeight = 104; AddAction.Clicked += delegate { var alert = UIAlertController.Create("Add from...", null, UIAlertControllerStyle.ActionSheet); var magnet = UIAlertAction.Create("Magnet", UIAlertActionStyle.Default, delegate { var magnetAlert = UIAlertController.Create("Add from magnet", "Please enter the magnet link below", UIAlertControllerStyle.Alert); magnetAlert.AddTextField((UITextField obj) => { obj.Placeholder = "magnet:"; }); var ok = UIAlertAction.Create("OK", UIAlertActionStyle.Default, delegate { var textField = magnetAlert.TextFields[0]; MagnetLink magnetLink = null; try { magnetLink = new MagnetLink(textField.Text); } catch (FormatException ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); var alertError = UIAlertController.Create("Error", "Wrong magnet link, check it and try again!", UIAlertControllerStyle.Alert); var close = UIAlertAction.Create("Close", UIAlertActionStyle.Cancel, null); alertError.AddAction(close); PresentViewController(alertError, true, null); return; } foreach (var m in Manager.Singletone.managers) { if (m.InfoHash.Equals(magnetLink.InfoHash)) { var alertError = UIAlertController.Create("This torrent already exists", "Torrent with hash: \"" + magnetLink.InfoHash.ToHex() + "\" already exists in download queue", UIAlertControllerStyle.Alert); var close = UIAlertAction.Create("Close", UIAlertActionStyle.Cancel, null); alertError.AddAction(close); PresentViewController(alertError, true, null); return; } } if (!Directory.Exists(Manager.ConfigFolder)) { Directory.CreateDirectory(Manager.ConfigFolder); } var manager = new TorrentManager(magnetLink, Manager.RootFolder, new TorrentSettings(), Manager.RootFolder + "/Config/" + magnetLink.InfoHash.ToHex() + ".torrent"); Manager.Singletone.managers.Add(manager); Manager.Singletone.RegisterManager(manager); TableView.ReloadData(); manager.TorrentStateChanged += delegate { Manager.OnFinishLoading(manager); }; manager.Start(); }); var cancelMagnet = UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, null); magnetAlert.AddAction(ok); magnetAlert.AddAction(cancelMagnet); PresentViewController(magnetAlert, true, null); }); var url = UIAlertAction.Create("URL", UIAlertActionStyle.Default, delegate { var urlAlert = UIAlertController.Create("Add from URL", "Please enter the existing torrent's URL below", UIAlertControllerStyle.Alert); urlAlert.AddTextField((UITextField obj) => { obj.Placeholder = "https://"; }); var ok = UIAlertAction.Create("OK", UIAlertActionStyle.Default, delegate { var textField = urlAlert.TextFields[0]; if (!Directory.Exists(Manager.ConfigFolder)) { Directory.CreateDirectory(Manager.ConfigFolder); } Torrent torrent = null; try { torrent = Torrent.Load(new Uri(textField.Text), Manager.RootFolder + "/Config/_temp.torrent"); } catch (TorrentException ex) { Console.WriteLine(ex.StackTrace); var alertError = UIAlertController.Create("An error occurred", "Please, open this link in Safari, and send .torrent file from it", UIAlertControllerStyle.Alert); var close = UIAlertAction.Create("Close", UIAlertActionStyle.Cancel, null); alertError.AddAction(close); PresentViewController(alertError, true, null); return; } catch (FormatException ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); var alertError = UIAlertController.Create("Error", "Wrong link, check it and try again!", UIAlertControllerStyle.Alert); var close = UIAlertAction.Create("Close", UIAlertActionStyle.Cancel, null); alertError.AddAction(close); PresentViewController(alertError, true, null); return; } foreach (var m in Manager.Singletone.managers) { if (m.Torrent.InfoHash.Equals(torrent.InfoHash)) { var alertError = UIAlertController.Create("This torrent already exists", "Torrent with name: \"" + torrent.Name + "\" already exists in download queue", UIAlertControllerStyle.Alert); var close = UIAlertAction.Create("Close", UIAlertActionStyle.Cancel, null); alertError.AddAction(close); PresentViewController(alertError, true, null); if (torrent.TorrentPath.EndsWith("/_temp.torrent")) { File.Delete(torrent.TorrentPath); } return; } } UIViewController controller = UIStoryboard.FromName("Main", NSBundle.MainBundle).InstantiateViewController("AddTorrent"); ((AddTorrentController)((UINavigationController)controller).ChildViewControllers[0]).torrent = torrent; UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(controller, true, null); }); var cancelUrl = UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, null); urlAlert.AddAction(ok); urlAlert.AddAction(cancelUrl); PresentViewController(urlAlert, true, null); }); var cancel = UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, null); alert.AddAction(magnet); alert.AddAction(url); alert.AddAction(cancel); if (alert.PopoverPresentationController != null) { alert.PopoverPresentationController.BarButtonItem = AddAction; } PresentViewController(alert, true, null); }; action = () => { InvokeOnMainThread(delegate { foreach (var cell in tableView.VisibleCells) { ((TorrentCell)cell).Update(); } Manager.Singletone.UpdateManagers(); }); }; masterAction = (manager) => { InvokeOnMainThread(delegate { foreach (var cell in tableView.VisibleCells) { if (((TorrentCell)cell).manager == manager) { ((TorrentCell)cell).Update(true); } } }); }; Manager.Singletone.restoreAction = () => { TableView.ReloadData(); }; //var bannerView = new BannerView(AdSizeCons.Banner) { // AdUnitID = ADSManager.ADBlockTestID, // RootViewController = this //}; //TableView.AddSubview(bannerView); //var frame = bannerView.Frame; //frame.Y = View.Frame.Size.Height - NavigationController.Toolbar.Frame.Height - bannerView.Frame.Height; //frame.Width = View.Frame.Width; //bannerView.Frame = frame; //bannerView.AdReceived += delegate { // Console.WriteLine("Received"); //}; //bannerView.LoadRequest(Request.GetDefaultRequest()); }
internal void LoadTorrents(List <string> torrentPaths, List <FH2File> obsoleteFiles) { StartDht(this.engine, Properties.Settings.Default.listenPort); this.engineState = EngineState.Downloading; this.managers.Clear(); this.torrents.Clear(); this.totalSize = 0; this.downloadSize = 0; this.initialProgress = -999999; this.lastProgress = 0; this.lastTime = -10000; this.activeWebSeeds = 0; string fastResumeFile = Path.Combine(this.parent.localAppDataFolder, "fastresume.data"); BEncodedDictionary fastResume; try { fastResume = BEncodedValue.Decode <BEncodedDictionary>(File.ReadAllBytes(fastResumeFile)); } catch { fastResume = new BEncodedDictionary(); } foreach (string filePath in torrentPaths) { Torrent torrent = null; try { torrent = Torrent.Load(filePath); } catch (Exception e) { Console.WriteLine(e); debug(e.ToString()); continue; } foreach (TorrentFile file in torrent.Files) { //file.Priority = Priority.DoNotDownload; //file.Priority = Priority.Normal; this.totalSize += file.Length; foreach (FH2File fh2File in obsoleteFiles) { if ((fh2File.fullPath == Path.Combine(torrent.Name, file.FullPath)) || (torrent.Name.ToLower().Contains("updater")) || ((fh2File.name.ToLower().Contains("ubuntu") && (fh2File.name.ToLower().Contains(".iso"))))) { //file.Priority = Priority.Normal; this.downloadSize += file.Length; break; } } } this.torrents.Add(torrent); //TorrentSettings settings = new TorrentSettings(5, 50, 0, 0); TorrentSettings settings = new TorrentSettings(5, 50, 0, this.engine.Settings.GlobalMaxUploadSpeed); TorrentManager manager = new TorrentManager(torrent, engine.Settings.SavePath, settings); if (fastResume.ContainsKey(torrent.InfoHash.ToHex())) { manager.LoadFastResume(new FastResume((BEncodedDictionary)fastResume[torrent.InfoHash.ToHex()])); } this.managers.Add(manager); manager.PeerConnected += manager_PeerConnected; manager.PeerDisconnected += manager_PeerDisconnected; this.engine.Register(manager); manager.TorrentStateChanged += waitForFinish; manager.TrackerManager.Announce(); // Disable rarest first and randomised picking - only allow priority based picking (i.e. selective downloading) //PiecePicker picker = new StandardPicker(); //picker = new PriorityPicker(picker); //manager.ChangePicker(picker); try { manager.Start(); } catch (Exception e) { MessageBox.Show("Could not start the torrent.\nError Message:\n" + e.Message); Console.WriteLine(e); debug(e.ToString()); } } }
void SetupTorrent(TorrentManager manager) { // Every time a piece is hashed, this is fired. manager.PieceHashed += delegate(object o, PieceHashedEventArgs e) { var tm = (TorrentManager)o; /*lock (this) { if (tm.State != TorrentState.Hashing) Console.WriteLine(string.Format("Piece Hashed: {0} - {1}", e.PieceIndex, e.HashPassed ? "Pass" : "Fail")); }*/ }; // Every time the state changes (Stopped -> Seeding -> Downloading -> Hashing) this is fired manager.TorrentStateChanged += delegate(object o, TorrentStateChangedEventArgs e) { var tm = (TorrentManager)o; var name = !tm.HasMetadata ? "Magnet" : tm.Torrent.Name; lock (this) Console.WriteLine("simpletorrent: [{1}] {0}", e.NewState.ToString(), name); lock (seedingLimitTorrents) { if (e.NewState == TorrentState.Seeding && seedingLimit.HasValue && seedingLimitTorrents.Where(a => a.Item2 == tm).Count() == 0) { Console.WriteLine("simpletorrent: Queuing \"{0}\" for automatic removal...", name); seedingLimitTorrents.Add(new Tuple<DateTime, TorrentManager>(DateTime.Now, tm)); } } if (e.NewState == TorrentState.Stopped) { try { var ti = torrentInformation[tm.InfoHash.ToHex()]; if (ti.ToRemove != null) { if (tm.HasMetadata && tm.Torrent != null) { File.Delete(tm.Torrent.TorrentPath); } engine.Unregister(tm); torrentInformation.Remove(manager.InfoHash.ToHex()); } if (ti.ToRemove == "delete-torrent-and-data") { System.Threading.Thread.Sleep(200); if (Directory.Exists(Path.Combine(tm.SavePath, tm.Torrent.Name))) { Directory.Delete(Path.Combine(tm.SavePath, tm.Torrent.Name), true); } else { File.Delete(Path.Combine (tm.SavePath, tm.Torrent.Name)); } } } catch (Exception ex) { debugWriter.WriteLine("Exception when attempting to stop torrent: " + ex.ToString()); } } else { try { var ti = torrentInformation[tm.InfoHash.ToHex()]; ti.CreationDateTime = File.GetCreationTime(tm.Torrent.TorrentPath); } catch { } } }; // Every time the tracker's state changes, this is fired foreach (TrackerTier tier in manager.TrackerManager) { foreach (MonoTorrent.Client.Tracker.Tracker t in tier.Trackers) { t.AnnounceComplete += delegate(object sender, AnnounceResponseEventArgs e) { //Console.WriteLine(string.Format("{0}: {1}", e.Successful, e.Tracker.ToString())); }; } } try { torrentInformation.Remove(manager.InfoHash.ToHex()); } catch { } TorrentInformation nTi = new TorrentInformation(); try { nTi.CreationDateTime = File.GetCreationTime(manager.Torrent.TorrentPath); } catch { } torrentInformation.Add(manager.InfoHash.ToHex(), nTi); // Start the torrentmanager. The file will then hash (if required) and begin downloading/seeding manager.Start(); }
private void DownloaderWorker_DoWork(object sender, DoWorkEventArgs e) { try { if (e.Argument == null) { return; } basePath = Environment.CurrentDirectory; dhtNodeFile = System.IO.Path.Combine(basePath, "DhtNodes"); downloadsPath = System.IO.Path.Combine(basePath, "Downloads"); torrentsPath = System.IO.Path.Combine(basePath, "Torrents"); fastResumeFile = System.IO.Path.Combine(torrentsPath, "fastresume.data"); torrents = new List <TorrentManager>(); // The list where all the torrentManagers will be stored that the engine gives us listener = new Top10Listener(10); string torrentpath = e.Argument.ToString(); int port = 6969; Torrent torrent = null; // Create the settings which the engine will use // downloadsPath - this is the path where we will save all the files to // port - this is the port we listen for connections on EngineSettings engineSettings = new EngineSettings(downloadsPath, port); engineSettings.PreferEncryption = false; engineSettings.AllowedEncryption = EncryptionTypes.All; //engineSettings.GlobalMaxUploadSpeed = 30 * 1024; //engineSettings.GlobalMaxDownloadSpeed = 100 * 1024; //engineSettings.MaxReadRate = 1 * 1024 * 1024; // Create the default settings which a torrent will have. // 4 Upload slots - a good ratio is one slot per 5kB of upload speed // 50 open connections - should never really need to be changed // Unlimited download speed - valid range from 0 -> int.Max // Unlimited upload speed - valid range from 0 -> int.Max TorrentSettings torrentDefaults = new TorrentSettings(4, 150, 0, 0); // Create an instance of the engine. engine = new ClientEngine(engineSettings); engine.ChangeListenEndpoint(new IPEndPoint(IPAddress.Any, port)); byte[] nodes = null; try { nodes = File.ReadAllBytes(dhtNodeFile); } catch { Console.WriteLine("No existing dht nodes could be loaded"); } DhtListener dhtListner = new DhtListener(new IPEndPoint(IPAddress.Any, port)); DhtEngine dht = new DhtEngine(dhtListner); engine.RegisterDht(dht); dhtListner.Start(); engine.DhtEngine.Start(nodes); // If the SavePath does not exist, we want to create it. if (!Directory.Exists(engine.Settings.SavePath)) { Directory.CreateDirectory(engine.Settings.SavePath); } // If the torrentsPath does not exist, we want to create it if (!Directory.Exists(torrentsPath)) { Directory.CreateDirectory(torrentsPath); } BEncodedDictionary fastResume; try { fastResume = BEncodedValue.Decode <BEncodedDictionary>(File.ReadAllBytes(fastResumeFile)); } catch { fastResume = new BEncodedDictionary(); } // Load the .torrent from the file into a Torrent instance // You can use this to do preprocessing should you need to torrent = Torrent.Load(torrentpath); // When any preprocessing has been completed, you create a TorrentManager // which you then register with the engine. TorrentManager manager = new TorrentManager(torrent, downloadsPath, torrentDefaults); //if (fastResume.ContainsKey(torrent.InfoHash.ToHex())) // manager.LoadFastResume(new FastResume((BEncodedDictionary)fastResume[torrent.infoHash.ToHex()])); engine.Register(manager); // Store the torrent manager in our list so we can access it later torrents.Add(manager); manager.PeersFound += new EventHandler <PeersAddedEventArgs>(manager_PeersFound); // Every time a piece is hashed, this is fired. manager.PieceHashed += delegate(object o, PieceHashedEventArgs ec) { lock (listener) listener.WriteLine(string.Format("Piece Hashed: {0} - {1}", ec.PieceIndex, ec.HashPassed ? "Pass" : "Fail")); }; // Every time the state changes (Stopped -> Seeding -> Downloading -> Hashing) this is fired manager.TorrentStateChanged += delegate(object o, TorrentStateChangedEventArgs ev) { lock (listener) listener.WriteLine("OldState: " + ev.OldState.ToString() + " NewState: " + ev.NewState.ToString()); }; // Every time the tracker's state changes, this is fired //foreach (TrackerTier tier in manager.TrackerManager) //{ // //foreach (MonoTorrent.Client.Tracker.Tracker t in tier.Trackers) // //{ // // t.AnnounceComplete += delegate (object sender, AnnounceResponseEventArgs e) // // { // // listener.WriteLine(string.Format("{0}: {1}", e.Successful, e.Tracker.ToString())); // // }; // //} //} // Start the torrentmanager. The file will then hash (if required) and begin downloading/seeding manager.Start(); // While the torrents are still running, print out some stats to the screen. // Details for all the loaded torrent managers are shown. bool running = true; StringBuilder sb = new StringBuilder(1024); while (running) { //if ((i++) % 10 == 0) //{ sb.Remove(0, sb.Length); running = torrents.Exists(delegate(TorrentManager m) { return(m.State != TorrentState.Stopped); }); //AppendFormat(sb, "Total Download Rate: {0:0.00}kB/sec", engine.TotalDownloadSpeed / 1024.0); downloadspeed = (engine.TotalDownloadSpeed / 1024.0).ToString(); //AppendFormat(sb, "Total Upload Rate: {0:0.00}kB/sec", engine.TotalUploadSpeed / 1024.0); //AppendFormat(sb, "Disk Read Rate: {0:0.00} kB/s", engine.DiskManager.ReadRate / 1024.0); //AppendFormat(sb, "Disk Write Rate: {0:0.00} kB/s", engine.DiskManager.WriteRate / 1024.0); //AppendFormat(sb, "Total Read: {0:0.00} kB", engine.DiskManager.TotalRead / 1024.0); //AppendFormat(sb, "Total Written: {0:0.00} kB", engine.DiskManager.TotalWritten / 1024.0); //AppendFormat(sb, "Open Connections: {0}", engine.ConnectionManager.OpenConnections); //AppendSeperator(sb); //AppendFormat(sb, "State: {0}", manager.State); //AppendFormat(sb, "Name: {0}", manager.Torrent == null ? "MetaDataMode" : manager.Torrent.Name); //AppendFormat(sb, "Progress: {0:0.00}", manager.Progress); //progress = manager.Progress.ToString(); //AppendFormat(sb, "Download Speed: {0:0.00} kB/s", manager.Monitor.DownloadSpeed / 1024.0); //AppendFormat(sb, "Upload Speed: {0:0.00} kB/s", manager.Monitor.UploadSpeed / 1024.0); //AppendFormat(sb, "Total Downloaded: {0:0.00} MB", manager.Monitor.DataBytesDownloaded / (1024.0 * 1024.0)); //AppendFormat(sb, "Total Uploaded: {0:0.00} MB", manager.Monitor.DataBytesUploaded / (1024.0 * 1024.0)); MonoTorrent.Client.Tracker.Tracker tracker = manager.TrackerManager.CurrentTracker; //AppendFormat(sb, "Tracker Status: {0}", tracker == null ? "<no tracker>" : tracker.State.ToString()); //AppendFormat(sb, "Warning Message: {0}", tracker == null ? "<no tracker>" : tracker.WarningMessage); //AppendFormat(sb, "Failure Message: {0}", tracker == null ? "<no tracker>" : tracker.FailureMessage); //if (manager.PieceManager != null) // AppendFormat(sb, "Current Requests: {0}", manager.PieceManager.CurrentRequestCount()); //foreach (PeerId p in manager.GetPeers()) // AppendFormat(sb, "\t{2} - {1:0.00}/{3:0.00}kB/sec - {0}", p.Peer.ConnectionUri, // p.Monitor.DownloadSpeed / 1024.0, // p.AmRequestingPiecesCount, // p.Monitor.UploadSpeed / 1024.0); //AppendFormat(sb, "", null); //if (manager.Torrent != null) // foreach (TorrentFile file in manager.Torrent.Files) // AppendFormat(sb, "{1:0.00}% - {0}", file.Path, file.BitField.PercentComplete); //Console.Clear(); //Console.WriteLine(sb.ToString()); //listener.ExportTo(Console.Out); //} DownloaderWorker.ReportProgress(Convert.ToInt32(manager.Progress), manager.State.ToString()); System.Threading.Thread.Sleep(500); } } catch (Exception ex) { } }
void RestoreTorrents() { SaveClass save = null; if (File.Exists(DatFile)) { try { save = Utils.DeSerializeObject <SaveClass>(DatFile); } catch (System.Xml.XmlException e) { Console.WriteLine(e.StackTrace); File.Move(DatFile, Path.Combine(ConfigFolder, "dat1.itor")); var controller = UIAlertController.Create("Config file loading error", "There was a problem loading the configuration file, a copy will be created under the \"dat1\" name, and a new one will be created", UIAlertControllerStyle.Alert); var topWindow = new UIWindow(UIScreen.MainScreen.Bounds); topWindow.RootViewController = new UIViewController(); topWindow.WindowLevel = UIWindowLevel.Alert + 1; var ok = UIAlertAction.Create("OK", UIAlertActionStyle.Cancel, delegate { topWindow.Hidden = true; topWindow = null; }); controller.AddAction(ok); topWindow.MakeKeyAndVisible(); topWindow.RootViewController.PresentViewController(controller, true, null); } } if (File.Exists(Path.Combine(ConfigFolder, "_temp.torrent"))) { File.Delete(Path.Combine(ConfigFolder, "_temp.torrent")); } if (Directory.Exists(ConfigFolder)) { foreach (var file in Directory.GetFiles(ConfigFolder)) { new Thread(() => { if (file.EndsWith(".torrent", StringComparison.Ordinal)) { Torrent torrent = Torrent.Load(file); TorrentManager manager = new TorrentManager(torrent, RootFolder, new TorrentSettings()); engine.Register(manager); manager.TorrentStateChanged += (sender, e) => { Manager.OnFinishLoading(manager, e); }; if (save != null && save.data.ContainsKey(torrent.InfoHash.ToHex())) { if (save.data[torrent.InfoHash.ToHex()].resume != null) { manager.LoadFastResume(new FastResume(BEncodedValue.Decode(save.data[torrent.InfoHash.ToHex()].resume) as BEncodedDictionary)); manager.dateOfAdded = save.data[torrent.InfoHash.ToHex()].date; manager.allowSeeding = save.data[torrent.InfoHash.ToHex()].allowSeeding; switch (save.data[torrent.InfoHash.ToHex()].state) { case TorrentState.Downloading: manager.Start(); break; default: manager.Stop(); break; } } foreach (var _file in torrent.Files) { if (save.data[torrent.InfoHash.ToHex()].downloading.ContainsKey(_file.Path)) { _file.Priority = save.data[torrent.InfoHash.ToHex()].downloading[_file.Path] ? Priority.Highest : Priority.DoNotDownload; } } } else { foreach (var _file in torrent.Files) { _file.Priority = Priority.DoNotDownload; } manager.HashCheck(true); } PiecePicker picker = new StandardPicker(); picker = new PriorityPicker(picker); manager.ChangePicker(picker); foreach (TrackerTier tier in manager.TrackerManager) { foreach (Tracker t in tier.Trackers) { t.AnnounceComplete += delegate(object sender, AnnounceResponseEventArgs e) { Console.WriteLine(string.Format("{0}!: {1}", e.Successful, e.Tracker)); }; } } managers.Add(manager); UIApplication.SharedApplication.InvokeOnMainThread(() => { restoreAction?.Invoke(); }); } }).Start(); } } }
void SetupTorrent(TorrentManager manager) { // Every time a piece is hashed, this is fired. manager.PieceHashed += delegate(object o, PieceHashedEventArgs e) { var tm = (TorrentManager)o; /*lock (this) * { * if (tm.State != TorrentState.Hashing) * Console.WriteLine(string.Format("Piece Hashed: {0} - {1}", e.PieceIndex, e.HashPassed ? "Pass" : "Fail")); * }*/ }; // Every time the state changes (Stopped -> Seeding -> Downloading -> Hashing) this is fired manager.TorrentStateChanged += delegate(object o, TorrentStateChangedEventArgs e) { var tm = (TorrentManager)o; var name = !tm.HasMetadata ? "Magnet" : tm.Torrent.Name; lock (this) Console.WriteLine("simpletorrent: [{1}] {0}", e.NewState.ToString(), name); lock (seedingLimitTorrents) { if (e.NewState == TorrentState.Seeding && seedingLimit.HasValue && seedingLimitTorrents.Where(a => a.Item2 == tm).Count() == 0) { Console.WriteLine("simpletorrent: Queuing \"{0}\" for automatic removal...", name); seedingLimitTorrents.Add(new Tuple <DateTime, TorrentManager>(DateTime.Now, tm)); } } if (e.NewState == TorrentState.Stopped) { try { var ti = torrentInformation[tm.InfoHash.ToHex()]; if (ti.ToRemove != null) { if (tm.HasMetadata && tm.Torrent != null) { File.Delete(tm.Torrent.TorrentPath); } engine.Unregister(tm); torrentInformation.Remove(manager.InfoHash.ToHex()); } if (ti.ToRemove == "delete-torrent-and-data") { System.Threading.Thread.Sleep(200); if (Directory.Exists(Path.Combine(tm.SavePath, tm.Torrent.Name))) { Directory.Delete(Path.Combine(tm.SavePath, tm.Torrent.Name), true); } else { File.Delete(Path.Combine(tm.SavePath, tm.Torrent.Name)); } } } catch (Exception ex) { debugWriter.WriteLine("Exception when attempting to stop torrent: " + ex.ToString()); } } else { try { var ti = torrentInformation[tm.InfoHash.ToHex()]; ti.CreationDateTime = File.GetCreationTime(tm.Torrent.TorrentPath); } catch { } } }; // Every time the tracker's state changes, this is fired foreach (TrackerTier tier in manager.TrackerManager) { foreach (MonoTorrent.Client.Tracker.Tracker t in tier.Trackers) { t.AnnounceComplete += delegate(object sender, AnnounceResponseEventArgs e) { //Console.WriteLine(string.Format("{0}: {1}", e.Successful, e.Tracker.ToString())); }; } } try { torrentInformation.Remove(manager.InfoHash.ToHex()); } catch { } TorrentInformation nTi = new TorrentInformation(); try { nTi.CreationDateTime = File.GetCreationTime(manager.Torrent.TorrentPath); } catch { } torrentInformation.Add(manager.InfoHash.ToHex(), nTi); // Start the torrentmanager. The file will then hash (if required) and begin downloading/seeding manager.Start(); }
public void Start() { TM.Start(); }
public override void ViewDidLoad() { base.ViewDidLoad(); files = torrent.Files.Clone() as TorrentFile[]; Array.Sort(files, delegate(TorrentFile f1, TorrentFile f2) { return(string.Compare(f1.Path, f2.Path, StringComparison.Ordinal)); }); foreach (var file in files) { Console.WriteLine(file.Path); } tableView.DataSource = this; tableView.Delegate = this; tableView.RowHeight = 78; Cancel.Clicked += delegate { if (torrent.TorrentPath.EndsWith("/_temp.torrent")) { File.Delete(torrent.TorrentPath); } DismissViewController(true, null); }; DeselectAllAction.Clicked += delegate { foreach (var file in files) { file.Priority = Priority.DoNotDownload; } foreach (var cell in tableView.VisibleCells) { ((FileCell)cell).Update(); } }; SelectAllAction.Clicked += delegate { foreach (var file in files) { file.Priority = Priority.Highest; } foreach (var cell in tableView.VisibleCells) { ((FileCell)cell).Update(); } }; Download.Clicked += delegate { TorrentManager manager = new TorrentManager(torrent, Manager.RootFolder, new TorrentSettings()); Manager.Singletone.managers.Add(manager); Manager.Singletone.RegisterManager(manager); if (MainController.Instance != null) { MainController.Instance.TableView.ReloadData(); } // Disable rarest first and randomised picking - only allow priority based picking (i.e. selective downloading) PiecePicker picker = new StandardPicker(); picker = new PriorityPicker(picker); manager.ChangePicker(picker); manager.TorrentStateChanged += delegate { Manager.OnFinishLoading(manager); }; foreach (var file in files) { if (file.Priority != Priority.DoNotDownload) { manager.Start(); break; } } if (!Directory.Exists(Manager.ConfigFolder)) { Directory.CreateDirectory(Manager.ConfigFolder); } if (File.Exists(Path.Combine(Manager.ConfigFolder, torrent.Name + ".torrent"))) { File.Delete(Path.Combine(Manager.ConfigFolder, torrent.Name + ".torrent")); } File.Copy(torrent.TorrentPath, Path.Combine(Manager.ConfigFolder, torrent.Name + ".torrent")); if (torrent.TorrentPath.EndsWith("/_temp.torrent")) { File.Delete(torrent.TorrentPath); } foreach (var file in files) { Console.WriteLine(file.Path + " " + file.Priority); } //SaveClass save = new SaveClass(manager); //Utils.SerializeObject<SaveClass>(save, AppDelegate.documents + "/Config/" + manager.Torrent.Name + ".sav"); DismissViewController(true, null); }; }
protected string Add(Torrent torrent, string outputDirectoryPath) { // Create the torrent manager. var torrentManager = new TorrentManager(torrent, outputDirectoryPath, DefaultTorrentSettings, ""); // Setup fast resume. if (FastResume.ContainsKey (torrent.InfoHash.ToHex ())) torrentManager.LoadFastResume (new FastResume ((BEncodedDictionary)FastResume [torrent.InfoHash.ToHex ()])); // Add to mappings cache. TorrentMappingsCache.RemoveAll (tmc => tmc.InfoHash == torrent.InfoHash.ToString ()); TorrentMappingsCache.Add(new TorrentMapping { InfoHash = torrent.InfoHash.ToString(), OutputDirectoryPath = outputDirectoryPath }); TorrentMappingsCache.Save (); // Register and start. Engine.Register(torrentManager); torrentManager.Start (); // Return Id. return torrentManager.InfoHash.ToString(); }
static void StartDownload(ClientEngine clientEngine, TorrentSettings torrentDefaultSettings) { string baseDir = Path.Combine(Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.Personal), "var"), "MonoTorrent"); Debug.WriteLine(string.Format("Base Dir is {0}", baseDir)); var torrent = Torrent.Load(Path.Combine(baseDir, TorrentFileName)); (torrent.Files[0] as TorrentFile).Priority = Priority.Highest; (torrent.Files[1] as TorrentFile).Priority = Priority.DoNotDownload; (torrent.Files[2] as TorrentFile).Priority = Priority.DoNotDownload; long targetDownloadSize = (torrent.Files[0] as TorrentFile).Length; long totalSize = torrent.Size; double targetPercentage = (double)targetDownloadSize / totalSize; Debug.WriteLine(string.Format("Intend to download {0}/{1} = {2}", targetDownloadSize, totalSize, targetPercentage)); var torrentManager = new TorrentManager(torrent, Path.Combine(baseDir, "Downloads"), torrentDefaultSettings); var progressMonitor = new PartialDownloadProgressMonitor(torrentManager); progressMonitor.FileDownloaded += new EventHandler<FileDownloadedEventArgs>(progressMonitor_FileDownloaded); clientEngine.Register(torrentManager); torrentManager.TorrentStateChanged += new EventHandler<TorrentStateChangedEventArgs>(torrentManager_TorrentStateChanged); // Start downloading torrentManager.Start(); // Keep running while the torrent isn't stopped or paused. while (torrentManager.State != TorrentState.Stopped && torrentManager.State != TorrentState.Paused) { Debug.WriteLine(string.Format("Progress: {0}", torrentManager.Progress)); System.Threading.Thread.Sleep(2000); } Console.Read(); }
public async void DownloadTorrent(string path) { Torrent torrent = await Task.Run(() => Torrent.Load(@"test.torrent")); // Torrent torrent = await Task.Run(() => Torrent.Load(path)); // StorageFolder storageFolder = await StorageFolder.GetFolderFromPathAsync(savePath); manager = new TorrentManager(torrent, savePath, new TorrentSettings()); engine.Register(manager); manager.Start(); }