public TorrentController(MainWindow mainWindow)
		{
			this.userTorrentSettings = mainWindow.userTorrentSettings;
			this.userEngineSettings = mainWindow.userEngineSettings;
			this.prefSettings = mainWindow.prefSettings;
			this.labels = mainWindow.labels;
			this.torrentListStore = mainWindow.torrentListStore;
			this.torrents = mainWindow.torrents;
			this.mainWindow = mainWindow;
			this.pieces = mainWindow.pieces;
			this.torrentPreviousUpload = new Dictionary<MonoTorrent.Client.TorrentManager,long>();
			this.torrentPreviousDownload = new Dictionary<MonoTorrent.Client.TorrentManager,long>();
			
			engineSettings = new EngineSettings(userEngineSettings.SavePath, userEngineSettings.ListenPort, userEngineSettings.GlobalMaxConnections, userEngineSettings.GlobalMaxHalfOpenConnections, userEngineSettings.GlobalMaxDownloadSpeed, userEngineSettings.GlobalMaxUploadSpeed, EngineSettings.DefaultSettings().MinEncryptionLevel, userEngineSettings.AllowLegacyConnections);
			torrentSettings = new TorrentSettings(userTorrentSettings.UploadSlots, userTorrentSettings.MaxConnections, userTorrentSettings.MaxDownloadSpeed, userTorrentSettings.MaxUploadSpeed, userTorrentSettings.FastResumeEnabled);
			
			engine = new ClientEngine(engineSettings);
			
			engine.ConnectionManager.PeerMessageTransferred += OnPeerMessageTransferred;
			
			hashProgress = new Dictionary<MonoTorrent.Client.TorrentManager,int>();
			torrentSwarm = new Dictionary<MonoTorrent.Client.TorrentManager,int>();
			torrentsDownloading = new ArrayList();
			torrentsSeeding = new ArrayList();
			allTorrents = new ArrayList();
		}
Example #2
0
        public MonoTorrentClient(string applicationDataDirectoryPath)
        {
            // Make directories.
            var monoTorrentClientApplicationDataDirectoryPath = Path.Combine (applicationDataDirectoryPath, this.GetType().Name);
            if (!Directory.Exists (monoTorrentClientApplicationDataDirectoryPath))
                Directory.CreateDirectory (monoTorrentClientApplicationDataDirectoryPath);

            TorrentFileDirectory = Path.Combine (monoTorrentClientApplicationDataDirectoryPath, "torrents");
            if (!Directory.Exists (TorrentFileDirectory))
                Directory.CreateDirectory (TorrentFileDirectory);

            BrokenTorrentFileDirectory = Path.Combine (monoTorrentClientApplicationDataDirectoryPath, "broken");
            if (!Directory.Exists (BrokenTorrentFileDirectory))
                Directory.CreateDirectory (BrokenTorrentFileDirectory);

            // Make files.
            DHTNodeFile = Path.Combine (monoTorrentClientApplicationDataDirectoryPath, "dhtNodes");
            FastResumeFile = Path.Combine (monoTorrentClientApplicationDataDirectoryPath, "fastResume");
            TorrentMappingsCacheFile = Path.Combine (monoTorrentClientApplicationDataDirectoryPath, "torrentMappingsCache");

            // Make mappings cache.
            TorrentMappingsCache = new ListFile<TorrentMapping> (TorrentMappingsCacheFile);

            // Make default torrent settings.
            DefaultTorrentSettings = new TorrentSettings (DefaultTorrentUploadSlots, DefaultTorrentOpenConnections, 0, 0);
        }
Example #3
0
        public TorrentManager(MagnetLink magnetLink, string savePath, TorrentSettings settings, string torrentSave)
        {
            Check.MagnetLink(magnetLink);
            Check.InfoHash(magnetLink.InfoHash);
            Check.SavePath(savePath);
            Check.Settings(settings);
            Check.TorrentSave(torrentSave);

            this.InfoHash    = magnetLink.InfoHash;
            this.Settings    = settings;
            this.torrentSave = torrentSave;
            IList <RawTrackerTier> announces = new RawTrackerTiers();

            if (magnetLink.AnnounceUrls != null)
            {
                announces.Add(magnetLink.AnnounceUrls);
            }

            if (MonoTorrent.Common.Torrent.TryLoad(torrentSave, out Torrent torrent) && torrent.InfoHash == magnetLink.InfoHash)
            {
                Torrent = torrent;
            }

            Initialise(savePath, "", announces);
            if (Torrent != null)
            {
                ChangePicker(CreateStandardPicker());
            }
        }
Example #4
0
        public BitTorrentManager(BitTorrentCache bittorrentCache, string selfNameSpace,
            DictionaryServiceProxy dhtProxy, DictionaryServiceTracker dhtTracker, ClientEngine clientEngine,
            TorrentSettings torrentDefaults, TorrentHelper torrentHelper,
            bool startSeedingAtStartup)
        {
            _bittorrentCache = bittorrentCache;
              SelfNameSpace = selfNameSpace;
              _dictProxy = dhtProxy;
              _dictTracker = dhtTracker;
              _torrentDefaults = torrentDefaults;
              _startSeedingAtStartup = startSeedingAtStartup;

              RegisterClientEngineEventHandlers(clientEngine);
              _clientEngine = clientEngine;

              _torrentHelper = torrentHelper;

              try {
            _fastResumeData = BEncodedValue.Decode<BEncodedDictionary>(
              File.ReadAllBytes(_bittorrentCache.FastResumeFilePath));
              } catch {
            _fastResumeData = new BEncodedDictionary();
              }

              // CacheRegistry is created here because the default cache registry file path is
              // defined here.
              CacheRegistry = new CacheRegistry(_bittorrentCache.CacheRegistryFilePath, selfNameSpace);
              CacheRegistry.LoadCacheDir(_bittorrentCache.DownloadsDirPath);
        }
Example #5
0
        public TorrentManager(MagnetLink magnetLink, string savePath, TorrentSettings settings, string torrentSave)
        {
            Check.MagnetLink(magnetLink);
            Check.InfoHash(magnetLink.InfoHash);
            Check.SavePath(savePath);
            Check.Settings(settings);
            Check.TorrentSave(torrentSave);

            this.infohash    = magnetLink.InfoHash;
            this.settings    = settings;
            this.torrentSave = torrentSave;
            IList <RawTrackerTier> announces = new RawTrackerTiers();

            if (magnetLink.AnnounceUrls != null)
            {
                announces.Add(magnetLink.AnnounceUrls);
            }
            this.webseeds = new List <String>();
            if (magnetLink.Webseeds != null)
            {
                foreach (string webseed in magnetLink.Webseeds)
                {
                    this.webseeds.Add(webseed);
                }
            }

            Initialise(savePath, "", announces);
        }
		public override bool Equals(object obj)
		{
			TorrentSettings settings = obj as TorrentSettings;
			return (settings == null) ? false : this.initialSeedingEnabled == settings.initialSeedingEnabled &&
												this.maxConnections == settings.maxConnections &&
												this.maxDownloadSpeed == settings.maxDownloadSpeed &&
												this.maxUploadSpeed == settings.maxUploadSpeed &&
												this.uploadSlots == settings.uploadSlots;
		}
		public TorrentStorage(string torrentPath, string savePath, TorrentSettings settings, TorrentState state, long uploadedData, long downloadedData)
		{
			this.torrentPath = torrentPath;
			this.savePath = savePath;
			this.settings = settings;
			this.state = state;
			this.uploadedData = uploadedData;
			this.downloadedData = downloadedData;
		}
 public TorrentSettingWindow(TorrentSettings defaultSettings, string savePath)
 {
     InitializeComponent();
     UploadSlotsNumericUpDown.Value = defaultSettings.UploadSlots;
     MaxConnectionsNumericUpDown.Value = defaultSettings.MaxConnections;
     MaxDownloadSpeedNumericUpDown.Value = defaultSettings.MaxDownloadSpeed;
     MaxUploadSpeedNumericUpDown.Value = defaultSettings.MaxUploadSpeed;
     FastResumeCheckBox.Checked = defaultSettings.FastResumeEnabled;
     SavePathTextBox.Text = savePath;
 }
