public async Task MismatchedPeerId_PrivateTorrent()
        {
            var manager = TestRig.CreatePrivate();

            using var engine = new ClientEngine();
            await engine.Register(manager);

            manager.Mode = new DownloadMode(manager, DiskManager, ConnectionManager, Settings);
            var peer      = PeerId.CreateNull(manager.Bitfield.Length);
            var handshake = new HandshakeMessage(manager.InfoHash, new BEncodedString(Enumerable.Repeat('c', 20).ToArray()), VersionInfo.ProtocolStringV100, false);

            Assert.Throws <TorrentException> (() => manager.Mode.HandleMessage(peer, handshake));
        }
        internal TorrentManager CreateTorrentManager(Torrent torrent, IFile file)
        {
            var localPath = (file is LocalFile) ? Path.GetDirectoryName(((LocalFile)file).LocalPath) : engine.Settings.SavePath;

            LoggingService.LogDebug("Local path: {0}", localPath);
            var manager = new TorrentManager(torrent,
                                             localPath,
                                             torrentDefaults);

            engine.Register(manager);
            LoggingService.LogDebug("{0}: Registered Manager with engine", Environment.TickCount);
            return(manager);
        }
Example #3
0
        /// <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);
        }
Example #4
0
        public void RegisterTorrent(TorrentManager torrent)
        {
            if (torrent.HasMetadata)
            {
                torrent.ChangePicker(CreateSlidingPicker(torrent));
            }
            else
            {
                torrent.MetadataReceived += TorrentOnMetadataReceived;
            }

            _engine.Register(torrent);
            _torrents.Add(torrent);
        }
Example #5
0
        public Download addTorrent(Torrent torrent, bool startTorrent, bool removeOriginal, TorrentSettings savedSettings, string savePath, bool isUrl)
        {
            string   originalPath = torrent.TorrentPath;
            Download manager;

            if (!Directory.Exists(savePath))
            {
                throw new TorrentException("Torrent save path does not exist, " + savePath);
            }

            // Check to see if torrent already exists
            if (engine.Contains(torrent))
            {
                logger.Error("Failed to add torrent, " + torrent.Name + " already exists.");
                throw new TorrentException("Failed to add torrent, " + torrent.Name + " already exists.");
            }

            // Move the .torrent to the local storage folder if it's not there already
            MoveToStorage(ref torrent);

            TorrentSettings settings = savedSettings ?? defaultTorrentSettings.Clone();
            FastResume      resume   = this.fastResume.Find(delegate(FastResume f) { return(f.Infohash == torrent.InfoHash); });

            manager = new Download(savePath, new TorrentManager(torrent, savePath, settings));
            if (resume != null)
            {
                manager.Manager.LoadFastResume(resume);
            }

            engine.Register(manager.Manager);

            if (removeOriginal)
            {
                logger.Info("Removing {0}", originalPath);
                File.Delete(originalPath);
            }

            Event.Raise <DownloadAddedEventArgs> (Added, this, new DownloadAddedEventArgs(manager));
            allTorrents.Add(manager);

            if (startTorrent)
            {
                logger.Info("Auto starting torrent " + manager.Torrent.Name);
                manager.Start();
            }

            logger.Info("Added torrent " + manager.Torrent.Name);

            return(manager);
        }
 public EngineTestRig(string savePath, int piecelength, PieceWriter writer)
 {
     if (writer == null)
     {
         writer = new MemoryWriter(new NullWriter());
     }
     listener    = new CustomListener();
     engine      = new ClientEngine(new EngineSettings(), listener, writer);
     torrentDict = CreateTorrent(piecelength);
     torrent     = Torrent.Load(torrentDict);
     manager     = new TorrentManager(torrent, savePath, new TorrentSettings());
     engine.Register(manager).Wait();
     //manager.Start();
 }
Example #7
0
        private ObjectPath Load(TorrentAdapter tAdapter, TorrentSettings settings, TorrentManager manager)
        {
            ObjectPath managerPath  = new ObjectPath(string.Format(DownloaderPath, downloaderNumber++));
            ObjectPath settingsPath = new ObjectPath(string.Format("{0}/settings", managerPath.ToString()));

            TorrentSettingsAdapter sAdapter = new TorrentSettingsAdapter(settings, settingsPath);
            TorrentManagerAdapter  mAdapter = new TorrentManagerAdapter(manager, tAdapter, sAdapter, managerPath);

            TorrentService.Bus.Register(sAdapter.Path, sAdapter);
            TorrentService.Bus.Register(mAdapter.Path, mAdapter);

            engine.Register(manager);
            downloaders.Add(mAdapter.Path, mAdapter);

            return(mAdapter.Path);
        }
        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();
        }
Example #9
0
        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();
        }
Example #10
0
 public void RecreateManager()
 {
     if (_manager != null)
     {
         _manager.Dispose();
         if (_engine.Contains(_manager))
         {
             _engine.Unregister(_manager);
         }
     }
     _torrentDict = CreateTorrent(_piecelength, _files, _tier);
     _torrent     = Torrent.Load(_torrentDict);
     _manager     = MetadataMode
                    ? new TorrentManager(_torrent.infoHash, _savePath, new TorrentSettings(), MetadataPath, new RawTrackerTiers())
                    : new TorrentManager(_torrent, _savePath, new TorrentSettings());
     _engine.Register(_manager);
 }
Example #11
0
        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();
        }
Example #12
0
        private async static void BegingTorrentDownload()
        {
            try
            {
                Console.WriteLine("Processing Torrent......");

                EngineSettings settings = new EngineSettings();
                settings.AllowedEncryption = EncryptionTypes.All;
                settings.SavePath          = Path.Combine(Environment.CurrentDirectory, "torrents");

                if (!Directory.Exists(settings.SavePath))
                {
                    Directory.CreateDirectory(settings.SavePath);
                }

                //End Point settings moved
                settings.ReportedAddress = new IPEndPoint(IPAddress.Any, 6969);

                var engine = new ClientEngine(settings);

                //engine.ChangeListenEndpoint(new IPEndPoint(IPAddress.Any, 6969));

                Torrent torrent = Torrent.Load("C:/9D4A9495BE35D97B13E60D143F37CC38378D8233.torrent");

                TorrentManager manager = new TorrentManager(torrent, engine.Settings.SavePath, new TorrentSettings());

                await engine.Register(manager);

                await manager.StartAsync();

                Console.WriteLine("COMPLTED...SUCCESS");

                //Lunch Direvtory
                // Process.Start(settings.SavePath);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"ERROR OCCURRED: {ex.Message}");
            }
        }
Example #13
0
        private bool DownloadTorrent(string path)
        {
            try
            {
                ClientEngine engine = new ClientEngine(new EngineSettings());

                MonoTorrent.Torrent torrent        = MonoTorrent.Torrent.Load(path);
                TorrentManager      torrentManager = new TorrentManager(torrent, SaveFolder, new TorrentSettings());
                engine.Register(torrentManager);
                System.Threading.Tasks.Task task = engine.StartAllAsync();
                task.Wait();

                // 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);
            }
        }
