Beispiel #1
0
        public static Boolean SaveNewspaper(Newspaper np)
        {
            SQLiteConnection connection = DatabaseConnectionHandler.Invoke();

            string sql = $"select count(*) from {TableNames.Newspapers} where s_link='{np.s_link}'";
            int    t   = connection.QueryFirst <int>(sql);

            if (t != 0) // проверка наличия новости в БД
            {
                return(true);
            }

            np.id = MainWindow.LastDBIdent;
            MainWindow.LastDBIdent++;

            try
            {
                sql = $"insert into {TableNames.NewspaperHeader} (s_text) " +
                      $"values ('{np.s_header}');";
                connection.Execute(sql);

                int headerId =
                    connection.QueryFirst <int>($"select id from " +
                                                $"{TableNames.NewspaperHeader} " +
                                                $"where s_text='{np.s_header}'");

                sql = $"insert into {TableNames.NewspaperDescription} " +
                      $"(s_text) values ('{np.s_description}');";
                connection.Execute(sql);

                int descriptionId =
                    connection.QueryFirst <int>($"select id from " +
                                                $"{TableNames.NewspaperDescription} " +
                                                $"where s_text='{np.s_description}'");

                sql = $"insert into {TableNames.NewspaperFullText} " +
                      $"(id, s_text, i_is_parsed) values ({np.id}, " +
                      $"'{np.s_full_text}', {np.i_is_parsed});";
                connection.Execute(sql);

                sql = $"insert into {TableNames.Newspapers} (i_thematic_id, " +
                      $"i_header_id, i_source_id, s_date, i_is_read, i_description_id, s_link) " +
                      $"values ({np.i_thematic_id}, {headerId}, {np.i_source_id}, " +
                      $"'{np.s_date}', {0}, {descriptionId}, '{np.s_link}');";
                connection.Execute(sql);
            }
            catch (Exception ex)
            {
                Console.WriteLine("error in newspaper save: " + ex.Message);
                return(false); // если ломается запрос в БД, то потом могут воникнуть проблемы с обработкой полной новости.
            }

            return(true);
        }
        private void TryLoadLink(NewsSource source)
        {
            HttpWebRequest  req  = (HttpWebRequest)WebRequest.Create(source.s_rss_link);
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

            Encoding enc; // некоторые сайты не возвращают кодировку

            try
            {
                enc = Encoding.GetEncoding(resp.CharacterSet);
            }
            catch (System.ArgumentException)
            {
                Console.WriteLine("enc");
                enc = Encoding.UTF8;
            }

            StreamReader sr = new StreamReader(resp.GetResponseStream(), enc);

            using (XmlReader reader = XmlReader.Create(new StringReader(sr.ReadToEnd())))
            {
                var formatter = new Rss20FeedFormatter();
                formatter.ReadFrom(reader);

                string tempName = formatter.Feed.Title.Text;
                source.s_name = tempName.Substring(0, tempName.Length < 18 ? tempName.Length : 18);

                foreach (SyndicationItem syndItem in formatter.Feed.Items)
                {
                    Newspaper np = new Newspaper();
                    try
                    {
                        np.i_thematic_id =
                            DataBase.GetThematicID(syndItem.Categories.Count != 0
                                ? syndItem.Categories.First().Name
                                : "-");
                        np.s_header      = syndItem.Title.Text.Replace("'", "");
                        np.s_description = syndItem.Summary?.Text.Replace("'", "");
                        np.s_date        = syndItem.PublishDate.DateTime.ToString();
                        np.i_source_id   = source.id;
                        np.s_link        = syndItem.Links[0].Uri.ToString();
                        np.i_is_read     = false;
                        DataBase.SaveNewspaper(np);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("np (rss adding) parsing error ");
                    }
                }
            }
        }
Beispiel #3
0
        private void ListBoxNewHeaders_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                Newspaper        selectedItem = (Newspaper)e.AddedItems[0];
                SQLiteConnection connection   = DatabaseConnectionHandler.Invoke();

                BuildFullTextView(selectedItem);

                selectedItem.i_is_read = true;
                string sql = $"update {TableNames.Newspapers} set " +
                             $"i_is_read=1 where id={selectedItem.id}";
                connection.Execute(sql);
            }
        }