Example #9
0
        public void Deserialize(BEncodedDictionary dict)
        {
            fastResume = new FastResume ((BEncodedDictionary) dict["FastResume"]);
            savePath = dict["SavePath"].ToString ();
            torrentPath = dict["TorrentPath"].ToString ();

            string sb = dict["Settings"].ToString ();
            XmlSerializer s = new XmlSerializer (typeof (TorrentSettings));
            using (System.IO.TextReader reader = new System.IO.StringReader (sb))
                settings = (TorrentSettings) s.Deserialize (reader);
        }
Example #10
0
        static void Main(string[] args)
        {
            var traceListener = new ConsoleTraceListener();

              Debug.Listeners.Add(traceListener);

              var torrentDefaults = new TorrentSettings(4, 150, 0, 0);
              torrentDefaults.UseDht = false;
              var engineSettings = new EngineSettings();
              engineSettings.PreferEncryption = false;
              engineSettings.AllowedEncryption = EncryptionTypes.All;
              var clientEngine = new ClientEngine(engineSettings);
              StartDownload(clientEngine, torrentDefaults);
        }
        /// <summary>
        /// Creates a new TorrentManager instance.
        /// </summary>
        /// <param name="torrent">The torrent to load in</param>
        /// <param name="savePath">The directory to save downloaded files to</param>
        /// <param name="settings">The settings to use for controlling connections</param>
        /// <param name="baseDirectory">In the case of a multi-file torrent, the name of the base directory containing the files. Defaults to Torrent.Name</param>
        public TorrentManager(Torrent torrent, string savePath, TorrentSettings settings, string baseDirectory)
        {
            Check.Torrent(torrent);
            Check.SavePath(savePath);
            Check.Settings(settings);
            Check.BaseDirectory(baseDirectory);

            this.torrent  = torrent;
            this.infohash = torrent.infoHash;
            this.settings = settings;

            Initialise(savePath, baseDirectory, torrent.AnnounceUrls);
            ChangePicker(CreateStandardPicker());
        }
        public TorrentManager(InfoHash infoHash, string savePath, TorrentSettings settings, string torrentSave, IList <RawTrackerTier> announces)
        {
            Check.InfoHash(infoHash);
            Check.SavePath(savePath);
            Check.Settings(settings);
            Check.TorrentSave(torrentSave);
            Check.Announces(announces);

            this.infohash    = infoHash;
            this.settings    = settings;
            this.torrentSave = torrentSave;

            Initialise(savePath, "", announces);
        }
        /// <summary>
        /// Adds the file to download. This method returns when the torrent is 
        /// added and doesn't wait for the download to complete.
        /// </summary>
        /// <param name="torrent">The torrent.</param>
        /// <param name="savePath">The save path.</param>
        public void StartDownloadingFile(Torrent torrent, string savePath, int lastPieceInProfile)
        {
            TorrentSettings torrentDefaults = new TorrentSettings(4, 150, 0, 0);
            var tm = new TorrentManager(torrent, savePath, torrentDefaults, "", lastPieceInProfile);
            // There is no need to scrape since we manage the tracker.
            tm.TrackerManager.CurrentTracker.CanScrape = false;

            _clientEngine.Register(tm);

            tm.TrackerManager.CurrentTracker.AnnounceComplete +=
                new EventHandler<AnnounceResponseEventArgs>(
                    TorrentEventHandlers.HandleAnnounceComplete);

            tm.TrackerManager.CurrentTracker.ScrapeComplete += delegate(object o, ScrapeResponseEventArgs e) {
                logger.DebugFormat("Scrape completed. Successful={0}, Tracker={1}",
                    e.Successful, e.Tracker.Uri);
            };

            tm.TorrentStateChanged +=
                new EventHandler<TorrentStateChangedEventArgs>(
                    TorrentEventHandlers.HandleTorrentStateChanged);

            tm.PieceHashed +=
                new EventHandler<PieceHashedEventArgs>(
                    TorrentEventHandlers.HandlePieceHashed);

            tm.PeerConnected += delegate(object o, PeerConnectionEventArgs e) {
                // Only log three connections.
                if (e.TorrentManager.OpenConnections < 4) {
                    logger.DebugFormat(
                        "Peer ({0}) Connected. Currently {1} open connection.",
                        e.PeerID.Uri, e.TorrentManager.OpenConnections);
                }
            };

            tm.PieceManager.BlockReceived += delegate(object o, BlockEventArgs e) {
                logger.DebugFormat("Block {0} from piece {1} is received.", e.Block.StartOffset / Piece.BlockSize, e.Piece.Index);
            };

            // We really only deal with one file.
            foreach (var file in tm.Torrent.Files) {
                _torrentManagerTable[file.FullPath] = tm;
            }

            tm.Start();
            logger.DebugFormat(
                "Starting to download torrent: {0}. Torrent manager started.",
                tm.Torrent.Name);
        }
Example #14
0
        public static void Main(string[] args)
        {
            BasicConfigurator.Configure(new ConsoleAppender() {
            Layout = new PatternLayout(
              "%timestamp [%thread] %-5level %logger{1} - %message%newline")
              });

              var torrentDefaults = new TorrentSettings(4, 150, 0, 0);
              torrentDefaults.UseDht = false;
              var engineSettings = new EngineSettings();
              engineSettings.PreferEncryption = false;
              engineSettings.AllowedEncryption = EncryptionTypes.All;
              var clientEngine = new ClientEngine(engineSettings);
              StartDownload(clientEngine, torrentDefaults);
        }
Example #15
0
        private static void StartDownload(ClientEngine clientEngine, TorrentSettings
            torrentDefaultSettings)
        {
            string baseDir = Path.Combine(Path.Combine(
              Environment.GetFolderPath(Environment.SpecialFolder.Personal),
              "var"), "MonoTorrent");
              Debug.WriteLine(string.Format("Base Dir is {0}", baseDir));
              var torrent = Torrent.Load(Path.Combine(baseDir, TorrentFileName));
              var torrentManager = new TorrentManager(torrent, Path.Combine(baseDir,
            "Downloads"), torrentDefaultSettings, "", -1);

              clientEngine.Register(torrentManager);
              torrentManager.Start();
              Console.Read();
        }