Example #14
0
        public TorrentFile(string pathToTorrent, string outPath, IPEndPoint endPoint, string dhtNodeFile = null, bool DHTenabled = true, bool preferEncryption = true, EncryptionTypes encryption = EncryptionTypes.All)
        {
            path     = pathToTorrent;
            savePath = outPath;

            settings = new EngineSettings();

            settings.AllowedEncryption = encryption;
            settings.PreferEncryption  = preferEncryption;
            settings.SavePath          = outPath;

            engine = new ClientEngine(settings);

            engine.ChangeListenEndpoint(endPoint);

            torrent = Torrent.Load(pathToTorrent);

            manager = new TorrentManager(torrent, outPath, new TorrentSettings());

            engine.Register(manager);

            byte[] nodes = null;
            try
            {
                nodes = File.ReadAllBytes(dhtNodeFile);
            }
            catch
            {
            }

            if (DHTenabled)
            {
                dhtListener = new DhtListener(endPoint);
                dhtEngine   = new DhtEngine(dhtListener);
                engine.RegisterDht(dhtEngine);
                dhtListener.Start();
                engine.DhtEngine.Start(nodes);
            }
        }
Example #15
0
        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);
            }
        }
        public async void AddTorrent(string torrentPath)
        {
            var torrentName = Path.GetFileName(torrentPath);

            if (!CheckTorrentInTorrentsPath(torrentName))
            {
                CopyTorrentToTorrentsFolder(torrentPath);
            }
            var     fastResume      = LoadFastResumeFile();
            Torrent torrent         = null;
            var     torrentDefaults = new TorrentSettings();

            if (torrentPath.EndsWith(".torrent", StringComparison.OrdinalIgnoreCase))
            {
                try
                {
                    torrent = await Torrent.LoadAsync(torrentPath);
                }
                catch (Exception exception)
                {
                    uiManager.TextBoxWriteLine("Couldn't decode: " + torrentPath + " ");
                    uiManager.TextBoxWriteLine(exception.Message);
                }

                var manager = new TorrentManager(torrent, pathsManager.DownloadsPath, torrentDefaults);
                if (fastResume != null && fastResume.ContainsKey(torrent.InfoHash.ToHex()))
                {
                    manager.LoadFastResume(new FastResume((BEncodedDictionary)fastResume[torrent.InfoHash.ToHex()]));
                }
                await engine.Register(manager);

                torrentsManagers.Add(manager);

                var torrentsDownloadInfo = GetTorrentsDownloadInfo();
                uiManager.TorrentsDataGridUpdate(torrentsDownloadInfo);
            }
        }
Example #17
0
        public MainViewModel()
        {
            tSettings.UseDht = true;

            EngineSettings eSettings = new EngineSettings();

            engine = new ClientEngine(eSettings);

            Torrents = new ObservableCollection <TorrentManagerWrapper>();

            foreach (TorrentManager manager in saveLoadManager.Load(tSettings))
            {
                engine.Register(manager);

                if (!manager.Complete)
                {
                    manager.Start();
                }

                TorrentManagerWrapper wrapper = new TorrentManagerWrapper(manager);

                Torrents.Add(wrapper);
            }
        }
Example #18
0
        private static async Task StartEngine()
        {
            Logger.Factory = (string className) => new TextLogger(Console.Out, className);

            int     port;
            Torrent torrent = null;

            // Ask the user what port they want to use for incoming connections
            Console.Write($"{Environment.NewLine}Choose a listen port: ");
            while (!Int32.TryParse(Console.ReadLine(), out port))
            {
            }

            // 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 {
                SavePath   = downloadsPath,
                ListenPort = port
            };

            //engineSettings.GlobalMaxUploadSpeed = 30 * 1024;
            //engineSettings.GlobalMaxDownloadSpeed = 100 * 1024;
            //engineSettings.MaxReadRate = 1 * 1024 * 1024;

            // Create the default settings which a torrent will have.
            TorrentSettings torrentDefaults = new TorrentSettings();

            // Create an instance of the engine.
            engine = new ClientEngine(engineSettings);

            byte[] nodes = Array.Empty <byte> ();
            try {
                if (File.Exists(dhtNodeFile))
                {
                    nodes = File.ReadAllBytes(dhtNodeFile);
                }
            } catch {
                Console.WriteLine("No existing dht nodes could be loaded");
            }

            DhtEngine dht = new DhtEngine(new IPEndPoint(IPAddress.Any, port));
            await engine.RegisterDhtAsync(dht);

            // This starts the Dht engine but does not wait for the full initialization to
            // complete. This is because it can take up to 2 minutes to bootstrap, depending
            // on how many nodes time out when they are contacted.
            await engine.DhtEngine.StartAsync(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 = new BEncodedDictionary();

            try {
                if (File.Exists(fastResumeFile))
                {
                    fastResume = BEncodedValue.Decode <BEncodedDictionary> (File.ReadAllBytes(fastResumeFile));
                }
            } catch {
            }

            // For each file in the torrents path that is a .torrent file, load it into the engine.
            foreach (string file in Directory.GetFiles(torrentsPath))
            {
                if (file.EndsWith(".torrent", StringComparison.OrdinalIgnoreCase))
                {
                    try {
                        // Load the .torrent from the file into a Torrent instance
                        // You can use this to do preprocessing should you need to
                        torrent = await Torrent.LoadAsync(file);

                        Console.WriteLine(torrent.InfoHash.ToString());
                    } catch (Exception e) {
                        Console.Write("Couldn't decode {0}: ", file);
                        Console.WriteLine(e.Message);
                        continue;
                    }
                    // 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()]));
                    }
                    await engine.Register(manager);

                    // Store the torrent manager in our list so we can access it later
                    torrents.Add(manager);
                    manager.PeersFound += Manager_PeersFound;
                }
            }

            // If we loaded no torrents, just exist. The user can put files in the torrents directory and start
            // the client again
            if (torrents.Count == 0)
            {
                Console.WriteLine("No torrents found in the Torrents directory");
                Console.WriteLine("Exiting...");
                engine.Dispose();
                return;
            }

            // For each torrent manager we loaded and stored in our list, hook into the events
            // in the torrent manager and start the engine.
            foreach (TorrentManager manager in torrents)
            {
                manager.PeerConnected += (o, e) => {
                    lock (listener)
                        listener.WriteLine($"Connection succeeded: {e.Peer.Uri}");
                };
                manager.ConnectionAttemptFailed += (o, e) => {
                    lock (listener)
                        listener.WriteLine(
                            $"Connection failed: {e.Peer.ConnectionUri} - {e.Reason} - {e.Peer.AllowedEncryption}");
                };
                // Every time a piece is hashed, this is fired.
                manager.PieceHashed += delegate(object o, PieceHashedEventArgs e) {
                    lock (listener)
                        listener.WriteLine($"Piece Hashed: {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) {
                    lock (listener)
                        listener.WriteLine($"OldState: {e.OldState} NewState: {e.NewState}");
                };

                // Every time the tracker's state changes, this is fired
                manager.TrackerManager.AnnounceComplete += (sender, e) => {
                    listener.WriteLine($"{e.Successful}: {e.Tracker}");
                };

                // Start the torrentmanager. The file will then hash (if required) and begin downloading/seeding
                await manager.StartAsync();
            }

            // Enable automatic port forwarding. The engine will use Mono.Nat to search for
            // uPnP or NAT-PMP compatible devices and then issue port forwarding requests to it.
            await engine.EnablePortForwardingAsync(CancellationToken.None);

            // This is how to access the list of port mappings, and to see if they were
            // successful, pending or failed. If they failed it could be because the public port
            // is already in use by another computer on your network.
            foreach (var successfulMapping in engine.PortMappings.Created)
            {
            }
            foreach (var failedMapping in engine.PortMappings.Failed)
            {
            }
            foreach (var failedMapping in engine.PortMappings.Pending)
            {
            }

            // While the torrents are still running, print out some stats to the screen.
            // Details for all the loaded torrent managers are shown.
            int           i       = 0;
            bool          running = true;
            StringBuilder sb      = new StringBuilder(1024);

            while (running)
            {
                if ((i++) % 10 == 0)
                {
                    sb.Remove(0, sb.Length);
                    running = torrents.Exists(m => m.State != TorrentState.Stopped);

                    AppendFormat(sb, "Total Download Rate: {0:0.00}kB/sec", engine.TotalDownloadSpeed / 1024.0);
                    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);

                    foreach (TorrentManager manager in torrents)
                    {
                        AppendSeparator(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);
                        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));
                        AppendFormat(sb, "Tracker Status");
                        foreach (var tier in manager.TrackerManager.Tiers)
                        {
                            AppendFormat(sb, $"\t{tier.ActiveTracker} : Announce Succeeded: {tier.LastAnnounceSucceeded}. Scrape Succeeded: {tier.LastScrapeSucceeded}.");
                        }
                        if (manager.PieceManager != null)
                        {
                            AppendFormat(sb, "Current Requests:   {0}", await manager.PieceManager.CurrentRequestCountAsync());
                        }

                        foreach (PeerId p in await manager.GetPeersAsync())
                        {
                            AppendFormat(sb, "\t{2} - {1:0.00}/{3:0.00}kB/sec - {0}", p.Uri,
                                         p.Monitor.DownloadSpeed / 1024.0,
                                         p.AmRequestingPiecesCount,
                                         p.Monitor.UploadSpeed / 1024.0);
                        }

                        AppendFormat(sb, "", null);
                        if (manager.Torrent != null)
                        {
                            foreach (var file in manager.Files)
                            {
                                AppendFormat(sb, "{1:0.00}% - {0}", file.Path, file.BitField.PercentComplete);
                            }
                        }
                    }
                    Console.Clear();
                    Console.WriteLine(sb.ToString());
                    listener.ExportTo(Console.Out);
                }

                Thread.Sleep(500);
            }

            // Stop searching for uPnP or NAT-PMP compatible devices and delete
            // all mapppings which had been created.
            await engine.DisablePortForwardingAsync(CancellationToken.None);
        }
