示例#1
0
        public void Stop()
        {
            if (torrentManager.State != TorrentState.Hashing)
            {
                torrentManager.Stop();

                while (torrentManager.State != TorrentState.Stopped)
                {
                    Thread.Sleep(250);
                }

                BEncodedList       bl   = new BEncodedList();
                FastResume         fr   = torrentManager.SaveFastResume();
                BEncodedDictionary item = fr.Encode();
                bl.Add(item);
                File.WriteAllBytes(fastResumeFile, bl.Encode());
            }
            else
            {
                torrentManager.Stop();
            }

            File.WriteAllBytes(dhtNodesFile, clientEngine.DhtEngine.SaveNodes());
            clientEngine.Dispose();
        }
示例#2
0
        public static void OnFinishLoading(TorrentManager manager, TorrentStateChangedEventArgs args)
        {
            var newState = Utils.GetManagerTorrentState(manager);

            Console.WriteLine(manager.Torrent.Name + " State chaged: " + newState);
            if (manager.State == TorrentState.Seeding && !manager.allowSeeding)
            {
                Console.WriteLine("Stopping 2");
                manager.Stop();
            }
            else if (manager.State == TorrentState.Downloading &&
                     !manager.allowSeeding)
            {
                long size       = 0;
                long downloaded = 0;

                if (manager.Torrent != null)
                {
                    foreach (var f in manager.Torrent.Files)
                    {
                        if (f.Priority != Priority.DoNotDownload)
                        {
                            size       += f.Length;
                            downloaded += f.BytesDownloaded;
                        }
                    }
                }

                if (downloaded >= size && manager.HasMetadata && manager.State != TorrentState.Hashing)
                {
                    Console.WriteLine("Stopping 3");
                    manager.Stop();
                }
            }
            else if (newState == TorrentState.Finished || newState == TorrentState.Seeding)
            {
                if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
                {
                    var content = new UNMutableNotificationContent();
                    content.Title = "Download finished";
                    content.Body  = manager.Torrent.Name + " finished downloading";
                    content.Sound = UNNotificationSound.Default;

                    var date       = DateTime.Now;
                    var trigger    = UNTimeIntervalNotificationTrigger.CreateTrigger(1, false);
                    var identifier = manager.Torrent.Name;
                    var request    = UNNotificationRequest.FromIdentifier(identifier, content, trigger);

                    UNUserNotificationCenter.Current.AddNotificationRequest(request, null);
                }

                Background.CheckToStopBackground();
            }
            foreach (var action in Manager.Singletone.managerStateChanged)
            {
                action?.Invoke();
            }
        }
 private void OnStopItemActivated(object sender, EventArgs args)
 {
     try{
         selectedTorrent.Stop();
     } catch (Exception)
     {
         logger.Warn("Unable to stop " + selectedTorrent.Torrent.Name);
     }
 }
示例#4
0
        public void NoAnnouncesTest()
        {
            rig.TorrentDict.Remove("announce-list");
            rig.TorrentDict.Remove("announce");
            Torrent t = Torrent.Load(rig.TorrentDict);

            rig.Engine.Unregister(rig.Manager);
            TorrentManager manager = new TorrentManager(t, "", new TorrentSettings());

            rig.Engine.Register(manager);

            AutoResetEvent handle = new AutoResetEvent(false);

            manager.TorrentStateChanged += delegate(object o, TorrentStateChangedEventArgs e) {
                if (e.NewState == TorrentState.Downloading || e.NewState == TorrentState.Stopped)
                {
                    handle.Set();
                }
            };
            manager.Start();
            handle.WaitOne();
            System.Threading.Thread.Sleep(1000);
            manager.Stop();

            Assert.IsTrue(handle.WaitOne(10000, true), "#1");
            Assert.IsTrue(manager.TrackerManager.Announce().WaitOne(10000, true), "#2");;
        }