Example #16
0
        internal TorrentManager(MagnetLink magnetLink, string savePath, TorrentSettings settings, string torrentSave)
        {
            Check.MagnetLink(magnetLink);
            Check.InfoHash(magnetLink.InfoHash);
            Check.SavePath(savePath);
            Check.Settings(settings);
            Check.TorrentSave(torrentSave);

            this.InfoHash    = magnetLink.InfoHash;
            this.Settings    = settings;
            this.torrentSave = torrentSave;
            IList <RawTrackerTier> announces = new RawTrackerTiers();

            if (magnetLink.AnnounceUrls != null)
            {
                announces.Add(magnetLink.AnnounceUrls);
            }
            Initialise(savePath, "", announces);
        }
        /// <summary>
        /// Creates a new TorrentManager instance.
        /// </summary>
        /// <param name="torrent">The torrent to load in</param>
        /// <param name="savePath">The directory to save downloaded files to</param>
        /// <param name="settings">The settings to use for controlling connections</param>
        /// <param name="baseDirectory">In the case of a multi-file torrent, the name of the base directory containing the files. Defaults to Torrent.Name</param>
        public TorrentManager(Torrent torrent, string savePath, TorrentSettings settings, string baseDirectory)
        {
            Check.Torrent(torrent);
            Check.SavePath(savePath);
            Check.Settings(settings);
            Check.BaseDirectory(baseDirectory);

            this.torrent  = torrent;
            this.infohash = torrent.InfoHash;
            this.settings = settings;
            this.webseeds = new List <String>();
            if (torrent.GetRightHttpSeeds != null)
            {
                foreach (string webseed in torrent.GetRightHttpSeeds)
                {
                    this.webseeds.Add(webseed);
                }
            }

            Initialise(savePath, baseDirectory, torrent.AnnounceUrls);
            ChangePicker(CreateStandardPicker());
        }
        public TorrentManager(InfoHash infoHash, string savePath, TorrentSettings settings, string torrentSave, IList <RawTrackerTier> announces, IList <String> webseeds = null)
        {
            Check.InfoHash(infoHash);
            Check.SavePath(savePath);
            Check.Settings(settings);
            Check.TorrentSave(torrentSave);
            Check.Announces(announces);

            this.infohash    = infoHash;
            this.settings    = settings;
            this.torrentSave = torrentSave;
            this.webseeds    = new List <String>();
            if (webseeds != null)
            {
                foreach (string webseed in webseeds)
                {
                    this.webseeds.Add(webseed);
                }
            }

            Initialise(savePath, "", announces);
        }
        public BitTorrentFileTransferProvider()
        {
            MonoTorrent.Client.Logger.AddListener(new System.Diagnostics.ConsoleTraceListener());

            string downloadPath = Core.Settings.IncompleteDownloadDir;
            EngineSettings settings = new EngineSettings (downloadPath, 1);

            torrentDefaults = new TorrentSettings (4, 60, 0, 0);

            listener = new MeshworkPeerConnectionListener ();
            engine = new ClientEngine(settings, listener);

            Core.FinishedLoading += delegate {
                Core.FileTransferManager.FileTransferRemoved += Core_FileTransferRemoved;
            };

            #if RIDICULOUS_DEBUG_OUTPUT
            engine.ConnectionManager.PeerMessageTransferred += delegate (object sender, PeerMessageEventArgs e) {
                LoggingService.LogDebug("{0}: {1}", e.Direction, e.Message.GetType().Name);
            };
            #endif
        }
        public TorrentManager(MagnetLink magnetLink, string savePath, TorrentSettings settings, string torrentSave)
        {
            Torrent torrent;

            Check.MagnetLink(magnetLink);
            Check.InfoHash(magnetLink.InfoHash);
            Check.SavePath(savePath);
            Check.Settings(settings);
            Check.TorrentSave(torrentSave);

            this.infohash    = magnetLink.InfoHash;
            this.settings    = settings;
            this.torrentSave = torrentSave;
            IList <RawTrackerTier> announces = new RawTrackerTiers();

            if (magnetLink.AnnounceUrls != null)
            {
                announces.Add(magnetLink.AnnounceUrls);
            }
            this.webseeds = new List <String>();
            if (magnetLink.Webseeds != null)
            {
                foreach (string webseed in magnetLink.Webseeds)
                {
                    this.webseeds.Add(webseed);
                }
            }

            if (Torrent.TryLoad(torrentSave, out torrent) && torrent.InfoHash == magnetLink.InfoHash)
            {
                this.torrent = torrent;
                Initialise(savePath, "", announces);
                ChangePicker(CreateStandardPicker());
                return;
            }

            Initialise(savePath, "", announces);
        }
Example #21
0
        /// <summary>
        /// Initializes the Torrent client  and its basic core members
        /// </summary>
        public TorrentClient()
        {
            saveDirectory = GlobalSettings.DownloadDirectory;
            metaSaveDirectory = GlobalSettings.DEFAULT_METADATA_DIRECTORY;
            dhtNodeFile = GlobalSettings.DHT_FILE;
            resumeFile = GlobalSettings.RESUME_FILE;
            Port = GlobalSettings.IncomingPort;
            CreateDir(saveDirectory);
            CreateDir(metaSaveDirectory);

            //initialize engine settings
            engineSettings = new EngineSettings();
            engineSettings = new EngineSettings(saveDirectory, Port);
            engineSettings.AllowedEncryption = MonoTorrent.Client.Encryption.EncryptionTypes.All;
            engineSettings.PreferEncryption = GlobalSettings.UseEncryption;
            engineSettings.GlobalMaxConnections = GlobalSettings.GlobalMaxConnections;

            //initialize torrent settings
            torrentSettings = new TorrentSettings();
            torrentSettings.EnablePeerExchange = GlobalSettings.UsePeerExchange;
            torrentSettings.UseDht = GlobalSettings.UseDht;
            torrentSettings.MaxConnections = GlobalSettings.TorrentMaxConnections;
        }
Example #22
0
        static void StartDownload(ClientEngine clientEngine, TorrentSettings torrentDefaultSettings)
        {
            string baseDir = Path.Combine(Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder.Personal), "var"),
            "MonoTorrent");
              Debug.WriteLine(string.Format("Base Dir is {0}", baseDir));

              var torrent = Torrent.Load(Path.Combine(baseDir, TorrentFileName));
              (torrent.Files[0] as TorrentFile).Priority = Priority.Highest;
              (torrent.Files[1] as TorrentFile).Priority = Priority.DoNotDownload;
              (torrent.Files[2] as TorrentFile).Priority = Priority.DoNotDownload;
              long targetDownloadSize = (torrent.Files[0] as TorrentFile).Length;
              long totalSize = torrent.Size;
              double targetPercentage = (double)targetDownloadSize / totalSize;
              Debug.WriteLine(string.Format("Intend to download {0}/{1} = {2}",
            targetDownloadSize, totalSize, targetPercentage));

              var torrentManager = new TorrentManager(torrent, Path.Combine(baseDir, "Downloads"), torrentDefaultSettings);
              var progressMonitor = new PartialDownloadProgressMonitor(torrentManager);
              progressMonitor.FileDownloaded += new EventHandler<FileDownloadedEventArgs>(progressMonitor_FileDownloaded);

              clientEngine.Register(torrentManager);

              torrentManager.TorrentStateChanged += new EventHandler<TorrentStateChangedEventArgs>(torrentManager_TorrentStateChanged);
              // Start downloading
              torrentManager.Start();

              // Keep running while the torrent isn't stopped or paused.
              while (torrentManager.State != TorrentState.Stopped &&
            torrentManager.State != TorrentState.Paused) {
            Debug.WriteLine(string.Format("Progress: {0}", torrentManager.Progress));
            System.Threading.Thread.Sleep(2000);
              }

              Console.Read();
        }
        public TorrentController()
        {
            this.defaultTorrentSettings = SettingsManager.DefaultTorrentSettings;
            this.SelectedDownloads = new List<Download> ();

            Ticker.Tick ();
            fastResume = LoadFastResume();
            Ticker.Tock ("Fast Resume");

            Ticker.Tick ();
            engine = new ClientEngine(SettingsManager.EngineSettings);
            Ticker.Tock ("Client engine");

            allTorrents = new List<Download>();

            Added += delegate(object sender, DownloadAddedEventArgs e) {
                e.Download.Priority = allTorrents.Count + 1;
            };
            Removed += delegate(object sender, DownloadAddedEventArgs e) {
                for (int i=0; i < allTorrents.Count; i++)
                    if (allTorrents [i].Priority > e.Download.Priority)
                        allTorrents[i].Priority--;
            };
        }
