static void Main(string[] args) { TorrentFile torrent; using (var stream = new FileStream("ubuntu-13.10-desktop-amd64.iso.torrent", FileMode.Open)) using (var decoded = new TorrentBDecoder(stream, Encoding.UTF8)) { var torrentAsDictionary = decoded.Decode() as Dictionary<object, object>; torrent = new TorrentFile(torrentAsDictionary, decoded.GetInfoHash()); } if (torrent.IsMultiAnnounce) { // Trackers are grouped. foreach (var trackerList in torrent.AnnounceList) { foreach(var tracker in trackerList) Console.WriteLine("Tracker: " + tracker); } } else { Console.WriteLine("Tracker: " + torrent.Announce); } }
internal bool Exists(string path, TorrentFile[] files) { Check.Path(path); Check.Files(files); foreach (var file in files) if (Exists(path, file)) return true; return false; }
internal TorrentFileStream GetStream(TorrentFile file, FileAccess access) { TorrentFileStream s = FindStream(file.FullPath); if (s != null) { // If we are requesting write access and the current stream does not have it if (((access & FileAccess.Write) == FileAccess.Write) && !s.CanWrite) { Logger.Log (null, "Didn't have write permission - reopening"); CloseAndRemove(s); s = null; } else { // Place the filestream at the end so we know it's been recently used list.Remove(s); list.Add(s); } } if (s == null) { if (!File.Exists(file.FullPath)) { Directory.CreateDirectory (Path.GetDirectoryName(file.FullPath)); SparseFile.CreateSparse (file.FullPath, file.Length); } s = new TorrentFileStream (file, FileMode.OpenOrCreate, access, FileShare.Read); Add(s); } return s; }
internal BufferedIO(object manager, ArraySegment<byte> buffer, long offset, int count, int pieceLength, TorrentFile[] files, string path) { this.Path = path; this.files = files; this.pieceLength = pieceLength; Initialise(buffer, offset, count); }
/// <summary> /// Parses a TorrentFile collection changeset into regular KeyValuePair enumerable. /// </summary> /// <param name="files"></param> /// <returns></returns> private static IEnumerable<KeyValuePair<string,string >> CreateQueryString(TorrentFile[] files) { var changed = (from f in files where f.PriorityChanged group f by f.Hash into g select new { Hash = g.Key, Values = g.Select(fl => new { Prior = fl.Priority, Index = Array.IndexOf(files, fl) }) }); var parameters = new List<KeyValuePair<string, string>>(); foreach (var ch in changed) { parameters.Add(new KeyValuePair<string, string>("hash",ch.Hash)); foreach (var value in ch.Values) { parameters.Add( new KeyValuePair<string, string>("p",((int)value.Prior).ToString())); parameters.Add(new KeyValuePair<string, string>("f",value.Index.ToString())); } } return parameters; }
public override void Move(string oldPath, string newPath, TorrentFile file, bool ignoreExisting) { var oldFile = GenerateFilePath(oldPath, file); var newFile = GenerateFilePath(newPath, file); streamsBuffer.CloseStream(oldFile); if (ignoreExisting) File.Delete(newFile); File.Move(oldFile, newFile); }
public override void Initialise(BitField bitfield, TorrentFile[] files, IEnumerable<Piece> requests) { this.bitfield = bitfield; endgameSelector = new BitField(bitfield.Length); this.files = files; inEndgame = false; TryEnableEndgame(); ActivePicker.Initialise(bitfield, files, requests); }
internal TorrentFileStream GetStream(TorrentFile file, FileAccessMode access) { var fullPath = file.FullPath; var asyncTokens = GetAsyncTokens(fullPath); try { asyncTokens.CancellationTokenSource.Token.ThrowIfCancellationRequested(); var s = FindStream(fullPath); if (s != null) { // If we are requesting write access and the current stream does not have it if (access == FileAccessMode.ReadWrite && !s.CanWrite) { Debug.WriteLine("Didn't have write permission - reopening"); CloseAndRemove(s); } else { lock (_locker) { // Place the filestream at the end so we know it's been recently used _streams.Remove(s); _streams.Add(s); } return s; } } try { var result = OpenStreamAsync(file, access, asyncTokens).Result; file.Exists = true; s = new TorrentFileStream(file, result) { Size = (ulong) file.Length }; Add(s); } catch (AggregateException ex) { if (ex.InnerException is OperationCanceledException || ex.InnerException is UnauthorizedAccessException) throw ex.InnerException; throw; } return s; } finally { if (asyncTokens != null) { asyncTokens.SemaphoreSlim.Release(); if (asyncTokens.CancellationTokenSource.IsCancellationRequested) Clear(fullPath); } } }
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(); }
public override void Write(TorrentFile file, long offset, byte[] buffer, int bufferOffset, int count) { Check.File(file); Check.Buffer(buffer); if (offset < 0L || offset + count > file.Length) throw new ArgumentOutOfRangeException(nameof(offset)); var s = GetStream(file, FileAccessMode.ReadWrite); s.Seek((ulong) offset); s.WriteAsync(buffer.AsBuffer(bufferOffset, count)).AsTask().Wait(); }
private string savePath; // The path where the base directory will be put #endregion Fields #region Constructors /// <summary> /// Creates a new FileManager with the supplied FileAccess /// </summary> /// <param name="files">The TorrentFiles you want to create/open on the disk</param> /// <param name="baseDirectory">The name of the directory that the files are contained in</param> /// <param name="savePath">The path to the directory that contains the baseDirectory</param> /// <param name="pieceLength">The length of a "piece" for this file</param> /// <param name="fileAccess">The access level for the files</param> internal FileManager(TorrentManager manager, TorrentFile[] files, int pieceLength, string savePath, string baseDirectory) { this.hasher = SHA1.Create(); this.manager = manager; this.savePath = Path.Combine(savePath, baseDirectory); this.files = files; this.pieceLength = pieceLength; foreach (TorrentFile file in files) fileSize += file.Length; }
public override void Initialise(BitField bitfield, TorrentFile[] files, IEnumerable<Piece> requests) { // 'Requests' should contain a list of all the pieces we need to complete pieces = new List<Piece>(requests); foreach (var piece in pieces) { for (var i = 0; i < piece.BlockCount; i++) if (piece.Blocks[i].RequestedOff != null) this.requests.Add(new Request(piece.Blocks[i].RequestedOff, piece.Blocks[i])); } }
public override void Write(TorrentFile file, long offset, byte[] buffer, int bufferOffset, int count) { Check.File(file); Check.Buffer(buffer); if (offset < 0 || offset + count > file.Length) throw new ArgumentOutOfRangeException("offset"); TorrentFileStream stream = GetStream(file, FileAccess.ReadWrite); stream.Seek(offset, SeekOrigin.Begin); stream.Write(buffer, bufferOffset, count); }
public void FixtureSetup() { pieceLength = Piece.BlockSize * 2; singleFile = new TorrentFile("path", Piece.BlockSize * 5); multiFile = new TorrentFile[] { new TorrentFile ("first", Piece.BlockSize - 550), new TorrentFile ("second", 100), new TorrentFile ("third", Piece.BlockSize) }; buffer = new byte[Piece.BlockSize]; torrentSize = Toolbox.Accumulate<TorrentFile>(multiFile, delegate(TorrentFile f) { return f.Length; }); }
public void FixtureSetup() { _pieceLength = Piece.BlockSize*2; _singleFile = new TorrentFile("path", Piece.BlockSize*5); _multiFile = new[] { new TorrentFile("first", Piece.BlockSize - 550), new TorrentFile("second", 100), new TorrentFile("third", Piece.BlockSize) }; _buffer = new byte[Piece.BlockSize]; _torrentSize = _multiFile.Sum(x => x.Length); }
public override void Flush(TorrentFile file) { for (int i = 0; i < cachedBlocks.Count; i++) { if (cachedBlocks[i].File == file) { CachedBlock b = cachedBlocks[i]; writer.Write(b.File, b.Offset, b.Buffer, 0, b.Count); ClientEngine.BufferManager.FreeBuffer(ref b.Buffer); } } cachedBlocks.RemoveAll(delegate(CachedBlock b) { return b.File == file; }); }
public override int Read(TorrentFile file, long offset, byte[] buffer, int bufferOffset, int count) { if (DoNotReadFrom.Contains(file)) return 0; if (!Paths.Contains(file.FullPath)) Paths.Add(file.FullPath); if (!DontWrite) for (int i = 0; i < count; i++) buffer[bufferOffset + i] = (byte)(bufferOffset + i); return count; }
public void Flush(TorrentFile file) { CachedBlocks.RemoveAll(delegate(CachedBlock b) { if (b.File != file) { return(false); } Interlocked.Add(ref cacheUsed, -b.Count); using (b.BufferReleaser) Writer.Write(b.File, b.Offset, b.Buffer, 0, b.Count); return(true); }); }
public void MoveFile(TorrentFile file, string path) { Check.File(file); Check.PathNotEmpty(path); CheckRegisteredAndDisposed(); CheckMetadata(); if (State != TorrentState.Stopped) { throw new TorrentException("Cannot move files when the torrent is active"); } Engine.DiskManager.MoveFile(this, file, path); }
public BufferedIO(object manager, ArraySegment<byte> buffer, int pieceIndex, int blockIndex, int count, int pieceLength, TorrentFile[] files, string path) { this.Path = path; this.files = files; this.pieceLength = pieceLength; Initialise(buffer, (long)pieceIndex*pieceLength + blockIndex*Piece.BlockSize, count); }
public override int Read(TorrentFile file, long offset, byte[] buffer, int bufferOffset, int count) { Check.File(file); Check.Buffer(buffer); if (offset < 0 || offset + count > file.Length) throw new ArgumentOutOfRangeException("offset"); Stream s = GetStream(file, FileAccess.Read); if (s.Length < offset + count) return 0; s.Seek(offset, SeekOrigin.Begin); return s.Read(buffer, bufferOffset, count); }
private void button1_Click(object sender, EventArgs e) { OpenFileDialog dialog = new OpenFileDialog(); dialog.Title = "Open Torrent File"; dialog.Filter = "Torrent files (*.torrent)|*.torrent"; if (dialog.ShowDialog() != DialogResult.OK) { return; } torrentName = dialog.FileName; torrentSize = 0; fileList.Clear(); listBoxInfo.Items.Clear(); textBox1.Text = torrentName; TorrentFile torrent = Bencode.DecodeTorrentFile(torrentName); add_info(torrent.Info["name"].ToString()); if (torrent.Info["source"] != null) { add_info(torrent.Info["source"].ToString()); } add_info(torrent.Comment); add_info(torrent.CreatedBy); add_info(torrent.CreationDate); fileNum = 0; BList files = (BList)torrent.Info["files"]; foreach (BDictionary file in files) { //add_info(file["length"].ToString()); BList path = (BList)file["path"]; string spath = ""; foreach (BString elem in path) { spath += "\\" + elem; } fileNum++; Int64 sz = Int64.Parse(file["length"].ToString()); torrentSize += sz; fileList.Add(spath, sz); } add_info(fileNum.ToString() + " file(s), " + FormatSize(torrentSize)); }
internal void MoveFile(TorrentManager manager, TorrentFile file, StorageFolder path) { IoLoop.QueueWait(delegate { try { Writer.Move(file, path, false); file.TargetFolder = path; } catch (Exception ex) { SetError(manager, Reason.WriteFailure, ex); } }); }
internal async Task MoveFileAsync(TorrentManager manager, TorrentFile file, string newPath) { await IOLoop; try { newPath = Path.GetFullPath(newPath); Writer.Move(file, newPath, false); file.FullPath = newPath; } catch (Exception ex) { await SetError(manager, Reason.WriteFailure, ex); } }
internal async Task <bool> CheckFileExistsAsync(TorrentManager manager, TorrentFile file) { await IOLoop; try { return(Writer.Exists(file)); } catch (Exception ex) { await SetError(manager, Reason.ReadFailure, ex); return(true); } }
public override int Read(TorrentFile file, long offset, byte[] buffer, int bufferOffset, int count) { Check.File(file); Check.Buffer(buffer); if (offset < 0L || offset + count > file.Length) throw new ArgumentOutOfRangeException(nameof(offset)); var s = GetStream(file, FileAccessMode.Read); if (s == null || s.Size < (ulong) offset + (ulong) count) return 0; s.Seek((ulong) offset); var buff = buffer.AsBuffer(bufferOffset, count); s.ReadAsync(buff, (uint) count, InputStreamOptions.Partial).AsTask().Wait(); return count; }
static void recalcForParent(TorrentFile item) { if (item.Children.Count == 0 && item.Parent != null) { var wee = item.Parent.Children.Where(x => x.Checked == true).ToList(); item.Parent.Size = wee.Sum(x => x.Size); } else { foreach (var itm in item.Children) { recalcForParent(itm.Children.First()); } } }
public override void Write(TorrentFile file, long offset, byte[] buffer, int bufferOffset, int count) { Check.File(file); Check.Buffer(buffer); if (offset < 0 || offset + count > file.Length) { throw new ArgumentOutOfRangeException("offset"); } TorrentFileStream stream = GetStream(file, FileAccess.ReadWrite); stream.Seek(offset, SeekOrigin.Begin); stream.Write(buffer, bufferOffset, count); }
internal void MoveFile(TorrentManager manager, TorrentFile file, string path) { IOLoop.QueueWait(delegate { try { path = Path.GetFullPath(path); writer.Move(file.FullPath, path, false); file.FullPath = path; } catch (Exception ex) { SetError(manager, Reason.WriteFailure, ex); } }); }
public async Task MoveFileAsync(TorrentManager manager, TorrentFile file, string path) { await IOLoop; try { path = Path.GetFullPath(path); Writer.Move(file.FullPath, path, false); file.FullPath = path; } catch (Exception ex) { SetError(manager, Reason.WriteFailure, ex); } }
public void Setup() { pieceLength = Piece.BlockSize * 2; singleFile = new TorrentFile("path", Piece.BlockSize * 5); multiFile = new TorrentFile[] { new TorrentFile("first", Piece.BlockSize - 550), new TorrentFile("second", 100), new TorrentFile("third", Piece.BlockSize) }; buffer = new byte[Piece.BlockSize]; torrentSize = Toolbox.Accumulate <TorrentFile>(multiFile, delegate(TorrentFile f) { return(f.Length); }); Initialise(buffer, 1); level2 = new MemoryWriter(new NullWriter(), Piece.BlockSize * 3); level1 = new MemoryWriter(level2, Piece.BlockSize * 3); }
private static string[] CreateTorrentRelocateCandidates(TorrentFile biggestFileInTorrent, IEnumerable <FileInfo> matchingFiles) { var torrentFileDepth = biggestFileInTorrent.FileLocationInTorrent.Split('/', '\\', StringSplitOptions.RemoveEmptyEntries).Length - 1; return(matchingFiles.Select(f => { var torrentPathCandidate = Path.GetDirectoryName(f.FullName) ?? throw new InvalidDataException(); for (int i = 0; i < torrentFileDepth; i++) { torrentPathCandidate = Directory.GetParent(torrentPathCandidate)?.FullName ?? throw new InvalidDataException(); } return torrentPathCandidate ?? throw new InvalidDataException(); }).ToArray()); }
/// <summary> /// Increments the downloads count. /// </summary> /// <param name="filepath">The filepath.</param> public void IncDownloadsCount(string filepath) { TorrentFile file = this.context.TorrentFiles .Where(tf => tf.Path == filepath) .Single(); User user = this.context.Users .Where(u => u.UserID == this.userID) .Single(); file.DownloadsCount = file.DownloadsCount + 1; user.DownloadsCount = user.DownloadsCount + 1; this.context.Entry(file).State = EntityState.Modified; this.context.Entry(user).State = EntityState.Modified; this.context.SaveChanges(); }
internal bool CheckFileExists(TorrentManager manager, TorrentFile file) { bool result = false; IOLoop.QueueWait(delegate { try { result = writer.Exists(file); } catch (Exception ex) { SetError(manager, Reason.ReadFailure, ex); } }); return(result); }
private void DisplayTorrentFileDetails(TorrentFile tor) { SetGUIProperty(GuiProperty.TorrentFile_Name, tor.FileName); SetGUIProperty(GuiProperty.TorrentFile_Size, tor.FileSizeFormatted); SetGUIProperty(GuiProperty.TorrentFile_Downloaded, tor.DownloadedFormatted); string pri = ""; switch ((TorrentFilePriority)tor.Priority) { case TorrentFilePriority.DontDownload: pri = Translation.DontDownload; break; case TorrentFilePriority.High: pri = Translation.High; break; case TorrentFilePriority.Low: pri = Translation.Low; break; case TorrentFilePriority.Medium: pri = Translation.Medium; break; } SetGUIProperty(GuiProperty.TorrentFile_Priority, pri); }
void FetchOriginalTorrent(IResourceInfo info) { var data = info.SiteData as SiteInfo; if (data == null || data.SiteDownloadLink.IsNullOrEmpty()) { return; } var torrent = NetworkClient.Create <byte[]>(HttpMethod.Get, data.SiteDownloadLink, ReferUrlPage).Send(); if (!torrent.IsValid()) { return; } try { //update hash var contentStream = new MemoryStream(torrent.Result); var tf = new TorrentFile(); try { tf.Load(contentStream, LoadFlag.ComputeMetaInfoHash); } catch (Exception) { return; } //总下载大小 var totalsize = tf.Files.Sum(s => s.Length); if (tf.Files.Count == 0) { totalsize = tf.MetaInfo.Length; } ((ResourceInfo)info).DownloadSizeValue = totalsize; ((ResourceInfo)info).Hash = tf.MetaInfoHashString; ((ResourceInfo)info).Data = torrent.Result; //report //AppContext.Instance.CloudService.ReportDownload(info.Hash, info.Title, GetDetailUrl(info), Info.Name, info.DownloadSize, torrent.Result); } catch (Exception) { } }
public override int Read(TorrentFile file, long offset, byte[] buffer, int bufferOffset, int count) { Check.File(file); Check.Buffer(buffer); for (var i = 0; i < cachedBlocks.Count; i++) { if (cachedBlocks[i].File != file) continue; if (cachedBlocks[i].Offset != offset || cachedBlocks[i].File != file || cachedBlocks[i].Count != count) continue; Buffer.BlockCopy(cachedBlocks[i].Buffer, 0, buffer, bufferOffset, count); return count; } return writer.Read(file, offset, buffer, bufferOffset, count); }
internal TorrentFileStream GetStream(TorrentFile file, FileAccess access) { TorrentFileStream s = FindStream(file.FullPath); if (s != null) { // If we are requesting write access and the current stream does not have it if (((access & FileAccess.Write) == FileAccess.Write) && !s.CanWrite) { Logger.Log(null, "Didn't have write permission - reopening"); CloseAndRemove(s); s = null; } else { // Place the filestream at the end so we know it's been recently used list.Remove(s); list.Add(s); } } if (s == null) { if (!File.Exists(file.FullPath)) { Directory.CreateDirectory(Path.GetDirectoryName(file.FullPath)); NtfsSparseFile.CreateSparse(file.FullPath, file.Length); } s = new TorrentFileStream(file, FileMode.OpenOrCreate, access, FileShare.ReadWrite); // Ensure that we truncate existing files which are too large if (s.Length > file.Length) { if (!s.CanWrite) { s.Close(); s = new TorrentFileStream(file, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite); } s.SetLength(file.Length); } Add(s); } return(s); }
private void btnParseTorrent_Click(object sender, EventArgs e) { string btFile = AppDomain.CurrentDomain.BaseDirectory + "b.torrent"; TorrentFile torrent = new TorrentFile(btFile); MessageBox.Show(torrent.TorrentName); //string[] torrentList = VTS.Common.VTSCommon.GetDirFile(@"G:\T\04-BT", "*.torrent", true); //int i = 1; //foreach (var item in torrentList) //{ // TorrentFile torrent = new TorrentFile(item); // this.txtCode.AppendText(i + ":" + torrent.TorrentName + Environment.NewLine); // i++; //} }
public MemoryWriterTests() { pieceLength = Piece.BlockSize*2; singleFile = new TorrentFile("path", Piece.BlockSize*5); multiFile = new[] { new TorrentFile("first", Piece.BlockSize - 550), new TorrentFile("second", 100), new TorrentFile("third", Piece.BlockSize) }; buffer = new byte[Piece.BlockSize]; torrentSize = Toolbox.Accumulate(multiFile, delegate(TorrentFile f) { return f.Length; }); Initialise(buffer, 1); level2 = new MemoryWriter(new NullWriter(), Piece.BlockSize*3); level1 = new MemoryWriter(level2, Piece.BlockSize*3); }
private Task <IRandomAccessStream> OpenStreamAsync(TorrentFile file, FileAccessMode access, AsynTokens asynTokens) { return(Task.Run(async() => { var token = asynTokens.CancellationTokenSource.Token; var fullPath = file.FullPath; var storageFile = await StorageHelper.CreateFileAsync(fullPath, file.TargetFolder); if (access == FileAccessMode.ReadWrite) { var stream = File.Open(storageFile.Path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); var randomAccessStream = stream.AsRandomAccessStream(); try { var size = (long)randomAccessStream.Size; var length = file.Length - size; if (length > 0L) { var buffer = ClientEngine.BufferManager.GetBuffer((int)Math.Min(length, 524288L)); try { randomAccessStream.Seek((ulong)size); for (var i = size; i < file.Length; i = i + (long)buffer.Length) { length = length - await randomAccessStream.WriteAsync( buffer.AsBuffer(0, (int)Math.Min(length, buffer.Length))); token.ThrowIfCancellationRequested(); } } finally { ClientEngine.BufferManager.FreeBuffer(ref buffer); } } } finally { randomAccessStream?.Dispose(); } } return await storageFile.OpenAsync(access); })); }
/// <summary> /// 执行下载 /// </summary> /// <param name="torrent"></param> /// <returns></returns> public byte[] Download(IResourceInfo torrent) { if (torrent.Provider == null || torrent.Provider.GetType() != typeof(TorLockSearchProvider)) { return(null); } if (torrent.Data != null) { return(torrent.Data as byte[]); } ((ResourceInfo)torrent).Hash = null; var data = (SiteInfo)torrent.SiteData; var url = $"https://www.torlock.com/tor/{data.SiteID}.torrent"; var torData = DownloadCore(url, ReferUrlPage); if (data != null) { //update hash var contentStream = new MemoryStream(torData); var tf = new TorrentFile(); try { tf.Load(contentStream, LoadFlag.ComputeMetaInfoHash); } catch (Exception) { return(null); } //总下载大小 var totalsize = tf.Files.Sum(s => s.Length); if (tf.Files.Count == 0) { totalsize = tf.MetaInfo.Length; } ((ResourceInfo)torrent).DownloadSizeValue = totalsize; ((ResourceInfo)torrent).Hash = tf.MetaInfoHashString; } return(torData); }
public async Task UsePartialFiles_InitiallyOn_ToggleOff() { var pieceLength = Constants.BlockSize * 4; var engine = new ClientEngine(EngineSettingsBuilder.CreateForTests(usePartialFiles: true)); var torrent = TestRig.CreateMultiFileTorrent(TorrentFile.Create(pieceLength, Constants.BlockSize, Constants.BlockSize * 2, Constants.BlockSize * 3), pieceLength, out BEncoding.BEncodedDictionary _); var manager = await engine.AddAsync(torrent, ""); Assert.AreNotEqual(manager.Files[0].DownloadCompleteFullPath, manager.Files[0].DownloadIncompleteFullPath); var settings = new EngineSettingsBuilder(engine.Settings) { UsePartialFiles = false }.ToSettings(); await engine.UpdateSettingsAsync(settings); Assert.AreEqual(manager.Files[0].DownloadCompleteFullPath, manager.Files[0].DownloadIncompleteFullPath); }
public async Task MoveFileAsync(TorrentFile file, string path) { Check.File(file); Check.PathNotEmpty(path); CheckRegisteredAndDisposed(); CheckMetadata(); if (State != TorrentState.Stopped) { throw new TorrentException("Cannot move files when the torrent is active"); } try { await Engine.DiskManager.MoveFileAsync(file, path); } catch (Exception ex) { TrySetError(Reason.WriteFailure, ex); } }
public int Read (TorrentFile file, long offset, byte[] buffer, int bufferOffset, int count) { Check.File (file); Check.Buffer (buffer); for (int i = 0; i < CachedBlocks.Count; i++) { if (CachedBlocks[i].File != file) continue; if (CachedBlocks[i].Offset != offset || CachedBlocks[i].File != file || CachedBlocks[i].Count != count) continue; Buffer.BlockCopy (CachedBlocks[i].Buffer, 0, buffer, bufferOffset, count); Interlocked.Add (ref cacheHits, count); return count; } Interlocked.Add (ref cacheMisses, count); return Writer.Read (file, offset, buffer, bufferOffset, count); }
internal TorrentFileStream GetStream(TorrentFile file, FileAccess access) { var fileStream = FindStream(file.FullPath); if (fileStream != null) { // If we are requesting write access and the current stream does not have it if (((access & FileAccess.Write) == FileAccess.Write) && !fileStream.CanWrite) { Logger.Log (null, "Didn't have write permission - reopening"); CloseAndRemove(fileStream); fileStream = null; } else { // Place the filestream at the end so we know it's been recently used _list.Remove(fileStream); _list.Add(fileStream); } } if (fileStream == null) { if (File.Exists(file.FullPath) == false) { Directory.CreateDirectory(Path.GetDirectoryName(file.FullPath)); SparseFile.CreateSparse(file.FullPath, file.Length); } fileStream = new TorrentFileStream (file, FileMode.OpenOrCreate, access, FileShare.Read); // Ensure that we truncate existing files which are too large if (fileStream.Length > file.Length) { if (!fileStream.CanWrite) { fileStream.Close(); fileStream = new TorrentFileStream(file, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read); } fileStream.SetLength(file.Length); } Add(fileStream); } return fileStream; }
private bool IsGoodFile(TorrentFile file) { var sizeInGigabytes = file.Length / 1_000_000_000.0; var extension = Path.GetExtension(file.Path); if (sizeInGigabytes > MinSizeGb && sizeInGigabytes < MaxSizeGb && (string.IsNullOrWhiteSpace(Extension) || string.Equals(extension, Extension, StringComparison.OrdinalIgnoreCase))) { //Print($"Size: {sizeGb:F2} Gb"); //Print($"Path: {path}"); //Print($"Extension: {extension}"); return(true); } return(false); }
public override int Read(TorrentFile file, long offset, byte[] buffer, int bufferOffset, int count) { Check.File(file); Check.Buffer(buffer); if (offset < 0 || offset + count > file.Length) { throw new ArgumentOutOfRangeException("offset"); } Stream s = GetStream(file, FileAccess.Read); if (s.Length < offset + count) { return(0); } s.Seek(offset, SeekOrigin.Begin); return(s.Read(buffer, bufferOffset, count)); }
private void RecurseToggle(TreeIter iter, bool value) { do { if (store.IterHasChild(iter)) { TreeIter child; store.IterChildren(out child, iter); RecurseToggle(child, value); } store.SetValue(iter, 1, value); TorrentFile file = (TorrentFile)store.GetValue(iter, 2); if (file != null) { file.Priority = value ? Priority.Normal : Priority.DoNotDownload; } } while (store.IterNext(ref iter)); }
private void btnCheckTorrent_Click(object sender, EventArgs e) { //假设一个BT种子没有下载完成 会怎样呢? TorrentFile torr = new TorrentFile(@"E:\T\BT包\019\吉泽明步.torrent"); IList <TorrentFileInfo> ls = torr.TorrentFileInfo; List <string> lsP = new List <string>(); foreach (var item in ls) { if (!lsP.Contains(item.Path)) { lsP.Add(item.Path); } } foreach (var item in lsP) { this.txtCode.AppendText(item + "\r\n"); } }
public int Read(TorrentFile file, long offset, byte [] buffer, int bufferOffset, int count) { ReadData.Add(Tuple.Create(file, offset, count)); if (Data == null) { var fileData = WrittenData .Where(t => t.Item1 == file) .OrderBy(t => t.Item2) .SelectMany(t => t.Item3) .ToArray(); Buffer.BlockCopy(fileData, (int)offset, buffer, bufferOffset, count); } else { var data = Data[file]; Buffer.BlockCopy(data, (int)offset, buffer, bufferOffset, count); } return(count); }
public void CreateSingleTest() { foreach (var v in _announces) { _creator.Announces.Add(v); } var torrentFile = new TorrentFile(Path.GetFileName(_files[0].Path), _files[0].Length, _files[0].StartPieceIndex, _files[0].EndPieceIndex); var dict = _creator.Create(torrentFile.Path, new List <TorrentFile>(new[] { torrentFile })); var torrent = Torrent.Load(dict); VerifyCommonParts(torrent); Assert.AreEqual(1, torrent.Files.Length, "#1"); Assert.AreEqual(torrentFile, torrent.Files[0], "#2"); }
public static void TestRead(string db, string file, string length, string offset, string count, string realfile) { logger.DebugFormat("DB file path: {0}", db); var dbs = new ChunkDbService(db, false); var ds = new DeduplicationService(dbs); var writer = new DedupDiskWriter(ds); var c = int.Parse(count); var buffer = new byte[c]; var f = new TorrentFile(file, long.Parse(length)); var o = long.Parse(offset); int actualRead = writer.Read(f, o, buffer, 0, c); byte[] bufferToCompare = new byte[c]; using (var rf = File.OpenRead(realfile)) { rf.Seek(o, SeekOrigin.Begin); rf.Read(bufferToCompare, 0, bufferToCompare.Length); } Assert.IsTrue(buffer.SequenceEqual(bufferToCompare)); }
public override void Move(TorrentFile file, StorageFolder newRoot, bool ignoreExisting) { Check.File(file); Check.SaveFolder(newRoot); if (file.TargetFolder == newRoot) return; try { Flush(file); _streamsBuffer.Move(file, newRoot, ignoreExisting); } catch (Exception ex) { if (!(ex.InnerException is FileNotFoundException)) { if (ex.InnerException.HResult != -2147467259) throw; } } file.TargetFolder = newRoot; }
public void Write(TorrentFile file, long offset, byte[] buffer, int bufferOffset, int count, bool forceWrite) { if (forceWrite) { writer.Write(file, offset, buffer, bufferOffset, count); } else { if (Used > Capacity - count) Flush(0); var cacheBuffer = BufferManager.EmptyBuffer; ClientEngine.BufferManager.GetBuffer(ref cacheBuffer, count); Buffer.BlockCopy(buffer, bufferOffset, cacheBuffer, 0, count); var block = new CachedBlock(); block.Buffer = cacheBuffer; block.Count = count; block.Offset = offset; block.File = file; cachedBlocks.Add(block); } }
internal void SetTorrentFilePriority(TorrentFile FileToUpdate, int Priority) { ServiceClient.SetFilePriority( FileToUpdate.ParentCollection.ParentTorrent.Hash, FileToUpdate.Index, Priority, _token); UpdateTorrentFiles(FileToUpdate.ParentCollection.ParentTorrent, true); }
long GetPieceCount(TorrentFile[] files) { long size = 0; foreach (var file in files) size += file.Length; //double count = (double)size/PieceLength; var pieceCount = size/PieceLength + (((size%PieceLength) != 0) ? 1 : 0); Logger.Log(null, "Piece Count: {0}", pieceCount); return pieceCount; }
///<summary> ///this method is used for multi file mode torrents to return a dictionary with ///file relevant informations. ///<param name="file">the file to report the informations for</param> ///<param name="basePath">used to subtract the absolut path information</param> ///</summary> BEncodedDictionary GetFileInfoDict(TorrentFile file) { var fileDict = new BEncodedDictionary(); fileDict.Add("length", new BEncodedNumber(file.Length)); var filePath = new BEncodedList(); var splittetPath = file.Path.Split(System.IO.Path.DirectorySeparatorChar); foreach (var s in splittetPath) { if (s.Length > 0) //exclude empties filePath.Add(new BEncodedString(s)); } fileDict.Add("path", filePath); return fileDict; }
///<summary> ///used for creating a single file torrent file ///<summary> ///<returns>the dictionary representing which is stored in the torrent file</returns> protected void CreateSingleFileTorrent(BEncodedDictionary dictionary, TorrentFile[] files, PieceWriter writer, string name) { AddCommonStuff(dictionary); var infoDict = (BEncodedDictionary)dictionary["info"]; infoDict.Add("length", new BEncodedNumber(files[0].Length)); infoDict.Add("name", (BEncodedString)name); if (StoreMD5) AddMD5(infoDict, Path); Logger.Log(null, "name == {0}", name); var path = System.IO.Path.GetDirectoryName(Path); infoDict.Add("pieces", new BEncodedString(CalcPiecesHash(path, files, writer))); }