public TorrentDownloader(
            Uri torrentDescriptionFileUri, TorrentSettings torrentSettings, ClientEngine clientEngine)
        {
            try
            {
                torrent      = MonoTorrent.Common.Torrent.Load(torrentDescriptionFileUri.LocalPath);
                this.Torrent = new TorrentFile(torrentDescriptionFileUri.LocalPath, torrent.Publisher);

                var config = Catalog.Factory.Resolve <IConfig>();
                defaultSaveFolder = config[BitTorrentSettings.DownloadFolder];

                var relativePath = torrent.Publisher;
                var absolutePath = Path.Combine(defaultSaveFolder, relativePath);
                var saveFolder   = Path.GetDirectoryName(absolutePath);
                if (saveFolder != null && !Directory.Exists(saveFolder))
                {
                    Directory.CreateDirectory(saveFolder);
                }

                manager = new TorrentManager(torrent, saveFolder, torrentSettings);

                State = TorrentState.Downloading;

                manager.TorrentStateChanged += ManagerOnTorrentStateChanged;

                engine = clientEngine;
                engine.Register(manager);
            }
            catch (Exception)
            {
                throw;
            }
        }
Esempio n. 2
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));
        }
Esempio n. 3
0
        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();
        }
        public TorrentManager(string magnetUrl, string downloadLocation)
        {
            var settings = new EngineSettings
            {
                SavePath   = downloadLocation,
                ListenPort = Port
            };

            var torrentDefaults = new TorrentSettings();
            var writer          = new DiskWriter();

            _dataAccessor = new MonotorrentDataAccessor(writer);
            _engine       = new ClientEngine(settings, writer);

            if (!Directory.Exists(downloadLocation))
            {
                Directory.CreateDirectory(downloadLocation);
            }

            var magnet = MagnetLink.Parse(magnetUrl);

            _manager              = new MonoTorrent.Client.TorrentManager(magnet, downloadLocation, torrentDefaults, downloadLocation);
            _manager.PieceHashed += async(sender, eventArgs) => await _matroskaPlayer.OnPieceHashed(sender, eventArgs);

            _manager.TorrentStateChanged += delegate(object sender, TorrentStateChangedEventArgs args) { Console.WriteLine(args.NewState); };
            _matroskaPlayer = new MatroskaPlayer(_manager, _dataAccessor);
            TorrentError   += OnError;
        }
Esempio n. 5
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 IEnumerable <TorrentManager> Load(TorrentSettings settings)
        {
            List <TorrentManager> managers = new List <TorrentManager>();

            if (File.Exists(pathToFolderApplicationData + "\\Torrents.dat"))
            {
                BinaryFormatter formatter = new BinaryFormatter();

                using (FileStream fs = new FileStream(pathToFolderApplicationData + "\\Torrents.dat", FileMode.OpenOrCreate))
                {
                    torrents = (List <ResumeTorrentInfo>)formatter.Deserialize(fs);
                }

                foreach (var torr in torrents)
                {
                    string pathWithName = pathToFolderApplicationData + "\\Torrents\\" + torr.FileName;
                    if (File.Exists(pathWithName))
                    {
                        Torrent        torrent = Torrent.Load(pathWithName);
                        TorrentManager manager = new TorrentManager(torrent, torr.SavePath, settings);
                        managers.Add(manager);
                    }
                }

                LoadFastResume(managers);
            }

            return(managers);
        }
            public void SetTorrentSettings_Test()
            {
                var torrentsInfo = _client.TorrentGet(TorrentFields.ALL_FIELDS);
                var torrentInfo  = torrentsInfo.Torrents.FirstOrDefault(t => t.Name.Contains("ubuntu"));

                Assert.IsNotNull(torrentInfo, "Torrent not found");

                var trackerInfo = torrentInfo.Trackers.FirstOrDefault();

                Assert.IsNotNull(trackerInfo, "Tracker not found");
                var             trackerCount = torrentInfo.Trackers.Length;
                TorrentSettings settings     = new TorrentSettings()
                {
                    IDs           = new object[] { torrentInfo.HashString },
                    TrackerRemove = new[] { trackerInfo.ID }
                };

                _client.TorrentSet(settings);

                torrentsInfo = _client.TorrentGet(TorrentFields.ALL_FIELDS, torrentInfo.ID);
                torrentInfo  = torrentsInfo.Torrents.FirstOrDefault();

                Assert.IsFalse(torrentInfo == null);
                Assert.IsFalse(trackerCount == torrentInfo.Trackers.Length);
            }
