Exemplo n.º 1
0
        //TODO передать токен для отмены ниже по стеку
        public void StartMonitoring(CancellationTokenSource tokenSource, DateTime startDate, DateTime endDate, string hashTag, Action stopService)
        {
            EventLog.WriteEntry(EventTarget, string.Format("Monitoring start with pararams: startData - {0} endDate - {1} HashTag - #{2}", startDate, endDate, hashTag), EventLogEntryType.Information);
            endDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, endDate.Hour, endDate.Minute, endDate.Second);
            var thread = new Thread(() =>
            {
                var printed    = new List <string>();
                string nextUrl = null;
                while (!tokenSource.IsCancellationRequested)
                {
                    try
                    {
                        if (DateTime.Now.Ticks >= endDate.Ticks)
                        {
                            break;
                        }
                        Task.Delay(TimeSpan.FromSeconds(5)).Wait();

                        ImageResponse result = string.IsNullOrEmpty(nextUrl)
                             ? _instagramExplorer.GetImagesByHashTag(hashTag, "", tokenSource.Token).Result
                             : _instagramExplorer.GetImagesFromUrl(nextUrl, tokenSource.Token).Result;

                        nextUrl            = result.Return(x => x.NextUrl, null);
                        long?lastPhotoTime = _imageRep.GetLastPhotoTimeCurrentSession();

                        foreach (var image in result.Images)
                        {
                            if (image.CreatedTime < _startTime.Ticks || image.CreatedTime <= lastPhotoTime)
                            {
                                nextUrl = null;
                                printed.Add(image.Url);
                            }
                            if (printed.Contains(image.Url))
                            {
                                continue;
                            }
                            _imageRep.SetLastPhotoTimeCurrentSession(image.CreatedTime);
                            _imageRep.Commit();
                            printed.Add(image.Url);

                            _messageAdapter.Print(image, _printerName);
                        }
                    }
                    catch (Exception ex)
                    {
                        EventLog.WriteEntry(EventTarget, string.Format("Error process image:{0}\n{1}", ex.Message, ex.StackTrace), EventLogEntryType.Information);
                    }
                }
                EventLog.WriteEntry(EventTarget, "Monitoring stop", EventLogEntryType.Information);
                stopService();
            });

            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
        }