Пример #1
0
        public static Author AddAuthor(string url)
        {
            _logger.Add("Добавление автора...");
            // Перевести URL на samlib.ru
            url = url.ToLowerInvariant().Replace("zhurnal.lib.ru", "samlib.ru");

            // аналог DoEvents в WPF, иначе "Добавление автора..." вообще не появляется, т.к. метод синхронный
            Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate { }));

            if (!url.StartsWith("http://") && !url.StartsWith("https://"))
            {
                url = "http://" + url;
            }

            Sites.ISite site = Sites.SitesDetector.GetSite(url);

            if (site == null)
            {
                _logger.Add("Указан незнакомый адрес/домен/протокол.", true, true);
                return(null);
            }


            // Если URL заканчивается на index.shtml, преобразовать его в нужный)
            url = site.PrepareAuthorUrlOnAdding(url);


            Author author = Authors.FindAuthor(url);

            if (author != null)
            {
                _logger.Add("Этот автор уже присутствует в списке", true, true);
                return(author);
            }

            try
            {
                string pageContent = WEB.DownloadPageSilent(url);
                if (pageContent == null)
                {
                    _logger.Add("Не удалось открыть страницу автора", true, true);
                    return(null);
                }


                string   authorName = "";
                DateTime updateDate = DateTime.MinValue;
                site.GetAuthorCredentials(pageContent, out authorName, out updateDate);
                //int index = pageContent.IndexOf('.', pageContent.IndexOf("<title>")) + 1;
                //string authorName = pageContent.Substring(index, pageContent.IndexOf('.', index) - index);
                //DateTime updateDate = GetUpdateDate(pageContent);

                if (updateDate == DateTime.MinValue)
                {
                    _logger.Add("Не удалось получить дату со страницы автора", true, true);
                    return(null);
                }
                if (authorName.Trim() == "")
                {
                    _logger.Add("Не удалось получить имя автора", true, true);
                    return(null);
                }
                author = new Author {
                    Name = authorName, IsNew = false, UpdateDate = updateDate, URL = url
                };


                author.CheckID();// генерим id
                Authors.Add(author);
                author.UpdateAuthorInfo(pageContent, SynchronizationContext.Current);
                _logger.Add("Добавлен: " + author.Name);
                author.Changed = true;
            }
            catch (Exception ex)
            {
                _logger.Add(ex.StackTrace, false, true);
                _logger.Add(ex.Message, false, true);
                _logger.Add("Необработанная ошибка при добавлении автора", true, true);
            }
            return(author);
        }
Пример #2
0
        private static bool ProcessArrivedBook(TransportBookInfo book, bool isMyInfo)
        {
            if (book == null || string.IsNullOrWhiteSpace(book.AuthorLink))
            {
                return(true);
            }
            if (Authors == null)
            {
                return(true);
            }
            var author = Authors.FindAuthor(book.AuthorLink);

            if (author == null)
            {
                return(true);
            }
            var alreadyStared = author.IsNew;

            if (author.IsIgnored || author.IsDeleted)
            {
                return(true);
            }
            var authorText = author.Texts.FirstOrDefault(t => t.Link == book.Link);
            // Link  у нас - относительный путь, поэтому не преобразовываем
            bool isNew     = false;
            bool isUpdated = false;

            var convertedTime = new DateTime(book.UpdateDate, DateTimeKind.Utc).ToLocalTime();


            if (isMyInfo)
            {
                if (authorText == null)
                {
                    return(true);
                }
                // просто маркируем свои штампы серверным, не меняя локальные даты проверок
                authorText.ServerStamp = book.UpdateDate;
                author.ServerStamp     = book.UpdateDate;
            }
            else
            {
                if (authorText == null)
                {
                    authorText = new AuthorText();
                    isNew      = true;
                }
                if (authorText.ServerStamp > book.UpdateDate)
                {
                    return(true);
                }

                if (!isNew)
                {
                    book.Size = book.Size < 0 ? 0 : book.Size; // кооректируем, иногда бывает -1
                    isUpdated = ((authorText.Name != book.Name || authorText.Size != book.Size ||
                                  (_setting.SkipBookDescription ? false : authorText.Description != book.Description)));
                }
                if (!isNew && !isUpdated)
                {
                    authorText.ServerStamp = book.UpdateDate;// скорректируем локальное значение. поставим серверное
                    return(true);
                }

                _messageBrokerTrayInfoCollectorTimer.Stop();

                authorText.Description = book.Description;
                authorText.Genres      = book.Genres;
                authorText.Link        = book.Link;
                authorText.Name        = book.Name;
                authorText.SectionName = book.SectionName;

                if (!authorText.IsNew)
                {
                    authorText.SizeOld = authorText.Size;
                }

                authorText.Size        = book.Size;
                authorText.UpdateDate  = convertedTime;
                authorText.ServerStamp = book.UpdateDate; // ставим штамп сервера

                authorText.IsNew = true;
                if (isNew)
                {
                    author.Texts.Add(authorText);
                }
                author.LastCheckDate = authorText.UpdateDate;
                try
                {
                    if (author.NextCheckDate < author.LastCheckDate)
                    {
                        var elasticScheduler = new ElasticScheduler(_logger, _setting);
                        elasticScheduler.MakePlan(author);
                        elasticScheduler.SaveStatistics();
                    }
                    author.UpdateDate  = authorText.UpdateDate;
                    author.ServerStamp = book.UpdateDate; // ставим штамп сервера

                    author.IsNew = true;

                    _logger.Add(string.Format("StatServer> Уведомление: обновился {0} ({1})", author.Name, authorText.Name),
                                true, false);
                    if (!_messageBrokerTrayInfo.Contains(author.Name) && !alreadyStared)
                    {
                        _messageBrokerTrayInfo = string.IsNullOrWhiteSpace(_messageBrokerTrayInfo)
                                                     ? author.Name
                                                     : _messageBrokerTrayInfo + "; " + author.Name;
                    }
                    _messageBrokerTrayInfoCollectorTimer.Start();
                }
                catch (Exception ex)
                {
                    _logger.Add(string.Format("Ошибка формирования плана проверок автора {0} - {1}", author.Name, ex));
                }
            }
            return(false);
        }