Esempio n. 8
0
        public async Task SetTorrentSettings_Test()
        {
            var torrentsInfo = await client.TorrentGetAsync(TorrentFields.ALL_FIELDS);

            var torrentInfo = torrentsInfo.TorrentList.FirstOrDefault();

            Assert.IsNotNull(torrentInfo, "Torrent not found");

            var trackerInfo = torrentInfo.Trackers.FirstOrDefault();

            Assert.IsNotNull(trackerInfo, "Tracker not found");
            var             trackerCount = torrentInfo.Trackers.Length;
            TorrentSettings settings     = new TorrentSettings()
            {
                IDs           = new int[] { torrentInfo.ID },
                TrackerRemove = new int[] { trackerInfo.ID }
            };

            client.TorrentSetAsync(settings);

            torrentsInfo = await client.TorrentGetAsync(TorrentFields.ALL_FIELDS, torrentInfo.ID);

            torrentInfo = torrentsInfo.TorrentList.FirstOrDefault();

            Assert.IsFalse(trackerCount == torrentInfo.Trackers.Length);
        }
Esempio n. 9
0
        public async void Save()
        {
            try
            {
                var sett = new TorrentSettings
                {
                    DownloadLimited = MXD_Bool,
                    UploadLimited   = MXU_Bool,
                    DownloadLimit   = MaxDownSp,
                    UploadLimit     = MaxUpSp,
                    SeedRatioLimit  = SeedRation,
                    SeedIdleLimit   = StopSeed,
                    IDs             = tors,
                    PeerLimit       = PeerLimit,
                    TrackerAdd      = toAdd?.Count <= 0 ? null : toAdd?.ToArray(),
                    TrackerRemove   = toRm?.Count <= 0 ? null : toRm?.ToArray(),
                };

                var resp = await _transmissionClient.TorrentSetAsync(sett, new CancellationToken());

                if (resp.Success)
                {
                    await TryCloseAsync();
                }
                else
                {
                    await MessageBoxViewModel.ShowDialog(LocalizationProvider.GetLocalizedValue(nameof(Resources.Strings.TorretPropertiesSetError)), _manager);
                }
            }
            finally
            {
                IsBusy = Visibility.Collapsed;
            }
        }
Esempio n. 10
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);
        }
		public void Restore()
		{
			GconfSettingsStorage gconf = new GconfSettingsStorage();
			
			try {
				uploadSlots = (int) gconf.Retrieve(SETTINGS_PATH + "UploadSlots");
			} catch(SettingNotFoundException) {
				uploadSlots = TorrentSettings.DefaultSettings().UploadSlots;
			}
			
			try {
				maxConnections = (int) gconf.Retrieve(SETTINGS_PATH + "MaxConnections");
			} catch(SettingNotFoundException) {
				maxConnections = TorrentSettings.DefaultSettings().MaxConnections;
			}
			
			try{
				maxDownloadSpeed = (int) gconf.Retrieve(SETTINGS_PATH + "MaxDownloadSpeed");
			} catch(SettingNotFoundException){
				maxDownloadSpeed = TorrentSettings.DefaultSettings().MaxDownloadSpeed;
			}
			
			try {
				maxUploadSpeed = (int) gconf.Retrieve(SETTINGS_PATH + "MaxUploadSpeed");
			} catch(SettingNotFoundException){
				maxUploadSpeed = TorrentSettings.DefaultSettings().MaxUploadSpeed;
			}
			
			try{
				fastResumeEnabled = (bool) gconf.Retrieve(SETTINGS_PATH + "FastResumeEnabled");
			} catch(SettingNotFoundException){
				fastResumeEnabled = TorrentSettings.DefaultSettings().FastResumeEnabled;
			}
			
		}
