コード例 #1
0
        public void Setup()
        {
            HashAlgoFactory.Register <SHA1, SHA1Fake>();

            creator   = new TestTorrentCreator();
            announces = new RawTrackerTiers();
            announces.Add(new RawTrackerTier(new string[] { "http://tier1.com/announce1", "http://tier1.com/announce2" }));
            announces.Add(new RawTrackerTier(new string[] { "http://tier2.com/announce1", "http://tier2.com/announce2" }));

            creator.Comment      = Comment;
            creator.CreatedBy    = CreatedBy;
            creator.PieceLength  = PieceLength;
            creator.Publisher    = Publisher;
            creator.PublisherUrl = PublisherUrl;
            creator.SetCustom(CustomKey, CustomValue);
            files = new List <TorrentFile>(new TorrentFile[] {
                new TorrentFile(Path.Combine(Path.Combine("Dir1", "SDir1"), "File1"), (int)(PieceLength * 2.30), 0, 1),
                new TorrentFile(Path.Combine(Path.Combine("Dir1", "SDir1"), "File2"), (int)(PieceLength * 36.5), 1, 3),
                new TorrentFile(Path.Combine(Path.Combine("Dir1", "SDir2"), "File3"), (int)(PieceLength * 3.17), 3, 12),
                new TorrentFile(Path.Combine(Path.Combine("Dir2", "SDir1"), "File4"), (int)(PieceLength * 1.22), 12, 15),
                new TorrentFile(Path.Combine(Path.Combine("Dir2", "SDir2"), "File5"), (int)(PieceLength * 6.94), 15, 15),
            });

            writer           = new TestWriter();
            writer.DontWrite = true;
        }
コード例 #2
0
        /// <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);
        }
コード例 #3
0
ファイル: Program.cs プロジェクト: thefkboss/sabscripts
        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);
        }
コード例 #4
0
        public void Setup()
        {
            creator = new TestTorrentCreator();
            announces = new List<List<string>>();

            announces.Add(new List<string>(new string[] { "http://tier1.com/announce1", "http://tier1.com/announce2" }));
            announces.Add(new List<string>(new string[] { "http://tier2.com/announce1", "http://tier2.com/announce2" }));

            creator.Comment = Comment;
            creator.CreatedBy = CreatedBy;
            creator.PieceLength = PieceLength;
            creator.Publisher = Publisher;
            creator.PublisherUrl = PublisherUrl;
            creator.AddCustom(CustomKey, CustomValue);
            files = new List<TorrentFile>(new TorrentFile[] { 
                new TorrentFile(Path.Combine(Path.Combine("Dir1", "SDir1"), "File1"), (int)(PieceLength * 2.30), 0, 1),
                new TorrentFile(Path.Combine(Path.Combine("Dir1", "SDir1"), "File2"), (int)(PieceLength * 36.5), 1, 3),
                new TorrentFile(Path.Combine(Path.Combine("Dir1", "SDir2"), "File3"), (int)(PieceLength * 3.17), 3, 12),
                new TorrentFile(Path.Combine(Path.Combine("Dir2", "SDir1"), "File4"), (int)(PieceLength * 1.22), 12, 15),
                new TorrentFile(Path.Combine(Path.Combine("Dir2", "SDir2"), "File5"), (int)(PieceLength * 6.94), 15, 15),
            });

            writer = new TestWriter();
            writer.DontWrite = true;
        }
コード例 #5
0
ファイル: PublishedSeed.cs プロジェクト: flq/Bin4Net
 public PublishedSeed(string torrentName, string pathToContent)
 {
     torrent = new TorrentCreator();
     //torrent.Announces.Add(new List<string> { "http://tracker.openbittorrent.com/announce" });
     Torrent.CreatedBy = "Bin4Net";
     this.torrentName = torrentName;
     this.pathToContent = pathToContent;
 }
コード例 #6
0
        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);
        }
コード例 #7
0
 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;
     }
 }
コード例 #8
0
        /// <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.");
            }
        }
コード例 #9
0
ファイル: TorrentCreator.cs プロジェクト: viwhi1/TDMaker
        /// <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.");
            }
        }
コード例 #10
0
        public void Setup()
        {
            creator   = new TorrentCreator(TestFactories);
            announces = new List <List <string> > {
                new List <string> (new[] { "http://tier1.com/announce1", "http://tier1.com/announce2" }),
                new List <string> (new[] { "http://tier2.com/announce1", "http://tier2.com/announce2" })
            };

            creator.Comment      = Comment;
            creator.CreatedBy    = CreatedBy;
            creator.PieceLength  = PieceLength;
            creator.Publisher    = Publisher;
            creator.PublisherUrl = PublisherUrl;
            creator.SetCustom(CustomKey, CustomValue);
            files = new List <TorrentCreator.InputFile> {
                new TorrentCreator.InputFile(Path.Combine("Dir1", "SDir1", "File1"), (long)(PieceLength * 2.30)),
                new TorrentCreator.InputFile(Path.Combine("Dir1", "SDir1", "File2"), (long)(PieceLength * 36.5)),
                new TorrentCreator.InputFile(Path.Combine("Dir1", "SDir2", "File3"), (long)(PieceLength * 3.17)),
                new TorrentCreator.InputFile(Path.Combine("Dir2", "SDir1", "File4"), (long)(PieceLength * 1.22)),
                new TorrentCreator.InputFile(Path.Combine("Dir2", "SDir2", "File5"), (long)(PieceLength * 6.94)),
            };
        }
コード例 #11
0
ファイル: TorrentHelper.cs プロジェクト: xujyan/hurricane
 /// <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));
 }
コード例 #12
0
        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;
        }
