Example #1
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);
        }
		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 #3
0
        public void Initialize(SettingsManager settingsManager)
        {
            SettingsManager = settingsManager;
            Torrents = new ObservableCollection<PeriodicTorrent>();
            Torrents.CollectionChanged += Torrents_CollectionChanged;

            var port = SettingsManager.IncomingPort;
            if (SettingsManager.UseRandomPort)
                port = new Random().Next(1, 65536);
            var settings = new EngineSettings(SettingsManager.DefaultDownloadLocation, port);

            settings.PreferEncryption = SettingsManager.EncryptionSettings != EncryptionTypes.PlainText; // Always prefer encryption unless it's disabled
            settings.AllowedEncryption = SettingsManager.EncryptionSettings;
            Client = new ClientEngine(settings);
            Client.ChangeListenEndpoint(new IPEndPoint(IPAddress.Any, port));
            if (SettingsManager.EnableDHT)
            {
                var listener = new DhtListener(new IPEndPoint(IPAddress.Any, port));
                var dht = new DhtEngine(listener);
                Client.RegisterDht(dht);
                listener.Start();
                if (File.Exists(SettingsManager.DhtCachePath))
                    dht.Start(File.ReadAllBytes(SettingsManager.DhtCachePath));
                else
                    dht.Start();
            }
            SettingsManager.PropertyChanged += SettingsManager_PropertyChanged;
        }
		public TorrentServer(string downloadsPath, int listenPort)
		{
			this.downloadsPath = downloadsPath;
			var engineSettings = new EngineSettings(downloadsPath, listenPort);
			engine = new ClientEngine(engineSettings);

		}
 internal ListenManager(ClientEngine engine)
 {
     Engine = engine;
     Listeners = new MonoTorrentCollection<PeerListener>();
     endCheckEncryptionCallback = ClientEngine.MainLoop.Wrap(EndCheckEncryption);
     handshakeReceivedCallback = (a, b, c) => ClientEngine.MainLoop.Queue(() => onPeerHandshakeReceived(a, b, c));
 }
		public void Init()
		{
			//get general settings in file
			GuiGeneralSettings genSettings = settingsBase.LoadSettings<GuiGeneralSettings>("General Settings");
			clientEngine = new ClientEngine(genSettings.GetEngineSettings());

			// Create Torrents path
			if (!Directory.Exists(genSettings.TorrentsPath))
				Directory.CreateDirectory(genSettings.TorrentsPath);

            // Add torrents from startup paramters to torrents folder
            foreach (string file in Global.TorrentFiles)
            {
                if (File.Exists(file) && file.EndsWith(".torrent"))
                {
					// FIXME: This isn't cross platform. Use the "Path" class to do this
                    string newFile = genSettings.TorrentsPath + file.Substring(file.LastIndexOf("\\"));
                    if (!File.Exists(newFile))
                        File.Copy(file, newFile);
                }
            }

			//load all torrents in torrents folder
			foreach (string file in Directory.GetFiles(genSettings.TorrentsPath, "*.torrent"))
			{
				GuiTorrentSettings torrentSettings = settingsBase.LoadSettings<GuiTorrentSettings>("Torrent Settings for " + file);
				Add(file, torrentSettings.GetTorrentSettings(),	
                    string.IsNullOrEmpty(torrentSettings.SavePath) ? clientEngine.Settings.SavePath : torrentSettings.SavePath);
			}

			//subscribe to event for update
			clientEngine.StatsUpdate += OnUpdateStats;
		}