Esempio n. 12
0
        public void SetTorrentSettings_Test()
        {
            var torrentsInfo = client.GetTorrents(TorrentFields.ALL_FIELDS);
            var torrentInfo  = torrentsInfo.Torrents.FirstOrDefault();

            Assert.IsNotNull(torrentInfo, "Torrent not found");

            var trackerInfo = torrentInfo.Trackers.FirstOrDefault();

            Assert.IsNotNull(trackerInfo, "Tracker not found");

            TorrentSettings settings = new TorrentSettings()
            {
                IDs           = new int[] { torrentInfo.ID },
                TrackerRemove = new int[] { trackerInfo.ID }
            };

            client.SetTorrents(settings);

            torrentsInfo = client.GetTorrents(TorrentFields.ALL_FIELDS, torrentInfo.ID);
            torrentInfo  = torrentsInfo.Torrents.FirstOrDefault();

            trackerInfo = torrentInfo.Trackers.FirstOrDefault(t => t.ID == trackerInfo.ID);
            Assert.IsNull(trackerInfo);
        }
Esempio n. 13
0
        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--;
                    }
                }
            };
        }
        /// <summary>
        /// Set torrent params (API: torrent-set)
        /// </summary>
        /// <param name="settings">New torrent params</param>
        public async Task <bool> TorrentSetAsync(TorrentSettings settings)
        {
            var request = new TransmissionRequest("torrent-set", settings.ToDictionary());

            TransmissionResponse response = await SendRequestAsync(request);

            return(response.Result.Equals("success", StringComparison.OrdinalIgnoreCase));
        }
Esempio n. 15
0
 public TorrentWrapper(Torrent torrent, string savePath, TorrentSettings settings)
     : base(torrent, savePath, settings)
 {
     Name     = torrent.Name;
     Size     = torrent.Size;
     IsMagnet = false;
     Path     = savePath;
 }
Esempio n. 16
0
 public GuiTorrentSettings(TorrentSettings settings)
 {
     if (settings == null)
     {
         throw new ArgumentNullException("settings");
     }
     this.settings = settings;
 }
Esempio n. 17
0
        static SettingsManager()
        {
            RegisterAll();

            DefaultTorrentSettings = new TorrentSettings();
            EngineSettings         = new EngineSettings();
            Preferences            = new PreferencesSettings();
        }
Esempio n. 18
0
 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;
 }
