/// <summary>
        /// Возвращает торрент файл
        /// </summary>
        /// <param name="softPostStr"></param>
        /// <returns></returns>
        public async Task <Stream> GetTorrentFile(string softPostStr)
        {
            int  softPostId;
            bool isParsable = int.TryParse(softPostStr, out softPostId);

            if (isParsable)
            {
                var query =
                    from el in _context.SoftPosts
                    where el.Id == softPostId
                    select el;

                SoftPost post = query.Single();

                var memoryStream = new MemoryStream();
                await using (var stream = new FileStream(post.TorrentFile, FileMode.Open))
                {
                    await stream.CopyToAsync(memoryStream);
                }
                memoryStream.Position = 0;
                return(memoryStream);
            }

            //todo: ошибка парсинга
            return(null);
        }
Esempio n. 2
0
        /// <summary>
        /// Добавляет новый пост на сайт
        /// </summary>
        /// <param name="inputParam"></param>
        /// <param name="imgUploadResult"></param>
        /// <returns>Если отработал успешно, то true, инчае false</returns>
        async Task <bool> SendPost(SoftPostInput inputParam,
                                   SoftFileUploadResult imgUploadResult,
                                   string userHash,
                                   SoftPost post)
        {
            IEnumerable <KeyValuePair <string, string> > formContent = inputParam.FormData;
            var manualContent = new Dictionary <string, string>
            {
                { inputParam.AddPostFormNameHeader, post.Name },
                { inputParam.AddPostFormDescriptionHeader, post.Description + post.Spoilers },
                { inputParam.AddPostFormPosterHeader, imgUploadResult.Xfvalue },
                { inputParam.UserHashHttpHeaderName, userHash }
            };

            string startKey = inputParam.AddPostFormScreenshotTemplateStartHeader;
            string endKey   = inputParam.AddPostFormScreenshotTemplateEndHeader;

            for (int i = 1; i <= inputParam.AddPostFormMaxCountScreenshots &&
                 i <= post.Imgs.Count; i++)
            {
                manualContent.Add(startKey + i + endKey, post.Imgs[i - 1].ImgUri);
            }
            //todo: Нужно добавить обработку исключения на случай если строка слишком длинная https://stackoverflow.com/questions/38440631
            var content = new FormUrlEncodedContent(formContent.Union(manualContent));

            var result = await _httpClient.PostAsync(inputParam.AddPostAddress, content);

            return(result.IsSuccessStatusCode);
        }
        /// <summary>
        /// Преобразует пост в SoftPost
        /// </summary>
        /// <param name="param"></param>
        /// <returns>SoftPost</returns>
        public async Task <SoftPost> Convert(DriverToSoftInput param)
        {
            SoftPost post = null;

            switch (param.Type)
            {
            case nameof(RutorItem):
                post = await RutorToSoft(param);

                break;

            case nameof(NnmclubItem):
                post = await NnmclubToSoft(param);

                break;

            default:
                break;
            }
            if (post != null)
            {
                _context.SoftPosts.Add(post);
                _context.SaveChanges();
                return(post);
            }
            return(null);
        }
        /// <summary>
        /// Преобразует NnmclubPost в SoftPost
        /// </summary>
        /// <returns></returns>
        async Task <SoftPost> NnmclubToSoft(DriverToSoftInput param)
        {
            NnmclubItem clubItem = _context
                                   .NnmclubItems
                                   .Include(el => el.NnmclubListItem)
                                   .Include(el => el.Imgs)
                                   .Include(el => el.Spoilers)
                                   .SingleOrDefault(el => el.Id == param.ParseItemId);

            if (clubItem != null)
            {
                string posterFullName = await DownloadFile(clubItem.Poster,
                                                           Path.GetFileName(clubItem.Poster),
                                                           param.ProxySocks5Addr,
                                                           param.ProxySocks5Port,
                                                           param.ProxyActive);

                if (posterFullName == null)
                {
                    _logger.LogError($"Не удалось загрузить постер. NnmclubItem.Id: {param.ParseItemId}; Href: {clubItem.NnmclubListItem.Href}");
                    return(null);
                }

                string torrentFullName = await DownloadFile(param.TorrentUri + clubItem.Torrent,
                                                            Path.GetRandomFileName().Replace('.', '_') + ".torrent",
                                                            param.ProxySocks5Addr,
                                                            param.ProxySocks5Port,
                                                            param.ProxyActive,
                                                            new Uri(param.AuthPage),
                                                            param.AuthParam);

                if (torrentFullName == null)
                {
                    _logger.LogError($"Не удалось загрузить торрент файл. NnmclubItem.Id: {param.ParseItemId}; Href: {clubItem.NnmclubListItem.Href}");
                    return(null);
                }

                var post = new SoftPost
                {
                    NnmclubItemId = param.ParseItemId,
                    Created       = DateTime.Now,
                    Name          = clubItem.Name,
                    Description   = clubItem.Description,
                    Spoilers      = FormatSpoilersNnmclub(clubItem.Spoilers),
                    PosterImg     = posterFullName,
                    TorrentFile   = torrentFullName,
                    Imgs          = (from img in clubItem.Imgs
                                     select new SoftPostImg
                    {
                        Created = DateTime.Now,
                        ImgUri = img.ImgUri
                    }).ToList(),
                };
                return(post);
            }
            _logger.LogError($"В базе не найдена презентация с указанным Id. NnmclubItem.Id: {param.ParseItemId}");
            return(null);
        }