Example #7
0
        public EngineAdapter(string name, EngineSettingsAdapter settings, ObjectPath path)
        {
            this.name = name;
            this.engine = new ClientEngine(settings.Settings);
            this.engineSettings = settings;
            this.path = path;

             	   DownloaderPath = path.ToString () + "/downloaders/{0}";
            StoragePath = Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData);

            StoragePath = System.IO.Path.Combine (StoragePath, "monotorrent-dbus");
            EnsurePath (StoragePath);

            StoragePath = System.IO.Path.Combine (StoragePath, string.Format ("engine-{0}", name));
            EnsurePath (StoragePath);

            downloaders = new Dictionary<ObjectPath, TorrentManagerAdapter> (new ObjectPathComparer());
            torrents = new Dictionary<ObjectPath,TorrentAdapter> ();

            engine.StatsUpdate += delegate {
                StatsUpdateHandler h = StatsUpdate;
                if (h != null)
                    h ();
            };
            LoadState ();
        }
        public CriticalExceptionEventArgs(Exception ex, ClientEngine engine)
        {
            if (ex == null)
                throw new ArgumentNullException("ex");
            if (engine == null)
                throw new ArgumentNullException("engine");

            this.engine = engine;
            this.ex = ex;
        }
        public TorrentService(ILogger <TorrentService> logger, IServiceScopeFactory scopeFactory)
        {
            _logger = logger;

            _httpClient = new HttpClient();
            _scope      = scopeFactory;

            _engine = new MonoTorrent.Client.ClientEngine();
            _timer  = new Timer(_TimerCallback, null, TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(30));
        }
 public EngineTestRig(string savePath, int piecelength, PieceWriter writer)
 {
     if (writer == null)
         writer = new MemoryWriter(new NullWriter());
     Listener = new CustomListener();
     Engine = new ClientEngine(new EngineSettings(), Listener, writer);
     TorrentDict = CreateTorrent(piecelength);
     Torrent = Torrent.Load(TorrentDict);
     Manager = new TorrentManager(Torrent, savePath, new TorrentSettings());
     Engine.Register(Manager);
     //manager.Start();
 }
Example #11
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);
        }
Example #12
0
 public EpisodeManager(List<TvShowTile> SubbscribedShows)
 {
     _subbedShows = new List<TvShow>();
     SubbscribedShows.ForEach((s) => _subbedShows.Add(s.TvShow));
     _timerCheckForNewEpisode = new Timer();
     //_timerCheckForNewEpisode.AutoReset = true;
     _timerCheckForNewEpisode.Elapsed += _timerCheckForNewEpisode_Elapsed;
     _timerCheckForNewEpisode.Interval = 1000; // TODO: Change to 1 second
     _repo = TvShowRepo.Repo;
     _engine = new ClientEngine(new EngineSettings());
     _client = new TorrentClient();
     //_strikeClient = new Strike();
     _timerCheckForNewEpisode.Start();
 }
Example #13
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 #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
        /// <summary>
        /// 
        /// </summary>
        /// <param name="settings"></param>
        public ConnectionManager(ClientEngine engine)
        {
            this.engine = engine;

            this.endCheckEncryptionCallback = delegate(IAsyncResult result) { ClientEngine.MainLoop.Queue(delegate { EndCheckEncryption(result); }); };
            this.endSendMessageCallback = delegate(bool s, int c, object o) { ClientEngine.MainLoop.Queue(delegate { EndSendMessage(s, c, o); }); };
            this.endCreateConnectionCallback = delegate(bool succeeded, object state) { ClientEngine.MainLoop.Queue(delegate { EndCreateConnection(succeeded, state); }); };
            this.incomingConnectionAcceptedCallback = delegate(bool s, int c, object o) { ClientEngine.MainLoop.Queue(delegate { IncomingConnectionAccepted(s, c, o); }); };

            this.bitfieldSentCallback = new MessagingCallback(PeerBitfieldSent);
            this.handshakeSentCallback = new MessagingCallback(this.PeerHandshakeSent);
            this.handshakeReceievedCallback = delegate(bool s, int c, object o) { ClientEngine.MainLoop.Queue(delegate { PeerHandshakeReceived(s, c, o); }); };
            this.messageSentCallback = new MessagingCallback(this.PeerMessageSent);

            this.torrents = new MonoTorrentCollection<TorrentManager>();
        }
        /// <summary>
        /// </summary>
        /// <param name="settings"></param>
        public ConnectionManager(ClientEngine engine)
        {
            this.engine = engine;

            endCheckEncryptionCallback = ClientEngine.MainLoop.Wrap(EndCheckEncryption);
            endSendMessageCallback = (a, b, c) => ClientEngine.MainLoop.Queue(() => EndSendMessage(a, b, c));
            endCreateConnectionCallback = (a, b, c) => ClientEngine.MainLoop.Queue(() => EndCreateConnection(a, b, c));
            incomingConnectionAcceptedCallback =
                (a, b, c) => ClientEngine.MainLoop.Queue(() => IncomingConnectionAccepted(a, b, c));

            handshakeSentCallback = PeerHandshakeSent;
            peerHandshakeReceivedCallback = (a, b, c) => ClientEngine.MainLoop.Queue(() => PeerHandshakeReceived(a, b, c));
            messageSentCallback = PeerMessageSent;
            messageReceivedCallback = (a, b, c) => ClientEngine.MainLoop.Queue(() => MessageReceived(a, b, c));

            pendingConnects = new List<AsyncConnectState>();
        }
