Ejemplo n.º 1
0
        public async Task <ReinsertResult> ReInsert(Anuncio anuncio, string Key2Captcha, string email)
        {
            ReinsertResult    result;
            CaptchaAnswer     captchaResponse;
            FormInsertAnuncio formInsertAnuncio;
            FormDeleteAnuncio formDeleteAnuncio;

            try
            {
                // Get Anuncio

                string htmlAnuncio = await Requests.GetAsync(anuncio.Url);

                GetException(htmlAnuncio, anuncio.Url, false);

                // Parse All Data
                FormUpdateAnuncio formAnuncio = ParseFormAnuncio(htmlAnuncio);
                formAnuncio.variables.email = email;
                anuncio.FormUpdateAnuncio   = JsonConvert.SerializeObject(formAnuncio);

                //Solve Captcha
                captchaResponse = await ResolveCaptcha(Key2Captcha, Requests.RevolicoInserrUrl, htmlAnuncio);

                formAnuncio.variables.captchaResponse = captchaResponse.Answerv2;
                //formAnuncio.variables.botScore = captchaResponse.Answerv3;

                // Parse Insert and Delete Forms
                formInsertAnuncio = new FormInsertAnuncio(formAnuncio);
                formDeleteAnuncio = new FormDeleteAnuncio(formAnuncio);

                // Insert new Announce
                string answer = await InsertAnuncio(formInsertAnuncio);

                // Verify Insertion
                GetException(answer, anuncio.Url, true, captchaResponse);

                // Update new Anuncio URL
                InsertResult insertResult = ParseInsertResult(answer);
                anuncio.Url = $"{Requests.RevolicoModifyUrl}?key={insertResult.FullId}";
                _log.LogWarning($"ReplaceInsert {anuncio.Id} {insertResult.FullId}");

                // Delete from Revolico
                await DeleteFromRevolico(formDeleteAnuncio);

                result = new ReinsertResult(anuncio);
            }
            catch (Exception ex)
            {
                result = new ReinsertResult(anuncio, ex);
            }

            return(result);
        }