Example #24
0
        public Transfer(string path)
        {
            this.basePath = Path.GetFullPath(path);
            this.torrentsPath = Path.Combine(basePath, "Torrents");
            this.fastResumePath = Path.Combine(basePath, "fastresume.data");
            this.dhtNodes = Path.Combine(basePath, "dhtNodes.data");
            this.downloadsPath = Path.Combine(basePath, "Downloads");

            EngineSettings settings = new EngineSettings(downloadsPath, enginePort);
            settings.AllowedEncryption = MonoTorrent.Client.Encryption.EncryptionTypes.All;
            settings.PreferEncryption = false;

            this.engine = new ClientEngine(settings);
            engine.ConnectionManager.PeerMessageTransferred += delegate(object o, PeerMessageEventArgs e)
            {
                Console.WriteLine( e.Message);
            };

            this.managerCollection = new List<TorrentManager>();
            this.defaultSettings = new TorrentSettings(50, 100, 100000, 100000, false);
            defaultSettings.UseDht = false;
            defaultSettings.EnablePeerExchange = true;
            this.startDHT();
        }
Example #25
0
        /* Constructor */
        /// <summary>
        /// Initializes a new instance of the <see cref="TorrentsData" /> class.
        /// </summary>
        public TorrentsData()
        {
            this.baseDir = Environment.CurrentDirectory;
            this.GetValues(out this.torrentsDir, out this.downloadDir, out this.uploadSpeed, out this.downloadSpeed);
            this.fastResumeFile = Path.Combine(this.torrentsDir, "fastresume.data");
            this.dhtNodeFile = Path.Combine(this.baseDir, "DhtNodes");
            this.torrentManagers = new List<TorrentManager>();
            this.topTrackers = new TopListeners(10);

            Console.CancelKeyPress += delegate { this.Shutdown(); };
            AppDomain.CurrentDomain.ProcessExit += delegate { this.Shutdown(); };
            AppDomain.CurrentDomain.UnhandledException += delegate(object sender, UnhandledExceptionEventArgs e) { Console.WriteLine(e.ExceptionObject); this.Shutdown(); };
            Thread.GetDomain().UnhandledException += delegate(object sender, UnhandledExceptionEventArgs e) { Console.WriteLine(e.ExceptionObject); this.Shutdown(); };

            this.InitializeEngine();
            this.torrentDefaults = new TorrentSettings(4, 150, this.downloadSpeed, this.uploadSpeed);
        }
Example #26
0
        public async Task <TorrentManager> AddAsync(Torrent torrent, string saveDirectory, TorrentSettings settings)
        {
            await MainLoop.SwitchThread();

            var metadata = new BEncodedDictionary {
                { "info", BEncodedValue.Decode(torrent.InfoMetadata) }
            };

            var metadataCachePath = Settings.GetMetadataPath(torrent.InfoHash);

            Directory.CreateDirectory(Path.GetDirectoryName(metadataCachePath));
            File.WriteAllBytes(metadataCachePath, metadata.Encode());

            return(await AddAsync(null, torrent, saveDirectory, settings));
        }
Example #27
0
        private ObjectPath Load(TorrentAdapter tAdapter, TorrentSettings settings, TorrentManager manager)
        {
            ObjectPath managerPath = new ObjectPath (string.Format (DownloaderPath, downloaderNumber++));
            ObjectPath settingsPath = new ObjectPath (string.Format ("{0}/settings", managerPath.ToString ()));

            TorrentSettingsAdapter sAdapter = new TorrentSettingsAdapter(settings, settingsPath);
            TorrentManagerAdapter mAdapter = new TorrentManagerAdapter(manager, tAdapter, sAdapter, managerPath);

            TorrentService.Bus.Register (sAdapter.Path, sAdapter);
            TorrentService.Bus.Register (mAdapter.Path, mAdapter);

            engine.Register (manager);
            downloaders.Add (mAdapter.Path, mAdapter);

            return mAdapter.Path;
        }
Example #28
0
        public static void ConfigureUnityContainer(IUnityContainer container)
        {
            #region Common
              var dhtTrackerListenerPort =
            Int32.Parse(ConfigurationManager.AppSettings["DhtTrackerListeningPort"]);
              var infoServerListeningPort = Int32.Parse(ConfigurationManager.AppSettings[
            "HttpPieceInfoServerListeningPort"]); // listeningPort
              #endregion

              #region TorrentSettings
              // 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);
              container.RegisterInstance<TorrentSettings>(torrentDefaults);
              #endregion

              #region ClientEngine
              // DefaultListenPort = 52138;
              var engineSettings = new EngineSettings();
              engineSettings.PreferEncryption = false;
              engineSettings.AllowedEncryption = EncryptionTypes.All;
              var clientEngine = new ClientEngine(engineSettings);
              container.RegisterInstance<ClientEngine>(clientEngine);
              #endregion

              #region DhtProxy
              var peerTtlSecs = 60 * 50;
              container.RegisterType<DictionaryServiceProxy>(
            new InjectionConstructor(typeof(DictionaryServiceBase),
              peerTtlSecs));
              #endregion

              #region DhtTracker
              // Singleton.
              container.RegisterType<DictionaryServiceTracker>(new ContainerControlledLifetimeManager(),
            new InjectionConstructor(
              typeof(DictionaryServiceProxy),
              string.Format("http://*:{0}/", dhtTrackerListenerPort))); // listeningPrefix
              #endregion

              #region TorrentHelper
              // Singleton.
              var cacheBaseDirPath =
            ConfigurationManager.AppSettings["BitTorrentManagerBaseDirPath"];
              IPAddress ip = NetUtil.GetLocalIPByInterface(
            ConfigurationManager.AppSettings["DhtTrackerIface"]);
              int gsserverPort = Int32.Parse(ConfigurationManager.AppSettings["GSServerPort"]);
              var bittorrentCache = new BitTorrentCache(cacheBaseDirPath);
              container.RegisterInstance<BitTorrentCache>(bittorrentCache);
              var torrentHelper = new TorrentHelper(
            bittorrentCache, ip, dhtTrackerListenerPort, gsserverPort);
              container.RegisterInstance<TorrentHelper>(torrentHelper);
              #endregion

              #region BitTorrentManager
              // Singleton.
              container.RegisterType<BitTorrentManager>(
            new ContainerControlledLifetimeManager(),
            new InjectionConstructor(
              typeof(BitTorrentCache),
              ConfigurationManager.AppSettings["BitTorrentManagerSelfNamespace"],
              typeof(DictionaryServiceProxy),
              typeof(DictionaryServiceTracker),
              typeof(ClientEngine),
              typeof(TorrentSettings),
              typeof(TorrentHelper),
              Boolean.Parse(ConfigurationManager.AppSettings[
            "BitTorrentManagerStartSeedingAtStartup"])
              ));
              #endregion

              #region IPieceInfoServer
              // Singleton.
              //container.RegisterType<IPieceInfoServer, HttpPieceInfoServer>(
              //    new ContainerControlledLifetimeManager(),
              //    new InjectionConstructor(
              //      infoServerListeningPort,
              //      typeof(PieceLevelTorrentManager)));
              #endregion

              #region PieceLevelTorrentManager
              container.RegisterType<PieceLevelTorrentManager>(
            new ContainerControlledLifetimeManager(),
            new InjectionConstructor(
              typeof(BitTorrentManager),
              typeof(BitTorrentCache),
              typeof(DictionaryServiceProxy),
              typeof(TorrentHelper),
              infoServerListeningPort));
              #endregion
        }