Example #19
0
        /// <summary>
        /// Downloads or seeds a file.
        /// </summary>
        /// <param name="torrent">The torrent.</param>
        /// <param name="saveDir">The full path of the directory to save the
        /// downloaded file.</param>
        /// <param name="waitHandle">Handle to wait on for the downloading to be
        /// finished. Pass null if no need to set the handle.</param>
        void StartDownload(Torrent torrent, string saveDir, EventWaitHandle waitHandle)
        {
            Logger.WriteLineIf(LogLevel.Verbose, _log_props,
                               string.Format("Starting to download torrent {0} to directory {1}",
                                             torrent.Name, saveDir));

            // When any preprocessing has been completed, you create a TorrentManager
            // which you then register with the engine.
            TorrentManager torrentManager;

            if (_fastResumeData.ContainsKey(torrent.InfoHash.ToArray()))
            {
                torrentManager = new TorrentManager(torrent, saveDir, _torrentDefaults);
                torrentManager.LoadFastResume(new FastResume((BEncodedDictionary)_fastResumeData[torrent.InfoHash.ToArray()]));
            }
            else
            {
                torrentManager = new TorrentManager(torrent, saveDir, _torrentDefaults);
            }

            _clientEngine.Register(torrentManager);

            // Every time a piece is hashed, this is fired.
            //torrentManager.PieceHashed += delegate(object o, PieceHashedEventArgs e) {
            //  Logger.WriteLineIf(LogLevel.Verbose, _log_props,
            //    string.Format("{2}: Piece Hashed: {0} - {1}", e.PieceIndex,
            //    e.HashPassed ? "Pass" : "Fail", torrentManager.Torrent.Name));
            //};

            // Every time the state changes (Stopped -> Seeding -> Downloading -> Hashing) this is fired
            torrentManager.TorrentStateChanged += delegate(object o, TorrentStateChangedEventArgs e) {
                Logger.WriteLineIf(LogLevel.Verbose, _log_props,
                                   string.Format("{0}: State changed from {1} to {2}", torrentManager.Torrent.Name,
                                                 e.OldState.ToString(), e.NewState.ToString()));

                switch (e.NewState)
                {
                case TorrentState.Downloading:
                    Logger.WriteLineIf(LogLevel.Verbose, _log_props,
                                       string.Format("OpenConnections: {0}", torrentManager.OpenConnections));
                    break;

                case TorrentState.Seeding:
                    if (e.OldState == TorrentState.Downloading)
                    {
                        Logger.WriteLineIf(LogLevel.Info, _log_props, string.Format(
                                               "{0}: Download completed.", torrentManager.Torrent.Name));
                        // Torrent statistics.
                        LogTorrentStatistics(torrentManager);
                        // Flush so that the file readers can get a hold of the file.
                        _clientEngine.DiskManager.Flush(e.TorrentManager);

                        if (waitHandle != null)
                        {
                            // Now that we have downloaded the file, we release the waitHandle.
                            waitHandle.Set();
                        }
                    }
                    break;

                default:
                    break;
                }
            };

            // Log the first time when a peer connects.
            torrentManager.PeerConnected += delegate(object sender,
                                                     PeerConnectionEventArgs e) {
                if (e.TorrentManager.OpenConnections == 1)
                {
                    Logger.WriteLineIf(LogLevel.Verbose, _log_props,
                                       string.Format("Peer ({0}) Connected. Currently 1 open connection.",
                                                     e.PeerID.Uri));
                }
            };

            // Log when the no connection left after a disconnection.
            torrentManager.PeerDisconnected += delegate(object sender,
                                                        PeerConnectionEventArgs e) {
                if (e.TorrentManager.OpenConnections == 0)
                {
                    Logger.WriteLineIf(LogLevel.Info, _log_props, string.Format(
                                           "{1}: Peer ({0}) disconnected. Message: {2}. No open connection now.",
                                           e.PeerID.Uri,
                                           e.TorrentManager.Torrent.Name,
                                           e.Message));
                }
                LogTorrentStatistics(e.TorrentManager);
            };

            torrentManager.PeersFound += delegate(object o, PeersAddedEventArgs e) {
                Logger.WriteLineIf(LogLevel.Verbose, _log_props, string.Format(
                                       "{2}: PeersFound: {0} New Peers. {1} Existing Peers.",
                                       e.NewPeers,
                                       e.ExistingPeers,
                                       e.TorrentManager.Torrent.Name));
            };

            foreach (TrackerTier tier in torrentManager.TrackerManager.TrackerTiers)
            {
                foreach (MonoTorrent.Client.Tracker.Tracker t in tier)
                {
                    t.AnnounceComplete += delegate(object sender,
                                                   AnnounceResponseEventArgs e) {
                        Logger.WriteLineIf(LogLevel.Verbose, _log_props,
                                           string.Format("{0}: AnnounceComplete. Tracker={1}, Successful={2}",
                                                         torrentManager.Torrent.Name,
                                                         e.Tracker.Uri,
                                                         e.Successful));
                        Logger.WriteLineIf(LogLevel.Verbose, _log_props, string.Format(
                                               "Tracker: Peers={2}, Complete={0}, Incomplete={1}",
                                               e.Tracker.Complete,
                                               e.Tracker.Incomplete,
                                               e.Peers.Count));
                    };
                }
            }

            // Start downloading
            torrentManager.Start();

            Logger.WriteLineIf(LogLevel.Verbose, _log_props,
                               string.Format("{0}: TorrentManager started", torrentManager.Torrent.Name));
        }
