Beispiel #1
0
        //public void saveTorrentFile()

        //hook events of each torrents to handlers.
        public static void initTorrentEvents(TorrentInfoModel torInfo)
        {
            torInfo.manager.PeerConnected += (o, e) => {
                lock (listener)
                    listener.WriteLine($"Connection succeeded: {e.Peer.Uri}");
                Console.WriteLine($"Connection succeeded: {e.Peer.Uri}");
            };
            torInfo.manager.ConnectionAttemptFailed += (o, e) => {
                lock (listener)
                    listener.WriteLine(
                        $"Connection failed: {e.Peer.ConnectionUri} - {e.Reason} - {e.Peer.AllowedEncryption}");
                Console.WriteLine($"Connection failed: {e.Peer.ConnectionUri} - {e.Reason} - {e.Peer.AllowedEncryption}");
            };
            // Every time a piece is hashed, this is fired.
            torInfo.manager.PieceHashed += delegate(object o, PieceHashedEventArgs e) {
                lock (listener)
                    listener.WriteLine($"Piece Hashed: {e.PieceIndex} - {(e.HashPassed ? "Pass" : "Fail")}");
                Console.WriteLine($"Piece Hashed: {e.PieceIndex} - {(e.HashPassed ? "Pass" : "Fail")}");
            };

            // Every time the state changes (Stopped -> Seeding -> Downloading -> Hashing) this is fired
            torInfo.manager.TorrentStateChanged += delegate(object o, TorrentStateChangedEventArgs e) {
                lock (listener)
                    listener.WriteLine($"OldState: {e.OldState} NewState: {e.NewState}");
                Console.WriteLine($"OldState: {e.OldState} NewState: {e.NewState}");
                TorrentInfoList[TorrentInfoList.IndexOf(torInfo)].status = e.NewState.ToString();
            };

            torInfo.manager.TorrentStateChanged += onStateChanged;
            // Every time the tracker's state changes, this is fired
            torInfo.manager.TrackerManager.AnnounceComplete += (sender, e) => {
                listener.WriteLine($"{e.Successful}: {e.Tracker}");
                Console.WriteLine($"{e.Successful}: {e.Tracker}");
            };
        }
Beispiel #2
0
        public async Task initDownloadMan()
        {
            string  torFilePath;
            Torrent torrent = null;
            bool    tmp     = false;

            /*Load fast resume file*/
            try
            {
                if (File.Exists(fastResumeFile))
                {
                    fastResume = BEncodedValue.Decode <BEncodedDictionary>(File.ReadAllBytes(fastResumeFile));
                }
            }
            catch
            {
                Debug.WriteLine("error here");
            }
            /*open torrentfile dir and load all the torrents*/
            if (System.IO.Directory.Exists(torrentsInfoPath))
            {
                string[] movies = System.IO.Directory.GetFiles(torrentsInfoPath);
                foreach (string m in movies)
                {
                    TorrentInfoModel torInfo = new TorrentInfoModel();
                    torInfo.ReadFromFile(m);
                    //readTorrentInfoFromFile(torInfo, m);
                    torFilePath = Path.Combine(torrentsPath, torInfo.torrentFileName);
                    if (System.IO.File.Exists(torFilePath))
                    {
                        Console.WriteLine("adding f= {0}", torFilePath);
                        torrent = await Torrent.LoadAsync(torFilePath);

                        TorrentManager manager = new TorrentManager(torrent, downloadsPath, new TorrentSettings());
                        manager.LoadFastResume(new FastResume((BEncodedDictionary)fastResume[torrent.InfoHash.ToHex()]));
                        await engine.Register(manager);

                        torInfo.manager         = manager;
                        torInfo.torrentFileName = torFilePath;
                        TorrentInfoList.Add(torInfo);
                        if (torInfo.status == TorrentState.Downloading.ToString())
                        {
                            await manager.StartAsync();
                        }
                        initTorrentEvents(torInfo); // hook all the events
                        tmp = true;
                    }
                }
                if (tmp)
                {
                    monitorTimer.Enabled = true;
                }
                Debug.WriteLine("torrent init exit!");
                //await engine.StartAllAsync();
            }
        }