示例#5
0
        public void Update(bool force = false)
        {
            if ((manager.State == TorrentState.Paused || manager.State == TorrentState.Stopped) && Progress.Progress >= 1f && !force)
            {
                return;
            }

            Title.Text = manager.Torrent != null ? manager.Torrent.Name : "Magnet download";

            long size       = 0;
            long downloaded = 0;

            if (manager.Torrent != null)
            {
                foreach (var f in manager.Torrent.Files)
                {
                    if (f.Priority != Priority.DoNotDownload)
                    {
                        size       += f.Length;
                        downloaded += f.BytesDownloaded;
                    }
                }
            }
            long progress = size != 0 ? downloaded * 10000 / size : 0;

            Info.Text         = Utils.GetSizeText(downloaded) + " of " + Utils.GetSizeText(size) + " (" + String.Format("{0:0.00}", ((float)progress / 100f)) + "%)";
            Status.Text       = manager.State == TorrentState.Downloading ? manager.State.ToString() + " - DL:" + Utils.GetSizeText(manager.Monitor.DownloadSpeed) + "/s, UL:" + Utils.GetSizeText(manager.Monitor.UploadSpeed) + "/s" : manager.State.ToString();
            Progress.Progress = progress / 10000f;
            if ((Progress.Progress >= 1f || size == 0) && manager.State != TorrentState.Hashing && manager.HasMetadata)
            {
                manager.Stop();
                Status.Text       = "Finished";
                Progress.Progress = 1f;
            }
        }
 public void Stop()
 {
     if (engine.IsRunning)
     {
         engine.StopAll();
     }
     manager.Stop();
 }
示例#7
0
        public override void Cancel()
        {
            // Torrent has been started
            if (manager != null)
            {
                // Don't try to stop twice.
                if (manager.State != TorrentState.Stopped)
                {
                    manager.Stop();
                }

                // Torrent has not been started, may be hashing.
            }

            LoggingService.LogDebug("Transfer Cancel() {0}", Environment.StackTrace);

            isCanceled = true;
        }
