Пример #1
0
 //-------------------------------------------------------------
 public void DownloadTorrent(byte[] torrentData)
 //-------------------------------------------------------------
 {
     Log.Get().Write("Client downloading files from torrent with size: " + torrentData.Length);
     MonoTorrent.Torrent torrent = MonoTorrent.Torrent.Load(torrentData);
     DownloadTorrent(torrent);
 }
Пример #2
0
        //-------------------------------------------------------------
        public byte[] InsertAnnounce(byte[] torrentData)
        //-------------------------------------------------------------
        {
            MonoTorrent.Torrent torrent = MonoTorrent.Torrent.Load(torrentData);
            torrent.AnnounceUrls.Clear();
            torrent.AnnounceUrls.Add(new RawTrackerTier(new[] { "http://" + Helper.GetHostIP().ToString() + ":" + TRACKERHTTP_PORT + "/announce", "udp://" + Helper.GetHostIP().ToString() + ":" + TRACKERUDP_PORT }));

            byte[]        result        = null;
            TorrentEditor torrentEditor = new TorrentEditor(torrent);

            torrentEditor.Announces.Clear();
            torrentEditor.Announces.Add(new RawTrackerTier(new[] { "http://" + Helper.GetHostIP().ToString() + ":" + TRACKERHTTP_PORT + "/announce", "udp://" + Helper.GetHostIP().ToString() + ":" + TRACKERUDP_PORT }));
            var dict = torrentEditor.ToDictionary();

            result = dict.Encode();

            return(result);
        }
Пример #3
0
        //-------------------------------------------------------------
        public void DownloadTorrent(MonoTorrent.Torrent torrent)
        //-------------------------------------------------------------
        {
            if (torrent == null)
            {
                Log.Get().Write("torrent is null", Log.LogType.Error);
            }

            if (torrent.AnnounceUrls.Count <= 0)
            {
                Log.Get().Write("torrent missing announce", Log.LogType.Error);
            }

            string path = Helper.GetDirection();

            Log.Get().Write("Client downloading files torrent: " + torrent.Name);

            if (!Helper.IsPortAvailable(CLIENT_PORT))
            {
                Log.Get().Write("Failed starting client downloading file on port: " + CLIENT_PORT + " Port in use", Log.LogType.Error);
            }

            if (settings == null || engine == null)
            {
                //Settings
                settings = new EngineSettings();
                settings.AllowedEncryption = EncryptionTypes.All;
                settings.PreferEncryption  = true;
                settings.SavePath          = path;
                settings.ListenPort        = CLIENT_PORT;

                //Create client engine
                engine = new ClientEngine(settings);
            }

            //Check if torrent exist (reStarting a torrent)
            var torrentManagersResult = torrentManagers.Where(t => t.Torrent.Name.Equals(torrent.Name)).ToList();

            if (torrentManagersResult.Count >= 1)
            {
                Log.Get().Write("ReStarting torrent: " + torrent.Name);
                torrentManagersResult.FirstOrDefault().StartAsync();
            }
            else //New torrent
            {
                Log.Get().Write("Preparing new torrent: " + torrent.Name);
                var torrentSettings = new TorrentSettings();
                torrentSettings.AllowDht          = false;
                torrentSettings.AllowPeerExchange = true;
                TorrentManager torrentManager = new TorrentManager(torrent, path, torrentSettings);

                //Add logning
                torrentManager.ConnectionAttemptFailed += delegate(object o, ConnectionAttemptFailedEventArgs e) { Log.Get().Write("TorrentManager connectionAttemptFailed reason:" + e.Reason.ToString(), Log.LogType.Error); };
                torrentManager.PeerConnected           += delegate(object o, PeerConnectedEventArgs e) { Log.Get().Write("TorrentManager PeerConnected"); };
                torrentManager.PeerDisconnected        += delegate(object o, PeerDisconnectedEventArgs e) { Log.Get().Write("TorrentManager PeerDisconnected"); };
                torrentManager.PeersFound  += delegate(object o, PeersAddedEventArgs e) { Log.Get().Write("TorrentManager PeersAdded"); };
                torrentManager.PieceHashed += pieceHashedDelegate;

                torrentManager.TorrentStateChanged += delegate(object o, TorrentStateChangedEventArgs e)
                {
                    Log.Get().Write("TorrentManager TorrentStateChanged, oldstate: " + e.OldState + " , newState: " + e.NewState);
                    if (kobberLan != null)
                    {
                        kobberLan.Invoke(new Action(() =>
                        {
                            bool status = kobberLan.UpdateProgressBar(e.NewState, (int)(torrentManager.Progress), torrentManager.Torrent.Name);
                            if (status == false)
                            {
                                torrentManager.StopAsync();

                                if (e.NewState != MonoTorrent.Client.TorrentState.Stopped && e.NewState != MonoTorrent.Client.TorrentState.Stopping)
                                {
                                    Log.Get().Write("TorrentHandler failed", Log.LogType.Error);
                                }
                            }
                        }));
                    }
                };

                engine.CriticalException += delegate(object o, CriticalExceptionEventArgs e) { Log.Get().Write("TorrentEngine CriticalException", Log.LogType.Error); };
                engine.StatsUpdate       += delegate(object o, StatsUpdateEventArgs e)
                {
                    if (o.GetType() == typeof(MonoTorrent.Client.ClientEngine))
                    {
                        ClientEngine clientEngine = (ClientEngine)o;

                        Log.Get().Write("TorrentEngine Statsupdate running: " + clientEngine.IsRunning +
                                        " , torrent Seeds: " + torrentManager.Peers.Seeds + ", Leech: " + torrentManager.Peers.Leechs +
                                        " , progress: " + torrentManager.Progress
                                        );

                        if (kobberLan != null && kobberLan.Disposing == false)
                        {
                            kobberLan.Invoke(new Action(() =>
                            {
                                bool status = kobberLan.UpdateProgressBar(torrentManager.State, (int)(torrentManager.Progress), torrentManager.Torrent.Name);
                                if (status == false)
                                {
                                    torrentManager.StopAsync();

                                    if (torrentManager.State != MonoTorrent.Client.TorrentState.Stopped && torrentManager.State != MonoTorrent.Client.TorrentState.Stopping)
                                    {
                                        Log.Get().Write("TorrentHandler failed", Log.LogType.Error);
                                    }
                                }
                            }));
                        }
                    }
                    else
                    {
                        Log.Get().Write("TorrentEngine Statsupdate: Unknown", Log.LogType.Error);
                    }
                };

                //Start downloading
                engine.Register(torrentManager);
                engine.StartAllAsync();

                //Add torrent to list
                torrentManagers.Add(torrentManager);
            }
        }
