Example #1
0
        void LoadTorrent()
        {
            // Load a .torrent file into memory
            Torrent torrent = Torrent.Load("myfile.torrent");

            // Set all the files to not download
            foreach (TorrentFile file in torrent.Files)
            {
                file.Priority = Priority.DoNotDownload;
            }

            // Set the first file as high priority and the second one as normal
            torrent.Files[0].Priority = Priority.Highest;
            torrent.Files[1].Priority = Priority.Normal;

            TorrentManager manager = new TorrentManager(torrent, "DownloadFolder", new TorrentSettings());

            managers.Add(manager);
            engine.Register(manager);

            // Disable rarest first and randomised picking - only allow priority based picking (i.e. selective downloading)
            PiecePicker picker = new StandardPicker();

            picker = new PriorityPicker(picker);
            manager.ChangePicker(picker);
        }
Example #2
0
        public async Task LoadTorrentAsync(string torrentFilePath, string savePath)
        {
            // Load a .torrent file into memory
            Torrent torrent = await Torrent.LoadAsync(torrentFilePath);

            // Set all the files to not download
            //foreach (TorrentFile file in torrent.Files)
            //    file.Priority = Priority.High;
            ////Set First File Prioroty
            //torrent.Files[1].Priority = Priority.Highest;
            if (string.IsNullOrWhiteSpace(savePath))
            {
                savePath = "TorrentsDownload";
            }
            //Proceed
            if (!Directory.Exists(savePath))
            {
                Directory.CreateDirectory(savePath);
            }

            TorrentManager manager = new TorrentManager(torrent, savePath, new TorrentSettings());

            managers.Add(manager);
            await engine.Register(manager);

            // Disable rarest first and randomised picking - only allow priority based picking (i.e. selective downloading)
            PiecePicker picker = new StandardPicker();

            picker = new PriorityPicker(picker);
            await manager.ChangePickerAsync(picker);

            await engine.StartAll();
        }
 public void Setup()
 {
     id.BitField.SetAll(true);
     tester = new TestPicker();
     picker = new PriorityPicker(tester);
     picker.Initialise(rig.Manager.Bitfield, rig.Torrent.Files, new List<Piece>());
     foreach (TorrentFile file in rig.Torrent.Files)
         file.Priority = Priority.Normal;
 }
 public void Setup()
 {
     _id.BitField.SetAll(true);
     _tester = new TestPicker();
     _picker = new PriorityPicker(_tester);
     _picker.Initialise(_rig.Manager.Bitfield, _rig.Torrent.Files, new List <Piece>());
     foreach (TorrentFile file in _rig.Torrent.Files)
     {
         file.Priority = Priority.Normal;
     }
 }
        public PriorityPickerTests()
        {
            rig = TestRig.CreateMultiFile();
            id = new PeerId(new Peer(new string('a', 20), new Uri("tcp://BLAH")), rig.Manager);
            id.BitField.SetAll(true);

            id.BitField.SetAll(true);
            tester = new TestPicker();
            picker = new PriorityPicker(tester);
            picker.Initialise(rig.Manager.Bitfield, rig.Torrent.Files, new List<Piece>());
            foreach (var file in rig.Torrent.Files)
                file.Priority = Priority.Normal;
        }
Example #6
0
        internal PiecePicker CreateStandardPicker()
        {
            PiecePicker picker;

            if (ClientEngine.SupportsEndgameMode)
            {
                picker = new EndGameSwitcher(new StandardPicker(), new EndGamePicker(),
                                             Torrent.PieceLength / Piece.BlockSize, this);
            }
            else
            {
                picker = new StandardPicker();
            }
            picker = new RandomisedPicker(picker);
            picker = new RarestFirstPicker(picker);
            picker = new PriorityPicker(picker);
            return(picker);
        }
Example #7
0
        private PiecePicker CreateSlidingPicker(TorrentManager torrent)
        {
            PiecePicker picker;

            if (ClientEngine.SupportsEndgameMode)
            {
                picker = new EndGameSwitcher(new StandardPicker(), new EndGamePicker(), torrent.Torrent.PieceLength / Piece.BlockSize, torrent);
            }
            else
            {
                picker = new StandardPicker();
            }
            picker = new RandomisedPicker(picker);
            picker = new SlidingWindowPicker(picker);
            picker = new PriorityPicker(picker);

            return(picker);
        }
