The Engine that contains the TorrentManagers
Inheritance: IDisposable
Exemple #1
0
 // savePath is the directory where downloads will be stored
 public TorrentFunc(StorageFolder Path)
 {
     // Create a basic ClientEngine without changing any settings
     this.engine = new ClientEngine(new EngineSettings());
     this.savePath = Path;
 }
 public TorrentStreamService(ClientEngine engine)
 {
     _engine = engine;
 }
Exemple #3
0
        public async void tor()
        {
            var port = 6881;
            var dhtPort = 15000;

            // Use Universal.Nat to enable upnp port mapping
            /* var natManager = new NatManager(port);
            natManager.Start();*/

            var picker = new FileOpenPicker();
            picker.FileTypeFilter.Add(".torrent");
            var file = await picker.PickSingleFileAsync();
            var stream = await file.OpenStreamForReadAsync();

            var torrent = Universal.Torrent.Common.Torrent.Load(stream);
            if (torrent != null)
            {
                var engineSettings = new EngineSettings(savePath, port)
                {
                    PreferEncryption = true,
                    AllowedEncryption = EncryptionTypes.All
                };

                // Create the default settings which a torrent will have.
                // 4 Upload slots - a good ratio is one slot per 5kB of upload speed
                // 50 open connections - should never really need to be changed
                // Unlimited download speed - valid range from 0 -> int.Max
                // Unlimited upload speed - valid range from 0 -> int.Max
                var torrentDefaults = new TorrentSettings(4, 150, 0, 0)
                {
                    UseDht = true,
                    EnablePeerExchange = true
                };

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

                //var dhtListner = new DhtListener(new IPEndPoint(IPAddress.Any, dhtPort));
                //var dht = new DhtEngine(dhtListner);
                //engine.RegisterDht(dht);
                //dhtListner.Start();
                //engine.DhtEngine.Start();

                // When any preprocessing has been completed, you create a TorrentManager
                // which you then register with the engine.
                var manager = new TorrentManager(torrent, ApplicationData.Current.LocalFolder, torrentDefaults);
                engine.Register(manager);

                // Every time a piece is hashed, this is fired.
                manager.PieceHashed +=
                    delegate (object o, PieceHashedEventArgs e)
                    {
                        //Debug.WriteLine("Piece Hashed: {0} - {1}", e.PieceIndex, e.HashPassed ? "Pass" : "Fail");
                    };

                // Every time the state changes (Stopped -> Seeding -> Downloading -> Hashing) this is fired
                manager.TorrentStateChanged +=
                    delegate (object o, TorrentStateChangedEventArgs e)
                    {
                        //Debug.WriteLine("OldState: " + e.OldState + " NewState: " + e.NewState);
                    };

                // Every time the tracker's state changes, this is fired
                foreach (var t in manager.TrackerManager.SelectMany(tier => tier.Trackers))
                {
                    t.AnnounceComplete +=
                        delegate (object sender, AnnounceResponseEventArgs e)
                        {
                            //  Debug.WriteLine("{0}: {1}", e.Successful, e.Tracker);
                        };
                }
                // Start the torrentmanager. The file will then hash (if required) and begin downloading/seeding
                manager.Start();

                var dispatcher = Window.Current.Dispatcher;
                engine.StatsUpdate +=
                    async (sender, args) =>
                    {
                        await
                            dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                () =>
                                {
                                    //TextBlock.Text = $"{manager.Peers.Seeds} seeds / {manager.Peers.Leechs} leechs / {manager.Progress} %";
                                });
                    };

            }
        }
        internal DiskManager(ClientEngine engine, PieceWriter.PieceWriter writer)
        {
            _bufferedReads = new Queue<BufferedIO>();
            _bufferedWrites = new Queue<BufferedIO>();
            _cache = new Cache<BufferedIO>(true).Synchronize();
            _engine = engine;
            ReadLimiter = new RateLimiter();
            _readMonitor = new SpeedMonitor();
            _writeMonitor = new SpeedMonitor();
            WriteLimiter = new RateLimiter();
            Writer = writer;

            _loopTask = delegate
            {
                if (Disposed)
                    return;

                while (this._bufferedWrites.Count > 0 &&
                       WriteLimiter.TryProcess(_bufferedWrites.Peek().InternalBuffer.Length/2048))
                {
                    BufferedIO write;
                    lock (_bufferLock)
                        write = this._bufferedWrites.Dequeue();
                    try
                    {
                        PerformWrite(write);
                        _cache.Enqueue(write);
                    }
                    catch (Exception ex)
                    {
                        if (write.Manager != null)
                            SetError(write.Manager, Reason.WriteFailure, ex);
                    }
                }

                while (this._bufferedReads.Count > 0 && ReadLimiter.TryProcess(_bufferedReads.Peek().Count/2048))
                {
                    BufferedIO read;
                    lock (_bufferLock)
                        read = this._bufferedReads.Dequeue();

                    try
                    {
                        PerformRead(read);
                        _cache.Enqueue(read);
                    }
                    catch (Exception ex)
                    {
                        if (read.Manager != null)
                            SetError(read.Manager, Reason.ReadFailure, ex);
                    }
                }
            };

            IoLoop.QueueTimeout(TimeSpan.FromSeconds(1), delegate
            {
                if (Disposed)
                    return false;

                _readMonitor.Tick();
                _writeMonitor.Tick();
                _loopTask();
                return true;
            });
        }