コード例 #1
0
        private void AddRelatedTorrents(TorrentModel tm, int maxTorrents)
        {
            if (!tm.HasImdbId())
            {
                return;
            }

            var torrents = this.torrentsRepo.FindByImdbId(tm.ImdbId, maxTorrents + 1); // maxTorrents + 1 just in case we get the current torrent and we have to dismiss it

            foreach (var t in torrents)
            {
                if (tm.RelatedTorrents.Count == maxTorrents)
                {
                    break;
                }

                if (t.Id == tm.Id)
                {
                    continue;
                }

                var relatedTorrent = new RelatedTorrentModel();
                AutoMapper.Mapper.Map(t, relatedTorrent);
                tm.RelatedTorrents.Add(relatedTorrent);
            }
        }
コード例 #2
0
        static async Task Main(string[] args)
        {
            using (var fs = new FileStream("b.torrent", FileMode.Open))
            {
                var          data         = Parser.Decode(fs);
                TorrentModel torrentModel = new TorrentModel(data as DictionaryField);
                _logger.LogWarnning("下载:" + torrentModel.Info.Name);

                _ = torrentModel.TrackAsync();

                torrentModel.Connecting();

                //var res2 = await torrentModel.ScrapeAsync();

                ////调试
                //torrentModel.Download(new Tracker.Models.TrackerResponse(IPEndPoint.Parse("192.168.1.102:29512"))
                //{
                //    Peers = new IPEndPoint[] {
                //        IPEndPoint.Parse("192.168.1.102:29512"),
                //    }
                //});

                torrentModel.WaitFinish();
            }
            _logger.LogWarnning("OK");
        }
コード例 #3
0
        /// <summary>
        /// Add torrent into my torrent list and return success code.
        /// </summary>
        /// <param name="fileName">filename of torrent</param>
        /// <param name="name">name to export as excel document</param>
        /// <param name="torrent">torrent object</param>
        /// <returns>0: success, 1: duplicated torrent, 2: duplicated name, 3: unexpected error</returns>
        public int AddTorrent(string fileName, string name, Torrent torrent)
        {
            int maxId = -1;

            // check validation
            foreach (TorrentModel model in torrentModels)
            {
                if (model.FileName.Equals(fileName))
                {
                    return(1);
                }
                if (model.TorrentManager.Torrent.InfoHash.Equals(torrent.InfoHash))
                {
                    return(1);
                }
                if (model.Name.Equals(name))
                {
                    return(2);
                }

                if (model.Id > maxId)
                {
                    maxId = model.Id;
                }
            }

            // When any preprocessing has been completed, you create a TorrentManager
            // which you then register with the engine.
            TorrentManager manager = new TorrentManager(torrent, downloadsPath, torrentDefaults);

            //if(fastResume.ContainsKey(torrent.InfoHash.ToHex())) // remove fast resume
            //{ // remove fast resume
            //    manager.LoadFastResume(new FastResume((BEncodedDictionary)fastResume[torrent.InfoHash.ToHex()])); // remove fast resume
            //} // remove fast resume
            engine.Register(manager);
            manager.PeersFound += new EventHandler <PeersAddedEventArgs>(manager_PeersFound);

            // Store the torrent manager in our list so we can access it later
            TorrentModel newModel = new TorrentModel {
                FileName = fileName, Name = name, TorrentManager = manager, Id = maxId + 1
            };

            torrentModels.Add(newModel);

            // Start the torrentmanager. The file will then hash (if required) and begin downloading/seeding
            manager.Start();

            models_Changed();

            return(0);
        }