Example #17
0
        public void Initialize()
        {
            Torrents = new ObservableCollection<PeriodicTorrent>();

            // TODO: Customize most of these settings
            var settings = new EngineSettings(Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Downloads"), 22239);
            settings.PreferEncryption = true;
            settings.AllowedEncryption = EncryptionTypes.RC4Full | EncryptionTypes.RC4Header;
            Client = new ClientEngine(settings);
            Client.ChangeListenEndpoint(new IPEndPoint(IPAddress.Any, 22239));
            var listener = new DhtListener(new IPEndPoint(IPAddress.Any, 22239));
            var dht = new DhtEngine(listener);
            Client.RegisterDht(dht);
            listener.Start();
            if (File.Exists(SettingsManager.DhtCachePath))
                dht.Start(File.ReadAllBytes(SettingsManager.DhtCachePath));
            else
                dht.Start();
        }
Example #18
0
        void SetupEngine()
        {
            EngineSettings settings = new EngineSettings();
            settings.AllowedEncryption = ChooseEncryption();

            // If both encrypted and unencrypted connections are supported, an encrypted connection will be attempted
            // first if this is true. Otherwise an unencrypted connection will be attempted first.
            settings.PreferEncryption = true;

            // Torrents will be downloaded here by default when they are registered with the engine
            settings.SavePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "Torrents");

            // The maximum upload speed is 200 kilobytes per second, or 204,800 bytes per second
            settings.GlobalMaxUploadSpeed = 200 * 1024;

            engine = new ClientEngine(settings);

            // Tell the engine to listen at port 6969 for incoming connections
            engine.ChangeListenEndpoint(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 6969));
        }
 public static void TestDownloadFile(string db, string torrentPath, string savePath)
 {
     //System.Diagnostics.Debugger.Launch();
     var dbs = new ChunkDbService(db, false);
     var ds = new DeduplicationService(dbs);
     var writer = new DedupDiskWriter(ds);
     var engineSettings = new EngineSettings();
     engineSettings.PreferEncryption = false;
     engineSettings.AllowedEncryption = EncryptionTypes.All;
     int port = 33123;
     var ip = NetUtil.GetLocalIPByInterface("Local Area Connection");
     engineSettings.ReportedAddress = new IPEndPoint(ip, port);
     var engine = new ClientEngine(engineSettings, new DedupDiskWriter(ds));
     var vd = new VirtualDiskDownloadService(engine, new FileInfoTable<TorrentManager>());
     var torrent = Torrent.Load(torrentPath);
     logger.DebugFormat("Loaded torrent file: {0}, piece length: {1}.",
         torrent.Name, torrent.PieceLength);
     var filePath = Path.Combine(savePath, torrent.Name);
     vd.StartDownloadingFile(torrent, savePath, dbs.GetManagedFile(filePath).ChunkMap.LastPieceInProfile);
     Console.Read();
 }
        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
        }
Example #21
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();
        }
Example #22
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();
        }
        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);
            }
        }
Example #24
0
 public LocalPeerListener(ClientEngine engine)
     : base(new IPEndPoint(IPAddress.Any, 6771))
 {
     this.engine = engine;
 }