Esempio n. 19
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;
     Path     = savePath;
 }
        /// <summary>
        /// Implements the <see cref="EndProcessing"/> method for <see cref="SetTransmissionTorrentsCmdlet"/>.
        /// Retrieve all torrents
        /// </summary>
        protected override void EndProcessing()
        {
            try
            {
                // validate a torrent id has been supplied
                if (!(TorrentIds ?? new List <int>()).Any())
                {
                    ThrowTerminatingError(new ErrorRecord(new Exception("The TorrentIds parameter must be supplied."), null, ErrorCategory.InvalidArgument, null));
                }

                var torrentSvc = new TorrentService();

                var request = new TorrentSettings
                {
                    BandwidthPriority   = BandwidthPriority,
                    DownloadLimit       = DownloadLimit,
                    DownloadLimited     = DownloadLimited,
                    HonorsSessionLimits = HonoursSessionLimits,
                    Ids            = _torrentIds.ToArray(),
                    Location       = Location,
                    PeerLimit      = PeerLimit,
                    QueuePosition  = QueuePosition,
                    SeedIdleLimit  = SeedIdleLimit,
                    SeedIdleMode   = SeedIdleMode,
                    SeedRatioLimit = SeedRatioLimit,
                    SeedRatioMode  = SeedRatioMode,
                    UploadLimit    = UploadLimit,
                    UploadLimited  = UploadLimited,
                    TrackerAdd     = (TrackerAdd ?? new List <string>()).Any()
                        ? TrackerAdd.ToArray()
                        : null,
                    TrackerRemove = (TrackerRemove ?? new List <int>()).Any()
                        ? TrackerRemove.ToArray()
                        : null
                };

                bool success = Task.Run(async() => await torrentSvc.SetTorrents(request)).Result;

                if (AsBool.IsPresent)
                {
                    WriteObject(success);

                    return;
                }

                if (!success)
                {
                    ThrowTerminatingError(new ErrorRecord(new Exception("Set torrent(s) failed"), null, ErrorCategory.OperationStopped, null));
                }

                WriteObject("Set torrent(s) successful");
            }
            catch (Exception e)
            {
                ThrowTerminatingError(new ErrorRecord(new Exception($"Failed to set torrent(s) with error: {e.Message}", e), null, ErrorCategory.OperationStopped, null));
            }
        }
 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;
 }
        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 ITorrentDownloader GetTorrentDownloader(Uri torrentDescriptionFileUri, bool initialSeedingEnabled = false, ClientEngine clientEngine = null)
        {
            var engine = clientEngine ?? GetClientEngine();

            var torrentSettings = new TorrentSettings {
                InitialSeedingEnabled = initialSeedingEnabled
            };

            var torrentDownloader = GetTorrentDownloader(torrentDescriptionFileUri, torrentSettings, engine);

            return(torrentDownloader);
        }
Esempio n. 24
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);
        }
Esempio n. 25
0
        /// <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);
        }
Esempio n. 26
0
        public Download addTorrent(Torrent torrent, bool startTorrent, bool removeOriginal, TorrentSettings savedSettings, string savePath, bool isUrl)
        {
            string   originalPath = torrent.TorrentPath;
            Download manager;

            if (!Directory.Exists(savePath))
            {
                throw new TorrentException("Torrent save path does not exist, " + savePath);
            }

            // Check to see if torrent already exists
            if (engine.Contains(torrent))
            {
                logger.Error("Failed to add torrent, " + torrent.Name + " already exists.");
                throw new TorrentException("Failed to add torrent, " + torrent.Name + " already exists.");
            }

            // Move the .torrent to the local storage folder if it's not there already
            MoveToStorage(ref torrent);

            TorrentSettings settings = savedSettings ?? defaultTorrentSettings.Clone();
            FastResume      resume   = this.fastResume.Find(delegate(FastResume f) { return(f.Infohash == torrent.InfoHash); });

            manager = new Download(savePath, new TorrentManager(torrent, savePath, settings));
            if (resume != null)
            {
                manager.Manager.LoadFastResume(resume);
            }

            engine.Register(manager.Manager);

            if (removeOriginal)
            {
                logger.Info("Removing {0}", originalPath);
                File.Delete(originalPath);
            }

            Event.Raise <DownloadAddedEventArgs> (Added, this, new DownloadAddedEventArgs(manager));
            allTorrents.Add(manager);

            if (startTorrent)
            {
                logger.Info("Auto starting torrent " + manager.Torrent.Name);
                manager.Start();
            }

            logger.Info("Added torrent " + manager.Torrent.Name);

            return(manager);
        }
        /// <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(System.Net.BitTorrent.Common.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);
        }
Esempio n. 29
0
        /// <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(Common.Torrent torrent, StorageFolder savePath, TorrentSettings settings,
                              string baseDirectory)
        {
            Check.Torrent(torrent);
            Check.SaveFolder(savePath);
            Check.Settings(settings);
            Check.BaseDirectory(baseDirectory);

            Torrent  = torrent;
            InfoHash = torrent.InfoHash;
            Settings = settings;

            Initialise(savePath, baseDirectory, torrent.AnnounceUrls);
            ChangePicker(CreateStandardPicker());
        }
        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();
        }