XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFENewsApplication

【WinUI】新闻软件

公开
关注 0 Fork 0 Star 0
返回提交历史

XFEstudio/XFENewsApplication

初步完成MSN新闻

4d04415
XFE工作室室长 <mail@xfegzs.com>
提交于

代码差异

15 个文件 +250 -9
Added XFENewsApplication.Core/Models/NewsSource.cs +12 -0
@@ -0,0 +1,12 @@
1 namespace XFENewsApplication.Core.Models;
2
3 public class NewsSource
4 {
5 public required string Title { get; set; }
6 public required string Url { get; set; }
7 public string? ID { get; set; }
8 public string? Authors { get; set; }
9 public string? PublishTime { get; set; }
10 public string? Abstract { get; set; }
11 public string? ImageUrl { get; set; }
12 }
Added XFENewsApplication.Core/Utilities/Helpers/ClimbHelper.cs +54 -0
@@ -0,0 +1,54 @@
1 using System.Text.Json;
2 using XFEExtension.NetCore.StringExtension;
3 using XFEExtension.NetCore.XFETransform.JsonConverter;
4 using XFENewsApplication.Core.Models;
5
6 namespace XFENewsApplication.Core.Utilities.Helpers;
7
8 public static class ClimbHelper
9 {
10 public static string? MSNAPI { get; set; }
11 public static async Task<List<NewsSource>> ClimbMSNNews()
12 {
13 var resultList = new List<NewsSource>();
14 int reTryTimes = 0;
15 using var client = new HttpClient();
16 client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36 Edg/129.0.0.0");
17 while (reTryTimes < 5)
18 try
19 {
20 if (MSNAPI.IsNullOrWhiteSpace())
21 {
22 QueryableJsonNode authJsonNode = await client.GetStringAsync("https://www.msn.cn/resolver/api/resolve/v3/config/?expType=AppConfig&expInstance=default&apptype=homePage&v=20250401.183&targetScope={%22audienceMode%22:%22adult%22,%22browser%22:{%22browserType%22:%22edgeChromium%22,%22version%22:%22135%22,%22ismobile%22:%22false%22},%22deviceFormFactor%22:%22desktop%22,%22domain%22:%22www.msn.cn%22,%22locale%22:{%22content%22:{%22language%22:%22zh%22,%22market%22:%22cn%22},%22display%22:{%22language%22:%22zh%22,%22market%22:%22cn%22}},%22os%22:%22windows%22,%22platform%22:%22web%22,%22pageType%22:%22hp%22,%22pageExperiments%22:[]}");
23 MSNAPI = authJsonNode["configs"]["StripeWC/default"]["properties"]["apikey"];
24 }
25 var result = await client.GetStringAsync($"https://assets.msn.com/service/news/feed/pages/weblayout?User=&activityId=&adoffsets=c1:-1,c2:-1&apikey={MSNAPI}&audienceMode=adult&cm=zh-cn&colstatus=c1:0,c2:0&column=c2&colwidth=300&contentType=article,video,slideshow,webcontent&it=edgeid&l3v=2&layout=c2&memory=8&newsSkip=0&newsTop=48&ocid=hponeservicefeed&pgc=11&private=1&scn=APP_ANON&timeOut=1000&vpSize=721x674&wposchema=byregion");
26 using var document = JsonDocument.Parse(result);
27 int i = 0;
28 foreach (var subNode in document.RootElement.GetProperty("sections").EnumerateArray().ElementAt(0).GetProperty("cards").EnumerateArray())
29 {
30 try
31 {
32 if (i++ == 0)
33 continue;
34 resultList.Add(new NewsSource
35 {
36 Title = subNode.GetProperty("title").GetString()!,
37 Url = subNode.GetProperty("url").GetString()!,
38 ID = subNode.GetProperty("id").GetString(),
39 Abstract = subNode.GetProperty("abstract").GetString()
40 });
41 }
42 catch { }
43 }
44 break;
45 }
46 catch
47 {
48 reTryTimes++;
49 }
50 if (reTryTimes >= 5)
51 throw new Exception("无法获取新闻,请检查网络连接");
52 return resultList;
53 }
54 }
Modified XFENewsApplication.Core/XFENewsApplication.Core.csproj +4 -0
@@ -18,4 +18,8 @@
18 18 </COMReference>
19 19 </ItemGroup>
20 20
21 <ItemGroup>
22 <PackageReference Include="XFEExtension.NetCore" Version="3.3.1" />
23 </ItemGroup>
24
21 25 </Project>
Added XFENewsApplication/Implements/Services/WebViewService.cs +10 -0
@@ -0,0 +1,10 @@
1 using XFENewsApplication.Interface.Services;
2
3 namespace XFENewsApplication.Implements.Services;
4
5 public class WebViewService : IWebViewService
6 {
7 private WebView2? webView;
8 public WebView2 WebView { get => webView ?? throw new NullReferenceException(); set => webView = value; }
9 public bool IsWebViewLoaded { get => WebView.IsLoaded; }
10 }
Added XFENewsApplication/Interface/Services/IWebViewService.cs +24 -0
@@ -0,0 +1,24 @@
1 using Windows.Foundation;
2
3 namespace XFENewsApplication.Interface.Services;
4
5 public interface IWebViewService
6 {
7 public WebView2 WebView { get; set; }
8 public bool IsWebViewLoaded { get; }
9 public Uri? Url { get => WebView.Source; set => WebView.Source = value; }
10
11 public IAsyncOperation<string> ExecuteScriptAsync(string javascriptCode) => WebView.ExecuteScriptAsync(javascriptCode);
12
13 public void Reload() => WebView.Reload();
14
15 public void GoForward() => WebView.GoForward();
16
17 public void GoBack() => WebView.GoBack();
18
19 public void NavigateToString(string htmlContent) => WebView.NavigateToString(htmlContent);
20
21 public void Close() => WebView.Close();
22
23 public void Initialize(WebView2 webView2) => WebView = webView2;
24 }
Modified XFENewsApplication/MainWindow.xaml.cs +1 -1
@@ -13,7 +13,7 @@ public sealed partial class MainWindow : Window
13 13 {
14 14 this.InitializeComponent();
15 15 ExtendsContentIntoTitleBar = true;
16 //AppWindow.SetIcon(Path.Combine(AppContext.BaseDirectory, "Assets/Icons/EditorIcon.ico"));
16 AppWindow.SetIcon(Path.Combine(AppContext.BaseDirectory, "Assets/Icons/EditorIcon.ico"));
17 17 AppWindow.TitleBar.PreferredHeightOption = Microsoft.UI.Windowing.TitleBarHeightOption.Tall;
18 18 UISettings.ColorValuesChanged += (_, _) => DispatcherQueue.TryEnqueue(() => AppThemeHelper.ChangeTheme(AppThemeHelper.Theme));
19 19 }
Modified XFENewsApplication/Profiles/CrossVersionProfiles/SystemProfile.cs +3 -0
@@ -11,5 +11,8 @@ public partial class SystemProfile : XFEProfile
11 11 [ProfileProperty]
12 12 private ElementTheme theme = ElementTheme.Default;
13 13
14 [ProfileProperty]
15 private double sideBarWidth = 450;
16
14 17 static partial void SetThemeProperty(ref ElementTheme value) => AppThemeHelper.ChangeTheme(value);
15 18 }
Added XFENewsApplication/ViewModels/NewsViewPageViewModel.cs +85 -0
@@ -0,0 +1,85 @@
1 using CommunityToolkit.Mvvm.ComponentModel;
2 using CommunityToolkit.Mvvm.Input;
3 using System.Collections.ObjectModel;
4 using System.Text.Json;
5 using XFEExtension.NetCore.WinUIHelper.Interface.Services;
6 using XFEExtension.NetCore.WinUIHelper.Utilities;
7 using XFEExtension.NetCore.XFETransform.JsonConverter;
8 using XFENewsApplication.Core.Models;
9 using XFENewsApplication.Core.Utilities.Helpers;
10 using XFENewsApplication.Implements.Services;
11 using XFENewsApplication.Interface.Services;
12 using XFENewsApplication.Profiles.CrossVersionProfiles;
13
14 namespace XFENewsApplication.ViewModels;
15
16 public partial class NewsViewPageViewModel : ViewModelBase
17 {
18 [ObservableProperty]
19 int selectedIndex = -1;
20 [ObservableProperty]
21 double sideBarWidth = SystemProfile.SideBarWidth;
22 private List<NewsSource> newsList = [];
23 public INavigationParameterService<string> NavigationParameterService { get; set; } = ServiceManager.GetService<INavigationParameterService<string>>();
24 public INavigationViewService? NavigationViewService { get; set; } = ServiceManager.GetService<INavigationViewService>();
25 public IListViewService ListViewService { get; set; } = ServiceManager.GetService<IListViewService>();
26 public IDialogService DialogService { get; set; } = ServiceManager.GetService<IDialogService>();
27 public IWebViewService WebViewService { get; set; } = new WebViewService();
28 public ObservableCollection<NewsSource> NewsList { get; } = [];
29
30 public NewsViewPageViewModel()
31 {
32 NavigationParameterService.ParameterChange += NavigationParameterService_ParameterChange;
33 ListViewService.SelectionChanged += ListViewService_SelectionChanged;
34 }
35
36 private async void ListViewService_SelectionChanged(object sender, SelectionChangedEventArgs e)
37 {
38 using var client = new HttpClient();
39 client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36 Edg/129.0.0.0");
40 try
41 {
42 if (ListViewService.ListView.SelectedItem is NewsSource newsSource)
43 {
44 var result = await client.GetStringAsync($"https://assets.msn.cn/content/view/v2/Detail/zh-cn/{newsSource.ID}");
45 var document = JsonDocument.Parse(result);
46 await WebViewService.WebView.EnsureCoreWebView2Async();
47 WebViewService.NavigateToString($"<h1>{document.RootElement.GetProperty("title")}</h1>\n{document.RootElement.GetProperty("body")}");
48 }
49 }
50 catch (Exception ex)
51 {
52 await WebViewService.WebView.EnsureCoreWebView2Async();
53 WebViewService.NavigateToString($"<h1>{ex.Message}</h1>\n<p>{ex}</p>");
54 }
55 }
56
57 private async void NavigationParameterService_ParameterChange(object? sender, string? e)
58 {
59 switch (e)
60 {
61 case "MSN":
62 await GetNews();
63 SelectedIndex = 0;
64 break;
65 default:
66 break;
67 }
68 }
69
70 private void LoadNewsSource(IEnumerable<NewsSource> newsSources)
71 {
72 foreach (var news in newsSources)
73 NewsList.Add(news);
74 }
75
76 [RelayCommand]
77 async Task GetNews()
78 {
79 await Task.Run(async () =>
80 {
81 newsList = await ClimbHelper.ClimbMSNNews();
82 });
83 LoadNewsSource(newsList);
84 }
85 }
Modified XFENewsApplication/Views/AppShellPage.xaml +3 -0
@@ -32,6 +32,9 @@
32 32 </Grid>
33 33 </Grid>
34 34 <NavigationView x:Name="navigationView" IsBackButtonVisible="Visible" Canvas.ZIndex="0" IsBackEnabled="{x:Bind ViewModel.CanGoBack, Mode=OneWay}" IsSettingsVisible="False" DisplayModeChanged="NavigationView_DisplayModeChanged" PaneOpening="NavigationView_PaneOpening" PaneOpened="NavigationView_PaneOpened" PaneClosing="NavigationView_PaneClosing" PaneClosed="NavigationView_PaneClosed">
35 <NavigationView.AutoSuggestBox>
36 <AutoSuggestBox QueryIcon="Find" PlaceholderText="搜索新闻源"/>
37 </NavigationView.AutoSuggestBox>
35 38 <NavigationView.MenuItems>
36 39 <NavigationViewItem Content="MSN新闻" add:NavigationAddition.NavigateTo="XFENewsApplication.Views.NewsViewPage" add:NavigationAddition.NavigateParameter="MSN">
37 40 <NavigationViewItem.Icon>
Modified XFENewsApplication/Views/AppShellPage.xaml.cs +1 -1
@@ -18,7 +18,7 @@ public sealed partial class AppShellPage : Page
18 18 ViewModel.NavigationViewService.Initialize(navigationView, navigationFrame);
19 19 ViewModel.MessageService.Initialize(messageStackPanel, DispatcherQueue);
20 20 ViewModel.LoadingService.Initialize(loadingGrid, globalLoadingGrid, globalLoadingTextBlock, DispatcherQueue, ViewModel.NavigationViewService.NavigationService);
21 ViewModel.NavigationViewService.NavigateTo<NewsViewPage>();
21 ViewModel.NavigationViewService.NavigateTo<NewsViewPage>("MSN");
22 22 }
23 23
24 24 private void NavigationView_DisplayModeChanged(NavigationView sender, NavigationViewDisplayModeChangedEventArgs args)
Modified XFENewsApplication/Views/NewsViewPage.xaml +31 -1
@@ -4,11 +4,41 @@
4 4 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
5 5 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
6 6 xmlns:local="using:XFENewsApplication.Views"
7 xmlns:coremodel="using:XFENewsApplication.Core.Models"
8 xmlns:controls="using:CommunityToolkit.WinUI.Controls"
7 9 xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
8 10 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
9 11 mc:Ignorable="d">
10 12
11 13 <Grid>
12
14 <Grid.ColumnDefinitions>
15 <ColumnDefinition Width="Auto"/>
16 <ColumnDefinition Width="Auto"/>
17 <ColumnDefinition/>
18 </Grid.ColumnDefinitions>
19 <Border x:Name="sideBar" MinWidth="300" MaxWidth="800" Width="{x:Bind ViewModel.SideBarWidth, Mode=TwoWay}">
20 <ListView x:Name="newsSourceListView" ItemsSource="{x:Bind ViewModel.NewsList}" SelectionMode="Single" SelectedIndex="{x:Bind ViewModel.SelectedIndex, Mode=TwoWay}" ScrollViewer.VerticalScrollBarVisibility="Hidden">
21 <ListView.ItemTemplate>
22 <DataTemplate x:DataType="coremodel:NewsSource">
23 <StackPanel Orientation="Vertical" Padding="5,24" Spacing="12">
24 <TextBlock Text="{x:Bind Title}" MaxLines="2" Style="{StaticResource SubtitleTextBlockStyle}" TextWrapping="Wrap"/>
25 <TextBlock Text="{x:Bind Abstract}" MaxLines="3" Foreground="{ThemeResource TextFillColorSecondaryBrush}" TextWrapping="Wrap"/>
26 </StackPanel>
27 </DataTemplate>
28 </ListView.ItemTemplate>
29 <ListView.ItemContainerStyle>
30 <Style TargetType="ListViewItem" BasedOn="{StaticResource DefaultListViewItemStyle}">
31 <Setter Property="Margin" Value="0,0,0,2"/>
32 <Setter Property="CornerRadius" Value="12"/>
33 </Style>
34 </ListView.ItemContainerStyle>
35 </ListView>
36 </Border>
37 <controls:ContentSizer Grid.Column="1" TargetControl="{x:Bind sideBar}" CornerRadius="4"/>
38 <Grid Grid.Column="2">
39 <ScrollView>
40 <StackPanel x:Name="contentStackPanel" Orientation="Vertical" Spacing="10"/>
41 </ScrollView>
42 </Grid>
13 43 </Grid>
14 44 </Page>
Modified XFENewsApplication/Views/NewsViewPage.xaml.cs +16 -1
@@ -1,12 +1,27 @@
1 namespace XFENewsApplication.Views;
1 using Microsoft.UI.Xaml.Navigation;
2
3 namespace XFENewsApplication.Views;
2 4
3 5 /// <summary>
4 6 /// 新闻展示页面
5 7 /// </summary>
6 8 public sealed partial class NewsViewPage : Page
7 9 {
10 public string? Parameter { get; set; }
11 public static NewsViewPage? Current { get; set; }
12 public NewsViewPageViewModel ViewModel { get; set; } = new();
8 13 public NewsViewPage()
9 14 {
15 Current = this;
10 16 this.InitializeComponent();
17 ViewModel.NavigationParameterService.Initialize(this);
18 ViewModel.ListViewService.Initialize(newsSourceListView);
19 ViewModel.WebViewService.Initialize(webView);
20 }
21
22 protected override void OnNavigatedTo(NavigationEventArgs e)
23 {
24 base.OnNavigatedTo(e);
25 ViewModel.NavigationParameterService.OnParameterChange(e.Parameter);
11 26 }
12 27 }
Modified XFENewsApplication/Views/SettingPage.xaml +3 -3
Modified XFENewsApplication/Views/SettingPage.xaml.cs +1 -1
Modified XFENewsApplication/XFENewsApplication.csproj +2 -1