Example #25
0
        private TestRig(string savePath, int piecelength, TestWriter writer, string[][] trackers, TorrentFile[] files,
            bool metadataMode)
        {
            this.files = files;
            this.savePath = savePath;
            this.piecelength = piecelength;
            tier = trackers;
            MetadataMode = metadataMode;
            MetadataPath = "metadataSave.torrent";
            Listener = new CustomListener();
            Engine = new ClientEngine(new EngineSettings(), Listener, writer);
            Writer = writer;

            RecreateManager();
        }
Example #26
0
        internal DiskManager(ClientEngine engine, PieceWriter writer)
        {
            this.bufferedReads = new Queue<BufferedIO>();
            this.bufferedWrites = new Queue<BufferedIO>();
            this.cache = new Cache<BufferedIO>(true).Synchronize ();
            this.engine = engine;
            this.readLimiter = new RateLimiter();
            this.readMonitor = new SpeedMonitor();
            this.writeMonitor = new SpeedMonitor();
            this.writeLimiter = new RateLimiter();
            this.writer = writer;

            LoopTask = delegate {
                if (disposed)
                    return;

                while (this.bufferedWrites.Count > 0 && writeLimiter.TryProcess(bufferedWrites.Peek ().buffer.Length / 2048))
                {
                    BufferedIO write;
                    lock (bufferLock)
                        write = this.bufferedWrites.Dequeue();
                    try
                    {
                        PerformWrite(write);
                        cache.Enqueue (write);
                    }
                    catch (Exception ex)
                    {
                        if (write.Manager != null)
                            SetError(write.Manager, Reason.WriteFailure, ex);
                    }
                }

                while (this.bufferedReads.Count > 0 && readLimiter.TryProcess(bufferedReads.Peek().Count / 2048))
                {
                    BufferedIO read;
                    lock(bufferLock)
                        read = this.bufferedReads.Dequeue();

                    try
                    {
                        PerformRead(read);
                        cache.Enqueue (read);
                    }
                    catch (Exception ex)
                    {
                        if(read.Manager != null)
                            SetError(read.Manager, Reason.ReadFailure, ex);
                    }
                }
            };

            IOLoop.QueueTimeout(TimeSpan.FromSeconds(1), delegate {
                if (disposed)
                    return false;

                readMonitor.Tick();
                writeMonitor.Tick();
                LoopTask();
                return true;
            });
        }
 public LocalPeerListener(ClientEngine engine)
     : base(new IPEndPoint(IPAddress.Any, 6771))
 {
     this.engine = engine;
 }
Example #28
0
        /// <summary>
        ///
        /// </summary>
        public ConnectionManager(ClientEngine engine)
        {
            this.engine = engine;

            PendingConnects = new List <AsyncConnectState>();
        }
 public VirtualDiskDownloadService(ClientEngine torrentClientEngine, 
     FileInfoTable<TorrentManager> torrentManagerTable)
 {
     _clientEngine = torrentClientEngine;
     _torrentManagerTable = torrentManagerTable;
 }