Example #29
0
 public void LoadTorrent(string path, bool autoStart, bool moveToStorage, bool removeOriginal, TorrentSettings settings, string savePath, bool isUrl)
 {
     #warning URL based torrents arent being loaded
     //return torrentController.addTorrent(path, autoStart, moveToStorage, removeOriginal, settings, savePath, isUrl);
 }
 /// <summary>
 /// Gets default settings for torrent
 /// </summary>
 /// <returns></returns>
 private TorrentSettings GetDefaultTorrentSettings()
 {
     // 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
     var torrentDefaults = new TorrentSettings(4, 150, 0, 0);
     return torrentDefaults;
 }
Example #31
0
 public Task <TorrentManager> AddStreamingAsync(Torrent torrent, string saveDirectory, TorrentSettings settings)
 => AddStreamingAsync(null, torrent, saveDirectory, settings);
Example #32
0
        async Task <TorrentManager> AddAsync(MagnetLink magnetLink, Torrent torrent, string saveDirectory, TorrentSettings settings)
        {
            saveDirectory = string.IsNullOrEmpty(saveDirectory) ? Environment.CurrentDirectory : Path.GetFullPath(saveDirectory);
            TorrentManager manager;

            if (magnetLink != null)
            {
                var metadataSaveFilePath = Settings.GetMetadataPath(magnetLink.InfoHash);
                manager = new TorrentManager(magnetLink, saveDirectory, settings, metadataSaveFilePath);
                if (Settings.AutoSaveLoadMagnetLinkMetadata && Torrent.TryLoad(metadataSaveFilePath, out torrent) && torrent.InfoHash == magnetLink.InfoHash)
                {
                    manager.SetMetadata(torrent);
                }
            }
            else
            {
                manager = new TorrentManager(torrent, saveDirectory, settings);
            }

            await Register(manager, true);

            await manager.MaybeLoadFastResumeAsync();

            return(manager);
        }
        private void StartEngine(int maxUpload)
        {
            int port = 54321;
            Torrent torrent = null;
            // 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 = true;
            engineSettings.AllowedEncryption = EncryptionTypes.RC4Full | EncryptionTypes.RC4Header;

            // 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(100, 150, 0, maxUpload);

            // 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);
                        RemoveReadOnly(torrent);
                    }
                    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)
                {
                };

                // Every time the state changes (Stopped -> Seeding -> Downloading -> Hashing) this is fired
                manager.TorrentStateChanged += OnTorrentStateChanged;

                // Every time the tracker's state changes, this is fired
                foreach (TrackerTier tier in manager.TrackerManager)
                {
                }
                // 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);
            DateTime lastAnnounce = DateTime.Now;
            bool firstRun = true;
            while (running)
            {
                if (firstRun || lastAnnounce < DateTime.Now.AddMinutes(-1))
                {
                    foreach (TorrentManager tm in torrents)
                    {
                        tm.TrackerManager.Announce();
                    }
                    lastAnnounce = DateTime.Now;
                    firstRun = false;
                }
                if ((i++) % 10 == 0)
                {
                    sb.Remove(0, sb.Length);
                    running = torrents.Exists(delegate(TorrentManager m) { return m.State != TorrentState.Stopped; });

                    TorrentState totalState = torrents.Exists(m => m.State == TorrentState.Hashing) ? TorrentState.Hashing : torrents.Exists(m => m.State == TorrentState.Downloading) ? TorrentState.Downloading : TorrentState.Seeding;

                    string status = "";
                    switch (totalState)
                    {
                        case TorrentState.Hashing:
                            double totalHashProgress = 0;
                            foreach (TorrentManager m in torrents)
                            {
                                totalHashProgress += (m.State == TorrentState.Hashing) ? m.Progress : 100;
                            }
                            totalHashProgress = totalHashProgress / torrents.Count;
                            status = String.Format("Checking files ({0:0.00}%)", totalHashProgress);
                            break;
                        case TorrentState.Seeding:
                            status = "";
                            break;
                        default:
                            double totalDownloadProgress = 0;
                            double totalDownloaded = 0;
                            double totalToDownload = 0;
                            double totalDownloadSpeed = 0;
                            long totalDownloadSize = 0;
                            foreach (TorrentManager m in torrents)
                                totalDownloadSize += m.Torrent.Size;

                            foreach (TorrentManager m in torrents)
                            {
                                totalDownloaded += m.Torrent.Size / 1024 * (m.Progress / 100);
                                totalToDownload += m.Torrent.Size / 1024;
                                totalDownloadSpeed += m.Monitor.DownloadSpeed;

                            }
                            totalDownloadProgress = (totalDownloaded / totalToDownload) * 100;
                            status = "Status: " + (torrents.Exists(m => m.State == TorrentState.Downloading && m.GetPeers().Count > 0) ? "Downloading" : "Finding peers");
                            status += "\n" + String.Format("Progress: {0:0.00}%", totalDownloadProgress);
                            status += "\n" + String.Format("D/L Speed: {0:0.00} kB/s", totalDownloadSpeed / 1024.0);
                            break;
                    }
                    if (installer != null)
                        installer.Status = status;

                    #region OLDPROGRESS
                    //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);
                    //    string status = "";
                    //    switch (manager.State)
                    //    {
                    //        case TorrentState.Hashing:
                    //            status = String.Format("Checking files ({0:0.00}%)", manager.Progress);
                    //            break;
                    //        case TorrentState.Seeding: status = ""; break;
                    //        default:
                    //            status = "Status: " + (manager.GetPeers().Count == 0 ? "Finding Peers" : "Downloading");
                    //            status += "\n" + String.Format("Progress: {0:0.00}%", manager.Progress);
                    //            status += "\n" + String.Format("D/L Speed: {0:0.00} kB/s", manager.Monitor.DownloadSpeed / 1024.0);
                    //            break;
                    //    }
                    //    if (installer != null)
                    //        installer.Status = status;
                    //    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.Status.ToString());
                    //    AppendFormat(sb, "Warning Message:    {0}", tracker == null ? "<no tracker>" : tracker.WarningMessage);
                    //    AppendFormat(sb, "Failure Message:    {0}", tracker == null ? "<no tracker>" : tracker.FailureMessage);
                    //}
                    ////Console.Clear();
                    //Console.WriteLine(sb.ToString());
                    #endregion
                }

                System.Threading.Thread.Sleep(500);
            }
        }
        async Task<TorrentManager> AddAsync (MagnetLink? magnetLink, Torrent? torrent, string saveDirectory, TorrentSettings settings)
        {
            await MainLoop;

            saveDirectory = string.IsNullOrEmpty (saveDirectory) ? Environment.CurrentDirectory : Path.GetFullPath (saveDirectory);
            TorrentManager manager;
            if (magnetLink != null) {
                var metadataSaveFilePath = Settings.GetMetadataPath (magnetLink.InfoHashes);
                manager = new TorrentManager (this, magnetLink, saveDirectory, settings);
                if (Settings.AutoSaveLoadMagnetLinkMetadata && Torrent.TryLoad (metadataSaveFilePath, out torrent) && torrent.InfoHashes == magnetLink.InfoHashes)
                    manager.SetMetadata (torrent);
            } else if (torrent != null) {
                manager = new TorrentManager (this, torrent, saveDirectory, settings);
            } else {
                throw new InvalidOperationException ($"You must pass a non-null {nameof (magnetLink)} or {nameof (torrent)}");
            }

            await Register (manager, true);
            await manager.MaybeLoadFastResumeAsync ();

            return manager;
        }
