Exemplo n.º 1
0
        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);
        }
        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);
                }
            }
        }
Exemplo n.º 3
0
        //-------------------------------------------------------------
        public void HashedDelegate(object o, TorrentCreatorEventArgs torrentEvent)
        //-------------------------------------------------------------
        {
            Log.Get().Write("Current File is " + torrentEvent.FileCompletion * 100 + "% hashed");
            Log.Get().Write("Overall " + torrentEvent.OverallCompletion * 100 + "% hashed");
            Log.Get().Write("Total data to hash: " + torrentEvent.OverallSize);

            if (kobberLan != null)
            {
                kobberLan.Invoke(new Action(() =>
                {
                    TorrentCreator c = (TorrentCreator)o;
                    if (String.IsNullOrEmpty(c.Comment))
                    {
                        return;
                    }

                    bool status = kobberLan.UpdateProgressBar(TorrentState.Metadata, (int)(torrentEvent.OverallCompletion * 100.0), c.Comment);
                    if (status == false)
                    {
                        c.Hashed -= HashedDelegate;
                        c.Comment = "";
                        Log.Get().Write("Hashed failed", Log.LogType.Error);
                    }
                }));
            }
        }
        public static void Main()
        {
            var io             = new Io();
            var torrentCreator = new TorrentCreator();

            var app = new App(io, torrentCreator);

            app.Run();
        }
Exemplo n.º 5
0
        public static Torrent GetTorrentFromFile(string PathToFile)
        {
            TorrentCreator TC = new TorrentCreator();

            TC.Private = false;
            ITorrentFileSource filePath = new TorrentFileSource(PathToFile);
            BEncodedDictionary bed      = TC.Create(filePath);

            return(Torrent.Load(bed));
        }
Exemplo n.º 6
0
        public static byte[] GetBytesFromFile(string PathToFile)
        {
            TorrentCreator TC = new TorrentCreator();

            TC.Private = false;
            ITorrentFileSource filePath = new TorrentFileSource(PathToFile);
            BEncodedDictionary bed      = TC.Create(filePath);

            return(bed.Encode());
        }
Exemplo n.º 7
0
        /// <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)));
        }
Exemplo n.º 8
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);
            }
        }
Exemplo n.º 9
0
        public void Save(TorrentInfo info)
        {
            var torrentsPath = _environment.GetApplicationDataPath().Combine("Torrents");

            using (var creator = new TorrentCreator(info))
            {
                var data     = creator.Generate();
                var filePath = torrentsPath.CombineWithFilePath(string.Format("{0}.torrent", info.InfoHash));
                var file     = _fileSystem.GetFile(filePath);

                using (var fileStream = file.Open(FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    fileStream.Write(data, 0, data.Length);
                }
            }
        }
Exemplo n.º 10
0
        public void Save(TorrentInfo info)
        {
            var torrentsPath = _environment.GetApplicationDataPath().Combine("Torrents");

            using (var creator = new TorrentCreator(info))
            {
                var data = creator.Generate();
                var filePath = torrentsPath.CombineWithFilePath(string.Format("{0}.torrent", info.InfoHash));
                var file = _fileSystem.GetFile(filePath);

                using (var fileStream = file.Open(FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    fileStream.Write(data, 0, data.Length);
                }
            }
        }
Exemplo n.º 11
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);
     }
 }
Exemplo n.º 12
0
        public async ValueTask CreateTorrentAsync(string torrentFileLocation, NewTorrentFile torrentFile)
        {
            var tc = new TorrentCreator
            {
                CreatedBy = "TorrentGrease",
                Private   = torrentFile.IsPrivate
            };

            foreach (var announceUrl in torrentFile.TrackerAnnounceUrls)
            {
                tc.Announces.Add(new RawTrackerTier(new BEncodedList(new BEncodedValue[]
                {
                    new BEncodedString(announceUrl)
                })));
            }

            await tc.CreateAsync(new CustomTorrentFileSource(torrentFile.Name, torrentFile.FileMappings), torrentFileLocation);
        }