Пример #4
0
 //-------------------------------------------------------------
 public string GetTorrentName(byte[] torrentData)
 //-------------------------------------------------------------
 {
     MonoTorrent.Torrent torrent = MonoTorrent.Torrent.Load(torrentData);
     return(torrent.Name);
 }
Пример #5
0
        //-------------------------------------------------------------
        public void StartTracker(byte[] torrentData)
        //-------------------------------------------------------------
        {
            Log.Get().Write("Starting torrent tracker server, http on port: " + TRACKERHTTP_PORT + " udp on port: " + TRACKERUDP_PORT);
            if (!Helper.IsPortAvailable(TRACKERHTTP_PORT))
            {
                Log.Get().Write("Failed starting torrent tracker server on http port: " + TRACKERHTTP_PORT + " Port in use", Log.LogType.Error);
            }
            if (!Helper.IsPortAvailable(TRACKERUDP_PORT))
            {
                Log.Get().Write("Failed starting torrent tracker server on UDP port: " + TRACKERUDP_PORT + " Port in use", Log.LogType.Error);
            }

            //-------------------------------------------------------------
            //Create tracker server
            //-------------------------------------------------------------
            if (trackerServer == null)
            {
                trackerServer = new TrackerServer();
                listenerHttp  = TrackerListenerFactory.CreateHttp(IPAddress.Any, TRACKERHTTP_PORT); // http://localhost:{TRACKER_PORT}/announce
                listenerUdp   = TrackerListenerFactory.CreateUdp(IPAddress.Any, TRACKERUDP_PORT);   // http://localhost:{TRACKER_PORT}/announce

                //Add logning
                trackerServer.PeerAnnounced   += delegate(object o, AnnounceEventArgs e) { Log.Get().Write("TrackerServer PeerAnnounced"); };
                trackerServer.PeerScraped     += delegate(object o, ScrapeEventArgs e) { Log.Get().Write("TrackerServer PeerScrape"); };
                trackerServer.PeerTimedOut    += delegate(object o, TimedOutEventArgs e) { Log.Get().Write("TrackerServer Peer timeout"); };
                listenerHttp.AnnounceReceived += delegate(object o, AnnounceRequest e) { Log.Get().Write("TrackerListenerHTTP Announce received"); };
                listenerHttp.ScrapeReceived   += delegate(object o, TrackerScrapeRequest e) { Log.Get().Write("TrackerListenerHTTP Scrape received"); };
                listenerHttp.StatusChanged    += delegate(object o, EventArgs e)
                {
                    Log.Get().Write("TrackerListenerHttp Status changed: " + listenerHttp.Status);  //Typecast not working here, protectionlevel error. :( /*((MonoTorrent.Tracker.Listeners.HttpTrackerListener)o)*/
                };
                listenerUdp.AnnounceReceived += delegate(object o, AnnounceRequest e) { Log.Get().Write("TrackerListenerUDP Announce received"); };
                listenerUdp.ScrapeReceived   += delegate(object o, TrackerScrapeRequest e) { Log.Get().Write("TrackerListenerUDP Scrape received"); };
                listenerUdp.StatusChanged    += delegate(object o, EventArgs e)
                {
                    Log.Get().Write("TrackerListenerUdp Status changed: " + listenerUdp.Status);
                };

                //Start tracking server
                trackerServer.RegisterListener(listenerHttp);
                trackerServer.RegisterListener(listenerUdp);
                listenerUdp.Start();
                listenerHttp.Start();
                trackerServer.AllowUnregisteredTorrents = false; // If an announce request is received for a torrent which is not registered with the tracker an error will be returned.
                Log.Get().Write("TrackerListener listener status http:" + listenerHttp.Status + " udp status: " + listenerUdp.Status);
            }

            //-------------------------------------------------------------
            //Add new torrent to tracker
            //-------------------------------------------------------------
            MonoTorrent.Torrent torrent   = MonoTorrent.Torrent.Load(torrentData);
            InfoHashTrackable   trackable = new InfoHashTrackable(torrent);

            trackerServer.Add(trackable);
            Log.Get().Write("Adding torrent to tracker server, torrent size: " + torrentData.Length);

            //-------------------------------------------------------------
            //Seed file
            //-------------------------------------------------------------
            Log.Get().Write("Prepare to seed file");
            DownloadTorrent(torrent);
        }