Esempio n. 5
0
        /// <summary>
        /// Добавляет пост на сайт
        /// </summary>
        /// <param name="inputParam"></param>
        /// <returns>Если отработал успешно, то true, инчае false</returns>
        public async Task <PublishResult> AddPost(SoftPostInput inputParam)
        {
            SoftPost post =
                _context.SoftPosts
                .Include(el => el.Imgs)
                .SingleOrDefault(el => el.Id == inputParam.SoftPostId);

            if (post == null)
            {
                _logger.LogError("Не удалось найти указанный подготовленный пост в базе. SoftPost.Id = " + inputParam.SoftPostId);
                return(PublishResult.Error);
            }

            string userHash = await Authorize(inputParam);

            //Загружаем файл
            PublishResult torrentUploadResult = await UploadFile(inputParam,
                                                                 Path.GetFileName(post.TorrentFile),
                                                                 post.TorrentFile,
                                                                 userHash,
                                                                 inputParam.TorrentUploadQueryString);

            if (torrentUploadResult == PublishResult.Error)
            {
                _logger.LogError("Не удалось загрузить торрент файл на сайт");
                return(PublishResult.Error);
            }
            if (torrentUploadResult == PublishResult.FileExist)
            {
                _logger.LogError("Такой торрент файл уже загружен");
                return(PublishResult.FileExist);
            }

            //Загружаем постер
            SoftFileUploadResult imgUploadResult = await UploadPoster(inputParam,
                                                                      Path.GetFileName(post.PosterImg),
                                                                      post.PosterImg,
                                                                      userHash,
                                                                      inputParam.PosterUploadQueryString);

            if (imgUploadResult == null)
            {
                _logger.LogError("Не удалось загрузить постер на сайт");
                return(PublishResult.Error);
            }

            //Выкладываем
            bool sendPostResult = await SendPost(inputParam, imgUploadResult, userHash, post);

            if (!sendPostResult)
            {
                _logger.LogError("Не удалось отправить пост на сайт");
                return(PublishResult.Error);
            }
            return(PublishResult.Success);
        }