Exemplo n.º 13
0
        private void Hash(TaskCompletionSource <bool> task)
        {
            var file = (LocalFile)task.Task.AsyncState;

            this.loggingService.LogDebug("trying to hash " + file.FullPath);

            StartedHashingFile?.Invoke(this, new FilenameEventArgs(file.FullPath));

            try
            {
                /* Create the torrent */
                TorrentCreator creator = new TorrentCreator();
                // Have to put something bogus here, otherwise MonoTorrent crashes!
                creator.Announces.Add(new MonoTorrentCollection <string>());
                creator.Announces[0].Add(String.Empty);

                creator.Path = file.LocalPath;
                Torrent torrent = Torrent.Load(creator.Create());

                /* Update the database */
                string[] pieces = new string[torrent.Pieces.Count];
                for (int x = 0; x < torrent.Pieces.Count; x++)
                {
                    byte[] hash = torrent.Pieces.ReadHash(x);
                    pieces[x] = Common.BytesToString(hash);
                }

                file.Update(Common.BytesToString(torrent.InfoHash.ToArray()),
                            Common.BytesToString(torrent.Files[0].SHA1),
                            torrent.PieceLength, pieces);

                FinishedHashingFile?.Invoke(this, new FilenameEventArgs(file.FullPath));

                task.TrySetResult(true);
            }
            catch (OperationCanceledException)
            {
                task.TrySetCanceled();
            }
            catch (Exception e)
            {
                task.TrySetException(e);
            }
        }
Exemplo n.º 14
0
        public void CreateTorrent()
        {
            string p = Info.TaskSettings.Media.Location;

            if (Info.TaskSettings.Profile != null && Info.TaskSettings.Profile.Trackers != null && (File.Exists(p) || Directory.Exists(p)))
            {
                foreach (string tracker in Info.TaskSettings.Profile.Trackers)
                {
                    TorrentCreator tc = new 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)));
                    Info.TaskSettings.TorrentFilePath = Path.Combine(Path.Combine(Info.TaskSettings.TorrentFolder, uri.Host), torrentFileName);

                    ReportProgress(string.Format("Creating {0}", Info.TaskSettings.TorrentFilePath));

                    tc.Hashed += delegate(object o, TorrentCreatorEventArgs e)
                    {
                        Info.TorrentProgress = e.OverallCompletion;
                        OnTorrentProgressChanged();
                    };

                    Helpers.CreateDirectoryFromFilePath(Info.TaskSettings.TorrentFilePath);
                    tc.Create(Info.TaskSettings.TorrentFilePath);
                    ReportProgress(string.Format("Created {0}", Info.TaskSettings.TorrentFilePath));
                    Success = true;
                }
            }
            else
            {
                DebugHelper.WriteLine("There were no active trackers configured to create a torrent.");
            }
        }
Exemplo n.º 15
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);
                }
            }
        }
Exemplo n.º 16
0
        private void Hash(ShareHasherTask task)
        {
            if (StartedHashingFile != null)
            {
                StartedHashingFile(task);
            }

            /* Create the torrent */
            var creator = new TorrentCreator();

            // Have to put something bogus here, otherwise MonoTorrent crashes!
            creator.Announces.Add(new MonoTorrentCollection <string>());
            creator.Announces[0].Add(string.Empty);

            //creator.Path = task.File.LocalPath;
            //Torrent torrent = Torrent.Load(creator.Create());
            Torrent torrent = null;              // FIXME

            /* Update the database */
            var pieces = new string[torrent.Pieces.Count];

            for (var x = 0; x < torrent.Pieces.Count; x++)
            {
                var hash = torrent.Pieces.ReadHash(x);
                pieces[x] = Common.Utils.BytesToString(hash);
            }

            task.File.Update(Common.Utils.BytesToString(torrent.InfoHash.ToArray()),
                             Common.Utils.BytesToString(torrent.Files[0].SHA1),
                             torrent.PieceLength, pieces);

            if (FinishedHashingFile != null)
            {
                FinishedHashingFile(task);
            }

            if (task.Callback != null)
            {
                task.Callback(null);
            }
        }
Exemplo n.º 17
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);
        }
Exemplo n.º 18
0
        public void Setup()
        {
            _creator   = new TestTorrentCreator();
            _announces = new RawTrackerTiers
            {
                new RawTrackerTier(new[]
                {
                    "http://tier1.com/announce1",
                    "http://tier1.com/announce2"
                }),
                new RawTrackerTier(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 <TorrentFile>(new[] {
                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)
            });

            new TestWriter {
                DontWrite = true
            };
        }
Exemplo n.º 19
0
        public async Task RunAsync()
        {
            //LoggerFactory.Creator = className => new TextLogger (Console.Out, className);

            var seederWriter = new MemoryWriter(new NullWriter(), DataSize);
            int port         = 37827;
            var seeder       = new ClientEngine(
                new EngineSettingsBuilder {
                AllowedEncryption = new[] { EncryptionType.PlainText },
                ListenPort        = port++
            }.ToSettings(),
                seederWriter
                );

            var downloaders = Enumerable.Range(port, 16).Select(p => {
                return(new ClientEngine(
                           new EngineSettingsBuilder {
                    ListenPort = p, AllowedEncryption = new[] { EncryptionType.PlainText }
                }.ToSettings(),
                           new MemoryWriter(new NullWriter(), DataSize)
                           ));
            }).ToArray();

            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);
                    await seederWriter.WriteAsync(seeder.Torrents[0].Files[0], offset, dataRead, 0, read);
                }
            }

            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);
            }
        }
