public void CreateSingleFromFolder() { System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly(); BEncodedDictionary dict = creator.Create(new TorrentFileSource(assembly.Location)); Torrent t = Torrent.Load(dict); Assert.AreEqual(1, t.Files.Count, "#1"); Assert.AreEqual(Path.GetFileName(assembly.Location), t.Name, "#2"); Assert.AreEqual(Path.GetFileName(assembly.Location), t.Files[0].Path, "#3"); // Create it again creator.Create(new TorrentFileSource(assembly.Location)); }
/// <summary> /// Tests creating torrent. /// </summary> /// <remarks>MonoTorrent TorrentCreator needs file to be available (even /// though it could be empty) even if dedup writer is used.</remarks> public static void TestCreateTorrent(string db, string dataFile, string savePath, string savePath1) { var dedupWriter = new DedupDiskWriter(new DeduplicationService(new ChunkDbService(db, false))); var creator = new DedupTorrentCreator(dedupWriter); var ip = NetUtil.GetLocalIPByInterface("Local Area Connection"); var tier = new RawTrackerTier { string.Format("http://{0}:25456/announce", ip.ToString()), "udp://tracker.publicbt.com:80/announce", "udp://tracker.openbittorrent.com:80/announce" }; var filename = Path.GetFileName(dataFile); creator.GetrightHttpSeeds.Add(string.Format( "http://{0}:49645/FileServer/FileRange/{1}", ip.ToString(), filename)); creator.Announces.Add(tier); var binaryTorrent = creator.Create(new TorrentFileSource(dataFile)); var torrent = Torrent.Load(binaryTorrent); string infoHash = torrent.InfoHash.ToHex(); File.WriteAllBytes(savePath, binaryTorrent.Encode()); // Now read from the real file. var creator1 = new TorrentCreator(); creator1.Announces.Add(tier); creator1.GetrightHttpSeeds.Add(string.Format( "http://{0}:49645/FileServer/FileRange/{1}", ip.ToString(), filename)); var binary1 = creator1.Create(new TorrentFileSource(dataFile)); string infoHash1 = Torrent.Load(binary1).InfoHash.ToHex(); File.WriteAllBytes(savePath1, binary1.Encode()); Assert.AreEqual(infoHash, infoHash1); logger.DebugFormat("InfoHash: {0}", infoHash); }
static void CreateTorrent(string path, string torrentFile, string torrentName) { Log("Creating the Torrent for {0}", torrentName); //Create the torrent with a command line application (monotorrent???) TorrentCreator tc = new TorrentCreator(); tc.Announces.Add(_torrentTrackers); //Add Trackers to Torrent //Add Comments :) tc.CreatedBy = "Sab2Torrent"; tc.Publisher = "http://code.google.com/p/sabscripts/"; tc.Path = path; //Add the path (folder) to Hash and add to the torrent //Print the Progress to the command line (mostly for debugging) tc.Hashed += delegate (object obj, TorrentCreatorEventArgs e) { Console.WriteLine("Overall {0:f}% hashed", e.OverallCompletion); }; if (_torrentPrivate) //If Config says torrent should be private, make it so! tc.Private = true; tc.Create(torrentFile); //Create the Torrent File Log("Torrent file created: {0}", torrentFile); }
private const int PieceLength = 16384;//64 * 1024; public ITorrent CreateTorrent(string downloadFolder, string relativeFileSourcePath, string destinationFolder) { var creator = new MonoTorrent.Common.TorrentCreator(); var config = Catalog.Factory.Resolve <IConfig>(); creator.Announces.Clear(); // Add one tier which contains a tracker var tier = new RawTrackerTier { string.Format( "http://{0}:{1}/announce", config[BitTorrentSettings.TrackerHost], config[BitTorrentSettings.TrackerPort]) }; creator.Announces.Add(tier); creator.Announce = string.Format( "http://{0}:{1}/announce", config[BitTorrentSettings.TrackerHost], config[BitTorrentSettings.TrackerPort]); creator.CreatedBy = "Monotorrent Client/" + VersionInfo.ClientVersion; creator.Comment = downloadFolder; creator.Publisher = relativeFileSourcePath; creator.PieceLength = PieceLength; creator.PublisherUrl = string.Empty; //not allowing dht, peer exchange creator.Private = true; creator.Hashed += (o, e) => Console.WriteLine("{0} {1}", e.FileSize, e.CurrentFile.First()); var fullSourcePath = Path.Combine(downloadFolder, relativeFileSourcePath); var fileSource = new TorrentFileSource(fullSourcePath); //var randomName = Path.GetTempFileName(); var destFile = Path.Combine(destinationFolder, Path.GetFileNameWithoutExtension(fullSourcePath) + ".torrent"); creator.Create(fileSource, destFile); var torrentFile = new TorrentFile(destFile, relativeFileSourcePath); return(torrentFile); }
private static Torrent CreateTorrentFromFile(string path) { try { var creator = new TorrentCreator(); creator.Path = path; var ms = new MemoryStream(); creator.Create(ms); ms.Seek(0, SeekOrigin.Begin); return Torrent.Load(ms); } catch (Exception ex) { Trace.TraceWarning("Error creating torrent from file {0}", path); return null; } }
/// <summary> /// Create torrent with progress /// </summary> /// <param name="workerMy"></param> public void CreateTorrent(BackgroundWorker workerMy) { string p = this.MediaLocation; if (this.TrackerGroupActive != null) { if (File.Exists(p) || Directory.Exists(p)) { foreach (Tracker myTracker in this.TrackerGroupActive.Trackers) { MonoTorrent.Common.TorrentCreator tc = new MonoTorrent.Common.TorrentCreator(); tc.CreatedBy = Application.ProductName; tc.Private = true; tc.Comment = MediaHelper.GetMediaName(p); tc.Path = p; tc.PublisherUrl = "https://github.com/McoreD/TDMaker"; tc.Publisher = Application.ProductName; tc.StoreMD5 = false; // delays torrent creation List <string> temp = new List <string>(); temp.Add(myTracker.AnnounceURL); tc.Announces.Add(temp); string torrentFileName = string.Format("{0} - {1}.torrent", (File.Exists(p) ? Path.GetFileName(p) : MediaHelper.GetMediaName(p)), myTracker.Name); this.SetTorrentFilePath(torrentFileName); ReportProgress(workerMy, ProgressType.UPDATE_STATUSBAR_DEBUG, string.Format("Creating {0}", this.TorrentFilePath)); tc.Hashed += delegate(object o, TorrentCreatorEventArgs e) { ReportProgress(workerMy, ProgressType.UPDATE_PROGRESSBAR_CUMULATIVE, e.OverallCompletion); }; HelpersLib.Helpers.CreateDirectoryIfNotExist(this.TorrentFilePath); tc.Create(this.TorrentFilePath); ReportProgress(workerMy, ProgressType.UPDATE_STATUSBAR_DEBUG, string.Format("Created {0}", this.TorrentFilePath)); } } } else { Console.WriteLine("There were no active trackers configured to create a torrent."); } }
public void CreateMultiTest() { foreach (var v in announces) { creator.Announces.Add(v); } BEncodedDictionary dict = creator.Create("TorrentName", files); Torrent torrent = Torrent.Load(dict); VerifyCommonParts(torrent); for (int i = 0; i < torrent.Files.Length; i++) { Assert.IsTrue(files.Exists(delegate(TorrentFile f) { return(f.Equals(torrent.Files[i])); })); } }
public void UpdateMission(ZkDataContext db, Mission mission, Mod modInfo) { var file = mission.Mutator.ToArray(); var tempName = Path.GetTempFileName() + ".zip"; File.WriteAllBytes(tempName, file); using (var zf = new ZipFile(tempName)) { zf.UpdateEntry("modinfo.lua", Encoding.UTF8.GetBytes(GetModInfo(mission.NameWithVersion, mission.Mod, mission.Name, "ZK"))); // FIXME hardcoded crap FixScript(mission, zf, "script.txt"); var script = FixScript(mission, zf, GlobalConst.MissionScriptFileName); modInfo.MissionScript = script; //modInfo.ShortName = mission.Name; modInfo.Name = mission.NameWithVersion; zf.Save(); } mission.Mutator = File.ReadAllBytes(tempName); mission.Script = Regex.Replace(mission.Script, "GameType=([^;]+);", (m) => { return string.Format("GameType={0};", mission.NameWithVersion); }); File.Delete(tempName); var resource = db.Resources.FirstOrDefault(x => x.MissionID == mission.MissionID); if (resource == null) { resource = new Resource() { DownloadCount = 0, TypeID = ZkData.ResourceType.Mod }; db.Resources.Add(resource); } resource.InternalName = mission.NameWithVersion; resource.MissionID = mission.MissionID; resource.ResourceDependencies.Clear(); resource.ResourceDependencies.Add(new ResourceDependency() { NeedsInternalName = mission.Map }); resource.ResourceDependencies.Add(new ResourceDependency() { NeedsInternalName = mission.Mod }); resource.ResourceContentFiles.Clear(); // generate torrent var tempFile = Path.Combine(Path.GetTempPath(), mission.SanitizedFileName); File.WriteAllBytes(tempFile, mission.Mutator.ToArray()); var creator = new TorrentCreator(); creator.Path = tempFile; var torrentStream = new MemoryStream(); creator.Create(torrentStream); try { File.Delete(tempFile); } catch { } var md5 = Hash.HashBytes(mission.Mutator.ToArray()).ToString(); resource.ResourceContentFiles.Add(new ResourceContentFile() { FileName = mission.SanitizedFileName, Length = mission.Mutator.Length, LinkCount = 1, Links = string.Format(MissionFileUrl, mission.MissionID), Md5 = md5 }); var basePath = GlobalConst.SiteDiskPath + @"\resources\"; File.WriteAllBytes(string.Format(@"{2}\{0}_{1}.torrent", resource.InternalName.EscapePath(), md5, basePath), torrentStream.ToArray()); File.WriteAllBytes(string.Format(@"{1}\{0}.metadata.xml.gz", resource.InternalName.EscapePath(), basePath), MetaDataCache.SerializeAndCompressMetaData(modInfo)); File.WriteAllBytes(string.Format(GlobalConst.SiteDiskPath + @"\img\missions\{0}.png", mission.MissionID, basePath), mission.Image.ToArray()); }
/// <summary> /// Creates torrent from the file specified by the given path. /// </summary> /// <param name="path">The path to the file/directory.</param> /// <param name="trackerUrl">The tracker URL.</param> /// <returns>The torrent</returns> public BEncodedDictionary CreateTorrent(string dataPath) { TorrentCreator creator = new TorrentCreator(); creator.Comment = "This torrent file is automatically created."; creator.CreatedBy = "GatorShare"; creator.Announces.Add(new RawTrackerTier { TrackerUrlPrefix }); return creator.Create(new TorrentFileSource(dataPath)); }
void PerformUnitSyncOperation(WorkItem workItem) { Trace.TraceInformation("PerformUnitSyncOperation"); VerifyUnitSync(); if (unitSync == null) { Trace.TraceError("Skipping file after unitsync loading errors: {0}", workItem.CacheItem.ShortPath); CacheMarkFailedUnitSync(workItem.CacheItem.ShortPath); return; } var info = GetUnitSyncData(workItem.CacheItem.FileName); UnInitUnitsync(); if (info != null) { workItem.CacheItem.InternalName = info.Name; workItem.CacheItem.ResourceType = info.ResourceType; CacheItemAdd(workItem.CacheItem); var args = new CancelEventArgs<ResourceInfo>(info); UploadUnitsyncData.Invoke(this,args); if (args.Cancel) return; var serializedData = MetaDataCache.SerializeAndCompressMetaData(info); var map = info as Map; object userState = null; try { var creator = new TorrentCreator(); creator.Path = GetFullPath(workItem); var ms = new MemoryStream(); creator.Create(ms); byte[] minimap = null; byte[] metalMap = null; byte[] heightMap = null; if (map != null) { minimap = map.Minimap.ToBytes(ImageSize); metalMap = map.Metalmap.ToBytes(ImageSize); heightMap = map.Heightmap.ToBytes(ImageSize); userState = new MapRegisteredEventArgs(info.Name, map, minimap, metalMap, heightMap, serializedData); } var mod = info as Mod; if (mod != null) userState = new KeyValuePair<Mod, byte[]>(mod, serializedData); Trace.TraceInformation("uploading {0} to server", info.Name); Task.Factory.StartNew(() => { ReturnValue e; try { e = service.RegisterResource(PlasmaServiceVersion, springPaths.SpringVersion, workItem.CacheItem.Md5.ToString(), workItem.CacheItem.Length, info.ResourceType, workItem.CacheItem.FileName, info.Name, serializedData, info.Dependencies, minimap, metalMap, heightMap, ms.ToArray()); } catch (Exception ex) { Trace.TraceError("Error uploading data to server: {0}", ex); return; } finally { Interlocked.Decrement(ref itemsSending); } if (e != ReturnValue.Ok) { Trace.TraceWarning("Resource registering failed: {0}", e); return; } var mapArgs = userState as MapRegisteredEventArgs; if (mapArgs != null) { var mapName = mapArgs.MapName; MetaData.SaveMinimap(mapName, mapArgs.Minimap); MetaData.SaveMetalmap(mapName, mapArgs.MetalMap); MetaData.SaveHeightmap(mapName, mapArgs.HeightMap); MetaData.SaveMetadata(mapName, mapArgs.SerializedData); MapRegistered(this, mapArgs); } else if (userState != null) { var kvp = (KeyValuePair<Mod, byte[]>)userState; var modInfo = kvp.Key; var serializedDataRet = kvp.Value; MetaData.SaveMetadata(modInfo.Name, serializedDataRet); ModRegistered(this, new EventArgs<Mod>(mod)); } }); Interlocked.Increment(ref itemsSending); } catch (Exception e) { Trace.TraceError("Error registering new resource {0}: {1}", workItem.CacheItem.ShortPath, e); } } else { Trace.TraceError("Could not unitsync file {0}", workItem.CacheItem.ShortPath); CacheMarkFailedUnitSync(workItem.CacheItem.ShortPath); } return; }
/// <summary> /// Create torrent with progress /// </summary> /// <param name="workerMy"></param> public void CreateTorrent(BackgroundWorker workerMy) { string p = this.MediaLocation; if (this.Profile != null && this.Profile.Trackers != null && (File.Exists(p) || Directory.Exists(p))) { foreach (string tracker in this.Profile.Trackers) { MonoTorrent.Common.TorrentCreator tc = new MonoTorrent.Common.TorrentCreator(); tc.CreatedBy = Application.ProductName; tc.Private = true; tc.Comment = MediaHelper.GetMediaName(p); tc.Path = p; tc.PublisherUrl = "https://github.com/McoreD/TDMaker"; tc.Publisher = Application.ProductName; tc.StoreMD5 = false; // delays torrent creation List<string> temp = new List<string>(); temp.Add(tracker); tc.Announces.Add(temp); var uri = new Uri(tracker); string torrentFileName = string.Format("{0}.torrent", (File.Exists(p) ? Path.GetFileNameWithoutExtension(p) : MediaHelper.GetMediaName(p))); TorrentFilePath = Path.Combine(Path.Combine(TorrentFolder, uri.Host), torrentFileName); ReportProgress(workerMy, ProgressType.UPDATE_STATUSBAR_DEBUG, string.Format("Creating {0}", this.TorrentFilePath)); tc.Hashed += delegate(object o, TorrentCreatorEventArgs e) { ReportProgress(workerMy, ProgressType.UPDATE_PROGRESSBAR_Cumulative, e.OverallCompletion); }; Helpers.CreateDirectoryIfNotExist(this.TorrentFilePath); tc.Create(this.TorrentFilePath); ReportProgress(workerMy, ProgressType.UPDATE_STATUSBAR_DEBUG, string.Format("Created {0}", this.TorrentFilePath)); } } else { DebugHelper.WriteLine("There were no active trackers configured to create a torrent."); } }
public void UpdateMission(ZkDataContext db, Mission mission, Mod modInfo) { var file = mission.Mutator.ToArray(); var tempName = Path.GetTempFileName() + ".zip"; File.WriteAllBytes(tempName, file); using (var zf = ZipFile.Open(tempName, ZipArchiveMode.Update)) { var modinfoEntry = zf.GetEntry("modinfo.lua"); modinfoEntry.Delete(); modinfoEntry = zf.CreateEntry("modinfo.lua"); WriteZipArchiveEntry(modinfoEntry, GetModInfo(mission.NameWithVersion, mission.ModRapidTag, mission.Name, "ZK")); FixScript(mission, zf, "script.txt"); var script = FixScript(mission, zf, GlobalConst.MissionScriptFileName); modInfo.MissionScript = script; //modInfo.ShortName = mission.Name; modInfo.Name = mission.NameWithVersion; } mission.Mutator = File.ReadAllBytes(tempName); if (string.IsNullOrEmpty(mission.Script)) mission.Script = " "; // tweak for silly update validation mission.Script = Regex.Replace(mission.Script, "GameType=([^;]+);", (m) => $"GameType={mission.NameWithVersion};"); File.Delete(tempName); var resource = db.Resources.FirstOrDefault(x => x.MissionID == mission.MissionID); if (resource == null) { resource = new Resource() { DownloadCount = 0, TypeID = ZkData.ResourceType.Mod }; db.Resources.Add(resource); } resource.InternalName = mission.NameWithVersion; resource.MissionID = mission.MissionID; resource.ResourceDependencies.Clear(); resource.ResourceDependencies.Add(new ResourceDependency() { NeedsInternalName = mission.Map }); resource.ResourceDependencies.Add(new ResourceDependency() { NeedsInternalName = mission.Mod }); resource.ResourceContentFiles.Clear(); // generate torrent var tempFile = Path.Combine(Path.GetTempPath(), mission.SanitizedFileName); File.WriteAllBytes(tempFile, mission.Mutator.ToArray()); var creator = new TorrentCreator(); creator.Path = tempFile; var torrentStream = new MemoryStream(); creator.Create(torrentStream); try { File.Delete(tempFile); } catch { } var md5 = Hash.HashBytes(mission.Mutator.ToArray()).ToString(); resource.ResourceContentFiles.Add(new ResourceContentFile() { FileName = mission.SanitizedFileName, Length = mission.Mutator.Length, LinkCount = 1, Links = string.Format(MissionFileUrl, mission.MissionID), Md5 = md5 }); var basePath = GlobalConst.SiteDiskPath + @"\resources\"; if (!Directory.Exists(basePath)) Directory.CreateDirectory(basePath); File.WriteAllBytes(string.Format(@"{2}\{0}_{1}.torrent", resource.InternalName.EscapePath(), md5, basePath), torrentStream.ToArray()); File.WriteAllBytes(string.Format(@"{1}\{0}.metadata.xml.gz", resource.InternalName.EscapePath(), basePath), MetaDataCache.SerializeAndCompressMetaData(modInfo)); var imgPath = GlobalConst.SiteDiskPath + @"\img\missions\"; if (!Directory.Exists(imgPath)) Directory.CreateDirectory(imgPath); File.WriteAllBytes(string.Format(imgPath + "{0}.png", mission.MissionID, basePath), mission.Image.ToArray()); }
private static void Register(UnitSync unitsync, ResourceInfo resource) { Trace.TraceInformation("UnitSyncer: registering {0}", resource.Name); try { var info = unitsync.GetResourceFromFileName(resource.ArchivePath); if (info != null) { var serializedData = MetaDataCache.SerializeAndCompressMetaData(info); var map = info as Map; var creator = new TorrentCreator(); creator.Path = resource.ArchivePath; var ms = new MemoryStream(); creator.Create(ms); byte[] minimap = null; byte[] metalMap = null; byte[] heightMap = null; if (map != null) { minimap = map.Minimap.ToBytes(ImageSize); metalMap = map.Metalmap.ToBytes(ImageSize); heightMap = map.Heightmap.ToBytes(ImageSize); } var hash = Hash.HashBytes(File.ReadAllBytes(resource.ArchivePath)); var length = new FileInfo(resource.ArchivePath).Length; Trace.TraceInformation("UnitSyncer: uploading {0} to server", info.Name); ReturnValue e; try { var service = GlobalConst.GetContentService(); e = service.RegisterResource(PlasmaServiceVersion, null, hash.ToString(), (int)length, info.ResourceType, resource.ArchiveName, info.Name, serializedData, info.Dependencies, minimap, metalMap, heightMap, ms.ToArray()); } catch (Exception ex) { Trace.TraceError("UnitSyncer: Error uploading data to server: {0}", ex); return; } if (e != ReturnValue.Ok) Trace.TraceWarning("UnitSyncer: Resource registering failed: {0}", e); } } catch (Exception ex) { Trace.TraceError("Error registering resource {0} : {1}", resource.ArchivePath, ex); } }
public Stream Create(string name, string sourceDirectoryPath, IEnumerable<string> trackers = null) { // Check sourceDirectoryPath is a directory. if (!Directory.Exists (sourceDirectoryPath)) throw new InvalidSourceDirectoryException ("Was not found or is not a directory."); // Create torrent file mappings. var fileMappings = new TorrentFileSource (sourceDirectoryPath, true).Files.Select (fm => { var info = new FileInfo (fm.Source); return new TorrentFile (fm.Destination, info.Length, fm.Source); }).ToList(); // Make creator. var creator = new TorrentCreator (); creator.PieceLength = TorrentCreator.RecommendedPieceSize (fileMappings); if (trackers != null) creator.Announces.Add (new RawTrackerTier(trackers)); // Make torrent, convert to stream and return. var torrentStream = new MemoryStream (); var torrentRAW = creator.Create (name, fileMappings).Encode (); torrentStream.Write(torrentRAW, 0, torrentRAW.Length); return torrentStream; }
/// <summary> /// Create a new torrent /// </summary> public void Create() { CreateWindow window = new CreateWindow(this); if (window.ShowDialog() == DialogResult.OK) { TorrentCreator creator = new TorrentCreator(); creator.Comment = window.Comment; creator.CreatedBy = window.CreateBy; creator.Path = window.FromPath; if (!String.IsNullOrEmpty(window.TrackerURL)) { creator.Announces.Add(new List<string>()); creator.Announces[0].Add(window.TrackerURL); } string newPath = Path.Combine(window.SaveTo, Path.GetFileName(window.FromPath)); creator.Create(newPath); } }