Example #20
0
        private static void StartEngine()
        {
            int     port    = 8589;
            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

            int yj  = 0;
            int yjv = 0;

            if (File.Exists("dwnspeed.tx"))
            {
                string hfg = File.ReadAllText("dwnspeed.tx");

                yjv = int.Parse(hfg);
            }
            if (File.Exists("uplspeed.tx"))
            {
                string hfg = File.ReadAllText("uplspeed.tx");

                yj = int.Parse(hfg);
            }

            TorrentSettings torrentDefaults = new TorrentSettings(100, 150, yjv, yj);

            // 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();
            }

            // For each file in the torrents path that is a .torrent file, load it into the engine.
            foreach (string file in Directory.GetFiles(torrentsPath))
            {
                if (file.EndsWith(".torrent"))
                {
                    try
                    {
                        // Load the .torrent from the file into a Torrent instance
                        // You can use this to do preprocessing should you need to
                        torrent = Torrent.Load(file);
                        Console.WriteLine(torrent.InfoHash.ToString());
                    }
                    catch (Exception e)
                    {
                        Console.Write("Couldn't decode {0}: ", file);
                        Console.WriteLine(e.Message);
                        continue;
                    }
                    // 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);
                }
            }

            // If we loaded no torrents, just exist. The user can put files in the torrents directory and start
            // the client again
            if (torrents.Count == 0)
            {
                Console.WriteLine("No torrents found in the Torrents directory");
                Console.WriteLine("Exiting...");
                engine.Dispose();
                return;
            }

            // For each torrent manager we loaded and stored in our list, hook into the events
            // in the torrent manager and start the engine.
            foreach (TorrentManager manager in torrents)
            {
                // Every time a piece is hashed, this is fired.
                manager.PieceHashed += delegate(object o, PieceHashedEventArgs e) {
                    lock (listener)
                        listener.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) {
                    lock (listener)
                        listener.WriteLine("OldState: " + e.OldState.ToString() + " NewState: " + e.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.
            int           i       = 0;
            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); });
                    foreach (TorrentManager manager in torrents)
                    {
                        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);
                        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);
                            }
                        }
                    }
                    AppendFormat(sb, "Total Download Rate: {0:0.00}kB/sec", engine.TotalDownloadSpeed / 1024.0);
                    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);


                    Console.Clear();
                    Console.WriteLine(sb.ToString());
                    listener.ExportTo(Console.Out);
                }

                System.Threading.Thread.Sleep(500);
            }
        }
        private static async Task StartEngine()
        {
            int     port;
            Torrent torrent = null;

            // Ask the user what port they want to use for incoming connections
            Console.Write($"{Environment.NewLine}Choose a listen port: ");
            while (!Int32.TryParse(Console.ReadLine(), out port))
            {
            }

            // 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
            {
                SavePath   = downloadsPath,
                ListenPort = port
            };

            //engineSettings.GlobalMaxUploadSpeed = 30 * 1024;
            //engineSettings.GlobalMaxDownloadSpeed = 100 * 1024;
            //engineSettings.MaxReadRate = 1 * 1024 * 1024;

            // Create the default settings which a torrent will have.
            TorrentSettings torrentDefaults = new TorrentSettings();

            // Create an instance of the engine.
            engine = new ClientEngine(engineSettings);



            byte[] nodes = Array.Empty <byte>();
            try
            {
                if (File.Exists(dhtNodeFile))
                {
                    nodes = File.ReadAllBytes(dhtNodeFile);
                }
            }
            catch
            {
                Console.WriteLine("No existing dht nodes could be loaded");
            }

            DhtEngine dht = new DhtEngine(new IPEndPoint(IPAddress.Any, port));
            await engine.RegisterDhtAsync(dht);

            // This starts the Dht engine but does not wait for the full initialization to
            // complete. This is because it can take up to 2 minutes to bootstrap, depending
            // on how many nodes time out when they are contacted.
            await engine.DhtEngine.StartAsync(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 = new BEncodedDictionary();

            try
            {
                if (File.Exists(fastResumeFile))
                {
                    fastResume = BEncodedValue.Decode <BEncodedDictionary>(File.ReadAllBytes(fastResumeFile));
                }
            }
            catch
            {
            }

            /*byte[] bytes;
             * string mlstr = Console.ReadLine();
             * if (mlstr=="")
             * {
             *  bytes = TCreator.GetBytesFromFile(@"C:\Users\eivar\Desktop\New folder\TemporaryExport\bin\Debug\netcoreapp3.0\Downloads\[Sakurato.Sub][Digimon Adventure][03][BIG5][1080P][V2].mp4");
             *  torrent = TCreator.GetTorrentFromByte(bytes);
             *  File.WriteAllBytes("torr.txt", bytes);
             * }
             * else
             * {
             *  //bytes = File.ReadAllBytes("torr.txt");
             *  //torrent = TCreator.GetTorrentFromByte(bytes);
             * }*/


            //Console.WriteLine(mlstr);



            //TorrentManager Tmanager = new TorrentManager(torrent, downloadsPath, torrentDefaults);

            /*if (fastResume.ContainsKey(torrent.InfoHash.ToHex()))
             *  Tmanager.LoadFastResume(new FastResume((BEncodedDictionary)fastResume[torrent.InfoHash.ToHex()]));*/
            //await engine.Register(Tmanager);
            //torrents.Add(Tmanager);

            // Store the torrent manager in our list so we can access it later
            //Tmanager.PeersFound += Manager_PeersFound;

            // For each file in the torrents path that is a .torrent file, load it into the engine.
            foreach (string file in Directory.GetFiles(torrentsPath))
            {
                if (file.EndsWith(".torrent", StringComparison.OrdinalIgnoreCase))
                {
                    try
                    {
                        // Load the .torrent from the file into a Torrent instance
                        // You can use this to do preprocessing should you need to

                        torrent = await Torrent.LoadAsync(file);

                        Console.WriteLine(torrent.InfoHash.ToString());
                    }
                    catch (Exception e)
                    {
                        Console.Write("Couldn't decode {0}: ", file);
                        Console.WriteLine(e.Message);
                        continue;
                    }
                    // 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()]));
                    }
                    await engine.Register(manager);

                    // Store the torrent manager in our list so we can access it later
                    torrents.Add(manager);
                    manager.PeersFound += Manager_PeersFound;
                }
            }

            // If we loaded no torrents, just exist. The user can put files in the torrents directory and start
            // the client again
            if (torrents.Count == 0)
            {
                Console.WriteLine("No torrents found in the Torrents directory");
                Console.WriteLine("Exiting...");
                engine.Dispose();
                return;
            }

            // For each torrent manager we loaded and stored in our list, hook into the events
            // in the torrent manager and start the engine.
            foreach (TorrentManager manager in torrents)
            {
                manager.PeerConnected += (o, e) => {
                    lock (listener)
                        listener.WriteLine($"Connection succeeded: {e.Peer.Uri}");
                };
                manager.ConnectionAttemptFailed += (o, e) => {
                    lock (listener)
                        listener.WriteLine(
                            $"Connection failed: {e.Peer.ConnectionUri} - {e.Reason} - {e.Peer.AllowedEncryption}");
                };
                // Every time a piece is hashed, this is fired.
                manager.PieceHashed += delegate(object o, PieceHashedEventArgs e) {
                    lock (listener)
                        listener.WriteLine($"Piece Hashed: {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) {
                    lock (listener)
                        listener.WriteLine($"OldState: {e.OldState} NewState: {e.NewState}");
                };

                // Every time the tracker's state changes, this is fired
                manager.TrackerManager.AnnounceComplete += (sender, e) => {
                    listener.WriteLine($"{e.Successful}: {e.Tracker}");
                };

                // Start the torrentmanager. The file will then hash (if required) and begin downloading/seeding
                await manager.StartAsync();
            }

            // Enable automatic port forwarding. The engine will use Mono.Nat to search for
            // uPnP or NAT-PMP compatible devices and then issue port forwarding requests to it.
            await engine.EnablePortForwardingAsync(CancellationToken.None);

            // This is how to access the list of port mappings, and to see if they were
            // successful, pending or failed. If they failed it could be because the public port
            // is already in use by another computer on your network.
            foreach (var successfulMapping in engine.PortMappings.Created)
            {
            }
            foreach (var failedMapping in engine.PortMappings.Failed)
            {
            }
            foreach (var failedMapping in engine.PortMappings.Pending)
            {
            }

            // While the torrents are still running, print out some stats to the screen.
            // Details for all the loaded torrent managers are shown.
            int           i       = 0;
            bool          running = true;
            StringBuilder sb      = new StringBuilder(1024);

            while (running)
            {
                await ConsoleFeedBack(sb, running, i);
            }

            // Stop searching for uPnP or NAT-PMP compatible devices and delete
            // all mapppings which had been created.
            await engine.DisablePortForwardingAsync(CancellationToken.None);
        }
Example #22
0
        public async Task RunAsync()
        {
            //LoggerFactory.Creator = className => new TextLogger (Console.Out, className);

            var seederWriter = new MemoryWriter(new NullWriter(), DataSize);
            int port         = 37827;
            var seeder       = new ClientEngine(
                new EngineSettingsBuilder {
                AllowedEncryption = new[] { EncryptionType.PlainText },
                ListenPort        = port++
            }.ToSettings(),
                seederWriter
                );

            var downloaders = Enumerable.Range(port, 16).Select(p => {
                return(new ClientEngine(
                           new EngineSettingsBuilder {
                    ListenPort = p, AllowedEncryption = new[] { EncryptionType.PlainText }
                }.ToSettings(),
                           new MemoryWriter(new NullWriter(), DataSize)
                           ));
            }).ToArray();

            Directory.CreateDirectory(DataDir);
            // Generate some fake data on-disk
            var buffer = Enumerable.Range(0, 16 * 1024).Select(s => (byte)s).ToArray();

            using (var fileStream = File.OpenWrite(Path.Combine(DataDir, "file.data"))) {
                for (int i = 0; i < DataSize / buffer.Length; i++)
                {
                    fileStream.Write(buffer, 0, buffer.Length);
                }
                fileStream.SetLength(DataSize);
            }

            var trackerListener = TrackerListenerFactory.CreateHttp(IPAddress.Parse("127.0.0.1"), 25611);
            var tracker         = new MonoTorrent.Tracker.TrackerServer {
                AllowUnregisteredTorrents = true
            };

            tracker.RegisterListener(trackerListener);
            trackerListener.Start();

            // Create the torrent file for the fake data
            var creator = new TorrentCreator();

            creator.Announces.Add(new List <string> ());
            creator.Announces [0].Add("http://127.0.0.1:25611/announce");

            var metadata = await creator.CreateAsync(new TorrentFileSource (DataDir));

            // Set up the seeder
            await seeder.Register(new TorrentManager (Torrent.Load(metadata), DataDir, new TorrentSettingsBuilder {
                UploadSlots = 20
            }.ToSettings()));

            using (var fileStream = File.OpenRead(Path.Combine(DataDir, "file.data"))) {
                while (fileStream.Position < fileStream.Length)
                {
                    var dataRead = new byte[16 * 1024];
                    int offset   = (int)fileStream.Position;
                    int read     = fileStream.Read(dataRead, 0, dataRead.Length);
                    await seederWriter.WriteAsync(seeder.Torrents[0].Files[0], offset, dataRead, 0, read);
                }
            }

            await seeder.StartAllAsync();

            List <Task> tasks = new List <Task> ();

            for (int i = 0; i < downloaders.Length; i++)
            {
                await downloaders[i].Register(new TorrentManager(
                                                  Torrent.Load(metadata),
                                                  Path.Combine(DataDir, "Downloader" + i)
                                                  ));

                tasks.Add(RepeatDownload(downloaders[i]));
            }

            while (true)
            {
                long downTotal        = seeder.TotalDownloadSpeed;
                long upTotal          = seeder.TotalUploadSpeed;
                long totalConnections = 0;
                long dataDown         = seeder.Torrents[0].Monitor.DataBytesDownloaded + seeder.Torrents[0].Monitor.ProtocolBytesDownloaded;
                long dataUp           = seeder.Torrents[0].Monitor.DataBytesUploaded + seeder.Torrents[0].Monitor.ProtocolBytesUploaded;
                foreach (var engine in downloaders)
                {
                    downTotal += engine.TotalDownloadSpeed;
                    upTotal   += engine.TotalUploadSpeed;

                    dataDown         += engine.Torrents[0].Monitor.DataBytesDownloaded + engine.Torrents[0].Monitor.ProtocolBytesDownloaded;
                    dataUp           += engine.Torrents[0].Monitor.DataBytesUploaded + engine.Torrents[0].Monitor.ProtocolBytesUploaded;
                    totalConnections += engine.ConnectionManager.OpenConnections;
                }
                Console.Clear();
                Console.WriteLine($"Speed Down:        {downTotal / 1024 / 1024}MB.");
                Console.WriteLine($"Speed Up:          {upTotal / 1024 / 1024}MB.");
                Console.WriteLine($"Data Down:          {dataDown / 1024 / 1024}MB.");
                Console.WriteLine($"Data Up:            {dataUp / 1024 / 1024}MB.");

                Console.WriteLine($"Total Connections: {totalConnections}");
                await Task.Delay(3000);
            }
        }
Example #23
0
        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();
                }
            }
        }