Exemplo n.º 20
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 is Map ? ResourceType.Map : ResourceType.Mod;

                CacheItemAdd(workItem.CacheItem);

                var args = new CancelEventArgs <IResourceInfo>(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 is Map ? ResourceType.Map : ResourceType.Mod, workItem.CacheItem.FileName, info.Name,
                                                         serializedData, mod != null ? mod.Dependencies.ToList() : null, 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
                        {
                            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;
        }
Exemplo n.º 21
0
        //-------------------------------------------------------------
        public async Task <byte[]> CreateTorrent(string path, string title)
        //-------------------------------------------------------------
        {
            byte[] result      = null;
            string pathTorrent = path + "\\_kobberlan.torrent";

            //-------------------------------------------------------------
            //Check if torrent file exist
            //-------------------------------------------------------------
            if (File.Exists(pathTorrent))
            {
                Log.Get().Write("Load torrent from path: " + pathTorrent);
                try
                {
                    int fileLength = (int)new System.IO.FileInfo(pathTorrent).Length;
                    result = new byte[fileLength];
                    FileStream fileStream = File.Open(pathTorrent, FileMode.Open);
                    fileStream.Read(result, 0, fileLength);
                    fileStream.Close();
                }
                catch (Exception ex)
                {
                    Log.Get().Write("Failed to load torrent file: " + ex, Log.LogType.Error);
                }
            }
            else
            {
                //-------------------------------------------------------------
                //Create new torrent file
                //-------------------------------------------------------------
                Log.Get().Write("Creating torrent file for path: " + path);

                TorrentCreator c = new TorrentCreator();
                c.CreatedBy = "Lan";
                c.Publisher = "Lan";
                c.Comment   = title;
                c.Private   = true; //Do not share the torrent with other tracker. (Disable DHT or peer exchange)

                //-------------------------------------------------------------
                // Every time a piece has been hashed, this event will fire.
                //-------------------------------------------------------------
                c.Hashed += HashedDelegate;

                //-------------------------------------------------------------
                //Path to directory
                //-------------------------------------------------------------
                ITorrentFileSource fileSource = new TorrentFileSource(path);

                //-------------------------------------------------------------
                //Create torrent
                //-------------------------------------------------------------
                BEncodedDictionary dict = await c.CreateAsync(fileSource);

                result = dict.Encode();
                Log.Get().Write("Creating torrent file in memory. Size: " + result.Length);

                //-------------------------------------------------------------
                //Save torrent to HDD (To increase loadtime next time)
                //-------------------------------------------------------------
                string createTorrentFile = ConfigurationManager.AppSettings.Get("Torrent:CreateTorrentFiles");
                if (Convert.ToBoolean(createTorrentFile))
                {
                    Log.Get().Write("Saving torrent file to path: " + pathTorrent);
                    try
                    {
                        FileStream fileStream = File.Create(pathTorrent);
                        fileStream.Write(result, 0, result.Length);
                        fileStream.Close();
                    }
                    catch (Exception ex)
                    {
                        Log.Get().Write("Failed to save torrent file: " + ex, Log.LogType.Error);
                    }
                }
            }

            return(result);
        }
Exemplo n.º 22
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);

            //upon completion of any work: dispose unitsync. It can be re-initialize again later by VerifyUnitSync()
            if (unitSync != null && GetWorkCost() < 1)
            {
                try
                {
                    unitSync.Dispose();
                    unitSync = null;
                }
                catch (Exception ex)
                {
                    Trace.TraceWarning("Error disposing unitsync: {0}", ex);
                }
            }
            if (info != null)
            {
                workItem.CacheItem.InternalName = info.Name;
                workItem.CacheItem.ResourceType = info is Map ? ResourceType.Map : ResourceType.Mod;
                var hashes = new List <SpringHashEntry>();
                if (workItem.CacheItem.SpringHash != null)
                {
                    hashes.AddRange(workItem.CacheItem.SpringHash.Where(x => x.SpringVersion != springPaths.SpringVersion));
                }
                hashes.Add(new SpringHashEntry()
                {
                    SpringHash = info.Checksum, SpringVersion = springPaths.SpringVersion
                });
                workItem.CacheItem.SpringHash = hashes.ToArray();

                CacheItemAdd(workItem.CacheItem);

                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);
                    service.RegisterResourceAsync(PlasmaServiceVersion,
                                                  springPaths.SpringVersion,
                                                  workItem.CacheItem.Md5.ToString(),
                                                  workItem.CacheItem.Length,
                                                  info is Map ? ResourceType.Map : ResourceType.Mod,
                                                  workItem.CacheItem.FileName,
                                                  info.Name,
                                                  info.Checksum,
                                                  serializedData,
                                                  mod != null ? mod.Dependencies : null,
                                                  minimap,
                                                  metalMap,
                                                  heightMap,
                                                  ms.ToArray(),
                                                  userState);
                    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;
        }
