public async void LoadTorrent(string filename) { if (!Directory.Exists(torrentDir)) { Directory.CreateDirectory(torrentDir); } try { string torrentFileName = Path.Combine(torrentDir, Path.GetFileName(filename)); File.Copy(filename, torrentFileName, true); var result = from t in Torrents where t.TorrentFileName == filename select t; if (result == null || result.Count() == 0) { var addParams = new AddTorrentParams { SaveFolder = Properties.Settings.Default.Location, Filename = filename }; var torrent = await Torrent.Create(addParams); torrent.TorrentFileName = torrentFileName; AddTorrent(torrent); } else { Error?.Invoke(this, "This torrent already exists"); } } catch (Exception ex) { Error?.Invoke(this, "Error parsing file"); } }
public void Handle(AddUrlMessage message) { using (var addParams = new AddTorrentParams()) { addParams.Name = message.Name; addParams.SavePath = message.SavePath ?? _keyValueStore.Get <string>("bt.save_path"); addParams.Url = message.Url; if (message.Trackers != null) { foreach (var tracker in message.Trackers) { addParams.Trackers.Add(tracker); } } // Parse info hash var infoHash = Regex.Match(message.Url, "urn:btih:([\\w]{32,40})").Groups[1].Value; if (infoHash.Length == 32) { infoHash = BitConverter.ToString(Base32Encoder.ToBytes(infoHash)).Replace("-", "").ToLowerInvariant(); } // Set label _metadataRepository.SetLabel(infoHash, message.Label); // Add torrent _session.AsyncAddTorrent(addParams); } }
public void LoadTorrent(string filename) { if (!Directory.Exists(torrentDir)) { Directory.CreateDirectory(torrentDir); } try { TorrentInfo info = new TorrentInfo(filename); string torrentFileName = Path.Combine(torrentDir, info.Name + ".torrent"); File.Copy(filename, torrentFileName, true); var result = from t in Torrents where t.InfoHash == info.InfoHash select t; if (result == null || result.Count() == 0) { var addParams = new AddTorrentParams { SavePath = Properties.Settings.Default.Location, TorrentInfo = info }; var torrent = Torrent.Create(addParams, session); torrent.TorrentFileName = torrentFileName; AddTorrent(torrent); } else { Error?.Invoke(this, "This torrent already exists"); } } catch { Error?.Invoke(this, "Error parsing file"); } }
public AddTorrentMessage(AddTorrentParams addParams) { if (addParams == null) { throw new ArgumentNullException("addParams"); } _addParams = addParams; }
public AddTorrentViewModel(IEventAggregator eventAggregator, TorrentInfo torrentInfo) { if (eventAggregator == null) throw new ArgumentNullException("eventAggregator"); _eventAggregator = eventAggregator; _addParams = new AddTorrentParams { TorrentInfo = torrentInfo }; _addParams.SavePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Downloads"); }
public async Task<bool> AddTorrent(Uri magnet, AddTorrentParams addTorrentParams = null) { if (addTorrentParams == null) { addTorrentParams = new AddTorrentParams(); } var argParams = new object[3]; argParams[0] = "url"; argParams[1] = magnet.ToString(); argParams[2] = addTorrentParams; var response = await SendJsonrpcRequest("webui.addTorrent", argParams); return response.IsSuccessStatusCode; }
public async Task<bool> AddTorrent(byte[] file, AddTorrentParams addTorrentParams = null) { if (addTorrentParams == null) { addTorrentParams = new AddTorrentParams(); } var argParams = new object[3]; argParams[0] = "file"; argParams[1] = Convert.ToBase64String(file); argParams[2] = addTorrentParams; var response = await SendJsonrpcRequest("webui.addTorrent", argParams); return response.IsSuccessStatusCode; }
public TorrentModel() { Session = new Session(); using (var db = new TorLiteDatabase()) { var colls = db.GetCollection <SessionState>("SessionState"); var state = colls.FindAll().FirstOrDefault(); if (state != null) { var ms = new MemoryStream(); db.FileStorage.Download(state.State, ms); ms.Position = 0; Session.Start(ms.GetBuffer()); } else { Session.Start(); } } this.Session.OnAlert += Session_OnAlert; this.Session.OnTorrentAddedAlert += Session_OnTorrentAddedAlert; this.Session.OnTorrentCheckedAlert += Session_OnTorrentCheckedAlert; this.Session.OnTorrentResumedAlert += Session_OnTorrentResumedAlert; this.Session.OnStateChangedAlert += Session_OnStateChangedAlert; this.Session.OnStateUpdateAlert += Session_OnStateUpdateAlert; this.Session.OnSaveResumeDataAlert += Session_OnSaveResumeDataAlert;; this.Session.OnStatsAlert += Session_OnStatsAlert; using (var db = new TorLiteDatabase()) { var cools = db.GetCollection <Torrent>("Torrents"); foreach (Torrent torrent in cools.FindAll()) { MemoryStream ms = new MemoryStream(); MemoryStream msInfo = new MemoryStream(); db.FileStorage.Download(torrent.File, msInfo); msInfo.Position = 0; db.FileStorage.Download(torrent.ResumeData, ms); ms.Position = 0; var par = new AddTorrentParams { ResumeData = ms.GetBuffer(), TorrentInfo = new TorrentInfo(msInfo.GetBuffer()) }; this.Session.AddTorrent(par); } } }
public AddTorrentViewModel(IEventAggregator eventAggregator, TorrentInfo torrentInfo) { if (eventAggregator == null) { throw new ArgumentNullException("eventAggregator"); } _eventAggregator = eventAggregator; _addParams = new AddTorrentParams { TorrentInfo = torrentInfo }; _addParams.SavePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Downloads"); }
private void HandleAddTorrent(TorrentInfo info, string filePath) { var par = new AddTorrentParams { SavePath = "C:/Downloads", TorrentInfo = info }; if (!this.ParentWindow.TorrentModel.Session.TorrentExist(par)) { this.ParentWindow.TorrentModel.Session.AddTorrent(par); using (var db = new TorLiteDatabase()) { var fadded = db.FileStorage.Upload(Guid.NewGuid().ToString(), filePath); var cools = db.GetCollection<Torrent>("Torrents"); cools.Insert(new Torrent { Name = par.TorrentInfo.Name, UTC_CreationDate = DateTime.UtcNow, File = fadded.Id, Hash = par.TorrentInfo.InfoHash, Path = par.SavePath }); } } }
public void Handle(AddTorrentMessage message) { using (var addParams = new AddTorrentParams()) { addParams.SavePath = message.SavePath ?? _keyValueStore.Get <string>("bt.save_path"); addParams.TorrentInfo = new TorrentInfo(message.Data); // Save torrent info _torrentInfoSaver.Save(addParams.TorrentInfo); // Save metadata _metadataRepository.SetLabel(addParams.TorrentInfo.InfoHash, message.Label); // Add torrent _session.AsyncAddTorrent(addParams); } }
public TorrentModel() { Session = new Session(); using (var db = new TorLiteDatabase()) { var colls = db.GetCollection<SessionState>("SessionState"); var state = colls.FindAll().FirstOrDefault(); if (state != null) { var ms = new MemoryStream(); db.FileStorage.Download(state.State, ms); ms.Position = 0; Session.Start(ms.GetBuffer()); } else Session.Start(); } this.Session.OnAlert += Session_OnAlert; this.Session.OnTorrentAddedAlert += Session_OnTorrentAddedAlert; this.Session.OnTorrentCheckedAlert += Session_OnTorrentCheckedAlert; this.Session.OnTorrentResumedAlert += Session_OnTorrentResumedAlert; this.Session.OnStateChangedAlert += Session_OnStateChangedAlert; this.Session.OnStateUpdateAlert += Session_OnStateUpdateAlert; this.Session.OnSaveResumeDataAlert += Session_OnSaveResumeDataAlert; ; this.Session.OnStatsAlert += Session_OnStatsAlert; using (var db = new TorLiteDatabase()) { var cools = db.GetCollection<Torrent>("Torrents"); foreach (Torrent torrent in cools.FindAll()) { MemoryStream ms = new MemoryStream(); MemoryStream msInfo = new MemoryStream(); db.FileStorage.Download(torrent.File, msInfo); msInfo.Position = 0; db.FileStorage.Download(torrent.ResumeData, ms); ms.Position = 0; var par = new AddTorrentParams { ResumeData = ms.GetBuffer(), TorrentInfo = new TorrentInfo(msInfo.GetBuffer()) }; this.Session.AddTorrent(par); } } }
private void HandleAddTorrent(TorrentInfo info, string filePath) { var par = new AddTorrentParams { SavePath = "C:/Downloads", TorrentInfo = info }; if (!this.ParentWindow.TorrentModel.Session.TorrentExist(par)) { this.ParentWindow.TorrentModel.Session.AddTorrent(par); using (var db = new TorLiteDatabase()) { var fadded = db.FileStorage.Upload(Guid.NewGuid().ToString(), filePath); var cools = db.GetCollection <Torrent>("Torrents"); cools.Insert(new Torrent { Name = par.TorrentInfo.Name, UTC_CreationDate = DateTime.UtcNow, File = fadded.Id, Hash = par.TorrentInfo.InfoHash, Path = par.SavePath }); } } }
private TorrentDownloader DownloadLocal(bool sequential) { if (TorrentSession == null) { TorrentSession = new Session(); TorrentSession.ListenOn(6881, 6889); } var torrentParams = new AddTorrentParams(); torrentParams.SavePath = GetDownloadPath(); torrentParams.Url = TorrentSource.Magnet; Handle = TorrentSession.AddTorrent(torrentParams); SetDownloadSpeedLimit(Settings.DownloadSpeed); SetUploadSpeedLimit(Settings.UploadSpeed); Handle.SequentialDownload = TorrentSource.IsSequential = sequential; Status = Handle.QueryStatus(); torrents.Add(this); TorrentDatabase.Save(TorrentSource); return(this); }
public async void LoadMagnet(string link) { if (!Directory.Exists(torrentDir)) { Directory.CreateDirectory(torrentDir); } try { if (link.StartsWith(@"magnet:?xt=urn:btih:") || link.StartsWith(@"http://") || link.StartsWith(@"https://")) { var addParams = new AddTorrentParams { SaveFolder = Properties.Settings.Default.Location, Url = link }; var torrent = await Torrent.Create(addParams); var result = from t in Torrents where t.InfoHash == torrent.InfoHash select t; if (result == null || result.Count() == 0) { AddTorrent(torrent); } else { Error?.Invoke(this, "This torrent already exists"); } } else { Error?.Invoke(this, "Wrong link"); } } catch (Exception ex) { Error?.Invoke(this, "Error opening magnet link!"); } }
/// <summary> /// Adds the torrent to session. /// </summary> /// <param name="torrent">The torrent.</param> public void AddTorrentToSession(TorrentEntity torrent) { using (var parameters = new AddTorrentParams()) { parameters.SavePath = torrent.SavePath; parameters.TorrentInfo = new TorrentInfo(torrent.TorrentMetadata); torrent.TorrentHandle = _session.AddTorrent(parameters); } if (!Torrents.Contains(torrent)) { for (var i = 0; i < torrent.TorrentFiles.Count; i++) { if (!torrent.TorrentFiles[i].IsSelected || torrent.TorrentFiles[i].Priority == TorrentPriority.Skip) { torrent.TorrentHandle.SetFilePriority(i, 0); torrent.TorrentFiles[i].Priority = TorrentPriority.Skip; } } Torrents.Add(torrent); _torrentRepository.InsertOrUpdate(torrent); } }
public bool TorrentExist(AddTorrentParams @params) { return(this._session.FindTorrent(@params.TorrentInfo.InfoHash) != null); }
public void AddTorrent(AddTorrentParams @params) { this._session.AsyncAddTorrent(@params); }
public AddTorrentMessage(AddTorrentParams addParams) { if (addParams == null) throw new ArgumentNullException("addParams"); _addParams = addParams; }
public void AddTorrentFromFile() { try { if (!IsDisposed) { byte[] bytes = File.ReadAllBytes(torrentFilePath); ti = new TorrentInfo(bytes); using (cMainForm.session) { cMainForm.session.ListenOn(6881, 6889); #region Torrent Parameters AddTorrentParams addParams = new AddTorrentParams(); if (unlimitedDownloadSpeed == false) { addParams.DownloadLimit = maxDownloadSpeed * 1024;//Transform byte to kB } if (unlimitedUploadSpeed == false) { addParams.UploadLimit = maxUploadSpeed * 1024; } addParams.TorrentInfo = ti; addParams.SavePath = string.Concat(saveFilePath, @"\", ti.Name); //This is weird, check it out later string resumeFile = Path.ChangeExtension(torrentFilePath, "resume"); if (File.Exists(resumeFile)) { addParams.ResumeData = File.ReadAllBytes(resumeFile);// Loading the resume data will load all torrents settings } #endregion // Add a torrent to the session and get a `TorrentHandle` in return. There is only one session that contains many handles. handle = cMainForm.session.AddTorrent(addParams); handle.SetPriority(128); if (handle.NeedSaveResumeData() == true) { SaveResumeData(); } SetLimitString(); cMainForm.mainForm.RunOnUIThread(() => cMainForm.mainForm.AddToMainList(ti.Name, ti.TotalSize, torrentIndex)); while (true) { if (pause == true) { PauseHandle(); } else if (handle.IsPaused == true && pause == false) { ResumeHandle(); } // Get a `TorrentStatus` instance from the handle. TorrentStatus status = handle.QueryStatus(); IEnumerable <PeerInfo> connectedPeers; connectedPeers = handle.GetPeerInfo(); if (status.IsSeeding) { break; } elapsedTime = status.ActiveTime; downloaded = status.Progress * 100; uploaded = status.TotalUpload * 100; uploadSpeed = status.UploadRate; downloadSpeed = status.DownloadRate; currentStatus = status.State.ToString(); UpdateProgressBar(downloaded); if (connectedPeers.Count() > 0 && cMainForm.mainForm.mainToolStripBottom.SelectedIndex == 2)//2 is client tab { cMainForm.mainForm.RunOnUIThread(() => cMainForm.mainForm.AddToClientList(connectedPeers, torrentIndex)); } if (cMainForm.mainForm.mainToolStripBottom.SelectedIndex == 0)//0 is info tab { cMainForm.mainForm.RunOnUIThread(() => cMainForm.mainForm.UpdateInfoTabData(downloaded.ToString(), uploaded.ToString(), uploadSpeed, downloadSpeed, formattedDownLimit, formattedUpLimit, currentStatus, elapsedTime.ToString(), torrentIndex)); } ; cMainForm.mainForm.RunOnUIThread(() => cMainForm.mainForm.EditMainList(downloaded.ToString(), uploadSpeed, downloadSpeed, currentStatus, torrentIndex)); Thread.Sleep(100); } } } } catch (Exception ex) { MessageBox.Show(ex.ToString(), "AddTorrentFromFile -- " + ex, MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public void Load() { // Set up message subscriptions _logger.Debug("Setting up subscriptions."); // Configure session _logger.Debug("Setting alert mask."); _session.SetAlertMask(SessionAlertCategory.Error | SessionAlertCategory.Peer | SessionAlertCategory.Status); var listenPort = _keyValueStore.Get <int>("bt.net.listen_port"); _session.ListenOn(listenPort, listenPort); _logger.Debug("Session listening on port {Port}.", listenPort); // Reload session settings _messageBus.Publish(new KeyValueChangedMessage(new[] { "bt.forceReloadSettings" })); // Start alerts thread _alertsThreadRunning = true; _alertsThread.Start(); // Load previous session state (if any) var sessionStatePath = _environment.GetApplicationDataPath().CombineWithFilePath("session_state"); if (_fileSystem.Exist(sessionStatePath)) { _logger.Debug("Loading session state."); var file = _fileSystem.GetFile(sessionStatePath); using (var stateStream = file.OpenRead()) using (var ms = new MemoryStream()) { stateStream.CopyTo(ms); _session.LoadState(ms.ToArray()); _logger.Debug("Loaded session state."); } } // Load previous torrents (if any) var torrentsPath = _environment.GetApplicationDataPath().Combine("Torrents"); var torrentsDirectory = _fileSystem.GetDirectory(torrentsPath); if (!torrentsDirectory.Exists) { torrentsDirectory.Create(); } foreach (var file in torrentsDirectory.GetFiles("*.torrent", SearchScope.Current)) { using (var torrentStream = file.OpenRead()) using (var torrentMemoryStream = new MemoryStream()) using (var addParams = new AddTorrentParams()) { torrentStream.CopyTo(torrentMemoryStream); addParams.SavePath = _keyValueStore.Get <string>("bt.save_path"); addParams.TorrentInfo = new TorrentInfo(torrentMemoryStream.ToArray()); _logger.Debug("Loading " + addParams.TorrentInfo.Name); // Check resume data var resumePath = file.Path.ChangeExtension(".resume"); var resumeFile = _fileSystem.GetFile(resumePath); if (resumeFile.Exists) { _logger.Debug("Loading resume data for " + addParams.TorrentInfo.Name); using (var resumeStream = resumeFile.OpenRead()) using (var resumeMemoryStream = new MemoryStream()) { resumeStream.CopyTo(resumeMemoryStream); addParams.ResumeData = resumeMemoryStream.ToArray(); } } // Add to muted torrents so we don't notify anyone _muted.Add(addParams.TorrentInfo.InfoHash); // Add torrent to session _session.AsyncAddTorrent(addParams); } } }
/// <summary> /// Download a movie /// </summary> /// <param name="movie">The movie to download</param> private async Task DownloadMovie(MovieFullDetails movie) { using (Session session = new Session()) { IsDownloadingMovie = true; // Inform subscribers we're actually loading a movie OnDownloadingMovie(new EventArgs()); // Listening to a port which is randomly between 6881 and 6889 session.ListenOn(6881, 6889); var addParams = new AddTorrentParams { // Where do we save the video file SavePath = Constants.MovieDownloads, // At this time, no quality selection is available in the interface, so we take the lowest Url = movie.Torrents.Aggregate((i1, i2) => (i1.SizeBytes < i2.SizeBytes ? i1 : i2)).Url }; TorrentHandle handle = session.AddTorrent(addParams); // We have to download sequentially, so that we're able to play the movie without waiting handle.SequentialDownload = true; bool alreadyBuffered = false; while (IsDownloadingMovie) { TorrentStatus status = handle.QueryStatus(); double progress = status.Progress * 100.0; // Inform subscribers of our progress OnLoadingMovieProgress(new MovieLoadingProgressEventArgs(progress, status.DownloadRate / 1024)); // We consider 2% of progress is enough to start playing if (progress >= Constants.MinimumBufferingBeforeMoviePlaying && !alreadyBuffered) { try { // We're looking for video file foreach (string directory in Directory.GetDirectories(Constants.MovieDownloads)) { foreach ( string filePath in Directory.GetFiles(directory, "*" + Constants.VideoFileExtension) ) { // Inform subscribers we have finished buffering the movie OnBufferedMovie(new MovieBufferedEventArgs(filePath)); alreadyBuffered = true; } } } catch (Exception e) { Console.WriteLine(e.Message); } } // Let sleep for a second before updating the torrent status await Task.Delay(1000, CancellationDownloadingToken.Token).ContinueWith(_ => { if (CancellationDownloadingToken.IsCancellationRequested && session != null) { OnStoppedDownloadingMovie(new EventArgs()); IsDownloadingMovie = false; session.RemoveTorrent(handle, true); } }).ConfigureAwait(false); } } }
public bool TorrentExist(AddTorrentParams @params) { return this._session.FindTorrent(@params.TorrentInfo.InfoHash) != null; }
/// <summary> /// Download a movie /// </summary> /// <param name="movie">The movie to download</param> /// <param name="downloadProgress">Report download progress</param> /// <param name="downloadRate">Report download rate</param> /// <param name="ct">Cancellation token</param> private async Task DownloadMovieAsync(MovieFull movie, IProgress<double> downloadProgress, IProgress<double> downloadRate, CancellationToken ct) { await Task.Run(async () => { using (var session = new Session()) { Logger.Debug( $"Start downloading movie : {movie.Title}"); IsDownloadingMovie = true; session.ListenOn(6881, 6889); var torrentUrl = movie.WatchInFullHdQuality ? movie.Torrents?.FirstOrDefault(torrent => torrent.Quality == "1080p")?.Url : movie.Torrents?.FirstOrDefault(torrent => torrent.Quality == "720p")?.Url; var addParams = new AddTorrentParams { SavePath = Constants.MovieDownloads, Url = torrentUrl, DownloadLimit = SimpleIoc.Default.GetInstance<SettingsViewModel>().DownloadLimit*1024, UploadLimit = SimpleIoc.Default.GetInstance<SettingsViewModel>().UploadLimit*1024 }; var handle = session.AddTorrent(addParams); // We have to download sequentially, so that we're able to play the movie without waiting handle.SequentialDownload = true; var alreadyBuffered = false; while (IsDownloadingMovie) { var status = handle.QueryStatus(); var progress = status.Progress*100.0; downloadProgress?.Report(progress); var test = Math.Round(status.DownloadRate/1024.0, 0); downloadRate?.Report(test); handle.FlushCache(); if (handle.NeedSaveResumeData()) { handle.SaveResumeData(); } if (progress >= Constants.MinimumBufferingBeforeMoviePlaying && !alreadyBuffered) { // Get movie file foreach ( var filePath in Directory.GetFiles(status.SavePath + handle.TorrentFile.Name, "*" + Constants.VideoFileExtension) ) { alreadyBuffered = true; movie.FilePath = new Uri(filePath); Messenger.Default.Send(new PlayMovieMessage(movie)); } } try { await Task.Delay(1000, ct); } catch (TaskCanceledException) { break; } } } }, ct); }
/// <summary> /// Download a torrent /// </summary> /// <returns><see cref="Task"/></returns> public Task Download(T media, TorrentType torrentType, MediaType mediaType, string torrentPath, int uploadLimit, int downloadLimit, IProgress <double> downloadProgress, IProgress <BandwidthRate> bandwidthRate, IProgress <int> nbSeeds, IProgress <int> nbPeers, Action buffered, Action cancelled, CancellationTokenSource cts) { return(Task.Run(async() => { Logger.Info( $"Start downloading : {torrentPath}"); using var session = new Session(); downloadProgress.Report(0d); bandwidthRate.Report(new BandwidthRate { DownloadRate = 0d, UploadRate = 0d }); nbSeeds.Report(0); nbPeers.Report(0); string savePath = string.Empty; switch (mediaType) { case MediaType.Movie: savePath = _cacheService.MovieDownloads; break; case MediaType.Show: savePath = _cacheService.ShowDownloads; break; case MediaType.Unkown: savePath = _cacheService.DropFilesDownloads; break; } if (torrentType == TorrentType.File) { using var addParams = new AddTorrentParams { save_path = savePath, ti = new TorrentInfo(torrentPath) }; using var handle = session.add_torrent(addParams); await HandleDownload(media, savePath, mediaType, uploadLimit, downloadLimit, downloadProgress, bandwidthRate, nbSeeds, nbPeers, handle, session, buffered, cancelled, cts); } else { var magnet = new MagnetUri(); using var error = new ErrorCode(); var addParams = new AddTorrentParams { save_path = savePath, }; magnet.parse_magnet_uri(torrentPath, addParams, error); using var handle = session.add_torrent(addParams); await HandleDownload(media, savePath, mediaType, uploadLimit, downloadLimit, downloadProgress, bandwidthRate, nbSeeds, nbPeers, handle, session, buffered, cancelled, cts); } })); }
/// <summary> /// Download a movie /// </summary> /// <param name="movie">The movie to download</param> private async Task DownloadMovie(MovieFullDetails movie) { using (Session session = new Session()) { IsDownloadingMovie = true; // Inform subscribers we're actually loading a movie OnDownloadingMovie(new EventArgs()); // Listening to a port which is randomly between 6881 and 6889 session.ListenOn(6881, 6889); var addParams = new AddTorrentParams { // Where do we save the video file SavePath = Constants.MovieDownloads, // At this time, no quality selection is available in the interface, so we take the lowest Url = movie.Torrents.Aggregate((i1, i2) => (i1.SizeBytes < i2.SizeBytes ? i1 : i2)).Url }; TorrentHandle handle = session.AddTorrent(addParams); // We have to download sequentially, so that we're able to play the movie without waiting handle.SequentialDownload = true; bool alreadyBuffered = false; while (IsDownloadingMovie) { TorrentStatus status = handle.QueryStatus(); double progress = status.Progress*100.0; // Inform subscribers of our progress OnLoadingMovieProgress(new MovieLoadingProgressEventArgs(progress, status.DownloadRate/1024)); // We consider 2% of progress is enough to start playing if (progress >= Constants.MinimumBufferingBeforeMoviePlaying && !alreadyBuffered) { try { // We're looking for video file foreach (string directory in Directory.GetDirectories(Constants.MovieDownloads)) { foreach ( string filePath in Directory.GetFiles(directory, "*" + Constants.VideoFileExtension) ) { // Inform subscribers we have finished buffering the movie OnBufferedMovie(new MovieBufferedEventArgs(filePath)); alreadyBuffered = true; } } } catch (Exception e) { Console.WriteLine(e.Message); } } // Let sleep for a second before updating the torrent status await Task.Delay(1000, CancellationDownloadingToken.Token).ContinueWith(_ => { if (CancellationDownloadingToken.IsCancellationRequested && session != null) { OnStoppedDownloadingMovie(new EventArgs()); IsDownloadingMovie = false; session.RemoveTorrent(handle, true); } }).ConfigureAwait(false); } } }
public void AddTorrentFromMagnet() { try { if (!IsDisposed) { using (cMainForm.session) { MagnetLink magnet = null; try { magnet = new MagnetLink(magnetLink); } catch { MessageBox.Show("Invalid magnet link", "Error"); return; } cMainForm.session.ListenOn(6881, 6889); #region Torrent Parameters AddTorrentParams addParams = new AddTorrentParams(); if (unlimitedDownloadSpeed == false) { addParams.DownloadLimit = maxDownloadSpeed * 1024;//Transform byte to kB } if (unlimitedUploadSpeed == false) { addParams.UploadLimit = maxUploadSpeed * 1024; } if (magnet.Name != null) { addParams.Name = magnet.Name; } addParams.Url = magnetLink; addParams.SavePath = saveFilePath; //This is weird, check it out later #endregion // Add a torrent to the session and get a `TorrentHandle` in return. There is only one session that contains many handles. handle = cMainForm.session.AddTorrent(addParams); handle.SetPriority(128); SetLimitString(); cMainForm.mainForm.RunOnUIThread(() => cMainForm.mainForm.AddToMainList(magnet.Name, handle.QueryStatus().TotalPayloadDownload, torrentIndex)); //ti doesn't exist here, you need to use info hash to get the name and size while (true) { if (pause == true) { PauseHandle(); } else if (handle.IsPaused == true && pause == false) { ResumeHandle(); } // Get a `TorrentStatus` instance from the handle. TorrentStatus status = handle.QueryStatus(); IEnumerable <PeerInfo> connectedPeers; connectedPeers = handle.GetPeerInfo(); if (status.IsSeeding) //If download is finished { break; } elapsedTime = status.ActiveTime; downloaded = status.Progress * 100; uploadSpeed = status.UploadRate; downloadSpeed = status.DownloadRate; currentStatus = status.State.ToString(); UpdateProgressBar(downloaded); if (connectedPeers.Count() > 0 && cMainForm.mainForm.mainToolStripBottom.SelectedIndex == 2)//2 is client tab { cMainForm.mainForm.RunOnUIThread(() => cMainForm.mainForm.AddToClientList(connectedPeers, torrentIndex)); } if (cMainForm.mainForm.mainToolStripBottom.SelectedIndex == 0)//0 is info tab { cMainForm.mainForm.RunOnUIThread(() => cMainForm.mainForm.UpdateInfoTabData(downloaded.ToString(), uploaded.ToString(), uploadSpeed, downloadSpeed, formattedDownLimit, formattedUpLimit, currentStatus, elapsedTime.ToString(), torrentIndex)); } if (cMainForm.mainForm.mainToolStripBottom.SelectedIndex == 1) //1 is file tab { cMainForm.mainForm.RunOnUIThread(() => cMainForm.mainForm.AddFilesToList(GetFilePriorities(), torrentIndex)); //Should send list of files instead of priorities but i don't know how to get the files :( } cMainForm.mainForm.RunOnUIThread(() => cMainForm.mainForm.EditMainList(downloaded.ToString(), uploadSpeed, downloadSpeed, currentStatus, torrentIndex)); Thread.Sleep(1); } } } } catch (Exception ex) { MessageBox.Show(ex.ToString(), "AddTorrentFromMagnet -- " + ex, MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public void Load() { // Set up message subscriptions _logger.Debug("Setting up subscriptions."); // Configure session _logger.Debug("Setting alert mask."); _session.SetAlertMask(SessionAlertCategory.Error | SessionAlertCategory.Peer | SessionAlertCategory.Status); var listenPort = _keyValueStore.Get<int>("bt.net.listen_port"); _session.ListenOn(listenPort, listenPort); _logger.Debug("Session listening on port {Port}.", listenPort); // Reload session settings _messageBus.Publish(new KeyValueChangedMessage(new[] {"bt.forceReloadSettings"})); // Start alerts thread _alertsThreadRunning = true; _alertsThread.Start(); // Load previous session state (if any) var sessionStatePath = _environment.GetApplicationDataPath().CombineWithFilePath("session_state"); if (_fileSystem.Exist(sessionStatePath)) { _logger.Debug("Loading session state."); var file = _fileSystem.GetFile(sessionStatePath); using (var stateStream = file.OpenRead()) using (var ms = new MemoryStream()) { stateStream.CopyTo(ms); _session.LoadState(ms.ToArray()); _logger.Debug("Loaded session state."); } } // Load previous torrents (if any) var torrentsPath = _environment.GetApplicationDataPath().Combine("Torrents"); var torrentsDirectory = _fileSystem.GetDirectory(torrentsPath); if (!torrentsDirectory.Exists) torrentsDirectory.Create(); foreach (var file in torrentsDirectory.GetFiles("*.torrent", SearchScope.Current)) { using (var torrentStream = file.OpenRead()) using (var torrentMemoryStream = new MemoryStream()) using (var addParams = new AddTorrentParams()) { torrentStream.CopyTo(torrentMemoryStream); addParams.SavePath = _keyValueStore.Get<string>("bt.save_path"); addParams.TorrentInfo = new TorrentInfo(torrentMemoryStream.ToArray()); _logger.Debug("Loading " + addParams.TorrentInfo.Name); // Check resume data var resumePath = file.Path.ChangeExtension(".resume"); var resumeFile = _fileSystem.GetFile(resumePath); if (resumeFile.Exists) { _logger.Debug("Loading resume data for " + addParams.TorrentInfo.Name); using (var resumeStream = resumeFile.OpenRead()) using (var resumeMemoryStream = new MemoryStream()) { resumeStream.CopyTo(resumeMemoryStream); addParams.ResumeData = resumeMemoryStream.ToArray(); } } // Add to muted torrents so we don't notify anyone _muted.Add(addParams.TorrentInfo.InfoHash); // Add torrent to session _session.AsyncAddTorrent(addParams); } } }
/// <summary> /// Download a movie /// </summary> /// <param name="movie">The movie to download</param> /// <param name="downloadProgress">Report download progress</param> /// <param name="downloadRate">Report download rate</param> /// <param name="ct">Cancellation token</param> private async Task DownloadMovieAsync(MovieFull movie, IProgress <double> downloadProgress, IProgress <double> downloadRate, CancellationToken ct) { await Task.Run(async() => { using (var session = new Session()) { IsDownloadingMovie = true; session.ListenOn(6881, 6889); var torrentUrl = movie.WatchInFullHdQuality ? movie.Torrents?.FirstOrDefault(torrent => torrent.Quality == "1080p")?.Url : movie.Torrents?.FirstOrDefault(torrent => torrent.Quality == "720p")?.Url; var addParams = new AddTorrentParams { SavePath = Constants.MovieDownloads, Url = torrentUrl, DownloadLimit = SimpleIoc.Default.GetInstance <SettingsViewModel>().DownloadLimit *1024, UploadLimit = SimpleIoc.Default.GetInstance <SettingsViewModel>().UploadLimit *1024 }; var handle = session.AddTorrent(addParams); // We have to download sequentially, so that we're able to play the movie without waiting handle.SequentialDownload = true; var alreadyBuffered = false; while (IsDownloadingMovie) { var status = handle.QueryStatus(); var progress = status.Progress * 100.0; downloadProgress?.Report(progress); var test = Math.Round(status.DownloadRate / 1024.0, 0); downloadRate?.Report(test); handle.FlushCache(); if (handle.NeedSaveResumeData()) { handle.SaveResumeData(); } if (progress >= Constants.MinimumBufferingBeforeMoviePlaying && !alreadyBuffered) { // Get movie file foreach ( var filePath in Directory.GetFiles(status.SavePath + handle.TorrentFile.Name, "*" + Constants.VideoFileExtension) ) { alreadyBuffered = true; movie.FilePath = new Uri(filePath); Messenger.Default.Send(new PlayMovieMessage(movie)); } } try { await Task.Delay(1000, ct); } catch (TaskCanceledException) { break; } } } }); }