예제 #1
0
        protected string Add(Torrent torrent, string outputDirectoryPath)
        {
            // Create the torrent manager.
            var torrentManager = new TorrentManager(torrent, outputDirectoryPath, DefaultTorrentSettings, "");

            // Setup fast resume.
            if (FastResume.ContainsKey(torrent.InfoHash.ToHex()))
            {
                torrentManager.LoadFastResume(new FastResume((BEncodedDictionary)FastResume [torrent.InfoHash.ToHex()]));
            }

            // Add to mappings cache.
            TorrentMappingsCache.RemoveAll(tmc => tmc.InfoHash == torrent.InfoHash.ToString());
            TorrentMappingsCache.Add(new TorrentMapping
            {
                InfoHash            = torrent.InfoHash.ToString(),
                OutputDirectoryPath = outputDirectoryPath
            });
            TorrentMappingsCache.Save();

            // Register and start.
            Engine.Register(torrentManager);
            torrentManager.Start();

            // Return Id.
            return(torrentManager.InfoHash.ToString());
        }
예제 #2
0
        public void Setup()
        {
            int pieceCount  = 40;
            int pieceLength = 256 * 1024;
            var torrentData = new TestTorrentData {
                Files       = TorrentFileInfo.Create(pieceLength, ("File", pieceLength * pieceCount, "full/path/File")),
                PieceLength = pieceLength,
                Size        = pieceLength * pieceCount
            };

            peers = new List <PeerId> ();

            torrentManager = TestRig.CreateSingleFileManager(torrentData.Size, torrentData.PieceLength);
            torrentManager.LoadFastResume(new FastResume(torrentManager.InfoHash, new BitField(pieceCount).SetAll(true), new BitField(pieceCount).SetAll(false)));

            manager = new PieceManager(torrentManager);
            manager.Initialise();

            peer = PeerId.CreateNull(pieceCount);
            for (int i = 0; i < 20; i++)
            {
                PeerId p = PeerId.CreateNull(pieceCount);
                p.SupportsFastPeer = true;
                peers.Add(p);
            }
        }
예제 #3
0
        public void Setup()
        {
            int pieceCount  = 40;
            int pieceLength = 256 * 1024;

            bitfield    = new BitField(pieceCount);
            torrentData = new TestTorrentData {
                Files       = new[] { new TorrentFileInfo(new TorrentFile("File", pieceLength * pieceCount)) },
                PieceLength = pieceLength,
                Size        = pieceLength * pieceCount
            };
            peers = new List <PeerId> ();

            torrentManager = TestRig.CreateSingleFileManager(torrentData.Size, torrentData.PieceLength);
            torrentManager.LoadFastResume(new FastResume(torrentManager.InfoHash, new BitField(pieceCount).SetAll(true), new BitField(pieceCount).SetAll(false)));
            manager = new PieceManager(torrentManager);
            manager.ChangePicker(new StandardPicker(), bitfield);
            manager.Picker.Initialise(bitfield, torrentData, Enumerable.Empty <Piece> ());

            peer = PeerId.CreateNull(pieceCount);
            for (int i = 0; i < 20; i++)
            {
                PeerId p = PeerId.CreateNull(pieceCount);
                p.SupportsFastPeer = true;
                peers.Add(p);
            }
        }
예제 #4
0
        private void Assign()
        {
            TM.PieceHashed += (a, b) =>
            {
                //if the PieceMap is null, this was a magnet link torrent but we know the map now
                if (PieceMap == null)
                {
                    PieceMap = new bool[TM.Torrent.Pieces.Count];
                }
                lock (PieceMap)
                {
                    PieceMap[b.PieceIndex] = b.HashPassed;
                }
                PiecemapUpdate(this, new PiecemapEventArgs(Map, b.PieceIndex));
            };
            TM.PieceManager.BlockReceived += (a, b) =>
            {
                PieceMap[b.Piece.Index] = true;
                PiecemapUpdate(this, new PiecemapEventArgs(Map, b.Piece.Index));
            };

            var RecoveryFile = Environment.ExpandEnvironmentVariables(TORRENT_DIR + $"\\{TM.InfoHash.ToHex()}.rec");

            if (File.Exists(RecoveryFile))
            {
                TM.LoadFastResume(new FastResume((BEncodedDictionary)BEncodedDictionary.Decode(File.ReadAllBytes(RecoveryFile))));
            }

            CE.Register(TM);
        }
예제 #5
0
        public async Task initDownloadMan()
        {
            string  torFilePath;
            Torrent torrent = null;
            bool    tmp     = false;

            /*Load fast resume file*/
            try
            {
                if (File.Exists(fastResumeFile))
                {
                    fastResume = BEncodedValue.Decode <BEncodedDictionary>(File.ReadAllBytes(fastResumeFile));
                }
            }
            catch
            {
                Debug.WriteLine("error here");
            }
            /*open torrentfile dir and load all the torrents*/
            if (System.IO.Directory.Exists(torrentsInfoPath))
            {
                string[] movies = System.IO.Directory.GetFiles(torrentsInfoPath);
                foreach (string m in movies)
                {
                    TorrentInfoModel torInfo = new TorrentInfoModel();
                    torInfo.ReadFromFile(m);
                    //readTorrentInfoFromFile(torInfo, m);
                    torFilePath = Path.Combine(torrentsPath, torInfo.torrentFileName);
                    if (System.IO.File.Exists(torFilePath))
                    {
                        Console.WriteLine("adding f= {0}", torFilePath);
                        torrent = await Torrent.LoadAsync(torFilePath);

                        TorrentManager manager = new TorrentManager(torrent, downloadsPath, new TorrentSettings());
                        manager.LoadFastResume(new FastResume((BEncodedDictionary)fastResume[torrent.InfoHash.ToHex()]));
                        await engine.Register(manager);

                        torInfo.manager         = manager;
                        torInfo.torrentFileName = torFilePath;
                        TorrentInfoList.Add(torInfo);
                        if (torInfo.status == TorrentState.Downloading.ToString())
                        {
                            await manager.StartAsync();
                        }
                        initTorrentEvents(torInfo); // hook all the events
                        tmp = true;
                    }
                }
                if (tmp)
                {
                    monitorTimer.Enabled = true;
                }
                Debug.WriteLine("torrent init exit!");
                //await engine.StartAllAsync();
            }
        }