Example #24
0
        //method to add torrent to torrent engine. source can be magnetic uri or .torrent file
        public async Task addTorrent(string torrentFilePath, string torrentFileName)
        {
            Debug.WriteLine("adding:{0}", torrentFilePath);
            TorrentInfoModel torinfo = new TorrentInfoModel();

            Torrent torrent = null;

            if (String.IsNullOrEmpty(torrentFilePath))
            {
                Console.WriteLine("empty file path!");
                return;
            }
            if (torrentFilePath.EndsWith(".torrent", StringComparison.OrdinalIgnoreCase))
            {
                try
                {
                    torrent = await Torrent.LoadAsync(torrentFilePath);

                    Console.WriteLine("info hash = {0}", torrent.InfoHash.ToString());
                }
                catch (Exception e)
                {
                    Console.Write("Couldnot decode {0}: ", torrentFilePath);
                    Console.WriteLine(e.Message);
                    return;
                }
                TorrentManager manager = new TorrentManager(torrent, downloadsPath, new TorrentSettings());
                if (fastResume.ContainsKey(torrent.InfoHash.ToHex()))
                {
                    manager.LoadFastResume(new FastResume((BEncodedDictionary)fastResume[torrent.InfoHash.ToHex()]));
                }
                await engine.Register(manager);

                //add to torrent global list.
                Debug.WriteLine("added to list:{0}", torrentFilePath);
                manager.PeersFound += Manager_PeersFound;


                //save .torrent to torrent path to restore.
                string destPath = Path.Combine(torrentsPath, torrentFileName);
                destPath.Replace(' ', '_');
                torinfo.manager         = manager;
                torinfo.torrentFileName = torrentFileName;// destPath;
                torinfo.status          = "downlaoding";
                torinfo.imageUrl        = "none";
                torinfo.dateAdded       = DateTime.Now.ToString();
                torinfo.speedUp         = "";
                torinfo.speedDl         = "";
                torinfo.progress        = "";
                torinfo.WriteToFile();
                //writeTorrentInfoToFile(torinfo);
                System.IO.File.Copy(torrentFilePath, destPath, true);
                TorrentInfoList.Add(torinfo);
                initTorrentEvents(torinfo);
                DoTorrentAction(torinfo, TorrentAction.START);
                Console.WriteLine("Torrent Size={0}", manager.Torrent.Size);
                Console.WriteLine("Torrent Name= {0}", torinfo.manager.Torrent.Name);
                if (!monitorTimer.Enabled)//start monitor if not started already.
                {
                    monitorTimer.Enabled = true;
                }
                Debug.WriteLine("started:{0}", torrentFilePath);
            }
            return;
        }
