From bc5be4f10a3db732bdbf8884f6b8474bcf1e15c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A7=9A=E5=BD=AA?= <1315508912@qq.com> Date: Tue, 5 Mar 2024 20:45:37 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=B8=B8=E5=AE=A2=E6=B7=BB=E5=8A=A0?= =?UTF-8?q?=E9=9A=8F=E6=9C=BAbuvid3=E8=A7=A3=E5=86=B3=E9=83=A8=E5=88=86?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3=E9=A3=8E=E6=8E=A7(=E7=9C=9F=E5=AE=9Ebuvid3?= =?UTF-8?q?=E6=9A=82=E6=9C=AA=E5=AE=9E=E7=8E=B0=E3=80=81=E5=90=8E=E7=BB=AD?= =?UTF-8?q?=E5=8F=AF=E4=BB=A5=E8=80=83=E8=99=91)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DownKyi.Core/BiliApi/Login/LoginHelper.cs | 4 +- .../BiliApi/Users/Models/SpacePublication.cs | 2 +- .../Users/Models/SpacePublicationList.cs | 2 +- .../BiliApi/Users/Models/UserInfoForSpace.cs | 4 +- .../BiliApi/Users/Models/UserInfoVip.cs | 2 +- DownKyi.Core/BiliApi/Users/UserInfo.cs | 51 ++--- DownKyi.Core/BiliApi/Users/UserSpace.cs | 199 ++++++++--------- DownKyi.Core/BiliApi/Video/VideoInfo.cs | 35 ++- DownKyi.Core/BiliApi/WebClient.cs | 105 ++++----- DownKyi.Core/Storage/StorageHeader.cs | 2 +- .../Utils/Encryptor/Encryptor.String.cs | 26 +-- DownKyi.Core/Utils/Encryptor/Hash.cs | 22 +- DownKyi.Core/Utils/Format.cs | 114 +++------- DownKyi.Core/Utils/HardDisk.cs | 6 +- DownKyi.Core/Utils/ObjectHelper.cs | 58 +++-- DownKyi.Core/Utils/QRCode.cs | 34 +-- DownKyi.Core/Utils/StringLogicalComparer.cs | 20 +- DownKyi/ViewModels/ViewIndexViewModel.cs | 38 ++-- DownKyi/ViewModels/ViewMySpaceViewModel.cs | 10 +- .../ViewModels/ViewPublicationViewModel.cs | 16 +- DownKyi/ViewModels/ViewUserSpaceViewModel.cs | 208 +++++++++--------- 21 files changed, 421 insertions(+), 537 deletions(-) diff --git a/DownKyi.Core/BiliApi/Login/LoginHelper.cs b/DownKyi.Core/BiliApi/Login/LoginHelper.cs index de4ce2f..d95c749 100644 --- a/DownKyi.Core/BiliApi/Login/LoginHelper.cs +++ b/DownKyi.Core/BiliApi/Login/LoginHelper.cs @@ -59,9 +59,9 @@ namespace DownKyi.Core.BiliApi.Login /// 获得登录的cookies /// /// - public static CookieContainer GetLoginInfoCookies() + public static CookieContainer? GetLoginInfoCookies() { - string tempFile = LOCAL_LOGIN_INFO + "-" + Guid.NewGuid().ToString("N"); + var tempFile = LOCAL_LOGIN_INFO + "-" + Guid.NewGuid().ToString("N"); if (File.Exists(LOCAL_LOGIN_INFO)) { diff --git a/DownKyi.Core/BiliApi/Users/Models/SpacePublication.cs b/DownKyi.Core/BiliApi/Users/Models/SpacePublication.cs index 5d183e4..29da690 100644 --- a/DownKyi.Core/BiliApi/Users/Models/SpacePublication.cs +++ b/DownKyi.Core/BiliApi/Users/Models/SpacePublication.cs @@ -6,7 +6,7 @@ namespace DownKyi.Core.BiliApi.Users.Models; // https://api.bilibili.com/x/space/arc/search public class SpacePublicationOrigin : BaseModel { - [JsonProperty("data")] public SpacePublication Data { get; set; } + [JsonProperty("data")] public SpacePublication? Data { get; set; } } public class SpacePublication : BaseModel diff --git a/DownKyi.Core/BiliApi/Users/Models/SpacePublicationList.cs b/DownKyi.Core/BiliApi/Users/Models/SpacePublicationList.cs index 03aafeb..9b3b374 100644 --- a/DownKyi.Core/BiliApi/Users/Models/SpacePublicationList.cs +++ b/DownKyi.Core/BiliApi/Users/Models/SpacePublicationList.cs @@ -6,5 +6,5 @@ namespace DownKyi.Core.BiliApi.Users.Models; public class SpacePublicationList : BaseModel { [JsonProperty("tlist")] public SpacePublicationListType Tlist { get; set; } - [JsonProperty("vlist")] public List Vlist { get; set; } + [JsonProperty("vlist")] public List? Vlist { get; set; } } \ No newline at end of file diff --git a/DownKyi.Core/BiliApi/Users/Models/UserInfoForSpace.cs b/DownKyi.Core/BiliApi/Users/Models/UserInfoForSpace.cs index afb97be..7f1b1e5 100644 --- a/DownKyi.Core/BiliApi/Users/Models/UserInfoForSpace.cs +++ b/DownKyi.Core/BiliApi/Users/Models/UserInfoForSpace.cs @@ -12,7 +12,7 @@ public class UserInfoForSpaceOrigin : BaseModel //public string Message { get; set; } //[JsonProperty("ttl")] //public int Ttl { get; set; } - [JsonProperty("data")] public UserInfoForSpace Data { get; set; } + [JsonProperty("data")] public UserInfoForSpace? Data { get; set; } } public class UserInfoForSpace : BaseModel @@ -37,7 +37,7 @@ public class UserInfoForSpace : BaseModel //public bool FansBadge { get; set; } // fans_medal // official - [JsonProperty("vip")] public UserInfoVip Vip { get; set; } + [JsonProperty("vip")] public UserInfoVip? Vip { get; set; } // pendant // nameplate diff --git a/DownKyi.Core/BiliApi/Users/Models/UserInfoVip.cs b/DownKyi.Core/BiliApi/Users/Models/UserInfoVip.cs index 203296e..00bde40 100644 --- a/DownKyi.Core/BiliApi/Users/Models/UserInfoVip.cs +++ b/DownKyi.Core/BiliApi/Users/Models/UserInfoVip.cs @@ -12,7 +12,7 @@ public class UserInfoVip : BaseModel // vip_pay_type // theme_type - [JsonProperty("label")] public UserInfoVipLabel Label { get; set; } + [JsonProperty("label")] public UserInfoVipLabel? Label { get; set; } [JsonProperty("avatar_subscript")] public int AvatarSubscript { get; set; } [JsonProperty("nickname_color")] public string NicknameColor { get; set; } diff --git a/DownKyi.Core/BiliApi/Users/UserInfo.cs b/DownKyi.Core/BiliApi/Users/UserInfo.cs index 39269de..f9e5427 100644 --- a/DownKyi.Core/BiliApi/Users/UserInfo.cs +++ b/DownKyi.Core/BiliApi/Users/UserInfo.cs @@ -15,22 +15,17 @@ public static class UserInfo /// 导航栏用户信息 /// /// - public static UserInfoForNavigation GetUserInfoForNavigation() + public static UserInfoForNavigation? GetUserInfoForNavigation() { - string url = "https://api.bilibili.com/x/web-interface/nav"; - string referer = "https://www.bilibili.com"; - string response = WebClient.RequestWeb(url, referer); + const string url = "https://api.bilibili.com/x/web-interface/nav"; + const string referer = "https://www.bilibili.com"; + var response = WebClient.RequestWeb(url, referer); try { - UserInfoForNavigationOrigin userInfo = - JsonConvert.DeserializeObject(response); - if (userInfo == null || userInfo.Data == null) - { - return null; - } + var userInfo = JsonConvert.DeserializeObject(response); - return userInfo.Data; + return userInfo?.Data; } catch (Exception e) { @@ -45,26 +40,22 @@ public static class UserInfo /// /// /// - public static UserInfoForSpace GetUserInfoForSpace(long mid) + public static UserInfoForSpace? GetUserInfoForSpace(long mid) { var parameters = new Dictionary { { "mid", mid } }; - string query = WbiSign.ParametersToQuery(WbiSign.EncodeWbi(parameters)); - string url = $"https://api.bilibili.com/x/space/wbi/acc/info?{query}"; - string referer = "https://www.bilibili.com"; - string response = WebClient.RequestWeb(url, referer); + var query = WbiSign.ParametersToQuery(WbiSign.EncodeWbi(parameters)); + var url = $"https://api.bilibili.com/x/space/wbi/acc/info?{query}"; + const string referer = "https://www.bilibili.com"; + var response = WebClient.RequestWeb(url, referer, needRandomBvuid3: true); try { - UserInfoForSpaceOrigin spaceInfo = JsonConvert.DeserializeObject(response); - if (spaceInfo == null || spaceInfo.Data == null) - { - return null; - } + var spaceInfo = JsonConvert.DeserializeObject(response); - return spaceInfo.Data; + return spaceInfo?.Data; } catch (Exception e) { @@ -78,21 +69,17 @@ public static class UserInfo /// 本用户详细信息 /// /// - public static MyInfo GetMyInfo() + public static MyInfo? GetMyInfo() { - string url = "https://api.bilibili.com/x/space/myinfo"; - string referer = "https://www.bilibili.com"; - string response = WebClient.RequestWeb(url, referer); + const string url = "https://api.bilibili.com/x/space/myinfo"; + const string referer = "https://www.bilibili.com"; + var response = WebClient.RequestWeb(url, referer); try { - MyInfoOrigin myInfo = JsonConvert.DeserializeObject(response); - if (myInfo == null || myInfo.Data == null) - { - return null; - } + var myInfo = JsonConvert.DeserializeObject(response); - return myInfo.Data; + return myInfo?.Data; } catch (Exception e) { diff --git a/DownKyi.Core/BiliApi/Users/UserSpace.cs b/DownKyi.Core/BiliApi/Users/UserSpace.cs index a1409ba..f6b1550 100644 --- a/DownKyi.Core/BiliApi/Users/UserSpace.cs +++ b/DownKyi.Core/BiliApi/Users/UserSpace.cs @@ -17,17 +17,16 @@ public static class UserSpace /// /// /// - public static SpaceSettings GetSpaceSettings(long mid) + public static SpaceSettings? GetSpaceSettings(long mid) { - string url = $"https://space.bilibili.com/ajax/settings/getSettings?mid={mid}"; - string referer = "https://www.bilibili.com"; - string response = WebClient.RequestWeb(url, referer); + var url = $"https://space.bilibili.com/ajax/settings/getSettings?mid={mid}"; + const string referer = "https://www.bilibili.com"; + var response = WebClient.RequestWeb(url, referer); try { - SpaceSettingsOrigin settings = JsonConvert.DeserializeObject(response); - if (settings == null || settings.Data == null || !settings.Status) { return null; } - return settings.Data; + var settings = JsonConvert.DeserializeObject(response); + return settings is not { Status: true } ? null : settings.Data; } catch (Exception e) { @@ -44,11 +43,11 @@ public static class UserSpace /// /// 用户id /// - public static List GetPublicationType(long mid) + public static List GetPublicationType(long mid) { - int pn = 1; - int ps = 1; - SpacePublicationList publication = GetPublication(mid, pn, ps); + const int pn = 1; + const int ps = 1; + var publication = GetPublication(mid, pn, ps); return GetPublicationType(publication); } @@ -57,18 +56,18 @@ public static class UserSpace /// /// 用户id /// - public static List GetPublicationType(SpacePublicationList publication) + public static List GetPublicationType(SpacePublicationList? publication) { - if (publication == null || publication.Tlist == null) + if (publication?.Tlist == null) { return null; } - List result = new List(); - JObject typeList = JObject.Parse(publication.Tlist.ToString("N")); + var result = new List(); + var typeList = JObject.Parse(publication.Tlist.ToString("N")); foreach (KeyValuePair item in typeList) { - SpacePublicationListTypeVideoZone value = JsonConvert.DeserializeObject(item.Value.ToString()); + var value = JsonConvert.DeserializeObject(item.Value.ToString()); result.Add(value); } return result; @@ -84,16 +83,16 @@ public static class UserSpace /// public static List GetAllPublication(long mid, int tid = 0, PublicationOrder order = PublicationOrder.PUBDATE, string keyword = "") { - List result = new List(); + var result = new List(); - int i = 0; + var i = 0; while (true) { i++; - int ps = 100; + const int ps = 100; - SpacePublicationList data = GetPublication(mid, i, ps, tid, order, keyword); - if (data == null || data.Vlist == null || data.Vlist.Count == 0) + var data = GetPublication(mid, i, ps, tid, order, keyword); + if (data?.Vlist == null || data.Vlist.Count == 0) { break; } result.AddRange(data.Vlist); @@ -112,7 +111,7 @@ public static class UserSpace /// 视频分区 /// 搜索关键词 /// - public static SpacePublicationList GetPublication(long mid, int pn, int ps, long tid = 0, PublicationOrder order = PublicationOrder.PUBDATE, string keyword = "") + public static SpacePublicationList? GetPublication(long mid, int pn, int ps, long tid = 0, PublicationOrder order = PublicationOrder.PUBDATE, string keyword = "") { var parameters = new Dictionary { @@ -123,15 +122,15 @@ public static class UserSpace { "tid", tid }, { "keyword", keyword }, }; - string query = WbiSign.ParametersToQuery(WbiSign.EncodeWbi(parameters)); - string url = $"https://api.bilibili.com/x/space/wbi/arc/search?{query}"; - string referer = "https://www.bilibili.com"; - string response = WebClient.RequestWeb(url, referer); + var query = WbiSign.ParametersToQuery(WbiSign.EncodeWbi(parameters)); + var url = $"https://api.bilibili.com/x/space/wbi/arc/search?{query}"; + const string referer = "https://www.bilibili.com"; + var response = WebClient.RequestWeb(url, referer); try { // 忽略play的值为“--”时的类型错误 - JsonSerializerSettings settings = new JsonSerializerSettings + var settings = new JsonSerializerSettings { Error = (sender, args) => { @@ -143,9 +142,8 @@ public static class UserSpace } }; - SpacePublicationOrigin spacePublication = JsonConvert.DeserializeObject(response, settings); - if (spacePublication == null || spacePublication.Data == null) { return null; } - return spacePublication.Data.List; + var spacePublication = JsonConvert.DeserializeObject(response, settings); + return spacePublication?.Data?.List; } catch (Exception e) { @@ -164,17 +162,16 @@ public static class UserSpace /// /// 用户id /// - public static List GetChannelList(long mid) + public static List? GetChannelList(long mid) { - string url = $"https://api.bilibili.com/x/space/channel/list?mid={mid}"; - string referer = "https://www.bilibili.com"; - string response = WebClient.RequestWeb(url, referer); + var url = $"https://api.bilibili.com/x/space/channel/list?mid={mid}"; + const string referer = "https://www.bilibili.com"; + var response = WebClient.RequestWeb(url, referer); try { - SpaceChannelOrigin spaceChannel = JsonConvert.DeserializeObject(response); - if (spaceChannel == null || spaceChannel.Data == null) { return null; } - return spaceChannel.Data.List; + var spaceChannel = JsonConvert.DeserializeObject(response); + return spaceChannel?.Data.List; } catch (Exception e) { @@ -190,18 +187,18 @@ public static class UserSpace /// /// /// - public static List GetAllChannelVideoList(long mid, long cid) + public static List GetAllChannelVideoList(long mid, long cid) { - List result = new List(); + var result = new List(); - int i = 0; + var i = 0; while (true) { i++; - int ps = 100; + const int ps = 100; - List data = GetChannelVideoList(mid, cid, i, ps); - if (data == null || data.Count == 0) + var data = GetChannelVideoList(mid, cid, i, ps); + if (data?.Count == 0) { break; } result.AddRange(data); @@ -217,18 +214,16 @@ public static class UserSpace /// /// /// - public static List GetChannelVideoList(long mid, long cid, int pn, int ps) + public static List? GetChannelVideoList(long mid, long cid, int pn, int ps) { - string url = $"https://api.bilibili.com/x/space/channel/video?mid={mid}&cid={cid}&pn={pn}&ps={ps}"; - string referer = "https://www.bilibili.com"; - string response = WebClient.RequestWeb(url, referer); + var url = $"https://api.bilibili.com/x/space/channel/video?mid={mid}&cid={cid}&pn={pn}&ps={ps}"; + const string referer = "https://www.bilibili.com"; + var response = WebClient.RequestWeb(url, referer); try { - SpaceChannelVideoOrigin spaceChannelVideo = JsonConvert.DeserializeObject(response); - if (spaceChannelVideo == null || spaceChannelVideo.Data == null || spaceChannelVideo.Data.List == null) - { return null; } - return spaceChannelVideo.Data.List.Archives; + var spaceChannelVideo = JsonConvert.DeserializeObject(response); + return spaceChannelVideo?.Data.List.Archives; } catch (Exception e) { @@ -249,19 +244,17 @@ public static class UserSpace /// 第几页 /// 每页的数量;最大值为20 /// - public static SpaceSeasonsSeries GetSeasonsSeries(long mid, int pageNum, int pageSize) + public static SpaceSeasonsSeries? GetSeasonsSeries(long mid, int pageNum, int pageSize) { // https://api.bilibili.com/x/polymer/space/seasons_series_list?mid=49246269&page_num=1&page_size=18 - string url = $"https://api.bilibili.com/x/polymer/space/seasons_series_list?mid={mid}&page_num={pageNum}&page_size={pageSize}"; - string referer = "https://www.bilibili.com"; - string response = WebClient.RequestWeb(url, referer); + var url = $"https://api.bilibili.com/x/polymer/space/seasons_series_list?mid={mid}&page_num={pageNum}&page_size={pageSize}"; + const string referer = "https://www.bilibili.com"; + var response = WebClient.RequestWeb(url, referer); try { - SpaceSeasonsSeriesOrigin origin = JsonConvert.DeserializeObject(response); - if (origin == null || origin.Data == null || origin.Data.ItemsLists == null) - { return null; } - return origin.Data.ItemsLists; + var origin = JsonConvert.DeserializeObject(response); + return origin?.Data.ItemsLists; } catch (Exception e) { @@ -278,19 +271,17 @@ public static class UserSpace /// /// /// - public static SpaceSeasonsDetail GetSeasonsDetail(long mid, long seasonId, int pageNum, int pageSize) + public static SpaceSeasonsDetail? GetSeasonsDetail(long mid, long seasonId, int pageNum, int pageSize) { // https://api.bilibili.com/x/polymer/space/seasons_archives_list?mid=23947287&season_id=665&sort_reverse=false&page_num=1&page_size=30 - string url = $"https://api.bilibili.com/x/polymer/space/seasons_archives_list?mid={mid}&season_id={seasonId}&page_num={pageNum}&page_size={pageSize}&sort_reverse=false"; - string referer = "https://www.bilibili.com"; - string response = WebClient.RequestWeb(url, referer); + var url = $"https://api.bilibili.com/x/polymer/space/seasons_archives_list?mid={mid}&season_id={seasonId}&page_num={pageNum}&page_size={pageSize}&sort_reverse=false"; + const string referer = "https://www.bilibili.com"; + var response = WebClient.RequestWeb(url, referer); try { - SpaceSeasonsDetailOrigin origin = JsonConvert.DeserializeObject(response); - if (origin == null || origin.Data == null) - { return null; } - return origin.Data; + var origin = JsonConvert.DeserializeObject(response); + return origin?.Data; } catch (Exception e) { @@ -305,19 +296,17 @@ public static class UserSpace /// /// /// - public static SpaceSeriesMetaData GetSeriesMeta(long seriesId) + public static SpaceSeriesMetaData? GetSeriesMeta(long seriesId) { // https://api.bilibili.com/x/series/series?series_id=1253087 - string url = $"https://api.bilibili.com/x/series/series?series_id={seriesId}"; - string referer = "https://www.bilibili.com"; - string response = WebClient.RequestWeb(url, referer); + var url = $"https://api.bilibili.com/x/series/series?series_id={seriesId}"; + const string referer = "https://www.bilibili.com"; + var response = WebClient.RequestWeb(url, referer); try { - SpaceSeriesMetaOrigin origin = JsonConvert.DeserializeObject(response); - if (origin == null || origin.Data == null) - { return null; } - return origin.Data; + var origin = JsonConvert.DeserializeObject(response); + return origin?.Data; } catch (Exception e) { @@ -335,20 +324,18 @@ public static class UserSpace /// /// /// - public static SpaceSeriesDetail GetSeriesDetail(long mid, long seriesId, int pn, int ps) + public static SpaceSeriesDetail? GetSeriesDetail(long mid, long seriesId, int pn, int ps) { // https://api.bilibili.com/x/series/archives?mid=27899754&series_id=1253087&only_normal=true&sort=desc&pn=1&ps=30 - string url = $"https://api.bilibili.com/x/series/archives?mid={mid}&series_id={seriesId}&only_normal=true&sort=desc&pn={pn}&ps={ps}"; - string referer = "https://www.bilibili.com"; - string response = WebClient.RequestWeb(url, referer); + var url = $"https://api.bilibili.com/x/series/archives?mid={mid}&series_id={seriesId}&only_normal=true&sort=desc&pn={pn}&ps={ps}"; + const string referer = "https://www.bilibili.com"; + var response = WebClient.RequestWeb(url, referer); try { - SpaceSeriesDetailOrigin origin = JsonConvert.DeserializeObject(response); - if (origin == null || origin.Data == null) - { return null; } - return origin.Data; + var origin = JsonConvert.DeserializeObject(response); + return origin?.Data; } catch (Exception e) { @@ -368,18 +355,16 @@ public static class UserSpace /// 页码 /// 每页项数 /// - public static List GetCheese(long mid, int pn, int ps) + public static List? GetCheese(long mid, int pn, int ps) { - string url = $"https://api.bilibili.com/pugv/app/web/season/page?mid={mid}&pn={pn}&ps={ps}"; - string referer = "https://www.bilibili.com"; - string response = WebClient.RequestWeb(url, referer); + var url = $"https://api.bilibili.com/pugv/app/web/season/page?mid={mid}&pn={pn}&ps={ps}"; + const string referer = "https://www.bilibili.com"; + var response = WebClient.RequestWeb(url, referer); try { - SpaceCheeseOrigin cheese = JsonConvert.DeserializeObject(response); - if (cheese == null || cheese.Data == null || cheese.Data.Items == null) - { return null; } - return cheese.Data.Items; + var cheese = JsonConvert.DeserializeObject(response); + return cheese?.Data.Items; } catch (Exception e) { @@ -396,15 +381,15 @@ public static class UserSpace /// public static List GetAllCheese(long mid) { - List result = new List(); + var result = new List(); - int i = 0; + var i = 0; while (true) { i++; - int ps = 50; + var ps = 50; - List data = GetCheese(mid, i, ps); + var data = GetCheese(mid, i, ps); if (data == null || data.Count == 0) { break; } @@ -425,18 +410,16 @@ public static class UserSpace /// 页码 /// 每页项数 /// - public static BangumiFollowData GetBangumiFollow(long mid, BangumiType type, int pn, int ps) + public static BangumiFollowData? GetBangumiFollow(long mid, BangumiType type, int pn, int ps) { - string url = $"https://api.bilibili.com/x/space/bangumi/follow/list?vmid={mid}&type={type:D}&pn={pn}&ps={ps}"; - string referer = "https://www.bilibili.com"; - string response = WebClient.RequestWeb(url, referer); + var url = $"https://api.bilibili.com/x/space/bangumi/follow/list?vmid={mid}&type={type:D}&pn={pn}&ps={ps}"; + const string referer = "https://www.bilibili.com"; + var response = WebClient.RequestWeb(url, referer); try { - BangumiFollowOrigin bangumiFollow = JsonConvert.DeserializeObject(response); - if (bangumiFollow == null || bangumiFollow.Data == null) - { return null; } - return bangumiFollow.Data; + var bangumiFollow = JsonConvert.DeserializeObject(response); + return bangumiFollow?.Data; } catch (Exception e) { @@ -454,16 +437,16 @@ public static class UserSpace /// public static List GetAllBangumiFollow(long mid, BangumiType type) { - List result = new List(); + var result = new List(); - int i = 0; + var i = 0; while (true) { i++; - int ps = 30; + const int ps = 30; - BangumiFollowData data = GetBangumiFollow(mid, type, i, ps); - if (data == null || data.List == null || data.List.Count == 0) + var data = GetBangumiFollow(mid, type, i, ps); + if (data?.List == null || data.List.Count == 0) { break; } result.AddRange(data.List); diff --git a/DownKyi.Core/BiliApi/Video/VideoInfo.cs b/DownKyi.Core/BiliApi/Video/VideoInfo.cs index bbeb4e8..1d11229 100644 --- a/DownKyi.Core/BiliApi/Video/VideoInfo.cs +++ b/DownKyi.Core/BiliApi/Video/VideoInfo.cs @@ -14,7 +14,7 @@ public static class VideoInfo /// /// /// - public static VideoView VideoViewInfo(string bvid = null, long aid = -1) + public static VideoView? VideoViewInfo(string? bvid = null, long aid = -1) { // https://api.bilibili.com/x/web-interface/view/detail?bvid=BV1Sg411F7cb&aid=969147110&need_operation_card=1&web_rm_repeat=1&need_elec=1&out_referer=https%3A%2F%2Fspace.bilibili.com%2F42018135%2Ffavlist%3Ffid%3D94341835 @@ -31,16 +31,15 @@ public static class VideoInfo { return null; } - string query = WbiSign.ParametersToQuery(WbiSign.EncodeWbi(parameters)); - string url = $"https://api.bilibili.com/x/web-interface/wbi/view?{query}"; - string referer = "https://www.bilibili.com"; - string response = WebClient.RequestWeb(url, referer); + var query = WbiSign.ParametersToQuery(WbiSign.EncodeWbi(parameters)); + var url = $"https://api.bilibili.com/x/web-interface/wbi/view?{query}"; + const string referer = "https://www.bilibili.com"; + var response = WebClient.RequestWeb(url, referer); try { var videoView = JsonConvert.DeserializeObject(response); - if (videoView != null) { return videoView.Data; } - else { return null; } + return videoView?.Data; } catch (Exception e) { @@ -56,22 +55,21 @@ public static class VideoInfo /// /// /// - public static string VideoDescription(string bvid = null, long aid = -1) + public static string? VideoDescription(string? bvid = null, long aid = -1) { - string baseUrl = "https://api.bilibili.com/x/web-interface/archive/desc"; - string referer = "https://www.bilibili.com"; + const string baseUrl = "https://api.bilibili.com/x/web-interface/archive/desc"; + const string referer = "https://www.bilibili.com"; string url; if (bvid != null) { url = $"{baseUrl}?bvid={bvid}"; } else if (aid >= -1) { url = $"{baseUrl}?aid={aid}"; } else { return null; } - string response = WebClient.RequestWeb(url, referer); + var response = WebClient.RequestWeb(url, referer); try { var desc = JsonConvert.DeserializeObject(response); - if (desc != null) { return desc.Data; } - else { return null; } + return desc?.Data; } catch (Exception e) { @@ -87,22 +85,21 @@ public static class VideoInfo /// /// /// - public static List VideoPagelist(string bvid = null, long aid = -1) + public static List? VideoPagelist(string? bvid = null, long aid = -1) { - string baseUrl = "https://api.bilibili.com/x/player/pagelist"; - string referer = "https://www.bilibili.com"; + const string baseUrl = "https://api.bilibili.com/x/player/pagelist"; + const string referer = "https://www.bilibili.com"; string url; if (bvid != null) { url = $"{baseUrl}?bvid={bvid}"; } else if (aid > -1) { url = $"{baseUrl}?aid={aid}"; } else { return null; } - string response = WebClient.RequestWeb(url, referer); + var response = WebClient.RequestWeb(url, referer); try { var pagelist = JsonConvert.DeserializeObject(response); - if (pagelist != null) { return pagelist.Data; } - else { return null; } + return pagelist?.Data; } catch (Exception e) { diff --git a/DownKyi.Core/BiliApi/WebClient.cs b/DownKyi.Core/BiliApi/WebClient.cs index 24c077e..fe84555 100644 --- a/DownKyi.Core/BiliApi/WebClient.cs +++ b/DownKyi.Core/BiliApi/WebClient.cs @@ -9,6 +9,20 @@ namespace DownKyi.Core.BiliApi; internal static class WebClient { + private static string GetRandomBuvid3() + { + // 随机生成10位字符串 + const string str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; + var random = new Random(); + var result = new StringBuilder(); + for (var i = 0; i < 10; i++) + { + result.Append(str[random.Next(str.Length)]); + } + + return result.ToString(); + } + /// /// 发送get或post请求 /// @@ -16,9 +30,10 @@ internal static class WebClient /// /// /// + /// /// - public static string RequestWeb(string url, string referer = null, string method = "GET", - Dictionary parameters = null, int retry = 3) + public static string RequestWeb(string url, string? referer = null, string method = "GET", + Dictionary? parameters = null, int retry = 3, bool needRandomBvuid3 = false) { // 重试次数 if (retry <= 0) @@ -29,25 +44,25 @@ internal static class WebClient // post请求,发送参数 if (method == "POST" && parameters != null) { - StringBuilder builder = new StringBuilder(); - int i = 0; + var builder = new StringBuilder(); + var i = 0; foreach (var item in parameters) { if (i > 0) { - builder.Append("&"); + builder.Append('&'); } - builder.AppendFormat("{0}={1}", item.Key, item.Value); + builder.Append($"{item.Key}={item.Value}"); i++; } - url += "?" + builder.ToString(); + url += "?" + builder; } try { - HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); + var request = (HttpWebRequest)WebRequest.Create(url); request.Method = method; request.Timeout = 30 * 1000; @@ -68,60 +83,48 @@ internal static class WebClient { request.Headers["origin"] = "https://m.bilibili.com"; - CookieContainer cookies = LoginHelper.GetLoginInfoCookies(); + var cookies = LoginHelper.GetLoginInfoCookies(); if (cookies != null) { request.CookieContainer = cookies; } - } - - string html = string.Empty; - using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) - { - if (response.ContentEncoding.ToLower().Contains("gzip")) - { - using (GZipStream stream = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress)) - { - using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) - { - html = reader.ReadToEnd(); - } - } - } - else if (response.ContentEncoding.ToLower().Contains("deflate")) - { - using (DeflateStream stream = - new DeflateStream(response.GetResponseStream(), CompressionMode.Decompress)) - { - using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) - { - html = reader.ReadToEnd(); - } - } - } - else if (response.ContentEncoding.ToLower().Contains("br")) - { - using (BrotliStream stream = - new BrotliStream(response.GetResponseStream(), CompressionMode.Decompress)) - { - using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) - { - html = reader.ReadToEnd(); - } - } - } else { - using (Stream stream = response.GetResponseStream()) + request.CookieContainer = new CookieContainer(); + if (needRandomBvuid3) { - using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) - { - html = reader.ReadToEnd(); - } + request.CookieContainer.Add(new Cookie("buvid3", GetRandomBuvid3(), "/", ".bilibili.com")); } } } + var html = string.Empty; + using var response = (HttpWebResponse)request.GetResponse(); + if (response.ContentEncoding.ToLower().Contains("gzip")) + { + using var stream = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress); + using var reader = new StreamReader(stream, Encoding.UTF8); + html = reader.ReadToEnd(); + } + else if (response.ContentEncoding.ToLower().Contains("deflate")) + { + using var stream = new DeflateStream(response.GetResponseStream(), CompressionMode.Decompress); + using var reader = new StreamReader(stream, Encoding.UTF8); + html = reader.ReadToEnd(); + } + else if (response.ContentEncoding.ToLower().Contains("br")) + { + using var stream = new BrotliStream(response.GetResponseStream(), CompressionMode.Decompress); + using var reader = new StreamReader(stream, Encoding.UTF8); + html = reader.ReadToEnd(); + } + else + { + using var stream = response.GetResponseStream(); + using var reader = new StreamReader(stream, Encoding.UTF8); + html = reader.ReadToEnd(); + } + return html; } catch (WebException e) diff --git a/DownKyi.Core/Storage/StorageHeader.cs b/DownKyi.Core/Storage/StorageHeader.cs index 5d904e0..0f229fd 100644 --- a/DownKyi.Core/Storage/StorageHeader.cs +++ b/DownKyi.Core/Storage/StorageHeader.cs @@ -135,7 +135,7 @@ public class StorageHeader } else { - string md5 = DownloadImage(url); + var md5 = DownloadImage(url); if (md5 != null) { Header newHeader = new Header diff --git a/DownKyi.Core/Utils/Encryptor/Encryptor.String.cs b/DownKyi.Core/Utils/Encryptor/Encryptor.String.cs index 51c7421..199c4c4 100644 --- a/DownKyi.Core/Utils/Encryptor/Encryptor.String.cs +++ b/DownKyi.Core/Utils/Encryptor/Encryptor.String.cs @@ -17,14 +17,13 @@ public static partial class Encryptor { try { - byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8)); //转换为字节 - byte[] rgbIV = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8)); - byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString); - DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider(); //实例化数据加密标准 - MemoryStream mStream = new MemoryStream(); //实例化内存流 + var rgbKey = Encoding.UTF8.GetBytes(encryptKey[..8]); //转换为字节 + var rgbIV = Encoding.UTF8.GetBytes(encryptKey[..8]); + var inputByteArray = Encoding.UTF8.GetBytes(encryptString); + var dCSP = new DESCryptoServiceProvider(); //实例化数据加密标准 + var mStream = new MemoryStream(); //实例化内存流 //将数据流链接到加密转换的流 - CryptoStream cStream = - new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write); + var cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write); cStream.Write(inputByteArray, 0, inputByteArray.Length); cStream.FlushFinalBlock(); // 转base64 @@ -48,13 +47,12 @@ public static partial class Encryptor { try { - byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey); - byte[] rgbIV = Encoding.UTF8.GetBytes(decryptKey); - byte[] inputByteArray = Convert.FromBase64String(decryptString); - DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider(); - MemoryStream mStream = new MemoryStream(); - CryptoStream cStream = - new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write); + var rgbKey = Encoding.UTF8.GetBytes(decryptKey); + var rgbIV = Encoding.UTF8.GetBytes(decryptKey); + var inputByteArray = Convert.FromBase64String(decryptString); + var DCSP = new DESCryptoServiceProvider(); + var mStream = new MemoryStream(); + var cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write); cStream.Write(inputByteArray, 0, inputByteArray.Length); cStream.FlushFinalBlock(); return Encoding.UTF8.GetString(mStream.ToArray()); diff --git a/DownKyi.Core/Utils/Encryptor/Hash.cs b/DownKyi.Core/Utils/Encryptor/Hash.cs index cf9f122..b246139 100644 --- a/DownKyi.Core/Utils/Encryptor/Hash.cs +++ b/DownKyi.Core/Utils/Encryptor/Hash.cs @@ -10,25 +10,25 @@ public static class Hash /// /// /// - public static string GetMd5Hash(string input) + public static string GetMd5Hash(string? input) { if (input == null) { return null; } - MD5 md5Hash = MD5.Create(); + var md5Hash = MD5.Create(); // 将输入字符串转换为字节数组并计算哈希数据 - byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input)); + var data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input)); // 创建一个 Stringbuilder 来收集字节并创建字符串 - StringBuilder sBuilder = new StringBuilder(); + var sBuilder = new StringBuilder(); // 循环遍历哈希数据的每一个字节并格式化为十六进制字符串 - for (int i = 0; i < data.Length; i++) + foreach (var t in data) { - sBuilder.Append(data[i].ToString("x2")); + sBuilder.Append(t.ToString("x2")); } // 返回十六进制字符串 @@ -44,15 +44,15 @@ public static class Hash { try { - FileStream file = new FileStream(fileName, FileMode.Open); + var file = new FileStream(fileName, FileMode.Open); MD5 md5 = new MD5CryptoServiceProvider(); - byte[] retVal = md5.ComputeHash(file); + var retVal = md5.ComputeHash(file); file.Close(); - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < retVal.Length; i++) + var sb = new StringBuilder(); + foreach (var t in retVal) { - sb.Append(retVal[i].ToString("x2")); + sb.Append(t.ToString("x2")); } return sb.ToString(); diff --git a/DownKyi.Core/Utils/Format.cs b/DownKyi.Core/Utils/Format.cs index 76cfae6..17d3547 100644 --- a/DownKyi.Core/Utils/Format.cs +++ b/DownKyi.Core/Utils/Format.cs @@ -1,6 +1,4 @@ -using System.Text.RegularExpressions; - -namespace DownKyi.Core.Utils; +namespace DownKyi.Core.Utils; public static class Format { @@ -14,15 +12,8 @@ public static class Format string formatDuration; if (duration / 60 > 0) { - long dur = duration / 60; - if (dur / 60 > 0) - { - formatDuration = $"{dur / 60}h{dur % 60}m{duration % 60}s"; - } - else - { - formatDuration = $"{duration / 60}m{duration % 60}s"; - } + var dur = duration / 60; + formatDuration = dur / 60 > 0 ? $"{dur / 60}h{dur % 60}m{duration % 60}s" : $"{duration / 60}m{duration % 60}s"; } else { @@ -42,21 +33,12 @@ public static class Format string formatDuration; if (duration / 60 > 0) { - long dur = duration / 60; - if (dur / 60 > 0) - { - formatDuration = string.Format("{0:D2}", dur / 60) + ":" + string.Format("{0:D2}", dur % 60) + ":" + - string.Format("{0:D2}", duration % 60); - } - else - { - formatDuration = "00:" + string.Format("{0:D2}", duration / 60) + ":" + - string.Format("{0:D2}", duration % 60); - } + var dur = duration / 60; + formatDuration = dur / 60 > 0 ? $"{dur / 60:D2}:{dur % 60:D2}:{duration % 60:D2}" : $"00:{duration / 60:D2}:{duration % 60:D2}"; } else { - formatDuration = "00:00:" + string.Format("{0:D2}", duration); + formatDuration = $"00:00:{duration:D2}"; } return formatDuration; @@ -72,20 +54,12 @@ public static class Format string formatDuration; if (duration / 60 > 0) { - long dur = duration / 60; - if (dur / 60 > 0) - { - formatDuration = string.Format("{0:D2}", dur / 60) + ":" + string.Format("{0:D2}", dur % 60) + ":" + - string.Format("{0:D2}", duration % 60); - } - else - { - formatDuration = string.Format("{0:D2}", duration / 60) + ":" + string.Format("{0:D2}", duration % 60); - } + var dur = duration / 60; + formatDuration = dur / 60 > 0 ? $"{dur / 60:D2}:{dur % 60:D2}:{duration % 60:D2}" : $"{duration / 60:D2}:{duration % 60:D2}"; } else { - formatDuration = "00:" + string.Format("{0:D2}", duration); + formatDuration = $"00:{duration:D2}"; } return formatDuration; @@ -98,19 +72,12 @@ public static class Format /// public static string FormatNumber(long number) { - if (number > 99999999) + return number switch { - return (number / 100000000.0f).ToString("F1") + "亿"; - } - - if (number > 9999) - { - return (number / 10000.0f).ToString("F1") + "万"; - } - else - { - return number.ToString(); - } + > 99999999 => (number / 100000000.0f).ToString("F1") + "亿", + > 9999 => (number / 10000.0f).ToString("F1") + "万", + _ => number.ToString() + }; } /// @@ -120,23 +87,13 @@ public static class Format /// public static string FormatSpeed(float speed) { - string formatSpeed; - if (speed <= 0) + string formatSpeed = speed switch { - formatSpeed = "0B/s"; - } - else if (speed < 1024) - { - formatSpeed = string.Format("{0:F2}", speed) + "B/s"; - } - else if (speed < 1024 * 1024) - { - formatSpeed = string.Format("{0:F2}", speed / 1024) + "KB/s"; - } - else - { - formatSpeed = string.Format("{0:F2}", speed / 1024 / 1024) + "MB/s"; - } + <= 0 => "0B/s", + < 1024 => $"{speed:F2}B/s", + < 1024 * 1024 => $"{speed / 1024:F2}KB/s", + _ => $"{speed / 1024 / 1024:F2}MB/s" + }; return formatSpeed; } @@ -148,27 +105,14 @@ public static class Format /// public static string FormatFileSize(long fileSize) { - string formatFileSize; - if (fileSize <= 0) + string formatFileSize = fileSize switch { - formatFileSize = "0B"; - } - else if (fileSize < 1024) - { - formatFileSize = fileSize.ToString() + "B"; - } - else if (fileSize < 1024 * 1024) - { - formatFileSize = (fileSize / 1024.0).ToString("#.##") + "KB"; - } - else if (fileSize < 1024 * 1024 * 1024) - { - formatFileSize = (fileSize / 1024.0 / 1024.0).ToString("#.##") + "MB"; - } - else - { - formatFileSize = (fileSize / 1024.0 / 1024.0 / 1024.0).ToString("#.##") + "GB"; - } + <= 0 => "0B", + < 1024 => fileSize.ToString() + "B", + < 1024 * 1024 => (fileSize / 1024.0).ToString("#.##") + "KB", + < 1024 * 1024 * 1024 => (fileSize / 1024.0 / 1024.0).ToString("#.##") + "MB", + _ => (fileSize / 1024.0 / 1024.0 / 1024.0).ToString("#.##") + "GB" + }; return formatFileSize; } @@ -204,8 +148,8 @@ public static class Format destName = Path.GetInvalidFileNameChars().Aggregate(destName, (current, c) => current.Replace(c.ToString(), string.Empty)); // 控制字符 - - + + // 移除前导和尾部的空白字符、dot符 destName = destName.Trim(); destName = destName.Trim('.'); diff --git a/DownKyi.Core/Utils/HardDisk.cs b/DownKyi.Core/Utils/HardDisk.cs index 0865748..bf0f131 100644 --- a/DownKyi.Core/Utils/HardDisk.cs +++ b/DownKyi.Core/Utils/HardDisk.cs @@ -17,9 +17,9 @@ public static class HardDisk try { hardDiskName = $"{hardDiskName}:\\"; - DriveInfo[] drives = DriveInfo.GetDrives(); + var drives = DriveInfo.GetDrives(); - foreach (DriveInfo drive in drives) + foreach (var drive in drives) { if (drive.Name == hardDiskName) { @@ -70,7 +70,7 @@ public static class HardDisk long freeSpace = 0; try { - DriveInfo driveInfo = new DriveInfo(path); + var driveInfo = new DriveInfo(path); // hardDiskName = $"{path}:\\"; freeSpace = driveInfo.TotalFreeSpace; } diff --git a/DownKyi.Core/Utils/ObjectHelper.cs b/DownKyi.Core/Utils/ObjectHelper.cs index 98763b4..7fcff78 100644 --- a/DownKyi.Core/Utils/ObjectHelper.cs +++ b/DownKyi.Core/Utils/ObjectHelper.cs @@ -16,40 +16,40 @@ public static class ObjectHelper /// public static CookieContainer ParseCookie(string url) { - CookieContainer cookieContainer = new CookieContainer(); + var cookieContainer = new CookieContainer(); - if (url == null || url == "") + if (url is null or "") { return cookieContainer; } - string[] strList = url.Split('?'); - if (strList.Count() < 2) + var strList = url.Split('?'); + if (strList.Length < 2) { return cookieContainer; } - string[] strList2 = strList[1].Split('&'); - if (strList2.Count() == 0) + var strList2 = strList[1].Split('&'); + if (strList2.Length == 0) { return cookieContainer; } // 获取expires - string expires = strList2.FirstOrDefault(it => it.Contains("Expires")).Split('=')[1]; - DateTime dateTime = DateTime.Now; + var expires = strList2.FirstOrDefault(it => it.Contains("Expires")).Split('=')[1]; + var dateTime = DateTime.Now; dateTime = dateTime.AddSeconds(int.Parse(expires)); foreach (var item in strList2) { - string[] strList3 = item.Split('='); - if (strList3.Count() < 2) + var strList3 = item.Split('='); + if (strList3.Length < 2) { continue; } - string name = strList3[0]; - string value = strList3[1]; + var name = strList3[0]; + var value = strList3[1]; // 不需要 if (name == "Expires" || name == "gourl") @@ -73,15 +73,15 @@ public static class ObjectHelper /// public static List GetAllCookies(CookieContainer cc) { - List lstCookies = new List(); + var lstCookies = new List(); - Hashtable table = (Hashtable)cc.GetType().InvokeMember("m_domainTable", + var table = (Hashtable)cc.GetType().InvokeMember("m_domainTable", BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance, null, cc, new object[] { }); - foreach (object pathList in table.Values) + foreach (var pathList in table.Values) { - SortedList lstCookieCol = (SortedList)pathList.GetType().InvokeMember("m_list", + var lstCookieCol = (SortedList)pathList.GetType().InvokeMember("m_list", BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance, null, pathList, new object[] { }); @@ -128,16 +128,14 @@ public static class ObjectHelper { try { - using (Stream stream = File.Create(file)) - { - Console.PrintLine("Writing object to disk... "); + using Stream stream = File.Create(file); + Console.PrintLine("Writing object to disk... "); - BinaryFormatter formatter = new BinaryFormatter(); - formatter.Serialize(stream, obj); + var formatter = new BinaryFormatter(); + formatter.Serialize(stream, obj); - Console.PrintLine("Done."); - return true; - } + Console.PrintLine("Done."); + return true; } catch (IOException e) { @@ -162,13 +160,11 @@ public static class ObjectHelper { try { - using (Stream stream = File.Open(file, FileMode.Open)) - { - Console.PrintLine("Reading object from disk... "); - BinaryFormatter formatter = new BinaryFormatter(); - Console.PrintLine("Done."); - return formatter.Deserialize(stream); - } + using Stream stream = File.Open(file, FileMode.Open); + Console.PrintLine("Reading object from disk... "); + var formatter = new BinaryFormatter(); + Console.PrintLine("Done."); + return formatter.Deserialize(stream); } catch (IOException e) { diff --git a/DownKyi.Core/Utils/QRCode.cs b/DownKyi.Core/Utils/QRCode.cs index 594b659..f297ff1 100644 --- a/DownKyi.Core/Utils/QRCode.cs +++ b/DownKyi.Core/Utils/QRCode.cs @@ -11,37 +11,27 @@ public static class QRCode /// 信息 /// 版本 1 ~ 40 /// 像素点大小 - /// 图标路径 - /// 图标尺寸 - /// 图标边框厚度 - /// 二维码白边 + /// 图标路径 + /// 图标尺寸 + /// 图标边框厚度 + /// 二维码白边 /// 位图 - public static Bitmap EncodeQRCode(string msg, int version, int pixel, string icon_path, int icon_size, - int icon_border, bool white_edge) + public static Bitmap EncodeQRCode(string msg, int version, int pixel, string? iconPath, int iconSize, int iconBorder, bool whiteEdge) { - QRCodeGenerator code_generator = new QRCodeGenerator(); + var codeGenerator = new QRCodeGenerator(); - QRCodeData code_data = code_generator.CreateQrCode(msg, QRCodeGenerator.ECCLevel.H /* 这里设置容错率的一个级别 */, true, + var codeData = codeGenerator.CreateQrCode(msg, QRCodeGenerator.ECCLevel.H /* 这里设置容错率的一个级别 */, true, false, QRCodeGenerator.EciMode.Utf8, version); - BitmapByteQRCode qrCode = new BitmapByteQRCode(code_data); - byte[] qrCodeAsBitmapByteArr = qrCode.GetGraphic(20); + var qrCode = new BitmapByteQRCode(codeData); + var qrCodeAsBitmapByteArr = qrCode.GetGraphic(20); Bitmap icon; - if (icon_path == null || icon_path == "") - { - icon = null; - } - else - { - icon = new Bitmap(icon_path); - } + icon = string.IsNullOrEmpty(iconPath) ? null : new Bitmap(iconPath); Bitmap bmp; - using (var ms = new MemoryStream(qrCodeAsBitmapByteArr)) - { - bmp = new Bitmap(ms); - } + using var ms = new MemoryStream(qrCodeAsBitmapByteArr); + bmp = new Bitmap(ms); // Bitmap bmp = qrCode.GetGraphic(pixel, Color.FromRgb(0,0,0), Color.FromRgb(255,255,255), icon, icon_size, icon_border, white_edge); diff --git a/DownKyi.Core/Utils/StringLogicalComparer.cs b/DownKyi.Core/Utils/StringLogicalComparer.cs index c59290e..2b8da48 100644 --- a/DownKyi.Core/Utils/StringLogicalComparer.cs +++ b/DownKyi.Core/Utils/StringLogicalComparer.cs @@ -8,19 +8,19 @@ public class StringLogicalComparer : IComparer /// /// /// - public int Compare(T x, T y) + public int Compare(T? x, T? y) { if (x == null || y == null) { throw new ArgumentException("Parameters can't be null"); } - string fileA = x as string; - string fileB = y as string; - char[] arr1 = fileA.ToCharArray(); - char[] arr2 = fileB.ToCharArray(); + var fileA = x as string; + var fileB = y as string; + var arr1 = fileA?.ToCharArray(); + var arr2 = fileB?.ToCharArray(); int i = 0, j = 0; - while (i < arr1.Length && j < arr2.Length) + while (i < arr1?.Length && j < arr2?.Length) { if (char.IsDigit(arr1[i]) && char.IsDigit(arr2[j])) { @@ -64,13 +64,11 @@ public class StringLogicalComparer : IComparer } } - if (arr1.Length == arr2.Length) + if (arr1?.Length == arr2?.Length) { return 0; } - else - { - return arr1.Length > arr2.Length ? 1 : -1; - } + + return arr1?.Length > arr2?.Length ? 1 : -1; } } \ No newline at end of file diff --git a/DownKyi/ViewModels/ViewIndexViewModel.cs b/DownKyi/ViewModels/ViewIndexViewModel.cs index 7b95a58..ea439cf 100644 --- a/DownKyi/ViewModels/ViewIndexViewModel.cs +++ b/DownKyi/ViewModels/ViewIndexViewModel.cs @@ -49,12 +49,12 @@ public class ViewIndexViewModel : ViewModelBase } - private VectorImage textLogo; + private VectorImage _textLogo; public VectorImage TextLogo { - get => textLogo; - set => SetProperty(ref textLogo, value); + get => _textLogo; + set => SetProperty(ref _textLogo, value); } private string _inputText; @@ -122,8 +122,8 @@ public class ViewIndexViewModel : ViewModelBase } // 输入确认事件 - public DelegateCommand inputCommand; - public DelegateCommand InputCommand => inputCommand ?? (inputCommand = new DelegateCommand(ExecuteInput)); + private DelegateCommand? _inputCommand; + public DelegateCommand InputCommand => _inputCommand ??= new DelegateCommand(ExecuteInput); /// /// 处理输入事件 @@ -159,10 +159,9 @@ public class ViewIndexViewModel : ViewModelBase } // 进入设置页面 - private DelegateCommand settingsCommand; + private DelegateCommand? _settingsCommand; - public DelegateCommand SettingsCommand => - settingsCommand ?? (settingsCommand = new DelegateCommand(ExecuteSettingsCommand)); + public DelegateCommand SettingsCommand => _settingsCommand ??= new DelegateCommand(ExecuteSettingsCommand); /// /// 进入设置页面 @@ -173,11 +172,9 @@ public class ViewIndexViewModel : ViewModelBase } // 进入下载管理页面 - private DelegateCommand downloadManagerCommand; + private DelegateCommand? _downloadManagerCommand; - public DelegateCommand DownloadManagerCommand => downloadManagerCommand ?? - (downloadManagerCommand = - new DelegateCommand(ExecuteDownloadManagerCommand)); + public DelegateCommand DownloadManagerCommand => _downloadManagerCommand ??= new DelegateCommand(ExecuteDownloadManagerCommand); /// /// 进入下载管理页面 @@ -187,11 +184,10 @@ public class ViewIndexViewModel : ViewModelBase NavigateToView.NavigationView(EventAggregator, ViewDownloadManagerViewModel.Tag, Tag, null); } -// 进入工具箱页面 - private DelegateCommand toolboxCommand; + // 进入工具箱页面 + private DelegateCommand? _toolboxCommand; - public DelegateCommand ToolboxCommand => - toolboxCommand ?? (toolboxCommand = new DelegateCommand(ExecuteToolboxCommand)); + public DelegateCommand ToolboxCommand => _toolboxCommand ??= new DelegateCommand(ExecuteToolboxCommand); /// /// 进入工具箱页面 @@ -216,8 +212,8 @@ public class ViewIndexViewModel : ViewModelBase LogManager.Debug(Tag, $"InputText: {InputText}"); InputText = Regex.Replace(InputText, @"[【]*[^【]*[^】]*[】 ]", ""); - SearchService searchService = new SearchService(); - bool isSupport = searchService.BiliInput(InputText, Tag, EventAggregator); + var searchService = new SearchService(); + var isSupport = searchService.BiliInput(InputText, Tag, EventAggregator); if (!isSupport) { // 关键词搜索 @@ -228,9 +224,9 @@ public class ViewIndexViewModel : ViewModelBase } - private async Task GetUserInfo() + private async Task GetUserInfo() { - UserInfoForNavigation userInfo = null; + UserInfoForNavigation? userInfo = null; await Task.Run(() => { // 获取用户信息 @@ -327,7 +323,7 @@ public class ViewIndexViewModel : ViewModelBase DownloadManager.Fill = DictionaryResource.GetColor("ColorPrimary"); // 根据传入参数不同执行不同任务 - string parameter = navigationContext.Parameters.GetValue("Parameter"); + var parameter = navigationContext.Parameters.GetValue("Parameter"); if (parameter == null) { // 其他情况只更新设置的用户信息,不更新UI diff --git a/DownKyi/ViewModels/ViewMySpaceViewModel.cs b/DownKyi/ViewModels/ViewMySpaceViewModel.cs index 7ffd333..773c1aa 100644 --- a/DownKyi/ViewModels/ViewMySpaceViewModel.cs +++ b/DownKyi/ViewModels/ViewMySpaceViewModel.cs @@ -553,13 +553,13 @@ public class ViewMySpaceViewModel : ViewModelBase } // 我的用户信息 - MyInfo myInfo = UserInfo.GetMyInfo(); + var myInfo = UserInfo.GetMyInfo(); if (myInfo != null) { isNoData = false; // 头像 - StorageHeader storageHeader = new StorageHeader(); + var storageHeader = new StorageHeader(); headerUri = storageHeader.GetHeader(mid, myInfo.Name, myInfo.Face); // 用户名 UserName = myInfo.Name; @@ -663,7 +663,7 @@ public class ViewMySpaceViewModel : ViewModelBase else { // 头像 - StorageHeader storageHeader = new StorageHeader(); + var storageHeader = new StorageHeader(); Header = storageHeader.GetHeaderThumbnail(headerUri, 64, 64); // 性别 Sex = sexUri == null ? null : ImageHelper.LoadFromResource(sexUri); @@ -683,7 +683,7 @@ public class ViewMySpaceViewModel : ViewModelBase await Task.Run(() => { // 导航栏信息 - UserInfoForNavigation navData = UserInfo.GetUserInfoForNavigation(); + var navData = UserInfo.GetUserInfoForNavigation(); if (navData != null) { ContentVisibility = true; @@ -695,7 +695,7 @@ public class ViewMySpaceViewModel : ViewModelBase } //用户的关系状态数 - UserRelationStat relationStat = UserStatus.GetUserRelationStat(mid); + var relationStat = UserStatus.GetUserRelationStat(mid); if (relationStat != null) { // 关注数 diff --git a/DownKyi/ViewModels/ViewPublicationViewModel.cs b/DownKyi/ViewModels/ViewPublicationViewModel.cs index e06c843..3738fa0 100644 --- a/DownKyi/ViewModels/ViewPublicationViewModel.cs +++ b/DownKyi/ViewModels/ViewPublicationViewModel.cs @@ -426,7 +426,7 @@ namespace DownKyi.ViewModels await Task.Run(() => { - CancellationToken cancellationToken = tokenSource.Token; + var cancellationToken = tokenSource.Token; var publications = Core.BiliApi.Users.UserSpace.GetPublication(mid, current, VideoNumberInPage, tab.Id); if (publications == null) @@ -449,7 +449,7 @@ namespace DownKyi.ViewModels foreach (var video in videos) { // 查询、保存封面 - string coverUrl = video.Pic; + var coverUrl = video.Pic; Bitmap cover; if (coverUrl == null || coverUrl == "") { @@ -462,12 +462,12 @@ namespace DownKyi.ViewModels coverUrl = $"https:{video.Pic}"; } - StorageCover storageCover = new StorageCover(); + var storageCover = new StorageCover(); cover = storageCover.GetCoverThumbnail(video.Aid, video.Bvid, -1, coverUrl, 200, 125); } // 播放数 - string play = string.Empty; + var play = string.Empty; if (video.Play > 0) { play = Format.FormatNumber(video.Play); @@ -477,13 +477,13 @@ namespace DownKyi.ViewModels play = "--"; } - DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); // 当地时区 - DateTime dateCTime = startTime.AddSeconds(video.Created); - string ctime = dateCTime.ToString("yyyy-MM-dd"); + var startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); // 当地时区 + var dateCTime = startTime.AddSeconds(video.Created); + var ctime = dateCTime.ToString("yyyy-MM-dd"); App.PropertyChangeAsync(() => { - PublicationMedia media = new PublicationMedia(EventAggregator) + var media = new PublicationMedia(EventAggregator) { Avid = video.Aid, Bvid = video.Bvid, diff --git a/DownKyi/ViewModels/ViewUserSpaceViewModel.cs b/DownKyi/ViewModels/ViewUserSpaceViewModel.cs index 6fcfb59..ac583e9 100644 --- a/DownKyi/ViewModels/ViewUserSpaceViewModel.cs +++ b/DownKyi/ViewModels/ViewUserSpaceViewModel.cs @@ -21,162 +21,163 @@ public class ViewUserSpaceViewModel : ViewModelBase { public const string Tag = "PageUserSpace"; - private readonly IRegionManager regionManager; + private readonly IRegionManager _regionManager; // mid private long mid = -1; #region 页面属性申明 - private VectorImage arrowBack; + private VectorImage _arrowBack; public VectorImage ArrowBack { - get => arrowBack; - set => SetProperty(ref arrowBack, value); + get => _arrowBack; + set => SetProperty(ref _arrowBack, value); } - private bool loading; + private bool _loading; + public bool Loading { - get => loading; - set => SetProperty(ref loading, value); + get => _loading; + set => SetProperty(ref _loading, value); } - private bool noDataVisibility; + private bool _noDataVisibility; public bool NoDataVisibility { - get => noDataVisibility; - set => SetProperty(ref noDataVisibility, value); + get => _noDataVisibility; + set => SetProperty(ref _noDataVisibility, value); } - private bool loadingVisibility; + private bool _loadingVisibility; public bool LoadingVisibility { - get => loadingVisibility; - set => SetProperty(ref loadingVisibility, value); + get => _loadingVisibility; + set => SetProperty(ref _loadingVisibility, value); } - private bool viewVisibility; + private bool _viewVisibility; public bool ViewVisibility { - get => viewVisibility; - set => SetProperty(ref viewVisibility, value); + get => _viewVisibility; + set => SetProperty(ref _viewVisibility, value); } - private bool contentVisibility; + private bool _contentVisibility; public bool ContentVisibility { - get => contentVisibility; - set => SetProperty(ref contentVisibility, value); + get => _contentVisibility; + set => SetProperty(ref _contentVisibility, value); } - private string topNavigationBg; + private string _topNavigationBg; public string TopNavigationBg { - get => topNavigationBg; - set => SetProperty(ref topNavigationBg, value); + get => _topNavigationBg; + set => SetProperty(ref _topNavigationBg, value); } - private Bitmap background; + private Bitmap _background; public Bitmap Background { - get => background; - set => SetProperty(ref background, value); + get => _background; + set => SetProperty(ref _background, value); } - private Bitmap header; + private Bitmap _header; public Bitmap Header { - get => header; - set => SetProperty(ref header, value); + get => _header; + set => SetProperty(ref _header, value); } - private string userName; + private string _userName; public string UserName { - get => userName; - set => SetProperty(ref userName, value); + get => _userName; + set => SetProperty(ref _userName, value); } - private Bitmap sex; + private Bitmap _sex; public Bitmap Sex { - get => sex; - set => SetProperty(ref sex, value); + get => _sex; + set => SetProperty(ref _sex, value); } - private Bitmap level; + private Bitmap _level; public Bitmap Level { - get => level; - set => SetProperty(ref level, value); + get => _level; + set => SetProperty(ref _level, value); } - private bool vipTypeVisibility; + private bool _vipTypeVisibility; public bool VipTypeVisibility { - get => vipTypeVisibility; - set => SetProperty(ref vipTypeVisibility, value); + get => _vipTypeVisibility; + set => SetProperty(ref _vipTypeVisibility, value); } - private string vipType; + private string _vipType; public string VipType { - get => vipType; - set => SetProperty(ref vipType, value); + get => _vipType; + set => SetProperty(ref _vipType, value); } - private string sign; + private string _sign; public string Sign { - get => sign; - set => SetProperty(ref sign, value); + get => _sign; + set => SetProperty(ref _sign, value); } - private string isFollowed; + private string _isFollowed; public string IsFollowed { - get => isFollowed; - set => SetProperty(ref isFollowed, value); + get => _isFollowed; + set => SetProperty(ref _isFollowed, value); } - private ObservableCollection tabLeftBanners; + private ObservableCollection _tabLeftBanners; public ObservableCollection TabLeftBanners { - get => tabLeftBanners; - set => SetProperty(ref tabLeftBanners, value); + get => _tabLeftBanners; + set => SetProperty(ref _tabLeftBanners, value); } - private ObservableCollection tabRightBanners; + private ObservableCollection _tabRightBanners; public ObservableCollection TabRightBanners { - get => tabRightBanners; - set => SetProperty(ref tabRightBanners, value); + get => _tabRightBanners; + set => SetProperty(ref _tabRightBanners, value); } - private int selectedRightBanner; + private int _selectedRightBanner; public int SelectedRightBanner { - get => selectedRightBanner; - set => SetProperty(ref selectedRightBanner, value); + get => _selectedRightBanner; + set => SetProperty(ref _selectedRightBanner, value); } #endregion @@ -184,7 +185,7 @@ public class ViewUserSpaceViewModel : ViewModelBase public ViewUserSpaceViewModel(IRegionManager regionManager, IEventAggregator eventAggregator) : base( eventAggregator) { - this.regionManager = regionManager; + this._regionManager = regionManager; #region 属性初始化 @@ -206,17 +207,16 @@ public class ViewUserSpaceViewModel : ViewModelBase #region 命令申明 // 返回事件 - private DelegateCommand backSpaceCommand; + private DelegateCommand? _backSpaceCommand; - public DelegateCommand BackSpaceCommand => - backSpaceCommand ?? (backSpaceCommand = new DelegateCommand(ExecuteBackSpace)); + public DelegateCommand BackSpaceCommand => _backSpaceCommand ??= new DelegateCommand(ExecuteBackSpace); /// /// 返回事件 /// private void ExecuteBackSpace() { - NavigationParam parameter = new NavigationParam + var parameter = new NavigationParam { ViewName = ParentView, ParentViewName = null, @@ -226,12 +226,9 @@ public class ViewUserSpaceViewModel : ViewModelBase } // 左侧tab点击事件 - private DelegateCommand tabLeftBannersCommand; + private DelegateCommand? _tabLeftBannersCommand; - public DelegateCommand TabLeftBannersCommand => tabLeftBannersCommand ?? - (tabLeftBannersCommand = - new DelegateCommand( - ExecuteTabLeftBannersCommand)); + public DelegateCommand TabLeftBannersCommand => _tabLeftBannersCommand ??= new DelegateCommand(ExecuteTabLeftBannersCommand); /// /// 左侧tab点击事件 @@ -239,12 +236,12 @@ public class ViewUserSpaceViewModel : ViewModelBase /// private void ExecuteTabLeftBannersCommand(object parameter) { - if (!(parameter is TabLeftBanner banner)) + if (parameter is not TabLeftBanner banner) { return; } - NavigationParameters param = new NavigationParameters() + var param = new NavigationParameters { { "object", banner.Object }, { "mid", mid }, @@ -253,25 +250,22 @@ public class ViewUserSpaceViewModel : ViewModelBase switch (banner.Id) { case 0: // 投稿 - regionManager.RequestNavigate("UserSpaceContentRegion", ViewArchiveViewModel.Tag, param); + _regionManager.RequestNavigate("UserSpaceContentRegion", ViewArchiveViewModel.Tag, param); break; case 1: // 频道(弃用) - regionManager.RequestNavigate("UserSpaceContentRegion", ViewChannelViewModel.Tag, param); + _regionManager.RequestNavigate("UserSpaceContentRegion", ViewChannelViewModel.Tag, param); break; case 2: // 合集和列表 - regionManager.RequestNavigate("UserSpaceContentRegion", UserSpace.ViewSeasonsSeriesViewModel.Tag, + _regionManager.RequestNavigate("UserSpaceContentRegion", UserSpace.ViewSeasonsSeriesViewModel.Tag, param); break; } } // 右侧tab点击事件 - private DelegateCommand tabRightBannersCommand; + private DelegateCommand? _tabRightBannersCommand; - public DelegateCommand TabRightBannersCommand => tabRightBannersCommand ?? - (tabRightBannersCommand = - new DelegateCommand( - ExecuteTabRightBannersCommand)); + public DelegateCommand TabRightBannersCommand => _tabRightBannersCommand ??= new DelegateCommand(ExecuteTabRightBannersCommand); /// /// 右侧tab点击事件 @@ -339,7 +333,7 @@ public class ViewUserSpaceViewModel : ViewModelBase SelectedRightBanner = -1; // 将内容置空,使其不指向任何页面 - regionManager.RequestNavigate("UserSpaceContentRegion", ""); + _regionManager.RequestNavigate("UserSpaceContentRegion", ""); ContentVisibility = false; ViewVisibility = false; @@ -352,20 +346,20 @@ public class ViewUserSpaceViewModel : ViewModelBase /// private async void UpdateSpaceInfo() { - bool isNoData = true; - Uri toutuUri = null; - string headerUri = null; - Uri sexUri = null; - Uri levelUri = null; + var isNoData = true; + Uri? toutuUri = null; + string? headerUri = null; + Uri? sexUri = null; + Uri? levelUri = null; await Task.Run(() => { // 背景图片 - SpaceSettings spaceSettings = Core.BiliApi.Users.UserSpace.GetSpaceSettings(mid); + var spaceSettings = Core.BiliApi.Users.UserSpace.GetSpaceSettings(mid); if (spaceSettings != null) { - StorageCover storageCover = new StorageCover(); - string toutu = storageCover.GetCover($"https://i0.hdslb.com/{spaceSettings.Toutu.Limg}"); + var storageCover = new StorageCover(); + var toutu = storageCover.GetCover($"https://i0.hdslb.com/{spaceSettings.Toutu.Limg}"); toutuUri = new Uri(toutu); } else @@ -374,28 +368,26 @@ public class ViewUserSpaceViewModel : ViewModelBase } // 用户信息 - UserInfoForSpace userInfo = UserInfo.GetUserInfoForSpace(mid); + var userInfo = UserInfo.GetUserInfoForSpace(mid); if (userInfo != null) { isNoData = false; // 头像 - StorageHeader storageHeader = new StorageHeader(); + var storageHeader = new StorageHeader(); headerUri = storageHeader.GetHeader(mid, userInfo.Name, userInfo.Face); // 用户名 UserName = userInfo.Name; - // 性别 - if (userInfo.Sex == "男") + sexUri = userInfo.Sex switch { - sexUri = new Uri("avares://DownKyi/Resources/sex/male.png"); - } - else if (userInfo.Sex == "女") - { - sexUri = new Uri("avares://DownKyi/Resources/sex/female.png"); - } + // 性别 + "男" => new Uri("avares://DownKyi/Resources/sex/male.png"), + "女" => new Uri("avares://DownKyi/Resources/sex/female.png"), + _ => sexUri + }; // 显示vip信息 - if (userInfo.Vip.Label.Text == null || userInfo.Vip.Label.Text == "") + if (userInfo.Vip?.Label?.Text is null or "") { VipTypeVisibility = false; } @@ -440,7 +432,7 @@ public class ViewUserSpaceViewModel : ViewModelBase else { // 头像 - StorageHeader storageHeader = new StorageHeader(); + var storageHeader = new StorageHeader(); Header = storageHeader.GetHeaderThumbnail(headerUri, 64, 64); // 性别 Sex = sexUri == null ? null : ImageHelper.LoadFromResource(sexUri); @@ -459,7 +451,7 @@ public class ViewUserSpaceViewModel : ViewModelBase ContentVisibility = true; // 投稿视频 - List publicationTypes = null; + List? publicationTypes = null; await Task.Run(() => { publicationTypes = Core.BiliApi.Users.UserSpace.GetPublicationType(mid); }); if (publicationTypes != null && publicationTypes.Count > 0) { @@ -493,9 +485,9 @@ public class ViewUserSpaceViewModel : ViewModelBase //} // 合集和列表 - SpaceSeasonsSeries seasonsSeries = null; + SpaceSeasonsSeries? seasonsSeries = null; await Task.Run(() => { seasonsSeries = Core.BiliApi.Users.UserSpace.GetSeasonsSeries(mid, 1, 20); }); - if (seasonsSeries != null && seasonsSeries.Page.Total > 0) + if (seasonsSeries is { Page.Total: > 0 }) { TabLeftBanners.Add(new TabLeftBanner { @@ -511,7 +503,7 @@ public class ViewUserSpaceViewModel : ViewModelBase // 订阅 // 关系状态数 - UserRelationStat relationStat = null; + UserRelationStat? relationStat = null; await Task.Run(() => { relationStat = UserStatus.GetUserRelationStat(mid); }); if (relationStat != null) { @@ -536,9 +528,9 @@ public class ViewUserSpaceViewModel : ViewModelBase } // UP主状态数,需要任意用户登录,否则不会返回任何数据 - UpStat upStat = null; + UpStat? upStat = null; await Task.Run(() => { upStat = UserStatus.GetUpStat(mid); }); - if (upStat != null && upStat.Archive != null && upStat.Article != null) + if (upStat is { Archive: not null, Article: not null }) { TabRightBanners.Add(new TabRightBanner { @@ -551,7 +543,7 @@ public class ViewUserSpaceViewModel : ViewModelBase }); long archiveView = 0; - if (upStat.Archive != null) + if (upStat?.Archive != null) { archiveView = upStat.Archive.View; } @@ -567,7 +559,7 @@ public class ViewUserSpaceViewModel : ViewModelBase }); long articleView = 0; - if (upStat.Article != null) + if (upStat?.Article != null) { articleView = upStat.Article.View; } @@ -593,7 +585,7 @@ public class ViewUserSpaceViewModel : ViewModelBase base.OnNavigatedTo(navigationContext); // 根据传入参数不同执行不同任务 - long parameter = navigationContext.Parameters.GetValue("Parameter"); + var parameter = navigationContext.Parameters.GetValue("Parameter"); if (parameter == 0) { return;