コード例 #4
0
        public ActionResult Index()
        {
            // TODO: This is an example, should be red from uploaded torrents
            var          torrents  = new List <TorrentModel>();
            const string id        = "6D80D046-6E45-4DBE-97D5-541FBCBB2E78";
            var          files     = new List <TorrentModelFile>();
            const int    totalSize = (1024 * 1024) * 100; // 100 Mb

            files.Add(new TorrentModelFile
            {
                FullPath = "testfile1.jpg",
                Size     = (totalSize / 4) * 1,
                Pieces   = new List <TorrentModelFilePiece> {
                    new TorrentModelFilePiece()
                    {
                        Size = ((totalSize / 4) * 1) / 2, Hash = "asd", StartByte = 0
                    },
                    new TorrentModelFilePiece()
                    {
                        Size = ((totalSize / 4) * 3) / 2, Hash = "asd", StartByte = ((totalSize / 4) * 1) / 2
                    }
                }
            });
            files.Add(new TorrentModelFile
            {
                FullPath = "testfile2.jpg",
                Size     = (totalSize / 4) * 3,
                Pieces   = new List <TorrentModelFilePiece> {
                    new TorrentModelFilePiece()
                    {
                        Size = ((totalSize / 4) * 3) / 2, Hash = "asd", StartByte = 0
                    },
                    new TorrentModelFilePiece()
                    {
                        Size = ((totalSize / 4) * 1) / 2, Hash = "asd", StartByte = ((totalSize / 4) * 3) / 2
                    }
                }
            });
            var torrent = new TorrentModel
            {
                Id       = id,
                Name     = "Test",
                Files    = files,
                Leechers = TorrentHub.Instance.Torrents.ContainsKey(id) ? TorrentHub.Instance.Torrents[id].Item1.Count : 0,
                Seeders  = TorrentHub.Instance.Torrents.ContainsKey(id) ? TorrentHub.Instance.Torrents[id].Item2.Count : 0,
                Size     = totalSize,
            };

            torrents.Add(torrent);
            return(View(torrents));
        }
コード例 #5
0
        private void AddTorrentsToTorrentsListModel(IEnumerable <Torrent> torrents, IList <StarredMovie> starred, User currentUser, TorrentsListModel model)
        {
            var moviesCache = new Dictionary <string, Movie>();

            foreach (var t in torrents)
            {
                Movie m = null;
                if (t.HasImdbId())
                {
                    if (!moviesCache.TryGetValue(t.ImdbId, out m))
                    {
                        m = this.moviesRepo.Find(t.ImdbId);
                        moviesCache.Add(t.ImdbId, m);
                    }
                }

                var tm = new TorrentModel();
                AutoMapper.Mapper.Map(t, tm);
                if (m != null)
                {
                    AutoMapper.Mapper.Map(m, tm);

                    if (string.IsNullOrEmpty(tm.Poster))
                    {
                        tm.Poster = m.Poster;
                    }
                }

                this.AddRelatedTorrents(tm, Constants.RelatedTorrentsCount);

                if (starred != null)
                {
                    tm.IsStarred = starred.Any(item => item.ImdbId.Equals(t.ImdbId, StringComparison.OrdinalIgnoreCase));
                }

                if (currentUser != null && currentUser.BookmarkPosition != null)
                {
                    tm.IsBookmarked = currentUser.BookmarkPosition.BookmarkedTorrentId == t.Id;
                    tm.IsNew        = (tm.AddedOn > currentUser.BookmarkPosition.BookmarkedTorrentAddedOn) || (tm.AddedOn == currentUser.BookmarkPosition.BookmarkedTorrentAddedOn && tm.Id < currentUser.BookmarkPosition.BookmarkedTorrentId);
                }
                else
                {
                    tm.IsNew = currentUser != null;
                }

                model.Torrents.Add(tm);
            }
        }
コード例 #6
0
        ///GET
        ///get torrent list
        ///
        ///POST
        ///Download Torrent from URL / magnet
        ///Pause Torrent
        ///Pause All
        ///Resume Torrent
        ///Resume ALl
        ///Delete Torrent
        ///Delete Torrent with downloaded data
        ///

        public static async Task <List <TorrentModel> > GetTorrentList()
        {
            string TorrentList = await CoreApi.GetASync("/query/torrents").ConfigureAwait(false);

            JArray parse = JArray.Parse(TorrentList);
            var    Jlist = parse.ToList();
            var    Lists = new List <TorrentModel>();
            List <TorrentModel> product = new List <TorrentModel>();

            foreach (JToken item in Jlist)
            {
                TorrentModel itemproperty = item.ToObject <TorrentModel>();
                product.Add(itemproperty);
            }
            return(await Task.FromResult(product));
        }