Example #35
0
 internal static byte[] Serialize(TorrentSettings settings)
 => Serialize(new TorrentSettingsBuilder(settings));
Example #36
0
	static void InitMonoTorrent ()
	{
		queue = new ArrayList ();
		engine_settings = new EngineSettings (config.DownloadDir, config.ListenPort);
		torrent_settings = new TorrentSettings (config.UploadSlots, config.MaxConnections,
							(int) config.UploadSpeed, (int) config.DownloadSpeed);
		
		engine = new ClientEngine (engine_settings);

		// Our store
		torrent_list = new TorrentList ();
		foreach (TorrentDesc td in config.Torrents){
			if (File.Exists (td.Filename)){
				torrent_list.Add (td.Filename);
			}
		}
	}
Example #37
0
        public async Task <TorrentManager> AddAsync(string metadataPath, string saveDirectory, TorrentSettings settings)
        {
            var torrent = await Torrent.LoadAsync(metadataPath).ConfigureAwait(false);

            var metadataCachePath = Settings.GetMetadataPath(torrent.InfoHash);

            if (metadataPath != metadataCachePath)
            {
                Directory.CreateDirectory(Path.GetDirectoryName(metadataCachePath));
                File.Copy(metadataPath, metadataCachePath, true);
            }
            return(await AddAsync(null, torrent, saveDirectory, settings));
        }
Example #38
0
#pragma warning disable CS0618 // Type or member is obsolete
        async Task <TorrentManager> AddAsync(MagnetLink magnetLink, Torrent torrent, string saveDirectory, TorrentSettings settings)
        {
            saveDirectory = string.IsNullOrEmpty(saveDirectory) ? Environment.CurrentDirectory : Path.GetFullPath(saveDirectory);
            TorrentManager manager;

            if (magnetLink != null)
            {
                var metadataSaveFilePath = Path.Combine(Settings.MetadataSaveDirectory, magnetLink.InfoHash.ToHex() + ".torrent");
                manager = new TorrentManager(magnetLink, saveDirectory, settings, metadataSaveFilePath);
            }
            else
            {
                manager = new TorrentManager(torrent, saveDirectory, settings);
            }
            await Register(manager);

            return(manager);
        }
 internal static BEncodedDictionary Serialize(TorrentSettings settings)
 => Serialize(new TorrentSettingsBuilder(settings));
Example #40
0
 public TorrentWrapper(MagnetLink magnetLink, string savePath, TorrentSettings settings, string torrentSave)
     : base(magnetLink, savePath, settings, torrentSave)
 {
     Name = magnetLink.Name;
     Name = HttpUtility.HtmlDecode(HttpUtility.UrlDecode(Name));
     Size = -1;
     IsMagnet = true;
 }
 /// <summary>
 /// Creates a new TorrentManager instance.
 /// </summary>
 /// <param name="torrent">The torrent to load in</param>
 /// <param name="savePath">The directory to save downloaded files to</param>
 /// <param name="settings">The settings to use for controlling connections</param>
 public TorrentManager(Torrent torrent, string savePath, TorrentSettings settings)
     : this(torrent, savePath, settings, torrent.Files.Length == 1 ? "" : torrent.Name)
 {
 }
Example #42
0
        public async Task <TorrentManager> AddAsync(Torrent torrent, string saveDirectory, TorrentSettings settings)
        {
            await MainLoop.SwitchThread();

            var editor = new TorrentEditor(new BEncodedDictionary {
                { "info", BEncodedValue.Decode(torrent.InfoMetadata) }
            });

            editor.SetCustom("name", (BEncodedString)torrent.Name);

            if (torrent.AnnounceUrls.Count > 0)
            {
                if (torrent.AnnounceUrls.Count == 1 && torrent.AnnounceUrls[0].Count == 1)
                {
                    editor.Announce = torrent.AnnounceUrls.Single().Single();
                }
                else
                {
                    foreach (var tier in torrent.AnnounceUrls)
                    {
                        var list = new List <string> ();
                        foreach (var tracker in tier)
                        {
                            list.Add(tracker);
                        }
                        editor.Announces.Add(list);
                    }
                }
            }

            var metadataCachePath = Settings.GetMetadataPath(torrent.InfoHash);

            Directory.CreateDirectory(Path.GetDirectoryName(metadataCachePath));
            File.WriteAllBytes(metadataCachePath, editor.ToDictionary().Encode());

            return(await AddAsync(null, torrent, saveDirectory, settings));
        }
Example #43
0
        public ObjectPath RegisterTorrent(string torrentPath, string savePath)
        {
            if (torrentPath == null)
                throw new ArgumentNullException ("torrent");
            if (savePath == null)
                throw new ArgumentNullException ("savePath");

            // Get the TorrentAdapter object
            ObjectPath torrent = LoadTorrent (torrentPath);

            // See if there is already a downloader for the torrent
            foreach (TorrentManagerAdapter m in downloaders.Values)
                if (m.Torrent == torrent)
                    return m.Path;

            // If there is no existing downloader, create a downloader
            TorrentSettings settings = new TorrentSettings ();
            TorrentManager manager = new TorrentManager (torrents[torrent].Torrent, savePath, settings);

            return Load (torrents[torrent], settings, manager);
        }
Example #44
0
 public TorrentWrapper(Torrent torrent, string savePath, TorrentSettings settings)
     : base(torrent, savePath, settings)
 {
     Name = torrent.Name;
     Size = torrent.Size;
     IsMagnet = false;
     Path = savePath;
 }
Example #45
0
 public async Task <TorrentManager> AddStreamingAsync(MagnetLink magnetLink, string saveDirectory, TorrentSettings settings)
 => await MakeStreamingAsync(await AddAsync(magnetLink, saveDirectory, settings));
Example #46
0
 public async Task <TorrentManager> AddStreamingAsync(string metadataPath, string saveDirectory, TorrentSettings settings)
 => await MakeStreamingAsync(await AddAsync(metadataPath, saveDirectory, settings));
Example #47
0
 public async Task <TorrentManager> AddStreamingAsync(Torrent torrent, string saveDirectory, TorrentSettings settings)
 => await MakeStreamingAsync(await AddAsync(torrent, saveDirectory, settings));