示例#8
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            if (manager == null)
            {
                return;
            }

            Update();
            tableView.DataSource = this;
            tableView.Delegate   = this;

            Start.Clicked += delegate {
                manager.Start();
                Update();
            };

            Pause.Clicked += delegate {
                manager.Pause();
                Update();
            };

            Remove.Clicked += delegate {
                var message          = manager.HasMetadata ? "Are you sure to remove " + manager.Torrent.Name + " torrent?" : "Are you sure to remove this magnet torrent?";
                var actionController = UIAlertController.Create(null, message, UIAlertControllerStyle.ActionSheet);
                var removeAll        = UIAlertAction.Create("Yes and remove data", UIAlertActionStyle.Destructive, delegate {
                    if (manager.State == TorrentState.Stopped)
                    {
                        Manager.Singletone.UnregisterManager(manager);
                    }
                    else
                    {
                        manager.TorrentStateChanged += (sender, e) => {
                            if (e.NewState == TorrentState.Stopped)
                            {
                                Manager.Singletone.UnregisterManager(manager);
                            }
                        };
                        manager.Stop();
                    }
                    Manager.Singletone.managers.Remove(manager);
                    Directory.Delete(Path.Combine(Manager.RootFolder, manager.Torrent.Name), true);
                    File.Delete(manager.Torrent.TorrentPath);

                    if (UIApplication.SharedApplication.KeyWindow.RootViewController is UISplitViewController splitController)
                    {
                        if (splitController.Collapsed)
                        {
                            (splitController.ViewControllers[0] as UINavigationController).PopViewController(true);
                        }
                        splitController.ShowDetailViewController(Utils.CreateEmptyViewController(), this);
                    }
                });
示例#9
0
        /// <summary>
        /// Removes torrent manager from the engine if no one file is downloading
        /// </summary>
        /// <param name="manager"></param>
        public void CancelTorrent(TorrentManager manager)
        {
            if (manager.Torrent == null || manager.Torrent.Files.All(f => f.Priority == Priority.DoNotDownload))
            {
                manager.Stop();
                _engine.Unregister(manager);
                _torrents.Remove(manager);
                manager.Dispose();

                if (manager.Torrent != null && manager.Torrent.TorrentPath.StartsWith(TorrentsFolder))
                {
                    File.Delete(manager.Torrent.TorrentPath);
                }
            }
        }
示例#10
0
        public void Stop()
        {
            Active = false;
            if (State == State.Queued)
            {
                State = State.Stopped;
            }
            else
            {
                manager.Stop();
                manager.Engine.ConnectionManager.PeerMessageTransferred -= HandlePeerMessageTransferred;

                Event.Raise(Stopped, this, EventArgs.Empty);
                State = State.Stopped;
            }
        }
示例#11
0
        private bool DownloadTorrent(string path)
        {
            try
            {
                ClientEngine engine = new ClientEngine(new EngineSettings());

                MonoTorrent.Common.Torrent torrent        = MonoTorrent.Common.Torrent.Load(@"C:\WexflowTesting\Torrent\sample.torrent");
                TorrentManager             torrentManager = new TorrentManager(torrent, @"C:\WexflowTesting\Torrent\", new TorrentSettings());
                engine.Register(torrentManager);
                torrentManager.Start();

                // Keep running while the torrent isn't stopped or paused.
                while (torrentManager.State != TorrentState.Stopped && torrentManager.State != TorrentState.Paused)
                {
                    Thread.Sleep(1000);

                    if (torrentManager.Progress == 100.0)
                    {
                        // If we want to stop a torrent, or the engine for whatever reason, we call engine.StopAll()
                        torrentManager.Stop();
                        engine.StopAll();
                        break;
                    }
                }

                InfoFormat("The torrent {0} download succeeded.", path);
                return(true);
            }
            catch (ThreadAbortException)
            {
                throw;
            }
            catch (Exception e)
            {
                ErrorFormat("An error occured while downloading the torrent {0}: {1}", path, e.Message);
                return(false);
            }
        }
示例#12
0
 public void Stop()
 {
     TM.Stop();
 }
示例#13
0
        public void TorrentControl(int selected)
        {
            Dialog d = new Dialog(60, 8, "Torrent Control");

            TorrentManager item = items [selected];

            d.Add(new TrimLabel(1, 1, 60 - 6, item.Torrent.Name));

            bool   stopped    = item.State == TorrentState.Stopped;
            Button bstartstop = new Button(stopped ? "Start" : "Stop");

            bstartstop.Clicked += delegate {
                if (stopped)
                {
                    item.Start();
                }
                else
                {
                    item.Stop();
                }
                d.Running = false;
            };
            d.AddButton(bstartstop);

            // Later, when we hook it up, look up the state

            bool   paused = item.State == TorrentState.Paused;
            Button br     = new Button(paused ? "Resume" : "Pause");

            br.Clicked += delegate {
                if (paused)
                {
                    item.Start();
                }
                else
                {
                    item.Pause();
                }
                d.Running = false;
            };
            d.AddButton(br);

            Button bd = new Button("Delete");

            bd.Clicked += delegate {
                Application.Error("Not Implemented",
                                  "I have not implemented delete yet");
                d.Running = false;
            };
            d.AddButton(bd);

            Button bmap = new Button("Map");

            bmap.Clicked += delegate {
                Application.Error("Not Implemented",
                                  "I have not implemented map yet");
                d.Running = false;
            };
            d.AddButton(bmap);

            Button bcancel = new Button("Cancel");

            bcancel.Clicked += delegate {
                d.Running = false;
            };
            Application.Run(d);
            UpdateStatus();
        }
示例#14
0
        void RestoreTorrents()
        {
            SaveClass save = null;

            if (File.Exists(DatFile))
            {
                try {
                    save = Utils.DeSerializeObject <SaveClass>(DatFile);
                } catch (System.Xml.XmlException e) {
                    Console.WriteLine(e.StackTrace);
                    File.Move(DatFile, Path.Combine(ConfigFolder, "dat1.itor"));
                    var controller = UIAlertController.Create("Config file loading error", "There was a problem loading the configuration file, a copy will be created under the \"dat1\" name, and a new one will be created", UIAlertControllerStyle.Alert);

                    var topWindow = new UIWindow(UIScreen.MainScreen.Bounds);
                    topWindow.RootViewController = new UIViewController();
                    topWindow.WindowLevel        = UIWindowLevel.Alert + 1;

                    var ok = UIAlertAction.Create("OK", UIAlertActionStyle.Cancel, delegate {
                        topWindow.Hidden = true;
                        topWindow        = null;
                    });
                    controller.AddAction(ok);

                    topWindow.MakeKeyAndVisible();
                    topWindow.RootViewController.PresentViewController(controller, true, null);
                }
            }
            if (File.Exists(Path.Combine(ConfigFolder, "_temp.torrent")))
            {
                File.Delete(Path.Combine(ConfigFolder, "_temp.torrent"));
            }

            if (Directory.Exists(ConfigFolder))
            {
                foreach (var file in Directory.GetFiles(ConfigFolder))
                {
                    new Thread(() => {
                        if (file.EndsWith(".torrent", StringComparison.Ordinal))
                        {
                            Torrent torrent        = Torrent.Load(file);
                            TorrentManager manager = new TorrentManager(torrent, RootFolder, new TorrentSettings());

                            engine.Register(manager);
                            manager.TorrentStateChanged += (sender, e) => {
                                Manager.OnFinishLoading(manager, e);
                            };

                            if (save != null && save.data.ContainsKey(torrent.InfoHash.ToHex()))
                            {
                                if (save.data[torrent.InfoHash.ToHex()].resume != null)
                                {
                                    manager.LoadFastResume(new FastResume(BEncodedValue.Decode(save.data[torrent.InfoHash.ToHex()].resume) as BEncodedDictionary));
                                    manager.dateOfAdded  = save.data[torrent.InfoHash.ToHex()].date;
                                    manager.allowSeeding = save.data[torrent.InfoHash.ToHex()].allowSeeding;
                                    switch (save.data[torrent.InfoHash.ToHex()].state)
                                    {
                                    case TorrentState.Downloading:
                                        manager.Start();
                                        break;

                                    default:
                                        manager.Stop();
                                        break;
                                    }
                                }
                                foreach (var _file in torrent.Files)
                                {
                                    if (save.data[torrent.InfoHash.ToHex()].downloading.ContainsKey(_file.Path))
                                    {
                                        _file.Priority = save.data[torrent.InfoHash.ToHex()].downloading[_file.Path] ? Priority.Highest : Priority.DoNotDownload;
                                    }
                                }
                            }
                            else
                            {
                                foreach (var _file in torrent.Files)
                                {
                                    _file.Priority = Priority.DoNotDownload;
                                }
                                manager.HashCheck(true);
                            }

                            PiecePicker picker = new StandardPicker();
                            picker             = new PriorityPicker(picker);
                            manager.ChangePicker(picker);

                            foreach (TrackerTier tier in manager.TrackerManager)
                            {
                                foreach (Tracker t in tier.Trackers)
                                {
                                    t.AnnounceComplete += delegate(object sender, AnnounceResponseEventArgs e) {
                                        Console.WriteLine(string.Format("{0}!: {1}", e.Successful, e.Tracker));
                                    };
                                }
                            }

                            managers.Add(manager);

                            UIApplication.SharedApplication.InvokeOnMainThread(() => {
                                restoreAction?.Invoke();
                            });
                        }
                    }).Start();
                }
            }
        }
		public void removeTorrent(TorrentManager torrent, bool deleteTorrent, bool deleteData)
		{
			if(torrent.State != TorrentState.Stopped)
				torrent.Stop();
			
			TreeIter iter = torrents[torrent];
			torrentListStore.Remove(ref iter);
			torrents.Remove(torrent);
			allTorrents.Remove(torrent);
			
			if(deleteData){
				logger.Info("Deleting torrent data " + torrent.Torrent.Name);
				foreach(TorrentFile torrentFile in torrent.Torrent.Files){
					try{
						File.Delete(Path.Combine(torrent.SavePath, torrentFile.Path));
					} catch {
						logger.Error("Unable to delete " + Path.Combine(torrent.SavePath, torrentFile.Path));
					}
				}
			}
			
			if(deleteTorrent){
				logger.Info(" Deleting torrent file " + torrent.Torrent.TorrentPath);
				if(torrent.Settings.FastResumeEnabled){
					try{
						File.Delete(torrent.Torrent.TorrentPath + ".fresume");
					} catch {
						logger.Error("Unable to delete " + torrent.Torrent.TorrentPath + ".fresume");
					}
				}
				
				try{
					File.Delete(torrent.Torrent.TorrentPath);
				} catch {
					logger.Error("Unable to delete " + torrent.Torrent.TorrentPath);
				}
			}
			
			foreach(TorrentLabel label in labels){
				label.RemoveTorrent(torrent);
			}
			
			logger.Info("Removed torrent " + torrent.Torrent.Name);
			mainWindow.AllLabel.RemoveTorrent(torrent);
			
			if(torrentSwarm.ContainsKey(torrent))
				torrentSwarm.Remove(torrent);
			if(hashProgress.ContainsKey(torrent))
				hashProgress.Remove(torrent);
			
			engine.Unregister(torrent);
		}
示例#16
0
        void RestoreTorrents()
        {
            SaveClass save = null;

            if (File.Exists(DatFile))
            {
                save = Utils.DeSerializeObject <SaveClass>(DatFile);
            }

            if (Directory.Exists(ConfigFolder))
            {
                foreach (var file in Directory.GetFiles(ConfigFolder))
                {
                    new Thread(() => {
                        if (file.EndsWith(".torrent", StringComparison.Ordinal))
                        {
                            Torrent torrent        = Torrent.Load(file);
                            TorrentManager manager = new TorrentManager(torrent, RootFolder, new TorrentSettings());

                            engine.Register(manager);

                            if (save != null && save.data.ContainsKey(torrent.InfoHash.ToHex()))
                            {
                                if (save.data[torrent.InfoHash.ToHex()].resume != null)
                                {
                                    manager.LoadFastResume(new FastResume(BEncodedValue.Decode(save.data[torrent.InfoHash.ToHex()].resume) as BEncodedDictionary));
                                    switch (save.data[torrent.InfoHash.ToHex()].state)
                                    {
                                    case TorrentState.Downloading:
                                        manager.Start();
                                        break;

                                    case TorrentState.Paused:
                                        manager.Pause();
                                        break;

                                    case TorrentState.Stopped:
                                        manager.Stop();
                                        break;
                                    }
                                }
                                foreach (var _file in torrent.Files)
                                {
                                    if (save.data[torrent.InfoHash.ToHex()].downloading.ContainsKey(_file.Path))
                                    {
                                        _file.Priority = save.data[torrent.InfoHash.ToHex()].downloading[_file.Path] ? Priority.Highest : Priority.DoNotDownload;
                                    }
                                }
                            }

                            PiecePicker picker = new StandardPicker();
                            picker             = new PriorityPicker(picker);
                            manager.ChangePicker(picker);
                            manager.TorrentStateChanged += delegate {
                                Manager.OnFinishLoading(manager);
                            };

                            foreach (TrackerTier tier in manager.TrackerManager)
                            {
                                foreach (Tracker t in tier.Trackers)
                                {
                                    t.AnnounceComplete += delegate(object sender, AnnounceResponseEventArgs e) {
                                        Console.WriteLine(string.Format("{0}!: {1}", e.Successful, e.Tracker));
                                    };
                                }
                            }

                            managers.Add(manager);

                            UIApplication.SharedApplication.InvokeOnMainThread(() => {
                                restoreAction?.Invoke();
                            });
                        }
                    }).Start();
                }
            }
        }
 public void Stop()
 {
     manager.Stop();
 }
示例#18
0
        public void NoAnnouncesTest()
        {
            rig.TorrentDict.Remove("announce-list");
            rig.TorrentDict.Remove("announce");
            Torrent t = Torrent.Load(rig.TorrentDict);
            rig.Engine.Unregister(rig.Manager);
            TorrentManager manager = new TorrentManager(t, "", new TorrentSettings());
            rig.Engine.Register(manager);

			AutoResetEvent handle = new AutoResetEvent(false);
            manager.TorrentStateChanged += delegate(object o, TorrentStateChangedEventArgs e) {
                if (e.NewState == TorrentState.Downloading || e.NewState == TorrentState.Stopped)
                    handle.Set();
            };
            manager.Start();
            handle.WaitOne();
            System.Threading.Thread.Sleep(1000);
			manager.Stop();

            Assert.IsTrue(handle.WaitOne(10000, true), "#1");
            Assert.IsTrue(manager.TrackerManager.Announce().WaitOne(10000, true), "#2"); ;
        }
示例#19
0
 public void Dispose()
 {
     TorrentManager.Stop();
     CurrentState = State.Unknown;
 }
示例#20
0
        public void removeTorrent(TorrentManager torrent, bool deleteTorrent, bool deleteData)
        {
            if (torrent.State != TorrentState.Stopped)
            {
                torrent.Stop();
            }

            TreeIter iter = torrents[torrent];

            torrentListStore.Remove(ref iter);
            torrents.Remove(torrent);
            allTorrents.Remove(torrent);

            if (deleteData)
            {
                logger.Info("Deleting torrent data " + torrent.Torrent.Name);
                foreach (TorrentFile torrentFile in torrent.Torrent.Files)
                {
                    try{
                        File.Delete(Path.Combine(torrent.SavePath, torrentFile.Path));
                    } catch {
                        logger.Error("Unable to delete " + Path.Combine(torrent.SavePath, torrentFile.Path));
                    }
                }
            }

            if (deleteTorrent)
            {
                logger.Info(" Deleting torrent file " + torrent.Torrent.TorrentPath);
                if (torrent.Settings.FastResumeEnabled)
                {
                    try{
                        File.Delete(torrent.Torrent.TorrentPath + ".fresume");
                    } catch {
                        logger.Error("Unable to delete " + torrent.Torrent.TorrentPath + ".fresume");
                    }
                }

                try{
                    File.Delete(torrent.Torrent.TorrentPath);
                } catch {
                    logger.Error("Unable to delete " + torrent.Torrent.TorrentPath);
                }
            }

            foreach (TorrentLabel label in labels)
            {
                label.RemoveTorrent(torrent);
            }

            logger.Info("Removed torrent " + torrent.Torrent.Name);
            mainWindow.AllLabel.RemoveTorrent(torrent);

            if (torrentSwarm.ContainsKey(torrent))
            {
                torrentSwarm.Remove(torrent);
            }
            if (hashProgress.ContainsKey(torrent))
            {
                hashProgress.Remove(torrent);
            }

            engine.Unregister(torrent);
        }