Beispiel #4
0
        private void BuildFullTextView(Newspaper np)
        {
            GridScrollView.Children.Clear();

            SQLiteConnection connection = DatabaseConnectionHandler.Invoke();
            String           sql        = $"select s_text from {TableNames.NewspaperFullText} " +
                                          $"where id={np.id}";
            string fullText = "";

            try
            {
                fullText = connection.QueryFirst <String>(sql);
            }
            catch (Exception ex)
            {
                Console.WriteLine("full text loading error, np id=" + np.id);
            }

            String thematic = connection.QueryFirst <String>(
                $"select s_name from {TableNames.Thematic} where id={np.i_thematic_id}");

            GridScrollView.RowDefinitions.Add(new RowDefinition());
            GridScrollView.VerticalAlignment = VerticalAlignment.Top;
            var tb = new TextBlock();

            tb.Inlines.Clear();
            Hyperlink hyperLink = new Hyperlink()
            {
                NavigateUri = new Uri(np.s_link)
            };

            hyperLink.RequestNavigate += Hyperlink_RequestNavigate;
            hyperLink.Foreground       = (SolidColorBrush)(new BrushConverter().ConvertFrom("#d9d9d9"));
            hyperLink.Inlines.Add(new Run("Открыть в браузере")
            {
                FontWeight = FontWeights.Normal
            });
            tb.Inlines.Add(hyperLink);
            tb.FontSize   = 20;
            tb.Foreground = (SolidColorBrush)(new BrushConverter().ConvertFrom("#d9d9d9"));
            GridScrollView.Children.Add(tb);
            Grid.SetRow(tb, GridScrollView.RowDefinitions.Count - 1);
            Grid.SetColumnSpan(tb, 2);

            if (thematic != "-")
            {
                var tb6 = new TextBlock();
                tb6.Text          = thematic;
                tb6.TextAlignment = TextAlignment.Right;
                tb6.FontSize      = 20;
                tb6.Foreground    = (SolidColorBrush)(new BrushConverter().ConvertFrom("#d9d9d9"));
                GridScrollView.Children.Add(tb6);
                Grid.SetRow(tb6, GridScrollView.RowDefinitions.Count - 1);
                Grid.SetColumn(tb6, 1);
            }

            GridScrollView.RowDefinitions.Add(new RowDefinition());
            var rect = new System.Windows.Shapes.Rectangle();

            rect.Height = 1;
            rect.Fill   = Brushes.Gray;
            GridScrollView.Children.Add(rect);
            Grid.SetRow(rect, GridScrollView.RowDefinitions.Count - 1);
            Grid.SetColumnSpan(rect, 2);


            GridScrollView.RowDefinitions.Add(new RowDefinition());
            var tb3 = new TextBlock();

            tb3.Text         = "\n" + np.s_header + "\n";
            tb3.Foreground   = (SolidColorBrush)(new BrushConverter().ConvertFrom("#f5f5f5"));
            tb3.TextWrapping = TextWrapping.Wrap;
            tb3.FontWeight   = FontWeights.Bold;
            tb3.FontSize     = 28;
            GridScrollView.Children.Add(tb3);
            Grid.SetRow(tb3, GridScrollView.RowDefinitions.Count - 1);
            Grid.SetColumnSpan(tb3, 2);


            GridScrollView.RowDefinitions.Add(new RowDefinition());
            var tb2 = new TextBlock();

            tb2.Text         = fullText.Length == 0 ? np.s_description : fullText;
            tb2.Foreground   = (SolidColorBrush)(new BrushConverter().ConvertFrom("#f5f5f5"));
            tb2.TextWrapping = TextWrapping.Wrap;
            tb2.FontSize     = 20;
            GridScrollView.Children.Add(tb2);
            Grid.SetRow(tb2, GridScrollView.RowDefinitions.Count - 1);
            Grid.SetColumnSpan(tb2, 2);


            SQLiteConnection conn = DatabaseConnectionHandler.Invoke();

            sql = $"select i_local_address_id from " +
                  $"{TableNames.Images} where i_newspaper_id={np.id}";
            List <int> localAddressIds = conn.Query <int>(sql).ToList();

            foreach (int localAddressId in localAddressIds) // загрузка всех картинок
            {
                sql = $"select s_path from {TableNames.LocalFileAddress} where id={localAddressId};";
                string localPath = conn.QueryFirst <string>(sql);
                var    img       = new System.Windows.Controls.Image();

                try
                {
                    img.Source = new BitmapImage(new Uri(Directory.GetCurrentDirectory() + "\\" + localPath));
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"error in image loading: {localPath} // {ex.Message}");
                    continue;
                }

                GridScrollView.RowDefinitions.Add(new RowDefinition());
                GridScrollView.Children.Add(img);
                Grid.SetRow(img, GridScrollView.RowDefinitions.Count - 1);
                Grid.SetColumnSpan(img, 2);
            }
        }
Beispiel #5
0
        public List <Newspaper> DownloadAndParseRSS(List <NewsSource> newsSources)
        {
            List <Newspaper> news = new List <Newspaper>();

            foreach (NewsSource source in newsSources)
            {
                if (_updateRSSWorker.CancellationPending)
                {
                    return(new List <Newspaper>());
                }

                HttpWebRequest  req  = (HttpWebRequest)WebRequest.Create(source.s_rss_link);
                HttpWebResponse resp = null;
                try
                {
                    resp = (HttpWebResponse)req.GetResponse();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("rss get error: " + source.s_rss_link + " ## " + ex.Message);
                    continue;
                }

                Encoding enc; // некоторые сайты не возвращают кодировку
                try
                {
                    enc = Encoding.GetEncoding(resp.CharacterSet);
                }
                catch (System.ArgumentException)
                {
                    //Console.WriteLine("set default encoding: " + resp.CharacterSet + " site: " + source.s_rss_link);
                    enc = Encoding.UTF8;
                }

                StreamReader sr = new StreamReader(resp.GetResponseStream(), enc);

                using (XmlReader reader = XmlReader.Create(new StringReader(sr.ReadToEnd())))
                {
                    var formatter = new Rss20FeedFormatter();
                    try
                    {
                        formatter.ReadFrom(reader);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("error in rss parsing: " + ex.Message);
                        continue;
                    }
                    foreach (SyndicationItem syndItem in formatter.Feed.Items)
                    {
                        Newspaper np = new Newspaper();

                        try
                        {
                            np.i_thematic_id = DataBase.GetThematicID(syndItem.Categories.Count != 0 ?
                                                                      syndItem.Categories.First().Name : "-");
                            np.s_header      = syndItem.Title.Text.Replace("'", "");
                            np.s_description = syndItem.Summary?.Text.Replace("'", "");
                            np.s_date        = syndItem.PublishDate.DateTime.ToString();
                            np.i_source_id   = source.id;
                            np.s_link        = syndItem.Links[0].Uri.ToString();
                            np.i_is_read     = false;
                            news.Add(np);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("np (rss updating) parsing error ");
                        }
                    }
                }

                Console.WriteLine(source.s_name + " done");
            }

            return(news);
        }