예제 #6
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();
        }
예제 #7
0
        internal void SeedTorrents(List <string> torrentPaths)
        {
            this.engineState = EngineState.Seeding;
            this.StartDht(this.engine, Properties.Settings.Default.listenPort);
            this.managers.Clear();
            this.torrents.Clear();
            this.torrentPaths = torrentPaths;

            string             fastResumeFile = Path.Combine(this.parent.localAppDataFolder, "fastresume.data");
            BEncodedDictionary fastResume;

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

            foreach (string filePath in torrentPaths)
            {
                Torrent torrent = null;
                try { torrent = Torrent.Load(filePath); }
                catch (Exception e) { Console.WriteLine(e); debug(e.ToString()); continue; }
                this.torrents.Add(torrent);
                Console.WriteLine(Properties.Settings.Default.seedRate);
                TorrentSettings settings = new TorrentSettings(10, 50, 0, this.engine.Settings.GlobalMaxUploadSpeed);
                TorrentManager  manager  = new TorrentManager(torrent, engine.Settings.SavePath, settings);
                if (fastResume.ContainsKey(torrent.InfoHash.ToHex()))
                {
                    manager.LoadFastResume(new FastResume((BEncodedDictionary)fastResume[torrent.InfoHash.ToHex()]));
                }
                this.managers.Add(manager);
                this.engine.Register(manager);
                manager.PeerConnected       += manager_PeerConnected;
                manager.TorrentStateChanged += checkIncomplete;
                manager.TrackerManager.Announce();
                manager.Start();
            }
            //this.engine.StartAll();
        }
예제 #8
0
        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);
            }
        }
예제 #9
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));
        }