Example #30
0
        internal DiskManager(ClientEngine engine, PieceWriter writer)
        {
            this.bufferedReads  = new Queue <BufferedIO>();
            this.bufferedWrites = new Queue <BufferedIO>();
            this.cache          = new Cache <BufferedIO>(true).Synchronize();
            this.engine         = engine;
            this.readLimiter    = new RateLimiter();
            this.readMonitor    = new SpeedMonitor();
            this.writeMonitor   = new SpeedMonitor();
            this.writeLimiter   = new RateLimiter();
            this.writer         = writer;

            LoopTask = delegate {
                if (disposed)
                {
                    return;
                }

                while (this.bufferedWrites.Count > 0 && writeLimiter.TryProcess(bufferedWrites.Peek().buffer.Length / 2048))
                {
                    BufferedIO write;
                    lock (bufferLock)
                        write = this.bufferedWrites.Dequeue();
                    try
                    {
                        PerformWrite(write);
                        cache.Enqueue(write);
                    }
                    catch (Exception ex)
                    {
                        logger.Error("Write error: {0}", ex.Message);
                        if (write.Manager != null)
                        {
                            SetError(write.Manager, Reason.WriteFailure, ex);
                        }
                    }
                }

                while (this.bufferedReads.Count > 0 && readLimiter.TryProcess(bufferedReads.Peek().Count / 2048))
                {
                    BufferedIO read;
                    lock (bufferLock)
                        read = this.bufferedReads.Dequeue();

                    try
                    {
                        PerformRead(read);
                        cache.Enqueue(read);
                    }
                    catch (Exception ex)
                    {
                        logger.Error("Read error: {0}", ex.Message);
                        if (read.Manager != null)
                        {
                            SetError(read.Manager, Reason.ReadFailure, ex);
                        }
                    }
                }
            };

            IOLoop.QueueTimeout(TimeSpan.FromSeconds(1), delegate {
                if (disposed)
                {
                    return(false);
                }

                readMonitor.Tick();
                writeMonitor.Tick();
                LoopTask();
                return(true);
            });
        }
Example #31
0
        private static void RegisterClientEngineEventHandlers(ClientEngine clientEngine)
        {
            clientEngine.CriticalException += delegate(object sender, CriticalExceptionEventArgs args) {
            Logger.WriteLineIf(LogLevel.Error, _log_props,
              string.Format("ClientEngine Critical Exception: {0}", args.Exception));
              };

              //cliengEngine.StatsUpdate += delegate(object sender, StatsUpdateEventArgs args) {
              //  Logger.WriteLineIf(LogLevel.Verbose, _log_props,
              //    string.Format("ClientEngine Stats Update"));
              //};

              clientEngine.TorrentRegistered += delegate(object sender, TorrentEventArgs args) {
            Logger.WriteLineIf(LogLevel.Verbose, _log_props,
              string.Format("ClientEngine Torrent Registered: {0}.", args.TorrentManager.Torrent.Name));
              };

              //cliengEngine.ConnectionManager.PeerMessageTransferred += delegate(object sender, PeerMessageEventArgs args) {
              //  Logger.WriteLineIf(LogLevel.Verbose, _log_props, string.Format(
              //    "ClientEngine Peer Message Transferred. Direction:{0}, Message: {1}.",
              //    args.Direction, args.Message));
              //};
        }
Example #32
0
 internal ListenManager(ClientEngine engine)
 {
     Engine    = engine ?? throw new ArgumentNullException(nameof(engine));
     Listeners = new List <IPeerListener>();
 }
        private static void EngineShutdown()
        {
            if (globalEngine != null)
            {
                StopAllTorrents(true);
                EngineStoppedOnPort(engineListenPort);
                engineListenPort = 0;

                string dhtNodesFileName = "";
                try
                {
                    dhtNodesFileName = GetDhtNodesFileName();
                    File.WriteAllBytes(dhtNodesFileName, globalEngine.DhtEngine.SaveNodes());
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error saving dht nodes file '{0}', reason: {1}", dhtNodesFileName, ex.Message);
                }

                globalEngine.Dispose();
                globalEngine = null;
            }

            foreach (TraceListener lst in Debug.Listeners)
            {
                lst.Flush();
                lst.Close();
            }
        }
Example #34
0
 internal ListenManager(ClientEngine engine)
 {
     Engine    = engine;
     listeners = new MonoTorrentCollection <PeerListener>();
 }
Example #35
0
 internal ListenManager(ClientEngine engine)
 {
     Engine   = engine ?? throw new ArgumentNullException(nameof(engine));
     Listener = new NullPeerListener();
     SKeys    = Array.Empty <InfoHash> ();
 }
 public CriticalExceptionEventArgs(Exception ex, ClientEngine engine)
 {
     Engine    = engine ?? throw new ArgumentNullException(nameof(engine));
     Exception = ex ?? throw new ArgumentNullException(nameof(ex));
 }
Example #37
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);
            }
        }
        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)
            {

            }
        }