Example #8
0
        void LoadTorrent()
        {
            // Load a .torrent file into memory
            Torrent torrent = Torrent.Load("myfile.torrent");

            // Set all the files to not download
            foreach (TorrentFile file in torrent.Files)
                file.Priority = Priority.DoNotDownload;

            // Set the first file as high priority and the second one as normal
            torrent.Files[0].Priority = Priority.Highest;
            torrent.Files[1].Priority = Priority.Normal;

            TorrentManager manager = new TorrentManager(torrent, "DownloadFolder", new TorrentSettings(), (FastResume) null);
            managers.Add(manager);
            engine.Register(manager);

            // Disable rarest first and randomised picking - only allow priority based picking (i.e. selective downloading)
            PiecePicker picker = new StandardPicker();
            picker = new PriorityPicker(picker);
            manager.ChangePicker(picker);
        }
Example #9
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();
                }
            }
        }
Example #10
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            files = torrent.Files.Clone() as TorrentFile[];
            Array.Sort(files, delegate(TorrentFile f1, TorrentFile f2) {
                return(string.Compare(f1.Path, f2.Path, StringComparison.Ordinal));
            });
            foreach (var file in files)
            {
                Console.WriteLine(file.Path);
            }

            tableView.DataSource = this;
            tableView.Delegate   = this;

            tableView.RowHeight = 78;

            Cancel.Clicked += delegate {
                if (torrent.TorrentPath.EndsWith("/_temp.torrent"))
                {
                    File.Delete(torrent.TorrentPath);
                }

                DismissViewController(true, null);
            };

            DeselectAllAction.Clicked += delegate {
                foreach (var file in files)
                {
                    file.Priority = Priority.DoNotDownload;
                }
                foreach (var cell in tableView.VisibleCells)
                {
                    ((FileCell)cell).Update();
                }
            };

            SelectAllAction.Clicked += delegate {
                foreach (var file in files)
                {
                    file.Priority = Priority.Highest;
                }
                foreach (var cell in tableView.VisibleCells)
                {
                    ((FileCell)cell).Update();
                }
            };

            Download.Clicked += delegate {
                TorrentManager manager = new TorrentManager(torrent, Manager.RootFolder, new TorrentSettings());
                Manager.Singletone.managers.Add(manager);
                Manager.Singletone.RegisterManager(manager);
                if (MainController.Instance != null)
                {
                    MainController.Instance.TableView.ReloadData();
                }

                // Disable rarest first and randomised picking - only allow priority based picking (i.e. selective downloading)
                PiecePicker picker = new StandardPicker();
                picker = new PriorityPicker(picker);
                manager.ChangePicker(picker);
                manager.TorrentStateChanged += delegate {
                    Manager.OnFinishLoading(manager);
                };

                foreach (var file in files)
                {
                    if (file.Priority != Priority.DoNotDownload)
                    {
                        manager.Start();
                        break;
                    }
                }

                if (!Directory.Exists(Manager.ConfigFolder))
                {
                    Directory.CreateDirectory(Manager.ConfigFolder);
                }
                if (File.Exists(Path.Combine(Manager.ConfigFolder, torrent.Name + ".torrent")))
                {
                    File.Delete(Path.Combine(Manager.ConfigFolder, torrent.Name + ".torrent"));
                }
                File.Copy(torrent.TorrentPath, Path.Combine(Manager.ConfigFolder, torrent.Name + ".torrent"));
                if (torrent.TorrentPath.EndsWith("/_temp.torrent"))
                {
                    File.Delete(torrent.TorrentPath);
                }

                foreach (var file in files)
                {
                    Console.WriteLine(file.Path + " " + file.Priority);
                }
                //SaveClass save = new SaveClass(manager);
                //Utils.SerializeObject<SaveClass>(save, AppDelegate.documents + "/Config/" + manager.Torrent.Name + ".sav");

                DismissViewController(true, null);
            };
        }
