public LoadTorrentDialog(Torrent torrent, string defaultPath) { if (torrent == null) throw new System.ArgumentNullException ("torrent"); if (defaultPath == null) throw new System.ArgumentNullException ("defaultPath"); this.Build(); PopulateStore (torrent); BuildColumns(); this.lblName.Text = torrent.Name; this.lblSize.Text = ByteConverter.ConvertSize (torrent.Size); if (!string.IsNullOrEmpty(defaultPath)) fileChooser.SetCurrentFolder(defaultPath); }
public InfoHashTrackable(Torrent torrent) { Check.Torrent(torrent); name = torrent.Name; infoHash = torrent.InfoHash; }
public Television(TLFeed feed, Database database, Collector collector, Torrenter torrenter) { feed.New += item => { if (item.Categories[0].Name != "Episodes") return; var shows = database.Get<Show>(); if (shows.Any(show => item.Title.Text.ToLower().Contains(show.Title.ToLower()))) { var model = new Torrent(item.Title.Text, item.Links.First().Uri.ToString(), item.Categories.First().Name); collector.Event(model); torrenter.Download(item.Links.First().Uri.ToString()); } }; collector.On<Search>(search => { var wc = new WebClient(); var result = wc.DownloadString("http://www.imdb.com/xml/find?json=1&tt=on&q=" + search.Query); try { var json = JObject.Parse(result); var exact = json["title_popular"]; if (exact == null) return; if(!exact["description"].ToString().Contains("TV")) return; var show = new Show(exact[0]["title"].ToString()); collector.Event(show); } catch { } }); }
public void SetUp() { socket = new FakeSocket(); file = TorrentTestUtils.CreateMultiFileTorrent(); socket.response = TrackerResponseTest.CreateTestResponseString(); }
static void Main(string[] args) { Torrent torrent = new Torrent(BenDecoder.Decode(args[0])); Tracker trackerClient = new Tracker(torrent); Console.WriteLine("Connecting to tracker at {0}", torrent.AnnounceUri); object cv = new object(); trackerClient.Connected += delegate { Console.WriteLine("Connected to {0}", torrent.AnnounceUri); }; trackerClient.Updated += delegate { if(trackerClient.LastResponse.IsSuccessful) { Console.WriteLine("{0} Seeders, {1} leechers", trackerClient.LastResponse.NumberOfSeeds, trackerClient.LastResponse.NumberOfLeechers); ConnectToPeers(trackerClient.LastResponse.Peers, torrent); } else { QuitWithError(cv, trackerClient.LastResponse.FailureReason); } }; trackerClient.Error += delegate(object sender, Exception e) { QuitWithError(cv, e.Message); }; trackerClient.Start(); lock(cv) { Monitor.Wait(cv); } }
public TorrentGetCommand(JsonObject response) { Program.DaemonDescriptor.ResetFailCount(); if (!Program.Connected) { return; } JsonObject arguments = (JsonObject)response[ProtocolConstants.KEY_ARGUMENTS]; JsonArray torrents = (JsonArray)arguments[ProtocolConstants.KEY_TORRENTS]; Program.DaemonDescriptor.UpdateSerial++; oldCount = Program.TorrentIndex.Count; UpdateTorrents.Clear(); for (int i = 0; i < torrents.Count; i++) { JsonObject torrent = (JsonObject)torrents[i]; string hash = (string)torrent[ProtocolConstants.FIELD_HASHSTRING]; Torrent t = null; lock (Program.TorrentIndex) { if (!Program.TorrentIndex.ContainsKey(hash)) { t = new Torrent(torrent); } else { t = Program.TorrentIndex[hash]; if (t.Update(torrent, false)) stateChange = true; } UpdateTorrents.Add(t); } totalUpload += t.UploadRate; totalDownload += t.DownloadRate; } }
public InfoHashTrackable(Torrent torrent) { if (torrent == null) throw new ArgumentNullException("torrent"); name = torrent.Name; infoHash = torrent.InfoHash; }
public HashFileLinkPieces(Torrent torrent, int pieceIndex, IList<FileLinkPiece> fileLinkPieces) { this._pieceIndex = pieceIndex; this._fileLinkPieces = fileLinkPieces; this._result = -1; this._torrent = torrent; }
public CustomITrackable(Torrent t) { // Note: I'm just storing the files, infohash and name. A typical Torrent instance // is ~100kB in memory. A typical CustomITrackable will be ~100 bytes. files = t.Files; infoHash = t.InfoHash; name = t.Name; }
public TorrentViewModel(Torrent torrent, IEventAggregator eventAggregator, ErrorTracker errorTracker, ServerUnits speedUnits, ServerUnits sizeUnits) { Id = torrent.ID; TorrentFileViewModel = new TorrentFileViewModel(Id, eventAggregator, errorTracker); Size = torrent.Size.ToSizeString(sizeUnits); Hash = torrent.Hash; Update(torrent, speedUnits, sizeUnits); }
public TorrentRandomAccessStream(TorrentStreamManager manager) { _manager = manager; _torrentFile = manager.TorrentVideoFile; _torrent = manager.Torrent; var stream = File.Open(Path.Combine(_torrentFile.TargetFolder.Path, _torrentFile.Path), FileMode.Open, FileAccess.Read, FileShare.ReadWrite); _internalStream = stream.AsRandomAccessStream(); }
internal HdknTorrent(Torrent torrent) { _torrent = torrent; foreach (var file in torrent.Files) { _files.Add(new HdknTorrentFile(file)); } }
/// <summary> /// /// </summary> /// <param name="torrent"></param> /// <param name="tracker"></param> public TorrentTracker(Torrent torrent, Tracker tracker) { Torrent = torrent; Tracker = tracker; Peers = new List<Peer>(); // par défaut, les peers ne sont pas compactés Compact = false; }
public TorrentState CreateTorrentState(Torrent t) { var hash = ExtractHash(t.Magnet); var ts = new TorrentState(hash, t.Episode.Season, t.Episode.Number); _tracked.Add(new WeakReference(ts)); return ts; }
private void VerifyCommonParts(Torrent torrent) { Assert.Equal(Comment, torrent.Comment); Assert.Equal(CreatedBy, torrent.CreatedBy); Assert.True(DateTime.Now - torrent.CreationDate < TimeSpan.FromSeconds(5)); Assert.Equal(PieceLength, torrent.PieceLength); Assert.Equal(Publisher, torrent.Publisher); Assert.Equal(PublisherUrl, torrent.PublisherUrl); Assert.Equal(2, torrent.AnnounceUrls.Count); Assert.Equal(2, torrent.AnnounceUrls[0].Count); Assert.Equal(2, torrent.AnnounceUrls[1].Count); }
public WebMultiDownload(IEnumerable<string> links, string targetFilePath, string tempFolder, Torrent torrent) { this.torrent = torrent; Length = (int)torrent.Size; Name = torrent.Name; urls = new List<string>(links); this.targetFilePath = targetFilePath; pieceStates = new PieceState[torrent.Pieces.Count]; for (var i = 0; i < pieceStates.Length; i++) pieceStates[i] = PieceState.Free; if (tempFolder != null) tempFilePath = Utils.MakePath(tempFolder, Path.GetFileName(targetFilePath)); else tempFilePath = Path.GetTempFileName(); }
/// <summary> /// Adds the file to download. This method returns when the torrent is /// added and doesn't wait for the download to complete. /// </summary> /// <param name="torrent">The torrent.</param> /// <param name="savePath">The save path.</param> public void StartDownloadingFile(Torrent torrent, string savePath, int lastPieceInProfile) { TorrentSettings torrentDefaults = new TorrentSettings(4, 150, 0, 0); var tm = new TorrentManager(torrent, savePath, torrentDefaults, "", lastPieceInProfile); // There is no need to scrape since we manage the tracker. tm.TrackerManager.CurrentTracker.CanScrape = false; _clientEngine.Register(tm); tm.TrackerManager.CurrentTracker.AnnounceComplete += new EventHandler<AnnounceResponseEventArgs>( TorrentEventHandlers.HandleAnnounceComplete); tm.TrackerManager.CurrentTracker.ScrapeComplete += delegate(object o, ScrapeResponseEventArgs e) { logger.DebugFormat("Scrape completed. Successful={0}, Tracker={1}", e.Successful, e.Tracker.Uri); }; tm.TorrentStateChanged += new EventHandler<TorrentStateChangedEventArgs>( TorrentEventHandlers.HandleTorrentStateChanged); tm.PieceHashed += new EventHandler<PieceHashedEventArgs>( TorrentEventHandlers.HandlePieceHashed); tm.PeerConnected += delegate(object o, PeerConnectionEventArgs e) { // Only log three connections. if (e.TorrentManager.OpenConnections < 4) { logger.DebugFormat( "Peer ({0}) Connected. Currently {1} open connection.", e.PeerID.Uri, e.TorrentManager.OpenConnections); } }; tm.PieceManager.BlockReceived += delegate(object o, BlockEventArgs e) { logger.DebugFormat("Block {0} from piece {1} is received.", e.Block.StartOffset / Piece.BlockSize, e.Piece.Index); }; // We really only deal with one file. foreach (var file in tm.Torrent.Files) { _torrentManagerTable[file.FullPath] = tm; } tm.Start(); logger.DebugFormat( "Starting to download torrent: {0}. Torrent manager started.", tm.Torrent.Name); }
public TorrentAdapter(Torrent torrent, ObjectPath path) { this.path = path; this.torrent = torrent; this.filesPath = path.ToString () + "/files/{0}"; files = new ObjectPath[torrent.Files.Length]; for (int i=0; i < files.Length; i++) { ObjectPath p = new ObjectPath (string.Format(filesPath, i)); TorrentFileAdapter adapter = new TorrentFileAdapter (torrent.Files[i], p); files[i] = p; TorrentService.Bus.Register (p, adapter); } }
static void Main(string[] args) { string filename = args[0]; BenDecoder decoder = new BenDecoder(File.OpenRead(filename)); Torrent torrent = new Torrent(decoder.ReadDictionary()); Console.WriteLine("Tracker: {0}", torrent.AnnounceUri); Console.WriteLine("Number of pieces: {0}", torrent.Pieces.Count); Console.WriteLine("Piece length: {0}", torrent.PieceLength); Console.WriteLine("Hash: {0}", torrent.InfoHash.ToHexString()); Console.WriteLine("Files:"); foreach (ITorrentFile file in torrent.Files) { Console.WriteLine(" Name: {0}, Size: {1}", file.Name, file.Length); } }
public void AddTorrent(Torrent torrent, string path, bool suppressMessages = false) { if (!Directory.Exists(path)) Directory.CreateDirectory(path); var wrapper = new TorrentWrapper(torrent, path, new TorrentSettings()); if (Client.Torrents.Any(t => t.Torrent.InfoHash == wrapper.InfoHash)) { if (!suppressMessages) MessageBox.Show(torrent.Name + " has already been added.", "Error"); return; } var periodic = Client.AddTorrent(wrapper); // Save torrent to cache var cache = Path.Combine(SettingsManager.TorrentCachePath, Path.GetFileName(torrent.TorrentPath)); if (File.Exists(cache)) File.Delete(cache); File.Copy(torrent.TorrentPath, cache); File.WriteAllText(Path.Combine(Path.GetDirectoryName(cache), Path.GetFileNameWithoutExtension(cache)) + ".info", path); periodic.CacheFilePath = cache; }
public void StartUp() { DateTime current = new DateTime(2006, 7, 1, 5, 5, 5); DateTime epochStart = new DateTime(1970, 1, 1, 0, 0, 0); TimeSpan span = current - epochStart; creationTime = (long)span.TotalSeconds; Console.WriteLine(creationTime.ToString() + "Creation seconds"); BEncodedDictionary torrentInfo = new BEncodedDictionary(); torrentInfo.Add("announce", new BEncodedString("http://myannouceurl/announce")); torrentInfo.Add("creation date", new BEncodedNumber(creationTime)); torrentInfo.Add("nodes", new BEncodedList()); //FIXME: What is this? torrentInfo.Add("comment.utf-8", new BEncodedString("my big long comment")); torrentInfo.Add("comment", new BEncodedString("my big long comment")); torrentInfo.Add("azureus_properties", new BEncodedDictionary()); //FIXME: What is this? torrentInfo.Add("created by", new BEncodedString("MonoTorrent/" + VersionInfo.ClientVersion)); torrentInfo.Add("encoding", new BEncodedString("UTF-8")); torrentInfo.Add("info", CreateInfoDict()); torrentInfo.Add("private", new BEncodedString("1")); torrent = Torrent.Load(torrentInfo); }
private static void ConnectToPeers(List<PeerInfo> peers, Torrent torrent) { foreach(PeerInfo peerInfo in peers) { Peer remotePeer = new Peer(peerInfo, torrent, PeerId.GetDefaultPeerId()); Console.WriteLine("Connecting to {0}:{1}", peerInfo.IpAddress, peerInfo.Port); remotePeer.Connected += delegate(object sender, EventArgs args) { Peer peer = sender as Peer; Console.WriteLine("Connected to peer at {0} on port {1}", peer.Info.IpAddress, (ushort)peer.Info.Port); }; remotePeer.HandshakeReceived += delegate(object sender, PeerEventArgs args) { Peer peer = sender as Peer; Console.WriteLine("Received handshake from {0}", peer.Info.IpAddress); }; remotePeer.Error += delegate(object sender, PeerEventArgs args) { Peer peer = sender as Peer; System.Diagnostics.Debug.WriteLine(string.Format("Error from {0}: {1}", peer.Info.IpAddress, args.Exception.Message)); }; remotePeer.Connect(); } }
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(); } }
protected override void HandleLtMetadataMessage(PeerId id, LTMetadata message) { base.HandleLtMetadataMessage(id, message); switch (message.MetadataMessageType) { case LTMetadata.eMessageType.Data: if (stream == null) { throw new Exception("Need extention handshake before ut_metadata message."); } stream.Seek(message.Piece * LTMetadata.BlockSize, SeekOrigin.Begin); stream.Write(message.MetadataPiece, 0, message.MetadataPiece.Length); bitField[message.Piece] = true; if (bitField.AllTrue) { byte[] hash; stream.Position = 0; using (SHA1 hasher = HashAlgoFactory.Create <SHA1>()) hash = hasher.ComputeHash(stream); if (!Manager.InfoHash.Equals(hash)) { bitField.SetAll(false); } else { Torrent t; stream.Position = 0; BEncodedDictionary dict = new BEncodedDictionary(); dict.Add("info", BEncodedValue.Decode(stream)); // FIXME: Add the trackers too if (Torrent.TryLoad(dict.Encode(), out t)) { try { if (Directory.Exists(savePath)) { savePath = Path.Combine(savePath, Manager.InfoHash.ToHex() + ".torrent"); } File.WriteAllBytes(savePath, dict.Encode()); } catch (Exception ex) { Logger.Log(null, "*METADATA EXCEPTION* - Can not write in {0} : {1}", savePath, ex); Manager.Error = new Error(Reason.WriteFailure, ex); Manager.Mode = new ErrorMode(Manager); return; } t.TorrentPath = savePath; Manager.Torrent = t; SwitchToRegular(); } else { bitField.SetAll(false); } } } //Double test because we can change the bitfield in the other block if (!bitField.AllTrue) { RequestNextNeededPiece(id); } break; case LTMetadata.eMessageType.Reject: //TODO //Think to what we do in this situation //for moment nothing ;) //reject or flood? break; case LTMetadata.eMessageType.Request: //ever done in base class but needed to avoid default break; default: throw new MessageException(string.Format("Invalid messagetype in LTMetadata: {0}", message.MetadataMessageType)); } }
public WebMultiDownload(IEnumerable <string> links, string targetFilePath, string tempFolder, Torrent torrent) { this.torrent = torrent; Length = (int)torrent.Size; Name = torrent.Name; urls = new List <string>(links); this.targetFilePath = targetFilePath; pieceStates = new PieceState[torrent.Pieces.Count]; for (var i = 0; i < pieceStates.Length; i++) { pieceStates[i] = PieceState.Free; } if (tempFolder != null) { tempFilePath = Utils.MakePath(tempFolder, Path.GetFileName(targetFilePath)); } else { tempFilePath = Path.GetTempFileName(); } }
public async Task <TorrentManager> AddStreamingAsync(string metadataPath, string saveDirectory, TorrentSettings settings) => await AddStreamingAsync(null, await Torrent.LoadAsync(metadataPath), saveDirectory, settings);
public Task <TorrentManager> AddStreamingAsync(Torrent torrent, string saveDirectory, TorrentSettings settings) => AddStreamingAsync(null, torrent, saveDirectory, settings);
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} 选择监听的端口: "); 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("No existing dht nodes could be loaded"); } 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, "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.LastScrapSucceeded}."); } 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); } // 停止搜索与uPnP或NAT-PMP兼容的设备,并删除所有已创建的映射. await engine.DisablePortForwardingAsync(CancellationToken.None); }
public bool HasTorrentGoalsBeenReached(Torrent torrent) { return(true); }
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); }
public HttpTracker(Torrent a_torrent, string a_trackerUrl) : base(a_torrent, a_trackerUrl) { }
public void Start(Torrent torrent) { throw new NotImplementedException(); }
public ActionResult Index(UploadModel uploadModel) { if (!ModelState.IsValid) { /* * var errors = ModelState * .Where(x => x.Value.Errors.Count > 0) * .Select(x => new { x.Key, x.Value.Errors }) * .ToArray(); */ foreach (var _error in GetModelStateErrorsAsList(this.ModelState)) { ModelState.AddModelError("", _error.ErrorMessage); } return(View(uploadModel)); } Torrent t; try { t = Torrent.Load(uploadModel.TorrentFile.InputStream); } catch (Exception) { ModelState.AddModelError("", "Invalid .torrent file."); return(View(uploadModel)); } if (!t.IsPrivate) { ModelState.AddModelError("", "The torrent file needs to be marked as \"Private\" when you create the torrent."); return(View(uploadModel)); } var TORRENT_DIR = TrackerSettings.TORRENT_DIRECTORY; var NFO_DIR = TrackerSettings.NFO_DIRECTORY; using (var db = new OpenTrackerDbContext()) { // var _torrentFilename = uploadModel.TorrentFile.FileName; if (!string.IsNullOrEmpty(uploadModel.TorrentName)) { _torrentFilename = uploadModel.TorrentName; } var cleanTorentFilename = Regex.Replace(_torrentFilename, "[^A-Za-z0-9]", string.Empty); var finalTorrentFilename = string.Format("TEMP-{0}-{1}", DateTime.Now.Ticks, cleanTorentFilename); var _torrentPath = Path.Combine(TORRENT_DIR, string.Format("{0}.torrent", finalTorrentFilename)); var _nfoPath = Path.Combine(NFO_DIR, string.Format("{0}.nfo", finalTorrentFilename)); uploadModel.NFO.SaveAs(_nfoPath); uploadModel.TorrentFile.SaveAs(_torrentPath); var infoHash = t.InfoHash.ToString().Replace("-", string.Empty); var torrentSize = t.Files.Sum(file => file.Length); var numfiles = t.Files.Count(); var client = t.CreatedBy; var torrent = new torrents { categoryid = uploadModel.CategoryId, info_hash = infoHash, torrentname = _torrentFilename.Replace(".torrent", string.Empty), description = uploadModel.Description, description_small = uploadModel.SmallDescription, added = (int)Unix.ConvertToUnixTimestamp(DateTime.UtcNow), numfiles = numfiles, size = torrentSize, client_created_by = client, owner = new Core.Account.AccountInformation().UserId }; db.AddTotorrents(torrent); db.SaveChanges(); var _torrent = (from tor in db.torrents where tor.info_hash == infoHash select tor) .Select(tor => new { tor.info_hash, tor.id }) .Take(1) .FirstOrDefault(); if (_torrent == null) { // TODO: error logging etc. here } else { System.IO.File.Move(_torrentPath, Path.Combine(TORRENT_DIR, string.Format("{0}.torrent", _torrent.id))); System.IO.File.Move(_nfoPath, Path.Combine(NFO_DIR, string.Format("{0}.nfo", _torrent.id))); var files = t.Files; foreach (var tFile in files.Select(torrentFile => new torrents_files { torrentid = torrent.id, filename = torrentFile.FullPath, filesize = torrentFile.Length }).OrderBy(torrentFile => torrentFile.filename)) { db.AddTotorrents_files(tFile); } db.SaveChanges(); } return(RedirectToAction("Index", "Browse")); } }
public async Task RunAsync() { //LoggerFactory.Creator = className => new TextLogger (Console.Out, className); int port = 37827; var seeder = new ClientEngine( new EngineSettingsBuilder { AllowedEncryption = new[] { EncryptionType.PlainText }, DiskCacheBytes = DataSize, ListenPort = port++ }.ToSettings() ); await seeder.ChangePieceWriterAsync(new NullWriter()); var downloaders = Enumerable.Range(port, 16).Select(p => { return(new ClientEngine( new EngineSettingsBuilder { AllowedEncryption = new[] { EncryptionType.PlainText }, DiskCacheBytes = DataSize, ListenPort = p, }.ToSettings() )); }).ToArray(); foreach (var engine in downloaders) { await engine.ChangePieceWriterAsync(new NullWriter()); } Directory.CreateDirectory(DataDir); // Generate some fake data on-disk var buffer = Enumerable.Range(0, 16 * 1024).Select(s => (byte)s).ToArray(); using (var fileStream = File.OpenWrite(Path.Combine(DataDir, "file.data"))) { for (int i = 0; i < DataSize / buffer.Length; i++) { fileStream.Write(buffer, 0, buffer.Length); } fileStream.SetLength(DataSize); } var trackerListener = TrackerListenerFactory.CreateHttp(IPAddress.Parse("127.0.0.1"), 25611); var tracker = new MonoTorrent.Tracker.TrackerServer { AllowUnregisteredTorrents = true }; tracker.RegisterListener(trackerListener); trackerListener.Start(); // Create the torrent file for the fake data var creator = new TorrentCreator(); creator.Announces.Add(new List <string> ()); creator.Announces [0].Add("http://127.0.0.1:25611/announce"); var metadata = await creator.CreateAsync(new TorrentFileSource (DataDir)); // Set up the seeder await seeder.Register(new TorrentManager (Torrent.Load(metadata), DataDir, new TorrentSettingsBuilder { UploadSlots = 20 }.ToSettings())); using (var fileStream = File.OpenRead(Path.Combine(DataDir, "file.data"))) { while (fileStream.Position < fileStream.Length) { var dataRead = new byte[16 * 1024]; int offset = (int)fileStream.Position; int read = fileStream.Read(dataRead, 0, dataRead.Length); // FIXME: Implement a custom IPieceWriter to handle this. // The internal MemoryWriter is limited and isn't a general purpose read/write API // await seederWriter.WriteAsync (seeder.Torrents[0].Files[0], offset, dataRead, 0, read, false); } } await seeder.StartAllAsync(); List <Task> tasks = new List <Task> (); for (int i = 0; i < downloaders.Length; i++) { await downloaders[i].Register(new TorrentManager( Torrent.Load(metadata), Path.Combine(DataDir, "Downloader" + i) )); tasks.Add(RepeatDownload(downloaders[i])); } while (true) { long downTotal = seeder.TotalDownloadSpeed; long upTotal = seeder.TotalUploadSpeed; long totalConnections = 0; long dataDown = seeder.Torrents[0].Monitor.DataBytesDownloaded + seeder.Torrents[0].Monitor.ProtocolBytesDownloaded; long dataUp = seeder.Torrents[0].Monitor.DataBytesUploaded + seeder.Torrents[0].Monitor.ProtocolBytesUploaded; foreach (var engine in downloaders) { downTotal += engine.TotalDownloadSpeed; upTotal += engine.TotalUploadSpeed; dataDown += engine.Torrents[0].Monitor.DataBytesDownloaded + engine.Torrents[0].Monitor.ProtocolBytesDownloaded; dataUp += engine.Torrents[0].Monitor.DataBytesUploaded + engine.Torrents[0].Monitor.ProtocolBytesUploaded; totalConnections += engine.ConnectionManager.OpenConnections; } Console.Clear(); Console.WriteLine($"Speed Down: {downTotal / 1024 / 1024}MB."); Console.WriteLine($"Speed Up: {upTotal / 1024 / 1024}MB."); Console.WriteLine($"Data Down: {dataDown / 1024 / 1024}MB."); Console.WriteLine($"Data Up: {dataUp / 1024 / 1024}MB."); Console.WriteLine($"Total Connections: {totalConnections}"); await Task.Delay(3000); } }
public Task <bool> RemoveAsync(Torrent torrent) { torrent = torrent ?? throw new ArgumentNullException(nameof(torrent)); return(RemoveAsync(torrent.InfoHash)); }
internal Torrent TorrentByHash(string hash) { Torrent torrent = _torrentSession.TorrentsAll.TorrentByHash(hash); return(torrent); }
private void ConnectNewPeersIfNeeded(IPeerConnector peerConnector, ITracker tracker, Torrent torrent) { if (peerConnector.Peers.Count < 25) { var trackerResult = tracker.Track(torrent, TrackerEvent.Started).Result; foreach (var peer in trackerResult.Peers) { var t = new Thread(() => peerConnector.TryConnectToPeer(peer, OnPeerEvent)); t.Start(); } } }
protected override void HandleLtMetadataMessage(PeerId id, LTMetadata message) { base.HandleLtMetadataMessage(id, message); switch (message.MetadataMessageType) { case LTMetadata.eMessageType.Data: // If we've already received everything successfully, do nothing! if (bitField.AllTrue) { return; } if (Stream == null) { throw new Exception("Need extention handshake before ut_metadata message."); } Stream.Seek(message.Piece * LTMetadata.BlockSize, SeekOrigin.Begin); Stream.Write(message.MetadataPiece, 0, message.MetadataPiece.Length); bitField[message.Piece] = true; if (bitField.AllTrue) { byte[] hash; Stream.Position = 0; using (SHA1 hasher = HashAlgoFactory.SHA1()) hash = hasher.ComputeHash(Stream); if (!Manager.InfoHash.Equals(hash)) { bitField.SetAll(false); } else { Stream.Position = 0; BEncodedDictionary dict = new BEncodedDictionary(); dict.Add("info", BEncodedValue.Decode(Stream)); if (Manager.TrackerManager.Tiers != null && Manager.TrackerManager.Tiers.Count > 0) { BEncodedList announceTrackers = new BEncodedList(); foreach (var tier in Manager.TrackerManager.Tiers) { BEncodedList announceUrls = new BEncodedList(); foreach (var tracker in tier.Trackers) { announceUrls.Add(new BEncodedString(tracker.Uri.OriginalString)); } announceTrackers.Add(announceUrls); } dict.Add("announce-list", announceTrackers); } var rawData = dict.Encode(); if (Torrent.TryLoad(rawData, out Torrent t)) { if (stopWhenDone) { Manager.RaiseMetadataReceived(rawData); return; } try { if (this.Settings.AutoSaveLoadMagnetLinkMetadata) { if (!Directory.Exists(Path.GetDirectoryName(savePath))) { Directory.CreateDirectory(Path.GetDirectoryName(savePath)); } File.Delete(savePath); File.WriteAllBytes(savePath, dict.Encode()); } } catch (Exception ex) { logger.ExceptionFormated(ex, "Cannot write metadata to path '{0}'", savePath); Manager.TrySetError(Reason.WriteFailure, ex); return; } Manager.SetMetadata(t); _ = Manager.StartAsync(); Manager.RaiseMetadataReceived(rawData); } else { bitField.SetAll(false); } } } RequestNextNeededPiece(id); break; case LTMetadata.eMessageType.Reject: //TODO //Think to what we do in this situation //for moment nothing ;) //reject or flood? break; case LTMetadata.eMessageType.Request: //ever done in base class but needed to avoid default break; default: throw new MessageException($"Invalid messagetype in LTMetadata: {message.MetadataMessageType}"); } }
public static string BuildTorrentTitle(Torrent torrent) => $"{GetTorrentTitlePrefix(torrent.series)}{torrent.series} [{torrent.quality}]";
public Download addTorrent(Torrent torrent, string savePath, bool startTorrent) { return(addTorrent(torrent, startTorrent, SettingsManager.Preferences.RemoveOnImport, null, savePath, false)); }
public Task <TorrentManager> AddStreamingAsync(Torrent torrent, string saveDirectory) => AddStreamingAsync(torrent, saveDirectory, new TorrentSettings());
public static void DownloadTorrent(string url, string downloadDirectory, int maxUploadSpeed) { var torrentFileName = string.Format("{0}.torrent", url.GetHashCode().ToString(CultureInfo.InvariantCulture)); var torrentManager = new TorrentManager( Torrent.Load(new Uri(url), torrentFileName), downloadDirectory, new TorrentSettings()); // find an unused port var listener = new TcpListener(IPAddress.Any, 0); listener.Start(); var port = ((IPEndPoint)listener.LocalEndpoint).Port; listener.Stop(); var engineSettings = new EngineSettings(downloadDirectory, port) { PreferEncryption = false, AllowedEncryption = EncryptionTypes.All, GlobalMaxUploadSpeed = maxUploadSpeed }; var dhtListner = new DhtListener(new IPEndPoint(IPAddress.Any, port)); var dht = new DhtEngine(dhtListner); var engine = new ClientEngine(engineSettings); engine.Register(torrentManager); engine.RegisterDht(dht); dhtListner.Start(); engine.DhtEngine.Start(); engine.StartAll(); while (true) { var status = string.Format("{0:0.00}% - {1}\nDL:{2:0.00} kB/s \nUL:{3:0.00} kB/s ", torrentManager.Progress, torrentManager.Torrent.Name, torrentManager.Monitor.DownloadSpeed / 1024.0, torrentManager.Monitor.UploadSpeed / 1024.0); var cursorPosition = new Tuple <int, int>(Console.CursorLeft, Console.CursorTop); Console.WriteLine(status); if (torrentManager.State == TorrentState.Seeding) { Console.WriteLine(); break; } Console.SetCursorPosition(cursorPosition.Item1, cursorPosition.Item2); Thread.Sleep(500); } dhtListner.Stop(); engine.DhtEngine.Stop(); engine.StopAll(); engine.Dispose(); File.Delete(torrentFileName); }
public Download addTorrent(Torrent torrent, bool startTorrent, bool removeOriginal, TorrentSettings savedSettings) { return(addTorrent(torrent, startTorrent, removeOriginal, savedSettings, engine.Settings.SavePath, false)); }
public TorrentDetailsMessage(object sender, Torrent torrent) : base(sender) { Torrent = torrent; }
// TODO: Refactor all of these functions!!! public Download addTorrent(Torrent torrent) { return(addTorrent(torrent, SettingsManager.EngineSettings.SavePath, SettingsManager.Preferences.StartNewTorrents)); }
/// <summary> /// Creates a new TorrentManager instance. /// </summary> /// <param name="torrent">The torrent to load in</param> /// <param name="savePath">The directory to save downloaded files to</param> /// <param name="settings">The settings to use for controlling connections</param> public TorrentManager(Torrent torrent, string savePath, TorrentSettings settings) : this(torrent, savePath, settings, torrent.Files.Length == 1 ? "" : torrent.Name) { }
static void VerifyCommonParts(Torrent torrent) { Assert.AreEqual(Comment, torrent.Comment, "#1"); Assert.AreEqual(CreatedBy, torrent.CreatedBy, "#2"); Assert.IsTrue((DateTime.Now - torrent.CreationDate) < TimeSpan.FromSeconds(5), "#3"); Assert.AreEqual(PieceLength, torrent.PieceLength, "#4"); Assert.AreEqual(Publisher, torrent.Publisher, "#5"); Assert.AreEqual(PublisherUrl, torrent.PublisherUrl, "#6"); Assert.AreEqual(2, torrent.AnnounceUrls.Count, "#7"); Assert.AreEqual(2, torrent.AnnounceUrls[0].Count, "#8"); Assert.AreEqual(2, torrent.AnnounceUrls[1].Count, "#9"); }
void Row_MouseRightButtonDown(object sender, MouseButtonEventArgs e) { DataGridRow dgr = sender as DataGridRow; if (dgr == null) { return; } if (dgTorrents.Items == null || dgTorrents.Items.Count == 0) { return; } if (dgTorrents.SelectedItems == null || dgTorrents.SelectedItems.Count == 0) { dgTorrents.SelectedItem = dgr.DataContext; } if (dgTorrents.SelectedItems.Count == 1) { dgTorrents.SelectedItem = dgr.DataContext; } ContextMenu m = new ContextMenu(); List <Torrent> selectedTorrents = new List <Torrent>(); foreach (object obj in dgTorrents.SelectedItems) { Torrent tor = obj as Torrent; selectedTorrents.Add(tor); } MenuItem itemStart = new MenuItem(); itemStart.Header = "Start"; itemStart.Click += new RoutedEventHandler(torrentStart); itemStart.CommandParameter = selectedTorrents; MenuItem itemStop = new MenuItem(); itemStop.Header = "Stop"; itemStop.Click += new RoutedEventHandler(torrentStop); itemStop.CommandParameter = selectedTorrents; MenuItem itemPause = new MenuItem(); itemPause.Header = "Pause"; itemPause.Click += new RoutedEventHandler(torrentPause); itemPause.CommandParameter = selectedTorrents; MenuItem itemRemove = new MenuItem(); itemRemove.Header = "Remove Torrent"; itemRemove.Click += new RoutedEventHandler(torrentRemove); itemRemove.CommandParameter = selectedTorrents; MenuItem itemRemoveData = new MenuItem(); itemRemoveData.Header = "Remove Torrent and Files"; itemRemoveData.Click += new RoutedEventHandler(torrentRemoveData); itemRemoveData.CommandParameter = selectedTorrents; if (selectedTorrents.Count == 1) { Torrent tor = selectedTorrents[0]; if (tor.IsNotRunning || tor.IsPaused) { m.Items.Add(itemStart); } if (tor.IsRunning || tor.IsPaused) { m.Items.Add(itemStop); } if (tor.IsRunning) { m.Items.Add(itemPause); } } else { m.Items.Add(itemStart); m.Items.Add(itemStop); m.Items.Add(itemPause); } m.Items.Add(itemRemove); m.Items.Add(itemRemoveData); m.IsOpen = true; }
public PeriodicTorrent GetTorrent(Torrent torrent) { return Torrents.FirstOrDefault(t => t.Torrent.Torrent == torrent); }
public bool Add(Torrent torrent) { return(true); }
public Task <bool> RemoveAsync(Torrent torrent) => RemoveAsync(torrent, RemoveMode.CacheDataOnly);
public TorrentWrapper(Torrent torrent, string savePath, TorrentSettings settings) : base(torrent, savePath, settings) { Name = torrent.Name; Size = torrent.Size; IsMagnet = false; Path = savePath; }
/// <summary> /// Opens the clicked torrent's webpage /// </summary> /// <param name="clickedItem"></param> public async void OnTorrentInfoClick(Torrent clickedItem) { await Windows.System.Launcher.LaunchUriAsync(new Uri(clickedItem.Comments)); }
internal TorrentManager CreateTorrentManager(Torrent torrent, IFile file) { string localPath = (file is LocalFile) ? System.IO.Path.GetDirectoryName(((LocalFile)file).LocalPath) : engine.Settings.SavePath; LoggingService.LogDebug("Local path: {0}", localPath); TorrentManager manager = new TorrentManager(torrent, localPath, torrentDefaults); engine.Register(manager); LoggingService.LogDebug("{0}: Registered Manager with engine", Environment.TickCount); return manager; }
private static void StartEngine() { int port; Torrent torrent; // 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 var engineSettings = new EngineSettings(_downloadsPath, port) { PreferEncryption = false, 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 var 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. var 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 += ManagerPeersFound; } } // 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(string.Format("OldState: {0} NewState: {1}", e.OldState, e.NewState)); }; // Every time the tracker's state changes, this is fired foreach (var tracker in manager.TrackerManager.SelectMany(tier => tier.Trackers)) { tracker.AnnounceComplete += (sender, 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. var i = 0; var running = true; var 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 (var 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)); var 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 (var peerId in manager.GetPeers()) { AppendFormat(sb, "\t{2} - {1:0.00}/{3:0.00}kB/sec - {0}", peerId.Peer.ConnectionUri, peerId.Monitor.DownloadSpeed / 1024.0, peerId.AmRequestingPiecesCount, peerId.Monitor.UploadSpeed / 1024.0); } AppendFormat(sb, "", null); if (manager.Torrent != null) { foreach (var 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); } }
public void SetUp() { torrent = TorrentTestUtils.CreateMultiFileTorrent(); }
private static Torrent ParseBitTorrent(BEncodedDictionary metaData) { var torrent = new Torrent(); if (metaData.ContainsKey("name.utf-8")) { torrent.Name = ((BEncodedString)metaData["name.utf-8"]).Text; } else if (metaData.ContainsKey("name")) { torrent.Name = ((BEncodedString)metaData["name"]).Text; } if (metaData.ContainsKey("length")) { torrent.FileSize = ((BEncodedNumber)metaData["length"]).Number; } if (metaData.ContainsKey("files")) { var files = (BEncodedList)metaData["files"]; torrent.Files = new List <TorrentFile>(); for (int j = 0; j < files.Count; j++) { var file = (BEncodedDictionary)files[j]; var filePaths = file.ContainsKey("path.utf-8") ? ((BEncodedList)file["path.utf-8"]).Select(path => ((BEncodedString)path).Text).ToArray() : ((BEncodedList)file["path"]).Select(path => ((BEncodedString)path).Text).ToArray(); var fileSize = ((BEncodedNumber)file["length"]).Number; if (filePaths.Length > 1) { var directory = torrent.Files.FirstOrDefault(f => f.Name == filePaths[0]); if (directory == null) { directory = new TorrentFile() { Name = filePaths[0], Files = new List <TorrentFile>() }; torrent.Files.Add(directory); } for (int i = 1, l = filePaths.Length - 1; i < filePaths.Length; i++) { var path = filePaths[i]; if (i == l && (!path.StartsWith("_____padding_file_") && !path.EndsWith("或以上版本____"))) { var fileItem = new TorrentFile() { Name = path, FileSize = fileSize }; directory.Files.Add(fileItem); } else { var newDirectory = directory.Files.FirstOrDefault(f => f.Name == path); if (newDirectory == null) { newDirectory = new TorrentFile() { Name = path, Files = new List <TorrentFile>() }; directory.Files.Add(newDirectory); } directory = newDirectory; } } } else if (filePaths.Length == 1) { if (filePaths[0].StartsWith("_____padding_file_") && filePaths[0].EndsWith("或以上版本____")) { continue; } var item = new TorrentFile { FileSize = fileSize, Name = filePaths[0] }; torrent.Files.Add(item); } } } return(torrent); }
public void AddOtherTorrent(Torrent torrent) { string[] information = torrent.GetInformation(); dataset.OthersTableRow row = data.OthersTable.NewOthersTableRow(); row.File = information[11]; row.File_Path = information[10]; row.Save_Structure = information[13]; row.Site_Origin = information[12]; row.Sent = false; data.OthersTable.AddOthersTableRow(row); }
public void AddTorrent(Torrent torrent) { #region Information Contents /* **Information[0-10] -- Music information** * * information[0] --> Artist * information[1] --> Album * information[2] --> AlbumType * information[3] --> bitrate * information[4] --> year * information[5] --> physical format (CD,DVD,VINYL,WEB) * information[6] --> bit format (MP3,FLAC) * * **Information[10-20] -- File Information** * * information[10] --> path * information[11] --> file name * information[12] --> birth * information[13] --> destination path * information[14] --> discard * */ #endregion dataset.TorrentsTableRow row = data.TorrentsTable.NewTorrentsTableRow(); string[] information = torrent.GetInformation(); row.BeginEdit(); row.File = information[11]; row.Artist = information[0]; row.Album = information[1]; row.Save_Structure = information[13]; row.Sent = false; row.Release_Format = information[2]; row.Bit_Rate = information[3]; row.Year = information[4]; row.Physical_Format = information[5]; row.Bit_Format = information[6]; row.File_Path = information[10]; row.Site_Origin = information[12]; row.EndEdit(); while (datasetbusy) System.Threading.Thread.Sleep(100);//sleep while changes are occuring.. DataRow dr = data.TorrentsTable.Rows.Find(row.ID); while (dr != null) { row.ID++; dr = data.TorrentsTable.Rows.Find(row.ID); } data.TorrentsTable.AddTorrentsTableRow(row); musicadapter.Update(row); }
public ToolTip(Control control, Torrent torrent) { _torrent = torrent; this.OwnerDraw = true; this.Draw +=ToolTip_Draw; this.Popup += ToolTip_Popup; this.Disposed += ToolTip_Disposed; AutoPopDelay = 15000; InitialDelay = 1000; ReshowDelay = 500; ShowAlways = true; base.ToolTipTitle = torrent.TorrentName; base.SetToolTip(control, torrent.PublisherUrl); }