public TrackerPeersAdded(TorrentManager manager, int peersAdded, int total, MonoTorrent.Client.Tracker.Tracker tracker) :base (manager, peersAdded, total) { if (tracker == null) throw new ArgumentNullException("tracker"); this.tracker = tracker; }
public TorrentStreamManager(TorrentManager torrentManager, long prepareSize = 10*1024L*1024L) { TorrentManager = torrentManager; _prepareSize = prepareSize; TorrentManager.TorrentStateChanged += TorrentManager_TorrentStateChanged; }
/// <summary> /// Initializes a new instance of the <see cref="ChokeUnchokeManager" /> class. /// </summary> /// <param name="torrentManager">The torrent manager.</param> /// <param name="minimumTimeBetweenReviews">The minimum time between reviews.</param> /// <param name="percentOfMaxRateToSkipReview">The percent of maximum rate to skip review.</param> public ChokeUnchokeManager(TorrentManager torrentManager, int minimumTimeBetweenReviews, int percentOfMaxRateToSkipReview) { _owningTorrent = torrentManager; _minimumTimeBetweenReviews = minimumTimeBetweenReviews; _percentOfMaxRateToSkipReview = percentOfMaxRateToSkipReview; }
public static PeerMessage DecodeMessage(byte[] buffer, int offset, int count, TorrentManager manager) { PeerMessage message; CreateMessage creator; if (count < 4) throw new ArgumentException("A message must contain a 4 byte length prefix"); int messageLength = IPAddress.HostToNetworkOrder(BitConverter.ToInt32(buffer, offset)); if (messageLength > (count - 4)) throw new ArgumentException("Incomplete message detected"); if (buffer[offset + 4] == ExtensionMessage.MessageId) return ExtensionMessage.DecodeMessage(buffer, offset + 4 + 1, count - 4 - 1, manager); if (!messageDict.TryGetValue(buffer[offset + 4], out creator)) throw new ProtocolException("Unknown message received"); // The message length is given in the second byte and the message body follows directly after that // We decode up to the number of bytes Received. If the message isn't complete, throw an exception message = creator(manager); message.Decode(buffer, offset + 4 + 1, count - 4 - 1); return message; }
public StoppingMode(TorrentManager manager) : base(manager) { CanAcceptConnections = false; var engine = manager.Engine; if (manager.Mode is HashingMode) handle.AddHandle(((HashingMode) manager.Mode).hashingWaitHandle, "Hashing"); if (manager.TrackerManager.CurrentTracker != null && manager.TrackerManager.CurrentTracker.Status == TrackerState.Ok) handle.AddHandle(manager.TrackerManager.Announce(TorrentEvent.Stopped), "Announcing"); foreach (var id in manager.Peers.ConnectedPeers) if (id.Connection != null) id.Connection.Dispose(); manager.Peers.ClearAll(); handle.AddHandle(engine.DiskManager.CloseFileStreams(manager), "DiskManager"); manager.Monitor.Reset(); manager.PieceManager.Reset(); engine.ConnectionManager.CancelPendingConnects(manager); engine.Stop(); }
public StoppingMode(TorrentManager manager) : base(manager) { CanAcceptConnections = false; var engine = manager.Engine; var hashingMode = manager.Mode as HashingMode; if (hashingMode != null) _handle.AddHandle(hashingMode.HashingWaitHandle, "Hashing"); if (manager.TrackerManager.CurrentTracker != null) _handle.AddHandle(manager.TrackerManager.Announce(TorrentEvent.Stopped), "Announcing"); foreach (var id in manager.Peers.ConnectedPeers.Where(id => id.Connection != null)) id.Connection.Dispose(); manager.Peers.ClearAll(); _handle.AddHandle(engine.DiskManager.CloseFileStreams(manager), "DiskManager"); manager.Monitor.Reset(); manager.PieceManager.Reset(); engine.ConnectionManager.CancelPendingConnects(manager); engine.Stop(); }
private DateTime timeOfLastReview; //When we last reviewed the choke/unchoke position #endregion Fields #region Constructors /// <summary> /// Creates a new choke/unchoke manager for a torrent manager /// </summeary> /// <param name="TorrentManager">The torrent manager this choke/unchoke manager belongs to</param> public ChokeUnchokeManager(TorrentManager TorrentManager, int MinimumTimeBetweenReviews, int PercentOfMaxRateToSkipReview) { owningTorrent = TorrentManager; minimumTimeBetweenReviews = MinimumTimeBetweenReviews; percentOfMaxRateToSkipReview = PercentOfMaxRateToSkipReview; }
public void AddConnection(TorrentConnection connection, TorrentManager manager) { string remoteId = String.Empty; LoggingService.LogDebug("AddConnection(): Start"); if (!connection.IsIncoming) { // Send my identity. // XXX: This absolutely needs to be signed. connection.Transport.SendMessage(System.Text.Encoding.ASCII.GetBytes(Core.MyNodeID)); // Get other end's identity. byte[] message = connection.Transport.ReceiveMessage(); remoteId = System.Text.Encoding.ASCII.GetString(message); } else { // Get other end's identity. byte[] message = connection.Transport.ReceiveMessage(); remoteId = System.Text.Encoding.ASCII.GetString(message); // Send my identity. // XXX: This absolutely needs to be signed. connection.Transport.SendMessage(System.Text.Encoding.ASCII.GetBytes(Core.MyNodeID)); } LoggingService.LogDebug("Pushing connection to engine: {0} - {1}", connection.IsIncoming ? "Incoming" : "Outgoing", ((Meshwork.Transport.TcpTransport)connection.Transport).RemoteEndPoint.ToString()); Peer p = new Peer("", new Uri(String.Format("meshwork:{0}", remoteId)), EncryptionTypes.PlainText); RaiseConnectionReceived(p, connection, manager); LoggingService.LogDebug("AddConnection(): End"); }
internal PeerConnectionEventArgs(TorrentManager manager, PeerId id, Direction direction, String message) : base(manager) { peerConnectionId = id; connectionDirection = direction; this.message = message; }
/// <summary> /// Create new instance of PeerConnectionFailedEventArgs for peer from given torrent. /// </summary> /// <param name="manager"></param> /// <param name="peer"></param> /// <param name="direction">Which direction the connection attempt was</param> /// <param name="message">Message associated with the failure</param> public PeerConnectionFailedEventArgs(TorrentManager manager, Peer peer, Direction direction, string message) : base(manager) { Peer = peer; ConnectionDirection = direction; Message = message; }
public AsyncConnectState(TorrentManager manager, Peer peer, IConnection connection, AsyncConnect callback) { Manager = manager; Peer = peer; Connection = connection; Callback = callback; }
public void AddTorrent(string path) { Torrent torrent = Torrent.Load(path); TorrentManager manager = new TorrentManager(torrent, downloadsPath, defaultSettings); engine.Register(manager); managerCollection.Add(manager); }
/// <summary> /// Creates a new TrackerUpdateEventArgs /// </summary> /// <param name="state">The current state of the update</param> /// <param name="response">The response of the tracker (if any)</param> public TrackerStateChangedEventArgs(TorrentManager manager, Tracker tracker, TrackerState oldState, TrackerState newState) : base(manager) { this.tracker = tracker; this.oldState = oldState; this.newState = newState; }
protected Mode(TorrentManager manager) { CanAcceptConnections = true; this.manager = manager; manager.chokeUnchoker = new ChokeUnchokeManager(manager, manager.Settings.MinimumTimeBetweenReviews, manager.Settings.PercentOfMaxRateToSkipReview); }
public void Start() { foreach (string file in Directory.GetFiles(downloadsPath, "*.torrent")) { Torrent torrent = Torrent.Load(file); string savePath = Path.Combine(downloadsPath, torrent.Name); var manager = new TorrentManager(torrent, savePath, new TorrentSettings()); manager.TorrentStateChanged += delegate(object sender, TorrentStateChangedEventArgs e) { if(e.NewState==TorrentState.Seeding) { ReportSeeding(e.TorrentManager.Torrent.Name); } Console.WriteLine("Torrent {0} changed: {1} -> {2}", e.TorrentManager.Torrent.Name, e.OldState, e.NewState); }; manager.PeerConnected += delegate(object sender, PeerConnectionEventArgs e) { Console.WriteLine("Peer {2} connect to: {0} as {1}", e.TorrentManager.Torrent.Name, e.ConnectionDirection, e.PeerID.Location); }; engine.Register(manager); } engine.StartAll(); WaitForDisposable.WaitOne(); }
/// <summary> /// Creates a new PeerMessageEventArgs /// </summary> /// <param name="message">The peer message involved</param> /// <param name="direction">The direction of the message</param> internal PeerMessageEventArgs(TorrentManager manager, PeerMessage message, Direction direction, PeerId id) : base(manager) { this.direction = direction; this.id = id; this.message = message; }
public InitialSeedingMode(TorrentManager manager) : base(manager) { unchoker = new InitialSeedUnchoker(manager); manager.chokeUnchoker = unchoker; zero = new BitField(manager.Bitfield.Length); }
/// <summary> /// Creates a new PeerMessageEventArgs /// </summary> /// <param name="manager">The manager.</param> /// <param name="message">The peer message involved</param> /// <param name="direction">The direction of the message</param> /// <param name="id">The identifier.</param> internal PeerMessageEventArgs(TorrentManager manager, PeerMessage message, Direction direction, PeerId id) : base(manager) { Direction = direction; ID = id; Message = message; }
public TorrentHandler(TorrentManager tm) { TorrentManager = tm; _delete = new List<string>(); _files = new List<FileInfo>(); _files.AddRange(Directory.GetFiles(tm.SavePath, "*.*", SearchOption.AllDirectories).Select(o => new FileInfo(o))); }
internal PeerConnectionEventArgs(TorrentManager manager, PeerId id, Direction direction, string message) : base(manager) { PeerID = id; ConnectionDirection = direction; Message = message; }
/// <summary> /// Create new instance of PeerConnectionFailedEventArgs for peer from given torrent. /// </summary> /// <param name="manager"></param> /// <param name="peer"></param> /// <param name="direction">Which direction the connection attempt was</param> /// <param name="message">Message associated with the failure</param> public PeerConnectionFailedEventArgs(TorrentManager manager, Peer peer, Direction direction, String message) : base(manager) { this.peer = peer; connectionDirection = direction; this.message = message; }
public PausedMode(TorrentManager manager) : base(manager) { // When in the Paused mode, a special RateLimiter will // activate and disable transfers. PauseMode itself // does not need to do anything special. }
public PieceMessage(TorrentManager manager, int pieceIndex, int startOffset, int blockLength) { this.manager = manager; this.pieceIndex = pieceIndex; this.startOffset = startOffset; this.requestLength = blockLength; }
public TrackerPeersAdded(TorrentManager manager, int peersAdded, int total, Tracker.Tracker tracker) : base(manager, peersAdded, total) { if (tracker == null) throw new ArgumentNullException(nameof(tracker)); Tracker = tracker; }
public static void EnqueueReceiveMessage(IConnection connection, IEncryption decryptor, IRateLimiter rateLimiter, ConnectionMonitor monitor, TorrentManager manager, AsyncMessageReceivedCallback callback, object state) { // FIXME: Hardcoded number int count = 4; var buffer = ClientEngine.BufferManager.GetBuffer (count); var data = receiveCache.Dequeue ().Initialise (connection, decryptor, rateLimiter, monitor, manager, buffer, callback, state); NetworkIO.EnqueueReceive (connection, buffer, 0, count, rateLimiter, monitor, data.ManagerMonitor, MessageLengthReceivedCallback, data); }
public EndGameSwitcher(StandardPicker standard, EndGamePicker endgame, int blocksPerPiece, TorrentManager torrentManager) : base(null) { this.standard = standard; this.endgame = endgame; this.blocksPerPiece = blocksPerPiece; this.torrentManager = torrentManager; }
public PeerExchangePeersAdded(TorrentManager manager, int count, int total, PeerId id) :base(manager, count, total) { if (id == null) throw new ArgumentNullException("id"); this.id = id; }
/// <summary> /// Creates a new TrackerUpdateEventArgs /// </summary> /// <param name="manager">The manager.</param> /// <param name="tracker">The tracker.</param> /// <param name="oldState">The old state.</param> /// <param name="newState">The new state.</param> public TrackerStateChangedEventArgs(TorrentManager manager, Tracker.Tracker tracker, TrackerState oldState, TrackerState newState) : base(manager) { Tracker = tracker; OldState = oldState; NewState = newState; }
internal TorrentManager PrepareManager(BinRootInfo bt) { //TODO: I suppose managers need to go once the torrent is finished, unless // the user wants to seed what he downloaded. We will see... var m = new TorrentManager(bt.Torrent, bt.FullPath, new TorrentSettings() { }, ""); engine.Register(m); return m; }
public InitialSeedUnchoker(TorrentManager manager) { advertisedPieces = new List<SeededPiece>(); bitfield = new BitField(manager.Bitfield.Length); this.manager = manager; peers = new List<ChokeData>(); temp = new BitField(bitfield.Length); }
public ErrorMode(TorrentManager manager) : base(manager) { CanAcceptConnections = false; CloseConnections(); }
public StartingMode(TorrentManager manager, DiskManager diskManager, ConnectionManager connectionManager, EngineSettings settings) : base(manager, diskManager, connectionManager, settings) { CanAcceptConnections = false; }
/// <summary> /// Creates a new PeersAddedEventArgs /// </summary> /// <param name="peersAdded">The number of peers just added</param> public PeerAddedEventArgs(TorrentManager manager, Peer peerAdded) : base(manager) { this.peer = peerAdded; }
public MetadataMode(TorrentManager manager, DiskManager diskManager, ConnectionManager connectionManager, EngineSettings settings, string savePath) : this(manager, diskManager, connectionManager, settings, savePath, false) { }
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); }
public static PeerMessage DecodeMessage(byte[] buffer, int offset, int count, TorrentManager manager) { PeerMessage message; CreateMessage creator; if (count < 4) { throw new ArgumentException("A message must contain a 4 byte length prefix"); } int messageLength = IPAddress.HostToNetworkOrder(BitConverter.ToInt32(buffer, offset)); if (messageLength > (count - 4)) { throw new ArgumentException("Incomplete message detected"); } if (buffer[offset + 4] == ExtensionMessage.MessageId) { return(ExtensionMessage.DecodeMessage(buffer, offset + 4 + 1, count - 4 - 1, manager)); } if (!messageDict.TryGetValue(buffer[offset + 4], out creator)) { throw new ProtocolException("Unknown message received"); } // The message length is given in the second byte and the message body follows directly after that // We decode up to the number of bytes Received. If the message isn't complete, throw an exception message = creator(manager); message.Decode(buffer, offset + 4 + 1, count - 4 - 1); return(message); }
public static string GetStatsLog(TorrentManager manager) { StringBuilder sb = new StringBuilder(); 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.Status.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, "Piece downloading sequence: [{0}].", string.Join(",", manager.TorrentStats.PieceDownloadSequence.ConvertAll <string>(x => x.ToString()))); AppendFormat(sb, "Prediction missies: {0}.", manager.TorrentStats.OnDemandRequests.Count); var peerDict = new Dictionary <PeerId, int>(); foreach (var piece in manager.TorrentStats.Pieces) { foreach (var block in piece.Blocks) { if (!block.Deduplicated) { var peerId = block.RequestedOff; if (!peerDict.ContainsKey(peerId)) { peerDict[peerId] = 1; } else { peerDict[peerId] = peerDict[peerId] + 1; } } } } AppendFormat(sb, "Peers this torrent are downloaded from (peer, blocks): [{0}].", string.Join(",", peerDict.ToList().ConvertAll <string>(x => string.Format("({0}, {1})", x.Key, x.Value)))); return(sb.ToString()); }
/// <summary> /// Creates a new PeersAddedEventArgs /// </summary> /// <param name="peersAdded">The number of peers just added</param> protected PeersAddedEventArgs(TorrentManager manager, int peersAdded, int total) : base(manager) { NewPeers = peersAdded; ExistingPeers = total - peersAdded; }
public TrackerRequestFactory(TorrentManager manager) { Manager = manager; }
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); } }
public TorrentEventArgs(TorrentManager manager) { TorrentManager = manager; }
/// <summary> /// Запускает загрузку /// </summary> /// <param name="TorrentPath">Путь к торрент файлу</param> /// <param name="DownloadPath">Путь загрузки</param> public void Start(string TorrentPath, string DownloadPath, DownloadModel downloadModel) { //Вспомогательный класс Top10Listener listener = new Top10Listener(10); TorrentManager _manager; Torrent _torrent = null; EngineSettings _engineSettings = new EngineSettings() { SavePath = DownloadPath, ListenPort = 31337 }; TorrentSettings _torrentDef = new TorrentSettings(5, 100, 0, 0); //Движок, реализующий функции закачки ClientEngine _engine = new ClientEngine(_engineSettings); BEncodedDictionary _fastResume; _fastResume = new BEncodedDictionary(); try { _torrent = Torrent.Load(TorrentPath + downloadModel.NameFile); } catch { _engine.Dispose(); } try { downloadModel.Name = _torrent.Name; _manager = new TorrentManager(_torrent, DownloadPath, _torrentDef); _engine.Register(_manager); _manager.TorrentStateChanged += delegate(object o, TorrentStateChangedEventArgs e) { lock (listener) listener.WriteLine("Last status: " + e.OldState.ToString() + " Current status: " + e.NewState.ToString()); }; foreach (TrackerTier ttier in _manager.TrackerManager.TrackerTiers) { foreach (Tracker tr in ttier.GetTrackers()) { tr.AnnounceComplete += delegate(object sender, AnnounceResponseEventArgs e) { listener.WriteLine(string.Format($"{e.Successful}: {e.Tracker}")); }; } } _manager.Start(); int i = 0; bool _running = true; StringBuilder _stringBuilder = new StringBuilder(1024); while (_running) { if ((i++) % 10 == 0) { if (_manager.State == TorrentState.Stopped) { _running = false; } downloadModel.Percent = Convert.ToInt16(_manager.Progress); downloadModel.Upload = _manager.Peers.Seeds; downloadModel.Download = _manager.Peers.Leechs; var Status = _manager.State; } } } catch { return; } }
public PauseLimiter(TorrentManager manager) { this.manager = manager; }
async Task TimedRead(TorrentManager manager, Stream stream, long position, List <(string, TimeSpan)> times)
/// <summary> /// Creates a new PieceHashedEventArgs /// </summary> /// <param name="manager">The <see cref="TorrentManager"/> whose piece was hashed</param> /// <param name="pieceIndex">The index of the piece that was hashed</param> /// <param name="hashPassed">True if the piece passed the hashcheck, false otherwise</param> internal PieceHashedEventArgs(TorrentManager manager, int pieceIndex, bool hashPassed) : this(manager, pieceIndex, hashPassed, 1, 1) { }
public void Flush(TorrentManager manager) { Check.Manager(manager); IoLoop.QueueWait(delegate { Writer.Flush(manager.Torrent.Files); }); }
internal PeerConnectionEventArgs(TorrentManager manager, PeerId id, Direction direction) : this(manager, id, direction, "") { }
public StoppingMode(TorrentManager manager, DiskManager diskManager, ConnectionManager connectionManager, EngineSettings settings) : base(manager, diskManager, connectionManager, settings) { }
public AsyncConnectState(TorrentManager manager, Peer peer, IConnection connection) { Manager = manager; Peer = peer; Connection = connection; }
public new static PeerMessage DecodeMessage(byte[] buffer, int offset, int count, TorrentManager manager) { CreateMessage creator; PeerMessage message; if (!ClientEngine.SupportsExtended) { throw new MessageException("Extension messages are not supported"); } if (!messageDict.TryGetValue(buffer[offset], out creator)) { throw new ProtocolException("Unknown extension message received"); } message = creator(manager); message.Decode(buffer, offset + 1, count - 1); return(message); }
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(); } } }
public MetadataMode(TorrentManager manager, DiskManager diskManager, ConnectionManager connectionManager, EngineSettings settings, string savePath, bool stopWhenDone) : base(manager, diskManager, connectionManager, settings) { this.savePath = savePath; this.stopWhenDone = stopWhenDone; }
public void RegisterManager(TorrentManager manager) { engine.Register(manager); }
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); } }
public void UnregisterManager(TorrentManager manager) { engine.Unregister(manager); }
public TorrentHandler(MagnetLink ML, string DownloadDir = DOWNLOAD_DIR) { InitBase(DownloadDir); TM = new TorrentManager(ML, Environment.ExpandEnvironmentVariables(DownloadDir), TS, Environment.ExpandEnvironmentVariables(TORRENT_DIR)); Assign(); }
public LocalPeersAdded(TorrentManager manager, int peersAdded, int total) : base(manager, peersAdded, total) { }
internal void Handle(TorrentManager manager, PeerId id) { manager.Mode.HandleMessage(id, this); }
public MetadataMode(TorrentManager manager, StorageFolder saveFolder) : base(manager) { _saveFolder = saveFolder; }