Example #48
0
 public async Task <TorrentManager> AddStreamingAsync(string metadataPath, string saveDirectory, TorrentSettings settings)
 => await AddStreamingAsync(null, await Torrent.LoadAsync(metadataPath), saveDirectory, settings);
        private void DownloaderWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                if (e.Argument == null)
                    return;

                basePath = Environment.CurrentDirectory;
                dhtNodeFile = System.IO.Path.Combine(basePath, "DhtNodes");
                downloadsPath = System.IO.Path.Combine(basePath, "Downloads");
                torrentsPath = System.IO.Path.Combine(basePath, "Torrents");
                fastResumeFile = System.IO.Path.Combine(torrentsPath, "fastresume.data");
                torrents = new List<TorrentManager>();     // The list where all the torrentManagers will be stored that the engine gives us
                listener = new Top10Listener(10);

                string torrentpath = e.Argument.ToString();

                int port = 6969;
                Torrent torrent = null;

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

                // Load the .torrent from the file into a Torrent instance
                // You can use this to do preprocessing should you need to
                torrent = Torrent.Load(torrentpath);

                // 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);

                // Every time a piece is hashed, this is fired.
                manager.PieceHashed += delegate (object o, PieceHashedEventArgs ec)
                {
                    lock (listener)
                        listener.WriteLine(string.Format("Piece Hashed: {0} - {1}", ec.PieceIndex, ec.HashPassed ? "Pass" : "Fail"));
                };

                // Every time the state changes (Stopped -> Seeding -> Downloading -> Hashing) this is fired
                manager.TorrentStateChanged += delegate (object o, TorrentStateChangedEventArgs ev)
                {
                    lock (listener)
                        listener.WriteLine("OldState: " + ev.OldState.ToString() + " NewState: " + ev.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.
                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);
                    downloadspeed = (engine.TotalDownloadSpeed / 1024.0).ToString();
                    //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);

                    //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);
                    //progress = manager.Progress.ToString();
                    //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);
                    //}
                    DownloaderWorker.ReportProgress(Convert.ToInt32(manager.Progress), manager.State.ToString());
                    System.Threading.Thread.Sleep(500);
                }
            }
            catch (Exception ex)
            {

            }
        }
Example #50
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)) { }
            port = 4545;

            // 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()) {
                            //CovertChannel.CovertChannel.targetPeerId = ;
                            //CovertChannel.CovertPicker picker = new CovertChannel.CovertPicker (null);
                            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);
            }
        }
 public GuiTorrentSettings(TorrentSettings settings)
 {
     if (settings == null)
         throw new ArgumentNullException("settings");
     this.settings = settings;
 }
Example #52
0
 public Task <TorrentManager> AddStreamingAsync(MagnetLink magnetLink, string saveDirectory, TorrentSettings settings)
 => AddStreamingAsync(magnetLink, null, saveDirectory, settings);
Example #53
0
 private static void StartDownload(ClientEngine clientEngine, 
     TorrentSettings torrentDefaults)
 {
     throw new NotImplementedException();
 }