コード例 #7
0
ファイル: TorrentService.cs プロジェクト: domxx9/NetworkTools
        public async Task AddTorrent(TorrentModel torrent)
        {
            if (torrent != null)
            {
                var fileInfo = new FileInfo(torrent.TorrentFile.FileName);
                // if(fileInfo.Extension != ".torrent") { throw new Exception("File is not a torrent file!"); }

                var path = Path.Combine(_config["ServerSettings:TorrentDir"], torrent.TorrentFile.FileName);
                using (var fileStream = new FileStream(path, FileMode.Create))
                {
                    torrent.TorrentFile.CopyTo(fileStream);
                };

                await _bittorrent.AddNewTorrent(path);
            }
        }
コード例 #8
0
        public async Task <IActionResult> Post(IFormFile torrent)
        {
            try
            {
                if (torrent != null)
                {
                    TorrentModel model = new TorrentModel
                    {
                        TorrentFile = torrent
                    };

                    await _torrentService.AddTorrent(model);

                    return(Ok());
                }
                return(BadRequest("No torrent file"));
            }
            catch (Exception ex)
            {
                return(StatusCode(500, ex));
            }
        }
コード例 #9
0
        private void WorkerTorrentsManage_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            List <ClientModel> connectedModels = new List <ClientModel>();

            foreach (var model in torrentModels)
            {
                var peers = model.TorrentManager.GetPeers();
                foreach (var peer in peers)
                {
                    var uri = peer.Uri;
                    Debug.WriteLine(uri.ToString());
                    var         isExist        = false;
                    var         isConnected    = false;
                    ClientModel existingClient = null;
                    foreach (var client in clientModels)
                    {
                        if (uri.Host.Equals(client.IpAddress) && model.TorrentManager.Torrent.InfoHash.Equals(client.TorrentModel.TorrentManager.Torrent.InfoHash))
                        {
                            if (client.IsConnected)
                            {
                                if (!connectedModels.Contains(client))
                                {
                                    connectedModels.Add(client);
                                }
                                isConnected = true;
                            }
                            else
                            {
                                client.IsConnected = true;
                                connectedModels.Add(client);
                            }
                            isExist        = true;
                            existingClient = client;
                            break;
                        }
                    }
                    if (isExist && isConnected)
                    {
                        continue;
                    }
                    dynamic ispAndCountry = Utils.Utils.IspAndCountryFromIp(uri.Host);
                    if ((string)ispAndCountry.Country == "Unknown")
                    {
                        continue;
                    }
                    //if (ispAndCountry.Country != "Germany")
                    //{
                    //    break;
                    //}
                    TorrentModel torrent = null;
                    foreach (var tmp in Instance.torrentModels)
                    {
                        if (tmp.TorrentManager == model.TorrentManager)
                        {
                            torrent = tmp;
                        }
                    }
                    if (torrent == null)
                    {
                        continue;
                    }

                    if (isExist /* && !isConnected*/)
                    {
                        ViewManager.Instance.AddClientViewModel(existingClient);
                    }
                    else
                    {
                        ClientModel newClient = new ClientModel {
                            IpAddress = uri.Host, Port = uri.Port, Client = peer.ClientApp.ClientExp, TorrentModel = torrent, DateTime = DateTime.Now, ISP = ispAndCountry.Isp, Country = ispAndCountry.Country, IsConnected = true
                        };
                        clientModels.Add(newClient);

                        ViewManager.Instance.AddClientViewModel(newClient);
                    }
                }
            }
            foreach (var viewModel in ViewManager.Instance.ClientViewModels)
            {
                viewModel.IsActive = false;
                foreach (var client in connectedModels)
                {
                    viewModel.IsActive = false;
                    if (viewModel.IpAddress.Equals(client.IpAddress) && viewModel.FileHash.Equals(client.TorrentModel.TorrentManager.Torrent.InfoHash.ToString()))
                    {
                        viewModel.IsActive = true;
                        viewModel.EndDate  = DateTime.Now.ToString("dd:MM:yyyy");
                        viewModel.EndTime  = DateTime.Now.ToString("HH:mm:ss");
                    }
                }
            }
        }