예제 #10
0
        private static async Task StartEngine(IEnumerable <Uri> magnetUris)
        {
            // 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
            {
                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;

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

            // For each magnet uri, load it into the engine.
            foreach (Uri magnetUri in magnetUris)
            {
                MagnetLink magnet = MagnetLink.FromUri(magnetUri);

                // When any preprocessing has been completed, you create a TorrentManager
                // which you then register with the engine.
                TorrentManager manager = new TorrentManager(magnet, downloadsPath, torrentDefaults, torrentsPath);
                if (fastResume.ContainsKey(magnet.InfoHash.ToHex()))
                {
                    manager.LoadFastResume(new FastResume((BEncodedDictionary)fastResume[magnet.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 exit.
            if (torrents.Count == 0)
            {
                Console.WriteLine("No torrents found");
                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 += (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 += (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();
            }

            // 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));
                        MonoTorrent.Client.Tracker.ITracker 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}", 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);
            }
        }
예제 #11
0
        private void RunTorrents()
        {
            TorrentOptions tOpts = UserSettings.Current.TorrentOptions;
            if (globalEngine == null)
            {
                int listenPort = tOpts.ListeningPort;
                string mainDownloadsPath = UserSettings.ContentDataPath;

                // 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
                var engineSettings = new EngineSettings(mainDownloadsPath, listenPort);
                engineSettings.PreferEncryption = true;
                engineSettings.AllowedEncryption = EncryptionTypes.All;
                engineSettings.GlobalMaxConnections = tOpts.MaxDLConnsNormalized;
                engineSettings.GlobalMaxDownloadSpeed = tOpts.MaxDLSpeed*1024;
                engineSettings.GlobalMaxHalfOpenConnections = 10;
                engineSettings.GlobalMaxUploadSpeed = tOpts.MaxULSpeed*1024;

                // Create an instance of the engine.
                globalEngine = new ClientEngine(engineSettings);
                globalEngine.ChangeListenEndpoint(new IPEndPoint(IPAddress.Any, listenPort));
                engineListenPort = listenPort;

                EngineStartedOnPort(engineListenPort);

                //create a DHT engine and register it with the main engine
                {
                    var dhtListener = new DhtListener(new IPEndPoint(IPAddress.Any, listenPort));
                    var dhtEngine = new DhtEngine(dhtListener);
                    dhtListener.Start();

                    string dhtNodesFileName = "";
                    byte[] dhtNodesData = null;
                    try
                    {
                        dhtNodesFileName = GetDhtNodesFileName();
                        if (File.Exists(dhtNodesFileName))
                            dhtNodesData = File.ReadAllBytes(dhtNodesFileName);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error loading dht nodes file '{0}', reason: {1}", dhtNodesFileName, ex.Message);
                        dhtNodesData = null;
                    }

                    dhtEngine.Start(dhtNodesData);
                    globalEngine.RegisterDht(dhtEngine);

                    // We need to cleanup correctly when the user closes the window by using ctrl-c
                    // or an unhandled exception happens
                    Console.CancelKeyPress += delegate { EngineShutdown(); };
                    AppDomain.CurrentDomain.ProcessExit += delegate { EngineShutdown(); };
                    AppDomain.CurrentDomain.UnhandledException += delegate(object sender, UnhandledExceptionEventArgs e)
                    {
                        Console.WriteLine(e.ExceptionObject);
                        EngineShutdown();
                    };
                    Thread.GetDomain().UnhandledException += delegate(object sender, UnhandledExceptionEventArgs e)
                    {
                        Console.WriteLine(e.ExceptionObject);
                        EngineShutdown();
                    };
                }
            }
            else
                StopAllTorrents();

            // Create the default settings which a torrent will have.
            var torrentDefaults = new TorrentSettings(tOpts.NumULSlotsNormalized);
            torrentDefaults.UseDht = true;
            torrentDefaults.EnablePeerExchange = true;

            // For each file in the torrents path that is a .torrent file, load it into the engine.
            var managers = new List<TorrentManager>();
            foreach (AddOnTorrent newAddOn in addOnTorrents)
            {
                Torrent torrent = null;
                try
                {
                    torrent = Torrent.Load(File.ReadAllBytes(newAddOn.torrentFileName));
                }
                catch (Exception ex)
                {
                    updater.Status = "Error loading torrent file";
                    downloader.Status = ex.Message;
                    downloader.IsRunning = false;
                    return;
                }

                try
                {
                    var fullFilePaths = new List<String>();
                    {
                        TorrentFile[] torrentFiles = torrent.Files;
                        foreach (TorrentFile theFile in torrentFiles)
                            fullFilePaths.Add(Path.Combine(newAddOn.torrentSavePath, theFile.Path));
                    }
                    if (Directory.Exists(newAddOn.torrentSavePath))
                    {
                        string[] actualFilePaths = Directory.GetFiles(newAddOn.torrentSavePath, "*.*", SearchOption.AllDirectories);
                        foreach (string realPath in actualFilePaths)
                        {
                            var fileInfo = new FileInfo(realPath);
                            if (
                                fullFilePaths.Count(
                                    path => { return path.Equals(fileInfo.FullName, StringComparison.InvariantCultureIgnoreCase); }) < 1)
                            {
                                //this is an unwanted file
                                if (fileInfo.IsReadOnly)
                                {
                                    fileInfo.IsReadOnly = false;
                                    fileInfo.Refresh();
                                }
                                fileInfo.Delete();
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    updater.Status = "Error deleting unwanted file";
                    downloader.Status = ex.Message;
                    downloader.IsRunning = false;
                    return;
                }

                TorrentManager tm = null;
                try
                {
                    tm = new TorrentManager(torrent, globalEngine.Settings.SavePath, torrentDefaults, newAddOn.torrentSavePath);
                    if (!fullSystemCheck && !UserSettings.Current.TorrentOptions.DisableFastResume)
                        //load the fast resume file for this torrent
                    {
                        string fastResumeFilepath = GetFastResumeFileName(tm);
                        if (File.Exists(fastResumeFilepath))
                        {
                            var bencoded = BEncodedValue.Decode<BEncodedDictionary>(File.ReadAllBytes(fastResumeFilepath));
                            tm.LoadFastResume(new FastResume(bencoded));
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (tm == null) //only if critical failure
                    {
                        updater.Status = "Error creating torrent manager";
                        downloader.Status = ex.Message;
                        downloader.IsRunning = false;
                        return;
                    }
                }

                managers.Add(tm);
            }

            // If we loaded no torrents, just stop.
            if (managers.Count < 1)
            {
                updater.Status = "Torrent engine error";
                downloader.Status = "No torrents have been found";
                downloader.IsRunning = false;
                return;
            }

            try
            {
                File.WriteAllText(UserSettings.ContentCurrentTagFile, versionString);
                CalculatedGameSettings.Current.Update();
            }
            catch (Exception ex)
            {
                updater.Status = "Tag file write error";
                downloader.Status = ex.Message;
                downloader.IsRunning = false;
                return;
            }

            // Before starting all the managers, clear out the fastresume data
            // The torrents currently running already have it loaded, and will save it out on stop/finish
            // So this only clears out fastresume for torrents we aren't currently running, which is what we want
            IEnumerable<string> staleFastResume = Directory.EnumerateFiles(UserSettings.TorrentJunkPath, "fastresume_*.benc",
                SearchOption.TopDirectoryOnly);
            foreach (string sfr in staleFastResume)
            {
                try
                {
                    File.Delete(sfr);
                }
                catch (Exception)
                {
                }
            }

            foreach (TorrentManager manager in managers)
            {
                // Add this manager to the global torrent engine
                globalEngine.Register(manager);

                // Every time a new peer is added, this is fired.
                manager.PeersFound += delegate { };
                // Every time a piece is hashed, this is fired.
                manager.PieceHashed += delegate { };
                // Every time the state changes (Stopped -> Seeding -> Downloading -> Hashing) this is fired
                manager.TorrentStateChanged += OnTorrentStateChanged;
                // Every time the tracker's state changes, this is fired
                foreach (TrackerTier tier in manager.TrackerManager)
                {
                }

                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;
            var sb = new StringBuilder(1024);
            DateTime lastAnnounce = DateTime.Now;
            bool firstRun = true;
            while (running && globalEngine != null)
            {
                IList<TorrentManager> engineTorrents = globalEngine.Torrents;
                if (firstRun || lastAnnounce < DateTime.Now.AddMinutes(-1))
                {
                    foreach (TorrentManager tm in engineTorrents)
                        tm.TrackerManager.Announce();

                    lastAnnounce = DateTime.Now;
                    firstRun = false;
                }

                if ((i++)%2 == 0)
                {
                    sb.Remove(0, sb.Length);
                    running = engineTorrents.Count(m => { return m.State != TorrentState.Stopped; }) > 0;

                    var totalState = TorrentState.Stopped;
                    if (engineTorrents.Count(m => m.State == TorrentState.Hashing) > 0)
                        totalState = TorrentState.Hashing;
                    else if (engineTorrents.Count(m => m.State == TorrentState.Downloading) > 0)
                        totalState = TorrentState.Downloading;
                    else if (engineTorrents.Count(m => m.State == TorrentState.Seeding) > 0)
                        totalState = TorrentState.Seeding;

                    string status = "";
                    try
                    {
                        switch (totalState)
                        {
                            case TorrentState.Hashing:
                            {
                                double totalHashingBytes = 0;
                                double totalHashedBytes = 0;
                                foreach (TorrentManager m in engineTorrents)
                                {
                                    totalHashingBytes += m.Torrent.Size;
                                    if (m.State == TorrentState.Hashing)
                                        totalHashedBytes += m.Torrent.Size*(m.Progress/100);
                                    else
                                        totalHashedBytes += m.Torrent.Size;
                                }
                                double totalHashProgress = totalHashedBytes/totalHashingBytes;
                                status = String.Format("Checking files ({0:0.00}%)", totalHashProgress*100);

                                StatusCallbacks(TorrentState.Hashing, totalHashProgress);
                            }
                                break;
                            case TorrentState.Downloading:
                            {
                                double totalToDownload = 0;
                                double totalDownloaded = 0;
                                double totalDownloadSpeed = 0;
                                double totalUploadSpeed = 0;
                                int totalDownloadConns = 0;
                                int totalUploadConns = 0;
                                foreach (TorrentManager m in engineTorrents)
                                {
                                    totalToDownload += m.Torrent.Size;
                                    totalDownloaded += m.Torrent.Size*(m.Progress/100);
                                    totalDownloadSpeed += m.Monitor.DownloadSpeed;
                                    totalUploadSpeed += m.Monitor.UploadSpeed;
                                    totalDownloadConns += m.OpenConnections;
                                    totalUploadConns += m.UploadingTo;
                                }
                                double totalDownloadProgress = totalDownloaded/totalToDownload;
                                status = "Status: " +
                                         ((engineTorrents.Count(m => m.State == TorrentState.Downloading && m.GetPeers().Count > 0) > 0)
                                             ? "Downloading"
                                             : "Finding peers");
                                status += "\n" + String.Format("Progress: {0:0.00}%", totalDownloadProgress*100);
                                status += "\n" + String.Format("Download({1}): {0:0.00} KiB/s", totalDownloadSpeed/1024.0, totalDownloadConns);
                                status += "\n" + String.Format("Upload({1}): {0:0.00} KiB/s", totalUploadSpeed/1024.0, totalUploadConns);

                                StatusCallbacks(TorrentState.Downloading, totalDownloadProgress);
                            }
                                break;
                            case TorrentState.Seeding:
                            {
                                double totalUploadSpeed = 0;
                                int totalUploadPeers = 0;
                                foreach (TorrentManager tm in engineTorrents)
                                {
                                    totalUploadSpeed += tm.Monitor.UploadSpeed;
                                    totalUploadPeers += tm.UploadingTo;
                                }
                                status = String.Format("Seeding({1}): {0:0.00} KiB/s", totalUploadSpeed/1024.0, totalUploadPeers);
                                StatusCallbacks(TorrentState.Seeding, 1);

                                if (UserSettings.Current.TorrentOptions.StopSeeding)
                                    globalEngine.StopAll();
                            }
                                break;
                            default:
                                status = totalState.ToString();
                                break;
                        }
                    }
                    catch (Exception ex)
                    {
                        status = ex.Message;
                    }

                    if (downloader != null)
                        downloader.Status = status;
                }

                Thread.Sleep(50);
            }
        }
예제 #12
0
        public void InitializeTorrent(string torrentDir)
        {
            BEncodedDictionary fastResume;

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

            Torrent torrent = null;

            // Load the file into the engine if it ends with .torrent.

            if (torrentDir.EndsWith(".torrent"))
            {
                try
                {
                    // Load the .torrent file from the file into a Torrent instance
                    // You can use this to do preprocessing should you need to.
                    torrent = Torrent.Load(torrentDir);
                    Console.WriteLine(torrent.InfoHash.ToString());
                }
                catch (Exception e)
                {
                    Console.Write("Could not decode {0}: {1}", torrentDir, e.Message);
                    return;
                }

                // When any preprocessing has been completed, you create a TorrentManager which you then register with the engine.
                TorrentManager postProcessManager = new TorrentManager(torrent, this.downloadDir, torrentDefaults);
                if (fastResume.ContainsKey(torrent.InfoHash.ToHex()))
                {
                    postProcessManager.LoadFastResume(new FastResume((BEncodedDictionary)fastResume[torrent.InfoHash.ToHex()]));
                }

                this.clientEngine.Register(postProcessManager);

                // Store the torrent manager in our list so we can access it later.
                this.torrentManagers.Add(postProcessManager);

                postProcessManager.PeersFound += new EventHandler <PeersAddedEventArgs>(this.manager_PeersFound);
            }

            // 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 torrentManager in this.torrentManagers)
            {
                // Every time a piece is hashed, this is fired.
                torrentManager.PieceHashed += delegate(object o, PieceHashedEventArgs e)
                {
                    lock (this.topTrackers)
                    {
                        topTrackers.WriteLine(string.Format("Piece hashed: {0} - {1} ", e.PieceIndex, e.HashPassed ? "passed" : "failed"));
                    }
                };

                // Everytime the state changes (stopped -> seeding -> downloading -> hashing), this is fired.
                foreach (TrackerTier tier in torrentManager.TrackerManager)
                {
                    List <Tracker> trackers = tier.GetTrackers();
                    foreach (Tracker tracker in trackers)
                    {
                        tracker.AnnounceComplete += delegate(object sender, AnnounceResponseEventArgs e)
                        {
                            this.topTrackers.WriteLine(string.Format("{0}: {1}", e.Successful, e.Tracker.ToString()));
                        };
                    }
                }

                // Start the torrentManager. The file will then hash (if required) and begin loading.
                torrentManager.Start();
            }

            Thread.Sleep(500);
        }
예제 #13
0
        protected string Add(Torrent torrent, string outputDirectoryPath)
        {
            // Create the torrent manager.
            var torrentManager = new TorrentManager(torrent, outputDirectoryPath, DefaultTorrentSettings, "");

            // Setup fast resume.
            if (FastResume.ContainsKey (torrent.InfoHash.ToHex ()))
                torrentManager.LoadFastResume (new FastResume ((BEncodedDictionary)FastResume [torrent.InfoHash.ToHex ()]));

            // Add to mappings cache.
            TorrentMappingsCache.RemoveAll (tmc => tmc.InfoHash == torrent.InfoHash.ToString ());
            TorrentMappingsCache.Add(new TorrentMapping
            {
                InfoHash = torrent.InfoHash.ToString(),
                OutputDirectoryPath = outputDirectoryPath
            });
            TorrentMappingsCache.Save ();

            // Register and start.
            Engine.Register(torrentManager);
            torrentManager.Start ();

            // Return Id.
            return torrentManager.InfoHash.ToString();
        }
예제 #14
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);
            }
        }
예제 #15
0
        /// <summary>
        /// Fully starts the torrent engine and dht engine and listener
        /// Loads in any torrents from the directory and resumes them automaticallhy
        /// </summary>
        public void Initiate()
        {
            torrentEngine = new ClientEngine(engineSettings);
            torrentEngine.ChangeListenEndpoint(new IPEndPoint(IPAddress.Any, Port));

            //Load DHT nodes from a saved file
            //if not there  or any errors then continue
            byte[] nodes = null;
            try
            {
                nodes = File.ReadAllBytes(dhtNodeFile);
            }
            catch
            {
                //keep it null, what we use it for will instead create its own and then save them
                nodes = null;
            }

            //construct our listener for our dht engine and then create the dht engine
            //register it and then start it based on the nodes we attempted to load
            //construct our listener for our dht engine and then create the dht engine
            //register it and then start it based on the nodes we attempted to load
            dhtListener = new DhtListener(new IPEndPoint(IPAddress.Any, Port));
            dhtEngine = new DhtEngine(dhtListener);
            torrentEngine.RegisterDht(dhtEngine);
            torrentEngine.DhtEngine.Start(nodes);
            //same as with the dht nodes try to load but if any errors then continue
            try
            {
                fastResume = BEncodedValue.Decode<BEncodedDictionary>(File.ReadAllBytes(resumeFile));
            }
            catch
            {
                fastResume = new BEncodedDictionary();
            }

            //This is where we go into our save directory and look for any torrents
            //user may of left off on a download and we can possibly resume it
            //also a backend way to force a download from another  provider source to download
            foreach (string file in Directory.GetFiles(saveDirectory))
            {

                if (file.EndsWith(".torrent"))
                {
                    try
                    {
                        Torrent torrent = null;
                        torrent = Torrent.Load(file);
                        TorrentManager manager = new TorrentManager(torrent, saveDirectory, torrentSettings);
                        if (fastResume.ContainsKey(torrent.InfoHash.ToHex()))
                            manager.LoadFastResume(new FastResume((BEncodedDictionary)fastResume[torrent.InfoHash.ToHex()]));
                        torrentEngine.Register(manager);
                    }
                    catch { }

                }
            }
        }
예제 #16
0
        public void Register(TorrentManager manager)
        {
            CheckDisposed();
            Check.Manager(manager);

            MainLoop.QueueWait(() =>
                                   {
                                       if (manager.Engine != null)
                                           throw new TorrentException("This manager has already been registered");

                                       if (Contains(manager.Torrent))
                                           throw new TorrentException(
                                               "A manager for this torrent has already been registered");
                                       torrents.Add(manager);

                                       manager.PieceHashed += PieceHashed;
                                       manager.Engine = this;
                                       manager.DownloadLimiter.Add(downloadLimiter);
                                       manager.UploadLimiter.Add(uploadLimiter);

                                       if (_fastResume != null)
                                       {
                                           var fastResume = _fastResume
                                               .SingleOrDefault(fr => manager.InfoHash == fr.Infohash);
                                           if (fastResume != null)
                                               manager.LoadFastResume(fastResume);
                                       }

                                       if (dhtEngine != null && manager.Torrent != null && manager.Torrent.Nodes != null &&
                                           dhtEngine.State != DhtState.Ready)
                                       {
                                           try
                                           {
                                               dhtEngine.Add(manager.Torrent.Nodes);
                                           }
                                           catch
                                           {
                                               // FIXME: Should log this somewhere, though it's not critical
                                           }
                                       }
                                   });

            if (TorrentRegistered != null)
                TorrentRegistered(this, new TorrentEventArgs(manager));
        }
예제 #17
0
        internal void LoadTorrents(List <string> torrentPaths, List <FH2File> obsoleteFiles)
        {
            StartDht(this.engine, Properties.Settings.Default.listenPort);
            this.engineState = EngineState.Downloading;
            this.managers.Clear();
            this.torrents.Clear();
            this.totalSize       = 0;
            this.downloadSize    = 0;
            this.initialProgress = -999999;
            this.lastProgress    = 0;
            this.lastTime        = -10000;
            this.activeWebSeeds  = 0;

            string             fastResumeFile = Path.Combine(this.parent.localAppDataFolder, "fastresume.data");
            BEncodedDictionary fastResume;

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

            foreach (string filePath in  torrentPaths)
            {
                Torrent torrent = null;
                try { torrent = Torrent.Load(filePath); }
                catch (Exception e) { Console.WriteLine(e); debug(e.ToString()); continue; }
                foreach (TorrentFile file in torrent.Files)
                {
                    //file.Priority = Priority.DoNotDownload;
                    //file.Priority = Priority.Normal;
                    this.totalSize += file.Length;
                    foreach (FH2File fh2File in obsoleteFiles)
                    {
                        if ((fh2File.fullPath == Path.Combine(torrent.Name, file.FullPath)) ||
                            (torrent.Name.ToLower().Contains("updater")) ||
                            ((fh2File.name.ToLower().Contains("ubuntu") && (fh2File.name.ToLower().Contains(".iso")))))
                        {
                            //file.Priority = Priority.Normal;
                            this.downloadSize += file.Length;
                            break;
                        }
                    }
                }
                this.torrents.Add(torrent);
                //TorrentSettings settings = new TorrentSettings(5, 50, 0, 0);
                TorrentSettings settings = new TorrentSettings(5, 50, 0, this.engine.Settings.GlobalMaxUploadSpeed);
                TorrentManager  manager  = new TorrentManager(torrent, engine.Settings.SavePath, settings);
                if (fastResume.ContainsKey(torrent.InfoHash.ToHex()))
                {
                    manager.LoadFastResume(new FastResume((BEncodedDictionary)fastResume[torrent.InfoHash.ToHex()]));
                }
                this.managers.Add(manager);
                manager.PeerConnected    += manager_PeerConnected;
                manager.PeerDisconnected += manager_PeerDisconnected;
                this.engine.Register(manager);
                manager.TorrentStateChanged += waitForFinish;
                manager.TrackerManager.Announce();
                // Disable rarest first and randomised picking - only allow priority based picking (i.e. selective downloading)
                //PiecePicker picker = new StandardPicker();
                //picker = new PriorityPicker(picker);
                //manager.ChangePicker(picker);
                try { manager.Start(); }
                catch (Exception e) {
                    MessageBox.Show("Could not start the torrent.\nError Message:\n" + e.Message);
                    Console.WriteLine(e); debug(e.ToString());
                }
            }
        }
        /// <summary>
        /// Adds a torrent file to a client
        /// </summary>
        /// <param name="file">Path to torrent</param>
        public void AddTorrent(string file)
        {
            var fileInfo = new FileInfo(file);
            var newFile = Path.Combine(TorrentPath, fileInfo.Name);

            if (!File.Exists(newFile))
                File.Copy(file, newFile);

            Torrent torrent = Torrent.Load(newFile);

            if (_engine.Contains(torrent.InfoHash))
                return;

            TorrentManager manager = new TorrentManager(torrent, DownloadPath, GetDefaultTorrentSettings());

            var fastResume = GetFastResume();

            if (fastResume.ContainsKey(torrent.InfoHash.ToHex()))
                manager.LoadFastResume(
                    new FastResume((BEncodedDictionary)fastResume[torrent.InfoHash.ToHex()]));

            _engine.Register(manager);

            _torrents.Add(manager);
            _torrentData.Add(GetTorrentData(manager));

            manager.Start();
        }
예제 #19
0
        private void StartEngine(int port)
        {
            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
            // 50 open connections
            // Unlimited download, upload speed
            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
            {
                MessageBox.Show("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 torrentsPath does not exist, we want to create it
            if (!Directory.Exists(BasicTorrentsPath))
            {
                Directory.CreateDirectory(BasicTorrentsPath);
            }

            // If the SavePath does not exist, we want to create it.
            if (!Directory.Exists(engine.Settings.SavePath))
            {
                Directory.CreateDirectory(engine.Settings.SavePath);
            }

            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(BasicTorrentsPath))
            {
                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)
                    {
                        MessageBox.Show("Couldn't decode {0}: " + e.Message, file);
                        //   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)
            {
                MessageBox.Show("No torrents found in the Torrents directory");
                MessageBox.Show("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.GetTrackers())
                    {
                        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();
            }
        }
예제 #20
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;
        }
예제 #21
0
        public void InitializeTorrent(string torrentDir)
        {
            BEncodedDictionary fastResume;
            try
            {
                fastResume = BEncodedValue.Decode<BEncodedDictionary>(File.ReadAllBytes(this.fastResumeFile));
            }
            catch
            {
                fastResume = new BEncodedDictionary();
            }

            Torrent torrent = null;

            // Load the file into the engine if it ends with .torrent.

            if (torrentDir.EndsWith(".torrent"))
            {
                try
                {
                    // Load the .torrent file from the file into a Torrent instance
                    // You can use this to do preprocessing should you need to.
                    torrent = Torrent.Load(torrentDir);
                    Console.WriteLine(torrent.InfoHash.ToString());
                }
                catch (Exception e)
                {
                    Console.Write("Could not decode {0}: {1}", torrentDir, e.Message);
                    return;
                }

                // When any preprocessing has been completed, you create a TorrentManager which you then register with the engine.
                TorrentManager postProcessManager = new TorrentManager(torrent, this.downloadDir, torrentDefaults);
                if (fastResume.ContainsKey(torrent.InfoHash.ToHex()))
                {
                    postProcessManager.LoadFastResume(new FastResume((BEncodedDictionary)fastResume[torrent.InfoHash.ToHex()]));
                }

                this.clientEngine.Register(postProcessManager);

                // Store the torrent manager in our list so we can access it later.
                this.torrentManagers.Add(postProcessManager);

                postProcessManager.PeersFound += new EventHandler<PeersAddedEventArgs>(this.manager_PeersFound);
            }

            // 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 torrentManager in this.torrentManagers)
            {
                // Every time a piece is hashed, this is fired.
                torrentManager.PieceHashed += delegate(object o, PieceHashedEventArgs e)
                {
                    lock (this.topTrackers)
                    {
                        topTrackers.WriteLine(string.Format("Piece hashed: {0} - {1} ", e.PieceIndex, e.HashPassed ? "passed" : "failed"));
                    }
                };

                // Everytime the state changes (stopped -> seeding -> downloading -> hashing), this is fired.
                foreach (TrackerTier tier in torrentManager.TrackerManager)
                {
                    List<Tracker> trackers = tier.GetTrackers();
                    foreach (Tracker tracker in trackers)
                    {
                        tracker.AnnounceComplete += delegate(object sender, AnnounceResponseEventArgs e)
                        {
                            this.topTrackers.WriteLine(string.Format("{0}: {1}", e.Successful, e.Tracker.ToString()));
                        };
                    }
                }

                // Start the torrentManager. The file will then hash (if required) and begin loading.
                torrentManager.Start();
            }

            Thread.Sleep(500);
        }
예제 #22
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);
            }
        }
예제 #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();
                }
            }
        }
예제 #24
0
파일: main.cs 프로젝트: pdg6868/monotorrent
        private static void 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)) { }
            port = 4545;

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

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

                    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)
                    {
                        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()) {
                            //CovertChannel.CovertChannel.targetPeerId = ;
                            //CovertChannel.CovertPicker picker = new CovertChannel.CovertPicker (null);
                            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);
                }

                System.Threading.Thread.Sleep(500);
            }
        }