Example #54
0
        async Task <TorrentManager> AddStreamingAsync(MagnetLink magnetLink, Torrent torrent, string saveDirectory, TorrentSettings settings)
        {
            var manager = await AddAsync(magnetLink, torrent, saveDirectory, settings);

            await manager.ChangePickerAsync(new StreamingPieceRequester());

            return(manager);
        }
        private void RunTorrents()
        {
            TorrentOptions tOpts = UserSettings.Current.TorrentOptions;
            if (globalEngine == null)
            {
                int listenPort = tOpts.ListeningPort;
                string mainDownloadsPath = UserSettings.ContentDataPath;

                // 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
                var engineSettings = new EngineSettings(mainDownloadsPath, listenPort);
                engineSettings.PreferEncryption = true;
                engineSettings.AllowedEncryption = EncryptionTypes.All;
                engineSettings.GlobalMaxConnections = tOpts.MaxDLConnsNormalized;
                engineSettings.GlobalMaxDownloadSpeed = tOpts.MaxDLSpeed*1024;
                engineSettings.GlobalMaxHalfOpenConnections = 10;
                engineSettings.GlobalMaxUploadSpeed = tOpts.MaxULSpeed*1024;

                // Create an instance of the engine.
                globalEngine = new ClientEngine(engineSettings);
                globalEngine.ChangeListenEndpoint(new IPEndPoint(IPAddress.Any, listenPort));
                engineListenPort = listenPort;

                EngineStartedOnPort(engineListenPort);

                //create a DHT engine and register it with the main engine
                {
                    var dhtListener = new DhtListener(new IPEndPoint(IPAddress.Any, listenPort));
                    var dhtEngine = new DhtEngine(dhtListener);
                    dhtListener.Start();

                    string dhtNodesFileName = "";
                    byte[] dhtNodesData = null;
                    try
                    {
                        dhtNodesFileName = GetDhtNodesFileName();
                        if (File.Exists(dhtNodesFileName))
                            dhtNodesData = File.ReadAllBytes(dhtNodesFileName);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error loading dht nodes file '{0}', reason: {1}", dhtNodesFileName, ex.Message);
                        dhtNodesData = null;
                    }

                    dhtEngine.Start(dhtNodesData);
                    globalEngine.RegisterDht(dhtEngine);

                    // We need to cleanup correctly when the user closes the window by using ctrl-c
                    // or an unhandled exception happens
                    Console.CancelKeyPress += delegate { EngineShutdown(); };
                    AppDomain.CurrentDomain.ProcessExit += delegate { EngineShutdown(); };
                    AppDomain.CurrentDomain.UnhandledException += delegate(object sender, UnhandledExceptionEventArgs e)
                    {
                        Console.WriteLine(e.ExceptionObject);
                        EngineShutdown();
                    };
                    Thread.GetDomain().UnhandledException += delegate(object sender, UnhandledExceptionEventArgs e)
                    {
                        Console.WriteLine(e.ExceptionObject);
                        EngineShutdown();
                    };
                }
            }
            else
                StopAllTorrents();

            // Create the default settings which a torrent will have.
            var torrentDefaults = new TorrentSettings(tOpts.NumULSlotsNormalized);
            torrentDefaults.UseDht = true;
            torrentDefaults.EnablePeerExchange = true;

            // For each file in the torrents path that is a .torrent file, load it into the engine.
            var managers = new List<TorrentManager>();
            foreach (AddOnTorrent newAddOn in addOnTorrents)
            {
                Torrent torrent = null;
                try
                {
                    torrent = Torrent.Load(File.ReadAllBytes(newAddOn.torrentFileName));
                }
                catch (Exception ex)
                {
                    updater.Status = "Error loading torrent file";
                    downloader.Status = ex.Message;
                    downloader.IsRunning = false;
                    return;
                }

                try
                {
                    var fullFilePaths = new List<String>();
                    {
                        TorrentFile[] torrentFiles = torrent.Files;
                        foreach (TorrentFile theFile in torrentFiles)
                            fullFilePaths.Add(Path.Combine(newAddOn.torrentSavePath, theFile.Path));
                    }
                    if (Directory.Exists(newAddOn.torrentSavePath))
                    {
                        string[] actualFilePaths = Directory.GetFiles(newAddOn.torrentSavePath, "*.*", SearchOption.AllDirectories);
                        foreach (string realPath in actualFilePaths)
                        {
                            var fileInfo = new FileInfo(realPath);
                            if (
                                fullFilePaths.Count(
                                    path => { return path.Equals(fileInfo.FullName, StringComparison.InvariantCultureIgnoreCase); }) < 1)
                            {
                                //this is an unwanted file
                                if (fileInfo.IsReadOnly)
                                {
                                    fileInfo.IsReadOnly = false;
                                    fileInfo.Refresh();
                                }
                                fileInfo.Delete();
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    updater.Status = "Error deleting unwanted file";
                    downloader.Status = ex.Message;
                    downloader.IsRunning = false;
                    return;
                }

                TorrentManager tm = null;
                try
                {
                    tm = new TorrentManager(torrent, globalEngine.Settings.SavePath, torrentDefaults, newAddOn.torrentSavePath);
                    if (!fullSystemCheck && !UserSettings.Current.TorrentOptions.DisableFastResume)
                        //load the fast resume file for this torrent
                    {
                        string fastResumeFilepath = GetFastResumeFileName(tm);
                        if (File.Exists(fastResumeFilepath))
                        {
                            var bencoded = BEncodedValue.Decode<BEncodedDictionary>(File.ReadAllBytes(fastResumeFilepath));
                            tm.LoadFastResume(new FastResume(bencoded));
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (tm == null) //only if critical failure
                    {
                        updater.Status = "Error creating torrent manager";
                        downloader.Status = ex.Message;
                        downloader.IsRunning = false;
                        return;
                    }
                }

                managers.Add(tm);
            }

            // If we loaded no torrents, just stop.
            if (managers.Count < 1)
            {
                updater.Status = "Torrent engine error";
                downloader.Status = "No torrents have been found";
                downloader.IsRunning = false;
                return;
            }

            try
            {
                File.WriteAllText(UserSettings.ContentCurrentTagFile, versionString);
                CalculatedGameSettings.Current.Update();
            }
            catch (Exception ex)
            {
                updater.Status = "Tag file write error";
                downloader.Status = ex.Message;
                downloader.IsRunning = false;
                return;
            }

            // Before starting all the managers, clear out the fastresume data
            // The torrents currently running already have it loaded, and will save it out on stop/finish
            // So this only clears out fastresume for torrents we aren't currently running, which is what we want
            IEnumerable<string> staleFastResume = Directory.EnumerateFiles(UserSettings.TorrentJunkPath, "fastresume_*.benc",
                SearchOption.TopDirectoryOnly);
            foreach (string sfr in staleFastResume)
            {
                try
                {
                    File.Delete(sfr);
                }
                catch (Exception)
                {
                }
            }

            foreach (TorrentManager manager in managers)
            {
                // Add this manager to the global torrent engine
                globalEngine.Register(manager);

                // Every time a new peer is added, this is fired.
                manager.PeersFound += delegate { };
                // Every time a piece is hashed, this is fired.
                manager.PieceHashed += delegate { };
                // Every time the state changes (Stopped -> Seeding -> Downloading -> Hashing) this is fired
                manager.TorrentStateChanged += OnTorrentStateChanged;
                // Every time the tracker's state changes, this is fired
                foreach (TrackerTier tier in manager.TrackerManager)
                {
                }

                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;
            var sb = new StringBuilder(1024);
            DateTime lastAnnounce = DateTime.Now;
            bool firstRun = true;
            while (running && globalEngine != null)
            {
                IList<TorrentManager> engineTorrents = globalEngine.Torrents;
                if (firstRun || lastAnnounce < DateTime.Now.AddMinutes(-1))
                {
                    foreach (TorrentManager tm in engineTorrents)
                        tm.TrackerManager.Announce();

                    lastAnnounce = DateTime.Now;
                    firstRun = false;
                }

                if ((i++)%2 == 0)
                {
                    sb.Remove(0, sb.Length);
                    running = engineTorrents.Count(m => { return m.State != TorrentState.Stopped; }) > 0;

                    var totalState = TorrentState.Stopped;
                    if (engineTorrents.Count(m => m.State == TorrentState.Hashing) > 0)
                        totalState = TorrentState.Hashing;
                    else if (engineTorrents.Count(m => m.State == TorrentState.Downloading) > 0)
                        totalState = TorrentState.Downloading;
                    else if (engineTorrents.Count(m => m.State == TorrentState.Seeding) > 0)
                        totalState = TorrentState.Seeding;

                    string status = "";
                    try
                    {
                        switch (totalState)
                        {
                            case TorrentState.Hashing:
                            {
                                double totalHashingBytes = 0;
                                double totalHashedBytes = 0;
                                foreach (TorrentManager m in engineTorrents)
                                {
                                    totalHashingBytes += m.Torrent.Size;
                                    if (m.State == TorrentState.Hashing)
                                        totalHashedBytes += m.Torrent.Size*(m.Progress/100);
                                    else
                                        totalHashedBytes += m.Torrent.Size;
                                }
                                double totalHashProgress = totalHashedBytes/totalHashingBytes;
                                status = String.Format("Checking files ({0:0.00}%)", totalHashProgress*100);

                                StatusCallbacks(TorrentState.Hashing, totalHashProgress);
                            }
                                break;
                            case TorrentState.Downloading:
                            {
                                double totalToDownload = 0;
                                double totalDownloaded = 0;
                                double totalDownloadSpeed = 0;
                                double totalUploadSpeed = 0;
                                int totalDownloadConns = 0;
                                int totalUploadConns = 0;
                                foreach (TorrentManager m in engineTorrents)
                                {
                                    totalToDownload += m.Torrent.Size;
                                    totalDownloaded += m.Torrent.Size*(m.Progress/100);
                                    totalDownloadSpeed += m.Monitor.DownloadSpeed;
                                    totalUploadSpeed += m.Monitor.UploadSpeed;
                                    totalDownloadConns += m.OpenConnections;
                                    totalUploadConns += m.UploadingTo;
                                }
                                double totalDownloadProgress = totalDownloaded/totalToDownload;
                                status = "Status: " +
                                         ((engineTorrents.Count(m => m.State == TorrentState.Downloading && m.GetPeers().Count > 0) > 0)
                                             ? "Downloading"
                                             : "Finding peers");
                                status += "\n" + String.Format("Progress: {0:0.00}%", totalDownloadProgress*100);
                                status += "\n" + String.Format("Download({1}): {0:0.00} KiB/s", totalDownloadSpeed/1024.0, totalDownloadConns);
                                status += "\n" + String.Format("Upload({1}): {0:0.00} KiB/s", totalUploadSpeed/1024.0, totalUploadConns);

                                StatusCallbacks(TorrentState.Downloading, totalDownloadProgress);
                            }
                                break;
                            case TorrentState.Seeding:
                            {
                                double totalUploadSpeed = 0;
                                int totalUploadPeers = 0;
                                foreach (TorrentManager tm in engineTorrents)
                                {
                                    totalUploadSpeed += tm.Monitor.UploadSpeed;
                                    totalUploadPeers += tm.UploadingTo;
                                }
                                status = String.Format("Seeding({1}): {0:0.00} KiB/s", totalUploadSpeed/1024.0, totalUploadPeers);
                                StatusCallbacks(TorrentState.Seeding, 1);

                                if (UserSettings.Current.TorrentOptions.StopSeeding)
                                    globalEngine.StopAll();
                            }
                                break;
                            default:
                                status = totalState.ToString();
                                break;
                        }
                    }
                    catch (Exception ex)
                    {
                        status = ex.Message;
                    }

                    if (downloader != null)
                        downloader.Status = status;
                }

                Thread.Sleep(50);
            }
        }