コード例 #13
0
ファイル: Form1.cs プロジェクト: leontodd/BatchTorrent
 private TorrentCreator InitTorrentCreator()
 {
     TorrentCreator tc = new TorrentCreator();
     tc.Hashed += delegate (object o, TorrentCreatorEventArgs ee)
     {
         ShowProgress(ee.FileCompletion, ee.OverallCompletion, ee.OverallSize);
     };
     foreach (string s in this.textBox2.Lines)
     {
         tc.Announces.Add(new RawTrackerTier(new string[] { s }));
     }
     tc.Comment = textBox3.Text;
     if (((KeyValuePair<string, long>)comboBox1.SelectedItem).Value != -1)
     {
         tc.PieceLength = ((KeyValuePair<string, long>)comboBox1.SelectedItem).Value;
     }
     tc.Private = checkBox1.Checked;
     tc.CreatedBy = "";
     return tc;
 }
コード例 #14
0
 private void createButtonClicked(object sender, RoutedEventArgs e)
 {
     var sourcePath = pathTextBox.Text;
     if (string.IsNullOrEmpty(sourcePath))
     {
         MessageBox.Show("Please select a file or files to add.");
         return;
     }
     if (singleFileRadioButton.IsChecked.Value)
     {
         if (!File.Exists(sourcePath))
         {
             MessageBox.Show("The selected file does not exist!");
             return;
         }
     }
     if (entireFolderRadioButton.IsChecked.Value)
     {
         if (!Directory.Exists(sourcePath))
         {
             MessageBox.Show("The selected folder does not exist!");
             return;
         }
     }
     Creator = new TorrentCreator();
     var source = new TorrentFileSource(sourcePath, ignoreHiddenFilesCheckBox.IsChecked.Value);
     var tier = new RawTrackerTier(trackerListBox.Items.Cast<string>());
     Creator.Announces.Add(tier);
     Creator.Comment = commentTextBox.Text;
     Creator.Private = privateTorrentCheckBox.IsChecked.Value;
     Creator.CreatedBy = "Patchy BitTorrent Client";
     Creator.PieceLength = TorrentCreator.RecommendedPieceSize(source.Files);
     var dialog = new SaveFileDialog();
     dialog.Filter = "Torrent Files (*.torrent)|*.torrent|All Files (*.*)|*.*";
     dialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
     FilePath = sourcePath;
     if (dialog.ShowDialog().Value)
     {
         // Create the torrent
         Path = dialog.FileName;
         if (!Path.EndsWith(".torrent"))
             Path += ".torrent";
         pathGrid.IsEnabled = trackerGrid.IsEnabled = optionsGrid.IsEnabled = createButton.IsEnabled = false;
         Creator.Hashed += Creator_Hashed;
         Creator.BeginCreate(source, CreationComplete, null);
     }
 }
コード例 #15
0
        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);
            }
        }
コード例 #16
0
ファイル: MonoTorrentClient.cs プロジェクト: kl4w/BTDeploy
        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;
        }
コード例 #17
0
        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());

        }
コード例 #18
0
		private void createTorrent()
		{
			creator = new TorrentCreator();
			
			progressDialog = new CreateTorrentProgressDialog();
			
			// TODO: Read the multi-tracker spec -- learn the proper way to add multiple trackers
			creator.Announces.Add(new MonoTorrentCollection<string>());
            		foreach(string s in GetTrackers())
            			creator.Announces[0].Add(s);
            		
			creator.Comment = Comment;
			creator.CreatedBy = "MonoTorrent";
			
			creator.Path = SavePath;

			creator.Hashed += OnHashed;
			
			TorrentCreatorAsyncResult creatorResult = creator.BeginCreate(null, BeginCreateCb);
			
			ResponseType cancelResult = (ResponseType) progressDialog.Run();
			if(cancelResult == ResponseType.Cancel){
				creatorResult.Abort();
				try{
					creator.EndCreate(creatorResult);
					progressDialog.Destroy();
				} catch (Exception e) {
					logger.ErrorException("Unable to end creation" + e.Message, e);
				}
			}
		}
コード例 #19
0
        private void createTorrent()
        {
            creator = new TorrentCreator();

            progressDialog = new CreateTorrentProgressDialog();

            // TODO: Read the multi-tracker spec -- learn the proper way to add multiple trackers
            creator.Announces.Add(new RawTrackerTier ());
            foreach(string s in GetTrackers())
                creator.Announces[0].Add(s);

            creator.Comment = Comment;
            creator.CreatedBy = Defines.ApplicationName;

            creator.Hashed += delegate(object o, TorrentCreatorEventArgs e) {
                GLib.Idle.Add(delegate {
                    OnHashed(o, e);
                    return false;
                });
            };

            var result = creator.BeginCreate(new TorrentFileSource (SavePath), delegate (IAsyncResult r) {
                GLib.Idle.Add (delegate {
                    BeginCreateCb (r);
                    return false;
                });
            }, null);

            ResponseType cancelResult = (ResponseType) progressDialog.Run();
            if(cancelResult == ResponseType.Cancel){
                creator.AbortCreation ();
                try{
                    creator.EndCreate(result);
                    progressDialog.Destroy();
                } catch (Exception e) {
                    logger.ErrorException("Unable to end creation" + e.Message, e);
                }
            }
        }
コード例 #20
0
        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());
        }
コード例 #21
0
        public void AutoSelectPieceLength()
        {
            var torrentCreator = new TorrentCreator(TestFactories);

            Assert.DoesNotThrowAsync(() => torrentCreator.CreateAsync("name", files, CancellationToken.None));
        }
コード例 #22
0
 /// <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);
     }
 }