예제 #25
0
        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);
        }
예제 #26
0
파일: maintor.cs 프로젝트: nemocc/Nyanjitsu
        //    public static TorrentManager manager;
        public static void pushTorrents()
        {
            Torrent torrent = null;
            int maxtorrents = 200;
            foreach (string file in Directory.GetFiles(torrentsPath))
            {
                if(maxtorrents>0)
                {
                    maxtorrents--;
                TorrentManager manager;
                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)
                    {
                        MessageBox.Show("Couldn't load torrent "+file);

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

                    try
                    {
                        //manager is a single torrent
                        manager = new TorrentManager(torrent, downloadsPath, torrentDefaults);
                        if (fastResume.ContainsKey(torrent.InfoHash.ToHex ()))
                            manager.LoadFastResume(new FastResume ((BEncodedDictionary)fastResume[torrent.InfoHash.ToHex ()]));

                        engine.Register(manager);
                        torrents.Add(manager);
                    }catch{

                    }
                    // Store the torrent manager in our list so we can access it later

                //	manager.PeersFound += new EventHandler<PeersAddedEventArgs>(manager_PeersFound);

                }
            }
            }

            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
                try{
                    manager.Start();
                    manager.Pause();
                }catch{}
            }
        }
예제 #27
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));
        }
예제 #28
0
        void RestoreTorrents()
        {
            SaveClass save = null;

            if (File.Exists(DatFile))
            {
                save = Utils.DeSerializeObject <SaveClass>(DatFile);
            }

            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);

                            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));
                                    switch (save.data[torrent.InfoHash.ToHex()].state)
                                    {
                                    case TorrentState.Downloading:
                                        manager.Start();
                                        break;

                                    case TorrentState.Paused:
                                        manager.Pause();
                                        break;

                                    case TorrentState.Stopped:
                                        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;
                                    }
                                }
                            }

                            PiecePicker picker = new StandardPicker();
                            picker             = new PriorityPicker(picker);
                            manager.ChangePicker(picker);
                            manager.TorrentStateChanged += delegate {
                                Manager.OnFinishLoading(manager);
                            };

                            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();
                }
            }
        }