Ejemplo n.º 2
0
        public async Task CheckAllTemporizadores()
        {
            try
            {
                DateTime UtcCuba = DateTime.Now.ToUtcCuba();
                TimeSpan ini     = new TimeSpan(0, 15, 0);
                TimeSpan fin     = new TimeSpan(23, 50, 0);
                if (ini > UtcCuba.TimeOfDay || UtcCuba.TimeOfDay > fin)
                {
                    return;
                }

                IEnumerable <Temporizador> list = await _temporizadorService.GetRunning();

                List <Task <IEnumerable <Anuncio> > > getAnunciosTasks = new List <Task <IEnumerable <Anuncio> > >();

                foreach (Temporizador t in list)
                {
                    getAnunciosTasks.Add(_anuncioService.GetAnunciosToUpdate(t.GrupoId, t.Etapa));
                }

                await Task.WhenAll(getAnunciosTasks);
                await SaveChanges();

                List <Anuncio>  listAnuncios = new List <Anuncio>();
                int             len          = getAnunciosTasks.Count;
                List <Registro> registros    = new List <Registro>(len);
                double          costo;
                for (int i = 0; i < len; i++)
                {
                    Task <IEnumerable <Anuncio> > item = getAnunciosTasks[i];
                    Temporizador temp = list.ElementAt(i);
                    if (item.IsCompletedSuccessfully && item.Result.Any())
                    {
                        listAnuncios.AddRange(item.Result);

                        costo = await _financieroService.CostoAnuncio(temp.UserId);

                        int CapResueltos = item.Result.Count();

                        Registro reg = new Registro(temp.UserId, CapResueltos, UtcCuba, costo);
                        registros.Add(reg);
                    }
                }

                IEnumerable <Anuncio> anunciosFromQueue = await _queueService.GetAnunciosFromQueue();

                listAnuncios.AddRange(anunciosFromQueue);

                listAnuncios = listAnuncios.GroupBy(a => a.GetUriId).Select(b => b.First()).ToList();
                if (listAnuncios.Any())
                {
                    await _registroService.AddRegistros(registros);

                    _log.LogWarning(string.Format("!!! ---- >>> Queue Messages {0}", listAnuncios.Count()));

                    List <CaptchaKeys> captchaKeys  = (await _captchaService.GetCaptchaKeyAsync()).ToList();
                    List <Emails>      randomEmails = (await _emailRandomService.GetList()).ToList();

                    int idxCaptcha  = 0,
                        idxEmail    = (new Random(DateTime.Now.Millisecond)).Next(0, randomEmails.Count),
                        lenCaptchas = captchaKeys.Count,
                        lenEmails   = randomEmails.Count,
                        cntAnuncios = 0;
                    List <Task <ReinsertResult> > reinsertTask = new List <Task <ReinsertResult> >();
                    foreach (Anuncio an in listAnuncios)
                    {
                        cntAnuncios++;
                        reinsertTask.Add(_anuncioService.ReInsert(an, captchaKeys[idxCaptcha].Key, randomEmails[idxEmail].Email));
                        idxCaptcha = (idxCaptcha + 1) % lenCaptchas;
                        idxEmail   = (idxEmail + 1) % lenEmails;

                        if (cntAnuncios == 30)
                        {
                            await Task.Delay(TimeSpan.FromSeconds(30));

                            cntAnuncios = 0;
                        }
                    }

                    await Task.WhenAll(reinsertTask);

                    List <Anuncio> anunciosProcesados = new List <Anuncio>(),
                                   anunciosEliminados = new List <Anuncio>();
                    len = reinsertTask.Count;
                    for (int i = 0; i < len; i++)
                    {
                        Task <ReinsertResult> taskResult = reinsertTask[i];
                        ReinsertResult        result     = taskResult.Result;
                        if (taskResult.IsCompletedSuccessfully && taskResult.Result.Success)
                        {
                            Anuncio an = result.Anuncio;
                            an.Procesando = 0;
                            anunciosProcesados.Add(an);
                        }
                        else
                        {
                            DateTime dateTime = DateTime.Now.ToUtcCuba();
                            if (result.HasException)
                            {
                                _log.LogWarning($"{result.Anuncio.GetUriId} | {result.Exception.Message} | {result.Exception.StackTrace}");
                            }

                            if (result.IsBaned)
                            {
                                dateTime = dateTime.AddMinutes(2);
                            }

                            if (result.NonRemoved)
                            {
                                int    pos = result.Exception.Message.IndexOf("https");
                                string url = result.Exception.Message.Substring(pos);
                                await _removeRepository.AddAsync(new RemoveQueue()
                                {
                                    Url = url
                                });

                                Anuncio an = result.Anuncio;
                                an.Procesando = 0;
                                anunciosProcesados.Add(an);
                                continue;
                            }

                            if (result.IsDeleted)
                            {
                                Anuncio an = result.Anuncio;
                                an.Procesando = 0;
                                an.Enable     = false;
                                an.Eliminado  = true;
                                anunciosEliminados.Add(result.Anuncio);
                                continue;
                            }

                            if (result.Despublicado)
                            {
                                Anuncio an = result.Anuncio;
                                an.Procesando   = 0;
                                an.Enable       = false;
                                an.Despublicado = true;
                                anunciosEliminados.Add(result.Anuncio);
                                continue;
                            }

                            if (!result.BadCaptcha && !result.RevolicoError)
                            {
                                Anuncio an = result.Anuncio;
                                an.Procesando = 0;
                                continue;
                            }

                            await _queueService.Add(result.Anuncio.Id, dateTime);
                        }
                    }

                    await SaveChanges();

                    await _anuncioService.NotifyDelete(anunciosEliminados);

                    int    totalProcesados = anunciosProcesados.Count;
                    int    totalAnuncios   = listAnuncios.Count();
                    double pct             = 100.0 * totalProcesados / totalAnuncios;
                    _log.LogWarning(string.Format("!!! ---- Actualizados correctamente {0} de {1} | {2}%", totalProcesados, totalAnuncios, pct));

                    //int verifyPub = await _validationService.VerifyPublication(anunciosProcesados.Select(a => a.Id).ToList());
                    //double pctVerify = 100.0 * verifyPub / totalProcesados;
                    //_log.LogWarning(string.Format("!!! ---- Mostrados correctamente {0} de {1} | {2}%", verifyPub, totalProcesados, pct));
                }
            }
            catch (Exception ex)
            {
                _log.LogError(ex.ToExceptionString());
            }
        }