Beispiel #3
0
        //start individual torrents.
        public async void DoTorrentAction(TorrentInfoModel torinfo, TorrentAction state)
        {
            string filePath;
            bool   response = false;

            switch (state)
            {
            case TorrentAction.START:
                await torinfo.manager.StartAsync();

                TorrentInfoList[TorrentInfoList.IndexOf(torinfo)].status = "Downloading";
                TorrentInfoList[TorrentInfoList.IndexOf(torinfo)].WriteToFile <string>("status", "Downloading");
                //writeTorrentInfoToFile(TorrentInfoList[TorrentInfoList.IndexOf(torinfo)]);
                break;

            case TorrentAction.STOP:
                await torinfo.manager.StopAsync();

                TorrentInfoList[TorrentInfoList.IndexOf(torinfo)].status = "Stopped";
                //writeTorrentInfoToFile(TorrentInfoList[TorrentInfoList.IndexOf(torinfo)]);
                TorrentInfoList[TorrentInfoList.IndexOf(torinfo)].WriteToFile <string>("status", "Stopped");
                break;

            case TorrentAction.PAUSE:
                await torinfo.manager.PauseAsync();

                TorrentInfoList[TorrentInfoList.IndexOf(torinfo)].status = "Paused";
                //writeTorrentInfoToFile(TorrentInfoList[TorrentInfoList.IndexOf(torinfo)]);
                TorrentInfoList[TorrentInfoList.IndexOf(torinfo)].WriteToFile <string>("status", "Paused");
                break;

            case TorrentAction.DELETE:
                /*delete .torrent file, infoFile, downloaded files*/
                response = await App.Current.MainPage.DisplayAlert("Delete?", "Would you like to delete your data?", "Yes", "No");

                if (!response)
                {
                    break;
                }
                filePath = Path.Combine(torrentsPath, torinfo.torrentFileName);
                //TorrentInfoList.RemoveAt(torinfo.index - 1);
                Console.WriteLine("deleting {0}", filePath);
                deleteFile(filePath, false);
                bool isDir = torinfo.manager.Torrent.Files.Count() == 1 ? false : true;
                filePath = Path.Combine(downloadsPath, torinfo.manager.Torrent.Name);
                Console.WriteLine("deleting {0}", filePath);
                deleteFile(filePath, isDir);
                Console.WriteLine("deleting {0}", torinfo.torrentInfoFileName);
                deleteFile(torinfo.torrentInfoFileName, false);
                await TorrentInfoList[TorrentInfoList.IndexOf(torinfo)].manager.StopAsync();
                await engine.Unregister(torinfo.manager);

                TorrentInfoList.Remove(torinfo);
                break;

            case TorrentAction.REMOVE:
                /*delete .torrent and info file*/
                response = await App.Current.MainPage.DisplayAlert("Remove?", "Would you like to remove your data?", "Yes", "No");

                if (!response)
                {
                    break;
                }
                filePath = Path.Combine(torrentsPath, torinfo.torrentFileName);
                //TorrentInfoList.RemoveAt(torinfo.index - 1);
                Console.WriteLine("deleting {0}", filePath);
                deleteFile(filePath, false);
                Console.WriteLine("deleting {0}", torinfo.torrentInfoFileName);
                deleteFile(torinfo.torrentInfoFileName, false);
                await TorrentInfoList[TorrentInfoList.IndexOf(torinfo)].manager.StopAsync();
                await engine.Unregister(torinfo.manager);

                TorrentInfoList.Remove(torinfo);
                break;

            default:
                break;

                //case Torrentstate.RESUME:
                //  await manager.();
                //break;
            }
        }
Beispiel #4
0
        //method to add torrent to torrent engine. source can be magnetic uri or .torrent file
        public async Task addTorrent(string torrentFilePath, string torrentFileName)
        {
            Debug.WriteLine("adding:{0}", torrentFilePath);
            TorrentInfoModel torinfo = new TorrentInfoModel();

            Torrent torrent = null;

            if (String.IsNullOrEmpty(torrentFilePath))
            {
                Console.WriteLine("empty file path!");
                return;
            }
            if (torrentFilePath.EndsWith(".torrent", StringComparison.OrdinalIgnoreCase))
            {
                try
                {
                    torrent = await Torrent.LoadAsync(torrentFilePath);

                    Console.WriteLine("info hash = {0}", torrent.InfoHash.ToString());
                }
                catch (Exception e)
                {
                    Console.Write("Couldnot decode {0}: ", torrentFilePath);
                    Console.WriteLine(e.Message);
                    return;
                }
                TorrentManager manager = new TorrentManager(torrent, downloadsPath, new TorrentSettings());
                if (fastResume.ContainsKey(torrent.InfoHash.ToHex()))
                {
                    manager.LoadFastResume(new FastResume((BEncodedDictionary)fastResume[torrent.InfoHash.ToHex()]));
                }
                await engine.Register(manager);

                //add to torrent global list.
                Debug.WriteLine("added to list:{0}", torrentFilePath);
                manager.PeersFound += Manager_PeersFound;


                //save .torrent to torrent path to restore.
                string destPath = Path.Combine(torrentsPath, torrentFileName);
                destPath.Replace(' ', '_');
                torinfo.manager         = manager;
                torinfo.torrentFileName = torrentFileName;// destPath;
                torinfo.status          = "downlaoding";
                torinfo.imageUrl        = "none";
                torinfo.dateAdded       = DateTime.Now.ToString();
                torinfo.speedUp         = "";
                torinfo.speedDl         = "";
                torinfo.progress        = "";
                torinfo.WriteToFile();
                //writeTorrentInfoToFile(torinfo);
                System.IO.File.Copy(torrentFilePath, destPath, true);
                TorrentInfoList.Add(torinfo);
                initTorrentEvents(torinfo);
                DoTorrentAction(torinfo, TorrentAction.START);
                Console.WriteLine("Torrent Size={0}", manager.Torrent.Size);
                Console.WriteLine("Torrent Name= {0}", torinfo.manager.Torrent.Name);
                if (!monitorTimer.Enabled)//start monitor if not started already.
                {
                    monitorTimer.Enabled = true;
                }
                Debug.WriteLine("started:{0}", torrentFilePath);
            }
            return;
        }