Example #11
0
        private async void OnTimedEvent(object source, ElapsedEventArgs e)
        {
            try
            {
                if (TorrentEngine == null)
                {
                    throw new Exception("Torrent Engine has not been started yet");
                }

                TimerWorker.Stop();
                this.CurrentStatus = QueueProcessorStatus.Seeding;

                Logger.LogInformation($"Running AT: {DateTime.UtcNow} UTC");

                using (var scope = ScopeFactory.CreateScope())
                {
                    var Db        = scope.ServiceProvider.GetRequiredService <HostedRepository>();
                    var allQueues = Db.BitClientProcessorQueues.Where(x => x.ExecutionStatus == ExecutionStatus.Queued).ToList();
                    if (allQueues != null && allQueues.Count > 0)
                    {
                        foreach (var queue in allQueues)
                        {
                            //Mark as Seeding
                            queue.ExecutionStatus    = ExecutionStatus.Seeding;
                            queue.LastUpdatedTimeUTC = DateTime.UtcNow;
                            Stopwatch stopWatch = new Stopwatch();
                            stopWatch.Start();

                            try
                            {
                                Logger.LogInformation($"Processing, Queue Tracking ID:{queue.TrackingId} AT: {DateTime.UtcNow} UTC");

                                #region ExecutionMain
                                // Load a .torrent file into memory
                                if (queue.TorrentFileBytes == null)
                                {
                                    throw new Exception("Torrent Content in Bytes is Empty");
                                }
                                Torrent torrent = await Torrent.LoadAsync(queue.TorrentFileBytes);

                                // Set all the files to not download
                                //foreach (TorrentFile file in torrent.Files)
                                //    file.Priority = Priority.High;
                                ////Set First File Prioroty
                                //torrent.Files[1].Priority = Priority.Highest;
                                string             subPath       = $"\\{queue.UserId}\\{queue.TrackingId}".ToUpper();
                                string             saveDirectory = GetTorrentDownloadPath() + subPath;
                                UserTorrentManager manager       = new UserTorrentManager(torrent, saveDirectory, new TorrentSettings());
                                //Asssign
                                manager.UserId                = queue.UserId;
                                manager.TrackingId            = queue.TrackingId;
                                manager.AvailableDownloadPath = $"{this.options.TorrentDownloadPath}{subPath}";

                                await TorrentEngine.Register(manager);

                                Db.UserTorrentManagers.Enqueue(manager);
                                // Disable rarest first and randomised picking - only allow priority based picking (i.e. selective downloading)
                                PiecePicker picker = new StandardPicker();
                                picker = new PriorityPicker(picker);
                                await manager.ChangePickerAsync(picker);

                                await this.TorrentEngine.StartAll();

                                #endregion

                                queue.ExecutionFeedBack = "Torrent added to Queue Successfully";
                                queue.ExecutionStatus   = ExecutionStatus.Processed;
                                Logger.LogInformation($"Torrent added to Queue Successfully, Tracking Id :{queue.TrackingId} AT: {DateTime.UtcNow} UTC");
                            }
                            catch (Exception ex)
                            {
                                queue.ErrorsCount++;
                                if (queue.ErrorsCount >= 5)
                                {
                                    queue.ExecutionStatus   = ExecutionStatus.ErrorOccurred;
                                    queue.ExecutionFeedBack = ex.Message;
                                }
                                else
                                {
                                    queue.ExecutionStatus   = ExecutionStatus.Queued;
                                    queue.ExecutionFeedBack = $"Requeued Attempt ({queue.ErrorsCount})";
                                }

                                Logger.LogError($"ERROR: {ex.Message}, Tracking Id :{queue.TrackingId} AT: {DateTime.UtcNow} UTC");
                            }


                            //**************** DONE *********************

                            stopWatch.Stop();
                            queue.LastUpdatedTimeUTC     = DateTime.UtcNow;
                            queue.ExecutionInMiliseconds = stopWatch.ElapsedMilliseconds;
                        }
                    }


                    //Exception Count Reset
                    _ExceptionCounts = 0;
                }
            }
            catch (Exception ex)
            {
                _ExceptionCounts++;
                Logger.LogError($"Processing Exception: {ex.Message}");
            }
            finally
            {
                ContinueTimer();
            }
        }
Example #12
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();
                }
            }
        }
Example #13
0
    void LoadTorrent(string path)
    {
        // Load a .torrent file into memory
        Torrent torrent = Torrent.Load (path);
        // Set all the files to not download
        //foreach (TorrentFile file in torrent.Files)
        //	file.Priority = Priority.DoNotDownload;

        // Set the first file as high priority and the second one as normal
        //torrent.Files[0].Priority = Priority.Highest;
        TorrentSettings ts =  new TorrentSettings ();
        ts.EnablePeerExchange = true;
        //ts.InitialSeedingEnabled = true;
        ts.UseDht = true;
        TorrentManager manager = new TorrentManager (torrent, dp, ts);
        manager.PeersFound += HandleManagerPeersFound;

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

        managers.Add (manager);

        engine.Register(manager);

        // Disable rarest first and randomised picking - only allow priority based picking (i.e. selective downloading)

        nodeview2.NodeStore.AddNode (new TorrentInfoRow (manager.Torrent.Name, manager.State.ToString (), manager.Torrent.Name.Substring (0, 10), "0", "0", "0", manager, managers.Count -1));
        nodeview2.Columns[0].MinWidth=100;
        nodeview2.Columns[1].MinWidth = 80;
        nodeview2.Columns[2].MinWidth = 65;
        nodeview2.Columns[3].MinWidth = 65;
        nodeview2.Columns[4].MinWidth = 50;
        nodeview2.NodeSelection.Changed += new System.EventHandler (OnSelectionChanged);
    }