Exemplo n.º 23
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, mission.Mod, "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());
        }
Exemplo n.º 24
0
        private static ResourceInfo Register(UnitSync unitsync, ResourceInfo resource)
        {
            Trace.TraceInformation("UnitSyncer: registering {0}", resource.Name);
            ResourceInfo info = null;

            try
            {
                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(null);
                    }

                    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);
                return(null);
            }

            return(info);
        }
Exemplo n.º 25
0
        /// <summary>
        /// 初始化
        /// </summary>
        protected override void BeginProcessing()
        {
            currentLocation = CurrentProviderLocation("").ProviderPath;

            //验证文件是否为存在
            if (Directory.Exists(FilePath))
            {
                isDirectory = true;
            }
            else if (File.Exists(FilePath))
            {
                isDirectory = false;
            }
            else if (Directory.Exists(currentLocation + "\\" + FilePath))
            {
                isDirectory = true;
                FilePath    = currentLocation + "\\" + FilePath;
            }
            else if (File.Exists(currentLocation + "\\" + FilePath))
            {
                isDirectory = false;
                FilePath    = currentLocation + "\\" + FilePath;
            }
            else
            {
                WriteError(new ErrorRecord(new DirectoryNotFoundException(), "", ErrorCategory.ObjectNotFound, FilePath));
                return;
            }

            //分块长度为空或0时计算长度
            if (PieceLength == null || PieceLength <= 0)
            {
                if (isDirectory)
                {
                    torrentCreator.PieceLength = TorrentCreator.RecommendedPieceSize(Directory.GetFiles(FilePath, "*", SearchOption.AllDirectories));
                }
                else
                {
                    torrentCreator.PieceLength = TorrentCreator.RecommendedPieceSize(new string[] { FilePath });
                }
            }
            else
            {
                torrentCreator.PieceLength = (long)PieceLength;
            }

            //元数据添加
            torrentCreator.Private = Private;
            if (Comment != null)
            {
                torrentCreator.Comment = Comment;
            }
            torrentCreator.CreatedBy = CreatedBy;
            if (Source != null)
            {
                torrentCreator.SetCustomSecure("source", new BEncodedString(Source));
            }
            if (WebSeedLinks != null)
            {
                foreach (var link in WebSeedLinks)
                {
                    torrentCreator.GetrightHttpSeeds.Add(link);
                }
            }
            if (AnnounceUrls != null)
            {
                torrentCreator.Announce = AnnounceUrls[0];
                if (AnnounceUrls.Length > 1)
                {
                    torrentCreator.Announces.Add(new MonoTorrent.RawTrackerTier(AnnounceUrls));
                }
            }

            //保存路径修正
            if (SavePath == null)
            {
                if (isDirectory)
                {
                    SavePath = Directory.GetParent(FilePath).FullName + "\\" + new DirectoryInfo(FilePath).Name + ".torrent";
                }
                else
                {
                    SavePath = new FileInfo(FilePath).Directory.FullName + "\\" + new FileInfo(FilePath).Name + ".torrent";
                }
            }
            else if (!Path.IsPathRooted(SavePath))
            {
                if (isDirectory)
                {
                    SavePath = Directory.GetParent(FilePath).FullName + "\\" + SavePath;
                }
                else
                {
                    SavePath = new FileInfo(FilePath).Directory.FullName + "\\" + SavePath;
                }
            }
        }
Exemplo n.º 26
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 = new Binary(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.InsertOnSubmit(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 sh = resource.ResourceSpringHashes.SingleOrDefault(x => x.SpringVersion == mission.SpringVersion);

            if (sh == null)
            {
                sh = new ResourceSpringHash();
                resource.ResourceSpringHashes.Add(sh);
            }
            sh.SpringVersion = mission.SpringVersion;
            sh.SpringHash    = 0;


            var basePath = ConfigurationManager.AppSettings["ResourcePath"] ?? @"c:\projekty\zero-k.info\www\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(@"c:\projekty\zero-k.info\www\img\missions\{0}.png", mission.MissionID, basePath), mission.Image.ToArray());
        }
Exemplo n.º 27
0
 public App(Io io, TorrentCreator torrentCreator)
 {
     this.io             = io;
     this.torrentCreator = torrentCreator;
 }