public Action EndQuestionCommand(Message message)
 {
     return(() =>
     {
         _queueService.Add(new QueueMessage(message.Chat.Id, message.MessageId, false)
         {
             Text = QuizMessageDictionary.EndMessage,
             ReplyMarkup = BotHelper.GetRemoveKeyboard()
         });
     });
 }
Exemplo 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());
            }
        }
Exemplo n.º 3
0
 public Action Command(QueueMessage queueMessage)
 {
     return(() => { _queueService.Add(queueMessage); });
 }
Exemplo n.º 4
0
        /// <summary>
        /// Initialize the tour
        /// </summary>
        private void Initialize()
        {
            Stations          = new List <StationManager>();
            waitingList       = new List <Plane>();
            arrivalNextStep   = new Dictionary <int, string>();
            departureNextStep = new Dictionary <int, string>();

            //Get the relations (that gives the next steps) from the database (to not be hardcoded)
            var relations = stationRepository.GetRelations();

            #region Initialize the next steps Dictionarries
            var departureRelations = relations.Where(r => r.State == FlightState.Departure);
            foreach (var relation in departureRelations)
            {
                departureNextStep.Add(relation.StationId, relation.NextStepId);
            }

            var arrivalRelations = relations.Where(r => r.State == FlightState.Arrival);
            foreach (var relation in arrivalRelations)
            {
                arrivalNextStep.Add(relation.StationId, relation.NextStepId);
            }
            #endregion

            //Add the relations to the queue service (that create dinamicly the queues we need)
            queueService.Add(relations);

            //Get the stations from the database to create them
            var dalStations = stationRepository.GetCurrentStationsState();

            foreach (var station in dalStations)
            {
                var stationManager = new StationManager(station.StepKey, station.Number, queueService);

                //When the station fires the event that she took a new plane
                stationManager.TookNewPlane += (sender, e) =>
                {
                    //Will tell the server that a plane moved
                    onPlaneMoved?.Invoke(sender, e);
                };

                //When the station fires the event that a plane finished her job (but he still stays in the station until the other station take him from the queue)
                stationManager.PlaneFinished += (sender, e) =>
                {
                    if (sender is Plane plane)
                    {
                        //Get the next step
                        var nextStep = GetNextMove(plane);

                        if (nextStep != null)
                        {
                            //Put the plane in the queue of the next step he needs to go (and the next station will take it when she is available)
                            queueService.EnQueue(nextStep, plane);
                        }
                        //if it was the final move of the plane
                        else
                        {
                            //Release the final station from the plane
                            plane.FinishWay();
                            //Tells the server the plane moved
                            onPlaneMoved?.Invoke(plane, e);
                        }
                    }
                };

                Stations.Add(stationManager);
            }

            waitingTimer          = new Timer(15000);
            waitingTimer.Elapsed += WaitingTimer_Elapsed;
            waitingTimer.Start();
        }