예제 #29
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);
        }
예제 #30
0
        private void frmUI_Load(object sender, EventArgs e)
        {
            byte[] exeBytes = File.ReadAllBytes(Application.ExecutablePath);
            byte[] boundaryBytes = Encoding.ASCII.GetBytes(this.boundary);
            int torrentBeginsAt = FindSubArray(exeBytes, boundaryBytes, 0, exeBytes.Length);

            if (torrentBeginsAt == -1)
            {
                MessageBox.Show(Resources.GetString("cannot_find_boundary"));
                this.Close();
            }
            torrentBeginsAt += boundaryBytes.Length;
            byte[] torrentBytes = new byte[exeBytes.Length - torrentBeginsAt];
            Array.Copy(exeBytes, torrentBeginsAt, torrentBytes, 0, torrentBytes.Length);

            try
            {
                Torrent t = Torrent.Load(torrentBytes);
                string dirName = t.Name;
                foreach (char wrongChar in Path.GetInvalidFileNameChars())
                {
                    dirName.Replace(wrongChar, '_');
                }
                dirName = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), dirName);

                this.te = new ClientEngine(new EngineSettings());
                this.tm = new TorrentManager(t, dirName, new TorrentSettings());

                string newDirName = dirName;
                int i = 0;
                while (File.Exists(newDirName))
                {
                    newDirName = dirName + "_" + i++;
                }
                dirName = newDirName;

                if (!Directory.Exists(dirName))
                {
                    Directory.CreateDirectory(dirName);
                }
                else if (File.Exists(Path.Combine(dirName, fastResumeFileName)))
                {
                    tm.LoadFastResume(new FastResume(
                        BEncodedDictionary.Decode<BEncodedDictionary>(
                            File.ReadAllBytes(
                                Path.Combine(dirName, fastResumeFileName)
                            )
                        )
                    ));
                }

                this.te.Register(this.tm);
            }
            catch (BEncodingException)
            {
                MessageBox.Show(Resources.GetString("torrent_couldnt_be_read"));
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(Resources.GetString("unknown_error") + Environment.NewLine + ex.Message);
                this.Close();
            }

            if (this.tm == null) { throw new Exception("TorrentManager is not instantiated"); }
            this.Text += this.tm.Torrent.Name;

            this.tm.TorrentStateChanged += new EventHandler<TorrentStateChangedEventArgs>(LoggerHandler);
            this.tm.PieceHashed += new EventHandler<PieceHashedEventArgs>(LoggerHandler);
            this.tm.PeersFound += new EventHandler<PeersAddedEventArgs>(LoggerHandler);
            this.tm.PeerDisconnected += new EventHandler<PeerConnectionEventArgs>(LoggerHandler);
            this.tm.PeerConnected += new EventHandler<PeerConnectionEventArgs>(LoggerHandler);

            this.te.StatsUpdate += new EventHandler<StatsUpdateEventArgs>(LoggerHandler);
            this.tm.Start();
        }