Пример #6
0
        private static void StartEngine()
        {
            int     port;
            Torrent torrent = null;

            // Ask the user what port they want to use for incoming connections
            Console.Write(Environment.NewLine + "Choose a listen port: ");
            while (!Int32.TryParse(Console.ReadLine(), out port))
            {
            }



            // Create the settings which the engine will use
            // downloadsPath - this is the path where we will save all the files to
            // port - this is the port we listen for connections on
            EngineSettings engineSettings = new EngineSettings(downloadsPath, port);

            engineSettings.PreferEncryption  = false;
            engineSettings.AllowedEncryption = EncryptionTypes.All;

            //engineSettings.GlobalMaxUploadSpeed = 30 * 1024;
            //engineSettings.GlobalMaxDownloadSpeed = 100 * 1024;
            //engineSettings.MaxReadRate = 1 * 1024 * 1024;


            // Create the default settings which a torrent will have.
            // 4 Upload slots - a good ratio is one slot per 5kB of upload speed
            // 50 open connections - should never really need to be changed
            // Unlimited download speed - valid range from 0 -> int.Max
            // Unlimited upload speed - valid range from 0 -> int.Max
            TorrentSettings torrentDefaults = new TorrentSettings(4, 150, 0, 0);

            // Create an instance of the engine.
            engine = new ClientEngine(engineSettings);
            engine.ChangeListenEndpoint(new IPEndPoint(IPAddress.Any, port));
            byte[] nodes = null;
            try
            {
                nodes = File.ReadAllBytes(dhtNodeFile);
            }
            catch
            {
                Console.WriteLine("No existing dht nodes could be loaded");
            }

            DhtListener dhtListner = new DhtListener(new IPEndPoint(IPAddress.Any, port));
            DhtEngine   dht        = new DhtEngine(dhtListner);

            engine.RegisterDht(dht);
            dhtListner.Start();
            engine.DhtEngine.Start(nodes);

            // If the SavePath does not exist, we want to create it.
            if (!Directory.Exists(engine.Settings.SavePath))
            {
                Directory.CreateDirectory(engine.Settings.SavePath);
            }

            // If the torrentsPath does not exist, we want to create it
            if (!Directory.Exists(torrentsPath))
            {
                Directory.CreateDirectory(torrentsPath);
            }

            BEncodedDictionary fastResume;

            try
            {
                fastResume = BEncodedValue.Decode <BEncodedDictionary>(File.ReadAllBytes(fastResumeFile));
            }
            catch
            {
                fastResume = new BEncodedDictionary();
            }

            // For each file in the torrents path that is a .torrent file, load it into the engine.
            foreach (string file in Directory.GetFiles(torrentsPath))
            {
                if (file.EndsWith(".torrent"))
                {
                    try
                    {
                        // Load the .torrent from the file into a Torrent instance
                        // You can use this to do preprocessing should you need to
                        torrent = Torrent.Load(file);
                        Console.WriteLine(torrent.InfoHash.ToString());
                    }
                    catch (Exception e)
                    {
                        Console.Write("Couldn't decode {0}: ", file);
                        Console.WriteLine(e.Message);
                        continue;
                    }
                    // When any preprocessing has been completed, you create a TorrentManager
                    // which you then register with the engine.
                    TorrentManager manager = new TorrentManager(torrent, downloadsPath, torrentDefaults);
                    if (fastResume.ContainsKey(torrent.InfoHash.ToHex()))
                    {
                        manager.LoadFastResume(new FastResume((BEncodedDictionary)fastResume[torrent.infoHash.ToHex()]));
                    }
                    engine.Register(manager);

                    // Store the torrent manager in our list so we can access it later
                    torrents.Add(manager);
                    manager.PeersFound += new EventHandler <PeersAddedEventArgs>(manager_PeersFound);
                }
            }

            // If we loaded no torrents, just exist. The user can put files in the torrents directory and start
            // the client again
            if (torrents.Count == 0)
            {
                Console.WriteLine("No torrents found in the Torrents directory");
                Console.WriteLine("Exiting...");
                engine.Dispose();
                return;
            }

            // For each torrent manager we loaded and stored in our list, hook into the events
            // in the torrent manager and start the engine.
            foreach (TorrentManager manager in torrents)
            {
                // Every time a piece is hashed, this is fired.
                manager.PieceHashed += delegate(object o, PieceHashedEventArgs e) {
                    lock (listener)
                        listener.WriteLine(string.Format("Piece Hashed: {0} - {1}", e.PieceIndex, e.HashPassed ? "Pass" : "Fail"));
                };

                // Every time the state changes (Stopped -> Seeding -> Downloading -> Hashing) this is fired
                manager.TorrentStateChanged += delegate(object o, TorrentStateChangedEventArgs e) {
                    lock (listener)
                        listener.WriteLine("OldState: " + e.OldState.ToString() + " NewState: " + e.NewState.ToString());
                };

                // Every time the tracker's state changes, this is fired
                foreach (TrackerTier tier in manager.TrackerManager)
                {
                    foreach (MonoTorrent.Client.Tracker.Tracker t in tier.Trackers)
                    {
                        t.AnnounceComplete += delegate(object sender, AnnounceResponseEventArgs e) {
                            listener.WriteLine(string.Format("{0}: {1}", e.Successful, e.Tracker.ToString()));
                        };
                    }
                }
                // Start the torrentmanager. The file will then hash (if required) and begin downloading/seeding
                manager.Start();
            }

            // While the torrents are still running, print out some stats to the screen.
            // Details for all the loaded torrent managers are shown.
            int           i       = 0;
            bool          running = true;
            StringBuilder sb      = new StringBuilder(1024);

            while (running)
            {
                if ((i++) % 10 == 0)
                {
                    sb.Remove(0, sb.Length);
                    running = torrents.Exists(delegate(TorrentManager m) { return(m.State != TorrentState.Stopped); });

                    AppendFormat(sb, "Total Download Rate: {0:0.00}kB/sec", engine.TotalDownloadSpeed / 1024.0);
                    AppendFormat(sb, "Total Upload Rate:   {0:0.00}kB/sec", engine.TotalUploadSpeed / 1024.0);
                    AppendFormat(sb, "Disk Read Rate:      {0:0.00} kB/s", engine.DiskManager.ReadRate / 1024.0);
                    AppendFormat(sb, "Disk Write Rate:     {0:0.00} kB/s", engine.DiskManager.WriteRate / 1024.0);
                    AppendFormat(sb, "Total Read:         {0:0.00} kB", engine.DiskManager.TotalRead / 1024.0);
                    AppendFormat(sb, "Total Written:      {0:0.00} kB", engine.DiskManager.TotalWritten / 1024.0);
                    AppendFormat(sb, "Open Connections:    {0}", engine.ConnectionManager.OpenConnections);

                    foreach (TorrentManager manager in torrents)
                    {
                        AppendSeperator(sb);
                        AppendFormat(sb, "State:           {0}", manager.State);
                        AppendFormat(sb, "Name:            {0}", manager.Torrent == null ? "MetaDataMode" : manager.Torrent.Name);
                        AppendFormat(sb, "Progress:           {0:0.00}", manager.Progress);
                        AppendFormat(sb, "Download Speed:     {0:0.00} kB/s", manager.Monitor.DownloadSpeed / 1024.0);
                        AppendFormat(sb, "Upload Speed:       {0:0.00} kB/s", manager.Monitor.UploadSpeed / 1024.0);
                        AppendFormat(sb, "Total Downloaded:   {0:0.00} MB", manager.Monitor.DataBytesDownloaded / (1024.0 * 1024.0));
                        AppendFormat(sb, "Total Uploaded:     {0:0.00} MB", manager.Monitor.DataBytesUploaded / (1024.0 * 1024.0));
                        MonoTorrent.Client.Tracker.Tracker tracker = manager.TrackerManager.CurrentTracker;
                        //AppendFormat(sb, "Tracker Status:     {0}", tracker == null ? "<no tracker>" : tracker.State.ToString());
                        AppendFormat(sb, "Warning Message:    {0}", tracker == null ? "<no tracker>" : tracker.WarningMessage);
                        AppendFormat(sb, "Failure Message:    {0}", tracker == null ? "<no tracker>" : tracker.FailureMessage);
                        if (manager.PieceManager != null)
                        {
                            AppendFormat(sb, "Current Requests:   {0}", manager.PieceManager.CurrentRequestCount());
                        }

                        foreach (PeerId p in manager.GetPeers())
                        {
                            AppendFormat(sb, "\t{2} - {1:0.00}/{3:0.00}kB/sec - {0}", p.Peer.ConnectionUri,
                                         p.Monitor.DownloadSpeed / 1024.0,
                                         p.AmRequestingPiecesCount,
                                         p.Monitor.UploadSpeed / 1024.0);
                        }

                        AppendFormat(sb, "", null);
                        if (manager.Torrent != null)
                        {
                            foreach (TorrentFile file in manager.Torrent.Files)
                            {
                                AppendFormat(sb, "{1:0.00}% - {0}", file.Path, file.BitField.PercentComplete);
                            }
                        }
                    }
                    Console.Clear();
                    Console.WriteLine(sb.ToString());
                    listener.ExportTo(Console.Out);
                }

                System.Threading.Thread.Sleep(500);
            }
        }
Пример #7
0
 public EditableTorrent(Torrent torrent)
 {
     Check.Torrent(torrent);
     Initialise(torrent.ToDictionary());
 }
Пример #8
0
 public Torrent ToTorrent()
 {
     return(Torrent.Load(ToDictionary()));
 }
Пример #9
0
 public TorrentEditor(Torrent torrent)
     : base(torrent)
 {
 }