Esempio n. 6
0
        /// <summary>
        /// Подготавливаем и выкладываем пост
        /// </summary>
        /// <param name="itemType">Тип поста</param>
        /// <param name="itemId">Id поста</param>
        /// <returns>Если метод выполнен успешно - true, инчае false</returns>
        async Task <PublishResult> Send(string itemType, int itemId)
        {
            //Подготавливаем
            DriverToSoftInput driverInput =
                _context.DriverToSoftInputs
                .Single(el => el.Active && el.Type == itemType);

            driverInput.ParseItemId = itemId;
            SoftPost post = await _driverService.Convert(driverInput);

            if (post == null)
            {
                _logger.LogError($"Не удалось подготовить пост к публикации. {itemType}.Id = " + itemId);
                return(PublishResult.Error);
            }

            //Выкладываем
            SoftPostInput softPostInput =
                _context.SoftPostInputs
                .Single(el => el.Active);

            softPostInput.SoftPostId = post.Id;
            softPostInput.PosterUploadQueryString =
                _context.DictionaryValues
                .Where(el => el.DictionaryName == softPostInput.PosterUploadQueryStringId)
                .ToDictionary(k => k.Key, v => v.Value);
            softPostInput.TorrentUploadQueryString =
                _context.DictionaryValues
                .Where(el => el.DictionaryName == softPostInput.TorrentUploadQueryStringId)
                .ToDictionary(k => k.Key, v => v.Value);
            softPostInput.FormData =
                _context.DictionaryValues
                .Where(el => el.DictionaryName == softPostInput.FormDataId)
                .ToDictionary(k => k.Key, v => v.Value);
            softPostInput.AuthData =
                _context.DictionaryValues
                .Where(el => el.DictionaryName == softPostInput.AuthDataId)
                .ToDictionary(k => k.Key, v => v.Value);
            PublishResult result = await _softService.AddPost(softPostInput);

            if (result == PublishResult.Error)
            {
                _logger.LogError("Не удалось выложить пост на сайт. SoftPost.Id = " + post.Id);
                return(PublishResult.Error);
            }
            if (result == PublishResult.FileExist)
            {
                _logger.LogError("Не удалось выложить пост на сайт. Такой файл уже загружен.");
                return(PublishResult.FileExist);
            }
            return(PublishResult.Success);
        }
        public async Task <ActionResult <SoftPost> > ToSoft(DriverToSoftInput param)
        {
            SoftPost result = await _driverService.Convert(param);

            if (result != null)
            {
                foreach (var item in result.Imgs)
                {
                    item.SoftPost = null;
                }
                return(Ok(result));
            }
            return(BadRequest("Сервису не удалось получить готовый пост"));
        }
        /// <summary>
        /// Преобразует RutorPost в SoftPost
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        async Task <SoftPost> RutorToSoft(DriverToSoftInput param)
        {
            RutorItem rutorItem = _context
                                  .RutorItems
                                  .Include(el => el.RutorListItem)
                                  .Include(el => el.Imgs)
                                  .Include(el => el.Spoilers)
                                  .SingleOrDefault(el => el.Id == param.ParseItemId);

            if (rutorItem != null)
            {
                var post = new SoftPost();
                post.RutorItemId = param.ParseItemId;
                post.Name        = rutorItem.Name;
                post.Created     = DateTime.Now;

                string torrentFile = await DownloadFile(param.TorrentUri + rutorItem.RutorListItem.HrefNumber,
                                                        Path.GetRandomFileName().Replace('.', '_') + ".torrent",
                                                        param.ProxySocks5Addr,
                                                        param.ProxySocks5Port,
                                                        param.ProxyActive);

                if (torrentFile == null)
                {
                    _logger.LogError($"Не удалось загрузить торрент файл. RutorItem.Id: {param.ParseItemId}; Href: {rutorItem.RutorListItem.HrefNumber}");
                    return(null);
                }
                post.TorrentFile = torrentFile;

                string posterFile = await GetPosterImgRutor(rutorItem.Imgs, param);

                if (posterFile == null)
                {
                    _logger.LogError($"Не удалось загрузить постер. RutorItem.Id: {param.ParseItemId}; Href: {rutorItem.RutorListItem.HrefNumber}");
                    return(null);
                }
                FileInfo img = new FileInfo(posterFile);
                if (img.Length > param.MaxPosterSize * 1024)
                {
                    posterFile = _imgsConverter.ConvertToJpg(posterFile, 100);
                }
                post.PosterImg = posterFile;

                var queryUriImgs =
                    (from el in rutorItem.Imgs
                     where el.ParentUrl != null
                     select el.ParentUrl).ToList();
                var queryParams =
                    (from el in _context.ImghostParsingInputs
                     where el.Active == true
                     select el).ToList();
                List <string> screenshots =
                    (await _imghostService.GetOriginalsUri(new ImghostGetOriginalsInput
                {
                    ImgsUri = queryUriImgs,
                    ParsingParams = queryParams,
                })).ToList();
                var queryScr =
                    (from el in screenshots
                     select new SoftPostImg
                {
                    Created = DateTime.Now,
                    ImgUri = el,
                }).ToList();
                post.Imgs = queryScr;

                post.Description = FormatDescriptionRutor(rutorItem.Description, post.PosterImg);
                post.Spoilers    = FormatSpoilersRutor(rutorItem.Spoilers);

                return(post);
            }
            _logger.LogError($"В базе не найдена раздача с указанным Id. RutorItem.Id: {param.ParseItemId}");
            return(null);
        }