Example #25
0
        public TorrentManager addTorrent(string torrentPath, bool startTorrent, bool moveToStorage, bool removeOriginal, TorrentSettings savedSettings, string savePath, bool isUrl)
        {
            Torrent        torrent;
            Torrent        torrentCheck;
            TorrentManager manager;
            string         newPath;

            if (!Directory.Exists(savePath))
            {
                throw new TorrentException("Torrent save path does not exist, " + savePath);
            }

            if (!isUrl && !File.Exists(torrentPath))
            {
                throw new TorrentException("Torrent path does not exist, " + torrentPath);
            }

            // Check to see if Torrent is valid
            if (!isUrl && !Torrent.TryLoad(torrentPath, out torrentCheck))
            {
                logger.Error("Failed to add torrent, " + Path.GetFileName(torrentPath) + " is not valid.");
                throw new TorrentException("Failed to add torrent, " + Path.GetFileName(torrentPath) + " is not valid.");
            }
            else if (isUrl && !Torrent.TryLoad(new System.Uri(torrentPath), Path.Combine(prefSettings.TorrentStorageLocation, Path.GetFileName(torrentPath)), out torrentCheck))
            {
                logger.Error("Failed to add URL, " + torrentPath + " is not valid.");
                throw new TorrentException("Failed to add URL, " + torrentPath + " is not valid.");
            }

            // Check to see if torrent already exists
            if (engine.Contains(torrentCheck))
            {
                logger.Error("Failed to add torrent, " + torrentCheck.Name + " already exists.");
                throw new TorrentException("Failed to add torrent, " + torrentCheck.Name + " already exists.");
            }

            // Move torrent to storage folder
            if (!isUrl && moveToStorage && (prefSettings.TorrentStorageLocation != Directory.GetParent(torrentPath).ToString()))
            {
                newPath = Path.Combine(prefSettings.TorrentStorageLocation, Path.GetFileName(torrentPath));
                logger.Debug("Copying torrent to " + newPath);
                File.Copy(torrentPath, newPath, true);

                if (removeOriginal)
                {
                    logger.Info("Deleting original torrent " + torrentPath);
                    try{
                        File.Delete(torrentPath);
                    } catch {
                        logger.Error("Unable to delete " + Path.GetFileName(torrentPath) + ".");
                        throw new Exception("Unable to delete " + Path.GetFileName(torrentPath) + ".");
                    }
                }
            }
            else
            {
                newPath = torrentPath;
            }



            // Load and register torrent
            if (!isUrl && !Torrent.TryLoad(newPath, out torrent))
            {
                logger.Error("Failed to register " + Path.GetFileName(newPath));
                throw new TorrentException("Failed to register " + Path.GetFileName(newPath));
            }
            else if (isUrl && !Torrent.TryLoad(new System.Uri(newPath), Path.Combine(prefSettings.TorrentStorageLocation, Path.GetFileName(newPath)), out torrent))
            {
                logger.Error("Failed to register " + newPath);
                throw new TorrentException("Failed to register " + newPath);
            }

            if (savedSettings == null)
            {
                manager = new TorrentManager(torrent, savePath, (TorrentSettings)torrentSettings.Clone());
            }
            else
            {
                manager = new TorrentManager(torrent, savePath, savedSettings);
            }

            engine.Register(manager);

            torrents.Add(manager, torrentListStore.AppendValues(manager));
            allTorrents.Add(manager);

            if (startTorrent)
            {
                logger.Info("Auto starting torrent " + manager.Torrent.Name);
                manager.Start();
                // Add to label
                if (manager.State == TorrentState.Downloading)
                {
                    mainWindow.DownloadingLabel.AddTorrent(manager);
                }
                else if (manager.State == TorrentState.Seeding)
                {
                    mainWindow.SeedingLabel.AddTorrent(manager);
                }
            }

            logger.Info("Added torrent " + manager.Torrent.Name);

            manager.TorrentStateChanged         += OnTorrentStateChanged;
            manager.PieceManager.BlockRequested += OnBlockRequested;
            manager.PieceHashed += OnPieceHashed;

            // add to "All" label
            mainWindow.AllLabel.AddTorrent(manager);

            return(manager);
        }