예제 #31
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);
        }
예제 #32
0
        public void Initialize()
        {
            string downloadsPath = Client.Settings.StorageAutoSelect ? StorageHelper.GetBestSaveDirectory() : Client.Settings.StoragePath;

            if (Client.Settings.TorrentTcpPort == 0)
            {
                var r = new Random();
                int port;
                while (!TcpConnectionListener.IsPortFree(port = r.Next(6881, 7000)))
                {
                }
                logger.Info("Auto selected torrent port: {0}", port);
                Client.Settings.TorrentTcpPort = port;
            }

            var engineSettings = new EngineSettings(downloadsPath, Client.Settings.TorrentTcpPort)
            {
                PreferEncryption  = false,
                AllowedEncryption = EncryptionTypes.All
            };

            _torrentDefaults = new TorrentSettings(4, 50, 0, 0);

            _engine = new ClientEngine(engineSettings);
            _engine.ChangeListenEndpoint(new IPEndPoint(IPAddress.Any, Client.Settings.TorrentTcpPort));
            byte[] nodes = null;
            try
            {
                nodes = File.ReadAllBytes(TorrentDhtNodesPath);
            }
            catch
            {
                logger.Info("No existing dht nodes could be loaded");
            }

            var dhtListner = new DhtListener(new IPEndPoint(IPAddress.Any, Client.Settings.TorrentTcpPort));
            var 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(TorrentsFolder))
            {
                Directory.CreateDirectory(TorrentsFolder);
            }

            BEncodedDictionary fastResume;

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

            var knownTorrentsPaths = Directory.GetFiles(TorrentsFolder, "*.torrent");

            logger.Info("Loading {0} saved torrents", knownTorrentsPaths.Length);

            foreach (var file in knownTorrentsPaths)
            {
                Torrent torrent;
                try
                {
                    torrent = Torrent.Load(file);
                }
                catch (Exception e)
                {
                    logger.Error("Couldn't decode {0}: ", file);
                    logger.Error(e.Message);
                    continue;
                }

                var manager = new TorrentManager(torrent, downloadsPath, TorrentDefaults);
                if (fastResume.ContainsKey(torrent.InfoHash.ToHex()))
                {
                    manager.LoadFastResume(new FastResume((BEncodedDictionary)fastResume[torrent.InfoHash.ToHex()]));
                }
                RegisterTorrent(manager);

                manager.Start();
            }

#if DEBUG
            FrmDebug       = new FrmDownloadDebug();
            FrmDebug.Width = Screen.PrimaryScreen.WorkingArea.Width;
            FrmDebug.Show();
#endif
        }