Example #26
0
        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)
            {
            }
        }
 public EngineTestRig(string savePath, int piecelength = 256*1024, PieceWriter writer = null)
 {
     if (writer == null)
         writer = new MemoryWriter(new NullWriter());
     _listener = new CustomListener();
     _engine = new ClientEngine(new EngineSettings(), _listener, writer);
     _torrentDict = CreateTorrent(piecelength);
     _torrent = Torrent.Load(_torrentDict);
     _manager = new TorrentManager(_torrent, savePath, new TorrentSettings());
     _engine.Register(_manager);
     //manager.Start();
 }
Example #28
0
        /// <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; }
        }
Example #29
0
        private static async Task StartEngine()
        {
            int     port    = 7878;
            Torrent torrent = null;

            EngineSettings engineSettings = new EngineSettings
            {
                SavePath   = downloadsPath,
                ListenPort = port
            };

            TorrentSettings torrentDefaults = new TorrentSettings();

            engine = new ClientEngine(engineSettings);

            byte[] nodes = Array.Empty <byte>();
            try
            {
                if (File.Exists(dhtNodeFile))
                {
                    nodes = File.ReadAllBytes(dhtNodeFile);
                }
            }
            catch
            {
                Console.WriteLine("No existing dht nodes could be loaded");
            }

            DhtEngine dht = new DhtEngine(new IPEndPoint(IPAddress.Any, port));
            await engine.RegisterDhtAsync(dht);

            await engine.DhtEngine.StartAsync(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 = new BEncodedDictionary();

            try
            {
                if (File.Exists(fastResumeFile))
                {
                    fastResume = BEncodedValue.Decode <BEncodedDictionary>(File.ReadAllBytes(fastResumeFile));
                }
            }
            catch
            {
            }


            try
            {
                torrent = await Torrent.LoadAsync(torrentFilePath);

                Console.WriteLine(torrent.InfoHash.ToString());
            }
            catch (Exception e)
            {
                Console.Write("Couldn't decode {0}: ", torrentFilePath);
                Console.WriteLine(e.Message);
            }

            TorrentManager manager = new TorrentManager(torrent, downloadsPath, torrentDefaults);

            if (fastResume.ContainsKey(torrent.InfoHash.ToHex()))
            {
                manager.LoadFastResume(new FastResume((BEncodedDictionary)fastResume[torrent.InfoHash.ToHex()]));
            }
            await engine.Register(manager);

            torrents.Add(manager);


            if (torrents.Count == 0)
            {
                Console.WriteLine("No torrents found in the Torrents directory");
                Console.WriteLine("Exiting...");
                engine.Dispose();
                return;
            }

            foreach (TorrentManager t in torrents)
            {
                await t.StartAsync();
            }

            int           i       = 0;
            bool          running = true;
            StringBuilder sb      = new StringBuilder(1024);

            while (running)
            {
                if ((i++) % 10 == 0)
                {
                    sb.Remove(0, sb.Length);
                    running = torrents.Exists(m => m.State != TorrentState.Stopped);

                    foreach (TorrentManager t in torrents)
                    {
                        if (manager.Torrent != null)
                        {
                            foreach (TorrentFile file in manager.Torrent.Files)
                            {
                                AppendFormat(sb, "{1:0.00}% - {0}", file.Path, file.BitField.PercentComplete);
                            }
                        }
                    }
                    Console.WriteLine(sb.ToString());
                }

                Thread.Sleep(500);
            }
        }
Example #30
0
        private async Task StartEngine()
        {
            int     port    = 5200;
            Torrent torrent = null;
            // Ask the user what port they want to use for incoming connections
            // 询问用户要将使用哪个端口用于连接
            //Console.Write ($"{Environment.NewLine} 选择监听的端口: ");
            //while (!Int32.TryParse (Console.ReadLine (), out port)) { }

            // 创建一个引擎的默认配置
            // downloadsPath - 文件下载的目录
            // port - 引擎监听的端口
            EngineSettings engineSettings = new EngineSettings {
                SavePath   = downloadsPath,
                ListenPort = port
            };

            //engineSettings.GlobalMaxUploadSpeed = 30 * 1024;
            //engineSettings.GlobalMaxDownloadSpeed = 100 * 1024;
            //engineSettings.MaxReadRate = 1 * 1024 * 1024;

            // 创建一个 Torrent 默认的配置信息.
            TorrentSettings torrentDefaults = new TorrentSettings();

            // 创建一个客户端引擎.
            engine = new ClientEngine(engineSettings);

            byte[] nodes = Array.Empty <byte> ();
            try {
                if (File.Exists(dhtNodeFile))
                {
                    nodes = File.ReadAllBytes(dhtNodeFile);
                }
            } catch {
                Console.WriteLine("无法加载任何现有DHT节点.");
            }

            DhtEngine dht = new DhtEngine(new IPEndPoint(IPAddress.Any, port));
            await engine.RegisterDhtAsync(dht);

            // 这将启动Dht引擎,但不会等待完全初始化完成.
            // 这是因为根据连接节点时超时的数量,启动最多需要2分钟.
            await engine.DhtEngine.StartAsync(nodes);

            // 如果下载路径不存在,则创建.
            if (!Directory.Exists(engine.Settings.SavePath))
            {
                Directory.CreateDirectory(engine.Settings.SavePath);
            }

            // 如果Torrent存储目录不存在,则创建.
            if (!Directory.Exists(torrentsPath))
            {
                Directory.CreateDirectory(torrentsPath);
            }

            BEncodedDictionary fastResume = new BEncodedDictionary();

            try {
                if (File.Exists(fastResumeFile))
                {
                    fastResume = BEncodedValue.Decode <BEncodedDictionary> (File.ReadAllBytes(fastResumeFile));
                }
            } catch {
            }

            // 将Torrents目录中的每个 torrent 文件将其加载到引擎中.
            foreach (string file in Directory.GetFiles(torrentsPath))
            {
                if (file.EndsWith(".torrent", StringComparison.OrdinalIgnoreCase))
                {
                    try {
                        // 加载torrent文件到Torrent实例中,如果需要的话,可以使用它进行预处理
                        torrent = await Torrent.LoadAsync(file);

                        Console.WriteLine(torrent.InfoHash.ToString());
                    } catch (Exception e) {
                        Console.Write("Couldn't decode {0}: ", file);
                        Console.WriteLine(e.Message);
                        continue;
                    }
                    // 当任何预处理完成后,您将创建一个TorrentManager,然后在引擎上创建它.
                    TorrentManager manager = new TorrentManager(torrent, downloadsPath, torrentDefaults);
                    if (fastResume.ContainsKey(torrent.InfoHash.ToHex()))
                    {
                        manager.LoadFastResume(new FastResume((BEncodedDictionary)fastResume[torrent.InfoHash.ToHex()]));
                    }
                    await engine.Register(manager);

                    // 将 TorrentManager 存储在列表中,方便以后访问它.
                    torrents.Add(manager);
                    manager.PeersFound += Manager_PeersFound;
                }
            }

            // If we loaded no torrents, just exist. The user can put files in the torrents directory and start the client again
            if (torrents.Count == 0)
            {
                Console.WriteLine("没有在目录中找到 torrent 文件");
                Console.WriteLine("退出...");
                engine.Dispose();
                return;
            }

            // 遍历存储在列表中的每个TorrentManager,在TorrentManager中连接到事件并启动引擎。
            foreach (TorrentManager manager in torrents)
            {
                manager.PeerConnected += (o, e) => {
                    lock (listener)
                        listener.WriteLine($"连接成功: {e.Peer.Uri}");
                };
                manager.ConnectionAttemptFailed += (o, e) => {
                    lock (listener)
                        listener.WriteLine(
                            $"连接失败: {e.Peer.ConnectionUri} - {e.Reason} - {e.Peer.AllowedEncryption}");
                };
                // 每次散列一个片段,就会触发这个.
                manager.PieceHashed += delegate(object o, PieceHashedEventArgs e) {
                    lock (listener)
                        listener.WriteLine($"散列的片段: {e.PieceIndex} - {(e.HashPassed ? "Pass" : "Fail")}");
                };

                // 每当状态改变时触发 (Stopped -> Seeding -> Downloading -> Hashing)
                manager.TorrentStateChanged += delegate(object o, TorrentStateChangedEventArgs e) {
                    lock (listener)
                        listener.WriteLine($"旧状态: {e.OldState} 新状态: {e.NewState}");
                };

                // 每当跟踪器的状态改变时,就会触发.
                manager.TrackerManager.AnnounceComplete += (sender, e) => {
                    listener.WriteLine($"{e.Successful}: {e.Tracker}");
                };

                // 开始运行TorrentManager.
                // 然后文件将散列(如果需要)并开始下载/发送.
                await manager.StartAsync();
            }

            // Enable automatic port forwarding. The engine will use Mono.Nat to search for
            // uPnP or NAT-PMP compatible devices and then issue port forwarding requests to it.
            await engine.EnablePortForwardingAsync(CancellationToken.None);

            // This is how to access the list of port mappings, and to see if they were
            // successful, pending or failed. If they failed it could be because the public port
            // is already in use by another computer on your network.
            foreach (var successfulMapping in engine.PortMappings.Created)
            {
            }
            foreach (var failedMapping in engine.PortMappings.Failed)
            {
            }
            foreach (var failedMapping in engine.PortMappings.Pending)
            {
            }

            // While the torrents are still running, print out some stats to the screen.
            // Details for all the loaded torrent managers are shown.
            int           i       = 0;
            bool          running = true;
            StringBuilder sb      = new StringBuilder(1024);

            while (running)
            {
                if ((i++) % 10 == 0)
                {
                    sb.Remove(0, sb.Length);
                    running = torrents.Exists(m => m.State != TorrentState.Stopped);

                    AppendFormat(sb, "总下载速度: {0:0.00}kB/sec", engine.TotalDownloadSpeed / 1024.0);
                    AppendFormat(sb, "总上传速度:   {0:0.00}kB/sec", engine.TotalUploadSpeed / 1024.0);
                    AppendFormat(sb, "磁盘读速度:      {0:0.00} kB/s", engine.DiskManager.ReadRate / 1024.0);
                    AppendFormat(sb, "磁盘写速度:     {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);

                    foreach (TorrentManager manager in torrents)
                    {
                        AppendSeparator(sb);
                        AppendFormat(sb, "状态:           {0}", manager.State);
                        AppendFormat(sb, "名称:            {0}", manager.Torrent == null ? "MetaDataMode" : manager.Torrent.Name);
                        AppendFormat(sb, "进度:           {0:0.00}", manager.Progress);
                        AppendFormat(sb, "下载速度:     {0:0.00} kB/s", manager.Monitor.DownloadSpeed / 1024.0);
                        AppendFormat(sb, "上传速度:       {0:0.00} kB/s", manager.Monitor.UploadSpeed / 1024.0);
                        AppendFormat(sb, "下载量:   {0:0.00} MB", manager.Monitor.DataBytesDownloaded / (1024.0 * 1024.0));
                        AppendFormat(sb, "上传量:     {0:0.00} MB", manager.Monitor.DataBytesUploaded / (1024.0 * 1024.0));
                        AppendFormat(sb, "Tracker Status");
                        foreach (var tier in manager.TrackerManager.Tiers)
                        {
                            AppendFormat(sb, $"\t{tier.ActiveTracker} : Announce Succeeded: {tier.LastAnnounceSucceeded}. Scrape Succeeded: {tier.LastScrapSucceeded}.");
                        }
                        if (manager.PieceManager != null)
                        {
                            AppendFormat(sb, "当前请求:   {0}", await manager.PieceManager.CurrentRequestCountAsync());
                        }

                        foreach (PeerId p in await manager.GetPeersAsync())
                        {
                            AppendFormat(sb, "\t{2} - {1:0.00}/{3:0.00}kB/sec - {0}", p.Uri,
                                         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);
                }

                Thread.Sleep(500);
            }

            // 停止搜索与uPnP或NAT-PMP兼容的设备,并删除所有已创建的映射.
            await engine.DisablePortForwardingAsync(CancellationToken.None);
        }
Example #31
0
        //-------------------------------------------------------------
        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);
            }
        }